@240xu/dsh-message-ops 0.12.0 → 0.13.1

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
@@ -1,8 +1,8 @@
1
- import { randomUUID, createHash, createHmac, timingSafeEqual } from "node:crypto";
1
+ import { randomUUID, createHash, createHmac, timingSafeEqual } from 'node:crypto'
2
2
 
3
3
  /** OpsError 单点在 session-file.js(computeShadowed 护栏也在那里抛它);此处转出保持既有导入面。 */
4
- export { OpsError } from "./session-file.js";
5
- import { OpsError } from "./session-file.js";
4
+ export { OpsError } from './session-file.js'
5
+ import { OpsError } from './session-file.js'
6
6
  /**
7
7
  * dsh-message-ops — 可复用操作核心(纯逻辑,无 HTTP、无 dsh-tools 依赖)。
8
8
  *
@@ -21,33 +21,33 @@ import { OpsError } from "./session-file.js";
21
21
  * @module dsh-message-ops/ops-core
22
22
  */
23
23
 
24
- import { readReplaceOp, messageText, computeShadowed } from "./session-file.js";
24
+ import { readReplaceOp, messageText, computeShadowed } from './session-file.js'
25
25
 
26
26
  // messageText 的单点实现在 session-file.js(listMessages 同用);此处转出保持
27
27
  // 既有导入面兼容(ops-core 的 messageText 调用方不受影响)。
28
- export { messageText };
28
+ export { messageText }
29
29
 
30
30
  /** 带语义状态码的操作错误(单点已迁至 session-file.js,此处仅转出)。 */
31
31
 
32
32
  /** planRevert:回撤语义 = 遮蔽 targetSeq 及其之后全部可见节点(连续到末尾)。 */
33
33
  export function planRevert(surface, targetSeq) {
34
- const nodes = surface && Array.isArray(surface.nodes) ? surface.nodes : [];
35
- const startIdx = nodes.indexOf(targetSeq);
36
- if (startIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409);
37
- const shadowedSeqs = nodes.slice(startIdx);
38
- if (shadowedSeqs.length === 0) throw new OpsError("nothing to revert", 409);
34
+ const nodes = surface && Array.isArray(surface.nodes) ? surface.nodes : []
35
+ const startIdx = nodes.indexOf(targetSeq)
36
+ if (startIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409)
37
+ const shadowedSeqs = nodes.slice(startIdx)
38
+ if (shadowedSeqs.length === 0) throw new OpsError('nothing to revert', 409)
39
39
  return {
40
40
  startSeq: targetSeq,
41
41
  endSeq: shadowedSeqs[shadowedSeqs.length - 1],
42
42
  shadowedSeqs,
43
- };
43
+ }
44
44
  }
45
45
 
46
46
  /** planDelete:单条遮蔽,要求 seq 仍在当前 surface 上可见。 */
47
47
  export function planDelete(surface, seq) {
48
- const nodes = surface && Array.isArray(surface.nodes) ? surface.nodes : [];
49
- if (!nodes.includes(seq)) throw new OpsError(`seq ${seq} not visible on current surface`, 409);
50
- return { startSeq: seq, endSeq: seq, shadowedSeqs: [seq] };
48
+ const nodes = surface && Array.isArray(surface.nodes) ? surface.nodes : []
49
+ if (!nodes.includes(seq)) throw new OpsError(`seq ${seq} not visible on current surface`, 409)
50
+ return { startSeq: seq, endSeq: seq, shadowedSeqs: [seq] }
51
51
  }
52
52
 
53
53
  // 写端 replace 拼写(前向兼容雷,评审 P1):当前运行时引擎
@@ -58,16 +58,16 @@ export function planDelete(surface, seq) {
58
58
  // "invalid replace surfaceOp"(validateNext 在事件入 log 前抛出,失败不落
59
59
  // 状态、无半写风险),降级用 {start,end} 重试一次并记住结果。读端
60
60
  // (readReplaceOp/computeShadowed/planRestore)两种拼写始终兼容。
61
- let replaceShape = null; // null=未探测 | "legacy"=startSeq/endSeq | "new"=start/end
61
+ let replaceShape = null // null=未探测 | "legacy"=startSeq/endSeq | "new"=start/end
62
62
 
63
63
  function replaceOpFor(shape, startSeq, endSeq) {
64
- return shape === "new"
65
- ? { op: "replace", start: startSeq, end: endSeq }
66
- : { op: "replace", startSeq, endSeq };
64
+ return shape === 'new' ? { op: 'replace', start: startSeq, end: endSeq } : { op: 'replace', startSeq, endSeq }
67
65
  }
68
66
 
69
67
  /** 测试专用:重置写端拼写探测缓存。 */
70
- export function _resetReplaceShape() { replaceShape = null; }
68
+ export function _resetReplaceShape() {
69
+ replaceShape = null
70
+ }
71
71
 
72
72
  /**
73
73
  * v4 消息归属(producer-owned source)构造。
@@ -90,8 +90,8 @@ export function _resetReplaceShape() { replaceShape = null; }
90
90
  *
91
91
  * ⚠️ 不要改成 `{kind:"message-ops"}`:它在 v3 直接非法(实测 FAIL)。
92
92
  */
93
- const PLUGIN_NAME = "@240xu/dsh-message-ops";
94
- const PRODUCER_KIND = `plugin:${PLUGIN_NAME}`; // 迁移后的 v4 形态
93
+ const PLUGIN_NAME = '@240xu/dsh-message-ops'
94
+ const PRODUCER_KIND = `plugin:${PLUGIN_NAME}` // 迁移后的 v4 形态
95
95
 
96
96
  /**
97
97
  * 按**目标代**构造消息 source —— v3 与 v4 的合法形状互斥(实测):
@@ -110,29 +110,35 @@ const PRODUCER_KIND = `plugin:${PLUGIN_NAME}`; // 迁移后的 v4 形态
110
110
  * @param {number|undefined} version 目标日志的 header.version(4 = v4;其余按 v3 形状)
111
111
  */
112
112
  function messageSource(role, version) {
113
- const r = role ?? "system";
113
+ const r = role ?? 'system'
114
114
  // ⚠️ role=system 只能写 "system-prompt":Session 运行时层(dsh-session/lib/index.js:1206)
115
115
  // 对 `system/message` 要求 kind **严格等于** "system-prompt",比 v4 格式闸更严,
116
116
  // 任何 producer-owned kind(含 plugin:<name>)都会被加载端拒���:
117
117
  // `session event at seq N message must have system-prompt source`
118
- if (r === "system") return { kind: "system-prompt" };
119
- if (version === 4) return { kind: PRODUCER_KIND, role: r };
120
- return { kind: "plugin", plugin: PLUGIN_NAME, role: r };
118
+ if (r === 'system') return { kind: 'system-prompt' }
119
+ if (version === 4) return { kind: PRODUCER_KIND, role: r }
120
+ return { kind: 'plugin', plugin: PLUGIN_NAME, role: r }
121
121
  }
122
122
 
123
123
  function assistantReplaySource(item, version) {
124
- const source = item && item.source;
124
+ const source = item && item.source
125
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);
126
+ if (
127
+ !source ||
128
+ source.kind !== 'model' ||
129
+ typeof source.provider !== 'string' ||
130
+ !source.provider ||
131
+ typeof source.model !== 'string' ||
132
+ !source.model
133
+ ) {
134
+ throw new OpsError('assistant replay requires the original model source', 500)
129
135
  }
130
- return { ...source };
136
+ return { ...source }
131
137
  }
132
- if (source && typeof source === "object" && typeof source.kind === "string" && source.kind) {
133
- return { ...source };
138
+ if (source && typeof source === 'object' && typeof source.kind === 'string' && source.kind) {
139
+ return { ...source }
134
140
  }
135
- return messageSource("assistant", version);
141
+ return messageSource('assistant', version)
136
142
  }
137
143
 
138
144
  /**
@@ -146,25 +152,25 @@ function assistantReplaySource(item, version) {
146
152
  * 正确形状见 `dsh-session-format-v2-to-v3/lib/index.js:264-271`。
147
153
  */
