sage-mem 0.1.2 → 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/LICENSE CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Bowen Zheng
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ Sage Plugins
2
+ Copyright 2026 gezi-wen
3
+
4
+ This product includes software developed by the Sage project
5
+ (https://github.com/gezi-wen/sage-mem).
package/README.md CHANGED
@@ -1,74 +1,46 @@
1
- # sage-mem · DSH 的记忆系统插件
1
+ # sage-mem · DSH 的文件式记忆插件
2
2
 
3
3
  给 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)(DSH)装上**跨会话记忆**——agent 今天记住的事,明天的新会话自动想起来。
4
4
 
5
- ## 为什么需要它
5
+ 记忆存在**本地 markdown 文件**里(frontmatter + 正文),不是数据库。透明、可检查、防膨胀。
6
6
 
7
- DSH 原生没有记忆系统。每个会话都是白纸:用户说过「我喜欢在深夜写代码」,下个会话再问「我喜欢什么」,agent 只能答不知道。
7
+ ## 为什么用文件
8
8
 
9
- sage-mem 补上这一块。它监听 DSH 的事件流,把会话内容沉淀到 SQLite,新会话启动时自动检索注入历史记忆。
9
+ DSH 原生没有记忆系统,每个会话都是白纸。市面上的记忆方案大多走 SQLite + 常驻 worker:
10
10
 
11
- **中文优先**。市面上的记忆方案在中文检索上普遍失效(SQLite FTS5 默认分词器对中文全部 0 命中)。sage-mem 的 worker 用 trigram 分词 + 短词兜底,中文实测全命中。
11
+ - 记忆写进数据库,**不透明**——想检查存了什么得查表,想清理要连数据库
12
+ - 事件自动捕获会**膨胀**——"用户打了个招呼"这种无实质内容也被存进去
13
+ - 需要一个**常驻 worker 进程** + 端口,多一份运维负担
14
+
15
+ sage-mem 换成文件式:每条记忆一个 markdown 文件,直接用编辑器打开就能看、能改、能删。存不存由 agent 按规则判断,不是事件全捕获。没有 worker、没有 SQLite、没有端口。
12
16
 
13
17
  ## 功能
14
18
 
15
- - **自动捕获**:工具调用(读写文件、执行命令)自动记录,无需手动整理
16
- - **AI 压缩**:会话内容由 LLM 压缩成结构化记忆(事实、摘要),中文输出
17
- - **跨会话注入**:新会话启动时自动检索并注入历史记忆,agent 不用自己翻
18
- - **中文检索**:trigram 分词(≥3 字查询)+ LIKE 兜底(<3 字短词如「猫」「芝麻」)
19
+ - **按问题检索注入**:每次提问,插件扫记忆目录,按相关性把记忆注入 system prompt,agent 第一轮就「想起来」
20
+ - **四类记忆**:`user`(用户是谁)/ `feedback`(工作方式指导)/ `project`(项目状态)/ `reference`(外部信息指针)
21
+ - **文件透明**:记忆就是 `*.md` 文件,frontmatter 存元数据,正文存内容
22
+ - **防膨胀**:写入靠规则引导 agent 判断「存不存」,无实质内容、能靠代码/git 推导的不存
23
+ - **Web 文件管理器**(v0.4):DSH 设置页「记忆管理」,浏览/查看/编辑/删除记忆文件,添加新记忆
19
24
 
20
25
  ## 架构
21
26
 
22
27
  ```
23
28
  DSH(Cordis 插件)
24
- └─ sage-mem 插件(事件监听 → HTTP 转发)← 本仓库
25
- │ HTTP 127.0.0.1
26
- ▼
27
- sage-mem worker(Bun 常驻,fork 自 claude-mem)← gezi-wen/claude-mem
28
- │
29
+ └─ sage-mem 插件(按问题检索 + 注入)← 本仓库
30
+ │ Node fs 直读
29
31
  ▼
30
- SQLite(FTS5 trigram 中文分词 + LLM 压缩)
32
+ memory/ 目录(markdown 文件,4 类)
33
+ ├── user_*.md
34
+ ├── feedback_*.md
35
+ ├── project_*.md
36
+ ├── reference_*.md
37
+ └── MEMORY.md ← 索引
31
38
  ```
32
39
 
