sage-mem 0.1.3 → 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/NOTICE +1 -1
- package/README.md +58 -60
- package/lib/client.js +432 -0
- package/lib/index.js +192 -120
- package/lib/typert.host.js +90 -0
- package/package.json +21 -3
package/NOTICE
CHANGED
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
|
-
|
|
7
|
+
## 为什么用文件
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
DSH 原生没有记忆系统,每个会话都是白纸。市面上的记忆方案大多走 SQLite + 常驻 worker:
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
- 记忆写进数据库,**不透明**——想检查存了什么得查表,想清理要连数据库
|
|
12
|
+
- 事件自动捕获会**膨胀**——"用户打了个招呼"这种无实质内容也被存进去
|
|
13
|
+
- 需要一个**常驻 worker 进程** + 端口,多一份运维负担
|
|
14
|
+
|
|
15
|
+
sage-mem 换成文件式:每条记忆一个 markdown 文件,直接用编辑器打开就能看、能改、能删。存不存由 agent 按规则判断,不是事件全捕获。没有 worker、没有 SQLite、没有端口。
|
|
12
16
|
|
|
13
17
|
## 功能
|
|
14
18
|
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
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
|
|
25
|
-
│
|
|
26
|
-
▼
|
|
27
|
-
sage-mem worker(Bun 常驻,fork 自 claude-mem)← gezi-wen/claude-mem
|
|
28
|
-
│
|
|
29
|
+
└─ sage-mem 插件(按问题检索 + 注入)← 本仓库
|
|
30
|
+
│ Node fs 直读
|
|
29
31
|
▼
|
|
30
|
-
|
|
32
|
+
memory/ 目录(markdown 文件,4 类)
|
|
33
|
+
├── user_*.md
|
|
34
|
+
├── feedback_*.md
|
|
35
|
+
├── project_*.md
|
|
36
|
+
├── reference_*.md
|
|
37
|
+
└── MEMORY.md ← 索引
|
|
31
38
|
```
|
|
32
39
|
|
|
33
|
-
|
|
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
|
|
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
|
-
|
|
107
|
+
sage-mem 是第三道:**我下次应该怎么想**——跨会话沉淀事实与教训。
|
|
108
108
|
|
|
109
|
-
##
|
|
109
|
+
## 旧版
|
|
110
110
|
|
|
111
|
-
|
|
112
|
-
- worker 不可用时插件静默跳过(不阻塞 DSH),记忆功能暂缺
|
|
113
|
-
- MVP 存储统一在 `project=sage` 空间,按工作区分项目是后续计划
|
|
111
|
+
本仓库早期是 SQLite + worker 架构,已归档到 [`sqlite-worker`](../../tree/sqlite-worker) 分支。文件式是继任实现。
|
|
114
112
|
|
|
115
113
|
## License
|
|
116
114
|
|
|
117
|
-
|
|
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
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* turn/end 时已就绪,session-start 同步注入必然生效。
|
|
10
|
+
* 写入靠 AGENTS.md 的「记忆使用」规则引导 agent 自己判断 + 用文件工具写
|
|
11
|
+
* memory 目录——透明、可检查、防膨胀。无 worker、无 SQLite、无端口。
|
|
14
12
|
*
|
|
15
|
-
* worker
|
|
16
|
-
* (sage-bundle 阶段统一装配,先起 worker 再起 dsh)。
|
|
17
|
-
*
|
|
18
|
-
* 这是 Sage 的第三道题:我下次应该怎么想 —— 跨会话沉淀事实与教训。
|
|
13
|
+
* 旧 worker 版见 git 分支 `sqlite-worker`。
|
|
19
14
|
*/
|
|
20
15
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
26
|
-
|
|
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
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
-
|
|
78
|
-
ctx
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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
|
-
|
|
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,15 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sage-mem",
|
|
3
|
-
"description": "
|
|
4
|
-
"version": "0.
|
|
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",
|
|
15
|
+
"lib/client.js",
|
|
16
|
+
"lib/typert.host.js",
|
|
13
17
|
"cordis.patch.yml",
|
|
14
18
|
"NOTICE"
|
|
15
19
|
],
|
|
@@ -17,10 +21,24 @@
|
|
|
17
21
|
"dsh": {
|
|
18
22
|
"bundle": {
|
|
19
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
|
+
]
|
|
20
31
|
}
|
|
21
32
|
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"zod": "^4.4.3"
|
|
35
|
+
},
|
|
22
36
|
"peerDependencies": {
|
|
23
|
-
"@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"
|
|
24
42
|
},
|
|
25
43
|
"repository": {
|
|
26
44
|
"type": "git",
|