@sejuneoh/aitop 0.33.1 → 0.34.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
@@ -37,8 +37,8 @@ Native Windows support is early (Windows Terminal recommended): Claude Code and
37
37
 
38
38
  ## Features
39
39
 
40
- - **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle, or stopped by an error (`! Login needed`, `! Connection lost`, read from the API error lines Claude Code already logs; it sorts right under waiting and pinned sessions and never counts as done). Subagent rows show how long they have run ([details](#subagents))
41
- - **Prompt cache countdown** for Claude sessions waiting on you or idle: `cache 3:12` after the status text (warning color under a minute, dim `cache expired` after), estimated from the log's `cache_creation` 5m/1h tokens and the last request start, per the [prompt caching docs](https://platform.claude.com/docs/en/build-with-claude/prompt-caching). Dropped first on narrow screens; `--json` has `cacheExpiresAt`
40
+ - **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle, or stopped by an error (`! Login needed`, `! Connection lost`, read from the API error lines Claude Code already logs; it sorts right under waiting and pinned sessions, is counted on its own as `! 1 stopped` in the header, the window title (`(2◆ 1! 1●)`), `n` and `--line`, and never counts as done). Subagent rows show how long they have run ([details](#subagents))
41
+ - **Prompt cache countdown** for Claude sessions waiting on you or idle: `cache 3:12` after the status text (warning color under a minute, dim `cache expired` after), estimated from the log's `cache_creation` 5m/1h tokens and the last request start, per the [prompt caching docs](https://platform.claude.com/docs/en/build-with-claude/prompt-caching). Dropped first on narrow screens, except under a minute, when the status text is shortened instead; `--json` has `cacheExpiresAt`
42
42
  - **Tool run time** while a session runs a tool: `Tool · Bash · 4m12s`, from the open tool call's start (Claude `tool_use`, Codex `function_call`, Antigravity running step). Shown after one minute, dim warning color from ten minutes (Claude Code's Bash timeout max), not counted while waiting for approval. Dropped first on narrow screens; `--json` has `toolStartedAt`
43
43
  - **Waiting alerts**: blocked sessions jump to the top, with optional bell, desktop notification or hook command
44
44
  - **Tokens and cost** per session and for today / last 7 days, estimated at public API list prices. This is not your bill
@@ -58,6 +58,7 @@ aitop --line print one short status line and exit (for tmux, e.g. $54.13 wai
58
58
  aitop --report daily daily cost table and exit
59
59
  aitop --report monthly monthly cost table (last 12 months) and exit
60
60
  aitop --report sessions yesterday's sessions with cost, for standups (--md, --json)
61
+ aitop --report trace <session> call tree of one Claude Code session with cost per tool call (--md, --json)
61
62
  aitop --help all options
62
63
  aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG=ko or "lang": "ko" in the config file)
63
64
  ```
@@ -104,6 +105,15 @@ aitop --report sessions --md --plan 200
104
105
  aitop --report sessions --since 7d --json
105
106
  ```
106
107
 
108
+ ### Call tree
109
+
110
+ `aitop --report trace <session> [--md|--json] [--show-prompts]` prints the call tree of one Claude Code session: each prompt, the tool calls under it and subagents under their `Agent`/`Task` call, with duration, tokens and estimated cost (API list price) per line. The session is the start of its id (as in `--json` and the resume command), a log file path, or a `/rename` name or title. A tool line gets the cost of the reply that called it, split across the tools that reply called; subagent and prompt lines total their whole branch. Totals can differ slightly from the session cost in other reports (subagent lines in very old logs are not placed in the tree). Repeated calls of one tool are grouped (`Grep ×38`), branches deeper than a subagent's own steps are folded, and past 300 lines the oldest prompts, and then the earliest steps inside a prompt or subagent, are left out and marked `N earlier steps left out`. Failed calls show `✗`, calls without a result yet `●`, and `(no result)` when a later prompt came first or the log has not changed for over 15 minutes. Commands, paths and prompt text are hidden unless you pass `--show-prompts`, and secrets are masked either way. It reads the log once and writes nothing. Codex and Antigravity sessions are not supported yet.
111
+
112
+ ```
113
+ aitop --report trace fix-login
114
+ aitop --report trace 1a2b3c4d --json
115
+ ```
116
+
107
117
  ### Notifications
108
118
 
109
119
  Off by default and only on the live screen. Sessions already waiting (or already over 90% context) when aitop starts are not reported.
@@ -126,7 +136,7 @@ The notification body shows the session's own name when it has one (Claude Code
126
136
 
127
137
  ### tmux status line
128
138
 
129
- `aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the sessions waiting for you with the longest waiting one's name and wait time (`wait fix-login 3m` for one, `wait 2 fix-login 3m` for more; Claude Code read live, names cut to 12 columns with `~`), 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 (the waiting name goes before the waiting count; with a daily budget and a waiting name, `$/h` often does not fit in 40, so raise `--line-width` to keep it). 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 with their names) 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.
139
+ `aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the sessions waiting for you with the longest waiting one's name and wait time (`wait fix-login 3m` for one, `wait 2 fix-login 3m` for more; Claude Code read live, names cut to 12 columns with `~`), the Claude Code sessions stopped by an API error (`stop 1`, read 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 (the waiting name goes before the waiting count, after `stop`; with a daily budget and a waiting name, `$/h` often does not fit in 40, so raise `--line-width` to keep it). 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 with their names) 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.
130
140
 
131
141
  Session names come from your sessions, so in tmux always use `--line=tmux`: it escapes `#` in names, while plain output could let tmux expand a `#{...}` or `#(...)` inside a name. In a zsh prompt with `PROMPT_SUBST`, a `%` in a name can be expanded by zsh, so escape `%` (for example `${$(aitop --line)//\%/%%}`) or use the line only in tmux.
132
142
 
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|sessions, --by tool|model|project, --days <N>, --months <N>, --since, --plan, --md, --show-prompts 는 reportOption 이 꺼낸다.
44
+ // --report daily|monthly|sessions|trace <세션>, --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`);
@@ -180,6 +180,36 @@ if (report.kind === 'sessions') {
180
180
  process.exit(0);
181
181
  }
182
182
 
183
+ // --report trace <세션>: 세션 하나의 호출 트리 (trace.mjs). 장부·캐시·실시간 tracker 없이 기록 파일만 한 번 읽는다. Codex·agy 는 미지원으로 알린다.
184
+ if (report.kind === 'trace') {
185
+ const { findTrace, readTrace, build, formatTrace, traceMarkdown, traceJson, candidatesText, STALE_MS } = await import('../src/trace.mjs');
186
+ const json = args.has('--json');
187
+ if (json && report.md) {
188
+ process.stderr.write(`aitop: ${t('opt.mdJson')}\n`);
189
+ process.exit(2);
190
+ }
191
+ const query = stripControl(report.session);
192
+ const found = await findTrace(report.session);
193
+ if (found.error) {
194
+ const head = t(found.error === 'many' ? 'trace.many' : 'trace.notFound', { query: JSON.stringify(query) });
195
+ process.stderr.write(`aitop: ${head}\n${found.error === 'many' ? candidatesText(found.candidates) + '\n' : ''}`);
196
+ process.exit(found.error === 'many' ? 2 : 1);
197
+ }
198
+ if (found.tool !== 'claude') {
199
+ process.stderr.write(`aitop: ${t('trace.unsupported', { tool: found.tool === 'agy' ? 'Antigravity' : 'Codex' })}\n`);
200
+ process.exit(1);
201
+ }
202
+ const { lines, subagents, mtime } = await readTrace(found.path, { showArgs: report.prompts });
203
+ // 기록이 STALE_MS 넘게 바뀌지 않았으면 끝난 세션으로 본다 (결과 없는 도구를 진행 중으로 두지 않는다).
204
+ const r = build(lines, { subagents, showArgs: report.prompts, ended: Date.now() - mtime > STALE_MS });
205
+ const meta = { id: found.id, name: found.name };
206
+ const cols = process.stdout.isTTY ? process.stdout.columns : Number(process.env.COLUMNS) || 0;
207
+ const text = json ? JSON.stringify(traceJson(r, VERSION, meta), null, 2) : report.md ? traceMarkdown(r, meta) : formatTrace(r, meta, { cols });
208
+ process.stdout.on('error', (err) => process.exit(err.code === 'EPIPE' ? 0 : 1));
209
+ await new Promise((resolve) => process.stdout.write(text + '\n', resolve));
210
+ process.exit(0);
211
+ }
212
+
183
213
  if (report.kind) {
184
214
  const { buildMonthly, buildReport, collectMonthly, collectReport, fitReport, formatReport, PIPE_COLUMNS, progressWriter, reportJson, MAX_DAYS, MAX_MONTHS } = await import('../src/report.mjs');
185
215
  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.33.1",
3
+ "version": "0.34.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/attention.mjs CHANGED
@@ -24,23 +24,26 @@ export function markSeen(state, id) {
24
24
  state.unseen.delete(id);
25
25
  }
26
26
 
27
- // 다음에 봐야 할 세션: 지금 선택한 세션은 빼고, 그 다음 것부터 한 바퀴 돌며 응답 대기 → 확인 전 순서로 찾는다.
27
+ // 오류로 멈춘 세션 (로그인 필요·연결 끊김 등, phase stopped). status 는 idle 이지만 사람이 손대야 하므로 대기와 따로 센다 (#262).
28
+ export const isStopped = (s) => Boolean(s.live) && s.phase?.kind === 'stopped';
29
+
30
+ // 다음에 봐야 할 세션: 지금 선택한 세션은 빼고, 그 다음 것부터 한 바퀴 돌며 응답 대기 → 멈춤 → 확인 전 순서로 찾는다.
28
31
  // 선택이 목록에 없으면(검색으로 가려짐 등) 맨 위부터 찾는다.
29
32
  export function nextAttention(state, sessions, selectedId) {
30
33
  const at = sessions.findIndex((s) => s.id === selectedId);
31
34
  const ordered = at < 0 ? sessions : [...sessions.slice(at + 1), ...sessions.slice(0, at)];
32
- return ordered.find((s) => s.status === 'waiting') ?? ordered.find((s) => state.unseen.has(s.id)) ?? null;
35
+ return ordered.find((s) => s.status === 'waiting') ?? ordered.find(isStopped) ?? ordered.find((s) => state.unseen.has(s.id)) ?? null;
33
36
  }
34
37
 
35
- // 응답 대기(◆)와 확인 전(●) 수.
38
+ // 응답 대기(◆), 멈춤(!), 확인 전(●) 수.
36
39
  export function attentionCounts(sessions) {
37
- return { waiting: sessions.filter((s) => s.live && s.status === 'waiting').length, unseen: sessions.filter((s) => s.unseen).length };
40
+ return { waiting: sessions.filter((s) => s.live && s.status === 'waiting').length, stopped: sessions.filter(isStopped).length, unseen: sessions.filter((s) => s.unseen).length };
38
41
  }
39
42
 
40
- // 창 제목: 맨 앞 아이콘(탭 사이에서 aitop 을 찾게) + 응답 대기·확인 전 수. 예: 󰚩 (2◆ 1●) aitop
43
+ // 창 제목: 맨 앞 아이콘(탭 사이에서 aitop 을 찾게) + 응답 대기·멈춤·확인 전 수. 예: 󰚩 (2◆ 1! 1●) aitop
41
44
  export function windowTitle(sessions, icon = '') {
42
- const { waiting, unseen } = attentionCounts(sessions);
43
- const marks = [waiting && `${waiting}◆`, unseen && `${unseen}●`].filter(Boolean);
45
+ const { waiting, stopped, unseen } = attentionCounts(sessions);
46
+ const marks = [waiting && `${waiting}◆`, stopped && `${stopped}!`, unseen && `${unseen}●`].filter(Boolean);
44
47
  return (icon ? icon + ' ' : '') + (marks.length ? `(${marks.join(' ')}) aitop` : 'aitop');
45
48
  }
46
49
 
package/src/i18n.mjs CHANGED
@@ -77,6 +77,9 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
77
77
  기간(기본: 어제 0시부터 지금까지, 최대 30일 전) 안에 사용량이 있는 세션을 비용이 큰 순서로 한 줄씩 보인다
78
78
  (도구, 모델, 프로젝트, 세션 이름, 시작·끝, 토큰, API 정가 환산 비용, 고친 파일 수). 맨 위 요약 카드에 합계와 도구별 비중.
79
79
  --plan 월 구독료를 주면 기간 몫의 몇 배인지 보인다. --md 는 붙여 넣을 Markdown. 첫 지시는 --show-prompts 일 때만
80
+ aitop --report trace <세션> [--md|--json] [--show-prompts] Claude Code 세션 하나의 호출 트리 (지시 → 도구 호출 → 서브에이전트)에
81
+ 시간·토큰·추정 비용(API 정가 환산)을 붙여 보인다. 세션은 id 앞부분, 기록 파일 경로, 또는 /rename 이름·제목.
82
+ 같은 도구 연속 호출은 Grep ×38 처럼 묶고, 깊은 가지는 접는다. 명령·경로 같은 인자와 지시 글은 --show-prompts 일 때만
80
83
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
81
84
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
82
85
  aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (Linux notify-send · macOS osascript · WSL 은 powershell.exe 로 Windows 알림, 없으면 건너뜀)
@@ -136,6 +139,9 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
136
139
  (tool, model, project, session name, start and end, tokens, API list price cost, files changed), with a summary card on top.
137
140
  --plan with your monthly subscription shows how many times its share for the period you used. --md prints pasteable Markdown.
138
141
  First prompts are shown only with --show-prompts
142
+ aitop --report trace <session> [--md|--json] [--show-prompts] show the call tree of one Claude Code session (prompt, tool calls, subagents)
143
+ with time, tokens and estimated cost (API list price). The session is the start of its id, a log file path, or a /rename name or title.
144
+ Repeated calls of one tool are grouped like Grep ×38 and deep branches are folded. Arguments and prompt text only with --show-prompts
139
145
  aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
140
146
  aitop --bell ring the terminal bell when a session starts waiting for you
141
147
  aitop --notify show a desktop notification when a session starts waiting (notify-send on Linux, osascript on macOS, a Windows toast via powershell.exe on WSL; skipped if missing)
@@ -229,8 +235,8 @@ export const STRINGS = {
229
235
  'opt.lineBad': '--line 값 {value} 이 잘못되었습니다 (plain 또는 tmux)',
230
236
  'opt.lineWidthMissing': '--line-width 값이 없습니다 (글자 수)',
231
237
  'opt.lineWidthBad': '--line-width 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
232
- 'opt.reportMissing': '--report 값이 없습니다 (daily, monthly 또는 sessions)',
233
- 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily, monthly 또는 sessions)',
238
+ 'opt.reportMissing': '--report 값이 없습니다 (daily, monthly, sessions 또는 trace)',
239
+ 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily, monthly, sessions 또는 trace)',
234
240
  'opt.sinceMissing': '--since 값이 없습니다 (yesterday, today, 7d 같은 일 수, 또는 YYYY-MM-DD)',
235
241
  'opt.sinceBad': '--since 값 {value} 이 잘못되었습니다 (yesterday, today, 7d 같은 일 수, 또는 YYYY-MM-DD)',
236
242
  'opt.sinceFuture': '--since 값 {value} 이 오늘보다 뒤입니다',
@@ -239,6 +245,9 @@ export const STRINGS = {
239
245
  'opt.sessionsOnly': '{opt} 는 --report sessions 와 함께 쓴다',
240
246
  'opt.notSessions': '{opt} 는 --report sessions 와 함께 쓸 수 없다 (기간은 --since)',
241
247
  'opt.mdJson': '--md 와 --json 은 함께 쓸 수 없다',
248
+ 'opt.mdOnly': '{opt} 는 --report sessions 또는 --report trace 와 함께 쓴다',
249
+ 'opt.notTrace': '{opt} 는 --report trace 와 함께 쓸 수 없다',
250
+ 'opt.traceMissing': '--report trace 뒤에 세션을 준다 (세션 id 앞부분, 기록 파일 경로, 또는 세션 이름)',
242
251
  'opt.byMissing': '--by 값이 없습니다 (tool, model 또는 project)',
243
252
  'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool, model 또는 project)',
244
253
  'opt.daysMissing': '--days 값이 없습니다 (일 수)',
@@ -291,6 +300,24 @@ export const STRINGS = {
291
300
  'sessions.empty': '이 기간에 사용량이 있는 세션이 없습니다',
292
301
  'sessions.noteBasis': '비용은 API 정가 환산이며 실제 청구액이 아닙니다. 시작·끝은 기간 안의 활동 시각, 파일은 고친 파일 수 (- 는 모름). 기다림은 응답을 끝낸 뒤 다음 입력·허락까지의 추정 (간격 하나당 2시간까지, 자리 비움과 구분하지 못함)',
293
302
  'sessions.capped': '--since 는 장부가 남기는 {n}일 전까지만 볼 수 있어 {n}일 전으로 줄입니다',
303
+ 'trace.title': '호출 트리 · {name} · {id}',
304
+ 'trace.summary': '{span} · 지시 {prompts} · 도구 호출 {tools} (서브에이전트 {agents}) · 토큰 {tokens} · {cost}',
305
+ 'trace.col.time': '시간',
306
+ 'trace.col.tokens': '토큰',
307
+ 'trace.col.cost': '비용',
308
+ 'trace.prompt': '지시',
309
+ 'trace.reply': '응답',
310
+ 'trace.running': '진행 중',
311
+ 'trace.errors': '(실패 {n})',
312
+ 'trace.lost': '(결과 없음)',
313
+ 'trace.folded': '(+{n} 접힘)',
314
+ 'trace.omittedSteps': '앞 {n}개 생략',
315
+ 'trace.omitted': '줄이 많아 오래된 지시 {n}개를 뺐습니다',
316
+ 'trace.noteBasis': '비용은 API 정가 환산 추정이며 실제 청구액이 아닙니다. 도구 줄은 그 도구를 부른 응답의 비용을 도구 수로 나눈 몫, 서브에이전트 줄과 지시 줄은 그 가지 전체 합입니다',
317
+ 'trace.empty': '이 기록에는 지시나 응답이 없습니다',
318
+ 'trace.unsupported': '{tool} 세션은 아직 호출 트리를 만들지 않습니다 (지금은 Claude Code 세션만)',
319
+ 'trace.notFound': '세션 {query} 를 찾지 못했습니다 (세션 id 앞부분, 기록 파일 경로, 또는 /rename 이름·제목)',
320
+ 'trace.many': '세션 {query} 에 맞는 것이 여럿입니다. id 를 더 길게 준다:',
294
321
 
295
322
  'cfg.notFile': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
296
323
  'cfg.tooBig': '설정 파일이 {kb}KB 를 넘어 읽지 않습니다',
@@ -367,6 +394,8 @@ export const STRINGS = {
367
394
  'phase.stopApi': 'API 오류로 멈춤',
368
395
  // 프롬프트 캐시 만료까지 남은 시간 (STATUS 칸 뒤, 상세 패널). 비용·한도는 단정하지 않는다.
369
396
  'cache.left': '캐시 {t}',
397
+ // STATUS 칸이 좁아 경고 덧붙임(캐시 1분 미만 등)을 남길 때 '다음 지시 대기' 대신 쓰는 짧은 문구.
398
+ 'status.idleBrief': '지시 대기',
370
399
  'cache.expired': '캐시 만료',
371
400
  'cache.ttl5m': '5분',
372
401
  'cache.ttl1h': '1시간',
@@ -392,8 +421,12 @@ export const STRINGS = {
392
421
 
393
422
  'hdr.working': { long: '작업 중', short: '작업' },
394
423
  'hdr.unseen': { long: '확인 전', short: '확인' },
395
- 'hdr.idle': '대기',
424
+ // '응답 대기'와 헷갈리지 않게 무엇을 기다리는지 적는다 (#264).
425
+ 'hdr.idle': { long: '지시 대기', short: '대기' },
426
+ // 살아 있는 세션 수. 영어 'live' 를 그대로 두지 않는다.
427
+ 'hdr.live': '세션 {n}',
396
428
  'hdr.waiting': { long: '응답 대기', short: '응답' },
429
+ 'hdr.stopped': '멈춤',
397
430
  'hdr.proj': '예상',
398
431
  'hdr.projApi': 'API 예상',
399
432
  'hdr.budget': '예산',
@@ -461,9 +494,19 @@ export const STRINGS = {
461
494
  'legend.waiting': '응답 대기 (권한·질문). 행 배경이 강조된다',
462
495
  'legend.unseen': '완료 · 확인 전 (작업이 끝났는데 아직 선택해 보지 않음)',
463
496
  'legend.idle': '다음 지시 대기',
497
+ 'legend.live': '실행 중, 상태 모름 (Gemini 는 프로세스만 보인다)',
464
498
  'legend.stopped': '오류로 멈춤 (로그인 필요, 연결 끊김 등). 기록의 API 오류 줄로 판단한다',
465
499
  'legend.ended': '종료',
466
500
  'legend.pin': '고정한 세션 (p). SESSION 칸 앞에 붙는다',
501
+ 'help.extras': '상태 덧붙임',
502
+ 'legend.done': '끝난 팀원 (잠깐 보이고 사라진다)',
503
+ 'legend.hot': '비용이 가장 큰 세션 두 개 (COST 칸)',
504
+ 'legend.cacheKey': '캐시 m:ss',
505
+ 'legend.cache': '캐시 남은 시간 (추정). 1분 미만은 굵은 경고색',
506
+ 'legend.toolKey': '· 4m12s',
507
+ 'legend.tool': '도구가 돈 시간 (1분부터). 10분 넘으면 경고색',
508
+ 'legend.stalledKey': '멈춘 듯',
509
+ 'legend.stalled': '팀원 기록이 3분(느린 도구 10분) 그대로. 짐작',
467
510
  'legend.status': '지금 단계. 큰 기록을 처음 읽는 동안은 기록 읽는 중 N%',
468
511
  'legend.tokens': '세션 누적 토큰 (서브에이전트 포함, 캐시 읽기 포함)',
469
512
  'legend.cost': 'API 정가로 환산한 비용 (Codex 는 OpenAI 정가 추정). 가격표에 없는 모델은 빼고 센다',
@@ -480,7 +523,7 @@ export const STRINGS = {
480
523
  // 화면 안 도움말의 키 설명 (help.mjs 의 VIEWS·COMMON). hk.<화면>.<이름>.
481
524
  'hk.table.search': '세션 검색 (이름·폴더·모델). Enter 적용, Esc 지우기',
482
525
  'hk.table.select': '세션 선택',
483
- 'hk.table.next': '다음 볼 세션으로 (응답 대기 → 완료 · 확인 전)',
526
+ 'hk.table.next': '다음 볼 세션으로 (응답 대기 → 멈춤 → 완료 · 확인 전)',
484
527
  'hk.table.sort': '정렬: 기본 → 비용순 → 컨텍스트순 → 최근순. 응답 대기는 늘 맨 위',
485
528
  'hk.table.group': '묶기: 없음 → 프로젝트 → 도구. 묶음 머리에 세션 수·비용',
486
529
  'hk.table.costMode': '비용 기준: API 환산 ↔ 캐시 제외. 표·헤더·상세가 같이 바뀐다 (예산은 늘 API 환산)',
@@ -652,8 +695,8 @@ export const STRINGS = {
652
695
  'opt.lineBad': 'bad --line value {value} (plain or tmux)',
653
696
  'opt.lineWidthMissing': '--line-width needs a value (characters)',
654
697
  'opt.lineWidthBad': 'bad --line-width value {value} (a whole number above 0)',
655
- 'opt.reportMissing': '--report needs a value (daily, monthly or sessions)',
656
- 'opt.reportBad': 'bad --report value {value} (daily, monthly or sessions)',
698
+ 'opt.reportMissing': '--report needs a value (daily, monthly, sessions or trace)',
699
+ 'opt.reportBad': 'bad --report value {value} (daily, monthly, sessions or trace)',
657
700
  'opt.sinceMissing': '--since needs a value (yesterday, today, a number of days like 7d, or YYYY-MM-DD)',
658
701
  'opt.sinceBad': 'bad --since value {value} (yesterday, today, a number of days like 7d, or YYYY-MM-DD)',
659
702
  'opt.sinceFuture': '--since value {value} is after today',
@@ -662,6 +705,9 @@ export const STRINGS = {
662
705
  'opt.sessionsOnly': '{opt} only works with --report sessions',
663
706
  'opt.notSessions': '{opt} does not work with --report sessions (use --since for the period)',
664
707
  'opt.mdJson': '--md and --json cannot be used together',
708
+ 'opt.mdOnly': '{opt} only works with --report sessions or --report trace',
709
+ 'opt.notTrace': '{opt} does not work with --report trace',
710
+ 'opt.traceMissing': '--report trace needs a session (the start of a session id, a log file path, or a session name)',
665
711
  'opt.byMissing': '--by needs a value (tool, model or project)',
666
712
  'opt.byBad': 'bad --by value {value} (tool, model or project)',
667
713
  'opt.daysMissing': '--days needs a value (number of days)',
@@ -712,6 +758,24 @@ export const STRINGS = {
712
758
  'sessions.empty': 'No session used tokens in this period',
713
759
  '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). Waited estimates the time from a finished reply to your next prompt or approval (up to 2 hours per gap; time away is counted too)',
714
760
  'sessions.capped': '--since is limited to {n} days back, which the ledger keeps, using {n} days',
761
+ 'trace.title': 'Call tree · {name} · {id}',
762
+ 'trace.summary': '{span} · prompts {prompts} · tool calls {tools} (subagents {agents}) · tokens {tokens} · {cost}',
763
+ 'trace.col.time': 'Time',
764
+ 'trace.col.tokens': 'Tokens',
765
+ 'trace.col.cost': 'Cost',
766
+ 'trace.prompt': 'prompt',
767
+ 'trace.reply': 'reply',
768
+ 'trace.running': 'running',
769
+ 'trace.errors': '({n} failed)',
770
+ 'trace.lost': '(no result)',
771
+ 'trace.folded': '(+{n} folded)',
772
+ 'trace.omittedSteps': '{n} earlier steps left out',
773
+ 'trace.omitted': 'Too many lines, so the {n} oldest prompts were left out',
774
+ 'trace.noteBasis': 'Cost is an API list price estimate, not your actual bill. A tool line gets the cost of the reply that called it, split across the tools it called; subagent and prompt lines total their whole branch',
775
+ 'trace.empty': 'This log has no prompts or replies',
776
+ 'trace.unsupported': '{tool} sessions have no call tree yet (only Claude Code sessions for now)',
777
+ 'trace.notFound': 'no session matches {query} (the start of a session id, a log file path, or a /rename name or title)',
778
+ 'trace.many': 'more than one session matches {query}. Give more of the id:',
715
779
 
716
780
  'cfg.notFile': 'config file is not a regular file, not reading it',
717
781
  'cfg.tooBig': 'config file is over {kb}KB, not reading it',
@@ -785,6 +849,7 @@ export const STRINGS = {
785
849
  'phase.stopNetwork': 'Connection lost',
786
850
  'phase.stopApi': { long: 'Stopped by API error', short: 'API error' },
787
851
  'cache.left': 'cache {t}',
852
+ 'status.idleBrief': 'Idle',
788
853
  'cache.expired': 'cache expired',
789
854
  'cache.ttl5m': '5m',
790
855
  'cache.ttl1h': '1h',
@@ -810,7 +875,9 @@ export const STRINGS = {
810
875
  'hdr.working': { long: 'working', short: 'busy' },
811
876
  'hdr.unseen': 'unseen',
812
877
  'hdr.idle': 'idle',
878
+ 'hdr.live': '{n} live',
813
879
  'hdr.waiting': { long: 'waiting', short: 'wait' },
880
+ 'hdr.stopped': 'stopped',
814
881
  'hdr.proj': 'est',
815
882
  'hdr.projApi': 'API est',
816
883
  'hdr.budget': 'budget',
@@ -878,9 +945,19 @@ export const STRINGS = {
878
945
  'legend.waiting': 'Waiting for you (permission or question)',
879
946
  'legend.unseen': 'Done, unseen (not selected yet)',
880
947
  'legend.idle': 'Idle, ready for the next prompt',
948
+ 'legend.live': 'Running, state unknown (Gemini: process only)',
881
949
  'legend.stopped': 'Stopped by an error (login needed, connection lost)',
882
950
  'legend.ended': 'Ended',
883
951
  'legend.pin': 'Pinned session (p), before SESSION',
952
+ 'help.extras': 'Status extras',
953
+ 'legend.done': 'Subagent finished (shown briefly)',
954
+ 'legend.hot': 'Two costliest sessions (COST)',
955
+ 'legend.cacheKey': 'cache m:ss',
956
+ 'legend.cache': 'Cache time left (estimate). Bold under 1 min',
957
+ 'legend.toolKey': '· 4m12s',
958
+ 'legend.tool': 'Tool run time (from 1 min). Warning at 10 min',
959
+ 'legend.stalledKey': 'stalled?',
960
+ 'legend.stalled': 'No log change 3 min (slow tools 10). A guess',
884
961
  'legend.status': 'Current step (Reading log N% on first load)',
885
962
  'legend.tokens': 'Tokens incl. subagents and cache reads',
886
963
  'legend.cost': 'API cost (Codex estimated). Unpriced models not counted',
@@ -896,7 +973,7 @@ export const STRINGS = {
896
973
 
897
974
  'hk.table.search': 'Search by name, folder or model',
898
975
  'hk.table.select': 'Select a session',
899
- 'hk.table.next': 'Next session to check (waiting, then unseen)',
976
+ 'hk.table.next': 'Next session to check (waiting, stopped, then unseen)',
900
977
  'hk.table.sort': 'Sort: cost, context, recent. Waiting on top',
901
978
  'hk.table.group': 'Group by project or tool, with cost',
902
979
  'hk.table.costMode': 'Cost basis: API cost or no cache',
package/src/line.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 gemini-gen 2m run 3 $3.1/h
1
+ // aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 gemini-gen 2m stop 1 run 3 $3.1/h
2
2
  // 글자는 ASCII 만 쓴다 (이모지·폭이 모호한 기호는 tmux 에서 칸이 어긋난다). 표기는 짧은 영어 약어로 고정하고 번역하지 않는다.
3
3
  // 예외는 세션 이름 속 한글·한자·가나뿐이다 (늘 2칸이라 어긋나지 않는다). 그 밖의 글자는 이름에서 지운다.
4
4
  // 색은 --line=tmux 일 때 tmux 서식(#[fg=colourN])으로만 넣고 ANSI 코드는 쓰지 않는다. NO_COLOR 면 서식도 넣지 않는다.
@@ -19,7 +19,8 @@ const CUT = '~';
19
19
 
20
20
  // tmux 256색 번호. 응답 대기는 눈에 띄는 주황, 돈은 화면 헤더와 같은 연두. 색약용은 노랑·파랑 계열로 가른다.
21
21
  // 작업 중은 눈에 덜 띄는 회색 계열로 둔다 (주목할 것은 대기다).
22
- const COLOURS = { normal: { waiting: 'colour214', money: 'colour154', running: 'colour250' }, colorBlind: { waiting: 'colour226', money: 'colour75', running: 'colour250' } };
22
+ // 멈춤(오류로 멈춘 세션)은 화면의 경고색과 같은 빨강, 색약용은 주홍. 색이 없어도 'stop' 글자로 갈린다.
23
+ const COLOURS = { normal: { waiting: 'colour214', stopped: 'colour203', money: 'colour154', running: 'colour250' }, colorBlind: { waiting: 'colour226', stopped: 'colour209', money: 'colour75', running: 'colour250' } };
23
24
 
24
25
  // --line, --line=plain|tmux, --line-width <N>, --line-width=<N> 를 꺼낸다. line 은 켜지 않았으면 null.
25
26
  export function lineOption(argv) {
@@ -81,17 +82,18 @@ function waitTexts(waiting, longest, now) {
81
82
  }
82
83
 
83
84
  // 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수),
84
- // longest(가장 오래 기다린 세션 { name, since }, 모르면 null), running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
85
+ // longest(가장 오래 기다린 세션 { name, since }, 모르면 null), stopped(오류로 멈춘 세션 수), running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
85
86
  // 0 인 항목은 뺀다. 오늘 비용이 0 이어도 예산이 있으면 $0.00/$50 으로 보인다.
86
- // width 를 넘으면 뒤 항목부터 줄인다: 시간당 지출, 작업 중, 대기 세션 이름, 대기 수, 오늘 비용 차례.
87
+ // width 를 넘으면 뒤 항목부터 줄인다: 시간당 지출, 작업 중, 멈춤 수, 대기 세션 이름, 대기 수, 오늘 비용 차례.
87
88
  // mode 가 tmux 이고 noColor 가 아니면 항목마다 tmux 서식을 씌운다. tmux 모드에서는 이름 속 # 을 ## 로 바꿔 서식으로 읽히지 않게 한다.
88
- export function formatLine({ today = 0, budgetDay = null, waiting = 0, longest = null, running = null, perHour = 0 } = {}, { mode = 'plain', noColor = false, width: max = DEFAULT_WIDTH, colorBlind = false, now = Date.now() } = {}) {
89
+ export function formatLine({ today = 0, budgetDay = null, waiting = 0, longest = null, stopped = 0, running = null, perHour = 0 } = {}, { mode = 'plain', noColor = false, width: max = DEFAULT_WIDTH, colorBlind = false, now = Date.now() } = {}) {
89
90
  const c = COLOURS[colorBlind ? 'colorBlind' : 'normal'];
90
91
  // texts: 긴 글부터. 폭이 모자라면 다음 글로 줄이고, 마지막 글도 넘으면 항목을 뺀다.
91
92
  const parts = [];
92
93
  const hasBudget = typeof budgetDay === 'number' && budgetDay > 0;
93
94
  if (!zero(today) || hasBudget) parts.push({ texts: [`${money(zero(today) ? 0 : today)}${hasBudget ? `/${budgetText(budgetDay)}` : ''}`], fg: c.money });
94
95
  if (waiting > 0) parts.push({ texts: waitTexts(waiting, longest, now), fg: c.waiting });
96
+ if (stopped > 0) parts.push({ texts: [`stop ${stopped}`], fg: c.stopped });
95
97
  if (running > 0) parts.push({ texts: [`run ${running}`], fg: c.running });
96
98
  if (!zero(perHour)) parts.push({ texts: [`${rate(perHour)}/h`], fg: c.money });
97
99
  while (parts.length && width(parts.map((p) => p.texts[0]).join(' ')) > max) {
@@ -126,10 +128,11 @@ export function pickCounts(summary, claudeWaiting = []) {
126
128
  export async function collectLine({ capMs = CAP_MS, now = Date.now() } = {}) {
127
129
  const { createBudget } = await import('./tail.mjs');
128
130
  const { collectLedger } = await import('./sources/claude-ledger.mjs');
129
- const { claudeWaiting } = await import('./sources/claude.mjs');
131
+ const { claudeWaiting, claudeStopped } = await import('./sources/claude.mjs');
130
132
  const { readSummary } = await import('./summary.mjs');
131
133
  const budget = createBudget(Infinity, capMs);
132
134
  const usage = collectLedger({ budget, now });
133
135
  if (budget.exhausted || usage.loading != null) return null;
134
- return { today: usage.today.cost, ...pickCounts(readSummary({ now }), claudeWaiting()), perHour: usage.lastHour.cost };
136
+ // 멈춤은 Claude 만 있는 상태라 요약 없이 세션 파일과 기록 끝에서 바로 센다.
137
+ return { today: usage.today.cost, ...pickCounts(readSummary({ now }), claudeWaiting()), stopped: claudeStopped(), perHour: usage.lastHour.cost };
135
138
  }
package/src/pricing.mjs CHANGED
@@ -1,28 +1,40 @@
1
1
  // Claude API 정가 기준 환산 비용 (USD / 100만 토큰). 구독 요금제 사용분도 "API 로 썼다면" 기준으로 계산한다.
2
- // 출처: Anthropic 모델 가격표(2026-10). 캐시 읽기는 입력가의 0.1배, 캐시 쓰기는 5분 1.25배·1시간 2배.
2
+ // 출처: Anthropic 공식 가격표 https://platform.claude.com/docs/en/about-claude/pricing (2026-11-18 확인).
3
+ // 캐시 읽기는 기본 입력가의 0.1배이고 표에 cacheRead 가 있는 모델만 다르다 (Fable·Mythos 5.1/5.2 는 0.025배, Opus·Sonnet 5.5 는 0.05배).
4
+ // 캐시 쓰기는 5분 1.25배·1시간 2배. Haiku 5.5 의 10만 토큰 초과 요청 단가(5배)는 반영하지 않는다:
5
+ // 보관 벡터(monthly.mjs)에는 요청별 크기가 남지 않아서, 모두 기본 단가로 계산한다.
3
6
  import { createHash } from 'node:crypto';
4
7
 
5
8
  const PRICES = {
9
+ 'claude-fable-5-2': { input: 8, output: 40, cacheRead: 0.2, fast: 2 },
10
+ 'claude-mythos-5-2': { input: 8, output: 40, cacheRead: 0.2, fast: 2 },
6
11
  'claude-fable-5-1': { input: 10, output: 50, cacheRead: 0.25 },
7
12
  'claude-mythos-5-1': { input: 10, output: 50, cacheRead: 0.25 },
8
13
  'claude-fable-5': { input: 10, output: 50 },
14
+ 'claude-mythos-5': { input: 10, output: 50 },
9
15
  'claude-opus-5-5': { input: 4, output: 20, cacheRead: 0.2, fast: 2 },
10
16
  'claude-opus-5': { input: 5, output: 25, fast: 2 },
11
17
  'claude-opus-4-8': { input: 5, output: 25, fast: 2 },
12
18
  'claude-opus-4-7': { input: 5, output: 25 },
13
19
  'claude-opus-4-6': { input: 5, output: 25 },
14
- 'claude-sonnet-5-5': { input: 2, output: 10, cacheRead: 0.2 },
20
+ 'claude-opus-4-5': { input: 5, output: 25 },
21
+ 'claude-opus-4-1': { input: 15, output: 75 },
22
+ 'claude-opus-4': { input: 15, output: 75 },
23
+ 'claude-sonnet-5-5': { input: 2, output: 10, cacheRead: 0.1 },
15
24
  'claude-sonnet-5': { input: 2, output: 10 },
16
25
  'claude-sonnet-4-6': { input: 3, output: 15 },
26
+ 'claude-sonnet-4-5': { input: 3, output: 15 },
27
+ 'claude-sonnet-4': { input: 3, output: 15 },
17
28
  'claude-haiku-5-5': { input: 0.1, output: 0.5 },
18
29
  'claude-haiku-4-5': { input: 1, output: 5 },
19
30
  };
20
31
 
21
32
  // Gemini API 정가 (USD / 100만 토큰, 유료 등급 standard). Antigravity CLI(agy) 사용분을 "API 로 썼다면" 기준으로 계산한다.
22
- // 출처: Google 공식 가격표 https://aistudio.google.com/docs/pricing (2026-11-06 확인). 긴 컨텍스트 구간은 따로 없다.
33
+ // 출처: Google 공식 가격표 https://aistudio.google.com/docs/pricing (2026-11-18 확인). 긴 컨텍스트 구간은 따로 없다.
23
34
  // 출력에는 생각 토큰이 들어 있고, cacheRead 는 context caching 가격이다. 가격이 바뀌는 모델은 날짜순 목록이며,
24
35
  // from 은 그 가격이 시작되는 날(UTC 0시)이다.
25
36
  const GEMINI_PRICES = {
37
+ 'gemini-4-hydrogen': [{ input: 1.5, output: 7.5, cacheRead: 0.075 }],
26
38
  'gemini-4-argon': [
27
39
  { input: 2, output: 10, cacheRead: 0.1 },
28
40
  { from: '2026-12-01', input: 4, output: 20, cacheRead: 0.2 },
@@ -42,21 +54,29 @@ const GEMINI_PRICES = {
42
54
  // 가격표의 지문(8자리). 표의 값이 하나라도 바뀌면 지문도 바뀐다.
43
55
  export const priceTag = (tables) => createHash('sha1').update(JSON.stringify(tables)).digest('hex').slice(0, 8);
44
56
 
45
- // 모델별 컨텍스트 창 크기(토큰). 출처: Anthropic 모델 표(2026-10). 표에 없는 모델은 contextWindow 가 추측한다.
57
+ // 모델별 컨텍스트 창 크기(토큰). 출처: Anthropic 모델 표 https://platform.claude.com/docs/en/about-claude/models/overview (2026-11-18 확인). 표에 없는 모델은 contextWindow 가 추측한다.
46
58
  const WINDOWS = {
47
59
  // Gemini 계열의 입력 한도(1,048,576 토큰). Antigravity 의 내부 모델 이름(gemini-4-argon 등)도 같다고 본다.
48
60
  'gemini-': 1_048_576,
61
+ 'claude-fable-5-2': 1_000_000,
62
+ 'claude-mythos-5-2': 1_000_000,
49
63
  'claude-fable-5-1': 1_000_000,
50
64
  'claude-mythos-5-1': 1_000_000,
51
65
  'claude-fable-5': 1_000_000,
66
+ 'claude-mythos-5': 1_000_000,
52
67
  'claude-opus-5-5': 1_000_000,
53
68
  'claude-opus-5': 1_000_000,
54
69
  'claude-opus-4-8': 1_000_000,
55
70
  'claude-opus-4-7': 1_000_000,
56
71
  'claude-opus-4-6': 1_000_000,
72
+ 'claude-opus-4-5': 200_000,
73
+ 'claude-opus-4-1': 200_000,
74
+ 'claude-opus-4': 200_000,
57
75
  'claude-sonnet-5-5': 1_000_000,
58
76
  'claude-sonnet-5': 1_000_000,
59
77
  'claude-sonnet-4-6': 1_000_000,
78
+ 'claude-sonnet-4-5': 200_000,
79
+ 'claude-sonnet-4': 200_000,
60
80
  'claude-haiku-5-5': 1_000_000,
61
81
  'claude-haiku-4-5': 200_000,
62
82
  };
@@ -71,8 +91,11 @@ function lookup(table, model) {
71
91
  }
72
92
 
73
93
  // 모르는 모델은 사용량으로 추측한다: 200k 를 넘었으면 1M 창, 아니면 200k 창.
94
+ // 표에 있어도 사용량이 표 값을 넘으면 추측 값을 쓴다: Sonnet 4/4.5 는 1M 베타로 200K 를 넘을 수 있는데, 기록의 모델 이름으로는 구분되지 않는다.
74
95
  export function contextWindow(model, used = 0) {
75
- return lookup(WINDOWS, model) ?? (used > 200_000 ? 1_000_000 : 200_000);
96
+ const guess = used > 200_000 ? 1_000_000 : 200_000;
97
+ const w = lookup(WINDOWS, model);
98
+ return w ? Math.max(w, guess) : guess;
76
99
  }
77
100
 
78
101
  function priceOf(model) {
@@ -123,9 +146,9 @@ export function vecCost(tool, model, v, f, at = Date.now()) {
123
146
 
124
147
  // Codex(OpenAI) API 정가 기준 환산 비용 (USD / 100만 토큰). Claude 와 같이 "API 로 썼다면" 기준이다.
125
148
  // 출처: OpenAI 공식 가격표 https://developers.openai.com/api/docs/pricing 와 모델별 문서
126
- // https://developers.openai.com/api/docs/models/<모델 이름> (2026-11-11 확인, 표의 모든 모델이 공식 값과 같다).
149
+ // https://developers.openai.com/api/docs/models/<모델 이름> (2026-11-18 확인, 표의 모든 모델이 공식 값과 같다).
127
150
  // cacheRead 는 cached input 가격이다. gpt-5.1-codex, gpt-5.1-codex-max, gpt-5-codex 는 가격표에는 없고 모델별 문서에만 있다
128
- // (세 모델 모두 지원 종료). gpt-5.6-sol 값은 2026-11-30 까지의 프로모션 가격이며, 그 뒤 가격은 아직 공개되지 않았다.
151
+ // (세 모델 모두 지원 종료). gpt-5.6-sol 값은 2026-11-30 까지의 프로모션 가격이며, 그 뒤 가격은 2026-11-18 에도 공식 가격표에 없다.
129
152
  // 긴 컨텍스트 단가(입력 272K 초과 요청은 입력 2배·출력 1.5배, gpt-5.6-*, gpt-5.5, gpt-5.4)는 반영하지 않는다:
130
153
  // 세션 누적 토큰만으로는 요청마다 272K 를 넘었는지 알 수 없어서, 모두 기본 단가로 계산한다.
131
154
  // 컨텍스트 창은 Codex 기록의 model_context_window 를 그대로 쓰므로 WINDOWS 표에 넣지 않는다.
package/src/report.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
  // 처음 읽는 동안 stderr 가 터미널이면 진행률을 보이고, 시간 상한을 넘으면 읽은 만큼으로 표를 내고 덜 읽었다고 알린다.
5
5
  // --report monthly: 최근 N달(기본·최대 12)의 달별 표. 지난 날은 월별 보관함(monthly.mjs), 접기 전의 날은 장부에서 센다.
6
6
  // --report sessions: 기간 안 세션별 한 줄과 요약 카드 (sessions-report.mjs).
7
+ // --report trace <세션>: 세션 하나의 호출 트리 (trace.mjs).
7
8
  import { t } from './i18n.mjs';
8
9
  import { fmtTokens, pad, stripControl, truncate, width } from './text.mjs';
9
10
  import { money } from './line.mjs';
@@ -11,7 +12,7 @@ import { KEEP_DAYS, lastDays } from './sources/common.mjs';
11
12
  import { projectLabels } from './sources/projects.mjs';
12
13
  import { KEEP_MONTHS, lastMonths, monthOf, monthEnd } from './monthly.mjs';
13
14
 
14
- export const KINDS = ['daily', 'monthly', 'sessions'];
15
+ export const KINDS = ['daily', 'monthly', 'sessions', 'trace'];
15
16
  export const BY = ['tool', 'model', 'project'];
16
17
  // --by project 의 특별한 열: 프로젝트를 못 찾은 기록, 열 수 상한을 넘어 합친 나머지. --json 에도 이 이름 그대로 나간다.
17
18
  export const UNKNOWN = '(unknown)';
@@ -61,6 +62,7 @@ export function parseSince(raw, now = Date.now()) {
61
62
  // kind 는 --report 를 주지 않았으면 null. --by·--days·--months 는 --report 와 함께일 때만 받는다.
62
63
  // --days 는 daily, --months 는 monthly 와만 쓴다. capped: --days 를 30으로(--months 를 12로, --since 를 30일 전으로) 줄였는지.
63
64
  // --report sessions 는 --since, --plan <USD>, --md, --show-prompts 를 받는다 (이 넷은 sessions 와만 쓴다). --by·--days·--months 는 받지 않는다.
65
+ // --report trace 는 바로 뒤(옵션 사이 어디든)의 세션 하나(session)와 --md, --show-prompts 만 받는다.
64
66
  export function reportOption(argv, now = Date.now()) {
65
67
  let kind = null;
66
68
  let by = 'tool';
@@ -75,12 +77,13 @@ export function reportOption(argv, now = Date.now()) {
75
77
  let md = false;
76
78
  let prompts = false;
77
79
  let sessionsOnly = null;
80
+ let mdOnly = null;
78
81
  let sinceRaw = DEFAULT_SINCE;
79
82
  const rest = [];
80
83
  for (let i = 0; i < argv.length; i++) {
81
84
  const a = argv[i];
82
85
  if (a === '--md' || a === '--show-prompts') {
83
- sessionsOnly ??= a;
86
+ mdOnly ??= a;
84
87
  if (a === '--md') md = true;
85
88
  else prompts = true;
86
89
  continue;
@@ -122,16 +125,25 @@ export function reportOption(argv, now = Date.now()) {
122
125
  } else error ??= raw === '' ? t(`opt.${name}Missing`) : t(`opt.${name}Bad`, { value: JSON.stringify(raw) });
123
126
  }
124
127
  }
125
- if (!error && sessionsOnly && kind !== 'sessions') error = t('opt.sessionsOnly', { opt: sessionsOnly });
128
+ // trace 의 세션: 옵션이 아닌 첫 인자 (--theme 값은 빼고). 나머지 옵션 처리는 bin 이 한다.
129
+ let session = null;
130
+ if (kind === 'trace') {
131
+ const i = rest.findIndex((a, j) => !a.startsWith('-') && !/^--theme$/.test(rest[j - 1] ?? ''));
132
+ if (i >= 0) session = rest.splice(i, 1)[0];
133
+ }
134
+ if (!error && mdOnly && kind !== 'sessions' && kind !== 'trace') error = t('opt.mdOnly', { opt: mdOnly });
135
+ if (!error && sessionsOnly && kind !== 'sessions') error = t(kind === 'trace' ? 'opt.notTrace' : 'opt.sessionsOnly', { opt: sessionsOnly });
126
136
  if (!error && extra && !kind) error = t('opt.reportOnly');
127
137
  if (!error && kind === 'sessions' && gave) error = t('opt.notSessions', { opt: `--${gave}` });
138
+ if (!error && kind === 'trace' && gave) error = t('opt.notTrace', { opt: `--${gave}` });
139
+ if (!error && kind === 'trace' && !session) error = t('opt.traceMissing');
128
140
  if (!error && gave && gave !== 'by' && kind && (gave === 'days') !== (kind === 'daily')) error = t(gave === 'days' ? 'opt.daysDaily' : 'opt.monthsMonthly');
129
141
  if (!error && kind === 'sessions') {
130
142
  const r = parseSince(sinceRaw, now);
131
143
  since = r.from;
132
144
  capped = r.capped;
133
145
  }
134
- return { kind, by, days, months, capped, rest, error, since, plan, md, prompts };
146
+ return { kind, by, days, months, capped, rest, error, since, plan, md, prompts, session };
135
147
  }
136
148
 
137
149
  const zero = () => ({ tokens: 0, cost: 0, unpriced: false });
@@ -6,7 +6,7 @@ import { loadCache } from '../cache.mjs';
6
6
  import { contextWindow } from '../pricing.mjs';
7
7
  import { join, basename } from 'node:path';
8
8
  import { isSessionAlive } from '../procs.mjs';
9
- import { ClaudeTracker, tailCustomTitle } from './claude-tracker.mjs';
9
+ import { ClaudeTracker, tailCustomTitle, tailStopReason } from './claude-tracker.mjs';
10
10
  import { emptyTokens, isLongTool, mergeActivity, MEMBER_FADE_MS, sessionName } from './common.mjs';
11
11
  import { mergeFiles } from './files.mjs';
12
12
  import { debug, debugIo } from '../log.mjs';
@@ -479,6 +479,18 @@ export function claudeWaiting() {
479
479
  return out;
480
480
  }
481
481
 
482
+ // --line 용: 오류로 멈춘 살아 있는 Claude 세션 수. 화면과 같이 대기(idle) 세션의 마지막 대화 줄이 API 오류인지 기록 끝만 본다.
483
+ // 세션 파일에 상태가 없는 예전 Claude Code 는 기록 수정 시각으로 상태를 짐작해야 해서 세지 않는다.
484
+ export function claudeStopped() {
485
+ let n = 0;
486
+ for (const e of sessionEntries()?.values() ?? []) {
487
+ if (!e.alive || e.waitingFor || e.status !== 'idle') continue;
488
+ const transcript = findTranscript(e.sessionId);
489
+ if (transcript && tailStopReason(transcript)) n++;
490
+ }
491
+ return n;
492
+ }
493
+
482
494
  export function collectClaude({ showEnded, budget, selectedId }) {
483
495
  const latest = sessionEntries();
484
496
  if (!latest) return [];