@kabxx/dsh-message-revision 0.0.0-stage → 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,601 @@
1
+ import { cleanupRevisionCandidates } from './revision-candidates.js';
2
+ import { acquireNativeLease } from './native-lease.js';
3
+ import {
4
+ isCanonicalPath, isSamePath, isSupportedPlatform, pathKey, replaceFileDurable, resolveRolloutPath,
5
+ } from './platform.js';
6
+ import { decompressZstdConcat } from './rollout-stream.js';
7
+ import { isProvisionalResumeMarker } from './rollback-events.js';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { lstat, open, readFile, unlink } from 'node:fs/promises';
10
+ import { basename, dirname, isAbsolute, join } from 'node:path';
11
+ import { setTimeout as wait } from 'node:timers/promises';
12
+ import {
13
+ cleanRewriteDebris, clearFailedCommitMarker, forgetRewriteJournal, hasPendingRewrite, listRewriteDebris, markRewriteCommitted,
14
+ matchJournalRevision, prepareRewriteJournal, readRewriteJournals, readRewriteOriginal, restoreWithdrawnChildren,
15
+ retireRewriteJournal, retrySettledRewriteRetirement, stageWithdrawnChildren,
16
+ } from './rewrite-journal.js';
17
+ import { promisify } from 'node:util';
18
+ import { constants, zstdCompress } from 'node:zlib';
19
+
20
+ const compress = promisify(zstdCompress);
21
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
22
+ const maxBytes = 256 * 1024 * 1024;
23
+ const maxQueue = 4096;
24
+ const maxCopies = 8192;
25
+ const logName = /^session\.v4\.jsonl(?:\.zstd)?$/u;
26
+
27
+ export class RevisionError extends Error {
28
+ constructor(message, options) {
29
+ super(message, options);
30
+ this.name = 'RevisionError';
31
+ }
32
+ }
33
+
34
+ function requireRevision(condition, message) {
35
+ if (!condition) throw new RevisionError(message);
36
+ }
37
+
38
+ /** Find the beginning of the turn and the existing next-turn queue entry. */
39
+ export function planRevision(events, messageId, inheritedCount = 0) {
40
+ const queues = { 'next-turn': [], 'next-step': [] };
41
+ let turn;
42
+ let selected;
43
+ let checkpoint;
44
+ let inputCopies = [];
45
+ let index = 0;
46
+ for (const event of events) {
47
+ requireRevision(event.seq === index, '会话日志的事件顺序不完整。');
48
+ const data = event.data;
49
+ if (event.type === 'agent/inbox/spliced') {
50
+ const queue = queues[data.target];
51
+ const count = data.removedCount ?? 0;
52
+ requireRevision(Array.isArray(queue) && Number.isSafeInteger(data.start) && data.start >= 0
53
+ && Number.isSafeInteger(count) && count >= 0 && data.start + count <= queue.length
54
+ && Array.isArray(data.inserted)
55
+ && queue.length - count + data.inserted.length <= maxQueue, '无法安全复原会话的消息队列。');
56
+ const inserted = data.inserted.map((message, offset) => {
57
+ requireRevision(typeof message?.id === 'string' && message.id.length <= 2048, '无法安全复原会话的消息队列。');
58
+ if (message.id !== messageId) return { id: message.id };
59
+ requireRevision(inputCopies.length < maxCopies, '同一消息的历史入队记录超出检查上限。');
60
+ const item = { message, index, offset };
61
+ inputCopies.push(item);
62
+ return { id: message.id, ...item };
63
+ });
64
+ queue.splice(data.start, count, ...inserted);
65
+ } else if (event.type === 'turn/start') {
66
+ requireRevision(turn === undefined && Number.isSafeInteger(data?.turn), '会话日志中存在未关闭的回合。');
67
+ const candidate = queues['next-turn'][0];
68
+ turn = {
69
+ index,
70
+ number: data.turn,
71
+ time: event.time,
72
+ input: candidate?.id === messageId ? candidate : undefined,
73
+ queuedCount: queues['next-turn'].length,
74
+ hasSteering: queues['next-step'].length > 0,
75
+ };
76
+ } else if (event.type === 'turn/end') {
77
+ requireRevision(turn !== undefined && turn.number === data?.turn, '会话日志的回合边界不完整。');
78
+ turn = undefined;
79
+ } else if (event.type === 'user/message' && data?.id === messageId && data.source?.kind === 'user') {
80
+ requireRevision(selected === undefined, '日志中找到了重复的用户消息。');
81
+ selected = event;
82
+ checkpoint = turn;
83
+ if (checkpoint) inputCopies = inputCopies.filter(item => item.index < checkpoint.index);
84
+ }
85
+ index++;
86
+ }
87
+ requireRevision(turn === undefined, '回复生成中,请先停止或等待完成。');
88
+ requireRevision(selected && checkpoint?.input?.message.id === messageId
89
+ && checkpoint.index > inheritedCount && checkpoint.input.index >= inheritedCount
90
+ && !checkpoint.hasSteering && checkpoint.queuedCount === 1,
91
+ '此消息没有可独立回退的对话轮次。');
92
+ requireRevision(queues['next-turn'].length === 0 && queues['next-step'].length === 0,
93
+ '会话仍有排队消息,请等队列清空后再试。');
94
+ const retainedInputs = inputCopies.filter(item => item.index < checkpoint.index);
95
+ requireRevision(retainedInputs.every(item => item.index >= inheritedCount && item.message.source?.kind === 'user'),
96
+ '无法替换继承历史中的同一条消息。');
97
+ return {
98
+ cut: checkpoint.index,
99
+ retainedInputs,
100
+ time: checkpoint.time,
101
+ message: checkpoint.input.message,
102
+ };
103
+ }
104
+
105
+ export function isRevisionAttachment(block) {
106
+ return (block?.type === 'image' || block?.type === 'file') && typeof block.attachment === 'object' && block.attachment !== null;
107
+ }
108
+
109
+ export function retainedRevisionAttachments(message, removed = []) {
110
+ requireRevision(Array.isArray(message.content), '无法读取该消息正文。');
111
+ for (const index of removed) {
112
+ requireRevision(isRevisionAttachment(message.content[index]), '无法确认待移除的附件。');
113
+ }
114
+ const ignored = new Set(removed);
115
+ return message.content.filter((block, index) => isRevisionAttachment(block) && !ignored.has(index));
116
+ }
117
+
118
+ export function revisionTextParts(message) {
119
+ return message.content.filter(block => block.type === 'text').map(block => block.text);
120
+ }
121
+
122
+ export function resolveRevisionText(message, { text, textParts }) {
123
+ const original = revisionTextParts(message);
124
+ if (textParts !== undefined) {
125
+ requireRevision(Array.isArray(textParts) && original.length > 1 && textParts.length === original.length
126
+ && textParts.every(part => typeof part === 'string') && textParts.join('') === text,
127
+ '分段正文与原消息不匹配,请重新打开编辑框。');
128
+ return textParts;
129
+ }
130
+ if (text === original.join('')) return original;
131
+ requireRevision(original.length <= 1, '此消息包含多段正文,请使用分段编辑。');
132
+ return [text];
133
+ }
134
+
135
+ export function rewriteMessage(message, input, removed, added) {
136
+ const retained = retainedRevisionAttachments(message, removed);
137
+ const textParts = resolveRevisionText(message, input);
138
+ requireRevision(input.text.trim() !== '' || retained.length > 0 || added.length > 0, '请输入消息内容或至少保留一个附件。');
139
+ const ignored = new Set(removed);
140
+ const content = [];
141
+ let part = 0;
142
+ for (const [index, block] of message.content.entries()) {
143
+ if (block.type === 'text') {
144
+ const replacement = textParts[part++];
145
+ if (replacement === block.text) content.push(block);
146
+ else if (replacement !== '') content.push({ ...block, text: replacement });
147
+ } else if (!ignored.has(index)) {
148
+ content.push(block);
149
+ }
150
+ }
151
+ if (part === 0 && input.text.trim() !== '') content.unshift({ type: 'text', text: input.text });
152
+ return { ...message, content: [...content, ...added] };
153
+ }
154
+
155
+ function validateText(text) {
156
+ requireRevision(typeof text === 'string' && text.length <= 200_000,
157
+ '消息内容无效,最多支持 200,000 个字符。');
158
+ }
159
+
160
+ function checkLocation(snapshot) {
161
+ const path = snapshot?.location?.path;
162
+ requireRevision(snapshot?.location?.kind === 'jsonl' && typeof path === 'string'
163
+ && isAbsolute(path) && logName.test(basename(path)), '当前会话存储格式不支持编辑。');
164
+ return path;
165
+ }
166
+
167
+ async function checkedRolloutPath(dshPath) {
168
+ const path = await resolveRolloutPath(dshPath);
169
+ requireRevision(path !== undefined, '会话日志路径异常。');
170
+ return path;
171
+ }
172
+
173
+ async function checkArtifact(path) {
174
+ const identity = await lstat(path, { bigint: true });
175
+ requireRevision(identity.isFile() && !identity.isSymbolicLink() && await isCanonicalPath(path),
176
+ '会话日志路径异常。');
177
+ requireRevision(identity.size <= maxBytes, '会话日志超出大小上限,无法编辑。');
178
+ return identity;
179
+ }
180
+
181
+ async function openLocked(persistence, sessionId, snapshot) {
182
+ const dshPath = checkLocation(snapshot);
183
+ const path = await checkedRolloutPath(dshPath);
184
+ const identity = await checkArtifact(path);
185
+ const handle = await persistence.open(sessionId, 'write');
186
+ try {
187
+ const current = await persistence.stat(sessionId);
188
+ requireRevision(handle.header.id === sessionId && isSamePath(checkLocation(current), dshPath)
189
+ && current.revision === snapshot.revision && isSamePath(await resolveRolloutPath(dshPath), path), '会话状态已变更,请刷新后重试。');
190
+ const { events } = await handle.read(0);
191
+ return { handle, path, identity, events, snapshot: current };
192
+ } catch (error) {
193
+ await handle.close();
194
+ throw error;
195
+ }
196
+ }
197
+
198
+ async function encodeReplacement(source, plan, message, controls, restoredCatalog) {
199
+ const compressed = source.path.endsWith('.zstd');
200
+ const raw = await readFile(source.path);
201
+ const decoded = compressed ? decompressZstdConcat(raw, { maxOutputLength: maxBytes }) : raw;
202
+ const lines = utf8.decode(decoded).split('\n');
203
+ requireRevision(lines.pop() === '' && lines.length === source.events.length + 1,
204
+ '会话日志不完整,已取消编辑。');
205
+ const header = JSON.parse(lines[0]);
206
+ requireRevision(header.type === 'session' && header.version === 4 && header.id === source.handle.header.id,
207
+ '会话日志文件头不匹配。');
208
+ const prefix = lines.slice(1, plan.cut + 1);
209
+ // A previous edit may have canceled the original queue occurrence and
210
+ // enqueued the same message again. Keep native splice semantics and replace
211
+ // the content in every retained occurrence of this specific user input.
212
+ for (const { index, offset } of plan.retainedInputs) {
213
+ const encodedInput = JSON.parse(prefix[index]);
214
+ const occurrence = encodedInput.data?.inserted?.[offset];
215
+ requireRevision(encodedInput.seq === index && encodedInput.type === 'agent/inbox/spliced'
216
+ && occurrence?.id === message.id && occurrence.source?.kind === 'user', '无法定位原消息的入队记录。');
217
+ encodedInput.data.inserted[offset] = { ...occurrence, content: message.content };
218
+ prefix[index] = JSON.stringify(encodedInput);
219
+ }
220
+ for (const event of restoredCatalog) {
221
+ prefix.push(JSON.stringify({ ...event, seq: prefix.length, time: plan.time }));
222
+ }
223
+ for (const control of controls) {
224
+ prefix.push(JSON.stringify({ type: control.type, seq: prefix.length, time: Date.now(), data: control.data }));
225
+ }
226
+ const headerBytes = Buffer.from(`${lines[0]}\n`);
227
+ const eventBytes = Buffer.from(`${prefix.join('\n')}\n`);
228
+ if (!compressed) return { original: raw, buffers: [headerBytes, eventBytes], retained: prefix.length };
229
+ const options = { params: { [constants.ZSTD_c_checksumFlag]: 1 } };
230
+ const buffers = await Promise.all([compress(headerBytes, options), compress(eventBytes, options)]);
231
+ return { original: raw, buffers, retained: prefix.length };
232
+ }
233
+
234
+ function catalogEntries(events) {
235
+ return events.filter(event => event.type === 'subagent/catalog');
236
+ }
237
+
238
+ function verifyCatalogBirth(event) {
239
+ const { childId, childCreatedAt, mode } = event.data;
240
+ requireRevision(typeof childId === 'string' && childId.length > 0
241
+ && ['continuable', 'one-shot', 'unknown', 'external'].includes(mode)
242
+ && Number.isSafeInteger(childCreatedAt) && childCreatedAt >= 0 && childCreatedAt <= event.time,
243
+ '无法确认子会话的登记或创建时间。');
244
+ }
245
+
246
+ /** Native migration can append an older child's creation fact at the log tail. */
247
+ export function splitChildCatalog(catalog, { cut, time }) {
248
+ const retained = [];
249
+ const withdrawn = [];
250
+ const seen = new Set();
251
+ for (const event of catalog) {
252
+ verifyCatalogBirth(event);
253
+ const { childId, childCreatedAt } = event.data;
254
+ requireRevision(!seen.has(childId), '子会话登记重复,无法安全判断归属。');
255
+ seen.add(childId);
256
+ if (event.seq < cut) {
257
+ requireRevision(childCreatedAt <= time, '子会话的创建时间与会话顺序不一致。');
258
+ retained.push(event);
259
+ } else {
260
+ requireRevision(childCreatedAt !== time, '子会话的创建时间与改写点重合,无法安全判定归属。');
261
+ (childCreatedAt < time ? retained : withdrawn).push(event);
262
+ }
263
+ }
264
+ return { retained, withdrawn };
265
+ }
266
+
267
+ function verifyChildHeader(header, parent, { childId, childCreatedAt }) {
268
+ requireRevision(header.id === childId && header.parentSession === parent.handle.header.id
269
+ && header.origin === 'subagent' && header.createdAt === childCreatedAt,
270
+ '子会话的实际归属或创建时间与登记不匹配。');
271
+ }
272
+
273
+ async function collectChildTree(persistence, parent, catalog, cutoff, locked, seen) {
274
+ for (const event of catalog) {
275
+ verifyCatalogBirth(event);
276
+ const { childId, childCreatedAt, mode } = event.data;
277
+ requireRevision(!seen.has(childId) && mode !== 'external', '无法安全核对子会话树。');
278
+ seen.add(childId);
279
+ requireRevision(childCreatedAt >= parent.handle.header.createdAt, '子会话早于其父会话,无法确认创建顺序。');
280
+ const snapshot = await persistence.stat(childId);
281
+ requireRevision(snapshot, '子会话记录不可用,无法核对其历史与后代。');
282
+ verifyChildHeader(snapshot.header, parent, event.data);
283
+
284
+ // The native writer lock makes the entire traversed subtree stable until the
285
+ // parent commits. It also catches descendants that are live or opening.
286
+ let child;
287
+ try {
288
+ child = await openLocked(persistence, childId, snapshot);
289
+ } catch (error) {
290
+ if (error.name === 'SessionAlreadyOwnedError') {
291
+ throw new RevisionError('关联的子智能体会话或其后代仍处于打开状态,请关闭后重试。', { cause: error });
292
+ }
293
+ throw error;
294
+ }
295
+ locked.push(child);
296
+ verifyChildHeader(child.handle.header, parent, event.data);
297
+ const ownEvents = child.events.slice(child.handle.inheritedEventCount);
298
+ if (cutoff !== undefined) {
299
+ requireRevision(childCreatedAt < cutoff && ownEvents.every(item => item.time < cutoff),
300
+ '保留的子智能体会话或其后代跨过改写点,无法编辑此消息。');
301
+ let inTurn = false;
302
+ for (const item of ownEvents) {
303
+ if (item.type === 'turn/start') inTurn = true;
304
+ if (item.type === 'turn/end') inTurn = false;
305
+ }
306
+ requireRevision(!inTurn, '保留的子智能体会话或其后代存在未关闭的回合。');
307
+ }
308
+ await collectChildTree(persistence, child, catalogEntries(ownEvents), cutoff, locked, seen);
309
+ }
310
+ }
311
+
312
+ async function checkUnchanged(entry) {
313
+ const now = await checkArtifact(entry.path);
314
+ const initial = entry.identity;
315
+ requireRevision(now.dev === initial.dev && now.ino === initial.ino && now.size === initial.size
316
+ && now.mtimeNs === initial.mtimeNs && now.ctimeNs === initial.ctimeNs,
317
+ '日志文件已变化,未继续替换。');
318
+ }
319
+
320
+ async function replaceArtifact(source, buffers, beforeReplace, onPublished, staging = dirname(source.path)) {
321
+ const directory = dirname(source.path);
322
+ const stage = join(staging, `.message-revision-${randomUUID()}.tmp`);
323
+ let pending = false;
324
+ try {
325
+ const file = await open(stage, 'wx', Number(source.identity.mode & 0o777n));
326
+ pending = true;
327
+ try {
328
+ for (const bytes of buffers) await file.writeFile(bytes);
329
+ await file.sync();
330
+ } finally {
331
+ await file.close();
332
+ }
333
+ await checkUnchanged(source);
334
+ await beforeReplace?.();
335
+ await checkUnchanged(source);
336
+ await replaceFileDurable(stage, source.path);
337
+ pending = false;
338
+ onPublished?.();
339
+ if (process.platform !== 'win32') {
340
+ const parent = await open(directory, 'r');
341
+ try { await parent.sync(); } finally { await parent.close(); }
342
+ }
343
+ } finally {
344
+ if (pending) await unlink(stage);
345
+ }
346
+ }
347
+
348
+ async function recoverRewrite(source, journal, { canRollback, beforeCommit } = {}) {
349
+ if (journal.committed) return;
350
+ const revision = await matchJournalRevision(journal);
351
+ requireRevision((canRollback?.() ?? true) && revision !== 'conflict',
352
+ '会话已变化,无法自动恢复上次编辑。');
353
+ if (revision === 'original') {
354
+ await restoreWithdrawnChildren(journal);
355
+ return;
356
+ }
357
+ const retained = journal.intent.candidate.records;
358
+ requireRevision(source.events.length >= retained
359
+ && source.events.slice(retained).every(event => isProvisionalResumeMarker(event, retained)),
360
+ '更新后的会话已有新增内容,无法自动回滚。');
361
+ const original = await readRewriteOriginal(journal);
362
+ await replaceArtifact(source, [original], async () => {
363
+ await beforeCommit?.([journal.intent.parentId, ...journal.intent.children.map(child => child.id)]);
364
+ await restoreWithdrawnChildren(journal);
365
+ }, undefined, journal.directory);
366
+ }
367
+
368
+ const recoveries = new Map();
369
+ const recoveryRetryDelays = [100, 250, 500, 1_000, 2_000, 4_000];
370
+
371
+ function recoverSessionRewrite(persistence, snapshot, { beforeCommit, canRollback, onError, restoreBoundedJournal, recoverDelivery } = {}) {
372
+ const { id } = snapshot.header;
373
+ const path = checkLocation(snapshot);
374
+ const key = pathKey(path);
375
+ const existing = recoveries.get(key);
376
+ if (existing) return existing;
377
+ const recovery = (async () => {
378
+ const [journal] = await readRewriteJournals(snapshot);
379
+ if (!journal) return false;
380
+ if (journal.intent.format === 2) {
381
+ if (journal.committed && journal.intent.delivery) {
382
+ recoverDelivery?.(journal);
383
+ return false;
384
+ }
385
+ const retire = () => retireRewriteJournal(journal, { deferCleanup: true, onCleanupError: error => onError?.(id, error) });
386
+ if (journal.committed) {
387
+ await retire();
388
+ return false;
389
+ }
390
+ if (!restoreBoundedJournal) throw new RevisionError('当前无法恢复多会话编辑事务。');
391
+ await restoreBoundedJournal(journal, {
392
+ beforeCommit,
393
+ canRollback: () => [...journal.intent.artifacts, ...journal.intent.children]
394
+ .every(entry => canRollback?.(entry.id) ?? true),
395
+ afterRestore: retire,
396
+ });
397
+ return true;
398
+ }
399
+ const source = await openLocked(persistence, id, snapshot);
400
+ try {
401
+ // Only act on the journal still present after obtaining the native lock.
402
+ const [current] = await readRewriteJournals(source.snapshot);
403
+ if (!current || current.intent.format !== 1) return false;
404
+ await recoverRewrite(source, current, { beforeCommit, canRollback: () => canRollback?.(id) ?? true });
405
+ await retireRewriteJournal(current);
406
+ return !current.committed;
407
+ } finally {
408
+ await source.handle.close();
409
+ }
410
+ })().finally(() => recoveries.delete(key));
411
+ recoveries.set(key, recovery);
412
+ return recovery;
413
+ }
414
+
415
+ async function retryLockedRewrites(persistence, pending, options) {
416
+ const { retrySignal, onError } = options;
417
+ for (const delay of recoveryRetryDelays) {
418
+ if (pending.size === 0 || retrySignal.aborted) return;
419
+ try { await wait(delay, undefined, { signal: retrySignal, ref: false }); } catch (error) {
420
+ if (retrySignal.aborted) return;
421
+ throw error;
422
+ }
423
+ for (const id of pending) {
424
+ if (retrySignal.aborted) return;
425
+ try {
426
+ const snapshot = await persistence.stat(id);
427
+ if (snapshot) await recoverSessionRewrite(persistence, snapshot, options);
428
+ pending.delete(id);
429
+ } catch (error) {
430
+ if (error.name === 'SessionAlreadyOwnedError') continue;
431
+ pending.delete(id);
432
+ onError?.(id, error);
433
+ }
434
+ }
435
+ }
436
+ }
437
+
438
+ /** Recover transactions left by a previous Host before admitting new rewrites. */
439
+ export async function recoverStoredSessions(persistence, options = {}) {
440
+ const { onError, retrySignal } = options;
441
+ const locked = new Set();
442
+ for (const snapshot of await persistence.list()) {
443
+ if (retrySignal?.aborted) break;
444
+ const { id } = snapshot.header;
445
+ try {
446
+ if (snapshot.location?.kind !== 'jsonl' || !isAbsolute(snapshot.location.path)
447
+ || !logName.test(basename(snapshot.location.path))) continue;
448
+ const dshPath = checkLocation(snapshot);
449
+ const path = await checkedRolloutPath(dshPath);
450
+ await cleanupRevisionCandidates(path, { retryBusy: true, onError: error => onError?.(id, error) })
451
+ .catch(error => onError?.(id, error));
452
+ await recoverSessionRewrite(persistence, snapshot, options);
453
+ const { preparations, retired } = await listRewriteDebris(path);
454
+ if (preparations.length > 0) {
455
+ if (isSupportedPlatform(process.platform)) {
456
+ try {
457
+ // An unpublished directory has never modified the live session. Its
458
+ // native writer lease protects metadata-only cleanup of any size.
459
+ const lease = await acquireNativeLease(path, dshPath);
460
+ try {
461
+ const current = await persistence.stat(id);
462
+ requireRevision(current?.header.id === id && isSamePath(checkLocation(current), dshPath), '会话状态已变更,请刷新后重试。');
463
+ await lease.assertHeld();
464
+ await cleanRewriteDebris((await listRewriteDebris(path)).preparations);
465
+ } finally { await lease.close(); }
466
+ } catch (error) { onError?.(id, error); }
467
+ } else {
468
+ const source = await openLocked(persistence, id, snapshot);
469
+ try {
470
+ await cleanRewriteDebris((await listRewriteDebris(source.path)).preparations);
471
+ } finally {
472
+ await source.handle.close();
473
+ }
474
+ }
475
+ }
476
+ await cleanRewriteDebris(retired);
477
+ } catch (error) {
478
+ if (retrySignal && error.name === 'SessionAlreadyOwnedError') locked.add(id);
479
+ onError?.(id, error);
480
+ }
481
+ }
482
+ if (locked.size > 0) {
483
+ void retryLockedRewrites(persistence, locked, options).catch(error => onError?.('startup', error));
484
+ }
485
+ }
486
+
487
+ export async function recoverPendingRewrite(persistence, snapshot, options) {
488
+ if (snapshot?.location?.kind !== 'jsonl') return false;
489
+ const path = await checkedRolloutPath(checkLocation(snapshot));
490
+ await retrySettledRewriteRetirement(path);
491
+ if (!await hasPendingRewrite(path)) return false;
492
+ const recovered = await recoverSessionRewrite(persistence, snapshot, options);
493
+ requireRevision(!await hasPendingRewrite(path), '上次编辑尚未完成恢复,请检查运行日志。');
494
+ return recovered;
495
+ }
496
+
497
+ export async function assertNoPendingRewrite(snapshot) {
498
+ if (snapshot?.location?.kind === 'jsonl') {
499
+ const path = await checkedRolloutPath(checkLocation(snapshot));
500
+ await retrySettledRewriteRetirement(path);
501
+ requireRevision(!await hasPendingRewrite(path), '上次编辑尚未完成恢复,请检查运行日志。');
502
+ }
503
+ }
504
+
505
+ /** Publish provisionally, then let DSH open the same ID before discarding any old data. */
506
+ export async function rewriteStoredSession(persistence, {
507
+ sessionId, messageId, text, textParts, expectedRevision, removedAttachments = [],
508
+ }, { beforeCommit, verifyReload, canRollback, closeFailedReload, afterCommit, onCleanupError, addedAttachments = [], controls = [] } = {}) {
509
+ validateText(text);
510
+ const snapshot = await persistence.stat(sessionId);
511
+ requireRevision(expectedRevision === undefined || snapshot?.revision === expectedRevision,
512
+ '会话状态已变更,请重新打开编辑框。');
513
+ const source = await openLocked(persistence, sessionId, snapshot);
514
+ const retainedChildren = [];
515
+ const withdrawnChildren = [];
516
+ let journal;
517
+ let published = false;
518
+ let committed = false;
519
+ let markerFailed = false;
520
+ let handlesClosed = false;
521
+ async function releaseHandles() {
522
+ if (handlesClosed) return;
523
+ handlesClosed = true;
524
+ const results = await Promise.allSettled([
525
+ ...retainedChildren.map(child => child.handle.close()),
526
+ ...withdrawnChildren.map(child => child.handle.close()),
527
+ source.handle.close(),
528
+ ]);
529
+ const failure = results.find(result => result.status === 'rejected');
530
+ if (failure) throw failure.reason;
531
+ }
532
+ try {
533
+ await assertNoPendingRewrite(source.snapshot);
534
+ requireRevision(source.handle.header.origin !== 'subagent', '子智能体会话不支持直接编辑,请在主会话中操作。');
535
+ const plan = planRevision(source.events, messageId, source.handle.inheritedEventCount);
536
+ const catalog = catalogEntries(source.events).filter(event => event.seq >= source.handle.inheritedEventCount);
537
+ const { retained, withdrawn } = splitChildCatalog(catalog, plan);
538
+ const seen = new Set([sessionId]);
539
+ await collectChildTree(persistence, source, retained, plan.time, retainedChildren, seen);
540
+ await collectChildTree(persistence, source, withdrawn, undefined, withdrawnChildren, seen);
541
+ const message = rewriteMessage(plan.message, { text, textParts }, removedAttachments, addedAttachments);
542
+ const replacement = await encodeReplacement(source, plan, message, controls, retained.filter(event => event.seq >= plan.cut));
543
+ const removedChildren = withdrawnChildren.map(child => child.handle.header.id);
544
+ for (const child of [...retainedChildren, ...withdrawnChildren]) await checkUnchanged(child);
545
+ await beforeCommit?.([sessionId, ...removedChildren]);
546
+ journal = await prepareRewriteJournal(source, withdrawnChildren, replacement);
547
+ await replaceArtifact(source, replacement.buffers, async () => {
548
+ for (const child of [...retainedChildren, ...withdrawnChildren]) await checkUnchanged(child);
549
+ await stageWithdrawnChildren(journal);
550
+ }, () => { published = true; }, journal.directory);
551
+ await releaseHandles();
552
+ await verifyReload?.();
553
+ try {
554
+ await markRewriteCommitted(journal);
555
+ } catch (error) {
556
+ markerFailed = true;
557
+ throw error;
558
+ }
559
+ committed = true;
560
+ const result = { messageId, removedChildren };
561
+ try {
562
+ await afterCommit?.(result);
563
+ } finally {
564
+ // Dispatch happens first. Cleanup cannot turn a saved edit into a failed
565
+ // request, and startup will retry committed or partially retired journals.
566
+ try {
567
+ await retireRewriteJournal(journal);
568
+ } catch (error) {
569
+ result.cleanupWarning = true;
570
+ onCleanupError?.(error);
571
+ }
572
+ }
573
+ return result;
574
+ } catch (error) {
575
+ if (committed || !journal) throw error;
576
+ try {
577
+ if (published) {
578
+ await releaseHandles();
579
+ if (markerFailed) await closeFailedReload?.();
580
+ const current = await openLocked(persistence, sessionId, await persistence.stat(sessionId));
581
+ try {
582
+ requireRevision(isSamePath(current.path, source.path) && (canRollback?.() ?? true), '无法确认候选会话已释放。');
583
+ if (markerFailed) await clearFailedCommitMarker(journal);
584
+ await recoverRewrite(current, journal, { canRollback, beforeCommit });
585
+ } finally {
586
+ await current.handle.close();
587
+ }
588
+ } else {
589
+ await restoreWithdrawnChildren(journal);
590
+ }
591
+ await retireRewriteJournal(journal);
592
+ } catch (rollbackError) {
593
+ throw new Error('编辑回滚失败,请刷新后检查会话。', { cause: rollbackError });
594
+ }
595
+ if (published) throw new RevisionError('无法加载更新后的会话,已恢复原记录。', { cause: error });
596
+ throw error;
597
+ } finally {
598
+ forgetRewriteJournal(journal);
599
+ await releaseHandles();
600
+ }
601
+ }