dsh-feiyu-memgate 0.2.0 → 0.3.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 +15 -3
- package/README.zh.md +15 -3
- package/client/client.js +17 -2
- package/docs/DETAIL.en.md +10 -3
- package/docs/DETAIL.md +10 -3
- package/package.json +1 -1
- package/src/commands.js +9 -4
- package/src/config.js +4 -0
- package/src/gateway.js +143 -0
- package/src/mirror.py +132 -0
- package/src/plugin.js +19 -3
- package/src/tiers.js +36 -4
package/README.md
CHANGED
|
@@ -59,7 +59,7 @@ Every setting can be changed in three ways. They write the same values.
|
|
|
59
59
|
- **The `/memgate` chat command.** See [The /memgate command](#the-memgate-command).
|
|
60
60
|
- **The profile's configuration file.** The row `feiyu-memgate` in the profile's `cordis.patch.yml`. The other two ways save their changes there. A home-level patch or a `--patch` overlay that sets the same row takes precedence, and a change they would override is refused.
|
|
61
61
|
|
|
62
|
-
Most settings take effect at once. A change of `gateway.mode`, `gateway.python`, `gateway.dataDir`, the retrieval tier or the endpoint settings in use, `advanced.profile`, `advanced.dailyWrites`, `advanced.redaction`, `advanced.newerFirst` or `advanced.forgetting` restarts the gateway. The count of the daily cap starts again then. Switching a module off removes what it registered in DSH. The gateway runs only while at least one of `modules.autoRecall`, `modules.rememberTool`, `modules.searchTool` and `modules.autoCapture` is on.
|
|
62
|
+
Most settings take effect at once. A change of `gateway.mode`, `gateway.python`, `gateway.dataDir`, the retrieval tier or the endpoint settings in use, `retrieval.hybrid` (only while it changes what the gateway runs: under `keyword` it does not), `advanced.profile`, `advanced.dailyWrites`, `advanced.redaction`, `advanced.newerFirst` or `advanced.forgetting` restarts the gateway. The count of the daily cap starts again then. Switching a module off removes what it registered in DSH. The gateway runs only while at least one of `modules.autoRecall`, `modules.rememberTool`, `modules.searchTool` and `modules.autoCapture` is on.
|
|
63
63
|
|
|
64
64
|
| Setting | What it does | Default | Notes |
|
|
65
65
|
|---|---|---|---|
|
|
@@ -71,6 +71,7 @@ Most settings take effect at once. A change of `gateway.mode`, `gateway.python`,
|
|
|
71
71
|
| `modules.commands` | Register the `/memgate` chat command. | on | Needs a host that has chat commands. |
|
|
72
72
|
| `modules.migrateOnTierChange` | When a vector tier becomes active, copy the keyword memories into its store in the background. | on | See [Semantic search](#semantic-search-optional-add-on). |
|
|
73
73
|
| `retrieval.tier` | How the bundled gateway finds memories: `auto`, `keyword`, `endpoint` or `local`. | `auto` | `/memgate use <tier>`. Table below. |
|
|
74
|
+
| `retrieval.hybrid` | Also search by keyword in the vector tiers and fuse the results. | off | `/memgate set retrieval.hybrid on`. Applies to `endpoint`, `local` and `auto` while it resolves to `local`; under `keyword` it does nothing. Same vector store file, plus a keyword index file. See [Hybrid search](#hybrid-search-optional). |
|
|
74
75
|
| `retrieval.url` | `endpoint` tier: base URL of an OpenAI-compatible embeddings API, for example `http://127.0.0.1:11434/v1`. | empty | Must start with `http://` or `https://`. |
|
|
75
76
|
| `retrieval.model` | `endpoint` tier: the embeddings model name. | empty | A different model uses a new, empty store. |
|
|
76
77
|
| `retrieval.apiKey` | `endpoint` tier: the API key, if the endpoint needs one. | empty | Secret. Write-only: the settings page never shows it again. |
|
|
@@ -101,6 +102,16 @@ Each tier keeps its own store file in the data folder. `/memgate tiers` lists th
|
|
|
101
102
|
|
|
102
103
|
When the add-on goes away or its model changes, an `auto` or `local` gateway restarts with the new state.
|
|
103
104
|
|
|
105
|
+
### Hybrid search (optional)
|
|
106
|
+
|
|
107
|
+
With `retrieval.hybrid` on, a vector tier asks two searches for every query and fuses the results: keyword search (which is exact when the question shares words with the memory) and vector search (which finds reworded memories). It is off by default.
|
|
108
|
+
|
|
109
|
+
- **When it applies.** To `endpoint`, to `local`, and to `auto` while it resolves to `local`. Under `keyword` the switch does nothing, and changing it does not restart the gateway. It applies to the bundled gateway only; a gateway you run yourself follows its own configuration.
|
|
110
|
+
- **Which files it uses.** The same vector store file as the tier without it (`memories-endpoint-<model>.db` or `memories-local-<model>-<hash>.db`, which keeps holding every memory), plus a keyword index file next to it, `memories-<store id>-keywords.db`. The forgetting files and the copy progress file keep the names they have without hybrid, because it is the same set of memories.
|
|
111
|
+
- **Switching it on or off loses no memory.** The vector file is the record; the keyword index is rebuilt from it. Memories saved, forgotten or copied while hybrid was off are picked up or dropped in the index at the next gateway start: before the gateway starts, the plugin brings the index in line with the vector file (it adds what the index lacks and removes what the vector file no longer has). **The first start after switching it on can therefore take a while on a large store** (the keyword index is built from the stored texts, with no embeddings request; on the Windows test machine about 2 seconds for 1,000 memories and 12 seconds for 5,000); the update stops after 60 seconds and continues at the next start, and the gateway starts either way. If the update fails, the gateway still starts with the index as it is, and the log (`gateway.log`) says how many memories were added and removed, never which.
|
|
112
|
+
- **Copying keyword memories into the vector store** works as without hybrid, and a memory copied is written to both.
|
|
113
|
+
- **What was measured, and its limit.** In the gateway's own benchmark with the bge-m3 model, the hybrid configuration reached these Hit@5 values (the share of questions for which a right memory is among the top five found): on PerLTQA (Chinese, 8,588 questions) 95.0% for hybrid, 87.3% for keyword and 83.3% for vector; on LoCoMo (English, 1,535 questions) 58.0% for hybrid, 51.6% for vector and 36.4% for keyword; on the project's own question set (160 questions) 96.7% for hybrid and 98.3% for vector, so there it did not help. The score lines of the hybrid configuration were chosen with bge-m3; with other models the same lines are used and were not measured. Nothing was measured again for this plugin or for the way it combines the two stores. The tables are in the repository's [benchmark on public datasets](https://github.com/N0rmal-114/feiyu-memgate/blob/main/README.en.md#public-datasets-perltqa-and-locomo).
|
|
114
|
+
|
|
104
115
|
### External gateway
|
|
105
116
|
|
|
106
117
|
With `gateway.mode` set to `external`, the plugin does not start anything. It talks to the gateway at `external.url` with the client token in `external.token`. If either is empty, memory is off and a warning is logged. `retrieval.*`, `gateway.python`, `gateway.dataDir`, the copy into a vector store and the gateway rules under `advanced` (`profile`, `dailyWrites`, `redaction`, `newerFirst`, `forgetting`) do nothing in this mode: the gateway follows its own configuration. `advanced.recallLimit`, `advanced.recallTimeoutMs` and `advanced.language` still apply.
|
|
@@ -193,6 +204,7 @@ The setup survives closing or reloading the page. After a DSH restart in the mid
|
|
|
193
204
|
|---|---|
|
|
194
205
|
| `memories.db` | The keyword store. |
|
|
195
206
|
| `memories-endpoint-<model>.db`, `memories-local-<model>-<hash>.db` | The stores of the vector tiers, one per model. |
|
|
207
|
+
| `memories-<store id>-keywords.db` | Only with `retrieval.hybrid` on: the keyword index next to the vector store of the same id. It holds the same memories and can be rebuilt from the vector store. |
|
|
196
208
|
| `migration-<store id>.json` | Copy progress for a vector store: counts and references, no texts. |
|
|
197
209
|
| `model-setup.json` | Progress of a model setup started from the settings page or `/memgate install`: the model, its step, the install scripts waiting for your decision and the last failure code. |
|
|
198
210
|
| `forgetting-ledger-<store id>.db`, `forgetting-archive-<store id>.db` | Only with forgetting on. The archive holds the full text of removed memories, unencrypted. |
|
|
@@ -216,9 +228,9 @@ The setup survives closing or reloading the page. After a DSH restart in the mid
|
|
|
216
228
|
- **One store per tier.** The plugin uses a single gateway client and a single store per tier. It does not keep separate memories per user or per project.
|
|
217
229
|
- **The settings page depends on host UI interfaces that are still changing.** The plugin works without it: every setting can be changed with `/memgate` or in the profile file.
|
|
218
230
|
- **Forgetting is experimental** and has been tested only in simulations.
|
|
219
|
-
- **Real-host testing.** Tested in the installed DeepSeek Harness 0.2.2-rc.1 on Windows 11 with an isolated profile: the plugin loads, the bundled gateway starts with a Python from PATH, the settings page renders and saves, the status and model routes answer only to the owner session, the chat command works, and with the add-on and bge-small-zh-v1.5 the local tier is used and reworded questions find their memories. Installing the add-on from npm through the settings page was run too, with the dependency's install script refused: the add-on is installed and enabled, the model is downloaded and the local tier takes over (the path that allows the script was not run). Not tested: macOS and Linux desktops, the Desktop application's own window (the web profile of the same host was used), and a conversation with a real model (automatic recall and the two tools were exercised in tests and against the gateway, not in a live chat).
|
|
231
|
+
- **Real-host testing.** Tested in the installed DeepSeek Harness 0.2.2-rc.1 on Windows 11 with an isolated profile: the plugin loads, the bundled gateway starts with a Python from PATH, the settings page renders and saves, the status and model routes answer only to the owner session, the chat command works, and with the add-on and bge-small-zh-v1.5 the local tier is used and reworded questions find their memories. Installing the add-on from npm through the settings page was run too, with the dependency's install script refused: the add-on is installed and enabled, the model is downloaded and the local tier takes over (the path that allows the script was not run). The hybrid switch of 0.3.0 was also run in an isolated profile, with a stand-in embeddings service on the local machine, not a real model: with the `endpoint` tier and `retrieval.hybrid` on, the gateway starts with a hybrid store and the memories of the keyword store are copied into both the vector file and the keyword index; after one memory was removed from the vector file while the host was stopped, the next start removed it from the index too. In that profile, where the plugin is linked from its source folder, the settings form says the settings are not available (0.2.0 behaves the same there), so the new switch was not seen in the form and was set through the profile file. Not tested: macOS and Linux desktops, the Desktop application's own window (the web profile of the same host was used), and a conversation with a real model (automatic recall and the two tools were exercised in tests and against the gateway, not in a live chat).
|
|
220
232
|
- **Other versions and systems.** Other DSH versions in the accepted ranges, other operating systems and other Python builds are not covered by a real-host test.
|
|
221
|
-
- This is version 0.
|
|
233
|
+
- This is version 0.3.0. It adds the optional `retrieval.hybrid` switch (off by default); no default changed.
|
|
222
234
|
|
|
223
235
|
## Troubleshooting
|
|
224
236
|
|
package/README.zh.md
CHANGED
|
@@ -59,7 +59,7 @@ dsh plugin --profile desktop add dsh-feiyu-memgate
|
|
|
59
59
|
- **`/memgate` 聊天命令。** 见[/memgate 命令](#memgate-命令)。
|
|
60
60
|
- **profile 的配置文件。** profile 的 `cordis.patch.yml` 里的 `feiyu-memgate` 这一行。另外两种方式也把改动存在这里。家目录级的补丁或 `--patch` 覆盖层如果设置了同一行,它们优先;会被它们盖掉的改动会被拒绝。
|
|
61
61
|
|
|
62
|
-
多数设置立即生效。改动 `gateway.mode`、`gateway.python`、`gateway.dataDir`、检索方式或正在使用的向量接口设置、`advanced.profile`、`advanced.dailyWrites`、`advanced.redaction`、`advanced.newerFirst`、`advanced.forgetting` 会重启网关,每日写入上限的计数随之重新开始。关掉一项功能,它在 DSH 里注册的东西就被移除。只有 `modules.autoRecall`、`modules.rememberTool`、`modules.searchTool`、`modules.autoCapture` 中至少有一个开着时,网关才会运行。
|
|
62
|
+
多数设置立即生效。改动 `gateway.mode`、`gateway.python`、`gateway.dataDir`、检索方式或正在使用的向量接口设置、`retrieval.hybrid`(只在它改变网关实际运行的内容时;在 `keyword` 下不会)、`advanced.profile`、`advanced.dailyWrites`、`advanced.redaction`、`advanced.newerFirst`、`advanced.forgetting` 会重启网关,每日写入上限的计数随之重新开始。关掉一项功能,它在 DSH 里注册的东西就被移除。只有 `modules.autoRecall`、`modules.rememberTool`、`modules.searchTool`、`modules.autoCapture` 中至少有一个开着时,网关才会运行。
|
|
63
63
|
|
|
64
64
|
| 设置 | 作用 | 默认值 | 备注 |
|
|
65
65
|
|---|---|---|---|
|
|
@@ -71,6 +71,7 @@ dsh plugin --profile desktop add dsh-feiyu-memgate
|
|
|
71
71
|
| `modules.commands` | 注册 `/memgate` 聊天命令。 | 开 | 需要支持聊天命令的宿主。 |
|
|
72
72
|
| `modules.migrateOnTierChange` | 向量检索启用时,在后台把关键词记忆复制到它的存储里。 | 开 | 见[语义检索](#语义检索可选插件)。 |
|
|
73
73
|
| `retrieval.tier` | 自带网关怎么查找记忆:`auto`、`keyword`、`endpoint` 或 `local`。 | `auto` | `/memgate use <方式>`。见下表。 |
|
|
74
|
+
| `retrieval.hybrid` | 向量检索下同时用关键词检索,结果合并。 | 关 | `/memgate set retrieval.hybrid on`。用于 `endpoint`、`local`,以及 `auto` 选到 `local` 的时候;在 `keyword` 下不起作用。向量存储文件不变,旁边多一个关键词索引文件。见[混合检索](#混合检索可选)。 |
|
|
74
75
|
| `retrieval.url` | `endpoint` 方式:OpenAI 兼容向量接口的基础地址,例如 `http://127.0.0.1:11434/v1`。 | 空 | 必须以 `http://` 或 `https://` 开头。 |
|
|
75
76
|
| `retrieval.model` | `endpoint` 方式:向量模型的名字。 | 空 | 换模型会用一个新的空存储。 |
|
|
76
77
|
| `retrieval.apiKey` | `endpoint` 方式:接口需要密钥时填写。 | 空 | 秘密。只写不读:设置页面保存后不再显示。 |
|
|
@@ -101,6 +102,16 @@ dsh plugin --profile desktop add dsh-feiyu-memgate
|
|
|
101
102
|
|
|
102
103
|
向量插件消失或它的模型变了,`auto` 或 `local` 下的网关会按新状态重启。
|
|
103
104
|
|
|
105
|
+
### 混合检索(可选)
|
|
106
|
+
|
|
107
|
+
`retrieval.hybrid` 打开后,向量检索方式对每个查询同时做两种检索并合并结果:关键词检索(问题和记忆用词相同时最准)和向量检索(能找到换了说法的记忆)。默认关闭。
|
|
108
|
+
|
|
109
|
+
- **什么时候起作用。** 用于 `endpoint`、`local`,以及 `auto` 选到 `local` 的时候。在 `keyword` 下这个开关不起作用,改它也不会重启网关。它只用于自带网关;自己运行的网关按它自己的配置。
|
|
110
|
+
- **用哪些文件。** 向量存储文件和不开它时相同(`memories-endpoint-<model>.db` 或 `memories-local-<model>-<hash>.db`,仍然保存全部记忆),旁边多一个关键词索引文件 `memories-<store id>-keywords.db`。遗忘相关文件和复制进度文件的名字和不开混合时一样,因为这是同一批记忆。
|
|
111
|
+
- **开或关都不会丢记忆。** 向量文件是记录,关键词索引从它重建。混合关闭期间保存、遗忘或复制的记忆,在下一次网关启动时补进索引或从索引里去掉:网关启动之前,插件先让索引和向量文件一致(补上索引缺的,去掉向量文件里已经没有的)。**所以开启后的第一次启动,记忆很多时可能要等一会儿**(索引由已存的文本建立,不需要向量接口;在测试用的 Windows 机器上,1,000 条约 2 秒,5,000 条约 12 秒);这一步最多 60 秒,没做完下次启动接着做,网关照常启动。更新失败时,网关仍用现有的索引启动;日志(`gateway.log`)只写补了几条、去掉了几条,不写是哪几条。
|
|
112
|
+
- **把关键词记忆复制到向量存储**和不开混合时一样,复制的记忆会同时写入两边。
|
|
113
|
+
- **测量依据和限度。** 在网关自己的基准里,用 bge-m3 模型时,混合配置的 Hit@5(前五条里有一条正确记忆的问题所占比例)如下:PerLTQA(中文,8,588 道题)混合 95.0%、关键词 87.3%、向量 83.3%;LoCoMo(英文,1,535 道题)混合 58.0%、向量 51.6%、关键词 36.4%;项目自己的题库(160 道题)混合 96.7%、向量 98.3%,这里混合没有带来提升。混合配置的分数线是用 bge-m3 选的;换别的模型用同一组分数线,没有测量过。这次没有为本插件或它组合两个存储的方式重新测量。表格见仓库 README 的[公开数据集](https://github.com/N0rmal-114/feiyu-memgate/blob/main/README.md#公开数据集perltqa-与-locomo)一节。
|
|
114
|
+
|
|
104
115
|
### 外部网关
|
|
105
116
|
|
|
106
117
|
`gateway.mode` 设为 `external` 时,插件什么都不启动,只用 `external.token` 里的客户端令牌连接 `external.url` 的网关。两项有一项为空,记忆功能就关闭,并在日志里记一条警告。这个模式下,`retrieval.*`、`gateway.python`、`gateway.dataDir`、复制到向量存储,以及 `advanced` 里的网关规则(`profile`、`dailyWrites`、`redaction`、`newerFirst`、`forgetting`)都不起作用:网关按它自己的配置运行。`advanced.recallLimit`、`advanced.recallTimeoutMs`、`advanced.language` 仍然有效。
|
|
@@ -193,6 +204,7 @@ profile 的 `cordis.patch.yml` 里,一行会整个替换同一个 `id` 那一
|
|
|
193
204
|
|---|---|
|
|
194
205
|
| `memories.db` | 关键词存储。 |
|
|
195
206
|
| `memories-endpoint-<model>.db`、`memories-local-<model>-<hash>.db` | 向量检索的存储,每个模型一个。 |
|
|
207
|
+
| `memories-<store id>-keywords.db` | 只在 `retrieval.hybrid` 打开时有:同一个存储 id 的向量存储旁边的关键词索引。它保存同样的记忆,可以从向量存储重建。 |
|
|
196
208
|
| `migration-<store id>.json` | 向量存储的复制进度:只有数量和引用,没有文本。 |
|
|
197
209
|
| `model-setup.json` | 从设置页面或 `/memgate install` 开始的模型设置进度:模型、进行到哪一步、等你决定的安装脚本、上次失败的代码。 |
|
|
198
210
|
| `forgetting-ledger-<store id>.db`、`forgetting-archive-<store id>.db` | 只在打开遗忘时出现。存档里是被删记忆的全文,没有加密。 |
|
|
@@ -216,9 +228,9 @@ profile 的 `cordis.patch.yml` 里,一行会整个替换同一个 `id` 那一
|
|
|
216
228
|
- **每种检索方式只有一个存储。** 插件只用一个网关客户端和每种方式一个存储,不按用户或项目分开保存记忆。
|
|
217
229
|
- **设置页面依赖宿主里仍在变化的界面接口。** 没有它插件照样能用:每项设置都能用 `/memgate` 或在 profile 文件里修改。
|
|
218
230
|
- **遗忘是实验性的**,只在模拟里测过。
|
|
219
|
-
- **真实环境测试。** 在 Windows 11 上已安装的 DeepSeek Harness 0.2.2-rc.1 里,用一个隔离的配置测过:插件能加载,自带网关用 PATH 上的 Python 启动,设置页面能显示和保存,状态接口和模型接口只回应所有者的会话,聊天命令可用;装上向量插件和 bge-small-zh-v1.5 后用的是 local 检索方式,换了说法的问题能找到对应的记忆。通过设置页面从 npm 安装向量插件也测过,测的是拒绝依赖的安装脚本这条路:向量插件装好并启用,模型下载完成,检索方式换成 local
|
|
231
|
+
- **真实环境测试。** 在 Windows 11 上已安装的 DeepSeek Harness 0.2.2-rc.1 里,用一个隔离的配置测过:插件能加载,自带网关用 PATH 上的 Python 启动,设置页面能显示和保存,状态接口和模型接口只回应所有者的会话,聊天命令可用;装上向量插件和 bge-small-zh-v1.5 后用的是 local 检索方式,换了说法的问题能找到对应的记忆。通过设置页面从 npm 安装向量插件也测过,测的是拒绝依赖的安装脚本这条路:向量插件装好并启用,模型下载完成,检索方式换成 local(允许脚本的那条路没有跑过)。0.3.0 的混合检索也在一个隔离的配置里跑过,向量接口用的是本机的一个替身服务,不是真实模型:`endpoint` 方式打开 `retrieval.hybrid` 后,网关以混合存储启动,关键词存储里的记忆被复制到向量文件和关键词索引两边;宿主停止时从向量文件里删掉一条,下次启动索引同步去掉了这一条。在这个从源码目录链接插件的配置里,设置页面的表单显示“设置现在不可用”(0.2.0 在这里也是这样),所以新开关在表单里的显示没有实际看到,开关是通过 profile 文件设置的。没有测过:macOS 和 Linux 桌面、桌面应用自己的窗口(用的是同一宿主的 web 配置)、和真实模型的对话(自动召回和两个工具只在测试里和对着网关测过,没有在实际聊天里用过)。
|
|
220
232
|
- **其他版本和系统。** 可接受范围内的其他 DSH 版本、其他操作系统和其他 Python 构建,都没有在真实宿主里测过。
|
|
221
|
-
- 当前版本是 0.
|
|
233
|
+
- 当前版本是 0.3.0。它新增了可选的 `retrieval.hybrid` 开关(默认关闭),没有改任何默认值。
|
|
222
234
|
|
|
223
235
|
## 故障排查
|
|
224
236
|
|
package/client/client.js
CHANGED
|
@@ -202,6 +202,19 @@ window.__ModuleLoader__.load({ id: 'dsh-feiyu-memgate', factory: (require) => {
|
|
|
202
202
|
"zh": "auto:dsh-feiyu-memgate-embed 插件的模型就绪时用 local,否则用 keyword。"
|
|
203
203
|
}
|
|
204
204
|
},
|
|
205
|
+
{
|
|
206
|
+
"key": "hybrid",
|
|
207
|
+
"kind": "boolean",
|
|
208
|
+
"default": false,
|
|
209
|
+
"label": {
|
|
210
|
+
"en": "Combine with keyword search (hybrid)",
|
|
211
|
+
"zh": "同时用关键词检索(混合)"
|
|
212
|
+
},
|
|
213
|
+
"help": {
|
|
214
|
+
"en": "Applies to the vector tiers (endpoint, local, and auto while it resolves to local); under keyword it does nothing. Keyword and vector search are both asked and their results fused. It uses the same vector store file as the tier without it, plus a keyword index file next to it, so switching it on or off loses no memory.",
|
|
215
|
+
"zh": "用于向量检索(endpoint、local,以及 auto 选到 local 的时候);在 keyword 下不起作用。关键词检索和向量检索同时查,结果合并。它用的向量存储文件和不开它时相同,旁边多一个关键词索引文件,所以开或关都不会丢记忆。"
|
|
216
|
+
}
|
|
217
|
+
},
|
|
205
218
|
{
|
|
206
219
|
"key": "url",
|
|
207
220
|
"kind": "string",
|
|
@@ -549,6 +562,7 @@ window.__ModuleLoader__.load({ id: 'dsh-feiyu-memgate', factory: (require) => {
|
|
|
549
562
|
pythonNone: 'not found (3.11 or newer needed)',
|
|
550
563
|
pythonUnknown: 'not checked',
|
|
551
564
|
retrievalExternal: 'decided by the external gateway',
|
|
565
|
+
hybridWord: 'keyword (hybrid)',
|
|
552
566
|
notInstalled: 'not installed',
|
|
553
567
|
memories: '{count} memories',
|
|
554
568
|
countUnknown: 'count unavailable',
|
|
@@ -615,6 +629,7 @@ window.__ModuleLoader__.load({ id: 'dsh-feiyu-memgate', factory: (require) => {
|
|
|
615
629
|
pythonNone: '没有找到(需要 3.11 或更新)',
|
|
616
630
|
pythonUnknown: '未检查',
|
|
617
631
|
retrievalExternal: '由外部网关决定',
|
|
632
|
+
hybridWord: '关键词(混合)',
|
|
618
633
|
notInstalled: '未安装',
|
|
619
634
|
memories: '{count} 条记忆',
|
|
620
635
|
countUnknown: '条数未知',
|
|
@@ -777,10 +792,10 @@ window.__ModuleLoader__.load({ id: 'dsh-feiyu-memgate', factory: (require) => {
|
|
|
777
792
|
const p = data.python
|
|
778
793
|
rows.push([t('python'), !p ? t('pythonUnknown') : p.found ? p.version + ' (' + p.source + ') · ' + p.executable : t('pythonNone')])
|
|
779
794
|
const r = data.retrieval || {}
|
|
780
|
-
rows.push([t('retrieval'), r.setting + (r.active ? ' → ' + r.active : '')])
|
|
795
|
+
rows.push([t('retrieval'), r.setting + (r.active ? ' → ' + r.active + (r.hybrid && r.hybrid.active ? ' + ' + t('hybridWord') : '') : '')])
|
|
781
796
|
if (data.store) {
|
|
782
797
|
const count = data.store.count === null || data.store.count === undefined ? t('countUnknown') : t('memories', { count: data.store.count })
|
|
783
|
-
rows.push([t('store'), data.store.type + ' · ' + data.store.file + ' · ' + count])
|
|
798
|
+
rows.push([t('store'), data.store.type + ' · ' + data.store.file + (data.store.keywordFile ? ' + ' + data.store.keywordFile : '') + ' · ' + count])
|
|
784
799
|
}
|
|
785
800
|
} else {
|
|
786
801
|
rows.push([t('retrieval'), t('retrievalExternal')])
|
package/docs/DETAIL.en.md
CHANGED
|
@@ -38,6 +38,7 @@ Every setting can be changed in three places: this plugin's settings page on the
|
|
|
38
38
|
| `modules.promptSection` | The fixed section in the system prompt | on |
|
|
39
39
|
| `modules.autoCapture` | Store your messages after each turn | off |
|
|
40
40
|
| `retrieval.tier` | How memories are found: `auto`, `keyword`, `endpoint`, `local` | `auto` |
|
|
41
|
+
| `retrieval.hybrid` | Also search by keyword in the vector tiers and fuse the results (no effect under `keyword`) | off |
|
|
41
42
|
| `advanced.recallLimit` | Most memories added per turn | 5 |
|
|
42
43
|
| `advanced.profile` | `broad`: more memories per turn, misses less, more noise, faster context growth; `precise`: about one close match per turn | `broad` |
|
|
43
44
|
| `advanced.dailyWrites` | Most memories written per day, 0 for no cap | 50 |
|
|
@@ -58,10 +59,16 @@ The section "Local embedding models" on the settings page lists each model's tie
|
|
|
58
59
|
|
|
59
60
|
An add-on that is installed but not switched on (for example after a `dsh plugin add` that stopped at the install script) is switched on through the plugin manager by the same button. Every failure is shown with its reason and what to do; when the engine cannot load (the add-on's status shows `runtime-missing`), on Windows install the runtime named above and restart DSH.
|
|
60
61
|
|
|
62
|
+
## Hybrid search (optional)
|
|
63
|
+
|
|
64
|
+
With `retrieval.hybrid` on, the vector tiers (`endpoint`, `local`, and `auto` while it resolves to `local`) ask keyword search and vector search for every query and fuse the results. Under `keyword` it does nothing. It uses the same vector store file as the tier without it, plus a keyword index file next to it (`memories-<store id>-keywords.db`), so switching it on or off loses no memory: before the gateway starts, the plugin brings the index in line with the vector file, and the first start after switching it on builds the index from the stored texts (at most 60 seconds per start; the gateway starts either way and the next start continues). The forgetting files and the copy progress file keep their names.
|
|
65
|
+
|
|
66
|
+
Measured basis, in the gateway's own benchmark with bge-m3 (nothing was measured again for this plugin): Hit@5 on PerLTQA (Chinese, 8,588 questions) is 95.0% for hybrid, 87.3% for keyword and 83.3% for vector; on LoCoMo (English, 1,535 questions) 58.0% for hybrid, 51.6% for vector and 36.4% for keyword; on the project's own set (160 questions) 96.7% for hybrid and 98.3% for vector. The score lines were chosen with bge-m3; with other models the same lines are used and were not measured. Tables: [benchmark on public datasets](https://github.com/N0rmal-114/feiyu-memgate/blob/main/README.en.md#public-datasets-perltqa-and-locomo).
|
|
67
|
+
|
|
61
68
|
## Data and privacy
|
|
62
69
|
|
|
63
70
|
- In the default mode everything stays on your machine. The gateway listens only on a random port of `127.0.0.1`, and its token is made anew at each start and kept in memory only. Something is downloaded only when you install the add-on or a model from the settings page or with `/memgate install`: the host's plugin manager fetches the add-on from npm, and the add-on fetches the model.
|
|
64
|
-
- Memories are plain SQLite files; the plugin does not encrypt them. To delete all data, quit DSH and delete `<DSH home>/data/feiyu-memgate/` (or the folder in `gateway.dataDir`, if you changed it).
|
|
71
|
+
- Memories are plain SQLite files; the plugin does not encrypt them. With `retrieval.hybrid` on there is one more, the keyword index `memories-<store id>-keywords.db`, which holds the same texts. To delete all data, quit DSH and delete `<DSH home>/data/feiyu-memgate/` (or the folder in `gateway.dataDir`, if you changed it).
|
|
65
72
|
- With the `endpoint` tier, the text of every saved memory and every recall query go to the embeddings API you configured.
|
|
66
73
|
- Recalled memories are part of the prompt and go to the model service of the conversation.
|
|
67
74
|
|
|
@@ -72,8 +79,8 @@ An add-on that is installed but not switched on (for example after a `dsh plugin
|
|
|
72
79
|
- Only memories the model chose to save exist, unless automatic capture is on.
|
|
73
80
|
- The daily write cap is counted in memory, per DSH process, and starts again when the gateway restarts.
|
|
74
81
|
- The settings page depends on host UI interfaces that are still changing; without it, every setting can be changed with `/memgate` or in the profile file.
|
|
75
|
-
- Real-host testing. Tested in the installed DeepSeek Harness 0.2.2-rc.1 on Windows 11 with an isolated profile: the plugin loads, the bundled gateway starts with a Python from PATH, the settings page renders and saves, the status and model routes answer only to the owner session, the chat command works, and with the add-on and bge-small-zh-v1.5 the local tier is used and reworded questions find their memories. Installing the add-on from npm through the settings page was run too, with the dependency's install script refused: the add-on is installed and enabled, the model is downloaded and the local tier takes over (the path that allows the script was not run). Not tested: macOS and Linux desktops, the Desktop application's own window (the web profile of the same host was used), and a conversation with a real model (automatic recall and the two tools were exercised in tests and against the gateway, not in a live chat).
|
|
76
|
-
- This is version 0.
|
|
82
|
+
- Real-host testing. Tested in the installed DeepSeek Harness 0.2.2-rc.1 on Windows 11 with an isolated profile: the plugin loads, the bundled gateway starts with a Python from PATH, the settings page renders and saves, the status and model routes answer only to the owner session, the chat command works, and with the add-on and bge-small-zh-v1.5 the local tier is used and reworded questions find their memories. Installing the add-on from npm through the settings page was run too, with the dependency's install script refused: the add-on is installed and enabled, the model is downloaded and the local tier takes over (the path that allows the script was not run). The hybrid switch of 0.3.0 was also run in an isolated profile, with a stand-in embeddings service on the local machine, not a real model: with the `endpoint` tier and `retrieval.hybrid` on, the gateway starts with a hybrid store and the memories of the keyword store are copied into both the vector file and the keyword index; after one memory was removed from the vector file while the host was stopped, the next start removed it from the index too. In that profile, where the plugin is linked from its source folder, the settings form says the settings are not available (0.2.0 behaves the same there), so the new switch was not seen in the form and was set through the profile file. Not tested: macOS and Linux desktops, the Desktop application's own window (the web profile of the same host was used), and a conversation with a real model (automatic recall and the two tools were exercised in tests and against the gateway, not in a live chat).
|
|
83
|
+
- This is version 0.3.0. It adds the optional `retrieval.hybrid` switch (off by default); no default changed.
|
|
77
84
|
|
|
78
85
|
## Troubleshooting
|
|
79
86
|
|
package/docs/DETAIL.md
CHANGED
|
@@ -38,6 +38,7 @@ dsh plugin --profile <name> add dsh-feiyu-memgate
|
|
|
38
38
|
| `modules.promptSection` | 系统提示词里的固定说明 | 开 |
|
|
39
39
|
| `modules.autoCapture` | 每轮结束后把你的消息直接存入记忆 | 关 |
|
|
40
40
|
| `retrieval.tier` | 检索方式:`auto`、`keyword`、`endpoint`、`local` | `auto` |
|
|
41
|
+
| `retrieval.hybrid` | 向量检索下同时用关键词检索并合并结果(`keyword` 下不起作用) | 关 |
|
|
41
42
|
| `advanced.recallLimit` | 每轮最多加入几条记忆 | 5 |
|
|
42
43
|
| `advanced.profile` | `broad` 每轮条数多、漏得少、杂讯也多,上下文涨得更快;`precise` 每轮约一条、更贴题 | `broad` |
|
|
43
44
|
| `advanced.dailyWrites` | 每天最多写入几条,0 为不限 | 50 |
|
|
@@ -58,10 +59,16 @@ dsh plugin --profile <name> add dsh-feiyu-memgate
|
|
|
58
59
|
|
|
59
60
|
已经装了但没有启用的向量插件(例如停在安装脚本上的 `dsh plugin add` 之后),按钮会通过插件管理器启用它。各种失败都会说明原因和怎么办;引擎加载不了(状态显示 `runtime-missing`)时,在 Windows 上安装上述运行库后重启 DSH。
|
|
60
61
|
|
|
62
|
+
## 混合检索(可选)
|
|
63
|
+
|
|
64
|
+
`retrieval.hybrid` 打开后,向量检索方式(`endpoint`、`local`,以及 `auto` 选到 `local` 的时候)对每个查询同时做关键词检索和向量检索,并合并结果;在 `keyword` 下不起作用。它用的向量存储文件和不开它时相同,旁边多一个关键词索引文件(`memories-<store id>-keywords.db`),所以开或关都不会丢记忆:网关启动之前,插件先让索引和向量文件一致,开启后的第一次启动由已存的文本建立索引(每次启动最多 60 秒,网关照常启动,下次启动接着做)。遗忘相关文件和复制进度文件的名字不变。
|
|
65
|
+
|
|
66
|
+
测量依据,来自网关自己的基准(用 bge-m3;这次没有为本插件重新测量):Hit@5 在 PerLTQA(中文,8,588 道题)上混合 95.0%、关键词 87.3%、向量 83.3%;在 LoCoMo(英文,1,535 道题)上混合 58.0%、向量 51.6%、关键词 36.4%;在项目自己的题库(160 道题)上混合 96.7%、向量 98.3%。分数线是用 bge-m3 选的,换别的模型用同一组分数线,没有测量过。表格见[公开数据集](https://github.com/N0rmal-114/feiyu-memgate/blob/main/README.md#公开数据集perltqa-与-locomo)。
|
|
67
|
+
|
|
61
68
|
## 数据与隐私
|
|
62
69
|
|
|
63
70
|
- 默认模式下一切都留在你的电脑上。网关只监听 `127.0.0.1` 的随机端口,令牌每次启动随机生成,只在内存里。只有你在设置页面或用 `/memgate install` 安装向量插件或模型时才会下载:宿主的插件管理器从 npm 取向量插件,向量插件下载模型。
|
|
64
|
-
- 记忆是普通的 SQLite
|
|
71
|
+
- 记忆是普通的 SQLite 文件,插件不加密。打开 `retrieval.hybrid` 时还多一个关键词索引 `memories-<store id>-keywords.db`,里面是同样的文本。删除全部数据:退出 DSH,删除 `<DSH home>/data/feiyu-memgate/`(改过 `gateway.dataDir` 的删那个文件夹)。
|
|
65
72
|
- `endpoint` 方式下,每条保存的记忆的文本和每次召回的查询,都会发给你配置的向量接口。
|
|
66
73
|
- 召回的记忆是提示词的一部分,会发给这段对话使用的模型服务。
|
|
67
74
|
|
|
@@ -72,8 +79,8 @@ dsh plugin --profile <name> add dsh-feiyu-memgate
|
|
|
72
79
|
- 只有模型选择保存的记忆才存在,除非打开自动记录。
|
|
73
80
|
- 每日写入上限在内存里计数,按 DSH 进程计,网关重启后重新开始。
|
|
74
81
|
- 设置页面依赖宿主里仍在变化的界面接口;没有它,用 `/memgate` 或 profile 文件也能改全部设置。
|
|
75
|
-
- 真实环境测试:在 Windows 11 上已安装的 DeepSeek Harness 0.2.2-rc.1 里,用一个隔离的配置测过:插件能加载,自带网关用 PATH 上的 Python 启动,设置页面能显示和保存,状态接口和模型接口只回应所有者的会话,聊天命令可用;装上向量插件和 bge-small-zh-v1.5 后用的是 local 检索方式,换了说法的问题能找到对应的记忆。通过设置页面从 npm 安装向量插件也测过,测的是拒绝依赖的安装脚本这条路:向量插件装好并启用,模型下载完成,检索方式换成 local
|
|
76
|
-
- 当前版本是 0.
|
|
82
|
+
- 真实环境测试:在 Windows 11 上已安装的 DeepSeek Harness 0.2.2-rc.1 里,用一个隔离的配置测过:插件能加载,自带网关用 PATH 上的 Python 启动,设置页面能显示和保存,状态接口和模型接口只回应所有者的会话,聊天命令可用;装上向量插件和 bge-small-zh-v1.5 后用的是 local 检索方式,换了说法的问题能找到对应的记忆。通过设置页面从 npm 安装向量插件也测过,测的是拒绝依赖的安装脚本这条路:向量插件装好并启用,模型下载完成,检索方式换成 local(允许脚本的那条路没有跑过)。0.3.0 的混合检索也在一个隔离的配置里跑过,向量接口用的是本机的一个替身服务,不是真实模型:`endpoint` 方式打开 `retrieval.hybrid` 后,网关以混合存储启动,关键词存储里的记忆被复制到向量文件和关键词索引两边;宿主停止时从向量文件里删掉一条,下次启动索引同步去掉了这一条。在这个从源码目录链接插件的配置里,设置页面的表单显示“设置现在不可用”(0.2.0 在这里也是这样),所以新开关在表单里的显示没有实际看到,开关是通过 profile 文件设置的。没有测过:macOS 和 Linux 桌面、桌面应用自己的窗口(用的是同一宿主的 web 配置)、和真实模型的对话(自动召回和两个工具只在测试里和对着网关测过,没有在实际聊天里用过)。
|
|
83
|
+
- 当前版本是 0.3.0。它新增了可选的 `retrieval.hybrid` 开关(默认关闭),没有改任何默认值。
|
|
77
84
|
|
|
78
85
|
## 遇到问题
|
|
79
86
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-feiyu-memgate",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "DeepSeek Harness (DSH) plugin for the feiyu-memgate memory gateway: automatic recall, remember and search tools, with a bundled gateway.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
package/src/commands.js
CHANGED
|
@@ -28,7 +28,7 @@ const TEXT = {
|
|
|
28
28
|
' reset <key> return a setting to its default',
|
|
29
29
|
' on <feature> switch a feature on (see the modules.* settings)',
|
|
30
30
|
' off <feature> switch a feature off',
|
|
31
|
-
' tiers the retrieval tiers: availability and what each needs',
|
|
31
|
+
' tiers the retrieval tiers: availability and what each needs, and whether hybrid is on',
|
|
32
32
|
' use <tier> choose the retrieval tier: auto, keyword, endpoint or local',
|
|
33
33
|
' models local embedding models: size, memory, languages, licence and state',
|
|
34
34
|
' install <model> [--accept-licence <licence name>] [--confirm]',
|
|
@@ -71,6 +71,8 @@ const TEXT = {
|
|
|
71
71
|
statusTitle: 'feiyu-memgate status',
|
|
72
72
|
tiersTitle: (setting, active) => `Retrieval tier: ${setting}${active ? `, active: ${active}` : ''}.`,
|
|
73
73
|
tiersExternal: 'Retrieval tiers apply to the managed gateway; an external gateway uses its own configuration.',
|
|
74
|
+
hybridWord: 'keyword (hybrid)',
|
|
75
|
+
hybridLine: (on, active) => `Hybrid (keyword and vector search together, retrieval.hybrid): ${on ? (active ? 'on' : 'on, but it does nothing under the current tier') : 'off'}.`,
|
|
74
76
|
tierLine: (t) => `- ${t.name}: ${t.available ? 'available' : 'not available'}${t.active ? ' (active)' : ''}. Needs: ${t.needs}.${t.missing.length ? ` Missing: ${t.missing.join(', ')}.` : ''}`,
|
|
75
77
|
labels: {
|
|
76
78
|
gateway: 'Gateway', python: 'Python', retrieval: 'Retrieval', store: 'Store', embed: 'Embedding add-on',
|
|
@@ -101,7 +103,7 @@ const TEXT = {
|
|
|
101
103
|
' reset <键> 把一项设置恢复默认',
|
|
102
104
|
' on <功能> 打开一项功能(见 modules.* 设置)',
|
|
103
105
|
' off <功能> 关闭一项功能',
|
|
104
|
-
' tiers
|
|
106
|
+
' tiers 各种检索方式:是否可用,各需要什么,混合检索是否开着',
|
|
105
107
|
' use <方式> 选择检索方式:auto、keyword、endpoint 或 local',
|
|
106
108
|
' models 本地向量模型:大小、内存、语言、许可和状态',
|
|
107
109
|
' install <模型> [--accept-licence <许可名称>] [--confirm]',
|
|
@@ -143,6 +145,8 @@ const TEXT = {
|
|
|
143
145
|
statusTitle: 'feiyu-memgate 状态',
|
|
144
146
|
tiersTitle: (setting, active) => `检索方式设置:${setting}${active ? `,正在使用:${active}` : ''}。`,
|
|
145
147
|
tiersExternal: '检索方式只用于自带网关;外部网关按它自己的配置。',
|
|
148
|
+
hybridWord: '关键词(混合)',
|
|
149
|
+
hybridLine: (on, active) => `混合检索(关键词和向量一起查,retrieval.hybrid):${on ? (active ? '开' : '已开,但当前检索方式下不起作用') : '关'}。`,
|
|
146
150
|
tierLine: (t) => `- ${t.name}:${t.available ? '可用' : '不可用'}${t.active ? '(正在使用)' : ''}。需要:${t.needs}。${t.missing.length ? `还缺:${t.missing.join('、')}。` : ''}`,
|
|
147
151
|
labels: {
|
|
148
152
|
gateway: '网关', python: 'Python', retrieval: '检索', store: '存储', embed: '向量插件',
|
|
@@ -198,10 +202,10 @@ export function formatStatus(s, lang) {
|
|
|
198
202
|
const p = s.python
|
|
199
203
|
lines.push(`${t.labels.python}: ${!p ? t.pythonUnknown : p.found ? `${p.version} (${p.source}) ${p.executable}` : t.pythonNone}`)
|
|
200
204
|
const r = s.retrieval
|
|
201
|
-
lines.push(`${t.labels.retrieval}: ${r.setting}${r.active ? ` → ${r.active}` : ''}`)
|
|
205
|
+
lines.push(`${t.labels.retrieval}: ${r.setting}${r.active ? ` → ${r.active}${r.hybrid?.active ? ` + ${t.hybridWord}` : ''}` : ''}`)
|
|
202
206
|
if (s.store) {
|
|
203
207
|
const count = s.store.count === null ? t.countUnknown : t.memories(s.store.count)
|
|
204
|
-
lines.push(`${t.labels.store}: ${s.store.type}, ${s.store.file}, ${count}`)
|
|
208
|
+
lines.push(`${t.labels.store}: ${s.store.type}, ${s.store.file}${s.store.keywordFile ? ` + ${s.store.keywordFile}` : ''}, ${count}`)
|
|
205
209
|
}
|
|
206
210
|
}
|
|
207
211
|
const e = s.embed
|
|
@@ -356,6 +360,7 @@ function formatTiers(s, lang) {
|
|
|
356
360
|
const lines = [t.tiersTitle(r.setting, r.active)]
|
|
357
361
|
if (s.gateway.mode === 'external') lines.push(t.tiersExternal)
|
|
358
362
|
for (const tier of r.tiers) lines.push(t.tierLine({ ...tier, needs: TIERS[tier.name].needs[lang] ?? TIERS[tier.name].needs.en }))
|
|
363
|
+
if (r.hybrid && s.gateway.mode !== 'external') lines.push(t.hybridLine(r.hybrid.setting, r.hybrid.active))
|
|
359
364
|
return lines.join('\n')
|
|
360
365
|
}
|
|
361
366
|
|
package/src/config.js
CHANGED
|
@@ -85,6 +85,10 @@ const GROUPS = [
|
|
|
85
85
|
en: 'auto uses local while the dsh-feiyu-memgate-embed add-on has a model ready, and keyword otherwise.',
|
|
86
86
|
zh: 'auto:dsh-feiyu-memgate-embed 插件的模型就绪时用 local,否则用 keyword。',
|
|
87
87
|
} },
|
|
88
|
+
bool('hybrid', false, { en: 'Combine with keyword search (hybrid)', zh: '同时用关键词检索(混合)' }, {
|
|
89
|
+
en: 'Applies to the vector tiers (endpoint, local, and auto while it resolves to local); under keyword it does nothing. Keyword and vector search are both asked and their results fused. It uses the same vector store file as the tier without it, plus a keyword index file next to it, so switching it on or off loses no memory.',
|
|
90
|
+
zh: '用于向量检索(endpoint、local,以及 auto 选到 local 的时候);在 keyword 下不起作用。关键词检索和向量检索同时查,结果合并。它用的向量存储文件和不开它时相同,旁边多一个关键词索引文件,所以开或关都不会丢记忆。',
|
|
91
|
+
}),
|
|
88
92
|
{ key: 'url', kind: 'string', default: '', format: 'url',
|
|
89
93
|
label: { en: 'Endpoint URL', zh: '向量接口地址' },
|
|
90
94
|
help: { en: 'endpoint tier: base URL of an OpenAI-compatible embeddings API, for example http://127.0.0.1:11434/v1.', zh: 'endpoint 方式:OpenAI 兼容向量接口的基础地址,例如 http://127.0.0.1:11434/v1。' } },
|
package/src/gateway.js
CHANGED
|
@@ -380,6 +380,113 @@ export const BOOTSTRAP = [
|
|
|
380
380
|
'sys.exit(main())',
|
|
381
381
|
].join('\n')
|
|
382
382
|
|
|
383
|
+
// ------------------------------------------------------------------ keyword index mirror
|
|
384
|
+
|
|
385
|
+
export const MIRROR_SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), 'mirror.py')
|
|
386
|
+
|
|
387
|
+
const MIRROR_COUNTS = ['added', 'removed', 'remaining']
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Run src/mirror.py once: it brings the keyword index of a hybrid store in line with the vector file
|
|
391
|
+
* (why: see that file). Same shape as the copy in src/migrate.js: a bounded helper, job as one JSON
|
|
392
|
+
* line on stdin, JSON lines on stdout, never kept alive by or outliving the host.
|
|
393
|
+
* python the gateway's interpreter ({ argv })
|
|
394
|
+
* mirror resolveStore().mirror: { keyword, vector }
|
|
395
|
+
* Resolves with { state: 'done' | 'partial' | 'failed' | 'stopped', added?, removed?, remaining?, kind? }.
|
|
396
|
+
* Returns { done: Promise, stop(): Promise }.
|
|
397
|
+
*/
|
|
398
|
+
export function runMirror({
|
|
399
|
+
python, mirror, dataDir, env = process.env, packageDir = PACKAGE_DIR,
|
|
400
|
+
deadlineSeconds = 60, marginSeconds = 30, stopGraceMs = 3000, spawnImpl = spawn,
|
|
401
|
+
}) {
|
|
402
|
+
let child = null
|
|
403
|
+
let stopped = false
|
|
404
|
+
const done = new Promise((resolve) => {
|
|
405
|
+
const job = { package_dir: packageDir, vector: mirror.vector, keyword: mirror.keyword, deadline_seconds: deadlineSeconds }
|
|
406
|
+
try {
|
|
407
|
+
child = spawnImpl(python.argv[0], [...python.argv.slice(1), '-I', '-B', MIRROR_SCRIPT], {
|
|
408
|
+
cwd: dataDir,
|
|
409
|
+
env: { ...scrubbedEnv(env), PYTHONIOENCODING: 'utf-8' },
|
|
410
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
411
|
+
windowsHide: true,
|
|
412
|
+
})
|
|
413
|
+
} catch (error) {
|
|
414
|
+
resolve({ state: 'failed', kind: typeof error?.code === 'string' ? error.code : 'spawn' })
|
|
415
|
+
return
|
|
416
|
+
}
|
|
417
|
+
trackChild(child)
|
|
418
|
+
child.unref?.()
|
|
419
|
+
for (const stream of [child.stdin, child.stdout]) stream?.unref?.()
|
|
420
|
+
child.stdin?.on('error', () => {})
|
|
421
|
+
child.stdin?.write(JSON.stringify(job) + '\n')
|
|
422
|
+
// A run that hangs ends after its own time limit and a margin.
|
|
423
|
+
const guard = setTimeout(() => {
|
|
424
|
+
try {
|
|
425
|
+
child.kill('SIGKILL')
|
|
426
|
+
} catch {
|
|
427
|
+
// already gone
|
|
428
|
+
}
|
|
429
|
+
}, (deadlineSeconds + marginSeconds) * 1000)
|
|
430
|
+
guard.unref?.()
|
|
431
|
+
|
|
432
|
+
let buffer = ''
|
|
433
|
+
let final = null
|
|
434
|
+
child.stdout?.setEncoding?.('utf8')
|
|
435
|
+
child.stdout?.on('data', (chunk) => {
|
|
436
|
+
buffer += chunk
|
|
437
|
+
let at
|
|
438
|
+
while ((at = buffer.indexOf('\n')) >= 0) {
|
|
439
|
+
const line = buffer.slice(0, at)
|
|
440
|
+
buffer = buffer.slice(at + 1)
|
|
441
|
+
let event
|
|
442
|
+
try {
|
|
443
|
+
event = JSON.parse(line)
|
|
444
|
+
} catch {
|
|
445
|
+
continue
|
|
446
|
+
}
|
|
447
|
+
const counts = {}
|
|
448
|
+
for (const key of MIRROR_COUNTS) if (Number.isSafeInteger(event?.[key]) && event[key] >= 0) counts[key] = event[key]
|
|
449
|
+
if (event?.event === 'done' || event?.event === 'partial') final = { state: event.event, ...counts }
|
|
450
|
+
else if (event?.event === 'failed') final = { state: 'failed', kind: /^[A-Za-z]{1,40}$/.test(event.kind) ? event.kind : 'error' }
|
|
451
|
+
}
|
|
452
|
+
})
|
|
453
|
+
let ended = false
|
|
454
|
+
const end = (code) => {
|
|
455
|
+
if (ended) return
|
|
456
|
+
ended = true
|
|
457
|
+
clearTimeout(guard)
|
|
458
|
+
untrackChild(child)
|
|
459
|
+
resolve(stopped ? { state: 'stopped' } : final ?? { state: 'failed', kind: code === null ? 'killed' : `exit${code}` })
|
|
460
|
+
}
|
|
461
|
+
child.once('exit', (code) => end(code))
|
|
462
|
+
child.once('error', () => end(null))
|
|
463
|
+
})
|
|
464
|
+
|
|
465
|
+
return {
|
|
466
|
+
done,
|
|
467
|
+
/** End the run now; what it wrote so far stays (the next run continues). */
|
|
468
|
+
async stop() {
|
|
469
|
+
stopped = true
|
|
470
|
+
const proc = child
|
|
471
|
+
if (!proc || proc.exitCode !== null || proc.signalCode !== null) return
|
|
472
|
+
try {
|
|
473
|
+
proc.stdin?.end()
|
|
474
|
+
} catch {
|
|
475
|
+
// already closed
|
|
476
|
+
}
|
|
477
|
+
const finished = await Promise.race([done.then(() => true), new Promise((r) => setTimeout(r, stopGraceMs, false))])
|
|
478
|
+
if (!finished) {
|
|
479
|
+
try {
|
|
480
|
+
proc.kill('SIGKILL')
|
|
481
|
+
} catch {
|
|
482
|
+
// already gone
|
|
483
|
+
}
|
|
484
|
+
await Promise.race([done, new Promise((r) => setTimeout(r, stopGraceMs))])
|
|
485
|
+
}
|
|
486
|
+
},
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
383
490
|
let instances = 0
|
|
384
491
|
|
|
385
492
|
// ------------------------------------------------------------------ manager
|
|
@@ -407,6 +514,8 @@ export function createGatewayManager({
|
|
|
407
514
|
stableMs = 60000,
|
|
408
515
|
stopGraceMs = 3000,
|
|
409
516
|
spawnImpl = spawn,
|
|
517
|
+
mirrorImpl = runMirror,
|
|
518
|
+
mirrorOptions = {},
|
|
410
519
|
} = {}) {
|
|
411
520
|
const instance = ++instances
|
|
412
521
|
const configFile = path.join(dataDir, `gateway-${process.pid}-${instance}.toml`)
|
|
@@ -421,6 +530,8 @@ export function createGatewayManager({
|
|
|
421
530
|
let python = null
|
|
422
531
|
let log = () => {}
|
|
423
532
|
let waiters = []
|
|
533
|
+
let mirroring = null // the running keyword index update, see src/mirror.py
|
|
534
|
+
let mirrorWarned = false
|
|
424
535
|
|
|
425
536
|
const warn = (message) => {
|
|
426
537
|
try {
|
|
@@ -482,6 +593,25 @@ export function createGatewayManager({
|
|
|
482
593
|
return false
|
|
483
594
|
}
|
|
484
595
|
|
|
596
|
+
// One run of the keyword index update; counts and kinds only go to the log.
|
|
597
|
+
async function mirror(spec) {
|
|
598
|
+
let result
|
|
599
|
+
try {
|
|
600
|
+
mirroring = mirrorImpl({ python, mirror: spec, dataDir, env, packageDir, ...mirrorOptions })
|
|
601
|
+
result = await mirroring.done
|
|
602
|
+
} catch {
|
|
603
|
+
result = { state: 'failed', kind: 'error' }
|
|
604
|
+
} finally {
|
|
605
|
+
mirroring = null
|
|
606
|
+
}
|
|
607
|
+
if (result.state === 'done' || result.state === 'partial') {
|
|
608
|
+
note(`keyword index ${result.state}: ${result.added ?? 0} added, ${result.removed ?? 0} removed, ${result.remaining ?? 0} remaining`)
|
|
609
|
+
} else if (result.state === 'failed') {
|
|
610
|
+
note(`keyword index update failed (${result.kind ?? 'error'})`)
|
|
611
|
+
}
|
|
612
|
+
return result
|
|
613
|
+
}
|
|
614
|
+
|
|
485
615
|
async function launch() {
|
|
486
616
|
timer = null
|
|
487
617
|
if (stopping) return
|
|
@@ -497,6 +627,17 @@ export function createGatewayManager({
|
|
|
497
627
|
return
|
|
498
628
|
}
|
|
499
629
|
if (stopping) return removeConfig()
|
|
630
|
+
// A hybrid store: bring the keyword index in line with the vector file first. The gateway is not
|
|
631
|
+
// running now, so nothing else writes to either file. A failed or partial update never keeps the
|
|
632
|
+
// gateway from starting: the next start continues where this one stopped.
|
|
633
|
+
if (config.store.mirror) {
|
|
634
|
+
const result = await mirror(config.store.mirror)
|
|
635
|
+
if (stopping) return removeConfig()
|
|
636
|
+
if (result.state === 'failed' && !mirrorWarned) {
|
|
637
|
+
mirrorWarned = true
|
|
638
|
+
warn(`feiyu-memgate: the keyword index could not be updated (${result.kind ?? 'error'}); hybrid search starts with what it has`)
|
|
639
|
+
}
|
|
640
|
+
}
|
|
500
641
|
const token = randomBytes(32).toString('base64url')
|
|
501
642
|
const proc = spawnImpl(python.argv[0], [
|
|
502
643
|
...python.argv.slice(1),
|
|
@@ -614,6 +755,8 @@ export function createGatewayManager({
|
|
|
614
755
|
timer = null
|
|
615
756
|
const proc = child
|
|
616
757
|
current = null
|
|
758
|
+
// A keyword index update still running ends now; launch() then sees `stopping` and spawns nothing.
|
|
759
|
+
if (mirroring) await mirroring.stop?.()
|
|
617
760
|
if (proc && proc.exitCode === null && proc.signalCode === null) {
|
|
618
761
|
const gone = new Promise((resolve) => {
|
|
619
762
|
proc.once('exit', resolve)
|
package/src/mirror.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Bring the keyword index of a hybrid store in line with its vector store file.
|
|
2
|
+
|
|
3
|
+
dsh-feiyu-memgate runs this with the interpreter that runs its gateway, right before it starts the
|
|
4
|
+
gateway (the gateway is not running then, so nothing else writes to either file):
|
|
5
|
+
|
|
6
|
+
python -I -B mirror.py
|
|
7
|
+
|
|
8
|
+
Why it exists: the vector file holds every memory of the store. While the hybrid switch is off,
|
|
9
|
+
saving, forgetting, deleting and the copy from the keyword store touch only that file, so the keyword
|
|
10
|
+
index next to it falls behind: a memory forgotten in the meantime would come back through the index,
|
|
11
|
+
and a memory saved in the meantime would have no keyword signal. This script makes the index hold
|
|
12
|
+
exactly the refs of the vector file: it removes the refs the vector file no longer has and adds the
|
|
13
|
+
ones it has not indexed yet, oldest first. It is idempotent: a second run right after a finished one
|
|
14
|
+
changes nothing.
|
|
15
|
+
|
|
16
|
+
The job arrives as one line of JSON on stdin: { package_dir, vector, keyword, deadline_seconds }, where
|
|
17
|
+
`vector` is the path of the vector store file and `keyword` is the keyword index as a gateway store
|
|
18
|
+
table ({ "type": "sqlite", "path": ... }). stdin then stays open, and the script exits as soon as it
|
|
19
|
+
closes: the plugin stopped the run, or the host process went away however it went away. Progress goes
|
|
20
|
+
to stdout as JSON lines. Nothing printed names a memory text, a ref, a key or a path: counts, and the
|
|
21
|
+
kind of error when a run fails. Exit code 0 for done and partial, 2 for failed.
|
|
22
|
+
|
|
23
|
+
The vector file is only read, through SQLite directly and read-only (it needs no embeddings endpoint).
|
|
24
|
+
The keyword index is written through the gateway's own backend, so its layout is always the one the
|
|
25
|
+
gateway expects. A run that reaches its time limit reports `partial` and the next start continues.
|
|
26
|
+
"""
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import sqlite3
|
|
30
|
+
import sys
|
|
31
|
+
import threading
|
|
32
|
+
import time
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
BATCH = 200
|
|
36
|
+
DEFAULT_DEADLINE = 60.0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _watch_stdin():
|
|
40
|
+
try:
|
|
41
|
+
while sys.stdin.buffer.read(4096):
|
|
42
|
+
pass
|
|
43
|
+
except BaseException: # noqa: BLE001 - any end of stdin ends the run
|
|
44
|
+
pass
|
|
45
|
+
os._exit(3)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def emit(event, **fields):
|
|
49
|
+
sys.stdout.write(json.dumps(dict(event=event, **fields)) + "\n")
|
|
50
|
+
sys.stdout.flush()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def open_vector(path):
|
|
54
|
+
"""A read-only connection to the vector store file, or None when there is none yet."""
|
|
55
|
+
if not os.path.exists(path):
|
|
56
|
+
return None
|
|
57
|
+
return sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, timeout=10.0)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def vector_refs(db):
|
|
61
|
+
"""Every ref of the vector store, oldest first. A file without the table holds nothing."""
|
|
62
|
+
if db is None:
|
|
63
|
+
return []
|
|
64
|
+
try:
|
|
65
|
+
return [row[0] for row in db.execute("SELECT ref FROM memories ORDER BY created_at, ref")]
|
|
66
|
+
except sqlite3.OperationalError:
|
|
67
|
+
return []
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def vector_items(db, refs):
|
|
71
|
+
"""(text, ref, date) of the given refs, in that order. Empty texts are left out."""
|
|
72
|
+
marks = ",".join("?" * len(refs))
|
|
73
|
+
rows = db.execute("SELECT ref, text, date FROM memories WHERE ref IN (%s)" % marks, refs).fetchall()
|
|
74
|
+
found = {ref: (text, date) for ref, text, date in rows}
|
|
75
|
+
return [(found[ref][0], ref, found[ref][1]) for ref in refs
|
|
76
|
+
if ref in found and isinstance(found[ref][0], str) and found[ref][0].strip()]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def main():
|
|
80
|
+
job = json.loads(sys.stdin.buffer.readline().decode("utf-8"))
|
|
81
|
+
threading.Thread(target=_watch_stdin, name="parent-watch", daemon=True).start()
|
|
82
|
+
sys.path.insert(0, job["package_dir"])
|
|
83
|
+
from feiyu_memgate import registry # noqa: E402 - the package path is part of the job
|
|
84
|
+
|
|
85
|
+
deadline = time.monotonic() + float(job.get("deadline_seconds", DEFAULT_DEADLINE))
|
|
86
|
+
keyword = None
|
|
87
|
+
vector = None
|
|
88
|
+
try:
|
|
89
|
+
vector = open_vector(job["vector"])
|
|
90
|
+
wanted = vector_refs(vector)
|
|
91
|
+
keyword = registry.create("backend", job["keyword"])
|
|
92
|
+
have = [ref for ref, _ in keyword.refs()]
|
|
93
|
+
wanted_set = set(wanted)
|
|
94
|
+
stale = [ref for ref in have if ref not in wanted_set]
|
|
95
|
+
have_set = set(have)
|
|
96
|
+
missing = [ref for ref in wanted if ref not in have_set]
|
|
97
|
+
emit("start", vector=len(wanted), keyword=len(have))
|
|
98
|
+
|
|
99
|
+
removed = 0
|
|
100
|
+
for ref in stale:
|
|
101
|
+
if time.monotonic() >= deadline:
|
|
102
|
+
break
|
|
103
|
+
keyword.delete(ref)
|
|
104
|
+
removed += 1
|
|
105
|
+
|
|
106
|
+
added = 0
|
|
107
|
+
handled = 0 # refs looked at, whether added or skipped as empty
|
|
108
|
+
while handled < len(missing) and time.monotonic() < deadline and removed == len(stale):
|
|
109
|
+
chunk = missing[handled:handled + BATCH]
|
|
110
|
+
for text, ref, date in vector_items(vector, chunk):
|
|
111
|
+
keyword.put(text, ref=ref, date=date)
|
|
112
|
+
added += 1
|
|
113
|
+
handled += len(chunk)
|
|
114
|
+
emit("progress", added=added, removed=removed, remaining=len(missing) - handled + len(stale) - removed)
|
|
115
|
+
|
|
116
|
+
remaining = len(missing) - handled + len(stale) - removed
|
|
117
|
+
emit("done" if remaining == 0 else "partial", added=added, removed=removed, remaining=remaining)
|
|
118
|
+
return 0
|
|
119
|
+
except Exception as error: # noqa: BLE001 - reported by kind only
|
|
120
|
+
emit("failed", kind=type(error).__name__)
|
|
121
|
+
return 2
|
|
122
|
+
finally:
|
|
123
|
+
for resource in (keyword, vector):
|
|
124
|
+
try:
|
|
125
|
+
if resource is not None:
|
|
126
|
+
resource.close()
|
|
127
|
+
except Exception: # noqa: BLE001
|
|
128
|
+
pass
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == "__main__":
|
|
132
|
+
sys.exit(main())
|
package/src/plugin.js
CHANGED
|
@@ -368,10 +368,23 @@ export function createPlugin(ctx, config, deps = {}) {
|
|
|
368
368
|
return null
|
|
369
369
|
}
|
|
370
370
|
|
|
371
|
+
// Whether the resolved store is hybrid: the switch alone is not enough (under keyword it does nothing,
|
|
372
|
+
// and a tier that lacks something has no store), so a change of the switch restarts the gateway only
|
|
373
|
+
// when it changes what the gateway runs.
|
|
374
|
+
function effectiveHybrid(s, f) {
|
|
375
|
+
try {
|
|
376
|
+
return resolveStore(s.retrieval, resolveDataDir(s.gateway.dataDir, env), f).hybrid === true
|
|
377
|
+
} catch {
|
|
378
|
+
return false
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
371
382
|
function reconcileGateway(s, f) {
|
|
372
383
|
const managed = needsMemory(s) && s.gateway.mode === 'managed'
|
|
373
384
|
const tier = effectiveTier(s.retrieval.tier, f)
|
|
374
|
-
const wanted = managed
|
|
385
|
+
const wanted = managed
|
|
386
|
+
? JSON.stringify([s.gateway.python, s.gateway.dataDir, tier, tierKey(s, tier, f), effectiveHybrid(s, f), policyOf(s)])
|
|
387
|
+
: null
|
|
375
388
|
if (needsMemory(s) && s.gateway.mode === 'external' && !(s.external.url && s.external.token)) {
|
|
376
389
|
if (!externalWarned) log.warn('feiyu-memgate: external mode needs external.url and external.token; memory is off')
|
|
377
390
|
externalWarned = true
|
|
@@ -754,6 +767,7 @@ export function createPlugin(ctx, config, deps = {}) {
|
|
|
754
767
|
retrieval: {
|
|
755
768
|
setting: s.retrieval.tier,
|
|
756
769
|
active: activeTier,
|
|
770
|
+
hybrid: { setting: s.retrieval.hybrid, active: managed && effectiveHybrid(s, f) },
|
|
757
771
|
tiers: TIER_NAMES.map((name) => {
|
|
758
772
|
const missing = TIERS[name].missing(s.retrieval, f)
|
|
759
773
|
return { name, available: missing.length === 0, missing, vector: TIERS[name].vector, active: name === activeTier }
|
|
@@ -796,9 +810,11 @@ export function createPlugin(ctx, config, deps = {}) {
|
|
|
796
810
|
tier: store.tier,
|
|
797
811
|
id: store.id,
|
|
798
812
|
type: store.table.type,
|
|
799
|
-
file: path.basename(store.
|
|
800
|
-
count: python ? await cachedCount(python, store.
|
|
813
|
+
file: path.basename(store.file),
|
|
814
|
+
count: python ? await cachedCount(python, store.file) : null,
|
|
815
|
+
hybrid: store.hybrid === true,
|
|
801
816
|
}
|
|
817
|
+
if (store.hybrid) out.store.keywordFile = path.basename(store.mirror.keyword.path)
|
|
802
818
|
}
|
|
803
819
|
return out
|
|
804
820
|
}
|
package/src/tiers.js
CHANGED
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
// searched under another, and switching back finds them again; the copy of keyword memories into a
|
|
17
17
|
// vector store (migrateOnTierChange) is the only thing that moves texts between files.
|
|
18
18
|
//
|
|
19
|
+
// The retrieval.hybrid switch adds a keyword index file next to the vector file of a vector tier
|
|
20
|
+
// (resolveStore below). The vector file stays the one that holds every memory; the index is rebuilt
|
|
21
|
+
// from it by src/mirror.py, so switching hybrid on or off loses nothing.
|
|
22
|
+
//
|
|
19
23
|
// `facts` is what the plugin knows about its surroundings at the moment: { embed } is the snapshot
|
|
20
24
|
// of the embedding add-on's service (readEmbed below), or null when the add-on is absent.
|
|
21
25
|
import { createHash } from 'node:crypto'
|
|
@@ -209,14 +213,42 @@ export function effectiveTier(setting, facts) {
|
|
|
209
213
|
}
|
|
210
214
|
|
|
211
215
|
/**
|
|
212
|
-
* The
|
|
213
|
-
*
|
|
216
|
+
* The keyword index file of a hybrid store: next to the vector file of the same store id. Tests and
|
|
217
|
+
* documents use this one definition.
|
|
218
|
+
*/
|
|
219
|
+
export function keywordIndexFile(dataDir, id) {
|
|
220
|
+
return path.join(dataDir, `memories-${id}-keywords.db`)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The store the managed gateway runs for these settings:
|
|
225
|
+
* { tier, missing, id, table, env, file, hybrid, mirror? }
|
|
226
|
+
* While something is missing, id, table and file are null and nothing may start.
|
|
227
|
+
* file the store file that holds every memory of this store (the vector file when hybrid)
|
|
228
|
+
* hybrid true when retrieval.hybrid is on, the tier is a vector tier and nothing is missing; the
|
|
229
|
+
* table is then a hybrid of a keyword index (first) and the vector table, and `id` stays the
|
|
230
|
+
* id of the vector store, so the ledger, the archive and the copy state are the same files
|
|
231
|
+
* as without hybrid: it is the same set of memories
|
|
232
|
+
* mirror hybrid only: { keyword, vector }, what src/mirror.py needs to bring the keyword index in
|
|
233
|
+
* line with the vector file before the gateway starts
|
|
214
234
|
*/
|
|
215
235
|
export function resolveStore(retrieval, dataDir, facts) {
|
|
216
236
|
const tier = effectiveTier(retrieval.tier, facts)
|
|
217
237
|
const entry = TIERS[tier]
|
|
218
238
|
const missing = entry.missing(retrieval, facts)
|
|
219
|
-
if (missing.length) return { tier, missing, id: null, table: null, env: {} }
|
|
239
|
+
if (missing.length) return { tier, missing, id: null, table: null, env: {}, file: null, hybrid: false }
|
|
220
240
|
const { id, table } = entry.store(retrieval, dataDir, facts)
|
|
221
|
-
|
|
241
|
+
const env = entry.env(retrieval, facts)
|
|
242
|
+
if (!(retrieval.hybrid === true && entry.vector)) return { tier, missing, id, table, env, file: table.path, hybrid: false }
|
|
243
|
+
// Keyword child first, vector child second, no weights: the order and the default the gateway's
|
|
244
|
+
// hybrid configurations were measured with. The vector child is the plain table unchanged
|
|
245
|
+
// (key_env included: the hybrid backend resolves a child's key_env from the environment itself).
|
|
246
|
+
const keyword = { type: 'sqlite', path: keywordIndexFile(dataDir, id) }
|
|
247
|
+
return {
|
|
248
|
+
tier, missing, id, env,
|
|
249
|
+
table: { type: 'hybrid', children: [keyword, table] },
|
|
250
|
+
file: table.path,
|
|
251
|
+
hybrid: true,
|
|
252
|
+
mirror: { keyword, vector: table.path },
|
|
253
|
+
}
|
|
222
254
|
}
|