@sejuneoh/aitop 0.39.0 → 0.40.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.
@@ -6,10 +6,38 @@ import { claudeCost } from '../pricing.mjs';
6
6
  import { addActivity, emptyTokens, pushEvent, describeTool, toolDetail, isNoisePrompt, parseTs, sessionName } from './common.mjs';
7
7
  import { debugIo } from '../log.mjs';
8
8
  import { addChange } from './files.mjs';
9
- import { ARTIFACT_CALLS_MAX, addArtifact, isPublish, pickArtifact } from './artifacts.mjs';
9
+ import { ARTIFACT_CALLS_MAX, addArtifact, isPublish, pathKey, pickArtifact } from './artifacts.mjs';
10
10
 
11
11
  const MAX_TURNS = 50;
12
12
 
13
+ // 아티팩트 원본 위치 (#307): 기록을 읽는 김에 메모리에만 기억한다. 캐시 파일·--json 에는 넣지 않는다 (#305 원칙).
14
+ // 경로마다 마지막 Write 결과 줄의 위치(바이트 오프셋·길이)와 시각, 그 경로를 마지막으로 고친(Edit·Artifact edits) 시각만 들고 본문은 들지 않는다.
15
+ let SRC_PATHS_MAX = 1024;
16
+ // 테스트용: 상한을 바꾼다. 이전 값을 돌려준다.
17
+ export function _setSrcLimit(n) {
18
+ const prev = SRC_PATHS_MAX;
19
+ SRC_PATHS_MAX = n;
20
+ return prev;
21
+ }
22
+ // 기록 경로 → 그 기록을 읽는 tracker. 아티팩트 원본을 열 때 위치를 묻는다 (artifact-source.mjs). 끝난 tracker 는 GC 가 가져간다.
23
+ const live = new Map();
24
+ export function liveTracker(path) {
25
+ const t = live.get(path)?.deref();
26
+ if (!t && live.has(path)) live.delete(path);
27
+ return t ?? null;
28
+ }
29
+
30
+ // 크기 상한이 있는 Map 에 넣는다 (오래된 것부터 버린다). 실제로 버렸으면 t.srcLost 를 켠다.
31
+ // 그 뒤로는 "기억에 없음" 이 "기록에 없음" 이 아니므로 artifact-source.mjs quickSource 가 훑기로 넘긴다.
32
+ function capSet(t, map, k, v) {
33
+ map.delete(k);
34
+ map.set(k, v);
35
+ if (map.size > SRC_PATHS_MAX) {
36
+ map.delete(map.keys().next().value);
37
+ t.srcLost = true;
38
+ }
39
+ }
40
+
13
41
  const RECENT_IDS = 64;
14
42
  const LOADING_MIN_BYTES = 4 * 1024 * 1024;
15
43
  // Claude Code 는 /rename 이름(custom-title 줄)을 기록 뒤에 자주 다시 붙인다. 끝부분만 읽어도 마지막 이름을 찾는다.
