dsh-plugin-memory 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,7 @@
18
18
  - **复利记忆**:遵循 Karpathy 的 *LLM Wiki* 约定——记忆是"一次编译、持续保鲜"的持久产物,不是每次查询重新 RAG。remember / recall / consolidate / forget 四操作 + salience 三级衰减。
19
19
  - **可迁移**:记忆本体是纯 markdown + git + 自描述 schema,任何能读 markdown 的 agent 都能接手。`dsh-memory pack/unpack` 打包迁移。
20
20
  - **内嵌技能**:通过 `ctx.skills.register()` 注册 `memory` 技能(操作协议随插件分发);项目级 `.dsh/skills/memory` 文件技能仍可覆盖它。
21
+ - **设置面板**:在 DSH 设置页提供「记忆 Memory」区块——总开关、记忆目录、开机注入、技能注册四项均可热改,立即生效,无需重启。
21
22
  - **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
22
23
 
23
24
  ## 架构
@@ -26,9 +27,10 @@
26
27
 
27
28
  ```
28
29
  dsh-plugin-memory(本插件)
29
- ├── lib/index.js # Cordis 入口:boot 注入 + 运行时技能注册
30
+ ├── lib/index.js # Cordis 入口:boot 注入 + 运行时技能注册 + settings 热改
30
31
  ├── lib/boot.js # boot 块渲染(SOUL/MEMORY/index + 最近 log,限额截断)
31
32
  ├── lib/scaffold.js # 记忆库脚手架(模板只建不覆盖)
33
+ ├── lib/client.js # 客户端半:设置面板「记忆 Memory」区块
32
34
  ├── skills/memory.md # 内嵌技能的操作协议正文
33
35
  └── scripts/memory.mjs # CLI:init/search/lint/status/pack/unpack
34
36
 
@@ -44,35 +46,46 @@ dsh-plugin-memory(本插件)
44
46
  ## 安装
45
47
 
46
48
  ```sh
47
- # npm
48
- npm install dsh-plugin-memory
49
-
50
- # 或 pnpm(推荐,DSH 生态默认包管理器)
51
- pnpm add dsh-plugin-memory
49
+ dsh plugin --profile <profile> add dsh-plugin-memory
52
50
  ```
53
51
 
54
- 在你的 profile 的 `cordis.patch.yml` 中加入:
55
-
56
- ```yaml
57
- - insert:
58
- - id: dsh-memory
59
- name: dsh-plugin-memory
60
- config:
61
- memoryDir: '~/.memory'
62
- ```
52
+ (包内置 `dsh.bundle` manifest,`dsh plugin add` 会把它自动挂进 profile 的 bundles 层;dsh-market 里的一键安装同此通道。)
63
53
 
64
54
  重启 profile(DSH Desktop 重启应用)后生效。
65
55
 
56
+ > ⚠️ **不要**再往 profile 的 `cordis.patch.yml` 里手写 `- insert: {id: dsh-memory, ...}`:
57
+ > 那会与 bundle manifest 的自动挂载产生两条同名 entry,整个 profile 会以
58
+ > `duplicate loader entry id "dsh-memory"` 启动失败(2026-08-18 实机事故)。
59
+ > 运行期配置(enabled / memoryDir / autoInject / registerSkill)改走
60
+ > `<dshHome>/memory.json`(设置面板热改);composition 配置见下表。
61
+ > 如需覆盖某个 composition 键,用**不带 insert 的 id 覆盖条目**(见配置一节)。
62
+
66
63
  ## 配置
67
64
 
68
65
  | 键 | 默认值 | 含义 |
69
66
  |---|---|---|
67
+ | `enabled` | `true` | 总开关:关闭后不注入 boot 块、不注册 `memory` 技能 |
70
68
  | `memoryDir` | `~/.memory` | 记忆库绝对路径(`~` 自动展开) |
71
69
  | `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | 开机注入的文件 |
72
70
  | `bootMaxChars` | `6000` | boot 块总字符预算(防止占用过多上下文) |
73
71
  | `autoInject` | `true` | 会话开始时注入 boot 块 |
74
72
  | `registerSkill` | `true` | 注册内嵌 `memory` 技能 |
75
73
  | `scaffold` | `true` | 记忆库缺失时自动创建模板(只建不覆盖) |
