@kabxx/dsh-message-revision 0.0.0-stage → 0.1.0
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/README.md +39 -2
- package/cordis.patch.yml +3 -0
- package/icon.svg +23 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +43 -4
- package/src/client.js +1067 -0
- package/src/index.js +443 -0
- package/src/revision.js +484 -0
- package/src/rewrite-journal.js +319 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
import {
|
|
2
|
+
assertNoPendingRewrite, isRevisionAttachment, planRevision, recoverStoredSessions, resolveRevisionText,
|
|
3
|
+
retainedRevisionAttachments, RevisionError, revisionTextParts, rewriteStoredSession, splitChildCatalog,
|
|
4
|
+
} from './revision.js';
|
|
5
|
+
|
|
6
|
+
export const name = 'message-revision';
|
|
7
|
+
export const inject = ['agents', 'connection', 'sessionController', 'sessionPersistence', 'sessions'];
|
|
8
|
+
|
|
9
|
+
const effectSymbol = Symbol.for('cordis.effect');
|
|
10
|
+
const originalSymbol = Symbol.for('cordis.original');
|
|
11
|
+
const headers = { 'Cache-Control': 'no-store' };
|
|
12
|
+
const BUSY = '回复生成中,请先停止或等待完成。';
|
|
13
|
+
const toolbarRevision = 1;
|
|
14
|
+
|
|
15
|
+
function assertIdle(agent) {
|
|
16
|
+
if (agent.status !== 'idle') throw new RevisionError(BUSY);
|
|
17
|
+
if (agent.inbox.hasPending) throw new RevisionError('会话仍有排队消息,请等队列清空后再试。');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function effectDisposers(fiber, label) {
|
|
21
|
+
const registered = fiber?.getEffects?.();
|
|
22
|
+
if (!Array.isArray(registered) || typeof fiber?._disposables?.[Symbol.iterator] !== 'function') return [];
|
|
23
|
+
const effects = registered.filter(effect => effect?.label === label);
|
|
24
|
+
const disposers = [...fiber._disposables].filter(fn => typeof fn === 'function' && effects.includes(fn[effectSymbol]));
|
|
25
|
+
return disposers.length === effects.length ? disposers : [];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function lifecycleDisposer(ctx, agent) {
|
|
29
|
+
// The controller owns the outer effect, while the Agent loop owns its scope.
|
|
30
|
+
// Cordis traces service.ctx to the caller, so use the actual controller owner.
|
|
31
|
+
const owner = ctx.sessionController[originalSymbol]?.ctx?.fiber;
|
|
32
|
+
const loop = agent.ctx?.fiber?.parent?.fiber;
|
|
33
|
+
const [scope, duplicate] = effectDisposers(loop, `agentLoop.scope(${agent.id})`);
|
|
34
|
+
const lifecycle = effectDisposers(owner, `agentLoop.lifecycle(${agent.id})`);
|
|
35
|
+
const scopeMeta = agent.scope?.rawDispose?.[effectSymbol];
|
|
36
|
+
const childEffects = scope?.[effectSymbol]?.children;
|
|
37
|
+
const failure = () => new RevisionError('无法重新加载当前会话。');
|
|
38
|
+
if (!scope || duplicate || lifecycle.length === 0 || !scopeMeta
|
|
39
|
+
|| !Array.isArray(childEffects) || !childEffects.includes(scopeMeta)) throw failure();
|
|
40
|
+
|
|
41
|
+
return async () => {
|
|
42
|
+
const ownerDisposers = new Set(owner._disposables);
|
|
43
|
+
if (ctx.agents.get(agent.id) !== agent || ctx.sessions.get(agent.id) !== agent.session
|
|
44
|
+
|| ![...loop._disposables].includes(scope) || lifecycle.some(dispose => !ownerDisposers.has(dispose))) throw failure();
|
|
45
|
+
// The latest controller registration is the live generation. Its native
|
|
46
|
+
// teardown must also release the exact scope of the Agent we're replacing.
|
|
47
|
+
const active = lifecycle.at(-1);
|
|
48
|
+
await active();
|
|
49
|
+
if ([...loop._disposables].includes(scope) || [...owner._disposables].includes(active)) throw failure();
|
|
50
|
+
// Older revisions of this plugin could leave completed owner registrations.
|
|
51
|
+
for (const dispose of lifecycle.slice(0, -1).reverse()) await dispose();
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function assertNoActivity(ctx, sessionId) {
|
|
56
|
+
const activities = await ctx.waterfall('workspace/session-activity', { sessionId }, async () => []);
|
|
57
|
+
if (activities?.length) throw new RevisionError(BUSY);
|
|
58
|
+
}
|
|
59
|
+
|
|
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('子智能体仍在运行,请等执行结束后再试。');
|
|
67
|
+
}
|
|
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('关联的子智能体会话仍处于打开状态,请关闭后重试。');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function editableAgent(ctx, sessionId) {
|
|
75
|
+
const agent = ctx.agents.get(sessionId);
|
|
76
|
+
if (!agent || ctx.sessions.get(sessionId) !== agent.session) {
|
|
77
|
+
throw new RevisionError('请先打开该会话。');
|
|
78
|
+
}
|
|
79
|
+
if (agent.session.header.origin === 'subagent' || agent.session.header.parentSession) {
|
|
80
|
+
throw new RevisionError('子智能体会话不支持直接编辑,请在主会话中操作。');
|
|
81
|
+
}
|
|
82
|
+
assertIdle(agent);
|
|
83
|
+
return agent;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const permissionEvents = ['permission/preset', 'sandbox/mode', 'approval/policy'];
|
|
87
|
+
|
|
88
|
+
function lastPermissionEvents(events) {
|
|
89
|
+
const latest = new Map();
|
|
90
|
+
for (const event of events) if (permissionEvents.includes(event.type)) latest.set(event.type, event);
|
|
91
|
+
return latest;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function modelAt(events) {
|
|
95
|
+
let pending;
|
|
96
|
+
let lastUsed;
|
|
97
|
+
for (const event of events) {
|
|
98
|
+
if (event.type === 'model/selection') pending = event.data;
|
|
99
|
+
if (event.type === 'request/header') {
|
|
100
|
+
const { config, adapterDefaults } = event.data.header;
|
|
101
|
+
const effort = adapterDefaults?.reasoningEffort === true ? undefined : config.reasoningEffort;
|
|
102
|
+
lastUsed = { provider: config.provider, model: config.model,
|
|
103
|
+
...(effort === undefined ? {} : { reasoningEffort: effort }) };
|
|
104
|
+
if (sameModel(pending, lastUsed)) pending = undefined;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return pending ?? lastUsed;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function sameModel(first, second) {
|
|
111
|
+
return first?.provider === second?.provider && first?.model === second?.model
|
|
112
|
+
&& first?.reasoningEffort === second?.reasoningEffort;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function preparePermissions(ctx, agent, events, prefix, preset) {
|
|
116
|
+
const current = lastPermissionEvents(events);
|
|
117
|
+
const retained = lastPermissionEvents(prefix);
|
|
118
|
+
if (preset !== undefined) {
|
|
119
|
+
const service = ctx.get('permissionPresets');
|
|
120
|
+
if (!service || preset === 'custom') throw new RevisionError('不支持该权限预设。');
|
|
121
|
+
// A detached native Session gives the real permission service its projection
|
|
122
|
+
// and Auto admission gate, without changing the live Session or its revision.
|
|
123
|
+
const seed = [...current.values()].map((event, seq) => ({ ...event, seq }));
|
|
124
|
+
let detached;
|
|
125
|
+
try {
|
|
126
|
+
detached = agent.session.constructor.create(agent.id, seed);
|
|
127
|
+
service.set(detached, preset);
|
|
128
|
+
// Require the effect to be recognizable by the stock permission resolver.
|
|
129
|
+
if (service.current(detached) !== preset) throw new Error('preset was not applied');
|
|
130
|
+
} catch (error) {
|
|
131
|
+
throw new RevisionError('所选权限预设不可用,请重新选择。', { cause: error });
|
|
132
|
+
}
|
|
133
|
+
for (const [type, event] of lastPermissionEvents(detached.snapshotEvents())) current.set(type, event);
|
|
134
|
+
}
|
|
135
|
+
return permissionEvents.flatMap(type => {
|
|
136
|
+
const next = current.get(type);
|
|
137
|
+
if (!next || JSON.stringify(next.data) === JSON.stringify(retained.get(type)?.data)) return [];
|
|
138
|
+
return [{ type, data: next.data }];
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function prepareAmendments(ctx, agent, input, events, plan) {
|
|
143
|
+
const retained = retainedRevisionAttachments(plan.message, input.removedAttachments);
|
|
144
|
+
const receiptIds = input.receiptIds ?? [];
|
|
145
|
+
const uploads = receiptIds.length === 0 ? undefined : ctx.get('fileUploads');
|
|
146
|
+
const staged = receiptIds.map(id => {
|
|
147
|
+
const part = uploads?.resolve(agent, id);
|
|
148
|
+
if (!isRevisionAttachment(part)) throw new RevisionError('附件上传已失效,请重新添加。');
|
|
149
|
+
return part;
|
|
150
|
+
});
|
|
151
|
+
if (input.text.trim() === '' && retained.length + staged.length === 0) {
|
|
152
|
+
throw new RevisionError('请输入消息内容或至少保留一个附件。');
|
|
153
|
+
}
|
|
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');
|
|
157
|
+
const llm = input.model || hasImages ? ctx.get('llm') : undefined;
|
|
158
|
+
if (input.model) {
|
|
159
|
+
try {
|
|
160
|
+
if (!llm?.listProviders().some(provider => provider.id === model.provider)
|
|
161
|
+
|| !(await llm.listModels(model.provider)).some(candidate => candidate.id === model.model)) {
|
|
162
|
+
throw new Error('model missing from catalog');
|
|
163
|
+
}
|
|
164
|
+
await llm.resolveCallConfig(model);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
throw new RevisionError('所选模型或思考强度不可用,请重新选择。', { cause: error });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (hasImages) {
|
|
170
|
+
try {
|
|
171
|
+
const info = await llm?.resolveModelInfo(model?.provider, model?.model);
|
|
172
|
+
if (info?.inputModalities && !info.inputModalities.includes('image')) {
|
|
173
|
+
throw new Error('model does not accept images');
|
|
174
|
+
}
|
|
175
|
+
} catch (error) {
|
|
176
|
+
throw new RevisionError('所选模型不支持图片输入,请切换模型或移除图片。', { cause: error });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
let addedAttachments = [];
|
|
180
|
+
if (staged.length > 0) {
|
|
181
|
+
const attachments = ctx.get('attachments');
|
|
182
|
+
if (!attachments) throw new RevisionError('当前环境不支持上传附件。');
|
|
183
|
+
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);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
throw new RevisionError('附件校验未通过,请重新添加。', { cause: error });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const controls = preparePermissions(ctx, agent, events, prefix, input.permissionPreset);
|
|
193
|
+
if (model && !sameModel(model, modelAt(prefix)) && (input.model || modelAt(events))) {
|
|
194
|
+
controls.push({ type: 'model/selection', data: model });
|
|
195
|
+
}
|
|
196
|
+
return { addedAttachments, controls };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function revisionSettings(ctx, agent) {
|
|
200
|
+
return {
|
|
201
|
+
model: agent.model.current(),
|
|
202
|
+
permissionPreset: ctx.get('permissionPresets')?.current(agent.session),
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function sameEffectiveModel(ctx, selected, original) {
|
|
207
|
+
if (selected === undefined || sameModel(selected, original)) return true;
|
|
208
|
+
if (selected.provider !== original?.provider || selected.model !== original?.model) return false;
|
|
209
|
+
const llm = ctx.get('llm');
|
|
210
|
+
if (!llm) return false;
|
|
211
|
+
try {
|
|
212
|
+
const [before, after] = await Promise.all([llm.resolveCallConfig(original), llm.resolveCallConfig(selected)]);
|
|
213
|
+
return sameModel(before, after);
|
|
214
|
+
} catch {
|
|
215
|
+
// Validation at submission will explain unsupported settings.
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function isUnchangedRevision(ctx, input, original, settings) {
|
|
221
|
+
const before = revisionTextParts(original);
|
|
222
|
+
const after = resolveRevisionText(original, input);
|
|
223
|
+
return before.length === after.length && before.every((part, index) => part === after[index])
|
|
224
|
+
&& !input.removedAttachments?.length && !input.receiptIds?.length
|
|
225
|
+
&& (input.permissionPreset === undefined || input.permissionPreset === settings.permissionPreset)
|
|
226
|
+
&& await sameEffectiveModel(ctx, input.model, settings.model);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function inspectRevision(ctx, { sessionId, messageId }) {
|
|
230
|
+
const agent = editableAgent(ctx, sessionId);
|
|
231
|
+
await ctx.sessions.flush(agent.session);
|
|
232
|
+
const snapshot = await ctx.sessionPersistence.stat(sessionId);
|
|
233
|
+
if (editableAgent(ctx, sessionId) !== agent || typeof snapshot?.revision !== 'string') {
|
|
234
|
+
throw new RevisionError('会话状态已变更,请刷新后重试。');
|
|
235
|
+
}
|
|
236
|
+
await assertNoPendingRewrite(snapshot);
|
|
237
|
+
const events = agent.session.snapshotEvents();
|
|
238
|
+
const plan = planRevision(events, messageId, agent.session.inheritedEventCount);
|
|
239
|
+
const textParts = revisionTextParts(plan.message);
|
|
240
|
+
return { ok: true, toolbarRevision, revision: snapshot.revision,
|
|
241
|
+
text: textParts.join(''), textParts, settings: revisionSettings(ctx, agent),
|
|
242
|
+
attachments: plan.message.content.flatMap((block, index) => isRevisionAttachment(block) ? [{ index, block }] : []),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function deliveredRevision(agent, messageId) {
|
|
247
|
+
return agent.session.snapshotEvents().some(event => event.type === 'user/message' && event.data.id === messageId);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function revisionCacheInvalidator(ctx) {
|
|
251
|
+
return async ids => {
|
|
252
|
+
// Same ID and header means the native cache cannot detect a history rewrite.
|
|
253
|
+
const cache = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
|
|
254
|
+
if (cache) for (const id of ids) await cache.delete(id);
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** The Web route and isolated tests share this host operation. */
|
|
259
|
+
export async function reviseSession(ctx, input, { onReopening } = {}) {
|
|
260
|
+
const { sessionId, messageId } = input;
|
|
261
|
+
const agent = editableAgent(ctx, sessionId);
|
|
262
|
+
await assertNoActivity(ctx, sessionId);
|
|
263
|
+
await ctx.sessions.flush(agent.session);
|
|
264
|
+
await assertNoActivity(ctx, sessionId);
|
|
265
|
+
const snapshot = await ctx.sessionPersistence.stat(sessionId);
|
|
266
|
+
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('会话状态已变更,请刷新后重试。');
|
|
275
|
+
}
|
|
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 };
|
|
280
|
+
}
|
|
281
|
+
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
|
+
}
|
|
295
|
+
|
|
296
|
+
let rewritten;
|
|
297
|
+
let updated;
|
|
298
|
+
let reopenedSeq;
|
|
299
|
+
try {
|
|
300
|
+
rewritten = await rewriteStoredSession(ctx.sessionPersistence, input, {
|
|
301
|
+
...amendments,
|
|
302
|
+
beforeCommit: revisionCacheInvalidator(ctx),
|
|
303
|
+
onCleanupError(error) {
|
|
304
|
+
ctx.logger.warn('Saved message revision cleanup failed for %s: %s', sessionId, error);
|
|
305
|
+
},
|
|
306
|
+
canRollback() {
|
|
307
|
+
return ctx.agents.get(sessionId) === undefined && ctx.sessions.get(sessionId) === undefined;
|
|
308
|
+
},
|
|
309
|
+
async closeFailedReload() {
|
|
310
|
+
if (!updated) return;
|
|
311
|
+
await assertNoActivity(ctx, sessionId);
|
|
312
|
+
if (ctx.agents.get(sessionId) === updated && ctx.sessions.get(sessionId) === updated.session
|
|
313
|
+
&& updated.status === 'idle' && updated.session.seq === reopenedSeq
|
|
314
|
+
&& updated.inbox.nextTurn.length === 1 && updated.inbox.nextTurn[0].id === messageId
|
|
315
|
+
&& updated.inbox.nextStep.length === 0) {
|
|
316
|
+
await lifecycleDisposer(ctx, updated)();
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
async verifyReload() {
|
|
320
|
+
const reopened = await ctx.sessionController.resolveAgent(sessionId);
|
|
321
|
+
if (!reopened.agent) throw reopened.error ?? new Error('无法重新打开会话。');
|
|
322
|
+
updated = reopened.agent;
|
|
323
|
+
reopenedSeq = updated.session.seq;
|
|
324
|
+
if (updated.inbox.nextTurn.some(message => message.id === messageId) || deliveredRevision(updated, messageId)) return;
|
|
325
|
+
// A startup hook may discard the candidate input and still return normally.
|
|
326
|
+
// Close that provisional Agent only if no other request owns it.
|
|
327
|
+
if (updated.status === 'idle' && !updated.inbox.hasPending) {
|
|
328
|
+
const seq = updated.session.seq;
|
|
329
|
+
await assertNoActivity(ctx, sessionId);
|
|
330
|
+
if (ctx.agents.get(sessionId) === updated && updated.session.seq === seq
|
|
331
|
+
&& updated.status === 'idle' && !updated.inbox.hasPending) {
|
|
332
|
+
await lifecycleDisposer(ctx, updated)();
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
throw new Error('重开会话时更新后的消息被移除。');
|
|
336
|
+
},
|
|
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)) {
|
|
344
|
+
throw new Error('消息已保存,但尚未触发发送。');
|
|
345
|
+
}
|
|
346
|
+
},
|
|
347
|
+
});
|
|
348
|
+
} catch (error) {
|
|
349
|
+
if (error instanceof RevisionError) await ctx.sessionController.resolveAgent(sessionId);
|
|
350
|
+
throw error;
|
|
351
|
+
}
|
|
352
|
+
return { ok: true, reload: true, ...(rewritten.cleanupWarning && { cleanupWarning: true }) };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function validId(value) {
|
|
356
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 2048 && !/[\u0000-\u001f]/u.test(value);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function validDistinctList(value, item) {
|
|
360
|
+
return Array.isArray(value) && value.length <= 128 && value.every(item) && new Set(value).size === value.length;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function parseSubmission(body) {
|
|
364
|
+
const { sessionId, messageId, text, textParts, expectedRevision, removedAttachments = [], receiptIds = [], permissionPreset } = body;
|
|
365
|
+
const model = body.model;
|
|
366
|
+
const usesToolbar = permissionPreset !== undefined || model !== undefined
|
|
367
|
+
|| removedAttachments?.length > 0 || receiptIds?.length > 0;
|
|
368
|
+
if ((usesToolbar || body.toolbarRevision !== undefined) && body.toolbarRevision !== toolbarRevision) return undefined;
|
|
369
|
+
if (typeof text !== 'string' || text.length > 200_000
|
|
370
|
+
|| (textParts !== undefined && (!Array.isArray(textParts) || textParts.length > 2_000
|
|
371
|
+
|| !textParts.every(part => typeof part === 'string' && part.length <= text.length)
|
|
372
|
+
|| textParts.reduce((size, part) => size + part.length, 0) !== text.length))
|
|
373
|
+
|| typeof expectedRevision !== 'string' || expectedRevision.length > 1024
|
|
374
|
+
|| !validDistinctList(removedAttachments, index => Number.isSafeInteger(index) && index >= 0)
|
|
375
|
+
|| !validDistinctList(receiptIds, id => validId(id) && id.length <= 128)
|
|
376
|
+
|| (permissionPreset !== undefined && (!validId(permissionPreset) || permissionPreset.length > 256))
|
|
377
|
+
|| (model !== undefined && (model === null || typeof model !== 'object' || Array.isArray(model)
|
|
378
|
+
|| !validId(model.provider) || !validId(model.model)
|
|
379
|
+
|| (model.reasoningEffort !== undefined && (!validId(model.reasoningEffort) || model.reasoningEffort.length > 256))))) {
|
|
380
|
+
return undefined;
|
|
381
|
+
}
|
|
382
|
+
return { sessionId, messageId, text, textParts, expectedRevision, removedAttachments, receiptIds, permissionPreset,
|
|
383
|
+
...(model && { model: { provider: model.provider, model: model.model,
|
|
384
|
+
...(model.reasoningEffort !== undefined && { reasoningEffort: model.reasoningEffort }) } }),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
export async function apply(ctx) {
|
|
389
|
+
if (typeof ctx.sessionPersistence.list === 'function') {
|
|
390
|
+
await recoverStoredSessions(ctx.sessionPersistence, {
|
|
391
|
+
beforeCommit: revisionCacheInvalidator(ctx),
|
|
392
|
+
canRollback: id => !ctx.agents.get(id) && !ctx.sessions.get(id),
|
|
393
|
+
onError: (id, error) => ctx.logger.warn('Pending message revision recovery for %s: %s', id, error),
|
|
394
|
+
}).catch(error => ctx.logger.warn('Cannot scan pending message revisions: %s', error));
|
|
395
|
+
}
|
|
396
|
+
const requests = new Set();
|
|
397
|
+
ctx.effect(() => ctx.connection.fetch.register({
|
|
398
|
+
path: '/api/message-revision',
|
|
399
|
+
methods: ['POST'],
|
|
400
|
+
requestBody: 'buffered',
|
|
401
|
+
async fetch(request) {
|
|
402
|
+
const send = (value, status = 200) => Response.json(value, { status, headers });
|
|
403
|
+
// Exact custom Connection routes use the host's owner admission policy.
|
|
404
|
+
if (request.headers.get('content-type')?.split(';', 1)[0].trim() !== 'application/json') {
|
|
405
|
+
return send({ ok: false, error: '请求格式无效。' }, 400);
|
|
406
|
+
}
|
|
407
|
+
const body = await request.json().catch(() => undefined);
|
|
408
|
+
if (!validId(body?.sessionId) || !validId(body?.messageId)) {
|
|
409
|
+
return send({ ok: false, toolbarRevision, error: '未找到该消息。' }, 400);
|
|
410
|
+
}
|
|
411
|
+
if (body.text === undefined) {
|
|
412
|
+
try {
|
|
413
|
+
return send(await inspectRevision(ctx, body));
|
|
414
|
+
} catch (error) {
|
|
415
|
+
if (error instanceof RevisionError) return send({ ok: false, error: error.message }, 409);
|
|
416
|
+
ctx.logger.warn('Message revision inspection failed: %s', error);
|
|
417
|
+
return send({ ok: false, error: '无法读取该消息,请刷新后重试。' }, 500);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const submission = parseSubmission(body);
|
|
421
|
+
if (!submission) {
|
|
422
|
+
return send({ ok: false, error: '编辑内容或参数无效,请重新打开编辑框。' }, 400);
|
|
423
|
+
}
|
|
424
|
+
if (requests.has(body.sessionId)) return send({ ok: false, error: '当前会话正在处理编辑请求。' }, 409);
|
|
425
|
+
requests.add(body.sessionId);
|
|
426
|
+
let reopening = false;
|
|
427
|
+
const failure = (error, status) => send({ ok: false, error, ...(reopening && { reconnect: true }) }, status);
|
|
428
|
+
try {
|
|
429
|
+
request.signal.throwIfAborted();
|
|
430
|
+
return send(await reviseSession(ctx, submission, { onReopening: () => { reopening = true; } }));
|
|
431
|
+
} catch (error) {
|
|
432
|
+
if (error instanceof RevisionError) return failure(error.message, 409);
|
|
433
|
+
if (error?.name === 'SessionAlreadyOwnedError') {
|
|
434
|
+
return failure('会话正被其他操作占用,请稍后重试。', 409);
|
|
435
|
+
}
|
|
436
|
+
ctx.logger.warn('Message revision failed: %s', error);
|
|
437
|
+
return failure('编辑失败,请重试。', 500);
|
|
438
|
+
} finally {
|
|
439
|
+
requests.delete(body.sessionId);
|
|
440
|
+
}
|
|
441
|
+
},
|
|
442
|
+
}));
|
|
443
|
+
}
|