@240xu/dsh-message-ops 0.11.1 → 0.11.3

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/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,63 @@ 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
 
303
+ /**
304
+ * 展开 `sourceEventSeqs` 的存储形态为宿主内存态整数序列。
305
+ *
306
+ * ⚠️ 宿主把**连续 ≥3 个** seq 无损压缩成 `[start, end]` 闭区间对
307
+ * (dsh-session/lib/index.js `encodeSeqRanges`,读盘 `decodeSeqRanges` 再展开)。
308
+ * 因此 `[[780, 782]]` 表示 **780、781、782 三个**节点,不是「两个端点」。
309
+ * 早期版本用 `flat(Infinity)` 处理 —— 会把 `[3, 6]` 变成 `3, 6`,
310
+ * 丢掉区间内的 4、5,写出的 marker 被引擎判 `sourceEventSeqs must include
311
+ * every shadowed surface node; missing 4, 5` 而 500/409。
312
+ *
313
+ * @param {unknown} value 存储形态(整数与/或 `[start, end]` 闭区间)
314
+ * @returns {number[]} 去重后保持首次出现顺序的整数序列
315
+ */
316
+ export function expandSourceSeqs(value) {
317
+ const out = [];
318
+ const seen = new Set();
319
+ const push = (seq) => {
320
+ if (!Number.isSafeInteger(seq)) throw new OpsError("surface replace sources must be integer seqs", 500);
321
+ if (seen.has(seq)) return;
322
+ seen.add(seq);
323
+ out.push(seq);
324
+ };
325
+ for (const entry of Array.isArray(value) ? value : []) {
326
+ if (Array.isArray(entry)) {
327
+ if (entry.length !== 2) throw new OpsError("surface replace source ranges must be [start, end] pairs", 500);
328
+ const [start, end] = entry;
329
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end < start) {
330
+ throw new OpsError("surface replace source ranges require integer start <= end", 500);
331
+ }
332
+ for (let seq = start; seq <= end; seq += 1) push(seq);
333
+ } else {
334
+ push(entry);
335
+ }
336
+ }
337
+ return out;
338
+ }
339
+
266
340
  export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs, noticeText, turnStep) {
267
341
  const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0
268
342
  ? turnStep : { turn: 1, step: 1 };
343
+ const sources = expandSourceSeqs(sourceEventSeqs);
269
344
  const data = { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", source: messageSource("system", 4), content: [{ type: "text", text: noticeText }] } };
270
345
  if (replaceShape) {
271
- return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs });
346
+ return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs: sources });
272
347
  }
273
348
  try {
274
- const event = session.append("system/message", data, { surfaceOp: replaceOpFor("legacy", startSeq, endSeq), sourceEventSeqs });
349
+ const event = session.append("system/message", data, { surfaceOp: replaceOpFor("legacy", startSeq, endSeq), sourceEventSeqs: sources });
275
350
  replaceShape = "legacy";
276
351
  return event;
277
352
  } catch (err) {
278
353
  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 });
354
+ const event = session.append("system/message", data, { surfaceOp: replaceOpFor("new", startSeq, endSeq), sourceEventSeqs: sources });
280
355
  replaceShape = "new";
281
356
  return event;
282
357
  }
@@ -318,6 +393,9 @@ export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
318
393
  type: e.type,
319
394
  role: e.type === "user/message" ? "user" : "assistant",
320
395
  text,
396
+ source: e.type === "assistant/message" && e.data && e.data.message
397
+ ? e.data.message.source
398
+ : undefined,
321
399
  });
322
400
  } else {
323
401
  skipped++; // tool/call 等不可安全重放的事件:跳过并在结果里计数
@@ -426,6 +504,71 @@ export function restoreProgress(events, markerSeq) {
426
504
  };
427
505
  }
428
506
 