74
+ | `configFile` | `<dshHome>/memory.json` | 用户可改配置的 JSON 文件路径(设置面板读写它) |
75
+
76
+ ### 设置面板(热改)
77
+
78
+ `enabled` / `memoryDir` / `autoInject` / `registerSkill` 四项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、技能注册随修改立即重建;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile`)只在 composition 配置层生效,改完需重启。
79
+
80
+ 覆盖 composition 键(例如把 boot 块预算调大),在 profile 的 `cordis.patch.yml` 里写**不带 `insert` 的 id 覆盖条目**:
81
+
82
+ ```yaml
83
+ - id: dsh-memory
84
+ config:
85
+ bootMaxChars: 12000
86
+ ```
87
+
88
+ > 实现说明:DSH 的 settings wire 只服务硬编码的命名空间白名单,插件命名空间写不进去,因此本插件走自建通道——配置存 `<dshHome>/memory.json`(schema 校验 + 原子落盘),由插件自注册的 `GET/POST /api/memory/config` 路由服务,客户端区块 fetch 直连。
76
89
 
77
90
  ## 首次使用:铸魂
78
91
 
@@ -0,0 +1,10 @@
1
+ # dsh-plugin-memory bundle layer.
2
+ #
3
+ # Declared via the `dsh.bundle.patch` manifest in package.json, so
4
+ # `dsh plugin add dsh-plugin-memory` (and the dsh-market install flow)
5
+ # mounts this insert automatically. User-level overrides — including the
6
+ # hot-editable `enabled` / `memoryDir` / `autoInject` / `registerSkill` —
7
+ # live in <dshHome>/memory.json, managed by the settings panel.
8
+ - insert:
9
+ - id: dsh-memory
10
+ name: dsh-plugin-memory
package/lib/client.js ADDED
@@ -0,0 +1,242 @@
1
+ /**
2
+ * dsh-plugin-memory 客户端半(零构建):
3
+ * 在设置面板注册「记忆 Memory」区块 —— 总开关 + 记忆目录 + 两个子开关。
4
+ *
5
+ * 数据通道:settings wire 只服务硬编码白名单(memory 不在其中),
6
+ * 因此本区块直连插件自建的 HTTP 路由(/api/memory/config):
7
+ * GET 读配置、POST 部分更新,Host 校验并立即热应用。
8
+ */
9
+ window.__ModuleLoader__.load({
10
+ id: 'dsh-plugin-memory',
11
+ factory: (require) => {
12
+ var module = { exports: {} }
13
+ var exports = module.exports
14
+ let react = require('react')
15
+
16
+ const React = react
17
+ const CONFIG_URL = '/api/memory/config'
18
+
19
+ const rowStyle = {
20
+ display: 'flex',
21
+ alignItems: 'center',
22
+ justifyContent: 'space-between',
23
+ gap: '12px',
24
+ padding: '14px 16px',
25
+ borderBottom: '1px solid var(--dsw-alias-border-l1, rgba(128,128,128,0.2))',
26
+ }
27
+ const labelStyle = { fontSize: '14px', lineHeight: '22px' }
28
+ const subStyle = { fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #999)' }
29
+ const errorStyle = { padding: '0 16px 8px', fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' }
30
+ const inputStyle = {
31
+ width: '240px',
32
+ padding: '6px 8px',
33
+ fontSize: '14px',
34
+ borderRadius: '6px',
35
+ border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))',
36
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
37
+ color: 'var(--dsw-alias-label-primary, inherit)',
38
+ }
39
+
40
+ function Toggle({ checked, disabled, onChange }) {
41
+ return React.createElement('button', {
42
+ type: 'button',
43
+ role: 'switch',
44
+ 'aria-checked': checked,
45
+ disabled,
46
+ onClick: () => onChange(!checked),
47
+ style: {
48
+ position: 'relative',
49
+ width: '40px',
50
+ height: '22px',
51
+ borderRadius: '11px',
52
+ border: 'none',
53
+ cursor: disabled ? 'not-allowed' : 'pointer',
54
+ background: checked ? 'var(--dsw-alias-brand-primary, #4c8bf5)' : 'var(--dsw-alias-label-secondary, #666)',
55
+ opacity: disabled ? 0.5 : 1,
56
+ transition: 'background 0.15s',
57
+ flexShrink: 0,
58
+ },
59
+ }, React.createElement('span', {
60
+ style: {
61
+ position: 'absolute',
62
+ top: '2px',
63
+ left: checked ? '20px' : '2px',
64
+ width: '18px',
65
+ height: '18px',
66
+ borderRadius: '9px',
67
+ background: '#fff',
68
+ transition: 'left 0.15s',
69
+ },
70
+ }))
71
+ }
72
+
73
+ function ErrorText({ message }) {
74
+ return React.createElement('div', { style: { padding: '14px 16px', fontSize: '13px', lineHeight: '20px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' } },
75
+ '记忆设置页加载失败:', message)
76
+ }
77
+
78
+ /** 渲染期兜底:任何异常都以文案形式显示,绝不空白。 */
79
+ class SectionBoundary extends React.Component {
80
+ constructor(props) {
81
+ super(props)
82
+ this.state = { error: undefined }
83
+ }
84
+ static getDerivedStateFromError(error) {
85
+ return { error: error instanceof Error ? error.message : String(error) }
86
+ }
87
+ render() {
88
+ if (this.state.error !== undefined) return React.createElement(ErrorText, { message: this.state.error })
89
+ return this.props.children
90
+ }
91
+ }
92
+
93
+ function MemorySection() {
94
+ return React.createElement(SectionBoundary, null, React.createElement(MemoryForm))
95
+ }
96
+
97
+ /** 目录输入:草稿态编辑,blur / Enter 才写回,避免每次按键触发 Host 重排。 */
98
+ function DirInput({ value, disabled, onCommit }) {
99
+ const [draft, setDraft] = React.useState(undefined)
100
+ const shown = draft !== undefined ? draft : (value ?? '')
101
+ const commit = () => {
102
+ if (draft === undefined) return
103
+ const trimmed = draft.trim()
104
+ if (trimmed.length > 0 && trimmed !== value) onCommit(trimmed)
105
+ setDraft(undefined)
106
+ }
107
+ return React.createElement('input', {
108
+ type: 'text',
109
+ placeholder: '~/.memory',
110
+ disabled,
111
+ value: shown,
112
+ onChange: (event) => setDraft(event.target.value),
113
+ onBlur: commit,
114
+ onKeyDown: (event) => {
115
+ if (event.key === 'Enter') commit()
116
+ if (event.key === 'Escape') setDraft(undefined)
117
+ },
118
+ style: inputStyle,
119
+ })
120
+ }
121
+
122
+ function MemoryForm() {
123
+ const [config, setConfig] = React.useState(undefined)
124
+ const [status, setStatus] = React.useState('loading')
125
+ const [error, setError] = React.useState(undefined)
126
+ const [saving, setSaving] = React.useState(false)
127
+
128
+ React.useEffect(() => {
129
+ let alive = true
130
+ fetch(CONFIG_URL)
131
+ .then(async (response) => {
132
+ if (!response.ok) throw new Error(`GET ${response.status}`)
133
+ return response.json()
134
+ })
135
+ .then((value) => {
136
+ if (!alive) return
137
+ setConfig(value)
138
+ setStatus('ready')
139
+ })
140
+ .catch((err) => {
141
+ if (!alive) return
142
+ setStatus('failed')
143
+ setError(err instanceof Error ? err.message : String(err))
144
+ })
145
+ return () => {
146
+ alive = false
147
+ }
148
+ }, [])
149
+
150
+ const apply = (patch) => {
151
+ setSaving(true)
152
+ setError(undefined)
153
+ fetch(CONFIG_URL, {
154
+ method: 'POST',
155
+ headers: { 'content-type': 'application/json' },
156
+ body: JSON.stringify(patch),
157
+ })
158
+ .then(async (response) => {
159
+ const body = await response.json().catch(() => ({}))
160
+ if (!response.ok) throw new Error(body.error ?? `POST ${response.status}`)
161
+ setConfig(body)
162
+ })
163
+ .catch((err) => {
164
+ setError(err instanceof Error ? err.message : String(err))
165
+ })
166
+ .finally(() => setSaving(false))
167
+ }
168
+
169
+ if (status === 'loading') {
170
+ return React.createElement('div', { style: { padding: '14px 16px', fontSize: '13px', color: 'var(--dsw-alias-label-secondary, #888)' } }, '读取配置中…')
171
+ }
172
+ if (status === 'failed') return React.createElement(ErrorText, { message: error ?? 'unknown' })
173
+
174
+ const value = config ?? {}
175
+ const disabled = saving
176
+
177
+ return React.createElement('div', { style: { padding: '8px 0' } },
178
+ React.createElement('div', { style: rowStyle },
179
+ React.createElement('div', null,
180
+ React.createElement('div', { style: labelStyle }, '启用记忆插件'),
181
+ React.createElement('div', { style: subStyle }, '总开关:关闭后不再注入记忆,也不注册 memory 技能'),
182
+ ),
183
+ React.createElement(Toggle, {
184
+ checked: value.enabled !== false,
185
+ disabled,
186
+ onChange: (next) => apply({ enabled: next }),
187
+ }),
188
+ ),
189
+ React.createElement('div', { style: rowStyle },
190
+ React.createElement('div', null,
191
+ React.createElement('div', { style: labelStyle }, '记忆目录'),
192
+ React.createElement('div', { style: subStyle }, '存放 SOUL/MEMORY/index/log 的路径,支持 ~ 开头;修改后立即切换,目录不存在时自动初始化'),
193
+ ),
194
+ React.createElement(DirInput, {
195
+ value: value.memoryDir,
196
+ disabled,
197
+ onCommit: (next) => apply({ memoryDir: next }),
198
+ }),
199
+ ),
200
+ React.createElement('div', { style: rowStyle },
201
+ React.createElement('div', null,
202
+ React.createElement('div', { style: labelStyle }, '开机注入记忆'),
203
+ React.createElement('div', { style: subStyle }, '每次会话开始把记忆快照注入上下文'),
204
+ ),
205
+ React.createElement(Toggle, {
206
+ checked: value.autoInject !== false,
207
+ disabled,
208
+ onChange: (next) => apply({ autoInject: next }),
209
+ }),
210
+ ),
211
+ React.createElement('div', { style: rowStyle },
212
+ React.createElement('div', null,
213
+ React.createElement('div', { style: labelStyle }, '注册 memory 技能'),
214
+ React.createElement('div', { style: subStyle }, '让 agent 获得 remember / recall / consolidate / forget 操作协议'),
215
+ ),
216
+ React.createElement(Toggle, {
217
+ checked: value.registerSkill !== false,
218
+ disabled,
219
+ onChange: (next) => apply({ registerSkill: next }),
220
+ }),
221
+ ),
222
+ error !== undefined ? React.createElement('div', { style: errorStyle }, '保存失败:', error) : null,
223
+ React.createElement('div', { style: { padding: '14px 16px', fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #888)' } },
224
+ `当前:${value.enabled === false ? '已停用' : `记忆库位于 ${value.memoryDir ?? '(未配置)'}`}。修改即时生效。`,
225
+ ),
226
+ )
227
+ }
228
+
229
+ function apply(ctx) {
230
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
231
+ name: 'settings.section',
232
+ id: 'memory',
233
+ order: 100,
234
+ label: () => '记忆 Memory',
235
+ }, MemorySection))
236
+ }
237
+
238
+ exports.apply = apply
239
+ exports.inject = ['slots']
240
+ return module.exports
241
+ },
242
+ })
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Memory configuration store: one JSON file as the single user-facing
3
+ * config source, layered over the composition defaults.
4
+ *
5
+ * Why not the `settings` service? The Web settings wire only serves a
6
+ * hard-coded allowlist (`WEB_SETTINGS_NAMESPACES` in dsh-host-apiproxy) and
7
+ * rejects every other namespace with `settings-not-exposed`; a plugin cannot
8
+ * add itself to that list yet. This store keeps the same "base + user layer"
9
+ * semantics with a private JSON file and an in-process watch, and the plugin
10
+ * serves it over its own HTTP route for the browser UI.
11
+ *
12
+ * @module dsh-plugin-memory/config-store
13
+ */
14
+
15
+ import { existsSync, readFileSync, renameSync, writeFileSync, mkdirSync } from 'node:fs'
16
+ import { dirname, join } from 'node:path'
17
+ import { homedir } from 'node:os'
18
+ import { SettingsSchema } from './schema.js'
19
+
20
+ export const MEMORY_CONFIG_FILENAME = 'memory.json'
21
+
22
+ export function defaultConfigPath() {
23
+ return join(process.env.DSH_HOME || join(homedir(), '.dsh'), MEMORY_CONFIG_FILENAME)
24
+ }
25
+
26
+ const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill']
27
+
28
+ function pickFields(input) {
29
+ const picked = {}
30
+ for (const key of FIELDS) {
31
+ if (input[key] !== undefined) picked[key] = input[key]
32
+ }
33
+ return picked
34
+ }
35
+
36
+ /**
37
+ * @typedef {object} MemorySettings
38
+ * @property {boolean} enabled
39
+ * @property {string} memoryDir
40
+ * @property {boolean} autoInject
41
+ * @property {boolean} registerSkill
42
+ */
43
+
44
+ /**
45
+ * @param {object} options
46
+ * @param {string} [options.path] absolute config-file path (defaults to `<dshHome>/memory.json`)
47
+ * @param {object} [options.base] composition defaults ({enabled, memoryDir, autoInject, registerSkill})
48
+ */
49
+ export class MemoryConfigStore {
50
+ constructor(options = {}) {
51
+ this.path = options.path ?? defaultConfigPath()
52
+ this.base = {
53
+ enabled: options.base?.enabled !== false,
54
+ memoryDir: typeof options.base?.memoryDir === 'string' && options.base.memoryDir.trim().length > 0
55
+ ? options.base.memoryDir
56
+ : '~/.memory',
57
+ autoInject: options.base?.autoInject !== false,
58
+ registerSkill: options.base?.registerSkill !== false,
59
+ }
60
+ this.config = { ...this.base }
61
+ this.watchers = new Set()
62
+ this.load()
63
+ }
64
+
65
+ /** Read the user file if present; invalid files are ignored, not fatal. */
66
+ load() {
67
+ let raw
68
+ try {
69
+ if (!existsSync(this.path)) return
70
+ raw = JSON.parse(readFileSync(this.path, 'utf8'))
71
+ } catch {
72
+ return // corrupt file: keep last good config
73
+ }
74
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return
75
+ try {
76
+ const picked = pickFields(raw)
77
+ if (picked.memoryDir !== undefined && (typeof picked.memoryDir !== 'string' || picked.memoryDir.trim().length === 0)) return
78
+ const resolved = SettingsSchema({ ...this.base, ...picked })
79
+ this.config = {
80
+ enabled: resolved.enabled,
81
+ memoryDir: resolved.memoryDir,
82
+ autoInject: resolved.autoInject,
83
+ registerSkill: resolved.registerSkill,
84
+ }
85
+ } catch {
86
+ // schema validation failed: keep last good config
87
+ }
88
+ }
89
+
90
+ /** Current effective config (stable reference until the next update). */
91
+ get() {
92
+ return this.config
93
+ }
94
+
95
+ /**
96
+ * Apply a partial update, persist it, and notify watchers.
97
+ * @param {Partial<MemorySettings>} patch
98
+ * @returns {MemorySettings} the new effective config
99
+ * @throws {Error} on invalid fields or values
100
+ */
101
+ update(patch) {
102
+ if (typeof patch !== 'object' || patch === null) throw new Error('config patch must be an object')
103
+ const picked = pickFields(patch)
104
+ if (picked.memoryDir !== undefined && (typeof picked.memoryDir !== 'string' || picked.memoryDir.trim().length === 0)) {
105
+ throw new Error('memoryDir must be a non-empty path string')
106
+ }
107
+ const next = SettingsSchema({
108
+ ...this.base,
109
+ ...this.config,
110
+ ...picked,
111
+ })
112
+ this.config = {
113
+ enabled: next.enabled,
114
+ memoryDir: next.memoryDir,
115
+ autoInject: next.autoInject,
116
+ registerSkill: next.registerSkill,
117
+ }
118
+ this.persist()
119
+ for (const watcher of this.watchers) {
120
+ try {
121
+ watcher(this.config)
122
+ } catch {
123
+ // best-effort notification
124
+ }
125
+ }
126
+ return this.config
127
+ }
128
+
129
+ /** Subscribe to config changes; returns the disposer. */
130
+ watch(callback) {
131
+ this.watchers.add(callback)
132
+ return () => this.watchers.delete(callback)
133
+ }
134
+
135
+ persist() {
136
+ try {
137
+ mkdirSync(dirname(this.path), { recursive: true })
138
+ const tmp = `${this.path}.tmp`
139
+ writeFileSync(tmp, `${JSON.stringify(this.config, null, 2)}\n`)
140
+ renameSync(tmp, this.path)
141
+ } catch (error) {
142
+ // Persistence is best-effort; the in-memory config is already applied.
143
+ // Surface the failure so the route can report it.
144
+ throw new Error(`config persisted in memory but not to disk: ${error instanceof Error ? error.message : String(error)}`)
145
+ }
146
+ }
147
+ }
package/lib/index.js CHANGED
@@ -19,6 +19,13 @@
19
19
  * pack / unpack) so memory stays usable from a shell and migratable
20
20
  * across machines and agents.
21
21
  *
22
+ * 4. **Settings panel.** `enabled` / `memoryDir` / `autoInject` /
23
+ * `registerSkill` are editable in the Settings panel and hot-apply.
24
+ * They live in `<dshHome>/memory.json` and are served to the browser
25
+ * through the plugin's own HTTP route — the settings wire only serves
26
+ * a hard-coded namespace allowlist, so a plugin namespace is never
27
+ * remotely writable (see `lib/config-store.js`).
28
+ *
22
29
  * The memory store itself is plain markdown + git — the plugin never owns
23
30
  * the format, only the workflows around it.
24
31
  *
@@ -26,12 +33,19 @@
26
33
  *
27
34
  * | key | default | meaning |
28
35
  * |---|---|---|
36
+ * | `enabled` | `true` | master switch: stops boot injection AND skill registration |
29
37
  * | `memoryDir` | `~/.memory` | absolute memory-store path (`~` expanded) |
30
38
  * | `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | files injected at boot |
