@sejuneoh/aitop 0.38.1 → 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.
- package/README.md +11 -2
- package/bin/aitop.mjs +2 -0
- package/package.json +1 -1
- package/src/cache.mjs +3 -1
- package/src/help.mjs +24 -3
- package/src/i18n.mjs +68 -0
- package/src/json.mjs +4 -0
- package/src/keys.mjs +94 -1
- package/src/sources/artifact-source.mjs +278 -0
- package/src/sources/artifacts.mjs +94 -0
- package/src/sources/claude-tracker.mjs +108 -3
- package/src/sources/claude.mjs +11 -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 +66 -1
- package/src/ui/draw.mjs +5 -2
- package/src/ui/theme.mjs +26 -0
- package/src/ui.mjs +12 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Claude 기록의 Artifact 도구 게시 결과 (#305). 상세 패널 아티팩트 구획과 --json 의 artifacts 가 쓴다.
|
|
2
|
+
// 게시(publish, action 이 없으면 publish) 호출과 짝이 되는 결과 줄의 toolUseResult 에서 몇 값만 꺼낸다.
|
|
3
|
+
// 입력의 file_path·edits 내용·prompt 와 결과의 나머지 값(path 등)은 담지 않는다.
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { win32 } from 'node:path';
|
|
6
|
+
import { mask, stripControl } from '../text.mjs';
|
|
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
|
+
|
|
17
|
+
// 세션마다 남기는 아티팩트 수 (마지막 게시가 최근인 것부터).
|
|
18
|
+
export const ARTIFACT_MAX = 20;
|
|
19
|
+
// 짝을 기다리는 게시 호출 수 상한. 결과가 오지 않은 호출이 쌓이지 않게 한다.
|
|
20
|
+
export const ARTIFACT_CALLS_MAX = 16;
|
|
21
|
+
|
|
22
|
+
const TITLE_MAX = 120;
|
|
23
|
+
const URL_MAX = 300;
|
|
24
|
+
const ID_MAX = 80;
|
|
25
|
+
const AUDIENCE_MAX = 24;
|
|
26
|
+
|
|
27
|
+
// 링크로 내보내는 주소: https://claude.ai/ 로 시작하고 URL 에 쓰는 ASCII 글자만 있는 것.
|
|
28
|
+
const SAFE_URL = /^https:\/\/claude\.ai\/[A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]*$/;
|
|
29
|
+
|
|
30
|
+
const str = (v, max) => (typeof v === 'string' ? stripControl(v).replace(/\s+/g, ' ').trim().slice(0, max) || null : null);
|
|
31
|
+
|
|
32
|
+
// 게시 호출인지. action 이 없으면 게시다.
|
|
33
|
+
export const isPublish = (input) => input?.action == null || input.action === 'publish';
|
|
34
|
+
|
|
35
|
+
// 허용 목록을 지난 링크 주소, 아니면 null. 기록에서 온 값이라 화면·--json 에 내기 전에 늘 여기를 지난다.
|
|
36
|
+
export function artifactLink(url) {
|
|
37
|
+
return typeof url === 'string' && url.length <= URL_MAX && SAFE_URL.test(url) ? url : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// 공유 범위 표시: 'org' 는 조직 공유, 'public'·'anyone' 은 공개, 그 밖('owner' 등)은 표시하지 않는다.
|
|
41
|
+
// 화면은 이 이름을 i18n 키로 바꾸고, --json 의 audience 는 기록의 원래 값을 그대로 낸다.
|
|
42
|
+
export function audienceKind(audience) {
|
|
43
|
+
const a = String(audience ?? '').toLowerCase();
|
|
44
|
+
if (a === 'org') return 'org';
|
|
45
|
+
if (a === 'public' || a === 'anyone') return 'public';
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function timeOf(v) {
|
|
50
|
+
if (typeof v === 'number' && Number.isFinite(v)) return v < 1e12 ? v * 1000 : v;
|
|
51
|
+
const t = typeof v === 'string' ? Date.parse(v) : NaN;
|
|
52
|
+
return Number.isFinite(t) ? t : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 결과 한 건 → 저장할 값. id 도 주소도 없으면 null.
|
|
56
|
+
export function pickArtifact(r, at, edits) {
|
|
57
|
+
if (!r || typeof r !== 'object' || Array.isArray(r)) return null;
|
|
58
|
+
// 주소는 원래 값이 허용 목록을 지날 때만 담는다. 제어 문자를 지워서 통과하게 만들지 않는다.
|
|
59
|
+
const url = artifactLink(r.url);
|
|
60
|
+
// 허용 목록 밖 주소는 묶는 데만 쓰고 값은 남기지 않는다 (해시).
|
|
61
|
+
const id = str(r.artifact_id, ID_MAX) ?? url ?? (typeof r.url === 'string' && r.url ? `h:${createHash('sha1').update(r.url).digest('hex').slice(0, 16)}` : null);
|
|
62
|
+
if (!id) return null;
|
|
63
|
+
// 사람이 보는 버전 번호는 seq (1, 2, …) 다. version 은 '1794205685-b571' 같은 내부 문자열이라 읽지 않는다.
|
|
64
|
+
const v = Number.isInteger(r.seq) && r.seq > 0 ? r.seq : null;
|
|
65
|
+
const title = str(r.title, TITLE_MAX);
|
|
66
|
+
// 제목은 화면 공유 때 새지 않게 비밀값처럼 보이는 글을 가린다.
|
|
67
|
+
return { id, title: title && mask(title), url, from: v, to: v, at: timeOf(r.updated) ?? at, audience: str(r.audience, AUDIENCE_MAX), edits: Boolean(edits) };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 같은 아티팩트(id)면 버전 범위를 넓히고 제목·주소·공개·바로 수정은 마지막 게시 것을 쓴다.
|
|
71
|
+
function fold(map, a) {
|
|
72
|
+
const m = map.get(a.id);
|
|
73
|
+
if (!m) return map.set(a.id, { ...a });
|
|
74
|
+
const min = (x, y) => (x == null ? y : y == null ? x : Math.min(x, y));
|
|
75
|
+
const max = (x, y) => (x == null ? y : y == null ? x : Math.max(x, y));
|
|
76
|
+
const late = a.at >= m.at ? a : m;
|
|
77
|
+
map.set(a.id, { id: a.id, title: late.title ?? m.title ?? a.title, url: late.url ?? m.url ?? a.url, from: min(m.from, a.from), to: max(m.to, a.to), at: Math.max(m.at, a.at), audience: late.audience ?? null, edits: late.edits });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const newest = (map) => [...map.values()].sort((a, b) => b.at - a.at).slice(0, ARTIFACT_MAX);
|
|
81
|
+
|
|
82
|
+
// list 에 한 건을 더한 새 목록 (최근 순, ARTIFACT_MAX 개까지).
|
|
83
|
+
export function addArtifact(list, a) {
|
|
84
|
+
const map = new Map((list ?? []).map((x) => [x.id, x]));
|
|
85
|
+
fold(map, a);
|
|
86
|
+
return newest(map);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 메인과 서브에이전트(또는 붙은 claude -p 실행)의 목록을 합친다.
|
|
90
|
+
export function mergeArtifacts(lists) {
|
|
91
|
+
const map = new Map();
|
|
92
|
+
for (const list of lists) for (const a of list ?? []) fold(map, a);
|
|
93
|
+
return newest(map);
|
|
94
|
+
}
|
|
@@ -6,9 +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, pathKey, pickArtifact } from './artifacts.mjs';
|
|
9
10
|
|
|
10
11
|
const MAX_TURNS = 50;
|
|
11
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
|
+
|
|
12
41
|
const RECENT_IDS = 64;
|
|
13
42
|
const LOADING_MIN_BYTES = 4 * 1024 * 1024;
|
|
14
43
|
// Claude Code 는 /rename 이름(custom-title 줄)을 기록 뒤에 자주 다시 붙인다. 끝부분만 읽어도 마지막 이름을 찾는다.
|
|
@@ -181,6 +210,7 @@ export class ClaudeTracker {
|
|
|
181
210
|
this.tail = new JsonlTail(path);
|
|
182
211
|
this.tail.onReset = () => this.reset();
|
|
183
212
|
this.reset();
|
|
213
|
+
live.set(path, new WeakRef(this));
|
|
184
214
|
this.title = null;
|
|
185
215
|
// 사용자가 /rename 으로 붙인 이름. 기록의 마지막 custom-title 이 이긴다.
|
|
186
216
|
this.customTitle = null;
|
|
@@ -191,7 +221,9 @@ export class ClaudeTracker {
|
|
|
191
221
|
const c = loadCache(path);
|
|
192
222
|
if (c) {
|
|
193
223
|
this.tail.offset = c.offset;
|
|
194
|
-
|
|
224
|
+
this.srcFrom = c.offset;
|
|
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 ?? [] });
|
|
226
|
+
this.artCalls = new Map(c.artCalls ?? []);
|
|
195
227
|
this.recent = new Map(c.recent);
|
|
196
228
|
this.pending = new Map(c.pending);
|
|
197
229
|
// 이 필드가 생기기 전 캐시는 이미 지나간 custom-title 을 모른다. 끝부분을 한 번 훑어 채우고 캐시에 다시 적어
|
|
@@ -253,6 +285,20 @@ export class ClaudeTracker {
|
|
|
253
285
|
this.cacheTtl = null;
|
|
254
286
|
this.inputAt = null;
|
|
255
287
|
this.inputFor = null;
|
|
288
|
+
// Artifact 도구로 게시한 것 (artifacts.mjs): 최근 순, 묶은 아티팩트마다 { id, title, url, from, to, at, audience, edits }.
|
|
289
|
+
this.artifacts = [];
|
|
290
|
+
// 결과를 기다리는 게시 호출: tool_use id → edits 로 고쳤는지.
|
|
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();
|
|
256
302
|
}
|
|
257
303
|
|
|
258
304
|
// 프롬프트 캐시가 만료되는 시각(ms). 캐시를 쓴 응답이 없으면 null.
|
|
@@ -275,7 +321,7 @@ export class ClaudeTracker {
|
|
|
275
321
|
}
|
|
276
322
|
|
|
277
323
|
update(budget) {
|
|
278
|
-
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);
|
|
279
325
|
if (n) markDirty(this.path, () => this.snapshot());
|
|
280
326
|
return n;
|
|
281
327
|
}
|
|
@@ -308,6 +354,8 @@ export class ClaudeTracker {
|
|
|
308
354
|
cacheTtl: this.cacheTtl,
|
|
309
355
|
inputAt: this.inputAt,
|
|
310
356
|
inputFor: this.inputFor,
|
|
357
|
+
artifacts: this.artifacts,
|
|
358
|
+
artCalls: [...this.artCalls],
|
|
311
359
|
};
|
|
312
360
|
}
|
|
313
361
|
|
|
@@ -333,7 +381,8 @@ export class ClaudeTracker {
|
|
|
333
381
|
if (this.recent.size > RECENT_IDS) this.recent.delete(this.recent.keys().next().value);
|
|
334
382
|
}
|
|
335
383
|
|
|
336
|
-
apply(x) {
|
|
384
|
+
apply(x, offset, length) {
|
|
385
|
+
this.noteSource(x, offset, length);
|
|
337
386
|
if (x.type === 'ai-title' && x.aiTitle) this.title = x.aiTitle;
|
|
338
387
|
if (x.type === 'custom-title') this.customTitle = sessionName(x.customTitle);
|
|
339
388
|
if (x.gitBranch) this.branch = x.gitBranch;
|
|
@@ -358,6 +407,10 @@ export class ClaudeTracker {
|
|
|
358
407
|
this.lastTool = describeTool(c.name, c.input);
|
|
359
408
|
// at: 호출을 낸 줄의 시각 (도구 실행 경과 시간의 기준). resumeAt: 허락 대기를 마지막으로 본 시각 (markWaiting).
|
|
360
409
|
this.pending.set(c.id, { name: c.name, what: this.lastTool, detail: toolDetail(c.name, c.input), agent: c.input?.subagent_type ?? null, at: parseTs(x.timestamp) });
|
|
410
|
+
if (c.name === 'Artifact' && isPublish(c.input)) {
|
|
411
|
+
this.artCalls.set(c.id, Boolean(c.input?.edits));
|
|
412
|
+
if (this.artCalls.size > ARTIFACT_CALLS_MAX) this.artCalls.delete(this.artCalls.keys().next().value);
|
|
413
|
+
}
|
|
361
414
|
pushEvent(this, x.timestamp, 'tool', this.lastTool);
|
|
362
415
|
this.lastKind = 'tool';
|
|
363
416
|
} else if (c.type === 'text' && c.text?.trim()) {
|
|
@@ -371,6 +424,7 @@ export class ClaudeTracker {
|
|
|
371
424
|
if (x.toolUseResult) addChange(this.files, x.toolUseResult, x.timestamp);
|
|
372
425
|
const c = x.message.content;
|
|
373
426
|
if (Array.isArray(c)) for (const p of c) if (p.type === 'tool_result') this.pending.delete(p.tool_use_id);
|
|
427
|
+
if (Array.isArray(c) && this.artCalls.size) this.applyArtifact(x, c);
|
|
374
428
|
const text = typeof c === 'string' ? c : Array.isArray(c) ? c.filter((p) => p.type === 'text').map((p) => p.text).join(' ') : '';
|
|
375
429
|
if (text && !isNoisePrompt(text)) {
|
|
376
430
|
const e = pushEvent(this, x.timestamp, 'prompt', text);
|
|
@@ -384,6 +438,57 @@ export class ClaudeTracker {
|
|
|
384
438
|
}
|
|
385
439
|
}
|
|
386
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
|
+
|
|
480
|
+
// 게시 호출의 결과 줄이면 아티팩트 목록에 더한다. 오류 결과는 빼고, 결과 값은 artifacts.mjs pickArtifact 가 고른 것만 담는다.
|
|
481
|
+
applyArtifact(x, content) {
|
|
482
|
+
for (const p of content) {
|
|
483
|
+
if (p.type !== 'tool_result' || !this.artCalls.has(p.tool_use_id)) continue;
|
|
484
|
+
const edits = this.artCalls.get(p.tool_use_id);
|
|
485
|
+
this.artCalls.delete(p.tool_use_id);
|
|
486
|
+
if (p.is_error) continue;
|
|
487
|
+
const a = pickArtifact(x.toolUseResult, parseTs(x.timestamp), edits);
|
|
488
|
+
if (a) this.artifacts = addArtifact(this.artifacts, a);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
387
492
|
// 허락을 기다리는 동안 보일 요청 내용. 열린 도구 호출 가운데 대기 문구(approve Bash 등)에 이름이 나온 것을 먼저,
|
|
388
493
|
// 없으면 가장 최근 것을 고른다. 팀원(Agent·Task) 호출만 열려 있으면 없음.
|
|
389
494
|
waitDetail(waitingFor = '') {
|
package/src/sources/claude.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { isSessionAlive, parentPid } from '../procs.mjs';
|
|
|
10
10
|
import { ClaudeTracker, headEntrypoint, tailCustomTitle, tailStopReason } from './claude-tracker.mjs';
|
|
11
11
|
import { emptyTokens, isLongTool, mergeActivity, MEMBER_FADE_MS, sessionName } from './common.mjs';
|
|
12
12
|
import { mergeFiles } from './files.mjs';
|
|
13
|
+
import { mergeArtifacts } from './artifacts.mjs';
|
|
13
14
|
import { debug, debugIo } from '../log.mjs';
|
|
14
15
|
import { claudeDirs, claudeProjectRoots, dedupeBy } from './dirs.mjs';
|
|
15
16
|
|
|
@@ -96,7 +97,7 @@ function loadingPhase(t) {
|
|
|
96
97
|
|
|
97
98
|
// 서브에이전트 전체(끝난 것 포함)의 토큰·비용 합계. 메인 세션 합계에 더해 화면에 보인다.
|
|
98
99
|
export function emptySub() {
|
|
99
|
-
return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, loading: false, files: [], activity: [] };
|
|
100
|
+
return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, loading: false, files: [], activity: [], artifacts: [], logs: [] };
|
|
100
101
|
}
|
|
101
102
|
|
|
102
103
|
// 메인 tracker 와 서브에이전트 합계를 화면에 보일 세션 숫자로 합친다. 기록을 아직 읽지 않았으면(t 없음) 비용은 null.
|
|
@@ -117,6 +118,10 @@ export function sessionTotals(t, sub) {
|
|
|
117
118
|
turns: t?.turns ?? [],
|
|
118
119
|
// 시간별 토큰: 메인과 서브에이전트를 칸별로 더한다.
|
|
119
120
|
activity: mergeActivity([t?.activity, ...sub.activity]),
|
|
121
|
+
// Artifact 도구로 게시한 것: 메인과 서브에이전트를 아티팩트별로 묶는다 (artifacts.mjs).
|
|
122
|
+
artifacts: mergeArtifacts([t?.artifacts, ...sub.artifacts]),
|
|
123
|
+
// 기록 파일 경로 (메인과 서브에이전트). 아티팩트 원본을 볼 때만 다시 읽는다 (artifact-source.mjs, #307). --json 에는 내지 않는다.
|
|
124
|
+
logs: t?.path ? [t.path, ...sub.logs] : [...sub.logs],
|
|
120
125
|
};
|
|
121
126
|
}
|
|
122
127
|
|
|
@@ -141,6 +146,9 @@ export function readMembers(transcript, parent, budget, { track = (p, b) => trac
|
|
|
141
146
|
sub.costUnknown ||= t.costUnknown;
|
|
142
147
|
sub.loading ||= t.loading != null;
|
|
143
148
|
sub.activity.push(t.activity);
|
|
149
|
+
// 서브에이전트가 게시한 아티팩트도 부모 세션 목록에 합친다 (#305).
|
|
150
|
+
sub.artifacts.push(t.artifacts ?? []);
|
|
151
|
+
sub.logs.push(join(dir, `agent-${id}.jsonl`));
|
|
144
152
|
if (t.files.length) sub.files.push({ agent: meta.agentType ?? 'agent', files: t.files, startedAt: t.firstAt ?? undefined });
|
|
145
153
|
const age = Date.now() - t.mtimeMs;
|
|
146
154
|
const awaited = Boolean(meta.toolUseId && parent?.pending.has(meta.toolUseId));
|
|
@@ -776,6 +784,8 @@ function absorb(root, c) {
|
|
|
776
784
|
root.costUnknown ||= Boolean(c.costUnknown);
|
|
777
785
|
root.loading ||= Boolean(c.loading);
|
|
778
786
|
root.activity = mergeActivity([root.activity, c.activity]);
|
|
787
|
+
if (c.artifacts?.length) root.artifacts = mergeArtifacts([root.artifacts, c.artifacts]);
|
|
788
|
+
if (c.logs?.length) root.logs = [...(root.logs ?? []), ...c.logs];
|
|
779
789
|
}
|
|
780
790
|
|
|
781
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 {
|