33
- 设计选择:记忆逻辑复用 [claude-mem](https://github.com/thedotmack/claude-mem)(Apache-2.0,9 万星),fork 后加中文修复,DSH 侧只写一个轻量桥接插件。改动最小,能追上游更新。
40
+ 没有 worker、没有 SQLite、没有 HTTP 端口、没有常驻进程。
34
41
 
35
42
  ## 安装
36
43
 
37
- ### 1. 部署 worker
38
-
39
- ```bash
40
- git clone https://github.com/gezi-wen/claude-mem.git
41
- cd claude-mem
42
- git checkout sage-mem-worker # 含中文 trigram 修复
43
- bun install
44
- ```
45
-
46
- 配置 `~/.claude-mem/settings.json`(worker 数据目录):
47
-
48
- ```json
49
- {
50
- "CLAUDE_MEM_PROVIDER": "openrouter",
51
- "CLAUDE_MEM_OPENROUTER_BASE_URL": "https://api.deepseek.com",
52
- "CLAUDE_MEM_OPENROUTER_MODEL": "deepseek-chat",
53
- "CLAUDE_MEM_CHROMA_ENABLED": "false",
54
- "CLAUDE_MEM_MODE": "code--zh"
55
- }
56
- ```
57
-
58
- `~/.claude-mem/.env` 放 API key(任意 OpenAI 兼容服务均可,不限于 DeepSeek):
59
-
60
- ```
61
- OPENROUTER_API_KEY=<你的 API key>
62
- ```
63
-
64
- 启动:
65
-
66
- ```bash
67
- bun src/services/worker-service.ts --daemon
68
- ```
69
-
70
- ### 2. 安装插件
71
-
72
44
  在你的 DSH profile 的 `package.json` 里加:
73
45
 
74
46
  ```json
@@ -96,22 +68,48 @@ bun src/services/worker-service.ts --daemon
96
68
 
97
69
  然后 `pnpm install` 重启 DSH。
98
70
 
71
+ ## 配置
72
+
73
+ 用环境变量 `SAGE_MEM_DIR` 指定记忆目录,默认 `~/.sage-mem/memory`:
74
+
75
+ ```
76
+ SAGE_MEM_DIR=/path/to/your/memory
77
+ ```
78
+
79
+ 记忆文件格式:
80
+
81
+ ```markdown
82
+ ---
83
+ name: 可选的短名
84
+ description: 一句话说清这条记忆是什么(检索与列表都靠它)
85
+ metadata:
86
+ type: user # user / feedback / project / reference
87
+ ---
88
+
89
+ 记忆正文。
90
+ ```
91
+
92
+ `feedback` 类建议带 `**Why:**`(原因)和 `**How to apply:**`(何时生效)两行,方便判断边界。
93
+
99
94
  ## 验证
100
95
 
101
- 跨会话中文记忆链路(实测):
96
+ 跨会话记忆链路(实测):
102
97
 
103
- 1. 会话 A 说「记住:我的猫叫芝麻,它喜欢晒太阳」
98
+ 1. 会话 A 说「记住:我的猫叫芝麻,它喜欢晒太阳」——agent 按规则写进 `memory/`
104
99
  2. 开新会话 B 问「我的猫叫什么」
105
- 3. agent 直接答出「芝麻」——记忆自动注入,无需 agent 自己找
100
+ 3. agent 第一轮直接答出「芝麻」——记忆自动注入,无需 agent 自己找
101
+
102
+ ## 相关项目
103
+
104
+ - [sage-persona](https://github.com/gezi-wen/sage-persona) — 人格(我是谁)
105
+ - [sage-meta](https://github.com/gezi-wen/sage-meta) — 自检(我做得对吗)
106
106
 
107
- 搭配 [sage-persona](https://github.com/gezi-wen/sage-persona)(我是谁)和 [sage-meta](https://github.com/gezi-wen/sage-meta)(我做得对吗)组成 Sage 三件套——这是三道题的第三道:**我下次应该怎么想**。
107
+ sage-mem 是第三道:**我下次应该怎么想**——跨会话沉淀事实与教训。
108
108
 
109
- ## 已知边界
109
+ ## 旧版
110
110
 
111
- - trigram 分词对 `<3` 字符查询无效,worker 已加 LIKE 兜底
112
- - worker 不可用时插件静默跳过(不阻塞 DSH),记忆功能暂缺
113
- - MVP 存储统一在 `project=sage` 空间,按工作区分项目是后续计划
111
+ 本仓库早期是 SQLite + worker 架构,已归档到 [`sqlite-worker`](../../tree/sqlite-worker) 分支。文件式是继任实现。
114
112
 
115
113
  ## License
116
114
 
117
- MIT(worker fork 为 Apache-2.0,见 [gezi-wen/claude-mem](https://github.com/gezi-wen/claude-mem))
115
+ Apache-2.0
package/lib/client.js ADDED
@@ -0,0 +1,432 @@
1
+ /**
2
+ * sage-mem — 客户端半:DSH 设置页「记忆管理」界面(文件管理器)。
3
+ *
4
+ * 手写 ModuleLoader bundle(与官方 dsh-client-* 包的构建产物同格式):
5
+ * window.__ModuleLoader__.load({ id, factory }),factory 内 require('react')
6
+ * 可用,module.exports 导出标准 Cordis 插件(apply/inject)。
7
+ *
8
+ * 数据通道:TypertRemoteService(host 半 MemoryGateway),通过
9
+ * ctx.get("remote.memory") 调用文件列表/读/写/删。remote 返回 {ok, value}
10
+ * 信封。浏览器侧无 zod,schema 手写(codec 只要求 mode==="strict" + parse)。
11
+ *
12
+ * 功能:浏览 memory 目录的 markdown 记忆文件(类型徽章 + 描述预览)、
13
+ * 查看/编辑全文、两步确认删除、添加新记忆(选类型 + 描述 + 正文)。
14
+ */
15
+
16
+ window.__ModuleLoader__.load({
17
+ id: "sage-mem",
18
+ factory: (require) => {
19
+ var module = { exports: {} };
20
+ var exports = module.exports;
21
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
22
+ let react = require("react");
23
+ const h = react.createElement;
24
+
25
+ // ── 手写 strict codec(浏览器无 zod,typert 只要求 parse 方法)──
26
+ function parseSchema(shape) {
27
+ return {
28
+ parse(value) {
29
+ if (value === null || typeof value !== "object") throw new Error("sage-mem: invalid payload");
30
+ for (const [key, check] of Object.entries(shape)) {
31
+ if (!(key in value)) throw new Error("sage-mem: missing field " + key);
32
+ check(value[key]);
33
+ }
34
+ return value;
35
+ },
36
+ };
37
+ }
38
+ const isStr = (v) => { if (typeof v !== "string") throw new Error("expected string"); };
39
+ const isBool = (v) => { if (typeof v !== "boolean") throw new Error("expected boolean"); };
40
+ const isNum = (v) => { if (typeof v !== "number") throw new Error("expected number"); };
41
+ const strSchema = { parse(v) { isStr(v); return v; } };
42
+ const fileSchema = parseSchema({ "file": isStr, "type": isStr, "description": isStr, "size": isNum });
43
+ const listSchema = { parse(v) { if (!Array.isArray(v)) throw new Error("expected array"); v.forEach((f) => fileSchema.parse(f)); return v; } };
44
+ const readSchema = parseSchema({ "name": isStr, "content": isStr });
45
+ const writeSchema = parseSchema({ "ok": isBool, "file": isStr });
46
+ const deleteSchema = parseSchema({ "ok": isBool });
47
+
48
+ const TYPERT_REMOTE = {
49
+ package: "sage-mem",
50
+ descriptors: [
51
+ {
52
+ id: "sage-mem#memory/listFiles",
53
+ service: "memory",
54
+ namespace: "memory",
55
+ method: "listFiles",
56
+ invocation: { kind: "direct" },
57
+ parameters: [],
58
+ result: { mode: "strict", typeSymbol: "sage-mem/types#FileList", schema: listSchema },
59
+ sourceLocation: { "file": "workspace/sage-mem/lib/index.js", "line": 1, "column": 1 },
60
+ },
61
+ {
62
+ id: "sage-mem#memory/readFile",
63
+ service: "memory",
64
+ namespace: "memory",
65
+ method: "readFile",
66
+ invocation: { kind: "direct" },
67
+ parameters: [
68
+ { name: "name", wire: "name", source: "json", codec: { mode: "strict", typeSymbol: "sage-mem/types#FileName", schema: strSchema } },
69
+ ],
70
+ result: { mode: "strict", typeSymbol: "sage-mem/types#FileContent", schema: readSchema },
71
+ sourceLocation: { "file": "workspace/sage-mem/lib/index.js", "line": 1, "column": 1 },
72
+ },
73
+ {
74
+ id: "sage-mem#memory/writeFile",
75
+ service: "memory",
76
+ namespace: "memory",
77
+ method: "writeFile",
78
+ invocation: { kind: "direct" },
79
+ parameters: [
80
+ { name: "name", wire: "name", source: "json", codec: { mode: "strict", typeSymbol: "sage-mem/types#FileName", schema: strSchema } },
81
+ { name: "content", wire: "content", source: "json", codec: { mode: "strict", typeSymbol: "sage-mem/types#FileContent", schema: strSchema } },
82
+ ],
83
+ result: { mode: "strict", typeSymbol: "sage-mem/types#WriteResult", schema: writeSchema },
84
+ sourceLocation: { "file": "workspace/sage-mem/lib/index.js", "line": 1, "column": 1 },
85
+ },
86
+ {
87
+ id: "sage-mem#memory/deleteFile",
88
+ service: "memory",
89
+ namespace: "memory",
90
+ method: "deleteFile",
91
+ invocation: { kind: "direct" },
92
+ parameters: [
93
+ { name: "name", wire: "name", source: "json", codec: { mode: "strict", typeSymbol: "sage-mem/types#FileName", schema: strSchema } },
94
+ ],
95
+ result: { mode: "strict", typeSymbol: "sage-mem/types#DeleteResult", schema: deleteSchema },
96
+ sourceLocation: { "file": "workspace/sage-mem/lib/index.js", "line": 1, "column": 1 },
97
+ },
98
+ ],
99
+ };
100
+
101
+ const CSS = [
102
+ ".smem-root{display:flex;flex-direction:column;gap:12px;font-size:13px;line-height:1.55;color:var(--dsw-alias-label-primary);max-width:760px;}",
103
+ ".smem-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}",
104
+ ".smem-title{font-size:15px;font-weight:600;}",
105
+ ".smem-dot{width:8px;height:8px;border-radius:50%;background:var(--dsw-alias-state-success-primary,#22c55e);flex:none;}",
106
+ ".smem-dot--bad{background:var(--dsw-alias-state-error-primary,#ef4444);}",
107
+ ".smem-muted{color:var(--dsw-alias-label-secondary);font-size:12px;}",
108
+ ".smem-toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}",
109
+ ".smem-search{flex:1;min-width:160px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:inherit;padding:5px 10px;font-size:12px;outline:none;font-family:inherit;}",
110
+ ".smem-search:focus{border-color:var(--dsw-alias-brand-primary,#4d76e6);}",
111
+ ".smem-btn{border:1px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-primary);border-radius:8px;padding:4px 12px;font-size:12px;cursor:pointer;font-family:inherit;white-space:nowrap;}",
112
+ ".smem-btn:hover{border-color:var(--dsw-alias-brand-primary,#4d76e6);color:var(--dsw-alias-brand-primary,#4d76e6);}",
113
+ ".smem-btn:disabled{opacity:.5;cursor:default;}",
114
+ ".smem-btn-primary{background:var(--dsw-alias-brand-primary,#4d76e6);border-color:var(--dsw-alias-brand-primary,#4d76e6);color:var(--dsw-alias-bg-base,#fff);}",
115
+ ".smem-btn-primary:hover{color:var(--dsw-alias-bg-base,#fff);opacity:.88;}",
116
+ ".smem-btn-danger-ghost{color:var(--dsw-alias-state-error-primary,#ef4444);border-color:var(--dsw-alias-border-l2);}",
117
+ ".smem-btn-danger{background:var(--dsw-alias-state-error-primary,#dc2626);border-color:var(--dsw-alias-state-error-primary,#dc2626);color:#fff;}",
118
+ ".smem-btn-danger:hover{color:#fff;opacity:.9;}",
119
+ ".smem-list{display:flex;flex-direction:column;gap:10px;}",
120
+ ".smem-card{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:10px 12px;display:flex;flex-direction:column;gap:6px;}",
121
+ ".smem-card-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}",
122
+ ".smem-card-title{font-weight:600;flex:1;min-width:120px;overflow-wrap:anywhere;text-align:left;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;}",
123
+ ".smem-badge{display:inline-flex;align-items:center;gap:4px;font-size:11px;color:var(--dsw-alias-label-secondary);border:1px solid var(--dsw-alias-border-l1);border-radius:6px;padding:1px 6px;white-space:nowrap;}",
124
+ ".smem-narrative{color:var(--dsw-alias-label-secondary);font-size:12.5px;white-space:pre-wrap;overflow-wrap:anywhere;}",
125
+ '.smem-narrative[data-clamp="1"]{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;cursor:pointer;}',
126
+ ".smem-card-foot{display:flex;justify-content:flex-end;}",
127
+ ".smem-actions{display:flex;gap:6px;}",
128
+ ".smem-form{border:1px solid var(--dsw-alias-border-l2);border-radius:10px;padding:12px;background:var(--dsw-alias-bg-layer-2);display:flex;flex-direction:column;gap:8px;}",
129
+ ".smem-form-title{font-weight:600;font-size:13px;}",
130
+ ".smem-label{font-size:12px;color:var(--dsw-alias-label-secondary);}",
131
+ ".smem-input,.smem-textarea{width:100%;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-base);color:inherit;padding:6px 10px;font-size:13px;outline:none;font-family:inherit;}",
132
+ ".smem-input:focus,.smem-textarea:focus{border-color:var(--dsw-alias-brand-primary,#4d76e6);}",
133
+ ".smem-textarea{resize:vertical;min-height:72px;}",
134
+ ".smem-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap;}",
135
+ ".smem-chip{border:1px solid var(--dsw-alias-border-l1);background:transparent;color:var(--dsw-alias-label-secondary);border-radius:999px;padding:3px 12px;font-size:12px;cursor:pointer;font-family:inherit;}",
136
+ ".smem-chip:hover{border-color:var(--dsw-alias-border-l2);}",
137
+ '.smem-chip[data-on="1"]{border-color:var(--dsw-alias-brand-primary,#4d76e6);color:var(--dsw-alias-brand-primary,#4d76e6);}',
138
+ ".smem-chips{display:flex;gap:6px;flex-wrap:wrap;}",
139
+ ".smem-err{border:1px solid var(--dsw-alias-state-error-primary,#ef4444);color:var(--dsw-alias-state-error-primary,#ef4444);border-radius:8px;padding:6px 10px;font-size:12px;white-space:pre-wrap;overflow-wrap:anywhere;}",
140
+ ".smem-ok{color:var(--dsw-alias-state-success-primary,#16a34a);font-size:12px;}",
141
+ ".smem-empty{border:1px dashed var(--dsw-alias-border-l2);border-radius:10px;padding:22px 14px;text-align:center;color:var(--dsw-alias-label-secondary);font-size:12.5px;}",
142
+ ].join("\n");
143
+
144
+ const TYPE_META = {
145
+ user: ["👤", "用户"],
146
+ feedback: ["📌", "反馈"],
147
+ project: ["📁", "项目"],
148
+ reference: ["🔗", "参考"],
149
+ };
150
+ const TYPE_ORDER = ["user", "feedback", "project", "reference"];
151
+
152
+ function fmtSize(n) {
153
+ if (n < 1024) return n + " B";
154
+ if (n < 1024 * 1024) return (n / 1024).toFixed(1) + " KB";
155
+ return (n / 1024 / 1024).toFixed(1) + " MB";
156
+ }
157
+
158
+ /** 拆 typert remote 的 {ok, value} 信封。 */
159
+ function unwrap(result) {
160
+ return result && result.ok ? result.value : result;
161
+ }
162
+
163
+ function Chip(props) {
164
+ return h("button", {
165
+ type: "button",
166
+ className: "smem-chip",
167
+ "data-on": props.on ? "1" : "0",
168
+ onClick: props.onClick,
169
+ }, props.label);
170
+ }
171
+
172
+ function Card(props) {
173
+ const item = props.item;
174
+ const meta = TYPE_META[item.type] || TYPE_META.reference;
175
+ const isOpen = !!props.expanded;
176
+ return h("div", { className: "smem-card", key: item.file }, [
177
+ h("div", { className: "smem-card-head", key: "head" }, [
178
+ h("span", { className: "smem-badge", key: "badge", title: "类型 " + String(item.type) }, meta[0] + " " + meta[1]),
179
+ h("span", { className: "smem-card-title", key: "title" }, item.file),
180
+ h("span", { className: "smem-muted", key: "size" }, fmtSize(item.size)),
181
+ ]),
182
+ item.description
183
+ ? h("div", {
184
+ className: "smem-narrative",
185
+ "data-clamp": isOpen ? "0" : "1",
186
+ key: "body",
187
+ onClick: function () { props.onToggle(item.file); },
188
+ title: isOpen ? "点击收起" : "点击展开全文",
189
+ }, String(item.description))
190
+ : null,
191
+ h("div", { className: "smem-card-foot", key: "foot" },
192
+ h("div", { className: "smem-actions", key: "acts" },
193
+ props.deleting
194
+ ? [
195
+ h("button", { type: "button", className: "smem-btn smem-btn-danger", key: "yes", onClick: function () { props.onConfirmDelete(item.file); } }, "确认删除"),
196
+ h("button", { type: "button", className: "smem-btn", key: "no", onClick: function () { props.onCancelDelete(); } }, "取消"),
197
+ ]
198
+ : [
199
+ h("button", { type: "button", className: "smem-btn", key: "edit", onClick: function () { props.onEdit(item.file); } }, "编辑"),
200
+ h("button", { type: "button", className: "smem-btn smem-btn-danger-ghost", key: "del", onClick: function () { props.onAskDelete(item.file); } }, "删除"),
201
+ ])),
202
+ ]);
203
+ }
204
+
205
+ function Section(props) {
206
+ const remote = props.ctx.get("remote.memory");
207
+ const sItems = react.useState([]);
208
+ const items = sItems[0], setItems = sItems[1];
209
+ const sLoading = react.useState(false);
210
+ const loading = sLoading[0], setLoading = sLoading[1];
211
+ const sError = react.useState(null);
212
+ const error = sError[0], setError = sError[1];
213
+ const sNotice = react.useState("");
214
+ const notice = sNotice[0], setNotice = sNotice[1];
215
+ const sQuery = react.useState("");
216
+ const query = sQuery[0], setQuery = sQuery[1];
217
+ const sExpanded = react.useState({});
218
+ const expanded = sExpanded[0], setExpanded = sExpanded[1];
219
+ const sDeleting = react.useState(null);
220
+ const deleting = sDeleting[0], setDeleting = sDeleting[1];
221
+ const sFormOpen = react.useState(false);
222
+ const formOpen = sFormOpen[0], setFormOpen = sFormOpen[1];
223
+ const sEditingFile = react.useState(null);
224
+ const editingFile = sEditingFile[0], setEditingFile = sEditingFile[1];
225
+ const sFormType = react.useState("feedback");
226
+ const formType = sFormType[0], setFormType = sFormType[1];
227
+ const sFormName = react.useState("");
228
+ const formName = sFormName[0], setFormName = sFormName[1];
229
+ const sFormDesc = react.useState("");
230
+ const formDesc = sFormDesc[0], setFormDesc = sFormDesc[1];
231
+ const sFormBody = react.useState("");
232
+ const formBody = sFormBody[0], setFormBody = sFormBody[1];
233
+ const sBusy = react.useState(false);
234
+ const busy = sBusy[0], setBusy = sBusy[1];
235
+ const sOk = react.useState(false);
236
+ const dirOk = sOk[0], setDirOk = sOk[1];
237
+
238
+ function load() {
239
+ setLoading(true);
240
+ setError(null);
241
+ remote.listFiles()
242
+ .then(function (res) {
243
+ if (res && typeof res === "object" && res.ok === false) {
244
+ const msg = res.error && res.error.message ? res.error.message : "remote 调用失败";
245
+ throw new Error("listFiles RPC 失败: " + msg);
246
+ }
247
+ const list = unwrap(res);
248
+ setItems(Array.isArray(list) ? list : []);
249
+ setDirOk(true);
250
+ })
251
+ .catch(function (e) { setError(String((e && e.message) || e)); setDirOk(false); })
252
+ .then(function () { setLoading(false); });
253
+ }
254
+
255
+ react.useEffect(function () { load(); }, []);
256
+
257
+ function closeForm() {
258
+ setFormOpen(false); setEditingFile(null); setFormName(""); setFormDesc(""); setFormBody(""); setFormType("feedback");
259
+ }
260
+
261
+ function openEdit(file) {
262
+ setError(null);
263
+ setBusy(true);
264
+ remote.readFile(file)
265
+ .then(function (res) {
266
+ const data = unwrap(res);
267
+ const content = (data && data.content) || "";
268
+ const fm = content.match(/^---\n([\s\S]*?)\n---\n?/);
269
+ let type = "reference";
270
+ let desc = "";
271
+ let body = content;
272
+ if (fm) {
273
+ body = content.slice(fm[0].length);
274
+ const t = fm[1].match(/type:\s*(\S+)/);
275
+ if (t) type = t[1];
276
+ const d = fm[1].match(/description:\s*"?(.+?)"?\n/);
277
+ if (d) desc = d[1].replace(/["']/g, "");
278
+ }
279
+ setEditingFile(file);
280
+ setFormName(file);
281
+ setFormType(TYPE_ORDER.indexOf(type) >= 0 ? type : "reference");
282
+ setFormDesc(desc);
283
+ setFormBody(body);
284
+ setFormOpen(true);
285
+ })
286
+ .catch(function (e) { setError(String((e && e.message) || e)); })
287
+ .then(function () { setBusy(false); });
288
+ }
289
+
290
+ function openAdd() {
291
+ setError(null);
292
+ setEditingFile(null);
293
+ setFormName("");
294
+ setFormType("feedback");
295
+ setFormDesc("");
296
+ setFormBody("");
297
+ setFormOpen(true);
298
+ }
299
+
300
+ function buildFrontmatter(type, desc) {
301
+ return "---\nname: \"\"\ndescription: \"" + desc.replace(/"/g, "'") + "\"\nmetadata:\n type: " + type + "\n---\n\n";
302
+ }
303
+
304
+ function submit() {
305
+ if (!formDesc.trim()) { setError("描述不能为空"); return; }
306
+ setBusy(true); setError(null); setNotice("");
307
+ const type = formType;
308
+ const name = (formName.trim() || (type + "_note.md"));
309
+ const safeName = name.endsWith(".md") ? name : name + ".md";
310
+ const content = buildFrontmatter(type, formDesc.trim()) + formBody;
311
+ remote.writeFile(safeName, content)
312
+ .then(function () {
313
+ closeForm();
314
+ setNotice(editingFile ? "已更新 " + safeName : "已保存 " + safeName);
315
+ load();
316
+ })
317
+ .catch(function (e) { setError(String((e && e.message) || e)); })
318
+ .then(function () { setBusy(false); });
319
+ }
320
+
321
+ function confirmDelete(file) {
322
+ setBusy(true); setError(null); setNotice("");
323
+ remote.deleteFile(file)
324
+ .then(function () {
325
+ setDeleting(null);
326
+ setNotice("已删除 " + file);
327
+ load();
328
+ })
329
+ .catch(function (e) { setError(String((e && e.message) || e)); })
330
+ .then(function () { setBusy(false); });
331
+ }
332
+
333
+ const q = query.trim().toLowerCase();
334
+ const filtered = items.filter(function (it) {
335
+ if (!q) return true;
336
+ const hay = ((it.file || "") + "\n" + (it.description || "") + "\n" + (it.type || "")).toLowerCase();
337
+ return hay.indexOf(q) >= 0;
338
+ });
339
+
340
+ return h("div", { className: "smem-root" }, [
341
+ h("div", { className: "smem-head", key: "head" }, [
342
+ h("span", { className: "smem-title", key: "t" }, "记忆文件(sage-mem)"),
343
+ h("span", { className: "smem-dot" + (dirOk ? "" : " smem-dot--bad"), key: "dot", title: dirOk ? "memory 目录可读" : "memory 目录不可读" }),
344
+ h("span", { className: "smem-muted", key: "st" }, dirOk ? "目录可读" : "目录不可读"),
345
+ h("span", { className: "smem-badge", key: "cnt" }, "共 " + String(items.length) + " 个文件"),
346
+ ]),
347
+ h("div", { className: "smem-toolbar", key: "bar" }, [
348
+ h("input", { className: "smem-search", key: "q", value: query, placeholder: "搜索文件名 / 描述 / 类型…", onChange: function (e) { setQuery(e.target.value); } }),
349
+ h("button", { type: "button", className: "smem-btn", key: "refresh", disabled: busy || loading, onClick: load }, "刷新"),
350
+ h("button", { type: "button", className: "smem-btn smem-btn-primary", key: "add", onClick: openAdd }, "+ 添加记忆"),
351
+ ]),
352
+ error ? h("div", { className: "smem-err", key: "err" }, "⚠ " + error) : null,
353
+ notice && !error ? h("div", { className: "smem-ok", key: "ok" }, "✓ " + notice) : null,
354
+ formOpen
355
+ ? h("div", { className: "smem-form", key: "form" }, [
356
+ h("div", { className: "smem-form-title", key: "ft" }, editingFile ? "编辑 " + editingFile : "添加记忆"),
357
+ h("div", { className: "smem-row", key: "cat" }, [
358
+ h("span", { className: "smem-label", key: "l" }, "类型:"),
359
+ h("div", { className: "smem-chips", key: "chips" }, TYPE_ORDER.map(function (t) {
360
+ const meta = TYPE_META[t];
361
+ return h(Chip, { key: t, label: meta[0] + " " + meta[1], on: formType === t, onClick: function () { setFormType(t); } });
362
+ })),
363
+ ]),
364
+ h("label", { className: "smem-label", key: "ln" }, "文件名(.md,留空自动 " + formType + "_note.md)"),
365
+ h("input", { className: "smem-input", key: "tn", value: formName, onChange: function (e) { setFormName(e.target.value); }, placeholder: "例如 project_traveler.md" }),
366
+ h("label", { className: "smem-label", key: "ld" }, "描述(写进 frontmatter,检索与列表都靠它)"),
367
+ h("input", { className: "smem-input", key: "td", value: formDesc, onChange: function (e) { setFormDesc(e.target.value); }, placeholder: "一句话说清这条记忆是什么" }),
368
+ h("label", { className: "smem-label", key: "lb" }, "正文(可选,frontmatter 自动生成)"),
369
+ h("textarea", { className: "smem-textarea", key: "tb", rows: 6, value: formBody, onChange: function (e) { setFormBody(e.target.value); }, placeholder: "要长期记住的细节" }),
370
+ h("div", { className: "smem-row", key: "btns" }, [
371
+ h("button", { type: "button", className: "smem-btn smem-btn-primary", key: "save", disabled: busy, onClick: submit }, busy ? "保存中…" : "保存"),
372
+ h("button", { type: "button", className: "smem-btn", key: "cancel", disabled: busy, onClick: closeForm }, "取消"),
373
+ ]),
374
+ ])
375
+ : null,
376
+ loading && items.length === 0
377
+ ? h("div", { className: "smem-muted", key: "loading" }, "加载中…")
378
+ : filtered.length === 0
379
+ ? h("div", { className: "smem-empty", key: "empty" },
380
+ items.length === 0
381
+ ? "还没有记忆文件。对话中值得记住的事会写到这里,也可以点「添加记忆」手动写入。"
382
+ : "没有符合搜索条件的文件。")
383
+ : h("div", { className: "smem-list", key: "list" }, filtered.map(function (it) {
384
+ return h(Card, {
385
+ key: it.file,
386
+ item: it,
387
+ expanded: !!expanded[it.file],
388
+ deleting: deleting === it.file,
389
+ onToggle: function (file) {
390
+ const nx = {};
391
+ nx[file] = !expanded[file];
392
+ setExpanded(Object.assign({}, expanded, nx));
393
+ },
394
+ onEdit: openEdit,
395
+ onAskDelete: function (file) { setDeleting(file); },
396
+ onCancelDelete: function () { setDeleting(null); },
397
+ onConfirmDelete: confirmDelete,
398
+ });
399
+ })),
400
+ ]);
401
+ }
402
+
403
+ const inject = ["slots", "remote"];
404
+
405
+ /**
406
+ * Client 插件:$mount strict remote contribution(第三方 remote 不在
407
+ * dsh-api-remotes 的固定列表里,必须自己挂),再注册设置页签。
408
+ */
409
+ async function apply(ctx) {
410
+ await ctx.remote.$mount(TYPERT_REMOTE);
411
+ // 样式注入(参照官方 client bundle 的 data-plugin-css 约定,幂等)
412
+ const tagId = "sage-mem/settings.css";
413
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
414
+ const tag = document.createElement("style");
415
+ tag.dataset.plugin = "sage-mem";
416
+ tag.dataset.pluginCss = tagId;
417
+ tag.textContent = CSS;
418
+ document.head.appendChild(tag);
419
+ }
420
+ ctx.slots.inject("settings.section", () =>
421
+ ctx.slots.register(
422
+ { name: "settings.section", id: "sage-mem", order: 20, label: "记忆管理" },
423
+ (props) => react.createElement(Section, { ...props, ctx }),
424
+ ),
425
+ );
426
+ }
427
+
428
+ exports.apply = apply;
429
+ exports.inject = inject;
430
+ return module.exports;
431
+ }
432
+ });
package/lib/index.js CHANGED
@@ -1,140 +1,212 @@
1
1
  /**
2
- * sage-mem — 记忆桥接插件。
2
+ * sage-mem — 文件式记忆插件(CC 原生方式)。
3
3
  *
4
- * 把 DSH 的事件流翻译成 sage-mem worker(fork 自 claude-mem)的 HTTP 调用:
5
- * user/message → POST /api/sessions/init 存用户 prompt
6
- * tool/call + result → POST /api/sessions/observations 捕获工具 IO
7
- * turn/end → POST /api/sessions/summarize 触发压缩
8
- * + 拉取最新记忆上下文缓存
9
- * agent/session-start → 同步注入上个会话的记忆缓存(避免异步注入的时序丢失)
4
+ * 记忆存在本地 markdown 文件目录(frontmatter + 正文,4 类),不是数据库。
5
+ * host 侧两件事:
6
+ * 1. 按问题检索注入:system-prompt/assemble 时扫 memory 目录,按双字匹配
7
+ * 选相关文件,读全文注入 system prompt,让 agent 第一轮就「想起」
8
+ * 2. TypertRemoteService:给设置页「记忆管理」提供文件列表/读/写/删
10
9
  *
11
- * 注入用「上一回合结束时的缓存」而非当场 fetch:agent/session-start 时 turn
12
- * 组装已经开始,异步 fetch 回来再 inject 会被 inbox 消费时序吞掉。缓存在上个
13
- * turn/end 时已就绪,session-start 同步注入必然生效。
10
+ * 写入靠 AGENTS.md 的「记忆使用」规则引导 agent 自己判断 + 用文件工具写
11
+ * memory 目录——透明、可检查、防膨胀。无 worker、无 SQLite、无端口。
14
12
  *
15
- * worker 不可用时静默跳过,不阻塞 DSH 主流程。worker 进程由启动脚本管理
16
- * (sage-bundle 阶段统一装配,先起 worker 再起 dsh)。
17
- *
18
- * 这是 Sage 的第三道题:我下次应该怎么想 —— 跨会话沉淀事实与教训。
13
+ * 旧 worker 版见 git 分支 `sqlite-worker`。
19
14
  */
20
15
 
21
- const WORKER_URL = process.env.SAGE_MEM_WORKER_URL || 'http://127.0.0.1:37700'
22
- const REQUEST_TIMEOUT_MS = 3000
23
- const PROJECT = 'sage' // MVP:统一记忆空间;后续可按 cwd 分项目
16
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
17
+ import { homedir } from 'node:os'
18
+ import { readFile, readdir, writeFile, unlink } from 'node:fs/promises'
19
+ import { join, basename } from 'node:path'
24
20
 
25
- export const name = 'sage-mem'
26
- export const inject = []
21
+ const MEMORY_DIR = process.env.SAGE_MEM_DIR || join(homedir(), '.sage-mem', 'memory')
22
+ const MAX_RESULTS = 5
23
+ const MAX_CHARS_PER_FILE = 1500
27
24
 
28
- /**
29
- * 构造 UserMessage(手写,零依赖:dsh-llm 无法从 workspace 插件解析)。
30
- * source 必需——DSH 消费消息时访问 message.source.kind,纯字符串会崩。
31
- */
32
- function pluginMessage(text, plugin) {
33
- return {
34
- id: crypto.randomUUID(),
35
- role: 'user',
36
- content: [{ type: 'text', text }],
37
- source: { kind: 'plugin', plugin },
38
- }
25
+ /** 提取消息文本,兼容 content 为字符串或 text-block 数组两种形态。 */
26
+ function extractText(content) {
27
+ if (typeof content === 'string') return content.trim()
28
+ if (!Array.isArray(content)) return ''
29
+ return content
30
+ .filter(b => b && b.type === 'text' && typeof b.text === 'string')
31
+ .map(b => b.text)
32
+ .join('\n')
33
+ .trim()
34
+ }
35
+
36
+ /** 提取双字(2-gram)集合,中英文数字通用。 */
37
+ function bigrams(s) {
38
+ const clean = String(s).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '')
39
+ const set = new Set()
40
+ for (let i = 0; i < clean.length - 1; i++) set.add(clean.slice(i, i + 2))
41
+ return set
39
42
  }
40
43
 
41
- export function apply(ctx) {
42
- // tool/call 先记 callId,等 tool/result 配对后一起送 worker
43
- const pendingCalls = new Map()
44
- // 上个会话的记忆上下文(turn/end 时拉取,下个 session-start 同步注入)
45
- let cachedContext = ''
46
- // 最后一条 assistant 消息(summarize 需要)
47
- let lastAssistantText = ''
48
-
49
- async function post(path, body) {
50
- try {
51
- return await fetch(WORKER_URL + path, {
52
- method: 'POST',
53
- headers: { 'Content-Type': 'application/json' },
54
- body: JSON.stringify(body),
55
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
56
- })
57
- } catch {
58
- return null // worker 不可用:静默跳过,不阻塞 DSH
59
- }
44
+ /** query 的双字在 text 中的覆盖率(0~1),作为相关性得分。 */
45
+ function score(query, text) {
46
+ const q = bigrams(query)
47
+ if (q.size === 0) return 0
48
+ const t = bigrams(text)
49
+ let hit = 0
50
+ for (const g of q) if (t.has(g)) hit++
51
+ return hit / q.size
52
+ }
53
+
54
+ /** 扫 memory 目录,读回全部记忆文件的正文(跳过索引与子目录)。 */
55
+ async function scanMemoryFiles() {
56
+ try {
57
+ const entries = await readdir(MEMORY_DIR, { withFileTypes: true })
58
+ const names = entries
59
+ .filter(e => e.isFile() && e.name.endsWith('.md') && e.name !== 'MEMORY.md')
60
+ .map(e => e.name)
61
+ const loaded = await Promise.all(names.map(async (name) => {
62
+ try {
63
+ const content = await readFile(join(MEMORY_DIR, name), 'utf8')
64
+ return { file: name, content }
65
+ } catch {
66
+ return null
67
+ }
68
+ }))
69
+ return loaded.filter(Boolean)
70
+ } catch {
71
+ return []
60
72
  }
73
+ }
61
74
 
62
- function textOf(message) {
63
- const blocks = Array.isArray(message?.content) ? message.content : []
64
- const texts = blocks.filter(b => b?.type === 'text').map(b => b.text).filter(Boolean)
65
- return texts.length ? texts.join('\n') : null
75
+ /** 按得分选相关文件,降序取 top N。 */
76
+ function selectRelevant(query, files) {
77
+ return files
78
+ .map(f => ({ ...f, score: score(query, f.content) }))
79
+ .filter(f => f.score > 0)
80
+ .sort((a, b) => b.score - a.score)
81
+ .slice(0, MAX_RESULTS)
82
+ }
83
+
84
+ /** 解析 frontmatter 的 name/description/type(兼容顶层与 metadata 嵌套两种 type)。 */
85
+ function parseFrontmatter(content) {
86
+ const m = content.match(/^---\n([\s\S]*?)\n---/)
87
+ if (!m) return { name: '', description: '', type: '' }
88
+ const body = m[1]
89
+ const grab = (key) => {
90
+ const hit = body.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'))
91
+ if (!hit) return ''
92
+ return hit[1].replace(/^["']|["']$/g, '').trim()
93
+ }
94
+ let type = grab('type')
95
+ if (!type) {
96
+ const nested = body.match(/^metadata:\s*\n(?:\s+[^\n]+\n)*?\s+type:\s*(\S+)/m)
97
+ if (nested) type = nested[1]
66
98
  }
99
+ return { name: grab('name'), description: grab('description'), type }
100
+ }
101
+
102
+ /** 防路径穿越:只取 basename,且必须在 memory 目录内(.md,排除索引)。 */
103
+ function safeName(raw) {
104
+ const name = basename(String(raw || ''))
105
+ if (!name || !name.endsWith('.md') || name === 'MEMORY.md') return null
106
+ return name
107
+ }
67
108
 
68
- // 1. 会话启动:同步注入上个会话的记忆缓存
69
- // 注意:事件名是 'agent/session-start'('emit' 只是分发模式,不是事件名)
70
- ctx.on('agent/session-start', (payload) => {
71
- const { agent } = payload
72
- if (cachedContext) {
73
- agent.inject(pluginMessage(`以下是过往会话沉淀的记忆(sage-mem 检索):\n\n${cachedContext}`, 'sage-mem'))
74
- }
109
+ /**
110
+ * 手动 @Remote marker 注册(Node 24 不解析装饰器语法,手写 decorator context)。
111
+ */
112
+ function markRemote(cls, method, exportName) {
113
+ const instance = Object.create(cls.prototype)
114
+ Remote(exportName)(undefined, {
115
+ kind: 'method',
116
+ name: method,
117
+ private: false,
118
+ static: false,
119
+ addInitializer(fn) {
120
+ fn.call(instance)
121
+ },
75
122
  })
123
+ }
76
124
 
77
- // 2. 会话内事件:写入记忆
78
- ctx.on('session/event', (subject, event) => {
79
- const sessionId = subject?.header?.id
80
- if (!sessionId) return
81
-
82
- switch (event.type) {
83
- case 'user/message': {
84
- const text = textOf(event.data)
85
- if (!text) return
86
- post('/api/sessions/init', { contentSessionId: sessionId, project: PROJECT, prompt: text })
87
- break
88
- }
89
- case 'assistant/message': {
90
- // payload 是 { turn, step, message, usage },message 嵌套一层
91
- const text = textOf(event.data?.message)
92
- if (text) lastAssistantText = text
93
- break
94
- }
95
- case 'tool/call': {
96
- pendingCalls.set(event.data.callId, { name: event.data.name, arguments: event.data.arguments })
97
- break
98
- }
99
- case 'tool/result': {
100
- const message = event.data?.message
101
- const call = pendingCalls.get(message?.callId)
102
- pendingCalls.delete(message?.callId)
103
- if (!call) return
104
- post('/api/sessions/observations', {
105
- contentSessionId: sessionId,
106
- tool_name: call.name,
107
- tool_input: call.arguments,
108
- tool_response: message.content,
109
- })
110
- break
111
- }
112
- case 'turn/end': {
113
- post('/api/sessions/summarize', {
114
- contentSessionId: sessionId,
115
- ...(lastAssistantText ? { last_assistant_message: lastAssistantText } : {}),
125
+ export class MemoryGateway extends TypertRemoteService {
126
+ constructor(ctx) {
127
+ super(ctx, 'memory')
128
+
129
+ // 按问题检索注入:system-prompt/assemble 是异步 waterfall,监听器可 await。
130
+ // 从 agent.session 拿当前 user message,扫 memory 目录按双字匹配选相关
131
+ // 文件,读全文作为动态 context 段注入——让 agent 第一轮就「想起」。
132
+ ctx.on('system-prompt/assemble', async (assembly, context, next) => {
133
+ const assembled = await next()
134
+ try {
135
+ const agent = context?.agent
136
+ const session = agent?.session
137
+ if (!session || typeof session.deriveMessages !== 'function') return assembled
138
+ const messages = [...session.deriveMessages()]
139
+ const lastUser = messages.reverse().find(m => m?.role === 'user')
140
+ const text = extractText(lastUser?.content)
141
+ if (!text || text.length < 2) return assembled
142
+
143
+ const files = await scanMemoryFiles()
144
+ const relevant = selectRelevant(text, files)
145
+ if (relevant.length === 0) return assembled
146
+
147
+ const parts = relevant.map(f => {
148
+ const body = f.content.length > MAX_CHARS_PER_FILE
149
+ ? f.content.slice(0, MAX_CHARS_PER_FILE) + '\n…(截断)'
150
+ : f.content
151
+ return `### ${f.file}\n${body}`
116
152
  })
