@sejuneoh/aitop 0.31.2 → 0.33.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
@@ -3,7 +3,7 @@
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.** One live terminal screen for every Claude Code, Codex CLI and Antigravity CLI session on your machine. Read-only.
6
+ **`top` for your AI coding agents.** One live terminal screen for every Claude Code, Codex CLI and Antigravity CLI session on your machine. No hooks, read-only.
7
7
 
8
8
  ```bash
9
9
  npx @sejuneoh/aitop # try it, no install
@@ -14,13 +14,14 @@ npm i -g @sejuneoh/aitop # then just run: aitop
14
14
 
15
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
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.
17
+ - **No hooks, nothing sent.** Claude Code, Codex CLI and Antigravity CLI side by side, from [several history folders](#several-claude-or-codex-profiles) (`~/.claude`, `~/.claude-work`, ...). aitop only reads the logs they already write. It changes no settings and needs no network, ports or dependencies.
18
18
 
19
19
  **How it differs from similar tools**
20
20
 
21
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
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
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.
24
+ - [Agents Stack](https://marketplace.visualstudio.com/items?itemName=MykD.agents-stack) is a VS Code extension for Claude Code, Antigravity, Codex and Gemini CLI. It adds hooks to each agent's config, and Antigravity has no hook for approval waits, so those do not show. aitop runs in any terminal, adds no hooks and shows Antigravity sessions waiting for approval.
24
25
 
25
26
  ## Install
26
27
 
@@ -36,9 +37,11 @@ Native Windows support is early (Windows Terminal recommended): Claude Code and
36
37
 
37
38
  ## Features
38
39
 
39
- - **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle
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`
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`
40
43
  - **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
44
+ - **Tokens and cost** per session and for today / last 7 days, estimated at public API list prices. This is not your bill
42
45
  - **Changed files and diffs** per session and per prompt
43
46
  - **Read-only**: no network, no ports, no dependencies. It only reads the session logs each CLI already writes
44
47
 
@@ -63,7 +66,15 @@ The language is picked from `--lang`, then `AITOP_LANG`, then `lang` in the conf
63
66
 
64
67
  To continue a session elsewhere (for example when you cannot jump to its tab, as in Windows Terminal with WSL), the detail panel shows a `Resume` command and `y` copies it to the clipboard with OSC 52: Claude `cd <dir> && claude --resume <id>`, Codex `cd <dir> && codex resume <id>`, Antigravity `cd <dir> && agy --conversation <id>` (none for Gemini CLI). A session from a data folder other than `~/.claude` / `~/.codex` (or any session while `CLAUDE_CONFIG_DIR` / `CODEX_HOME` is set) gets `CLAUDE_CONFIG_DIR=<dir>` / `CODEX_HOME=<dir>` before the tool so it finds the right history. Claude finds sessions per folder, so without a known folder no command is made; ids that are not UUIDs make none either. A short detail panel leaves the command out; use `y` or `--json` then. Paths and ids are shell quoted and control characters are stripped. Windows Terminal, WezTerm, iTerm2 and kitty accept OSC 52; tmux needs `set -g set-clipboard on`; other terminals ignore it silently, so copy the command from the panel. Nothing is sent to the session. `--json` has the same command as `resumeCmd` per session (`null` if none).
65
68
 
66
- In `--json`, `phase` stays the Korean status text in every language (as does `AITOP_WAITING_FOR` for `--on-waiting`). Session `name` uses the same user-given names as the table: a Codex session's `name` changes from the folder name to its `thread_name` once it has one. For scripts, use `phaseKind`, a stable state name: `think`, `write`, `tool`, `team`, `waiting`, `idle`, `done`, `ended` (or `null`). Other text fields follow their own rules: with English selected, `--doctor --json` has Korean `tools.*.hint` but English `config.problems`.
69
+ In `--json`, `phase` stays the Korean status text in every language (as does `AITOP_WAITING_FOR` for `--on-waiting`). Session `name` uses the same user-given names as the table: a Codex session's `name` changes from the folder name to its `thread_name` once it has one. For scripts, use `phaseKind`, a stable state name: `think`, `write`, `tool`, `team`, `waiting`, `idle`, `stopped`, `done`, `ended` (or `null`). `stopped` is an idle Claude session whose last log entry is an API error; `stopReason` then says why (`{ "kind": "auth" }` login needed, `network` connection lost, `api` any other API error), `null` otherwise. Other text fields follow their own rules: with English selected, `--doctor --json` has Korean `tools.*.hint` but English `config.problems`.
70
+
71
+ ### Subagents
72
+
73
+ Subagents show as `├─` rows under their session. While one works, its row shows how long it has run (`42s`, `3m12s`, `1h05m`).
74
+
75
+ A dim `stalled?` appears when a working subagent's log has not changed for 3 minutes. While it runs a tool that can be slow (Bash, PowerShell, a nested agent, web fetch or search, an MCP tool, agy `run_command`), the limit is 10 minutes. It is only a guess. It never shows while the session waits for you, and it does not change sorting, alerts, the window title or `--line`. `--json` has it per member as `stalled`, with `startedAt` and `lastActivityAt`.
76
+
77
+ When an Antigravity subagent waits for your approval, its parent row waits too, as `<agent>: <tool>`. So the session jumps to the top and counts for `n`, `--notify` and `--line`. If the parent waits itself, its own wait shows first. Other waiting subagents show on their own rows.
67
78
 
68
79
  ### Daily report
69
80
 
@@ -82,7 +93,11 @@ aitop --report monthly --by model --months 6
82
93
 
83
94
  ### Session report
84
95
 
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; unpriced models are left out, not guessed, and `--json` marks them with `unpriced`) 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).
96
+ `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, time the agent waited for you, tokens, cost (API list price; unpriced models are left out, not guessed, and `--json` marks them with `unpriced`) 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. The card's last line totals the waits (`Agents waited for you 1h12m (estimate)`).
97
+
98
+ Waited is an **estimate**: the sum of gaps from the agent's last line (reply or tool result) to your next input. Inputs are, for Claude, prompts you typed (slash commands included) and answers you picked in a permission dialog or AskUserQuestion; for Codex, `user_message`. Prompts queued while the agent worked and background task notifications do not count, and an interrupt restarts the clock. The logs do not say whether you were at the screen, so **time away cannot be told apart** from waiting; each gap counts for at most 2 hours, so a session left open overnight does not swamp the total. A Claude permission dialog's start time is not logged, so the gap runs from the tool call to its result and includes the tool's run time after approval. Codex does not log approvals, so only prompts count there. Gaps crossing the period start count only the part inside, and subagents are not counted (parent session only). Each session is summed on its own, so with sessions running side by side the total can exceed wall-clock time. agy shows `-`. `--json` has `waitedMs` (milliseconds, `null` when unknown) per session and in `summary`.
99
+
100
+ `--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
101
 
87
102
  ```
