@sejuneoh/aitop 0.33.2 → 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/src/trace.mjs ADDED
@@ -0,0 +1,659 @@
1
+ // aitop --report trace <세션>: 세션 하나의 호출 트리 (#258). 지시 → 도구 호출·응답 → 서브에이전트 가지마다 시간·토큰·추정 비용을 붙인다.
2
+ // build(lines, opts) 는 파일을 읽지 않는 순수 함수다 (나중에 상세 화면에서 증분으로 다시 쓰기 위해). 읽기는 readTrace, 찾기는 findTrace 가 한다.
3
+ // 비용 규칙: 응답(API 호출) 한 번의 비용은 그 응답이 부른 도구들이 똑같이 나눠 갖는다 (도구를 부르기로 한 호출의 몫).
4
+ // 도구를 부르지 않은 응답은 '응답' 줄로 남는다. 서브에이전트(Agent·Task) 줄의 비용은 그 가지 전체(서브에이전트 기록 포함) 합이다.
5
+ // Codex·agy 는 아직 트리를 만들지 않는다 (findTrace 가 도구만 알려 주고 bin 이 미지원으로 알린다).
6
+ // 실시간 tracker·캐시는 쓰지 않는다. 기록 파일을 한 번 스트림으로 읽을 뿐, 디스크에 쓰지 않는다.
7
+ import { createReadStream, existsSync, openSync, readSync, closeSync, readdirSync, readFileSync, statSync } from 'node:fs';
8
+ import { createInterface } from 'node:readline';
9
+ import { basename, join, resolve } from 'node:path';
10
+ import { t } from './i18n.mjs';
11
+ import { claudeCost } from './pricing.mjs';
12
+ import { fmtElapsed, fmtTokens, mask, maskStrict, oneLine, pad, stripControl, truncate, width } from './text.mjs';
13
+ import { money } from './line.mjs';
14
+ import { glyphs } from './ui/glyphs.mjs';
15
+ import { isNoisePrompt, sessionName, toolDetail } from './sources/common.mjs';
16
+
17
+ // 노드 수 상한 (묶고 접은 뒤). 넘으면 오래된 지시부터 뺀다.
18
+ export const MAX_NODES = 300;
19
+ // 기본으로 펼치는 깊이. 지시가 0, 그 아래 도구가 1, 서브에이전트 안 도구가 2. 더 깊은 것은 접고 수만 남긴다.
20
+ export const DEPTH = 2;
21
+ // 출력 폭 (80열 기준). 좁은 터미널에서는 그 폭, 최소 MIN_COLS.
22
+ export const COLS = 80;
23
+ const MIN_COLS = 50;
24
+ const AGENT_TOOLS = new Set(['Agent', 'Task']);
25
+ // 이 시간 넘게 기록이 바뀌지 않았으면 끝난 세션으로 보고, 결과 없는 도구를 진행 중이 아니라 결과 없음으로 둔다.
26
+ // 실시간 화면이 서브에이전트를 실행 중으로 보지 않는 기준(claude.mjs 의 MEMBER_STALE_MS)과 같다.
27
+ export const STALE_MS = 15 * 60_000;
28
+ // 지시 글·서브에이전트 설명의 최대 길이 (화면은 칸에 맞춰 더 자르고, --json 은 이 길이까지).
29
+ const TEXT_MAX = 500;
30
+ // 읽을 때 남길 사용자 줄 글의 길이 (지시 판정과 지시 글에 충분한 만큼).
31
+ const KEEP_TEXT = 2000;
32
+
33
+ const timeOf = (ts) => {
34
+ const v = ts ? Date.parse(ts) : NaN;
35
+ return Number.isFinite(v) ? v : null;
36
+ };
37
+ const tokensOf = (u) => (u ? (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) : 0);
38
+ // 기록에서 온 글: 제어문자를 지우고 한 줄로, 비밀값을 가린다.
39
+ const clean = (s) => mask(oneLine(stripControl(String(s ?? ''))));
40
+ // 옵트인으로 내보내는 글(지시 글, 서브에이전트 설명): 도구 인자(toolDetail)와 같은 maskStrict 로 가리고 TEXT_MAX 에서 자른다.
41
+ const argText = (s) => {
42
+ if (s == null) return null;
43
+ const v = maskStrict(oneLine(stripControl(String(s)))).trim();
44
+ if (!v) return null;
45
+ return v.length > TEXT_MAX ? v.slice(0, TEXT_MAX - 1) + '…' : v;
46
+ };
47
+
48
+ function node(kind, id, name, start) {
49
+ return { id, kind, name, start, end: null, status: kind === 'prompt' || kind === 'turn' ? 'done' : 'running', tokens: 0, cost: 0, children: [] };
50
+ }
51
+
52
+ // 기록 하나(메인 또는 서브에이전트)를 따라가며 노드를 만든다. top: 메인이면 사용자 지시마다 prompt 노드를 연다.
53
+ // 돌려주는 값: { list: 맨 위 노드들(메인은 prompt, 서브에이전트는 도구·응답), first, last }.
54
+ function walk(lines, ctx, top) {
55
+ const list = [];
56
+ let cur = null;
57
+ let first = null;
58
+ let last = null;
59
+ let model = null;
60
+ const turns = new Map();
61
+ // 지시 앞에 나온 줄(이어 시작한 세션 등)은 번호 0 의 빈 지시에 둔다.
62
+ const holder = () => {
63
+ if (!top) return list;
64
+ if (!cur) {
65
+ cur = Object.assign(node('prompt', 'p0', 'prompt', null), { n: 0 });
66
+ list.push(cur);
67
+ }
68
+ return cur.children;
69
+ };
70
+ for (const raw of lines) {
71
+ let x = raw;
72
+ if (typeof x === 'string') {
73
+ try {
74
+ x = JSON.parse(x);
75
+ } catch {
76
+ continue;
77
+ }
78
+ }
79
+ if (!x || typeof x !== 'object') continue;
80
+ // 예전 Claude Code 는 서브에이전트 줄을 메인 기록에 isSidechain 으로 섞었다. 부모를 알 수 없어 메인 트리에서는 뺀다.
81
+ if (top && x.isSidechain) continue;
82
+ const at = timeOf(x.timestamp);
83
+ if (at != null) {
84
+ first ??= at;
85
+ last = at;
86
+ }
87
+ if (x.isMeta || !x.message) continue;
88
+ if (x.type === 'assistant') {
89
+ const m = x.message;
90
+ if (m.model && !String(m.model).startsWith('<')) model = m.model;
91
+ const id = m.id ?? `m${ctx.seq++}`;
92
+ let turn = turns.get(id);
93
+ if (!turn) {
94
+ turn = node('turn', id, 'reply', at);
95
+ turns.set(id, turn);
96
+ holder().push(turn);
97
+ }
98
+ turn.end = at ?? turn.end;
99
+ // 같은 message.id 가 블록마다 반복되므로 마지막 usage 를 쓴다. id 가 없으면 세지 않는다 (claude-tracker.mjs addUsage 와 같은 규칙).
100
+ if (m.usage && m.id) {
101
+ turn.usage = m.usage;
102
+ turn.model = m.model ?? model;
103
+ }
104
+ for (const c of Array.isArray(m.content) ? m.content : []) {
105
+ if (c?.type !== 'tool_use') continue;
106
+ const agent = AGENT_TOOLS.has(c.name);
107
+ const n = node(agent ? 'agent' : 'tool', String(c.id ?? `u${ctx.seq++}`), String(c.name ?? '?'), at);
108
+ if (agent) n.agent = c.input?.subagent_type ?? null;
109
+ if (ctx.showArgs) n.detail = agent ? argText(c.input?.description) : toolDetail(c.name, c.input);
110
+ if (ctx.waiting?.has(n.id)) n.status = 'waiting';
111
+ turn.children.push(n);
112
+ ctx.tools.set(n.id, n);
113
+ }
114
+ } else if (x.type === 'user') {
115
+ const c = x.message.content;
116
+ if (Array.isArray(c)) {
117
+ for (const p of c) {
118
+ if (p?.type !== 'tool_result') continue;
119
+ const n = ctx.tools.get(p.tool_use_id);
120
+ if (!n) continue;
121
+ n.end = at;
122
+ n.status = p.is_error ? 'error' : 'done';
123
+ }
124
+ }
125
+ const text = typeof c === 'string' ? c : Array.isArray(c) ? c.filter((p) => p?.type === 'text').map((p) => p.text).join(' ') : '';
126
+ if (top && text && !isNoisePrompt(text)) {
127
+ cur = node('prompt', `p${ctx.prompts + 1}`, 'prompt', at);
128
+ cur.n = ++ctx.prompts;
129
+ if (ctx.showArgs) cur.text = argText(text);
130
+ list.push(cur);
131
+ }
132
+ }
133
+ if (top && cur && at != null) cur.end = at;
134
+ }
135
+ // 응답 비용을 매기고, 도구를 부른 응답은 그 도구들로 바꾼다 (비용은 도구 수로 나눈다).
136
+ const settle = (arr) => {
137
+ const out = [];
138
+ for (const n of arr) {
139
+ if (n.kind === 'prompt') {
140
+ n.children = settle(n.children);
141
+ out.push(n);
142
+ continue;
143
+ }
144
+ const tok = tokensOf(n.usage);
145
+ const price = n.usage ? claudeCost(n.model, n.usage) : null;
146
+ const unpriced = !price && tok > 0;
147
+ const cost = price?.total ?? 0;
148
+ delete n.usage;
149
+ delete n.model;
150
+ if (!n.children.length) {
151
+ Object.assign(n, { tokens: tok, cost, ...(unpriced ? { unpriced: true } : {}) });
152
+ out.push(n);
153
+ continue;
154
+ }
155
+ const k = n.children.length;
156
+ for (const c of n.children) {
157
+ Object.assign(c, { tokens: tok / k, cost: cost / k, ...(unpriced ? { unpriced: true } : {}) });
158
+ c.children = [];
159
+ out.push(c);
160
+ }
161
+ }
162
+ return out;
163
+ };
164
+ return { list: settle(list), first, last };
165
+ }
166
+
167
+ // 서브에이전트 기록을 Agent·Task 노드(meta.toolUseId 와 같은 tool_use id)의 자식으로 붙인다. 서브에이전트 안의 Agent 도 같은 방법으로 따라간다.
168
+ function attach(nodes, ctx, seen) {
169
+ for (const n of nodes) {
170
+ if (n.kind === 'agent') {
171
+ const sub = ctx.subs.get(n.id);
172
+ if (sub && !seen.has(sub)) {
173
+ seen.add(sub);
174
+ const w = walk(sub.lines ?? [], ctx, false);
175
+ n.children = w.list;
176
+ n.agent ??= sub.meta?.agentType ?? null;
177
+ if (ctx.showArgs) n.detail ??= argText(sub.meta?.description);
178
+ n.linked = true;
179
+ }
180
+ }
181
+ attach(n.children, ctx, seen);
182
+ }
183
+ }
184
+
185
+ // 결과가 없는 도구: 마지막 지시 안이고 부모 가지가 끝나지 않았으면 진행 중, 아니면 결과를 잃은 것(끊김)으로 실패.
186
+ function finish(nodes, open) {
187
+ for (const n of nodes) {
188
+ if ((n.kind === 'tool' || n.kind === 'agent') && n.end == null && n.status !== 'waiting' && !open) {
189
+ n.status = 'error';
190
+ n.lost = true;
191
+ }
192
+ finish(n.children, open && !((n.kind === 'agent' || n.kind === 'tool') && n.end != null));
193
+ }
194
+ }
195
+
196
+ // 가지 합계: tokens·cost 는 자기 몫 + 자식 합. 상태는 진행 중 > 대기 > 실패 순으로 위로 올린다 (지시만).
197
+ function total(n) {
198
+ for (const c of n.children) {
199
+ total(c);
200
+ n.tokens += c.tokens;
201
+ n.cost += c.cost;
202
+ if (c.unpriced) n.unpriced = true;
203
+ }
204
+ if (n.kind === 'prompt') {
205
+ const st = new Set(n.children.map((c) => c.status));
206
+ n.status = st.has('running') ? 'running' : st.has('waiting') ? 'waiting' : 'done';
207
+ }
208
+ }
209
+
210
+ // 이어진 같은 이름의 도구(자식 없는 것)를 한 줄로 묶는다: "Grep ×38". 응답 줄끼리도 묶는다.
211
+ function group(nodes) {
212
+ const out = [];
213
+ for (const n of nodes) {
214
+ n.children = group(n.children);
215
+ const prev = out.at(-1);
216
+ const same = prev && (n.kind === 'tool' || n.kind === 'turn') && prev.kind === n.kind && prev.name === n.name && !n.children.length && !prev.children.length;
217
+ if (!same) {
218
+ out.push(n);
219
+ continue;
220
+ }
221
+ if (!prev.count) {
222
+ prev.count = 1;
223
+ prev.errors = prev.status === 'error' ? 1 : 0;
224
+ prev.ids = [prev.id];
225
+ delete prev.detail;
226
+ }
227
+ prev.count++;
228
+ prev.ids.push(n.id);
229
+ if (n.status === 'error') prev.errors++;
230
+ if (n.lost) prev.lost = true;
231
+ prev.tokens += n.tokens;
232
+ prev.cost += n.cost;
233
+ if (n.unpriced) prev.unpriced = true;
234
+ // 묶음의 끝: 모두 끝났으면 가장 늦은 끝, 하나라도 끝나지 않았으면 모름.
235
+ prev.end = prev.end != null && n.end != null ? Math.max(prev.end, n.end) : null;
236
+ const rank = { running: 3, waiting: 2, error: 1, done: 0 };
237
+ if (rank[n.status] > rank[prev.status]) prev.status = n.status;
238
+ }
239
+ return out;
240
+ }
241
+
242
+ const countAll = (nodes) => nodes.reduce((a, n) => a + 1 + countAll(n.children), 0);
243
+
244
+ // depth 보다 깊은 노드는 접는다: 자식을 지우고 숨긴 노드 수를 folded 에 남긴다.
245
+ function fold(nodes, depth, d = 0) {
246
+ for (const n of nodes) {
247
+ if (d >= depth && n.children.length) {
248
+ n.folded = countAll(n.children);
249
+ n.children = [];
250
+ } else fold(n.children, depth, d + 1);
251
+ }
252
+ }
253
+
254
+ // 노드 수 상한: 어느 깊이든 전체 노드 수가 max 를 넘지 않게 한다. 최근 것부터 남기고, 자리가 모자라면 앞쪽 형제를 빼고
255
+ // 그 부모에 뺀 수(omitted)를 남긴다. 맨 위(지시 목록)에서 뺀 지시 수는 돌려준다.
256
+ function trim(n, budget) {
257
+ let left = budget - 1;
258
+ const kept = [];
259
+ let i = n.children.length - 1;
260
+ for (; i >= 0 && left > 0; i--) {
261
+ left -= trim(n.children[i], left);
262
+ kept.unshift(n.children[i]);
263
+ }
264
+ if (i >= 0) {
265
+ n.omitted = (n.omitted ?? 0) + i + 1;
266
+ n.children = kept;
267
+ }
268
+ return budget - left;
269
+ }
270
+
271
+ function cap(prompts, max) {
272
+ const root = { children: prompts };
273
+ trim(root, max + 1);
274
+ prompts.splice(0, prompts.length, ...root.children);
275
+ return root.omitted ?? 0;
276
+ }
277
+
278
+ const walkAll = (nodes, f) => {
279
+ for (const n of nodes) {
280
+ f(n);
281
+ walkAll(n.children, f);
282
+ }
283
+ };
284
+
285
+ // 기록 줄들 → 호출 트리. lines: 메인 기록의 줄(객체 또는 JSON 문자열). opts:
286
+ // subagents: [{ meta, lines }] (meta 는 subagents/agent-<id>.meta.json, toolUseId 로 부모 Agent·Task 호출에 붙는다)
287
+ // showArgs: 도구 인자(detail)·지시 글(text)을 넣을지 (기본 false, 넣을 때도 비밀값을 가린다)
288
+ // maxNodes, depth, group(false 면 묶지 않음), waiting(허락 대기 중인 tool_use id 집합: 기록만으로는 알 수 없어 밖에서 준다)
289
+ // ended: 세션이 끝났는지 (readTrace 의 mtime 이 STALE_MS 보다 오래됐으면). 끝났으면 결과 없는 도구는 진행 중이 아니라 결과 없음.
290
+ // 돌려주는 값: { tool, start, end, tokens, cost, unpriced, counts, omitted, nodes }. nodes 는 지시(prompt) 목록이다.
291
+ export function build(lines, opts = {}) {
292
+ const { subagents = [], showArgs = false, maxNodes = MAX_NODES, depth = DEPTH, waiting = null, ended = false } = opts;
293
+ const ctx = { seq: 0, prompts: 0, tools: new Map(), subs: new Map(), showArgs, waiting: waiting ? new Set(waiting) : null };
294
+ for (const s of subagents) if (s?.meta?.toolUseId) ctx.subs.set(String(s.meta.toolUseId), s);
295
+ const w = walk(lines, ctx, true);
296
+ const prompts = w.list;
297
+ attach(prompts, ctx, new Set());
298
+ // 부모 호출을 찾지 못한 서브에이전트는 시작 시각이 들어가는 지시 끝에 붙인다.
299
+ const used = new Set();
300
+ walkAll(prompts, (n) => n.linked && used.add(n.id));
301
+ for (const s of subagents) {
302
+ const id = String(s?.meta?.toolUseId ?? '');
303
+ if (id && used.has(id)) continue;
304
+ const sw = walk(s?.lines ?? [], ctx, false);
305
+ if (!sw.list.length) continue;
306
+ const a = node('agent', id || `a${ctx.seq++}`, 'Agent', sw.first);
307
+ Object.assign(a, { agent: s?.meta?.agentType ?? null, children: sw.list, end: sw.last, status: 'done' });
308
+ if (showArgs) a.detail = argText(s?.meta?.description);
309
+ let home = prompts.filter((p) => p.start != null && sw.first != null && p.start <= sw.first).at(-1) ?? prompts[0];
310
+ if (!home) prompts.push((home = Object.assign(node('prompt', 'p0', 'prompt', sw.first), { n: 0 })));
311
+ home.children.push(a);
312
+ }
313
+ const lastPrompt = prompts.at(-1);
314
+ for (const p of prompts) finish(p.children, p === lastPrompt && !ended);
315
+ const root = { kind: 'root', tokens: 0, cost: 0, children: prompts };
316
+ total(root);
317
+ const counts = { prompts: ctx.prompts, tools: 0, agents: 0, errors: 0, running: 0 };
318
+ walkAll(prompts, (n) => {
319
+ if (n.kind === 'tool' || n.kind === 'agent') counts.tools++;
320
+ if (n.kind === 'agent') counts.agents++;
321
+ if (n.status === 'error') counts.errors++;
322
+ if ((n.kind === 'tool' || n.kind === 'agent') && n.status === 'running') counts.running++;
323
+ });
324
+ let nodes = opts.group === false ? prompts : group(prompts);
325
+ fold(nodes, depth);
326
+ const omitted = cap(nodes, Math.max(1, maxNodes));
327
+ // linked 는 안에서만 쓴다.
328
+ walkAll(nodes, (n) => delete n.linked);
329
+ return { tool: 'claude', start: w.first, end: w.last, tokens: root.tokens, cost: root.cost, unpriced: Boolean(root.unpriced), counts, omitted, nodes };
330
+ }
331
+
332
+ // ---- 찾기와 읽기 (I/O) ----
333
+
334
+ const HEAD_BYTES = 256 * 1024;
335
+ // 이름으로 찾을 때 볼 최근 기록 수 (기록이 수천 개여도 오래 걸리지 않게).
336
+ const NAME_SCAN = 300;
337
+
338
+ function list(dir) {
339
+ try {
340
+ return readdirSync(dir);
341
+ } catch {
342
+ return [];
343
+ }
344
+ }
345
+ const mtimeOf = (p) => {
346
+ try {
347
+ return statSync(p).mtimeMs;
348
+ } catch {
349
+ return 0;
350
+ }
351
+ };
352
+
353
+ // 기록 앞부분의 ai-title 과 뒤쪽의 마지막 custom-title(/rename). 이름으로 찾을 때와 머리글에 쓴다.
354
+ export function claudeNames(path) {
355
+ let title = null;
356
+ let custom = null;
357
+ try {
358
+ const fd = openSync(path, 'r');
359
+ try {
360
+ const size = statSync(path).size;
361
+ for (const start of size > HEAD_BYTES ? [0, size - HEAD_BYTES] : [0]) {
362
+ const buf = Buffer.alloc(Math.min(HEAD_BYTES, size));
363
+ const text = buf.toString('utf8', 0, readSync(fd, buf, 0, buf.length, start));
364
+ for (const l of text.split('\n')) {
365
+ if (!l.includes('"ai-title"') && !l.includes('"custom-title"')) continue;
366
+ try {
367
+ const x = JSON.parse(l);
368
+ if (x.type === 'ai-title' && x.aiTitle) title = sessionName(x.aiTitle);
369
+ if (x.type === 'custom-title') custom = sessionName(x.customTitle);
370
+ } catch {}
371
+ }
372
+ }
373
+ } finally {
374
+ closeSync(fd);
375
+ }
376
+ } catch {}
377
+ return { title, custom, name: custom ?? title };
378
+ }
379
+
380
+ // 세션 찾기. query: 기록 파일 경로, 세션 id(앞부분도 됨, 대소문자 무시), 또는 세션 이름(/rename 이름·제목, 일부도 됨).
381
+ // id 는 aitop --json 의 id·이어 열기 명령(resume.mjs)이 쓰는 값과 같다: Claude 는 기록 파일 이름의 UUID, Codex 는 rollout 파일 이름 끝의 UUID, agy 는 대화 id.
382
+ // 돌려주는 값: { tool, path, id, name } 또는 { error: 'none'|'many', candidates }.
383
+ export async function findTrace(query, { claudeRoots, codexRoots, agyRoot } = {}) {
384
+ const q = String(query ?? '').trim();
385
+ if (!q) return { error: 'none', candidates: [] };
386
+ if (claudeRoots == null || codexRoots == null) {
387
+ const d = await import('./sources/dirs.mjs');
388
+ claudeRoots ??= d.claudeProjectRoots();
389
+ codexRoots ??= d.codexSessionRoots();
390
+ }
391
+ if (agyRoot == null) agyRoot = (await import('./sources/antigravity.mjs')).AGY_ROOT;
392
+ // 1) 파일 경로
393
+ if (/\.(jsonl|db)$/i.test(q) && existsSync(q)) {
394
+ const p = resolve(q);
395
+ const name = basename(p);
396
+ if (/\.db$/i.test(name)) return { tool: 'agy', path: p, id: name.slice(0, -3), name: null };
397
+ if (/^rollout-/.test(name)) return { tool: 'codex', path: p, id: name.slice(0, -6), name: null };
398
+ return { tool: 'claude', path: p, id: name.slice(0, -6), name: claudeNames(p).name };
399
+ }
400
+ const low = q.toLowerCase();
401
+ const found = [];
402
+ // 2) id: Claude 기록 (projects/<폴더>/<id>.jsonl, 같은 id 가 여러 폴더에 있으면 최근 것 하나)
403
+ const claude = [];
404
+ for (const root of claudeRoots) {
405
+ for (const dir of list(root)) {
406
+ for (const f of list(join(root, dir))) {
407
+ if (!f.endsWith('.jsonl')) continue;
408
+ claude.push({ tool: 'claude', id: f.slice(0, -6), path: join(root, dir, f) });
409
+ }
410
+ }
411
+ }
412
+ const byId = new Map();
413
+ for (const c of claude) {
414
+ if (!c.id.toLowerCase().startsWith(low)) continue;
415
+ c.mtime = mtimeOf(c.path);
416
+ const prev = byId.get(c.id);
417
+ if (!prev || c.mtime > prev.mtime) byId.set(c.id, c);
418
+ }
419
+ found.push(...byId.values());
420
+ // Codex: sessions/YYYY/MM/DD/rollout-...-<uuid>.jsonl
421
+ const digits = (p) => list(p).filter((n) => /^\d+$/.test(n)).map((n) => join(p, n));
422
+ for (const root of codexRoots) {
423
+ for (const y of digits(root))
424
+ for (const m of digits(y))
425
+ for (const d of digits(m))
426
+ for (const f of list(d)) {
427
+ const u = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(f)?.[1];
428
+ if (u && u.toLowerCase().startsWith(low)) found.push({ tool: 'codex', id: u, path: join(d, f), mtime: mtimeOf(join(d, f)) });
429
+ }
430
+ }
431
+ // agy: conversations/<id>.db
432
+ for (const f of list(join(agyRoot, 'conversations'))) {
433
+ if (f.endsWith('.db') && f.toLowerCase().startsWith(low)) found.push({ tool: 'agy', id: f.slice(0, -3), path: join(agyRoot, 'conversations', f), mtime: mtimeOf(join(agyRoot, 'conversations', f)) });
434
+ }
435
+ // 3) 이름: 최근 Claude 기록의 /rename 이름·제목. 순서: id 가 똑같은 것 > 이름이 똑같은 것 > id 앞부분 > 이름에 들어 있는 것.
436
+ // id 가 똑같거나 id 앞부분으로 하나가 정해지면 이름을 읽지 않는다 (최근 기록 300개를 읽는 비용을 아낀다). 이름은 많아야 한 번 읽는다.
437
+ const exact = found.filter((c) => c.id.toLowerCase() === low);
438
+ let pick = exact.length === 1 ? exact : found.length === 1 ? found : [];
439
+ if (!pick.length) {
440
+ for (const c of claude) c.mtime ??= mtimeOf(c.path);
441
+ const recent = claude.sort((a, b) => b.mtime - a.mtime).slice(0, NAME_SCAN);
442
+ const named = [];
443
+ for (const c of recent) {
444
+ const n = claudeNames(c.path).name;
445
+ if (n && n.toLowerCase().includes(low)) named.push({ ...c, name: n });
446
+ }
447
+ const same = named.filter((c) => c.name.toLowerCase() === low);
448
+ pick = same.length ? same : found.length ? found : named;
449
+ }
450
+ pick.sort((a, b) => b.mtime - a.mtime);
451
+ if (pick.length === 1) {
452
+ const c = pick[0];
453
+ return { tool: c.tool, path: c.path, id: c.id, name: c.name ?? (c.tool === 'claude' ? claudeNames(c.path).name : null) };
454
+ }
455
+ if (!pick.length) return { error: 'none', candidates: [] };
456
+ return { error: 'many', candidates: pick.slice(0, 5).map((c) => ({ tool: c.tool, id: c.id, name: c.name ?? (c.tool === 'claude' ? claudeNames(c.path).name : null), mtime: c.mtime })) };
457
+ }
458
+
459
+ // 줄 하나에서 build 가 쓰는 필드만 남긴다. 도구 결과 본문·이미지·응답 글은 버려 큰 기록에서도 메모리를 적게 쓴다.
460
+ // 도구 인자(input)는 showArgs 일 때만 남긴다 (서브에이전트 종류·설명만 늘 남긴다).
461
+ export function slim(x, showArgs = false) {
462
+ if (!x || typeof x !== 'object') return null;
463
+ const out = { type: x.type, timestamp: x.timestamp };
464
+ if (x.isSidechain) out.isSidechain = true;
465
+ if (x.isMeta) out.isMeta = true;
466
+ const m = x.message;
467
+ if (!m || typeof m !== 'object' || (x.type !== 'assistant' && x.type !== 'user')) return out;
468
+ const cut = (v) => (typeof v === 'string' ? v.slice(0, KEEP_TEXT) : '');
469
+ let content;
470
+ if (typeof m.content === 'string') content = cut(m.content);
471
+ else if (Array.isArray(m.content)) {
472
+ content = [];
473
+ for (const c of m.content) {
474
+ if (c?.type === 'tool_use') {
475
+ const agent = AGENT_TOOLS.has(c.name);
476
+ const input = showArgs ? c.input : agent ? { subagent_type: c.input?.subagent_type } : undefined;
477
+ content.push({ type: 'tool_use', id: c.id, name: c.name, input });
478
+ } else if (c?.type === 'tool_result') content.push({ type: 'tool_result', tool_use_id: c.tool_use_id, is_error: c.is_error });
479
+ else if (c?.type === 'text' && x.type === 'user') content.push({ type: 'text', text: cut(c.text) });
480
+ }
481
+ }
482
+ out.message = { id: m.id, model: m.model, usage: m.usage, content };
483
+ return out;
484
+ }
485
+
486
+ // 파일 한 개를 한 번 스트림으로 읽어 줄 배열로 (slim 한 줄). 읽지 못한 줄은 버린다.
487
+ async function readLines(path, showArgs) {
488
+ const out = [];
489
+ const rl = createInterface({ input: createReadStream(path, { encoding: 'utf8' }), crlfDelay: Infinity });
490
+ for await (const l of rl) {
491
+ if (!l) continue;
492
+ try {
493
+ const x = slim(JSON.parse(l), showArgs);
494
+ if (x) out.push(x);
495
+ } catch {}
496
+ }
497
+ return out;
498
+ }
499
+
500
+ // Claude 기록과 그 서브에이전트 기록(<id>/subagents/agent-*.jsonl 과 .meta.json)을 읽는다. build 에 그대로 넘긴다.
501
+ // mtime: 메인·서브에이전트 기록 가운데 가장 최근 수정 시각 (끝난 세션인지 볼 때 쓴다).
502
+ export async function readTrace(path, { showArgs = false } = {}) {
503
+ const lines = await readLines(path, showArgs);
504
+ let mtime = mtimeOf(path);
505
+ const dir = join(path.replace(/\.jsonl$/, ''), 'subagents');
506
+ const subagents = [];
507
+ for (const f of list(dir).sort()) {
508
+ if (!f.endsWith('.meta.json')) continue;
509
+ const id = f.slice('agent-'.length, -'.meta.json'.length);
510
+ let meta = {};
511
+ try {
512
+ meta = JSON.parse(readFileSync(join(dir, f), 'utf8')) ?? {};
513
+ } catch {}
514
+ const p = join(dir, `agent-${id}.jsonl`);
515
+ mtime = Math.max(mtime, mtimeOf(p));
516
+ subagents.push({ id, meta, lines: existsSync(p) ? await readLines(p, showArgs) : [] });
517
+ }
518
+ return { lines, subagents, mtime };
519
+ }
520
+
521
+ // ---- 출력 ----
522
+
523
+ const two = (n) => String(n).padStart(2, '0');
524
+ const hms = (ms) => {
525
+ const d = new Date(ms);
526
+ return `${two(d.getHours())}:${two(d.getMinutes())}:${two(d.getSeconds())}`;
527
+ };
528
+ const mdhm = (ms) => {
529
+ const d = new Date(ms);
530
+ return `${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
531
+ };
532
+ const costText = (n) => (n.unpriced && !(n.cost > 0) ? '-' : money(n.cost));
533
+ const durText = (n) => (n.start != null && n.end != null ? fmtElapsed(n.end - n.start) : n.status === 'running' ? t('trace.running') : '-');
534
+ const MARK = { done: 'traceDone', error: 'traceFail', running: 'traceRun', waiting: 'waiting' };
535
+
536
+ // 줄 하나의 이름 칸: 지시는 번호·시작 시각(·지시 글), 도구는 이름(×묶음 수, 서브에이전트 종류, 인자).
537
+ function label(n) {
538
+ const g = glyphs();
539
+ if (n.kind === 'prompt') {
540
+ const head = `#${n.n}${n.start != null ? ` ${hms(n.start)}` : ''}`;
541
+ return n.text ? `${head} ${n.text}` : `${head} ${t('trace.prompt')}`;
542
+ }
543
+ let s = n.kind === 'turn' ? t('trace.reply') : n.name;
544
+ if (n.kind === 'agent' && n.agent) s += ` ${clean(n.agent)}`;
545
+ if (n.count) s += ` ${g.times}${n.count}`;
546
+ if (n.errors && n.count) s += ` ${t('trace.errors', { n: n.errors })}`;
547
+ if (n.lost) s += ` ${t('trace.lost')}`;
548
+ if (n.folded) s += ` ${t('trace.folded', { n: n.folded })}`;
549
+ if (n.detail) s += ` ${clean(n.detail)}`;
550
+ return s;
551
+ }
552
+
553
+ // 트리 줄들 (표 출력과 Markdown 코드 블록이 같이 쓴다). 오른쪽에 시간·토큰·비용 칸.
554
+ function treeLines(r, cols) {
555
+ const W = Math.max(MIN_COLS, Math.min(cols > 0 ? cols : COLS, COLS));
556
+ const g = glyphs();
557
+ const R = [7, 7, 8];
558
+ const left = W - R.reduce((a, n) => a + n + 1, 0);
559
+ const row = (l, n) => `${pad(l, left)} ${pad(durText(n), R[0], 'right')} ${pad(n.tokens > 0 ? fmtTokens(Math.round(n.tokens)) : '-', R[1], 'right')} ${pad(costText(n), R[2], 'right')}`.trimEnd();
560
+ const out = [`${pad('', left)} ${pad(t('trace.col.time'), R[0], 'right')} ${pad(t('trace.col.tokens'), R[1], 'right')} ${pad(t('trace.col.cost'), R[2], 'right')}`.trimEnd()];
561
+ const draw = (nodes, prefix) => {
562
+ nodes.forEach((n, i) => {
563
+ const lastOne = i === nodes.length - 1;
564
+ const mark = g[MARK[n.status]] ?? ' ';
565
+ out.push(row(`${prefix}${lastOne ? g.memberLast : g.member}${mark} ${label(n)}`, n));
566
+ const next = prefix + (lastOne ? ' '.repeat(width(g.memberLast)) : g.memberPipe);
567
+ if (n.omitted) out.push(`${next}${g.member}${t('trace.omittedSteps', { n: n.omitted })}`);
568
+ draw(n.children, next);
569
+ });
570
+ };
571
+ for (const p of r.nodes) {
572
+ out.push(row(`${g[MARK[p.status]] ?? ' '} ${label(p)}`, p));
573
+ if (p.omitted) out.push(`${g.member}${t('trace.omittedSteps', { n: p.omitted })}`);
574
+ draw(p.children, '');
575
+ }
576
+ return out;
577
+ }
578
+
579
+ function titleOf(r, meta) {
580
+ return t('trace.title', { name: clean(meta.name ?? '-'), id: String(meta.id ?? '').slice(0, 8) });
581
+ }
582
+
583
+ function summaryOf(r) {
584
+ // 끝이 시작과 같은 날이면 시:분만.
585
+ const end = r.end == null ? '-' : mdhm(r.end).slice(0, 5) === mdhm(r.start).slice(0, 5) ? mdhm(r.end).slice(6) : mdhm(r.end);
586
+ const span = r.start != null ? `${mdhm(r.start)} ~ ${end}` : '-';
587
+ return t('trace.summary', { span, prompts: r.counts.prompts, tools: r.counts.tools, agents: r.counts.agents, tokens: fmtTokens(Math.round(r.tokens)), cost: costText(r) });
588
+ }
589
+
590
+ function notes(r) {
591
+ const out = [];
592
+ if (r.omitted) out.push(t('trace.omitted', { n: r.omitted }));
593
+ out.push(t('trace.noteBasis'));
594
+ if (r.unpriced) out.push(t('report.unpriced'));
595
+ return out;
596
+ }
597
+
598
+ // 사람이 읽는 80열 텍스트. meta: { id, name }.
599
+ export function formatTrace(r, meta = {}, { cols = COLS } = {}) {
600
+ const out = [titleOf(r, meta), summaryOf(r), ''];
601
+ if (r.nodes.length) out.push(...treeLines(r, cols));
602
+ else out.push(t('trace.empty'));
603
+ out.push('', ...notes(r));
604
+ return out.join('\n');
605
+ }
606
+
607
+ // Markdown: 제목·요약, 트리는 코드 블록 (기호와 칸이 그대로 맞게).
608
+ export function traceMarkdown(r, meta = {}) {
609
+ const out = [`**${titleOf(r, meta).replace(/[\\`*_[\]<>#~!|]/g, '\\$&')}**`, '', `- ${summaryOf(r)}`, ''];
610
+ if (r.nodes.length) out.push('```text', ...treeLines(r, COLS).map((l) => l.replace(/```/g, "'''")), '```');
611
+ else out.push(t('trace.empty'));
612
+ out.push('', ...notes(r).map((l) => `_${l}_`));
613
+ return out.join('\n');
614
+ }
615
+
616
+ // --json 모양: 키는 영어, 시각은 ISO(모르면 null). detail·text 는 build 에 showArgs 를 줬을 때만 있다.
617
+ export function traceJson(r, version, meta = {}) {
618
+ const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
619
+ const conv = (n) => ({
620
+ id: n.id,
621
+ kind: n.kind,
622
+ name: n.kind === 'prompt' ? `#${n.n}` : n.name,
623
+ ...(n.kind === 'agent' ? { agent: n.agent ?? null } : {}),
624
+ start: iso(n.start),
625
+ end: iso(n.end),
626
+ status: n.status,
627
+ tokens: Math.round(n.tokens),
628
+ cost: n.cost,
629
+ ...(n.unpriced ? { unpriced: true } : {}),
630
+ ...(n.count ? { count: n.count, errors: n.errors } : {}),
631
+ ...(n.lost ? { lost: true } : {}),
632
+ ...(n.folded ? { folded: n.folded } : {}),
633
+ ...(n.omitted ? { omitted: n.omitted } : {}),
634
+ ...(n.text != null ? { text: n.text } : {}),
635
+ ...(n.detail != null ? { detail: clean(n.detail) } : {}),
636
+ children: n.children.map(conv),
637
+ });
638
+ return {
639
+ version,
640
+ report: 'trace',
641
+ tool: r.tool,
642
+ session: { id: meta.id ?? null, name: meta.name ?? null },
643
+ basis: 'api',
644
+ start: iso(r.start),
645
+ end: iso(r.end),
646
+ tokens: Math.round(r.tokens),
647
+ cost: r.cost,
648
+ unpriced: r.unpriced,
649
+ counts: r.counts,
650
+ omitted: r.omitted,
651
+ nodes: r.nodes.map(conv),
652
+ };
653
+ }
654
+
655
+ // 여러 세션이 맞을 때 고를 수 있게 보이는 후보 줄.
656
+ export function candidatesText(list) {
657
+ return list.map((c) => ` ${c.tool.padEnd(6)} ${c.id.slice(0, 8)} ${c.mtime ? mdhm(c.mtime) : '-'} ${truncate(clean(c.name ?? '-'), 40)}`).join('\n');
658
+ }
659
+
package/src/ui/chrome.mjs CHANGED
@@ -22,6 +22,7 @@ const LEGEND_IDS = [
22
22
  ['◆', 'legend.waiting'],
23
23
  ['●', 'legend.unseen'],
24
24
  ['○', 'legend.idle'],
25
+ ['◐', 'legend.live'],
25
26
  ['!', 'legend.stopped'],
26
27
  ['·', 'legend.ended'],
27
28
  ['★', 'legend.pin'],
@@ -36,6 +37,14 @@ const LEGEND_IDS = [
36
37
  ['+N', 'legend.folded'],
37
38
  ['legend.periodKey', 'legend.period'],
38
39
  ['legend.filesKey', 'legend.files'],
40
+ ['', ''],
41
+ // 상태 글·행 끝에 덧붙는 표시 (#264). 열 설명보다 덜 찾으므로 맨 뒤에 둔다.
42
+ ['help.extras', null],
43
+ ['✓', 'legend.done'],
44
+ ['▲', 'legend.hot'],
45
+ ['legend.cacheKey', 'legend.cache'],
46
+ ['legend.toolKey', 'legend.tool'],
47
+ ['legend.stalledKey', 'legend.stalled'],
39
48
  ];
40
49
 
41
50
  // 지금 언어의 상태 기호·열 설명. 제목 줄은 설명이 null 이다.