148
154
  export function replayEventData(item, ts, version = 4) {
149
- if (item.type === "user/message") {
155
+ if (item.type === 'user/message') {
150
156
  return {
151
157
  id: item.id ?? randomUUID(),
152
- role: "user",
153
- source: messageSource("user", version),
154
- content: [{ type: "text", text: item.text }],
155
- };
158
+ role: 'user',
159
+ source: messageSource('user', version),
160
+ content: [{ type: 'text', text: item.text }],
161
+ }
156
162
  }
157
163
  if (!ts || !Number.isSafeInteger(ts.turn) || ts.turn <= 0 || !Number.isSafeInteger(ts.step) || ts.step <= 0) {
158
- throw new OpsError("replayEventData: assistant/message 需要打开的 turn/step,拒绝写出注定无法加载的事件", 500);
164
+ throw new OpsError('replayEventData: assistant/message 需要打开的 turn/step,拒绝写出注定无法加载的事件', 500)
159
165
  }
160
166
  return {
161
167
  turn: ts.turn,
162
168
  step: ts.step,
163
169
  message: {
164
170
  id: item.id ?? randomUUID(),
165
- role: "assistant",
171
+ role: 'assistant',
166
172
  source: assistantReplaySource(item, version),
167
- content: [{ type: "text", text: item.text }],
173
+ content: [{ type: 'text', text: item.text }],
168
174
  },
169
175
  // ⚠️ v4 契约 `stream: AssistantStreamRecord[]` **非可选**
170
176
  // (SessionEventMap,见 dsh-agent-preset-registry/lib/typert.host.js:647)。
@@ -187,7 +193,7 @@ export function replayEventData(item, ts, version = 4) {
187
193
  // ⚠️ 反面教材:不要写「半填充流」(如只放 message-end/usage chunk)——
188
194
  // 一旦 timed.length !== 0,宿主要求 blocks()/usage/replayState 与 message 全部深等,做不全就是新的写坏。
189
195
  stream: [],
190
- };
196
+ }
191
197
  }
192
198
 
193
199
  /**
@@ -208,13 +214,13 @@ export function replayEventData(item, ts, version = 4) {
208
214
  export function deriveTurnStep(events) {
209
215
  if (Array.isArray(events)) {
210
216
  for (let i = events.length - 1; i >= 0; i--) {
211
- const d = events[i] && events[i].data;
217
+ const d = events[i] && events[i].data
212
218
  if (d && Number.isSafeInteger(d.turn) && d.turn > 0 && Number.isSafeInteger(d.step) && d.step > 0) {
213
- return { turn: d.turn, step: d.step };
219
+ return { turn: d.turn, step: d.step }
214
220
  }
215
221
  }
216
222
  }
217
- return { turn: 1, step: 1 };
223
+ return { turn: 1, step: 1 }
218
224
  }
219
225
 
220
226
  /**
@@ -238,74 +244,106 @@ export function deriveTurnStep(events) {
238
244
  */
239
245
  /** 合成 turn 落盘后,把宿主 idle agent 的 turn 游标对齐到该 turn(否则下一条真实消息会重号)。 */
240
246
  export function alignLiveTurnCursor(ctx, session, turn) {
241
- if (!Number.isSafeInteger(turn) || turn < 1 || !session || typeof session.id !== "string") return false;
247
+ if (!Number.isSafeInteger(turn) || turn < 1 || !session || typeof session.id !== 'string') return false
242
248
  // 0.11.4:插件 `inject` 故意留空(tools 是可选增强),因此 `ctx.agents`
243
249
  // **属性访问恒为 undefined** —— 旧实现只写 `ctx.agents`,这条对齐从来没执行过。
244
250
  // 实测 `ctx.get("agents")` 在 HTTP 请求期可解析(同 resolveSession 的取法),
245
251
  // 故属性优先、ctx.get 兜底。
246
- let agents = null;
247
- try { if (ctx && ctx.agents) agents = ctx.agents; } catch { /* getter threw */ }
248
- if (!agents) { try { agents = ctx && typeof ctx.get === "function" ? ctx.get("agents") : null; } catch { /* absent */ } }
249
- let agent = null;
250
- try { agent = agents && typeof agents.get === "function" ? agents.get(session.id) : null; } catch { /* registry miss */ }
251
- if (!agent || agent.phase?.kind !== "idle" || typeof agent.setPhase !== "function") return false;
252
- const lastTurn = Number.isSafeInteger(agent.phase.lastTurn) ? agent.phase.lastTurn : 0;
253
- if (lastTurn >= turn) return false;
254
- agent.setPhase({ kind: "idle", lastTurn: turn });
255
- return true;
252
+ let agents = null
253
+ try {
254
+ if (ctx && ctx.agents) agents = ctx.agents
255
+ } catch {
256
+ /* getter threw */
257
+ }
258
+ if (!agents) {
259
+ try {
260
+ agents = ctx && typeof ctx.get === 'function' ? ctx.get('agents') : null
261
+ } catch {
262
+ /* absent */
263
+ }
264
+ }
265
+ let agent = null
266
+ try {
267
+ agent = agents && typeof agents.get === 'function' ? agents.get(session.id) : null
268
+ } catch {
269
+ /* registry miss */
270
+ }
271
+ if (!agent || agent.phase?.kind !== 'idle' || typeof agent.setPhase !== 'function') return false
272
+ const lastTurn = Number.isSafeInteger(agent.phase.lastTurn) ? agent.phase.lastTurn : 0
273
+ if (lastTurn >= turn) return false
274
+ agent.setPhase({ kind: 'idle', lastTurn: turn })
275
+ return true
256
276
  }
257
277
 
258
278
  export function sessionLogOf(session) {
259
- if (!session) return null;
260
- if (Array.isArray(session.log)) return session.log;
261
- if (Array.isArray(session.events)) return session.events;
262
- if (typeof session.events === "function") {
263
- try { const log = session.events(); return Array.isArray(log) ? log : null; } catch { return null; }
279
+ if (!session) return null
280
+ if (Array.isArray(session.log)) return session.log
281
+ if (Array.isArray(session.events)) return session.events
282
+ if (typeof session.events === 'function') {
283
+ try {
284
+ const log = session.events()
285
+ return Array.isArray(log) ? log : null
286
+ } catch {
287
+ return null
288
+ }
264
289
  }
265
- return null;
290
+ return null
266
291
  }
267
292
 
268
293
  export function planNoticeWindow(events) {
269
- let turn = null, step = null, maxTurn = 0;
294
+ let turn = null,
295
+ step = null,
296
+ maxTurn = 0
270
297
  for (const e of events ?? []) {
271
- const d = e?.data;
272
- if (Number.isSafeInteger(d?.turn) && d.turn > maxTurn) maxTurn = d.turn;
298
+ const d = e?.data
299
+ if (Number.isSafeInteger(d?.turn) && d.turn > maxTurn) maxTurn = d.turn
273
300
  switch (e?.type) {
274
- case "turn/start": turn = d?.turn ?? null; step = null; break;
275
- case "step/start": step = d?.step ?? null; break;
276
- case "step/end": step = null; break;
277
- case "turn/end": turn = null; step = null; break;
278
- default: break;
301
+ case 'turn/start':
302
+ turn = d?.turn ?? null
303
+ step = null
304
+ break
305
+ case 'step/start':
306
+ step = d?.step ?? null
307
+ break
308
+ case 'step/end':
309
+ step = null
310
+ break
311
+ case 'turn/end':
312
+ turn = null
313
+ step = null
314
+ break
315
+ default:
316
+ break
279
317
  }
280
318
  }
281
319
  // 会话正开着 turn+step(例如上一轮被中断)→ 直接用现成窗口,不造合成 turn
282
- if (turn !== null && step !== null) return { synthetic: false, turn, step };
283
- if (turn !== null) throw new OpsError("session is between steps; retry after the current turn settles", 409);
284
- const nextTurn = maxTurn + 1;
285
- return { synthetic: true, turn: nextTurn, step: 1 };
320
+ if (turn !== null && step !== null) return { synthetic: false, turn, step }
321
+ if (turn !== null) throw new OpsError('session is between steps; retry after the current turn settles', 409)
322
+ const nextTurn = maxTurn + 1
323
+ return { synthetic: true, turn: nextTurn, step: 1 }
286
324
  }
287
325
 
288
326
  /** 合成窗口的前缀事件(seq/time 由调用方分配)。 */
289
327
  export function noticeWindowPreamble(win) {
290
- if (!win.synthetic) return [];
328
+ if (!win.synthetic) return []
291
329
  return [
292
- { kind: "turn/start", data: { turn: win.turn, reason: "message-ops" } },
293
- { kind: "step/start", data: { turn: win.turn, step: win.step } },
294
- ];
330
+ { kind: 'turn/start', data: { turn: win.turn, reason: 'message-ops' } },
331
+ { kind: 'step/start', data: { turn: win.turn, step: win.step } },
332
+ ]
295
333
  }
296
334
 
297
335
  /** 合成窗口的后缀事件。 */
