@restregular/dsh-memory 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -58
- package/cordis.patch.yml +6 -8
- package/icon.svg +1 -0
- package/lib/client.js +859 -0
- package/lib/index.js +72 -0
- package/lib/inject/apply.js +80 -80
- package/lib/inject/inject.js +127 -127
- package/lib/panel.js +353 -0
- package/lib/provider/apply.js +133 -128
- package/lib/provider/embed-install.js +1144 -1002
- package/lib/provider/embed-server.js +308 -294
- package/lib/provider/embed.js +103 -103
- package/lib/provider/hardware.js +225 -0
- package/lib/provider/index.js +1271 -907
- package/lib/provider/models.js +253 -0
- package/lib/provider/recommend.js +187 -0
- package/lib/provider/rerank-cache.js +62 -62
- package/lib/provider/rerank.js +169 -169
- package/lib/provider/scoring.js +143 -143
- package/lib/provider/secrets.js +55 -55
- package/lib/provider/store.js +491 -491
- package/lib/tools/apply.js +104 -104
- package/lib/tools/index.js +224 -224
- package/package.json +17 -6
package/lib/panel.js
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
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 记录数 + 待嵌入数
|
|
12
|
+
* GET /records ?scope=&q= 枚举/过滤记录
|
|
13
|
+
* POST /update {id, content?, kind?, importance?, tags?, supersededBy?}
|
|
14
|
+
* POST /delete {id}
|
|
15
|
+
* scope 惰性加载是同步的(store.scope()),无需 ready 门。内容编辑会作废旧向量
|
|
16
|
+
* 并加入 embedPending,由 provider 的回填队列重新嵌入。
|
|
17
|
+
*
|
|
18
|
+
* 安全(每个路由都过 refuseRequest,见下):
|
|
19
|
+
* 注册在裸 webServer 上的路由**既不在宿主的 /api 围栏之后,也不在浏览器登录
|
|
20
|
+
* 之后** —— 宿主的围栏是一个给别的路由主动调用的服务方法(connection.requestRejection),
|
|
21
|
+
* 不是自动套上的中间件(dsh-market #603 的结论:裸 webServer 路由在登录开启时
|
|
22
|
+
* 可被无 session 调用 = 任意代码执行)。这里的读接口能读出全部记忆,写接口能改写、
|
|
23
|
+
* 删除、清空,还能拉起/卸载向量服务,所以必须自己问一次。
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
function writeJson(res, body, status = 200) {
|
|
27
|
+
try {
|
|
28
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
|
29
|
+
res.end(JSON.stringify(body))
|
|
30
|
+
} catch { /* 客户端已断开 */ }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function writeError(res, error) {
|
|
34
|
+
const status = Number(error?.status) || 500
|
|
35
|
+
writeJson(res, { ok: false, error: { code: error?.code || 'internal', message: error?.message || String(error) } }, status)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
class ApiError extends Error {
|
|
39
|
+
constructor(status, code, message) {
|
|
40
|
+
super(message)
|
|
41
|
+
this.status = status
|
|
42
|
+
this.code = code
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 只认本机权威(loopback),没有宿主围栏时的兜底。 */
|
|
47
|
+
const LOOPBACK_AUTHORITY = /^(?:127(?:\.\d{1,3}){3}|\[::1\]|::1|localhost)(?::\d+)?$/i
|
|
48
|
+
|
|
49
|
+
/** 请求头里的 Host,小写归一;缺失返回空串。 */
|
|
50
|
+
function hostHeader(req) {
|
|
51
|
+
const value = req?.headers?.host
|
|
52
|
+
return typeof value === 'string' ? value.trim().toLowerCase() : ''
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 部署自己声明的权威(宿主 connection 的 trustedHosts);拿不到就空数组。 */
|
|
56
|
+
function trustedAuthorities(ctx) {
|
|
57
|
+
try {
|
|
58
|
+
const connection = ctx?.get?.('connection')
|
|
59
|
+
return Array.isArray(connection?.trustedHosts)
|
|
60
|
+
? connection.trustedHosts.filter((entry) => typeof entry === 'string').map((entry) => entry.toLowerCase())
|
|
61
|
+
: []
|
|
62
|
+
} catch {
|
|
63
|
+
return []
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 该不该拒绝这个请求。
|
|
69
|
+
*
|
|
70
|
+
* 两层,顺序有讲究:
|
|
71
|
+
* 1. 宿主发布了 connection.requestRejection 时**以它为准** —— 它同时含 Host/Origin
|
|
72
|
+
* 围栏(防 DNS rebinding 与跨站调用)与浏览器登录(login-token cookie)。
|
|
73
|
+
* 围栏自己抛错时返回 403:抛错意味着"什么都没放行",此处失败关闭,不能放行。
|
|
74
|
+
* 2. 旧宿主没有这个服务时自己来:Host 必须是 loopback 或宿主声明的权威,
|
|
75
|
+
* sec-fetch-site 不得是 cross-site,带 Origin 就必须与 Host 相等。
|
|
76
|
+
* (注意 content-type: text/plain 也能携带合法 JSON 体且不触发预检,
|
|
77
|
+
* 所以"要求 JSON 体"挡不住跨站 —— 承重的是 Host/Origin 这一层。)
|
|
78
|
+
*
|
|
79
|
+
* @returns 需要拒绝时返回状态码(401 未登录 / 403 不受信任),否则 undefined。
|
|
80
|
+
*/
|
|
81
|
+
export function refuseRequest(ctx, req) {
|
|
82
|
+
let connection
|
|
83
|
+
try { connection = ctx?.get?.('connection') } catch { connection = undefined }
|
|
84
|
+
const gate = connection?.requestRejection
|
|
85
|
+
if (typeof gate === 'function') {
|
|
86
|
+
try {
|
|
87
|
+
const status = gate.call(connection, req)
|
|
88
|
+
return typeof status === 'number' ? status : undefined
|
|
89
|
+
} catch {
|
|
90
|
+
return 403
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const host = hostHeader(req)
|
|
94
|
+
if (host === '') return 403
|
|
95
|
+
if (!LOOPBACK_AUTHORITY.test(host) && !trustedAuthorities(ctx).includes(host)) return 403
|
|
96
|
+
if (String(req?.headers?.['sec-fetch-site'] ?? '').toLowerCase() === 'cross-site') return 403
|
|
97
|
+
const origin = req?.headers?.origin
|
|
98
|
+
if (origin !== undefined) {
|
|
99
|
+
try {
|
|
100
|
+
if (new URL(String(origin)).host.toLowerCase() !== host) return 403
|
|
101
|
+
} catch {
|
|
102
|
+
return 403
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return undefined
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 拒绝时的响应体:给人话,不说内部概念。 */
|
|
109
|
+
function writeRefusal(res, status) {
|
|
110
|
+
writeJson(res, {
|
|
111
|
+
ok: false,
|
|
112
|
+
error: {
|
|
113
|
+
code: status === 401 ? 'LOGIN_REQUIRED' : 'UNTRUSTED_REQUEST',
|
|
114
|
+
message: status === 401
|
|
115
|
+
? '需要先登录 DSH:请重新打开启动时打印的那个网址。'
|
|
116
|
+
: '这个请求来自不受信任的来源,已拒绝。',
|
|
117
|
+
},
|
|
118
|
+
}, status)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function readJsonBody(req) {
|
|
122
|
+
const chunks = []
|
|
123
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
124
|
+
const raw = Buffer.concat(chunks).toString('utf8')
|
|
125
|
+
return raw.length > 0 ? JSON.parse(raw) : {}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function wireRecord(rec, scopeStore) {
|
|
129
|
+
return {
|
|
130
|
+
id: rec.id,
|
|
131
|
+
scope: rec.scope,
|
|
132
|
+
kind: rec.kind,
|
|
133
|
+
content: rec.content,
|
|
134
|
+
tags: rec.tags ?? [],
|
|
135
|
+
importance: rec.importance,
|
|
136
|
+
createdAt: rec.createdAt,
|
|
137
|
+
updatedAt: rec.updatedAt,
|
|
138
|
+
accessCount: rec.accessCount ?? 0,
|
|
139
|
+
supersededBy: rec.supersededBy ?? null,
|
|
140
|
+
supersedes: rec.supersedes ?? null,
|
|
141
|
+
embedded: !scopeStore.embedPending.has(rec.id) && scopeStore.vectors.has(rec.id),
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function collectScope(scopeStore) {
|
|
146
|
+
const out = []
|
|
147
|
+
for (const rec of scopeStore.records.values()) out.push(wireRecord(rec, scopeStore))
|
|
148
|
+
return out.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function handle(ctx, routePath, req, res) {
|
|
152
|
+
const url = new URL(req.url ?? '/', 'http://dsh.local')
|
|
153
|
+
const path = url.pathname.slice(routePath.length) || '/'
|
|
154
|
+
const method = req.method ?? 'GET'
|
|
155
|
+
// 围栏在最前面:任何路由(读也一样)都先过宿主,再谈记忆。
|
|
156
|
+
const refused = refuseRequest(ctx, req)
|
|
157
|
+
if (refused !== undefined) {
|
|
158
|
+
writeRefusal(res, refused)
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
const memory = ctx.get('memory')
|
|
163
|
+
if (!memory?.store) throw new ApiError(503, 'MEMORY_UNAVAILABLE', 'memory provider 未加载')
|
|
164
|
+
const store = memory.store
|
|
165
|
+
// Scopes are created lazily, so a fresh process only knows the ones it has
|
|
166
|
+
// touched. A management view must see everything written on disk (project
|
|
167
|
+
// memories from earlier sessions included) — best-effort discovery.
|
|
168
|
+
try { store.loadDiscovered?.() } catch { /* discovery is best-effort */ }
|
|
169
|
+
|
|
170
|
+
if (method === 'GET' && path === '/status') {
|
|
171
|
+
const scopes = store.allScopes().map((s) => ({
|
|
172
|
+
scope: s.scope,
|
|
173
|
+
records: s.records.size,
|
|
174
|
+
pendingEmbeds: s.embedPending.size,
|
|
175
|
+
}))
|
|
176
|
+
let embedServer = null
|
|
177
|
+
// older providers have no lifecycle API — the panel simply omits the card
|
|
178
|
+
try { embedServer = (await memory.embedServerStatus?.()) ?? null } catch { embedServer = null }
|
|
179
|
+
writeJson(res, { ok: true, value: { scopes, embedServer } })
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
if (method === 'GET' && path === '/embed/status') {
|
|
183
|
+
if (typeof memory.embedServerStatus !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
|
|
184
|
+
writeJson(res, { ok: true, value: await memory.embedServerStatus() })
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
if (method === 'POST' && path === '/embed/start') {
|
|
188
|
+
if (typeof memory.startEmbedServerManually !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
|
|
189
|
+
const state = await memory.startEmbedServerManually()
|
|
190
|
+
console.log(`[dsh-memory-panel] 手动启动向量服务 -> ${state}`)
|
|
191
|
+
writeJson(res, { ok: true, value: { state, ...(await memory.embedServerStatus()) } })
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
if (method === 'POST' && path === '/embed/stop') {
|
|
195
|
+
if (typeof memory.stopEmbedServerManually !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
|
|
196
|
+
const out = memory.stopEmbedServerManually()
|
|
197
|
+
console.log(`[dsh-memory-panel] 手动停止向量服务 -> ${out.reason}`)
|
|
198
|
+
writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
if (method === 'GET' && path === '/embed/model') {
|
|
202
|
+
if (typeof memory.modelsReport !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供模型清单接口(请升级 @restregular/dsh-memory)')
|
|
203
|
+
writeJson(res, { ok: true, value: await memory.modelsReport(false) })
|
|
204
|
+
return
|
|
205
|
+
}
|
|
206
|
+
if (method === 'POST' && path === '/embed/model/refresh') {
|
|
207
|
+
if (typeof memory.modelsReport !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供模型清单接口(请升级 @restregular/dsh-memory)')
|
|
208
|
+
// 强制重探硬件:用户点了「重新检测」,缓存必须让路。
|
|
209
|
+
writeJson(res, { ok: true, value: await memory.modelsReport(true) })
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
if (method === 'POST' && path === '/embed/install') {
|
|
213
|
+
if (typeof memory.installVectorBackend !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供自动安装接口(请升级 @restregular/dsh-memory)')
|
|
214
|
+
// 面板可以带选择:预设 / 档位 / 风味,或者一个完全自定义的 GGUF。
|
|
215
|
+
const body = await readJsonBody(req)
|
|
216
|
+
const override = {}
|
|
217
|
+
if (typeof body.preset === 'string' && body.preset !== '') override.preset = body.preset
|
|
218
|
+
if (typeof body.variant === 'string' && body.variant !== '') override.variant = body.variant
|
|
219
|
+
if (typeof body.flavor === 'string' && body.flavor !== '') override.flavor = body.flavor
|
|
220
|
+
if (body.custom !== undefined && typeof body.custom === 'object' && body.custom !== null) {
|
|
221
|
+
const url = String(body.custom.url ?? '')
|
|
222
|
+
const dims = Number(body.custom.dims)
|
|
223
|
+
if (url === '' || !Number.isFinite(dims) || dims <= 0) throw new ApiError(400, 'CUSTOM_MODEL_INVALID', '自定义模型需要 url 与 dims')
|
|
224
|
+
override.custom = {
|
|
225
|
+
url,
|
|
226
|
+
dims,
|
|
227
|
+
...(body.custom.file ? { file: String(body.custom.file) } : {}),
|
|
228
|
+
...(body.custom.pooling ? { pooling: String(body.custom.pooling) } : {}),
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
memory.installVectorBackend(override)
|
|
232
|
+
console.log(`[dsh-memory-panel] 开始下载向量服务 ${JSON.stringify(override)}`)
|
|
233
|
+
writeJson(res, { ok: true, value: { ...(await memory.embedServerStatus()) } })
|
|
234
|
+
return
|
|
235
|
+
}
|
|
236
|
+
if (method === 'POST' && path === '/embed/install/cancel') {
|
|
237
|
+
if (typeof memory.cancelVectorInstall !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供自动安装接口(请升级 @restregular/dsh-memory)')
|
|
238
|
+
memory.cancelVectorInstall()
|
|
239
|
+
console.log('[dsh-memory-panel] 取消下载本地向量服务')
|
|
240
|
+
writeJson(res, { ok: true, value: { ...(await memory.embedServerStatus()) } })
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
if (method === 'POST' && path === '/embed/uninstall') {
|
|
244
|
+
if (typeof memory.uninstallVectorBackend !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供卸载接口(请升级 @restregular/dsh-memory)')
|
|
245
|
+
const out = memory.uninstallVectorBackend()
|
|
246
|
+
console.log(`[dsh-memory-panel] 卸载向量服务 -> ${out.reason},释放 ${(out.freedBytes / 1048576).toFixed(1)} MB`)
|
|
247
|
+
writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
|
|
248
|
+
return
|
|
249
|
+
}
|
|
250
|
+
if (method === 'POST' && path === '/data/wipe') {
|
|
251
|
+
if (typeof memory.wipeAllRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供数据清理接口(请升级 @restregular/dsh-memory)')
|
|
252
|
+
const body = await readJsonBody(req)
|
|
253
|
+
// Deleting everything is irreversible: require the caller to say so out
|
|
254
|
+
// loud, not just to click a button.
|
|
255
|
+
if (String(body.confirm ?? '') !== 'delete') throw new ApiError(400, 'CONFIRM_REQUIRED', '需要 confirm: "delete" 才执行删除')
|
|
256
|
+
const out = memory.wipeAllRecords()
|
|
257
|
+
console.log(`[dsh-memory-panel] 清空记忆数据 -> ${out.removed} 条 / ${out.scopes.length} 个作用域`)
|
|
258
|
+
writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
if (method === 'GET' && path === '/records') {
|
|
262
|
+
const scope = url.searchParams.get('scope')
|
|
263
|
+
const query = (url.searchParams.get('q') ?? '').trim().toLowerCase()
|
|
264
|
+
const stores = scope ? [store.scope(scope)] : store.allScopes()
|
|
265
|
+
let records = stores.flatMap((s) => collectScope(s))
|
|
266
|
+
if (query) {
|
|
267
|
+
records = records.filter((r) =>
|
|
268
|
+
r.content.toLowerCase().includes(query)
|
|
269
|
+
|| r.kind.toLowerCase().includes(query)
|
|
270
|
+
|| r.tags.some((t) => t.toLowerCase().includes(query)))
|
|
271
|
+
}
|
|
272
|
+
writeJson(res, { ok: true, value: { records } })
|
|
273
|
+
return
|
|
274
|
+
}
|
|
275
|
+
if (method === 'POST' && path === '/update') {
|
|
276
|
+
const body = await readJsonBody(req)
|
|
277
|
+
const id = String(body.id ?? '')
|
|
278
|
+
let target = null
|
|
279
|
+
for (const s of store.allScopes()) {
|
|
280
|
+
const rec = s.records.get(id)
|
|
281
|
+
if (rec) { target = { s, rec }; break }
|
|
282
|
+
}
|
|
283
|
+
if (!target) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${id}`)
|
|
284
|
+
const { s, rec } = target
|
|
285
|
+
if (body.content !== undefined) {
|
|
286
|
+
const content = String(body.content)
|
|
287
|
+
if (!content.trim()) throw new ApiError(400, 'CONTENT_EMPTY', 'content 不能为空')
|
|
288
|
+
if (content !== rec.content) {
|
|
289
|
+
rec.content = content
|
|
290
|
+
// 旧向量作废,排队重新嵌入(provider 的维护循环负责回填)
|
|
291
|
+
s.vectors.delete(id)
|
|
292
|
+
s.embedPending.add(id)
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (body.kind !== undefined) rec.kind = String(body.kind)
|
|
296
|
+
if (body.importance !== undefined) rec.importance = Math.min(1, Math.max(0, Number(body.importance) || 0))
|
|
297
|
+
if (body.tags !== undefined) rec.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
|
|
298
|
+
if (body.supersededBy !== undefined) rec.supersedes = body.supersededBy === null ? undefined : String(body.supersededBy)
|
|
299
|
+
rec.updatedAt = Date.now()
|
|
300
|
+
s.dirty = true
|
|
301
|
+
store.scheduleFlush()
|
|
302
|
+
writeJson(res, { ok: true, value: { record: wireRecord(rec, s) } })
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
if (method === 'POST' && path === '/delete') {
|
|
306
|
+
const body = await readJsonBody(req)
|
|
307
|
+
let removed = false
|
|
308
|
+
for (const s of store.allScopes()) {
|
|
309
|
+
if (s.records.has(String(body.id))) { removed = s.remove(String(body.id)); break }
|
|
310
|
+
}
|
|
311
|
+
if (!removed) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${body.id}`)
|
|
312
|
+
store.scheduleFlush()
|
|
313
|
+
writeJson(res, { ok: true, value: { removed: 1 } })
|
|
314
|
+
return
|
|
315
|
+
}
|
|
316
|
+
throw new ApiError(404, 'not_found', `unknown endpoint ${method} ${path}`)
|
|
317
|
+
} catch (error) {
|
|
318
|
+
ctx?.logger?.warn?.(error instanceof Error ? error : new Error(String(error)))
|
|
319
|
+
writeError(res, error)
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export const name = 'dsh-memory-panel'
|
|
324
|
+
export function apply(ctx, config = {}) {
|
|
325
|
+
const routePath = String(config.route || '/memory/api').replace(/\/$/, '')
|
|
326
|
+
try {
|
|
327
|
+
// 动态注入(cordis ctx.inject):webServer 已就绪则立即回调,否则等它出现,
|
|
328
|
+
// 不阻塞 entry 激活,也绝不让缺服务变成 fiber FAILED(dsh-client-modules 同款)。
|
|
329
|
+
ctx.inject(['webServer'], (svcCtx) => {
|
|
330
|
+
try {
|
|
331
|
+
const webServer = svcCtx.get('webServer')
|
|
332
|
+
if (!webServer || typeof webServer.register !== 'function') {
|
|
333
|
+
console.log('[dsh-memory-panel] webServer 不可用,面板 API 不注册(记忆工具不受影响)')
|
|
334
|
+
return
|
|
335
|
+
}
|
|
336
|
+
webServer.register({
|
|
337
|
+
kind: 'prefix',
|
|
338
|
+
path: routePath,
|
|
339
|
+
// returning the promise is ignored by the http server but makes the
|
|
340
|
+
// handler awaitable in tests/host-sim
|
|
341
|
+
handler: (req, res) => Promise.resolve(handle(ctx, routePath, req, res))
|
|
342
|
+
.catch((error) => writeError(res, error)),
|
|
343
|
+
})
|
|
344
|
+
console.log(`[dsh-memory-panel] 路由已注册 ${routePath}`)
|
|
345
|
+
} catch (error) {
|
|
346
|
+
console.log('[dsh-memory-panel] 路由注册失败(可能已存在,复用):', error?.message)
|
|
347
|
+
}
|
|
348
|
+
})
|
|
349
|
+
} catch (error) {
|
|
350
|
+
// 铁律:面板绝不允许把异常抛回 cordis(desktop fail-loud 会拖垮整个启动)
|
|
351
|
+
console.error('[dsh-memory-panel] apply 意外失败(已吞掉,不影响启动):', error?.message)
|
|
352
|
+
}
|
|
353
|
+
}
|
package/lib/provider/apply.js
CHANGED
|
@@ -1,128 +1,133 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cordis wiring for dsh-memory-local. Loaded only inside DSH.
|
|
3
|
-
*
|
|
4
|
-
* Per the official docs:
|
|
5
|
-
* - registers the service so consumers reach it as `ctx.memory`
|
|
6
|
-
* - the LLM rerank caller adapts `ctx.llm` (one-shot GenerateOptions with
|
|
7
|
-
* RequestUserInput) — attached lazily via ctx.get, so the plugin never sits
|
|
8
|
-
* PENDING just because no LLM adapter is loaded
|
|
9
|
-
*/
|
|
10
|
-
import { Service, } from '@deepseek-ai/cordis'
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
import { LocalMemoryService, } from './index.js'
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
export const name = 'dsh-memory-local'
|
|
22
|
-
|
|
23
|
-
export class CordisMemoryService extends Service {
|
|
24
|
-
impl
|
|
25
|
-
|
|
26
|
-
constructor(ctx , config = {}) {
|
|
27
|
-
super(ctx, 'memory')
|
|
28
|
-
this.impl = new LocalMemoryService(config)
|
|
29
|
-
ctx.effect(() => () => this.impl.flushSync())
|
|
30
|
-
this.attachRerank(ctx, config)
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Wire the rerank stage to ctx.llm when both it and a model are configured.
|
|
35
|
-
* Uses the documented one-shot shape: GenerateOptions + RequestUserInput,
|
|
36
|
-
* consuming `text-delta` chunks until finish.
|
|
37
|
-
*/
|
|
38
|
-
attachRerank(ctx , config ) {
|
|
39
|
-
const llmCfg = config.retrieval?.llm
|
|
40
|
-
if (!llmCfg?.enabled || !llmCfg.model) return
|
|
41
|
-
const llm = ctx.get('llm')
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
if (!llm?.stream) return
|
|
45
|
-
this.impl.setLlmInvoke(async ({ system, prompt, signal }) => {
|
|
46
|
-
const chunks = []
|
|
47
|
-
const stream = llm.stream({
|
|
48
|
-
provider: llmCfg.provider || 'deepseek',
|
|
49
|
-
model: llmCfg.model,
|
|
50
|
-
system,
|
|
51
|
-
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
52
|
-
maxTokens: 300,
|
|
53
|
-
temperature: 0,
|
|
54
|
-
signal,
|
|
55
|
-
})
|
|
56
|
-
for await (const chunk of stream) {
|
|
57
|
-
if (chunk.type === 'text-delta' && typeof chunk.textDelta === 'string') chunks.push(chunk.textDelta)
|
|
58
|
-
}
|
|
59
|
-
return chunks.join('')
|
|
60
|
-
})
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
save(input ) {
|
|
64
|
-
return this.impl.save(input)
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** Direct store access for server-side consumers (e.g. the memory panel). */
|
|
68
|
-
get store() {
|
|
69
|
-
return this.impl.store
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Embedding-backend lifecycle, exposed for the memory panel's buttons. */
|
|
73
|
-
embedServerStatus() {
|
|
74
|
-
return this.impl.embedServerStatus()
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
startEmbedServerManually() {
|
|
78
|
-
return this.impl.startEmbedServerManually()
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
stopEmbedServerManually() {
|
|
82
|
-
return this.impl.stopEmbedServerManually()
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** Panel: download llama.cpp + the GGML model, then adopt and start them. */
|
|
86
|
-
installVectorBackend() {
|
|
87
|
-
this.impl.installVectorBackend()
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Panel:
|
|
91
|
-
|
|
92
|
-
this.impl.
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Panel:
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** Panel:
|
|
101
|
-
|
|
102
|
-
return this.impl.
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Cordis wiring for dsh-memory-local. Loaded only inside DSH.
|
|
3
|
+
*
|
|
4
|
+
* Per the official docs:
|
|
5
|
+
* - registers the service so consumers reach it as `ctx.memory`
|
|
6
|
+
* - the LLM rerank caller adapts `ctx.llm` (one-shot GenerateOptions with
|
|
7
|
+
* RequestUserInput) — attached lazily via ctx.get, so the plugin never sits
|
|
8
|
+
* PENDING just because no LLM adapter is loaded
|
|
9
|
+
*/
|
|
10
|
+
import { Service, } from '@deepseek-ai/cordis'
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
import { LocalMemoryService, } from './index.js'
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
export const name = 'dsh-memory-local'
|
|
22
|
+
|
|
23
|
+
export class CordisMemoryService extends Service {
|
|
24
|
+
impl
|
|
25
|
+
|
|
26
|
+
constructor(ctx , config = {}) {
|
|
27
|
+
super(ctx, 'memory')
|
|
28
|
+
this.impl = new LocalMemoryService(config)
|
|
29
|
+
ctx.effect(() => () => this.impl.flushSync())
|
|
30
|
+
this.attachRerank(ctx, config)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Wire the rerank stage to ctx.llm when both it and a model are configured.
|
|
35
|
+
* Uses the documented one-shot shape: GenerateOptions + RequestUserInput,
|
|
36
|
+
* consuming `text-delta` chunks until finish.
|
|
37
|
+
*/
|
|
38
|
+
attachRerank(ctx , config ) {
|
|
39
|
+
const llmCfg = config.retrieval?.llm
|
|
40
|
+
if (!llmCfg?.enabled || !llmCfg.model) return
|
|
41
|
+
const llm = ctx.get('llm')
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
if (!llm?.stream) return
|
|
45
|
+
this.impl.setLlmInvoke(async ({ system, prompt, signal }) => {
|
|
46
|
+
const chunks = []
|
|
47
|
+
const stream = llm.stream({
|
|
48
|
+
provider: llmCfg.provider || 'deepseek',
|
|
49
|
+
model: llmCfg.model,
|
|
50
|
+
system,
|
|
51
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
52
|
+
maxTokens: 300,
|
|
53
|
+
temperature: 0,
|
|
54
|
+
signal,
|
|
55
|
+
})
|
|
56
|
+
for await (const chunk of stream) {
|
|
57
|
+
if (chunk.type === 'text-delta' && typeof chunk.textDelta === 'string') chunks.push(chunk.textDelta)
|
|
58
|
+
}
|
|
59
|
+
return chunks.join('')
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
save(input ) {
|
|
64
|
+
return this.impl.save(input)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Direct store access for server-side consumers (e.g. the memory panel). */
|
|
68
|
+
get store() {
|
|
69
|
+
return this.impl.store
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Embedding-backend lifecycle, exposed for the memory panel's buttons. */
|
|
73
|
+
embedServerStatus() {
|
|
74
|
+
return this.impl.embedServerStatus()
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
startEmbedServerManually() {
|
|
78
|
+
return this.impl.startEmbedServerManually()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
stopEmbedServerManually() {
|
|
82
|
+
return this.impl.stopEmbedServerManually()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Panel: download llama.cpp + the GGML model, then adopt and start them. */
|
|
86
|
+
installVectorBackend(override ) {
|
|
87
|
+
this.impl.installVectorBackend(override ?? {})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Panel: 模型清单 + 硬件探测 + 按硬件推荐(探测有缓存,只在面板问的时候跑)。 */
|
|
91
|
+
modelsReport(force = false) {
|
|
92
|
+
return this.impl.modelsReport(force)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Panel: abort an in-flight download. */
|
|
96
|
+
cancelVectorInstall() {
|
|
97
|
+
this.impl.cancelVectorInstall()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Panel: remove the runtime + model we installed (never the memory store). */
|
|
101
|
+
uninstallVectorBackend() {
|
|
102
|
+
return this.impl.uninstallVectorBackend()
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Panel: delete every record in every scope. */
|
|
106
|
+
wipeAllRecords() {
|
|
107
|
+
return this.impl.wipeAllRecords()
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
search(query ) {
|
|
111
|
+
return this.impl.search(query)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
forget(input ) {
|
|
115
|
+
return this.impl.forget(input)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
list(input ) {
|
|
119
|
+
return this.impl.list(input)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function apply(ctx , config = {}) {
|
|
124
|
+
class ScopedMemoryService extends CordisMemoryService {
|
|
125
|
+
constructor(ctx2 ) {
|
|
126
|
+
super(ctx2, config)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
ctx.plugin(ScopedMemoryService)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
//# sourceURL=source/memory-local/src/apply.ts
|