88
103
  aitop --report sessions --md --plan 200
@@ -100,7 +115,7 @@ aitop --on-waiting 'my-hook.sh' run a command with /bin/sh -c for the same
100
115
  ```
101
116
 
102
117
  - `waiting`: a session starts waiting for your approval or answer.
103
- - `done`: a session that was busy for over 3 minutes in one turn (config `doneMinutes`; time spent waiting for approval does not count) goes idle and stays idle for 5 seconds. Brief idle gaps between tool calls, approval waits, ended sessions, subagents and sessions whose status is guessed from file times are not reported. Once per turn.
118
+ - `done`: a session that was busy for over 3 minutes in one turn (config `doneMinutes`; time spent waiting for approval does not count) goes idle and stays idle for 5 seconds. Brief idle gaps between tool calls, approval waits, ended sessions, subagents, sessions stopped by an API error and sessions whose status is guessed from file times are not reported. Once per turn.
104
119
  - `context`: context use passes 90%, once; it re-arms after it drops below 85% (for example after compaction).
105
120
 
106
121
  The hook keeps its name: it gets `AITOP_EVENT` (`waiting`, `done` or `context`) plus `AITOP_TOOL`, `AITOP_PROJECT`, `AITOP_SESSION_ID`, `AITOP_CWD` and `AITOP_WAITING_FOR` in its environment. Config file: `"notify": true` or `"notify": ["waiting", "done", "context"]`, `"onWaiting": "..."` (file must be `chmod 600`), `"doneMinutes": 5`. Plain `--notify` keeps the kinds from the config `notify` list (waiting only when there is none). `--no-notify` turns off only the desktop notification: the hook still follows those kinds. `--bell` stays waiting only.
@@ -129,3 +144,5 @@ aitop reads `~/.claude` and `~/.codex` by default. To read more profiles, list t
129
144
  ## License
130
145
 
131
146
  [MIT](https://github.com/SejuneOh/aitop/blob/main/LICENSE)
147
+
148
+ Not affiliated with or endorsed by Anthropic, OpenAI or Google. Product names are trademarks of their owners.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.31.2",
3
+ "version": "0.33.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/attention.mjs CHANGED
@@ -11,7 +11,8 @@ export function updateAttention(state, sessions, selectedId) {
11
11
  ids.add(s.id);
12
12
  const before = state.prev.get(s.id);
13
13
  // 상태를 기록 수정 시각으로 추측한 세션(statusGuessed)은, 작업이 아닌 줄이 붙어도 잠깐 작업 중으로 보이므로 확인 전으로 치지 않는다.
14
- if (s.id === selectedId || s.status === 'busy' || s.status === 'shell' || !s.live) state.unseen.delete(s.id);
14
+ // 오류로 멈춘 세션(stopReason)은 끝난 게 아니므로 확인 전으로 치지 않는다 (화면에 멈춘 이유가 그대로 보인다).
15
+ if (s.id === selectedId || s.status === 'busy' || s.status === 'shell' || !s.live || s.stopReason) state.unseen.delete(s.id);
15
16
  else if ((before === 'busy' || before === 'shell') && s.status === 'idle' && !s.statusGuessed) state.unseen.add(s.id);
16
17
  state.prev.set(s.id, s.status);
17
18
  }
@@ -74,6 +75,7 @@ export function takeNewlyWaiting(watch, sessions) {
74
75
  // 도구 호출 사이의 잠깐 대기는 settleMs 안에 다시 작업 중이 되므로 같은 작업으로 이어 센다 (그 틈도 작업 시간에 넣는다).
75
76
  // 응답 대기(waiting)는 따로 알리므로 끝남으로 치지 않는다. 같은 작업은 이어지지만 기다린 시간은 작업 시간에 넣지 않는다.
76
77
  // 상태를 추측한 세션(statusGuessed), 끝난 세션, 하위 에이전트 줄은 알리지 않는다.
78
+ // 오류로 멈춘 세션(stopReason: 로그인 만료, 연결 끊김 등)도 끝난 게 아니므로 알리지 않고 그 작업을 잊는다.
77
79
  // context: 사용률이 ctxHigh 이상이 되면 한 번 알리고, ctxRearm 아래로 내려가면(압축 등) 다시 알릴 수 있게 한다.
78
80
  // 기록을 다 읽기 전(s.loading)의 세션은 기준선만 잡고, 다 읽은 첫 갱신에 이미 높으면 알리지 않는다.
79
81
  export const DONE_MS = 3 * 60_000;
@@ -101,7 +103,7 @@ export function takeEvents(watch, sessions, { now = Date.now(), ready = true } =
101
103
  const reset = () => Object.assign(st, { run: false, busyMs: 0, busyAt: null, idleSince: null });
102
104
 
103
105
  // done
104
- if (s.statusGuessed) reset();
106
+ if (s.statusGuessed || s.stopReason) reset();
105
107
  else if (isBusy(s)) {
106
108
  st.run = true;
107
109
  st.busyAt ??= now;
package/src/i18n.mjs CHANGED
@@ -276,18 +276,20 @@ export const STRINGS = {
276
276
  'sessions.cardTools': '도구별 비용 비중: {tools}',
277
277
  'sessions.cardToolsTokens': '도구별 토큰 비중: {tools}',
278
278
  'sessions.cardPlan': '구독료 {plan}/월의 {days}일 몫 {prorated} 대비 {ratio} (API 정가 환산, 실제 청구액이 아님)',
279
+ 'sessions.cardWaited': '에이전트가 기다린 시간 {waited} (추정)',
279
280
  'sessions.col.tool': '도구',
280
281
  'sessions.col.model': '모델',
281
282
  'sessions.col.project': '프로젝트',
282
283
  'sessions.col.name': '세션',
283
284
  'sessions.col.start': '시작',
284
285
  'sessions.col.end': '끝',
286
+ 'sessions.col.waited': '기다림',
285
287
  'sessions.col.tokens': '토큰',
286
288
  'sessions.col.cost': '비용',
287
289
  'sessions.col.files': '파일',
288
290
  'sessions.col.prompt': '첫 지시',
289
291
  'sessions.empty': '이 기간에 사용량이 있는 세션이 없습니다',
290
- 'sessions.noteBasis': '비용은 API 정가 환산이며 실제 청구액이 아닙니다. 시작·끝은 기간 안의 활동 시각, 파일은 고친 파일 수 (- 는 모름)',
292
+ 'sessions.noteBasis': '비용은 API 정가 환산이며 실제 청구액이 아닙니다. 시작·끝은 기간 안의 활동 시각, 파일은 고친 파일 수 (- 는 모름). 기다림은 응답을 끝낸 뒤 다음 입력·허락까지의 추정 (간격 하나당 2시간까지, 자리 비움과 구분하지 못함)',
291
293
  'sessions.capped': '--since 는 장부가 남기는 {n}일 전까지만 볼 수 있어 {n}일 전으로 줄입니다',
292
294
 
293
295
  'cfg.notFile': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
@@ -354,6 +356,17 @@ export const STRINGS = {
354
356
  'phase.geminiLimited': '실행 중 (세부 정보 미지원)',
355
357
  'phase.agyOldNode': '실행 중 (세부 정보는 Node 22.15 이상)',
356
358
  'phase.waiting': '응답 대기',
359
+ // 오류로 멈춤 (kind stopped, claude.mjs stoppedPhase). 사용 한도는 기록 표본이 없어 아직 가르지 않는다.
360
+ 'phase.stopAuth': '로그인 필요',
361
+ 'phase.stopNetwork': '연결 끊김',
362
+ 'phase.stopApi': 'API 오류로 멈춤',
363
+ // 프롬프트 캐시 만료까지 남은 시간 (STATUS 칸 뒤, 상세 패널). 비용·한도는 단정하지 않는다.
364
+ 'cache.left': '캐시 {t}',
365
+ 'cache.expired': '캐시 만료',
366
+ 'cache.ttl5m': '5분',
367
+ 'cache.ttl1h': '1시간',
368
+ 'detail.cacheLeft': '프롬프트 캐시 {t} 남음 ({ttl} TTL, 마지막 요청 시작 기준 추정)',
369
+ 'detail.cacheExpired': '프롬프트 캐시 만료 ({ttl} TTL, 마지막 요청 시작 기준 추정)',
357
370
  'phase.shell': '쉘 명령 실행 중',
358
371
  'phase.tool': '도구 실행 · {what}',
359
372
  'phase.toolUnknown': '도구 실행 · 도구',
@@ -391,6 +404,7 @@ export const STRINGS = {
391
404
  'tools.hidden': '숨김 {list}',
392
405
  'tools.ended': '종료된 세션 포함 (24시간)',
393
406
  'table.title': '세션 {n}',
407
+ 'member.stalled': '멈춘 듯',
394
408
  'group.count': '{n}개',
395
409
  'group.waiting': '응답 대기',
396
410
  'group.pinned': '고정',
@@ -442,6 +456,7 @@ export const STRINGS = {
442
456
  'legend.waiting': '응답 대기 (권한·질문). 행 배경이 강조된다',
443
457
  'legend.unseen': '완료 · 확인 전 (작업이 끝났는데 아직 선택해 보지 않음)',
444
458
  'legend.idle': '다음 지시 대기',
459
+ 'legend.stopped': '오류로 멈춤 (로그인 필요, 연결 끊김 등). 기록의 API 오류 줄로 판단한다',
445
460
  'legend.ended': '종료',
446
461
  'legend.pin': '고정한 세션 (p). SESSION 칸 앞에 붙는다',
447
462
  'legend.status': '지금 단계. 큰 기록을 처음 읽는 동안은 기록 읽는 중 N%',
@@ -677,18 +692,20 @@ export const STRINGS = {
677
692
  'sessions.cardTools': 'Cost share by tool: {tools}',
678
693
  'sessions.cardToolsTokens': 'Token share by tool: {tools}',
679
694
  'sessions.cardPlan': '{ratio} the {days}-day share {prorated} of a {plan}/month subscription (API list price, not your actual bill)',
695
+ 'sessions.cardWaited': 'Agents waited for you {waited} (estimate)',
680
696
  'sessions.col.tool': 'Tool',
681
697
  'sessions.col.model': 'Model',
682
698
  'sessions.col.project': 'Project',
683
699
  'sessions.col.name': 'Session',
684
700
  'sessions.col.start': 'Start',
685
701
  'sessions.col.end': 'End',
702
+ 'sessions.col.waited': 'Waited',
686
703
  'sessions.col.tokens': 'Tokens',
687
704
  'sessions.col.cost': 'Cost',
688
705
  'sessions.col.files': 'Files',
689
706
  'sessions.col.prompt': 'First prompt',
690
707
  '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)',
708
+ '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)',
692
709
  'sessions.capped': '--since is limited to {n} days back, which the ledger keeps, using {n} days',
693
710
 
694
711
  'cfg.notFile': 'config file is not a regular file, not reading it',
@@ -754,6 +771,15 @@ export const STRINGS = {
754
771
  'phase.geminiLimited': { long: 'Running (no details yet)', short: 'Running' },
755
772
  'phase.agyOldNode': { long: 'Running (details need Node 22.15+)', short: 'Running' },
756
773
  'phase.waiting': { long: 'Waiting for you', short: 'Waiting' },
774
+ 'phase.stopAuth': 'Login needed',
775
+ 'phase.stopNetwork': 'Connection lost',
776
+ 'phase.stopApi': { long: 'Stopped by API error', short: 'API error' },
777
+ 'cache.left': 'cache {t}',
778
+ 'cache.expired': 'cache expired',
779
+ 'cache.ttl5m': '5m',
780
+ 'cache.ttl1h': '1h',
781
+ 'detail.cacheLeft': 'Prompt cache {t} left ({ttl} TTL, estimated from the last request start)',
782
+ 'detail.cacheExpired': 'Prompt cache expired ({ttl} TTL, estimated from the last request start)',
757
783
  'phase.shell': { long: 'Running shell command', short: 'Shell' },
758
784
  'phase.tool': { long: 'Running tool · {what}', short: 'Tool · {what}' },
759
785
  'phase.toolUnknown': { long: 'Running tool', short: 'Tool' },
@@ -790,6 +816,7 @@ export const STRINGS = {
790
816
  'tools.hidden': 'hidden {list}',
791
817
  'tools.ended': 'with ended sessions (24h)',
792
818
  'table.title': 'Sessions {n}',
819
+ 'member.stalled': 'stalled?',
793
820
  'group.count': '{n}',
794
821
  'group.waiting': 'Waiting',
795
822
  'group.pinned': 'Pinned',
@@ -841,6 +868,7 @@ export const STRINGS = {
841
868
  'legend.waiting': 'Waiting for you (permission or question)',
842
869
  'legend.unseen': 'Done, unseen (not selected yet)',
843
870
  'legend.idle': 'Idle, ready for the next prompt',
871
+ 'legend.stopped': 'Stopped by an error (login needed, connection lost)',
844
872
  'legend.ended': 'Ended',
845
873
  'legend.pin': 'Pinned session (p), before SESSION',
846
874
  'legend.status': 'Current step (Reading log N% on first load)',
package/src/json.mjs CHANGED
@@ -2,6 +2,7 @@ import { projectBudget } from './budget.mjs';
2
2
  import { toolsJson } from './doctor.mjs';
3
3
  import { phaseText } from './i18n.mjs';
4
4
  import { resumeCmd } from './resume.mjs';
5
+ import { memberStalled } from './sources/common.mjs';
5
6
 
6
7
  // aitop --json 출력. 다른 스크립트나 AI 가 읽기 쉬운 모양으로 세션 목록과 사용량 합계를 담는다.
7
8
  // 텍스트는 수집 단계에서 이미 비밀값 가림이 적용돼 있다.
@@ -45,6 +46,12 @@ export function toJson(data, version = null, opts = {}) {
45
46
  // phase 는 화면 언어와 상관없이 늘 한국어 문구(예전과 같은 글)로 두고, 언어와 상관없는 상태 이름은 phaseKind 로 준다.
46
47
  phase: koPhase(s.phase),
47
48
  phaseKind: s.phase?.kind ?? null,
49
+ // 오류로 멈춘 이유 { kind: 'auth'|'network'|'api' } (phaseKind 가 stopped 일 때만), 아니면 null.
50
+ stopReason: s.stopReason ?? null,
51
+ // 프롬프트 캐시가 만료되는 시각 (Claude 의 응답 대기·다음 지시 대기 세션만, 마지막 요청 시작 기준 추정). 이미 지난 시각일 수 있다.
52
+ cacheExpiresAt: iso(s.cacheExpiresAt),
53
+ // 지금 도는 도구가 시작된 시각 (작업 중이고 진행 단계가 도구 실행일 때만, 허락 대기 중이면 null). 화면과 달리 1분 미만도 나간다.
54
+ toolStartedAt: iso(s.toolStartedAt),
48
55
  waitingFor: s.waitingFor ?? null,
49
56
  // 이 세션을 이어 여는 셸 명령 (resume.mjs). 만들 수 없으면 null.
50
57
  resumeCmd: resumeCmd(s),
@@ -60,7 +67,9 @@ export function toJson(data, version = null, opts = {}) {
60
67
  context: { used: s.context?.used ?? 0, window: s.context?.window ?? null },
61
68
  // 변경 내용(diff)은 넣지 않고 파일별 통계만 넣는다. 줄 수는 편집마다 더한 누적값이다 (git diff 아님).
62
69
  files: (s.files ?? []).map((f) => ({ path: f.path, created: Boolean(f.created), edits: f.edits, writtenLines: f.add, deletedLines: f.del, updatedAt: iso(f.at), agents: f.agents ?? [] })),
63
- members: (s.members ?? []).map((m) => ({ name: m.name, task: m.task ?? null, model: m.model ?? null, status: m.status, phase: koPhase(m.phase), phaseKind: m.phase?.kind ?? null, tokens: m.tokens ?? 0, cost: money(m.cost) })),
70
+ // startedAt·lastActivityAt 은 세션의 startedAt·updatedAt 과 같은 ISO 시각이다 (모르면 null).
71
+ // stalled 는 화면의 '멈춘 듯' 과 같은 짐작(common.mjs memberStalled)을 data.at 기준으로 본 값이다.
72
+ members: (s.members ?? []).map((m) => ({ name: m.name, task: m.task ?? null, model: m.model ?? null, status: m.status, phase: koPhase(m.phase), phaseKind: m.phase?.kind ?? null, tokens: m.tokens ?? 0, cost: money(m.cost), startedAt: iso(m.startedAt), lastActivityAt: iso(m.lastActivityAt), stalled: memberStalled(m, data.at ?? Date.now(), s.status) })),
64
73
  })),
65
74
  };
66
75
  }
package/src/order.mjs CHANGED
@@ -4,6 +4,9 @@
4
4
  // 대기 세션이 제 프로젝트 묶음 안에 흩어지면 맨 위라는 약속이 깨지고, 묶음 머리 위에 따로 두면 어느 묶음 소속인지 헷갈린다.
5
5
  // 고정(p)한 세션은 응답 대기 바로 아래에 고정한 순서대로 둔다. 정렬을 바꿔도 그 순서는 바뀌지 않고, 묶을 때는 '고정' 묶음 하나로 모은다.
6
6
  // 응답 대기를 고정보다 위에 두는 것은 사람이 할 일이 고정 목록에 가려지지 않게 하려는 것이다. 고정한 세션이 응답 대기가 되면 대기 쪽으로 올라간다.
7
+ // 오류로 멈춘 세션(phase stopped: 로그인 필요·연결 끊김 등)은 고정 바로 아래, 나머지 세션의 맨 위에 둔다 (#240).
8
+ // 끝난 줄 알고 지나치지 않게 올리되, 지금 바로 답해야 하는 응답 대기와 사람이 정한 고정 순서보다는 아래다.
9
+ // 묶을 때는 따로 모으지 않고 제 묶음의 맨 위에 두므로, 그 묶음도 앞으로 온다.
7
10
  import { costOf } from './ui/draw.mjs';
8
11
  import { lastName } from './paths.mjs';
9
12
 
@@ -54,7 +57,8 @@ export function arrange(sessions, { sort = 'default', group = 'none', costMode =
54
57
  const rank = new Map((pins ?? []).map((id, i) => [id, i]));
55
58
  const waiting = sessions.filter((s) => s.status === 'waiting').sort(cmp);
56
59
  const pinned = sessions.filter((s) => s.status !== 'waiting' && rank.has(s.id)).sort((a, b) => rank.get(a.id) - rank.get(b.id));
57
- const rest = sessions.filter((s) => s.status !== 'waiting' && !rank.has(s.id)).sort(cmp);
60
+ const stopped = (s) => (s.phase?.kind === 'stopped' ? 0 : 1);
61
+ const rest = sessions.filter((s) => s.status !== 'waiting' && !rank.has(s.id)).sort((a, b) => stopped(a) - stopped(b) || cmp(a, b));
58
62
  const keyOf = GROUP_KEY[group];
59
63
  if (!keyOf) return { sessions: [...waiting, ...pinned, ...rest], groups: null };
60
64
  const byName = new Map();
@@ -3,10 +3,12 @@
3
3
  // 토큰·비용·모델·프로젝트는 날짜별 장부(--report daily 와 같은 값, 같은 프로젝트 규칙)에서, 시작·끝 시각·고친 파일·첫 지시·세션 이름은
4
4
  // 기록 요약(sources/sheets.mjs)에서 온다. agy 는 시작·끝을 장부의 호출 시각에서 얻고, 고친 파일과 첫 지시는 모른다 ('-').
5
5
  // 첫 지시는 --show-prompts 일 때만 낸다 (공유용 출력에 개인 내용이 섞이지 않게).
6
+ // 기다린 시간(waited)은 기록 요약의 날짜별 w 합이다 (에이전트가 끝낸 뒤 사용자 입력까지, 간격 하나당 2시간 상한, sheets.mjs).
7
+ // 부모 세션 기록에서만 세고(서브에이전트는 넣지 않는다), agy 는 모른다 ('-').
6
8
  import { existsSync } from 'node:fs';
7
9
  import { basename, dirname, join } from 'node:path';
8
10
  import { t } from './i18n.mjs';
9
- import { fmtTokens, mask, oneLine, pad, stripControl, truncate, width } from './text.mjs';
11
+ import { fmtElapsed, fmtTokens, mask, oneLine, pad, stripControl, truncate, width } from './text.mjs';
10
12
  import { money } from './line.mjs';
11
13
  import { tildeIn } from './paths.mjs';
12
14
  import { dayKey } from './sources/common.mjs';
@@ -169,6 +171,8 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
169
171
  }
170
172
  if (g.tool === 'claude') paths.add(g.mainPath);
171
173
  let prompt = null;
174
+ // 기다린 시간: 부모 기록의 기록 요약이 있을 때만 (없으면 모름).
175
+ let waited = g.tool !== 'agy' && extra.has(g.mainPath) ? 0 : null;
172
176
  for (const p of paths) {
173
177
  const e = extra.get(p);
174
178
  if (!e) {
@@ -181,6 +185,7 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
181
185
  for (const f of x.f ?? []) files.add(f);
182
186
  if (x.more) more = true;
183
187
  if (p === g.mainPath && x.p && prompt == null) prompt = x.p;
188
+ if (p === g.mainPath && waited != null) waited += x.w ?? 0;
184
189
  }
185
190
  }
186
191
  const main = g.tool === 'agy' ? agy.get(g.mainPath) : extra.get(g.mainPath);
@@ -206,6 +211,7 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
206
211
  files: filesKnown ? files.size : null,
207
212
  filesMore: filesKnown && more,
208
213
  prompt,
214
+ waited,
209
215
  });
210
216
  }
211
217
  const rank = (x) => TOOLS.indexOf(x.tool);
@@ -214,8 +220,10 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
214
220
  }
215
221
 
216
222
  function summaryOf(sessions, since, now, plan) {
217
- const total = { sessions: sessions.length, tokens: 0, cost: 0, unpriced: false, tools: {} };
223
+ // waited: 아는 세션의 기다린 시간 합. 아는 세션이 하나도 없으면 null.
224
+ const total = { sessions: sessions.length, tokens: 0, cost: 0, unpriced: false, tools: {}, waited: null };
218
225
  for (const s of sessions) {
226
+ if (s.waited != null) total.waited = (total.waited ?? 0) + s.waited;
219
227
  total.tokens += s.tokens;
220
228
  total.cost += s.cost;
221
229
  if (s.unpriced) total.unpriced = true;
@@ -259,6 +267,8 @@ export function sessionsJson(r, version, { partial = false, prompts = false } =
259
267
  shareBy: s.shareBy,
260
268
  tools: s.tools,
261
269
  plan: s.plan,
270
+ // 기다린 시간 합 (ms, 추정). 모르면 null.
271
+ waitedMs: s.waited,
262
272
  },
263
273
  sessions: r.sessions.map((x) => ({
264
274
  tool: x.tool,
@@ -274,6 +284,8 @@ export function sessionsJson(r, version, { partial = false, prompts = false } =
274
284
  cost: x.cost,
275
285
  unpriced: x.unpriced,
276
286
  files: x.files,
287
+ // 기다린 시간 (ms, 추정). agy 처럼 모르면 null.
288
+ waitedMs: x.waited,
277
289
  ...(prompts ? { prompt: x.prompt } : {}),
278
290
  })),
279
291
  };
@@ -289,6 +301,7 @@ const mdhm = (ms) => {
289
301
  const endText = (x) => (x.end == null ? '-' : x.start != null && dayKey(x.start) === dayKey(x.end) ? hm(new Date(x.end)) : mdhm(x.end));
290
302
  const startText = (x) => (x.start == null ? '-' : mdhm(x.start));
291
303
  const costText = (x) => (used(x) && !(x.unpriced && !(x.cost > 0)) ? money(x.cost) : '-');
304
+ const waitedText = (ms) => (ms == null ? '-' : fmtElapsed(ms));
292
305
  const filesText = (x) => (x.files == null ? '-' : `${x.files}${x.filesMore ? '+' : ''}`);
293
306
  const modelText = (x) => (x.model ? `${x.model}${x.models.length > 1 ? ` +${x.models.length - 1}` : ''}` : '-');
294
307
  const projectText = (x) => (x.project === UNKNOWN ? t('report.unknown') : x.project);
@@ -311,6 +324,7 @@ function cardLines(r, md = false) {
311
324
  const p = s.plan;
312
325
  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
326
  }
327
+ if (s.waited != null) out.push(t('sessions.cardWaited', { waited: b(waitedText(s.waited)) }));
314
328
  return out;
315
329
  }
316
330
 
@@ -318,9 +332,10 @@ function titleOf(r) {
318
332
  return t('sessions.title', { from: `${dayKey(r.since)} 00:00`, to: `${dayKey(r.now)} ${hm(new Date(r.now))}`, days: daysText(r.days) });
319
333
  }
320
334
 
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]);
335
+ // 기다림 칸은 시작·끝 옆에 둔다 (시간끼리). 좁은 터미널에서는 다른 칸처럼 그대로 두고 세션 이름 칸이 줄어든다.
336
+ const HEAD_KEYS = ['tool', 'model', 'project', 'name', 'start', 'end', 'waited', 'tokens', 'cost', 'files'];
337
+ const rowCells = (x) => [x.tool, clean(modelText(x)), clean(projectText(x)), clean(x.name), startText(x), endText(x), waitedText(x.waited), used(x) ? fmtTokens(Math.round(x.tokens)) : '-', costText(x), filesText(x)];
338
+ const RIGHT = new Set([6, 7, 8, 9]);
324
339
  // 칸 폭 상한 (세션 이름은 터미널 폭에 맞춘다).
325
340
  const MAX_W = { 1: 24, 2: 20 };
326
341
  const NAME_MIN = 12;
@@ -9,7 +9,7 @@ import { homedir } from 'node:os';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { openReadOnly, loadSqlite } from '../sqlite.mjs';
11
11
  import { findProcesses, isAgy, openFiles } from '../procs.mjs';
12
- import { addActivity, emptyTokens, mergeActivity, pushEvent, describeTool, toolDetail, isNoisePrompt, MEMBER_FADE_MS } from './common.mjs';
12
+ import { addActivity, emptyTokens, mergeActivity, pushEvent, describeTool, toolDetail, isNoisePrompt, isLongTool, MEMBER_FADE_MS } from './common.mjs';
13
13
  import { contextWindow, geminiCost } from '../pricing.mjs';
14
14
  import { debug, debugIo } from '../log.mjs';
15
15
 
@@ -245,6 +245,8 @@ const fresh = () => ({
245
245
  events: [],
246
246
  turns: [],
247
247
  turnCount: 0,
248
+ // 읽은 단계 가운데 가장 이른 만든 시각 (서브에이전트 경과 시간의 기준).
249
+ firstAt: null,
248
250
  lastTool: null,
249
251
  last: null,
250
252
  // 아직 바뀌는 중인 단계 가운데 가장 뒤의 것 (지금 무엇을 하는지 보이는 데 쓴다).
@@ -426,6 +428,7 @@ function addEvent(n, at, kind, text) {
426
428
 
427
429
  function applyStep(n, s, idx) {
428
430
  if (!s) return;
431
+ if (s.at && (n.firstAt == null || s.at < n.firstAt)) n.firstAt = s.at;
429
432
  const at = s.at ? new Date(s.at).toISOString() : null;
430
433
  if (s.type === STEP.PROMPT) {
431
434
  if (s.text && !isNoisePrompt(s.text)) {
@@ -599,22 +602,28 @@ export function matchLive(procs, rows, filesOf = openFiles, dir = AGY_ROOT) {
599
602
  return { live, loose };
600
603
  }
601
604
 
602
- function member(r, g) {
605
+ // wait: 이 서브에이전트가 허락을 기다리는 도구 (subWait 가 정한다). 기다리면 상태를 'waiting' 으로 두고 무엇을 기다리는지 보인다.
606
+ function member(r, g, wait = null) {
603
607
  return {
604
608
  id: r.id,
605
609
  name: r.agent || 'agent',
606
610
  model: g.model,
607
611
  task: r.title ?? '',
608
- status: r.running ? 'busy' : 'done',
612
+ status: wait ? 'waiting' : r.running ? 'busy' : 'done',
609
613
  started: g.tokens.total > 0,
610
- phase: r.running ? { kind: 'think', msg: 'steps', args: { n: r.steps } } : { kind: 'done' },
614
+ phase: wait ? { kind: 'waiting', args: { what: wait } } : r.running ? { kind: 'think', msg: 'steps', args: { n: r.steps } } : { kind: 'done' },
611
615
  now: '',
612
616
  tokens: g.tokens.total,
613
617
  cost: g.cost,
614
618
  costNoCache: g.costNoCache,
615
619
  costUnknown: g.costUnknown,
616
- // 기록에 시작 시각이 없어 마지막으로 바뀐 시각을 둔다 (정렬용).
620
+ // 대화 목록에는 시작 시각이 없어 마지막으로 바뀐 시각을 둔다 (정렬용).
617
621
  updatedAt: r.updatedAt,
622
+ // 경과 시간의 기준은 읽은 단계 가운데 가장 이른 만든 시각, 멈춘 듯 판단은 대화 목록의 마지막 수정 시각이다.
623
+ startedAt: g.firstAt ?? null,
624
+ lastActivityAt: r.updatedAt ?? null,
625
+ // 실행 중인 단계가 run_command 처럼 오래 걸릴 수 있는 도구면 멈춘 듯 기준을 길게 잡는다 (common.mjs).
626
+ longStep: Boolean(r.running && g.open?.type === STEP.TOOL && isLongTool(g.open.tool?.name)),
618
627
  };
619
628
  }
620
629
 
@@ -638,13 +647,22 @@ export function waitingFor(g) {
638
647
  return w.what;
639
648
  }
640
649
 
650
+ // 서브에이전트가 허락을 기다리는지. 부모와 같은 규칙(waitingFor: steps status 9, 본 뒤 -wal 이 바뀌면 대기 아님)을 쓴다.
651
+ // 부모 세션이 살아 있고 서브에이전트 자신도 아직 실행 중(r.running)일 때만 센다. 끝난 서브에이전트에 남은 9 는
652
+ // 허락 없이 끝난 흔적이라 무시한다.
653
+ export function subWait(parentLive, r, g) {
654
+ if (!parentLive || !r.running) return null;
655
+ return waitingFor(g);
656
+ }
657
+
641
658
  // 실행 중일 때는 아직 바뀌는 중인 단계, 없으면 마지막으로 끝난 단계로 지금 할 일을 짐작한다.
642
659
  // 끝난 답변이 도구 호출을 냈으면 그 도구를 실행할 차례이고, 끝난 도구 호출 뒤에는 모델이 결과를 읽고 생각한다.
643
- export function phaseOf(live, r, g, runningMembers = 0) {
660
+ // kidWait: 부모가 기다리지 않을 때 대신 보일 서브에이전트의 허락 대기 문구 (collectAgy 가 정한다).
661
+ export function phaseOf(live, r, g, runningMembers = 0, kidWait = null) {
644
662
  if (!live) return { kind: 'ended' };
645
663
  // 같이 도는 에이전트 수는 args.agents 로 보내고, 화면이 문구 뒤에 붙인다.
646
664
  const extra = runningMembers ? { agents: runningMembers } : {};
647
- const wait = waitingFor(g);
665
+ const wait = waitingFor(g) ?? kidWait;
648
666
  if (wait) return { kind: 'waiting', args: { what: wait, ...extra } };
649
667
  if (!r.running) return { kind: 'idle' };
650
668
  // 바뀌는 중인 단계와 끝난 단계 가운데 더 뒤의 것이 지금 하는 일이다 (앞의 명령이 오래 도는 동안 뒤 단계가 이어질 수 있다).
@@ -659,6 +677,18 @@ export function phaseOf(live, r, g, runningMembers = 0) {
659
677
  return runningMembers ? { ...p, args: { ...p.args, ...extra } } : p;
660
678
  }
661
679
 
680
+ // phaseOf 가 '도구 실행' 으로 보이는 단계가 아직 바뀌는 중인 도구 단계(steps status 2)면 그 단계를 만든 시각(ms), 아니면 null.
681
+ // 답변이 낸 도구 호출만 있고 도구 단계가 아직 없을 때(실행할 차례)는 시작 시각을 모르므로 null.
682
+ // 허락 대기(status 9)를 본 단계면(g.resume, collectAgy 가 적는다) 대기를 마지막으로 본 시각부터 잰다.
683
+ export function toolStartOf(phase, g) {
684
+ if (phase?.kind !== 'tool') return null;
685
+ const s = g.open;
686
+ const open = s && (!g.last || (s.idx ?? Infinity) > (g.last.idx ?? -1));
687
+ if (!open || s.type !== STEP.TOOL || !Number.isFinite(s.at)) return null;
688
+ const resumed = g.resume?.idx === s.idx ? g.resume.at : null;
689
+ return Number.isFinite(resumed) ? Math.max(s.at, resumed) : s.at;
690
+ }
691
+
662
692
  function placeholder(p, msg) {
663
693
  return {
664
694
  tool: 'gemini',
@@ -708,10 +738,11 @@ export function collectAgy({ showEnded, budget }) {
708
738
  const kids = children.get(r.id) ?? [];
709
739
  // 서브에이전트 기록은 한 번만 읽어 행과 합계가 같은 값을 쓰게 한다.
710
740
  const kidUsage = kids.map((c) => readConversation(c.id, budget));
741
+ const kidWaits = kids.map((c, i) => subWait(isLive, c, kidUsage[i]));
711
742
  // 끝난 서브에이전트는 Claude 팀원처럼 잠시 "완료"로 보였다가 행에서 빠진다. 합계에는 그대로 남는다.
712
743
  const members = kids
713
- .map((c, i) => member(c, kidUsage[i]))
714
- .filter((m) => m.status === 'busy' || (m.updatedAt != null && Date.now() - m.updatedAt <= MEMBER_FADE_MS))
744
+ .map((c, i) => member(c, kidUsage[i], kidWaits[i]))
745
+ .filter((m) => m.status !== 'done' || (m.updatedAt != null && Date.now() - m.updatedAt <= MEMBER_FADE_MS))
715
746
  .sort((a, b) => (a.updatedAt ?? 0) - (b.updatedAt ?? 0));
716
747
  // 메인과 서브에이전트를 항목별로 더한다 (Claude 세션과 같은 방식).
717
748
  const tokens = { ...g.tokens, main: g.tokens.total, sub: 0, subCount: kids.length };
@@ -726,8 +757,26 @@ export function collectAgy({ showEnded, budget }) {
726
757
  costNoCache += u.costNoCache;
727
758
  costUnknown ||= u.costUnknown;
728
759
  }
729
- const running = members.filter((m) => m.status === 'busy').length;
730
- const wait = isLive ? waitingFor(g) : null;
760
+ // 허락을 기다리는 서브에이전트도 아직 끝나지 않았으니 같이 도는 에이전트로 센다.
761
+ const running = members.filter((m) => m.status !== 'done').length;
762
+ // 부모 행의 대기 규칙:
763
+ // 1. 부모 대화가 허락을 기다리면 그것을 보인다. 부모와 서브가 함께 기다려도 부모 것이 먼저다.
764
+ // 2. 아니면 기다리는 서브에이전트 가운데 가장 오래 기다린 것(마지막으로 바뀐 시각이 가장 이른 것)을 '이름: 도구' 로 보인다.
765
+ // 나머지 서브에이전트의 대기는 각자의 팀원 행에 보인다.
766
+ // 대기 정렬·--notify·--line·summary.json 은 세션의 status·waitingFor·waitSince 를 쓰므로 이것으로 함께 바뀐다.
767
+ const own = isLive ? waitingFor(g) : null;
768
+ // 허락 대기를 본 도구 단계와 그 시각. 허락한 뒤의 실행 경과 시간은 여기서부터 잰다 (toolStartOf).
769
+ if (own) g.resume = { idx: g.wait.idx, at: Date.now() };
770
+ let kidIdx = -1;
771
+ if (!own) {
772
+ for (let i = 0; i < kids.length; i++) {
773
+ if (kidWaits[i] && (kidIdx < 0 || (kids[i].updatedAt ?? Infinity) < (kids[kidIdx].updatedAt ?? Infinity))) kidIdx = i;
774
+ }
775
+ }
776
+ const kidWait = kidIdx >= 0 ? `${kids[kidIdx].agent || 'agent'}: ${kidWaits[kidIdx]}` : null;
777
+ const wait = own ?? kidWait;
778
+ const phase = phaseOf(isLive, r, g, running, kidWait);
779
+ const waitDetail = own ? (g.wait.detail ?? own) : kidWait ? (kidUsage[kidIdx].wait?.detail ?? kidWaits[kidIdx]) : null;
731
780
  out.push({
732
781
  tool: 'gemini',
733
782
  id: r.id,
@@ -740,17 +789,19 @@ export function collectAgy({ showEnded, budget }) {
740
789
  model: g.model,
741
790
  live: isLive,
742
791
  status: !isLive ? 'ended' : wait ? 'waiting' : r.running ? 'busy' : 'idle',
743
- phase: phaseOf(isLive, r, g, running),
792
+ phase,
793
+ // 지금 도는 도구 단계가 시작된 시각(ms) 또는 null (toolStartOf).
794
+ toolStartedAt: wait ? null : toolStartOf(phase, g),
744
795
  cost,
745
796
  costNoCache,
746
797
  costUnknown,
747
798
  waitingFor: wait,
748
- waitDetail: wait ? (g.wait.detail ?? wait) : null,
799
+ waitDetail,
749
800
  now: g.lastTool ?? g.events.at(-1)?.text ?? '',
750
801
  startedAt: null,
751
802
  updatedAt: r.updatedAt ?? Date.now(),
752
803
  // 대기 시작 시각 (--line 요약용). 기록에 시각이 없으면 지금 시각으로 메우지 않고 null.
753
- waitSince: wait ? (r.updatedAt ?? null) : null,
804
+ waitSince: own ? (r.updatedAt ?? null) : kidWait ? (kids[kidIdx].updatedAt ?? null) : null,
754
805
  tokens,
755
806
  context: { used: g.prompt, window: contextWindow(g.model, g.prompt) },
756
807
  events: g.events,