@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.
package/src/revision.js CHANGED
@@ -1,18 +1,27 @@
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';
1
8
  import { randomUUID } from 'node:crypto';
2
- import { lstat, open, readFile, realpath, rename, unlink } from 'node:fs/promises';
9
+ import { lstat, open, readFile, unlink } from 'node:fs/promises';
3
10
  import { basename, dirname, isAbsolute, join } from 'node:path';
11
+ import { setTimeout as wait } from 'node:timers/promises';
4
12
  import {
5
13
  cleanRewriteDebris, clearFailedCommitMarker, forgetRewriteJournal, hasPendingRewrite, listRewriteDebris, markRewriteCommitted,
6
14
  matchJournalRevision, prepareRewriteJournal, readRewriteJournals, readRewriteOriginal, restoreWithdrawnChildren,
7
- retireRewriteJournal, stageWithdrawnChildren,
15
+ retireRewriteJournal, retrySettledRewriteRetirement, stageWithdrawnChildren,
8
16
  } from './rewrite-journal.js';
9
17
  import { promisify } from 'node:util';
10
- import { constants, zstdCompress, zstdDecompress } from 'node:zlib';
18
+ import { constants, zstdCompress } from 'node:zlib';
11
19
 
12
20
  const compress = promisify(zstdCompress);
13
- const decompress = promisify(zstdDecompress);
14
21
  const utf8 = new TextDecoder('utf-8', { fatal: true });
15
22
  const maxBytes = 256 * 1024 * 1024;
23
+ const maxQueue = 4096;
24
+ const maxCopies = 8192;
16
25
  const logName = /^session\.v4\.jsonl(?:\.zstd)?$/u;
17
26
 