507
+ export function buildRestoreIndex(events) {
508
+ const bySeq = new Map();
509
+ const noticesByMarker = new Map();
510
+ const candidates = [];
511
+ for (const e of events) {
512
+ if (!e || typeof e.seq !== "number") continue;
513
+ bySeq.set(e.seq, e);
514
+ if (e.type === "user/message" || e.type === "assistant/message") {
515
+ if ((messageText(e) || "").trim()) candidates.push(e.seq);
516
+ }
517
+ const markerSeq = e.data && e.data.restoresSeq;
518
+ if (Number.isSafeInteger(markerSeq)) {
519
+ const list = noticesByMarker.get(markerSeq);
520
+ if (list) list.push(e); else noticesByMarker.set(markerSeq, [e]);
521
+ }
522
+ }
523
+ return { bySeq, noticesByMarker, candidates };
524
+ }
525
+
526
+ export function restoreProgressFromIndex(index, markerSeq) {
527
+ const marker = index.bySeq.get(markerSeq);
528
+ if (!marker) return null;
529
+ const range = readReplaceOp(marker);
530
+ if (!range) return null;
531
+ const { startSeq, endSeq } = range;
532
+ const candidates = [];
533
+ for (const q of index.candidates) {
534
+ if (q >= startSeq && q <= endSeq) candidates.push(q);
535
+ }
536
+ const notices = index.noticesByMarker.get(markerSeq) || [];
537
+ const restored = new Set();
538
+ let legacy = false;
539
+ let discarded = false;
540
+ for (const n of notices) {
541
+ if (n.data.discarded === true) { discarded = true; continue; }
542
+ const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null;
543
+ if (!seqs) { legacy = true; continue; }
544
+ for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q);
545
+ }
546
+ const pending = candidates.filter((q) => !restored.has(q));
547
+ return {
548
+ startSeq,
549
+ endSeq,
550
+ restoredSeqs: Array.from(restored).sort((a, b) => a - b),
551
+ pendingSeqs: pending,
552
+ complete: legacy || discarded ? true : pending.length === 0,
553
+ legacy,
554
+ discarded,
555
+ };
556
+ }
557
+
558
+ export function pendingRestoreTurnsFromIndex(index, markerSeq, progress) {
559
+ if (!progress || progress.pendingSeqs.length === 0) return [];
560
+ const turns = [];
561
+ let current = null;
562
+ for (const q of progress.pendingSeqs) {
563
+ const e = index.bySeq.get(q);
564
+ if (!e) continue;
565
+ if (e.type === "user/message") { current = { turnSeq: q, seqs: [q] }; turns.push(current); }
566
+ else if (current) current.seqs.push(q);
567
+ else turns.push({ turnSeq: q, seqs: [q] });
568
+ }
569
+ return turns;
570
+ }
571
+
429
572
  /**
430
573
  * 0.8.0:贴条按行展示用 —— 列出该标记仍未重放的「轮」(一个 user 消息及其后
431
574
  * 到下一个 user 之前的 assistant 回复算一轮,对齐 opencode 按轮步进恢复)。
@@ -527,8 +670,8 @@ export function isJsonContentType(req) {
527
670
  // 同机无凭证进程 GET 即可整卷消息/全文(宿主同条件 401——审计缺口)。
528
671
  // 对齐修法(选型理由见报告):前端本来就带 cookie → 围栏里**校验同款
529
672
  // cookie**;secret 经 credentials 服务的合法读法取(no-op modifyRecord,
530
- // 勿写勿落盘);宿主无此服务 / 记录缺失或格式升级 → **降级回旧围栏语义**
531
- // 并告警(UI 永不因新校验而被 401,老版本宿主下行为不变)。
673
+ // 勿写勿落盘)。无 credentials 服务 = 老宿主 → 保留旧围栏;有服务但记录
674
+ // 缺失/格式升级 → **fail-closed** 并告警,避免永久 allow-all。
532
675
  // 非浏览器 GET(curl 等)从 200 变 401 = 与宿主对齐的有意行为变化。
533
676
 
534
677
  const AUTH_RECORD_KEY = "client-connection/browser-session";
@@ -625,7 +768,8 @@ export function browserAuthPayload(req, secret) {
625
768
  /**
626
769
  * 经 credentials 服务读宿主 BrowserAuth 签名 secret。**唯一读法**:
627
770
  * no-op modifyRecord(mutate 返回 undefined = 记录未动、返回 current),
628
- * 不落盘不经 argv。宿主无该成分 / 记录缺失 / 格式或长度不符 → null(降级)。
771
+ * 不落盘不经 argv。宿主无该成分 / 记录缺失 / 格式或长度不符 → null。
772
+ * 调用方据此决定老宿主降级还是 fail-closed(有 credentials 服务即后者)。
629
773
  * @param {object|undefined} credentials ctx.get("credentials")
630
774
  * @returns {Promise<Buffer|null>}
631
775
  */
