icex-dsh-memory 0.0.0-stage → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/client.js +260 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +106 -0
- package/icon.svg +5 -0
- package/index.js +647 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +43 -4
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
#
|
|
1
|
+
# icex-dsh-memory
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cross-session memory for DeepSeek Harness, in one host plugin.
|
|
4
|
+
|
|
5
|
+
- **Injected once per session** — a budgeted digest of durable facts enters the context as an inbox message (`agent.inject`), so the system-prompt prefix stays stable and the model can see exactly which memories it received in the session log.
|
|
6
|
+
- **Settings-page editor** — the plugin's page in Plugins shows the current store and lets you edit it, global or per working directory.
|
|
7
|
+
- **One tool, five actions** — `memory` with `add`, `replace`, `forget`, `search`, `list`.
|
|
8
|
+
- **Plain Markdown store** you can read, edit and version: `~/.dsh/memory/MEMORY.md` (global) and `<cwd>/.dsh/memory/MEMORY.md` (per working directory).
|
|
9
|
+
- **Provenance** — every entry carries `src=<session>@<seq>` and a date; memory is an index into the session log, never a replacement for it.
|
|
10
|
+
- **Self-maintaining** — on the first session after a week, the plugin merges near-duplicates and archives entries beyond the cap; nothing is deleted, and `memory consolidate` runs it on demand.
|
|
11
|
+
- **No dependencies** — the tool API is loaded from the running app; when it cannot be found the plugin still injects memory and the policy falls back to editing the file with the built-in filesystem tools.
|
|
12
|
+
|
|
13
|
+
See [docs/DETAIL.md](docs/DETAIL.md) for the store format, budgets, and known limits.
|
package/client.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* icex-dsh-memory client bundle: the settings-page editor for the memory store.
|
|
3
|
+
*
|
|
4
|
+
* The Host half serves GET/POST /api/icex-memory (global or project scope); this
|
|
5
|
+
* module renders the textarea and calls it. No build step: the DSH module loader
|
|
6
|
+
* runs the factory and React comes from the platform module table.
|
|
7
|
+
*/
|
|
8
|
+
window.__ModuleLoader__.load({
|
|
9
|
+
id: 'icex-dsh-memory',
|
|
10
|
+
factory(require) {
|
|
11
|
+
const React = require('react')
|
|
12
|
+
const h = React.createElement
|
|
13
|
+
const useEffect = React.useEffect
|
|
14
|
+
const useState = React.useState
|
|
15
|
+
|
|
16
|
+
const PACKAGE = 'icex-dsh-memory'
|
|
17
|
+
const NS = 'icex-dsh-memory'
|
|
18
|
+
|
|
19
|
+
const en = {
|
|
20
|
+
'settings.title': 'Memory',
|
|
21
|
+
'settings.scope': 'Scope',
|
|
22
|
+
'settings.scope.global': 'Global',
|
|
23
|
+
'settings.scope.project': 'Project',
|
|
24
|
+
'settings.dir.label': 'Working directory',
|
|
25
|
+
'settings.dir.placeholder': '/Users/me/codes/project',
|
|
26
|
+
'settings.dir.load': 'Load',
|
|
27
|
+
'settings.loading': 'Loading…',
|
|
28
|
+
'settings.saving': 'Saving…',
|
|
29
|
+
'settings.save': 'Save',
|
|
30
|
+
'settings.reload': 'Reload',
|
|
31
|
+
'settings.placeholder': 'One fact per line: - [pref] … <!-- id=… src=… at=… -->',
|
|
32
|
+
'settings.entries': '{count} entries',
|
|
33
|
+
'settings.path': 'File: {path}',
|
|
34
|
+
'settings.saved': 'Saved. New sessions pick it up at startup.',
|
|
35
|
+
'settings.unsaved': 'Unsaved changes.',
|
|
36
|
+
'settings.error': 'Failed: {message}',
|
|
37
|
+
'settings.hint': 'Entries are injected at the start of the next session. Keep one fact per line, at most 200 characters.',
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const zh = {
|
|
41
|
+
'settings.title': '记忆',
|
|
42
|
+
'settings.scope': '作用域',
|
|
43
|
+
'settings.scope.global': '全局',
|
|
44
|
+
'settings.scope.project': '项目',
|
|
45
|
+
'settings.dir.label': '工作目录',
|
|
46
|
+
'settings.dir.placeholder': '/Users/me/codes/project',
|
|
47
|
+
'settings.dir.load': '读取',
|
|
48
|
+
'settings.loading': '读取中…',
|
|
49
|
+
'settings.saving': '保存中…',
|
|
50
|
+
'settings.save': '保存',
|
|
51
|
+
'settings.reload': '重新读取',
|
|
52
|
+
'settings.placeholder': '一行一条:- [pref] … <!-- id=… src=… at=… -->',
|
|
53
|
+
'settings.entries': '{count} 条',
|
|
54
|
+
'settings.path': '文件:{path}',
|
|
55
|
+
'settings.saved': '已保存,下个会话开始时生效。',
|
|
56
|
+
'settings.unsaved': '有未保存的修改。',
|
|
57
|
+
'settings.error': '失败:{message}',
|
|
58
|
+
'settings.hint': '记忆会在下一个会话开始时注入。一行一条事实,每条不超过 200 字。',
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Minimal translator with {name} interpolation over the slot's locale texts. */
|
|
62
|
+
function translator(source) {
|
|
63
|
+
const table = source !== null && typeof source === 'object' ? source : en
|
|
64
|
+
return function t(key, values) {
|
|
65
|
+
const template = typeof table[key] === 'string' ? table[key] : key
|
|
66
|
+
if (values === undefined) return template
|
|
67
|
+
return template.replace(/\{(\w+)\}/g, function (match, name) {
|
|
68
|
+
return values[name] === undefined ? match : String(values[name])
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function installStyles() {
|
|
74
|
+
if (typeof document === 'undefined') return function () {}
|
|
75
|
+
const style = document.createElement('style')
|
|
76
|
+
style.dataset.icexMemory = 'true'
|
|
77
|
+
style.textContent = [
|
|
78
|
+
'.icex-memory { display: flex; flex-direction: column; gap: 12px; }',
|
|
79
|
+
'.icex-memory-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }',
|
|
80
|
+
'.icex-memory-tabs { display: inline-flex; border: 1px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-md); overflow: hidden; }',
|
|
81
|
+
'.icex-memory-tab { padding: 4px 12px; border: 0; background: transparent; color: var(--dsw-alias-label-secondary); cursor: pointer; font: inherit; }',
|
|
82
|
+
'.icex-memory-tab[data-active="true"] { background: var(--dsw-alias-state-business-primary); color: var(--dsw-alias-label-on-color); }',
|
|
83
|
+
'.icex-memory-dir { flex: 1 1 240px; min-width: 160px; padding: 5px 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-md); background: var(--dsw-specific-menu); color: var(--dsw-alias-label-primary); font: inherit; }',
|
|
84
|
+
'.icex-memory-text { width: 100%; min-height: 260px; resize: vertical; padding: 10px; border: 1px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-md); background: var(--dsw-specific-menu); color: var(--dsw-alias-label-primary); font-family: var(--dsw-font-mono, ui-monospace, monospace); font-size: 12px; line-height: 1.55; white-space: pre; }',
|
|
85
|
+
'.icex-memory-button { padding: 5px 12px; border: 1px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-md); background: transparent; color: var(--dsw-alias-label-primary); cursor: pointer; font: inherit; }',
|
|
86
|
+
'.icex-memory-button[data-primary="true"] { background: var(--dsw-alias-state-business-primary); border-color: transparent; color: var(--dsw-alias-label-on-color); }',
|
|
87
|
+
'.icex-memory-button:disabled { opacity: 0.5; cursor: default; }',
|
|
88
|
+
'.icex-memory-meta { color: var(--dsw-alias-label-secondary); font-size: 12px; }',
|
|
89
|
+
'.icex-memory-hint { color: var(--dsw-alias-label-secondary); font-size: 12px; }',
|
|
90
|
+
'.icex-memory-error { color: var(--dsw-alias-state-error-primary); font-size: 12px; }',
|
|
91
|
+
].join('\n')
|
|
92
|
+
document.head.appendChild(style)
|
|
93
|
+
return function () {
|
|
94
|
+
style.remove()
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function MemoryPanel(props) {
|
|
99
|
+
const t = translator(props.t)
|
|
100
|
+
const [scope, setScope] = useState('global')
|
|
101
|
+
const [dir, setDir] = useState('')
|
|
102
|
+
const [text, setText] = useState('')
|
|
103
|
+
const [path, setPath] = useState('')
|
|
104
|
+
const [entries, setEntries] = useState(0)
|
|
105
|
+
const [dirty, setDirty] = useState(false)
|
|
106
|
+
const [busy, setBusy] = useState(false)
|
|
107
|
+
const [message, setMessage] = useState(null)
|
|
108
|
+
|
|
109
|
+
function endpoint() {
|
|
110
|
+
const query = '?scope=' + scope + (scope === 'project' ? '&dir=' + encodeURIComponent(dir) : '')
|
|
111
|
+
return '/api/icex-memory' + query
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function load() {
|
|
115
|
+
setBusy(true)
|
|
116
|
+
setMessage(null)
|
|
117
|
+
try {
|
|
118
|
+
const response = await fetch(endpoint(), { credentials: 'same-origin' })
|
|
119
|
+
const body = await response.json()
|
|
120
|
+
if (body.ok !== true) throw new Error(body.error ?? response.status)
|
|
121
|
+
setText(body.text ?? '')
|
|
122
|
+
setPath(body.path ?? '')
|
|
123
|
+
setEntries(body.entries ?? 0)
|
|
124
|
+
setDirty(false)
|
|
125
|
+
} catch (error) {
|
|
126
|
+
setMessage({ kind: 'error', text: t('settings.error', { message: String(error.message ?? error) }) })
|
|
127
|
+
} finally {
|
|
128
|
+
setBusy(false)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function save() {
|
|
133
|
+
setBusy(true)
|
|
134
|
+
setMessage(null)
|
|
135
|
+
try {
|
|
136
|
+
const response = await fetch(endpoint(), {
|
|
137
|
+
method: 'POST',
|
|
138
|
+
credentials: 'same-origin',
|
|
139
|
+
headers: { 'content-type': 'application/json' },
|
|
140
|
+
body: JSON.stringify({ text }),
|
|
141
|
+
})
|
|
142
|
+
const body = await response.json()
|
|
143
|
+
if (body.ok !== true) throw new Error(body.error ?? response.status)
|
|
144
|
+
setEntries(body.entries ?? 0)
|
|
145
|
+
setPath(body.path ?? path)
|
|
146
|
+
setDirty(false)
|
|
147
|
+
setMessage({ kind: 'ok', text: t('settings.saved') })
|
|
148
|
+
} catch (error) {
|
|
149
|
+
setMessage({ kind: 'error', text: t('settings.error', { message: String(error.message ?? error) }) })
|
|
150
|
+
} finally {
|
|
151
|
+
setBusy(false)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
useEffect(() => {
|
|
156
|
+
if (scope === 'global') void load()
|
|
157
|
+
}, [scope])
|
|
158
|
+
|
|
159
|
+
if (props.view === 'summary') return null
|
|
160
|
+
|
|
161
|
+
return h('section', { className: 'icex-memory', 'aria-label': t('settings.title') },
|
|
162
|
+
h('div', { className: 'icex-memory-row' },
|
|
163
|
+
h('span', { className: 'icex-memory-meta' }, t('settings.scope')),
|
|
164
|
+
h('div', { className: 'icex-memory-tabs' },
|
|
165
|
+
['global', 'project'].map(function (value) {
|
|
166
|
+
return h('button', {
|
|
167
|
+
key: value,
|
|
168
|
+
type: 'button',
|
|
169
|
+
className: 'icex-memory-tab',
|
|
170
|
+
'data-active': scope === value ? 'true' : 'false',
|
|
171
|
+
onClick: function () {
|
|
172
|
+
setScope(value)
|
|
173
|
+
if (value === 'global') void load()
|
|
174
|
+
},
|
|
175
|
+
}, t('settings.scope.' + value))
|
|
176
|
+
}))),
|
|
177
|
+
scope === 'project'
|
|
178
|
+
? h('div', { className: 'icex-memory-row' },
|
|
179
|
+
h('span', { className: 'icex-memory-meta' }, t('settings.dir.label')),
|
|
180
|
+
h('input', {
|
|
181
|
+
className: 'icex-memory-dir',
|
|
182
|
+
value: dir,
|
|
183
|
+
placeholder: t('settings.dir.placeholder'),
|
|
184
|
+
spellCheck: false,
|
|
185
|
+
onChange: function (event) {
|
|
186
|
+
setDir(event.target.value)
|
|
187
|
+
},
|
|
188
|
+
onKeyDown: function (event) {
|
|
189
|
+
if (event.key === 'Enter') void load()
|
|
190
|
+
},
|
|
191
|
+
}),
|
|
192
|
+
h('button', {
|
|
193
|
+
type: 'button',
|
|
194
|
+
className: 'icex-memory-button',
|
|
195
|
+
disabled: busy || dir.trim() === '',
|
|
196
|
+
onClick: function () {
|
|
197
|
+
void load()
|
|
198
|
+
},
|
|
199
|
+
}, t('settings.dir.load')))
|
|
200
|
+
: null,
|
|
201
|
+
h('textarea', {
|
|
202
|
+
className: 'icex-memory-text',
|
|
203
|
+
spellCheck: false,
|
|
204
|
+
value: text,
|
|
205
|
+
placeholder: t('settings.placeholder'),
|
|
206
|
+
onChange: function (event) {
|
|
207
|
+
setText(event.target.value)
|
|
208
|
+
setDirty(true)
|
|
209
|
+
},
|
|
210
|
+
}),
|
|
211
|
+
h('div', { className: 'icex-memory-row' },
|
|
212
|
+
h('button', {
|
|
213
|
+
type: 'button',
|
|
214
|
+
className: 'icex-memory-button',
|
|
215
|
+
'data-primary': 'true',
|
|
216
|
+
disabled: busy || !dirty,
|
|
217
|
+
onClick: function () {
|
|
218
|
+
void save()
|
|
219
|
+
},
|
|
220
|
+
}, busy ? t('settings.saving') : t('settings.save')),
|
|
221
|
+
h('button', {
|
|
222
|
+
type: 'button',
|
|
223
|
+
className: 'icex-memory-button',
|
|
224
|
+
disabled: busy,
|
|
225
|
+
onClick: function () {
|
|
226
|
+
void load()
|
|
227
|
+
},
|
|
228
|
+
}, busy ? t('settings.loading') : t('settings.reload')),
|
|
229
|
+
h('span', { className: 'icex-memory-meta' }, t('settings.entries', { count: entries })),
|
|
230
|
+
dirty ? h('span', { className: 'icex-memory-meta' }, t('settings.unsaved')) : null),
|
|
231
|
+
message === null
|
|
232
|
+
? null
|
|
233
|
+
: h('div', {
|
|
234
|
+
className: message.kind === 'error' ? 'icex-memory-error' : 'icex-memory-meta',
|
|
235
|
+
role: message.kind === 'error' ? 'alert' : 'status',
|
|
236
|
+
}, message.text),
|
|
237
|
+
path === '' ? null : h('div', { className: 'icex-memory-meta' }, t('settings.path', { path })),
|
|
238
|
+
h('div', { className: 'icex-memory-hint' }, t('settings.hint')))
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function apply(ctx) {
|
|
242
|
+
ctx.effect(installStyles, 'icex-dsh-memory: styles')
|
|
243
|
+
ctx.effect(function () {
|
|
244
|
+
return ctx.locale.register(NS, { en: en, zh: zh })
|
|
245
|
+
}, 'icex-dsh-memory: locale')
|
|
246
|
+
ctx.slots.inject('plugins.bundle.config', function () {
|
|
247
|
+
return ctx.slots.register({
|
|
248
|
+
name: 'plugins.bundle.config',
|
|
249
|
+
key: PACKAGE,
|
|
250
|
+
locale: NS,
|
|
251
|
+
}, MemoryPanel)
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return {
|
|
256
|
+
inject: ['slots', 'locale'],
|
|
257
|
+
apply: apply,
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
})
|
package/cordis.patch.yml
ADDED
package/docs/DETAIL.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# Icex DSH Memory
|
|
2
|
+
|
|
3
|
+
给 DeepSeek Harness 加一层跨会话记忆。只做三件事:把事实存成可读的文件、在会话开始时注入一段有预算的摘要、给模型一个写入口。
|
|
4
|
+
|
|
5
|
+
## 存储
|
|
6
|
+
|
|
7
|
+
两个作用域,都是纯 Markdown,可以手改、可以进 git:
|
|
8
|
+
|
|
9
|
+
| 作用域 | 路径 | 用途 |
|
|
10
|
+
| --- | --- | --- |
|
|
11
|
+
| global | `~/.dsh/memory/MEMORY.md`(`$DSH_HOME` 优先) | 用户偏好、跨项目约定 |
|
|
12
|
+
| project | `<cwd>/.dsh/memory/MEMORY.md` | 只在这个工作目录生效的项目事实 |
|
|
13
|
+
|
|
14
|
+
一行一条:
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
- [pref] 回答要结论先行,不要铺垫 <!-- id=4c1a2b src=session-5f0adb65@42 at=2026-11-20 -->
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
- `kind`:`pref` / `project` / `pitfall` / `decision` / `tool`
|
|
21
|
+
- `id`:由内容与日期派生的 6 位短 id,`replace` / `forget` 用它定位
|
|
22
|
+
- `src`:产生这条事实的会话与事件序号;记忆指回原始日志,冲突时以日志为准
|
|
23
|
+
- `at`:写入日期
|
|
24
|
+
|
|
25
|
+
`add` 会做一次近似查重(同作用域、词集 Jaccard ≥ 0.85),命中时返回已有条目而不是新增;`replace` / `forget` 按行原地修改,文件里其他手写内容保持不动。
|
|
26
|
+
|
|
27
|
+
## 注入
|
|
28
|
+
|
|
29
|
+
每次 agent 创建时(`agent/created`)读取两个作用域,拼成一条 `<memory-context>` 消息,通过 `agent.inject` 放进收件箱:
|
|
30
|
+
|
|
31
|
+
- 只注入一次,不随每步变化;不动系统提示前缀,避免打掉 provider 的 KV cache
|
|
32
|
+
- 作为 `agent/inbox/spliced` 事件进日志,可在会话里回看"这次到底给了模型哪些记忆"
|
|
33
|
+
- 预算:全局 620 字符 / 项目 1000 字符,各取最近 8 / 12 条;装不下的条目收起并显式写"…N more",不静默截断
|
|
34
|
+
- 内容为空的会话不注入
|
|
35
|
+
|
|
36
|
+
## 工具
|
|
37
|
+
|
|
38
|
+
`memory`,一个工具五个 action:
|
|
39
|
+
|
|
40
|
+
| action | 参数 | 行为 |
|
|
41
|
+
| --- | --- | --- |
|
|
42
|
+
| `add` | `text`, `kind`, `scope` | 查重后追加一行,带 `src` 与日期 |
|
|
43
|
+
| `replace` | `id`, `text`, `kind` | 原地替换该条 |
|
|
44
|
+
| `forget` | `id` | 删除该条 |
|
|
45
|
+
| `search` | `query`, `scope` | 本地词集打分,返回最多 10 条 |
|
|
46
|
+
| `list` | `scope` | 最近 20 条 |
|
|
47
|
+
|
|
48
|
+
写入约束:单条 ≤200 字符、拒绝疑似密钥(`sk-…`、`token=`、私钥等)、`add` 自动查重。文件写入走"临时文件 + rename",避免并发写坏。
|
|
49
|
+
|
|
50
|
+
## 整理(自动 + 手动)
|
|
51
|
+
|
|
52
|
+
插件自己完成,不依赖任何定时器或后台进程:**每次会话开始检查一次**,距上次整理超过 `consolidateIntervalDays`(默认 7 天)就顺手跑一遍。
|
|
53
|
+
|
|
54
|
+
整理只做两件确定性的事,不调用模型、不删除内容:
|
|
55
|
+
|
|
56
|
+
1. **合并近似重复**:同一作用域内相似度 ≥ `dedupeSimilarity`(默认 0.85)的条目只留一条,被合并的进归档。
|
|
57
|
+
2. **控制条数**:单作用域超过 `maxEntries`(默认 60)时,最旧的条目移进 `MEMORY.archive.md`,不是删掉。
|
|
58
|
+
|
|
59
|
+
被移走的条目全部写在同目录的 `MEMORY.archive.md` 里,随时可以捞回来。运行结果记录在 `~/.dsh/memory/.state.json`(上次时间 + 本次报告),并用 `.consolidate.lock` 防止两个会话同时整理。
|
|
60
|
+
|
|
61
|
+
想立刻整理就调工具:`memory` + `action: consolidate`,返回合并和被归档的条数。
|
|
62
|
+
|
|
63
|
+
可调参数(写在 bundle 的 config 里,全部可选):
|
|
64
|
+
|
|
65
|
+
| 字段 | 默认 | 含义 |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `consolidateIntervalDays` | `7` | 两次自动整理的最小间隔天数 |
|
|
68
|
+
| `maxEntries` | `60` | 每个作用域保留的最大条数,超出部分归档 |
|
|
69
|
+
| `dedupeSimilarity` | `0.85` | 判定重复的相似度阈值(0.5–0.99) |
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
## 设置页编辑
|
|
73
|
+
|
|
74
|
+
插件在 **Plugins → Icex DSH Memory** 的配置区里提供一个「记忆」板块:
|
|
75
|
+
|
|
76
|
+
- 作用域切换:**全局**(`~/.dsh/memory/MEMORY.md`)或**项目**(填一个工作目录,编辑 `<dir>/.dsh/memory/MEMORY.md`)
|
|
77
|
+
- 直接编辑整个文件,保存后原子写入,下个会话开始时生效
|
|
78
|
+
- 显示条数、文件路径、未保存状态;保存时同样拦截疑似凭证,单文件上限 256 KiB
|
|
79
|
+
|
|
80
|
+
接口是 `GET/POST /api/icex-memory?scope=global|project&dir=<abs>`,只对已认证的本机浏览器 Peer 开放。
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
## 安装
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
cd ~/codes/icex-dsh-memory
|
|
87
|
+
# 在 Plugins 里用本地目录安装,或把该目录作为一个 bundle 加进 profile 的 dsh.profile.bundles
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
插件自行从运行中的 app 里加载 `@deepseek-ai/dsh-tools`;通过 `link:` 安装也不需要在本仓库跑 `pnpm install`。找不到时降级为"只注入 + 用文件工具编辑",不会报错中断会话。
|
|
91
|
+
|
|
92
|
+
## 验证
|
|
93
|
+
|
|
94
|
+
1. 新开一个会话,问"你的记忆里有我吗"——应能看到注入的摘要(也可在会话日志里找 `agent/inbox/spliced`)。
|
|
95
|
+
2. 说一条长期偏好,确认模型调用 `memory add`;检查 `~/.dsh/memory/MEMORY.md` 多了一行带 `src` 的条目。
|
|
96
|
+
3. 再开一个新会话,确认该条目出现在开场摘要里。
|
|
97
|
+
4. 说"这条不用了",确认走 `forget` 或 `replace`,文件里对应行消失或更新。
|
|
98
|
+
5. 用 context 面板对比:注入 token 应 ≤ 1.5k;同一会话多轮之间 `cacheRead` 不应因记忆抖动。
|
|
99
|
+
|
|
100
|
+
## 已知边界
|
|
101
|
+
|
|
102
|
+
- **只注入一次**:同一会话内新增的记忆不会中途重新注入,下个会话才生效(这是为了缓存稳定)。
|
|
103
|
+
- **不做 LLM 蒸馏**:什么时候写由模型判断,整理只做确定性的去重与归档,不改写措辞、不调用模型;检索也是词集打分,没有 embedding。
|
|
104
|
+
- **不做向量召回**:需要原始对话细节时,用官方 opt-in 的 `dsh-tool-session-query`(`session_search`,作用域为 cwd 完全相同)。
|
|
105
|
+
- **project 作用域按工作目录精确匹配**:在子目录开新会话不会继承父目录的项目记忆。
|
|
106
|
+
- 超过预算的旧条目不会自动淘汰,只是不进入摘要;需要长期维护时手动 `list` + `forget`。
|
package/icon.svg
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
|
|
2
|
+
<rect x="6" y="10" width="52" height="44" rx="8" fill="none" stroke="#4B5563" stroke-width="3"/>
|
|
3
|
+
<path d="M16 24h32M16 34h24M16 44h28" stroke="#4B5563" stroke-width="3" stroke-linecap="round"/>
|
|
4
|
+
<circle cx="50" cy="44" r="7" fill="#4B5563"/>
|
|
5
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* icex-dsh-memory — cross-session memory for DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* Two halves, both host-side:
|
|
5
|
+
* 1. A budgeted digest of durable facts is injected once per agent as an inbox
|
|
6
|
+
* message (`agent.inject`), so it never disturbs the system-prompt prefix and
|
|
7
|
+
* stays visible in the session log.
|
|
8
|
+
* 2. A `memory` tool reads and writes those facts, one line per fact, with a
|
|
9
|
+
* provenance pointer back to the session that produced it.
|
|
10
|
+
*
|
|
11
|
+
* The store is plain Markdown the user can edit by hand:
|
|
12
|
+
* ~/.dsh/memory/MEMORY.md global facts
|
|
13
|
+
* <cwd>/.dsh/memory/MEMORY.md project facts (same working directory)
|
|
14
|
+
*
|
|
15
|
+
* Format, one entry per line:
|
|
16
|
+
* - [pref] Answer conclusions first. <!-- id=m7k2 src=session-abc@42 at=2026-11-20 -->
|
|
17
|
+
*
|
|
18
|
+
* `@deepseek-ai/dsh-tools` is optional: when it resolves, the model gets the
|
|
19
|
+
* `memory` tool; when it does not, the policy falls back to editing the file
|
|
20
|
+
* with the built-in filesystem tools.
|
|
21
|
+
*/
|
|
22
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, statSync } from 'node:fs'
|
|
23
|
+
import { createHash } from 'node:crypto'
|
|
24
|
+
import { homedir } from 'node:os'
|
|
25
|
+
import { dirname, join } from 'node:path'
|
|
26
|
+
import { pathToFileURL } from 'node:url'
|
|
27
|
+
|
|
28
|
+
export const name = 'icex-dsh-memory'
|
|
29
|
+
export const inject = ['systemPrompt', 'tools']
|
|
30
|
+
|
|
31
|
+
/** Absolute directory of the global memory store. */
|
|
32
|
+
export const HOME = process.env.DSH_HOME && process.env.DSH_HOME !== ''
|
|
33
|
+
? join(process.env.DSH_HOME, 'memory')
|
|
34
|
+
: join(homedir(), '.dsh', 'memory')
|
|
35
|
+
|
|
36
|
+
const KINDS = ['pref', 'project', 'pitfall', 'decision', 'tool']
|
|
37
|
+
const GLOBAL_FILE = join(HOME, 'MEMORY.md')
|
|
38
|
+
const STATE_FILE = join(HOME, '.state.json')
|
|
39
|
+
const LOCK_FILE = join(HOME, '.consolidate.lock')
|
|
40
|
+
const CONSOLIDATE = { intervalDays: 7, maxEntries: 60, dedupe: 0.85 }
|
|
41
|
+
const ENTRY_RE = /^- \[([a-z]+)\] (.+?)(?: <!-- id=([0-9a-z]+) src=(\S+) at=([0-9-]+) -->)?$/u
|
|
42
|
+
const MAX_TEXT = 200
|
|
43
|
+
const BUDGET = { global: 1000, project: 1200 }
|
|
44
|
+
const TAKE = { global: 12, project: 12 }
|
|
45
|
+
|
|
46
|
+
/** A single durable fact. */
|
|
47
|
+
export function makeEntry(text, kind, src) {
|
|
48
|
+
const trimmed = String(text).trim().replace(/\s+/g, ' ')
|
|
49
|
+
if (trimmed === '') throw new Error('memory text is empty')
|
|
50
|
+
if (trimmed.length > MAX_TEXT) throw new Error('memory text exceeds ' + MAX_TEXT + ' characters')
|
|
51
|
+
if (!KINDS.includes(kind)) throw new Error('unknown memory kind: ' + kind)
|
|
52
|
+
if (looksSecret(trimmed)) throw new Error('refusing to store something that looks like a secret')
|
|
53
|
+
const at = new Date().toISOString().slice(0, 10)
|
|
54
|
+
const id = createHash('sha256').update(trimmed + '\u0000' + at).digest('hex').slice(0, 6)
|
|
55
|
+
return { id, kind, text: trimmed, src: src === '' ? 'manual' : src, at }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Cheap secret screen: never persist credentials. */
|
|
59
|
+
export function looksSecret(text) {
|
|
60
|
+
return /(sk-[A-Za-z0-9]{8,}|ghp_[A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|-----BEGIN [A-Z ]*PRIVATE KEY|(?:password|passwd|api[_-]?key|token|secret)\s*[:=]\s*\S{4,})/i.test(text)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Render one entry as a store line. */
|
|
64
|
+
export function formatEntry(entry) {
|
|
65
|
+
return '- [' + entry.kind + '] ' + entry.text + ' <!-- id=' + entry.id + ' src=' + entry.src + ' at=' + entry.at + ' -->'
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Parse store text into entries, keeping unrelated user prose out of the way. */
|
|
69
|
+
export function parseEntries(text) {
|
|
70
|
+
const entries = []
|
|
71
|
+
for (const line of String(text).split('\n')) {
|
|
72
|
+
const match = ENTRY_RE.exec(line.trim())
|
|
73
|
+
if (match === null) continue
|
|
74
|
+
entries.push({
|
|
75
|
+
id: match[3] === undefined ? '' : match[3],
|
|
76
|
+
kind: match[1],
|
|
77
|
+
text: match[2].trim(),
|
|
78
|
+
src: match[4] === undefined ? '' : match[4],
|
|
79
|
+
at: match[5] === undefined ? '' : match[5],
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
return entries
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Read a store file, returning entries and the raw line array. */
|
|
86
|
+
export function readStore(file) {
|
|
87
|
+
if (!existsSync(file)) return { entries: [], lines: [] }
|
|
88
|
+
const text = readFileSync(file, 'utf8')
|
|
89
|
+
return { entries: parseEntries(text), lines: text.split('\n') }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Write a file atomically (tmp beside the target, then rename). */
|
|
93
|
+
function writeAtomic(file, text) {
|
|
94
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
95
|
+
const tmp = file + '.tmp-' + process.pid + '-' + Date.now()
|
|
96
|
+
writeFileSync(tmp, text, 'utf8')
|
|
97
|
+
renameSync(tmp, file)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Append one entry, preserving any prose the user keeps in the file. */
|
|
101
|
+
export function appendEntry(file, entry) {
|
|
102
|
+
const { lines } = readStore(file)
|
|
103
|
+
const body = lines.length === 0 ? [] : lines.slice()
|
|
104
|
+
while (body.length > 0 && body[body.length - 1].trim() === '') body.pop()
|
|
105
|
+
body.push(formatEntry(entry), '')
|
|
106
|
+
writeAtomic(file, body.join('\n'))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Replace the entry with this id, in place. */
|
|
110
|
+
export function replaceEntry(file, id, entry) {
|
|
111
|
+
const { lines } = readStore(file)
|
|
112
|
+
const index = lines.findIndex((line) => {
|
|
113
|
+
const match = ENTRY_RE.exec(line.trim())
|
|
114
|
+
return match !== null && match[3] === id
|
|
115
|
+
})
|
|
116
|
+
if (index < 0) return false
|
|
117
|
+
lines[index] = formatEntry({ ...entry, id })
|
|
118
|
+
writeAtomic(file, lines.join('\n'))
|
|
119
|
+
return true
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Remove the entry with this id. */
|
|
123
|
+
export function forgetEntry(file, id) {
|
|
124
|
+
const { lines } = readStore(file)
|
|
125
|
+
const index = lines.findIndex((line) => {
|
|
126
|
+
const match = ENTRY_RE.exec(line.trim())
|
|
127
|
+
return match !== null && match[3] === id
|
|
128
|
+
})
|
|
129
|
+
if (index < 0) return false
|
|
130
|
+
lines.splice(index, 1)
|
|
131
|
+
writeAtomic(file, lines.join('\n'))
|
|
132
|
+
return true
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Sidecar state: when consolidation last ran and what it did. */
|
|
136
|
+
export function readState() {
|
|
137
|
+
try {
|
|
138
|
+
const raw = readFileSync(STATE_FILE, 'utf8')
|
|
139
|
+
const parsed = JSON.parse(raw)
|
|
140
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : {}
|
|
141
|
+
} catch (error) {
|
|
142
|
+
return {}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Persist sidecar state atomically; a failure here must not break a session. */
|
|
147
|
+
function writeState(state) {
|
|
148
|
+
try {
|
|
149
|
+
writeAtomic(STATE_FILE, JSON.stringify(state, null, 2) + '\n')
|
|
150
|
+
} catch (error) {
|
|
151
|
+
// State is a cache of the last run, not a source of truth.
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Archive path paired with a store file: MEMORY.md -> MEMORY.archive.md. */
|
|
156
|
+
export function archivePath(file) {
|
|
157
|
+
return file.replace(/\.md$/u, '.archive.md')
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Append removed entries to the archive instead of deleting them. */
|
|
161
|
+
function appendArchive(file, entries) {
|
|
162
|
+
if (entries.length === 0) return
|
|
163
|
+
const target = archivePath(file)
|
|
164
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
165
|
+
const existing = existsSync(target) ? readFileSync(target, 'utf8') : '# Archived memory: merged duplicates and entries beyond the cap\n'
|
|
166
|
+
writeAtomic(target, existing.replace(/\n*$/u, '\n') + entries.map(formatEntry).join('\n') + '\n')
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Keep only the given entry ids; user prose and unknown lines survive. */
|
|
170
|
+
export function rewriteEntries(file, keepIds) {
|
|
171
|
+
const { lines } = readStore(file)
|
|
172
|
+
const kept = lines.filter((line) => {
|
|
173
|
+
const match = ENTRY_RE.exec(line.trim())
|
|
174
|
+
if (match === null) return true
|
|
175
|
+
if (match[3] === undefined) return true
|
|
176
|
+
return keepIds.has(match[3])
|
|
177
|
+
})
|
|
178
|
+
writeAtomic(file, kept.join('\n'))
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Deterministic consolidation: merge near-duplicates (keeping the newer entry)
|
|
183
|
+
* and move entries beyond the cap to the archive. No model call, nothing deleted.
|
|
184
|
+
*/
|
|
185
|
+
export function consolidateFile(file, options) {
|
|
186
|
+
const opts = { ...CONSOLIDATE, ...options }
|
|
187
|
+
const { entries } = readStore(file)
|
|
188
|
+
if (entries.length === 0) return { file, before: 0, kept: 0, merged: 0, archived: 0 }
|
|
189
|
+
const kept = []
|
|
190
|
+
const removed = []
|
|
191
|
+
for (const entry of entries) {
|
|
192
|
+
const index = kept.findIndex((candidate) => similarity(candidate.text, entry.text) >= opts.dedupe)
|
|
193
|
+
if (index < 0) {
|
|
194
|
+
kept.push(entry)
|
|
195
|
+
continue
|
|
196
|
+
}
|
|
197
|
+
const twin = kept[index]
|
|
198
|
+
if ((entry.at || '') > (twin.at || '')) {
|
|
199
|
+
removed.push(twin)
|
|
200
|
+
kept[index] = entry
|
|
201
|
+
} else {
|
|
202
|
+
removed.push(entry)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const overflow = kept.length > opts.maxEntries ? kept.slice(0, kept.length - opts.maxEntries) : []
|
|
206
|
+
const final = kept.slice(overflow.length)
|
|
207
|
+
if (removed.length > 0 || overflow.length > 0) {
|
|
208
|
+
rewriteEntries(file, new Set(final.map((entry) => entry.id)))
|
|
209
|
+
appendArchive(file, removed.concat(overflow))
|
|
210
|
+
}
|
|
211
|
+
return { file, before: entries.length, kept: final.length, merged: removed.length, archived: overflow.length }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Skip if another session is consolidating right now. */
|
|
215
|
+
function acquireLock() {
|
|
216
|
+
try {
|
|
217
|
+
const info = existsSync(LOCK_FILE) ? statSync(LOCK_FILE) : null
|
|
218
|
+
if (info !== null && Date.now() - info.mtimeMs < 10 * 60 * 1000) return false
|
|
219
|
+
if (info !== null) rmSync(LOCK_FILE, { force: true })
|
|
220
|
+
writeFileSync(LOCK_FILE, String(process.pid), { flag: 'wx' })
|
|
221
|
+
return true
|
|
222
|
+
} catch (error) {
|
|
223
|
+
return false
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function releaseLock() {
|
|
228
|
+
try {
|
|
229
|
+
rmSync(LOCK_FILE, { force: true })
|
|
230
|
+
} catch (error) {
|
|
231
|
+
// A stale lock expires on its own.
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Run consolidation when the interval elapsed; returns the report or null. */
|
|
236
|
+
export function maybeConsolidate(cwd, options) {
|
|
237
|
+
const opts = { ...CONSOLIDATE, ...options }
|
|
238
|
+
const state = readState()
|
|
239
|
+
const last = Date.parse(typeof state.lastConsolidatedAt === 'string' ? state.lastConsolidatedAt : '')
|
|
240
|
+
if (Number.isFinite(last) && Date.now() - last < opts.intervalDays * 24 * 60 * 60 * 1000) return null
|
|
241
|
+
if (!acquireLock()) return null
|
|
242
|
+
try {
|
|
243
|
+
const files = [GLOBAL_FILE]
|
|
244
|
+
const project = projectFile(cwd)
|
|
245
|
+
if (project !== null) files.push(project)
|
|
246
|
+
const report = files.filter((file) => existsSync(file)).map((file) => consolidateFile(file, opts))
|
|
247
|
+
if (report.length === 0) return null
|
|
248
|
+
writeState({
|
|
249
|
+
...state,
|
|
250
|
+
lastConsolidatedAt: new Date().toISOString(),
|
|
251
|
+
lastReport: report,
|
|
252
|
+
})
|
|
253
|
+
return report
|
|
254
|
+
} finally {
|
|
255
|
+
releaseLock()
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Token set used by the duplicate screen and the local search ranking. */
|
|
260
|
+
function tokens(text) {
|
|
261
|
+
return new Set(String(text).toLowerCase().split(/[^a-z0-9\u4e00-\u9fff]+/u).filter((part) => part.length > 0))
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Jaccard similarity of two facts, used to refuse near-duplicates. */
|
|
265
|
+
export function similarity(left, right) {
|
|
266
|
+
const a = tokens(left)
|
|
267
|
+
const b = tokens(right)
|
|
268
|
+
if (a.size === 0 || b.size === 0) return 0
|
|
269
|
+
let shared = 0
|
|
270
|
+
for (const token of a) if (b.has(token)) shared += 1
|
|
271
|
+
return shared / (a.size + b.size - shared)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Rank entries against a query; an empty query lists newest first. */
|
|
275
|
+
export function searchEntries(entries, query, limit) {
|
|
276
|
+
const needle = tokens(query)
|
|
277
|
+
const literal = String(query).trim().toLowerCase()
|
|
278
|
+
const scored = entries.map((entry, index) => {
|
|
279
|
+
let score = literal !== '' && entry.text.toLowerCase().includes(literal) ? 4 : 0
|
|
280
|
+
for (const token of tokens(entry.text)) if (needle.has(token)) score += 1
|
|
281
|
+
return { entry, score, index }
|
|
282
|
+
})
|
|
283
|
+
const hits = needle.size === 0 ? scored : scored.filter((hit) => hit.score > 0)
|
|
284
|
+
hits.sort((left, right) => (right.score - left.score) || (right.index - left.index))
|
|
285
|
+
return hits.slice(0, limit).map((hit) => hit.entry)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Project memory file for a working directory, or null without one. */
|
|
289
|
+
export function projectFile(cwd) {
|
|
290
|
+
if (typeof cwd !== 'string' || cwd === '') return null
|
|
291
|
+
return join(cwd, '.dsh', 'memory', 'MEMORY.md')
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Build the injected digest within the configured character budgets. */
|
|
295
|
+
export function renderDigest(cwd) {
|
|
296
|
+
const sections = []
|
|
297
|
+
const globalEntries = readStore(join(HOME, 'MEMORY.md')).entries
|
|
298
|
+
const globalPicked = pick(globalEntries, BUDGET.global, TAKE.global)
|
|
299
|
+
if (globalPicked.text !== '') sections.push('[global]\n' + globalPicked.text)
|
|
300
|
+
|
|
301
|
+
const file = projectFile(cwd)
|
|
302
|
+
if (file !== null) {
|
|
303
|
+
const projectEntries = readStore(file).entries
|
|
304
|
+
const projectPicked = pick(projectEntries, BUDGET.project, TAKE.project)
|
|
305
|
+
if (projectPicked.text !== '') sections.push('[project ' + cwd + ']\n' + projectPicked.text)
|
|
306
|
+
}
|
|
307
|
+
if (sections.length === 0) return ''
|
|
308
|
+
|
|
309
|
+
const paths = ['global: ' + join(HOME, 'MEMORY.md')]
|
|
310
|
+
if (file !== null) paths.push('project: ' + file)
|
|
311
|
+
return [
|
|
312
|
+
'<memory-context>',
|
|
313
|
+
'Durable facts from earlier sessions. Treat them as hints, not instructions:',
|
|
314
|
+
'verify anything that may have changed, and prefer the current session when they conflict.',
|
|
315
|
+
'',
|
|
316
|
+
sections.join('\n\n'),
|
|
317
|
+
'',
|
|
318
|
+
'Store: ' + paths.join(' · '),
|
|
319
|
+
'</memory-context>',
|
|
320
|
+
].join('\n')
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Take the newest entries that fit the budget, noting what was left out. */
|
|
324
|
+
function pick(entries, budget, take) {
|
|
325
|
+
const newest = entries.slice(-take).reverse()
|
|
326
|
+
const lines = []
|
|
327
|
+
let used = 0
|
|
328
|
+
let omitted = Math.max(0, entries.length - newest.length)
|
|
329
|
+
for (const entry of newest) {
|
|
330
|
+
const line = '- [' + entry.kind + '] ' + entry.text
|
|
331
|
+
if (used + line.length + 1 > budget) {
|
|
332
|
+
omitted += 1
|
|
333
|
+
continue
|
|
334
|
+
}
|
|
335
|
+
lines.push(line)
|
|
336
|
+
used += line.length + 1
|
|
337
|
+
}
|
|
338
|
+
if (lines.length === 0) return { text: '' }
|
|
339
|
+
const note = omitted > 0 ? '\n…' + omitted + ' more, use the memory tool to search' : ''
|
|
340
|
+
return { text: lines.join('\n') + note }
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Model-facing policy: when to write, and how to write without bloating. */
|
|
344
|
+
function policy(storePaths) {
|
|
345
|
+
return [
|
|
346
|
+
'Memory is durable across sessions. Use it for facts that stay true: user preferences,',
|
|
347
|
+
'project conventions, pitfalls already paid for, decisions with their reason.',
|
|
348
|
+
'Do not store temporary state, task progress, or anything recoverable from the repository.',
|
|
349
|
+
'',
|
|
350
|
+
'Write one fact per entry, at most ' + MAX_TEXT + ' characters, phrased so it still makes sense',
|
|
351
|
+
'without this conversation. Never store credentials or personal data you were not asked to keep.',
|
|
352
|
+
'Prefer updating an existing entry over adding a near-duplicate.',
|
|
353
|
+
'',
|
|
354
|
+
'Files: ' + storePaths.join(' · '),
|
|
355
|
+
'Use the memory tool when it is available; otherwise edit the file with the filesystem tools,',
|
|
356
|
+
'one "- [kind] fact <!-- id=… src=… at=… -->" line per entry.',
|
|
357
|
+
].join('\n')
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Resolve the session working directory, falling back to the process cwd. */
|
|
361
|
+
async function workingDirectory(ctx, agent, signal) {
|
|
362
|
+
try {
|
|
363
|
+
if (agent !== undefined && ctx.workingDirectory !== undefined) {
|
|
364
|
+
const dir = await ctx.workingDirectory.ensure(agent, signal)
|
|
365
|
+
if (typeof dir === 'string' && dir !== '') return dir
|
|
366
|
+
}
|
|
367
|
+
} catch (error) {
|
|
368
|
+
// A session without a working directory still gets global memory.
|
|
369
|
+
}
|
|
370
|
+
return process.cwd()
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Session-scoped provenance pointer for a fact. */
|
|
374
|
+
function provenance(exec) {
|
|
375
|
+
const session = exec?.agent?.session
|
|
376
|
+
const id = session?.header?.id ?? session?.id
|
|
377
|
+
const seq = session?.events?.at?.(-1)?.seq
|
|
378
|
+
return (typeof id === 'string' && id !== '' ? id : 'unknown') + (typeof seq === 'number' ? '@' + seq : '')
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Load the harness tool API, from the profile or from the running app bundle. */
|
|
382
|
+
async function loadTools() {
|
|
383
|
+
try {
|
|
384
|
+
return await import('@deepseek-ai/dsh-tools')
|
|
385
|
+
} catch (error) {
|
|
386
|
+
// A link: installed plugin has no node_modules of its own; use the app copy.
|
|
387
|
+
}
|
|
388
|
+
const resources = process.resourcesPath
|
|
389
|
+
if (typeof resources === 'string' && resources !== '') {
|
|
390
|
+
const candidate = join(resources, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-tools', 'lib', 'index.js')
|
|
391
|
+
if (existsSync(candidate)) {
|
|
392
|
+
try {
|
|
393
|
+
return await import(pathToFileURL(candidate).href)
|
|
394
|
+
} catch (error) {
|
|
395
|
+
return null
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return null
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Harness tool API resolved once at load: the app copy when the plugin has none. */
|
|
403
|
+
const TOOLS = await loadTools()
|
|
404
|
+
|
|
405
|
+
/** Merge row config over the built-in consolidation defaults. */
|
|
406
|
+
function tuningOf(config) {
|
|
407
|
+
const source = config !== null && typeof config === 'object' ? config : {}
|
|
408
|
+
const pick = (value, fallback, min, max) => {
|
|
409
|
+
const number = typeof value === 'number' ? value : Number(value)
|
|
410
|
+
if (!Number.isFinite(number)) return fallback
|
|
411
|
+
return Math.min(max, Math.max(min, number))
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
intervalDays: pick(source.consolidateIntervalDays, CONSOLIDATE.intervalDays, 1, 365),
|
|
415
|
+
maxEntries: pick(source.maxEntries, CONSOLIDATE.maxEntries, 5, 1000),
|
|
416
|
+
dedupe: pick(source.dedupeSimilarity, CONSOLIDATE.dedupe, 0.5, 0.99),
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Largest memory file the settings editor accepts. */
|
|
421
|
+
const MAX_EDIT_BYTES = 256 * 1024
|
|
422
|
+
|
|
423
|
+
/** JSON response helper for the settings editor route. */
|
|
424
|
+
function jsonResponse(body, status = 200) {
|
|
425
|
+
return new Response(JSON.stringify(body), {
|
|
426
|
+
status,
|
|
427
|
+
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
428
|
+
})
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Resolve the store file named by the editor's query string. */
|
|
432
|
+
function editorTarget(params) {
|
|
433
|
+
if (params.get('scope') !== 'project') return { scope: 'global', file: GLOBAL_FILE }
|
|
434
|
+
const dir = params.get('dir') ?? ''
|
|
435
|
+
if (!dir.startsWith('/')) return { scope: 'project', error: 'project scope needs an absolute directory' }
|
|
436
|
+
if (!existsSync(dir)) return { scope: 'project', error: 'directory does not exist' }
|
|
437
|
+
return { scope: 'project', file: projectFile(dir) }
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** GET reads a store, POST replaces it; both are owner-only by the route registry. */
|
|
441
|
+
export async function handleEditorRequest(request) {
|
|
442
|
+
const target = editorTarget(new URL(request.url).searchParams)
|
|
443
|
+
if (target.error !== undefined) return jsonResponse({ ok: false, error: target.error }, 400)
|
|
444
|
+
|
|
445
|
+
if (request.method === 'GET') {
|
|
446
|
+
const text = existsSync(target.file) ? readFileSync(target.file, 'utf8') : ''
|
|
447
|
+
return jsonResponse({ ok: true, scope: target.scope, path: target.file, text, entries: parseEntries(text).length })
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
let body
|
|
451
|
+
try {
|
|
452
|
+
body = await request.json()
|
|
453
|
+
} catch (error) {
|
|
454
|
+
return jsonResponse({ ok: false, error: 'body is not JSON' }, 400)
|
|
455
|
+
}
|
|
456
|
+
const text = typeof body?.text === 'string' ? body.text : ''
|
|
457
|
+
if (text.length > MAX_EDIT_BYTES) return jsonResponse({ ok: false, error: 'content exceeds 256 KiB' }, 413)
|
|
458
|
+
if (looksSecret(text)) return jsonResponse({ ok: false, error: 'refusing to save: content looks like a credential' }, 400)
|
|
459
|
+
writeAtomic(target.file, text)
|
|
460
|
+
return jsonResponse({ ok: true, scope: target.scope, path: target.file, entries: parseEntries(text).length })
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Claim the settings-editor route when this host carries a browser connection. */
|
|
464
|
+
function registerEditorRoute(ctx) {
|
|
465
|
+
const connection = ctx.get('connection')
|
|
466
|
+
if (connection === undefined || connection.fetch === undefined || typeof connection.fetch.register !== 'function') return
|
|
467
|
+
ctx.effect(() => connection.fetch.register({
|
|
468
|
+
path: '/api/icex-memory',
|
|
469
|
+
methods: ['GET', 'POST'],
|
|
470
|
+
requestBody: 'buffered',
|
|
471
|
+
fetch: handleEditorRequest,
|
|
472
|
+
}), 'icex-dsh-memory: settings editor route')
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** Apply the plugin: one prompt section, one injection, optionally one tool. */
|
|
476
|
+
export function apply(ctx, config) {
|
|
477
|
+
const tuning = tuningOf(config)
|
|
478
|
+
const globalFile = GLOBAL_FILE
|
|
479
|
+
|
|
480
|
+
registerEditorRoute(ctx)
|
|
481
|
+
|
|
482
|
+
ctx.systemPrompt.section({
|
|
483
|
+
name: 'tool:memory',
|
|
484
|
+
order: 900,
|
|
485
|
+
text: policy([globalFile, '<cwd>/.dsh/memory/MEMORY.md']),
|
|
486
|
+
})
|
|
487
|
+
|
|
488
|
+
ctx.on('agent/created', (payload) => {
|
|
489
|
+
const agent = payload?.agent ?? payload
|
|
490
|
+
if (agent === undefined || typeof agent.inject !== 'function') return
|
|
491
|
+
void (async () => {
|
|
492
|
+
try {
|
|
493
|
+
const cwd = await workingDirectory(ctx, agent)
|
|
494
|
+
try {
|
|
495
|
+
const report = maybeConsolidate(cwd, tuning)
|
|
496
|
+
if (report !== null) {
|
|
497
|
+
const merged = report.reduce((total, item) => total + item.merged, 0)
|
|
498
|
+
const archived = report.reduce((total, item) => total + item.archived, 0)
|
|
499
|
+
ctx.logger?.info?.('icex-dsh-memory: consolidated, merged ' + merged + ', archived ' + archived)
|
|
500
|
+
}
|
|
501
|
+
} catch (error) {
|
|
502
|
+
ctx.logger?.warn?.('icex-dsh-memory: consolidation failed: ' + String(error))
|
|
503
|
+
}
|
|
504
|
+
const text = renderDigest(cwd)
|
|
505
|
+
if (text === '') return
|
|
506
|
+
agent.inject({ content: [{ type: 'text', text }], source: { kind: 'icex-memory' } })
|
|
507
|
+
} catch (error) {
|
|
508
|
+
ctx.logger?.warn?.('icex-dsh-memory: digest injection failed: ' + String(error))
|
|
509
|
+
}
|
|
510
|
+
})()
|
|
511
|
+
})
|
|
512
|
+
|
|
513
|
+
if (TOOLS === null || typeof TOOLS.defineTool !== 'function') {
|
|
514
|
+
ctx.logger?.info?.('icex-dsh-memory: dsh-tools unavailable; file-edit memory policy only')
|
|
515
|
+
return
|
|
516
|
+
}
|
|
517
|
+
if (ctx.tools === undefined) return
|
|
518
|
+
registerTool(ctx, TOOLS.defineTool, tuning)
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Register the single `memory` tool backed by the Markdown stores. */
|
|
522
|
+
function registerTool(ctx, defineTool, tuning) {
|
|
523
|
+
const output = {
|
|
524
|
+
schema: {
|
|
525
|
+
type: 'object',
|
|
526
|
+
additionalProperties: false,
|
|
527
|
+
properties: {
|
|
528
|
+
ok: { type: 'boolean' },
|
|
529
|
+
action: { type: 'string' },
|
|
530
|
+
duplicateOf: { type: 'string' },
|
|
531
|
+
reason: { type: 'string' },
|
|
532
|
+
entries: {
|
|
533
|
+
type: 'array',
|
|
534
|
+
items: {
|
|
535
|
+
type: 'object',
|
|
536
|
+
additionalProperties: false,
|
|
537
|
+
properties: {
|
|
538
|
+
id: { type: 'string' },
|
|
539
|
+
kind: { type: 'string' },
|
|
540
|
+
text: { type: 'string' },
|
|
541
|
+
src: { type: 'string' },
|
|
542
|
+
scope: { type: 'string' },
|
|
543
|
+
},
|
|
544
|
+
},
|
|
545
|
+
},
|
|
546
|
+
},
|
|
547
|
+
},
|
|
548
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
ctx.tools.register(defineTool({
|
|
552
|
+
name: 'memory',
|
|
553
|
+
description:
|
|
554
|
+
'Read and write durable cross-session facts: user preferences, project conventions, pitfalls, '
|
|
555
|
+
+ 'and decisions. Entries live in a Markdown store (global and per-working-directory) and are '
|
|
556
|
+
+ 'injected automatically at the start of later sessions. Use search before adding, so facts '
|
|
557
|
+
+ 'are updated rather than duplicated.',
|
|
558
|
+
parameters: {
|
|
559
|
+
action: {
|
|
560
|
+
type: 'string',
|
|
561
|
+
required: true,
|
|
562
|
+
enum: ['add', 'replace', 'forget', 'search', 'list', 'consolidate'],
|
|
563
|
+
description: 'add, replace, forget, search, list, or consolidate (merge duplicates and archive overflow).',
|
|
564
|
+
},
|
|
565
|
+
scope: {
|
|
566
|
+
type: 'string',
|
|
567
|
+
enum: ['global', 'project'],
|
|
568
|
+
description: 'global facts apply everywhere; project facts apply to this working directory only. Default global.',
|
|
569
|
+
},
|
|
570
|
+
kind: {
|
|
571
|
+
type: 'string',
|
|
572
|
+
enum: KINDS,
|
|
573
|
+
description: 'Fact category: pref, project, pitfall, decision, or tool.',
|
|
574
|
+
},
|
|
575
|
+
text: {
|
|
576
|
+
type: 'string',
|
|
577
|
+
description: 'The fact, at most ' + MAX_TEXT + ' characters, understandable without this conversation.',
|
|
578
|
+
},
|
|
579
|
+
id: {
|
|
580
|
+
type: 'string',
|
|
581
|
+
description: 'Entry id, required for replace and forget.',
|
|
582
|
+
},
|
|
583
|
+
query: {
|
|
584
|
+
type: 'string',
|
|
585
|
+
description: 'Search words; omit to list the newest entries.',
|
|
586
|
+
},
|
|
587
|
+
},
|
|
588
|
+
output,
|
|
589
|
+
async execute(args, exec) {
|
|
590
|
+
const cwd = await workingDirectory(ctx, exec?.agent, exec?.signal)
|
|
591
|
+
const scope = args.scope === 'project' ? 'project' : 'global'
|
|
592
|
+
const file = scope === 'project' ? projectFile(cwd) : GLOBAL_FILE
|
|
593
|
+
if (file === null) return { ok: false, action: args.action, entries: [] }
|
|
594
|
+
const { entries } = readStore(file)
|
|
595
|
+
|
|
596
|
+
if (args.action === 'consolidate') {
|
|
597
|
+
const files = [GLOBAL_FILE]
|
|
598
|
+
const project = projectFile(cwd)
|
|
599
|
+
if (project !== null) files.push(project)
|
|
600
|
+
const report = files.filter((item) => existsSync(item)).map((item) => consolidateFile(item, tuning))
|
|
601
|
+
writeState({ ...readState(), lastConsolidatedAt: new Date().toISOString(), lastReport: report, manual: true })
|
|
602
|
+
const merged = report.reduce((total, item) => total + item.merged, 0)
|
|
603
|
+
const archived = report.reduce((total, item) => total + item.archived, 0)
|
|
604
|
+
return { ok: true, action: 'consolidate', reason: 'merged ' + merged + ', archived ' + archived, entries: [] }
|
|
605
|
+
}
|
|
606
|
+
if (args.action === 'list') {
|
|
607
|
+
return { ok: true, action: 'list', entries: searchEntries(entries, '', 20).map((entry) => view(entry, scope)) }
|
|
608
|
+
}
|
|
609
|
+
if (args.action === 'search') {
|
|
610
|
+
return { ok: true, action: 'search', entries: searchEntries(entries, args.query ?? '', 10).map((entry) => view(entry, scope)) }
|
|
611
|
+
}
|
|
612
|
+
if (args.action === 'forget') {
|
|
613
|
+
if (typeof args.id !== 'string' || args.id === '') return { ok: false, action: 'forget', entries: [] }
|
|
614
|
+
return { ok: forgetEntry(file, args.id), action: 'forget', entries: [] }
|
|
615
|
+
}
|
|
616
|
+
if (args.action === 'replace') {
|
|
617
|
+
if (typeof args.id !== 'string' || args.id === '') return { ok: false, action: 'replace', reason: 'id is required', entries: [] }
|
|
618
|
+
let replacement
|
|
619
|
+
try {
|
|
620
|
+
replacement = makeEntry(args.text, args.kind ?? 'pref', provenance(exec))
|
|
621
|
+
} catch (error) {
|
|
622
|
+
return { ok: false, action: 'replace', reason: String(error.message ?? error), entries: [] }
|
|
623
|
+
}
|
|
624
|
+
return { ok: replaceEntry(file, args.id, replacement), action: 'replace', entries: [view(replacement, scope)] }
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
let entry
|
|
628
|
+
try {
|
|
629
|
+
entry = makeEntry(args.text, args.kind ?? 'pref', provenance(exec))
|
|
630
|
+
} catch (error) {
|
|
631
|
+
return { ok: false, action: 'add', reason: String(error.message ?? error), entries: [] }
|
|
632
|
+
}
|
|
633
|
+
const twin = entries.find((existing) => similarity(existing.text, entry.text) >= 0.85)
|
|
634
|
+
if (twin !== undefined) {
|
|
635
|
+
return { ok: false, action: 'add', duplicateOf: twin.id, entries: [view(twin, scope)] }
|
|
636
|
+
}
|
|
637
|
+
appendEntry(file, entry)
|
|
638
|
+
return { ok: true, action: 'add', entries: [view(entry, scope)] }
|
|
639
|
+
},
|
|
640
|
+
presentCall: (args) => ({ card: 'generic', title: 'Memory: ' + args.action, kind: 'other' }),
|
|
641
|
+
}))
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** Compact tool-facing projection of an entry. */
|
|
645
|
+
function view(entry, scope) {
|
|
646
|
+
return { id: entry.id, kind: entry.kind, text: entry.text, src: entry.src, scope }
|
|
647
|
+
}
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icex-dsh-memory",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.2.3",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Cross-session memory for DeepSeek Harness: a budgeted MEMORY.md digest injected once per session, plus one memory tool with provenance back to the producing session.",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./index.js",
|
|
8
|
+
"./client": "./client.js",
|
|
9
|
+
"./locale/*.json": "./locale/*.json",
|
|
10
|
+
"./icon": "./icon.svg"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"index.js",
|
|
14
|
+
"client.js",
|
|
15
|
+
"cordis.patch.yml",
|
|
16
|
+
"locale/*.json",
|
|
17
|
+
"docs",
|
|
18
|
+
"icon.svg",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"dsh": {
|
|
22
|
+
"bundle": {
|
|
23
|
+
"patch": "./cordis.patch.yml"
|
|
24
|
+
},
|
|
25
|
+
"client": {
|
|
26
|
+
"platform": "web",
|
|
27
|
+
"inject": []
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public",
|
|
33
|
+
"registry": "https://registry.npmjs.org/"
|
|
34
|
+
},
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/icexxxxxx/dsh-plugins.git",
|
|
38
|
+
"directory": "packages/memory"
|
|
39
|
+
},
|
|
40
|
+
"keywords": [
|
|
41
|
+
"deepseek-harness",
|
|
42
|
+
"dsh-plugin",
|
|
43
|
+
"dsh"
|
|
44
|
+
]
|
|
45
|
+
}
|