298
336
  export function noticeWindowPostamble(win) {
299
- if (!win.synthetic) return [];
337
+ if (!win.synthetic) return []
300
338
  return [
301
- { kind: "step/end", data: { turn: win.turn, step: win.step } },
339
+ { kind: 'step/end', data: { turn: win.turn, step: win.step } },
302
340
  // ⚠️ turn/end.data.reason 是**必填契约**(types.d.ts:271-276),引擎自己也这么写
303
341
  // (dsh-session/lib/index.js:783-786)。UI 的 trajectory 装配器无防护地读
304
342
  // `match.event.data.reason.kind`(dsh-client-ui-trajectory/lib/client.js:997-998)
305
343
  // → 缺字段会让整个会话页白屏(ConversationNodeAssembler.replayContext 抛 TypeError)。
306
344
  // 用 "completed":这是成功的记账 turn;用 "interrupted" 会被聊天 UI 渲染成“已停止”。
307
- { kind: "turn/end", data: { turn: win.turn, reason: { kind: "completed" } } },
308
- ];
345
+ { kind: 'turn/end', data: { turn: win.turn, reason: { kind: 'completed' } } },
346
+ ]
309
347
  }
310
348
 
311
349
  /**
@@ -322,46 +360,49 @@ export function noticeWindowPostamble(win) {
322
360
  * @returns {number[]} 去重后保持首次出现顺序的整数序列
323
361
  */
324
362
  export function expandSourceSeqs(value) {
325
- const out = [];
326
- const seen = new Set();
327
- const push = (seq) => {
328
- if (!Number.isSafeInteger(seq)) throw new OpsError("surface replace sources must be integer seqs", 500);
329
- if (seen.has(seq)) return;
330
- seen.add(seq);
331
- out.push(seq);
332
- };
363
+ const out = []
364
+ const seen = new Set()
365
+ const push = seq => {
366
+ if (!Number.isSafeInteger(seq)) throw new OpsError('surface replace sources must be integer seqs', 500)
367
+ if (seen.has(seq)) return
368
+ seen.add(seq)
369
+ out.push(seq)
370
+ }
333
371
  for (const entry of Array.isArray(value) ? value : []) {
334
372
  if (Array.isArray(entry)) {
335
- if (entry.length !== 2) throw new OpsError("surface replace source ranges must be [start, end] pairs", 500);
336
- const [start, end] = entry;
373
+ if (entry.length !== 2) throw new OpsError('surface replace source ranges must be [start, end] pairs', 500)
374
+ const [start, end] = entry
337
375
  if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end < start) {
338
- throw new OpsError("surface replace source ranges require integer start <= end", 500);
376
+ throw new OpsError('surface replace source ranges require integer start <= end', 500)
339
377
  }
340
- for (let seq = start; seq <= end; seq += 1) push(seq);
378
+ for (let seq = start; seq <= end; seq += 1) push(seq)
341
379
  } else {
342
- push(entry);
380
+ push(entry)
343
381
  }
344
382
  }
345
- return out;
383
+ return out
346
384
  }
347
385
 
348
386
  export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs, noticeText, turnStep) {
349
- const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0
350
- ? turnStep : { turn: 1, step: 1 };
351
- const sources = expandSourceSeqs(sourceEventSeqs);
352
- const data = { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", source: messageSource("system", 4), content: [{ type: "text", text: noticeText }] } };
387
+ const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0 ? turnStep : { turn: 1, step: 1 }
388
+ const sources = expandSourceSeqs(sourceEventSeqs)
389
+ const data = {
390
+ turn: ts.turn,
391
+ step: ts.step,
392
+ message: { id: randomUUID(), role: 'system', source: messageSource('system', 4), content: [{ type: 'text', text: noticeText }] },
393
+ }
353
394
  if (replaceShape) {
354
- return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs: sources });
395
+ return session.append('system/message', data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs: sources })
355
396
  }
356
397
  try {
357
- const event = session.append("system/message", data, { surfaceOp: replaceOpFor("legacy", startSeq, endSeq), sourceEventSeqs: sources });
358
- replaceShape = "legacy";
359
- return event;
398
+ const event = session.append('system/message', data, { surfaceOp: replaceOpFor('legacy', startSeq, endSeq), sourceEventSeqs: sources })
399
+ replaceShape = 'legacy'
400
+ return event
360
401
  } catch (err) {
361
- if (!/invalid replace surfaceOp/.test(String(err && err.message))) throw err;
362
- const event = session.append("system/message", data, { surfaceOp: replaceOpFor("new", startSeq, endSeq), sourceEventSeqs: sources });
363
- replaceShape = "new";
364
- return event;
402
+ if (!/invalid replace surfaceOp/.test(String(err && err.message))) throw err
403
+ const event = session.append('system/message', data, { surfaceOp: replaceOpFor('new', startSeq, endSeq), sourceEventSeqs: sources })
404
+ replaceShape = 'new'
405
+ return event
365
406
  }
366
407
  }
367
408
 
@@ -373,47 +414,48 @@ export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs,
373
414
  * seq(其 surfaceOp 为 replace、sourceEventSeqs 记录了被遮蔽节点)
374
415
  */
375
416
  export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
376
- if (!Array.isArray(events)) throw new OpsError("restore: events must be an array", 500);
377
- if (!Number.isSafeInteger(restoreSeq) || restoreSeq < 0) throw new OpsError("invalid seq", 400);
378
- const ev = events.find((e) => e && e.seq === restoreSeq);
379
- if (!ev) throw new OpsError(`restore: event seq ${restoreSeq} not found in log`, 404);
417
+ if (!Array.isArray(events)) throw new OpsError('restore: events must be an array', 500)
418
+ if (!Number.isSafeInteger(restoreSeq) || restoreSeq < 0) throw new OpsError('invalid seq', 400)
419
+ const ev = events.find(e => e && e.seq === restoreSeq)
420
+ if (!ev) throw new OpsError(`restore: event seq ${restoreSeq} not found in log`, 404)
380
421
  // 读取端拼写统一走 session-file 的 readReplaceOp(双拼写兼容的单点)。
381
- const range = readReplaceOp(ev);
422
+ const range = readReplaceOp(ev)
382
423
  if (!range) {
383
- throw new OpsError(`restore: seq ${restoreSeq} is not a revert/delete marker event (no well-formed replace surfaceOp)`, 409);
424
+ throw new OpsError(`restore: seq ${restoreSeq} is not a revert/delete marker event (no well-formed replace surfaceOp)`, 409)
384
425
  }
385
- const { startSeq, endSeq } = range;
426
+ const { startSeq, endSeq } = range
386
427
  // 0.8.0 按轮步进:upToSeq 给定则只重放到该 seq(含),后续仍保持遮蔽;
387
428
  // excludeSeqs = 已重放过(先前轮次 notice 的 restoredSourceSeqs 并集),
388
429
  // **必须排除,否则每轮都从区间头重放 → 消息副本刷屏**(0.8.0 实测 B1)。
389
- const cap = Number.isSafeInteger(upToSeq) ? Math.min(upToSeq, endSeq) : endSeq;
390
- const excluded = Array.isArray(excludeSeqs) ? new Set(excludeSeqs.filter((q) => Number.isSafeInteger(q))) : null;
391
- const replayable = [];
392
- let skipped = 0;
430
+ const cap = Number.isSafeInteger(upToSeq) ? Math.min(upToSeq, endSeq) : endSeq
431
+ const excluded = Array.isArray(excludeSeqs) ? new Set(excludeSeqs.filter(q => Number.isSafeInteger(q))) : null
432
+ const replayable = []
433
+ let skipped = 0
393
434
  for (const e of events) {
394
- if (!e || typeof e.seq !== "number" || e.seq < startSeq || e.seq > cap) continue;
395
- if (e.type === "user/message" || e.type === "assistant/message") {
396
- if (excluded && excluded.has(e.seq)) continue;
397
- const text = messageText(e);
398
- if (!text.trim()) { skipped++; continue; }
435
+ if (!e || typeof e.seq !== 'number' || e.seq < startSeq || e.seq > cap) continue
436
+ if (e.type === 'user/message' || e.type === 'assistant/message') {
437
+ if (excluded && excluded.has(e.seq)) continue
438
+ const text = messageText(e)
439
+ if (!text.trim()) {
440
+ skipped++
441
+ continue
442
+ }
399
443
  replayable.push({
400
444
  seq: e.seq,
401
445
  type: e.type,
402
- role: e.type === "user/message" ? "user" : "assistant",
446
+ role: e.type === 'user/message' ? 'user' : 'assistant',
403
447
  text,
404
- source: e.type === "assistant/message" && e.data && e.data.message
405
- ? e.data.message.source
406
- : undefined,
407
- });
448
+ source: e.type === 'assistant/message' && e.data && e.data.message ? e.data.message.source : undefined,
449
+ })
408
450
  } else {
409
- skipped++; // tool/call 等不可安全重放的事件:跳过并在结果里计数
451
+ skipped++ // tool/call 等不可安全重放的事件:跳过并在结果里计数
410
452
  }