@@ -651,6 +795,7 @@ export async function loadBrowserAuthSecret(credentials) {
651
795
  const WEB_AUTH_RETRY_MS = 10_000;
652
796
  let __webAuthSecret = null;
653
797
  let __webAuthProbeAt = 0;
798
+ let __webAuthProbe = null;
654
799
  let __webAuthWarned = false;
655
800
 
656
801
  /** 测试钩子:直接注入/清除 secret,绕开 credentials 服务。 */
@@ -658,13 +803,14 @@ export function _setWebAuthSecret(secret) { __webAuthSecret = secret; }
658
803
  export function _resetWebAuth() {
659
804
  __webAuthSecret = null;
660
805
  __webAuthProbeAt = 0;
806
+ __webAuthProbe = null;
661
807
  __webAuthWarned = false;
662
808
  }
663
809
 
664
810
  /**
665
- * 围栏的鉴权半段:取活跃 secret(含惰性探测与失败 memo)。
811
+ * 围栏的鉴权半段:取活跃 secret(含单飞探测与 10s 失败 memo)。
666
812
  * secret 存在但请求未携有效 cookie → false(路由层回 401);
667
- * secret 不可得(无 credentials / 记录缺失 / 老版本宿主)→ true = 降级回旧围栏。
813
+ * 无 credentials 服务(老宿主)→ true = 旧围栏;有服务但记录不可读 → false(fail-closed)。
668
814
  * @param {object|undefined} ctx 插件 ctx(get("credentials"))
669
815
  * @param {object} req http 请求
670
816
  */
@@ -672,19 +818,32 @@ export async function webAuthGate(ctx, req) {
672
818
  if (__webAuthSecret !== null) {
673
819
  return browserAuthPayload(req, __webAuthSecret) !== undefined;
674
820
  }
821
+
822
+ let credentials = null;
823
+ try { credentials = ctx && typeof ctx.get === "function" ? ctx.get("credentials") : null; } catch { /* legacy ctx */ }
824
+ if (!credentials || typeof credentials.modifyRecord !== "function") return true;
825
+
675
826
  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
- );
827
+ if (__webAuthProbe === null && now - __webAuthProbeAt >= WEB_AUTH_RETRY_MS) {
828
+ __webAuthProbeAt = now;
829
+ __webAuthProbe = loadBrowserAuthSecret(credentials)
830
+ .then((secret) => {
831
+ __webAuthSecret = secret;
832
+ if (secret === null && !__webAuthWarned) {
833
+ __webAuthWarned = true;
834
+ console.warn(
835
+ "[message-ops] BrowserAuth cookie 鉴权已启用但 `client-connection/browser-session` 记录不可读"
836
+ + "——GET 鉴权 fail-closed;请检查该记录是否存在",
837
+ );
838
+ }
839
+ return secret;
840
+ })
841
+ .finally(() => { __webAuthProbe = null; });
686
842
  }
687
- return __webAuthSecret === null ? true : browserAuthPayload(req, __webAuthSecret) !== undefined;
843
+
844
+ if (__webAuthProbe === null) return false;
845
+ const secret = await __webAuthProbe;
846
+ return secret !== null && browserAuthPayload(req, secret) !== undefined;
688
847
  }
689
848
 
690
849
 
