@240xu/dsh-message-ops 0.24.0 → 0.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +653 -0
- package/package.json +8 -4
- package/src/auth.js +274 -0
- package/src/client/00-core.js +284 -0
- package/src/client/10-i18n.js +260 -0
- package/src/client/20-host-state.js +311 -0
- package/src/client/30-panel.js +1478 -0
- package/src/client/40-edit.js +189 -0
- package/src/client/50-inline-edit.js +348 -0
- package/src/client/60-session.js +353 -0
- package/src/client/70-revert.js +679 -0
- package/src/client/80-inject.js +864 -0
- package/src/client/85-sidebar.js +368 -0
- package/src/client/90-apply.js +126 -0
- package/src/client.js +1906 -1277
- package/src/derived-incremental.js +787 -0
- package/src/host-services.js +84 -0
- package/src/index.js +1100 -280
- package/src/ops-core.js +624 -362
- package/src/ops-write.js +301 -0
- package/src/session-file.js +145 -22
- package/src/session-trash.js +495 -42
- package/src/write-lock.js +48 -0
package/src/ops-core.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomUUID
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
2
|
|
|
3
3
|
/** OpsError 单点在 session-file.js(computeShadowed 护栏也在那里抛它);此处转出保持既有导入面。 */
|
|
4
4
|
export { OpsError } from './session-file.js'
|
|
@@ -21,7 +21,7 @@ import { OpsError } from './session-file.js'
|
|
|
21
21
|
* @module dsh-message-ops/ops-core
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
-
import { readReplaceOp, messageText, messageTextFull, computeShadowed } from './session-file.js'
|
|
24
|
+
import { readReplaceOp, messageText, messageTextFull, computeShadowed, looksLikeOwnMarker, MARKER_TEXT_PREFIXES } from './session-file.js'
|
|
25
25
|
|
|
26
26
|
// messageText 的单点实现在 session-file.js(listMessages 同用);此处转出保持
|
|
27
27
|
// 既有导入面兼容(ops-core 的 messageText 调用方不受影响)。
|
|
@@ -38,16 +38,50 @@ export { messageText }
|
|
|
38
38
|
* 界面上表现为「恢复之后又多出一条『回滚后的节点』」。实测语料里已经出现过
|
|
39
39
|
* 5 次(seq 3424/3658/3689/3721/3746),全部由 dock 用 `mk.seq` 当目标造成。
|
|
40
40
|
*/
|
|
41
|
+
export { MARKER_TEXT_PREFIXES }
|
|
42
|
+
|
|
43
|
+
/** 任何带 well-formed replace surfaceOp 的 system/message(含宿主的系统提示改写)。 */
|
|
41
44
|
export function isMarkerEvent(e) {
|
|
42
45
|
return !!e && e.type === 'system/message' && readReplaceOp(e) !== null
|
|
43
46
|
}
|
|
44
47
|
|
|
48
|
+
/**
|
|
49
|
+
* 本插件写的回撤/删除标记(而不是宿主的 compaction checkpoint / 系统提示改写 / tool 改写)。
|
|
50
|
+
*
|
|
51
|
+
* 宿主自己也写 replace 事件(语料:compaction checkpoint 5 条、system 改写 137 条、
|
|
52
|
+
* tool 改写 182 条);它们同样是 `system/message` 或 user/message + replace op。
|
|
53
|
+
* 只按「有 replace op」判定会把压缩前的整段历史当回撤标记恢复出去(上下文回涨)。
|
|
54
|
+
*/
|
|
55
|
+
export function isOwnMarkerEvent(e) {
|
|
56
|
+
if (!isMarkerEvent(e)) return false
|
|
57
|
+
if (e.type !== 'system/message') return false
|
|
58
|
+
const src = e.data && e.data.message && e.data.message.source
|
|
59
|
+
// 只认 system 消息(compaction checkpoint 是 user/message,tool 改写是 tool/result)。
|
|
60
|
+
if (src && (typeof src.kind !== 'string' || !src.kind.startsWith('system'))) return false
|
|
61
|
+
// 0.33.0(宿主契约):身份判据改为**正向**证据 —— data.opsMarker 或正文前缀。
|
|
62
|
+
// 旧的「sources 含字面量 0」守卫在真实日志里恒不命中(surface 头节点是 seq 5/6),
|
|
63
|
+
// 于是宿主的单节点系统提示改写也被当成自有 marker(语料 227/234 条)。
|
|
64
|
+
return looksLikeOwnMarker(e)
|
|
65
|
+
}
|
|
66
|
+
|
|
45
67
|
export function planRevert(surface, targetSeq) {
|
|
46
68
|
const nodes = surface && Array.isArray(surface.nodes) ? surface.nodes : []
|
|
47
69
|
const startIdx = nodes.indexOf(targetSeq)
|
|
48
70
|
if (startIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409)
|
|
49
71
|
const shadowedSeqs = nodes.slice(startIdx)
|
|
50
72
|
if (shadowedSeqs.length === 0) throw new OpsError('nothing to revert', 409)
|
|
73
|
+
// 0.26.0:节点 0 保护面(宿主 assertSystemHeadRewrite,见 systemHeadRejection 的
|
|
74
|
+
// 长注释)。live 路径拿到的是宿主**真实** surface,头节点即 system prompt,
|
|
75
|
+
// 多节点回滚它会被宿主拒绝整份日志 —— 规划层必须同判(磁盘路径已同判)。
|
|
76
|
+
const head = nodes[0]
|
|
77
|
+
const headEvent = head === targetSeq ? surfaceHeadEventOf(surface) : null
|
|
78
|
+
if (startIdx === 0 && headEvent && headEvent.type === 'system/message' && shadowedSeqs.length !== 1) {
|
|
79
|
+
throw new OpsError(
|
|
80
|
+
'surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node' +
|
|
81
|
+
`(目标 seq ${targetSeq} 是 surface 头节点,回滚它会把系统提示连同后面 ${shadowedSeqs.length - 1} 个节点一起遮蔽 —— 宿主会整份拒绝该日志)`,
|
|
82
|
+
409,
|
|
83
|
+
)
|
|
84
|
+
}
|
|
51
85
|
return {
|
|
52
86
|
startSeq: targetSeq,
|
|
53
87
|
endSeq: shadowedSeqs[shadowedSeqs.length - 1],
|
|
@@ -55,10 +89,34 @@ export function planRevert(surface, targetSeq) {
|
|
|
55
89
|
}
|
|
56
90
|
}
|
|
57
91
|
|
|
92
|
+
/**
|
|
93
|
+
* live surface 对象的头事件(宿主 `SurfaceManager` 只暴露 `nodes`,不带事件本体)。
|
|
94
|
+
*
|
|
95
|
+
* 无事件可查时按**保守**口径处理:live surface 的节点 0 在真实会话里恒为
|
|
96
|
+
* system prompt(语料 240/240 份如此),故把「头节点 + 多节点遮蔽」一律拒绝,
|
|
97
|
+
* 而不是放行后让宿主把整份日志拒掉(后者用户无法自救)。
|
|
98
|
+
*/
|
|
99
|
+
function surfaceHeadEventOf(surface) {
|
|
100
|
+
const events = surface && Array.isArray(surface.events) ? surface.events : null
|
|
101
|
+
if (events) {
|
|
102
|
+
const seq = surface.nodes[0]
|
|
103
|
+
return events.find(e => e && e.seq === seq) || { type: 'system/message' }
|
|
104
|
+
}
|
|
105
|
+
return { type: 'system/message', assumed: true }
|
|
106
|
+
}
|
|
107
|
+
|
|
58
108
|
/** planDelete:单条遮蔽,要求 seq 仍在当前 surface 上可见。 */
|
|
59
109
|
export function planDelete(surface, seq) {
|
|
60
110
|
const nodes = surface && Array.isArray(surface.nodes) ? surface.nodes : []
|
|
61
|
-
if (!nodes.includes(seq))
|
|
111
|
+
if (!nodes.includes(seq)) {
|
|
112
|
+
const all = surface && Array.isArray(surface.allNodes) ? surface.allNodes : null
|
|
113
|
+
// live 面没有全量事件(只有 surface.nodes):无法判定「不存在」时保持 409
|
|
114
|
+
if (all && !all.includes(seq)) throw new OpsError(`seq ${seq} not found in this session surface`, 404)
|
|
115
|
+
throw new OpsError(`seq ${seq} not visible on current surface`, 409)
|
|
116
|
+
}
|
|
117
|
+
// 单节点遮蔽恒满足宿主的 node-0 豁免(system/message over exactly that node),
|
|
118
|
+
// 故 delete 不额外拒绝;但 marker 仍不得当目标(与磁盘路径同判,planDeleteFromEvents
|
|
119
|
+
// 侧有事件本体可判,这条在 live 路径由调用方给事件,见 opsCommit 的 isMarkerEvent 闸)。
|
|
62
120
|
return { startSeq: seq, endSeq: seq, shadowedSeqs: [seq] }
|
|
63
121
|
}
|
|
64
122
|
|
|
@@ -132,6 +190,34 @@ function messageSource(role, version) {
|
|
|
132
190
|
return { kind: 'plugin', plugin: PLUGIN_NAME, role: r }
|
|
133
191
|
}
|
|
134
192
|
|
|
193
|
+
/**
|
|
194
|
+
* 重放副本的 source —— 必须保持 `kind: 'user'`。
|
|
195
|
+
*
|
|
196
|
+
* 宿主 `messageDefinition.start`(dsh-client-ui-chat)只把 `source.kind === 'user'`
|
|
197
|
+
* 的 user/message 渲染成用户气泡;其余 kind 一律降级成 context 注入,落进
|
|
198
|
+
* 「过程」折叠区、正文不显示。旧实现用 `plugin:<name>` 区分副本,直接后果是
|
|
199
|
+
* **恢复出来的提问在界面上消失**(真机实测:只剩助手回答)。
|
|
200
|
+
*
|
|
201
|
+
* 副本用 `replayedFrom` 自识别:`markCommitted` / `applyLiveCommitted` 据此排除,
|
|
202
|
+
* 否则"恢复"会立刻被当成"用户又说了话"而提交 marker,dock 一恢复就消失。
|
|
203
|
+
*
|
|
204
|
+
* @param {{seq?:number}} item 重放项(`seq` 是原消息 seq)
|
|
205
|
+
* @returns {object} v3/v4 都合法的 source:真人输入为 `{kind:'user', rpcId, replayedFrom}`,
|
|
206
|
+
* 注入行保留原 kind 与其它字段并附加 `replayedFrom`
|
|
207
|
+
*/
|
|
208
|
+
function userReplaySource(item) {
|
|
209
|
+
const from = item && item.seq
|
|
210
|
+
const replayedFrom = Number.isSafeInteger(from) ? from : null
|
|
211
|
+
const original = item && item.source
|
|
212
|
+
const kind = original && typeof original.kind === 'string' && original.kind ? original.kind : 'user'
|
|
213
|
+
// 真人输入:新 rpcId(副本不是那次发送)、kind 必须仍是 user。
|
|
214
|
+
if (kind === 'user') return { kind: 'user', rpcId: randomUUID(), replayedFrom }
|
|
215
|
+
// 注入行(time-context / tool-jobs / agent-instructions / runtime-context …):
|
|
216
|
+
// 保留原 kind —— 宿主仍把它渲染成注入上下文,不会伪造出一条"用户发言"。
|
|
217
|
+
// 真机实测:旧实现把 time-context 副本写成 plugin:* → 恢复后以用户消息形态出现。
|
|
218
|
+
return { ...original, kind, replayedFrom }
|
|
219
|
+
}
|
|
220
|
+
|
|
135
221
|
function assistantReplaySource(item, version) {
|
|
136
222
|
const source = item && item.source
|
|
137
223
|
if (version === 4) {
|
|
@@ -168,7 +254,7 @@ export function replayEventData(item, ts, version = 4) {
|
|
|
168
254
|
return {
|
|
169
255
|
id: item.id ?? randomUUID(),
|
|
170
256
|
role: 'user',
|
|
171
|
-
source:
|
|
257
|
+
source: userReplaySource(item),
|
|
172
258
|
content: [{ type: 'text', text: item.text }],
|
|
173
259
|
}
|
|
174
260
|
}
|
|
@@ -255,13 +341,66 @@ export function deriveTurnStep(events) {
|
|
|
255
341
|
* preamble?: Array, postamble?: Array}}
|
|
256
342
|
*/
|
|
257
343
|
/** 合成 turn 落盘后,把宿主 idle agent 的 turn 游标对齐到该 turn(否则下一条真实消息会重号)。 */
|
|
258
|
-
|
|
344
|
+
/** 取 live 会话对应的宿主动机(属性优先、ctx.get 兜底;两者都没有返回 null)。 */
|
|
345
|
+
export function liveAgentOf(ctx, session, agentsOverride) {
|
|
346
|
+
if (!session || typeof session.id !== 'string') return null
|
|
347
|
+
// 0.39.4:宿主 0.2.3 的 fiber 隔离下插件 fiber 里 `ctx.get('agents')` 可能恒
|
|
348
|
+
// undefined;调用方用 `ctx.inject` 预捕获后从第 3 参传入(与
|
|
349
|
+
// alignLiveTurnCursor 同口径)。srv-audit D1:运行中闸门曾因此在真机形态下失效。
|
|
350
|
+
let agents = null
|
|
351
|
+
if (agentsOverride && typeof agentsOverride.get === 'function') agents = agentsOverride
|
|
352
|
+
try {
|
|
353
|
+
if (agents) {
|
|
354
|
+
/* 已用捕获实例 */
|
|
355
|
+
} else if (ctx && ctx.agents) agents = ctx.agents
|
|
356
|
+
} catch {
|
|
357
|
+
/* getter threw */
|
|
358
|
+
}
|
|
359
|
+
if (!agents) {
|
|
360
|
+
try {
|
|
361
|
+
agents = ctx && typeof ctx.get === 'function' ? ctx.get('agents') : null
|
|
362
|
+
} catch {
|
|
363
|
+
/* absent */
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
return agents && typeof agents.get === 'function' ? agents.get(session.id) : null
|
|
368
|
+
} catch {
|
|
369
|
+
return null
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* 合成 turn 前置闸:宿主动机不是 idle(running / maintenance…)时**不要写**合成窗口。
|
|
375
|
+
*
|
|
376
|
+
* 为什么必须拒绝而不是写完再对齐:`alignLiveTurnCursor` 只在 `phase.kind === 'idle'`
|
|
377
|
+
* 时推进 `lastTurn`;maintenance 结束会用**进入前的** lastTurn 还原。写进去的
|
|
378
|
+
* turn/start(N) 就会和宿主下一轮使用的 N 重号,加载端关系闸拒绝整份日志
|
|
379
|
+
* (`turn/start does not open the expected turn`)→ 会话直接打不开。
|
|
380
|
+
*/
|
|
381
|
+
export function livePhaseError(ctx, session, agentsOverride) {
|
|
382
|
+
const agent = liveAgentOf(ctx, session, agentsOverride)
|
|
383
|
+
if (!agent) return null
|
|
384
|
+
const phase = agent.phase
|
|
385
|
+
const kind = phase && typeof phase.kind === 'string' ? phase.kind : null
|
|
386
|
+
if (kind && kind !== 'idle') return new OpsError(`session is busy (agent phase ${kind}); stop it and retry`, 409)
|
|
387
|
+
return null
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
export function alignLiveTurnCursor(ctx, session, turn, agentsOverride) {
|
|
259
391
|
if (!Number.isSafeInteger(turn) || turn < 1 || !session || typeof session.id !== 'string') return false
|
|
260
392
|
// 0.11.4:插件 `inject` 故意留空(tools 是可选增强),因此 `ctx.agents`
|
|
261
393
|
// **属性访问恒为 undefined** —— 旧实现只写 `ctx.agents`,这条对齐从来没执行过。
|
|
262
394
|
// 实测 `ctx.get("agents")` 在 HTTP 请求期可解析(同 resolveSession 的取法),
|
|
263
395
|
// 故属性优先、ctx.get 兜底。
|
|
396
|
+
// 0.37.4:宿主 0.2.3 上首两种取法都可能拿不到(fiber 隔离),调用方可通过
|
|
397
|
+
// `ctx.inject(['agents'])` 预捕获服务并从这里传入。
|
|
264
398
|
let agents = null
|
|
399
|
+
try {
|
|
400
|
+
if (agentsOverride) agents = agentsOverride
|
|
401
|
+
} catch {
|
|
402
|
+
/* override getter threw */
|
|
403
|
+
}
|
|
265
404
|
try {
|
|
266
405
|
if (ctx && ctx.agents) agents = ctx.agents
|
|
267
406
|
} catch {
|
|
@@ -371,6 +510,9 @@ export function noticeWindowPostamble(win) {
|
|
|
371
510
|
* @param {unknown} value 存储形态(整数与/或 `[start, end]` 闭区间)
|
|
372
511
|
* @returns {number[]} 去重后保持首次出现顺序的整数序列
|
|
373
512
|
*/
|
|
513
|
+
/** 与 session-file.computeShadowed 同值的区间上限(单条 marker 最多展开多少 seq)。 */
|
|
514
|
+
export const MAX_SPAN = 1_000_000
|
|
515
|
+
|
|
374
516
|
export function expandSourceSeqs(value) {
|
|
375
517
|
const out = []
|
|
376
518
|
const seen = new Set()
|
|
@@ -387,6 +529,9 @@ export function expandSourceSeqs(value) {
|
|
|
387
529
|
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end < start) {
|
|
388
530
|
throw new OpsError('surface replace source ranges require integer start <= end', 500)
|
|
389
531
|
}
|
|
532
|
+
if (end - start > MAX_SPAN) {
|
|
533
|
+
throw new OpsError(`surface replace source range too large: [${start}..${end}] exceeds MAX_SPAN=${MAX_SPAN}`, 404)
|
|
534
|
+
}
|
|
390
535
|
for (let seq = start; seq <= end; seq += 1) push(seq)
|
|
391
536
|
} else {
|
|
392
537
|
push(entry)
|
|
@@ -401,7 +546,13 @@ export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs,
|
|
|
401
546
|
const data = {
|
|
402
547
|
turn: ts.turn,
|
|
403
548
|
step: ts.step,
|
|
404
|
-
|
|
549
|
+
// 0.33.0(宿主 P0):正文**不写进 content**。宿主 SystemPromptProjection 把
|
|
550
|
+
// 每个非空 system/message 当系统提示节点:append 型会追加重复 prompt 并让正文
|
|
551
|
+
// 进模型上下文,replace 型会在下一 series 被改写成空。记账文案放 data.text,
|
|
552
|
+
// 宿主格式闸与运行时闸均 PASS(实测),模型不再可见。
|
|
553
|
+
message: { id: randomUUID(), role: 'system', source: messageSource('system', 4), content: [] },
|
|
554
|
+
text: noticeText,
|
|
555
|
+
opsMarker: 'message-ops/v1',
|
|
405
556
|
}
|
|
406
557
|
if (replaceShape) {
|
|
407
558
|
return session.append('system/message', data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs: sources })
|
|
@@ -430,22 +581,66 @@ export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
|
|
|
430
581
|
if (!Number.isSafeInteger(restoreSeq) || restoreSeq < 0) throw new OpsError('invalid seq', 400)
|
|
431
582
|
const ev = events.find(e => e && e.seq === restoreSeq)
|
|
432
583
|
if (!ev) throw new OpsError(`restore: event seq ${restoreSeq} not found in log`, 404)
|
|
584
|
+
// 0.27.0:已被后续回撤取代的 marker **不再是可恢复对象**。
|
|
585
|
+
//
|
|
586
|
+
// 真机复现:回撤到第二条(M1)→ 再回撤到第一条(M2,区间覆盖 M1)→ dock 里
|
|
587
|
+
// M1 仍在待恢复列表;点恢复把「第二条/第三条」重放回末尾,而这三条正是用户
|
|
588
|
+
// 刚刚回撤掉的。语义上 M1 已被 M2 取代,恢复它等于绕过 M2。
|
|
589
|
+
// 判据见 supersededByMarker(排除了只覆盖 marker 自己的「自噬」记录)。
|
|
590
|
+
const fold = foldSurfaceNodes(events)
|
|
591
|
+
const superseder = supersededByMarker(fold, restoreSeq)
|
|
592
|
+
if (superseder !== null) {
|
|
593
|
+
throw new OpsError(
|
|
594
|
+
`restore: marker seq ${restoreSeq} is shadowed by a later revert (seq ${superseder}) — restore that later marker first` +
|
|
595
|
+
`(该回撤标记已被后续回撤遮蔽;先恢复后一次回撤,否则会把已经回撤掉的内容重新放出来)`,
|
|
596
|
+
409,
|
|
597
|
+
)
|
|
598
|
+
}
|
|
433
599
|
// 读取端拼写统一走 session-file 的 readReplaceOp(双拼写兼容的单点)。
|
|
434
600
|
const range = readReplaceOp(ev)
|
|
435
601
|
if (!range) {
|
|
436
602
|
throw new OpsError(`restore: seq ${restoreSeq} is not a revert/delete marker event (no well-formed replace surfaceOp)`, 409)
|
|
437
603
|
}
|
|
604
|
+
if (!isOwnMarkerEvent(ev)) {
|
|
605
|
+
throw new OpsError(
|
|
606
|
+
`restore: seq ${restoreSeq} is not a message-ops revert marker (it is a host surface rewrite such as a compaction checkpoint) — refusing to replay its shadowed history`,
|
|
607
|
+
409,
|
|
608
|
+
)
|
|
609
|
+
}
|
|
438
610
|
const { startSeq, endSeq } = range
|
|
439
611
|
// 0.8.0 按轮步进:upToSeq 给定则只重放到该 seq(含),后续仍保持遮蔽;
|
|
440
612
|
// excludeSeqs = 已重放过(先前轮次 notice 的 restoredSourceSeqs 并集),
|
|
441
613
|
// **必须排除,否则每轮都从区间头重放 → 消息副本刷屏**(0.8.0 实测 B1)。
|
|
442
|
-
|
|
614
|
+
//
|
|
615
|
+
// 0.26.0(根因修正):候选集必须是**该 marker 真正遮蔽的节点**,不是数值区间。
|
|
616
|
+
// 宿主 foldSurface 用节点索引 splice,数值区间会**连带把早先 marker 已遮蔽的
|
|
617
|
+
// 节点算进来** → 重放用户根本没回滚过的消息。实测 session-ab6f marker 1197:
|
|
618
|
+
// 区间 89..1191 里数值候选 151 条,宿主遮蔽集只有 `[89, 90, 1191]` —— 旧实现会把
|
|
619
|
+
// 149 条早已被遮蔽的历史消息当作"恢复对象"重放出去(复原的是别人回滚掉的内容)。
|
|
620
|
+
const shadowed = markerShadowedSeqs(events, ev, fold)
|
|
621
|
+
// 数值区间仅用于「无法判定遮蔽集」的历史/损坏 marker(markerShadowedSeqs 返回 null)。
|
|
622
|
+
// 反向区间(start > end)在数值口径下**没有语义**(宿主是节点索引区间)——
|
|
623
|
+
// 猜 min..max 会重放用户根本没回滚过的消息,故此时一律不出候选(与
|
|
624
|
+
// `computeShadowed` 对无凭据反向 marker 的历史约定一致:视为未遮蔽任何东西)。
|
|
625
|
+
const numericOnly = shadowed == null && startSeq <= endSeq
|
|
626
|
+
const numericCap = Number.isSafeInteger(upToSeq) ? Math.min(upToSeq, Math.max(startSeq, endSeq)) : Math.max(startSeq, endSeq)
|
|
627
|
+
const fallbackSpan = numericOnly ? { lo: Math.min(startSeq, endSeq), hi: numericCap } : null
|
|
628
|
+
// shadowed == null 且反向区间 → 空集(不猜)。numericOnly 时此集不参与判定。
|
|
629
|
+
const shadowedSet = shadowed == null ? new Set() : new Set(shadowed.filter(q => Number.isSafeInteger(q)))
|
|
630
|
+
const stepCap = Number.isSafeInteger(upToSeq) ? upToSeq : null
|
|
443
631
|
const excluded = Array.isArray(excludeSeqs) ? new Set(excludeSeqs.filter(q => Number.isSafeInteger(q))) : null
|
|
444
632
|
const replayable = []
|
|
445
633
|
let skipped = 0
|
|
446
634
|
for (const e of events) {
|
|
447
|
-
if (!e || typeof e.seq !== 'number'
|
|
448
|
-
if (
|
|
635
|
+
if (!e || typeof e.seq !== 'number') continue
|
|
636
|
+
if (numericOnly) {
|
|
637
|
+
if (e.seq < fallbackSpan.lo || e.seq > fallbackSpan.hi) continue
|
|
638
|
+
} else {
|
|
639
|
+
if (!shadowedSet.has(e.seq)) continue
|
|
640
|
+
// 按轮步进:落在 upToSeq 之后的候选仍保持遮蔽(不计 skipped,它们不是"跳过")
|
|
641
|
+
if (stepCap !== null && e.seq > stepCap) continue
|
|
642
|
+
}
|
|
643
|
+
if (isReplayableMessage(e)) {
|
|
449
644
|
if (excluded && excluded.has(e.seq)) continue
|
|
450
645
|
// 0.23.0(深挖 S-1):重放必须取**全段**。宿主把长文本拆成多个 content
|
|
451
646
|
// 段(compaction checkpoint 实测 321+7954+20 三段),旧实现用 messageText
|
|
@@ -461,24 +656,42 @@ export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
|
|
|
461
656
|
type: e.type,
|
|
462
657
|
role: e.type === 'user/message' ? 'user' : 'assistant',
|
|
463
658
|
text,
|
|
464
|
-
|
|
659
|
+
// user 反向也带 source:注入行要按原 kind 重放(见 userReplaySource)。
|
|
660
|
+
source:
|
|
661
|
+
e.type === 'assistant/message'
|
|
662
|
+
? e.data && e.data.message
|
|
663
|
+
? e.data.message.source
|
|
664
|
+
: undefined
|
|
665
|
+
: e.data && e.data.source
|
|
666
|
+
? e.data.source
|
|
667
|
+
: undefined,
|
|
465
668
|
})
|
|
466
669
|
} else {
|
|
467
|
-
|
|
670
|
+
// tool/*、system/* 与注入行(非真实用户输入)都不是重放对象:跳过并计数
|
|
671
|
+
skipped++
|
|
468
672
|
}
|
|
469
673
|
}
|
|
470
674
|
// 0.5.6:区间无可重放消息(如只遮蔽了 tool/system 事件)不再 409 ——
|
|
471
675
|
// dock 会为这类标记常驻显示恢复按钮,409 死按钮 = 永远清不掉(实测 8 连 409)。
|
|
472
|
-
// 改为返回空计划:
|
|
676
|
+
// 改为返回空计划:ops-write 的脚本仍会追加说明 notice(含 restoresSeq)→ 标记停用、
|
|
473
677
|
// dock 计数递减;语义如实:0 条重放 + 文案说明区间无 user/assistant 内容。
|
|
474
|
-
|
|
678
|
+
const top = Math.max(startSeq, endSeq)
|
|
679
|
+
const effectiveUpTo = stepCap === null ? top : Math.min(stepCap, top)
|
|
680
|
+
return { restoreSeq, startSeq, endSeq, upToSeq: effectiveUpTo, replayable, skipped }
|
|
475
681
|
}
|
|
476
682
|
|
|
477
683
|
/**
|
|
478
|
-
*
|
|
479
|
-
*
|
|
480
|
-
*
|
|
684
|
+
* 停用(discard)文案:live append 与磁盘路径共用,避免两处各写一份、改一处漏一处。
|
|
685
|
+
* @param {object} plan 恢复计划(planRestore 的返回值)
|
|
686
|
+
* @returns {string} 说明文本
|
|
481
687
|
*/
|
|
688
|
+
export function restoreDiscardText(plan) {
|
|
689
|
+
return (
|
|
690
|
+
`[消息操作] 回撤标记 seq ${plan.restoreSeq} 已停用(丢弃):区间内容保持遮蔽、未重放;` +
|
|
691
|
+
`日志原文仍在,可搜索`
|
|
692
|
+
)
|
|
693
|
+
}
|
|
694
|
+
|
|
482
695
|
/** 恢复说明文案(live append 与磁盘路径共用;空可重放 = 停用语义)。 */
|
|
483
696
|
export function restoreNoticeText(plan) {
|
|
484
697
|
return plan.replayable.length === 0
|
|
@@ -490,41 +703,6 @@ export function restoreNoticeText(plan) {
|
|
|
490
703
|
`;原区间仍处于遮蔽状态,恢复为重放而非解除遮蔽`
|
|
491
704
|
}
|
|
492
705
|
|
|
493
|
-
export function applyRestore(session, plan, { flush } = {}) {
|
|
494
|
-
const eventSeqs = []
|
|
495
|
-
const notice = plan.discard
|
|
496
|
-
? `[消息操作] 回撤标记 seq ${plan.restoreSeq} 已停用(丢弃):区间内容保持遮蔽、未重放;日志原文仍在,可搜索`
|
|
497
|
-
: restoreNoticeText(plan)
|
|
498
|
-
// 0.4.2:notice 事件携带 restoresSeq —— dock 据此把被恢复的标记从「活跃回撤」
|
|
499
|
-
// 中移除(对齐 opencode clear 语义:恢复后不再显示为待恢复项)。
|
|
500
|
-
const ts = plan.turnStep && Number.isSafeInteger(plan.turnStep.turn) && plan.turnStep.turn > 0 ? plan.turnStep : { turn: 1, step: 1 }
|
|
501
|
-
const noticeEvent = session.append(
|
|
502
|
-
'system/message',
|
|
503
|
-
{
|
|
504
|
-
turn: ts.turn,
|
|
505
|
-
step: ts.step,
|
|
506
|
-
message: { id: randomUUID(), role: 'system', source: messageSource('system', 4), content: [{ type: 'text', text: notice }] },
|
|
507
|
-
restoresSeq: plan.restoreSeq,
|
|
508
|
-
restoredSourceSeqs: plan.discard ? [] : plan.replayable.map(i => i.seq),
|
|
509
|
-
...(plan.discard ? { discarded: true } : {}),
|
|
510
|
-
},
|
|
511
|
-
{ surfaceOp: 'append' },
|
|
512
|
-
)
|
|
513
|
-
if (noticeEvent && noticeEvent.seq != null) eventSeqs.push(noticeEvent.seq)
|
|
514
|
-
for (const item of plan.discard ? [] : plan.replayable) {
|
|
515
|
-
const event = session.append(item.type, replayEventData(item, ts), { surfaceOp: 'append' })
|
|
516
|
-
if (event && event.seq != null) eventSeqs.push(event.seq)
|
|
517
|
-
}
|
|
518
|
-
if (flush) {
|
|
519
|
-
try {
|
|
520
|
-
flush()
|
|
521
|
-
} catch {
|
|
522
|
-
/* flush 失败不回滚已接受的事件 */
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
return { restoredCount: plan.discard ? 0 : plan.replayable.length, skipped: plan.skipped, eventSeqs }
|
|
526
|
-
}
|
|
527
|
-
|
|
528
706
|
/**
|
|
529
707
|
* 0.8.0:计算一次 revert/delete 标记的「恢复进度」。
|
|
530
708
|
*
|
|
@@ -536,22 +714,94 @@ export function applyRestore(session, plan, { flush } = {}) {
|
|
|
536
714
|
* - complete:是否已全部恢复(标记不再活跃)
|
|
537
715
|
* - legacy:旧通知(无 restoredSourceSeqs 字段)→ 视为整段已恢复
|
|
538
716
|
*/
|
|
717
|
+
/**
|
|
718
|
+
* 可重放候选 = 真实用户输入 + 助手回复。
|
|
719
|
+
*
|
|
720
|
+
* 注入行(runtime-context / system-reminder / time-context / skill-catalog …)虽然
|
|
721
|
+
* 也是 user/message 且带文本,但它们**不是对话内容**:宿主下一轮会重新注入,
|
|
722
|
+
* 重放只会把内部提示再发一遍,并在 dock 里生成「#35」这种无意义行 ——
|
|
723
|
+
* 真机实测:回撤一条用户消息,展开框出现 4 行,其中 3 行是 #35/#36/#37。
|
|
724
|
+
*
|
|
725
|
+
* @param {object} e 会话事件
|
|
726
|
+
* @returns {boolean} 是否可作为恢复(重放)对象
|
|
727
|
+
*/
|
|
728
|
+
function isReplayableMessage(e) {
|
|
729
|
+
if (!e) return false
|
|
730
|
+
if (e.type === 'assistant/message') return true
|
|
731
|
+
if (e.type !== 'user/message') return false
|
|
732
|
+
const d = e.data
|
|
733
|
+
// v4 把消息本体摊在 data 上;v3/旧日志包在 data.message 里(两套读法都要认)。
|
|
734
|
+
const source =
|
|
735
|
+
d && d.source && typeof d.source === 'object'
|
|
736
|
+
? d.source
|
|
737
|
+
: d && d.message && d.message.source && typeof d.message.source === 'object'
|
|
738
|
+
? d.message.source
|
|
739
|
+
: null
|
|
740
|
+
// 没有 source 的旧日志 / 夹具:按用户内容处理(真实 v4 注入行一定带 kind)
|
|
741
|
+
if (!source) return true
|
|
742
|
+
// 0.33.2:恢复副本(带 replayedFrom)**可以**成为候选 —— 候选集只包含「被更晚的
|
|
743
|
+
// marker 遮蔽」的节点,那正是副本被再次回撤的场景;排除它会导致
|
|
744
|
+
// 「回撤 → 恢复 → 再回撤 → 恢复」永久丢掉被回撤的用户提问(有答无问,
|
|
745
|
+
// restoredSourceSeqs 也少一条)。重复重放由 excludeSeqs/restoredSeqs 去重。
|
|
746
|
+
return source.kind === 'user'
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* 「该 marker 的可重放候选集」单点口径(restoreProgress 直算版与索引版共用)。
|
|
751
|
+
*
|
|
752
|
+
* 0.26.0:候选取**宿主遮蔽集**(`markerShadowedSeqs`),不再取数值区间。
|
|
753
|
+
* 与 `planRestore` 的候选集同源,二者因此不会再出现「进度说还有 151 条待恢复、
|
|
754
|
+
* 实际只能恢复 2 条」的分裂。空文本消息仍然不算候选(重放不出内容)。
|
|
755
|
+
*
|
|
756
|
+
* 兜底:抹蔽集无法判定(历史损坏 marker)时退回数值区间,与旧行为一致。
|
|
757
|
+
*
|
|
758
|
+
* @param {Array} events 全量事件
|
|
759
|
+
* @param {object} marker 标记事件
|
|
760
|
+
* @param {{startSeq:number,endSeq:number}} range marker 的 replace 区间
|
|
761
|
+
* @returns {number[]} 候选 seq(升序)
|
|
762
|
+
*/
|
|
763
|
+
function restoreCandidates(events, marker, range, fold = null) {
|
|
764
|
+
const shadowed = markerShadowedSeqs(events, marker, fold)
|
|
765
|
+
const candidates = []
|
|
766
|
+
if (shadowed) {
|
|
767
|
+
const set = new Set(shadowed.filter(q => Number.isSafeInteger(q)))
|
|
768
|
+
for (const e of events) {
|
|
769
|
+
if (!e || typeof e.seq !== 'number' || !set.has(e.seq)) continue
|
|
770
|
+
if (!isReplayableMessage(e)) continue
|
|
771
|
+
if (!messageTextFull(e).trim()) continue
|
|
772
|
+
candidates.push(e.seq)
|
|
773
|
+
}
|
|
774
|
+
// 升序:宿主遮蔽集按**节点序**(compaction checkpoint 的反向区间会得到非升序
|
|
775
|
+
// 数组),而贴条按行展示与 step 步进都假定升序(旧实现天然升序)。
|
|
776
|
+
return candidates.sort((a, b) => a - b)
|
|
777
|
+
}
|
|
778
|
+
const lo = Math.min(range.startSeq, range.endSeq)
|
|
779
|
+
const hi = Math.max(range.startSeq, range.endSeq)
|
|
780
|
+
// 反向区间(start > end)且遮蔽集无法判定(无凭据、折叠也定位不到端点)→
|
|
781
|
+
// 与 `computeShadowed` 的历史约定一致:**视为未遮蔽任何东西**,不拿 min..max
|
|
782
|
+
// 去猜。数值区间对反向 marker 没有语义(宿主是节点索引区间),瞎猜会重放
|
|
783
|
+
// 用户根本没回滚过的消息。
|
|
784
|
+
if (range.startSeq > range.endSeq) return []
|
|
785
|
+
for (const e of events) {
|
|
786
|
+
if (!e || typeof e.seq !== 'number' || e.seq < lo || e.seq > hi) continue
|
|
787
|
+
if (!isReplayableMessage(e)) continue
|
|
788
|
+
if (!messageTextFull(e).trim()) continue
|
|
789
|
+
candidates.push(e.seq)
|
|
790
|
+
}
|
|
791
|
+
return candidates
|
|
792
|
+
}
|
|
793
|
+
|
|
539
794
|
export function restoreProgress(events, markerSeq) {
|
|
540
795
|
const list = Array.isArray(events) ? events : []
|
|
541
796
|
const marker = list.find(e => e && e.seq === markerSeq)
|
|
542
797
|
if (!marker) return null
|
|
543
798
|
const range = readReplaceOp(marker)
|
|
544
799
|
if (!range) return null
|
|
800
|
+
// 宿主的 replace 事件(compaction checkpoint / 系统提示改写)不是回撤标记:
|
|
801
|
+
// 不产生「待恢复轮」,否则 dock 会列出压缩前的整段历史并可点恢复。
|
|
802
|
+
if (!isOwnMarkerEvent(marker)) return null
|
|
545
803
|
const { startSeq, endSeq } = range
|
|
546
|
-
|
|
547
|
-
const candidates = []
|
|
548
|
-
for (const e of list) {
|
|
549
|
-
if (!e || typeof e.seq !== 'number' || e.seq < startSeq || e.seq > endSeq) continue
|
|
550
|
-
if (e.type !== 'user/message' && e.type !== 'assistant/message') continue
|
|
551
|
-
if (!(messageText(e) || '').trim()) continue
|
|
552
|
-
candidates.push(e.seq)
|
|
553
|
-
}
|
|
554
|
-
// 收集针对该标记的所有恢复 notice
|
|
804
|
+
const candidates = restoreCandidates(list, marker, range)
|
|
555
805
|
const notices = list.filter(e => e && e.data && e.data.restoresSeq === markerSeq)
|
|
556
806
|
const restored = new Set()
|
|
557
807
|
let legacy = false
|
|
@@ -576,21 +826,40 @@ export function restoreProgress(events, markerSeq) {
|
|
|
576
826
|
endSeq,
|
|
577
827
|
restoredSeqs: Array.from(restored).sort((a, b) => a - b),
|
|
578
828
|
pendingSeqs: pending,
|
|
829
|
+
// 0.33.2:区分「全部恢复完」与「本来就没有可恢复内容」。两者 complete 都是
|
|
830
|
+
// true,但只有前者该拒绝再次恢复;后者必须允许写停用 notice(0.5.6 语义)。
|
|
831
|
+
candidateCount: candidates.length,
|
|
579
832
|
complete: legacy || discarded ? true : pending.length === 0,
|
|
580
833
|
legacy,
|
|
581
834
|
discarded,
|
|
582
835
|
}
|
|
583
836
|
}
|
|
584
837
|
|
|
838
|
+
/**
|
|
839
|
+
* 恢复进度索引(`buildDerived` 每份日志建一次)。
|
|
840
|
+
*
|
|
841
|
+
* 0.26.0 新增 `candidateTexts`:索引版候选集必须与直算版**同源同判据**
|
|
842
|
+
* (遮蔽集 + `messageTextFull` 非空)。旧实现建索引时用 `messageText`(首段)
|
|
843
|
+
* 判非空、按数值区间选候选 —— 与 `planRestore` 三处口径分裂,实测 457 条
|
|
844
|
+
* 前向 marker 里 17 条候选集与宿主真值不符(16 条 compact-checkpoint、
|
|
845
|
+
* 1 条 system-prompt)。现在把「节点序遮蔽集」一并缓存进索引:`buildDerived`
|
|
846
|
+
* 每份日志只折叠一次 surface,标记越多越省。
|
|
847
|
+
*/
|
|
585
848
|
export function buildRestoreIndex(events) {
|
|
586
849
|
const bySeq = new Map()
|
|
587
850
|
const noticesByMarker = new Map()
|
|
588
851
|
const candidates = []
|
|
852
|
+
const textBySeq = new Map()
|
|
589
853
|
for (const e of events) {
|
|
590
854
|
if (!e || typeof e.seq !== 'number') continue
|
|
591
855
|
bySeq.set(e.seq, e)
|
|
592
|
-
if (e
|
|
593
|
-
|
|
856
|
+
if (isReplayableMessage(e)) {
|
|
857
|
+
// 0.26.0:判据与 planRestore 对齐 —— 首段为空但后段有内容的也算候选
|
|
858
|
+
// (实测 0 条「首段空而全文非空」,但口径必须一处,否则未来必分裂)。
|
|
859
|
+
if (messageTextFull(e).trim()) {
|
|
860
|
+
candidates.push(e.seq)
|
|
861
|
+
textBySeq.set(e.seq, messageTextFull(e))
|
|
862
|
+
}
|
|
594
863
|
}
|
|
595
864
|
const markerSeq = e.data && e.data.restoresSeq
|
|
596
865
|
if (Number.isSafeInteger(markerSeq)) {
|
|
@@ -599,7 +868,8 @@ export function buildRestoreIndex(events) {
|
|
|
599
868
|
else noticesByMarker.set(markerSeq, [e])
|
|
600
869
|
}
|
|
601
870
|
}
|
|
602
|
-
|
|
871
|
+
const fold = foldSurfaceNodes(events)
|
|
872
|
+
return { bySeq, noticesByMarker, candidates, textBySeq, fold }
|
|
603
873
|
}
|
|
604
874
|
|
|
605
875
|
export function restoreProgressFromIndex(index, markerSeq) {
|
|
@@ -607,10 +877,18 @@ export function restoreProgressFromIndex(index, markerSeq) {
|
|
|
607
877
|
if (!marker) return null
|
|
608
878
|
const range = readReplaceOp(marker)
|
|
609
879
|
if (!range) return null
|
|
880
|
+
if (!isOwnMarkerEvent(marker)) return null
|
|
610
881
|
const { startSeq, endSeq } = range
|
|
882
|
+
// 0.26.0:候选集走与 restoreProgress 完全相同的单点口径(遮蔽集,非数值区间)。
|
|
883
|
+
const shadowed = markerShadowedSeqs([], marker, index.fold)
|
|
611
884
|
const candidates = []
|
|
612
|
-
|
|
613
|
-
|
|
885
|
+
if (shadowed) {
|
|
886
|
+
const set = new Set(shadowed.filter(q => Number.isSafeInteger(q)))
|
|
887
|
+
for (const q of index.candidates) if (set.has(q)) candidates.push(q)
|
|
888
|
+
} else {
|
|
889
|
+
const lo = Math.min(startSeq, endSeq)
|
|
890
|
+
const hi = Math.max(startSeq, endSeq)
|
|
891
|
+
for (const q of index.candidates) if (q >= lo && q <= hi) candidates.push(q)
|
|
614
892
|
}
|
|
615
893
|
const notices = index.noticesByMarker.get(markerSeq) || []
|
|
616
894
|
const restored = new Set()
|
|
@@ -634,28 +912,55 @@ export function restoreProgressFromIndex(index, markerSeq) {
|
|
|
634
912
|
endSeq,
|
|
635
913
|
restoredSeqs: Array.from(restored).sort((a, b) => a - b),
|
|
636
914
|
pendingSeqs: pending,
|
|
915
|
+
// 0.33.2:区分「全部恢复完」与「本来就没有可恢复内容」。两者 complete 都是
|
|
916
|
+
// true,但只有前者该拒绝再次恢复;后者必须允许写停用 notice(0.5.6 语义)。
|
|
917
|
+
candidateCount: candidates.length,
|
|
637
918
|
complete: legacy || discarded ? true : pending.length === 0,
|
|
638
919
|
legacy,
|
|
639
920
|
discarded,
|
|
640
921
|
}
|
|
641
922
|
}
|
|
642
923
|
|
|
643
|
-
|
|
644
|
-
|
|
924
|
+
/**
|
|
925
|
+
* 把待恢复 seq 按「轮」分组:真实用户输入开一轮,其后的助手回复并入同轮;
|
|
926
|
+
* 换 turn 号的助手回复单起一轮(注入行引导的轮没有真实用户消息)。
|
|
927
|
+
*
|
|
928
|
+
* 0.28.0:注入行已不在候选集里(见 isReplayableMessage),旧实现「user 就开新轮」
|
|
929
|
+
* 会把一条用户消息后面的助手回复按 user 切分,恢复面板出现同一轮拆成多行。
|
|
930
|
+
*
|
|
931
|
+
* @param {number[]} seqs 升序待恢复 seq
|
|
932
|
+
* @param {Map<number, object>} bySeq seq → 事件
|
|
933
|
+
* @returns {Array<{turnSeq:number, turn:number|null, seqs:number[]}>} 按轮分组
|
|
934
|
+
*/
|
|
935
|
+
function groupPendingTurns(seqs, bySeq) {
|
|
645
936
|
const turns = []
|
|
646
937
|
let current = null
|
|
647
|
-
for (const q of
|
|
648
|
-
const e =
|
|
938
|
+
for (const q of seqs) {
|
|
939
|
+
const e = bySeq.get(q)
|
|
649
940
|
if (!e) continue
|
|
941
|
+
const turn = e.data && Number.isSafeInteger(e.data.turn) ? e.data.turn : null
|
|
650
942
|
if (e.type === 'user/message') {
|
|
651
|
-
current = { turnSeq: q, seqs: [q] }
|
|
943
|
+
current = { turnSeq: q, turn: turn, seqs: [q] }
|
|
652
944
|
turns.push(current)
|
|
653
|
-
|
|
654
|
-
|
|
945
|
+
continue
|
|
946
|
+
}
|
|
947
|
+
const sameTurn = current !== null && (current.turn === null || turn === null || current.turn === turn)
|
|
948
|
+
if (sameTurn) {
|
|
949
|
+
if (current.turn === null) current.turn = turn
|
|
950
|
+
current.seqs.push(q)
|
|
951
|
+
continue
|
|
952
|
+
}
|
|
953
|
+
current = { turnSeq: q, turn: turn, seqs: [q] }
|
|
954
|
+
turns.push(current)
|
|
655
955
|
}
|
|
656
956
|
return turns
|
|
657
957
|
}
|
|
658
958
|
|
|
959
|
+
export function pendingRestoreTurnsFromIndex(index, markerSeq, progress) {
|
|
960
|
+
if (!progress || progress.pendingSeqs.length === 0) return []
|
|
961
|
+
return groupPendingTurns(progress.pendingSeqs, index.bySeq).map(t => ({ turnSeq: t.turnSeq, seqs: t.seqs }))
|
|
962
|
+
}
|
|
963
|
+
|
|
659
964
|
/**
|
|
660
965
|
* 0.8.0:贴条按行展示用 —— 列出该标记仍未重放的「轮」(一个 user 消息及其后
|
|
661
966
|
* 到下一个 user 之前的 assistant 回复算一轮,对齐 opencode 按轮步进恢复)。
|
|
@@ -676,316 +981,190 @@ export function pendingRestoreTurns(events, markerSeq, progress = null) {
|
|
|
676
981
|
const list = Array.isArray(events) ? events : []
|
|
677
982
|
const bySeq = new Map()
|
|
678
983
|
for (const e of list) if (e && typeof e.seq === 'number') bySeq.set(e.seq, e)
|
|
679
|
-
|
|
680
|
-
let current = null
|
|
681
|
-
for (const q of prog.pendingSeqs) {
|
|
682
|
-
const e = bySeq.get(q)
|
|
683
|
-
if (!e) continue
|
|
684
|
-
if (e.type === 'user/message') {
|
|
685
|
-
current = { turnSeq: q, seqs: [q] }
|
|
686
|
-
turns.push(current)
|
|
687
|
-
} else if (current) current.seqs.push(q)
|
|
688
|
-
else turns.push({ turnSeq: q, seqs: [q] }) // 孤立 assistant(无前导 user)
|
|
689
|
-
}
|
|
690
|
-
return turns
|
|
984
|
+
return groupPendingTurns(prog.pendingSeqs, bySeq).map(t => ({ turnSeq: t.turnSeq, seqs: t.seqs }))
|
|
691
985
|
}
|
|
692
986
|
|
|
693
987
|
// ---------------------------------------------------------------------------
|
|
694
|
-
// HTTP
|
|
695
|
-
//
|
|
696
|
-
// packages/client/connection/src/api-request-trust.ts),必须自建。三层:
|
|
697
|
-
// 1. Host 必须是回环地址 → 挡 DNS rebinding(伪造 Host 的攻击页直接 403);
|
|
698
|
-
// 2. sec-fetch-site: cross-site 拒绝 → 挡跨站浏览器请求;
|
|
699
|
-
// 3. Origin 存在时必须与 Host 同源 → 挡其余跨站 POST/GET。
|
|
700
|
-
// 非浏览器客户端(curl / Agent 工具 / 宿主自身)不带 sec-fetch-site 与
|
|
701
|
-
// Origin,且 Host 均为回环 → 天然放行,无需 token。
|
|
988
|
+
// HTTP 信任围栏 / 浏览器 cookie 鉴权 —— 0.28.0 拆到 auth.js(单一职责)。
|
|
989
|
+
// 这里只做转出,保持既有导入面(index.js 与测试都从 ops-core 取)。
|
|
702
990
|
// ---------------------------------------------------------------------------
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
} catch {
|
|
713
|
-
return undefined
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
function isLoopbackHostname(hostname) {
|
|
718
|
-
if (hostname === 'localhost' || hostname === '[::1]') return true
|
|
719
|
-
const parts = hostname.split('.')
|
|
720
|
-
return parts.length === 4 && parts[0] === '127' && parts.every(p => /^\d{1,3}$/.test(p) && Number(p) <= 255)
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
/** 与 slv-check 同款的信任判定(回环 Host + 非 cross-site + Origin 同源)。 */
|
|
724
|
-
export function isTrustedApiRequest(req) {
|
|
725
|
-
const host = headerOf(req && req.headers, 'host')
|
|
726
|
-
if (host === undefined) return false
|
|
727
|
-
const hostUrl = parseAuthority(host)
|
|
728
|
-
if (hostUrl === undefined) return false
|
|
729
|
-
if (!isLoopbackHostname(hostUrl.hostname)) return false
|
|
730
|
-
if (headerOf(req.headers, 'sec-fetch-site') === 'cross-site') return false
|
|
731
|
-
const origin = headerOf(req.headers, 'origin')
|
|
732
|
-
if (origin === undefined) return true
|
|
733
|
-
try {
|
|
734
|
-
return new URL(origin).host === hostUrl.host
|
|
735
|
-
} catch {
|
|
736
|
-
return false
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
/**
|
|
741
|
-
* 写操作 CSRF 防护:Content-Type 必须 application/json(允许 ;charset=… 后缀)。
|
|
742
|
-
* 为何不需要一次性 token:浏览器对**所有** POST(含 text/plain 绕预检的
|
|
743
|
-
* 那条路)都会附带 Origin 头,第 3 层 Origin 同源校验已覆盖跨站 POST;
|
|
744
|
-
* Content-Type 约束是纵深防御(阻止非 JSON 客户端误写),而自定义头
|
|
745
|
-
* (如 X-Requested-With)天然触发 CORS 预检,与 Origin 校验等价,故
|
|
746
|
-
* 引入 token 只增加握手复杂度而不增加安全性——围栏已足够(论证记录于此)。
|
|
747
|
-
*/
|
|
748
|
-
export function isJsonContentType(req) {
|
|
749
|
-
const ct = headerOf(req && req.headers, 'content-type') || ''
|
|
750
|
-
return ct.split(';')[0].trim().toLowerCase() === 'application/json'
|
|
751
|
-
}
|
|
991
|
+
export {
|
|
992
|
+
isTrustedApiRequest,
|
|
993
|
+
isJsonContentType,
|
|
994
|
+
browserAuthPayload,
|
|
995
|
+
loadBrowserAuthSecret,
|
|
996
|
+
_setWebAuthSecret,
|
|
997
|
+
_resetWebAuth,
|
|
998
|
+
webAuthGate,
|
|
999
|
+
} from './auth.js'
|
|
752
1000
|
|
|
753
1001
|
// ---------------------------------------------------------------------------
|
|
754
|
-
// 0.
|
|
1002
|
+
// 0.5.7 · 磁盘路径(lazy-view 会话不进对象层时的回退)
|
|
755
1003
|
// ---------------------------------------------------------------------------
|
|
756
|
-
//
|
|
757
|
-
//
|
|
758
|
-
// browserAuth 认证——根 token 只在 authorizeIndex 换 cookie:GET /<token>
|
|
759
|
-
// → 铸 HttpOnly+SameSite=Strict 的签名 cookie(名 = dsh-auth-<b64url(
|
|
760
|
-
// sha256(authority))>,载荷 v{1|2}.<b64url(json)>.<b64url(hmac-sha256)>
|
|
761
|
-
// secret 32 字节,存 credentials 记录 client-connection/browser-session)
|
|
762
|
-
// → 重定向 ./;此后每条 /api 都凭 cookie 过 admit,无 cookie → 401。
|
|
763
|
-
// 前端取数是同源 fetch(默认凭证)——cookie 自动随行,**全程没有
|
|
764
|
-
// Authorization 头,也没有 ?token= 打到 /api**。
|
|
765
|
-
// 插件路由此前只跑 isTrustedApiRequest(该围栏自述 "is not an auth layer"),
|
|
766
|
-
// 同机无凭证进程 GET 即可整卷消息/全文(宿主同条件 401——审计缺口)。
|
|
767
|
-
// 对齐修法(选型理由见报告):前端本来就带 cookie → 围栏里**校验同款
|
|
768
|
-
// cookie**;secret 经 credentials 服务的合法读法取(no-op modifyRecord,
|
|
769
|
-
// 勿写勿落盘)。无 credentials 服务 = 老宿主 → 保留旧围栏;有服务但记录
|
|
770
|
-
// 缺失/格式升级 → **fail-closed** 并告警,避免永久 allow-all。
|
|
771
|
-
// 非浏览器 GET(curl 等)从 200 变 401 = 与宿主对齐的有意行为变化。
|
|
772
|
-
|
|
773
|
-
const AUTH_RECORD_KEY = 'client-connection/browser-session'
|
|
774
|
-
const AUTH_COOKIE_PREFIX = 'dsh-auth-'
|
|
775
|
-
const AUTH_STORED_SECRET_VERSION = 1
|
|
776
|
-
const AUTH_SECRET_BYTES = 32
|
|
777
|
-
|
|
778
|
-
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u
|
|
779
|
-
|
|
780
|
-
function encodeBase64Url(value) {
|
|
781
|
-
return Buffer.from(value).toString('base64').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '')
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
function decodeBase64Url(value) {
|
|
785
|
-
if (!BASE64URL_PATTERN.test(value) || value.length % 4 === 1) return undefined
|
|
786
|
-
const padding = '='.repeat((4 - (value.length % 4)) % 4)
|
|
787
|
-
const decoded = Buffer.from(value.replaceAll('-', '+').replaceAll('_', '/') + padding, 'base64')
|
|
788
|
-
return encodeBase64Url(decoded) === value ? decoded : undefined
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
/** 宿主 requestAudience 的口径:HTTP 用 url.host;TLS 用 url.origin。插件
|
|
792
|
-
* 读不到监听面协议,两种拼写都试(名字与载荷 authority 用**同一个**拼写
|
|
793
|
-
* 配对校验,跨拼写伪造照样被拒)。 */
|
|
794
|
-
function cookieAuthorityCandidates(hostHeader) {
|
|
795
|
-
try {
|
|
796
|
-
const url = new URL(`http://${hostHeader}`)
|
|
797
|
-
return [url.host, `https://${url.host}`]
|
|
798
|
-
} catch {
|
|
799
|
-
return []
|
|
800
|
-
}
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
/** 宿主 cookieValue:按分号切段取**第一个**同名区的值(无解码语义)。 */
|
|
804
|
-
function cookieValue(rawCookie, name) {
|
|
805
|
-
if (typeof rawCookie !== 'string') return undefined
|
|
806
|
-
for (const segment of rawCookie.split(';')) {
|
|
807
|
-
const at = segment.indexOf('=')
|
|
808
|
-
if (at === -1 || segment.slice(0, at).trim() !== name) continue
|
|
809
|
-
return segment.slice(at + 1).trim()
|
|
810
|
-
}
|
|
811
|
-
return undefined
|
|
812
|
-
}
|
|
1004
|
+
// store-miss 时**直接向日志追加 zstd 帧**(字段逐项镜像引擎金标准),磁盘会话的
|
|
1005
|
+
// 视图按帧重读、追加即可见;live 会话仍走引擎路径。复盘见 README「0.5.7」。
|
|
813
1006
|
|
|
814
|
-
/**
|
|
815
|
-
function
|
|
816
|
-
|
|
817
|
-
const [version, body, encodedSignature] = parts
|
|
818
|
-
if (parts.length !== 3 || (version !== 'v1' && version !== 'v2') || body === undefined || encodedSignature === undefined) return undefined
|
|
819
|
-
const actualSignature = decodeBase64Url(encodedSignature)
|
|
820
|
-
if (actualSignature === undefined) return undefined
|
|
821
|
-
const expectedSignature = createHmac('sha256', secret).update(body).digest()
|
|
822
|
-
if (actualSignature.length !== expectedSignature.length || !timingSafeEqual(actualSignature, expectedSignature)) return undefined
|
|
823
|
-
const bodyBytes = decodeBase64Url(body)
|
|
824
|
-
if (bodyBytes === undefined) return undefined
|
|
825
|
-
let decoded
|
|
826
|
-
try {
|
|
827
|
-
decoded = JSON.parse(bodyBytes.toString('utf8'))
|
|
828
|
-
} catch {
|
|
829
|
-
return undefined
|
|
830
|
-
}
|
|
831
|
-
if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) return undefined
|
|
832
|
-
if (decoded.version !== 1 && decoded.version !== 2) return undefined
|
|
833
|
-
if (version !== `v${decoded.version}`) return undefined
|
|
834
|
-
if (typeof decoded.authority !== 'string' || decoded.authority === '') return undefined
|
|
835
|
-
if (typeof decoded.issuedAt !== 'number' || !Number.isSafeInteger(decoded.issuedAt)) return undefined
|
|
836
|
-
if (typeof decoded.expiresAt !== 'number' || !Number.isSafeInteger(decoded.expiresAt)) return undefined
|
|
837
|
-
const payload = { version: decoded.version, authority: decoded.authority, issuedAt: decoded.issuedAt, expiresAt: decoded.expiresAt }
|
|
838
|
-
if (decoded.version === 1) return payload
|
|
839
|
-
if (typeof decoded.id !== 'string' || decoded.id.length === 0) return undefined
|
|
840
|
-
return { ...payload, id: decoded.id }
|
|
1007
|
+
/** 事件类型是否为 surface 节点(message 类;step/end、turn/end 等结构性事件不是)。 */
|
|
1008
|
+
export function isSurfaceMessageType(type) {
|
|
1009
|
+
return type === 'user/message' || type === 'assistant/message' || type === 'system/message' || type === 'developer/message'
|
|
841
1010
|
}
|
|
842
1011
|
|
|
1012
|
+
/** 磁盘可见节点:按事件流推导的 message 类 seq(剔除既有遮蔽)。 */
|
|
843
1013
|
/**
|
|
844
|
-
*
|
|
845
|
-
*
|
|
1014
|
+
* 当前 surface 上的**全部**节点(v4 的 5 种 surface 类型),已剔除被遮蔽的。
|
|
1015
|
+
*
|
|
1016
|
+
* ⚠️ 与 `diskVisibleNodes` 的区别是关键的(0.8.2 实机事故):
|
|
1017
|
+
* `diskVisibleNodes` 只收 4 种**消息**类型(UI 列表用),而 v4 的 surface 还包含
|
|
1018
|
+
* `tool/result`。surface replace 的 `sourceEventSeqs` 必须覆盖**被遮蔽的每一个
|
|
1019
|
+
* surface 节点**(`foldSurface`:`sourceEventSeqs must include every shadowed
|
|
1020
|
+
* surface node`)—— 用消息集合当溯源会漏掉区间内的 tool/result,**整份日志被
|
|
1021
|
+
* 加载端拒绝**。这正是历史上 14 个打不开的会话的真正成因(不是区间压缩编码问题)。
|
|
1022
|
+
*
|
|
1023
|
+
* ── 0.26.0 根因修正 ────────────────────────────────────────────────────────
|
|
1024
|
+
* 旧实现用 `computeShadowed` 的**数值区间**语义(`startSeq..endSeq` 里所有 seq
|
|
1025
|
+
* 都算被遮蔽),宿主用的是**节点索引**语义(`nodes.indexOf(startSeq)` /
|
|
1026
|
+
* `nodes.indexOf(endSeq)` 定位后 `splice`)。两者在「区间内还有别人先遮蔽掉的
|
|
1027
|
+
* 节点」时**不等价**:数值语义会连带把早先标记已遮蔽的节点重复算进去,节点序
|
|
1028
|
+
* 语义只消费当时仍在表上的节点。
|
|
1029
|
+
*
|
|
1030
|
+
* 实测(263 份可折叠语料,与安装的 `foldSurface` 逐份对拍):
|
|
1031
|
+
* - 节点数组与本实现一致:**新 263/263、旧 216/263**(旧实现 47 份分歧);
|
|
1032
|
+
* - replace 的 `shadowedSeqs`:本实现 263/263 完全一致(0 分歧);
|
|
1033
|
+
* - 用宿主闸复验回滚目标(每份日志全部可见节点):**旧实现 13787 个目标里
|
|
1034
|
+
* 2495 个被宿主拒绝(18.1%:`start seq not found in surface` 2285、
|
|
1035
|
+
* `node 0 holds the system prompt` 195、`sourceEventSeqs missing shadowed`
|
|
1036
|
+
* 15);新实现 11323 个目标 0 拒绝**。
|
|
1037
|
+
*
|
|
1038
|
+
* 反向区间(`startSeq > endSeq`,语料 afcc0453 共 9 条 compact-checkpoint)在
|
|
1039
|
+
* 宿主是**合法的节点序区间**(索引 start < 索引 end);节点序实现天然支持,
|
|
1040
|
+
* 数值实现只能退回「凭据」近似。故本实现统一走节点序,端点解析不了时才回落
|
|
1041
|
+
* 到旧数值口径(损坏/伪造日志不因此炸掉整份读取)。
|
|
1042
|
+
*
|
|
1043
|
+
* @param {Array} events 全量事件
|
|
1044
|
+
* @returns {{ nodes:number[], shadowedByMarker:Map<number,number[]>, bySeq:Map<number,object>, fallbacks:number }}
|
|
846
1045
|
*/
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
const
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
const
|
|
854
|
-
for (const
|
|
855
|
-
|
|
856
|
-
if (
|
|
857
|
-
const
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
1046
|
+
function foldSurfaceNodes(events) {
|
|
1047
|
+
const nodes = []
|
|
1048
|
+
const shadowedByMarker = new Map()
|
|
1049
|
+
const bySeq = new Map()
|
|
1050
|
+
let fallbacks = 0
|
|
1051
|
+
const list = Array.isArray(events) ? events : []
|
|
1052
|
+
for (const e of list) if (e && Number.isSafeInteger(e.seq)) bySeq.set(e.seq, e)
|
|
1053
|
+
for (const e of list) {
|
|
1054
|
+
if (!e || !Number.isSafeInteger(e.seq)) continue
|
|
1055
|
+
if (!isSurfaceType(e.type)) continue
|
|
1056
|
+
const range = readReplaceOp(e)
|
|
1057
|
+
if (!range) {
|
|
1058
|
+
nodes.push(e.seq)
|
|
1059
|
+
continue
|
|
1060
|
+
}
|
|
1061
|
+
const startIdx = nodes.indexOf(range.startSeq)
|
|
1062
|
+
const endIdx = nodes.indexOf(range.endSeq)
|
|
1063
|
+
if (startIdx !== -1 && endIdx !== -1 && startIdx <= endIdx) {
|
|
1064
|
+
const shadowed = nodes.slice(startIdx, endIdx + 1)
|
|
1065
|
+
shadowedByMarker.set(e.seq, shadowed)
|
|
1066
|
+
nodes.splice(startIdx, endIdx - startIdx + 1, e.seq)
|
|
1067
|
+
continue
|
|
1068
|
+
}
|
|
1069
|
+
// 端点不在当前节点表上(历史损坏/伪造 marker):退回旧数值口径,绝不 throw —
|
|
1070
|
+
// 读取路径必须能打开日志,规划路径由下面的显式校验(409)负责拒绝。
|
|
1071
|
+
fallbacks += 1
|
|
1072
|
+
let kept
|
|
1073
|
+
if (range.startSeq <= range.endSeq) {
|
|
1074
|
+
kept = nodes.filter(q => q < range.startSeq || q > range.endSeq)
|
|
1075
|
+
} else {
|
|
1076
|
+
const src = Array.isArray(e.sourceEventSeqs) ? e.sourceEventSeqs : []
|
|
1077
|
+
const removed = new Set(src.filter(q => Number.isSafeInteger(q)))
|
|
1078
|
+
kept = nodes.filter(q => !removed.has(q))
|
|
1079
|
+
}
|
|
1080
|
+
kept.push(e.seq)
|
|
1081
|
+
nodes.length = 0
|
|
1082
|
+
nodes.push(...kept)
|
|
864
1083
|
}
|
|
865
|
-
return
|
|
1084
|
+
return { nodes, shadowedByMarker, bySeq, fallbacks }
|
|
866
1085
|
}
|
|
867
1086
|
|
|
868
1087
|
/**
|
|
869
|
-
*
|
|
870
|
-
*
|
|
871
|
-
*
|
|
872
|
-
*
|
|
873
|
-
*
|
|
874
|
-
*
|
|
1088
|
+
* 某个 marker「真正遮蔽了哪些 surface 节点」。
|
|
1089
|
+
*
|
|
1090
|
+
* 优先级:宿主节点序折叠结果 → `sourceEventSeqs` 凭据 → 旧数值区间。
|
|
1091
|
+
* 实测 485 条 replace 中 452 条凭据与宿主遮蔽集**完全相等**、33 条为超集
|
|
1092
|
+
* (多为同一 turn 内顺带列出的结构性 seq),**0 条缺失** —— 所以凭据是可靠的
|
|
1093
|
+
* 次优来源;数值区间是最后兜底(历史 marker 无凭据时)。
|
|
1094
|
+
*
|
|
1095
|
+
* @returns {number[]|null} null = 完全无法判定(无区间也无凭据)
|
|
875
1096
|
*/
|
|
876
|
-
|
|
877
|
-
if (!
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
1097
|
+
function markerShadowedSeqs(events, marker, fold = null) {
|
|
1098
|
+
if (!marker) return null
|
|
1099
|
+
const state = fold || foldSurfaceNodes(events)
|
|
1100
|
+
const known = state.shadowedByMarker.get(marker.seq)
|
|
1101
|
+
if (known) return known
|
|
1102
|
+
const src = Array.isArray(marker.sourceEventSeqs) ? expandSourceSeqs(marker.sourceEventSeqs) : null
|
|
1103
|
+
if (src && src.length > 0) return src.filter(q => q < marker.seq)
|
|
1104
|
+
const range = readReplaceOp(marker)
|
|
1105
|
+
if (!range || range.startSeq > range.endSeq) return null
|
|
1106
|
+
// 0.33.2:数值回退必须与 computeShadowed 同一上限,否则一条损坏/伪造 marker
|
|
1107
|
+
// (end-start 可达 1e9)就能把 /messages 的事件循环卡死(实测 8s 超时)。
|
|
1108
|
+
if (range.endSeq - range.startSeq > MAX_SPAN) {
|
|
1109
|
+
throw new OpsError(`surface replace span too large: [${range.startSeq}..${range.endSeq}] exceeds MAX_SPAN=${MAX_SPAN}`, 404)
|
|
883
1110
|
}
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
if (typeof payload.secret !== 'string') return null
|
|
888
|
-
const secret = decodeBase64Url(payload.secret)
|
|
889
|
-
if (!secret || secret.length !== AUTH_SECRET_BYTES) return null
|
|
890
|
-
return secret
|
|
1111
|
+
const out = []
|
|
1112
|
+
for (let q = range.startSeq; q <= range.endSeq; q += 1) out.push(q)
|
|
1113
|
+
return out
|
|
891
1114
|
}
|
|
892
1115
|
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
const WEB_AUTH_RETRY_MS = 10_000
|
|
896
|
-
let __webAuthSecret = null
|
|
897
|
-
let __webAuthProbeAt = 0
|
|
898
|
-
let __webAuthProbe = null
|
|
899
|
-
let __webAuthWarned = false
|
|
900
|
-
|
|
901
|
-
/** 测试钩子:直接注入/清除 secret,绕开 credentials 服务。 */
|
|
902
|
-
export function _setWebAuthSecret(secret) {
|
|
903
|
-
__webAuthSecret = secret
|
|
904
|
-
}
|
|
905
|
-
export function _resetWebAuth() {
|
|
906
|
-
__webAuthSecret = null
|
|
907
|
-
__webAuthProbeAt = 0
|
|
908
|
-
__webAuthProbe = null
|
|
909
|
-
__webAuthWarned = false
|
|
1116
|
+
export function diskSurfaceNodes(events) {
|
|
1117
|
+
return foldSurfaceNodes(events).nodes
|
|
910
1118
|
}
|
|
911
1119
|
|
|
912
1120
|
/**
|
|
913
|
-
*
|
|
914
|
-
*
|
|
915
|
-
*
|
|
916
|
-
*
|
|
917
|
-
*
|
|
1121
|
+
* 该 marker 是否已被**后续真正回撤**取代(于是不可再恢复)。
|
|
1122
|
+
*
|
|
1123
|
+
* 判据 = 存在 seq 更大的 replace marker,其节点序遮蔽集包含本 marker,
|
|
1124
|
+
* **且该集合不止一个节点**。
|
|
1125
|
+
*
|
|
1126
|
+
* 为什么要求 `shadowed.length > 1`:历史上存在「自噬 marker」——旧 dock 拿 marker
|
|
1127
|
+
* 自己当目标写出的 `startSeq === endSeq === 前一 marker seq`、content 为空 的记录。
|
|
1128
|
+
* 它只覆盖前一条 marker 本身,不代表用户又回撤了一次;此时恢复前一条 marker
|
|
1129
|
+
* 恰恰是唯一的挽回路径(否则该回撤永远无法撤销)。
|
|
1130
|
+
*
|
|
1131
|
+
* 真机复现的负例:回撤到第二条(M1)→ 再回撤到第一条(M2,遮蔽集 = [第一条,
|
|
1132
|
+
* 第一条的答复, M1])→ 恢复 M1 会把用户已回撤掉的第二、三条重新放回会话末尾。
|
|
1133
|
+
*
|
|
1134
|
+
* @param {{shadowedByMarker: Map<number, number[]>}} fold foldSurfaceNodes 的结果
|
|
1135
|
+
* @param {number} markerSeq 待判定 marker 的 seq
|
|
1136
|
+
* @returns {number|null} 取代它的 marker seq;null = 未被取代
|
|
918
1137
|
*/
|
|
919
|
-
export
|
|
920
|
-
if (
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
credentials = ctx && typeof ctx.get === 'function' ? ctx.get('credentials') : null
|
|
927
|
-
} catch {
|
|
928
|
-
/* legacy ctx */
|
|
1138
|
+
export function supersededByMarker(fold, markerSeq) {
|
|
1139
|
+
if (!fold || !(fold.shadowedByMarker instanceof Map)) return null
|
|
1140
|
+
let hit = null
|
|
1141
|
+
for (const [laterSeq, shadowed] of fold.shadowedByMarker) {
|
|
1142
|
+
if (!Number.isSafeInteger(laterSeq) || laterSeq <= markerSeq) continue
|
|
1143
|
+
if (!Array.isArray(shadowed) || shadowed.length <= 1) continue
|
|
1144
|
+
if (shadowed.includes(markerSeq)) hit = hit === null ? laterSeq : Math.min(hit, laterSeq)
|
|
929
1145
|
}
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
const now = Date.now()
|
|
933
|
-
if (__webAuthProbe === null && now - __webAuthProbeAt >= WEB_AUTH_RETRY_MS) {
|
|
934
|
-
__webAuthProbeAt = now
|
|
935
|
-
__webAuthProbe = loadBrowserAuthSecret(credentials)
|
|
936
|
-
.then(secret => {
|
|
937
|
-
__webAuthSecret = secret
|
|
938
|
-
if (secret === null && !__webAuthWarned) {
|
|
939
|
-
__webAuthWarned = true
|
|
940
|
-
console.warn(
|
|
941
|
-
'[message-ops] BrowserAuth cookie 鉴权已启用但 `client-connection/browser-session` 记录不可读' +
|
|
942
|
-
'——GET 鉴权 fail-closed;请检查该记录是否存在',
|
|
943
|
-
)
|
|
944
|
-
}
|
|
945
|
-
return secret
|
|
946
|
-
})
|
|
947
|
-
.finally(() => {
|
|
948
|
-
__webAuthProbe = null
|
|
949
|
-
})
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
if (__webAuthProbe === null) return false
|
|
953
|
-
const secret = await __webAuthProbe
|
|
954
|
-
return secret !== null && browserAuthPayload(req, secret) !== undefined
|
|
1146
|
+
return hit
|
|
955
1147
|
}
|
|
956
1148
|
|
|
957
|
-
// ---------------------------------------------------------------------------
|
|
958
|
-
// 0.5.7 · 磁盘路径(lazy-view 会话不进对象层时的回退)
|
|
959
|
-
// ---------------------------------------------------------------------------
|
|
960
|
-
// store-miss 时**直接向日志追加 zstd 帧**(字段逐项镜像引擎金标准),磁盘会话的
|
|
961
|
-
// 视图按帧重读、追加即可见;live 会话仍走引擎路径。复盘见 README「0.5.7」。
|
|
962
|
-
|
|
963
|
-
/** 事件类型是否为 surface 节点(message 类;step/end、turn/end 等结构性事件不是)。 */
|
|
964
|
-
export function isSurfaceMessageType(type) {
|
|
965
|
-
return type === 'user/message' || type === 'assistant/message' || type === 'system/message' || type === 'developer/message'
|
|
966
|
-
}
|
|
967
|
-
|
|
968
|
-
/** 磁盘可见节点:按事件流推导的 message 类 seq(剔除既有遮蔽)。 */
|
|
969
1149
|
/**
|
|
970
|
-
*
|
|
1150
|
+
* 一次折叠算出「哪些 marker 已被后续回撤取代」。
|
|
971
1151
|
*
|
|
972
|
-
*
|
|
973
|
-
* `
|
|
974
|
-
*
|
|
975
|
-
*
|
|
976
|
-
*
|
|
977
|
-
* 会漏掉区间内的 tool/result,**整份日志被加载端拒绝**。这正是历史上 14 个打不开的
|
|
978
|
-
* 会话的真正成因(不是区间压缩编码问题)。
|
|
1152
|
+
* `/messages` 的派生缓存用它给每行打 `superseded`(客户端 dock 据此隐藏),
|
|
1153
|
+
* 与 `planRestore` 的 409 闸共用同一条语义(`supersededByMarker`)。
|
|
1154
|
+
*
|
|
1155
|
+
* @param {Array} events 全量事件
|
|
1156
|
+
* @returns {Map<number, number>} marker seq → 取代它的 marker seq
|
|
979
1157
|
*/
|
|
980
|
-
export function
|
|
981
|
-
const
|
|
982
|
-
const
|
|
983
|
-
for (const e of events) {
|
|
1158
|
+
export function supersededMarkers(events) {
|
|
1159
|
+
const fold = foldSurfaceNodes(events)
|
|
1160
|
+
const out = new Map()
|
|
1161
|
+
for (const e of Array.isArray(events) ? events : []) {
|
|
984
1162
|
if (!e || !Number.isSafeInteger(e.seq)) continue
|
|
985
|
-
if (
|
|
986
|
-
|
|
1163
|
+
if (!readReplaceOp(e)) continue
|
|
1164
|
+
const superseder = supersededByMarker(fold, e.seq)
|
|
1165
|
+
if (superseder !== null) out.set(e.seq, superseder)
|
|
987
1166
|
}
|
|
988
|
-
return
|
|
1167
|
+
return out
|
|
989
1168
|
}
|
|
990
1169
|
|
|
991
1170
|
function isSurfaceType(type) {
|
|
@@ -993,12 +1172,43 @@ function isSurfaceType(type) {
|
|
|
993
1172
|
}
|
|
994
1173
|
|
|
995
1174
|
export function diskVisibleNodes(events) {
|
|
996
|
-
|
|
997
|
-
|
|
1175
|
+
const state = foldSurfaceNodes(events)
|
|
1176
|
+
return state.nodes.filter(seq => {
|
|
1177
|
+
const e = state.bySeq.get(seq)
|
|
998
1178
|
return e && isSurfaceMessageType(e.type)
|
|
999
1179
|
})
|
|
1000
1180
|
}
|
|
1001
1181
|
|
|
1182
|
+
/**
|
|
1183
|
+
* 宿主保护面:surface 节点 0 承载 system prompt。
|
|
1184
|
+
*
|
|
1185
|
+
* `surface.js` `assertSystemHeadRewrite`(安装版 0.2.0-rc.2,385-394 行):
|
|
1186
|
+
* 当 `startIdx === 0` 且该节点是 `system/message` 时,replace **必须**本身是
|
|
1187
|
+
* `system/message` 且只遮蔽那一个节点,否则整份日志被加载端拒绝:
|
|
1188
|
+
* `surface replace: node 0 holds the system prompt and may be rewritten only
|
|
1189
|
+
* by a system/message over exactly that node`
|
|
1190
|
+
*
|
|
1191
|
+
* 实测:243 份无 compaction 日志里 27 个「可见的头节点」回滚目标,旧规划器
|
|
1192
|
+
* **全部放行**(把头节点之后全部遮蔽 = 多节点),宿主**全部拒绝**;在 6112 个
|
|
1193
|
+
* 目标上以宿主闸复验,「节点序 + 本护栏」的判定与宿主 0 分歧。
|
|
1194
|
+
*
|
|
1195
|
+
* @param {Array} surfaceNodes 节点序 surface(已剔除遮蔽)
|
|
1196
|
+
* @param {number} startIdx 目标在节点表上的索引
|
|
1197
|
+
* @param {number} shadowedCount 本次将遮蔽的节点数
|
|
1198
|
+
* @returns {string|null} 拒绝理由;null = 通过
|
|
1199
|
+
*/
|
|
1200
|
+
function systemHeadRejection(events, surfaceNodes, startIdx, shadowedCount) {
|
|
1201
|
+
if (startIdx !== 0) return null
|
|
1202
|
+
const headSeq = surfaceNodes[0]
|
|
1203
|
+
const head = (events ?? []).find(e => e && e.seq === headSeq)
|
|
1204
|
+
if (!head || head.type !== 'system/message') return null
|
|
1205
|
+
if (shadowedCount === 1) return null
|
|
1206
|
+
return (
|
|
1207
|
+
`surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node` +
|
|
1208
|
+
`(目标 seq ${headSeq} 是 surface 头节点,回滚它会把系统提示连同后面 ${shadowedCount - 1} 个节点一起遮蔽 —— 宿主会整份拒绝该日志)`
|
|
1209
|
+
)
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1002
1212
|
/** 磁盘版 planRevert:target 必须可见,遮蔽 target 之后(含)全部可见节点。 */
|
|
1003
1213
|
export function planRevertFromEvents(events, targetSeq) {
|
|
1004
1214
|
// 0.14.0 护栏:marker 不是对话,不能被回滚(否则产生自噬的空 replace 记录)。
|
|
@@ -1006,20 +1216,60 @@ export function planRevertFromEvents(events, targetSeq) {
|
|
|
1006
1216
|
if (isMarkerEvent(targetEvent)) {
|
|
1007
1217
|
throw new OpsError(`seq ${targetSeq} is a revert/delete marker, not a message — restore it instead of reverting it`, 409)
|
|
1008
1218
|
}
|
|
1009
|
-
|
|
1010
|
-
|
|
1219
|
+
if (readReplaceOp(targetEvent) !== null) {
|
|
1220
|
+
// 宿主自己的 replace 事件(compaction checkpoint / 系统提示改写 / tool 改写)
|
|
1221
|
+
// 不是可回滚的消息:遮蔽它会让模型同时看不到摘要与原文。
|
|
1222
|
+
throw new OpsError(`seq ${targetSeq} is a host surface rewrite, not a message — refusing to revert it`, 409)
|
|
1223
|
+
}
|
|
1224
|
+
// 一次折叠同时产出「全部 surface 节点」与「message 节点」(旧实现折叠两遍,
|
|
1225
|
+
// 大日志上 planRevertFromEvents 实测 141.4 ms,其中一半是白重算)。
|
|
1226
|
+
const state = foldSurfaceNodes(events)
|
|
1227
|
+
const nodes = state.nodes.filter(seq => {
|
|
1228
|
+
const e = state.bySeq.get(seq)
|
|
1229
|
+
return e && isSurfaceMessageType(e.type)
|
|
1230
|
+
})
|
|
1011
1231
|
const startIdx = nodes.indexOf(targetSeq)
|
|
1012
1232
|
if (startIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409)
|
|
1013
|
-
|
|
1014
|
-
const
|
|
1233
|
+
// 目标用「消息」集合(回滚对象是消息),溯源用「全部 surface」集合(0.8.2 修正)
|
|
1234
|
+
const surfaceIdx = state.nodes.indexOf(targetSeq)
|
|
1235
|
+
if (surfaceIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409)
|
|
1236
|
+
const shadowedSeqs = state.nodes.slice(surfaceIdx)
|
|
1015
1237
|
if (shadowedSeqs.length === 0) throw new OpsError('nothing to revert', 409)
|
|
1238
|
+
const headReject = systemHeadRejection(events, state.nodes, surfaceIdx, shadowedSeqs.length)
|
|
1239
|
+
if (headReject) throw new OpsError(headReject, 409)
|
|
1016
1240
|
return { startSeq: targetSeq, endSeq: shadowedSeqs[shadowedSeqs.length - 1], shadowedSeqs }
|
|
1017
1241
|
}
|
|
1018
1242
|
|
|
1019
|
-
/**
|
|
1243
|
+
/**
|
|
1244
|
+
* 磁盘版 planDelete:单条可见遮蔽。
|
|
1245
|
+
*
|
|
1246
|
+
* 0.26.0 补齐两道旧实现缺失的护栏(与 `planRevertFromEvents` 对齐):
|
|
1247
|
+
* 1. **marker 不能当删除目标** —— 旧实现只在 revert 侧拦,delete 侧放行;
|
|
1248
|
+
* 实测 session-645bd9 的 marker seq 21:`revert` → 409 DENY,`delete`
|
|
1249
|
+
* → **ALLOW**,落定即「遮蔽 marker 自己」的自噬空记录(语料 3424/3658/
|
|
1250
|
+
* 3689/3721/3746/7252/7524/7525/7526/8954… 共 51 条空 content marker 就是这么来的)。
|
|
1251
|
+
* 2. **节点 0 保护** —— delete 虽是单节点,但若目标就是头节点且头节点是
|
|
1252
|
+
* `system/message`,宿主要求 replace 事件本身必须是 `system/message`
|
|
1253
|
+
* (delete 写的就是 system/message,故单节点头删除**合法**);这里仍显式
|
|
1254
|
+
* 校验以免未来改成别的写法时静默失效。
|
|
1255
|
+
*/
|
|
1020
1256
|
export function planDeleteFromEvents(events, seq) {
|
|
1021
|
-
const
|
|
1022
|
-
|
|
1257
|
+
const targetEvent = (events ?? []).find(e => e && e.seq === seq)
|
|
1258
|
+
// 0.41.3(srv-audit D19):seq 根本不存在 → 404(与 /text 口径一致);
|
|
1259
|
+
// 存在但被遮蔽/非消息 → 409。旧实现两者都报 409「not visible」。
|
|
1260
|
+
if (!targetEvent) throw new OpsError(`seq ${seq} not found in this session log`, 404)
|
|
1261
|
+
if (isMarkerEvent(targetEvent)) {
|
|
1262
|
+
throw new OpsError(`seq ${seq} is a revert/delete marker, not a message — restore it instead of deleting it`, 409)
|
|
1263
|
+
}
|
|
1264
|
+
if (readReplaceOp(targetEvent) !== null) {
|
|
1265
|
+
throw new OpsError(`seq ${seq} is a host surface rewrite, not a message — refusing to delete it`, 409)
|
|
1266
|
+
}
|
|
1267
|
+
const state = foldSurfaceNodes(events)
|
|
1268
|
+
const visible = state.nodes.filter(q => {
|
|
1269
|
+
const e = state.bySeq.get(q)
|
|
1270
|
+
return e && isSurfaceMessageType(e.type)
|
|
1271
|
+
})
|
|
1272
|
+
if (!visible.includes(seq) || !state.nodes.includes(seq)) {
|
|
1023
1273
|
throw new OpsError(`seq ${seq} not visible on current surface`, 409)
|
|
1024
1274
|
}
|
|
1025
1275
|
// 单节点遮蔽:溯源就是它自己(0.8.2:也走完整 surface 判定,避免非 surface 节点)
|
|
@@ -1043,7 +1293,13 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
|
|
|
1043
1293
|
data: {
|
|
1044
1294
|
turn: turnStep.turn,
|
|
1045
1295
|
step: turnStep.step,
|
|
1046
|
-
message:
|
|
1296
|
+
message:
|
|
1297
|
+
version === 4
|
|
1298
|
+
? { id: randomUUID(), role: 'system', source: messageSource('system', version), content: [] }
|
|
1299
|
+
: { id: randomUUID(), role: 'system', source: messageSource('system', version), content: [{ type: 'text', text }] },
|
|
1300
|
+
// v4:正文放 data(宿主透传额外字段),模型不可见;v3 的精确键校验会拒绝额外
|
|
1301
|
+
// 字段,而 v3 写入已由磁盘路径整体拒绝(见 index.js),这里只为历史夹具保留。
|
|
1302
|
+
...(version === 4 ? { text, opsMarker: 'message-ops/v1' } : {}),
|
|
1047
1303
|
},
|
|
1048
1304
|
sourceEventSeqs: sources,
|
|
1049
1305
|
surfaceOp: { op: 'replace', startSeq, endSeq },
|
|
@@ -1067,9 +1323,15 @@ export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq,
|
|
|
1067
1323
|
data: {
|
|
1068
1324
|
turn: turnStep.turn,
|
|
1069
1325
|
step: turnStep.step,
|
|
1070
|
-
message:
|
|
1326
|
+
message:
|
|
1327
|
+
version === 4
|
|
1328
|
+
? { id: randomUUID(), role: 'system', source: messageSource('system', version), content: [] }
|
|
1329
|
+
: { id: randomUUID(), role: 'system', source: messageSource('system', version), content: [{ type: 'text', text }] },
|
|
1330
|
+
...(version === 4 ? { text, opsMarker: 'message-ops/v1' } : {}),
|
|
1071
1331
|
restoresSeq: restoreSeq,
|
|
1072
|
-
|
|
1332
|
+
// 0.35.2:非 discard 时即使为空也要写 []。restoreProgress 把「字段缺失」
|
|
1333
|
+
// 判成 legacy(complete=true)→ 一次空重放通知会让 marker 永久 409。
|
|
1334
|
+
...(discard ? {} : { restoredSourceSeqs: restored }),
|
|
1073
1335
|
...(discard ? { discarded: true } : {}),
|
|
1074
1336
|
},
|
|
1075
1337
|
surfaceOp: 'append',
|