411
453
  }
412
454
  // 0.5.6:区间无可重放消息(如只遮蔽了 tool/system 事件)不再 409 ——
413
455
  // dock 会为这类标记常驻显示恢复按钮,409 死按钮 = 永远清不掉(实测 8 连 409)。
414
456
  // 改为返回空计划:applyRestore 仍追加说明 notice(含 restoresSeq)→ 标记停用、
415
457
  // dock 计数递减;语义如实:0 条重放 + 文案说明区间无 user/assistant 内容。
416
- return { restoreSeq, startSeq, endSeq, upToSeq: Number.isSafeInteger(upToSeq) ? cap : endSeq, replayable, skipped };
458
+ return { restoreSeq, startSeq, endSeq, upToSeq: Number.isSafeInteger(upToSeq) ? cap : endSeq, replayable, skipped }
417
459
  }
418
460
 
419
461
  /**
@@ -425,40 +467,46 @@ export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
425
467
  export function restoreNoticeText(plan) {
426
468
  return plan.replayable.length === 0
427
469
  ? `[消息恢复] seq ${plan.startSeq}..${plan.endSeq} 区间无可重放的 user/assistant 消息(` +
428
- `内容为 tool/system 事件或空文本)——该回撤标记就此停用,区间保持遮蔽`
429
- : `[消息恢复] 重放 seq ${plan.startSeq}..${(plan.upToSeq != null ? plan.upToSeq : plan.endSeq)} 的 ${plan.replayable.length} 条消息` +
430
- (plan.upToSeq != null && plan.upToSeq < plan.endSeq ? `(按轮步进:seq ${plan.upToSeq + 1}..${plan.endSeq} 仍遮蔽)` : "") +
431
- (plan.skipped > 0 ? `(另有 ${plan.skipped} 条不可重放事件已跳过)` : "") +
432
- `;原区间仍处于遮蔽状态,恢复为重放而非解除遮蔽`;
470
+ `内容为 tool/system 事件或空文本)——该回撤标记就此停用,区间保持遮蔽`
471
+ : `[消息恢复] 重放 seq ${plan.startSeq}..${plan.upToSeq != null ? plan.upToSeq : plan.endSeq} 的 ${plan.replayable.length} 条消息` +
472
+ (plan.upToSeq != null && plan.upToSeq < plan.endSeq ? `(按轮步进:seq ${plan.upToSeq + 1}..${plan.endSeq} 仍遮蔽)` : '') +
473
+ (plan.skipped > 0 ? `(另有 ${plan.skipped} 条不可重放事件已跳过)` : '') +
474
+ `;原区间仍处于遮蔽状态,恢复为重放而非解除遮蔽`
433
475
  }
434
476
 
435
477
  export function applyRestore(session, plan, { flush } = {}) {
436
- const eventSeqs = [];
478
+ const eventSeqs = []
437
479
  const notice = plan.discard
438
480
  ? `[消息操作] 回撤标记 seq ${plan.restoreSeq} 已停用(丢弃):区间内容保持遮蔽、未重放;日志原文仍在,可搜索`
439
- : restoreNoticeText(plan);
481
+ : restoreNoticeText(plan)
440
482
  // 0.4.2:notice 事件携带 restoresSeq —— dock 据此把被恢复的标记从「活跃回撤」
441
483
  // 中移除(对齐 opencode clear 语义:恢复后不再显示为待恢复项)。
442
- const ts = plan.turnStep && Number.isSafeInteger(plan.turnStep.turn) && plan.turnStep.turn > 0
443
- ? plan.turnStep : { turn: 1, step: 1 };
484
+ const ts = plan.turnStep && Number.isSafeInteger(plan.turnStep.turn) && plan.turnStep.turn > 0 ? plan.turnStep : { turn: 1, step: 1 }
444
485
  const noticeEvent = session.append(
445
- "system/message",
446
- { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", source: messageSource("system", 4), content: [{ type: "text", text: notice }] }, restoresSeq: plan.restoreSeq, restoredSourceSeqs: plan.discard ? [] : plan.replayable.map((i) => i.seq), ...(plan.discard ? { discarded: true } : {}) },
447
- { surfaceOp: "append" },
448
- );
449
- if (noticeEvent && noticeEvent.seq != null) eventSeqs.push(noticeEvent.seq);
486
+ 'system/message',
487
+ {
488
+ turn: ts.turn,
489
+ step: ts.step,
490
+ message: { id: randomUUID(), role: 'system', source: messageSource('system', 4), content: [{ type: 'text', text: notice }] },
491
+ restoresSeq: plan.restoreSeq,
492
+ restoredSourceSeqs: plan.discard ? [] : plan.replayable.map(i => i.seq),
493
+ ...(plan.discard ? { discarded: true } : {}),
494
+ },
495
+ { surfaceOp: 'append' },
496
+ )
497
+ if (noticeEvent && noticeEvent.seq != null) eventSeqs.push(noticeEvent.seq)
450
498
  for (const item of plan.discard ? [] : plan.replayable) {
451
- const event = session.append(
452
- item.type,
453
- replayEventData(item, ts),
454
- { surfaceOp: "append" },
455
- );
456
- if (event && event.seq != null) eventSeqs.push(event.seq);
499
+ const event = session.append(item.type, replayEventData(item, ts), { surfaceOp: 'append' })
500
+ if (event && event.seq != null) eventSeqs.push(event.seq)
457
501
  }
458
502
  if (flush) {
459
- try { flush(); } catch { /* flush 失败不回滚已接受的事件 */ }
503
+ try {
504
+ flush()
505
+ } catch {
506
+ /* flush 失败不回滚已接受的事件 */
507
+ }
460
508
  }
461
- return { restoredCount: plan.discard ? 0 : plan.replayable.length, skipped: plan.skipped, eventSeqs };
509
+ return { restoredCount: plan.discard ? 0 : plan.replayable.length, skipped: plan.skipped, eventSeqs }
462
510
  }
463
511
 
464
512
  /**
@@ -473,34 +521,40 @@ export function applyRestore(session, plan, { flush } = {}) {
473
521
  * - legacy:旧通知(无 restoredSourceSeqs 字段)→ 视为整段已恢复
474
522
  */
475
523
  export function restoreProgress(events, markerSeq) {
476
- const list = Array.isArray(events) ? events : [];
477
- const marker = list.find((e) => e && e.seq === markerSeq);
478
- if (!marker) return null;
479
- const range = readReplaceOp(marker);
480
- if (!range) return null;
481
- const { startSeq, endSeq } = range;
524
+ const list = Array.isArray(events) ? events : []
525
+ const marker = list.find(e => e && e.seq === markerSeq)
526
+ if (!marker) return null
527
+ const range = readReplaceOp(marker)
528
+ if (!range) return null
529
+ const { startSeq, endSeq } = range
482
530
  // 该区间内可重放的消息型事件
483
- const candidates = [];
531
+ const candidates = []
484
532
  for (const e of list) {
485
- if (!e || typeof e.seq !== "number" || e.seq < startSeq || e.seq > endSeq) continue;
486
- if (e.type !== "user/message" && e.type !== "assistant/message") continue;
487
- if (!(messageText(e) || "").trim()) continue;
488
- candidates.push(e.seq);
533
+ if (!e || typeof e.seq !== 'number' || e.seq < startSeq || e.seq > endSeq) continue
534
+ if (e.type !== 'user/message' && e.type !== 'assistant/message') continue
535
+ if (!(messageText(e) || '').trim()) continue
536
+ candidates.push(e.seq)
489
537
  }
490
538
  // 收集针对该标记的所有恢复 notice
491
- const notices = list.filter((e) => e && e.data && e.data.restoresSeq === markerSeq);
492
- const restored = new Set();
493
- let legacy = false;
494
- let discarded = false;
539
+ const notices = list.filter(e => e && e.data && e.data.restoresSeq === markerSeq)
540
+ const restored = new Set()
541
+ let legacy = false
542
+ let discarded = false
495
543
  for (const n of notices) {
496
544
  // 0.8.1:显式丢弃(不重放内容、仅停用标记)也算完成——
497
545
  // 用户场景"我都没回滚过,清掉测试遗留条",2709 条重放是另一种污染。
498
- if (n.data.discarded === true) { discarded = true; continue; }
499
- const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null;
500
- if (!seqs) { legacy = true; continue; }
501
- for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q);
546
+ if (n.data.discarded === true) {
547
+ discarded = true
548
+ continue
549
+ }
550
+ const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null
551
+ if (!seqs) {
552
+ legacy = true
553
+ continue
554
+ }
555
+ for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q)
502
556
  }