@@ -765,6 +924,7 @@ export function nextSeqFrom(events) {
765
924
 
766
925
  /** 磁盘回撤/删除标记事件(字段镜像引擎金标准:type/seq/time/data/sourceEventSeqs/surfaceOp)。 */
767
926
  export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs, version = 4 }) {
927
+ const sources = expandSourceSeqs(shadowedSeqs);
768
928
  return {
769
929
  type: "system/message",
770
930
  seq,
@@ -774,7 +934,7 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
774
934
  step: turnStep.step,
775
935
  message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
776
936
  },
777
- sourceEventSeqs: [...shadowedSeqs],
937
+ sourceEventSeqs: sources,
778
938
  surfaceOp: { op: "replace", startSeq, endSeq },
779
939
  };
780
940
  }
@@ -17,8 +17,6 @@ import os from "node:os";
17
17
  import { constants, zstdCompressSync, zstdDecompressSync } from "node:zlib";
18
18
 
19
19
  const ZSTD_MAGIC = 0xfd2fb528;
20
- /** 魔数的字节形态(Buffer.indexOf 用;小端 0xfd2fb528 → 28 b5 2f fd)。 */
21
- const ZSTD_MAGIC_BYTES = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
22
20
 
23
21
  /** 带语义状态码的操作错误(单点:HTTP 直接映射 status,工具端转失败文本)。 */
24
22
  export class OpsError extends Error {
@@ -67,14 +65,52 @@ function compressFrame(input) {
67
65
  });
68
66
  }
69
67
 
68
+ /**
69
+ * 按 RFC 8878 计算一个 zstd 帧的精确结束偏移。
70
+ * 魔数可能出现在压缩载荷内,因此不能用 Buffer.indexOf 定帧界。
71
+ * @returns {{end:number}|{error:'truncated'|'malformed'}}
72
+ */
73
+ function zstdFrameEnd(buf, start) {
74
+ if (start + 4 > buf.length || buf.readUInt32LE(start) !== ZSTD_MAGIC) return { error: "malformed" };
75
+ let p = start + 4;
76
+ if (p >= buf.length) return { error: "truncated" };
77
+ const fhd = buf[p++];
78
+ if ((fhd & 0x18) !== 0) return { error: "malformed" };
79
+ const fcsFlag = fhd >> 6;
80
+ const singleSegment = (fhd >> 5) & 1;
81
+ const checksum = (fhd >> 2) & 1;
82
+ const dictFlag = fhd & 3;
83
+ if (!singleSegment) {
84
+ if (p >= buf.length) return { error: "truncated" };
85
+ p += 1;
86
+ }
87
+ const dictSize = [0, 1, 2, 4][dictFlag];
88
+ const fcsSize = fcsFlag === 0 ? (singleSegment ? 1 : 0) : [0, 2, 4, 8][fcsFlag];
89
+ p += dictSize + fcsSize;
90
+ if (p > buf.length) return { error: "truncated" };
91
+ for (;;) {
92
+ if (p + 3 > buf.length) return { error: "truncated" };
93
+ const bh = buf[p] | (buf[p + 1] << 8) | (buf[p + 2] << 16);
94
+ p += 3;
95
+ const last = bh & 1;
96
+ const type = (bh >> 1) & 3;
97
+ const size = bh >>> 3;
98
+ if (type === 3) return { error: "malformed" };
99
+ const payload = type === 1 ? 1 : size;
100
+ if (p + payload > buf.length) return { error: "truncated" };
101
+ p += payload;
102
+ if (last) break;
103
+ }
104
+ if (checksum) {
105
+ if (p + 4 > buf.length) return { error: "truncated" };
106
+ p += 4;
107
+ }
108
+ return { end: p };
109
+ }
110
+
70
111
  /**
71
112
  * 扫描串联 zstd 流的完整帧边界(不解压块)。
72
- *
73
- * 找「下一个魔数」用 Buffer.indexOf(原生 memchr 实现)而不是逐字节
74
- * readUInt32LE 循环 —— 10.8MB 日志的逐字节扫描实测 44~73ms 且全程同步
75
- * 阻塞事件循环(单次卡顿 146ms 的主要来源);indexOf 同样从 offset+4
76
- * 起找、同样要求 4 字节完整落在缓冲区内,语义与原循环**逐位等价**
77
- * (命中区间 [offset+4, buf.length-4],找不到则 end=buf.length)。
113
+ * 帧界按结构计算,任何非帧字节或畸形帧都 fail-closed。
78
114
  * @returns {{frames: {start:number,end:number}[], tornStart?: number}}
79
115
  */
