dsh-plugin-memory 0.13.2 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +5 -1
- package/README.zh.md +5 -1
- package/lib/activity-tracker.js +16 -0
- package/lib/boot.js +25 -9
- package/lib/client.js +331 -0
- package/lib/config-store.js +4 -1
- package/lib/index.js +184 -4
- package/lib/schema.js +3 -0
- package/lib/session-gate.js +231 -0
- package/lib/types/index.d.ts +14 -0
- package/package.json +1 -1
- package/skills/memory.md +1 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,36 @@
|
|
|
2
2
|
|
|
3
3
|
所有记录跟随 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 风格;版本号与 `package.json` 保持一致。
|
|
4
4
|
|
|
5
|
+
## [0.14.0] - 2026-11-04
|
|
6
|
+
|
|
7
|
+
### Added(0.14.0:会话级记忆开关)
|
|
8
|
+
|
|
9
|
+
- **按会话开关**:`/memory on|off|status`(宿主命令面,自动进 `/` 与 `+` 菜单)、输入框工具行左侧的 chip(`conversation.input.left`)、设置面板「会话与工作区」三处共用同一个 gate:关闭后**本会话不注入 boot 块、不发 digest/追忆提醒、不盖 `last_access`**(记忆文件不删、其它会话不受影响)。
|
|
10
|
+
- **工作区默认关**:`disabledWorkspaces`(按会话 cwd、`~` 展开、路径边界匹配);会话级 override 优先于工作区默认;面板「此工作区默认关闭」用当前活跃会话的 cwd 写入。
|
|
11
|
+
- **会话状态持久化**:`<dshHome>/memory-sessions.json`(`sessionStateFile` / `sessionTtlDays: 7`),恢复的会话保持选择,过期条目自动清理。
|
|
12
|
+
- 新 HTTP 路由 `GET/POST /api/memory/session`(GET 读状态、POST 切换;缺 sessionId 时回退到活跃会话);`ActivityTracker.activeId()`;新模块 `lib/session-gate.js`(纯 Node,可单测)。
|
|
13
|
+
- **chip 形态(当日调整)**:输入框左侧 chip 从「点击盲切」改为**下拉菜单**——「本会话 开/关」与「此工作区默认 开/关」两组单选,Host 拒绝/读不到状态时在菜单里显示原因;图标由 🧠 emoji 换成与设置侧栏同源的 14px brain-circuit SVG。
|
|
14
|
+
- 边界(文档已写清):`memory` 技能仍全局注册,宿主无法按会话停技能;关闭后 agent 上下文里没有记忆协议。
|
|
15
|
+
|
|
16
|
+
### Tests
|
|
17
|
+
|
|
18
|
+
- `session-gate` 11 条(默认 / 会话 override / 工作区默认 / 优先级 / TTL / 持久化 / 路径边界 / 损坏文件 / toggle);`session-control` 6 条集成(命令面、路由、boot 门控、活跃会话回退);`session-ui` 4 条客户端渲染(chip 两态、英文文案、面板加载态、路由常量);更新 `plugin-metadata`(commands 可选注入 + 新配置字段)与 `client-i18n`(chip slot 声明)。
|
|
19
|
+
- 全量 **283/283**(0.13.3 基线 262 + 21);`npm test` self-test PASS。
|
|
20
|
+
|
|
21
|
+
## [0.13.3] - 2026-11-02
|
|
22
|
+
|
|
23
|
+
### Fixed(boot 预算单位:字节 vs 字符)
|
|
24
|
+
|
|
25
|
+
- **中文 / 日文 / 韩文记忆库的 boot 文件被系统性低估预算**:`allocateBootBudget()` 用 `statSync().size`(UTF-8 字节)判断文件大小,`readCapped()` 却按字符 `slice()` 截断。中文 1 字 = 3 字节,于是每个 CJK 文件都被判成「超过均分额度」,cap 被抬到 `total/3`,pool 提前耗尽、短文件退回的余量永远不回流,真正长的文件被无谓截断。实测(12000 预算、`字` 每字 3 字节):6000 字符的 SOUL 被截到 4000,而此时预算还有 2000 字符空闲。
|
|
26
|
+
- 修复:`sizeOf()` 改为读取内容取 `.length`(字符),与 `readCapped` 及全仓其它口径(insights / checkup / doctor 均按字符)统一;同一 `allocateBootBudget()` 调用内缓存尺寸,读盘次数不增加量级。
|
|
27
|
+
- 影响面:英文库 1 字节 ≈ 1 字符,行为不变;CJK 库恢复按字符分配,短文件退回的余量可以回流给真正长的文件。
|
|
28
|
+
- **不变的部分**:`readCapped` 的截断提示、`renderBootBlock` 的总量兜底、`readTailCapped`(log)本来就是字符口径,未改动。
|
|
29
|
+
|
|
30
|
+
### Tests
|
|
31
|
+
|
|
32
|
+
- `boot-budget` 新增 2 条 CJK 用例:`字` × 6000/1000/3000(长文件拿到回流、不截断);用户报告形状 `字` × 2141/3979/2744(短文件不再虚高吃 pool)。
|
|
33
|
+
- 全量 **262/262 通过**(0.13.2 基线 260 + 2);`node scripts/memory.mjs --self-test` PASS。
|
|
34
|
+
|
|
5
35
|
## [0.13.2] - 2026-10-30
|
|
6
36
|
|
|
7
37
|
### Fixed(reviewer 复核尾巴 + 结构修正)
|
package/README.md
CHANGED
|
@@ -34,6 +34,7 @@ After that the loop is simple: the agent writes memories back as you work, and y
|
|
|
34
34
|
## Features
|
|
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
|
+
- **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.
|
|
37
38
|
- **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.
|
|
38
39
|
- **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.
|
|
39
40
|
- **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.
|
|
@@ -136,6 +137,9 @@ Restart the profile (restart the DSH Desktop app) to take effect.
|
|
|
136
137
|
| `toneIntensity` | `low` | `low` / `medium` / `off` (pure engineering voice) |
|
|
137
138
|
| `growthRecapEnabled` | `true` | Weekly growth recap on the recall channel |
|
|
138
139
|
| `growthRecapIntervalDays` | `7` | Days between growth recaps |
|
|
140
|
+
| `disabledWorkspaces` | `[]` | Workspaces (session cwd, `~` expanded, path-boundary match) that default to memory **off**; a per-session override still wins; hot-editable |
|
|
141
|
+
| `sessionStateFile` | `<dshHome>/memory-sessions.json` | Where per-session overrides live (composition) |
|
|
142
|
+
| `sessionTtlDays` | `7` | Days a session override stays valid before it is pruned (composition) |
|
|
139
143
|
| `autoCommit` | `true` | Git auto-commit switch for the store (composition) |
|
|
140
144
|
| `autoCommitQuietSeconds` | `60` | How long changes must be quiet before committing (debounce) |
|
|
141
145
|
| `autoCommitIntervalSeconds` | `60` | Change polling interval |
|
|
@@ -144,7 +148,7 @@ Restart the profile (restart the DSH Desktop app) to take effect.
|
|
|
144
148
|
|
|
145
149
|
The section is registered as **"Memory"** in the English UI and **「记忆」** in the Chinese UI — it follows DSH's own language setting (see [Language](#language) below).
|
|
146
150
|
|
|
147
|
-
|
|
151
|
+
Sixteen settings are editable in the "Memory" section of the DSH settings page and take effect **immediately**: `enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` / `proactiveCooldownSeconds` / `toneGuideEnabled` / `toneIntensity` / `growthRecapEnabled` / `growthRecapIntervalDays` / `disabledWorkspaces` — boot injection, the two polite gates, skill registration, proactive recall (including its random interval and cap), speech-right arbitration, the tone section, the weekly growth recap and the per-session switch all follow the change at once; switching the store directory scaffolds the new one automatically (when `scaffold: true`). The remaining keys (`bootFiles` / `bootMaxChars` / `bootFileBudgets` / `trackPageAccess` / `scaffold` / `configFile` / `sessionStateFile` / `sessionTtlDays` / `digestNudge*` / `autoCommit*`) only apply at the composition layer and need a restart.
|
|
148
152
|
|
|
149
153
|
A **Review now** button sits beside them: it is a **control, not a setting** — it asks the plugin to send one growth recap immediately. It still respects the speech floor (it backs off if the other plugin is speaking), sends nothing when this week has no new material, works even while `recallEnabled` is off, and reports the outcome in the panel (sending / sent / deferred / session busy / no content / disabled / failed) — the result notice clears itself after 5 seconds.
|
|
150
154
|
|
package/README.zh.md
CHANGED
|
@@ -34,6 +34,7 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
34
34
|
## 特性
|
|
35
35
|
|
|
36
36
|
- **开机强制注入(带路由表保护)**:插件通过 `ctx.systemPrompt.context()` 把记忆 boot 块(`SOUL.md` 人格 + `MEMORY.md` 协议 + `index.md` 目录 + 最近动态)注入会话上下文。宿主按投影去重:记忆不变就不重复注入,变化时新快照自动取代旧的——这是"新会话必先加载记忆"的**硬保障**,不需要模型碰运气调技能。总预算是 `bootMaxChars`,**按文件分配**:每个文件先拿一份均分(受实际大小封顶),剩余额度优先给 `index.md`、再给尚有内容未注入的文件——所以记忆库长大时,目录的尾部不会先被截掉(详见「boot 预算分配」)。默认还带**两道礼貌闸门**:`deferUntilUserSpeaks`(用户开口后才注入)与 `activeSessionOnly`(只注入当前激活会话),见「配置」。
|
|
37
|
+
- **按会话开关(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 上下文里没有记忆协议——这个边界在文档里写清。
|
|
37
38
|
- **last_access 自动戳记**:`MEMORY.md` 的 salience 衰减规则依赖 `last_access`,而它以前纯粹靠自觉——模板里有字段、规则里提到它,但没有任何代码去写它,于是每个页面都原地变老、衰减表形同虚设。现在会话收到第一条真实用户消息时,插件会把 boot 块**实际注入过的页面**(`SOUL.md` / `MEMORY.md` / `index.md` + 目录里被引用到的页)戳成当天,每会话一次、按天幂等,只改 `last_access` 一行;`dsh-memory touch <pages...>` 可手动补记,`trackPageAccess: false` 可关闭。
|
|
38
39
|
- **SOUL.md 铸魂**:安装后首要任务是和用户对话定义灵魂(名字、性格、价值观、语气、边界)、确认身份与关系(`BOOTSTRAP.md` 清单驱动,complete 前优先于常规任务)。
|
|
39
40
|
- **铸魂自动引导**:记忆库还没有灵魂(`BOOTSTRAP.md` 非 complete,或 `SOUL.md` 仍是占位模板)时,boot 块会自动前置一段第一人称引导词——「我的首要任务是确认我是谁,还有你是谁:我叫什么名字、怎么称呼你、你我是什么关系、我该是什么样的性格」——像 OpenClaw 初始化那样,**由 agent 在对话里主动发起铸魂**,逐项问、逐项写回,而不是等用户来喂。铸魂完成后引导词自动消失,零开销。
|
|
@@ -144,13 +145,16 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
144
145
|
| `toneIntensity` | `low` | `low` / `medium` / `off`(off = 纯工程师语气) |
|
|
145
146
|
| `growthRecapEnabled` | `true` | 每周成长回顾(走 recall 通道) |
|
|
146
147
|
| `growthRecapIntervalDays` | `7` | 两次成长回顾间隔天数 |
|
|
148
|
+
| `disabledWorkspaces` | `[]` | 默认关闭记忆的工作区(按会话 cwd、`~` 展开、路径边界匹配);会话级 override 仍然优先;面板可热改 |
|
|
149
|
+
| `sessionStateFile` | `<dshHome>/memory-sessions.json` | 会话级 override 的落盘位置(composition) |
|
|
150
|
+
| `sessionTtlDays` | `7` | 会话 override 的有效天数,过期清理(composition) |
|
|
147
151
|
| `autoCommit` | `true` | 记忆库 git 自动提交开关(composition) |
|
|
148
152
|
| `autoCommitQuietSeconds` | `60` | 变更静默多久后提交(防抖) |
|
|
149
153
|
| `autoCommitIntervalSeconds` | `60` | 变更轮询间隔 |
|
|
150
154
|
|
|
151
155
|
### 设置面板(热改)
|
|
152
156
|
|
|
153
|
-
`enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` / `proactiveCooldownSeconds` / `toneGuideEnabled` / `toneIntensity` / `growthRecapEnabled` / `growthRecapIntervalDays`
|
|
157
|
+
`enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` / `proactiveCooldownSeconds` / `toneGuideEnabled` / `toneIntensity` / `growthRecapEnabled` / `growthRecapIntervalDays` / `disabledWorkspaces` 十六项在 DSH 设置页的「记忆 / Memory」区块中可改(跟随语言),**即时生效**:boot 注入、两道礼貌闸门、技能注册、主动追忆(含随机间隔与次数)、发言权仲裁、语气段、每周成长回顾与会话级开关随修改立即生效;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `bootFileBudgets` / `trackPageAccess` / `scaffold` / `configFile` / `sessionStateFile` / `sessionTtlDays` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
|
|
154
158
|
|
|
155
159
|
旁边还有一个 **「立即回顾」按钮**:它是**控制动作,不是配置项**——让插件立刻发一次成长回顾。仍尊重发言权仲裁(别的插件在说话就让位)、本周没有新内容就不发、即使 `recallEnabled` 关闭也能用,并在面板里给出结果(回顾中 / 已发送 / 让位 / 会话正忙 / 没有新内容 / 已关闭 / 失败),结果提示 5 秒后自动消失。
|
|
156
160
|
|
package/lib/activity-tracker.js
CHANGED
|
@@ -95,6 +95,22 @@ export class ActivityTracker {
|
|
|
95
95
|
return winner === id
|
|
96
96
|
}
|
|
97
97
|
|
|
98
|
+
/** The live agent that most recently received a real user message, or
|
|
99
|
+
* `undefined` when nobody has spoken yet. */
|
|
100
|
+
activeId() {
|
|
101
|
+
let winner
|
|
102
|
+
let latest = 0
|
|
103
|
+
for (const [id, state] of this.states) {
|
|
104
|
+
if (!state.hasUserSpoken) continue
|
|
105
|
+
if (this.agents && this.agents.get(id) === undefined) continue
|
|
106
|
+
if (state.lastUserSeq > latest) {
|
|
107
|
+
latest = state.lastUserSeq
|
|
108
|
+
winner = id
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return winner
|
|
112
|
+
}
|
|
113
|
+
|
|
98
114
|
/**
|
|
99
115
|
* Fold the two gates + config toggles into one predicate. With both toggles
|
|
100
116
|
* off, always inject (backward compatible).
|
package/lib/boot.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* @module dsh-plugin-memory/boot
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import { existsSync, readFileSync
|
|
14
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
15
15
|
import { join } from 'node:path'
|
|
16
16
|
|
|
17
17
|
/** Files injected at session start when the config does not override them. */
|
|
@@ -92,8 +92,14 @@ export function parseLogEntries(logText, count = 5) {
|
|
|
92
92
|
* twice the even share each): `index.md` first, then by size, so
|
|
93
93
|
* truncation lands on bulky files no matter their order in `bootFiles`.
|
|
94
94
|
*
|
|
95
|
-
* While every file fits inside its even share this is
|
|
96
|
-
* behaviour; it only starts to differ once the store outgrows its share.
|
|
95
|
+
* While every file fits inside its even share this is character-for-character
|
|
96
|
+
* the old behaviour; it only starts to differ once the store outgrows its share.
|
|
97
|
+
*
|
|
98
|
+
* Budgets are expressed in **characters**, matching `readCapped` (`String.slice`)
|
|
99
|
+
* and every other size in the plugin. Sizing the files by `statSync().size` was
|
|
100
|
+
* a unit mismatch: a CJK file is ~3 UTF-8 bytes per character, so it looked 3x
|
|
101
|
+
* longer than it is, got capped at the even share, and the pool was spent before
|
|
102
|
+
* the surplus could flow back to the file that was actually long.
|
|
97
103
|
*
|
|
98
104
|
* @param {string} memoryDir absolute path of the memory store
|
|
99
105
|
* @param {{ files?: string[], total?: number, perFile?: Record<string, number> }} [options]
|
|
@@ -102,13 +108,23 @@ export function parseLogEntries(logText, count = 5) {
|
|
|
102
108
|
export function allocateBootBudget(memoryDir, options = {}) {
|
|
103
109
|
const files = (options.files ?? []).filter((f) => typeof f === 'string' && f.length > 0)
|
|
104
110
|
const total = Math.max(512, Number(options.total) || 6000)
|
|
105
|
-
const sizeOf = (
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
111
|
+
const sizeOf = (() => {
|
|
112
|
+
const sizes = new Map()
|
|
113
|
+
return (fileName) => {
|
|
114
|
+
if (sizes.has(fileName)) return sizes.get(fileName)
|
|
115
|
+
let chars = 0
|
|
116
|
+
try {
|
|
117
|
+
// Characters, not bytes: caps are consumed by readCapped, which slices
|
|
118
|
+
// a UTF-16 string. A CJK file is ~3 bytes per character, so counting
|
|
119
|
+
// bytes would overstate it ~3x and starve the leftover pool.
|
|
120
|
+
chars = readFileSync(join(memoryDir, fileName), 'utf8').length
|
|
121
|
+
} catch {
|
|
122
|
+
chars = 0
|
|
123
|
+
}
|
|
124
|
+
sizes.set(fileName, chars)
|
|
125
|
+
return chars
|
|
110
126
|
}
|
|
111
|
-
}
|
|
127
|
+
})()
|
|
112
128
|
|
|
113
129
|
const caps = new Map(files.map((f) => [f, 0]))
|
|
114
130
|
const explicit = options.perFile ?? {}
|
package/lib/client.js
CHANGED
|
@@ -21,6 +21,8 @@ window.__ModuleLoader__.load({
|
|
|
21
21
|
const CONTROL_URL = '/api/memory/control'
|
|
22
22
|
const INSIGHTS_URL = '/api/memory/insights'
|
|
23
23
|
const GRAPH_URL = '/api/memory/graph'
|
|
24
|
+
/** Per-session gate: the panel and the composer chip share this route. */
|
|
25
|
+
const SESSION_URL = '/api/memory/session'
|
|
24
26
|
/** Poll while the panel is open, so memory edits show up without a reload. */
|
|
25
27
|
const GRAPH_REFRESH_MS = 25000
|
|
26
28
|
|
|
@@ -83,6 +85,25 @@ window.__ModuleLoader__.load({
|
|
|
83
85
|
growthNowFailed: '回顾失败:',
|
|
84
86
|
growthNowError: '回顾失败',
|
|
85
87
|
growthNowNoSession: '没有活跃会话可回顾',
|
|
88
|
+
sessionSection: '会话与工作区',
|
|
89
|
+
sessionSectionHint: '记忆开关按会话生效:关闭后本会话不注入记忆、不提醒、不盖 last_access(记忆文件不会删)。',
|
|
90
|
+
sessionCurrent: '当前会话记忆',
|
|
91
|
+
sessionCurrentHint: '只影响当前会话;输入框旁的 chip 与 /memory off 效果相同',
|
|
92
|
+
sessionWorkspace: '此工作区默认关闭',
|
|
93
|
+
sessionWorkspaceHint: '以当前会话的工作目录为准,之后该目录下的新会话默认不记记忆',
|
|
94
|
+
sessionNoActive: '还没有活跃会话:先在任意会话里说句话,这里才能读出当前会话',
|
|
95
|
+
sessionFailed: '操作失败,稍后再试:',
|
|
96
|
+
sessionLoading: '读取会话状态中…',
|
|
97
|
+
chipOn: '记忆开',
|
|
98
|
+
chipOff: '记忆关',
|
|
99
|
+
chipHint: '点击选择记忆范围(也可用 /memory on|off)',
|
|
100
|
+
chipMenuSession: '本会话',
|
|
101
|
+
chipMenuWorkspace: '此工作区默认',
|
|
102
|
+
chipMenuOn: '开',
|
|
103
|
+
chipMenuOff: '关',
|
|
104
|
+
chipMenuTitle: '记忆范围',
|
|
105
|
+
chipMenuUnavailable: '暂时读不到会话状态',
|
|
106
|
+
chipMenuFailed: '操作失败:',
|
|
86
107
|
minutesPlaceholder: '30',
|
|
87
108
|
maxMinutesPlaceholder: '240',
|
|
88
109
|
maxPerSessionPlaceholder: '3',
|
|
@@ -193,6 +214,25 @@ window.__ModuleLoader__.load({
|
|
|
193
214
|
growthNowFailed: 'Recap failed: ',
|
|
194
215
|
growthNowError: 'Recap failed',
|
|
195
216
|
growthNowNoSession: 'No active session to recap',
|
|
217
|
+
sessionSection: 'Session & workspace',
|
|
218
|
+
sessionSectionHint: 'The memory switch is per session: off means no injection, no nudges and no last_access stamping for this session (nothing is deleted).',
|
|
219
|
+
sessionCurrent: 'Memory for this session',
|
|
220
|
+
sessionCurrentHint: 'Only affects the current session; the composer chip and /memory off do the same',
|
|
221
|
+
sessionWorkspace: 'Mute this workspace by default',
|
|
222
|
+
sessionWorkspaceHint: 'Uses the current session workspace; new sessions under this directory start muted',
|
|
223
|
+
sessionNoActive: 'No active session yet: say something in any session so the panel can read it',
|
|
224
|
+
sessionFailed: 'Something went wrong; try again: ',
|
|
225
|
+
sessionLoading: 'Reading session state…',
|
|
226
|
+
chipOn: 'Memory on',
|
|
227
|
+
chipOff: 'Memory off',
|
|
228
|
+
chipHint: 'Choose the memory scope (or /memory on|off)',
|
|
229
|
+
chipMenuSession: 'This session',
|
|
230
|
+
chipMenuWorkspace: 'Workspace default',
|
|
231
|
+
chipMenuOn: 'On',
|
|
232
|
+
chipMenuOff: 'Off',
|
|
233
|
+
chipMenuTitle: 'Memory scope',
|
|
234
|
+
chipMenuUnavailable: 'Could not read the session state',
|
|
235
|
+
chipMenuFailed: 'Action failed: ',
|
|
196
236
|
minutesPlaceholder: '30',
|
|
197
237
|
maxMinutesPlaceholder: '240',
|
|
198
238
|
maxPerSessionPlaceholder: '3',
|
|
@@ -687,6 +727,272 @@ window.__ModuleLoader__.load({
|
|
|
687
727
|
React.createElement('option', { key: option.value, value: option.value }, option.label)))
|
|
688
728
|
}
|
|
689
729
|
|
|
730
|
+
// ---------------- 会话与工作区(设置面板) ----------------
|
|
731
|
+
//
|
|
732
|
+
// 会话级记忆开关的第二个入口:设置页没有 sessionId,Host 的
|
|
733
|
+
// /api/memory/session 会用「最近发言的活跃会话」代理,所以这里读到/改到的
|
|
734
|
+
// 就是用户当前正在用的那个会话。
|
|
735
|
+
function SessionControls(props) {
|
|
736
|
+
const t = useT(props)
|
|
737
|
+
const [state, setState] = React.useState(undefined)
|
|
738
|
+
const [busy, setBusy] = React.useState(false)
|
|
739
|
+
const [error, setError] = React.useState(undefined)
|
|
740
|
+
|
|
741
|
+
React.useEffect(() => {
|
|
742
|
+
fetch(SESSION_URL)
|
|
743
|
+
.then(async (response) => {
|
|
744
|
+
if (!response.ok) throw new Error(`GET ${response.status}`)
|
|
745
|
+
return response.json()
|
|
746
|
+
})
|
|
747
|
+
.then((value) => setState(value))
|
|
748
|
+
.catch(() => setState({ ok: false, reason: 'error' }))
|
|
749
|
+
}, [])
|
|
750
|
+
|
|
751
|
+
const act = (action) => {
|
|
752
|
+
setBusy(true)
|
|
753
|
+
setError(undefined)
|
|
754
|
+
fetch(SESSION_URL, {
|
|
755
|
+
method: 'POST',
|
|
756
|
+
headers: { 'content-type': 'application/json' },
|
|
757
|
+
body: JSON.stringify({ action }),
|
|
758
|
+
})
|
|
759
|
+
.then(async (response) => {
|
|
760
|
+
const body = await response.json().catch(() => ({}))
|
|
761
|
+
if (!response.ok) throw new Error(body.error ?? `POST ${response.status}`)
|
|
762
|
+
setState(body)
|
|
763
|
+
})
|
|
764
|
+
.catch((err) => setError(`${t('sessionFailed')}${err instanceof Error ? err.message : String(err)}`))
|
|
765
|
+
.finally(() => setBusy(false))
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
const heading = React.createElement('div', { style: { padding: '8px 16px 2px' } },
|
|
769
|
+
React.createElement('div', { style: labelStyle }, t('sessionSection')),
|
|
770
|
+
React.createElement('div', { style: subStyle }, t('sessionSectionHint')),
|
|
771
|
+
)
|
|
772
|
+
if (state === undefined) {
|
|
773
|
+
return React.createElement('div', { style: { padding: '4px 0' } }, heading,
|
|
774
|
+
React.createElement('div', { style: { padding: '8px 16px', ...subStyle } }, t('sessionLoading')))
|
|
775
|
+
}
|
|
776
|
+
const active = state.ok !== false
|
|
777
|
+
const row = (label, hint, control) => React.createElement('div', { style: rowStyle },
|
|
778
|
+
React.createElement('div', null,
|
|
779
|
+
React.createElement('div', { style: labelStyle }, label),
|
|
780
|
+
React.createElement('div', { style: subStyle }, hint),
|
|
781
|
+
),
|
|
782
|
+
control,
|
|
783
|
+
)
|
|
784
|
+
return React.createElement('div', { style: { padding: '4px 0' } },
|
|
785
|
+
heading,
|
|
786
|
+
active ? null : React.createElement('div', { style: { padding: '8px 16px', ...subStyle } }, t('sessionNoActive')),
|
|
787
|
+
active ? row(t('sessionCurrent'), t('sessionCurrentHint'),
|
|
788
|
+
React.createElement(Toggle, {
|
|
789
|
+
label: t('sessionCurrent'),
|
|
790
|
+
checked: state.effective === true,
|
|
791
|
+
disabled: busy,
|
|
792
|
+
onChange: (next) => act(next ? 'on' : 'off'),
|
|
793
|
+
})) : null,
|
|
794
|
+
active ? row(t('sessionWorkspace'), t('sessionWorkspaceHint'),
|
|
795
|
+
React.createElement(Toggle, {
|
|
796
|
+
label: t('sessionWorkspace'),
|
|
797
|
+
checked: state.workspaceDisabled === true,
|
|
798
|
+
disabled: busy || typeof state.cwd !== 'string' || state.cwd.length === 0,
|
|
799
|
+
onChange: (next) => act(next ? 'workspace-off' : 'workspace-on'),
|
|
800
|
+
})) : null,
|
|
801
|
+
active && typeof state.cwd === 'string' && state.cwd.length > 0
|
|
802
|
+
? React.createElement('div', { style: { padding: '2px 16px 8px', ...subStyle } }, state.cwd)
|
|
803
|
+
: null,
|
|
804
|
+
error !== undefined
|
|
805
|
+
? React.createElement('div', { role: 'alert', style: { padding: '4px 16px 8px', fontSize: '12px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' } }, error)
|
|
806
|
+
: null,
|
|
807
|
+
)
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
// ---------------- 会话内 chip(composer 工具行左侧) ----------------
|
|
811
|
+
//
|
|
812
|
+
// 与内置 Plan 开关同构:状态来自 Host 的 per-session gate。点击打开下拉,
|
|
813
|
+
// 分别设置「本会话」与「此工作区默认」——比盲切更可控;Host 拒绝时把
|
|
814
|
+
// 原因显示出来(单点盲切失败时用户只会看到「点了没反应」)。
|
|
815
|
+
const chipButtonStyle = (enabled) => ({
|
|
816
|
+
display: 'inline-flex',
|
|
817
|
+
alignItems: 'center',
|
|
818
|
+
gap: '5px',
|
|
819
|
+
padding: '4px 8px',
|
|
820
|
+
fontSize: '13px',
|
|
821
|
+
lineHeight: '18px',
|
|
822
|
+
borderRadius: '6px',
|
|
823
|
+
border: 'none',
|
|
824
|
+
// Match the composer toolbar's own secondary text/icons instead of
|
|
825
|
+
// looking like a foreign pill (the boxed style read as "highlighted").
|
|
826
|
+
background: 'transparent',
|
|
827
|
+
color: 'var(--dsw-alias-label-secondary, #888)',
|
|
828
|
+
cursor: 'pointer',
|
|
829
|
+
whiteSpace: 'nowrap',
|
|
830
|
+
opacity: enabled ? 1 : 0.55,
|
|
831
|
+
})
|
|
832
|
+
const chipMenuStyle = {
|
|
833
|
+
position: 'absolute',
|
|
834
|
+
bottom: 'calc(100% + 6px)',
|
|
835
|
+
left: 0,
|
|
836
|
+
zIndex: 40,
|
|
837
|
+
minWidth: '156px',
|
|
838
|
+
padding: '6px',
|
|
839
|
+
borderRadius: '8px',
|
|
840
|
+
border: '1px solid var(--dsw-alias-border-l1, rgba(128,128,128,0.2))',
|
|
841
|
+
background: 'var(--dsw-alias-bg-layer-2, #fff)',
|
|
842
|
+
boxShadow: '0 6px 20px rgba(0, 0, 0, 0.12)',
|
|
843
|
+
display: 'flex',
|
|
844
|
+
flexDirection: 'column',
|
|
845
|
+
gap: '2px',
|
|
846
|
+
}
|
|
847
|
+
const chipMenuHeadingStyle = { padding: '4px 8px 2px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary, #888)' }
|
|
848
|
+
const chipMenuItemStyle = (active) => ({
|
|
849
|
+
display: 'flex',
|
|
850
|
+
alignItems: 'center',
|
|
851
|
+
gap: '6px',
|
|
852
|
+
padding: '5px 8px',
|
|
853
|
+
fontSize: '12px',
|
|
854
|
+
lineHeight: '16px',
|
|
855
|
+
borderRadius: '5px',
|
|
856
|
+
border: 'none',
|
|
857
|
+
textAlign: 'left',
|
|
858
|
+
background: active ? 'var(--dsw-alias-bg-layer-3, rgba(128,128,128,0.12))' : 'transparent',
|
|
859
|
+
color: 'var(--dsw-alias-label-primary, inherit)',
|
|
860
|
+
cursor: 'pointer',
|
|
861
|
+
})
|
|
862
|
+
const chipMenuDividerStyle = { height: '1px', margin: '4px 6px', background: 'var(--dsw-alias-border-l1, rgba(128,128,128,0.2))' }
|
|
863
|
+
const chipMenuErrorStyle = { padding: '4px 8px', fontSize: '11px', lineHeight: '15px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' }
|
|
864
|
+
|
|
865
|
+
/** 16px brain-circuit glyph (same paths as the settings nav mark). */
|
|
866
|
+
function MemoryGlyph() {
|
|
867
|
+
return React.createElement('svg', {
|
|
868
|
+
width: 16,
|
|
869
|
+
height: 16,
|
|
870
|
+
viewBox: '0 0 16 16',
|
|
871
|
+
fill: 'none',
|
|
872
|
+
stroke: 'currentColor',
|
|
873
|
+
strokeWidth: 1.3,
|
|
874
|
+
strokeLinecap: 'round',
|
|
875
|
+
strokeLinejoin: 'round',
|
|
876
|
+
'aria-hidden': true,
|
|
877
|
+
}, BRAIN_CIRCUIT_PATHS.map((path, index) => (path.kind === 'circle'
|
|
878
|
+
? React.createElement('circle', { key: index, cx: path.cx, cy: path.cy, r: path.r })
|
|
879
|
+
: React.createElement('path', { key: index, d: path.d }))))
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function MemoryChip(props) {
|
|
883
|
+
const t = useT(props)
|
|
884
|
+
const sessionId = props?.sessionId
|
|
885
|
+
const [state, setState] = React.useState(undefined)
|
|
886
|
+
const [busy, setBusy] = React.useState(false)
|
|
887
|
+
const [open, setOpen] = React.useState(false)
|
|
888
|
+
const [error, setError] = React.useState(undefined)
|
|
889
|
+
|
|
890
|
+
const read = () => {
|
|
891
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return
|
|
892
|
+
fetch(`${SESSION_URL}?sessionId=${encodeURIComponent(sessionId)}`)
|
|
893
|
+
.then(async (response) => (response.ok ? response.json() : undefined))
|
|
894
|
+
.then((value) => {
|
|
895
|
+
if (value === undefined) return
|
|
896
|
+
setState(value)
|
|
897
|
+
if (value.ok === false) setError(t('chipMenuUnavailable'))
|
|
898
|
+
})
|
|
899
|
+
.catch(() => setError(t('chipMenuUnavailable')))
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
React.useEffect(() => {
|
|
903
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return undefined
|
|
904
|
+
read()
|
|
905
|
+
const timer = typeof setInterval === 'function' ? setInterval(read, 10000) : undefined
|
|
906
|
+
return () => {
|
|
907
|
+
if (timer !== undefined) clearInterval(timer)
|
|
908
|
+
}
|
|
909
|
+
}, [sessionId])
|
|
910
|
+
|
|
911
|
+
// Close on outside click only while open (the test harness stubs hooks).
|
|
912
|
+
React.useEffect(() => {
|
|
913
|
+
if (!open || typeof document === 'undefined') return undefined
|
|
914
|
+
const close = () => setOpen(false)
|
|
915
|
+
document.addEventListener('mousedown', close)
|
|
916
|
+
return () => document.removeEventListener('mousedown', close)
|
|
917
|
+
}, [open])
|
|
918
|
+
|
|
919
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return null
|
|
920
|
+
const enabled = state === undefined ? true : state.ok !== false && state.effective !== false
|
|
921
|
+
const workspaceMuted = state?.workspaceDisabled === true
|
|
922
|
+
|
|
923
|
+
const act = (action) => {
|
|
924
|
+
setBusy(true)
|
|
925
|
+
setError(undefined)
|
|
926
|
+
fetch(SESSION_URL, {
|
|
927
|
+
method: 'POST',
|
|
928
|
+
headers: { 'content-type': 'application/json' },
|
|
929
|
+
body: JSON.stringify({ action, sessionId }),
|
|
930
|
+
})
|
|
931
|
+
.then(async (response) => {
|
|
932
|
+
const body = await response.json().catch(() => ({}))
|
|
933
|
+
if (!response.ok) throw new Error(body.error ?? `POST ${response.status}`)
|
|
934
|
+
if (body.ok === false) throw new Error(String(body.reason ?? 'no-session'))
|
|
935
|
+
setState(body)
|
|
936
|
+
setOpen(false)
|
|
937
|
+
})
|
|
938
|
+
.catch((err) => setError(`${t('chipMenuFailed')}${err instanceof Error ? err.message : String(err)}`))
|
|
939
|
+
.finally(() => setBusy(false))
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
const item = (label, action, active) => React.createElement('button', {
|
|
943
|
+
type: 'button',
|
|
944
|
+
role: 'menuitemradio',
|
|
945
|
+
'aria-checked': active,
|
|
946
|
+
disabled: busy,
|
|
947
|
+
onClick: (event) => {
|
|
948
|
+
event.stopPropagation()
|
|
949
|
+
act(action)
|
|
950
|
+
},
|
|
951
|
+
style: chipMenuItemStyle(active),
|
|
952
|
+
}, active ? `✓ ${label}` : ` ${label}`)
|
|
953
|
+
|
|
954
|
+
const menu = open
|
|
955
|
+
? React.createElement('div', {
|
|
956
|
+
role: 'menu',
|
|
957
|
+
'aria-label': t('chipMenuTitle'),
|
|
958
|
+
onMouseDown: (event) => event.stopPropagation(),
|
|
959
|
+
style: chipMenuStyle,
|
|
960
|
+
},
|
|
961
|
+
React.createElement('div', { style: chipMenuHeadingStyle }, t('chipMenuSession')),
|
|
962
|
+
item(t('chipMenuOn'), 'on', enabled),
|
|
963
|
+
item(t('chipMenuOff'), 'off', !enabled),
|
|
964
|
+
React.createElement('div', { style: chipMenuDividerStyle }),
|
|
965
|
+
React.createElement('div', { style: chipMenuHeadingStyle }, t('chipMenuWorkspace')),
|
|
966
|
+
item(t('chipMenuOn'), 'workspace-on', !workspaceMuted),
|
|
967
|
+
item(t('chipMenuOff'), 'workspace-off', workspaceMuted),
|
|
968
|
+
error !== undefined
|
|
969
|
+
? React.createElement('div', { role: 'alert', style: chipMenuErrorStyle }, error)
|
|
970
|
+
: null,
|
|
971
|
+
)
|
|
972
|
+
: null
|
|
973
|
+
|
|
974
|
+
return React.createElement('span', { style: { position: 'relative', display: 'inline-flex' } },
|
|
975
|
+
React.createElement('button', {
|
|
976
|
+
type: 'button',
|
|
977
|
+
title: t('chipHint'),
|
|
978
|
+
'aria-label': t('chipHint'),
|
|
979
|
+
'aria-haspopup': 'menu',
|
|
980
|
+
'aria-expanded': open,
|
|
981
|
+
'data-dsh-memory-chip-btn': '',
|
|
982
|
+
disabled: busy,
|
|
983
|
+
onClick: (event) => {
|
|
984
|
+
event.stopPropagation()
|
|
985
|
+
setOpen((value) => !value)
|
|
986
|
+
},
|
|
987
|
+
style: chipButtonStyle(enabled),
|
|
988
|
+
},
|
|
989
|
+
React.createElement(MemoryGlyph, null),
|
|
990
|
+
React.createElement('span', null, enabled ? t('chipOn') : t('chipOff')),
|
|
991
|
+
),
|
|
992
|
+
menu,
|
|
993
|
+
)
|
|
994
|
+
}
|
|
995
|
+
|
|
690
996
|
function MemoryForm(props) {
|
|
691
997
|
const t = useT(props)
|
|
692
998
|
const { onSaved } = props
|
|
@@ -982,6 +1288,7 @@ window.__ModuleLoader__.load({
|
|
|
982
1288
|
}, growthBusy ? t('growthNowRunning') : t('growthNow')),
|
|
983
1289
|
),
|
|
984
1290
|
),
|
|
1291
|
+
React.createElement(SessionControls, { t }),
|
|
985
1292
|
error !== undefined ? React.createElement('div', { role: 'alert', style: errorStyle }, t('saveFailed'), error) : null,
|
|
986
1293
|
React.createElement('div', { style: { padding: '14px 16px', fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #888)' } },
|
|
987
1294
|
value.enabled === false
|
|
@@ -1565,9 +1872,30 @@ window.__ModuleLoader__.load({
|
|
|
1565
1872
|
locale: LOCALE_NS,
|
|
1566
1873
|
label: labelOf,
|
|
1567
1874
|
}, MemorySection))
|
|
1875
|
+
// 会话内开关(composer 工具行左侧 chip)。旧宿主可能不声明该 slot:
|
|
1876
|
+
// 注册失败只影响 chip,/memory 命令与设置面板入口仍然可用。
|
|
1877
|
+
try {
|
|
1878
|
+
ctx.slots.inject('conversation.input.left', () => ctx.slots.register({
|
|
1879
|
+
name: 'conversation.input.left',
|
|
1880
|
+
id: 'memory-session-toggle',
|
|
1881
|
+
order: 100,
|
|
1882
|
+
locale: LOCALE_NS,
|
|
1883
|
+
}, MemoryChip))
|
|
1884
|
+
} catch {
|
|
1885
|
+
// no composer slot on this host
|
|
1886
|
+
}
|
|
1568
1887
|
// 官方 settings.section 没有 icon 字段,侧栏标记只能靠自己认领;
|
|
1569
1888
|
// 认领键就是当前语言的 label(语言切换后 MutationObserver 会重新对齐)。
|
|
1570
1889
|
ctx.effect(() => claimNavIcon(labelOf), 'memory: settings nav icon')
|
|
1890
|
+
// Inline styles cannot express :hover; the chip should light up like the
|
|
1891
|
+
// composer's other toolbar buttons on pointer-over.
|
|
1892
|
+
ctx.effect(() => {
|
|
1893
|
+
if (typeof document === 'undefined') return undefined
|
|
1894
|
+
const tag = document.createElement('style')
|
|
1895
|
+
tag.textContent = '[data-dsh-memory-chip-btn]:hover { background: var(--dsw-alias-bg-layer-2, rgba(128,128,128,0.12)); } [data-dsh-memory-chip-btn]:disabled { cursor: not-allowed; }'
|
|
1896
|
+
document.head.appendChild(tag)
|
|
1897
|
+
return () => tag.remove()
|
|
1898
|
+
}, 'memory: chip styles')
|
|
1571
1899
|
}
|
|
1572
1900
|
|
|
1573
1901
|
exports.apply = apply
|
|
@@ -1578,6 +1906,9 @@ window.__ModuleLoader__.load({
|
|
|
1578
1906
|
exports.__test = {
|
|
1579
1907
|
MemorySection,
|
|
1580
1908
|
MemoryForm,
|
|
1909
|
+
SessionControls,
|
|
1910
|
+
MemoryChip,
|
|
1911
|
+
SESSION_URL,
|
|
1581
1912
|
InsightsCard,
|
|
1582
1913
|
GraphCard,
|
|
1583
1914
|
GraphView,
|
package/lib/config-store.js
CHANGED
|
@@ -23,7 +23,7 @@ export function defaultConfigPath() {
|
|
|
23
23
|
return join(process.env.DSH_HOME || join(homedir(), '.dsh'), MEMORY_CONFIG_FILENAME)
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'deferUntilUserSpeaks', 'activeSessionOnly', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession', 'proactiveCooldownSeconds', 'toneGuideEnabled', 'toneIntensity', 'growthRecapEnabled', 'growthRecapIntervalDays']
|
|
26
|
+
const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'deferUntilUserSpeaks', 'activeSessionOnly', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession', 'proactiveCooldownSeconds', 'toneGuideEnabled', 'toneIntensity', 'growthRecapEnabled', 'growthRecapIntervalDays', 'disabledWorkspaces']
|
|
27
27
|
|
|
28
28
|
/** Tone intensity values the schema accepts; invalid composition input falls back to low. */
|
|
29
29
|
const TONE_INTENSITIES = ['low', 'medium', 'off']
|
|
@@ -71,6 +71,7 @@ export class MemoryConfigStore {
|
|
|
71
71
|
toneIntensity: TONE_INTENSITIES.includes(options.base?.toneIntensity) ? options.base.toneIntensity : 'low',
|
|
72
72
|
growthRecapEnabled: options.base?.growthRecapEnabled !== false,
|
|
73
73
|
growthRecapIntervalDays: options.base?.growthRecapIntervalDays ?? 7,
|
|
74
|
+
disabledWorkspaces: Array.isArray(options.base?.disabledWorkspaces) ? options.base.disabledWorkspaces : [],
|
|
74
75
|
}
|
|
75
76
|
this.config = { ...this.base }
|
|
76
77
|
this.watchers = new Set()
|
|
@@ -107,6 +108,7 @@ export class MemoryConfigStore {
|
|
|
107
108
|
toneIntensity: resolved.toneIntensity,
|
|
108
109
|
growthRecapEnabled: resolved.growthRecapEnabled,
|
|
109
110
|
growthRecapIntervalDays: resolved.growthRecapIntervalDays,
|
|
111
|
+
disabledWorkspaces: resolved.disabledWorkspaces,
|
|
110
112
|
}
|
|
111
113
|
} catch {
|
|
112
114
|
// schema validation failed: keep last good config
|
|
@@ -151,6 +153,7 @@ export class MemoryConfigStore {
|
|
|
151
153
|
toneIntensity: next.toneIntensity,
|
|
152
154
|
growthRecapEnabled: next.growthRecapEnabled,
|
|
153
155
|
growthRecapIntervalDays: next.growthRecapIntervalDays,
|
|
156
|
+
disabledWorkspaces: next.disabledWorkspaces,
|
|
154
157
|
}
|
|
155
158
|
this.persist()
|
|
156
159
|
for (const watcher of this.watchers) {
|
package/lib/index.js
CHANGED
|
@@ -108,6 +108,7 @@ import { buildToneGuide } from './tone.js'
|
|
|
108
108
|
import { claimProactiveLock, defaultProactiveCooldownPath } from './proactive-lock.js'
|
|
109
109
|
import { AutoCommitter } from './autocommit.js'
|
|
110
110
|
import { ActivityTracker } from './activity-tracker.js'
|
|
111
|
+
import { SessionGate, matchesWorkspace } from './session-gate.js'
|
|
111
112
|
import {
|
|
112
113
|
MEMORY_SKILL_NAME,
|
|
113
114
|
MEMORY_SKILL_DESCRIPTION,
|
|
@@ -127,6 +128,9 @@ export const INSIGHTS_ROUTE_PATH = '/api/memory/insights'
|
|
|
127
128
|
export const GRAPH_ROUTE_PATH = '/api/memory/graph'
|
|
128
129
|
export const CONTROL_ROUTE_PATH = '/api/memory/control'
|
|
129
130
|
|
|
131
|
+
/** Per-session memory gate: GET the state, POST a toggle. */
|
|
132
|
+
export const SESSION_ROUTE_PATH = '/api/memory/session'
|
|
133
|
+
|
|
130
134
|
export const inject = ['systemPrompt', 'skills', 'agents']
|
|
131
135
|
|
|
132
136
|
/** Schemastery schema applied to the plugin config before startup. */
|
|
@@ -173,6 +177,14 @@ export const Config = z.object({
|
|
|
173
177
|
// Weekly growth recap, delivered on the recall channel.
|
|
174
178
|
growthRecapEnabled: z.boolean().default(true),
|
|
175
179
|
growthRecapIntervalDays: z.number().default(7),
|
|
180
|
+
// Workspaces that default to memory off: sessions whose cwd falls inside
|
|
181
|
+
// one of these roots start muted. A per-session override (the composer chip
|
|
182
|
+
// or `/memory on`) still wins, so this is a default, not a hard block.
|
|
183
|
+
disabledWorkspaces: z.array(z.string()).default([]),
|
|
184
|
+
// Where per-session overrides live (default `<dshHome>/memory-sessions.json`).
|
|
185
|
+
sessionStateFile: z.union([z.string(), z.const(undefined)]),
|
|
186
|
+
// Days a session override stays valid before it is pruned. Default 7.
|
|
187
|
+
sessionTtlDays: z.number().default(7),
|
|
176
188
|
// Auto-commit: keep the store's git history current after a quiet period.
|
|
177
189
|
autoCommit: z.boolean().default(true),
|
|
178
190
|
autoCommitQuietSeconds: z.number().default(60),
|
|
@@ -222,6 +234,7 @@ export function apply(ctx, config = {}) {
|
|
|
222
234
|
toneIntensity: ['low', 'medium', 'off'].includes(config.toneIntensity) ? config.toneIntensity : 'low',
|
|
223
235
|
growthRecapEnabled: config.growthRecapEnabled !== false,
|
|
224
236
|
growthRecapIntervalDays: config.growthRecapIntervalDays ?? 7,
|
|
237
|
+
disabledWorkspaces: Array.isArray(config.disabledWorkspaces) ? config.disabledWorkspaces : [],
|
|
225
238
|
},
|
|
226
239
|
})
|
|
227
240
|
|
|
@@ -230,6 +243,74 @@ export function apply(ctx, config = {}) {
|
|
|
230
243
|
// it, and shared with the digest guard + recall nudge so they never disagree.
|
|
231
244
|
const tracker = new ActivityTracker({ agents: ctx.agents, logger: ctx.logger })
|
|
232
245
|
|
|
246
|
+
// Per-session memory gate: a session can opt out even while the plugin is
|
|
247
|
+
// on, and whole workspaces can default to off. Precedence: global switch >
|
|
248
|
+
// session override > disabledWorkspaces > on. Shared by the boot block,
|
|
249
|
+
// page-access stamping, the digest guard and the recall nudge.
|
|
250
|
+
const sessionGate = new SessionGate({
|
|
251
|
+
path: typeof config.sessionStateFile === 'string' && config.sessionStateFile.trim().length > 0
|
|
252
|
+
? config.sessionStateFile
|
|
253
|
+
: undefined,
|
|
254
|
+
ttlDays: config.sessionTtlDays,
|
|
255
|
+
})
|
|
256
|
+
const sessionCwd = (agent) => agent?.session?.header?.cwd
|
|
257
|
+
const sessionEnabled = (agent, resolved) => sessionGate.effectiveEnabled(
|
|
258
|
+
agent.id,
|
|
259
|
+
sessionCwd(agent),
|
|
260
|
+
{ globalEnabled: resolved.enabled, disabledWorkspaces: resolved.disabledWorkspaces },
|
|
261
|
+
)
|
|
262
|
+
const describeSession = (agent, resolved) => {
|
|
263
|
+
const cwd = sessionCwd(agent)
|
|
264
|
+
return {
|
|
265
|
+
sessionId: agent.id,
|
|
266
|
+
cwd,
|
|
267
|
+
override: sessionGate.getOverride(agent.id),
|
|
268
|
+
workspaceDisabled: matchesWorkspace(cwd, resolved.disabledWorkspaces),
|
|
269
|
+
globalEnabled: resolved.enabled !== false,
|
|
270
|
+
effective: sessionGate.effectiveEnabled(agent.id, cwd, {
|
|
271
|
+
globalEnabled: resolved.enabled,
|
|
272
|
+
disabledWorkspaces: resolved.disabledWorkspaces,
|
|
273
|
+
}),
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const setWorkspaceDefault = (resolved, cwd, off) => {
|
|
277
|
+
if (typeof cwd !== 'string' || cwd.trim().length === 0) return false
|
|
278
|
+
const current = Array.isArray(resolved.disabledWorkspaces) ? resolved.disabledWorkspaces : []
|
|
279
|
+
const without = current.filter((entry) => entry !== cwd)
|
|
280
|
+
store.update({ disabledWorkspaces: off ? [...without, cwd] : without })
|
|
281
|
+
return true
|
|
282
|
+
}
|
|
283
|
+
const handleMemoryCommand = (agent, rawInput) => {
|
|
284
|
+
const resolved = store.get()
|
|
285
|
+
const arg = String(rawInput ?? '').trim().toLowerCase()
|
|
286
|
+
const cwd = sessionCwd(agent)
|
|
287
|
+
if (arg === '' || arg === 'status') {
|
|
288
|
+
const status = describeSession(agent, resolved)
|
|
289
|
+
return {
|
|
290
|
+
kind: 'success',
|
|
291
|
+
text: `Memory is ${status.effective ? 'ON' : 'OFF'} for this session`
|
|
292
|
+
+ (status.workspaceDisabled ? ' (this workspace defaults to OFF)' : '')
|
|
293
|
+
+ (status.override !== undefined ? ' [explicit session override]' : ''),
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (arg === 'on' || arg === 'off') {
|
|
297
|
+
sessionGate.setOverride(agent.id, arg === 'on', cwd)
|
|
298
|
+
return { kind: 'success', text: `Memory is now ${arg.toUpperCase()} for this session.` }
|
|
299
|
+
}
|
|
300
|
+
if (arg === 'workspace-off' || arg === 'workspace-on') {
|
|
301
|
+
if (!setWorkspaceDefault(resolved, cwd, arg === 'workspace-off')) {
|
|
302
|
+
return { kind: 'error', text: 'This session has no workspace directory to remember.' }
|
|
303
|
+
}
|
|
304
|
+
return {
|
|
305
|
+
kind: 'success',
|
|
306
|
+
text: arg === 'workspace-off'
|
|
307
|
+
? `This workspace (${cwd}) now defaults to memory OFF.`
|
|
308
|
+
: `This workspace (${cwd}) no longer defaults to memory OFF.`,
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return { kind: 'error', text: 'Usage: /memory [on|off|status|workspace-off|workspace-on]' }
|
|
312
|
+
}
|
|
313
|
+
|
|
233
314
|
let bootDispose
|
|
234
315
|
let skillDispose
|
|
235
316
|
let scaffoldedDir
|
|
@@ -304,6 +385,8 @@ export function apply(ctx, config = {}) {
|
|
|
304
385
|
// the active session.
|
|
305
386
|
const resolved = store.get()
|
|
306
387
|
const agent = context?.agent
|
|
388
|
+
// User intent first (the session switch), then the two polite gates.
|
|
389
|
+
if (agent && !sessionEnabled(agent, resolved)) return ''
|
|
307
390
|
if (agent && !tracker.shouldInject(agent.id, resolved)) return ''
|
|
308
391
|
// Tone drift rides on the boot block (charged to its budget). Read
|
|
309
392
|
// live from the store so the Settings select applies on the next
|
|
@@ -340,6 +423,23 @@ export function apply(ctx, config = {}) {
|
|
|
340
423
|
|
|
341
424
|
rebuild()
|
|
342
425
|
|
|
426
|
+
// Human command plane: `/memory on|off|status|workspace-off|workspace-on`.
|
|
427
|
+
// Commands never enter the model context (the host executes them in the UI
|
|
428
|
+
// command plane), and the handler's `agent` is the session the command ran
|
|
429
|
+
// in. Optional injection keeps older hosts without a commands service alive.
|
|
430
|
+
ctx.inject(['commands'], (cmdCtx) => {
|
|
431
|
+
cmdCtx.effect(() => {
|
|
432
|
+
const dispose = cmdCtx.commands.register({
|
|
433
|
+
name: 'memory',
|
|
434
|
+
description: 'Turn long-term memory on/off for this session (/memory on|off|status)',
|
|
435
|
+
handler: ({ agent, rawInput }) => handleMemoryCommand(agent, rawInput),
|
|
436
|
+
})
|
|
437
|
+
return () => {
|
|
438
|
+
dispose?.()
|
|
439
|
+
}
|
|
440
|
+
}, 'memory.command()')
|
|
441
|
+
})
|
|
442
|
+
|
|
343
443
|
// Activity tracker: attach to every live ROOT agent so the two gates
|
|
344
444
|
// (has-user-spoken + active-session) see real user messages as they land.
|
|
345
445
|
ctx.effect(() => {
|
|
@@ -372,7 +472,9 @@ export function apply(ctx, config = {}) {
|
|
|
372
472
|
if (target?.id !== agent.id) return
|
|
373
473
|
if (message?.source?.kind !== 'user') return
|
|
374
474
|
if (stamped.has(agent.id)) return
|
|
375
|
-
|
|
475
|
+
const resolved = store.get()
|
|
476
|
+
if (!sessionEnabled(agent, resolved)) return
|
|
477
|
+
if (!tracker.shouldInject(agent.id, resolved)) return
|
|
376
478
|
stamped.add(agent.id)
|
|
377
479
|
try {
|
|
378
480
|
const memoryDir = currentMemoryDir
|
|
@@ -413,7 +515,7 @@ export function apply(ctx, config = {}) {
|
|
|
413
515
|
readConfig: () => {
|
|
414
516
|
const resolved = store.get()
|
|
415
517
|
return {
|
|
416
|
-
enabled: resolved.enabled,
|
|
518
|
+
enabled: resolved.enabled && sessionEnabled(agent, resolved),
|
|
417
519
|
afterMinutes: config.digestNudgeAfterMinutes,
|
|
418
520
|
cooldownMinutes: config.digestNudgeCooldownMinutes,
|
|
419
521
|
maxPerSession: config.digestNudgeMaxPerSession,
|
|
@@ -453,7 +555,7 @@ export function apply(ctx, config = {}) {
|
|
|
453
555
|
readConfig: () => {
|
|
454
556
|
const resolved = store.get()
|
|
455
557
|
return {
|
|
456
|
-
enabled: resolved.enabled,
|
|
558
|
+
enabled: resolved.enabled && sessionEnabled(agent, resolved),
|
|
457
559
|
recallEnabled: resolved.recallEnabled !== false,
|
|
458
560
|
minMinutes: resolved.recallIntervalMinMinutes,
|
|
459
561
|
maxMinutes: resolved.recallIntervalMaxMinutes,
|
|
@@ -599,6 +701,84 @@ export function apply(ctx, config = {}) {
|
|
|
599
701
|
})
|
|
600
702
|
webCtx.effect(() => disposeControlRoute, 'memory.control-route()')
|
|
601
703
|
|
|
704
|
+
// Per-session gate route: the composer chip and the Settings panel both
|
|
705
|
+
// read and write it. A missing sessionId means "the active session" — the
|
|
706
|
+
// same proxy /api/memory/control uses (the panel has no session id of its
|
|
707
|
+
// own; the browser chip always passes one).
|
|
708
|
+
const disposeSessionRoute = webCtx.webServer.register({
|
|
709
|
+
kind: 'exact',
|
|
710
|
+
path: SESSION_ROUTE_PATH,
|
|
711
|
+
handler: async (req, res) => {
|
|
712
|
+
try {
|
|
713
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
714
|
+
const resolveAgent = (sessionId) => {
|
|
715
|
+
const id = typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : tracker.activeId()
|
|
716
|
+
if (id === undefined) return undefined
|
|
717
|
+
const direct = ctx.agents.get?.(id)
|
|
718
|
+
if (direct !== undefined) return direct
|
|
719
|
+
// Some hosts key the registry differently from the session id the
|
|
720
|
+
// client sends; scanning the roots keeps the chip working either way.
|
|
721
|
+
const roots = typeof ctx.agents.roots === 'function' ? ctx.agents.roots() : []
|
|
722
|
+
return roots.find((agent) => agent.id === id
|
|
723
|
+
|| agent.session?.header?.id === id
|
|
724
|
+
|| agent.session?.id === id)
|
|
725
|
+
}
|
|
726
|
+
const sendJson = (status, payload) => {
|
|
727
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
|
728
|
+
res.end(JSON.stringify(payload))
|
|
729
|
+
}
|
|
730
|
+
if (req.method === 'GET') {
|
|
731
|
+
const agent = resolveAgent(url.searchParams.get('sessionId') ?? undefined)
|
|
732
|
+
if (agent === undefined) {
|
|
733
|
+
sendJson(200, { ok: false, reason: 'no-session' })
|
|
734
|
+
return
|
|
735
|
+
}
|
|
736
|
+
sendJson(200, { ok: true, ...describeSession(agent, store.get()) })
|
|
737
|
+
return
|
|
738
|
+
}
|
|
739
|
+
if (req.method === 'POST') {
|
|
740
|
+
const chunks = []
|
|
741
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
742
|
+
let body
|
|
743
|
+
try {
|
|
744
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
|
|
745
|
+
} catch {
|
|
746
|
+
sendJson(400, { error: 'body must be JSON' })
|
|
747
|
+
return
|
|
748
|
+
}
|
|
749
|
+
const agent = resolveAgent(typeof body?.sessionId === 'string' ? body.sessionId : undefined)
|
|
750
|
+
if (agent === undefined) {
|
|
751
|
+
sendJson(200, { ok: false, reason: 'no-session' })
|
|
752
|
+
return
|
|
753
|
+
}
|
|
754
|
+
const action = typeof body?.action === 'string' ? body.action : ''
|
|
755
|
+
const resolved = store.get()
|
|
756
|
+
const cwd = sessionCwd(agent)
|
|
757
|
+
if (action === 'toggle') sessionGate.toggle(agent.id, undefined, cwd)
|
|
758
|
+
else if (action === 'on' || action === 'off') sessionGate.setOverride(agent.id, action === 'on', cwd)
|
|
759
|
+
else if (action === 'clear') sessionGate.clearOverride(agent.id)
|
|
760
|
+
else if (action === 'workspace-off' || action === 'workspace-on') {
|
|
761
|
+
if (!setWorkspaceDefault(resolved, cwd, action === 'workspace-off')) {
|
|
762
|
+
sendJson(400, { error: 'this session has no workspace directory' })
|
|
763
|
+
return
|
|
764
|
+
}
|
|
765
|
+
} else {
|
|
766
|
+
sendJson(400, { error: `unknown action ${JSON.stringify(action)}` })
|
|
767
|
+
return
|
|
768
|
+
}
|
|
769
|
+
sendJson(200, { ok: true, ...describeSession(agent, store.get()) })
|
|
770
|
+
return
|
|
771
|
+
}
|
|
772
|
+
sendJson(405, { error: 'method not allowed' })
|
|
773
|
+
} catch (error) {
|
|
774
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
|
|
775
|
+
res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))
|
|
776
|
+
}
|
|
777
|
+
},
|
|
778
|
+
})
|
|
779
|
+
webCtx.effect(() => disposeSessionRoute, 'memory.session-route()')
|
|
780
|
+
ctx.logger?.info(`memory: session route at ${SESSION_ROUTE_PATH}`)
|
|
781
|
+
|
|
602
782
|
// Read-only health dashboard payload. Built fresh on every request from the
|
|
603
783
|
// store on disk, so the panel always reflects the newest state and the
|
|
604
784
|
// plugin never caches a stale view of the user's memory.
|
|
@@ -671,7 +851,7 @@ Object.defineProperties(apply, {
|
|
|
671
851
|
|
|
672
852
|
export default apply
|
|
673
853
|
|
|
674
|
-
export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore, ActivityTracker }
|
|
854
|
+
export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore, ActivityTracker, SessionGate }
|
|
675
855
|
export { touchPages, touchPageFile, extractReferencedPages, listPagePaths, accessSummary, today }
|
|
676
856
|
export { collectInsights, readRecentLog } from './insights.js'
|
|
677
857
|
export { buildMemoryGraph, EDGE_KINDS } from './graph.js'
|
package/lib/schema.js
CHANGED
|
@@ -33,4 +33,7 @@ export const SettingsSchema = z.object({
|
|
|
33
33
|
// 0.12.0: weekly growth recap delivered on the recall channel.
|
|
34
34
|
growthRecapEnabled: z.boolean().default(true),
|
|
35
35
|
growthRecapIntervalDays: z.number().default(7),
|
|
36
|
+
// Workspaces that default to memory off (session gate layer 3). A session
|
|
37
|
+
// inside one of these roots starts muted until the user turns it back on.
|
|
38
|
+
disabledWorkspaces: z.array(z.string()).default([]),
|
|
36
39
|
})
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-session memory gate: "remember this conversation, or leave it alone?"
|
|
3
|
+
*
|
|
4
|
+
* The plugin has always had a global switch (`enabled`). This module adds the
|
|
5
|
+
* finer layer the user actually needs: a session can opt out of memory even
|
|
6
|
+
* while the plugin is on, and a whole workspace can default to "off" for the
|
|
7
|
+
* projects that should never be remembered.
|
|
8
|
+
*
|
|
9
|
+
* Precedence (highest first):
|
|
10
|
+
*
|
|
11
|
+
* 1. `globalEnabled === false` — the plugin master switch wins over everything;
|
|
12
|
+
* 2. a per-session override (`/memory off`, the composer chip, the panel);
|
|
13
|
+
* 3. `disabledWorkspaces` matching the session cwd (path-boundary match);
|
|
14
|
+
* 4. otherwise enabled.
|
|
15
|
+
*
|
|
16
|
+
* Overrides are keyed by session id and persisted to a small JSON file
|
|
17
|
+
* (`<dshHome>/memory-sessions.json`) so a resumed session keeps its choice.
|
|
18
|
+
* Entries older than `ttlDays` are pruned on read: session ids are never
|
|
19
|
+
* reused, so stale entries would otherwise accumulate forever.
|
|
20
|
+
*
|
|
21
|
+
* This module is pure Node builtins — no host packages, so the gate logic is
|
|
22
|
+
* unit-testable inside a bare checkout (same rule as `boot.js`).
|
|
23
|
+
*
|
|
24
|
+
* @module dsh-plugin-memory/session-gate
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
28
|
+
import { homedir } from 'node:os'
|
|
29
|
+
import { dirname, join, resolve, sep } from 'node:path'
|
|
30
|
+
|
|
31
|
+
/** File name of the session-override store, next to the plugin's memory.json. */
|
|
32
|
+
export const SESSION_STATE_FILENAME = 'memory-sessions.json'
|
|
33
|
+
|
|
34
|
+
/** Days an override stays valid before it is pruned. */
|
|
35
|
+
export const DEFAULT_TTL_DAYS = 7
|
|
36
|
+
|
|
37
|
+
/** Absolute path of the session-override store. */
|
|
38
|
+
export function defaultSessionStatePath() {
|
|
39
|
+
return join(process.env.DSH_HOME || join(homedir(), '.dsh'), SESSION_STATE_FILENAME)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Expand a leading `~` to the user's home directory. Non-strings pass through
|
|
44
|
+
* as `undefined` so callers can treat missing config as "no rule".
|
|
45
|
+
*
|
|
46
|
+
* @param {unknown} value
|
|
47
|
+
* @returns {string | undefined}
|
|
48
|
+
*/
|
|
49
|
+
export function expandHome(value) {
|
|
50
|
+
if (typeof value !== 'string') return undefined
|
|
51
|
+
const trimmed = value.trim()
|
|
52
|
+
if (trimmed === '~') return homedir()
|
|
53
|
+
if (trimmed.startsWith('~/')) return join(homedir(), trimmed.slice(2))
|
|
54
|
+
return trimmed
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Does `cwd` fall inside any of the configured roots?
|
|
59
|
+
*
|
|
60
|
+
* Matching is on path boundaries, so `/Users/x/work` covers
|
|
61
|
+
* `/Users/x/work/repo` but not `/Users/x/work2`. `~` is expanded.
|
|
62
|
+
*
|
|
63
|
+
* @param {string | undefined} cwd
|
|
64
|
+
* @param {string[] | undefined} patterns
|
|
65
|
+
* @returns {boolean}
|
|
66
|
+
*/
|
|
67
|
+
export function matchesWorkspace(cwd, patterns) {
|
|
68
|
+
if (typeof cwd !== 'string' || cwd.trim().length === 0) return false
|
|
69
|
+
const target = resolve(cwd)
|
|
70
|
+
if (!Array.isArray(patterns)) return false
|
|
71
|
+
return patterns.some((pattern) => {
|
|
72
|
+
const expanded = expandHome(pattern)
|
|
73
|
+
if (expanded === undefined || expanded.length === 0) return false
|
|
74
|
+
const root = resolve(expanded)
|
|
75
|
+
return target === root || target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Persistent per-session overrides.
|
|
81
|
+
*
|
|
82
|
+
* @param {object} [options]
|
|
83
|
+
* @param {string} [options.path] state-file path (defaults to `<dshHome>/memory-sessions.json`)
|
|
84
|
+
* @param {number} [options.ttlDays] override lifetime in days (default 7)
|
|
85
|
+
* @param {() => number} [options.now] clock injection for tests
|
|
86
|
+
*/
|
|
87
|
+
export class SessionGate {
|
|
88
|
+
constructor(options = {}) {
|
|
89
|
+
this.path = options.path ?? defaultSessionStatePath()
|
|
90
|
+
this.ttlDays = Number.isFinite(options.ttlDays) && options.ttlDays > 0
|
|
91
|
+
? options.ttlDays
|
|
92
|
+
: DEFAULT_TTL_DAYS
|
|
93
|
+
this.now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
94
|
+
/** @type {Map<string, { enabled: boolean, updatedAt: number, cwd?: string }>} */
|
|
95
|
+
this.sessions = new Map()
|
|
96
|
+
this.load()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Read the state file; corrupt or missing files mean "no overrides". */
|
|
100
|
+
load() {
|
|
101
|
+
let raw
|
|
102
|
+
try {
|
|
103
|
+
if (!existsSync(this.path)) return
|
|
104
|
+
raw = JSON.parse(readFileSync(this.path, 'utf8'))
|
|
105
|
+
} catch {
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return
|
|
109
|
+
const sessions = raw.sessions
|
|
110
|
+
if (typeof sessions !== 'object' || sessions === null || Array.isArray(sessions)) return
|
|
111
|
+
for (const [id, entry] of Object.entries(sessions)) {
|
|
112
|
+
if (typeof id !== 'string' || id.length === 0) continue
|
|
113
|
+
if (typeof entry !== 'object' || entry === null || typeof entry.enabled !== 'boolean') continue
|
|
114
|
+
if (!Number.isFinite(entry.updatedAt)) continue
|
|
115
|
+
this.sessions.set(id, {
|
|
116
|
+
enabled: entry.enabled,
|
|
117
|
+
updatedAt: entry.updatedAt,
|
|
118
|
+
cwd: typeof entry.cwd === 'string' ? entry.cwd : undefined,
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
this.prune()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Drop expired overrides; returns the number of pruned entries. */
|
|
125
|
+
prune() {
|
|
126
|
+
const cutoff = this.now() - this.ttlDays * 24 * 60 * 60 * 1000
|
|
127
|
+
let removed = 0
|
|
128
|
+
for (const [id, entry] of this.sessions) {
|
|
129
|
+
if (entry.updatedAt < cutoff) {
|
|
130
|
+
this.sessions.delete(id)
|
|
131
|
+
removed += 1
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (removed > 0) this.persist()
|
|
135
|
+
return removed
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The session's explicit choice, or `undefined` when it has none.
|
|
140
|
+
* Expired entries count as "no choice" and are pruned.
|
|
141
|
+
*
|
|
142
|
+
* @param {string} sessionId
|
|
143
|
+
* @returns {boolean | undefined}
|
|
144
|
+
*/
|
|
145
|
+
getOverride(sessionId) {
|
|
146
|
+
const entry = this.sessions.get(sessionId)
|
|
147
|
+
if (entry === undefined) return undefined
|
|
148
|
+
const cutoff = this.now() - this.ttlDays * 24 * 60 * 60 * 1000
|
|
149
|
+
if (entry.updatedAt < cutoff) {
|
|
150
|
+
this.sessions.delete(sessionId)
|
|
151
|
+
this.persist()
|
|
152
|
+
return undefined
|
|
153
|
+
}
|
|
154
|
+
return entry.enabled
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Pin one session on/off.
|
|
159
|
+
*
|
|
160
|
+
* @param {string} sessionId
|
|
161
|
+
* @param {boolean} enabled
|
|
162
|
+
* @param {string} [cwd] session workspace, kept for debugging the state file
|
|
163
|
+
*/
|
|
164
|
+
setOverride(sessionId, enabled, cwd) {
|
|
165
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return
|
|
166
|
+
this.sessions.set(sessionId, {
|
|
167
|
+
enabled: enabled === true,
|
|
168
|
+
updatedAt: this.now(),
|
|
169
|
+
...(typeof cwd === 'string' && cwd.length > 0 ? { cwd } : {}),
|
|
170
|
+
})
|
|
171
|
+
this.persist()
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Remove one session's override (back to the workspace/global default). */
|
|
175
|
+
clearOverride(sessionId) {
|
|
176
|
+
if (this.sessions.delete(sessionId)) this.persist()
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Flip one session. With `explicit` given that value is used instead of the
|
|
181
|
+
* flip, which makes the command handling idempotent.
|
|
182
|
+
*
|
|
183
|
+
* @param {string} sessionId
|
|
184
|
+
* @param {boolean} [explicit]
|
|
185
|
+
* @param {string} [cwd] session workspace, kept for debugging the state file
|
|
186
|
+
* @returns {boolean} the new enabled state
|
|
187
|
+
*/
|
|
188
|
+
toggle(sessionId, explicit, cwd) {
|
|
189
|
+
const current = this.getOverride(sessionId) ?? true
|
|
190
|
+
const next = typeof explicit === 'boolean' ? explicit : !current
|
|
191
|
+
this.setOverride(sessionId, next, cwd)
|
|
192
|
+
return next
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The one predicate every injection point shares.
|
|
197
|
+
*
|
|
198
|
+
* @param {string} sessionId
|
|
199
|
+
* @param {string | undefined} cwd
|
|
200
|
+
* @param {{ globalEnabled?: boolean, disabledWorkspaces?: string[] }} [config]
|
|
201
|
+
* @returns {boolean}
|
|
202
|
+
*/
|
|
203
|
+
effectiveEnabled(sessionId, cwd, config = {}) {
|
|
204
|
+
if (config.globalEnabled === false) return false
|
|
205
|
+
const override = this.getOverride(sessionId)
|
|
206
|
+
if (override !== undefined) return override
|
|
207
|
+
if (matchesWorkspace(cwd, config.disabledWorkspaces)) return false
|
|
208
|
+
return true
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Current on-disk session count (debugging / diagnostics). */
|
|
212
|
+
get size() {
|
|
213
|
+
return this.sessions.size
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Persist atomically; failures are best-effort and never break a turn. */
|
|
217
|
+
persist() {
|
|
218
|
+
try {
|
|
219
|
+
mkdirSync(dirname(this.path), { recursive: true })
|
|
220
|
+
const payload = {
|
|
221
|
+
version: 1,
|
|
222
|
+
sessions: Object.fromEntries(this.sessions),
|
|
223
|
+
}
|
|
224
|
+
const tmp = `${this.path}.tmp`
|
|
225
|
+
writeFileSync(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
|
|
226
|
+
renameSync(tmp, this.path)
|
|
227
|
+
} catch {
|
|
228
|
+
// best effort: the in-memory gate still works for this process
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
package/lib/types/index.d.ts
CHANGED
|
@@ -71,6 +71,16 @@ export interface MemoryConfig {
|
|
|
71
71
|
growthRecapEnabled?: boolean
|
|
72
72
|
/** Days between growth recaps. Default `7`. */
|
|
73
73
|
growthRecapIntervalDays?: number
|
|
74
|
+
/**
|
|
75
|
+
* Workspaces (by session cwd, `~` expanded, path-boundary match) that
|
|
76
|
+
* default to memory **off**. A per-session override still wins.
|
|
77
|
+
* Default `[]`.
|
|
78
|
+
*/
|
|
79
|
+
disabledWorkspaces?: string[]
|
|
80
|
+
/** Where per-session overrides live (default `<dshHome>/memory-sessions.json`). */
|
|
81
|
+
sessionStateFile?: string
|
|
82
|
+
/** Days a session override stays valid before it is pruned. Default `7`. */
|
|
83
|
+
sessionTtlDays?: number
|
|
74
84
|
/** Auto-commit the store's git history after a quiet period. Default `true`. */
|
|
75
85
|
autoCommit?: boolean
|
|
76
86
|
/** Seconds of quiet before an auto-commit. Default `60`. */
|
|
@@ -94,6 +104,9 @@ export const GRAPH_ROUTE_PATH: '/api/memory/graph'
|
|
|
94
104
|
/** Manual control route (`growth-now`): deliver one recap on demand. */
|
|
95
105
|
export const CONTROL_ROUTE_PATH: '/api/memory/control'
|
|
96
106
|
|
|
107
|
+
/** Per-session memory gate: read state (GET) / toggle it (POST). */
|
|
108
|
+
export const SESSION_ROUTE_PATH: '/api/memory/session'
|
|
109
|
+
|
|
97
110
|
/** User-editable settings (composition config is the base layer). */
|
|
98
111
|
export interface MemorySettings {
|
|
99
112
|
enabled?: boolean
|
|
@@ -111,6 +124,7 @@ export interface MemorySettings {
|
|
|
111
124
|
toneIntensity?: 'low' | 'medium' | 'off'
|
|
112
125
|
growthRecapEnabled?: boolean
|
|
113
126
|
growthRecapIntervalDays?: number
|
|
127
|
+
disabledWorkspaces?: string[]
|
|
114
128
|
}
|
|
115
129
|
|
|
116
130
|
/** Schemastery schema for {@link MemorySettings}. */
|
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.14.0",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|
package/skills/memory.md
CHANGED
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
- 只记**跨会话仍然有价值**的内容:关于用户的稳定事实、偏好、决策与理由、项目背景、学到的工具坑与工作流。不记一次性闲聊、不记能从当前对话直接看到的临时状态。
|
|
26
26
|
- 与用户偏好/语气相关的修正,优先写入 `SOUL.md`(经用户确认)或 `user/preferences.md`。
|
|
27
27
|
- **digest 是强制义务,不是可选项**:每次会话收尾前,把本会话的关键沉淀写回(页面 + `index.md` + `log.md`),否则「长期记忆」只是空话。当收到插件注入的 digest 提醒(一条 `source.kind === 'plugin'` 的合成消息)时**立即执行**,不得以「等会儿」拖延;若本会话确无值得持久化的内容,在 `log.md` 记一条「## [日期] digest | 无新增」并说明原因——这同样会解除提醒。
|
|
28
|
+
- **会话级开关**:本会话的记忆可能被用户关闭(输入框工具行的 chip 或 `/memory off`)。关闭时不要主动调用 remember / recall / consolidate,也不要往记忆库写东西;只有用户显式说「记住这个」才写。开关状态持久化在 `<dshHome>/memory-sessions.json`,恢复会话后仍然有效;用户说「打开记忆」或 `/memory on` 即恢复。
|
|
28
29
|
|
|
29
30
|
## 迁移与导出
|
|
30
31
|
|