18
27
  export class RevisionError extends Error {
@@ -32,36 +41,48 @@ export function planRevision(events, messageId, inheritedCount = 0) {
32
41
  let turn;
33
42
  let selected;
34
43
  let checkpoint;
35
- const inputCopies = [];
36
- for (const [index, event] of events.entries()) {
44
+ let inputCopies = [];
45
+ let index = 0;
46
+ for (const event of events) {
37
47
  requireRevision(event.seq === index, '会话日志的事件顺序不完整。');
38
48
  const data = event.data;
39
49
  if (event.type === 'agent/inbox/spliced') {
40
50
  const queue = queues[data.target];
41
51
  const count = data.removedCount ?? 0;
42
- requireRevision(queue && Number.isSafeInteger(data.start) && data.start >= 0
52
+ requireRevision(Array.isArray(queue) && Number.isSafeInteger(data.start) && data.start >= 0
43
53
  && Number.isSafeInteger(count) && count >= 0 && data.start + count <= queue.length
44
- && Array.isArray(data.inserted), '无法安全复原会话的消息队列。');
45
- const inserted = data.inserted.map((message, offset) => ({ message, index, offset }));
46
- for (const item of inserted) if (item.message.id === messageId) inputCopies.push(item);
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
+ });
47
64
  queue.splice(data.start, count, ...inserted);
48
65
  } else if (event.type === 'turn/start') {
49
- requireRevision(turn === undefined, '会话日志中存在未关闭的回合。');
66
+ requireRevision(turn === undefined && Number.isSafeInteger(data?.turn), '会话日志中存在未关闭的回合。');
67
+ const candidate = queues['next-turn'][0];
50
68
  turn = {
51
69
  index,
52
70
  number: data.turn,
53
- input: queues['next-turn'][0],
71
+ time: event.time,
72
+ input: candidate?.id === messageId ? candidate : undefined,
54
73
  queuedCount: queues['next-turn'].length,
55
74
  hasSteering: queues['next-step'].length > 0,
56
75
  };
57
76
  } else if (event.type === 'turn/end') {
58
- requireRevision(turn?.number === data.turn, '会话日志的回合边界不完整。');
77
+ requireRevision(turn !== undefined && turn.number === data?.turn, '会话日志的回合边界不完整。');
59
78
  turn = undefined;
60
79
  } else if (event.type === 'user/message' && data?.id === messageId && data.source?.kind === 'user') {
61
80
  requireRevision(selected === undefined, '日志中找到了重复的用户消息。');
62
81
  selected = event;
63
82
  checkpoint = turn;
83
+ if (checkpoint) inputCopies = inputCopies.filter(item => item.index < checkpoint.index);
64
84
  }
85
+ index++;
65
86
  }
66
87
  requireRevision(turn === undefined, '回复生成中,请先停止或等待完成。');
67
88
  requireRevision(selected && checkpoint?.input?.message.id === messageId
@@ -76,7 +97,7 @@ export function planRevision(events, messageId, inheritedCount = 0) {
76
97
  return {
77
98
  cut: checkpoint.index,
78
99
  retainedInputs,
79
- time: events[checkpoint.index].time,
100
+ time: checkpoint.time,
80
101
  message: checkpoint.input.message,
81
102
  };
82
103
  }
@@ -111,7 +132,7 @@ export function resolveRevisionText(message, { text, textParts }) {
111
132
  return [text];
112
133
  }
113
134
 
114
- function rewriteMessage(message, input, removed, added) {
135
+ export function rewriteMessage(message, input, removed, added) {
115
136
  const retained = retainedRevisionAttachments(message, removed);
116
137
  const textParts = resolveRevisionText(message, input);
117
138
  requireRevision(input.text.trim() !== '' || retained.length > 0 || added.length > 0, '请输入消息内容或至少保留一个附件。');
@@ -143,22 +164,29 @@ function checkLocation(snapshot) {
143
164
  return path;
144
165
  }
145
166
 
167
+ async function checkedRolloutPath(dshPath) {
168
+ const path = await resolveRolloutPath(dshPath);
169
+ requireRevision(path !== undefined, '会话日志路径异常。');
170
+ return path;
171
+ }
172
+
146
173
  async function checkArtifact(path) {
147
174
  const identity = await lstat(path, { bigint: true });
148
- requireRevision(identity.isFile() && !identity.isSymbolicLink() && await realpath(path) === path,
175
+ requireRevision(identity.isFile() && !identity.isSymbolicLink() && await isCanonicalPath(path),
149
176
  '会话日志路径异常。');
150
177
  requireRevision(identity.size <= maxBytes, '会话日志超出大小上限,无法编辑。');
151
178
  return identity;
152
179
  }
153
180
 
154
181
  async function openLocked(persistence, sessionId, snapshot) {
155
- const path = checkLocation(snapshot);
182
+ const dshPath = checkLocation(snapshot);
183
+ const path = await checkedRolloutPath(dshPath);
156
184
  const identity = await checkArtifact(path);
157
185
  const handle = await persistence.open(sessionId, 'write');
158
186
  try {
159
187
  const current = await persistence.stat(sessionId);
160
- requireRevision(handle.header.id === sessionId && checkLocation(current) === path
161
- && current.revision === snapshot.revision, '会话状态已变更,请刷新后重试。');
188
+ requireRevision(handle.header.id === sessionId && isSamePath(checkLocation(current), dshPath)
189
+ && current.revision === snapshot.revision && isSamePath(await resolveRolloutPath(dshPath), path), '会话状态已变更,请刷新后重试。');
162
190
  const { events } = await handle.read(0);
163
191
  return { handle, path, identity, events, snapshot: current };
164
192
  } catch (error) {
@@ -170,7 +198,7 @@ async function openLocked(persistence, sessionId, snapshot) {
170
198
  async function encodeReplacement(source, plan, message, controls, restoredCatalog) {
171
199
  const compressed = source.path.endsWith('.zstd');
172
200
  const raw = await readFile(source.path);
173
- const decoded = compressed ? await decompress(raw, { maxOutputLength: maxBytes }) : raw;
201
+ const decoded = compressed ? decompressZstdConcat(raw, { maxOutputLength: maxBytes }) : raw;
174
202
  const lines = utf8.decode(decoded).split('\n');
175
203
  requireRevision(lines.pop() === '' && lines.length === source.events.length + 1,
176
204
  '会话日志不完整,已取消编辑。');
@@ -305,7 +333,7 @@ async function replaceArtifact(source, buffers, beforeReplace, onPublished, stag
305
333
  await checkUnchanged(source);
306
334
  await beforeReplace?.();
307
335
  await checkUnchanged(source);
308
- await rename(stage, source.path);
336
+ await replaceFileDurable(stage, source.path);
309
337
  pending = false;
310
338
  onPublished?.();
311
339
  if (process.platform !== 'win32') {
@@ -317,19 +345,6 @@ async function replaceArtifact(source, buffers, beforeReplace, onPublished, stag
317
345
  }
318
346
  }
319
347
 
320
- function isProvisionalOpenEvent(event) {
321
- // A failed initializer may have persisted settings or other native events.
322
- // A turn or an accepted human input could belong to a different operation.
323
- const { data } = event;
324
- if (event.type === 'turn/start' || event.type === 'step/start'
325
- || (event.type === 'user/message' && data.source?.kind === 'user')) return false;
326
- if (event.type !== 'agent/inbox/spliced') return true;
327
- return (data.removedCount ?? 0) === 0
328
- ? data.inserted?.every(message => message.source?.kind !== 'user' && message.source?.kind !== 'retry')
329
- : data.target === 'next-turn' && data.start === 0 && data.removedCount === 1
330
- && data.inserted?.length === 0 && data.outcome === 'canceled';
331
- }
332
-
333
348
  async function recoverRewrite(source, journal, { canRollback, beforeCommit } = {}) {
334
349
  if (journal.committed) return;
335
350
  const revision = await matchJournalRevision(journal);
@@ -340,7 +355,8 @@ async function recoverRewrite(source, journal, { canRollback, beforeCommit } = {
340
355
  return;
341
356
  }
342
357
  const retained = journal.intent.candidate.records;
343
- requireRevision(source.events.length >= retained && source.events.slice(retained).every(isProvisionalOpenEvent),
358
+ requireRevision(source.events.length >= retained
359
+ && source.events.slice(retained).every(event => isProvisionalResumeMarker(event, retained)),
344
360
  '更新后的会话已有新增内容,无法自动回滚。');
345
361
  const original = await readRewriteOriginal(journal);
346
362
  await replaceArtifact(source, [original], async () => {
@@ -349,37 +365,140 @@ async function recoverRewrite(source, journal, { canRollback, beforeCommit } = {
349
365
  }, undefined, journal.directory);
350
366
  }
351
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
+
352
438
  /** Recover transactions left by a previous Host before admitting new rewrites. */
353
- export async function recoverStoredSessions(persistence, { beforeCommit, canRollback, onError } = {}) {
439
+ export async function recoverStoredSessions(persistence, options = {}) {
440
+ const { onError, retrySignal } = options;
441
+ const locked = new Set();
354
442
  for (const snapshot of await persistence.list()) {
443
+ if (retrySignal?.aborted) break;
355
444
  const { id } = snapshot.header;
356
445
  try {
357
- const journals = await readRewriteJournals(snapshot);
358
- if (snapshot.location?.kind !== 'jsonl' || !isAbsolute(snapshot.location.path)) continue;
359
- const { preparations, retired } = await listRewriteDebris(snapshot.location.path);
360
- if (journals.length > 0 || preparations.length > 0) {
361
- const source = await openLocked(persistence, id, snapshot);
362
- try {
363
- // The journal may have been retired between scanning and claiming the lock.
364
- for (const journal of await readRewriteJournals(source.snapshot)) {
365
- await recoverRewrite(source, journal, { beforeCommit, canRollback: () => canRollback?.(id) ?? true });
366
- await retireRewriteJournal(journal);
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();
367
473
  }
368
- await cleanRewriteDebris((await listRewriteDebris(source.path)).preparations);
369
- } finally {
370
- await source.handle.close();
371
474
  }
372
475
  }
373
476
  await cleanRewriteDebris(retired);
374
477
  } catch (error) {
478
+ if (retrySignal && error.name === 'SessionAlreadyOwnedError') locked.add(id);
375
479
  onError?.(id, error);
376
480
  }
377
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;
378
495
  }
379
496
 
380
497
  export async function assertNoPendingRewrite(snapshot) {
381
498
  if (snapshot?.location?.kind === 'jsonl') {
382
- requireRevision(!await hasPendingRewrite(checkLocation(snapshot)), '上次编辑尚未完成恢复,请检查运行日志。');
499
+ const path = await checkedRolloutPath(checkLocation(snapshot));
500
+ await retrySettledRewriteRetirement(path);
501
+ requireRevision(!await hasPendingRewrite(path), '上次编辑尚未完成恢复,请检查运行日志。');
383
502
  }
384
503
  }
385
504
 
@@ -419,8 +538,6 @@ export async function rewriteStoredSession(persistence, {
419
538
  const seen = new Set([sessionId]);
420
539
  await collectChildTree(persistence, source, retained, plan.time, retainedChildren, seen);
421
540
  await collectChildTree(persistence, source, withdrawn, undefined, withdrawnChildren, seen);
422
- requireRevision(withdrawnChildren.length === 0 || process.platform !== 'win32',
423
- '当前系统不支持清理关联的子智能体会话。');
424
541
  const message = rewriteMessage(plan.message, { text, textParts }, removedAttachments, addedAttachments);
425
542
  const replacement = await encodeReplacement(source, plan, message, controls, retained.filter(event => event.seq >= plan.cut));
426
543
  const removedChildren = withdrawnChildren.map(child => child.handle.header.id);
@@ -462,7 +579,7 @@ export async function rewriteStoredSession(persistence, {
462
579
  if (markerFailed) await closeFailedReload?.();
463
580
  const current = await openLocked(persistence, sessionId, await persistence.stat(sessionId));
464
581
  try {
465
- requireRevision(current.path === source.path && (canRollback?.() ?? true), '无法确认候选会话已释放。');
582
+ requireRevision(isSamePath(current.path, source.path) && (canRollback?.() ?? true), '无法确认候选会话已释放。');
466
583
  if (markerFailed) await clearFailedCommitMarker(journal);
467
584
  await recoverRewrite(current, journal, { canRollback, beforeCommit });
468
585
  } finally {