@@ -182,6 +210,7 @@ export class ClaudeTracker {
182
210
  this.tail = new JsonlTail(path);
183
211
  this.tail.onReset = () => this.reset();
184
212
  this.reset();
213
+ live.set(path, new WeakRef(this));
185
214
  this.title = null;
186
215
  // 사용자가 /rename 으로 붙인 이름. 기록의 마지막 custom-title 이 이긴다.
187
216
  this.customTitle = null;
@@ -192,6 +221,7 @@ export class ClaudeTracker {
192
221
  const c = loadCache(path);
193
222
  if (c) {
194
223
  this.tail.offset = c.offset;
224
+ this.srcFrom = c.offset;
195
225
  Object.assign(this, { tokens: c.tokens, cost: c.cost, costNoCache: c.costNoCache, costUnknown: c.costUnknown, context: c.context, model: c.model, title: c.title, customTitle: c.customTitle ?? null, branch: c.branch, events: c.events, lastTool: c.lastTool, lastKind: c.lastKind, files: c.files ?? [], turns: c.turns ?? [], turnCount: c.turnCount ?? 0, firstAt: c.firstAt ?? null, activity: c.activity ?? {}, stopReason: c.stopReason ?? null, cacheAt: c.cacheAt ?? null, cacheTtl: c.cacheTtl ?? null, inputAt: c.inputAt ?? null, inputFor: c.inputFor ?? null, artifacts: c.artifacts ?? [] });
196
226
  this.artCalls = new Map(c.artCalls ?? []);
197
227
  this.recent = new Map(c.recent);
@@ -259,6 +289,16 @@ export class ClaudeTracker {
259
289
  this.artifacts = [];
260
290
  // 결과를 기다리는 게시 호출: tool_use id → edits 로 고쳤는지.
261
291
  this.artCalls = new Map();
292
+ // 원본 위치 (메모리만, #307). artPaths: 아티팩트 id → { path, at }, writes: 경로 → { at, offset, length }, edited: 경로 → 마지막으로 고친 시각.
293
+ // srcFrom: 이 tracker 가 처음부터 읽기 시작한 위치. 0 이 아니면(캐시에서 이어 읽음) 그 앞 줄은 모르므로 열 때 기록을 훑는다.
294
+ this.artPaths = new Map();
295
+ this.writes = new Map();
296
+ this.edited = new Map();
297
+ this.srcFrom = 0;
298
+ // 상한 때문에 기억에서 버린 항목이 있는지 (capSet).
299
+ this.srcLost = false;
300
+ // 게시 호출의 file_path (결과에 path 가 없을 때 쓴다): tool_use id → 경로.
301
+ this.artFiles = new Map();
262
302
  }
263
303
 
264
304
  // 프롬프트 캐시가 만료되는 시각(ms). 캐시를 쓴 응답이 없으면 null.
@@ -281,7 +321,7 @@ export class ClaudeTracker {
281
321
  }
282
322
 
283
323
  update(budget) {
284
- const n = this.tail.read((x) => this.apply(x), budget);
324
+ const n = this.tail.read((x, offset, length) => this.apply(x, offset, length), budget);
285
325
  if (n) markDirty(this.path, () => this.snapshot());
286
326
  return n;
287
327
  }
@@ -341,7 +381,8 @@ export class ClaudeTracker {
341
381
  if (this.recent.size > RECENT_IDS) this.recent.delete(this.recent.keys().next().value);
342
382
  }
343
383
 
344
- apply(x) {
384
+ apply(x, offset, length) {
385
+ this.noteSource(x, offset, length);
345
386
  if (x.type === 'ai-title' && x.aiTitle) this.title = x.aiTitle;
346
387
  if (x.type === 'custom-title') this.customTitle = sessionName(x.customTitle);
347
388
  if (x.gitBranch) this.branch = x.gitBranch;
@@ -397,6 +438,45 @@ export class ClaudeTracker {
397
438
  }
398
439
  }
399
440
 
441
+ // 원본 위치 기억 (#307). 줄의 위치를 모르면(offset 없음) 아무것도 하지 않는다.
442
+ noteSource(x, offset, length) {
443
+ if (!Number.isFinite(offset)) return;
444
+ const at = parseTs(x.timestamp);
445
+ if (x.type === 'assistant') {
446
+ for (const c of Array.isArray(x.message?.content) ? x.message.content : []) {
447
+ if (c?.type !== 'tool_use' || c.name !== 'Artifact' || !isPublish(c.input)) continue;
448
+ const fp = typeof c.input?.file_path === 'string' ? c.input.file_path : null;
449
+ if (fp) capSet(this, this.artFiles, c.id, fp);
450
+ if (fp && Array.isArray(c.input.edits) && c.input.edits.length) capSet(this, this.edited, pathKey(fp), at);
451
+ }
452
+ return;
453
+ }
454
+ if (x.type !== 'user' || !x.toolUseResult || typeof x.toolUseResult !== 'object') return;
455
+ const r = x.toolUseResult;
456
+ const results = Array.isArray(x.message?.content) ? x.message.content.filter((p) => p?.type === 'tool_result') : [];
457
+ // 결과를 받은 게시 호출의 file_path 는 더 들고 있지 않는다 (오류여도). 게시가 많아도 상한에 걸리지 않게.
458
+ const files = new Map();
459
+ for (const p of results)
460
+ if (this.artFiles.has(p.tool_use_id)) {
461
+ files.set(p.tool_use_id, this.artFiles.get(p.tool_use_id));
462
+ this.artFiles.delete(p.tool_use_id);
463
+ }
464
+ if (results.some((p) => p.is_error)) return;
465
+ // writes·edited 의 키는 pathKey (Windows 는 구분자·대소문자를 맞춘다).
466
+ if (typeof r.filePath === 'string') {
467
+ if (typeof r.content === 'string' && (r.type === 'create' || r.type === 'update')) capSet(this, this.writes, pathKey(r.filePath), { at, offset, length });
468
+ else if (Array.isArray(r.structuredPatch)) capSet(this, this.edited, pathKey(r.filePath), at);
469
+ }
470
+ for (const p of results) {
471
+ if (!files.has(p.tool_use_id) && !this.artCalls.has(p.tool_use_id)) continue;
472
+ const a = pickArtifact(r, at);
473
+ const path = typeof r.path === 'string' ? r.path : files.get(p.tool_use_id);
474
+ // pre: 게시 때 이 기록이 아는 그 경로의 마지막 Write. 게시 뒤에 다시 써도 게시본에 가까운 본문을 고를 수 있게 한다.
475
+ const pre = path ? this.writes.get(pathKey(path)) : null;
476
+ if (a && path) capSet(this, this.artPaths, a.id, { path, at, ...(pre ? { pre } : {}) });
477
+ }
478
+ }
479
+
400
480
  // 게시 호출의 결과 줄이면 아티팩트 목록에 더한다. 오류 결과는 빼고, 결과 값은 artifacts.mjs pickArtifact 가 고른 것만 담는다.
401
481
  applyArtifact(x, content) {
402
482
  for (const p of content) {
@@ -97,7 +97,7 @@ function loadingPhase(t) {
97
97
 
98
98
  // 서브에이전트 전체(끝난 것 포함)의 토큰·비용 합계. 메인 세션 합계에 더해 화면에 보인다.
99
99
  export function emptySub() {
100
- return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, loading: false, files: [], activity: [], artifacts: [] };
100
+ return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, loading: false, files: [], activity: [], artifacts: [], logs: [] };
101
101
  }
102
102
 
103
103
  // 메인 tracker 와 서브에이전트 합계를 화면에 보일 세션 숫자로 합친다. 기록을 아직 읽지 않았으면(t 없음) 비용은 null.
@@ -120,6 +120,8 @@ export function sessionTotals(t, sub) {
120
120
  activity: mergeActivity([t?.activity, ...sub.activity]),
121
121
  // Artifact 도구로 게시한 것: 메인과 서브에이전트를 아티팩트별로 묶는다 (artifacts.mjs).
122
122
  artifacts: mergeArtifacts([t?.artifacts, ...sub.artifacts]),
123
+ // 기록 파일 경로 (메인과 서브에이전트). 아티팩트 원본을 볼 때만 다시 읽는다 (artifact-source.mjs, #307). --json 에는 내지 않는다.
124
+ logs: t?.path ? [t.path, ...sub.logs] : [...sub.logs],
123
125
  };
124
126
  }
125
127
 
@@ -146,6 +148,7 @@ export function readMembers(transcript, parent, budget, { track = (p, b) => trac
146
148
  sub.activity.push(t.activity);
147
149
  // 서브에이전트가 게시한 아티팩트도 부모 세션 목록에 합친다 (#305).
148
150
  sub.artifacts.push(t.artifacts ?? []);
151
+ sub.logs.push(join(dir, `agent-${id}.jsonl`));
149
152
  if (t.files.length) sub.files.push({ agent: meta.agentType ?? 'agent', files: t.files, startedAt: t.firstAt ?? undefined });
150
153
  const age = Date.now() - t.mtimeMs;
151
154
  const awaited = Boolean(meta.toolUseId && parent?.pending.has(meta.toolUseId));
@@ -782,6 +785,7 @@ function absorb(root, c) {
782
785
  root.loading ||= Boolean(c.loading);
783
786
  root.activity = mergeActivity([root.activity, c.activity]);
784
787
  if (c.artifacts?.length) root.artifacts = mergeArtifacts([root.artifacts, c.artifacts]);
788
+ if (c.logs?.length) root.logs = [...(root.logs ?? []), ...c.logs];
785
789
  }
786
790
 
787
791
  // 팀원 행 모양 (readMembers 와 같은 칸). sdk: true 면 화면이 이름 앞에 -p 를 붙인다.
package/src/tail.mjs CHANGED
@@ -85,20 +85,28 @@ export class JsonlTail {
85
85
  this.restLength += n;
86
86
  continue;
87
87
  }
88
+ // data 첫 바이트의 파일 위치. 줄마다 (위치, 바이트 길이)를 함께 넘긴다 (아티팩트 원본 위치 기억, #307).
89
+ const base = this.offset - n - this.restLength;
88
90
  const data = this.restLength ? Buffer.concat([...this.rest, chunk.subarray(0, end)]) : chunk.subarray(0, end);
89
91
  this.rest = end + 1 < n ? [Buffer.from(chunk.subarray(end + 1))] : [];
90
92
  this.restLength = n - end - 1;
91
- for (const line of data.toString('utf8').split('\n')) {
92
- if (!line) continue;
93
- let x;
94
- try {
95
- x = JSON.parse(line);
96
- } catch (e) {
97
- debug('jsonl', 'line parse failed', e, this.path);
98
- continue;
93
+ for (let s = 0; s <= data.length; ) {
94
+ let e = data.indexOf(NL, s);
95
+ if (e < 0) e = data.length;
96
+ if (e > s) {
97
+ let x;
98
+ try {
99
+ x = JSON.parse(data.toString('utf8', s, e));
100
+ } catch (err) {
101
+ debug('jsonl', 'line parse failed', err, this.path);
102
+ x = null;
103
+ }
104
+ if (x) {
105
+ onLine(x, base + s, e - s);
106
+ count++;
107
+ }
99
108
  }
100
- onLine(x);
101
- count++;
109
+ s = e + 1;
102
110
  }
103
111
  }
104
112
  } finally {