@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.
package/src/index.js ADDED
@@ -0,0 +1,742 @@
1
+ import {
2
+ assertNoPendingRewrite, isRevisionAttachment, planRevision, recoverPendingRewrite, recoverStoredSessions,
3
+ resolveRevisionText, retainedRevisionAttachments, RevisionError, revisionTextParts, rewriteMessage,
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';
12
+
13
+ export const name = 'message-revision';
14
+ export const inject = ['agents', 'connection', 'sessionController', 'sessionPersistence', 'sessions'];
15
+
16
+ const effectSymbol = Symbol.for('cordis.effect');
17
+ const originalSymbol = Symbol.for('cordis.original');
18
+ const headers = { 'Cache-Control': 'no-store' };
19
+ const BUSY = '回复生成中,请先停止或等待完成。';
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
+ }
28
+
29
+ function assertIdle(agent) {
30
+ assertIdlePhase(agent);
31
+ if (agent.inbox.hasPending) throw new RevisionError('会话仍有排队消息,请等队列清空后再试。');
32
+ }
33
+
34
+ function effectDisposers(fiber, label) {
35
+ const registered = fiber?.getEffects?.();
36
+ if (!Array.isArray(registered) || typeof fiber?._disposables?.[Symbol.iterator] !== 'function') return [];
37
+ const effects = registered.filter(effect => effect?.label === label);
38
+ const disposers = [...fiber._disposables].filter(fn => typeof fn === 'function' && effects.includes(fn[effectSymbol]));
39
+ return disposers.length === effects.length ? disposers : [];
40
+ }
41
+
42
+ function lifecycleDisposer(ctx, agent) {
43
+ // The controller owns the outer effect, while the Agent loop owns its scope.
44
+ // Cordis traces service.ctx to the caller, so use the actual controller owner.
45
+ const owner = ctx.sessionController[originalSymbol]?.ctx?.fiber;
46
+ const loop = agent.ctx?.fiber?.parent?.fiber;
47
+ const [scope, duplicate] = effectDisposers(loop, `agentLoop.scope(${agent.id})`);
48
+ const lifecycle = effectDisposers(owner, `agentLoop.lifecycle(${agent.id})`);
49
+ const scopeMeta = agent.scope?.rawDispose?.[effectSymbol];
50
+ const childEffects = scope?.[effectSymbol]?.children;
51
+ const failure = () => new RevisionError('无法重新加载当前会话。');
52
+ if (!scope || duplicate || lifecycle.length === 0 || !scopeMeta
53
+ || !Array.isArray(childEffects) || !childEffects.includes(scopeMeta)) throw failure();
54
+
55
+ return async () => {
56
+ const ownerDisposers = new Set(owner._disposables);
57
+ if (ctx.agents.get(agent.id) !== agent || ctx.sessions.get(agent.id) !== agent.session
58
+ || ![...loop._disposables].includes(scope) || lifecycle.some(dispose => !ownerDisposers.has(dispose))) throw failure();
59
+ // The latest controller registration is the live generation. Its native
60
+ // teardown must also release the exact scope of the Agent we're replacing.
61
+ const active = lifecycle.at(-1);
62
+ assertIdlePhase(agent);
63
+ await active();
64
+ if ([...loop._disposables].includes(scope) || [...owner._disposables].includes(active)) throw failure();
65
+ // Older revisions of this plugin could leave completed owner registrations.
66
+ for (const dispose of lifecycle.slice(0, -1).reverse()) await dispose();
67
+ };
68
+ }
69
+
70
+ async function assertNoActivity(ctx, sessionId) {
71
+ const activities = await ctx.waterfall('workspace/session-activity', { sessionId }, async () => []);
72
+ if (activities?.length) throw new RevisionError(BUSY);
73
+ }
74
+
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
+ }
80
+ }
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));
88
+ }
89
+ }
90
+
91
+ function editableAgent(ctx, sessionId) {
92
+ const agent = ctx.agents.get(sessionId);
93
+ if (!agent || ctx.sessions.get(sessionId) !== agent.session) {
94
+ throw new RevisionError('请先打开该会话。');
95
+ }
96
+ if (agent.session.header.origin === 'subagent') {
97
+ throw new RevisionError('子智能体会话不支持直接编辑,请在主会话中操作。');
98
+ }
99
+ assertIdle(agent);
100
+ return agent;
101
+ }
102
+
103
+ const permissionEvents = ['permission/preset', 'sandbox/mode', 'approval/policy'];
104
+
105
+ function lastPermissionEvents(events) {
106
+ const latest = new Map();
107
+ for (const event of events) if (permissionEvents.includes(event.type)) latest.set(event.type, event);
108
+ return latest;
109
+ }
110
+
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;
118
+ for (const event of events) {
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') {
129
+ const { config, adapterDefaults } = event.data.header;
130
+ const effort = adapterDefaults?.reasoningEffort === true ? undefined : config.reasoningEffort;
131
+ lastUsedModel = { provider: config.provider, model: config.model,
132
+ ...(effort === undefined ? {} : { reasoningEffort: effort }) };
133
+ if (sameModel(pendingModel, lastUsedModel)) pendingModel = undefined;
134
+ }
135
+ }
136
+ const currentModel = pendingModel ?? lastUsedModel;
137
+ if (!capturedPrefix) retainedModel = currentModel;
138
+ return { currentPermissions, retainedPermissions, currentModel, retainedModel };
139
+ }
140
+
141
+ function sameModel(first, second) {
142
+ return first?.provider === second?.provider && first?.model === second?.model
143
+ && first?.reasoningEffort === second?.reasoningEffort;
144
+ }
145
+
146
+ function preparePermissions(ctx, agent, current, retained, preset) {
147
+ if (preset !== undefined) {
148
+ const service = ctx.get('permissionPresets');
149
+ if (!service || preset === 'custom') throw new RevisionError('不支持该权限预设。');
150
+ // A detached native Session gives the real permission service its projection
151
+ // and Auto admission gate, without changing the live Session or its revision.
152
+ const seed = [...current.values()].map((event, seq) => ({ ...event, seq }));
153
+ let detached;
154
+ try {
155
+ detached = agent.session.constructor.create(agent.id, seed);
156
+ service.set(detached, preset);
157
+ // Require the effect to be recognizable by the stock permission resolver.
158
+ if (service.current(detached) !== preset) throw new Error('preset was not applied');
159
+ } catch (error) {
160
+ throw new RevisionError('所选权限预设不可用,请重新选择。', { cause: error });
161
+ }
162
+ for (const [type, event] of lastPermissionEvents(detached.snapshotEvents())) current.set(type, event);
163
+ }
164
+ return permissionEvents.flatMap(type => {
165
+ const next = current.get(type);
166
+ if (!next || JSON.stringify(next.data) === JSON.stringify(retained.get(type)?.data)) return [];
167
+ return [{ type, data: next.data }];
168
+ });
169
+ }
170
+
171
+ async function prepareRevisionInputs(ctx, agent, input, original, settings) {
172
+ const retained = retainedRevisionAttachments(original, input.removedAttachments);
173
+ const receiptIds = input.receiptIds ?? [];
174
+ const uploads = receiptIds.length === 0 ? undefined : ctx.get('fileUploads');
175
+ const staged = receiptIds.map(id => {
176
+ const part = uploads?.resolve(agent, id);
177
+ if (!isRevisionAttachment(part)) throw new RevisionError('附件上传已失效,请重新添加。');
178
+ return part;
179
+ });
180
+ if (input.text.trim() === '' && retained.length + staged.length === 0) {
181
+ throw new RevisionError('请输入消息内容或至少保留一个附件。');
182
+ }
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;
192
+ const llm = input.model || hasImages ? ctx.get('llm') : undefined;
193
+ if (input.model) {
194
+ try {
195
+ if (!llm?.listProviders().some(provider => provider.id === model.provider)
196
+ || !(await llm.listModels(model.provider)).some(candidate => candidate.id === model.model)) {
197
+ throw new Error('model missing from catalog');
198
+ }
199
+ await llm.resolveCallConfig(model);
200
+ } catch (error) {
201
+ throw new RevisionError('所选模型或思考强度不可用,请重新选择。', { cause: error });
202
+ }
203
+ }
204
+ if (hasImages) {
205
+ try {
206
+ const info = await llm?.resolveModelInfo(model?.provider, model?.model);
207
+ if (info?.inputModalities && !info.inputModalities.includes('image')) {
208
+ throw new Error('model does not accept images');
209
+ }
210
+ } catch (error) {
211
+ throw new RevisionError('所选模型不支持图片输入,请切换模型或移除图片。', { cause: error });
212
+ }
213
+ }
214
+ let addedAttachments = [];
215
+ if (staged.length > 0) {
216
+ const attachments = ctx.get('attachments');
217
+ if (!attachments) throw new RevisionError('当前环境不支持上传附件。');
218
+ try {
219
+ addedAttachments = await attachments.admitPromptContent(staged);
220
+ } catch (error) {
221
+ throw new RevisionError('附件校验未通过,请重新添加。', { cause: error });
222
+ }
223
+ }
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)) {
231
+ controls.push({ type: 'model/selection', data: model });
232
+ }
233
+ return controls;
234
+ }
235
+
236
+ function revisionSettings(ctx, agent) {
237
+ return {
238
+ model: agent.model.current(),
239
+ permissionPreset: ctx.get('permissionPresets')?.current(agent.session),
240
+ };
241
+ }
242
+
243
+ async function sameEffectiveModel(ctx, selected, original) {
244
+ if (selected === undefined || sameModel(selected, original)) return true;
245
+ if (selected.provider !== original?.provider || selected.model !== original?.model) return false;
246
+ const llm = ctx.get('llm');
247
+ if (!llm) return false;
248
+ try {
249
+ const [before, after] = await Promise.all([llm.resolveCallConfig(original), llm.resolveCallConfig(selected)]);
250
+ return sameModel(before, after);
251
+ } catch {
252
+ // Validation at submission will explain unsupported settings.
253
+ return false;
254
+ }
255
+ }
256
+
257
+ async function isUnchangedRevision(ctx, input, original, settings) {
258
+ const before = revisionTextParts(original);
259
+ const after = resolveRevisionText(original, input);
260
+ return before.length === after.length && before.every((part, index) => part === after[index])
261
+ && !input.removedAttachments?.length && !input.receiptIds?.length
262
+ && (input.permissionPreset === undefined || input.permissionPreset === settings.permissionPreset)
263
+ && await sameEffectiveModel(ctx, input.model, settings.model);
264
+ }
265
+
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);
287
+ const agent = editableAgent(ctx, sessionId);
288
+ await ctx.sessions.flush(agent.session);
289
+ const snapshot = await ctx.sessionPersistence.stat(sessionId);
290
+ if (editableAgent(ctx, sessionId) !== agent || typeof snapshot?.revision !== 'string') {
291
+ throw new RevisionError('会话状态已变更,请刷新后重试。');
292
+ }
293
+ await assertNoPendingRewrite(snapshot);
294
+ const { message } = planRevision(nativeEvents(agent.session), messageId, agent.session.inheritedEventCount);
295
+ const textParts = revisionTextParts(message);
296
+ return { ok: true, toolbarRevision, revision: snapshot.revision,
297
+ text: textParts.join(''), textParts, settings: revisionSettings(ctx, agent),
298
+ attachments: message.content.flatMap((block, index) => isRevisionAttachment(block) ? [{ index, block }] : []),
299
+ };
300
+ }
301
+
302
+ function deliveredRevision(agent, 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(); } };
474
+ }
475
+
476
+ function revisionCacheInvalidator(ctx) {
477
+ return async ids => {
478
+ // Same ID and header means the native cache cannot detect a history rewrite.
479
+ const cache = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
480
+ if (cache) for (const id of ids) await cache.delete(id);
481
+ };
482
+ }
483
+
484
+ /** The Web route and isolated tests share this host operation. */
485
+ export async function reviseSession(ctx, input, options = {}) {
486
+ const { sessionId, messageId } = input;
487
+ await recoverEditableSession(ctx, sessionId, options.recoverDelivery);
488
+ const agent = editableAgent(ctx, sessionId);
489
+ await assertNoActivity(ctx, sessionId);
490
+ await ctx.sessions.flush(agent.session);
491
+ await assertNoActivity(ctx, sessionId);
492
+ const snapshot = await ctx.sessionPersistence.stat(sessionId);
493
+ await assertNoPendingRewrite(snapshot);
494
+ if (input.expectedRevision !== undefined && snapshot?.revision !== input.expectedRevision) {
495
+ throw new RevisionError('会话状态已变更,请重新打开编辑框。');
496
+ }
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;
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 版本不支持安全重发编辑后的消息。');
526
+ const dispose = lifecycleDisposer(ctx, agent);
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 };
543
+
544
+ const rewrittenChildren = work.artifacts.slice(1).map(artifact => artifact.header.id);
545
+ let childChanges;
546
+ let updated;
547
+ let reopenedSeq;
548
+ let released = false;
549
+ try {
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, {
565
+ beforeCommit: revisionCacheInvalidator(ctx),
566
+ messageId,
567
+ onCleanupError(error) {
568
+ ctx.logger.warn('Saved message revision cleanup failed for %s: %s', sessionId, error);
569
+ },
570
+ canRollback() {
571
+ return work.entries.every(({ header }) => !ctx.agents.get(header.id) && !ctx.sessions.get(header.id));
572
+ },
573
+ async closeFailedReload() {
574
+ if (!updated) return;
575
+ await assertNoActivity(ctx, sessionId);
576
+ if (ctx.agents.get(sessionId) === updated && ctx.sessions.get(sessionId) === updated.session
577
+ && updated.status === 'idle' && updated.session.seq === reopenedSeq
578
+ && updated.inbox.nextTurn.length === 1 && updated.inbox.nextTurn[0].id === messageId
579
+ && updated.inbox.nextStep.length === 0) {
580
+ await lifecycleDisposer(ctx, updated)();
581
+ }
582
+ },
583
+ async verifyReload() {
584
+ const reopened = await ctx.sessionController.resolveAgent(sessionId);
585
+ if (!reopened.agent) throw reopened.error ?? new Error('无法重新打开会话。');
586
+ updated = reopened.agent;
587
+ reopenedSeq = updated.session.seq;
588
+ if (typeof updated.wakeDriver === 'function' && (updated.inbox.nextTurn.some(message => message.id === messageId)
589
+ || deliveredRevision(updated, messageId))) return;
590
+ // A startup hook may discard the candidate input and still return normally.
591
+ // Close that provisional Agent only if no other request owns it.
592
+ if (updated.status === 'idle' && !updated.inbox.hasPending) {
593
+ const seq = updated.session.seq;
594
+ await assertNoActivity(ctx, sessionId);
595
+ if (ctx.agents.get(sessionId) === updated && updated.session.seq === seq
596
+ && updated.status === 'idle' && !updated.inbox.hasPending) {
597
+ await lifecycleDisposer(ctx, updated)();
598
+ }
599
+ }
600
+ throw new Error('重开会话时更新后的消息被移除。');
601
+ },
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;
614
+ throw new Error('消息已保存,但尚未触发发送。');
615
+ } catch (error) {
616
+ recoverDelivery?.(sessionId);
617
+ throw error;
618
+ }
619
+ },
620
+ });
621
+ } catch (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));
630
+ }
631
+ return { ok: true, reload: true, ...childChanges };
632
+ }
633
+
634
+ function validId(value) {
635
+ return typeof value === 'string' && value.length > 0 && value.length <= 2048 && !/[\u0000-\u001f]/u.test(value);
636
+ }
637
+
638
+ function validDistinctList(value, item) {
639
+ return Array.isArray(value) && value.length <= 128 && value.every(item) && new Set(value).size === value.length;
640
+ }
641
+
642
+ function parseSubmission(body) {
643
+ const { sessionId, messageId, text, textParts, expectedRevision, removedAttachments = [], receiptIds = [], permissionPreset } = body;
644
+ const model = body.model;
645
+ const usesToolbar = permissionPreset !== undefined || model !== undefined
646
+ || removedAttachments?.length > 0 || receiptIds?.length > 0;
647
+ if ((usesToolbar || body.toolbarRevision !== undefined) && body.toolbarRevision !== toolbarRevision) return undefined;
648
+ if (typeof text !== 'string' || text.length > 200_000
649
+ || (textParts !== undefined && (!Array.isArray(textParts) || textParts.length > 2_000
650
+ || !textParts.every(part => typeof part === 'string' && part.length <= text.length)
651
+ || textParts.reduce((size, part) => size + part.length, 0) !== text.length))
652
+ || typeof expectedRevision !== 'string' || expectedRevision.length > 1024
653
+ || !validDistinctList(removedAttachments, index => Number.isSafeInteger(index) && index >= 0)
654
+ || !validDistinctList(receiptIds, id => validId(id) && id.length <= 128)
655
+ || (permissionPreset !== undefined && (!validId(permissionPreset) || permissionPreset.length > 256))
656
+ || (model !== undefined && (model === null || typeof model !== 'object' || Array.isArray(model)
657
+ || !validId(model.provider) || !validId(model.model)
658
+ || (model.reasoningEffort !== undefined && (!validId(model.reasoningEffort) || model.reasoningEffort.length > 256))))) {
659
+ return undefined;
660
+ }
661
+ return { sessionId, messageId, text, textParts, expectedRevision, removedAttachments, receiptIds, permissionPreset,
662
+ ...(model && { model: { provider: model.provider, model: model.model,
663
+ ...(model.reasoningEffort !== undefined && { reasoningEffort: model.reasoningEffort }) } }),
664
+ };
665
+ }
666
+
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());
673
+ if (typeof ctx.sessionPersistence.list === 'function') {
674
+ await recoverStoredSessions(ctx.sessionPersistence, {
675
+ retrySignal: recoveryLifetime.signal,
676
+ beforeCommit: revisionCacheInvalidator(ctx),
677
+ canRollback: id => !ctx.agents.get(id) && !ctx.sessions.get(id),
678
+ restoreBoundedJournal,
679
+ recoverDelivery: journal => { recoverDelivery(journal.intent.parentId); },
680
+ onError: (id, error) => ctx.logger.warn('Pending message revision recovery for %s: %s', id, error),
681
+ }).catch(error => ctx.logger.warn('Cannot scan pending message revisions: %s', error));
682
+ }
683
+ ctx.effect(() => () => notifications.close());
684
+ ctx.inject?.(['typert'], scope => registerRevisionNotifications(scope, notifications));
685
+ const requests = new Set();
686
+ ctx.effect(() => ctx.connection.fetch.register({
687
+ path: '/api/message-revision',
688
+ methods: ['POST'],
689
+ requestBody: 'buffered',
690
+ async fetch(request) {
691
+ const send = (value, status = 200) => Response.json(value, { status, headers });
692
+ // Exact custom Connection routes use the host's owner admission policy.
693
+ if (request.headers.get('content-type')?.split(';', 1)[0].trim() !== 'application/json') {
694
+ return send({ ok: false, error: '请求格式无效。' }, 400);
695
+ }
696
+ const body = await request.json().catch(() => undefined);
697
+ if (!validId(body?.sessionId) || !validId(body?.messageId)) {
698
+ return send({ ok: false, toolbarRevision, error: '未找到该消息。' }, 400);
699
+ }
700
+ if (body.text === undefined) {
701
+ try {
702
+ return send(await inspectRevision(ctx, body, recoverDelivery));
703
+ } catch (error) {
704
+ if (error instanceof RevisionError) return send({ ok: false, error: error.message }, 409);
705
+ ctx.logger.warn('Message revision inspection failed: %s', error);
706
+ return send({ ok: false, error: '无法读取该消息,请刷新后重试。' }, 500);
707
+ }
708
+ }
709
+ const submission = parseSubmission(body);
710
+ if (!submission) {
711
+ return send({ ok: false, error: '编辑内容或参数无效,请重新打开编辑框。' }, 400);
712
+ }
713
+ if (requests.has(body.sessionId)) return send({ ok: false, error: '当前会话正在处理编辑请求。' }, 409);
714
+ requests.add(body.sessionId);
715
+ let reopening = false;
716
+ let childChanges;
717
+ const failure = (error, status) => send({ ok: false, error, ...(reopening && { reconnect: true }), ...childChanges }, status);
718
+ try {
719
+ request.signal.throwIfAborted();
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
+ }));
729
+ } catch (error) {
730
+ if (error instanceof RevisionError || error?.name === 'RewriteRollbackConflictError') return failure(error.message, 409);
731
+ if (error?.name === 'SessionAlreadyOwnedError') {
732
+ return failure('会话正被其他操作占用,请稍后重试。', 409);
733
+ }
734
+ ctx.logger.warn('Message revision failed: %s', error);
735
+ return failure(reopening ? '编辑未完成,请先检查当前会话。' : '编辑失败,请重试。', 500);
736
+ } finally {
737
+ requests.delete(body.sessionId);
738
+ }
739
+ },
740
+ }));
741
+ deliveryRecovery.start();
742
+ }