@sejuneoh/aitop 0.30.0 → 0.31.1

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
@@ -3,29 +3,47 @@
3
3
  [![npm](https://img.shields.io/npm/v/@sejuneoh/aitop)](https://www.npmjs.com/package/@sejuneoh/aitop)
4
4
  [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/SejuneOh/aitop/blob/main/LICENSE)
5
5
 
6
- **`top` for your AI coding agents.** A read-only terminal monitor that shows every Claude Code, Codex CLI and Antigravity CLI session on your machine in one live screen: what each one is doing, which ones are waiting for you, and how many tokens they used.
6
+ **`top` for your AI coding agents.** One live terminal screen for every Claude Code, Codex CLI and Antigravity CLI session on your machine. Read-only.
7
7
 
8
- ![aitop showing Claude Code, Codex and Antigravity sessions (demo data)](https://raw.githubusercontent.com/SejuneOh/aitop/main/docs/demo.gif)
8
+ ```bash
9
+ npx @sejuneoh/aitop # try it, no install
10
+ npm i -g @sejuneoh/aitop # then just run: aitop
11
+ ```
9
12
 
10
- - **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle
11
- - **Waiting alerts**: blocked sessions jump to the top, with optional bell, desktop notification or hook command
12
- - **Tokens and cost** per session and for today / last 7 days, at public API list prices
13
- - **Changed files and diffs** per session and per prompt
14
- - **Read-only**: no network, no ports, no dependencies. It only reads the session logs each CLI already writes
13
+ ![aitop: a session starts waiting, jumps to the top, and its resume command shows in the detail panel (demo data)](https://raw.githubusercontent.com/SejuneOh/aitop/main/docs/demo.gif)
15
14
 
16
- > The UI follows your locale: English by default, Korean when the locale starts with `ko`. Set `AITOP_LANG=ko|en` (or `--lang`) to pick one. This covers the live screen, `--once`, `--help`, `--doctor`, error messages and desktop notifications. Keys and options work the same in both.
15
+ - **See who needs you.** A waiting session jumps to the top and `n` takes you there. Add `--notify=waiting,done,context` for desktop alerts, or `aitop --line` for a tmux status line.
16
+ - **Know which session is which.** Every row shows the session name (your `/rename` or the tool's title). `y` copies a resume command, and `--report sessions` prints yesterday's sessions with cost for your standup.
17
+ - **All agents, all profiles, nothing sent.** Claude Code, Codex and Antigravity side by side, from [several history folders](#several-claude-or-codex-profiles) (`~/.claude`, `~/.claude-work`, ...). No network, no ports, no dependencies.
18
+
19
+ **How it differs from similar tools**
20
+
21
+ - [ccusage](https://github.com/ryoppippi/ccusage) reports token usage and cost from local logs (daily, monthly, session, 5-hour blocks). aitop is a live session monitor first, with smaller cost reports on the side.
22
+ - [abtop](https://github.com/graykode/abtop) is a Rust live dashboard for Claude Code, Codex CLI and OpenCode, with rate limits, ports and keys to kill sessions. aitop installs with npm, also covers Antigravity, and only watches.
23
+ - [claude-code-monitor](https://github.com/onikan27/claude-code-monitor) watches Claude Code on macOS through hooks it adds to `~/.claude/settings.json`, with a phone web view. aitop adds no hooks and only reads existing logs, on Linux, macOS, WSL and Windows.
17
24
 
18
25
  ## Install
19
26
 
20
27
  Requires Node.js 22+ on Linux, macOS, WSL or Windows.
21
28
 
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.
23
-
24
29
  ```bash
25
- npm install -g @sejuneoh/aitop
30
+ npx @sejuneoh/aitop # run the latest version without installing
31
+ npm install -g @sejuneoh/aitop # or install it
26
32
  aitop
27
33
  ```
28
34
 
35
+ 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.
36
+
37
+ ## Features
38
+
39
+ - **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle
40
+ - **Waiting alerts**: blocked sessions jump to the top, with optional bell, desktop notification or hook command
41
+ - **Tokens and cost** per session and for today / last 7 days, at public API list prices
42
+ - **Changed files and diffs** per session and per prompt
43
+ - **Read-only**: no network, no ports, no dependencies. It only reads the session logs each CLI already writes
44
+
45
+ > The UI follows your locale: English by default, Korean when the locale starts with `ko`. Set `AITOP_LANG=ko|en` (or `--lang`) to pick one. This covers the live screen, `--once`, `--help`, `--doctor`, error messages and desktop notifications. Keys and options work the same in both.
46
+
29
47
  ## Usage
30
48
 
31
49
  ```
@@ -36,6 +54,7 @@ aitop --doctor check which tools and logs aitop can see
36
54
  aitop --line print one short status line and exit (for tmux, e.g. $54.13 wait 2 fix-login 3m run 3 $3.1/h)
37
55
  aitop --report daily daily cost table and exit
38
56
  aitop --report monthly monthly cost table (last 12 months) and exit
57
+ aitop --report sessions yesterday's sessions with cost, for standups (--md, --json)
39
58
  aitop --help all options
40
59
  aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG=ko or "lang": "ko" in the config file)
41
60
  ```
@@ -61,6 +80,15 @@ aitop --report daily --by project --days 7
61
80
  aitop --report monthly --by model --months 6
62
81
  ```
63
82
 
83
+ ### Session report
84
+
85
+ `aitop --report sessions [--since yesterday|today|Nd|YYYY-MM-DD] [--plan USD] [--md|--json] [--show-prompts]` lists every session that used tokens in the period (default: since midnight yesterday; at most 30 days back), highest cost first: tool, main model (`+N` more), project (same rule as `--by project`), session name (your `/rename` name, then the tool's title, then the folder), start and end of activity within the period, tokens, cost (API list price, `?` for unpriced models) and files changed (`-` when unknown, always for agy). A summary card on top shows the total, the share per tool and the session count; `--plan 200` adds how many times the period's share of a $200/month subscription (period days / 30) you used, still in API list price and not your bill. Claude subagents are counted in their parent session. `--md` prints Markdown you can paste (`|` and line breaks escaped), `--json` the same numbers for scripts. First prompts are hidden unless you pass `--show-prompts`, so they do not end up in shared output (session names still show).
86
+
87
+ ```
88
+ aitop --report sessions --md --plan 200
89
+ aitop --report sessions --since 7d --json
90
+ ```
91
+
64
92
  ### Notifications
65
93
 
66
94
  Off by default and only on the live screen. Sessions already waiting (or already over 90% context) when aitop starts are not reported.
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|monthly, --by tool|model|project, --days <N>, --months <N> 은 reportOption 이 꺼낸다.
44
+ // --report daily|monthly|sessions, --by tool|model|project, --days <N>, --months <N>, --since, --plan, --md, --show-prompts 는 reportOption 이 꺼낸다.
45
45
  const report = reportOption(line.rest);
46
46
  if (report.error) {
47
47
  process.stderr.write(`aitop: ${report.error}\n`);
@@ -153,6 +153,33 @@ if (line.mode) {
153
153
  // --report: 날짜별 사용량 표(또는 --json)를 내고 끝낸다. 실시간 화면·세션 목록은 읽지 않고 장부만 읽는다.
154
154
  // --report monthly 는 월별 보관함(monthly.mjs)과 장부를 합친다.
155
155
  // 처음 실행은 30일치(monthly 는 1년치) 기록을 읽으므로 stderr 가 터미널이면 진행률을 보이고, 시간 상한(AITOP_REPORT_MS, 기본 120초)을 넘으면 읽은 만큼 낸다.
156
+ // --report sessions: 기간 안 세션별 한 줄과 요약 카드. 진행률·시간 상한은 daily 와 같다. --md 는 Markdown, --json 은 JSON.
157
+ if (report.kind === 'sessions') {
158
+ const { collectSessions, buildSessions, formatSessions, sessionsMarkdown, sessionsJson } = await import('../src/sessions-report.mjs');
159
+ const { progressWriter, MAX_DAYS } = await import('../src/report.mjs');
160
+ const { flushCache } = await import('../src/cache.mjs');
161
+ const json = args.has('--json');
162
+ if (json && report.md) {
163
+ process.stderr.write(`aitop: ${t('opt.mdJson')}\n`);
164
+ process.exit(2);
165
+ }
166
+ if (report.capped) process.stderr.write(`aitop: ${t('sessions.capped', { n: MAX_DAYS })}\n`);
167
+ const progress = progressWriter();
168
+ const maxMs = Number(process.env.AITOP_REPORT_MS) > 0 ? Number(process.env.AITOP_REPORT_MS) : undefined;
169
+ const now = Date.now();
170
+ const got = await collectSessions({ since: report.since, now, maxMs, onProgress: progress.update });
171
+ progress.done();
172
+ flushCache();
173
+ if (got.partial && json) process.stderr.write(`aitop: ${t('report.partial')}\n`);
174
+ const r = buildSessions(got.books, { since: report.since, now, extra: got.extra, agy: got.agy, plan: report.plan });
175
+ const cols = process.stdout.isTTY ? process.stdout.columns : Number(process.env.COLUMNS) || 0;
176
+ const opts = { partial: got.partial, prompts: report.prompts };
177
+ const text = json ? JSON.stringify(sessionsJson(r, VERSION, opts), null, 2) : report.md ? sessionsMarkdown(r, opts) : formatSessions(r, { ...opts, cols });
178
+ process.stdout.on('error', (err) => process.exit(err.code === 'EPIPE' ? 0 : 1));
179
+ await new Promise((resolve) => process.stdout.write(text + '\n', resolve));
180
+ process.exit(0);
181
+ }
182
+
156
183
  if (report.kind) {
157
184
  const { buildMonthly, buildReport, collectMonthly, collectReport, fitReport, formatReport, PIPE_COLUMNS, progressWriter, reportJson, MAX_DAYS, MAX_MONTHS } = await import('../src/report.mjs');
158
185
  const { flushCache } = await import('../src/cache.mjs');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.30.0",
3
+ "version": "0.31.1",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/i18n.mjs CHANGED
@@ -73,6 +73,10 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
73
73
  프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
74
74
  aitop --report monthly [--by tool|model|project] [--months N] [--json] 최근 N달(기본·최대 12)의 달별 표. 지난 날은 캐시 폴더의
75
75
  monthly.json 에 달별로 남겨 기록이 지워져도 남는다. 처음 실행은 1년치 기록을 한 번 읽는다. * 이번 달, ~ 일부만 센 달
76
+ aitop --report sessions [--since yesterday|today|Nd|YYYY-MM-DD] [--plan USD] [--md|--json] [--show-prompts]
77
+ 기간(기본: 어제 0시부터 지금까지, 최대 30일 전) 안에 사용량이 있는 세션을 비용이 큰 순서로 한 줄씩 보인다
78
+ (도구, 모델, 프로젝트, 세션 이름, 시작·끝, 토큰, API 정가 환산 비용, 고친 파일 수). 맨 위 요약 카드에 합계와 도구별 비중.
79
+ --plan 월 구독료를 주면 기간 몫의 몇 배인지 보인다. --md 는 붙여 넣을 Markdown. 첫 지시는 --show-prompts 일 때만
76
80
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
77
81
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
78
82
  aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
@@ -127,6 +131,11 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
127
131
  aitop --report monthly [--by tool|model|project] [--months N] [--json] the same per month for the last N months (default and max 12).
128
132
  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.
129
133
  * marks this month, ~ a month only partly counted
134
+ aitop --report sessions [--since yesterday|today|Nd|YYYY-MM-DD] [--plan USD] [--md|--json] [--show-prompts]
135
+ list each session with usage in the period (default: since midnight yesterday, at most 30 days back), highest cost first
136
+ (tool, model, project, session name, start and end, tokens, API list price cost, files changed), with a summary card on top.
137
+ --plan with your monthly subscription shows how many times its share for the period you used. --md prints pasteable Markdown.
138
+ First prompts are shown only with --show-prompts
130
139
  aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
131
140
  aitop --bell ring the terminal bell when a session starts waiting for you
132
141
  aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
@@ -220,8 +229,16 @@ export const STRINGS = {
220
229
  'opt.lineBad': '--line 값 {value} 이 잘못되었습니다 (plain 또는 tmux)',
221
230
  'opt.lineWidthMissing': '--line-width 값이 없습니다 (글자 수)',
222
231
  'opt.lineWidthBad': '--line-width 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
223
- 'opt.reportMissing': '--report 값이 없습니다 (daily 또는 monthly)',
224
- 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily 또는 monthly)',
232
+ 'opt.reportMissing': '--report 값이 없습니다 (daily, monthly 또는 sessions)',
233
+ 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily, monthly 또는 sessions)',
234
+ 'opt.sinceMissing': '--since 값이 없습니다 (yesterday, today, 7d 같은 일 수, 또는 YYYY-MM-DD)',
235
+ 'opt.sinceBad': '--since 값 {value} 이 잘못되었습니다 (yesterday, today, 7d 같은 일 수, 또는 YYYY-MM-DD)',
236
+ 'opt.sinceFuture': '--since 값 {value} 이 오늘보다 뒤입니다',
237
+ 'opt.planMissing': '--plan 값이 없습니다 (월 구독료, USD)',
238
+ 'opt.planBad': '--plan 값 {value} 이 잘못되었습니다 (0 보다 큰 숫자, USD)',
239
+ 'opt.sessionsOnly': '{opt} 는 --report sessions 와 함께 쓴다',
240
+ 'opt.notSessions': '{opt} 는 --report sessions 와 함께 쓸 수 없다 (기간은 --since)',
241
+ 'opt.mdJson': '--md 와 --json 은 함께 쓸 수 없다',
225
242
  'opt.byMissing': '--by 값이 없습니다 (tool, model 또는 project)',
226
243
  'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool, model 또는 project)',
227
244
  'opt.daysMissing': '--days 값이 없습니다 (일 수)',
@@ -253,6 +270,25 @@ export const STRINGS = {
253
270
  'report.noteCurrent': '* 이번 달 (아직 진행 중)',
254
271
  'report.notePartial': '~ 일부 날만 셌습니다 (그 전 기록이 지워졌거나 보관함이 비어 있던 때)',
255
272
  'report.noteMissing': '기록 없음: 남은 기록도 보관함도 없는 달입니다 (0 이 아니라 모름)',
273
+ // 세션 리포트 (--report sessions).
274
+ 'sessions.title': '세션 리포트 · {from} ~ {to} ({days}일)',
275
+ 'sessions.cardTotal': '합계 {cost} (API 정가 환산) · 토큰 {tokens} · 세션 {n}개',
276
+ 'sessions.cardTools': '도구별 비용 비중: {tools}',
277
+ 'sessions.cardToolsTokens': '도구별 토큰 비중: {tools}',
278
+ 'sessions.cardPlan': '구독료 {plan}/월의 {days}일 몫 {prorated} 대비 {ratio} (API 정가 환산, 실제 청구액이 아님)',
279
+ 'sessions.col.tool': '도구',
280
+ 'sessions.col.model': '모델',
281
+ 'sessions.col.project': '프로젝트',
282
+ 'sessions.col.name': '세션',
283
+ 'sessions.col.start': '시작',
284
+ 'sessions.col.end': '끝',
285
+ 'sessions.col.tokens': '토큰',
286
+ 'sessions.col.cost': '비용',
287
+ 'sessions.col.files': '파일',
288
+ 'sessions.col.prompt': '첫 지시',
289
+ 'sessions.empty': '이 기간에 사용량이 있는 세션이 없습니다',
290
+ 'sessions.noteBasis': '비용은 API 정가 환산이며 실제 청구액이 아닙니다. 시작·끝은 기간 안의 활동 시각, 파일은 고친 파일 수 (- 는 모름)',
291
+ 'sessions.capped': '--since 는 장부가 남기는 {n}일 전까지만 볼 수 있어 {n}일 전으로 줄입니다',
256
292
 
257
293
  'cfg.notFile': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
258
294
  'cfg.tooBig': '설정 파일이 {kb}KB 를 넘어 읽지 않습니다',
@@ -596,8 +632,16 @@ export const STRINGS = {
596
632
  'opt.lineBad': 'bad --line value {value} (plain or tmux)',
597
633
  'opt.lineWidthMissing': '--line-width needs a value (characters)',
598
634
  'opt.lineWidthBad': 'bad --line-width value {value} (a whole number above 0)',
599
- 'opt.reportMissing': '--report needs a value (daily or monthly)',
600
- 'opt.reportBad': 'bad --report value {value} (daily or monthly)',
635
+ 'opt.reportMissing': '--report needs a value (daily, monthly or sessions)',
636
+ 'opt.reportBad': 'bad --report value {value} (daily, monthly or sessions)',
637
+ 'opt.sinceMissing': '--since needs a value (yesterday, today, a number of days like 7d, or YYYY-MM-DD)',
638
+ 'opt.sinceBad': 'bad --since value {value} (yesterday, today, a number of days like 7d, or YYYY-MM-DD)',
639
+ 'opt.sinceFuture': '--since value {value} is after today',
640
+ 'opt.planMissing': '--plan needs a value (monthly subscription in USD)',
641
+ 'opt.planBad': 'bad --plan value {value} (a number above 0, USD)',
642
+ 'opt.sessionsOnly': '{opt} only works with --report sessions',
643
+ 'opt.notSessions': '{opt} does not work with --report sessions (use --since for the period)',
644
+ 'opt.mdJson': '--md and --json cannot be used together',
601
645
  'opt.byMissing': '--by needs a value (tool, model or project)',
602
646
  'opt.byBad': 'bad --by value {value} (tool, model or project)',
603
647
  'opt.daysMissing': '--days needs a value (number of days)',
@@ -628,6 +672,24 @@ export const STRINGS = {
628
672
  'report.noteCurrent': '* this month (still in progress)',
629
673
  'report.notePartial': '~ only some days were counted (older logs were deleted or the archive was empty then)',
630
674
  'report.noteMissing': 'no data: neither logs nor the archive cover this month (unknown, not zero)',
675
+ 'sessions.title': 'Sessions, {from} to {to} ({days} days)',
676
+ 'sessions.cardTotal': 'Total {cost} (API list price) · {tokens} tokens · {n} sessions',
677
+ 'sessions.cardTools': 'Cost share by tool: {tools}',
678
+ 'sessions.cardToolsTokens': 'Token share by tool: {tools}',
679
+ 'sessions.cardPlan': '{ratio} the {days}-day share {prorated} of a {plan}/month subscription (API list price, not your actual bill)',
680
+ 'sessions.col.tool': 'Tool',
681
+ 'sessions.col.model': 'Model',
682
+ 'sessions.col.project': 'Project',
683
+ 'sessions.col.name': 'Session',
684
+ 'sessions.col.start': 'Start',
685
+ 'sessions.col.end': 'End',
686
+ 'sessions.col.tokens': 'Tokens',
687
+ 'sessions.col.cost': 'Cost',
688
+ 'sessions.col.files': 'Files',
689
+ 'sessions.col.prompt': 'First prompt',
690
+ 'sessions.empty': 'No session used tokens in this period',
691
+ 'sessions.noteBasis': 'Cost is the API list price, not your actual bill. Start and end are activity times within the period; Files is the number of files changed (- means unknown)',
692
+ 'sessions.capped': '--since is limited to {n} days back, which the ledger keeps, using {n} days',
631
693
 
632
694
  'cfg.notFile': 'config file is not a regular file, not reading it',
633
695
  'cfg.tooBig': 'config file is over {kb}KB, not reading it',
package/src/report.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  // 줄은 최근 날짜가 위(오늘부터 거꾸로)이고, 맨 아래 합계 줄은 위 날짜 줄을 더한 값이다. --json 도 같은 값을 숫자로만 낸다.
4
4
  // 처음 읽는 동안 stderr 가 터미널이면 진행률을 보이고, 시간 상한을 넘으면 읽은 만큼으로 표를 내고 덜 읽었다고 알린다.
5
5
  // --report monthly: 최근 N달(기본·최대 12)의 달별 표. 지난 날은 월별 보관함(monthly.mjs), 접기 전의 날은 장부에서 센다.
6
+ // --report sessions: 기간 안 세션별 한 줄과 요약 카드 (sessions-report.mjs).
6
7
  import { t } from './i18n.mjs';
7
8
  import { fmtTokens, pad, stripControl, truncate, width } from './text.mjs';
8
9
  import { money } from './line.mjs';
@@ -10,7 +11,7 @@ import { KEEP_DAYS, lastDays } from './sources/common.mjs';
10
11
  import { projectLabels } from './sources/projects.mjs';
11
12
  import { KEEP_MONTHS, lastMonths, monthOf, monthEnd } from './monthly.mjs';
12
13
 
13
- export const KINDS = ['daily', 'monthly'];
14
+ export const KINDS = ['daily', 'monthly', 'sessions'];
14
15
  export const BY = ['tool', 'model', 'project'];
15
16
  // --by project 의 특별한 열: 프로젝트를 못 찾은 기록, 열 수 상한을 넘어 합친 나머지. --json 에도 이 이름 그대로 나간다.
16
17
  export const UNKNOWN = '(unknown)';
@@ -30,10 +31,37 @@ const PROGRESS_AFTER_MS = 400;
30
31
  const FLUSH_MS = 3000;
31
32
  const TOOLS = ['claude', 'codex', 'agy'];
32
33
 
34
+ // --report sessions 의 기본 기간.
35
+ export const DEFAULT_SINCE = 'yesterday';
36
+
37
+ // --since 값 → { from: 기간 시작 ms(로컬 0시), back: 오늘부터 며칠 전인지, capped } 또는 { error }.
38
+ // yesterday, today, Nd(N일 전 0시), YYYY-MM-DD(그날 0시). KEEP_DAYS 일 전보다 앞이면 KEEP_DAYS 일 전으로 줄인다 (capped).
39
+ export function parseSince(raw, now = Date.now()) {
40
+ const d = new Date(now);
41
+ const at = (back) => new Date(d.getFullYear(), d.getMonth(), d.getDate() - back).getTime();
42
+ let back = null;
43
+ if (raw === 'today') back = 0;
44
+ else if (raw === 'yesterday') back = 1;
45
+ else if (/^\d+d$/.test(raw)) back = Number(raw.slice(0, -1));
46
+ else {
47
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(raw);
48
+ if (!m) return { error: raw === '' ? t('opt.sinceMissing') : t('opt.sinceBad', { value: JSON.stringify(raw) }) };
49
+ const day = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
50
+ // 2026-02-30 처럼 없는 날짜는 다음 달로 넘어가므로 되돌려 확인한다.
51
+ if (day.getFullYear() !== Number(m[1]) || day.getMonth() !== Number(m[2]) - 1 || day.getDate() !== Number(m[3])) return { error: t('opt.sinceBad', { value: JSON.stringify(raw) }) };
52
+ back = Math.round((at(0) - day.getTime()) / 86400_000);
53
+ if (back < 0) return { error: t('opt.sinceFuture', { value: JSON.stringify(raw) }) };
54
+ }
55
+ const capped = back > KEEP_DAYS;
56
+ back = Math.min(back, KEEP_DAYS);
57
+ return { from: at(back), back, capped };
58
+ }
59
+
33
60
  // --report <kind>, --report=<kind>, --by <tool|model|project>, --by=..., --days <N>, --months <N> (= 꼴도) 를 꺼낸다.
34
61
  // kind 는 --report 를 주지 않았으면 null. --by·--days·--months 는 --report 와 함께일 때만 받는다.
35
- // --days 는 daily, --months 는 monthly 와만 쓴다. capped: --days 를 30으로(--months 를 12로) 줄였는지.
36
- export function reportOption(argv) {
62
+ // --days 는 daily, --months 는 monthly 와만 쓴다. capped: --days 를 30으로(--months 를 12로, --since 를 30일 전으로) 줄였는지.
63
+ // --report sessions 는 --since, --plan <USD>, --md, --show-prompts 를 받는다 (이 넷은 sessions 와만 쓴다). --by·--days·--months 는 받지 않는다.
64
+ export function reportOption(argv, now = Date.now()) {
37
65
  let kind = null;
38
66
  let by = 'tool';
39
67
  let days = DEFAULT_DAYS;
@@ -42,10 +70,22 @@ export function reportOption(argv) {
42
70
  let gave = null;
43
71
  let error = null;
44
72
  let extra = false;
73
+ let since = null;
74
+ let plan = null;
75
+ let md = false;
76
+ let prompts = false;
77
+ let sessionsOnly = null;
78
+ let sinceRaw = DEFAULT_SINCE;
45
79
  const rest = [];
46
80
  for (let i = 0; i < argv.length; i++) {
47
81
  const a = argv[i];
48
- const m = /^--(report|by|days|months)(?:=(.*))?$/.exec(a);
82
+ if (a === '--md' || a === '--show-prompts') {
83
+ sessionsOnly ??= a;
84
+ if (a === '--md') md = true;
85
+ else prompts = true;
86
+ continue;
87
+ }
88
+ const m = /^--(report|by|days|months|since|plan)(?:=(.*))?$/.exec(a);
49
89
  if (!m) {
50
90
  rest.push(a);
51
91
  continue;
@@ -55,8 +95,19 @@ export function reportOption(argv) {
55
95
  if (name === 'report') {
56
96
  if (KINDS.includes(raw)) kind = raw;
57
97
  else error ??= raw === '' ? t('opt.reportMissing') : t('opt.reportBad', { value: JSON.stringify(raw) });
98
+ } else if (name === 'since') {
99
+ sessionsOnly ??= '--since';
100
+ sinceRaw = raw;
101
+ const r = parseSince(raw, now);
102
+ if (r.error) error ??= r.error;
103
+ } else if (name === 'plan') {
104
+ sessionsOnly ??= '--plan';
105
+ const n = /^\d+(?:\.\d+)?$/.test(raw) ? Number(raw) : NaN;
106
+ if (n > 0) plan = n;
107
+ else error ??= raw === '' ? t('opt.planMissing') : t('opt.planBad', { value: JSON.stringify(raw) });
58
108
  } else if (name === 'by') {
59
109
  extra = true;
110
+ gave ??= 'by';
60
111
  if (BY.includes(raw)) by = raw;
61
112
  else error ??= raw === '' ? t('opt.byMissing') : t('opt.byBad', { value: JSON.stringify(raw) });
62
113
  } else {
@@ -71,9 +122,16 @@ export function reportOption(argv) {
71
122
  } else error ??= raw === '' ? t(`opt.${name}Missing`) : t(`opt.${name}Bad`, { value: JSON.stringify(raw) });
72
123
  }
73
124
  }
125
+ if (!error && sessionsOnly && kind !== 'sessions') error = t('opt.sessionsOnly', { opt: sessionsOnly });
74
126
  if (!error && extra && !kind) error = t('opt.reportOnly');
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 };
127
+ if (!error && kind === 'sessions' && gave) error = t('opt.notSessions', { opt: `--${gave}` });
128
+ if (!error && gave && gave !== 'by' && kind && (gave === 'days') !== (kind === 'daily')) error = t(gave === 'days' ? 'opt.daysDaily' : 'opt.monthsMonthly');
129
+ if (!error && kind === 'sessions') {
130
+ const r = parseSince(sinceRaw, now);
131
+ since = r.from;
132
+ capped = r.capped;
133
+ }
134
+ return { kind, by, days, months, capped, rest, error, since, plan, md, prompts };
77
135
  }
78
136
 
79
137
  const zero = () => ({ tokens: 0, cost: 0, unpriced: false });
@@ -0,0 +1,377 @@
1
+ // aitop --report sessions: 기간(--since, 기본 어제 0시부터 지금까지) 안에 사용량이 있는 세션을 한 줄씩 보이고, 맨 위에 요약 카드
2
+ // (기간 API 정가 합계, 도구별 비중, 세션 수, --plan 을 주면 구독료 비례 몫의 몇 배인지)를 둔다. 표, --md, --json 셋 중 하나로 낸다.
3
+ // 토큰·비용·모델·프로젝트는 날짜별 장부(--report daily 와 같은 값, 같은 프로젝트 규칙)에서, 시작·끝 시각·고친 파일·첫 지시·세션 이름은
4
+ // 기록 요약(sources/sheets.mjs)에서 온다. agy 는 시작·끝을 장부의 호출 시각에서 얻고, 고친 파일과 첫 지시는 모른다 ('-').
5
+ // 첫 지시는 --show-prompts 일 때만 낸다 (공유용 출력에 개인 내용이 섞이지 않게).
6
+ import { existsSync } from 'node:fs';
7
+ import { basename, dirname, join } from 'node:path';
8
+ import { t } from './i18n.mjs';
9
+ import { fmtTokens, mask, oneLine, pad, stripControl, truncate, width } from './text.mjs';
10
+ import { money } from './line.mjs';
11
+ import { tildeIn } from './paths.mjs';
12
+ import { dayKey } from './sources/common.mjs';
13
+ import { projectLabels } from './sources/projects.mjs';
14
+ import { MAX_MS, UNKNOWN, collectReport } from './report.mjs';
15
+
16
+ const DAY_MS = 86400_000;
17
+ // 구독료를 나눌 달 길이 (일).
18
+ export const PLAN_DAYS = 30;
19
+ // 화면·Markdown 의 첫 지시 길이 (글자 폭).
20
+ export const PROMPT_WIDTH = 60;
21
+ const TOOLS = ['claude', 'codex', 'agy'];
22
+ const STEP_MS = 250;
23
+ const FLUSH_MS = 3000;
24
+
25
+ const used = (x) => x && (x.tokens > 0 || x.cost > 0);
26
+ // 장부 days 중 기간 [lo, hi] 안에 사용량이 있는 날.
27
+ const inWindow = (b, lo, hi) => Object.entries(b.days ?? {}).filter(([d, x]) => d >= lo && d <= hi && used(x));
28
+
29
+ // Claude 기록 경로 → { sid, main }. 서브에이전트(<sid>/subagents/agent-x.jsonl)는 부모 세션 id 와 부모 기록 경로.
30
+ export function claudeSession(path) {
31
+ const parts = String(path).split(/[\\/]/);
32
+ if (parts.at(-2) === 'subagents' && parts.length >= 3) {
33
+ const sid = parts.at(-3);
34
+ return { sid, main: join(dirname(dirname(dirname(path))), `${sid}.jsonl`), sub: true };
35
+ }
36
+ return { sid: basename(path, '.jsonl'), main: path, sub: false };
37
+ }
38
+
39
+ // 장부와 기록 요약을 읽는다. since: 기간 시작 ms (로컬 0시). 돌려주는 값: { books, extra, agy, partial }.
40
+ // books 는 collectReport(by project)의 장부, extra 는 기록 경로 → { days, custom, title }, agy 는 대화 id → { cwd, title, root }.
41
+ // 처음 읽는 동안 onProgress(0~1, 지난 ms) 로 진행률을 알리고, 시간 상한(maxMs, 장부와 합쳐서)을 넘으면 읽은 만큼으로 partial 을 켠다.
42
+ export async function collectSessions({ since, now = Date.now(), maxMs = MAX_MS, onProgress = () => {}, stepMs = STEP_MS } = {}) {
43
+ const start = Date.now();
44
+ const span = Math.max(1, Math.ceil((now - since) / DAY_MS)) + 1;
45
+ const got = await collectReport({ span, maxMs, now, by: 'project', onProgress: (r, ms) => onProgress(r * 0.7, ms), stepMs });
46
+ const { createBudget } = await import('./tail.mjs');
47
+ const { flushCache } = await import('./cache.mjs');
48
+ const { sheetOf } = await import('./sources/sheets.mjs');
49
+ const { codexIndexName } = await import('./sources/codex.mjs');
50
+ const lo = dayKey(since);
51
+ const hi = dayKey(now);
52
+ const want = new Map();
53
+ let agyUsed = false;
54
+ for (const b of got.books) {
55
+ if (!b.path || !inWindow(b, lo, hi).length) continue;
56
+ if (b.tool === 'agy') agyUsed = true;
57
+ else if (b.tool === 'codex') want.set(b.path, { tool: 'codex' });
58
+ else if (b.tool === 'claude') {
59
+ const s = claudeSession(b.path);
60
+ want.set(b.path, { tool: 'claude', sub: s.sub });
61
+ // 서브에이전트만 기간 안에 쓰였어도 부모 기록에서 이름을 찾는다.
62
+ if (s.sub && !want.has(s.main) && existsSync(s.main)) want.set(s.main, { tool: 'claude', sub: false });
63
+ }
64
+ }
65
+ const sheets = [...want].map(([p, o]) => sheetOf(p, o.tool, { sub: o.sub }));
66
+ let partial = got.partial;
67
+ let lastFlush = Date.now();
68
+ for (;;) {
69
+ const budget = createBudget(Infinity, stepMs);
70
+ for (const s of sheets) s.update(budget);
71
+ if (!budget.exhausted) break;
72
+ const spent = Date.now() - start;
73
+ const size = sheets.reduce((a, s) => a + s.tail.size, 0);
74
+ const left = sheets.reduce((a, s) => a + s.left, 0);
75
+ onProgress(0.7 + 0.3 * (size ? 1 - left / size : 0), spent);
76
+ if (Date.now() - lastFlush > FLUSH_MS) {
77
+ flushCache();
78
+ lastFlush = Date.now();
79
+ }
80
+ if (spent >= maxMs) {
81
+ partial = true;
82
+ break;
83
+ }
84
+ await new Promise((resolve) => setImmediate(resolve));
85
+ }
86
+ const extra = new Map();
87
+ for (const s of sheets) {
88
+ // Codex: 기록 안의 이름 바꾸기가 먼저, 없으면 session_index.jsonl 의 이름.
89
+ const custom = s.custom ?? (s.tool === 'codex' ? codexIndexName(s.path, s.id) : null);
90
+ extra.set(s.path, { days: s.days, custom, title: s.title });
91
+ }
92
+ let agy = new Map();
93
+ if (agyUsed) {
94
+ const { agyConversations } = await import('./sources/projects.mjs');
95
+ agy = agyConversations();
96
+ }
97
+ return { books: got.books, extra, agy, partial };
98
+ }
99
+
100
+ // 세션 표. books: [{ tool, path, project, days }], extra: 경로 → { days, custom, title }, agy: 대화 id → { title, root }.
101
+ // 줄은 기간 안 API 정가 비용이 큰 순서(같으면 토큰, 늦게 끝난 순)다. 스탠드업·공유에서 "어디에 많이 들었나" 가 먼저 보이게.
102
+ // plan: 월 구독료(USD). 주면 summary.plan 에 기간 몫(경과 일수/30)과 그 몇 배인지를 둔다.
103
+ export function buildSessions(books, { since, now = Date.now(), extra = new Map(), agy = new Map(), plan = null } = {}) {
104
+ const lo = dayKey(since);
105
+ const hi = dayKey(now);
106
+ const groups = new Map();
107
+ for (const b of books) {
108
+ const win = inWindow(b, lo, hi);
109
+ if (!win.length) continue;
110
+ let key;
111
+ let main = false;
112
+ let mainPath = null;
113
+ if (b.tool === 'claude') {
114
+ const s = claudeSession(b.path ?? '');
115
+ key = `claude:${s.sid}`;
116
+ main = !s.sub;
117
+ mainPath = s.main;
118
+ } else if (b.tool === 'agy') {
119
+ const id = basename(b.path ?? '', '.db');
120
+ const root = agy.get(id)?.root ?? id;
121
+ key = `agy:${root}`;
122
+ main = root === id;
123
+ mainPath = root;
124
+ } else {
125
+ key = `${b.tool}:${b.path}`;
126
+ main = true;
127
+ mainPath = b.path;
128
+ }
129
+ const g = groups.get(key) ?? { tool: b.tool, mainPath, parts: [], project: null, mainProject: undefined };
130
+ groups.set(key, g);
131
+ g.parts.push({ b, win });
132
+ if (main) g.mainProject = b.project ?? null;
133
+ g.project ??= b.project ?? null;
134
+ }
135
+ const projects = [...groups.values()].map((g) => (g.mainProject !== undefined ? g.mainProject : g.project));
136
+ const labels = projectLabels(new Set(projects.filter(Boolean)));
137
+ const sessions = [];
138
+ let gi = 0;
139
+ for (const g of groups.values()) {
140
+ const project = projects[gi++];
141
+ const models = {};
142
+ let tokens = 0;
143
+ let cost = 0;
144
+ let unpriced = false;
145
+ let a = null;
146
+ let z = null;
147
+ const files = new Set();
148
+ let more = false;
149
+ let filesKnown = g.tool !== 'agy';
150
+ const time = (x) => {
151
+ if (Number.isFinite(x?.a) && (a == null || x.a < a)) a = x.a;
152
+ if (Number.isFinite(x?.z) && (z == null || x.z > z)) z = x.z;
153
+ };
154
+ const paths = new Set();
155
+ for (const { b, win } of g.parts) {
156
+ paths.add(b.path);
157
+ for (const [, d] of win) {
158
+ tokens += d.tokens;
159
+ cost += d.cost;
160
+ if (d.unknown) unpriced = true;
161
+ const parts = d.models && Object.keys(d.models).length ? d.models : { unknown: d };
162
+ for (const [m, x] of Object.entries(parts)) {
163
+ const o = (models[m] ??= { tokens: 0, cost: 0 });
164
+ o.tokens += x.tokens;
165
+ o.cost += x.cost;
166
+ }
167
+ if (g.tool === 'agy') time(d);
168
+ }
169
+ }
170
+ if (g.tool === 'claude') paths.add(g.mainPath);
171
+ let prompt = null;
172
+ for (const p of paths) {
173
+ const e = extra.get(p);
174
+ if (!e) {
175
+ if (g.tool !== 'agy' && g.parts.some((x) => x.b.path === p)) filesKnown = false;
176
+ continue;
177
+ }
178
+ for (const [d, x] of Object.entries(e.days ?? {}).sort(([k1], [k2]) => (k1 < k2 ? -1 : 1))) {
179
+ if (d < lo || d > hi) continue;
180
+ time(x);
181
+ for (const f of x.f ?? []) files.add(f);
182
+ if (x.more) more = true;
183
+ if (p === g.mainPath && x.p && prompt == null) prompt = x.p;
184
+ }
185
+ }
186
+ const main = g.tool === 'agy' ? agy.get(g.mainPath) : extra.get(g.mainPath);
187
+ const custom = g.tool === 'agy' ? null : (main?.custom ?? null);
188
+ const other = main?.title ?? null;
189
+ const label = project ? labels.get(project) : null;
190
+ const name = custom ?? other ?? (project ? basename(String(project)) : null) ?? g.tool;
191
+ const ranked = Object.entries(models)
192
+ .filter(([, x]) => used(x))
193
+ .sort(([m1, x], [m2, y]) => y.cost - x.cost || y.tokens - x.tokens || m1.localeCompare(m2));
194
+ sessions.push({
195
+ tool: g.tool,
196
+ model: ranked[0]?.[0] ?? null,
197
+ models: ranked.map(([m]) => m),
198
+ project: label ?? UNKNOWN,
199
+ projectPath: project ?? null,
200
+ name,
201
+ start: a,
202
+ end: z,
203
+ tokens,
204
+ cost,
205
+ unpriced,
206
+ files: filesKnown ? files.size : null,
207
+ filesMore: filesKnown && more,
208
+ prompt,
209
+ });
210
+ }
211
+ const rank = (x) => TOOLS.indexOf(x.tool);
212
+ sessions.sort((x, y) => y.cost - x.cost || y.tokens - x.tokens || (y.end ?? 0) - (x.end ?? 0) || rank(x) - rank(y) || x.name.localeCompare(y.name));
213
+ return { report: 'sessions', since, now, days: Math.max(0, now - since) / DAY_MS, sessions, summary: summaryOf(sessions, since, now, plan) };
214
+ }
215
+
216
+ function summaryOf(sessions, since, now, plan) {
217
+ const total = { sessions: sessions.length, tokens: 0, cost: 0, unpriced: false, tools: {} };
218
+ for (const s of sessions) {
219
+ total.tokens += s.tokens;
220
+ total.cost += s.cost;
221
+ if (s.unpriced) total.unpriced = true;
222
+ const o = (total.tools[s.tool] ??= { sessions: 0, tokens: 0, cost: 0, share: 0 });
223
+ o.sessions++;
224
+ o.tokens += s.tokens;
225
+ o.cost += s.cost;
226
+ }
227
+ // 비중은 비용으로 나눈다. 비용이 모두 0 이면(가격표에 없는 모델만) 토큰으로 나눈다.
228
+ const byCost = total.cost > 0;
229
+ for (const o of Object.values(total.tools)) o.share = byCost ? o.cost / total.cost : total.tokens > 0 ? o.tokens / total.tokens : 0;
230
+ total.tools = Object.fromEntries(Object.entries(total.tools).sort(([a, x], [b, y]) => y.share - x.share || TOOLS.indexOf(a) - TOOLS.indexOf(b)));
231
+ total.shareBy = byCost ? 'cost' : 'tokens';
232
+ if (plan > 0) {
233
+ const days = Math.max(0, now - since) / DAY_MS;
234
+ const prorated = (plan * days) / PLAN_DAYS;
235
+ total.plan = { monthly: plan, days, prorated, ratio: prorated > 0 ? total.cost / prorated : null };
236
+ } else total.plan = null;
237
+ return total;
238
+ }
239
+
240
+ // --json 모양: 키는 영어, 숫자는 숫자로. 시각은 ISO 문자열(모르면 null). 첫 지시(prompt)는 prompts 일 때만 둔다.
241
+ export function sessionsJson(r, version, { partial = false, prompts = false } = {}) {
242
+ const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
243
+ const s = r.summary;
244
+ return {
245
+ version,
246
+ report: 'sessions',
247
+ since: dayKey(r.since),
248
+ from: iso(r.since),
249
+ to: iso(r.now),
250
+ days: r.days,
251
+ basis: 'api',
252
+ partial,
253
+ unpriced: s.unpriced,
254
+ summary: {
255
+ sessions: s.sessions,
256
+ tokens: s.tokens,
257
+ cost: s.cost,
258
+ unpriced: s.unpriced,
259
+ shareBy: s.shareBy,
260
+ tools: s.tools,
261
+ plan: s.plan,
262
+ },
263
+ sessions: r.sessions.map((x) => ({
264
+ tool: x.tool,
265
+ model: x.model,
266
+ models: x.models,
267
+ project: x.project,
268
+ // 홈 아래 경로는 ~ 로 줄인다 (공유용 출력에 사용자 이름이 덜 드러나게).
269
+ projectPath: x.projectPath == null ? null : tildeIn(x.projectPath),
270
+ name: x.name,
271
+ start: iso(x.start),
272
+ end: iso(x.end),
273
+ tokens: x.tokens,
274
+ cost: x.cost,
275
+ unpriced: x.unpriced,
276
+ files: x.files,
277
+ ...(prompts ? { prompt: x.prompt } : {}),
278
+ })),
279
+ };
280
+ }
281
+
282
+ const two = (n) => String(n).padStart(2, '0');
283
+ const hm = (d) => `${two(d.getHours())}:${two(d.getMinutes())}`;
284
+ const mdhm = (ms) => {
285
+ const d = new Date(ms);
286
+ return `${two(d.getMonth() + 1)}-${two(d.getDate())} ${hm(d)}`;
287
+ };
288
+ // 끝 시각: 시작과 같은 날이면 시:분만.
289
+ const endText = (x) => (x.end == null ? '-' : x.start != null && dayKey(x.start) === dayKey(x.end) ? hm(new Date(x.end)) : mdhm(x.end));
290
+ const startText = (x) => (x.start == null ? '-' : mdhm(x.start));
291
+ const costText = (x) => (used(x) ? `${money(x.cost)}${x.unpriced ? '?' : ''}` : '-');
292
+ const filesText = (x) => (x.files == null ? '-' : `${x.files}${x.filesMore ? '+' : ''}`);
293
+ const modelText = (x) => (x.model ? `${x.model}${x.models.length > 1 ? ` +${x.models.length - 1}` : ''}` : '-');
294
+ const projectText = (x) => (x.project === UNKNOWN ? t('report.unknown') : x.project);
295
+ // 기록에서 온 글: 제어문자를 지우고 한 줄로.
296
+ const clean = (s) => oneLine(stripControl(String(s ?? '')));
297
+ // 첫 지시: 한 줄, 제어문자 제거, 비밀값 가림, 약 60 글자 폭에서 자른다.
298
+ export const promptText = (s) => (s ? truncate(mask(clean(s)), PROMPT_WIDTH) : '-');
299
+ // 0 보다 크지만 반올림하면 0% 인 몫은 <1% 로 (쓴 도구가 0% 로 보이지 않게).
300
+ const pct = (n) => (n > 0 && n < 0.005 ? '<1%' : `${Math.round(n * 100)}%`);
301
+ const daysText = (n) => (n >= 10 ? String(Math.round(n)) : n.toFixed(1));
302
+
303
+ // 요약 카드의 줄들 (표와 Markdown 이 같은 글을 쓴다). md 면 굵게 표시.
304
+ function cardLines(r, md = false) {
305
+ const s = r.summary;
306
+ const b = (x) => (md ? `**${x}**` : x);
307
+ const out = [t('sessions.cardTotal', { cost: b(`${money(s.cost)}${s.unpriced ? '?' : ''}`), tokens: fmtTokens(Math.round(s.tokens)), n: s.sessions })];
308
+ const tools = Object.entries(s.tools).map(([tool, o]) => `${tool} ${pct(o.share)}`);
309
+ if (tools.length) out.push(t(s.shareBy === 'cost' ? 'sessions.cardTools' : 'sessions.cardToolsTokens', { tools: tools.join(' · ') }));
310
+ if (s.plan) {
311
+ const p = s.plan;
312
+ out.push(t('sessions.cardPlan', { plan: money(p.monthly), days: daysText(p.days), prorated: money(p.prorated), ratio: b(p.ratio == null ? '-' : `${p.ratio >= 10 ? Math.round(p.ratio) : p.ratio.toFixed(1)}x`) }));
313
+ }
314
+ return out;
315
+ }
316
+
317
+ function titleOf(r) {
318
+ return t('sessions.title', { from: `${dayKey(r.since)} 00:00`, to: `${dayKey(r.now)} ${hm(new Date(r.now))}`, days: daysText(r.days) });
319
+ }
320
+
321
+ const HEAD_KEYS = ['tool', 'model', 'project', 'name', 'start', 'end', 'tokens', 'cost', 'files'];
322
+ const rowCells = (x) => [x.tool, clean(modelText(x)), clean(projectText(x)), clean(x.name), startText(x), endText(x), used(x) ? fmtTokens(Math.round(x.tokens)) : '-', costText(x), filesText(x)];
323
+ const RIGHT = new Set([6, 7, 8]);
324
+ // 칸 폭 상한 (세션 이름은 터미널 폭에 맞춘다).
325
+ const MAX_W = { 1: 24, 2: 20 };
326
+ const NAME_MIN = 12;
327
+ const NAME_MAX = 40;
328
+
329
+ // 사람이 읽는 표. cols: 터미널 폭 (모르면 0). 세션 이름 칸이 남는 폭을 쓴다. prompts 면 줄 끝에 첫 지시 칸을 둔다.
330
+ export function formatSessions(r, { partial = false, prompts = false, cols = 0 } = {}) {
331
+ const head = HEAD_KEYS.map((k) => t(`sessions.col.${k}`));
332
+ if (prompts) head.push(t('sessions.col.prompt'));
333
+ const body = r.sessions.map((x) => {
334
+ const c = rowCells(x);
335
+ if (prompts) c.push(promptText(x.prompt));
336
+ return c;
337
+ });
338
+ const all = [head, ...body];
339
+ const w = head.map((_, i) => Math.max(...all.map((row) => width(row[i]))));
340
+ for (const [i, max] of Object.entries(MAX_W)) w[i] = Math.min(w[i], Math.max(max, width(head[i])));
341
+ // 첫 지시 칸은 맨 끝이라 채우지 않는다. 세션 이름 칸은 남는 폭(최소 NAME_MIN, 최대 NAME_MAX).
342
+ const fixed = w.reduce((a, n, i) => (i === 3 || (prompts && i === w.length - 1) ? a : a + n), 0) + 2 * (w.length - 1);
343
+ const room = cols > 0 ? cols - fixed - (prompts ? PROMPT_WIDTH : 0) : NAME_MAX;
344
+ w[3] = Math.min(w[3], Math.max(NAME_MIN, Math.min(NAME_MAX, room)));
345
+ const fmt = (row) => row.map((s, i) => (prompts && i === row.length - 1 ? s : pad(s, w[i], RIGHT.has(i) ? 'right' : 'left'))).join(' ').trimEnd();
346
+ const rule = w.map((n, i) => '-'.repeat(prompts && i === w.length - 1 ? Math.min(n, PROMPT_WIDTH) : n)).join(' ');
347
+ const out = [titleOf(r), '', ...cardLines(r).map((l) => ` ${l}`), ''];
348
+ if (r.sessions.length) out.push(fmt(head), rule, ...body.map(fmt));
349
+ else out.push(t('sessions.empty'));
350
+ out.push('', t('sessions.noteBasis'));
351
+ if (r.summary.unpriced) out.push(t('report.unpriced'));
352
+ if (partial) out.push(t('report.partial'));
353
+ return out.join('\n');
354
+ }
355
+
356
+ // Markdown 표 칸: 줄바꿈은 공백으로 바꾸고, | 와 서식 글자(\ ` * _ [ ] < > # ~ !)는 \ 로 이스케이프한다.
357
+ // 붙여 넣은 곳에서 표가 깨지거나 세션 이름이 굵게·링크·HTML 로 바뀌지 않게.
358
+ export const mdCell = (s) => stripControl(String(s ?? '').replace(/\r\n?|\n/g, ' ')).trim().replace(/[\\`*_[\]<>#~!|]/g, '\\$&') || '-';
359
+
360
+ // 그대로 붙여 넣을 수 있는 Markdown: 제목, 요약 몇 줄, 표.
361
+ export function sessionsMarkdown(r, { partial = false, prompts = false } = {}) {
362
+ const head = HEAD_KEYS.map((k) => t(`sessions.col.${k}`));
363
+ if (prompts) head.push(t('sessions.col.prompt'));
364
+ const out = [`**${mdCell(titleOf(r))}**`, '', ...cardLines(r, true).map((l) => `- ${l}`), ''];
365
+ if (r.sessions.length) {
366
+ out.push(`| ${head.map(mdCell).join(' | ')} |`, `|${head.map((_, i) => (RIGHT.has(i) ? ' ---: ' : ' --- ')).join('|')}|`);
367
+ for (const x of r.sessions) {
368
+ const c = rowCells(x);
369
+ if (prompts) c.push(promptText(x.prompt));
370
+ out.push(`| ${c.map(mdCell).join(' | ')} |`);
371
+ }
372
+ } else out.push(t('sessions.empty'));
373
+ out.push('', `_${t('sessions.noteBasis')}_`);
374
+ if (r.summary.unpriced) out.push('', `_${mdCell(t('report.unpriced'))}_`);
375
+ if (partial) out.push('', `_${mdCell(t('report.partial'))}_`);
376
+ return out.join('\n');
377
+ }
@@ -96,7 +96,15 @@ export class AgyBook {
96
96
  if (last < n.idx) n = { idx: -1, model: null, days: {}, slots: {} };
97
97
  result = has
98
98
  ? readCalls(db, n, last, budget, mtime, ({ model, usage: u, cost, at }) => {
99
+ const fresh = !n.days[dayKey(at)];
99
100
  const day = (n.days[dayKey(at)] ??= { tokens: 0, cost: 0, costNoCache: 0, unknown: false });
101
+ // 그날 첫·마지막 호출 시각 (세션 리포트의 시작·끝). 장부 kind 는 그대로라 예전 캐시에서 불러온 날에는 a 가 없다.
102
+ // 그런 날(이미 센 호출이 있는데 a 가 없는 날)은 첫 호출을 모르므로 a 를 채우지 않는다 (시작은 '모름').
103
+ // z 는 마지막 호출이라 이어서 갱신해도 맞다.
104
+ if (Number.isFinite(at)) {
105
+ if ((fresh || day.a != null) && !(day.a <= at)) day.a = at;
106
+ if (!(day.z >= at)) day.z = at;
107
+ }
100
108
  const tokens = u.input + u.output + u.cacheRead + u.cacheWrite;
101
109
  day.tokens += tokens;
102
110
  day.cost += cost?.total ?? 0;
@@ -339,6 +339,13 @@ function applyLine(st, x) {
339
339
  }
340
340
  }
341
341
 
342
+ // 세션 리포트용: rollout(path)·세션 id 의 session_index.jsonl 이름 (없으면 null). 색인은 새로 붙은 줄만 읽는다.
343
+ export function codexIndexName(path, id) {
344
+ if (!id) return null;
345
+ readIndex(undefined);
346
+ return indexName(path, id);
347
+ }
348
+
342
349
  export const _test = { newState, applyLine, phaseOf, snapshot, readIndex, indexName };
343
350
 
344
351
  export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf = processStart, canList = canListProcesses }) {
@@ -103,12 +103,19 @@ export function codexProject(path) {
103
103
 
104
104
  // 대화 id → 작업 폴더. 서브에이전트는 작업 폴더가 비어 있으면 부모를 따라 올라간다. 리포트 한 번에 한 번만 읽는다.
105
105
  export function agyWorkspaces(root = AGY_ROOT) {
106
+ return new Map([...agyConversations(root)].map(([id, c]) => [id, c.cwd]));
107
+ }
108
+
109
+ // 대화 id → { cwd, title, root }. root: 부모를 끝까지 따라간 맨 위 대화 id (서브에이전트를 그 세션에 묶을 때 쓴다).
110
+ // title 은 agy 가 붙인 대화 제목 (세션 리포트의 '그 밖 이름').
111
+ export function agyConversations(root = AGY_ROOT) {
106
112
  const out = new Map();
107
113
  let db;
108
114
  try {
109
115
  db = openReadOnly(join(root, 'conversation_summaries.db'));
110
116
  if (!db) return out;
111
- const rows = db.prepare('select conversation_id id, parent_conversation_id parent, workspace_uris ws from conversation_summaries').all();
117
+ // title 열은 예전 기록에 없을 수 있어 * 로 읽는다.
118
+ const rows = db.prepare('select * from conversation_summaries').all().map((r) => ({ id: r.conversation_id, parent: r.parent_conversation_id, ws: r.workspace_uris, title: r.title }));
112
119
  const byId = new Map(rows.map((r) => [r.id, r]));
113
120
  for (const r of rows) {
114
121
  let cur = r;
@@ -117,7 +124,9 @@ export function agyWorkspaces(root = AGY_ROOT) {
117
124
  cur = byId.get(cur.parent);
118
125
  cwd = cur ? cwdOf(cur.ws) : null;
119
126
  }
120
- out.set(r.id, cwd);
127
+ let top = r;
128
+ for (let i = 0; top.parent && byId.has(top.parent) && i < 10; i++) top = byId.get(top.parent);
129
+ out.set(r.id, { cwd, title: typeof r.title === 'string' && r.title ? r.title : null, root: top.id });
121
130
  }
122
131
  } catch (e) {
123
132
  debugIo('report', 'agy workspaces read failed', e);
@@ -0,0 +1,170 @@
1
+ // 세션 리포트(--report sessions)용 기록 요약: Claude·Codex 기록 파일 하나마다 날짜별 활동 시작·끝 시각, 고친 파일, 그날 첫 지시와
2
+ // 세션 이름(사용자 이름, 그 밖 이름)을 모은다. 사용량(토큰·비용)은 장부(claude-ledger.mjs 등)가 세고, 여기서는 세지 않는다.
3
+ // 장부 캐시 모양은 그대로 두고 따로 읽는다 (장부를 다시 세지 않게). 리포트가 기간 안에 사용량이 있는 기록만 부른다.
4
+ // 기록은 읽기만 하고, 어디까지 읽었는지는 aitop 캐시에 둔다.
5
+ import { JsonlTail } from '../tail.mjs';
6
+ import { loadCache, markDirty } from '../cache.mjs';
7
+ import { dayKey, isNoisePrompt, recentDays, sessionName } from './common.mjs';
8
+ import { readChange } from './files.mjs';
9
+ import { parsePatch, extractPatch, patchSucceeded } from './patch.mjs';
10
+ import { mask, oneLine } from '../text.mjs';
11
+
12
+ const KIND = 'sheet1';
13
+ // 하루에 남기는 고친 파일 수 상한 (캐시가 커지지 않게). 넘으면 more 에 표시해 '200+' 처럼 보인다.
14
+ export const FILES_MAX = 200;
15
+ // 캐시에 남기는 지시 글 길이. 화면에는 더 짧게 자른다.
16
+ const PROMPT_MAX = 200;
17
+ // 결과를 기다리는 Codex 패치 수 상한.
18
+ const PENDING_MAX = 50;
19
+ // 날짜를 남기는 일수 (리포트가 보는 30일보다 조금 길게).
20
+ const KEEP = 32;
21
+
22
+ const clip = (s) => {
23
+ const one = mask(oneLine(s));
24
+ return one ? one.slice(0, PROMPT_MAX) : null;
25
+ };
26
+
27
+ export class SessionSheet {
28
+ // tool: 'claude' 또는 'codex'. sub: Claude 서브에이전트 기록 (지시 글을 세션 첫 지시로 쓰지 않는다).
29
+ constructor(path, tool, { sub = false } = {}) {
30
+ this.tool = tool;
31
+ this.sub = sub;
32
+ this.tail = new JsonlTail(path);
33
+ this.tail.onReset = () => this.clear();
34
+ this.clear();
35
+ const c = loadCache(path, KIND);
36
+ if (c) {
37
+ this.tail.offset = c.offset;
38
+ this.days = c.days ?? {};
39
+ this.custom = c.custom ?? null;
40
+ this.title = c.title ?? null;
41
+ this.id = c.id ?? null;
42
+ this.cwd = c.cwd ?? null;
43
+ this.pending = c.pending ?? {};
44
+ }
45
+ }
46
+
47
+ clear() {
48
+ // 날짜 → { a: 첫 활동 ms, z: 마지막 활동 ms, f: 고친 파일 경로들, more: 상한을 넘었는지, p: 그날 첫 지시 }
49
+ this.days = {};
50
+ // custom: 사용자가 붙인 이름 (Claude custom-title, Codex thread_name_updated). title: 그 밖 이름 (Claude ai-title).
51
+ this.custom = null;
52
+ this.title = null;
53
+ // Codex 세션 id (session_index.jsonl 이름을 찾을 때 쓴다)와 작업 폴더 (상대 경로 패치를 풀 때 쓴다).
54
+ this.id = null;
55
+ this.cwd = null;
56
+ // Codex: 결과를 기다리는 패치 호출 id → 고칠 파일 경로들.
57
+ this.pending = {};
58
+ }
59
+
60
+ // 아직 읽지 않은 크기.
61
+ get left() {
62
+ return Math.max(0, this.tail.size - this.tail.offset);
63
+ }
64
+
65
+ get path() {
66
+ return this.tail.path;
67
+ }
68
+
69
+ update(budget) {
70
+ const n = this.tail.read((x) => this.apply(x), budget);
71
+ if (n) markDirty(this.tail.path, () => this.snapshot(), KIND);
72
+ return n;
73
+ }
74
+
75
+ snapshot() {
76
+ return { offset: this.tail.lineOffset, days: recentDays(this.days, KEEP), custom: this.custom, title: this.title, id: this.id, cwd: this.cwd, pending: this.pending };
77
+ }
78
+
79
+ day(at) {
80
+ const d = (this.days[dayKey(at)] ??= { a: at, z: at, f: [] });
81
+ if (at < d.a) d.a = at;
82
+ if (at > d.z) d.z = at;
83
+ return d;
84
+ }
85
+
86
+ addFile(at, path) {
87
+ if (typeof path !== 'string' || !path) return;
88
+ const d = this.day(at);
89
+ if (d.f.includes(path)) return;
90
+ if (d.f.length >= FILES_MAX) d.more = true;
91
+ else d.f.push(path);
92
+ }
93
+
94
+ prompt(at, text) {
95
+ if (this.sub || !text || isNoisePrompt(text)) return;
96
+ const d = this.day(at);
97
+ d.p ??= clip(text);
98
+ }
99
+
100
+ apply(x) {
101
+ if (this.tool === 'codex') return this.applyCodex(x);
102
+ if (x.type === 'custom-title') this.custom = sessionName(x.customTitle);
103
+ if (x.type === 'ai-title' && x.aiTitle) this.title = sessionName(x.aiTitle);
104
+ if (x.type !== 'user' && x.type !== 'assistant') return;
105
+ const at = Date.parse(x.timestamp);
106
+ if (!Number.isFinite(at)) return;
107
+ this.day(at);
108
+ if (x.type !== 'user' || x.isMeta || !x.message) return;
109
+ if (x.toolUseResult) {
110
+ const c = readChange(x.toolUseResult, at);
111
+ if (c) this.addFile(at, c.path);
112
+ }
113
+ const c = x.message.content;
114
+ const text = typeof c === 'string' ? c : Array.isArray(c) ? c.filter((p) => p?.type === 'text').map((p) => p.text).join(' ') : '';
115
+ this.prompt(at, text);
116
+ }
117
+
118
+ applyCodex(x) {
119
+ const p = x.payload ?? {};
120
+ if (x.type === 'session_meta') {
121
+ this.id = p.id ?? this.id;
122
+ this.cwd = p.cwd ?? this.cwd;
123
+ return;
124
+ }
125
+ if (x.type === 'turn_context') this.cwd = p.cwd ?? this.cwd;
126
+ if (x.type !== 'event_msg' && x.type !== 'response_item') return;
127
+ const at = Date.parse(x.timestamp);
128
+ if (!Number.isFinite(at)) return;
129
+ this.day(at);
130
+ if (x.type === 'event_msg') {
131
+ if (p.type === 'thread_name_updated') this.custom = sessionName(p.thread_name);
132
+ if (p.type === 'user_message') this.prompt(at, p.message);
133
+ return;
134
+ }
135
+ // 패치는 결과가 성공일 때만 고친 파일로 센다 (codex.mjs 와 같다).
136
+ let text = null;
137
+ if (p.type === 'custom_tool_call' && p.name === 'apply_patch') text = String(p.input ?? '');
138
+ else if (p.type === 'function_call') {
139
+ let args = {};
140
+ try {
141
+ args = JSON.parse(p.arguments ?? '{}');
142
+ } catch {}
143
+ const cmd = Array.isArray(args.command) ? args.command.join('\n') : String(args.command ?? '');
144
+ if (/\bapply_patch\b/.test(cmd)) text = extractPatch(cmd);
145
+ } else if ((p.type === 'function_call_output' || p.type === 'custom_tool_call_output') && this.pending[p.call_id]) {
146
+ const paths = this.pending[p.call_id];
147
+ delete this.pending[p.call_id];
148
+ if (patchSucceeded(p.output)) for (const f of paths) this.addFile(at, f);
149
+ return;
150
+ }
151
+ if (text && p.call_id) {
152
+ const paths = parsePatch(text, this.cwd).map((r) => r.filePath);
153
+ if (!paths.length) return;
154
+ const keys = Object.keys(this.pending);
155
+ if (keys.length >= PENDING_MAX) delete this.pending[keys[0]];
156
+ this.pending[p.call_id] = paths;
157
+ }
158
+ }
159
+ }
160
+
161
+ const sheets = new Map();
162
+
163
+ // 기록 파일 하나의 요약. 처음이면 만들고(캐시가 있으면 이어 읽는다), 같은 실행 안에서는 다시 쓴다.
164
+ export function sheetOf(path, tool, opts) {
165
+ let s = sheets.get(path);
166
+ if (!s) sheets.set(path, (s = new SessionSheet(path, tool, opts)));
167
+ return s;
168
+ }
169
+
170
+ export const _test = { reset: () => sheets.clear() };