@sejuneoh/aitop 0.33.2 → 0.35.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/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.2",
3
+ "version": "0.35.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': '예산',
@@ -427,6 +460,8 @@ export const STRINGS = {
427
460
  'empty.or': ' 또는 ',
428
461
 
429
462
  'foot.help': '도움',
463
+ // 폭이 모자라 키 안내가 빠졌을 때 ? 칩 라벨.
464
+ 'foot.helpAll': '키 전체',
430
465
  'foot.closeHelp': '도움 닫기',
431
466
  'foot.readOnly': '⊘ 읽기전용',
432
467
  'foot.count': '{n}개',
@@ -461,9 +496,21 @@ export const STRINGS = {
461
496
  'legend.waiting': '응답 대기 (권한·질문). 행 배경이 강조된다',
462
497
  'legend.unseen': '완료 · 확인 전 (작업이 끝났는데 아직 선택해 보지 않음)',
463
498
  'legend.idle': '다음 지시 대기',
499
+ 'legend.live': '실행 중, 상태 모름 (Gemini 는 프로세스만 보인다)',
464
500
  'legend.stopped': '오류로 멈춤 (로그인 필요, 연결 끊김 등). 기록의 API 오류 줄로 판단한다',
465
501
  'legend.ended': '종료',
466
502
  'legend.pin': '고정한 세션 (p). SESSION 칸 앞에 붙는다',
503
+ 'help.extras': '상태 덧붙임',
504
+ 'legend.done': '끝난 팀원 (잠깐 보이고 사라진다)',
505
+ 'legend.hot': '비용이 가장 큰 세션 두 개 (COST 칸)',
506
+ 'legend.cacheKey': '캐시 m:ss',
507
+ 'legend.cache': '캐시 남은 시간 (추정). 1분 미만은 굵은 경고색',
508
+ 'legend.toolKey': '· 4m12s',
509
+ 'legend.tool': '도구가 돈 시간 (1분부터). 10분 넘으면 경고색',
510
+ 'legend.elapsedKey': '{g}3m12s',
511
+ 'legend.elapsed': '팀원 행 끝: 팀원이 일을 시작한 뒤 지난 시간',
512
+ 'legend.stalledKey': '멈춘 듯',
513
+ 'legend.stalled': '팀원 기록이 3분(느린 도구 10분) 그대로. 짐작',
467
514
  'legend.status': '지금 단계. 큰 기록을 처음 읽는 동안은 기록 읽는 중 N%',
468
515
  'legend.tokens': '세션 누적 토큰 (서브에이전트 포함, 캐시 읽기 포함)',
469
516
  'legend.cost': 'API 정가로 환산한 비용 (Codex 는 OpenAI 정가 추정). 가격표에 없는 모델은 빼고 센다',
@@ -480,7 +527,7 @@ export const STRINGS = {
480
527
  // 화면 안 도움말의 키 설명 (help.mjs 의 VIEWS·COMMON). hk.<화면>.<이름>.
481
528
  'hk.table.search': '세션 검색 (이름·폴더·모델). Enter 적용, Esc 지우기',
482
529
  'hk.table.select': '세션 선택',
483
- 'hk.table.next': '다음 볼 세션으로 (응답 대기 → 완료 · 확인 전)',
530
+ 'hk.table.next': '다음 볼 세션으로 (응답 대기 → 멈춤 → 완료 · 확인 전)',
484
531
  'hk.table.sort': '정렬: 기본 → 비용순 → 컨텍스트순 → 최근순. 응답 대기는 늘 맨 위',
485
532
  'hk.table.group': '묶기: 없음 → 프로젝트 → 도구. 묶음 머리에 세션 수·비용',
486
533
  'hk.table.costMode': '비용 기준: API 환산 ↔ 캐시 제외. 표·헤더·상세가 같이 바뀐다 (예산은 늘 API 환산)',
@@ -652,8 +699,8 @@ export const STRINGS = {
652
699
  'opt.lineBad': 'bad --line value {value} (plain or tmux)',
653
700
  'opt.lineWidthMissing': '--line-width needs a value (characters)',
654
701
  '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)',
702
+ 'opt.reportMissing': '--report needs a value (daily, monthly, sessions or trace)',
703
+ 'opt.reportBad': 'bad --report value {value} (daily, monthly, sessions or trace)',
657
704
  'opt.sinceMissing': '--since needs a value (yesterday, today, a number of days like 7d, or YYYY-MM-DD)',
658
705
  'opt.sinceBad': 'bad --since value {value} (yesterday, today, a number of days like 7d, or YYYY-MM-DD)',
659
706
  'opt.sinceFuture': '--since value {value} is after today',
@@ -662,6 +709,9 @@ export const STRINGS = {
662
709
  'opt.sessionsOnly': '{opt} only works with --report sessions',
663
710
  'opt.notSessions': '{opt} does not work with --report sessions (use --since for the period)',
664
711
  'opt.mdJson': '--md and --json cannot be used together',
712
+ 'opt.mdOnly': '{opt} only works with --report sessions or --report trace',
713
+ 'opt.notTrace': '{opt} does not work with --report trace',
714
+ 'opt.traceMissing': '--report trace needs a session (the start of a session id, a log file path, or a session name)',
665
715
  'opt.byMissing': '--by needs a value (tool, model or project)',
666
716
  'opt.byBad': 'bad --by value {value} (tool, model or project)',
667
717
  'opt.daysMissing': '--days needs a value (number of days)',
@@ -712,6 +762,24 @@ export const STRINGS = {
712
762
  'sessions.empty': 'No session used tokens in this period',
713
763
  '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
764
  'sessions.capped': '--since is limited to {n} days back, which the ledger keeps, using {n} days',
765
+ 'trace.title': 'Call tree · {name} · {id}',
766
+ 'trace.summary': '{span} · prompts {prompts} · tool calls {tools} (subagents {agents}) · tokens {tokens} · {cost}',
767
+ 'trace.col.time': 'Time',
768
+ 'trace.col.tokens': 'Tokens',
769
+ 'trace.col.cost': 'Cost',
770
+ 'trace.prompt': 'prompt',
771
+ 'trace.reply': 'reply',
772
+ 'trace.running': 'running',
773
+ 'trace.errors': '({n} failed)',
774
+ 'trace.lost': '(no result)',
775
+ 'trace.folded': '(+{n} folded)',
776
+ 'trace.omittedSteps': '{n} earlier steps left out',
777
+ 'trace.omitted': 'Too many lines, so the {n} oldest prompts were left out',
778
+ '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',
779
+ 'trace.empty': 'This log has no prompts or replies',
780
+ 'trace.unsupported': '{tool} sessions have no call tree yet (only Claude Code sessions for now)',
781
+ 'trace.notFound': 'no session matches {query} (the start of a session id, a log file path, or a /rename name or title)',
782
+ 'trace.many': 'more than one session matches {query}. Give more of the id:',
715
783
 
716
784
  'cfg.notFile': 'config file is not a regular file, not reading it',
717
785
  'cfg.tooBig': 'config file is over {kb}KB, not reading it',
@@ -785,6 +853,7 @@ export const STRINGS = {
785
853
  'phase.stopNetwork': 'Connection lost',
786
854
  'phase.stopApi': { long: 'Stopped by API error', short: 'API error' },
787
855
  'cache.left': 'cache {t}',
856
+ 'status.idleBrief': 'Idle',
788
857
  'cache.expired': 'cache expired',
789
858
  'cache.ttl5m': '5m',
790
859
  'cache.ttl1h': '1h',
@@ -810,7 +879,9 @@ export const STRINGS = {
810
879
  'hdr.working': { long: 'working', short: 'busy' },
811
880
  'hdr.unseen': 'unseen',
812
881
  'hdr.idle': 'idle',
882
+ 'hdr.live': '{n} live',
813
883
  'hdr.waiting': { long: 'waiting', short: 'wait' },
884
+ 'hdr.stopped': 'stopped',
814
885
  'hdr.proj': 'est',
815
886
  'hdr.projApi': 'API est',
816
887
  'hdr.budget': 'budget',
@@ -844,6 +915,7 @@ export const STRINGS = {
844
915
  'empty.or': ' or ',
845
916
 
846
917
  'foot.help': 'help',
918
+ 'foot.helpAll': 'all keys',
847
919
  'foot.closeHelp': 'close help',
848
920
  'foot.readOnly': '⊘ read-only',
849
921
  'foot.count': '{n} found',
@@ -878,9 +950,21 @@ export const STRINGS = {
878
950
  'legend.waiting': 'Waiting for you (permission or question)',
879
951
  'legend.unseen': 'Done, unseen (not selected yet)',
880
952
  'legend.idle': 'Idle, ready for the next prompt',
953
+ 'legend.live': 'Running, state unknown (Gemini: process only)',
881
954
  'legend.stopped': 'Stopped by an error (login needed, connection lost)',
882
955
  'legend.ended': 'Ended',
883
956
  'legend.pin': 'Pinned session (p), before SESSION',
957
+ 'help.extras': 'Status extras',
958
+ 'legend.done': 'Subagent finished (shown briefly)',
959
+ 'legend.hot': 'Two costliest sessions (COST)',
960
+ 'legend.cacheKey': 'cache m:ss',
961
+ 'legend.cache': 'Cache time left (estimate). Bold under 1 min',
962
+ 'legend.toolKey': '· 4m12s',
963
+ 'legend.tool': 'Tool run time (from 1 min). Warning at 10 min',
964
+ 'legend.elapsedKey': '{g}3m12s',
965
+ 'legend.elapsed': 'Subagent row end: time since it started',
966
+ 'legend.stalledKey': 'stalled?',
967
+ 'legend.stalled': 'No log change 3 min (slow tools 10). A guess',
884
968
  'legend.status': 'Current step (Reading log N% on first load)',
885
969
  'legend.tokens': 'Tokens incl. subagents and cache reads',
886
970
  'legend.cost': 'API cost (Codex estimated). Unpriced models not counted',
@@ -896,7 +980,7 @@ export const STRINGS = {
896
980
 
897
981
  'hk.table.search': 'Search by name, folder or model',
898
982
  'hk.table.select': 'Select a session',
899
- 'hk.table.next': 'Next session to check (waiting, then unseen)',
983
+ 'hk.table.next': 'Next session to check (waiting, stopped, then unseen)',
900
984
  'hk.table.sort': 'Sort: cost, context, recent. Waiting on top',
901
985
  'hk.table.group': 'Group by project or tool, with cost',
902
986
  '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 면 서식도 넣지 않는다.
@@ -10,6 +10,8 @@ export const MODES = ['plain', 'tmux'];
10
10
  export const DEFAULT_WIDTH = 40;
11
11
  // 캐시가 없을 때(처음 실행) 장부를 읽는 시간 상한. 넘으면 '...' 만 내고 끝낸다 (tmux 를 오래 막지 않게).
12
12
  export const CAP_MS = 1500;
13
+ // 멈춤 수를 세는 데(지시 대기 세션의 기록 끝 읽기) 장부 뒤에 남겨 두는 최소 시간.
14
+ export const STOP_MIN_MS = 300;
13
15
  // 캐시가 없거나 시간 상한을 넘었을 때 내는 글.
14
16
  export const PENDING = '...';
15
17
  // 기다리는 세션 이름의 최대 폭 (칸). 기본 폭 40 에 오늘 비용·예산·대기(이름과 시간)·작업 중이 함께 들어가는 길이.
@@ -19,7 +21,8 @@ const CUT = '~';
19
21
 
20
22
  // tmux 256색 번호. 응답 대기는 눈에 띄는 주황, 돈은 화면 헤더와 같은 연두. 색약용은 노랑·파랑 계열로 가른다.
21
23
  // 작업 중은 눈에 덜 띄는 회색 계열로 둔다 (주목할 것은 대기다).
22
- const COLOURS = { normal: { waiting: 'colour214', money: 'colour154', running: 'colour250' }, colorBlind: { waiting: 'colour226', money: 'colour75', running: 'colour250' } };
24
+ // 멈춤(오류로 멈춘 세션)은 화면의 경고색과 같은 빨강, 색약용은 주홍. 색이 없어도 'stop' 글자로 갈린다.
25
+ const COLOURS = { normal: { waiting: 'colour214', stopped: 'colour203', money: 'colour154', running: 'colour250' }, colorBlind: { waiting: 'colour226', stopped: 'colour209', money: 'colour75', running: 'colour250' } };
23
26
 
24
27
  // --line, --line=plain|tmux, --line-width <N>, --line-width=<N> 를 꺼낸다. line 은 켜지 않았으면 null.
25
28
  export function lineOption(argv) {
@@ -81,17 +84,18 @@ function waitTexts(waiting, longest, now) {
81
84
  }
82
85
 
83
86
  // 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수),
84
- // longest(가장 오래 기다린 세션 { name, since }, 모르면 null), running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
87
+ // longest(가장 오래 기다린 세션 { name, since }, 모르면 null), stopped(오류로 멈춘 세션 수, 시간 안에 다 세지 못했으면 null), running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
85
88
  // 0 인 항목은 뺀다. 오늘 비용이 0 이어도 예산이 있으면 $0.00/$50 으로 보인다.
86
- // width 를 넘으면 뒤 항목부터 줄인다: 시간당 지출, 작업 중, 대기 세션 이름, 대기 수, 오늘 비용 차례.
89
+ // width 를 넘으면 뒤 항목부터 줄인다: 시간당 지출, 작업 중, 멈춤 수, 대기 세션 이름, 대기 수, 오늘 비용 차례.
87
90
  // 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() } = {}) {
91
+ 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
92
  const c = COLOURS[colorBlind ? 'colorBlind' : 'normal'];
90
93
  // texts: 긴 글부터. 폭이 모자라면 다음 글로 줄이고, 마지막 글도 넘으면 항목을 뺀다.
91
94
  const parts = [];
92
95
  const hasBudget = typeof budgetDay === 'number' && budgetDay > 0;
93
96
  if (!zero(today) || hasBudget) parts.push({ texts: [`${money(zero(today) ? 0 : today)}${hasBudget ? `/${budgetText(budgetDay)}` : ''}`], fg: c.money });
94
97
  if (waiting > 0) parts.push({ texts: waitTexts(waiting, longest, now), fg: c.waiting });
98
+ if (stopped > 0) parts.push({ texts: [`stop ${stopped}`], fg: c.stopped });
95
99
  if (running > 0) parts.push({ texts: [`run ${running}`], fg: c.running });
96
100
  if (!zero(perHour)) parts.push({ texts: [`${rate(perHour)}/h`], fg: c.money });
97
101
  while (parts.length && width(parts.map((p) => p.texts[0]).join(' ')) > max) {
@@ -126,10 +130,14 @@ export function pickCounts(summary, claudeWaiting = []) {
126
130
  export async function collectLine({ capMs = CAP_MS, now = Date.now() } = {}) {
127
131
  const { createBudget } = await import('./tail.mjs');
128
132
  const { collectLedger } = await import('./sources/claude-ledger.mjs');
129
- const { claudeWaiting } = await import('./sources/claude.mjs');
133
+ const { claudeLineCounts } = await import('./sources/claude.mjs');
130
134
  const { readSummary } = await import('./summary.mjs');
131
135
  const budget = createBudget(Infinity, capMs);
132
136
  const usage = collectLedger({ budget, now });
133
137
  if (budget.exhausted || usage.loading != null) return null;
134
- return { today: usage.today.cost, ...pickCounts(readSummary({ now }), claudeWaiting()), perHour: usage.lastHour.cost };
138
+ // 멈춤은 Claude 만 있는 상태라 요약 없이 세션 파일과 기록 끝에서 바로 센다. 대기 목록과 같은 세션 목록을 쓴다.
139
+ // 기록 끝 읽기도 장부와 같은 시간 상한 안에 둔다. 장부가 상한을 거의 다 쓴 경우에도 세어 볼 수 있게 최소 STOP_MIN_MS 는 준다.
140
+ // 그래도 다 세지 못하면 stopped 는 null 이고 줄에서 멈춤 칸만 빠진다.
141
+ const { waiting, stopped } = claudeLineCounts({ deadline: Math.max(budget.deadline, Date.now() + STOP_MIN_MS) });
142
+ return { today: usage.today.cost, ...pickCounts(readSummary({ now }), waiting), stopped, perHour: usage.lastHour.cost };
135
143
  }
package/src/pricing.mjs CHANGED
@@ -55,6 +55,8 @@ const GEMINI_PRICES = {
55
55
  export const priceTag = (tables) => createHash('sha1').update(JSON.stringify(tables)).digest('hex').slice(0, 8);
56
56
 
57
57
  // 모델별 컨텍스트 창 크기(토큰). 출처: Anthropic 모델 표 https://platform.claude.com/docs/en/about-claude/models/overview (2026-11-18 확인). 표에 없는 모델은 contextWindow 가 추측한다.
58
+ // 가격과 달리 창 크기는 틀려도 비용이 바뀌지 않고, 같은 계열이면 거의 같다. 그래서 표와 똑같은 이름이 없으면
59
+ // 앞부분이 같은 가장 긴 키(계열)의 값을 쓴다 (contextWindow 참고).
58
60
  const WINDOWS = {
59
61
  // Gemini 계열의 입력 한도(1,048,576 토큰). Antigravity 의 내부 모델 이름(gemini-4-argon 등)도 같다고 본다.
60
62
  'gemini-': 1_048_576,
@@ -81,20 +83,47 @@ const WINDOWS = {
81
83
  'claude-haiku-4-5': 200_000,
82
84
  };
83
85
 
86
+ // Claude 모델 이름을 가격표 키 모양으로 맞춘다. 떼는 것은 클라우드·도구가 같은 모델에 붙이는 모양뿐이다:
87
+ // - 앞의 Bedrock 접두사: anthropic., global.anthropic., us.anthropic., us-gov.anthropic. 등 (모델 표의 Amazon Bedrock ID)
88
+ // - 끝의 Bedrock 판 번호: -v1:0 (bedrock-runtime 의 예전 ID 모양. 콜론까지 있을 때만 뗀다)
89
+ // - 끝의 [1m]: Claude Code 의 1M 창 모델 지정 (claude-opus-4-6[1m])
90
+ // - 끝의 -latest (Codex 와 같은 규칙)
91
+ // - 끝의 날짜: claude-opus-4-20250514 (4.6 이전 Claude API 의 날짜판 ID), claude-opus-4@20250514 (Vertex AI)
92
+ // - 끝의 -0: claude-opus-4-0, claude-sonnet-4-0 은 claude-opus-4, claude-sonnet-4 의 공식 별칭이다 (계열-주판-0 모양만)
93
+ // 그 밖의 꼬리(-preview, -v2, -9 등)는 다른 모델일 수 있어서 떼지 않는다.
94
+ const claudeKey = (model) =>
95
+ model
96
+ .replace(/^(?:[a-z][a-z0-9-]*\.)?anthropic\./, '')
97
+ .replace(/\[\d+[km]\]$/i, '')
98
+ .replace(/-v\d+:\d+$/, '')
99
+ .replace(/-latest$/, '')
100
+ .replace(/[-@]\d{8}$/, '')
101
+ .replace(/^(claude-[a-z]+-\d+)-0$/, '$1');
102
+
103
+ // 표에서 모델을 찾는다. 이름이 표와 똑같을 때, 또는 claudeKey 로 다듬은 이름이 표와 똑같을 때만 찾는다.
104
+ // 앞부분만 같은 다른 모델(claude-opus-4-9 와 claude-opus-4 등)에 엉뚱한 가격·창 크기를 매기지 않기 위해서다 (#255, #266).
84
105
  function lookup(table, model) {
85
106
  if (!model) return null;
86
- if (table[model]) return table[model];
87
- const key = Object.keys(table)
107
+ return table[model] ?? table[claudeKey(model)] ?? null;
108
+ }
109
+
110
+ // 창 크기 표 찾기. 정확히 맞는 키(claudeKey 로 다듬은 이름 포함)가 먼저이고, 없으면 다듬은 이름과 앞부분이 같은
111
+ // 가장 긴 키(계열 값)를 쓴다. 표에 없는 새 모델(claude-sonnet-5-6 등)이 200K 추측으로 떨어져 게이지가 부풀지 않게 하려는 것이다.
112
+ function windowOf(model) {
113
+ const exact = lookup(WINDOWS, model);
114
+ if (exact || !model) return exact;
115
+ const name = claudeKey(model);
116
+ const key = Object.keys(WINDOWS)
88
117
  .sort((a, b) => b.length - a.length)
89
- .find((k) => model.startsWith(k));
90
- return key ? table[key] : null;
118
+ .find((k) => name.startsWith(k));
119
+ return key ? WINDOWS[key] : null;
91
120
  }
92
121
 
93
122
  // 모르는 모델은 사용량으로 추측한다: 200k 를 넘었으면 1M 창, 아니면 200k 창.
94
123
  // 표에 있어도 사용량이 표 값을 넘으면 추측 값을 쓴다: Sonnet 4/4.5 는 1M 베타로 200K 를 넘을 수 있는데, 기록의 모델 이름으로는 구분되지 않는다.
95
124
  export function contextWindow(model, used = 0) {
96
125
  const guess = used > 200_000 ? 1_000_000 : 200_000;
97
- const w = lookup(WINDOWS, model);
126
+ const w = windowOf(model);
98
127
  return w ? Math.max(w, guess) : guess;
99
128
  }
100
129
 
@@ -178,9 +207,13 @@ export function openaiPrice(model) {
178
207
  return OPENAI_PRICES[model] ?? OPENAI_PRICES[model.replace(/-(latest|\d{4}-\d{2}-\d{2})$/, '')] ?? null;
179
208
  }
180
209
 
181
- // 가격표가 바뀌면 이 값이 바뀌고, 캐시 폴더도 바뀌어 예전 비용이 다시 계산된다. 세 표(Claude, Gemini, Codex)를 모두 넣는다.
210
+ // 가격표가 바뀌면 이 값이 바뀌고, 캐시 폴더도 바뀌어 예전 비용이 다시 계산된다 (월별 보관함도 다시 계산한다).
211
+ // 세 표(Claude, Gemini, Codex)와 찾는 규칙의 판 번호(LOOKUP_REV)를 함께 넣는다.
212
+ // 표의 값은 그대로여도 모델 이름으로 가격을 찾는 규칙(lookup, claudeKey, openaiPrice 등)이 바뀌면 LOOKUP_REV 를 올린다.
213
+ // lookup-2: Claude 가격을 앞부분 일치가 아니라 정규화 후 정확 일치로 찾는다 (#266).
182
214
  export const PRICE_TABLES = [PRICES, GEMINI_PRICES, OPENAI_PRICES];
183
- export const PRICE_TAG = priceTag(PRICE_TABLES);
215
+ export const LOOKUP_REV = 'lookup-2';
216
+ export const PRICE_TAG = priceTag([...PRICE_TABLES, LOOKUP_REV]);
184
217
 
185
218
  // Codex 세션 누적 토큰(tokens: input 은 캐시 제외, cacheRead, output)의 환산 비용. 가격표에 없는 모델이면 null.
186
219
  export function codexCost(model, t) {
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 });