117
- // 元认知捕获:回合最后一条 assistant 输出(装了 sage-meta 时是自检输出)
118
- // 作为带标记的 observation 发,worker 压缩时按 lesson 类型引导归类
119
- if (lastAssistantText) {
120
- post('/api/sessions/observations', {
121
- contentSessionId: sessionId,
122
- tool_name: 'meta/self-check',
123
- tool_input: { turn: event.data?.turn },
124
- tool_response: lastAssistantText,
125
- })
153
+
154
+ return {
155
+ ...assembled,
156
+ contexts: [...(assembled.contexts ?? []), {
157
+ name: 'sage-mem:recall',
158
+ order: 1000,
159
+ text: `以下是与你当前问题相关的历史记忆(文件式,来自 ${MEMORY_DIR}):\n\n${parts.join('\n\n')}`,
160
+ }],
126
161
  }
127
- // 拉取最新记忆上下文,缓存给下一个会话注入
128
- fetch(`${WORKER_URL}/api/context/inject?project=${encodeURIComponent(PROJECT)}`, {
129
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
130
- })
131
- .then(r => (r.ok ? r.text() : null))
132
- .then(text => {
133
- if (text) cachedContext = text
134
- })
135
- .catch(() => {})
136
- break
162
+ } catch {
163
+ return assembled
137
164
  }
