feat: complete local memory and Mnemon integration (0.10.1)
This commit is contained in:
parent
3ef7ffef6f
commit
1dfc7c7380
|
|
@ -24,3 +24,14 @@ node_modules/
|
|||
# generated previews (node preview-card.mjs)
|
||||
_preview/
|
||||
preview-debug.mjs
|
||||
.codegraph/
|
||||
|
||||
# 可重新生成的输出与临时文件
|
||||
artifacts/
|
||||
.tmp-*
|
||||
|
||||
# 项目本地记忆数据(.dsh 本身仍可跟踪)
|
||||
/.dsh/brain/
|
||||
|
||||
# 测试/本地运行生成的项目记忆脚手架
|
||||
/.dsh/.gitignore
|
||||
|
|
|
|||
318
README.md
318
README.md
|
|
@ -1,16 +1,16 @@
|
|||
# dsh-brain
|
||||
|
||||
> **0.8.0 统一版(2026-11-11)**:本地开发线(0.7.0,含技能市场 / MCP 市场 /
|
||||
> 多来源技能树 / 跨软件工作区清单 / 工作区级技能写)与云端线(0.5.1,完成
|
||||
> dsh-brain 改名的部署半区)在此合流。插件现以 **dsh-brain** 发布:
|
||||
> 包名、页面路由(`/dsh-brain/*`,旧 `/cloud-memory/*` 保留为别名)、
|
||||
> 客户端模块 id、设置侧车(`dsh-brain.json` 等)全部切换;旧侧车在首次
|
||||
> 加载时自动复制迁移、原文件保留;令牌环境变量 `DSH_BRAIN_*` 优先、
|
||||
> 旧名继续有效。Mnemon provider 引用改为 `dsh-brain/mnemon-provider`。
|
||||
> **0.10.1**:插件按功能拆成五个可单独开关的子插件(见「五个子插件」);
|
||||
> 技能同步引入按内容与更新时间的自动冲突解决(0.9.9/0.9.10 语义);
|
||||
> 令牌环境变量改为**绑定服务地址**(见「配置」)。
|
||||
|
||||
把 DeepSeek Harness 接到 LongMemory 云端记忆服务:**每轮对话结束自动上报一条活动记录**(只上传元数据),并把云端记忆库变成 agent 可用的工具。
|
||||
把 DeepSeek Harness 接到 LongMemory 云端记忆服务:每轮对话结束自动上报一条
|
||||
活动记录(只上传元数据),并把云端记忆库变成 agent 可用的工具;同时双向
|
||||
同步云端技能中心与本机技能目录。
|
||||
|
||||
当前版本 **0.8.0**,含宿主端与浏览器端两部分:host 半负责活动上报与工具注册,`client/index.js` 提供「设置 → 插件 → 云端记忆」配置卡片。
|
||||
当前版本 **0.10.1**,含宿主端与浏览器端两部分:宿主端负责活动上报、
|
||||
记忆工具注册与技能同步,`client/index.js` 提供「设置 → 插件 → 云端记忆」
|
||||
配置卡片。
|
||||
|
||||
## 它做什么
|
||||
|
||||
|
|
@ -18,11 +18,35 @@
|
|||
| --- | --- |
|
||||
| 活动上报 | 监听 `session/event` 的 `turn/start`、`turn/end`,每个结束的回合调用一次 `POST /activity/turn`。上报字段只有 6 个:`client_id`、`conversation_id`、`turn_id`、`status`、`started_at`、`completed_at`。 |
|
||||
| 幂等 | `turn_id` 为 `<sessionId>:<turn>`,服务端按 `turn_id` 去重,重试不会重复计数。 |
|
||||
| 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试(说明载荷或令牌有问题)。 |
|
||||
| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具直接读写云端记忆库。 |
|
||||
| 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试。切换账号或换服务地址后,旧队列条目会被丢弃,不会发到新账号。 |
|
||||
| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具实时读写云端记忆库。 |
|
||||
| 技能同步 | 云端技能中心 ↔ 本机技能目录双向同步,冲突按内容与时间自动取较新(详见「技能同步」)。 |
|
||||
| 配置页 | `GET /dsh-brain` 提供完整配置界面(本 profile 关闭了原生设置页,所以自带页面)。 |
|
||||
|
||||
**绝不上传**:提示词正文、工具输出、文件内容、本地路径、令牌。上报载荷在类型层面就只有六个字段,构造它的函数拿不到正文。
|
||||
**上传范围(如实说明)**:活动上报只上传上表 6 个元数据字段,不含提示词
|
||||
正文。**可选的摘要功能**(`summaryToken`)开启时,会把结束回合的对话文本
|
||||
(脱敏、截断后)发送到独立的 summary 端点用于生成摘要——不开启该功能就
|
||||
没有正文上传。令牌永不随页面回显原文,只回掩码。
|
||||
|
||||
## 五个子插件
|
||||
|
||||
0.10.1 起 `dsh-brain` 以一个包提供五个子插件行,可在宿主
|
||||
「设置 → 插件」页逐行开关(HMR 生效、重启保持):
|
||||
|
||||
| 子插件 | 提供什么 |
|
||||
| --- | --- |
|
||||
| `dsh-brain-cloudsync` | 连接与上报:登录/测试/补发/技能同步路由、重试定时器、同步定时器。 |
|
||||
| `dsh-brain-memory` | 五个 `memory_*` 工具注册。 |
|
||||
| `dsh-brain-skills` | 技能管理页、`skill_list` 工具、技能市场、来源树。 |
|
||||
| `dsh-brain-mcp` | MCP 管理页开关(页签与宿主桥接能力声明;MCP 连接本身由宿主 `dsh-mcp-connector` 管理,本插件不做 MCP 云同步)。 |
|
||||
| `dsh-brain-settings-ui` | 配置页与状态/能力/配置路由。 |
|
||||
|
||||
- 停掉 `dsh-brain-cloudsync` 后活动上报与技能同步停止,但记忆读写工具
|
||||
仍可用(它们实时访问云端)。停掉 `dsh-brain-memory` 才会移除记忆工具。
|
||||
- 共享服务(设置、客户端、同步引擎)由进程级内核统一构造,关掉再开不会
|
||||
重复实例;设置持久化在 `$DSH_HOME/dsh-brain.json`(侧车文件为权威,
|
||||
插件行的 config 只作首次种子)。
|
||||
- 根导出 `.` 仍是兼容组合器:老的单行 profile 升级后行为不变。
|
||||
|
||||
## 安装
|
||||
|
||||
|
|
@ -31,18 +55,13 @@
|
|||
dsh plugin --profile desktop add dsh-brain
|
||||
```
|
||||
|
||||
装好后确认 profile 的 `package.json` 里有两处:
|
||||
装好后确认 profile 的 `package.json` 依赖里有 `dsh-brain`。重启 DSH,在
|
||||
「设置 → 插件 → 云端记忆」里配置(备用入口:
|
||||
`http://127.0.0.1:<当次端口>/dsh-brain`,旧 `/cloud-memory` 路由保留为别名)。
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"dependencies": { "dsh-brain": "^0.8.0" },
|
||||
"dsh": { "profile": { "bundles": [ /* ..., */ "dsh-cloud-memory" ] } }
|
||||
}
|
||||
```
|
||||
|
||||
重启 DSH,在「设置 → 插件 → 云端记忆」里配置(备用入口:`http://127.0.0.1:<当次端口>/cloud-memory`)。
|
||||
|
||||
> `baseUrl` 默认是占位符 `https://your-memory-host/api/longmemory`。**首次使用必须先把它改成你自己的 LongMemory 服务地址**(配置页里填,或写进 `$DSH_HOME/cloud-memory.json`),否则上报与工具都会连接失败。
|
||||
> `baseUrl` 默认是占位符 `https://your-memory-host/api/longmemory`。
|
||||
> **首次使用必须先把它改成你自己的 LongMemory 服务地址**(配置页里填,
|
||||
> 或写进 `$DSH_HOME/dsh-brain.json`),否则上报与工具都会连接失败。
|
||||
|
||||
## 登录(推荐)
|
||||
|
||||
|
|
@ -50,132 +69,171 @@ dsh plugin --profile desktop add dsh-brain
|
|||
|
||||
```
|
||||
密码 → POST /api/auth/login(一次性会话 cookie)
|
||||
→ POST /api/auth/tokens ×2(activity:write、memory:write)
|
||||
→ 只把两个 cmt_… 令牌写进 $DSH_HOME/cloud-memory.json
|
||||
→ POST /api/auth/tokens ×3(activity:write、memory:write、summary:write)
|
||||
→ 把成功签发的 cmt_… 令牌写进 $DSH_HOME/dsh-brain.json
|
||||
→ 失败的 scope 同步清除旧令牌(账号切换是原子的,不留上一个账号的凭据)
|
||||
→ 密码与会话 cookie 立即丢弃
|
||||
```
|
||||
|
||||
- 密码只在这一串请求里存在:不落盘、不写日志、不随 `/cloud-memory/status` 回显。
|
||||
- 密码只在这一串请求里存在:不落盘、不写日志、不随 `/dsh-brain/status` 回显。
|
||||
- 服务端只保存令牌哈希,令牌可单独撤销;改密码不影响已签发令牌。
|
||||
- 服务地址不是 HTTPS(且不是 loopback)时插件拒绝发送密码。
|
||||
- 管理员账号不能签发个人令牌(服务端 `403 management_only`),请用普通用户。
|
||||
- 也可跳过登录,直接手填两个令牌(见下)。
|
||||
- 也可跳过登录,直接手填令牌(见下)。
|
||||
|
||||
## 配置
|
||||
|
||||
配置文件 `$DSH_HOME/cloud-memory.json`(默认 `%USERPROFILE%\.dsh\cloud-memory.json`),字段:
|
||||
配置文件 `$DSH_HOME/dsh-brain.json`(默认 `%USERPROFILE%\.dsh\dsh-brain.json`;
|
||||
旧的 `cloud-memory.json` 首次加载时自动复制迁移、原文件保留),字段:
|
||||
|
||||
| 字段 | 默认 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `enabled` | `true` | 关闭后不上报、工具直接报错。 |
|
||||
| `enabled` | `true` | 总开关。新字段(`activityEnabled` 等)未设置时继承它。 |
|
||||
| `activityEnabled` | 继承 `enabled` | 只关活动上报。 |
|
||||
| `memoryEnabled` | 继承 `enabled` | 只关记忆工具。 |
|
||||
| `skillsSyncEnabled` | `true` | 云端技能中心与本机技能目录的双向同步开关。 |
|
||||
| `baseUrl` | `https://your-memory-host/api/longmemory` | 服务基址,自动去掉结尾斜杠。 |
|
||||
| `clientId` | `dsh-desktop` | 上报时的 `client_id`。 |
|
||||
| `requestTimeoutMs` | `8000` | 单次请求超时,1000–60000。 |
|
||||
| `defaultK` | `10` | `memory_search` 未指定 `k` 时的条数。 |
|
||||
| `activityToken` | — | `activity:write` 令牌,形如 `cmt_…`。 |
|
||||
| `memoryToken` | — | `memory:read` / `memory:write` 令牌,形如 `cmt_…`。 |
|
||||
| `skillsSyncEnabled` | `true` | 云端技能中心与本机技能目录的双向同步开关。 |
|
||||
| `memoryToken` | — | `memory:read` / `memory:write` 令牌。 |
|
||||
| `summaryToken` | — | `summary:write` 令牌(摘要功能,可选)。 |
|
||||
| `skillsDir` | 空 | 本机技能目录覆盖;为空时用 `$DSH_HOME/skills`。 |
|
||||
| `localMemoryEnabled` | `true` | 本地优先记忆总开关;离线、无令牌可用。 |
|
||||
| `cloudMemoryEnabled` | `false` | 云端记忆适配器开关;需要 memory 令牌,默认关闭。 |
|
||||
| `autoMemorySpaces` | `true` | 首次使用时幂等创建全局与当前项目空间。 |
|
||||
| `autoSummaryEnabled` | `true` | 自动捕获用户明确表达的长期信息。 |
|
||||
| `autoProfileEnabled` | `true` | 自动维护 USER.md 画像(推测进入待确认区)。 |
|
||||
| `localMemoryK` | `5` | 本地检索默认返回条数。 |
|
||||
|
||||
两个令牌也可以用环境变量 `DSH_CLOUD_MEMORY_ACTIVITY_TOKEN`、`DSH_CLOUD_MEMORY_MEMORY_TOKEN` 覆盖。
|
||||
三个令牌也可以用环境变量覆盖:`DSH_BRAIN_ACTIVITY_TOKEN`、
|
||||
`DSH_BRAIN_MEMORY_TOKEN`、`DSH_BRAIN_SUMMARY_TOKEN`(旧名
|
||||
`DSH_CLOUD_MEMORY_*` 继续有效)。环境变量令牌**绑定服务地址**:必须同时
|
||||
设置 `DSH_BRAIN_TOKEN_ORIGIN`(或旧名 `DSH_CLOUD_MEMORY_TOKEN_ORIGIN`)
|
||||
且等于当前 `baseUrl` 的 origin 才会生效;在配置页清除令牌后,环境变量
|
||||
也不会再兜底回来。
|
||||
|
||||
> 一个 key 只有一种 scope,所以需要两个令牌:只做上报就只填活动令牌,只做检索就只填记忆令牌。
|
||||
> 一个 key 只有一种 scope,所以需要三个令牌:只做上报就只填活动令牌,
|
||||
> 只做检索就只填记忆令牌。
|
||||
|
||||
## 本地优先记忆
|
||||
|
||||
第一阶段默认使用本地记忆,不需要账号、令牌或网络:全局数据在
|
||||
`$DSH_HOME/brain`,项目数据在 `<项目>/.dsh/brain`,不会创建 `.mnemon`。
|
||||
全局与项目空间在第一次使用记忆工具时自动创建,重启和多窗口复用已有空间;
|
||||
项目 `.dsh/.gitignore` 只忽略 `brain/`,不会忽略整个 `.dsh`。
|
||||
|
||||
记忆工具默认走本地存储;只有当 `cloudMemoryEnabled=true` 且配置了
|
||||
memory 令牌时才切换为云端适配器。自动总结只保存用户明确表达的长期信息,
|
||||
自动画像只把明确偏好写入 USER.md,推测内容留在待确认区。Provider SDK
|
||||
来自 `src/mnemon/fork`,完整上游源码保存在 `vendor/dsh-mnemon`(独立 fork,
|
||||
包名 `dsh-brain-mnemon`)。详见 `docs/LOCAL_MEMORY_IMPLEMENTATION.md` 与
|
||||
`docs/MNEMON_FORK.md`;验收对照见 `docs/LOCAL_MEMORY_ACCEPTANCE.md`。
|
||||
|
||||
## Mnemon 集成(记忆空间 Provider)
|
||||
|
||||
自 0.2.0 起,本包同时是一个 Mnemon 记忆空间 Provider:Mnemon 管本地在场
|
||||
(运行时记忆每轮注入),长期记忆的每一次读、写都实时穿透到 LongMemory——
|
||||
云端是真源,本地不留长期副本。因此其他工具(Claude Code、Codex、看板)
|
||||
刚写进 LongMemory 的记忆,DSH 里立刻能召回。
|
||||
|
||||
启用方式:在 Mnemon 的记忆空间来源配置里给 providers 列表加一行
|
||||
本包同时保留 Mnemon 记忆空间 Provider 适配:Mnemon 管本地在场(运行时记忆
|
||||
每轮注入),云端 Provider 的每一次读、写都实时穿透到 LongMemory。启用方式:在 Mnemon 的记忆空间来源配置里给 providers 列表加一行
|
||||
(profile 覆盖或 bundle 配置均可),然后重启 DSH:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- use: dsh-cloud-memory/mnemon-provider
|
||||
- use: dsh-brain/mnemon-provider
|
||||
instanceId: longmemory
|
||||
```
|
||||
|
||||
之后在 Mnemon 的插件页会出现 LongMemory 的服务字段(Endpoint / Memory
|
||||
token),留空即复用本插件已有的 `cloud-memory.json` 配置,一处配置两处生效。
|
||||
每个记忆空间映射一个 LongMemory 项目:发现流程会自动列出账号下的全部
|
||||
项目,外加一个不分项目的「全部」空间;也可以在空间上手动填 Project ID。
|
||||
token / Project ID),留空即复用本插件已有的 `dsh-brain.json` 配置,一处
|
||||
配置两处生效。每个记忆空间映射一个 LongMemory 项目:发现流程会自动列出
|
||||
账号下的全部项目,外加一个不分项目的「全部」空间;也可以在空间上手动填
|
||||
Project ID。读取会校验命中的项目与空间一致(项目隔离)。
|
||||
|
||||
v1 范围:支持 发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;暂不支持
|
||||
删除(LongMemory 客户端接口没有删除操作)与图谱读取(接口未暴露,
|
||||
返回空图谱且能力声明为关)。离线时长期记忆不可用,Mnemon 的本地
|
||||
运行时记忆不受影响。
|
||||
v1 范围:支持发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;暂不支持删除
|
||||
(LongMemory 客户端接口没有删除操作)与图谱读取(接口未暴露,返回空图
|
||||
谱且能力声明为关)。写入按服务端回执区分「已存储 / 排队中(未确认)」。
|
||||
离线时长期记忆不可用,Mnemon 的本地运行时记忆不受影响。
|
||||
|
||||
本地长期记忆也通过 `dsh-brain/mnemon-native-provider` 暴露为 Mnemon Native Provider,使用 vendored `dsh-brain-mnemon.memory-space-provider/v1` 协议;验证:`node verify-mnemon-native.mjs`。
|
||||
|
||||
验证:`node verify-mnemon-provider.mjs`(对本地 stub 服务跑通
|
||||
发现→写入→召回→项目隔离全流程)。
|
||||
|
||||
## 技能同步
|
||||
|
||||
自 0.3.0 起,插件在记忆之外还双向同步技能:云端技能中心是总汇,本机
|
||||
技能目录(默认 `$DSH_HOME/skills`)是工作副本,本地的浏览、启停、分类
|
||||
仍归 DSH 技能管理器。插件启动 5 秒后首跑,之后每 15 分钟对账一次;
|
||||
结果与冲突列表见 `GET /cloud-memory/status` 的 `skills` 字段,聊天里
|
||||
也可以用 `skill_list` 工具查看云端清单。
|
||||
插件在记忆之外还双向同步技能:云端技能中心是总汇,本机技能目录(默认
|
||||
`$DSH_HOME/skills`)是工作副本,本地的浏览、启停、分类仍归技能管理页。
|
||||
插件启动 5 秒后首跑,之后每 15 分钟对账一次;结果与冲突列表见
|
||||
`GET /dsh-brain/status` 的 `skills` 字段,聊天里也可以用 `skill_list`
|
||||
工具查看云端清单。
|
||||
|
||||
- **下行**:云端技能按平台自己的规矩落地——先验整包清单哈希、再逐
|
||||
文件验 sha256,原子写入,并留下 `.manifest.json` 交付记录;云端标
|
||||
记了「脚本已变更待确认」的包不会自动安装,先在看板里确认。
|
||||
- **上行**:本地原创技能(管理器安装、导入或手写的)自动发布到云
|
||||
端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被
|
||||
别人先改过就报冲突、不强行覆盖。
|
||||
- **下行**:云端技能先验整包清单哈希、再逐文件验 sha256,原子写入(临时
|
||||
文件随机命名),并留下 `.manifest.json` 交付记录;文件路径逐个校验
|
||||
(相对路径、固定布局、扩展名白名单),路径穿越与校验和不符直接拒绝。
|
||||
云端标记了「脚本已变更待确认」的包不会自动安装,先在看板里确认。
|
||||
- **上行**:本地原创技能(管理器安装、导入或手写的)自动发布到云端;
|
||||
之后的修改以新修订发布,带 `expected_revision` 守卫,云端被别人先改过
|
||||
就报冲突、不强行覆盖。
|
||||
|
||||
防事故的规矩:先比内容,本地与云端逐字节一致时直接补交付记录,不传
|
||||
不覆盖;内容不同时按时间自动取较新的一边——云端 `updated_at` 更新就
|
||||
先备份本地再覆盖,本地文件 mtime 更新就发布新修订;只有时间相同或缺
|
||||
失时才报冲突(`locally_modified` / `name_collision` / `cloud_newer`),
|
||||
等面板里逐项确认。本地删除不删云端,且同版本不会被重新拉回(云端出
|
||||
了新版才会再下来)。面板里可逐项处理,也可用「全部保留本地 / 全部采用
|
||||
云端」批量处理(有二次确认,失败项会逐条汇总)。云端只接受固定布局(根目录只有 `SKILL.md`,
|
||||
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
|
||||
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
|
||||
`unsupported_layout`,不会为了迁就而裁剪文件。
|
||||
先备份本地再覆盖(备份在 `$DSH_HOME/.dsh-brain-backups/sync/`),本地
|
||||
文件 mtime 更新就发布新修订;只有时间相同或缺失时才报冲突
|
||||
(`locally_modified` / `name_collision` / `cloud_newer`),等面板里逐项
|
||||
确认。本地删除不删云端,且同版本不会被重新拉回(云端出了新版才会再
|
||||
下来)。面板里可逐项处理,也可用「全部保留本地 / 全部采用云端」批量处
|
||||
理(有二次确认,失败项会逐条汇总)。云端只接受固定布局(根目录只有
|
||||
`SKILL.md`,其余文件进 `references/`、`scripts/`、`assets/`,扩展名有
|
||||
白名单,单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能
|
||||
报 `unsupported_layout`,不会为了迁就而裁剪文件。
|
||||
|
||||
验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通
|
||||
下行安装、上行发布与修订、按时间自动上行/下行、内容一致自动认领、
|
||||
同名同时间保留冲突、脚本待审、布局拒绝、删除不传播全流程)。
|
||||
验证:`node verify-skills-sync.mjs` / `node verify-sync-resolve.mjs`
|
||||
(对本地 stub 技能中心跑通下行安装、上行发布与修订、按时间自动上行/
|
||||
下行、内容一致自动认领、同名同时间保留冲突、脚本待审、布局拒绝、删除
|
||||
不传播、批量解决全流程)。
|
||||
|
||||
## 技能管理(内置)
|
||||
|
||||
自 0.4.0 起,常用的本地管理也长在插件里,页面在 `/cloud-memory/skills`
|
||||
(配置页有链接进入):
|
||||
常用的本地管理也长在插件里,页面在 `/dsh-brain/skills`(配置页有链接
|
||||
进入):
|
||||
|
||||
- **列表**:本机全部技能,标注来源(云端交付 / 本地已传云端 / 本地)
|
||||
与云端修订号;
|
||||
- **列表**:本机全部技能,标注来源(云端交付 / 本地已传云端 / 本地)与
|
||||
云端修订号;
|
||||
- **启停**:停用是把技能文件夹挪到 `$DSH_HOME/skills-disabled/` 暂存
|
||||
——DSH 看不见它,自然不会加载;启用再挪回来。不碰 DSH 内部机制,
|
||||
可靠且可逆。同步引擎认识暂存区:停用的云端技能不会被拉回技能目
|
||||
录,云端出了新版会在暂存区里原地更新;
|
||||
- **删除**:真删,文件夹直接删除、不可恢复(页面上会先弹确认)。
|
||||
只删本地:云端副本不动,删掉的同版本也不会被同步重新拉回来;
|
||||
- **从 git 安装**:粘贴 https:// 或 file:// 仓库地址,浅克隆后把仓
|
||||
库里所有带 `SKILL.md` 的文件夹装进技能目录;不执行仓库里的任何
|
||||
代码,同名技能跳过不覆盖。
|
||||
可靠且可逆。同步引擎认识暂存区:停用的云端技能不会被拉回技能目录,
|
||||
云端出了新版会在暂存区里原地更新;
|
||||
- **删除**:真删,文件夹直接删除、不可恢复(页面上会先弹确认)。只删
|
||||
本地:云端副本不动,删掉的同版本也不会被同步重新拉回来;
|
||||
- **从 git 安装**:粘贴 https:// 或 file:// 仓库地址,浅克隆后把仓库里
|
||||
所有带 `SKILL.md` 的文件夹装进技能目录;不执行仓库里的任何代码,
|
||||
同名技能跳过不覆盖。
|
||||
|
||||
范围就到 DSH 技能目录这一处:技能市场的发现中心、扫描其它工具
|
||||
(Codex、Cursor 等)的技能目录不在内置范围——还需要那些的话继续
|
||||
留着第三方管理器,两边不冲突;不需要的话现在可以卸掉它了。
|
||||
范围就到 DSH 技能目录这一处:技能市场的发现中心、扫描其它工具(Codex、
|
||||
Cursor 等)的技能目录不在内置范围——还需要那些的话继续留着第三方管
|
||||
理器,两边不冲突;不需要的话现在可以卸掉它了。
|
||||
|
||||
验证:`node verify-skill-admin.mjs`(列表与来源判定、启停、真删、
|
||||
git 安装与同名跳过、以及停用技能与同步引擎的配合共 15 项)。
|
||||
验证:`node verify-skill-admin.mjs`(列表与来源判定、启停、真删、git 安装
|
||||
与同名跳过、以及停用技能与同步引擎的配合)。
|
||||
|
||||
## HTTP 接口
|
||||
|
||||
主路径 `/dsh-brain/*`(旧 `/cloud-memory/*` 保留为别名):
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/cloud-memory` | 配置页面 |
|
||||
| GET | `/cloud-memory/status` | 设置 + 上报计数 + 最近 50 条记录(令牌只返回掩码) |
|
||||
| PUT | `/cloud-memory/config` | 应用设置补丁(令牌留空表示不修改) |
|
||||
| POST | `/cloud-memory/login` | 账号密码登录,换取两个令牌并保存(密码不落盘) |
|
||||
| POST | `/cloud-memory/test` | 分别校验两个令牌(活动令牌用空载荷探测,鉴权先于载荷校验,返回 400 即代表令牌有效,不会写入记录) |
|
||||
| POST | `/cloud-memory/flush` | 立即补发待重试队列 |
|
||||
| GET | `/dsh-brain` | 配置页面 |
|
||||
| GET | `/dsh-brain/status` | 设置 + 上报计数 + 最近 50 条记录 + 技能同步状态(令牌只返回掩码) |
|
||||
| GET | `/dsh-brain/capabilities` | 能力声明(按已启用的子插件聚合) |
|
||||
| PUT | `/dsh-brain/config` | 应用设置补丁(令牌留空表示不修改) |
|
||||
| POST | `/dsh-brain/login` | 账号密码登录,换取令牌并保存(密码不落盘;失败的 scope 同时清除旧令牌) |
|
||||
| POST | `/dsh-brain/test` | 分别校验令牌(活动令牌用空载荷探测,鉴权先于载荷校验,返回 400 即代表令牌有效,不会写入记录) |
|
||||
| POST | `/dsh-brain/flush` | 立即补发待重试队列(总开关关闭时不补发) |
|
||||
| GET | `/dsh-brain/sync/status` · POST `/dsh-brain/sync/run` | 同步状态 / 立即同步(run 要求同源 JSON POST) |
|
||||
| POST | `/dsh-brain/sync/resolve` · `/dsh-brain/sync/resolve-all` | 逐项 / 批量解决冲突 |
|
||||
|
||||
写接口会校验同源 `Origin`,跨站请求返回 403。
|
||||
写接口会校验同源 `Origin` 与 `Content-Type: application/json`,跨站请求
|
||||
返回 403/415。
|
||||
|
||||
## 状态语义
|
||||
|
||||
|
|
@ -190,10 +248,19 @@ git 安装与同名跳过、以及停用技能与同步引擎的配合共 15 项
|
|||
|
||||
## 故障排查
|
||||
|
||||
- **热力图不涨**:看 `/cloud-memory/status` 的 `reporter.skipped` 与 `lastError`;常见原因是没配 `activityToken`、插件被 `enabled:false` 关掉,或令牌缺 `activity:write` scope。
|
||||
- **工具报“未配置记忆令牌”**:填 `memoryToken`;写入还需要云端已配置 WebDAV 主存储(否则服务端 409 `storage_not_configured`)。
|
||||
- **网络不可用**:上报会进队列,恢复后 30 秒内自动补发;也可以在配置页点“重试上报队列”。
|
||||
- **令牌泄漏风险**:令牌只存在本机 JSON 文件里,页面只回显掩码(`cmt_act…0001`)。文件权限依赖用户目录 ACL(Windows 无 POSIX 位)。
|
||||
- **热力图不涨**:看 `/dsh-brain/status` 的 `reporter.skipped` 与
|
||||
`lastError`;常见原因是没配 `activityToken`、`activityEnabled:false`、
|
||||
总开关 `enabled:false`,或令牌缺 `activity:write` scope。
|
||||
- **工具报「未配置记忆令牌」**:填 `memoryToken`(配置页或环境变量——
|
||||
环境变量需同时设置正确的 `DSH_BRAIN_TOKEN_ORIGIN`);写入还需要云端
|
||||
已配置 WebDAV 主存储(否则服务端 409 `storage_not_configured`)。
|
||||
- **环境变量令牌不生效**:检查 `DSH_BRAIN_TOKEN_ORIGIN` 是否设置且等于
|
||||
当前 `baseUrl` 的 origin(`https://host:port` 形式);origin 不匹配时
|
||||
插件有意忽略环境变量。
|
||||
- **网络不可用**:上报会进队列,恢复后 30 秒内自动补发;也可以在配置页
|
||||
点「重试上报队列」。
|
||||
- **令牌泄漏风险**:令牌只存在本机 JSON 文件里,页面只回显掩码
|
||||
(`cmt_act…0001`)。文件权限依赖用户目录 ACL(Windows 无 POSIX 位)。
|
||||
|
||||
## 开发与发布
|
||||
|
||||
|
|
@ -208,31 +275,54 @@ node scripts/pack-guard.mjs # 白名单与脱敏闸门,不通
|
|||
pnpm publish --access public --no-git-checks
|
||||
```
|
||||
|
||||
`prepack` 会先重建 `lib/`,`prepublishOnly` 会先跑 `pack-guard`:包里一旦出现 `AGENTS.md`、`TODO.md`、`*.mjs` 探测脚本、`tsconfig*.json`、本机路径、个人域名或令牌原文,发布立刻中止。
|
||||
`prepack` 会先重建 `lib/`,`prepublishOnly` 会先跑 `pack-guard`:包里一旦
|
||||
出现 `AGENTS.md`、`TODO.md`、`*.mjs` 探测脚本、`tsconfig*.json`、本机路径、
|
||||
个人域名或令牌原文,发布立刻中止。
|
||||
|
||||
> lifecycle 脚本要求 `node` 在 `PATH` 里。若报 `'node' is not recognized`,先把 DSH 运行时自带 node 的 `bin` 目录加进 `$env:Path` 再发布。
|
||||
> lifecycle 脚本要求 `node` 在 `PATH` 里。若报 `'node' is not recognized`,
|
||||
> 先把 DSH 运行时自带 node 的 `bin` 目录加进 `$env:Path` 再发布。
|
||||
|
||||
## 统一管理卡(0.7.0)
|
||||
## 统一管理卡
|
||||
|
||||
「设置 → 云端记忆」现在是三个页签:**连接与上报 / 技能管理 / MCP 管理**。
|
||||
「设置 → 云端记忆」是三个页签:**连接与上报 / 技能管理 / MCP 管理**。
|
||||
|
||||
- 身份验证卡内切换「账号登录 / 手动令牌」,切换不清凭据、不发请求。
|
||||
- 服务地址换 origin 时,旧令牌一律清除(`credentialsCleared`),要求重新认证。
|
||||
- 技能安装是两步:`install/plan` 把仓库克隆到隔离暂存目录并列出候选(含冲突、脚本、体积),`install/commit` 只写入选中的目录;`.git` 与符号链接不复制,仓库脚本不执行。
|
||||
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
|
||||
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。
|
||||
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
|
||||
- **同步冲突(P3)**:`sync/status|run|resolve|resolve-all` 提供两侧信息;面板支持逐项「保留本地 / 采用云端 / 手动合并」,也支持「全部保留本地 / 全部采用云端」批量处理(二次确认,逐项失败会汇总提示)。
|
||||
- **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治理策略。
|
||||
- 服务地址换 origin 时,旧令牌一律清除(`credentialsCleared`),要求重新
|
||||
认证;环境变量令牌也会因 origin 绑定而失效。
|
||||
- 技能安装是两步:`install/plan` 把仓库克隆到隔离暂存目录并列出候选
|
||||
(含冲突、脚本、体积),`install/commit` 只写入选中的目录;`.git` 与
|
||||
符号链接不复制,仓库脚本不执行。
|
||||
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示
|
||||
并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
|
||||
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的
|
||||
`.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)
|
||||
→勾选安装。客户端只传 provider/id,从不传 URL。
|
||||
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply`
|
||||
与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
|
||||
- **同步冲突(P3)**:`sync/status|run|resolve|resolve-all` 提供两侧信息;
|
||||
面板支持逐项「保留本地 / 采用云端 / 手动合并」,也支持「全部保留本地 /
|
||||
全部采用云端」批量处理(二次确认,逐项失败会汇总提示)。
|
||||
- **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口
|
||||
`/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移
|
||||
除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治
|
||||
理策略。停用 `dsh-brain-mcp` 子插件只隐藏 MCP 页签与能力声明,不影响
|
||||
宿主连接本身;本插件不做 MCP 配置的云端同步。
|
||||
|
||||
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。
|
||||
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含
|
||||
`verify-market` / `verify-skill-update` / `verify-sync-resolve` /
|
||||
`verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` /
|
||||
`verify-review-fixes` / `verify-theme`)。
|
||||
|
||||
### 技能来源树
|
||||
|
||||
「技能管理」按软件来源分组(DSH / 公共 Agent / Codex / WorkBuddy / Claude Code / OpenCode),
|
||||
每个来源下是分类,分类下是技能:
|
||||
「技能管理」按软件来源分组(DSH / 公共 Agent / Codex / WorkBuddy /
|
||||
Claude Code / OpenCode),每个来源下是分类,分类下是技能:
|
||||
|
||||
- 分类只记在 `$DSH_HOME/cloud-memory-skill-groups.json` 里,**不移动文件**;删除分类只是把技能放回「未分类」。
|
||||
- 只有 DSH 来源的开关是真的(目录移入/移出 `skills-disabled`,新会话生效);其他软件的目录本卡只读,开关标记为「仅本卡」。
|
||||
- 来源行提供「+ 新建分类」「打开目录」「来源开关」;分类行提供「+ 加入技能 / 改名 / 删除 / 分类开关」;技能行提供详情、启停、卸载。
|
||||
- 预览(真实数据、光照/暗色):`node preview-card.mjs` 生成 `_preview/skill-tree*.png`。
|
||||
- 分类只记在 `$DSH_HOME/dsh-brain-skill-groups.json` 里,**不移动文件**;
|
||||
删除分类只是把技能放回「未分类」。
|
||||
- 只有 DSH 来源的开关是真的(目录移入/移出 `skills-disabled`,新会话生
|
||||
效);其他软件的目录本卡只读,开关标记为「仅本卡」。
|
||||
- 来源行提供「+ 新建分类」「打开目录」「来源开关」;分类行提供「+ 加入
|
||||
技能 / 改名 / 删除 / 分类开关」;技能行提供详情、启停、卸载。
|
||||
- 预览(真实数据、光照/暗色):`node preview-card.mjs` 生成
|
||||
`_preview/skill-tree*.png`。
|
||||
|
|
|
|||
|
|
@ -939,9 +939,9 @@ window.__ModuleLoader__.load({
|
|||
else patch({ status: 'error', error: bodyError(res, '读取同步状态失败') })
|
||||
}, function (error) { patch({ status: 'error', error: messageOf(error) }) })
|
||||
}
|
||||
function resolve(name, action) {
|
||||
function resolve(name, action, conflictId) {
|
||||
patch({ busy: name + ':' + action, notice: null })
|
||||
postJson(API.sync + '/resolve', { name: name, action: action }).then(function (res) {
|
||||
postJson(API.sync + '/resolve', { name: name, action: action, conflictId: conflictId }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
var stats = state.data === null ? null : state.data.stats
|
||||
patch({ busy: '', data: { stats: stats, conflicts: res.body.conflicts || [] }, notice: { tone: 'ok', text: name + ':' + (res.body.note || '已处理') } })
|
||||
|
|
@ -959,7 +959,7 @@ window.__ModuleLoader__.load({
|
|||
function resolveAll(action) {
|
||||
if (conflicts.length === 0) { patch({ pendingAll: null }); return }
|
||||
patch({ busy: 'all:' + action, notice: null })
|
||||
postJson(API.sync + '/resolve-all', { action: action }).then(function (res) {
|
||||
postJson(API.sync + '/resolve-all', { action: action, conflictIds: conflicts.map(function (item) { return item.conflictId }) }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
var resolved = Array.isArray(res.body.resolved) ? res.body.resolved : []
|
||||
var failed = Array.isArray(res.body.failed) ? res.body.failed : []
|
||||
|
|
@ -993,9 +993,9 @@ window.__ModuleLoader__.load({
|
|||
),
|
||||
h('p', { style: styles.hint }, conflict.note),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { label: '保留本地', variant: 'small', disabled: state.busy !== '' || conflict.canKeepLocal !== true, onClick: function () { resolve(conflict.name, 'keep_local') } }),
|
||||
h(Btn, { label: '采用云端', variant: 'small', disabled: state.busy !== '' || conflict.canTakeCloud !== true, onClick: function () { resolve(conflict.name, 'take_cloud') } }),
|
||||
h(Btn, { label: '手动合并', variant: 'small', disabled: state.busy !== '', onClick: function () { resolve(conflict.name, 'manual') } }),
|
||||
h(Btn, { label: '保留本地', variant: 'small', disabled: state.busy !== '' || conflict.canKeepLocal !== true, onClick: function () { resolve(conflict.name, 'keep_local', conflict.conflictId) } }),
|
||||
h(Btn, { label: '采用云端', variant: 'small', disabled: state.busy !== '' || conflict.canTakeCloud !== true, onClick: function () { resolve(conflict.name, 'take_cloud', conflict.conflictId) } }),
|
||||
h(Btn, { label: '手动合并', variant: 'small', disabled: state.busy !== '', onClick: function () { resolve(conflict.name, 'manual', conflict.conflictId) } }),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
|
@ -2227,6 +2227,16 @@ window.__ModuleLoader__.load({
|
|||
var activityToken = tokens.activity === undefined ? {} : tokens.activity
|
||||
var memoryToken = tokens.memory === undefined ? {} : tokens.memory
|
||||
var summaryToken = tokens.summary === undefined ? {} : tokens.summary
|
||||
// Token source label: where the effective credential comes from. An env
|
||||
// token only applies when its origin binding matches the service origin.
|
||||
var tokenHint = function (view) {
|
||||
if (view.configured !== true) {
|
||||
if (view.source === 'env') return '来自环境变量(DSH_BRAIN_*_TOKEN,绑定当前 origin)'
|
||||
return undefined
|
||||
}
|
||||
if (view.source === 'env') return '当前:' + String(view.masked) + '(来自环境变量,绑定当前 origin)'
|
||||
return '当前:' + String(view.masked)
|
||||
}
|
||||
var checkedAt = checkSource === null ? '—' : formatTime(checkSource.at === undefined ? checkSource.checkedAt : checkSource.at)
|
||||
|
||||
var connectivity = !draft.baseUrlConfigured
|
||||
|
|
@ -2369,7 +2379,7 @@ window.__ModuleLoader__.load({
|
|||
type: 'password',
|
||||
value: tokenDraft.activity,
|
||||
placeholder: activityToken.configured === true ? '已配置 ' + String(activityToken.masked) + ',留空表示不修改' : '未配置',
|
||||
hint: activityToken.configured === true ? '当前:' + String(activityToken.masked) : undefined,
|
||||
hint: tokenHint(activityToken),
|
||||
onChange: function (value) {
|
||||
patchTokens({ activity: value })
|
||||
},
|
||||
|
|
@ -2379,7 +2389,7 @@ window.__ModuleLoader__.load({
|
|||
type: 'password',
|
||||
value: tokenDraft.memory,
|
||||
placeholder: memoryToken.configured === true ? '已配置 ' + String(memoryToken.masked) + ',留空表示不修改' : '未配置',
|
||||
hint: memoryToken.configured === true ? '当前:' + String(memoryToken.masked) : undefined,
|
||||
hint: tokenHint(memoryToken),
|
||||
onChange: function (value) {
|
||||
patchTokens({ memory: value })
|
||||
},
|
||||
|
|
@ -2389,7 +2399,7 @@ window.__ModuleLoader__.load({
|
|||
type: 'password',
|
||||
value: tokenDraft.summary,
|
||||
placeholder: summaryToken.configured === true ? '已配置 ' + String(summaryToken.masked) + ',留空表示不修改' : '未配置',
|
||||
hint: summaryToken.configured === true ? '当前:' + String(summaryToken.masked) : undefined,
|
||||
hint: tokenHint(summaryToken),
|
||||
onChange: function (value) {
|
||||
patchTokens({ summary: value })
|
||||
},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,122 @@
|
|||
# Local Memory Phase 1 Acceptance
|
||||
|
||||
Date: 2026-11-24 (Asia/Shanghai)
|
||||
|
||||
Scope: the local-first phase described by `docs/plans/LOCAL_MEMORY_PLAN.md`.
|
||||
Cloud synchronization is deliberately **not** implemented in this phase (plan
|
||||
section 15); the local layer remains usable without an account, token or network.
|
||||
|
||||
## Commands and results
|
||||
|
||||
| Command | Result |
|
||||
| --- | --- |
|
||||
| `node verify-local-memory.mjs` | ALL 22 CHECKS PASSED |
|
||||
| `node verify-local-memory-acceptance.mjs` | ALL 23 CHECKS PASSED |
|
||||
| `node verify-local-memory-round3.mjs` | ALL 19 CHECKS PASSED |
|
||||
| `node verify-auto-summary-round3.mjs` | ALL 7 CHECKS PASSED |
|
||||
| `node verify-memory-switches-round3.mjs` | ALL 5 CHECKS PASSED |
|
||||
| `node verify-skill-sync-round2.mjs` | ALL 13 CHECKS PASSED |
|
||||
| `node verify-sync-resolve.mjs` | 23/23 passed |
|
||||
| `node verify-skill-sync-scope-round3.mjs` | ALL 2 CHECKS PASSED |
|
||||
| `node verify-skill-sync-conflict-round5.mjs` | ALL 5 CHECKS PASSED |
|
||||
| `node verify-local-memory-round4.mjs` | ALL 12 CHECKS PASSED |
|
||||
| `node verify-local-memory-round5.mjs` | ALL 6 CHECKS PASSED |
|
||||
| `node verify-local-memory-round6.mjs` | ALL 8 CHECKS PASSED |
|
||||
| `node verify-auto-summary-host-retry-round5.mjs` | ALL 3 CHECKS PASSED |
|
||||
| `node verify-skill-update.mjs` | 16/16 passed |
|
||||
| `node verify-mnemon-native.mjs` | ALL 6 CHECKS PASSED |
|
||||
| `node verify-mnemon-fork.mjs` | ALL 23 CHECKS PASSED |
|
||||
| `node verify-mnemon-provider.mjs` | ALL 14 CHECKS PASSED |
|
||||
| `node scripts/verify-all.mjs` | 38 scripts: 38 passed (1 with environmental skips), all green |
|
||||
|
||||
## Acceptance mapping
|
||||
|
||||
| # | Criterion | Evidence |
|
||||
| --- | --- | --- |
|
||||
| 1 | Fresh environment can use memory without manual space creation | `verify-local-memory-acceptance.mjs` check 1 |
|
||||
| 2 | One global and one current-project space are created automatically | check 2 |
|
||||
| 3 | Restart / repeated initialization does not duplicate spaces | checks 3, 13 |
|
||||
| 4 | Global and project directories follow `.dsh/brain`, no `.mnemon` | check 4 |
|
||||
| 5 | Offline / no-account / no-cloud-config local use works | check 5 and `verify-local-memory.mjs` |
|
||||
| 6 | Cloud adapter receives zero calls when sync is off | checks 16, 17 |
|
||||
| 7 | Automatic summary is incremental, deduplicated, source-traceable and compactly projected | checks 10, 22 |
|
||||
| 8 | Automatic profile stores only explicit preferences; one-off wording is ignored; correction invalidates the old text | checks 9, 11, 23 |
|
||||
| 9 | Default search covers current project + global and caps results | checks 6, 7, 8 |
|
||||
| 10 | Update / delete / concurrent writes / restart do not lose or duplicate records | checks 12, 13; tombstone check in `verify-local-memory.mjs` |
|
||||
| 11 | Project `.dsh/brain` is not committed by default | check 19 |
|
||||
| 12 | Existing Source / Provider / Strategy / Skill / public interfaces remain available | `verify-all.mjs`, `verify-mnemon-provider.mjs` |
|
||||
| 13 | Settings page never accesses SQLite, CLI or Provider internals | check 18 |
|
||||
| 14 | Legacy migration is verifiable and rollbackable, original files remain | check 15 |
|
||||
| 15 | Automatic summary and manual writes never store secrets | checks 20, 21 |
|
||||
|
||||
## Fourth-round regression mapping
|
||||
|
||||
| Area | Assertions |
|
||||
| --- | --- |
|
||||
| Migration rollback | occupied destination failure leaves active records intact; retry restores and repeated rollback is safe; parallel migration receipts |
|
||||
| Summary document transaction | corrupt index, index success + Markdown failure, retry, replay and duplicate prevention |
|
||||
| Conflict scope | connection snapshot test plus existing account-isolation assertions |
|
||||
| Profile validation | empty/secret update rejected without changing the old record |
|
||||
| Skill rollback | added/changed/removed file statistics checked in `verify-skill-update.mjs` |
|
||||
|
||||
## Third-round regression mapping
|
||||
|
||||
| Area | Assertions |
|
||||
| --- | --- |
|
||||
| Workspace isolation | `verify-local-memory-round3.mjs` A/B writes, searches, reads and shared global state |
|
||||
| Storage safety | concurrent first initialization; corrupt JSON preserved; projection retry; 1005-record pagination |
|
||||
| Summary events | `verify-auto-summary-round3.mjs` structured text, injected-content exclusion, three replays, empty replay, one-off rule |
|
||||
| Query scope | project filter before `k` truncation; filtered list total and offset |
|
||||
| Memory switches | `verify-memory-switches-round3.mjs` local/cloud/all-off combinations and status without side effects |
|
||||
| Skill sync | uploaded-file deletion, different local folder name, connection snapshot, existing account isolation |
|
||||
|
||||
## Fix found during acceptance
|
||||
|
||||
`LocalMemoryManager.createBackup()` originally asked `fs.cp` to copy the whole
|
||||
global root into a subdirectory of itself, which fails with
|
||||
`ERR_FS_CP_EINVAL` on Windows and Node 24. It now creates the backup directory
|
||||
and copies each top-level entry except `backups` into it. The acceptance test
|
||||
check 14 covers this regression.
|
||||
|
||||
## Fifth-round regression mapping
|
||||
|
||||
| Area | Assertions |
|
||||
| --- | --- |
|
||||
| Rollback final copy | destination child conflict fails before active mutation; retry and restore copy remain valid |
|
||||
| Re-import after rollback | re-migration restores exactly one active record; repeated migration deduplicates |
|
||||
| Host summary retry | host event failure keeps the pending turn; retry after document repair creates one summary |
|
||||
| Conflict confirmation | conflict preview carries conflictId/scope/local/cloud versions; stale confirmation is rejected |
|
||||
|
||||
## Sixth-round regression mapping
|
||||
|
||||
| Area | Assertions |
|
||||
| --- | --- |
|
||||
| Migration ownership | content-only duplicate is not owned; mixed existing/new rollback removes only the new record |
|
||||
| Restore safety | non-empty target rejected before active mutation; completed rollback copy path verified |
|
||||
| Workspace-scoped rollback | migration initiated in A and rolled back from B uses A's receipt target |
|
||||
| Conflict/alias | preview-bound confirmation; physical directory aliases preserved (round-5/round-2 scripts) |
|
||||
|
||||
## Environment limits
|
||||
|
||||
- Verified with Node 24.21.0 and the bundled TypeScript toolchain. Node 20 was
|
||||
not installed in this environment; the package engine remains `>=20`.
|
||||
- `pnpm install --lockfile-only --ignore-scripts` regenerated the lockfile with
|
||||
the root Mnemon dependency removed. A clean frozen install was not re-run;
|
||||
the offline mirror lacked the metadata needed for that check.
|
||||
- Real DSH host MCP, a real Mnemon host process and a real cloud endpoint were
|
||||
not exercised. `verify-mcp-bridge.mjs` is excluded from the default suite;
|
||||
run it explicitly with `DSH_VERIFY_REAL_MCP=1`. The provider registration
|
||||
test uses a host-shaped fake and temporary files.
|
||||
- The host-event pending-summary queue is in-process only; restart persistence
|
||||
is not implemented in this phase.
|
||||
|
||||
## Not covered in this phase
|
||||
|
||||
- Real cloud push/pull, cloud change cursors, remote conflict merge and external
|
||||
Provider adapters (plan section 15; later cloud-sync).
|
||||
- The full upstream Mnemon runtime is not loaded automatically as dsh-brain's
|
||||
active engine: the complete source fork is in `vendor/dsh-mnemon`, the active
|
||||
provider SDK subset is `src/mnemon/fork`, and the local native provider entry
|
||||
is `src/mnemon/native.ts` (host registration covered by `verify-mnemon-native.mjs`).
|
||||
- Cross-process file-lock behavior under adversarial operating-system failures;
|
||||
normal concurrent writes and restart behavior are covered.
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
# Local Memory Implementation (Phase 1)
|
||||
|
||||
This repository now implements the local-first memory phase from
|
||||
`docs/plans/LOCAL_MEMORY_PLAN.md`. Cloud syncing remains disabled by default
|
||||
and no local memory operation requires an account, token or network.
|
||||
|
||||
## Layout
|
||||
|
||||
- Global: `$DSH_HOME/brain/`
|
||||
- `runtime/memories.json` — local JSON record store
|
||||
- `runtime/USER.md`, `runtime/MEMORY.md` — generated compact projections
|
||||
- `spaces/global/space.json` — stable global space marker
|
||||
- `backups/`, `state/`
|
||||
- Project: `<project>/.dsh/brain/`
|
||||
- `documents/` — project summaries and decisions
|
||||
- `memory-space/` — project memory records and space marker
|
||||
- `state/`
|
||||
- The project `.dsh/.gitignore` ignores `brain/` only; it does not ignore
|
||||
the rest of `.dsh`.
|
||||
- No `.mnemon` directory is created.
|
||||
|
||||
## Management API
|
||||
|
||||
The settings-ui bundle exposes a local-memory management surface under
|
||||
`/dsh-brain/local-memory`:
|
||||
|
||||
- `GET /status` — storage roots, space markers and sync switches;
|
||||
- `GET /spaces` and `GET /documents` — available spaces and project documents;
|
||||
- `GET /memories?limit=&offset=` — paginated local records;
|
||||
- `GET /search?q=&k=` — bounded local search over the project and global spaces;
|
||||
- `POST /forget` — revision-checked tombstone delete;
|
||||
- `POST /backup` — create a copy of the global brain root;
|
||||
- `GET|POST /migrate` — inspect legacy `.mnemon` locations, copy one into
|
||||
backups, or roll a copied backup into a new destination.
|
||||
|
||||
All write routes require a same-origin request. These routes only use
|
||||
`LocalMemoryManager`'s public methods and never touch SQLite, CLI or provider
|
||||
privates.
|
||||
|
||||
## Data model
|
||||
|
||||
Every memory record has a unique id, scope, space id, content, category,
|
||||
tags, source, created/updated timestamps, revision (starting at 1), a local
|
||||
monotonic `changeSeq`, and a tombstone flag for deletes. Writes are atomic and
|
||||
serialized through a per-space lock. Exact duplicate content returns the
|
||||
existing record with `duplicate: true`.
|
||||
|
||||
## Automatic behavior
|
||||
|
||||
- Global and project spaces are created lazily and idempotently on first memory
|
||||
use; restarting or opening multiple windows reuses the same markers.
|
||||
- Explicit long-term statements from user turns are captured incrementally into
|
||||
USER.md/MEMORY.md by `LocalMemoryManager.summarizeConversation`; assistant
|
||||
text and raw transcripts are never stored by that path.
|
||||
- The generated USER.md/MEMORY.md files are exposed as a compact system-prompt
|
||||
section (`dsh-brain:local-memory`) once per turn; they are not re-injected in
|
||||
full and are empty when local memory is disabled.
|
||||
- `proposeProfile(..., inferred=true)` keeps inferred behavior in a pending
|
||||
area; only explicit entries are projected into USER.md. `correctProfile`
|
||||
increments the revision and regenerates the projection.
|
||||
- Search defaults to the project and global spaces only and returns five items.
|
||||
- Cloud memory is selected only when `cloudMemoryEnabled` is true **and** a
|
||||
memory token is configured; otherwise the memory tools use the local remote.
|
||||
|
||||
## Migration
|
||||
|
||||
`legacyMigrationReport()` reports existing `.mnemon` locations without moving
|
||||
anything. `migrateLegacy(path)` copies a legacy tree into `backups/` and records
|
||||
the operation in `state/migrations.json`; `rollbackMigration(backup, destination)`
|
||||
copies it back to a new location. Neither operation deletes the original.
|
||||
|
||||
## Verification
|
||||
|
||||
`node verify-local-memory.mjs` covers directory creation, idempotent spaces,
|
||||
deduplication, revisions/tombstones, restart persistence, summary/profile
|
||||
projections, documents, migration reporting and the local memory remote.
|
||||
`node scripts/verify-all.mjs` runs the complete repository suite.
|
||||
`node verify-local-memory-acceptance.mjs` and `docs/LOCAL_MEMORY_ACCEPTANCE.md`
|
||||
map the plan criteria to executable evidence.
|
||||
|
||||
## Workspace and reliability
|
||||
|
||||
- Every tool/session operation runs inside `LocalMemoryManager.withWorkspace`
|
||||
(AsyncLocalStorage). Project stores and document stores are cached per
|
||||
normalized workspace path, not per manager instance, so switching A to B in
|
||||
one process cannot read A's project records.
|
||||
- `JsonMemoryStore` and `JsonDocumentStore` distinguish a missing data file from
|
||||
a corrupt or incompatible one. Corrupt files are preserved and reported; only
|
||||
a missing file initializes an empty store.
|
||||
- Initialization, project mapping, session checkpoints and projection writes
|
||||
use per-target file locks and unique temporary names. A committed memory write
|
||||
with a failed projection leaves `state/projection.json` dirty; the next
|
||||
`ensureGlobal()` retries it.
|
||||
- `src/mnemon/native.ts` exposes the local store as a Mnemon Native provider
|
||||
using the vendored `dsh-brain-mnemon.memory-space-provider/v1` contract.
|
||||
|
||||
## Mnemon fork and remaining gaps
|
||||
|
||||
`vendor/dsh-mnemon` is the independent `dsh-brain-mnemon` source fork of
|
||||
`omdsh-dev/dsh-mnemon` (upstream revision `8b650ab5ef33522e03887b250b13336593daa26f`,
|
||||
0.5.54, MIT). It retains the complete upstream Monorepo source, including
|
||||
Runtime, Documents, Memory Spaces, Skills Source, Mnemon Native, all external
|
||||
Provider plugins and all strategy plugins. See `docs/MNEMON_FORK.md` and
|
||||
`vendor/dsh-mnemon/FORK_NOTICE.md`.
|
||||
|
||||
The provider-SDK subset used by dsh-brain is copied to `src/mnemon/fork`; the
|
||||
package no longer depends on `dsh-mnemon-source-memory-spaces`. The local JSON
|
||||
engine above remains the phase-1 kernel behind the public memory tools. Loading
|
||||
the full upstream Mnemon runtime as the memory engine, cloud change cursors,
|
||||
remote conflict merge and external Provider adapters remain later cloud-sync
|
||||
work.
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
# Mnemon fork (dsh-brain)
|
||||
|
||||
## Status
|
||||
|
||||
- Fork location: `vendor/dsh-mnemon`
|
||||
- Fork package: `dsh-brain-mnemon` `0.5.54-dsh.1` (private)
|
||||
- Upstream: `omdsh-dev/dsh-mnemon`
|
||||
- Upstream revision: `8b650ab5ef33522e03887b250b13336593daa26f`
|
||||
- Upstream version: `0.5.54`
|
||||
- License: MIT, Copyright (c) 2026 dsh-external contributors
|
||||
|
||||
The snapshot contains the complete upstream Monorepo source: core/host/client/sdk,
|
||||
Runtime, Documents, Memory Spaces, Skills Source, Mnemon Native, every external
|
||||
Provider plugin and every strategy plugin. Upstream docs, changelogs and the MIT
|
||||
license/third-party notices are kept as-is.
|
||||
|
||||
## Identity policy
|
||||
|
||||
Every package name, import specifier, runtime schema id, bundle entry id and
|
||||
plugin directory has been rewritten from `dsh-mnemon` to `dsh-brain-mnemon`.
|
||||
The root package is marked private and records its upstream provenance in
|
||||
`package.json#dshBrainFork` and `FORK_NOTICE.md`. Upstream repository URLs,
|
||||
copyright notices and license files are preserved.
|
||||
|
||||
## Active integration
|
||||
|
||||
`src/mnemon/fork` is the provider-SDK subset dsh-brain actually builds against.
|
||||
It mirrors `plugins/dsh-mnemon-source-memory-spaces/src` from the same upstream
|
||||
revision with a local contract adapter, and is imported by `src/mnemon/index.ts`,
|
||||
`src/mnemon/descriptor.ts` and `src/mnemon/driver.ts`. dsh-brain no longer
|
||||
declares `dsh-mnemon-source-memory-spaces` as a peer or dev dependency.
|
||||
|
||||
## Sync and verification
|
||||
|
||||
Regenerate the snapshot with:
|
||||
|
||||
```bash
|
||||
node scripts/fork-mnemon.mjs --source <upstream-checkout> --target vendor/dsh-mnemon --force
|
||||
node scripts/fork-mnemon.mjs --check
|
||||
node verify-mnemon-fork.mjs
|
||||
```
|
||||
|
||||
Update `PINNED_REVISION` and `PINNED_VERSION` in `scripts/fork-mnemon.mjs` when
|
||||
syncing. Review the diff and keep `LICENSE`, `THIRD_PARTY_NOTICES.md` and
|
||||
`FORK_NOTICE.md` intact.
|
||||
|
||||
## Current scope
|
||||
|
||||
The fork snapshot is complete, but dsh-brain currently loads only its local
|
||||
provider-SDK subset and the phase-1 local JSON memory engine. Loading the full
|
||||
upstream Mnemon runtime as the memory engine, cloud change cursors, remote
|
||||
conflict merging and external Provider adapters remain later cloud-sync work.
|
||||
|
||||
## Native provider entry
|
||||
|
||||
`src/mnemon/native.ts` exposes the local JSON memory store through the vendored
|
||||
provider contract `dsh-brain-mnemon.memory-space-provider/v1`. Its manifest and
|
||||
actual host `install()` path are covered by `verify-mnemon-native.mjs`, including
|
||||
remember / search / get / forget against a temporary project workspace.
|
||||
|
||||
## Cloud-sync handoff
|
||||
|
||||
The later cloud-sync layer must add, rather than assume, these semantics on top of
|
||||
the provider protocol:
|
||||
|
||||
- local `changeSeq` is not a cloud `change_id`; each sync stream needs a durable
|
||||
cloud cursor and a local outbox state (`pending` / `pushed` / `acknowledged`);
|
||||
- idempotency keys per write/delete operation, plus retry and backoff policy;
|
||||
- revision-based conflict detection and a merge/quarantine result instead of
|
||||
last-write-wins;
|
||||
- tombstone/delete events because some providers hard-delete and cannot expose
|
||||
deletions through browse;
|
||||
- Provider transport adapters reusing connection discovery, status, search,
|
||||
read/write, graph, timeout, cancellation and redaction;
|
||||
- separate switches for memory sync and Skill sync, and an explicit first-sync
|
||||
scope confirmation for spaces, profile and project documents.
|
||||
|
||||
The current phase intentionally does not implement cloud push/pull or conflict
|
||||
merge (plan section 15).
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
# 部门(Departments)规划
|
||||
|
||||
版本:v1(规划稿,本会话只做规划,不实施)
|
||||
日期:2026-11-24
|
||||
来源:主会话 11-24 16:05–17:04 的讨论定论 + 已验收的库层实现。
|
||||
|
||||
## 1. 概念定稿(用户确认)
|
||||
|
||||
- **部门 = 专家**,同一概念的两种叫法,统一用"部门"。
|
||||
- 部门是一个**可复用的长期工作身份**:每次使用沉淀一点记忆,
|
||||
久了靠压缩上下文延续——不是另起一套 Agent 运行时。
|
||||
- 记忆三层:部门私有记忆 + 项目记忆 + 全局记忆,按需注入,
|
||||
不全量塞上下文。
|
||||
- billion-context 继续做**独立工具**,不内置进记忆系统
|
||||
(16:35 用户拍板:"听你的 bc 继续用做独立的")。
|
||||
|
||||
## 2. 选型结论(search-first,11-24 17:04 核对)
|
||||
|
||||
| 候选 | 结论 |
|
||||
| --- | --- |
|
||||
| DSH 原生(子 Agent / 任务会话 / reuseSession) | **会话执行与恢复直接复用**,不重造 |
|
||||
| Letta(Apache-2.0) | 最接近部门概念;借鉴"身份 + 私有记忆 + 会话引用"数据模型;运行时太重,不接入 |
|
||||
| LangGraph(MIT) | 借鉴"短期 thread + 长期 namespace"边界:恢复会话 ≠ 注入全部记忆 |
|
||||
| Mastra | thread+resource 类似,但无必要引入;许可证未核清,不入选 |
|
||||
|
||||
**Verdict:会话执行复用 DSH;数据模型借鉴 Letta/LangGraph;
|
||||
部门注册、私有空间与记忆策略基于现有 LocalMemoryManager 薄实现,
|
||||
不 Fork 新框架。**
|
||||
|
||||
## 3. 已完成(库层,另一会话实施并验收)
|
||||
|
||||
src/local-memory/departments/(types/registry/manager/index),
|
||||
verify-departments.mjs 26 项全绿:
|
||||
|
||||
- 幂等创建(scope+名称,重名不覆盖);全局/项目两种归属
|
||||
- role / skills / allowedTools / readGlobal / readProject 策略
|
||||
- 私有 memory-space(departments/<id>/memory-space),跨部门不可见,
|
||||
精确去重,写入自动打 departmentId
|
||||
- recall:私有优先 → 项目 → 全局,总量限 k(默认 5),跨源去重
|
||||
- resumeSession 返回同一可移植引用;attachSession 显式绑宿主会话
|
||||
- checkpoint(currentTask/handoff);revision 冲突拒绝过期写
|
||||
- disable 保留数据不复活;秘密拒收;文件锁 + 原子写
|
||||
|
||||
## 4. 缺口与接线规划(P1.5,详见 NEXT_PHASE_PLAN.md §4.5)
|
||||
|
||||
库层只有 ./local-memory 导出,未接用户面:
|
||||
|
||||
- D1 kernel 构造 DepartmentManager + settings-ui 管理路由
|
||||
(/dsh-brain/departments,同源写门禁)
|
||||
- D2 memory 子插件注册 department_* 工具
|
||||
(create/list/remember/recall/checkpoint/resume)
|
||||
- D3 宿主会话挂钩:启动 resume+attach,回合结束可选 checkpoint;
|
||||
失败不阻塞对话
|
||||
- D4 设置页部门页签(只走公开 API)
|
||||
|
||||
## 5. 边界与约束
|
||||
|
||||
- 部门私有空间云同步**默认不上传**,纳入 cloud-sync M4 范围确认。
|
||||
- 部门不是权限隔离的替代品:项目空间隔离语义不变。
|
||||
- 上下文预算:recall 总量受限;部门身份注入走精简投影,
|
||||
不整段注入 role 全文(role 上限 12000 字符仅存储用)。
|
||||
- 本阶段不做:部门间协作编排、部门层级树、自动部门推荐。
|
||||
|
||||
## 6. 验收
|
||||
|
||||
- verify-departments.mjs 26 项保持全绿
|
||||
- 新增 verify-departments-wiring.mjs:工具注册 / 路由鉴权 /
|
||||
开关行为 / 会话恢复 / 禁用后工具拒绝
|
||||
|
|
@ -0,0 +1,405 @@
|
|||
# DSH Brain 本地记忆与 Mnemon Fork 改造方案
|
||||
|
||||
版本:讨论定稿
|
||||
日期:2026-11-24
|
||||
范围:第一阶段只实现本地记忆;云端同步当前关闭,只保留接口和 Provider 源码拆解成果。
|
||||
|
||||
## 1. 已确认的需求
|
||||
|
||||
1. 独立 Fork Mnemon,作为记忆内核;dsh-brain 的 memory 模块只做连接和适配。
|
||||
2. 本地优先:断网、无账号、无云端配置时,全部本地记忆功能可用。
|
||||
3. 同时使用全局记忆空间和项目记忆空间,两者都自动创建。
|
||||
4. 不再创建 .mnemon 目录。
|
||||
5. 全局数据放用户目录的 .dsh/brain,项目数据放项目目录的 .dsh/brain。
|
||||
6. 自动总结记忆、自动生成和更新用户画像。
|
||||
7. 自动分流、去重、按需检索,控制每轮 token 消耗。
|
||||
8. 云同步与本地功能彻底解耦,当前默认关闭;稳定后可对新安装默认开启,但不得覆盖用户手动关闭的配置。
|
||||
9. 本阶段不移除 Skill、Source、Provider、Strategy 或其他现有功能。
|
||||
10. 拆解外部 Provider 源码,为后续云端同步复用,不把它们误当成同步本身。
|
||||
|
||||
## 2. 总体结构
|
||||
|
||||
dsh-brain
|
||||
├── memory:连接 Fork 后的 Mnemon,提供本地记忆能力
|
||||
├── skill-management:保留 Skill 管理、自进化、市场与评测
|
||||
├── mcp-management:保留 MCP 管理
|
||||
├── cloud-sync:后续负责同步、冲突和外部 Agent 接入
|
||||
└── settings-ui:统一设置页面,只调用公开 API
|
||||
|
||||
Fork 后的 Mnemon 继续保留:
|
||||
├── Runtime
|
||||
├── Documents
|
||||
├── Memory Spaces
|
||||
├── Skills Source
|
||||
├── Mnemon Native 与全部外部 Provider
|
||||
├── 默认三层策略及其他策略
|
||||
├── 自动捕获、蒸馏与空闲总结
|
||||
└── Pack 备份、Git 同步与公开管理 API
|
||||
|
||||
本阶段不调整上述功能的归属,不停止注册,不删除依赖,不物理删除源码。
|
||||
|
||||
## 3. 许可证与 Fork 约束
|
||||
|
||||
上游仓库:omdsh-dev/dsh-mnemon。
|
||||
已核对 dsh-mnemon@0.5.44 与上游仓库均为 MIT。
|
||||
|
||||
允许复制、修改、合并、发布、再许可和商用。必须保留完整 MIT 许可证与原版权声明:
|
||||
|
||||
Copyright (c) 2026 dsh-external contributors
|
||||
|
||||
Fork 应使用新的包名、插件标识和显示名称,避免与原版同时注册相同的工具、路由和服务。保留 upstream 远程仓库,以便合并后续安全修复。
|
||||
|
||||
## 4. 四层记忆与两类长期空间
|
||||
|
||||
| 层级 | 内容 | 默认读取方式 |
|
||||
|---|---|---|
|
||||
| USER.md | 用户身份、长期偏好 | 每轮提供精简投影 |
|
||||
| MEMORY.md | 跨会话协作规则 | 每轮提供精简投影 |
|
||||
| Documents | 项目总结、决策、实施记录、未解决问题 | 相关时检索,按需读全文 |
|
||||
| Memory Spaces | 长期事实、知识、经验、实体和关系 | 按需搜索,只返回相关条目 |
|
||||
|
||||
长期空间分为:
|
||||
|
||||
- 全局记忆空间:保存跨项目通用的长期知识,所有项目可搜索。
|
||||
- 项目记忆空间:保存当前项目特有的长期事实,默认只服务当前项目。
|
||||
|
||||
项目记忆也可以保留项目 ID、来源和标签,但项目空间不能仅靠标签代替权限隔离。
|
||||
|
||||
## 5. 本地目录定稿
|
||||
|
||||
全局根目录:
|
||||
|
||||
C:\Users\qyh15\.dsh\brain\
|
||||
├─ runtime\
|
||||
│ ├─ memories.json
|
||||
│ ├─ USER.md
|
||||
│ └─ MEMORY.md
|
||||
├─ spaces\
|
||||
│ └─ global\
|
||||
├─ backups\
|
||||
└─ state\
|
||||
|
||||
项目根目录:
|
||||
|
||||
<项目目录>\.dsh\brain\
|
||||
├─ documents\
|
||||
├─ memory-space\
|
||||
└─ state\
|
||||
|
||||
要求:
|
||||
|
||||
- 项目首次使用记忆时才自动创建项目内目录。
|
||||
- 不在项目源码中生成 .mnemon。
|
||||
- 全局 Runtime 使用 JSON 作为真实记录,USER.md 与 MEMORY.md 是生成的紧凑投影。
|
||||
- 长期记忆沿用 Mnemon Native 的实际存储结构;如使用 SQLite,不上传数据库文件给云端拆解。
|
||||
- 项目的 .dsh/brain 必须默认不被 Git 提交,但不要因此忽略整个 .dsh。
|
||||
- 若发现旧 .mnemon 数据,不静默移动或删除;提供明确的迁移、验证和回滚入口。
|
||||
- 修改 Runtime、Documents、Native、Pack、锁、临时文件和项目映射的全部默认路径,不能只修改界面显示。
|
||||
|
||||
## 6. 自动初始化与自动创建空间
|
||||
|
||||
### 6.1 全局空间
|
||||
|
||||
首次启动自动完成:
|
||||
|
||||
1. 准备本地 Native 运行组件和存储目录。
|
||||
2. 创建固定内部 ID 的全局空间。
|
||||
3. 激活空间并设为全局长期记忆的默认读写位置。
|
||||
4. 保存初始化完成状态。
|
||||
|
||||
### 6.2 项目空间
|
||||
|
||||
第一次在某项目中使用记忆时自动完成:
|
||||
|
||||
1. 创建项目内 .dsh/brain。
|
||||
2. 初始化项目 Documents。
|
||||
3. 创建并激活当前项目空间。
|
||||
4. 建立稳定的项目 ID 与路径映射。
|
||||
|
||||
### 6.3 一致性与用户控制
|
||||
|
||||
- 重启后复用已有空间,不重复创建。
|
||||
- 多窗口同时初始化同一空间也必须保持幂等。
|
||||
- 用户主动删除或停用后不得自动复活。
|
||||
- 自动创建空间、自动总结、自动画像分别提供独立开关。
|
||||
- 初始化失败时明确报告,不静默切换云端 Provider。
|
||||
- Runtime 和 Documents 应尽量保持可用,长期空间故障不能拖垮全部本地功能。
|
||||
|
||||
## 7. 自动总结与内容分流
|
||||
|
||||
自动总结只提炼值得长期保存的信息,不保存聊天全文。
|
||||
|
||||
分流规则:
|
||||
|
||||
- 用户明确表达的长期偏好 → USER.md。
|
||||
- 跨会话协作规则 → MEMORY.md。
|
||||
- 项目总结、实施记录、未解决问题 → 当前项目 Documents。
|
||||
- 项目特有的长期事实 → 当前项目空间。
|
||||
- 跨项目通用的知识和经验 → 全局空间。
|
||||
- 无法确定是否通用的内容 → 先放当前项目空间,避免污染全局记忆。
|
||||
|
||||
执行要求:
|
||||
|
||||
- 使用增量检查点,不每次重读和总结全部历史。
|
||||
- 保留来源会话、来源记录和修订信息。
|
||||
- 不覆盖原始项目档案,总结与原文分开保存。
|
||||
- 相同内容重复出现时去重。
|
||||
- 总结失败不阻塞对话、本地读写或手工记忆。
|
||||
- 不保存密码、API Key、Token、恢复码等秘密。
|
||||
- 默认不保存原始聊天全文。
|
||||
- 如调用模型,沿用现有模型配置,不新增另一套密钥;设置中说明模型处理的内容范围。
|
||||
|
||||
## 8. 自动生成用户画像
|
||||
|
||||
画像只保存用户明确表达且适合长期保留的信息:
|
||||
|
||||
- 身份、角色和专业背景。
|
||||
- 常用语言。
|
||||
- 回答长度、详细程度和表达风格偏好。
|
||||
- 明确要求长期遵守的协作规则。
|
||||
|
||||
约束:
|
||||
|
||||
- 行为推测只能进入待确认区,不能直接写成事实。
|
||||
- 一次性要求不能升级为永久偏好。
|
||||
- 不能根据助手回答、网页或工具输出推断用户画像。
|
||||
- 用户纠正后更新旧条目,不保留互相冲突的有效版本。
|
||||
- 每条画像保留来源、更新时间和修订号。
|
||||
- 用户可查看、修改、删除和关闭自动画像。
|
||||
- 画像默认只保存在本地,未来云同步也需单独确认范围。
|
||||
|
||||
## 9. 搜索与 token 控制
|
||||
|
||||
- 第一阶段以现有关键词、Native 召回和本地检索能力为基础,不强制引入新的向量数据库。
|
||||
- 默认只搜索当前项目空间和全局空间,不扫描所有历史项目。
|
||||
- 默认返回约 5 条相关结果,可配置上限。
|
||||
- 列表优先返回摘要、ID、分类、标签、来源和修订信息。
|
||||
- 完整正文按需读取。
|
||||
- 全局共享不等于每轮全量注入。
|
||||
- Runtime 保持小而稳定;Documents 与 Memory Spaces 按需检索。
|
||||
|
||||
## 10. 本地数据可靠性
|
||||
|
||||
每条长期记忆至少需要:
|
||||
|
||||
- 唯一 ID。
|
||||
- 所属空间。
|
||||
- 内容和分类。
|
||||
- 来源。
|
||||
- 创建时间和更新时间。
|
||||
- revision,初始为 1,每次修改或删除递增。
|
||||
- 删除标记或等效 tombstone。
|
||||
- 本地变化编号,为未来同步准备;它不是云端 change_id。
|
||||
|
||||
写入要求:
|
||||
|
||||
- 记忆内容与本地变化记录在同一事务中保存。
|
||||
- 完全相同的重复写入不产生多条有效记忆。
|
||||
- 重复命中返回已有记录并明确标记去重。
|
||||
- 修改冲突依据 revision 检测,不仅依赖设备时间。
|
||||
- 保留锁、原子写入、路径限制、超时、输出上限和凭据脱敏。
|
||||
|
||||
## 11. Provider 源码拆解:共同协议
|
||||
|
||||
源码位置:
|
||||
|
||||
plugins/dsh-mnemon-source-memory-spaces/src/provider-sdk.ts
|
||||
plugins/dsh-mnemon-source-memory-spaces/src/contracts.ts
|
||||
plugins/dsh-mnemon-source-memory-spaces/src/providers/http.ts
|
||||
plugins/dsh-mnemon-source-memory-spaces/src/providers/process.ts
|
||||
|
||||
公共协议可复用为后续云端适配层:
|
||||
|
||||
- discover:发现远端或本地已有空间。
|
||||
- status:健康状态、统计和能力检查。
|
||||
- search:按 smart、keyword、basic 等模式检索。
|
||||
- list/browse:浏览和读取记忆。
|
||||
- remember:写入记忆。
|
||||
- forget:删除记忆。
|
||||
- graph、related、entities、link:可选关系能力。
|
||||
- connection:端点、用户、Agent、项目、容器等连接字段。
|
||||
- secret 字段、已配置状态、清除秘密和响应脱敏。
|
||||
- AbortSignal、超时、取消和输出限制。
|
||||
|
||||
共同 Insight 当前包含 id、content、category、importance、tags、entities、source、score、createdAt、externalUri 等字段。
|
||||
|
||||
重要缺口:公共协议没有统一的 revision、云端 change_id、同步游标、幂等操作号和冲突回执。后续 cloud-sync 必须扩展这些语义,不能直接假设所有第三方 Provider 已支持增量同步。
|
||||
|
||||
## 12. 各 Provider 源码与能力
|
||||
|
||||
| Provider | 类型与核心能力 | 写入/删除 | 对云端同步的参考价值 |
|
||||
|---|---|---|---|
|
||||
| Mnemon Native | 本地精确写入、搜索、浏览、图谱、实体、关系、手动链接 | exact;soft delete | 本地主存储、删除记录、关系与本地变化基础 |
|
||||
| OpenViking | 文件系统式共享记忆;语义检索;关键词 grep;空间和用户发现 | exact;hard delete | 写后读校验、内容回执、URI 映射、空间发现 |
|
||||
| Honcho | 用户建模、用户/Agent peer、持久结论 | exact;hard delete | 多 Agent 身份、用户与 Agent 分权、结论查询 |
|
||||
| Mem0 | 自动事实提取、语义搜索、重排、去重;平台或自托管 | async-extracting;hard delete | 异步写入状态、提取结果与本地原文的一致性 |
|
||||
| Hindsight | 知识图谱、实体解析、多策略召回、反思 | async-extracting;soft delete;operation_id | 异步操作号、图谱关系、软删除与状态统计 |
|
||||
| Holographic | 本地结构化事实、信任分、实体解析、组合检索 | exact;hard delete | 本地事实去重、信任过滤、图谱与关系查询 |
|
||||
| RetainDB | 向量与 BM25 混合检索、用户画像、类型化事实 | exact;hard delete | 用户画像、混合检索、项目与用户维度 |
|
||||
| ByteRover | 通过 brv CLI 的本地层次知识树 | async-extracting;不支持 browse/forget | CLI 进程约束;不能作为完整云同步协议模板 |
|
||||
| Supermemory | 语义记忆、持久画像、会话摄取、多容器召回 | async-extracting;soft delete | 容器隔离、画像、异步写入和软删除 |
|
||||
|
||||
注意:
|
||||
|
||||
- OpenViking 默认端点可以是本机地址,但协议属于远程共享记忆,不应仅凭地址判断部署位置。
|
||||
- Holographic 与 ByteRover 是本地 Provider,不是云端同步方案。
|
||||
- async-extracting 表示提交后还可能异步提炼,不能把 HTTP 成功误当成最终记忆已完全一致。
|
||||
- hard delete 的 Provider 无法天然提供云端 tombstone,需要 cloud-sync 自己保存删除事件。
|
||||
- 不支持 browse 或 forget 的 Provider 不能承担完整双向同步。
|
||||
|
||||
## 13. 云端同步如何复用这些源码
|
||||
|
||||
后续建议拆成三层,而不是把 Provider 驱动直接当作同步器:
|
||||
|
||||
1. 本地变化层:记录本地新增、修改、删除、revision、本地变化编号和待同步状态。
|
||||
2. cloud-sync 编排层:推送变化、拉取云端 change_id、重试、幂等、冲突和删除事件。
|
||||
3. Provider/传输适配层:复用连接配置、发现、状态、搜索、读写、图谱、超时、取消和脱敏能力。
|
||||
|
||||
云端可以建立自己的 Brain Cloud Provider,实现公共 Provider 协议;但真正的增量同步仍由 cloud-sync 负责。
|
||||
|
||||
云端同步的是记忆条目及变化,不是 SQLite 文件。其他 Agent 通过统一 MCP 或 HTTP 服务访问云端,不需要知道本地数据库格式。
|
||||
|
||||
## 14. 云同步开关与默认策略
|
||||
|
||||
当前阶段:
|
||||
|
||||
- 默认关闭。
|
||||
- 不要求登录、令牌或云端地址。
|
||||
- 不启动同步定时器,不发起云端记忆请求。
|
||||
- 云端故障不影响本地功能。
|
||||
- 记忆同步与 Skill 同步分别控制。
|
||||
- 本地 memory 不直接依赖云端客户端。
|
||||
|
||||
未来稳定并验收后:
|
||||
|
||||
- 新安装可默认开启。
|
||||
- 已手动关闭的用户保持关闭。
|
||||
- 默认开启不等于静默上传;首次同步前必须确认空间、画像和项目档案的同步范围。
|
||||
- 反复开关不得删除或复制本地数据。
|
||||
|
||||
## 15. 本阶段明确不做
|
||||
|
||||
- 不实际推送或拉取云端记忆。
|
||||
- 不实现云端冲突合并。
|
||||
- 不上传 SQLite 文件。
|
||||
- 不用 Git 代替实时数据库同步。
|
||||
- 不实现 WorkBuddy、Codex 的云端服务入口。
|
||||
- 不移除、不迁移、不停止注册任何现有功能。
|
||||
- 不为了精简而删除 Provider 协议、安全检查、revision 或文件锁。
|
||||
|
||||
## 16. 实施顺序
|
||||
|
||||
1. 建立独立 Fork,修改包名和插件标识,保留 MIT 与 upstream。
|
||||
2. 保持全部现有功能和默认装配,先建立回归基线。
|
||||
3. 将本地默认根目录迁移到约定的 .dsh/brain,提供旧目录迁移与回滚。
|
||||
4. 实现 Native 自动就绪、全局空间和项目空间的幂等自动创建。
|
||||
5. 实现本地数据模型、revision、变化记录、去重和删除标记。
|
||||
6. 实现自动总结、内容分流、自动画像及独立开关。
|
||||
7. 完善搜索、token 预算、管理 API、设置页和本地备份。
|
||||
8. 完成断网、重启、并发、安全和兼容验收。
|
||||
9. 云端阶段再基于 Provider 拆解成果实现 cloud-sync。
|
||||
|
||||
## 17. 第一阶段验收标准
|
||||
|
||||
1. 全新环境无需手工创建空间即可使用记忆。
|
||||
2. 自动得到一个全局空间和当前项目空间。
|
||||
3. 重启、多窗口和重复初始化不会重复创建空间。
|
||||
4. 全局与项目目录均符合 .dsh/brain 约定,不生成 .mnemon。
|
||||
5. 断网、无账号、无云端配置时本地功能完整可用。
|
||||
6. 云同步关闭时云端适配器调用次数为零。
|
||||
7. 自动总结可增量执行、去重并追溯来源。
|
||||
8. 自动画像只保存明确偏好,用户纠正后旧版本失效。
|
||||
9. 默认搜索只覆盖当前项目与全局空间,并限制返回数量。
|
||||
10. 修改、删除、并发写入和重启不会丢失或复制记忆。
|
||||
11. 项目的 .dsh/brain 不被 Git 默认提交。
|
||||
12. 所有现有 Source、Provider、Strategy、Skill 和公开插件接口保持可用。
|
||||
13. 配置页不直接访问 SQLite、CLI 或 Provider 私有实现。
|
||||
14. 旧数据迁移可验证、可回滚,不静默删除旧文件。
|
||||
|
||||
## 18. 后续移除决定(已确认,当前不执行)
|
||||
|
||||
后续要做功能移除和精简,但不属于本地第一阶段。
|
||||
|
||||
执行前置条件:
|
||||
|
||||
- 本地记忆、自动空间、自动总结和用户画像已经稳定并通过验收。
|
||||
- cloud-sync 所需的 Provider 公共协议、适配层和必要源码已经完成拆解与复用。
|
||||
- 已用依赖分析确认待移除功能没有被公开导出、工具、路由、配置、页面或其他模块引用。
|
||||
|
||||
后续移除原则:
|
||||
|
||||
- Skill、Provider、Strategy、Git 同步等分别确定归属,不做不加区分的一次性删除。
|
||||
- 云端同步仍需的能力先提取并验证,再移除默认内置或冗余实现。
|
||||
- 每次移除都保留可回滚点,并运行完整回归测试。
|
||||
- 在该阶段正式开始前,继续保留全部现有功能,不停止注册、不删除依赖、不物理删除源码。
|
||||
|
||||
## 19. 仓库整理与生成物归档
|
||||
|
||||
本节只记录整理方案,不代表已经删除或移动相关文件。清理必须在单独任务中执行,并先核对文件内容与 Git 状态。
|
||||
|
||||
### 19.1 目标目录约定
|
||||
|
||||
dsh-brain/
|
||||
├─ docs/
|
||||
│ └─ plans/ ← 设计、改造与实施方案
|
||||
├─ tests/
|
||||
│ └─ verification/ ← 后续统一收纳 verify-*.mjs
|
||||
├─ artifacts/ ← 可重新生成的输出,默认不提交 Git
|
||||
│ ├─ analysis/ ← 临时分析和工具导出
|
||||
│ ├─ logs/ ← 验证与运行日志
|
||||
│ └─ preview/ ← HTML、截图和预览输出
|
||||
├─ src/ ← 源码
|
||||
├─ client/ ← 浏览器端源码
|
||||
└─ lib/ ← 入库的构建产物与发布入口
|
||||
|
||||
后续新增方案统一放 docs/plans,不得在仓库根目录新增 LOCAL_MEMORY_PLAN.md 一类散落文档。临时分析、日志和预览输出统一进入 artifacts 对应子目录,不得继续堆在根目录。
|
||||
|
||||
### 19.2 可优先清理的历史输出
|
||||
|
||||
在确认不需要保留历史分析过程后,可清理以下历史对话或工具调用记录:
|
||||
|
||||
- .code-graph-core-history.txt
|
||||
- .dsh-analysis-archive.json
|
||||
- .dsh-analysis-task.txt
|
||||
- .review-context.txt
|
||||
- .session-init.txt
|
||||
- .tmp-b1.txt
|
||||
- .tmp-b5.txt
|
||||
- .tmp-codegraph-history.txt
|
||||
- .tmp-mnemon-history.txt
|
||||
- .tmp-review-history.txt
|
||||
|
||||
根目录的 .tmp-verify-*.log 属于旧验证日志,_preview 属于可重新生成的 HTML 和截图,可在核对后清理。清理这些输出不应改变源码、测试和发布行为。
|
||||
|
||||
.codegraph/cache 是可重建索引缓存;node_modules 是可重装依赖,但删除后当前项目不能立即构建和测试。默认暂时保留,不与普通垃圾文件一起清理。
|
||||
|
||||
### 19.3 必须保留的成果与运行目录
|
||||
|
||||
- docs/plans/LOCAL_MEMORY_PLAN.md:本方案,必须保留。
|
||||
- verify-review-fixes.mjs:新增修复验证成果,不能当作临时垃圾删除。
|
||||
- src/version.ts 与 lib/version.js:新增修复成果,不能因未被 Git 跟踪而删除。
|
||||
- 其他 verify-*.mjs:保留;后续移入 tests/verification 时必须同步调整引用、包脚本和工作目录,再运行验证。
|
||||
- .tmp-remote-skill-sync.ts:虽然名称带临时前缀,但包含源代码;比较差异并确认归并前必须保留。
|
||||
- lib:项目入口和发布包直接使用,且 .gitignore 明确要求入库,禁止按普通编译缓存删除。
|
||||
- client:浏览器端代码,必须保留。
|
||||
|
||||
### 19.4 整理执行门禁
|
||||
|
||||
1. 先列出待处理文件、来源和 Git 状态,再执行删除或移动。
|
||||
2. 删除前区分历史输出、可重建缓存、源码、测试和未跟踪修复成果。
|
||||
3. 移动测试脚本后更新 import 路径、package.json scripts、文档和 CI 调用。
|
||||
4. 将 artifacts 加入适当的 Git 忽略规则;不要误忽略 src、client、lib 或正式文档。
|
||||
5. 项目记忆数据仍按 .dsh/brain 约定存放,不得混入 artifacts,也不得默认提交 Git。
|
||||
6. 整理完成后运行类型检查、构建、现有验证脚本和插件入口检查。
|
||||
7. 根目录只保留项目标准配置、说明和必要入口,不遗留临时记录、旧日志或预览输出。
|
||||
|
||||
## 20. 实施交付物
|
||||
|
||||
- Fork 仓库与上游跟踪说明。
|
||||
- MIT 和第三方声明确认。
|
||||
- 本地目录与旧数据迁移说明。
|
||||
- 自动初始化、自动总结、自动画像的配置和状态说明。
|
||||
- 本地数据结构与 revision 约定。
|
||||
- Provider 公共协议和云端同步缺口说明。
|
||||
- 测试命令、真实结果和未覆盖范围。
|
||||
- 后续 cloud-sync 所需接口清单。
|
||||
|
|
@ -0,0 +1,187 @@
|
|||
# DSH Brain 四模块拆分 · 后续阶段规划
|
||||
|
||||
版本:v1(接续 LOCAL_MEMORY_PLAN.md)
|
||||
日期:2026-11-24
|
||||
状态:待确认排期;本文档只记录规划,不代表已执行。
|
||||
|
||||
## 0. 当前基线(已完成事实)
|
||||
|
||||
四模块 + 设置页的 bundle 拆分**已经落地**(0.9.11,commit `3ef7ffe`):
|
||||
|
||||
| Bundle | 入口 | 职责 |
|
||||
| --- | --- | --- |
|
||||
| dsh-brain-memory | src/entries/memory.ts | memory_* 工具,经 kernel MemoryRemoteFactory 访问存储 |
|
||||
| dsh-brain-skills | src/entries/skills.ts | 技能管理页、skill_list、市场、来源树、客户端注册 |
|
||||
| dsh-brain-mcp | src/entries/mcp.ts | MCP 管理页能力声明(连接由宿主 dsh-mcp-connector 管理) |
|
||||
| dsh-brain-cloudsync | src/entries/cloudsync.ts | 活动上报、登录/测试/补发/技能同步路由与定时器 |
|
||||
| dsh-brain-settings-ui | src/entries/settings-ui.ts | 配置页与 status/capabilities/config/migrate 路由 |
|
||||
|
||||
本地记忆第一阶段(LOCAL_MEMORY_PLAN.md §1–17)**已验收**:
|
||||
docs/LOCAL_MEMORY_ACCEPTANCE.md 记录 38 个验证脚本全绿(2 个环境性跳过)。
|
||||
Mnemon fork 位于 vendor/dsh-mnemon(dsh-brain-mnemon 0.5.54-dsh.1,MIT 保留),
|
||||
活跃适配层为 src/mnemon/fork + src/mnemon/native.ts。
|
||||
|
||||
已知未收口事项(2026-11-24 20:05 复核):
|
||||
- 工作树有 85 个未提交文件(本地记忆阶段全部成果 + lib 构建产物 + vendor/);最新 tag 仍为 v0.9.10。
|
||||
- 成果已另行安排人工审核(用户确认),P0 的审阅环节不由规划会话承担;审核结论落地后仍需完成提交与打 tag。
|
||||
- verify-all 本轮未能重跑(宿主 shell 审批通道故障),沿用验收文档记录;P0 需重跑确认。
|
||||
- 真实云 endpoint、真实 Mnemon 宿主进程、frozen install 未在验收中覆盖。
|
||||
|
||||
## 1. 阶段总览
|
||||
|
||||
P0 收口固化 → P1 仓库整理(§19) → P2 cloud-sync 记忆同步 → P3 功能移除精简(§18) → P4 发布
|
||||
|
||||
P2 与 P1 可并行;P3 严格依赖 P2 验收通过(§18 前置条件)。
|
||||
|
||||
**推荐执行序(2026-11-24 调整,待用户确认)**:
|
||||
|
||||
P0 收口固化 → P1.5 部门接线(D1→D2→D3→D4) → P1 仓库整理 → P2 cloud-sync → P3 → P4
|
||||
|
||||
理由:部门库层已验收、只差接线(2–3 天),是用户可见价值最快的路径;
|
||||
先于 P2 做出真实使用反馈,还能反过来校准云同步的条目模型。
|
||||
P0 仍是硬门禁(部门代码就在未提交的 85 个文件里,先固化基线再动新刀)。
|
||||
P1 仓库整理让位到部门之后:整理会移动 verify 脚本位置,放在接线后做可少改一次引用。
|
||||
|
||||
## 2. P0 · 收口与基线固化(先做,半天)
|
||||
|
||||
执行归属:由实施会话/人工执行;本会话只维护规划。审核已另行安排,剩余动作是下面 1–3 项。
|
||||
|
||||
1. 重跑 `npm run typecheck`、`npm run build`、`node scripts/verify-all.mjs`,确认全绿。
|
||||
2. 审阅并提交本地记忆阶段成果,按主题分 commit:
|
||||
- feat(local-memory): 本地存储/空间/部门/迁移 + 对应 verify
|
||||
- feat(mnemon): fork 快照、provider-sdk 子集、native 入口 + vendor/
|
||||
- feat(auto-summary): 自动总结/画像/开关 + 对应 verify
|
||||
- docs: 方案、验收、fork 说明
|
||||
- chore: lib 构建产物与 lockfile
|
||||
3. 打 tag(建议 v0.10.0-local.1)作为后续所有阶段的回滚点。
|
||||
|
||||
门禁:typecheck + build + verify-all 全绿才允许进入后续阶段。
|
||||
|
||||
## 3. P1 · 仓库整理(执行 LOCAL_MEMORY_PLAN §19,1 天)
|
||||
|
||||
详细实施方案已细化为 docs/plans/REPO_CLEANUP_PLAN.md(含 39 个 verify 脚本引用全量扫描、C0–C5 执行切片、发布件零改动门禁)。要点:
|
||||
1. 先产出「待处理文件清单 + Git 状态」再动手;区分历史输出 / 可重建缓存 / 源码 / 未跟踪修复成果。
|
||||
2. verify-*.mjs 迁入 tests/verification/,同步更新 package.json scripts、
|
||||
scripts/verify-all.mjs 引用与工作目录假设;verify-review-fixes.mjs、
|
||||
src/version.ts、lib/version.js 是成果不是垃圾。
|
||||
3. 建 artifacts/{analysis,logs,preview},加入 .gitignore;_preview 与
|
||||
.tmp-verify-*.log 核对后归档或清理。
|
||||
4. .codegraph/planning-context.txt 等历史会话导出移入 artifacts/analysis。
|
||||
5. lib 保持入库(发布入口),client 保留;.dsh/brain 数据不混入 artifacts。
|
||||
6. 整理后重跑 typecheck + build + verify-all + 插件入口检查,单独 commit。
|
||||
|
||||
## 4. P2 · cloud-sync 记忆增量同步(核心新工作,约 1–2 周)
|
||||
|
||||
目标:把本地记忆(Runtime 投影之外的 Documents / Memory Spaces / 画像)
|
||||
与 LongMemory 云端做**条目级**增量双向同步。不做 SQLite 文件上传,
|
||||
不用 Git 代替实时同步(§15 边界继续有效)。
|
||||
|
||||
### 4.1 三层架构(复用 §13 拆解成果)
|
||||
|
||||
L1 本地变化层 (src/local-memory/changelog)
|
||||
outbox:id、space、op(create/update/delete)、revision、
|
||||
local_change_no、payload 摘要、pending/synced/failed 状态
|
||||
—— 与记忆写入同事务落盘(§10 已有 revision/tombstone 基础)
|
||||
L2 同步编排层 (src/cloudsync/memory-sync)
|
||||
push outbox → 云端 change_id 游标 pull → 幂等重试 →
|
||||
冲突检测(revision + 内容 hash) → 冲突预览/确认 UI →
|
||||
删除事件(tombstone)传播
|
||||
L3 Provider/传输适配层 (src/mnemon/fork 协议扩展)
|
||||
实现 Brain Cloud Provider:discover/status/search/list/
|
||||
remember/forget + connection/secret 脱敏/AbortSignal
|
||||
—— 补齐公共协议缺口:revision、change_id、游标、
|
||||
幂等操作号、冲突回执(§11 已确认缺口)
|
||||
|
||||
### 4.2 分期切片
|
||||
|
||||
- M1 协议定稿:云端 API 契约(change feed、幂等号、冲突回执)书面化,
|
||||
服务端与插件两侧确认;产出 docs/plans/CLOUD_SYNC_CONTRACT.md。
|
||||
- M2 单向推送:outbox → push,幂等重试、账号切换隔离(复用 activity
|
||||
队列的账号绑定语义);断网堆积、恢复补发。
|
||||
- M3 拉取与合并:change_id 游标 pull、远端 tombstone 应用、
|
||||
revision 冲突检测;冲突走「预览 + conflictId + 过期确认拒绝」
|
||||
(沿用 skill-sync round5 已验证的交互语义)。
|
||||
- M4 范围确认与默认策略:首次同步前确认空间/画像/项目档案范围;
|
||||
记忆同步与 Skill 同步独立开关;手动关闭永不覆盖(§14)。
|
||||
|
||||
### 4.3 验收标准(新增 verify-cloud-sync-*.mjs)
|
||||
|
||||
1. sync 关闭时云端调用为零(沿用第一阶段 check 16/17 语义)。
|
||||
2. 断网→恢复:outbox 不丢不重,幂等号去重。
|
||||
3. 双端并发修改同一记忆:revision 冲突被检出,预览含双方版本,
|
||||
过期确认被拒绝;解决后两端一致。
|
||||
4. 删除传播:本地删→云端 tombstone;云端删→本地 tombstone;
|
||||
hard-delete Provider 场景由 L1 自存删除事件。
|
||||
5. 账号/服务地址切换:旧队列与游标作废,不串号。
|
||||
6. 反复开关同步不删除、不复制本地数据。
|
||||
7. 秘密字段永不上传;画像同步需单独确认。
|
||||
8. 真实 endpoint 冒烟(弥补第一阶段环境缺口)。
|
||||
|
||||
## 4.5 P1.5 · 部门(Departments)接线与暴露(新增,约 2–3 天)
|
||||
|
||||
执行序建议:**提前到 P1 之前**(P0 之后立即做),见 §1 推荐执行序。
|
||||
每个切片 D1–D4 独立 commit + verify,D1+D2 完成即有最小可用闭环
|
||||
(agent 能建部门/存记忆/召回),D3/D4 可再拆半天粒度跟进。
|
||||
|
||||
概念定稿与选型依据见 docs/plans/DEPARTMENT_PLAN.md。
|
||||
|
||||
现状核实(2026-11-24):
|
||||
- DepartmentManager 已完整实现于 src/local-memory/departments/
|
||||
(types/registry/manager/index),verify-departments.mjs 26 项检查全绿。
|
||||
- 能力:按 scope+名称幂等创建;角色/skills/allowedTools/记忆读取策略;
|
||||
私有 memory-space(departments/<id>/memory-space,对其他部门不可见);
|
||||
可复用会话引用 resumeSession/attachSession(host 绑定显式);
|
||||
checkpoint(currentTask/handoff);recall 私有优先+项目/全局可选、
|
||||
总量受限、去重;revision 冲突检测;disable 不删数据不复活;秘密拒收。
|
||||
- **缺口:只有库级导出(./local-memory),未接任何用户面**——
|
||||
kernel 未构造实例,无 agent 工具、无 /dsh-brain 管理路由、
|
||||
设置页无部门页签、宿主会话生命周期未挂 attach/checkpoint。
|
||||
|
||||
接线切片(每步独立 commit + verify):
|
||||
- D1 kernel 构造 DepartmentManager(共享 LocalMemoryManager),
|
||||
随 localMemoryEnabled 开关;settings-ui 增加 /dsh-brain/departments
|
||||
管理路由(list/create/update/disable/checkpoint,同源写门禁)。
|
||||
- D2 memory 子插件注册 department_* agent 工具
|
||||
(create/list/remember/recall/checkpoint/resume),
|
||||
工具描述声明私有空间语义;k 上限沿用 5。
|
||||
- D3 宿主会话挂钩:会话启动时按部门 resumeSession + attachSession,
|
||||
回合结束可选 checkpoint;失败不阻塞对话。
|
||||
- D4 设置页部门页签(只走公开 API,不触存储内部);
|
||||
云同步阶段部门私有空间默认不上传,纳入 M4 范围确认。
|
||||
|
||||
验收:verify-departments.mjs 保持全绿 + 新增 verify-departments-wiring.mjs
|
||||
(工具注册/路由鉴权/开关行为/会话恢复/禁用后工具拒绝)。
|
||||
|
||||
## 5. P3 · 功能移除与精简(执行 §18,P2 验收后)
|
||||
|
||||
前置条件(§18):本地记忆稳定 ✅ + cloud-sync 协议拆解复用 ✅(P2) +
|
||||
依赖分析确认无引用。
|
||||
|
||||
1. 用 code-graph 对候选移除项逐项出影响面报告(公开导出/工具/路由/
|
||||
配置/页面引用为零才可移除)。
|
||||
2. 候选顺序(每项独立 commit + 回滚点 + 全量回归):
|
||||
a. 冗余外部 Provider 默认内置(保留协议与源码于 vendor,停止默认注册)
|
||||
b. 旧 cloud-memory 兼容别名路由(确认无存量 profile 依赖后)
|
||||
c. 根导出组合器中已被五入口取代的重复装配
|
||||
3. 原则:不停止仍被引用的注册;不物理删除 vendor 源码;
|
||||
每步保留回滚点。
|
||||
|
||||
## 6. P4 · 发布与分发
|
||||
|
||||
1. 版本 0.10.0:README 更新(本地优先 + 云同步可选)、CHANGELOG。
|
||||
2. pack-guard + prepack 校验五入口 exports 完整;frozen install 验证
|
||||
(补第一阶段缺口)。
|
||||
3. 新安装默认策略评审:cloudMemoryEnabled 是否默认开(§14:需 P2
|
||||
验收 + 首次范围确认交互就绪后才允许)。
|
||||
4. 真实 DSH 宿主端到端冒烟:五子插件逐行开关 HMR、重启保持、
|
||||
离线全功能。
|
||||
|
||||
## 7. 风险与开放问题
|
||||
|
||||
- 云端 LongMemory 服务端是否已有 change feed / 幂等号接口?M1 前需确认,
|
||||
否则 P2 工期取决于服务端改造。
|
||||
- async-extracting 类 Provider(Mem0/Hindsight/Supermemory)不承担
|
||||
双向同步;Brain Cloud Provider 必须 exact 语义。
|
||||
- 多窗口并发同步的文件锁对抗性故障未覆盖(第一阶段遗留),P2 M2
|
||||
加并发用例。
|
||||
- 宿主 shell 审批通道当前故障,P0 重跑验证前需恢复或换通道。
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
# P1 · 仓库整理实施方案(Repo Cleanup)
|
||||
|
||||
版本:v1(规划稿,本会话只做规划,不实施)
|
||||
日期:2026-11-24
|
||||
依据:LOCAL_MEMORY_PLAN.md §19 + 本轮逐项核实(39 个 verify 脚本的引用扫描、Git 状态、目录实测)。
|
||||
执行归属:实施会话/人工;每步独立 commit,门禁见 §7。
|
||||
|
||||
## 0. 前置核对(执行前必读)
|
||||
|
||||
**P0 落账状态与用户口径不一致(2026-11-24 20:2x 实测)**:
|
||||
用户表示"已经收了",但本仓库 Git 显示——HEAD 仍为 `3ef7ffe`(五子插件拆分),
|
||||
85 个文件未提交,最新 tag 仍为 v0.9.10,无 stash、无其他本地分支。
|
||||
可能审核/收口发生在另一份检出或尚未推送。**执行本方案第一步是重新核对
|
||||
Git 状态;若基线仍未固化,先回 NEXT_PHASE_PLAN §2 完成 P0,再动整理。**
|
||||
(main 领先 origin/main 8 个 commit,推送时机由用户决定,本方案不含 push。)
|
||||
|
||||
## 1. 现状盘点(已核实事实)
|
||||
|
||||
根目录现有内容分类:
|
||||
|
||||
| 类别 | 内容 | 处置 |
|
||||
| --- | --- | --- |
|
||||
| 源码/产物(保留原位) | src/ client/ lib/ vendor/ scripts/ docs/ | 不动(lib 是发布入口,.gitignore 明确入库) |
|
||||
| 验证脚本 ×39 | 根目录 verify-*.mjs(26 tracked + 13 untracked) | 迁入 tests/verification/(§3) |
|
||||
| 预览生成器 ×3 | preview-card/import-mcp.mjs(tracked) | 迁入 scripts/preview/,输出改 artifacts/preview(§4) |
|
||||
| 可再生输出 | _preview/(2.3 MB,12 个 html/png,已忽略) | 删除,可由生成器重建 |
|
||||
| 索引缓存 | .codegraph/cache(26.7 MB,已忽略) | 保留不动(重建成本高,非垃圾) |
|
||||
| 历史会话导出 | .codegraph/*.txt ×4(planning-context、session-recap-b1×2、mnemon-storage-investigation)+ code-graph.json/CODE-GRAPH.md/manifest.json | txt 移入 artifacts/analysis/;json/md 是 codegraph 工具自身数据,留在 .codegraph |
|
||||
| §19.2 列举的旧临时文件 | .tmp-b1.txt、.review-context.txt 等 10 项 | **已不存在**(本轮实测根目录无任何 .tmp*),无需清理 |
|
||||
| 项目记忆数据 | .dsh/brain/(已忽略) | 不动,不混入 artifacts |
|
||||
|
||||
其他事实:
|
||||
- package.json 的 verify/test 都指向 scripts/verify-all.mjs;typecheck/build/prepack 不涉及根目录脚本。
|
||||
- .npmignore 已排除 *.mjs 与 scripts/,files 字段只含 lib/client/cordis.patch.yml/README/LICENSE——**迁移不影响发布件**。
|
||||
- pack-guard.mjs / release-prep.mjs / fork-mnemon.mjs 无 verify-*/_preview/.codegraph 引用(已扫描)。
|
||||
- .gitignore 已含 artifacts/、_preview/、.tmp-*、.codegraph/ 规则,artifacts 目录建立后无需新增忽略规则。
|
||||
|
||||
## 2. 目标目录(沿用 §19.1,微调预览生成器归属)
|
||||
|
||||
dsh-brain/
|
||||
├─ docs/plans/ ← 方案(已就位:LOCAL_MEMORY/NEXT_PHASE/DEPARTMENT/本文档)
|
||||
├─ tests/verification/ ← 39 个 verify-*.mjs 统一收纳
|
||||
├─ scripts/
|
||||
│ ├─ verify-all.mjs ← 扫描目录改为 tests/verification
|
||||
│ └─ preview/ ← 3 个 preview-*.mjs 生成器(源码归 scripts)
|
||||
├─ artifacts/ ← 已忽略,不提交
|
||||
│ ├─ analysis/ ← .codegraph 历史 txt 导出
|
||||
│ ├─ logs/ ← 预留:验证/运行日志
|
||||
│ └─ preview/ ← 预览生成器的新输出目录(替代 _preview)
|
||||
├─ src/ client/ lib/ vendor/ ← 不动
|
||||
└─ 根目录 ← 只剩标准配置 + README + LICENSE
|
||||
|
||||
## 3. 验证脚本迁移(核心步骤,引用已全量扫描)
|
||||
|
||||
39 个脚本的项目引用只有三种形态,全部要改:
|
||||
|
||||
1. **相对导入 `./lib/...`(36 个脚本)** → 改 `../../lib/...`。
|
||||
涉及 api/store/config/reporter/kernel/entries/local-memory/mnemon/skills 等,
|
||||
逐脚本正则替换 `from './lib/` → `from '../../lib/`(含动态 import())。
|
||||
2. **cwd 相对读取(1 个)**:verify-theme.mjs 读 `'./client/index.js'`。
|
||||
verify-all 以 cwd=root 跑子进程,迁移后 cwd 不变则仍可用;
|
||||
但为消除 cwd 依赖,统一改成基于 import.meta.url 定位仓库根(与第 3 类同法)。
|
||||
3. **here 相对读取(2 个)**:verify-card-debug/card-render 用
|
||||
`dirname(fileURLToPath(import.meta.url))` join 'client'。
|
||||
迁移后 here 变成 tests/verification,须改为 `join(here,'..','..','client')`
|
||||
或引入统一的 root 常量。
|
||||
|
||||
配套改动:
|
||||
- scripts/verify-all.mjs:扫描目录从仓库根改为 `join(root,'tests','verification')`;
|
||||
子进程 cwd 保持仓库根不变(保证第 2 类兼容);文件名过滤正则不变。
|
||||
- README.md:8 处 `node verify-*.mjs` 示例路径更新为 `node tests/verification/verify-*.mjs`。
|
||||
- docs/management-surface.md:约 20 处脚本名提及多为纯文件名(无路径),核对后仅改带路径的。
|
||||
- docs/plans/LOCAL_MEMORY_PLAN.md §19 与验收文档中的路径描述追加"已迁移"注记,不改历史记录正文。
|
||||
|
||||
**保留红线(§19.3)**:verify-review-fixes.mjs、src/version.ts、lib/version.js 是成果;
|
||||
.tmp-remote-skill-sync.ts 若在其他检出存在,归并前不得删(本检出未见此文件)。
|
||||
|
||||
## 4. 预览生成器与输出
|
||||
|
||||
- preview-card/import/mcp.mjs 迁至 scripts/preview/(tracked 源码,git mv 保历史)。
|
||||
- 三个脚本的 outDir 从 `join(here,'_preview')` 改为仓库根下 `artifacts/preview`
|
||||
(here 现在指向 scripts/preview,用 `join(here,'..','..','artifacts','preview')`)。
|
||||
- README 中 `node preview-card.mjs` 的调用示例同步更新。
|
||||
- 旧 _preview/(2.3 MB)确认生成器可重建后删除;.gitignore 的 _preview/ 规则可留可删(建议留,防旧工具复活)。
|
||||
|
||||
## 5. 历史导出归档
|
||||
|
||||
- .codegraph/planning-context.txt、session-recap-b1.txt、session-recap-b1-full.txt、
|
||||
mnemon-storage-investigation.txt → 移入 artifacts/analysis/(移动即出 Git 视野,因 .codegraph 本就忽略)。
|
||||
- .codegraph/code-graph.json、CODE-GRAPH.md、manifest.json、cache/ 留在原地(工具工作数据)。
|
||||
- 本轮解码产生的 .codegraph/cache/dept-*.jsonl、sess-*.jsonl 属可重建缓存,随 cache 保留或由实施者清理,不影响仓库。
|
||||
|
||||
## 6. 执行切片(每步独立 commit + 验证)
|
||||
|
||||
| 步 | 动作 | commit 主题 | 验证 |
|
||||
| --- | --- | --- | --- |
|
||||
| C0 | 核对 Git 基线(§0),产出待处理清单 | 无(只读) | 清单评审 |
|
||||
| C1 | 建 tests/verification + git mv 39 个脚本 + 改三类引用 + verify-all 扫描目录 | refactor(tests): move verify scripts into tests/verification | typecheck + build + npm run verify 全绿(38 过 + 2 环境跳过口径不变) |
|
||||
| C2 | 预览生成器迁 scripts/preview + 输出改 artifacts/preview + 删 _preview | chore(preview): relocate generators and outputs | 跑一次 preview-card 确认产物落 artifacts/preview |
|
||||
| C3 | .codegraph 历史 txt 归档 artifacts/analysis + 建 artifacts/logs 占位 | chore(artifacts): archive historical exports | git status 干净度核对 |
|
||||
| C4 | README / management-surface / 计划文档路径注记 | docs: update paths after repo cleanup | 文档内路径抽查 |
|
||||
| C5 | 终验:typecheck + build + verify-all + verify-plugin-entry + npm pack --dry-run 比对 files 清单 | 无(验证) | 发布件与整理前一致(lib/client 字节不变) |
|
||||
|
||||
预计工作量:半天~1 天(C1 占大头,36 个脚本的机械替换 + 全量验证)。
|
||||
|
||||
## 7. 门禁与回滚
|
||||
|
||||
1. C0 清单先行:任何删除/移动前列出文件名、来源、Git 状态(§19.4)。
|
||||
2. 每步 commit 独立,出问题 revert 单步即可;C1 之前打轻量 tag(如 pre-cleanup)可选。
|
||||
3. lib/ client/ src/ vendor/ 的字节在本阶段**零改动**——整理只动位置与引用,
|
||||
npm pack --dry-run 前后对比作为硬证据。
|
||||
4. artifacts/ 不提交;.dsh/brain 数据不进 artifacts;不误加忽略规则覆盖源码。
|
||||
5. 完成后根目录仅剩:配置文件(package/tsconfig/git/npm 系)、README、LICENSE、
|
||||
cordis.patch.yml 与标准目录。
|
||||
|
||||
## 8. 与后续阶段的衔接
|
||||
|
||||
- 本方案即 NEXT_PHASE_PLAN 的 P1;推荐执行序中排在 P1.5 部门接线之后
|
||||
(部门 D1–D4 会新增 verify-departments-wiring.mjs,先接线后迁移可少搬一次)。
|
||||
- 若用户决定先整理后接线,本方案同样成立:新验证脚本直接写进 tests/verification 即可。
|
||||
- P2 cloud-sync 的新 verify-cloud-sync-*.mjs 一律出生在新位置,不再回落根目录。
|
||||
323
lib/api.js
323
lib/api.js
|
|
@ -38,6 +38,195 @@ function sessionCookieOf(headers) {
|
|||
}
|
||||
return '';
|
||||
}
|
||||
/**
|
||||
* Runtime response-shape guards.
|
||||
*
|
||||
* A 2xx with syntactically valid JSON but the wrong shape is still a failed
|
||||
* call: without these checks `null` becomes `data: null` and every downstream
|
||||
* `data.items ?? []` silently turns a contract violation into "empty". The
|
||||
* helpers throw; request() normalizes the throw to `invalid_response`.
|
||||
*/
|
||||
function requireResponseObject(value, what) {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error(`${what} must be a JSON object`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function requireResponseArray(body, key) {
|
||||
const value = body[key];
|
||||
if (!Array.isArray(value))
|
||||
throw new Error(`${key} must be an array`);
|
||||
return value;
|
||||
}
|
||||
function requireResponseString(body, key, allowEmpty = false) {
|
||||
const value = body[key];
|
||||
if (typeof value !== 'string' || (!allowEmpty && value === '')) {
|
||||
throw new Error(`${key} must be a non-empty string`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function optionalResponseString(body, key) {
|
||||
const value = body[key];
|
||||
if (value !== undefined && typeof value !== 'string')
|
||||
throw new Error(`${key} must be a string`);
|
||||
}
|
||||
function optionalNullableString(body, key) {
|
||||
const value = body[key];
|
||||
if (value !== undefined && value !== null && typeof value !== 'string') {
|
||||
throw new Error(`${key} must be a string or null`);
|
||||
}
|
||||
}
|
||||
function optionalResponseNumber(body, key) {
|
||||
const value = body[key];
|
||||
if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value))) {
|
||||
throw new Error(`${key} must be a number`);
|
||||
}
|
||||
}
|
||||
function optionalResponseBoolean(body, key) {
|
||||
const value = body[key];
|
||||
if (value !== undefined && typeof value !== 'boolean')
|
||||
throw new Error(`${key} must be a boolean`);
|
||||
}
|
||||
function optionalResponseStringArray(body, key) {
|
||||
const value = body[key];
|
||||
if (value === undefined)
|
||||
return;
|
||||
if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
|
||||
throw new Error(`${key} must be an array of strings`);
|
||||
}
|
||||
}
|
||||
function optionalStringOrNumber(body, key) {
|
||||
const value = body[key];
|
||||
if (value !== undefined && typeof value !== 'string' && typeof value !== 'number') {
|
||||
throw new Error(`${key} must be a string or number`);
|
||||
}
|
||||
}
|
||||
function validateTurnAck(value) {
|
||||
const body = requireResponseObject(value, 'activity turn response');
|
||||
optionalResponseBoolean(body, 'recorded');
|
||||
optionalResponseBoolean(body, 'duplicate');
|
||||
return body;
|
||||
}
|
||||
function validateSummaryAck(value) {
|
||||
const body = requireResponseObject(value, 'activity summary response');
|
||||
optionalResponseNumber(body, 'staged');
|
||||
optionalResponseNumber(body, 'skipped');
|
||||
optionalResponseBoolean(body, 'full');
|
||||
return body;
|
||||
}
|
||||
function validateMemoryHitItem(value, what) {
|
||||
const body = requireResponseObject(value, what);
|
||||
optionalResponseString(body, 'id');
|
||||
optionalResponseString(body, 'content');
|
||||
optionalResponseStringArray(body, 'tags');
|
||||
optionalResponseString(body, 'primary_sector');
|
||||
if (body.project_id !== undefined && body.project_id !== null && typeof body.project_id !== 'string') {
|
||||
throw new Error(`${what}.project_id must be a string or null`);
|
||||
}
|
||||
optionalResponseNumber(body, 'revision');
|
||||
optionalResponseNumber(body, 'created_at');
|
||||
optionalResponseNumber(body, 'updated_at');
|
||||
return body;
|
||||
}
|
||||
function validateMemoryRead(value) {
|
||||
const body = requireResponseObject(value, 'memory response');
|
||||
requireResponseString(body, 'id');
|
||||
return validateMemoryHitItem(body, 'memory response');
|
||||
}
|
||||
function validateSearchResponse(value) {
|
||||
const body = requireResponseObject(value, 'memory search response');
|
||||
const matches = requireResponseArray(body, 'matches');
|
||||
matches.forEach((entry, index) => validateMemoryHitItem(entry, `matches[${index}]`));
|
||||
optionalResponseNumber(body, 'total');
|
||||
optionalResponseString(body, 'search_mode');
|
||||
return body;
|
||||
}
|
||||
function validateListResponse(value) {
|
||||
const body = requireResponseObject(value, 'memory list response');
|
||||
const items = requireResponseArray(body, 'items');
|
||||
items.forEach((entry, index) => validateMemoryHitItem(entry, `items[${index}]`));
|
||||
optionalResponseNumber(body, 'total');
|
||||
return body;
|
||||
}
|
||||
function validateProjectsResponse(value) {
|
||||
const body = requireResponseObject(value, 'projects response');
|
||||
const projects = requireResponseArray(body, 'projects');
|
||||
projects.forEach((entry, index) => {
|
||||
const project = requireResponseObject(entry, `projects[${index}]`);
|
||||
optionalResponseString(project, 'id');
|
||||
optionalResponseString(project, 'name');
|
||||
});
|
||||
return body;
|
||||
}
|
||||
function validateAddResponse(value) {
|
||||
const body = requireResponseObject(value, 'memory add response');
|
||||
optionalResponseString(body, 'id');
|
||||
optionalResponseNumber(body, 'revision');
|
||||
optionalResponseBoolean(body, 'deleted');
|
||||
optionalResponseString(body, 'state');
|
||||
optionalResponseBoolean(body, 'remote_saved');
|
||||
if (body.memory !== undefined && body.memory !== null) {
|
||||
validateMemoryHitItem(body.memory, 'memory');
|
||||
}
|
||||
return body;
|
||||
}
|
||||
function validateStorageStatus(value) {
|
||||
return requireResponseObject(value, 'storage status response');
|
||||
}
|
||||
function validateSkillSummary(value, what) {
|
||||
const body = requireResponseObject(value, what);
|
||||
requireResponseString(body, 'name');
|
||||
optionalResponseString(body, 'description');
|
||||
optionalNullableString(body, 'category');
|
||||
optionalResponseString(body, 'execution_mode');
|
||||
optionalResponseBoolean(body, 'enabled');
|
||||
optionalResponseNumber(body, 'revision');
|
||||
optionalResponseString(body, 'manifest_sha256');
|
||||
optionalResponseNumber(body, 'files');
|
||||
optionalResponseNumber(body, 'bytes');
|
||||
optionalResponseBoolean(body, 'script_changed');
|
||||
optionalStringOrNumber(body, 'created_at');
|
||||
optionalStringOrNumber(body, 'updated_at');
|
||||
return body;
|
||||
}
|
||||
function validateSkillListing(value) {
|
||||
const body = requireResponseObject(value, 'skills response');
|
||||
const items = requireResponseArray(body, 'items');
|
||||
items.forEach((entry, index) => validateSkillSummary(entry, `items[${index}]`));
|
||||
optionalResponseNumber(body, 'total');
|
||||
optionalResponseNumber(body, 'trash_total');
|
||||
return body;
|
||||
}
|
||||
function validateSkillBundle(value) {
|
||||
const body = requireResponseObject(value, 'skill bundle response');
|
||||
requireResponseString(body, 'name');
|
||||
optionalResponseNumber(body, 'revision');
|
||||
if (typeof body.revision !== 'number' || !Number.isFinite(body.revision)) {
|
||||
throw new Error('revision must be a number');
|
||||
}
|
||||
requireResponseString(body, 'manifest_sha256');
|
||||
optionalResponseBoolean(body, 'script_changed');
|
||||
optionalResponseStringArray(body, 'script_changes');
|
||||
const files = requireResponseArray(body, 'files');
|
||||
files.forEach((entry, index) => {
|
||||
const file = requireResponseObject(entry, `files[${index}]`);
|
||||
requireResponseString(file, 'path');
|
||||
requireResponseString(file, 'sha256');
|
||||
requireResponseString(file, 'data', true);
|
||||
optionalResponseNumber(file, 'size');
|
||||
optionalResponseString(file, 'encoding');
|
||||
});
|
||||
return body;
|
||||
}
|
||||
function validateSkillWriteResult(value) {
|
||||
const body = requireResponseObject(value, 'skill write response');
|
||||
if (body.skill !== undefined && body.skill !== null) {
|
||||
validateSkillSummary(body.skill, 'skill');
|
||||
}
|
||||
optionalResponseNumber(body, 'revision');
|
||||
optionalResponseString(body, 'manifest_sha256');
|
||||
return body;
|
||||
}
|
||||
/** Map one HTTP error body onto a {@link CloudError}. */
|
||||
function errorFromBody(status, raw, retryAfterHeader) {
|
||||
let code = `http_${status}`;
|
||||
|
|
@ -78,7 +267,7 @@ export class CloudClient {
|
|||
constructor(options) {
|
||||
this.options = options;
|
||||
}
|
||||
async request(method, path, body, tokenOverride) {
|
||||
async request(method, path, body, tokenOverride, validate) {
|
||||
const token = tokenOverride ?? this.options.token();
|
||||
const base = this.options.baseUrl();
|
||||
const url = `${base}${path}`;
|
||||
|
|
@ -98,22 +287,51 @@ export class CloudClient {
|
|||
const reason = error instanceof Error ? error.message : String(error);
|
||||
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} ${path}: ${reason}` } };
|
||||
}
|
||||
const text = await response.text().catch(() => '');
|
||||
// A failed body read (connection torn mid-response) is NOT an empty
|
||||
// success: a 200 whose payload cannot be read must surface as an error,
|
||||
// not as `{ ok: true, data: {} }`.
|
||||
let text;
|
||||
try {
|
||||
text = await response.text();
|
||||
}
|
||||
catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: errorFromBody(response.status, `body read failed: ${reason}`, response.headers.get('retry-after')) };
|
||||
}
|
||||
return { ok: false, error: { status: response.status, code: 'body_read_error', message: `${method} ${path}: body read failed: ${reason}` } };
|
||||
}
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) };
|
||||
}
|
||||
if (text.trim() === '')
|
||||
return { ok: true, status: response.status, data: {} };
|
||||
try {
|
||||
return { ok: true, status: response.status, data: JSON.parse(text) };
|
||||
// Empty bodies are endpoint-specific: the validator decides whether `{}`
|
||||
// is an acceptable 2xx payload (add/turn acknowledgements) or a missing
|
||||
// required field (list/search/projects/skills/bundle). Probes pass no
|
||||
// validator on purpose: any 2xx already proves the credential, and a 400
|
||||
// remains their "authenticated but bad body" signal.
|
||||
let parsed = {};
|
||||
if (text.trim() !== '') {
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: `${method} ${path}: response was not JSON` } };
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: 'response was not JSON' } };
|
||||
if (validate !== undefined) {
|
||||
try {
|
||||
validate(parsed);
|
||||
}
|
||||
catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_response', message: `${method} ${path}: ${reason}` } };
|
||||
}
|
||||
}
|
||||
return { ok: true, status: response.status, data: parsed };
|
||||
}
|
||||
/** Report one conversation turn (activity:write token). */
|
||||
reportTurn(payload, token) {
|
||||
return this.request('POST', '/activity/turn', payload, token);
|
||||
return this.request('POST', '/activity/turn', payload, token, validateTurnAck);
|
||||
}
|
||||
/**
|
||||
* Read-only reachability probe: any HTTP answer (even 401 or 404) proves the
|
||||
|
|
@ -136,7 +354,7 @@ export class CloudClient {
|
|||
}
|
||||
/** Stage one turn summary as pending proposals (summary:write token). */
|
||||
submitSummary(payload, token) {
|
||||
return this.request('POST', '/activity/summary', payload, token);
|
||||
return this.request('POST', '/activity/summary', payload, token, validateSummaryAck);
|
||||
}
|
||||
/**
|
||||
* Verify a summary token without staging anything.
|
||||
|
|
@ -174,11 +392,11 @@ export class CloudClient {
|
|||
const body = { query, k };
|
||||
if (project !== undefined && project !== '')
|
||||
body.filters = { project_id: project };
|
||||
return this.request('POST', '/memory/query', body);
|
||||
return this.request('POST', '/memory/query', body, undefined, validateSearchResponse);
|
||||
}
|
||||
/** Read one memory by id (memory token). */
|
||||
read(id) {
|
||||
return this.request('GET', `/memory/${encodeURIComponent(id)}`);
|
||||
return this.request('GET', `/memory/${encodeURIComponent(id)}`, undefined, undefined, validateMemoryRead);
|
||||
}
|
||||
/** List memories with optional paging filters (memory token). */
|
||||
list(options = {}) {
|
||||
|
|
@ -190,7 +408,7 @@ export class CloudClient {
|
|||
if (options.project !== undefined && options.project !== '')
|
||||
params.set('project_id', options.project);
|
||||
const suffix = params.toString() === '' ? '' : `?${params.toString()}`;
|
||||
return this.request('GET', `/memory/all${suffix}`);
|
||||
return this.request('GET', `/memory/all${suffix}`, undefined, undefined, validateListResponse);
|
||||
}
|
||||
/** Store one memory; `operationId` makes the write idempotent (memory token). */
|
||||
add(input) {
|
||||
|
|
@ -204,31 +422,31 @@ export class CloudClient {
|
|||
body.project_id = input.project;
|
||||
if (input.sector !== undefined && input.sector !== '')
|
||||
body.metadata = { primary_sector: input.sector };
|
||||
return this.request('POST', '/memory/add', body);
|
||||
return this.request('POST', '/memory/add', body, undefined, validateAddResponse);
|
||||
}
|
||||
/** List the account's projects (memory token). */
|
||||
projects() {
|
||||
return this.request('GET', '/dashboard/projects');
|
||||
return this.request('GET', '/dashboard/projects', undefined, undefined, validateProjectsResponse);
|
||||
}
|
||||
/** Storage configuration state (memory token). */
|
||||
storageStatus() {
|
||||
return this.request('GET', '/storage/status');
|
||||
return this.request('GET', '/storage/status', undefined, undefined, validateStorageStatus);
|
||||
}
|
||||
/** List the cloud skill center inventory (memory token). */
|
||||
listSkills() {
|
||||
return this.request('GET', '/skills');
|
||||
return this.request('GET', '/skills', undefined, undefined, validateSkillListing);
|
||||
}
|
||||
/** Fetch one skill bundle with hashed, base64-carried files (memory token). */
|
||||
skillBundle(name) {
|
||||
return this.request('GET', `/skills/${encodeURIComponent(name)}/bundle`);
|
||||
return this.request('GET', `/skills/${encodeURIComponent(name)}/bundle`, undefined, undefined, validateSkillBundle);
|
||||
}
|
||||
/** Create one skill in the center; `expected_revision` must be 0 (memory token). */
|
||||
createSkill(body) {
|
||||
return this.request('POST', '/skills', body);
|
||||
return this.request('POST', '/skills', body, undefined, validateSkillWriteResult);
|
||||
}
|
||||
/** Replace one skill's files/description at an expected revision (memory token). */
|
||||
updateSkill(name, body) {
|
||||
return this.request('PATCH', `/skills/${encodeURIComponent(name)}`, body);
|
||||
return this.request('PATCH', `/skills/${encodeURIComponent(name)}`, body, undefined, validateSkillWriteResult);
|
||||
}
|
||||
/**
|
||||
* One call against the dashboard auth surface (`/api/auth/*`).
|
||||
|
|
@ -238,8 +456,12 @@ export class CloudClient {
|
|||
* the origin of the configured base URL is sent explicitly — that is a header
|
||||
* only a non-browser client can set, which is exactly what this is.
|
||||
*/
|
||||
async authFetch(method, path, body, cookie) {
|
||||
const baseUrl = this.options.baseUrl();
|
||||
async authFetch(method, path, body, cookie, target) {
|
||||
// The target is frozen by the caller at the start of the login flow; every
|
||||
// auth request in that flow must hit the same service, even if settings
|
||||
// change while a request is in flight.
|
||||
const baseUrl = target?.baseUrl ?? this.options.baseUrl();
|
||||
const timeoutMs = target?.timeoutMs ?? this.options.timeoutMs();
|
||||
const base = authBase(baseUrl);
|
||||
if (base === '')
|
||||
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } };
|
||||
|
|
@ -252,7 +474,7 @@ export class CloudClient {
|
|||
}
|
||||
if (cookie !== undefined && cookie !== '')
|
||||
headers.Cookie = cookie;
|
||||
const init = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) };
|
||||
const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) };
|
||||
if (body !== undefined) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
init.body = JSON.stringify(body);
|
||||
|
|
@ -265,7 +487,17 @@ export class CloudClient {
|
|||
const reason = error instanceof Error ? error.message : String(error);
|
||||
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} /auth${path}: ${reason}` } };
|
||||
}
|
||||
const text = await response.text().catch(() => '');
|
||||
let text;
|
||||
try {
|
||||
text = await response.text();
|
||||
}
|
||||
catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: errorFromBody(response.status, `body read failed: ${reason}`, response.headers.get('retry-after')) };
|
||||
}
|
||||
return { ok: false, error: { status: response.status, code: 'body_read_error', message: `${method} /auth${path}: body read failed: ${reason}` } };
|
||||
}
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) };
|
||||
}
|
||||
|
|
@ -275,7 +507,9 @@ export class CloudClient {
|
|||
parsed = JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
parsed = {};
|
||||
// Swallowing a malformed login/token body would make the caller treat
|
||||
// garbage as an empty success; surface it as a normalized failure.
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: `${method} /auth${path}: response was not JSON` } };
|
||||
}
|
||||
}
|
||||
return { ok: true, status: response.status, body: parsed, headers: response.headers };
|
||||
|
|
@ -287,28 +521,45 @@ export class CloudClient {
|
|||
* is a short-lived session cookie that the caller immediately spends on
|
||||
* {@link CloudClient.mintToken} and then drops.
|
||||
*/
|
||||
async login(username, password) {
|
||||
const sent = await this.authFetch('POST', '/login', { username, password });
|
||||
async login(username, password, target) {
|
||||
const sent = await this.authFetch('POST', '/login', { username, password }, undefined, target);
|
||||
if (!sent.ok)
|
||||
return sent;
|
||||
const cookie = sessionCookieOf(sent.headers);
|
||||
if (cookie === '') {
|
||||
return { ok: false, error: { status: sent.status, code: 'no_session', message: '登录成功,但服务端没有下发会话' } };
|
||||
}
|
||||
const body = sent.body;
|
||||
return { ok: true, status: sent.status, data: { user: body.user ?? {}, sessionCookie: cookie } };
|
||||
let body;
|
||||
try {
|
||||
body = requireResponseObject(sent.body, 'login response');
|
||||
if (body.user !== undefined && body.user !== null)
|
||||
requireResponseObject(body.user, 'login response user');
|
||||
}
|
||||
catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
return { ok: false, error: { status: sent.status, code: 'invalid_response', message: `POST /auth/login: ${reason}` } };
|
||||
}
|
||||
const user = (body.user ?? {});
|
||||
return { ok: true, status: sent.status, data: { user, sessionCookie: cookie } };
|
||||
}
|
||||
/** Mint one scoped API token using a live session cookie. */
|
||||
async mintToken(sessionCookie, scope, label) {
|
||||
const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie);
|
||||
async mintToken(sessionCookie, scope, label, target) {
|
||||
const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie, target);
|
||||
if (!sent.ok)
|
||||
return sent;
|
||||
const body = sent.body;
|
||||
const issued = body.token;
|
||||
if (issued === undefined || typeof issued.token !== 'string' || issued.token === '') {
|
||||
return { ok: false, error: { status: sent.status, code: 'no_token', message: '服务端没有返回令牌' } };
|
||||
try {
|
||||
const body = requireResponseObject(sent.body, 'token response');
|
||||
const issued = requireResponseObject(body.token, 'token response token');
|
||||
requireResponseString(issued, 'token');
|
||||
optionalResponseString(issued, 'id');
|
||||
optionalResponseString(issued, 'scope');
|
||||
optionalResponseString(issued, 'label');
|
||||
return { ok: true, status: sent.status, data: issued };
|
||||
}
|
||||
catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
return { ok: false, error: { status: sent.status, code: 'invalid_response', message: `POST /auth/tokens: ${reason}` } };
|
||||
}
|
||||
return { ok: true, status: sent.status, data: issued };
|
||||
}
|
||||
}
|
||||
/** Render a {@link CloudError} as one display line. */
|
||||
|
|
|
|||
|
|
@ -133,8 +133,12 @@ async function serveLogin(deps, req, res) {
|
|||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
const target = deps.store.settings().baseUrl;
|
||||
if (!isSecureLoginTarget(target)) {
|
||||
// Snapshot the complete connection before any credential leaves the
|
||||
// process. Every auth call in this flow is pinned to this target, and the
|
||||
// final patch is refused if the configured address changed meanwhile.
|
||||
const settings = deps.store.settings();
|
||||
const target = { baseUrl: settings.baseUrl, timeoutMs: settings.requestTimeoutMs };
|
||||
if (!isSecureLoginTarget(target.baseUrl)) {
|
||||
// Refuse to put a password on a plaintext channel that is not loopback.
|
||||
json(res, 400, { ok: false, error: '服务地址不是 HTTPS,拒绝在上面发送密码,请先把服务地址改成 https://' });
|
||||
return;
|
||||
|
|
@ -169,21 +173,25 @@ async function serveLogin(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
const client = deps.client();
|
||||
const session = await client.login(username, password);
|
||||
const session = await client.login(username, password, target);
|
||||
if (!session.ok) {
|
||||
const status = session.error.status === 429 ? 429 : 401;
|
||||
json(res, status, { ok: false, error: describeError(session.error) });
|
||||
return;
|
||||
}
|
||||
const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity);
|
||||
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory);
|
||||
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary);
|
||||
const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity, target);
|
||||
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory, target);
|
||||
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary, target);
|
||||
if (!activity.ok && !memory.ok) {
|
||||
const first = activity.ok ? memory : activity;
|
||||
const reason = first.ok ? '无法创建令牌' : describeError(first.error);
|
||||
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` });
|
||||
return;
|
||||
}
|
||||
// Atomic account switch: a scope whose mint failed must not keep the token
|
||||
// of the PREVIOUS account — clearing beats carrying a stale credential the
|
||||
// user just replaced. (Writing a token clears the clear-marker, so ordering
|
||||
// inside one patch is irrelevant.)
|
||||
const patch = {};
|
||||
if (activity.ok && typeof activity.data.token === 'string')
|
||||
patch.activityToken = activity.data.token;
|
||||
|
|
@ -191,6 +199,19 @@ async function serveLogin(deps, req, res) {
|
|||
patch.memoryToken = memory.data.token;
|
||||
if (summary.ok && typeof summary.data.token === 'string')
|
||||
patch.summaryToken = summary.data.token;
|
||||
if (!activity.ok || typeof activity.data.token !== 'string')
|
||||
patch.clearActivityToken = true;
|
||||
if (!memory.ok || typeof memory.data.token !== 'string')
|
||||
patch.clearMemoryToken = true;
|
||||
if (!summary.ok || typeof summary.data.token !== 'string')
|
||||
patch.clearSummaryToken = true;
|
||||
// A settings edit while login/mintToken was in flight could otherwise bind
|
||||
// fresh tokens minted for the OLD service to the NEW address. Refuse the
|
||||
// patch outright: no token at all is safer than a wrong-attribution token.
|
||||
if (deps.store.settings().baseUrl !== target.baseUrl) {
|
||||
json(res, 409, { ok: false, error: '登录过程中服务地址已变更,本次登录结果已丢弃,请确认服务地址后重新登录' });
|
||||
return;
|
||||
}
|
||||
const applied = deps.store.patch(patch);
|
||||
if (!applied.ok) {
|
||||
json(res, 500, { ok: false, error: applied.error });
|
||||
|
|
@ -239,10 +260,11 @@ async function serveSync(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
if (suffix === '/run') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
// Mutating route: the method, origin and content-type gates live in
|
||||
// jsonBody so a cross-site form/text POST cannot trigger a sync pass.
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
}
|
||||
const stats = await sync.syncOnce();
|
||||
json(res, 200, { ok: true, stats, conflicts: await sync.conflictDetails() });
|
||||
return;
|
||||
|
|
@ -255,7 +277,7 @@ async function serveSync(deps, req, res) {
|
|||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const result = await sync.resolveConflict(body.name, body.action);
|
||||
const result = await sync.resolveConflict(body.name, body.action, body.conflictId);
|
||||
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
|
||||
return;
|
||||
}
|
||||
|
|
@ -267,7 +289,7 @@ async function serveSync(deps, req, res) {
|
|||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const result = await sync.resolveConflicts(body.action);
|
||||
const result = await sync.resolveConflicts(body.action, body.conflictIds);
|
||||
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() });
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,18 @@ export const DEFAULT_SETTINGS = {
|
|||
summaryMaxChars: 6000,
|
||||
skillsSyncEnabled: true,
|
||||
skillsDir: '',
|
||||
/** Local-first memory: on by default, independent of any cloud account. */
|
||||
localMemoryEnabled: true,
|
||||
/** Cloud memory adapter; off by default in the local-first phase. */
|
||||
cloudMemoryEnabled: false,
|
||||
/** Automatically create the global and current-project spaces. */
|
||||
autoMemorySpaces: true,
|
||||
/** Automatically capture explicit long-term facts from conversation turns. */
|
||||
autoSummaryEnabled: true,
|
||||
/** Automatically maintain the USER.md profile from explicit preferences. */
|
||||
autoProfileEnabled: true,
|
||||
/** Default result count for local memory search. */
|
||||
localMemoryK: 5,
|
||||
};
|
||||
const MIN_TIMEOUT_MS = 1000;
|
||||
const MAX_TIMEOUT_MS = 60_000;
|
||||
|
|
@ -112,5 +124,18 @@ export function settingsFromConfig(raw) {
|
|||
result.skillsSyncEnabled = source.skillsSyncEnabled;
|
||||
if (typeof source.skillsDir === 'string')
|
||||
result.skillsDir = source.skillsDir.trim().slice(0, 512);
|
||||
if (typeof source.localMemoryEnabled === 'boolean')
|
||||
result.localMemoryEnabled = source.localMemoryEnabled;
|
||||
if (typeof source.cloudMemoryEnabled === 'boolean')
|
||||
result.cloudMemoryEnabled = source.cloudMemoryEnabled;
|
||||
if (typeof source.autoMemorySpaces === 'boolean')
|
||||
result.autoMemorySpaces = source.autoMemorySpaces;
|
||||
if (typeof source.autoSummaryEnabled === 'boolean')
|
||||
result.autoSummaryEnabled = source.autoSummaryEnabled;
|
||||
if (typeof source.autoProfileEnabled === 'boolean')
|
||||
result.autoProfileEnabled = source.autoProfileEnabled;
|
||||
const localMemoryK = boundedInt(source.localMemoryK, 1, 100);
|
||||
if (localMemoryK !== undefined)
|
||||
result.localMemoryK = localMemoryK;
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import { brainKernel } from "../kernel.js";
|
||||
import { createMemoryTools } from "../memory/tools.js";
|
||||
import { conversationIdOf, redactSecrets, textOf, turnOf } from "../reporter.js";
|
||||
export const name = 'dsh-brain-memory';
|
||||
/** Services required before `apply` runs. */
|
||||
export const inject = ['tools'];
|
||||
/** Register the sub-plugin with the host. */
|
||||
export function apply(ctx, config) {
|
||||
const kernel = brainKernel(config, ctx.logger('dsh-brain'));
|
||||
const logger = ctx.logger('dsh-brain');
|
||||
const kernel = brainKernel(config, logger);
|
||||
kernel.activate('memory');
|
||||
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation');
|
||||
ctx.inject(['tools'], (toolsCtx) => {
|
||||
|
|
@ -16,4 +18,114 @@ export function apply(ctx, config) {
|
|||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`);
|
||||
}
|
||||
});
|
||||
// Project the compact USER.md/MEMORY.md state into the system prompt each turn.
|
||||
// The files are generated from explicit profile/rule records only.
|
||||
ctx.inject(['systemPrompt'], (prompted) => {
|
||||
const host = prompted;
|
||||
const service = typeof host.get === 'function' ? host.get('systemPrompt') : host.systemPrompt;
|
||||
const prompt = service;
|
||||
prompt?.section?.({
|
||||
name: 'dsh-brain:local-memory',
|
||||
order: 151,
|
||||
text: () => kernel.settings().localMemoryEnabled === false ? '' : kernel.localMemory.projectionText(),
|
||||
});
|
||||
});
|
||||
// Local automatic summary: consume real host messages (structured content),
|
||||
// ignore host/plugin injections, and persist progress by stable session + turn.
|
||||
const turns = new Map();
|
||||
const pending = new Map();
|
||||
const openTurns = new Map();
|
||||
let flushing = false;
|
||||
let retryTimer;
|
||||
const onEvent = ctx.on;
|
||||
const workspaceOfSession = (session) => session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace;
|
||||
const isInjected = (value) => {
|
||||
if (value === null || typeof value !== 'object')
|
||||
return false;
|
||||
const source = value.source;
|
||||
if (source === null || typeof source !== 'object')
|
||||
return false;
|
||||
const kind = source.kind;
|
||||
return typeof kind === 'string' && kind !== 'user';
|
||||
};
|
||||
const flushPending = async () => {
|
||||
if (flushing || pending.size === 0)
|
||||
return;
|
||||
flushing = true;
|
||||
try {
|
||||
for (const [key, item] of [...pending]) {
|
||||
try {
|
||||
await kernel.localMemory.withWorkspace(item.workspace, () => kernel.localMemory.summarizeConversation({
|
||||
sessionId: item.conversation,
|
||||
turns: [{ turnId: String(item.turn), user: item.user }],
|
||||
}, item.workspace));
|
||||
pending.delete(key);
|
||||
}
|
||||
catch (error) {
|
||||
item.attempts += 1;
|
||||
logger.warn('dsh-brain local summary failed (will retry): ' + (error instanceof Error ? error.message : String(error)));
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
flushing = false;
|
||||
if (pending.size > 0) {
|
||||
if (retryTimer !== undefined)
|
||||
clearTimeout(retryTimer);
|
||||
retryTimer = setTimeout(() => { retryTimer = undefined; void flushPending(); }, 2000);
|
||||
retryTimer.unref?.();
|
||||
}
|
||||
}
|
||||
};
|
||||
ctx.effect(() => {
|
||||
const dispose = onEvent('session/event', (session, event) => {
|
||||
const conversation = conversationIdOf(session);
|
||||
if (conversation === undefined)
|
||||
return;
|
||||
if (event.type === 'turn/start') {
|
||||
const started = turnOf(event.data);
|
||||
if (started !== undefined)
|
||||
openTurns.set(conversation, started);
|
||||
void flushPending();
|
||||
return;
|
||||
}
|
||||
const eventTurn = turnOf(event.data);
|
||||
const turn = eventTurn ?? openTurns.get(conversation);
|
||||
if (event.type === 'user/message') {
|
||||
const raw = textOf(event.data?.message ?? event.data);
|
||||
if (turn === undefined || raw === undefined || isInjected(event.data?.message ?? event.data))
|
||||
return;
|
||||
const key = conversation + ':' + String(turn);
|
||||
const entry = turns.get(key) ?? { turn, user: [] };
|
||||
entry.user.push(redactSecrets(raw).slice(0, 4000));
|
||||
turns.set(key, entry);
|
||||
return;
|
||||
}
|
||||
if (event.type === 'turn/end' && turn !== undefined) {
|
||||
const key = conversation + ':' + String(turn);
|
||||
const entry = turns.get(key);
|
||||
turns.delete(key);
|
||||
if (eventTurn === undefined || openTurns.get(conversation) === eventTurn)
|
||||
openTurns.delete(conversation);
|
||||
if (entry === undefined || entry.user.length === 0)
|
||||
return;
|
||||
const settings = kernel.settings();
|
||||
if (settings.localMemoryEnabled === false || settings.autoSummaryEnabled === false)
|
||||
return;
|
||||
pending.set(key, { conversation, turn, ...(workspaceOfSession(session) === undefined ? {} : { workspace: workspaceOfSession(session) }), user: entry.user.join('\n'), attempts: 0 });
|
||||
void flushPending();
|
||||
return;
|
||||
}
|
||||
if (event.type === 'session/end' || event.type === 'session/close' || event.type === 'session/closed' || event.type === 'session/terminated') {
|
||||
openTurns.delete(conversation);
|
||||
for (const key of turns.keys())
|
||||
if (key.startsWith(conversation + ':'))
|
||||
turns.delete(key);
|
||||
}
|
||||
});
|
||||
return () => { dispose(); if (retryTimer !== undefined) {
|
||||
clearTimeout(retryTimer);
|
||||
retryTimer = undefined;
|
||||
} };
|
||||
}, 'dsh-brain-memory: local summary');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@
|
|||
*/
|
||||
import { join, resolve } from 'node:path';
|
||||
import { CloudClient } from "./api.js";
|
||||
import { LocalMemoryManager, LocalMemoryRemote } from "./local-memory/index.js";
|
||||
import { VERSION } from "./version.js";
|
||||
import { createCloudMemoryRemoteFactory } from "./cloudsync.js";
|
||||
import { ClientRegistry } from "./clients.js";
|
||||
import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js";
|
||||
|
|
@ -30,15 +32,33 @@ import { SkillSync } from "./skill-sync.js";
|
|||
import { SkillUpdater } from "./skill-update.js";
|
||||
import { SettingsStore, dshHome } from "./store.js";
|
||||
import { AdminSkillRepository } from "./skills/repository.js";
|
||||
/** Version reported by the status card. */
|
||||
export const VERSION = '0.9.11';
|
||||
/** Version reported by the status card (single source: package.json). */
|
||||
export { VERSION };
|
||||
/** The shared service set behind every dsh-brain sub-plugin entry. */
|
||||
/** Resolve a workspace from the different host tool/session context shapes. */
|
||||
function workspaceFromExec(exec) {
|
||||
if (exec === null || typeof exec !== 'object')
|
||||
return undefined;
|
||||
const value = exec;
|
||||
const candidates = [
|
||||
value.workspace, value.cwd, value.projectPath,
|
||||
value.session?.cwd, value.session?.workspace, value.session?.header?.cwd, value.session?.header?.workspace,
|
||||
value.agent?.session?.cwd, value.agent?.session?.header?.cwd,
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && candidate.trim() !== '')
|
||||
return candidate;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
export class BrainKernel {
|
||||
active = new Set();
|
||||
settingsOf;
|
||||
store;
|
||||
client;
|
||||
memoryRemoteFactory;
|
||||
localMemory;
|
||||
localMemoryRemote;
|
||||
reporter;
|
||||
skillAdmin;
|
||||
skillRepository;
|
||||
|
|
@ -65,12 +85,38 @@ export class BrainKernel {
|
|||
settings: () => settings(),
|
||||
memoryToken: () => store.memoryToken(),
|
||||
});
|
||||
// Local-first memory is independent of the cloud adapter: it initializes
|
||||
// lazily on the first memory tool call and needs no token or account.
|
||||
this.localMemory = new LocalMemoryManager({
|
||||
cwd: () => process.cwd(),
|
||||
settings: () => ({
|
||||
localMemoryEnabled: settings().localMemoryEnabled,
|
||||
cloudMemoryEnabled: settings().cloudMemoryEnabled,
|
||||
autoMemorySpaces: settings().autoMemorySpaces,
|
||||
autoSummaryEnabled: settings().autoSummaryEnabled,
|
||||
autoProfileEnabled: settings().autoProfileEnabled,
|
||||
localMemoryK: settings().localMemoryK,
|
||||
}),
|
||||
});
|
||||
this.localMemoryRemote = new LocalMemoryRemote(this.localMemory);
|
||||
// The global space is part of first boot; project space stays lazy until
|
||||
// the first memory use in that project.
|
||||
if (settings().localMemoryEnabled !== false && settings().autoMemorySpaces !== false)
|
||||
void this.localMemory.ensureGlobal().catch((error) => { logger.warn('dsh-brain local memory initialization failed: ' + (error instanceof Error ? error.message : String(error))); });
|
||||
this.reporter = new Reporter({
|
||||
client,
|
||||
// Pinned clients: one request leaves under the connection it started
|
||||
// with, never under whatever settings say by the time it lands.
|
||||
clientFor: (context) => new CloudClient({
|
||||
baseUrl: () => context.baseUrl,
|
||||
token: () => context.activityToken,
|
||||
timeoutMs: () => context.timeoutMs,
|
||||
}),
|
||||
settings: () => ({ enabled: settings().activityEnabled, clientId: settings().clientId }),
|
||||
activityToken: () => store.activityToken(),
|
||||
baseUrl: () => settings().baseUrl,
|
||||
summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }),
|
||||
summaryToken: () => store.summaryToken(),
|
||||
timeoutMs: () => settings().requestTimeoutMs,
|
||||
log: (message) => logger.warn(message),
|
||||
});
|
||||
// The skill bundle owns its folders; the kernel only wires the shared root
|
||||
|
|
@ -96,11 +142,26 @@ export class BrainKernel {
|
|||
});
|
||||
this.skillSync = new SkillSync({
|
||||
client: () => client,
|
||||
clientForScope: (scope) => new CloudClient({
|
||||
baseUrl: () => scope.endpoint,
|
||||
token: () => scope.accountToken,
|
||||
timeoutMs: () => settings().requestTimeoutMs,
|
||||
}),
|
||||
settings: () => ({
|
||||
enabled: settings().enabled,
|
||||
skillsSyncEnabled: settings().skillsSyncEnabled,
|
||||
}),
|
||||
repository: () => this.skillRepository,
|
||||
repositoryForScope: (scope) => new AdminSkillRepository({
|
||||
admin: skillAdmin,
|
||||
skillsRoot: () => scope.root,
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
}),
|
||||
scope: () => ({
|
||||
endpoint: settings().baseUrl,
|
||||
accountToken: store.memoryToken(),
|
||||
root: skillsRootDir(),
|
||||
}),
|
||||
log: (message) => logger.info(message),
|
||||
});
|
||||
// The tree's sources are detected per call so a directory created while
|
||||
|
|
@ -167,10 +228,28 @@ export class BrainKernel {
|
|||
const store = this.store;
|
||||
const settings = this.settingsOf;
|
||||
return {
|
||||
remote: () => this.memoryRemoteFactory.current(),
|
||||
// Local-first by default. The cloud adapter is only selected when the
|
||||
// user explicitly enables it AND has a memory token; otherwise memory
|
||||
// tools stay fully usable offline.
|
||||
remote: () => {
|
||||
const effective = settings();
|
||||
const localEnabled = effective.localMemoryEnabled !== false;
|
||||
const cloudEnabled = effective.cloudMemoryEnabled === true && store.memoryToken() !== '';
|
||||
if (cloudEnabled)
|
||||
return this.memoryRemoteFactory.current();
|
||||
if (localEnabled)
|
||||
return this.localMemoryRemote;
|
||||
throw new Error('memory_disabled');
|
||||
},
|
||||
client: () => this.client,
|
||||
memoryToken: () => store.memoryToken(),
|
||||
settings: () => ({ enabled: settings().memoryEnabled, defaultK: settings().defaultK }),
|
||||
settings: () => {
|
||||
const effective = settings();
|
||||
const local = effective.localMemoryEnabled !== false && !(effective.cloudMemoryEnabled === true && store.memoryToken() !== '');
|
||||
return { enabled: effective.memoryEnabled, defaultK: local ? effective.localMemoryK : effective.defaultK };
|
||||
},
|
||||
localMemory: () => settings().localMemoryEnabled !== false,
|
||||
workspace: (exec) => workspaceFromExec(exec),
|
||||
};
|
||||
}
|
||||
/**
|
||||
|
|
@ -193,6 +272,7 @@ export class BrainKernel {
|
|||
updates: skills ? this.updater : undefined,
|
||||
clients: skills ? this.clients : undefined,
|
||||
mcp: this.isActive('mcp'),
|
||||
localMemory: this.localMemory,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
export { DepartmentManager } from "./manager.js";
|
||||
|
|
@ -0,0 +1,256 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { join } from 'node:path';
|
||||
import { LocalMemoryManager, projectIdFor } from "../manager.js";
|
||||
import { containsSecret, JsonMemoryStore } from "../storage.js";
|
||||
import { DepartmentRegistry } from "./registry.js";
|
||||
function text(value, max, required = false) {
|
||||
const result = typeof value === 'string' ? value.trim().slice(0, max) : '';
|
||||
if (required && result === '')
|
||||
throw new Error('department_required_field');
|
||||
return result;
|
||||
}
|
||||
function list(value) {
|
||||
if (!Array.isArray(value))
|
||||
return [];
|
||||
return [...new Set(value.filter((item) => typeof item === 'string').map((item) => item.trim().slice(0, 200)).filter((item) => item !== ''))].slice(0, 50);
|
||||
}
|
||||
function hostName(value) {
|
||||
const host = text(value, 64, true);
|
||||
if (!/^[a-z0-9][a-z0-9_-]*$/.test(host))
|
||||
throw new Error('department_invalid_host');
|
||||
return host;
|
||||
}
|
||||
function limitOf(value) {
|
||||
return Math.max(1, Math.min(50, Math.trunc(value ?? 5)));
|
||||
}
|
||||
/** Persistent departments: private memory, reusable session references and bounded recall. */
|
||||
export class DepartmentManager {
|
||||
memory;
|
||||
constructor(options) { this.memory = options.memory; }
|
||||
root(scope) { return scope === 'global' ? this.memory.globalRoot : this.memory.projectRoot; }
|
||||
registry(scope) { return new DepartmentRegistry(join(this.root(scope), 'departments', 'registry.json')); }
|
||||
store(department) {
|
||||
return new JsonMemoryStore(join(this.root(department.scope), 'departments', department.id, 'memory-space'), 'department', department.spaceId);
|
||||
}
|
||||
async activeStore(department) {
|
||||
if (!department.active)
|
||||
throw new Error('department_disabled');
|
||||
const store = this.store(department);
|
||||
const meta = await store.init(department.name + ' 私有记忆');
|
||||
if (!meta.active)
|
||||
throw new Error('department_disabled');
|
||||
return store;
|
||||
}
|
||||
async find(id) {
|
||||
const global = (await this.registry('global').read()).departments.find((item) => item.id === id);
|
||||
if (global !== undefined)
|
||||
return global;
|
||||
return (await this.registry('project').read()).departments.find((item) => item.id === id);
|
||||
}
|
||||
async required(id) {
|
||||
const department = await this.find(id);
|
||||
if (department === undefined)
|
||||
throw new Error('department_not_found');
|
||||
return department;
|
||||
}
|
||||
/** Create once by scope + case-insensitive name; repeated calls return the existing department. */
|
||||
async create(input) {
|
||||
const scope = input.scope ?? 'project';
|
||||
const name = text(input.name, 100, true);
|
||||
const role = text(input.role ?? '', 12000);
|
||||
if (containsSecret(role))
|
||||
throw new Error('secret_not_allowed');
|
||||
await this.memory.ensureGlobal();
|
||||
if (scope === 'project')
|
||||
await this.memory.ensureProject();
|
||||
return this.registry(scope).update(async (file) => {
|
||||
const existing = file.departments.find((item) => item.name.toLocaleLowerCase() === name.toLocaleLowerCase());
|
||||
if (existing !== undefined)
|
||||
return { department: existing, created: false };
|
||||
const id = 'dept_' + randomUUID();
|
||||
const timestamp = new Date().toISOString();
|
||||
const department = {
|
||||
id, name, role, scope,
|
||||
...(scope === 'project' ? { projectId: projectIdFor(this.memory.projectRoot) } : {}),
|
||||
spaceId: 'department_' + id.slice(5),
|
||||
skills: list(input.skills), allowedTools: list(input.allowedTools),
|
||||
memory: { readGlobal: input.readGlobal ?? true, readProject: input.readProject ?? true },
|
||||
sessionRefs: {}, active: true, createdAt: timestamp, updatedAt: timestamp, revision: 1,
|
||||
};
|
||||
await this.activeStore(department);
|
||||
file.departments.push(department);
|
||||
return { department, created: true };
|
||||
});
|
||||
}
|
||||
async get(id) { return this.find(id); }
|
||||
async list(scope) {
|
||||
const scopes = scope === undefined ? ['project', 'global'] : [scope];
|
||||
const files = await Promise.all(scopes.map((item) => this.registry(item).read()));
|
||||
return files.flatMap((file) => file.departments).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id));
|
||||
}
|
||||
async update(id, patch, expectedRevision) {
|
||||
const current = await this.required(id);
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
if (patch.role !== undefined && containsSecret(patch.role))
|
||||
throw new Error('secret_not_allowed');
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id);
|
||||
if (department === undefined)
|
||||
throw new Error('department_not_found');
|
||||
if (expectedRevision !== undefined && department.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
if (patch.name !== undefined)
|
||||
department.name = text(patch.name, 100, true);
|
||||
if (patch.role !== undefined)
|
||||
department.role = text(patch.role, 12000);
|
||||
if (patch.skills !== undefined)
|
||||
department.skills = list(patch.skills);
|
||||
if (patch.allowedTools !== undefined)
|
||||
department.allowedTools = list(patch.allowedTools);
|
||||
if (patch.readGlobal !== undefined || patch.readProject !== undefined) {
|
||||
department.memory = {
|
||||
readGlobal: patch.readGlobal ?? department.memory.readGlobal,
|
||||
readProject: patch.readProject ?? department.memory.readProject,
|
||||
};
|
||||
}
|
||||
department.revision += 1;
|
||||
department.updatedAt = new Date().toISOString();
|
||||
return department;
|
||||
});
|
||||
}
|
||||
/** Return the same portable reference on every resume; a host session id can be attached separately. */
|
||||
async resumeSession(id, host = 'dsh') {
|
||||
const current = await this.required(id);
|
||||
await this.activeStore(current);
|
||||
const normalizedHost = hostName(host);
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id);
|
||||
if (department === undefined)
|
||||
throw new Error('department_not_found');
|
||||
if (!department.active)
|
||||
throw new Error('department_disabled');
|
||||
const timestamp = new Date().toISOString();
|
||||
const existing = department.sessionRefs[normalizedHost];
|
||||
if (existing !== undefined) {
|
||||
existing.lastUsedAt = timestamp;
|
||||
department.updatedAt = timestamp;
|
||||
return existing;
|
||||
}
|
||||
const reference = { id: 'ds_' + randomUUID(), host: normalizedHost, reusable: true, createdAt: timestamp, lastUsedAt: timestamp };
|
||||
department.sessionRefs[normalizedHost] = reference;
|
||||
department.updatedAt = timestamp;
|
||||
return reference;
|
||||
});
|
||||
}
|
||||
/** Attach a real host session without replacing the portable reference. */
|
||||
async attachSession(id, host, hostSessionId) {
|
||||
const normalizedHost = hostName(host);
|
||||
const externalId = text(hostSessionId, 500, true);
|
||||
const reference = await this.resumeSession(id, normalizedHost);
|
||||
const current = await this.required(id);
|
||||
await this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id);
|
||||
if (department === undefined)
|
||||
throw new Error('department_not_found');
|
||||
const target = department.sessionRefs[normalizedHost];
|
||||
if (target === undefined)
|
||||
throw new Error('department_session_not_found');
|
||||
target.hostSessionId = externalId;
|
||||
target.lastUsedAt = new Date().toISOString();
|
||||
department.updatedAt = target.lastUsedAt;
|
||||
});
|
||||
return { ...reference, hostSessionId: externalId };
|
||||
}
|
||||
async checkpoint(id, input, expectedRevision) {
|
||||
const current = await this.required(id);
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000);
|
||||
const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000);
|
||||
if ((currentTask !== undefined && containsSecret(currentTask)) || (handoff !== undefined && containsSecret(handoff)))
|
||||
throw new Error('secret_not_allowed');
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id);
|
||||
if (department === undefined)
|
||||
throw new Error('department_not_found');
|
||||
if (expectedRevision !== undefined && department.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
if (input.currentTask !== undefined) {
|
||||
if (currentTask === '')
|
||||
delete department.currentTask;
|
||||
else
|
||||
department.currentTask = currentTask;
|
||||
}
|
||||
if (input.handoff !== undefined) {
|
||||
if (handoff === '')
|
||||
delete department.handoff;
|
||||
else
|
||||
department.handoff = handoff;
|
||||
}
|
||||
department.revision += 1;
|
||||
department.updatedAt = new Date().toISOString();
|
||||
return department;
|
||||
});
|
||||
}
|
||||
async remember(id, input) {
|
||||
const department = await this.required(id);
|
||||
const store = await this.activeStore(department);
|
||||
return store.add({
|
||||
...input,
|
||||
source: input.source ?? 'department:' + id,
|
||||
departmentId: id,
|
||||
...(department.projectId === undefined ? {} : { projectId: department.projectId }),
|
||||
});
|
||||
}
|
||||
/** Private first on equal scores; project/global are opt-in and the total result count stays bounded. */
|
||||
async recall(id, query, k = 5, workspace) {
|
||||
const department = await this.required(id);
|
||||
const limit = limitOf(k);
|
||||
const privateHits = await this.store(department).search(query, limit);
|
||||
const shared = [];
|
||||
if (department.memory.readProject && department.memory.readGlobal) {
|
||||
shared.push(...await this.memory.searchHits(query, limit * 2, workspace));
|
||||
}
|
||||
else if (department.memory.readGlobal) {
|
||||
shared.push(...await this.memory.searchHits(query, limit, workspace, 'global'));
|
||||
}
|
||||
else if (department.memory.readProject) {
|
||||
shared.push(...await this.memory.searchHits(query, limit, workspace, department.projectId ?? projectIdFor(this.memory.projectRoot)));
|
||||
}
|
||||
const rank = { department: 3, project: 2, global: 1 };
|
||||
const candidates = [
|
||||
...privateHits.map((hit) => ({ ...hit, origin: 'department' })),
|
||||
...shared.map((hit) => ({ ...hit, origin: hit.record.scope === 'global' ? 'global' : 'project' })),
|
||||
];
|
||||
const seen = new Set();
|
||||
return candidates.sort((a, b) => b.score - a.score || rank[b.origin] - rank[a.origin] || b.record.updatedAt.localeCompare(a.record.updatedAt))
|
||||
.filter((hit) => {
|
||||
const key = hit.record.content.trim();
|
||||
if (seen.has(key))
|
||||
return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
}).slice(0, limit);
|
||||
}
|
||||
/** Disable without deleting private memories or allowing automatic session recovery. */
|
||||
async disable(id, expectedRevision) {
|
||||
const current = await this.required(id);
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
const store = this.store(current);
|
||||
if (await store.spaceMeta() !== undefined)
|
||||
await store.setActive(false);
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id);
|
||||
if (department === undefined)
|
||||
throw new Error('department_not_found');
|
||||
if (expectedRevision !== undefined && department.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
department.active = false;
|
||||
department.revision += 1;
|
||||
department.updatedAt = new Date().toISOString();
|
||||
return department;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import { withFileLock } from "../storage.js";
|
||||
const EMPTY = { version: 1, departments: [] };
|
||||
async function atomicWrite(path, content) {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const temporary = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp';
|
||||
try {
|
||||
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
|
||||
await rename(temporary, path);
|
||||
}
|
||||
catch (error) {
|
||||
await rm(temporary, { force: true }).catch(() => { });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/** JSON registry for one global or project department collection. */
|
||||
export class DepartmentRegistry {
|
||||
path;
|
||||
constructor(path) { this.path = path; }
|
||||
async read() {
|
||||
let text;
|
||||
try {
|
||||
text = await readFile(this.path, 'utf8');
|
||||
}
|
||||
catch (error) {
|
||||
if (error.code === 'ENOENT')
|
||||
return { ...EMPTY, departments: [] };
|
||||
throw new Error('department_registry_read_failed: ' + (error instanceof Error ? error.message : String(error)));
|
||||
}
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
throw new Error('department_registry_corrupt');
|
||||
}
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
||||
throw new Error('department_registry_corrupt');
|
||||
const file = value;
|
||||
if (file.version !== undefined && file.version !== 1)
|
||||
throw new Error('department_registry_incompatible');
|
||||
if (!Array.isArray(file.departments))
|
||||
throw new Error('department_registry_incompatible');
|
||||
return { version: 1, departments: file.departments };
|
||||
}
|
||||
async update(job) {
|
||||
return withFileLock(this.path + '.lock', async () => {
|
||||
const file = await this.read();
|
||||
const result = await job(file);
|
||||
await atomicWrite(this.path, JSON.stringify(file, null, 2) + '\n');
|
||||
return result;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export {};
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
export { LocalMemoryManager, globalBrainRoot, projectBrainRoot, projectIdFor } from "./manager.js";
|
||||
export { LocalMemoryRemote } from "./remote.js";
|
||||
export { DepartmentManager } from "./departments/index.js";
|
||||
export { JsonMemoryStore, JsonMemoryStore as LocalMemoryStore, JsonDocumentStore, JsonDocumentStore as LocalDocumentStore, localMemoryHash, containsSecret } from "./storage.js";
|
||||
|
|
@ -0,0 +1,630 @@
|
|||
/** Local-first memory manager: .dsh/brain layout, spaces, projections and summaries. */
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { mkdir, readFile, writeFile, rename, rm, cp, stat, readdir } from 'node:fs/promises';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { dshHome } from "../store.js";
|
||||
import { JsonDocumentStore, JsonMemoryStore, containsSecret, localMemoryHash, withFileLock } from "./storage.js";
|
||||
export function globalBrainRoot() { return resolve(dshHome(), 'brain'); }
|
||||
/** Resolve a user-supplied workspace to its project base, accepting both the project root and its .dsh/brain path. */
|
||||
export function projectBaseOf(value) {
|
||||
const normalized = resolve(value);
|
||||
const brainSuffix = join('.dsh', 'brain');
|
||||
return normalized.endsWith(brainSuffix) ? dirname(dirname(normalized)) : normalized;
|
||||
}
|
||||
export function projectBrainRoot(cwd = process.cwd()) { return join(projectBaseOf(cwd), '.dsh', 'brain'); }
|
||||
export function projectIdFor(root) { return 'project_' + localMemoryHash(resolve(root)).slice(0, 16); }
|
||||
async function atomicWrite(path, content) {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const tmp = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp';
|
||||
try {
|
||||
await writeFile(tmp, content, { encoding: 'utf8', mode: 0o600 });
|
||||
await rename(tmp, path);
|
||||
}
|
||||
catch (error) {
|
||||
await rm(tmp, { force: true }).catch(() => { });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async function treeDigest(root) {
|
||||
const files = [];
|
||||
const walk = async (dir, prefix) => {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const rel = prefix === '' ? entry.name : prefix + '/' + entry.name;
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
await walk(full, rel);
|
||||
continue;
|
||||
}
|
||||
if (entry.isFile())
|
||||
files.push(rel + ':' + localMemoryHash((await readFile(full)).toString('base64')));
|
||||
}
|
||||
};
|
||||
await walk(root, '');
|
||||
return localMemoryHash(files.sort().join('\n'));
|
||||
}
|
||||
async function readJson(path, fallback) {
|
||||
let text;
|
||||
try {
|
||||
text = await readFile(path, 'utf8');
|
||||
}
|
||||
catch (error) {
|
||||
if (error.code === 'ENOENT')
|
||||
return fallback;
|
||||
throw new Error(`local_memory_state_read_failed: ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
throw new Error(`local_memory_state_corrupt: ${path}`);
|
||||
}
|
||||
}
|
||||
async function writeGitIgnore(projectBase) {
|
||||
const dsh = join(projectBase, '.dsh');
|
||||
await mkdir(dsh, { recursive: true });
|
||||
const path = join(dsh, '.gitignore');
|
||||
let text = '';
|
||||
try {
|
||||
text = await readFile(path, 'utf8');
|
||||
}
|
||||
catch { }
|
||||
if (!/^brain\/?$/m.test(text)) {
|
||||
text = text.trimEnd() + (text === '' ? '' : '\n') + 'brain/\n';
|
||||
await atomicWrite(path, text);
|
||||
}
|
||||
}
|
||||
export class LocalMemoryManager {
|
||||
cwdOf;
|
||||
defaultWorkspaceOf;
|
||||
settingsOf;
|
||||
workspaceContext = new AsyncLocalStorage();
|
||||
workspaces = new Map();
|
||||
fixedGlobalRoot;
|
||||
fixedProjectRoot;
|
||||
constructor(options = {}) {
|
||||
this.cwdOf = options.cwd ?? (() => process.cwd());
|
||||
this.defaultWorkspaceOf = options.workspace;
|
||||
this.settingsOf = options.settings ?? (() => ({}));
|
||||
this.fixedGlobalRoot = options.globalRoot;
|
||||
this.fixedProjectRoot = options.projectRoot;
|
||||
}
|
||||
/** Bind one operation to a workspace; AsyncLocalStorage keeps concurrent sessions isolated. */
|
||||
withWorkspace(workspace, job) { return this.workspaceContext.run(workspace, job); }
|
||||
workspacePath(workspace) {
|
||||
const value = workspace ?? this.workspaceContext.getStore() ?? this.defaultWorkspaceOf?.() ?? this.cwdOf();
|
||||
return resolve(value);
|
||||
}
|
||||
projectRootFor(workspace) { return this.fixedProjectRoot ?? projectBrainRoot(this.workspacePath(workspace)); }
|
||||
projectBaseFor(workspace) { return projectBaseOf(this.workspacePath(workspace)); }
|
||||
get globalRoot() { return this.fixedGlobalRoot ?? globalBrainRoot(); }
|
||||
get projectRoot() { return this.projectRootFor(); }
|
||||
get globalStore() { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global'); }
|
||||
projectStoreFor(workspace) { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))); }
|
||||
async storeFor(scope, workspace) {
|
||||
if (scope === 'global')
|
||||
return this.globalStore;
|
||||
return this.ensureProject(workspace);
|
||||
}
|
||||
projectionDirtyPath() { return join(this.globalRoot, 'state', 'projection.json'); }
|
||||
async markProjectionDirty(error) {
|
||||
const marker = String(Date.now()) + '-' + randomUUID();
|
||||
await atomicWrite(this.projectionDirtyPath(), JSON.stringify({ dirty: true, marker, ...(error === undefined ? {} : { lastError: error instanceof Error ? error.message : String(error) }), updatedAt: new Date().toISOString() }, null, 2) + '\n');
|
||||
return marker;
|
||||
}
|
||||
async clearProjectionDirty(marker) {
|
||||
try {
|
||||
const state = JSON.parse(await readFile(this.projectionDirtyPath(), 'utf8'));
|
||||
if (state.marker === marker)
|
||||
await rm(this.projectionDirtyPath(), { force: true });
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
/** Retry a projection left dirty by a committed memory write. */
|
||||
async repairProjectionsIfDirty() {
|
||||
if (!existsSync(this.projectionDirtyPath()))
|
||||
return false;
|
||||
try {
|
||||
await this.regenerateProjections();
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
async tryRegenerateProjections() {
|
||||
try {
|
||||
await this.regenerateProjections();
|
||||
return { projectionPending: false };
|
||||
}
|
||||
catch (error) {
|
||||
return { projectionPending: true, projectionError: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
/** Idempotently create the global space and its runtime projections. */
|
||||
async ensureGlobal() {
|
||||
return withFileLock(join(this.globalRoot, 'state', '.init.lock'), async () => {
|
||||
await mkdir(join(this.globalRoot, 'runtime'), { recursive: true });
|
||||
await mkdir(join(this.globalRoot, 'spaces', 'global'), { recursive: true });
|
||||
await mkdir(join(this.globalRoot, 'backups'), { recursive: true });
|
||||
await mkdir(join(this.globalRoot, 'state'), { recursive: true });
|
||||
const meta = await this.globalStore.init('全局记忆');
|
||||
const spaceMarker = join(this.globalRoot, 'spaces', 'global', 'space.json');
|
||||
if (!(await stat(spaceMarker).catch(() => undefined)))
|
||||
await atomicWrite(spaceMarker, JSON.stringify(meta, null, 2) + '\n');
|
||||
const userPath = join(this.globalRoot, 'runtime', 'USER.md');
|
||||
const memoryPath = join(this.globalRoot, 'runtime', 'MEMORY.md');
|
||||
if (!(await stat(userPath).catch(() => undefined)))
|
||||
await atomicWrite(userPath, '# USER\n\n');
|
||||
if (!(await stat(memoryPath).catch(() => undefined)))
|
||||
await atomicWrite(memoryPath, '# MEMORY\n\n');
|
||||
const initPath = join(this.globalRoot, 'state', 'init.json');
|
||||
if (!(await stat(initPath).catch(() => undefined)))
|
||||
await atomicWrite(initPath, JSON.stringify({ version: 1, globalReady: true, createdAt: new Date().toISOString() }, null, 2) + '\n');
|
||||
await this.repairProjectionsIfDirty();
|
||||
return meta;
|
||||
});
|
||||
}
|
||||
/** First use in a project creates its .dsh/brain and a stable project space. */
|
||||
async ensureProject(workspace) {
|
||||
await this.ensureGlobal();
|
||||
const root = this.fixedProjectRoot ?? join(this.projectBaseFor(workspace), '.dsh', 'brain');
|
||||
const base = projectBaseOf(root);
|
||||
const cached = this.workspaces.get(root);
|
||||
if (cached !== undefined)
|
||||
return cached.store;
|
||||
return withFileLock(join(root, '.init.lock'), async () => {
|
||||
const again = this.workspaces.get(root);
|
||||
if (again !== undefined)
|
||||
return again.store;
|
||||
const id = projectIdFor(root);
|
||||
await mkdir(join(root, 'documents'), { recursive: true });
|
||||
await mkdir(join(root, 'state'), { recursive: true });
|
||||
const store = new JsonMemoryStore(join(root, 'memory-space'), 'project', id);
|
||||
await store.init('项目记忆');
|
||||
const documents = new JsonDocumentStore(join(root, 'documents'));
|
||||
await documents.init();
|
||||
await writeGitIgnore(base);
|
||||
const mappingPath = join(this.globalRoot, 'state', 'projects.json');
|
||||
await withFileLock(join(this.globalRoot, 'state', '.projects.lock'), async () => {
|
||||
const mapping = await readJson(mappingPath, {});
|
||||
mapping[id] = { root, updatedAt: new Date().toISOString() };
|
||||
await atomicWrite(mappingPath, JSON.stringify(mapping, null, 2) + '\n');
|
||||
});
|
||||
const state = { root, store, documents };
|
||||
this.workspaces.set(root, state);
|
||||
return store;
|
||||
});
|
||||
}
|
||||
/** Public alias used by callers that initialize explicit local memory. */
|
||||
async initialize(workspace) { return this.ensure(workspace); }
|
||||
async ensure(workspace) {
|
||||
const global = await this.ensureGlobal();
|
||||
const projectStore = await this.ensureProject(workspace);
|
||||
const project = await projectStore.spaceMeta();
|
||||
return { global, project: project ?? { id: projectStore.spaceId, scope: 'project', name: '项目记忆', root: projectStore.root, createdAt: new Date().toISOString(), active: true } };
|
||||
}
|
||||
/** Add one memory and regenerate the compact projections. */
|
||||
async remember(input) {
|
||||
const workspace = this.workspacePath();
|
||||
const scope = input.scope ?? 'project';
|
||||
const store = await this.storeFor(scope, workspace);
|
||||
await this.markProjectionDirty();
|
||||
const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) });
|
||||
if (result.duplicate)
|
||||
return result;
|
||||
return { ...result, ...(await this.tryRegenerateProjections()) };
|
||||
}
|
||||
async add(input) { return this.remember(input); }
|
||||
async read(id, workspace) {
|
||||
const globalRecord = await this.globalStore.read(id);
|
||||
if (globalRecord !== undefined)
|
||||
return globalRecord;
|
||||
return (await this.ensureProject(workspace)).read(id);
|
||||
}
|
||||
async collectHits(query, workspace, projectId) {
|
||||
const projectStore = await this.ensureProject(workspace);
|
||||
const globalHits = await this.globalStore.search(query, 1000);
|
||||
const projectHits = await projectStore.search(query, 1000);
|
||||
const scoped = [...projectHits, ...globalHits].filter(({ record }) => {
|
||||
if (projectId === undefined || projectId === '')
|
||||
return true;
|
||||
if (projectId === 'global')
|
||||
return record.scope === 'global';
|
||||
return record.scope === 'project' && record.projectId === projectId;
|
||||
});
|
||||
const seen = new Set();
|
||||
return scoped.filter(({ record }) => { if (seen.has(record.id))
|
||||
return false; seen.add(record.id); return true; })
|
||||
.sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt));
|
||||
}
|
||||
async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
|
||||
const hits = await this.collectHits(query, workspace, projectId);
|
||||
const limit = Math.max(1, Math.min(100, Math.trunc(k)));
|
||||
return hits.slice(0, limit);
|
||||
}
|
||||
async search(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
|
||||
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record);
|
||||
}
|
||||
async list(options = {}, workspace, projectId) {
|
||||
const projectStore = await this.ensureProject(workspace);
|
||||
const records = [...(await this.globalStore.records()), ...(await projectStore.records())];
|
||||
const scoped = records.filter((record) => {
|
||||
if (projectId === undefined || projectId === '')
|
||||
return true;
|
||||
if (projectId === 'global')
|
||||
return record.scope === 'global';
|
||||
return record.scope === 'project' && record.projectId === projectId;
|
||||
});
|
||||
const seen = new Set();
|
||||
const ordered = scoped.filter((record) => { if (seen.has(record.id))
|
||||
return false; seen.add(record.id); return true; })
|
||||
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id));
|
||||
const offset = Math.max(0, Math.trunc(options.offset ?? 0));
|
||||
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)));
|
||||
return { items: ordered.slice(offset, offset + limit), total: ordered.length };
|
||||
}
|
||||
async forget(id, expectedRevision, workspace) {
|
||||
const globalRecord = await this.globalStore.read(id);
|
||||
await this.markProjectionDirty();
|
||||
if (globalRecord !== undefined) {
|
||||
const removed = await this.globalStore.forget(id, expectedRevision);
|
||||
await this.tryRegenerateProjections();
|
||||
return removed;
|
||||
}
|
||||
const store = await this.ensureProject(workspace);
|
||||
const removed = await store.forget(id, expectedRevision);
|
||||
await this.tryRegenerateProjections();
|
||||
return removed;
|
||||
}
|
||||
async projects(workspace) {
|
||||
const global = await this.globalStore.spaceMeta();
|
||||
const root = this.projectRootFor(workspace);
|
||||
const project = await this.projectStoreFor(workspace).spaceMeta();
|
||||
return [...(global === undefined ? [] : [{ id: 'global', name: '全局记忆' }]), { id: project?.id ?? projectIdFor(root), name: '项目记忆' }];
|
||||
}
|
||||
async documents(workspace) {
|
||||
const root = this.projectRootFor(workspace);
|
||||
return new JsonDocumentStore(join(root, 'documents')).list();
|
||||
}
|
||||
async addDocument(input, workspace) {
|
||||
const store = await this.ensureProject(workspace);
|
||||
void store;
|
||||
const root = this.projectRootFor(workspace);
|
||||
const documents = this.workspaces.get(root)?.documents;
|
||||
if (documents === undefined)
|
||||
throw new Error('local_documents_unavailable');
|
||||
return documents.add(input);
|
||||
}
|
||||
async storageStatus(workspace) {
|
||||
const projectRoot = this.projectRootFor(workspace);
|
||||
const global = await this.globalStore.spaceMeta();
|
||||
const project = await this.projectStoreFor(workspace).spaceMeta();
|
||||
return { provider: 'local', globalRoot: this.globalRoot, projectRoot, spaces: { global: global ?? null, project: project ?? null }, cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false };
|
||||
}
|
||||
/** Return the compact per-turn projection used by the system prompt. */
|
||||
projectionText(limit = 2000) {
|
||||
const read = (path) => { try {
|
||||
return readFileSync(path, 'utf8').trim();
|
||||
}
|
||||
catch {
|
||||
return '';
|
||||
} };
|
||||
const user = read(join(this.globalRoot, 'runtime', 'USER.md'));
|
||||
const memory = read(join(this.globalRoot, 'runtime', 'MEMORY.md'));
|
||||
if (user === '' && memory === '')
|
||||
return '';
|
||||
const cut = (text) => text.length > limit ? text.slice(0, limit) + '\n…' : text;
|
||||
return ['## dsh-brain local memory', '### USER.md', cut(user || '(empty)'), '### MEMORY.md', cut(memory || '(empty)')].join('\n');
|
||||
}
|
||||
/** Generate USER.md/MEMORY.md from explicit profile/rule records only. */
|
||||
async regenerateProjections() {
|
||||
const marker = await this.markProjectionDirty();
|
||||
await withFileLock(join(this.globalRoot, 'state', '.projection.lock'), async () => {
|
||||
try {
|
||||
const runtimeFile = join(this.globalRoot, 'runtime', 'memories.json');
|
||||
const mirrorFile = join(this.globalRoot, 'spaces', 'global', 'memories.json');
|
||||
const data = await readFile(runtimeFile, 'utf8').catch((error) => { if (error.code === 'ENOENT')
|
||||
return undefined; throw error; });
|
||||
if (data !== undefined)
|
||||
await atomicWrite(mirrorFile, data);
|
||||
const records = await this.globalStore.records();
|
||||
const user = records.filter((record) => record.category === 'preference' || record.category === 'identity');
|
||||
const rules = records.filter((record) => record.category === 'rule');
|
||||
const render = (title, items) => '# ' + title + '\n\n' + items.map((record) => '- ' + record.content.replace(/\n/g, ' ') + ' *(rev ' + String(record.revision) + ', ' + record.source + ')*').join('\n') + (items.length === 0 ? '' : '\n');
|
||||
await atomicWrite(join(this.globalRoot, 'runtime', 'USER.md'), render('USER', user));
|
||||
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules));
|
||||
await this.clearProjectionDirty(marker);
|
||||
}
|
||||
catch (error) {
|
||||
await this.markProjectionDirty(error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/** Incremental, privacy-preserving summary: only explicit text is stored. */
|
||||
async summarizeConversation(input, workspace) {
|
||||
if (this.settingsOf().autoSummaryEnabled === false)
|
||||
return { stored: 0, duplicates: 0, skipped: true };
|
||||
await this.ensureProject(workspace);
|
||||
await this.markProjectionDirty();
|
||||
return withFileLock(join(this.globalRoot, 'state', '.sessions.lock'), async () => {
|
||||
const checkpointPath = join(this.globalRoot, 'state', 'sessions.json');
|
||||
const checkpoints = await readJson(checkpointPath, {});
|
||||
const prior = checkpoints[input.sessionId];
|
||||
const processed = new Set(prior?.processed ?? []);
|
||||
const fresh = input.turns.filter((turn) => turn.turnId === undefined || !processed.has(turn.turnId));
|
||||
let stored = 0;
|
||||
let duplicates = 0;
|
||||
for (const turn of fresh) {
|
||||
const user = (turn.user ?? '').trim();
|
||||
if (user === '' || containsSecret(user))
|
||||
continue;
|
||||
for (const sentence of user.split(/[\n。!?!?]/).map((item) => item.trim()).filter((item) => item !== '')) {
|
||||
if (/(这次|本次|今天|暂时|临时|只此一次|一次性)/.test(sentence))
|
||||
continue;
|
||||
if (!/(记住|长期|以后|今后|往后|每次|永远|始终|总是|从来不|我一向|我(?:喜欢|偏好|习惯|希望|要求)|规则|偏好|习惯|from now on|remember|prefer)/i.test(sentence))
|
||||
continue;
|
||||
const category = /(总是|始终|必须|不要|别|规则|要求|always|never|must)/i.test(sentence) ? 'rule' : 'preference';
|
||||
if (category === 'preference' && this.settingsOf().autoProfileEnabled === false)
|
||||
continue;
|
||||
const result = await this.globalStore.add({ content: sentence, category, source: 'session:' + input.sessionId, sessionId: input.sessionId, tags: ['auto-summary'] });
|
||||
if (result.duplicate)
|
||||
duplicates += 1;
|
||||
else
|
||||
stored += 1;
|
||||
}
|
||||
}
|
||||
const nextCount = (prior?.count ?? 0) + fresh.length;
|
||||
const processedNext = new Set(processed);
|
||||
for (const turn of fresh)
|
||||
if (turn.turnId !== undefined)
|
||||
processedNext.add(turn.turnId);
|
||||
let documentId;
|
||||
if (fresh.length > 0) {
|
||||
const documents = this.workspaces.get(this.projectRootFor(workspace))?.documents;
|
||||
if (documents === undefined)
|
||||
throw new Error('local_documents_unavailable');
|
||||
const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] });
|
||||
documentId = document.id;
|
||||
}
|
||||
const lastTurn = prior?.lastTurn;
|
||||
const lastCandidate = fresh.map((turn) => turn.turnId).filter((value) => value !== undefined).at(-1);
|
||||
const lastValue = lastCandidate === undefined ? lastTurn : lastTurn === undefined ? lastCandidate : (Number.isFinite(Number(lastCandidate)) && Number.isFinite(Number(lastTurn)) ? (Number(lastCandidate) >= Number(lastTurn) ? lastCandidate : lastTurn) : lastTurn);
|
||||
checkpoints[input.sessionId] = { ...(lastValue === undefined ? {} : { lastTurn: lastValue }), count: nextCount, processed: [...processedNext].slice(-1000) };
|
||||
await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n');
|
||||
if (stored > 0) {
|
||||
const repair = await this.tryRegenerateProjections();
|
||||
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair };
|
||||
}
|
||||
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false };
|
||||
});
|
||||
}
|
||||
/** Add an explicit profile entry; inferred entries stay in the pending area. */
|
||||
async proposeProfile(content, source = 'user', inferred = false) {
|
||||
if (this.settingsOf().autoProfileEnabled === false)
|
||||
throw new Error('auto_profile_disabled');
|
||||
await this.ensureGlobal();
|
||||
await this.markProjectionDirty();
|
||||
const result = await this.globalStore.add({ content, category: inferred ? 'profile-pending' : 'preference', source, tags: ['profile'] });
|
||||
if (!inferred)
|
||||
await this.tryRegenerateProjections();
|
||||
return result.record;
|
||||
}
|
||||
async confirmProfile(id) { await this.ensureGlobal(); await this.markProjectionDirty(); const record = await this.globalStore.read(id); if (record === undefined)
|
||||
throw new Error('memory_not_found'); await this.globalStore.update(id, { category: 'preference' }); await this.tryRegenerateProjections(); }
|
||||
/** Correct an existing profile entry in place; the revision increments and prior text is not kept as a live entry. */
|
||||
async correctProfile(id, content, expectedRevision) { await this.ensureGlobal(); await this.markProjectionDirty(); const record = await this.globalStore.update(id, { content, category: 'preference' }, expectedRevision); await this.tryRegenerateProjections(); return record; }
|
||||
/** Copy the whole global memory root into backups; no source file is removed. */
|
||||
async createBackup() {
|
||||
await this.ensureGlobal();
|
||||
const path = join(this.globalRoot, 'backups', 'backup-' + new Date().toISOString().replace(/[:.]/g, '-'));
|
||||
await mkdir(path, { recursive: true });
|
||||
for (const entry of await readdir(this.globalRoot, { withFileTypes: true })) {
|
||||
if (entry.name === 'backups')
|
||||
continue;
|
||||
await cp(join(this.globalRoot, entry.name), join(path, entry.name), { recursive: true, force: false });
|
||||
}
|
||||
return { path };
|
||||
}
|
||||
/** Report legacy .mnemon locations without deleting anything. */
|
||||
async legacyMigrationReport(workspace) {
|
||||
const found = [];
|
||||
for (const path of [join(this.projectBaseFor(workspace), '.mnemon'), join(dshHome(), '.mnemon')]) {
|
||||
if (await stat(path).catch(() => undefined) !== undefined)
|
||||
found.push(path);
|
||||
}
|
||||
return { found, targetGlobal: this.globalRoot, targetProject: this.projectRootFor(workspace) };
|
||||
}
|
||||
async findLegacyMemoryFiles(root) {
|
||||
const out = [];
|
||||
const walk = async (dir) => {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
await walk(full);
|
||||
continue;
|
||||
}
|
||||
if (/^(memories|memory)\.json$/i.test(entry.name) || /\.memory\.json$/i.test(entry.name))
|
||||
out.push(full);
|
||||
}
|
||||
};
|
||||
await walk(root);
|
||||
return out;
|
||||
}
|
||||
legacyRecordsFrom(value) {
|
||||
if (Array.isArray(value))
|
||||
return value.filter((item) => item !== null && typeof item === 'object' && !Array.isArray(item));
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
||||
return [];
|
||||
const record = value;
|
||||
for (const key of ['records', 'memories', 'items']) {
|
||||
if (Array.isArray(record[key]))
|
||||
return this.legacyRecordsFrom(record[key]);
|
||||
}
|
||||
return record.content === undefined && record.text === undefined && record.memory === undefined ? [] : [record];
|
||||
}
|
||||
async importLegacyRecords(sourcePath, workspace) {
|
||||
const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(sourcePath);
|
||||
const scope = projectLegacy ? 'project' : 'global';
|
||||
const store = await this.storeFor(scope, workspace);
|
||||
let imported = 0;
|
||||
let duplicates = 0;
|
||||
let skipped = 0;
|
||||
const ids = [];
|
||||
for (const file of await this.findLegacyMemoryFiles(sourcePath)) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(await readFile(file, 'utf8'));
|
||||
}
|
||||
catch {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
for (const item of this.legacyRecordsFrom(parsed)) {
|
||||
const content = typeof item.content === 'string' ? item.content : typeof item.text === 'string' ? item.text : typeof item.memory === 'string' ? item.memory : '';
|
||||
if (content.trim() === '') {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
const category = typeof item.category === 'string' ? item.category : typeof item.sector === 'string' ? item.sector : undefined;
|
||||
const tags = Array.isArray(item.tags) ? item.tags.filter((tag) => typeof tag === 'string') : [];
|
||||
const legacyId = typeof item.id === 'string' ? item.id : '';
|
||||
const operationId = 'legacy-' + localMemoryHash(file + '|' + legacyId + '|' + content);
|
||||
try {
|
||||
const result = await store.add({ content, ...(category === undefined ? {} : { category }), tags, source: 'legacy:' + file, operationId, scope, ...(scope === 'project' ? { projectId: projectIdFor(this.projectRootFor(workspace)) } : {}) });
|
||||
if (result.duplicate)
|
||||
duplicates += 1;
|
||||
else
|
||||
imported += 1;
|
||||
// Content-only duplicates were present before this migration and
|
||||
// must never enter this migration's rollback ownership list.
|
||||
if ((!result.duplicate || result.duplicateKind === 'operation') && !ids.includes(result.record.id))
|
||||
ids.push(result.record.id);
|
||||
}
|
||||
catch {
|
||||
skipped += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { imported, duplicates, skipped, ids, scope, ...(workspace === undefined ? {} : { workspace }) };
|
||||
}
|
||||
/** Copy a legacy directory into backups; never moves or deletes the source. */
|
||||
async migrateLegacy(path, workspace) {
|
||||
return withFileLock(join(this.globalRoot, 'state', '.migrations.lock'), async () => {
|
||||
const target = join(this.globalRoot, 'backups', 'migration-' + Date.now().toString(36) + '-' + randomUUID().slice(0, 8));
|
||||
await mkdir(this.globalRoot, { recursive: true });
|
||||
await cp(path, target, { recursive: true, force: false });
|
||||
await this.markProjectionDirty();
|
||||
const manifestPath = join(this.globalRoot, 'state', 'migrations.json');
|
||||
const manifest = await readJson(manifestPath, []);
|
||||
const resolvedWorkspace = this.workspacePath(workspace);
|
||||
const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(path);
|
||||
const targetScope = projectLegacy ? 'project' : 'global';
|
||||
const entry = { source: path, copiedTo: target, createdAt: new Date().toISOString(), status: 'importing', importedIds: [], targetScope, workspace: resolvedWorkspace };
|
||||
manifest.push(entry);
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
||||
try {
|
||||
const imported = await this.importLegacyRecords(path, workspace);
|
||||
entry.importedIds = imported.ids;
|
||||
entry.status = imported.skipped > 0 ? 'partial' : 'complete';
|
||||
Object.assign(entry, { imported: imported.imported, duplicates: imported.duplicates, skipped: imported.skipped, partial: imported.skipped > 0 });
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
||||
return { copiedTo: target, imported: imported.imported, duplicates: imported.duplicates, skipped: imported.skipped, partial: imported.skipped > 0 };
|
||||
}
|
||||
catch (error) {
|
||||
entry.status = 'error';
|
||||
entry.error = error instanceof Error ? error.message : String(error);
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n').catch(() => { });
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/** Restore a prepared backup first, then remove imported records; retries resume safely. */
|
||||
async rollbackMigration(copiedTo, destination) {
|
||||
return withFileLock(join(this.globalRoot, 'state', '.migrations.lock'), async () => {
|
||||
const manifestPath = join(this.globalRoot, 'state', 'migrations.json');
|
||||
const manifest = await readJson(manifestPath, []);
|
||||
const entry = manifest.find((item) => item.copiedTo === copiedTo);
|
||||
if (entry === undefined)
|
||||
throw new Error('migration_not_found');
|
||||
const backupStat = await stat(copiedTo).catch(() => undefined);
|
||||
if (backupStat === undefined || !backupStat.isDirectory())
|
||||
throw new Error('migration_backup_missing');
|
||||
const completedDestination = entry.rollback?.destination;
|
||||
if (entry.rollback?.status === 'complete' && completedDestination !== undefined) {
|
||||
return { restoredTo: completedDestination, removedImported: 0 };
|
||||
}
|
||||
if (completedDestination !== undefined && destination !== undefined && resolve(completedDestination) !== resolve(destination)) {
|
||||
throw new Error('restore_destination_mismatch');
|
||||
}
|
||||
const restoredTo = completedDestination ?? destination ?? join(this.globalRoot, 'backups', 'restore-' + Date.now().toString(36));
|
||||
const destinationStat = await stat(restoredTo).catch(() => undefined);
|
||||
if (destinationStat !== undefined && !destinationStat.isDirectory())
|
||||
throw new Error('restore_destination_not_directory');
|
||||
entry.rollback = entry.rollback ?? {};
|
||||
entry.rollback.destination = restoredTo;
|
||||
if (entry.rollback.staging === undefined || !(await stat(entry.rollback.staging).catch(() => undefined))?.isDirectory()) {
|
||||
const staging = join(this.globalRoot, 'backups', '.restore-' + Date.now().toString(36) + '-' + randomUUID());
|
||||
await cp(copiedTo, staging, { recursive: true, force: false });
|
||||
entry.rollback.staging = staging;
|
||||
}
|
||||
const rollbackStatus = entry.rollback.status;
|
||||
if (rollbackStatus === 'complete') {
|
||||
if ((await readdir(restoredTo).catch(() => [])).length > 0)
|
||||
throw new Error('restore_destination_not_empty');
|
||||
await cp(copiedTo, restoredTo, { recursive: true, force: false });
|
||||
if (await treeDigest(copiedTo) !== await treeDigest(restoredTo))
|
||||
throw new Error('restore_copy_incomplete');
|
||||
return { restoredTo, removedImported: 0 };
|
||||
}
|
||||
if (rollbackStatus === undefined || rollbackStatus === 'prepared') {
|
||||
entry.rollback.status = 'prepared';
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
||||
}
|
||||
// Land the restore copy before touching the active store. A conflicting
|
||||
// child in the destination therefore fails with the active store intact.
|
||||
if (rollbackStatus !== 'copied' && rollbackStatus !== 'records_removed' && rollbackStatus !== 'complete') {
|
||||
if ((await readdir(restoredTo).catch(() => [])).length > 0)
|
||||
throw new Error('restore_destination_not_empty');
|
||||
await cp(entry.rollback.staging, restoredTo, { recursive: true, force: false });
|
||||
if (await treeDigest(entry.rollback.staging) !== await treeDigest(restoredTo))
|
||||
throw new Error('restore_copy_incomplete');
|
||||
entry.rollback.status = 'copied';
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
||||
}
|
||||
if (rollbackStatus === 'copied') {
|
||||
const copyStat = await stat(restoredTo).catch(() => undefined);
|
||||
if (copyStat === undefined || !copyStat.isDirectory())
|
||||
throw new Error('restore_copy_missing');
|
||||
if (await treeDigest(restoredTo) !== await treeDigest(copiedTo))
|
||||
throw new Error('restore_copy_incomplete');
|
||||
}
|
||||
const store = entry.targetScope === 'project' ? await this.storeFor('project', entry.workspace) : this.globalStore;
|
||||
let removedImported = 0;
|
||||
if (rollbackStatus !== 'records_removed' && rollbackStatus !== 'complete') {
|
||||
for (const id of entry.importedIds ?? []) {
|
||||
try {
|
||||
await store.forget(id);
|
||||
removedImported += 1;
|
||||
}
|
||||
catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message.includes('memory_not_found'))
|
||||
continue;
|
||||
throw new Error('rollback_record_failed: ' + message);
|
||||
}
|
||||
}
|
||||
entry.rollback.status = 'records_removed';
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
||||
}
|
||||
await rm(entry.rollback.staging, { recursive: true, force: true }).catch(() => { });
|
||||
entry.rollback.status = 'complete';
|
||||
entry.status = 'rolled_back';
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
||||
const projection = removedImported > 0 ? await this.tryRegenerateProjections() : { projectionPending: false };
|
||||
return { restoredTo, removedImported, ...projection };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
function hitOf(record) {
|
||||
return { id: record.id, content: record.content, tags: record.tags, project_id: record.projectId ?? null, primary_sector: record.category, revision: record.revision, created_at: Date.parse(record.createdAt), updated_at: Date.parse(record.updatedAt) };
|
||||
}
|
||||
function ok(data) { return { ok: true, status: 200, data }; }
|
||||
export class LocalMemoryRemote {
|
||||
manager;
|
||||
constructor(manager) {
|
||||
this.manager = manager;
|
||||
}
|
||||
run(workspace, job) {
|
||||
return workspace === undefined ? job() : this.manager.withWorkspace(workspace, job);
|
||||
}
|
||||
async search(query, k, project, workspace) {
|
||||
return this.run(workspace, async () => {
|
||||
const records = await this.manager.search(query, k, workspace, project);
|
||||
const matches = records.map(hitOf);
|
||||
return ok({ matches, total: matches.length, search_mode: 'local' });
|
||||
});
|
||||
}
|
||||
async read(id, workspace) {
|
||||
return this.run(workspace, async () => {
|
||||
const record = await this.manager.read(id, workspace);
|
||||
if (record === undefined)
|
||||
return { ok: false, error: { status: 404, code: 'memory_not_found', message: '记忆不存在' } };
|
||||
return ok(hitOf(record));
|
||||
});
|
||||
}
|
||||
async add(input, workspace) {
|
||||
return this.run(workspace, async () => {
|
||||
const result = await this.manager.remember({ content: input.content, tags: input.tags, category: input.sector, source: 'memory_tool', operationId: input.operationId, scope: input.project === 'global' ? 'global' : 'project' });
|
||||
return ok({ id: result.record.id, revision: result.record.revision, state: 'stored', remote_saved: true });
|
||||
});
|
||||
}
|
||||
async list(options = {}, workspace) {
|
||||
return this.run(workspace, async () => {
|
||||
const page = await this.manager.list({ limit: options.limit, offset: options.offset }, workspace, options.project);
|
||||
return ok({ items: page.items.map(hitOf), total: page.total });
|
||||
});
|
||||
}
|
||||
async projects(workspace) {
|
||||
return this.run(workspace, async () => ok({ projects: await this.manager.projects(workspace) }));
|
||||
}
|
||||
async storageStatus(workspace) {
|
||||
return this.run(workspace, async () => ok(await this.manager.storageStatus(workspace)));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,266 @@
|
|||
/** Atomic JSON storage for one local memory space. */
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
const EMPTY_FILE = { version: 1, nextChange: 1, operations: {}, records: [] };
|
||||
function nowIso() { return new Date().toISOString(); }
|
||||
const SECRET_PATTERNS = [
|
||||
/(?:api[ _-]?key|access[ _-]?token|client[ _-]?secret|secret|password|passwd|pwd)\s*(?:是|为|[:=:])\s*["']?[A-Za-z0-9_\-./+=]{6,}/i,
|
||||
/(?:密码|口令|令牌|密钥|恢复码)\s*(?:是|为|[:=:])\s*\S{6,}/,
|
||||
/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
|
||||
/\bBearer\s+[A-Za-z0-9\-._~+/]+=*/i,
|
||||
];
|
||||
/** Secrets never belong in a memory record or an automatic summary. */
|
||||
export function containsSecret(value) { return SECRET_PATTERNS.some((pattern) => pattern.test(value)); }
|
||||
function safeText(value, max = 64000) { return typeof value === 'string' ? value.trim().slice(0, max) : ''; }
|
||||
function tagsOf(value) {
|
||||
if (!Array.isArray(value))
|
||||
return [];
|
||||
const tags = value.filter((item) => typeof item === 'string').map((item) => item.trim()).filter((item) => item !== '');
|
||||
return [...new Set(tags)].slice(0, 20);
|
||||
}
|
||||
async function atomicWrite(path, content) {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const tmp = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp';
|
||||
try {
|
||||
await writeFile(tmp, content, { encoding: 'utf8', mode: 0o600 });
|
||||
await rename(tmp, path);
|
||||
}
|
||||
catch (error) {
|
||||
await rm(tmp, { force: true }).catch(() => { });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export async function withFileLock(lockPath, job) {
|
||||
await mkdir(dirname(lockPath), { recursive: true });
|
||||
const started = Date.now();
|
||||
let handle;
|
||||
while (handle === undefined) {
|
||||
try {
|
||||
handle = await open(lockPath, 'wx', 0o600);
|
||||
}
|
||||
catch (error) {
|
||||
const code = error.code;
|
||||
if (code !== 'EEXIST')
|
||||
throw error;
|
||||
const info = await stat(lockPath).catch(() => undefined);
|
||||
if (info !== undefined && Date.now() - info.mtimeMs > 60000) {
|
||||
await rm(lockPath, { force: true }).catch(() => { });
|
||||
continue;
|
||||
}
|
||||
if (Date.now() - started > 10000)
|
||||
throw new Error('local_memory_lock_timeout');
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await job();
|
||||
}
|
||||
finally {
|
||||
await handle.close().catch(() => { });
|
||||
await rm(lockPath, { force: true }).catch(() => { });
|
||||
}
|
||||
}
|
||||
export class JsonMemoryStore {
|
||||
root;
|
||||
scope;
|
||||
spaceId;
|
||||
dataPath;
|
||||
metaPath;
|
||||
lockPath;
|
||||
constructor(root, scope, spaceId) {
|
||||
this.root = root;
|
||||
this.scope = scope;
|
||||
this.spaceId = spaceId;
|
||||
this.dataPath = join(root, 'memories.json');
|
||||
this.metaPath = join(root, 'space.json');
|
||||
this.lockPath = join(root, '.lock');
|
||||
}
|
||||
async init(name = this.scope === 'global' ? '全局记忆' : '项目记忆') {
|
||||
await mkdir(this.root, { recursive: true });
|
||||
return withFileLock(this.lockPath, async () => {
|
||||
const existing = await this.spaceMeta();
|
||||
if (existing !== undefined)
|
||||
return existing;
|
||||
const meta = { id: this.spaceId, scope: this.scope, name, root: this.root, createdAt: nowIso(), active: true };
|
||||
await atomicWrite(this.metaPath, JSON.stringify(meta, null, 2) + '\n');
|
||||
return meta;
|
||||
});
|
||||
}
|
||||
async setActive(active) {
|
||||
return withFileLock(this.lockPath, async () => {
|
||||
const existing = await this.spaceMeta();
|
||||
if (existing === undefined)
|
||||
throw new Error('local_memory_space_not_found');
|
||||
const next = { ...existing, active };
|
||||
await atomicWrite(this.metaPath, JSON.stringify(next, null, 2) + '\n');
|
||||
return next;
|
||||
});
|
||||
}
|
||||
async spaceMeta() {
|
||||
let text;
|
||||
try {
|
||||
text = await readFile(this.metaPath, 'utf8');
|
||||
}
|
||||
catch (error) {
|
||||
if (error.code === 'ENOENT')
|
||||
return undefined;
|
||||
throw new Error(`local_memory_meta_read_failed: ${this.metaPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
throw new Error(`local_memory_meta_corrupt: ${this.metaPath}`);
|
||||
}
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
||||
throw new Error(`local_memory_meta_corrupt: ${this.metaPath}`);
|
||||
const value = parsed;
|
||||
if (typeof value.id !== 'string' || (value.scope !== 'global' && value.scope !== 'project' && value.scope !== 'department'))
|
||||
throw new Error(`local_memory_meta_incompatible: ${this.metaPath}`);
|
||||
return { id: value.id, scope: value.scope, name: typeof value.name === 'string' ? value.name : value.id, root: typeof value.root === 'string' ? value.root : this.root, createdAt: typeof value.createdAt === 'string' ? value.createdAt : nowIso(), active: value.active !== false };
|
||||
}
|
||||
async readFile() {
|
||||
let text;
|
||||
try {
|
||||
text = await readFile(this.dataPath, 'utf8');
|
||||
}
|
||||
catch (error) {
|
||||
if (error.code === 'ENOENT')
|
||||
return { ...EMPTY_FILE, operations: {}, records: [] };
|
||||
throw new Error(`local_memory_read_failed: ${this.dataPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
throw new Error(`local_memory_corrupt: ${this.dataPath}`);
|
||||
}
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
||||
throw new Error(`local_memory_corrupt: ${this.dataPath}`);
|
||||
const value = parsed;
|
||||
if (value.version !== undefined && value.version !== 1)
|
||||
throw new Error(`local_memory_incompatible: ${this.dataPath}`);
|
||||
if (value.records !== undefined && !Array.isArray(value.records))
|
||||
throw new Error(`local_memory_incompatible: ${this.dataPath}`);
|
||||
return { version: 1, nextChange: typeof value.nextChange === 'number' && Number.isFinite(value.nextChange) ? value.nextChange : 1, operations: value.operations !== null && typeof value.operations === 'object' && !Array.isArray(value.operations) ? value.operations : {}, records: Array.isArray(value.records) ? value.records.filter((record) => record !== null && typeof record === 'object') : [] };
|
||||
}
|
||||
async writeFile(file) { await atomicWrite(this.dataPath, JSON.stringify(file, null, 2) + '\n'); }
|
||||
activeRecords(file) { return file.records.filter((record) => record.deleted !== true); }
|
||||
async add(input) {
|
||||
const content = safeText(input.content);
|
||||
if (content === '')
|
||||
throw new Error('记忆内容不能为空');
|
||||
if (containsSecret(content))
|
||||
throw new Error('secret_not_allowed');
|
||||
return withFileLock(this.lockPath, async () => {
|
||||
const file = await this.readFile();
|
||||
if (input.operationId !== undefined && input.operationId !== '') {
|
||||
const prior = file.operations[input.operationId];
|
||||
if (prior !== undefined) {
|
||||
const found = file.records.find((record) => record.id === prior);
|
||||
if (found !== undefined && found.deleted !== true)
|
||||
return { record: found, duplicate: true, duplicateKind: 'operation' };
|
||||
}
|
||||
}
|
||||
const duplicate = this.activeRecords(file).find((record) => record.content === content && record.spaceId === this.spaceId);
|
||||
if (duplicate !== undefined)
|
||||
return { record: duplicate, duplicate: true, duplicateKind: 'content' };
|
||||
const timestamp = nowIso();
|
||||
const record = { id: 'lm_' + randomUUID(), scope: this.scope, spaceId: this.spaceId, content, ...(input.category === undefined || input.category === '' ? {} : { category: input.category }), tags: tagsOf(input.tags), source: safeText(input.source, 500) || 'local', ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }), ...(input.projectId === undefined ? {} : { projectId: input.projectId }), ...(input.departmentId === undefined ? {} : { departmentId: input.departmentId }), createdAt: timestamp, updatedAt: timestamp, revision: 1, changeSeq: file.nextChange, ...(input.operationId === undefined ? {} : { operationId: input.operationId }) };
|
||||
file.nextChange += 1;
|
||||
file.records.push(record);
|
||||
if (input.operationId !== undefined && input.operationId !== '')
|
||||
file.operations[input.operationId] = record.id;
|
||||
await this.writeFile(file);
|
||||
return { record, duplicate: false };
|
||||
});
|
||||
}
|
||||
async read(id) { return this.activeRecords(await this.readFile()).find((record) => record.id === id); }
|
||||
async search(query, k = 5) {
|
||||
const file = await this.readFile();
|
||||
const q = query.trim().toLowerCase();
|
||||
const terms = q.split(/\s+/).filter((term) => term !== '');
|
||||
return this.activeRecords(file).map((record) => { const haystack = (record.content + '\n' + (record.tags ?? []).join(' ') + '\n' + (record.category ?? '')).toLowerCase(); const score = terms.length === 0 ? 1 : terms.reduce((sum, term) => sum + (haystack.includes(term) ? 1 : 0), 0); return { record, score }; }).filter((hit) => terms.length === 0 || hit.score > 0).sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)).slice(0, Math.max(1, Math.min(100, Math.trunc(k))));
|
||||
}
|
||||
async list(options = {}) {
|
||||
const file = await this.readFile();
|
||||
const records = this.activeRecords(file).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||||
const offset = Math.max(0, Math.trunc(options.offset ?? 0));
|
||||
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)));
|
||||
return { items: records.slice(offset, offset + limit), total: records.length };
|
||||
}
|
||||
async update(id, patch, expectedRevision) {
|
||||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined)
|
||||
throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict'); if (patch.content !== undefined) {
|
||||
const content = safeText(patch.content);
|
||||
if (content === '')
|
||||
throw new Error('记忆内容不能为空');
|
||||
if (containsSecret(content))
|
||||
throw new Error('secret_not_allowed');
|
||||
record.content = content;
|
||||
} if (patch.tags !== undefined)
|
||||
record.tags = tagsOf(patch.tags); if (patch.category !== undefined)
|
||||
record.category = patch.category; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record; });
|
||||
}
|
||||
async forget(id, expectedRevision) {
|
||||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined)
|
||||
throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict'); record.deleted = true; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record; });
|
||||
}
|
||||
async records() { return this.activeRecords(await this.readFile()); }
|
||||
}
|
||||
export class JsonDocumentStore {
|
||||
root;
|
||||
indexPath;
|
||||
lockPath;
|
||||
constructor(root) { this.root = root; this.indexPath = join(root, 'index.json'); this.lockPath = join(root, '.lock'); }
|
||||
async init() { await mkdir(this.root, { recursive: true }); await mkdir(join(this.root, 'files'), { recursive: true }); }
|
||||
async read() {
|
||||
let text;
|
||||
try {
|
||||
text = await readFile(this.indexPath, 'utf8');
|
||||
}
|
||||
catch (error) {
|
||||
if (error.code === 'ENOENT')
|
||||
return { version: 1, nextRevision: 1, documents: [] };
|
||||
throw new Error(`local_documents_read_failed: ${this.indexPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
throw new Error(`local_documents_corrupt: ${this.indexPath}`);
|
||||
}
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
||||
throw new Error(`local_documents_corrupt: ${this.indexPath}`);
|
||||
const value = parsed;
|
||||
if (value.documents !== undefined && !Array.isArray(value.documents))
|
||||
throw new Error(`local_documents_incompatible: ${this.indexPath}`);
|
||||
return { version: 1, nextRevision: typeof value.nextRevision === 'number' ? value.nextRevision : 1, documents: Array.isArray(value.documents) ? value.documents : [] };
|
||||
}
|
||||
async write(file) { await atomicWrite(this.indexPath, JSON.stringify(file, null, 2) + '\n'); }
|
||||
async add(input) {
|
||||
const title = safeText(input.title, 500);
|
||||
const content = safeText(input.content, 200000);
|
||||
if (title === '' || content === '')
|
||||
throw new Error('文档标题和内容不能为空');
|
||||
if (containsSecret(title) || containsSecret(content))
|
||||
throw new Error('secret_not_allowed');
|
||||
return withFileLock(this.lockPath, async () => { const file = await this.read(); const duplicate = file.documents.find((document) => document.deleted !== true && document.title === title && document.content === content); if (duplicate !== undefined) {
|
||||
const filePath = join(this.root, 'files', duplicate.id + '.md');
|
||||
if ((await readFile(filePath).catch(() => undefined)) === undefined)
|
||||
await atomicWrite(filePath, '# ' + title + '\n\n' + content + '\n');
|
||||
return duplicate;
|
||||
} const timestamp = nowIso(); const document = { id: 'doc_' + randomUUID(), title, content, source: safeText(input.source, 500) || 'local', tags: tagsOf(input.tags), createdAt: timestamp, updatedAt: timestamp, revision: 1 }; file.documents.push(document); await this.write(file); await atomicWrite(join(this.root, 'files', document.id + '.md'), '# ' + title + '\n\n' + content + '\n'); return document; });
|
||||
}
|
||||
async list() { return (await this.read()).documents.filter((document) => document.deleted !== true); }
|
||||
async readDocument(id) { return (await this.read()).documents.find((document) => document.id === id && document.deleted !== true); }
|
||||
async remove(id) { await withFileLock(this.lockPath, async () => { const file = await this.read(); const document = file.documents.find((item) => item.id === id && item.deleted !== true); if (document === undefined)
|
||||
return; document.deleted = true; document.revision += 1; document.updatedAt = nowIso(); await this.write(file); }); }
|
||||
}
|
||||
export function localMemoryHash(value) { return createHash('sha256').update(value).digest('hex'); }
|
||||
|
|
@ -0,0 +1 @@
|
|||
export {};
|
||||
|
|
@ -46,13 +46,17 @@ export function renderJson(_args, value) {
|
|||
/** Assert the memory scope is usable, or throw a message the model can act on. */
|
||||
export function requireMemoryToken(deps) {
|
||||
if (!deps.settings().enabled) {
|
||||
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。');
|
||||
throw new Error('记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。');
|
||||
}
|
||||
// Local-first mode needs no credential and wins unless cloud mode was
|
||||
// explicitly selected and configured. If local memory is off, only a
|
||||
// configured cloud credential may select the cloud adapter.
|
||||
if (deps.localMemory?.() === true)
|
||||
return '';
|
||||
const token = deps.memoryToken();
|
||||
if (token === '') {
|
||||
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。');
|
||||
}
|
||||
return token;
|
||||
if (token !== '')
|
||||
return token;
|
||||
throw new Error('记忆功能未启用或未配置令牌。请在 /dsh-brain 页面开启本地记忆,或填入 mem_… / cmt_… 记忆令牌。');
|
||||
}
|
||||
/** Search stored memories by keyword. */
|
||||
function searchTool(deps) {
|
||||
|
|
@ -84,7 +88,8 @@ function searchTool(deps) {
|
|||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
const query = typeof args.query === 'string' ? args.query.trim() : '';
|
||||
if (query === '')
|
||||
|
|
@ -92,7 +97,7 @@ function searchTool(deps) {
|
|||
const requested = typeof args.k === 'number' && Number.isFinite(args.k) ? Math.trunc(args.k) : deps.settings().defaultK;
|
||||
const k = Math.min(1000, Math.max(1, requested));
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const result = await deps.remote().search(query, k, project);
|
||||
const result = await deps.remote().search(query, k, project, workspace);
|
||||
if (!result.ok)
|
||||
throw new Error(`检索失败:${describeError(result.error)}`);
|
||||
const matches = result.data.matches ?? [];
|
||||
|
|
@ -122,12 +127,13 @@ function readTool(deps) {
|
|||
schema: { type: 'object', properties: { id: { type: 'string' }, content: { type: 'string' } }, required: ['id'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
const id = typeof args.id === 'string' ? args.id.trim() : '';
|
||||
if (id === '')
|
||||
throw new Error('id 不能为空。');
|
||||
const result = await deps.remote().read(id);
|
||||
const result = await deps.remote().read(id, workspace);
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 404)
|
||||
throw new Error(`没有找到 id=${id} 的记忆(可能已删除)。`);
|
||||
|
|
@ -170,7 +176,8 @@ function addTool(deps) {
|
|||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
const content = typeof args.content === 'string' ? args.content : '';
|
||||
if (content.trim() === '')
|
||||
|
|
@ -184,7 +191,7 @@ function addTool(deps) {
|
|||
const sector = typeof args.sector === 'string' && SECTORS.includes(args.sector) ? args.sector : undefined;
|
||||
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : '';
|
||||
const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID();
|
||||
const result = await deps.remote().add({ content, tags, project, sector, operationId });
|
||||
const result = await deps.remote().add({ content, tags, project, sector, operationId }, workspace);
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。');
|
||||
|
|
@ -219,14 +226,15 @@ function listTool(deps) {
|
|||
schema: { type: 'object', properties: { total: { type: 'number' }, items: { type: 'array', items: { type: 'object' } } }, required: ['items'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
const rawLimit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : 20;
|
||||
const limit = Math.min(100, Math.max(1, rawLimit));
|
||||
const rawOffset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0;
|
||||
const offset = Math.max(0, rawOffset);
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const result = await deps.remote().list({ limit, offset, project });
|
||||
const result = await deps.remote().list({ limit, offset, project }, workspace);
|
||||
if (!result.ok)
|
||||
throw new Error(`列表读取失败:${describeError(result.error)}`);
|
||||
const items = result.data.items ?? [];
|
||||
|
|
@ -244,9 +252,10 @@ function projectsTool(deps) {
|
|||
schema: { type: 'object', properties: { projects: { type: 'array', items: { type: 'object' } } }, required: ['projects'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute() {
|
||||
async execute(_args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
const result = await deps.remote().projects();
|
||||
const result = await deps.remote().projects(workspace);
|
||||
if (!result.ok)
|
||||
throw new Error(`项目列表读取失败:${describeError(result.error)}`);
|
||||
return { projects: result.data.projects ?? [] };
|
||||
|
|
|
|||
|
|
@ -51,6 +51,41 @@ export function insightFromHit(hit) {
|
|||
insight.score = score;
|
||||
return insight;
|
||||
}
|
||||
/**
|
||||
* Classify a LongMemory write receipt without trusting it.
|
||||
*
|
||||
* The service may stage a write (remote_saved:false / state:'pending'), may
|
||||
* answer with a bare 200 and no usable body, or may return fields of the
|
||||
* wrong type. An explicit `state` wins over every other hint; a receipt that
|
||||
* says the write is staged can never be promoted to `stored` by an id or a
|
||||
* revision. Unknown state values and malformed fields degrade to `unknown`
|
||||
* instead of throwing or guessing.
|
||||
*/
|
||||
export function classifyWriteReceipt(receipt) {
|
||||
if (receipt === null || typeof receipt !== 'object' || Array.isArray(receipt))
|
||||
return 'unknown';
|
||||
const body = receipt;
|
||||
const state = typeof body.state === 'string' ? body.state.trim().toLowerCase() : '';
|
||||
if (state !== '') {
|
||||
if (state === 'pending' || state === 'queued')
|
||||
return 'pending';
|
||||
if (state === 'stored' || state === 'saved' || state === 'completed') {
|
||||
// The explicit state says saved, but a contradictory remote_saved:false
|
||||
// still means the write is only staged — never report it as stored.
|
||||
return body.remote_saved === false ? 'pending' : 'stored';
|
||||
}
|
||||
return 'unknown';
|
||||
}
|
||||
if (typeof body.remote_saved === 'boolean')
|
||||
return body.remote_saved ? 'stored' : 'pending';
|
||||
// Older servers answer with just the created id (and sometimes revision);
|
||||
// that is the only remaining signal that the write reached the store.
|
||||
if (typeof body.id === 'string' && body.id !== '')
|
||||
return 'stored';
|
||||
if (typeof body.revision === 'number' && Number.isFinite(body.revision))
|
||||
return 'stored';
|
||||
return 'unknown';
|
||||
}
|
||||
export class LongMemoryProvider {
|
||||
authority;
|
||||
options;
|
||||
|
|
@ -184,12 +219,29 @@ export class LongMemoryProvider {
|
|||
if (!result.ok) {
|
||||
throw new Error(`LongMemory remember failed: ${result.error.message}`);
|
||||
}
|
||||
// The write receipt decides what to report — the service may stage the
|
||||
// write (remote_saved:false) or answer with a bare 200 and no usable
|
||||
// body, and claiming `stored` then would be a lie the UI repeats.
|
||||
const receipt = result.data;
|
||||
const action = classifyWriteReceipt(receipt);
|
||||
const record = receipt !== null && typeof receipt === 'object' && !Array.isArray(receipt)
|
||||
? receipt
|
||||
: {};
|
||||
const id = typeof record.id === 'string' && record.id !== '' ? record.id : undefined;
|
||||
const revision = typeof record.revision === 'number' && Number.isFinite(record.revision)
|
||||
? record.revision
|
||||
: undefined;
|
||||
const summary = action === 'stored'
|
||||
? 'Stored in LongMemory (live).'
|
||||
: action === 'pending'
|
||||
? 'Queued by LongMemory; not yet confirmed as saved.'
|
||||
: 'LongMemory accepted the write but the receipt does not confirm storage; state unknown.';
|
||||
return {
|
||||
action: 'stored',
|
||||
action,
|
||||
provider: this.id,
|
||||
summary: 'Stored in LongMemory (live).',
|
||||
...(result.data.id === undefined ? {} : { id: result.data.id }),
|
||||
...(result.data.revision === undefined ? {} : { revision: result.data.revision }),
|
||||
summary,
|
||||
...(id === undefined ? {} : { id }),
|
||||
...(revision === undefined ? {} : { revision }),
|
||||
};
|
||||
}
|
||||
/** Exact read of one memory by id. */
|
||||
|
|
@ -199,6 +251,16 @@ export class LongMemoryProvider {
|
|||
const result = await this.client(resolved).read(id);
|
||||
if (!result.ok)
|
||||
return undefined;
|
||||
// The read is exact-id, so the service may return a memory from ANY
|
||||
// project the account can see. A space explicitly bound to one project
|
||||
// must not leak hits from another, while the account-wide default space
|
||||
// (no projectId) intentionally reads every project the token can access.
|
||||
const spaceProject = resolved.projectId;
|
||||
if (spaceProject !== undefined) {
|
||||
const hitProject = result.data.project_id;
|
||||
if (typeof hitProject !== 'string' || hitProject !== spaceProject)
|
||||
return undefined;
|
||||
}
|
||||
return insightFromHit(result.data);
|
||||
}
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -0,0 +1,75 @@
|
|||
export const NATIVE_PROVIDER_ID = 'mnemon-native';
|
||||
export const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
export const DEFAULT_RECALL_LIMIT = 10;
|
||||
export const DEFAULT_RECALL_QUALITY_POLICY = 'strict-v1';
|
||||
export function isNativeProvider(provider) {
|
||||
return (provider.typeId ?? provider.id) === NATIVE_PROVIDER_ID;
|
||||
}
|
||||
export const MEMORY_PLACEMENT_CAPABILITIES = ['graph', 'entities', 'related', 'exact-write', 'link', 'forget'];
|
||||
export const CATEGORIES = ['preference', 'decision', 'fact', 'insight', 'context', 'general'];
|
||||
export const SOURCES = ['user', 'agent', 'external'];
|
||||
export const EDGE_TYPES = ['temporal', 'semantic', 'causal', 'entity'];
|
||||
export const INTENTS = ['WHY', 'WHEN', 'ENTITY', 'GENERAL'];
|
||||
export function normalizeEntityKey(entity) {
|
||||
return entity.normalize('NFKC').trim().toLocaleLowerCase();
|
||||
}
|
||||
export const DEFAULT_EMBEDDING_ENDPOINT = 'http://localhost:11434';
|
||||
export const DEFAULT_EMBEDDING_MODEL = 'nomic-embed-text';
|
||||
export const EMBEDDING_PROTOCOL_AUTO = 'auto';
|
||||
export const EMBEDDING_PROTOCOL_OLLAMA = 'ollama';
|
||||
export const EMBEDDING_PROTOCOL_OPENAI = 'openai';
|
||||
export const DEFAULT_EMBEDDING_PROTOCOL = EMBEDDING_PROTOCOL_AUTO;
|
||||
export const MNEMON_EMBEDDING_PROTOCOLS = [EMBEDDING_PROTOCOL_AUTO, EMBEDDING_PROTOCOL_OLLAMA, EMBEDDING_PROTOCOL_OPENAI];
|
||||
export const EMBEDDING_CREDENTIAL_PREFIX = 'dsh-mnemon/embedding-';
|
||||
export const EMBEDDING_CREDENTIAL_REFERENCE = /^dsh-mnemon\/embedding-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
|
||||
export const EMBEDDING_ENVIRONMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u;
|
||||
export const MEMORY_SPACES_DIRECTORY = 'data';
|
||||
export const MEMORY_SPACE_REGISTRY_FILE = '.dsh-memory-bodies.json';
|
||||
export const MEMORY_SPACE_DATABASE_FILE = 'mnemon.db';
|
||||
export const MEMORY_SPACE_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
|
||||
export const MEMORY_SPACE_NAME_MAX_LENGTH = 100;
|
||||
export const MEMORY_SPACE_DESCRIPTION_MAX_LENGTH = 1000;
|
||||
export const MNEMON_ACTIVE_STORE_FILE = 'active';
|
||||
export const MEMORY_PROVIDER_REGISTRY_FILE = 'memory-providers.json';
|
||||
function isObject(value) {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
export function parseMemorySpaceRegistry(value) {
|
||||
const registry = isObject(value) ? value : undefined;
|
||||
if (registry?.version !== 1 || !Array.isArray(registry.bodies))
|
||||
throw new Error('Memory Space registry is invalid');
|
||||
const ids = new Set();
|
||||
const bodies = registry.bodies.map((raw) => {
|
||||
const body = isObject(raw) ? raw : undefined;
|
||||
if (typeof body?.id !== 'string' || !MEMORY_SPACE_ID_PATTERN.test(body.id) || ids.has(body.id))
|
||||
throw new Error('Memory Space registry contains an invalid or duplicate id');
|
||||
if (typeof body.name !== 'string' || body.name.trim() === '' || body.name.length > MEMORY_SPACE_NAME_MAX_LENGTH
|
||||
|| typeof body.description !== 'string' || body.description.length > MEMORY_SPACE_DESCRIPTION_MAX_LENGTH)
|
||||
throw new Error('Memory Space registry contains invalid metadata');
|
||||
if (typeof body.createdAt !== 'string' || typeof body.updatedAt !== 'string')
|
||||
throw new Error('Memory Space registry contains invalid timestamps');
|
||||
ids.add(body.id);
|
||||
return { id: body.id, name: body.name, description: body.description, active: body.active === true, createdAt: body.createdAt, updatedAt: body.updatedAt };
|
||||
});
|
||||
return { version: 1, bodies };
|
||||
}
|
||||
export function summarizeMemorySpaceRegistry(value) {
|
||||
const registry = isObject(value) ? value : undefined;
|
||||
const listed = registry?.bodies;
|
||||
const spaces = Array.isArray(listed) ? listed.filter(isObject) : [];
|
||||
return {
|
||||
valid: registry?.version === 1 && Array.isArray(listed),
|
||||
spaces: spaces.length,
|
||||
active: spaces.filter(space => space.active === true).length,
|
||||
};
|
||||
}
|
||||
export function summarizeMemoryProviderRegistry(value) {
|
||||
const registry = isObject(value) ? value : undefined;
|
||||
const services = registry?.services;
|
||||
const listed = registry?.bodies;
|
||||
return {
|
||||
valid: registry !== undefined,
|
||||
services: isObject(services) ? Object.keys(services).length : 0,
|
||||
connections: Array.isArray(listed) ? listed.length : 0,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export { CATEGORIES, SOURCES, EDGE_TYPES, INTENTS } from "./contracts.js";
|
||||
export * from "./providers/adapter.js";
|
||||
export { MEMORY_SPACE_PROVIDER_API_VERSION, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition } from "./providers/definitions.js";
|
||||
export * from "./providers/http.js";
|
||||
export * from "./providers/process.js";
|
||||
|
|
@ -0,0 +1 @@
|
|||
export const NORMALIZED_RELEVANCE_SCORE = Object.freeze({ kind: 'normalized-relevance' });
|
||||
|
|
@ -0,0 +1,243 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
export const MEMORY_SPACE_PROVIDER_API_VERSION = 'dsh-brain-mnemon.memory-space-provider/v1';
|
||||
const STABLE_ID = /^[a-z][a-z0-9-]{0,127}$/u;
|
||||
const FIELD_KEY = /^[a-z][a-zA-Z0-9_-]{0,127}$/u;
|
||||
export function requiredId(value, label) {
|
||||
const normalized = value.trim();
|
||||
if (!STABLE_ID.test(normalized))
|
||||
throw new Error(`${label} must match [a-z][a-z0-9-]{0,127}`);
|
||||
return normalized;
|
||||
}
|
||||
function requiredText(value, label, max = 500) {
|
||||
const normalized = value.trim();
|
||||
if (normalized === '')
|
||||
throw new Error(`${label} is required`);
|
||||
if (normalized.length > max)
|
||||
throw new Error(`${label} is too long (max ${max} characters)`);
|
||||
return normalized;
|
||||
}
|
||||
function requiredFieldKey(value, label) {
|
||||
const normalized = value.trim();
|
||||
if (!FIELD_KEY.test(normalized))
|
||||
throw new Error(`${label} must start with a letter and contain only letters, digits, _ or -`);
|
||||
return normalized;
|
||||
}
|
||||
function captureIcon(value) {
|
||||
if (value === undefined)
|
||||
return undefined;
|
||||
const icon = structuredClone(value);
|
||||
if (icon.kind === 'brand')
|
||||
icon.value = requiredId(icon.value, 'Memory Space Provider icon brand');
|
||||
else if (icon.kind === 'glyph')
|
||||
icon.value = requiredText(icon.value, 'Memory Space Provider icon glyph', 16);
|
||||
else if (icon.kind === 'data-url') {
|
||||
icon.value = requiredText(icon.value, 'Memory Space Provider icon data URL', 200_000);
|
||||
if (!/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[a-zA-Z0-9+/=]+$/u.test(icon.value)) {
|
||||
throw new Error('Memory Space Provider icon must be a base64 image data URL');
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Error(`unsupported Memory Space Provider icon kind: ${String(icon.kind)}`);
|
||||
}
|
||||
return icon;
|
||||
}
|
||||
function captureCapabilities(value) {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
||||
throw new Error('Memory Space Provider capabilities must be an object');
|
||||
const capabilities = structuredClone(value);
|
||||
for (const key of ['search', 'browse', 'graph', 'entities', 'related', 'remember', 'link', 'forget']) {
|
||||
if (typeof capabilities[key] !== 'boolean')
|
||||
throw new Error(`Memory Space Provider capability ${key} must be boolean`);
|
||||
}
|
||||
if (capabilities.writeMode !== 'exact' && capabilities.writeMode !== 'async-extracting')
|
||||
throw new Error('unsupported Memory Space Provider write mode');
|
||||
if (!['soft', 'hard', 'unsupported'].includes(capabilities.deletionMode))
|
||||
throw new Error('unsupported Memory Space Provider deletion mode');
|
||||
return capabilities;
|
||||
}
|
||||
function captureFields(value) {
|
||||
if (!Array.isArray(value))
|
||||
throw new Error('Memory Space Provider fields must be an array');
|
||||
const fields = structuredClone(value);
|
||||
const fieldKeys = new Set();
|
||||
for (const field of fields) {
|
||||
const key = requiredFieldKey(field.key, 'Memory Space Provider field key');
|
||||
if (fieldKeys.has(key))
|
||||
throw new Error(`duplicate Memory Space Provider field: ${key}`);
|
||||
fieldKeys.add(key);
|
||||
field.key = key;
|
||||
field.label = requiredText(field.label, `Memory Space Provider field ${key} label`, 100);
|
||||
if (field.i18nKey !== undefined)
|
||||
field.i18nKey = requiredText(field.i18nKey, `Memory Space Provider field ${key} i18nKey`, 200);
|
||||
if (field.scope !== 'service' && field.scope !== 'memory')
|
||||
throw new Error(`unsupported Memory Space Provider field scope: ${String(field.scope)}`);
|
||||
if (!['text', 'url', 'secret', 'number', 'boolean', 'select', 'path'].includes(field.input))
|
||||
throw new Error(`unsupported Memory Space Provider field input: ${String(field.input)}`);
|
||||
if (typeof field.required !== 'boolean')
|
||||
throw new Error(`Memory Space Provider field ${key} required must be boolean`);
|
||||
if (field.role !== undefined && field.role !== 'global-location')
|
||||
throw new Error(`unsupported Memory Space Provider field role: ${String(field.role)}`);
|
||||
if (field.role === 'global-location' && (field.scope !== 'service' || field.input !== 'path'))
|
||||
throw new Error(`Memory Space Provider field ${key} global-location must be a service path`);
|
||||
if (field.placeholder !== undefined)
|
||||
field.placeholder = requiredText(field.placeholder, `Memory Space Provider field ${key} placeholder`, 2_000);
|
||||
if (field.help !== undefined)
|
||||
field.help = requiredText(field.help, `Memory Space Provider field ${key} help`, 2_000);
|
||||
if (field.min !== undefined && (!Number.isFinite(field.min) || field.input !== 'number'))
|
||||
throw new Error(`Memory Space Provider field ${key} min requires a finite number field`);
|
||||
if (field.max !== undefined && (!Number.isFinite(field.max) || field.input !== 'number'))
|
||||
throw new Error(`Memory Space Provider field ${key} max requires a finite number field`);
|
||||
if (field.min !== undefined && field.max !== undefined && field.min > field.max)
|
||||
throw new Error(`Memory Space Provider field ${key} min exceeds max`);
|
||||
if (field.maxLength !== undefined && (!['text', 'url', 'secret', 'select', 'path'].includes(field.input)
|
||||
|| !Number.isInteger(field.maxLength) || field.maxLength < 1 || field.maxLength > 8_000))
|
||||
throw new Error(`Memory Space Provider field ${key} maxLength is invalid`);
|
||||
if (field.pattern !== undefined) {
|
||||
if (!['text', 'url', 'secret', 'path'].includes(field.input))
|
||||
throw new Error(`Memory Space Provider field ${key} pattern requires a textual field`);
|
||||
field.pattern = requiredText(field.pattern, `Memory Space Provider field ${key} pattern`, 1_000);
|
||||
try {
|
||||
new RegExp(field.pattern, 'u');
|
||||
}
|
||||
catch {
|
||||
throw new Error(`Memory Space Provider field ${key} pattern is invalid`);
|
||||
}
|
||||
}
|
||||
if (field.validationMessage !== undefined) {
|
||||
if (field.pattern === undefined)
|
||||
throw new Error(`Memory Space Provider field ${key} validationMessage requires a pattern`);
|
||||
field.validationMessage = requiredText(field.validationMessage, `Memory Space Provider field ${key} validationMessage`, 500);
|
||||
}
|
||||
if (field.normalize !== undefined && (field.normalize !== 'trim-trailing-slash' || !['text', 'url', 'path'].includes(field.input))) {
|
||||
throw new Error(`unsupported Memory Space Provider field normalization: ${String(field.normalize)}`);
|
||||
}
|
||||
if (field.options !== undefined) {
|
||||
if (field.input !== 'select' || field.options.length === 0)
|
||||
throw new Error(`Memory Space Provider field ${key} options require a non-empty select field`);
|
||||
const optionValues = new Set();
|
||||
for (const option of field.options) {
|
||||
option.value = requiredText(option.value, `Memory Space Provider field ${key} option value`, 200);
|
||||
option.label = requiredText(option.label, `Memory Space Provider field ${key} option label`, 200);
|
||||
if (option.i18nKey !== undefined)
|
||||
option.i18nKey = requiredText(option.i18nKey, `Memory Space Provider field ${key} option i18nKey`, 200);
|
||||
if (optionValues.has(option.value))
|
||||
throw new Error(`duplicate Memory Space Provider field ${key} option: ${option.value}`);
|
||||
optionValues.add(option.value);
|
||||
}
|
||||
}
|
||||
else if (field.input === 'select')
|
||||
throw new Error(`Memory Space Provider select field ${key} requires options`);
|
||||
if (field.defaultValue !== undefined) {
|
||||
const valid = field.input === 'boolean'
|
||||
? typeof field.defaultValue === 'boolean'
|
||||
: field.input === 'number'
|
||||
? typeof field.defaultValue === 'number' && Number.isFinite(field.defaultValue)
|
||||
: typeof field.defaultValue === 'string';
|
||||
if (!valid || field.input === 'select' && !field.options?.some(option => option.value === field.defaultValue)) {
|
||||
throw new Error(`Memory Space Provider field ${key} default is invalid`);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const field of fields) {
|
||||
if (field.discoveryDefaultFrom === undefined)
|
||||
continue;
|
||||
field.discoveryDefaultFrom = requiredFieldKey(field.discoveryDefaultFrom, `Memory Space Provider field ${field.key} discoveryDefaultFrom`);
|
||||
const source = fields.find(candidate => candidate.key === field.discoveryDefaultFrom);
|
||||
if (field.scope !== 'service' || source?.scope !== 'memory' || source.input === 'secret') {
|
||||
throw new Error(`Memory Space Provider field ${field.key} discovery default must reference a memory field`);
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
function canonical(value, label, ancestors = new Set(), depth = 0) {
|
||||
if (depth > 64)
|
||||
throw new Error(`${label} exceeds the maximum nesting depth`);
|
||||
if (value === null || typeof value === 'boolean' || typeof value === 'string')
|
||||
return JSON.stringify(value);
|
||||
if (typeof value === 'number') {
|
||||
if (!Number.isFinite(value))
|
||||
throw new Error(`${label} contains a non-finite number`);
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (typeof value !== 'object')
|
||||
throw new Error(`${label} must be JSON-safe`);
|
||||
if (ancestors.has(value))
|
||||
throw new Error(`${label} contains a cycle`);
|
||||
ancestors.add(value);
|
||||
try {
|
||||
if (Array.isArray(value))
|
||||
return `[${value.map(item => canonical(item, label, ancestors, depth + 1)).join(',')}]`;
|
||||
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
|
||||
throw new Error(`${label} contains a non-plain object`);
|
||||
}
|
||||
return `{${Object.entries(value)
|
||||
.filter(([, item]) => item !== undefined)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item, label, ancestors, depth + 1)}`)
|
||||
.join(',')}}`;
|
||||
}
|
||||
finally {
|
||||
ancestors.delete(value);
|
||||
}
|
||||
}
|
||||
export function digest(value, label) {
|
||||
return createHash('sha256').update(canonical(value, label)).digest('hex');
|
||||
}
|
||||
export function deepFreeze(value) {
|
||||
if (typeof value !== 'object' || value === null || Object.isFrozen(value))
|
||||
return value;
|
||||
for (const child of Object.values(value))
|
||||
deepFreeze(child);
|
||||
return Object.freeze(value);
|
||||
}
|
||||
function captureManifest(value) {
|
||||
canonical(value, 'Memory Space Provider manifest');
|
||||
const manifest = structuredClone(value);
|
||||
if (manifest.apiVersion !== MEMORY_SPACE_PROVIDER_API_VERSION)
|
||||
throw new Error(`unsupported Memory Space Provider API: ${String(manifest.apiVersion)}`);
|
||||
if (manifest.kind !== 'provider')
|
||||
throw new Error('Memory Space Provider manifest kind must be provider');
|
||||
manifest.typeId = requiredId(manifest.typeId, 'Memory Space Provider typeId');
|
||||
manifest.packageName = requiredText(manifest.packageName, 'Memory Space Provider packageName');
|
||||
manifest.version = requiredText(manifest.version, 'Memory Space Provider version', 100);
|
||||
manifest.label = requiredText(manifest.label, 'Memory Space Provider label', 100);
|
||||
manifest.icon = captureIcon(manifest.icon);
|
||||
manifest.summary = requiredText(manifest.summary, 'Memory Space Provider summary', 1_000);
|
||||
if (manifest.summaryI18nKey !== undefined)
|
||||
manifest.summaryI18nKey = requiredText(manifest.summaryI18nKey, 'Memory Space Provider summaryI18nKey', 200);
|
||||
if (manifest.locality !== 'local' && manifest.locality !== 'remote')
|
||||
throw new Error('Memory Space Provider locality must be local or remote');
|
||||
if (manifest.origin !== 'native' && manifest.origin !== 'third-party')
|
||||
throw new Error('Memory Space Provider origin must be native or third-party');
|
||||
if (!['automatic', 'optional-override', 'provider-global'].includes(manifest.workspaceBinding)) {
|
||||
throw new Error(`unsupported Memory Space Provider workspace binding: ${String(manifest.workspaceBinding)}`);
|
||||
}
|
||||
if (!['normalized-relevance', 'provider-native', 'none'].includes(manifest.scoreSemantics)) {
|
||||
throw new Error(`unsupported Memory Space Provider score semantics: ${String(manifest.scoreSemantics)}`);
|
||||
}
|
||||
manifest.capabilities = captureCapabilities(manifest.capabilities);
|
||||
manifest.fields = captureFields(manifest.fields);
|
||||
if (!Array.isArray(manifest.secrets))
|
||||
throw new Error('Memory Space Provider secrets must be an array');
|
||||
const secretFields = manifest.fields.filter(field => field.input === 'secret').map(field => field.key).sort();
|
||||
const secrets = [...new Set(manifest.secrets.map(secret => requiredFieldKey(secret, 'Memory Space Provider secret')))].sort();
|
||||
if (canonical(secretFields, 'Memory Space Provider secret fields') !== canonical(secrets, 'Memory Space Provider secrets')) {
|
||||
throw new Error('Memory Space Provider secrets must exactly match secret config fields');
|
||||
}
|
||||
manifest.secrets = secrets;
|
||||
return deepFreeze(manifest);
|
||||
}
|
||||
function captureDefinition(value) {
|
||||
if (typeof value?.create !== 'function')
|
||||
throw new Error('Memory Space Provider definition requires a create factory');
|
||||
return Object.freeze({ manifest: captureManifest(value.manifest), create: value.create });
|
||||
}
|
||||
export function defineMemorySpaceProvider(module) {
|
||||
const id = requiredId(module.id, 'Memory Space Provider module id');
|
||||
if (typeof module.apply !== 'function')
|
||||
throw new Error(`Memory Space Provider module ${id} requires apply()`);
|
||||
return Object.freeze({ ...module, id });
|
||||
}
|
||||
export function defineMemorySpaceProviderDefinition(definition) {
|
||||
return captureDefinition(definition);
|
||||
}
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
export function bearerAuthHeader(apiKey) {
|
||||
if (typeof apiKey !== 'string')
|
||||
return undefined;
|
||||
const token = apiKey.trim().replace(/^Bearer(?:\s+|$)/iu, '').trim();
|
||||
return token === '' ? undefined : `Bearer ${token}`;
|
||||
}
|
||||
export function jsonObject(value) {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
export function jsonString(value) {
|
||||
return typeof value === 'string' ? value : undefined;
|
||||
}
|
||||
export function jsonNumber(value) {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
export function jsonArray(value) {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
export function firstArray(value, ...keys) {
|
||||
if (Array.isArray(value))
|
||||
return value;
|
||||
const root = jsonObject(value);
|
||||
for (const key of keys)
|
||||
if (Array.isArray(root?.[key]))
|
||||
return root[key];
|
||||
const nested = jsonObject(root?.data);
|
||||
for (const key of keys)
|
||||
if (Array.isArray(nested?.[key]))
|
||||
return nested[key];
|
||||
return [];
|
||||
}
|
||||
function errorDetail(payload) {
|
||||
if (typeof payload === 'string')
|
||||
return payload.trim() || undefined;
|
||||
const root = jsonObject(payload);
|
||||
const direct = jsonString(root?.message) ?? jsonString(root?.error) ?? jsonString(root?.detail);
|
||||
if (direct !== undefined)
|
||||
return direct;
|
||||
const error = jsonObject(root?.error);
|
||||
return jsonString(error?.message) ?? jsonString(error?.detail);
|
||||
}
|
||||
export class HttpMemoryProvider {
|
||||
memorySpaces;
|
||||
label;
|
||||
requestFetch;
|
||||
requestTimeoutMs;
|
||||
/** @deprecated Use memorySpaces. */
|
||||
memoryBodies;
|
||||
constructor(memorySpaces, options = {}) {
|
||||
this.memorySpaces = memorySpaces;
|
||||
this.memoryBodies = memorySpaces;
|
||||
this.label = options.label;
|
||||
this.requestFetch = options.fetch ?? globalThis.fetch;
|
||||
this.requestTimeoutMs = options.requestTimeoutMs ?? 15_000;
|
||||
}
|
||||
async graph(body, signal) {
|
||||
const items = await this.list(body, { limit: 200 }, signal);
|
||||
return {
|
||||
nodes: items.map(item => ({ ...item, color: '#6574d9' })),
|
||||
edges: [],
|
||||
generatedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
connection(body) {
|
||||
if ((body.provider.typeId ?? body.provider.id) !== this.id)
|
||||
throw new Error(`${this.id} cannot serve provider ${body.provider.id}`);
|
||||
return this.memorySpaces.providerConnection(body.id, body.provider.id);
|
||||
}
|
||||
async request(body, path, options = {}) {
|
||||
const connection = this.connection(body);
|
||||
return this.requestConnection(connection, path, options);
|
||||
}
|
||||
async requestConnection(connection, path, options = {}) {
|
||||
const endpoint = String(connection.endpoint ?? '').replace(/\/+$/u, '');
|
||||
const label = this.label ?? this.id;
|
||||
if (endpoint === '')
|
||||
throw new Error(`${label} endpoint is not configured`);
|
||||
if (!path.startsWith('/'))
|
||||
throw new Error(`${label} request path must be absolute`);
|
||||
options.signal?.throwIfAborted();
|
||||
const controller = new AbortController();
|
||||
const relay = () => controller.abort(options.signal?.reason);
|
||||
options.signal?.addEventListener('abort', relay, { once: true });
|
||||
const timeoutMs = options.timeoutMs ?? this.requestTimeoutMs;
|
||||
const timer = setTimeout(() => controller.abort(new Error(`${label} request timed out`)), timeoutMs);
|
||||
const headers = new Headers(options.headers);
|
||||
if (options.json !== undefined && !headers.has('Content-Type'))
|
||||
headers.set('Content-Type', 'application/json');
|
||||
try {
|
||||
const response = await this.requestFetch(`${endpoint}${path}`, {
|
||||
method: options.method ?? (options.json === undefined ? 'GET' : 'POST'),
|
||||
headers,
|
||||
...(options.json === undefined ? {} : { body: JSON.stringify(options.json) }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
const raw = await response.text();
|
||||
let payload = {};
|
||||
if (raw !== '') {
|
||||
try {
|
||||
payload = JSON.parse(raw);
|
||||
}
|
||||
catch {
|
||||
payload = raw;
|
||||
}
|
||||
}
|
||||
if (!response.ok) {
|
||||
const detail = errorDetail(payload);
|
||||
throw Object.assign(new Error(`${label} HTTP ${response.status}${detail === undefined ? '' : `: ${detail}`}`), { status: response.status });
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
catch (error) {
|
||||
if (controller.signal.aborted && options.signal?.aborted !== true) {
|
||||
throw new Error(`${label} request timed out after ${timeoutMs}ms`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
finally {
|
||||
clearTimeout(timer);
|
||||
options.signal?.removeEventListener('abort', relay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
import { spawn } from 'node:child_process';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
export class ProcessError extends Error {
|
||||
reason;
|
||||
constructor(message, reason) {
|
||||
super(message);
|
||||
this.reason = reason;
|
||||
this.name = 'ProcessError';
|
||||
}
|
||||
}
|
||||
export const DEFAULT_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
||||
export const runProcess = (command, args, options) => new Promise((resolve, reject) => {
|
||||
const label = options.label ?? 'mnemon';
|
||||
const child = spawn(command, [...args], {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
||||
...(options.env === undefined ? {} : { env: options.env }),
|
||||
});
|
||||
const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
const stdoutDecoder = new StringDecoder('utf8');
|
||||
const stderrDecoder = new StringDecoder('utf8');
|
||||
let outputBytes = 0;
|
||||
let settled = false;
|
||||
let killTimer;
|
||||
const stop = () => {
|
||||
if (child.exitCode !== null || child.signalCode !== null)
|
||||
return;
|
||||
child.kill('SIGTERM');
|
||||
killTimer = setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null)
|
||||
child.kill('SIGKILL');
|
||||
}, 1500);
|
||||
};
|
||||
const finish = (error, result) => {
|
||||
if (settled)
|
||||
return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
if (killTimer !== undefined)
|
||||
clearTimeout(killTimer);
|
||||
options.signal?.removeEventListener('abort', abort);
|
||||
if (error === null)
|
||||
resolve(result);
|
||||
else
|
||||
reject(error);
|
||||
};
|
||||
const abort = () => {
|
||||
stop();
|
||||
finish(new ProcessError(`${label} command aborted: ${String(options.signal?.reason ?? 'cancelled')}`, 'aborted'));
|
||||
};
|
||||
const append = (target, chunk) => {
|
||||
outputBytes += chunk.byteLength;
|
||||
if (outputBytes > maxOutputBytes) {
|
||||
stop();
|
||||
finish(new ProcessError(`${label} output exceeded ${maxOutputBytes} bytes`, 'output-limit'));
|
||||
return;
|
||||
}
|
||||
if (target === 'stdout')
|
||||
stdout += stdoutDecoder.write(chunk);
|
||||
else
|
||||
stderr += stderrDecoder.write(chunk);
|
||||
};
|
||||
child.stdout.on('data', (chunk) => { append('stdout', chunk); });
|
||||
child.stderr.on('data', (chunk) => { append('stderr', chunk); });
|
||||
child.on('error', (error) => {
|
||||
finish(new ProcessError(`failed to launch ${label} (${JSON.stringify(command)}): ${error.message}`, 'launch'));
|
||||
});
|
||||
child.on('close', (exitCode) => {
|
||||
stdout += stdoutDecoder.end();
|
||||
stderr += stderrDecoder.end();
|
||||
finish(null, { stdout, stderr, exitCode });
|
||||
});
|
||||
const timeout = setTimeout(() => {
|
||||
stop();
|
||||
finish(new ProcessError(`${label} did not respond within ${options.timeoutMs}ms`, 'timeout'));
|
||||
}, options.timeoutMs);
|
||||
if (options.signal?.aborted === true)
|
||||
abort();
|
||||
else
|
||||
options.signal?.addEventListener('abort', abort, { once: true });
|
||||
});
|
||||
|
|
@ -12,13 +12,14 @@
|
|||
* Registration is deliberately a user step: until then this file is inert
|
||||
* and the rest of the plugin behaves exactly as before.
|
||||
*/
|
||||
import { MEMORY_SPACE_PROVIDER_API_VERSION, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition, } from 'dsh-mnemon-source-memory-spaces/provider-sdk';
|
||||
import { MEMORY_SPACE_PROVIDER_API_VERSION, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition, } from "./fork/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
import { LongMemoryProvider } from "./driver.js";
|
||||
import { createSidecarMemoryRemoteFactory } from "../cloudsync.js";
|
||||
import { VERSION } from "../version.js";
|
||||
export { LongMemoryProvider, descriptor };
|
||||
/** Keep in sync with the package version (asserted by the verify script). */
|
||||
const PROVIDER_VERSION = '0.9.8';
|
||||
/** Manifest version, sourced from package.json via src/version.ts. */
|
||||
const PROVIDER_VERSION = VERSION;
|
||||
export const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
import { MEMORY_SPACE_PROVIDER_API_VERSION, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition } from "./fork/provider-sdk.js";
|
||||
import { LocalMemoryManager } from "../local-memory/index.js";
|
||||
import { VERSION } from "../version.js";
|
||||
export const descriptor = {
|
||||
id: 'dsh-brain-native',
|
||||
label: 'DSH Brain Native',
|
||||
icon: { kind: 'glyph', value: '🧠' },
|
||||
kind: 'local',
|
||||
workspaceBinding: 'optional-override',
|
||||
summary: 'Local DSH Brain memory spaces: project and global records stored under .dsh/brain.',
|
||||
origin: 'native',
|
||||
capabilities: { search: true, browse: true, graph: false, entities: false, related: false, remember: true, link: false, forget: true, writeMode: 'exact', deletionMode: 'soft' },
|
||||
fields: [],
|
||||
serviceConfigured: true,
|
||||
};
|
||||
function workspaceOf(body) {
|
||||
return body.dbPath !== undefined && body.dbPath !== '' ? body.dbPath : undefined;
|
||||
}
|
||||
function insightOf(record, score) {
|
||||
return { id: record.id, content: record.content, ...(record.category === undefined ? {} : { category: record.category }), tags: record.tags, source: record.source === 'session' ? 'user' : 'external', createdAt: record.createdAt, ...(score === undefined ? {} : { score }) };
|
||||
}
|
||||
export class LocalMnemonProvider {
|
||||
manager;
|
||||
id = descriptor.id;
|
||||
scoreSemantics = { kind: 'provider-native' };
|
||||
constructor(manager) {
|
||||
this.manager = manager;
|
||||
}
|
||||
async status(body) {
|
||||
try {
|
||||
const status = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body)));
|
||||
return { healthy: true, stats: { totalInsights: Number(status.spaces?.project ? 0 : 0), deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } };
|
||||
}
|
||||
catch (error) {
|
||||
return { healthy: false, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
async search(body, request) {
|
||||
const records = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.search(request.query, request.limit ?? 10, workspaceOf(body)));
|
||||
return { results: records.map((record) => insightOf(record)) };
|
||||
}
|
||||
async list(body, request) {
|
||||
const page = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.list({ limit: request.limit ?? 50, offset: 0 }, workspaceOf(body)));
|
||||
return page.items.map((record) => insightOf(record));
|
||||
}
|
||||
async remember(body, request) {
|
||||
const result = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.remember({ content: request.content, category: request.category, tags: request.tags, source: 'mnemon-native', scope: 'project' }));
|
||||
return { action: 'stored', id: result.record.id, revision: result.record.revision };
|
||||
}
|
||||
async get(body, id) {
|
||||
const record = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.read(id, workspaceOf(body)));
|
||||
return record === undefined ? undefined : insightOf(record);
|
||||
}
|
||||
async forget(body, id) {
|
||||
const record = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.forget(id, undefined, workspaceOf(body)));
|
||||
return { action: 'deleted', id: record.id, revision: record.revision };
|
||||
}
|
||||
async graph() { return { nodes: [], edges: [], generatedAt: new Date().toISOString() }; }
|
||||
}
|
||||
export const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: 'provider',
|
||||
typeId: descriptor.id,
|
||||
packageName: 'dsh-brain',
|
||||
version: VERSION,
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: [],
|
||||
scoreSemantics: 'provider-native',
|
||||
},
|
||||
create: (context) => new LocalMnemonProvider(context.memorySpaces?.runner ? new LocalMemoryManager({ cwd: () => context.memorySpaces?.runner.effectiveDataDir() ?? process.cwd() }) : new LocalMemoryManager()),
|
||||
});
|
||||
export default defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) { host.install(ctx, definition); },
|
||||
});
|
||||
222
lib/reporter.js
222
lib/reporter.js
|
|
@ -42,7 +42,7 @@ export function statusForReason(reason) {
|
|||
}
|
||||
}
|
||||
/** Extract the numeric turn id from a `turn/start` or `turn/end` payload. */
|
||||
function turnOf(data) {
|
||||
export function turnOf(data) {
|
||||
if (data === undefined)
|
||||
return undefined;
|
||||
const value = data.turn;
|
||||
|
|
@ -116,6 +116,8 @@ export function redactSecrets(text) {
|
|||
*/
|
||||
/** A queued report is retried at most this many times before being dropped. */
|
||||
const MAX_RETRY_ATTEMPTS = 5;
|
||||
/** Conversations kept in the summary buffer; the oldest is evicted beyond this. */
|
||||
const MAX_CONVERSATIONS = 50;
|
||||
export class Reporter {
|
||||
options;
|
||||
startedAt = new Map();
|
||||
|
|
@ -154,7 +156,7 @@ export class Reporter {
|
|||
this.startedAt.delete(oldest.value);
|
||||
}
|
||||
}
|
||||
/** Handle any `session/event`; only `turn/start` and `turn/end` matter here. */
|
||||
/** Handle any `session/event`; message, turn and session lifecycle events matter. */
|
||||
handleEvent(session, event) {
|
||||
if (event === null || typeof event !== 'object')
|
||||
return;
|
||||
|
|
@ -166,16 +168,38 @@ export class Reporter {
|
|||
this.handleStart(session, event);
|
||||
return;
|
||||
}
|
||||
if (event.type === 'session/end' || event.type === 'session/close' || event.type === 'session/closed' || event.type === 'session/terminated') {
|
||||
// A session that ends without a turn/end must not leave transcript text
|
||||
// (or start timestamps) behind for a later session with the same id.
|
||||
this.releaseConversation(conversationIdOf(session));
|
||||
return;
|
||||
}
|
||||
if (event.type !== 'turn/end')
|
||||
return;
|
||||
this.handleEnd(session, event);
|
||||
}
|
||||
/** Drop every buffered turn and open-turn timestamp for one conversation. */
|
||||
releaseConversation(conversationId) {
|
||||
if (conversationId === undefined)
|
||||
return;
|
||||
this.transcripts.delete(conversationId);
|
||||
for (const key of this.startedAt.keys()) {
|
||||
if (key.startsWith(`${conversationId}:`))
|
||||
this.startedAt.delete(key);
|
||||
}
|
||||
}
|
||||
handleEnd(session, event) {
|
||||
const settings = this.options.settings();
|
||||
const conversationId = conversationIdOf(session);
|
||||
const turn = turnOf(event.data);
|
||||
if (conversationId === undefined || turn === undefined)
|
||||
if (conversationId === undefined)
|
||||
return;
|
||||
const turn = turnOf(event.data);
|
||||
if (turn === undefined) {
|
||||
// Without a turn id there is nothing reportable or summarizable; still
|
||||
// release any buffered text so it cannot outlive the conversation.
|
||||
this.releaseConversation(conversationId);
|
||||
return;
|
||||
}
|
||||
const key = `${conversationId}:${turn}`;
|
||||
const completedAt = toEpochMs(event.time) ?? Date.now();
|
||||
const startedAt = this.startedAt.get(key) ?? completedAt;
|
||||
|
|
@ -183,10 +207,18 @@ export class Reporter {
|
|||
const reason = event.data?.reason;
|
||||
const status = statusForReason(reason);
|
||||
if (status === null) {
|
||||
// A forked turn restarts in the child session; its partial text would
|
||||
// double-count there, so release it here instead of letting it leak
|
||||
// into the child's summary.
|
||||
this.releaseTranscript(conversationId, turn);
|
||||
this.push({ turnId: key, conversationId, status: 'cancelled', startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'forked turn is not reported' });
|
||||
this.skipped += 1;
|
||||
return;
|
||||
}
|
||||
// Summary staging and activity reporting are independent features with
|
||||
// independent credentials: every turn releases its buffered text, even
|
||||
// when the activity side is disabled or unconfigured.
|
||||
void this.sendSummary(conversationId, turn, status);
|
||||
if (!settings.enabled) {
|
||||
this.push({ turnId: key, conversationId, status, startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'reporting disabled' });
|
||||
this.skipped += 1;
|
||||
|
|
@ -207,37 +239,78 @@ export class Reporter {
|
|||
completed_at: completedAt,
|
||||
};
|
||||
void this.send(payload);
|
||||
void this.sendSummary(conversationId, key, status);
|
||||
}
|
||||
/** Buffer one redacted message for the turn that is still open. */
|
||||
/**
|
||||
* Buffer one redacted message for the turn that is still open.
|
||||
*
|
||||
* Nothing is buffered unless summaries are fully configured: a disabled or
|
||||
* token-less summary must not keep accumulating transcript text, and a
|
||||
* message with no turn of its own is dropped rather than attached to an
|
||||
* unrelated future turn.
|
||||
*/
|
||||
collect(session, event) {
|
||||
// Summary is part of the activity pipeline: when activity reporting is
|
||||
// switched off, no new transcript text is collected. Buffered text from
|
||||
// before the switch is released in sendSummary instead of being sent.
|
||||
if (!this.options.settings().enabled || !this.options.summary().enabled || this.options.summaryToken() === '')
|
||||
return;
|
||||
const conversationId = conversationIdOf(session);
|
||||
if (conversationId === undefined)
|
||||
return;
|
||||
const turn = turnOf(event.data);
|
||||
if (turn === undefined)
|
||||
return;
|
||||
const raw = textOf(event.data);
|
||||
if (raw === undefined)
|
||||
return;
|
||||
const value = redactSecrets(raw).slice(0, 4000);
|
||||
const buffer = this.transcripts.get(conversationId) ?? [];
|
||||
buffer.push({ role: event.type === 'user/message' ? 'user' : 'assistant', text: value, turn: turnOf(event.data) });
|
||||
if (buffer.length > 120)
|
||||
buffer.splice(0, buffer.length - 120);
|
||||
this.transcripts.set(conversationId, buffer);
|
||||
const scope = this.summaryScope(this.connection());
|
||||
let buffer = this.transcripts.get(conversationId);
|
||||
if (buffer === undefined) {
|
||||
buffer = { scope, messages: [] };
|
||||
this.transcripts.set(conversationId, buffer);
|
||||
if (this.transcripts.size > MAX_CONVERSATIONS) {
|
||||
const oldest = this.transcripts.keys().next();
|
||||
if (oldest.done !== true)
|
||||
this.transcripts.delete(oldest.value);
|
||||
}
|
||||
}
|
||||
else if (buffer.scope !== scope) {
|
||||
// Connection switched mid-conversation: the earlier text belongs to the
|
||||
// old account and must never reach the new one.
|
||||
this.options.log(`dsh-brain: dropping turn-summary buffer after a connection switch: ${conversationId}`);
|
||||
buffer.scope = scope;
|
||||
buffer.messages = [];
|
||||
}
|
||||
buffer.messages.push({ role: event.type === 'user/message' ? 'user' : 'assistant', text: value, turn });
|
||||
if (buffer.messages.length > 120)
|
||||
buffer.messages.splice(0, buffer.messages.length - 120);
|
||||
}
|
||||
/** Take this turn's messages out of the buffer, capped by the char budget. */
|
||||
takeTranscript(conversationId, turnKey) {
|
||||
const buffer = this.transcripts.get(conversationId) ?? [];
|
||||
const turn = Number(turnKey.slice(turnKey.lastIndexOf(':') + 1));
|
||||
/**
|
||||
* Split the conversation buffer into this turn's messages and the rest.
|
||||
*
|
||||
* Only messages tagged with exactly this turn belong to it; anything else
|
||||
* (a stray turn-less message) is dropped, not reattached to a future turn.
|
||||
*/
|
||||
partitionTranscript(conversationId, turn) {
|
||||
const buffer = this.transcripts.get(conversationId);
|
||||
if (buffer === undefined)
|
||||
return { picked: [], rest: [] };
|
||||
const picked = [];
|
||||
const rest = [];
|
||||
for (const item of buffer) {
|
||||
const matches = Number.isFinite(turn) && (item.turn === undefined || item.turn === turn);
|
||||
for (const item of buffer.messages) {
|
||||
const matches = item.turn !== undefined && item.turn === turn;
|
||||
if (matches)
|
||||
picked.push({ role: item.role, text: item.text });
|
||||
else
|
||||
else if (item.turn !== undefined && item.turn !== turn)
|
||||
rest.push(item);
|
||||
}
|
||||
this.transcripts.set(conversationId, rest);
|
||||
buffer.messages = rest;
|
||||
return { picked, rest };
|
||||
}
|
||||
/** Take this turn's messages out of the buffer, capped by the char budget. */
|
||||
takeTranscript(conversationId, turn) {
|
||||
const { picked } = this.partitionTranscript(conversationId, turn);
|
||||
const maxChars = Math.max(1000, this.options.summary().maxChars);
|
||||
let total = 0;
|
||||
const kept = [];
|
||||
|
|
@ -249,24 +322,56 @@ export class Reporter {
|
|||
}
|
||||
return kept;
|
||||
}
|
||||
/** Stage one summary; failures only surface in the status card. */
|
||||
async sendSummary(conversationId, turnKey, status) {
|
||||
/** Drop this turn's messages without sending them (fork, cancel, disable). */
|
||||
releaseTranscript(conversationId, turn) {
|
||||
this.partitionTranscript(conversationId, turn);
|
||||
}
|
||||
/**
|
||||
* Stage one summary; failures only surface in the status card.
|
||||
*
|
||||
* Every end path consumes the turn's buffered text: sent, failed, cancelled
|
||||
* and disabled all release the buffer, so a turn never leaves text behind
|
||||
* for an unrelated later turn. Text collected under a different connection
|
||||
* scope is dropped here instead of being handed to the current account.
|
||||
*/
|
||||
async sendSummary(conversationId, turn, status) {
|
||||
const context = this.connection();
|
||||
const scope = this.summaryScope(context);
|
||||
const buffer = this.transcripts.get(conversationId);
|
||||
let messages = [];
|
||||
if (buffer === undefined) {
|
||||
// Nothing was buffered (summaries may have been off during the turn).
|
||||
}
|
||||
else if (buffer.scope === scope) {
|
||||
messages = this.takeTranscript(conversationId, turn);
|
||||
}
|
||||
else {
|
||||
// The buffered text belongs to a different account or service: never
|
||||
// hand it to the current one — release everything.
|
||||
this.options.log(`dsh-brain: dropping turn-summary buffer for a switched account: ${conversationId}`);
|
||||
this.transcripts.delete(conversationId);
|
||||
}
|
||||
const activity = this.options.settings();
|
||||
if (!activity.enabled) {
|
||||
// The activity switch also gates summaries: a turn ending while
|
||||
// reporting is off must release its text, not stage it.
|
||||
this.releaseTranscript(conversationId, turn);
|
||||
return;
|
||||
}
|
||||
const summary = this.options.summary();
|
||||
const token = this.options.summaryToken();
|
||||
if (!summary.enabled || token === '' || status !== 'completed')
|
||||
const token = context.summaryToken;
|
||||
if (!summary.enabled || token === '' || status !== 'completed' || messages.length === 0)
|
||||
return;
|
||||
const messages = this.takeTranscript(conversationId, turnKey);
|
||||
if (messages.length === 0)
|
||||
return;
|
||||
const payload = { conversation_id: conversationId, turn_id: turnKey, messages };
|
||||
const payload = { conversation_id: conversationId, turn_id: `${conversationId}:${turn}`, messages };
|
||||
this.summaryAttempted += 1;
|
||||
const result = await this.options.client.submitSummary(payload, token);
|
||||
const client = this.clientFor(context);
|
||||
const result = await client.submitSummary(payload, token);
|
||||
if (result.ok) {
|
||||
this.summaryStaged += typeof result.data.staged === 'number' ? result.data.staged : 0;
|
||||
return;
|
||||
}
|
||||
if (result.error.status === 0 || result.error.status >= 500) {
|
||||
const retry = await this.options.client.submitSummary(payload, token);
|
||||
const retry = await client.submitSummary(payload, token);
|
||||
if (retry.ok) {
|
||||
this.summaryStaged += typeof retry.data.staged === 'number' ? retry.data.staged : 0;
|
||||
return;
|
||||
|
|
@ -284,8 +389,10 @@ export class Reporter {
|
|||
/** Send one payload, queueing it when the failure looks transient. */
|
||||
async send(payload) {
|
||||
this.attempted += 1;
|
||||
const token = this.options.activityToken();
|
||||
const result = await this.options.client.reportTurn(payload, token);
|
||||
// Pin the connection BEFORE the first await: the record leaves under the
|
||||
// account it was collected for, even when settings change mid-send.
|
||||
const context = this.connection();
|
||||
const result = await this.clientFor(context).reportTurn(payload, context.activityToken);
|
||||
const now = Date.now();
|
||||
if (result.ok) {
|
||||
const duplicate = result.data.duplicate === true || result.status === 200;
|
||||
|
|
@ -322,25 +429,70 @@ export class Reporter {
|
|||
});
|
||||
// 4xx (other than 429) means the payload or token is wrong: retrying cannot help.
|
||||
if (result.error.status === 0 || result.error.status >= 500) {
|
||||
this.queue.push(payload);
|
||||
this.queue.push({ payload, scope: this.activityScope(context) });
|
||||
if (this.queue.length > 200)
|
||||
this.queue.shift();
|
||||
}
|
||||
this.options.log(`dsh-brain: turn report failed: ${this.lastError}`);
|
||||
}
|
||||
/** Resolve the client bound to the context pinned for this request. */
|
||||
clientFor(context) {
|
||||
if (this.options.clientFor !== undefined)
|
||||
return this.options.clientFor(context);
|
||||
if (this.options.client !== undefined)
|
||||
return this.options.client;
|
||||
throw new Error('Reporter requires clientFor(context)');
|
||||
}
|
||||
/** Snapshot the whole connection at one instant. */
|
||||
connection() {
|
||||
return {
|
||||
baseUrl: this.options.baseUrl === undefined ? '' : this.options.baseUrl(),
|
||||
activityToken: this.options.activityToken(),
|
||||
summaryToken: this.options.summaryToken(),
|
||||
timeoutMs: this.options.timeoutMs === undefined ? 30_000 : this.options.timeoutMs(),
|
||||
};
|
||||
}
|
||||
/** Scope key binding an activity record to one endpoint+account. */
|
||||
activityScope(context) {
|
||||
return `${context.baseUrl}|${context.activityToken}`;
|
||||
}
|
||||
/** Scope key binding summary text to one endpoint+account. */
|
||||
summaryScope(context) {
|
||||
return `${context.baseUrl}|${context.summaryToken}`;
|
||||
}
|
||||
/** Retry queued reports; safe to call at any time. */
|
||||
async flush() {
|
||||
if (this.draining)
|
||||
return { sent: 0, remaining: this.queue.length };
|
||||
// Retrying is a reporting action: when reporting is switched off, the
|
||||
// queue waits instead of pushing data the user turned off.
|
||||
if (!this.options.settings().enabled)
|
||||
return { sent: 0, remaining: this.queue.length };
|
||||
this.draining = true;
|
||||
let sent = 0;
|
||||
try {
|
||||
while (this.queue.length > 0) {
|
||||
const payload = this.queue[0];
|
||||
if (payload === undefined)
|
||||
// Re-check the gates on EVERY entry: a mid-flush disable stops new
|
||||
// requests (records already sent are not recalled), and a mid-flush
|
||||
// account switch drops the remaining old-account entries.
|
||||
if (!this.options.settings().enabled)
|
||||
break;
|
||||
const context = this.connection();
|
||||
const scope = this.activityScope(context);
|
||||
// A queued entry belongs to the account that failed to send it. After a
|
||||
// token or endpoint switch the current credential must not replay old
|
||||
// records to (or as) a different account, so stale entries are dropped.
|
||||
const head = this.queue[0];
|
||||
if (head === undefined)
|
||||
break;
|
||||
if (head.scope !== scope) {
|
||||
this.queue.shift();
|
||||
this.options.log(`dsh-brain: dropping queued turn report for a switched account: ${head.payload.turn_id}`);
|
||||
continue;
|
||||
}
|
||||
const payload = head.payload;
|
||||
this.attempted += 1;
|
||||
const result = await this.options.client.reportTurn(payload, this.options.activityToken());
|
||||
const result = await this.clientFor(context).reportTurn(payload, context.activityToken);
|
||||
if (!result.ok) {
|
||||
this.lastError = describeError(result.error);
|
||||
this.failed += 1;
|
||||
|
|
|
|||
168
lib/routes.js
168
lib/routes.js
|
|
@ -18,6 +18,7 @@ export const ROUTES = {
|
|||
sync: '/dsh-brain/sync',
|
||||
clients: '/dsh-brain/clients',
|
||||
migrate: '/dsh-brain/migrate',
|
||||
localMemory: '/dsh-brain/local-memory',
|
||||
};
|
||||
/** Reported when the MCP sub-plugin entry is not applied; the client keeps the tab hidden. */
|
||||
const MCP_UNAVAILABLE = {
|
||||
|
|
@ -80,6 +81,12 @@ export function buildStatusPayload(deps) {
|
|||
memoryEnabled: view.memoryEnabled,
|
||||
skillsSyncEnabled: view.skillsSyncEnabled,
|
||||
skillsDir: view.skillsDir,
|
||||
localMemoryEnabled: view.localMemoryEnabled,
|
||||
cloudMemoryEnabled: view.cloudMemoryEnabled,
|
||||
autoMemorySpaces: view.autoMemorySpaces,
|
||||
autoSummaryEnabled: view.autoSummaryEnabled,
|
||||
autoProfileEnabled: view.autoProfileEnabled,
|
||||
localMemoryK: view.localMemoryK,
|
||||
};
|
||||
return {
|
||||
ok: true,
|
||||
|
|
@ -145,6 +152,162 @@ async function serveConfig(deps, req, res) {
|
|||
...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }),
|
||||
});
|
||||
}
|
||||
/** Local memory management API: status/search/documents/backup/migration. */
|
||||
async function serveLocalMemory(deps, req, res) {
|
||||
const manager = deps.localMemory;
|
||||
if (manager === undefined) {
|
||||
fail(res, 503, 'local-memory-unavailable');
|
||||
return;
|
||||
}
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
const marker = '/local-memory';
|
||||
const markerAt = url.pathname.indexOf(marker);
|
||||
const suffix = markerAt < 0 ? '' : url.pathname.slice(markerAt + marker.length);
|
||||
if (suffix === '' || suffix === '/' || suffix === '/status') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, ...(await manager.storageStatus()) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/spaces') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, spaces: await manager.projects() });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/documents') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, documents: await manager.documents() });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/memories') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50));
|
||||
const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0);
|
||||
const page = await manager.list({ limit, offset });
|
||||
json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/forget') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
let body;
|
||||
try {
|
||||
body = JSON.parse(await readBody(req));
|
||||
}
|
||||
catch {
|
||||
fail(res, 400, 'invalid-json');
|
||||
return;
|
||||
}
|
||||
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
||||
fail(res, 400, 'invalid-body');
|
||||
return;
|
||||
}
|
||||
const input = body;
|
||||
const id = typeof input.id === 'string' ? input.id.trim() : '';
|
||||
if (id === '') {
|
||||
fail(res, 400, 'id-required');
|
||||
return;
|
||||
}
|
||||
const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined;
|
||||
json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/search') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const query = (url.searchParams.get('q') ?? '').trim();
|
||||
if (query === '') {
|
||||
fail(res, 400, 'query-required');
|
||||
return;
|
||||
}
|
||||
const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10);
|
||||
const k = Number.isFinite(requested) ? Math.max(1, Math.min(100, requested)) : 5;
|
||||
const records = await manager.search(query, k);
|
||||
json(res, 200, { ok: true, query, count: records.length, matches: records.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/backup') {
|
||||
if (req.method !== 'POST' || !sameOrigin(req)) {
|
||||
fail(res, req.method !== 'POST' ? 405 : 403, req.method !== 'POST' ? 'method-not-allowed' : 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, ...(await manager.createBackup()) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/migrate') {
|
||||
if (req.method === 'GET') {
|
||||
const report = await manager.legacyMigrationReport();
|
||||
json(res, 200, { ok: true, ...report });
|
||||
return;
|
||||
}
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
let body;
|
||||
try {
|
||||
body = JSON.parse(await readBody(req));
|
||||
}
|
||||
catch {
|
||||
fail(res, 400, 'invalid-json');
|
||||
return;
|
||||
}
|
||||
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
||||
fail(res, 400, 'invalid-body');
|
||||
return;
|
||||
}
|
||||
const input = body;
|
||||
const action = typeof input.action === 'string' ? input.action : 'report';
|
||||
if (action === 'report') {
|
||||
const report = await manager.legacyMigrationReport();
|
||||
json(res, 200, { ok: true, ...report });
|
||||
return;
|
||||
}
|
||||
if (action === 'migrate') {
|
||||
if (typeof input.path !== 'string' || input.path.trim() === '') {
|
||||
fail(res, 400, 'path-required');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, ...(await manager.migrateLegacy(input.path.trim())) });
|
||||
return;
|
||||
}
|
||||
if (action === 'rollback') {
|
||||
if (typeof input.copiedTo !== 'string' || input.copiedTo.trim() === '') {
|
||||
fail(res, 400, 'copiedTo-required');
|
||||
return;
|
||||
}
|
||||
const destination = typeof input.destination === 'string' && input.destination.trim() !== '' ? input.destination.trim() : undefined;
|
||||
json(res, 200, { ok: true, ...(await manager.rollbackMigration(input.copiedTo.trim(), destination)) });
|
||||
return;
|
||||
}
|
||||
fail(res, 400, 'unknown-action');
|
||||
return;
|
||||
}
|
||||
fail(res, 404, 'unknown-local-memory-route');
|
||||
}
|
||||
/** dsh-brain data migration: GET status, POST run. */
|
||||
async function serveMigrate(_deps, req, res) {
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
|
|
@ -213,6 +376,11 @@ export function createRoutes(deps) {
|
|||
*/
|
||||
export function createCoreRoutes(deps) {
|
||||
return [
|
||||
{
|
||||
kind: 'prefix',
|
||||
path: ROUTES.localMemory,
|
||||
handler: (req, res) => serveLocalMemory(deps, req, res),
|
||||
},
|
||||
{
|
||||
kind: 'exact',
|
||||
path: ROUTES.status,
|
||||
|
|
|
|||
|
|
@ -266,6 +266,11 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
<input id="defaultK" type="number" min="1" max="100" />
|
||||
<div class="hint">memory_search 未显式指定 k 时的返回上限(1–100)。</div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="localMemoryK">本地记忆检索条数</label>
|
||||
<input id="localMemoryK" type="number" min="1" max="100" />
|
||||
<div class="hint">本地优先模式默认返回 5 条,可按项目调整。</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="toggles">
|
||||
<label class="toggle" for="memoryEnabled">
|
||||
|
|
@ -273,6 +278,31 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
<span class="track"></span>
|
||||
<span><span class="ttitle">启用记忆工具</span><span class="tdesc">未显式设置时跟随总开关</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="localMemoryEnabled">
|
||||
<input id="localMemoryEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">本地记忆</span><span class="tdesc">离线可用,不需要账号或令牌</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="cloudMemoryEnabled">
|
||||
<input id="cloudMemoryEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">云端记忆适配器</span><span class="tdesc">需要已配置记忆令牌;默认关闭</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="autoMemorySpaces">
|
||||
<input id="autoMemorySpaces" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">自动创建空间</span><span class="tdesc">全局与当前项目空间幂等创建</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="autoSummaryEnabled">
|
||||
<input id="autoSummaryEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">自动总结</span><span class="tdesc">只保存明确表达的长期信息</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="autoProfileEnabled">
|
||||
<input id="autoProfileEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">自动画像</span><span class="tdesc">只保存明确偏好,推测进入待确认区</span></span>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
|
@ -408,6 +438,12 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
el('clientId').value = settings.clientId || '';
|
||||
el('requestTimeoutMs').value = settings.requestTimeoutMs || '';
|
||||
el('defaultK').value = settings.defaultK || '';
|
||||
el('localMemoryK').value = settings.localMemoryK || '';
|
||||
el('localMemoryEnabled').checked = settings.localMemoryEnabled !== false;
|
||||
el('cloudMemoryEnabled').checked = settings.cloudMemoryEnabled === true;
|
||||
el('autoMemorySpaces').checked = settings.autoMemorySpaces !== false;
|
||||
el('autoSummaryEnabled').checked = settings.autoSummaryEnabled !== false;
|
||||
el('autoProfileEnabled').checked = settings.autoProfileEnabled !== false;
|
||||
el('enabled').checked = settings.enabled === true;
|
||||
el('activityEnabled').checked = settings.activityEnabled === true;
|
||||
el('summaryEnabled').checked = settings.summaryEnabled === true;
|
||||
|
|
@ -489,6 +525,12 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
clientId: el('clientId').value.trim(),
|
||||
requestTimeoutMs: Number(el('requestTimeoutMs').value),
|
||||
defaultK: Number(el('defaultK').value),
|
||||
localMemoryK: Number(el('localMemoryK').value),
|
||||
localMemoryEnabled: el('localMemoryEnabled').checked,
|
||||
cloudMemoryEnabled: el('cloudMemoryEnabled').checked,
|
||||
autoMemorySpaces: el('autoMemorySpaces').checked,
|
||||
autoSummaryEnabled: el('autoSummaryEnabled').checked,
|
||||
autoProfileEnabled: el('autoProfileEnabled').checked,
|
||||
enabled: el('enabled').checked,
|
||||
activityEnabled: el('activityEnabled').checked,
|
||||
summaryEnabled: el('summaryEnabled').checked,
|
||||
|
|
|
|||
|
|
@ -147,7 +147,7 @@ async function walkFiles(dir, cap = MAX_SKILL_FILES + 1) {
|
|||
return out;
|
||||
}
|
||||
/** A folder name we are willing to move around: one path segment, no tricks. */
|
||||
function checkFolder(folder) {
|
||||
export function checkFolder(folder) {
|
||||
if (typeof folder !== 'string' || folder === '' || folder.length > 128 ||
|
||||
folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0')) {
|
||||
fail('invalid_name', `技能目录名无效:${String(folder)}`);
|
||||
|
|
@ -166,9 +166,17 @@ export class SkillAdmin {
|
|||
return this.deps.stagingRoot?.() ?? skillsStagingDir();
|
||||
}
|
||||
guardSync() {
|
||||
if (this.deps.gate().isRunning())
|
||||
const gate = this.deps.gate();
|
||||
const busy = gate.busy === undefined ? gate.isRunning() : gate.busy();
|
||||
if (busy)
|
||||
fail('sync_running', '技能同步正在进行,请稍候再试。');
|
||||
}
|
||||
/** Run one whole admin transaction behind the shared sync/update mutex. */
|
||||
async exclusive(job) {
|
||||
this.guardSync();
|
||||
const gate = this.deps.gate();
|
||||
return gate.runExclusive === undefined ? job() : gate.runExclusive(job);
|
||||
}
|
||||
async describe(folder, dir, enabled, provenance) {
|
||||
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined);
|
||||
if (markdown === undefined)
|
||||
|
|
@ -279,32 +287,33 @@ export class SkillAdmin {
|
|||
}
|
||||
/** Enable (move back into the root) or disable (park) one skill. */
|
||||
async setEnabled(folderInput, enabled) {
|
||||
this.guardSync();
|
||||
const folder = checkFolder(folderInput);
|
||||
const found = await this.locate(folder);
|
||||
if (found === undefined)
|
||||
fail('not_found', `没有找到技能:${folder}`);
|
||||
const targetArea = enabled ? 'root' : 'holding';
|
||||
if (found.area === targetArea)
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput);
|
||||
const found = await this.locate(folder);
|
||||
if (found === undefined)
|
||||
fail('not_found', `没有找到技能:${folder}`);
|
||||
const targetArea = enabled ? 'root' : 'holding';
|
||||
if (found.area === targetArea)
|
||||
return { folder, enabled, note: this.effectNote(enabled) };
|
||||
const targetRoot = enabled ? this.deps.skillsRoot() : this.deps.holdingDir();
|
||||
await mkdir(targetRoot, { recursive: true });
|
||||
const target = join(targetRoot, folder);
|
||||
if (await isDirectory(target))
|
||||
fail('collision', `目标位置已存在同名技能:${folder}`);
|
||||
try {
|
||||
await rename(found.dir, target);
|
||||
}
|
||||
catch (error) {
|
||||
// A cross-device move must not leave the skill half-copied: fall back to a
|
||||
// plain copy only for EXDEV, and only then remove the source.
|
||||
if (error.code !== 'EXDEV')
|
||||
throw error;
|
||||
await cp(found.dir, target, { recursive: true, filter: (source) => !source.split(/[\\/]/).includes('.git') });
|
||||
await rm(found.dir, { recursive: true, force: true });
|
||||
}
|
||||
this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`);
|
||||
return { folder, enabled, note: this.effectNote(enabled) };
|
||||
const targetRoot = enabled ? this.deps.skillsRoot() : this.deps.holdingDir();
|
||||
await mkdir(targetRoot, { recursive: true });
|
||||
const target = join(targetRoot, folder);
|
||||
if (await isDirectory(target))
|
||||
fail('collision', `目标位置已存在同名技能:${folder}`);
|
||||
try {
|
||||
await rename(found.dir, target);
|
||||
}
|
||||
catch (error) {
|
||||
// A cross-device move must not leave the skill half-copied: fall back to a
|
||||
// plain copy only for EXDEV, and only then remove the source.
|
||||
if (error.code !== 'EXDEV')
|
||||
throw error;
|
||||
await cp(found.dir, target, { recursive: true, filter: (source) => !source.split(/[\\/]/).includes('.git') });
|
||||
await rm(found.dir, { recursive: true, force: true });
|
||||
}
|
||||
this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`);
|
||||
return { folder, enabled, note: this.effectNote(enabled) };
|
||||
});
|
||||
}
|
||||
/** The enable/disable mechanism is a directory move, not a live switch. */
|
||||
effectNote(enabled) {
|
||||
|
|
@ -342,16 +351,17 @@ export class SkillAdmin {
|
|||
* itself stays usable by the verification harness and by trusted callers.
|
||||
*/
|
||||
async remove(folderInput) {
|
||||
this.guardSync();
|
||||
const folder = checkFolder(folderInput);
|
||||
const found = await this.locate(folder);
|
||||
if (found === undefined)
|
||||
fail('not_found', `没有找到技能:${folder}`);
|
||||
const files = await walkFiles(found.dir);
|
||||
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
|
||||
await rm(found.dir, { recursive: true, force: true });
|
||||
this.deps.log(`skill deleted: ${folder}`);
|
||||
return { folder, dir: found.dir, files: files.length, bytes };
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput);
|
||||
const found = await this.locate(folder);
|
||||
if (found === undefined)
|
||||
fail('not_found', `没有找到技能:${folder}`);
|
||||
const files = await walkFiles(found.dir);
|
||||
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
|
||||
await rm(found.dir, { recursive: true, force: true });
|
||||
this.deps.log(`skill deleted: ${folder}`);
|
||||
return { folder, dir: found.dir, files: files.length, bytes };
|
||||
});
|
||||
}
|
||||
async readPlans() {
|
||||
try {
|
||||
|
|
@ -392,196 +402,198 @@ export class SkillAdmin {
|
|||
* root here; the caller picks folders and commits.
|
||||
*/
|
||||
async prepareInstall(urlInput, options = {}) {
|
||||
this.guardSync();
|
||||
if (typeof urlInput !== 'string')
|
||||
fail('invalid_url', '请提供仓库地址。');
|
||||
const url = urlInput.trim();
|
||||
if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) {
|
||||
fail('invalid_url', '只接受 https:// 或 file:// 的 git 仓库地址。');
|
||||
}
|
||||
const stagingRoot = this.stagingRoot();
|
||||
await mkdir(stagingRoot, { recursive: true });
|
||||
const planId = `plan_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`;
|
||||
const stagingDir = join(stagingRoot, planId);
|
||||
try {
|
||||
await execFileText('git', ['clone', '--depth', '1', '--no-tags', '--', url, stagingDir]);
|
||||
if (typeof options.ref === 'string' && options.ref !== '') {
|
||||
try {
|
||||
await execFileText('git', ['-C', stagingDir, 'fetch', '--depth', '1', 'origin', options.ref]);
|
||||
await execFileText('git', ['-C', stagingDir, 'checkout', '--detach', 'FETCH_HEAD']);
|
||||
}
|
||||
catch {
|
||||
// The default-branch clone is still usable; the recorded commit below
|
||||
// is whatever was actually checked out, so an install stays auditable.
|
||||
}
|
||||
return this.exclusive(async () => {
|
||||
if (typeof urlInput !== 'string')
|
||||
fail('invalid_url', '请提供仓库地址。');
|
||||
const url = urlInput.trim();
|
||||
if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) {
|
||||
fail('invalid_url', '只接受 https:// 或 file:// 的 git 仓库地址。');
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
const code = error.code;
|
||||
fail('git_failed', code === 'ENOENT'
|
||||
? '本机没有 git 命令,无法从仓库安装技能。'
|
||||
: '仓库克隆失败(地址不可达、需要登录,或不是 git 仓库)。');
|
||||
}
|
||||
let commit = '';
|
||||
try {
|
||||
commit = (await execFileText('git', ['-C', stagingDir, 'rev-parse', 'HEAD'], 20_000)).trim();
|
||||
}
|
||||
catch {
|
||||
commit = '';
|
||||
}
|
||||
const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill';
|
||||
const found = [];
|
||||
const collect = async (dir, depth) => {
|
||||
if (found.length >= MAX_CANDIDATES)
|
||||
return;
|
||||
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined);
|
||||
if (markdown !== undefined) {
|
||||
found.push({ folder: dir === stagingDir ? repoName : basename(dir), dir });
|
||||
return;
|
||||
}
|
||||
if (depth >= 3)
|
||||
return;
|
||||
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (entry.isDirectory() && entry.name !== '.git' && !entry.isSymbolicLink()) {
|
||||
await collect(join(dir, entry.name), depth + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
await collect(stagingDir, 0);
|
||||
if (found.length === 0) {
|
||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。');
|
||||
}
|
||||
const candidates = [];
|
||||
for (const candidate of found) {
|
||||
const markdown = await readFile(join(candidate.dir, 'SKILL.md'), 'utf8').catch(() => '');
|
||||
const frontmatter = parseSkillFrontmatter(markdown);
|
||||
const files = await walkFiles(candidate.dir);
|
||||
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
|
||||
const existing = await this.locate(candidate.folder);
|
||||
let problem;
|
||||
const stagingRoot = this.stagingRoot();
|
||||
await mkdir(stagingRoot, { recursive: true });
|
||||
const planId = `plan_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`;
|
||||
const stagingDir = join(stagingRoot, planId);
|
||||
try {
|
||||
checkFolder(candidate.folder);
|
||||
await execFileText('git', ['clone', '--depth', '1', '--no-tags', '--', url, stagingDir]);
|
||||
if (typeof options.ref === 'string' && options.ref !== '') {
|
||||
try {
|
||||
await execFileText('git', ['-C', stagingDir, 'fetch', '--depth', '1', 'origin', options.ref]);
|
||||
await execFileText('git', ['-C', stagingDir, 'checkout', '--detach', 'FETCH_HEAD']);
|
||||
}
|
||||
catch {
|
||||
// The default-branch clone is still usable; the recorded commit below
|
||||
// is whatever was actually checked out, so an install stays auditable.
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
const code = error.code;
|
||||
fail('git_failed', code === 'ENOENT'
|
||||
? '本机没有 git 命令,无法从仓库安装技能。'
|
||||
: '仓库克隆失败(地址不可达、需要登录,或不是 git 仓库)。');
|
||||
}
|
||||
let commit = '';
|
||||
try {
|
||||
commit = (await execFileText('git', ['-C', stagingDir, 'rev-parse', 'HEAD'], 20_000)).trim();
|
||||
}
|
||||
catch {
|
||||
problem = '目录名不合法,不能作为技能目录';
|
||||
commit = '';
|
||||
}
|
||||
if (problem === undefined && files.length > MAX_SKILL_FILES)
|
||||
problem = `文件过多(>${MAX_SKILL_FILES})`;
|
||||
if (problem === undefined && bytes > MAX_SKILL_BYTES)
|
||||
problem = `体积过大(>${MAX_SKILL_BYTES} 字节)`;
|
||||
const name = frontmatter.name;
|
||||
candidates.push({
|
||||
folder: candidate.folder,
|
||||
name: typeof name === 'string' && name !== '' ? name : candidate.folder,
|
||||
description: String(frontmatter.description ?? '').slice(0, 300),
|
||||
files: files.length,
|
||||
bytes,
|
||||
scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20),
|
||||
conflict: existing !== undefined,
|
||||
...(existing === undefined ? {} : { conflictLocation: existing.area }),
|
||||
...(problem === undefined ? {} : { problem }),
|
||||
rel: relative(stagingDir, candidate.dir),
|
||||
});
|
||||
}
|
||||
const plan = {
|
||||
id: planId,
|
||||
kind: 'install',
|
||||
url,
|
||||
createdAt: Date.now(),
|
||||
expiresAt: Date.now() + PLAN_TTL_MS,
|
||||
stagingDir,
|
||||
candidates,
|
||||
...(commit === '' ? {} : { commit }),
|
||||
...(typeof options.ref === 'string' && options.ref !== '' ? { ref: options.ref } : {}),
|
||||
...(options.source === undefined ? {} : { source: options.source }),
|
||||
};
|
||||
const file = await this.sweepPlans(await this.readPlans());
|
||||
file.plans.push(plan);
|
||||
await this.writePlans(file);
|
||||
this.deps.log(`skill install staged: ${url} -> ${planId} (${candidates.length} candidates)`);
|
||||
return {
|
||||
planId,
|
||||
url,
|
||||
expiresAt: plan.expiresAt,
|
||||
...(commit === '' ? {} : { commit }),
|
||||
candidates: candidates.map((candidate) => ({ ...candidate, id: candidate.folder })),
|
||||
};
|
||||
const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill';
|
||||
const found = [];
|
||||
const collect = async (dir, depth) => {
|
||||
if (found.length >= MAX_CANDIDATES)
|
||||
return;
|
||||
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined);
|
||||
if (markdown !== undefined) {
|
||||
found.push({ folder: dir === stagingDir ? repoName : basename(dir), dir });
|
||||
return;
|
||||
}
|
||||
if (depth >= 3)
|
||||
return;
|
||||
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (entry.isDirectory() && entry.name !== '.git' && !entry.isSymbolicLink()) {
|
||||
await collect(join(dir, entry.name), depth + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
await collect(stagingDir, 0);
|
||||
if (found.length === 0) {
|
||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。');
|
||||
}
|
||||
const candidates = [];
|
||||
for (const candidate of found) {
|
||||
const markdown = await readFile(join(candidate.dir, 'SKILL.md'), 'utf8').catch(() => '');
|
||||
const frontmatter = parseSkillFrontmatter(markdown);
|
||||
const files = await walkFiles(candidate.dir);
|
||||
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
|
||||
const existing = await this.locate(candidate.folder);
|
||||
let problem;
|
||||
try {
|
||||
checkFolder(candidate.folder);
|
||||
}
|
||||
catch {
|
||||
problem = '目录名不合法,不能作为技能目录';
|
||||
}
|
||||
if (problem === undefined && files.length > MAX_SKILL_FILES)
|
||||
problem = `文件过多(>${MAX_SKILL_FILES})`;
|
||||
if (problem === undefined && bytes > MAX_SKILL_BYTES)
|
||||
problem = `体积过大(>${MAX_SKILL_BYTES} 字节)`;
|
||||
const name = frontmatter.name;
|
||||
candidates.push({
|
||||
folder: candidate.folder,
|
||||
name: typeof name === 'string' && name !== '' ? name : candidate.folder,
|
||||
description: String(frontmatter.description ?? '').slice(0, 300),
|
||||
files: files.length,
|
||||
bytes,
|
||||
scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20),
|
||||
conflict: existing !== undefined,
|
||||
...(existing === undefined ? {} : { conflictLocation: existing.area }),
|
||||
...(problem === undefined ? {} : { problem }),
|
||||
rel: relative(stagingDir, candidate.dir),
|
||||
});
|
||||
}
|
||||
const plan = {
|
||||
id: planId,
|
||||
kind: 'install',
|
||||
url,
|
||||
createdAt: Date.now(),
|
||||
expiresAt: Date.now() + PLAN_TTL_MS,
|
||||
stagingDir,
|
||||
candidates,
|
||||
...(commit === '' ? {} : { commit }),
|
||||
...(typeof options.ref === 'string' && options.ref !== '' ? { ref: options.ref } : {}),
|
||||
...(options.source === undefined ? {} : { source: options.source }),
|
||||
};
|
||||
const file = await this.sweepPlans(await this.readPlans());
|
||||
file.plans.push(plan);
|
||||
await this.writePlans(file);
|
||||
this.deps.log(`skill install staged: ${url} -> ${planId} (${candidates.length} candidates)`);
|
||||
return {
|
||||
planId,
|
||||
url,
|
||||
expiresAt: plan.expiresAt,
|
||||
...(commit === '' ? {} : { commit }),
|
||||
candidates: candidates.map((candidate) => ({ ...candidate, id: candidate.folder })),
|
||||
};
|
||||
});
|
||||
}
|
||||
/** Install the folders the user picked from a staged plan. */
|
||||
async commitInstall(planInput) {
|
||||
this.guardSync();
|
||||
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
|
||||
if (planId === '')
|
||||
fail('invalid_plan', '缺少安装计划 id。');
|
||||
const selection = Array.isArray(planInput.folders) ? planInput.folders : [];
|
||||
const file = await this.sweepPlans(await this.readPlans());
|
||||
const plan = file.plans.find((item) => item.id === planId);
|
||||
if (plan === undefined) {
|
||||
return this.exclusive(async () => {
|
||||
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
|
||||
if (planId === '')
|
||||
fail('invalid_plan', '缺少安装计划 id。');
|
||||
const selection = Array.isArray(planInput.folders) ? planInput.folders : [];
|
||||
const file = await this.sweepPlans(await this.readPlans());
|
||||
const plan = file.plans.find((item) => item.id === planId);
|
||||
if (plan === undefined) {
|
||||
await this.writePlans(file);
|
||||
fail('plan_expired', '安装计划已过期或不存在,请重新拉取仓库。');
|
||||
}
|
||||
const wanted = selection.map((value) => checkFolder(value));
|
||||
const installed = [];
|
||||
const skipped = [];
|
||||
const skillsRoot = resolve(this.deps.skillsRoot());
|
||||
await mkdir(skillsRoot, { recursive: true });
|
||||
for (const candidate of plan.candidates) {
|
||||
if (!wanted.includes(candidate.folder))
|
||||
continue;
|
||||
if (candidate.problem !== undefined) {
|
||||
skipped.push({ folder: candidate.folder, reason: candidate.problem });
|
||||
continue;
|
||||
}
|
||||
const existing = await this.locate(candidate.folder);
|
||||
if (existing !== undefined) {
|
||||
skipped.push({ folder: candidate.folder, reason: existing.area === 'holding' ? 'already_exists_disabled' : 'already_exists' });
|
||||
continue;
|
||||
}
|
||||
const stagingRoot = resolve(plan.stagingDir);
|
||||
const source = candidate.rel !== undefined && candidate.rel !== ''
|
||||
? resolve(stagingRoot, candidate.rel)
|
||||
: stagingRoot;
|
||||
const target = resolve(skillsRoot, candidate.folder);
|
||||
// Both sides must stay inside their own root: a crafted plan file cannot
|
||||
// make this write outside the skills directory.
|
||||
if (!source.startsWith(stagingRoot) || !target.startsWith(`${skillsRoot}${sep}`)) {
|
||||
skipped.push({ folder: candidate.folder, reason: 'path_escape' });
|
||||
continue;
|
||||
}
|
||||
await cp(source, target, {
|
||||
recursive: true,
|
||||
// `.git` never travels with a skill, and a link could point outside the
|
||||
// repository: both are dropped rather than copied.
|
||||
filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath),
|
||||
});
|
||||
// Record provenance so the skill can later be diffed, updated and rolled
|
||||
// back without the cloud center. The file holds no credentials.
|
||||
if (plan.commit !== undefined && plan.commit !== '') {
|
||||
const record = {
|
||||
version: 1,
|
||||
provider: plan.source?.provider ?? 'git',
|
||||
repoUrl: plan.url,
|
||||
ref: plan.ref ?? plan.commit,
|
||||
commit: plan.commit,
|
||||
sourcePath: candidate.rel ?? candidate.folder,
|
||||
installedAt: new Date().toISOString(),
|
||||
...(plan.source?.entryId === undefined ? {} : { entryId: plan.source.entryId }),
|
||||
...(plan.source?.version === undefined ? {} : { marketVersion: plan.source.version }),
|
||||
};
|
||||
await writeFile(join(target, '.skill-source.json'), `${JSON.stringify(record, null, 2)}\n`, 'utf8').catch(() => { });
|
||||
}
|
||||
installed.push(candidate.folder);
|
||||
this.deps.log(`skill installed from git: ${candidate.folder}`);
|
||||
}
|
||||
const remaining = plan.candidates
|
||||
.filter((candidate) => !installed.includes(candidate.folder))
|
||||
.map((candidate) => candidate.folder);
|
||||
file.plans = file.plans.filter((item) => item.id !== planId);
|
||||
await this.writePlans(file);
|
||||
fail('plan_expired', '安装计划已过期或不存在,请重新拉取仓库。');
|
||||
}
|
||||
const wanted = selection.map((value) => checkFolder(value));
|
||||
const installed = [];
|
||||
const skipped = [];
|
||||
const skillsRoot = resolve(this.deps.skillsRoot());
|
||||
await mkdir(skillsRoot, { recursive: true });
|
||||
for (const candidate of plan.candidates) {
|
||||
if (!wanted.includes(candidate.folder))
|
||||
continue;
|
||||
if (candidate.problem !== undefined) {
|
||||
skipped.push({ folder: candidate.folder, reason: candidate.problem });
|
||||
continue;
|
||||
}
|
||||
const existing = await this.locate(candidate.folder);
|
||||
if (existing !== undefined) {
|
||||
skipped.push({ folder: candidate.folder, reason: existing.area === 'holding' ? 'already_exists_disabled' : 'already_exists' });
|
||||
continue;
|
||||
}
|
||||
const stagingRoot = resolve(plan.stagingDir);
|
||||
const source = candidate.rel !== undefined && candidate.rel !== ''
|
||||
? resolve(stagingRoot, candidate.rel)
|
||||
: candidate.folder === basename(plan.stagingDir) ? stagingRoot : resolve(stagingRoot, candidate.folder);
|
||||
const target = resolve(skillsRoot, candidate.folder);
|
||||
// Both sides must stay inside their own root: a crafted plan file cannot
|
||||
// make this write outside the skills directory.
|
||||
if (!source.startsWith(stagingRoot) || !target.startsWith(`${skillsRoot}${sep}`)) {
|
||||
skipped.push({ folder: candidate.folder, reason: 'path_escape' });
|
||||
continue;
|
||||
}
|
||||
await cp(source, target, {
|
||||
recursive: true,
|
||||
// `.git` never travels with a skill, and a link could point outside the
|
||||
// repository: both are dropped rather than copied.
|
||||
filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath),
|
||||
});
|
||||
// Record provenance so the skill can later be diffed, updated and rolled
|
||||
// back without the cloud center. The file holds no credentials.
|
||||
if (plan.commit !== undefined && plan.commit !== '') {
|
||||
const record = {
|
||||
version: 1,
|
||||
provider: plan.source?.provider ?? 'git',
|
||||
repoUrl: plan.url,
|
||||
ref: plan.ref ?? plan.commit,
|
||||
commit: plan.commit,
|
||||
sourcePath: candidate.rel ?? candidate.folder,
|
||||
installedAt: new Date().toISOString(),
|
||||
...(plan.source?.entryId === undefined ? {} : { entryId: plan.source.entryId }),
|
||||
...(plan.source?.version === undefined ? {} : { marketVersion: plan.source.version }),
|
||||
};
|
||||
await writeFile(join(target, '.skill-source.json'), `${JSON.stringify(record, null, 2)}\n`, 'utf8').catch(() => { });
|
||||
}
|
||||
installed.push(candidate.folder);
|
||||
this.deps.log(`skill installed from git: ${candidate.folder}`);
|
||||
}
|
||||
const remaining = plan.candidates
|
||||
.filter((candidate) => !installed.includes(candidate.folder))
|
||||
.map((candidate) => candidate.folder);
|
||||
file.plans = file.plans.filter((item) => item.id !== planId);
|
||||
await this.writePlans(file);
|
||||
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
return { installed, skipped, remaining };
|
||||
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
return { installed, skipped, remaining };
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Import one skill folder from another tool's skills directory (the
|
||||
|
|
@ -592,38 +604,41 @@ export class SkillAdmin {
|
|||
* like a git install does.
|
||||
*/
|
||||
async importFolder(fromDir, folderInput) {
|
||||
this.guardSync();
|
||||
const folder = checkFolder(folderInput);
|
||||
const existing = await this.locate(folder);
|
||||
if (existing !== undefined) {
|
||||
fail('already_exists', existing.area === 'holding'
|
||||
? `DSH 里已有一个停用中的同名技能(${folder}),先处理它再导入。`
|
||||
: `DSH 里已有同名技能(${folder}),不重复导入。`);
|
||||
}
|
||||
const skillsRoot = resolve(this.deps.skillsRoot());
|
||||
await mkdir(skillsRoot, { recursive: true });
|
||||
const target = resolve(skillsRoot, folder);
|
||||
if (!target.startsWith(`${skillsRoot}${sep}`))
|
||||
fail('path_escape', '导入目标越出技能目录。');
|
||||
await cp(fromDir, target, {
|
||||
recursive: true,
|
||||
filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath),
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput);
|
||||
const existing = await this.locate(folder);
|
||||
if (existing !== undefined) {
|
||||
fail('already_exists', existing.area === 'holding'
|
||||
? `DSH 里已有一个停用中的同名技能(${folder}),先处理它再导入。`
|
||||
: `DSH 里已有同名技能(${folder}),不重复导入。`);
|
||||
}
|
||||
const skillsRoot = resolve(this.deps.skillsRoot());
|
||||
await mkdir(skillsRoot, { recursive: true });
|
||||
const target = resolve(skillsRoot, folder);
|
||||
if (!target.startsWith(`${skillsRoot}${sep}`))
|
||||
fail('path_escape', '导入目标越出技能目录。');
|
||||
await cp(fromDir, target, {
|
||||
recursive: true,
|
||||
filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath),
|
||||
});
|
||||
this.deps.log(`skill imported from another tool: ${folder}`);
|
||||
return { folder };
|
||||
});
|
||||
this.deps.log(`skill imported from another tool: ${folder}`);
|
||||
return { folder };
|
||||
}
|
||||
/** Throw away a staged plan and its clone. */
|
||||
async cancelInstall(planInput) {
|
||||
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
|
||||
if (planId === '')
|
||||
fail('invalid_plan', '缺少安装计划 id。');
|
||||
const file = await this.sweepPlans(await this.readPlans());
|
||||
const plan = file.plans.find((item) => item.id === planId);
|
||||
file.plans = file.plans.filter((item) => item.id !== planId);
|
||||
await this.writePlans(file);
|
||||
if (plan !== undefined)
|
||||
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
return { cancelled: planId };
|
||||
return this.exclusive(async () => {
|
||||
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
|
||||
if (planId === '')
|
||||
fail('invalid_plan', '缺少安装计划 id。');
|
||||
const file = await this.sweepPlans(await this.readPlans());
|
||||
const plan = file.plans.find((item) => item.id === planId);
|
||||
file.plans = file.plans.filter((item) => item.id !== planId);
|
||||
await this.writePlans(file);
|
||||
if (plan !== undefined)
|
||||
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
return { cancelled: planId };
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Legacy one-shot install, kept for the standalone `/dsh-brain/skills`
|
||||
|
|
@ -649,10 +664,10 @@ export class SkillAdmin {
|
|||
}
|
||||
/** Pending plans, so a reloaded page can resume a staged install. */
|
||||
async listPlans() {
|
||||
const file = await this.sweepPlans(await this.readPlans());
|
||||
await this.writePlans(file);
|
||||
const file = await this.readPlans();
|
||||
const now = Date.now();
|
||||
return {
|
||||
plans: file.plans.map((plan) => ({
|
||||
plans: file.plans.filter((plan) => plan.expiresAt > now).map((plan) => ({
|
||||
planId: plan.id,
|
||||
url: plan.url,
|
||||
expiresAt: plan.expiresAt,
|
||||
|
|
|
|||
|
|
@ -35,8 +35,8 @@
|
|||
* silently trimmed.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { CLOUD_SKILL_NAME, isCloudSkillPath, linkedSkillManifest, MAX_FILE_BYTES, MAX_FILES, MAX_SKILL_BYTES, parseSkillFrontmatter, TEXT_EXT } from "./skills/shared.js";
|
||||
import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
|
||||
import { CLOUD_SKILL_NAME, isCloudSkillPath, linkedSkillManifest, MAX_FILE_BYTES, MAX_FILES, MAX_SKILL_BYTES, parseSkillFrontmatter, sha256Hex, TEXT_EXT } from "./skills/shared.js";
|
||||
import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { describeError } from "./api.js";
|
||||
import { dshHome, migrateLegacyFile } from "./store.js";
|
||||
|
|
@ -73,6 +73,13 @@ export function skillsStatePath() {
|
|||
export class SkillSync {
|
||||
deps;
|
||||
running = false;
|
||||
/** Tail of the serialization queue shared by every skill write transaction. */
|
||||
queueTail = Promise.resolve();
|
||||
/** Jobs accepted into the queue but not settled yet; makes busy() honest. */
|
||||
pendingWrites = 0;
|
||||
stateCache;
|
||||
runRepository;
|
||||
runScopeKey;
|
||||
current = {
|
||||
running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0,
|
||||
};
|
||||
|
|
@ -83,9 +90,27 @@ export class SkillSync {
|
|||
stats() {
|
||||
return this.current;
|
||||
}
|
||||
/** SkillSyncGate: true while a pass is in flight. */
|
||||
/** SkillSyncGate: true while any sync/resolve/admin write transaction is queued or running. */
|
||||
isRunning() {
|
||||
return this.running || this.current.running;
|
||||
return this.busy();
|
||||
}
|
||||
/** SkillSyncGate: richer busy signal covering queued writes too. */
|
||||
busy() {
|
||||
return this.running || this.current.running || this.pendingWrites > 0;
|
||||
}
|
||||
/**
|
||||
* SkillSyncGate: the one shared write lock. Every mutating entry point —
|
||||
* sync passes, resolves, admin moves/installs/deletes, update and rollback
|
||||
* — enters through this queue, so their async bodies never interleave.
|
||||
*/
|
||||
async runExclusive(job) {
|
||||
this.pendingWrites += 1;
|
||||
try {
|
||||
return await this.enqueue(job);
|
||||
}
|
||||
finally {
|
||||
this.pendingWrites -= 1;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* SkillSyncGate: where one skill folder came from. `null` means the
|
||||
|
|
@ -105,14 +130,15 @@ export class SkillSync {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
stateCache;
|
||||
async loadStateCached() {
|
||||
const info = await stat(this.statePath()).catch(() => undefined);
|
||||
const mtimeMs = info?.mtimeMs ?? -1;
|
||||
if (this.stateCache !== undefined && this.stateCache.mtimeMs === mtimeMs)
|
||||
const scopeKey = this.scopeKey(this.scopeIdentity());
|
||||
if (this.stateCache !== undefined && this.stateCache.mtimeMs === mtimeMs && this.stateCache.scopeKey === scopeKey) {
|
||||
return this.stateCache.state;
|
||||
}
|
||||
const state = await this.loadState();
|
||||
this.stateCache = { mtimeMs, state };
|
||||
this.stateCache = { mtimeMs, scopeKey, state };
|
||||
return state;
|
||||
}
|
||||
/** True when a cloud-delivered bundle still matches its receipt. */
|
||||
|
|
@ -134,8 +160,15 @@ export class SkillSync {
|
|||
* makes the DOWN pass skip the name (uploaded) while the UP pass skips its
|
||||
* local folder (delivery manifest), so neither side ever syncs again.
|
||||
*/
|
||||
markDelivered(state, name, manifest) {
|
||||
state.delivered[name] = { manifest };
|
||||
markDelivered(state, name, manifest, folder) {
|
||||
state.delivered[name] = {
|
||||
manifest,
|
||||
...(folder === undefined || folder === name ? {} : { folder }),
|
||||
syncedAt: new Date().toISOString(),
|
||||
endpoint: state.scope.endpoint,
|
||||
account: state.scope.account,
|
||||
root: state.scope.root,
|
||||
};
|
||||
delete state.uploaded[name];
|
||||
}
|
||||
/**
|
||||
|
|
@ -144,23 +177,121 @@ export class SkillSync {
|
|||
* skipped as cloud-origin.
|
||||
*/
|
||||
markUploaded(state, name, record) {
|
||||
state.uploaded[name] = record;
|
||||
state.uploaded[name] = {
|
||||
...record,
|
||||
endpoint: state.scope.endpoint,
|
||||
account: state.scope.account,
|
||||
root: state.scope.root,
|
||||
};
|
||||
delete state.delivered[name];
|
||||
}
|
||||
async loadState() {
|
||||
const clean = { version: 1, uploaded: {}, delivered: {}, removed: {} };
|
||||
/** Active scope identity, derived from the live endpoint/account/root. */
|
||||
scopeIdentity(rawScope) {
|
||||
const raw = rawScope ?? this.deps.scope?.();
|
||||
if (raw === undefined)
|
||||
return { endpoint: 'default', account: sha256Hex(''), root: 'default' };
|
||||
const endpoint = raw.endpoint.trim().replace(/\/+$/, '') || 'default';
|
||||
return { endpoint, account: sha256Hex(raw.accountToken), root: raw.root };
|
||||
}
|
||||
scopeKey(scope) {
|
||||
return sha256Hex(`${scope.endpoint}\n${scope.account}\n${scope.root}`).slice(0, 32);
|
||||
}
|
||||
/**
|
||||
* True when this exact local bundle was uploaded under another endpoint,
|
||||
* account or local root. Switching accounts must never silently publish the
|
||||
* previous account's source content into the new account.
|
||||
*/
|
||||
foreignUpload(state, folder, manifest) {
|
||||
for (const [key, scope] of Object.entries(state.scopes)) {
|
||||
if (key === state.key)
|
||||
continue;
|
||||
for (const record of Object.values(scope.uploaded)) {
|
||||
if (record.folder === folder)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const legacy = state.legacy?.uploaded ?? {};
|
||||
return Object.values(legacy).some((record) => record.folder === folder);
|
||||
}
|
||||
emptyState(scope = this.scopeIdentity()) {
|
||||
return {
|
||||
version: 2,
|
||||
key: this.scopeKey(scope),
|
||||
scope,
|
||||
uploaded: {},
|
||||
delivered: {},
|
||||
removed: {},
|
||||
scopes: {},
|
||||
};
|
||||
}
|
||||
static mapOf(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
||||
}
|
||||
static scopeOf(value) {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
||||
return undefined;
|
||||
const raw = value;
|
||||
if (typeof raw.endpoint !== 'string' || typeof raw.account !== 'string' || typeof raw.root !== 'string')
|
||||
return undefined;
|
||||
return {
|
||||
endpoint: raw.endpoint,
|
||||
account: raw.account,
|
||||
root: raw.root,
|
||||
uploaded: SkillSync.mapOf(raw.uploaded),
|
||||
delivered: SkillSync.mapOf(raw.delivered),
|
||||
removed: SkillSync.mapOf(raw.removed),
|
||||
};
|
||||
}
|
||||
async loadState(scope = this.scopeIdentity()) {
|
||||
const clean = this.emptyState(scope);
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(this.statePath(), 'utf8'));
|
||||
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
const raw = parsed;
|
||||
const map = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
||||
return clean;
|
||||
const raw = parsed;
|
||||
const scopes = {};
|
||||
if (raw.scopes !== null && typeof raw.scopes === 'object' && !Array.isArray(raw.scopes)) {
|
||||
for (const [key, value] of Object.entries(raw.scopes)) {
|
||||
const scope = SkillSync.scopeOf(value);
|
||||
if (scope !== undefined)
|
||||
scopes[key] = scope;
|
||||
}
|
||||
}
|
||||
if (raw.version === 2) {
|
||||
const active = scopes[clean.key];
|
||||
const legacy = raw.legacy !== null && typeof raw.legacy === 'object' && !Array.isArray(raw.legacy)
|
||||
? raw.legacy
|
||||
: undefined;
|
||||
return {
|
||||
version: 1,
|
||||
uploaded: map(raw.uploaded),
|
||||
delivered: map(raw.delivered),
|
||||
removed: map(raw.removed),
|
||||
...clean,
|
||||
scopes,
|
||||
uploaded: active?.uploaded ?? {},
|
||||
delivered: active?.delivered ?? {},
|
||||
removed: active?.removed ?? {},
|
||||
...(legacy === undefined ? {} : {
|
||||
legacy: {
|
||||
uploaded: SkillSync.mapOf(legacy.uploaded),
|
||||
delivered: SkillSync.mapOf(legacy.delivered),
|
||||
removed: SkillSync.mapOf(legacy.removed),
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
// v1 sidecar: no way to prove which endpoint/account/root wrote it.
|
||||
// Keep it as a read-only quarantine so old-origin content can never be
|
||||
// auto-uploaded into a newly configured account.
|
||||
const legacy = {
|
||||
uploaded: SkillSync.mapOf(raw.uploaded),
|
||||
delivered: SkillSync.mapOf(raw.delivered),
|
||||
removed: SkillSync.mapOf(raw.removed),
|
||||
};
|
||||
return {
|
||||
...clean,
|
||||
// A local deletion is user intent, not account content, so the marker
|
||||
// itself may carry forward; uploaded/delivered records stay quarantined.
|
||||
removed: { ...legacy.removed },
|
||||
legacy,
|
||||
};
|
||||
}
|
||||
catch {
|
||||
// Missing or corrupt sidecar: start clean; the cloud is the truth.
|
||||
|
|
@ -168,11 +299,37 @@ export class SkillSync {
|
|||
return clean;
|
||||
}
|
||||
async saveState(state) {
|
||||
state.scopes[state.key] = {
|
||||
endpoint: state.scope.endpoint,
|
||||
account: state.scope.account,
|
||||
root: state.scope.root,
|
||||
uploaded: state.uploaded,
|
||||
delivered: state.delivered,
|
||||
removed: state.removed,
|
||||
};
|
||||
const path = this.statePath();
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const temporary = `${path}.tmp-${process.pid}`;
|
||||
await writeFile(temporary, JSON.stringify(state, null, 2));
|
||||
await rename(temporary, path);
|
||||
const temporary = `${path}.tmp-${process.pid}-${randomUUID()}`;
|
||||
// Top-level uploaded/delivered/removed mirror the active scope: the file
|
||||
// remains readable by older dashboards and verification scripts, while
|
||||
// scopes{} is the authoritative, account-isolated copy.
|
||||
const payload = {
|
||||
version: 2,
|
||||
scope: { ...state.scope, key: state.key },
|
||||
scopes: state.scopes,
|
||||
uploaded: state.uploaded,
|
||||
delivered: state.delivered,
|
||||
removed: state.removed,
|
||||
...(state.legacy === undefined ? {} : { legacy: state.legacy }),
|
||||
};
|
||||
try {
|
||||
await writeFile(temporary, JSON.stringify(payload, null, 2));
|
||||
await rename(temporary, path);
|
||||
}
|
||||
catch (error) {
|
||||
await rm(temporary, { force: true }).catch(() => { });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/** One full pass; never throws — outcomes land in the stats. */
|
||||
async syncOnce() {
|
||||
|
|
@ -181,13 +338,33 @@ export class SkillSync {
|
|||
const settings = this.deps.settings();
|
||||
if (!settings.enabled || !settings.skillsSyncEnabled)
|
||||
return this.current;
|
||||
return this.runExclusive(() => this.syncOnceLocked());
|
||||
}
|
||||
/**
|
||||
* Serialized job runner: every mutating entry point (sync pass, single
|
||||
* resolve, batch resolve) queues here, so an in-flight pass and a UI resolve
|
||||
* can never interleave their awaits over the same skill files and state.
|
||||
*/
|
||||
enqueue(job) {
|
||||
const next = this.queueTail.then(job, job);
|
||||
this.queueTail = next.catch(() => { });
|
||||
return next;
|
||||
}
|
||||
async syncOnceLocked() {
|
||||
if (this.running)
|
||||
return this.current;
|
||||
const run = this.captureRun();
|
||||
const scope = run.scope;
|
||||
const client = run.client;
|
||||
const repo = run.repo;
|
||||
this.runScopeKey = this.scopeKey(scope);
|
||||
this.running = true;
|
||||
const stats = {
|
||||
running: true, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0,
|
||||
};
|
||||
this.current = stats;
|
||||
try {
|
||||
await this.pass(stats);
|
||||
await this.pass(stats, { scope, client, repo });
|
||||
stats.lastRunAt = new Date().toISOString();
|
||||
}
|
||||
catch (error) {
|
||||
|
|
@ -197,6 +374,8 @@ export class SkillSync {
|
|||
finally {
|
||||
stats.running = false;
|
||||
this.running = false;
|
||||
this.runRepository = undefined;
|
||||
this.runScopeKey = undefined;
|
||||
this.current = stats;
|
||||
}
|
||||
return this.current;
|
||||
|
|
@ -204,27 +383,57 @@ export class SkillSync {
|
|||
/** Record a conflict once per pass, however many rules trip over it. */
|
||||
conflict(stats, name, reason) {
|
||||
if (!stats.conflicts.some((item) => item.name === name && item.reason === reason)) {
|
||||
stats.conflicts.push({ name, reason });
|
||||
stats.conflicts.push({ name, reason, ...(this.runScopeKey === undefined ? {} : { scopeKey: this.runScopeKey }) });
|
||||
}
|
||||
}
|
||||
/** One full pass; never throws — outcomes land in the stats. */
|
||||
async pass(stats) {
|
||||
const repo = this.deps.repository();
|
||||
const client = this.deps.client();
|
||||
captureRun() {
|
||||
const rawScope = this.deps.scope?.() ?? { endpoint: 'default', accountToken: '', root: 'default' };
|
||||
const scope = this.scopeIdentity(rawScope);
|
||||
return { scope, client: this.deps.clientForScope?.(rawScope) ?? this.deps.client(), repo: this.deps.repositoryForScope?.(scope) ?? this.currentRepository() };
|
||||
}
|
||||
currentRepository() { return this.runRepository ?? this.deps.repository(); }
|
||||
async pass(stats, run) {
|
||||
this.runRepository = run.repo;
|
||||
const repo = run.repo;
|
||||
const client = run.client;
|
||||
const state = await this.loadState(run.scope);
|
||||
const listing = await client.listSkills();
|
||||
if (!listing.ok)
|
||||
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
|
||||
const items = (listing.data.items ?? []).filter((item) => typeof item.name === 'string' && CLOUD_SKILL_NAME.test(item.name));
|
||||
const cloudByName = new Map(items.map((item) => [item.name, item]));
|
||||
const state = await this.loadState();
|
||||
let stateDirty = false;
|
||||
// Self-heal: an uploaded folder whose delivery receipt reappeared (a
|
||||
// restore, a hand copy) counts as cloud-delivered from now on.
|
||||
for (const name of Object.keys(state.uploaded)) {
|
||||
const local = await repo.read(name);
|
||||
const record = state.uploaded[name];
|
||||
if (record === undefined)
|
||||
continue;
|
||||
const local = await repo.read(record.folder);
|
||||
const delivery = local?.delivery;
|
||||
if (delivery !== undefined) {
|
||||
this.markDelivered(state, name, delivery.manifest ?? '');
|
||||
this.markDelivered(state, name, delivery.manifest ?? '', record.folder);
|
||||
stateDirty = true;
|
||||
}
|
||||
}
|
||||
// Local presence is scanned BEFORE DOWN. A cloud-delivered skill the user
|
||||
// deleted must be tombstoned before the cloud listing can resurrect it.
|
||||
// The parking area counts as present (a parked skill is disabled, not
|
||||
// deleted), and a first download has no receipt yet, so it can never be
|
||||
// mistaken for a deletion.
|
||||
const presentFolders = new Set((await repo.list()).map((entry) => entry.name));
|
||||
for (const [name, record] of Object.entries(state.uploaded)) {
|
||||
if (!presentFolders.has(record.folder)) {
|
||||
state.removed[name] = { manifest: cloudByName.get(name)?.manifest_sha256 ?? record.manifest };
|
||||
delete state.uploaded[name];
|
||||
stateDirty = true;
|
||||
}
|
||||
}
|
||||
for (const [name, record] of Object.entries(state.delivered)) {
|
||||
if (!presentFolders.has(record.folder ?? name)) {
|
||||
state.removed[name] = { manifest: record.manifest };
|
||||
delete state.delivered[name];
|
||||
stateDirty = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -240,20 +449,25 @@ export class SkillSync {
|
|||
continue;
|
||||
}
|
||||
const removed = state.removed[item.name];
|
||||
const local = await repo.read(item.name);
|
||||
const uploaded = state.uploaded[item.name];
|
||||
const localFolder = uploaded?.folder ?? state.delivered[item.name]?.folder ?? item.name;
|
||||
const local = await repo.read(localFolder);
|
||||
const exists = local !== undefined;
|
||||
const delivery = local?.delivery;
|
||||
if (removed !== undefined && exists) {
|
||||
delete state.removed[item.name];
|
||||
stateDirty = true;
|
||||
}
|
||||
else if (removed !== undefined && item.manifest_sha256 === removed.manifest) {
|
||||
stats.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
else if (removed !== undefined) {
|
||||
delete state.removed[item.name];
|
||||
stateDirty = true;
|
||||
if (removed !== undefined) {
|
||||
if (exists) {
|
||||
// The user re-created the folder locally: lift the tombstone and let
|
||||
// the normal collision rules decide what happens next.
|
||||
delete state.removed[item.name];
|
||||
stateDirty = true;
|
||||
}
|
||||
else {
|
||||
// A tombstone is name-based, not manifest-based: a later cloud
|
||||
// revision must not silently resurrect something the user deleted.
|
||||
// An explicit take_cloud/reinstall clears the marker instead.
|
||||
stats.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (exists && delivery !== undefined) {
|
||||
if (!this.deliveredIntact(local, delivery)) {
|
||||
|
|
@ -267,7 +481,7 @@ export class SkillSync {
|
|||
}
|
||||
if (delivery.manifest === item.manifest_sha256) {
|
||||
if (state.delivered[item.name]?.manifest !== item.manifest_sha256) {
|
||||
this.markDelivered(state, item.name, item.manifest_sha256 ?? '');
|
||||
this.markDelivered(state, item.name, item.manifest_sha256 ?? '', localFolder);
|
||||
stateDirty = true;
|
||||
}
|
||||
stats.skipped += 1;
|
||||
|
|
@ -300,8 +514,8 @@ export class SkillSync {
|
|||
this.conflict(stats, item.name, 'script_review_required');
|
||||
continue;
|
||||
}
|
||||
await repo.write(item.name, bundle.data);
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
|
||||
await repo.write(item.name, bundle.data, { folder: localFolder });
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256, localFolder);
|
||||
stateDirty = true;
|
||||
if (exists)
|
||||
stats.updated.push(item.name);
|
||||
|
|
@ -331,6 +545,47 @@ export class SkillSync {
|
|||
}
|
||||
const record = state.uploaded[skill.name];
|
||||
const cloud = cloudByName.get(skill.name);
|
||||
if (record === undefined && this.foreignUpload(state, entry.name, skill.manifest)) {
|
||||
// Quarantined content from another endpoint/account/root: never upload
|
||||
// it automatically. A user can still explicitly import/edit it later.
|
||||
stats.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if (record !== undefined && record.manifest === skill.manifest) {
|
||||
const cloudRevision = cloud?.revision;
|
||||
const cloudManifest = cloud?.manifest_sha256;
|
||||
const remoteChanged = cloud !== undefined && ((cloudRevision !== undefined && cloudRevision !== record.revision) ||
|
||||
(cloudManifest !== undefined && cloudManifest !== record.manifest));
|
||||
if (!remoteChanged) {
|
||||
stats.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if (cloudManifest === skill.manifest) {
|
||||
// Same bytes, newer cloud revision: re-pin the receipt only.
|
||||
this.markUploaded(state, skill.name, {
|
||||
folder: entry.name,
|
||||
revision: cloudRevision ?? record.revision,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
});
|
||||
stateDirty = true;
|
||||
stats.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
// Local is byte-for-byte what we last uploaded, but the center moved
|
||||
// on: the local copy is stale, so take the cloud revision instead of
|
||||
// re-uploading the old bytes over it. Script changes still wait for
|
||||
// explicit review inside autoTakeCloud.
|
||||
const auto = await this.autoTakeCloud(cloud, local, state, stats, client, entry.name);
|
||||
if (auto !== 'unresolved') {
|
||||
stateDirty = true;
|
||||
continue;
|
||||
}
|
||||
if (!knownConflicts.has(skill.name))
|
||||
this.conflict(stats, skill.name, 'cloud_newer');
|
||||
continue;
|
||||
}
|
||||
if (cloud !== undefined && record === undefined) {
|
||||
if (knownConflicts.has(skill.name))
|
||||
continue;
|
||||
|
|
@ -341,6 +596,7 @@ export class SkillSync {
|
|||
folder: entry.name,
|
||||
revision: cloud.revision ?? 1,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
});
|
||||
stateDirty = true;
|
||||
|
|
@ -359,10 +615,6 @@ export class SkillSync {
|
|||
this.conflict(stats, skill.name, 'name_collision');
|
||||
continue;
|
||||
}
|
||||
if (record !== undefined && record.manifest === skill.manifest) {
|
||||
stats.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
const files = this.toUploadFiles(skill.files);
|
||||
const operationId = `dsh-skill-${randomUUID()}`;
|
||||
if (record === undefined || cloud === undefined) {
|
||||
|
|
@ -382,6 +634,7 @@ export class SkillSync {
|
|||
folder: entry.name,
|
||||
revision: created.data.skill?.revision ?? created.data.revision ?? 1,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
});
|
||||
stateDirty = true;
|
||||
|
|
@ -397,6 +650,7 @@ export class SkillSync {
|
|||
folder: entry.name,
|
||||
revision: cloud.revision,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
});
|
||||
stateDirty = true;
|
||||
|
|
@ -433,30 +687,13 @@ export class SkillSync {
|
|||
folder: entry.name,
|
||||
revision: updated.data.skill?.revision ?? updated.data.revision ?? record.revision + 1,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
});
|
||||
stateDirty = true;
|
||||
stats.updated.push(skill.name);
|
||||
}
|
||||
}
|
||||
// Presence counts the parking area too: a parked skill is disabled,
|
||||
// not deleted. Anything missing from both is a deliberate removal
|
||||
// (remembered, so it is not resurrected); the cloud copy stays.
|
||||
const presentFolders = new Set((await repo.list()).map((entry) => entry.name));
|
||||
for (const [name, record] of Object.entries(state.uploaded)) {
|
||||
if (!presentFolders.has(record.folder)) {
|
||||
state.removed[name] = { manifest: cloudByName.get(name)?.manifest_sha256 ?? record.manifest };
|
||||
delete state.uploaded[name];
|
||||
stateDirty = true;
|
||||
}
|
||||
}
|
||||
for (const [name, record] of Object.entries(state.delivered)) {
|
||||
if (!presentFolders.has(name)) {
|
||||
state.removed[name] = { manifest: record.manifest };
|
||||
delete state.delivered[name];
|
||||
stateDirty = true;
|
||||
}
|
||||
}
|
||||
if (stateDirty)
|
||||
await this.saveState(state);
|
||||
const changed = stats.downloaded.length + stats.uploaded.length + stats.updated.length;
|
||||
|
|
@ -527,16 +764,16 @@ export class SkillSync {
|
|||
* receipt without a transfer, so the next pass treats the folder as
|
||||
* cloud-origin and nobody is asked to pick between two identical copies.
|
||||
*/
|
||||
async adoptIdenticalDelivery(item, local) {
|
||||
await this.deps.repository().write(item.name, {
|
||||
async adoptIdenticalDelivery(item, local, folder) {
|
||||
await this.currentRepository().write(item.name, {
|
||||
name: item.name,
|
||||
revision: item.revision ?? 1,
|
||||
manifest_sha256: item.manifest_sha256 ?? this.localManifest(local.files),
|
||||
files: local.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
});
|
||||
}, { folder });
|
||||
}
|
||||
/** Fetch, verify and install the cloud copy, backing the local one up first. */
|
||||
async autoTakeCloud(item, local, state, stats, client) {
|
||||
async autoTakeCloud(item, local, state, stats, client, folder) {
|
||||
if (item.script_changed === true) {
|
||||
this.conflict(stats, item.name, 'script_review_required');
|
||||
return 'conflict';
|
||||
|
|
@ -554,10 +791,12 @@ export class SkillSync {
|
|||
this.conflict(stats, item.name, 'script_review_required');
|
||||
return 'conflict';
|
||||
}
|
||||
const uploaded = state.uploaded[item.name];
|
||||
const localFolder = folder ?? uploaded?.folder ?? local?.name ?? item.name;
|
||||
if (local !== undefined)
|
||||
await this.deps.repository().snapshot(item.name);
|
||||
await this.deps.repository().write(item.name, bundle.data);
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
|
||||
await this.currentRepository().snapshot(localFolder);
|
||||
await this.currentRepository().write(item.name, bundle.data, { folder: localFolder, cleanupFiles: uploaded?.files?.map((file) => file.path) });
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256, localFolder);
|
||||
delete state.removed[item.name];
|
||||
stats.updated.push(item.name);
|
||||
return 'resolved';
|
||||
|
|
@ -576,13 +815,14 @@ export class SkillSync {
|
|||
return 'conflict';
|
||||
}
|
||||
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
|
||||
await this.deps.repository().write(skill.name, {
|
||||
await this.currentRepository().write(skill.name, {
|
||||
name: skill.name,
|
||||
revision,
|
||||
manifest_sha256: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
}, { delivery: false });
|
||||
this.markUploaded(state, skill.name, { folder, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
|
||||
this.markUploaded(state, skill.name, { folder, revision, manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() });
|
||||
delete state.removed[skill.name];
|
||||
stats.updated.push(skill.name);
|
||||
return 'resolved';
|
||||
|
|
@ -592,8 +832,8 @@ export class SkillSync {
|
|||
if (!local.files.some((file) => file.path === 'SKILL.md'))
|
||||
return 'unresolved';
|
||||
if (item.manifest_sha256 !== undefined && this.localManifest(local.files) === item.manifest_sha256) {
|
||||
await this.adoptIdenticalDelivery(item, local);
|
||||
this.markDelivered(state, item.name, item.manifest_sha256);
|
||||
await this.adoptIdenticalDelivery(item, local, local.name);
|
||||
this.markDelivered(state, item.name, item.manifest_sha256, local.name);
|
||||
stats.skipped += 1;
|
||||
return 'resolved';
|
||||
}
|
||||
|
|
@ -602,8 +842,8 @@ export class SkillSync {
|
|||
/** Resolve a locally-modified cloud delivery. */
|
||||
async autoResolveLocalDrift(item, local, state, stats, client) {
|
||||
if (item.manifest_sha256 !== undefined && local.files.length > 0 && this.localManifest(local.files) === item.manifest_sha256) {
|
||||
await this.adoptIdenticalDelivery(item, local);
|
||||
this.markDelivered(state, item.name, item.manifest_sha256);
|
||||
await this.adoptIdenticalDelivery(item, local, local.name);
|
||||
this.markDelivered(state, item.name, item.manifest_sha256, local.name);
|
||||
stats.skipped += 1;
|
||||
return 'resolved';
|
||||
}
|
||||
|
|
@ -616,7 +856,7 @@ export class SkillSync {
|
|||
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
|
||||
return 'unresolved';
|
||||
if (cloudAt > localAt)
|
||||
return this.autoTakeCloud(item, local, state, stats, client);
|
||||
return this.autoTakeCloud(item, local, state, stats, client, local.name);
|
||||
const skill = await this.readLocalSkill(local, item.name);
|
||||
if (skill === undefined)
|
||||
return 'unresolved';
|
||||
|
|
@ -634,18 +874,27 @@ export class SkillSync {
|
|||
* `take_cloud`). Partial failures are collected instead of aborting the
|
||||
* whole batch, so the UI can show "N done, M failed" in one shot.
|
||||
*/
|
||||
async resolveConflicts(actionInput) {
|
||||
async resolveConflicts(actionInput, conflictIdsInput) {
|
||||
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : '';
|
||||
if (action === '')
|
||||
throw new Error('invalid_action');
|
||||
return this.runExclusive(() => this.resolveConflictsLocked(action, conflictIdsInput));
|
||||
}
|
||||
async resolveConflictsLocked(action, conflictIdsInput) {
|
||||
if (this.running)
|
||||
throw new Error('sync_running');
|
||||
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))];
|
||||
const run = this.captureRun();
|
||||
const scopeKey = this.scopeKey(run.scope);
|
||||
const details = await this.conflictDetails(run);
|
||||
const requested = Array.isArray(conflictIdsInput) ? new Set(conflictIdsInput.filter((value) => typeof value === 'string')) : undefined;
|
||||
const selected = details.filter((detail) => (detail.scopeKey === scopeKey || detail.scopeKey === '') && (requested === undefined || requested.has(detail.conflictId)));
|
||||
const names = [...new Set(selected.map((detail) => detail.name))];
|
||||
const idByName = new Map(selected.map((detail) => [detail.name, detail.conflictId]));
|
||||
const resolved = [];
|
||||
const failed = [];
|
||||
for (const name of names) {
|
||||
try {
|
||||
await this.resolveConflict(name, action);
|
||||
await this.resolveConflictLocked(name, action, run, idByName.get(name));
|
||||
resolved.push(name);
|
||||
}
|
||||
catch (error) {
|
||||
|
|
@ -654,14 +903,16 @@ export class SkillSync {
|
|||
}
|
||||
return { action, resolved, failed };
|
||||
}
|
||||
async conflictDetails() {
|
||||
async conflictDetails(run) {
|
||||
const conflicts = this.current.conflicts;
|
||||
if (conflicts.length === 0)
|
||||
return [];
|
||||
const repo = this.deps.repository();
|
||||
const active = run ?? this.captureRun();
|
||||
const repo = active.repo;
|
||||
const state = await this.loadState(active.scope);
|
||||
let cloudItems = [];
|
||||
try {
|
||||
const listing = await this.deps.client().listSkills();
|
||||
const listing = await active.client.listSkills();
|
||||
if (listing.ok)
|
||||
cloudItems = listing.data.items ?? [];
|
||||
}
|
||||
|
|
@ -671,7 +922,8 @@ export class SkillSync {
|
|||
const byName = new Map(cloudItems.map((item) => [item.name, item]));
|
||||
const out = [];
|
||||
for (const conflict of conflicts) {
|
||||
const local = await repo.read(conflict.name);
|
||||
const localFolder = state.uploaded[conflict.name]?.folder ?? state.delivered[conflict.name]?.folder ?? conflict.name;
|
||||
const local = await repo.read(localFolder);
|
||||
const location = local?.area ?? 'none';
|
||||
const files = local?.files.length ?? 0;
|
||||
const bytes = (local?.files ?? []).reduce((sum, file) => sum + file.size, 0);
|
||||
|
|
@ -680,7 +932,15 @@ export class SkillSync {
|
|||
modified = local.delivery === undefined ? true : !this.deliveredIntact(local, local.delivery);
|
||||
}
|
||||
const cloudItem = byName.get(conflict.name);
|
||||
const localVersion = local === undefined ? 'none' : sha256Hex(local.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
|
||||
const cloudVersion = cloudItem === undefined ? 'none' : String(cloudItem.revision ?? '') + ':' + String(cloudItem.manifest_sha256 ?? '');
|
||||
const scopeKey = conflict.scopeKey ?? this.scopeKey(active.scope);
|
||||
const conflictId = sha256Hex([scopeKey, conflict.name, conflict.reason, localVersion, cloudVersion].join('|'));
|
||||
out.push({
|
||||
conflictId,
|
||||
scopeKey,
|
||||
localVersion,
|
||||
cloudVersion,
|
||||
name: conflict.name,
|
||||
reason: conflict.reason,
|
||||
local: { exists: location !== 'none', location, files, bytes, modified },
|
||||
|
|
@ -700,112 +960,143 @@ export class SkillSync {
|
|||
}
|
||||
return out;
|
||||
}
|
||||
async resolveConflict(nameInput, actionInput) {
|
||||
async resolveConflict(nameInput, actionInput, conflictIdInput) {
|
||||
const name = typeof nameInput === 'string' ? nameInput : '';
|
||||
if (name === '' || !CLOUD_SKILL_NAME.test(name))
|
||||
throw new Error('invalid_name');
|
||||
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' || actionInput === 'manual' ? actionInput : '';
|
||||
if (action === '')
|
||||
throw new Error('invalid_action');
|
||||
return this.runExclusive(() => { const run = this.captureRun(); return this.resolveConflictLocked(name, action, run, typeof conflictIdInput === 'string' ? conflictIdInput : undefined); });
|
||||
}
|
||||
async resolveConflictLocked(name, action, run, expectedConflictId) {
|
||||
if (this.running)
|
||||
throw new Error('sync_running');
|
||||
const repo = this.deps.repository();
|
||||
const client = this.deps.client();
|
||||
const listing = await client.listSkills();
|
||||
if (!listing.ok)
|
||||
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
|
||||
const cloud = (listing.data.items ?? []).find((item) => item.name === name);
|
||||
const state = await this.loadState();
|
||||
if (action === 'manual') {
|
||||
return {
|
||||
name,
|
||||
action,
|
||||
applied: false,
|
||||
note: '已返回两侧信息,未改动任何文件;手工编辑后在下次同步前保存即可。',
|
||||
...(cloud?.revision === undefined ? {} : { revision: cloud.revision }),
|
||||
};
|
||||
}
|
||||
if (action === 'keep_local') {
|
||||
const local = await repo.read(name);
|
||||
if (local === undefined)
|
||||
throw new Error('no_local_copy');
|
||||
const skill = await this.readLocalSkill(local, name);
|
||||
if (skill === undefined)
|
||||
throw new Error('not_a_skill');
|
||||
if (typeof skill === 'string')
|
||||
throw new Error(skill);
|
||||
const files = this.toUploadFiles(skill.files);
|
||||
const operationId = `dsh-skill-${randomUUID()}`;
|
||||
if (cloud === undefined) {
|
||||
const created = await client.createSkill({
|
||||
name: skill.name,
|
||||
const active = run ?? this.captureRun();
|
||||
const scope = active.scope;
|
||||
const repo = active.repo;
|
||||
const client = active.client;
|
||||
this.runRepository = repo;
|
||||
try {
|
||||
const conflict = this.current.conflicts.find((item) => item.name === name);
|
||||
if (conflict?.scopeKey !== undefined && conflict.scopeKey !== this.scopeKey(scope))
|
||||
throw new Error('stale_conflict');
|
||||
if (expectedConflictId === undefined)
|
||||
throw new Error('confirmation_required');
|
||||
const details = await this.conflictDetails(active);
|
||||
const confirmed = details.find((detail) => detail.name === name);
|
||||
if (confirmed === undefined || confirmed.conflictId !== expectedConflictId)
|
||||
throw new Error('stale_conflict');
|
||||
const listing = await client.listSkills();
|
||||
if (!listing.ok)
|
||||
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
|
||||
const cloud = (listing.data.items ?? []).find((item) => item.name === name);
|
||||
const state = await this.loadState(scope);
|
||||
const localFolder = state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name;
|
||||
const localNow = await repo.read(localFolder);
|
||||
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
|
||||
if (localVersionNow !== confirmed.localVersion)
|
||||
throw new Error('stale_conflict');
|
||||
if ((cloud?.revision ?? undefined) !== (confirmed.cloud?.revision ?? undefined) || (cloud?.manifest_sha256 ?? undefined) !== (confirmed.cloud?.manifest ?? undefined))
|
||||
throw new Error('stale_conflict');
|
||||
if (action === 'manual') {
|
||||
return {
|
||||
name,
|
||||
action,
|
||||
applied: false,
|
||||
note: '已返回两侧信息,未改动任何文件;手工编辑后在下次同步前保存即可。',
|
||||
...(cloud?.revision === undefined ? {} : { revision: cloud.revision }),
|
||||
};
|
||||
}
|
||||
if (action === 'keep_local') {
|
||||
const local = localNow;
|
||||
if (local === undefined)
|
||||
throw new Error('no_local_copy');
|
||||
const skill = await this.readLocalSkill(local, localFolder);
|
||||
if (skill === undefined)
|
||||
throw new Error('not_a_skill');
|
||||
if (typeof skill === 'string')
|
||||
throw new Error(skill);
|
||||
const files = this.toUploadFiles(skill.files);
|
||||
const operationId = `dsh-skill-${randomUUID()}`;
|
||||
if (confirmed.cloud === null) {
|
||||
const created = await client.createSkill({
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
execution_mode: skill.hasScripts ? 'local-bundle' : 'prompt-only',
|
||||
files,
|
||||
expected_revision: 0,
|
||||
operation_id: operationId,
|
||||
});
|
||||
if (!created.ok)
|
||||
throw new Error(`upload_failed: ${describeError(created.error)}`);
|
||||
const revision = created.data.skill?.revision ?? created.data.revision ?? 1;
|
||||
await repo.write(name, {
|
||||
name: skill.name,
|
||||
revision,
|
||||
manifest_sha256: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
}, { delivery: false });
|
||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() });
|
||||
delete state.removed[name];
|
||||
await this.saveState(state);
|
||||
this.dropConflict(name);
|
||||
return { name, action, applied: true, revision, note: '已把本地版本新建到云端。' };
|
||||
}
|
||||
const updated = await client.updateSkill(skill.name, {
|
||||
description: skill.description,
|
||||
execution_mode: skill.hasScripts ? 'local-bundle' : 'prompt-only',
|
||||
files,
|
||||
expected_revision: 0,
|
||||
expected_revision: confirmed.cloud?.revision ?? 0,
|
||||
operation_id: operationId,
|
||||
});
|
||||
if (!created.ok)
|
||||
throw new Error(`upload_failed: ${describeError(created.error)}`);
|
||||
const revision = created.data.skill?.revision ?? created.data.revision ?? 1;
|
||||
if (!updated.ok) {
|
||||
if (updated.error.code === 'revision_conflict')
|
||||
throw new Error('stale_revision');
|
||||
throw new Error(`upload_failed: ${describeError(updated.error)}`);
|
||||
}
|
||||
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (confirmed.cloud?.revision ?? 0) + 1;
|
||||
await repo.write(name, {
|
||||
name: skill.name,
|
||||
revision,
|
||||
manifest_sha256: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
}, { delivery: false });
|
||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
|
||||
}, { delivery: false, folder: localFolder });
|
||||
this.markUploaded(state, name, { folder: localFolder, revision, manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() });
|
||||
delete state.removed[name];
|
||||
await this.saveState(state);
|
||||
this.dropConflict(name);
|
||||
return { name, action, applied: true, revision, note: '已把本地版本新建到云端。' };
|
||||
return { name, action, applied: true, revision, note: '已用本地版本覆盖云端(revision 已更新)。' };
|
||||
}
|
||||
const updated = await client.updateSkill(skill.name, {
|
||||
description: skill.description,
|
||||
files,
|
||||
expected_revision: cloud.revision ?? 0,
|
||||
operation_id: operationId,
|
||||
});
|
||||
if (!updated.ok) {
|
||||
if (updated.error.code === 'revision_conflict')
|
||||
throw new Error('stale_revision');
|
||||
throw new Error(`upload_failed: ${describeError(updated.error)}`);
|
||||
if (confirmed.cloud === null)
|
||||
throw new Error('no_cloud_copy');
|
||||
const bundle = await client.skillBundle(name);
|
||||
if (!bundle.ok)
|
||||
throw new Error(`bundle_failed: ${describeError(bundle.error)}`);
|
||||
if (bundle.data.name !== name || bundle.data.revision !== confirmed.cloud.revision || bundle.data.manifest_sha256 !== confirmed.cloud.manifest)
|
||||
throw new Error('stale_conflict');
|
||||
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
|
||||
throw new Error('manifest_mismatch');
|
||||
}
|
||||
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
|
||||
await repo.write(name, {
|
||||
name: skill.name,
|
||||
revision,
|
||||
manifest_sha256: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
}, { delivery: false });
|
||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
|
||||
const local = localNow;
|
||||
const backup = local !== undefined ? (await repo.snapshot(localFolder)) ?? '' : '';
|
||||
await repo.write(name, bundle.data, { folder: localFolder });
|
||||
this.markDelivered(state, name, bundle.data.manifest_sha256, localFolder);
|
||||
delete state.removed[name];
|
||||
await this.saveState(state);
|
||||
this.dropConflict(name);
|
||||
return { name, action, applied: true, revision, note: '已用本地版本覆盖云端(revision 已更新)。' };
|
||||
return {
|
||||
name,
|
||||
action,
|
||||
applied: true,
|
||||
revision: bundle.data.revision,
|
||||
...(backup === '' ? {} : { backup }),
|
||||
note: '已采用云端版本覆盖本地(本地已备份)。',
|
||||
};
|
||||
}
|
||||
if (cloud === undefined)
|
||||
throw new Error('no_cloud_copy');
|
||||
const bundle = await client.skillBundle(name);
|
||||
if (!bundle.ok)
|
||||
throw new Error(`bundle_failed: ${describeError(bundle.error)}`);
|
||||
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
|
||||
throw new Error('manifest_mismatch');
|
||||
finally {
|
||||
this.runRepository = undefined;
|
||||
}
|
||||
const local = await repo.read(name);
|
||||
const backup = local !== undefined ? (await repo.snapshot(name)) ?? '' : '';
|
||||
await repo.write(name, bundle.data);
|
||||
this.markDelivered(state, name, bundle.data.manifest_sha256);
|
||||
delete state.removed[name];
|
||||
await this.saveState(state);
|
||||
this.dropConflict(name);
|
||||
return {
|
||||
name,
|
||||
action,
|
||||
applied: true,
|
||||
revision: bundle.data.revision,
|
||||
...(backup === '' ? {} : { backup }),
|
||||
note: '已采用云端版本覆盖本地(本地已备份)。',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -104,9 +104,17 @@ export class SkillUpdater {
|
|||
return this.deps.backupsDir?.() ?? skillBackupsDir();
|
||||
}
|
||||
guard() {
|
||||
if (this.deps.gate().isRunning())
|
||||
const gate = this.deps.gate();
|
||||
const busy = gate.busy === undefined ? gate.isRunning() : gate.busy();
|
||||
if (busy)
|
||||
throw new SkillAdminError('sync_running', '技能同步正在进行,请稍候再试。');
|
||||
}
|
||||
/** Run the whole update/rollback transaction behind the shared write lock. */
|
||||
async exclusive(job) {
|
||||
this.guard();
|
||||
const gate = this.deps.gate();
|
||||
return gate.runExclusive === undefined ? job() : gate.runExclusive(job);
|
||||
}
|
||||
async find(folder) {
|
||||
const found = await this.deps.admin.locate(folder);
|
||||
if (found === undefined)
|
||||
|
|
@ -187,63 +195,65 @@ export class SkillUpdater {
|
|||
}
|
||||
/** Back up the current folder, then replace it with the source's latest. */
|
||||
async applyUpdate(folderInput, expectedCommit) {
|
||||
this.guard();
|
||||
const folder = typeof folderInput === 'string' ? folderInput : '';
|
||||
if (folder === '')
|
||||
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
|
||||
const { dir, source } = await this.find(folder);
|
||||
const check = await this.checkUpdate(folder);
|
||||
if (!check.available)
|
||||
throw new SkillAdminError('up_to_date', '已经是最新版本,无需更新。');
|
||||
if (typeof expectedCommit === 'string' && expectedCommit !== '' && check.remoteCommit !== expectedCommit) {
|
||||
throw new SkillAdminError('stale_plan', '来源在上次检查后已更新,请重新检查差异再更新。');
|
||||
}
|
||||
return this.replaceWith(dir, source, { commit: check.remoteCommit ?? source.commit, ref: source.ref });
|
||||
return this.exclusive(async () => {
|
||||
const folder = typeof folderInput === 'string' ? folderInput : '';
|
||||
if (folder === '')
|
||||
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
|
||||
const { dir, source } = await this.find(folder);
|
||||
const check = await this.checkUpdate(folder);
|
||||
if (!check.available)
|
||||
throw new SkillAdminError('up_to_date', '已经是最新版本,无需更新。');
|
||||
if (typeof expectedCommit === 'string' && expectedCommit !== '' && check.remoteCommit !== expectedCommit) {
|
||||
throw new SkillAdminError('stale_plan', '来源在上次检查后已更新,请重新检查差异再更新。');
|
||||
}
|
||||
return this.replaceWith(dir, source, { commit: check.remoteCommit ?? source.commit, ref: source.ref });
|
||||
});
|
||||
}
|
||||
/** Restore the most recent pre-update backup. */
|
||||
async rollback(folderInput) {
|
||||
this.guard();
|
||||
const folder = typeof folderInput === 'string' ? folderInput : '';
|
||||
if (folder === '')
|
||||
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
|
||||
const { dir, source } = await this.find(folder);
|
||||
const root = join(this.backupsRoot(), folder);
|
||||
const entries = (await readdir(root, { withFileTypes: true }).catch(() => []))
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => entry.name)
|
||||
.sort();
|
||||
const latest = entries[entries.length - 1];
|
||||
if (latest === undefined)
|
||||
throw new SkillAdminError('no_backup', '没有可回退的备份。');
|
||||
const backupDir = join(root, latest);
|
||||
const restored = await readSkillSourceRecord(backupDir);
|
||||
// Restore in place: move the current aside, copy the backup over, then drop
|
||||
// the aside copy only after the backup has landed.
|
||||
const aside = `${dir}.rollbacking-${Date.now().toString(36)}`;
|
||||
await mkdir(join(dir, '..'), { recursive: true });
|
||||
await rename(dir, aside);
|
||||
try {
|
||||
await copySkillTree(backupDir, dir);
|
||||
}
|
||||
catch (error) {
|
||||
await rm(dir, { recursive: true, force: true }).catch(() => { });
|
||||
await rename(aside, dir).catch(() => { });
|
||||
throw new SkillAdminError('rollback_failed', `回退失败,原目录已尽量还原:${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
await rm(aside, { recursive: true, force: true }).catch(() => { });
|
||||
this.deps.log(`skill rolled back: ${folder} <- ${latest}`);
|
||||
const beforeFiles = await hashTree(backupDir);
|
||||
beforeFiles.delete('.skill-source.json');
|
||||
const nowFiles = await hashTree(dir);
|
||||
nowFiles.delete('.skill-source.json');
|
||||
const diff = diffTrees(nowFiles, beforeFiles);
|
||||
return {
|
||||
folder,
|
||||
from: source.commit,
|
||||
to: restored?.commit ?? source.commit,
|
||||
backup: backupDir,
|
||||
...diff,
|
||||
};
|
||||
return this.exclusive(async () => {
|
||||
const folder = typeof folderInput === 'string' ? folderInput : '';
|
||||
if (folder === '')
|
||||
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
|
||||
const { dir, source } = await this.find(folder);
|
||||
const root = join(this.backupsRoot(), folder);
|
||||
const entries = (await readdir(root, { withFileTypes: true }).catch(() => []))
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => entry.name)
|
||||
.sort();
|
||||
const latest = entries[entries.length - 1];
|
||||
if (latest === undefined)
|
||||
throw new SkillAdminError('no_backup', '没有可回退的备份。');
|
||||
const backupDir = join(root, latest);
|
||||
const restored = await readSkillSourceRecord(backupDir);
|
||||
// Restore in place: move the current aside, copy the backup over, then drop
|
||||
// the aside copy only after the backup has landed.
|
||||
const beforeFiles = await hashTree(dir);
|
||||
const aside = `${dir}.rollbacking-${Date.now().toString(36)}`;
|
||||
await mkdir(join(dir, '..'), { recursive: true });
|
||||
await rename(dir, aside);
|
||||
try {
|
||||
await copySkillTree(backupDir, dir);
|
||||
}
|
||||
catch (error) {
|
||||
await rm(dir, { recursive: true, force: true }).catch(() => { });
|
||||
await rename(aside, dir).catch(() => { });
|
||||
throw new SkillAdminError('rollback_failed', `回退失败,原目录已尽量还原:${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
await rm(aside, { recursive: true, force: true }).catch(() => { });
|
||||
this.deps.log(`skill rolled back: ${folder} <- ${latest}`);
|
||||
beforeFiles.delete('.skill-source.json');
|
||||
const nowFiles = await hashTree(dir);
|
||||
nowFiles.delete('.skill-source.json');
|
||||
const diff = diffTrees(beforeFiles, nowFiles);
|
||||
return {
|
||||
folder,
|
||||
from: source.commit,
|
||||
to: restored?.commit ?? source.commit,
|
||||
backup: backupDir,
|
||||
...diff,
|
||||
};
|
||||
});
|
||||
}
|
||||
/** Shared write path: backup, copy new tree, rewrite provenance. */
|
||||
async replaceWith(dir, source, next) {
|
||||
|
|
|
|||
|
|
@ -2,9 +2,16 @@
|
|||
// Directory layout, atomic writes, the delivery receipt and park/unpark
|
||||
// moves live here, so the sync engine never builds a skill path itself.
|
||||
import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { dirname, join, resolve, sep } from 'node:path';
|
||||
import { dshHome } from "../store.js";
|
||||
import { sha256Hex } from "./shared.js";
|
||||
import { checkFolder } from "../skill-admin.js";
|
||||
import { isCloudSkillPath, sha256Hex } from "./shared.js";
|
||||
function inside(root, target) {
|
||||
const normalizedRoot = resolve(root);
|
||||
const normalizedTarget = resolve(target);
|
||||
return normalizedTarget === normalizedRoot || normalizedTarget.startsWith(normalizedRoot + sep);
|
||||
}
|
||||
const RECEIPT = '.manifest.json';
|
||||
async function isDirectory(path) {
|
||||
try {
|
||||
|
|
@ -89,8 +96,18 @@ export class AdminSkillRepository {
|
|||
}
|
||||
return entries;
|
||||
}
|
||||
async locate(name) {
|
||||
const folder = checkFolder(name);
|
||||
const rootDir = join(this.deps.skillsRoot(), folder);
|
||||
if (await isDirectory(rootDir))
|
||||
return { area: 'root', dir: rootDir };
|
||||
const parkedDir = join(this.deps.holdingDir(), folder);
|
||||
if (await isDirectory(parkedDir))
|
||||
return { area: 'holding', dir: parkedDir };
|
||||
return undefined;
|
||||
}
|
||||
async read(name) {
|
||||
const found = await this.deps.admin.locate(name);
|
||||
const found = await this.locate(name);
|
||||
if (found === undefined)
|
||||
return undefined;
|
||||
const area = found.area;
|
||||
|
|
@ -104,30 +121,51 @@ export class AdminSkillRepository {
|
|||
return { name, area, files, delivery: await readDeliveryReceipt(found.dir) };
|
||||
}
|
||||
async write(name, bundle, options) {
|
||||
const found = await this.deps.admin.locate(name);
|
||||
// New skills land in root; a parked folder is written in place.
|
||||
const dir = found?.dir ?? join(this.deps.skillsRoot(), name);
|
||||
const previous = await readDeliveryReceipt(dir);
|
||||
await mkdir(dir, { recursive: true });
|
||||
const keep = new Set(bundle.files.map((file) => file.path));
|
||||
const written = [];
|
||||
let n = 0;
|
||||
// The folder name decides where the whole bundle lands, and the file paths
|
||||
// decide where each write goes — both are attacker-reachable through a
|
||||
// hostile cloud payload, so both are checked before ANY byte is written.
|
||||
checkFolder(name);
|
||||
const decoded = [];
|
||||
for (const file of bundle.files) {
|
||||
if (typeof file.path !== 'string' || !isCloudSkillPath(file.path)) {
|
||||
throw new Error(`refusing to write skill ${name}: invalid file path ${JSON.stringify(file.path)}`);
|
||||
}
|
||||
const bytes = Buffer.from(file.data, 'base64');
|
||||
if (sha256Hex(bytes) !== file.sha256)
|
||||
throw new Error('checksum mismatch for ' + file.path);
|
||||
decoded.push({ file, bytes });
|
||||
}
|
||||
const folder = options?.folder !== undefined && options.folder !== '' ? checkFolder(options.folder) : name;
|
||||
const found = await this.locate(folder);
|
||||
// New skills land in root; a parked folder is written in place.
|
||||
const dir = found?.dir ?? join(this.deps.skillsRoot(), folder);
|
||||
const previous = await readDeliveryReceipt(dir);
|
||||
const cleanup = new Set([...(previous?.files ?? []).map((file) => file.path), ...(options?.cleanupFiles ?? [])]);
|
||||
await mkdir(dir, { recursive: true });
|
||||
const keep = new Set(bundle.files.map((file) => file.path));
|
||||
const written = [];
|
||||
for (const { file, bytes } of decoded) {
|
||||
const target = join(dir, ...file.path.split('/'));
|
||||
if (!inside(dir, target))
|
||||
throw new Error('skill_path_outside_root: ' + file.path);
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
const tmp = target + '.tmp-' + String(n++);
|
||||
// Unique temp name: concurrent writers to the same skill must never
|
||||
// share a predictable temp file, or one rename can commit the other's bytes.
|
||||
const tmp = `${target}.tmp-${randomUUID()}`;
|
||||
await writeFile(tmp, bytes);
|
||||
await rename(tmp, target);
|
||||
written.push({ path: file.path, sha256: file.sha256, size: bytes.length });
|
||||
}
|
||||
// Remove files the previous delivery owned but the new bundle does not.
|
||||
if (previous?.files !== undefined) {
|
||||
for (const file of previous.files) {
|
||||
if (!keep.has(file.path))
|
||||
await rm(join(dir, ...file.path.split('/')), { force: true });
|
||||
// Receipts are ours, but a tampered one must not delete outside the folder.
|
||||
for (const path of cleanup) {
|
||||
if (typeof path !== 'string' || keep.has(path))
|
||||
continue;
|
||||
if (isCloudSkillPath(path)) {
|
||||
const target = join(dir, ...path.split('/'));
|
||||
if (!inside(dir, target))
|
||||
throw new Error('skill_path_outside_root: ' + path);
|
||||
await rm(target, { force: true });
|
||||
}
|
||||
}
|
||||
const receipt = join(dir, RECEIPT);
|
||||
|
|
@ -136,7 +174,7 @@ export class AdminSkillRepository {
|
|||
return;
|
||||
}
|
||||
const payload = { name, revision: bundle.revision, manifest_sha256: bundle.manifest_sha256, files: written, synced_at: new Date().toISOString() };
|
||||
const tmp = receipt + '.tmp';
|
||||
const tmp = `${receipt}.tmp-${randomUUID()}`;
|
||||
await writeFile(tmp, JSON.stringify(payload, null, 2) + '\n');
|
||||
await rename(tmp, receipt);
|
||||
}
|
||||
|
|
@ -147,7 +185,7 @@ export class AdminSkillRepository {
|
|||
await this.deps.admin.setEnabled(name, true);
|
||||
}
|
||||
async snapshot(name) {
|
||||
const found = await this.deps.admin.locate(name);
|
||||
const found = await this.locate(name);
|
||||
if (found === undefined)
|
||||
return undefined;
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
|
|
|
|||
124
lib/store.js
124
lib/store.js
|
|
@ -60,6 +60,19 @@ export function maskToken(token) {
|
|||
return `${token.slice(0, 3)}…`;
|
||||
return `${token.slice(0, 7)}…${token.slice(-4)}`;
|
||||
}
|
||||
/** Record that one token label was cleared (blocks the env fallback). */
|
||||
function markCleared(state, label) {
|
||||
const labels = new Set(state.clearedTokens ?? []);
|
||||
labels.add(label);
|
||||
state.clearedTokens = [...labels];
|
||||
}
|
||||
/** Drop the cleared marker for one label (a fresh token was written). */
|
||||
function unsetCleared(state, label) {
|
||||
if (state.clearedTokens === undefined)
|
||||
return;
|
||||
const remaining = state.clearedTokens.filter((item) => item !== label);
|
||||
state.clearedTokens = remaining.length > 0 ? remaining : undefined;
|
||||
}
|
||||
/** Validate one sidecar field; returns the normalized value or undefined. */
|
||||
function cleanString(value) {
|
||||
if (typeof value !== 'string')
|
||||
|
|
@ -84,10 +97,29 @@ function parseState(raw) {
|
|||
const state = { version: 1 };
|
||||
if (typeof source.enabled === 'boolean')
|
||||
state.enabled = source.enabled;
|
||||
// The split gates persist too: a saved `false` must survive a reload
|
||||
// instead of silently falling back to the inherited `enabled`.
|
||||
if (typeof source.activityEnabled === 'boolean')
|
||||
state.activityEnabled = source.activityEnabled;
|
||||
if (typeof source.memoryEnabled === 'boolean')
|
||||
state.memoryEnabled = source.memoryEnabled;
|
||||
if (typeof source.skillsSyncEnabled === 'boolean')
|
||||
state.skillsSyncEnabled = source.skillsSyncEnabled;
|
||||
if (typeof source.skillsDir === 'string')
|
||||
state.skillsDir = source.skillsDir;
|
||||
if (typeof source.localMemoryEnabled === 'boolean')
|
||||
state.localMemoryEnabled = source.localMemoryEnabled;
|
||||
if (typeof source.cloudMemoryEnabled === 'boolean')
|
||||
state.cloudMemoryEnabled = source.cloudMemoryEnabled;
|
||||
if (typeof source.autoMemorySpaces === 'boolean')
|
||||
state.autoMemorySpaces = source.autoMemorySpaces;
|
||||
if (typeof source.autoSummaryEnabled === 'boolean')
|
||||
state.autoSummaryEnabled = source.autoSummaryEnabled;
|
||||
if (typeof source.autoProfileEnabled === 'boolean')
|
||||
state.autoProfileEnabled = source.autoProfileEnabled;
|
||||
const localMemoryK = clampInt(source.localMemoryK, 1, 100);
|
||||
if (localMemoryK !== undefined)
|
||||
state.localMemoryK = localMemoryK;
|
||||
const baseUrl = normalizeBaseUrl(source.baseUrl);
|
||||
if (baseUrl !== undefined)
|
||||
state.baseUrl = baseUrl;
|
||||
|
|
@ -114,6 +146,11 @@ function parseState(raw) {
|
|||
const summaryToken = cleanString(source.summaryToken);
|
||||
if (summaryToken !== undefined)
|
||||
state.summaryToken = summaryToken;
|
||||
if (Array.isArray(source.clearedTokens)) {
|
||||
const labels = source.clearedTokens.filter((label) => label === 'activity' || label === 'memory' || label === 'summary');
|
||||
if (labels.length > 0)
|
||||
state.clearedTokens = labels;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
catch {
|
||||
|
|
@ -192,6 +229,18 @@ export class SettingsStore {
|
|||
resolved.skillsSyncEnabled = this.state.skillsSyncEnabled;
|
||||
if (this.state.skillsDir !== undefined)
|
||||
resolved.skillsDir = this.state.skillsDir;
|
||||
if (this.state.localMemoryEnabled !== undefined)
|
||||
resolved.localMemoryEnabled = this.state.localMemoryEnabled;
|
||||
if (this.state.cloudMemoryEnabled !== undefined)
|
||||
resolved.cloudMemoryEnabled = this.state.cloudMemoryEnabled;
|
||||
if (this.state.autoMemorySpaces !== undefined)
|
||||
resolved.autoMemorySpaces = this.state.autoMemorySpaces;
|
||||
if (this.state.autoSummaryEnabled !== undefined)
|
||||
resolved.autoSummaryEnabled = this.state.autoSummaryEnabled;
|
||||
if (this.state.autoProfileEnabled !== undefined)
|
||||
resolved.autoProfileEnabled = this.state.autoProfileEnabled;
|
||||
if (this.state.localMemoryK !== undefined)
|
||||
resolved.localMemoryK = this.state.localMemoryK;
|
||||
// The split gates inherit `enabled` unless the config or the sidecar set
|
||||
// them explicitly, so an old configuration keeps its exact behaviour.
|
||||
if (this.state.activityEnabled === undefined && this.configExplicit.activityEnabled === undefined) {
|
||||
|
|
@ -202,17 +251,46 @@ export class SettingsStore {
|
|||
}
|
||||
return resolved;
|
||||
}
|
||||
/** The activity:write bearer token (sidecar first, env fallback). */
|
||||
/** The activity:write bearer token (sidecar first, origin-bound env fallback). */
|
||||
activityToken() {
|
||||
return this.state.activityToken ?? envToken('DSH_BRAIN_ACTIVITY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_ACTIVITY_TOKEN') ?? '';
|
||||
return this.tokenFor('activity', this.state.activityToken);
|
||||
}
|
||||
/** The memory:read / memory:write bearer token. */
|
||||
memoryToken() {
|
||||
return this.state.memoryToken ?? envToken('DSH_BRAIN_MEMORY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_MEMORY_TOKEN') ?? '';
|
||||
return this.tokenFor('memory', this.state.memoryToken);
|
||||
}
|
||||
/** The summary:write bearer token (optional; absent disables summaries). */
|
||||
summaryToken() {
|
||||
return this.state.summaryToken ?? envToken('DSH_BRAIN_SUMMARY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_SUMMARY_TOKEN') ?? '';
|
||||
return this.tokenFor('summary', this.state.summaryToken);
|
||||
}
|
||||
/**
|
||||
* Env-var tokens are an escape hatch for unattended setups, so they must be
|
||||
* explicit about WHICH service they belong to: `DSH_BRAIN_TOKEN_ORIGIN` (or
|
||||
* the legacy `DSH_CLOUD_MEMORY_TOKEN_ORIGIN`) has to name the origin of the
|
||||
* current baseUrl. A token cleared from the sidecar stays cleared — the
|
||||
* marker blocks the env fallback until a new token is written.
|
||||
*/
|
||||
tokenFor(label, sidecar) {
|
||||
if (sidecar !== undefined && sidecar !== '')
|
||||
return sidecar;
|
||||
if (this.state.clearedTokens?.includes(label) === true)
|
||||
return '';
|
||||
const envPrefix = label === 'activity' ? 'DSH_BRAIN_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_BRAIN_MEMORY_TOKEN' : 'DSH_BRAIN_SUMMARY_TOKEN';
|
||||
const legacyPrefix = label === 'activity' ? 'DSH_CLOUD_MEMORY_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_CLOUD_MEMORY_MEMORY_TOKEN' : 'DSH_CLOUD_MEMORY_SUMMARY_TOKEN';
|
||||
const boundOrigin = envToken('DSH_BRAIN_TOKEN_ORIGIN') ?? envToken('DSH_CLOUD_MEMORY_TOKEN_ORIGIN');
|
||||
if (boundOrigin === undefined)
|
||||
return '';
|
||||
if (boundOrigin !== originOf(this.settings().baseUrl))
|
||||
return '';
|
||||
return envToken(envPrefix) ?? envToken(legacyPrefix) ?? '';
|
||||
}
|
||||
/** Which layer currently supplies each token (drives the card's hint). */
|
||||
tokenSource(label, sidecar) {
|
||||
if (sidecar !== undefined && sidecar !== '')
|
||||
return 'sidecar';
|
||||
if (this.tokenFor(label, sidecar) !== '')
|
||||
return 'env';
|
||||
return 'none';
|
||||
}
|
||||
/** Masked snapshot for the browser card. */
|
||||
describe() {
|
||||
|
|
@ -222,9 +300,9 @@ export class SettingsStore {
|
|||
const summary = this.summaryToken();
|
||||
return {
|
||||
...settings,
|
||||
activityToken: { configured: activity !== '', masked: activity === '' ? '' : maskToken(activity) },
|
||||
memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory) },
|
||||
summaryToken: { configured: summary !== '', masked: summary === '' ? '' : maskToken(summary) },
|
||||
activityToken: { configured: activity !== '', masked: activity === '' ? '' : maskToken(activity), source: this.tokenSource('activity', this.state.activityToken) },
|
||||
memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory), source: this.tokenSource('memory', this.state.memoryToken) },
|
||||
summaryToken: { configured: summary !== '', masked: summary === '' ? '' : maskToken(summary), source: this.tokenSource('summary', this.state.summaryToken) },
|
||||
statePath: this.file,
|
||||
baseUrlConfigured: !isPlaceholderBaseUrl(settings.baseUrl),
|
||||
baseUrlOrigin: originOf(settings.baseUrl),
|
||||
|
|
@ -275,6 +353,7 @@ export class SettingsStore {
|
|||
return { ok: false, error: 'activity token must start with cmt_' };
|
||||
next.activityToken = activityToken;
|
||||
provided.push('activity');
|
||||
unsetCleared(next, 'activity');
|
||||
}
|
||||
const memoryToken = cleanString(patch.memoryToken);
|
||||
if (memoryToken !== undefined) {
|
||||
|
|
@ -282,6 +361,7 @@ export class SettingsStore {
|
|||
return { ok: false, error: 'memory token must start with cmt_' };
|
||||
next.memoryToken = memoryToken;
|
||||
provided.push('memory');
|
||||
unsetCleared(next, 'memory');
|
||||
}
|
||||
if (patch.requestTimeoutMs !== undefined) {
|
||||
const requestTimeoutMs = clampInt(patch.requestTimeoutMs, 1000, 60_000);
|
||||
|
|
@ -319,19 +399,42 @@ export class SettingsStore {
|
|||
return { ok: false, error: 'skillsDir too long' };
|
||||
next.skillsDir = skillsDir;
|
||||
}
|
||||
for (const key of ['localMemoryEnabled', 'cloudMemoryEnabled', 'autoMemorySpaces', 'autoSummaryEnabled', 'autoProfileEnabled']) {
|
||||
if (patch[key] !== undefined) {
|
||||
if (typeof patch[key] !== 'boolean')
|
||||
return { ok: false, error: key + ' must be a boolean' };
|
||||
next[key] = patch[key];
|
||||
}
|
||||
}
|
||||
if (patch.localMemoryK !== undefined) {
|
||||
const localMemoryK = clampInt(patch.localMemoryK, 1, 100);
|
||||
if (localMemoryK === undefined)
|
||||
return { ok: false, error: 'localMemoryK must be a number' };
|
||||
next.localMemoryK = localMemoryK;
|
||||
}
|
||||
const summaryToken = cleanString(patch.summaryToken);
|
||||
if (summaryToken !== undefined) {
|
||||
if (!summaryToken.startsWith('cmt_'))
|
||||
return { ok: false, error: 'summary token must start with cmt_' };
|
||||
next.summaryToken = summaryToken;
|
||||
provided.push('summary');
|
||||
unsetCleared(next, 'summary');
|
||||
}
|
||||
if (patch.clearSummaryToken === true)
|
||||
// Clearing pins a marker: the env fallback must not resurrect a token the
|
||||
// user explicitly removed, and an address switch must not hand the env
|
||||
// token of the old service to the new one either.
|
||||
if (patch.clearSummaryToken === true) {
|
||||
delete next.summaryToken;
|
||||
if (patch.clearActivityToken === true)
|
||||
markCleared(next, 'summary');
|
||||
}
|
||||
if (patch.clearActivityToken === true) {
|
||||
delete next.activityToken;
|
||||
if (patch.clearMemoryToken === true)
|
||||
markCleared(next, 'activity');
|
||||
}
|
||||
if (patch.clearMemoryToken === true) {
|
||||
delete next.memoryToken;
|
||||
markCleared(next, 'memory');
|
||||
}
|
||||
// Switching the service origin must not hand the previous service's
|
||||
// bearer tokens to the new one: everything this request did not explicitly
|
||||
// replace is dropped, and the caller is told so it can ask to re-authenticate.
|
||||
|
|
@ -349,6 +452,7 @@ export class SettingsStore {
|
|||
if (provided.includes(label))
|
||||
continue;
|
||||
delete next[key];
|
||||
markCleared(next, label);
|
||||
clearedTokens.push(label);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
/**
|
||||
* Single source of truth for the package version.
|
||||
*
|
||||
* The compiled file lives in `lib/`, so `../package.json` resolves to this
|
||||
* package's manifest both in the repo and inside node_modules. Every surface
|
||||
* that reports a version (status card, capabilities, Mnemon manifest) reads it
|
||||
* from here, so a release bump is one edit in package.json.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const FALLBACK_VERSION = '0.10.1';
|
||||
function readVersion() {
|
||||
try {
|
||||
const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'));
|
||||
if (typeof manifest.version === 'string' && manifest.version !== '')
|
||||
return manifest.version;
|
||||
}
|
||||
catch {
|
||||
// A missing or broken manifest must not take the plugin down.
|
||||
}
|
||||
return FALLBACK_VERSION;
|
||||
}
|
||||
/** Version reported by the status card, capabilities and the Mnemon manifest. */
|
||||
export const VERSION = readVersion();
|
||||
19
package.json
19
package.json
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-brain",
|
||||
"version": "0.9.11",
|
||||
"version": "0.10.1",
|
||||
"description": "Cloud memory for DSH: report one activity turn per conversation round and expose memory_search / memory_read / memory_add tools against a LongMemory cloud endpoint.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
|
@ -15,7 +15,9 @@
|
|||
"./settings-ui": "./lib/entries/settings-ui.js",
|
||||
"./cordis.patch.yml": "./cordis.patch.yml",
|
||||
"./package.json": "./package.json",
|
||||
"./mnemon-provider": "./lib/mnemon/index.js"
|
||||
"./mnemon-provider": "./lib/mnemon/index.js",
|
||||
"./local-memory": "./lib/local-memory/index.js",
|
||||
"./mnemon-native-provider": "./lib/mnemon/native.js"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
|
|
@ -37,21 +39,19 @@
|
|||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"verify": "node scripts/verify-all.mjs",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"prepack": "tsc -p tsconfig.build.json",
|
||||
"prepublishOnly": "node scripts/pack-guard.mjs"
|
||||
"prepublishOnly": "node scripts/pack-guard.mjs",
|
||||
"test": "node scripts/verify-all.mjs"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.2",
|
||||
"react": "^18.2.0",
|
||||
"dsh-mnemon-source-memory-spaces": "^0.5.1"
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"dsh-mnemon-source-memory-spaces": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
@ -67,8 +67,7 @@
|
|||
"@types/react": "~18.3.1",
|
||||
"react": "^18.2.0",
|
||||
"tsdown": "^0.22.2",
|
||||
"typescript": "^5.6.0",
|
||||
"dsh-mnemon-source-memory-spaces": "^0.5.11"
|
||||
"typescript": "^5.6.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
|
|
|
|||
|
|
@ -38,9 +38,6 @@ importers:
|
|||
'@types/react':
|
||||
specifier: ~18.3.1
|
||||
version: 18.3.31
|
||||
dsh-mnemon-source-memory-spaces:
|
||||
specifier: ^0.5.11
|
||||
version: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
|
||||
react:
|
||||
specifier: ^18.2.0
|
||||
version: 18.3.1
|
||||
|
|
|
|||
|
|
@ -0,0 +1,198 @@
|
|||
#!/usr/bin/env node
|
||||
/**
|
||||
* Materialize the independent dsh-brain Mnemon fork.
|
||||
*
|
||||
* The snapshot is omdsh-dev/dsh-mnemon with every package, import specifier,
|
||||
* runtime schema id and bundle entry id renamed from dsh-mnemon to
|
||||
* dsh-brain-mnemon. The MIT license and upstream provenance stay in the tree.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/fork-mnemon.mjs --source <upstream-checkout> [--target vendor/dsh-mnemon] [--force]
|
||||
* node scripts/fork-mnemon.mjs --check [--target vendor/dsh-mnemon]
|
||||
*/
|
||||
import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join, relative, resolve, sep } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const DEFAULT_TARGET = join(ROOT, 'vendor', 'dsh-mnemon')
|
||||
const UPSTREAM_REPOSITORY = 'https://github.com/omdsh-dev/dsh-mnemon.git'
|
||||
const PINNED_REVISION = '8b650ab5ef33522e03887b250b13336593daa26f'
|
||||
const PINNED_VERSION = '0.5.54'
|
||||
const FORK_NAME = 'dsh-brain-mnemon'
|
||||
const FORK_VERSION = PINNED_VERSION + '-dsh.1'
|
||||
const FORK_DISPLAY_NAME = 'Dsh Brain Mnemon'
|
||||
|
||||
const REWRITE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs', '.cjs', '.json', '.jsonc', '.yml', '.yaml', '.css', '.scss', '.html', '.toml', '.sh', '.ps1', '.patch', '.snapshot'])
|
||||
const SKIP_DIRS = new Set(['.git', 'node_modules', 'dist', 'coverage'])
|
||||
const SKIP_PREFIXES = ['LICENSE', 'THIRD_PARTY_NOTICES', 'CHANGELOG', 'README', 'CONTRIBUTING', 'SECURITY', 'ISSUE_TRIAGE', 'docs/', 'assets/', 'examples/']
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = { target: DEFAULT_TARGET, force: false, check: false, source: '' }
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const token = argv[i]
|
||||
if (token === '--force') args.force = true
|
||||
else if (token === '--check') args.check = true
|
||||
else if (token === '--source') args.source = resolve(argv[++i] || '')
|
||||
else if (token === '--target') args.target = resolve(argv[++i] || '')
|
||||
else if (token === '--help' || token === '-h') args.help = true
|
||||
else throw new Error('Unknown argument: ' + token)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
function assertSafeTarget(target) {
|
||||
const vendorRoot = join(ROOT, 'vendor')
|
||||
if (resolve(target) !== DEFAULT_TARGET) throw new Error('Refusing to write outside the canonical vendor/dsh-mnemon target')
|
||||
}
|
||||
|
||||
async function walk(dir, files = []) {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
if (entry.isSymbolicLink()) continue
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) { if (!SKIP_DIRS.has(entry.name)) await walk(full, files) }
|
||||
else if (entry.isFile()) files.push(full)
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
function isTextFile(file) {
|
||||
const ext = file.slice(file.lastIndexOf('.')).toLowerCase()
|
||||
return REWRITE_EXTENSIONS.has(ext) || !file.includes('.')
|
||||
}
|
||||
|
||||
function shouldRewrite(file, target) {
|
||||
const rel = relative(target, file).split(sep).join('/')
|
||||
if (SKIP_PREFIXES.some(prefix => rel === prefix.replace(/\/$/, '') || rel.startsWith(prefix))) return false
|
||||
return isTextFile(file)
|
||||
}
|
||||
|
||||
async function rewriteTree(target) {
|
||||
let rewritten = 0
|
||||
for (const file of await walk(target)) {
|
||||
if (!shouldRewrite(file, target)) continue
|
||||
const before = await readFile(file, 'utf8')
|
||||
if (!before.includes('dsh-mnemon') && !before.includes('id: mnemon')) continue
|
||||
let after = before.replaceAll('dsh-mnemon', FORK_NAME)
|
||||
after = after.replace(/id: mnemon-bundle\b/g, 'id: ' + FORK_NAME + '-bundle')
|
||||
after = after.replace(/id: mnemon\b/g, 'id: ' + FORK_NAME)
|
||||
after = after.replace(/id: mnemon-/g, 'id: ' + FORK_NAME + '-')
|
||||
if (after !== before) { await writeFile(file, after, 'utf8'); rewritten += 1 }
|
||||
}
|
||||
return rewritten
|
||||
}
|
||||
|
||||
async function restoreUpstreamUrls(target) {
|
||||
let restored = 0
|
||||
for (const file of await walk(target)) {
|
||||
if (!shouldRewrite(file, target)) continue
|
||||
const before = await readFile(file, 'utf8')
|
||||
const after = before.replaceAll('https://github.com/omdsh-dev/dsh-brain-mnemon', 'https://github.com/omdsh-dev/dsh-mnemon')
|
||||
if (after !== before) { await writeFile(file, after, 'utf8'); restored += 1 }
|
||||
}
|
||||
return restored
|
||||
}
|
||||
|
||||
async function renamePluginDirs(target) {
|
||||
const pluginRoot = join(target, 'plugins')
|
||||
let renamed = 0
|
||||
for (const entry of await readdir(pluginRoot, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.startsWith('dsh-mnemon-')) continue
|
||||
await rename(join(pluginRoot, entry.name), join(pluginRoot, entry.name.replace(/^dsh-mnemon-/, FORK_NAME + '-')))
|
||||
renamed += 1
|
||||
}
|
||||
return renamed
|
||||
}
|
||||
|
||||
async function finalizeRootPackage(target) {
|
||||
const packagePath = join(target, 'package.json')
|
||||
const pkg = JSON.parse(await readFile(packagePath, 'utf8'))
|
||||
pkg.name = FORK_NAME
|
||||
pkg.version = FORK_VERSION
|
||||
pkg.private = true
|
||||
pkg.description = FORK_DISPLAY_NAME + ': independent dsh-brain fork of dsh-mnemon. Composable, view-based context for DeepSeek Harness with pluggable memory sources, strategies and skills.'
|
||||
if (pkg.publishConfig) delete pkg.publishConfig
|
||||
pkg.repository = { type: 'git', url: UPSTREAM_REPOSITORY }
|
||||
pkg.homepage = UPSTREAM_REPOSITORY.replace(/\.git$/, '') + '#readme'
|
||||
pkg.bugs = { url: UPSTREAM_REPOSITORY.replace(/\.git$/, '') + '/issues' }
|
||||
pkg.dshBrainFork = { displayName: FORK_DISPLAY_NAME, upstream: UPSTREAM_REPOSITORY, upstreamRevision: PINNED_REVISION, upstreamVersion: PINNED_VERSION, license: 'MIT', note: 'Keep upstream URLs and MIT notices when syncing.' }
|
||||
if (pkg.bin && typeof pkg.bin === 'object') {
|
||||
pkg.bin = Object.fromEntries(Object.entries(pkg.bin).map(([name, value]) => [name.replace(/^dsh-mnemon/, FORK_NAME), value]))
|
||||
}
|
||||
await writeFile(packagePath, JSON.stringify(pkg, null, 2) + '\n', 'utf8')
|
||||
}
|
||||
|
||||
async function writeForkNotice(target) {
|
||||
const notice = [
|
||||
'# dsh-brain Mnemon fork',
|
||||
'',
|
||||
'- Display name: ' + FORK_DISPLAY_NAME,
|
||||
'- Fork package name: ' + FORK_NAME,
|
||||
'- Fork version: ' + FORK_VERSION,
|
||||
'- Upstream: ' + UPSTREAM_REPOSITORY,
|
||||
'- Upstream revision: ' + PINNED_REVISION,
|
||||
'- Upstream version: ' + PINNED_VERSION,
|
||||
'- License: MIT (see LICENSE)',
|
||||
'',
|
||||
'This directory is a source snapshot, not a git submodule. The tree keeps the upstream',
|
||||
'MIT license, copyright notice and third-party notices. Package names, import',
|
||||
'specifiers, runtime schema ids, bundle entry ids and the repair-session bin name',
|
||||
'are rewritten from dsh-mnemon to ' + FORK_NAME + ' so the fork can coexist with',
|
||||
'the upstream plugin without registering the same package or entry ids.',
|
||||
'',
|
||||
'Regenerate with:',
|
||||
'',
|
||||
' node scripts/fork-mnemon.mjs --source <upstream-checkout> --target vendor/dsh-mnemon --force',
|
||||
'',
|
||||
'Update procedure: check out the desired upstream revision, run the command above,',
|
||||
'then bump PINNED_REVISION / PINNED_VERSION in scripts/fork-mnemon.mjs.',
|
||||
'Review the diff before committing; do not rewrite upstream docs or license files.',
|
||||
'',
|
||||
].join('\n')
|
||||
await writeFile(join(target, 'FORK_NOTICE.md'), notice, 'utf8')
|
||||
}
|
||||
|
||||
async function verify(target) {
|
||||
const pkg = JSON.parse(await readFile(join(target, 'package.json'), 'utf8'))
|
||||
if (pkg.name !== FORK_NAME) throw new Error('package.name is ' + pkg.name + ', expected ' + FORK_NAME)
|
||||
if (!pkg.private) throw new Error('fork package must stay private')
|
||||
if (!pkg.dshBrainFork || pkg.dshBrainFork.upstreamRevision !== PINNED_REVISION) throw new Error('missing fork provenance metadata')
|
||||
const entry = await readFile(join(target, 'cordis.patch.yml'), 'utf8')
|
||||
if (!entry.includes('name: ' + FORK_NAME + '/bundle')) throw new Error('bundle entry was not renamed')
|
||||
if (!entry.includes('id: ' + FORK_NAME + '-bundle')) throw new Error('bundle entry id was not renamed')
|
||||
let forbidden = 0
|
||||
for (const file of await walk(target)) {
|
||||
if (!shouldRewrite(file, target) || relative(target, file) === 'package.json') continue
|
||||
const body = await readFile(file, 'utf8')
|
||||
const sanitized = body.replaceAll('https://github.com/omdsh-dev/dsh-mnemon', '')
|
||||
if (sanitized.includes('dsh-mnemon') || /id: mnemon\b/.test(sanitized)) { forbidden += 1; console.error('unrenamed upstream identifier: ' + relative(ROOT, file)) }
|
||||
}
|
||||
if (forbidden > 0) throw new Error(forbidden + ' rewritten-eligible files still mention dsh-mnemon')
|
||||
for (const entry of await readdir(join(target, 'plugins'), { withFileTypes: true })) {
|
||||
if (entry.isDirectory() && !entry.name.startsWith(FORK_NAME + '-')) throw new Error('plugin directory not renamed: ' + entry.name)
|
||||
}
|
||||
return { target: relative(ROOT, target), name: pkg.name, version: pkg.version, private: pkg.private, revision: PINNED_REVISION }
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2))
|
||||
if (args.help) { console.log('Usage: node scripts/fork-mnemon.mjs --source <upstream-checkout> [--target vendor/dsh-mnemon] [--force]'); return }
|
||||
assertSafeTarget(args.target)
|
||||
if (args.check) { console.log(JSON.stringify(await verify(args.target), null, 2)); return }
|
||||
if (!args.source) throw new Error('--source is required when materializing a fork (or use --check)')
|
||||
const sourcePackage = JSON.parse(await readFile(join(args.source, 'package.json'), 'utf8'))
|
||||
if (sourcePackage.name !== 'dsh-mnemon') throw new Error('source package name is ' + sourcePackage.name + ', expected dsh-mnemon')
|
||||
if (sourcePackage.version !== PINNED_VERSION) throw new Error('source version is ' + sourcePackage.version + ', expected ' + PINNED_VERSION)
|
||||
try { await stat(args.target); if (!args.force) throw new Error('target exists; pass --force to replace it'); await rm(args.target, { recursive: true, force: true }) }
|
||||
catch (error) { if (error.code !== 'ENOENT') throw error }
|
||||
await mkdir(args.target, { recursive: true })
|
||||
await cp(args.source, args.target, { recursive: true, filter: src => !src.includes(sep + '.git' + sep) && !src.endsWith(sep + '.git') && !src.includes(sep + 'node_modules' + sep) })
|
||||
const rewritten = await rewriteTree(args.target)
|
||||
const restoredUrls = await restoreUpstreamUrls(args.target)
|
||||
const renamedDirs = await renamePluginDirs(args.target)
|
||||
await finalizeRootPackage(args.target)
|
||||
await writeForkNotice(args.target)
|
||||
console.log(JSON.stringify({ ...(await verify(args.target)), rewrittenFiles: rewritten, restoredUpstreamUrls: restoredUrls, renamedPluginDirs: renamedDirs }, null, 2))
|
||||
}
|
||||
|
||||
main().catch(error => { console.error('fork-mnemon: ' + error.message); process.exitCode = 1 })
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
// Runs every root verify-*.mjs in a child process and reports a summary.
|
||||
// Exit code is non-zero if any script fails. Scripts that skip (environmental
|
||||
// limitations) count as pass with a note.
|
||||
import { readdirSync } from 'node:fs'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { join, dirname } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||
const node = process.execPath
|
||||
|
||||
const includeRealHost = process.env.DSH_VERIFY_REAL_MCP === '1'
|
||||
const names = readdirSync(root)
|
||||
.filter((f) => /^verify-.*\.mjs$/.test(f) && (includeRealHost || f !== 'verify-mcp-bridge.mjs'))
|
||||
.sort()
|
||||
|
||||
const results = []
|
||||
for (const name of names) {
|
||||
const started = Date.now()
|
||||
const r = spawnSync(node, [join(root, name)], {
|
||||
cwd: root,
|
||||
encoding: 'utf8',
|
||||
timeout: 5 * 60_000,
|
||||
})
|
||||
const code = r.status === null ? 1 : r.status
|
||||
const out = (r.stdout || '') + (r.stderr || '')
|
||||
const tail = out.trimEnd().split('\n').filter(Boolean).slice(-3).join(' | ')
|
||||
const skipped = out.split('\n').some((line) => /^SKIP(?:\s|:|$)/.test(line.trim()))
|
||||
results.push({ name, code, ms: Date.now() - started, skipped, tail })
|
||||
const flag = code === 0 ? (skipped ? 'PASS*' : 'PASS') : 'FAIL'
|
||||
console.log(`${flag.padEnd(5)} ${name} (${(results[results.length - 1].ms / 1000).toFixed(1)}s)`)
|
||||
if (code !== 0) console.log(' ' + tail.slice(0, 500))
|
||||
}
|
||||
|
||||
const failed = results.filter((r) => r.code !== 0)
|
||||
const skippedCount = results.filter((r) => r.skipped).length
|
||||
console.log(
|
||||
`\n${results.length} scripts: ${results.length - failed.length} passed` +
|
||||
(skippedCount ? ` (${skippedCount} with environmental skips)` : '') +
|
||||
(failed.length ? `, ${failed.length} FAILED: ${failed.map((f) => f.name).join(', ')}` : ', all green'),
|
||||
)
|
||||
if (failed.length) {
|
||||
console.log('Last output of each failure:')
|
||||
for (const f of failed) console.log(' ' + f.name + ': ' + f.tail.slice(0, 300))
|
||||
process.exit(1)
|
||||
}
|
||||
356
src/api.ts
356
src/api.ts
|
|
@ -236,6 +236,230 @@ export interface CloudClientOptions {
|
|||
timeoutMs: () => number
|
||||
}
|
||||
|
||||
/**
|
||||
* Optional frozen connection target for a multi-step auth flow.
|
||||
*
|
||||
* Login and minting happen in separate calls; without an override each call
|
||||
* re-reads the live settings, so a settings edit between them would send the
|
||||
* password and the session cookie to different services. Passing one target
|
||||
* keeps the whole flow pinned to the connection snapshotted at its start.
|
||||
*/
|
||||
export interface CloudAuthTarget {
|
||||
/** Base URL for this auth call (defaults to the client's live setting). */
|
||||
baseUrl?: string
|
||||
/** Timeout for this auth call (defaults to the client's live setting). */
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime response-shape guards.
|
||||
*
|
||||
* A 2xx with syntactically valid JSON but the wrong shape is still a failed
|
||||
* call: without these checks `null` becomes `data: null` and every downstream
|
||||
* `data.items ?? []` silently turns a contract violation into "empty". The
|
||||
* helpers throw; request() normalizes the throw to `invalid_response`.
|
||||
*/
|
||||
function requireResponseObject(value: unknown, what: string): Record<string, unknown> {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error(`${what} must be a JSON object`)
|
||||
}
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
|
||||
function requireResponseArray(body: Record<string, unknown>, key: string): unknown[] {
|
||||
const value = body[key]
|
||||
if (!Array.isArray(value)) throw new Error(`${key} must be an array`)
|
||||
return value
|
||||
}
|
||||
|
||||
function requireResponseString(body: Record<string, unknown>, key: string, allowEmpty = false): string {
|
||||
const value = body[key]
|
||||
if (typeof value !== 'string' || (!allowEmpty && value === '')) {
|
||||
throw new Error(`${key} must be a non-empty string`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function optionalResponseString(body: Record<string, unknown>, key: string): void {
|
||||
const value = body[key]
|
||||
if (value !== undefined && typeof value !== 'string') throw new Error(`${key} must be a string`)
|
||||
}
|
||||
|
||||
function optionalNullableString(body: Record<string, unknown>, key: string): void {
|
||||
const value = body[key]
|
||||
if (value !== undefined && value !== null && typeof value !== 'string') {
|
||||
throw new Error(`${key} must be a string or null`)
|
||||
}
|
||||
}
|
||||
|
||||
function optionalResponseNumber(body: Record<string, unknown>, key: string): void {
|
||||
const value = body[key]
|
||||
if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value))) {
|
||||
throw new Error(`${key} must be a number`)
|
||||
}
|
||||
}
|
||||
|
||||
function optionalResponseBoolean(body: Record<string, unknown>, key: string): void {
|
||||
const value = body[key]
|
||||
if (value !== undefined && typeof value !== 'boolean') throw new Error(`${key} must be a boolean`)
|
||||
}
|
||||
|
||||
function optionalResponseStringArray(body: Record<string, unknown>, key: string): void {
|
||||
const value = body[key]
|
||||
if (value === undefined) return
|
||||
if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
|
||||
throw new Error(`${key} must be an array of strings`)
|
||||
}
|
||||
}
|
||||
|
||||
function optionalStringOrNumber(body: Record<string, unknown>, key: string): void {
|
||||
const value = body[key]
|
||||
if (value !== undefined && typeof value !== 'string' && typeof value !== 'number') {
|
||||
throw new Error(`${key} must be a string or number`)
|
||||
}
|
||||
}
|
||||
|
||||
function validateTurnAck(value: unknown): TurnAck {
|
||||
const body = requireResponseObject(value, 'activity turn response')
|
||||
optionalResponseBoolean(body, 'recorded')
|
||||
optionalResponseBoolean(body, 'duplicate')
|
||||
return body as unknown as TurnAck
|
||||
}
|
||||
|
||||
function validateSummaryAck(value: unknown): SummaryAck {
|
||||
const body = requireResponseObject(value, 'activity summary response')
|
||||
optionalResponseNumber(body, 'staged')
|
||||
optionalResponseNumber(body, 'skipped')
|
||||
optionalResponseBoolean(body, 'full')
|
||||
return body as unknown as SummaryAck
|
||||
}
|
||||
|
||||
function validateMemoryHitItem(value: unknown, what: string): MemoryHit {
|
||||
const body = requireResponseObject(value, what)
|
||||
optionalResponseString(body, 'id')
|
||||
optionalResponseString(body, 'content')
|
||||
optionalResponseStringArray(body, 'tags')
|
||||
optionalResponseString(body, 'primary_sector')
|
||||
if (body.project_id !== undefined && body.project_id !== null && typeof body.project_id !== 'string') {
|
||||
throw new Error(`${what}.project_id must be a string or null`)
|
||||
}
|
||||
optionalResponseNumber(body, 'revision')
|
||||
optionalResponseNumber(body, 'created_at')
|
||||
optionalResponseNumber(body, 'updated_at')
|
||||
return body as unknown as MemoryHit
|
||||
}
|
||||
|
||||
function validateMemoryRead(value: unknown): MemoryHit {
|
||||
const body = requireResponseObject(value, 'memory response')
|
||||
requireResponseString(body, 'id')
|
||||
return validateMemoryHitItem(body, 'memory response')
|
||||
}
|
||||
|
||||
function validateSearchResponse(value: unknown): SearchResponse {
|
||||
const body = requireResponseObject(value, 'memory search response')
|
||||
const matches = requireResponseArray(body, 'matches')
|
||||
matches.forEach((entry, index) => validateMemoryHitItem(entry, `matches[${index}]`))
|
||||
optionalResponseNumber(body, 'total')
|
||||
optionalResponseString(body, 'search_mode')
|
||||
return body as unknown as SearchResponse
|
||||
}
|
||||
|
||||
function validateListResponse(value: unknown): ListResponse {
|
||||
const body = requireResponseObject(value, 'memory list response')
|
||||
const items = requireResponseArray(body, 'items')
|
||||
items.forEach((entry, index) => validateMemoryHitItem(entry, `items[${index}]`))
|
||||
optionalResponseNumber(body, 'total')
|
||||
return body as unknown as ListResponse
|
||||
}
|
||||
|
||||
function validateProjectsResponse(value: unknown): ProjectsResponse {
|
||||
const body = requireResponseObject(value, 'projects response')
|
||||
const projects = requireResponseArray(body, 'projects')
|
||||
projects.forEach((entry, index) => {
|
||||
const project = requireResponseObject(entry, `projects[${index}]`)
|
||||
optionalResponseString(project, 'id')
|
||||
optionalResponseString(project, 'name')
|
||||
})
|
||||
return body as unknown as ProjectsResponse
|
||||
}
|
||||
|
||||
function validateAddResponse(value: unknown): AddResponse {
|
||||
const body = requireResponseObject(value, 'memory add response')
|
||||
optionalResponseString(body, 'id')
|
||||
optionalResponseNumber(body, 'revision')
|
||||
optionalResponseBoolean(body, 'deleted')
|
||||
optionalResponseString(body, 'state')
|
||||
optionalResponseBoolean(body, 'remote_saved')
|
||||
if (body.memory !== undefined && body.memory !== null) {
|
||||
validateMemoryHitItem(body.memory, 'memory')
|
||||
}
|
||||
return body as unknown as AddResponse
|
||||
}
|
||||
|
||||
function validateStorageStatus(value: unknown): Record<string, unknown> {
|
||||
return requireResponseObject(value, 'storage status response')
|
||||
}
|
||||
|
||||
function validateSkillSummary(value: unknown, what: string): SkillSummary {
|
||||
const body = requireResponseObject(value, what)
|
||||
requireResponseString(body, 'name')
|
||||
optionalResponseString(body, 'description')
|
||||
optionalNullableString(body, 'category')
|
||||
optionalResponseString(body, 'execution_mode')
|
||||
optionalResponseBoolean(body, 'enabled')
|
||||
optionalResponseNumber(body, 'revision')
|
||||
optionalResponseString(body, 'manifest_sha256')
|
||||
optionalResponseNumber(body, 'files')
|
||||
optionalResponseNumber(body, 'bytes')
|
||||
optionalResponseBoolean(body, 'script_changed')
|
||||
optionalStringOrNumber(body, 'created_at')
|
||||
optionalStringOrNumber(body, 'updated_at')
|
||||
return body as unknown as SkillSummary
|
||||
}
|
||||
|
||||
function validateSkillListing(value: unknown): SkillListing {
|
||||
const body = requireResponseObject(value, 'skills response')
|
||||
const items = requireResponseArray(body, 'items')
|
||||
items.forEach((entry, index) => validateSkillSummary(entry, `items[${index}]`))
|
||||
optionalResponseNumber(body, 'total')
|
||||
optionalResponseNumber(body, 'trash_total')
|
||||
return body as unknown as SkillListing
|
||||
}
|
||||
|
||||
function validateSkillBundle(value: unknown): SkillBundle {
|
||||
const body = requireResponseObject(value, 'skill bundle response')
|
||||
requireResponseString(body, 'name')
|
||||
optionalResponseNumber(body, 'revision')
|
||||
if (typeof body.revision !== 'number' || !Number.isFinite(body.revision)) {
|
||||
throw new Error('revision must be a number')
|
||||
}
|
||||
requireResponseString(body, 'manifest_sha256')
|
||||
optionalResponseBoolean(body, 'script_changed')
|
||||
optionalResponseStringArray(body, 'script_changes')
|
||||
const files = requireResponseArray(body, 'files')
|
||||
files.forEach((entry, index) => {
|
||||
const file = requireResponseObject(entry, `files[${index}]`)
|
||||
requireResponseString(file, 'path')
|
||||
requireResponseString(file, 'sha256')
|
||||
requireResponseString(file, 'data', true)
|
||||
optionalResponseNumber(file, 'size')
|
||||
optionalResponseString(file, 'encoding')
|
||||
})
|
||||
return body as unknown as SkillBundle
|
||||
}
|
||||
|
||||
function validateSkillWriteResult(value: unknown): SkillWriteResult {
|
||||
const body = requireResponseObject(value, 'skill write response')
|
||||
if (body.skill !== undefined && body.skill !== null) {
|
||||
validateSkillSummary(body.skill, 'skill')
|
||||
}
|
||||
optionalResponseNumber(body, 'revision')
|
||||
optionalResponseString(body, 'manifest_sha256')
|
||||
return body as unknown as SkillWriteResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** Map one HTTP error body onto a {@link CloudError}. */
|
||||
function errorFromBody(status: number, raw: string, retryAfterHeader: string | null): CloudError {
|
||||
let code = `http_${status}`
|
||||
|
|
@ -270,7 +494,13 @@ function errorFromBody(status: number, raw: string, retryAfterHeader: string | n
|
|||
export class CloudClient {
|
||||
constructor(private readonly options: CloudClientOptions) {}
|
||||
|
||||
private async request<T>(method: string, path: string, body?: unknown, tokenOverride?: string): Promise<CloudResult<T>> {
|
||||
private async request<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
tokenOverride?: string,
|
||||
validate?: (value: unknown) => T,
|
||||
): Promise<CloudResult<T>> {
|
||||
const token = tokenOverride ?? this.options.token()
|
||||
const base = this.options.baseUrl()
|
||||
const url = `${base}${path}`
|
||||
|
|
@ -288,21 +518,49 @@ export class CloudClient {
|
|||
const reason = error instanceof Error ? error.message : String(error)
|
||||
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} ${path}: ${reason}` } }
|
||||
}
|
||||
const text = await response.text().catch(() => '')
|
||||
// A failed body read (connection torn mid-response) is NOT an empty
|
||||
// success: a 200 whose payload cannot be read must surface as an error,
|
||||
// not as `{ ok: true, data: {} }`.
|
||||
let text: string
|
||||
try {
|
||||
text = await response.text()
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: errorFromBody(response.status, `body read failed: ${reason}`, response.headers.get('retry-after')) }
|
||||
}
|
||||
return { ok: false, error: { status: response.status, code: 'body_read_error', message: `${method} ${path}: body read failed: ${reason}` } }
|
||||
}
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) }
|
||||
}
|
||||
if (text.trim() === '') return { ok: true, status: response.status, data: {} as T }
|
||||
try {
|
||||
return { ok: true, status: response.status, data: JSON.parse(text) as T }
|
||||
} catch {
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: 'response was not JSON' } }
|
||||
// Empty bodies are endpoint-specific: the validator decides whether `{}`
|
||||
// is an acceptable 2xx payload (add/turn acknowledgements) or a missing
|
||||
// required field (list/search/projects/skills/bundle). Probes pass no
|
||||
// validator on purpose: any 2xx already proves the credential, and a 400
|
||||
// remains their "authenticated but bad body" signal.
|
||||
let parsed: unknown = {}
|
||||
if (text.trim() !== '') {
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: `${method} ${path}: response was not JSON` } }
|
||||
}
|
||||
}
|
||||
if (validate !== undefined) {
|
||||
try {
|
||||
validate(parsed)
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_response', message: `${method} ${path}: ${reason}` } }
|
||||
}
|
||||
}
|
||||
return { ok: true, status: response.status, data: parsed as T }
|
||||
}
|
||||
|
||||
/** Report one conversation turn (activity:write token). */
|
||||
reportTurn(payload: TurnPayload, token: string): Promise<CloudResult<TurnAck>> {
|
||||
return this.request<TurnAck>('POST', '/activity/turn', payload, token)
|
||||
return this.request<TurnAck>('POST', '/activity/turn', payload, token, validateTurnAck)
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -326,7 +584,7 @@ export class CloudClient {
|
|||
|
||||
/** Stage one turn summary as pending proposals (summary:write token). */
|
||||
submitSummary(payload: SummaryPayload, token: string): Promise<CloudResult<SummaryAck>> {
|
||||
return this.request<SummaryAck>('POST', '/activity/summary', payload, token)
|
||||
return this.request<SummaryAck>('POST', '/activity/summary', payload, token, validateSummaryAck)
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -363,12 +621,12 @@ export class CloudClient {
|
|||
async search(query: string, k: number, project?: string): Promise<CloudResult<SearchResponse>> {
|
||||
const body: Record<string, unknown> = { query, k }
|
||||
if (project !== undefined && project !== '') body.filters = { project_id: project }
|
||||
return this.request<SearchResponse>('POST', '/memory/query', body)
|
||||
return this.request<SearchResponse>('POST', '/memory/query', body, undefined, validateSearchResponse)
|
||||
}
|
||||
|
||||
/** Read one memory by id (memory token). */
|
||||
read(id: string): Promise<CloudResult<MemoryHit>> {
|
||||
return this.request<MemoryHit>('GET', `/memory/${encodeURIComponent(id)}`)
|
||||
return this.request<MemoryHit>('GET', `/memory/${encodeURIComponent(id)}`, undefined, undefined, validateMemoryRead)
|
||||
}
|
||||
|
||||
/** List memories with optional paging filters (memory token). */
|
||||
|
|
@ -378,7 +636,7 @@ export class CloudClient {
|
|||
if (options.offset !== undefined) params.set('offset', String(options.offset))
|
||||
if (options.project !== undefined && options.project !== '') params.set('project_id', options.project)
|
||||
const suffix = params.toString() === '' ? '' : `?${params.toString()}`
|
||||
return this.request<ListResponse>('GET', `/memory/all${suffix}`)
|
||||
return this.request<ListResponse>('GET', `/memory/all${suffix}`, undefined, undefined, validateListResponse)
|
||||
}
|
||||
|
||||
/** Store one memory; `operationId` makes the write idempotent (memory token). */
|
||||
|
|
@ -390,37 +648,37 @@ export class CloudClient {
|
|||
if (input.tags !== undefined && input.tags.length > 0) body.tags = input.tags
|
||||
if (input.project !== undefined && input.project !== '') body.project_id = input.project
|
||||
if (input.sector !== undefined && input.sector !== '') body.metadata = { primary_sector: input.sector }
|
||||
return this.request<AddResponse>('POST', '/memory/add', body)
|
||||
return this.request<AddResponse>('POST', '/memory/add', body, undefined, validateAddResponse)
|
||||
}
|
||||
|
||||
/** List the account's projects (memory token). */
|
||||
projects(): Promise<CloudResult<ProjectsResponse>> {
|
||||
return this.request<ProjectsResponse>('GET', '/dashboard/projects')
|
||||
return this.request<ProjectsResponse>('GET', '/dashboard/projects', undefined, undefined, validateProjectsResponse)
|
||||
}
|
||||
|
||||
/** Storage configuration state (memory token). */
|
||||
storageStatus(): Promise<CloudResult<Record<string, unknown>>> {
|
||||
return this.request<Record<string, unknown>>('GET', '/storage/status')
|
||||
return this.request<Record<string, unknown>>('GET', '/storage/status', undefined, undefined, validateStorageStatus)
|
||||
}
|
||||
|
||||
/** List the cloud skill center inventory (memory token). */
|
||||
listSkills(): Promise<CloudResult<SkillListing>> {
|
||||
return this.request<SkillListing>('GET', '/skills')
|
||||
return this.request<SkillListing>('GET', '/skills', undefined, undefined, validateSkillListing)
|
||||
}
|
||||
|
||||
/** Fetch one skill bundle with hashed, base64-carried files (memory token). */
|
||||
skillBundle(name: string): Promise<CloudResult<SkillBundle>> {
|
||||
return this.request<SkillBundle>('GET', `/skills/${encodeURIComponent(name)}/bundle`)
|
||||
return this.request<SkillBundle>('GET', `/skills/${encodeURIComponent(name)}/bundle`, undefined, undefined, validateSkillBundle)
|
||||
}
|
||||
|
||||
/** Create one skill in the center; `expected_revision` must be 0 (memory token). */
|
||||
createSkill(body: Record<string, unknown>): Promise<CloudResult<SkillWriteResult>> {
|
||||
return this.request<SkillWriteResult>('POST', '/skills', body)
|
||||
return this.request<SkillWriteResult>('POST', '/skills', body, undefined, validateSkillWriteResult)
|
||||
}
|
||||
|
||||
/** Replace one skill's files/description at an expected revision (memory token). */
|
||||
updateSkill(name: string, body: Record<string, unknown>): Promise<CloudResult<SkillWriteResult>> {
|
||||
return this.request<SkillWriteResult>('PATCH', `/skills/${encodeURIComponent(name)}`, body)
|
||||
return this.request<SkillWriteResult>('PATCH', `/skills/${encodeURIComponent(name)}`, body, undefined, validateSkillWriteResult)
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -436,8 +694,13 @@ export class CloudClient {
|
|||
path: string,
|
||||
body?: unknown,
|
||||
cookie?: string,
|
||||
target?: CloudAuthTarget,
|
||||
): Promise<{ ok: true; status: number; body: unknown; headers: Headers } | { ok: false; error: CloudError }> {
|
||||
const baseUrl = this.options.baseUrl()
|
||||
// The target is frozen by the caller at the start of the login flow; every
|
||||
// auth request in that flow must hit the same service, even if settings
|
||||
// change while a request is in flight.
|
||||
const baseUrl = target?.baseUrl ?? this.options.baseUrl()
|
||||
const timeoutMs = target?.timeoutMs ?? this.options.timeoutMs()
|
||||
const base = authBase(baseUrl)
|
||||
if (base === '') return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
|
|
@ -447,7 +710,7 @@ export class CloudClient {
|
|||
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }
|
||||
}
|
||||
if (cookie !== undefined && cookie !== '') headers.Cookie = cookie
|
||||
const init: RequestInit = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) }
|
||||
const init: RequestInit = { method, headers, signal: AbortSignal.timeout(timeoutMs) }
|
||||
if (body !== undefined) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
init.body = JSON.stringify(body)
|
||||
|
|
@ -459,7 +722,16 @@ export class CloudClient {
|
|||
const reason = error instanceof Error ? error.message : String(error)
|
||||
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} /auth${path}: ${reason}` } }
|
||||
}
|
||||
const text = await response.text().catch(() => '')
|
||||
let text: string
|
||||
try {
|
||||
text = await response.text()
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: errorFromBody(response.status, `body read failed: ${reason}`, response.headers.get('retry-after')) }
|
||||
}
|
||||
return { ok: false, error: { status: response.status, code: 'body_read_error', message: `${method} /auth${path}: body read failed: ${reason}` } }
|
||||
}
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) }
|
||||
}
|
||||
|
|
@ -468,7 +740,9 @@ export class CloudClient {
|
|||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = {}
|
||||
// Swallowing a malformed login/token body would make the caller treat
|
||||
// garbage as an empty success; surface it as a normalized failure.
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: `${method} /auth${path}: response was not JSON` } }
|
||||
}
|
||||
}
|
||||
return { ok: true, status: response.status, body: parsed, headers: response.headers }
|
||||
|
|
@ -481,27 +755,41 @@ export class CloudClient {
|
|||
* is a short-lived session cookie that the caller immediately spends on
|
||||
* {@link CloudClient.mintToken} and then drops.
|
||||
*/
|
||||
async login(username: string, password: string): Promise<CloudResult<LoginOutcome>> {
|
||||
const sent = await this.authFetch('POST', '/login', { username, password })
|
||||
async login(username: string, password: string, target?: CloudAuthTarget): Promise<CloudResult<LoginOutcome>> {
|
||||
const sent = await this.authFetch('POST', '/login', { username, password }, undefined, target)
|
||||
if (!sent.ok) return sent
|
||||
const cookie = sessionCookieOf(sent.headers)
|
||||
if (cookie === '') {
|
||||
return { ok: false, error: { status: sent.status, code: 'no_session', message: '登录成功,但服务端没有下发会话' } }
|
||||
}
|
||||
const body = sent.body as { user?: AccountInfo }
|
||||
return { ok: true, status: sent.status, data: { user: body.user ?? {}, sessionCookie: cookie } }
|
||||
let body: Record<string, unknown>
|
||||
try {
|
||||
body = requireResponseObject(sent.body, 'login response')
|
||||
if (body.user !== undefined && body.user !== null) requireResponseObject(body.user, 'login response user')
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
return { ok: false, error: { status: sent.status, code: 'invalid_response', message: `POST /auth/login: ${reason}` } }
|
||||
}
|
||||
const user = (body.user ?? {}) as AccountInfo
|
||||
return { ok: true, status: sent.status, data: { user, sessionCookie: cookie } }
|
||||
}
|
||||
|
||||
/** Mint one scoped API token using a live session cookie. */
|
||||
async mintToken(sessionCookie: string, scope: string, label: string): Promise<CloudResult<IssuedToken>> {
|
||||
const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie)
|
||||
async mintToken(sessionCookie: string, scope: string, label: string, target?: CloudAuthTarget): Promise<CloudResult<IssuedToken>> {
|
||||
const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie, target)
|
||||
if (!sent.ok) return sent
|
||||
const body = sent.body as { token?: IssuedToken }
|
||||
const issued = body.token
|
||||
if (issued === undefined || typeof issued.token !== 'string' || issued.token === '') {
|
||||
return { ok: false, error: { status: sent.status, code: 'no_token', message: '服务端没有返回令牌' } }
|
||||
try {
|
||||
const body = requireResponseObject(sent.body, 'token response')
|
||||
const issued = requireResponseObject(body.token, 'token response token')
|
||||
requireResponseString(issued, 'token')
|
||||
optionalResponseString(issued, 'id')
|
||||
optionalResponseString(issued, 'scope')
|
||||
optionalResponseString(issued, 'label')
|
||||
return { ok: true, status: sent.status, data: issued as unknown as IssuedToken }
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
return { ok: false, error: { status: sent.status, code: 'invalid_response', message: `POST /auth/tokens: ${reason}` } }
|
||||
}
|
||||
return { ok: true, status: sent.status, data: issued }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -172,8 +172,12 @@ async function serveLogin(deps: CloudSyncRouteDeps, req: IncomingMessage, res: S
|
|||
fail(res, 403, 'origin-rejected')
|
||||
return
|
||||
}
|
||||
const target = deps.store.settings().baseUrl
|
||||
if (!isSecureLoginTarget(target)) {
|
||||
// Snapshot the complete connection before any credential leaves the
|
||||
// process. Every auth call in this flow is pinned to this target, and the
|
||||
// final patch is refused if the configured address changed meanwhile.
|
||||
const settings = deps.store.settings()
|
||||
const target = { baseUrl: settings.baseUrl, timeoutMs: settings.requestTimeoutMs }
|
||||
if (!isSecureLoginTarget(target.baseUrl)) {
|
||||
// Refuse to put a password on a plaintext channel that is not loopback.
|
||||
json(res, 400, { ok: false, error: '服务地址不是 HTTPS,拒绝在上面发送密码,请先把服务地址改成 https://' })
|
||||
return
|
||||
|
|
@ -205,25 +209,39 @@ async function serveLogin(deps: CloudSyncRouteDeps, req: IncomingMessage, res: S
|
|||
return
|
||||
}
|
||||
const client = deps.client()
|
||||
const session = await client.login(username, password)
|
||||
const session = await client.login(username, password, target)
|
||||
if (!session.ok) {
|
||||
const status = session.error.status === 429 ? 429 : 401
|
||||
json(res, status, { ok: false, error: describeError(session.error) })
|
||||
return
|
||||
}
|
||||
const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity)
|
||||
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory)
|
||||
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary)
|
||||
const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity, target)
|
||||
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory, target)
|
||||
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary, target)
|
||||
if (!activity.ok && !memory.ok) {
|
||||
const first = activity.ok ? memory : activity
|
||||
const reason = first.ok ? '无法创建令牌' : describeError(first.error)
|
||||
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` })
|
||||
return
|
||||
}
|
||||
// Atomic account switch: a scope whose mint failed must not keep the token
|
||||
// of the PREVIOUS account — clearing beats carrying a stale credential the
|
||||
// user just replaced. (Writing a token clears the clear-marker, so ordering
|
||||
// inside one patch is irrelevant.)
|
||||
const patch: Record<string, unknown> = {}
|
||||
if (activity.ok && typeof activity.data.token === 'string') patch.activityToken = activity.data.token
|
||||
if (memory.ok && typeof memory.data.token === 'string') patch.memoryToken = memory.data.token
|
||||
if (summary.ok && typeof summary.data.token === 'string') patch.summaryToken = summary.data.token
|
||||
if (!activity.ok || typeof activity.data.token !== 'string') patch.clearActivityToken = true
|
||||
if (!memory.ok || typeof memory.data.token !== 'string') patch.clearMemoryToken = true
|
||||
if (!summary.ok || typeof summary.data.token !== 'string') patch.clearSummaryToken = true
|
||||
// A settings edit while login/mintToken was in flight could otherwise bind
|
||||
// fresh tokens minted for the OLD service to the NEW address. Refuse the
|
||||
// patch outright: no token at all is safer than a wrong-attribution token.
|
||||
if (deps.store.settings().baseUrl !== target.baseUrl) {
|
||||
json(res, 409, { ok: false, error: '登录过程中服务地址已变更,本次登录结果已丢弃,请确认服务地址后重新登录' })
|
||||
return
|
||||
}
|
||||
const applied = deps.store.patch(patch)
|
||||
if (!applied.ok) {
|
||||
json(res, 500, { ok: false, error: applied.error })
|
||||
|
|
@ -271,7 +289,10 @@ async function serveSync(deps: CloudSyncRouteDeps, req: IncomingMessage, res: Se
|
|||
return
|
||||
}
|
||||
if (suffix === '/run') {
|
||||
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
|
||||
// Mutating route: the method, origin and content-type gates live in
|
||||
// jsonBody so a cross-site form/text POST cannot trigger a sync pass.
|
||||
const body = await jsonBody(req, res)
|
||||
if (body === undefined) return
|
||||
const stats = await sync.syncOnce()
|
||||
json(res, 200, { ok: true, stats, conflicts: await sync.conflictDetails() })
|
||||
return
|
||||
|
|
@ -280,7 +301,7 @@ async function serveSync(deps: CloudSyncRouteDeps, req: IncomingMessage, res: Se
|
|||
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
|
||||
const body = await jsonBody(req, res)
|
||||
if (body === undefined) return
|
||||
const result = await sync.resolveConflict(body.name, body.action)
|
||||
const result = await sync.resolveConflict(body.name, body.action, body.conflictId)
|
||||
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() })
|
||||
return
|
||||
}
|
||||
|
|
@ -288,7 +309,7 @@ async function serveSync(deps: CloudSyncRouteDeps, req: IncomingMessage, res: Se
|
|||
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
|
||||
const body = await jsonBody(req, res)
|
||||
if (body === undefined) return
|
||||
const result = await sync.resolveConflicts(body.action)
|
||||
const result = await sync.resolveConflicts(body.action, body.conflictIds)
|
||||
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() })
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,18 @@ export const DEFAULT_SETTINGS: Settings = {
|
|||
summaryMaxChars: 6000,
|
||||
skillsSyncEnabled: true,
|
||||
skillsDir: '',
|
||||
/** Local-first memory: on by default, independent of any cloud account. */
|
||||
localMemoryEnabled: true,
|
||||
/** Cloud memory adapter; off by default in the local-first phase. */
|
||||
cloudMemoryEnabled: false,
|
||||
/** Automatically create the global and current-project spaces. */
|
||||
autoMemorySpaces: true,
|
||||
/** Automatically capture explicit long-term facts from conversation turns. */
|
||||
autoSummaryEnabled: true,
|
||||
/** Automatically maintain the USER.md profile from explicit preferences. */
|
||||
autoProfileEnabled: true,
|
||||
/** Default result count for local memory search. */
|
||||
localMemoryK: 5,
|
||||
}
|
||||
|
||||
/** Effective, fully-resolved settings. */
|
||||
|
|
@ -43,6 +55,18 @@ export interface Settings {
|
|||
skillsSyncEnabled: boolean
|
||||
/** Local skills directory override; empty means `$DSH_HOME/skills`. */
|
||||
skillsDir: string
|
||||
/** Local-first memory gate. */
|
||||
localMemoryEnabled: boolean
|
||||
/** Cloud memory adapter gate; defaults off. */
|
||||
cloudMemoryEnabled: boolean
|
||||
/** Automatically create global and project spaces on first use. */
|
||||
autoMemorySpaces: boolean
|
||||
/** Automatic long-term summary capture. */
|
||||
autoSummaryEnabled: boolean
|
||||
/** Automatic USER.md profile maintenance. */
|
||||
autoProfileEnabled: boolean
|
||||
/** Default local memory result count. */
|
||||
localMemoryK: number
|
||||
}
|
||||
|
||||
/** Raw row config as it comes out of the cordis loader. */
|
||||
|
|
@ -128,5 +152,12 @@ export function settingsFromConfig(raw: unknown): Partial<Settings> {
|
|||
if (summaryMaxChars !== undefined) result.summaryMaxChars = summaryMaxChars
|
||||
if (typeof source.skillsSyncEnabled === 'boolean') result.skillsSyncEnabled = source.skillsSyncEnabled
|
||||
if (typeof source.skillsDir === 'string') result.skillsDir = source.skillsDir.trim().slice(0, 512)
|
||||
if (typeof source.localMemoryEnabled === 'boolean') result.localMemoryEnabled = source.localMemoryEnabled
|
||||
if (typeof source.cloudMemoryEnabled === 'boolean') result.cloudMemoryEnabled = source.cloudMemoryEnabled
|
||||
if (typeof source.autoMemorySpaces === 'boolean') result.autoMemorySpaces = source.autoMemorySpaces
|
||||
if (typeof source.autoSummaryEnabled === 'boolean') result.autoSummaryEnabled = source.autoSummaryEnabled
|
||||
if (typeof source.autoProfileEnabled === 'boolean') result.autoProfileEnabled = source.autoProfileEnabled
|
||||
const localMemoryK = boundedInt(source.localMemoryK, 1, 100)
|
||||
if (localMemoryK !== undefined) result.localMemoryK = localMemoryK
|
||||
return result
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,6 +48,9 @@ export interface CloudMemoryContext extends Context {
|
|||
export interface SessionLike {
|
||||
id?: string
|
||||
sessionId?: string
|
||||
cwd?: string
|
||||
workspace?: string
|
||||
header?: { cwd?: string; workspace?: string }
|
||||
}
|
||||
|
||||
/** One `session/event` payload. */
|
||||
|
|
|
|||
|
|
@ -8,9 +8,10 @@
|
|||
* memory_add / … while the settings page, skill management, and activity
|
||||
* reporting keep working.
|
||||
*/
|
||||
import type { CloudMemoryContext } from '../context-types.ts'
|
||||
import type { CloudMemoryContext, SessionEventLike, SessionLike } from '../context-types.ts'
|
||||
import { brainKernel } from '../kernel.ts'
|
||||
import { createMemoryTools } from '../memory/tools.ts'
|
||||
import { conversationIdOf, redactSecrets, textOf, turnOf } from '../reporter.ts'
|
||||
|
||||
export const name = 'dsh-brain-memory'
|
||||
|
||||
|
|
@ -19,7 +20,8 @@ export const inject = ['tools']
|
|||
|
||||
/** Register the sub-plugin with the host. */
|
||||
export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
||||
const kernel = brainKernel(config, ctx.logger('dsh-brain'))
|
||||
const logger = ctx.logger('dsh-brain')
|
||||
const kernel = brainKernel(config, logger)
|
||||
kernel.activate('memory')
|
||||
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation')
|
||||
|
||||
|
|
@ -30,4 +32,102 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
|||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`)
|
||||
}
|
||||
})
|
||||
|
||||
// Project the compact USER.md/MEMORY.md state into the system prompt each turn.
|
||||
// The files are generated from explicit profile/rule records only.
|
||||
ctx.inject(['systemPrompt'], (prompted) => {
|
||||
const host = prompted as unknown as { get?: (name: string) => unknown; systemPrompt?: unknown }
|
||||
const service = typeof host.get === 'function' ? host.get('systemPrompt') : host.systemPrompt
|
||||
const prompt = service as { section?: (value: { name: string; order: number; text: () => string }) => unknown } | undefined
|
||||
prompt?.section?.({
|
||||
name: 'dsh-brain:local-memory',
|
||||
order: 151,
|
||||
text: () => kernel.settings().localMemoryEnabled === false ? '' : kernel.localMemory.projectionText(),
|
||||
})
|
||||
})
|
||||
|
||||
// Local automatic summary: consume real host messages (structured content),
|
||||
// ignore host/plugin injections, and persist progress by stable session + turn.
|
||||
const turns = new Map<string, { turn: number; user: string[] }>()
|
||||
const pending = new Map<string, { conversation: string; turn: number; workspace?: string; user: string; attempts: number }>()
|
||||
const openTurns = new Map<string, number>()
|
||||
let flushing = false
|
||||
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const onEvent = ctx.on as unknown as (
|
||||
name: 'session/event',
|
||||
listener: (session: SessionLike, event: SessionEventLike) => void,
|
||||
) => () => void
|
||||
const workspaceOfSession = (session: SessionLike): string | undefined =>
|
||||
session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace
|
||||
const isInjected = (value: unknown): boolean => {
|
||||
if (value === null || typeof value !== 'object') return false
|
||||
const source = (value as Record<string, unknown>).source
|
||||
if (source === null || typeof source !== 'object') return false
|
||||
const kind = (source as Record<string, unknown>).kind
|
||||
return typeof kind === 'string' && kind !== 'user'
|
||||
}
|
||||
const flushPending = async (): Promise<void> => {
|
||||
if (flushing || pending.size === 0) return
|
||||
flushing = true
|
||||
try {
|
||||
for (const [key, item] of [...pending]) {
|
||||
try {
|
||||
await kernel.localMemory.withWorkspace(item.workspace, () => kernel.localMemory.summarizeConversation({
|
||||
sessionId: item.conversation,
|
||||
turns: [{ turnId: String(item.turn), user: item.user }],
|
||||
}, item.workspace))
|
||||
pending.delete(key)
|
||||
} catch (error) {
|
||||
item.attempts += 1
|
||||
logger.warn('dsh-brain local summary failed (will retry): ' + (error instanceof Error ? error.message : String(error)))
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
flushing = false
|
||||
if (pending.size > 0) {
|
||||
if (retryTimer !== undefined) clearTimeout(retryTimer)
|
||||
retryTimer = setTimeout(() => { retryTimer = undefined; void flushPending() }, 2000)
|
||||
retryTimer.unref?.()
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.effect(() => {
|
||||
const dispose = onEvent('session/event', (session, event) => {
|
||||
const conversation = conversationIdOf(session)
|
||||
if (conversation === undefined) return
|
||||
if (event.type === 'turn/start') {
|
||||
const started = turnOf(event.data)
|
||||
if (started !== undefined) openTurns.set(conversation, started)
|
||||
void flushPending()
|
||||
return
|
||||
}
|
||||
const eventTurn = turnOf(event.data)
|
||||
const turn = eventTurn ?? openTurns.get(conversation)
|
||||
if (event.type === 'user/message') {
|
||||
const raw = textOf(event.data?.message ?? event.data)
|
||||
if (turn === undefined || raw === undefined || isInjected(event.data?.message ?? event.data)) return
|
||||
const key = conversation + ':' + String(turn)
|
||||
const entry = turns.get(key) ?? { turn, user: [] }
|
||||
entry.user.push(redactSecrets(raw).slice(0, 4000))
|
||||
turns.set(key, entry)
|
||||
return
|
||||
}
|
||||
if (event.type === 'turn/end' && turn !== undefined) {
|
||||
const key = conversation + ':' + String(turn)
|
||||
const entry = turns.get(key); turns.delete(key)
|
||||
if (eventTurn === undefined || openTurns.get(conversation) === eventTurn) openTurns.delete(conversation)
|
||||
if (entry === undefined || entry.user.length === 0) return
|
||||
const settings = kernel.settings()
|
||||
if (settings.localMemoryEnabled === false || settings.autoSummaryEnabled === false) return
|
||||
pending.set(key, { conversation, turn, ...(workspaceOfSession(session) === undefined ? {} : { workspace: workspaceOfSession(session) }), user: entry.user.join('\n'), attempts: 0 })
|
||||
void flushPending()
|
||||
return
|
||||
}
|
||||
if (event.type === 'session/end' || event.type === 'session/close' || event.type === 'session/closed' || event.type === 'session/terminated') {
|
||||
openTurns.delete(conversation)
|
||||
for (const key of turns.keys()) if (key.startsWith(conversation + ':')) turns.delete(key)
|
||||
}
|
||||
})
|
||||
return () => { dispose(); if (retryTimer !== undefined) { clearTimeout(retryTimer); retryTimer = undefined } }
|
||||
}, 'dsh-brain-memory: local summary')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@
|
|||
*/
|
||||
import { join, resolve } from 'node:path'
|
||||
import { CloudClient } from './api.ts'
|
||||
import { LocalMemoryManager, LocalMemoryRemote } from './local-memory/index.ts'
|
||||
import { VERSION } from './version.ts'
|
||||
import { createCloudMemoryRemoteFactory } from './cloudsync.ts'
|
||||
import { ClientRegistry } from './clients.ts'
|
||||
import { ClaudePluginMarketplaceProvider, MarketService } from './market.ts'
|
||||
|
|
@ -32,8 +34,8 @@ import { SkillUpdater } from './skill-update.ts'
|
|||
import { SettingsStore, dshHome } from './store.ts'
|
||||
import { AdminSkillRepository } from './skills/repository.ts'
|
||||
|
||||
/** Version reported by the status card. */
|
||||
export const VERSION = '0.9.11'
|
||||
/** Version reported by the status card (single source: package.json). */
|
||||
export { VERSION }
|
||||
|
||||
/** Logger face the kernel services need (the first entry supplies the host one). */
|
||||
export interface KernelLogger {
|
||||
|
|
@ -45,6 +47,22 @@ export interface KernelLogger {
|
|||
export type BrainBundle = 'cloudsync' | 'memory' | 'skills' | 'mcp' | 'settings-ui'
|
||||
|
||||
/** The shared service set behind every dsh-brain sub-plugin entry. */
|
||||
|
||||
/** Resolve a workspace from the different host tool/session context shapes. */
|
||||
function workspaceFromExec(exec: unknown): string | undefined {
|
||||
if (exec === null || typeof exec !== 'object') return undefined
|
||||
const value = exec as Record<string, any>
|
||||
const candidates = [
|
||||
value.workspace, value.cwd, value.projectPath,
|
||||
value.session?.cwd, value.session?.workspace, value.session?.header?.cwd, value.session?.header?.workspace,
|
||||
value.agent?.session?.cwd, value.agent?.session?.header?.cwd,
|
||||
]
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && candidate.trim() !== '') return candidate
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export class BrainKernel {
|
||||
private readonly active = new Set<BrainBundle>()
|
||||
private readonly settingsOf: () => ReturnType<SettingsStore['settings']>
|
||||
|
|
@ -52,6 +70,8 @@ export class BrainKernel {
|
|||
readonly store: SettingsStore
|
||||
readonly client: CloudClient
|
||||
readonly memoryRemoteFactory: ReturnType<typeof createCloudMemoryRemoteFactory>
|
||||
readonly localMemory: LocalMemoryManager
|
||||
readonly localMemoryRemote: LocalMemoryRemote
|
||||
readonly reporter: Reporter
|
||||
readonly skillAdmin: SkillAdmin
|
||||
readonly skillRepository: AdminSkillRepository
|
||||
|
|
@ -82,12 +102,38 @@ export class BrainKernel {
|
|||
memoryToken: () => store.memoryToken(),
|
||||
})
|
||||
|
||||
// Local-first memory is independent of the cloud adapter: it initializes
|
||||
// lazily on the first memory tool call and needs no token or account.
|
||||
this.localMemory = new LocalMemoryManager({
|
||||
cwd: () => process.cwd(),
|
||||
settings: () => ({
|
||||
localMemoryEnabled: settings().localMemoryEnabled,
|
||||
cloudMemoryEnabled: settings().cloudMemoryEnabled,
|
||||
autoMemorySpaces: settings().autoMemorySpaces,
|
||||
autoSummaryEnabled: settings().autoSummaryEnabled,
|
||||
autoProfileEnabled: settings().autoProfileEnabled,
|
||||
localMemoryK: settings().localMemoryK,
|
||||
}),
|
||||
})
|
||||
this.localMemoryRemote = new LocalMemoryRemote(this.localMemory)
|
||||
// The global space is part of first boot; project space stays lazy until
|
||||
// the first memory use in that project.
|
||||
if (settings().localMemoryEnabled !== false && settings().autoMemorySpaces !== false) void this.localMemory.ensureGlobal().catch((error: unknown) => { logger.warn('dsh-brain local memory initialization failed: ' + (error instanceof Error ? error.message : String(error))) })
|
||||
|
||||
this.reporter = new Reporter({
|
||||
client,
|
||||
// Pinned clients: one request leaves under the connection it started
|
||||
// with, never under whatever settings say by the time it lands.
|
||||
clientFor: (context) => new CloudClient({
|
||||
baseUrl: () => context.baseUrl,
|
||||
token: () => context.activityToken,
|
||||
timeoutMs: () => context.timeoutMs,
|
||||
}),
|
||||
settings: () => ({ enabled: settings().activityEnabled, clientId: settings().clientId }),
|
||||
activityToken: () => store.activityToken(),
|
||||
baseUrl: () => settings().baseUrl,
|
||||
summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }),
|
||||
summaryToken: () => store.summaryToken(),
|
||||
timeoutMs: () => settings().requestTimeoutMs,
|
||||
log: (message) => logger.warn(message),
|
||||
})
|
||||
|
||||
|
|
@ -117,11 +163,26 @@ export class BrainKernel {
|
|||
|
||||
this.skillSync = new SkillSync({
|
||||
client: () => client,
|
||||
clientForScope: (scope) => new CloudClient({
|
||||
baseUrl: () => scope.endpoint,
|
||||
token: () => scope.accountToken,
|
||||
timeoutMs: () => settings().requestTimeoutMs,
|
||||
}),
|
||||
settings: () => ({
|
||||
enabled: settings().enabled,
|
||||
skillsSyncEnabled: settings().skillsSyncEnabled,
|
||||
}),
|
||||
repository: () => this.skillRepository,
|
||||
repositoryForScope: (scope) => new AdminSkillRepository({
|
||||
admin: skillAdmin,
|
||||
skillsRoot: () => scope.root,
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
}),
|
||||
scope: () => ({
|
||||
endpoint: settings().baseUrl,
|
||||
accountToken: store.memoryToken(),
|
||||
root: skillsRootDir(),
|
||||
}),
|
||||
log: (message) => logger.info(message),
|
||||
})
|
||||
|
||||
|
|
@ -196,10 +257,26 @@ export class BrainKernel {
|
|||
const store = this.store
|
||||
const settings = this.settingsOf
|
||||
return {
|
||||
remote: () => this.memoryRemoteFactory.current(),
|
||||
// Local-first by default. The cloud adapter is only selected when the
|
||||
// user explicitly enables it AND has a memory token; otherwise memory
|
||||
// tools stay fully usable offline.
|
||||
remote: () => {
|
||||
const effective = settings()
|
||||
const localEnabled = effective.localMemoryEnabled !== false
|
||||
const cloudEnabled = effective.cloudMemoryEnabled === true && store.memoryToken() !== ''
|
||||
if (cloudEnabled) return this.memoryRemoteFactory.current()
|
||||
if (localEnabled) return this.localMemoryRemote
|
||||
throw new Error('memory_disabled')
|
||||
},
|
||||
client: () => this.client,
|
||||
memoryToken: () => store.memoryToken(),
|
||||
settings: () => ({ enabled: settings().memoryEnabled, defaultK: settings().defaultK }),
|
||||
settings: () => {
|
||||
const effective = settings()
|
||||
const local = effective.localMemoryEnabled !== false && !(effective.cloudMemoryEnabled === true && store.memoryToken() !== '')
|
||||
return { enabled: effective.memoryEnabled, defaultK: local ? effective.localMemoryK : effective.defaultK }
|
||||
},
|
||||
localMemory: () => settings().localMemoryEnabled !== false,
|
||||
workspace: (exec?: unknown) => workspaceFromExec(exec),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -223,6 +300,7 @@ export class BrainKernel {
|
|||
updates: skills ? this.updater : undefined,
|
||||
clients: skills ? this.clients : undefined,
|
||||
mcp: this.isActive('mcp'),
|
||||
localMemory: this.localMemory,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
export { DepartmentManager } from './manager.ts'
|
||||
export type { DepartmentManagerOptions } from './manager.ts'
|
||||
export type { Department, DepartmentCreateInput, DepartmentMemoryPolicy, DepartmentRecallHit, DepartmentScope, DepartmentSessionRef, DepartmentUpdateInput } from './types.ts'
|
||||
|
|
@ -0,0 +1,238 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { join } from 'node:path'
|
||||
import { LocalMemoryManager, projectIdFor } from '../manager.ts'
|
||||
import { containsSecret, JsonMemoryStore } from '../storage.ts'
|
||||
import type { LocalMemoryAddInput, LocalMemoryRecord, LocalMemorySearchHit } from '../types.ts'
|
||||
import { DepartmentRegistry } from './registry.ts'
|
||||
import type { Department, DepartmentCreateInput, DepartmentRecallHit, DepartmentScope, DepartmentSessionRef, DepartmentUpdateInput } from './types.ts'
|
||||
|
||||
function text(value: unknown, max: number, required = false): string {
|
||||
const result = typeof value === 'string' ? value.trim().slice(0, max) : ''
|
||||
if (required && result === '') throw new Error('department_required_field')
|
||||
return result
|
||||
}
|
||||
function list(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return [...new Set(value.filter((item): item is string => typeof item === 'string').map((item) => item.trim().slice(0, 200)).filter((item) => item !== ''))].slice(0, 50)
|
||||
}
|
||||
function hostName(value: string): string {
|
||||
const host = text(value, 64, true)
|
||||
if (!/^[a-z0-9][a-z0-9_-]*$/.test(host)) throw new Error('department_invalid_host')
|
||||
return host
|
||||
}
|
||||
function limitOf(value: number | undefined): number {
|
||||
return Math.max(1, Math.min(50, Math.trunc(value ?? 5)))
|
||||
}
|
||||
|
||||
export interface DepartmentManagerOptions {
|
||||
memory: LocalMemoryManager
|
||||
}
|
||||
|
||||
/** Persistent departments: private memory, reusable session references and bounded recall. */
|
||||
export class DepartmentManager {
|
||||
readonly memory: LocalMemoryManager
|
||||
constructor(options: DepartmentManagerOptions) { this.memory = options.memory }
|
||||
|
||||
private root(scope: DepartmentScope): string { return scope === 'global' ? this.memory.globalRoot : this.memory.projectRoot }
|
||||
private registry(scope: DepartmentScope): DepartmentRegistry { return new DepartmentRegistry(join(this.root(scope), 'departments', 'registry.json')) }
|
||||
private store(department: Department): JsonMemoryStore {
|
||||
return new JsonMemoryStore(join(this.root(department.scope), 'departments', department.id, 'memory-space'), 'department', department.spaceId)
|
||||
}
|
||||
private async activeStore(department: Department): Promise<JsonMemoryStore> {
|
||||
if (!department.active) throw new Error('department_disabled')
|
||||
const store = this.store(department)
|
||||
const meta = await store.init(department.name + ' 私有记忆')
|
||||
if (!meta.active) throw new Error('department_disabled')
|
||||
return store
|
||||
}
|
||||
private async find(id: string): Promise<Department | undefined> {
|
||||
const global = (await this.registry('global').read()).departments.find((item) => item.id === id)
|
||||
if (global !== undefined) return global
|
||||
return (await this.registry('project').read()).departments.find((item) => item.id === id)
|
||||
}
|
||||
private async required(id: string): Promise<Department> {
|
||||
const department = await this.find(id)
|
||||
if (department === undefined) throw new Error('department_not_found')
|
||||
return department
|
||||
}
|
||||
|
||||
/** Create once by scope + case-insensitive name; repeated calls return the existing department. */
|
||||
async create(input: DepartmentCreateInput): Promise<{ department: Department; created: boolean }> {
|
||||
const scope = input.scope ?? 'project'
|
||||
const name = text(input.name, 100, true)
|
||||
const role = text(input.role ?? '', 12000)
|
||||
if (containsSecret(role)) throw new Error('secret_not_allowed')
|
||||
await this.memory.ensureGlobal()
|
||||
if (scope === 'project') await this.memory.ensureProject()
|
||||
return this.registry(scope).update(async (file) => {
|
||||
const existing = file.departments.find((item) => item.name.toLocaleLowerCase() === name.toLocaleLowerCase())
|
||||
if (existing !== undefined) return { department: existing, created: false }
|
||||
const id = 'dept_' + randomUUID()
|
||||
const timestamp = new Date().toISOString()
|
||||
const department: Department = {
|
||||
id, name, role, scope,
|
||||
...(scope === 'project' ? { projectId: projectIdFor(this.memory.projectRoot) } : {}),
|
||||
spaceId: 'department_' + id.slice(5),
|
||||
skills: list(input.skills), allowedTools: list(input.allowedTools),
|
||||
memory: { readGlobal: input.readGlobal ?? true, readProject: input.readProject ?? true },
|
||||
sessionRefs: {}, active: true, createdAt: timestamp, updatedAt: timestamp, revision: 1,
|
||||
}
|
||||
await this.activeStore(department)
|
||||
file.departments.push(department)
|
||||
return { department, created: true }
|
||||
})
|
||||
}
|
||||
|
||||
async get(id: string): Promise<Department | undefined> { return this.find(id) }
|
||||
|
||||
async list(scope?: DepartmentScope): Promise<Department[]> {
|
||||
const scopes: DepartmentScope[] = scope === undefined ? ['project', 'global'] : [scope]
|
||||
const files = await Promise.all(scopes.map((item) => this.registry(item).read()))
|
||||
return files.flatMap((file) => file.departments).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id))
|
||||
}
|
||||
|
||||
async update(id: string, patch: DepartmentUpdateInput, expectedRevision?: number): Promise<Department> {
|
||||
const current = await this.required(id)
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict')
|
||||
if (patch.role !== undefined && containsSecret(patch.role)) throw new Error('secret_not_allowed')
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id)
|
||||
if (department === undefined) throw new Error('department_not_found')
|
||||
if (expectedRevision !== undefined && department.revision !== expectedRevision) throw new Error('revision_conflict')
|
||||
if (patch.name !== undefined) department.name = text(patch.name, 100, true)
|
||||
if (patch.role !== undefined) department.role = text(patch.role, 12000)
|
||||
if (patch.skills !== undefined) department.skills = list(patch.skills)
|
||||
if (patch.allowedTools !== undefined) department.allowedTools = list(patch.allowedTools)
|
||||
if (patch.readGlobal !== undefined || patch.readProject !== undefined) {
|
||||
department.memory = {
|
||||
readGlobal: patch.readGlobal ?? department.memory.readGlobal,
|
||||
readProject: patch.readProject ?? department.memory.readProject,
|
||||
}
|
||||
}
|
||||
department.revision += 1
|
||||
department.updatedAt = new Date().toISOString()
|
||||
return department
|
||||
})
|
||||
}
|
||||
|
||||
/** Return the same portable reference on every resume; a host session id can be attached separately. */
|
||||
async resumeSession(id: string, host = 'dsh'): Promise<DepartmentSessionRef> {
|
||||
const current = await this.required(id)
|
||||
await this.activeStore(current)
|
||||
const normalizedHost = hostName(host)
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id)
|
||||
if (department === undefined) throw new Error('department_not_found')
|
||||
if (!department.active) throw new Error('department_disabled')
|
||||
const timestamp = new Date().toISOString()
|
||||
const existing = department.sessionRefs[normalizedHost]
|
||||
if (existing !== undefined) {
|
||||
existing.lastUsedAt = timestamp
|
||||
department.updatedAt = timestamp
|
||||
return existing
|
||||
}
|
||||
const reference: DepartmentSessionRef = { id: 'ds_' + randomUUID(), host: normalizedHost, reusable: true, createdAt: timestamp, lastUsedAt: timestamp }
|
||||
department.sessionRefs[normalizedHost] = reference
|
||||
department.updatedAt = timestamp
|
||||
return reference
|
||||
})
|
||||
}
|
||||
|
||||
/** Attach a real host session without replacing the portable reference. */
|
||||
async attachSession(id: string, host: string, hostSessionId: string): Promise<DepartmentSessionRef> {
|
||||
const normalizedHost = hostName(host)
|
||||
const externalId = text(hostSessionId, 500, true)
|
||||
const reference = await this.resumeSession(id, normalizedHost)
|
||||
const current = await this.required(id)
|
||||
await this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id)
|
||||
if (department === undefined) throw new Error('department_not_found')
|
||||
const target = department.sessionRefs[normalizedHost]
|
||||
if (target === undefined) throw new Error('department_session_not_found')
|
||||
target.hostSessionId = externalId
|
||||
target.lastUsedAt = new Date().toISOString()
|
||||
department.updatedAt = target.lastUsedAt
|
||||
})
|
||||
return { ...reference, hostSessionId: externalId }
|
||||
}
|
||||
|
||||
async checkpoint(id: string, input: { currentTask?: string; handoff?: string }, expectedRevision?: number): Promise<Department> {
|
||||
const current = await this.required(id)
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict')
|
||||
const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000)
|
||||
const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000)
|
||||
if ((currentTask !== undefined && containsSecret(currentTask)) || (handoff !== undefined && containsSecret(handoff))) throw new Error('secret_not_allowed')
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id)
|
||||
if (department === undefined) throw new Error('department_not_found')
|
||||
if (expectedRevision !== undefined && department.revision !== expectedRevision) throw new Error('revision_conflict')
|
||||
if (input.currentTask !== undefined) {
|
||||
if (currentTask === '') delete department.currentTask
|
||||
else department.currentTask = currentTask
|
||||
}
|
||||
if (input.handoff !== undefined) {
|
||||
if (handoff === '') delete department.handoff
|
||||
else department.handoff = handoff
|
||||
}
|
||||
department.revision += 1
|
||||
department.updatedAt = new Date().toISOString()
|
||||
return department
|
||||
})
|
||||
}
|
||||
|
||||
async remember(id: string, input: Omit<LocalMemoryAddInput, 'scope' | 'projectId' | 'departmentId'>): Promise<{ record: LocalMemoryRecord; duplicate: boolean }> {
|
||||
const department = await this.required(id)
|
||||
const store = await this.activeStore(department)
|
||||
return store.add({
|
||||
...input,
|
||||
source: input.source ?? 'department:' + id,
|
||||
departmentId: id,
|
||||
...(department.projectId === undefined ? {} : { projectId: department.projectId }),
|
||||
})
|
||||
}
|
||||
|
||||
/** Private first on equal scores; project/global are opt-in and the total result count stays bounded. */
|
||||
async recall(id: string, query: string, k = 5, workspace?: string): Promise<DepartmentRecallHit[]> {
|
||||
const department = await this.required(id)
|
||||
const limit = limitOf(k)
|
||||
const privateHits = await this.store(department).search(query, limit)
|
||||
const shared: LocalMemorySearchHit[] = []
|
||||
if (department.memory.readProject && department.memory.readGlobal) {
|
||||
shared.push(...await this.memory.searchHits(query, limit * 2, workspace))
|
||||
} else if (department.memory.readGlobal) {
|
||||
shared.push(...await this.memory.searchHits(query, limit, workspace, 'global'))
|
||||
} else if (department.memory.readProject) {
|
||||
shared.push(...await this.memory.searchHits(query, limit, workspace, department.projectId ?? projectIdFor(this.memory.projectRoot)))
|
||||
}
|
||||
const rank = { department: 3, project: 2, global: 1 }
|
||||
const candidates: DepartmentRecallHit[] = [
|
||||
...privateHits.map((hit) => ({ ...hit, origin: 'department' as const })),
|
||||
...shared.map((hit) => ({ ...hit, origin: hit.record.scope === 'global' ? 'global' as const : 'project' as const })),
|
||||
]
|
||||
const seen = new Set<string>()
|
||||
return candidates.sort((a, b) => b.score - a.score || rank[b.origin] - rank[a.origin] || b.record.updatedAt.localeCompare(a.record.updatedAt))
|
||||
.filter((hit) => {
|
||||
const key = hit.record.content.trim()
|
||||
if (seen.has(key)) return false
|
||||
seen.add(key)
|
||||
return true
|
||||
}).slice(0, limit)
|
||||
}
|
||||
|
||||
/** Disable without deleting private memories or allowing automatic session recovery. */
|
||||
async disable(id: string, expectedRevision?: number): Promise<Department> {
|
||||
const current = await this.required(id)
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict')
|
||||
const store = this.store(current)
|
||||
if (await store.spaceMeta() !== undefined) await store.setActive(false)
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
const department = file.departments.find((item) => item.id === id)
|
||||
if (department === undefined) throw new Error('department_not_found')
|
||||
if (expectedRevision !== undefined && department.revision !== expectedRevision) throw new Error('revision_conflict')
|
||||
department.active = false
|
||||
department.revision += 1
|
||||
department.updatedAt = new Date().toISOString()
|
||||
return department
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { dirname } from 'node:path'
|
||||
import { withFileLock } from '../storage.ts'
|
||||
import type { Department } from './types.ts'
|
||||
|
||||
interface RegistryFile {
|
||||
version: 1
|
||||
departments: Department[]
|
||||
}
|
||||
|
||||
const EMPTY: RegistryFile = { version: 1, departments: [] }
|
||||
|
||||
async function atomicWrite(path: string, content: string): Promise<void> {
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const temporary = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp'
|
||||
try {
|
||||
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 })
|
||||
await rename(temporary, path)
|
||||
} catch (error) {
|
||||
await rm(temporary, { force: true }).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** JSON registry for one global or project department collection. */
|
||||
export class DepartmentRegistry {
|
||||
readonly path: string
|
||||
constructor(path: string) { this.path = path }
|
||||
|
||||
async read(): Promise<RegistryFile> {
|
||||
let text: string
|
||||
try { text = await readFile(this.path, 'utf8') }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY, departments: [] }
|
||||
throw new Error('department_registry_read_failed: ' + (error instanceof Error ? error.message : String(error)))
|
||||
}
|
||||
let value: unknown
|
||||
try { value = JSON.parse(text) }
|
||||
catch { throw new Error('department_registry_corrupt') }
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('department_registry_corrupt')
|
||||
const file = value as Partial<RegistryFile>
|
||||
if (file.version !== undefined && file.version !== 1) throw new Error('department_registry_incompatible')
|
||||
if (!Array.isArray(file.departments)) throw new Error('department_registry_incompatible')
|
||||
return { version: 1, departments: file.departments }
|
||||
}
|
||||
|
||||
async update<T>(job: (file: RegistryFile) => Promise<T> | T): Promise<T> {
|
||||
return withFileLock(this.path + '.lock', async () => {
|
||||
const file = await this.read()
|
||||
const result = await job(file)
|
||||
await atomicWrite(this.path, JSON.stringify(file, null, 2) + '\n')
|
||||
return result
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
import type { LocalMemoryScope, LocalMemorySearchHit } from '../types.ts'
|
||||
|
||||
/** A department is one reusable working identity, not a hierarchy of experts. */
|
||||
export type DepartmentScope = LocalMemoryScope
|
||||
|
||||
export interface DepartmentMemoryPolicy {
|
||||
readGlobal: boolean
|
||||
readProject: boolean
|
||||
}
|
||||
|
||||
/** A portable reference to a host session; host attachment is explicit. */
|
||||
export interface DepartmentSessionRef {
|
||||
id: string
|
||||
host: string
|
||||
hostSessionId?: string
|
||||
reusable: true
|
||||
createdAt: string
|
||||
lastUsedAt: string
|
||||
}
|
||||
|
||||
export interface Department {
|
||||
id: string
|
||||
name: string
|
||||
role: string
|
||||
scope: DepartmentScope
|
||||
projectId?: string
|
||||
spaceId: string
|
||||
skills: string[]
|
||||
allowedTools: string[]
|
||||
memory: DepartmentMemoryPolicy
|
||||
sessionRefs: Record<string, DepartmentSessionRef>
|
||||
currentTask?: string
|
||||
handoff?: string
|
||||
active: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
revision: number
|
||||
}
|
||||
|
||||
export interface DepartmentCreateInput {
|
||||
name: string
|
||||
role?: string
|
||||
scope?: DepartmentScope
|
||||
skills?: string[]
|
||||
allowedTools?: string[]
|
||||
readGlobal?: boolean
|
||||
readProject?: boolean
|
||||
}
|
||||
|
||||
export interface DepartmentUpdateInput {
|
||||
name?: string
|
||||
role?: string
|
||||
skills?: string[]
|
||||
allowedTools?: string[]
|
||||
readGlobal?: boolean
|
||||
readProject?: boolean
|
||||
}
|
||||
|
||||
export interface DepartmentRecallHit extends LocalMemorySearchHit {
|
||||
origin: 'department' | 'project' | 'global'
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
export { LocalMemoryManager, globalBrainRoot, projectBrainRoot, projectIdFor } from './manager.ts'
|
||||
export { LocalMemoryRemote } from './remote.ts'
|
||||
export { DepartmentManager } from './departments/index.ts'
|
||||
export type { Department, DepartmentCreateInput, DepartmentMemoryPolicy, DepartmentRecallHit, DepartmentScope, DepartmentSessionRef, DepartmentUpdateInput } from './departments/index.ts'
|
||||
export { JsonMemoryStore, JsonMemoryStore as LocalMemoryStore, JsonDocumentStore, JsonDocumentStore as LocalDocumentStore, localMemoryHash, containsSecret } from './storage.ts'
|
||||
export type { LocalDocument, LocalMemoryAddInput, LocalMemoryRecord, LocalMemoryScope, LocalMemorySettings, LocalMemorySearchHit, LocalMemorySpaceScope, LocalSpaceMeta } from './types.ts'
|
||||
|
|
@ -0,0 +1,519 @@
|
|||
/** Local-first memory manager: .dsh/brain layout, spaces, projections and summaries. */
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
import { mkdir, readFile, writeFile, rename, rm, cp, stat, readdir } from 'node:fs/promises'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { dshHome } from '../store.ts'
|
||||
import { JsonDocumentStore, JsonMemoryStore, containsSecret, localMemoryHash, withFileLock } from './storage.ts'
|
||||
import type { LocalDocument, LocalMemoryAddInput, LocalMemoryRecord, LocalMemoryScope, LocalMemorySettings, LocalSpaceMeta } from './types.ts'
|
||||
|
||||
export function globalBrainRoot(): string { return resolve(dshHome(), 'brain') }
|
||||
/** Resolve a user-supplied workspace to its project base, accepting both the project root and its .dsh/brain path. */
|
||||
export function projectBaseOf(value: string): string {
|
||||
const normalized = resolve(value)
|
||||
const brainSuffix = join('.dsh', 'brain')
|
||||
return normalized.endsWith(brainSuffix) ? dirname(dirname(normalized)) : normalized
|
||||
}
|
||||
export function projectBrainRoot(cwd: string = process.cwd()): string { return join(projectBaseOf(cwd), '.dsh', 'brain') }
|
||||
export function projectIdFor(root: string): string { return 'project_' + localMemoryHash(resolve(root)).slice(0, 16) }
|
||||
|
||||
async function atomicWrite(path: string, content: string): Promise<void> {
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const tmp = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp'
|
||||
try {
|
||||
await writeFile(tmp, content, { encoding: 'utf8', mode: 0o600 })
|
||||
await rename(tmp, path)
|
||||
} catch (error) {
|
||||
await rm(tmp, { force: true }).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
async function treeDigest(root: string): Promise<string> {
|
||||
const files: string[] = []
|
||||
const walk = async (dir: string, prefix: string): Promise<void> => {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const rel = prefix === '' ? entry.name : prefix + '/' + entry.name
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) { await walk(full, rel); continue }
|
||||
if (entry.isFile()) files.push(rel + ':' + localMemoryHash((await readFile(full)).toString('base64')))
|
||||
}
|
||||
}
|
||||
await walk(root, '')
|
||||
return localMemoryHash(files.sort().join('\n'))
|
||||
}
|
||||
|
||||
async function readJson<T>(path: string, fallback: T): Promise<T> {
|
||||
let text: string
|
||||
try { text = await readFile(path, 'utf8') }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return fallback
|
||||
throw new Error(`local_memory_state_read_failed: ${path}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
try { return JSON.parse(text) as T }
|
||||
catch { throw new Error(`local_memory_state_corrupt: ${path}`) }
|
||||
}
|
||||
async function writeGitIgnore(projectBase: string): Promise<void> {
|
||||
const dsh = join(projectBase, '.dsh'); await mkdir(dsh, { recursive: true })
|
||||
const path = join(dsh, '.gitignore')
|
||||
let text = ''
|
||||
try { text = await readFile(path, 'utf8') } catch {}
|
||||
if (!/^brain\/?$/m.test(text)) { text = text.trimEnd() + (text === '' ? '' : '\n') + 'brain/\n'; await atomicWrite(path, text) }
|
||||
}
|
||||
|
||||
export interface LocalMemoryManagerOptions {
|
||||
cwd?: () => string
|
||||
/** Optional per-instance workspace provider; a tool/session workspace overrides it. */
|
||||
workspace?: () => string | undefined
|
||||
settings?: () => LocalMemorySettings
|
||||
/** Optional explicit global root (tests/embedding); defaults to $DSH_HOME/brain. */
|
||||
globalRoot?: string
|
||||
/** Optional explicit project root; defaults to <cwd>/.dsh/brain. */
|
||||
projectRoot?: string
|
||||
}
|
||||
export interface LocalTurn { turnId?: string; user?: string; assistant?: string }
|
||||
interface WorkspaceStores { root: string; store: JsonMemoryStore; documents: JsonDocumentStore }
|
||||
interface SessionCheckpoint { lastTurn?: string; count: number; processed?: string[] }
|
||||
|
||||
export class LocalMemoryManager {
|
||||
private readonly cwdOf: () => string
|
||||
private readonly defaultWorkspaceOf: (() => string | undefined) | undefined
|
||||
private readonly settingsOf: () => LocalMemorySettings
|
||||
private readonly workspaceContext = new AsyncLocalStorage<string | undefined>()
|
||||
private readonly workspaces = new Map<string, WorkspaceStores>()
|
||||
private readonly fixedGlobalRoot: string | undefined
|
||||
private readonly fixedProjectRoot: string | undefined
|
||||
constructor(options: LocalMemoryManagerOptions = {}) {
|
||||
this.cwdOf = options.cwd ?? (() => process.cwd())
|
||||
this.defaultWorkspaceOf = options.workspace
|
||||
this.settingsOf = options.settings ?? (() => ({}))
|
||||
this.fixedGlobalRoot = options.globalRoot
|
||||
this.fixedProjectRoot = options.projectRoot
|
||||
}
|
||||
/** Bind one operation to a workspace; AsyncLocalStorage keeps concurrent sessions isolated. */
|
||||
withWorkspace<T>(workspace: string | undefined, job: () => Promise<T>): Promise<T> { return this.workspaceContext.run(workspace, job) }
|
||||
private workspacePath(workspace?: string): string {
|
||||
const value = workspace ?? this.workspaceContext.getStore() ?? this.defaultWorkspaceOf?.() ?? this.cwdOf()
|
||||
return resolve(value)
|
||||
}
|
||||
private projectRootFor(workspace?: string): string { return this.fixedProjectRoot ?? projectBrainRoot(this.workspacePath(workspace)) }
|
||||
private projectBaseFor(workspace?: string): string { return projectBaseOf(this.workspacePath(workspace)) }
|
||||
get globalRoot(): string { return this.fixedGlobalRoot ?? globalBrainRoot() }
|
||||
get projectRoot(): string { return this.projectRootFor() }
|
||||
private get globalStore(): JsonMemoryStore { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global') }
|
||||
private projectStoreFor(workspace?: string): JsonMemoryStore { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))) }
|
||||
private async storeFor(scope: LocalMemoryScope, workspace?: string): Promise<JsonMemoryStore> {
|
||||
if (scope === 'global') return this.globalStore
|
||||
return this.ensureProject(workspace)
|
||||
}
|
||||
private projectionDirtyPath(): string { return join(this.globalRoot, 'state', 'projection.json') }
|
||||
private async markProjectionDirty(error?: unknown): Promise<string> {
|
||||
const marker = String(Date.now()) + '-' + randomUUID()
|
||||
await atomicWrite(this.projectionDirtyPath(), JSON.stringify({ dirty: true, marker, ...(error === undefined ? {} : { lastError: error instanceof Error ? error.message : String(error) }), updatedAt: new Date().toISOString() }, null, 2) + '\n')
|
||||
return marker
|
||||
}
|
||||
private async clearProjectionDirty(marker: string): Promise<void> {
|
||||
try { const state = JSON.parse(await readFile(this.projectionDirtyPath(), 'utf8')) as { marker?: unknown }; if (state.marker === marker) await rm(this.projectionDirtyPath(), { force: true }) } catch {}
|
||||
}
|
||||
/** Retry a projection left dirty by a committed memory write. */
|
||||
async repairProjectionsIfDirty(): Promise<boolean> {
|
||||
if (!existsSync(this.projectionDirtyPath())) return false
|
||||
try { await this.regenerateProjections(); return true } catch { return false }
|
||||
}
|
||||
private async tryRegenerateProjections(): Promise<{ projectionPending: boolean; projectionError?: string }> {
|
||||
try { await this.regenerateProjections(); return { projectionPending: false } }
|
||||
catch (error) { return { projectionPending: true, projectionError: error instanceof Error ? error.message : String(error) } }
|
||||
}
|
||||
/** Idempotently create the global space and its runtime projections. */
|
||||
async ensureGlobal(): Promise<LocalSpaceMeta> {
|
||||
return withFileLock(join(this.globalRoot, 'state', '.init.lock'), async () => {
|
||||
await mkdir(join(this.globalRoot, 'runtime'), { recursive: true })
|
||||
await mkdir(join(this.globalRoot, 'spaces', 'global'), { recursive: true })
|
||||
await mkdir(join(this.globalRoot, 'backups'), { recursive: true })
|
||||
await mkdir(join(this.globalRoot, 'state'), { recursive: true })
|
||||
const meta = await this.globalStore.init('全局记忆')
|
||||
const spaceMarker = join(this.globalRoot, 'spaces', 'global', 'space.json')
|
||||
if (!(await stat(spaceMarker).catch(() => undefined))) await atomicWrite(spaceMarker, JSON.stringify(meta, null, 2) + '\n')
|
||||
const userPath = join(this.globalRoot, 'runtime', 'USER.md')
|
||||
const memoryPath = join(this.globalRoot, 'runtime', 'MEMORY.md')
|
||||
if (!(await stat(userPath).catch(() => undefined))) await atomicWrite(userPath, '# USER\n\n')
|
||||
if (!(await stat(memoryPath).catch(() => undefined))) await atomicWrite(memoryPath, '# MEMORY\n\n')
|
||||
const initPath = join(this.globalRoot, 'state', 'init.json')
|
||||
if (!(await stat(initPath).catch(() => undefined))) await atomicWrite(initPath, JSON.stringify({ version: 1, globalReady: true, createdAt: new Date().toISOString() }, null, 2) + '\n')
|
||||
await this.repairProjectionsIfDirty()
|
||||
return meta
|
||||
})
|
||||
}
|
||||
/** First use in a project creates its .dsh/brain and a stable project space. */
|
||||
async ensureProject(workspace?: string): Promise<JsonMemoryStore> {
|
||||
await this.ensureGlobal()
|
||||
const root = this.fixedProjectRoot ?? join(this.projectBaseFor(workspace), '.dsh', 'brain')
|
||||
const base = projectBaseOf(root)
|
||||
const cached = this.workspaces.get(root)
|
||||
if (cached !== undefined) return cached.store
|
||||
return withFileLock(join(root, '.init.lock'), async () => {
|
||||
const again = this.workspaces.get(root)
|
||||
if (again !== undefined) return again.store
|
||||
const id = projectIdFor(root)
|
||||
await mkdir(join(root, 'documents'), { recursive: true })
|
||||
await mkdir(join(root, 'state'), { recursive: true })
|
||||
const store = new JsonMemoryStore(join(root, 'memory-space'), 'project', id)
|
||||
await store.init('项目记忆')
|
||||
const documents = new JsonDocumentStore(join(root, 'documents'))
|
||||
await documents.init()
|
||||
await writeGitIgnore(base)
|
||||
const mappingPath = join(this.globalRoot, 'state', 'projects.json')
|
||||
await withFileLock(join(this.globalRoot, 'state', '.projects.lock'), async () => {
|
||||
const mapping = await readJson<Record<string, { root: string; updatedAt: string }>>(mappingPath, {})
|
||||
mapping[id] = { root, updatedAt: new Date().toISOString() }
|
||||
await atomicWrite(mappingPath, JSON.stringify(mapping, null, 2) + '\n')
|
||||
})
|
||||
const state = { root, store, documents }
|
||||
this.workspaces.set(root, state)
|
||||
return store
|
||||
})
|
||||
}
|
||||
/** Public alias used by callers that initialize explicit local memory. */
|
||||
async initialize(workspace?: string): Promise<{ global: LocalSpaceMeta; project: LocalSpaceMeta }> { return this.ensure(workspace) }
|
||||
async ensure(workspace?: string): Promise<{ global: LocalSpaceMeta; project: LocalSpaceMeta }> {
|
||||
const global = await this.ensureGlobal()
|
||||
const projectStore = await this.ensureProject(workspace)
|
||||
const project = await projectStore.spaceMeta()
|
||||
return { global, project: project ?? { id: projectStore.spaceId, scope: 'project', name: '项目记忆', root: projectStore.root, createdAt: new Date().toISOString(), active: true } }
|
||||
}
|
||||
/** Add one memory and regenerate the compact projections. */
|
||||
async remember(input: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; projectionPending?: boolean; projectionError?: string }> {
|
||||
const workspace = this.workspacePath()
|
||||
const scope = input.scope ?? 'project'
|
||||
const store = await this.storeFor(scope, workspace)
|
||||
await this.markProjectionDirty()
|
||||
const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) })
|
||||
if (result.duplicate) return result
|
||||
return { ...result, ...(await this.tryRegenerateProjections()) }
|
||||
}
|
||||
async add(input: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; projectionPending?: boolean; projectionError?: string }> { return this.remember(input) }
|
||||
async read(id: string, workspace?: string): Promise<LocalMemoryRecord | undefined> {
|
||||
const globalRecord = await this.globalStore.read(id)
|
||||
if (globalRecord !== undefined) return globalRecord
|
||||
return (await this.ensureProject(workspace)).read(id)
|
||||
}
|
||||
private async collectHits(query: string, workspace?: string, projectId?: string): Promise<{ record: LocalMemoryRecord; score: number }[]> {
|
||||
const projectStore = await this.ensureProject(workspace)
|
||||
const globalHits = await this.globalStore.search(query, 1000)
|
||||
const projectHits = await projectStore.search(query, 1000)
|
||||
const scoped = [...projectHits, ...globalHits].filter(({ record }) => {
|
||||
if (projectId === undefined || projectId === '') return true
|
||||
if (projectId === 'global') return record.scope === 'global'
|
||||
return record.scope === 'project' && record.projectId === projectId
|
||||
})
|
||||
const seen = new Set<string>()
|
||||
return scoped.filter(({ record }) => { if (seen.has(record.id)) return false; seen.add(record.id); return true })
|
||||
.sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt))
|
||||
}
|
||||
async searchHits(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise<{ record: LocalMemoryRecord; score: number }[]> {
|
||||
const hits = await this.collectHits(query, workspace, projectId)
|
||||
const limit = Math.max(1, Math.min(100, Math.trunc(k)))
|
||||
return hits.slice(0, limit)
|
||||
}
|
||||
async search(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise<LocalMemoryRecord[]> {
|
||||
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record)
|
||||
}
|
||||
async list(options: { limit?: number; offset?: number } = {}, workspace?: string, projectId?: string): Promise<{ items: LocalMemoryRecord[]; total: number }> {
|
||||
const projectStore = await this.ensureProject(workspace)
|
||||
const records = [...(await this.globalStore.records()), ...(await projectStore.records())]
|
||||
const scoped = records.filter((record) => {
|
||||
if (projectId === undefined || projectId === '') return true
|
||||
if (projectId === 'global') return record.scope === 'global'
|
||||
return record.scope === 'project' && record.projectId === projectId
|
||||
})
|
||||
const seen = new Set<string>()
|
||||
const ordered = scoped.filter((record) => { if (seen.has(record.id)) return false; seen.add(record.id); return true })
|
||||
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id))
|
||||
const offset = Math.max(0, Math.trunc(options.offset ?? 0))
|
||||
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)))
|
||||
return { items: ordered.slice(offset, offset + limit), total: ordered.length }
|
||||
}
|
||||
async forget(id: string, expectedRevision?: number, workspace?: string): Promise<LocalMemoryRecord> {
|
||||
const globalRecord = await this.globalStore.read(id)
|
||||
await this.markProjectionDirty()
|
||||
if (globalRecord !== undefined) { const removed = await this.globalStore.forget(id, expectedRevision); await this.tryRegenerateProjections(); return removed }
|
||||
const store = await this.ensureProject(workspace)
|
||||
const removed = await store.forget(id, expectedRevision)
|
||||
await this.tryRegenerateProjections()
|
||||
return removed
|
||||
}
|
||||
async projects(workspace?: string): Promise<{ id: string; name: string }[]> {
|
||||
const global = await this.globalStore.spaceMeta()
|
||||
const root = this.projectRootFor(workspace)
|
||||
const project = await this.projectStoreFor(workspace).spaceMeta()
|
||||
return [...(global === undefined ? [] : [{ id: 'global', name: '全局记忆' }]), { id: project?.id ?? projectIdFor(root), name: '项目记忆' }]
|
||||
}
|
||||
async documents(workspace?: string): Promise<LocalDocument[]> {
|
||||
const root = this.projectRootFor(workspace)
|
||||
return new JsonDocumentStore(join(root, 'documents')).list()
|
||||
}
|
||||
async addDocument(input: { title: string; content: string; source?: string; tags?: string[] }, workspace?: string): Promise<LocalDocument> {
|
||||
const store = await this.ensureProject(workspace)
|
||||
void store
|
||||
const root = this.projectRootFor(workspace)
|
||||
const documents = this.workspaces.get(root)?.documents
|
||||
if (documents === undefined) throw new Error('local_documents_unavailable')
|
||||
return documents.add(input)
|
||||
}
|
||||
async storageStatus(workspace?: string): Promise<Record<string, unknown>> {
|
||||
const projectRoot = this.projectRootFor(workspace)
|
||||
const global = await this.globalStore.spaceMeta()
|
||||
const project = await this.projectStoreFor(workspace).spaceMeta()
|
||||
return { provider: 'local', globalRoot: this.globalRoot, projectRoot, spaces: { global: global ?? null, project: project ?? null }, cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false }
|
||||
}
|
||||
/** Return the compact per-turn projection used by the system prompt. */
|
||||
projectionText(limit = 2000): string {
|
||||
const read = (path: string): string => { try { return readFileSync(path, 'utf8').trim() } catch { return '' } }
|
||||
const user = read(join(this.globalRoot, 'runtime', 'USER.md'))
|
||||
const memory = read(join(this.globalRoot, 'runtime', 'MEMORY.md'))
|
||||
if (user === '' && memory === '') return ''
|
||||
const cut = (text: string): string => text.length > limit ? text.slice(0, limit) + '\n…' : text
|
||||
return ['## dsh-brain local memory', '### USER.md', cut(user || '(empty)'), '### MEMORY.md', cut(memory || '(empty)')].join('\n')
|
||||
}
|
||||
/** Generate USER.md/MEMORY.md from explicit profile/rule records only. */
|
||||
async regenerateProjections(): Promise<void> {
|
||||
const marker = await this.markProjectionDirty()
|
||||
await withFileLock(join(this.globalRoot, 'state', '.projection.lock'), async () => {
|
||||
try {
|
||||
const runtimeFile = join(this.globalRoot, 'runtime', 'memories.json')
|
||||
const mirrorFile = join(this.globalRoot, 'spaces', 'global', 'memories.json')
|
||||
const data = await readFile(runtimeFile, 'utf8').catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return undefined; throw error })
|
||||
if (data !== undefined) await atomicWrite(mirrorFile, data)
|
||||
const records = await this.globalStore.records()
|
||||
const user = records.filter((record) => record.category === 'preference' || record.category === 'identity')
|
||||
const rules = records.filter((record) => record.category === 'rule')
|
||||
const render = (title: string, items: LocalMemoryRecord[]): string => '# ' + title + '\n\n' + items.map((record) => '- ' + record.content.replace(/\n/g, ' ') + ' *(rev ' + String(record.revision) + ', ' + record.source + ')*').join('\n') + (items.length === 0 ? '' : '\n')
|
||||
await atomicWrite(join(this.globalRoot, 'runtime', 'USER.md'), render('USER', user))
|
||||
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules))
|
||||
await this.clearProjectionDirty(marker)
|
||||
} catch (error) {
|
||||
await this.markProjectionDirty(error)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
/** Incremental, privacy-preserving summary: only explicit text is stored. */
|
||||
async summarizeConversation(input: { sessionId: string; turns: LocalTurn[]; summary?: string }, workspace?: string): Promise<{ stored: number; duplicates: number; documentId?: string; skipped: boolean; projectionPending?: boolean; projectionError?: string }> {
|
||||
if (this.settingsOf().autoSummaryEnabled === false) return { stored: 0, duplicates: 0, skipped: true }
|
||||
await this.ensureProject(workspace)
|
||||
await this.markProjectionDirty()
|
||||
return withFileLock(join(this.globalRoot, 'state', '.sessions.lock'), async () => {
|
||||
const checkpointPath = join(this.globalRoot, 'state', 'sessions.json')
|
||||
const checkpoints = await readJson<Record<string, SessionCheckpoint>>(checkpointPath, {})
|
||||
const prior = checkpoints[input.sessionId]
|
||||
const processed = new Set(prior?.processed ?? [])
|
||||
const fresh = input.turns.filter((turn) => turn.turnId === undefined || !processed.has(turn.turnId))
|
||||
let stored = 0; let duplicates = 0
|
||||
for (const turn of fresh) {
|
||||
const user = (turn.user ?? '').trim(); if (user === '' || containsSecret(user)) continue
|
||||
for (const sentence of user.split(/[\n。!?!?]/).map((item) => item.trim()).filter((item) => item !== '')) {
|
||||
if (/(这次|本次|今天|暂时|临时|只此一次|一次性)/.test(sentence)) continue
|
||||
if (!/(记住|长期|以后|今后|往后|每次|永远|始终|总是|从来不|我一向|我(?:喜欢|偏好|习惯|希望|要求)|规则|偏好|习惯|from now on|remember|prefer)/i.test(sentence)) continue
|
||||
const category = /(总是|始终|必须|不要|别|规则|要求|always|never|must)/i.test(sentence) ? 'rule' : 'preference'
|
||||
if (category === 'preference' && this.settingsOf().autoProfileEnabled === false) continue
|
||||
const result = await this.globalStore.add({ content: sentence, category, source: 'session:' + input.sessionId, sessionId: input.sessionId, tags: ['auto-summary'] })
|
||||
if (result.duplicate) duplicates += 1; else stored += 1
|
||||
}
|
||||
}
|
||||
const nextCount = (prior?.count ?? 0) + fresh.length
|
||||
const processedNext = new Set(processed)
|
||||
for (const turn of fresh) if (turn.turnId !== undefined) processedNext.add(turn.turnId)
|
||||
let documentId: string | undefined
|
||||
if (fresh.length > 0) {
|
||||
const documents = this.workspaces.get(this.projectRootFor(workspace))?.documents
|
||||
if (documents === undefined) throw new Error('local_documents_unavailable')
|
||||
const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] })
|
||||
documentId = document.id
|
||||
}
|
||||
const lastTurn = prior?.lastTurn
|
||||
const lastCandidate = fresh.map((turn) => turn.turnId).filter((value): value is string => value !== undefined).at(-1)
|
||||
const lastValue = lastCandidate === undefined ? lastTurn : lastTurn === undefined ? lastCandidate : (Number.isFinite(Number(lastCandidate)) && Number.isFinite(Number(lastTurn)) ? (Number(lastCandidate) >= Number(lastTurn) ? lastCandidate : lastTurn) : lastTurn)
|
||||
checkpoints[input.sessionId] = { ...(lastValue === undefined ? {} : { lastTurn: lastValue }), count: nextCount, processed: [...processedNext].slice(-1000) }
|
||||
await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n')
|
||||
if (stored > 0) { const repair = await this.tryRegenerateProjections(); return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair } }
|
||||
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false }
|
||||
})
|
||||
}
|
||||
/** Add an explicit profile entry; inferred entries stay in the pending area. */
|
||||
async proposeProfile(content: string, source = 'user', inferred = false): Promise<LocalMemoryRecord> {
|
||||
if (this.settingsOf().autoProfileEnabled === false) throw new Error('auto_profile_disabled')
|
||||
await this.ensureGlobal(); await this.markProjectionDirty(); const result = await this.globalStore.add({ content, category: inferred ? 'profile-pending' : 'preference', source, tags: ['profile'] }); if (!inferred) await this.tryRegenerateProjections(); return result.record
|
||||
}
|
||||
async confirmProfile(id: string): Promise<void> { await this.ensureGlobal(); await this.markProjectionDirty(); const record = await this.globalStore.read(id); if (record === undefined) throw new Error('memory_not_found'); await this.globalStore.update(id, { category: 'preference' }); await this.tryRegenerateProjections() }
|
||||
/** Correct an existing profile entry in place; the revision increments and prior text is not kept as a live entry. */
|
||||
async correctProfile(id: string, content: string, expectedRevision?: number): Promise<LocalMemoryRecord> { await this.ensureGlobal(); await this.markProjectionDirty(); const record = await this.globalStore.update(id, { content, category: 'preference' }, expectedRevision); await this.tryRegenerateProjections(); return record }
|
||||
/** Copy the whole global memory root into backups; no source file is removed. */
|
||||
async createBackup(): Promise<{ path: string }> {
|
||||
await this.ensureGlobal()
|
||||
const path = join(this.globalRoot, 'backups', 'backup-' + new Date().toISOString().replace(/[:.]/g, '-'))
|
||||
await mkdir(path, { recursive: true })
|
||||
for (const entry of await readdir(this.globalRoot, { withFileTypes: true })) {
|
||||
if (entry.name === 'backups') continue
|
||||
await cp(join(this.globalRoot, entry.name), join(path, entry.name), { recursive: true, force: false })
|
||||
}
|
||||
return { path }
|
||||
}
|
||||
/** Report legacy .mnemon locations without deleting anything. */
|
||||
async legacyMigrationReport(workspace?: string): Promise<{ found: string[]; targetGlobal: string; targetProject: string }> {
|
||||
const found: string[] = []
|
||||
for (const path of [join(this.projectBaseFor(workspace), '.mnemon'), join(dshHome(), '.mnemon')]) { if (await stat(path).catch(() => undefined) !== undefined) found.push(path) }
|
||||
return { found, targetGlobal: this.globalRoot, targetProject: this.projectRootFor(workspace) }
|
||||
}
|
||||
private async findLegacyMemoryFiles(root: string): Promise<string[]> {
|
||||
const out: string[] = []
|
||||
const walk = async (dir: string): Promise<void> => {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) { await walk(full); continue }
|
||||
if (/^(memories|memory)\.json$/i.test(entry.name) || /\.memory\.json$/i.test(entry.name)) out.push(full)
|
||||
}
|
||||
}
|
||||
await walk(root)
|
||||
return out
|
||||
}
|
||||
private legacyRecordsFrom(value: unknown): Record<string, unknown>[] {
|
||||
if (Array.isArray(value)) return value.filter((item): item is Record<string, unknown> => item !== null && typeof item === 'object' && !Array.isArray(item))
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) return []
|
||||
const record = value as Record<string, unknown>
|
||||
for (const key of ['records', 'memories', 'items']) {
|
||||
if (Array.isArray(record[key])) return this.legacyRecordsFrom(record[key])
|
||||
}
|
||||
return record.content === undefined && record.text === undefined && record.memory === undefined ? [] : [record]
|
||||
}
|
||||
private async importLegacyRecords(sourcePath: string, workspace?: string): Promise<{ imported: number; duplicates: number; skipped: number; ids: string[]; scope: LocalMemoryScope; workspace?: string }> {
|
||||
const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(sourcePath)
|
||||
const scope: LocalMemoryScope = projectLegacy ? 'project' : 'global'
|
||||
const store = await this.storeFor(scope, workspace)
|
||||
let imported = 0; let duplicates = 0; let skipped = 0; const ids: string[] = []
|
||||
for (const file of await this.findLegacyMemoryFiles(sourcePath)) {
|
||||
let parsed: unknown
|
||||
try { parsed = JSON.parse(await readFile(file, 'utf8')) } catch { skipped += 1; continue }
|
||||
for (const item of this.legacyRecordsFrom(parsed)) {
|
||||
const content = typeof item.content === 'string' ? item.content : typeof item.text === 'string' ? item.text : typeof item.memory === 'string' ? item.memory : ''
|
||||
if (content.trim() === '') { skipped += 1; continue }
|
||||
const category = typeof item.category === 'string' ? item.category : typeof item.sector === 'string' ? item.sector : undefined
|
||||
const tags = Array.isArray(item.tags) ? item.tags.filter((tag): tag is string => typeof tag === 'string') : []
|
||||
const legacyId = typeof item.id === 'string' ? item.id : ''
|
||||
const operationId = 'legacy-' + localMemoryHash(file + '|' + legacyId + '|' + content)
|
||||
try {
|
||||
const result = await store.add({ content, ...(category === undefined ? {} : { category }), tags, source: 'legacy:' + file, operationId, scope, ...(scope === 'project' ? { projectId: projectIdFor(this.projectRootFor(workspace)) } : {}) })
|
||||
if (result.duplicate) duplicates += 1
|
||||
else imported += 1
|
||||
// Content-only duplicates were present before this migration and
|
||||
// must never enter this migration's rollback ownership list.
|
||||
if ((!result.duplicate || result.duplicateKind === 'operation') && !ids.includes(result.record.id)) ids.push(result.record.id)
|
||||
} catch { skipped += 1 }
|
||||
}
|
||||
}
|
||||
return { imported, duplicates, skipped, ids, scope, ...(workspace === undefined ? {} : { workspace }) }
|
||||
}
|
||||
/** Copy a legacy directory into backups; never moves or deletes the source. */
|
||||
|
||||
async migrateLegacy(path: string, workspace?: string): Promise<{ copiedTo: string; imported: number; duplicates: number; skipped: number; partial: boolean }> {
|
||||
return withFileLock(join(this.globalRoot, 'state', '.migrations.lock'), async () => {
|
||||
const target = join(this.globalRoot, 'backups', 'migration-' + Date.now().toString(36) + '-' + randomUUID().slice(0, 8))
|
||||
await mkdir(this.globalRoot, { recursive: true })
|
||||
await cp(path, target, { recursive: true, force: false })
|
||||
await this.markProjectionDirty()
|
||||
const manifestPath = join(this.globalRoot, 'state', 'migrations.json')
|
||||
const manifest = await readJson<Array<{ source: string; copiedTo: string; createdAt: string; status?: string; error?: string; importedIds?: string[]; imported?: number; duplicates?: number; skipped?: number; targetScope?: LocalMemoryScope; workspace?: string; partial?: boolean; rollback?: { staging?: string; destination?: string; status?: string } }>>(manifestPath, [])
|
||||
const resolvedWorkspace = this.workspacePath(workspace)
|
||||
const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(path)
|
||||
const targetScope: LocalMemoryScope = projectLegacy ? 'project' : 'global'
|
||||
const entry: any = { source: path, copiedTo: target, createdAt: new Date().toISOString(), status: 'importing', importedIds: [] as string[], targetScope, workspace: resolvedWorkspace }
|
||||
manifest.push(entry)
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
|
||||
try {
|
||||
const imported = await this.importLegacyRecords(path, workspace)
|
||||
entry.importedIds = imported.ids
|
||||
entry.status = imported.skipped > 0 ? 'partial' : 'complete'
|
||||
Object.assign(entry, { imported: imported.imported, duplicates: imported.duplicates, skipped: imported.skipped, partial: imported.skipped > 0 })
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
|
||||
return { copiedTo: target, imported: imported.imported, duplicates: imported.duplicates, skipped: imported.skipped, partial: imported.skipped > 0 }
|
||||
} catch (error) {
|
||||
entry.status = 'error'
|
||||
entry.error = error instanceof Error ? error.message : String(error)
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n').catch(() => {})
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
/** Restore a prepared backup first, then remove imported records; retries resume safely. */
|
||||
async rollbackMigration(copiedTo: string, destination?: string): Promise<{ restoredTo: string; removedImported: number; projectionPending?: boolean; projectionError?: string }> {
|
||||
return withFileLock(join(this.globalRoot, 'state', '.migrations.lock'), async () => {
|
||||
const manifestPath = join(this.globalRoot, 'state', 'migrations.json')
|
||||
const manifest = await readJson<Array<{ copiedTo?: string; importedIds?: string[]; targetScope?: LocalMemoryScope; workspace?: string; status?: string; error?: string; rollback?: { staging?: string; destination?: string; status?: string } }>>(manifestPath, [])
|
||||
const entry = manifest.find((item) => item.copiedTo === copiedTo)
|
||||
if (entry === undefined) throw new Error('migration_not_found')
|
||||
const backupStat = await stat(copiedTo).catch(() => undefined)
|
||||
if (backupStat === undefined || !backupStat.isDirectory()) throw new Error('migration_backup_missing')
|
||||
const completedDestination = entry.rollback?.destination
|
||||
if (entry.rollback?.status === 'complete' && completedDestination !== undefined) {
|
||||
return { restoredTo: completedDestination, removedImported: 0 }
|
||||
}
|
||||
if (completedDestination !== undefined && destination !== undefined && resolve(completedDestination) !== resolve(destination)) {
|
||||
throw new Error('restore_destination_mismatch')
|
||||
}
|
||||
const restoredTo = completedDestination ?? destination ?? join(this.globalRoot, 'backups', 'restore-' + Date.now().toString(36))
|
||||
const destinationStat = await stat(restoredTo).catch(() => undefined)
|
||||
if (destinationStat !== undefined && !destinationStat.isDirectory()) throw new Error('restore_destination_not_directory')
|
||||
entry.rollback = entry.rollback ?? {}
|
||||
entry.rollback.destination = restoredTo
|
||||
if (entry.rollback.staging === undefined || !(await stat(entry.rollback.staging).catch(() => undefined))?.isDirectory()) {
|
||||
const staging = join(this.globalRoot, 'backups', '.restore-' + Date.now().toString(36) + '-' + randomUUID())
|
||||
await cp(copiedTo, staging, { recursive: true, force: false })
|
||||
entry.rollback.staging = staging
|
||||
}
|
||||
const rollbackStatus = entry.rollback.status
|
||||
if (rollbackStatus === 'complete') {
|
||||
if ((await readdir(restoredTo).catch(() => [])).length > 0) throw new Error('restore_destination_not_empty')
|
||||
await cp(copiedTo, restoredTo, { recursive: true, force: false })
|
||||
if (await treeDigest(copiedTo) !== await treeDigest(restoredTo)) throw new Error('restore_copy_incomplete')
|
||||
return { restoredTo, removedImported: 0 }
|
||||
}
|
||||
if (rollbackStatus === undefined || rollbackStatus === 'prepared') {
|
||||
entry.rollback.status = 'prepared'
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
|
||||
}
|
||||
// Land the restore copy before touching the active store. A conflicting
|
||||
// child in the destination therefore fails with the active store intact.
|
||||
if (rollbackStatus !== 'copied' && rollbackStatus !== 'records_removed' && rollbackStatus !== 'complete') {
|
||||
if ((await readdir(restoredTo).catch(() => [])).length > 0) throw new Error('restore_destination_not_empty')
|
||||
await cp(entry.rollback.staging, restoredTo, { recursive: true, force: false })
|
||||
if (await treeDigest(entry.rollback.staging) !== await treeDigest(restoredTo)) throw new Error('restore_copy_incomplete')
|
||||
entry.rollback.status = 'copied'
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
|
||||
}
|
||||
if (rollbackStatus === 'copied') {
|
||||
const copyStat = await stat(restoredTo).catch(() => undefined)
|
||||
if (copyStat === undefined || !copyStat.isDirectory()) throw new Error('restore_copy_missing')
|
||||
if (await treeDigest(restoredTo) !== await treeDigest(copiedTo)) throw new Error('restore_copy_incomplete')
|
||||
}
|
||||
const store = entry.targetScope === 'project' ? await this.storeFor('project', entry.workspace) : this.globalStore
|
||||
let removedImported = 0
|
||||
if (rollbackStatus !== 'records_removed' && rollbackStatus !== 'complete') {
|
||||
for (const id of entry.importedIds ?? []) {
|
||||
try { await store.forget(id); removedImported += 1 }
|
||||
catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
if (message.includes('memory_not_found')) continue
|
||||
throw new Error('rollback_record_failed: ' + message)
|
||||
}
|
||||
}
|
||||
entry.rollback.status = 'records_removed'
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
|
||||
}
|
||||
await rm(entry.rollback.staging, { recursive: true, force: true }).catch(() => {})
|
||||
entry.rollback.status = 'complete'
|
||||
entry.status = 'rolled_back'
|
||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
|
||||
const projection = removedImported > 0 ? await this.tryRegenerateProjections() : { projectionPending: false }
|
||||
return { restoredTo, removedImported, ...projection }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
/** A MemoryRemote implementation backed entirely by local files. */
|
||||
import type { AddResponse, CloudResult, ListResponse, MemoryHit, ProjectsResponse, SearchResponse } from '../api.ts'
|
||||
import type { MemoryRemote } from '../memory/remote.ts'
|
||||
import type { LocalMemoryManager } from './manager.ts'
|
||||
import type { LocalMemoryRecord } from './types.ts'
|
||||
|
||||
function hitOf(record: LocalMemoryRecord): MemoryHit {
|
||||
return { id: record.id, content: record.content, tags: record.tags, project_id: record.projectId ?? null, primary_sector: record.category, revision: record.revision, created_at: Date.parse(record.createdAt), updated_at: Date.parse(record.updatedAt) }
|
||||
}
|
||||
function ok<T>(data: T): CloudResult<T> { return { ok: true, status: 200, data } }
|
||||
|
||||
export class LocalMemoryRemote implements MemoryRemote {
|
||||
constructor(private readonly manager: LocalMemoryManager) {}
|
||||
private run<T>(workspace: string | undefined, job: () => Promise<T>): Promise<T> {
|
||||
return workspace === undefined ? job() : this.manager.withWorkspace(workspace, job)
|
||||
}
|
||||
async search(query: string, k: number, project?: string, workspace?: string): Promise<CloudResult<SearchResponse>> {
|
||||
return this.run(workspace, async () => {
|
||||
const records = await this.manager.search(query, k, workspace, project)
|
||||
const matches = records.map(hitOf)
|
||||
return ok({ matches, total: matches.length, search_mode: 'local' })
|
||||
})
|
||||
}
|
||||
async read(id: string, workspace?: string): Promise<CloudResult<MemoryHit>> {
|
||||
return this.run(workspace, async () => {
|
||||
const record = await this.manager.read(id, workspace)
|
||||
if (record === undefined) return { ok: false, error: { status: 404, code: 'memory_not_found', message: '记忆不存在' } }
|
||||
return ok(hitOf(record))
|
||||
})
|
||||
}
|
||||
async add(input: { content: string; tags?: string[]; project?: string; sector?: string; operationId: string }, workspace?: string): Promise<CloudResult<AddResponse>> {
|
||||
return this.run(workspace, async () => {
|
||||
const result = await this.manager.remember({ content: input.content, tags: input.tags, category: input.sector, source: 'memory_tool', operationId: input.operationId, scope: input.project === 'global' ? 'global' : 'project' })
|
||||
return ok({ id: result.record.id, revision: result.record.revision, state: 'stored', remote_saved: true })
|
||||
})
|
||||
}
|
||||
async list(options: { limit?: number; offset?: number; project?: string } = {}, workspace?: string): Promise<CloudResult<ListResponse>> {
|
||||
return this.run(workspace, async () => {
|
||||
const page = await this.manager.list({ limit: options.limit, offset: options.offset }, workspace, options.project)
|
||||
return ok({ items: page.items.map(hitOf), total: page.total })
|
||||
})
|
||||
}
|
||||
async projects(workspace?: string): Promise<CloudResult<ProjectsResponse>> {
|
||||
return this.run(workspace, async () => ok({ projects: await this.manager.projects(workspace) }))
|
||||
}
|
||||
async storageStatus(workspace?: string): Promise<CloudResult<Record<string, unknown>>> {
|
||||
return this.run(workspace, async () => ok(await this.manager.storageStatus(workspace)))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
/** Atomic JSON storage for one local memory space. */
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import type { LocalDocument, LocalMemoryAddInput, LocalMemoryRecord, LocalMemorySearchHit, LocalMemorySpaceScope, LocalSpaceMeta } from './types.ts'
|
||||
|
||||
interface MemoryFile { version: 1; nextChange: number; operations: Record<string, string>; records: LocalMemoryRecord[] }
|
||||
const EMPTY_FILE: MemoryFile = { version: 1, nextChange: 1, operations: {}, records: [] }
|
||||
function nowIso(): string { return new Date().toISOString() }
|
||||
const SECRET_PATTERNS = [
|
||||
/(?:api[ _-]?key|access[ _-]?token|client[ _-]?secret|secret|password|passwd|pwd)\s*(?:是|为|[:=:])\s*["']?[A-Za-z0-9_\-./+=]{6,}/i,
|
||||
/(?:密码|口令|令牌|密钥|恢复码)\s*(?:是|为|[:=:])\s*\S{6,}/,
|
||||
/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
|
||||
/\bBearer\s+[A-Za-z0-9\-._~+/]+=*/i,
|
||||
]
|
||||
/** Secrets never belong in a memory record or an automatic summary. */
|
||||
export function containsSecret(value: string): boolean { return SECRET_PATTERNS.some((pattern) => pattern.test(value)) }
|
||||
function safeText(value: unknown, max = 64000): string { return typeof value === 'string' ? value.trim().slice(0, max) : '' }
|
||||
function tagsOf(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
const tags = value.filter((item): item is string => typeof item === 'string').map((item) => item.trim()).filter((item) => item !== '')
|
||||
return [...new Set(tags)].slice(0, 20)
|
||||
}
|
||||
async function atomicWrite(path: string, content: string): Promise<void> {
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const tmp = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp'
|
||||
try {
|
||||
await writeFile(tmp, content, { encoding: 'utf8', mode: 0o600 })
|
||||
await rename(tmp, path)
|
||||
} catch (error) {
|
||||
await rm(tmp, { force: true }).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
export async function withFileLock<T>(lockPath: string, job: () => Promise<T>): Promise<T> {
|
||||
await mkdir(dirname(lockPath), { recursive: true })
|
||||
const started = Date.now()
|
||||
let handle: Awaited<ReturnType<typeof open>> | undefined
|
||||
while (handle === undefined) {
|
||||
try { handle = await open(lockPath, 'wx', 0o600) }
|
||||
catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code
|
||||
if (code !== 'EEXIST') throw error
|
||||
const info = await stat(lockPath).catch(() => undefined)
|
||||
if (info !== undefined && Date.now() - info.mtimeMs > 60000) { await rm(lockPath, { force: true }).catch(() => {}); continue }
|
||||
if (Date.now() - started > 10000) throw new Error('local_memory_lock_timeout')
|
||||
await new Promise((resolve) => setTimeout(resolve, 40))
|
||||
}
|
||||
}
|
||||
try { return await job() } finally { await handle.close().catch(() => {}); await rm(lockPath, { force: true }).catch(() => {}) }
|
||||
}
|
||||
|
||||
export class JsonMemoryStore {
|
||||
readonly root: string
|
||||
readonly scope: LocalMemorySpaceScope
|
||||
readonly spaceId: string
|
||||
readonly dataPath: string
|
||||
readonly metaPath: string
|
||||
private readonly lockPath: string
|
||||
constructor(root: string, scope: LocalMemorySpaceScope, spaceId: string) {
|
||||
this.root = root; this.scope = scope; this.spaceId = spaceId
|
||||
this.dataPath = join(root, 'memories.json'); this.metaPath = join(root, 'space.json'); this.lockPath = join(root, '.lock')
|
||||
}
|
||||
async init(name = this.scope === 'global' ? '全局记忆' : '项目记忆'): Promise<LocalSpaceMeta> {
|
||||
await mkdir(this.root, { recursive: true })
|
||||
return withFileLock(this.lockPath, async () => {
|
||||
const existing = await this.spaceMeta(); if (existing !== undefined) return existing
|
||||
const meta: LocalSpaceMeta = { id: this.spaceId, scope: this.scope, name, root: this.root, createdAt: nowIso(), active: true }
|
||||
await atomicWrite(this.metaPath, JSON.stringify(meta, null, 2) + '\n'); return meta
|
||||
})
|
||||
}
|
||||
async setActive(active: boolean): Promise<LocalSpaceMeta> {
|
||||
return withFileLock(this.lockPath, async () => {
|
||||
const existing = await this.spaceMeta()
|
||||
if (existing === undefined) throw new Error('local_memory_space_not_found')
|
||||
const next = { ...existing, active }
|
||||
await atomicWrite(this.metaPath, JSON.stringify(next, null, 2) + '\n')
|
||||
return next
|
||||
})
|
||||
}
|
||||
async spaceMeta(): Promise<LocalSpaceMeta | undefined> {
|
||||
let text: string
|
||||
try { text = await readFile(this.metaPath, 'utf8') }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
|
||||
throw new Error(`local_memory_meta_read_failed: ${this.metaPath}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
let parsed: unknown
|
||||
try { parsed = JSON.parse(text) }
|
||||
catch { throw new Error(`local_memory_meta_corrupt: ${this.metaPath}`) }
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`local_memory_meta_corrupt: ${this.metaPath}`)
|
||||
const value = parsed as Record<string, unknown>
|
||||
if (typeof value.id !== 'string' || (value.scope !== 'global' && value.scope !== 'project' && value.scope !== 'department')) throw new Error(`local_memory_meta_incompatible: ${this.metaPath}`)
|
||||
return { id: value.id, scope: value.scope, name: typeof value.name === 'string' ? value.name : value.id, root: typeof value.root === 'string' ? value.root : this.root, createdAt: typeof value.createdAt === 'string' ? value.createdAt : nowIso(), active: value.active !== false }
|
||||
}
|
||||
private async readFile(): Promise<MemoryFile> {
|
||||
let text: string
|
||||
try { text = await readFile(this.dataPath, 'utf8') }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY_FILE, operations: {}, records: [] }
|
||||
throw new Error(`local_memory_read_failed: ${this.dataPath}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
let parsed: unknown
|
||||
try { parsed = JSON.parse(text) }
|
||||
catch { throw new Error(`local_memory_corrupt: ${this.dataPath}`) }
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`local_memory_corrupt: ${this.dataPath}`)
|
||||
const value = parsed as Partial<MemoryFile>
|
||||
if (value.version !== undefined && value.version !== 1) throw new Error(`local_memory_incompatible: ${this.dataPath}`)
|
||||
if (value.records !== undefined && !Array.isArray(value.records)) throw new Error(`local_memory_incompatible: ${this.dataPath}`)
|
||||
return { version: 1, nextChange: typeof value.nextChange === 'number' && Number.isFinite(value.nextChange) ? value.nextChange : 1, operations: value.operations !== null && typeof value.operations === 'object' && !Array.isArray(value.operations) ? value.operations : {}, records: Array.isArray(value.records) ? value.records.filter((record): record is LocalMemoryRecord => record !== null && typeof record === 'object') : [] }
|
||||
}
|
||||
private async writeFile(file: MemoryFile): Promise<void> { await atomicWrite(this.dataPath, JSON.stringify(file, null, 2) + '\n') }
|
||||
private activeRecords(file: MemoryFile): LocalMemoryRecord[] { return file.records.filter((record) => record.deleted !== true) }
|
||||
async add(input: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; duplicateKind?: 'operation' | 'content' }> {
|
||||
const content = safeText(input.content); if (content === '') throw new Error('记忆内容不能为空'); if (containsSecret(content)) throw new Error('secret_not_allowed')
|
||||
return withFileLock(this.lockPath, async () => {
|
||||
const file = await this.readFile()
|
||||
if (input.operationId !== undefined && input.operationId !== '') { const prior = file.operations[input.operationId]; if (prior !== undefined) { const found = file.records.find((record) => record.id === prior); if (found !== undefined && found.deleted !== true) return { record: found, duplicate: true, duplicateKind: 'operation' } } }
|
||||
const duplicate = this.activeRecords(file).find((record) => record.content === content && record.spaceId === this.spaceId)
|
||||
if (duplicate !== undefined) return { record: duplicate, duplicate: true, duplicateKind: 'content' }
|
||||
const timestamp = nowIso()
|
||||
const record: LocalMemoryRecord = { id: 'lm_' + randomUUID(), scope: this.scope, spaceId: this.spaceId, content, ...(input.category === undefined || input.category === '' ? {} : { category: input.category }), tags: tagsOf(input.tags), source: safeText(input.source, 500) || 'local', ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }), ...(input.projectId === undefined ? {} : { projectId: input.projectId }), ...(input.departmentId === undefined ? {} : { departmentId: input.departmentId }), createdAt: timestamp, updatedAt: timestamp, revision: 1, changeSeq: file.nextChange, ...(input.operationId === undefined ? {} : { operationId: input.operationId }) }
|
||||
file.nextChange += 1; file.records.push(record); if (input.operationId !== undefined && input.operationId !== '') file.operations[input.operationId] = record.id
|
||||
await this.writeFile(file); return { record, duplicate: false }
|
||||
})
|
||||
}
|
||||
async read(id: string): Promise<LocalMemoryRecord | undefined> { return this.activeRecords(await this.readFile()).find((record) => record.id === id) }
|
||||
async search(query: string, k = 5): Promise<LocalMemorySearchHit[]> {
|
||||
const file = await this.readFile(); const q = query.trim().toLowerCase(); const terms = q.split(/\s+/).filter((term) => term !== '')
|
||||
return this.activeRecords(file).map((record) => { const haystack = (record.content + '\n' + (record.tags ?? []).join(' ') + '\n' + (record.category ?? '')).toLowerCase(); const score = terms.length === 0 ? 1 : terms.reduce((sum, term) => sum + (haystack.includes(term) ? 1 : 0), 0); return { record, score } }).filter((hit) => terms.length === 0 || hit.score > 0).sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)).slice(0, Math.max(1, Math.min(100, Math.trunc(k))))
|
||||
}
|
||||
async list(options: { limit?: number; offset?: number } = {}): Promise<{ items: LocalMemoryRecord[]; total: number }> {
|
||||
const file = await this.readFile(); const records = this.activeRecords(file).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); const offset = Math.max(0, Math.trunc(options.offset ?? 0)); const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50))); return { items: records.slice(offset, offset + limit), total: records.length }
|
||||
}
|
||||
async update(id: string, patch: { content?: string; tags?: string[]; category?: string }, expectedRevision?: number): Promise<LocalMemoryRecord> {
|
||||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined) throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision) throw new Error('revision_conflict'); if (patch.content !== undefined) { const content = safeText(patch.content); if (content === '') throw new Error('记忆内容不能为空'); if (containsSecret(content)) throw new Error('secret_not_allowed'); record.content = content } if (patch.tags !== undefined) record.tags = tagsOf(patch.tags); if (patch.category !== undefined) record.category = patch.category; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record })
|
||||
}
|
||||
async forget(id: string, expectedRevision?: number): Promise<LocalMemoryRecord> {
|
||||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined) throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision) throw new Error('revision_conflict'); record.deleted = true; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record })
|
||||
}
|
||||
async records(): Promise<LocalMemoryRecord[]> { return this.activeRecords(await this.readFile()) }
|
||||
}
|
||||
|
||||
interface DocumentFile { version: 1; nextRevision: number; documents: LocalDocument[] }
|
||||
export class JsonDocumentStore {
|
||||
readonly root: string; private readonly indexPath: string; private readonly lockPath: string
|
||||
constructor(root: string) { this.root = root; this.indexPath = join(root, 'index.json'); this.lockPath = join(root, '.lock') }
|
||||
async init(): Promise<void> { await mkdir(this.root, { recursive: true }); await mkdir(join(this.root, 'files'), { recursive: true }) }
|
||||
private async read(): Promise<DocumentFile> {
|
||||
let text: string
|
||||
try { text = await readFile(this.indexPath, 'utf8') }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { version: 1, nextRevision: 1, documents: [] }
|
||||
throw new Error(`local_documents_read_failed: ${this.indexPath}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
let parsed: unknown
|
||||
try { parsed = JSON.parse(text) }
|
||||
catch { throw new Error(`local_documents_corrupt: ${this.indexPath}`) }
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`local_documents_corrupt: ${this.indexPath}`)
|
||||
const value = parsed as Partial<DocumentFile>
|
||||
if (value.documents !== undefined && !Array.isArray(value.documents)) throw new Error(`local_documents_incompatible: ${this.indexPath}`)
|
||||
return { version: 1, nextRevision: typeof value.nextRevision === 'number' ? value.nextRevision : 1, documents: Array.isArray(value.documents) ? value.documents : [] }
|
||||
}
|
||||
private async write(file: DocumentFile): Promise<void> { await atomicWrite(this.indexPath, JSON.stringify(file, null, 2) + '\n') }
|
||||
async add(input: { title: string; content: string; source?: string; tags?: string[] }): Promise<LocalDocument> {
|
||||
const title = safeText(input.title, 500); const content = safeText(input.content, 200000); if (title === '' || content === '') throw new Error('文档标题和内容不能为空'); if (containsSecret(title) || containsSecret(content)) throw new Error('secret_not_allowed')
|
||||
return withFileLock(this.lockPath, async () => { const file = await this.read(); const duplicate = file.documents.find((document) => document.deleted !== true && document.title === title && document.content === content); if (duplicate !== undefined) { const filePath = join(this.root, 'files', duplicate.id + '.md'); if ((await readFile(filePath).catch(() => undefined)) === undefined) await atomicWrite(filePath, '# ' + title + '\n\n' + content + '\n'); return duplicate } const timestamp = nowIso(); const document: LocalDocument = { id: 'doc_' + randomUUID(), title, content, source: safeText(input.source, 500) || 'local', tags: tagsOf(input.tags), createdAt: timestamp, updatedAt: timestamp, revision: 1 }; file.documents.push(document); await this.write(file); await atomicWrite(join(this.root, 'files', document.id + '.md'), '# ' + title + '\n\n' + content + '\n'); return document })
|
||||
}
|
||||
async list(): Promise<LocalDocument[]> { return (await this.read()).documents.filter((document) => document.deleted !== true) }
|
||||
async readDocument(id: string): Promise<LocalDocument | undefined> { return (await this.read()).documents.find((document) => document.id === id && document.deleted !== true) }
|
||||
async remove(id: string): Promise<void> { await withFileLock(this.lockPath, async () => { const file = await this.read(); const document = file.documents.find((item) => item.id === id && item.deleted !== true); if (document === undefined) return; document.deleted = true; document.revision += 1; document.updatedAt = nowIso(); await this.write(file) }) }
|
||||
}
|
||||
|
||||
export function localMemoryHash(value: string): string { return createHash('sha256').update(value).digest('hex') }
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
/** Local-first memory records and public result types. */
|
||||
export type LocalMemoryScope = 'global' | 'project'
|
||||
/** Physical scope of a stored memory; departments reuse the same store with isolated ownership. */
|
||||
export type LocalMemorySpaceScope = LocalMemoryScope | 'department'
|
||||
|
||||
export interface LocalMemoryRecord {
|
||||
/** Stable unique id. */
|
||||
id: string
|
||||
scope: LocalMemorySpaceScope
|
||||
spaceId: string
|
||||
content: string
|
||||
category?: string
|
||||
tags: string[]
|
||||
source: string
|
||||
sessionId?: string
|
||||
projectId?: string
|
||||
departmentId?: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
revision: number
|
||||
deleted?: boolean
|
||||
/** Local monotonic change number; not a cloud change_id. */
|
||||
changeSeq: number
|
||||
operationId?: string
|
||||
}
|
||||
|
||||
export interface LocalSpaceMeta {
|
||||
id: string
|
||||
scope: LocalMemorySpaceScope
|
||||
name: string
|
||||
root: string
|
||||
createdAt: string
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export interface LocalMemoryAddInput {
|
||||
content: string
|
||||
category?: string
|
||||
tags?: string[]
|
||||
source?: string
|
||||
sessionId?: string
|
||||
projectId?: string
|
||||
departmentId?: string
|
||||
operationId?: string
|
||||
scope?: LocalMemoryScope
|
||||
}
|
||||
|
||||
export interface LocalMemorySearchHit {
|
||||
record: LocalMemoryRecord
|
||||
score: number
|
||||
}
|
||||
|
||||
export interface LocalDocument {
|
||||
id: string
|
||||
title: string
|
||||
content: string
|
||||
source: string
|
||||
tags: string[]
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
revision: number
|
||||
deleted?: boolean
|
||||
}
|
||||
|
||||
export interface LocalMemorySettings {
|
||||
localMemoryEnabled?: boolean
|
||||
cloudMemoryEnabled?: boolean
|
||||
autoMemorySpaces?: boolean
|
||||
autoSummaryEnabled?: boolean
|
||||
autoProfileEnabled?: boolean
|
||||
localMemoryK?: number
|
||||
}
|
||||
|
|
@ -30,12 +30,12 @@ export interface MemoryConnection {
|
|||
|
||||
/** The remote surface the memory bundle consumes (a client subset). */
|
||||
export interface MemoryRemote {
|
||||
search(query: string, k: number, project?: string): Promise<CloudResult<SearchResponse>>
|
||||
read(id: string): Promise<CloudResult<MemoryHit>>
|
||||
add(input: { content: string; tags?: string[]; project?: string; sector?: string; operationId: string }): Promise<CloudResult<AddResponse>>
|
||||
list(options?: { limit?: number; offset?: number; project?: string }): Promise<CloudResult<ListResponse>>
|
||||
projects(): Promise<CloudResult<ProjectsResponse>>
|
||||
storageStatus(): Promise<CloudResult<Record<string, unknown>>>
|
||||
search(query: string, k: number, project?: string, workspace?: string): Promise<CloudResult<SearchResponse>>
|
||||
read(id: string, workspace?: string): Promise<CloudResult<MemoryHit>>
|
||||
add(input: { content: string; tags?: string[]; project?: string; sector?: string; operationId: string }, workspace?: string): Promise<CloudResult<AddResponse>>
|
||||
list(options?: { limit?: number; offset?: number; project?: string }, workspace?: string): Promise<CloudResult<ListResponse>>
|
||||
projects(workspace?: string): Promise<CloudResult<ProjectsResponse>>
|
||||
storageStatus(workspace?: string): Promise<CloudResult<Record<string, unknown>>>
|
||||
}
|
||||
|
||||
/** How the composition root hands remotes to the memory bundle. */
|
||||
|
|
|
|||
|
|
@ -28,6 +28,10 @@ export interface MemoryToolDeps {
|
|||
memoryToken: () => string
|
||||
/** Effective settings. */
|
||||
settings: () => { enabled: boolean; defaultK: number }
|
||||
/** True when the local-first store is available; then no cloud token is required. */
|
||||
localMemory?: () => boolean
|
||||
/** Resolve the workspace from the tool execution context. */
|
||||
workspace?: (exec?: unknown) => string | undefined
|
||||
}
|
||||
|
||||
/** Text block shape the harness renders. */
|
||||
|
|
@ -66,15 +70,17 @@ export function renderJson(_args: unknown, value: unknown): TextBlock[] {
|
|||
}
|
||||
|
||||
/** Assert the memory scope is usable, or throw a message the model can act on. */
|
||||
export function requireMemoryToken(deps: { memoryToken: () => string; settings: () => { enabled: boolean } }): string {
|
||||
export function requireMemoryToken(deps: { memoryToken: () => string; settings: () => { enabled: boolean }; localMemory?: () => boolean }): string {
|
||||
if (!deps.settings().enabled) {
|
||||
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。')
|
||||
throw new Error('记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。')
|
||||
}
|
||||
// Local-first mode needs no credential and wins unless cloud mode was
|
||||
// explicitly selected and configured. If local memory is off, only a
|
||||
// configured cloud credential may select the cloud adapter.
|
||||
if (deps.localMemory?.() === true) return ''
|
||||
const token = deps.memoryToken()
|
||||
if (token === '') {
|
||||
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。')
|
||||
}
|
||||
return token
|
||||
if (token !== '') return token
|
||||
throw new Error('记忆功能未启用或未配置令牌。请在 /dsh-brain 页面开启本地记忆,或填入 mem_… / cmt_… 记忆令牌。')
|
||||
}
|
||||
|
||||
/** Search stored memories by keyword. */
|
||||
|
|
@ -108,14 +114,15 @@ function searchTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
|||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
const workspace = deps.workspace?.(exec)
|
||||
requireMemoryToken(deps)
|
||||
const query = typeof args.query === 'string' ? args.query.trim() : ''
|
||||
if (query === '') throw new Error('query 不能为空。')
|
||||
const requested = typeof args.k === 'number' && Number.isFinite(args.k) ? Math.trunc(args.k) : deps.settings().defaultK
|
||||
const k = Math.min(1000, Math.max(1, requested))
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||
const result = await deps.remote().search(query, k, project)
|
||||
const result = await deps.remote().search(query, k, project, workspace)
|
||||
if (!result.ok) throw new Error(`检索失败:${describeError(result.error)}`)
|
||||
const matches = result.data.matches ?? []
|
||||
return {
|
||||
|
|
@ -145,11 +152,12 @@ function readTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
|||
schema: { type: 'object', properties: { id: { type: 'string' }, content: { type: 'string' } }, required: ['id'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
const workspace = deps.workspace?.(exec)
|
||||
requireMemoryToken(deps)
|
||||
const id = typeof args.id === 'string' ? args.id.trim() : ''
|
||||
if (id === '') throw new Error('id 不能为空。')
|
||||
const result = await deps.remote().read(id)
|
||||
const result = await deps.remote().read(id, workspace)
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 404) throw new Error(`没有找到 id=${id} 的记忆(可能已删除)。`)
|
||||
throw new Error(`读取失败:${describeError(result.error)}`)
|
||||
|
|
@ -193,7 +201,8 @@ function addTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
|||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
const workspace = deps.workspace?.(exec)
|
||||
requireMemoryToken(deps)
|
||||
const content = typeof args.content === 'string' ? args.content : ''
|
||||
if (content.trim() === '') throw new Error('content 不能为空。')
|
||||
|
|
@ -205,7 +214,7 @@ function addTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
|||
const sector = typeof args.sector === 'string' && (SECTORS as readonly string[]).includes(args.sector) ? args.sector : undefined
|
||||
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : ''
|
||||
const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID()
|
||||
const result = await deps.remote().add({ content, tags, project, sector, operationId })
|
||||
const result = await deps.remote().add({ content, tags, project, sector, operationId }, workspace)
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。')
|
||||
|
|
@ -241,14 +250,15 @@ function listTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
|||
schema: { type: 'object', properties: { total: { type: 'number' }, items: { type: 'array', items: { type: 'object' } } }, required: ['items'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
const workspace = deps.workspace?.(exec)
|
||||
requireMemoryToken(deps)
|
||||
const rawLimit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : 20
|
||||
const limit = Math.min(100, Math.max(1, rawLimit))
|
||||
const rawOffset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0
|
||||
const offset = Math.max(0, rawOffset)
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||
const result = await deps.remote().list({ limit, offset, project })
|
||||
const result = await deps.remote().list({ limit, offset, project }, workspace)
|
||||
if (!result.ok) throw new Error(`列表读取失败:${describeError(result.error)}`)
|
||||
const items = result.data.items ?? []
|
||||
return { total: result.data.total ?? items.length, items: items.map(toHitView) }
|
||||
|
|
@ -266,9 +276,10 @@ function projectsTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
|||
schema: { type: 'object', properties: { projects: { type: 'array', items: { type: 'object' } } }, required: ['projects'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(): Promise<unknown> {
|
||||
async execute(_args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
const workspace = deps.workspace?.(exec)
|
||||
requireMemoryToken(deps)
|
||||
const result = await deps.remote().projects()
|
||||
const result = await deps.remote().projects(workspace)
|
||||
|
||||
if (!result.ok) throw new Error(`项目列表读取失败:${describeError(result.error)}`)
|
||||
return { projects: result.data.projects ?? [] }
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { MemoryProviderDescriptor } from 'dsh-mnemon-source-memory-spaces/provider-sdk'
|
||||
import type { MemoryProviderDescriptor } from './fork/provider-sdk.ts'
|
||||
|
||||
/**
|
||||
* Browser-safe metadata for the LongMemory Provider.
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ import type {
|
|||
ProviderSpaceStatus,
|
||||
RememberRequest,
|
||||
SearchRequest,
|
||||
} from 'dsh-mnemon-source-memory-spaces/provider-sdk'
|
||||
} from './fork/provider-sdk.ts'
|
||||
import type { MemoryHit } from '../api.ts'
|
||||
import type { MemoryConnection, MemoryRemote, MemoryRemoteFactory } from '../memory/remote.ts'
|
||||
import { descriptor } from './descriptor.ts'
|
||||
|
|
@ -71,6 +71,40 @@ export function insightFromHit(hit: MemoryHit): Insight | undefined {
|
|||
return insight
|
||||
}
|
||||
|
||||
/** Coarse write state reported to the host. */
|
||||
export type WriteReceiptAction = 'stored' | 'pending' | 'unknown'
|
||||
|
||||
/**
|
||||
* Classify a LongMemory write receipt without trusting it.
|
||||
*
|
||||
* The service may stage a write (remote_saved:false / state:'pending'), may
|
||||
* answer with a bare 200 and no usable body, or may return fields of the
|
||||
* wrong type. An explicit `state` wins over every other hint; a receipt that
|
||||
* says the write is staged can never be promoted to `stored` by an id or a
|
||||
* revision. Unknown state values and malformed fields degrade to `unknown`
|
||||
* instead of throwing or guessing.
|
||||
*/
|
||||
export function classifyWriteReceipt(receipt: unknown): WriteReceiptAction {
|
||||
if (receipt === null || typeof receipt !== 'object' || Array.isArray(receipt)) return 'unknown'
|
||||
const body = receipt as Record<string, unknown>
|
||||
const state = typeof body.state === 'string' ? body.state.trim().toLowerCase() : ''
|
||||
if (state !== '') {
|
||||
if (state === 'pending' || state === 'queued') return 'pending'
|
||||
if (state === 'stored' || state === 'saved' || state === 'completed') {
|
||||
// The explicit state says saved, but a contradictory remote_saved:false
|
||||
// still means the write is only staged — never report it as stored.
|
||||
return body.remote_saved === false ? 'pending' : 'stored'
|
||||
}
|
||||
return 'unknown'
|
||||
}
|
||||
if (typeof body.remote_saved === 'boolean') return body.remote_saved ? 'stored' : 'pending'
|
||||
// Older servers answer with just the created id (and sometimes revision);
|
||||
// that is the only remaining signal that the write reached the store.
|
||||
if (typeof body.id === 'string' && body.id !== '') return 'stored'
|
||||
if (typeof body.revision === 'number' && Number.isFinite(body.revision)) return 'stored'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
export class LongMemoryProvider implements MemoryProviderAdapter {
|
||||
readonly id = descriptor.id
|
||||
/** LongMemory scores are its own scale; the host may only order by them. */
|
||||
|
|
@ -207,12 +241,29 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
if (!result.ok) {
|
||||
throw new Error(`LongMemory remember failed: ${result.error.message}`)
|
||||
}
|
||||
// The write receipt decides what to report — the service may stage the
|
||||
// write (remote_saved:false) or answer with a bare 200 and no usable
|
||||
// body, and claiming `stored` then would be a lie the UI repeats.
|
||||
const receipt: unknown = result.data
|
||||
const action = classifyWriteReceipt(receipt)
|
||||
const record = receipt !== null && typeof receipt === 'object' && !Array.isArray(receipt)
|
||||
? receipt as Record<string, unknown>
|
||||
: {}
|
||||
const id = typeof record.id === 'string' && record.id !== '' ? record.id : undefined
|
||||
const revision = typeof record.revision === 'number' && Number.isFinite(record.revision)
|
||||
? record.revision
|
||||
: undefined
|
||||
const summary = action === 'stored'
|
||||
? 'Stored in LongMemory (live).'
|
||||
: action === 'pending'
|
||||
? 'Queued by LongMemory; not yet confirmed as saved.'
|
||||
: 'LongMemory accepted the write but the receipt does not confirm storage; state unknown.'
|
||||
return {
|
||||
action: 'stored',
|
||||
action,
|
||||
provider: this.id,
|
||||
summary: 'Stored in LongMemory (live).',
|
||||
...(result.data.id === undefined ? {} : { id: result.data.id }),
|
||||
...(result.data.revision === undefined ? {} : { revision: result.data.revision }),
|
||||
summary,
|
||||
...(id === undefined ? {} : { id }),
|
||||
...(revision === undefined ? {} : { revision }),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -222,6 +273,15 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
const resolved = this.resolve(body)
|
||||
const result = await this.client(resolved).read(id)
|
||||
if (!result.ok) return undefined
|
||||
// The read is exact-id, so the service may return a memory from ANY
|
||||
// project the account can see. A space explicitly bound to one project
|
||||
// must not leak hits from another, while the account-wide default space
|
||||
// (no projectId) intentionally reads every project the token can access.
|
||||
const spaceProject = resolved.projectId
|
||||
if (spaceProject !== undefined) {
|
||||
const hitProject = result.data.project_id
|
||||
if (typeof hitProject !== 'string' || hitProject !== spaceProject) return undefined
|
||||
}
|
||||
return insightFromHit(result.data)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2026 dsh-external contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
# Mnemon Provider SDK Fork
|
||||
|
||||
This directory is the vendored, source-compatible fork of the Mnemon Memory
|
||||
Spaces Provider SDK used by dsh-brain's `mnemon-provider` entry.
|
||||
|
||||
- Upstream repository: `omdsh-dev/dsh-mnemon`
|
||||
- Upstream revision: `8b650ab5ef33522e03887b250b13336593daa26f` (0.5.54)
|
||||
- Upstream package: `dsh-mnemon-source-memory-spaces` 0.5.54
|
||||
- License: MIT, Copyright (c) 2026 dsh-external contributors
|
||||
- Fork package identity: `dsh-brain-mnemon-provider-sdk` (internal source path)
|
||||
- Plugin identifiers owned by dsh-brain are prefixed `dsh-brain-`; this fork
|
||||
does not register upstream tool, route or service ids.
|
||||
|
||||
## Why this directory exists
|
||||
|
||||
The previous phase kept `dsh-mnemon-source-memory-spaces` as an optional peer
|
||||
dependency even though only its Provider protocol types and helpers were used.
|
||||
That made dsh-brain's local-first memory depend on a separate installation of
|
||||
the upstream package. The source in this directory is a pinned fork snapshot of
|
||||
the subset dsh-brain actually needs, so the package can build and run without
|
||||
the upstream peer. The complete upstream source is vendored at
|
||||
`vendor/dsh-mnemon`; `docs/MNEMON_FORK.md` records provenance and sync rules.
|
||||
|
||||
## Sync rule
|
||||
|
||||
To update the fork, check out the new upstream revision, re-copy the files below
|
||||
from `plugins/dsh-mnemon-source-memory-spaces/src`, keep the local contract
|
||||
adapter at the top of `contracts.ts`, then run:
|
||||
|
||||
```bash
|
||||
npm run typecheck
|
||||
npm run build
|
||||
node verify-mnemon-fork.mjs
|
||||
node verify-mnemon-provider.mjs
|
||||
```
|
||||
|
||||
Files mirrored: `contracts.ts`, `provider-sdk.ts`,
|
||||
`providers/{adapter,definitions,http,process}.ts`.
|
||||
|
|
@ -0,0 +1,714 @@
|
|||
/**
|
||||
* Forked from dsh-mnemon-source-memory-spaces 0.5.54.
|
||||
* Upstream: omdsh-dev/dsh-mnemon @ 8b650ab5ef33522e03887b250b13336593daa26f
|
||||
* Copyright (c) 2026 dsh-external contributors. MIT licensed; see ./LICENSE.
|
||||
*/
|
||||
export type MemoryJsonPrimitive = string | number | boolean | null
|
||||
export type MemoryJsonValue = MemoryJsonPrimitive | MemoryJsonValue[] | { [key: string]: MemoryJsonValue }
|
||||
export type JsonValue = MemoryJsonValue
|
||||
export type MemoryViewConsistencyMode = 'exact-snapshot' | 'namespace-pinned-live-read'
|
||||
export interface MemoryReadGrant {
|
||||
id: string
|
||||
sourceInstanceKey: string
|
||||
schema: string
|
||||
value: MemoryJsonValue
|
||||
revision: string
|
||||
consistency: MemoryViewConsistencyMode
|
||||
}
|
||||
|
||||
export type MemoryProviderId = string
|
||||
|
||||
export const NATIVE_PROVIDER_ID = 'mnemon-native'
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 10_000
|
||||
export const DEFAULT_RECALL_LIMIT = 10
|
||||
export const DEFAULT_RECALL_QUALITY_POLICY = 'strict-v1'
|
||||
|
||||
export function isNativeProvider(provider: { readonly id: MemoryProviderId; readonly typeId?: string | undefined }): boolean {
|
||||
return (provider.typeId ?? provider.id) === NATIVE_PROVIDER_ID
|
||||
}
|
||||
|
||||
export type MemoryProviderConnectionValue = string | number | boolean
|
||||
export type MemoryProviderConnection = Record<string, MemoryProviderConnectionValue>
|
||||
|
||||
export interface MemoryProviderIcon {
|
||||
kind: 'brand' | 'data-url' | 'glyph'
|
||||
value: string
|
||||
}
|
||||
|
||||
export interface MemoryProviderConfigOption {
|
||||
value: string
|
||||
label: string
|
||||
i18nKey?: string
|
||||
}
|
||||
|
||||
export interface MemoryProviderConfigField {
|
||||
key: string
|
||||
label: string
|
||||
i18nKey?: string
|
||||
scope: 'service' | 'memory'
|
||||
role?: 'global-location'
|
||||
input: 'text' | 'url' | 'secret' | 'number' | 'boolean' | 'select' | 'path'
|
||||
required: boolean
|
||||
defaultValue?: MemoryProviderConnectionValue
|
||||
placeholder?: string
|
||||
help?: string
|
||||
min?: number
|
||||
max?: number
|
||||
maxLength?: number
|
||||
pattern?: string
|
||||
normalize?: 'trim-trailing-slash'
|
||||
validationMessage?: string
|
||||
discoveryDefaultFrom?: string
|
||||
options?: MemoryProviderConfigOption[]
|
||||
}
|
||||
|
||||
export const MEMORY_PLACEMENT_CAPABILITIES = ['graph', 'entities', 'related', 'exact-write', 'link', 'forget'] as const
|
||||
export type MemoryPlacementCapability = (typeof MEMORY_PLACEMENT_CAPABILITIES)[number]
|
||||
export type MemoryPlacementPreference = 'balanced' | 'local-first' | 'shared-first'
|
||||
|
||||
export interface MemoryPlacementRules {
|
||||
allowedProviderIds?: MemoryProviderId[]
|
||||
dataBoundary?: 'allow-remote' | 'local-only'
|
||||
requiredCapabilities?: MemoryPlacementCapability[]
|
||||
preference?: MemoryPlacementPreference
|
||||
}
|
||||
|
||||
export interface MemoryPersistenceStrategy {
|
||||
mode?: 'manual' | 'automatic'
|
||||
providerId?: MemoryProviderId
|
||||
prompt?: string
|
||||
rules?: MemoryPlacementRules
|
||||
providerConnections?: Partial<Record<MemoryProviderId, MemoryProviderConnection>>
|
||||
}
|
||||
|
||||
export interface ResolvedMemoryPersistenceStrategy {
|
||||
mode: 'manual' | 'automatic'
|
||||
providerId: MemoryProviderId
|
||||
providerDefaulted?: true
|
||||
prompt: string
|
||||
rules: {
|
||||
allowedProviderIds: MemoryProviderId[]
|
||||
dataBoundary: 'allow-remote' | 'local-only'
|
||||
requiredCapabilities: MemoryPlacementCapability[]
|
||||
preference: MemoryPlacementPreference
|
||||
}
|
||||
providerConnections: Partial<Record<MemoryProviderId, MemoryProviderConnection>>
|
||||
}
|
||||
|
||||
export interface AutomaticMemoryPlacementRequest {
|
||||
mode: 'automatic'
|
||||
prompt?: string
|
||||
rules?: MemoryPlacementRules
|
||||
}
|
||||
|
||||
export interface MemoryPlacementDecision {
|
||||
mode: 'automatic'
|
||||
providerId: MemoryProviderId
|
||||
decidedBy: 'rules' | 'llm'
|
||||
reason: string
|
||||
confidence: 'high' | 'medium' | 'low'
|
||||
candidateProviderIds: MemoryProviderId[]
|
||||
appliedRules: string[]
|
||||
decidedAt: string
|
||||
runId?: string
|
||||
subagentProvider?: string
|
||||
}
|
||||
|
||||
export interface MemoryProviderCapabilities {
|
||||
search: boolean
|
||||
browse: boolean
|
||||
graph: boolean
|
||||
entities: boolean
|
||||
related: boolean
|
||||
remember: boolean
|
||||
link: boolean
|
||||
forget: boolean
|
||||
writeMode: 'exact' | 'async-extracting'
|
||||
deletionMode: 'soft' | 'hard' | 'unsupported'
|
||||
}
|
||||
|
||||
export interface MemoryProviderDescriptor {
|
||||
typeId?: string
|
||||
id: MemoryProviderId
|
||||
label: string
|
||||
icon?: MemoryProviderIcon
|
||||
kind: 'local' | 'remote'
|
||||
workspaceBinding: 'automatic' | 'optional-override' | 'provider-global'
|
||||
summary: string
|
||||
summaryI18nKey?: string
|
||||
origin: 'native' | 'third-party'
|
||||
capabilities: MemoryProviderCapabilities
|
||||
fields: MemoryProviderConfigField[]
|
||||
serviceConfigured?: boolean
|
||||
}
|
||||
|
||||
export interface MemoryProviderServiceView {
|
||||
providerId: MemoryProviderId
|
||||
enabled: boolean
|
||||
configured: boolean
|
||||
settings: MemoryProviderConnection
|
||||
configuredSecrets: string[]
|
||||
secretValues?: MemoryProviderConnection
|
||||
}
|
||||
|
||||
export interface MemoryProviderServiceCatalog {
|
||||
providers: MemoryProviderDescriptor[]
|
||||
items: MemoryProviderServiceView[]
|
||||
generatedAt: string
|
||||
}
|
||||
|
||||
export interface UpdateMemoryProviderServiceRequest {
|
||||
providerId: MemoryProviderId
|
||||
settings: MemoryProviderConnection
|
||||
enabled?: boolean
|
||||
clearSecrets?: string[]
|
||||
}
|
||||
|
||||
export interface MemoryProviderRuntimeStatus {
|
||||
providerId: MemoryProviderId
|
||||
label: string
|
||||
icon?: MemoryProviderIcon
|
||||
enabled: boolean
|
||||
configured: boolean
|
||||
status: 'disabled' | 'idle' | 'healthy' | 'unhealthy'
|
||||
memoryBodyCount: number
|
||||
activeMemoryBodyCount: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface MemorySpaceProvider {
|
||||
id: MemoryProviderId
|
||||
typeId?: string
|
||||
label: string
|
||||
icon?: MemoryProviderIcon
|
||||
origin?: 'native' | 'third-party'
|
||||
kind: 'local' | 'remote'
|
||||
location: string
|
||||
targetUri?: string
|
||||
account?: string
|
||||
user?: string
|
||||
actorPeerId?: string
|
||||
apiKeyConfigured: boolean
|
||||
settings: MemoryProviderConnection
|
||||
configuredSecrets: string[]
|
||||
capabilities: MemoryProviderCapabilities
|
||||
}
|
||||
|
||||
export interface OpenVikingSpaceConnection {
|
||||
endpoint: string
|
||||
targetUri: string
|
||||
apiKey?: string
|
||||
account?: string
|
||||
user?: string
|
||||
actorPeerId?: string
|
||||
}
|
||||
|
||||
export interface MemorySpace {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
active: boolean
|
||||
dbPath: string
|
||||
provider: MemorySpaceProvider
|
||||
placement?: MemoryPlacementDecision
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface CreateMemorySpaceRequest {
|
||||
name: string
|
||||
description: string
|
||||
active?: boolean
|
||||
providerId?: MemoryProviderId
|
||||
connection?: MemoryProviderConnection
|
||||
providerConnections?: Partial<Record<MemoryProviderId, MemoryProviderConnection>>
|
||||
openViking?: OpenVikingSpaceConnection
|
||||
placement?: AutomaticMemoryPlacementRequest
|
||||
}
|
||||
|
||||
export interface UpdateMemorySpaceRequest {
|
||||
name?: string
|
||||
description?: string
|
||||
active?: boolean
|
||||
connection?: MemoryProviderConnection
|
||||
clearSecrets?: string[]
|
||||
openViking?: Partial<OpenVikingSpaceConnection> & { clearApiKey?: boolean }
|
||||
}
|
||||
|
||||
export interface MemorySpaceMetadataUpdate {
|
||||
memoryBodyId: string
|
||||
title: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface MemorySpaceMetadataMaintenanceResult {
|
||||
delegated: true
|
||||
runId: string
|
||||
provider: string
|
||||
summary: string
|
||||
updates: MemorySpaceMetadataUpdate[]
|
||||
}
|
||||
|
||||
export type Category = 'preference' | 'decision' | 'fact' | 'insight' | 'context' | 'general'
|
||||
export const CATEGORIES = ['preference', 'decision', 'fact', 'insight', 'context', 'general'] as const satisfies readonly Category[]
|
||||
export type Source = 'user' | 'agent' | 'external'
|
||||
export const SOURCES = ['user', 'agent', 'external'] as const satisfies readonly Source[]
|
||||
export type EdgeType = 'temporal' | 'semantic' | 'causal' | 'entity'
|
||||
export const EDGE_TYPES = ['temporal', 'semantic', 'causal', 'entity'] as const satisfies readonly EdgeType[]
|
||||
export type Intent = 'WHY' | 'WHEN' | 'ENTITY' | 'GENERAL'
|
||||
export const INTENTS = ['WHY', 'WHEN', 'ENTITY', 'GENERAL'] as const satisfies readonly Intent[]
|
||||
|
||||
export type RecallRelevanceTier = 'high' | 'medium' | 'ranked' | 'low' | 'unknown'
|
||||
|
||||
export function normalizeEntityKey(entity: string): string {
|
||||
return entity.normalize('NFKC').trim().toLocaleLowerCase()
|
||||
}
|
||||
|
||||
export interface Insight {
|
||||
id: string
|
||||
content: string
|
||||
category?: string
|
||||
importance?: number
|
||||
tags?: string[]
|
||||
entities?: string[]
|
||||
source?: string
|
||||
score?: number
|
||||
normalizedScore?: number
|
||||
relevanceTier?: RecallRelevanceTier
|
||||
federatedScore?: number
|
||||
confidence?: string
|
||||
intent?: string
|
||||
matchedVia?: string
|
||||
createdAt?: string
|
||||
depth?: number
|
||||
edgeType?: string
|
||||
memoryBodyId?: string
|
||||
memoryBodyName?: string
|
||||
memoryProviderId?: MemoryProviderId
|
||||
memoryProviderLabel?: string
|
||||
memoryCapabilities?: MemoryProviderCapabilities
|
||||
externalUri?: string
|
||||
}
|
||||
|
||||
export interface SearchRequest {
|
||||
query: string
|
||||
mode?: 'smart' | 'keyword' | 'basic'
|
||||
limit?: number
|
||||
category?: Category
|
||||
source?: Source
|
||||
intent?: Intent
|
||||
memoryBodyIds?: string[]
|
||||
inspect?: boolean
|
||||
}
|
||||
|
||||
export interface RememberRequest {
|
||||
content: string
|
||||
category?: Category
|
||||
importance?: number
|
||||
tags?: string[]
|
||||
entities?: string[]
|
||||
source?: Source
|
||||
memoryBodyId?: string
|
||||
}
|
||||
|
||||
export interface MemorySpaceStats {
|
||||
totalInsights: number
|
||||
deletedInsights: number
|
||||
edgeCount: number
|
||||
oplogCount: number
|
||||
dbSizeBytes: number
|
||||
byCategory: Record<string, number>
|
||||
topEntities: Array<{ entity: string; count: number }>
|
||||
}
|
||||
|
||||
export interface MemorySpaceView extends MemorySpace {
|
||||
mnemonDefault: boolean
|
||||
providerEnabled?: boolean
|
||||
healthy: boolean
|
||||
statusLoading?: boolean
|
||||
error?: string
|
||||
stats?: MemorySpaceStats
|
||||
}
|
||||
|
||||
export interface MemorySpaceWriteScopeRequest {
|
||||
viewId: string
|
||||
grant: MemoryReadGrant
|
||||
}
|
||||
|
||||
export interface MemorySpaceWriteScope {
|
||||
viewId: string
|
||||
sourceInstanceKey: string
|
||||
memoryBodyIds: string[]
|
||||
}
|
||||
|
||||
export interface MemorySpaceCatalog {
|
||||
items: MemorySpaceView[]
|
||||
providers: MemoryProviderDescriptor[]
|
||||
persistenceStrategy?: Omit<ResolvedMemoryPersistenceStrategy, 'providerConnections'>
|
||||
total: number
|
||||
activeCount: number
|
||||
directory: string
|
||||
generatedAt: string
|
||||
writeScope?: MemorySpaceWriteScope
|
||||
rediscovery?: { running: boolean; last?: MemorySpaceRediscovery }
|
||||
}
|
||||
|
||||
export interface MemorySpaceRediscoveryResult {
|
||||
providerId: MemoryProviderId
|
||||
label: string
|
||||
found: number
|
||||
added: Array<{ id: string; name: string }>
|
||||
disconnected: number
|
||||
error?: string
|
||||
timedOut?: boolean
|
||||
}
|
||||
|
||||
export interface MemorySpaceRediscovery {
|
||||
at: string
|
||||
trigger: 'startup' | 'manual'
|
||||
results: MemorySpaceRediscoveryResult[]
|
||||
}
|
||||
|
||||
export interface MemoryGraphNode extends Insight {
|
||||
color: string
|
||||
graphId?: string
|
||||
kind?: 'memory' | 'entity' | 'space'
|
||||
memoryBodyIds?: string[]
|
||||
memoryBodyNames?: string[]
|
||||
occurrenceCount?: number
|
||||
}
|
||||
|
||||
export interface MemoryGraphEdge {
|
||||
sourceId: string
|
||||
targetId: string
|
||||
label: string
|
||||
color: string
|
||||
type?: EdgeType | 'scope'
|
||||
}
|
||||
|
||||
export interface MemoryGraphSnapshot {
|
||||
nodes: MemoryGraphNode[]
|
||||
edges: MemoryGraphEdge[]
|
||||
generatedAt: string
|
||||
memoryBodies?: Array<Pick<MemorySpace, 'id' | 'name' | 'active'>>
|
||||
sources?: MemoryReadSource[]
|
||||
}
|
||||
|
||||
export type MemoryReadMode = 'search' | 'graph' | 'projection' | 'enumerable' | 'query-only' | 'entities' | 'unsupported'
|
||||
export type MemoryReadStatus = 'ready' | 'empty' | 'query-required' | 'unsupported' | 'unavailable' | 'loading'
|
||||
|
||||
export interface MemoryReadSource {
|
||||
memoryBodyId: string
|
||||
memoryBodyName: string
|
||||
providerId: MemoryProviderId
|
||||
providerLabel: string
|
||||
mode: MemoryReadMode
|
||||
status: MemoryReadStatus
|
||||
itemCount: number
|
||||
edgeCount?: number
|
||||
memoryCount?: number
|
||||
complete?: boolean
|
||||
hint?: string
|
||||
quality?: RecallQualityStats
|
||||
}
|
||||
|
||||
export interface RecallQualityStats {
|
||||
policyId: string
|
||||
fallbackFrom?: string
|
||||
fetched: number
|
||||
retained: number
|
||||
selected: number
|
||||
droppedLowScore: number
|
||||
droppedNonPositiveScore: number
|
||||
droppedInvalidScore: number
|
||||
unscored: number
|
||||
unscaled: number
|
||||
ranked?: number
|
||||
outOfRange?: number
|
||||
}
|
||||
|
||||
export interface MemoryListRequest {
|
||||
query?: string
|
||||
category?: Category
|
||||
limit?: number
|
||||
memoryBodyIds?: string[]
|
||||
}
|
||||
|
||||
export interface MemoryListView {
|
||||
items: MemoryGraphNode[]
|
||||
total: number
|
||||
generatedAt: string
|
||||
sources?: MemoryReadSource[]
|
||||
}
|
||||
|
||||
export interface MemorySpaceMetadataSample {
|
||||
memoryBodyId: string
|
||||
name: string
|
||||
description: string
|
||||
providerId: MemorySpace['provider']['id']
|
||||
providerLabel: string
|
||||
method: 'native-basic' | 'browse' | 'search'
|
||||
evidence: Array<Pick<Insight, 'content' | 'category' | 'entities'>>
|
||||
}
|
||||
|
||||
export interface MemoryPlacementCandidate {
|
||||
id: MemoryProviderId
|
||||
label: string
|
||||
kind: 'local' | 'remote'
|
||||
configured: boolean
|
||||
summary: string
|
||||
capabilities: MemoryProviderCapabilities
|
||||
}
|
||||
|
||||
export interface PreparedMemoryPlacement {
|
||||
prompt: string
|
||||
candidates: MemoryPlacementCandidate[]
|
||||
appliedRules: string[]
|
||||
selectorBrief: string
|
||||
}
|
||||
|
||||
export interface LlmMemoryPlacementSelection {
|
||||
providerId: string
|
||||
reason: string
|
||||
confidence: string
|
||||
}
|
||||
|
||||
export const DEFAULT_EMBEDDING_ENDPOINT = 'http://localhost:11434'
|
||||
export const DEFAULT_EMBEDDING_MODEL = 'nomic-embed-text'
|
||||
export const EMBEDDING_PROTOCOL_AUTO = 'auto'
|
||||
export const EMBEDDING_PROTOCOL_OLLAMA = 'ollama'
|
||||
export const EMBEDDING_PROTOCOL_OPENAI = 'openai'
|
||||
export const DEFAULT_EMBEDDING_PROTOCOL = EMBEDDING_PROTOCOL_AUTO
|
||||
export const MNEMON_EMBEDDING_PROTOCOLS = [EMBEDDING_PROTOCOL_AUTO, EMBEDDING_PROTOCOL_OLLAMA, EMBEDDING_PROTOCOL_OPENAI] as const
|
||||
|
||||
export interface RecallQualityConfig {
|
||||
policy?: string
|
||||
lowScoreThreshold?: number
|
||||
highScoreThreshold?: number
|
||||
candidateMultiplier?: number
|
||||
maxMediumResults?: number
|
||||
maxRankedResults?: number
|
||||
maxUnknownResults?: number
|
||||
}
|
||||
|
||||
export interface ResolvedRecallQualityConfig {
|
||||
policy: string
|
||||
lowScoreThreshold: number
|
||||
highScoreThreshold: number
|
||||
candidateMultiplier: number
|
||||
maxMediumResults: number
|
||||
maxRankedResults: number
|
||||
maxUnknownResults: number
|
||||
}
|
||||
|
||||
export type MnemonEmbeddingProtocol = (typeof MNEMON_EMBEDDING_PROTOCOLS)[number]
|
||||
|
||||
export interface MnemonEmbeddingConfig {
|
||||
enabled?: boolean
|
||||
endpoint?: string
|
||||
model?: string
|
||||
apiKey?: string
|
||||
apiKeyEnv?: string
|
||||
apiKeyRef?: string
|
||||
protocol?: MnemonEmbeddingProtocol
|
||||
}
|
||||
|
||||
export interface ResolvedMnemonEmbeddingConfig {
|
||||
enabled: boolean
|
||||
endpoint: string
|
||||
model: string
|
||||
apiKey: string
|
||||
apiKeyEnv?: string
|
||||
apiKeyRef?: string
|
||||
protocol: MnemonEmbeddingProtocol
|
||||
}
|
||||
|
||||
export interface MnemonEmbeddingSettingsView extends MnemonEmbeddingConfig {
|
||||
apiKeyStorage?: 'none' | 'legacy' | 'environment' | 'credentials'
|
||||
apiKeyConfigured?: boolean
|
||||
}
|
||||
|
||||
export const EMBEDDING_CREDENTIAL_PREFIX = 'dsh-mnemon/embedding-'
|
||||
export const EMBEDDING_CREDENTIAL_REFERENCE = /^dsh-mnemon\/embedding-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u
|
||||
export const EMBEDDING_ENVIRONMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u
|
||||
|
||||
export interface MnemonEmbeddingCredential {
|
||||
version: 1
|
||||
endpoint: string
|
||||
apiKey: string
|
||||
}
|
||||
|
||||
export interface MnemonEmbeddingStatus {
|
||||
available: boolean
|
||||
model: string
|
||||
protocol?: string
|
||||
totalInsights: number
|
||||
embedded: number
|
||||
coverage: string
|
||||
spaces?: MnemonEmbeddingSpaceStatus[]
|
||||
}
|
||||
|
||||
export interface MnemonEmbeddingSpaceStatus {
|
||||
memoryBodyId: string
|
||||
name: string
|
||||
active: boolean
|
||||
totalInsights: number
|
||||
embedded: number
|
||||
coverage: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface MnemonEmbeddingFill {
|
||||
memoryBodyId: string
|
||||
filled: number
|
||||
remaining: number
|
||||
model: string
|
||||
stopped?: 'time' | 'refused'
|
||||
}
|
||||
|
||||
export interface MemorySpacesStatus {
|
||||
healthy: boolean
|
||||
error?: string
|
||||
version?: string
|
||||
cliPath: string
|
||||
commandFound: boolean
|
||||
dataDir: string
|
||||
store: string
|
||||
mnemonDefaultStore: string
|
||||
dshActiveStores: string[]
|
||||
writeEnabled: boolean
|
||||
timeoutMs: number
|
||||
defaultRecallLimit: number
|
||||
recallQuality: ResolvedRecallQualityConfig
|
||||
embeddingManaged?: boolean
|
||||
memoryBodyDirectory: string
|
||||
memoryBodies: MemorySpaceView[]
|
||||
providerServices?: MemoryProviderRuntimeStatus[]
|
||||
stats?: MemorySpaceStats & { dbPath?: string }
|
||||
}
|
||||
|
||||
export interface EntityView {
|
||||
items: Array<{ entity: string; count: number }>
|
||||
insights: Insight[]
|
||||
selected?: string
|
||||
sources?: MemoryReadSource[]
|
||||
total?: number
|
||||
complete?: boolean
|
||||
}
|
||||
|
||||
export interface EntityMemoriesView {
|
||||
entity: string
|
||||
total: number
|
||||
offset: number
|
||||
items: Insight[]
|
||||
complete: boolean
|
||||
sources: MemoryReadSource[]
|
||||
}
|
||||
|
||||
export interface EntityRelatedView {
|
||||
entity: string
|
||||
items: Insight[]
|
||||
sources: MemoryReadSource[]
|
||||
}
|
||||
|
||||
export const MEMORY_SPACES_DIRECTORY = 'data'
|
||||
export const MEMORY_SPACE_REGISTRY_FILE = '.dsh-memory-bodies.json'
|
||||
export const MEMORY_SPACE_DATABASE_FILE = 'mnemon.db'
|
||||
export const MEMORY_SPACE_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/
|
||||
export const MEMORY_SPACE_NAME_MAX_LENGTH = 100
|
||||
export const MEMORY_SPACE_DESCRIPTION_MAX_LENGTH = 1000
|
||||
export const MNEMON_ACTIVE_STORE_FILE = 'active'
|
||||
export const MEMORY_PROVIDER_REGISTRY_FILE = 'memory-providers.json'
|
||||
|
||||
export interface MemorySpaceRegistryEntry {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
active: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface MemorySpaceRegistryFile {
|
||||
version: 1
|
||||
bodies: MemorySpaceRegistryEntry[]
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export function parseMemorySpaceRegistry(value: unknown): MemorySpaceRegistryFile {
|
||||
const registry = isObject(value) ? value : undefined
|
||||
if (registry?.version !== 1 || !Array.isArray(registry.bodies)) throw new Error('Memory Space registry is invalid')
|
||||
const ids = new Set<string>()
|
||||
const bodies = registry.bodies.map((raw): MemorySpaceRegistryEntry => {
|
||||
const body = isObject(raw) ? raw : undefined
|
||||
if (typeof body?.id !== 'string' || !MEMORY_SPACE_ID_PATTERN.test(body.id) || ids.has(body.id)) throw new Error('Memory Space registry contains an invalid or duplicate id')
|
||||
if (typeof body.name !== 'string' || body.name.trim() === '' || body.name.length > MEMORY_SPACE_NAME_MAX_LENGTH
|
||||
|| typeof body.description !== 'string' || body.description.length > MEMORY_SPACE_DESCRIPTION_MAX_LENGTH) throw new Error('Memory Space registry contains invalid metadata')
|
||||
if (typeof body.createdAt !== 'string' || typeof body.updatedAt !== 'string') throw new Error('Memory Space registry contains invalid timestamps')
|
||||
ids.add(body.id)
|
||||
return { id: body.id, name: body.name, description: body.description, active: body.active === true, createdAt: body.createdAt, updatedAt: body.updatedAt }
|
||||
})
|
||||
return { version: 1, bodies }
|
||||
}
|
||||
|
||||
export interface MemorySpaceRegistrySummary {
|
||||
valid: boolean
|
||||
spaces: number
|
||||
active: number
|
||||
}
|
||||
|
||||
export function summarizeMemorySpaceRegistry(value: unknown): MemorySpaceRegistrySummary {
|
||||
const registry = isObject(value) ? value : undefined
|
||||
const listed = registry?.bodies
|
||||
const spaces = Array.isArray(listed) ? listed.filter(isObject) : []
|
||||
return {
|
||||
valid: registry?.version === 1 && Array.isArray(listed),
|
||||
spaces: spaces.length,
|
||||
active: spaces.filter(space => space.active === true).length,
|
||||
}
|
||||
}
|
||||
|
||||
export interface MemoryProviderRegistrySummary {
|
||||
valid: boolean
|
||||
services: number
|
||||
connections: number
|
||||
}
|
||||
|
||||
export function summarizeMemoryProviderRegistry(value: unknown): MemoryProviderRegistrySummary {
|
||||
const registry = isObject(value) ? value : undefined
|
||||
const services = registry?.services
|
||||
const listed = registry?.bodies
|
||||
return {
|
||||
valid: registry !== undefined,
|
||||
services: isObject(services) ? Object.keys(services).length : 0,
|
||||
connections: Array.isArray(listed) ? listed.length : 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated Use CreateMemorySpaceRequest. The wire shape is unchanged. */
|
||||
export type CreateMemoryBodyRequest = CreateMemorySpaceRequest
|
||||
/** @deprecated Use UpdateMemorySpaceRequest. The wire shape is unchanged. */
|
||||
export type UpdateMemoryBodyRequest = UpdateMemorySpaceRequest
|
||||
/** @deprecated Use MemorySpace. The wire shape is unchanged. */
|
||||
export type MemoryBody = MemorySpace
|
||||
/** @deprecated Use MemorySpaceCatalog. The wire shape is unchanged. */
|
||||
export type MemoryBodyCatalog = MemorySpaceCatalog
|
||||
export type MemoryBodyDirectory = MemorySpaceCatalog
|
||||
/** @deprecated Use MemorySpaceMetadataMaintenanceResult. The wire shape is unchanged. */
|
||||
export type MemoryBodyMetadataMaintenanceResult = MemorySpaceMetadataMaintenanceResult
|
||||
/** @deprecated Use MemorySpaceMetadataSample. The wire shape is unchanged. */
|
||||
export type MemoryBodyMetadataSample = MemorySpaceMetadataSample
|
||||
/** @deprecated Use MemorySpaceMetadataUpdate. The wire shape is unchanged. */
|
||||
export type MemoryBodyMetadataUpdate = MemorySpaceMetadataUpdate
|
||||
/** @deprecated Use MemorySpaceProvider. The wire shape is unchanged. */
|
||||
export type MemoryBodyProvider = MemorySpaceProvider
|
||||
/** @deprecated Use MemorySpaceStats. The wire shape is unchanged. */
|
||||
export type MemoryBodyStats = MemorySpaceStats
|
||||
/** @deprecated Use MemorySpaceView. The wire shape is unchanged. */
|
||||
export type MemoryBodyView = MemorySpaceView
|
||||
/** @deprecated Use OpenVikingSpaceConnection. The wire shape is unchanged. */
|
||||
export type OpenVikingBodyConnection = OpenVikingSpaceConnection
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
export { CATEGORIES, SOURCES, EDGE_TYPES, INTENTS } from './contracts.ts'
|
||||
export type {
|
||||
JsonValue, Category, Source, EdgeType, Intent, Insight,
|
||||
MemorySpace, MemorySpaceProvider, MemorySpaceStats, MemoryGraphNode, MemoryGraphEdge, MemoryGraphSnapshot,
|
||||
MemoryListRequest, RememberRequest, SearchRequest, OpenVikingSpaceConnection,
|
||||
MemoryProviderId, MemoryProviderConnection, MemoryProviderConnectionValue,
|
||||
MemoryProviderIcon, MemoryProviderConfigField, MemoryProviderConfigOption,
|
||||
MemoryProviderCapabilities, MemoryProviderDescriptor,
|
||||
} from './contracts.ts'
|
||||
export * from './providers/adapter.ts'
|
||||
export { MEMORY_SPACE_PROVIDER_API_VERSION, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition } from './providers/definitions.ts'
|
||||
export type {
|
||||
MemorySpaceProviderManifest, MemorySpaceProviderDefinition, MemorySpaceProviderRuntimeContext,
|
||||
MemorySpaceProviderScoreSemantics, MemorySpaceProviderDisposer, MemorySpaceProviderHost,
|
||||
MemorySpaceProviderModule, MemorySpaceProviderEntry,
|
||||
} from './providers/definitions.ts'
|
||||
export * from './providers/http.ts'
|
||||
export * from './providers/process.ts'
|
||||
|
||||
export type { MemoryBody, MemoryBodyProvider, MemoryBodyStats, OpenVikingBodyConnection } from './contracts.ts'
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
import type { JsonValue } from '../contracts.ts'
|
||||
import type {
|
||||
EdgeType,
|
||||
Insight,
|
||||
MemorySpace,
|
||||
MemorySpaceStats,
|
||||
MemoryGraphSnapshot,
|
||||
MemoryListRequest,
|
||||
MemoryProviderConnection,
|
||||
RememberRequest,
|
||||
SearchRequest,
|
||||
} from '../contracts.ts'
|
||||
|
||||
export interface MemorySpaceAuthority {
|
||||
readonly runner: { effectiveDataDir(): string }
|
||||
list(): MemorySpace[]
|
||||
providerConnection(id: string, expectedProviderId?: string): MemoryProviderConnection
|
||||
}
|
||||
|
||||
export interface MemorySpaceNativeRunOptions {
|
||||
signal?: AbortSignal
|
||||
store?: string
|
||||
maxOutputBytes?: number
|
||||
}
|
||||
|
||||
export interface MemorySpaceNativeRunner {
|
||||
runJson(args: readonly string[], options?: MemorySpaceNativeRunOptions): Promise<JsonValue>
|
||||
runText(args: readonly string[], options?: MemorySpaceNativeRunOptions): Promise<string>
|
||||
}
|
||||
|
||||
export interface MemoryProviderAdapterFactoryContext {
|
||||
memorySpaces?: MemorySpaceAuthority
|
||||
/** @deprecated Use memorySpaces when present; retained for existing Provider factories. */
|
||||
memoryBodies: MemorySpaceAuthority
|
||||
config: { timeoutMs: number; defaultRecallLimit?: number }
|
||||
nativeRunner?: MemorySpaceNativeRunner
|
||||
}
|
||||
|
||||
export interface ProviderSpaceStatus {
|
||||
healthy: boolean
|
||||
error?: string
|
||||
stats?: MemorySpaceStats
|
||||
}
|
||||
|
||||
export interface ProviderSearchResult {
|
||||
results: Insight[]
|
||||
hint?: string
|
||||
}
|
||||
|
||||
export interface ProviderScoreSemantics {
|
||||
kind: 'normalized-relevance' | 'provider-native'
|
||||
}
|
||||
|
||||
export type MemoryProviderScoreSemantics = 'normalized-relevance' | 'provider-native' | 'none'
|
||||
|
||||
export const NORMALIZED_RELEVANCE_SCORE: ProviderScoreSemantics = Object.freeze({ kind: 'normalized-relevance' })
|
||||
|
||||
export interface ProviderEntityIndex {
|
||||
memories: Insight[]
|
||||
complete: boolean
|
||||
}
|
||||
|
||||
export interface ProviderMemorySpace {
|
||||
externalId: string
|
||||
name: string
|
||||
description: string
|
||||
connection: MemoryProviderConnection
|
||||
}
|
||||
|
||||
export interface MemoryProviderAdapter {
|
||||
readonly id: MemorySpace['provider']['id']
|
||||
readonly scoreSemantics?: ProviderScoreSemantics
|
||||
discover?(connection: MemoryProviderConnection, signal?: AbortSignal): Promise<ProviderMemorySpace[]>
|
||||
invalidateStatus?(memoryBodyId?: string): void
|
||||
status(body: MemorySpace, signal?: AbortSignal): Promise<ProviderSpaceStatus>
|
||||
search(body: MemorySpace, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>
|
||||
graph(body: MemorySpace, signal?: AbortSignal): Promise<MemoryGraphSnapshot>
|
||||
list(body: MemorySpace, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>
|
||||
remember(body: MemorySpace, request: RememberRequest, signal?: AbortSignal): Promise<JsonValue>
|
||||
metadataSample?(body: MemorySpace, limit: number, signal?: AbortSignal): Promise<Insight[]>
|
||||
entityIndex?(body: MemorySpace, signal?: AbortSignal): Promise<ProviderEntityIndex>
|
||||
rememberMany?(body: MemorySpace, requests: readonly RememberRequest[], signal?: AbortSignal): Promise<JsonValue[]>
|
||||
get?(body: MemorySpace, id: string, signal?: AbortSignal): Promise<Insight | undefined>
|
||||
related?(body: MemorySpace, id: string, depth: number, edge?: EdgeType, signal?: AbortSignal): Promise<Insight[]>
|
||||
link?(body: MemorySpace, sourceId: string, targetId: string, type: EdgeType, weight: number, reason?: string, signal?: AbortSignal): Promise<JsonValue>
|
||||
forget?(body: MemorySpace, id: string, signal?: AbortSignal): Promise<JsonValue>
|
||||
dispose?(): void | Promise<void>
|
||||
}
|
||||
|
||||
/** @deprecated Use ProviderSpaceStatus. */
|
||||
export type ProviderBodyStatus = ProviderSpaceStatus
|
||||
|
|
@ -0,0 +1,262 @@
|
|||
import { createHash } from 'node:crypto'
|
||||
import type { Context, Plugin } from '@deepseek-ai/cordis'
|
||||
import type {
|
||||
MemoryProviderCapabilities,
|
||||
MemoryProviderConfigField,
|
||||
MemoryProviderDescriptor,
|
||||
MemoryProviderIcon,
|
||||
} from '../contracts.ts'
|
||||
import type { MemoryProviderAdapter } from './adapter.ts'
|
||||
import type { MemoryProviderAdapterFactoryContext } from './adapter.ts'
|
||||
|
||||
export const MEMORY_SPACE_PROVIDER_API_VERSION = 'dsh-brain-mnemon.memory-space-provider/v1' as const
|
||||
|
||||
const STABLE_ID = /^[a-z][a-z0-9-]{0,127}$/u
|
||||
const FIELD_KEY = /^[a-z][a-zA-Z0-9_-]{0,127}$/u
|
||||
|
||||
export type MemorySpaceProviderScoreSemantics = 'normalized-relevance' | 'provider-native' | 'none'
|
||||
|
||||
export interface MemorySpaceProviderManifest {
|
||||
apiVersion: typeof MEMORY_SPACE_PROVIDER_API_VERSION
|
||||
kind: 'provider'
|
||||
typeId: string
|
||||
packageName: string
|
||||
version: string
|
||||
label: string
|
||||
icon?: MemoryProviderIcon | undefined
|
||||
summary: string
|
||||
summaryI18nKey?: string
|
||||
origin: 'native' | 'third-party'
|
||||
locality: 'local' | 'remote'
|
||||
workspaceBinding: MemoryProviderDescriptor['workspaceBinding']
|
||||
capabilities: MemoryProviderCapabilities
|
||||
fields: MemoryProviderConfigField[]
|
||||
secrets: string[]
|
||||
scoreSemantics: MemorySpaceProviderScoreSemantics
|
||||
}
|
||||
|
||||
export interface MemorySpaceProviderRuntimeContext extends MemoryProviderAdapterFactoryContext {
|
||||
providerInstanceId: string
|
||||
manifest: MemorySpaceProviderManifest
|
||||
}
|
||||
|
||||
export interface MemorySpaceProviderDefinition {
|
||||
manifest: MemorySpaceProviderManifest
|
||||
create(context: MemorySpaceProviderRuntimeContext): MemoryProviderAdapter
|
||||
}
|
||||
|
||||
export type MemorySpaceProviderDisposer = () => void | Promise<void>
|
||||
|
||||
export interface MemorySpaceProviderHost {
|
||||
install(owner: Context, definition: MemorySpaceProviderDefinition): MemorySpaceProviderDisposer
|
||||
}
|
||||
|
||||
export interface MemorySpaceProviderModule<Config = undefined> {
|
||||
readonly id: string
|
||||
readonly Config?: Plugin.Base<Config>['Config']
|
||||
apply(ctx: Context, host: MemorySpaceProviderHost, config: Config): void | Promise<void>
|
||||
}
|
||||
|
||||
export interface MemorySpaceProviderEntry<Config = unknown> {
|
||||
instanceId: string
|
||||
module: MemorySpaceProviderModule<Config>
|
||||
config: Config
|
||||
}
|
||||
|
||||
export function requiredId(value: string, label: string): string {
|
||||
const normalized = value.trim()
|
||||
if (!STABLE_ID.test(normalized)) throw new Error(`${label} must match [a-z][a-z0-9-]{0,127}`)
|
||||
return normalized
|
||||
}
|
||||
|
||||
function requiredText(value: string, label: string, max = 500): string {
|
||||
const normalized = value.trim()
|
||||
if (normalized === '') throw new Error(`${label} is required`)
|
||||
if (normalized.length > max) throw new Error(`${label} is too long (max ${max} characters)`)
|
||||
return normalized
|
||||
}
|
||||
|
||||
function requiredFieldKey(value: string, label: string): string {
|
||||
const normalized = value.trim()
|
||||
if (!FIELD_KEY.test(normalized)) throw new Error(`${label} must start with a letter and contain only letters, digits, _ or -`)
|
||||
return normalized
|
||||
}
|
||||
|
||||
function captureIcon(value: MemoryProviderIcon | undefined): MemoryProviderIcon | undefined {
|
||||
if (value === undefined) return undefined
|
||||
const icon = structuredClone(value)
|
||||
if (icon.kind === 'brand') icon.value = requiredId(icon.value, 'Memory Space Provider icon brand')
|
||||
else if (icon.kind === 'glyph') icon.value = requiredText(icon.value, 'Memory Space Provider icon glyph', 16)
|
||||
else if (icon.kind === 'data-url') {
|
||||
icon.value = requiredText(icon.value, 'Memory Space Provider icon data URL', 200_000)
|
||||
if (!/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[a-zA-Z0-9+/=]+$/u.test(icon.value)) {
|
||||
throw new Error('Memory Space Provider icon must be a base64 image data URL')
|
||||
}
|
||||
} else {
|
||||
throw new Error(`unsupported Memory Space Provider icon kind: ${String(icon.kind)}`)
|
||||
}
|
||||
return icon
|
||||
}
|
||||
|
||||
function captureCapabilities(value: MemoryProviderCapabilities): MemoryProviderCapabilities {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('Memory Space Provider capabilities must be an object')
|
||||
const capabilities = structuredClone(value)
|
||||
for (const key of ['search', 'browse', 'graph', 'entities', 'related', 'remember', 'link', 'forget'] as const) {
|
||||
if (typeof capabilities[key] !== 'boolean') throw new Error(`Memory Space Provider capability ${key} must be boolean`)
|
||||
}
|
||||
if (capabilities.writeMode !== 'exact' && capabilities.writeMode !== 'async-extracting') throw new Error('unsupported Memory Space Provider write mode')
|
||||
if (!['soft', 'hard', 'unsupported'].includes(capabilities.deletionMode)) throw new Error('unsupported Memory Space Provider deletion mode')
|
||||
return capabilities
|
||||
}
|
||||
|
||||
function captureFields(value: MemoryProviderConfigField[]): MemoryProviderConfigField[] {
|
||||
if (!Array.isArray(value)) throw new Error('Memory Space Provider fields must be an array')
|
||||
const fields = structuredClone(value)
|
||||
const fieldKeys = new Set<string>()
|
||||
for (const field of fields) {
|
||||
const key = requiredFieldKey(field.key, 'Memory Space Provider field key')
|
||||
if (fieldKeys.has(key)) throw new Error(`duplicate Memory Space Provider field: ${key}`)
|
||||
fieldKeys.add(key)
|
||||
field.key = key
|
||||
field.label = requiredText(field.label, `Memory Space Provider field ${key} label`, 100)
|
||||
if (field.i18nKey !== undefined) field.i18nKey = requiredText(field.i18nKey, `Memory Space Provider field ${key} i18nKey`, 200)
|
||||
if (field.scope !== 'service' && field.scope !== 'memory') throw new Error(`unsupported Memory Space Provider field scope: ${String(field.scope)}`)
|
||||
if (!['text', 'url', 'secret', 'number', 'boolean', 'select', 'path'].includes(field.input)) throw new Error(`unsupported Memory Space Provider field input: ${String(field.input)}`)
|
||||
if (typeof field.required !== 'boolean') throw new Error(`Memory Space Provider field ${key} required must be boolean`)
|
||||
if (field.role !== undefined && field.role !== 'global-location') throw new Error(`unsupported Memory Space Provider field role: ${String(field.role)}`)
|
||||
if (field.role === 'global-location' && (field.scope !== 'service' || field.input !== 'path')) throw new Error(`Memory Space Provider field ${key} global-location must be a service path`)
|
||||
if (field.placeholder !== undefined) field.placeholder = requiredText(field.placeholder, `Memory Space Provider field ${key} placeholder`, 2_000)
|
||||
if (field.help !== undefined) field.help = requiredText(field.help, `Memory Space Provider field ${key} help`, 2_000)
|
||||
if (field.min !== undefined && (!Number.isFinite(field.min) || field.input !== 'number')) throw new Error(`Memory Space Provider field ${key} min requires a finite number field`)
|
||||
if (field.max !== undefined && (!Number.isFinite(field.max) || field.input !== 'number')) throw new Error(`Memory Space Provider field ${key} max requires a finite number field`)
|
||||
if (field.min !== undefined && field.max !== undefined && field.min > field.max) throw new Error(`Memory Space Provider field ${key} min exceeds max`)
|
||||
if (field.maxLength !== undefined && (
|
||||
!['text', 'url', 'secret', 'select', 'path'].includes(field.input)
|
||||
|| !Number.isInteger(field.maxLength) || field.maxLength < 1 || field.maxLength > 8_000
|
||||
)) throw new Error(`Memory Space Provider field ${key} maxLength is invalid`)
|
||||
if (field.pattern !== undefined) {
|
||||
if (!['text', 'url', 'secret', 'path'].includes(field.input)) throw new Error(`Memory Space Provider field ${key} pattern requires a textual field`)
|
||||
field.pattern = requiredText(field.pattern, `Memory Space Provider field ${key} pattern`, 1_000)
|
||||
try { new RegExp(field.pattern, 'u') } catch { throw new Error(`Memory Space Provider field ${key} pattern is invalid`) }
|
||||
}
|
||||
if (field.validationMessage !== undefined) {
|
||||
if (field.pattern === undefined) throw new Error(`Memory Space Provider field ${key} validationMessage requires a pattern`)
|
||||
field.validationMessage = requiredText(field.validationMessage, `Memory Space Provider field ${key} validationMessage`, 500)
|
||||
}
|
||||
if (field.normalize !== undefined && (field.normalize !== 'trim-trailing-slash' || !['text', 'url', 'path'].includes(field.input))) {
|
||||
throw new Error(`unsupported Memory Space Provider field normalization: ${String(field.normalize)}`)
|
||||
}
|
||||
if (field.options !== undefined) {
|
||||
if (field.input !== 'select' || field.options.length === 0) throw new Error(`Memory Space Provider field ${key} options require a non-empty select field`)
|
||||
const optionValues = new Set<string>()
|
||||
for (const option of field.options) {
|
||||
option.value = requiredText(option.value, `Memory Space Provider field ${key} option value`, 200)
|
||||
option.label = requiredText(option.label, `Memory Space Provider field ${key} option label`, 200)
|
||||
if (option.i18nKey !== undefined) option.i18nKey = requiredText(option.i18nKey, `Memory Space Provider field ${key} option i18nKey`, 200)
|
||||
if (optionValues.has(option.value)) throw new Error(`duplicate Memory Space Provider field ${key} option: ${option.value}`)
|
||||
optionValues.add(option.value)
|
||||
}
|
||||
} else if (field.input === 'select') throw new Error(`Memory Space Provider select field ${key} requires options`)
|
||||
if (field.defaultValue !== undefined) {
|
||||
const valid = field.input === 'boolean'
|
||||
? typeof field.defaultValue === 'boolean'
|
||||
: field.input === 'number'
|
||||
? typeof field.defaultValue === 'number' && Number.isFinite(field.defaultValue)
|
||||
: typeof field.defaultValue === 'string'
|
||||
if (!valid || field.input === 'select' && !field.options?.some(option => option.value === field.defaultValue)) {
|
||||
throw new Error(`Memory Space Provider field ${key} default is invalid`)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const field of fields) {
|
||||
if (field.discoveryDefaultFrom === undefined) continue
|
||||
field.discoveryDefaultFrom = requiredFieldKey(field.discoveryDefaultFrom, `Memory Space Provider field ${field.key} discoveryDefaultFrom`)
|
||||
const source = fields.find(candidate => candidate.key === field.discoveryDefaultFrom)
|
||||
if (field.scope !== 'service' || source?.scope !== 'memory' || source.input === 'secret') {
|
||||
throw new Error(`Memory Space Provider field ${field.key} discovery default must reference a memory field`)
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
function canonical(value: unknown, label: string, ancestors = new Set<object>(), depth = 0): string {
|
||||
if (depth > 64) throw new Error(`${label} exceeds the maximum nesting depth`)
|
||||
if (value === null || typeof value === 'boolean' || typeof value === 'string') return JSON.stringify(value)
|
||||
if (typeof value === 'number') {
|
||||
if (!Number.isFinite(value)) throw new Error(`${label} contains a non-finite number`)
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
if (typeof value !== 'object') throw new Error(`${label} must be JSON-safe`)
|
||||
if (ancestors.has(value)) throw new Error(`${label} contains a cycle`)
|
||||
ancestors.add(value)
|
||||
try {
|
||||
if (Array.isArray(value)) return `[${value.map(item => canonical(item, label, ancestors, depth + 1)).join(',')}]`
|
||||
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
|
||||
throw new Error(`${label} contains a non-plain object`)
|
||||
}
|
||||
return `{${Object.entries(value as Record<string, unknown>)
|
||||
.filter(([, item]) => item !== undefined)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item, label, ancestors, depth + 1)}`)
|
||||
.join(',')}}`
|
||||
} finally {
|
||||
ancestors.delete(value)
|
||||
}
|
||||
}
|
||||
|
||||
export function digest(value: unknown, label: string): string {
|
||||
return createHash('sha256').update(canonical(value, label)).digest('hex')
|
||||
}
|
||||
|
||||
export function deepFreeze<T>(value: T): T {
|
||||
if (typeof value !== 'object' || value === null || Object.isFrozen(value)) return value
|
||||
for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)
|
||||
return Object.freeze(value)
|
||||
}
|
||||
|
||||
function captureManifest(value: MemorySpaceProviderManifest): MemorySpaceProviderManifest {
|
||||
canonical(value, 'Memory Space Provider manifest')
|
||||
const manifest = structuredClone(value)
|
||||
if (manifest.apiVersion !== MEMORY_SPACE_PROVIDER_API_VERSION) throw new Error(`unsupported Memory Space Provider API: ${String(manifest.apiVersion)}`)
|
||||
if (manifest.kind !== 'provider') throw new Error('Memory Space Provider manifest kind must be provider')
|
||||
manifest.typeId = requiredId(manifest.typeId, 'Memory Space Provider typeId')
|
||||
manifest.packageName = requiredText(manifest.packageName, 'Memory Space Provider packageName')
|
||||
manifest.version = requiredText(manifest.version, 'Memory Space Provider version', 100)
|
||||
manifest.label = requiredText(manifest.label, 'Memory Space Provider label', 100)
|
||||
manifest.icon = captureIcon(manifest.icon)
|
||||
manifest.summary = requiredText(manifest.summary, 'Memory Space Provider summary', 1_000)
|
||||
if (manifest.summaryI18nKey !== undefined) manifest.summaryI18nKey = requiredText(manifest.summaryI18nKey, 'Memory Space Provider summaryI18nKey', 200)
|
||||
if (manifest.locality !== 'local' && manifest.locality !== 'remote') throw new Error('Memory Space Provider locality must be local or remote')
|
||||
if (manifest.origin !== 'native' && manifest.origin !== 'third-party') throw new Error('Memory Space Provider origin must be native or third-party')
|
||||
if (!['automatic', 'optional-override', 'provider-global'].includes(manifest.workspaceBinding)) {
|
||||
throw new Error(`unsupported Memory Space Provider workspace binding: ${String(manifest.workspaceBinding)}`)
|
||||
}
|
||||
if (!['normalized-relevance', 'provider-native', 'none'].includes(manifest.scoreSemantics)) {
|
||||
throw new Error(`unsupported Memory Space Provider score semantics: ${String(manifest.scoreSemantics)}`)
|
||||
}
|
||||
manifest.capabilities = captureCapabilities(manifest.capabilities)
|
||||
manifest.fields = captureFields(manifest.fields)
|
||||
if (!Array.isArray(manifest.secrets)) throw new Error('Memory Space Provider secrets must be an array')
|
||||
const secretFields = manifest.fields.filter(field => field.input === 'secret').map(field => field.key).sort()
|
||||
const secrets = [...new Set(manifest.secrets.map(secret => requiredFieldKey(secret, 'Memory Space Provider secret')))].sort()
|
||||
if (canonical(secretFields, 'Memory Space Provider secret fields') !== canonical(secrets, 'Memory Space Provider secrets')) {
|
||||
throw new Error('Memory Space Provider secrets must exactly match secret config fields')
|
||||
}
|
||||
manifest.secrets = secrets
|
||||
return deepFreeze(manifest)
|
||||
}
|
||||
|
||||
function captureDefinition(value: MemorySpaceProviderDefinition): MemorySpaceProviderDefinition {
|
||||
if (typeof value?.create !== 'function') throw new Error('Memory Space Provider definition requires a create factory')
|
||||
return Object.freeze({ manifest: captureManifest(value.manifest), create: value.create })
|
||||
}
|
||||
|
||||
export function defineMemorySpaceProvider<Config>(module: MemorySpaceProviderModule<Config>): MemorySpaceProviderModule<Config> {
|
||||
const id = requiredId(module.id, 'Memory Space Provider module id')
|
||||
if (typeof module.apply !== 'function') throw new Error(`Memory Space Provider module ${id} requires apply()`)
|
||||
return Object.freeze({ ...module, id })
|
||||
}
|
||||
|
||||
export function defineMemorySpaceProviderDefinition(definition: MemorySpaceProviderDefinition): MemorySpaceProviderDefinition {
|
||||
return captureDefinition(definition)
|
||||
}
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
import type { JsonValue } from '../contracts.ts'
|
||||
import type { MemorySpaceAuthority } from './adapter.ts'
|
||||
import type {
|
||||
Insight,
|
||||
MemorySpace,
|
||||
MemoryGraphSnapshot,
|
||||
MemoryListRequest,
|
||||
MemoryProviderConnection,
|
||||
MemoryProviderId,
|
||||
} from '../contracts.ts'
|
||||
|
||||
export interface HttpProviderOptions {
|
||||
label?: string
|
||||
fetch?: typeof fetch
|
||||
requestTimeoutMs?: number
|
||||
}
|
||||
|
||||
export interface JsonRequestOptions {
|
||||
method?: string
|
||||
headers?: HeadersInit
|
||||
json?: JsonValue
|
||||
signal?: AbortSignal | undefined
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export type HttpRequestInit = JsonRequestOptions
|
||||
|
||||
export function bearerAuthHeader(apiKey: unknown): string | undefined {
|
||||
if (typeof apiKey !== 'string') return undefined
|
||||
const token = apiKey.trim().replace(/^Bearer(?:\s+|$)/iu, '').trim()
|
||||
return token === '' ? undefined : `Bearer ${token}`
|
||||
}
|
||||
|
||||
export function jsonObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: undefined
|
||||
}
|
||||
|
||||
export function jsonString(value: unknown): string | undefined {
|
||||
return typeof value === 'string' ? value : undefined
|
||||
}
|
||||
|
||||
export function jsonNumber(value: unknown): number | undefined {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
|
||||
}
|
||||
|
||||
export function jsonArray(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : []
|
||||
}
|
||||
|
||||
export function firstArray(value: unknown, ...keys: string[]): unknown[] {
|
||||
if (Array.isArray(value)) return value
|
||||
const root = jsonObject(value)
|
||||
for (const key of keys) if (Array.isArray(root?.[key])) return root[key] as unknown[]
|
||||
const nested = jsonObject(root?.data)
|
||||
for (const key of keys) if (Array.isArray(nested?.[key])) return nested[key] as unknown[]
|
||||
return []
|
||||
}
|
||||
|
||||
function errorDetail(payload: unknown): string | undefined {
|
||||
if (typeof payload === 'string') return payload.trim() || undefined
|
||||
const root = jsonObject(payload)
|
||||
const direct = jsonString(root?.message) ?? jsonString(root?.error) ?? jsonString(root?.detail)
|
||||
if (direct !== undefined) return direct
|
||||
const error = jsonObject(root?.error)
|
||||
return jsonString(error?.message) ?? jsonString(error?.detail)
|
||||
}
|
||||
|
||||
export abstract class HttpMemoryProvider {
|
||||
abstract readonly id: MemoryProviderId
|
||||
protected readonly label: string | undefined
|
||||
protected readonly requestFetch: typeof fetch
|
||||
protected readonly requestTimeoutMs: number
|
||||
|
||||
/** @deprecated Use memorySpaces. */
|
||||
protected readonly memoryBodies: MemorySpaceAuthority
|
||||
|
||||
constructor(protected readonly memorySpaces: MemorySpaceAuthority, options: HttpProviderOptions = {}) {
|
||||
this.memoryBodies = memorySpaces
|
||||
this.label = options.label
|
||||
this.requestFetch = options.fetch ?? globalThis.fetch
|
||||
this.requestTimeoutMs = options.requestTimeoutMs ?? 15_000
|
||||
}
|
||||
|
||||
abstract list(body: MemorySpace, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>
|
||||
|
||||
async graph(body: MemorySpace, signal?: AbortSignal): Promise<MemoryGraphSnapshot> {
|
||||
const items = await this.list(body, { limit: 200 }, signal)
|
||||
return {
|
||||
nodes: items.map(item => ({ ...item, color: '#6574d9' })),
|
||||
edges: [],
|
||||
generatedAt: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
protected connection(body: MemorySpace): MemoryProviderConnection {
|
||||
if ((body.provider.typeId ?? body.provider.id) !== this.id) throw new Error(`${this.id} cannot serve provider ${body.provider.id}`)
|
||||
return this.memorySpaces.providerConnection(body.id, body.provider.id)
|
||||
}
|
||||
|
||||
protected async request(body: MemorySpace, path: string, options: JsonRequestOptions = {}): Promise<unknown> {
|
||||
const connection = this.connection(body)
|
||||
return this.requestConnection(connection, path, options)
|
||||
}
|
||||
|
||||
protected async requestConnection(connection: MemoryProviderConnection, path: string, options: JsonRequestOptions = {}): Promise<unknown> {
|
||||
const endpoint = String(connection.endpoint ?? '').replace(/\/+$/u, '')
|
||||
const label = this.label ?? this.id
|
||||
if (endpoint === '') throw new Error(`${label} endpoint is not configured`)
|
||||
if (!path.startsWith('/')) throw new Error(`${label} request path must be absolute`)
|
||||
options.signal?.throwIfAborted()
|
||||
const controller = new AbortController()
|
||||
const relay = () => controller.abort(options.signal?.reason)
|
||||
options.signal?.addEventListener('abort', relay, { once: true })
|
||||
const timeoutMs = options.timeoutMs ?? this.requestTimeoutMs
|
||||
const timer = setTimeout(() => controller.abort(new Error(`${label} request timed out`)), timeoutMs)
|
||||
const headers = new Headers(options.headers)
|
||||
if (options.json !== undefined && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
|
||||
try {
|
||||
const response = await this.requestFetch(`${endpoint}${path}`, {
|
||||
method: options.method ?? (options.json === undefined ? 'GET' : 'POST'),
|
||||
headers,
|
||||
...(options.json === undefined ? {} : { body: JSON.stringify(options.json) }),
|
||||
signal: controller.signal,
|
||||
})
|
||||
const raw = await response.text()
|
||||
let payload: unknown = {}
|
||||
if (raw !== '') {
|
||||
try { payload = JSON.parse(raw) } catch { payload = raw }
|
||||
}
|
||||
if (!response.ok) {
|
||||
const detail = errorDetail(payload)
|
||||
throw Object.assign(new Error(`${label} HTTP ${response.status}${detail === undefined ? '' : `: ${detail}`}`), { status: response.status })
|
||||
}
|
||||
return payload
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted && options.signal?.aborted !== true) {
|
||||
throw new Error(`${label} request timed out after ${timeoutMs}ms`)
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
options.signal?.removeEventListener('abort', relay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
import { spawn } from 'node:child_process'
|
||||
import { StringDecoder } from 'node:string_decoder'
|
||||
|
||||
export interface ProcessResult {
|
||||
stdout: string
|
||||
stderr: string
|
||||
exitCode: number | null
|
||||
}
|
||||
|
||||
export interface ProcessOptions {
|
||||
signal?: AbortSignal | undefined
|
||||
timeoutMs: number
|
||||
maxOutputBytes?: number
|
||||
cwd?: string | undefined
|
||||
env?: NodeJS.ProcessEnv | undefined
|
||||
label?: string | undefined
|
||||
}
|
||||
|
||||
export type ProcessRunner = (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessOptions,
|
||||
) => Promise<ProcessResult>
|
||||
|
||||
export type ProcessFailureReason = 'launch' | 'timeout' | 'aborted' | 'output-limit'
|
||||
|
||||
export class ProcessError extends Error {
|
||||
constructor(message: string, readonly reason: ProcessFailureReason) {
|
||||
super(message)
|
||||
this.name = 'ProcessError'
|
||||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_MAX_OUTPUT_BYTES = 2 * 1024 * 1024
|
||||
|
||||
export const runProcess: ProcessRunner = (command, args, options) => new Promise((resolve, reject) => {
|
||||
const label = options.label ?? 'mnemon'
|
||||
const child = spawn(command, [...args], {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
||||
...(options.env === undefined ? {} : { env: options.env }),
|
||||
})
|
||||
const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
const stdoutDecoder = new StringDecoder('utf8')
|
||||
const stderrDecoder = new StringDecoder('utf8')
|
||||
let outputBytes = 0
|
||||
let settled = false
|
||||
let killTimer: NodeJS.Timeout | undefined
|
||||
|
||||
const stop = (): void => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return
|
||||
child.kill('SIGTERM')
|
||||
killTimer = setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
|
||||
}, 1500)
|
||||
}
|
||||
const finish = (error: Error | null, result?: ProcessResult): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
if (killTimer !== undefined) clearTimeout(killTimer)
|
||||
options.signal?.removeEventListener('abort', abort)
|
||||
if (error === null) resolve(result!)
|
||||
else reject(error)
|
||||
}
|
||||
const abort = (): void => {
|
||||
stop()
|
||||
finish(new ProcessError(`${label} command aborted: ${String(options.signal?.reason ?? 'cancelled')}`, 'aborted'))
|
||||
}
|
||||
const append = (target: 'stdout' | 'stderr', chunk: Buffer): void => {
|
||||
outputBytes += chunk.byteLength
|
||||
if (outputBytes > maxOutputBytes) {
|
||||
stop()
|
||||
finish(new ProcessError(`${label} output exceeded ${maxOutputBytes} bytes`, 'output-limit'))
|
||||
return
|
||||
}
|
||||
if (target === 'stdout') stdout += stdoutDecoder.write(chunk)
|
||||
else stderr += stderrDecoder.write(chunk)
|
||||
}
|
||||
|
||||
child.stdout.on('data', (chunk: Buffer) => { append('stdout', chunk) })
|
||||
child.stderr.on('data', (chunk: Buffer) => { append('stderr', chunk) })
|
||||
child.on('error', (error) => {
|
||||
finish(new ProcessError(`failed to launch ${label} (${JSON.stringify(command)}): ${error.message}`, 'launch'))
|
||||
})
|
||||
child.on('close', (exitCode) => {
|
||||
stdout += stdoutDecoder.end()
|
||||
stderr += stderrDecoder.end()
|
||||
finish(null, { stdout, stderr, exitCode })
|
||||
})
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
stop()
|
||||
finish(new ProcessError(`${label} did not respond within ${options.timeoutMs}ms`, 'timeout'))
|
||||
}, options.timeoutMs)
|
||||
if (options.signal?.aborted === true) abort()
|
||||
else options.signal?.addEventListener('abort', abort, { once: true })
|
||||
})
|
||||
|
|
@ -16,15 +16,16 @@ import {
|
|||
MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
defineMemorySpaceProvider,
|
||||
defineMemorySpaceProviderDefinition,
|
||||
} from 'dsh-mnemon-source-memory-spaces/provider-sdk'
|
||||
} from './fork/provider-sdk.ts'
|
||||
import { descriptor } from './descriptor.ts'
|
||||
import { LongMemoryProvider } from './driver.ts'
|
||||
import { createSidecarMemoryRemoteFactory } from '../cloudsync.ts'
|
||||
import { VERSION } from '../version.ts'
|
||||
|
||||
export { LongMemoryProvider, descriptor }
|
||||
|
||||
/** Keep in sync with the package version (asserted by the verify script). */
|
||||
const PROVIDER_VERSION = '0.9.8'
|
||||
/** Manifest version, sourced from package.json via src/version.ts. */
|
||||
const PROVIDER_VERSION = VERSION
|
||||
|
||||
export const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,93 @@
|
|||
/** Local Mnemon Native provider exposed through the same Mnemon host contract. */
|
||||
import type {
|
||||
Insight,
|
||||
JsonValue,
|
||||
MemoryGraphSnapshot,
|
||||
MemoryListRequest,
|
||||
MemoryProviderAdapter,
|
||||
MemorySpace,
|
||||
ProviderSearchResult,
|
||||
ProviderSpaceStatus,
|
||||
RememberRequest,
|
||||
SearchRequest,
|
||||
} from './fork/provider-sdk.ts'
|
||||
import { MEMORY_SPACE_PROVIDER_API_VERSION, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition } from './fork/provider-sdk.ts'
|
||||
import { LocalMemoryManager } from '../local-memory/index.ts'
|
||||
import { VERSION } from '../version.ts'
|
||||
|
||||
export const descriptor = {
|
||||
id: 'dsh-brain-native',
|
||||
label: 'DSH Brain Native',
|
||||
icon: { kind: 'glyph' as const, value: '🧠' },
|
||||
kind: 'local' as const,
|
||||
workspaceBinding: 'optional-override' as const,
|
||||
summary: 'Local DSH Brain memory spaces: project and global records stored under .dsh/brain.',
|
||||
origin: 'native' as const,
|
||||
capabilities: { search: true, browse: true, graph: false, entities: false, related: false, remember: true, link: false, forget: true, writeMode: 'exact' as const, deletionMode: 'soft' as const },
|
||||
fields: [],
|
||||
serviceConfigured: true,
|
||||
}
|
||||
|
||||
function workspaceOf(body: MemorySpace): string | undefined {
|
||||
return body.dbPath !== undefined && body.dbPath !== '' ? body.dbPath : undefined
|
||||
}
|
||||
function insightOf(record: { id: string; content: string; category?: string; tags: string[]; source: string; createdAt: string; updatedAt: string }, score?: number): Insight {
|
||||
return { id: record.id, content: record.content, ...(record.category === undefined ? {} : { category: record.category }), tags: record.tags, source: record.source === 'session' ? 'user' : 'external', createdAt: record.createdAt, ...(score === undefined ? {} : { score }) }
|
||||
}
|
||||
|
||||
export class LocalMnemonProvider implements MemoryProviderAdapter {
|
||||
readonly id = descriptor.id
|
||||
readonly scoreSemantics = { kind: 'provider-native' as const }
|
||||
constructor(private readonly manager: LocalMemoryManager) {}
|
||||
async status(body: MemorySpace): Promise<ProviderSpaceStatus> {
|
||||
try { const status = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body))); return { healthy: true, stats: { totalInsights: Number((status as any).spaces?.project ? 0 : 0), deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } } }
|
||||
catch (error) { return { healthy: false, error: error instanceof Error ? error.message : String(error) } }
|
||||
}
|
||||
async search(body: MemorySpace, request: SearchRequest): Promise<ProviderSearchResult> {
|
||||
const records = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.search(request.query, request.limit ?? 10, workspaceOf(body)))
|
||||
return { results: records.map((record) => insightOf(record)) }
|
||||
}
|
||||
async list(body: MemorySpace, request: MemoryListRequest): Promise<Insight[]> {
|
||||
const page = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.list({ limit: request.limit ?? 50, offset: 0 }, workspaceOf(body)))
|
||||
return page.items.map((record) => insightOf(record))
|
||||
}
|
||||
async remember(body: MemorySpace, request: RememberRequest): Promise<JsonValue> {
|
||||
const result = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.remember({ content: request.content, category: request.category, tags: request.tags, source: 'mnemon-native', scope: 'project' }))
|
||||
return { action: 'stored', id: result.record.id, revision: result.record.revision }
|
||||
}
|
||||
async get(body: MemorySpace, id: string): Promise<Insight | undefined> {
|
||||
const record = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.read(id, workspaceOf(body)))
|
||||
return record === undefined ? undefined : insightOf(record)
|
||||
}
|
||||
async forget(body: MemorySpace, id: string): Promise<JsonValue> {
|
||||
const record = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.forget(id, undefined, workspaceOf(body)))
|
||||
return { action: 'deleted', id: record.id, revision: record.revision }
|
||||
}
|
||||
async graph(): Promise<MemoryGraphSnapshot> { return { nodes: [], edges: [], generatedAt: new Date().toISOString() } }
|
||||
}
|
||||
|
||||
export const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: 'provider',
|
||||
typeId: descriptor.id,
|
||||
packageName: 'dsh-brain',
|
||||
version: VERSION,
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: [],
|
||||
scoreSemantics: 'provider-native',
|
||||
},
|
||||
create: (context) => new LocalMnemonProvider(context.memorySpaces?.runner ? new LocalMemoryManager({ cwd: () => context.memorySpaces?.runner.effectiveDataDir() ?? process.cwd() }) : new LocalMemoryManager()),
|
||||
})
|
||||
|
||||
export default defineMemorySpaceProvider<undefined>({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) { host.install(ctx, definition) },
|
||||
})
|
||||
261
src/reporter.ts
261
src/reporter.ts
|
|
@ -48,9 +48,24 @@ export interface ReporterSnapshot {
|
|||
recent: ReportRecord[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything one outbound request needs, frozen at request start. Requests and
|
||||
* queued retries carry the context they began with: a settings change
|
||||
* mid-flight cannot redirect or re-attribute an in-progress record.
|
||||
*/
|
||||
export interface ReporterConnection {
|
||||
baseUrl: string
|
||||
activityToken: string
|
||||
summaryToken: string
|
||||
timeoutMs: number
|
||||
}
|
||||
|
||||
/** Collaborators the reporter needs. */
|
||||
export interface ReporterOptions {
|
||||
client: CloudClient
|
||||
/** Client bound to one pinned connection context. */
|
||||
clientFor?: (context: ReporterConnection) => CloudClient
|
||||
/** Legacy single client; only safe for tests and single-connection use. */
|
||||
client?: CloudClient
|
||||
/** Effective settings (never a token). */
|
||||
settings: () => { enabled: boolean; clientId: string }
|
||||
/** Activity token, or empty when unconfigured. */
|
||||
|
|
@ -59,6 +74,10 @@ export interface ReporterOptions {
|
|||
summary: () => { enabled: boolean; maxChars: number }
|
||||
/** summary:write token, or empty when summaries are not configured. */
|
||||
summaryToken: () => string
|
||||
/** Current service endpoint, used to bind queues and buffers to one account. */
|
||||
baseUrl?: () => string
|
||||
/** Per-request timeout, mirrored into pinned contexts. */
|
||||
timeoutMs?: () => number
|
||||
/** Log sink for operator-visible diagnostics. */
|
||||
log: (message: string) => void
|
||||
}
|
||||
|
|
@ -107,7 +126,7 @@ export function statusForReason(reason: unknown): TurnStatus | null {
|
|||
}
|
||||
|
||||
/** Extract the numeric turn id from a `turn/start` or `turn/end` payload. */
|
||||
function turnOf(data: Record<string, unknown> | undefined): number | undefined {
|
||||
export function turnOf(data: Record<string, unknown> | undefined): number | undefined {
|
||||
if (data === undefined) return undefined
|
||||
const value = data.turn
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value
|
||||
|
|
@ -173,6 +192,24 @@ interface BufferedMessage extends SummaryMessage {
|
|||
turn?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* One conversation's summary buffer, owned by the connection scope that
|
||||
* collected it. A scope change mid-conversation drops the old text: it must
|
||||
* never be handed to the new account.
|
||||
*/
|
||||
interface TranscriptBuffer {
|
||||
/** `baseUrl|summaryToken` the text was collected under. */
|
||||
scope: string
|
||||
messages: BufferedMessage[]
|
||||
}
|
||||
|
||||
/** A queued retry, bound to the account+endpoint that produced it. */
|
||||
interface QueuedReport {
|
||||
payload: TurnPayload
|
||||
/** `baseUrl|token` of the account that enqueued it; a mismatch drops it. */
|
||||
scope: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks open turns and reports each finished one.
|
||||
*
|
||||
|
|
@ -182,9 +219,12 @@ interface BufferedMessage extends SummaryMessage {
|
|||
/** A queued report is retried at most this many times before being dropped. */
|
||||
const MAX_RETRY_ATTEMPTS = 5
|
||||
|
||||
/** Conversations kept in the summary buffer; the oldest is evicted beyond this. */
|
||||
const MAX_CONVERSATIONS = 50
|
||||
|
||||
export class Reporter {
|
||||
private readonly startedAt = new Map<string, number>()
|
||||
private readonly queue: TurnPayload[] = []
|
||||
private readonly queue: QueuedReport[] = []
|
||||
private readonly retries = new Map<string, number>()
|
||||
private readonly recent: ReportRecord[] = []
|
||||
private attempted = 0
|
||||
|
|
@ -196,7 +236,7 @@ export class Reporter {
|
|||
private lastError: string | undefined
|
||||
private draining = false
|
||||
/** Redacted message text per conversation, consumed at turn/end. */
|
||||
private readonly transcripts = new Map<string, BufferedMessage[]>()
|
||||
private readonly transcripts = new Map<string, TranscriptBuffer>()
|
||||
private summaryAttempted = 0
|
||||
private summaryStaged = 0
|
||||
private summaryFailed = 0
|
||||
|
|
@ -218,7 +258,7 @@ export class Reporter {
|
|||
}
|
||||
}
|
||||
|
||||
/** Handle any `session/event`; only `turn/start` and `turn/end` matter here. */
|
||||
/** Handle any `session/event`; message, turn and session lifecycle events matter. */
|
||||
handleEvent(session: SessionLike | undefined, event: SessionEventLike): void {
|
||||
if (event === null || typeof event !== 'object') return
|
||||
if (event.type === 'user/message' || event.type === 'assistant/message') {
|
||||
|
|
@ -229,15 +269,36 @@ export class Reporter {
|
|||
this.handleStart(session, event)
|
||||
return
|
||||
}
|
||||
if (event.type === 'session/end' || event.type === 'session/close' || event.type === 'session/closed' || event.type === 'session/terminated') {
|
||||
// A session that ends without a turn/end must not leave transcript text
|
||||
// (or start timestamps) behind for a later session with the same id.
|
||||
this.releaseConversation(conversationIdOf(session))
|
||||
return
|
||||
}
|
||||
if (event.type !== 'turn/end') return
|
||||
this.handleEnd(session, event)
|
||||
}
|
||||
|
||||
/** Drop every buffered turn and open-turn timestamp for one conversation. */
|
||||
private releaseConversation(conversationId: string | undefined): void {
|
||||
if (conversationId === undefined) return
|
||||
this.transcripts.delete(conversationId)
|
||||
for (const key of this.startedAt.keys()) {
|
||||
if (key.startsWith(`${conversationId}:`)) this.startedAt.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
private handleEnd(session: SessionLike | undefined, event: SessionEventLike): void {
|
||||
const settings = this.options.settings()
|
||||
const conversationId = conversationIdOf(session)
|
||||
if (conversationId === undefined) return
|
||||
const turn = turnOf(event.data)
|
||||
if (conversationId === undefined || turn === undefined) return
|
||||
if (turn === undefined) {
|
||||
// Without a turn id there is nothing reportable or summarizable; still
|
||||
// release any buffered text so it cannot outlive the conversation.
|
||||
this.releaseConversation(conversationId)
|
||||
return
|
||||
}
|
||||
const key = `${conversationId}:${turn}`
|
||||
const completedAt = toEpochMs(event.time) ?? Date.now()
|
||||
const startedAt = this.startedAt.get(key) ?? completedAt
|
||||
|
|
@ -245,10 +306,18 @@ export class Reporter {
|
|||
const reason = event.data?.reason
|
||||
const status = statusForReason(reason)
|
||||
if (status === null) {
|
||||
// A forked turn restarts in the child session; its partial text would
|
||||
// double-count there, so release it here instead of letting it leak
|
||||
// into the child's summary.
|
||||
this.releaseTranscript(conversationId, turn)
|
||||
this.push({ turnId: key, conversationId, status: 'cancelled', startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'forked turn is not reported' })
|
||||
this.skipped += 1
|
||||
return
|
||||
}
|
||||
// Summary staging and activity reporting are independent features with
|
||||
// independent credentials: every turn releases its buffered text, even
|
||||
// when the activity side is disabled or unconfigured.
|
||||
void this.sendSummary(conversationId, turn, status)
|
||||
if (!settings.enabled) {
|
||||
this.push({ turnId: key, conversationId, status, startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'reporting disabled' })
|
||||
this.skipped += 1
|
||||
|
|
@ -269,34 +338,71 @@ export class Reporter {
|
|||
completed_at: completedAt,
|
||||
}
|
||||
void this.send(payload)
|
||||
void this.sendSummary(conversationId, key, status)
|
||||
}
|
||||
|
||||
/** Buffer one redacted message for the turn that is still open. */
|
||||
/**
|
||||
* Buffer one redacted message for the turn that is still open.
|
||||
*
|
||||
* Nothing is buffered unless summaries are fully configured: a disabled or
|
||||
* token-less summary must not keep accumulating transcript text, and a
|
||||
* message with no turn of its own is dropped rather than attached to an
|
||||
* unrelated future turn.
|
||||
*/
|
||||
private collect(session: SessionLike | undefined, event: SessionEventLike): void {
|
||||
// Summary is part of the activity pipeline: when activity reporting is
|
||||
// switched off, no new transcript text is collected. Buffered text from
|
||||
// before the switch is released in sendSummary instead of being sent.
|
||||
if (!this.options.settings().enabled || !this.options.summary().enabled || this.options.summaryToken() === '') return
|
||||
const conversationId = conversationIdOf(session)
|
||||
if (conversationId === undefined) return
|
||||
const turn = turnOf(event.data)
|
||||
if (turn === undefined) return
|
||||
const raw = textOf(event.data)
|
||||
if (raw === undefined) return
|
||||
const value = redactSecrets(raw).slice(0, 4000)
|
||||
const buffer = this.transcripts.get(conversationId) ?? []
|
||||
buffer.push({ role: event.type === 'user/message' ? 'user' : 'assistant', text: value, turn: turnOf(event.data) })
|
||||
if (buffer.length > 120) buffer.splice(0, buffer.length - 120)
|
||||
this.transcripts.set(conversationId, buffer)
|
||||
const scope = this.summaryScope(this.connection())
|
||||
let buffer = this.transcripts.get(conversationId)
|
||||
if (buffer === undefined) {
|
||||
buffer = { scope, messages: [] }
|
||||
this.transcripts.set(conversationId, buffer)
|
||||
if (this.transcripts.size > MAX_CONVERSATIONS) {
|
||||
const oldest = this.transcripts.keys().next()
|
||||
if (oldest.done !== true) this.transcripts.delete(oldest.value)
|
||||
}
|
||||
} else if (buffer.scope !== scope) {
|
||||
// Connection switched mid-conversation: the earlier text belongs to the
|
||||
// old account and must never reach the new one.
|
||||
this.options.log(`dsh-brain: dropping turn-summary buffer after a connection switch: ${conversationId}`)
|
||||
buffer.scope = scope
|
||||
buffer.messages = []
|
||||
}
|
||||
buffer.messages.push({ role: event.type === 'user/message' ? 'user' : 'assistant', text: value, turn })
|
||||
if (buffer.messages.length > 120) buffer.messages.splice(0, buffer.messages.length - 120)
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the conversation buffer into this turn's messages and the rest.
|
||||
*
|
||||
* Only messages tagged with exactly this turn belong to it; anything else
|
||||
* (a stray turn-less message) is dropped, not reattached to a future turn.
|
||||
*/
|
||||
private partitionTranscript(conversationId: string, turn: number): { picked: SummaryMessage[]; rest: BufferedMessage[] } {
|
||||
const buffer = this.transcripts.get(conversationId)
|
||||
if (buffer === undefined) return { picked: [], rest: [] }
|
||||
const picked: SummaryMessage[] = []
|
||||
const rest: BufferedMessage[] = []
|
||||
for (const item of buffer.messages) {
|
||||
const matches = item.turn !== undefined && item.turn === turn
|
||||
if (matches) picked.push({ role: item.role, text: item.text })
|
||||
else if (item.turn !== undefined && item.turn !== turn) rest.push(item)
|
||||
}
|
||||
buffer.messages = rest
|
||||
return { picked, rest }
|
||||
}
|
||||
|
||||
/** Take this turn's messages out of the buffer, capped by the char budget. */
|
||||
private takeTranscript(conversationId: string, turnKey: string): SummaryMessage[] {
|
||||
const buffer = this.transcripts.get(conversationId) ?? []
|
||||
const turn = Number(turnKey.slice(turnKey.lastIndexOf(':') + 1))
|
||||
const picked: SummaryMessage[] = []
|
||||
const rest: BufferedMessage[] = []
|
||||
for (const item of buffer) {
|
||||
const matches = Number.isFinite(turn) && (item.turn === undefined || item.turn === turn)
|
||||
if (matches) picked.push({ role: item.role, text: item.text })
|
||||
else rest.push(item)
|
||||
}
|
||||
this.transcripts.set(conversationId, rest)
|
||||
private takeTranscript(conversationId: string, turn: number): SummaryMessage[] {
|
||||
const { picked } = this.partitionTranscript(conversationId, turn)
|
||||
const maxChars = Math.max(1000, this.options.summary().maxChars)
|
||||
let total = 0
|
||||
const kept: SummaryMessage[] = []
|
||||
|
|
@ -308,22 +414,54 @@ export class Reporter {
|
|||
return kept
|
||||
}
|
||||
|
||||
/** Stage one summary; failures only surface in the status card. */
|
||||
private async sendSummary(conversationId: string, turnKey: string, status: TurnStatus): Promise<void> {
|
||||
/** Drop this turn's messages without sending them (fork, cancel, disable). */
|
||||
private releaseTranscript(conversationId: string, turn: number): void {
|
||||
this.partitionTranscript(conversationId, turn)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage one summary; failures only surface in the status card.
|
||||
*
|
||||
* Every end path consumes the turn's buffered text: sent, failed, cancelled
|
||||
* and disabled all release the buffer, so a turn never leaves text behind
|
||||
* for an unrelated later turn. Text collected under a different connection
|
||||
* scope is dropped here instead of being handed to the current account.
|
||||
*/
|
||||
private async sendSummary(conversationId: string, turn: number, status: TurnStatus): Promise<void> {
|
||||
const context = this.connection()
|
||||
const scope = this.summaryScope(context)
|
||||
const buffer = this.transcripts.get(conversationId)
|
||||
let messages: SummaryMessage[] = []
|
||||
if (buffer === undefined) {
|
||||
// Nothing was buffered (summaries may have been off during the turn).
|
||||
} else if (buffer.scope === scope) {
|
||||
messages = this.takeTranscript(conversationId, turn)
|
||||
} else {
|
||||
// The buffered text belongs to a different account or service: never
|
||||
// hand it to the current one — release everything.
|
||||
this.options.log(`dsh-brain: dropping turn-summary buffer for a switched account: ${conversationId}`)
|
||||
this.transcripts.delete(conversationId)
|
||||
}
|
||||
const activity = this.options.settings()
|
||||
if (!activity.enabled) {
|
||||
// The activity switch also gates summaries: a turn ending while
|
||||
// reporting is off must release its text, not stage it.
|
||||
this.releaseTranscript(conversationId, turn)
|
||||
return
|
||||
}
|
||||
const summary = this.options.summary()
|
||||
const token = this.options.summaryToken()
|
||||
if (!summary.enabled || token === '' || status !== 'completed') return
|
||||
const messages = this.takeTranscript(conversationId, turnKey)
|
||||
if (messages.length === 0) return
|
||||
const payload: SummaryPayload = { conversation_id: conversationId, turn_id: turnKey, messages }
|
||||
const token = context.summaryToken
|
||||
if (!summary.enabled || token === '' || status !== 'completed' || messages.length === 0) return
|
||||
const payload: SummaryPayload = { conversation_id: conversationId, turn_id: `${conversationId}:${turn}`, messages }
|
||||
this.summaryAttempted += 1
|
||||
const result = await this.options.client.submitSummary(payload, token)
|
||||
const client = this.clientFor(context)
|
||||
const result = await client.submitSummary(payload, token)
|
||||
if (result.ok) {
|
||||
this.summaryStaged += typeof result.data.staged === 'number' ? result.data.staged : 0
|
||||
return
|
||||
}
|
||||
if (result.error.status === 0 || result.error.status >= 500) {
|
||||
const retry = await this.options.client.submitSummary(payload, token)
|
||||
const retry = await client.submitSummary(payload, token)
|
||||
if (retry.ok) {
|
||||
this.summaryStaged += typeof retry.data.staged === 'number' ? retry.data.staged : 0
|
||||
return
|
||||
|
|
@ -342,8 +480,10 @@ export class Reporter {
|
|||
/** Send one payload, queueing it when the failure looks transient. */
|
||||
private async send(payload: TurnPayload): Promise<void> {
|
||||
this.attempted += 1
|
||||
const token = this.options.activityToken()
|
||||
const result = await this.options.client.reportTurn(payload, token)
|
||||
// Pin the connection BEFORE the first await: the record leaves under the
|
||||
// account it was collected for, even when settings change mid-send.
|
||||
const context = this.connection()
|
||||
const result = await this.clientFor(context).reportTurn(payload, context.activityToken)
|
||||
const now = Date.now()
|
||||
if (result.ok) {
|
||||
const duplicate = result.data.duplicate === true || result.status === 200
|
||||
|
|
@ -378,23 +518,68 @@ export class Reporter {
|
|||
})
|
||||
// 4xx (other than 429) means the payload or token is wrong: retrying cannot help.
|
||||
if (result.error.status === 0 || result.error.status >= 500) {
|
||||
this.queue.push(payload)
|
||||
this.queue.push({ payload, scope: this.activityScope(context) })
|
||||
if (this.queue.length > 200) this.queue.shift()
|
||||
}
|
||||
this.options.log(`dsh-brain: turn report failed: ${this.lastError}`)
|
||||
}
|
||||
|
||||
/** Resolve the client bound to the context pinned for this request. */
|
||||
private clientFor(context: ReporterConnection): CloudClient {
|
||||
if (this.options.clientFor !== undefined) return this.options.clientFor(context)
|
||||
if (this.options.client !== undefined) return this.options.client
|
||||
throw new Error('Reporter requires clientFor(context)')
|
||||
}
|
||||
|
||||
/** Snapshot the whole connection at one instant. */
|
||||
private connection(): ReporterConnection {
|
||||
return {
|
||||
baseUrl: this.options.baseUrl === undefined ? '' : this.options.baseUrl(),
|
||||
activityToken: this.options.activityToken(),
|
||||
summaryToken: this.options.summaryToken(),
|
||||
timeoutMs: this.options.timeoutMs === undefined ? 30_000 : this.options.timeoutMs(),
|
||||
}
|
||||
}
|
||||
|
||||
/** Scope key binding an activity record to one endpoint+account. */
|
||||
private activityScope(context: ReporterConnection): string {
|
||||
return `${context.baseUrl}|${context.activityToken}`
|
||||
}
|
||||
|
||||
/** Scope key binding summary text to one endpoint+account. */
|
||||
private summaryScope(context: ReporterConnection): string {
|
||||
return `${context.baseUrl}|${context.summaryToken}`
|
||||
}
|
||||
|
||||
/** Retry queued reports; safe to call at any time. */
|
||||
async flush(): Promise<{ sent: number; remaining: number }> {
|
||||
if (this.draining) return { sent: 0, remaining: this.queue.length }
|
||||
// Retrying is a reporting action: when reporting is switched off, the
|
||||
// queue waits instead of pushing data the user turned off.
|
||||
if (!this.options.settings().enabled) return { sent: 0, remaining: this.queue.length }
|
||||
this.draining = true
|
||||
let sent = 0
|
||||
try {
|
||||
while (this.queue.length > 0) {
|
||||
const payload = this.queue[0]
|
||||
if (payload === undefined) break
|
||||
// Re-check the gates on EVERY entry: a mid-flush disable stops new
|
||||
// requests (records already sent are not recalled), and a mid-flush
|
||||
// account switch drops the remaining old-account entries.
|
||||
if (!this.options.settings().enabled) break
|
||||
const context = this.connection()
|
||||
const scope = this.activityScope(context)
|
||||
// A queued entry belongs to the account that failed to send it. After a
|
||||
// token or endpoint switch the current credential must not replay old
|
||||
// records to (or as) a different account, so stale entries are dropped.
|
||||
const head = this.queue[0]
|
||||
if (head === undefined) break
|
||||
if (head.scope !== scope) {
|
||||
this.queue.shift()
|
||||
this.options.log(`dsh-brain: dropping queued turn report for a switched account: ${head.payload.turn_id}`)
|
||||
continue
|
||||
}
|
||||
const payload = head.payload
|
||||
this.attempted += 1
|
||||
const result = await this.options.client.reportTurn(payload, this.options.activityToken())
|
||||
const result = await this.clientFor(context).reportTurn(payload, context.activityToken)
|
||||
if (!result.ok) {
|
||||
this.lastError = describeError(result.error)
|
||||
this.failed += 1
|
||||
|
|
|
|||
104
src/routes.ts
104
src/routes.ts
|
|
@ -25,6 +25,7 @@ import type { SettingsStore, SettingsView, TokenView } from './store.ts'
|
|||
import type { Reporter } from './reporter.ts'
|
||||
import { createSettingsUiRoutes } from './settings-ui/routes.ts'
|
||||
import type { CloudMemoryWebRoute } from './context-types.ts'
|
||||
import type { LocalMemoryManager } from './local-memory/manager.ts'
|
||||
import type { SkillSync, SkillSyncStats } from './skill-sync.ts'
|
||||
import type { SkillAdmin } from './skill-admin.ts'
|
||||
import type { SkillGroupManager } from './skill-groups.ts'
|
||||
|
|
@ -51,6 +52,7 @@ export const ROUTES = {
|
|||
sync: '/dsh-brain/sync',
|
||||
clients: '/dsh-brain/clients',
|
||||
migrate: '/dsh-brain/migrate',
|
||||
localMemory: '/dsh-brain/local-memory',
|
||||
} as const
|
||||
|
||||
/** Everything the routes need from the plugin core. */
|
||||
|
|
@ -75,6 +77,8 @@ export interface RouteDeps {
|
|||
clients?: ClientRegistry
|
||||
/** Whether the MCP sub-plugin entry is applied (gates the MCP tab). */
|
||||
mcp?: boolean
|
||||
/** Local memory manager, when the memory bundle is available. */
|
||||
localMemory?: LocalMemoryManager
|
||||
}
|
||||
|
||||
/** One feature flag the card reads before it renders a control. */
|
||||
|
|
@ -166,6 +170,12 @@ export function buildStatusPayload(deps: RouteDeps): Record<string, unknown> {
|
|||
memoryEnabled: view.memoryEnabled,
|
||||
skillsSyncEnabled: view.skillsSyncEnabled,
|
||||
skillsDir: view.skillsDir,
|
||||
localMemoryEnabled: view.localMemoryEnabled,
|
||||
cloudMemoryEnabled: view.cloudMemoryEnabled,
|
||||
autoMemorySpaces: view.autoMemorySpaces,
|
||||
autoSummaryEnabled: view.autoSummaryEnabled,
|
||||
autoProfileEnabled: view.autoProfileEnabled,
|
||||
localMemoryK: view.localMemoryK,
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
|
|
@ -235,6 +245,95 @@ async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerRes
|
|||
})
|
||||
}
|
||||
|
||||
/** Local memory management API: status/search/documents/backup/migration. */
|
||||
async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const manager = deps.localMemory
|
||||
if (manager === undefined) {
|
||||
fail(res, 503, 'local-memory-unavailable')
|
||||
return
|
||||
}
|
||||
const url = new URL(req.url ?? '/', 'http://localhost')
|
||||
const marker = '/local-memory'
|
||||
const markerAt = url.pathname.indexOf(marker)
|
||||
const suffix = markerAt < 0 ? '' : url.pathname.slice(markerAt + marker.length)
|
||||
if (suffix === '' || suffix === '/' || suffix === '/status') {
|
||||
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
|
||||
json(res, 200, { ok: true, ...(await manager.storageStatus()) })
|
||||
return
|
||||
}
|
||||
if (suffix === '/spaces') {
|
||||
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
|
||||
json(res, 200, { ok: true, spaces: await manager.projects() })
|
||||
return
|
||||
}
|
||||
if (suffix === '/documents') {
|
||||
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
|
||||
json(res, 200, { ok: true, documents: await manager.documents() })
|
||||
return
|
||||
}
|
||||
if (suffix === '/memories') {
|
||||
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
|
||||
const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50))
|
||||
const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0)
|
||||
const page = await manager.list({ limit, offset })
|
||||
json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) })
|
||||
return
|
||||
}
|
||||
if (suffix === '/forget') {
|
||||
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
|
||||
if (!sameOrigin(req)) { fail(res, 403, 'origin-rejected'); return }
|
||||
let body: unknown
|
||||
try { body = JSON.parse(await readBody(req)) } catch { fail(res, 400, 'invalid-json'); return }
|
||||
if (body === null || typeof body !== 'object' || Array.isArray(body)) { fail(res, 400, 'invalid-body'); return }
|
||||
const input = body as Record<string, unknown>
|
||||
const id = typeof input.id === 'string' ? input.id.trim() : ''
|
||||
if (id === '') { fail(res, 400, 'id-required'); return }
|
||||
const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined
|
||||
json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision) })
|
||||
return
|
||||
}
|
||||
if (suffix === '/search') {
|
||||
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
|
||||
const query = (url.searchParams.get('q') ?? '').trim()
|
||||
if (query === '') { fail(res, 400, 'query-required'); return }
|
||||
const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10)
|
||||
const k = Number.isFinite(requested) ? Math.max(1, Math.min(100, requested)) : 5
|
||||
const records = await manager.search(query, k)
|
||||
json(res, 200, { ok: true, query, count: records.length, matches: records.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) })
|
||||
return
|
||||
}
|
||||
if (suffix === '/backup') {
|
||||
if (req.method !== 'POST' || !sameOrigin(req)) { fail(res, req.method !== 'POST' ? 405 : 403, req.method !== 'POST' ? 'method-not-allowed' : 'origin-rejected'); return }
|
||||
json(res, 200, { ok: true, ...(await manager.createBackup()) })
|
||||
return
|
||||
}
|
||||
if (suffix === '/migrate') {
|
||||
if (req.method === 'GET') { const report = await manager.legacyMigrationReport(); json(res, 200, { ok: true, ...report }); return }
|
||||
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
|
||||
if (!sameOrigin(req)) { fail(res, 403, 'origin-rejected'); return }
|
||||
let body: unknown
|
||||
try { body = JSON.parse(await readBody(req)) } catch { fail(res, 400, 'invalid-json'); return }
|
||||
if (body === null || typeof body !== 'object' || Array.isArray(body)) { fail(res, 400, 'invalid-body'); return }
|
||||
const input = body as Record<string, unknown>
|
||||
const action = typeof input.action === 'string' ? input.action : 'report'
|
||||
if (action === 'report') { const report = await manager.legacyMigrationReport(); json(res, 200, { ok: true, ...report }); return }
|
||||
if (action === 'migrate') {
|
||||
if (typeof input.path !== 'string' || input.path.trim() === '') { fail(res, 400, 'path-required'); return }
|
||||
json(res, 200, { ok: true, ...(await manager.migrateLegacy(input.path.trim())) })
|
||||
return
|
||||
}
|
||||
if (action === 'rollback') {
|
||||
if (typeof input.copiedTo !== 'string' || input.copiedTo.trim() === '') { fail(res, 400, 'copiedTo-required'); return }
|
||||
const destination = typeof input.destination === 'string' && input.destination.trim() !== '' ? input.destination.trim() : undefined
|
||||
json(res, 200, { ok: true, ...(await manager.rollbackMigration(input.copiedTo.trim(), destination)) })
|
||||
return
|
||||
}
|
||||
fail(res, 400, 'unknown-action')
|
||||
return
|
||||
}
|
||||
fail(res, 404, 'unknown-local-memory-route')
|
||||
}
|
||||
|
||||
/** dsh-brain data migration: GET status, POST run. */
|
||||
async function serveMigrate(_deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const url = new URL(req.url ?? '/', 'http://localhost')
|
||||
|
|
@ -299,6 +398,11 @@ export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] {
|
|||
*/
|
||||
export function createCoreRoutes(deps: RouteDeps): CloudMemoryWebRoute[] {
|
||||
return [
|
||||
{
|
||||
kind: 'prefix',
|
||||
path: ROUTES.localMemory,
|
||||
handler: (req, res) => serveLocalMemory(deps, req, res),
|
||||
},
|
||||
{
|
||||
kind: 'exact',
|
||||
path: ROUTES.status,
|
||||
|
|
|
|||
|
|
@ -268,6 +268,11 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
<input id="defaultK" type="number" min="1" max="100" />
|
||||
<div class="hint">memory_search 未显式指定 k 时的返回上限(1–100)。</div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="localMemoryK">本地记忆检索条数</label>
|
||||
<input id="localMemoryK" type="number" min="1" max="100" />
|
||||
<div class="hint">本地优先模式默认返回 5 条,可按项目调整。</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="toggles">
|
||||
<label class="toggle" for="memoryEnabled">
|
||||
|
|
@ -275,6 +280,31 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
<span class="track"></span>
|
||||
<span><span class="ttitle">启用记忆工具</span><span class="tdesc">未显式设置时跟随总开关</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="localMemoryEnabled">
|
||||
<input id="localMemoryEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">本地记忆</span><span class="tdesc">离线可用,不需要账号或令牌</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="cloudMemoryEnabled">
|
||||
<input id="cloudMemoryEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">云端记忆适配器</span><span class="tdesc">需要已配置记忆令牌;默认关闭</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="autoMemorySpaces">
|
||||
<input id="autoMemorySpaces" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">自动创建空间</span><span class="tdesc">全局与当前项目空间幂等创建</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="autoSummaryEnabled">
|
||||
<input id="autoSummaryEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">自动总结</span><span class="tdesc">只保存明确表达的长期信息</span></span>
|
||||
</label>
|
||||
<label class="toggle" for="autoProfileEnabled">
|
||||
<input id="autoProfileEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">自动画像</span><span class="tdesc">只保存明确偏好,推测进入待确认区</span></span>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
|
@ -410,6 +440,12 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
el('clientId').value = settings.clientId || '';
|
||||
el('requestTimeoutMs').value = settings.requestTimeoutMs || '';
|
||||
el('defaultK').value = settings.defaultK || '';
|
||||
el('localMemoryK').value = settings.localMemoryK || '';
|
||||
el('localMemoryEnabled').checked = settings.localMemoryEnabled !== false;
|
||||
el('cloudMemoryEnabled').checked = settings.cloudMemoryEnabled === true;
|
||||
el('autoMemorySpaces').checked = settings.autoMemorySpaces !== false;
|
||||
el('autoSummaryEnabled').checked = settings.autoSummaryEnabled !== false;
|
||||
el('autoProfileEnabled').checked = settings.autoProfileEnabled !== false;
|
||||
el('enabled').checked = settings.enabled === true;
|
||||
el('activityEnabled').checked = settings.activityEnabled === true;
|
||||
el('summaryEnabled').checked = settings.summaryEnabled === true;
|
||||
|
|
@ -491,6 +527,12 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
clientId: el('clientId').value.trim(),
|
||||
requestTimeoutMs: Number(el('requestTimeoutMs').value),
|
||||
defaultK: Number(el('defaultK').value),
|
||||
localMemoryK: Number(el('localMemoryK').value),
|
||||
localMemoryEnabled: el('localMemoryEnabled').checked,
|
||||
cloudMemoryEnabled: el('cloudMemoryEnabled').checked,
|
||||
autoMemorySpaces: el('autoMemorySpaces').checked,
|
||||
autoSummaryEnabled: el('autoSummaryEnabled').checked,
|
||||
autoProfileEnabled: el('autoProfileEnabled').checked,
|
||||
enabled: el('enabled').checked,
|
||||
activityEnabled: el('activityEnabled').checked,
|
||||
summaryEnabled: el('summaryEnabled').checked,
|
||||
|
|
|
|||
|
|
@ -160,7 +160,7 @@ async function walkFiles(dir: string, cap = MAX_SKILL_FILES + 1): Promise<{ path
|
|||
}
|
||||
|
||||
/** A folder name we are willing to move around: one path segment, no tricks. */
|
||||
function checkFolder(folder: unknown): string {
|
||||
export function checkFolder(folder: unknown): string {
|
||||
if (typeof folder !== 'string' || folder === '' || folder.length > 128 ||
|
||||
folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0')) {
|
||||
fail('invalid_name', `技能目录名无效:${String(folder)}`)
|
||||
|
|
@ -278,7 +278,16 @@ export class SkillAdmin {
|
|||
}
|
||||
|
||||
private guardSync(): void {
|
||||
if (this.deps.gate().isRunning()) fail('sync_running', '技能同步正在进行,请稍候再试。')
|
||||
const gate = this.deps.gate()
|
||||
const busy = gate.busy === undefined ? gate.isRunning() : gate.busy()
|
||||
if (busy) fail('sync_running', '技能同步正在进行,请稍候再试。')
|
||||
}
|
||||
|
||||
/** Run one whole admin transaction behind the shared sync/update mutex. */
|
||||
private async exclusive<T>(job: () => Promise<T>): Promise<T> {
|
||||
this.guardSync()
|
||||
const gate = this.deps.gate()
|
||||
return gate.runExclusive === undefined ? job() : gate.runExclusive(job)
|
||||
}
|
||||
|
||||
private async describe(
|
||||
|
|
@ -395,7 +404,7 @@ export class SkillAdmin {
|
|||
|
||||
/** Enable (move back into the root) or disable (park) one skill. */
|
||||
async setEnabled(folderInput: unknown, enabled: boolean): Promise<{ folder: string; enabled: boolean; note: string }> {
|
||||
this.guardSync()
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput)
|
||||
const found = await this.locate(folder)
|
||||
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
|
||||
|
|
@ -416,6 +425,7 @@ export class SkillAdmin {
|
|||
}
|
||||
this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`)
|
||||
return { folder, enabled, note: this.effectNote(enabled) }
|
||||
})
|
||||
}
|
||||
|
||||
/** The enable/disable mechanism is a directory move, not a live switch. */
|
||||
|
|
@ -465,7 +475,7 @@ export class SkillAdmin {
|
|||
* itself stays usable by the verification harness and by trusted callers.
|
||||
*/
|
||||
async remove(folderInput: unknown): Promise<{ folder: string; dir: string; files: number; bytes: number }> {
|
||||
this.guardSync()
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput)
|
||||
const found = await this.locate(folder)
|
||||
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
|
||||
|
|
@ -474,6 +484,7 @@ export class SkillAdmin {
|
|||
await rm(found.dir, { recursive: true, force: true })
|
||||
this.deps.log(`skill deleted: ${folder}`)
|
||||
return { folder, dir: found.dir, files: files.length, bytes }
|
||||
})
|
||||
}
|
||||
|
||||
private async readPlans(): Promise<PlansFile> {
|
||||
|
|
@ -522,7 +533,7 @@ export class SkillAdmin {
|
|||
commit?: string
|
||||
candidates: (InstallPlanCandidate & { id: string })[]
|
||||
}> {
|
||||
this.guardSync()
|
||||
return this.exclusive(async () => {
|
||||
if (typeof urlInput !== 'string') fail('invalid_url', '请提供仓库地址。')
|
||||
const url = urlInput.trim()
|
||||
if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) {
|
||||
|
|
@ -629,6 +640,7 @@ export class SkillAdmin {
|
|||
...(commit === '' ? {} : { commit }),
|
||||
candidates: candidates.map((candidate) => ({ ...candidate, id: candidate.folder })) as (InstallPlanCandidate & { id: string })[],
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** Install the folders the user picked from a staged plan. */
|
||||
|
|
@ -637,7 +649,7 @@ export class SkillAdmin {
|
|||
skipped: { folder: string; reason: string }[]
|
||||
remaining: string[]
|
||||
}> {
|
||||
this.guardSync()
|
||||
return this.exclusive(async () => {
|
||||
const planId = typeof planInput.planId === 'string' ? planInput.planId : ''
|
||||
if (planId === '') fail('invalid_plan', '缺少安装计划 id。')
|
||||
const selection = Array.isArray(planInput.folders) ? planInput.folders : []
|
||||
|
|
@ -666,7 +678,7 @@ export class SkillAdmin {
|
|||
const stagingRoot = resolve(plan.stagingDir)
|
||||
const source = candidate.rel !== undefined && candidate.rel !== ''
|
||||
? resolve(stagingRoot, candidate.rel)
|
||||
: candidate.folder === basename(plan.stagingDir) ? stagingRoot : resolve(stagingRoot, candidate.folder)
|
||||
: stagingRoot
|
||||
const target = resolve(skillsRoot, candidate.folder)
|
||||
// Both sides must stay inside their own root: a crafted plan file cannot
|
||||
// make this write outside the skills directory.
|
||||
|
|
@ -706,6 +718,7 @@ export class SkillAdmin {
|
|||
await this.writePlans(file)
|
||||
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => {})
|
||||
return { installed, skipped, remaining }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -717,7 +730,7 @@ export class SkillAdmin {
|
|||
* like a git install does.
|
||||
*/
|
||||
async importFolder(fromDir: string, folderInput: unknown): Promise<{ folder: string }> {
|
||||
this.guardSync()
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput)
|
||||
const existing = await this.locate(folder)
|
||||
if (existing !== undefined) {
|
||||
|
|
@ -735,10 +748,12 @@ export class SkillAdmin {
|
|||
})
|
||||
this.deps.log(`skill imported from another tool: ${folder}`)
|
||||
return { folder }
|
||||
})
|
||||
}
|
||||
|
||||
/** Throw away a staged plan and its clone. */
|
||||
async cancelInstall(planInput: { planId?: unknown }): Promise<{ cancelled: string }> {
|
||||
return this.exclusive(async () => {
|
||||
const planId = typeof planInput.planId === 'string' ? planInput.planId : ''
|
||||
if (planId === '') fail('invalid_plan', '缺少安装计划 id。')
|
||||
const file = await this.sweepPlans(await this.readPlans())
|
||||
|
|
@ -747,6 +762,7 @@ export class SkillAdmin {
|
|||
await this.writePlans(file)
|
||||
if (plan !== undefined) await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => {})
|
||||
return { cancelled: planId }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -773,10 +789,11 @@ export class SkillAdmin {
|
|||
}
|
||||
|
||||
/** Pending plans, so a reloaded page can resume a staged install. */
|
||||
async listPlans(): Promise<{ plans: { planId: string; url: string; expiresAt: number; folders: string[] }[] }> { const file = await this.sweepPlans(await this.readPlans())
|
||||
await this.writePlans(file)
|
||||
async listPlans(): Promise<{ plans: { planId: string; url: string; expiresAt: number; folders: string[] }[] }> {
|
||||
const file = await this.readPlans()
|
||||
const now = Date.now()
|
||||
return {
|
||||
plans: file.plans.map((plan) => ({
|
||||
plans: file.plans.filter((plan) => plan.expiresAt > now).map((plan) => ({
|
||||
planId: plan.id,
|
||||
url: plan.url,
|
||||
expiresAt: plan.expiresAt,
|
||||
|
|
|
|||
|
|
@ -36,8 +36,8 @@
|
|||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { SkillLocalBundle, SkillProvenance, SkillRepository, SkillRepositoryDelivery, SkillRepositoryFile, SkillSyncGate } from './skills/contracts.ts'
|
||||
import { CLOUD_SKILL_NAME, isCloudSkillPath, linkedSkillManifest, MAX_FILE_BYTES, MAX_FILES, MAX_SKILL_BYTES, parseSkillFrontmatter, TEXT_EXT } from './skills/shared.ts'
|
||||
import {mkdir, readFile, rename, stat, writeFile} from 'node:fs/promises'
|
||||
import { CLOUD_SKILL_NAME, isCloudSkillPath, linkedSkillManifest, MAX_FILE_BYTES, MAX_FILES, MAX_SKILL_BYTES, parseSkillFrontmatter, sha256Hex, TEXT_EXT } from './skills/shared.ts'
|
||||
import {mkdir, readFile, rename, rm, stat, writeFile} from 'node:fs/promises'
|
||||
import {dirname, join} from 'node:path'
|
||||
import type {CloudClient, SkillSummary, SkillUploadFile} from './api.ts'
|
||||
import {describeError} from './api.ts'
|
||||
|
|
@ -78,6 +78,8 @@ type AutoResolution = 'resolved' | 'conflict' | 'unresolved'
|
|||
export interface SkillSyncConflict {
|
||||
name: string
|
||||
reason: string
|
||||
/** Scope key captured when the conflict was detected. */
|
||||
scopeKey?: string
|
||||
}
|
||||
|
||||
/** Outcome of the most recent (or running) sync pass. */
|
||||
|
|
@ -92,12 +94,51 @@ export interface SkillSyncStats {
|
|||
skipped: number
|
||||
}
|
||||
|
||||
/** Endpoint + account identity + local root that one sync state belongs to. */
|
||||
export interface SkillSyncScope {
|
||||
endpoint: string
|
||||
/** SHA-256 hex of the account token. Never store the raw token. */
|
||||
account: string
|
||||
/** Absolute local skills root this state applies to. */
|
||||
root: string
|
||||
}
|
||||
|
||||
/** What the sidecar remembers about one locally-originated upload. */
|
||||
interface UploadRecord {
|
||||
folder: string
|
||||
revision: number
|
||||
manifest: string
|
||||
/** Files that belonged to the last upload; used to remove stale cloud-owned files. */
|
||||
files?: { path: string; sha256: string }[]
|
||||
syncedAt: string
|
||||
endpoint?: string
|
||||
account?: string
|
||||
root?: string
|
||||
}
|
||||
|
||||
/** One cloud delivery receipt remembered for the active scope. */
|
||||
interface DeliveredRecord {
|
||||
manifest: string
|
||||
/** Actual local folder when it differs from the logical cloud name. */
|
||||
folder?: string
|
||||
syncedAt?: string
|
||||
endpoint?: string
|
||||
account?: string
|
||||
root?: string
|
||||
}
|
||||
|
||||
/** One local deletion marker, scoped to the endpoint/account/root it came from. */
|
||||
interface RemovedRecord {
|
||||
manifest: string
|
||||
endpoint?: string
|
||||
account?: string
|
||||
root?: string
|
||||
}
|
||||
|
||||
interface ScopeState extends SkillSyncScope {
|
||||
uploaded: Record<string, UploadRecord>
|
||||
delivered: Record<string, DeliveredRecord>
|
||||
removed: Record<string, RemovedRecord>
|
||||
}
|
||||
|
||||
/** Sidecar state: `$DSH_HOME/dsh-brain-skills.json` (legacy `cloud-memory-skills.json` migrates on first use). */
|
||||
|
|
@ -109,16 +150,25 @@ export function skillsStatePath(): string {
|
|||
return target
|
||||
}
|
||||
interface SyncState {
|
||||
version: 1
|
||||
version: 2
|
||||
key: string
|
||||
scope: SkillSyncScope
|
||||
/** Views of the active scope; the top-level JSON mirrors these for old readers. */
|
||||
uploaded: Record<string, UploadRecord>
|
||||
/** Cloud skills currently delivered locally, by delivered manifest. */
|
||||
delivered: Record<string, { manifest: string }>
|
||||
delivered: Record<string, DeliveredRecord>
|
||||
removed: Record<string, RemovedRecord>
|
||||
/** Every kept scope, including scopes used by other accounts/roots. */
|
||||
scopes: Record<string, ScopeState>
|
||||
/**
|
||||
* Skills the user deleted locally, by the cloud manifest at deletion
|
||||
* time. A deleted skill stays deleted until the cloud publishes a
|
||||
* different manifest; the cloud copy itself is never removed.
|
||||
* Pre-scope state (v1) has no endpoint/account/root, so it is quarantined:
|
||||
* it is kept on disk but never used to auto-upload old-origin content into
|
||||
* whatever account happens to be configured now.
|
||||
*/
|
||||
removed: Record<string, { manifest: string }>
|
||||
legacy?: {
|
||||
uploaded: Record<string, UploadRecord>
|
||||
delivered: Record<string, DeliveredRecord>
|
||||
removed: Record<string, RemovedRecord>
|
||||
}
|
||||
}
|
||||
|
||||
/** One local skill read into the sync shape. */
|
||||
|
|
@ -136,9 +186,26 @@ export interface SkillSyncDeps {
|
|||
settings: () => { enabled: boolean; skillsSyncEnabled: boolean }
|
||||
repository: () => SkillRepository
|
||||
log: (message: string) => void
|
||||
/**
|
||||
* Identity of the configured endpoint/account/root. The kernel wires the
|
||||
* live settings here; direct constructions (tests, embedding) may omit it
|
||||
* and share one default scope.
|
||||
*/
|
||||
scope?: () => { endpoint: string; accountToken: string; root: string }
|
||||
/** Build a client pinned to the scope captured at the start of a sync pass. */
|
||||
clientForScope?: (scope: { endpoint: string; accountToken: string; root: string }) => CloudClient
|
||||
/** Build a repository pinned to the local root captured at the start of a sync pass. */
|
||||
repositoryForScope?: (scope: SkillSyncScope) => SkillRepository
|
||||
}
|
||||
export class SkillSync implements SkillSyncGate {
|
||||
private running = false
|
||||
/** Tail of the serialization queue shared by every skill write transaction. */
|
||||
private queueTail: Promise<unknown> = Promise.resolve()
|
||||
/** Jobs accepted into the queue but not settled yet; makes busy() honest. */
|
||||
private pendingWrites = 0
|
||||
private stateCache: { mtimeMs: number; scopeKey: string; state: SyncState } | undefined
|
||||
private runRepository: SkillRepository | undefined
|
||||
private runScopeKey: string | undefined
|
||||
private current: SkillSyncStats = {
|
||||
running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0,
|
||||
}
|
||||
|
|
@ -149,9 +216,28 @@ export class SkillSync implements SkillSyncGate {
|
|||
stats(): SkillSyncStats {
|
||||
return this.current
|
||||
}
|
||||
/** SkillSyncGate: true while a pass is in flight. */
|
||||
/** SkillSyncGate: true while any sync/resolve/admin write transaction is queued or running. */
|
||||
isRunning(): boolean {
|
||||
return this.running || this.current.running
|
||||
return this.busy()
|
||||
}
|
||||
|
||||
/** SkillSyncGate: richer busy signal covering queued writes too. */
|
||||
busy(): boolean {
|
||||
return this.running || this.current.running || this.pendingWrites > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* SkillSyncGate: the one shared write lock. Every mutating entry point —
|
||||
* sync passes, resolves, admin moves/installs/deletes, update and rollback
|
||||
* — enters through this queue, so their async bodies never interleave.
|
||||
*/
|
||||
async runExclusive<T>(job: () => Promise<T>): Promise<T> {
|
||||
this.pendingWrites += 1
|
||||
try {
|
||||
return await this.enqueue(job)
|
||||
} finally {
|
||||
this.pendingWrites -= 1
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -173,14 +259,15 @@ export class SkillSync implements SkillSyncGate {
|
|||
return null
|
||||
}
|
||||
|
||||
private stateCache: { mtimeMs: number; state: SyncState } | undefined
|
||||
|
||||
private async loadStateCached(): Promise<SyncState> {
|
||||
const info = await stat(this.statePath()).catch(() => undefined)
|
||||
const mtimeMs = info?.mtimeMs ?? -1
|
||||
if (this.stateCache !== undefined && this.stateCache.mtimeMs === mtimeMs) return this.stateCache.state
|
||||
const scopeKey = this.scopeKey(this.scopeIdentity())
|
||||
if (this.stateCache !== undefined && this.stateCache.mtimeMs === mtimeMs && this.stateCache.scopeKey === scopeKey) {
|
||||
return this.stateCache.state
|
||||
}
|
||||
const state = await this.loadState()
|
||||
this.stateCache = { mtimeMs, state }
|
||||
this.stateCache = { mtimeMs, scopeKey, state }
|
||||
return state
|
||||
}
|
||||
|
||||
|
|
@ -203,8 +290,15 @@ export class SkillSync implements SkillSyncGate {
|
|||
* makes the DOWN pass skip the name (uploaded) while the UP pass skips its
|
||||
* local folder (delivery manifest), so neither side ever syncs again.
|
||||
*/
|
||||
private markDelivered(state: SyncState, name: string, manifest: string): void {
|
||||
state.delivered[name] = { manifest }
|
||||
private markDelivered(state: SyncState, name: string, manifest: string, folder?: string): void {
|
||||
state.delivered[name] = {
|
||||
manifest,
|
||||
...(folder === undefined || folder === name ? {} : { folder }),
|
||||
syncedAt: new Date().toISOString(),
|
||||
endpoint: state.scope.endpoint,
|
||||
account: state.scope.account,
|
||||
root: state.scope.root,
|
||||
}
|
||||
delete state.uploaded[name]
|
||||
}
|
||||
|
||||
|
|
@ -214,25 +308,121 @@ export class SkillSync implements SkillSyncGate {
|
|||
* skipped as cloud-origin.
|
||||
*/
|
||||
private markUploaded(state: SyncState, name: string, record: UploadRecord): void {
|
||||
state.uploaded[name] = record
|
||||
state.uploaded[name] = {
|
||||
...record,
|
||||
endpoint: state.scope.endpoint,
|
||||
account: state.scope.account,
|
||||
root: state.scope.root,
|
||||
}
|
||||
delete state.delivered[name]
|
||||
}
|
||||
|
||||
private async loadState(): Promise<SyncState> {
|
||||
const clean = { version: 1 as const, uploaded: {}, delivered: {}, removed: {} }
|
||||
/** Active scope identity, derived from the live endpoint/account/root. */
|
||||
private scopeIdentity(rawScope?: { endpoint: string; accountToken: string; root: string }): SkillSyncScope {
|
||||
const raw = rawScope ?? this.deps.scope?.()
|
||||
if (raw === undefined) return { endpoint: 'default', account: sha256Hex(''), root: 'default' }
|
||||
const endpoint = raw.endpoint.trim().replace(/\/+$/, '') || 'default'
|
||||
return { endpoint, account: sha256Hex(raw.accountToken), root: raw.root }
|
||||
}
|
||||
|
||||
private scopeKey(scope: SkillSyncScope): string {
|
||||
return sha256Hex(`${scope.endpoint}\n${scope.account}\n${scope.root}`).slice(0, 32)
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this exact local bundle was uploaded under another endpoint,
|
||||
* account or local root. Switching accounts must never silently publish the
|
||||
* previous account's source content into the new account.
|
||||
*/
|
||||
private foreignUpload(state: SyncState, folder: string, manifest: string): boolean {
|
||||
for (const [key, scope] of Object.entries(state.scopes)) {
|
||||
if (key === state.key) continue
|
||||
for (const record of Object.values(scope.uploaded)) {
|
||||
if (record.folder === folder) return true
|
||||
}
|
||||
}
|
||||
const legacy = state.legacy?.uploaded ?? {}
|
||||
return Object.values(legacy).some((record) => record.folder === folder)
|
||||
}
|
||||
|
||||
private emptyState(scope: SkillSyncScope = this.scopeIdentity()): SyncState {
|
||||
return {
|
||||
version: 2,
|
||||
key: this.scopeKey(scope),
|
||||
scope,
|
||||
uploaded: {},
|
||||
delivered: {},
|
||||
removed: {},
|
||||
scopes: {},
|
||||
}
|
||||
}
|
||||
|
||||
private static mapOf<T>(value: unknown): Record<string, T> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, T>) : {}
|
||||
}
|
||||
|
||||
private static scopeOf(value: unknown): ScopeState | undefined {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
|
||||
const raw = value as Record<string, unknown>
|
||||
if (typeof raw.endpoint !== 'string' || typeof raw.account !== 'string' || typeof raw.root !== 'string') return undefined
|
||||
return {
|
||||
endpoint: raw.endpoint,
|
||||
account: raw.account,
|
||||
root: raw.root,
|
||||
uploaded: SkillSync.mapOf(raw.uploaded),
|
||||
delivered: SkillSync.mapOf(raw.delivered),
|
||||
removed: SkillSync.mapOf(raw.removed),
|
||||
}
|
||||
}
|
||||
|
||||
private async loadState(scope: SkillSyncScope = this.scopeIdentity()): Promise<SyncState> {
|
||||
const clean = this.emptyState(scope)
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(await readFile(this.statePath(), 'utf8'))
|
||||
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
const raw = parsed as { uploaded?: unknown; delivered?: unknown; removed?: unknown }
|
||||
const map = (value: unknown): Record<string, never> =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, never>) : {}
|
||||
return {
|
||||
version: 1,
|
||||
uploaded: map(raw.uploaded) as Record<string, UploadRecord>,
|
||||
delivered: map(raw.delivered) as Record<string, { manifest: string }>,
|
||||
removed: map(raw.removed) as Record<string, { manifest: string }>,
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return clean
|
||||
const raw = parsed as Record<string, unknown>
|
||||
const scopes: Record<string, ScopeState> = {}
|
||||
if (raw.scopes !== null && typeof raw.scopes === 'object' && !Array.isArray(raw.scopes)) {
|
||||
for (const [key, value] of Object.entries(raw.scopes as Record<string, unknown>)) {
|
||||
const scope = SkillSync.scopeOf(value)
|
||||
if (scope !== undefined) scopes[key] = scope
|
||||
}
|
||||
}
|
||||
if (raw.version === 2) {
|
||||
const active = scopes[clean.key]
|
||||
const legacy = raw.legacy !== null && typeof raw.legacy === 'object' && !Array.isArray(raw.legacy)
|
||||
? raw.legacy as Record<string, unknown>
|
||||
: undefined
|
||||
return {
|
||||
...clean,
|
||||
scopes,
|
||||
uploaded: active?.uploaded ?? {},
|
||||
delivered: active?.delivered ?? {},
|
||||
removed: active?.removed ?? {},
|
||||
...(legacy === undefined ? {} : {
|
||||
legacy: {
|
||||
uploaded: SkillSync.mapOf(legacy.uploaded),
|
||||
delivered: SkillSync.mapOf(legacy.delivered),
|
||||
removed: SkillSync.mapOf(legacy.removed),
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
// v1 sidecar: no way to prove which endpoint/account/root wrote it.
|
||||
// Keep it as a read-only quarantine so old-origin content can never be
|
||||
// auto-uploaded into a newly configured account.
|
||||
const legacy = {
|
||||
uploaded: SkillSync.mapOf<UploadRecord>(raw.uploaded),
|
||||
delivered: SkillSync.mapOf<DeliveredRecord>(raw.delivered),
|
||||
removed: SkillSync.mapOf<RemovedRecord>(raw.removed),
|
||||
}
|
||||
return {
|
||||
...clean,
|
||||
// A local deletion is user intent, not account content, so the marker
|
||||
// itself may carry forward; uploaded/delivered records stay quarantined.
|
||||
removed: { ...legacy.removed },
|
||||
legacy,
|
||||
}
|
||||
} catch {
|
||||
// Missing or corrupt sidecar: start clean; the cloud is the truth.
|
||||
}
|
||||
|
|
@ -240,11 +430,36 @@ export class SkillSync implements SkillSyncGate {
|
|||
}
|
||||
|
||||
private async saveState(state: SyncState): Promise<void> {
|
||||
state.scopes[state.key] = {
|
||||
endpoint: state.scope.endpoint,
|
||||
account: state.scope.account,
|
||||
root: state.scope.root,
|
||||
uploaded: state.uploaded,
|
||||
delivered: state.delivered,
|
||||
removed: state.removed,
|
||||
}
|
||||
const path = this.statePath()
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const temporary = `${path}.tmp-${process.pid}`
|
||||
await writeFile(temporary, JSON.stringify(state, null, 2))
|
||||
await rename(temporary, path)
|
||||
const temporary = `${path}.tmp-${process.pid}-${randomUUID()}`
|
||||
// Top-level uploaded/delivered/removed mirror the active scope: the file
|
||||
// remains readable by older dashboards and verification scripts, while
|
||||
// scopes{} is the authoritative, account-isolated copy.
|
||||
const payload = {
|
||||
version: 2,
|
||||
scope: { ...state.scope, key: state.key },
|
||||
scopes: state.scopes,
|
||||
uploaded: state.uploaded,
|
||||
delivered: state.delivered,
|
||||
removed: state.removed,
|
||||
...(state.legacy === undefined ? {} : { legacy: state.legacy }),
|
||||
}
|
||||
try {
|
||||
await writeFile(temporary, JSON.stringify(payload, null, 2))
|
||||
await rename(temporary, path)
|
||||
} catch (error) {
|
||||
await rm(temporary, { force: true }).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** One full pass; never throws — outcomes land in the stats. */
|
||||
|
|
@ -252,13 +467,34 @@ export class SkillSync implements SkillSyncGate {
|
|||
if (this.running) return this.current
|
||||
const settings = this.deps.settings()
|
||||
if (!settings.enabled || !settings.skillsSyncEnabled) return this.current
|
||||
return this.runExclusive(() => this.syncOnceLocked())
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialized job runner: every mutating entry point (sync pass, single
|
||||
* resolve, batch resolve) queues here, so an in-flight pass and a UI resolve
|
||||
* can never interleave their awaits over the same skill files and state.
|
||||
*/
|
||||
private enqueue<T>(job: () => Promise<T>): Promise<T> {
|
||||
const next = this.queueTail.then(job, job)
|
||||
this.queueTail = next.catch(() => {})
|
||||
return next
|
||||
}
|
||||
|
||||
private async syncOnceLocked(): Promise<SkillSyncStats> {
|
||||
if (this.running) return this.current
|
||||
const run = this.captureRun()
|
||||
const scope = run.scope
|
||||
const client = run.client
|
||||
const repo = run.repo
|
||||
this.runScopeKey = this.scopeKey(scope)
|
||||
this.running = true
|
||||
const stats: SkillSyncStats = {
|
||||
running: true, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0,
|
||||
}
|
||||
this.current = stats
|
||||
try {
|
||||
await this.pass(stats)
|
||||
await this.pass(stats, { scope, client, repo })
|
||||
stats.lastRunAt = new Date().toISOString()
|
||||
} catch (error) {
|
||||
stats.lastError = error instanceof Error ? error.message : String(error)
|
||||
|
|
@ -266,6 +502,8 @@ export class SkillSync implements SkillSyncGate {
|
|||
} finally {
|
||||
stats.running = false
|
||||
this.running = false
|
||||
this.runRepository = undefined
|
||||
this.runScopeKey = undefined
|
||||
this.current = stats
|
||||
}
|
||||
return this.current
|
||||
|
|
@ -274,28 +512,60 @@ export class SkillSync implements SkillSyncGate {
|
|||
/** Record a conflict once per pass, however many rules trip over it. */
|
||||
private conflict(stats: SkillSyncStats, name: string, reason: string): void {
|
||||
if (!stats.conflicts.some((item) => item.name === name && item.reason === reason)) {
|
||||
stats.conflicts.push({ name, reason })
|
||||
stats.conflicts.push({ name, reason, ...(this.runScopeKey === undefined ? {} : { scopeKey: this.runScopeKey }) })
|
||||
}
|
||||
}
|
||||
|
||||
/** One full pass; never throws — outcomes land in the stats. */
|
||||
private async pass(stats: SkillSyncStats): Promise<void> {
|
||||
const repo = this.deps.repository()
|
||||
const client = this.deps.client()
|
||||
private captureRun(): { scope: SkillSyncScope; client: CloudClient; repo: SkillRepository } {
|
||||
const rawScope = this.deps.scope?.() ?? { endpoint: 'default', accountToken: '', root: 'default' }
|
||||
const scope = this.scopeIdentity(rawScope)
|
||||
return { scope, client: this.deps.clientForScope?.(rawScope) ?? this.deps.client(), repo: this.deps.repositoryForScope?.(scope) ?? this.currentRepository() }
|
||||
}
|
||||
|
||||
private currentRepository(): SkillRepository { return this.runRepository ?? this.deps.repository() }
|
||||
|
||||
private async pass(stats: SkillSyncStats, run: { scope: SkillSyncScope; client: CloudClient; repo: SkillRepository }): Promise<void> {
|
||||
this.runRepository = run.repo
|
||||
const repo = run.repo
|
||||
const client = run.client
|
||||
const state = await this.loadState(run.scope)
|
||||
const listing = await client.listSkills()
|
||||
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
|
||||
const items = (listing.data.items ?? []).filter((item) => typeof item.name === 'string' && CLOUD_SKILL_NAME.test(item.name))
|
||||
const cloudByName = new Map(items.map((item) => [item.name as string, item]))
|
||||
const state = await this.loadState()
|
||||
let stateDirty = false
|
||||
|
||||
// Self-heal: an uploaded folder whose delivery receipt reappeared (a
|
||||
// restore, a hand copy) counts as cloud-delivered from now on.
|
||||
for (const name of Object.keys(state.uploaded)) {
|
||||
const local = await repo.read(name)
|
||||
const record = state.uploaded[name]
|
||||
if (record === undefined) continue
|
||||
const local = await repo.read(record.folder)
|
||||
const delivery = local?.delivery
|
||||
if (delivery !== undefined) {
|
||||
this.markDelivered(state, name, delivery.manifest ?? '')
|
||||
this.markDelivered(state, name, delivery.manifest ?? '', record.folder)
|
||||
stateDirty = true
|
||||
}
|
||||
}
|
||||
|
||||
// Local presence is scanned BEFORE DOWN. A cloud-delivered skill the user
|
||||
// deleted must be tombstoned before the cloud listing can resurrect it.
|
||||
// The parking area counts as present (a parked skill is disabled, not
|
||||
// deleted), and a first download has no receipt yet, so it can never be
|
||||
// mistaken for a deletion.
|
||||
const presentFolders = new Set((await repo.list()).map((entry) => entry.name))
|
||||
for (const [name, record] of Object.entries(state.uploaded)) {
|
||||
if (!presentFolders.has(record.folder)) {
|
||||
state.removed[name] = { manifest: cloudByName.get(name)?.manifest_sha256 ?? record.manifest }
|
||||
delete state.uploaded[name]
|
||||
stateDirty = true
|
||||
}
|
||||
}
|
||||
for (const [name, record] of Object.entries(state.delivered)) {
|
||||
if (!presentFolders.has(record.folder ?? name)) {
|
||||
state.removed[name] = { manifest: record.manifest }
|
||||
delete state.delivered[name]
|
||||
stateDirty = true
|
||||
}
|
||||
}
|
||||
|
|
@ -306,18 +576,24 @@ export class SkillSync implements SkillSyncGate {
|
|||
if (item.enabled === false) { stats.skipped += 1; continue }
|
||||
if (state.uploaded[item.name] !== undefined) { stats.skipped += 1; continue }
|
||||
const removed = state.removed[item.name]
|
||||
const local = await repo.read(item.name)
|
||||
const uploaded = state.uploaded[item.name]
|
||||
const localFolder = uploaded?.folder ?? state.delivered[item.name]?.folder ?? item.name
|
||||
const local = await repo.read(localFolder)
|
||||
const exists = local !== undefined
|
||||
const delivery = local?.delivery
|
||||
if (removed !== undefined && exists) {
|
||||
delete state.removed[item.name]
|
||||
stateDirty = true
|
||||
} else if (removed !== undefined && item.manifest_sha256 === removed.manifest) {
|
||||
stats.skipped += 1
|
||||
continue
|
||||
} else if (removed !== undefined) {
|
||||
delete state.removed[item.name]
|
||||
stateDirty = true
|
||||
if (removed !== undefined) {
|
||||
if (exists) {
|
||||
// The user re-created the folder locally: lift the tombstone and let
|
||||
// the normal collision rules decide what happens next.
|
||||
delete state.removed[item.name]
|
||||
stateDirty = true
|
||||
} else {
|
||||
// A tombstone is name-based, not manifest-based: a later cloud
|
||||
// revision must not silently resurrect something the user deleted.
|
||||
// An explicit take_cloud/reinstall clears the marker instead.
|
||||
stats.skipped += 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (exists && delivery !== undefined) {
|
||||
if (!this.deliveredIntact(local, delivery)) {
|
||||
|
|
@ -331,7 +607,7 @@ export class SkillSync implements SkillSyncGate {
|
|||
}
|
||||
if (delivery.manifest === item.manifest_sha256) {
|
||||
if (state.delivered[item.name]?.manifest !== item.manifest_sha256) {
|
||||
this.markDelivered(state, item.name, item.manifest_sha256 ?? '')
|
||||
this.markDelivered(state, item.name, item.manifest_sha256 ?? '', localFolder)
|
||||
stateDirty = true
|
||||
}
|
||||
stats.skipped += 1
|
||||
|
|
@ -363,8 +639,8 @@ export class SkillSync implements SkillSyncGate {
|
|||
this.conflict(stats, item.name, 'script_review_required')
|
||||
continue
|
||||
}
|
||||
await repo.write(item.name, bundle.data)
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256)
|
||||
await repo.write(item.name, bundle.data, { folder: localFolder })
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256, localFolder)
|
||||
stateDirty = true
|
||||
if (exists) stats.updated.push(item.name)
|
||||
else stats.downloaded.push(item.name)
|
||||
|
|
@ -388,6 +664,48 @@ export class SkillSync implements SkillSyncGate {
|
|||
}
|
||||
const record = state.uploaded[skill.name]
|
||||
const cloud = cloudByName.get(skill.name)
|
||||
if (record === undefined && this.foreignUpload(state, entry.name, skill.manifest)) {
|
||||
// Quarantined content from another endpoint/account/root: never upload
|
||||
// it automatically. A user can still explicitly import/edit it later.
|
||||
stats.skipped += 1
|
||||
continue
|
||||
}
|
||||
if (record !== undefined && record.manifest === skill.manifest) {
|
||||
const cloudRevision = cloud?.revision
|
||||
const cloudManifest = cloud?.manifest_sha256
|
||||
const remoteChanged = cloud !== undefined && (
|
||||
(cloudRevision !== undefined && cloudRevision !== record.revision) ||
|
||||
(cloudManifest !== undefined && cloudManifest !== record.manifest)
|
||||
)
|
||||
if (!remoteChanged) {
|
||||
stats.skipped += 1
|
||||
continue
|
||||
}
|
||||
if (cloudManifest === skill.manifest) {
|
||||
// Same bytes, newer cloud revision: re-pin the receipt only.
|
||||
this.markUploaded(state, skill.name, {
|
||||
folder: entry.name,
|
||||
revision: cloudRevision ?? record.revision,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
})
|
||||
stateDirty = true
|
||||
stats.skipped += 1
|
||||
continue
|
||||
}
|
||||
// Local is byte-for-byte what we last uploaded, but the center moved
|
||||
// on: the local copy is stale, so take the cloud revision instead of
|
||||
// re-uploading the old bytes over it. Script changes still wait for
|
||||
// explicit review inside autoTakeCloud.
|
||||
const auto = await this.autoTakeCloud(cloud, local, state, stats, client, entry.name)
|
||||
if (auto !== 'unresolved') {
|
||||
stateDirty = true
|
||||
continue
|
||||
}
|
||||
if (!knownConflicts.has(skill.name)) this.conflict(stats, skill.name, 'cloud_newer')
|
||||
continue
|
||||
}
|
||||
if (cloud !== undefined && record === undefined) {
|
||||
if (knownConflicts.has(skill.name)) continue
|
||||
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
|
||||
|
|
@ -397,6 +715,7 @@ export class SkillSync implements SkillSyncGate {
|
|||
folder: entry.name,
|
||||
revision: cloud.revision ?? 1,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
})
|
||||
stateDirty = true
|
||||
|
|
@ -415,7 +734,6 @@ export class SkillSync implements SkillSyncGate {
|
|||
this.conflict(stats, skill.name, 'name_collision')
|
||||
continue
|
||||
}
|
||||
if (record !== undefined && record.manifest === skill.manifest) { stats.skipped += 1; continue }
|
||||
const files: SkillUploadFile[] = this.toUploadFiles(skill.files)
|
||||
const operationId = `dsh-skill-${randomUUID()}`
|
||||
if (record === undefined || cloud === undefined) {
|
||||
|
|
@ -435,6 +753,7 @@ export class SkillSync implements SkillSyncGate {
|
|||
folder: entry.name,
|
||||
revision: created.data.skill?.revision ?? created.data.revision ?? 1,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
})
|
||||
stateDirty = true
|
||||
|
|
@ -449,6 +768,7 @@ export class SkillSync implements SkillSyncGate {
|
|||
folder: entry.name,
|
||||
revision: cloud.revision,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
})
|
||||
stateDirty = true
|
||||
|
|
@ -484,6 +804,7 @@ export class SkillSync implements SkillSyncGate {
|
|||
folder: entry.name,
|
||||
revision: updated.data.skill?.revision ?? updated.data.revision ?? record.revision + 1,
|
||||
manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
|
||||
syncedAt: new Date().toISOString(),
|
||||
})
|
||||
stateDirty = true
|
||||
|
|
@ -491,25 +812,6 @@ export class SkillSync implements SkillSyncGate {
|
|||
}
|
||||
}
|
||||
|
||||
// Presence counts the parking area too: a parked skill is disabled,
|
||||
// not deleted. Anything missing from both is a deliberate removal
|
||||
// (remembered, so it is not resurrected); the cloud copy stays.
|
||||
const presentFolders = new Set((await repo.list()).map((entry) => entry.name))
|
||||
for (const [name, record] of Object.entries(state.uploaded)) {
|
||||
if (!presentFolders.has(record.folder)) {
|
||||
state.removed[name] = { manifest: cloudByName.get(name)?.manifest_sha256 ?? record.manifest }
|
||||
delete state.uploaded[name]
|
||||
stateDirty = true
|
||||
}
|
||||
}
|
||||
for (const [name, record] of Object.entries(state.delivered)) {
|
||||
if (!presentFolders.has(name)) {
|
||||
state.removed[name] = { manifest: record.manifest }
|
||||
delete state.delivered[name]
|
||||
stateDirty = true
|
||||
}
|
||||
}
|
||||
|
||||
if (stateDirty) await this.saveState(state)
|
||||
const changed = stats.downloaded.length + stats.uploaded.length + stats.updated.length
|
||||
if (changed > 0 || stats.conflicts.length > 0) {
|
||||
|
|
@ -577,13 +879,13 @@ export class SkillSync implements SkillSyncGate {
|
|||
* receipt without a transfer, so the next pass treats the folder as
|
||||
* cloud-origin and nobody is asked to pick between two identical copies.
|
||||
*/
|
||||
private async adoptIdenticalDelivery(item: SkillSummary, local: SkillLocalBundle): Promise<void> {
|
||||
await this.deps.repository().write(item.name, {
|
||||
private async adoptIdenticalDelivery(item: SkillSummary, local: SkillLocalBundle, folder?: string): Promise<void> {
|
||||
await this.currentRepository().write(item.name, {
|
||||
name: item.name,
|
||||
revision: item.revision ?? 1,
|
||||
manifest_sha256: item.manifest_sha256 ?? this.localManifest(local.files),
|
||||
files: local.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
})
|
||||
}, { folder })
|
||||
}
|
||||
|
||||
/** Fetch, verify and install the cloud copy, backing the local one up first. */
|
||||
|
|
@ -593,6 +895,7 @@ export class SkillSync implements SkillSyncGate {
|
|||
state: SyncState,
|
||||
stats: SkillSyncStats,
|
||||
client: CloudClient,
|
||||
folder?: string,
|
||||
): Promise<AutoResolution> {
|
||||
if (item.script_changed === true) {
|
||||
this.conflict(stats, item.name, 'script_review_required')
|
||||
|
|
@ -611,9 +914,11 @@ export class SkillSync implements SkillSyncGate {
|
|||
this.conflict(stats, item.name, 'script_review_required')
|
||||
return 'conflict'
|
||||
}
|
||||
if (local !== undefined) await this.deps.repository().snapshot(item.name)
|
||||
await this.deps.repository().write(item.name, bundle.data)
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256)
|
||||
const uploaded = state.uploaded[item.name]
|
||||
const localFolder = folder ?? uploaded?.folder ?? local?.name ?? item.name
|
||||
if (local !== undefined) await this.currentRepository().snapshot(localFolder)
|
||||
await this.currentRepository().write(item.name, bundle.data, { folder: localFolder, cleanupFiles: uploaded?.files?.map((file) => file.path) })
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256, localFolder)
|
||||
delete state.removed[item.name]
|
||||
stats.updated.push(item.name)
|
||||
return 'resolved'
|
||||
|
|
@ -640,13 +945,14 @@ export class SkillSync implements SkillSyncGate {
|
|||
return 'conflict'
|
||||
}
|
||||
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1
|
||||
await this.deps.repository().write(skill.name, {
|
||||
await this.currentRepository().write(skill.name, {
|
||||
name: skill.name,
|
||||
revision,
|
||||
manifest_sha256: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
}, { delivery: false })
|
||||
this.markUploaded(state, skill.name, { folder, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() })
|
||||
this.markUploaded(state, skill.name, { folder, revision, manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() })
|
||||
delete state.removed[skill.name]
|
||||
stats.updated.push(skill.name)
|
||||
return 'resolved'
|
||||
|
|
@ -662,8 +968,8 @@ export class SkillSync implements SkillSyncGate {
|
|||
): Promise<AutoResolution> {
|
||||
if (!local.files.some((file) => file.path === 'SKILL.md')) return 'unresolved'
|
||||
if (item.manifest_sha256 !== undefined && this.localManifest(local.files) === item.manifest_sha256) {
|
||||
await this.adoptIdenticalDelivery(item, local)
|
||||
this.markDelivered(state, item.name, item.manifest_sha256)
|
||||
await this.adoptIdenticalDelivery(item, local, local.name)
|
||||
this.markDelivered(state, item.name, item.manifest_sha256, local.name)
|
||||
stats.skipped += 1
|
||||
return 'resolved'
|
||||
}
|
||||
|
|
@ -679,8 +985,8 @@ export class SkillSync implements SkillSyncGate {
|
|||
client: CloudClient,
|
||||
): Promise<AutoResolution> {
|
||||
if (item.manifest_sha256 !== undefined && local.files.length > 0 && this.localManifest(local.files) === item.manifest_sha256) {
|
||||
await this.adoptIdenticalDelivery(item, local)
|
||||
this.markDelivered(state, item.name, item.manifest_sha256)
|
||||
await this.adoptIdenticalDelivery(item, local, local.name)
|
||||
this.markDelivered(state, item.name, item.manifest_sha256, local.name)
|
||||
stats.skipped += 1
|
||||
return 'resolved'
|
||||
}
|
||||
|
|
@ -698,7 +1004,7 @@ export class SkillSync implements SkillSyncGate {
|
|||
const cloudAt = this.cloudUpdatedAt(item)
|
||||
const localAt = newestMtime(local.files)
|
||||
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt) return 'unresolved'
|
||||
if (cloudAt > localAt) return this.autoTakeCloud(item, local, state, stats, client)
|
||||
if (cloudAt > localAt) return this.autoTakeCloud(item, local, state, stats, client, local.name)
|
||||
const skill = await this.readLocalSkill(local, item.name)
|
||||
if (skill === undefined) return 'unresolved'
|
||||
if (typeof skill === 'string') {
|
||||
|
|
@ -717,16 +1023,26 @@ export class SkillSync implements SkillSyncGate {
|
|||
* `take_cloud`). Partial failures are collected instead of aborting the
|
||||
* whole batch, so the UI can show "N done, M failed" in one shot.
|
||||
*/
|
||||
async resolveConflicts(actionInput: unknown): Promise<SyncResolveBatchResult> {
|
||||
async resolveConflicts(actionInput: unknown, conflictIdsInput?: unknown): Promise<SyncResolveBatchResult> {
|
||||
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : ''
|
||||
if (action === '') throw new Error('invalid_action')
|
||||
return this.runExclusive(() => this.resolveConflictsLocked(action, conflictIdsInput))
|
||||
}
|
||||
|
||||
private async resolveConflictsLocked(action: 'keep_local' | 'take_cloud', conflictIdsInput?: unknown): Promise<SyncResolveBatchResult> {
|
||||
if (this.running) throw new Error('sync_running')
|
||||
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))]
|
||||
const run = this.captureRun()
|
||||
const scopeKey = this.scopeKey(run.scope)
|
||||
const details = await this.conflictDetails(run)
|
||||
const requested = Array.isArray(conflictIdsInput) ? new Set(conflictIdsInput.filter((value): value is string => typeof value === 'string')) : undefined
|
||||
const selected = details.filter((detail) => (detail.scopeKey === scopeKey || detail.scopeKey === '') && (requested === undefined || requested.has(detail.conflictId)))
|
||||
const names = [...new Set(selected.map((detail) => detail.name))]
|
||||
const idByName = new Map(selected.map((detail) => [detail.name, detail.conflictId]))
|
||||
const resolved: string[] = []
|
||||
const failed: { name: string; error: string }[] = []
|
||||
for (const name of names) {
|
||||
try {
|
||||
await this.resolveConflict(name, action)
|
||||
await this.resolveConflictLocked(name, action, run, idByName.get(name))
|
||||
resolved.push(name)
|
||||
} catch (error) {
|
||||
failed.push({ name, error: error instanceof Error ? error.message : String(error) })
|
||||
|
|
@ -735,13 +1051,15 @@ export class SkillSync implements SkillSyncGate {
|
|||
return { action, resolved, failed }
|
||||
}
|
||||
|
||||
async conflictDetails(): Promise<SyncConflictDetail[]> {
|
||||
async conflictDetails(run?: { scope: SkillSyncScope; client: CloudClient; repo: SkillRepository }): Promise<SyncConflictDetail[]> {
|
||||
const conflicts = this.current.conflicts
|
||||
if (conflicts.length === 0) return []
|
||||
const repo = this.deps.repository()
|
||||
const active = run ?? this.captureRun()
|
||||
const repo = active.repo
|
||||
const state = await this.loadState(active.scope)
|
||||
let cloudItems: SkillSummary[] = []
|
||||
try {
|
||||
const listing = await this.deps.client().listSkills()
|
||||
const listing = await active.client.listSkills()
|
||||
if (listing.ok) cloudItems = listing.data.items ?? []
|
||||
} catch {
|
||||
// Offline: report local sides only, never throw the list away.
|
||||
|
|
@ -749,7 +1067,8 @@ export class SkillSync implements SkillSyncGate {
|
|||
const byName = new Map(cloudItems.map((item) => [item.name, item]))
|
||||
const out: SyncConflictDetail[] = []
|
||||
for (const conflict of conflicts) {
|
||||
const local = await repo.read(conflict.name)
|
||||
const localFolder = state.uploaded[conflict.name]?.folder ?? state.delivered[conflict.name]?.folder ?? conflict.name
|
||||
const local = await repo.read(localFolder)
|
||||
const location: 'root' | 'holding' | 'none' = local?.area ?? 'none'
|
||||
const files = local?.files.length ?? 0
|
||||
const bytes = (local?.files ?? []).reduce((sum, file) => sum + file.size, 0)
|
||||
|
|
@ -758,7 +1077,15 @@ export class SkillSync implements SkillSyncGate {
|
|||
modified = local.delivery === undefined ? true : !this.deliveredIntact(local, local.delivery)
|
||||
}
|
||||
const cloudItem = byName.get(conflict.name)
|
||||
const localVersion = local === undefined ? 'none' : sha256Hex(local.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'))
|
||||
const cloudVersion = cloudItem === undefined ? 'none' : String(cloudItem.revision ?? '') + ':' + String(cloudItem.manifest_sha256 ?? '')
|
||||
const scopeKey = conflict.scopeKey ?? this.scopeKey(active.scope)
|
||||
const conflictId = sha256Hex([scopeKey, conflict.name, conflict.reason, localVersion, cloudVersion].join('|'))
|
||||
out.push({
|
||||
conflictId,
|
||||
scopeKey,
|
||||
localVersion,
|
||||
cloudVersion,
|
||||
name: conflict.name,
|
||||
reason: conflict.reason,
|
||||
local: { exists: location !== 'none', location, files, bytes, modified },
|
||||
|
|
@ -779,18 +1106,37 @@ export class SkillSync implements SkillSyncGate {
|
|||
return out
|
||||
}
|
||||
|
||||
async resolveConflict(nameInput: unknown, actionInput: unknown): Promise<SyncResolveResult> {
|
||||
async resolveConflict(nameInput: unknown, actionInput: unknown, conflictIdInput?: unknown): Promise<SyncResolveResult> {
|
||||
const name = typeof nameInput === 'string' ? nameInput : ''
|
||||
if (name === '' || !CLOUD_SKILL_NAME.test(name)) throw new Error('invalid_name')
|
||||
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' || actionInput === 'manual' ? actionInput : ''
|
||||
if (action === '') throw new Error('invalid_action')
|
||||
return this.runExclusive(() => { const run = this.captureRun(); return this.resolveConflictLocked(name, action, run, typeof conflictIdInput === 'string' ? conflictIdInput : undefined) })
|
||||
}
|
||||
|
||||
private async resolveConflictLocked(name: string, action: 'keep_local' | 'take_cloud' | 'manual', run?: { scope: SkillSyncScope; client: CloudClient; repo: SkillRepository }, expectedConflictId?: string): Promise<SyncResolveResult> {
|
||||
if (this.running) throw new Error('sync_running')
|
||||
const repo = this.deps.repository()
|
||||
const client = this.deps.client()
|
||||
const active = run ?? this.captureRun()
|
||||
const scope = active.scope
|
||||
const repo = active.repo
|
||||
const client = active.client
|
||||
this.runRepository = repo
|
||||
try {
|
||||
const conflict = this.current.conflicts.find((item) => item.name === name)
|
||||
if (conflict?.scopeKey !== undefined && conflict.scopeKey !== this.scopeKey(scope)) throw new Error('stale_conflict')
|
||||
if (expectedConflictId === undefined) throw new Error('confirmation_required')
|
||||
const details = await this.conflictDetails(active)
|
||||
const confirmed = details.find((detail) => detail.name === name)
|
||||
if (confirmed === undefined || confirmed.conflictId !== expectedConflictId) throw new Error('stale_conflict')
|
||||
const listing = await client.listSkills()
|
||||
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
|
||||
const cloud = (listing.data.items ?? []).find((item) => item.name === name)
|
||||
const state = await this.loadState()
|
||||
const state = await this.loadState(scope)
|
||||
const localFolder = state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name
|
||||
const localNow = await repo.read(localFolder)
|
||||
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'))
|
||||
if (localVersionNow !== confirmed.localVersion) throw new Error('stale_conflict')
|
||||
if ((cloud?.revision ?? undefined) !== (confirmed.cloud?.revision ?? undefined) || (cloud?.manifest_sha256 ?? undefined) !== (confirmed.cloud?.manifest ?? undefined)) throw new Error('stale_conflict')
|
||||
|
||||
if (action === 'manual') {
|
||||
return {
|
||||
|
|
@ -803,14 +1149,14 @@ export class SkillSync implements SkillSyncGate {
|
|||
}
|
||||
|
||||
if (action === 'keep_local') {
|
||||
const local = await repo.read(name)
|
||||
const local = localNow
|
||||
if (local === undefined) throw new Error('no_local_copy')
|
||||
const skill = await this.readLocalSkill(local, name)
|
||||
const skill = await this.readLocalSkill(local, localFolder)
|
||||
if (skill === undefined) throw new Error('not_a_skill')
|
||||
if (typeof skill === 'string') throw new Error(skill)
|
||||
const files = this.toUploadFiles(skill.files)
|
||||
const operationId = `dsh-skill-${randomUUID()}`
|
||||
if (cloud === undefined) {
|
||||
if (confirmed.cloud === null) {
|
||||
const created = await client.createSkill({
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
|
|
@ -827,7 +1173,8 @@ export class SkillSync implements SkillSyncGate {
|
|||
manifest_sha256: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
}, { delivery: false })
|
||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() })
|
||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() })
|
||||
delete state.removed[name]
|
||||
await this.saveState(state)
|
||||
this.dropConflict(name)
|
||||
|
|
@ -836,37 +1183,39 @@ export class SkillSync implements SkillSyncGate {
|
|||
const updated = await client.updateSkill(skill.name, {
|
||||
description: skill.description,
|
||||
files,
|
||||
expected_revision: cloud.revision ?? 0,
|
||||
expected_revision: confirmed.cloud?.revision ?? 0,
|
||||
operation_id: operationId,
|
||||
})
|
||||
if (!updated.ok) {
|
||||
if (updated.error.code === 'revision_conflict') throw new Error('stale_revision')
|
||||
throw new Error(`upload_failed: ${describeError(updated.error)}`)
|
||||
}
|
||||
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1
|
||||
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (confirmed.cloud?.revision ?? 0) + 1
|
||||
await repo.write(name, {
|
||||
name: skill.name,
|
||||
revision,
|
||||
manifest_sha256: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||
}, { delivery: false })
|
||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() })
|
||||
}, { delivery: false, folder: localFolder })
|
||||
this.markUploaded(state, name, { folder: localFolder, revision, manifest: skill.manifest,
|
||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() })
|
||||
delete state.removed[name]
|
||||
await this.saveState(state)
|
||||
this.dropConflict(name)
|
||||
return { name, action, applied: true, revision, note: '已用本地版本覆盖云端(revision 已更新)。' }
|
||||
}
|
||||
|
||||
if (cloud === undefined) throw new Error('no_cloud_copy')
|
||||
if (confirmed.cloud === null) throw new Error('no_cloud_copy')
|
||||
const bundle = await client.skillBundle(name)
|
||||
if (!bundle.ok) throw new Error(`bundle_failed: ${describeError(bundle.error)}`)
|
||||
if (bundle.data.name !== name || bundle.data.revision !== confirmed.cloud.revision || bundle.data.manifest_sha256 !== confirmed.cloud.manifest) throw new Error('stale_conflict')
|
||||
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
|
||||
throw new Error('manifest_mismatch')
|
||||
}
|
||||
const local = await repo.read(name)
|
||||
const backup = local !== undefined ? (await repo.snapshot(name)) ?? '' : ''
|
||||
await repo.write(name, bundle.data)
|
||||
this.markDelivered(state, name, bundle.data.manifest_sha256)
|
||||
const local = localNow
|
||||
const backup = local !== undefined ? (await repo.snapshot(localFolder)) ?? '' : ''
|
||||
await repo.write(name, bundle.data, { folder: localFolder })
|
||||
this.markDelivered(state, name, bundle.data.manifest_sha256, localFolder)
|
||||
delete state.removed[name]
|
||||
await this.saveState(state)
|
||||
this.dropConflict(name)
|
||||
|
|
@ -878,11 +1227,17 @@ export class SkillSync implements SkillSyncGate {
|
|||
...(backup === '' ? {} : { backup }),
|
||||
note: '已采用云端版本覆盖本地(本地已备份)。',
|
||||
}
|
||||
} finally { this.runRepository = undefined }
|
||||
}
|
||||
}
|
||||
|
||||
/** One conflict with both sides, for the resolve UI. */
|
||||
export interface SyncConflictDetail {
|
||||
/** Stable token over scope + local + cloud preview versions. */
|
||||
conflictId: string
|
||||
scopeKey: string
|
||||
localVersion: string
|
||||
cloudVersion: string
|
||||
name: string
|
||||
reason: string
|
||||
local: { exists: boolean; location: 'root' | 'holding' | 'none'; files: number; bytes: number; modified: boolean }
|
||||
|
|
|
|||
|
|
@ -152,7 +152,16 @@ export class SkillUpdater {
|
|||
}
|
||||
|
||||
private guard(): void {
|
||||
if (this.deps.gate().isRunning()) throw new SkillAdminError('sync_running', '技能同步正在进行,请稍候再试。')
|
||||
const gate = this.deps.gate()
|
||||
const busy = gate.busy === undefined ? gate.isRunning() : gate.busy()
|
||||
if (busy) throw new SkillAdminError('sync_running', '技能同步正在进行,请稍候再试。')
|
||||
}
|
||||
|
||||
/** Run the whole update/rollback transaction behind the shared write lock. */
|
||||
private async exclusive<T>(job: () => Promise<T>): Promise<T> {
|
||||
this.guard()
|
||||
const gate = this.deps.gate()
|
||||
return gate.runExclusive === undefined ? job() : gate.runExclusive(job)
|
||||
}
|
||||
|
||||
private async find(folder: string): Promise<{ dir: string; source: SkillSourceRecord }> {
|
||||
|
|
@ -232,7 +241,7 @@ export class SkillUpdater {
|
|||
|
||||
/** Back up the current folder, then replace it with the source's latest. */
|
||||
async applyUpdate(folderInput: unknown, expectedCommit?: unknown): Promise<UpdateResult> {
|
||||
this.guard()
|
||||
return this.exclusive(async () => {
|
||||
const folder = typeof folderInput === 'string' ? folderInput : ''
|
||||
if (folder === '') throw new SkillAdminError('invalid_name', '缺少技能目录名。')
|
||||
const { dir, source } = await this.find(folder)
|
||||
|
|
@ -242,11 +251,12 @@ export class SkillUpdater {
|
|||
throw new SkillAdminError('stale_plan', '来源在上次检查后已更新,请重新检查差异再更新。')
|
||||
}
|
||||
return this.replaceWith(dir, source, { commit: check.remoteCommit ?? source.commit, ref: source.ref })
|
||||
})
|
||||
}
|
||||
|
||||
/** Restore the most recent pre-update backup. */
|
||||
async rollback(folderInput: unknown): Promise<UpdateResult> {
|
||||
this.guard()
|
||||
return this.exclusive(async () => {
|
||||
const folder = typeof folderInput === 'string' ? folderInput : ''
|
||||
if (folder === '') throw new SkillAdminError('invalid_name', '缺少技能目录名。')
|
||||
const { dir, source } = await this.find(folder)
|
||||
|
|
@ -261,6 +271,7 @@ export class SkillUpdater {
|
|||
const restored = await readSkillSourceRecord(backupDir)
|
||||
// Restore in place: move the current aside, copy the backup over, then drop
|
||||
// the aside copy only after the backup has landed.
|
||||
const beforeFiles = await hashTree(dir)
|
||||
const aside = `${dir}.rollbacking-${Date.now().toString(36)}`
|
||||
await mkdir(join(dir, '..'), { recursive: true })
|
||||
await rename(dir, aside)
|
||||
|
|
@ -273,11 +284,10 @@ export class SkillUpdater {
|
|||
}
|
||||
await rm(aside, { recursive: true, force: true }).catch(() => {})
|
||||
this.deps.log(`skill rolled back: ${folder} <- ${latest}`)
|
||||
const beforeFiles = await hashTree(backupDir)
|
||||
beforeFiles.delete('.skill-source.json')
|
||||
const nowFiles = await hashTree(dir)
|
||||
nowFiles.delete('.skill-source.json')
|
||||
const diff = diffTrees(nowFiles, beforeFiles)
|
||||
const diff = diffTrees(beforeFiles, nowFiles)
|
||||
return {
|
||||
folder,
|
||||
from: source.commit,
|
||||
|
|
@ -285,6 +295,7 @@ export class SkillUpdater {
|
|||
backup: backupDir,
|
||||
...diff,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** Shared write path: backup, copy new tree, rewrite provenance. */
|
||||
|
|
|
|||
|
|
@ -24,6 +24,16 @@ export interface SkillProvenance {
|
|||
export interface SkillSyncGate {
|
||||
isRunning(): boolean
|
||||
provenance(name: string): Promise<SkillProvenance | null>
|
||||
/**
|
||||
* Optional shared write lock. Sync, resolve, admin writes, update and
|
||||
* rollback all enter through this one queue so a long async transaction
|
||||
* (a sync pass, a clone/apply, a folder move) can never interleave with
|
||||
* another writer. Older gates that do not implement it fall back to the
|
||||
* isRunning() entry guard.
|
||||
*/
|
||||
runExclusive?<T>(job: () => Promise<T>): Promise<T>
|
||||
/** Optional richer busy signal: true while any write transaction is queued or running. */
|
||||
busy?(): boolean
|
||||
}
|
||||
|
||||
/** One managed folder — including folders that are not valid skills yet,
|
||||
|
|
@ -51,6 +61,10 @@ export interface SkillRepositoryDelivery {
|
|||
manifest?: string
|
||||
files?: { path: string; sha256: string }[]
|
||||
syncedAt?: string
|
||||
/** Endpoint/account/local-root binding, when the writer recorded one. */
|
||||
endpoint?: string
|
||||
account?: string
|
||||
root?: string
|
||||
}
|
||||
|
||||
/** A local skill folder as the sync engine sees it. */
|
||||
|
|
@ -64,6 +78,10 @@ export interface SkillLocalBundle {
|
|||
export interface SkillRepositoryWriteOptions {
|
||||
/** Write the cloud delivery receipt (default true); false clears it. */
|
||||
delivery?: boolean
|
||||
/** Actual local folder name when it differs from the logical skill name. */
|
||||
folder?: string
|
||||
/** Paths owned by the last upload and safe to remove when the cloud no longer has them. */
|
||||
cleanupFiles?: string[]
|
||||
}
|
||||
|
||||
export interface SkillRepository {
|
||||
|
|
|
|||
|
|
@ -3,12 +3,13 @@
|
|||
// moves live here, so the sync engine never builds a skill path itself.
|
||||
|
||||
import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { dirname, join, resolve, sep } from 'node:path'
|
||||
import { dshHome } from '../store.ts'
|
||||
import type { SkillAdmin } from '../skill-admin.ts'
|
||||
import { checkFolder, type SkillAdmin } from '../skill-admin.ts'
|
||||
import type { SkillBundle } from '../api.ts'
|
||||
import type { SkillLocalBundle, SkillRepository, SkillRepositoryDelivery, SkillRepositoryEntry } from './contracts.ts'
|
||||
import { sha256Hex } from './shared.ts'
|
||||
import { isCloudSkillPath, sha256Hex } from './shared.ts'
|
||||
|
||||
export interface AdminSkillRepositoryDeps {
|
||||
/** Folder moves and locate() come from the admin; it already owns park/unpark. */
|
||||
|
|
@ -17,6 +18,12 @@ export interface AdminSkillRepositoryDeps {
|
|||
holdingDir: () => string
|
||||
}
|
||||
|
||||
function inside(root: string, target: string): boolean {
|
||||
const normalizedRoot = resolve(root)
|
||||
const normalizedTarget = resolve(target)
|
||||
return normalizedTarget === normalizedRoot || normalizedTarget.startsWith(normalizedRoot + sep)
|
||||
}
|
||||
|
||||
const RECEIPT = '.manifest.json'
|
||||
|
||||
async function isDirectory(path: string): Promise<boolean> {
|
||||
|
|
@ -97,8 +104,17 @@ export class AdminSkillRepository implements SkillRepository {
|
|||
return entries
|
||||
}
|
||||
|
||||
private async locate(name: string): Promise<{ area: 'root' | 'holding'; dir: string } | undefined> {
|
||||
const folder = checkFolder(name)
|
||||
const rootDir = join(this.deps.skillsRoot(), folder)
|
||||
if (await isDirectory(rootDir)) return { area: 'root', dir: rootDir }
|
||||
const parkedDir = join(this.deps.holdingDir(), folder)
|
||||
if (await isDirectory(parkedDir)) return { area: 'holding', dir: parkedDir }
|
||||
return undefined
|
||||
}
|
||||
|
||||
async read(name: string): Promise<SkillLocalBundle | undefined> {
|
||||
const found = await this.deps.admin.locate(name)
|
||||
const found = await this.locate(name)
|
||||
if (found === undefined) return undefined
|
||||
const area = found.area
|
||||
const files = (await walkSkillFiles(found.dir)).map((file) => ({
|
||||
|
|
@ -111,29 +127,48 @@ export class AdminSkillRepository implements SkillRepository {
|
|||
return { name, area, files, delivery: await readDeliveryReceipt(found.dir) }
|
||||
}
|
||||
|
||||
async write(name: string, bundle: SkillBundle, options?: { delivery?: boolean }): Promise<void> {
|
||||
const found = await this.deps.admin.locate(name)
|
||||
async write(name: string, bundle: SkillBundle, options?: { delivery?: boolean; folder?: string; cleanupFiles?: string[] }): Promise<void> {
|
||||
// The folder name decides where the whole bundle lands, and the file paths
|
||||
// decide where each write goes — both are attacker-reachable through a
|
||||
// hostile cloud payload, so both are checked before ANY byte is written.
|
||||
checkFolder(name)
|
||||
const decoded: { file: { path: string; sha256: string; data: string }; bytes: Buffer }[] = []
|
||||
for (const file of bundle.files) {
|
||||
if (typeof file.path !== 'string' || !isCloudSkillPath(file.path)) {
|
||||
throw new Error(`refusing to write skill ${name}: invalid file path ${JSON.stringify(file.path)}`)
|
||||
}
|
||||
const bytes = Buffer.from(file.data, 'base64')
|
||||
if (sha256Hex(bytes) !== file.sha256) throw new Error('checksum mismatch for ' + file.path)
|
||||
decoded.push({ file, bytes })
|
||||
}
|
||||
const folder = options?.folder !== undefined && options.folder !== '' ? checkFolder(options.folder) : name
|
||||
const found = await this.locate(folder)
|
||||
// New skills land in root; a parked folder is written in place.
|
||||
const dir = found?.dir ?? join(this.deps.skillsRoot(), name)
|
||||
const dir = found?.dir ?? join(this.deps.skillsRoot(), folder)
|
||||
const previous = await readDeliveryReceipt(dir)
|
||||
const cleanup = new Set<string>([...(previous?.files ?? []).map((file) => file.path), ...(options?.cleanupFiles ?? [])])
|
||||
await mkdir(dir, { recursive: true })
|
||||
const keep = new Set(bundle.files.map((file) => file.path))
|
||||
const written: { path: string; sha256: string; size: number }[] = []
|
||||
let n = 0
|
||||
for (const file of bundle.files) {
|
||||
const bytes = Buffer.from(file.data, 'base64')
|
||||
if (sha256Hex(bytes) !== file.sha256) throw new Error('checksum mismatch for ' + file.path)
|
||||
for (const { file, bytes } of decoded) {
|
||||
const target = join(dir, ...file.path.split('/'))
|
||||
if (!inside(dir, target)) throw new Error('skill_path_outside_root: ' + file.path)
|
||||
await mkdir(dirname(target), { recursive: true })
|
||||
const tmp = target + '.tmp-' + String(n++)
|
||||
// Unique temp name: concurrent writers to the same skill must never
|
||||
// share a predictable temp file, or one rename can commit the other's bytes.
|
||||
const tmp = `${target}.tmp-${randomUUID()}`
|
||||
await writeFile(tmp, bytes)
|
||||
await rename(tmp, target)
|
||||
written.push({ path: file.path, sha256: file.sha256, size: bytes.length })
|
||||
}
|
||||
// Remove files the previous delivery owned but the new bundle does not.
|
||||
if (previous?.files !== undefined) {
|
||||
for (const file of previous.files) {
|
||||
if (!keep.has(file.path)) await rm(join(dir, ...file.path.split('/')), { force: true })
|
||||
// Receipts are ours, but a tampered one must not delete outside the folder.
|
||||
for (const path of cleanup) {
|
||||
if (typeof path !== 'string' || keep.has(path)) continue
|
||||
if (isCloudSkillPath(path)) {
|
||||
const target = join(dir, ...path.split('/'))
|
||||
if (!inside(dir, target)) throw new Error('skill_path_outside_root: ' + path)
|
||||
await rm(target, { force: true })
|
||||
}
|
||||
}
|
||||
const receipt = join(dir, RECEIPT)
|
||||
|
|
@ -142,7 +177,7 @@ export class AdminSkillRepository implements SkillRepository {
|
|||
return
|
||||
}
|
||||
const payload = { name, revision: bundle.revision, manifest_sha256: bundle.manifest_sha256, files: written, synced_at: new Date().toISOString() }
|
||||
const tmp = receipt + '.tmp'
|
||||
const tmp = `${receipt}.tmp-${randomUUID()}`
|
||||
await writeFile(tmp, JSON.stringify(payload, null, 2) + '\n')
|
||||
await rename(tmp, receipt)
|
||||
}
|
||||
|
|
@ -156,7 +191,7 @@ export class AdminSkillRepository implements SkillRepository {
|
|||
}
|
||||
|
||||
async snapshot(name: string): Promise<string | undefined> {
|
||||
const found = await this.deps.admin.locate(name)
|
||||
const found = await this.locate(name)
|
||||
if (found === undefined) return undefined
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
||||
const target = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp)
|
||||
|
|
|
|||
109
src/store.ts
109
src/store.ts
|
|
@ -33,12 +33,22 @@ export interface PersistedState {
|
|||
summaryToken?: string
|
||||
skillsSyncEnabled?: boolean
|
||||
skillsDir?: string
|
||||
localMemoryEnabled?: boolean
|
||||
cloudMemoryEnabled?: boolean
|
||||
autoMemorySpaces?: boolean
|
||||
autoSummaryEnabled?: boolean
|
||||
autoProfileEnabled?: boolean
|
||||
localMemoryK?: number
|
||||
/** Token labels the user cleared — set so an env fallback cannot resurrect them. */
|
||||
clearedTokens?: string[]
|
||||
}
|
||||
|
||||
/** Masked token view handed to the browser. */
|
||||
export interface TokenView {
|
||||
configured: boolean
|
||||
masked: string
|
||||
/** Where the live token comes from: sidecar file, bound env var, or nothing. */
|
||||
source: 'sidecar' | 'env' | 'none'
|
||||
}
|
||||
|
||||
/** Browser-facing settings snapshot (no secrets). */
|
||||
|
|
@ -99,6 +109,20 @@ export function maskToken(token: string): string {
|
|||
return `${token.slice(0, 7)}…${token.slice(-4)}`
|
||||
}
|
||||
|
||||
/** Record that one token label was cleared (blocks the env fallback). */
|
||||
function markCleared(state: PersistedState, label: 'activity' | 'memory' | 'summary'): void {
|
||||
const labels = new Set(state.clearedTokens ?? [])
|
||||
labels.add(label)
|
||||
state.clearedTokens = [...labels]
|
||||
}
|
||||
|
||||
/** Drop the cleared marker for one label (a fresh token was written). */
|
||||
function unsetCleared(state: PersistedState, label: 'activity' | 'memory' | 'summary'): void {
|
||||
if (state.clearedTokens === undefined) return
|
||||
const remaining = state.clearedTokens.filter((item) => item !== label)
|
||||
state.clearedTokens = remaining.length > 0 ? remaining : undefined
|
||||
}
|
||||
|
||||
/** Validate one sidecar field; returns the normalized value or undefined. */
|
||||
function cleanString(value: unknown): string | undefined {
|
||||
if (typeof value !== 'string') return undefined
|
||||
|
|
@ -121,8 +145,19 @@ function parseState(raw: string): PersistedState {
|
|||
const source = value as Record<string, unknown>
|
||||
const state: PersistedState = { version: 1 }
|
||||
if (typeof source.enabled === 'boolean') state.enabled = source.enabled
|
||||
// The split gates persist too: a saved `false` must survive a reload
|
||||
// instead of silently falling back to the inherited `enabled`.
|
||||
if (typeof source.activityEnabled === 'boolean') state.activityEnabled = source.activityEnabled
|
||||
if (typeof source.memoryEnabled === 'boolean') state.memoryEnabled = source.memoryEnabled
|
||||
if (typeof source.skillsSyncEnabled === 'boolean') state.skillsSyncEnabled = source.skillsSyncEnabled
|
||||
if (typeof source.skillsDir === 'string') state.skillsDir = source.skillsDir
|
||||
if (typeof source.localMemoryEnabled === 'boolean') state.localMemoryEnabled = source.localMemoryEnabled
|
||||
if (typeof source.cloudMemoryEnabled === 'boolean') state.cloudMemoryEnabled = source.cloudMemoryEnabled
|
||||
if (typeof source.autoMemorySpaces === 'boolean') state.autoMemorySpaces = source.autoMemorySpaces
|
||||
if (typeof source.autoSummaryEnabled === 'boolean') state.autoSummaryEnabled = source.autoSummaryEnabled
|
||||
if (typeof source.autoProfileEnabled === 'boolean') state.autoProfileEnabled = source.autoProfileEnabled
|
||||
const localMemoryK = clampInt(source.localMemoryK, 1, 100)
|
||||
if (localMemoryK !== undefined) state.localMemoryK = localMemoryK
|
||||
const baseUrl = normalizeBaseUrl(source.baseUrl)
|
||||
if (baseUrl !== undefined) state.baseUrl = baseUrl
|
||||
const clientId = cleanString(source.clientId)
|
||||
|
|
@ -140,6 +175,11 @@ function parseState(raw: string): PersistedState {
|
|||
if (summaryMaxChars !== undefined) state.summaryMaxChars = summaryMaxChars
|
||||
const summaryToken = cleanString(source.summaryToken)
|
||||
if (summaryToken !== undefined) state.summaryToken = summaryToken
|
||||
if (Array.isArray(source.clearedTokens)) {
|
||||
const labels = source.clearedTokens.filter((label): label is string =>
|
||||
label === 'activity' || label === 'memory' || label === 'summary')
|
||||
if (labels.length > 0) state.clearedTokens = labels
|
||||
}
|
||||
return state
|
||||
} catch {
|
||||
return { version: 1 }
|
||||
|
|
@ -209,6 +249,12 @@ export class SettingsStore {
|
|||
if (this.state.summaryMaxChars !== undefined) resolved.summaryMaxChars = this.state.summaryMaxChars
|
||||
if (this.state.skillsSyncEnabled !== undefined) resolved.skillsSyncEnabled = this.state.skillsSyncEnabled
|
||||
if (this.state.skillsDir !== undefined) resolved.skillsDir = this.state.skillsDir
|
||||
if (this.state.localMemoryEnabled !== undefined) resolved.localMemoryEnabled = this.state.localMemoryEnabled
|
||||
if (this.state.cloudMemoryEnabled !== undefined) resolved.cloudMemoryEnabled = this.state.cloudMemoryEnabled
|
||||
if (this.state.autoMemorySpaces !== undefined) resolved.autoMemorySpaces = this.state.autoMemorySpaces
|
||||
if (this.state.autoSummaryEnabled !== undefined) resolved.autoSummaryEnabled = this.state.autoSummaryEnabled
|
||||
if (this.state.autoProfileEnabled !== undefined) resolved.autoProfileEnabled = this.state.autoProfileEnabled
|
||||
if (this.state.localMemoryK !== undefined) resolved.localMemoryK = this.state.localMemoryK
|
||||
// The split gates inherit `enabled` unless the config or the sidecar set
|
||||
// them explicitly, so an old configuration keeps its exact behaviour.
|
||||
if (this.state.activityEnabled === undefined && this.configExplicit.activityEnabled === undefined) {
|
||||
|
|
@ -220,19 +266,44 @@ export class SettingsStore {
|
|||
return resolved
|
||||
}
|
||||
|
||||
/** The activity:write bearer token (sidecar first, env fallback). */
|
||||
/** The activity:write bearer token (sidecar first, origin-bound env fallback). */
|
||||
activityToken(): string {
|
||||
return this.state.activityToken ?? envToken('DSH_BRAIN_ACTIVITY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_ACTIVITY_TOKEN') ?? ''
|
||||
return this.tokenFor('activity', this.state.activityToken)
|
||||
}
|
||||
|
||||
/** The memory:read / memory:write bearer token. */
|
||||
memoryToken(): string {
|
||||
return this.state.memoryToken ?? envToken('DSH_BRAIN_MEMORY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_MEMORY_TOKEN') ?? ''
|
||||
return this.tokenFor('memory', this.state.memoryToken)
|
||||
}
|
||||
|
||||
/** The summary:write bearer token (optional; absent disables summaries). */
|
||||
summaryToken(): string {
|
||||
return this.state.summaryToken ?? envToken('DSH_BRAIN_SUMMARY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_SUMMARY_TOKEN') ?? ''
|
||||
return this.tokenFor('summary', this.state.summaryToken)
|
||||
}
|
||||
|
||||
/**
|
||||
* Env-var tokens are an escape hatch for unattended setups, so they must be
|
||||
* explicit about WHICH service they belong to: `DSH_BRAIN_TOKEN_ORIGIN` (or
|
||||
* the legacy `DSH_CLOUD_MEMORY_TOKEN_ORIGIN`) has to name the origin of the
|
||||
* current baseUrl. A token cleared from the sidecar stays cleared — the
|
||||
* marker blocks the env fallback until a new token is written.
|
||||
*/
|
||||
private tokenFor(label: 'activity' | 'memory' | 'summary', sidecar: string | undefined): string {
|
||||
if (sidecar !== undefined && sidecar !== '') return sidecar
|
||||
if (this.state.clearedTokens?.includes(label) === true) return ''
|
||||
const envPrefix = label === 'activity' ? 'DSH_BRAIN_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_BRAIN_MEMORY_TOKEN' : 'DSH_BRAIN_SUMMARY_TOKEN'
|
||||
const legacyPrefix = label === 'activity' ? 'DSH_CLOUD_MEMORY_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_CLOUD_MEMORY_MEMORY_TOKEN' : 'DSH_CLOUD_MEMORY_SUMMARY_TOKEN'
|
||||
const boundOrigin = envToken('DSH_BRAIN_TOKEN_ORIGIN') ?? envToken('DSH_CLOUD_MEMORY_TOKEN_ORIGIN')
|
||||
if (boundOrigin === undefined) return ''
|
||||
if (boundOrigin !== originOf(this.settings().baseUrl)) return ''
|
||||
return envToken(envPrefix) ?? envToken(legacyPrefix) ?? ''
|
||||
}
|
||||
|
||||
/** Which layer currently supplies each token (drives the card's hint). */
|
||||
private tokenSource(label: 'activity' | 'memory' | 'summary', sidecar: string | undefined): 'sidecar' | 'env' | 'none' {
|
||||
if (sidecar !== undefined && sidecar !== '') return 'sidecar'
|
||||
if (this.tokenFor(label, sidecar) !== '') return 'env'
|
||||
return 'none'
|
||||
}
|
||||
|
||||
/** Masked snapshot for the browser card. */
|
||||
|
|
@ -243,9 +314,9 @@ export class SettingsStore {
|
|||
const summary = this.summaryToken()
|
||||
return {
|
||||
...settings,
|
||||
activityToken: { configured: activity !== '', masked: activity === '' ? '' : maskToken(activity) },
|
||||
memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory) },
|
||||
summaryToken: { configured: summary !== '', masked: summary === '' ? '' : maskToken(summary) },
|
||||
activityToken: { configured: activity !== '', masked: activity === '' ? '' : maskToken(activity), source: this.tokenSource('activity', this.state.activityToken) },
|
||||
memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory), source: this.tokenSource('memory', this.state.memoryToken) },
|
||||
summaryToken: { configured: summary !== '', masked: summary === '' ? '' : maskToken(summary), source: this.tokenSource('summary', this.state.summaryToken) },
|
||||
statePath: this.file,
|
||||
baseUrlConfigured: !isPlaceholderBaseUrl(settings.baseUrl),
|
||||
baseUrlOrigin: originOf(settings.baseUrl),
|
||||
|
|
@ -291,12 +362,14 @@ export class SettingsStore {
|
|||
if (!activityToken.startsWith('cmt_')) return { ok: false, error: 'activity token must start with cmt_' }
|
||||
next.activityToken = activityToken
|
||||
provided.push('activity')
|
||||
unsetCleared(next, 'activity')
|
||||
}
|
||||
const memoryToken = cleanString(patch.memoryToken)
|
||||
if (memoryToken !== undefined) {
|
||||
if (!memoryToken.startsWith('cmt_')) return { ok: false, error: 'memory token must start with cmt_' }
|
||||
next.memoryToken = memoryToken
|
||||
provided.push('memory')
|
||||
unsetCleared(next, 'memory')
|
||||
}
|
||||
if (patch.requestTimeoutMs !== undefined) {
|
||||
const requestTimeoutMs = clampInt(patch.requestTimeoutMs, 1000, 60_000)
|
||||
|
|
@ -327,15 +400,30 @@ export class SettingsStore {
|
|||
if (skillsDir.length > 512) return { ok: false, error: 'skillsDir too long' }
|
||||
next.skillsDir = skillsDir
|
||||
}
|
||||
for (const key of ['localMemoryEnabled', 'cloudMemoryEnabled', 'autoMemorySpaces', 'autoSummaryEnabled', 'autoProfileEnabled'] as const) {
|
||||
if (patch[key] !== undefined) {
|
||||
if (typeof patch[key] !== 'boolean') return { ok: false, error: key + ' must be a boolean' }
|
||||
next[key] = patch[key]
|
||||
}
|
||||
}
|
||||
if (patch.localMemoryK !== undefined) {
|
||||
const localMemoryK = clampInt(patch.localMemoryK, 1, 100)
|
||||
if (localMemoryK === undefined) return { ok: false, error: 'localMemoryK must be a number' }
|
||||
next.localMemoryK = localMemoryK
|
||||
}
|
||||
const summaryToken = cleanString(patch.summaryToken)
|
||||
if (summaryToken !== undefined) {
|
||||
if (!summaryToken.startsWith('cmt_')) return { ok: false, error: 'summary token must start with cmt_' }
|
||||
next.summaryToken = summaryToken
|
||||
provided.push('summary')
|
||||
unsetCleared(next, 'summary')
|
||||
}
|
||||
if (patch.clearSummaryToken === true) delete next.summaryToken
|
||||
if (patch.clearActivityToken === true) delete next.activityToken
|
||||
if (patch.clearMemoryToken === true) delete next.memoryToken
|
||||
// Clearing pins a marker: the env fallback must not resurrect a token the
|
||||
// user explicitly removed, and an address switch must not hand the env
|
||||
// token of the old service to the new one either.
|
||||
if (patch.clearSummaryToken === true) { delete next.summaryToken; markCleared(next, 'summary') }
|
||||
if (patch.clearActivityToken === true) { delete next.activityToken; markCleared(next, 'activity') }
|
||||
if (patch.clearMemoryToken === true) { delete next.memoryToken; markCleared(next, 'memory') }
|
||||
|
||||
// Switching the service origin must not hand the previous service's
|
||||
// bearer tokens to the new one: everything this request did not explicitly
|
||||
|
|
@ -352,6 +440,7 @@ export class SettingsStore {
|
|||
if (next[key] === undefined) continue
|
||||
if (provided.includes(label)) continue
|
||||
delete next[key]
|
||||
markCleared(next, label)
|
||||
clearedTokens.push(label)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
* Single source of truth for the package version.
|
||||
*
|
||||
* The compiled file lives in `lib/`, so `../package.json` resolves to this
|
||||
* package's manifest both in the repo and inside node_modules. Every surface
|
||||
* that reports a version (status card, capabilities, Mnemon manifest) reads it
|
||||
* from here, so a release bump is one edit in package.json.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const FALLBACK_VERSION = '0.10.1'
|
||||
|
||||
function readVersion(): string {
|
||||
try {
|
||||
const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')) as { version?: unknown }
|
||||
if (typeof manifest.version === 'string' && manifest.version !== '') return manifest.version
|
||||
} catch {
|
||||
// A missing or broken manifest must not take the plugin down.
|
||||
}
|
||||
return FALLBACK_VERSION
|
||||
}
|
||||
|
||||
/** Version reported by the status card, capabilities and the Mnemon manifest. */
|
||||
export const VERSION = readVersion()
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
# Release intents
|
||||
|
||||
Every pull request that changes a published artifact adds a changeset here with
|
||||
`pnpm changeset`. [Releasing independent packages](../docs/en/development/releasing.md)
|
||||
([中文](../docs/zh-CN/development/releasing.md)) says which packages to select, how
|
||||
the release pull request consumes these files, and how publication works.
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"changelog": false,
|
||||
"commit": false,
|
||||
"fixed": [],
|
||||
"linked": [],
|
||||
"access": "public",
|
||||
"baseBranch": "main",
|
||||
"updateInternalDependencies": "patch",
|
||||
"bumpVersionsWithWorkspaceProtocolOnly": false,
|
||||
"ignore": [],
|
||||
"___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": {
|
||||
"onlyUpdatePeerDependentsWhenOutOfRange": true,
|
||||
"updateInternalDependents": "out-of-range"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
---
|
||||
"dsh-mnemon": patch
|
||||
---
|
||||
|
||||
Surface the redacted last failed tool call detail when a delegated memory subagent or standalone idle review completes without recording its structured result, redact stopped diagnostics on standalone reviews, preserve managed review turn-end error details when `diagnostic` is omitted, and map `blocked` isolated review endings to `refusal`.
|
||||
|
||||
当委派记忆子 Agent 或独立空闲复盘在未记录结构化结果的情况下结束时,附加脱敏后的最后一次失败工具调用详情;对独立复盘的停止诊断信息统一脱敏,在托管独立复盘省略 `diagnostic` 时保留 `turn/end` 错误详情,并将 `blocked` 结束原因映射为 `refusal`。
|
||||
|
|
@ -0,0 +1,149 @@
|
|||
name: Bug 报告 / Bug report
|
||||
description: 报告异常现象、复现步骤和环境;日志及修复建议可选。 / Describe the problem, reproduction steps and environment; logs and fixes are optional.
|
||||
title: "[Bug]: "
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
请填写现象、预期结果、复现步骤和环境。信息不足时机器人会提示补充,模板检查不会自动关闭 Issue。
|
||||
Describe the problem, expected outcome, reproduction steps and environment. Missing information prompts a request for details; template checks do not close issues.
|
||||
|
||||
日志、截图和对照结果可直接放在复现步骤中。下方的证据、冒烟测试、代码引用和补丁草案均为选填,无需重复内容或先提供修复方案。
|
||||
Logs, screenshots and control results may go directly in the reproduction steps. Separate evidence, smoke tests, code references and patch proposals are optional; no duplication or fix is required.
|
||||
|
||||
通过 CLI/API 提交时可使用相同段落标题组织正文。类型填写为“Bug 报告 / Bug report”时,机器人会补齐 `bug` 标签,无需提交者拥有标签权限。
|
||||
CLI/API reports may use the same section headings. The bot adds the `bug` label when the type is “Bug 报告 / Bug report”; reporters do not need label permissions.
|
||||
|
||||
提交前请先搜索确认没有重复 / Search for existing reports before submitting: [Issues](https://github.com/omdsh-dev/dsh-mnemon/issues?q=is%3Aissue)
|
||||
|
||||
不要粘贴 token、密钥、私有记忆内容或未脱敏日志。安全漏洞请按 [SECURITY.md](../../SECURITY.md) 私下报告。
|
||||
Do not post tokens, credentials, private memory, or unredacted logs. Report security vulnerabilities privately through [SECURITY.md](../../SECURITY.md).
|
||||
- type: checkboxes
|
||||
id: duplicate-check
|
||||
attributes:
|
||||
label: 提交前查重 / Duplicate check
|
||||
description: 请搜索 open 和 closed Issue。 / Search both open and closed issues.
|
||||
options:
|
||||
- label: 我已搜索 open/closed Issue,确认没有重复。 / I searched open and closed issues and found no duplicate.
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: 涉及区域 / Affected area
|
||||
description: 选择问题主要涉及的组件或边界。 / Select the component or boundary most closely related to the problem.
|
||||
options:
|
||||
- 安装、更新或发布 / Installation, update, or release
|
||||
- Host 激活或 Headless / Host activation or Headless
|
||||
- 运行时记忆 / Runtime Memory
|
||||
- 项目档案 / Project Documents
|
||||
- 记忆空间或 Provider / Memory Spaces or Providers
|
||||
- 子 Agent 或 Agent 工作流 / Subagent or Agent workflow
|
||||
- Web UI 或对话交互 / Web UI or conversation interaction
|
||||
- 设置、存储或安全 / Settings, storage, or security
|
||||
- CLI、RPC、命令或工具 / CLI, RPC, commands, or tools
|
||||
- 文档 / Documentation
|
||||
- 其他或不确定 / Other or unsure
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: issue-type
|
||||
attributes:
|
||||
label: Issue 类型 / Issue type
|
||||
description: 本表单仅用于可复现的 Bug;功能请求或问题请使用另一个表单。 / This form is only for reproducible bugs; use the other form for requests or questions.
|
||||
options:
|
||||
- Bug 报告 / Bug report
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: summary
|
||||
attributes:
|
||||
label: 摘要 / Summary
|
||||
description: 用一两句话描述实际发生的问题。 / Describe the observed problem in one or two sentences.
|
||||
placeholder: 出了什么问题?影响了哪些操作? / What went wrong, and which operations are affected?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected-outcome
|
||||
attributes:
|
||||
label: 预期结果 / Expected outcome
|
||||
description: 描述正确行为以及可以验证的结果。 / Describe the correct behavior and an observable result.
|
||||
placeholder: 你期望发生什么? / What did you expect to happen?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: details-reproduction
|
||||
attributes:
|
||||
label: 详情或复现步骤 / Details or reproduction steps
|
||||
description: 提供最小复现步骤和实际结果;报错和日志(包括 JSON 或普通文本)可直接写在这里。 / Include minimal steps and observed results; errors and logs, including JSON or plain text, may go here.
|
||||
placeholder: |
|
||||
1. 配置 / Configure ...
|
||||
2. 启动 / Start ...
|
||||
3. 调用或点击 / Invoke or click ...
|
||||
4. 观察到 / Observe ...
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: 环境信息 / Environment
|
||||
description: 请提供 DSH、dsh-brain-mnemon、Mnemon、Node.js、操作系统、浏览器以及相关 Provider/配置,并先脱敏。 / Provide DSH, dsh-brain-mnemon, Mnemon, Node.js, OS, browser, and relevant redacted Provider or configuration details.
|
||||
placeholder: |
|
||||
- DSH 版本 / DSH version:
|
||||
- dsh-brain-mnemon 版本或 commit / dsh-brain-mnemon version or commit:
|
||||
- Mnemon 版本 / Mnemon version:
|
||||
- Node.js / pnpm:
|
||||
- 操作系统或浏览器 / OS or browser:
|
||||
- Provider 或相关配置(已脱敏)/ Provider or related configuration (redacted):
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: bug-evidence
|
||||
attributes:
|
||||
label: Bug 证据 / Bug evidence
|
||||
description: 选填。复现步骤已有证据时无需重复;支持普通文本、任意语言代码块、图片或附件。 / Optional. Do not repeat evidence already in the steps; plain text, any code-block language, images or attachments are accepted.
|
||||
placeholder: 可粘贴脱敏报错、日志、截图或附件,也可留空。 / Add redacted errors, logs, screenshots or attachments, or leave blank.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: smoke-test
|
||||
attributes:
|
||||
label: 冒烟测试 / Smoke test
|
||||
description: 选填。补充实际执行的验证、观察结果或对照实验;未执行可留空。 / Optional. Add checks you actually ran, observed results or controls; leave blank if none were run.
|
||||
placeholder: |
|
||||
- 测试环境 / Test environment:
|
||||
- 执行命令或操作 / Commands or actions:
|
||||
- 实际结果 / Observed result:
|
||||
- 对照版本或配置 / Control version or configuration:
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: code-reference
|
||||
attributes:
|
||||
label: 引用代码 / Code references
|
||||
description: 选填。知道相关代码位置时,可提供路径、函数或固定 commit 链接。 / Optional. If you know the relevant code, add paths, functions or links pinned to a commit.
|
||||
placeholder: |
|
||||
src/host/subagent.ts:870
|
||||
tests/subagent.spec.ts
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: patch
|
||||
attributes:
|
||||
label: 补丁草案 / Patch proposal
|
||||
description: 选填。已有修复思路时可以补充;无需为提交 Bug 先编写补丁。 / Optional. Share a fix if you have one; a patch is not required to report a bug.
|
||||
placeholder: |
|
||||
```diff
|
||||
--- a/src/example.ts
|
||||
+++ b/src/example.ts
|
||||
@@ ... @@
|
||||
```
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: 补充信息 / Additional context
|
||||
description: 补充相关 Issue、PR、最小复现仓库或其他已脱敏上下文。 / Add related issues, pull requests, a minimal reproduction, or other redacted context.
|
||||
validations:
|
||||
required: false
|
||||
|
|
@ -0,0 +1 @@
|
|||
blank_issues_enabled: false
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
name: 功能请求或问题 / Request or question
|
||||
description: 请求功能、更新文档或提出项目问题。 / Request a feature or documentation update, or ask a project question.
|
||||
title: "[Issue]: "
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
请填写请求、预期结果、使用场景和相关环境。信息不足时机器人会提示补充,模板检查不会自动关闭 Issue。Bug 请使用“Bug 报告 / Bug report”表单。
|
||||
Describe the request, expected outcome, use case and relevant environment. Missing information prompts a request for details; template checks do not close issues. Use the “Bug 报告 / Bug report” form for bugs.
|
||||
|
||||
通过 CLI/API 提交时可使用相同段落标题组织正文;补充信息可直接编辑原 Issue,机器人会更新已有提示。
|
||||
CLI/API reports may use the same section headings. Edit the original issue to add information; the bot updates its existing reminder.
|
||||
|
||||
提交前请先搜索确认没有重复 / Search for existing issues before submitting: [Issues](https://github.com/omdsh-dev/dsh-mnemon/issues?q=is%3Aissue)
|
||||
|
||||
不要公开提交漏洞、token、密钥、私有记忆内容或未脱敏日志。安全问题请按 [SECURITY.md](../../SECURITY.md) 私下报告。
|
||||
Do not post vulnerabilities, tokens, credentials, private memory, or unredacted logs. Report security concerns privately through [SECURITY.md](../../SECURITY.md).
|
||||
- type: checkboxes
|
||||
id: duplicate-check
|
||||
attributes:
|
||||
label: 提交前查重 / Duplicate check
|
||||
description: 请搜索 open 和 closed Issue。 / Search both open and closed issues.
|
||||
options:
|
||||
- label: 我已搜索 open/closed Issue,确认没有重复。 / I searched open and closed issues and found no duplicate.
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: 涉及区域 / Affected area
|
||||
description: 选择请求或问题主要涉及的组件或边界。 / Select the component or boundary most closely related to the request or question.
|
||||
options:
|
||||
- 安装、更新或发布 / Installation, update, or release
|
||||
- Host 激活或 Headless / Host activation or Headless
|
||||
- 运行时记忆 / Runtime Memory
|
||||
- 项目档案 / Project Documents
|
||||
- 记忆空间或 Provider / Memory Spaces or Providers
|
||||
- 子 Agent 或 Agent 工作流 / Subagent or Agent workflow
|
||||
- Web UI 或对话交互 / Web UI or conversation interaction
|
||||
- 设置、存储或安全 / Settings, storage, or security
|
||||
- CLI、RPC、命令或工具 / CLI, RPC, commands, or tools
|
||||
- 文档 / Documentation
|
||||
- 其他或不确定 / Other or unsure
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: issue-type
|
||||
attributes:
|
||||
label: Issue 类型 / Issue type
|
||||
description: 选择最接近的分类。 / Select the closest category.
|
||||
options:
|
||||
- 功能请求 / Feature request
|
||||
- 增强或优化 / Enhancement or optimization
|
||||
- 文档 / Documentation
|
||||
- 问题 / Question
|
||||
- 其他 / Other
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: summary
|
||||
attributes:
|
||||
label: 摘要 / Summary
|
||||
description: 用一两句话描述问题或请求。 / Describe the question or request in one or two sentences.
|
||||
placeholder: 希望解决什么问题或增加什么能力? / What problem should be solved or capability added?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected-outcome
|
||||
attributes:
|
||||
label: 预期结果 / Expected outcome
|
||||
description: 描述完成后的可观察行为和验收结果。 / Describe the observable behavior and acceptance result after completion.
|
||||
placeholder: 怎样才算完成? / What would count as complete?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: details-reproduction
|
||||
attributes:
|
||||
label: 详情或复现步骤 / Details or reproduction steps
|
||||
description: 说明使用场景、现有行为、约束和替代方案;若涉及问题,请给出复现步骤。 / Explain the use case, current behavior, constraints, and alternatives; include reproduction steps when relevant.
|
||||
placeholder: |
|
||||
- 使用场景 / Use case:
|
||||
- 当前限制 / Current limitation:
|
||||
- 建议方案 / Proposed approach:
|
||||
- 不在范围内的内容 / Out of scope:
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: 环境信息 / Environment
|
||||
description: 请提供 DSH、dsh-brain-mnemon、Mnemon、操作系统及相关配置;与环境无关时填写 N/A。 / Provide DSH, dsh-brain-mnemon, Mnemon, OS, and relevant configuration details, or enter N/A when environment-independent.
|
||||
placeholder: |
|
||||
- DSH 版本 / DSH version:
|
||||
- dsh-brain-mnemon 版本或 commit / dsh-brain-mnemon version or commit:
|
||||
- Mnemon 版本 / Mnemon version:
|
||||
- 操作系统或浏览器 / OS or browser:
|
||||
- 相关配置(已脱敏)/ Related configuration (redacted):
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: 补充信息 / Additional context
|
||||
description: 补充截图、日志、设计草图、相关 Issue/PR 或其他上下文。 / Add screenshots, logs, design sketches, related issues or pull requests, or other context.
|
||||
validations:
|
||||
required: false
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
> 提交 PR 前请阅读[贡献指南](../CONTRIBUTING.zh-CN.md)、[Contributing Guide](../CONTRIBUTING.md)与[开发和验证指南](../docs/zh-CN/development/README.md) / [Development and Verification Guide](../docs/en/development/README.md)。
|
||||
> Before opening a PR, read the [Contributing Guide](../CONTRIBUTING.md), [贡献指南](../CONTRIBUTING.zh-CN.md), and the [Development and Verification Guide](../docs/en/development/README.md) / [开发和验证指南](../docs/zh-CN/development/README.md).
|
||||
> PR 标题和提交信息必须使用 Conventional Commits(`type(scope): subject`),且不得包含 emoji。 / PR titles and commits must use Conventional Commits (`type(scope): subject`) and must not contain emoji.
|
||||
> 本仓库接受 Bug 修复、兼容性适配、现有能力增强、性能或体验优化和维护类 PR。全新能力、Provider、持久化格式或安全边界变更必须先提 Issue 并获得维护者确认。 / This repository accepts bug fixes, compatibility work, improvements to existing capabilities, performance or UX optimization, and maintenance. New capabilities, Providers, persistence formats, or security-boundary changes require prior maintainer approval in an Issue.
|
||||
> 外部贡献者的仅文档类 PR 不直接接受;请先提 Issue 讨论。维护者的发布说明与文档维护不受此限制。 / Documentation-only PRs from external contributors are not accepted directly; open an Issue first. Maintainer release notes and documentation maintenance are exempt.
|
||||
|
||||
## 摘要 / Summary
|
||||
|
||||
<!-- 用一两句话说明改了什么、为什么改,以及用户或系统行为如何变化。 / In one or two sentences, explain what changed, why, and how user or system behavior changes. -->
|
||||
|
||||
## 关联 Issue 或背景 / Related Issue or Context
|
||||
|
||||
<!-- 优先使用 Closes #123 或 Fixes #123。没有 Issue 时填写 N/A 并解释为什么可以直接提交。 / Prefer Closes #123 or Fixes #123. If there is no Issue, enter N/A and explain why a direct PR is appropriate. -->
|
||||
|
||||
## 涉及区域 / Affected Areas
|
||||
|
||||
<!-- 至少勾选一项。 / Check at least one item. -->
|
||||
|
||||
- [ ] Host 激活、Headless 或 bundle / Host activation, Headless, or bundle
|
||||
- [ ] 运行时记忆 / Runtime Memory
|
||||
- [ ] 项目档案 / Project Documents
|
||||
- [ ] 记忆空间或 Provider / Memory Spaces or Providers
|
||||
- [ ] 子 Agent 或 Agent 工作流 / Subagent or Agent workflow
|
||||
- [ ] Web UI 或对话交互 / Web UI or conversation interaction
|
||||
- [ ] 设置、存储或安全 / Settings, storage, or security
|
||||
- [ ] CLI、RPC、命令或工具 / CLI, RPC, commands, or tools
|
||||
- [ ] 安装、更新或发布 / Installation, update, or release
|
||||
- [ ] 测试、构建或文档 / Tests, build, or documentation
|
||||
- [ ] 其他(请说明)/ Other (explain below)
|
||||
|
||||
## PR 类型 / PR Type
|
||||
|
||||
<!-- 至少勾选一项;仅文档类 PR 的限制见文件顶部说明。 / Check at least one item; see the note above for documentation-only PRs. -->
|
||||
|
||||
- [ ] 面向用户的功能或行为变更 / User-facing feature or behavior change
|
||||
- [ ] Bug 修复 / Bug fix
|
||||
- [ ] 增强或优化 / Enhancement or optimization
|
||||
- [ ] 兼容性适配 / Compatibility change
|
||||
- [ ] 维护或重构 / Maintenance or refactor
|
||||
- [ ] 测试或构建 / Tests or build
|
||||
|
||||
## 最新代码确认 / Latest Codebase Confirmation
|
||||
|
||||
- [ ] 我已基于最新 `main` 分支开发,或在提交前已 rebase 或合并最新 `main`。 / I developed from the latest `main`, or rebased or merged the latest `main` before submitting.
|
||||
|
||||
同步命令 / Sync command:
|
||||
|
||||
<!-- 示例 / Example: git fetch origin && git rebase origin/main -->
|
||||
|
||||
## AI 编码披露 / AI Coding Disclosure
|
||||
|
||||
<!-- 必填。勾选且仅勾选一项;模型和工具字段不得留空。 / Required. Check exactly one option; the model and tool fields must not be blank. -->
|
||||
|
||||
- [ ] 完全 AI 编码:全部编程改动由 AI 产出,并由贡献者接受和审查。 / Fully AI-coded: AI produced all programming changes, which the contributor accepted and reviewed.
|
||||
- [ ] 部分 AI 辅助:AI 帮助编写或修改了部分内容。 / Partially AI-assisted: AI helped write or modify part of the change.
|
||||
- [ ] 未使用 AI 编码辅助。 / No AI coding assistance was used.
|
||||
|
||||
使用的 AI 模型 / AI model used:
|
||||
|
||||
<!-- 使用 AI 时填写具体模型;未使用时填 N/A。 / Name the model when AI was used; otherwise enter N/A. -->
|
||||
|
||||
使用的编码 Agent 工具 / Coding Agent tool used:
|
||||
|
||||
<!-- 使用 AI 时填写 Codex、Claude Code、Cursor 等;未使用时填 N/A。 / Name tools such as Codex, Claude Code, or Cursor when AI was used; otherwise enter N/A. -->
|
||||
|
||||
## 仓库规范检查 / Repository Rules
|
||||
|
||||
<!-- 本仓库硬性规范,请逐项确认。 / Confirm every mandatory repository rule. -->
|
||||
|
||||
- [ ] 未修改 DSH 官方源码,未让 tsconfig 指向 DSH 源码 checkout,仅使用正式的 `@deepseek-ai/*` NPM 契约。 / I did not modify DSH source or point tsconfig at a DSH source checkout, and used only published `@deepseek-ai/*` NPM contracts.
|
||||
- [ ] Client 与 Host 边界仍以浏览器安全的 `src/host/protocol.ts` 为准,没有在两侧重复定义 wire DTO。 / The Client and Host boundary still uses browser-safe `src/host/protocol.ts` as the source for wire DTOs.
|
||||
- [ ] 持久化格式、RPC 权限、路径或凭据处理的变更包含兼容或拒绝路径、安全分析和相应测试。 / Changes to persistence formats, RPC authority, paths, or credentials include compatibility or rejection paths, security analysis, and tests.
|
||||
- [ ] 没有提交 token、密钥、私有记忆、未脱敏日志或生成的 `lib/` 文件。 / I did not commit tokens, credentials, private memory, unredacted logs, or generated `lib/` files.
|
||||
- [ ] 用户可见文案和长期文档已同步维护中文与英文版本,命令、配置键和路径保持一致。 / User-facing copy and long-lived documentation are synchronized in Chinese and English, with matching commands, configuration keys, and paths.
|
||||
- [ ] 会改变发布制品或其元数据的 PR 已添加 changeset;仅测试、CI 或站点文档变更可不添加。 / A PR that changes a published artifact or its metadata includes a changeset; test-only, CI-only, and site-documentation-only changes may omit one.
|
||||
- [ ] 新增和修改的代码、注释、文档、提交信息不含 emoji。 / New and modified code, comments, documentation, and commits contain no emoji.
|
||||
|
||||
## 兼容性与数据安全 / Compatibility and Data Safety
|
||||
|
||||
<!-- 必填。说明对 DSH、Mnemon、Provider、配置、存储格式、升级或回滚和现有数据的影响。没有影响时填 N/A 并说明理由。 / Required. Explain effects on DSH, Mnemon, Providers, configuration, storage formats, upgrades or rollback, and existing data. Enter N/A with a reason when there is no impact. -->
|
||||
|
||||
## 本地验证 / Local Validation
|
||||
|
||||
执行的命令 / Commands run:
|
||||
|
||||
```bash
|
||||
pnpm run verify
|
||||
```
|
||||
|
||||
结果摘要 / Result summary:
|
||||
|
||||
<!-- 写明通过、跳过或失败的项目和原因,不要留空。 / Report passed, skipped, or failed checks and the reasons; do not leave this blank. -->
|
||||
|
||||
## 用户可见变更证据 / Local Feature Evidence
|
||||
|
||||
<!--
|
||||
截图或短视频有助于判断重要 WebUI 变更时,请附上关键界面的前后对比或新状态。 / Add a before/after comparison or key-state screenshot when it helps reviewers assess a material WebUI change.
|
||||
外部贡献者直接将截图或短视频拖拽附在 GitHub PR 描述中即可,无需上传到 `mnemon-dev/assets`;维护者与自动化 CLI 流程可使用 `node scripts/upload-pr-evidence.mjs` 上传至 `mnemon-dev/assets` 并以完整 40 位 commit SHA 引用。禁止向 `main` 提交 PR 验收图片目录。 / External contributors should drag and drop screenshots or short videos directly in the GitHub PR description and do not need to upload to `mnemon-dev/assets`; maintainers and automated CLI workflows may use `node scripts/upload-pr-evidence.mjs` to upload to `mnemon-dev/assets` pinned by full 40-character commit SHA. Never commit PR binary asset directories to `main`.
|
||||
提供截图或短视频时,请展示 / If including screenshots or a short video, show:
|
||||
- 改动前/后界面对比,或新增视图与关键交互状态 / before/after comparison, or the new view and key interactive states
|
||||
- 使用的是本 PR 或最新代码 / the PR or latest code is running
|
||||
- 功能已启用或配置 / the feature is enabled or configured
|
||||
- 操作成功并出现可见结果 / the action succeeds with a visible result
|
||||
- 没有泄露凭据、私有记忆或敏感路径 / no credentials, private memory, or sensitive paths are exposed
|
||||
纯内部改动可填 N/A 并解释。 / For internal-only changes, enter N/A and explain.
|
||||
-->
|
||||
|
||||
证据 / Evidence:
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
## v0.5.0-rc.1 · Composable Memory Plugins
|
||||
|
||||
This release candidate keeps the v0.4 Sidebar experience and upgrades the implementation to a composable, View-based memory system. Existing configuration, three-tier workflows, storage formats, and ordinary UI remain compatible. The only new user-facing controls are three disabled-by-default switches under **Settings → Memory System → Memory enhancements**.
|
||||
|
||||
### What ships
|
||||
|
||||
- One `dsh-mnemon` Starter plus sixteen independently published, version-locked packages: three Sources, one default Strategy, three optional Strategy enhancements, and nine Memory Space Providers.
|
||||
- A narrow `ctx.mnemonMemory` runtime boundary, public `dsh-mnemon/extension-sdk`, isolated `dsh-mnemon/testing` fixtures, Fiber-owned registration, immutable turn Views, Source-local grants, and bounded execution.
|
||||
- Optional scoped composition, light-context projection, and current-turn auto-capture guidance. These extensions compose through distinct slots and remain disabled unless the user enables them.
|
||||
- Independent package, tarball, Node 20/22/24, Windows, Headless, copied-data upgrade, and real `v0.4.7 → v0.5.0-rc.1` Registry upgrade gates.
|
||||
|
||||
### Community requests
|
||||
|
||||
- [#110](https://github.com/omdsh-dev/dsh-mnemon/issues/110): auto-capture now offers an opt-in current-turn recording policy. It is not an unsupervised background writer, so the broader request remains open.
|
||||
- [#40](https://github.com/omdsh-dev/dsh-mnemon/issues/40): light-context provides a bounded projection policy. Revisioned incremental injection remains an upstream-dependent open item.
|
||||
- [#77](https://github.com/omdsh-dev/dsh-mnemon/issues/77): scoped composition generalizes the existing global/project memory use case with ordered Sources and a writable subset.
|
||||
|
||||
### Install
|
||||
|
||||
This prerelease is available on the npm `rc` channel and does not replace `latest`:
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add dsh-mnemon@0.5.0-rc.1
|
||||
```
|
||||
|
||||
Use `headless` instead of `web` for a Headless profile. Back up the effective memory root, Documents, DSH profile/configuration, and separately managed Provider data before trying a prerelease.
|
||||
|
||||
Full compatibility boundaries, rollback instructions, and extension limitations are documented in the [English release notes](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.0-rc.1/docs/en/releases/v0.5.0-rc.1.md) and [中文发布说明](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.0-rc.1/docs/zh-CN/releases/v0.5.0-rc.1.md).
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
## v0.5.0 · Composable Memory Plugins
|
||||
|
||||
v0.5.0 keeps the familiar v0.4 Sidebar experience while making the implementation composable through independently published Source, Strategy, and Provider plugins. Existing configuration, three-tier workflows, storage formats, and ordinary UI remain compatible. The only new user-facing controls are three disabled-by-default switches under **Settings → Memory System → Memory enhancements**.
|
||||
|
||||
### What ships
|
||||
|
||||
- One `dsh-mnemon` Starter plus sixteen independently published, version-locked packages: three Sources, one default Strategy, three optional Strategy enhancements, and nine Memory Space Providers.
|
||||
- A narrow `ctx.mnemonMemory` runtime boundary, the public `dsh-mnemon/extension-sdk`, isolated `dsh-mnemon/testing` fixtures, Fiber-owned registration, immutable turn Views, Source-local grants, and bounded execution.
|
||||
- Optional scoped composition, light-context projection, and current-turn auto-capture guidance. These extensions compose through distinct slots and remain disabled unless the user enables them.
|
||||
- Independent package, tarball, Node 20/22/24, Windows, Headless, copied-data upgrade, and real `v0.4.7 → v0.5.0` Registry upgrade gates.
|
||||
|
||||
The runtime behavior and persisted formats are unchanged from `v0.5.0-rc.1`; the stable promotion additionally generalizes and verifies the release pipeline for the npm `latest` channel.
|
||||
|
||||
### Community requests
|
||||
|
||||
- [#110](https://github.com/omdsh-dev/dsh-mnemon/issues/110): auto-capture provides an opt-in current-turn recording policy. It does not add an unsupervised background writer.
|
||||
- [#40](https://github.com/omdsh-dev/dsh-mnemon/issues/40): light-context provides a bounded projection policy. Revisioned incremental injection remains an upstream-dependent open item.
|
||||
- [#77](https://github.com/omdsh-dev/dsh-mnemon/issues/77): scoped composition generalizes the global/project memory use case with ordered Sources and a writable subset.
|
||||
|
||||
### Install or upgrade
|
||||
|
||||
`v0.5.0` is the npm `latest` release:
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add dsh-mnemon@0.5.0
|
||||
```
|
||||
|
||||
Use `headless` instead of `web` for a Headless profile, then restart DSH. Back up the effective memory root, Documents, DSH profile/configuration, and separately managed Provider data before upgrading.
|
||||
|
||||
Full compatibility boundaries, rollback instructions, and extension limits are documented in the [English release notes](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.0/docs/en/releases/v0.5.0.md) and [中文发布说明](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.0/docs/zh-CN/releases/v0.5.0.md).
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
## v0.5.1 · Desktop and Turn Reliability
|
||||
|
||||
v0.5.1 is a coordinated patch release for the `dsh-mnemon` Starter and all sixteen official Source, Strategy, and Provider packages. It fixes two user-visible failures on the stable DSH 0.1.2-rc.1 line without changing configuration or persisted data.
|
||||
|
||||
### Fixes
|
||||
|
||||
- [#176](https://github.com/omdsh-dev/dsh-mnemon/issues/176): mount the Memory System launcher through the released Desktop Sidebar's actual nested parent. Settings no longer fall back to a read-only state after an `insertBefore` `NotFoundError`.
|
||||
- [#172](https://github.com/omdsh-dev/dsh-mnemon/issues/172): abort and settle an in-flight Idle Review before the next ordinary turn binds the same Agent runtime. The new turn no longer fails with `Mnemon runtime is already pinned`.
|
||||
|
||||
### Verification and delivery
|
||||
|
||||
- Both regressions were reproduced and corrected in isolated real DSH 0.1.2-rc.1 WebUI profiles, with before/after screenshots and focused regression tests in [PR #177](https://github.com/omdsh-dev/dsh-mnemon/pull/177) and [PR #178](https://github.com/omdsh-dev/dsh-mnemon/pull/178).
|
||||
- PR CI now keeps two complementary heavy jobs and verifies independent packed plugins through a bounded four-worker queue. The measured critical path fell from 6m14s to 3m01s while retaining integrated source, public-entry, standalone package, external-consumer, and real DSH checks ([PR #179](https://github.com/omdsh-dev/dsh-mnemon/pull/179)).
|
||||
|
||||
### Install or upgrade
|
||||
|
||||
`v0.5.1` is published on the npm `latest` channel:
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add dsh-mnemon@0.5.1
|
||||
```
|
||||
|
||||
Use `headless` instead of `web` for a Headless profile, then restart DSH. No storage migration is required. Back up the effective memory root, Documents, DSH profile/configuration, and separately managed Provider data before upgrading.
|
||||
|
||||
Full compatibility and rollback details are in the [English release notes](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.1/docs/en/releases/v0.5.1.md) and [中文发布说明](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.1/docs/zh-CN/releases/v0.5.1.md).
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
## v0.5.10 · Exact Memory Writes and Bounded Automatic Review
|
||||
|
||||
- [#256](https://github.com/omdsh-dev/dsh-mnemon/pull/256): prefer a unique exact Runtime entry for replace/remove before substring matching. Short entries such as `X` can be changed alongside `EGO_LINUX_CHROME`.
|
||||
- [#234](https://github.com/omdsh-dev/dsh-mnemon/pull/234): create the original OpenViking content, verify indexing and exact readback, and return scoped file receipts for archive compensation. Original contributor commits remain in the merged history.
|
||||
- [#257](https://github.com/omdsh-dev/dsh-mnemon/pull/257): add an independent automatic-review switch, cadence and attempt limits, bounded default spawn context, and committed-write receipts after failure. Pause automatic review before child creation with the incompatible Agent Teams composition.
|
||||
|
||||
### Packages and upgrade
|
||||
|
||||
New publications: **dsh-mnemon 0.5.10**, **OpenViking Provider 0.5.5**, **Memory Spaces Source 0.5.8**, and **Runtime Source 0.5.7**. The remaining thirteen plugins keep their existing versions.
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add dsh-mnemon@0.5.10
|
||||
```
|
||||
|
||||
Restart DSH and reload the browser; use `headless` for that Profile. The review budget resets when the parent Agent unloads or the Host restarts. The Agent Teams guard pauses automatic review; upstream Team policy and manual delegation are not repaired.
|
||||
|
||||
### 中文说明
|
||||
|
||||
本版修复 Runtime 短条目编辑与删除、OpenViking 原文写入和回执验证,并限制自动审阅的频率、次数和默认上下文。自动审阅增加独立开关;遇到不兼容的 Agent Teams 组合时,在创建子 Agent 前暂停。审阅失败后保留已提交写入的回执,方便核对。
|
||||
|
||||
主包发布 0.5.10,OpenViking Provider 发布 0.5.5,Memory Spaces Source 发布 0.5.8,Runtime Source 发布 0.5.7。升级后重启 DSH。审阅预算随父 Agent 卸载或 Host 重启而重置;Team 兼容处理不代表上游策略或手动委派已修复。
|
||||
|
||||
The combined implementation passed 1,162 root tests plus plugin suites, real CLI/WebUI checks, real OpenViking storage checks and independent plugin composition. Before/after screenshots remain in the linked reports. Model responses and embeddings were deterministic local fixtures. The release workflow verifies versioned artifacts, Registry composition and a real upgrade before creating this Release.
|
||||
|
||||
See the [English release notes](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.10/docs/en/releases/v0.5.10.md) and [中文发布说明](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.10/docs/zh-CN/releases/v0.5.10.md).
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
## v0.5.11 · Quiet Windows Git Branch Detection
|
||||
|
||||
[#260](https://github.com/omdsh-dev/dsh-mnemon/pull/260) fixes [#259](https://github.com/omdsh-dev/dsh-mnemon/issues/259): Runtime Git branch probes hide their Windows console, preventing brief terminal windows in GUI hosts. Branch filtering, the two-second timeout and failure fallback are unchanged.
|
||||
|
||||
### Packages and upgrade
|
||||
|
||||
New publications: **dsh-mnemon 0.5.11** and **Runtime Source 0.5.8**. The other fifteen plugins retain their versions; configuration and memory data need no migration.
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add dsh-mnemon@0.5.11
|
||||
```
|
||||
|
||||
Restart DSH and reload the browser; use `headless` for that Profile. Mnemon CLI remains independently maintained.
|
||||
|
||||
### 中文说明
|
||||
|
||||
本版修复 Windows GUI 宿主查询 Git 分支时短暂弹出终端窗口的问题。Runtime 查询增加隐藏窗口选项,保留分支过滤、两秒超时和失败回退。主包发布 0.5.11,Runtime Source 发布 0.5.8,其余十五个插件不变,无需迁移配置或已有记忆。升级后重启 DSH 并刷新浏览器。
|
||||
|
||||
Four real Windows trials observed 104–105 visible windows per baseline trial and zero after the fix. The implementation passed 59 Runtime tests, 1,162 root tests, real CLI/macOS WebUI checks and independent plugin composition. [Before/after evidence](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.11/docs/pr-assets/issue-259-windows-git-console/README.md) distinguishes Windows process observation from macOS WebUI validation. The release workflow checks versioned artifacts, Registry composition and an actual upgrade before creating this Release.
|
||||
|
||||
See [English release notes](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.11/docs/en/releases/v0.5.11.md) and [中文发布说明](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.11/docs/zh-CN/releases/v0.5.11.md).
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
## v0.5.12 · DSH RC and Alpha Compatibility
|
||||
|
||||
[#263](https://github.com/omdsh-dev/dsh-mnemon/pull/263) fixes [#261](https://github.com/omdsh-dev/dsh-mnemon/issues/261): the turn memory bar and save action now register correctly on DSH 0.1.6-alpha.2 while retaining 0.1.5-rc.2 compatibility. Sidebar and Settings use the public main-session binding; explicitly scoped views keep their own session and workspace authority.
|
||||
|
||||
### Packages and upgrade
|
||||
|
||||
Only **dsh-mnemon 0.5.12** is newly published. The sixteen companion plugins retain their versions. No configuration or stored-memory migration is required.
|
||||
|
||||
The Client now requires **DSH 0.1.5-rc.1 or the supported newer cohorts**: the declared range is `^0.1.5-rc.1 || ^0.1.6-alpha.2`, with RC2 and alpha.2 explicitly verified. Older hosts without the public UI Session service must keep their previously verified Mnemon release.
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add dsh-mnemon@0.5.12
|
||||
```
|
||||
|
||||
Restart DSH and reload the browser; use `headless` for that Profile. Mnemon CLI remains independently maintained.
|
||||
|
||||
### 中文说明
|
||||
|
||||
本版修复 DSH 0.1.6-alpha.2 中回合记忆条和“存入记忆”入口无法挂载的问题,同时兼容已验证的 0.1.5-rc.2。Sidebar 与设置页使用公开主会话 binding,Builtin 等显式范围界面保留各自会话和工作区权限。仅发布主包 0.5.12,十六个配套插件不变,无需迁移数据。Client 兼容下限为 DSH 0.1.5-rc.1;缺少公开 UI Session 服务的旧宿主应继续使用此前验证过的 Mnemon 版本。升级后重启 DSH 并刷新浏览器。
|
||||
|
||||
The implementation passed 1,183 root tests, actual Mnemon CLI checks, real RC2/alpha.2 WebUI operations and independent plugin composition. The [before/after evidence](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.12/docs/pr-assets/issue-261-dsh-slots/README.md) includes peer-plugin coexistence, workspace isolation and original screenshots. Models use an explicit loopback fixture; tools, storage and browser operations are real. The release workflow rechecks versioned artifacts, full Registry composition and an actual v0.4.7 upgrade before creating this Release.
|
||||
|
||||
See [English release notes](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.12/docs/en/releases/v0.5.12.md) and [中文发布说明](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.12/docs/zh-CN/releases/v0.5.12.md).
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
## v0.5.13 · Workspace, Builtin and DSH 0.1.7 Compatibility
|
||||
|
||||
- [#268](https://github.com/omdsh-dev/dsh-mnemon/pull/268) rejects Windows workspace paths below regular files before computing storage identities. Valid identities are preserved; existing storage is not moved or deleted.
|
||||
- [#269](https://github.com/omdsh-dev/dsh-mnemon/pull/269) hides only the owning conversation's width handles while Builtin memory is open. The composer remains usable, and returning to Chat restores width dragging.
|
||||
- [#270](https://github.com/omdsh-dev/dsh-mnemon/pull/270) supports DSH 0.1.7-alpha.1 live Config settings, icon exports and Session message sources, while retaining older hosts and historical Mnemon message deduplication. Profile settings keep revision checks, explicit choices and native expressions.
|
||||
|
||||
### Packages and upgrade
|
||||
|
||||
Only **dsh-mnemon advances to 0.5.13**; all sixteen companion plugins retain their versions. Compatibility evidence covers unchanged public DSH 0.1.5-rc.2, 0.1.6-alpha.2 and 0.1.7-alpha.1 packages. The Client floor remains 0.1.5-rc.1; Mnemon CLI remains independently maintained.
|
||||
|
||||
Back up the DSH profile configuration, legacy settings and relevant Mnemon data before upgrading.
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add dsh-mnemon@0.5.13
|
||||
```
|
||||
|
||||
Restart DSH and reload the browser; use `headless` for that Profile. If DSH first imports an original `settings.yaml`, Mnemon's supplemental UI/View recovery waits for the next cold Host start and can require a second complete stop/start. A browser refresh is insufficient. Recovery preserves `settings.yaml.imported` and requires the canonical `mnemon` root with the exact owning profile namespace; it does not guess custom roots or foreign suffixes.
|
||||
|
||||
Downgrades need the matching configuration backup and manual reconciliation of later changes. New settings have no automatic reverse export. Runtime, Documents and Memory Spaces data formats are unchanged.
|
||||
|
||||
### 中文说明
|
||||
|
||||
本版包含三项修复:Windows 工作区路径如果位于普通文件之下,会在计算存储标识前被拒绝,合法标识与已有存储保持不变;Builtin 记忆页仅隐藏所属对话的宽度手柄,常驻输入框仍可用,返回 Chat 后恢复拖拽;适配 DSH 0.1.7-alpha.1 的实时 Config 设置、图标与 Session 消息来源,同时保留旧宿主兼容、历史消息去重、设置修订检查、当前显式选择和原生表达式。
|
||||
|
||||
仅主包升级至 0.5.13,十六个配套插件版本不变。兼容证据覆盖未修改的公开 DSH 0.1.5-rc.2、0.1.6-alpha.2 和 0.1.7-alpha.1,Client 下限仍为 0.1.5-rc.1,Mnemon CLI 独立维护。升级前备份 Profile 配置、旧设置及相关数据,升级后重启 DSH 并刷新浏览器。首次由 DSH 导入原始 `settings.yaml` 后,Mnemon 补充 UI/View 恢复会延后到下一次冷启动,可能需要第二次完整停止并启动 Host;仅刷新页面不够。
|
||||
|
||||
恢复保留 `settings.yaml.imported` 原件,只接受标准 `mnemon` 根 Entry 与所属 Profile 的精确命名空间,不猜测自定义根或其他 Profile 的后缀。降级需要对应配置备份,并手动核对后续更改;没有自动逆向导出。Runtime、Documents 和 Memory Spaces 数据格式不变。
|
||||
|
||||
The implementation evidence covers [native Windows paths](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.13/docs/pr-assets/issue-266-workspace-ancestor/README.md), [Builtin interaction](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.13/docs/pr-assets/issue-265-builtin-width-handles/README.md), and [DSH settings, recovery and Sessions](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.13/docs/pr-assets/issue-267-settings-migration/README.md). Model responses use an explicit loopback fixture without an external model API key; tools, storage and browser operations are real. 发布证据覆盖原生 Windows 路径、Builtin 交互及 DSH 设置、恢复与 Session;模型使用本地夹具,工具、存储和浏览器操作真实执行。
|
||||
|
||||
The release workflow must verify the versioned artifacts, full Registry composition and an actual v0.4.7 upgrade before creating this Release. 发布工作流须完成版本化制品、完整 Registry 组合及 v0.4.7 真实升级检查,之后才创建此 Release。
|
||||
|
||||
See [English release notes](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.13/docs/en/releases/v0.5.13.md) and [中文发布说明](https://github.com/omdsh-dev/dsh-mnemon/blob/v0.5.13/docs/zh-CN/releases/v0.5.13.md).
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue