@240xu/dsh-message-ops 0.12.0 → 0.13.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.
@@ -11,37 +11,37 @@
11
11
  * @module dsh-message-ops/session-file
12
12
  */
13
13
 
14
- import fs from "node:fs";
15
- import path from "node:path";
16
- import os from "node:os";
17
- import { constants, zstdCompressSync, zstdDecompressSync } from "node:zlib";
14
+ import fs from 'node:fs'
15
+ import path from 'node:path'
16
+ import os from 'node:os'
17
+ import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib'
18
18
 
19
- const ZSTD_MAGIC = 0xfd2fb528;
19
+ const ZSTD_MAGIC = 0xfd2fb528
20
20
 
21
21
  /** 带语义状态码的操作错误(单点:HTTP 直接映射 status,工具端转失败文本)。 */
22
22
  export class OpsError extends Error {
23
23
  constructor(message, status = 400) {
24
- super(message);
25
- this.status = status;
24
+ super(message)
25
+ this.status = status
26
26
  }
27
27
  }
28
28
 
29
29
  /** messageText 的「合格 text 段」选择口径(单点):type==='text' 且非空白。 */
30
30
  function textSegments(e) {
31
- const msg = e && e.data && e.data.message;
32
- const content = msg && Array.isArray(msg.content) ? msg.content : (e && e.data && e.data.content);
33
- if (!Array.isArray(content)) return [];
34
- const out = [];
31
+ const msg = e && e.data && e.data.message
32
+ const content = msg && Array.isArray(msg.content) ? msg.content : e && e.data && e.data.content
33
+ if (!Array.isArray(content)) return []
34
+ const out = []
35
35
  for (const c of content) {
36
- if (c && c.type === "text" && typeof c.text === "string" && c.text.trim()) out.push(c.text);
36
+ if (c && c.type === 'text' && typeof c.text === 'string' && c.text.trim()) out.push(c.text)
37
37
  }
38
- return out;
38
+ return out
39
39
  }
40
40
 
41
41
  /** 从 message 事件提取首个非空 text 块(listMessages / ops-core 共用单点)。 */
42
42
  export function messageText(e) {
43
- const segs = textSegments(e);
44
- return segs.length ? segs[0] : "";
43
+ const segs = textSegments(e)
44
+ return segs.length ? segs[0] : ''
45
45
  }
46
46
 
47
47
  /**
@@ -54,15 +54,15 @@ export function messageText(e) {
54
54
  * "\\n\\n" 恰好还原段落边界,也不会把「。」「#」硬粘成一行)。
55
55
  */
56
56
  export function messageTextFull(e) {
57
- const segs = textSegments(e);
58
- return segs.join("\n\n");
57
+ const segs = textSegments(e)
58
+ return segs.join('\n\n')
59
59
  }
60
60
 
61
61
  /** 与 DSH 宿主一致:帧带 checksum(ZSTD_c_checksumFlag=1)。 */
62
62
  function compressFrame(input) {
63
- return zstdCompressSync(Buffer.from(input, "utf8"), {
63
+ return zstdCompressSync(Buffer.from(input, 'utf8'), {
64
64
  params: { [constants.ZSTD_c_checksumFlag]: 1 },
65
- });
65
+ })
66
66
  }
67
67
 
68
68
  /**
@@ -71,41 +71,41 @@ function compressFrame(input) {
71
71
  * @returns {{end:number}|{error:'truncated'|'malformed'}}
72
72
  */
73
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;
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
83
  if (!singleSegment) {
84
- if (p >= buf.length) return { error: "truncated" };
85
- p += 1;
84
+ if (p >= buf.length) return { error: 'truncated' }
85
+ p += 1
86
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" };
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
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;
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
103
  }
104
104
  if (checksum) {
105
- if (p + 4 > buf.length) return { error: "truncated" };
106
- p += 4;
105
+ if (p + 4 > buf.length) return { error: 'truncated' }
106
+ p += 4
107
107
  }
108
- return { end: p };
108
+ return { end: p }
109
109
  }
