@240xu/dsh-message-ops 0.7.0 → 0.9.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/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/branch/list/restore 共用 HTTP 同一套
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
@@ -23,9 +25,9 @@
23
25
  import { zstdCompressSync } from "node:zlib";
24
26
  import { open as openFile, truncate as truncateFile, stat as statFile } from "node:fs/promises";
25
27
  import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFile, readSessionFileAsync, listMessages, computeShadowed, messageText } from "./session-file.js";
26
- import { applyBranch } from "./branch.js";
27
- import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, deriveTurnStep,
28
- OpsError, planRevert, planDelete, planRestore, applyRestore, applySurfaceReplace, exportMarkdown,
28
+ import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble,
29
+ OpsError, planRevert, planDelete, planRestore, applyRestore, applySurfaceReplace,
30
+ restoreProgress, pendingRestoreTurns,
29
31
  isTrustedApiRequest, isJsonContentType,
30
32
  } from "./ops-core.js";
31
33
 
@@ -266,6 +268,26 @@ async function opsList(targetCtx, sessionId) {
266
268
  m.visible = visibleNodes ? visibleNodes.has(m.seq) : !shadowed.has(m.seq);
267
269
  if (m.visible) visibleCount++;
268
270
  }
271
+ // 0.8.0 按轮步进:为每个回撤/删除标记附恢复进度与"待恢复轮"。
272
+ // 一次建 seq→text 索引,避免每标记全量扫文本(性能评审点)。
273
+ const seqText = new Map();
274
+ for (const e of events) {
275
+ if (!e || typeof e.seq !== "number") continue;
276
+ if (e.type !== "user/message" && e.type !== "assistant/message") continue;
277
+ const t = messageText(e);
278
+ if (t && t.trim()) seqText.set(e.seq, t.trim().replace(/\s+/g, " ").slice(0, 80));
279
+ }
280
+ for (const m of messages) {
281
+ if (!m || m.marker !== true) continue;
282
+ const prog = restoreProgress(events, m.seq);
283
+ if (!prog) { m.restoreComplete = false; m.pendingTurns = []; continue; }
284
+ m.restoreComplete = prog.complete;
285
+ m.pendingTurns = pendingRestoreTurns(events, m.seq).map((t) => ({
286
+ upTo: t.seqs[t.seqs.length - 1],
287
+ count: t.seqs.length,
288
+ preview: seqText.get(t.turnSeq) || ('#' + t.turnSeq),
289
+ }));
290
+ }
269
291
  return {
270
292
  ok: true,
271
293
  session: { id: header.id, createdAt: header.createdAt, parentSession: header.parentSession ?? null },
@@ -282,8 +304,13 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
282
304
  if (!Number.isSafeInteger(seq) || seq < 0) throw new OpsError("invalid seq", 400);
283
305
  if (isRunning(targetCtx, sessionId)) throw new OpsError("session is running; stop it first", 409);
284
306
  const { logPath } = pickSessionDir(sessionId);
285
- const { events } = await readSessionFileAsync(logPath);
286
- const turnStep = deriveTurnStep(events);
307
+ const { header, events } = await readSessionFileAsync(logPath);
308
+ // 0.8.2:空闲会话(实测 340/364)没有打开的 turn/step → 用自足的**合成 turn**
309
+ // 承载 notice,而不是拒绝。引擎 append-only 插不进已有 step,但合成一整个 turn 合法
310
+ //��已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
311
+ // 带 reason:"message-ops",UI 与审计可识别,不与真实模型轮次混淆。
312
+ const win = planNoticeWindow(events);
313
+ const turnStep = { turn: win.turn, step: win.step };
287
314
  const notice = mode === "delete"
288
315
  ? `[消息删除] 已遮蔽 seq ${seq}`
289
316
  : null; // revert 文案含 shadowed 数量,规划后拼
@@ -296,10 +323,16 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
296
323
  const plan = mode === "delete" ? planDelete(session.surface, seq) : planRevert(session.surface, seq);
297
324
  const text = mode === "delete" ? notice
298
325
  : `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`;
326
+ // 0.8.2:会话 store 命中时走引擎路径 —— 同样要先开合成 turn 窗口,
327
+ // 否则 notice 落在已关闭的 turn/step 里,加载端拒绝整份历史。
328
+ for (const pre of noticeWindowPreamble(win)) session.append(pre.kind, pre.data);
299
329
  const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep);
