@240xu/dsh-message-ops 0.8.0 → 0.9.2
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 +162 -7
- package/package.json +2 -2
- package/src/client.js +312 -132
- package/src/index.js +114 -103
- package/src/ops-core.js +213 -65
- package/src/session-file.js +29 -1
- package/test/branch-export-removed.test.js +73 -0
- package/test/fence.test.js +0 -27
- package/test/injected-regex.test.js +62 -0
- package/test/legacy-format.test.js +0 -17
- package/test/ops-core.test.js +42 -45
- package/test/revert-contract.test.js +118 -0
- package/test/session-file.test.js +0 -24
- package/test/step-restore.test.js +16 -0
- package/test/surface-visibility.test.js +166 -0
- package/test/user-revert-anchor.test.js +103 -0
- package/src/branch.js +0 -57
package/src/index.js
CHANGED
|
@@ -5,16 +5,18 @@
|
|
|
5
5
|
* 五操作一条龙(同名插件,一个注入点):
|
|
6
6
|
* POST /api/message-ops/revert 回滚:surface replace 遮蔽 targetSeq..末尾
|
|
7
7
|
* POST /api/message-ops/delete 删除:surface replace 遮蔽单条 seq
|
|
8
|
-
* POST /api/message-ops/branch 分支:磁盘级 fork(新会话,parentSession 关联)
|
|
9
8
|
* GET /api/message-ops/messages 消息列表(磁盘真相 + 可见性标注)
|
|
10
|
-
* GET /api/message-ops/export 导出 Markdown(seq 可选上界,附件下载)
|
|
11
9
|
* POST /api/message-ops/restore 回滚恢复:重放被遮蔽的 user/assistant 消息
|
|
12
10
|
*
|
|
13
11
|
* 回滚/删除走 DSH 原生 surface replace(append-only,日志完整可恢复;
|
|
14
12
|
* 约束由引擎 assertProvenance 校验,违规如实上报 409)。
|
|
15
13
|
* 运行中的会话一律拒绝(409),由用户先停止再操作。
|
|
16
14
|
*
|
|
17
|
-
* Agent 工具:action revert/delete/
|
|
15
|
+
* Agent 工具:action revert/delete/list/restore 共用 HTTP 同一套
|
|
16
|
+
*
|
|
17
|
+
* 分支与导出不属本插件:dsh 官方已有 session/fork(任意 atSeq,且会补 fork closers)
|
|
18
|
+
* 与 /api/session.export(ZIP 归档)。0.9.0 移除了本插件的磁盘分支与 Markdown 导出 ——
|
|
19
|
+
* 前者语义有偏差(缺 isSeeded / inheritedEventCount / closers),后者零 UI 入口。
|
|
18
20
|
* 核心逻辑(src/ops-core.js)。工具注册是容错的——ctx 里没有 tools 服务、
|
|
19
21
|
* 或 @deepseek-ai/dsh-tools 包不可解析时,只跳过工具注册,不影响 HTTP。
|
|
20
22
|
* @module dsh-message-ops
|
|
@@ -22,10 +24,9 @@
|
|
|
22
24
|
|
|
23
25
|
import { zstdCompressSync } from "node:zlib";
|
|
24
26
|
import { open as openFile, truncate as truncateFile, stat as statFile } from "node:fs/promises";
|
|
25
|
-
import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFile, readSessionFileAsync, listMessages, computeShadowed, messageText } from "./session-file.js";
|
|
26
|
-
import {
|
|
27
|
-
|
|
28
|
-
OpsError, planRevert, planDelete, planRestore, applyRestore, applySurfaceReplace, exportMarkdown,
|
|
27
|
+
import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFile, readSessionFileAsync, listMessages, computeShadowed, messageText, turnBounds } from "./session-file.js";
|
|
28
|
+
import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble,
|
|
29
|
+
OpsError, planRevert, planDelete, planRestore, applyRestore, applySurfaceReplace,
|
|
29
30
|
restoreProgress, pendingRestoreTurns,
|
|
30
31
|
isTrustedApiRequest, isJsonContentType,
|
|
31
32
|
} from "./ops-core.js";
|
|
@@ -276,6 +277,15 @@ async function opsList(targetCtx, sessionId) {
|
|
|
276
277
|
const t = messageText(e);
|
|
277
278
|
if (t && t.trim()) seqText.set(e.seq, t.trim().replace(/\s+/g, " ").slice(0, 80));
|
|
278
279
|
}
|
|
280
|
+
// 0.9.1:**reverted** = opencode 语义「回撤边界及其后」。
|
|
281
|
+
//
|
|
282
|
+
// ⚠️ 不能用 `visible` 当隐藏判据 —— `visible` 是「是否在模型 surface 上」,
|
|
283
|
+
// 而 tool/call / turn/* / model/* **根本不是 surface 节点**(SURFACE_TYPES 只有
|
|
284
|
+
// system|user|developer|assistant/message 与 tool/result),它们永远 visible=false。
|
|
285
|
+
// 照抄会把**所有**工���调用行永久藏掉(实测 3/3 全被误藏)。
|
|
286
|
+
//
|
|
287
|
+
// 正确口径:每个活跃回撤标记的 range.start 之后的全部 seq 都算已回撤
|
|
288
|
+
// —— 这正是 opencode 的 `messages.slice(0, boundaryIndex)`(边界自己也不显示)。
|
|
279
289
|
for (const m of messages) {
|
|
280
290
|
if (!m || m.marker !== true) continue;
|
|
281
291
|
const prog = restoreProgress(events, m.seq);
|
|
@@ -287,6 +297,34 @@ async function opsList(targetCtx, sessionId) {
|
|
|
287
297
|
preview: seqText.get(t.turnSeq) || ('#' + t.turnSeq),
|
|
288
298
|
}));
|
|
289
299
|
}
|
|
300
|
+
|
|
301
|
+
// 0.9.1:**reverted** = opencode 语义「回撤边界及其后」。
|
|
302
|
+
//
|
|
303
|
+
// ⚠️ 不能用 `visible` 当隐藏判据 —— `visible` 是「是否在模型 surface 上」,
|
|
304
|
+
// 而 tool/call / turn/* / model/* **根本不是 surface 节点**(SURFACE_TYPES 只有
|
|
305
|
+
// system|user|developer|assistant/message 与 tool/result),它们永远 visible=false。
|
|
306
|
+
// 照抄会把**所有**工具调用行永久藏掉(实测 3/3 全被误藏)。
|
|
307
|
+
//
|
|
308
|
+
// 正确口径:每个**未恢复**的回撤标记 range.start 之后的全部 seq 都算已回撤 ——
|
|
309
|
+
// 这正是 opencode 的 `messages.slice(0, boundaryIndex)`(边界自己也不显示)。
|
|
310
|
+
const revertFences = messages
|
|
311
|
+
.filter((m) => m && m.marker === true && m.restoreComplete === false
|
|
312
|
+
&& m.range && typeof m.range.start === 'number')
|
|
313
|
+
.map((m) => m.range.start);
|
|
314
|
+
for (const m of messages) {
|
|
315
|
+
m.reverted = typeof m.seq === 'number' && revertFences.some((start) => m.seq >= start);
|
|
316
|
+
}
|
|
317
|
+
// 0.9.1:回合页脚/过程条的 node-key id 就是 turn 号,而它们**不是消息**,
|
|
318
|
+
// 无法用「首个带 turn 字段的消息」定位(该 turn 内可能一条消息都没有,
|
|
319
|
+
// 实测 turn 2 就映射不到)。这里直接给 turn/start 的 seq 映射表。
|
|
320
|
+
const bounds = turnBounds(events);
|
|
321
|
+
// 用 **turn/end 的 seq** 而不是 turn/start:回撤边界常落在某个 turn **内部**
|
|
322
|
+
// (实测边界 seq 54 在 turn 2 的 [51..62] 之间)。用起始 seq 会漏判该回合的页脚,
|
|
323
|
+
// 用结束 seq 则「边界之前完全在前」的回合自然落选。
|
|
324
|
+
const turnEndSeq = {};
|
|
325
|
+
for (const [turn, seq] of bounds.ends) turnEndSeq[turn] = seq;
|
|
326
|
+
for (const [turn, seq] of bounds.starts) if (!(turn in turnEndSeq)) turnEndSeq[turn] = seq;
|
|
327
|
+
|
|
290
328
|
return {
|
|
291
329
|
ok: true,
|
|
292
330
|
session: { id: header.id, createdAt: header.createdAt, parentSession: header.parentSession ?? null },
|
|
@@ -294,6 +332,8 @@ async function opsList(targetCtx, sessionId) {
|
|
|
294
332
|
runningSource: __runningSource,
|
|
295
333
|
total: messages.length,
|
|
296
334
|
visibleCount,
|
|
335
|
+
turnEndSeq,
|
|
336
|
+
revertFences,
|
|
297
337
|
messages,
|
|
298
338
|
};
|
|
299
339
|
}
|
|
@@ -303,8 +343,13 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
|
303
343
|
if (!Number.isSafeInteger(seq) || seq < 0) throw new OpsError("invalid seq", 400);
|
|
304
344
|
if (isRunning(targetCtx, sessionId)) throw new OpsError("session is running; stop it first", 409);
|
|
305
345
|
const { logPath } = pickSessionDir(sessionId);
|
|
306
|
-
const { events } = await readSessionFileAsync(logPath);
|
|
307
|
-
|
|
346
|
+
const { header, events } = await readSessionFileAsync(logPath);
|
|
347
|
+
// 0.8.2:空闲会话(实测 340/364)没有打开的 turn/step → 用自足的**合成 turn**
|
|
348
|
+
// 承载 notice,而不是拒绝。引擎 append-only 插不进已有 step,但合成一整个 turn 合法
|
|
349
|
+
//��已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
|
|
350
|
+
// 带 reason:"message-ops",UI 与审计可识别,不与真实模型轮次混淆。
|
|
351
|
+
const win = planNoticeWindow(events);
|
|
352
|
+
const turnStep = { turn: win.turn, step: win.step };
|
|
308
353
|
const notice = mode === "delete"
|
|
309
354
|
? `[消息删除] 已遮蔽 seq ${seq}`
|
|
310
355
|
: null; // revert 文案含 shadowed 数量,规划后拼
|
|
@@ -317,10 +362,16 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
|
317
362
|
const plan = mode === "delete" ? planDelete(session.surface, seq) : planRevert(session.surface, seq);
|
|
318
363
|
const text = mode === "delete" ? notice
|
|
319
364
|
: `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`;
|
|
365
|
+
// 0.8.2:会话 store 命中时走引擎路径 —— 同样要先开合成 turn 窗口,
|
|
366
|
+
// 否则 notice 落在已关闭的 turn/step 里,加载端拒绝整份历史。
|
|
367
|
+
for (const pre of noticeWindowPreamble(win)) session.append(pre.kind, pre.data);
|
|
320
368
|
const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep);
|
|
369
|
+
// 必须闭合:否则引擎内存里 turn 16 永远开着 → isRunning 恒真 → 后续操作全被 409
|
|
370
|
+
for (const post of noticeWindowPostamble(win)) session.append(post.kind, post.data);
|
|
321
371
|
flushSessions(targetCtx, session);
|
|
322
372
|
return {
|
|
323
373
|
ok: true, mode, seq,
|
|
374
|
+
syntheticTurn: win.synthetic === true,
|
|
324
375
|
shadowedCount: plan.shadowedSeqs.length,
|
|
325
376
|
eventSeq: event && event.seq != null ? event.seq : null,
|
|
326
377
|
};
|
|
@@ -332,30 +383,30 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
|
332
383
|
const plan = mode === "delete" ? planDeleteFromEvents(events, seq) : planRevertFromEvents(events, seq);
|
|
333
384
|
const text = mode === "delete" ? notice
|
|
334
385
|
: `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`;
|
|
386
|
+
// 0.8.2:磁盘路径同样把 marker 包进合成 turn(裸 zstd 写、零校验,写错就是整份日志报废)
|
|
387
|
+
const baseTime = Date.now();
|
|
388
|
+
let cursor = nextSeqFrom(events);
|
|
389
|
+
const batch = noticeWindowPreamble(win).map((e, i) => ({
|
|
390
|
+
type: e.kind, seq: cursor++, time: baseTime + i, data: e.data,
|
|
391
|
+
}));
|
|
335
392
|
const marker = buildMarkerEvent({
|
|
336
|
-
seq:
|
|
393
|
+
seq: cursor++, time: baseTime + batch.length, turnStep, text, version: header?.version ?? 4,
|
|
337
394
|
startSeq: plan.startSeq, endSeq: plan.endSeq, shadowedSeqs: plan.shadowedSeqs,
|
|
338
395
|
});
|
|
339
|
-
|
|
396
|
+
batch.push(marker);
|
|
397
|
+
let tail = marker.time + 1;
|
|
398
|
+
for (const e of noticeWindowPostamble(win)) batch.push({ type: e.kind, seq: cursor++, time: tail++, data: e.data });
|
|
399
|
+
await diskAppend(logPath, batch);
|
|
340
400
|
return {
|
|
341
|
-
ok: true, mode, seq, disk: true,
|
|
401
|
+
ok: true, mode, seq, disk: true, syntheticTurn: win.synthetic === true,
|
|
342
402
|
shadowedCount: plan.shadowedSeqs.length,
|
|
343
403
|
eventSeq: marker.seq,
|
|
344
404
|
};
|
|
345
405
|
}
|
|
346
406
|
|
|
347
|
-
function opsBranch(targetCtx, sessionId, upToSeq) {
|
|
348
|
-
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
349
|
-
if (!Number.isSafeInteger(upToSeq) || upToSeq < 0) throw new OpsError("invalid upToSeq", 400);
|
|
350
|
-
if (isRunning(targetCtx, sessionId)) {
|
|
351
|
-
throw new OpsError("session is running; stop it first (the log may be mid-append)", 409);
|
|
352
|
-
}
|
|
353
|
-
const { logPath } = pickSessionDir(sessionId);
|
|
354
|
-
return { ok: true, ...applyBranch(logPath, upToSeq) };
|
|
355
|
-
}
|
|
356
|
-
|
|
357
407
|
// 0.8.0:upToSeq 可选 —— 给定则按轮步进恢复(只重放到该 seq,后续仍遮蔽)。
|
|
358
|
-
|
|
408
|
+
// 0.8.1:opts.discard —— 不重放内容,仅停用标记(清贴条)。
|
|
409
|
+
async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
|
|
359
410
|
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
360
411
|
if (!Number.isSafeInteger(restoreSeq) || restoreSeq < 0) throw new OpsError("invalid seq", 400);
|
|
361
412
|
if (upToSeq !== undefined && (!Number.isSafeInteger(upToSeq) || upToSeq < 0)) throw new OpsError("invalid upToSeq", 400);
|
|
@@ -364,8 +415,16 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq) {
|
|
|
364
415
|
const { events } = await readSessionFileAsync(logPath);
|
|
365
416
|
// 0.8.0(B1 修复):步进恢复必须排除先前轮次已重放的源 seq,
|
|
366
417
|
// 否则每轮从区间头重放 → 消息副本成倍出现。
|
|
418
|
+
// 0.8.2:空闲会话(实测 340/364)没有打开的 turn/step → 用自足的**合成 turn**
|
|
419
|
+
// 承载 notice,而不是拒绝。引擎 append-only 插不进已有 step,但合成一整个 turn 合法
|
|
420
|
+
//��已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
|
|
421
|
+
// 带 reason:"message-ops",UI 与审计可识别,不与真实模型轮次混淆。
|
|
422
|
+
const win = planNoticeWindow(events);
|
|
367
423
|
const progress = restoreProgress(events, restoreSeq);
|
|
368
424
|
const plan = planRestore(events, restoreSeq, upToSeq, progress ? progress.restoredSeqs : null);
|
|
425
|
+
plan.turnStep = { turn: win.turn, step: win.step };
|
|
426
|
+
plan.window = win;
|
|
427
|
+
if (discard) plan.discard = true;
|
|
369
428
|
if (plan.replayable.length === 0 && progress && !progress.complete && progress.pendingSeqs.length > 0) {
|
|
370
429
|
// 请求的 upTo 之前已全部重放过 → 只补一条进度 notice(不重复重放)
|
|
371
430
|
plan.upToSeq = upToSeq != null ? Math.min(upToSeq, plan.endSeq) : plan.endSeq;
|
|
@@ -373,10 +432,12 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq) {
|
|
|
373
432
|
const acq = await acquireSession(targetCtx, sessionId);
|
|
374
433
|
if (acq !== null && acq.session !== undefined) {
|
|
375
434
|
try {
|
|
435
|
+
for (const pre of noticeWindowPreamble(win)) acq.session.append(pre.kind, pre.data);
|
|
376
436
|
const result = applyRestore(acq.session, plan, {
|
|
377
437
|
flush: () => { flushSessions(targetCtx, acq.session); },
|
|
378
438
|
});
|
|
379
|
-
|
|
439
|
+
for (const post of noticeWindowPostamble(winR)) acq.session.append(post.kind, post.data);
|
|
440
|
+
return { ok: true, ...result, discarded: plan.discard === true, upToSeq: plan.upToSeq, restoredSourceSeqs: plan.replayable.map((i) => i.seq), range: { startSeq: plan.startSeq, endSeq: plan.endSeq } };
|
|
380
441
|
} finally {
|
|
381
442
|
acq.release();
|
|
382
443
|
}
|
|
@@ -384,18 +445,28 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq) {
|
|
|
384
445
|
// store-miss → 磁盘路径:说明事件 + 重放事件批量追加(一个帧)
|
|
385
446
|
let cursor = nextSeqFrom(events);
|
|
386
447
|
const baseTime = Date.now();
|
|
387
|
-
const
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
448
|
+
const version = (await readSessionFileAsync(logPath)).header?.version ?? 4;
|
|
449
|
+
const batch = noticeWindowPreamble(win).map((e, i) => ({
|
|
450
|
+
type: e.kind, seq: cursor++, time: baseTime + i, data: e.data,
|
|
451
|
+
}));
|
|
452
|
+
const noticeBase = baseTime + batch.length;
|
|
453
|
+
batch.push(buildRestoreNoticeEvent({
|
|
454
|
+
seq: cursor++, time: noticeBase, turnStep: plan.turnStep, version,
|
|
455
|
+
text: plan.discard
|
|
456
|
+
? `[消息操作] 回撤标记 seq ${plan.restoreSeq} 已停用(丢弃):区间内容保持遮蔽、未重放;日志原文仍在,可搜索`
|
|
457
|
+
: restoreNoticeText(plan),
|
|
458
|
+
restoreSeq: plan.restoreSeq,
|
|
459
|
+
discard: plan.discard === true,
|
|
460
|
+
}));
|
|
392
461
|
let offset = 0;
|
|
393
|
-
for (const item of plan.replayable) {
|
|
394
|
-
batch.push(buildReplayEvent({ seq: cursor++, time:
|
|
462
|
+
for (const item of plan.discard ? [] : plan.replayable) {
|
|
463
|
+
batch.push(buildReplayEvent({ seq: cursor++, time: noticeBase + (++offset), item, turnStep: plan.turnStep, version }));
|
|
395
464
|
}
|
|
465
|
+
let tail = noticeBase + offset + 1;
|
|
466
|
+
for (const e of noticeWindowPostamble(win)) batch.push({ type: e.kind, seq: cursor++, time: tail++, data: e.data });
|
|
396
467
|
await diskAppend(logPath, batch);
|
|
397
468
|
return {
|
|
398
|
-
ok: true, disk: true,
|
|
469
|
+
ok: true, disk: true, syntheticTurn: win.synthetic === true,
|
|
399
470
|
restoredCount: plan.replayable.length,
|
|
400
471
|
upToSeq: plan.upToSeq,
|
|
401
472
|
restoredSourceSeqs: plan.replayable.map((i) => i.seq),
|
|
@@ -405,18 +476,6 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq) {
|
|
|
405
476
|
};
|
|
406
477
|
}
|
|
407
478
|
|
|
408
|
-
async function opsExport(targetCtx, sessionId, seq) {
|
|
409
|
-
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
410
|
-
if (seq !== undefined && (!Number.isSafeInteger(seq) || seq < 0)) throw new OpsError("invalid seq", 400);
|
|
411
|
-
const { logPath } = pickSessionDir(sessionId);
|
|
412
|
-
const { header, events, frameCount, partial } = await readSessionFileAsync(logPath);
|
|
413
|
-
let markdown = exportMarkdown(header, events, seq);
|
|
414
|
-
// 超阈值提示(partial 语义):内容完整,仅告知本次解压耗时可能较长。
|
|
415
|
-
if (partial) {
|
|
416
|
-
markdown += `\n> 注:本日志共 ${frameCount} 个事件帧(超过 ${500} 帧阈值),本次导出已完整读取,但大日志解压耗时较长。\n`;
|
|
417
|
-
}
|
|
418
|
-
return { header, markdown, upToSeq: seq, frameCount, partial };
|
|
419
|
-
}
|
|
420
479
|
|
|
421
480
|
// ---------------------------------------------------------------------------
|
|
422
481
|
// Agent 工具 message_ops(容错注册)
|
|
@@ -431,12 +490,12 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
|
|
|
431
490
|
return defineTool({
|
|
432
491
|
name: "message_ops",
|
|
433
492
|
description:
|
|
434
|
-
"Manage DSH conversation messages: list messages with visibility, revert to a seq (surface replace shadows the tail), delete a single message,
|
|
493
|
+
"Manage DSH conversation messages: list messages with visibility, revert to a seq (surface replace shadows the tail), delete a single message, restore (replay) messages shadowed by a previous revert. These are the message-level operations dsh does NOT provide natively (use the built-in session/fork for branching and /export for archives). Sessions must not be running for mutating actions.",
|
|
435
494
|
parameters: {
|
|
436
495
|
action: {
|
|
437
496
|
type: "string",
|
|
438
497
|
required: true,
|
|
439
|
-
enum: ["list", "revert", "delete", "
|
|
498
|
+
enum: ["list", "revert", "delete", "restore"],
|
|
440
499
|
description: "Which operation to perform.",
|
|
441
500
|
},
|
|
442
501
|
sessionId: {
|
|
@@ -446,11 +505,10 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
|
|
|
446
505
|
},
|
|
447
506
|
seq: {
|
|
448
507
|
type: "integer",
|
|
449
|
-
description: "revert/delete: the target seq. restore: the seq of the revert/delete marker event.
|
|
508
|
+
description: "revert/delete: the target seq. restore: the seq of the revert/delete marker event. Ignored by list.",
|
|
450
509
|
},
|
|
451
510
|
upToSeq: {
|
|
452
511
|
type: "integer",
|
|
453
|
-
description: "branch: fork keeps events up to this seq (inclusive).",
|
|
454
512
|
},
|
|
455
513
|
},
|
|
456
514
|
output: {
|
|
@@ -463,19 +521,14 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
|
|
|
463
521
|
try {
|
|
464
522
|
let result;
|
|
465
523
|
// 0.5.2(P1):ops 自 0.2.1 起为 async——不 await 会把 Promise 直接送进 renderResult,
|
|
466
|
-
// list/restore 必抛 TypeError
|
|
524
|
+
// list/restore 必抛 TypeError(测试桩曾是同步的故漏检)。
|
|
467
525
|
switch (action) {
|
|
468
526
|
case "list": result = await ops.list(ctx, sessionId); break;
|
|
469
527
|
case "revert": result = await ops.revert(ctx, sessionId, args.seq); break;
|
|
470
528
|
case "delete": result = await ops.delete(ctx, sessionId, args.seq); break;
|
|
471
|
-
case "branch": result = await ops.branch(ctx, sessionId, args.upToSeq); break;
|
|
472
529
|
case "restore": result = await ops.restore(ctx, sessionId, args.seq); break;
|
|
473
|
-
case "export": result = await ops.export(ctx, sessionId, args.seq); break;
|
|
474
530
|
default: throw new OpsError(`unknown action: ${action}`, 400);
|
|
475
531
|
}
|
|
476
|
-
if (action === "branch" && result && typeof result === "object" && result.parentSession == null) {
|
|
477
|
-
result.parentSession = sessionId; // renderResult 需要原始会话 id(branch 返回值不含/可为 undefined)
|
|
478
|
-
}
|
|
479
532
|
return renderResult(action, result);
|
|
480
533
|
} catch (e) {
|
|
481
534
|
return `${action} failed: ${e && e.message ? e.message : e}`;
|
|
@@ -489,7 +542,7 @@ function renderResult(action, r) {
|
|
|
489
542
|
switch (action) {
|
|
490
543
|
case "list": {
|
|
491
544
|
const lines = [
|
|
492
|
-
`session ${r.session.id}
|
|
545
|
+
`session ${r.session.id}`,
|
|
493
546
|
`running: ${r.running}; total: ${r.total}; visible: ${r.visibleCount}`,
|
|
494
547
|
];
|
|
495
548
|
for (const m of r.messages) {
|
|
@@ -500,12 +553,8 @@ function renderResult(action, r) {
|
|
|
500
553
|
case "revert":
|
|
501
554
|
case "delete":
|
|
502
555
|
return `${r.mode} ok: shadowed ${r.shadowedCount} node(s) from seq ${r.seq}; marker event seq ${r.eventSeq}`;
|
|
503
|
-
case "branch":
|
|
504
|
-
return `branch ok: new session ${r.newId} (parent ${r.parentSession ?? "n/a"}), kept ${r.keptEvents ?? "?"} event(s)`;
|
|
505
556
|
case "restore":
|
|
506
557
|
return `restore ok: replayed ${r.restoredCount} message(s) from range ${r.range.startSeq}..${r.range.endSeq} (${r.skipped} skipped); appended event seqs ${r.eventSeqs.join(", ")}`;
|
|
507
|
-
case "export":
|
|
508
|
-
return r.markdown;
|
|
509
558
|
default:
|
|
510
559
|
return JSON.stringify(r);
|
|
511
560
|
}
|
|
@@ -526,13 +575,15 @@ function registerToolTolerantly(ctx) {
|
|
|
526
575
|
list: (c, id) => opsList(c, id),
|
|
527
576
|
revert: (c, id, seq) => opsCommit(c, "revert", id, seq),
|
|
528
577
|
delete: (c, id, seq) => opsCommit(c, "delete", id, seq),
|
|
529
|
-
branch: (c, id, upToSeq) => opsBranch(c, id, upToSeq),
|
|
530
578
|
restore: (c, id, seq, upToSeq) => opsRestore(c, id, seq, upToSeq),
|
|
531
|
-
export: (c, id, seq) => opsExport(c, id, seq),
|
|
532
579
|
};
|
|
533
580
|
tools.register(createMessageOpsTool({ defineTool, ops, ctx: targetCtx }));
|
|
534
581
|
})
|
|
535
|
-
.catch(() => {
|
|
582
|
+
// 0.9.0:不再静默吞错。原先 catch(() => {}) 让「工具注册成功与否」完全无从诊断
|
|
583
|
+
// (实测日志里 defineTool / ERR_MODULE_NOT_FOUND 零命中)。
|
|
584
|
+
.catch((e) => {
|
|
585
|
+
console.warn('[message-ops] defineTool 注册失败,工具不可用(其余功能不受影响):', e && (e.code || e.message) ? (e.code || e.message) : e)
|
|
586
|
+
});
|
|
536
587
|
return true;
|
|
537
588
|
}
|
|
538
589
|
if (tryRegister(ctx)) return;
|
|
@@ -617,23 +668,6 @@ export function apply(ctx) {
|
|
|
617
668
|
kind: "exact", path: "/api/message-ops/delete", handler: commitHandler("delete"),
|
|
618
669
|
}), "dsh-message-ops: delete route");
|
|
619
670
|
|
|
620
|
-
// --- POST branch:磁盘级 fork(唯一非破坏操作) ---------------------------
|
|
621
|
-
targetCtx.effect(() => host.register({
|
|
622
|
-
kind: "exact",
|
|
623
|
-
path: "/api/message-ops/branch",
|
|
624
|
-
handler: async (req, res) => {
|
|
625
|
-
if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
626
|
-
if (!writeFence(req, res)) return;
|
|
627
|
-
const body = await readFencedBody(req, res);
|
|
628
|
-
if (body === undefined) return;
|
|
629
|
-
if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
|
|
630
|
-
try {
|
|
631
|
-
return sendJson(res, 200, opsBranch(targetCtx, body.sessionId, body.upToSeq));
|
|
632
|
-
} catch (err) {
|
|
633
|
-
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
634
|
-
}
|
|
635
|
-
},
|
|
636
|
-
}), "dsh-message-ops: branch route");
|
|
637
671
|
|
|
638
672
|
// --- POST restore:回滚恢复(重放语义,见 ops-core.js 注释) --------------
|
|
639
673
|
targetCtx.effect(() => host.register({
|
|
@@ -647,36 +681,13 @@ export function apply(ctx) {
|
|
|
647
681
|
if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
|
|
648
682
|
try {
|
|
649
683
|
// 0.8.0:body.upToSeq 存在 → 按轮步进恢复(只到该 seq)
|
|
650
|
-
return sendJson(res, 200, await opsRestore(targetCtx, body.sessionId, body.seq, body.upToSeq != null ? Number(body.upToSeq) : undefined));
|
|
684
|
+
return sendJson(res, 200, await opsRestore(targetCtx, body.sessionId, body.seq, body.upToSeq != null ? Number(body.upToSeq) : undefined, body.discard === true));
|
|
651
685
|
} catch (err) {
|
|
652
686
|
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
653
687
|
}
|
|
654
688
|
},
|
|
655
689
|
}), "dsh-message-ops: restore route");
|
|
656
690
|
|
|
657
|
-
// --- GET export:Markdown 附件下载 ----------------------------------------
|
|
658
|
-
targetCtx.effect(() => host.register({
|
|
659
|
-
kind: "exact",
|
|
660
|
-
path: "/api/message-ops/export",
|
|
661
|
-
handler: async (req, res) => {
|
|
662
|
-
if (!fence(req, res)) return;
|
|
663
|
-
try {
|
|
664
|
-
const url = new URL(req.url, "http://localhost");
|
|
665
|
-
const sessionId = url.searchParams.get("sessionId") || "";
|
|
666
|
-
const rawSeq = url.searchParams.get("seq");
|
|
667
|
-
const seq = rawSeq === null || rawSeq === "" ? undefined : Number(rawSeq);
|
|
668
|
-
const { header, markdown, upToSeq } = await opsExport(targetCtx, sessionId, seq);
|
|
669
|
-
const suffix = upToSeq === undefined ? "full" : `seq-${upToSeq}`;
|
|
670
|
-
res.writeHead(200, {
|
|
671
|
-
"content-type": "text/markdown; charset=utf-8",
|
|
672
|
-
"content-disposition": `attachment; filename="${header.id}-${suffix}.md"`,
|
|
673
|
-
});
|
|
674
|
-
res.end(markdown);
|
|
675
|
-
} catch (err) {
|
|
676
|
-
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
677
|
-
}
|
|
678
|
-
},
|
|
679
|
-
}), "dsh-message-ops: export route");
|
|
680
691
|
}
|
|
681
692
|
|
|
682
693
|
const ws = ctx.get("webServer");
|