503
- const pending = candidates.filter((q) => !restored.has(q));
557
+ const pending = candidates.filter(q => !restored.has(q))
504
558
  return {
505
559
  startSeq,
506
560
  endSeq,
@@ -509,49 +563,56 @@ export function restoreProgress(events, markerSeq) {
509
563
  complete: legacy || discarded ? true : pending.length === 0,
510
564
  legacy,
511
565
  discarded,
512
- };
566
+ }
513
567
  }
514
568
 
515
569
  export function buildRestoreIndex(events) {
516
- const bySeq = new Map();
517
- const noticesByMarker = new Map();
518
- const candidates = [];
570
+ const bySeq = new Map()
571
+ const noticesByMarker = new Map()
572
+ const candidates = []
519
573
  for (const e of events) {
520
- if (!e || typeof e.seq !== "number") continue;
521
- bySeq.set(e.seq, e);
522
- if (e.type === "user/message" || e.type === "assistant/message") {
523
- if ((messageText(e) || "").trim()) candidates.push(e.seq);
574
+ if (!e || typeof e.seq !== 'number') continue
575
+ bySeq.set(e.seq, e)
576
+ if (e.type === 'user/message' || e.type === 'assistant/message') {
577
+ if ((messageText(e) || '').trim()) candidates.push(e.seq)
524
578
  }
525
- const markerSeq = e.data && e.data.restoresSeq;
579
+ const markerSeq = e.data && e.data.restoresSeq
526
580
  if (Number.isSafeInteger(markerSeq)) {
527
- const list = noticesByMarker.get(markerSeq);
528
- if (list) list.push(e); else noticesByMarker.set(markerSeq, [e]);
581
+ const list = noticesByMarker.get(markerSeq)
582
+ if (list) list.push(e)
583
+ else noticesByMarker.set(markerSeq, [e])
529
584
  }
530
585
  }
531
- return { bySeq, noticesByMarker, candidates };
586
+ return { bySeq, noticesByMarker, candidates }
532
587
  }
533
588
 
534
589
  export function restoreProgressFromIndex(index, markerSeq) {
535
- const marker = index.bySeq.get(markerSeq);
536
- if (!marker) return null;
537
- const range = readReplaceOp(marker);
538
- if (!range) return null;
539
- const { startSeq, endSeq } = range;
540
- const candidates = [];
590
+ const marker = index.bySeq.get(markerSeq)
591
+ if (!marker) return null
592
+ const range = readReplaceOp(marker)
593
+ if (!range) return null
594
+ const { startSeq, endSeq } = range
595
+ const candidates = []
541
596
  for (const q of index.candidates) {
542
- if (q >= startSeq && q <= endSeq) candidates.push(q);
597
+ if (q >= startSeq && q <= endSeq) candidates.push(q)
543
598
  }
544
- const notices = index.noticesByMarker.get(markerSeq) || [];
545
- const restored = new Set();
546
- let legacy = false;
547
- let discarded = false;
599
+ const notices = index.noticesByMarker.get(markerSeq) || []
600
+ const restored = new Set()
601
+ let legacy = false
602
+ let discarded = false
548
603
  for (const n of notices) {
549
- if (n.data.discarded === true) { discarded = true; continue; }
550
- const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null;
551
- if (!seqs) { legacy = true; continue; }
552
- for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q);
604
+ if (n.data.discarded === true) {
605
+ discarded = true
606
+ continue
607
+ }
608
+ const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null
609
+ if (!seqs) {
610
+ legacy = true
611
+ continue
612
+ }
613
+ for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q)
553
614
  }
554
- const pending = candidates.filter((q) => !restored.has(q));
615
+ const pending = candidates.filter(q => !restored.has(q))
555
616
  return {
556
617
  startSeq,
557
618
  endSeq,
@@ -560,21 +621,23 @@ export function restoreProgressFromIndex(index, markerSeq) {
560
621
  complete: legacy || discarded ? true : pending.length === 0,
561
622
  legacy,
562
623
  discarded,
563
- };
624
+ }
564
625
  }
565
626
 
566
627
  export function pendingRestoreTurnsFromIndex(index, markerSeq, progress) {
567
- if (!progress || progress.pendingSeqs.length === 0) return [];
568
- const turns = [];
569
- let current = null;
628
+ if (!progress || progress.pendingSeqs.length === 0) return []
629
+ const turns = []
630
+ let current = null
570
631
  for (const q of progress.pendingSeqs) {
571
- const e = index.bySeq.get(q);
572
- if (!e) continue;
573
- if (e.type === "user/message") { current = { turnSeq: q, seqs: [q] }; turns.push(current); }
574
- else if (current) current.seqs.push(q);
575
- else turns.push({ turnSeq: q, seqs: [q] });
632
+ const e = index.bySeq.get(q)
633
+ if (!e) continue
634
+ if (e.type === 'user/message') {
635
+ current = { turnSeq: q, seqs: [q] }
636
+ turns.push(current)
637
+ } else if (current) current.seqs.push(q)
638
+ else turns.push({ turnSeq: q, seqs: [q] })
576
639
  }
577
- return turns;
640
+ return turns
578
641
  }
579
642
 
580
643
  /**
@@ -592,24 +655,25 @@ export function pendingRestoreTurnsFromIndex(index, markerSeq, progress) {
592
655
  * @returns {Array<{ turnSeq:number, seqs:number[] }>} 按 seq 升序
593
656
  */
594
657
  export function pendingRestoreTurns(events, markerSeq, progress = null) {
595
- const prog = progress || restoreProgress(events, markerSeq);
596
- if (!prog || prog.pendingSeqs.length === 0) return [];
597
- const list = Array.isArray(events) ? events : [];
598
- const bySeq = new Map();
599
- for (const e of list) if (e && typeof e.seq === "number") bySeq.set(e.seq, e);
600
- const turns = [];
601
- let current = null;
658
+ const prog = progress || restoreProgress(events, markerSeq)
659
+ if (!prog || prog.pendingSeqs.length === 0) return []
660
+ const list = Array.isArray(events) ? events : []
661
+ const bySeq = new Map()
662
+ for (const e of list) if (e && typeof e.seq === 'number') bySeq.set(e.seq, e)
663
+ const turns = []
664
+ let current = null
602
665
  for (const q of prog.pendingSeqs) {
603
- const e = bySeq.get(q);
604
- if (!e) continue;
605
- if (e.type === "user/message") { current = { turnSeq: q, seqs: [q] }; turns.push(current) }
606
- else if (current) current.seqs.push(q);
607
- else turns.push({ turnSeq: q, seqs: [q] }); // 孤立 assistant(无前导 user)
666
+ const e = bySeq.get(q)
667
+ if (!e) continue
668
+ if (e.type === 'user/message') {
669
+ current = { turnSeq: q, seqs: [q] }
670
+ turns.push(current)
671
+ } else if (current) current.seqs.push(q)
672
+ else turns.push({ turnSeq: q, seqs: [q] }) // 孤立 assistant(无前导 user)
608
673
  }
609
- return turns;
674
+ return turns
610
675
  }
611
676
 
612
-
613
677
  // ---------------------------------------------------------------------------
614
678
  // HTTP 信任围栏(评审 P0):插件经 webServer.register 挂载的路由不经过宿主
615
679
  // connection RPC 面的 isTrustedApiRequest 围栏(dsh-src
@@ -622,31 +686,39 @@ export function pendingRestoreTurns(events, markerSeq, progress = null) {
622
686
  // ---------------------------------------------------------------------------
623
687
 
624
688
  function headerOf(headers, name) {
625
- const value = headers && headers[name];
626
- return typeof value === "string" ? value : undefined;
689
+ const value = headers && headers[name]
690
+ return typeof value === 'string' ? value : undefined
627
691
  }
628
692
 
629
693
  function parseAuthority(authority) {
630
- try { return new URL(`http://${authority}`); } catch { return undefined; }
694
+ try {
695
+ return new URL(`http://${authority}`)
696
+ } catch {
697
+ return undefined
698
+ }
631
699
  }
632
700
 
633
701
  function isLoopbackHostname(hostname) {
634
- if (hostname === "localhost" || hostname === "[::1]") return true;
635
- const parts = hostname.split(".");
636
- return parts.length === 4 && parts[0] === "127" && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255);
702
+ if (hostname === 'localhost' || hostname === '[::1]') return true
703
+ const parts = hostname.split('.')
704
+ return parts.length === 4 && parts[0] === '127' && parts.every(p => /^\d{1,3}$/.test(p) && Number(p) <= 255)
637
705
  }
638
706
 
