@240xu/dsh-message-ops 0.11.1 → 0.11.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/src/index.js CHANGED
@@ -9,11 +9,12 @@
9
9
  import { zstdCompressSync } from "node:zlib";
10
10
  import { open as openFile, truncate as truncateFile, stat as statFile } from "node:fs/promises";
11
11
  import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFileAsync, listMessages, computeShadowed, messageText, messageTextFull, turnBounds, markCommitted } from "./session-file.js";
12
- import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble,
12
+ import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble, sessionLogOf, alignLiveTurnCursor,
13
13
  OpsError, planRevert, planDelete, planRestore, applyRestore, applySurfaceReplace,
14
- restoreProgress, pendingRestoreTurns,
14
+ restoreProgress, pendingRestoreTurns, buildRestoreIndex, restoreProgressFromIndex, pendingRestoreTurnsFromIndex,
15
15
  isTrustedApiRequest, isJsonContentType, webAuthGate,
16
16
  } from "./ops-core.js";
17
+ import { deleteSessionToTrash, listTrash, restoreTrash, purgeTrash, resolveSessionTitle } from "./session-trash.js";
17
18
 
18
19
  export const name = "dsh-message-ops";
19
20
  // 保持 inject 为空:tools 是可选增强而非硬依赖(cordis 的 inject 是
@@ -50,8 +51,8 @@ async function fence(targetCtx, req, res) {
50
51
  }
51
52
  // 0.10.8:宿主同条件 GET 被读全量(审计缺口)。宿主 /api admit = 三层围栏
52
53
  // 之外还要 BrowserAuth cookie(无 cookie → 401);前端同源 fetch 自动带