110
110
 
111
111
  /**
@@ -114,26 +114,26 @@ function zstdFrameEnd(buf, start) {
114
114
  * @returns {{frames: {start:number,end:number}[], tornStart?: number}}
115
115
  */
116
116
  export function scanZstdFrames(buf) {
117
- const frames = [];
118
- let offset = 0;
117
+ const frames = []
118
+ let offset = 0
119
119
  while (offset < buf.length) {
120
- const start = offset;
121
- if (buf.length - offset < 4) return { frames, tornStart: start };
120
+ const start = offset
121
+ if (buf.length - offset < 4) return { frames, tornStart: start }
122
122
  if (buf.readUInt32LE(offset) !== ZSTD_MAGIC) {
123
- throw new Error(`corrupt zstd session log: invalid frame magic at byte ${offset}`);
123
+ throw new Error(`corrupt zstd session log: invalid frame magic at byte ${offset}`)
124
124
  }
125
- const parsed = zstdFrameEnd(buf, offset);
126
- if (parsed.error === "truncated") {
127
- frames.push({ start, end: buf.length });
128
- return { frames, tornStart: start };
125
+ const parsed = zstdFrameEnd(buf, offset)
126
+ if (parsed.error === 'truncated') {
127
+ frames.push({ start, end: buf.length })
128
+ return { frames, tornStart: start }
129
129
  }
130
130
  if (parsed.error) {
131
- throw new Error(`corrupt zstd session log: malformed frame at byte ${offset}`);
131
+ throw new Error(`corrupt zstd session log: malformed frame at byte ${offset}`)
132
132
  }
133
- frames.push({ start, end: parsed.end });
134
- offset = parsed.end;
133
+ frames.push({ start, end: parsed.end })
134
+ offset = parsed.end
135
135
  }
136
- return { frames };
136
+ return { frames }
137
137
  }
138
138
 
139
139
  /**
@@ -145,16 +145,23 @@ export function scanZstdFrames(buf) {
145
145
  * 撕裂行(JSON.parse 失败)按宿主「完整前缀」语义跳过。
146
146
  */
147
147
  function collectHeaderAndEvents(text, events) {
148
- let header = null;
149
- for (const line of text.split("\n")) {
150
- const t = line.trim();
151
- if (!t) continue;
152
- let json;
153
- try { json = JSON.parse(t); } catch { continue; /* torn record: skip */ }
154
- if (!header && json && typeof json === "object" && json.type === "session") { header = json; continue; }
155
- events.push(json);
148
+ let header = null
149
+ for (const line of text.split('\n')) {
150
+ const t = line.trim()
151
+ if (!t) continue
152
+ let json
153
+ try {
154
+ json = JSON.parse(t)
155
+ } catch {
156
+ continue /* torn record: skip */
157
+ }
158
+ if (!header && json && typeof json === 'object' && json.type === 'session') {
159
+ header = json
160
+ continue
161
+ }
162
+ events.push(json)
156
163
  }
157
- return header;
164
+ return header
158
165
  }
159
166
 
160
167
  /**
@@ -162,64 +169,68 @@ function collectHeaderAndEvents(text, events) {
162
169
  * 逐行扫描路径,见 collectHeaderAndEvents。
163
170
  */
164
171
  export function readSessionFile(file) {
165
- const buf = fs.readFileSync(file);
166
- const { frames } = scanZstdFrames(buf);
167
- if (frames.length === 0) throw new Error("empty or header-less session log");
168
- const events = [];
169
- let header = null;
172
+ const buf = fs.readFileSync(file)
173
+ const { frames } = scanZstdFrames(buf)
174
+ if (frames.length === 0) throw new Error('empty or header-less session log')
175
+ const events = []
176
+ let header = null
170
177
  for (const f of frames) {
171
- const text = zstdDecompressSync(buf.subarray(f.start, f.end)).toString("utf8");
172
- const found = collectHeaderAndEvents(text, events);
173
- if (!header) header = found;
178
+ const text = zstdDecompressSync(buf.subarray(f.start, f.end)).toString('utf8')
179
+ const found = collectHeaderAndEvents(text, events)
180
+ if (!header) header = found
174
181
  }
175
- if (!header) throw new Error(`session log ${file}: no {type:"session"} header line in any frame`);
176
- return { header, events };
182
+ if (!header) throw new Error(`session log ${file}: no {type:"session"} header line in any frame`)
183
+ return { header, events }
177
184
  }
178
185
 
179
186
  /** Read only the first zstd frame (header); a damaged body cannot block titles. */
180
187
  export function readSessionHeader(file) {
181
- const buf = fs.readFileSync(file);
188
+ const buf = fs.readFileSync(file)
182
189
  if (buf.length < 4 || buf.readUInt32LE(0) !== ZSTD_MAGIC) {
183
- throw new Error(`session log ${file}: no zstd header frame`);
190
+ throw new Error(`session log ${file}: no zstd header frame`)
184
191
  }
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;
192
+ const parsed = zstdFrameEnd(buf, 0)
193
+ if (parsed.error) throw new Error(`session log ${file}: ${parsed.error} header frame`)
194
+ const text = zstdDecompressSync(buf.subarray(0, parsed.end)).toString('utf8')
195
+ for (const line of text.split('\n')) {
196
+ const t = line.trim()
197
+ if (!t) continue
198
+ let json
199
+ try {
200
+ json = JSON.parse(t)
201
+ } catch {
202
+ continue
203
+ }
204
+ if (json && typeof json === 'object' && json.type === 'session') return json
194
205
  }
195
- throw new Error(`session log ${file}: no {type:"session"} header line in the first frame`);
206
+ throw new Error(`session log ${file}: no {type:"session"} header line in the first frame`)
196
207
  }
197
208
 
198
209
  /** 物化整份日志:header 帧(恰一行)+ 单一事件帧(全部事件行)。 */
199
210
  export function encodeSessionFile(header, events) {
200
- const headerText = JSON.stringify(header) + "\n";
201
- const bodyText = events.map((e) => JSON.stringify(e)).join("\n") + "\n";
202
- return Buffer.concat([compressFrame(headerText), compressFrame(bodyText)]);
211
+ const headerText = JSON.stringify(header) + '\n'
212
+ const bodyText = events.map(e => JSON.stringify(e)).join('\n') + '\n'
213
+ return Buffer.concat([compressFrame(headerText), compressFrame(bodyText)])
203
214
  }
204
215
 
205
216
  /** 会话根目录(尊重 DSH_HOME;Windows/Termux 通吃)。 */
206
217
  export function sessionsRoot() {
207
- const home = process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
208
- return path.join(home, "sessions");
218
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
219
+ return path.join(home, 'sessions')
209
220
  }
210
221
 
211
- const SESSION_ID_RE = /^(session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
222
+ const SESSION_ID_RE = /^(session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
212
223
 
213
224
  export function isSessionId(v) {
214
- return typeof v === "string" && SESSION_ID_RE.test(v);
225
+ return typeof v === 'string' && SESSION_ID_RE.test(v)
215
226
  }
216
227
 
217
228
  /** 会话 id 的两种拼写(带/不带 session- 前缀)。 */
218
229
  export function sessionIdVariants(sessionId) {
219
- const variants = new Set([sessionId]);
220
- if (sessionId.startsWith("session-")) variants.add(sessionId.slice("session-".length));
221
- else variants.add(`session-${sessionId}`);
222
- return [...variants];
230
+ const variants = new Set([sessionId])
231
+ if (sessionId.startsWith('session-')) variants.add(sessionId.slice('session-'.length))
232
+ else variants.add(`session-${sessionId}`)
233
+ return [...variants]
223
234
  }
224
235
 
225
236
  /**
@@ -228,35 +239,47 @@ export function sessionIdVariants(sessionId) {
228
239
  * @returns {{dir: string, logPath: string}[]}
229
240
  */
230
241
  export function findSessionDirs(sessionId) {
231
- const root = sessionsRoot();
232
- let slugs = [];
233
- try { slugs = fs.readdirSync(root, { withFileTypes: true }); } catch { return []; }
234
- const variants = sessionIdVariants(sessionId);
235
- const found = [];
242
+ const root = sessionsRoot()
243
+ let slugs = []
244
+ try {
245
+ slugs = fs.readdirSync(root, { withFileTypes: true })
246
+ } catch {
247
+ return []
248
+ }
249
+ const variants = sessionIdVariants(sessionId)
250
+ const found = []
236
251
  for (const slug of slugs) {
237
- if (!slug.isDirectory()) continue;
252
+ if (!slug.isDirectory()) continue
238
253
  for (const variant of variants) {
239
- const dir = path.join(root, slug.name, variant);
254
+ const dir = path.join(root, slug.name, variant)
240
255
  try {
241
- if (!fs.statSync(dir).isDirectory()) continue;
242
- } catch { continue; }
256
+ if (!fs.statSync(dir).isDirectory()) continue
257
+ } catch {
258
+ continue
259
+ }
243
260
  // 探测序列(用户实测 DSH 已升级 v4 格式):v4 → v3 → 旧单帧,
244
261
  // 高版本优先;文件名与 header.version 对应,读取逻辑三格式同构。
245
- let logPath = null;
246
- for (const name of ["session.v4.jsonl.zstd", "session.v3.jsonl.zstd", "session.jsonl.zstd"]) {
247
- const candidate = path.join(dir, name);
248
- try { fs.statSync(candidate); logPath = candidate; break; } catch { /* probe next */ }
262
+ let logPath = null
263
+ for (const name of ['session.v4.jsonl.zstd', 'session.v3.jsonl.zstd', 'session.jsonl.zstd']) {
264
+ const candidate = path.join(dir, name)
265
+ try {
266
+ fs.statSync(candidate)
267
+ logPath = candidate
268
+ break
269
+ } catch {
270
+ /* probe next */
271
+ }
249
272
  }
250
- if (!logPath) continue;
251
- if (!found.some((f) => f.dir === dir)) found.push({ dir, logPath });
273
+ if (!logPath) continue
274
+ if (!found.some(f => f.dir === dir)) found.push({ dir, logPath })
252
275
  }
253
276
  }
254
- return found;
277
+ return found
255
278
  }
256
279
 
257
280
  /** 新建会话 id(与宿主同款 session-<uuid> 拼写)。 */
258
281
  export function newSessionId() {
259
- return `session-${crypto.randomUUID()}`;
282
+ return `session-${crypto.randomUUID()}`
260
283
  }
261
284
 
262
285
  /** 从事件流提取消息级列表(user/assistant/system message + tool/call 摘要)。 */
@@ -271,69 +294,75 @@ export function newSessionId() {
271
294
  * @returns {{starts: Map<number, number>, ends: Map<number, number>}}
272
295
  */
273
296
  export function turnBounds(events) {
274
- const starts = new Map();
275
- const ends = new Map();
297
+ const starts = new Map()
298
+ const ends = new Map()
276
299
  for (const e of events) {
277
- if (!e || typeof e.seq !== "number") continue;
278
- const t = e.data && e.data.turn;
279
- if (!Number.isSafeInteger(t)) continue;
280
- if (e.type === "turn/start") starts.set(t, e.seq);
281
- else if (e.type === "turn/end") ends.set(t, e.seq);
300
+ if (!e || typeof e.seq !== 'number') continue
301
+ const t = e.data && e.data.turn
302
+ if (!Number.isSafeInteger(t)) continue
303
+ if (e.type === 'turn/start') starts.set(t, e.seq)
304
+ else if (e.type === 'turn/end') ends.set(t, e.seq)
282
305
  }
283
- return { starts, ends };
306
+ return { starts, ends }
284
307
  }
285
308
 
286
309
  export function listMessages(events) {
287
- const syntheticTurns = new Set();
310
+ const syntheticTurns = new Set()
288
311
  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);
312
+ if (e && e.type === 'turn/start' && e.data && e.data.reason === 'message-ops' && Number.isSafeInteger(e.data.turn))
313
+ syntheticTurns.add(e.data.turn)
291
314
  }
292
- const messages = [];
315
+ const messages = []
293
316
  for (const e of events) {
294
- if (!e || typeof e.seq !== "number") continue;
295
- if (e.type === "user/message" || e.type === "assistant/message" || e.type === "system/message") {
296
- const text = messageText(e);
297
- const msg = e.data && e.data.message;
317
+ if (!e || typeof e.seq !== 'number') continue
318
+ if (e.type === 'user/message' || e.type === 'assistant/message' || e.type === 'system/message') {
319
+ const text = messageText(e)
320
+ const msg = e.data && e.data.message
298
321
  // id:宿主持久化的消息身份(user 在 data.id、assistant 在 data.message.id),
299
322
  // 供 0.2.0 assistant-actions 槽(ownerProps={messageId})反查 seq。
300
323
  // marker:本事件是 revert/delete 落定的 replace 标记 → 对话框据此提供「恢复」模式。
301
- const isReplaceMarker = !!(e.surfaceOp && typeof e.surfaceOp === "object" && e.surfaceOp.op === "replace");
324
+ const isReplaceMarker = !!(e.surfaceOp && typeof e.surfaceOp === 'object' && e.surfaceOp.op === 'replace')
302
325
  messages.push({
303
326
  seq: e.seq,
304
327
  type: e.type,
305
- role: (msg && msg.role) || (e.type === "user/message" ? "user" : e.type === "assistant/message" ? "assistant" : "system"),
328
+ role: (msg && msg.role) || (e.type === 'user/message' ? 'user' : e.type === 'assistant/message' ? 'assistant' : 'system'),
306
329
  id: (msg && msg.id) || e.data.id || null,
307
330
  marker: isReplaceMarker,
308
- snippet: text.replace(/\s+/g, " ").trim().slice(0, 160),
331
+ snippet: text.replace(/\s+/g, ' ').trim().slice(0, 160),
309
332
  // 0.4.0 composer 回填:user 消息携带全文(revert 后 setDraft 原文)
310
- fullText: e.type === "user/message" ? text : null,
333
+ fullText: e.type === 'user/message' ? text : null,
311
334
  // 0.4.1 dock:replace 标记携带范围与来源(区分手工回撤 vs compaction)
312
- range: isReplaceMarker && e.surfaceOp.startSeq != null && e.surfaceOp.endSeq != null
313
- ? { start: e.surfaceOp.startSeq, end: e.surfaceOp.endSeq } : null,
335
+ range:
336
+ isReplaceMarker && e.surfaceOp.startSeq != null && e.surfaceOp.endSeq != null
337
+ ? { start: e.surfaceOp.startSeq, end: e.surfaceOp.endSeq }
338
+ : null,
314
339
  sourceKind: (e.data && e.data.source && e.data.source.kind) || null,
315
340
  // 0.4.2:恢复标记引用(restore 的 notice 事件带回它所恢复的标记 seq)
316
- restoresSeq: (e.type === "system/message" && e.data && typeof e.data.restoresSeq === "number")
317
- ? e.data.restoresSeq : null,
341
+ restoresSeq: e.type === 'system/message' && e.data && typeof e.data.restoresSeq === 'number' ? e.data.restoresSeq : null,
318
342
  time: e.time ?? null,
319
343
  turn: (e.data && e.data.turn) ?? null,
320
344
  syntheticTurn: syntheticTurns.has(e.data && e.data.turn) || undefined,
321
345
  // 0.9.1:assistant 节点的宿主 node-key 是 `14:assistant-step<turn>:<step>`,
322
346
  // 没有 step 就无法把渲染行映射回日志 seq → 回滚时助手回答藏不掉。
323
347
  step: (e.data && e.data.step) ?? null,
324
- });
325
- } else if (e.type === "tool/call") {
326
- const d = e.data || {};
327
- const name = d.name || (d.call && d.call.name) || "tool";
348
+ })
349
+ } else if (e.type === 'tool/call') {
350
+ const d = e.data || {}
351
+ const name = d.name || (d.call && d.call.name) || 'tool'
328
352
  messages.push({
329
- seq: e.seq, type: "tool/call", role: "tool", snippet: `[tool] ${name}`,
330
- time: e.time ?? null, turn: d.turn ?? null, step: d.step ?? null,
353
+ seq: e.seq,
354
+ type: 'tool/call',
355
+ role: 'tool',
356
+ snippet: `[tool] ${name}`,
357
+ time: e.time ?? null,
358
+ turn: d.turn ?? null,
359
+ step: d.step ?? null,
331
360
  // 0.9.1:工具节点的宿主 node-key 是 `9:tool-call<callId>`
332
361
  id: d.callId ?? null,
333
- });
362
+ })
334
363
  }
335
364
  }
336
- return messages;
365
+ return messages
337
366
  }