639
707
  /** 与 slv-check 同款的信任判定(回环 Host + 非 cross-site + Origin 同源)。 */
640
708
  export function isTrustedApiRequest(req) {
641
- const host = headerOf(req && req.headers, "host");
642
- if (host === undefined) return false;
643
- const hostUrl = parseAuthority(host);
644
- if (hostUrl === undefined) return false;
645
- if (!isLoopbackHostname(hostUrl.hostname)) return false;
646
- if (headerOf(req.headers, "sec-fetch-site") === "cross-site") return false;
647
- const origin = headerOf(req.headers, "origin");
648
- if (origin === undefined) return true;
649
- try { return new URL(origin).host === hostUrl.host; } catch { return false; }
709
+ const host = headerOf(req && req.headers, 'host')
710
+ if (host === undefined) return false
711
+ const hostUrl = parseAuthority(host)
712
+ if (hostUrl === undefined) return false
713
+ if (!isLoopbackHostname(hostUrl.hostname)) return false
714
+ if (headerOf(req.headers, 'sec-fetch-site') === 'cross-site') return false
715
+ const origin = headerOf(req.headers, 'origin')
716
+ if (origin === undefined) return true
717
+ try {
718
+ return new URL(origin).host === hostUrl.host
719
+ } catch {
720
+ return false
721
+ }
650
722
  }
651
723
 
652
724
  /**
@@ -658,8 +730,8 @@ export function isTrustedApiRequest(req) {
658
730
  * 引入 token 只增加握手复杂度而不增加安全性——围栏已足够(论证记录于此)。
659
731
  */
660
732
  export function isJsonContentType(req) {
661
- const ct = headerOf(req && req.headers, "content-type") || "";
662
- return ct.split(";")[0].trim().toLowerCase() === "application/json";
733
+ const ct = headerOf(req && req.headers, 'content-type') || ''
734
+ return ct.split(';')[0].trim().toLowerCase() === 'application/json'
663
735
  }
664
736
 
665
737
  // ---------------------------------------------------------------------------
@@ -682,22 +754,22 @@ export function isJsonContentType(req) {
682
754
  // 缺失/格式升级 → **fail-closed** 并告警,避免永久 allow-all。
683
755
  // 非浏览器 GET(curl 等)从 200 变 401 = 与宿主对齐的有意行为变化。
684
756
 
685
- const AUTH_RECORD_KEY = "client-connection/browser-session";
686
- const AUTH_COOKIE_PREFIX = "dsh-auth-";
687
- const AUTH_STORED_SECRET_VERSION = 1;
688
- const AUTH_SECRET_BYTES = 32;
757
+ const AUTH_RECORD_KEY = 'client-connection/browser-session'
758
+ const AUTH_COOKIE_PREFIX = 'dsh-auth-'
759
+ const AUTH_STORED_SECRET_VERSION = 1
760
+ const AUTH_SECRET_BYTES = 32
689
761
 
690
- const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;
762
+ const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u
691
763
 
692
764
  function encodeBase64Url(value) {
693
- return Buffer.from(value).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
765
+ return Buffer.from(value).toString('base64').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '')
694
766
  }
695
767
 
696
768
  function decodeBase64Url(value) {
697
- if (!BASE64URL_PATTERN.test(value) || value.length % 4 === 1) return undefined;
698
- const padding = "=".repeat((4 - (value.length % 4)) % 4);
699
- const decoded = Buffer.from(value.replaceAll("-", "+").replaceAll("_", "/") + padding, "base64");
700
- return encodeBase64Url(decoded) === value ? decoded : undefined;
769
+ if (!BASE64URL_PATTERN.test(value) || value.length % 4 === 1) return undefined
770
+ const padding = '='.repeat((4 - (value.length % 4)) % 4)
771
+ const decoded = Buffer.from(value.replaceAll('-', '+').replaceAll('_', '/') + padding, 'base64')
772
+ return encodeBase64Url(decoded) === value ? decoded : undefined
701
773
  }
702
774
 
703
775
  /** 宿主 requestAudience 的口径:HTTP 用 url.host;TLS 用 url.origin。插件
@@ -705,47 +777,51 @@ function decodeBase64Url(value) {
705
777
  * 配对校验,跨拼写伪造照样被拒)。 */
706
778
  function cookieAuthorityCandidates(hostHeader) {
707
779
  try {
708
- const url = new URL(`http://${hostHeader}`);
709
- return [url.host, `https://${url.host}`];
780
+ const url = new URL(`http://${hostHeader}`)
781
+ return [url.host, `https://${url.host}`]
710
782
  } catch {
711
- return [];
783
+ return []
712
784
  }
713
785
  }
714
786
 
715
787
  /** 宿主 cookieValue:按分号切段取**第一个**同名区的值(无解码语义)。 */
716
788
  function cookieValue(rawCookie, name) {
717
- if (typeof rawCookie !== "string") return undefined;
718
- for (const segment of rawCookie.split(";")) {
719
- const at = segment.indexOf("=");
720
- if (at === -1 || segment.slice(0, at).trim() !== name) continue;
721
- return segment.slice(at + 1).trim();
789
+ if (typeof rawCookie !== 'string') return undefined
790
+ for (const segment of rawCookie.split(';')) {
791
+ const at = segment.indexOf('=')
792
+ if (at === -1 || segment.slice(0, at).trim() !== name) continue
793
+ return segment.slice(at + 1).trim()
722
794
  }
723
- return undefined;
795
+ return undefined
724
796
  }
725
797
 
726
798
  /** 宿主 decodeCookie 的镜像:三段结构 + HMAC + 载荷形状(v1 浏览器 peer / v2 带操作者 id)。 */
727
799
  function decodeBrowserAuthCookie(value, secret) {
728
- const parts = value.split(".");
729
- const [version, body, encodedSignature] = parts;
730
- if (parts.length !== 3 || (version !== "v1" && version !== "v2") || body === undefined || encodedSignature === undefined) return undefined;
731
- const actualSignature = decodeBase64Url(encodedSignature);
732
- if (actualSignature === undefined) return undefined;
733
- const expectedSignature = createHmac("sha256", secret).update(body).digest();
734
- if (actualSignature.length !== expectedSignature.length || !timingSafeEqual(actualSignature, expectedSignature)) return undefined;
735
- const bodyBytes = decodeBase64Url(body);
736
- if (bodyBytes === undefined) return undefined;
737
- let decoded;
738
- try { decoded = JSON.parse(bodyBytes.toString("utf8")); } catch { return undefined; }
739
- if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) return undefined;
740
- if (decoded.version !== 1 && decoded.version !== 2) return undefined;
741
- if (version !== `v${decoded.version}`) return undefined;
742
- if (typeof decoded.authority !== "string" || decoded.authority === "") return undefined;
743
- if (typeof decoded.issuedAt !== "number" || !Number.isSafeInteger(decoded.issuedAt)) return undefined;
744
- if (typeof decoded.expiresAt !== "number" || !Number.isSafeInteger(decoded.expiresAt)) return undefined;
745
- const payload = { version: decoded.version, authority: decoded.authority, issuedAt: decoded.issuedAt, expiresAt: decoded.expiresAt };
746
- if (decoded.version === 1) return payload;
747
- if (typeof decoded.id !== "string" || decoded.id.length === 0) return undefined;
748
- return { ...payload, id: decoded.id };
800
+ const parts = value.split('.')
801
+ const [version, body, encodedSignature] = parts
802
+ if (parts.length !== 3 || (version !== 'v1' && version !== 'v2') || body === undefined || encodedSignature === undefined) return undefined
803
+ const actualSignature = decodeBase64Url(encodedSignature)
804
+ if (actualSignature === undefined) return undefined
805
+ const expectedSignature = createHmac('sha256', secret).update(body).digest()
806
+ if (actualSignature.length !== expectedSignature.length || !timingSafeEqual(actualSignature, expectedSignature)) return undefined
807
+ const bodyBytes = decodeBase64Url(body)
808
+ if (bodyBytes === undefined) return undefined
809
+ let decoded
810
+ try {
811
+ decoded = JSON.parse(bodyBytes.toString('utf8'))
812
+ } catch {
813
+ return undefined
814
+ }
815
+ if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) return undefined
816
+ if (decoded.version !== 1 && decoded.version !== 2) return undefined
817
+ if (version !== `v${decoded.version}`) return undefined
818
+ if (typeof decoded.authority !== 'string' || decoded.authority === '') return undefined
819
+ if (typeof decoded.issuedAt !== 'number' || !Number.isSafeInteger(decoded.issuedAt)) return undefined
820
+ if (typeof decoded.expiresAt !== 'number' || !Number.isSafeInteger(decoded.expiresAt)) return undefined
821
+ const payload = { version: decoded.version, authority: decoded.authority, issuedAt: decoded.issuedAt, expiresAt: decoded.expiresAt }
822
+ if (decoded.version === 1) return payload
823
+ if (typeof decoded.id !== 'string' || decoded.id.length === 0) return undefined
824
+ return { ...payload, id: decoded.id }
749
825
  }