330
+ // 必须闭合:否则引擎内存里 turn 16 永远开着 → isRunning 恒真 → 后续操作全被 409
331
+ for (const post of noticeWindowPostamble(win)) session.append(post.kind, post.data);
300
332
  flushSessions(targetCtx, session);
301
333
  return {
302
334
  ok: true, mode, seq,
335
+ syntheticTurn: win.synthetic === true,
303
336
  shadowedCount: plan.shadowedSeqs.length,
304
337
  eventSeq: event && event.seq != null ? event.seq : null,
305
338
  };
@@ -311,42 +344,61 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
311
344
  const plan = mode === "delete" ? planDeleteFromEvents(events, seq) : planRevertFromEvents(events, seq);
312
345
  const text = mode === "delete" ? notice
313
346
  : `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`;
347
+ // 0.8.2:磁盘路径同样把 marker 包进合成 turn(裸 zstd 写、零校验,写错就是整份日志报废)
348
+ const baseTime = Date.now();
349
+ let cursor = nextSeqFrom(events);
350
+ const batch = noticeWindowPreamble(win).map((e, i) => ({
351
+ type: e.kind, seq: cursor++, time: baseTime + i, data: e.data,
352
+ }));
314
353
  const marker = buildMarkerEvent({
315
- seq: nextSeqFrom(events), time: Date.now(), turnStep, text,
354
+ seq: cursor++, time: baseTime + batch.length, turnStep, text, version: header?.version ?? 4,
316
355
  startSeq: plan.startSeq, endSeq: plan.endSeq, shadowedSeqs: plan.shadowedSeqs,
317
356
  });
318
- await diskAppend(logPath, [marker]);
357
+ batch.push(marker);
358
+ let tail = marker.time + 1;
359
+ for (const e of noticeWindowPostamble(win)) batch.push({ type: e.kind, seq: cursor++, time: tail++, data: e.data });
360
+ await diskAppend(logPath, batch);
319
361
  return {
320
- ok: true, mode, seq, disk: true,
362
+ ok: true, mode, seq, disk: true, syntheticTurn: win.synthetic === true,
321
363
  shadowedCount: plan.shadowedSeqs.length,
322
364
  eventSeq: marker.seq,
323
365
  };
324
366
  }
325
367
 
326
- function opsBranch(targetCtx, sessionId, upToSeq) {
327
- if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
328
- if (!Number.isSafeInteger(upToSeq) || upToSeq < 0) throw new OpsError("invalid upToSeq", 400);
329
- if (isRunning(targetCtx, sessionId)) {
330
- throw new OpsError("session is running; stop it first (the log may be mid-append)", 409);
331
- }
332
- const { logPath } = pickSessionDir(sessionId);
333
- return { ok: true, ...applyBranch(logPath, upToSeq) };
334
- }
335
-
336
- async function opsRestore(targetCtx, sessionId, restoreSeq) {
368
+ // 0.8.0:upToSeq 可选 —— 给定则按轮步进恢复(只重放到该 seq,后续仍遮蔽)。
369
+ // 0.8.1:opts.discard —— 不重放内容,仅停用标记(清贴条)。
370
+ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
337
371
  if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
338
372
  if (!Number.isSafeInteger(restoreSeq) || restoreSeq < 0) throw new OpsError("invalid seq", 400);
373
+ if (upToSeq !== undefined && (!Number.isSafeInteger(upToSeq) || upToSeq < 0)) throw new OpsError("invalid upToSeq", 400);
339
374
  if (isRunning(targetCtx, sessionId)) throw new OpsError("session is running; stop it first", 409);
340
375
  const { logPath } = pickSessionDir(sessionId);
341
376
  const { events } = await readSessionFileAsync(logPath);
342
- const plan = planRestore(events, restoreSeq);
377
+ // 0.8.0(B1 修复):步进恢复必须排除先前轮次已重放的源 seq,
378
+ // 否则每轮从区间头重放 → 消息副本成倍出现。
379
+ // 0.8.2:空闲会话(实测 340/364)没有打开的 turn/step → 用自足的**合成 turn**
380
+ // 承载 notice,而不是拒绝。引擎 append-only 插不进已有 step,但合成一整个 turn 合法
381
+ //��已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
382
+ // 带 reason:"message-ops",UI 与审计可识别,不与真实模型轮次混淆。
383
+ const win = planNoticeWindow(events);
384
+ const progress = restoreProgress(events, restoreSeq);
385
+ const plan = planRestore(events, restoreSeq, upToSeq, progress ? progress.restoredSeqs : null);
386
+ plan.turnStep = { turn: win.turn, step: win.step };
387
+ plan.window = win;
388
+ if (discard) plan.discard = true;
389
+ if (plan.replayable.length === 0 && progress && !progress.complete && progress.pendingSeqs.length > 0) {
390
+ // 请求的 upTo 之前已全部重放过 → 只补一条进度 notice(不重复重放)
391
+ plan.upToSeq = upToSeq != null ? Math.min(upToSeq, plan.endSeq) : plan.endSeq;
392
+ }
343
393
  const acq = await acquireSession(targetCtx, sessionId);
344
394
  if (acq !== null && acq.session !== undefined) {
345
395
  try {
396
+ for (const pre of noticeWindowPreamble(win)) acq.session.append(pre.kind, pre.data);
346
397
  const result = applyRestore(acq.session, plan, {
347
398
  flush: () => { flushSessions(targetCtx, acq.session); },
348
399
  });
349
- return { ok: true, ...result, range: { startSeq: plan.startSeq, endSeq: plan.endSeq } };
400
+ for (const post of noticeWindowPostamble(winR)) acq.session.append(post.kind, post.data);
401
+ 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 } };
350
402
  } finally {
351
403
  acq.release();
352
404
  }