138
- }
139
- })
165
+ })
166
+ }
167
+
168
+ /** 列出 memory 目录全部记忆文件(文件名 + 类型 + 描述 + 大小)。 */
169
+ async listFiles() {
170
+ const files = await scanMemoryFiles()
171
+ return files.map(f => {
172
+ const meta = parseFrontmatter(f.content)
173
+ return {
174
+ file: f.file,
175
+ type: meta.type || 'reference',
176
+ description: meta.description || '',
177
+ size: f.content.length,
178
+ }
179
+ })
180
+ }
181
+
182
+ /** 读单个记忆文件全文。 */
183
+ async readFile(name) {
184
+ const safe = safeName(name)
185
+ if (!safe) throw new Error('sage-mem: invalid file name')
186
+ const content = await readFile(join(MEMORY_DIR, safe), 'utf8')
187
+ return { name: safe, content }
188
+ }
189
+
190
+ /** 写(新增或覆盖)单个记忆文件。 */
191
+ async writeFile(name, content) {
192
+ const safe = safeName(name)
193
+ if (!safe) throw new Error('sage-mem: invalid file name')
194
+ await writeFile(join(MEMORY_DIR, safe), String(content ?? ''), 'utf8')
195
+ return { ok: true, file: safe }
196
+ }
197
+
198
+ /** 删除单个记忆文件。 */
199
+ async deleteFile(name) {
200
+ const safe = safeName(name)
201
+ if (!safe) throw new Error('sage-mem: invalid file name')
202
+ await unlink(join(MEMORY_DIR, safe))
203
+ return { ok: true }
204
+ }
140
205
  }