750
826
 
751
827
  /**
@@ -753,24 +829,24 @@ function decodeBrowserAuthCookie(value, secret) {
753
829
  * @returns 载荷(通过)或 undefined(未认证)。返回值只当布尔用。
754
830
  */
755
831
  export function browserAuthPayload(req, secret) {
756
- if (secret == null) return undefined;
757
- const host = headerOf(req && req.headers, "host");
758
- if (host === undefined) return undefined;
759
- const rawCookie = headerOf(req.headers, "cookie");
760
- if (rawCookie === undefined) return undefined;
761
- const now = Date.now();
832
+ if (secret == null) return undefined
833
+ const host = headerOf(req && req.headers, 'host')
834
+ if (host === undefined) return undefined
835
+ const rawCookie = headerOf(req.headers, 'cookie')
836
+ if (rawCookie === undefined) return undefined
837
+ const now = Date.now()
762
838
  for (const authority of cookieAuthorityCandidates(host)) {
763
- const value = cookieValue(rawCookie, AUTH_COOKIE_PREFIX + encodeBase64Url(createHash("sha256").update(authority).digest()));
764
- if (value === undefined) continue;
765
- const payload = decodeBrowserAuthCookie(value, secret);
839
+ const value = cookieValue(rawCookie, AUTH_COOKIE_PREFIX + encodeBase64Url(createHash('sha256').update(authority).digest()))
840
+ if (value === undefined) continue
841
+ const payload = decodeBrowserAuthCookie(value, secret)
766
842
  // payload.authority 与产生名字的同一个拼写配对(宿主同样的绑定语义)。
767
- if (payload === undefined || payload.authority !== authority) continue;
843
+ if (payload === undefined || payload.authority !== authority) continue
768
844
  // 宿主 authenticate(:555 附近) 的时效三条;expiresAt-issuedAt 的 maxAge
769
845
  // 窗口不复制(host 可配 cookieMaxAgeDays,插件复制会误杀合法长龄 cookie)。
770
- if (payload.issuedAt > now || payload.expiresAt <= now || payload.expiresAt <= payload.issuedAt) continue;
771
- return payload;
846
+ if (payload.issuedAt > now || payload.expiresAt <= now || payload.expiresAt <= payload.issuedAt) continue
847
+ return payload
772
848
  }
773
- return undefined;
849
+ return undefined
774
850
  }
775
851
 
776
852
  /**
@@ -782,37 +858,39 @@ export function browserAuthPayload(req, secret) {
782
858
  * @returns {Promise<Buffer|null>}
783
859
  */
784
860
  export async function loadBrowserAuthSecret(credentials) {
785
- if (!credentials || typeof credentials.modifyRecord !== "function") return null;
786
- let record;
861
+ if (!credentials || typeof credentials.modifyRecord !== 'function') return null
862
+ let record
787
863
  try {
788
- record = await credentials.modifyRecord(AUTH_RECORD_KEY, async () => undefined);
864
+ record = await credentials.modifyRecord(AUTH_RECORD_KEY, async () => undefined)
789
865
  } catch {
790
- return null;
866
+ return null
791
867
  }
792
- if (record === undefined || record === null || typeof record !== "object" || record.kind !== "grant") return null;
793
- const payload = record.payload;
794
- if (!payload || typeof payload !== "object" || payload.version !== AUTH_STORED_SECRET_VERSION) return null;
795
- if (typeof payload.secret !== "string") return null;
796
- const secret = decodeBase64Url(payload.secret);
797
- if (!secret || secret.length !== AUTH_SECRET_BYTES) return null;
798
- return secret;
868
+ if (record === undefined || record === null || typeof record !== 'object' || record.kind !== 'grant') return null
869
+ const payload = record.payload
870
+ if (!payload || typeof payload !== 'object' || payload.version !== AUTH_STORED_SECRET_VERSION) return null
871
+ if (typeof payload.secret !== 'string') return null
872
+ const secret = decodeBase64Url(payload.secret)
873
+ if (!secret || secret.length !== AUTH_SECRET_BYTES) return null
874
+ return secret
799
875
  }
800
876
 
801
877
  // 进程级 memo:secret 一次命中就终身持有(宿主 create 只在缺失时铸新记录,
802
878
  // 正常进程内不会换代);探测失败 10s 内不重试,401 风暴不会打爆 credential 锁。
803
- const WEB_AUTH_RETRY_MS = 10_000;
804
- let __webAuthSecret = null;
805
- let __webAuthProbeAt = 0;
806
- let __webAuthProbe = null;
807
- let __webAuthWarned = false;
879
+ const WEB_AUTH_RETRY_MS = 10_000
880
+ let __webAuthSecret = null
881
+ let __webAuthProbeAt = 0
882
+ let __webAuthProbe = null
883
+ let __webAuthWarned = false
808
884
 
809
885
  /** 测试钩子:直接注入/清除 secret,绕开 credentials 服务。 */
810
- export function _setWebAuthSecret(secret) { __webAuthSecret = secret; }
886
+ export function _setWebAuthSecret(secret) {
887
+ __webAuthSecret = secret
888
+ }
811
889
  export function _resetWebAuth() {
812
- __webAuthSecret = null;
813
- __webAuthProbeAt = 0;
814
- __webAuthProbe = null;
815
- __webAuthWarned = false;
890
+ __webAuthSecret = null
891
+ __webAuthProbeAt = 0
892
+ __webAuthProbe = null
893
+ __webAuthWarned = false
816
894
  }
817
895
 
818
896
  /**
@@ -824,37 +902,42 @@ export function _resetWebAuth() {
824
902
  */
