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