@restregular/dsh-memory 0.4.1 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -13
- package/lib/client.js +19 -7
- package/lib/inject/apply.js +27 -8
- package/lib/inject/inject.js +75 -3
- package/lib/panel.js +106 -12
- package/lib/provider/apply.js +40 -1
- package/lib/provider/index.js +270 -31
- package/lib/provider/scope.js +338 -0
- package/lib/provider/store.js +102 -10
- package/lib/tools/apply.js +123 -103
- package/lib/tools/index.js +370 -221
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -11,9 +11,10 @@ English: Local, durable memory for DeepSeek Harness — one npm package, one loa
|
|
|
11
11
|
|
|
12
12
|
| 能力 | 说明 |
|
|
13
13
|
| --- | --- |
|
|
14
|
-
| **落盘存储** | 每条记忆一行 JSONL,按 scope 分文件(global /
|
|
14
|
+
| **落盘存储** | 每条记忆一行 JSONL,按 scope 分文件(会话 / project / global / 自定义),同 scope 内按内容去重;写入前过凭据扫描 |
|
|
15
|
+
| **作用域** | 默认写进**当前会话**;读默认合并「会话 + 项目 + global」。也能写 `global`、当前项目,或任意自定义名(首次写入自动建) |
|
|
15
16
|
| **双通道检索** | 词法(IDF + CJK bigram)**+** 向量(llama-server 的 `/v1/embeddings`)。向量缺席时自动降级为纯词法,**不报错、不阻塞** |
|
|
16
|
-
| **自动召回** | `agent/pre-step` 注入相关记忆(可关、有 token 预算、按 topK
|
|
17
|
+
| **自动召回** | `agent/pre-step` 注入相关记忆(可关、有 token 预算、按 topK 截断,范围同为会话+项目+global) |
|
|
17
18
|
| **四个工具** | `memory_save` / `memory_search` / `memory_list` / `memory_forget` |
|
|
18
19
|
| **管理面板** | 设置页「记忆」:浏览 / 搜索 / 编辑 / 删除、向量服务启停、模型与硬件、维护(卸载 / 清空) |
|
|
19
20
|
| **向量后端一键装** | 面板里选模型 → 下 llama.cpp 运行时 + 模型 → 托管 `llama-server` 进程;内置 8 个模型 + 硬件推荐 + 自定义 GGUF |
|
|
@@ -56,19 +57,31 @@ pnpm add @restregular/dsh-memory
|
|
|
56
57
|
```jsonc
|
|
57
58
|
memory_save({
|
|
58
59
|
"content": "本仓库用 pnpm 11 安装依赖,PATH 上的 pnpm 10 会踩 ERR_PNPM_UNEXPECTED_STORE", // 必填,自洽的一句话
|
|
59
|
-
"scope": "
|
|
60
|
-
"kind": "fact",
|
|
60
|
+
"scope": "session", // 可省略 = 当前会话;global(所有项目) / project(当前工作区) / 任意自定义名
|
|
61
|
+
"kind": "fact", // fact / decision / preference / procedure / note
|
|
61
62
|
"tags": ["pnpm", "toolchain"],
|
|
62
|
-
"importance": 0.8
|
|
63
|
+
"importance": 0.8 // 0~1
|
|
63
64
|
})
|
|
64
65
|
```
|
|
65
66
|
|
|
66
|
-
|
|
67
|
-
|
|
67
|
+
作用域怎么选:
|
|
68
|
+
|
|
69
|
+
| 写法 | 含义 |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| 省略 / `session` | **当前会话**(子代理共享父会话;拿不到会话信息时回退到当前项目) |
|
|
72
|
+
| `project` | 当前工作区(键是 `project:<cwd>`) |
|
|
73
|
+
| `global` | 所有项目共享 |
|
|
74
|
+
| `handbook`、`项目笔记` … | **自定义作用域**:任意名字,首次 `memory_save` 时自动创建 |
|
|
75
|
+
| `session:<id>` / `project:<path>` | 显式钉住某个会话 / 某个工作区 |
|
|
76
|
+
| `all` / `*` | **只在读取时可用**:跨所有已发现的作用域;写入会明确报错 |
|
|
77
|
+
|
|
78
|
+
**2. 检索**:`memory_search({ query: "pnpm 装依赖", topK: 5 })` —— 省略 `scope` = 会话 + 项目 + global 合并(按来源标注、按 id 去重);`scope: "all"` 查所有作用域;写具体名字则只查那一个。
|
|
79
|
+
**3. 列出 / 忘记**:`memory_list({ limit: 20 })`(默认只列当前会话,末尾附作用域清单 + 记录数)、`memory_forget({ id })` 或 `memory_forget({ query, scope })`(按内容删默认**只作用于当前会话**,防止跨作用域误删)。
|
|
68
80
|
|
|
69
81
|
**4. 打开面板**:设置页 →「记忆」。面板里能做的事:
|
|
70
82
|
|
|
71
83
|
- 顶部统计(记忆数 / 作用域数 / 待嵌入向量数)与记录列表(搜索、按作用域筛选、展开编辑、删除)
|
|
84
|
+
- 作用域下拉**动态枚举实际存在的作用域**:`global` 显示「全局」、project 显示 cwd、会话 scope 显示会话标题(拿不到就显示「会话 <id 前 8 位>」)、自定义 scope 显示原名
|
|
72
85
|
- 「向量服务」:状态、地址、启停开关、**模型与硬件**(见下)、维护(卸载向量服务 / 清空记忆数据,两步确认)
|
|
73
86
|
|
|
74
87
|
面板后端在 `/memory/api`,全部路由:`GET /status`、`GET /records`、`POST /update`、`POST /delete`、`GET /embed/status`、`POST /embed/start|stop`、`GET /embed/model`、`POST /embed/model/refresh|install|install/cancel|uninstall`、`POST /data/wipe`。
|
|
@@ -77,12 +90,17 @@ memory_save({
|
|
|
77
90
|
|
|
78
91
|
| 路径 | 内容 |
|
|
79
92
|
| --- | --- |
|
|
80
|
-
| `<storeDir
|
|
81
|
-
| `<storeDir
|
|
93
|
+
| `<storeDir>/global.jsonl` | global 作用域的记忆,一行一条 |
|
|
94
|
+
| `<storeDir>/projects/<sha1(scope)>.jsonl` | 其它作用域(会话 / 项目 / 自定义)各一个文件;文件名是 scope 键的 SHA-1,所以名字里带路径分隔符也不可能穿越 |
|
|
95
|
+
| `<storeDir>/projects/<sha1(scope)>.vec` | 向量边车。首行是身份头 `#<model>\t<dims>`,后面每行 `id\t<base64 向量>` |
|
|
82
96
|
| `<installRoot>/llamacpp/` | llama-server 运行时(exe + 依赖 dll + `llama-server.log`) |
|
|
83
97
|
| `<installRoot>/models/` | 下载的 GGUF 模型 |
|
|
84
98
|
| `<installRoot>/selected-model.json` | 面板里选过哪一档(比配置优先级低) |
|
|
85
99
|
|
|
100
|
+
`storeDir` 默认 `.dsh-memory`(相对启动目录),**建议显式配一个绝对路径**。文件是**首次写入才创建**(读一个不存在的 scope 只会得到空结果,不会造出空文件);`projects/` 目录在插件启动时就建好。**作用域被删空后,它的 `.jsonl` 与 `.vec` 会在下一次落盘时一起移除**(0.5.1 起),不会再留下 0 字节文件;下次写同一个名字会重新创建。唯一例外是 `global.jsonl`:保留作用域删空后只清内容、保留文件。
|
|
101
|
+
|
|
102
|
+
scope 键的三种形态:`global`、`project:<cwd>`、`session:<会话 id>`,其余都是自定义名(小写折叠、内部空白折成一个空格、最长 64 字符,禁止 `:`、路径分隔符、控制字符、`..` 与保留名 `global/project/session/all`)。**没有任何数据迁移**:旧的 `project:<cwd>` 文件继续原样读写。
|
|
103
|
+
|
|
86
104
|
`installRoot` 默认 `~/.dsh/memory-vector`;显式配了 `storeDir` 时取**它的父目录**(所以手写的 `<root>/llamacpp` + `<root>/models` 布局会被直接认出来)。
|
|
87
105
|
|
|
88
106
|
> **换模型 = 向量作废重建**。`.vec` 的身份头记录 `model` 与 `dims`,对不上就整份丢弃并重新嵌入;重建期间检索暂时只用词法。面板会在换之前告诉你涉及多少条记忆。
|
|
@@ -96,7 +114,11 @@ provider 的配置在顶层,工具 / 注入 / 面板各占一个小节(合并前
|
|
|
96
114
|
name: '@restregular/dsh-memory'
|
|
97
115
|
config:
|
|
98
116
|
storeDir: '~/.dsh/memory-store'
|
|
99
|
-
scopes:
|
|
117
|
+
scopes:
|
|
118
|
+
global: true
|
|
119
|
+
project: true
|
|
120
|
+
session: true # 会话作用域(默认开)
|
|
121
|
+
custom: { enabled: true, max: 200 } # 自定义作用域:开关 + 数量上限(只数自定义的)
|
|
100
122
|
retrieval:
|
|
101
123
|
topK: 5
|
|
102
124
|
recallN: 30
|
|
@@ -118,11 +140,16 @@ provider 的配置在顶层,工具 / 注入 / 面板各占一个小节(合并前
|
|
|
118
140
|
llm: { enabled: false } # LLM 重排(可选)
|
|
119
141
|
limits: { maxRecordsPerScope: 2000, maxRecordChars: 4000 }
|
|
120
142
|
secrets: { enabled: true, mode: refuse }
|
|
121
|
-
tools: { defaultScope:
|
|
122
|
-
inject: { enabled: true, tokenBudget: 500, topK: 5 }
|
|
143
|
+
tools: { defaultScope: session } # session(新默认)/ project / global;projectScope 默认 project:<会话 cwd>
|
|
144
|
+
inject: { enabled: true, tokenBudget: 500, topK: 5 } # 可加 extraScopes: ['handbook']
|
|
123
145
|
panel: { route: '/memory/api' }
|
|
124
146
|
```
|
|
125
147
|
|
|
148
|
+
- **`tools.defaultScope`** 决定*省略 scope 时写到哪*:`session`(0.5.0 起的默认)、`project`、`global`。会话写不进去(宿主没给会话信息、或 `scopes.session: false`)时**自动回退到当前项目**,不报错。
|
|
149
|
+
- **`scopes.custom.max`** 只统计自定义作用域(已发现 + 已加载去重);到上限后 `memory_save` 新建会被拒并提示可复用的名字(`SCOPE_LIMIT`),写已有作用域不受限。会话/项目/global 既不计入也不受限。
|
|
150
|
+
- **读与写的默认是一致的**:写进会话的东西,`memory_search` 默认就能读回来(合并会话 + 项目 + global,按 id 去重,同分时 session > project > 自定义 > global)。想只看某一个就显式给 `scope`。
|
|
151
|
+
- 旧配置(只有 `scopes: { global: true, project: true }`、`tools.defaultScope: project`)照常工作 —— 不写新字段就是新默认值(`session: true`、`custom: { enabled: true, max: 200 }`),想保持 0.4.x 的老行为就显式写 `tools.defaultScope: project`。
|
|
152
|
+
|
|
126
153
|
向量检索是**按配置启用**的:写了 `endpoint`、配了 `spawn`、或面板里装了本地后端才会碰网络,否则一个请求都不发,检索自动降级为纯词法(IDF + CJK bigram)。不需要自动召回就 `inject.enabled: false`。
|
|
127
154
|
|
|
128
155
|
`spawn.enabled: true` 时:应用启动后台拉起向量服务、退出时自动关闭;带 PID 文件的遗留实例会被接管,没有 PID 文件的外部实例不接管。
|
|
@@ -194,10 +221,30 @@ npm run verify # 构建到 .verify/,不落 packages/(CI 或改动后自检)
|
|
|
194
221
|
可选的真实加载验证(证明产物在没有 TS 支持的普通 node 里能跑):
|
|
195
222
|
|
|
196
223
|
```bash
|
|
197
|
-
node tools/build-single-package.mjs --scope @restregular --version 0.
|
|
224
|
+
node tools/build-single-package.mjs --scope @restregular --version 0.5.1 \
|
|
198
225
|
--host-modules <一个 @deepseek-ai 目录> # 或设 DSH_HOST_MODULES
|
|
199
226
|
```
|
|
200
227
|
|
|
228
|
+
### 发布 / Publish
|
|
229
|
+
|
|
230
|
+
```bash
|
|
231
|
+
npm run build # 产物落到 packages/dsh-memory(版本号在 package.json 的 build/verify 里)
|
|
232
|
+
node tools/publish-npm-packages.mjs --scope @restregular --version 0.5.1
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
`publish-npm-packages.mjs` 发的是**单包** `packages/dsh-memory`,顺序是
|
|
236
|
+
`npm test` → `npm run verify` → `npm whoami` 预检 → `npm pack --dry-run` 校验产物清单(缺
|
|
237
|
+
`lib/client.js`/`cordis.patch.yml` 等必填项、或混进 `.ts`/测试文件都会中止)→ `npm publish`。
|
|
238
|
+
任何一步失败都停在"什么都没发出去"的状态;`--dry-run` 只走到校验,`--skip-checks` 跳过前两步。
|
|
239
|
+
|
|
240
|
+
npm token **不经过命令行**:默认从 DevCred 读取(凭据名默认 `npm-agent-use`,`--credential` 可换),
|
|
241
|
+
由 `devcred inject` 把 `NPM_TOKEN` 交给一个只写文件、不回显的子进程,写进临时目录里的私有
|
|
242
|
+
`.npmrc`,发布后连临时目录一起删除;也可以 `--token-file <npmrc>` 指一份自己的凭据文件。
|
|
243
|
+
|
|
244
|
+
> npm 的**暂存发布(staged publishing)** 会让重复版本号撞上 `E409 Cannot publish over previously
|
|
245
|
+
> staged version`:说明这个版本已经在 npm 侧暂存、等待在 npmjs.com 的包页面批准,批准前
|
|
246
|
+
> `latest` 不会指向它。这时不需要再发一次,去网页上确认即可。
|
|
247
|
+
|
|
201
248
|
## 仓库结构 / Layout
|
|
202
249
|
|
|
203
250
|
```
|
|
@@ -233,6 +280,16 @@ tools/build-single-package.mjs 构建(产物契约检查 + 可选加载验证)
|
|
|
233
280
|
|
|
234
281
|
## 版本
|
|
235
282
|
|
|
283
|
+
- **0.5.1** —— 清理空作用域文件:作用域被删空后(删掉最后一条、或 `POST /data/wipe`),它的 `.jsonl` 与 `.vec` 会在下一次落盘时一起移除,不再留 0 字节文件与只剩身份头的边车;下次写同一个名字会重新创建。`global.jsonl` 是唯一例外(保留作用域只清内容、留文件)。同版本的旧文件行为不变,无数据迁移。
|
|
284
|
+
- **0.5.0** —— 作用域重构:
|
|
285
|
+
- **默认作用域 = 当前会话**:`memory_save` 省略 `scope` 时写进 `session:<会话 id>`(子代理共享父会话;拿不到会话信息或 `scopes.session: false` 时回退当前项目,不报错)。
|
|
286
|
+
- **读写默认一致**:0.4.x 的写路径默认是 `project:<cwd>`、而 provider 的读路径默认是 `global` —— 写进去的记忆默认检索不到。现在两边都是「会话 + 项目 + global」合并去重(同分时 session > project > 自定义 > global)。
|
|
287
|
+
- **自定义作用域**:`scope` 可以填任意名字(如 `handbook`、`项目笔记`),首次写入时自动创建;新增 `scopes.custom.enabled` / `scopes.custom.max`(默认 200,只统计自定义的)与 `SCOPE_LIMIT` / `SCOPE_INVALID` 明确报错 —— **取消了"认不出的 scope 静默回退默认值"**。
|
|
288
|
+
- **`scope: 'all'`**(或 `*`)跨所有已发现作用域读取;写入路径明确报错。`memory_forget({query})` 默认只作用于当前会话,`all` + query 直接拒绝,防批量误删。
|
|
289
|
+
- **读路径不再创建文件**:`memory_search` / `memory_list` / `memory_forget` / 面板对不存在的 scope 返回空结果;只有 `memory_save` 才会建文件。
|
|
290
|
+
- 面板:作用域下拉与「作用域数」动态枚举现存作用域,会话 scope 显示会话标题(拿不到就「会话 <id 前 8 位>」)。
|
|
291
|
+
- **不迁移、不重命名任何文件**:旧的 `global.jsonl` 与 `projects/<sha1>.jsonl` 仍按原路径原样读写;`tools.defaultScope` 保留,新增取值 `session` 并作为默认。
|
|
292
|
+
- 要完全保持 0.4.x 的写行为:`tools.defaultScope: project`。
|
|
236
293
|
- **0.4.0** —— 单包合并里程碑:面板并入主包(一条 entry)、模型清单与硬件推荐、自定义 GGUF、运行时风味、"一次只保留一份"。
|
|
237
294
|
- **0.3.x 及更早** —— 拆分结构(provider / tools / inject / panel 各自独立 entry)。从 0.3.x 升级请按上面的单行 entry 重新挂载,并把旧的多条 entry 删掉。
|
|
238
295
|
|
package/lib/client.js
CHANGED
|
@@ -156,11 +156,20 @@ window.__ModuleLoader__.load({
|
|
|
156
156
|
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
/**
|
|
160
|
+
* scope 键 → 展示标签。优先用 /status 返回的 `label`(服务端能查会话标题、能解析
|
|
161
|
+
* project 的 cwd);服务端没给(旧 provider / 还没加载到)时用本地回退。
|
|
162
|
+
*/
|
|
163
|
+
function scopeLabel(scope, labels) {
|
|
164
|
+
const mapped = labels && labels[scope]
|
|
165
|
+
if (typeof mapped === 'string' && mapped.length > 0) return mapped
|
|
166
|
+
if (scope === 'global') return '全局'
|
|
167
|
+
if (scope.startsWith('project:')) return scope.slice(8)
|
|
168
|
+
if (scope.startsWith('session:')) return `会话 ${scope.slice(8, 16)}`
|
|
169
|
+
return scope
|
|
161
170
|
}
|
|
162
171
|
|
|
163
|
-
function RecordCard({ rec, vectorOn, onSaved, onDeleted }) {
|
|
172
|
+
function RecordCard({ rec, vectorOn, labels, onSaved, onDeleted }) {
|
|
164
173
|
// collapsed by default: the list stays scannable, full text on demand
|
|
165
174
|
const [expanded, setExpanded] = React.useState(false)
|
|
166
175
|
const [editing, setEditing] = React.useState(false)
|
|
@@ -215,7 +224,7 @@ window.__ModuleLoader__.load({
|
|
|
215
224
|
},
|
|
216
225
|
},
|
|
217
226
|
h('span', { className: open ? 'chev open' : 'chev' }, '▶'),
|
|
218
|
-
h('span', { className: 'badge scope', title: rec.scope }, scopeLabel(rec.scope)),
|
|
227
|
+
h('span', { className: 'badge scope', title: rec.scope }, scopeLabel(rec.scope, labels)),
|
|
219
228
|
h('span', { className: 'badge' }, rec.kind),
|
|
220
229
|
rec.supersedes ? h('span', { className: 'badge', title: `修正 #${rec.supersedes}` }, '修正') : null,
|
|
221
230
|
// 只在"待嵌入"时提示:已嵌入是常态,向量没启用时这条也没有行动价值。
|
|
@@ -648,6 +657,9 @@ window.__ModuleLoader__.load({
|
|
|
648
657
|
|
|
649
658
|
const total = scopes.reduce((n, s) => n + s.records, 0)
|
|
650
659
|
const pending = scopes.reduce((n, s) => n + s.pendingEmbeds, 0)
|
|
660
|
+
// 服务端 /status 给的 scope → label 映射(会话标题、project 的 cwd 只有服务端知道)
|
|
661
|
+
const labels = {}
|
|
662
|
+
for (const s of scopes) if (s && s.scope && typeof s.label === 'string') labels[s.scope] = s.label
|
|
651
663
|
|
|
652
664
|
// 向量卡片的状态判定。provider 给的 mode 决定"该不该有启停开关":
|
|
653
665
|
// off 没配置任何后端 → 不给开关,模型与安装入口都在「模型与硬件」里
|
|
@@ -795,11 +807,11 @@ window.__ModuleLoader__.load({
|
|
|
795
807
|
onChange: (e) => setQ(e.target.value),
|
|
796
808
|
onKeyDown: (e) => { if (e.key === 'Enter') load(q, scopeFilter) },
|
|
797
809
|
}),
|
|
798
|
-
// 作用域也用同一个自绘下拉(与模型/运行时统一)
|
|
810
|
+
// 作用域也用同一个自绘下拉(与模型/运行时统一);标签优先用服务端给的 label
|
|
799
811
|
h(Dropdown, {
|
|
800
812
|
items: [
|
|
801
813
|
{ value: '', label: '全部作用域' },
|
|
802
|
-
...scopes.map((s) => ({ value: s.scope, label: scopeLabel(s.scope) })),
|
|
814
|
+
...scopes.map((s) => ({ value: s.scope, label: s.label || scopeLabel(s.scope) })),
|
|
803
815
|
],
|
|
804
816
|
value: scopeFilter,
|
|
805
817
|
disabled: loading,
|
|
@@ -812,7 +824,7 @@ window.__ModuleLoader__.load({
|
|
|
812
824
|
!loading && !error && records.length === 0
|
|
813
825
|
? h('div', { className: 'empty' }, filtering ? '没有匹配的记忆' : '还没有记忆')
|
|
814
826
|
: h('div', { className: 'list' },
|
|
815
|
-
records.map((rec) => h(RecordCard, { key: rec.id, rec, vectorOn: configured && vectorEnabled, onSaved: () => load(), onDeleted: () => load() }))),
|
|
827
|
+
records.map((rec) => h(RecordCard, { key: rec.id, rec, vectorOn: configured && vectorEnabled, labels: labels, onSaved: () => load(), onDeleted: () => load() }))),
|
|
816
828
|
)
|
|
817
829
|
}
|
|
818
830
|
|
package/lib/inject/apply.js
CHANGED
|
@@ -14,11 +14,18 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
import {
|
|
18
|
+
MemoryInjector,
|
|
19
|
+
defaultInjectConfig,
|
|
20
|
+
normalizeExtraScopes,
|
|
21
|
+
resolveInjectScopes,
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
} from './inject.js'
|
|
19
26
|
|
|
20
27
|
|
|
21
|
-
|
|
28
|
+
|
|
22
29
|
|
|
23
30
|
|
|
24
31
|
|
|
@@ -30,14 +37,22 @@ export function apply(ctx , config = {}) {
|
|
|
30
37
|
tokenBudget: config.tokenBudget ?? defaultInjectConfig.tokenBudget,
|
|
31
38
|
topK: config.topK ?? defaultInjectConfig.topK,
|
|
32
39
|
}
|
|
40
|
+
const extraScopes = normalizeExtraScopes(config.extraScopes ?? [])
|
|
41
|
+
const readScopesFor = (memory , agent ) =>
|
|
42
|
+
resolveInjectScopes(memory, agent, extraScopes, ctx.get?.('sessions') )
|
|
33
43
|
|
|
34
44
|
// One injector per activation: its repeat-suppression state must live across
|
|
35
45
|
// the steps of a turn (a per-step instance would re-inject every step).
|
|
36
46
|
const injector = new MemoryInjector(
|
|
37
|
-
async (query, signal) => {
|
|
38
|
-
const memory = ctx.get('memory')
|
|
47
|
+
async (query, signal, scopes) => {
|
|
48
|
+
const memory = ctx.get('memory')
|
|
39
49
|
if (!memory?.search) return []
|
|
40
|
-
return memory.search({
|
|
50
|
+
return memory.search({
|
|
51
|
+
text: query,
|
|
52
|
+
signal,
|
|
53
|
+
topK: cfg.topK,
|
|
54
|
+
...(scopes !== undefined ? { scopes: [...scopes] } : {}),
|
|
55
|
+
})
|
|
41
56
|
},
|
|
42
57
|
cfg,
|
|
43
58
|
)
|
|
@@ -48,10 +63,14 @@ export function apply(ctx , config = {}) {
|
|
|
48
63
|
// A rejected step must pass through untouched — never rebuild the decision.
|
|
49
64
|
if (!decision || decision.kind === 'reject' || input.signal?.aborted) return decision
|
|
50
65
|
// optional capability: absence (or partial load) → pass through untouched
|
|
51
|
-
|
|
66
|
+
const memory = ctx.get('memory')
|
|
67
|
+
if (!memory) return decision
|
|
52
68
|
|
|
69
|
+
// 会话上下文只在 pre-step 里拿得到:交给 search 的 `scopes`,与 memory_search 的
|
|
70
|
+
// 默认合并集合用同一套解析(provider 的 resolveReadScopes)。
|
|
71
|
+
const scopes = readScopesFor(memory, (input ).agent)
|
|
53
72
|
const text = await injector.maybeInject(
|
|
54
|
-
{ messages: input.messages , signal: input.signal },
|
|
73
|
+
{ messages: input.messages , signal: input.signal, ...(scopes !== undefined ? { scopes } : {}) },
|
|
55
74
|
{ messages: decision.messages },
|
|
56
75
|
)
|
|
57
76
|
if (!text) return decision
|
package/lib/inject/inject.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { estimateTokens } from '../provider/rerank.js'
|
|
10
|
+
import { normalizeScopeInput } from '../provider/scope.js'
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
|
|
@@ -14,6 +15,11 @@ import { estimateTokens } from '../provider/rerank.js'
|
|
|
14
15
|
|
|
15
16
|
|
|
16
17
|
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
17
23
|
|
|
18
24
|
|
|
19
25
|
export const defaultInjectConfig = {
|
|
@@ -22,6 +28,66 @@ export const defaultInjectConfig = {
|
|
|
22
28
|
topK: 5,
|
|
23
29
|
}
|
|
24
30
|
|
|
31
|
+
/** 召回注入能用到的那部分 provider 能力。 */
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
/** 宿主里"按会话 id 找 live session"的那一小部分能力(拿不到就不做父会话召回)。 */
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 把 config.extraScopes 规范化成 scope 键列表;非法项忽略并记一行日志
|
|
44
|
+
* (配置写错不该让整个注入半边失效)。
|
|
45
|
+
*/
|
|
46
|
+
export function normalizeExtraScopes(raw , warn = console.warn) {
|
|
47
|
+
const out = []
|
|
48
|
+
for (const item of raw) {
|
|
49
|
+
const normalized = normalizeScopeInput(item)
|
|
50
|
+
if (!normalized.ok) {
|
|
51
|
+
warn(`[dsh-memory-inject] 忽略非法的 inject.extraScopes 项 ${JSON.stringify(item)}: ${normalized.message}`)
|
|
52
|
+
continue
|
|
53
|
+
}
|
|
54
|
+
if (normalized.scope !== undefined && !out.includes(normalized.scope)) out.push(normalized.scope)
|
|
55
|
+
}
|
|
56
|
+
return out
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 无显式 scope 时的召回范围:当前会话 + 当前项目 + global(provider 解析)
|
|
61
|
+
* + inject.extraScopes + 父会话(fork 时,只读召回)。
|
|
62
|
+
* 任何一步拿不到都只降级,绝不抛(注入路径抛错会打断整个 agent 循环)。
|
|
63
|
+
*/
|
|
64
|
+
export function resolveInjectScopes(
|
|
65
|
+
memory ,
|
|
66
|
+
agent ,
|
|
67
|
+
extraScopes ,
|
|
68
|
+
sessions ,
|
|
69
|
+
) {
|
|
70
|
+
const scopes = []
|
|
71
|
+
try {
|
|
72
|
+
for (const scope of memory.resolveReadScopes?.(agent) ?? []) {
|
|
73
|
+
if (!scopes.includes(scope)) scopes.push(scope)
|
|
74
|
+
}
|
|
75
|
+
} catch { /* 降级为 extraScopes */ }
|
|
76
|
+
for (const scope of extraScopes) if (!scopes.includes(scope)) scopes.push(scope)
|
|
77
|
+
// fork 出来的会话:父会话的记忆也值得召回(只读)。父会话可能已不在内存里,拿不到就跳过。
|
|
78
|
+
try {
|
|
79
|
+
const header = (agent )?.session?.header
|
|
80
|
+
const parent = typeof header?.parentSession === 'string' ? header.parentSession : undefined
|
|
81
|
+
if (parent !== undefined && header?.origin !== 'subagent') {
|
|
82
|
+
if (sessions?.get?.(parent) !== undefined) {
|
|
83
|
+
const scope = `session:${parent}`
|
|
84
|
+
if (!scopes.includes(scope)) scopes.push(scope)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
} catch { /* 父会话召回是可选增强 */ }
|
|
88
|
+
return scopes.length > 0 ? scopes : undefined
|
|
89
|
+
}
|
|
90
|
+
|
|
25
91
|
/** Minimal structural view of the messages we inspect (role + text blocks). */
|
|
26
92
|
|
|
27
93
|
|
|
@@ -31,6 +97,12 @@ export const defaultInjectConfig = {
|
|
|
31
97
|
|
|
32
98
|
|
|
33
99
|
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
34
106
|
|
|
35
107
|
|
|
36
108
|
|
|
@@ -89,11 +161,11 @@ export function recallText(text ) {
|
|
|
89
161
|
*/
|
|
90
162
|
export class MemoryInjector {
|
|
91
163
|
lastText = ''
|
|
92
|
-
search
|
|
164
|
+
search
|
|
93
165
|
cfg
|
|
94
166
|
|
|
95
167
|
constructor(
|
|
96
|
-
search
|
|
168
|
+
search ,
|
|
97
169
|
cfg ,
|
|
98
170
|
) {
|
|
99
171
|
this.search = search
|
|
@@ -110,7 +182,7 @@ export class MemoryInjector {
|
|
|
110
182
|
|
|
111
183
|
let hits
|
|
112
184
|
try {
|
|
113
|
-
hits = await this.search(query, input.signal)
|
|
185
|
+
hits = await this.search(query, input.signal, input.scopes)
|
|
114
186
|
} catch {
|
|
115
187
|
return undefined // retrieval failure never breaks the agent loop
|
|
116
188
|
}
|
package/lib/panel.js
CHANGED
|
@@ -8,12 +8,12 @@
|
|
|
8
8
|
* - apply 整体兜底 catch:任何意外都不允许向外抛。
|
|
9
9
|
*
|
|
10
10
|
* 提供管理员 API(前缀路由 /memory/api):
|
|
11
|
-
* GET /status 各 scope 记录数 + 待嵌入数
|
|
11
|
+
* GET /status 各 scope 记录数 + 待嵌入数 + 展示标签
|
|
12
12
|
* GET /records ?scope=&q= 枚举/过滤记录
|
|
13
13
|
* POST /update {id, content?, kind?, importance?, tags?, supersededBy?}
|
|
14
14
|
* POST /delete {id}
|
|
15
|
-
* scope 惰性加载是同步的(store.
|
|
16
|
-
*
|
|
15
|
+
* scope 惰性加载是同步的(store.peek(),**读路径不创建**),无需 ready 门。内容编辑会作废旧
|
|
16
|
+
* 向量并加入 embedPending,由 provider 的回填队列重新嵌入。
|
|
17
17
|
*
|
|
18
18
|
* 安全(每个路由都过 refuseRequest,见下):
|
|
19
19
|
* 注册在裸 webServer 上的路由**既不在宿主的 /api 围栏之后,也不在浏览器登录
|
|
@@ -22,6 +22,11 @@
|
|
|
22
22
|
* 可被无 session 调用 = 任意代码执行)。这里的读接口能读出全部记忆,写接口能改写、
|
|
23
23
|
* 删除、清空,还能拉起/卸载向量服务,所以必须自己问一次。
|
|
24
24
|
*/
|
|
25
|
+
// scope 规范化与 provider 共用同一份实现。路径按**源码树位置**写:构建脚本的改写表
|
|
26
|
+
// 会把它落成产物里的 `../provider/scope.js`(`lib/panel.js` → `lib/provider/scope.js`),
|
|
27
|
+
// 在源码树里同一路径直接命中 source/memory-local/src —— 测试与真实加载都能解析。
|
|
28
|
+
import { normalizeScopeInput } from './provider/scope.js'
|
|
29
|
+
|
|
25
30
|
|
|
26
31
|
function writeJson(res, body, status = 200) {
|
|
27
32
|
try {
|
|
@@ -125,6 +130,62 @@ async function readJsonBody(req) {
|
|
|
125
130
|
return raw.length > 0 ? JSON.parse(raw) : {}
|
|
126
131
|
}
|
|
127
132
|
|
|
133
|
+
/**
|
|
134
|
+
* scope 键 → **不需要查宿主服务**的展示标签。
|
|
135
|
+
* global → 「全局」
|
|
136
|
+
* project:<cwd> → cwd
|
|
137
|
+
* session:<id> → 「会话 <id 前 8 位>」
|
|
138
|
+
* 其他 → 原名(自定义 scope)
|
|
139
|
+
*/
|
|
140
|
+
function fallbackScopeLabel(scope) {
|
|
141
|
+
if (scope === 'global') return '全局'
|
|
142
|
+
if (scope.startsWith('project:')) return scope.slice('project:'.length)
|
|
143
|
+
if (scope.startsWith('session:')) return `会话 ${scope.slice('session:'.length, 'session:'.length + 8)}`
|
|
144
|
+
return scope
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* scope 键 → 展示标签。在 fallback 之上多一步:会话 scope 尽力取会话标题
|
|
149
|
+
* (宿主 `sessionTitle` 服务的 `get(session)` → `{ title }`,见 @deepseek-ai/dsh-session-title)。
|
|
150
|
+
* 所有宿主服务访问都在 try/catch 里:面板绝不能因为拿不到标题而失败。
|
|
151
|
+
*/
|
|
152
|
+
function scopeLabel(ctx, scope) {
|
|
153
|
+
if (!scope.startsWith('session:')) return fallbackScopeLabel(scope)
|
|
154
|
+
const id = scope.slice('session:'.length)
|
|
155
|
+
const short = id.slice(0, 8)
|
|
156
|
+
try {
|
|
157
|
+
const session = ctx?.get?.('sessions')?.get?.(id)
|
|
158
|
+
if (session !== undefined) {
|
|
159
|
+
const title = ctx.get('sessionTitle')?.get?.(session)?.title
|
|
160
|
+
if (typeof title === 'string' && title.length > 0) return `${title}(${short})`
|
|
161
|
+
}
|
|
162
|
+
} catch { /* 标题是尽力而为 */ }
|
|
163
|
+
return `会话 ${short}`
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 会话 scope 查标题的上限:标题要读会话事件日志,scope 多了它就成了 /status 的大头。 */
|
|
167
|
+
const TITLE_LOOKUP_LIMIT = 50
|
|
168
|
+
/** discovery(读每个 scope 文件的第一条记录)结果的缓存时长。 */
|
|
169
|
+
const DISCOVER_CACHE_MS = 3000
|
|
170
|
+
/** 每个 memory 服务的发现缓存。面板看不到进程数,所以按服务实例各存一份。 */
|
|
171
|
+
const discoveryCache = new WeakMap()
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 发现磁盘上的 scope,3 秒内只做一次。
|
|
175
|
+
* 面板每个请求都想要一份完整清单(别的进程写下的 scope 也要看得见),而 discovery 要
|
|
176
|
+
* 读每个文件的第一条记录 —— 没有缓存的话刷新一下就是一次全目录扫描。
|
|
177
|
+
*/
|
|
178
|
+
function discoverScopes(memory, store) {
|
|
179
|
+
const now = Date.now()
|
|
180
|
+
const cached = discoveryCache.get(memory)
|
|
181
|
+
if (cached !== undefined && now - cached.at < DISCOVER_CACHE_MS) return
|
|
182
|
+
discoveryCache.set(memory, { at: now })
|
|
183
|
+
try {
|
|
184
|
+
if (typeof memory.discoverScopes === 'function') memory.discoverScopes()
|
|
185
|
+
else store.loadDiscovered?.()
|
|
186
|
+
} catch { /* discovery is best-effort */ }
|
|
187
|
+
}
|
|
188
|
+
|
|
128
189
|
function wireRecord(rec, scopeStore) {
|
|
129
190
|
return {
|
|
130
191
|
id: rec.id,
|
|
@@ -164,14 +225,18 @@ async function handle(ctx, routePath, req, res) {
|
|
|
164
225
|
const store = memory.store
|
|
165
226
|
// Scopes are created lazily, so a fresh process only knows the ones it has
|
|
166
227
|
// touched. A management view must see everything written on disk (project
|
|
167
|
-
// memories from earlier sessions included) — best-effort discovery.
|
|
168
|
-
|
|
228
|
+
// memories from earlier sessions included) — best-effort discovery, cached.
|
|
229
|
+
discoverScopes(memory, store)
|
|
169
230
|
|
|
170
231
|
if (method === 'GET' && path === '/status') {
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
records: s.records.size,
|
|
174
|
-
|
|
232
|
+
const stats = typeof memory.scopeStats === 'function'
|
|
233
|
+
? memory.scopeStats()
|
|
234
|
+
: store.allScopes().map((s) => ({ scope: s.scope, records: s.records.size, pendingEmbeds: s.embedPending.size }))
|
|
235
|
+
// 会话标题是尽力而为的增强,而且要读会话事件日志:只给最近活跃的前 N 个查,
|
|
236
|
+
// 其余直接用「会话 <id 前 8 位>」。列表本身**始终**完整(不受这个上限影响)。
|
|
237
|
+
const scopes = stats.map((s, index) => ({
|
|
238
|
+
...s,
|
|
239
|
+
label: index < TITLE_LOOKUP_LIMIT ? scopeLabel(ctx, s.scope) : fallbackScopeLabel(s.scope),
|
|
175
240
|
}))
|
|
176
241
|
let embedServer = null
|
|
177
242
|
// older providers have no lifecycle API — the panel simply omits the card
|
|
@@ -259,10 +324,34 @@ async function handle(ctx, routePath, req, res) {
|
|
|
259
324
|
return
|
|
260
325
|
}
|
|
261
326
|
if (method === 'GET' && path === '/records') {
|
|
262
|
-
const
|
|
327
|
+
const rawScope = url.searchParams.get('scope')
|
|
263
328
|
const query = (url.searchParams.get('q') ?? '').trim().toLowerCase()
|
|
264
|
-
|
|
265
|
-
|
|
329
|
+
// scope 先过同一套规范化:非法 → 400(而不是当成一个陌生 scope 去建文件);
|
|
330
|
+
// 合法但不存在的 scope → 空列表。`peek`/`peekScope`,**绝不通过 store.scope() 创建**。
|
|
331
|
+
let scope = null
|
|
332
|
+
if (rawScope !== null && rawScope.trim() !== '') {
|
|
333
|
+
const normalized = normalizeScopeInput(rawScope)
|
|
334
|
+
if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
|
|
335
|
+
if (normalized.kind === 'all') {
|
|
336
|
+
scope = null // 全部
|
|
337
|
+
} else if (normalized.kind === 'current-session' || normalized.kind === 'current-project') {
|
|
338
|
+
// 面板不在某个 agent 里:按 provider 的读取集合解析('project' → 当前项目键);
|
|
339
|
+
// 解析不出会话时就退化为全部,而不是报错。
|
|
340
|
+
const refs = typeof memory.resolveReadScopes === 'function' ? memory.resolveReadScopes(undefined) : []
|
|
341
|
+
scope = refs.length > 0 ? refs : null
|
|
342
|
+
} else {
|
|
343
|
+
scope = normalized.scope ?? null
|
|
344
|
+
}
|
|
345
|
+
} else {
|
|
346
|
+
scope = null
|
|
347
|
+
}
|
|
348
|
+
const stores = scope === null
|
|
349
|
+
? store.allScopes()
|
|
350
|
+
: (Array.isArray(scope) ? scope : [scope])
|
|
351
|
+
.map((s) => store.peek(s))
|
|
352
|
+
.filter((s) => s !== undefined)
|
|
353
|
+
let records = []
|
|
354
|
+
for (const s of stores) records.push(...collectScope(s))
|
|
266
355
|
if (query) {
|
|
267
356
|
records = records.filter((r) =>
|
|
268
357
|
r.content.toLowerCase().includes(query)
|
|
@@ -321,6 +410,8 @@ async function handle(ctx, routePath, req, res) {
|
|
|
321
410
|
}
|
|
322
411
|
|
|
323
412
|
export const name = 'dsh-memory-panel'
|
|
413
|
+
/** 路由处理器(导出供测试直接调用:围栏、规范化、peek 行为都在这里)。 */
|
|
414
|
+
export { handle as handleRequest }
|
|
324
415
|
export function apply(ctx, config = {}) {
|
|
325
416
|
const routePath = String(config.route || '/memory/api').replace(/\/$/, '')
|
|
326
417
|
try {
|
|
@@ -351,3 +442,6 @@ export function apply(ctx, config = {}) {
|
|
|
351
442
|
console.error('[dsh-memory-panel] apply 意外失败(已吞掉,不影响启动):', error?.message)
|
|
352
443
|
}
|
|
353
444
|
}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
//# sourceURL=source/memory-panel/lib/index.js
|
package/lib/provider/apply.js
CHANGED
|
@@ -14,6 +14,7 @@ import { Service, } from '@deepseek-ai/cordis'
|
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
|
|
17
|
+
|
|
17
18
|
|
|
18
19
|
import { LocalMemoryService, } from './index.js'
|
|
19
20
|
|
|
@@ -111,19 +112,57 @@ export class CordisMemoryService extends Service {
|
|
|
111
112
|
return this.impl.search(query)
|
|
112
113
|
}
|
|
113
114
|
|
|
114
|
-
forget(input
|
|
115
|
+
forget(input ) {
|
|
115
116
|
return this.impl.forget(input)
|
|
116
117
|
}
|
|
117
118
|
|
|
118
119
|
list(input ) {
|
|
119
120
|
return this.impl.list(input)
|
|
120
121
|
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 当前 agent 上下文 → 默认合并读取范围(会话 + 项目 + global,按开关与 key 去重)。
|
|
125
|
+
* 工具与召回注入都走它,保证与 `resolveWriteScope` 是同一套口径。
|
|
126
|
+
*/
|
|
127
|
+
resolveReadScopes(agent ) {
|
|
128
|
+
return this.impl.resolveReadScopes(agent)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 写路径默认 scope(省略 scope 时落到哪)。 */
|
|
132
|
+
resolveWriteScope(agent , requested ) {
|
|
133
|
+
return this.impl.resolveWriteScope(agent, requested)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 作用域清单(名字 + 条数),面板 /status 与 memory_list 共用。 */
|
|
137
|
+
scopeStats() {
|
|
138
|
+
return this.impl.scopeStats()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 作用域清单的一行文字;SCOPE_LIMIT 错误提示里会带上它。 */
|
|
142
|
+
scopeInventory(limit ) {
|
|
143
|
+
return this.impl.scopeInventory(limit)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 把磁盘上已有的 scope 全部发现并加载(读 "all" / 面板枚举前调用;带 3 秒缓存)。 */
|
|
147
|
+
discoverScopes() {
|
|
148
|
+
return this.impl.discoverScopes()
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 当前进程已知的 scope 键(只读,不触发发现)。 */
|
|
152
|
+
knownScopes() {
|
|
153
|
+
return this.impl.knownScopes()
|
|
154
|
+
}
|
|
121
155
|
}
|
|
122
156
|
|
|
123
157
|
export function apply(ctx , config = {}) {
|
|
124
158
|
class ScopedMemoryService extends CordisMemoryService {
|
|
125
159
|
constructor(ctx2 ) {
|
|
126
160
|
super(ctx2, config)
|
|
161
|
+
// 写路径默认口径来自 tools 小节(defaultScope 缺省 = 会话);项目键缺省
|
|
162
|
+
// project:<cwd>,即 DSH 进程的启动目录 = 这个 profile 目录。
|
|
163
|
+
const tools = (config ).tools
|
|
164
|
+
this.impl.setProjectScope((tools?.projectScope ?? `project:${process.cwd()}`) )
|
|
165
|
+
if (tools?.defaultScope !== undefined) this.impl.setDefaultScope(tools.defaultScope)
|
|
127
166
|
}
|
|
128
167
|
}
|
|
129
168
|
ctx.plugin(ScopedMemoryService)
|