206
+
207
+ markRemote(MemoryGateway, 'listFiles', 'listFiles')
208
+ markRemote(MemoryGateway, 'readFile', 'readFile')
209
+ markRemote(MemoryGateway, 'writeFile', 'writeFile')
210
+ markRemote(MemoryGateway, 'deleteFile', 'deleteFile')
211
+
212
+ export default MemoryGateway
@@ -0,0 +1,90 @@
1
+ /**
2
+ * sage-mem — 手写 strict typert host manifest(对齐官方生成文件格式)。
3
+ * typert-loader 在插件挂载时读 package.json 的 exports["./typert"],
4
+ * import 本文件并把 TYPERT 注册进 ctx.typert.local(strict 定义)。
5
+ * schema 必须是 zod v4 实例(typert-loader 校验 "_zod" in schema)。
6
+ */
7
+ import { z } from 'zod'
8
+
9
+ const fileNameSchema = z.string()
10
+ const fileContentSchema = z.string()
11
+
12
+ const fileSchema = z.object({
13
+ 'file': z.string().readonly(),
14
+ 'type': z.string().readonly(),
15
+ 'description': z.string().readonly(),
16
+ 'size': z.number().readonly(),
17
+ }).readonly()
18
+
19
+ const listResultSchema = z.array(fileSchema)
20
+ const readResultSchema = z.object({
21
+ 'name': z.string().readonly(),
22
+ 'content': z.string().readonly(),
23
+ }).readonly()
24
+ const writeResultSchema = z.object({
25
+ 'ok': z.boolean().readonly(),
26
+ 'file': z.string().readonly(),
27
+ }).readonly()
28
+ const deleteResultSchema = z.object({
29
+ 'ok': z.boolean().readonly(),
30
+ }).readonly()
31
+
32
+ export const TYPERT = {
33
+ package: 'sage-mem',
34
+ face: 'host',
35
+ schemas: [],
36
+ invocations: [
37
+ {
38
+ id: 'sage-mem#memory/listFiles',
39
+ service: 'memory',
40
+ namespace: 'memory',
41
+ method: 'listFiles',
42
+ invocation: { kind: 'direct' },
43
+ parameters: [],
44
+ result: { mode: 'strict', typeSymbol: 'sage-mem/types#FileList', schema: listResultSchema },
45
+ sourceLocation: { "file": "workspace/sage-mem/lib/index.js", "line": 1, "column": 1 },
46
+ },
47
+ {
48
+ id: 'sage-mem#memory/readFile',
49
+ service: 'memory',
50
+ namespace: 'memory',
51
+ method: 'readFile',
52
+ invocation: { kind: 'direct' },
53
+ parameters: [
54
+ { name: 'name', wire: 'name', source: 'json', codec: { mode: 'strict', typeSymbol: 'sage-mem/types#FileName', schema: fileNameSchema } },
55
+ ],
56
+ result: { mode: 'strict', typeSymbol: 'sage-mem/types#FileContent', schema: readResultSchema },
57
+ sourceLocation: { "file": "workspace/sage-mem/lib/index.js", "line": 1, "column": 1 },
58
+ },
59
+ {
60
+ id: 'sage-mem#memory/writeFile',
61
+ service: 'memory',
62
+ namespace: 'memory',
63
+ method: 'writeFile',
64
+ invocation: { kind: 'direct' },
65
+ parameters: [
66
+ { name: 'name', wire: 'name', source: 'json', codec: { mode: 'strict', typeSymbol: 'sage-mem/types#FileName', schema: fileNameSchema } },
67
+ { name: 'content', wire: 'content', source: 'json', codec: { mode: 'strict', typeSymbol: 'sage-mem/types#FileContent', schema: fileContentSchema } },
68
+ ],
69
+ result: { mode: 'strict', typeSymbol: 'sage-mem/types#WriteResult', schema: writeResultSchema },
70
+ sourceLocation: { "file": "workspace/sage-mem/lib/index.js", "line": 1, "column": 1 },
71
+ },
72
+ {
73
+ id: 'sage-mem#memory/deleteFile',
74
+ service: 'memory',
75
+ namespace: 'memory',
76
+ method: 'deleteFile',
77
+ invocation: { kind: 'direct' },
78
+ parameters: [
79
+ { name: 'name', wire: 'name', source: 'json', codec: { mode: 'strict', typeSymbol: 'sage-mem/types#FileName', schema: fileNameSchema } },
80
+ ],
81
+ result: { mode: 'strict', typeSymbol: 'sage-mem/types#DeleteResult', schema: deleteResultSchema },
82
+ sourceLocation: { "file": "workspace/sage-mem/lib/index.js", "line": 1, "column": 1 },
83
+ },
84
+ ],
85
+ model: {
86
+ "services": [],
87
+ "events": [],
88
+ "objects": [],
89
+ },
90
+ }
package/package.json CHANGED
@@ -1,25 +1,44 @@
1
1
  {
2
2
  "name": "sage-mem",
3
- "description": "Memory plugin for DeepSeek Harness (DSH) — cross-session memory with Chinese-first full-text search",
4
- "version": "0.1.2",
3
+ "description": "File-based memory plugin for DeepSeek Harness (DSH) — cross-session memory in transparent markdown files",
4
+ "version": "0.4.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
8
8
  ".": "./lib/index.js",
9
+ "./client": "./lib/client.js",
10
+ "./typert": "./lib/typert.host.js",
9
11
  "./package.json": "./package.json"
10
12
  },
