dsh-plugin-memory 0.14.0 → 0.15.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/CHANGELOG.md +25 -0
- package/README.md +11 -1
- package/README.zh.md +11 -1
- package/lib/boot.js +11 -3
- package/lib/client.js +163 -0
- package/lib/index.js +60 -1
- package/lib/soul.js +268 -0
- package/lib/types/index.d.ts +3 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,31 @@
|
|
|
2
2
|
|
|
3
3
|
所有记录跟随 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 风格;版本号与 `package.json` 保持一致。
|
|
4
4
|
|
|
5
|
+
## [0.15.1] - 2026-11-04
|
|
6
|
+
|
|
7
|
+
### Docs
|
|
8
|
+
|
|
9
|
+
- **README 新增「反馈与交流 / Feedback & community」章节**(中英):issue 链接 + 「dsh-plugin-memory 插件沟通」微信群二维码(`assets/wechat-group.png`,GitHub raw 绝对 URL,npm 页面同样可见),并标注二维码有效期;过期后以 issue 为准。
|
|
10
|
+
|
|
11
|
+
## [0.15.0] - 2026-11-04
|
|
12
|
+
|
|
13
|
+
### Added(0.15.0:快速铸魂 + 未铸魂提醒)
|
|
14
|
+
|
|
15
|
+
- **设置页「人格基础(快速铸魂)」卡片**:我的名字 / 你的称呼 / 基础人格描述,保存写入 `SOUL.md` 的受管区块(`<!-- dsh-memory:soul:start/end -->`,只替换区块,其余内容一字不动),并自动把 `BOOTSTRAP.md` 标 `status: complete`。新用户预填**通用默认值**(`助手` / `你` / **三段式人格示例**),绝不预设别人的名字;默认值直接回显在输入框里,可改可直接保存。描述支持多行(区块内用两空格续行,读写幂等)。
|
|
16
|
+
- **未铸魂提醒**:boot 块仍前置第一人称引导,并明确要求 agent **先提醒用户**(可直接对话回答,也可去设置页填卡片);受管区块三字段齐全即视为基础铸魂完成,不再催。
|
|
17
|
+
- **渲染层过滤**:注入 SOUL 时剔除 `_(铸魂对话中确认)_` 占位行(文件本身保留,详细人格仍可后续对话补充)。
|
|
18
|
+
- 新模块 `lib/soul.js`(纯 Node);新路由 `GET/POST /api/memory/soul`(GET 读字段、POST 保存并标 complete;校验长度、只写 memoryDir 内 SOUL.md、原子写)。
|
|
19
|
+
|
|
20
|
+
### Fixed(存量手写 SOUL 不回显)
|
|
21
|
+
|
|
22
|
+
- **对话铸魂的老库在面板里显示「还没铸魂」**:`readSoulProfile` 原先只认受管区块,而老库是对话铸魂写的手写 SOUL(没有区块)→ 面板回退到通用默认 + placeholder。现在无区块时从 SOUL 解析 `名字` / `相互称呼` / `角色` 回显;GET `/api/memory/soul` 新增 `needsBootstrap`,面板区分三态:**未铸魂 / 已铸魂(对话生成,值为解析结果)/ 已由面板接管**。
|
|
23
|
+
- 默认人格描述改为**三段式示例**并直接回显,可改可直接保存;描述支持多行(受管区块用两空格续行,读写幂等)。
|
|
24
|
+
|
|
25
|
+
### Tests
|
|
26
|
+
|
|
27
|
+
- `soul` 15 条(读取/插入/幂等替换/校验/BOOTSTRAP/占位符过滤/多行 round-trip/老库回显/与 boot 集成);`session-control` 新增 soul 路由集成;`soul-card` 3 条(客户端渲染 + 路由常量)。
|
|
28
|
+
- 全量 **301/301**(0.14.0 基线 283 + 18);`npm test` self-test PASS。
|
|
29
|
+
|
|
5
30
|
## [0.14.0] - 2026-11-04
|
|
6
31
|
|
|
7
32
|
### Added(0.14.0:会话级记忆开关)
|
package/README.md
CHANGED
|
@@ -35,6 +35,7 @@ After that the loop is simple: the agent writes memories back as you work, and y
|
|
|
35
35
|
|
|
36
36
|
- **Mandatory boot injection (with routing-table protection)**: the plugin injects a memory boot block (`SOUL.md` persona + `MEMORY.md` protocol + `index.md` directory + recent activity) into the session context via `ctx.systemPrompt.context()`. The host deduplicates by projection: an unchanged memory is injected once, and a changed memory replaces the previous snapshot — this is the **hard guarantee** that a new session always loads memory first, rather than hoping the model calls a skill. The total budget is `bootMaxChars`, **allocated per file**: every file first gets an equal share (capped by its real size), and the remaining budget goes to `index.md` first, then to files that still have content left — so as the store grows, the tail of the directory is not the first thing to be truncated (see "boot budget allocation"). Two polite gates ship enabled by default: `deferUntilUserSpeaks` (inject only after the user speaks) and `activeSessionOnly` (inject only into the currently active session) — see "Configuration".
|
|
37
37
|
- **Per-session switch (v0.14.0)**: not every conversation should be remembered. A chip in the composer (`conversation.input.left`), the `/memory on|off|status` command, and a switch in the settings panel all flip the same per-session gate: off means **no boot injection, no digest/recall nudges and no `last_access` stamping for that session** — nothing is deleted, and other sessions are untouched. Whole projects can default to off via `disabledWorkspaces` (path-boundary match on the session cwd; a per-session override still wins), and each session's choice is remembered for `sessionTtlDays` (7) so a resumed session keeps it. The command plane and the chip share `/api/memory/session`, so `/`-menu users and pointer users never disagree. The `memory` skill stays globally registered (the host cannot scope skills per session); with no boot block injected the agent has no memory protocol in context — the boundary is documented.
|
|
38
|
+
- **Quick soul setup (v0.15.0)**: the settings page has a **Basic soul (quick forging)** card — *my name / what I call you / baseline persona* — which writes a fenced managed block into `SOUL.md` (the rest of the file is left untouched) and marks `BOOTSTRAP.md` complete. A user who never chats about their soul can shed the template persona with one save; the boot block picks it up from the next session, no restart. Brand-new users are pre-filled with **generic defaults** (`助手` / `你` / a three-line persona example) so the card never shows somebody else's name and the fields are already filled in for editing (or saving as-is). The persona field accepts multiple lines. Stores forged in chat (no managed block) are echoed from the `SOUL.md` text — name, mutual address and role — so the card never pretends a soul is missing. While no profile exists the boot block still prepends the first-person forging nudge, and now **asks the agent to remind the user first**, pointing at both the chat path and this card. `GET/POST /api/memory/soul`. The file keeps its `_(铸魂对话中确认)_` placeholders — only the injected copy filters them out, so the detailed sections can still be filled in later.
|
|
38
39
|
- **Automatic `last_access` stamping**: the salience decay rules in `MEMORY.md` depend on `last_access`, which used to be pure self-discipline — the field existed in the template and the rules mentioned it, but no code ever wrote it, so every page silently aged and the decay table was decorative. Now, on the first real user message of a session, the plugin stamps today's date onto the pages the boot block **actually injected** (`SOUL.md` / `MEMORY.md` / `index.md` plus the pages the directory references) — once per session, idempotent per day, touching only the `last_access` line. `dsh-memory touch <pages...>` backfills manually; `trackPageAccess: false` disables it.
|
|
39
40
|
- **SOUL.md soul-forging**: right after installation, the first task is a conversation with the user to define a soul (name, personality, values, tone, boundaries) and to confirm identity and relationship, driven by the `BOOTSTRAP.md` checklist, which takes priority over ordinary tasks until complete.
|
|
40
41
|
- **Automatic soul-forging guidance**: while the store has no soul yet (`BOOTSTRAP.md` not complete, or `SOUL.md` still the placeholder template), the boot block prepends a first-person prompt — "my first job is to establish who I am and who you are: what my name is, what to call you, what we are to each other, and what personality I should have" — so the agent **starts the forging conversation itself**, item by item, writing each answer back, OpenClaw-style, instead of waiting to be fed. The prompt disappears once forging completes, at zero cost.
|
|
@@ -203,6 +204,8 @@ To override a composition key (for example raising the boot budget), write an **
|
|
|
203
204
|
|
|
204
205
|
After installation, the agent's first task in the first session is **not** to work, but to talk with you about its soul: name, personality, values, tone, boundaries, plus who you are and what you are to each other. Each item is confirmed and written back to `SOUL.md` / `user/profile.md` until `BOOTSTRAP.md`'s `status` becomes `complete`. You can skip or defer at any time.
|
|
205
206
|
|
|
207
|
+
Prefer not to chat about it? **Settings → Memory → Basic soul** fills the three essentials in one save (my name / your name / baseline persona), writes them into a managed block in `SOUL.md`, and marks forging complete — the same result as the conversation, in ten seconds.
|
|
208
|
+
|
|
206
209
|
## The four operations
|
|
207
210
|
|
|
208
211
|
- **remember**: distil what is worth persisting into pages, updating `index.md` and appending to `log.md` in the same pass. Keep routing-table discipline when maintaining the index: one line per page, a one-sentence summary (≤ 80 characters) plus `salience`.
|
|
@@ -267,7 +270,14 @@ The test suite (`node --test`) currently holds **260 tests**, and CI (`.github/w
|
|
|
267
270
|
- [ ] GitHub Actions CI (running `--self-test` and lint)
|
|
268
271
|
- [ ] Encrypted memory storage option
|
|
269
272
|
|
|
270
|
-
|
|
273
|
+
## Feedback & community
|
|
274
|
+
|
|
275
|
+
- **Bug reports / feature requests / PRs**: [open an issue](https://github.com/LittleBlackTong/dsh-plugin-memory/issues) — that is the durable channel and it always works.
|
|
276
|
+
- **WeChat group**: scan the QR code below to join the **「dsh-plugin-memory 插件沟通」** group — questions, feedback and PR coordination all happen there.
|
|
277
|
+
|
|
278
|
+

|
|
279
|
+
|
|
280
|
+
> The QR code is valid until **2026-11-11**. If it has expired, open an issue and I'll refresh it.
|
|
271
281
|
|
|
272
282
|
## License
|
|
273
283
|
|
package/README.zh.md
CHANGED
|
@@ -27,6 +27,8 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
27
27
|
|
|
28
28
|
2. **重启应用**,开个会话随便说句话。boot 块会自动加载——因为记忆库还没有灵魂,agent 会**主动开始「铸魂」对话**:它叫什么名字、怎么称呼你、你们是什么关系、该是什么性格。答多答少都行,它会逐项写回去。
|
|
29
29
|
|
|
30
|
+
不想聊也行:**设置 → 记忆 → 人格基础**,一次保存填好「我的名字 / 你的称呼 / 基础人格描述」,直接写入 `SOUL.md` 受管区块并把铸魂标记为完成——十秒钟,效果和对话一样。
|
|
31
|
+
|
|
30
32
|
3. **确认生效**。`dsh-memory doctor` 做一次环境体检(脚手架 / 孤儿页 / git 状态 / boot 预算),最后给出修复每一条的命令。或者打开**设置 → 记忆**看健康看板,选项都能热改。
|
|
31
33
|
|
|
32
34
|
之后就很简单了:你干活时 agent 顺手把记忆写回去;你随时能手动整理记忆库——纯 markdown + git,没有任何锁死的东西。
|
|
@@ -35,6 +37,7 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
35
37
|
|
|
36
38
|
- **开机强制注入(带路由表保护)**:插件通过 `ctx.systemPrompt.context()` 把记忆 boot 块(`SOUL.md` 人格 + `MEMORY.md` 协议 + `index.md` 目录 + 最近动态)注入会话上下文。宿主按投影去重:记忆不变就不重复注入,变化时新快照自动取代旧的——这是"新会话必先加载记忆"的**硬保障**,不需要模型碰运气调技能。总预算是 `bootMaxChars`,**按文件分配**:每个文件先拿一份均分(受实际大小封顶),剩余额度优先给 `index.md`、再给尚有内容未注入的文件——所以记忆库长大时,目录的尾部不会先被截掉(详见「boot 预算分配」)。默认还带**两道礼貌闸门**:`deferUntilUserSpeaks`(用户开口后才注入)与 `activeSessionOnly`(只注入当前激活会话),见「配置」。
|
|
37
39
|
- **按会话开关(v0.14.0)**:不是每段对话都该被记住。输入框工具行左侧的 chip、`/memory on|off|status` 命令、设置面板里的开关,三者改的是同一个会话级 gate:关闭后**本会话不注入 boot 块、不发 digest/追忆提醒、不盖 `last_access`**——记忆文件不删,其它会话不受影响。整个项目可以设成默认关(`disabledWorkspaces`,按会话 cwd 的路径边界匹配,会话级 override 仍然优先);每个会话的选择会记住 `sessionTtlDays`(7)天,恢复的会话保持原选择。命令面与 chip 共用 `/api/memory/session`,键盘用户与鼠标用户不会看到两套状态。`memory` 技能仍是全局注册(宿主无法按会话停技能);boot 不注入后 agent 上下文里没有记忆协议——这个边界在文档里写清。
|
|
40
|
+
- **快速铸魂(v0.15.0)**:设置页新增「人格基础(快速铸魂)」卡片——**我的名字 / 你的称呼 / 基础人格描述**——保存后写入 `SOUL.md` 的受管区块(其余内容一字不动),并把 `BOOTSTRAP.md` 标成 complete。从没聊过铸魂的用户,一次保存就能摆脱模板人格;boot 块下一次会话即生效(无需重启)。新用户预填**通用默认值**(`助手` / `你` / 三段式人格示例),不会出现别人的名字;默认值直接回显在输入框里,可改也可直接保存。人格描述支持多行。对话铸魂的老库(没有受管区块)会从 `SOUL.md` 解析回显名字/相互称呼/角色,不会假装"还没铸魂"。还没设置时,boot 块仍会前置第一人称铸魂引导,并且**现在会先提醒用户**:既可以对话回答,也可以去设置页填卡片。`GET/POST /api/memory/soul`。文件里的 `_(铸魂对话中确认)_` 占位行保留(只在注入副本里过滤),详细人格仍可后续对话补充。
|
|
38
41
|
- **last_access 自动戳记**:`MEMORY.md` 的 salience 衰减规则依赖 `last_access`,而它以前纯粹靠自觉——模板里有字段、规则里提到它,但没有任何代码去写它,于是每个页面都原地变老、衰减表形同虚设。现在会话收到第一条真实用户消息时,插件会把 boot 块**实际注入过的页面**(`SOUL.md` / `MEMORY.md` / `index.md` + 目录里被引用到的页)戳成当天,每会话一次、按天幂等,只改 `last_access` 一行;`dsh-memory touch <pages...>` 可手动补记,`trackPageAccess: false` 可关闭。
|
|
39
42
|
- **SOUL.md 铸魂**:安装后首要任务是和用户对话定义灵魂(名字、性格、价值观、语气、边界)、确认身份与关系(`BOOTSTRAP.md` 清单驱动,complete 前优先于常规任务)。
|
|
40
43
|
- **铸魂自动引导**:记忆库还没有灵魂(`BOOTSTRAP.md` 非 complete,或 `SOUL.md` 仍是占位模板)时,boot 块会自动前置一段第一人称引导词——「我的首要任务是确认我是谁,还有你是谁:我叫什么名字、怎么称呼你、你我是什么关系、我该是什么样的性格」——像 OpenClaw 初始化那样,**由 agent 在对话里主动发起铸魂**,逐项问、逐项写回,而不是等用户来喂。铸魂完成后引导词自动消失,零开销。
|
|
@@ -273,7 +276,14 @@ node scripts/memory.mjs --self-test # 冒烟测试(无需安装依赖)
|
|
|
273
276
|
- [ ] GitHub Actions CI(跑 `--self-test` 与 lint)
|
|
274
277
|
- [ ] 记忆加密存储选项
|
|
275
278
|
|
|
276
|
-
|
|
279
|
+
## 反馈与交流
|
|
280
|
+
|
|
281
|
+
- **报 bug / 提需求 / 交 PR**:[提 issue](https://github.com/LittleBlackTong/dsh-plugin-memory/issues)——这是长期有效的渠道。
|
|
282
|
+
- **微信群**:扫下面的二维码加入「dsh-plugin-memory 插件沟通」群,问题、反馈、PR 协调都在群里。
|
|
283
|
+
|
|
284
|
+

|
|
285
|
+
|
|
286
|
+
> 二维码有效期到 **2026-11-11**;过期后请提 issue,我会更新。
|
|
277
287
|
|
|
278
288
|
## License
|
|
279
289
|
|
package/lib/boot.js
CHANGED
|
@@ -6,13 +6,15 @@
|
|
|
6
6
|
* store costs nothing extra after the first injection; when the store
|
|
7
7
|
* changes, the new snapshot supersedes the old one.
|
|
8
8
|
*
|
|
9
|
-
* This module depends only on `node:*` builtins
|
|
9
|
+
* This module depends only on `node:*` builtins plus this package's pure
|
|
10
|
+
* `soul.js` (which itself uses builtins only).
|
|
10
11
|
*
|
|
11
12
|
* @module dsh-plugin-memory/boot
|
|
12
13
|
*/
|
|
13
14
|
|
|
14
15
|
import { existsSync, readFileSync } from 'node:fs'
|
|
15
16
|
import { join } from 'node:path'
|
|
17
|
+
import { filterBootstrapPlaceholders, hasManagedSoulProfile } from './soul.js'
|
|
16
18
|
|
|
17
19
|
/** Files injected at session start when the config does not override them. */
|
|
18
20
|
export const DEFAULT_BOOT_FILES = ['SOUL.md', 'MEMORY.md', 'index.md']
|
|
@@ -187,7 +189,7 @@ export function allocateBootBudget(memoryDir, options = {}) {
|
|
|
187
189
|
*/
|
|
188
190
|
export const SOUL_DIRECTIVE = `### 铸魂阶段 · 我还没有灵魂
|
|
189
191
|
|
|
190
|
-
|
|
192
|
+
我的记忆库还是空的——我还没有名字、不知道我是谁、也不知道你是谁。**所以在做任何任务之前,我先提醒用户**:我们花两分钟把这件事定下来——你可以直接回答我,也可以打开「设置 → 记忆 → 人格基础」自己填(保存后下一次会话生效)。这正是我们现在要一起完成的:**我的首要任务是确认我是谁,还有你是谁——我叫什么名字、怎么称呼你、你我是什么关系、我该是什么样的性格。**
|
|
191
193
|
|
|
192
194
|
所以我会在对话里主动问你,一次一个问题,你确认一项我就写回记忆一项:
|
|
193
195
|
|
|
@@ -224,6 +226,9 @@ export function readBootstrapStatus(memoryDir) {
|
|
|
224
226
|
* @returns {boolean}
|
|
225
227
|
*/
|
|
226
228
|
export function needsSoulBootstrap(memoryDir) {
|
|
229
|
+
// A profile saved from the Settings panel counts as a basic soul: stop
|
|
230
|
+
// nagging even while the detailed template sections are still placeholders.
|
|
231
|
+
if (hasManagedSoulProfile(memoryDir)) return false
|
|
227
232
|
const soulText = readCapped(join(memoryDir, 'SOUL.md'), 4096)
|
|
228
233
|
if (soulText === undefined || soulText.includes('(铸魂对话中确认)')) return true
|
|
229
234
|
if (!existsSync(join(memoryDir, 'BOOTSTRAP.md'))) return false
|
|
@@ -272,7 +277,10 @@ export function renderBootBlock(memoryDir, options = {}) {
|
|
|
272
277
|
const cap = caps.get(fileName) ?? 0
|
|
273
278
|
const text = cap > 0 ? readCapped(path, cap) : undefined
|
|
274
279
|
if (text === undefined || text.trim() === '') continue
|
|
275
|
-
|
|
280
|
+
// Placeholder lines are noise once a basic soul exists; the file keeps
|
|
281
|
+
// them (a later conversation may fill the detailed sections in).
|
|
282
|
+
const content = fileName === 'SOUL.md' ? filterBootstrapPlaceholders(text) : text
|
|
283
|
+
sections.push(`### ${fileName}\n\n${content}`)
|
|
276
284
|
// Personality first, then how to speak: the tone section goes right after
|
|
277
285
|
// the soul file so the rules are read as an extension of the persona.
|
|
278
286
|
if (fileName === 'SOUL.md' && toneSection.length > 0) {
|
package/lib/client.js
CHANGED
|
@@ -104,6 +104,23 @@ window.__ModuleLoader__.load({
|
|
|
104
104
|
chipMenuTitle: '记忆范围',
|
|
105
105
|
chipMenuUnavailable: '暂时读不到会话状态',
|
|
106
106
|
chipMenuFailed: '操作失败:',
|
|
107
|
+
soulSection: '人格基础(快速铸魂)',
|
|
108
|
+
soulHint: '下面是通用默认值,按你的喜好改;保存后下一次会话生效。也可以直接在对话里让我逐项问,效果一样。',
|
|
109
|
+
soulUnmanaged: '还没铸魂:下面是通用默认,可直接用或按喜好改',
|
|
110
|
+
soulFromChat: '已铸魂(对话生成):下面是 SOUL.md 里的当前值,保存后由面板接管',
|
|
111
|
+
soulManaged: '已设置 · 保存后下一次会话生效',
|
|
112
|
+
soulAgentName: '我的名字',
|
|
113
|
+
soulAgentPlaceholder: '例如:小蓝',
|
|
114
|
+
soulUserName: '你的称呼',
|
|
115
|
+
soulUserPlaceholder: '例如:阿周',
|
|
116
|
+
soulSummary: '基础人格描述',
|
|
117
|
+
soulSummaryPlaceholder: '例如:直接、诚实、先结论后细节;不确定时明说,不编造。',
|
|
118
|
+
soulSave: '保存人格',
|
|
119
|
+
soulSaving: '保存中…',
|
|
120
|
+
soulSaved: '已保存,下次会话生效',
|
|
121
|
+
soulSavedForged: '已保存,铸魂标记为完成',
|
|
122
|
+
soulLoading: '读取人格设置中…',
|
|
123
|
+
soulFailed: '保存失败:',
|
|
107
124
|
minutesPlaceholder: '30',
|
|
108
125
|
maxMinutesPlaceholder: '240',
|
|
109
126
|
maxPerSessionPlaceholder: '3',
|
|
@@ -233,6 +250,23 @@ window.__ModuleLoader__.load({
|
|
|
233
250
|
chipMenuTitle: 'Memory scope',
|
|
234
251
|
chipMenuUnavailable: 'Could not read the session state',
|
|
235
252
|
chipMenuFailed: 'Action failed: ',
|
|
253
|
+
soulSection: 'Basic soul (quick forging)',
|
|
254
|
+
soulHint: 'Below is a generic default — tweak it to taste; saving applies from the next session. You can also let me ask you item by item in chat.',
|
|
255
|
+
soulUnmanaged: 'Not forged yet: the generic defaults below are ready to use or tweak',
|
|
256
|
+
soulFromChat: 'Soul forged in chat: values below are parsed from SOUL.md; saving hands it to the panel',
|
|
257
|
+
soulManaged: 'Set · saving applies from the next session',
|
|
258
|
+
soulAgentName: 'My name',
|
|
259
|
+
soulAgentPlaceholder: 'e.g. 小蓝',
|
|
260
|
+
soulUserName: 'What I call you',
|
|
261
|
+
soulUserPlaceholder: 'e.g. 阿周',
|
|
262
|
+
soulSummary: 'Baseline persona',
|
|
263
|
+
soulSummaryPlaceholder: 'e.g. Direct, honest, conclusion first; say when unsure, never fabricate.',
|
|
264
|
+
soulSave: 'Save soul',
|
|
265
|
+
soulSaving: 'Saving…',
|
|
266
|
+
soulSaved: 'Saved; applies from the next session',
|
|
267
|
+
soulSavedForged: 'Saved; soul forging marked complete',
|
|
268
|
+
soulLoading: 'Reading the soul profile…',
|
|
269
|
+
soulFailed: 'Save failed: ',
|
|
236
270
|
minutesPlaceholder: '30',
|
|
237
271
|
maxMinutesPlaceholder: '240',
|
|
238
272
|
maxPerSessionPlaceholder: '3',
|
|
@@ -488,6 +522,9 @@ window.__ModuleLoader__.load({
|
|
|
488
522
|
const t = useT(props)
|
|
489
523
|
return React.createElement(LocaleContext.Provider, { value: t },
|
|
490
524
|
React.createElement('div', { 'data-dsh-memory-panel': '', style: { padding: '8px 0' } },
|
|
525
|
+
React.createElement(SectionBoundary, null,
|
|
526
|
+
React.createElement(SoulCard),
|
|
527
|
+
),
|
|
491
528
|
React.createElement(SectionBoundary, null,
|
|
492
529
|
React.createElement(MemoryForm, { onSaved: () => setGen((value) => value + 1) }),
|
|
493
530
|
),
|
|
@@ -727,6 +764,130 @@ window.__ModuleLoader__.load({
|
|
|
727
764
|
React.createElement('option', { key: option.value, value: option.value }, option.label)))
|
|
728
765
|
}
|
|
729
766
|
|
|
767
|
+
// ---------------- 人格基础(快速铸魂) ----------------
|
|
768
|
+
//
|
|
769
|
+
// 面板里直接填三件事,写入 SOUL.md 的受管区块(不碰用户手写内容),
|
|
770
|
+
// 并顺手把 BOOTSTRAP 标 complete:没铸魂的用户不必先聊一轮才能甩掉模板人格。
|
|
771
|
+
const SOUL_URL = '/api/memory/soul'
|
|
772
|
+
|
|
773
|
+
function SoulCard(props) {
|
|
774
|
+
const t = useT(props)
|
|
775
|
+
const [state, setState] = React.useState(undefined)
|
|
776
|
+
const [draft, setDraft] = React.useState(undefined)
|
|
777
|
+
const [busy, setBusy] = React.useState(false)
|
|
778
|
+
const [notice, setNotice] = React.useState(undefined)
|
|
779
|
+
const [error, setError] = React.useState(undefined)
|
|
780
|
+
|
|
781
|
+
React.useEffect(() => {
|
|
782
|
+
fetch(SOUL_URL)
|
|
783
|
+
.then(async (response) => {
|
|
784
|
+
if (!response.ok) throw new Error(`GET ${response.status}`)
|
|
785
|
+
return response.json()
|
|
786
|
+
})
|
|
787
|
+
.then((value) => setState(value))
|
|
788
|
+
.catch(() => setState({ ok: false, reason: 'error' }))
|
|
789
|
+
}, [])
|
|
790
|
+
|
|
791
|
+
React.useEffect(() => {
|
|
792
|
+
if (notice === undefined || typeof setTimeout !== 'function') return undefined
|
|
793
|
+
const timer = setTimeout(() => setNotice(undefined), 5000)
|
|
794
|
+
return () => clearTimeout(timer)
|
|
795
|
+
}, [notice])
|
|
796
|
+
|
|
797
|
+
if (state === undefined) {
|
|
798
|
+
return React.createElement('div', { style: { ...cardStyle, fontSize: '12px', color: 'var(--dsw-alias-label-secondary, #888)' } }, t('soulLoading'))
|
|
799
|
+
}
|
|
800
|
+
const profile = state.profile ?? {}
|
|
801
|
+
const managed = profile.managed === true
|
|
802
|
+
const value = draft ?? {
|
|
803
|
+
agentName: profile.agentName ?? '',
|
|
804
|
+
userName: profile.userName ?? '',
|
|
805
|
+
summary: profile.summary ?? '',
|
|
806
|
+
}
|
|
807
|
+
const update = (key) => (event) => setDraft({ ...value, [key]: event.target.value })
|
|
808
|
+
const save = () => {
|
|
809
|
+
setBusy(true)
|
|
810
|
+
setError(undefined)
|
|
811
|
+
fetch(SOUL_URL, {
|
|
812
|
+
method: 'POST',
|
|
813
|
+
headers: { 'content-type': 'application/json' },
|
|
814
|
+
body: JSON.stringify(value),
|
|
815
|
+
})
|
|
816
|
+
.then(async (response) => {
|
|
817
|
+
const body = await response.json().catch(() => ({}))
|
|
818
|
+
if (!response.ok) throw new Error(body.error ?? `POST ${response.status}`)
|
|
819
|
+
setState({ ok: true, profile: body.profile, bootstrapStatus: body.bootstrapStatus, needsBootstrap: false })
|
|
820
|
+
setDraft(undefined)
|
|
821
|
+
setNotice(body.bootstrapChanged ? t('soulSavedForged') : t('soulSaved'))
|
|
822
|
+
})
|
|
823
|
+
.catch((err) => setError(`${t('soulFailed')}${err instanceof Error ? err.message : String(err)}`))
|
|
824
|
+
.finally(() => setBusy(false))
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
const field = (label, key, placeholder, maxLength) => React.createElement('div', { style: { marginBottom: '10px' } },
|
|
828
|
+
React.createElement('div', { style: labelStyle }, label),
|
|
829
|
+
React.createElement('input', {
|
|
830
|
+
type: 'text',
|
|
831
|
+
'aria-label': label,
|
|
832
|
+
value: value[key],
|
|
833
|
+
placeholder,
|
|
834
|
+
disabled: busy,
|
|
835
|
+
maxLength,
|
|
836
|
+
onChange: update(key),
|
|
837
|
+
style: { ...inputStyle, width: '100%', maxWidth: '360px' },
|
|
838
|
+
}),
|
|
839
|
+
)
|
|
840
|
+
|
|
841
|
+
return React.createElement('div', { style: cardStyle },
|
|
842
|
+
React.createElement('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '10px', marginBottom: '4px' } },
|
|
843
|
+
React.createElement('div', { style: { ...labelStyle, fontWeight: 600 } }, t('soulSection')),
|
|
844
|
+
state.needsBootstrap === false && !managed
|
|
845
|
+
? React.createElement('span', { style: subStyle }, t('soulFromChat'))
|
|
846
|
+
: managed
|
|
847
|
+
? React.createElement('span', { style: subStyle }, t('soulManaged'))
|
|
848
|
+
: React.createElement('span', { role: 'status', style: { ...subStyle, color: 'var(--dsw-alias-state-warning-primary, #b7791f)' } }, t('soulUnmanaged')),
|
|
849
|
+
),
|
|
850
|
+
React.createElement('div', { style: { ...subStyle, marginBottom: '12px' } }, t('soulHint')),
|
|
851
|
+
field(t('soulAgentName'), 'agentName', t('soulAgentPlaceholder'), 64),
|
|
852
|
+
field(t('soulUserName'), 'userName', t('soulUserPlaceholder'), 64),
|
|
853
|
+
React.createElement('div', { style: { marginBottom: '10px' } },
|
|
854
|
+
React.createElement('div', { style: labelStyle }, t('soulSummary')),
|
|
855
|
+
React.createElement('textarea', {
|
|
856
|
+
'aria-label': t('soulSummary'),
|
|
857
|
+
value: value.summary,
|
|
858
|
+
placeholder: t('soulSummaryPlaceholder'),
|
|
859
|
+
disabled: busy,
|
|
860
|
+
maxLength: 2000,
|
|
861
|
+
rows: 3,
|
|
862
|
+
onChange: update('summary'),
|
|
863
|
+
style: { ...inputStyle, width: '100%', maxWidth: '520px', fontFamily: 'inherit', resize: 'vertical' },
|
|
864
|
+
}),
|
|
865
|
+
),
|
|
866
|
+
React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '12px' } },
|
|
867
|
+
React.createElement('button', {
|
|
868
|
+
type: 'button',
|
|
869
|
+
disabled: busy,
|
|
870
|
+
onClick: save,
|
|
871
|
+
style: {
|
|
872
|
+
padding: '7px 14px',
|
|
873
|
+
fontSize: '13px',
|
|
874
|
+
lineHeight: '18px',
|
|
875
|
+
borderRadius: '6px',
|
|
876
|
+
border: '1px solid var(--dsw-alias-border-l2, #d4d4d8)',
|
|
877
|
+
background: 'var(--dsw-alias-brand-primary, #4c8bf5)',
|
|
878
|
+
color: '#fff',
|
|
879
|
+
cursor: busy ? 'not-allowed' : 'pointer',
|
|
880
|
+
opacity: busy ? 0.6 : 1,
|
|
881
|
+
},
|
|
882
|
+
}, busy ? t('soulSaving') : t('soulSave')),
|
|
883
|
+
notice !== undefined ? React.createElement('span', { role: 'status', style: subStyle }, notice) : null,
|
|
884
|
+
),
|
|
885
|
+
error !== undefined
|
|
886
|
+
? React.createElement('div', { role: 'alert', style: { marginTop: '8px', fontSize: '12px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' } }, error)
|
|
887
|
+
: null,
|
|
888
|
+
)
|
|
889
|
+
}
|
|
890
|
+
|
|
730
891
|
// ---------------- 会话与工作区(设置面板) ----------------
|
|
731
892
|
//
|
|
732
893
|
// 会话级记忆开关的第二个入口:设置页没有 sessionId,Host 的
|
|
@@ -1908,6 +2069,8 @@ window.__ModuleLoader__.load({
|
|
|
1908
2069
|
MemoryForm,
|
|
1909
2070
|
SessionControls,
|
|
1910
2071
|
MemoryChip,
|
|
2072
|
+
SoulCard,
|
|
2073
|
+
SOUL_URL,
|
|
1911
2074
|
SESSION_URL,
|
|
1912
2075
|
InsightsCard,
|
|
1913
2076
|
GraphCard,
|
package/lib/index.js
CHANGED
|
@@ -88,7 +88,7 @@
|
|
|
88
88
|
import { homedir } from 'node:os'
|
|
89
89
|
import { join, resolve } from 'node:path'
|
|
90
90
|
import z from '@deepseek-ai/schemastery'
|
|
91
|
-
import { renderBootBlock, DEFAULT_BOOT_FILES } from './boot.js'
|
|
91
|
+
import { renderBootBlock, DEFAULT_BOOT_FILES, needsSoulBootstrap, readBootstrapStatus } from './boot.js'
|
|
92
92
|
import {
|
|
93
93
|
accessSummary,
|
|
94
94
|
extractReferencedPages,
|
|
@@ -109,6 +109,7 @@ import { claimProactiveLock, defaultProactiveCooldownPath } from './proactive-lo
|
|
|
109
109
|
import { AutoCommitter } from './autocommit.js'
|
|
110
110
|
import { ActivityTracker } from './activity-tracker.js'
|
|
111
111
|
import { SessionGate, matchesWorkspace } from './session-gate.js'
|
|
112
|
+
import { markBootstrapComplete, readSoulProfile, writeSoulProfile } from './soul.js'
|
|
112
113
|
import {
|
|
113
114
|
MEMORY_SKILL_NAME,
|
|
114
115
|
MEMORY_SKILL_DESCRIPTION,
|
|
@@ -131,6 +132,9 @@ export const CONTROL_ROUTE_PATH = '/api/memory/control'
|
|
|
131
132
|
/** Per-session memory gate: GET the state, POST a toggle. */
|
|
132
133
|
export const SESSION_ROUTE_PATH = '/api/memory/session'
|
|
133
134
|
|
|
135
|
+
/** Basic soul profile (managed SOUL.md block): GET the fields, POST a save. */
|
|
136
|
+
export const SOUL_ROUTE_PATH = '/api/memory/soul'
|
|
137
|
+
|
|
134
138
|
export const inject = ['systemPrompt', 'skills', 'agents']
|
|
135
139
|
|
|
136
140
|
/** Schemastery schema applied to the plugin config before startup. */
|
|
@@ -779,6 +783,61 @@ export function apply(ctx, config = {}) {
|
|
|
779
783
|
webCtx.effect(() => disposeSessionRoute, 'memory.session-route()')
|
|
780
784
|
ctx.logger?.info(`memory: session route at ${SESSION_ROUTE_PATH}`)
|
|
781
785
|
|
|
786
|
+
// Basic soul profile: the Settings panel's card edits three fields inside
|
|
787
|
+
// SOUL.md's managed block. Saving also marks BOOTSTRAP complete, so a user
|
|
788
|
+
// who never chats about their soul stops seeing the forging nudge.
|
|
789
|
+
const disposeSoulRoute = webCtx.webServer.register({
|
|
790
|
+
kind: 'exact',
|
|
791
|
+
path: SOUL_ROUTE_PATH,
|
|
792
|
+
handler: async (req, res) => {
|
|
793
|
+
try {
|
|
794
|
+
const sendJson = (status, payload) => {
|
|
795
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
|
796
|
+
res.end(JSON.stringify(payload))
|
|
797
|
+
}
|
|
798
|
+
if (req.method === 'GET') {
|
|
799
|
+
sendJson(200, {
|
|
800
|
+
ok: true,
|
|
801
|
+
profile: readSoulProfile(currentMemoryDir),
|
|
802
|
+
bootstrapStatus: readBootstrapStatus(currentMemoryDir),
|
|
803
|
+
needsBootstrap: needsSoulBootstrap(currentMemoryDir),
|
|
804
|
+
})
|
|
805
|
+
return
|
|
806
|
+
}
|
|
807
|
+
if (req.method === 'POST') {
|
|
808
|
+
const chunks = []
|
|
809
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
810
|
+
let body
|
|
811
|
+
try {
|
|
812
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
|
|
813
|
+
} catch {
|
|
814
|
+
sendJson(400, { error: 'body must be JSON' })
|
|
815
|
+
return
|
|
816
|
+
}
|
|
817
|
+
const profile = writeSoulProfile(currentMemoryDir, {
|
|
818
|
+
agentName: body?.agentName,
|
|
819
|
+
userName: body?.userName,
|
|
820
|
+
summary: body?.summary,
|
|
821
|
+
})
|
|
822
|
+
const bootstrapChanged = markBootstrapComplete(currentMemoryDir)
|
|
823
|
+
sendJson(200, {
|
|
824
|
+
ok: true,
|
|
825
|
+
profile,
|
|
826
|
+
bootstrapChanged,
|
|
827
|
+
bootstrapStatus: readBootstrapStatus(currentMemoryDir),
|
|
828
|
+
})
|
|
829
|
+
return
|
|
830
|
+
}
|
|
831
|
+
sendJson(405, { error: 'method not allowed' })
|
|
832
|
+
} catch (error) {
|
|
833
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
834
|
+
res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))
|
|
835
|
+
}
|
|
836
|
+
},
|
|
837
|
+
})
|
|
838
|
+
webCtx.effect(() => disposeSoulRoute, 'memory.soul-route()')
|
|
839
|
+
ctx.logger?.info(`memory: soul route at ${SOUL_ROUTE_PATH}`)
|
|
840
|
+
|
|
782
841
|
// Read-only health dashboard payload. Built fresh on every request from the
|
|
783
842
|
// store on disk, so the panel always reflects the newest state and the
|
|
784
843
|
// plugin never caches a stale view of the user's memory.
|
package/lib/soul.js
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Soul profile: the three fields the Settings panel can edit without a
|
|
3
|
+
* conversation — who the agent is called, what to call the user, and a short
|
|
4
|
+
* baseline persona. They live in a **managed block** inside `SOUL.md`, so the
|
|
5
|
+
* rest of the user's hand-written soul file is never touched.
|
|
6
|
+
*
|
|
7
|
+
* Why a managed block instead of rewriting the template placeholders:
|
|
8
|
+
* `SOUL.md` is user-owned prose. Matching template lines is brittle (users edit
|
|
9
|
+
* it), while a fenced block is idempotent, visible, and trivially migratable.
|
|
10
|
+
*
|
|
11
|
+
* The block is the source of truth for "basic soul is done": once all three
|
|
12
|
+
* fields are set, the boot block stops nagging for soul-forging even if the
|
|
13
|
+
* template's `_(铸魂对话中确认)_` placeholders are still lying around (those
|
|
14
|
+
* lines are filtered out of the injected copy, not out of the file).
|
|
15
|
+
*
|
|
16
|
+
* Pure Node builtins; no host packages.
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-plugin-memory/soul
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
22
|
+
import { join } from 'node:path'
|
|
23
|
+
|
|
24
|
+
/** Opening marker of the managed block. */
|
|
25
|
+
export const SOUL_PROFILE_START = '<!-- dsh-memory:soul:start -->'
|
|
26
|
+
|
|
27
|
+
/** Closing marker of the managed block. */
|
|
28
|
+
export const SOUL_PROFILE_END = '<!-- dsh-memory:soul:end -->'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Generic defaults for a brand-new user: no names, no assumptions. The panel
|
|
32
|
+
* pre-fills these so saving is one click, and they read naturally ("你") rather
|
|
33
|
+
* than pretending the agent already has a specific identity.
|
|
34
|
+
*/
|
|
35
|
+
export const DEFAULT_SOUL_PROFILE = Object.freeze({
|
|
36
|
+
agentName: '助手',
|
|
37
|
+
userName: '你',
|
|
38
|
+
summary: [
|
|
39
|
+
'直接、诚实、先结论后细节;不确定时明说,绝不编造。',
|
|
40
|
+
'语气可以轻松,偶尔自嘲,但事实、数字、结论一字不掺水。',
|
|
41
|
+
'主动指出风险与替代方案,最终决定权留给你。',
|
|
42
|
+
].join('\n'),
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
/** Max characters for either name. */
|
|
46
|
+
export const SOUL_NAME_MAX = 64
|
|
47
|
+
|
|
48
|
+
/** Max characters for the baseline persona description. */
|
|
49
|
+
export const SOUL_SUMMARY_MAX = 2000
|
|
50
|
+
|
|
51
|
+
const PLACEHOLDER = '(铸魂对话中确认)'
|
|
52
|
+
|
|
53
|
+
const trim = (value) => (typeof value === 'string' ? value.trim() : '')
|
|
54
|
+
|
|
55
|
+
/** Extract the managed block body, or `undefined` when absent/malformed. */
|
|
56
|
+
function extractBlock(text) {
|
|
57
|
+
const start = text.indexOf(SOUL_PROFILE_START)
|
|
58
|
+
if (start === -1) return undefined
|
|
59
|
+
const end = text.indexOf(SOUL_PROFILE_END, start)
|
|
60
|
+
if (end === -1) return undefined
|
|
61
|
+
return text.slice(start + SOUL_PROFILE_START.length, end)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Read one `- **label**:value` field from the block body. The persona field
|
|
66
|
+
* may wrap onto continuation lines indented by two spaces (markdown list
|
|
67
|
+
* continuation), so a multi-line description survives the round trip.
|
|
68
|
+
*/
|
|
69
|
+
function blockField(block, label) {
|
|
70
|
+
const prefix = `- **${label}**:`
|
|
71
|
+
const lines = block.split('\n')
|
|
72
|
+
const start = lines.findIndex((line) => line.startsWith(prefix))
|
|
73
|
+
if (start === -1) return ''
|
|
74
|
+
const out = [lines[start].slice(prefix.length).trim()]
|
|
75
|
+
for (let index = start + 1; index < lines.length; index += 1) {
|
|
76
|
+
const line = lines[index]
|
|
77
|
+
if (!line.startsWith(' ')) break
|
|
78
|
+
out.push(line.slice(2).trimEnd())
|
|
79
|
+
}
|
|
80
|
+
return out.filter((line) => line.length > 0).join('\n').trim()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Echo the profile a legacy SOUL.md already states (forged in chat, no managed
|
|
85
|
+
* block). Common shapes from this plugin's own template and conversations:
|
|
86
|
+
* - **名字**:小蓝。
|
|
87
|
+
* - **角色**:……
|
|
88
|
+
* - **相互称呼**:阿周 ↔ 小蓝。
|
|
89
|
+
* Values that are still placeholders are ignored.
|
|
90
|
+
*/
|
|
91
|
+
function readLegacySoul(text) {
|
|
92
|
+
const clean = (value) => {
|
|
93
|
+
if (typeof value !== 'string') return ''
|
|
94
|
+
const trimmed = value.trim().replace(/[。..,,;;]+$/u, '').trim()
|
|
95
|
+
if (trimmed.length === 0 || trimmed.includes(PLACEHOLDER)) return ''
|
|
96
|
+
return trimmed
|
|
97
|
+
}
|
|
98
|
+
const lineValue = (label) => {
|
|
99
|
+
const match = new RegExp(`^- \\*\\*${label}\\*\\*:(.*)$`, 'm').exec(text)
|
|
100
|
+
return clean(match ? match[1] : '')
|
|
101
|
+
}
|
|
102
|
+
const name = lineValue('名字')
|
|
103
|
+
const role = lineValue('角色')
|
|
104
|
+
const mutual = lineValue('相互称呼')
|
|
105
|
+
let userName = ''
|
|
106
|
+
if (mutual.length > 0) {
|
|
107
|
+
const parts = mutual.split(/\s*(?:↔|<->|⇄)\s*/u).map((part) => part.trim()).filter(Boolean)
|
|
108
|
+
userName = parts.length >= 2 ? parts[0] : mutual
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
agentName: name || DEFAULT_SOUL_PROFILE.agentName,
|
|
112
|
+
userName: userName || DEFAULT_SOUL_PROFILE.userName,
|
|
113
|
+
summary: (role || DEFAULT_SOUL_PROFILE.summary).slice(0, SOUL_SUMMARY_MAX),
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Read the soul profile.
|
|
119
|
+
*
|
|
120
|
+
* With a managed block, the block wins. Without one (a store forged in chat),
|
|
121
|
+
* the fields the SOUL already states are echoed back so the panel never claims
|
|
122
|
+
* "not forged yet" for a user who has a soul. A truly empty/placeholder store
|
|
123
|
+
* falls back to the generic defaults.
|
|
124
|
+
*
|
|
125
|
+
* @param {string} memoryDir
|
|
126
|
+
* @returns {{ agentName: string, userName: string, summary: string, managed: boolean }}
|
|
127
|
+
*/
|
|
128
|
+
export function readSoulProfile(memoryDir) {
|
|
129
|
+
let text = ''
|
|
130
|
+
try {
|
|
131
|
+
text = readFileSync(join(memoryDir, 'SOUL.md'), 'utf8')
|
|
132
|
+
} catch {
|
|
133
|
+
text = ''
|
|
134
|
+
}
|
|
135
|
+
const block = extractBlock(text)
|
|
136
|
+
if (block === undefined) {
|
|
137
|
+
return { ...readLegacySoul(text), managed: false }
|
|
138
|
+
}
|
|
139
|
+
const agentName = blockField(block, '我的名字')
|
|
140
|
+
const userName = blockField(block, '你的称呼')
|
|
141
|
+
const summary = blockField(block, '基础灵魂描述')
|
|
142
|
+
return {
|
|
143
|
+
agentName: agentName || DEFAULT_SOUL_PROFILE.agentName,
|
|
144
|
+
userName: userName || DEFAULT_SOUL_PROFILE.userName,
|
|
145
|
+
summary: summary || DEFAULT_SOUL_PROFILE.summary,
|
|
146
|
+
managed: agentName.length > 0 && userName.length > 0 && summary.length > 0,
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Whether the basic soul has been set from the Settings panel.
|
|
152
|
+
* @param {string} memoryDir
|
|
153
|
+
* @returns {boolean}
|
|
154
|
+
*/
|
|
155
|
+
export function hasManagedSoulProfile(memoryDir) {
|
|
156
|
+
return readSoulProfile(memoryDir).managed === true
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Render the managed block. Multi-line descriptions use two-space
|
|
160
|
+
* continuation lines so the block stays valid markdown and round-trips. */
|
|
161
|
+
function renderBlock({ agentName, userName, summary }) {
|
|
162
|
+
const summaryMarkdown = String(summary)
|
|
163
|
+
.split('\n')
|
|
164
|
+
.map((line, index) => (index === 0 ? line : ` ${line}`))
|
|
165
|
+
.join('\n')
|
|
166
|
+
return `${SOUL_PROFILE_START}
|
|
167
|
+
## 人格基础(设置页维护,可手改)
|
|
168
|
+
|
|
169
|
+
- **我的名字**:${agentName}
|
|
170
|
+
- **你的称呼**:${userName}
|
|
171
|
+
- **基础灵魂描述**:${summaryMarkdown}
|
|
172
|
+
${SOUL_PROFILE_END}`
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Insert the block after the title line (never before frontmatter), or replace
|
|
177
|
+
* an existing one. Everything else in the file is preserved verbatim.
|
|
178
|
+
*/
|
|
179
|
+
function replaceOrInsert(text, block) {
|
|
180
|
+
const start = text.indexOf(SOUL_PROFILE_START)
|
|
181
|
+
if (start !== -1) {
|
|
182
|
+
const end = text.indexOf(SOUL_PROFILE_END, start)
|
|
183
|
+
if (end !== -1) {
|
|
184
|
+
return text.slice(0, start) + block + text.slice(end + SOUL_PROFILE_END.length)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const lines = text.split('\n')
|
|
188
|
+
let insertAt = 0
|
|
189
|
+
if (lines[0]?.trim() === '---') {
|
|
190
|
+
// Skip the YAML frontmatter if present.
|
|
191
|
+
const endIndex = lines.findIndex((line, index) => index > 0 && line.trim() === '---')
|
|
192
|
+
insertAt = endIndex === -1 ? 0 : endIndex + 1
|
|
193
|
+
}
|
|
194
|
+
const titleIndex = lines.findIndex((line, index) => index >= insertAt && line.startsWith('# '))
|
|
195
|
+
if (titleIndex !== -1) insertAt = titleIndex + 1
|
|
196
|
+
const before = lines.slice(0, insertAt).join('\n')
|
|
197
|
+
const after = lines.slice(insertAt).join('\n')
|
|
198
|
+
return `${before}\n\n${block}\n${after.startsWith('\n') ? '' : '\n'}${after}`
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Write the soul profile into the managed block (atomic).
|
|
203
|
+
*
|
|
204
|
+
* @param {string} memoryDir
|
|
205
|
+
* @param {{ agentName?: string, userName?: string, summary?: string }} profile
|
|
206
|
+
* @returns {{ agentName: string, userName: string, summary: string, managed: true }}
|
|
207
|
+
*/
|
|
208
|
+
export function writeSoulProfile(memoryDir, profile = {}) {
|
|
209
|
+
const agentName = trim(profile.agentName)
|
|
210
|
+
const userName = trim(profile.userName)
|
|
211
|
+
const summary = trim(profile.summary)
|
|
212
|
+
if (agentName.length === 0) throw new Error('agentName must be a non-empty string')
|
|
213
|
+
if (agentName.length > SOUL_NAME_MAX) throw new Error(`agentName must be at most ${SOUL_NAME_MAX} characters`)
|
|
214
|
+
if (userName.length > SOUL_NAME_MAX) throw new Error(`userName must be at most ${SOUL_NAME_MAX} characters`)
|
|
215
|
+
if (summary.length === 0) throw new Error('summary must be a non-empty string')
|
|
216
|
+
if (summary.length > SOUL_SUMMARY_MAX) throw new Error(`summary must be at most ${SOUL_SUMMARY_MAX} characters`)
|
|
217
|
+
|
|
218
|
+
const path = join(memoryDir, 'SOUL.md')
|
|
219
|
+
let text
|
|
220
|
+
try {
|
|
221
|
+
text = readFileSync(path, 'utf8')
|
|
222
|
+
} catch {
|
|
223
|
+
throw new Error('SOUL.md not found (run the memory scaffold first)')
|
|
224
|
+
}
|
|
225
|
+
const updated = replaceOrInsert(text, renderBlock({ agentName, userName, summary }))
|
|
226
|
+
const tmp = `${path}.tmp`
|
|
227
|
+
writeFileSync(tmp, updated, 'utf8')
|
|
228
|
+
renameSync(tmp, path)
|
|
229
|
+
return { agentName, userName, summary, managed: true }
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Flip `status: pending` to `status: complete` in BOOTSTRAP.md.
|
|
234
|
+
*
|
|
235
|
+
* @param {string} memoryDir
|
|
236
|
+
* @returns {boolean} whether the file changed
|
|
237
|
+
*/
|
|
238
|
+
export function markBootstrapComplete(memoryDir) {
|
|
239
|
+
const path = join(memoryDir, 'BOOTSTRAP.md')
|
|
240
|
+
if (!existsSync(path)) return false
|
|
241
|
+
let text
|
|
242
|
+
try {
|
|
243
|
+
text = readFileSync(path, 'utf8')
|
|
244
|
+
} catch {
|
|
245
|
+
return false
|
|
246
|
+
}
|
|
247
|
+
if (/^status:\s*complete\s*$/m.test(text)) return false
|
|
248
|
+
const updated = /^status:\s*\S+/m.test(text)
|
|
249
|
+
? text.replace(/^status:\s*\S+/m, 'status: complete')
|
|
250
|
+
: `---\nstatus: complete\n---\n\n${text}`
|
|
251
|
+
const tmp = `${path}.tmp`
|
|
252
|
+
writeFileSync(tmp, updated, 'utf8')
|
|
253
|
+
renameSync(tmp, path)
|
|
254
|
+
return true
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Remove `_(铸魂对话中确认)_` placeholder lines from the **injected** copy of
|
|
259
|
+
* SOUL.md. The file itself keeps them (the user or a later conversation may
|
|
260
|
+
* still fill the detailed sections in).
|
|
261
|
+
*
|
|
262
|
+
* @param {string} text
|
|
263
|
+
* @returns {string}
|
|
264
|
+
*/
|
|
265
|
+
export function filterBootstrapPlaceholders(text) {
|
|
266
|
+
if (typeof text !== 'string' || text.length === 0) return text
|
|
267
|
+
return text.split('\n').filter((line) => !line.includes(PLACEHOLDER)).join('\n')
|
|
268
|
+
}
|
package/lib/types/index.d.ts
CHANGED
|
@@ -107,6 +107,9 @@ export const CONTROL_ROUTE_PATH: '/api/memory/control'
|
|
|
107
107
|
/** Per-session memory gate: read state (GET) / toggle it (POST). */
|
|
108
108
|
export const SESSION_ROUTE_PATH: '/api/memory/session'
|
|
109
109
|
|
|
110
|
+
/** Basic soul profile (managed SOUL.md block): read fields (GET) / save (POST). */
|
|
111
|
+
export const SOUL_ROUTE_PATH: '/api/memory/soul'
|
|
112
|
+
|
|
110
113
|
/** User-editable settings (composition config is the base layer). */
|
|
111
114
|
export interface MemorySettings {
|
|
112
115
|
enabled?: boolean
|
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.
|
|
4
|
+
"version": "0.15.1",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|