@kabxx/dsh-message-revision 0.1.0 → 0.1.1

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,521 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readSync } from 'node:fs';
3
+ import { lstat, open, unlink } from 'node:fs/promises';
4
+ import { basename, dirname, isAbsolute } from 'node:path';
5
+ import { Readable } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { promisify } from 'node:util';
8
+ import { constants, createZstdDecompress, zstdCompress, zstdDecompressSync } from 'node:zlib';
9
+ import { isCanonicalPath, openReadOnlyFlags } from './platform.js';
10
+
11
+ const compress = promisify(zstdCompress);
12
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
13
+ const chunkBytes = 128 * 1024;
14
+ const inlineZstdOutputBytes = 256 * 1024;
15
+ const frameBytes = 512 * 1024;
16
+ const maxCandidateBytes = 256 * 1024 * 1024;
17
+ const zstdMagic = 0xFD2FB528;
18
+ const zstdSkippableMask = 0xFFFFFFF0;
19
+ const zstdSkippableMagic = 0x184D2A50;
20
+ export const maxRecordBytes = 16 * 1024 * 1024;
21
+ export const nativeLogName = /^session\.v4\.jsonl(?:\.zstd)?$/u;
22
+ export const legacyLogName = /^session\.v3\.jsonl(?:\.zstd)?$/u;
23
+
24
+ export function requireRollout(condition, message) {
25
+ if (!condition) throw new Error(message);
26
+ }
27
+
28
+ /** Compare opened files by native identity while keeping the wire representation JSON-safe. */
29
+ export function fileIdentity(stat) {
30
+ return Object.fromEntries(['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].map(key => [key, String(stat[key])]));
31
+ }
32
+
33
+ function sameIdentity(stat, expected) {
34
+ return Object.entries(fileIdentity(stat)).every(([key, value]) => expected[key] === value);
35
+ }
36
+
37
+ export async function checkRolloutIdentity(path, expected) {
38
+ const stat = await lstat(path, { bigint: true });
39
+ requireRollout(stat.isFile() && await isCanonicalPath(path) && sameIdentity(stat, expected),
40
+ '会话日志在检查期间已变化,请重新打开编辑框。');
41
+ }
42
+
43
+ /** Stream a single native event row at a time. Legacy generations are read-only. */
44
+ export async function* readRolloutLines(path, sessionId, { allowLegacy = false, trackZstdPrefix = false } = {}) {
45
+ requireRollout(typeof path === 'string' && isAbsolute(path), '会话日志路径或格式异常。');
46
+ const name = basename(path);
47
+ const expectedVersion = nativeLogName.test(name) ? 4 : allowLegacy && legacyLogName.test(name) ? 3 : undefined;
48
+ requireRollout(expectedVersion !== undefined && await isCanonicalPath(path), '会话日志路径或格式异常。');
49
+ const file = await open(path, openReadOnlyFlags());
50
+ try {
51
+ const initial = await file.stat({ bigint: true });
52
+ requireRollout(initial.isFile() && initial.size <= BigInt(Number.MAX_SAFE_INTEGER), '会话日志路径或大小异常。');
53
+ const identity = fileIdentity(initial);
54
+ await checkRolloutIdentity(path, identity);
55
+ const fileSize = Number(initial.size);
56
+ let fragments = [];
57
+ let bytes = 0;
58
+ let index = -1;
59
+ let framePrefix;
60
+ let reusable = true;
61
+ function onFrame(offset, frame) {
62
+ // A prefix can only end between records. The preceding frames have
63
+ // already passed decoding and checksum verification in this scan.
64
+ if (reusable && index > 0 && bytes === 0 && offset <= maxCandidateBytes) {
65
+ framePrefix = { end: offset, startSeq: index };
66
+ }
67
+ reusable &&= frame.reusable === true;
68
+ }
69
+ const chunks = path.endsWith('.zstd')
70
+ ? streamZstdChunks(file, 0, fileSize, trackZstdPrefix ? onFrame : undefined)
71
+ : readFrameChunks(file, 0, fileSize);
72
+ for await (const chunk of chunks) {
73
+ let start = 0;
74
+ while (start < chunk.length) {
75
+ const newline = chunk.indexOf(0x0a, start);
76
+ const end = newline < 0 ? chunk.length : newline + 1;
77
+ const part = chunk.subarray(start, end);
78
+ bytes += part.length;
79
+ requireRollout(bytes <= maxRecordBytes, '会话含有超过 16 MiB 的单条记录,无法安全编辑。');
80
+ if (newline === -1) {
81
+ fragments.push(part);
82
+ } else {
83
+ const line = fragments.length ? Buffer.concat([...fragments, part], bytes) : part;
84
+ fragments = [];
85
+ bytes = 0;
86
+ const record = JSON.parse(utf8.decode(line));
87
+ requireRollout(record && typeof record === 'object' && !Array.isArray(record), '会话日志内含无效记录。');
88
+ if (index === -1) {
89
+ requireRollout(record.type === 'session' && record.version === expectedVersion && record.id === sessionId,
90
+ '会话日志文件头不匹配。');
91
+ if (expectedVersion === 3) {
92
+ requireRollout(record.origin === 'subagent' && typeof record.parentSession === 'string'
93
+ && typeof record.isSeeded === 'boolean' && Number.isSafeInteger(record.createdAt) && record.createdAt >= 0
94
+ && Number.isSafeInteger(record.delegationDepth) && record.delegationDepth > 0,
95
+ '无法核对旧版子会话日志的身份。');
96
+ }
97
+ } else {
98
+ requireRollout(record.seq === index && typeof record.type === 'string' && Number.isSafeInteger(record.time)
99
+ && record.time >= 0 && Object.hasOwn(record, 'data'), '会话日志的事件顺序或记录无效。');
100
+ }
101
+ yield { record, line, index, identity, framePrefix };
102
+ index++;
103
+ }
104
+ start = end;
105
+ }
106
+ }
107
+ requireRollout(index >= 0 && bytes === 0, '会话日志不完整,已取消编辑。');
108
+ await checkRolloutIdentity(path, identity);
109
+ } finally {
110
+ await file.close();
111
+ }
112
+ }
113
+
114
+ function readExactSync(fd, buf, len, pos) {
115
+ let offset = 0;
116
+ while (offset < len) {
117
+ const bytesRead = readSync(fd, buf, offset, len - offset, pos + offset);
118
+ if (bytesRead <= 0) return null;
119
+ offset += bytesRead;
120
+ }
121
+ return buf.subarray(0, len);
122
+ }
123
+
124
+ function makeBufferedSlice(fd, fileSize) {
125
+ const buf = Buffer.allocUnsafe(chunkBytes);
126
+ let bufStart = 0;
127
+ let bufEnd = 0;
128
+ return function readSlice(pos, len) {
129
+ if (len === 0) return buf.subarray(0, 0);
130
+ if (pos < 0 || len > chunkBytes || pos + len > fileSize) return null;
131
+ if (pos < bufStart || pos + len > bufEnd) {
132
+ const want = Math.min(chunkBytes, fileSize - pos);
133
+ let filled = 0;
134
+ while (filled < len) {
135
+ const bytesRead = readSync(fd, buf, filled, want - filled, pos + filled);
136
+ if (bytesRead <= 0) return null;
137
+ filled += bytesRead;
138
+ }
139
+ bufStart = pos;
140
+ bufEnd = pos + filled;
141
+ }
142
+ return buf.subarray(pos - bufStart, pos - bufStart + len);
143
+ };
144
+ }
145
+
146
+ function readZstdFrame(readSlice, start, fileSize, { strictDsh = true } = {}) {
147
+ let pos = start;
148
+ const magicBuf = readSlice(pos, 4);
149
+ if (!magicBuf) return null;
150
+ const magic = magicBuf.readUInt32LE(0);
151
+ if (!strictDsh && ((magic & zstdSkippableMask) >>> 0) === zstdSkippableMagic) {
152
+ const lenBuf = readSlice(pos + 4, 4);
153
+ if (!lenBuf) return null;
154
+ const end = pos + 8 + lenBuf.readUInt32LE(0);
155
+ return end <= fileSize ? { end, skippable: true } : null;
156
+ }
157
+ if (magic !== zstdMagic) return null;
158
+ const descBuf = readSlice(pos + 4, 1);
159
+ if (!descBuf) return null;
160
+ const descriptor = descBuf[0];
161
+ const checksum = (descriptor & 0x04) !== 0;
162
+ const reusable = checksum && (descriptor & 0x1b) === 0;
163
+ if ((descriptor & 0x18) !== 0 || (strictDsh && !reusable)) return null;
164
+ const dictFlag = descriptor & 0x03;
165
+ const dictBytes = dictFlag === 3 ? 4 : dictFlag;
166
+ const contentSizeFlag = descriptor >>> 6;
167
+ const singleSegment = (descriptor & 0x20) !== 0;
168
+ const fcsBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
169
+ const headerLen = 5 + (singleSegment ? 0 : 1) + dictBytes + fcsBytes;
170
+ if (pos + headerLen > fileSize) return null;
171
+ let contentSize;
172
+ if (fcsBytes > 0) {
173
+ const fcs = readSlice(pos + 5 + (singleSegment ? 0 : 1) + dictBytes, fcsBytes);
174
+ if (!fcs) return null;
175
+ if (fcsBytes === 1) contentSize = fcs[0];
176
+ else if (fcsBytes === 2) contentSize = fcs.readUInt16LE(0) + 256;
177
+ else if (fcsBytes === 4) contentSize = fcs.readUInt32LE(0);
178
+ else {
179
+ const value = fcs.readBigUInt64LE(0);
180
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) return null;
181
+ contentSize = Number(value);
182
+ }
183
+ }
184
+ pos += headerLen;
185
+ for (;;) {
186
+ const block = readSlice(pos, 3);
187
+ if (!block) return null;
188
+ const raw = block[0] | (block[1] << 8) | (block[2] << 16);
189
+ const lastBlock = (raw & 1) !== 0;
190
+ const blockType = (raw >>> 1) & 0x03;
191
+ const blockSize = raw >>> 3;
192
+ if (blockType === 0x03 || blockSize > chunkBytes) return null;
193
+ pos += 3 + (blockType === 0x01 ? 1 : blockSize);
194
+ if (pos > fileSize) return null;
195
+ if (lastBlock) break;
196
+ }
197
+ if (checksum) pos += 4;
198
+ if (pos > fileSize) return null;
199
+ return { end: pos, contentSize, reusable, skippable: false };
200
+ }
201
+
202
+ /**
203
+ * Decode concatenated Zstandard frames from a file handle in bounded memory.
204
+ * Node 24's built-in Zstd stream stops after the first frame in a concatenated
205
+ * stream, so walking RFC 8878 frame boundaries keeps Electron (Node 24) and
206
+ * CLI (Node 26) behavior identical while detecting torn trailing frames.
207
+ */
208
+ async function* streamZstdChunks(file, startOffset, fileSize, onFrame) {
209
+ const readSlice = makeBufferedSlice(file.fd, fileSize);
210
+ let pos = startOffset;
211
+ while (pos < fileSize) {
212
+ const frame = readZstdFrame(readSlice, pos, fileSize, { strictDsh: false });
213
+ requireRollout(frame !== null, '会话日志不完整,已取消编辑。');
214
+ onFrame?.(pos, frame);
215
+ const frameEnd = frame.end;
216
+ if (frame.skippable) {
217
+ pos = frameEnd;
218
+ continue;
219
+ }
220
+ const frameLen = frameEnd - pos;
221
+ if (frameLen <= chunkBytes && frame.contentSize !== undefined && frame.contentSize <= inlineZstdOutputBytes) {
222
+ const raw = readSlice(pos, frameLen);
223
+ requireRollout(raw !== null, '会话日志读取不完整。');
224
+ const out = zstdDecompressSync(raw, {
225
+ maxOutputLength: inlineZstdOutputBytes,
226
+ params: { [constants.ZSTD_d_windowLogMax]: 27 },
227
+ });
228
+ if (out.length > 0) yield out;
229
+ } else {
230
+ const input = Readable.from(readFrameChunks(file, pos, frameEnd));
231
+ const decoded = createZstdDecompress({ chunkSize: chunkBytes, params: { [constants.ZSTD_d_windowLogMax]: 27 } });
232
+ const transport = pipeline(input, decoded).then(() => undefined, error => error);
233
+ let done = false;
234
+ try {
235
+ for await (const chunk of decoded) {
236
+ if (chunk.length > 0) yield chunk;
237
+ }
238
+ const error = await transport;
239
+ if (error) throw error;
240
+ done = true;
241
+ } finally {
242
+ if (!done) {
243
+ decoded.destroy();
244
+ input.destroy();
245
+ }
246
+ await transport;
247
+ }
248
+ }
249
+ pos = frameEnd;
250
+ }
251
+ }
252
+
253
+ /** Decode all concatenated Zstandard frames in an in-memory buffer with a total output cap. */
254
+ export function decompressZstdConcat(buffer, { maxOutputLength = maxCandidateBytes } = {}) {
255
+ const readSlice = (pos, len) => (pos >= 0 && pos + len <= buffer.length ? buffer.subarray(pos, pos + len) : null);
256
+ const parts = [];
257
+ let total = 0;
258
+ let pos = 0;
259
+ while (pos < buffer.length) {
260
+ const frame = readZstdFrame(readSlice, pos, buffer.length, { strictDsh: false });
261
+ requireRollout(frame !== null, '会话日志不完整,已取消编辑。');
262
+ if (!frame.skippable) {
263
+ const remaining = maxOutputLength - total;
264
+ requireRollout(remaining > 0 || frame.contentSize === undefined || frame.contentSize === 0, '会话日志超出解压大小上限。');
265
+ let out;
266
+ try {
267
+ out = zstdDecompressSync(buffer.subarray(pos, frame.end), {
268
+ maxOutputLength: Math.max(1, remaining),
269
+ params: { [constants.ZSTD_d_windowLogMax]: 27 },
270
+ });
271
+ } catch (error) {
272
+ if (error?.code === 'ERR_BUFFER_TOO_LARGE' || error instanceof RangeError) {
273
+ throw new Error('会话日志超出解压大小上限。', { cause: error });
274
+ }
275
+ throw error;
276
+ }
277
+ total += out.length;
278
+ requireRollout(total <= maxOutputLength, '会话日志超出解压大小上限。');
279
+ if (out.length > 0) parts.push(out);
280
+ }
281
+ pos = frame.end;
282
+ }
283
+ return parts.length === 1 ? parts[0] : Buffer.concat(parts, total);
284
+ }
285
+
286
+ async function* readFrameChunks(file, start, end) {
287
+ let pos = start;
288
+ while (pos < end) {
289
+ const size = Math.min(chunkBytes, end - pos);
290
+ const buf = Buffer.allocUnsafe(size);
291
+ const { bytesRead } = await file.read(buf, 0, size, pos);
292
+ if (bytesRead <= 0) throw new Error('会话日志读取不完整。');
293
+ yield bytesRead === size ? buf : buf.subarray(0, bytesRead);
294
+ pos += bytesRead;
295
+ }
296
+ }
297
+
298
+ async function readFirstRecordInZstdFrame(file, start, end, { singleLine = false } = {}) {
299
+ const input = Readable.from(readFrameChunks(file, start, end));
300
+ const decoded = createZstdDecompress({ chunkSize: chunkBytes, params: { [constants.ZSTD_d_windowLogMax]: 27 } });
301
+ const transport = pipeline(input, decoded).then(() => undefined, error => error);
302
+ let fragments = [];
303
+ let bytes = 0;
304
+ let line;
305
+ let extra = false;
306
+ let finished = false;
307
+ try {
308
+ for await (const chunk of decoded) {
309
+ if (line !== undefined) {
310
+ if (chunk.length > 0) { extra = true; break; }
311
+ continue;
312
+ }
313
+ const newline = chunk.indexOf(0x0a);
314
+ const part = newline < 0 ? chunk : chunk.subarray(0, newline + 1);
315
+ bytes += part.length;
316
+ if (bytes > maxRecordBytes) return null;
317
+ if (newline === -1) {
318
+ fragments.push(part);
319
+ } else {
320
+ line = fragments.length ? Buffer.concat([...fragments, part], bytes) : part;
321
+ fragments = [];
322
+ if (!singleLine) break;
323
+ if (newline + 1 < chunk.length) { extra = true; break; }
324
+ }
325
+ }
326
+ if (singleLine && !extra) {
327
+ const error = await transport;
328
+ if (error) return null;
329
+ finished = true;
330
+ }
331
+ } catch {
332
+ return null;
333
+ } finally {
334
+ if (!finished) {
335
+ decoded.destroy();
336
+ input.destroy();
337
+ }
338
+ await transport;
339
+ }
340
+ if (!line || extra) return null;
341
+ try {
342
+ const record = JSON.parse(utf8.decode(line));
343
+ return record && typeof record === 'object' && !Array.isArray(record) ? record : null;
344
+ } catch {
345
+ return null;
346
+ }
347
+ }
348
+
349
+ /** Locate the owned tail frame of a checksummed v4 Zstandard seeded subagent log. */
350
+ export async function probeSeededSubagentTail(path, sessionId, cutoff) {
351
+ if (typeof path !== 'string' || !isAbsolute(path) || !path.endsWith('.zstd')
352
+ || !nativeLogName.test(basename(path)) || !Number.isSafeInteger(cutoff) || cutoff < 0
353
+ || !await isCanonicalPath(path)) return null;
354
+ const file = await open(path, openReadOnlyFlags());
355
+ try {
356
+ const initial = await file.stat({ bigint: true });
357
+ if (!initial.isFile() || initial.size > BigInt(Number.MAX_SAFE_INTEGER)) return null;
358
+ const identity = fileIdentity(initial);
359
+ await checkRolloutIdentity(path, identity);
360
+ const fileSize = Number(initial.size);
361
+ const scratch = Buffer.allocUnsafe(64);
362
+ function readSmall(pos, len) {
363
+ if (pos + len > fileSize || len > scratch.length) return null;
364
+ return readExactSync(file.fd, scratch, len, pos);
365
+ }
366
+ const frame0 = readZstdFrame(readSmall, 0, fileSize);
367
+ if (!frame0 || frame0.end >= fileSize) return null;
368
+ const header = await readFirstRecordInZstdFrame(file, 0, frame0.end, { singleLine: true });
369
+ if (header?.type !== 'session' || header.version !== 4 || header.id !== sessionId
370
+ || header.isSeeded !== true || header.origin !== 'subagent' || typeof header.parentSession !== 'string'
371
+ || !Number.isSafeInteger(header.createdAt) || header.createdAt < 0) return null;
372
+ const frame1 = readZstdFrame(readSmall, frame0.end, fileSize);
373
+ // Normal DSH one-shot seed frames always record an explicit positive Frame_Content_Size,
374
+ // whereas v3->v4 streaming migrations omit it and must fall back to full scan.
375
+ if (!frame1 || frame1.end >= fileSize || frame1.contentSize === undefined || frame1.contentSize <= 0) return null;
376
+ const frame2 = readZstdFrame(readSmall, frame1.end, fileSize);
377
+ if (!frame2) return null;
378
+ const firstSeed = await readFirstRecordInZstdFrame(file, frame0.end, frame1.end);
379
+ if (firstSeed?.seq !== 0 || typeof firstSeed.type !== 'string' || !Number.isSafeInteger(firstSeed.time)
380
+ || firstSeed.time < 0 || !Object.hasOwn(firstSeed, 'data')) return null;
381
+ const firstTail = await readFirstRecordInZstdFrame(file, frame1.end, frame2.end);
382
+ if (!firstTail || !Number.isSafeInteger(firstTail.seq) || firstTail.seq < 1
383
+ || typeof firstTail.type !== 'string' || !Number.isSafeInteger(firstTail.time)
384
+ || firstTail.time < 0 || firstTail.time >= cutoff || !Object.hasOwn(firstTail, 'data')) return null;
385
+ if (firstTail.type !== 'subagent/descriptor'
386
+ && !(header.agentPreset !== undefined && firstTail.type === 'agent-preset/selected'
387
+ && firstTail.data?.agentPreset === header.agentPreset)) return null;
388
+ await checkRolloutIdentity(path, identity);
389
+ return {
390
+ header,
391
+ identity,
392
+ tailOffset: frame1.end,
393
+ startSeq: firstTail.seq,
394
+ inheritedCount: firstTail.seq - 1,
395
+ seedFrameBytes: frame1.contentSize ?? 0,
396
+ };
397
+ } finally {
398
+ await file.close();
399
+ }
400
+ }
401
+
402
+ /** Stream compressed native events starting from a verified Zstandard frame boundary. */
403
+ export async function* readRolloutLinesFromOffset(path, startOffset, startSeq, expected) {
404
+ requireRollout(typeof path === 'string' && isAbsolute(path) && path.endsWith('.zstd')
405
+ && nativeLogName.test(basename(path)) && await isCanonicalPath(path), '会话日志路径或格式异常。');
406
+ const file = await open(path, openReadOnlyFlags());
407
+ try {
408
+ const initial = await file.stat({ bigint: true });
409
+ requireRollout(initial.isFile() && initial.size <= BigInt(Number.MAX_SAFE_INTEGER)
410
+ && sameIdentity(initial, expected), '会话日志在检查期间已变化,请重新打开编辑框。');
411
+ requireRollout(Number.isSafeInteger(startOffset) && startOffset > 0 && BigInt(startOffset) < initial.size,
412
+ '会话日志偏移量异常。');
413
+ await checkRolloutIdentity(path, expected);
414
+ let fragments = [];
415
+ let bytes = 0;
416
+ let index = startSeq;
417
+ for await (const chunk of streamZstdChunks(file, startOffset, Number(initial.size))) {
418
+ let start = 0;
419
+ while (start < chunk.length) {
420
+ const newline = chunk.indexOf(0x0a, start);
421
+ const end = newline < 0 ? chunk.length : newline + 1;
422
+ const part = chunk.subarray(start, end);
423
+ bytes += part.length;
424
+ requireRollout(bytes <= maxRecordBytes, '会话含有超过 16 MiB 的单条记录,无法安全编辑。');
425
+ if (newline === -1) {
426
+ fragments.push(part);
427
+ } else {
428
+ const line = fragments.length ? Buffer.concat([...fragments, part], bytes) : part;
429
+ fragments = [];
430
+ bytes = 0;
431
+ const record = JSON.parse(utf8.decode(line));
432
+ requireRollout(record && typeof record === 'object' && !Array.isArray(record)
433
+ && record.seq === index && typeof record.type === 'string' && Number.isSafeInteger(record.time)
434
+ && record.time >= 0 && Object.hasOwn(record, 'data'), '会话日志的事件顺序或记录无效。');
435
+ yield { record, line, index };
436
+ index++;
437
+ }
438
+ start = end;
439
+ }
440
+ }
441
+ requireRollout(bytes === 0, '会话日志不完整,已取消编辑。');
442
+ await checkRolloutIdentity(path, expected);
443
+ } finally {
444
+ await file.close();
445
+ }
446
+ }
447
+
448
+ /** Buffer one small native frame at a time and publish to a caller-chosen temporary file. */
449
+ export async function writeRolloutCandidate(path, compressed, records, prefixCopy) {
450
+ requireRollout(typeof path === 'string' && isAbsolute(path) && await isCanonicalPath(dirname(path)),
451
+ '候选日志路径异常。');
452
+ const file = await open(path, 'wx', 0o600);
453
+ let owner;
454
+ const hash = createHash('sha256');
455
+ const options = { params: { [constants.ZSTD_c_checksumFlag]: 1 } };
456
+ let size = 0;
457
+ let used = 0;
458
+ let pieces = [];
459
+ let complete = false;
460
+ async function flush() {
461
+ if (pieces.length === 0) return;
462
+ const raw = pieces.length === 1 ? pieces[0] : Buffer.concat(pieces, used);
463
+ pieces = [];
464
+ used = 0;
465
+ const bytes = compressed ? await compress(raw, options) : raw;
466
+ requireRollout(size + bytes.length <= maxCandidateBytes, '候选日志超出磁盘写入上限。');
467
+ await file.writeFile(bytes);
468
+ size += bytes.length;
469
+ hash.update(bytes);
470
+ }
471
+ try {
472
+ owner = await file.stat({ bigint: true });
473
+ if (prefixCopy) {
474
+ requireRollout(compressed, '非压缩会话日志不支持压缩前缀透传。');
475
+ const source = await open(prefixCopy.sourcePath, openReadOnlyFlags());
476
+ try {
477
+ const stat = await source.stat({ bigint: true });
478
+ requireRollout(stat.isFile() && sameIdentity(stat, prefixCopy.expected), '会话日志在检查期间已变化,请重新打开编辑框。');
479
+ await checkRolloutIdentity(prefixCopy.sourcePath, prefixCopy.expected);
480
+ requireRollout(prefixCopy.end > 0 && prefixCopy.end <= Number(stat.size) && prefixCopy.end <= maxCandidateBytes,
481
+ '候选日志超出磁盘写入上限。');
482
+ const copyBuf = Buffer.allocUnsafe(chunkBytes);
483
+ let offset = 0;
484
+ while (offset < prefixCopy.end) {
485
+ const { bytesRead } = await source.read(copyBuf, 0, Math.min(chunkBytes, prefixCopy.end - offset), offset);
486
+ requireRollout(bytesRead > 0, '会话日志读取不完整,已取消编辑。');
487
+ const slice = bytesRead === copyBuf.length ? copyBuf : copyBuf.subarray(0, bytesRead);
488
+ await file.writeFile(slice);
489
+ hash.update(slice);
490
+ size += bytesRead;
491
+ offset += bytesRead;
492
+ }
493
+ await checkRolloutIdentity(prefixCopy.sourcePath, prefixCopy.expected);
494
+ } finally {
495
+ await source.close();
496
+ }
497
+ }
498
+ for await (const { line, index } of records) {
499
+ requireRollout(line.length <= maxRecordBytes && line.at(-1) === 0x0a, '候选日志包含无效或过大的记录。');
500
+ if (used + line.length > frameBytes) await flush();
501
+ pieces.push(line);
502
+ used += line.length;
503
+ if (index === -1 || used >= frameBytes) await flush();
504
+ }
505
+ await flush();
506
+ await file.sync();
507
+ complete = true;
508
+ return { size, digest: hash.digest('hex') };
509
+ } finally {
510
+ try { await file.close(); } finally {
511
+ if (!complete) {
512
+ const current = await lstat(path, { bigint: true }).catch(error => {
513
+ if (error.code !== 'ENOENT') throw error;
514
+ return undefined;
515
+ });
516
+ if (owner && current?.isFile() && current.dev === owner.dev && current.ino === owner.ino
517
+ && await isCanonicalPath(path)) await unlink(path);
518
+ }
519
+ }
520
+ }
521
+ }