338
367
 
339
368
  /**
@@ -342,12 +371,12 @@ export function listMessages(events) {
342
371
  * dsh-src 较新副本的 {op:'replace', start, end};其余视为非法返回 null。
343
372
  */
344
373
  export function readReplaceOp(e) {
345
- const op = e && e.surfaceOp;
346
- if (!op || typeof op !== "object" || op.op !== "replace") return null;
347
- const startSeq = Number.isSafeInteger(op.startSeq) ? op.startSeq : op.start;
348
- const endSeq = Number.isSafeInteger(op.endSeq) ? op.endSeq : op.end;
349
- if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq)) return null;
350
- return { startSeq, endSeq };
374
+ const op = e && e.surfaceOp
375
+ if (!op || typeof op !== 'object' || op.op !== 'replace') return null
376
+ const startSeq = Number.isSafeInteger(op.startSeq) ? op.startSeq : op.start
377
+ const endSeq = Number.isSafeInteger(op.endSeq) ? op.endSeq : op.end
378
+ if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq)) return null
379
+ return { startSeq, endSeq }
351
380
  }
352
381
 
353
382
  /**
@@ -382,18 +411,18 @@ export function readReplaceOp(e) {
382
411
  * @param {Array<object>} messages listMessages 的输出(会被就地打上 committed)
383
412
  */
