@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/index.js CHANGED
@@ -1,7 +1,14 @@
1
1
  import {
2
- assertNoPendingRewrite, isRevisionAttachment, planRevision, recoverStoredSessions, resolveRevisionText,
3
- retainedRevisionAttachments, RevisionError, revisionTextParts, rewriteStoredSession, splitChildCatalog,
2
+ assertNoPendingRewrite, isRevisionAttachment, planRevision, recoverPendingRewrite, recoverStoredSessions,
3
+ resolveRevisionText, retainedRevisionAttachments, RevisionError, revisionTextParts, rewriteMessage,
4
4
  } from './revision.js';
5
+ import { prepareBoundedRevision, revalidateWork } from './bounded-revision.js';
6
+ import { commitBoundedRevision, restoreBoundedJournal } from './bounded-commit.js';
7
+ import {
8
+ assertRewriteSetSpace, matchJournalRevision, readRewriteJournals, RewriteJournalSpaceError, scheduleSettledRewriteRetirement,
9
+ } from './rewrite-journal.js';
10
+ import { createRevisionNotifications, registerRevisionNotifications } from './revision-notifications.js';
11
+ import { isSamePath, resolveRolloutPath } from './platform.js';
5
12
 
6
13
  export const name = 'message-revision';
7
14
  export const inject = ['agents', 'connection', 'sessionController', 'sessionPersistence', 'sessions'];
@@ -11,9 +18,16 @@ const originalSymbol = Symbol.for('cordis.original');
11
18
  const headers = { 'Cache-Control': 'no-store' };
12
19
  const BUSY = '回复生成中,请先停止或等待完成。';
13
20
  const toolbarRevision = 1;
21
+ const activeRevision = Symbol.for('dsh-message-revision.active-rewrite');
22
+
23
+ function assertIdlePhase(agent) {
24
+ // This rc.5 driver reports its private maintenance phase as public idle.
25
+ if (agent.phase?.kind === 'maintenance') throw new RevisionError('会话正在维护或压缩上下文,请等操作完成后重试。');
26
+ if (agent.status !== 'idle' || (agent.phase !== undefined && agent.phase?.kind !== 'idle')) throw new RevisionError(BUSY);
27
+ }
14
28
 
15
29
  function assertIdle(agent) {
16
- if (agent.status !== 'idle') throw new RevisionError(BUSY);
30
+ assertIdlePhase(agent);
17
31
  if (agent.inbox.hasPending) throw new RevisionError('会话仍有排队消息,请等队列清空后再试。');
18
32
  }
19
33
 