11
13
  "files": [
12
14
  "lib/index.js",
13
- "cordis.patch.yml"
15
+ "lib/client.js",
16
+ "lib/typert.host.js",
17
+ "cordis.patch.yml",
18
+ "NOTICE"
14
19
  ],
15
- "license": "MIT",
20
+ "license": "Apache-2.0",
16
21
  "dsh": {
17
22
  "bundle": {
18
23
  "patch": "./cordis.patch.yml"
24
+ },
25
+ "client": {
26
+ "platform": "web",
27
+ "inject": [
28
+ "@deepseek-ai/dsh-client-locale",
29
+ "@deepseek-ai/dsh-client-runtime"
30
+ ]
19
31
  }
20
32
  },
33
+ "dependencies": {
34
+ "zod": "^4.4.3"
35
+ },
21
36
  "peerDependencies": {
22
- "@deepseek-ai/cordis": "^4.0.1"
37
+ "@deepseek-ai/cordis": "^4.0.1",
38
+ "@deepseek-ai/dsh-typert-protocol": "^0.1.0-rc.6",
39
+ "@deepseek-ai/dsh-client-locale": "^0.1.0-rc.6",
40
+ "@deepseek-ai/dsh-client-runtime": "^0.1.0-rc.6",
41
+ "react": "^18.0.0"
23
42
  },
24
43
  "repository": {
25
44
  "type": "git",