53
- // cookie,取数不受影响。secret 读不到 = 降级回旧围栏(webAuthGate 内部
54
- // 告警一次),老宿主/测桩不破坏。
54
+ // cookie,取数不受影响。无 credentials 服务 = 老宿主旧围栏;有服务但
55
+ // 记录不可读 = 401 fail-closed(webAuthGate 内部告警一次)。
55
56
  if (!(await webAuthGate(targetCtx, req))) {
56
57
  sendJson(res, 401, { ok: false, error: "unauthorized (browser auth cookie required; reopen the URL printed by dsh web)" });
57
58
  return false;
@@ -354,6 +355,7 @@ async function buildDerived(logPath) {
354
355
  // seqText 索引,也不扫一遍 events(seqText 为 null 时下面两处都短路:
355
356
  // 本循环直接跳过,marker 循环体也一次都不会执行)。
356
357
  const seqText = messages.some((m) => m.marker === true) ? new Map() : null;
358
+ const restoreIndex = seqText ? buildRestoreIndex(events) : null;
357
359
  for (const e of seqText ? events : []) {
358
360
  if (!e || typeof e.seq !== "number") continue;
359
361
  if (e.type !== "user/message" && e.type !== "assistant/message") continue;
@@ -378,10 +380,10 @@ async function buildDerived(logPath) {
378
380
  // —— 这正是 opencode 的 `messages.slice(0, boundaryIndex)`(边界自己也不显示)。
379
381
  for (const m of messages) {
380
382
  if (!m || m.marker !== true) continue;
381
- const prog = restoreProgress(events, m.seq);
383
+ const prog = restoreProgressFromIndex(restoreIndex, m.seq);
382
384
  if (!prog) { m.restoreComplete = false; m.pendingTurns = []; continue; }
383
385
  m.restoreComplete = prog.complete;
384
- m.pendingTurns = pendingRestoreTurns(events, m.seq, prog).map((t) => ({
386
+ m.pendingTurns = pendingRestoreTurnsFromIndex(restoreIndex, m.seq, prog).map((t) => ({
385
387
  upTo: t.seqs[t.seqs.length - 1],
386
388
  count: t.seqs.length,
387
389
  // 0.10.2:轮起点常落在注入行上(system-reminder / 后台任务 / 子代理通知),
@@ -455,8 +457,9 @@ async function loadDerived(logPath) {
455
457
  return entry.promise;
456
458
  }
457
459
 
458
- async function opsList(targetCtx, sessionId) {
460
+ async function opsList(targetCtx, sessionId, opts = {}) {
459
461
  if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
462
+ const compact = opts && opts.compact === true;
460
463
  const { logPath } = pickSessionDir(sessionId);
461
464
  // 文件派生段(读日志 → 消息 → 遮蔽集 → marker 进度 → turn 边界)走缓存:
462
465
  // key = logPath、失效看读前 stat 的 mtimeMs+size,见 loadDerived 注释。
@@ -470,6 +473,8 @@ async function opsList(targetCtx, sessionId) {
470
473
  applyLiveCommitted(messages, live);
471
474
  const visibleNodes = live && live.surface && Array.isArray(live.surface.nodes) ? new Set(live.surface.nodes) : null;
472
475
  let visibleCount = 0;
476
+ let shadowedCount = 0;
477
+ let markerCount = 0;
473
478
  for (const m of messages) {
474
479
  m.visible = visibleNodes ? visibleNodes.has(m.seq) : !shadowed.has(m.seq);
475
480
  // 0.9.6:**shadowed 与 visible 是两套语义,不能混用。**
@@ -484,22 +489,128 @@ async function opsList(targetCtx, sessionId) {
484
489
  // transcript 藏行必须用它;visible 只留给「可回滚目标」(lastRevertable)。
485
490
  m.shadowed = shadowed.has(m.seq);
486
491
  if (m.visible) visibleCount++;
492
+ if (m.shadowed) shadowedCount++;
493
+ if (m.marker === true) markerCount++;
487
494
  }
488
495
 
496
+ const visibleMessages = compact
497
+ ? messages.map((m) => ({
498
+ seq: m.seq,
499
+ role: m.role,
500
+ snippet: m.snippet,
501
+ time: m.time,
502
+ visible: m.visible,
503
+ shadowed: m.shadowed,
504
+ }))
505
+ : messages;
506
+
489
507
  return {
490
508
  ok: true,
491
- session: { id: header.id, createdAt: header.createdAt, parentSession: header.parentSession ?? null },
509
+ session: {
510
+ id: header.id,
511
+ createdAt: header.createdAt,
512
+ parentSession: header.parentSession ?? null,
513
+ confirmTitle: resolveSessionTitle(targetCtx, sessionId) || header.id,
514
+ },
492
515
  running: isRunning(targetCtx, sessionId),
493
516
  runningSource: __runningSource,
494
517
  total: messages.length,
495
518
  visibleCount,
519
+ shadowedCount,
520
+ markerCount,
496
521
  turnEndSeq,
497
- messages,
522
+ messages: visibleMessages,
498
523
  };
499
524
  }
500
525
 
501
- /** 测试钩子(非公开 API):直接驱动 list 与文件派生缓存。 */
502
- export const _internals = { opsList, loadDerived, derivedCache };
526
+ // ---------------------------------------------------------------------------
527
+ // Per-session search (full text, beyond the 160-char snippet)
528
+ // ---------------------------------------------------------------------------
529
+ const SEARCH_CACHE_MAX = 8;
530
+ const searchCache = new Map(); // logPath -> { mtimeMs, size, promise }
531
+
532
+ /** Build the searchable corpus once per log revision (full text, lowercased lazily). */
533
+ async function buildSearchCorpus(logPath) {
534
+ const { events } = await readSessionFileAsync(logPath);
535
+ const messages = listMessages(events);
536
+ const shadowed = computeShadowed(events);
537
+ const bySeq = new Map();
538
+ for (const e of events) if (e && typeof e.seq === "number") bySeq.set(e.seq, e);
539
+ const corpus = [];
540
+ for (const m of messages) {
541
+ const ev = bySeq.get(m.seq);
542
+ const text = ev ? messageTextFull(ev) : "";
543
+ corpus.push({
544
+ seq: m.seq,
545
+ type: m.type,
546
+ role: m.role,
547
+ marker: m.marker === true,
548
+ shadowed: shadowed.has(m.seq),
549
+ text: text || m.snippet || "",
550
+ });
551
+ }
552
+ return corpus;
553
+ }
554
+
555
+ async function loadSearchCorpus(logPath) {
556
+ const st = await statFile(logPath);
557
+ const hit = searchCache.get(logPath);
558
+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
559
+ searchCache.delete(logPath);
560
+ searchCache.set(logPath, hit);
561
+ return hit.promise;
562
+ }
563
+ const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: buildSearchCorpus(logPath) };
564
+ searchCache.delete(logPath);
565
+ searchCache.set(logPath, entry);
566
+ while (searchCache.size > SEARCH_CACHE_MAX) searchCache.delete(searchCache.keys().next().value);
567
+ entry.promise.catch(() => { if (searchCache.get(logPath) === entry) searchCache.delete(logPath); });
568
+ return entry.promise;
569
+ }
570
+
571
+ function searchSnippet(text, query, radius = 45) {
572
+ const lower = text.toLowerCase();
573
+ const at = lower.indexOf(query);
574
+ const start = at < 0 ? 0 : Math.max(0, at - radius);
575
+ const end = at < 0 ? Math.min(text.length, 160) : Math.min(text.length, at + query.length + radius);
576
+ const raw = text.slice(start, end).replace(/\s+/g, " ").trim();
577
+ return (start > 0 ? "…" : "") + raw.slice(0, 158) + (end < text.length ? "…" : "");
578
+ }
579
+
580
+ async function opsSearch(targetCtx, sessionId, query, opts = {}) {
581
+ if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
582
+ const q = typeof query === "string" ? query.trim() : "";
583
+ if (q.length === 0) throw new OpsError("query is required", 400);
584
+ if (q.length > 500) throw new OpsError("query too long (max 500)", 400);
585
+ const role = opts && typeof opts.role === "string" && opts.role ? opts.role : null;
586
+ if (role && !["user", "assistant", "system", "tool"].includes(role)) {
587
+ throw new OpsError("invalid role", 400);
588
+ }
589
+ const limit = Number.isSafeInteger(opts && opts.limit) ? Math.max(1, Math.min(100, opts.limit)) : 50;
590
+ const { logPath } = pickSessionDir(sessionId);
591
+ const corpus = await loadSearchCorpus(logPath);
592
+ const needle = q.toLowerCase();
593
+ const results = [];
594
+ let total = 0;
595
+ for (const row of corpus) {
596
+ if (role && row.role !== role) continue;
597
+ if (!row.text.toLowerCase().includes(needle)) continue;
598
+ total++;
599
+ if (results.length >= limit) continue;
600
+ results.push({
601
+ seq: row.seq,
602
+ type: row.type,
603
+ role: row.role,
604
+ marker: row.marker,
605
+ shadowed: row.shadowed,
606
+ snippet: searchSnippet(row.text, needle),
607
+ });
608
+ }
609
+ return { ok: true, query: q, role, limit, total, truncated: total > results.length, results };
610
+ }
611
+
612
+ /** 测试钩子(非公开 API):直接驱动 list / search 与文件派生缓存。 */
613
+ export const _internals = { opsList, opsSearch, loadDerived, loadSearchCorpus, derivedCache, searchCache };
503
614
 
504
615
  async function opsCommit(targetCtx, mode, sessionId, seq) {
505
616
  if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
@@ -511,8 +622,7 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
511
622
  // 承载 notice,而不是拒绝。引擎 append-only 插不进已有 step,但合成一整个 turn 合法
512
623
  //��已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
513
624
  // 带 reason:"message-ops",UI 与审计可识别,不与真实模型轮次混淆。
514
- const win = planNoticeWindow(events);
515
- const turnStep = { turn: win.turn, step: win.step };
625
+ let win = planNoticeWindow(events);
516
626
  const notice = mode === "delete"
517
627
  ? `[消息删除] 已遮蔽 seq ${seq}`
518
628
  : null; // revert 文案含 shadowed 数量,规划后拼
@@ -520,6 +630,9 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
520
630
  if (acq !== null && acq.session !== undefined) {
521
631
  try {
522
632
  const session = acq.session;
633
+ const liveEvents = sessionLogOf(session);
634
+ if (liveEvents) win = planNoticeWindow(liveEvents);
635
+ const turnStep = { turn: win.turn, step: win.step };
523
636
  // 0.5.4(P0):v4 准入要求 system/message 带正 turn/step——缺字段时持久层
524
637
  // encodeEventBatch 的 SessionFormatError 未捕获会**打死整个 dsh 进程**。
525
638
  const plan = mode === "delete" ? planDelete(session.surface, seq) : planRevert(session.surface, seq);
@@ -539,6 +652,7 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
539
652
  const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep);
540
653
  // 必须闭合:否则引擎内存里 turn 16 永远开着 → isRunning 恒真 → 后续操作全被 409
541
654
  for (const post of noticeWindowPostamble(win)) session.append(post.kind, post.data);
655
+ if (win.synthetic) alignLiveTurnCursor(targetCtx, session, win.turn);
542
656
  flushSessions(targetCtx, session);
543
657
  return {
544
658
  ok: true, mode, seq,
@@ -568,7 +682,7 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
568
682
  type: e.kind, seq: cursor++, time: baseTime + i, data: e.data,
569
683
  }));
570
684
  const marker = buildMarkerEvent({
571
- seq: cursor++, time: baseTime + batch.length, turnStep, text, version: header?.version ?? 4,
685
+ seq: cursor++, time: baseTime + batch.length, turnStep: { turn: win.turn, step: win.step }, text, version: header?.version ?? 4,
572
686
  startSeq: plan.startSeq, endSeq: plan.endSeq, shadowedSeqs: plan.shadowedSeqs,
573
687
  });
574
688
  batch.push(marker);
@@ -594,27 +708,34 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
594
708
  // 0.8.0(B1 修复):步进恢复必须排除先前轮次已重放的源 seq,
595
709
  // 否则每轮从区间头重放 → 消息副本成倍出现。
596
710
  // 合成 turn 承载 notice 的完整理由见 opsCommit() 处(0.8.2,实测 340/364 空闲会话)。
597
- const win = planNoticeWindow(events);
598
- const progress = restoreProgress(events, restoreSeq);
599
- const plan = planRestore(events, restoreSeq, upToSeq, progress ? progress.restoredSeqs : null);
600
- plan.turnStep = { turn: win.turn, step: win.step };
601
- plan.window = win;
602
- if (discard) plan.discard = true;
603
- if (plan.replayable.length === 0 && progress && !progress.complete && progress.pendingSeqs.length > 0) {
604
- // 请求的 upTo 之前已全部重放过 → 只补一条进度 notice(不重复重放)
605
- plan.upToSeq = upToSeq != null ? Math.min(upToSeq, plan.endSeq) : plan.endSeq;
606
- }
711
+ const buildPlan = (sourceEvents) => {
712
+ const window = planNoticeWindow(sourceEvents);
713
+ const progress = restoreProgress(sourceEvents, restoreSeq);
714
+ const restorePlan = planRestore(sourceEvents, restoreSeq, upToSeq, progress ? progress.restoredSeqs : null);
715
+ restorePlan.turnStep = { turn: window.turn, step: window.step };
716
+ restorePlan.window = window;
717
+ if (discard) restorePlan.discard = true;
718
+ if (restorePlan.replayable.length === 0 && progress && !progress.complete && progress.pendingSeqs.length > 0) {
719
+ // 请求的 upTo 之前已全部重放过 → 只补一条进度 notice(不重复重放)
720
+ restorePlan.upToSeq = upToSeq != null ? Math.min(upToSeq, restorePlan.endSeq) : restorePlan.endSeq;
721
+ }
722
+ return { win: window, plan: restorePlan };
723
+ };
724
+ let { win, plan } = buildPlan(events);
607
725
  const acq = await acquireSession(targetCtx, sessionId);
608
726
  if (acq !== null && acq.session !== undefined) {
609
727
  // 0.10.8 孤儿护栏(与 opsCommit 同型):planRestore/进度校验本就在 preamble
610
728
  // 之前完成;applyRestore 里的引擎 append 若抛(如 replay 坐标错开),
611
729
  // preamble 已落——闭合合成 turn 再原样抛出,不留常开孤儿窗口。
612
730
  try {
731
+ const liveEvents = sessionLogOf(acq.session);
732
+ if (liveEvents) ({ win, plan } = buildPlan(liveEvents));
613
733
  for (const pre of noticeWindowPreamble(win)) acq.session.append(pre.kind, pre.data);
614
734
  const result = applyRestore(acq.session, plan, {
615
735
  flush: () => { flushSessions(targetCtx, acq.session); },
616
736
  });
617
737
  for (const post of noticeWindowPostamble(win)) acq.session.append(post.kind, post.data);
738
+ if (win.synthetic) alignLiveTurnCursor(targetCtx, acq.session, win.turn);
618
739
  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 } };
619
740
  } catch (err) {
620
741
  for (const post of noticeWindowPostamble(win)) {
@@ -797,13 +918,40 @@ export function apply(ctx) {
797
918
  if (!(await fence(targetCtx, req, res))) return;
798
919
  try {
799
920
  const url = new URL(req.url, "http://localhost");
800
- return sendJson(res, 200, await opsList(targetCtx, url.searchParams.get("sessionId") || ""));
921
+ return sendJson(res, 200, await opsList(targetCtx, url.searchParams.get("sessionId") || "", {
922
+ compact: url.searchParams.get("view") === "compact",
923
+ }));
801
924
  } catch (err) {
802
925
  return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
803
926
  }
804
927
  },
805
928
  }), "dsh-message-ops: messages route");
806
929
 
930
+ // --- GET /api/message-ops/search:会话内全文搜索(服务端,匹配 snippet 之外) --
931
+ targetCtx.effect(() => host.register({
932
+ kind: "exact",
933
+ path: "/api/message-ops/search",
934
+ handler: async (req, res) => {
935
+ if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
936
+ if (!(await fence(targetCtx, req, res))) return;
937
+ try {
938
+ const url = new URL(req.url, "http://localhost");
939
+ const limitRaw = Number.parseInt(url.searchParams.get("limit") || "", 10);
940
+ return sendJson(res, 200, await opsSearch(
941
+ targetCtx,
942
+ url.searchParams.get("sessionId") || "",
943
+ url.searchParams.get("q") || "",
944
+ {
945
+ role: url.searchParams.get("role") || null,
946
+ limit: Number.isSafeInteger(limitRaw) ? limitRaw : undefined,
947
+ },
948
+ ));
949
+ } catch (err) {
950
+ return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
951
+ }
952
+ },
953
+ }), "dsh-message-ops: search route");
954
+
807
955
  // --- GET /api/message-ops/text:单条消息全文(0.5.2 引用按钮按需取) ----------
808
956
  // assistant 消息的 fullText 不在 messages 列表里(载荷控制),quote 点击时单取。
809
957
  targetCtx.effect(() => host.register({
@@ -877,6 +1025,45 @@ export function apply(ctx) {
877
1025
  },
878
1026
  }), "dsh-message-ops: restore route");
879
1027
 
1028
+ // --- Session trash:删除整条会话(可逆),列表 / 恢复 / 永久清理 ----------
1029
+ targetCtx.effect(() => host.register({
1030
+ kind: "exact",
1031
+ path: "/api/message-ops/session/trash",
1032
+ handler: async (req, res) => {
1033
+ if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
1034
+ if (!(await fence(targetCtx, req, res))) return;
1035
+ try {
1036
+ return sendJson(res, 200, { ok: true, entries: await listTrash(targetCtx, { purgeExpired: true }) });
1037
+ } catch (err) {
1038
+ return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
1039
+ }
1040
+ },
1041
+ }), "dsh-message-ops: session trash route");
1042
+
1043
+ const sessionAction = (path, action) => targetCtx.effect(() => host.register({
1044
+ kind: "exact",
1045
+ path,
1046
+ handler: async (req, res) => {
1047
+ if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
1048
+ if (!(await writeFence(targetCtx, req, res))) return;
1049
+ const body = await readFencedBody(req, res);
1050
+ if (body === undefined) return;
1051
+ if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
1052
+ try {
1053
+ return sendJson(res, 200, await action(targetCtx, body));
1054
+ } catch (err) {
1055
+ return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
1056
+ }
1057
+ },
1058
+ }), "dsh-message-ops: " + path);
1059
+
1060
+ sessionAction("/api/message-ops/session/delete", (c, b) =>
1061
+ deleteSessionToTrash(c, b.sessionId, b.confirmTitle));
1062
+ sessionAction("/api/message-ops/session/restore", (c, b) =>
1063
+ restoreTrash(c, b.trashId));
1064
+ sessionAction("/api/message-ops/session/purge", (c, b) =>
1065
+ purgeTrash(c, b.trashId));
1066
+
880
1067
  }
881
1068
 
882
1069
  const ws = ctx.get("webServer");
package/src/ops-core.js CHANGED
@@ -120,6 +120,21 @@ function messageSource(role, version) {
120
120
  return { kind: "plugin", plugin: PLUGIN_NAME, role: r };
121
121
  }
122
122
 
123
+ function assistantReplaySource(item, version) {
124
+ const source = item && item.source;
125
+ if (version === 4) {
126
+ if (!source || source.kind !== "model" || typeof source.provider !== "string" || !source.provider
127
+ || typeof source.model !== "string" || !source.model) {
128
+ throw new OpsError("assistant replay requires the original model source", 500);
129
+ }
130
+ return { ...source };
131
+ }
132
+ if (source && typeof source === "object" && typeof source.kind === "string" && source.kind) {
133
+ return { ...source };
134
+ }
135
+ return messageSource("assistant", version);
136
+ }
137
+
123
138
  /**
124
139
  * 重放事件的 data 形状 —— **按事件类型分派**。
125
140
  *
@@ -148,7 +163,7 @@ export function replayEventData(item, ts, version = 4) {
148
163
  message: {
149
164
  id: item.id ?? randomUUID(),
150
165
  role: "assistant",
151
- source: messageSource("assistant", version),
166
+ source: assistantReplaySource(item, version),
152
167
  content: [{ type: "text", text: item.text }],
153
168
  },
154
169
  // ⚠️ v4 契约 `stream: AssistantStreamRecord[]` **非可选**
@@ -221,6 +236,27 @@ export function deriveTurnStep(events) {
221
236
  * @returns {{synthetic: boolean, turn: number, step: number,
222
237
  * preamble?: Array, postamble?: Array}}
223
238
  */
239
+ /** 合成 turn 落盘后,把宿主 idle agent 的 turn 游标对齐到该 turn(否则下一条真实消息会重号)。 */
240
+ export function alignLiveTurnCursor(ctx, session, turn) {
241
+ if (!Number.isSafeInteger(turn) || turn < 1 || !session || typeof session.id !== "string") return false;
242
+ const agent = ctx && ctx.agents && typeof ctx.agents.get === "function" ? ctx.agents.get(session.id) : undefined;
243
+ if (!agent || agent.phase?.kind !== "idle" || typeof agent.setPhase !== "function") return false;
244
+ const lastTurn = Number.isSafeInteger(agent.phase.lastTurn) ? agent.phase.lastTurn : 0;
245
+ if (lastTurn >= turn) return false;
246
+ agent.setPhase({ kind: "idle", lastTurn: turn });
247
+ return true;
248
+ }
249
+
250
+ export function sessionLogOf(session) {
251
+ if (!session) return null;
252
+ if (Array.isArray(session.log)) return session.log;
253
+ if (Array.isArray(session.events)) return session.events;
254
+ if (typeof session.events === "function") {
255
+ try { const log = session.events(); return Array.isArray(log) ? log : null; } catch { return null; }
256
+ }
257
+ return null;
258
+ }
259
+
224
260
  export function planNoticeWindow(events) {
225
261
  let turn = null, step = null, maxTurn = 0;
226
262
  for (const e of events ?? []) {
@@ -236,6 +272,7 @@ export function planNoticeWindow(events) {
236
272
  }
237
273
  // 会话正开着 turn+step(例如上一轮被中断)→ 直接用现成窗口,不造合成 turn
238
274
  if (turn !== null && step !== null) return { synthetic: false, turn, step };
275
+ if (turn !== null) throw new OpsError("session is between steps; retry after the current turn settles", 409);
239
276
  const nextTurn = maxTurn + 1;
240
277
  return { synthetic: true, turn: nextTurn, step: 1 };
241
278
  }
@@ -258,25 +295,27 @@ export function noticeWindowPostamble(win) {
258
295
  // (dsh-session/lib/index.js:783-786)。UI 的 trajectory 装配器无防护地读
259
296
  // `match.event.data.reason.kind`(dsh-client-ui-trajectory/lib/client.js:997-998)
260
297
  // → 缺字段会让整个会话页白屏(ConversationNodeAssembler.replayContext 抛 TypeError)。
261
- // kind 选 "interrupted":语义上就是"非模型驱动的 turn"(引擎用它标记被打断的轮次)。
262
- { kind: "turn/end", data: { turn: win.turn, reason: { kind: "interrupted" } } },
298
+ // 用 "completed":这是成功的记账 turn;用 "interrupted" 会被聊天 UI 渲染成“已停止”。
299
+ { kind: "turn/end", data: { turn: win.turn, reason: { kind: "completed" } } },
263
300
  ];
264
301
  }
265
302
 
266
303
  export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs, noticeText, turnStep) {
267
304
  const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0
268
305
  ? turnStep : { turn: 1, step: 1 };
306
+ const sources = [...new Set((Array.isArray(sourceEventSeqs) ? sourceEventSeqs : []).flat(Infinity))];
307
+ if (!sources.every(Number.isSafeInteger)) throw new OpsError("surface replace sources must be integer seqs", 500);
269
308
  const data = { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", source: messageSource("system", 4), content: [{ type: "text", text: noticeText }] } };
270
309
  if (replaceShape) {
271
- return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs });
310
+ return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs: sources });
272
311
  }
273
312
  try {
274
- const event = session.append("system/message", data, { surfaceOp: replaceOpFor("legacy", startSeq, endSeq), sourceEventSeqs });
313
+ const event = session.append("system/message", data, { surfaceOp: replaceOpFor("legacy", startSeq, endSeq), sourceEventSeqs: sources });
275
314
  replaceShape = "legacy";
276
315
  return event;
277
316
  } catch (err) {
278
317
  if (!/invalid replace surfaceOp/.test(String(err && err.message))) throw err;
279
- const event = session.append("system/message", data, { surfaceOp: replaceOpFor("new", startSeq, endSeq), sourceEventSeqs });
318
+ const event = session.append("system/message", data, { surfaceOp: replaceOpFor("new", startSeq, endSeq), sourceEventSeqs: sources });
280
319
  replaceShape = "new";
281
320
  return event;
282
321
  }
@@ -318,6 +357,9 @@ export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
318
357
  type: e.type,
319
358
  role: e.type === "user/message" ? "user" : "assistant",
320
359
  text,
360
+ source: e.type === "assistant/message" && e.data && e.data.message
361
+ ? e.data.message.source
362
+ : undefined,
321
363
  });
322
364
  } else {
323
365
  skipped++; // tool/call 等不可安全重放的事件:跳过并在结果里计数
@@ -426,6 +468,71 @@ export function restoreProgress(events, markerSeq) {
426
468
  };
427
469
  }
428
470
 
471
+ export function buildRestoreIndex(events) {
472
+ const bySeq = new Map();
473
+ const noticesByMarker = new Map();
474
+ const candidates = [];
475
+ for (const e of events) {
476
+ if (!e || typeof e.seq !== "number") continue;
477
+ bySeq.set(e.seq, e);
478
+ if (e.type === "user/message" || e.type === "assistant/message") {
479
+ if ((messageText(e) || "").trim()) candidates.push(e.seq);
480
+ }
481
+ const markerSeq = e.data && e.data.restoresSeq;
482
+ if (Number.isSafeInteger(markerSeq)) {
483
+ const list = noticesByMarker.get(markerSeq);
484
+ if (list) list.push(e); else noticesByMarker.set(markerSeq, [e]);
485
+ }
486
+ }
487
+ return { bySeq, noticesByMarker, candidates };
488
+ }
489
+
490
+ export function restoreProgressFromIndex(index, markerSeq) {
491
+ const marker = index.bySeq.get(markerSeq);
492
+ if (!marker) return null;
493
+ const range = readReplaceOp(marker);
494
+ if (!range) return null;
495
+ const { startSeq, endSeq } = range;
496
+ const candidates = [];
497
+ for (const q of index.candidates) {
498
+ if (q >= startSeq && q <= endSeq) candidates.push(q);
499
+ }
500
+ const notices = index.noticesByMarker.get(markerSeq) || [];
501
+ const restored = new Set();
502
+ let legacy = false;
503
+ let discarded = false;
504
+ for (const n of notices) {
505
+ if (n.data.discarded === true) { discarded = true; continue; }
506
+ const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null;
507
+ if (!seqs) { legacy = true; continue; }
508
+ for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q);
509
+ }
510
+ const pending = candidates.filter((q) => !restored.has(q));
511
+ return {
512
+ startSeq,
513
+ endSeq,
514
+ restoredSeqs: Array.from(restored).sort((a, b) => a - b),
515
+ pendingSeqs: pending,
516
+ complete: legacy || discarded ? true : pending.length === 0,
517
+ legacy,
518
+ discarded,
519
+ };
520
+ }
521
+
522
+ export function pendingRestoreTurnsFromIndex(index, markerSeq, progress) {
523
+ if (!progress || progress.pendingSeqs.length === 0) return [];
524
+ const turns = [];
525
+ let current = null;
526
+ for (const q of progress.pendingSeqs) {
527
+ const e = index.bySeq.get(q);
528
+ if (!e) continue;
529
+ if (e.type === "user/message") { current = { turnSeq: q, seqs: [q] }; turns.push(current); }
530
+ else if (current) current.seqs.push(q);
531
+ else turns.push({ turnSeq: q, seqs: [q] });
532
+ }
533
+ return turns;
534
+ }
535
+
429
536
  /**
430
537
  * 0.8.0:贴条按行展示用 —— 列出该标记仍未重放的「轮」(一个 user 消息及其后
431
538
  * 到下一个 user 之前的 assistant 回复算一轮,对齐 opencode 按轮步进恢复)。
@@ -527,8 +634,8 @@ export function isJsonContentType(req) {
527
634
  // 同机无凭证进程 GET 即可整卷消息/全文(宿主同条件 401——审计缺口)。
528
635
  // 对齐修法(选型理由见报告):前端本来就带 cookie → 围栏里**校验同款
529
636
  // cookie**;secret 经 credentials 服务的合法读法取(no-op modifyRecord,
530
- // 勿写勿落盘);宿主无此服务 / 记录缺失或格式升级 → **降级回旧围栏语义**
531
- // 并告警(UI 永不因新校验而被 401,老版本宿主下行为不变)。
637
+ // 勿写勿落盘)。无 credentials 服务 = 老宿主 → 保留旧围栏;有服务但记录
638
+ // 缺失/格式升级 → **fail-closed** 并告警,避免永久 allow-all。
532
639
  // 非浏览器 GET(curl 等)从 200 变 401 = 与宿主对齐的有意行为变化。
533
640
 
534
641
  const AUTH_RECORD_KEY = "client-connection/browser-session";
@@ -625,7 +732,8 @@ export function browserAuthPayload(req, secret) {
625
732
  /**
626
733
  * 经 credentials 服务读宿主 BrowserAuth 签名 secret。**唯一读法**:
627
734
  * no-op modifyRecord(mutate 返回 undefined = 记录未动、返回 current),
628
- * 不落盘不经 argv。宿主无该成分 / 记录缺失 / 格式或长度不符 → null(降级)。
735
+ * 不落盘不经 argv。宿主无该成分 / 记录缺失 / 格式或长度不符 → null。
736
+ * 调用方据此决定老宿主降级还是 fail-closed(有 credentials 服务即后者)。
629
737
  * @param {object|undefined} credentials ctx.get("credentials")
630
738
  * @returns {Promise<Buffer|null>}
631
739
  */
@@ -651,6 +759,7 @@ export async function loadBrowserAuthSecret(credentials) {
651
759
  const WEB_AUTH_RETRY_MS = 10_000;
652
760
  let __webAuthSecret = null;
653
761
  let __webAuthProbeAt = 0;
762
+ let __webAuthProbe = null;
654
763
  let __webAuthWarned = false;
655
764
 
656
765
  /** 测试钩子:直接注入/清除 secret,绕开 credentials 服务。 */
@@ -658,13 +767,14 @@ export function _setWebAuthSecret(secret) { __webAuthSecret = secret; }
658
767
  export function _resetWebAuth() {
659
768
  __webAuthSecret = null;
660
769
  __webAuthProbeAt = 0;
770
+ __webAuthProbe = null;
661
771
  __webAuthWarned = false;
662
772
  }
663
773
 
664
774
  /**
665
- * 围栏的鉴权半段:取活跃 secret(含惰性探测与失败 memo)。
775
+ * 围栏的鉴权半段:取活跃 secret(含单飞探测与 10s 失败 memo)。
666
776
  * secret 存在但请求未携有效 cookie → false(路由层回 401);
667
- * secret 不可得(无 credentials / 记录缺失 / 老版本宿主)→ true = 降级回旧围栏。
777
+ * 无 credentials 服务(老宿主)→ true = 旧围栏;有服务但记录不可读 → false(fail-closed)。
668
778
  * @param {object|undefined} ctx 插件 ctx(get("credentials"))
669
779
  * @param {object} req http 请求
670
780
  */
@@ -672,19 +782,32 @@ export async function webAuthGate(ctx, req) {
672
782
  if (__webAuthSecret !== null) {
673
783
  return browserAuthPayload(req, __webAuthSecret) !== undefined;
674
784
  }
785
+
786
+ let credentials = null;
787
+ try { credentials = ctx && typeof ctx.get === "function" ? ctx.get("credentials") : null; } catch { /* legacy ctx */ }
788
+ if (!credentials || typeof credentials.modifyRecord !== "function") return true;
789
+
675
790
  const now = Date.now();
676
- if (now - __webAuthProbeAt < WEB_AUTH_RETRY_MS) return true; // 失败窗口内 = 降级
677
- __webAuthProbeAt = now;
678
- const credentials = ctx && typeof ctx.get === "function" ? ctx.get("credentials") : null;
679
- __webAuthSecret = await loadBrowserAuthSecret(credentials);
680
- if (__webAuthSecret === null && !__webAuthWarned) {
681
- __webAuthWarned = true;
682
- console.warn(
683
- "[message-ops] BrowserAuth cookie 鉴权未启用(`client-connection/browser-session` 记录不可读)"
684
- + "——GET 鉴权降级为旧的三层围栏语义;若这是 0.2.0+ 宿主,请检查该记录是否存在",
685
- );
791
+ if (__webAuthProbe === null && now - __webAuthProbeAt >= WEB_AUTH_RETRY_MS) {
792
+ __webAuthProbeAt = now;
793
+ __webAuthProbe = loadBrowserAuthSecret(credentials)
794
+ .then((secret) => {
795
+ __webAuthSecret = secret;
796
+ if (secret === null && !__webAuthWarned) {
797
+ __webAuthWarned = true;
798
+ console.warn(
799
+ "[message-ops] BrowserAuth cookie 鉴权已启用但 `client-connection/browser-session` 记录不可读"
800
+ + "——GET 鉴权 fail-closed;请检查该记录是否存在",
801
+ );
802
+ }
803
+ return secret;
804
+ })
805
+ .finally(() => { __webAuthProbe = null; });
686
806
  }
687
- return __webAuthSecret === null ? true : browserAuthPayload(req, __webAuthSecret) !== undefined;
807
+
808
+ if (__webAuthProbe === null) return false;
809
+ const secret = await __webAuthProbe;
810
+ return secret !== null && browserAuthPayload(req, secret) !== undefined;
688
811
  }
689
812
 
690
813
 
@@ -765,6 +888,8 @@ export function nextSeqFrom(events) {
765
888
 
766
889
  /** 磁盘回撤/删除标记事件(字段镜像引擎金标准:type/seq/time/data/sourceEventSeqs/surfaceOp)。 */
767
890
  export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs, version = 4 }) {
891
+ const sources = [...new Set((Array.isArray(shadowedSeqs) ? shadowedSeqs : []).flat(Infinity))];
892
+ if (!sources.every(Number.isSafeInteger)) throw new OpsError("surface replace sources must be integer seqs", 500);
768
893
  return {
769
894
  type: "system/message",
770
895
  seq,
@@ -774,7 +899,7 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
774
899
  step: turnStep.step,
775
900
  message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
776
901
  },
777
- sourceEventSeqs: [...shadowedSeqs],
902
+ sourceEventSeqs: sources,
778
903
  surfaceOp: { op: "replace", startSeq, endSeq },
779
904
  };
780
905
  }