384
413
  export function markCommitted(messages) {
385
- const realUserSeqs = [];
414
+ const realUserSeqs = []
386
415
  for (const m of messages) {
387
- if (m && m.type === "user/message" && m.sourceKind === "user") realUserSeqs.push(m.seq);
416
+ if (m && m.type === 'user/message' && m.sourceKind === 'user') realUserSeqs.push(m.seq)
388
417
  }
389
418
  for (const m of messages) {
390
- if (!m || m.marker !== true) continue;
391
- m.committed = realUserSeqs.some((seq) => seq > m.seq);
419
+ if (!m || m.marker !== true) continue
420
+ m.committed = realUserSeqs.some(seq => seq > m.seq)
392
421
  }
393
- return messages;
422
+ return messages
394
423
  }
395
424
 
396
- const MAX_SPAN = 1_000_000;
425
+ const MAX_SPAN = 1_000_000
397
426
 
398
427
  /**
399
428
  * M1 护栏:超 span 上限直接抛(fail loud;与 session-search 同款常量与阈值,
@@ -402,10 +431,10 @@ const MAX_SPAN = 1_000_000;
402
431
  * 伪造 marker,不允许把它卡死事件循环。
403
432
  */
404
433
  export function computeShadowed(events) {
405
- const shadowed = new Set();
434
+ const shadowed = new Set()
406
435
  for (const e of events) {
407
- const range = readReplaceOp(e);
408
- if (!range) continue;
436
+ const range = readReplaceOp(e)
437
+ if (!range) continue
409
438
  // M2′(0.10.9):反向区间 [start>end] —— 引擎 foldSurface 的替换遮蔽是
410
439
  // 「节点索引序重算」(dsh-session/types/surface.js:299-327 replacementRange
411
440
  // 用 nodes.indexOf + nodes.slice)。数值方向本身合法,宿主判 clean(语料
@@ -413,25 +442,25 @@ export function computeShadowed(events) {
413
442
  // 磁盘口径下唯一等价的推导源是顶层 sourceEventSeqs(折叠凭据 = 被消费的
414
443
  // 原事件序列);无凭据时无法等价推导,保持旧约定忽略。
415
444
  if (range.startSeq > range.endSeq) {
416
- const src = e.sourceEventSeqs;
417
- if (!Array.isArray(src)) continue;
445
+ const src = e.sourceEventSeqs
446
+ if (!Array.isArray(src)) continue
418
447
  for (const s of src) {
419
- if (Number.isInteger(s) && s >= 0 && s < e.seq) shadowed.add(s);
448
+ if (Number.isInteger(s) && s >= 0 && s < e.seq) shadowed.add(s)
420
449
  }
421
- continue;
450
+ continue
422
451
  }
423
452
  if (range.endSeq - range.startSeq > MAX_SPAN) {
424
453
  throw new OpsError(
425
454
  `surface replace span too large: [${range.startSeq}..${range.endSeq}] exceeds MAX_SPAN=${MAX_SPAN} — refusing to materialize (corrupt or hostile replace marker?)`,
426
455
  404,
427
- );
456
+ )
428
457
  }
429
- for (let s = range.startSeq; s <= range.endSeq; s++) shadowed.add(s);
458
+ for (let s = range.startSeq; s <= range.endSeq; s++) shadowed.add(s)
430
459
  }
431
- return shadowed;
460
+ return shadowed
432
461
  }