31
39
  * | `bootMaxChars` | `6000` | total character budget of the boot block |
32
40
  * | `autoInject` | `true` | inject the boot block at session start |
33
41
  * | `registerSkill` | `true` | register the embedded `memory` skill |
34
42
  * | `scaffold` | `true` | create the store layout + templates when missing |
43
+ * | `configFile` | `<dshHome>/memory.json` | user-facing config file (Settings panel) |
44
+ *
45
+ * `enabled`, `memoryDir`, `autoInject` and `registerSkill` are editable in
46
+ * the Settings panel and hot-apply: boot injection, the skill registration
47
+ * and the scaffold react to edits immediately. The other keys are
48
+ * composition-time only.
35
49
  *
36
50
  * ## Install
37
51
  *
@@ -45,6 +59,9 @@
45
59
  * - insert:
46
60
  * - id: dsh-memory
47
61
  * name: dsh-plugin-memory
62
+ * inject:
63
+ * - systemPrompt
64
+ * - skills
48
65
  * config:
49
66
  * memoryDir: '~/.memory'
50
67
  * ```
@@ -57,6 +74,8 @@ import { join, resolve } from 'node:path'
57
74
  import z from '@deepseek-ai/schemastery'
58
75
  import { renderBootBlock } from './boot.js'
59
76
  import { ensureMemoryScaffold } from './scaffold.js'
77
+ import { MemoryConfigStore } from './config-store.js'
78
+ import { SettingsSchema } from './schema.js'
60
79
  import {
61
80
  MEMORY_SKILL_NAME,
62
81
  MEMORY_SKILL_DESCRIPTION,
@@ -66,16 +85,21 @@ import {
66
85
 
67
86
  export const name = 'memory'
68
87
 
88
+ /** HTTP route serving the user-facing config to the browser Settings panel. */
89
+ export const CONFIG_ROUTE_PATH = '/api/memory/config'
90
+
69
91
  export const inject = ['systemPrompt', 'skills']
70
92
 
71
93
  /** Schemastery schema applied to the plugin config before startup. */
72
94
  export const Config = z.object({
95
+ enabled: z.boolean().default(true),
73
96
  memoryDir: z.string().default('~/.memory'),
74
97
  bootFiles: z.array(z.string()).default(['SOUL.md', 'MEMORY.md', 'index.md']),
75
98
  bootMaxChars: z.number().default(6000),
76
99
  autoInject: z.boolean().default(true),
77
100
  registerSkill: z.boolean().default(true),
78
101
  scaffold: z.boolean().default(true),
102
+ configFile: z.union([z.string(), z.const(undefined)]),
79
103
  })
80
104
 
81
105
  /**
@@ -97,53 +121,157 @@ export function resolveMemoryDir(dir) {
97
121
  * @returns {() => void} disposer
98
122
  */
99
123
  export function apply(ctx, config = {}) {
100
- const memoryDir = resolveMemoryDir(config.memoryDir ?? '~/.memory')
101
124
  const bootMaxChars = Math.max(512, Number(config.bootMaxChars) || 6000)
125
+ const bootFiles = config.bootFiles ?? ['SOUL.md', 'MEMORY.md', 'index.md']
126
+ const scaffoldEnabled = config.scaffold !== false
102
127
 
103
- if (config.scaffold !== false) {
104
- const created = ensureMemoryScaffold(memoryDir)
105
- if (created.length > 0) {
106
- ctx.logger?.info(`memory: initialized scaffold at ${memoryDir} (${created.length} entries)`)
128
+ // Single user-facing config source: composition defaults + memory.json.
129
+ const store = new MemoryConfigStore({
130
+ path: typeof config.configFile === 'string' && config.configFile.trim().length > 0 ? config.configFile : undefined,
131
+ base: {
132
+ enabled: config.enabled !== false,
133
+ memoryDir: config.memoryDir ?? '~/.memory',
134
+ autoInject: config.autoInject !== false,
135
+ registerSkill: config.registerSkill !== false,
136
+ },
137
+ })
138
+
139
+ let bootDispose
140
+ let skillDispose
141
+ let scaffoldedDir
142
+
143
+ const disposeBoot = () => {
144
+ if (bootDispose !== undefined) {
145
+ bootDispose()
146
+ bootDispose = undefined
107
147
  }
108
148
  }
109
149
 
110
- const disposers = []
111
-
112
- if (config.autoInject !== false) {
113
- disposers.push(ctx.systemPrompt.context({
114
- name: 'memory-boot',
115
- order: -200,
116
- text: () => renderBootBlock(memoryDir, {
117
- bootFiles: config.bootFiles ?? ['SOUL.md', 'MEMORY.md', 'index.md'],
118
- bootMaxChars,
119
- }),
120
- }))
150
+ const disposeSkill = () => {
151
+ if (skillDispose !== undefined) {
152
+ skillDispose()
153
+ skillDispose = undefined
154
+ }
121
155
  }
122
156
 
123
- if (config.registerSkill !== false) {
124
- disposers.push(ctx.skills.register({
125
- name: MEMORY_SKILL_NAME,
126
- description: MEMORY_SKILL_DESCRIPTION,
127
- whenToUse: MEMORY_SKILL_WHEN_TO_USE,
128
- content: memorySkillContent(),
129
- source: 'dsh-plugin-memory',
130
- resourceBase: { kind: 'directory', path: memoryDir },
131
- }))
157
+ /**
158
+ * Bring boot injection, skill registration and the scaffold in line with
159
+ * the current resolved config. Called once at startup and on every
160
+ * config-store change; teardown + re-register keeps it correct for both
161
+ * toggle and memory-dir edits.
162
+ */
163
+ const rebuild = () => {
164
+ const resolved = store.get()
165
+ const memoryDir = resolveMemoryDir(resolved.memoryDir)
166
+ const wantBoot = resolved.enabled && resolved.autoInject
167
+ const wantSkill = resolved.enabled && resolved.registerSkill
168
+
169
+ if (resolved.enabled && scaffoldEnabled && memoryDir !== scaffoldedDir) {
170
+ const created = ensureMemoryScaffold(memoryDir)
171
+ scaffoldedDir = memoryDir
172
+ if (created.length > 0) {
173
+ ctx.logger?.info(`memory: initialized scaffold at ${memoryDir} (${created.length} entries)`)
174
+ }
175
+ }
176
+
177
+ if (wantBoot) {
178
+ disposeBoot()
179
+ bootDispose = ctx.systemPrompt.context({
180
+ name: 'memory-boot',
181
+ order: -200,
182
+ text: () => renderBootBlock(memoryDir, { bootFiles, bootMaxChars }),
183
+ })
184
+ } else {
185
+ disposeBoot()
186
+ }
187
+
188
+ if (wantSkill) {
189
+ disposeSkill()
190
+ skillDispose = ctx.skills.register({
191
+ name: MEMORY_SKILL_NAME,
192
+ description: MEMORY_SKILL_DESCRIPTION,
193
+ whenToUse: MEMORY_SKILL_WHEN_TO_USE,
194
+ content: memorySkillContent(),
195
+ source: 'dsh-plugin-memory',
196
+ resourceBase: { kind: 'directory', path: memoryDir },
197
+ })
198
+ } else {
199
+ disposeSkill()
200
+ }
201
+
202
+ ctx.logger?.info(
203
+ `memory: ${resolved.enabled ? `enabled, store at ${memoryDir}` : 'disabled'}`
204
+ + ` (boot ${wantBoot ? 'on' : 'off'}, skill ${wantSkill ? 'on' : 'off'})`,
205
+ )
132
206
  }
133
207
 
134
- ctx.logger?.info(`memory: store at ${memoryDir}`)
208
+ rebuild()
135
209
 
136
- return () => {
137
- for (const dispose of disposers) {
138
- try {
139
- dispose()
140
- } catch {
141
- // best-effort teardown
142
- }
210
+ // Settings-panel hot edits: any store change re-applies the config.
211
+ ctx.effect(() => {
212
+ const unwatch = store.watch(() => rebuild())
213
+ return () => {
214
+ unwatch()
143
215
  }
216
+ }, 'memory.config-watch()')
217
+
218
+ // Browser config route (optional: headless deployments have no webServer).
219
+ ctx.inject(['webServer'], (webCtx) => {
220
+ const disposeRoute = webCtx.webServer.register({
221
+ kind: 'exact',
222
+ path: CONFIG_ROUTE_PATH,
223
+ handler: async (req, res) => {
224
+ try {
225
+ if (req.method === 'GET') {
226
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
227
+ res.end(JSON.stringify(store.get()))
228
+ return
229
+ }
230
+ if (req.method === 'POST') {
231
+ const chunks = []
232
+ for await (const chunk of req) chunks.push(chunk)
233
+ const body = Buffer.concat(chunks).toString('utf8')
234
+ let patch
235
+ try {
236
+ patch = JSON.parse(body)
237
+ } catch {
238
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
239
+ res.end(JSON.stringify({ error: 'body must be JSON' }))
240
+ return
241
+ }
242
+ const next = store.update(patch)
243
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
244
+ res.end(JSON.stringify(next))
245
+ return
246
+ }
247
+ res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' })
248
+ res.end(JSON.stringify({ error: 'method not allowed' }))
249
+ } catch (error) {
250
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
251
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))
252
+ }
253
+ },
254
+ })
255
+ webCtx.effect(() => disposeRoute, 'memory.config-route()')
256
+ ctx.logger?.info(`memory: config route at ${CONFIG_ROUTE_PATH} (store ${store.path})`)
257
+ })
258
+
259
+ return () => {
260
+ disposeBoot()
261
+ disposeSkill()
144
262
  }
145
263
  }
146
264
 
265
+ // DSH's loader unwraps a package's default export before it starts the
266
+ // Cordis plugin. Keep the default export callable for direct consumers, but
267
+ // attach the Cordis metadata to that function so injected services and the
268
+ // config schema survive the unwrap step.
269
+ Object.defineProperties(apply, {
270
+ name: { value: name },
271
+ inject: { value: inject },
272
+ Config: { value: Config },
273
+ })
274
+
147
275
  export default apply
148
276
 
149
- export { renderBootBlock, ensureMemoryScaffold }
277
+ export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore }
package/lib/schema.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Shared schemas for dsh-plugin-memory.
3
+ *
4
+ * Split out so the config store can validate without importing the plugin
5
+ * entry (which imports the store).
6
+ *
7
+ * @module dsh-plugin-memory/schema
8
+ */
9
+
10
+ import z from '@deepseek-ai/schemastery'
11
+
12
+ /** The user-facing settings schema: composition config is the base layer. */
13
+ export const SettingsSchema = z.object({
14
+ enabled: z.boolean().default(true),
15
+ memoryDir: z.string().default('~/.memory'),
16
+ autoInject: z.boolean().default(true),
17
+ registerSkill: z.boolean().default(true),
18
+ })
@@ -14,6 +14,8 @@ export const inject: ['systemPrompt', 'skills']
14
14
 
15
15
  /** User-facing plugin configuration (all fields optional). */
16
16
  export interface MemoryConfig {
17
+ /** Master switch: stops boot injection AND skill registration. Default `true`. */
18
+ enabled?: boolean
17
19
  /** Absolute memory-store path; `~` is expanded. Default `'~/.memory'`. */
18
20
  memoryDir?: string
19
21
  /** Files injected at session start. Default `['SOUL.md', 'MEMORY.md', 'index.md']`. */
@@ -26,18 +28,56 @@ export interface MemoryConfig {
26
28
  registerSkill?: boolean
27
29
  /** Create the store layout and templates when missing. Default `true`. */
28
30
  scaffold?: boolean
31
+ /** Absolute user-facing config-file path. Default `<dshHome>/memory.json`. */
32
+ configFile?: string
29
33
  }
30
34
 
31
35
  /** Schemastery schema for {@link MemoryConfig}. */
32
36
  export const Config: import('@deepseek-ai/schemastery').default<MemoryConfig>
33
37
 
38
+ /** HTTP route serving the user-facing config to the Settings panel. */
39
+ export const CONFIG_ROUTE_PATH: '/api/memory/config'
40
+
41
+ /** User-editable settings (composition config is the base layer). */
42
+ export interface MemorySettings {
43
+ enabled?: boolean
44
+ memoryDir?: string
45
+ autoInject?: boolean
46
+ registerSkill?: boolean
47
+ }
48
+
49
+ /** Schemastery schema for {@link MemorySettings}. */
50
+ export const SettingsSchema: import('@deepseek-ai/schemastery').default<MemorySettings>
51
+
52
+ /** JSON config store: base + user layer, atomic persist, in-process watch. */
53
+ export class MemoryConfigStore {
54
+ constructor(options?: { path?: string; base?: MemorySettings })
55
+ readonly path: string
56
+ get(): MemorySettings
57
+ update(patch: Partial<MemorySettings>): MemorySettings
58
+ watch(callback: (config: MemorySettings) => void): () => void
59
+ }
60
+
61
+ /** Default config-file path (`<dshHome>/memory.json`). */
62
+ export function defaultConfigPath(): string
63
+
34
64
  /** Expand `~` and resolve `dir` to an absolute path. */
35
65
  export function resolveMemoryDir(dir: string): string
36
66
 
67
+ /** Callable Cordis plugin entry plus metadata consumed by the DSH loader. */
68
+ export interface MemoryPlugin {
69
+ (ctx: Context, config?: MemoryConfig): () => void
70
+ readonly name: 'memory'
71
+ readonly inject: ['systemPrompt', 'skills']
72
+ readonly Config: import('@deepseek-ai/schemastery').default<MemoryConfig>
73
+ }
74
+
37
75
  /** Cordis plugin entry. Returns the effect disposer. */
38
76
  export function apply(ctx: Context, config?: MemoryConfig): () => void
39
77
 
40
- export default apply
78
+ declare const plugin: MemoryPlugin
79
+
80
+ export default plugin
41
81
 
42
82
  /** Render the boot memory block injected at session start. */
43
83
  export function renderBootBlock(
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-plugin-memory",
3
3
  "description": "Long-term memory plugin for DeepSeek Harness: persistent cross-session markdown memory with a soul/persona file, auto-injected at every session start, plus remember/recall/consolidate/forget workflows and portable migration tooling.",
4
- "version": "0.1.0",
4
+ "version": "0.2.1",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -14,13 +14,26 @@
14
14
  "types": "./lib/types/index.d.ts",
15
15
  "default": "./lib/index.js"
16
16
  },
17
+ "./client": "./lib/client.js",
17
18
  "./package.json": "./package.json"
18
19
  },
20
+ "dsh": {
21
+ "bundle": {
22
+ "patch": "./cordis.patch.yml"
23
+ },
24
+ "client": {
25
+ "platform": "web",
26
+ "inject": [
27
+ "@deepseek-ai/dsh-client-runtime"
28
+ ]
29
+ }
30
+ },
19
31
  "files": [
20
32
  "lib/**",
21
33
  "skills/**",
22
34
  "scripts/**",
23
35
  "docs/**",
36
+ "cordis.patch.yml",
24
37
  "README.md",
25
38
  "LICENSE"
26
39
  ],
@@ -54,6 +67,7 @@
54
67
  "homepage": "https://github.com/LittleBlackTong/dsh-plugin-memory#readme",
55
68
  "scripts": {
56
69
  "test": "node scripts/memory.mjs --self-test",
70
+ "test:plugin": "node --test test/plugin-metadata.test.mjs",
57
71
  "lint:memory": "node scripts/memory.mjs lint"
58
72
  }
59
73
  }