@@ -354,36 +406,37 @@ async function opsRestore(targetCtx, sessionId, restoreSeq) {
354
406
  // store-miss → 磁盘路径:说明事件 + 重放事件批量追加(一个帧)
355
407
  let cursor = nextSeqFrom(events);
356
408
  const baseTime = Date.now();
357
- const batch = [buildRestoreNoticeEvent({
358
- seq: cursor++, time: baseTime, turnStep: plan.turnStep,
359
- text: restoreNoticeText(plan), restoreSeq: plan.restoreSeq,
360
- })];
409
+ const version = (await readSessionFileAsync(logPath)).header?.version ?? 4;
410
+ const batch = noticeWindowPreamble(win).map((e, i) => ({
411
+ type: e.kind, seq: cursor++, time: baseTime + i, data: e.data,
412
+ }));
413
+ const noticeBase = baseTime + batch.length;
414
+ batch.push(buildRestoreNoticeEvent({
415
+ seq: cursor++, time: noticeBase, turnStep: plan.turnStep, version,
416
+ text: plan.discard
417
+ ? `[消息操作] 回撤标记 seq ${plan.restoreSeq} 已停用(丢弃):区间内容保持遮蔽、未重放;日志原文仍在,可搜索`
418
+ : restoreNoticeText(plan),
419
+ restoreSeq: plan.restoreSeq,
420
+ discard: plan.discard === true,
421
+ }));
361
422
  let offset = 0;
362
- for (const item of plan.replayable) {
363
- batch.push(buildReplayEvent({ seq: cursor++, time: baseTime + (++offset), item }));
423
+ for (const item of plan.discard ? [] : plan.replayable) {
424
+ batch.push(buildReplayEvent({ seq: cursor++, time: noticeBase + (++offset), item, turnStep: plan.turnStep, version }));
364
425
  }
426
+ let tail = noticeBase + offset + 1;
427
+ for (const e of noticeWindowPostamble(win)) batch.push({ type: e.kind, seq: cursor++, time: tail++, data: e.data });
365
428
  await diskAppend(logPath, batch);
366
429
  return {
367
- ok: true, disk: true,
430
+ ok: true, disk: true, syntheticTurn: win.synthetic === true,
368
431
  restoredCount: plan.replayable.length,
432
+ upToSeq: plan.upToSeq,
433
+ restoredSourceSeqs: plan.replayable.map((i) => i.seq),
369
434
  skipped: plan.skipped,
370
435
  eventSeqs: batch.map((e) => e.seq),
371
436
  range: { startSeq: plan.startSeq, endSeq: plan.endSeq },
372
437
  };
373
438
  }
374
439
 
375
- async function opsExport(targetCtx, sessionId, seq) {
376
- if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
377
- if (seq !== undefined && (!Number.isSafeInteger(seq) || seq < 0)) throw new OpsError("invalid seq", 400);
378
- const { logPath } = pickSessionDir(sessionId);
379
- const { header, events, frameCount, partial } = await readSessionFileAsync(logPath);
380
- let markdown = exportMarkdown(header, events, seq);
381
- // 超阈值提示(partial 语义):内容完整,仅告知本次解压耗时可能较长。
382
- if (partial) {
383
- markdown += `\n> 注:本日志共 ${frameCount} 个事件帧(超过 ${500} 帧阈值),本次导出已完整读取,但大日志解压耗时较长。\n`;
384
- }
385
- return { header, markdown, upToSeq: seq, frameCount, partial };
386
- }
387
440
 
388
441
  // ---------------------------------------------------------------------------
389
442
  // Agent 工具 message_ops(容错注册)
@@ -398,12 +451,12 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
398
451
  return defineTool({
399
452
  name: "message_ops",
400
453
  description:
401
- "Manage DSH conversation messages: list messages with visibility, revert to a seq (surface replace shadows the tail), delete a single message, fork a branch from any seq, restore (replay) messages shadowed by a previous revert, or export the conversation as Markdown. Sessions must not be running for mutating actions.",
454
+ "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.",
402
455
  parameters: {
403
456
  action: {
404
457
  type: "string",
405
458
  required: true,
406
- enum: ["list", "revert", "delete", "branch", "restore", "export"],
459
+ enum: ["list", "revert", "delete", "restore"],
407
460
  description: "Which operation to perform.",
408
461
  },
409
462
  sessionId: {
@@ -413,11 +466,10 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
413
466
  },
414
467
  seq: {
415
468
  type: "integer",
416
- description: "revert/delete: the target seq. restore: the seq of the revert/delete marker event. export: optional upper bound (inclusive). Ignored by list/branch.",
469
+ description: "revert/delete: the target seq. restore: the seq of the revert/delete marker event. Ignored by list.",
417
470
  },
418
471
  upToSeq: {
419
472
  type: "integer",
420
- description: "branch: fork keeps events up to this seq (inclusive).",
421
473
  },
422
474
  },
423
475
  output: {
@@ -430,19 +482,14 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
430
482
  try {
431
483
  let result;
432
484
  // 0.5.2(P1):ops 自 0.2.1 起为 async——不 await 会把 Promise 直接送进 renderResult,
433
- // list/restore 必抛 TypeError、export 渲出空 text(测试桩曾是同步的故漏检)。
485
+ // list/restore 必抛 TypeError(测试桩曾是同步的故漏检)。
434
486
  switch (action) {
435
487
  case "list": result = await ops.list(ctx, sessionId); break;
436
488
  case "revert": result = await ops.revert(ctx, sessionId, args.seq); break;
437
489
  case "delete": result = await ops.delete(ctx, sessionId, args.seq); break;
438
- case "branch": result = await ops.branch(ctx, sessionId, args.upToSeq); break;
439
490
  case "restore": result = await ops.restore(ctx, sessionId, args.seq); break;
440
- case "export": result = await ops.export(ctx, sessionId, args.seq); break;
441
491
  default: throw new OpsError(`unknown action: ${action}`, 400);
442
492
  }
443
- if (action === "branch" && result && typeof result === "object" && result.parentSession == null) {
444
- result.parentSession = sessionId; // renderResult 需要原始会话 id(branch 返回值不含/可为 undefined)
445
- }
446
493
  return renderResult(action, result);
447
494
  } catch (e) {
448
495
  return `${action} failed: ${e && e.message ? e.message : e}`;
@@ -456,7 +503,7 @@ function renderResult(action, r) {
456
503
  switch (action) {
457
504
  case "list": {
458
505
  const lines = [
459
- `session ${r.session.id}${r.session.parentSession ? ` (branch of ${r.session.parentSession})` : ""}`,
506
+ `session ${r.session.id}`,
460
507
  `running: ${r.running}; total: ${r.total}; visible: ${r.visibleCount}`,
461
508
  ];
462
509
  for (const m of r.messages) {
@@ -467,12 +514,8 @@ function renderResult(action, r) {
467
514
  case "revert":
468
515
  case "delete":
469
516
  return `${r.mode} ok: shadowed ${r.shadowedCount} node(s) from seq ${r.seq}; marker event seq ${r.eventSeq}`;
470
- case "branch":
471
- return `branch ok: new session ${r.newId} (parent ${r.parentSession ?? "n/a"}), kept ${r.keptEvents ?? "?"} event(s)`;
472
517
  case "restore":
473
518
  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(", ")}`;
474
- case "export":
475
- return r.markdown;
476
519
  default:
477
520
  return JSON.stringify(r);
478
521
  }
@@ -493,13 +536,15 @@ function registerToolTolerantly(ctx) {
493
536
  list: (c, id) => opsList(c, id),
494
537
  revert: (c, id, seq) => opsCommit(c, "revert", id, seq),
495
538
  delete: (c, id, seq) => opsCommit(c, "delete", id, seq),
496
- branch: (c, id, upToSeq) => opsBranch(c, id, upToSeq),
497
- restore: (c, id, seq) => opsRestore(c, id, seq),
498
- export: (c, id, seq) => opsExport(c, id, seq),
539
+ restore: (c, id, seq, upToSeq) => opsRestore(c, id, seq, upToSeq),
499
540
  };
500
541
  tools.register(createMessageOpsTool({ defineTool, ops, ctx: targetCtx }));
501
542
  })
502
- .catch(() => { /* dsh-tools 不可解析:跳过工具注册,不影响其余功能 */ });
543
+ // 0.9.0:不再静默吞错。原先 catch(() => {}) 让「工具注册成功与否」完全无从诊断
544
+ // (实测日志里 defineTool / ERR_MODULE_NOT_FOUND 零命中)。
545
+ .catch((e) => {
546
+ console.warn('[message-ops] defineTool 注册失败,工具不可用(其余功能不受影响):', e && (e.code || e.message) ? (e.code || e.message) : e)
547
+ });
503
548
  return true;
504
549
  }
505
550
  if (tryRegister(ctx)) return;
@@ -584,23 +629,6 @@ export function apply(ctx) {
584
629
  kind: "exact", path: "/api/message-ops/delete", handler: commitHandler("delete"),
585
630
  }), "dsh-message-ops: delete route");
586
631
 
587
- // --- POST branch:磁盘级 fork(唯一非破坏操作) ---------------------------
588
- targetCtx.effect(() => host.register({
589
- kind: "exact",
590
- path: "/api/message-ops/branch",
591
- handler: async (req, res) => {
592
- if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
593
- if (!writeFence(req, res)) return;
594
- const body = await readFencedBody(req, res);
595
- if (body === undefined) return;
596
- if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
597
- try {
598
- return sendJson(res, 200, opsBranch(targetCtx, body.sessionId, body.upToSeq));
599
- } catch (err) {
600
- return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
601
- }
602
- },
603
- }), "dsh-message-ops: branch route");
604
632
 
605
633
  // --- POST restore:回滚恢复(重放语义,见 ops-core.js 注释) --------------
606
634
  targetCtx.effect(() => host.register({
@@ -613,36 +641,14 @@ export function apply(ctx) {
613
641
  if (body === undefined) return;
614
642
  if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
615
643
  try {
616
- return sendJson(res, 200, await opsRestore(targetCtx, body.sessionId, body.seq));
644
+ // 0.8.0:body.upToSeq 存在 → 按轮步进恢复(只到该 seq)
645
+ return sendJson(res, 200, await opsRestore(targetCtx, body.sessionId, body.seq, body.upToSeq != null ? Number(body.upToSeq) : undefined, body.discard === true));
617
646
  } catch (err) {
618
647
  return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
619
648
  }
620
649
  },
621
650
  }), "dsh-message-ops: restore route");
622
651
 
623
- // --- GET export:Markdown 附件下载 ----------------------------------------
624
- targetCtx.effect(() => host.register({
625
- kind: "exact",
626
- path: "/api/message-ops/export",
627
- handler: async (req, res) => {
628
- if (!fence(req, res)) return;
629
- try {
630
- const url = new URL(req.url, "http://localhost");
631
- const sessionId = url.searchParams.get("sessionId") || "";
632
- const rawSeq = url.searchParams.get("seq");
633
- const seq = rawSeq === null || rawSeq === "" ? undefined : Number(rawSeq);
634
- const { header, markdown, upToSeq } = await opsExport(targetCtx, sessionId, seq);
635
- const suffix = upToSeq === undefined ? "full" : `seq-${upToSeq}`;
636
- res.writeHead(200, {
637
- "content-type": "text/markdown; charset=utf-8",
638
- "content-disposition": `attachment; filename="${header.id}-${suffix}.md"`,
639
- });
640
- res.end(markdown);
641
- } catch (err) {
642
- return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
643
- }
644
- },
645
- }), "dsh-message-ops: export route");
646
652
  }
647
653
 
648
654
  const ws = ctx.get("webServer");