blun-king-cli 9.1.653 → 9.1.654

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.
@@ -0,0 +1,1420 @@
1
+ // original-history-entry.ts
2
+ import { dirname as dirname2, join as join2 } from "node:path";
3
+
4
+ // packages/agent-core/src/agent/records/original-bytes.ts
5
+ import { lstat, open } from "node:fs/promises";
6
+ var identity = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
7
+ var failure = (code) => new Error(code);
8
+ var FileOriginalByteSource = class {
9
+ constructor(filename, owner) {
10
+ this.filename = filename;
11
+ this.owner = owner;
12
+ }
13
+ filename;
14
+ owner;
15
+ snapshots = /* @__PURE__ */ new WeakMap();
16
+ disposed = false;
17
+ dispose() {
18
+ this.disposed = true;
19
+ }
20
+ async capture(signal) {
21
+ this.check(signal);
22
+ const generation = this.owner.generation();
23
+ try {
24
+ await this.owner.flush();
25
+ } catch {
26
+ this.check(signal, generation);
27
+ throw failure("ORIGINAL_SOURCE_UNAVAILABLE");
28
+ }
29
+ this.check(signal, generation);
30
+ return this.withFile(generation, void 0, signal, async (_file, stat) => {
31
+ if (stat.size > BigInt(Number.MAX_SAFE_INTEGER)) throw failure("ORIGINAL_SOURCE_UNAVAILABLE");
32
+ const snapshot = Object.freeze({ kind: "raw-wire-prefix", endByte: Number(stat.size) });
33
+ this.snapshots.set(snapshot, { generation, identity: identity(stat), endByte: snapshot.endByte });
34
+ return snapshot;
35
+ });
36
+ }
37
+ async read(snapshot, offset, maxBytes, signal) {
38
+ this.check(signal);
39
+ const state = this.snapshots.get(snapshot);
40
+ if (state === void 0) throw failure("ORIGINAL_SNAPSHOT_INVALID");
41
+ this.check(signal, state.generation);
42
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > state.endByte || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 65536) throw failure("ORIGINAL_BYTE_RANGE_INVALID");
43
+ return this.withFile(state.generation, state, signal, async (file) => {
44
+ const bytes = Buffer.alloc(Math.min(maxBytes, state.endByte - offset));
45
+ let read = 0;
46
+ while (read < bytes.length) {
47
+ const part = await file.read(bytes, read, bytes.length - read, offset + read);
48
+ this.check(signal, state.generation);
49
+ if (part.bytesRead === 0) throw failure("ORIGINAL_SOURCE_CHANGED");
50
+ read += part.bytesRead;
51
+ }
52
+ return { bytes, nextOffset: offset + read, atEnd: offset + read === state.endByte };
53
+ });
54
+ }
55
+ /** Local ownership/lifecycle fence only; read() performs physical file checks. */
56
+ assertCurrent(snapshot, signal) {
57
+ this.check(signal);
58
+ const state = this.snapshots.get(snapshot);
59
+ if (state === void 0) throw failure("ORIGINAL_SNAPSHOT_INVALID");
60
+ this.check(signal, state.generation);
61
+ }
62
+ check(signal, generation) {
63
+ signal?.throwIfAborted();
64
+ if (this.disposed) throw failure("ORIGINAL_SOURCE_CLOSED");
65
+ if (generation !== void 0 && generation !== this.owner.generation()) throw failure("ORIGINAL_SOURCE_CHANGED");
66
+ }
67
+ async checkedStat(file, generation, signal) {
68
+ const stat = await file.stat({ bigint: true });
69
+ this.check(signal, generation);
70
+ const pathStat = await lstat(this.filename, { bigint: true });
71
+ this.check(signal, generation);
72
+ if (!stat.isFile() || !pathStat.isFile() || stat.nlink !== 1n || pathStat.nlink !== 1n || identity(stat) !== identity(pathStat)) throw failure("ORIGINAL_SOURCE_CHANGED");
73
+ return stat;
74
+ }
75
+ async withFile(generation, state, signal, operation) {
76
+ this.check(signal, generation);
77
+ let file;
78
+ let result;
79
+ let primaryError, failed = false, cleanupFailed = false;
80
+ try {
81
+ if (this.owner.validatePath !== void 0) {
82
+ await this.owner.validatePath(this.filename);
83
+ this.check(signal, generation);
84
+ }
85
+ file = await open(this.filename, "r");
86
+ this.check(signal, generation);
87
+ const before = await this.checkedStat(file, generation, signal);
88
+ if (state !== void 0 && (identity(before) !== state.identity || before.size < BigInt(state.endByte))) {
89
+ throw failure("ORIGINAL_SOURCE_CHANGED");
90
+ }
91
+ result = await operation(file, before);
92
+ this.check(signal, generation);
93
+ const after = await this.checkedStat(file, generation, signal);
94
+ if (identity(after) !== identity(before) || after.size < before.size) throw failure("ORIGINAL_SOURCE_CHANGED");
95
+ if (this.owner.validatePath !== void 0) await this.owner.validatePath(this.filename);
96
+ } catch (error) {
97
+ failed = true;
98
+ primaryError = error;
99
+ } finally {
100
+ try {
101
+ await file?.close();
102
+ } catch {
103
+ cleanupFailed = true;
104
+ }
105
+ }
106
+ this.check(signal, generation);
107
+ if (failed) {
108
+ if (primaryError instanceof Error && primaryError.message.startsWith("ORIGINAL_")) throw primaryError;
109
+ throw failure("ORIGINAL_SOURCE_UNAVAILABLE");
110
+ }
111
+ if (cleanupFailed) throw failure("ORIGINAL_SOURCE_UNAVAILABLE");
112
+ return result;
113
+ }
114
+ };
115
+
116
+ // packages/agent-core/src/agent/records/original-history.ts
117
+ import { createHash as createHash2 } from "node:crypto";
118
+ import { TextDecoder as TextDecoder2 } from "node:util";
119
+
120
+ // packages/agent-core/src/agent/records/original-history-shell.ts
121
+ function shellHistoryText(text, phase) {
122
+ if (phase === "input") return shellTag(text, "bash-input");
123
+ if (phase === "output") return [shellTag(text, "bash-stdout"), shellTag(text, "bash-stderr")].filter(Boolean).join("\n");
124
+ return "";
125
+ }
126
+ function shellTag(text, tag) {
127
+ return (new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`, "u").exec(text)?.[1] ?? "").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&amp;", "&");
128
+ }
129
+
130
+ // packages/agent-core/src/agent/context/original-sources.ts
131
+ var MAX_COMPACTION_SOURCE_IDS = 1024;
132
+ function isOriginalHistorySourceId(value) {
133
+ return typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u.test(value);
134
+ }
135
+
136
+ // packages/agent-core/src/agent/records/original-frames.ts
137
+ var failure2 = (code) => new Error(code);
138
+ var integer = (n, min, max) => Number.isSafeInteger(n) && n >= min && n <= max;
139
+ var OriginalFrameScanner = class {
140
+ constructor(source) {
141
+ this.source = source;
142
+ }
143
+ source;
144
+ cursors = /* @__PURE__ */ new WeakMap();
145
+ frames = /* @__PURE__ */ new WeakMap();
146
+ open(snapshot, direction) {
147
+ if (direction !== "forward" && direction !== "backward") throw failure2("ORIGINAL_DIRECTION_INVALID");
148
+ if (!integer(snapshot.endByte, 0, Number.MAX_SAFE_INTEGER)) throw failure2("ORIGINAL_SNAPSHOT_INVALID");
149
+ const offset = direction === "forward" ? 0 : snapshot.endByte;
150
+ return this.openAt(snapshot, direction, offset);
151
+ }
152
+ async seek(snapshot, direction, offset, signal) {
153
+ if (direction !== "forward" && direction !== "backward") throw failure2("ORIGINAL_DIRECTION_INVALID");
154
+ this.source.assertCurrent(snapshot, signal);
155
+ const { endByte } = snapshot;
156
+ if (!integer(offset, 0, endByte)) throw failure2("ORIGINAL_FRAME_BOUNDARY_INVALID");
157
+ const atEdge = offset === 0 || offset === endByte;
158
+ const boundary = await this.source.read(snapshot, atEdge ? endByte : offset - 1, 1, signal);
159
+ this.source.assertCurrent(snapshot, signal);
160
+ if (!atEdge && boundary.bytes[0] !== 10) throw failure2("ORIGINAL_FRAME_BOUNDARY_INVALID");
161
+ return this.openAt(snapshot, direction, offset);
162
+ }
163
+ async scan(cursor, options = {}) {
164
+ const input = this.cursors.get(cursor);
165
+ if (input === void 0) throw failure2("ORIGINAL_CURSOR_INVALID");
166
+ const { maxBytes = 262144, maxFrames = 100, signal } = options;
167
+ if (!integer(maxBytes, 1, 262144) || !integer(maxFrames, 1, 100)) throw failure2("ORIGINAL_SCAN_BUDGET_INVALID");
168
+ const state = { ...input }, frames = [];
169
+ let bytesRead = 0;
170
+ await this.validate(state.snapshot, signal);
171
+ while (!state.finished && frames.length < maxFrames) {
172
+ const atBoundary = state.direction === "forward" ? state.position === state.snapshot.endByte : state.position === 0;
173
+ if (atBoundary) {
174
+ if (state.direction === "forward" && state.edge < state.position) {
175
+ frames.push(this.frame(state.snapshot, state.edge, state.position, false));
176
+ } else if (state.direction === "backward" && (state.edge > 0 || state.terminated)) {
177
+ frames.push(this.frame(state.snapshot, 0, state.edge, state.terminated));
178
+ }
179
+ state.finished = true;
180
+ break;
181
+ }
182
+ if (bytesRead >= maxBytes) break;
183
+ const available = state.direction === "forward" ? state.snapshot.endByte - state.position : state.position;
184
+ const length = Math.min(65536, maxBytes - bytesRead, available);
185
+ const start = state.direction === "forward" ? state.position : state.position - length;
186
+ const window = await this.source.read(state.snapshot, start, length, signal);
187
+ signal?.throwIfAborted();
188
+ bytesRead += window.bytes.length;
189
+ if (state.direction === "forward") {
190
+ for (let i = 0; i < window.bytes.length && frames.length < maxFrames; i++) {
191
+ state.position = start + i + 1;
192
+ if (window.bytes[i] === 10) {
193
+ frames.push(this.frame(state.snapshot, state.edge, start + i, true));
194
+ state.edge = state.position;
195
+ }
196
+ }
197
+ if (state.position === state.snapshot.endByte && state.edge === state.position) state.finished = true;
198
+ } else {
199
+ for (let i = window.bytes.length - 1; i >= 0 && frames.length < maxFrames; i--) {
200
+ const absolute = start + i;
201
+ state.position = absolute;
202
+ if (window.bytes[i] === 10) {
203
+ if (state.edge > absolute + 1 || state.terminated) {
204
+ frames.push(this.frame(state.snapshot, absolute + 1, state.edge, state.terminated));
205
+ }
206
+ state.edge = absolute;
207
+ state.terminated = true;
208
+ }
209
+ }
210
+ }
211
+ }
212
+ await this.validate(state.snapshot, signal);
213
+ this.source.assertCurrent(state.snapshot, signal);
214
+ return { frames, nextCursor: state.finished ? void 0 : this.cursor(state), done: state.finished, bytesRead };
215
+ }
216
+ async readFrame(frame, offset, maxBytes, signal) {
217
+ const snapshot = this.frames.get(frame);
218
+ if (snapshot === void 0) throw failure2("ORIGINAL_FRAME_INVALID");
219
+ const length = frame.endByte - frame.startByte;
220
+ if (!integer(offset, 0, length) || !integer(maxBytes, 1, 65536)) throw failure2("ORIGINAL_FRAME_RANGE_INVALID");
221
+ const remaining = length - offset;
222
+ const window = await this.source.read(
223
+ snapshot,
224
+ remaining === 0 ? snapshot.endByte : frame.startByte + offset,
225
+ remaining === 0 ? 1 : Math.min(maxBytes, remaining),
226
+ signal
227
+ );
228
+ await this.validate(snapshot, signal);
229
+ this.source.assertCurrent(snapshot, signal);
230
+ return { bytes: window.bytes, nextOffset: offset + window.bytes.length, atEnd: offset + window.bytes.length === length };
231
+ }
232
+ openAt(snapshot, direction, offset) {
233
+ return this.cursor({ snapshot, direction, position: offset, edge: offset, terminated: false, finished: false });
234
+ }
235
+ async validate(snapshot, signal) {
236
+ await this.source.read(snapshot, snapshot.endByte, 1, signal);
237
+ signal?.throwIfAborted();
238
+ }
239
+ cursor(state) {
240
+ const cursor = Object.freeze({ direction: state.direction, offset: state.position });
241
+ this.cursors.set(cursor, state);
242
+ return cursor;
243
+ }
244
+ frame(snapshot, startByte, endByte, terminated) {
245
+ const frame = Object.freeze({ startByte, endByte, terminated });
246
+ this.frames.set(frame, snapshot);
247
+ return frame;
248
+ }
249
+ };
250
+
251
+ // packages/agent-core/src/agent/records/original-history-checkpoint.ts
252
+ var MAX_CHECKPOINT_RECORD_BYTES = 1024 * 1024;
253
+ var sourceHeader = /^\s*\{\s*"type"\s*:\s*"context\.(?:append_message|append_loop_event|apply_compaction)"\s*,\s*"originalHistorySourceId"\s*:\s*"([a-f0-9-]{36})"/u;
254
+ async function* checkpointSourceFrames(scanner, source, snapshot, start, signal) {
255
+ let cursor = await scanner.seek(snapshot, "backward", start, signal);
256
+ let cache;
257
+ while (cursor !== void 0) {
258
+ const page = await scanner.scan(cursor, { maxBytes: 128 * 1024, maxFrames: 32, signal });
259
+ for (const frame of page.frames) {
260
+ if (!frame.terminated || frame.endByte - frame.startByte > MAX_CHECKPOINT_RECORD_BYTES) continue;
261
+ const end = Math.min(frame.endByte, frame.startByte + 256);
262
+ if (end === frame.startByte) continue;
263
+ if (cache === void 0 || frame.startByte < cache.start || end > cache.start + cache.bytes.length) {
264
+ const start2 = Math.max(0, end - 65536);
265
+ const window = await source.read(snapshot, start2, end - start2, signal);
266
+ cache = { start: start2, bytes: window.bytes };
267
+ }
268
+ const head = cache.bytes.subarray(frame.startByte - cache.start, end - cache.start);
269
+ const id = sourceHeader.exec(Buffer.from(head).toString("utf8"))?.[1];
270
+ if (id !== void 0) yield { frame, id };
271
+ }
272
+ cursor = page.nextCursor;
273
+ }
274
+ }
275
+ function count(value) {
276
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
277
+ }
278
+ function readCheckpointSources(value) {
279
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
280
+ const { recordIds, unlinkedMessages, omittedRecords } = value;
281
+ if (!Array.isArray(recordIds) || recordIds.length > MAX_COMPACTION_SOURCE_IDS || !recordIds.every(isOriginalHistorySourceId) || new Set(recordIds).size !== recordIds.length) return void 0;
282
+ const incompleteMessages = count(unlinkedMessages);
283
+ const omitted = count(omittedRecords);
284
+ if (incompleteMessages === void 0 || omitted === void 0) return void 0;
285
+ return { recordIds, unlinkedMessages: incompleteMessages, omittedRecords: omitted };
286
+ }
287
+ function readCheckpoint(record) {
288
+ if (record?.["type"] !== "context.apply_compaction") return void 0;
289
+ const tokensBefore = count(record["tokensBefore"]);
290
+ const tokensAfter = count(record["tokensAfter"]);
291
+ const compactedCount = count(record["compactedCount"]);
292
+ if (tokensBefore === void 0 || tokensAfter === void 0 || compactedCount === void 0) return void 0;
293
+ const time = count(record["time"]);
294
+ const sources = readCheckpointSources(record["originalHistorySources"]);
295
+ return {
296
+ time: time !== void 0 && time <= 864e13 ? time : void 0,
297
+ tokensBefore,
298
+ tokensAfter,
299
+ compactedCount,
300
+ droppedCount: count(record["droppedCount"]),
301
+ sources: sources === void 0 ? void 0 : {
302
+ records: sources.recordIds.length,
303
+ incompleteMessages: sources.unlinkedMessages,
304
+ omittedRecords: sources.omittedRecords
305
+ }
306
+ };
307
+ }
308
+
309
+ // packages/agent-core/src/logging/formatter.ts
310
+ var REDACTED = "[REDACTED]";
311
+ const SECRET_ASSIGNMENT = /(?<![\w.-])(?<quote>["']?)(?<key>(?:[a-z0-9_.-]*[_.-])?(?<label>authorization|(?:set[-_])?cookie|api[_-]?key|(?:access|refresh|id)[_-]?token|token|password|(?:(?:client|api)[_-]?)?secret))\k<quote>(?!["'\u0060])[ \t]*(?<separator>[:=])[ \t]*/gi;
312
+ const QUOTED_SECRET = /(["'\u0060])(?:\\[^\r\n]|(?!\1)[^\\\r\n])*(?:\1|\\?(?=\r|\n|$))/y;
313
+ const AUTH_VALUE = /((?:bearer|basic)[ \t]+)[^\s"'\u0060,;()[\]{}<>&]+/iy;
314
+ const COOKIE_VALUE = /[!#$%&*+\-.^_|\w]+=[^ \t\r\n"'\u0060,()[\]{}<>;]+(?:[ \t]*;[ \t]*[!#$%&*+\-.^_|\w]+=[^ \t\r\n"'\u0060,()[\]{}<>;]+)*/y;
315
+ const RAW_SECRET = /[^\s"'\u0060,;()[\]{}<>&]+/y;
316
+ const QUERY_SECRET = /[^\s"'\u0060,;()[\]{}<>&#]+/y;
317
+ const NON_SECRET_LITERAL = /^(?:true|false|null|undefined|void|string|number|boolean|bigint|symbol|object|unknown|never|any)$/;
318
+ const JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
319
+ const TYPE_REFERENCE = /^[A-Z][A-Z]*[a-z][a-zA-Z0-9.]*$/;
320
+ const TYPE_DELIMITER = /[ \t]*(?:[;),[<>\]}|&]|$)/y;
321
+ const BARE_LABEL = /^(?:token|password|secret)$/;
322
+ const TOKEN_LIKE = /^(?:[a-f0-9]{12,}|(?=.*[0-9_/+=-]).{12,})$/i;
323
+ const STANDALONE_CREDENTIAL = /(https?:\/\/[^/\\\s:@?#"'\u0060,;()[\]{}<>]+:)[^/\\\s@?#"'\u0060,;()[\]{}<>]+(@)|\b(?:(bot\d{6,}:)[a-z0-9_-]{20,}|(\d{6,}:)AA[a-z0-9_-]{25,}|sk-[a-z0-9_-]{16,}|gh[pousr]_[a-z0-9_]{20,}|github_pat_[a-z0-9_]{22,}|(bearer[ \t]+)(?:eyJ[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+|(?=[a-z0-9._~+/=-]*[0-9_~+/=-])[a-z0-9._~+/=-]{15,}[a-z0-9_~+/=-]))/gi;
324
+ function redactLogText(value) {
325
+ const parts = [];
326
+ const assignments = new RegExp(SECRET_ASSIGNMENT);
327
+ let consumed = 0;
328
+ for (let key; key = assignments.exec(value); ) {
329
+ const start = assignments.lastIndex;
330
+ const field = key.groups?.["key"]?.toLowerCase() ?? "";
331
+ const label = key.groups?.["label"]?.toLowerCase();
332
+ const colon = key.groups?.["separator"] === ":";
333
+ const quotedKey = Boolean(key.groups?.["quote"]);
334
+ const opening = value[start];
335
+ const quoted = opening === '"' || opening === "'" || !colon && opening === "`";
336
+ const prefix = value[key.index - 1];
337
+ const pattern = quoted ? QUOTED_SECRET : label === "authorization" ? AUTH_VALUE : colon && label?.endsWith("cookie") ? COOKIE_VALUE : !colon && (prefix === "?" || prefix === "&") ? QUERY_SECRET : RAW_SECRET;
338
+ pattern.lastIndex = start;
339
+ const matched = pattern.exec(value);
340
+ if (!matched) continue;
341
+ if (colon && pattern === RAW_SECRET) {
342
+ const raw = matched[0];
343
+ if (NON_SECRET_LITERAL.test(raw) || quotedKey && JSON_NUMBER.test(raw)) continue;
344
+ if (!quotedKey) {
345
+ const looksLikeToken = TOKEN_LIKE.test(raw);
346
+ TYPE_DELIMITER.lastIndex = pattern.lastIndex;
347
+ if (!looksLikeToken && TYPE_REFERENCE.test(raw) && TYPE_DELIMITER.test(value)) continue;
348
+ if (BARE_LABEL.test(field) && !looksLikeToken) continue;
349
+ }
350
+ }
351
+ const affix = matched[1] ?? "";
352
+ parts.push(value.slice(consumed, start), affix + REDACTED + (quoted ? affix : ""));
353
+ consumed = assignments.lastIndex = pattern.lastIndex;
354
+ }
355
+ if (consumed > 0) parts.push(value.slice(consumed));
356
+ const text = consumed === 0 ? value : parts.join("");
357
+ return text.replace(STANDALONE_CREDENTIAL, (_match, urlPrefix, at, botPrefix, idPrefix, bearerPrefix) => (urlPrefix ?? botPrefix ?? idPrefix ?? bearerPrefix ?? "") + REDACTED + (at ?? ""));
358
+ }
359
+
360
+ // packages/agent-core/src/agent/records/original-history-record.ts
361
+ var PREVIEW_LENGTH = 240;
362
+ function fields(value) {
363
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
364
+ }
365
+ function contentText(value) {
366
+ return Array.isArray(value) ? value.flatMap((part) => {
367
+ const content = fields(part);
368
+ if (content?.["type"] === "text" && typeof content["text"] === "string") return [content["text"]];
369
+ if (content?.["type"] === "image_url" || content?.["type"] === "video_url" || content?.["type"] === "audio_url") {
370
+ return ["[Attachment]"];
371
+ }
372
+ return [];
373
+ }).join("\n") : "";
374
+ }
375
+ function contentMedia(value) {
376
+ if (!Array.isArray(value)) return [];
377
+ return value.flatMap((part) => {
378
+ const content = fields(part);
379
+ const type = content?.["type"];
380
+ const kind = type === "image_url" ? "image" : type === "audio_url" ? "audio" : type === "video_url" ? "video" : void 0;
381
+ if (content === void 0 || kind === void 0) return [];
382
+ const url = fields(content[kind + "Url"])?.["url"];
383
+ const original = kind === "image" ? content["originalImageRef"] : void 0;
384
+ return [{
385
+ kind,
386
+ url: typeof url === "string" ? url : "",
387
+ originalImageRef: original === void 0 || typeof original === "string" ? original : null
388
+ }];
389
+ });
390
+ }
391
+ function visibleRecord(value) {
392
+ const record = fields(value);
393
+ if (record === void 0) return void 0;
394
+ switch (record["type"]) {
395
+ case "turn.interrupted_output":
396
+ return display("assistant", record["text"]);
397
+ case "context.append_message": {
398
+ const message = fields(record["message"]);
399
+ if (message === void 0) return void 0;
400
+ const origin = fields(message["origin"]);
401
+ const role = message["role"];
402
+ if (role !== "user" && role !== "assistant" && role !== "tool") return void 0;
403
+ const text = contentText(message["content"]);
404
+ if (role === "user" && origin?.["kind"] === "shell_command") {
405
+ return display(origin["phase"] === "input" ? "user" : "output", shellHistoryText(text, origin["phase"]));
406
+ }
407
+ if (message["origin"] !== void 0 && origin?.["kind"] !== "user") return void 0;
408
+ return display(role === "tool" ? "output" : role, role === "user" ? channelMessageText(text) : text, contentMedia(message["content"]));
409
+ }
410
+ case "context.append_loop_event": {
411
+ const event = fields(record["event"]);
412
+ if (event === void 0) return void 0;
413
+ if (event["type"] === "content.part") {
414
+ const part = fields(event["part"]);
415
+ if (part?.["type"] === "text") return display("assistant", part["text"]);
416
+ return display("assistant", contentText([part]), contentMedia([part]));
417
+ }
418
+ if (event["type"] === "tool.call") return display("tool", event["name"]);
419
+ if (event["type"] === "tool.result") {
420
+ const result = fields(event["result"]);
421
+ const output = result?.["output"];
422
+ const visible = display("output", typeof output === "string" ? output : contentText(output), contentMedia(output));
423
+ const storedOutput = result?.["storedOutput"];
424
+ return visible === void 0 || storedOutput === void 0 ? visible : { ...visible, storedOutput };
425
+ }
426
+ return void 0;
427
+ }
428
+ case "context.apply_compaction":
429
+ return { kind: "compaction", text: "" };
430
+ case "context.clear":
431
+ return { kind: "clear", text: "" };
432
+ case "context.undo":
433
+ return { kind: "undo", text: "" };
434
+ default:
435
+ return void 0;
436
+ }
437
+ }
438
+ function channelMessageText(text) {
439
+ const opener = /(?:^|\n)<channel\s+source="(?:telegram|aigramm)"[^>]*>/u.exec(text);
440
+ if (opener === null) return text;
441
+ const start = opener.index + opener[0].length;
442
+ const end = text.lastIndexOf("</channel>");
443
+ return end >= start ? text.slice(start, end).trim() : "";
444
+ }
445
+ function display(kind, text, media) {
446
+ if (typeof text !== "string" || text.trim().length === 0 && (media?.length ?? 0) === 0) return void 0;
447
+ return { kind, text: safeDisplayText(text), media };
448
+ }
449
+ function safeDisplayText(text) {
450
+ const clean = text.replaceAll("\r\n", "\n").replaceAll(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/g, "");
451
+ return redactLogText(clean);
452
+ }
453
+ function preview(text) {
454
+ return text.slice(0, PREVIEW_LENGTH).replace(/[\uD800-\uDBFF]$/u, "");
455
+ }
456
+
457
+ // packages/agent-core/src/agent/records/original-tool-output.ts
458
+ import { createHash } from "node:crypto";
459
+ import { lstat as lstat2 } from "node:fs/promises";
460
+ import { TextDecoder } from "node:util";
461
+
462
+ // node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
463
+ var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
464
+ function normalizeWindowsPath(input = "") {
465
+ if (!input) {
466
+ return input;
467
+ }
468
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
469
+ }
470
+ var _UNC_REGEX = /^[/\\]{2}/;
471
+ var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
472
+ var _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
473
+ var normalize = function(path) {
474
+ if (path.length === 0) {
475
+ return ".";
476
+ }
477
+ path = normalizeWindowsPath(path);
478
+ const isUNCPath = path.match(_UNC_REGEX);
479
+ const isPathAbsolute = isAbsolute(path);
480
+ const trailingSeparator = path[path.length - 1] === "/";
481
+ path = normalizeString(path, !isPathAbsolute);
482
+ if (path.length === 0) {
483
+ if (isPathAbsolute) {
484
+ return "/";
485
+ }
486
+ return trailingSeparator ? "./" : ".";
487
+ }
488
+ if (trailingSeparator) {
489
+ path += "/";
490
+ }
491
+ if (_DRIVE_LETTER_RE.test(path)) {
492
+ path += "/";
493
+ }
494
+ if (isUNCPath) {
495
+ if (!isPathAbsolute) {
496
+ return `//./${path}`;
497
+ }
498
+ return `//${path}`;
499
+ }
500
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
501
+ };
502
+ var join = function(...segments) {
503
+ let path = "";
504
+ for (const seg of segments) {
505
+ if (!seg) {
506
+ continue;
507
+ }
508
+ if (path.length > 0) {
509
+ const pathTrailing = path[path.length - 1] === "/";
510
+ const segLeading = seg[0] === "/";
511
+ const both = pathTrailing && segLeading;
512
+ if (both) {
513
+ path += seg.slice(1);
514
+ } else {
515
+ path += pathTrailing || segLeading ? seg : `/${seg}`;
516
+ }
517
+ } else {
518
+ path += seg;
519
+ }
520
+ }
521
+ return normalize(path);
522
+ };
523
+ function normalizeString(path, allowAboveRoot) {
524
+ let res = "";
525
+ let lastSegmentLength = 0;
526
+ let lastSlash = -1;
527
+ let dots = 0;
528
+ let char = null;
529
+ for (let index = 0; index <= path.length; ++index) {
530
+ if (index < path.length) {
531
+ char = path[index];
532
+ } else if (char === "/") {
533
+ break;
534
+ } else {
535
+ char = "/";
536
+ }
537
+ if (char === "/") {
538
+ if (lastSlash === index - 1 || dots === 1) ;
539
+ else if (dots === 2) {
540
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
541
+ if (res.length > 2) {
542
+ const lastSlashIndex = res.lastIndexOf("/");
543
+ if (lastSlashIndex === -1) {
544
+ res = "";
545
+ lastSegmentLength = 0;
546
+ } else {
547
+ res = res.slice(0, lastSlashIndex);
548
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
549
+ }
550
+ lastSlash = index;
551
+ dots = 0;
552
+ continue;
553
+ } else if (res.length > 0) {
554
+ res = "";
555
+ lastSegmentLength = 0;
556
+ lastSlash = index;
557
+ dots = 0;
558
+ continue;
559
+ }
560
+ }
561
+ if (allowAboveRoot) {
562
+ res += res.length > 0 ? "/.." : "..";
563
+ lastSegmentLength = 2;
564
+ }
565
+ } else {
566
+ if (res.length > 0) {
567
+ res += `/${path.slice(lastSlash + 1, index)}`;
568
+ } else {
569
+ res = path.slice(lastSlash + 1, index);
570
+ }
571
+ lastSegmentLength = index - lastSlash - 1;
572
+ }
573
+ lastSlash = index;
574
+ dots = 0;
575
+ } else if (char === "." && dots !== -1) {
576
+ ++dots;
577
+ } else {
578
+ dots = -1;
579
+ }
580
+ }
581
+ return res;
582
+ }
583
+ var isAbsolute = function(p) {
584
+ return _IS_ABSOLUTE_RE.test(p);
585
+ };
586
+ var dirname = function(p) {
587
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
588
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
589
+ segments[0] += "/";
590
+ }
591
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
592
+ };
593
+
594
+ // packages/agent-core/src/agent/records/original-tool-output.ts
595
+ var FILE = /^[a-zA-Z0-9._-]{1,80}-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}\.txt$/u;
596
+ async function readOriginalToolOutput(directory, reference, signal, validatePath) {
597
+ signal.throwIfAborted();
598
+ if (reference === null || typeof reference !== "object") return void 0;
599
+ const { file, bytes, sha256 } = reference;
600
+ if (typeof file !== "string" || !FILE.test(file) || typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes <= 0 || typeof sha256 !== "string" || !/^[a-f0-9]{64}$/u.test(sha256)) {
601
+ return void 0;
602
+ }
603
+ try {
604
+ const parent = await lstat2(directory, { bigint: true });
605
+ if (!parent.isDirectory()) return void 0;
606
+ const source = new FileOriginalByteSource(join(directory, file), {
607
+ flush: async () => {
608
+ },
609
+ generation: () => 0,
610
+ ...validatePath === void 0 ? {} : { validatePath }
611
+ });
612
+ const snapshot = await source.capture(signal);
613
+ if (snapshot.endByte !== bytes) return void 0;
614
+ const digest = createHash("sha256");
615
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
616
+ const chunks = [];
617
+ let offset = 0;
618
+ while (offset < bytes) {
619
+ const window = await source.read(snapshot, offset, 64 * 1024, signal);
620
+ digest.update(window.bytes);
621
+ chunks.push(decoder.decode(window.bytes, { stream: !window.atEnd }));
622
+ offset = window.nextOffset;
623
+ }
624
+ const after = await lstat2(directory, { bigint: true });
625
+ signal.throwIfAborted();
626
+ if (!after.isDirectory() || after.dev !== parent.dev || after.ino !== parent.ino || after.birthtimeNs !== parent.birthtimeNs || digest.digest("hex") !== sha256) return void 0;
627
+ return chunks.join("");
628
+ } catch {
629
+ signal.throwIfAborted();
630
+ return void 0;
631
+ }
632
+ }
633
+
634
+ // packages/agent-core/src/agent/records/original-history.ts
635
+ var invalidRecord = /* @__PURE__ */ Symbol("invalid record");
636
+ var INLINE_BYTES = 32 * 1024;
637
+ var WINDOW_BYTES = 64 * 1024;
638
+ var PAGE_FRAMES = 32;
639
+ var PAGE_BYTES = 128 * 1024;
640
+ var MAX_EXPORT_ENTRY_BYTES = 16 * 1024 * 1024;
641
+ var OriginalHistoryView = class _OriginalHistoryView {
642
+ #scanner;
643
+ #source;
644
+ #snapshot;
645
+ #lifetime;
646
+ #position;
647
+ #media;
648
+ #toolResultsDir;
649
+ #validatePath;
650
+ #cursors = /* @__PURE__ */ new WeakMap();
651
+ #frames = /* @__PURE__ */ new WeakMap();
652
+ #sourceDigests = /* @__PURE__ */ new WeakMap();
653
+ #attachments = /* @__PURE__ */ new WeakMap();
654
+ constructor(source, snapshot, lifetime, storage) {
655
+ this.#source = source;
656
+ this.#snapshot = snapshot;
657
+ this.#lifetime = lifetime;
658
+ this.#position = storage.position;
659
+ this.#media = storage.media;
660
+ this.#toolResultsDir = storage.toolResultsDir;
661
+ this.#validatePath = storage.validatePath;
662
+ this.#scanner = new OriginalFrameScanner(source);
663
+ }
664
+ static async capture(source, lifetime, signal, storage = {}) {
665
+ const operation = signal === void 0 ? lifetime : AbortSignal.any([lifetime, signal]);
666
+ const snapshot = await source.capture(operation);
667
+ source.assertCurrent(snapshot, operation);
668
+ return new _OriginalHistoryView(source, snapshot, lifetime, storage);
669
+ }
670
+ at(edge) {
671
+ this.#source.assertCurrent(this.#snapshot, this.#lifetime);
672
+ return this.cursor(this.#scanner.open(this.#snapshot, edge === "oldest" ? "forward" : "backward"));
673
+ }
674
+ async read(cursor, signal) {
675
+ const operation = this.operationSignal(signal);
676
+ const start = this.#cursors.get(cursor);
677
+ if (start === void 0) throw new Error("ORIGINAL_HISTORY_CURSOR_INVALID");
678
+ const page = await this.#scanner.scan(start, { maxBytes: PAGE_BYTES, maxFrames: PAGE_FRAMES, signal: operation });
679
+ const entries = [];
680
+ const frames = start.direction === "backward" ? page.frames.toReversed() : page.frames;
681
+ const last = frames.at(-1);
682
+ const decoder = new TextDecoder2("utf-8", { fatal: true });
683
+ let cached;
684
+ for (const frame of frames) {
685
+ if (frame.endByte === frame.startByte) continue;
686
+ if (frame.endByte - frame.startByte > INLINE_BYTES) {
687
+ const head = await this.#scanner.readFrame(frame, 0, 256, operation);
688
+ const type = /^\s*\{\s*"type"\s*:\s*"([a-z_.]+)"/u.exec(Buffer.from(head.bytes).toString("utf8"))?.[1];
689
+ if (type === "context.apply_compaction") {
690
+ entries.push(this.entry(frame, frame.terminated ? "compaction" : "unavailable", "", false));
691
+ } else if (type === void 0 || type === "context.append_message" || type === "context.append_loop_event" || type === "turn.interrupted_output") {
692
+ entries.push(this.entry(frame, "large", "", true));
693
+ }
694
+ continue;
695
+ }
696
+ if (cached === void 0 || frame.endByte > cached.start + cached.bytes.length) {
697
+ const window = await this.#source.read(
698
+ this.#snapshot,
699
+ frame.startByte,
700
+ Math.min(WINDOW_BYTES, last.endByte - frame.startByte),
701
+ operation
702
+ );
703
+ cached = { start: frame.startByte, bytes: window.bytes };
704
+ }
705
+ const record = decodeRecord(decoder, cached.bytes.subarray(frame.startByte - cached.start, frame.endByte - cached.start));
706
+ if (record === invalidRecord) entries.push(this.entry(frame, "unavailable", "", false));
707
+ else if (record !== void 0) entries.push(this.entry(
708
+ frame,
709
+ record.kind,
710
+ preview(record.text),
711
+ record.storedOutput !== void 0 || record.text.length > PREVIEW_LENGTH
712
+ ));
713
+ }
714
+ const continuation = page.nextCursor === void 0 ? void 0 : this.cursor(page.nextCursor);
715
+ const first = frames[0];
716
+ const afterLast = last === void 0 ? void 0 : last.endByte + Number(last.terminated);
717
+ const older = start.direction === "backward" ? continuation : first !== void 0 && first.startByte > 0 ? this.cursor(await this.#scanner.seek(this.#snapshot, "backward", first.startByte, operation)) : void 0;
718
+ const newer = start.direction === "forward" ? continuation : afterLast !== void 0 && afterLast < this.#snapshot.endByte ? this.cursor(await this.#scanner.seek(this.#snapshot, "forward", afterLast, operation)) : void 0;
719
+ this.#source.assertCurrent(this.#snapshot, operation);
720
+ return { entries, older, newer };
721
+ }
722
+ async text(entry, signal) {
723
+ const frame = this.#frames.get(entry);
724
+ if (frame === void 0 || !entry.expandable) throw new Error("ORIGINAL_HISTORY_ENTRY_INVALID");
725
+ const operation = this.operationSignal(signal);
726
+ const result = await this.readRecord(frame, operation, entry);
727
+ this.#source.assertCurrent(this.#snapshot, operation);
728
+ if (result === void 0 || result === invalidRecord) return void 0;
729
+ if (result.storedOutput === void 0) return result.text;
730
+ const text = this.#toolResultsDir === void 0 ? void 0 : await readOriginalToolOutput(this.#toolResultsDir, result.storedOutput, operation, this.#validatePath);
731
+ this.#source.assertCurrent(this.#snapshot, operation);
732
+ if (text === void 0) throw new Error("ORIGINAL_TOOL_OUTPUT_UNAVAILABLE");
733
+ return safeDisplayText(text);
734
+ }
735
+ async *exportEntries(signal) {
736
+ const operation = this.operationSignal(signal);
737
+ let cursor = this.at("oldest");
738
+ while (cursor !== void 0) {
739
+ const page = await this.read(cursor, operation);
740
+ for (const entry of page.entries) {
741
+ this.#source.assertCurrent(this.#snapshot, operation);
742
+ if (entry.kind === "unavailable") {
743
+ yield { kind: "unavailable", reason: "record" };
744
+ continue;
745
+ }
746
+ const frame = this.#frames.get(entry);
747
+ const bytes = frame.endByte - frame.startByte;
748
+ if (!entry.expandable && entry.kind !== "large" && bytes <= INLINE_BYTES) {
749
+ yield { kind: entry.kind, text: entry.preview };
750
+ continue;
751
+ }
752
+ if (bytes > MAX_EXPORT_ENTRY_BYTES) {
753
+ yield { kind: "unavailable", reason: "size" };
754
+ continue;
755
+ }
756
+ const record = await this.readRecord(frame, operation, entry);
757
+ if (record === void 0) continue;
758
+ if (record === invalidRecord) yield { kind: "unavailable", reason: "record" };
759
+ else if (record.storedOutput === void 0) yield { kind: record.kind, text: record.text };
760
+ else {
761
+ const bytes2 = fields(record.storedOutput)?.["bytes"];
762
+ if (typeof bytes2 === "number" && bytes2 > MAX_EXPORT_ENTRY_BYTES) {
763
+ yield { kind: "unavailable", reason: "size" };
764
+ continue;
765
+ }
766
+ const text = this.#toolResultsDir === void 0 ? void 0 : await readOriginalToolOutput(this.#toolResultsDir, record.storedOutput, operation, this.#validatePath);
767
+ yield text === void 0 ? { kind: "unavailable", reason: "tool-output" } : { kind: record.kind, text: safeDisplayText(text) };
768
+ }
769
+ }
770
+ cursor = page.newer;
771
+ }
772
+ this.#source.assertCurrent(this.#snapshot, operation);
773
+ }
774
+ async bookmark(entry, signal) {
775
+ const frame = this.#frames.get(entry);
776
+ if (frame === void 0 || entry.kind === "unavailable") throw new Error("ORIGINAL_HISTORY_ENTRY_INVALID");
777
+ const sha256 = await this.digest(frame, this.operationSignal(signal));
778
+ const expected = this.#sourceDigests.get(entry);
779
+ if (expected !== void 0 && expected !== sha256) throw new Error("ORIGINAL_SOURCE_CHANGED");
780
+ return { startByte: frame.startByte, endByte: frame.endByte, sha256 };
781
+ }
782
+ async checkpoint(entry, signal) {
783
+ return readCheckpoint(await this.checkpointRecord(entry, this.operationSignal(signal)));
784
+ }
785
+ async findCheckpoint(id, signal) {
786
+ if (!isOriginalHistorySourceId(id)) return void 0;
787
+ const operation = this.operationSignal(signal);
788
+ for await (const candidate of checkpointSourceFrames(this.#scanner, this.#source, this.#snapshot, this.#snapshot.endByte, operation)) {
789
+ if (candidate.id !== id) continue;
790
+ const hash = createHash2("sha256");
791
+ const record = fields(await this.readValue(candidate.frame, operation, hash));
792
+ if (record?.["originalHistorySourceId"] !== id || readCheckpoint(record) === void 0) continue;
793
+ this.#source.assertCurrent(this.#snapshot, operation);
794
+ const entry = this.entry(candidate.frame, "compaction", "", false);
795
+ this.#sourceDigests.set(entry, hash.digest("hex"));
796
+ return entry;
797
+ }
798
+ return void 0;
799
+ }
800
+ async *checkpointSources(entry, signal) {
801
+ const operation = this.operationSignal(signal);
802
+ const record = await this.checkpointRecord(entry, operation);
803
+ if (readCheckpoint(record) === void 0) return;
804
+ const ids = new Set(readCheckpointSources(record?.["originalHistorySources"])?.recordIds);
805
+ if (ids.size === 0) return;
806
+ const start = this.#frames.get(entry).startByte;
807
+ for await (const { frame, id } of checkpointSourceFrames(this.#scanner, this.#source, this.#snapshot, start, operation)) {
808
+ if (!ids.has(id)) continue;
809
+ const hash = createHash2("sha256");
810
+ const value = await this.readValue(frame, operation, hash);
811
+ const candidate = fields(value);
812
+ if (candidate?.["originalHistorySourceId"] !== id) continue;
813
+ const visible = visibleRecord(value);
814
+ if (visible === void 0 || visible.kind === "clear" || visible.kind === "undo") continue;
815
+ if (visible.kind === "compaction" && readCheckpoint(candidate) === void 0) continue;
816
+ const sha256 = hash.digest("hex");
817
+ ids.delete(id);
818
+ yield { kind: visible.kind, preview: preview(visible.text), open: (signal2) => this.openSource(
819
+ frame,
820
+ sha256,
821
+ signal2 === void 0 ? operation : AbortSignal.any([operation, signal2])
822
+ ) };
823
+ if (ids.size === 0) return;
824
+ }
825
+ }
826
+ async openSource(frame, sha256, signal) {
827
+ const value = await this.readVerifiedValue(frame, signal, sha256);
828
+ const record = visibleRecord(value);
829
+ if (record === void 0) return void 0;
830
+ const entry = this.entry(
831
+ frame,
832
+ record.kind,
833
+ preview(record.text),
834
+ record.storedOutput !== void 0 || record.text.length > PREVIEW_LENGTH
835
+ );
836
+ this.#sourceDigests.set(entry, sha256);
837
+ return entry;
838
+ }
839
+ async checkpointRecord(entry, operation) {
840
+ const frame = this.#frames.get(entry);
841
+ if (frame === void 0 || entry.kind !== "compaction") throw new Error("ORIGINAL_HISTORY_ENTRY_INVALID");
842
+ this.#source.assertCurrent(this.#snapshot, operation);
843
+ if (!frame.terminated || frame.endByte - frame.startByte > MAX_CHECKPOINT_RECORD_BYTES) return void 0;
844
+ const value = await this.readVerifiedValue(frame, operation, this.#sourceDigests.get(entry));
845
+ this.#source.assertCurrent(this.#snapshot, operation);
846
+ return fields(value);
847
+ }
848
+ async attachments(entry, signal) {
849
+ const frame = this.#frames.get(entry);
850
+ if (frame === void 0) throw new Error("ORIGINAL_HISTORY_ENTRY_INVALID");
851
+ const operation = this.operationSignal(signal);
852
+ const record = await this.readRecord(frame, operation, entry);
853
+ this.#source.assertCurrent(this.#snapshot, operation);
854
+ if (record === void 0 || record === invalidRecord) return [];
855
+ return (record.media ?? []).map((reference) => {
856
+ const attachment = Object.freeze({
857
+ kind: reference.kind,
858
+ original: reference.originalImageRef !== void 0
859
+ });
860
+ this.#attachments.set(attachment, reference);
861
+ return attachment;
862
+ });
863
+ }
864
+ async readAttachment(attachment, signal) {
865
+ const reference = this.#attachments.get(attachment);
866
+ if (reference === void 0) throw new Error("ORIGINAL_HISTORY_ATTACHMENT_INVALID");
867
+ const operation = this.operationSignal(signal);
868
+ this.#source.assertCurrent(this.#snapshot, operation);
869
+ const { kind, url, originalImageRef } = reference;
870
+ const media = originalImageRef === void 0 ? await this.#media?.read(kind, url, operation) : await this.#media?.readOriginalImage(originalImageRef, operation);
871
+ this.#source.assertCurrent(this.#snapshot, operation);
872
+ return media;
873
+ }
874
+ async readAt(bookmark, signal) {
875
+ const operation = this.operationSignal(signal);
876
+ const { startByte, endByte, sha256 } = bookmark;
877
+ if (!Number.isSafeInteger(startByte) || !Number.isSafeInteger(endByte) || startByte < 0 || startByte >= endByte || endByte > this.#snapshot.endByte || typeof sha256 !== "string" || !/^[a-f0-9]{64}$/u.test(sha256)) return void 0;
878
+ let next;
879
+ try {
880
+ next = this.cursor(await this.#scanner.seek(this.#snapshot, "forward", startByte, operation));
881
+ } catch (error) {
882
+ if (error instanceof Error && error.message === "ORIGINAL_FRAME_BOUNDARY_INVALID") return void 0;
883
+ throw error;
884
+ }
885
+ while (next !== void 0) {
886
+ const page = await this.read(next, operation);
887
+ const first = page.entries[0];
888
+ if (first !== void 0) {
889
+ const frame = this.#frames.get(first);
890
+ if (first.kind === "unavailable" || frame.startByte !== startByte || frame.endByte !== endByte || await this.digest(frame, operation) !== sha256) return void 0;
891
+ return page;
892
+ }
893
+ next = page.newer;
894
+ if (next !== void 0 && this.#cursors.get(next).offset > endByte) return void 0;
895
+ }
896
+ return void 0;
897
+ }
898
+ async restorePosition(signal) {
899
+ const operation = this.operationSignal(signal);
900
+ const position = await this.#position?.read(operation);
901
+ if (position === void 0) return void 0;
902
+ const page = await this.readAt(position.bookmark, operation);
903
+ return page === void 0 ? void 0 : { page, detailOffset: position.detailOffset };
904
+ }
905
+ async savePosition(entry, detailOffset) {
906
+ if (this.#position === void 0) return;
907
+ if (detailOffset !== void 0 && (!Number.isSafeInteger(detailOffset) || detailOffset < 0)) {
908
+ throw new Error("ORIGINAL_HISTORY_OFFSET_INVALID");
909
+ }
910
+ const bookmark = await this.bookmark(entry);
911
+ this.#source.assertCurrent(this.#snapshot, this.#lifetime);
912
+ await this.#position.write({ bookmark, detailOffset }, this.#lifetime);
913
+ }
914
+ async search(query, cursor, signal) {
915
+ const term = query.trim();
916
+ if (term.length === 0) throw new Error("ORIGINAL_HISTORY_QUERY_EMPTY");
917
+ const literal = term.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
918
+ const pattern = new RegExp(literal, "iu");
919
+ const operation = this.operationSignal(signal);
920
+ const start = cursor ?? this.at("latest");
921
+ if (start.direction !== "backward") throw new Error("ORIGINAL_HISTORY_CURSOR_INVALID");
922
+ const page = await this.read(start, operation);
923
+ const matches = [];
924
+ for (const entry of page.entries.toReversed()) {
925
+ const text = entry.expandable ? await this.text(entry, operation).catch((error) => {
926
+ if (error instanceof Error && error.message === "ORIGINAL_TOOL_OUTPUT_UNAVAILABLE") return void 0;
927
+ throw error;
928
+ }) : entry.preview;
929
+ if (text === void 0) continue;
930
+ const match = pattern.exec(text);
931
+ if (match !== null) {
932
+ const offset = match.index;
933
+ const startOfExcerpt = Math.max(0, offset - 40);
934
+ matches.push({ entry, offset, preview: preview(text.slice(startOfExcerpt)) });
935
+ }
936
+ }
937
+ this.#source.assertCurrent(this.#snapshot, operation);
938
+ return { matches, older: page.older };
939
+ }
940
+ operationSignal(signal) {
941
+ return signal === void 0 ? this.#lifetime : AbortSignal.any([this.#lifetime, signal]);
942
+ }
943
+ cursor(value) {
944
+ const cursor = Object.freeze({ direction: value.direction });
945
+ this.#cursors.set(cursor, value);
946
+ return cursor;
947
+ }
948
+ entry(frame, kind, text, expandable) {
949
+ const entry = Object.freeze({ kind, preview: text, expandable });
950
+ this.#frames.set(entry, frame);
951
+ return entry;
952
+ }
953
+ async readRecord(frame, signal, entry) {
954
+ const value = await this.readVerifiedValue(frame, signal, this.#sourceDigests.get(entry));
955
+ return value === invalidRecord ? invalidRecord : visibleRecord(value);
956
+ }
957
+ async readVerifiedValue(frame, signal, expected) {
958
+ const hash = expected === void 0 ? void 0 : createHash2("sha256");
959
+ const value = await this.readValue(frame, signal, hash);
960
+ return hash === void 0 || hash.digest("hex") === expected ? value : invalidRecord;
961
+ }
962
+ async readValue(frame, signal, hash) {
963
+ const decoder = new TextDecoder2("utf-8", { fatal: true });
964
+ const chunks = [];
965
+ let offset = 0;
966
+ while (offset < frame.endByte - frame.startByte) {
967
+ const window = await this.#scanner.readFrame(frame, offset, WINDOW_BYTES, signal);
968
+ hash?.update(window.bytes);
969
+ try {
970
+ chunks.push(decoder.decode(window.bytes, { stream: !window.atEnd }));
971
+ } catch {
972
+ return invalidRecord;
973
+ }
974
+ offset = window.nextOffset;
975
+ }
976
+ return parseValue(chunks.join(""));
977
+ }
978
+ async digest(frame, signal) {
979
+ const hash = createHash2("sha256");
980
+ let offset = 0;
981
+ while (offset < frame.endByte - frame.startByte) {
982
+ const window = await this.#scanner.readFrame(frame, offset, WINDOW_BYTES, signal);
983
+ hash.update(window.bytes);
984
+ offset = window.nextOffset;
985
+ }
986
+ this.#source.assertCurrent(this.#snapshot, signal);
987
+ return hash.digest("hex");
988
+ }
989
+ };
990
+ function decodeRecord(decoder, bytes) {
991
+ try {
992
+ return parseRecord(decoder.decode(bytes));
993
+ } catch {
994
+ return invalidRecord;
995
+ }
996
+ }
997
+ function parseRecord(text) {
998
+ const value = parseValue(text);
999
+ return value === invalidRecord ? invalidRecord : visibleRecord(value);
1000
+ }
1001
+ function parseValue(text) {
1002
+ try {
1003
+ return JSON.parse(text);
1004
+ } catch {
1005
+ return invalidRecord;
1006
+ }
1007
+ }
1008
+
1009
+ // packages/agent-core/src/agent/records/original-history-media.ts
1010
+ import { createHash as createHash3 } from "node:crypto";
1011
+ import { lstat as lstat3, mkdir } from "node:fs/promises";
1012
+
1013
+ // packages/agent-core/src/tools/support/file-type.ts
1014
+ var MEDIA_SNIFF_BYTES = 512;
1015
+ var IMAGE_MIME_BY_SUFFIX = Object.freeze({
1016
+ ".png": "image/png",
1017
+ ".jpg": "image/jpeg",
1018
+ ".jpeg": "image/jpeg",
1019
+ ".gif": "image/gif",
1020
+ ".bmp": "image/bmp",
1021
+ ".tif": "image/tiff",
1022
+ ".tiff": "image/tiff",
1023
+ ".webp": "image/webp",
1024
+ ".ico": "image/x-icon",
1025
+ ".heic": "image/heic",
1026
+ ".heif": "image/heif",
1027
+ ".avif": "image/avif",
1028
+ ".svgz": "image/svg+xml"
1029
+ });
1030
+ var VIDEO_MIME_BY_SUFFIX = Object.freeze({
1031
+ ".mp4": "video/mp4",
1032
+ ".mpg": "video/mpeg",
1033
+ ".mpeg": "video/mpeg",
1034
+ ".mkv": "video/x-matroska",
1035
+ ".avi": "video/x-msvideo",
1036
+ ".mov": "video/quicktime",
1037
+ ".ogv": "video/ogg",
1038
+ ".wmv": "video/x-ms-wmv",
1039
+ ".webm": "video/webm",
1040
+ ".m4v": "video/x-m4v",
1041
+ ".flv": "video/x-flv",
1042
+ ".3gp": "video/3gpp",
1043
+ ".3g2": "video/3gpp2"
1044
+ });
1045
+ var TEXT_MIME_BY_SUFFIX = Object.freeze({
1046
+ ".svg": "image/svg+xml"
1047
+ });
1048
+ var ASF_HEADER = Buffer.from([
1049
+ 48,
1050
+ 38,
1051
+ 178,
1052
+ 117,
1053
+ 142,
1054
+ 102,
1055
+ 207,
1056
+ 17,
1057
+ 166,
1058
+ 217,
1059
+ 0,
1060
+ 170,
1061
+ 0,
1062
+ 98,
1063
+ 206,
1064
+ 108
1065
+ ]);
1066
+ var FTYP_IMAGE_BRANDS = Object.freeze({
1067
+ avif: "image/avif",
1068
+ avis: "image/avif",
1069
+ heic: "image/heic",
1070
+ heif: "image/heif",
1071
+ heix: "image/heif",
1072
+ hevc: "image/heic",
1073
+ mif1: "image/heif",
1074
+ msf1: "image/heif"
1075
+ });
1076
+ var FTYP_VIDEO_BRANDS = Object.freeze({
1077
+ isom: "video/mp4",
1078
+ iso2: "video/mp4",
1079
+ iso5: "video/mp4",
1080
+ mp41: "video/mp4",
1081
+ mp42: "video/mp4",
1082
+ avc1: "video/mp4",
1083
+ mp4v: "video/mp4",
1084
+ m4v: "video/x-m4v",
1085
+ qt: "video/quicktime",
1086
+ "3gp4": "video/3gpp",
1087
+ "3gp5": "video/3gpp",
1088
+ "3gp6": "video/3gpp",
1089
+ "3gp7": "video/3gpp",
1090
+ "3g2": "video/3gpp2"
1091
+ });
1092
+ function toBuffer(data) {
1093
+ return Buffer.isBuffer(data) ? data : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
1094
+ }
1095
+ function startsWith(buf, prefix) {
1096
+ const needle = Buffer.isBuffer(prefix) ? prefix : Buffer.from(prefix);
1097
+ if (buf.length < needle.length) return false;
1098
+ for (let i = 0; i < needle.length; i += 1) {
1099
+ if (buf[i] !== needle[i]) return false;
1100
+ }
1101
+ return true;
1102
+ }
1103
+ function sniffFtypBrand(header) {
1104
+ if (header.length < 12) return null;
1105
+ if (header.subarray(4, 8).toString("latin1") !== "ftyp") return null;
1106
+ const raw = header.subarray(8, 12).toString("latin1").toLowerCase();
1107
+ return raw.replaceAll(/[\s\u0000]+$/g, "").trim();
1108
+ }
1109
+ function sniffMediaFromMagic(data) {
1110
+ const buf = toBuffer(data);
1111
+ const header = buf.length > MEDIA_SNIFF_BYTES ? buf.subarray(0, MEDIA_SNIFF_BYTES) : buf;
1112
+ if (startsWith(header, [137, 80, 78, 71, 13, 10, 26, 10])) {
1113
+ return { kind: "image", mimeType: "image/png" };
1114
+ }
1115
+ if (startsWith(header, [255, 216, 255])) {
1116
+ return { kind: "image", mimeType: "image/jpeg" };
1117
+ }
1118
+ if (startsWith(header, Buffer.from("GIF87a")) || startsWith(header, Buffer.from("GIF89a"))) {
1119
+ return { kind: "image", mimeType: "image/gif" };
1120
+ }
1121
+ if (startsWith(header, Buffer.from("BM"))) {
1122
+ return { kind: "image", mimeType: "image/bmp" };
1123
+ }
1124
+ if (startsWith(header, [73, 73, 42, 0]) || startsWith(header, [77, 77, 0, 42])) {
1125
+ return { kind: "image", mimeType: "image/tiff" };
1126
+ }
1127
+ if (startsWith(header, [0, 0, 1, 0])) {
1128
+ return { kind: "image", mimeType: "image/x-icon" };
1129
+ }
1130
+ if (startsWith(header, Buffer.from("RIFF")) && header.length >= 12) {
1131
+ const chunk = header.subarray(8, 12).toString("latin1");
1132
+ if (chunk === "WEBP") return { kind: "image", mimeType: "image/webp" };
1133
+ if (chunk === "AVI ") return { kind: "video", mimeType: "video/x-msvideo" };
1134
+ }
1135
+ if (startsWith(header, Buffer.from("FLV"))) {
1136
+ return { kind: "video", mimeType: "video/x-flv" };
1137
+ }
1138
+ if (startsWith(header, ASF_HEADER)) {
1139
+ return { kind: "video", mimeType: "video/x-ms-wmv" };
1140
+ }
1141
+ if (startsWith(header, [26, 69, 223, 163])) {
1142
+ const lowered = header.toString("latin1").toLowerCase();
1143
+ if (lowered.includes("webm")) return { kind: "video", mimeType: "video/webm" };
1144
+ if (lowered.includes("matroska")) return { kind: "video", mimeType: "video/x-matroska" };
1145
+ }
1146
+ const brand = sniffFtypBrand(header);
1147
+ if (brand !== null && brand !== "") {
1148
+ if (brand in FTYP_IMAGE_BRANDS) {
1149
+ return { kind: "image", mimeType: FTYP_IMAGE_BRANDS[brand] };
1150
+ }
1151
+ if (brand in FTYP_VIDEO_BRANDS) {
1152
+ return { kind: "video", mimeType: FTYP_VIDEO_BRANDS[brand] };
1153
+ }
1154
+ }
1155
+ return null;
1156
+ }
1157
+
1158
+ // packages/agent-core/src/utils/fs.ts
1159
+ import { randomBytes } from "node:crypto";
1160
+ import * as nodeFs from "node:fs";
1161
+ import { open as open2, rename, unlink } from "node:fs/promises";
1162
+ async function syncDir(dirPath) {
1163
+ if (process.platform === "win32") return;
1164
+ const dirFh = await open2(dirPath, "r");
1165
+ try {
1166
+ await dirFh.sync();
1167
+ } finally {
1168
+ await dirFh.close();
1169
+ }
1170
+ }
1171
+ function syncFd(fd) {
1172
+ return new Promise((resolve2, reject) => {
1173
+ nodeFs.fsync(fd, (err) => {
1174
+ if (err) {
1175
+ reject(err);
1176
+ return;
1177
+ }
1178
+ resolve2();
1179
+ });
1180
+ });
1181
+ }
1182
+ async function atomicWrite(filePath, content, _syncOverride) {
1183
+ const hex = randomBytes(4).toString("hex");
1184
+ const tmpPath = `${filePath}.tmp.${process.pid}.${hex}`;
1185
+ let renamed = false;
1186
+ try {
1187
+ const fh = await open2(tmpPath, "w");
1188
+ try {
1189
+ await fh.writeFile(content);
1190
+ await (_syncOverride ?? syncFd)(fh.fd);
1191
+ } finally {
1192
+ await fh.close();
1193
+ }
1194
+ if (process.platform === "win32") {
1195
+ try {
1196
+ await unlink(filePath);
1197
+ } catch (error) {
1198
+ const code = error.code;
1199
+ if (code !== "ENOENT") throw error;
1200
+ }
1201
+ }
1202
+ await rename(tmpPath, filePath);
1203
+ renamed = true;
1204
+ } finally {
1205
+ if (!renamed) {
1206
+ try {
1207
+ await unlink(tmpPath);
1208
+ } catch {
1209
+ }
1210
+ }
1211
+ }
1212
+ }
1213
+
1214
+ // packages/agent-core/src/agent/records/original-history-media.ts
1215
+ var STORED_TYPES = /* @__PURE__ */ new Map([
1216
+ ["image/png", "png"],
1217
+ ["image/jpeg", "jpg"],
1218
+ ["image/jpg", "jpg"],
1219
+ ["image/gif", "gif"],
1220
+ ["image/webp", "webp"],
1221
+ ["image/bmp", "bmp"],
1222
+ ["image/tiff", "tif"],
1223
+ ["audio/mpeg", "mp3"],
1224
+ ["audio/mp4", "m4a"],
1225
+ ["audio/wav", "wav"],
1226
+ ["audio/x-wav", "wav"],
1227
+ ["audio/ogg", "ogg"],
1228
+ ["audio/webm", "webm"],
1229
+ ["audio/flac", "flac"],
1230
+ ["video/mp4", "mp4"],
1231
+ ["video/webm", "webm"],
1232
+ ["video/quicktime", "mov"]
1233
+ ]);
1234
+ var INLINE_PREFIX = /^data:([a-z]+\/[a-z0-9.+-]+);base64,/i;
1235
+ var BLOB_REF = /^blobref:([a-z]+\/[a-z0-9.+-]+);([a-f0-9]{64})$/i;
1236
+ var ORIGINAL_IMAGE_REF = /^([a-f0-9]{32})\.(png|jpg|gif|webp|bmp|tif)$/u;
1237
+ function agreesWithMediaHeader(bytes, mime) {
1238
+ const header = bytes.subarray(0, 12).toString("latin1");
1239
+ switch (mime) {
1240
+ case "audio/flac":
1241
+ return header.startsWith("fLaC");
1242
+ case "audio/ogg":
1243
+ return header.startsWith("OggS");
1244
+ case "audio/wav":
1245
+ case "audio/x-wav":
1246
+ return header.startsWith("RIFF") && header.endsWith("WAVE");
1247
+ case "audio/mp4":
1248
+ return header.slice(4) === "ftypM4A ";
1249
+ case "audio/mpeg":
1250
+ return header.startsWith("ID3") || bytes.length >= 4 && bytes[0] === 255 && (bytes[1] & 224) === 224 && (bytes[1] & 6) !== 0 && (bytes[2] & 240) !== 240;
1251
+ case "audio/webm":
1252
+ return sniffMediaFromMagic(bytes)?.mimeType === "video/webm";
1253
+ default:
1254
+ return sniffMediaFromMagic(bytes)?.mimeType === (mime === "image/jpg" ? "image/jpeg" : mime);
1255
+ }
1256
+ }
1257
+ var OriginalHistoryMediaSource = class {
1258
+ constructor(blobsDir, attachmentsDir, originalsDir) {
1259
+ this.blobsDir = blobsDir;
1260
+ this.attachmentsDir = attachmentsDir;
1261
+ this.originalsDir = originalsDir;
1262
+ }
1263
+ blobsDir;
1264
+ attachmentsDir;
1265
+ originalsDir;
1266
+ async readOriginalImage(reference, signal) {
1267
+ signal.throwIfAborted();
1268
+ const match = reference === null ? null : ORIGINAL_IMAGE_REF.exec(reference);
1269
+ if (match === null || this.originalsDir === void 0) return void 0;
1270
+ const { originalsDir } = this;
1271
+ const hash = createHash3("sha256");
1272
+ let mime;
1273
+ const read = await this.readFile(originalsDir, match[0], signal, (chunk, offset) => {
1274
+ if (offset === 0) {
1275
+ const header = sniffMediaFromMagic(chunk);
1276
+ if (header?.kind === "image") mime = header.mimeType;
1277
+ }
1278
+ hash.update(chunk);
1279
+ });
1280
+ if (!read || mime === void 0 || STORED_TYPES.get(mime) !== match[2] || !hash.digest("hex").startsWith(match[1])) return void 0;
1281
+ return { kind: "image", mime, path: join(originalsDir, match[0]) };
1282
+ }
1283
+ async read(kind, url, signal) {
1284
+ signal.throwIfAborted();
1285
+ const inline = INLINE_PREFIX.exec(url);
1286
+ const blob = inline === null ? BLOB_REF.exec(url) : null;
1287
+ const mime = (inline?.[1] ?? blob?.[1])?.toLowerCase();
1288
+ const extension = mime === void 0 ? void 0 : STORED_TYPES.get(mime);
1289
+ if (mime === void 0 || !mime.startsWith(kind + "/") || extension === void 0) return void 0;
1290
+ let bytes;
1291
+ if (inline !== null) {
1292
+ const payload = url.slice(inline[0].length);
1293
+ bytes = Buffer.from(payload, "base64");
1294
+ if (bytes.length === 0 || bytes.toString("base64") !== payload) return void 0;
1295
+ } else if (blob !== null) {
1296
+ bytes = await this.readBlob(blob[2].toLowerCase(), signal);
1297
+ }
1298
+ if (bytes === void 0 || !agreesWithMediaHeader(bytes, mime)) return void 0;
1299
+ const path = await this.materialize(bytes, extension, signal);
1300
+ return path === void 0 ? void 0 : { kind, mime, path };
1301
+ }
1302
+ async materialize(bytes, extension, signal) {
1303
+ try {
1304
+ signal.throwIfAborted();
1305
+ await mkdir(this.attachmentsDir, { recursive: true, mode: 448 });
1306
+ if (!(await lstat3(this.attachmentsDir)).isDirectory()) return void 0;
1307
+ const digest = createHash3("sha256").update(bytes).digest("hex");
1308
+ const name = digest + "." + extension;
1309
+ const path = join(this.attachmentsDir, name);
1310
+ const existing = await lstat3(path).catch((error) => {
1311
+ if (error.code === "ENOENT") return void 0;
1312
+ throw error;
1313
+ });
1314
+ if (existing !== void 0) {
1315
+ const digestOnDisk = createHash3("sha256");
1316
+ const readable = await this.readFile(this.attachmentsDir, name, signal, (chunk) => {
1317
+ digestOnDisk.update(chunk);
1318
+ });
1319
+ return readable && digestOnDisk.digest("hex") === digest ? path : void 0;
1320
+ }
1321
+ signal.throwIfAborted();
1322
+ await atomicWrite(path, bytes);
1323
+ await syncDir(this.attachmentsDir);
1324
+ signal.throwIfAborted();
1325
+ return path;
1326
+ } catch {
1327
+ signal.throwIfAborted();
1328
+ return void 0;
1329
+ }
1330
+ }
1331
+ async readBlob(hash, signal) {
1332
+ const chunks = [];
1333
+ const read = await this.readFile(this.blobsDir, hash, signal, (chunk) => {
1334
+ chunks.push(chunk);
1335
+ });
1336
+ if (!read) return void 0;
1337
+ const bytes = Buffer.concat(chunks);
1338
+ const actual = createHash3("sha256").update(bytes.toString("base64")).digest("hex");
1339
+ signal.throwIfAborted();
1340
+ return actual === hash ? bytes : void 0;
1341
+ }
1342
+ async readFile(directory, name, signal, onChunk) {
1343
+ try {
1344
+ const ownedDirectory = await lstat3(directory, { bigint: true });
1345
+ if (!ownedDirectory.isDirectory()) return false;
1346
+ const file = join(directory, name);
1347
+ const entry = await lstat3(file, { bigint: true });
1348
+ if (!entry.isFile() || entry.nlink !== 1n) return false;
1349
+ const source = new FileOriginalByteSource(file, { flush: async () => {
1350
+ }, generation: () => 0 });
1351
+ const snapshot = await source.capture(signal);
1352
+ if (snapshot.endByte === 0) return false;
1353
+ let offset = 0;
1354
+ while (offset < snapshot.endByte) {
1355
+ const window = await source.read(snapshot, offset, 64 * 1024, signal);
1356
+ onChunk(window.bytes, offset);
1357
+ offset = window.nextOffset;
1358
+ }
1359
+ const after = await lstat3(directory, { bigint: true });
1360
+ signal.throwIfAborted();
1361
+ return after.isDirectory() && after.dev === ownedDirectory.dev && after.ino === ownedDirectory.ino;
1362
+ } catch {
1363
+ signal.throwIfAborted();
1364
+ return false;
1365
+ }
1366
+ }
1367
+ };
1368
+
1369
+ // packages/agent-core/src/agent/records/original-history-position.ts
1370
+ import { lstat as lstat4 } from "node:fs/promises";
1371
+ var MAX_POSITION_BYTES = 1024;
1372
+ var OriginalHistoryPositionFile = class {
1373
+ constructor(path) {
1374
+ this.path = path;
1375
+ }
1376
+ path;
1377
+ async read(signal) {
1378
+ const source = new FileOriginalByteSource(this.path, { flush: async () => {
1379
+ }, generation: () => 0 });
1380
+ try {
1381
+ signal.throwIfAborted();
1382
+ if (!(await lstat4(this.path)).isFile()) return void 0;
1383
+ const snapshot = await source.capture(signal);
1384
+ if (snapshot.endByte === 0 || snapshot.endByte > MAX_POSITION_BYTES) return void 0;
1385
+ const { bytes } = await source.read(snapshot, 0, MAX_POSITION_BYTES, signal);
1386
+ const value = JSON.parse(Buffer.from(bytes).toString("utf8"));
1387
+ if (value?.version !== 1 || value.bookmark === null || typeof value.bookmark !== "object") return void 0;
1388
+ const { detailOffset } = value;
1389
+ if (detailOffset !== void 0 && (!Number.isSafeInteger(detailOffset) || detailOffset < 0)) return void 0;
1390
+ return { bookmark: value.bookmark, detailOffset };
1391
+ } catch {
1392
+ signal.throwIfAborted();
1393
+ return void 0;
1394
+ }
1395
+ }
1396
+ async write(position, signal) {
1397
+ signal.throwIfAborted();
1398
+ await atomicWrite(this.path, JSON.stringify({ version: 1, ...position }) + "\n");
1399
+ await syncDir(dirname(this.path));
1400
+ signal.throwIfAborted();
1401
+ }
1402
+ };
1403
+
1404
+ // original-history-entry.ts
1405
+ function createJournalReader(filename, flush, generation, mediaOriginalsDir) {
1406
+ const path = dirname2(filename);
1407
+ const source = new FileOriginalByteSource(filename, { flush, generation });
1408
+ const storage = {
1409
+ position: new OriginalHistoryPositionFile(join2(path, "original-history-position.json")),
1410
+ media: new OriginalHistoryMediaSource(join2(path, "blobs"), join2(path, "history-attachments"), mediaOriginalsDir),
1411
+ toolResultsDir: join2(path, "tool-results")
1412
+ };
1413
+ return {
1414
+ open: (lifetime, signal) => OriginalHistoryView.capture(source, lifetime, signal, storage),
1415
+ dispose: () => source.dispose()
1416
+ };
1417
+ }
1418
+ export {
1419
+ createJournalReader
1420
+ };