@240xu/dsh-message-ops 0.24.0 → 0.47.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/README.md +654 -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 +1180 -283
- 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/index.js
CHANGED
|
@@ -7,12 +7,14 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { zstdCompressSync } from 'node:zlib'
|
|
10
|
+
import { constants as fsConstants } from 'node:fs'
|
|
10
11
|
import { open as openFile, truncate as truncateFile, stat as statFile } from 'node:fs/promises'
|
|
11
12
|
import {
|
|
12
13
|
isSessionId,
|
|
13
14
|
sessionIdVariants,
|
|
14
15
|
findSessionDirs,
|
|
15
16
|
readSessionFileAsync,
|
|
17
|
+
readSessionHeader,
|
|
16
18
|
listMessages,
|
|
17
19
|
computeShadowed,
|
|
18
20
|
messageText,
|
|
@@ -22,33 +24,38 @@ import {
|
|
|
22
24
|
readReplaceOp,
|
|
23
25
|
} from './session-file.js'
|
|
24
26
|
import {
|
|
25
|
-
|
|
27
|
+
applyScriptLive,
|
|
28
|
+
buildCommitScript,
|
|
29
|
+
buildRestoreScript,
|
|
30
|
+
materializeDisk,
|
|
31
|
+
} from './ops-write.js'
|
|
32
|
+
import {
|
|
26
33
|
planRevertFromEvents,
|
|
27
34
|
planDeleteFromEvents,
|
|
28
35
|
nextSeqFrom,
|
|
29
|
-
buildMarkerEvent,
|
|
30
|
-
buildRestoreNoticeEvent,
|
|
31
|
-
buildReplayEvent,
|
|
32
36
|
planNoticeWindow,
|
|
33
|
-
noticeWindowPreamble,
|
|
34
|
-
noticeWindowPostamble,
|
|
35
37
|
sessionLogOf,
|
|
36
38
|
alignLiveTurnCursor,
|
|
39
|
+
liveAgentOf,
|
|
40
|
+
livePhaseError,
|
|
37
41
|
OpsError,
|
|
38
42
|
planRevert,
|
|
39
43
|
planDelete,
|
|
44
|
+
isMarkerEvent,
|
|
40
45
|
planRestore,
|
|
41
|
-
applyRestore,
|
|
42
|
-
applySurfaceReplace,
|
|
43
46
|
restoreProgress,
|
|
44
47
|
pendingRestoreTurns,
|
|
45
48
|
buildRestoreIndex,
|
|
46
49
|
restoreProgressFromIndex,
|
|
47
50
|
pendingRestoreTurnsFromIndex,
|
|
51
|
+
supersededMarkers,
|
|
48
52
|
isTrustedApiRequest,
|
|
49
53
|
isJsonContentType,
|
|
50
54
|
webAuthGate,
|
|
51
55
|
} from './ops-core.js'
|
|
56
|
+
import { captureServices, serviceOf, resetCapturedServicesForTests } from './host-services.js'
|
|
57
|
+
import { applyDerivedBatch, derivedTextsOf, primeDerivedIncremental, NotIncrementalError } from './derived-incremental.js'
|
|
58
|
+
import { withSessionLock, withWriteLock } from './write-lock.js'
|
|
52
59
|
import { deleteSessionToTrash, listTrash, restoreTrash, purgeTrash, resolveSessionTitle } from './session-trash.js'
|
|
53
60
|
|
|
54
61
|
export const name = 'dsh-message-ops'
|
|
@@ -57,9 +64,90 @@ export const name = 'dsh-message-ops'
|
|
|
57
64
|
// apply 内部容错探测,见 registerToolTolerantly。
|
|
58
65
|
export const inject = []
|
|
59
66
|
|
|
67
|
+
/**
|
|
68
|
+
* 判定错误该回什么 HTTP 状态(0.39.6)。
|
|
69
|
+
*
|
|
70
|
+
* srv-audit D13:路由此前只认 `OpsError`,其余一律 500 —— 但**引擎/宿主契约拒绝**
|
|
71
|
+
* (surface replace 溯源不全、turn/step 关系闸、消息形状)本就是「请求与当前状态
|
|
72
|
+
* 冲突」,README 承诺 409,且客户端凭状态码区分「可重试」与「已失效」。
|
|
73
|
+
* 损坏日志(D17)同理:应 409 并附修复指引而不是 500。
|
|
74
|
+
* @param {unknown} err 抛出的错误
|
|
75
|
+
* @returns {number} HTTP 状态码
|
|
76
|
+
*/
|
|
77
|
+
function errorStatusOf(err) {
|
|
78
|
+
if (err instanceof OpsError) return err.status
|
|
79
|
+
const message = String((err && err.message) || err)
|
|
80
|
+
if (
|
|
81
|
+
/invalid replace surfaceOp|does not open the expected turn|does not match an open turn|does not match an open step|must include every shadowed|is not a surface event|lacks an identified message|invalid message role|mismatched tool call ids/i.test(
|
|
82
|
+
message,
|
|
83
|
+
)
|
|
84
|
+
) {
|
|
85
|
+
return 409
|
|
86
|
+
}
|
|
87
|
+
// 0.47.0(srv-audit E20):宿主/读取层的「日志本身坏了」是**状态问题**(可打开宿主修复),
|
|
88
|
+
// 不是内部 500。旧实现只匹配 /session log has/,漏了宿主 workspace 校验器的
|
|
89
|
+
// `corrupt session log "<path>"`(E20 实测列表/全文/写三路都落 500 并被 0.43.2 脱敏)。
|
|
90
|
+
if (/empty or header-less session log|invalid zstd frame|unsupported session version|session log has|corrupt session log|unsupported session format/i.test(message)) {
|
|
91
|
+
return 409
|
|
92
|
+
}
|
|
93
|
+
return 500
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 严格解析整数查询参数(0.41.2,srv-audit D18)。
|
|
98
|
+
*
|
|
99
|
+
* `Number.parseInt('3abc')` → 3、`'1e3'` → 1:旧实现会把明显非法的参数静默截断成
|
|
100
|
+
* 合法值并 200,与「seq=x → 400」的既有契约不一致。只接受纯十进制整数串。
|
|
101
|
+
* @param {string|null} raw 原始字符串
|
|
102
|
+
* @returns {number|undefined} 合法整数或 undefined
|
|
103
|
+
*/
|
|
104
|
+
function strictIntParam(raw) {
|
|
105
|
+
if (raw === null || raw === undefined) return undefined
|
|
106
|
+
const text = String(raw).trim()
|
|
107
|
+
if (!/^-?\d+$/.test(text)) return undefined
|
|
108
|
+
const value = Number(text)
|
|
109
|
+
return Number.isSafeInteger(value) ? value : undefined
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 把错误压成**可回给客户端**的文案(0.43.2,srv-audit P3 + D8 泄露面)。
|
|
114
|
+
*
|
|
115
|
+
* - 领域错误(OpsError):保留 message,但去掉尾部内部诊断 `[resolve: …]`
|
|
116
|
+
* (诊断仍进服务端日志,便于排障;不再出现在响应体/工具结果里)。
|
|
117
|
+
* - 其它错误(500):响应只说 internal error,**不泄露绝对路径/内部标识**;
|
|
118
|
+
* 完整信息走 console.error。
|
|
119
|
+
* @param {unknown} err 抛出值
|
|
120
|
+
* @param {string} status 已判定的 HTTP 状态
|
|
121
|
+
* @param {string} [where] 日志用路由标签
|
|
122
|
+
* @returns {{status:number, error:string}} 响应状态与文案
|
|
123
|
+
*/
|
|
124
|
+
function publicErrorOf(err, status, where = 'route') {
|
|
125
|
+
const raw = String((err && err.message) || err)
|
|
126
|
+
const diagAt = raw.indexOf('[resolve:')
|
|
127
|
+
const message = diagAt === -1 ? raw : raw.slice(0, diagAt).trim()
|
|
128
|
+
if (diagAt !== -1) {
|
|
129
|
+
console.warn('[message-ops] internal resolve diagnostic (' + where + '):', raw.slice(diagAt))
|
|
130
|
+
}
|
|
131
|
+
// 0.47.0(E20):损坏日志的宿主文案带绝对路径 —— 409 也要脱敏(细节进日志)。
|
|
132
|
+
if (status === 409 && /corrupt session log|invalid zstd frame|unsupported session (version|format)/i.test(message)) {
|
|
133
|
+
console.warn('[message-ops] unreadable session log (' + where + '):', message)
|
|
134
|
+
return { status, error: 'session log is corrupt or unreadable; open it once in the dsh host to repair, then retry' }
|
|
135
|
+
}
|
|
136
|
+
if (status === 500) {
|
|
137
|
+
console.error('[message-ops] internal error (' + where + '):', raw, err && err.stack ? String(err.stack).split('\n').slice(1, 4).join(' | ') : '')
|
|
138
|
+
return { status, error: 'internal error (details in the dsh server log)' }
|
|
139
|
+
}
|
|
140
|
+
return { status, error: message || 'request failed' }
|
|
141
|
+
}
|
|
142
|
+
|
|
60
143
|
function sendJson(res, status, body) {
|
|
61
144
|
const payload = JSON.stringify(body)
|
|
62
|
-
|
|
145
|
+
// 会话内容属敏感数据:禁止中间层/浏览器缓存,并阻止内容嗅探。
|
|
146
|
+
res.writeHead(status, {
|
|
147
|
+
'content-type': 'application/json; charset=utf-8',
|
|
148
|
+
'cache-control': 'no-store',
|
|
149
|
+
'x-content-type-options': 'nosniff',
|
|
150
|
+
})
|
|
63
151
|
res.end(payload)
|
|
64
152
|
}
|
|
65
153
|
|
|
@@ -81,10 +169,107 @@ async function readJsonBody(req) {
|
|
|
81
169
|
}
|
|
82
170
|
}
|
|
83
171
|
|
|
84
|
-
/**
|
|
172
|
+
/**
|
|
173
|
+
* 判定请求是否来自**显式配置**的可信 Host(0.47.1,srv-audit E19)。
|
|
174
|
+
*
|
|
175
|
+
* 宿主 0.2.3 下 `connection.admit` 不可调用时,非回环站点只能靠部署方在插件
|
|
176
|
+
* `config.trustedHosts` 里显式声明。判定与宿主同条件:
|
|
177
|
+
* - Host(去端口)必须精确命中列表;
|
|
178
|
+
* - `sec-fetch-site` 存在时必须是 same-origin(拒 cross-site);
|
|
179
|
+
* - `Origin` 存在时必须与本请求 Host 同源。
|
|
180
|
+
* 之后仍要过 `webAuthGate`(BrowserAuth cookie)—— 配置只放宽「来源」,不放宽认证。
|
|
181
|
+
*
|
|
182
|
+
* @param {object} req Node HTTP 请求(需 headers)
|
|
183
|
+
* @returns {boolean} 是否命中配置的可信 Host
|
|
184
|
+
*/
|
|
185
|
+
function isConfiguredTrustedHost(req) {
|
|
186
|
+
if (__trustedHosts.length === 0) return false
|
|
187
|
+
const headers = (req && req.headers) || {}
|
|
188
|
+
const hostHeader = String(headers.host || '').toLowerCase()
|
|
189
|
+
if (!hostHeader) return false
|
|
190
|
+
const hostnameOnly = hostHeader.split(':')[0]
|
|
191
|
+
if (!__trustedHosts.includes(hostHeader) && !__trustedHosts.includes(hostnameOnly)) return false
|
|
192
|
+
const site = String(headers['sec-fetch-site'] || '').toLowerCase()
|
|
193
|
+
if (site && site !== 'same-origin' && site !== 'none') return false
|
|
194
|
+
const origin = String(headers.origin || '').toLowerCase()
|
|
195
|
+
if (origin) {
|
|
196
|
+
let originHost = ''
|
|
197
|
+
try {
|
|
198
|
+
originHost = new URL(origin).host
|
|
199
|
+
} catch {
|
|
200
|
+
return false
|
|
201
|
+
}
|
|
202
|
+
if (originHost !== hostHeader && originHost !== hostnameOnly) return false
|
|
203
|
+
}
|
|
204
|
+
return true
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* 统一入口围栏:全部 /api/message-ops/* 路由先过这一层。
|
|
209
|
+
*
|
|
210
|
+
* 0.33.2:优先复用宿主 Connection 的 `requestRejection`(Host/Origin + BrowserAuth
|
|
211
|
+
* cookie + trustedHosts),与宿主 `/api` 完全同一条判据 —— 自研围栏只认回环 Host,
|
|
212
|
+
* 经 `--trusted-host` 暴露的站点(如 dsh.sepic.space)会整站 403,与 README 的承诺
|
|
213
|
+
* 不符。老宿主没有该服务时退回原有三层信任 + webAuthGate。
|
|
214
|
+
*/
|
|
85
215
|
async function fence(targetCtx, req, res) {
|
|
86
|
-
|
|
87
|
-
|
|
216
|
+
let connection = null
|
|
217
|
+
try {
|
|
218
|
+
connection = targetCtx && typeof targetCtx.get === 'function' ? targetCtx.get('connection') : null
|
|
219
|
+
} catch {
|
|
220
|
+
connection = null
|
|
221
|
+
}
|
|
222
|
+
// 0.41.1(srv-audit D16):宿主 0.2.2-rc.2 起移除了 `requestRejection`,改为
|
|
223
|
+
// `admit(request)`(返回 `{rejection?:number}` 或 `{peer}`)。旧实现直接退回
|
|
224
|
+
// 「只认回环 Host」的自研围栏 → 经 `--trusted-host` 暴露的站点整站 403
|
|
225
|
+
// (README 承诺的 trustedHosts 复用失效)。
|
|
226
|
+
//
|
|
227
|
+
// 0.46.1(P0):宿主 0.2.3 的 cordis 服务隔离会在 **admit 内部**读
|
|
228
|
+
// `connection.authentication` 时按调用方 fiber 校验 inject —— 本插件 `inject` 为空
|
|
229
|
+
// (tools 是可选增强,不能声明硬依赖),于是 admit 抛
|
|
230
|
+
// `cannot get property "connection.authentication" without inject`。
|
|
231
|
+
// 旧实现把这个异常当 `{rejection:401}` → **全站 401(GET 也挂)**。
|
|
232
|
+
// 现在:admit 抛错(非业务拒绝)时**降级**到静态围栏,不把内部异常翻译成拒绝;
|
|
233
|
+
// 真拒绝仍走 `{rejection}` 正常映射。
|
|
234
|
+
if (connection && typeof connection.admit === 'function' && typeof connection.requestRejection !== 'function') {
|
|
235
|
+
let admission = null
|
|
236
|
+
let admitFailed = false
|
|
237
|
+
try {
|
|
238
|
+
admission = connection.admit({ headers: req.headers, method: req.method, url: req.url })
|
|
239
|
+
} catch (err) {
|
|
240
|
+
admitFailed = true
|
|
241
|
+
noteAdmitFallback(err)
|
|
242
|
+
}
|
|
243
|
+
if (!admitFailed) {
|
|
244
|
+
if (admission && admission.rejection !== undefined && admission.rejection !== null) {
|
|
245
|
+
const status = typeof admission.rejection === 'number' ? admission.rejection : 403
|
|
246
|
+
sendJson(res, status, { ok: false, error: status === 401 ? 'unauthorized' : 'untrusted request origin (host connection rejected)' })
|
|
247
|
+
return false
|
|
248
|
+
}
|
|
249
|
+
return true
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (connection && typeof connection.requestRejection === 'function') {
|
|
253
|
+
let rejection
|
|
254
|
+
try {
|
|
255
|
+
rejection = connection.requestRejection({ headers: req.headers, method: req.method, url: req.url })
|
|
256
|
+
} catch {
|
|
257
|
+
rejection = 401
|
|
258
|
+
}
|
|
259
|
+
if (rejection !== undefined && rejection !== null && rejection !== false) {
|
|
260
|
+
const status = typeof rejection === 'number' ? rejection : 403
|
|
261
|
+
sendJson(res, status, { ok: false, error: status === 401 ? 'unauthorized' : 'untrusted request origin (host connection rejected)' })
|
|
262
|
+
return false
|
|
263
|
+
}
|
|
264
|
+
return true
|
|
265
|
+
}
|
|
266
|
+
if (!isTrustedApiRequest(req) && !isConfiguredTrustedHost(req)) {
|
|
267
|
+
sendJson(res, 403, {
|
|
268
|
+
ok: false,
|
|
269
|
+
error: __trustedHosts.length > 0
|
|
270
|
+
? 'untrusted request origin (host not in config.trustedHosts + same-origin only)'
|
|
271
|
+
: 'untrusted request origin (loopback Host + same-origin only)',
|
|
272
|
+
})
|
|
88
273
|
return false
|
|
89
274
|
}
|
|
90
275
|
// 0.10.8:宿主同条件 GET 被读全量(审计缺口)。宿主 /api admit = 三层围栏
|
|
@@ -98,6 +283,22 @@ async function fence(targetCtx, req, res) {
|
|
|
98
283
|
return true
|
|
99
284
|
}
|
|
100
285
|
|
|
286
|
+
/**
|
|
287
|
+
* admit 不可用(宿主服务隔离未声明 inject)时的降级告警(进程内只告警一次)。
|
|
288
|
+
* @param {unknown} err 原始异常
|
|
289
|
+
* @returns {void}
|
|
290
|
+
*/
|
|
291
|
+
function noteAdmitFallback(err) {
|
|
292
|
+
if (__admitFallbackWarned) return
|
|
293
|
+
__admitFallbackWarned = true
|
|
294
|
+
console.warn(
|
|
295
|
+
'[message-ops] connection.admit unavailable to this plugin fiber (' +
|
|
296
|
+
String((err && err.message) || err) +
|
|
297
|
+
'); falling back to the loopback/same-origin fence. --trusted-host sites may need the host to ' +
|
|
298
|
+
'admit this plugin (see README compatibility notes).',
|
|
299
|
+
)
|
|
300
|
+
}
|
|
301
|
+
|
|
101
302
|
/** 写操作围栏:入口信任 + Content-Type 必须 application/json(CSRF 纵深)。 */
|
|
102
303
|
async function writeFence(targetCtx, req, res) {
|
|
103
304
|
if (!(await fence(targetCtx, req, res))) return false
|
|
@@ -118,14 +319,32 @@ async function readFencedBody(req, res) {
|
|
|
118
319
|
}
|
|
119
320
|
}
|
|
120
321
|
|
|
121
|
-
/**
|
|
122
|
-
|
|
123
|
-
|
|
322
|
+
/**
|
|
323
|
+
* 从 sessions 注册表解析(两种 id 拼写都试)。
|
|
324
|
+
*
|
|
325
|
+
* @param ctx - 宿主 ctx
|
|
326
|
+
* @param sessionId - 会话 id(`uuid` / `session-<uuid>` 两种拼写都试)
|
|
327
|
+
* @param diag - 可选的诊断出参:`{ why: string }`。传了才会记录**为什么**成/败
|
|
328
|
+
* (只在需要把原因拼进错误信息的失败路径上传,成功路径零字符串开销)。
|
|
329
|
+
* @returns live SessionFace,或 `undefined`(未命中)
|
|
330
|
+
*/
|
|
331
|
+
// 0.37.4:宿主 0.2.3 的 fiber 隔离让 `ctx.get('agents'|'sessions')` 在插件 fiber 上
|
|
332
|
+
// 可能恒为 undefined(真机日志:boot 期全 undefined,写合成 turn 时 agents 仍不可见)。
|
|
333
|
+
// cordis 的 `ctx.inject(deps, fn)` 回调拿到的是**注入命名空间**,服务一定在其同名属性
|
|
334
|
+
// 上 —— 用它把两个关键服务捕获一次,供 resolveSession / alignLiveTurnCursor 复用。
|
|
335
|
+
function resolveSession(ctx, sessionId, diag) {
|
|
124
336
|
// 宿主自己的取法是 `this.ctx.sessions.get(id)`(api-session-controller 同款);
|
|
125
337
|
// 实测 `ctx.get("sessions")` 在 inject 子 fiber 下解析到的注册表**查不到视图已
|
|
126
338
|
// 加载的会话**(dock 已渲染但 get 双变体 miss —— agents.get 同 ctx 却命中),
|
|
127
339
|
// 故属性优先、ctx.get 兜底,两处都试全变体。
|
|
128
340
|
const candidates = []
|
|
341
|
+
// 诊断只写进调用方传进来的 diag 袋子(原先写进程级全局变量 → 0 读取方,
|
|
342
|
+
// 等于「排障线索被扔进黑洞」;现在由失败路径拼进 OpsError)。
|
|
343
|
+
const note = msg => {
|
|
344
|
+
if (diag) diag.why = msg
|
|
345
|
+
}
|
|
346
|
+
const capturedSessions = serviceOf(ctx, 'sessions')
|
|
347
|
+
if (capturedSessions) candidates.push(['captured', capturedSessions])
|
|
129
348
|
try {
|
|
130
349
|
if (ctx && ctx.sessions) candidates.push(['prop', ctx.sessions])
|
|
131
350
|
} catch {
|
|
@@ -138,7 +357,7 @@ function resolveSession(ctx, sessionId) {
|
|
|
138
357
|
/* absent */
|
|
139
358
|
}
|
|
140
359
|
if (candidates.length === 0) {
|
|
141
|
-
|
|
360
|
+
note('no-sessions-service')
|
|
142
361
|
return undefined
|
|
143
362
|
}
|
|
144
363
|
const variants = sessionIdVariants(sessionId)
|
|
@@ -151,7 +370,7 @@ function resolveSession(ctx, sessionId) {
|
|
|
151
370
|
for (const variant of variants) {
|
|
152
371
|
const s = svc.get(variant)
|
|
153
372
|
if (s !== undefined) {
|
|
154
|
-
|
|
373
|
+
note('hit via ' + src + '.get ' + String(variant).slice(0, 24))
|
|
155
374
|
return s
|
|
156
375
|
}
|
|
157
376
|
}
|
|
@@ -163,7 +382,7 @@ function resolveSession(ctx, sessionId) {
|
|
|
163
382
|
if (Array.isArray(arr)) {
|
|
164
383
|
const hit = arr.find(x => x && (variants.includes(x.id) || variants.includes(x.sessionId)))
|
|
165
384
|
if (hit) {
|
|
166
|
-
|
|
385
|
+
note('hit via ' + src + '.list() n=' + arr.length)
|
|
167
386
|
return hit
|
|
168
387
|
}
|
|
169
388
|
tried.push(
|
|
@@ -186,7 +405,7 @@ function resolveSession(ctx, sessionId) {
|
|
|
186
405
|
}
|
|
187
406
|
tried.push(src + ':miss')
|
|
188
407
|
}
|
|
189
|
-
|
|
408
|
+
note(tried.join(',') + ' tried=' + variants.length + ' first=' + String(variants[0]).slice(0, 30))
|
|
190
409
|
return undefined
|
|
191
410
|
}
|
|
192
411
|
|
|
@@ -199,9 +418,13 @@ function resolveSession(ctx, sessionId) {
|
|
|
199
418
|
* 会话 → 所有变更操作 404「not found in registry」。官方越界获取通道是
|
|
200
419
|
* retain(target, {source}) → await ready → binding.session(ISessions 契约);
|
|
201
420
|
* 引用在 mutation 完成后 release(final reference 触发 teardown,须先 flush)。
|
|
421
|
+
*
|
|
422
|
+
* @param diag - 可选诊断出参 `{ why }`:记录「live 面为什么没拿到」。原先这份
|
|
423
|
+
* 信息写在一个进程级诊断变量里,且**全仓 0 个读取方**(审计 §1.6)—— 等于每次
|
|
424
|
+
* 失败都重新拼一遍字符串却扔进黑洞。现在只由失败路径收集,并真的拼进错误信息。
|
|
202
425
|
*/
|
|
203
|
-
async function acquireSession(ctx, sessionId) {
|
|
204
|
-
const direct = resolveSession(ctx, sessionId)
|
|
426
|
+
async function acquireSession(ctx, sessionId, diag) {
|
|
427
|
+
const direct = resolveSession(ctx, sessionId, diag)
|
|
205
428
|
if (direct !== undefined) return { session: direct, release() {} }
|
|
206
429
|
const owners = []
|
|
207
430
|
// reflect 层:api-session-controller 把 ISessions(ClientSessions,带 retain)经
|
|
@@ -229,7 +452,7 @@ async function acquireSession(ctx, sessionId) {
|
|
|
229
452
|
owners.length === 0
|
|
230
453
|
? 'no-owner (prop-absent && get-absent)'
|
|
231
454
|
: owners.map(([src, o]) => src + ':no-retain(' + (o == null ? 'null' : typeof o) + ')').join(',')
|
|
232
|
-
|
|
455
|
+
if (diag) diag.why = (diag.why || '') + ' | ISessions:' + why
|
|
233
456
|
return null
|
|
234
457
|
}
|
|
235
458
|
const isess = holders[0][1]
|
|
@@ -239,7 +462,7 @@ async function acquireSession(ctx, sessionId) {
|
|
|
239
462
|
const binding = await ref.ready
|
|
240
463
|
const face = binding && binding.session
|
|
241
464
|
if (!face) {
|
|
242
|
-
|
|
465
|
+
if (diag) diag.why = 'retain-ready-no-session-face'
|
|
243
466
|
try {
|
|
244
467
|
ref.release()
|
|
245
468
|
} catch {
|
|
@@ -247,7 +470,6 @@ async function acquireSession(ctx, sessionId) {
|
|
|
247
470
|
}
|
|
248
471
|
return null
|
|
249
472
|
}
|
|
250
|
-
__resolveSource = 'acquired via ISessions.retain'
|
|
251
473
|
return {
|
|
252
474
|
session: face,
|
|
253
475
|
release: () => {
|
|
@@ -259,7 +481,7 @@ async function acquireSession(ctx, sessionId) {
|
|
|
259
481
|
},
|
|
260
482
|
}
|
|
261
483
|
} catch (e) {
|
|
262
|
-
|
|
484
|
+
if (diag) diag.why = 'retain-failed: ' + String(e && e.message).slice(0, 80)
|
|
263
485
|
if (ref) {
|
|
264
486
|
try {
|
|
265
487
|
ref.release()
|
|
@@ -272,6 +494,8 @@ async function acquireSession(ctx, sessionId) {
|
|
|
272
494
|
}
|
|
273
495
|
|
|
274
496
|
let __runningSource = null // 诊断:最近一次 isRunning 的判定来源
|
|
497
|
+
/** admit 降级告警只打一次(0.46.1 P0:0.2.3 服务隔离下 admit 会抛)。 */
|
|
498
|
+
let __admitFallbackWarned = false
|
|
275
499
|
/**
|
|
276
500
|
* 用**宿主内存日志**补算 marker's committed(0.10.5 · R2 的根治)。
|
|
277
501
|
*
|
|
@@ -314,7 +538,11 @@ function applyLiveCommitted(messages, live) {
|
|
|
314
538
|
for (const e of log) {
|
|
315
539
|
if (!e || typeof e.seq !== 'number' || e.seq <= maxUserSeq) continue
|
|
316
540
|
if (e.type !== 'user/message') continue
|
|
317
|
-
|
|
541
|
+
const source = (e.data || {}).source
|
|
542
|
+
if (!source || source.kind !== 'user') continue
|
|
543
|
+
// 0.27.0:restore 重放的 user/message 仍是 kind:'user'(否则界面上不可见),
|
|
544
|
+
// 用 replayedFrom 自识别;不算「真实用户输入」,否则恢复后 dock 立刻消失。
|
|
545
|
+
if (Object.hasOwn(source, 'replayedFrom')) continue
|
|
318
546
|
maxUserSeq = e.seq
|
|
319
547
|
}
|
|
320
548
|
if (maxUserSeq < 0) return false
|
|
@@ -337,8 +565,13 @@ function isRunning(ctx, sessionId) {
|
|
|
337
565
|
// running: this.ctx.agents.get(session.id)?.status === "running"
|
|
338
566
|
// 原实现把「agents 注册表有条目」直接当 running —— 会话仅在视图中打开
|
|
339
567
|
// 就有条目 → 打开即 409 锁死所有变更操作。必须再比对 status。
|
|
568
|
+
// 0.42.1(srv-audit D21):诊断变量是进程级的,旧实现不复位 → 一次请求的诊断会
|
|
569
|
+
// 串到下一次(跨会话运行中判定看似随机)。每个请求入口先清空。
|
|
570
|
+
__runningSource = ''
|
|
340
571
|
try {
|
|
341
572
|
const candidates = []
|
|
573
|
+
const fromCaptured = serviceOf(ctx, 'agents')
|
|
574
|
+
if (fromCaptured) candidates.push(fromCaptured)
|
|
342
575
|
try {
|
|
343
576
|
if (ctx && ctx.agents) candidates.push(ctx.agents)
|
|
344
577
|
} catch {
|
|
@@ -382,7 +615,9 @@ async function diskAppend(logPath, newEvents) {
|
|
|
382
615
|
if (!Array.isArray(newEvents) || newEvents.length === 0) throw new OpsError('diskAppend: empty batch', 400)
|
|
383
616
|
const jsonl = newEvents.map(e => JSON.stringify(e)).join('\n') + '\n'
|
|
384
617
|
const frame = zstdCompressSync(Buffer.from(jsonl, 'utf8'))
|
|
385
|
-
|
|
618
|
+
// 0.33.5(sec L4):追加写不跟随符号链接(Windows 无 O_NOFOLLOW 时退回普通追加)。
|
|
619
|
+
const noFollow = fsConstants.O_NOFOLLOW | fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY
|
|
620
|
+
const handle = await openFile(logPath, Number.isSafeInteger(noFollow) ? noFollow : 'a')
|
|
386
621
|
let closed = false
|
|
387
622
|
const closeHandle = async () => {
|
|
388
623
|
if (closed) return
|
|
@@ -397,7 +632,14 @@ async function diskAppend(logPath, newEvents) {
|
|
|
397
632
|
} catch (error) {
|
|
398
633
|
try {
|
|
399
634
|
await closeHandle()
|
|
400
|
-
|
|
635
|
+
// 0.33.1:只在「文件确实是 before + 我们这一帧」时才回滚。并发写者可能已在
|
|
636
|
+
// 之后追加了自己的帧,无条件 truncate(before) 会把对方的数据一并截掉。
|
|
637
|
+
const after = await statFile(logPath)
|
|
638
|
+
if (after.size === before + frame.length) {
|
|
639
|
+
await truncateFile(logPath, before)
|
|
640
|
+
} else {
|
|
641
|
+
throw new Error(`append rollback skipped: size ${after.size} != expected ${before + frame.length} (concurrent writer?)`)
|
|
642
|
+
}
|
|
401
643
|
} catch (rollbackError) {
|
|
402
644
|
throw new AggregateError([error, rollbackError], `failed to roll back append to "${logPath}"`)
|
|
403
645
|
}
|
|
@@ -408,16 +650,153 @@ async function diskAppend(logPath, newEvents) {
|
|
|
408
650
|
}
|
|
409
651
|
}
|
|
410
652
|
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
653
|
+
/**
|
|
654
|
+
* flush 宿主持久化并**吞掉失败**(不把已成功的写入改成失败)。
|
|
655
|
+
*
|
|
656
|
+
* 0.33.1:必须 await —— 旧实现只 catch 同步 throw,`sessions.flush()` 返回的
|
|
657
|
+
* rejected promise 被裸丢弃;Node 24 默认 `--unhandled-rejections=throw`,
|
|
658
|
+
* 一次 fsync EIO/磁盘满就会打死整个 dsh 进程。await 同时把「响应返回」放到
|
|
659
|
+
* 落盘之后,紧接的 restore 才能读到刚写的 marker。
|
|
660
|
+
* @param {object} ctx 插件上下文
|
|
661
|
+
* @param {object} session 目标会话
|
|
662
|
+
* @returns {Promise<void>} 无返回值;失败只告警
|
|
663
|
+
*/
|
|
664
|
+
async function flushSessions(ctx, session) {
|
|
665
|
+
const sessions = serviceOf(ctx, 'sessions')
|
|
666
|
+
if (!sessions || typeof sessions.flush !== 'function') {
|
|
667
|
+
// 0.39.4:服务不可见时 flush 不会执行 —— 事件只留在内存(崩溃即丢 marker)。
|
|
668
|
+
// 原来是静默 return,现在留一行诊断(同 agents 的一次性警告口径)。
|
|
669
|
+
if (!flushMissingWarned) {
|
|
670
|
+
flushMissingWarned = true
|
|
671
|
+
console.warn('[message-ops] host sessions service is not visible to this plugin; writes are not flushed to the persist layer')
|
|
418
672
|
}
|
|
673
|
+
return
|
|
674
|
+
}
|
|
675
|
+
try {
|
|
676
|
+
await sessions.flush(session)
|
|
677
|
+
} catch (error) {
|
|
678
|
+
console.warn('[message-ops] flush failed (events stay in memory):', error && error.message)
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// ── 0.33.1 磁盘写硬化 ──────────────────────────────────────────────────────
|
|
683
|
+
// 同一 logPath 的 read→plan→append 必须串行:两个并发请求各自读到同一 maxSeq,
|
|
684
|
+
// 会各写一份 seq,宿主加载判 `event seq N is not dense` → 整份会话打不开
|
|
685
|
+
// (已用宿主 format catalog 复现)。跨进程仍需宿主 flock,这里是进程内第一道闸。
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* 在同一会话日志上串行执行一次写事务。
|
|
689
|
+
* @param {string} key 会话日志绝对路径
|
|
690
|
+
* @param {Function} task 事务体(内部必须重新读盘,不得复用锁外快照)
|
|
691
|
+
* @returns {Promise<any>} task 的返回值
|
|
692
|
+
*/
|
|
693
|
+
/**
|
|
694
|
+
* 进程内「读自己刚写的」缓冲(0.40.2,srv-audit D4 第二层)。
|
|
695
|
+
*
|
|
696
|
+
* 宿主把 live append 异步批窗落盘;插件若在同一批窗内再次规划(只读盘兜底),
|
|
697
|
+
* 会看不到刚写的事件 → 同一 marker 被二次恢复(重复副本)。这里按 logPath 记录
|
|
698
|
+
* 最近一次写入的事件,读盘规划时按 seq 合并;一旦磁盘已包含这些 seq 即自动失效。
|
|
699
|
+
*/
|
|
700
|
+
const pendingLiveWrites = new Map() // logPath -> { events: object[], at: number }
|
|
701
|
+
const PENDING_LIVE_TTL_MS = 30_000
|
|
702
|
+
|
|
703
|
+
function notePendingLiveWrite(logPath, events) {
|
|
704
|
+
if (!Array.isArray(events) || events.length === 0) return
|
|
705
|
+
const kept = (events || []).filter(e => e && Number.isSafeInteger(e.seq))
|
|
706
|
+
if (kept.length === 0) return
|
|
707
|
+
pendingLiveWrites.set(logPath, { events: kept.slice(), at: Date.now() })
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function mergePendingLiveWrites(logPath, diskEvents) {
|
|
711
|
+
const entry = pendingLiveWrites.get(logPath)
|
|
712
|
+
const base = Array.isArray(diskEvents) ? diskEvents : []
|
|
713
|
+
if (!entry) return base
|
|
714
|
+
if (Date.now() - entry.at > PENDING_LIVE_TTL_MS) {
|
|
715
|
+
pendingLiveWrites.delete(logPath)
|
|
716
|
+
return base
|
|
717
|
+
}
|
|
718
|
+
const maxSeq = base.length > 0 ? base[base.length - 1].seq : -1
|
|
719
|
+
const fresh = entry.events.filter(e => e.seq > maxSeq)
|
|
720
|
+
if (fresh.length === 0) {
|
|
721
|
+
pendingLiveWrites.delete(logPath)
|
|
722
|
+
return base
|
|
723
|
+
}
|
|
724
|
+
return base.concat(fresh)
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* live 合成 turn 的 agents 服务探测(**告警,不阻断**)。
|
|
731
|
+
*
|
|
732
|
+
* 0.33.5 曾在这里 fail-closed(409),真机证明本机 profile 的插件上下文根本拿不到
|
|
733
|
+
* `agents`(`sessions/sessionController/...` 也多为 undefined)—— 一旦阻断,所有
|
|
734
|
+
* 回撤/删除/恢复都不可用。宿主在加载/唤醒时会从日志重建生命周期,实测照写不会
|
|
735
|
+
* 让日志不可加载,因此恢复 fail-open,只在首次缺失时告警一次。
|
|
736
|
+
*
|
|
737
|
+
* 残留风险(文档化):agents 缺失时既无法检测 maintenance 相位、也无法推进
|
|
738
|
+
* `lastTurn`;若宿主随后用旧游标开新 turn,可能出现重号。该风险在本机 profile
|
|
739
|
+
* 下不可消除(没有可用 seam),只能观察日志告警。
|
|
740
|
+
* @param {object} ctx 插件上下文
|
|
741
|
+
* @param {object} session 目标会话
|
|
742
|
+
* @param {{synthetic?:boolean}} win 窗口规划
|
|
743
|
+
* @returns {boolean} agents 服务是否可见
|
|
744
|
+
*/
|
|
745
|
+
let agentsMissingWarned = false
|
|
746
|
+
let flushMissingWarned = false
|
|
747
|
+
function agentsServiceVisible(ctx, session, win) {
|
|
748
|
+
if (!win || win.synthetic !== true) return true
|
|
749
|
+
const agents = serviceOf(ctx, 'agents')
|
|
750
|
+
if (!agents && !agentsMissingWarned) {
|
|
751
|
+
agentsMissingWarned = true
|
|
752
|
+
console.warn(
|
|
753
|
+
'[message-ops] host agents service is not visible to this plugin; synthetic turns are written without advancing the host turn cursor',
|
|
754
|
+
)
|
|
755
|
+
}
|
|
756
|
+
return !!agents
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* 磁盘写前置闸:撕裂尾 / 完整帧内撕裂行 / 非 v4 一律拒绝。
|
|
761
|
+
*
|
|
762
|
+
* 撕裂尾后直接 append 会让新帧与残字节拼成非法帧界(宿主扫描器同样抛
|
|
763
|
+
* `invalid frame magic`),整份日志从此不可加载;正确做法是让宿主打开一次
|
|
764
|
+
* 会话完成修复,用户再重试。v3 的 system/message 必须带 plugin source,
|
|
765
|
+
* 而我们的 source 形状按 v4 写,写一次就会让 v3 校验器拒绝整份日志。
|
|
766
|
+
* @param {{header:object,tornTail:boolean,tornRecords:number}} read 读盘结果
|
|
767
|
+
* @param {string} logPath 会话日志路径(仅用于报错)
|
|
768
|
+
*/
|
|
769
|
+
function assertWritableSessionLog(read, logPath) {
|
|
770
|
+
const raw = read && read.header ? read.header.version : undefined
|
|
771
|
+
// 0.41.0(srv-audit D14):旧实现只挡「整数且 ≠4」。header 无 version(旧单帧格式)
|
|
772
|
+
// 或 version 是字符串 "4" 时会被放行,并按「v3 形状」写出 marker(正文进
|
|
773
|
+
// message.content、无 opsMarker)—— 在 v4 宿主里会被当成系统提示注入模型。
|
|
774
|
+
// 磁盘写只接受**明确的数值 v4**;其它一律 409 并给出修复指引。
|
|
775
|
+
if (raw === undefined) {
|
|
776
|
+
throw new OpsError(
|
|
777
|
+
`session log ${logPath} has no numeric format version; disk writes only support v4 — open the session once in the host so it migrates, then retry`,
|
|
778
|
+
409,
|
|
779
|
+
)
|
|
780
|
+
}
|
|
781
|
+
const version = Number.isSafeInteger(raw) ? raw : Number.NaN
|
|
782
|
+
if (!Number.isSafeInteger(version) || version !== 4) {
|
|
783
|
+
throw new OpsError(
|
|
784
|
+
`session log ${logPath} is format v${version}; disk writes only support v4 (v3 requires a plugin source shape). Open the session once in the host so it migrates, then retry`,
|
|
785
|
+
409,
|
|
786
|
+
)
|
|
787
|
+
}
|
|
788
|
+
if (read && read.tornTail) {
|
|
789
|
+
throw new OpsError(
|
|
790
|
+
`session log ${logPath} has a torn tail (uncommitted write). Open the session once in the host to repair it, then retry`,
|
|
791
|
+
409,
|
|
792
|
+
)
|
|
793
|
+
}
|
|
794
|
+
if (read && read.tornRecords > 0) {
|
|
795
|
+
throw new OpsError(
|
|
796
|
+
`session log ${logPath} contains ${read.tornRecords} torn record(s) inside complete frames; refusing to append until the host repairs it`,
|
|
797
|
+
409,
|
|
798
|
+
)
|
|
419
799
|
}
|
|
420
|
-
return undefined
|
|
421
800
|
}
|
|
422
801
|
|
|
423
802
|
// ---------------------------------------------------------------------------
|
|
@@ -433,6 +812,24 @@ function pickSessionDir(sessionId) {
|
|
|
433
812
|
return dirs[0]
|
|
434
813
|
}
|
|
435
814
|
|
|
815
|
+
/**
|
|
816
|
+
* 把「live 面为什么没拿到」拼进 OpsError 消息(审计 §1.6 + §2.2)。
|
|
817
|
+
*
|
|
818
|
+
* 背景:0.5.6 排障期把原因拼进一个进程级诊断变量,但**全仓 0 个读取方** ——
|
|
819
|
+
* 于是 404/409 只剩 `not visible on current surface` / `session is running`,
|
|
820
|
+
* 排障者看不到「registry 是属性没读到、还是 get 双变体 miss、还是 retain 被拒」。
|
|
821
|
+
* 现在原因随 `diag` 一路带到失败点,只拼在**错误消息**里:
|
|
822
|
+
* · 不改 status —— 路由层仍按 `err.status` 映射 HTTP,工具端仍按 message 渲染;
|
|
823
|
+
* · 成功路径不产生任何字符串(diag 只在失败路径被读取);
|
|
824
|
+
* · 幂等 —— 同一条原因不会拼两遍(catch 里可能被重抛)。
|
|
825
|
+
*/
|
|
826
|
+
function withResolveDiag(err, diag) {
|
|
827
|
+
const why = diag && diag.why
|
|
828
|
+
if (!why || !(err instanceof OpsError)) return err
|
|
829
|
+
if (err.message.indexOf(why) >= 0) return err
|
|
830
|
+
return new OpsError(`${err.message} [resolve: ${why}]`, err.status)
|
|
831
|
+
}
|
|
832
|
+
|
|
436
833
|
// ---------------------------------------------------------------------------
|
|
437
834
|
// 文件派生缓存(P0-1):mtime+size 失效 · 在途去重 · LRU 16
|
|
438
835
|
// ---------------------------------------------------------------------------
|
|
@@ -456,6 +853,17 @@ function pickSessionDir(sessionId) {
|
|
|
456
853
|
// - **绝不缓存 raw events**(实测 114MB/次的短命堆分配,388 会话不可控)。
|
|
457
854
|
// 缓存的是**派生结果**:header / messages / shadowed / turnEndSeq /
|
|
458
855
|
// marker 进度 —— 量级 = 响应体(最大约 1.8MB)× 16,上限几十 MB。
|
|
856
|
+
// 0.25.0 追加的「消息全文索引」(seq → messageTextFull,见 buildDerived)
|
|
857
|
+
// 也属于派生结果:实测 9.1MB 会话派生常驻 2.68MB、索引 3633 行再加 0.37MB
|
|
858
|
+
// (只索引 listMessages 的行;若改索引全量 events 文本会 +3.39MB → 6.07MB,
|
|
859
|
+
// 16 条 LRU 就是 54MB,不取)。
|
|
860
|
+
// - 0.25.0 起 **searchCache 已并入本缓存**(原先是同一 key 的第二张表):
|
|
861
|
+
// opsSearch 的语料完全可由 messages + 同一份全文索引重建(实测 3633 行
|
|
862
|
+
// 重建 2.0ms),因此删掉整层重复实现。收益是双份:
|
|
863
|
+
// · 第一次搜索不再**第二次全量读盘**(实测 809ms / 1 次读盘 → 4.8ms / 0 次);
|
|
864
|
+
// · 常驻内存反而下降(旧 dump 出的 search 语料 3633 行常驻 +3.64MB/条 × 8 条,
|
|
865
|
+
// 现在只有 0.37MB/条的全文索引 × 16 条)。
|
|
866
|
+
// /messages 与 /search 现在共享同一条 mtimeMs+size 失效路径。
|
|
459
867
|
//
|
|
460
868
|
// **刻意不进缓存、每请求重算**(放进缓存就是 0.9.6 那类事故):
|
|
461
869
|
// - m.visible ← 依赖 live.surface.nodes(live 会话的 surface 会变)。
|
|
@@ -466,9 +874,26 @@ function pickSessionDir(sessionId) {
|
|
|
466
874
|
// - m.shadowed ← 判据恒为 computeShadowed(纯文件派生,与 live 无关,
|
|
467
875
|
// 0.9.6 起藏行判据就是它而不是 visible);但**写在每请求的浅拷贝上**,
|
|
468
876
|
// 缓存对象本身永不被改写 —— 跨请求零串扰。
|
|
469
|
-
|
|
877
|
+
// 0.33.4(perf-audit #6):16 → 48。顺序浏览 20 个会话时 16 会 0% 命中
|
|
878
|
+
// (每次 miss 都把自己下次要用的条目挤出去),48 覆盖一次翻页。
|
|
879
|
+
const DERIVED_CACHE_MAX = 48
|
|
470
880
|
const derivedCache = new Map() // logPath -> { mtimeMs, size, promise }
|
|
471
881
|
|
|
882
|
+
/**
|
|
883
|
+
* derived 对象 → 消息全文索引(seq → messageTextFull)。
|
|
884
|
+
*
|
|
885
|
+
* ⚠️ 为什么是 WeakMap 而不是 derived 的字段、也不是第二张缓存表(0.25.0 取舍):
|
|
886
|
+
* - **不能**做成 derived 的字段:`Object.keys(derived)` 是既有测试契约
|
|
887
|
+
* (test/derived-cache.test.js 断言它恰为 header/messages/shadowed/turnEndSeq),
|
|
888
|
+
* 且文本索引是内部细节,绝不该出现在任何 HTTP 响应里。
|
|
889
|
+
* - **不能**再建一张按 logPath 的缓存表:两张表的 key 相同却各自 stat/失效,
|
|
890
|
+
* 多一个「一边新一边旧」的窗口,且 0.25.0 已经把旧的 searchCache 并进来了
|
|
891
|
+
* (见上方缓存注释块)。
|
|
892
|
+
* - WeakMap 的生命周期与 derived 对象**严格同步**:缓存条目持 promise → derived
|
|
893
|
+
* 对象;条目被 LRU 淘汰/失效后 derived 与索引一起可回收,没有额外驻留。
|
|
894
|
+
*/
|
|
895
|
+
const derivedTexts = new WeakMap() // derived -> Map<seq, string>
|
|
896
|
+
|
|
472
897
|
/**
|
|
473
898
|
* 真实计算:读日志 → 消息列表 → 遮蔽集 → marker 恢复进度 → turn 边界。
|
|
474
899
|
* 返回的对象归缓存所有,**调用方不得原地修改**(opsList 用浅拷贝后再挂
|
|
@@ -476,7 +901,32 @@ const derivedCache = new Map() // logPath -> { mtimeMs, size, promise }
|
|
|
476
901
|
*/
|
|
477
902
|
async function buildDerived(logPath) {
|
|
478
903
|
// 大日志的逐帧解压走异步让出路径,避免阻塞 GUI 事件循环(评审 P1)。
|
|
479
|
-
const { header, events } = await readSessionFileAsync(logPath)
|
|
904
|
+
const { header, events, frameCount, partial } = await readSessionFileAsync(logPath)
|
|
905
|
+
// 0.40.4(srv-audit D22):`partial`(>500 帧)此前计算了但无人消费 —— 大日志
|
|
906
|
+
// (实测 26363 帧 / 137MB)用户看不到任何提示。这里随派生结果带出,由 GET 响应
|
|
907
|
+
// 的 `frames`/`partial` 字段回给客户端。
|
|
908
|
+
// ⚠️ 必须**原地扩展**同一个对象:`deriveFromEvents` 把文本索引登记在 WeakMap
|
|
909
|
+
// (键就是返回对象),spread 出新对象会让每次请求都弱映射 miss → 重新读盘。
|
|
910
|
+
const derived = deriveFromEvents(header, events)
|
|
911
|
+
derived.frameCount = frameCount
|
|
912
|
+
derived.partial = partial
|
|
913
|
+
// 0.44.0(D6):把增量状态的建表(20k 事件约 32ms)摊进这次本来就要 19.5s 的读盘,
|
|
914
|
+
// 之后写后 apply 是稳态 ~1.5ms;失败返回 false 不影响读路径。
|
|
915
|
+
primeDerivedIncremental(derived, events)
|
|
916
|
+
return derived
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* 纯函数:事件数组 → 文件派生结果(消息 / 遮蔽集 / marker 进度 / turn 边界)。
|
|
921
|
+
*
|
|
922
|
+
* 0.35.0:从 buildDerived 拆出,供 live 会话复用 —— 写路径落盘后文件已变化,
|
|
923
|
+
* 但宿主内存里的 `session.log` 是权威,直接派生可跳过 131MB 的 zstd 解压+JSON 解析
|
|
924
|
+
* (实测 20–40s → 秒级)。
|
|
925
|
+
* @param {object} header 会话头(live 可能缺字段,调用方补齐)
|
|
926
|
+
* @param {Array} events 事件数组
|
|
927
|
+
* @returns {{header:object, messages:Array, shadowed:Set<number>, turnEndSeq:number}} 派生结果
|
|
928
|
+
*/
|
|
929
|
+
function deriveFromEvents(header, events) {
|
|
480
930
|
const messages = listMessages(events)
|
|
481
931
|
const shadowed = computeShadowed(events)
|
|
482
932
|
// 0.8.0 按轮步进:为每个回撤/删除标记附恢复进度与"待恢复轮"。
|
|
@@ -486,6 +936,8 @@ async function buildDerived(logPath) {
|
|
|
486
936
|
// 本循环直接跳过,marker 循环体也一次都不会执行)。
|
|
487
937
|
const seqText = messages.some(m => m.marker === true) ? new Map() : null
|
|
488
938
|
const restoreIndex = seqText ? buildRestoreIndex(events) : null
|
|
939
|
+
// 0.27.0:一次折叠算出「已被后续回撤取代」的 marker(与 planRestore 的 409 闸同源)。
|
|
940
|
+
const superseded = seqText ? supersededMarkers(events) : null
|
|
489
941
|
for (const e of seqText ? events : []) {
|
|
490
942
|
if (!e || typeof e.seq !== 'number') continue
|
|
491
943
|
if (e.type !== 'user/message' && e.type !== 'assistant/message') continue
|
|
@@ -510,6 +962,8 @@ async function buildDerived(logPath) {
|
|
|
510
962
|
// —— 这正是 opencode 的 `messages.slice(0, boundaryIndex)`(边界自己也不显示)。
|
|
511
963
|
for (const m of messages) {
|
|
512
964
|
if (!m || m.marker !== true) continue
|
|
965
|
+
// 已被后续回撤取代 → dock 不再列出(恢复它等于绕过后来那次回撤)。
|
|
966
|
+
if (superseded && superseded.has(m.seq)) m.superseded = true
|
|
513
967
|
const prog = restoreProgressFromIndex(restoreIndex, m.seq)
|
|
514
968
|
if (!prog) {
|
|
515
969
|
m.restoreComplete = false
|
|
@@ -529,7 +983,10 @@ async function buildDerived(logPath) {
|
|
|
529
983
|
// 3721/3746 全是这么来的)。
|
|
530
984
|
//
|
|
531
985
|
// 正向修法:range 是 marker 的语义本体("我遮蔽了谁"),dock 只该用它。
|
|
532
|
-
|
|
986
|
+
// 0.33.4(perf-audit #3):用已建好的 restoreIndex.bySeq 查事件本体。
|
|
987
|
+
// 旧实现每个 marker 都对全部事件做一次 find → O(markers × events) 二次方,
|
|
988
|
+
// 实测 10 marker × 22k 事件 62ms、100 marker × 165k 事件 4–5s。
|
|
989
|
+
const range = readReplaceOp((restoreIndex && restoreIndex.bySeq.get(m.seq)) || null)
|
|
533
990
|
if (range) m.range = range
|
|
534
991
|
m.pendingTurns = pendingRestoreTurnsFromIndex(restoreIndex, m.seq, prog).map(t => ({
|
|
535
992
|
upTo: t.seqs[t.seqs.length - 1],
|
|
@@ -612,7 +1069,85 @@ async function buildDerived(logPath) {
|
|
|
612
1069
|
if (!m || typeof m.seq !== 'number') continue
|
|
613
1070
|
m.turnStartSeq = enclosingTurnStart.get(m.seq) ?? null
|
|
614
1071
|
}
|
|
615
|
-
|
|
1072
|
+
// ── 0.25.0 · 供 /text 与 /search 复用的「同一份」消息全文索引 ──────────────
|
|
1073
|
+
//
|
|
1074
|
+
// 实测取舍(样本 = 9.1MB / 12890 事件 / 3633 消息,见上方缓存注释块):
|
|
1075
|
+
// ① 索引**只覆盖 listMessages 的行**(user/assistant/system/developer +
|
|
1076
|
+
// tool/call),3633 条、常驻 0.37MB、构建 p50 2.1ms。listMessages 恰好就是
|
|
1077
|
+
// /text 的消费面(面板 pick / 铅笔编辑框都从这些行来),也恰好是
|
|
1078
|
+
// /search 语料的全部行(旧 buildSearchCorpus 也遍历同一批 rows)。
|
|
1079
|
+
// 逐行取 messageTextFull,与旧 /text 的 `messageTextFull(ev)` 逐字一致
|
|
1080
|
+
// (tool/call 恒为 '',与旧行为相同)。
|
|
1081
|
+
// ② **不索引非消息事件**(tool/result 最多 49930 字/条、1676 条共 1.5M 字符):
|
|
1082
|
+
// 「整个 events 全量文本」变体实测常驻 +3.39MB(2.68 → 6.07MB),16 条 LRU
|
|
1083
|
+
// 就是 54MB 纯浪费;这些 seq 界面取不到(面板/编辑框只认消息行),
|
|
1084
|
+
// 真被请求时走下面的「未命中按需读盘」分支。
|
|
1085
|
+
// ③ **不另建 search 语料表**:语料 = 本索引 + snippet 兜底,实测重建 2.0ms。
|
|
1086
|
+
// 旧 searchCache(同 key 的第二张表、常驻 +3.64MB/条 × 8)因此整个删除。
|
|
1087
|
+
const messageTexts = new Map() // seq -> 全文(仅 listMessages 行)
|
|
1088
|
+
const rowSeqs = new Set()
|
|
1089
|
+
for (const m of messages) if (m && typeof m.seq === 'number') rowSeqs.add(m.seq)
|
|
1090
|
+
for (const e of events) {
|
|
1091
|
+
if (!e || typeof e.seq !== 'number' || !rowSeqs.has(e.seq)) continue
|
|
1092
|
+
messageTexts.set(e.seq, messageTextFull(e))
|
|
1093
|
+
}
|
|
1094
|
+
// 0.43.0(srv-audit D24):宿主把「会话标题」落成 `session/title` 事件并由投影折叠
|
|
1095
|
+
// 最后一条(dsh-session-title:`events.findLast(type==='session/title')`)。
|
|
1096
|
+
// 插件此前只认投影行/header/首条用户消息 —— 未打开过的会话标题会与侧栏不一致。
|
|
1097
|
+
// 这里在已有遍历成本内折叠,零额外读盘。
|
|
1098
|
+
let sessionTitle = null
|
|
1099
|
+
for (const e of events) {
|
|
1100
|
+
if (e && e.type === 'session/title' && e.data && typeof e.data.title === 'string' && e.data.title.trim()) {
|
|
1101
|
+
sessionTitle = e.data.title.trim()
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
const derived = { header, messages, shadowed, turnEndSeq, sessionTitle }
|
|
1105
|
+
derivedTexts.set(derived, messageTexts)
|
|
1106
|
+
return derived
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// 0.35.0:live 会话的派生结果按「事件数组引用 + 长度」缓存。宿主 append 会让
|
|
1110
|
+
// 长度变化,自动重算;surface replace 也追加事件,因此长度是足够的失效信号。
|
|
1111
|
+
const liveDerivedCache = new WeakMap() // events -> { length, derived }
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* 从宿主内存事件派生(不读盘)。
|
|
1115
|
+
* @param {object} live 宿主会话
|
|
1116
|
+
* @param {Array} events live 事件数组
|
|
1117
|
+
* @param {string} sessionId 会话 id(header 缺 id 时兜底)
|
|
1118
|
+
* @returns {object} 派生结果
|
|
1119
|
+
*/
|
|
1120
|
+
function deriveFromLive(live, events, sessionId) {
|
|
1121
|
+
const cached = liveDerivedCache.get(events)
|
|
1122
|
+
if (cached && cached.length === events.length) return cached.derived
|
|
1123
|
+
const length = events.length
|
|
1124
|
+
const liveHeader = (live && live.header) || {}
|
|
1125
|
+
const header = {
|
|
1126
|
+
...liveHeader,
|
|
1127
|
+
id: liveHeader.id || sessionId,
|
|
1128
|
+
createdAt: typeof liveHeader.createdAt === 'number' ? liveHeader.createdAt : 0,
|
|
1129
|
+
}
|
|
1130
|
+
const derived = deriveFromEvents(header, events)
|
|
1131
|
+
liveDerivedCache.set(events, { length, derived })
|
|
1132
|
+
return derived
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/**
|
|
1136
|
+
* 取派生结果:live 有内存事件时优先(跳过读盘),否则走文件缓存。
|
|
1137
|
+
* @param {object|undefined} ctx 插件上下文(无 sessions 服务时为 undefined)
|
|
1138
|
+
* @param {string} sessionId 会话 id
|
|
1139
|
+
* @param {string} logPath 日志路径
|
|
1140
|
+
* @returns {Promise<{derived:object, live:object|null}>} 派生结果与 live 会话
|
|
1141
|
+
*/
|
|
1142
|
+
async function derivedAndLive(ctx, sessionId, logPath) {
|
|
1143
|
+
const live = ctx ? resolveSession(ctx, sessionId) : null
|
|
1144
|
+
const events = live ? sessionLogOf(live) : null
|
|
1145
|
+
if (Array.isArray(events) && events.length > 0) {
|
|
1146
|
+
// 0.42.2(ui-0404 观察):live 派生不读盘,因此没有 frameCount —— 响应里
|
|
1147
|
+
// `frames` 缺失会让调用方误以为是契约不一致。用 `derivedFrom` 显式说明来源。
|
|
1148
|
+
return { derived: deriveFromLive(live, events, sessionId), live, derivedFrom: 'live' }
|
|
1149
|
+
}
|
|
1150
|
+
return { derived: await loadDerived(logPath), live, derivedFrom: 'disk' }
|
|
616
1151
|
}
|
|
617
1152
|
|
|
618
1153
|
/**
|
|
@@ -627,7 +1162,11 @@ async function loadDerived(logPath) {
|
|
|
627
1162
|
derivedCache.set(logPath, hit) // LRU touch(Map 插入序 = LRU 序)
|
|
628
1163
|
return hit.promise
|
|
629
1164
|
}
|
|
630
|
-
const entry = { mtimeMs: st.mtimeMs, size: st.size, promise:
|
|
1165
|
+
const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: null, value: null }
|
|
1166
|
+
entry.promise = buildDerived(logPath).then(derived => {
|
|
1167
|
+
entry.value = derived
|
|
1168
|
+
return derived
|
|
1169
|
+
})
|
|
631
1170
|
derivedCache.delete(logPath)
|
|
632
1171
|
derivedCache.set(logPath, entry)
|
|
633
1172
|
while (derivedCache.size > DERIVED_CACHE_MAX) {
|
|
@@ -646,11 +1185,20 @@ async function opsList(targetCtx, sessionId, opts = {}) {
|
|
|
646
1185
|
const { logPath } = pickSessionDir(sessionId)
|
|
647
1186
|
// 文件派生段(读日志 → 消息 → 遮蔽集 → marker 进度 → turn 边界)走缓存:
|
|
648
1187
|
// key = logPath、失效看读前 stat 的 mtimeMs+size,见 loadDerived 注释。
|
|
649
|
-
const {
|
|
1188
|
+
const { derived, live, derivedFrom } = await derivedAndLive(targetCtx, sessionId, logPath)
|
|
1189
|
+
const { header, messages: baseMessages, shadowed, turnEndSeq } = derived
|
|
650
1190
|
// 每请求**浅拷贝**一份再挂 per-request 字段:缓存对象永不被改写,
|
|
651
|
-
// 并发请求之间零串扰(浅拷
|
|
1191
|
+
// 并发请求之间零串扰(浅拷 3633 个小对象实测 0.56ms / 请求)。
|
|
1192
|
+
//
|
|
1193
|
+
// 0.25.0 评估结论:**保留浅拷,不做「只投影 compact 需要的字段」的特化**。
|
|
1194
|
+
// · 实测省下的量级 = 0.56ms(浅拷)→ 0.12ms(零浅拷 + 投影内联算),
|
|
1195
|
+
// 即约 0.4ms;而响应里 `JSON.stringify` 本身 9.9ms、网络/渲染是几十 ms。
|
|
1196
|
+
// · 代价却是**两套行语义**:full 视图仍要浅拷(它返回整行 + visible/shadowed),
|
|
1197
|
+
// compact 视图若改成「零浅拷」就多一条「不得再改行」的隐式约束;任何未来
|
|
1198
|
+
// 往 per-request 行上挂字段的改动都会静默只对 full 生效。这个风险 > 0.4ms。
|
|
1199
|
+
// · 可选的微优化(已评估、不采纳):把 `{...m}` 换成 `Object.assign({}, m)` 或
|
|
1200
|
+
// 预建模板 —— V8 上差异在噪声内(实测 0.5~0.6ms 区间抖动)。
|
|
652
1201
|
const messages = baseMessages.map(m => ({ ...m }))
|
|
653
|
-
const live = resolveSession(targetCtx, sessionId)
|
|
654
1202
|
// R2 根治:磁盘派生可能还停在落盘批窗之前,用 live.log 补算 committed。
|
|
655
1203
|
// 必须在 messages 浅拷贝之后(绝不改写 derivedCache 里的对象)。
|
|
656
1204
|
applyLiveCommitted(messages, live)
|
|
@@ -704,6 +1252,8 @@ async function opsList(targetCtx, sessionId, opts = {}) {
|
|
|
704
1252
|
// 客户端拿到 undefined 会把**已恢复完毕**的 marker 继续列在待恢复列表里。
|
|
705
1253
|
restoreComplete: m.restoreComplete === true,
|
|
706
1254
|
committed: m.committed === true,
|
|
1255
|
+
// 0.27.0:已被后续回撤取代的 marker —— dock 必须隐藏(同 planRestore 的 409 闸)
|
|
1256
|
+
superseded: m.superseded === true,
|
|
707
1257
|
}))
|
|
708
1258
|
: messages
|
|
709
1259
|
|
|
@@ -713,7 +1263,7 @@ async function opsList(targetCtx, sessionId, opts = {}) {
|
|
|
713
1263
|
id: header.id,
|
|
714
1264
|
createdAt: header.createdAt,
|
|
715
1265
|
parentSession: header.parentSession ?? null,
|
|
716
|
-
confirmTitle: resolveSessionTitle(targetCtx, sessionId) || header.id,
|
|
1266
|
+
confirmTitle: resolveSessionTitle(targetCtx, sessionId, { eventTitle: derived.sessionTitle }) || header.id,
|
|
717
1267
|
},
|
|
718
1268
|
running: isRunning(targetCtx, sessionId),
|
|
719
1269
|
runningSource: __runningSource,
|
|
@@ -723,56 +1273,51 @@ async function opsList(targetCtx, sessionId, opts = {}) {
|
|
|
723
1273
|
markerCount,
|
|
724
1274
|
turnEndSeq,
|
|
725
1275
|
messages: visibleMessages,
|
|
1276
|
+
// 0.40.4(srv-audit D22):大日志读取规模(>500 帧 partial=true),供客户端提示。
|
|
1277
|
+
// `frames` 只在磁盘派生时可算(live 派生不读盘);`derivedFrom` 显式说明来源。
|
|
1278
|
+
derivedFrom,
|
|
1279
|
+
...(Number.isSafeInteger(derived.frameCount) ? { frames: derived.frameCount } : {}),
|
|
1280
|
+
...(derived.partial === true ? { partial: true } : {}),
|
|
726
1281
|
}
|
|
727
1282
|
}
|
|
728
1283
|
|
|
729
1284
|
// ---------------------------------------------------------------------------
|
|
730
1285
|
// Per-session search (full text, beyond the 160-char snippet)
|
|
731
1286
|
// ---------------------------------------------------------------------------
|
|
732
|
-
|
|
733
|
-
|
|
1287
|
+
// 0.25.0:**不再有第二张 searchCache**。旧实现自带 SEARCH_CACHE_MAX=8 的
|
|
1288
|
+
// logPath/mtimeMs/size 表,与 derivedCache key 完全相同却互不复用 —— 后果是
|
|
1289
|
+
// 「先 /messages 再 /search」必然为同一份文件**再读一遍盘**(9.1MB 会话实测
|
|
1290
|
+
// 540ms 纯重复成本),而两张表各自失效还多一个「一边新一边旧」的窗口。
|
|
1291
|
+
// 现在语料由 loadDerived 的派生结果重建(实测 3633 行 2.0ms),共享同一条
|
|
1292
|
+
// mtimeMs+size 失效路径与 LRU 16;常驻内存同时下降(旧的语料副本 +3.64MB/条,
|
|
1293
|
+
// 现在只有 0.37MB/条的 messageTexts)。
|
|
734
1294
|
|
|
735
|
-
/**
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
const
|
|
741
|
-
|
|
1295
|
+
/** derived 的 messages → 可搜索语料(文本优先取 messageTexts,缺失退回 snippet)。 */
|
|
1296
|
+
// 0.33.12(perf-audit #5):语料只依赖 derived(shadowed 是该文件的纯派生),
|
|
1297
|
+
// 缓存到 WeakMap 后 /search 不再每次重建 + 逐行 toLowerCase(45k 行 140ms → ~10ms)。
|
|
1298
|
+
const searchCorpusCache = new WeakMap()
|
|
1299
|
+
function searchCorpusOf(derived) {
|
|
1300
|
+
const cached = searchCorpusCache.get(derived)
|
|
1301
|
+
if (cached) return cached
|
|
1302
|
+
const texts = derivedTexts.get(derived) || new Map()
|
|
1303
|
+
const { messages, shadowed } = derived
|
|
742
1304
|
const corpus = []
|
|
743
1305
|
for (const m of messages) {
|
|
744
|
-
const
|
|
745
|
-
const text = ev ? messageTextFull(ev) : ''
|
|
1306
|
+
const text = texts.get(m.seq) || m.snippet || ''
|
|
746
1307
|
corpus.push({
|
|
747
1308
|
seq: m.seq,
|
|
748
1309
|
type: m.type,
|
|
749
1310
|
role: m.role,
|
|
750
1311
|
marker: m.marker === true,
|
|
751
1312
|
shadowed: shadowed.has(m.seq),
|
|
752
|
-
text
|
|
1313
|
+
text,
|
|
1314
|
+
lower: text.toLowerCase(),
|
|
753
1315
|
})
|
|
754
1316
|
}
|
|
1317
|
+
searchCorpusCache.set(derived, corpus)
|
|
755
1318
|
return corpus
|
|
756
1319
|
}
|
|
757
1320
|
|
|
758
|
-
async function loadSearchCorpus(logPath) {
|
|
759
|
-
const st = await statFile(logPath)
|
|
760
|
-
const hit = searchCache.get(logPath)
|
|
761
|
-
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
|
|
762
|
-
searchCache.delete(logPath)
|
|
763
|
-
searchCache.set(logPath, hit)
|
|
764
|
-
return hit.promise
|
|
765
|
-
}
|
|
766
|
-
const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: buildSearchCorpus(logPath) }
|
|
767
|
-
searchCache.delete(logPath)
|
|
768
|
-
searchCache.set(logPath, entry)
|
|
769
|
-
while (searchCache.size > SEARCH_CACHE_MAX) searchCache.delete(searchCache.keys().next().value)
|
|
770
|
-
entry.promise.catch(() => {
|
|
771
|
-
if (searchCache.get(logPath) === entry) searchCache.delete(logPath)
|
|
772
|
-
})
|
|
773
|
-
return entry.promise
|
|
774
|
-
}
|
|
775
|
-
|
|
776
1321
|
function searchSnippet(text, query, radius = 45) {
|
|
777
1322
|
const lower = text.toLowerCase()
|
|
778
1323
|
const at = lower.indexOf(query)
|
|
@@ -793,13 +1338,14 @@ async function opsSearch(targetCtx, sessionId, query, opts = {}) {
|
|
|
793
1338
|
}
|
|
794
1339
|
const limit = Number.isSafeInteger(opts && opts.limit) ? Math.max(1, Math.min(100, opts.limit)) : 50
|
|
795
1340
|
const { logPath } = pickSessionDir(sessionId)
|
|
796
|
-
|
|
1341
|
+
// 与 /messages 共用同一条缓存:命中时为 0 读盘、语料重建 2.0ms。
|
|
1342
|
+
const corpus = searchCorpusOf((await derivedAndLive(targetCtx, sessionId, logPath)).derived)
|
|
797
1343
|
const needle = q.toLowerCase()
|
|
798
1344
|
const results = []
|
|
799
1345
|
let total = 0
|
|
800
1346
|
for (const row of corpus) {
|
|
801
1347
|
if (role && row.role !== role) continue
|
|
802
|
-
if (!row.
|
|
1348
|
+
if (!row.lower.includes(needle)) continue
|
|
803
1349
|
total++
|
|
804
1350
|
if (results.length >= limit) continue
|
|
805
1351
|
results.push({
|
|
@@ -814,30 +1360,267 @@ async function opsSearch(targetCtx, sessionId, query, opts = {}) {
|
|
|
814
1360
|
return { ok: true, query: q, role, limit, total, truncated: total > results.length, results }
|
|
815
1361
|
}
|
|
816
1362
|
|
|
817
|
-
/**
|
|
818
|
-
|
|
1363
|
+
/**
|
|
1364
|
+
* 单条消息全文(GET /api/message-ops/text 的唯一实现)。
|
|
1365
|
+
*
|
|
1366
|
+
* 0.25.0 修的就是这个绕路:旧路由每次 `readSessionFileAsync(logPath)` 全量重读
|
|
1367
|
+
* 日志(9.1MB 会话实测 550~1100ms/次),而面板每选一条消息就打一次 —— 绕过
|
|
1368
|
+
* 了 loadDerived 的 mtimeMs+size 缓存,等于把 /messages 刚付出的解压+解析
|
|
1369
|
+
* 成本再付一遍。现在命中缓存的成本 = 一次 Map.get(实测 0 读盘、<0.1ms)。
|
|
1370
|
+
*
|
|
1371
|
+
* 未命中(不在 messages 行里 / 缓存被 LRU 挤出 / 文件已变化):退回「按需
|
|
1372
|
+
* 现读」,语义与旧实现完全一致(旧实现本来就是 ev 不存在 → 404)。
|
|
1373
|
+
* @returns {Promise<string>} 全文(未索引的行返回 '')
|
|
1374
|
+
* @throws {OpsError} 404 = 该 seq 在日志里不存在;400 = 参数非法
|
|
1375
|
+
*/
|
|
1376
|
+
async function opsText(sessionId, seq, targetCtx) {
|
|
1377
|
+
if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
|
|
1378
|
+
if (!Number.isSafeInteger(seq) || seq < 0) throw new OpsError('invalid seq', 400)
|
|
1379
|
+
// seq 0 在日志头里是结构事件区(permission/preset 等,实测恒非消息),
|
|
1380
|
+
// messageText 恒空串;引用按钮/编辑框不可能点它 —— 保持 404 而不是 200 {text:""}。
|
|
1381
|
+
if (seq === 0) throw new OpsError('no quotable message at seq 0', 404)
|
|
1382
|
+
const { logPath } = pickSessionDir(sessionId)
|
|
1383
|
+
const derived = (await derivedAndLive(targetCtx, sessionId, logPath)).derived
|
|
1384
|
+
const texts = derivedTexts.get(derived)
|
|
1385
|
+
if (texts && texts.has(seq)) return texts.get(seq)
|
|
1386
|
+
// 冷分支:缓存里没有这条 seq。两种可能 ——
|
|
1387
|
+
// a) 它压根不是消息事件(tool/result 之类):旧实现也会找到 event 并返回
|
|
1388
|
+
// messageTextFull 的结果(可能非空),所以这里同样按需读盘,**不改变** 404 语义;
|
|
1389
|
+
// b) 缓存条目刚被 LRU 淘汰/文件已变:读盘后就是最新真相。
|
|
1390
|
+
const { events } = await readSessionFileAsync(logPath)
|
|
1391
|
+
const ev = events.find(e => e && e.seq === seq)
|
|
1392
|
+
if (!ev) throw new OpsError('seq not found', 404)
|
|
1393
|
+
return messageTextFull(ev)
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
/**
|
|
1397
|
+
* live 写入的统一落地与失败收尾(0.35.1 M4)。
|
|
1398
|
+
*
|
|
1399
|
+
* opsCommit / opsRestore 只在「怎么规划」上不同;落地后的三件事完全一致:
|
|
1400
|
+
* applyScriptLive → 推动宿主 turn 游标(失败告警)→ flush;失败时闭合窗口
|
|
1401
|
+
* (applyScriptLive 内部已完成,至多一次)并尽力推进游标,然后原样抛出。
|
|
1402
|
+
* @param {object} targetCtx 插件上下文
|
|
1403
|
+
* @param {object} session 宿主会话
|
|
1404
|
+
* @param {string} sessionId 会话 id(告警用)
|
|
1405
|
+
* @param {object} win 窗口规划(synthetic/turn/step)
|
|
1406
|
+
* @param {object} script buildCommitScript / buildRestoreScript 的结果
|
|
1407
|
+
* @param {object} diag 诊断收集器
|
|
1408
|
+
* @returns {Promise<{state:{windowOpened:boolean,closed:boolean,emitted:Array}, aligned:boolean}>} 落盘状态与对齐结果
|
|
1409
|
+
*/
|
|
1410
|
+
async function runLiveScript(targetCtx, session, sessionId, win, script, diag) {
|
|
1411
|
+
const state = { windowOpened: false, closed: false, emitted: [] }
|
|
1412
|
+
try {
|
|
1413
|
+
applyScriptLive(session, script, state)
|
|
1414
|
+
// 0.39.5(srv-audit D2):闭合失败 = 窗口还开着。这时**不能推进宿主 turn 游标**
|
|
1415
|
+
// —— 宿主下一次真实轮次会用同一个 turn 号,加载端关系闸会拒绝整份日志
|
|
1416
|
+
// (`turn/start does not open the expected turn`)。
|
|
1417
|
+
if (state.closeFailures && state.closeFailures.length > 0) {
|
|
1418
|
+
const detail = state.closeFailures.map(f => f.kind + ': ' + f.message).join('; ')
|
|
1419
|
+
console.warn('[message-ops] synthetic turn left open (postamble rejected):', { session: sessionId, turn: win.turn, detail })
|
|
1420
|
+
await flushSessions(targetCtx, session)
|
|
1421
|
+
return { state, aligned: false, partial: true, warning: 'synthetic turn left open (' + detail + ')' }
|
|
1422
|
+
}
|
|
1423
|
+
const aligned = win.synthetic ? alignLiveTurnCursor(targetCtx, session, win.turn, serviceOf(targetCtx, 'agents')) : false
|
|
1424
|
+
if (win.synthetic && !aligned) {
|
|
1425
|
+
console.warn('[message-ops] synthetic turn written but agent cursor was not advanced', { session: sessionId, turn: win.turn })
|
|
1426
|
+
}
|
|
1427
|
+
await flushSessions(targetCtx, session)
|
|
1428
|
+
return { state, aligned }
|
|
1429
|
+
} catch (err) {
|
|
1430
|
+
if (win && win.synthetic && state.windowOpened) {
|
|
1431
|
+
try {
|
|
1432
|
+
alignLiveTurnCursor(targetCtx, session, win.turn, serviceOf(targetCtx, 'agents'))
|
|
1433
|
+
} catch {
|
|
1434
|
+
/* 尽力而为:对齐失败不覆盖原始错误 */
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
throw withResolveDiag(err, diag)
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
/**
|
|
1442
|
+
* 磁盘写入的统一编排(0.35.3 M5):read→assert→plan→script→materialize→append。
|
|
1443
|
+
*
|
|
1444
|
+
* opsCommit / opsRestore 的磁盘分支原先各自复制这一串(含锁内重读、v4 断言、
|
|
1445
|
+
* seq/time 分配、错误诊断)。差异只有规划与响应字段,用三个回调表达。
|
|
1446
|
+
* @param {object} input 编排参数
|
|
1447
|
+
* @param {string} input.logPath 会话日志路径
|
|
1448
|
+
* @param {object} input.diag 诊断收集器
|
|
1449
|
+
* @param {(events:Array)=>object} input.plannedOf 由最新事件规划(返回任意计划对象)
|
|
1450
|
+
* @param {(planned:object)=>object} input.scriptOf 计划 → ops-write 语义脚本
|
|
1451
|
+
* @param {(planned:object, materialized:object, read:object)=>object} input.resultOf 构造响应
|
|
1452
|
+
* @returns {Promise<object>} resultOf 的返回值
|
|
1453
|
+
*/
|
|
1454
|
+
/**
|
|
1455
|
+
* 写盘成功后把已知批次并进派生缓存(0.44.0,srv-audit D6)。
|
|
1456
|
+
*
|
|
1457
|
+
* 缓存按日志 mtimeMs+size 失效:本插件自己 append 一帧后,下一次 GET 会为同一份
|
|
1458
|
+
* 日志再全量读一次(137MB 会话实测 19.5s)。写批次的事件内容完全已知(materializeDisk
|
|
1459
|
+
* 的 batch),因此可以把旧派生 + 批次增量合并成新派生并直接替换缓存条目。
|
|
1460
|
+
*
|
|
1461
|
+
* 失败(NotIncrementalError / 缓存未命中 / stat 竞争)一律**放弃增量**,让下一次
|
|
1462
|
+
* GET 走原全量路径 —— 宁可慢也不能错。
|
|
1463
|
+
* @param {string} logPath 会话日志路径
|
|
1464
|
+
* @param {Array} preEvents 批次之前的全量事件(写路径锁内刚读过)
|
|
1465
|
+
* @param {Array} batch 本次写入的事件(diskAppend 的 batch)
|
|
1466
|
+
* @returns {void}
|
|
1467
|
+
*/
|
|
1468
|
+
function adoptIncrementalCache(logPath, preEvents, batch, statBefore) {
|
|
1469
|
+
try {
|
|
1470
|
+
const entry = derivedCache.get(logPath)
|
|
1471
|
+
// 铁律 1:只有缓存派生与「本次读盘前的文件状态」一致才允许增量;
|
|
1472
|
+
// 不一致(宿主在缓存之后又写过)就删条目,让下一次 GET 全量重建。
|
|
1473
|
+
if (!statBefore || !entry || entry.mtimeMs !== statBefore.mtimeMs || entry.size !== statBefore.size || !entry.value) {
|
|
1474
|
+
if (entry) derivedCache.delete(logPath)
|
|
1475
|
+
return
|
|
1476
|
+
}
|
|
1477
|
+
const prev = entry.value
|
|
1478
|
+
const texts = derivedTexts.get(prev)
|
|
1479
|
+
const next = applyDerivedBatch(prev, batch, {
|
|
1480
|
+
events: preEvents,
|
|
1481
|
+
texts,
|
|
1482
|
+
framesAdded: 1,
|
|
1483
|
+
register: (derived, map) => {
|
|
1484
|
+
derivedTexts.set(derived, map)
|
|
1485
|
+
},
|
|
1486
|
+
})
|
|
1487
|
+
const registered = derivedTextsOf(next)
|
|
1488
|
+
if (registered && !derivedTexts.has(next)) derivedTexts.set(next, registered)
|
|
1489
|
+
statFile(logPath)
|
|
1490
|
+
.then(st => {
|
|
1491
|
+
derivedCache.delete(logPath)
|
|
1492
|
+
derivedCache.set(logPath, { mtimeMs: st.mtimeMs, size: st.size, promise: Promise.resolve(next), value: next })
|
|
1493
|
+
})
|
|
1494
|
+
.catch(() => {
|
|
1495
|
+
/* 拿不到新 stat 就不动缓存:下一次 GET 会因 mtime 不符而重建 */
|
|
1496
|
+
})
|
|
1497
|
+
} catch (error) {
|
|
1498
|
+
if (!(error instanceof NotIncrementalError)) {
|
|
1499
|
+
console.warn('[message-ops] incremental derived adoption failed:', error && error.message)
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
async function runDiskWrite({ logPath, diag, plannedOf, scriptOf, resultOf }) {
|
|
1505
|
+
return withWriteLock(logPath, async () => {
|
|
1506
|
+
// 0.44.0(D6):读盘前 stat —— 增量接管缓存时用它证明「缓存派生与本次读到的是
|
|
1507
|
+
// 同一文件状态」,否则绝不拿陈旧派生做增量(三铁律之一)。
|
|
1508
|
+
const statBefore = await statFile(logPath).catch(() => null)
|
|
1509
|
+
const read = await readSessionFileAsync(logPath)
|
|
1510
|
+
assertWritableSessionLog(read, logPath)
|
|
1511
|
+
let planned
|
|
1512
|
+
try {
|
|
1513
|
+
planned = plannedOf(read.events)
|
|
1514
|
+
} catch (err) {
|
|
1515
|
+
throw withResolveDiag(err, diag)
|
|
1516
|
+
}
|
|
1517
|
+
const script = scriptOf(planned)
|
|
1518
|
+
const materialized = materializeDisk(script, {
|
|
1519
|
+
startSeq: nextSeqFrom(read.events),
|
|
1520
|
+
baseTime: Date.now(),
|
|
1521
|
+
version: read.header.version ?? 4,
|
|
1522
|
+
})
|
|
1523
|
+
await diskAppend(logPath, materialized.batch)
|
|
1524
|
+
// D6:写后增量更新派生缓存(失败静默退回全量)
|
|
1525
|
+
adoptIncrementalCache(logPath, read.events, materialized.batch, statBefore)
|
|
1526
|
+
return resultOf(planned, materialized, read)
|
|
1527
|
+
})
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
/** 测试钩子(非公开 API):直接驱动 list / search / text 与文件派生缓存。 */
|
|
1531
|
+
export const _internals = {
|
|
1532
|
+
errorStatusOf,
|
|
1533
|
+
validateConfig,
|
|
1534
|
+
isConfiguredTrustedHost,
|
|
1535
|
+
setTrustedHostsForTests: hosts => {
|
|
1536
|
+
__trustedHosts = hosts
|
|
1537
|
+
},
|
|
1538
|
+
publicErrorOf,
|
|
1539
|
+
runningSourceOf: () => __runningSource,
|
|
1540
|
+
resetCapturedServicesForTests,
|
|
1541
|
+
registerToolTolerantly,
|
|
1542
|
+
runLiveScript,
|
|
1543
|
+
serviceOf,
|
|
1544
|
+
isRunning,
|
|
1545
|
+
captureServices,
|
|
1546
|
+
opsList,
|
|
1547
|
+
opsSearch,
|
|
1548
|
+
opsText,
|
|
1549
|
+
opsCommit,
|
|
1550
|
+
opsRestore,
|
|
1551
|
+
fence,
|
|
1552
|
+
diskAppend,
|
|
1553
|
+
loadDerived,
|
|
1554
|
+
derivedTexts,
|
|
1555
|
+
derivedCache,
|
|
1556
|
+
searchCorpusOf,
|
|
1557
|
+
}
|
|
819
1558
|
|
|
820
1559
|
async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
821
1560
|
if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
|
|
822
1561
|
if (!Number.isSafeInteger(seq) || seq < 0) throw new OpsError('invalid seq', 400)
|
|
1562
|
+
// 0.40.3(srv-audit D7/D8):与回收站移动/purge 共用的按会话锁 —— 否则 delete 与
|
|
1563
|
+
// revert 并发时宿主持有 fd,日志写入丢失;两次 delete 会互相回滚 archive 墓碑。
|
|
1564
|
+
return withSessionLock(sessionId, () => commitUnderLock(targetCtx, mode, sessionId, seq))
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
async function commitUnderLock(targetCtx, mode, sessionId, seq) {
|
|
823
1568
|
if (isRunning(targetCtx, sessionId)) throw new OpsError('session is running; stop it first', 409)
|
|
824
1569
|
const { logPath } = pickSessionDir(sessionId)
|
|
825
|
-
const { header, events } = await readSessionFileAsync(logPath)
|
|
826
1570
|
// 0.8.2:空闲会话(实测 340/364)没有打开的 turn/step → 用自足的**合成 turn**
|
|
827
1571
|
// 承载 notice,而不是拒绝。引擎 append-only 插不进已有 step,但合成一整个 turn 合法
|
|
828
|
-
|
|
1572
|
+
//(已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
|
|
829
1573
|
// 带 reason:"message-ops",UI 与审计可识别,不与真实模型轮次混淆。
|
|
830
|
-
let win = planNoticeWindow(events)
|
|
831
1574
|
const notice = mode === 'delete' ? `[消息删除] 已遮蔽 seq ${seq}` : null // revert 文案含 shadowed 数量,规划后拼
|
|
832
|
-
|
|
1575
|
+
// 审计 §1.6 + §2.2:live 面拿不到时会退回磁盘路径 —— 那是**正常**的 lazy-view 形态,
|
|
1576
|
+
// 但「为什么拿不到」以前被扔进没人读的全局变量。现在只在**真的失败**时把它
|
|
1577
|
+
// 拼进 OpsError(成功路径零字符串开销、也不改变任何控制流)。
|
|
1578
|
+
const diag = {}
|
|
1579
|
+
const acq = await acquireSession(targetCtx, sessionId, diag)
|
|
1580
|
+
let win = null
|
|
833
1581
|
if (acq !== null && acq.session !== undefined) {
|
|
834
1582
|
try {
|
|
835
|
-
|
|
1583
|
+
// 0.40.1(srv-audit D4):live 分支与磁盘分支共用同一 per-logPath 串行队列。
|
|
1584
|
+
// 规划回退读盘(`liveEvents` 拿不到时 `await readSessionFileAsync`)是 await 点,
|
|
1585
|
+
// 旧实现没有互斥 → 两个并发 restore 基于同一份磁盘快照各写一遍(重复副本)。
|
|
1586
|
+
return await withWriteLock(logPath, async () => {
|
|
1587
|
+
const session = acq.session
|
|
836
1588
|
const liveEvents = sessionLogOf(session)
|
|
837
|
-
|
|
1589
|
+
// 0.33.1:live 面是权威;只有拿不到事件本体时才读盘做规划兜底(store 命中时
|
|
1590
|
+
// 磁盘可能落后于落盘批窗,先读盘会把「已存在的 marker」判成不存在)。
|
|
1591
|
+
const sourceEvents = liveEvents || mergePendingLiveWrites(logPath, (await readSessionFileAsync(logPath)).events)
|
|
1592
|
+
win = planNoticeWindow(sourceEvents)
|
|
838
1593
|
const turnStep = { turn: win.turn, step: win.step }
|
|
839
1594
|
// 0.5.4(P0):v4 准入要求 system/message 带正 turn/step——缺字段时持久层
|
|
840
1595
|
// encodeEventBatch 的 SessionFormatError 未捕获会**打死整个 dsh 进程**。
|
|
1596
|
+
// 0.26.0(core-d 审计发现的最后一个自噬入口):
|
|
1597
|
+
// live 路径的 `planDelete/planRevert` 只拿得到 `session.surface.nodes`(没有事件
|
|
1598
|
+
// 本体),因此判不出「目标是不是一条 marker」。磁盘路径的
|
|
1599
|
+
// planDeleteFromEvents/planRevertFromEvents 早已有这道闸,live 路径原先漏了 →
|
|
1600
|
+
// 把 marker 自己当删除目标会写出一条 content 为空的新 replace(自噬 marker)。
|
|
1601
|
+
// 语料实测 40 条空 content 的 system/message replace(3424/3658/3689/3721/
|
|
1602
|
+
// 3746/7252/7524/7525/7526/8954…)全是这么来的。
|
|
1603
|
+
// 这里用 liveEvents(事件本体)补一次同判;判不了(无 liveEvents)就交给
|
|
1604
|
+
// planDelete/planRevert 自己的节点校验(保持原行为,不引入新的拒绝面)。
|
|
1605
|
+
if (liveEvents) {
|
|
1606
|
+
const target = liveEvents.find(e => e && e.seq === seq)
|
|
1607
|
+
if (target && isMarkerEvent(target))
|
|
1608
|
+
throw new OpsError(`seq ${seq} is a revert/delete marker and cannot be a ${mode} target (would create a self-eating marker)`, 409)
|
|
1609
|
+
}
|
|
1610
|
+
const liveLog = sessionLogOf(session) || []
|
|
1611
|
+
const targetEvent = liveLog.find(e => e && e.seq === seq)
|
|
1612
|
+
// 0.33.2(与磁盘路径同判):宿主的 surface 改写(compaction checkpoint、
|
|
1613
|
+
// 系统提示改写)不是对话消息。live 侧只查 isMarkerEvent(system/message)
|
|
1614
|
+
// 与 tool/result,会把 user/message + replace 的 checkpoint 放行 —— 遮蔽它
|
|
1615
|
+
// 等于把压缩后的整段上下文清空。
|
|
1616
|
+
if (targetEvent && readReplaceOp(targetEvent) !== null) {
|
|
1617
|
+
throw new OpsError(`seq ${seq} is a host surface rewrite, not a message — refusing to ${mode} it`, 409)
|
|
1618
|
+
}
|
|
1619
|
+
if (targetEvent && targetEvent.type === 'tool/result') {
|
|
1620
|
+
// 遮蔽 tool/result 会让 assistant 的 tool-call 失去配对 → 下一次模型请求被拒。
|
|
1621
|
+
// 磁盘路径靠 isSurfaceMessageType 过滤(tool/result 不在消息集),live 侧必须显式拦。
|
|
1622
|
+
throw new OpsError(`seq ${seq} is a tool result, not a message — refusing to ${mode} it`, 409)
|
|
1623
|
+
}
|
|
841
1624
|
const plan = mode === 'delete' ? planDelete(session.surface, seq) : planRevert(session.surface, seq)
|
|
842
1625
|
const text = mode === 'delete' ? notice : `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`
|
|
843
1626
|
// 0.8.2:会话 store 命中时走引擎路径 —— 同样要先开合成 turn 窗口,
|
|
@@ -856,80 +1639,61 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
|
856
1639
|
// 日志落成 `step/end, turn/end, step/end, turn/end`。宿主读盘直接判
|
|
857
1640
|
// `step/end does not match an open turn and step`,整份会话变 corrupt
|
|
858
1641
|
// (实测 session-5b49db5b seq 806-809)。用 closed 标志保证闭环只发生一次。
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
mode,
|
|
881
|
-
seq,
|
|
882
|
-
syntheticTurn: win.synthetic === true,
|
|
883
|
-
// 0.11.4:暴露对齐结果。live 路径必须 true;disk 路径(store-miss)没有
|
|
884
|
-
// 内存 agent,false 属正常。若 live 也 false,下一条真实消息就会重号。
|
|
885
|
-
turnAligned: aligned,
|
|
886
|
-
shadowedCount: plan.shadowedSeqs.length,
|
|
887
|
-
eventSeq: event && event.seq != null ? event.seq : null,
|
|
1642
|
+
// P0(0.32.0):宿主动机不在 idle(maintenance 也算 status 空闲)时禁止写合成窗口——
|
|
1643
|
+
// 写完无法推进 lastTurn,宿主下一轮会重号,整份日志被拒读。
|
|
1644
|
+
const phaseErr = livePhaseError(targetCtx, session, serviceOf(targetCtx, 'agents'))
|
|
1645
|
+
if (phaseErr) throw withResolveDiag(phaseErr, diag)
|
|
1646
|
+
// 0.33.10:agents 缺失只告警(本机 profile 恒缺失,硬拒绝会堵死所有写操作)。
|
|
1647
|
+
agentsServiceVisible(targetCtx, session, win)
|
|
1648
|
+
// 0.34.2(M3):live 与 disk 共用同一份语义脚本;落地方式由 applyScriptLive
|
|
1649
|
+
// 负责(引擎分配 seq/time、replace 走 applySurfaceReplace 的拼写探测)。
|
|
1650
|
+
const script = buildCommitScript({ mode, seq, win, plan })
|
|
1651
|
+
const live = await runLiveScript(targetCtx, session, sessionId, win, script, diag)
|
|
1652
|
+
notePendingLiveWrite(logPath, live.state.emitted)
|
|
1653
|
+
const markerEvent = live.state.emitted.find(e => e && e.type === 'system/message')
|
|
1654
|
+
return {
|
|
1655
|
+
ok: true,
|
|
1656
|
+
mode,
|
|
1657
|
+
seq,
|
|
1658
|
+
syntheticTurn: win.synthetic === true,
|
|
1659
|
+
turnAligned: live.aligned,
|
|
1660
|
+
shadowedCount: plan.shadowedSeqs.length,
|
|
1661
|
+
eventSeq: markerEvent && markerEvent.seq != null ? markerEvent.seq : null,
|
|
1662
|
+
...(live.partial === true ? { partial: true, warning: live.warning } : {}),
|
|
888
1663
|
}
|
|
889
|
-
}
|
|
890
|
-
// 只补闭合**尚未发生**的窗口;已闭合过就绝不再写第二遍。
|
|
891
|
-
closeWindow()
|
|
892
|
-
throw err
|
|
893
|
-
}
|
|
1664
|
+
})
|
|
894
1665
|
} finally {
|
|
895
1666
|
acq.release()
|
|
896
1667
|
}
|
|
897
1668
|
}
|
|
898
|
-
// store-miss(lazy-view 只读盘会话)→ 磁盘路径:镜像引擎字段直接追加 zstd
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
//
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
1669
|
+
// store-miss(lazy-view 只读盘会话)→ 磁盘路径:镜像引擎字段直接追加 zstd 帧。
|
|
1670
|
+
// 审计 §2.2:这条路径的失败(`start seq N not visible on current surface` 等)
|
|
1671
|
+
// 现在带上 diag —— 它正是「live 面也没拿到 + 磁盘面也拒」的最终现场。
|
|
1672
|
+
//
|
|
1673
|
+
// 0.33.1(P0):read→plan→append 整段进 per-logPath 串行队列。两个并发请求
|
|
1674
|
+
// 各自读到同一 maxSeq 会各写一份 seq,宿主加载判 `event seq N is not dense`,
|
|
1675
|
+
// 整份会话打不开(已用宿主 format catalog 复现)。
|
|
1676
|
+
// 0.8.2:磁盘路径同样把 marker 包进合成 turn(裸 zstd 写、零校验,写错就是整份日志报废)。
|
|
1677
|
+
// 0.34.0:事件序列由 ops-write 单一脚本层物化(与 live 共用同一份语义脚本)。
|
|
1678
|
+
return runDiskWrite({
|
|
1679
|
+
logPath,
|
|
1680
|
+
diag,
|
|
1681
|
+
plannedOf: events => {
|
|
1682
|
+
const plannedWin = planNoticeWindow(events)
|
|
1683
|
+
const plannedPlan = mode === 'delete' ? planDeleteFromEvents(events, seq) : planRevertFromEvents(events, seq)
|
|
1684
|
+
return { win: plannedWin, plan: plannedPlan }
|
|
1685
|
+
},
|
|
1686
|
+
scriptOf: ({ win: plannedWin, plan: plannedPlan }) => buildCommitScript({ mode, seq, win: plannedWin, plan: plannedPlan }),
|
|
1687
|
+
resultOf: ({ win: plannedWin, plan: plannedPlan }, { markerSeq }) => ({
|
|
1688
|
+
ok: true,
|
|
1689
|
+
mode,
|
|
1690
|
+
seq,
|
|
1691
|
+
disk: true,
|
|
1692
|
+
syntheticTurn: plannedWin.synthetic === true,
|
|
1693
|
+
shadowedCount: plannedPlan.shadowedSeqs.length,
|
|
1694
|
+
eventSeq: markerSeq,
|
|
1695
|
+
}),
|
|
919
1696
|
})
|
|
920
|
-
batch.push(marker)
|
|
921
|
-
let tail = marker.time + 1
|
|
922
|
-
for (const e of noticeWindowPostamble(win)) batch.push({ type: e.kind, seq: cursor++, time: tail++, data: e.data })
|
|
923
|
-
await diskAppend(logPath, batch)
|
|
924
|
-
return {
|
|
925
|
-
ok: true,
|
|
926
|
-
mode,
|
|
927
|
-
seq,
|
|
928
|
-
disk: true,
|
|
929
|
-
syntheticTurn: win.synthetic === true,
|
|
930
|
-
shadowedCount: plan.shadowedSeqs.length,
|
|
931
|
-
eventSeq: marker.seq,
|
|
932
|
-
}
|
|
933
1697
|
}
|
|
934
1698
|
|
|
935
1699
|
// 0.8.0:upToSeq 可选 —— 给定则按轮步进恢复(只重放到该 seq,后续仍遮蔽)。
|
|
@@ -938,109 +1702,143 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
|
|
|
938
1702
|
if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
|
|
939
1703
|
if (!Number.isSafeInteger(restoreSeq) || restoreSeq < 0) throw new OpsError('invalid seq', 400)
|
|
940
1704
|
if (upToSeq !== undefined && (!Number.isSafeInteger(upToSeq) || upToSeq < 0)) throw new OpsError('invalid upToSeq', 400)
|
|
1705
|
+
return withSessionLock(sessionId, () => restoreUnderLock(targetCtx, sessionId, restoreSeq, upToSeq, discard))
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
async function restoreUnderLock(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
|
|
941
1709
|
if (isRunning(targetCtx, sessionId)) throw new OpsError('session is running; stop it first', 409)
|
|
942
1710
|
const { logPath } = pickSessionDir(sessionId)
|
|
943
|
-
|
|
1711
|
+
// ⚠️ 这里曾尝试用 `session.lock` 存在性判定「宿主仍持有写租约」,已撤回:
|
|
1712
|
+
// 宿主崩溃后锁文件会残留(文件在、flock 已释放),只查存在性会把磁盘写永久 409。
|
|
1713
|
+
// 0.33.1:磁盘写走进程内 per-logPath 串行队列(withWriteLock),并在锁内重读;
|
|
1714
|
+
// 跨进程仍依赖宿主 flock(插件不参与),文档已声明单宿主限制。
|
|
944
1715
|
// 0.8.0(B1 修复):步进恢复必须排除先前轮次已重放的源 seq,
|
|
945
1716
|
// 否则每轮从区间头重放 → 消息副本成倍出现。
|
|
946
1717
|
// 合成 turn 承载 notice 的完整理由见 opsCommit() 处(0.8.2,实测 340/364 空闲会话)。
|
|
947
1718
|
const buildPlan = sourceEvents => {
|
|
948
1719
|
const window = planNoticeWindow(sourceEvents)
|
|
949
1720
|
const progress = restoreProgress(sourceEvents, restoreSeq)
|
|
1721
|
+
// 0.33.2:只有「确实有可重放内容且全部恢复完」才拒绝。零候选 marker
|
|
1722
|
+
// (只遮蔽 tool/system/注入行)此前也被判 complete → restore 与 discard 永久
|
|
1723
|
+
// 409,而 dock 又按 restoreComplete 隐藏它 —— 标记再也清不掉(0.5.6 逃生路被封死)。
|
|
1724
|
+
if (progress && progress.complete && (progress.candidateCount ?? 0) > 0 && !discard) {
|
|
1725
|
+
throw new OpsError('restore: this marker has already been restored (no pending turns)', 409)
|
|
1726
|
+
}
|
|
1727
|
+
// 0.39.7(srv-audit D12):discard 此前不幂等 —— 每次重试都追加一个合成 turn + notice
|
|
1728
|
+
// (实测连续 5 次 = 5 条)。已丢弃过就明确 409,不写事件。
|
|
1729
|
+
if (discard && progress && progress.discarded) {
|
|
1730
|
+
throw new OpsError('restore: this marker was already discarded', 409)
|
|
1731
|
+
}
|
|
950
1732
|
const restorePlan = planRestore(sourceEvents, restoreSeq, upToSeq, progress ? progress.restoredSeqs : null)
|
|
951
1733
|
restorePlan.turnStep = { turn: window.turn, step: window.step }
|
|
952
|
-
restorePlan.window = window
|
|
953
1734
|
if (discard) restorePlan.discard = true
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
1735
|
+
// 0.39.7(srv-audit D11):请求的 upTo 之前已全部重放过、但后续轮仍 pending 时,
|
|
1736
|
+
// 旧实现「只补一条进度 notice」——文案却是「区间无可重放…该回撤标记就此停用」,
|
|
1737
|
+
// 与事实(marker 仍 pending)矛盾,还白白写一个合成 turn。改为 409 并指明出路。
|
|
1738
|
+
// 注意与「upTo 早于候选」区分:那种情况 progress.restoredSeqs 为空,写一条
|
|
1739
|
+
// `restoredSourceSeqs: []` 的 notice 是**有意**的(否则进度判 legacy → 永久 409,
|
|
1740
|
+
// 见 test/empty-replay-recovery.test.js)。这里只挡「已经恢复过、再要同一段」。
|
|
1741
|
+
if (
|
|
1742
|
+
!discard &&
|
|
1743
|
+
restorePlan.replayable.length === 0 &&
|
|
1744
|
+
progress &&
|
|
1745
|
+
!progress.complete &&
|
|
1746
|
+
progress.pendingSeqs.length > 0 &&
|
|
1747
|
+
progress.restoredSeqs.length > 0
|
|
1748
|
+
) {
|
|
1749
|
+
throw new OpsError(
|
|
1750
|
+
'restore: nothing to replay up to this point (already restored); restore the remaining turns by their own upToSeq, or use discard to stop restoring',
|
|
1751
|
+
409,
|
|
1752
|
+
)
|
|
957
1753
|
}
|
|
958
1754
|
return { win: window, plan: restorePlan }
|
|
959
1755
|
}
|
|
960
|
-
|
|
961
|
-
const
|
|
1756
|
+
// 与 opsCommit 同一诊断口径(审计 §1.6):restore 也走两条面,失败要把原因带上。
|
|
1757
|
+
const diag = {}
|
|
1758
|
+
let win = null
|
|
1759
|
+
let plan = null
|
|
1760
|
+
const acq = await acquireSession(targetCtx, sessionId, diag)
|
|
962
1761
|
if (acq !== null && acq.session !== undefined) {
|
|
963
1762
|
// 0.10.8 孤儿护栏(与 opsCommit 同型):planRestore/进度校验本就在 preamble
|
|
964
1763
|
// 之前完成;applyRestore 里的引擎 append 若抛(如 replay 坐标错开),
|
|
965
1764
|
// preamble 已落——闭合合成 turn 再原样抛出,不留常开孤儿窗口。
|
|
1765
|
+
// 0.29.x P0(与 opsCommit 0.11.3 同型):postamble 只能写一次,且只补**未写**的部分。
|
|
1766
|
+
// 旧实现把整段 postamble 同时放在成功路径和 catch 里;成功路径的第二个 postamble
|
|
1767
|
+
// 事件被引擎拒(或 flush 抛错)时,catch 会把已追加的 step/end 再写一遍 →
|
|
1768
|
+
// 日志落成 `step/end, turn/end, step/end, turn/end`,宿主读盘判
|
|
1769
|
+
// `step/end does not match an open turn and step`,整份会话 corrupt。
|
|
1770
|
+
// 注意:closeWindow 必须声明在 try 之外 —— catch 也要用它。
|
|
1771
|
+
// P0(0.32.0):与 opsCommit 同款前置闸 —— 非 idle phase 写合成窗口 = 重号风险。
|
|
1772
|
+
const phaseErr = livePhaseError(targetCtx, acq.session, serviceOf(targetCtx, 'agents'))
|
|
1773
|
+
if (phaseErr) {
|
|
1774
|
+
acq.release()
|
|
1775
|
+
throw withResolveDiag(phaseErr, diag)
|
|
1776
|
+
}
|
|
1777
|
+
let state = null
|
|
966
1778
|
try {
|
|
1779
|
+
// 0.40.1(srv-audit D4):与磁盘分支共用同一 per-logPath 串行队列 —— 规划回退读盘
|
|
1780
|
+
// 的 await 点会让两个并发 restore 基于同一份快照各写一遍(重复副本)。
|
|
1781
|
+
return await withWriteLock(logPath, async () => {
|
|
967
1782
|
const liveEvents = sessionLogOf(acq.session)
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
})
|
|
975
|
-
|
|
976
|
-
|
|
1783
|
+
// 0.33.1:live 面是权威;拿不到事件本体才读盘兜底。
|
|
1784
|
+
const sourceEvents = liveEvents || mergePendingLiveWrites(logPath, (await readSessionFileAsync(logPath)).events)
|
|
1785
|
+
;({ win, plan } = buildPlan(sourceEvents))
|
|
1786
|
+
// 0.33.10:agents 缺失只告警,不阻断。
|
|
1787
|
+
agentsServiceVisible(targetCtx, acq.session, win)
|
|
1788
|
+
// 0.34.2(M3):与磁盘路径共用同一份语义脚本(notice / replay / advance / close)。
|
|
1789
|
+
const script = buildRestoreScript({ win, plan })
|
|
1790
|
+
const liveResult = await runLiveScript(targetCtx, acq.session, sessionId, win, script, diag)
|
|
1791
|
+
notePendingLiveWrite(logPath, liveResult.state.emitted)
|
|
1792
|
+
state = liveResult.state
|
|
1793
|
+
const aligned = liveResult.aligned
|
|
1794
|
+
// 0.34.3:与磁盘路径同口径 —— eventSeqs = 本次实际写入的**全部**事件
|
|
1795
|
+
// (含窗口开合)。旧 live 只返回 notice+replay,模型看到的进度与磁盘路径不一致。
|
|
1796
|
+
const eventSeqs = state.emitted.filter(e => e && e.seq != null).map(e => e.seq)
|
|
977
1797
|
return {
|
|
978
1798
|
ok: true,
|
|
979
|
-
|
|
1799
|
+
restoredCount: plan.discard ? 0 : plan.replayable.length,
|
|
1800
|
+
skipped: plan.skipped,
|
|
1801
|
+
eventSeqs,
|
|
980
1802
|
turnAligned: aligned,
|
|
981
1803
|
discarded: plan.discard === true,
|
|
982
1804
|
upToSeq: plan.upToSeq,
|
|
983
|
-
restoredSourceSeqs: plan.replayable.map(i => i.seq),
|
|
1805
|
+
restoredSourceSeqs: plan.discard ? [] : plan.replayable.map(i => i.seq),
|
|
984
1806
|
range: { startSeq: plan.startSeq, endSeq: plan.endSeq },
|
|
1807
|
+
...(liveResult.partial === true ? { partial: true, warning: liveResult.warning } : {}),
|
|
985
1808
|
}
|
|
1809
|
+
})
|
|
986
1810
|
} catch (err) {
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
acq.session.append(post.kind, post.data)
|
|
990
|
-
} catch {
|
|
991
|
-
/* postamble 被引擎拒:维持原错误上抛 */
|
|
992
|
-
}
|
|
993
|
-
}
|
|
994
|
-
throw err
|
|
1811
|
+
// 规划阶段失败时一个事件都没写;runLiveScript 已处理窗口闭合与失败对齐。
|
|
1812
|
+
throw withResolveDiag(err, diag)
|
|
995
1813
|
} finally {
|
|
996
1814
|
acq.release()
|
|
997
1815
|
}
|
|
998
1816
|
}
|
|
999
|
-
// store-miss → 磁盘路径:说明事件 +
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
// 下一轮 excludeSeqs 才不会重复重放同一批消息(详见 ops-core 该函数注释)。
|
|
1023
|
-
restoredSourceSeqs: plan.discard ? [] : plan.replayable.map(i => i.seq),
|
|
1817
|
+
// store-miss → 磁盘路径:说明事件 + 重放事件批量追加(一个帧)。
|
|
1818
|
+
// 0.33.1:read→plan→append 串行化,并在锁内重读重规划(并发 restore 会写出重复 seq)。
|
|
1819
|
+
// 0.34.0:notice / 多助手 step 分配 / postamble 由 ops-write 脚本统一物化。
|
|
1820
|
+
return runDiskWrite({
|
|
1821
|
+
logPath,
|
|
1822
|
+
diag,
|
|
1823
|
+
plannedOf: events => {
|
|
1824
|
+
const planned = buildPlan(events)
|
|
1825
|
+
return { win: planned.win, plan: planned.plan }
|
|
1826
|
+
},
|
|
1827
|
+
scriptOf: ({ win: plannedWin, plan: plannedPlan }) => buildRestoreScript({ win: plannedWin, plan: plannedPlan }),
|
|
1828
|
+
resultOf: ({ win: plannedWin, plan: plannedPlan }, { batch }) => ({
|
|
1829
|
+
ok: true,
|
|
1830
|
+
disk: true,
|
|
1831
|
+
// 与 live 路径同字段:discard 的语义要让调用方一眼可见。
|
|
1832
|
+
discarded: plannedPlan.discard === true,
|
|
1833
|
+
syntheticTurn: plannedWin.synthetic === true,
|
|
1834
|
+
restoredCount: plannedPlan.discard ? 0 : plannedPlan.replayable.length,
|
|
1835
|
+
upToSeq: plannedPlan.upToSeq,
|
|
1836
|
+
restoredSourceSeqs: plannedPlan.discard ? [] : plannedPlan.replayable.map(i => i.seq),
|
|
1837
|
+
skipped: plannedPlan.skipped,
|
|
1838
|
+
eventSeqs: batch.map(e => e.seq),
|
|
1839
|
+
range: { startSeq: plannedPlan.startSeq, endSeq: plannedPlan.endSeq },
|
|
1024
1840
|
}),
|
|
1025
|
-
)
|
|
1026
|
-
let offset = 0
|
|
1027
|
-
for (const item of plan.discard ? [] : plan.replayable) {
|
|
1028
|
-
batch.push(buildReplayEvent({ seq: cursor++, time: noticeBase + ++offset, item, turnStep: plan.turnStep, version }))
|
|
1029
|
-
}
|
|
1030
|
-
let tail = noticeBase + offset + 1
|
|
1031
|
-
for (const e of noticeWindowPostamble(win)) batch.push({ type: e.kind, seq: cursor++, time: tail++, data: e.data })
|
|
1032
|
-
await diskAppend(logPath, batch)
|
|
1033
|
-
return {
|
|
1034
|
-
ok: true,
|
|
1035
|
-
disk: true,
|
|
1036
|
-
syntheticTurn: win.synthetic === true,
|
|
1037
|
-
restoredCount: plan.replayable.length,
|
|
1038
|
-
upToSeq: plan.upToSeq,
|
|
1039
|
-
restoredSourceSeqs: plan.replayable.map(i => i.seq),
|
|
1040
|
-
skipped: plan.skipped,
|
|
1041
|
-
eventSeqs: batch.map(e => e.seq),
|
|
1042
|
-
range: { startSeq: plan.startSeq, endSeq: plan.endSeq },
|
|
1043
|
-
}
|
|
1841
|
+
})
|
|
1044
1842
|
}
|
|
1045
1843
|
|
|
1046
1844
|
// ---------------------------------------------------------------------------
|
|
@@ -1052,11 +1850,11 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
|
|
|
1052
1850
|
* 这里保持零静态依赖、可在测试里用桩验证。ops 为核心操作表,签名:
|
|
1053
1851
|
* (targetCtx, sessionId[, seq]) → 结果对象,失败抛 OpsError。
|
|
1054
1852
|
*/
|
|
1055
|
-
export function createMessageOpsTool({ defineTool, ops, ctx }) {
|
|
1853
|
+
export function createMessageOpsTool({ defineTool, ops, ctx, authorizeTarget = authorizeToolTarget }) {
|
|
1056
1854
|
return defineTool({
|
|
1057
1855
|
name: 'message_ops',
|
|
1058
1856
|
description:
|
|
1059
|
-
'Manage DSH conversation messages: list messages with visibility, revert to a seq (surface replace shadows the tail), delete a single message, restore (replay) messages shadowed by a previous revert.
|
|
1857
|
+
'Manage DSH conversation messages: list messages with visibility, revert to a seq (surface replace shadows the tail), delete a single message, restore (replay) messages shadowed by a previous revert. Listing excludes rolled-back (shadowed) message bodies; it only reports them as hidden. Sessions must not be running for mutating actions. The target session must belong to the caller workspace (same cwd).',
|
|
1060
1858
|
parameters: {
|
|
1061
1859
|
action: {
|
|
1062
1860
|
type: 'string',
|
|
@@ -1075,6 +1873,7 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
|
|
|
1075
1873
|
},
|
|
1076
1874
|
upToSeq: {
|
|
1077
1875
|
type: 'integer',
|
|
1876
|
+
description: 'restore only: replay up to this seq (per-turn step); omitted = replay all pending turns.',
|
|
1078
1877
|
},
|
|
1079
1878
|
},
|
|
1080
1879
|
output: {
|
|
@@ -1083,10 +1882,15 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
|
|
|
1083
1882
|
return [{ type: 'text', text: value }]
|
|
1084
1883
|
},
|
|
1085
1884
|
},
|
|
1086
|
-
async execute(args) {
|
|
1885
|
+
async execute(args, exec) {
|
|
1087
1886
|
const action = args.action
|
|
1088
1887
|
const sessionId = String(args.sessionId || '').trim()
|
|
1089
1888
|
try {
|
|
1889
|
+
// 0.33.2(安全 P0):模型工具必须与宿主自己的 session 工具**同口径**授权 ——
|
|
1890
|
+
// 调用者 cwd 必须等于目标会话 header.cwd(宿主 dsh-tool-session-query 的
|
|
1891
|
+
// authorizeTarget 就是这么做的)。旧实现 execute(args) 完全不看 exec,
|
|
1892
|
+
// 任何模型/子代理能跨 workspace 读改别人的会话,且 node:fs 写入绕过沙箱。
|
|
1893
|
+
await authorizeTarget(exec, sessionId)
|
|
1090
1894
|
let result
|
|
1091
1895
|
// 0.5.2(P1):ops 自 0.2.1 起为 async——不 await 会把 Promise 直接送进 renderResult,
|
|
1092
1896
|
// list/restore 必抛 TypeError(测试桩曾是同步的故漏检)。
|
|
@@ -1101,12 +1905,15 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
|
|
|
1101
1905
|
result = await ops.delete(ctx, sessionId, args.seq)
|
|
1102
1906
|
break
|
|
1103
1907
|
case 'restore':
|
|
1104
|
-
|
|
1908
|
+
// 0.36.0:upToSeq 是「按轮恢复」的唯一入口,旧实现声明了参数却没传。
|
|
1909
|
+
result = await ops.restore(ctx, sessionId, args.seq, args.upToSeq)
|
|
1105
1910
|
break
|
|
1106
1911
|
default:
|
|
1107
1912
|
throw new OpsError(`unknown action: ${action}`, 400)
|
|
1108
1913
|
}
|
|
1109
|
-
|
|
1914
|
+
// 0.33.2(安全):list 默认不把已回滚/删除的原文喂回模型 —— 回撤的产品语义
|
|
1915
|
+
// 就是从上下文移除;HTTP /messages 仍保留 shadowed 行给恢复 UI 用。
|
|
1916
|
+
return renderResult(action, action === 'list' ? withoutShadowed(result) : result)
|
|
1110
1917
|
} catch (e) {
|
|
1111
1918
|
return `${action} failed: ${e && e.message ? e.message : e}`
|
|
1112
1919
|
}
|
|
@@ -1114,6 +1921,35 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
|
|
|
1114
1921
|
})
|
|
1115
1922
|
}
|
|
1116
1923
|
|
|
1924
|
+
/** list 结果去掉 shadowed 行(模型不再看到已回滚内容)。 */
|
|
1925
|
+
function withoutShadowed(r) {
|
|
1926
|
+
if (!r || !Array.isArray(r.messages)) return r
|
|
1927
|
+
return { ...r, messages: r.messages.filter(m => m && m.shadowed !== true) }
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/**
|
|
1931
|
+
* 模型工具的目标授权:调用者 cwd 必须等于目标会话 header.cwd。
|
|
1932
|
+
*
|
|
1933
|
+
* 与宿主 `dsh-tool-session-query/src/workspace-access.ts` 的 authorizeTarget 同口径。
|
|
1934
|
+
* 读 header 只解第一帧,成本与标题读取同量级。
|
|
1935
|
+
* @param {object} exec 工具执行上下文(宿主传入)
|
|
1936
|
+
* @param {string} sessionId 目标会话
|
|
1937
|
+
* @returns {Promise<void>} 未通过时抛 403/404
|
|
1938
|
+
*/
|
|
1939
|
+
async function authorizeToolTarget(exec, sessionId) {
|
|
1940
|
+
const caller =
|
|
1941
|
+
exec && exec.agent && exec.agent.session && exec.agent.session.header && typeof exec.agent.session.header.cwd === 'string'
|
|
1942
|
+
? exec.agent.session.header.cwd
|
|
1943
|
+
: null
|
|
1944
|
+
if (!caller) throw new OpsError('message_ops requires a workspace-bound agent (no session cwd)', 403)
|
|
1945
|
+
if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
|
|
1946
|
+
const { logPath } = pickSessionDir(sessionId)
|
|
1947
|
+
const header = readSessionHeader(logPath)
|
|
1948
|
+
if (typeof header.cwd === 'string' && header.cwd !== caller) {
|
|
1949
|
+
throw new OpsError('target session belongs to another workspace', 403)
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1117
1953
|
/** 工具结果 → 模型可读的多行文本。 */
|
|
1118
1954
|
function renderResult(action, r) {
|
|
1119
1955
|
switch (action) {
|
|
@@ -1138,20 +1974,33 @@ function renderResult(action, r) {
|
|
|
1138
1974
|
* 容错工具注册:ctx 已带 tools 服务就直接注册;没有就等它出现
|
|
1139
1975
|
* (ctx.inject 子 fiber,永不 fatal);dsh-tools 包解析失败也只跳过。
|
|
1140
1976
|
*/
|
|
1141
|
-
function registerToolTolerantly(ctx) {
|
|
1142
|
-
|
|
1143
|
-
|
|
1977
|
+
function registerToolTolerantly(ctx, loadDefineTool) {
|
|
1978
|
+
// 0.37.3(真机形态):cordis 的 `ctx.inject(deps, fn)` 回调收到的是**注入命名空间**
|
|
1979
|
+
// (服务挂在同名属性上),不一定有 `.get()`。旧实现 `sub.get('tools')` 在后到的
|
|
1980
|
+
// 分支会抛 `targetCtx.get is not a function`,把「等 tools 出现」的容错路径变成
|
|
1981
|
+
// apply 期异常。这里两种取值都接受。
|
|
1982
|
+
const toolsOf = scope =>
|
|
1983
|
+
scope && typeof scope.get === 'function' ? scope.get('tools') : scope && scope.tools
|
|
1984
|
+
function tryRegister(scope) {
|
|
1985
|
+
const tools = toolsOf(scope)
|
|
1144
1986
|
if (!tools || typeof tools.register !== 'function') return false
|
|
1145
1987
|
// 动态 import:包缺失时只跳过工具,不拖垮插件的 HTTP 面。
|
|
1146
|
-
|
|
1147
|
-
|
|
1988
|
+
// loadDefineTool 只给测试注入;生产走真实包。
|
|
1989
|
+
const loader = loadDefineTool || (() => import('@deepseek-ai/dsh-tools').then(m => m.defineTool))
|
|
1990
|
+
loader()
|
|
1991
|
+
.then(defineTool => {
|
|
1148
1992
|
const ops = {
|
|
1149
1993
|
list: (c, id) => opsList(c, id),
|
|
1150
1994
|
revert: (c, id, seq) => opsCommit(c, 'revert', id, seq),
|
|
1151
1995
|
delete: (c, id, seq) => opsCommit(c, 'delete', id, seq),
|
|
1152
1996
|
restore: (c, id, seq, upToSeq) => opsRestore(c, id, seq, upToSeq),
|
|
1153
1997
|
}
|
|
1154
|
-
|
|
1998
|
+
// ops 始终绑定 apply 期的 ctx(不是 inject 命名空间)—— 工具执行时要用
|
|
1999
|
+
// 它解析 sessions/agents;命名空间对象上没有这些解析能力。
|
|
2000
|
+
tools.register(createMessageOpsTool({ defineTool, ops, ctx }))
|
|
2001
|
+
// 0.37.3:一行成功日志 —— 真机上「工具到底registered 没有」此前只能靠猜
|
|
2002
|
+
// (失败有 warn,成功零输出)。
|
|
2003
|
+
console.log('[message-ops] tool registered: message_ops')
|
|
1155
2004
|
})
|
|
1156
2005
|
// 0.9.0:不再静默吞错。原先 catch(() => {}) 让「工具注册成功与否」完全无从诊断
|
|
1157
2006
|
// (实测日志里 defineTool / ERR_MODULE_NOT_FOUND 零命中)。
|
|
@@ -1173,7 +2022,39 @@ function registerToolTolerantly(ctx) {
|
|
|
1173
2022
|
// 插件入口:HTTP 路由 + 容错工具注册
|
|
1174
2023
|
// ---------------------------------------------------------------------------
|
|
1175
2024
|
|
|
1176
|
-
|
|
2025
|
+
/**
|
|
2026
|
+
* 校验插件配置(0.47.1,srv-audit E19)。
|
|
2027
|
+
*
|
|
2028
|
+
* 宿主 0.2.3 + `inject=[]` 时 `connection.admit` 不可调用(服务隔离),插件拿不到
|
|
2029
|
+
* trustedHosts 判定。此处允许部署方显式配置可信 Host(cordis.yml 的插件 `config`),
|
|
2030
|
+
* 让经 `--trusted-host` 暴露的站点仍可用 —— 与宿主判定同条件(同源 + BrowserAuth cookie)。
|
|
2031
|
+
*
|
|
2032
|
+
* @param {unknown} config cordis 传入的插件配置
|
|
2033
|
+
* @returns {{trustedHosts: string[]}} 规范化后的配置
|
|
2034
|
+
* @throws {Error} 配置形状非法时 fail loud(不静默忽略)
|
|
2035
|
+
*/
|
|
2036
|
+
export function validateConfig(config) {
|
|
2037
|
+
if (config === undefined || config === null) return { trustedHosts: [] }
|
|
2038
|
+
if (typeof config !== 'object' || Array.isArray(config)) throw new Error('dsh-message-ops: config must be an object')
|
|
2039
|
+
const unknown = Object.keys(config).filter(key => key !== 'trustedHosts')
|
|
2040
|
+
if (unknown.length > 0) throw new Error(`dsh-message-ops: unknown config key "${unknown[0]}"`)
|
|
2041
|
+
const raw = config.trustedHosts
|
|
2042
|
+
if (raw === undefined) return { trustedHosts: [] }
|
|
2043
|
+
if (!Array.isArray(raw)) throw new Error('dsh-message-ops: trustedHosts must be an array of host names')
|
|
2044
|
+
const hosts = []
|
|
2045
|
+
for (const item of raw) {
|
|
2046
|
+
if (typeof item !== 'string' || item.trim() === '') throw new Error('dsh-message-ops: trustedHosts entries must be non-empty strings')
|
|
2047
|
+
if (/^[^:/]*:/.test(item) || item.includes('/')) throw new Error(`dsh-message-ops: trustedHosts entry "${item}" must be a bare host name (no port, no scheme)`)
|
|
2048
|
+
hosts.push(item.trim().toLowerCase())
|
|
2049
|
+
}
|
|
2050
|
+
return { trustedHosts: hosts }
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
/** 本插件进程内生效的可信 Host 列表(apply 时写入;测试可重置)。 */
|
|
2054
|
+
let __trustedHosts = []
|
|
2055
|
+
|
|
2056
|
+
export function apply(ctx, config) {
|
|
2057
|
+
__trustedHosts = validateConfig(config).trustedHosts
|
|
1177
2058
|
// 诊断(0.5.4 调试):会话状态服务解析情况
|
|
1178
2059
|
try {
|
|
1179
2060
|
const names = ['sessions', 'agents', 'sessionController', 'sessionList', 'session-manager']
|
|
@@ -1196,6 +2077,13 @@ export function apply(ctx) {
|
|
|
1196
2077
|
} catch (e) {
|
|
1197
2078
|
console.log('[message-ops] probe failed: ' + e)
|
|
1198
2079
|
}
|
|
2080
|
+
try {
|
|
2081
|
+
const captured = captureServices(ctx)
|
|
2082
|
+
console.log('[message-ops] captured services: sessions=' + !!captured.sessions + ' agents=' + !!captured.agents)
|
|
2083
|
+
} catch (e) {
|
|
2084
|
+
console.log('[message-ops] capture failed: ' + e)
|
|
2085
|
+
}
|
|
2086
|
+
|
|
1199
2087
|
function registerHttp(host, targetCtx) {
|
|
1200
2088
|
// --- GET /api/message-ops/messages:消息列表(只读) ---------------------
|
|
1201
2089
|
targetCtx.effect(
|
|
@@ -1216,10 +2104,8 @@ export function apply(ctx) {
|
|
|
1216
2104
|
}),
|
|
1217
2105
|
)
|
|
1218
2106
|
} catch (err) {
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
error: String(err && err.message ? err.message : err),
|
|
1222
|
-
})
|
|
2107
|
+
const pub = publicErrorOf(err, errorStatusOf(err))
|
|
2108
|
+
return sendJson(res, pub.status, { ok: false, error: pub.error })
|
|
1223
2109
|
}
|
|
1224
2110
|
},
|
|
1225
2111
|
}),
|
|
@@ -1237,20 +2123,22 @@ export function apply(ctx) {
|
|
|
1237
2123
|
if (!(await fence(targetCtx, req, res))) return
|
|
1238
2124
|
try {
|
|
1239
2125
|
const url = new URL(req.url, 'http://localhost')
|
|
1240
|
-
const limitRaw =
|
|
2126
|
+
const limitRaw = url.searchParams.get('limit')
|
|
2127
|
+
const limit = strictIntParam(limitRaw)
|
|
2128
|
+
if (limitRaw !== null && limit === undefined) {
|
|
2129
|
+
return sendJson(res, 400, { ok: false, error: 'invalid limit' })
|
|
2130
|
+
}
|
|
1241
2131
|
return sendJson(
|
|
1242
2132
|
res,
|
|
1243
2133
|
200,
|
|
1244
2134
|
await opsSearch(targetCtx, url.searchParams.get('sessionId') || '', url.searchParams.get('q') || '', {
|
|
1245
2135
|
role: url.searchParams.get('role') || null,
|
|
1246
|
-
limit
|
|
2136
|
+
limit,
|
|
1247
2137
|
}),
|
|
1248
2138
|
)
|
|
1249
2139
|
} catch (err) {
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
error: String(err && err.message ? err.message : err),
|
|
1253
|
-
})
|
|
2140
|
+
const pub = publicErrorOf(err, errorStatusOf(err))
|
|
2141
|
+
return sendJson(res, pub.status, { ok: false, error: pub.error })
|
|
1254
2142
|
}
|
|
1255
2143
|
},
|
|
1256
2144
|
}),
|
|
@@ -1258,7 +2146,8 @@ export function apply(ctx) {
|
|
|
1258
2146
|
)
|
|
1259
2147
|
|
|
1260
2148
|
// --- GET /api/message-ops/text:单条消息全文(0.5.2 引用按钮按需取) ----------
|
|
1261
|
-
// assistant 消息的 fullText 不在 messages 列表里(载荷控制),quote
|
|
2149
|
+
// assistant 消息的 fullText 不在 messages 列表里(载荷控制),quote/铅笔点击时单取。
|
|
2150
|
+
// 0.25.0:改走 opsText —— 复用 loadDerived 的派生缓存,不再每次全量重读日志。
|
|
1262
2151
|
targetCtx.effect(
|
|
1263
2152
|
() =>
|
|
1264
2153
|
host.register({
|
|
@@ -1270,25 +2159,15 @@ export function apply(ctx) {
|
|
|
1270
2159
|
try {
|
|
1271
2160
|
const url = new URL(req.url, 'http://localhost')
|
|
1272
2161
|
const sessionId = url.searchParams.get('sessionId') || ''
|
|
1273
|
-
const
|
|
1274
|
-
|
|
1275
|
-
if (
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
const { logPath } = pickSessionDir(sessionId)
|
|
1280
|
-
const { events } = await readSessionFileAsync(logPath)
|
|
1281
|
-
const ev = events.find(e => e && e.seq === seq)
|
|
1282
|
-
if (!ev) throw new OpsError('seq not found', 404)
|
|
1283
|
-
// 0.10.8:宿主会把长文本拆成多段 content(seq 6830 实测 321+7954+20),
|
|
1284
|
-
// 只回首段 = 摘要拦腰截断。messageTextFull 与 messageText 同一条
|
|
1285
|
-
// 「合格 text 段」口径,聚合改为全量拼接。
|
|
1286
|
-
return sendJson(res, 200, { ok: true, seq, text: messageTextFull(ev) })
|
|
2162
|
+
const seqRaw = url.searchParams.get('seq')
|
|
2163
|
+
const seq = strictIntParam(seqRaw)
|
|
2164
|
+
if (seq === undefined) {
|
|
2165
|
+
return sendJson(res, 400, { ok: false, error: 'invalid seq' })
|
|
2166
|
+
}
|
|
2167
|
+
return sendJson(res, 200, { ok: true, seq, text: await opsText(sessionId, seq, targetCtx) })
|
|
1287
2168
|
} catch (err) {
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
error: String(err && err.message ? err.message : err),
|
|
1291
|
-
})
|
|
2169
|
+
const pub = publicErrorOf(err, errorStatusOf(err))
|
|
2170
|
+
return sendJson(res, pub.status, { ok: false, error: pub.error })
|
|
1292
2171
|
}
|
|
1293
2172
|
},
|
|
1294
2173
|
}),
|
|
@@ -1305,10 +2184,8 @@ export function apply(ctx) {
|
|
|
1305
2184
|
try {
|
|
1306
2185
|
return sendJson(res, 200, await opsCommit(targetCtx, mode, body.sessionId, body.seq))
|
|
1307
2186
|
} catch (err) {
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
error: String(err && err.message ? err.message : err),
|
|
1311
|
-
})
|
|
2187
|
+
const pub = publicErrorOf(err, errorStatusOf(err))
|
|
2188
|
+
return sendJson(res, pub.status, { ok: false, error: pub.error })
|
|
1312
2189
|
}
|
|
1313
2190
|
}
|
|
1314
2191
|
|
|
@@ -1346,6 +2223,15 @@ export function apply(ctx) {
|
|
|
1346
2223
|
if (!body || typeof body !== 'object') return sendJson(res, 400, { ok: false, error: 'invalid json' })
|
|
1347
2224
|
try {
|
|
1348
2225
|
// 0.8.0:body.upToSeq 存在 → 按轮步进恢复(只到该 seq)
|
|
2226
|
+
// 0.33.2:不得用 Number() 强转("2"/true/[] 都会被接受)。
|
|
2227
|
+
if (body.upToSeq !== undefined && body.upToSeq !== null && !Number.isSafeInteger(body.upToSeq)) {
|
|
2228
|
+
return sendJson(res, 400, { ok: false, error: 'invalid upToSeq' })
|
|
2229
|
+
}
|
|
2230
|
+
// 0.41.2(srv-audit D20):discard 只接受布尔。旧实现 `=== true` 把
|
|
2231
|
+
// "true"/1 静默当 false(用户以为丢弃了、实际执行了恢复)。
|
|
2232
|
+
if (body.discard !== undefined && typeof body.discard !== 'boolean') {
|
|
2233
|
+
return sendJson(res, 400, { ok: false, error: 'invalid discard (boolean expected)' })
|
|
2234
|
+
}
|
|
1349
2235
|
return sendJson(
|
|
1350
2236
|
res,
|
|
1351
2237
|
200,
|
|
@@ -1353,15 +2239,13 @@ export function apply(ctx) {
|
|
|
1353
2239
|
targetCtx,
|
|
1354
2240
|
body.sessionId,
|
|
1355
2241
|
body.seq,
|
|
1356
|
-
body.upToSeq
|
|
2242
|
+
body.upToSeq === undefined || body.upToSeq === null ? undefined : body.upToSeq,
|
|
1357
2243
|
body.discard === true,
|
|
1358
2244
|
),
|
|
1359
2245
|
)
|
|
1360
2246
|
} catch (err) {
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
error: String(err && err.message ? err.message : err),
|
|
1364
|
-
})
|
|
2247
|
+
const pub = publicErrorOf(err, errorStatusOf(err))
|
|
2248
|
+
return sendJson(res, pub.status, { ok: false, error: pub.error })
|
|
1365
2249
|
}
|
|
1366
2250
|
},
|
|
1367
2251
|
}),
|
|
@@ -1378,12 +2262,12 @@ export function apply(ctx) {
|
|
|
1378
2262
|
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
1379
2263
|
if (!(await fence(targetCtx, req, res))) return
|
|
1380
2264
|
try {
|
|
1381
|
-
|
|
2265
|
+
// 0.33.7(sec L2):GET 不得有删除副作用。过期条目的清理改在
|
|
2266
|
+
// 会话删除/回收站动作(POST)里做。
|
|
2267
|
+
return sendJson(res, 200, { ok: true, entries: await listTrash(targetCtx) })
|
|
1382
2268
|
} catch (err) {
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
error: String(err && err.message ? err.message : err),
|
|
1386
|
-
})
|
|
2269
|
+
const pub = publicErrorOf(err, errorStatusOf(err))
|
|
2270
|
+
return sendJson(res, pub.status, { ok: false, error: pub.error })
|
|
1387
2271
|
}
|
|
1388
2272
|
},
|
|
1389
2273
|
}),
|
|
@@ -1405,21 +2289,34 @@ export function apply(ctx) {
|
|
|
1405
2289
|
try {
|
|
1406
2290
|
return sendJson(res, 200, await action(targetCtx, body))
|
|
1407
2291
|
} catch (err) {
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
error: String(err && err.message ? err.message : err),
|
|
1411
|
-
})
|
|
2292
|
+
const pub = publicErrorOf(err, errorStatusOf(err))
|
|
2293
|
+
return sendJson(res, pub.status, { ok: false, error: pub.error })
|
|
1412
2294
|
}
|
|
1413
2295
|
},
|
|
1414
2296
|
}),
|
|
1415
2297
|
'dsh-message-ops: ' + path,
|
|
1416
2298
|
)
|
|
1417
2299
|
|
|
1418
|
-
sessionAction('/api/message-ops/session/delete', (c, b) =>
|
|
2300
|
+
sessionAction('/api/message-ops/session/delete', async (c, b) => {
|
|
2301
|
+
const out = await deleteSessionToTrash(c, b.sessionId, b.confirmTitle)
|
|
2302
|
+
// 顺带清理过期回收站条目(GET 已改为只读)。
|
|
2303
|
+
try {
|
|
2304
|
+
await listTrash(c, { purgeExpired: true })
|
|
2305
|
+
} catch {
|
|
2306
|
+
/* 清理失败不影响删除结果 */
|
|
2307
|
+
}
|
|
2308
|
+
return out
|
|
2309
|
+
})
|
|
1419
2310
|
sessionAction('/api/message-ops/session/restore', (c, b) => restoreTrash(c, b.trashId))
|
|
1420
2311
|
sessionAction('/api/message-ops/session/purge', (c, b) => purgeTrash(c, b.trashId))
|
|
1421
2312
|
}
|
|
1422
2313
|
|
|
2314
|
+
// 0.35.6:**不得**在 `workspace/session-unarchiving` 上注册 listener。
|
|
2315
|
+
// 真机 A/B 证明:只要注册(即使 listener 立即返回、不抛错),宿主的
|
|
2316
|
+
// unarchive RPC 就报 `gateway/internal`(诊断版 listener 内日志从未执行)。
|
|
2317
|
+
// 保护性拦截因此放弃;回收站恢复走插件自己的 Restore,宿主限制记录在
|
|
2318
|
+
// docs/revert-restore-audit.md。
|
|
2319
|
+
|
|
1423
2320
|
const ws = ctx.get('webServer')
|
|
1424
2321
|
if (ws !== undefined) registerHttp(ws, ctx)
|
|
1425
2322
|
else ctx.inject(['webServer'], sub => registerHttp(sub.webServer, sub))
|