@@ -45,6 +59,7 @@ function lifecycleDisposer(ctx, agent) {
45
59
  // The latest controller registration is the live generation. Its native
46
60
  // teardown must also release the exact scope of the Agent we're replacing.
47
61
  const active = lifecycle.at(-1);
62
+ assertIdlePhase(agent);
48
63
  await active();
49
64
  if ([...loop._disposables].includes(scope) || [...owner._disposables].includes(active)) throw failure();
50
65
  // Older revisions of this plugin could leave completed owner registrations.
@@ -57,17 +72,19 @@ async function assertNoActivity(ctx, sessionId) {
57
72
  if (activities?.length) throw new RevisionError(BUSY);
58
73
  }
59
74
 
60
- function assertChildrenIdle(ctx, agent, events, plan) {
61
- const catalog = events.slice(agent.session.inheritedEventCount)
62
- .filter(event => event.type === 'subagent/catalog');
63
- const { withdrawn } = splitChildCatalog(catalog, plan);
64
- const childIds = new Set(catalog.map(event => event.data.childId));
65
- if (ctx.agents.list().some(candidate => childIds.has(candidate.id) && candidate.status !== 'idle')) {
66
- throw new RevisionError('子智能体仍在运行,请等执行结束后再试。');
75
+ function assertChildrenReleased(ctx, work) {
76
+ for (const { header: { id } } of work.entries.slice(1)) {
77
+ if (ctx.agents.get(id) || ctx.sessions.get(id)) {
78
+ throw new RevisionError('关联的子智能体会话仍处于打开状态,请关闭后重试。');
79
+ }
67
80
  }
68
- const withdrawnIds = new Set(withdrawn.map(event => event.data.childId));
69
- if (ctx.agents.list().some(candidate => withdrawnIds.has(candidate.id))) {
70
- throw new RevisionError('关联的子智能体会话仍处于打开状态,请关闭后重试。');
81
+ }
82
+
83
+ function* nativeEvents(session, end = session.seq, start = 0) {
84
+ // Use bounded ranges of the immutable native log instead of retaining a
85
+ // second array of every event while the candidate is prepared or reopened.
86
+ for (let offset = start; offset < end; offset += 512) {
87
+ yield* session.snapshotEvents(offset, Math.min(end, offset + 512));
71
88
  }
72
89
  }
73
90
 
@@ -76,7 +93,7 @@ function editableAgent(ctx, sessionId) {
76
93
  if (!agent || ctx.sessions.get(sessionId) !== agent.session) {
77
94
  throw new RevisionError('请先打开该会话。');
78
95
  }
79
- if (agent.session.header.origin === 'subagent' || agent.session.header.parentSession) {
96
+ if (agent.session.header.origin === 'subagent') {
80
97
  throw new RevisionError('子智能体会话不支持直接编辑,请在主会话中操作。');
81
98
  }
82
99
  assertIdle(agent);
@@ -91,20 +108,34 @@ function lastPermissionEvents(events) {
91
108
  return latest;
92
109
  }
93
110
 
94
- function modelAt(events) {
95
- let pending;
96
- let lastUsed;
111
+ function foldControlState(events, cut) {
112
+ const currentPermissions = new Map();
113
+ const retainedPermissions = new Map();
114
+ let pendingModel;
115
+ let lastUsedModel;
116
+ let retainedModel;
117
+ let capturedPrefix = false;
97
118
  for (const event of events) {
98
- if (event.type === 'model/selection') pending = event.data;
99
- if (event.type === 'request/header') {
119
+ if (!capturedPrefix && event.seq >= cut) {
120
+ retainedModel = pendingModel ?? lastUsedModel;
121
+ capturedPrefix = true;
122
+ }
123
+ if (permissionEvents.includes(event.type)) {
124
+ currentPermissions.set(event.type, event);
125
+ if (event.seq < cut) retainedPermissions.set(event.type, event);
126
+ } else if (event.type === 'model/selection') {
127
+ pendingModel = event.data;
128
+ } else if (event.type === 'request/header') {
100
129
  const { config, adapterDefaults } = event.data.header;
101
130
  const effort = adapterDefaults?.reasoningEffort === true ? undefined : config.reasoningEffort;
102
- lastUsed = { provider: config.provider, model: config.model,
131
+ lastUsedModel = { provider: config.provider, model: config.model,
103
132
  ...(effort === undefined ? {} : { reasoningEffort: effort }) };
104
- if (sameModel(pending, lastUsed)) pending = undefined;
133
+ if (sameModel(pendingModel, lastUsedModel)) pendingModel = undefined;
105
134
  }
106
135
  }
107
- return pending ?? lastUsed;
136
+ const currentModel = pendingModel ?? lastUsedModel;
137
+ if (!capturedPrefix) retainedModel = currentModel;
138
+ return { currentPermissions, retainedPermissions, currentModel, retainedModel };
108
139
  }
109
140
 
110
141
  function sameModel(first, second) {
@@ -112,9 +143,7 @@ function sameModel(first, second) {
112
143
  && first?.reasoningEffort === second?.reasoningEffort;
113
144
  }
114
145
 
115
- function preparePermissions(ctx, agent, events, prefix, preset) {
116
- const current = lastPermissionEvents(events);
117
- const retained = lastPermissionEvents(prefix);
146
+ function preparePermissions(ctx, agent, current, retained, preset) {
118
147
  if (preset !== undefined) {
119
148
  const service = ctx.get('permissionPresets');
120
149
  if (!service || preset === 'custom') throw new RevisionError('不支持该权限预设。');
@@ -139,8 +168,8 @@ function preparePermissions(ctx, agent, events, prefix, preset) {
139
168
  });
140
169
  }
141
170
 
142
- async function prepareAmendments(ctx, agent, input, events, plan) {
143
- const retained = retainedRevisionAttachments(plan.message, input.removedAttachments);
171
+ async function prepareRevisionInputs(ctx, agent, input, original, settings) {
172
+ const retained = retainedRevisionAttachments(original, input.removedAttachments);
144
173
  const receiptIds = input.receiptIds ?? [];
145
174
  const uploads = receiptIds.length === 0 ? undefined : ctx.get('fileUploads');
146
175
  const staged = receiptIds.map(id => {
@@ -151,9 +180,15 @@ async function prepareAmendments(ctx, agent, input, events, plan) {
151
180
  if (input.text.trim() === '' && retained.length + staged.length === 0) {
152
181
  throw new RevisionError('请输入消息内容或至少保留一个附件。');
153
182
  }
154
- const prefix = events.slice(0, plan.cut);
155
- const model = input.model ?? agent.model.current();
156
- const hasImages = [...retained, ...staged].some(part => part.type === 'image');
183
+ const stagedImages = staged.some(part => part.type === 'image');
184
+ const retainedImages = retained.some(part => part.type === 'image');
185
+ // Native admission counts upload bytes. Historical image references only
186
+ // contain the normalized size, even if no originalDimensions are present.
187
+ if (stagedImages && retainedImages) {
188
+ throw new RevisionError('旧图片的原始上传大小无法核对。请移除旧图片,或用原文件重新添加后再发送。');
189
+ }
190
+ const model = input.model ?? settings.model;
191
+ const hasImages = stagedImages || retainedImages;
157
192
  const llm = input.model || hasImages ? ctx.get('llm') : undefined;
158
193
  if (input.model) {
159
194
  try {
@@ -181,19 +216,21 @@ async function prepareAmendments(ctx, agent, input, events, plan) {
181
216
  const attachments = ctx.get('attachments');
182
217
  if (!attachments) throw new RevisionError('当前环境不支持上传附件。');
183
218
  try {
184
- // Count retained images against the same combined native message limits.
185
- const images = retained.filter(part => part.type === 'image')
186
- .map(part => ({ ...part, encodedBytes: part.attachment.bytes }));
187
- addedAttachments = (await attachments.admitPromptContent([...images, ...staged])).slice(images.length);
219
+ addedAttachments = await attachments.admitPromptContent(staged);
188
220
  } catch (error) {
189
221
  throw new RevisionError('附件校验未通过,请重新添加。', { cause: error });
190
222
  }
191
223
  }
192
- const controls = preparePermissions(ctx, agent, events, prefix, input.permissionPreset);
193
- if (model && !sameModel(model, modelAt(prefix)) && (input.model || modelAt(events))) {
224
+ return { retained, addedAttachments, model };
225
+ }
226
+
227
+ function revisionControls(ctx, agent, input, cut, model) {
228
+ const { currentPermissions, retainedPermissions, currentModel, retainedModel } = foldControlState(nativeEvents(agent.session), cut);
229
+ const controls = preparePermissions(ctx, agent, currentPermissions, retainedPermissions, input.permissionPreset);
230
+ if (model && !sameModel(model, retainedModel) && (input.model || currentModel)) {
194
231
  controls.push({ type: 'model/selection', data: model });
195
232
  }
196
- return { addedAttachments, controls };
233
+ return controls;
197
234
  }
198
235
 
199
236
  function revisionSettings(ctx, agent) {
@@ -226,7 +263,27 @@ async function isUnchangedRevision(ctx, input, original, settings) {
226
263
  && await sameEffectiveModel(ctx, input.model, settings.model);
227
264
  }
228
265
 
229
- async function inspectRevision(ctx, { sessionId, messageId }) {
266
+ async function recoverEditableSession(ctx, sessionId, recoverDelivery) {
267
+ let restored;
268
+ try {
269
+ restored = await recoverPendingRewrite(ctx.sessionPersistence, await ctx.sessionPersistence.stat(sessionId), {
270
+ beforeCommit: revisionCacheInvalidator(ctx),
271
+ canRollback: id => !ctx.agents.get(id) && !ctx.sessions.get(id),
272
+ restoreBoundedJournal,
273
+ recoverDelivery: recoverDelivery && (journal => recoverDelivery(journal.intent.parentId)),
274
+ });
275
+ } catch (error) {
276
+ if (error?.name === 'SessionAlreadyOwnedError') {
277
+ throw new RevisionError('上次编辑仍在等待会话释放,稍后可重新打开编辑框。', { cause: error });
278
+ }
279
+ if (error?.name === 'RewriteRollbackConflictError') throw new RevisionError(error.message, { cause: error });
280
+ throw error;
281
+ }
282
+ if (restored) await ctx.sessionController.resolveAgent(sessionId);
283
+ }
284
+
285
+ async function inspectRevision(ctx, { sessionId, messageId }, recoverDelivery) {
286
+ await recoverEditableSession(ctx, sessionId, recoverDelivery);
230
287
  const agent = editableAgent(ctx, sessionId);
231
288
  await ctx.sessions.flush(agent.session);
232
289
  const snapshot = await ctx.sessionPersistence.stat(sessionId);
@@ -234,17 +291,186 @@ async function inspectRevision(ctx, { sessionId, messageId }) {
234
291
  throw new RevisionError('会话状态已变更,请刷新后重试。');
235
292
  }
236
293
  await assertNoPendingRewrite(snapshot);
237
- const events = agent.session.snapshotEvents();
238
- const plan = planRevision(events, messageId, agent.session.inheritedEventCount);
239
- const textParts = revisionTextParts(plan.message);
294
+ const { message } = planRevision(nativeEvents(agent.session), messageId, agent.session.inheritedEventCount);
295
+ const textParts = revisionTextParts(message);
240
296
  return { ok: true, toolbarRevision, revision: snapshot.revision,
241
297
  text: textParts.join(''), textParts, settings: revisionSettings(ctx, agent),
242
- attachments: plan.message.content.flatMap((block, index) => isRevisionAttachment(block) ? [{ index, block }] : []),
298
+ attachments: message.content.flatMap((block, index) => isRevisionAttachment(block) ? [{ index, block }] : []),
243
299
  };
244
300
  }
245
301
 
246
302
  function deliveredRevision(agent, messageId) {
247
- return agent.session.snapshotEvents().some(event => event.type === 'user/message' && event.data.id === messageId);
303
+ for (const event of nativeEvents(agent.session)) {
304
+ if (event.type === 'user/message' && event.data.id === messageId) return true;
305
+ }
306
+ return false;
307
+ }
308
+
309
+ function committedPromptState(agent, journal) {
310
+ const { messageId } = journal.intent.delivery;
311
+ const begin = journal.intent.artifacts[0].candidate.records;
312
+ if (agent.session.seq < begin) throw new Error('Native session does not contain the committed revision');
313
+ // The committed candidate starts with exactly one pending next-turn item.
314
+ let position = 0;
315
+ let turn;
316
+ let claim;
317
+ for (const { type, data } of nativeEvents(agent.session, agent.session.seq, begin)) {
318
+ if (type === 'user/message' && data.id === messageId) return 'settled';
319
+ if (type === 'turn/start') {
320
+ turn = data.turn;
321
+ } else if (type === 'turn/end' && data.turn === turn) {
322
+ if (claim?.turn === data.turn) {
323
+ // A closed turn with recorded execution must not submit its input again.
324
+ if (data.reason.kind !== 'interrupted' || claim.executed) return 'settled';
325
+ claim.interrupted = true;
326
+ }
327
+ turn = undefined;
328
+ }
329
+ if (claim && turn === claim.turn && data.turn === claim.turn
330
+ && (type === 'assistant/message' || type === 'assistant/attempt' || type === 'tool/call' || type === 'tool/result')) {
331
+ claim.executed = true;
332
+ }
333
+ if (type !== 'agent/inbox/spliced' || data.target !== 'next-turn') continue;
334
+ const replacement = data.inserted.findIndex(message => message.id === messageId);
335
+ if (position === undefined) {
336
+ if (replacement >= 0) {
337
+ position = data.start + replacement;
338
+ claim = undefined;
339
+ }
340
+ continue;
341
+ }
342
+ if (position < data.start) continue;
343
+ const removed = data.removedCount ?? 0;
344
+ if (position < data.start + removed) {
345
+ if (replacement < 0) {
346
+ if (data.outcome === 'canceled') return 'settled';
347
+ if (turn === undefined) throw new Error('Native inbox claimed the committed input outside a turn');
348
+ position = undefined;
349
+ claim = { turn, executed: false, interrupted: false };
350
+ } else position = data.start + replacement;
351
+ } else position += data.inserted.length - removed;
352
+ }
353
+ if (position === undefined) return claim?.interrupted ? 'interrupted' : 'claimed';
354
+ if (agent.inbox.nextTurn[position]?.id !== messageId) throw new Error('Cannot reconcile the committed input with the native inbox');
355
+ return 'pending';
356
+ }
357
+
358
+ function findCommittedInput(session, journal) {
359
+ const { messageId } = journal.intent.delivery;
360
+ const begin = journal.intent.artifacts[0].candidate.records;
361
+ for (let end = begin; end > 0; end -= 512) {
362
+ const events = session.snapshotEvents(Math.max(0, end - 512), end);
363
+ for (let index = events.length - 1; index >= 0; index--) {
364
+ const { type, data } = events[index];
365
+ if (type !== 'agent/inbox/spliced' || data.target !== 'next-turn') continue;
366
+ const message = data.inserted.find(item => item.id === messageId);
367
+ if (message) return message;
368
+ }
369
+ }
370
+ throw new Error('Cannot find the revision input in the committed history');
371
+ }
372
+
373
+ async function deliverCommittedPrompt(ctx, agent, journal) {
374
+ const { parentId } = journal.intent;
375
+ if (ctx.agents.get(parentId) !== agent || ctx.sessions.get(parentId) !== agent.session) return 'waiting';
376
+ const state = committedPromptState(agent, journal);
377
+ if (state === 'settled') return await ctx.sessions.flush(agent.session) === true ? 'settled' : 'waiting';
378
+ if (state === 'claimed') return 'started';
379
+ if (agent.status !== 'idle' || agent.inbox.nextStep.length !== 0) return 'waiting';
380
+ if (state === 'interrupted') {
381
+ if (agent.inbox.nextTurn.length !== 0) return 'waiting';
382
+ // Native recovery durably closed an earlier claim before its user/message.
383
+ // Restore the same input only after confirming no request or tool ran.
384
+ agent.followup(findCommittedInput(agent.session, journal));
385
+ } else {
386
+ if (agent.inbox.nextTurn.length !== 1) return 'waiting';
387
+ // rc.5 can wake the existing queue item without another enqueue record.
388
+ if (typeof agent.wakeDriver !== 'function') throw new Error('Native inbox wakeup is unavailable');
389
+ agent.wakeDriver();
390
+ }
391
+ const after = committedPromptState(agent, journal);
392
+ return after === 'settled' && await ctx.sessions.flush(agent.session) === true ? 'settled' : 'started';
393
+ }
394
+
395
+ async function recoverCommittedPrompt(ctx, journal) {
396
+ const { parentId } = journal.intent;
397
+ let agent = ctx.agents.get(parentId);
398
+ const snapshot = agent ? undefined : await ctx.sessionPersistence.stat(parentId);
399
+ if (await matchJournalRevision(journal) !== 'candidate') throw new Error('Committed revision no longer matches its journal');
400
+ if (!agent) {
401
+ if (!isSamePath(snapshot?.location?.path, journal.dshPath ?? journal.parentPath) || ctx.sessions.get(parentId)
402
+ || !isSamePath(await resolveRolloutPath(snapshot.location.path), journal.parentPath)
403
+ || (await ctx.sessionPersistence.stat(parentId))?.revision !== snapshot.revision) return 'waiting';
404
+ const reopened = await ctx.sessionController.resolveAgent(parentId);
405
+ if (!reopened.agent) throw reopened.error ?? new Error('Cannot reopen the committed session');
406
+ agent = reopened.agent;
407
+ }
408
+ return deliverCommittedPrompt(ctx, agent, journal);
409
+ }
410
+
411
+ function installDeliveryRecovery(ctx) {
412
+ const tracked = new Set();
413
+ const pending = new Set();
414
+ let timer;
415
+ let started = false;
416
+ let disposed = false;
417
+ let running = false;
418
+ let currentId;
419
+ // Process outstanding deliveries serially after the initial journal scan.
420
+ // A failed cold open waits for the session's next native activation.
421
+ function schedule() {
422
+ if (!started || timer || running || disposed || pending.size === 0) return;
423
+ timer = setImmediate(() => { timer = undefined; void run(); });
424
+ timer.unref?.();
425
+ }
426
+ async function run() {
427
+ running = true;
428
+ try {
429
+ for (const id of pending) {
430
+ if (disposed) break;
431
+ pending.delete(id);
432
+ currentId = id;
433
+ try {
434
+ const snapshot = await ctx.sessionPersistence.stat(id);
435
+ const journal = (await readRewriteJournals(snapshot)).find(entry => entry.committed && entry.intent.delivery);
436
+ if (!journal) {
437
+ tracked.delete(id);
438
+ pending.delete(id);
439
+ } else if (await recoverCommittedPrompt(ctx, journal) === 'settled') {
440
+ scheduleSettledRewriteRetirement(journal, { onCleanupError(error) {
441
+ ctx.logger.warn('Saved message revision cleanup failed for %s: %s', id, error);
442
+ } });
443
+ tracked.delete(id);
444
+ pending.delete(id);
445
+ }
446
+ } catch (error) {
447
+ ctx.logger.warn('Pending message revision delivery for %s: %s', id, error);
448
+ } finally { currentId = undefined; }
449
+ }
450
+ } finally {
451
+ running = false;
452
+ schedule();
453
+ }
454
+ }
455
+ function track(id) { tracked.add(id); pending.add(id); schedule(); }
456
+ function onAgent(agent) {
457
+ if (agent.id !== currentId && tracked.has(agent.id)) { pending.add(agent.id); schedule(); }
458
+ }
459
+ ctx.effect(() => {
460
+ const created = ctx.on('agent/created', ({ agent }) => onAgent(agent));
461
+ const idle = ctx.on('agent/status', ({ agent, status }) => { if (status === 'idle') onAgent(agent); });
462
+ const finish = ctx.on('session/event', (session, event) => {
463
+ if (event.type !== 'user/message' && event.type !== 'turn/end') return;
464
+ const agent = ctx.agents.get(session.id);
465
+ if (agent?.session !== session || !tracked.has(agent.id)) return;
466
+ // Delivery can finish while this very session is being checked. Revisit
467
+ // it afterwards if that check did not already observe the final event.
468
+ pending.add(agent.id);
469
+ schedule();
470
+ });
471
+ return () => { disposed = true; clearImmediate(timer); created(); idle(); finish(); pending.clear(); tracked.clear(); };
472
+ });
473
+ return { track, start() { started = true; schedule(); } };
248
474
  }
249
475
 
250
476
  function revisionCacheInvalidator(ctx) {
@@ -256,55 +482,93 @@ function revisionCacheInvalidator(ctx) {
256
482
  }
257
483
 
258
484
  /** The Web route and isolated tests share this host operation. */
259
- export async function reviseSession(ctx, input, { onReopening } = {}) {
485
+ export async function reviseSession(ctx, input, options = {}) {
260
486
  const { sessionId, messageId } = input;
487
+ await recoverEditableSession(ctx, sessionId, options.recoverDelivery);
261
488
  const agent = editableAgent(ctx, sessionId);
262
489
  await assertNoActivity(ctx, sessionId);
263
490
  await ctx.sessions.flush(agent.session);
264
491
  await assertNoActivity(ctx, sessionId);
265
492
  const snapshot = await ctx.sessionPersistence.stat(sessionId);
266
493
  await assertNoPendingRewrite(snapshot);
267
- if (input.expectedRevision !== undefined) {
268
- if (snapshot?.revision !== input.expectedRevision) {
269
- throw new RevisionError('会话状态已变更,请重新打开编辑框。');
270
- }
271
- }
272
- assertIdle(agent);
273
- if (ctx.agents.get(sessionId) !== agent || ctx.sessions.get(sessionId) !== agent.session) {
274
- throw new RevisionError('会话状态已变更,请刷新后重试。');
494
+ if (input.expectedRevision !== undefined && snapshot?.revision !== input.expectedRevision) {
495
+ throw new RevisionError('会话状态已变更,请重新打开编辑框。');
275
496
  }
276
- const events = agent.session.snapshotEvents();
277
- const plan = planRevision(events, messageId, agent.session.inheritedEventCount);
278
- if (await isUnchangedRevision(ctx, input, plan.message, revisionSettings(ctx, agent))) {
279
- return { ok: true, unchanged: true };
497
+ if (editableAgent(ctx, sessionId) !== agent) throw new RevisionError('会话状态已变更,请刷新后重试。');
498
+ const seq = agent.session.seq;
499
+ const { message: original } = planRevision(nativeEvents(agent.session, seq), messageId, agent.session.inheritedEventCount);
500
+ const settings = revisionSettings(ctx, agent);
501
+ // Provider lookups can take arbitrarily long. Complete them before claiming
502
+ // the single resource slot used by the log worker and transaction.
503
+ if (await isUnchangedRevision(ctx, input, original, settings)) return { ok: true, unchanged: true };
504
+ const prepared = await prepareRevisionInputs(ctx, agent, input, original, settings);
505
+ options.signal?.throwIfAborted();
506
+ if (globalThis[activeRevision]) throw new RevisionError('已有会话正在编辑,请稍后重试。');
507
+ globalThis[activeRevision] = true;
508
+ try {
509
+ return await reviseSessionExclusive(ctx, input, { agent, seq, snapshot, prepared }, options);
510
+ } finally {
511
+ globalThis[activeRevision] = false;
280
512
  }
513
+ }
514
+
515
+ async function reviseSessionExclusive(ctx, input, { agent, seq, snapshot, prepared },
516
+ { onReopening, onCommitted, signal, recoverDelivery }) {
517
+ const { sessionId, messageId } = input;
518
+ const validateAgent = () => {
519
+ if (editableAgent(ctx, sessionId) !== agent || agent.session.seq !== seq
520
+ || (!input.model && !sameModel(agent.model.current(), prepared.model))) {
521
+ throw new RevisionError('会话状态已变更,请重新提交。');
522
+ }
523
+ };
524
+ validateAgent();
525
+ if (typeof agent.wakeDriver !== 'function') throw new RevisionError('当前 DSH 版本不支持安全重发编辑后的消息。');
281
526
  const dispose = lifecycleDisposer(ctx, agent);
282
- assertChildrenIdle(ctx, agent, events, plan);
283
- const amendments = await prepareAmendments(ctx, agent, input, events, plan);
284
- await ctx.sessions.flush(agent.session);
285
- await assertNoActivity(ctx, sessionId);
286
- if (editableAgent(ctx, sessionId) !== agent || agent.session.seq !== events.length) {
287
- throw new RevisionError('会话状态已变更,请刷新后重试。');
288
- }
289
- assertChildrenIdle(ctx, agent, events, plan);
290
- onReopening?.();
291
- await dispose();
292
- if (ctx.sessions.get(sessionId) || ctx.agents.get(sessionId)) {
293
- throw new RevisionError('会话仍在释放中,请稍后重试。');
294
- }
527
+ const work = await prepareBoundedRevision(ctx.sessionPersistence, snapshot, messageId, plan => {
528
+ validateAgent();
529
+ const [record] = agent.session.snapshotEvents(plan.input.index, plan.input.index + 1);
530
+ const queued = record?.type === 'agent/inbox/spliced' && record.data.inserted?.[plan.input.offset];
531
+ if (queued?.id !== messageId || queued.source?.kind !== 'user') {
532
+ throw new RevisionError('无法核对原消息的入队记录,请重新打开编辑框。');
533
+ }
534
+ const retained = retainedRevisionAttachments(queued, input.removedAttachments);
535
+ if (JSON.stringify(retained) !== JSON.stringify(prepared.retained)) {
536
+ throw new RevisionError('会话附件与原始消息不一致,请重新打开编辑框。');
537
+ }
538
+ const controls = revisionControls(ctx, agent, input, plan.cut, prepared.model);
539
+ const { content } = rewriteMessage(queued, input, input.removedAttachments ?? [], prepared.addedAttachments);
540
+ return { message: { id: messageId, content }, controls };
541
+ }, { signal, eventCount: seq, inheritedCount: agent.session.inheritedEventCount });
542
+ if (!work) return { ok: true, unchanged: true };
295
543
 
296
- let rewritten;
544
+ const rewrittenChildren = work.artifacts.slice(1).map(artifact => artifact.header.id);
545
+ let childChanges;
297
546
  let updated;
298
547
  let reopenedSeq;
548
+ let released = false;
299
549
  try {
300
- rewritten = await rewriteStoredSession(ctx.sessionPersistence, input, {
301
- ...amendments,
550
+ await ctx.sessions.flush(agent.session);
551
+ await assertNoActivity(ctx, sessionId);
552
+ await revalidateWork(ctx.sessionPersistence, work);
553
+ await assertNoPendingRewrite(snapshot);
554
+ await assertRewriteSetSpace(work.parent, work.artifacts);
555
+ validateAgent();
556
+ assertChildrenReleased(ctx, work);
557
+ signal?.throwIfAborted();
558
+ onReopening?.();
559
+ await dispose();
560
+ released = true;
561
+ if (ctx.sessions.get(sessionId) || ctx.agents.get(sessionId)) {
562
+ throw new RevisionError('会话仍在释放中,请稍后重试。');
563
+ }
564
+ await commitBoundedRevision(ctx.sessionPersistence, work, {
302
565
  beforeCommit: revisionCacheInvalidator(ctx),
566
+ messageId,
303
567
  onCleanupError(error) {
304
568
  ctx.logger.warn('Saved message revision cleanup failed for %s: %s', sessionId, error);
305
569
  },
306
570
  canRollback() {
307
- return ctx.agents.get(sessionId) === undefined && ctx.sessions.get(sessionId) === undefined;
571
+ return work.entries.every(({ header }) => !ctx.agents.get(header.id) && !ctx.sessions.get(header.id));
308
572
  },
309
573
  async closeFailedReload() {
310
574
  if (!updated) return;
@@ -321,7 +585,8 @@ export async function reviseSession(ctx, input, { onReopening } = {}) {
321
585
  if (!reopened.agent) throw reopened.error ?? new Error('无法重新打开会话。');
322
586
  updated = reopened.agent;
323
587
  reopenedSeq = updated.session.seq;
324
- if (updated.inbox.nextTurn.some(message => message.id === messageId) || deliveredRevision(updated, messageId)) return;
588
+ if (typeof updated.wakeDriver === 'function' && (updated.inbox.nextTurn.some(message => message.id === messageId)
589
+ || deliveredRevision(updated, messageId))) return;
325
590
  // A startup hook may discard the candidate input and still return normally.
326
591
  // Close that provisional Agent only if no other request owns it.
327
592
  if (updated.status === 'idle' && !updated.inbox.hasPending) {
@@ -334,22 +599,36 @@ export async function reviseSession(ctx, input, { onReopening } = {}) {
334
599
  }
335
600
  throw new Error('重开会话时更新后的消息被移除。');
336
601
  },
337
- async afterCommit({ messageId }) {
338
- const pending = updated.inbox.nextTurn;
339
- if (updated.status === 'idle' && pending.length === 1 && pending[0].id === messageId) {
340
- if (!updated.inbox.remove(pending[0].id)) throw new Error('消息已保存,但未能触发发送。');
341
- updated.followup(pending[0]);
342
- await ctx.sessions.flush(updated.session);
343
- } else if (!deliveredRevision(updated, messageId)) {
602
+ async afterCommit({ removedChildren }, journal) {
603
+ childChanges = {
604
+ ...(rewrittenChildren.length > 0 && { rewrittenChildren }),
605
+ ...(removedChildren.length > 0 && { withdrawnChildren: removedChildren }),
606
+ ...(work.affectedParentIds?.length > 0 && { affectedParentIds: work.affectedParentIds }),
607
+ };
608
+ onCommitted?.(childChanges);
609
+ try {
610
+ const delivery = await deliverCommittedPrompt(ctx, updated, journal);
611
+ if (delivery === 'settled') return true;
612
+ recoverDelivery?.(sessionId);
613
+ if (delivery === 'started') return false;
344
614
  throw new Error('消息已保存,但尚未触发发送。');
615
+ } catch (error) {
616
+ recoverDelivery?.(sessionId);
617
+ throw error;
345
618
  }
346
619
  },
347
620
  });
348
621
  } catch (error) {
349
- if (error instanceof RevisionError) await ctx.sessionController.resolveAgent(sessionId);
350
- throw error;
622
+ const rejected = error instanceof RewriteJournalSpaceError
623
+ ? new RevisionError(error.message, { cause: error }) : error;
624
+ if (released && (rejected instanceof RevisionError || rejected.name === 'SessionAlreadyOwnedError')) {
625
+ await ctx.sessionController.resolveAgent(sessionId);
626
+ }
627
+ throw rejected;
628
+ } finally {
629
+ await work.dispose().catch(error => ctx.logger?.warn('Cannot clean up message revision staging: %s', error));
351
630
  }
352
- return { ok: true, reload: true, ...(rewritten.cleanupWarning && { cleanupWarning: true }) };
631
+ return { ok: true, reload: true, ...childChanges };
353
632
  }
354
633
 
355
634
  function validId(value) {
@@ -386,13 +665,23 @@ function parseSubmission(body) {
386
665
  }
387
666
 
388
667
  export async function apply(ctx) {
668
+ const notifications = createRevisionNotifications();
669
+ const deliveryRecovery = installDeliveryRecovery(ctx);
670
+ const recoverDelivery = deliveryRecovery.track;
671
+ const recoveryLifetime = new AbortController();
672
+ ctx.effect(() => () => recoveryLifetime.abort());
389
673
  if (typeof ctx.sessionPersistence.list === 'function') {
390
674
  await recoverStoredSessions(ctx.sessionPersistence, {
675
+ retrySignal: recoveryLifetime.signal,
391
676
  beforeCommit: revisionCacheInvalidator(ctx),
392
677
  canRollback: id => !ctx.agents.get(id) && !ctx.sessions.get(id),
678
+ restoreBoundedJournal,
679
+ recoverDelivery: journal => { recoverDelivery(journal.intent.parentId); },
393
680
  onError: (id, error) => ctx.logger.warn('Pending message revision recovery for %s: %s', id, error),
394
681
  }).catch(error => ctx.logger.warn('Cannot scan pending message revisions: %s', error));
395
682
  }
683
+ ctx.effect(() => () => notifications.close());
684
+ ctx.inject?.(['typert'], scope => registerRevisionNotifications(scope, notifications));
396
685
  const requests = new Set();
397
686
  ctx.effect(() => ctx.connection.fetch.register({
398
687
  path: '/api/message-revision',
@@ -410,7 +699,7 @@ export async function apply(ctx) {
410
699
  }
411
700
  if (body.text === undefined) {
412
701
  try {
413
- return send(await inspectRevision(ctx, body));
702
+ return send(await inspectRevision(ctx, body, recoverDelivery));
414
703
  } catch (error) {
415
704
  if (error instanceof RevisionError) return send({ ok: false, error: error.message }, 409);
416
705
  ctx.logger.warn('Message revision inspection failed: %s', error);
@@ -424,20 +713,30 @@ export async function apply(ctx) {
424
713
  if (requests.has(body.sessionId)) return send({ ok: false, error: '当前会话正在处理编辑请求。' }, 409);
425
714
  requests.add(body.sessionId);
426
715
  let reopening = false;
427
- const failure = (error, status) => send({ ok: false, error, ...(reopening && { reconnect: true }) }, status);
716
+ let childChanges;
717
+ const failure = (error, status) => send({ ok: false, error, ...(reopening && { reconnect: true }), ...childChanges }, status);
428
718
  try {
429
719
  request.signal.throwIfAborted();
430
- return send(await reviseSession(ctx, submission, { onReopening: () => { reopening = true; } }));
720
+ return send(await reviseSession(ctx, submission, {
721
+ signal: request.signal,
722
+ recoverDelivery,
723
+ onReopening: () => { reopening = true; },
724
+ onCommitted(changes) {
725
+ childChanges = changes;
726
+ notifications.publish(changes);
727
+ },
728
+ }));
431
729
  } catch (error) {
432
- if (error instanceof RevisionError) return failure(error.message, 409);
730
+ if (error instanceof RevisionError || error?.name === 'RewriteRollbackConflictError') return failure(error.message, 409);
433
731
  if (error?.name === 'SessionAlreadyOwnedError') {
434
732
  return failure('会话正被其他操作占用,请稍后重试。', 409);
435
733
  }
436
734
  ctx.logger.warn('Message revision failed: %s', error);
437
- return failure('编辑失败,请重试。', 500);
735
+ return failure(reopening ? '编辑未完成,请先检查当前会话。' : '编辑失败,请重试。', 500);
438
736
  } finally {
439
737
  requests.delete(body.sessionId);
440
738
  }
441
739
  },
442
740
  }));
741
+ deliveryRecovery.start();
443
742
  }