433
462
 
434
- const yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
463
+ const yieldToLoop = () => new Promise(resolve => setImmediate(resolve))
435
464
 
436
465
  /**
437
466
  * readSessionFile 的异步变体:文件读取走 fs.promises.readFile(线程池,
@@ -444,22 +473,22 @@ const yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
444
473
  * 用户提示「仅完整读取,无截断,但本次请求耗时可能较长」。
445
474
  */
446
475
  export async function readSessionFileAsync(file, { framesPerYield = 8, frameBudget = 500 } = {}) {
447
- const buf = await fs.promises.readFile(file);
448
- const { frames } = scanZstdFrames(buf);
449
- if (frames.length === 0) throw new Error("empty or header-less session log");
450
- const events = [];
451
- let header = null;
452
- let framesSinceYield = 0;
476
+ const buf = await fs.promises.readFile(file)
477
+ const { frames } = scanZstdFrames(buf)
478
+ if (frames.length === 0) throw new Error('empty or header-less session log')
479
+ const events = []
480
+ let header = null
481
+ let framesSinceYield = 0
453
482
  for (const f of frames) {
454
- const text = zstdDecompressSync(buf.subarray(f.start, f.end)).toString("utf8");
455
- const found = collectHeaderAndEvents(text, events);
456
- if (!header) header = found;
483
+ const text = zstdDecompressSync(buf.subarray(f.start, f.end)).toString('utf8')
484
+ const found = collectHeaderAndEvents(text, events)
485
+ if (!header) header = found
457
486
  if (++framesSinceYield >= framesPerYield) {
458
- framesSinceYield = 0;
459
- await yieldToLoop();
487
+ framesSinceYield = 0
488
+ await yieldToLoop()
460
489
  }
461
490
  }
462
- if (!header) throw new Error(`session log ${file}: no {type:"session"} header line in any frame`);
463
- const bodyFrames = frames.length - 1;
464
- return { header, events, frameCount: bodyFrames, partial: bodyFrames > frameBudget };
491
+ if (!header) throw new Error(`session log ${file}: no {type:"session"} header line in any frame`)
492
+ const bodyFrames = frames.length - 1
493
+ return { header, events, frameCount: bodyFrames, partial: bodyFrames > frameBudget }
465
494
  }