@sejuneoh/aitop 0.39.0 → 0.41.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 +52 -5
- package/bin/aitop.mjs +37 -7
- package/package.json +1 -1
- package/src/config.mjs +53 -0
- package/src/doctor.mjs +2 -0
- package/src/help.mjs +24 -3
- package/src/i18n.mjs +115 -4
- package/src/json.mjs +13 -1
- package/src/keys.mjs +99 -1
- package/src/notify.mjs +4 -1
- package/src/order.mjs +12 -1
- package/src/remote.mjs +372 -0
- package/src/resume.mjs +44 -1
- package/src/sources/artifact-source.mjs +278 -0
- package/src/sources/artifacts.mjs +10 -0
- package/src/sources/claude-tracker.mjs +83 -3
- package/src/sources/claude.mjs +5 -1
- package/src/tail.mjs +18 -10
- package/src/ui/artifact-view.mjs +634 -0
- package/src/ui/chrome.mjs +4 -0
- package/src/ui/detail.mjs +23 -7
- package/src/ui/table.mjs +28 -2
- package/src/ui.mjs +33 -10
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// 아티팩트 원본 찾기 (#307). 상세 패널 아티팩트 목록에서 Enter 로 볼 때만 부른다 (미리 읽거나 캐시에 쌓지 않는다).
|
|
2
|
+
// 순서: 1) 게시 결과의 path 에 있는 로컬 파일 2) 같은 세션(서브에이전트 포함) 기록에서 그 경로로 마지막에 Write 한 본문 3) 원본 없음.
|
|
3
|
+
// 기록 본문을 쓸 때 그 Write 뒤에 같은 경로의 Edit 이나 Artifact edits 가 있었으면 게시본과 다를 수 있다고 알린다.
|
|
4
|
+
// 경로는 기록의 게시 결과(toolUseResult.path, 없으면 게시 호출의 file_path)에서만 얻는다. 목록·캐시·--json 에는 경로를 두지 않는다.
|
|
5
|
+
// 보통은 기록을 읽던 tracker 가 메모리에 기억한 위치(경로, Write 결과 줄의 오프셋)만 읽고, 위치를 모를 때만 기록을 뒤에서 나눠 훑는다.
|
|
6
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
|
|
7
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
8
|
+
import { isAbsolute } from 'node:path';
|
|
9
|
+
import { isPublish, pathKey, pickArtifact } from './artifacts.mjs';
|
|
10
|
+
import { parseTs } from './common.mjs';
|
|
11
|
+
import { liveTracker } from './claude-tracker.mjs';
|
|
12
|
+
|
|
13
|
+
// 원본으로 읽는 최대 바이트 (artifacts.mjs). 넘으면 앞부분만 보이고 cut 을 켠다.
|
|
14
|
+
export { SOURCE_MAX } from './artifacts.mjs';
|
|
15
|
+
import { SOURCE_MAX } from './artifacts.mjs';
|
|
16
|
+
|
|
17
|
+
const PATH_MAX = 4096;
|
|
18
|
+
const okPath = (p) => typeof p === 'string' && p.length <= PATH_MAX && isAbsolute(p) && !/[\x00-\x1f\x7f]/.test(p);
|
|
19
|
+
|
|
20
|
+
// 바이트 앞부분을 글로. 잘린 자리의 반쪽 글자는 버린다.
|
|
21
|
+
function decode(buf) {
|
|
22
|
+
const d = new StringDecoder('utf8');
|
|
23
|
+
return d.write(buf);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// 로컬 파일 읽기: 일반 파일이고 심볼릭 링크가 아닐 때만. 실패하면 null (조용히 다음 출처로).
|
|
27
|
+
// lstat 와 open 사이에 링크로 바뀌는 것도 막는다 (O_NOFOLLOW 가 있는 OS 는 열 때 거절, 없으면 같은 파일인지 dev·ino 로 다시 본다).
|
|
28
|
+
export function readLocal(path, max = SOURCE_MAX) {
|
|
29
|
+
if (!okPath(path)) return null;
|
|
30
|
+
let fd;
|
|
31
|
+
try {
|
|
32
|
+
const st = lstatSync(path);
|
|
33
|
+
if (st.isSymbolicLink() || !st.isFile()) return null;
|
|
34
|
+
fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
35
|
+
const f = fstatSync(fd);
|
|
36
|
+
if (!f.isFile() || f.dev !== st.dev || f.ino !== st.ino) return null;
|
|
37
|
+
const n = Math.min(f.size, max);
|
|
38
|
+
const buf = Buffer.alloc(n);
|
|
39
|
+
let got = 0;
|
|
40
|
+
while (got < n) {
|
|
41
|
+
const r = readSync(fd, buf, got, n - got, got);
|
|
42
|
+
if (!r) break;
|
|
43
|
+
got += r;
|
|
44
|
+
}
|
|
45
|
+
return { text: decode(buf.subarray(0, got)), cut: f.size > max, size: f.size };
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
} finally {
|
|
49
|
+
if (fd != null)
|
|
50
|
+
try {
|
|
51
|
+
closeSync(fd);
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// 기록을 한 줄씩 읽는다 (큰 기록도 통째로 올리지 않는다). want 에 걸리는 줄만 JSON 으로 푼다.
|
|
57
|
+
// 생성기라서 1MB 를 읽을 때마다 한 번 멈춘다(yield). 화면 쪽은 시간을 잘라 이어 돌려 키 입력과 그리기를 막지 않는다.
|
|
58
|
+
function* eachRecord(path, want, fn) {
|
|
59
|
+
let fd;
|
|
60
|
+
try {
|
|
61
|
+
fd = openSync(path, 'r');
|
|
62
|
+
const d = new StringDecoder('utf8');
|
|
63
|
+
const buf = Buffer.alloc(1 << 20);
|
|
64
|
+
let rest = '';
|
|
65
|
+
let pos = 0;
|
|
66
|
+
const take = (l) => {
|
|
67
|
+
if (!want(l)) return;
|
|
68
|
+
try {
|
|
69
|
+
fn(JSON.parse(l));
|
|
70
|
+
} catch {}
|
|
71
|
+
};
|
|
72
|
+
for (;;) {
|
|
73
|
+
const n = readSync(fd, buf, 0, buf.length, pos);
|
|
74
|
+
if (!n) break;
|
|
75
|
+
pos += n;
|
|
76
|
+
rest += d.write(buf.subarray(0, n));
|
|
77
|
+
let start = 0;
|
|
78
|
+
let i;
|
|
79
|
+
while ((i = rest.indexOf('\n', start)) >= 0) {
|
|
80
|
+
take(rest.slice(start, i));
|
|
81
|
+
start = i + 1;
|
|
82
|
+
}
|
|
83
|
+
rest = rest.slice(start);
|
|
84
|
+
yield n;
|
|
85
|
+
}
|
|
86
|
+
if (rest) take(rest);
|
|
87
|
+
} catch {
|
|
88
|
+
} finally {
|
|
89
|
+
if (fd != null)
|
|
90
|
+
try {
|
|
91
|
+
closeSync(fd);
|
|
92
|
+
} catch {}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// JSON 안에 적힌 모양 (따옴표 없이).
|
|
97
|
+
const inJson = (s) => JSON.stringify(s).slice(1, -1);
|
|
98
|
+
|
|
99
|
+
const toolUses = (x) => (x?.type === 'assistant' && Array.isArray(x.message?.content) ? x.message.content.filter((c) => c?.type === 'tool_use') : []);
|
|
100
|
+
const toolResults = (x) => (x?.type === 'user' && Array.isArray(x.message?.content) ? x.message.content.filter((c) => c?.type === 'tool_result') : []);
|
|
101
|
+
|
|
102
|
+
// 기록들에서 이 아티팩트(a.id)를 마지막으로 게시한 결과의 경로와 시각 { path, at }. 결과에 path 가 없으면 게시 호출의 file_path.
|
|
103
|
+
function* findPathSteps(logs, a) {
|
|
104
|
+
const calls = new Map();
|
|
105
|
+
let best = null;
|
|
106
|
+
const raw = a?.id && !a.id.startsWith('h:') ? inJson(a.id) : null;
|
|
107
|
+
for (const log of logs ?? []) {
|
|
108
|
+
yield* eachRecord(
|
|
109
|
+
log,
|
|
110
|
+
(l) => l.includes('"Artifact"') || (l.includes('"toolUseResult"') && (!raw || l.includes(raw))),
|
|
111
|
+
(x) => {
|
|
112
|
+
for (const c of toolUses(x)) if (c.name === 'Artifact' && isPublish(c.input)) calls.set(c.id, c.input?.file_path);
|
|
113
|
+
if (!x.toolUseResult) return;
|
|
114
|
+
for (const p of toolResults(x)) {
|
|
115
|
+
if (!calls.has(p.tool_use_id) || p.is_error) continue;
|
|
116
|
+
const got = pickArtifact(x.toolUseResult, parseTs(x.timestamp));
|
|
117
|
+
if (got?.id !== a.id) continue;
|
|
118
|
+
const path = okPath(x.toolUseResult.path) ? x.toolUseResult.path : okPath(calls.get(p.tool_use_id)) ? calls.get(p.tool_use_id) : null;
|
|
119
|
+
const at = parseTs(x.timestamp);
|
|
120
|
+
if (path && (!best || at >= best.at)) best = { path, at };
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return best;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 기록들에서 path 를 쓰고 고친 일. 게시 시각(pubAt) 이전(같거나 이전)의 마지막 Write 본문(pre),
|
|
129
|
+
// 게시 뒤 첫 Write 본문(post), 그리고 Write·Edit·Artifact edits 가 있었던 시각들(mods)을 모은다. 본문은 둘까지만 든다.
|
|
130
|
+
function* findWritesSteps(logs, path, pubAt, max = SOURCE_MAX) {
|
|
131
|
+
let pre = null;
|
|
132
|
+
let post = null;
|
|
133
|
+
const mods = [];
|
|
134
|
+
const key = pathKey(path);
|
|
135
|
+
const esc = inJson(path);
|
|
136
|
+
// Windows 는 구분자·대소문자가 다르게 적힌 줄도 봐야 하므로 넓게 거른다.
|
|
137
|
+
const want = process.platform === 'win32' ? (l) => l.includes('"filePath"') || l.includes('"file_path"') : (l) => l.includes(esc) || l.includes(path);
|
|
138
|
+
for (const log of logs ?? []) {
|
|
139
|
+
yield* eachRecord(log, want, (x) => {
|
|
140
|
+
const at = parseTs(x.timestamp);
|
|
141
|
+
for (const c of toolUses(x)) if (c.name === 'Artifact' && isPublish(c.input) && pathKey(c.input?.file_path) === key && Array.isArray(c.input.edits) && c.input.edits.length) mods.push(at);
|
|
142
|
+
const r = x.toolUseResult;
|
|
143
|
+
if (x.type !== 'user' || !r || typeof r !== 'object' || pathKey(r.filePath) !== key) return;
|
|
144
|
+
if (toolResults(x).some((p) => p.is_error)) return;
|
|
145
|
+
if (typeof r.content === 'string' && (r.type === 'create' || r.type === 'update')) {
|
|
146
|
+
mods.push(at);
|
|
147
|
+
if (at <= pubAt) {
|
|
148
|
+
if (!pre || at >= pre.at) pre = { at, ...cap(r.content, max) };
|
|
149
|
+
} else if (!post || at < post.at) post = { at, ...cap(r.content, max) };
|
|
150
|
+
} else if (Array.isArray(r.structuredPatch)) mods.push(at);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
return { pre, post, mods };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const cap = (text, max) => (text.length > max ? { text: text.slice(0, max), cut: true } : { text, cut: false });
|
|
157
|
+
const none = (path) => ({ kind: 'none', path, text: '', cut: false, changed: false });
|
|
158
|
+
|
|
159
|
+
// 생성기를 끝까지 돌린 값.
|
|
160
|
+
function run(gen) {
|
|
161
|
+
for (;;) {
|
|
162
|
+
const r = gen.next();
|
|
163
|
+
if (r.done) return r.value;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export const findPath = (logs, a) => run(findPathSteps(logs, a))?.path ?? null;
|
|
168
|
+
|
|
169
|
+
// 게시본과 다를 수 있는지 (#307 리뷰):
|
|
170
|
+
// - 로컬 파일: 마지막 게시 뒤에 같은 경로의 Write·Edit·Artifact edits 가 있었으면.
|
|
171
|
+
// - 기록 본문: 게시 이전 마지막 Write 를 쓰고, 그 뒤에 고친 일이 있었으면. 게시 이전 Write 가 없어 게시 뒤 첫 Write 를 쓰면 늘.
|
|
172
|
+
function* scanSteps(s, a) {
|
|
173
|
+
const logs = s?.logs ?? [];
|
|
174
|
+
const hit = yield* findPathSteps(logs, a);
|
|
175
|
+
if (!hit) return none(null);
|
|
176
|
+
const local = readLocal(hit.path);
|
|
177
|
+
const { pre, post, mods } = yield* findWritesSteps(logs, hit.path, hit.at);
|
|
178
|
+
if (local) return { kind: 'local', path: hit.path, text: local.text, cut: local.cut, changed: mods.some((at) => at > hit.at) };
|
|
179
|
+
const w = pre ?? post;
|
|
180
|
+
if (!w) return none(hit.path);
|
|
181
|
+
return { kind: 'record', path: hit.path, text: w.text, cut: w.cut, changed: w === post || mods.some((at) => at > w.at) };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 기억한 위치의 Write 결과 줄 하나만 읽는다. 그 자리에 같은 경로의 Write 결과가 없으면(기록이 다시 쓰임) null.
|
|
185
|
+
export const LINE_MAX = 64 * 1024 * 1024;
|
|
186
|
+
export function readWriteAt(log, offset, length, path, max = SOURCE_MAX) {
|
|
187
|
+
if (!Number.isFinite(offset) || !(length > 0) || length > LINE_MAX) return null;
|
|
188
|
+
let fd;
|
|
189
|
+
try {
|
|
190
|
+
fd = openSync(log, 'r');
|
|
191
|
+
const buf = Buffer.alloc(length);
|
|
192
|
+
let got = 0;
|
|
193
|
+
while (got < length) {
|
|
194
|
+
const r = readSync(fd, buf, got, length - got, offset + got);
|
|
195
|
+
if (!r) break;
|
|
196
|
+
got += r;
|
|
197
|
+
}
|
|
198
|
+
if (got < length) return null;
|
|
199
|
+
const x = JSON.parse(buf.toString('utf8'));
|
|
200
|
+
const r = x?.toolUseResult;
|
|
201
|
+
if (x?.type !== 'user' || pathKey(r?.filePath) !== pathKey(path) || typeof r.content !== 'string' || (r.type !== 'create' && r.type !== 'update')) return null;
|
|
202
|
+
return cap(r.content, max);
|
|
203
|
+
} catch {
|
|
204
|
+
return null;
|
|
205
|
+
} finally {
|
|
206
|
+
if (fd != null)
|
|
207
|
+
try {
|
|
208
|
+
closeSync(fd);
|
|
209
|
+
} catch {}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// 기록을 읽는 tracker 가 기억한 위치로 찾는다 (claude-tracker.mjs noteSource). 훑지 않는다. 결과는 훑기(scanSteps)와 같은 규칙이다.
|
|
214
|
+
// 모르면 null: tracker 가 없거나, 캐시에서 이어 읽어 앞부분을 모르거나 상한 때문에 기억을 버린(srcLost) 상태에서 찾지 못했거나,
|
|
215
|
+
// 기억한 줄이 바뀌었거나, 게시 이전 마지막 Write 를 확실히 모를 때. srcLost 면 '고친 적 없음(changed false)' 도 믿을 수 없어 훑기로 넘긴다.
|
|
216
|
+
export function quickSource(s, a, find = liveTracker) {
|
|
217
|
+
const ts = (s?.logs ?? []).map((p) => find(p));
|
|
218
|
+
if (!ts.length || ts.some((t) => !t)) return null;
|
|
219
|
+
// 모든 기록을 처음부터 읽었고 버린 기억도 없으면 못 찾은 것도 답이다.
|
|
220
|
+
const lost = ts.some((t) => t.srcLost);
|
|
221
|
+
const complete = !lost && ts.every((t) => t.srcFrom === 0);
|
|
222
|
+
let hit = null;
|
|
223
|
+
let owner = null;
|
|
224
|
+
for (const t of ts) {
|
|
225
|
+
const p = t.artPaths?.get(a?.id);
|
|
226
|
+
if (p && okPath(p.path) && (!hit || p.at >= hit.at)) [hit, owner] = [p, t];
|
|
227
|
+
}
|
|
228
|
+
if (!hit) return complete ? none(null) : null;
|
|
229
|
+
const key = pathKey(hit.path);
|
|
230
|
+
// 경로를 마지막으로 쓰거나 고친 시각 (기록마다 마지막 Write 와 마지막 Edit·edits).
|
|
231
|
+
const lastMod = Math.max(-Infinity, ...ts.flatMap((t) => [t.edited?.get(key) ?? -Infinity, t.writes?.get(key)?.at ?? -Infinity]));
|
|
232
|
+
const done = (doc) => (doc.changed || !lost ? doc : null);
|
|
233
|
+
const local = readLocal(hit.path);
|
|
234
|
+
if (local) return done({ kind: 'local', path: hit.path, text: local.text, cut: local.cut, changed: lastMod > hit.at });
|
|
235
|
+
// 게시 이전 마지막 Write: 기록마다 마지막 Write 가 게시 이전이면 그것, 게시한 기록은 게시 때 붙여 둔 것(pre).
|
|
236
|
+
// 게시 뒤 Write 만 아는 기록이 있으면 그 앞 Write 를 모르므로 훑는다.
|
|
237
|
+
let w = null;
|
|
238
|
+
for (const t of ts) {
|
|
239
|
+
const last = t.writes?.get(key);
|
|
240
|
+
let x = last && last.at <= hit.at ? last : null;
|
|
241
|
+
if (!x && t === owner && hit.pre && hit.pre.at <= hit.at) x = hit.pre;
|
|
242
|
+
else if (!x && last) return null;
|
|
243
|
+
if (x && (!w || x.at >= w.at)) w = { ...x, log: t.path };
|
|
244
|
+
}
|
|
245
|
+
if (!w) return complete ? none(hit.path) : null;
|
|
246
|
+
const body = readWriteAt(w.log, w.offset, w.length, hit.path);
|
|
247
|
+
if (!body) return null;
|
|
248
|
+
return done({ kind: 'record', path: hit.path, text: body.text, cut: body.cut, changed: lastMod > w.at });
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 원본 찾기 (기다리는 판). s.logs: 세션 기록 경로 (메인과 서브에이전트, claude.mjs sessionTotals).
|
|
252
|
+
// 돌려주는 값: { kind: 'local'|'record'|'none', path, text, cut, changed }
|
|
253
|
+
export function loadArtifactSource(s, a) {
|
|
254
|
+
return quickSource(s, a) ?? run(scanSteps(s, a));
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// 화면용: 기억한 위치로 바로 찾으면 그 값을, 아니면 null 을 돌려주고 기록 훑기를 뒤에서 시간을 잘라 돌린다.
|
|
258
|
+
// 한 번에 slice ms 만 돌고 다음 이벤트 루프로 넘긴다. cancelled() 가 참이면 그만둔다. 끝나면 done(doc).
|
|
259
|
+
export function openArtifactSource(s, a, { done, cancelled = () => false, slice = 30 } = {}) {
|
|
260
|
+
const quick = quickSource(s, a);
|
|
261
|
+
if (quick) return quick;
|
|
262
|
+
const gen = scanSteps(s, a);
|
|
263
|
+
const step = () => {
|
|
264
|
+
if (cancelled()) {
|
|
265
|
+
gen.return();
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const until = Date.now() + slice;
|
|
269
|
+
for (;;) {
|
|
270
|
+
const r = gen.next();
|
|
271
|
+
if (r.done) return done?.(r.value);
|
|
272
|
+
if (Date.now() >= until) break;
|
|
273
|
+
}
|
|
274
|
+
setImmediate(step);
|
|
275
|
+
};
|
|
276
|
+
setImmediate(step);
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
@@ -2,8 +2,18 @@
|
|
|
2
2
|
// 게시(publish, action 이 없으면 publish) 호출과 짝이 되는 결과 줄의 toolUseResult 에서 몇 값만 꺼낸다.
|
|
3
3
|
// 입력의 file_path·edits 내용·prompt 와 결과의 나머지 값(path 등)은 담지 않는다.
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
|
+
import { win32 } from 'node:path';
|
|
5
6
|
import { mask, stripControl } from '../text.mjs';
|
|
6
7
|
|
|
8
|
+
// 경로를 비교하는 키. Windows 는 구분자(/ 와 역슬래시)와 대소문자를 맞추고, 다른 OS 는 그대로 (#307).
|
|
9
|
+
// 아티팩트 원본으로 읽는 최대 바이트 (artifact-source.mjs, 화면의 잘림 표시).
|
|
10
|
+
export const SOURCE_MAX = 2 * 1024 * 1024;
|
|
11
|
+
|
|
12
|
+
export function pathKey(p, platform = process.platform) {
|
|
13
|
+
if (typeof p !== 'string') return null;
|
|
14
|
+
return platform === 'win32' ? win32.normalize(p).toLowerCase() : p;
|
|
15
|
+
}
|
|
16
|
+
|
|
7
17
|
// 세션마다 남기는 아티팩트 수 (마지막 게시가 최근인 것부터).
|
|
8
18
|
export const ARTIFACT_MAX = 20;
|
|
9
19
|
// 짝을 기다리는 게시 호출 수 상한. 결과가 오지 않은 호출이 쌓이지 않게 한다.
|
|
@@ -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) {
|
package/src/sources/claude.mjs
CHANGED
|
@@ -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 (
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
x
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
-
|
|
101
|
-
count++;
|
|
109
|
+
s = e + 1;
|
|
102
110
|
}
|
|
103
111
|
}
|
|
104
112
|
} finally {
|