@restregular/dsh-memory 0.28.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/panel.js CHANGED
@@ -1,1287 +1,1348 @@
1
- /**
2
- * dsh-memory-panel — 服务端(entry)。
3
- *
4
- * 架构照抄 dsh-meme 的铁律(2026-10-10 crash 的教训):
5
- * - 不导出 inject:一切服务 ctx.get() 被动获取,缺谁就降级跳过,
6
- * 绝不让 fiber 进入 FAILED(desktop fail-loud,一个 entry 失败=整个应用起不来);
7
- * - 路由注册 try/catch:冲突则复用/记日志,不抛;
8
- * - apply 整体兜底 catch:任何意外都不允许向外抛。
9
- *
10
- * 提供管理员 API(前缀路由 /memory/api):
11
- * GET /status 各 scope 记录数 + 待嵌入数 + 展示标签 + 用途描述(0.28.0)
12
- * GET /records ?scope=&q= 枚举/过滤记录
13
- * GET /search ?scope=&q=&topK= 语义检索(向量 + 词法,provider 排序)
14
- * POST /update {id, content?, kind?, importance?, tags?, triggers?, expiresAt?/ttlMs?}
15
- * → 新建一条修正版(supersedes=id),旧记录保留(0.23.0)
16
- * POST /delete {id}
17
- * scope 惰性加载是同步的(store.peek(),**读路径不创建**),无需 ready 门。内容编辑会作废旧
18
- * 向量并加入 embedPending,由 provider 的回填队列重新嵌入。
19
- *
20
- * 安全(每个路由都过 refuseRequest,见下):
21
- * 注册在裸 webServer 上的路由**既不在宿主的 /api 围栏之后,也不在浏览器登录
22
- * 之后** —— 宿主的围栏是一个给别的路由主动调用的服务方法(connection.requestRejection),
23
- * 不是自动套上的中间件(dsh-market #603 的结论:裸 webServer 路由在登录开启时
24
- * 可被无 session 调用 = 任意代码执行)。这里的读接口能读出全部记忆,写接口能改写、
25
- * 删除、清空,还能拉起/卸载向量服务,所以必须自己问一次。
26
- */
27
- // scope 规范化与 provider 共用同一份实现。路径按**源码树位置**写:构建脚本的改写表
28
- // 会把它落成产物里的 `../provider/scope.js`(`lib/panel.js` → `lib/provider/scope.js`),
29
- // 在源码树里同一路径直接命中 source/memory-local/src —— 测试与真实加载都能解析。
30
- import { normalizeScopeInput, resolveCurrentScopes, scopeDisplayName, sessionShortId } from './provider/scope.js'
31
-
32
-
33
- function writeJson(res, body, status = 200) {
34
- try {
35
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
36
- res.end(JSON.stringify(body))
37
- } catch { /* 客户端已断开 */ }
38
- }
39
-
40
- /** provider 侧的"调用方输入有问题"错误码 → 400;其余未标注的仍算 500。 */
41
- const CLIENT_ERROR_CODES = new Set([
42
- 'SCOPE_INVALID', 'SCOPE_DISABLED', 'CONTENT_EMPTY', 'CONTENT_TOO_LONG',
43
- 'SECRET_DETECTED', 'IMPORT_INVALID', 'IMPORT_TOO_LARGE', 'KIND_INVALID',
44
- 'QUERY_EMPTY', 'QUERY_INVALID', 'SESSION_REQUIRED', 'SCOPE_EMPTY', 'SCOPE_NOT_VISIBLE',
45
- ])
46
-
47
- function writeError(res, error) {
48
- const code = typeof error?.code === 'string' ? error.code : 'internal'
49
- const status = Number(error?.status) || (CLIENT_ERROR_CODES.has(code) ? 400 : code === 'SCOPE_LIMIT' ? 409 : 500)
50
- writeJson(res, { ok: false, error: { code, message: error?.message || String(error) } }, status)
51
- }
52
-
53
- class ApiError extends Error {
54
- constructor(status, code, message) {
55
- super(message)
56
- this.status = status
57
- this.code = code
58
- }
59
- }
60
-
61
- /** 只认本机权威(loopback),没有宿主围栏时的兜底。 */
62
- const LOOPBACK_AUTHORITY = /^(?:127(?:\.\d{1,3}){3}|\[::1\]|::1|localhost)(?::\d+)?$/i
63
-
64
- /** 请求头里的 Host,小写归一;缺失返回空串。 */
65
- function hostHeader(req) {
66
- const value = req?.headers?.host
67
- return typeof value === 'string' ? value.trim().toLowerCase() : ''
68
- }
69
-
70
- /** 部署自己声明的权威(宿主 connection 的 trustedHosts);拿不到就空数组。 */
71
- function trustedAuthorities(ctx) {
72
- try {
73
- const connection = ctx?.get?.('connection')
74
- return Array.isArray(connection?.trustedHosts)
75
- ? connection.trustedHosts.filter((entry) => typeof entry === 'string').map((entry) => entry.toLowerCase())
76
- : []
77
- } catch {
78
- return []
79
- }
80
- }
81
-
82
- /**
83
- * 该不该拒绝这个请求。
84
- *
85
- * 两层,顺序有讲究:
86
- * 1. 宿主发布了 connection.requestRejection 时**以它为准** —— 它同时含 Host/Origin
87
- * 围栏(防 DNS rebinding 与跨站调用)与浏览器登录(login-token cookie)。
88
- * 围栏自己抛错时返回 403:抛错意味着"什么都没放行",此处失败关闭,不能放行。
89
- * 2. 旧宿主没有这个服务时自己来:Host 必须是 loopback 或宿主声明的权威,
90
- * sec-fetch-site 不得是 cross-site,带 Origin 就必须与 Host 相等。
91
- * (注意 content-type: text/plain 也能携带合法 JSON 体且不触发预检,
92
- * 所以"要求 JSON 体"挡不住跨站 —— 承重的是 Host/Origin 这一层。)
93
- *
94
- * @returns 需要拒绝时返回状态码(401 未登录 / 403 不受信任),否则 undefined。
95
- */
96
- export function refuseRequest(ctx, req) {
97
- let connection
98
- try { connection = ctx?.get?.('connection') } catch { connection = undefined }
99
- const gate = connection?.requestRejection
100
- if (typeof gate === 'function') {
101
- try {
102
- const status = gate.call(connection, req)
103
- return typeof status === 'number' ? status : undefined
104
- } catch {
105
- return 403
106
- }
107
- }
108
- const host = hostHeader(req)
109
- if (host === '') return 403
110
- if (!LOOPBACK_AUTHORITY.test(host) && !trustedAuthorities(ctx).includes(host)) return 403
111
- if (String(req?.headers?.['sec-fetch-site'] ?? '').toLowerCase() === 'cross-site') return 403
112
- const origin = req?.headers?.origin
113
- if (origin !== undefined) {
114
- try {
115
- if (new URL(String(origin)).host.toLowerCase() !== host) return 403
116
- } catch {
117
- return 403
118
- }
119
- }
120
- return undefined
121
- }
122
-
123
- /** 拒绝时的响应体:给人话,不说内部概念。 */
124
- function writeRefusal(res, status) {
125
- writeJson(res, {
126
- ok: false,
127
- error: {
128
- code: status === 401 ? 'LOGIN_REQUIRED' : 'UNTRUSTED_REQUEST',
129
- message: status === 401
130
- ? '需要先登录 DSH:请重新打开启动时打印的那个网址。'
131
- : '这个请求来自不受信任的来源,已拒绝。',
132
- },
133
- }, status)
134
- }
135
-
136
- async function readJsonBody(req) {
137
- const chunks = []
138
- for await (const chunk of req) chunks.push(chunk)
139
- const raw = Buffer.concat(chunks).toString('utf8')
140
- return raw.length > 0 ? JSON.parse(raw) : {}
141
- }
142
-
143
- /**
144
- * scope 键 → **不需要查宿主服务**的展示名(带类型前缀)。
145
- * global → `global:全局`
146
- * project:<cwd> → `project:<cwd>`
147
- * session:<id> → `session:session-1a2b3c4d`(会话 id 前 16 位)
148
- * 自定义 → `custom:<名字>`(自定义 scope 的键本身没有前缀,靠类型补)
149
- *
150
- * 细节都有两处坑:①会话 id 以 `session-` 开头(正好 8 个字符),取 8 位会让所有会话
151
- * 作用域都显示成同一个名字,所以取 16 位;②自定义作用域与 global 的键天然不带前缀,
152
- * 必须按类型补 —— 规则集中在 provider 的 scopeDisplayName。
153
- */
154
- function fallbackScopeLabel(scope) {
155
- return scopeDisplayName(scope)
156
- }
157
-
158
- /**
159
- * scope 键 → 展示名。在 fallback 之上多一步:会话 scope 尽力取会话标题
160
- * (宿主 `sessionTitle` 服务的 `get(session)` → `{ title }`,见 @deepseek-ai/dsh-session-title)。
161
- * 所有宿主服务访问都在 try/catch 里:面板绝不能因为拿不到标题而失败。
162
- *
163
- * 带标题时形如 `session:修层级(1a2b3c4d)` —— 类型前缀仍在最前面,名字部分换成标题。
164
- */
165
- function scopeLabel(ctx, scope) {
166
- if (!scope.startsWith('session:')) return scopeDisplayName(scope)
167
- const id = scope.slice('session:'.length)
168
- const short = sessionShortId(id)
169
- try {
170
- const session = ctx?.get?.('sessions')?.get?.(id)
171
- if (session !== undefined) {
172
- const title = ctx.get('sessionTitle')?.get?.(session)?.title
173
- if (typeof title === 'string' && title.length > 0) return scopeDisplayName(scope, `${title}(${short})`)
174
- }
175
- } catch { /* 标题是尽力而为 */ }
176
- return scopeDisplayName(scope)
177
- }
178
-
179
- /** 会话 scope 查标题的上限:标题要读会话事件日志,scope 多了它就成了 /status 的大头。 */
180
- const TITLE_LOOKUP_LIMIT = 50
181
- /** discovery(读每个 scope 文件的第一条记录)结果的缓存时长。 */
182
- const DISCOVER_CACHE_MS = 3000
183
- /** 每个 memory 服务的发现缓存。面板看不到进程数,所以按服务实例各存一份。 */
184
- const discoveryCache = new WeakMap()
185
-
186
- /**
187
- * 发现磁盘上的 scope,3 秒内只做一次。
188
- * 面板每个请求都想要一份完整清单(别的进程写下的 scope 也要看得见),而 discovery 要
189
- * 读每个文件的第一条记录 —— 没有缓存的话刷新一下就是一次全目录扫描。
190
- */
191
- function discoverScopes(memory, store) {
192
- const now = Date.now()
193
- const cached = discoveryCache.get(memory)
194
- if (cached !== undefined && now - cached.at < DISCOVER_CACHE_MS) return
195
- discoveryCache.set(memory, { at: now })
196
- try {
197
- if (typeof memory.discoverScopes === 'function') memory.discoverScopes()
198
- else store.loadDiscovered?.()
199
- } catch { /* discovery is best-effort */ }
200
- }
201
-
202
- function wireRecord(rec, scopeStore, supersededBy = null) {
203
- return {
204
- id: rec.id,
205
- scope: rec.scope,
206
- kind: rec.kind,
207
- content: rec.content,
208
- tags: rec.tags ?? [],
209
- importance: rec.importance,
210
- createdAt: rec.createdAt,
211
- updatedAt: rec.updatedAt,
212
- accessCount: rec.accessCount ?? 0,
213
- supersededBy,
214
- supersedes: rec.supersedes ?? null,
215
- triggers: rec.triggers ?? [],
216
- expiredAt: rec.expiredAt ?? null,
217
- expired: rec.expiredAt !== undefined && rec.expiredAt < Date.now(),
218
- embedded: !scopeStore.embedPending.has(rec.id) && scopeStore.vectors.has(rec.id),
219
- }
220
- }
221
-
222
- function collectScope(scopeStore) {
223
- // supersedes 是"新记录 → 旧记录"的指向;反查一次,给旧记录标上"已被修正"。
224
- const correctedBy = new Map()
225
- for (const rec of scopeStore.records.values()) {
226
- if (rec.supersedes) correctedBy.set(rec.supersedes, rec.id)
227
- }
228
- const out = []
229
- for (const rec of scopeStore.records.values()) out.push(wireRecord(rec, scopeStore, correctedBy.get(rec.id) ?? null))
230
- return out.sort((a, b) => b.updatedAt - a.updatedAt)
231
- }
232
-
233
- /** 审计时间参数:Unix ms 或可解析的 ISO 字符串。 */
234
- function parseAuditTime(value, name) {
235
- if (value === null || value === undefined || value === '') return undefined
236
- const numeric = Number(value)
237
- if (Number.isFinite(numeric)) return numeric
238
- const parsed = Date.parse(value)
239
- if (Number.isFinite(parsed)) return parsed
240
- throw new ApiError(400, 'AUDIT_QUERY_INVALID', `${name} 必须是毫秒时间戳或 ISO 时间`)
241
- }
242
-
243
- /** 面板查询参数 → audit sink 的 AuditListQuery。 */
244
- const AUDIT_CHANNELS = new Set(['digest', 'recall', 'rules', 'rules_delta', 'policy', 'nudge', 'signal', 'lifecycle'])
245
- const AUDIT_OUTCOMES = new Set(['success', 'failed', 'skipped', 'partial', 'unknown'])
246
- function parseAuditQuery(url) {
247
- const text = (name) => {
248
- const value = url.searchParams.get(name)
249
- const trimmed = value === null ? '' : value.trim()
250
- return trimmed === '' ? undefined : trimmed
251
- }
252
- const limitRaw = text('limit')
253
- let limit
254
- if (limitRaw !== undefined) {
255
- if (!/^\d+$/.test(limitRaw)) throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'limit 必须是 1..200 的整数')
256
- limit = Number(limitRaw)
257
- if (limit < 1 || limit > 200) throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'limit 必须在 1..200 之间')
258
- }
259
- const cursor = text('cursor')
260
- if (cursor !== undefined && !/^\d+$/.test(cursor)) {
261
- throw new ApiError(400, 'AUDIT_CURSOR_INVALID', 'cursor 必须是 seq 数字')
262
- }
263
- const channel = text('channel')
264
- if (channel !== undefined && !AUDIT_CHANNELS.has(channel)) {
265
- throw new ApiError(400, 'AUDIT_QUERY_INVALID', `未知 channel: ${channel}`)
266
- }
267
- const outcome = text('outcome')
268
- if (outcome !== undefined && !AUDIT_OUTCOMES.has(outcome)) {
269
- throw new ApiError(400, 'AUDIT_QUERY_INVALID', `未知 outcome: ${outcome}`)
270
- }
271
- const since = parseAuditTime(text('since'), 'since')
272
- const until = parseAuditTime(text('until'), 'until')
273
- if (since !== undefined && until !== undefined && since > until) {
274
- throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'since 不能晚于 until')
275
- }
276
- return {
277
- ...(text('session') !== undefined ? { sessionId: text('session') } : {}),
278
- ...(text('trace') !== undefined ? { traceId: text('trace') } : {}),
279
- ...(text('operation') !== undefined ? { operationId: text('operation') } : {}),
280
- ...(text('memory') !== undefined ? { memoryId: text('memory') } : {}),
281
- ...(channel !== undefined ? { channel } : {}),
282
- ...(text('trigger') !== undefined ? { trigger: text('trigger') } : {}),
283
- ...(outcome !== undefined ? { outcome } : {}),
284
- ...(url.searchParams.get('problem') === '1' ? { problem: true } : {}),
285
- ...(since !== undefined ? { since } : {}),
286
- ...(until !== undefined ? { until } : {}),
287
- ...(limit !== undefined ? { limit } : {}),
288
- ...(cursor !== undefined ? { cursor } : {}),
289
- }
290
- }
291
-
292
- function publicAuditQuery(query) {
293
- return {
294
- ...(query.sessionId !== undefined ? { sessionId: query.sessionId } : {}),
295
- ...(query.traceId !== undefined ? { traceId: query.traceId } : {}),
296
- ...(query.operationId !== undefined ? { operationId: query.operationId } : {}),
297
- ...(query.memoryId !== undefined ? { memoryId: query.memoryId } : {}),
298
- ...(query.channel !== undefined ? { channel: query.channel } : {}),
299
- ...(query.trigger !== undefined ? { trigger: query.trigger } : {}),
300
- ...(query.outcome !== undefined ? { outcome: query.outcome } : {}),
301
- ...(query.problem === true ? { problem: true } : {}),
302
- ...(query.since !== undefined ? { since: query.since } : {}),
303
- ...(query.until !== undefined ? { until: query.until } : {}),
304
- limit: query.limit ?? 50,
305
- ...(query.cursor !== undefined ? { cursor: query.cursor } : {}),
306
- scope: query.sessionId !== undefined ? 'session' : 'all',
307
- }
308
- }
309
-
310
- function emptyAuditStats() {
311
- return {
312
- entries: 0, capacity: 0, perSessionCapacity: 0, dropped: 0,
313
- writeErrors: 0, persistence: 'memory',
314
- }
315
- }
316
-
317
- function auditStats(memory) {
318
- try {
319
- const stats = typeof memory?.injectAuditStats === 'function' ? memory.injectAuditStats() : undefined
320
- return stats && typeof stats === 'object' ? stats : emptyAuditStats()
321
- } catch {
322
- return { ...emptyAuditStats(), persistence: 'degraded' }
323
- }
324
- }
325
-
326
- /** 旧 provider 只有 injectAudit(list) 时,在面板侧补最小过滤/分页。 */
327
- function legacyAuditPage(memory, query) {
328
- const all = (() => {
329
- try { return typeof memory?.injectAudit === 'function' ? memory.injectAudit(query.sessionId) : [] } catch { return [] }
330
- })()
331
- const entries = Array.isArray(all) ? all : []
332
- const filtered = entries.filter((entry) => {
333
- if (!entry || typeof entry !== 'object') return false
334
- if (query.channel !== undefined && entry.channel !== query.channel) return false
335
- if (query.trigger !== undefined && entry.trigger !== query.trigger) return false
336
- if (query.outcome !== undefined && entry.outcome !== query.outcome) return false
337
- if (query.problem === true) {
338
- const delivery = entry.delivery
339
- const omitted = Array.isArray(entry.omitted) ? entry.omitted.length : 0
340
- if (!(entry.outcome === 'failed' || entry.outcome === 'partial' || omitted > 0 || (delivery && delivery.status !== 'appended' && delivery.status !== 'unknown'))) return false
341
- }
342
- if (query.memoryId !== undefined) {
343
- const ids = [
344
- ...(entry.contentIds ?? []), ...(entry.hintIds ?? []),
345
- ...((entry.selected && entry.selected.contentIds) ?? []),
346
- ...((entry.omitted ?? []).map((item) => item.id)),
347
- ]
348
- if (!ids.includes(query.memoryId)) return false
349
- }
350
- if (query.since !== undefined && !(entry.at >= query.since)) return false
351
- if (query.until !== undefined && !(entry.at <= query.until)) return false
352
- return true
353
- })
354
- const limit = query.limit ?? 50
355
- const start = query.cursor === undefined ? 0 : Number(query.cursor)
356
- const page = filtered.slice(start, start + limit)
357
- return {
358
- entries: page,
359
- total: filtered.length,
360
- ...(start + limit < filtered.length ? { nextCursor: String(start + limit) } : {}),
361
- stats: emptyAuditStats(),
362
- }
363
- }
364
-
365
- /**
366
- * 把一个审计条目的 turn/step 锚点解析成轨迹可直接聚焦的 tool call id。
367
- *
368
- * Trajectory 的深链只接受 callId(它的 `toolCallFocus` 就是同一性映射),所以
369
- * 没有 operationId 的审计事件(摘要/规则等按步注入)需要回到会话事件里找该步
370
- * 的第一个 `tool/call`。找不到工具调用时不伪造:返回 null,由客户端退化成
371
- * “只切到轨迹页”。
372
- *
373
- * @param ctx - Host 插件上下文。
374
- * @param query - `{ sessionId, turn?, step?, callId? }`。
375
- * @returns 锚点结果(永不抛错)。
376
- */
377
- export function findTrajectoryAnchor(ctx, query) {
378
- const sessionId = typeof query?.sessionId === 'string' ? query.sessionId.trim() : ''
379
- if (sessionId === '') return { callId: null, reason: 'session_required' }
380
- let session
381
- try { session = ctx?.get?.('sessions')?.get?.(sessionId) } catch { session = undefined }
382
- if (session === undefined || typeof session?.ownEvents !== 'function') {
383
- return { callId: null, reason: 'session_unavailable' }
384
- }
385
- const turn = typeof query.turn === 'number' ? query.turn : undefined
386
- const step = typeof query.step === 'number' ? query.step : undefined
387
- // 已有 callId 时校验它确实属于这个会话,避免把跨会话/伪造 id 送进轨迹。
388
- const wanted = typeof query.callId === 'string' && query.callId !== '' ? query.callId : undefined
389
- try {
390
- for (const event of session.ownEvents()) {
391
- if (event?.type !== 'tool/call') continue
392
- const data = event.data ?? {}
393
- if (turn !== undefined && data.turn !== turn) continue
394
- if (step !== undefined && data.step !== step) continue
395
- const callId = typeof data.callId === 'string' ? data.callId : undefined
396
- if (callId === undefined) continue
397
- if (wanted !== undefined && callId !== wanted) continue
398
- return {
399
- callId,
400
- tool: typeof data.name === 'string' ? data.name : undefined,
401
- turn: typeof data.turn === 'number' ? data.turn : undefined,
402
- step: typeof data.step === 'number' ? data.step : undefined,
403
- reason: wanted !== undefined ? 'operation' : 'step_tool',
404
- }
405
- }
406
- } catch { /* 事件窗口读取失败:按找不到处理 */ }
407
- return { callId: null, reason: wanted !== undefined ? 'operation_not_found' : 'no_tool_in_step' }
408
- }
409
-
410
- function auditPage(memory, query) { if (memory === undefined || memory === null) {
411
- throw new ApiError(503, 'AUDIT_UNAVAILABLE', 'memory provider 未加载')
412
- }
413
- try {
414
- if (typeof memory.injectAuditPage === 'function') {
415
- const page = memory.injectAuditPage(query)
416
- if (page && typeof page === 'object' && Array.isArray(page.entries)) {
417
- return {
418
- entries: page.entries,
419
- total: typeof page.total === 'number' ? page.total : page.entries.length,
420
- ...(typeof page.nextCursor === 'string' ? { nextCursor: page.nextCursor } : {}),
421
- stats: page.stats && typeof page.stats === 'object' ? page.stats : emptyAuditStats(),
422
- }
423
- }
424
- }
425
- if (typeof memory.injectAudit === 'function') return legacyAuditPage(memory, query)
426
- throw new ApiError(503, 'AUDIT_UNAVAILABLE', 'provider 未提供注入审计接口(请升级 @restregular/dsh-memory)')
427
- } catch (error) {
428
- if (error instanceof ApiError) throw error
429
- if (error && typeof error.code === 'string' && error.code.startsWith('AUDIT_')) {
430
- throw new ApiError(400, error.code, error.message || '审计查询参数无效')
431
- }
432
- throw error
433
- }
434
- }
435
-
436
- /** 导出:按当前筛选循环取页(上限 200/页,最多 50 页 = 10000 条)。 */
437
- function collectAuditEntries(memory, query) {
438
- const out = []
439
- let cursor
440
- for (let i = 0; i < 50; i++) {
441
- const page = auditPage(memory, { ...query, ...(cursor !== undefined ? { cursor } : {}), limit: 200 })
442
- out.push(...page.entries)
443
- if (page.nextCursor === undefined) break
444
- cursor = page.nextCursor
445
- }
446
- return out
447
- }
448
-
449
- /** scope 选择 → 实际存在的 ScopeStore(读路径只用 peek,绝不通过 store.scope() 创建)。 */
450
- function selectedStores(store, selection) {
451
- if (selection === null) return store.allScopes()
452
- return (Array.isArray(selection) ? selection : [selection])
453
- .map((s) => store.peek(s))
454
- .filter((s) => s !== undefined)
455
- }
456
-
457
- /**
458
- * 面板的 scope 参数 → 要看的 scope 集合。
459
- * null = 全部作用域
460
- * string[] = 规范化后的 scope 键(current-session / current-project 由 provider 解析)
461
- * 非法输入抛 400,合法但不存在的 scope 由 selectedStores 自然过滤成空集合。
462
- */
463
- function resolveScopeSelection(memory, rawScope) {
464
- if (rawScope === null || rawScope === undefined || rawScope.trim() === '') return null
465
- const normalized = normalizeScopeInput(rawScope)
466
- if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
467
- if (normalized.kind === 'all') return null
468
- if (normalized.kind === 'current-session' || normalized.kind === 'current-project') {
469
- // 面板不在某个 agent 里:按 provider 的读取集合解析('project' → 当前项目键);
470
- // 解析不出会话时就退化为全部,而不是报错。
471
- const refs = typeof memory.resolveReadScopes === 'function' ? memory.resolveReadScopes(undefined) : []
472
- return refs.length > 0 ? refs : null
473
- }
474
- return normalized.scope ?? null
475
- }
476
-
477
- /** 面板已知的记忆类型(与工具的 kind enum 一致)。 */
478
- /**
479
- * 会话「记忆可见域」的完整快照:自己的覆盖 + 生效策略 + 可选范围目录。
480
- *
481
- * 自己的覆盖(null = 没设置)用于面板上的"恢复默认";effective 用于预选(子 Agent
482
- * 会话会继承父会话的覆盖);defaults 是"没有显式覆盖时 Agent 实际会读的集合",
483
- * 首次打开面板时按它预选,而不是显示成什么都没选。
484
- *
485
- * 0.19.1 起不再支持按记忆类型收窄:目录只返回 scope,不再返回 kinds。
486
- */
487
- function visibilityPayload(ctx, memory, sessionId) {
488
- let session
489
- try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
490
- const agentLike = { session: session !== undefined ? session : { id: sessionId } }
491
- const own = typeof memory.sessionVisibility === 'function' ? memory.sessionVisibility(sessionId) : null
492
- let effective = null
493
- let inherited = false
494
- // 0.20.0 起 provider 永远给一份生效策略(没有显式覆盖时是默认策略)。
495
- // source 告诉面板这份策略是"自己的 / 继承的 / 默认的"。
496
- let source = own === null ? 'default' : 'explicit'
497
- try {
498
- if (typeof memory.visibilityPolicy === 'function') {
499
- const policy = memory.visibilityPolicy(agentLike)
500
- if (policy !== undefined && policy !== null) {
501
- effective = policy
502
- source = policy.source === 'explicit' || policy.source === 'inherited' || policy.source === 'default'
503
- ? policy.source
504
- : (own === null ? 'default' : 'explicit')
505
- inherited = source === 'inherited'
506
- }
507
- }
508
- } catch { /* 可见域是增强;拿不到就只返回自己的覆盖 */ }
509
-
510
- let refs
511
- try { if (session !== undefined) refs = resolveCurrentScopes({ session }) } catch { refs = undefined }
512
- // 没有显式覆盖时,面板仍预选"当前默认读取集合"(会话 + 项目 + global + 工作区绑定),
513
- // 让用户看到 Agent 现在实际能看到什么;保存后才变成显式覆盖。
514
- let defaults = []
515
- try {
516
- const resolved = memory.resolveReadScopes?.(agentLike)
517
- if (Array.isArray(resolved)) defaults = resolved
518
- } catch { /* 降级为空 */ }
519
-
520
- // 0.23.0:工作区级绑定 + 每个作用域的 read / write 状态。
521
- let workspace = null
522
- let bindings = []
523
- try {
524
- if (typeof memory.projectKeyFor === 'function') workspace = memory.projectKeyFor(agentLike)
525
- if (typeof memory.workspaceBindings === 'function') {
526
- const list = memory.workspaceBindings(agentLike)
527
- if (Array.isArray(list)) bindings = list
528
- }
529
- } catch { /* 绑定是增强;拿不到就按"没有绑定"处理 */ }
530
- const bound = new Set(bindings)
531
- const rules = new Map()
532
- for (const rule of (Array.isArray(effective?.scopes) ? effective.scopes : [])) {
533
- if (rule && typeof rule.scope === 'string' && !rules.has(rule.scope)) rules.set(rule.scope, rule)
534
- }
535
-
536
- const stats = typeof memory.scopeStats === 'function' ? memory.scopeStats() : []
537
- const byScope = new Map()
538
- for (const item of Array.isArray(stats) ? stats : []) {
539
- if (item && typeof item.scope === 'string') byScope.set(item.scope, { ...item })
540
- }
541
- // 即使还没有任何记录 / 宿主没给 sessions,也要能把默认集合里的 scope 勾出来。
542
- const ensure = (scope) => {
543
- if (typeof scope === 'string' && scope !== '' && !byScope.has(scope)) {
544
- byScope.set(scope, { scope, records: 0, pendingEmbeds: 0 })
545
- }
546
- }
547
- const sessionScope = refs?.session ?? defaults.find((scope) => scope.startsWith('session:'))
548
- const projectScope = refs?.project ?? defaults.find((scope) => scope.startsWith('project:'))
549
- // 默认范围的**基础集合** = 会话 + 项目 + global。它们天然包含在默认范围里,
550
- // 面板按「已绑定」展示且不可取消;工作区绑定只负责额外并入其它作用域。
551
- let defaultScopes = []
552
- try {
553
- const list = typeof memory.defaultScopes === 'function' ? memory.defaultScopes(agentLike) : undefined
554
- if (Array.isArray(list)) defaultScopes = list.filter((scope) => typeof scope === 'string' && scope !== '')
555
- } catch { /* 旧 provider:退回下面的本地面包 */ }
556
- if (defaultScopes.length === 0) {
557
- defaultScopes = [sessionScope, projectScope, 'global'].filter((scope) => typeof scope === 'string' && scope !== '')
558
- }
559
- const defaultBound = new Set(defaultScopes)
560
- ensure(sessionScope)
561
- ensure(projectScope)
562
- ensure('global')
563
- for (const scope of defaults) ensure(scope)
564
- for (const scope of bindings) ensure(scope)
565
- const rank = (scope) => scope === sessionScope ? 0 : scope === projectScope ? 1 : scope === 'global' ? 2 : 3
566
- const scopes = [...byScope.values()]
567
- .sort((a, b) => rank(a.scope) - rank(b.scope) || String(a.scope).localeCompare(String(b.scope)))
568
- .map((item) => {
569
- const rule = rules.get(item.scope)
570
- return {
571
- ...item,
572
- // 别名也带类型前缀:项目别名 → `project:<别名>`,自定义 → `custom:<别名>`。
573
- label: typeof item.name === 'string' && item.name !== ''
574
- ? scopeDisplayName(item.scope, item.name)
575
- : scopeLabel(ctx, item.scope),
576
- read: rule === undefined ? true : rule.read !== false,
577
- write: rule === undefined ? true : rule.write !== false,
578
- // bound = 显式绑定或默认范围自带;defaultBound 告诉客户端这一项不能取消。
579
- bound: bound.has(item.scope) || defaultBound.has(item.scope),
580
- defaultBound: defaultBound.has(item.scope),
581
- bindable: !String(item.scope).startsWith('session:') && !defaultBound.has(item.scope),
582
- }
583
- })
584
- return {
585
- sessionId,
586
- override: own,
587
- effective,
588
- inherited,
589
- source,
590
- defaults,
591
- defaultScopes,
592
- workspace,
593
- bindings: [...bound],
594
- scopes,
595
- }
596
- }
597
-
598
- /**
599
- * 校验并规范化「工作区绑定」提交(0.25.13)。
600
- *
601
- * `/visibility` 与 `/bindings` 共用同一套规则:只接受**具体作用域键**
602
- * (不接受 `all` / 当前项目 / 当前会话这类别名),会话作用域不能绑定到工作区
603
- * (它只属于某一次会话),重复项去重保序。
604
- *
605
- * @param rawBindings - 客户端提交的绑定数组(任意值都按非法处理)。
606
- * @returns 规范化后的作用域键数组。
607
- */
608
- function normalizeBindings(rawBindings) {
609
- if (!Array.isArray(rawBindings)) throw new ApiError(400, 'SCOPE_INVALID', 'bindings 必须是字符串数组')
610
- const bindings = []
611
- for (const raw of rawBindings) {
612
- if (typeof raw !== 'string' || raw.trim() === '') throw new ApiError(400, 'SCOPE_INVALID', '绑定项必须是非空字符串')
613
- const normalized = normalizeScopeInput(raw)
614
- if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
615
- if (normalized.kind === 'all' || normalized.kind === 'current-project' || normalized.kind === 'current-session' || normalized.scope === undefined) {
616
- throw new ApiError(400, 'SCOPE_INVALID', `绑定必须是具体作用域键: ${JSON.stringify(raw)}`)
617
- }
618
- if (normalized.scope.startsWith('session:')) {
619
- throw new ApiError(400, 'SCOPE_INVALID', '会话作用域不能绑定到工作区')
620
- }
621
- if (!bindings.includes(normalized.scope)) bindings.push(normalized.scope)
622
- }
623
- return bindings
624
- }
625
-
626
- /**
627
- * 面板「记忆权限」的授权快照(0.25.0)。
628
- *
629
- * grants 由 Agent 通过 memory_scopes request 申请、用户批准产生;这里只暴露
630
- * scope / 权限 / 授予时间,不返回任何记忆正文。`inherited` 表示这条授权属于父会话。
631
- */
632
- function grantsPayload(ctx, memory, sessionId) {
633
- const list = []
634
- let grants = []
635
- try {
636
- grants = typeof memory.sessionGrants === 'function' ? memory.sessionGrants(sessionId) : []
637
- } catch { grants = [] }
638
- for (const grant of Array.isArray(grants) ? grants : []) {
639
- if (!grant || typeof grant.scope !== 'string' || grant.scope === '') continue
640
- const permissions = Array.isArray(grant.permissions)
641
- ? grant.permissions.filter((permission) => permission === 'read' || permission === 'write')
642
- : []
643
- if (permissions.length === 0) continue
644
- const ownerSession = typeof grant.sessionId === 'string' && grant.sessionId !== '' ? grant.sessionId : sessionId
645
- list.push({
646
- id: typeof grant.id === 'string' ? grant.id : '',
647
- scope: grant.scope,
648
- label: scopeLabel(ctx, grant.scope),
649
- permissions,
650
- grantedAt: typeof grant.grantedAt === 'number' ? grant.grantedAt : 0,
651
- ownerSession,
652
- inherited: ownerSession !== sessionId,
653
- })
654
- }
655
- list.sort((a, b) => a.grantedAt - b.grantedAt || a.scope.localeCompare(b.scope))
656
- return { sessionId, grants: list }
657
- }
658
-
659
- async function handle(ctx, routePath, req, res) {
660
- const url = new URL(req.url ?? '/', 'http://dsh.local')
661
- const path = url.pathname.slice(routePath.length) || '/'
662
- const method = req.method ?? 'GET'
663
- // 围栏在最前面:任何路由(读也一样)都先过宿主,再谈记忆。
664
- const refused = refuseRequest(ctx, req)
665
- if (refused !== undefined) {
666
- writeRefusal(res, refused)
667
- return
668
- }
669
- try {
670
- const memory = ctx.get('memory')
671
- // 审计路由只依赖注入半边挂载的 sink,不依赖记忆 store;先于 store 检查。
672
- if (method === 'GET' && path === '/audit') {
673
- const query = parseAuditQuery(url)
674
- const value = auditPage(memory, query)
675
- writeJson(res, { ok: true, value: { ...value, query: publicAuditQuery(query) } })
676
- return
677
- }
678
- if (method === 'GET' && path === '/audit/stats') {
679
- writeJson(res, { ok: true, value: auditStats(memory) })
680
- return
681
- }
682
- if (method === 'GET' && path === '/anchor') {
683
- const numeric = (name) => {
684
- const raw = url.searchParams.get(name)
685
- if (raw === null || raw.trim() === '') return undefined
686
- if (!/^-?\d+$/.test(raw.trim())) throw new ApiError(400, 'ANCHOR_QUERY_INVALID', `${name} 必须是整数`)
687
- return Number(raw)
688
- }
689
- const query = {
690
- sessionId: url.searchParams.get('session') ?? '',
691
- turn: numeric('turn'),
692
- step: numeric('step'),
693
- callId: url.searchParams.get('callId') ?? undefined,
694
- }
695
- writeJson(res, { ok: true, value: findTrajectoryAnchor(ctx, query) })
696
- return
697
- }
698
- if (method === 'GET' && path === '/audit/export') {
699
- const query = parseAuditQuery(url)
700
- const format = url.searchParams.get('format') === 'jsonl' ? 'jsonl' : 'json'
701
- const entries = collectAuditEntries(memory, query)
702
- const body = format === 'jsonl'
703
- ? entries.map((entry) => JSON.stringify(entry)).join('\n') + (entries.length > 0 ? '\n' : '')
704
- : JSON.stringify({
705
- schemaVersion: 2,
706
- exportedAt: Date.now(),
707
- query: publicAuditQuery(query),
708
- count: entries.length,
709
- entries,
710
- }, null, 2) + '\n'
711
- try {
712
- res.writeHead(200, {
713
- 'content-type': format === 'jsonl' ? 'application/x-ndjson; charset=utf-8' : 'application/json; charset=utf-8',
714
- 'content-disposition': `attachment; filename="dsh-memory-audit.${format === 'jsonl' ? 'jsonl' : 'json'}"`,
715
- 'cache-control': 'no-store',
716
- })
717
- res.end(body)
718
- } catch { /* client disconnected */ }
719
- return
720
- }
721
- if (!memory?.store) throw new ApiError(503, 'MEMORY_UNAVAILABLE', 'memory provider 未加载')
722
- const store = memory.store
723
- // Scopes are created lazily, so a fresh process only knows the ones it has
724
- // touched. A management view must see everything written on disk (project
725
- // memories from earlier sessions included) — best-effort discovery, cached.
726
- discoverScopes(memory, store)
727
-
728
- // 会话级「记忆可见范围」:输入框旁的按钮读写这一对接口。
729
- if (method === 'GET' && path === '/visibility') {
730
- if (typeof memory.sessionVisibility !== 'function') {
731
- throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
732
- }
733
- const sessionId = (url.searchParams.get('session') ?? '').trim()
734
- if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
735
- writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
736
- return
737
- }
738
- if (method === 'POST' && path === '/visibility') {
739
- if (typeof memory.setSessionVisibility !== 'function') {
740
- throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
741
- }
742
- const body = await readJsonBody(req)
743
- const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
744
- if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
745
- let next = null
746
- const rawConfig = body?.visibility
747
- // 新协议:{ visibility: { scopes: [{ scope, read?, write? }], level } } | null
748
- // 兼容 0.19.0 的 { scopes: [{ scope, kinds? }] } 与 0.18 的 { scopes: string[] }:
749
- // 0.19.1 起不再限制记忆类型,提交里的 kinds 一律忽略。
750
- const rawScopes = rawConfig !== null && rawConfig !== undefined && typeof rawConfig === 'object'
751
- ? rawConfig.scopes
752
- : body?.scopes
753
- if (rawScopes !== null && rawScopes !== undefined) {
754
- if (!Array.isArray(rawScopes)) throw new ApiError(400, 'SCOPE_INVALID', 'scopes 必须是数组或 null')
755
- if (rawScopes.length === 0) throw new ApiError(400, 'SCOPE_EMPTY', '至少选择一个可见范围')
756
- const scopes = []
757
- for (const raw of rawScopes) {
758
- const scopeRaw = typeof raw === 'string' ? raw : raw?.scope
759
- if (typeof scopeRaw !== 'string' || scopeRaw.trim() === '') {
760
- throw new ApiError(400, 'SCOPE_INVALID', 'scope 必须是非空字符串')
761
- }
762
- const normalized = normalizeScopeInput(scopeRaw)
763
- if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
764
- if (normalized.kind === 'all' || normalized.kind === 'current-project' || normalized.kind === 'current-session') {
765
- throw new ApiError(400, 'SCOPE_INVALID', `可见范围必须是具体作用域键: ${JSON.stringify(scopeRaw)}`)
766
- }
767
- if (normalized.scope === undefined || scopes.some((item) => item.scope === normalized.scope)) continue
768
- // 0.23.0:read / write 状态。省略 = 可读可写;只有显式 false 才落盘。
769
- const read = typeof raw === 'object' && raw !== null && raw.read === false
770
- const write = typeof raw === 'object' && raw !== null && raw.write === false
771
- scopes.push({
772
- scope: normalized.scope,
773
- ...(read ? { read: false } : {}),
774
- ...(write ? { write: false } : {}),
775
- })
776
- }
777
- const levelRaw = rawConfig !== null && rawConfig !== undefined && typeof rawConfig === 'object' ? rawConfig.level : 'absolute'
778
- const level = levelRaw === 'normal' || levelRaw === 'none' ? levelRaw : 'absolute'
779
- next = { scopes, level }
780
- }
781
- // 工作区级绑定:省略 = 不改;数组 = 整体替换。与可见范围同一个保存动作提交。
782
- const rawBindings = body?.bindings
783
- if (rawBindings !== undefined) {
784
- if (typeof memory.setWorkspaceBindings !== 'function') {
785
- throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供工作区绑定接口(请升级 @restregular/dsh-memory)')
786
- }
787
- const bindings = normalizeBindings(rawBindings)
788
- let session
789
- try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
790
- memory.setWorkspaceBindings({ session: session !== undefined ? session : { id: sessionId } }, bindings)
791
- }
792
- memory.setSessionVisibility(sessionId, next)
793
- writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
794
- return
795
- }
796
-
797
- // 记忆权限浮窗的「绑定」按钮**单独保存**(0.25.13):绑定是工作区级设置
798
- // (本工作区新会话的默认可见范围),和「勾选范围 / 可读可写」的草稿无关,
799
- // 所以点一下立即落盘,不需要用户再点「保存」;也不注入上下文提示。
800
- if (method === 'POST' && path === '/bindings') {
801
- if (typeof memory.setWorkspaceBindings !== 'function') {
802
- throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供工作区绑定接口(请升级 @restregular/dsh-memory)')
803
- }
804
- const body = await readJsonBody(req)
805
- const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
806
- if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
807
- const bindings = normalizeBindings(body?.bindings)
808
- let session
809
- try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
810
- const written = memory.setWorkspaceBindings({ session: session !== undefined ? session : { id: sessionId } }, bindings)
811
- writeJson(res, {
812
- ok: true,
813
- value: { sessionId, bindings: Array.isArray(written) ? written : bindings },
814
- })
815
- return
816
- }
817
-
818
- // 普通限制下的范围外访问审批:客户端浮层轮询待审批,用户点「拒绝 / 允许一次」后回写。
819
- // `summary=1` 是 0.25.14 新增的轻量口径:侧边栏阻塞提醒只需要 id + sessionId,
820
- // 不带条目正文,避免全局 1.5s 轮询把审批内容一遍遍传一遍。
821
- if (method === 'GET' && path === '/approvals') {
822
- if (typeof memory.pendingVisibilityApprovals !== 'function') {
823
- throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供可见域审批接口(请升级 @restregular/dsh-memory)')
824
- }
825
- const sessionId = (url.searchParams.get('session') ?? '').trim()
826
- const summary = url.searchParams.get('summary') === '1'
827
- const approvals = summary && typeof memory.pendingVisibilityApprovalPresence === 'function'
828
- ? memory.pendingVisibilityApprovalPresence(sessionId === '' ? undefined : sessionId)
829
- : memory.pendingVisibilityApprovals(sessionId === '' ? undefined : sessionId)
830
- writeJson(res, { ok: true, value: { approvals } })
831
- return
832
- }
833
- if (method === 'POST' && path === '/approvals') {
834
- if (typeof memory.answerVisibilityApproval !== 'function') {
835
- throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供可见域审批接口(请升级 @restregular/dsh-memory)')
836
- }
837
- const body = await readJsonBody(req)
838
- const id = typeof body?.id === 'string' ? body.id.trim() : ''
839
- if (id === '') throw new ApiError(400, 'APPROVAL_ID_REQUIRED', 'id 不能为空')
840
- const outcome = body?.outcome === 'allowed-once' ? 'allowed-once' : body?.outcome === 'rejected' ? 'rejected' : ''
841
- if (outcome === '') throw new ApiError(400, 'APPROVAL_OUTCOME_INVALID', 'outcome 必须是 allowed-once 或 rejected')
842
- // 0.21.0:逐条允许。省略 = 全部允许;空数组 = 一条都不允许(按拒绝处理)。
843
- const rawIds = body?.allowedIds
844
- if (rawIds !== undefined && rawIds !== null && !Array.isArray(rawIds)) {
845
- throw new ApiError(400, 'APPROVAL_IDS_INVALID', 'allowedIds 必须是字符串数组')
846
- }
847
- const allowedIds = Array.isArray(rawIds) ? rawIds.filter((value) => typeof value === 'string' && value !== '') : undefined
848
- const answered = allowedIds === undefined
849
- ? memory.answerVisibilityApproval(id, outcome)
850
- : memory.answerVisibilityApproval(id, outcome, allowedIds)
851
- writeJson(res, { ok: true, value: { answered } })
852
- return
853
- }
854
-
855
- // 面板「记忆权限」:Agent 申请到的会话授权 + 撤销(0.25.0)。
856
- if (method === 'GET' && path === '/grants') {
857
- if (typeof memory.sessionGrants !== 'function') {
858
- throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话授权接口(请升级 @restregular/dsh-memory)')
859
- }
860
- const sessionId = (url.searchParams.get('session') ?? '').trim()
861
- if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
862
- writeJson(res, { ok: true, value: grantsPayload(ctx, memory, sessionId) })
863
- return
864
- }
865
- if (method === 'POST' && path === '/grants') {
866
- if (typeof memory.revokeGrant !== 'function') {
867
- throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供授权撤销接口(请升级 @restregular/dsh-memory)')
868
- }
869
- const body = await readJsonBody(req)
870
- const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
871
- const id = typeof body?.id === 'string' ? body.id.trim() : ''
872
- if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
873
- if (id === '') throw new ApiError(400, 'GRANT_ID_REQUIRED', 'id 不能为空')
874
- const revoked = memory.revokeGrant(sessionId, id)
875
- if (!revoked) throw new ApiError(404, 'GRANT_NOT_FOUND', '没有找到这条授权(可能已撤销或已过期)')
876
- const view = typeof body?.view === 'string' && body.view.trim() !== '' ? body.view.trim() : sessionId
877
- writeJson(res, { ok: true, value: grantsPayload(ctx, memory, view) })
878
- return
879
- }
880
-
881
- if (method === 'GET' && path === '/status') {
882
- const stats = typeof memory.scopeStats === 'function'
883
- ? memory.scopeStats()
884
- : store.allScopes().map((s) => ({ scope: s.scope, records: s.records.size, pendingEmbeds: s.embedPending.size }))
885
- // 作用域用途(0.28.0):面板「记录 → 作用域」子标签页要展示的「这个域是干什么的」。
886
- // 与 memory_scopes 目录 / memory_search 的范围外清单同源(scope-meta 手写优先,
887
- // 没写过按类型给默认描述),所以三处看到的用途永远一致。
888
- const catalog = new Map()
889
- try {
890
- if (typeof memory.scopeCatalog === 'function') {
891
- for (const entry of memory.scopeCatalog(undefined) ?? []) {
892
- if (entry && typeof entry.scope === 'string') catalog.set(entry.scope, entry)
893
- }
894
- }
895
- } catch { /* 目录是增强:拿不到就只有名称与条数 */ }
896
- // 会话标题是尽力而为的增强,而且要读会话事件日志:只给最近活跃的前 N 个查,
897
- // 其余直接用「会话 <id 前 16 位>」。列表本身**始终**完整(不受这个上限影响)。
898
- const scopes = stats.map((s, index) => {
899
- const entry = catalog.get(s.scope)
900
- return {
901
- ...s,
902
- // 别名(项目 / 自定义作用域)也要带类型前缀;没有别名时退回按类型算的展示名。
903
- label: typeof s.name === 'string' && s.name !== ''
904
- ? scopeDisplayName(s.scope, s.name)
905
- : (index < TITLE_LOOKUP_LIMIT ? scopeLabel(ctx, s.scope) : fallbackScopeLabel(s.scope)),
906
- ...(entry !== undefined && typeof entry.description === 'string' && entry.description.trim() !== ''
907
- ? { description: entry.description.trim() }
908
- : {}),
909
- ...(entry !== undefined && typeof entry.origin === 'string' ? { origin: entry.origin } : {}),
910
- }
911
- })
912
- // 删光记录不等于作用域消失:目录里有用途、却没有记录的作用域也列出来。
913
- // 只收**有元数据**的(updatedAt 来自 scope-meta):默认三路里的 global / 当前项目
914
- // 也会出现在目录里,但它们未必真的落过盘,全塞进列表就是凭空多出两个作用域。
915
- // 别的会话的 session scope 不列 —— 它们的用途是空的,只会把清单变长。
916
- const seen = new Set(scopes.map((s) => s.scope))
917
- for (const [key, entry] of catalog) {
918
- if (seen.has(key) || key.startsWith('session:')) continue
919
- if (typeof entry.description !== 'string' || entry.description.trim() === '') continue
920
- if (!(typeof entry.updatedAt === 'number' && entry.updatedAt > 0)) continue
921
- scopes.push({
922
- scope: key,
923
- records: 0,
924
- pendingEmbeds: 0,
925
- updatedAt: entry.updatedAt,
926
- label: typeof entry.name === 'string' && entry.name !== ''
927
- ? scopeDisplayName(key, entry.name)
928
- : fallbackScopeLabel(key),
929
- description: entry.description.trim(),
930
- ...(typeof entry.origin === 'string' ? { origin: entry.origin } : {}),
931
- })
932
- }
933
- let embedServer = null
934
- // older providers have no lifecycle API — the panel simply omits the card
935
- try { embedServer = (await memory.embedServerStatus?.()) ?? null } catch { embedServer = null }
936
- let rules = null
937
- try { rules = typeof memory.ruleStats === 'function' ? memory.ruleStats() : null } catch { rules = null }
938
- writeJson(res, { ok: true, value: { scopes, embedServer, rules } })
939
- return
940
- }
941
- if (method === 'GET' && path === '/settings') {
942
- if (typeof memory.injectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
943
- writeJson(res, { ok: true, value: memory.injectSettings() })
944
- return
945
- }
946
- if (method === 'POST' && path === '/settings') {
947
- if (typeof memory.updateInjectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
948
- const body = await readJsonBody(req)
949
- writeJson(res, { ok: true, value: memory.updateInjectSettings(body) })
950
- return
951
- }
952
- if (method === 'POST' && path === '/create') {
953
- if (typeof memory.createRecord !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供新建接口(请升级 @restregular/dsh-memory)')
954
- const body = await readJsonBody(req)
955
- const record = await memory.createRecord({
956
- ...(typeof body.scope === 'string' ? { scope: body.scope } : {}),
957
- ...(typeof body.kind === 'string' ? { kind: body.kind } : {}),
958
- ...(typeof body.content === 'string' ? { content: body.content } : {}),
959
- ...(Array.isArray(body.tags) ? { tags: body.tags.map(String) } : {}),
960
- ...(typeof body.importance === 'number' ? { importance: body.importance } : {}),
961
- ...(typeof body.ttlMs === 'number' ? { ttlMs: body.ttlMs } : {}),
962
- ...(typeof body.expiresAt === 'number' ? { expiresAt: body.expiresAt } : {}),
963
- ...(Array.isArray(body.triggers) ? { triggers: body.triggers.map(String) } : {}),
964
- })
965
- console.log(`[dsh-memory-panel] 新建 ${record.kind} @ ${record.scope}: ${record.id}`)
966
- writeJson(res, { ok: true, value: { record } })
967
- return
968
- }
969
- if (method === 'GET' && path === '/export') {
970
- if (typeof memory.exportAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导出接口(请升级 @restregular/dsh-memory)')
971
- writeJson(res, { ok: true, value: memory.exportAll() })
972
- return
973
- }
974
- if (method === 'POST' && path === '/import') {
975
- if (typeof memory.importRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导入接口(请升级 @restregular/dsh-memory)')
976
- const body = await readJsonBody(req)
977
- const result = await memory.importRecords(body)
978
- console.log(`[dsh-memory-panel] 导入完成: 新增 ${result.imported} / 跳过 ${result.skipped} / 失败 ${result.rejected}`)
979
- writeJson(res, { ok: true, value: result })
980
- return
981
- }
982
- if (method === 'GET' && path === '/embed/status') { if (typeof memory.embedServerStatus !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
983
- writeJson(res, { ok: true, value: await memory.embedServerStatus() })
984
- return
985
- }
986
- if (method === 'POST' && path === '/embed/start') {
987
- if (typeof memory.startEmbedServerManually !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
988
- const state = await memory.startEmbedServerManually()
989
- console.log(`[dsh-memory-panel] 手动启动向量服务 -> ${state}`)
990
- writeJson(res, { ok: true, value: { state, ...(await memory.embedServerStatus()) } })
991
- return
992
- }
993
- if (method === 'POST' && path === '/embed/stop') {
994
- if (typeof memory.stopEmbedServerManually !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
995
- const out = memory.stopEmbedServerManually()
996
- console.log(`[dsh-memory-panel] 手动停止向量服务 -> ${out.reason}`)
997
- writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
998
- return
999
- }
1000
- if (method === 'GET' && path === '/embed/model') {
1001
- if (typeof memory.modelsReport !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供模型清单接口(请升级 @restregular/dsh-memory)')
1002
- writeJson(res, { ok: true, value: await memory.modelsReport(false) })
1003
- return
1004
- }
1005
- if (method === 'POST' && path === '/embed/model/refresh') {
1006
- if (typeof memory.modelsReport !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供模型清单接口(请升级 @restregular/dsh-memory)')
1007
- // 强制重探硬件:用户点了「重新检测」,缓存必须让路。
1008
- writeJson(res, { ok: true, value: await memory.modelsReport(true) })
1009
- return
1010
- }
1011
- if (method === 'POST' && path === '/embed/install') {
1012
- if (typeof memory.installVectorBackend !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供自动安装接口(请升级 @restregular/dsh-memory)')
1013
- // 面板可以带选择:预设 / 档位 / 风味,或者一个完全自定义的 GGUF。
1014
- const body = await readJsonBody(req)
1015
- const override = {}
1016
- if (typeof body.preset === 'string' && body.preset !== '') override.preset = body.preset
1017
- if (typeof body.variant === 'string' && body.variant !== '') override.variant = body.variant
1018
- if (typeof body.flavor === 'string' && body.flavor !== '') override.flavor = body.flavor
1019
- if (body.custom !== undefined && typeof body.custom === 'object' && body.custom !== null) {
1020
- const url = String(body.custom.url ?? '')
1021
- const dims = Number(body.custom.dims)
1022
- if (url === '' || !Number.isFinite(dims) || dims <= 0) throw new ApiError(400, 'CUSTOM_MODEL_INVALID', '自定义模型需要 url 与 dims')
1023
- override.custom = {
1024
- url,
1025
- dims,
1026
- ...(body.custom.file ? { file: String(body.custom.file) } : {}),
1027
- ...(body.custom.pooling ? { pooling: String(body.custom.pooling) } : {}),
1028
- }
1029
- }
1030
- memory.installVectorBackend(override)
1031
- console.log(`[dsh-memory-panel] 开始下载向量服务 ${JSON.stringify(override)}`)
1032
- writeJson(res, { ok: true, value: { ...(await memory.embedServerStatus()) } })
1033
- return
1034
- }
1035
- if (method === 'POST' && path === '/embed/install/cancel') {
1036
- if (typeof memory.cancelVectorInstall !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供自动安装接口(请升级 @restregular/dsh-memory)')
1037
- memory.cancelVectorInstall()
1038
- console.log('[dsh-memory-panel] 取消下载本地向量服务')
1039
- writeJson(res, { ok: true, value: { ...(await memory.embedServerStatus()) } })
1040
- return
1041
- }
1042
- if (method === 'POST' && path === '/embed/uninstall') {
1043
- if (typeof memory.uninstallVectorBackend !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供卸载接口(请升级 @restregular/dsh-memory)')
1044
- const out = memory.uninstallVectorBackend()
1045
- console.log(`[dsh-memory-panel] 卸载向量服务 -> ${out.reason},释放 ${(out.freedBytes / 1048576).toFixed(1)} MB`)
1046
- writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
1047
- return
1048
- }
1049
- if (method === 'POST' && path === '/embed/reindex') {
1050
- if (typeof memory.reindexAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量重建接口(请升级 @restregular/dsh-memory)')
1051
- // 同步部分只作废旧向量 + 排队,真正的重嵌在后台跑,不阻塞请求;进度看 /status 的待嵌入计数。
1052
- const result = memory.reindexAll() ?? {}
1053
- const total = typeof result.total === 'number' ? result.total : 0
1054
- console.log(`[dsh-memory-panel] 开始重建全部向量:${total} 条`)
1055
- writeJson(res, { ok: true, value: { scheduled: true, records: total } })
1056
- return
1057
- }
1058
- if (method === 'POST' && path === '/data/wipe') {
1059
- if (typeof memory.wipeAllRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供数据清理接口(请升级 @restregular/dsh-memory)')
1060
- const body = await readJsonBody(req)
1061
- // Deleting everything is irreversible: require the caller to say so out
1062
- // loud, not just to click a button.
1063
- if (String(body.confirm ?? '') !== 'delete') throw new ApiError(400, 'CONFIRM_REQUIRED', '需要 confirm: "delete" 才执行删除')
1064
- const out = memory.wipeAllRecords()
1065
- console.log(`[dsh-memory-panel] 清空记忆数据 -> ${out.removed} 条 / ${out.scopes.length} 个作用域`)
1066
- writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
1067
- return
1068
- }
1069
- if (method === 'GET' && path === '/records') {
1070
- const rawScope = url.searchParams.get('scope')
1071
- const query = (url.searchParams.get('q') ?? '').trim().toLowerCase()
1072
- const idQuery = (url.searchParams.get('id') ?? '').trim()
1073
- // scope 先过同一套规范化:非法 → 400(而不是当成一个陌生 scope 去建文件);
1074
- // 合法但不存在的 scope → 空列表。`peek`/`peekScope`,**绝不通过 store.scope() 创建**。
1075
- const stores = selectedStores(store, resolveScopeSelection(memory, rawScope))
1076
- let records = []
1077
- for (const s of stores) records.push(...collectScope(s))
1078
- if (query) {
1079
- records = records.filter((r) =>
1080
- r.content.toLowerCase().includes(query)
1081
- || r.kind.toLowerCase().includes(query)
1082
- || r.tags.some((t) => t.toLowerCase().includes(query)))
1083
- }
1084
- if (idQuery) {
1085
- records = records.filter((r) => r.id === idQuery || r.id.startsWith(idQuery))
1086
- }
1087
- writeJson(res, { ok: true, value: { records } })
1088
- return
1089
- }
1090
- // 记录页的「语义检索」:和 memory_search 同一套召回排序(向量 + 词法 + 可选重排),
1091
- // 由 provider 的 searchForPanel 执行 —— 只读、不写访问计数,并报告向量通道是否
1092
- // 真的参与,面板据此如实标注「语义排序」还是「退回关键词」。
1093
- if (method === 'GET' && path === '/search') {
1094
- const text = (url.searchParams.get('q') ?? '').trim()
1095
- if (text === '') throw new ApiError(400, 'QUERY_EMPTY', '搜索内容不能为空')
1096
- let topK = 20
1097
- const rawTopK = (url.searchParams.get('topK') ?? '').trim()
1098
- if (rawTopK !== '') {
1099
- if (!/^\d+$/.test(rawTopK)) throw new ApiError(400, 'QUERY_INVALID', 'topK 必须是 1..50 的整数')
1100
- topK = Number(rawTopK)
1101
- if (topK < 1 || topK > 50) throw new ApiError(400, 'QUERY_INVALID', 'topK 必须在 1..50 之间')
1102
- }
1103
- const scopes = selectedStores(store, resolveScopeSelection(memory, url.searchParams.get('scope')))
1104
- const keys = scopes.map((s) => s.scope)
1105
- // 空集合不能交给旧 provider 的 search():它会退回"默认项目 + global",
1106
- // 等于点了一个不存在的 scope 却搜出别的 scope 的记录。
1107
- if (keys.length === 0) {
1108
- writeJson(res, { ok: true, value: { hits: [], mode: 'lexical', reason: 'no-records', embedded: 0, total: 0 } })
1109
- return
1110
- }
1111
- const totalRecords = scopes.reduce((n, s) => n + s.records.size, 0)
1112
- const wireHit = (hit) => {
1113
- const scopeStore = store.peek(hit.record.scope)
1114
- let supersededBy = null
1115
- if (scopeStore !== undefined) {
1116
- for (const other of scopeStore.records.values()) {
1117
- if (other.supersedes === hit.record.id) { supersededBy = other.id; break }
1118
- }
1119
- }
1120
- const record = wireRecord(
1121
- hit.record,
1122
- scopeStore ?? { embedPending: new Map(), vectors: new Map() },
1123
- supersededBy,
1124
- )
1125
- return typeof hit.score === 'number' ? { ...record, score: hit.score } : record
1126
- }
1127
- let result
1128
- if (typeof memory.searchForPanel === 'function') {
1129
- result = await memory.searchForPanel({ text, scopes: keys, topK })
1130
- } else if (typeof memory.search === 'function') {
1131
- // 旧 provider 没有面板专用入口:退回通用检索(会写访问计数),向量是否参与
1132
- // 只能按"有没有向量"来推断。
1133
- let embedded = 0
1134
- for (const s of scopes) embedded += s.vectors.size
1135
- const hits = await memory.search({ text, scopes: keys, topK })
1136
- result = {
1137
- hits,
1138
- mode: embedded > 0 ? 'vector' : 'lexical',
1139
- ...(embedded > 0 ? {} : { reason: 'no-vectors' }),
1140
- embedded,
1141
- total: totalRecords,
1142
- }
1143
- } else {
1144
- // 连检索接口都没有:退回 /records?q= 同口径的关键词过滤,面板不至于空转。
1145
- const lowercase = text.toLowerCase()
1146
- const hits = []
1147
- for (const s of scopes) {
1148
- for (const r of collectScope(s)) {
1149
- if (r.content.toLowerCase().includes(lowercase)
1150
- || r.kind.toLowerCase().includes(lowercase)
1151
- || r.tags.some((t) => t.toLowerCase().includes(lowercase))) hits.push({ record: r })
1152
- }
1153
- }
1154
- result = { hits: hits.slice(0, topK), mode: 'lexical', reason: 'provider-lexical', embedded: 0, total: totalRecords }
1155
- }
1156
- writeJson(res, {
1157
- ok: true,
1158
- value: {
1159
- hits: result.hits.slice(0, topK).map(wireHit),
1160
- mode: result.mode,
1161
- ...(result.reason !== undefined ? { reason: result.reason } : {}),
1162
- embedded: result.embedded ?? 0,
1163
- total: result.total ?? totalRecords,
1164
- },
1165
- })
1166
- return
1167
- }
1168
- if (method === 'POST' && path === '/update') {
1169
- const body = await readJsonBody(req)
1170
- const id = String(body.id ?? '')
1171
- // 0.23.0:编辑 = 新建一条修正版,旧记录不原地修改。旧 provider 没有
1172
- // reviseRecord 时才退回原来的原地编辑,避免版本错配直接报错。
1173
- if (typeof memory.reviseRecord === 'function') {
1174
- const input = { id }
1175
- if (body.content !== undefined) input.content = String(body.content)
1176
- if (body.kind !== undefined) input.kind = String(body.kind)
1177
- if (body.importance !== undefined) input.importance = Number(body.importance)
1178
- if (body.tags !== undefined) input.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
1179
- if (body.triggers !== undefined) input.triggers = Array.isArray(body.triggers) ? body.triggers.map(String) : []
1180
- if (body.expiredAt === null) input.expiresAt = null
1181
- else if (typeof body.expiresAt === 'number') input.expiresAt = body.expiresAt
1182
- else if (typeof body.ttlMs === 'number' && body.ttlMs > 0) input.ttlMs = body.ttlMs
1183
- const { record, superseded } = await memory.reviseRecord(input)
1184
- const scopeStore = store.peek(record.scope) ?? { embedPending: new Map(), vectors: new Map() }
1185
- let supersededBy = null
1186
- for (const other of scopeStore.records.values()) {
1187
- if (other.supersedes === record.id) { supersededBy = other.id; break }
1188
- }
1189
- console.log(`[dsh-memory-panel] 修正记忆 ${superseded} -> ${record.id}`)
1190
- writeJson(res, { ok: true, value: { record: wireRecord(record, scopeStore, supersededBy), superseded } })
1191
- return
1192
- }
1193
- let target = null
1194
- for (const s of store.allScopes()) {
1195
- const rec = s.records.get(id)
1196
- if (rec) { target = { s, rec }; break }
1197
- }
1198
- if (!target) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${id}`)
1199
- const { s, rec } = target
1200
- let reindex = false
1201
- if (body.content !== undefined) {
1202
- const content = String(body.content)
1203
- if (!content.trim()) throw new ApiError(400, 'CONTENT_EMPTY', 'content 不能为空')
1204
- if (content !== rec.content) {
1205
- rec.content = content
1206
- // 旧向量作废:内存 + 磁盘一起丢掉(vectorsDirty),再排队重建。
1207
- // 只删内存不标 dirty 的话,重启后 load 会看到旧向量、把它当成"已嵌入"。
1208
- s.vectors.delete(id)
1209
- s.vectorsDirty = true
1210
- s.embedPending.add(id)
1211
- reindex = true
1212
- }
1213
- }
1214
- if (body.kind !== undefined) rec.kind = String(body.kind)
1215
- if (body.importance !== undefined) rec.importance = Math.min(1, Math.max(0, Number(body.importance) || 0))
1216
- if (body.tags !== undefined) rec.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
1217
- if (body.triggers !== undefined) rec.triggers = Array.isArray(body.triggers) ? body.triggers.map(String) : []
1218
- if (body.supersededBy !== undefined) rec.supersedes = body.supersededBy === null ? undefined : String(body.supersededBy)
1219
- // 过期时间:null 清除;expiresAt 绝对时间优先;ttlMs 相对当前时间。
1220
- if (body.expiredAt === null) delete rec.expiredAt
1221
- else if (typeof body.expiresAt === 'number') rec.expiredAt = body.expiresAt
1222
- else if (typeof body.ttlMs === 'number' && body.ttlMs > 0) rec.expiredAt = Date.now() + body.ttlMs
1223
- rec.updatedAt = Date.now()
1224
- // 改动本身要进增量(flush 只落增量,不再整份快照覆盖);向量作废靠 vectorsDirty。
1225
- s.insert(rec)
1226
- store.scheduleFlush()
1227
- // 立即重建向量(不等 60s 的定时回填);失败就留在 pending 里由重试兜底。
1228
- if (reindex && typeof memory.reindexRecord === 'function') {
1229
- void memory.reindexRecord(rec.scope, id).catch(() => {})
1230
- }
1231
- writeJson(res, { ok: true, value: { record: wireRecord(rec, s) } })
1232
- return
1233
- }
1234
- if (method === 'POST' && path === '/delete') {
1235
- const body = await readJsonBody(req)
1236
- let removed = false
1237
- for (const s of store.allScopes()) {
1238
- if (s.records.has(String(body.id))) { removed = s.remove(String(body.id)); break }
1239
- }
1240
- if (!removed) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${body.id}`)
1241
- store.scheduleFlush()
1242
- writeJson(res, { ok: true, value: { removed: 1 } })
1243
- return
1244
- }
1245
- throw new ApiError(404, 'not_found', `unknown endpoint ${method} ${path}`)
1246
- } catch (error) {
1247
- ctx?.logger?.warn?.(error instanceof Error ? error : new Error(String(error)))
1248
- writeError(res, error)
1249
- }
1250
- }
1251
-
1252
- export const name = 'dsh-memory-panel'
1253
- /** 路由处理器(导出供测试直接调用:围栏、规范化、peek 行为都在这里)。 */
1254
- export { handle as handleRequest }
1255
- export function apply(ctx, config = {}) {
1256
- const routePath = String(config.route || '/memory/api').replace(/\/$/, '')
1257
- try {
1258
- // 动态注入(cordis ctx.inject):webServer 已就绪则立即回调,否则等它出现,
1259
- // 不阻塞 entry 激活,也绝不让缺服务变成 fiber FAILED(dsh-client-modules 同款)。
1260
- ctx.inject(['webServer'], (svcCtx) => {
1261
- try {
1262
- const webServer = svcCtx.get('webServer')
1263
- if (!webServer || typeof webServer.register !== 'function') {
1264
- console.log('[dsh-memory-panel] webServer 不可用,面板 API 不注册(记忆工具不受影响)')
1265
- return
1266
- }
1267
- webServer.register({
1268
- kind: 'prefix',
1269
- path: routePath,
1270
- // returning the promise is ignored by the http server but makes the
1271
- // handler awaitable in tests/host-sim
1272
- handler: (req, res) => Promise.resolve(handle(ctx, routePath, req, res))
1273
- .catch((error) => writeError(res, error)),
1274
- })
1275
- console.log(`[dsh-memory-panel] 路由已注册 ${routePath}`)
1276
- } catch (error) {
1277
- console.log('[dsh-memory-panel] 路由注册失败(可能已存在,复用):', error?.message)
1278
- }
1279
- })
1280
- } catch (error) {
1281
- // 铁律:面板绝不允许把异常抛回 cordis(desktop fail-loud 会拖垮整个启动)
1282
- console.error('[dsh-memory-panel] apply 意外失败(已吞掉,不影响启动):', error?.message)
1283
- }
1284
- }
1
+ /**
2
+ * dsh-memory-panel — 服务端(entry)。
3
+ *
4
+ * 架构照抄 dsh-meme 的铁律(2026-10-10 crash 的教训):
5
+ * - 不导出 inject:一切服务 ctx.get() 被动获取,缺谁就降级跳过,
6
+ * 绝不让 fiber 进入 FAILED(desktop fail-loud,一个 entry 失败=整个应用起不来);
7
+ * - 路由注册 try/catch:冲突则复用/记日志,不抛;
8
+ * - apply 整体兜底 catch:任何意外都不允许向外抛。
9
+ *
10
+ * 提供管理员 API(前缀路由 /memory/api):
11
+ * GET /status 各 scope 记录数 + 待嵌入数 + 展示标签 + 用途描述(0.28.0)
12
+ * POST /scope-meta {scope, description?, name?} 编辑作用域用途 / 别名(0.29.0)
13
+ * GET /records ?scope=&q= 枚举/过滤记录
14
+ * GET /search ?scope=&q=&topK= 语义检索(向量 + 词法,provider 排序)
15
+ * POST /update {id, content?, kind?, importance?, tags?, triggers?, expiresAt?/ttlMs?}
16
+ * → 新建一条修正版(supersedes=id),旧记录保留(0.23.0)
17
+ * POST /delete {id}
18
+ * scope 惰性加载是同步的(store.peek(),**读路径不创建**),无需 ready 门。内容编辑会作废旧
19
+ * 向量并加入 embedPending,由 provider 的回填队列重新嵌入。
20
+ *
21
+ * 安全(每个路由都过 refuseRequest,见下):
22
+ * 注册在裸 webServer 上的路由**既不在宿主的 /api 围栏之后,也不在浏览器登录
23
+ * 之后** —— 宿主的围栏是一个给别的路由主动调用的服务方法(connection.requestRejection),
24
+ * 不是自动套上的中间件(dsh-market #603 的结论:裸 webServer 路由在登录开启时
25
+ * 可被无 session 调用 = 任意代码执行)。这里的读接口能读出全部记忆,写接口能改写、
26
+ * 删除、清空,还能拉起/卸载向量服务,所以必须自己问一次。
27
+ */
28
+ // scope 规范化与 provider 共用同一份实现。路径按**源码树位置**写:构建脚本的改写表
29
+ // 会把它落成产物里的 `../provider/scope.js`(`lib/panel.js` → `lib/provider/scope.js`),
30
+ // 在源码树里同一路径直接命中 source/memory-local/src —— 测试与真实加载都能解析。
31
+ import { normalizeScopeInput, resolveCurrentScopes, scopeDisplayName, sessionShortId } from './provider/scope.js'
32
+
33
+
34
+ function writeJson(res, body, status = 200) {
35
+ try {
36
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
37
+ res.end(JSON.stringify(body))
38
+ } catch { /* 客户端已断开 */ }
39
+ }
40
+
41
+ /** provider 侧的"调用方输入有问题"错误码 → 400;其余未标注的仍算 500。 */
42
+ const CLIENT_ERROR_CODES = new Set([
43
+ 'SCOPE_INVALID', 'SCOPE_DISABLED', 'CONTENT_EMPTY', 'CONTENT_TOO_LONG',
44
+ 'SECRET_DETECTED', 'IMPORT_INVALID', 'IMPORT_TOO_LARGE', 'KIND_INVALID',
45
+ 'QUERY_EMPTY', 'QUERY_INVALID', 'SESSION_REQUIRED', 'SCOPE_EMPTY', 'SCOPE_NOT_VISIBLE',
46
+ // 0.29.0:作用域用途 / 别名的编辑错误(名字非法 / 重名 / 不支持 / 用途过长)
47
+ 'SCOPE_NAME_INVALID', 'SCOPE_NAME_TAKEN', 'SCOPE_NAME_UNSUPPORTED', 'SCOPE_DESCRIPTION_TOO_LONG',
48
+ ])
49
+
50
+ function writeError(res, error) {
51
+ const code = typeof error?.code === 'string' ? error.code : 'internal'
52
+ const status = Number(error?.status) || (CLIENT_ERROR_CODES.has(code) ? 400 : code === 'SCOPE_LIMIT' ? 409 : 500)
53
+ writeJson(res, { ok: false, error: { code, message: error?.message || String(error) } }, status)
54
+ }
55
+
56
+ class ApiError extends Error {
57
+ constructor(status, code, message) {
58
+ super(message)
59
+ this.status = status
60
+ this.code = code
61
+ }
62
+ }
63
+
64
+ /** 只认本机权威(loopback),没有宿主围栏时的兜底。 */
65
+ const LOOPBACK_AUTHORITY = /^(?:127(?:\.\d{1,3}){3}|\[::1\]|::1|localhost)(?::\d+)?$/i
66
+
67
+ /** 请求头里的 Host,小写归一;缺失返回空串。 */
68
+ function hostHeader(req) {
69
+ const value = req?.headers?.host
70
+ return typeof value === 'string' ? value.trim().toLowerCase() : ''
71
+ }
72
+
73
+ /** 部署自己声明的权威(宿主 connection 的 trustedHosts);拿不到就空数组。 */
74
+ function trustedAuthorities(ctx) {
75
+ try {
76
+ const connection = ctx?.get?.('connection')
77
+ return Array.isArray(connection?.trustedHosts)
78
+ ? connection.trustedHosts.filter((entry) => typeof entry === 'string').map((entry) => entry.toLowerCase())
79
+ : []
80
+ } catch {
81
+ return []
82
+ }
83
+ }
84
+
85
+ /**
86
+ * 该不该拒绝这个请求。
87
+ *
88
+ * 两层,顺序有讲究:
89
+ * 1. 宿主发布了 connection.requestRejection 时**以它为准** —— 它同时含 Host/Origin
90
+ * 围栏(防 DNS rebinding 与跨站调用)与浏览器登录(login-token cookie)。
91
+ * 围栏自己抛错时返回 403:抛错意味着"什么都没放行",此处失败关闭,不能放行。
92
+ * 2. 旧宿主没有这个服务时自己来:Host 必须是 loopback 或宿主声明的权威,
93
+ * sec-fetch-site 不得是 cross-site,带 Origin 就必须与 Host 相等。
94
+ * (注意 content-type: text/plain 也能携带合法 JSON 体且不触发预检,
95
+ * 所以"要求 JSON 体"挡不住跨站 —— 承重的是 Host/Origin 这一层。)
96
+ *
97
+ * @returns 需要拒绝时返回状态码(401 未登录 / 403 不受信任),否则 undefined。
98
+ */
99
+ export function refuseRequest(ctx, req) {
100
+ let connection
101
+ try { connection = ctx?.get?.('connection') } catch { connection = undefined }
102
+ const gate = connection?.requestRejection
103
+ if (typeof gate === 'function') {
104
+ try {
105
+ const status = gate.call(connection, req)
106
+ return typeof status === 'number' ? status : undefined
107
+ } catch {
108
+ return 403
109
+ }
110
+ }
111
+ const host = hostHeader(req)
112
+ if (host === '') return 403
113
+ if (!LOOPBACK_AUTHORITY.test(host) && !trustedAuthorities(ctx).includes(host)) return 403
114
+ if (String(req?.headers?.['sec-fetch-site'] ?? '').toLowerCase() === 'cross-site') return 403
115
+ const origin = req?.headers?.origin
116
+ if (origin !== undefined) {
117
+ try {
118
+ if (new URL(String(origin)).host.toLowerCase() !== host) return 403
119
+ } catch {
120
+ return 403
121
+ }
122
+ }
123
+ return undefined
124
+ }
125
+
126
+ /** 拒绝时的响应体:给人话,不说内部概念。 */
127
+ function writeRefusal(res, status) {
128
+ writeJson(res, {
129
+ ok: false,
130
+ error: {
131
+ code: status === 401 ? 'LOGIN_REQUIRED' : 'UNTRUSTED_REQUEST',
132
+ message: status === 401
133
+ ? '需要先登录 DSH:请重新打开启动时打印的那个网址。'
134
+ : '这个请求来自不受信任的来源,已拒绝。',
135
+ },
136
+ }, status)
137
+ }
138
+
139
+ async function readJsonBody(req) {
140
+ const chunks = []
141
+ for await (const chunk of req) chunks.push(chunk)
142
+ const raw = Buffer.concat(chunks).toString('utf8')
143
+ return raw.length > 0 ? JSON.parse(raw) : {}
144
+ }
145
+
146
+ /**
147
+ * scope 键 → **不需要查宿主服务**的展示名(带类型前缀)。
148
+ * global → `global:全局`
149
+ * project:<cwd> → `project:<cwd>`
150
+ * session:<id> → `session:session-1a2b3c4d`(会话 id 前 16 位)
151
+ * 自定义 → `custom:<名字>`(自定义 scope 的键本身没有前缀,靠类型补)
152
+ *
153
+ * 细节都有两处坑:①会话 id 以 `session-` 开头(正好 8 个字符),取 8 位会让所有会话
154
+ * 作用域都显示成同一个名字,所以取 16 位;②自定义作用域与 global 的键天然不带前缀,
155
+ * 必须按类型补 —— 规则集中在 provider 的 scopeDisplayName。
156
+ */
157
+ function fallbackScopeLabel(scope) {
158
+ return scopeDisplayName(scope)
159
+ }
160
+
161
+ /**
162
+ * scope 键 → 展示名。在 fallback 之上多一步:会话 scope 尽力取会话标题
163
+ * (宿主 `sessionTitle` 服务的 `get(session)` → `{ title }`,见 @deepseek-ai/dsh-session-title)。
164
+ * 所有宿主服务访问都在 try/catch 里:面板绝不能因为拿不到标题而失败。
165
+ *
166
+ * 带标题时形如 `session:修层级(1a2b3c4d)` —— 类型前缀仍在最前面,名字部分换成标题。
167
+ */
168
+ function scopeLabel(ctx, scope) {
169
+ if (!scope.startsWith('session:')) return scopeDisplayName(scope)
170
+ const id = scope.slice('session:'.length)
171
+ const short = sessionShortId(id)
172
+ try {
173
+ const session = ctx?.get?.('sessions')?.get?.(id)
174
+ if (session !== undefined) {
175
+ const title = ctx.get('sessionTitle')?.get?.(session)?.title
176
+ if (typeof title === 'string' && title.length > 0) return scopeDisplayName(scope, `${title}(${short})`)
177
+ }
178
+ } catch { /* 标题是尽力而为 */ }
179
+ return scopeDisplayName(scope)
180
+ }
181
+
182
+ /** 会话 scope 查标题的上限:标题要读会话事件日志,scope 多了它就成了 /status 的大头。 */
183
+ const TITLE_LOOKUP_LIMIT = 50
184
+ /** discovery(读每个 scope 文件的第一条记录)结果的缓存时长。 */
185
+ const DISCOVER_CACHE_MS = 3000
186
+ /** 每个 memory 服务的发现缓存。面板看不到进程数,所以按服务实例各存一份。 */
187
+ const discoveryCache = new WeakMap()
188
+
189
+ /**
190
+ * 发现磁盘上的 scope,3 秒内只做一次。
191
+ * 面板每个请求都想要一份完整清单(别的进程写下的 scope 也要看得见),而 discovery 要
192
+ * 读每个文件的第一条记录 —— 没有缓存的话刷新一下就是一次全目录扫描。
193
+ */
194
+ function discoverScopes(memory, store) {
195
+ const now = Date.now()
196
+ const cached = discoveryCache.get(memory)
197
+ if (cached !== undefined && now - cached.at < DISCOVER_CACHE_MS) return
198
+ discoveryCache.set(memory, { at: now })
199
+ try {
200
+ if (typeof memory.discoverScopes === 'function') memory.discoverScopes()
201
+ else store.loadDiscovered?.()
202
+ } catch { /* discovery is best-effort */ }
203
+ }
204
+
205
+ function wireRecord(rec, scopeStore, supersededBy = null) {
206
+ return {
207
+ id: rec.id,
208
+ scope: rec.scope,
209
+ kind: rec.kind,
210
+ content: rec.content,
211
+ tags: rec.tags ?? [],
212
+ importance: rec.importance,
213
+ createdAt: rec.createdAt,
214
+ updatedAt: rec.updatedAt,
215
+ accessCount: rec.accessCount ?? 0,
216
+ supersededBy,
217
+ supersedes: rec.supersedes ?? null,
218
+ triggers: rec.triggers ?? [],
219
+ expiredAt: rec.expiredAt ?? null,
220
+ expired: rec.expiredAt !== undefined && rec.expiredAt < Date.now(),
221
+ embedded: !scopeStore.embedPending.has(rec.id) && scopeStore.vectors.has(rec.id),
222
+ }
223
+ }
224
+
225
+ function collectScope(scopeStore) {
226
+ // supersedes 是"新记录 → 旧记录"的指向;反查一次,给旧记录标上"已被修正"。
227
+ const correctedBy = new Map()
228
+ for (const rec of scopeStore.records.values()) {
229
+ if (rec.supersedes) correctedBy.set(rec.supersedes, rec.id)
230
+ }
231
+ const out = []
232
+ for (const rec of scopeStore.records.values()) out.push(wireRecord(rec, scopeStore, correctedBy.get(rec.id) ?? null))
233
+ return out.sort((a, b) => b.updatedAt - a.updatedAt)
234
+ }
235
+
236
+ /** 审计时间参数:Unix ms 或可解析的 ISO 字符串。 */
237
+ function parseAuditTime(value, name) {
238
+ if (value === null || value === undefined || value === '') return undefined
239
+ const numeric = Number(value)
240
+ if (Number.isFinite(numeric)) return numeric
241
+ const parsed = Date.parse(value)
242
+ if (Number.isFinite(parsed)) return parsed
243
+ throw new ApiError(400, 'AUDIT_QUERY_INVALID', `${name} 必须是毫秒时间戳或 ISO 时间`)
244
+ }
245
+
246
+ /** 面板查询参数 → audit sink 的 AuditListQuery。 */
247
+ const AUDIT_CHANNELS = new Set(['digest', 'recall', 'rules', 'rules_delta', 'policy', 'nudge', 'signal', 'lifecycle'])
248
+ const AUDIT_OUTCOMES = new Set(['success', 'failed', 'skipped', 'partial', 'unknown'])
249
+ function parseAuditQuery(url) {
250
+ const text = (name) => {
251
+ const value = url.searchParams.get(name)
252
+ const trimmed = value === null ? '' : value.trim()
253
+ return trimmed === '' ? undefined : trimmed
254
+ }
255
+ const limitRaw = text('limit')
256
+ let limit
257
+ if (limitRaw !== undefined) {
258
+ if (!/^\d+$/.test(limitRaw)) throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'limit 必须是 1..200 的整数')
259
+ limit = Number(limitRaw)
260
+ if (limit < 1 || limit > 200) throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'limit 必须在 1..200 之间')
261
+ }
262
+ const cursor = text('cursor')
263
+ if (cursor !== undefined && !/^\d+$/.test(cursor)) {
264
+ throw new ApiError(400, 'AUDIT_CURSOR_INVALID', 'cursor 必须是 seq 数字')
265
+ }
266
+ const channel = text('channel')
267
+ if (channel !== undefined && !AUDIT_CHANNELS.has(channel)) {
268
+ throw new ApiError(400, 'AUDIT_QUERY_INVALID', `未知 channel: ${channel}`)
269
+ }
270
+ const outcome = text('outcome')
271
+ if (outcome !== undefined && !AUDIT_OUTCOMES.has(outcome)) {
272
+ throw new ApiError(400, 'AUDIT_QUERY_INVALID', `未知 outcome: ${outcome}`)
273
+ }
274
+ const since = parseAuditTime(text('since'), 'since')
275
+ const until = parseAuditTime(text('until'), 'until')
276
+ if (since !== undefined && until !== undefined && since > until) {
277
+ throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'since 不能晚于 until')
278
+ }
279
+ return {
280
+ ...(text('session') !== undefined ? { sessionId: text('session') } : {}),
281
+ ...(text('trace') !== undefined ? { traceId: text('trace') } : {}),
282
+ ...(text('operation') !== undefined ? { operationId: text('operation') } : {}),
283
+ ...(text('memory') !== undefined ? { memoryId: text('memory') } : {}),
284
+ ...(channel !== undefined ? { channel } : {}),
285
+ ...(text('trigger') !== undefined ? { trigger: text('trigger') } : {}),
286
+ ...(outcome !== undefined ? { outcome } : {}),
287
+ ...(url.searchParams.get('problem') === '1' ? { problem: true } : {}),
288
+ ...(since !== undefined ? { since } : {}),
289
+ ...(until !== undefined ? { until } : {}),
290
+ ...(limit !== undefined ? { limit } : {}),
291
+ ...(cursor !== undefined ? { cursor } : {}),
292
+ }
293
+ }
294
+
295
+ function publicAuditQuery(query) {
296
+ return {
297
+ ...(query.sessionId !== undefined ? { sessionId: query.sessionId } : {}),
298
+ ...(query.traceId !== undefined ? { traceId: query.traceId } : {}),
299
+ ...(query.operationId !== undefined ? { operationId: query.operationId } : {}),
300
+ ...(query.memoryId !== undefined ? { memoryId: query.memoryId } : {}),
301
+ ...(query.channel !== undefined ? { channel: query.channel } : {}),
302
+ ...(query.trigger !== undefined ? { trigger: query.trigger } : {}),
303
+ ...(query.outcome !== undefined ? { outcome: query.outcome } : {}),
304
+ ...(query.problem === true ? { problem: true } : {}),
305
+ ...(query.since !== undefined ? { since: query.since } : {}),
306
+ ...(query.until !== undefined ? { until: query.until } : {}),
307
+ limit: query.limit ?? 50,
308
+ ...(query.cursor !== undefined ? { cursor: query.cursor } : {}),
309
+ scope: query.sessionId !== undefined ? 'session' : 'all',
310
+ }
311
+ }
312
+
313
+ function emptyAuditStats() {
314
+ return {
315
+ entries: 0, capacity: 0, perSessionCapacity: 0, dropped: 0,
316
+ writeErrors: 0, persistence: 'memory',
317
+ }
318
+ }
319
+
320
+ function auditStats(memory) {
321
+ try {
322
+ const stats = typeof memory?.injectAuditStats === 'function' ? memory.injectAuditStats() : undefined
323
+ return stats && typeof stats === 'object' ? stats : emptyAuditStats()
324
+ } catch {
325
+ return { ...emptyAuditStats(), persistence: 'degraded' }
326
+ }
327
+ }
328
+
329
+ /** 旧 provider 只有 injectAudit(list) 时,在面板侧补最小过滤/分页。 */
330
+ function legacyAuditPage(memory, query) {
331
+ const all = (() => {
332
+ try { return typeof memory?.injectAudit === 'function' ? memory.injectAudit(query.sessionId) : [] } catch { return [] }
333
+ })()
334
+ const entries = Array.isArray(all) ? all : []
335
+ const filtered = entries.filter((entry) => {
336
+ if (!entry || typeof entry !== 'object') return false
337
+ if (query.channel !== undefined && entry.channel !== query.channel) return false
338
+ if (query.trigger !== undefined && entry.trigger !== query.trigger) return false
339
+ if (query.outcome !== undefined && entry.outcome !== query.outcome) return false
340
+ if (query.problem === true) {
341
+ const delivery = entry.delivery
342
+ const omitted = Array.isArray(entry.omitted) ? entry.omitted.length : 0
343
+ if (!(entry.outcome === 'failed' || entry.outcome === 'partial' || omitted > 0 || (delivery && delivery.status !== 'appended' && delivery.status !== 'unknown'))) return false
344
+ }
345
+ if (query.memoryId !== undefined) {
346
+ const ids = [
347
+ ...(entry.contentIds ?? []), ...(entry.hintIds ?? []),
348
+ ...((entry.selected && entry.selected.contentIds) ?? []),
349
+ ...((entry.omitted ?? []).map((item) => item.id)),
350
+ ]
351
+ if (!ids.includes(query.memoryId)) return false
352
+ }
353
+ if (query.since !== undefined && !(entry.at >= query.since)) return false
354
+ if (query.until !== undefined && !(entry.at <= query.until)) return false
355
+ return true
356
+ })
357
+ const limit = query.limit ?? 50
358
+ const start = query.cursor === undefined ? 0 : Number(query.cursor)
359
+ const page = filtered.slice(start, start + limit)
360
+ return {
361
+ entries: page,
362
+ total: filtered.length,
363
+ ...(start + limit < filtered.length ? { nextCursor: String(start + limit) } : {}),
364
+ stats: emptyAuditStats(),
365
+ }
366
+ }
367
+
368
+ /**
369
+ * 把一个审计条目的 turn/step 锚点解析成轨迹可直接聚焦的 tool call id。
370
+ *
371
+ * Trajectory 的深链只接受 callId(它的 `toolCallFocus` 就是同一性映射),所以
372
+ * 没有 operationId 的审计事件(摘要/规则等按步注入)需要回到会话事件里找该步
373
+ * 的第一个 `tool/call`。找不到工具调用时不伪造:返回 null,由客户端退化成
374
+ * “只切到轨迹页”。
375
+ *
376
+ * @param ctx - Host 插件上下文。
377
+ * @param query - `{ sessionId, turn?, step?, callId? }`。
378
+ * @returns 锚点结果(永不抛错)。
379
+ */
380
+ export function findTrajectoryAnchor(ctx, query) {
381
+ const sessionId = typeof query?.sessionId === 'string' ? query.sessionId.trim() : ''
382
+ if (sessionId === '') return { callId: null, reason: 'session_required' }
383
+ let session
384
+ try { session = ctx?.get?.('sessions')?.get?.(sessionId) } catch { session = undefined }
385
+ if (session === undefined || typeof session?.ownEvents !== 'function') {
386
+ return { callId: null, reason: 'session_unavailable' }
387
+ }
388
+ const turn = typeof query.turn === 'number' ? query.turn : undefined
389
+ const step = typeof query.step === 'number' ? query.step : undefined
390
+ // 已有 callId 时校验它确实属于这个会话,避免把跨会话/伪造 id 送进轨迹。
391
+ const wanted = typeof query.callId === 'string' && query.callId !== '' ? query.callId : undefined
392
+ try {
393
+ for (const event of session.ownEvents()) {
394
+ if (event?.type !== 'tool/call') continue
395
+ const data = event.data ?? {}
396
+ if (turn !== undefined && data.turn !== turn) continue
397
+ if (step !== undefined && data.step !== step) continue
398
+ const callId = typeof data.callId === 'string' ? data.callId : undefined
399
+ if (callId === undefined) continue
400
+ if (wanted !== undefined && callId !== wanted) continue
401
+ return {
402
+ callId,
403
+ tool: typeof data.name === 'string' ? data.name : undefined,
404
+ turn: typeof data.turn === 'number' ? data.turn : undefined,
405
+ step: typeof data.step === 'number' ? data.step : undefined,
406
+ reason: wanted !== undefined ? 'operation' : 'step_tool',
407
+ }
408
+ }
409
+ } catch { /* 事件窗口读取失败:按找不到处理 */ }
410
+ return { callId: null, reason: wanted !== undefined ? 'operation_not_found' : 'no_tool_in_step' }
411
+ }
412
+
413
+ function auditPage(memory, query) { if (memory === undefined || memory === null) {
414
+ throw new ApiError(503, 'AUDIT_UNAVAILABLE', 'memory provider 未加载')
415
+ }
416
+ try {
417
+ if (typeof memory.injectAuditPage === 'function') {
418
+ const page = memory.injectAuditPage(query)
419
+ if (page && typeof page === 'object' && Array.isArray(page.entries)) {
420
+ return {
421
+ entries: page.entries,
422
+ total: typeof page.total === 'number' ? page.total : page.entries.length,
423
+ ...(typeof page.nextCursor === 'string' ? { nextCursor: page.nextCursor } : {}),
424
+ stats: page.stats && typeof page.stats === 'object' ? page.stats : emptyAuditStats(),
425
+ }
426
+ }
427
+ }
428
+ if (typeof memory.injectAudit === 'function') return legacyAuditPage(memory, query)
429
+ throw new ApiError(503, 'AUDIT_UNAVAILABLE', 'provider 未提供注入审计接口(请升级 @restregular/dsh-memory)')
430
+ } catch (error) {
431
+ if (error instanceof ApiError) throw error
432
+ if (error && typeof error.code === 'string' && error.code.startsWith('AUDIT_')) {
433
+ throw new ApiError(400, error.code, error.message || '审计查询参数无效')
434
+ }
435
+ throw error
436
+ }
437
+ }
438
+
439
+ /** 导出:按当前筛选循环取页(上限 200/页,最多 50 页 = 10000 条)。 */
440
+ function collectAuditEntries(memory, query) {
441
+ const out = []
442
+ let cursor
443
+ for (let i = 0; i < 50; i++) {
444
+ const page = auditPage(memory, { ...query, ...(cursor !== undefined ? { cursor } : {}), limit: 200 })
445
+ out.push(...page.entries)
446
+ if (page.nextCursor === undefined) break
447
+ cursor = page.nextCursor
448
+ }
449
+ return out
450
+ }
451
+
452
+ /** scope 选择 → 实际存在的 ScopeStore(读路径只用 peek,绝不通过 store.scope() 创建)。 */
453
+ function selectedStores(store, selection) {
454
+ if (selection === null) return store.allScopes()
455
+ return (Array.isArray(selection) ? selection : [selection])
456
+ .map((s) => store.peek(s))
457
+ .filter((s) => s !== undefined)
458
+ }
459
+
460
+ /**
461
+ * 面板的 scope 参数 → 要看的 scope 集合。
462
+ * null = 全部作用域
463
+ * string[] = 规范化后的 scope 键(current-session / current-project 由 provider 解析)
464
+ * 非法输入抛 400,合法但不存在的 scope 由 selectedStores 自然过滤成空集合。
465
+ */
466
+ function resolveScopeSelection(memory, rawScope) {
467
+ if (rawScope === null || rawScope === undefined || rawScope.trim() === '') return null
468
+ const normalized = normalizeScopeInput(rawScope)
469
+ if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
470
+ if (normalized.kind === 'all') return null
471
+ if (normalized.kind === 'current-session' || normalized.kind === 'current-project') {
472
+ // 面板不在某个 agent 里:按 provider 的读取集合解析('project' → 当前项目键);
473
+ // 解析不出会话时就退化为全部,而不是报错。
474
+ const refs = typeof memory.resolveReadScopes === 'function' ? memory.resolveReadScopes(undefined) : []
475
+ return refs.length > 0 ? refs : null
476
+ }
477
+ return normalized.scope ?? null
478
+ }
479
+
480
+ /** 面板已知的记忆类型(与工具的 kind enum 一致)。 */
481
+ /**
482
+ * 会话「记忆可见域」的完整快照:自己的覆盖 + 生效策略 + 可选范围目录。
483
+ *
484
+ * 自己的覆盖(null = 没设置)用于面板上的"恢复默认";effective 用于预选(子 Agent
485
+ * 会话会继承父会话的覆盖);defaults 是"没有显式覆盖时 Agent 实际会读的集合",
486
+ * 首次打开面板时按它预选,而不是显示成什么都没选。
487
+ *
488
+ * 0.19.1 起不再支持按记忆类型收窄:目录只返回 scope,不再返回 kinds。
489
+ */
490
+ function visibilityPayload(ctx, memory, sessionId) {
491
+ let session
492
+ try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
493
+ const agentLike = { session: session !== undefined ? session : { id: sessionId } }
494
+ const own = typeof memory.sessionVisibility === 'function' ? memory.sessionVisibility(sessionId) : null
495
+ let effective = null
496
+ let inherited = false
497
+ // 0.20.0 起 provider 永远给一份生效策略(没有显式覆盖时是默认策略)。
498
+ // source 告诉面板这份策略是"自己的 / 继承的 / 默认的"。
499
+ let source = own === null ? 'default' : 'explicit'
500
+ try {
501
+ if (typeof memory.visibilityPolicy === 'function') {
502
+ const policy = memory.visibilityPolicy(agentLike)
503
+ if (policy !== undefined && policy !== null) {
504
+ effective = policy
505
+ source = policy.source === 'explicit' || policy.source === 'inherited' || policy.source === 'default'
506
+ ? policy.source
507
+ : (own === null ? 'default' : 'explicit')
508
+ inherited = source === 'inherited'
509
+ }
510
+ }
511
+ } catch { /* 可见域是增强;拿不到就只返回自己的覆盖 */ }
512
+
513
+ let refs
514
+ try { if (session !== undefined) refs = resolveCurrentScopes({ session }) } catch { refs = undefined }
515
+ // 没有显式覆盖时,面板仍预选"当前默认读取集合"(会话 + 项目 + global + 工作区绑定),
516
+ // 让用户看到 Agent 现在实际能看到什么;保存后才变成显式覆盖。
517
+ let defaults = []
518
+ try {
519
+ const resolved = memory.resolveReadScopes?.(agentLike)
520
+ if (Array.isArray(resolved)) defaults = resolved
521
+ } catch { /* 降级为空 */ }
522
+
523
+ // 0.23.0:工作区级绑定 + 每个作用域的 read / write 状态。
524
+ let workspace = null
525
+ let bindings = []
526
+ try {
527
+ if (typeof memory.projectKeyFor === 'function') workspace = memory.projectKeyFor(agentLike)
528
+ if (typeof memory.workspaceBindings === 'function') {
529
+ const list = memory.workspaceBindings(agentLike)
530
+ if (Array.isArray(list)) bindings = list
531
+ }
532
+ } catch { /* 绑定是增强;拿不到就按"没有绑定"处理 */ }
533
+ const bound = new Set(bindings)
534
+ const rules = new Map()
535
+ for (const rule of (Array.isArray(effective?.scopes) ? effective.scopes : [])) {
536
+ if (rule && typeof rule.scope === 'string' && !rules.has(rule.scope)) rules.set(rule.scope, rule)
537
+ }
538
+
539
+ const stats = typeof memory.scopeStats === 'function' ? memory.scopeStats() : []
540
+ const byScope = new Map()
541
+ for (const item of Array.isArray(stats) ? stats : []) {
542
+ if (item && typeof item.scope === 'string') byScope.set(item.scope, { ...item })
543
+ }
544
+ // 即使还没有任何记录 / 宿主没给 sessions,也要能把默认集合里的 scope 勾出来。
545
+ const ensure = (scope) => {
546
+ if (typeof scope === 'string' && scope !== '' && !byScope.has(scope)) {
547
+ byScope.set(scope, { scope, records: 0, pendingEmbeds: 0 })
548
+ }
549
+ }
550
+ const sessionScope = refs?.session ?? defaults.find((scope) => scope.startsWith('session:'))
551
+ const projectScope = refs?.project ?? defaults.find((scope) => scope.startsWith('project:'))
552
+ // 默认范围的**基础集合** = 会话 + 项目 + global。它们天然包含在默认范围里,
553
+ // 面板按「已绑定」展示且不可取消;工作区绑定只负责额外并入其它作用域。
554
+ let defaultScopes = []
555
+ try {
556
+ const list = typeof memory.defaultScopes === 'function' ? memory.defaultScopes(agentLike) : undefined
557
+ if (Array.isArray(list)) defaultScopes = list.filter((scope) => typeof scope === 'string' && scope !== '')
558
+ } catch { /* 旧 provider:退回下面的本地面包 */ }
559
+ if (defaultScopes.length === 0) {
560
+ defaultScopes = [sessionScope, projectScope, 'global'].filter((scope) => typeof scope === 'string' && scope !== '')
561
+ }
562
+ const defaultBound = new Set(defaultScopes)
563
+ ensure(sessionScope)
564
+ ensure(projectScope)
565
+ ensure('global')
566
+ for (const scope of defaults) ensure(scope)
567
+ for (const scope of bindings) ensure(scope)
568
+ const rank = (scope) => scope === sessionScope ? 0 : scope === projectScope ? 1 : scope === 'global' ? 2 : 3
569
+ const scopes = [...byScope.values()]
570
+ .sort((a, b) => rank(a.scope) - rank(b.scope) || String(a.scope).localeCompare(String(b.scope)))
571
+ .map((item) => {
572
+ const rule = rules.get(item.scope)
573
+ return {
574
+ ...item,
575
+ // 别名也带类型前缀:项目别名 → `project:<别名>`,自定义 → `custom:<别名>`。
576
+ label: typeof item.name === 'string' && item.name !== ''
577
+ ? scopeDisplayName(item.scope, item.name)
578
+ : scopeLabel(ctx, item.scope),
579
+ read: rule === undefined ? true : rule.read !== false,
580
+ write: rule === undefined ? true : rule.write !== false,
581
+ // bound = 显式绑定或默认范围自带;defaultBound 告诉客户端这一项不能取消。
582
+ bound: bound.has(item.scope) || defaultBound.has(item.scope),
583
+ defaultBound: defaultBound.has(item.scope),
584
+ bindable: !String(item.scope).startsWith('session:') && !defaultBound.has(item.scope),
585
+ }
586
+ })
587
+ return {
588
+ sessionId,
589
+ override: own,
590
+ effective,
591
+ inherited,
592
+ source,
593
+ defaults,
594
+ defaultScopes,
595
+ workspace,
596
+ bindings: [...bound],
597
+ scopes,
598
+ }
599
+ }
600
+
601
+ /**
602
+ * 校验并规范化「工作区绑定」提交(0.25.13)。
603
+ *
604
+ * `/visibility` 与 `/bindings` 共用同一套规则:只接受**具体作用域键**
605
+ * (不接受 `all` / 当前项目 / 当前会话这类别名),会话作用域不能绑定到工作区
606
+ * (它只属于某一次会话),重复项去重保序。
607
+ *
608
+ * @param rawBindings - 客户端提交的绑定数组(任意值都按非法处理)。
609
+ * @returns 规范化后的作用域键数组。
610
+ */
611
+ function normalizeBindings(rawBindings) {
612
+ if (!Array.isArray(rawBindings)) throw new ApiError(400, 'SCOPE_INVALID', 'bindings 必须是字符串数组')
613
+ const bindings = []
614
+ for (const raw of rawBindings) {
615
+ if (typeof raw !== 'string' || raw.trim() === '') throw new ApiError(400, 'SCOPE_INVALID', '绑定项必须是非空字符串')
616
+ const normalized = normalizeScopeInput(raw)
617
+ if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
618
+ if (normalized.kind === 'all' || normalized.kind === 'current-project' || normalized.kind === 'current-session' || normalized.scope === undefined) {
619
+ throw new ApiError(400, 'SCOPE_INVALID', `绑定必须是具体作用域键: ${JSON.stringify(raw)}`)
620
+ }
621
+ if (normalized.scope.startsWith('session:')) {
622
+ throw new ApiError(400, 'SCOPE_INVALID', '会话作用域不能绑定到工作区')
623
+ }
624
+ if (!bindings.includes(normalized.scope)) bindings.push(normalized.scope)
625
+ }
626
+ return bindings
627
+ }
628
+
629
+ /**
630
+ * 面板「记忆权限」的授权快照(0.25.0)。
631
+ *
632
+ * grants 由 Agent 通过 memory_scopes request 申请、用户批准产生;这里只暴露
633
+ * scope / 权限 / 授予时间,不返回任何记忆正文。`inherited` 表示这条授权属于父会话。
634
+ */
635
+ function grantsPayload(ctx, memory, sessionId) {
636
+ const list = []
637
+ let grants = []
638
+ try {
639
+ grants = typeof memory.sessionGrants === 'function' ? memory.sessionGrants(sessionId) : []
640
+ } catch { grants = [] }
641
+ for (const grant of Array.isArray(grants) ? grants : []) {
642
+ if (!grant || typeof grant.scope !== 'string' || grant.scope === '') continue
643
+ const permissions = Array.isArray(grant.permissions)
644
+ ? grant.permissions.filter((permission) => permission === 'read' || permission === 'write')
645
+ : []
646
+ if (permissions.length === 0) continue
647
+ const ownerSession = typeof grant.sessionId === 'string' && grant.sessionId !== '' ? grant.sessionId : sessionId
648
+ list.push({
649
+ id: typeof grant.id === 'string' ? grant.id : '',
650
+ scope: grant.scope,
651
+ label: scopeLabel(ctx, grant.scope),
652
+ permissions,
653
+ grantedAt: typeof grant.grantedAt === 'number' ? grant.grantedAt : 0,
654
+ ownerSession,
655
+ inherited: ownerSession !== sessionId,
656
+ })
657
+ }
658
+ list.sort((a, b) => a.grantedAt - b.grantedAt || a.scope.localeCompare(b.scope))
659
+ return { sessionId, grants: list }
660
+ }
661
+
662
+ async function handle(ctx, routePath, req, res) {
663
+ const url = new URL(req.url ?? '/', 'http://dsh.local')
664
+ const path = url.pathname.slice(routePath.length) || '/'
665
+ const method = req.method ?? 'GET'
666
+ // 围栏在最前面:任何路由(读也一样)都先过宿主,再谈记忆。
667
+ const refused = refuseRequest(ctx, req)
668
+ if (refused !== undefined) {
669
+ writeRefusal(res, refused)
670
+ return
671
+ }
672
+ try {
673
+ const memory = ctx.get('memory')
674
+ // 审计路由只依赖注入半边挂载的 sink,不依赖记忆 store;先于 store 检查。
675
+ if (method === 'GET' && path === '/audit') {
676
+ const query = parseAuditQuery(url)
677
+ const value = auditPage(memory, query)
678
+ writeJson(res, { ok: true, value: { ...value, query: publicAuditQuery(query) } })
679
+ return
680
+ }
681
+ if (method === 'GET' && path === '/audit/stats') {
682
+ writeJson(res, { ok: true, value: auditStats(memory) })
683
+ return
684
+ }
685
+ if (method === 'GET' && path === '/anchor') {
686
+ const numeric = (name) => {
687
+ const raw = url.searchParams.get(name)
688
+ if (raw === null || raw.trim() === '') return undefined
689
+ if (!/^-?\d+$/.test(raw.trim())) throw new ApiError(400, 'ANCHOR_QUERY_INVALID', `${name} 必须是整数`)
690
+ return Number(raw)
691
+ }
692
+ const query = {
693
+ sessionId: url.searchParams.get('session') ?? '',
694
+ turn: numeric('turn'),
695
+ step: numeric('step'),
696
+ callId: url.searchParams.get('callId') ?? undefined,
697
+ }
698
+ writeJson(res, { ok: true, value: findTrajectoryAnchor(ctx, query) })
699
+ return
700
+ }
701
+ if (method === 'GET' && path === '/audit/export') {
702
+ const query = parseAuditQuery(url)
703
+ const format = url.searchParams.get('format') === 'jsonl' ? 'jsonl' : 'json'
704
+ const entries = collectAuditEntries(memory, query)
705
+ const body = format === 'jsonl'
706
+ ? entries.map((entry) => JSON.stringify(entry)).join('\n') + (entries.length > 0 ? '\n' : '')
707
+ : JSON.stringify({
708
+ schemaVersion: 2,
709
+ exportedAt: Date.now(),
710
+ query: publicAuditQuery(query),
711
+ count: entries.length,
712
+ entries,
713
+ }, null, 2) + '\n'
714
+ try {
715
+ res.writeHead(200, {
716
+ 'content-type': format === 'jsonl' ? 'application/x-ndjson; charset=utf-8' : 'application/json; charset=utf-8',
717
+ 'content-disposition': `attachment; filename="dsh-memory-audit.${format === 'jsonl' ? 'jsonl' : 'json'}"`,
718
+ 'cache-control': 'no-store',
719
+ })
720
+ res.end(body)
721
+ } catch { /* client disconnected */ }
722
+ return
723
+ }
724
+ if (!memory?.store) throw new ApiError(503, 'MEMORY_UNAVAILABLE', 'memory provider 未加载')
725
+ const store = memory.store
726
+ // Scopes are created lazily, so a fresh process only knows the ones it has
727
+ // touched. A management view must see everything written on disk (project
728
+ // memories from earlier sessions included) — best-effort discovery, cached.
729
+ discoverScopes(memory, store)
730
+
731
+ // 会话级「记忆可见范围」:输入框旁的按钮读写这一对接口。
732
+ if (method === 'GET' && path === '/visibility') {
733
+ if (typeof memory.sessionVisibility !== 'function') {
734
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
735
+ }
736
+ const sessionId = (url.searchParams.get('session') ?? '').trim()
737
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
738
+ writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
739
+ return
740
+ }
741
+ if (method === 'POST' && path === '/visibility') {
742
+ if (typeof memory.setSessionVisibility !== 'function') {
743
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
744
+ }
745
+ const body = await readJsonBody(req)
746
+ const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
747
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
748
+ let next = null
749
+ const rawConfig = body?.visibility
750
+ // 新协议:{ visibility: { scopes: [{ scope, read?, write? }], level } } | null
751
+ // 兼容 0.19.0 的 { scopes: [{ scope, kinds? }] } 与 0.18 的 { scopes: string[] }:
752
+ // 0.19.1 起不再限制记忆类型,提交里的 kinds 一律忽略。
753
+ const rawScopes = rawConfig !== null && rawConfig !== undefined && typeof rawConfig === 'object'
754
+ ? rawConfig.scopes
755
+ : body?.scopes
756
+ if (rawScopes !== null && rawScopes !== undefined) {
757
+ if (!Array.isArray(rawScopes)) throw new ApiError(400, 'SCOPE_INVALID', 'scopes 必须是数组或 null')
758
+ if (rawScopes.length === 0) throw new ApiError(400, 'SCOPE_EMPTY', '至少选择一个可见范围')
759
+ const scopes = []
760
+ for (const raw of rawScopes) {
761
+ const scopeRaw = typeof raw === 'string' ? raw : raw?.scope
762
+ if (typeof scopeRaw !== 'string' || scopeRaw.trim() === '') {
763
+ throw new ApiError(400, 'SCOPE_INVALID', 'scope 必须是非空字符串')
764
+ }
765
+ const normalized = normalizeScopeInput(scopeRaw)
766
+ if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
767
+ if (normalized.kind === 'all' || normalized.kind === 'current-project' || normalized.kind === 'current-session') {
768
+ throw new ApiError(400, 'SCOPE_INVALID', `可见范围必须是具体作用域键: ${JSON.stringify(scopeRaw)}`)
769
+ }
770
+ if (normalized.scope === undefined || scopes.some((item) => item.scope === normalized.scope)) continue
771
+ // 0.23.0:read / write 状态。省略 = 可读可写;只有显式 false 才落盘。
772
+ const read = typeof raw === 'object' && raw !== null && raw.read === false
773
+ const write = typeof raw === 'object' && raw !== null && raw.write === false
774
+ scopes.push({
775
+ scope: normalized.scope,
776
+ ...(read ? { read: false } : {}),
777
+ ...(write ? { write: false } : {}),
778
+ })
779
+ }
780
+ const levelRaw = rawConfig !== null && rawConfig !== undefined && typeof rawConfig === 'object' ? rawConfig.level : 'absolute'
781
+ const level = levelRaw === 'normal' || levelRaw === 'none' ? levelRaw : 'absolute'
782
+ next = { scopes, level }
783
+ }
784
+ // 工作区级绑定:省略 = 不改;数组 = 整体替换。与可见范围同一个保存动作提交。
785
+ const rawBindings = body?.bindings
786
+ if (rawBindings !== undefined) {
787
+ if (typeof memory.setWorkspaceBindings !== 'function') {
788
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供工作区绑定接口(请升级 @restregular/dsh-memory)')
789
+ }
790
+ const bindings = normalizeBindings(rawBindings)
791
+ let session
792
+ try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
793
+ memory.setWorkspaceBindings({ session: session !== undefined ? session : { id: sessionId } }, bindings)
794
+ }
795
+ memory.setSessionVisibility(sessionId, next)
796
+ writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
797
+ return
798
+ }
799
+
800
+ // 记忆权限浮窗的「绑定」按钮**单独保存**(0.25.13):绑定是工作区级设置
801
+ // (本工作区新会话的默认可见范围),和「勾选范围 / 可读可写」的草稿无关,
802
+ // 所以点一下立即落盘,不需要用户再点「保存」;也不注入上下文提示。
803
+ if (method === 'POST' && path === '/bindings') {
804
+ if (typeof memory.setWorkspaceBindings !== 'function') {
805
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供工作区绑定接口(请升级 @restregular/dsh-memory)')
806
+ }
807
+ const body = await readJsonBody(req)
808
+ const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
809
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
810
+ const bindings = normalizeBindings(body?.bindings)
811
+ let session
812
+ try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
813
+ const written = memory.setWorkspaceBindings({ session: session !== undefined ? session : { id: sessionId } }, bindings)
814
+ writeJson(res, {
815
+ ok: true,
816
+ value: { sessionId, bindings: Array.isArray(written) ? written : bindings },
817
+ })
818
+ return
819
+ }
820
+
821
+ // 普通限制下的范围外访问审批:客户端浮层轮询待审批,用户点「拒绝 / 允许一次」后回写。
822
+ // `summary=1` 是 0.25.14 新增的轻量口径:侧边栏阻塞提醒只需要 id + sessionId,
823
+ // 不带条目正文,避免全局 1.5s 轮询把审批内容一遍遍传一遍。
824
+ if (method === 'GET' && path === '/approvals') {
825
+ if (typeof memory.pendingVisibilityApprovals !== 'function') {
826
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供可见域审批接口(请升级 @restregular/dsh-memory)')
827
+ }
828
+ const sessionId = (url.searchParams.get('session') ?? '').trim()
829
+ const summary = url.searchParams.get('summary') === '1'
830
+ const approvals = summary && typeof memory.pendingVisibilityApprovalPresence === 'function'
831
+ ? memory.pendingVisibilityApprovalPresence(sessionId === '' ? undefined : sessionId)
832
+ : memory.pendingVisibilityApprovals(sessionId === '' ? undefined : sessionId)
833
+ writeJson(res, { ok: true, value: { approvals } })
834
+ return
835
+ }
836
+ if (method === 'POST' && path === '/approvals') {
837
+ if (typeof memory.answerVisibilityApproval !== 'function') {
838
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供可见域审批接口(请升级 @restregular/dsh-memory)')
839
+ }
840
+ const body = await readJsonBody(req)
841
+ const id = typeof body?.id === 'string' ? body.id.trim() : ''
842
+ if (id === '') throw new ApiError(400, 'APPROVAL_ID_REQUIRED', 'id 不能为空')
843
+ const outcome = body?.outcome === 'allowed-once' ? 'allowed-once' : body?.outcome === 'rejected' ? 'rejected' : ''
844
+ if (outcome === '') throw new ApiError(400, 'APPROVAL_OUTCOME_INVALID', 'outcome 必须是 allowed-once 或 rejected')
845
+ // 0.21.0:逐条允许。省略 = 全部允许;空数组 = 一条都不允许(按拒绝处理)。
846
+ const rawIds = body?.allowedIds
847
+ if (rawIds !== undefined && rawIds !== null && !Array.isArray(rawIds)) {
848
+ throw new ApiError(400, 'APPROVAL_IDS_INVALID', 'allowedIds 必须是字符串数组')
849
+ }
850
+ const allowedIds = Array.isArray(rawIds) ? rawIds.filter((value) => typeof value === 'string' && value !== '') : undefined
851
+ const answered = allowedIds === undefined
852
+ ? memory.answerVisibilityApproval(id, outcome)
853
+ : memory.answerVisibilityApproval(id, outcome, allowedIds)
854
+ writeJson(res, { ok: true, value: { answered } })
855
+ return
856
+ }
857
+
858
+ // 面板「记忆权限」:Agent 申请到的会话授权 + 撤销(0.25.0)。
859
+ if (method === 'GET' && path === '/grants') {
860
+ if (typeof memory.sessionGrants !== 'function') {
861
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话授权接口(请升级 @restregular/dsh-memory)')
862
+ }
863
+ const sessionId = (url.searchParams.get('session') ?? '').trim()
864
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
865
+ writeJson(res, { ok: true, value: grantsPayload(ctx, memory, sessionId) })
866
+ return
867
+ }
868
+ if (method === 'POST' && path === '/grants') {
869
+ if (typeof memory.revokeGrant !== 'function') {
870
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供授权撤销接口(请升级 @restregular/dsh-memory)')
871
+ }
872
+ const body = await readJsonBody(req)
873
+ const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
874
+ const id = typeof body?.id === 'string' ? body.id.trim() : ''
875
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
876
+ if (id === '') throw new ApiError(400, 'GRANT_ID_REQUIRED', 'id 不能为空')
877
+ const revoked = memory.revokeGrant(sessionId, id)
878
+ if (!revoked) throw new ApiError(404, 'GRANT_NOT_FOUND', '没有找到这条授权(可能已撤销或已过期)')
879
+ const view = typeof body?.view === 'string' && body.view.trim() !== '' ? body.view.trim() : sessionId
880
+ writeJson(res, { ok: true, value: grantsPayload(ctx, memory, view) })
881
+ return
882
+ }
883
+
884
+ if (method === 'GET' && path === '/status') {
885
+ const stats = typeof memory.scopeStats === 'function'
886
+ ? memory.scopeStats()
887
+ : store.allScopes().map((s) => ({ scope: s.scope, records: s.records.size, pendingEmbeds: s.embedPending.size }))
888
+ // 作用域用途(0.28.0):面板「记录 → 作用域」子标签页要展示的「这个域是干什么的」。
889
+ // 与 memory_scopes 目录 / memory_search 的范围外清单同源(scope-meta 手写优先,
890
+ // 没写过按类型给默认描述),所以三处看到的用途永远一致。
891
+ const catalog = new Map()
892
+ try {
893
+ if (typeof memory.scopeCatalog === 'function') {
894
+ for (const entry of memory.scopeCatalog(undefined) ?? []) {
895
+ if (entry && typeof entry.scope === 'string') catalog.set(entry.scope, entry)
896
+ }
897
+ }
898
+ } catch { /* 目录是增强:拿不到就只有名称与条数 */ }
899
+ // 会话标题是尽力而为的增强,而且要读会话事件日志:只给最近活跃的前 N 个查,
900
+ // 其余直接用「会话 <id 前 16 位>」。列表本身**始终**完整(不受这个上限影响)。
901
+ // 手写用途与默认描述的区分(0.29.0):面板要能编辑「用途」,就得知道现在显示的是
902
+ // 自己写的那句,还是按类型补的默认描述 —— 编辑框只预填手写的,否则一保存就把
903
+ // 默认文案固化成手写内容。`descriptionSource` 就是给这个用的。
904
+ const customDescriptionOf = (scope) => {
905
+ try {
906
+ const meta = typeof memory.scopeMeta === 'function' ? memory.scopeMeta(scope) : undefined
907
+ return typeof meta?.description === 'string' ? meta.description.trim() : ''
908
+ } catch {
909
+ return ''
910
+ }
911
+ }
912
+ const scopes = stats.map((s, index) => {
913
+ const entry = catalog.get(s.scope)
914
+ const custom = customDescriptionOf(s.scope)
915
+ return {
916
+ ...s,
917
+ // 别名(项目 / 自定义作用域)也要带类型前缀;没有别名时退回按类型算的展示名。
918
+ label: typeof s.name === 'string' && s.name !== ''
919
+ ? scopeDisplayName(s.scope, s.name)
920
+ : (index < TITLE_LOOKUP_LIMIT ? scopeLabel(ctx, s.scope) : fallbackScopeLabel(s.scope)),
921
+ ...(custom !== ''
922
+ ? { description: custom, descriptionSource: 'custom' }
923
+ : entry !== undefined && typeof entry.description === 'string' && entry.description.trim() !== ''
924
+ ? { description: entry.description.trim(), descriptionSource: 'default' }
925
+ : {}),
926
+ ...(entry !== undefined && typeof entry.origin === 'string' ? { origin: entry.origin } : {}),
927
+ }
928
+ })
929
+ // 删光记录不等于作用域消失:目录里有用途、却没有记录的作用域也列出来。
930
+ // 只收**有元数据**的(updatedAt 来自 scope-meta):默认三路里的 global / 当前项目
931
+ // 也会出现在目录里,但它们未必真的落过盘,全塞进列表就是凭空多出两个作用域。
932
+ // 别的会话的 session scope 不列 —— 它们的用途是空的,只会把清单变长。
933
+ const seen = new Set(scopes.map((s) => s.scope))
934
+ for (const [key, entry] of catalog) {
935
+ if (seen.has(key) || key.startsWith('session:')) continue
936
+ if (typeof entry.description !== 'string' || entry.description.trim() === '') continue
937
+ if (!(typeof entry.updatedAt === 'number' && entry.updatedAt > 0)) continue
938
+ scopes.push({
939
+ scope: key,
940
+ records: 0,
941
+ pendingEmbeds: 0,
942
+ updatedAt: entry.updatedAt,
943
+ ...(typeof entry.name === 'string' && entry.name !== '' ? { name: entry.name } : {}),
944
+ label: typeof entry.name === 'string' && entry.name !== ''
945
+ ? scopeDisplayName(key, entry.name)
946
+ : fallbackScopeLabel(key),
947
+ description: entry.description.trim(),
948
+ descriptionSource: customDescriptionOf(key) !== '' ? 'custom' : 'default',
949
+ ...(typeof entry.origin === 'string' ? { origin: entry.origin } : {}),
950
+ ...(entry.archived === true ? { archived: true } : {}),
951
+ })
952
+ }
953
+ let embedServer = null
954
+ // older providers have no lifecycle API — the panel simply omits the card
955
+ try { embedServer = (await memory.embedServerStatus?.()) ?? null } catch { embedServer = null }
956
+ let rules = null
957
+ try { rules = typeof memory.ruleStats === 'function' ? memory.ruleStats() : null } catch { rules = null }
958
+ writeJson(res, { ok: true, value: { scopes, embedServer, rules } })
959
+ return
960
+ }
961
+ if (method === 'POST' && path === '/scope-meta') {
962
+ // 用户编辑作用域的描述 / 别名(0.29.0)。面板是用户本人的操作,不带会话可见域;
963
+ // 但只允许改**目录里看得见**的作用域,免得手滑把用途写到一条永远读不到的元数据上。
964
+ if (typeof memory.describeScope !== 'function' && typeof memory.renameScope !== 'function') {
965
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供作用域编辑接口(请升级 @restregular/dsh-memory)')
966
+ }
967
+ const body = await readJsonBody(req)
968
+ const scope = typeof body?.scope === 'string' ? body.scope.trim() : ''
969
+ if (scope === '') throw new ApiError(400, 'SCOPE_INVALID', 'scope 不能为空')
970
+ const wantDescription = typeof body?.description === 'string'
971
+ const wantName = typeof body?.name === 'string'
972
+ if (!wantDescription && !wantName) {
973
+ throw new ApiError(400, 'SCOPE_NOTHING_TO_UPDATE', '至少提供 description(用途)或 name(别名)之一')
974
+ }
975
+ if (typeof memory.scopeCatalog === 'function') {
976
+ let known = false
977
+ try {
978
+ known = (memory.scopeCatalog(undefined) ?? []).some((item) => item?.scope === scope)
979
+ } catch { known = true /* 目录不可用时不拦:让 provider 自己校验 */ }
980
+ if (!known) throw new ApiError(404, 'SCOPE_UNKNOWN', `目录里没有作用域 ${scope}(可能刚被删除或改名)`)
981
+ }
982
+ let description
983
+ if (wantDescription) {
984
+ if (typeof memory.describeScope !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供作用域用途编辑接口')
985
+ description = memory.describeScope(scope, String(body.description), 'user').description
986
+ }
987
+ let name
988
+ if (wantName) {
989
+ if (typeof memory.renameScope !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供作用域别名编辑接口')
990
+ name = memory.renameScope(scope, String(body.name)).name ?? ''
991
+ }
992
+ writeJson(res, {
993
+ ok: true,
994
+ value: {
995
+ scope,
996
+ ...(wantDescription ? { description } : {}),
997
+ ...(wantName ? { name } : {}),
998
+ },
999
+ })
1000
+ return
1001
+ }
1002
+ if (method === 'GET' && path === '/settings') {
1003
+ if (typeof memory.injectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
1004
+ writeJson(res, { ok: true, value: memory.injectSettings() })
1005
+ return
1006
+ }
1007
+ if (method === 'POST' && path === '/settings') {
1008
+ if (typeof memory.updateInjectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
1009
+ const body = await readJsonBody(req)
1010
+ writeJson(res, { ok: true, value: memory.updateInjectSettings(body) })
1011
+ return
1012
+ }
1013
+ if (method === 'POST' && path === '/create') {
1014
+ if (typeof memory.createRecord !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供新建接口(请升级 @restregular/dsh-memory)')
1015
+ const body = await readJsonBody(req)
1016
+ const record = await memory.createRecord({
1017
+ ...(typeof body.scope === 'string' ? { scope: body.scope } : {}),
1018
+ ...(typeof body.kind === 'string' ? { kind: body.kind } : {}),
1019
+ ...(typeof body.content === 'string' ? { content: body.content } : {}),
1020
+ ...(Array.isArray(body.tags) ? { tags: body.tags.map(String) } : {}),
1021
+ ...(typeof body.importance === 'number' ? { importance: body.importance } : {}),
1022
+ ...(typeof body.ttlMs === 'number' ? { ttlMs: body.ttlMs } : {}),
1023
+ ...(typeof body.expiresAt === 'number' ? { expiresAt: body.expiresAt } : {}),
1024
+ ...(Array.isArray(body.triggers) ? { triggers: body.triggers.map(String) } : {}),
1025
+ })
1026
+ console.log(`[dsh-memory-panel] 新建 ${record.kind} @ ${record.scope}: ${record.id}`)
1027
+ writeJson(res, { ok: true, value: { record } })
1028
+ return
1029
+ }
1030
+ if (method === 'GET' && path === '/export') {
1031
+ if (typeof memory.exportAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导出接口(请升级 @restregular/dsh-memory)')
1032
+ writeJson(res, { ok: true, value: memory.exportAll() })
1033
+ return
1034
+ }
1035
+ if (method === 'POST' && path === '/import') {
1036
+ if (typeof memory.importRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导入接口(请升级 @restregular/dsh-memory)')
1037
+ const body = await readJsonBody(req)
1038
+ const result = await memory.importRecords(body)
1039
+ console.log(`[dsh-memory-panel] 导入完成: 新增 ${result.imported} / 跳过 ${result.skipped} / 失败 ${result.rejected}`)
1040
+ writeJson(res, { ok: true, value: result })
1041
+ return
1042
+ }
1043
+ if (method === 'GET' && path === '/embed/status') { if (typeof memory.embedServerStatus !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
1044
+ writeJson(res, { ok: true, value: await memory.embedServerStatus() })
1045
+ return
1046
+ }
1047
+ if (method === 'POST' && path === '/embed/start') {
1048
+ if (typeof memory.startEmbedServerManually !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
1049
+ const state = await memory.startEmbedServerManually()
1050
+ console.log(`[dsh-memory-panel] 手动启动向量服务 -> ${state}`)
1051
+ writeJson(res, { ok: true, value: { state, ...(await memory.embedServerStatus()) } })
1052
+ return
1053
+ }
1054
+ if (method === 'POST' && path === '/embed/stop') {
1055
+ if (typeof memory.stopEmbedServerManually !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
1056
+ const out = memory.stopEmbedServerManually()
1057
+ console.log(`[dsh-memory-panel] 手动停止向量服务 -> ${out.reason}`)
1058
+ writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
1059
+ return
1060
+ }
1061
+ if (method === 'GET' && path === '/embed/model') {
1062
+ if (typeof memory.modelsReport !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供模型清单接口(请升级 @restregular/dsh-memory)')
1063
+ writeJson(res, { ok: true, value: await memory.modelsReport(false) })
1064
+ return
1065
+ }
1066
+ if (method === 'POST' && path === '/embed/model/refresh') {
1067
+ if (typeof memory.modelsReport !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供模型清单接口(请升级 @restregular/dsh-memory)')
1068
+ // 强制重探硬件:用户点了「重新检测」,缓存必须让路。
1069
+ writeJson(res, { ok: true, value: await memory.modelsReport(true) })
1070
+ return
1071
+ }
1072
+ if (method === 'POST' && path === '/embed/install') {
1073
+ if (typeof memory.installVectorBackend !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供自动安装接口(请升级 @restregular/dsh-memory)')
1074
+ // 面板可以带选择:预设 / 档位 / 风味,或者一个完全自定义的 GGUF。
1075
+ const body = await readJsonBody(req)
1076
+ const override = {}
1077
+ if (typeof body.preset === 'string' && body.preset !== '') override.preset = body.preset
1078
+ if (typeof body.variant === 'string' && body.variant !== '') override.variant = body.variant
1079
+ if (typeof body.flavor === 'string' && body.flavor !== '') override.flavor = body.flavor
1080
+ if (body.custom !== undefined && typeof body.custom === 'object' && body.custom !== null) {
1081
+ const url = String(body.custom.url ?? '')
1082
+ const dims = Number(body.custom.dims)
1083
+ if (url === '' || !Number.isFinite(dims) || dims <= 0) throw new ApiError(400, 'CUSTOM_MODEL_INVALID', '自定义模型需要 url 与 dims')
1084
+ override.custom = {
1085
+ url,
1086
+ dims,
1087
+ ...(body.custom.file ? { file: String(body.custom.file) } : {}),
1088
+ ...(body.custom.pooling ? { pooling: String(body.custom.pooling) } : {}),
1089
+ }
1090
+ }
1091
+ memory.installVectorBackend(override)
1092
+ console.log(`[dsh-memory-panel] 开始下载向量服务 ${JSON.stringify(override)}`)
1093
+ writeJson(res, { ok: true, value: { ...(await memory.embedServerStatus()) } })
1094
+ return
1095
+ }
1096
+ if (method === 'POST' && path === '/embed/install/cancel') {
1097
+ if (typeof memory.cancelVectorInstall !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供自动安装接口(请升级 @restregular/dsh-memory)')
1098
+ memory.cancelVectorInstall()
1099
+ console.log('[dsh-memory-panel] 取消下载本地向量服务')
1100
+ writeJson(res, { ok: true, value: { ...(await memory.embedServerStatus()) } })
1101
+ return
1102
+ }
1103
+ if (method === 'POST' && path === '/embed/uninstall') {
1104
+ if (typeof memory.uninstallVectorBackend !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供卸载接口(请升级 @restregular/dsh-memory)')
1105
+ const out = memory.uninstallVectorBackend()
1106
+ console.log(`[dsh-memory-panel] 卸载向量服务 -> ${out.reason},释放 ${(out.freedBytes / 1048576).toFixed(1)} MB`)
1107
+ writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
1108
+ return
1109
+ }
1110
+ if (method === 'POST' && path === '/embed/reindex') {
1111
+ if (typeof memory.reindexAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量重建接口(请升级 @restregular/dsh-memory)')
1112
+ // 同步部分只作废旧向量 + 排队,真正的重嵌在后台跑,不阻塞请求;进度看 /status 的待嵌入计数。
1113
+ const result = memory.reindexAll() ?? {}
1114
+ const total = typeof result.total === 'number' ? result.total : 0
1115
+ console.log(`[dsh-memory-panel] 开始重建全部向量:${total} 条`)
1116
+ writeJson(res, { ok: true, value: { scheduled: true, records: total } })
1117
+ return
1118
+ }
1119
+ if (method === 'POST' && path === '/data/wipe') {
1120
+ if (typeof memory.wipeAllRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供数据清理接口(请升级 @restregular/dsh-memory)')
1121
+ const body = await readJsonBody(req)
1122
+ // Deleting everything is irreversible: require the caller to say so out
1123
+ // loud, not just to click a button.
1124
+ if (String(body.confirm ?? '') !== 'delete') throw new ApiError(400, 'CONFIRM_REQUIRED', '需要 confirm: "delete" 才执行删除')
1125
+ const out = memory.wipeAllRecords()
1126
+ console.log(`[dsh-memory-panel] 清空记忆数据 -> ${out.removed} 条 / ${out.scopes.length} 个作用域`)
1127
+ writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
1128
+ return
1129
+ }
1130
+ if (method === 'GET' && path === '/records') {
1131
+ const rawScope = url.searchParams.get('scope')
1132
+ const query = (url.searchParams.get('q') ?? '').trim().toLowerCase()
1133
+ const idQuery = (url.searchParams.get('id') ?? '').trim()
1134
+ // scope 先过同一套规范化:非法 → 400(而不是当成一个陌生 scope 去建文件);
1135
+ // 合法但不存在的 scope → 空列表。`peek`/`peekScope`,**绝不通过 store.scope() 创建**。
1136
+ const stores = selectedStores(store, resolveScopeSelection(memory, rawScope))
1137
+ let records = []
1138
+ for (const s of stores) records.push(...collectScope(s))
1139
+ if (query) {
1140
+ records = records.filter((r) =>
1141
+ r.content.toLowerCase().includes(query)
1142
+ || r.kind.toLowerCase().includes(query)
1143
+ || r.tags.some((t) => t.toLowerCase().includes(query)))
1144
+ }
1145
+ if (idQuery) {
1146
+ records = records.filter((r) => r.id === idQuery || r.id.startsWith(idQuery))
1147
+ }
1148
+ writeJson(res, { ok: true, value: { records } })
1149
+ return
1150
+ }
1151
+ // 记录页的「语义检索」:和 memory_search 同一套召回排序(向量 + 词法 + 可选重排),
1152
+ // 由 provider 的 searchForPanel 执行 —— 只读、不写访问计数,并报告向量通道是否
1153
+ // 真的参与,面板据此如实标注「语义排序」还是「退回关键词」。
1154
+ if (method === 'GET' && path === '/search') {
1155
+ const text = (url.searchParams.get('q') ?? '').trim()
1156
+ if (text === '') throw new ApiError(400, 'QUERY_EMPTY', '搜索内容不能为空')
1157
+ let topK = 20
1158
+ const rawTopK = (url.searchParams.get('topK') ?? '').trim()
1159
+ if (rawTopK !== '') {
1160
+ if (!/^\d+$/.test(rawTopK)) throw new ApiError(400, 'QUERY_INVALID', 'topK 必须是 1..50 的整数')
1161
+ topK = Number(rawTopK)
1162
+ if (topK < 1 || topK > 50) throw new ApiError(400, 'QUERY_INVALID', 'topK 必须在 1..50 之间')
1163
+ }
1164
+ const scopes = selectedStores(store, resolveScopeSelection(memory, url.searchParams.get('scope')))
1165
+ const keys = scopes.map((s) => s.scope)
1166
+ // 空集合不能交给旧 provider 的 search():它会退回"默认项目 + global",
1167
+ // 等于点了一个不存在的 scope 却搜出别的 scope 的记录。
1168
+ if (keys.length === 0) {
1169
+ writeJson(res, { ok: true, value: { hits: [], mode: 'lexical', reason: 'no-records', embedded: 0, total: 0 } })
1170
+ return
1171
+ }
1172
+ const totalRecords = scopes.reduce((n, s) => n + s.records.size, 0)
1173
+ const wireHit = (hit) => {
1174
+ const scopeStore = store.peek(hit.record.scope)
1175
+ let supersededBy = null
1176
+ if (scopeStore !== undefined) {
1177
+ for (const other of scopeStore.records.values()) {
1178
+ if (other.supersedes === hit.record.id) { supersededBy = other.id; break }
1179
+ }
1180
+ }
1181
+ const record = wireRecord(
1182
+ hit.record,
1183
+ scopeStore ?? { embedPending: new Map(), vectors: new Map() },
1184
+ supersededBy,
1185
+ )
1186
+ return typeof hit.score === 'number' ? { ...record, score: hit.score } : record
1187
+ }
1188
+ let result
1189
+ if (typeof memory.searchForPanel === 'function') {
1190
+ result = await memory.searchForPanel({ text, scopes: keys, topK })
1191
+ } else if (typeof memory.search === 'function') {
1192
+ // 旧 provider 没有面板专用入口:退回通用检索(会写访问计数),向量是否参与
1193
+ // 只能按"有没有向量"来推断。
1194
+ let embedded = 0
1195
+ for (const s of scopes) embedded += s.vectors.size
1196
+ const hits = await memory.search({ text, scopes: keys, topK })
1197
+ result = {
1198
+ hits,
1199
+ mode: embedded > 0 ? 'vector' : 'lexical',
1200
+ ...(embedded > 0 ? {} : { reason: 'no-vectors' }),
1201
+ embedded,
1202
+ total: totalRecords,
1203
+ }
1204
+ } else {
1205
+ // 连检索接口都没有:退回 /records?q= 同口径的关键词过滤,面板不至于空转。
1206
+ const lowercase = text.toLowerCase()
1207
+ const hits = []
1208
+ for (const s of scopes) {
1209
+ for (const r of collectScope(s)) {
1210
+ if (r.content.toLowerCase().includes(lowercase)
1211
+ || r.kind.toLowerCase().includes(lowercase)
1212
+ || r.tags.some((t) => t.toLowerCase().includes(lowercase))) hits.push({ record: r })
1213
+ }
1214
+ }
1215
+ result = { hits: hits.slice(0, topK), mode: 'lexical', reason: 'provider-lexical', embedded: 0, total: totalRecords }
1216
+ }
1217
+ writeJson(res, {
1218
+ ok: true,
1219
+ value: {
1220
+ hits: result.hits.slice(0, topK).map(wireHit),
1221
+ mode: result.mode,
1222
+ ...(result.reason !== undefined ? { reason: result.reason } : {}),
1223
+ embedded: result.embedded ?? 0,
1224
+ total: result.total ?? totalRecords,
1225
+ },
1226
+ })
1227
+ return
1228
+ }
1229
+ if (method === 'POST' && path === '/update') {
1230
+ const body = await readJsonBody(req)
1231
+ const id = String(body.id ?? '')
1232
+ // 0.23.0:编辑 = 新建一条修正版,旧记录不原地修改。旧 provider 没有
1233
+ // reviseRecord 时才退回原来的原地编辑,避免版本错配直接报错。
1234
+ if (typeof memory.reviseRecord === 'function') {
1235
+ const input = { id }
1236
+ if (body.content !== undefined) input.content = String(body.content)
1237
+ if (body.kind !== undefined) input.kind = String(body.kind)
1238
+ if (body.importance !== undefined) input.importance = Number(body.importance)
1239
+ if (body.tags !== undefined) input.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
1240
+ if (body.triggers !== undefined) input.triggers = Array.isArray(body.triggers) ? body.triggers.map(String) : []
1241
+ if (body.expiredAt === null) input.expiresAt = null
1242
+ else if (typeof body.expiresAt === 'number') input.expiresAt = body.expiresAt
1243
+ else if (typeof body.ttlMs === 'number' && body.ttlMs > 0) input.ttlMs = body.ttlMs
1244
+ const { record, superseded } = await memory.reviseRecord(input)
1245
+ const scopeStore = store.peek(record.scope) ?? { embedPending: new Map(), vectors: new Map() }
1246
+ let supersededBy = null
1247
+ for (const other of scopeStore.records.values()) {
1248
+ if (other.supersedes === record.id) { supersededBy = other.id; break }
1249
+ }
1250
+ console.log(`[dsh-memory-panel] 修正记忆 ${superseded} -> ${record.id}`)
1251
+ writeJson(res, { ok: true, value: { record: wireRecord(record, scopeStore, supersededBy), superseded } })
1252
+ return
1253
+ }
1254
+ let target = null
1255
+ for (const s of store.allScopes()) {
1256
+ const rec = s.records.get(id)
1257
+ if (rec) { target = { s, rec }; break }
1258
+ }
1259
+ if (!target) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${id}`)
1260
+ const { s, rec } = target
1261
+ let reindex = false
1262
+ if (body.content !== undefined) {
1263
+ const content = String(body.content)
1264
+ if (!content.trim()) throw new ApiError(400, 'CONTENT_EMPTY', 'content 不能为空')
1265
+ if (content !== rec.content) {
1266
+ rec.content = content
1267
+ // 旧向量作废:内存 + 磁盘一起丢掉(vectorsDirty),再排队重建。
1268
+ // 只删内存不标 dirty 的话,重启后 load 会看到旧向量、把它当成"已嵌入"。
1269
+ s.vectors.delete(id)
1270
+ s.vectorsDirty = true
1271
+ s.embedPending.add(id)
1272
+ reindex = true
1273
+ }
1274
+ }
1275
+ if (body.kind !== undefined) rec.kind = String(body.kind)
1276
+ if (body.importance !== undefined) rec.importance = Math.min(1, Math.max(0, Number(body.importance) || 0))
1277
+ if (body.tags !== undefined) rec.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
1278
+ if (body.triggers !== undefined) rec.triggers = Array.isArray(body.triggers) ? body.triggers.map(String) : []
1279
+ if (body.supersededBy !== undefined) rec.supersedes = body.supersededBy === null ? undefined : String(body.supersededBy)
1280
+ // 过期时间:null 清除;expiresAt 绝对时间优先;ttlMs 相对当前时间。
1281
+ if (body.expiredAt === null) delete rec.expiredAt
1282
+ else if (typeof body.expiresAt === 'number') rec.expiredAt = body.expiresAt
1283
+ else if (typeof body.ttlMs === 'number' && body.ttlMs > 0) rec.expiredAt = Date.now() + body.ttlMs
1284
+ rec.updatedAt = Date.now()
1285
+ // 改动本身要进增量(flush 只落增量,不再整份快照覆盖);向量作废靠 vectorsDirty。
1286
+ s.insert(rec)
1287
+ store.scheduleFlush()
1288
+ // 立即重建向量(不等 60s 的定时回填);失败就留在 pending 里由重试兜底。
1289
+ if (reindex && typeof memory.reindexRecord === 'function') {
1290
+ void memory.reindexRecord(rec.scope, id).catch(() => {})
1291
+ }
1292
+ writeJson(res, { ok: true, value: { record: wireRecord(rec, s) } })
1293
+ return
1294
+ }
1295
+ if (method === 'POST' && path === '/delete') {
1296
+ const body = await readJsonBody(req)
1297
+ let removed = false
1298
+ for (const s of store.allScopes()) {
1299
+ if (s.records.has(String(body.id))) { removed = s.remove(String(body.id)); break }
1300
+ }
1301
+ if (!removed) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${body.id}`)
1302
+ store.scheduleFlush()
1303
+ writeJson(res, { ok: true, value: { removed: 1 } })
1304
+ return
1305
+ }
1306
+ throw new ApiError(404, 'not_found', `unknown endpoint ${method} ${path}`)
1307
+ } catch (error) {
1308
+ ctx?.logger?.warn?.(error instanceof Error ? error : new Error(String(error)))
1309
+ writeError(res, error)
1310
+ }
1311
+ }
1312
+
1313
+ export const name = 'dsh-memory-panel'
1314
+ /** 路由处理器(导出供测试直接调用:围栏、规范化、peek 行为都在这里)。 */
1315
+ export { handle as handleRequest }
1316
+ export function apply(ctx, config = {}) {
1317
+ const routePath = String(config.route || '/memory/api').replace(/\/$/, '')
1318
+ try {
1319
+ // 动态注入(cordis ctx.inject):webServer 已就绪则立即回调,否则等它出现,
1320
+ // 不阻塞 entry 激活,也绝不让缺服务变成 fiber FAILED(dsh-client-modules 同款)。
1321
+ ctx.inject(['webServer'], (svcCtx) => {
1322
+ try {
1323
+ const webServer = svcCtx.get('webServer')
1324
+ if (!webServer || typeof webServer.register !== 'function') {
1325
+ console.log('[dsh-memory-panel] webServer 不可用,面板 API 不注册(记忆工具不受影响)')
1326
+ return
1327
+ }
1328
+ webServer.register({
1329
+ kind: 'prefix',
1330
+ path: routePath,
1331
+ // returning the promise is ignored by the http server but makes the
1332
+ // handler awaitable in tests/host-sim
1333
+ handler: (req, res) => Promise.resolve(handle(ctx, routePath, req, res))
1334
+ .catch((error) => writeError(res, error)),
1335
+ })
1336
+ console.log(`[dsh-memory-panel] 路由已注册 ${routePath}`)
1337
+ } catch (error) {
1338
+ console.log('[dsh-memory-panel] 路由注册失败(可能已存在,复用):', error?.message)
1339
+ }
1340
+ })
1341
+ } catch (error) {
1342
+ // 铁律:面板绝不允许把异常抛回 cordis(desktop fail-loud 会拖垮整个启动)
1343
+ console.error('[dsh-memory-panel] apply 意外失败(已吞掉,不影响启动):', error?.message)
1344
+ }
1345
+ }
1285
1346
 
1286
1347
 
1287
1348
  //# sourceURL=source/memory-panel/lib/index.js