80
116
  export function scanZstdFrames(buf) {
@@ -86,11 +122,16 @@ export function scanZstdFrames(buf) {
86
122
  if (buf.readUInt32LE(offset) !== ZSTD_MAGIC) {
87
123
  throw new Error(`corrupt zstd session log: invalid frame magic at byte ${offset}`);
88
124
  }
89
- let end = buf.length;
90
- const found = buf.indexOf(ZSTD_MAGIC_BYTES, offset + 4);
91
- if (found !== -1) end = found;
92
- frames.push({ start, end });
93
- offset = end;
125
+ const parsed = zstdFrameEnd(buf, offset);
126
+ if (parsed.error === "truncated") {
127
+ frames.push({ start, end: buf.length });
128
+ return { frames, tornStart: start };
129
+ }
130
+ if (parsed.error) {
131
+ throw new Error(`corrupt zstd session log: malformed frame at byte ${offset}`);
132
+ }
133
+ frames.push({ start, end: parsed.end });
134
+ offset = parsed.end;
94
135
  }
95
136
  return { frames };
96
137
  }
@@ -135,6 +176,25 @@ export function readSessionFile(file) {
135
176
  return { header, events };
136
177
  }
137
178
 
179
+ /** Read only the first zstd frame (header); a damaged body cannot block titles. */
180
+ export function readSessionHeader(file) {
181
+ const buf = fs.readFileSync(file);
182
+ if (buf.length < 4 || buf.readUInt32LE(0) !== ZSTD_MAGIC) {
183
+ throw new Error(`session log ${file}: no zstd header frame`);
184
+ }
185
+ const parsed = zstdFrameEnd(buf, 0);
186
+ if (parsed.error) throw new Error(`session log ${file}: ${parsed.error} header frame`);
187
+ const text = zstdDecompressSync(buf.subarray(0, parsed.end)).toString("utf8");
188
+ for (const line of text.split("\n")) {
189
+ const t = line.trim();
190
+ if (!t) continue;
191
+ let json;
192
+ try { json = JSON.parse(t); } catch { continue; }
193
+ if (json && typeof json === "object" && json.type === "session") return json;
194
+ }
195
+ throw new Error(`session log ${file}: no {type:"session"} header line in the first frame`);
196
+ }
197
+
138
198
  /** 物化整份日志:header 帧(恰一行)+ 单一事件帧(全部事件行)。 */
139
199
  export function encodeSessionFile(header, events) {
140
200
  const headerText = JSON.stringify(header) + "\n";
@@ -224,6 +284,11 @@ export function turnBounds(events) {
224
284
  }
225
285
 
226
286
  export function listMessages(events) {
287
+ const syntheticTurns = new Set();
288
+ for (const e of events) {
289
+ if (e && e.type === "turn/start" && e.data && e.data.reason === "message-ops"
290
+ && Number.isSafeInteger(e.data.turn)) syntheticTurns.add(e.data.turn);
291
+ }
227
292
  const messages = [];
228
293
  for (const e of events) {
229
294
  if (!e || typeof e.seq !== "number") continue;
@@ -252,6 +317,7 @@ export function listMessages(events) {
252
317
  ? e.data.restoresSeq : null,
253
318
  time: e.time ?? null,
254
319
  turn: (e.data && e.data.turn) ?? null,
320
+ syntheticTurn: syntheticTurns.has(e.data && e.data.turn) || undefined,
255
321
  // 0.9.1:assistant 节点的宿主 node-key 是 `14:assistant-step<turn>:<step>`,
256
322
  // 没有 step 就无法把渲染行映射回日志 seq → 回滚时助手回答藏不掉。
257
323
  step: (e.data && e.data.step) ?? null,