825
903
  export async function webAuthGate(ctx, req) {
826
904
  if (__webAuthSecret !== null) {
827
- return browserAuthPayload(req, __webAuthSecret) !== undefined;
905
+ return browserAuthPayload(req, __webAuthSecret) !== undefined
828
906
  }
829
907
 
830
- let credentials = null;
831
- try { credentials = ctx && typeof ctx.get === "function" ? ctx.get("credentials") : null; } catch { /* legacy ctx */ }
832
- if (!credentials || typeof credentials.modifyRecord !== "function") return true;
908
+ let credentials = null
909
+ try {
910
+ credentials = ctx && typeof ctx.get === 'function' ? ctx.get('credentials') : null
911
+ } catch {
912
+ /* legacy ctx */
913
+ }
914
+ if (!credentials || typeof credentials.modifyRecord !== 'function') return true
833
915
 
834
- const now = Date.now();
916
+ const now = Date.now()
835
917
  if (__webAuthProbe === null && now - __webAuthProbeAt >= WEB_AUTH_RETRY_MS) {
836
- __webAuthProbeAt = now;
918
+ __webAuthProbeAt = now
837
919
  __webAuthProbe = loadBrowserAuthSecret(credentials)
838
- .then((secret) => {
839
- __webAuthSecret = secret;
920
+ .then(secret => {
921
+ __webAuthSecret = secret
840
922
  if (secret === null && !__webAuthWarned) {
841
- __webAuthWarned = true;
923
+ __webAuthWarned = true
842
924
  console.warn(
843
- "[message-ops] BrowserAuth cookie 鉴权已启用但 `client-connection/browser-session` 记录不可读"
844
- + "——GET 鉴权 fail-closed;请检查该记录是否存在",
845
- );
925
+ '[message-ops] BrowserAuth cookie 鉴权已启用但 `client-connection/browser-session` 记录不可读' +
926
+ '——GET 鉴权 fail-closed;请检查该记录是否存在',
927
+ )
846
928
  }
847
- return secret;
929
+ return secret
930
+ })
931
+ .finally(() => {
932
+ __webAuthProbe = null
848
933
  })
849
- .finally(() => { __webAuthProbe = null; });
850
934
  }
851
935
 
852
- if (__webAuthProbe === null) return false;
853
- const secret = await __webAuthProbe;
854
- return secret !== null && browserAuthPayload(req, secret) !== undefined;
936
+ if (__webAuthProbe === null) return false
937
+ const secret = await __webAuthProbe
938
+ return secret !== null && browserAuthPayload(req, secret) !== undefined
855
939
  }
856
940
 
857
-
858
941
  // ---------------------------------------------------------------------------
859
942
  // 0.5.7 · 磁盘路径(lazy-view 会话不进对象层时的回退)
860
943
  // ---------------------------------------------------------------------------
@@ -863,8 +946,7 @@ export async function webAuthGate(ctx, req) {
863
946
 
864
947
  /** 事件类型是否为 surface 节点(message 类;step/end、turn/end 等结构性事件不是)。 */
865
948
  export function isSurfaceMessageType(type) {
866
- return type === "user/message" || type === "assistant/message"
867
- || type === "system/message" || type === "developer/message";
949
+ return type === 'user/message' || type === 'assistant/message' || type === 'system/message' || type === 'developer/message'
868
950
  }
869
951
 
870
952
  /** 磁盘可见节点:按事件流推导的 message 类 seq(剔除既有遮蔽)。 */
@@ -880,71 +962,71 @@ export function isSurfaceMessageType(type) {
880
962
  * 会话的真正成因(不是区间压缩编码问题)。
881
963
  */
882
964
  export function diskSurfaceNodes(events) {
883
- const shadowed = computeShadowed(events);
884
- const nodes = [];
965
+ const shadowed = computeShadowed(events)
966
+ const nodes = []
885
967
  for (const e of events) {
886
- if (!e || !Number.isSafeInteger(e.seq)) continue;
887
- if (shadowed.has(e.seq)) continue;
888
- if (isSurfaceType(e.type)) nodes.push(e.seq);
968
+ if (!e || !Number.isSafeInteger(e.seq)) continue
969
+ if (shadowed.has(e.seq)) continue
970
+ if (isSurfaceType(e.type)) nodes.push(e.seq)
889
971
  }
890
- return nodes;
972
+ return nodes
891
973
  }
892
974
 
893
975
  function isSurfaceType(type) {
894
- return isSurfaceMessageType(type) || type === "tool/result";
976
+ return isSurfaceMessageType(type) || type === 'tool/result'
895
977
  }
896
978
 
897
979
  export function diskVisibleNodes(events) {
898
- return diskSurfaceNodes(events).filter((seq) => {
899
- const e = events.find((x) => x && x.seq === seq);
900
- return e && isSurfaceMessageType(e.type);
901
- });
980
+ return diskSurfaceNodes(events).filter(seq => {
981
+ const e = events.find(x => x && x.seq === seq)
982
+ return e && isSurfaceMessageType(e.type)
983
+ })
902
984
  }
903
985
 
904
986
  /** 磁盘版 planRevert:target 必须可见,遮蔽 target 之后(含)全部可见节点。 */
905
987
  export function planRevertFromEvents(events, targetSeq) {
906
988
  // 目标用「消息」集合(回滚对象是消息),溯源用「全部 surface」集合(0.8.2 修正)
907
- const nodes = diskVisibleNodes(events);
908
- const startIdx = nodes.indexOf(targetSeq);
909
- if (startIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409);
910
- const surface = diskSurfaceNodes(events);
911
- const shadowedSeqs = surface.slice(surface.indexOf(targetSeq));
912
- if (shadowedSeqs.length === 0) throw new OpsError("nothing to revert", 409);
913
- return { startSeq: targetSeq, endSeq: shadowedSeqs[shadowedSeqs.length - 1], shadowedSeqs };
989
+ const nodes = diskVisibleNodes(events)
990
+ const startIdx = nodes.indexOf(targetSeq)
991
+ if (startIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409)
992
+ const surface = diskSurfaceNodes(events)
993
+ const shadowedSeqs = surface.slice(surface.indexOf(targetSeq))
994
+ if (shadowedSeqs.length === 0) throw new OpsError('nothing to revert', 409)
995
+ return { startSeq: targetSeq, endSeq: shadowedSeqs[shadowedSeqs.length - 1], shadowedSeqs }
914
996
  }
915
997
 
916
998
  /** 磁盘版 planDelete:单条可见遮蔽。 */
917
999
  export function planDeleteFromEvents(events, seq) {
918
- const surface = diskSurfaceNodes(events);
1000
+ const surface = diskSurfaceNodes(events)
919
1001
  if (!diskVisibleNodes(events).includes(seq) || !surface.includes(seq)) {
920
- throw new OpsError(`seq ${seq} not visible on current surface`, 409);
1002
+ throw new OpsError(`seq ${seq} not visible on current surface`, 409)
921
1003
  }
922
1004
  // 单节点遮蔽:溯源就是它自己(0.8.2:也走完整 surface 判定,避免非 surface 节点)
923
- return { startSeq: seq, endSeq: seq, shadowedSeqs: [seq] };
1005
+ return { startSeq: seq, endSeq: seq, shadowedSeqs: [seq] }
924
1006
  }
925
1007
 
926
1008
  /** 下一个可用 seq(全量事件 max+1;结构性事件也占 seq)。 */
927
1009
  export function nextSeqFrom(events) {
928
- let max = -1;
929
- for (const e of events) if (e && Number.isSafeInteger(e.seq) && e.seq > max) max = e.seq;
930
- return max + 1;
1010
+ let max = -1
1011
+ for (const e of events) if (e && Number.isSafeInteger(e.seq) && e.seq > max) max = e.seq
1012
+ return max + 1
931
1013
  }
932
1014
 
933
1015
  /** 磁盘回撤/删除标记事件(字段镜像引擎金标准:type/seq/time/data/sourceEventSeqs/surfaceOp)。 */
934
1016
  export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs, version = 4 }) {
935
- const sources = expandSourceSeqs(shadowedSeqs);
1017
+ const sources = expandSourceSeqs(shadowedSeqs)
936
1018
  return {
937
- type: "system/message",
1019
+ type: 'system/message',
938
1020
  seq,
939
1021
  time,
940
1022
  data: {
941
1023
  turn: turnStep.turn,
942
1024
  step: turnStep.step,
943
- message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
1025
+ message: { id: randomUUID(), role: 'system', source: messageSource('system', version), content: [{ type: 'text', text }] },
944
1026
  },
945
1027
  sourceEventSeqs: sources,
946
- surfaceOp: { op: "replace", startSeq, endSeq },
947
- };
1028
+ surfaceOp: { op: 'replace', startSeq, endSeq },
1029
+ }
948
1030
  }
949
1031
 
950
1032
  /**
@@ -956,23 +1038,21 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
956
1038
  * `excludeSeqs` 为空 → 同一区间被**反复重放**(实测 008f3759 两轮各 209 条)。
957
1039
  */
958
1040
  export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq, discard, restoredSourceSeqs, version = 4 }) {
959
- const restored = Array.isArray(restoredSourceSeqs)
960
- ? [...new Set(restoredSourceSeqs.filter((q) => Number.isSafeInteger(q)))]
961
- : [];
1041
+ const restored = Array.isArray(restoredSourceSeqs) ? [...new Set(restoredSourceSeqs.filter(q => Number.isSafeInteger(q)))] : []
962
1042
  return {
963
- type: "system/message",
1043
+ type: 'system/message',
964
1044
  seq,
965
1045
  time,
966
1046
  data: {
967
1047
  turn: turnStep.turn,
968
1048
  step: turnStep.step,
969
- message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
1049
+ message: { id: randomUUID(), role: 'system', source: messageSource('system', version), content: [{ type: 'text', text }] },
970
1050
  restoresSeq: restoreSeq,
971
1051
  ...(restored.length > 0 ? { restoredSourceSeqs: restored } : {}),
972
1052
  ...(discard ? { discarded: true } : {}),
973
1053
  },
974
- surfaceOp: "append",
975
- };
1054
+ surfaceOp: 'append',
1055
+ }
976
1056
  }
977
1057
 
978
1058
  /**
@@ -986,15 +1066,17 @@ export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq,
986
1066
  * 而 `diskAppend` 是裸 zstd 写、零校验,拦不住。
987
1067
  */
988
1068
  export function buildReplayEvent({ seq, time, item, turnStep, version = 4 }) {
989
- const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0
990
- && Number.isSafeInteger(turnStep.step) && turnStep.step > 0
991
- ? turnStep
992
- : (() => { throw new OpsError("buildReplayEvent: 缺少合法的打开 turn/step,拒绝写出注定无法加载的事件", 500); })();
1069
+ const ts =
1070
+ turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0 && Number.isSafeInteger(turnStep.step) && turnStep.step > 0
1071
+ ? turnStep
1072
+ : (() => {
1073
+ throw new OpsError('buildReplayEvent: 缺少合法的打开 turn/step,拒绝写出注定无法加载的事件', 500)
1074
+ })()
993
1075
  return {
994
1076
  type: item.type,
995
1077
  seq,
996
1078
  time,
997
1079
  data: replayEventData(item, ts, version),
998
- surfaceOp: "append",
999
- };
1080
+ surfaceOp: 'append',
1081
+ }
1000
1082
  }