Compare commits
51 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
81074c99f4 | |
|
|
71dc1b574c | |
|
|
e7367d7766 | |
|
|
c8101a3e54 | |
|
|
d68840202e | |
|
|
bdea045635 | |
|
|
3d7b59b4c9 | |
|
|
0b655385af | |
|
|
891b19f809 | |
|
|
dfe31ac3f8 | |
|
|
3703a4458c | |
|
|
af42877991 | |
|
|
8f5ee01b7a | |
|
|
9fe5e495b3 | |
|
|
5fef328115 | |
|
|
89e67d05be | |
|
|
45f1ca9648 | |
|
|
22b2497e61 | |
|
|
cae5c08a80 | |
|
|
467aea49be | |
|
|
53ff5701a7 | |
|
|
a11864ff36 | |
|
|
50b90eae8a | |
|
|
4dbc09086e | |
|
|
accc1c3800 | |
|
|
8161fae848 | |
|
|
736adb4903 | |
|
|
a835074f5c | |
|
|
cde027d330 | |
|
|
1004511d25 | |
|
|
1dfc7c7380 | |
|
|
3ef7ffef6f | |
|
|
55a0e09df8 | |
|
|
dd5d58659e | |
|
|
9f5daaf266 | |
|
|
cb7bc0c19b | |
|
|
19eb15b231 | |
|
|
e1035358ab | |
|
|
0412095635 | |
|
|
8e5145349d | |
|
|
6d868abb28 | |
|
|
7d053b2fe9 | |
|
|
d2bd955aa9 | |
|
|
4123d9de9e | |
|
|
dbf39339c2 | |
|
|
881f822c69 | |
|
|
d9339a9094 | |
|
|
f64d96f5e4 | |
|
|
4579dad251 | |
|
|
ac1e415208 | |
|
|
3d23769899 |
|
|
@ -24,3 +24,14 @@ node_modules/
|
|||
# generated previews (node preview-card.mjs)
|
||||
_preview/
|
||||
preview-debug.mjs
|
||||
.codegraph/
|
||||
|
||||
# 可重新生成的输出与临时文件
|
||||
artifacts/
|
||||
.tmp-*
|
||||
|
||||
# 项目本地记忆数据(.dsh 本身仍可跟踪)
|
||||
/.dsh/brain/
|
||||
|
||||
# 测试/本地运行生成的项目记忆脚手架
|
||||
/.dsh/.gitignore
|
||||
|
|
|
|||
320
README.md
320
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,36 @@
|
|||
| --- | --- |
|
||||
| 活动上报 | 监听 `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-ui` | 左侧栏 Brain 总面板与 better-sidebar 项目记忆页签;配置页与状态/能力/配置路由。 |
|
||||
|
||||
- 停掉 `dsh-brain-cloudsync` 后活动上报与技能同步停止,但记忆读写工具
|
||||
仍可用(它们实时访问云端)。停掉 `dsh-brain-memory` 才会移除记忆工具。
|
||||
- 共享服务(设置、客户端、同步引擎)由进程级内核统一构造,关掉再开不会
|
||||
重复实例;设置持久化在 `$DSH_HOME/dsh-brain.json`(侧车文件为权威,
|
||||
插件行的 config 只作首次种子)。
|
||||
- 根导出 `.` 仍是兼容组合器:老的单行 profile 升级后行为不变。
|
||||
- 0.11.0 起第五个子插件行 id 从 `dsh-brain-settings-ui` 改为 `dsh-brain-ui`(package exports 保留 `./settings-ui` 别名指向同一入口)。若 profile 里还留有旧 id 的禁用/配置行,请到「设置 → 插件」对 `dsh-brain-ui` 重新设置;插件不会自动改写宿主配置文件。
|
||||
|
||||
## 安装
|
||||
|
||||
|
|
@ -31,18 +56,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,129 +70,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` 守卫,云端被别人先改过
|
||||
就报冲突、不强行覆盖。
|
||||
|
||||
防事故的规矩:云端交付的技能从不回传,本地改动它只报
|
||||
`locally_modified` 冲突、原样不动;本地删除不删云端,且同版本不会
|
||||
被重新拉回(云端出了新版才会再下来);同名技能两边都有时互不抢占,
|
||||
报 `name_collision`。云端只接受固定布局(根目录只有 `SKILL.md`,
|
||||
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
|
||||
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
|
||||
`unsupported_layout`,不会为了迁就而裁剪文件。
|
||||
防事故的规矩:先比内容,本地与云端逐字节一致时直接补交付记录,不传
|
||||
不覆盖;内容不同时按时间自动取较新的一边——云端 `updated_at` 更新就
|
||||
先备份本地再覆盖(备份在 `$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。
|
||||
|
||||
## 状态语义
|
||||
|
||||
|
|
@ -187,10 +249,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 位)。
|
||||
|
||||
## 开发与发布
|
||||
|
||||
|
|
@ -205,31 +276,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` 提供两侧信息,逐项「保留本地 / 采用云端 / 手动合并」。
|
||||
- **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`。
|
||||
|
|
|
|||
7617
client/index.js
7617
client/index.js
File diff suppressed because it is too large
Load Diff
|
|
@ -1,13 +1,36 @@
|
|||
# dsh-brain bundle patch
|
||||
# dsh-brain bundle patch — five toggleable sub-plugins.
|
||||
#
|
||||
# Local-only build: this package is never published, so the row below is the
|
||||
# Local-only build: this package is never published, so these rows are the
|
||||
# only way the plugin reaches the desktop profile tree. The host Loader
|
||||
# resolves the row `name` as a package from the profile node_modules.
|
||||
# resolves each row `name` as a subpath export of this package; all rows
|
||||
# load in one process and share the kernel (src/kernel.ts), so each row
|
||||
# only registers its own routes / tools / timers.
|
||||
#
|
||||
# Toggling: the host Settings → Plugins page (and dshmarket) write
|
||||
# `- id: <row> / disabled: true` lines into the profile patch, keyed by row
|
||||
# id. Settings themselves persist in $DSH_HOME/dsh-brain.json; the seed
|
||||
# config below only matters on first boot, so the rows stay safe to toggle
|
||||
# in any order.
|
||||
#
|
||||
# Do NOT copy this insert block into the profile's cordis.patch.yml —
|
||||
# duplicating entry ids breaks the Settings page. Keep overrides as
|
||||
# top-level `- id: <row>` rows only.
|
||||
#
|
||||
# The compat root export (`.`) stays for older single-row profiles: it
|
||||
# applies all five entries at once.
|
||||
- insert:
|
||||
- id: dsh-brain
|
||||
name: 'dsh-brain'
|
||||
- id: dsh-brain-cloudsync
|
||||
name: dsh-brain/cloudsync
|
||||
config:
|
||||
enabled: true
|
||||
baseUrl: https://your-memory-host/api/longmemory
|
||||
clientId: dsh-desktop
|
||||
skillsSyncEnabled: true
|
||||
- id: dsh-brain-memory
|
||||
name: dsh-brain/memory
|
||||
- id: dsh-brain-skills
|
||||
name: dsh-brain/skills
|
||||
- id: dsh-brain-mcp
|
||||
name: dsh-brain/mcp
|
||||
- id: dsh-brain-ui
|
||||
name: dsh-brain/ui
|
||||
|
|
|
|||
|
|
@ -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 19 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).
|
||||
|
|
@ -74,7 +74,7 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
|
|||
- 技能市场:无经验证来源,`features.skillsMarketplace=false`。
|
||||
- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。
|
||||
- 自动更新与版本回退:未实现(无来源清单与制品基线)。
|
||||
- MCP 市场的内嵌浏览与安装:未实现,只给宿主面板位置。
|
||||
- MCP 市场的内嵌浏览与安装:**0.9.6 起从卡片移除**(宿主 `catalog` 返回 405,只留错误条没有意义),目录浏览回到宿主插件市场。
|
||||
- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。
|
||||
- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。
|
||||
|
||||
|
|
@ -165,23 +165,24 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
|
|||
|
||||
### 6.3 同步冲突交互
|
||||
|
||||
`SkillSync` 仍然只按原策略暂停冲突项,但会暴露两侧信息并允许人工处置:
|
||||
`SkillSync` 先自动处置:内容一致直接认领,内容不同按「本地文件 mtime vs 云端 `updated_at`」自动采用较新的一边(下行覆盖前备份到 `$DSH_HOME/.dsh-brain-backups/sync/`);只有时间相同/缺失、或本地布局无法上传时才留下冲突,并暴露两侧信息允许人工处置:
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
|
||||
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
|
||||
| POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` |
|
||||
| POST | `/cloud-memory/sync/resolve-all` | `{action}`:对当前全部冲突批量 `keep_local` / `take_cloud`,返回 `{resolved[], failed[{name,error}]}` |
|
||||
|
||||
- `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。
|
||||
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.cloud-memory-backups/sync/<name>/<时间>`,再写入云端 bundle。
|
||||
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.dsh-brain-backups/sync/<name>/<时间>`,再写入云端 bundle。
|
||||
- `manual`:只返回两侧信息,不改任何文件。
|
||||
|
||||
### 6.4 验证
|
||||
|
||||
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
|
||||
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
|
||||
- `verify-sync-resolve.mjs`:12 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝)。
|
||||
- `verify-sync-resolve.mjs`:23 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝、批量成功与部分失败)。
|
||||
|
||||
## 7. P4:MCP 管理与市场(0.6.0)
|
||||
|
||||
|
|
@ -199,8 +200,8 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
|
|||
|
||||
| 区块 | 能力 |
|
||||
|---|---|
|
||||
| 我的连接 | 读取连接(名称/传输/鉴权/启用/状态/注入方式/范围/健康时间/最近错误)、健康检查、工具缓存、启停、重连、两段式移除 |
|
||||
| MCP 市场 | `catalog` 目录浏览与搜索;无认证直接 `connect`;OAuth 走浏览器授权 `connect`;bearer / api-key 通过 `configure` 填凭据(只写宿主,不回显) |
|
||||
| 我的连接 | 默认一行骨架(名称 + 状态 + 传输 + 「详情」),展开后才显示鉴权/注入/范围/健康检查/最近错误与单条操作;上方有搜索、状态筛选、多选与全选、批量健康检查/启用/停用/重连/两段式批量移除 |
|
||||
| ~~MCP 市场~~ | **0.9.6 已删除**:宿主的 `catalog` 方法在当前 dsh-mcp-connector 上返回 `HTTP 405`,内嵌面板只能显示错误条。目录浏览与安装回到宿主自己的插件市场,本卡不再渲染该区块 |
|
||||
| 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 |
|
||||
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
|
||||
| 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 |
|
||||
|
|
@ -236,7 +237,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
|
|||
| `skills/install/plan` `install/commit` | `sync_running` |
|
||||
| `skills/toggle` `skills/remove` | `sync_running` |
|
||||
| `skills/update/apply` `skills/rollback` | `sync_running` |
|
||||
| `sync/resolve` | `sync_running` |
|
||||
| `sync/resolve` `sync/resolve-all` | `sync_running` |
|
||||
|
||||
HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,117 @@
|
|||
# 验收单 · 部门接线 D1+D2(给 GPT 审查会话)
|
||||
|
||||
日期:2026-11-24
|
||||
仓库:C:\Users\qyh15\dsh-brain(分支 main)
|
||||
角色:你是独立验收者。实施者是 DeepSeek(另一会话),你只检查、不修改代码。
|
||||
依据:DEPARTMENT_HANDOFF.md(交接单)、DEPARTMENT_TASKS.md(任务卡)、DEPARTMENT_PLAN.md(边界)。
|
||||
前提:DeepSeek 已报告完成。若未报告完成,只做预检并如实标注"未完成验收"。
|
||||
|
||||
## 0. 验收纪律
|
||||
|
||||
- 一切结论以你亲自跑出的命令输出和读到的代码为准;实施者的自述只是线索。
|
||||
- 每项给 PASS / FAIL / SKIP(附证据:命令输出片段或 文件:行号)。
|
||||
- 发现问题只记录,不顺手修;FAIL 项汇总后交回用户裁决。
|
||||
- 不 push、不打 tag、不改任何源码;允许写临时脚本到系统 temp 目录。
|
||||
|
||||
## 1. 基线与范围核对(先做)
|
||||
|
||||
| # | 检查 | 方法 | 通过标准 |
|
||||
| --- | --- | --- | --- |
|
||||
| A1 | 起点基线 | git log --oneline v0.10.1..HEAD | 首个新增 commit 为 docs/plans 交接文档(规划侧),其后 5 个左右对应 D1a/D1b/D2a/D2b/V |
|
||||
| A2 | 库层零改动 | git diff v0.10.1..HEAD -- src/local-memory/departments/ | **输出必须为空**;非空即 FAIL(硬约束) |
|
||||
| A3 | 范围不越界 | git diff --stat v0.10.1..HEAD | 改动应限于:src/kernel.ts、src/routes.ts、src/settings-ui/(新路由文件)、src/memory/departments-tools.ts(新)、src/entries/memory.ts、lib/ 对应产物、verify-departments-wiring.mjs(新)、package.json 若有 scripts 增补。出现 cloud-sync/src/local-memory 其他子目录改动 → 逐条质询 |
|
||||
| A4 | 无新依赖 | git diff v0.10.1..HEAD -- package.json pnpm-lock.yaml | dependencies/devDependencies 无新增;lockfile 不应大变 |
|
||||
| A5 | 工作树状态 | git status --porcelain | 干净(全部已提交);脏则记录未提交内容 |
|
||||
|
||||
## 2. 门禁命令(亲自重跑,不采信报告)
|
||||
|
||||
npm run typecheck
|
||||
npm run build
|
||||
node verify-departments.mjs # 原库层 21 项必须仍全绿(实测口径)
|
||||
node scripts/verify-all.mjs # 口径:38 过 + 2 环境跳过 + 新增 wiring 全绿;exit 0
|
||||
node verify-plugin-entry.mjs # 入口形状不变
|
||||
|
||||
| # | 通过标准 |
|
||||
| --- | --- |
|
||||
| B1 | typecheck exit 0 |
|
||||
| B2 | build exit 0,且 build 后 git status 仍干净(lib 产物已随卡提交,重建无 diff)|
|
||||
| B3 | verify-departments 21 PASS 0 FAIL |
|
||||
| B4 | verify-all exit 0;对比基线口径,原有脚本无一转 FAIL;wiring 脚本 0 SKIP |
|
||||
| B5 | verify-plugin-entry 全绿 |
|
||||
|
||||
注意:verify-all 的 SKIP 判定是输出行 /^SKIP/;环境性跳过只允许出现在原有 2 个脚本。
|
||||
|
||||
## 3. 代码审查要点(读 diff,对照任务卡)
|
||||
|
||||
| # | 检查 | 位置 | 通过标准 |
|
||||
| --- | --- | --- | --- |
|
||||
| C1 | kernel 构造共享实例 | src/kernel.ts | DepartmentManager({ memory: this.localMemory }),同一实例;routeDeps() 暴露 departments |
|
||||
| C2 | 路由归属与别名 | src/routes.ts | ROUTES.departments='/dsh-brain/departments';挂在 createCoreRoutes(settings-ui bundle);legacy 别名自动派生 |
|
||||
| C3 | 写门禁 | 新路由 handler | 每个 POST 先 sameOrigin(req)(src/http.ts),跨源 403 origin-rejected;GET 不设写闸但 405 拒非 GET |
|
||||
| C4 | 错误码映射 | 新路由 handler | 库层错误 message 精确映射:revision_conflict→409、department_not_found→404、department_disabled/secret_not_allowed/department_required_field/department_invalid_host→400 或 409(按任务卡表);未知错误 500 且不泄栈 |
|
||||
| C5 | 开关语义 | 路由 + 工具 | localMemoryEnabled=false → 路由 503、工具抛中文禁用错误;departments 未构造 → 503 departments-unavailable |
|
||||
| C6 | 工具手写定义 | src/memory/departments-tools.ts | 6 个工具名齐全(department_create/list/remember/recall/checkpoint/resume);无 import @deepseek-ai/dsh-tools;execute 抛错契约 |
|
||||
| C7 | recall 预算(2026-11-24 修订) | 工具 + 路由 | k clamp 1..5 默认 5;**工具 content ≤600 含省略号**;路由允许全文但必须带 contentSnippet ≤600(共用同一 snippet 实现);hits 带 origin |
|
||||
| C8 | workspace 绑定(2026-11-24 修订) | 工具 + 路由 | 不仅解析 deps.workspace(exec),还必须经 localMemory.withWorkspace 包裹**全部六个操作**(create/list/remember/recall/checkpoint/resume);双工作区探针:同名 project 部门各自 created=true、ID 不同、私有记忆互不可见 |
|
||||
| C9 | entry 注册生命周期 | src/entries/memory.ts | 注册在 ctx.inject(['tools']) 内、经 toolsCtx.effect;随 memory bundle 卸载;未动 systemPrompt 段与自动总结监听器 |
|
||||
| C10 | 私有空间不上云 | 全 diff | 无任何把 department 空间接入 cloud-sync/reporter 的改动 |
|
||||
| C11 | resume/attach 语义 | 工具 + 路由 | 给 hostSessionId 走 attachSession,否则 resumeSession;返回 reusable 引用 |
|
||||
| C12 | revision 透传 | update/disable/checkpoint | expectedRevision 可选参数原样传库层,不在接线层吞掉 |
|
||||
|
||||
## 4. 行为抽查(独立探针,不复用实施者的测试)
|
||||
|
||||
写一个临时探针脚本(系统 temp 目录,import 仓库 lib/),至少覆盖:
|
||||
|
||||
1. 闭环:create → remember → recall(query 命中, origin='department') → checkpoint → resume(reusable=true)。
|
||||
2. 幂等:同名同 scope 二次 create 返回 created=false 且 id 不变。
|
||||
3. 隔离:部门 A remember 的内容,部门 B recall 不命中(私有空间语义)。
|
||||
4. 禁用:disable 后 remember 抛 department_disabled;数据文件仍在磁盘。
|
||||
5. 秘密拒收:remember 含 API key 样式内容抛 secret_not_allowed。
|
||||
6. HTTP:起真实 server 挂 createCoreRoutes(kernel.routeDeps())(手法参考 verify-brain-panel.mjs):
|
||||
- GET /dsh-brain/departments/list → 200
|
||||
- POST /dsh-brain/departments/create 带跨源 Origin → 403
|
||||
- 同源 POST 缺 name → 400;正常 → 200
|
||||
- expectedRevision 过期 → 409
|
||||
- GET /cloud-memory/departments/list(legacy)→ 200
|
||||
7. 上下文预算:recall k=99 实际返回 ≤5 条。
|
||||
|
||||
| # | 通过标准 |
|
||||
| --- | --- |
|
||||
| D1–D7 | 上述 7 组探针全部符合预期;任何一组失败即 FAIL 并附输出 |
|
||||
|
||||
## 5. 发布件一致性
|
||||
|
||||
npm pack --dry-run
|
||||
|
||||
| # | 通过标准 |
|
||||
| --- | --- |
|
||||
| E1 | files 清单仍只含 lib/client/cordis.patch.yml/README/LICENSE 系;verify-*.mjs、tests/、docs/plans 不进包 |
|
||||
| E2 | 包内 lib/memory/departments-tools.js 存在(新工具随包发布)|
|
||||
|
||||
## 6. 裁决与回报格式
|
||||
|
||||
- 全 PASS → 结论"验收通过,D1+D2 最小可用闭环成立",建议用户打 tag(如 v0.10.2-dept.1,由用户定)。
|
||||
- 有 FAIL → 逐条列出:编号 / 证据(输出或 文件:行号)/ 影响 / 建议修复方向(不实施)。
|
||||
- 有偏离任务卡但合理的决定 → 单列"偏离清单",交用户追认。
|
||||
- 回报末尾附:你亲自跑过的命令清单 + 各自 exit code。
|
||||
|
||||
## 7. 明确不在本次验收范围
|
||||
|
||||
D3 宿主会话挂钩、D4 设置页页签、云同步、部门协作编排——发现"没做"不算缺陷。
|
||||
|
||||
|
||||
## 8. 复验口径(2026-11-24,FAIL 修复后)
|
||||
|
||||
- 首轮验收 FAIL:C7(片段 601/715 超预算)、C8(项目部门未按调用工作区隔离)、A5(skill-sync.ts 在途改动混树)。
|
||||
- 修复单:docs/plans/DEPARTMENT_FIX.md(DeepSeek 执行,两 commit)。
|
||||
- 复验范围:C7/C8 新断言 + A5 干净树 + verify-all 口径不回退;其余 PASS 项不重跑,除非修复 diff 触及。
|
||||
- **复验基线(2026-11-24 23:25 规划侧预检)**:修复已入库并推送,HEAD `45f1ca9`。
|
||||
三个修复 commit:`cae5c08`(skill-sync 冲突绑定确认快照,含 19 项 conflict-round5 全绿)、
|
||||
`22b2497`(C8 工作区绑定)、`45f1ca9`(C7 省略号计入预算)。
|
||||
规划侧亲跑:typecheck exit 0;verify-all 39 脚本全绿;wiring **25 项**全 PASS(原 18+新 7);
|
||||
departments 21 项全 PASS;工作树干净。
|
||||
实现要点供复核:工具面 inDepartmentWorkspace 助手包裹六操作;路由面 withWorkspace 9 处;
|
||||
departmentSnippet 导出共享(slice(0,limit-1)+'…');路由 /recall 返回 content 全文 + contentSnippet 双字段。
|
||||
GPT 复验请独立重跑 C7/C8 探针(双工作区隔离 + 600 预算),并抽查 cae5c08 是否满足
|
||||
"提交前修复任务" P1 的 5 条验收用例(该线属技能同步,不在部门验收范围,但同批交付建议顺带核)。
|
||||
- npm 不在 PATH 时用 bundled node + pnpm 等价命令,记 PASS(等价)而非 SKIP。
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
# D1+D2 验收 FAIL 项修复单(给 DeepSeek)
|
||||
|
||||
日期:2026-11-24
|
||||
依据:GPT 独立验收报告(基线 accc1c3)。规划侧已逐项对照源码复核,两个 FAIL 均属实。
|
||||
基线注意(2026-11-24 21:55 溯源定案):工作树的 src/skill-sync.ts 未提交改动
|
||||
**已查明是 DeepSeek 会话(8adf7c86)自己的在途工作**——第五/六轮修复任务与
|
||||
"提交前修复任务"(P1 技能冲突按用户确认版本执行)期间,turn 9–14 共 23 次
|
||||
run_code 直写该文件(08:38–12:22 UTC),最后一次 seq5642 在 12:22:54Z。
|
||||
它不是旧项目残留,也不是 GPT 验收所改(GPT 全程只读+临时副本)。
|
||||
**处置:该改动属于另一条任务线(技能冲突确认),与部门修复无关。
|
||||
DeepSeek 修部门 FAIL 前,先把 skill-sync.ts 的在途改动按原任务收尾单独提交
|
||||
(或经用户同意 stash),部门修复 commit 不得混入它。**
|
||||
注意:该在途 diff 的方向与"提交前修复任务"要求相反(移除了 confirmed 快照守卫、
|
||||
改用新鲜云端列表),收尾提交前须按原任务验收用例复核,不能直接当成品提交。
|
||||
|
||||
## FAIL-1(C8)· 项目部门未按调用工作区隔离【严重,先修】
|
||||
|
||||
现象:同一进程内,工作区 A、B 分别创建同名 project 部门,B 得到 created=false
|
||||
和 A 的 ID——B 的部门建到了 A 的项目注册表里。
|
||||
|
||||
根因(已核实):
|
||||
- DepartmentManager.root(scope) 读 this.memory.projectRoot(manager.ts:36 附近),
|
||||
而 projectRoot 取 AsyncLocalStorage 的 workspaceContext,缺省回落 process.cwd()。
|
||||
- LocalMemoryManager 已有现成绑定机制:withWorkspace(workspace, job)(manager.ts:94)。
|
||||
- memory/tools.ts 的五个工具把 workspace 作为参数传给 remote(remote 内部绑定);
|
||||
但 departments-tools.ts 只有 recall 传了 workspace 参数,create/list/remember/
|
||||
checkpoint/resume 都没绑定,且 DepartmentManager 公开方法除 recall 外不收 workspace。
|
||||
|
||||
修法(库层零改动约束下,接线层绑定):
|
||||
1. DepartmentToolDeps 增加 memory: () => LocalMemoryManager(kernel.departmentToolDeps()
|
||||
补返回 this.localMemory)。
|
||||
2. 六个工具的 execute 统一包一层:
|
||||
const ws = deps.workspace(exec)
|
||||
return deps.memory().withWorkspace(ws, async () => { …原逻辑… })
|
||||
recall 保留现有 workspace 参数传递(双保险,库层 recall 自己也会用)。
|
||||
3. HTTP 路由侧:departments-routes.ts 的每个分支同样用
|
||||
deps.localMemory.withWorkspace(workspace, …) 包裹;workspace 来源:
|
||||
- 工具面:exec 上下文(已有)。
|
||||
- HTTP 面:query/body 的 workspace 参数(recall 已支持,扩展到 create/list/
|
||||
remember/checkpoint/resume/update/disable);缺省时回落 process.cwd() 语义不变。
|
||||
RouteDeps 已含 localMemory,无需新增依赖面。
|
||||
4. 不改 src/local-memory/departments/ 任何字节(A2 红线)。
|
||||
|
||||
验证(新增断言进 verify-departments-wiring.mjs):
|
||||
- 同进程双工作区:withWorkspace(A) create 'X' → withWorkspace(B) create 'X'
|
||||
必须 created=true 且 ID 不同;B recall 不见 A 的私有记忆。
|
||||
- 工具面模拟 exec={workspace:B} 调 department_create,注册表落 B 的
|
||||
.dsh/brain/departments/registry.json(mkdtemp 双项目夹具)。
|
||||
- 原 18 项 wiring + 21 项库层保持全绿。
|
||||
|
||||
commit:fix(departments): bind caller workspace around every department operation
|
||||
|
||||
## FAIL-2(C7)· 召回片段超 600 字符预算【轻,后修】
|
||||
|
||||
现象:工具 snippet 截 600 后追加 '…' 实长 601;HTTP /recall 直接返回完整
|
||||
record.content(实测 715)。
|
||||
|
||||
裁定(规划侧统一口径,消除任务卡与验收单的矛盾):
|
||||
- **agent 工具面**:snippet 总长 ≤600 **含省略号**——改 slice(0, limit-1) + '…'。
|
||||
- **HTTP 管理路由**:/recall 是同源管理页消费,允许全文(任务卡 D1b 原口径),
|
||||
但为防误用也加投影:默认返回 content 全文 + contentSnippet(≤600 含省略号)双字段;
|
||||
验收断言改为"snippet 字段 ≤600"。若 GPT 复验坚持路由也限 600,则路由直接复用
|
||||
同一 snippet 函数返回短片段——两种都合规,实施者选前者(管理页需要全文编辑)。
|
||||
- 共用一个 snippet 实现:从 departments-tools.ts 导出或挪到共享 util,
|
||||
路由 import 同一函数,杜绝两处漂移。
|
||||
|
||||
验证:wiring 脚本加断言——构造 700 字符记忆,工具返回 content.length ≤600;
|
||||
路由返回 contentSnippet.length ≤600。
|
||||
|
||||
commit:fix(departments): count ellipsis inside the 600-char recall budget
|
||||
|
||||
## 执行顺序与门禁
|
||||
|
||||
1. 先处置 skill-sync.ts 在途改动(问用户),保证干净起点。
|
||||
2. FAIL-1 → FAIL-2 各一 commit,每 commit 前跑:
|
||||
typecheck + build + verify-departments(21) + verify-departments-wiring(18+新断言)。
|
||||
3. 终验:verify-all 全绿(39+ 脚本口径不回退)。
|
||||
4. 完成后 push,通知用户转 GPT 复验(复验范围:C7/C8 + 新断言 + A5 干净树;
|
||||
其余 PASS 项不重跑,除非 diff 触及)。
|
||||
|
||||
## 给 GPT 复验的口径更新
|
||||
|
||||
- C7 通过标准修订:工具 content ≤600 含省略号;路由 contentSnippet ≤600(全文字段允许)。
|
||||
- C8 通过标准:双工作区 create 各自 created=true、ID 不同、私有记忆互不可见;
|
||||
工具与 HTTP 两面都要探。
|
||||
- A5:交付提交必须干净树;skill-sync 改动若属另一任务,单独 commit 不混入。
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
# 执行交接单 · 部门接线 D1+D2(给 DeepSeek 实施会话)
|
||||
|
||||
日期:2026-11-24
|
||||
仓库:C:\Users\qyh15\dsh-brain(分支 main,基线 tag v0.10.1 / commit 1dfc7c7)
|
||||
角色:你是实施者。本单 + DEPARTMENT_TASKS.md 是你的全部任务来源;规划会话不参与实施。
|
||||
|
||||
## 任务一句话
|
||||
|
||||
把已验收的部门库层(src/local-memory/departments/,21 项验证全绿)接上用户面:
|
||||
kernel 构造 + 管理路由(D1)+ 6 个 department_* agent 工具(D2),并新增 wiring 验收。
|
||||
完成标志:V 卡终验命令全绿。预计一天内。
|
||||
|
||||
## 开工前核对(5 分钟)
|
||||
|
||||
1. git status 干净、git log -1 为 docs/plans 交接文档 commit 或其后继(基线 v0.10.1 + 规划文档);若工作树脏,停下报告,不要混提交。
|
||||
注:node 不在系统 PATH 时用宿主自带 node.exe(DeepSeek Harness resources/runtime/.../node/bin/node.exe),npm 同理。
|
||||
2. 读 docs/plans/DEPARTMENT_TASKS.md 全文——每卡的改动文件、签名、错误码、验证命令都在里面。
|
||||
3. 背景按需查:DEPARTMENT_PLAN.md(概念与边界)、NEXT_PHASE_PLAN.md §4.5(阶段位置)。
|
||||
4. node verify-departments.mjs 先跑一遍确认 21 项全绿(你的起点基线;原稿误记 26,已修订)。
|
||||
|
||||
## 执行顺序
|
||||
|
||||
D1a(kernel 构造)→ ┬ D1b(管理路由)┐
|
||||
└ D2a(工具工厂)→ D2b(entry 注册)┴→ V(wiring 验收)
|
||||
|
||||
D1b 与 D2a 可并行。每卡独立 commit,commit 主题按任务卡给定文案。
|
||||
|
||||
## 硬约束(违反即返工)
|
||||
|
||||
- src/local-memory/departments/ 库层零改动;只消费其公开 API。
|
||||
- 不引新依赖;工具手写 ToolDefinition(禁 import @deepseek-ai/dsh-tools,原因见 memory/tools.ts 头注释)。
|
||||
- 不动 cloud-sync;部门私有空间不上云。
|
||||
- 不做 D3(宿主会话挂钩)、D4(设置页页签)——超出本轮范围。
|
||||
- recall k 上限 5 硬 clamp;POST 路由必须过 sameOrigin 闸门。
|
||||
- lib/ 构建产物随卡提交(仓库约定 lib 入库);每卡 commit 前跑该卡验证命令。
|
||||
|
||||
## 终验(全部通过才报完成)
|
||||
|
||||
npm run typecheck && npm run build
|
||||
node scripts/verify-all.mjs # 原 38 过 + 2 环境跳过口径不变,新增 wiring 全绿
|
||||
node verify-plugin-entry.mjs
|
||||
|
||||
## 验收
|
||||
|
||||
完成后由独立 GPT 审查会话按 docs/plans/DEPARTMENT_ACCEPTANCE.md 验收(A/B/C/D/E 五组检查)。
|
||||
实施者不得自验代替独立验收。
|
||||
|
||||
## 交付物
|
||||
|
||||
1. 5 个 commit(D1a/D1b/D2a/D2b/V),push 与否听用户指示。
|
||||
2. 回报格式:每卡 commit hash + 验证结果摘要;如有偏离任务卡的决定,逐条列出原因。
|
||||
3. 遇到任务卡与代码现状不符(基线漂移):停下,报告差异,等规划侧修订,不要自行改方案。
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
# 部门(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 21 项全绿(2026-11-24 实测复核,原稿误记 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)
|
||||
|
||||
D1/D2 已拆为可执行任务卡:docs/plans/DEPARTMENT_TASKS.md(D1a/D1b/D2a/D2b/V,含改动文件、签名、错误码、验证命令)。
|
||||
|
||||
库层只有 ./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 21 项保持全绿
|
||||
- 新增 verify-departments-wiring.mjs:工具注册 / 路由鉴权 /
|
||||
开关行为 / 会话恢复 / 禁用后工具拒绝
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
# 复验单 · 部门接线 D1+D2 FAIL 修复(给 GPT)
|
||||
|
||||
日期:2026-11-24
|
||||
仓库:C:\Users\qyh15\dsh-brain(main,已推送)
|
||||
角色:独立复验者。只检查、不修改源码、不 commit/push/tag。
|
||||
前情:首轮验收(基线 accc1c3)FAIL 三项:C7 片段超预算、C8 项目部门未按工作区隔离、A5 混树。
|
||||
DeepSeek 已修复,规划侧预检全绿。本次是**复验**,不是全量重验。
|
||||
|
||||
## 0. 基线与范围
|
||||
|
||||
- 复验基线:`45f1ca9`(fix(departments): count ellipsis inside the 600-char recall budget)。
|
||||
- 三个修复 commit(v0.10.1 之后、本轮审查对象):
|
||||
| commit | 内容 |
|
||||
| --- | --- |
|
||||
| cae5c08 | fix(skill-sync): bind conflict resolution to the confirmed preview snapshot |
|
||||
| 22b2497 | fix(departments): bind caller workspace around every department operation |
|
||||
| 45f1ca9 | fix(departments): count ellipsis inside the 600-char recall budget |
|
||||
- 注意:HEAD 可能已前进(UI 规划文档 commit 89e67d0/5fef328/9fe5e49 等,纯 docs/plans)。
|
||||
审查 diff 用 `git diff accc1c3..45f1ca9`;若 HEAD 更新,确认新增仅 docs/plans 或 UI 施工
|
||||
(src-client/ 等),UI 施工不在本次复验范围。
|
||||
- 环境:npm/node 不在 PATH 时用 bundled node + pnpm 等价命令,记 PASS(等价):
|
||||
node: C:/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/node/bin/node.exe
|
||||
或 C:/Users/qyh15/AppData/Local/Programs/DeepSeek Harness/resources/runtime/primary-runtime/dependencies/node/bin/node.exe
|
||||
pnpm: C:/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/pnpm/bin/pnpm.mjs
|
||||
|
||||
## 1. 门禁(亲自重跑)
|
||||
|
||||
git status --porcelain # A5:必须干净(UI 施工在途则记录并区分归属)
|
||||
pnpm run typecheck # B1
|
||||
pnpm run build # B2:build 后 git status 仍干净(lib 已入库)
|
||||
node verify-departments.mjs # B3:21 项全 PASS
|
||||
node scripts/verify-all.mjs # B4:39 脚本全绿(1 环境跳过),exit 0
|
||||
node verify-departments-wiring.mjs # 25 项全 PASS(原 18 + 新 7),0 SKIP
|
||||
node verify-skill-sync-conflict-round5.mjs # cae5c08 配套:19 项全 PASS
|
||||
|
||||
## 2. C8 复验(工作区隔离)——独立探针,不复用实施者测试
|
||||
|
||||
写临时探针(系统 temp,import 仓库 lib/),至少断言:
|
||||
1. 同一进程、两个 mkdtemp 工作区 A/B:
|
||||
withWorkspace(A) 内 create({name:'X',scope:'project'}) → created=true, idA;
|
||||
withWorkspace(B) 内同名 create → **created=true, idB ≠ idA**(首轮 FAIL 点:B 曾拿到 A 的 id)。
|
||||
2. A 内 remember 私有内容,B 内 recall 同 query → 0 命中。
|
||||
3. 工具面:createDepartmentTools(deps) 的 department_create.execute(args, {workspace:B})
|
||||
→ 注册表落 B 的 .dsh/brain/departments/registry.json(检查磁盘路径)。
|
||||
4. HTTP 面:起真实 server 挂 createCoreRoutes(kernel.routeDeps()),
|
||||
POST /departments/create?workspace=A 与 body workspace=B 分别建同名部门 → 两个 id。
|
||||
5. 六操作全覆盖抽查:list/remember/recall/checkpoint/resume 在 withWorkspace(B) 下
|
||||
不读不写 A 的目录(recall 已有 workspace 参数,其余靠包裹)。
|
||||
代码核对点:src/memory/departments-tools.ts 的 inDepartmentWorkspace 助手是否包裹全部六个
|
||||
execute;src/settings-ui/departments-routes.ts 各分支 withWorkspace(9 处);
|
||||
kernel.departmentToolDeps() 是否暴露 memory 访问器。库层 src/local-memory/departments/ 必须零改动
|
||||
(git diff accc1c3..45f1ca9 -- src/local-memory/departments/ 为空)。
|
||||
|
||||
## 3. C7 复验(600 字符预算)
|
||||
|
||||
1. 构造 700 字符记忆 → department_recall 工具返回 content.length **≤600**(省略号计入)。
|
||||
2. HTTP GET /departments/recall → hits[].contentSnippet.length ≤600;content 全文字段允许存在
|
||||
(管理页消费,裁定口径见 DEPARTMENT_ACCEPTANCE.md §8)。
|
||||
3. departmentSnippet 为共享导出(departments-tools.ts export,路由 import 同一函数),
|
||||
实现 slice(0, limit-1)+'…'。
|
||||
4. k=99 仍 clamp 到 5(回归确认)。
|
||||
|
||||
## 4. cae5c08 顺带核(技能冲突线,非部门验收范围)
|
||||
|
||||
对照"提交前修复任务"P1 的 5 条验收用例(verify-skill-sync-conflict-round5.mjs 已扩到 19 项):
|
||||
1. 有效确认 keep_local/take_cloud 跑通,断言实际远端调用/磁盘/回执;
|
||||
2. 确认后远端变化 → 条件写入拒绝,expected_revision 仍是预览值;
|
||||
3. 下载包完整但 revision/manifest 不同 → 过期,本地不动;
|
||||
4. 确认后本地变化 → 不上传不覆盖;
|
||||
5. 批量混合有效+过期 → 只有有效条目写入。
|
||||
读 diff 确认 previews Map 快照机制方向正确(绑定用户确认的预览,而非新鲜列表)。
|
||||
此项结论单列,不影响部门复验裁决。
|
||||
|
||||
## 5. 裁决与回报
|
||||
|
||||
- 全 PASS → "复验通过,D1+D2 最小可用闭环成立",建议用户打 tag(如 v0.10.2-dept.1,用户定)。
|
||||
- 有 FAIL → 编号/证据(输出或 文件:行号)/影响/修复方向(不实施)。
|
||||
- 回报末尾附亲自跑过的命令清单 + exit code。
|
||||
- 首轮已 PASS 的 A1–A4/B5/C1–C6/C9–C12/D1–D7/E1–E2 不重跑,除非修复 diff 触及对应文件。
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
# P1.5 · 部门接线 D1/D2 可执行任务卡
|
||||
|
||||
版本:v1(规划稿;实施会话照卡执行,本会话只维护规划)
|
||||
日期:2026-11-24
|
||||
基线:v0.10.1(commit 1dfc7c7)+ docs/plans 交接文档 commit(见 HANDOFF 开工核对)。上游方案:DEPARTMENT_PLAN.md、NEXT_PHASE_PLAN.md §4.5。
|
||||
所有行号/签名以 2026-11-24 对 src/ 的实测为准;执行前若基线变动先重新核对。
|
||||
|
||||
## 总览
|
||||
|
||||
| 卡 | 内容 | 依赖 | 预估 |
|
||||
| --- | --- | --- | --- |
|
||||
| D1a | kernel 构造 DepartmentManager + routeDeps 暴露 | 无 | 0.5h |
|
||||
| D1b | /dsh-brain/departments 管理路由(settings-ui bundle) | D1a | 2–3h |
|
||||
| D2a | department_* 工具工厂(6 个工具) | D1a | 2–3h |
|
||||
| D2b | memory entry 注册工具 + 开关语义 | D2a | 0.5h |
|
||||
| V | verify-departments-wiring.mjs 新增验收 | D1b+D2b | 1–2h |
|
||||
|
||||
D1a→D1b 与 D1a→D2a 两条链可并行。每卡独立 commit;全部完成后跑 V 卡终验。
|
||||
D3(宿主会话挂钩)、D4(设置页页签)不在本轮,见 DEPARTMENT_PLAN §4。
|
||||
|
||||
---
|
||||
|
||||
## D1a · kernel 构造 DepartmentManager
|
||||
|
||||
改动文件:src/kernel.ts(现 324 行)
|
||||
|
||||
1. import 增加 DepartmentManager:现有行
|
||||
`import { LocalMemoryManager, LocalMemoryRemote } from './local-memory/index.ts'`
|
||||
改为同时导入 DepartmentManager(index.ts 已导出,无需动 local-memory)。
|
||||
2. BrainKernel 类字段区(readonly localMemoryRemote 之后)加:
|
||||
`readonly departments: DepartmentManager`
|
||||
3. constructor 中 `this.localMemoryRemote = new LocalMemoryRemote(this.localMemory)`
|
||||
之后加:`this.departments = new DepartmentManager({ memory: this.localMemory })`
|
||||
——共享同一 LocalMemoryManager 实例(库层约定,见 verify-departments.mjs 用法)。
|
||||
不做 ensureGlobal 之类的额外初始化:部门私有空间由 create 时懒建。
|
||||
4. routeDeps() 返回对象(现有 localMemory: this.localMemory 之后)加:
|
||||
`departments: this.departments,`
|
||||
5. src/routes.ts 的 RouteDeps 接口加可选字段:
|
||||
`/** Department registry (P1.5), when wired in. */ departments?: DepartmentManager`
|
||||
(import type 自 ./local-memory/index.ts)。
|
||||
|
||||
开关语义:DepartmentManager 构造无副作用,常建即可;
|
||||
localMemoryEnabled=false 的拒绝发生在路由/工具层(D1b/D2a),不在构造层。
|
||||
|
||||
验证:npm run typecheck && npm run build;node verify-departments.mjs 保持 21 项全绿。
|
||||
commit:feat(departments): construct DepartmentManager in the shared kernel
|
||||
|
||||
## D1b · /dsh-brain/departments 管理路由
|
||||
|
||||
改动文件:src/routes.ts(ROUTES 表 + createCoreRoutes)、
|
||||
新文件 src/settings-ui/departments-routes.ts(或并入 routes.ts 的 serveDepartments,二选一,建议独立文件对齐 settings-ui/routes.ts 风格)。
|
||||
|
||||
路由归属:settings-ui bundle(createCoreRoutes 已被 settings-ui entry 注册,
|
||||
legacy /cloud-memory 别名自动跟随,无需另接)。
|
||||
|
||||
1. ROUTES 表加 `departments: '/dsh-brain/departments'`。
|
||||
2. createCoreRoutes 数组加一项:
|
||||
`{ kind: 'prefix', path: ROUTES.departments, handler: (req,res) => serveDepartments(deps, req, res) }`
|
||||
3. serveDepartments 完全仿照 serveLocalMemory 的既有模式:
|
||||
- deps.departments === undefined → 503 'departments-unavailable'
|
||||
- suffix 解析用 marker '/departments'(同 serveLocalMemory 的 markerAt 写法)
|
||||
- 子路由与方法:
|
||||
|
||||
| suffix | 方法 | 行为 | 错误码 |
|
||||
| --- | --- | --- | --- |
|
||||
| '' 或 '/' 或 '/list' | GET | list(scope?),scope 取 query(global/project) | 405 |
|
||||
| '/create' | POST | create(input);name 必填 trim 非空 | 400 name-required / 403 origin-rejected |
|
||||
| '/update' | POST | update(id, patch, expectedRevision?) | 400 id-required / 409 revision-conflict(库层抛错映射) |
|
||||
| '/disable' | POST | disable(id, expectedRevision?) | 同上 |
|
||||
| '/checkpoint' | POST | checkpoint(id, {currentTask?, handoff?}, expectedRevision?) | 同上 |
|
||||
| '/recall' | GET | recall(id, query, k?, workspace?);k clamp 1..5(默认 5) | 400 id-required |
|
||||
| '/resume' | POST | resumeSession(id, host?);attach 语义(hostSessionId)同 POST 传入 | 400 id-required |
|
||||
|
||||
- 所有 POST:sameOrigin(req) 闸门(复用 src/http.ts 现有函数)→ readBody → JSON.parse
|
||||
→ 对象校验,失败 400 invalid-json / invalid-body(照抄 serveLocalMemory '/forget' 段)。
|
||||
- localMemoryEnabled=false 时统一 503 'local-memory-disabled'(读 settings 判定,
|
||||
与工具层口径一致)。
|
||||
- 库层错误消息(如 revision 冲突、department-not-found、disabled)用 try/catch 映射:
|
||||
已知 message → 409/404/400;未知 → 500,不泄内部栈。
|
||||
4. 响应投影:Department 对象直接 JSON 化即可(role 上限 12000 字符仅存储用,
|
||||
管理路由是同源页面消费,允许全文;agent 工具侧才做精简投影,见 D2a)。
|
||||
|
||||
验证:typecheck + build;手工 curl 或 V 卡脚本覆盖:GET list 200、POST create 同源 200/
|
||||
跨源 403、缺 name 400、revision 过期 409、禁用后 503。
|
||||
commit:feat(departments): management routes under the settings-ui bundle
|
||||
|
||||
## D2a · department_* 工具工厂
|
||||
|
||||
新文件:src/memory/departments-tools.ts(对齐 memory/tools.ts 的手写 ToolDefinition 风格,
|
||||
不用 defineTool——该文件头注释已说明双模块实例风险,遵守)。
|
||||
|
||||
导出:`export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionLike[]`
|
||||
|
||||
DepartmentToolDeps 接口(kernel.toolDeps() 扩展或独立工厂均可,建议独立):
|
||||
```ts
|
||||
interface DepartmentToolDeps {
|
||||
departments: () => DepartmentManager
|
||||
settings: () => { localMemoryEnabled: boolean; memoryEnabled: boolean }
|
||||
workspace: (exec?: unknown) => string | undefined
|
||||
}
|
||||
```
|
||||
kernel.ts 加 departmentToolDeps() 方法返回上述形状(departments: () => this.departments)。
|
||||
|
||||
六个工具(名字即 agent 面 API,描述必须声明私有空间语义):
|
||||
|
||||
| 工具 | 参数(JSON Schema) | 行为 |
|
||||
| --- | --- | --- |
|
||||
| department_create | name*, role?, scope?(global/project), skills?[], allowedTools?[], readGlobal?, readProject? | create;返回 {id,name,scope,created};重名幂等不覆盖 |
|
||||
| department_list | scope? | list;返回精简视图 {id,name,scope,active,currentTask?,revision}(不含 role 全文) |
|
||||
| department_remember | departmentId*, content*, category?, tags?[] | remember;返回 {id,duplicate};秘密拒收错误原样透传 |
|
||||
| department_recall | departmentId*, query*, k?(1..5 默认 5) | recall(id,query,k,workspace(exec));返回 hits[{origin,content snippet≤600,id}](复用 memory/tools.ts 的 snippet 手法) |
|
||||
| department_checkpoint | departmentId*, currentTask?, handoff?, expectedRevision? | checkpoint;返回 {revision,updatedAt} |
|
||||
| department_resume | departmentId*, host?, hostSessionId? | resumeSession 或 attachSession(给了 hostSessionId 走 attach);返回 sessionRef |
|
||||
|
||||
共同契约(照抄 memory/tools.ts 既有约定):
|
||||
- execute 抛错 → 宿主转 isError:true;错误消息中文可行动(参照 requireMemoryToken 文案风格)。
|
||||
- 前置检查:memoryEnabled=false 或 localMemoryEnabled=false → 抛
|
||||
'部门功能当前已禁用…请在 /dsh-brain 页面开启';部门 active=false → 库层已拒绝,透传。
|
||||
- 输出统一 renderJson(从 memory/tools.ts 导出复用,已是 export)。
|
||||
- workspace 解析:execute(args, exec) 的 exec 经 deps.workspace(exec)(kernel 已有
|
||||
workspaceFromExec,勿重造)。
|
||||
- recall 的 k 上限 5 硬 clamp,防上下文膨胀(DEPARTMENT_PLAN §5 边界)。
|
||||
|
||||
验证:typecheck + build;V 卡覆盖工具行为。
|
||||
commit:feat(departments): six department_* agent tools
|
||||
|
||||
## D2b · memory entry 注册
|
||||
|
||||
改动文件:src/entries/memory.ts(现 134 行)
|
||||
|
||||
在现有 createMemoryTools 注册循环之后(同一 ctx.inject(['tools']) 回调内)加:
|
||||
```ts
|
||||
for (const tool of createDepartmentTools(kernel.departmentToolDeps())) {
|
||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool \${tool.name}`)
|
||||
}
|
||||
```
|
||||
(模板字符串反引号按正常 TS 写,此处为文档转义。)
|
||||
|
||||
要点:
|
||||
- 工具随 memory bundle 开关整体注册/卸载——与五个 memory_* 工具同生命周期,
|
||||
不新增 bundle、不动 inject 声明。
|
||||
- systemPrompt 投影段(order 151)本轮不加部门内容(D3 范围)。
|
||||
- 自动总结监听器不动。
|
||||
|
||||
验证:typecheck + build + node verify-plugin-entry.mjs(入口形状不变);
|
||||
V 卡验证注册名单含 6 个 department_*。
|
||||
commit:feat(departments): register department tools in the memory entry
|
||||
|
||||
## V · verify-departments-wiring.mjs
|
||||
|
||||
新文件:仓库根 verify-departments-wiring.mjs(P1 整理前的出生位置;
|
||||
若执行时 REPO_CLEANUP_PLAN 已先行,则直接写 tests/verification/ 并改 ../../lib 引用)。
|
||||
|
||||
harness 风格照抄 verify-departments.mjs:mkdtemp 假 DSH_HOME + project、
|
||||
check/throws 计数、动态 import('./lib/...')、结尾汇总 exit code。
|
||||
|
||||
覆盖清单(对应 DEPARTMENT_PLAN §6 验收):
|
||||
1. 工具注册:resetBrainKernel() 后 brainKernel(config,logger),
|
||||
createDepartmentTools(kernel.departmentToolDeps()) 长度 6、名字齐全、
|
||||
parameters 为合法 JSON Schema 对象。
|
||||
2. 工具行为闭环:create→remember→recall(私有命中 origin='department')→
|
||||
checkpoint→resume 返回 reusable 引用;k>5 被 clamp。
|
||||
3. 开关行为:localMemoryEnabled=false 时 execute 抛禁用错误;
|
||||
memoryEnabled=false 同理。
|
||||
4. 禁用部门:disable 后 remember/recall 抛错(库层语义透传)。
|
||||
5. 路由鉴权:起真实 http server 挂 createCoreRoutes(kernel.routeDeps())
|
||||
(参考 verify-brain-panel.mjs 的起服务手法):
|
||||
GET list 200;POST create 无 Origin 闸门票据 → 403;同源 → 200;
|
||||
缺 name → 400;expectedRevision 过期 → 409;未构造 departments → 503。
|
||||
6. legacy 别名:/cloud-memory/departments/list 同样可达。
|
||||
7. 环境性跳过口径:无真实宿主依赖,本脚本应 0 SKIP。
|
||||
|
||||
终验命令(全部通过才算 P1.5 D1+D2 完成):
|
||||
```
|
||||
npm run typecheck && npm run build
|
||||
node scripts/verify-all.mjs # 原 38 过 + 2 环境跳过不变,新增 wiring 全绿
|
||||
node verify-plugin-entry.mjs # 入口形状
|
||||
```
|
||||
commit:test(departments): wiring verification for tools and routes
|
||||
|
||||
## 边界提醒(执行者必读)
|
||||
|
||||
- 不改 src/local-memory/departments/ 库层任何字节——21 项验收是既成事实,
|
||||
接线只消费其公开 API。
|
||||
- 不动 cloud-sync:部门私有空间默认不上云(M4 再议)。
|
||||
- 不引新依赖;手写 ToolDefinition,不 import @deepseek-ai/dsh-tools。
|
||||
- lib/ 产物由 npm run build 生成后随卡提交(仓库约定 lib 入库)。
|
||||
- 每卡 commit 前跑该卡验证命令;V 卡终验后才向用户报"最小可用闭环完成"。
|
||||
|
|
@ -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,108 @@
|
|||
# 诊断日志规格(.dsh/brain/logs,随 UI 批次交付)
|
||||
|
||||
版本:v1 · 2026-11-24 23:40
|
||||
需求(用户原话):"这个版本需要在 .dsh 里面的 brain 留下 log,用来后续出问题 debug 的。
|
||||
先不升级,等 UI 做好一起升级。"
|
||||
定位:新增 U5 卡,与 U0–U4 同批交付、同次升级生效。基线 8f5ee01。
|
||||
|
||||
## 1. 落盘位置与文件布局
|
||||
|
||||
$DSH_HOME/brain/logs/ ← 全局(globalBrainRoot()/logs)
|
||||
brain-YYYY-MM-DD.log ← 按天滚动,JSONL(每行一个事件)
|
||||
brain-YYYY-MM-DD.1.log ← 单日超 5 MB 时序号滚动
|
||||
<project>/.dsh/brain/logs/ ← 项目级(projectBrainRoot(ws)/logs)
|
||||
brain-YYYY-MM-DD.log ← 只记该项目工作区的事件
|
||||
|
||||
- 全局事件(启动/开关/迁移/云同步/技能同步)落全局;带 workspace 的记忆/部门操作落项目。
|
||||
- 目录懒创建(首次写时 mkdir recursive);**.gitignore 已忽略 /.dsh/brain/,日志天然不入库**。
|
||||
- 保留策略:启动时清理 14 天前的日志文件(只删 logs/ 内 brain-*.log,别的不碰)。
|
||||
|
||||
## 2. 事件格式(JSONL,一行一事件)
|
||||
|
||||
{"ts":"ISO8601","level":"info|warn|error","event":"<点分名>","scope":"global|project",
|
||||
"workspace":"<路径,可省>","sessionId":"<可省>","detail":{…},"err":"<message,可省>"}
|
||||
|
||||
- detail 只放结构化小字段(id/scope/revision/耗时 ms/计数),**禁止记忆正文全文**;
|
||||
内容类字段一律截断 ≤120 字符并过 containsSecret(storage.ts 已有)拒收秘密。
|
||||
- 写入必须不阻塞主流程:appendFile 异步 + 失败静默(日志自身错误只 console.warn 一次)。
|
||||
- 单进程内串行队列(Promise chain)防交错;跨进程靠 append 原子性(单行 <64KB)。
|
||||
|
||||
## 3. 埋点清单( event 名 → 触发处 )
|
||||
|
||||
### 启动与配置(kernel.ts / entries)
|
||||
- boot.kernel constructor 完成:version、五 bundle 激活态、localMemoryEnabled/cloudMemoryEnabled/autoSummaryEnabled
|
||||
- boot.entry 各 entry apply/deactivate:bundle 名
|
||||
- config.change SettingsStore 写入时:变更键名列表(值不落盘,token 类只记 present/absent)
|
||||
- switch.gate memoryEnabled/localMemoryEnabled 拒绝工具/路由时:被拒面(tool/route)、名字
|
||||
|
||||
### 本地记忆(local-memory/manager.ts)
|
||||
- memory.ensure ensureGlobal/ensureProject:root、created/reused
|
||||
- memory.remember add/remember:scope、recordId、duplicate、category、耗时
|
||||
- memory.search search/searchHits:query 截断、k、命中数、来源分布、耗时
|
||||
- memory.forget forget:recordId、revision
|
||||
- memory.projection regenerateProjections/repair:dirty 原因、字节数、耗时
|
||||
- memory.summary summarizeConversation:sessionId、turn、成功/失败/重试次数、err
|
||||
- memory.profile proposeProfile/confirmProfile/correctProfile:动作、记录数
|
||||
- memory.migration migrateLegacy/rollbackMigration/importLegacyRecords:阶段、计数、err(数据安全关键路径,全阶段落盘)
|
||||
- memory.backup createBackup:路径、字节数
|
||||
|
||||
### 部门(接线层埋,库层零改动约束不变)
|
||||
- dept.create/update/disable/checkpoint/resume/recall/remember
|
||||
在 departments-tools.ts execute 与 departments-routes.ts handler 的包裹层记:
|
||||
departmentId、workspace、revision、结果/错误码。**不改 src/local-memory/departments/**。
|
||||
|
||||
### 云与技能(reporter/skill-sync,保护期后埋)
|
||||
- cloud.report 上报批次:turn 数、成功/失败、http 状态(token 不落盘)
|
||||
- sync.pass skill-sync 每轮:downloaded/uploaded/conflicts/skipped 计数、耗时
|
||||
- sync.resolve 冲突解决:name、action、conflictId、结果
|
||||
⚠ skill-sync.ts 在 GPT 复验保护期内禁改——本组埋点放 U5 后半段,
|
||||
复验通过后补;若 UI 批次先完成,cloud/sync 埋点单独小 commit 跟进,不阻塞升级。
|
||||
|
||||
### UI(src-client,浏览器侧)
|
||||
- 浏览器端不直接写文件:面板/页签的关键错误经既有路由无法上报时,
|
||||
console.warn 带 [dsh-brain] 前缀即可(宿主控制台可见);
|
||||
服务端路由错误已由 http 层 fail() 统一记 route.error(见下)。
|
||||
|
||||
### 路由层(routes.ts / settings-ui/*routes.ts / departments-routes.ts 保护期后)
|
||||
- route.error 任何 4xx/5xx:path、method、status、错误码(body 不落盘)
|
||||
- route.write POST 成功:path、关键 id(create/forget/resolve 类)
|
||||
|
||||
## 4. 实现形态
|
||||
|
||||
新文件 src/diagnostics.ts(host 侧,~150 行):
|
||||
export interface BrainLogEvent { level; event; scope?; workspace?; sessionId?; detail?; err? }
|
||||
export class BrainLogger {
|
||||
constructor(opts: { globalRoot: () => string; projectRootOf: (ws?: string) => string; enabled: () => boolean })
|
||||
log(e: BrainLogEvent): void // 同步入队,异步落盘,永不 throw
|
||||
flush(): Promise<void> // 测试用
|
||||
prune(): void // 启动清 14 天前
|
||||
}
|
||||
- kernel 构造 BrainLogger 并注入:LocalMemoryManager options 加 logger?(可选,缺省 noop,
|
||||
库层签名向后兼容);DepartmentToolDeps/RouteDeps 加 logger?;reporter/skillSync 的 log 回调
|
||||
双写(宿主 logger + BrainLogger)。
|
||||
- 开关:settings 加 diagnosticsEnabled(默认 true,继承 enabled);关闭时 noop。
|
||||
侧车 dsh-brain.json 可关;设置页 U2 概览卡显示日志路径与开关。
|
||||
- **LocalMemoryManager 属库层但不在部门保护目录内**,加可选 logger 参数允许;
|
||||
verify-local-memory* 现有断言不得回退(logger 缺省时行为字节等价)。
|
||||
|
||||
## 5. 验收(新增 verify-diagnostics.mjs)
|
||||
|
||||
1. mkdtemp DSH_HOME + 双项目:remember/search/forget 后项目 logs/ 出现当日 JSONL,
|
||||
事件名/字段齐全;全局操作落全局 logs/。
|
||||
2. 秘密拒收:detail 含 API key 样式 → 该字段被拒/截断,文件无秘密原文。
|
||||
3. 正文不落盘:700 字符记忆 remember → 日志无全文(≤120 截断)。
|
||||
4. 滚动:写 >5MB(测试用小阈值注入)→ .1.log 出现;14 天前旧文件被 prune。
|
||||
5. 关闭开关 → 零文件产生;logger 抛错注入 → 主流程不受影响。
|
||||
6. 日志失败静默:logs 目录置只读 → remember 仍成功。
|
||||
7. verify-all 全量口径不回退;typecheck/build 全绿。
|
||||
|
||||
commit:feat(diagnostics): JSONL debug logs under .dsh/brain/logs with redaction and rotation
|
||||
|
||||
## 6. 排期与升级批次
|
||||
|
||||
- U5 与 U0–U4 并行可行(diagnostics.ts 独立;manager 可选参数不碰部门保护文件)。
|
||||
- 建议顺序:U0 → U1 → (U2 ∥ U3 ∥ U5) → U4 终验。
|
||||
- **升级批次**:U0–U5 全部完成 + GPT 部门复验通过 → 一次升级 profile 依赖 → 重启 →
|
||||
冒烟清单(另出升级卡):status 版本、.dsh/brain 生成、memory_search 离线命中、
|
||||
部门工具可见、左栏 Brain 面板、better-sidebar 页签、**logs/ 出现当日 JSONL**。
|
||||
- skill-sync/cloud 埋点若因保护期滞后,升级后小 commit 补,不阻塞。
|
||||
|
|
@ -0,0 +1,193 @@
|
|||
# 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:33 复核):**P0 已完成**——用户已提交并推送,
|
||||
HEAD `1dfc7c7` feat: complete local memory and Mnemon integration (0.10.1),
|
||||
tag `v0.10.1`(替代原建议名 v0.10.0-local.1),工作树干净,origin/main 同步。
|
||||
后续阶段的回滚点即 v0.10.1。
|
||||
- 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):settings-ui 升格为 UI bundle——左侧栏总面板 + better-sidebar 项目记忆页签。方案 docs/plans/UI_PLAN.md;决策已定:B 借壳不借芯 + 彻底改名 dsh-brain-ui;可执行任务卡 docs/plans/UI_TASKS.md + 详细规格 UI_SPEC.md(U0–U4)+ 诊断日志 LOGGING_SPEC.md(U5)。升级批次(用户拍板):先不升级宿主,UI 全卡完成 + 部门复验通过后一次升级,新版须带 .dsh/brain/logs 诊断日志。
|
||||
|
||||
**推荐执行序(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 · 收口与基线固化(先做,半天)
|
||||
|
||||
**状态:已完成(2026-11-24)**。实际落账:单 commit `1dfc7c7` + tag `v0.10.1`(未按下面 1–3 的分主题拆分,成果已入库为准;verify-all 重跑记录见验收文档)。以下保留原计划供追溯:
|
||||
|
||||
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 天)
|
||||
|
||||
状态(2026-11-24 23:25):D1+D2 实施完成,GPT 首轮验收 FAIL 两项(C7/C8)已修复
|
||||
(22b2497/45f1ca9),wiring 25 项全绿,待 GPT 复验。复验通过后进入 UI 改造(UI_PLAN.md)或 P1 仓库整理。
|
||||
|
||||
执行序建议:**提前到 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 21 项检查全绿(实测复核,原稿误记 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/D2 可执行任务卡见 docs/plans/DEPARTMENT_TASKS.md):
|
||||
- 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,118 @@
|
|||
# P1 · 仓库整理实施方案(Repo Cleanup)
|
||||
|
||||
版本:v1(规划稿,本会话只做规划,不实施)
|
||||
日期:2026-11-24
|
||||
依据:LOCAL_MEMORY_PLAN.md §19 + 本轮逐项核实(39 个 verify 脚本的引用扫描、Git 状态、目录实测)。
|
||||
执行归属:实施会话/人工;每步独立 commit,门禁见 §7。
|
||||
|
||||
## 0. 前置核对(执行前必读)
|
||||
|
||||
**基线已固化(2026-11-24 20:33 复核)**:P0 完成——HEAD `1dfc7c7`(0.10.1 本地记忆+Mnemon 集成),
|
||||
tag `v0.10.1`,工作树干净,已推送 origin/main。本方案的回滚点即 v0.10.1。
|
||||
C0 仍保留"动手前再核对一次 Git 状态"的动作,防执行时隔了新的改动。
|
||||
|
||||
## 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 一律出生在新位置,不再回落根目录。
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
# UI 批次验收 FAIL 修复单(给 GPT 执行)
|
||||
|
||||
日期:2026-11-25
|
||||
基线:c8101a3(U0–U5 七个交付 commit 齐全,工作树干净)。
|
||||
依据:GPT 独立复核报告(三个 P1 + diff --check 六处)。规划侧已逐项对照源码核实,全部属实。
|
||||
角色变更:本轮由 **GPT 实施修复**(此前 GPT 只验收;用户明确指派)。修完自验 + 交回规划侧复核。
|
||||
环境:npm/node 不在 PATH,用宿主 bundled node + pnpm(路径见 UI_HANDOFF.md §开工前核对)。
|
||||
|
||||
## 根因分析(已核实,照此修,不要另起方案)
|
||||
|
||||
### P1-A 项目记忆跨工作区混列
|
||||
两处断点,都要修:
|
||||
1. **服务端**:src/routes.ts serveLocalMemory 的五个 GET 分支(status/spaces/documents/memories)
|
||||
与 forget POST 都**不读 workspace 参数**,直接调 manager.xxx()——manager 这些方法
|
||||
全都已支持可选 workspace 尾参(storageStatus(workspace?)/projects(workspace?)/
|
||||
documents(workspace?)/list(options,workspace?,projectId?)/forget(id,rev?,workspace?)),
|
||||
路由层没传而已。
|
||||
2. **客户端**:src-client/sidebar/ProjectMemoryView.tsx 的 status/memories 请求不带
|
||||
workspace(departments/list 带了);src-client/panel/MemoryTab.tsx 定义了
|
||||
workspaceSuffix 助手但**三个请求都没用它**,且组件 props 没有 workspace 来源。
|
||||
|
||||
修法:
|
||||
- routes.ts:每个分支加
|
||||
`const workspace = url.searchParams.get('workspace')?.trim() || undefined`
|
||||
并传入 manager 对应方法;forget 从 body.workspace 取(string trim)。
|
||||
响应形状不变(新增可选入参,向后兼容)。
|
||||
- ProjectMemoryView.tsx:status/memories/documents 请求统一加
|
||||
`workspace === undefined ? '' : '?workspace=' + encodeURIComponent(workspace)`
|
||||
(memories 已有 query 用 &)。workspace 来自 props.scope?.cwd(已有变量)。
|
||||
- MemoryTab.tsx:props 加 workspace?: string;BrainPanel 渲染 MemoryTab 时传入
|
||||
面板持有的当前会话 cwd(与 DepartmentTab 同源;若面板尚无 workspace 状态,
|
||||
加一个经 ctx sessions 面探测的 hook,参考 UI_SPEC U2 的 workspace 取值段)。
|
||||
三个请求用上 workspaceSuffix。
|
||||
- **注意**:local-memory 路由不在部门保护清单内(保护的是 departments-routes.ts),可以改。
|
||||
|
||||
### P1-B 发布包带构建机绝对路径 + 重建不一致
|
||||
根因:tsdown.config.ts brainCssPlugin 的虚拟模块 id 用**绝对路径**
|
||||
(CSS_VIRTUAL_PREFIX + absolute + '.mjs'),rolldown 把虚拟 id 写成产物注释:
|
||||
client/index.js L4193/L5092 出现
|
||||
`// \0dsh-brain-css:C:\Users\qyh15\dsh-brain\src-client\...module.css.mjs`。
|
||||
pack-guard 内容黑名单 /C:[\\/]Users[\\/]/ 命中 → exit 1;换机重建注释路径不同 → 字节不一致。
|
||||
|
||||
修法(tsdown.config.ts):
|
||||
1. resolveId 返回的虚拟 id 改用**仓库相对路径**:
|
||||
`const rel = relative(process.cwd(), absolute).replaceAll('\\','/')`
|
||||
return CSS_VIRTUAL_PREFIX + rel + CSS_VIRTUAL_SUFFIX
|
||||
2. load 里 fileId 还原绝对路径供 readFile/addWatchFile:
|
||||
`const fileId = resolvePath(process.cwd(), virtualId.slice(prefix.length, -suffix.length))`
|
||||
3. filename(classMap 哈希与 tagId)已经是 relative——保持不变,确保哈希稳定。
|
||||
4. 重建后 client/index.js 不得再含 C:\\Users 或 qyh15;
|
||||
隔离副本重建产物与提交产物逐字节一致(pack-guard 的 rebuild-parity 口径)。
|
||||
5. 顺手核 client/index.js 是否还有其他绝对路径注释(grep 'C:' 全文件)。
|
||||
|
||||
### P1-C 诊断搜索日志落错工作区 + 121 字符
|
||||
两个独立小 bug:
|
||||
1. **search 日志 workspace 丢失**:manager.ts searchHits L233 把形参 workspace 直接传给
|
||||
logger;当调用方经 withWorkspace(B) 包裹而**不显式传 workspace 形参**时(remote.run
|
||||
之外的路径、或测试直调),形参为 undefined → BrainLogger.directoryFor('project', undefined)
|
||||
→ projectRootOf(undefined) 回落默认工作区 A。remember 之所以正确,是因为它用
|
||||
`this.workspacePath()`(读 AsyncLocalStorage 上下文)而非形参。
|
||||
修法:searchHits 日志行改用 `const ws = this.workspacePath(workspace)`
|
||||
(workspacePath 已接受可选 override,看 manager 现有签名;若只读上下文则
|
||||
`workspace ?? this.workspacePath()`),与 remember 同口径。
|
||||
同查 forget/projects/documents/storageStatus 各日志行是否同样依赖形参——统一改上下文优先。
|
||||
2. **121 字符**:diagnostics.ts sanitizeValue 截断 `value.slice(0,120)+'…'` = 121。
|
||||
与部门 C7 同款错误。修法:`value.slice(0, MAX_FIELD_CHARS - 1) + '…'`;
|
||||
err 字段同理 `slice(0, MAX_ERR_CHARS - 1)`。规格口径"≤120 含省略号"。
|
||||
|
||||
### P2 diff --check 六处 EOF 空行
|
||||
src-client/api.ts:95 / format.ts:98 / sections/ImportSection.tsx:301 /
|
||||
sections/McpCustomSection.tsx:99 / sections/SyncResolveSection.tsx:118 / styles.ts:368
|
||||
——各删文件末尾多余空行(保留单个终止换行)。
|
||||
|
||||
## 测试补强(修代码同时补断言,防回归)
|
||||
|
||||
1. verify-diagnostics.mjs:
|
||||
- 双工作区 search:withWorkspace(B) 内 memory.search(不显式传 workspace)→
|
||||
日志落 B 的 logs/,A 无该事件(现有测试 L44 只搜默认区,漏了这个路径)。
|
||||
- 截断边界:构造 130 字符 detail 字段 → 落盘值 length ≤120(含省略号)。
|
||||
2. verify-client-build.mjs(或新增 verify-ui-workspace.mjs):
|
||||
- 静态断言 ProjectMemoryView/MemoryTab 的 memories/status/documents 请求含 workspace 拼接。
|
||||
- HTTP 探针:双工作区 A/B 各 remember 一条 → GET memories?workspace=B 只含 B 记录
|
||||
(服务端隔离);GET 不带 workspace 行为与旧版一致(回落 process.cwd())。
|
||||
3. pack-guard 重跑 exit 0;隔离重建 parity changed=[] extra=[]。
|
||||
4. git diff --check exit 0。
|
||||
|
||||
## 执行与验收
|
||||
|
||||
顺序:P1-C(最小)→ P1-A → P1-B → P2 → 测试补强,可合 2–3 个 commit:
|
||||
- fix(diagnostics): route search logs by workspace context and count ellipsis in budget
|
||||
- fix(ui): pass workspace through local-memory routes and both memory views
|
||||
- build(client): relative css virtual ids — no machine paths in bundle
|
||||
- style: trim EOF blank lines flagged by git diff --check
|
||||
(测试补强随对应 fix commit 入库。)
|
||||
|
||||
终验(全绿才报完成):
|
||||
typecheck + build(bundled node + pnpm)
|
||||
node scripts/verify-all.mjs # 41 脚本口径不回退
|
||||
node verify-client-build.mjs # 40 项
|
||||
node verify-diagnostics.mjs # 15 项 + 新断言
|
||||
node verify-departments-wiring.mjs # 25 项(保护期回归)
|
||||
node scripts/pack-guard.mjs # exit 0
|
||||
git diff --check # exit 0
|
||||
隔离副本重建 → client/index.js 与提交逐字节一致
|
||||
|
||||
约束:
|
||||
- 部门保护四文件仍禁改(departments-tools/departments-routes/skill-sync/库层 departments/)。
|
||||
manager.ts 的日志行修改允许(不在保护清单);不改任何存储语义。
|
||||
- 不 push 不打 tag 不升级宿主;修完回报 commit hash + 验证摘要,规划侧复核后由用户定推送。
|
||||
- 与根因分析不符的现状:停下报告,不自行改方案。
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
# 执行交接单 · UI 改造 U0–U5(给新 DeepSeek 会话)
|
||||
|
||||
日期:2026-11-24
|
||||
仓库:C:\Users\qyh15\dsh-brain(分支 main,基线 af42877,已推送)
|
||||
角色:你是实施者。本单 + docs/plans/ 下四份规格是你的全部任务来源;规划会话不参与实施。
|
||||
你不需要知道之前会话的历史——所有结论都已固化在文档里。
|
||||
|
||||
## 任务一句话
|
||||
|
||||
把 dsh-brain 的 settings-ui 子插件升格为 UI bundle:左侧栏总面板 + better-sidebar
|
||||
项目记忆页签 + .dsh/brain/logs 诊断日志,bundle id 彻底改名 dsh-brain-ui。
|
||||
完成标志:U0–U5 全部 commit、终验命令全绿。预计 4–5 天。
|
||||
|
||||
## 必读文档(按序)
|
||||
|
||||
1. docs/plans/UI_HANDOFF.md ← 本单
|
||||
2. docs/plans/UI_SPEC.md ← 详细施工规格(文件级改动、代码骨架、API 契约、逐卡验收)——执行以此为准
|
||||
3. docs/plans/UI_TASKS.md ← 任务卡总览(U0–U5 依赖与排期)
|
||||
4. docs/plans/LOGGING_SPEC.md ← U5 诊断日志独立规格
|
||||
背景按需查:UI_PLAN.md(决策记录:B 借壳不借芯 + 彻底改名)、DEPARTMENT_PLAN.md(部门概念)。
|
||||
|
||||
## 开工前核对(5 分钟)
|
||||
|
||||
1. git status 干净、git log -1 为 af42877 或其后继(后继应仅 docs/plans 或他人 UI 施工)。
|
||||
若工作树脏:停下报告,不要混提交。
|
||||
2. node verify-departments.mjs → ALL 21 CHECKS PASSED(起点基线)。
|
||||
3. node scripts/verify-all.mjs → 39 scripts 全绿(1 环境跳过)。
|
||||
4. 环境:npm/node 不在系统 PATH。用宿主自带运行时:
|
||||
node: C:/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/node/bin/node.exe
|
||||
(或 C:/Users/qyh15/AppData/Local/Programs/DeepSeek Harness/resources/runtime/primary-runtime/dependencies/node/bin/node.exe)
|
||||
pnpm: C:/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/pnpm/bin/pnpm.mjs
|
||||
npm run X 等价于 node <pnpm.mjs> run X;tsc 直接 node node_modules/typescript/bin/tsc。
|
||||
|
||||
## 执行顺序
|
||||
|
||||
U0(client 构建链)→ U1(左栏面板骨架)→ ┬ U2(记忆/部门页签)┐
|
||||
├ U3(better-sidebar 页签)├→ U4(改名+终验)
|
||||
└ U5(诊断日志)──────────┘
|
||||
|
||||
U2/U3/U5 可并行。每卡独立 commit,文案按 UI_SPEC.md 各卡给定。
|
||||
|
||||
## 硬约束(违反即返工)
|
||||
|
||||
- **保护期禁改四文件**(GPT 部门复验未结束):src/memory/departments-tools.ts、
|
||||
src/settings-ui/departments-routes.ts、src/skill-sync.ts、src/local-memory/departments/。
|
||||
可以 import 它们的导出(如 departmentSnippet)。U5 的 skill-sync/cloud 埋点因此滞后,
|
||||
复验通过后单独小 commit 补,不阻塞本批。
|
||||
- 运行时零新依赖:tsdown ^0.22.2 已在 devDependencies;react 走宿主 shim externals。
|
||||
- client 产物必须仍是单文件 window.__ModuleLoader__ IIFE,id:'dsh-brain' 不变
|
||||
(子插件 row id 才改 dsh-brain-ui,两者是两回事)。
|
||||
- 抄 vendor/dsh-mnemon 源码处保留 MIT 出处注释。
|
||||
- 样式走 --dsw-alias-* token,无纯白纯黑硬编码(verify-theme 会查)。
|
||||
- lib/ 与 client/index.js 构建产物随卡入库(仓库约定)。
|
||||
- 每卡 commit 前跑该卡验证命令;遇到与规格不符的现状:停下报告差异,等规划侧修订。
|
||||
- 不 push 不打 tag 不升级宿主 profile——完成后回报,由用户决定推送与升级时机。
|
||||
|
||||
## 终验(U4 末尾,全部通过才报完成)
|
||||
|
||||
node <pnpm> run typecheck && node <pnpm> run build
|
||||
node scripts/verify-all.mjs # 39+ 脚本口径不回退
|
||||
node verify-plugin-entry.mjs # 含 './settings-ui' 别名兼容断言
|
||||
node verify-client-build.mjs # U0 新增
|
||||
node verify-diagnostics.mjs # U5 新增
|
||||
node <pnpm> pack --dry-run # files 含 client/index.js、lib/entries/ui.js
|
||||
|
||||
## 交付物
|
||||
|
||||
1. 每卡一个 commit(U0/U1/U2/U3/U5/U4,共 6 个左右),回报 hash + 验证摘要。
|
||||
2. 偏离规格的决定逐条列原因,交用户追认。
|
||||
3. 完成后通知用户:可转 GPT 做 UI 验收(验收单由规划侧另出),并触发宿主升级批次
|
||||
(升级前提:本批全绿 + 部门复验通过;升级卡规划侧另备)。
|
||||
|
|
@ -0,0 +1,197 @@
|
|||
# settings-ui → UI 改造方案(总面板 + better-sidebar 项目记忆入口)
|
||||
|
||||
版本:v1(规划稿,本会话只做规划,不实施)
|
||||
日期:2026-11-24
|
||||
基线:accc1c3(D1+D2 部门接线已入库并推送)。
|
||||
需求(用户原话):"把 setting ui 改成 UI,因为我需要有左侧栏入口打开的总面板,
|
||||
有需要挂载在 better-sidebar 的项目记忆入口。"
|
||||
|
||||
## 0. 宿主接入面实测结论(2026-11-24,全部来自本机已装插件源码)
|
||||
|
||||
三个真实可用的注册面,各有现成范例:
|
||||
|
||||
| 面 | 机制 | 范例(本机已装) | 效果 |
|
||||
| --- | --- | --- | --- |
|
||||
| 左侧栏全局面板 | client 半区 ctx.slots.inject('sidebar.panellist', …) 注册行 + ctx.slots.inject('main', …) 注册页面 | @linxin666/dsh-client-ui-task-board v0.4.20(lib/client.js native-panel 段) | 与宿主"插件/日程"页同级的左栏入口,点开占中列主区;shell 拥有行盒/标签/高亮/折叠轨 |
|
||||
| better-sidebar 页签 | client 半区 inject ['betterSidebar'],ctx.betterSidebar.registerTab(descriptor) | dsh-better-sidebar 0.32.1 README_ZH 最小示例 + lib/types/client/service.d.ts | 右侧栏/底部工作台新增页签类型,按会话 scope 渲染 |
|
||||
| 设置卡(现状保留) | ctx.slots.inject('settings.section' / 'plugins.bundle.config') | dsh-brain client/index.js 现有 apply() | 设置页内嵌卡,不动 |
|
||||
|
||||
关键契约细节(照抄范例,不自造):
|
||||
- panellist 行 options:{ name:'sidebar.panellist', id:<panelId>, order:<n>, label:()=>string },
|
||||
组件只画 glyph(svg,带 data-dsh-panel-entry=<panelId> 语义锚点);
|
||||
Plugins order=0、Schedule=10、task-board=20 → 本项目建议 order=30。
|
||||
- main 页 options:{ name:'main', key:<panelId>, inject:()=>({…}) },
|
||||
组件收 shell 注入的 face;layout 只在该面板选中时挂载,其余时间中列归会话。
|
||||
- registerTab descriptor:{ id:'dsh-brain:memory', title, description, icon?, order?,
|
||||
single:true, component:(props:TabComponentProps)=>ReactNode };
|
||||
props 含 ctx/store/scope/sessionId/tab/visible——**visible=false 时暂停轮询**(契约明说)。
|
||||
single:true = 单实例,重复打开聚焦已有页签。
|
||||
- 两个 seat 都经 slots.inject 延迟触发,与 shell 加载顺序无关;shell 不支持时静默不挂。
|
||||
- better-sidebar 未安装时 registerTab 面不存在 → 必须优雅降级(见 §3)。
|
||||
|
||||
|
||||
## 0.5 复用 Mnemon 面板的评估(2026-11-24 用户提议:"mnemon 里面有面板,拿他的面板改")
|
||||
|
||||
**事实核对(全部实测)**:
|
||||
- Mnemon 确实有完整面板,且**正在你宿主里运行**:desktop profile 的 mnemon 行
|
||||
disabled:false,左栏已有"记忆系统"(panel id 'mnemon')与技能页(order 31),
|
||||
better-sidebar 页签 'dsh-mnemon:memory'(order 55,single)。
|
||||
- vendor/dsh-mnemon fork 含全部客户端源码:src/client 96 文件 / 737 KB
|
||||
(45 tsx + 40 ts + 9 css),MnemonWorkbench.tsx 单文件 49 KB。
|
||||
- **接入面可直接抄**:native-sidebar.tsx(panellist+main 双 seat、usePanelInfo
|
||||
激活判定、window-drag band)、better-sidebar.tsx(registerTab + internal/service
|
||||
事件 reconcile 热插拔)、HeldSeat/ExternalStore 模式——比 task-board 范例更完整。
|
||||
- **但 Workbench 本体不能直接搬**:数据面走 connection.rpc.call(MNEMON_*_CHANNEL)
|
||||
的宿主 RPC(9 条通道),类型耦合 ../host/protocol.ts(client 内 52 处 import)
|
||||
与 @deepseek-ai/dsh-client-ui-slots/layout(58 处);渲染的是 Mnemon 运行时视图
|
||||
(MemoryViewDashboard/策略/组件目录),不是 dsh-brain 的 HTTP JSON。
|
||||
直接改 = 给 LocalMemoryManager 假扮整个 Mnemon host RPC 面,或把 49 KB Workbench
|
||||
逐页改写到 HTTP——两者都比手写面板贵。
|
||||
- **存在一条真复用路(选项 C)**:dsh-brain 已有 native provider
|
||||
(src/mnemon/native.ts,descriptor id 'dsh-brain-native',经 vendored provider-sdk
|
||||
暴露 verify-mnemon-native 6 项全绿)。把它注册进**正在运行的 Mnemon 宿主**当一个
|
||||
source,Mnemon 现成面板即可浏览/搜索/编辑 dsh-brain 本地记忆——零新 UI。
|
||||
代价:①依赖外部 dsh-mnemon@0.5.48 与 fork 0.5.54-dsh.1 的 provider 协议兼容性
|
||||
(需实测);②面板是 Mnemon 品牌与概念(空间/来源/策略),部门、技能同步、
|
||||
连接上报等 dsh-brain 自有面不在其中;③与 P3"功能移除精简"方向相悖
|
||||
(长期要摆脱双记忆系统并存)。
|
||||
|
||||
**三选项对比**:
|
||||
|
||||
| 选项 | 做法 | 工作量 | 得到 | 风险 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| A 原方案 | 手写 React 总面板 + 侧栏页签(U1–U4) | 中(3–5 天) | 完全自有品牌与概念,部门/技能/连接全纳入 | 无外部依赖;样式从零 |
|
||||
| B 借壳不借芯(推荐) | A 的骨架 + **抄 Mnemon 接入层代码**(双 seat 注册、HeldSeat、reconcile、css module 布局样式),内容页对 HTTP 手写 | 中偏小(2–4 天) | 接入层经过生产验证,少踩坑;数据面干净 | 需引入 client 构建链(tsx/css modules → 单文件 bundle,见下) |
|
||||
| C 寄生 Mnemon | native provider 注册进运行中的 Mnemon,用它的现成面板 | 小(1–2 天,若协议兼容) | 立即有成熟面板可看本地记忆 | 双系统耦合、品牌混淆、与 P3 精简方向冲突;部门等自有面无着落 |
|
||||
|
||||
**推荐:B 为主,C 作可选过渡**——若你想"今天就能在面板里看到本地记忆",
|
||||
先做 C 的 provider 注册(小活,独立验收),再按 B 建自有面板,建成后 C 可撤。
|
||||
不推荐整体搬 Workbench(数据面假扮成本 > 手写)。
|
||||
|
||||
**B 的构建链决策点**:现有 client/index.js 是手写无打包器(__ModuleLoader__ 契约)。
|
||||
抄 Mnemon 的 tsx/css module 代码需要加一条 client 构建(tsup/esbuild → 单文件 IIFE,
|
||||
产物仍写 client/index.js 入库,宿主加载方式不变)。这是 devDependency 级新增,
|
||||
不违反"运行时零新依赖",但要在 U1 前定案。若坚持零构建,则只抄逻辑不抄 tsx,
|
||||
样式手写等价物(工作量回到 A)。
|
||||
|
||||
## 1. 目标形态
|
||||
|
||||
左侧栏 [Brain] 行(order 30)
|
||||
└─ 总面板(main slot,key='dsh-brain')
|
||||
页签:概览 / 记忆 / 部门 / 技能 / MCP / 连接与上报
|
||||
—— 现有 client/index.js 三页签 + settings-ui page.ts 八卡片的全部能力
|
||||
收进一个 React 面板,数据仍走同源公开路由,零新后端。
|
||||
better-sidebar 页签 "项目记忆"(id='dsh-brain:memory',single)
|
||||
└─ 当前会话项目的记忆视图:空间状态 / 记忆列表 / 搜索 / 文档 / 部门召回
|
||||
按 scope.sessionId → 会话 cwd → projectId 定位项目空间。
|
||||
设置卡(settings.section)保留为精简入口:状态 + 跳转总面板按钮。
|
||||
/dsh-brain 独立 HTML 页保留为兜底(无 shell seat 的环境仍可用)。
|
||||
|
||||
## 2. bundle 改名与边界
|
||||
|
||||
- src/entries/settings-ui.ts → src/entries/ui.ts;export name 'dsh-brain-settings-ui'
|
||||
→ 'dsh-brain-ui';package.json exports './settings-ui' → './ui'(保留 './settings-ui'
|
||||
别名导出指向同一文件,老 profile 行不断)。
|
||||
- cordis.patch.yml insert 行 id 同步改 dsh-brain-ui;**兼容风险**:宿主 Settings→Plugins
|
||||
的禁用行按旧 id 写死过(profile patch 里可能有 '- id: dsh-brain-settings-ui'),
|
||||
改名后旧禁用行失效 → 迁移说明必须写清,或保留旧 id 只改显示名(见 §6 决策点)。
|
||||
- kernel BrainBundle 类型 'settings-ui' → 'ui'(isActive/routeDeps 同步);
|
||||
路由归属不变:page + core routes(status/capabilities/config/migrate/local-memory/departments)
|
||||
仍由该 entry 注册,legacy /cloud-memory 别名自动跟随。
|
||||
- 五子插件结构不变,只是第五个从"设置页"升格为"UI 面板";其余四 bundle 零改动。
|
||||
|
||||
## 3. 切片(每片独立 commit + verify)
|
||||
|
||||
### U1 · client 总面板骨架(左栏入口)
|
||||
- client/index.js:新增 panelId='dsh-brain';apply() 里加两个 slots.inject
|
||||
(panellist 行 + main 页),照 task-board native-panel 模式;glyph 自绘 svg。
|
||||
- main 页组件 = 现有 SettingsCard 升格为 BrainPanel:页签壳 + 现有三页签内容复用,
|
||||
新增"概览"页签(status/capabilities 聚合,数据已有)。
|
||||
- 设置卡注册保留但瘦身:状态摘要 + "打开总面板"按钮(经 shell 面板切换 API;
|
||||
若 seat 不可用则回退 window.open('/dsh-brain'))。
|
||||
- 降级:slots 里没有 sidebar.panellist/main seat 时(web 精简 shell),
|
||||
仅保留设置卡 + 独立页,console.info 一次,不报错。
|
||||
- verify:verify-plugin-entry.mjs 更新入口名单;新增 verify-ui-panel.mjs
|
||||
(静态断言 client bundle 含两 seat 注册、panelId、降级分支;形状检查为主,
|
||||
DOM 行为留给 U4 冒烟)。
|
||||
|
||||
### U2 · 记忆/部门页签并入总面板
|
||||
- "记忆"页签:消费 /dsh-brain/local-memory(status/spaces/documents/memories/forget),
|
||||
列表 + 搜索 + 分页(limit/offset 路由已支持)。
|
||||
- "部门"页签:消费 /dsh-brain/departments(list/create/update/disable/checkpoint/recall/resume),
|
||||
表单走同源 POST(sameOrigin 闸门天然满足)。
|
||||
- 两页签均为 React 手写(沿用 client/index.js 无打包器约定),不引新依赖。
|
||||
- verify:verify-ui-panel.mjs 扩展路由消费断言;手工冒烟脚本起真实 server 核对 JSON 形状。
|
||||
|
||||
### U3 · better-sidebar "项目记忆"页签
|
||||
- client apply():探测 ctx.betterSidebar(typeof registerTab === 'function');
|
||||
存在则 ctx.effect(() => ctx.betterSidebar.registerTab({...})),不存在静默跳过。
|
||||
- descriptor:id='dsh-brain:memory',title='项目记忆',description 写明
|
||||
"当前会话项目的本地记忆:空间/条目/搜索/部门召回",single:true,order 建议 60。
|
||||
- component(props):scope.sessionId → 会话 header.cwd(经 ctx sessions 面或
|
||||
status 路由带回)→ 项目空间视图;visible=false 暂停一切轮询。
|
||||
- 内容 = U2 记忆页签的项目子集(只读浏览 + 搜索 + forget),不做创建部门等重操作
|
||||
(重操作引导去总面板)。
|
||||
- 降级链:better-sidebar 未装 → 无页签(总面板不受影响);装了但 fiber 卸载 → disposer 自动清理。
|
||||
- verify:verify-ui-panel.mjs 断言 registerTab 探测与 disposer;
|
||||
真实宿主冒烟(U4)确认页签出现在 + 菜单。
|
||||
|
||||
### U4 · 改名落地 + 终验
|
||||
- entries/settings-ui.ts → entries/ui.ts(含 exports 别名、patch 行、kernel 类型)。
|
||||
- 全量门禁:typecheck + build + verify-all(39 脚本口径不回退)+ verify-plugin-entry。
|
||||
- 宿主冒烟(升级 profile 依赖后):左栏出现 Brain 行 → 点开总面板六页签;
|
||||
better-sidebar + 菜单出现"项目记忆";设置卡仍在;/dsh-brain 独立页仍可达。
|
||||
- npm pack --dry-run:files 清单不变(client/lib 入库),exports 新增 './ui'。
|
||||
|
||||
## 4. 数据面(零新后端原则)
|
||||
|
||||
总面板与侧栏页签全部消费既有公开路由:
|
||||
status / capabilities / config / local-memory/* / departments/* / skills / market / sync / clients / migrate。
|
||||
唯一可能的新增:GET /dsh-brain/local-memory/memories 已支持 limit/offset,够用;
|
||||
项目定位若需要"会话→cwd"映射,优先用 better-sidebar props.scope 自带信息,
|
||||
其次 status 路由扩展一个 workspace 字段(小改,单独评审)。
|
||||
**不新增写路由**;所有写操作沿用 sameOrigin 闸门与 revision 冲突语义。
|
||||
|
||||
## 5. 边界与约束
|
||||
|
||||
- client/index.js 保持手写无打包器(宿主 __ModuleLoader__ require shim 契约,
|
||||
文件头注释已写明);不引 React 之外的运行时依赖。
|
||||
- 面板/页签组件必须容错:路由失败显示可行动错误条,不白屏(沿用 CardBoundary 模式)。
|
||||
- better-sidebar 是可选增强:未安装时一切功能经总面板/独立页可达,不硬依赖。
|
||||
- 部门私有空间不上云边界不变;侧栏页签只读浏览为主。
|
||||
- 皮肤语义锚点:glyph 带 data-dsh-panel-entry,面板根带 data-dsh-plugin="dsh-brain"
|
||||
(对齐 task-board 的 L2 皮肤契约,避免主题适配找不到行)。
|
||||
|
||||
## 6. 决策记录与待决点
|
||||
|
||||
**已定(2026-11-24 23:30,用户拍板):选项 B 借壳不借芯**——抄 Mnemon 接入层
|
||||
(native-sidebar/better-sidebar 双 seat 注册、HeldSeat、reconcile)与 css module 布局样式,
|
||||
内容页对 dsh-brain 自有 HTTP 路由手写;接受新增 client 构建 devDependency
|
||||
(tsup/esbuild → 单文件 IIFE,产物仍 client/index.js 入库,宿主 __ModuleLoader__ 加载方式不变)。
|
||||
不做 C 寄生过渡。构建链选型在 U1 任务卡定案(倾向 tsup,与 vendor fork 同链)。
|
||||
|
||||
**已定(2026-11-24 23:33,用户拍板):bundle id 彻底改名 dsh-brain-ui**——
|
||||
exports 保留 './settings-ui' 别名指向同一文件,老 profile 行不断;
|
||||
旧 id 的宿主禁用/配置行不自动改写(越权),entry 探测到旧行时 logger.warn 提示,
|
||||
README 升级说明写明。详见 UI_TASKS.md U4 改名清单。
|
||||
|
||||
可执行任务卡:docs/plans/UI_TASKS.md(U0 构建链→U1 面板骨架→U2 记忆/部门页签→
|
||||
U3 better-sidebar 页签→U4 改名+终验;tsdown 已在 devDeps,无需新增依赖)。
|
||||
|
||||
以下为原待决点存档:
|
||||
|
||||
1. **bundle id 改名策略**:彻底改 'dsh-brain-ui'(干净,但老 profile 禁用行需迁移)
|
||||
vs 保留 id 'dsh-brain-settings-ui' 只改显示名与职责(零迁移成本)。建议后者起步,
|
||||
发布 0.11.0 时再彻底改名。
|
||||
2. 总面板页签顺序与命名:概览/记忆/部门/技能/MCP/连接与上报(可调)。
|
||||
3. better-sidebar 页签是否也要"部门"独立页签(本轮建议只做一个"项目记忆",部门在总面板)。
|
||||
4. 排期位置:建议插在 P1 仓库整理之前、GPT 验收 D1+D2 之后(UI 改造会动 client 与
|
||||
entries,先让部门验收落定,避免验收基线漂移)。
|
||||
|
||||
## 7. 验收(新增 verify-ui-panel.mjs + 宿主冒烟)
|
||||
|
||||
- 静态:client bundle 含 panellist/main/betterSidebar 三注册面与各自降级分支;
|
||||
panelId/descriptor id 唯一;exports 别名齐全。
|
||||
- 门禁:typecheck/build/verify-all 全绿,39 脚本口径不回退。
|
||||
- 宿主冒烟清单(U4):左栏行、总面板六页签、侧栏页签、设置卡、独立页五处逐一截图核对。
|
||||
- 发布件:npm pack --dry-run 比对,client/index.js 与 lib/entries/ui.js 在包内。
|
||||
|
|
@ -0,0 +1,260 @@
|
|||
# UI 改造详细实施规格(给 DeepSeek 执行)
|
||||
|
||||
版本:v1 · 2026-11-24 23:40
|
||||
基线:5fef328(main,已推送)。开工前 git status 必须干净。
|
||||
决策:B 借壳不借芯 + bundle id 彻底改名 dsh-brain-ui(用户拍板)。
|
||||
本规格是 UI_TASKS.md 的展开版:每卡给出文件级改动、可抄源码位置、代码骨架、验收命令。
|
||||
U5 诊断日志独立规格:LOGGING_SPEC.md(.dsh/brain/logs JSONL,脱敏/滚动/开关,随本批交付)。
|
||||
冲突保护:GPT 部门复验未结束前,**禁改** src/memory/departments-tools.ts、
|
||||
src/settings-ui/departments-routes.ts、src/skill-sync.ts、src/local-memory/departments/。
|
||||
(可以 import 它们的导出,如 departmentSnippet。)
|
||||
|
||||
═══════════════════════════════════════════
|
||||
U0 · client 构建链落地(0.5–1 天)
|
||||
═══════════════════════════════════════════
|
||||
|
||||
## 现状事实(已实测)
|
||||
- client/index.js:3735 行手写 IIFE,window.__ModuleLoader__.load({id:'dsh-brain',factory})。
|
||||
- devDependencies 已含 tsdown ^0.22.2、typescript ^5.6.0、react ^18.2.0、@types/react。
|
||||
**不需要新增任何依赖。**
|
||||
- vendor/dsh-mnemon/tsdown.config.ts 的 client 段是现成模板(banner/intro/footer、
|
||||
css modules 内联插件 clientCssPlugin、react externals)。
|
||||
- 现有 client 结构图(迁移按此切模块):
|
||||
L22 API 常量 / L49 request / L67 postJson / L71 messageOf / L79 bridgeCall(MCP)
|
||||
L108-235 格式化与标签表 / L246-612 styles 对象 / L613-762 基础组件(Pill,Banner,Field,Btn,IconBtn,Switch,Toggle,Section)
|
||||
L774 MarketSection / L929 SyncResolveSection / L1038 McpCustomSection / L1127 McpConfigSection
|
||||
L1259 ImportSection / L1551 SettingsCard(主体,含 connection/skills/mcp 三页签) / L3680 CardBoundary / L3704 apply
|
||||
|
||||
## 改动清单
|
||||
1. 新建 src-client/ 目录,把上述结构迁为 TS 模块(行为等价优先,不重构逻辑):
|
||||
src-client/index.ts ← 入口,导出 {apply, inject:['slots'], name:'dsh-brain'}
|
||||
src-client/api.ts ← API 常量 + request/postJson/messageOf/bodyError
|
||||
src-client/format.ts ← formatTime/formatIso/formatBytes/shortHash/readStored/store + 标签表
|
||||
src-client/components.tsx ← Pill/Banner/Field/Btn/IconBtn/Switch/Toggle/Section/CardBoundary
|
||||
src-client/bridge.ts ← bridgeCall/bridgeMessage(MCP 宿主桥探测)
|
||||
src-client/sections/*.tsx ← MarketSection/SyncResolveSection/McpCustomSection/McpConfigSection/ImportSection
|
||||
src-client/SettingsCard.tsx ← 主体(三页签状态机原样搬)
|
||||
src-client/styles.ts ← 现 styles 对象暂原样保留(U1 起新样式走 .module.css)
|
||||
迁移规则:var→const/let、function 组件补 props 类型(宽松 any 起步,后续收紧)、
|
||||
h=React.createElement 保留或改 jsx(tsdown jsx:'automatic' 需 react/jsx-runtime external,
|
||||
建议保留 h 写法减少差异)。
|
||||
2. 新建根 tsdown.config.ts,只含 client 段(host lib 仍走 tsc,不动):
|
||||
```ts
|
||||
import type { UserConfig } from 'tsdown'
|
||||
const PLUGIN_ID = 'dsh-brain'
|
||||
export default {
|
||||
name: PLUGIN_ID + '/client',
|
||||
entry: { index: 'src-client/index.ts' },
|
||||
outDir: 'client',
|
||||
format: 'cjs',
|
||||
platform: 'browser',
|
||||
target: 'es2022',
|
||||
fixedExtension: false,
|
||||
outExtensions: () => ({ js: '.js' }),
|
||||
dts: false, sourcemap: false, clean: false,
|
||||
deps: { neverBundle: [/^react(?:\/.*)?$/, /^react-dom(?:\/.*)?$/] },
|
||||
define: { 'process.env.NODE_ENV': '"production"' },
|
||||
plugins: [clientCssPlugin()], // U1 再启用;U0 可先空数组
|
||||
outputOptions: {
|
||||
banner: `window.__ModuleLoader__.load({ id: '${PLUGIN_ID}', factory: (require) => {`,
|
||||
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
||||
footer: 'return module.exports; } });',
|
||||
},
|
||||
} satisfies UserConfig
|
||||
```
|
||||
css 插件从 vendor/dsh-mnemon/tsdown.config.ts 的 clientCssPlugin 抄(lightningcss
|
||||
transform → style 注入),vendor 已是 devDep 链内可用?——**核对 lightningcss 是否
|
||||
已在 node_modules(tsdown 自带依赖)**;若不可直接 import,用 tsdown 内置 css 处理
|
||||
(modules 选项)替代,产物同样内联。U0 阶段无 css 文件,插件可后置到 U1。
|
||||
3. package.json scripts:
|
||||
"build:client": "tsdown"
|
||||
"build": "tsc -p tsconfig.build.json && tsdown"
|
||||
"prepack": "tsc -p tsconfig.build.json && tsdown"
|
||||
tsconfig.json / tsconfig.build.json 的 include 排除 src-client(避免 host tsc 双编译);
|
||||
新增 tsconfig.client.json(extends 根,include src-client,jsx react-jsx,noEmit true)
|
||||
并把 typecheck 改为 "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit"。
|
||||
4. 旧手写版备份:cp client/index.js artifacts/analysis/client-legacy.js(artifacts 已 gitignore)。
|
||||
5. 新增 verify-client-build.mjs(仓库根,harness 风格照抄 verify-departments.mjs):
|
||||
- 读 client/index.js 断言:含 __ModuleLoader__.load、id:'dsh-brain'、
|
||||
'settings.section'、'plugins.bundle.config'、三页签标签(连接与上报/技能管理/MCP 管理)。
|
||||
- 用 vm + react shim require 产物,调 apply({slots:{inject:(seat,cb)=>{…记录}}}),
|
||||
断言两个 seat 注册回调可触发、组件渲染不抛(react shim 用 node_modules/react 真身,
|
||||
createElement 返回普通对象即可,不需要 DOM)。
|
||||
- 与 artifacts/analysis/client-legacy.js 做"行为面"对比:两版 apply 注册的 seat/options
|
||||
JSON 形状一致(order/id/key/label() 输出)。
|
||||
|
||||
## 验收
|
||||
npm run typecheck && npm run build && node verify-client-build.mjs
|
||||
node scripts/verify-all.mjs # 39 脚本口径不回退
|
||||
git status:client/index.js 变更 + src-client/ 新增 + 配置,全部入库。
|
||||
commit:build(client): migrate hand-written bundle to tsdown with equivalent output
|
||||
|
||||
═══════════════════════════════════════════
|
||||
U1 · 左栏总面板骨架(1 天)
|
||||
═══════════════════════════════════════════
|
||||
|
||||
## 可抄源码(vendor/dsh-mnemon/src/client/,MIT 保留声明)
|
||||
- shared/store.ts ExternalStore(~40 行,整抄改前缀)
|
||||
- shared/dom-seat.ts HeldSeat + createRafCoalescer(整抄)
|
||||
- native-sidebar.tsx mountMnemonSidebarNavigation 的双 seat 注册模式:
|
||||
ctx.slots.inject('main', () => ctx.slots.inject('sidebar.panellist', () => {
|
||||
register main {name:'main', key:PANEL_ID, inject:()=>({…})}
|
||||
register panellist {name:'sidebar.panellist', id:PANEL_ID, order:30, label:()=>'Brain'}
|
||||
}))
|
||||
**简化**:Mnemon 的 fallback DOM 注入(mountMnemonSidebarEntry/coordinateSidebarPanels)
|
||||
不抄——seat 不可用时本项目回退设置卡+独立页,不做 DOM 接管。
|
||||
- MnemonWorkspace.module.css(2KB 全文已核):nativeWorkspace/windowDragBand/entry 系列
|
||||
抄骨架,data-dsh-brain-mnemon-* 属性改 data-dsh-brain-*;配色全走
|
||||
--dsw-alias-* token(verify-theme 口径:无纯白纯黑硬编码)。
|
||||
- panelInfo 激活判定:ctx.layout.panelInfo.{getSnapshot,subscribe},
|
||||
activePanelId !== PANEL_ID 时暂停轮询(照抄 MnemonMainPanel 的 usePanelInfo)。
|
||||
|
||||
## 新文件
|
||||
src-client/panel/seat.ts ← ExternalStore/HeldSeat(抄改)
|
||||
src-client/panel/register.ts ← registerBrainPanel(ctx): 双 seat + disposer;
|
||||
PANEL_ID='dsh-brain';order 30;
|
||||
glyph svg data-dsh-panel-entry="dsh-brain";
|
||||
seat 缺席静默(inject 回调不触发即降级)
|
||||
src-client/panel/BrainPanel.tsx ← 页签壳:概览/记忆/部门/技能/MCP/连接与上报;
|
||||
本轮实现"概览"+"连接与上报",其余占位;
|
||||
根 div data-dsh-plugin="dsh-brain" + windowDragBand
|
||||
src-client/panel/Overview.tsx ← GET /dsh-brain/status + /capabilities 聚合卡片
|
||||
(版本、五 bundle 开关态、本地记忆状态、同步统计),
|
||||
15s 轮询仅激活时跑
|
||||
src-client/panel/BrainPanel.module.css ← 抄 vendor css 骨架
|
||||
src-client/panel/brain-icon.tsx ← 脑形 glyph(参考 vendor memory-icon.tsx 简化自绘)
|
||||
|
||||
## 改动
|
||||
- src-client/index.ts apply:保留 settings.section/plugins.bundle.config 注册;
|
||||
新增 registerBrainPanel(ctx)(经 ctx.effect 挂 disposer)。
|
||||
- SettingsCard 瘦身:settings.section 的卡内容改为状态摘要 + "打开总面板"按钮:
|
||||
onClick → typeof ctx.layout?.selectPanel==='function' ? ctx.layout.selectPanel('dsh-brain')
|
||||
: window.open('/dsh-brain')。原三页签完整内容迁入 BrainPanel 的对应页签
|
||||
(connection 本轮搬,skills/mcp 在 U2 后随占位替换——**本轮先把现有 SettingsCard
|
||||
整体作为"连接与上报"页签内容复用,避免大改**)。
|
||||
- inject 声明:['slots'] 不变(layout 经 ctx.get 探测,不硬依赖)。
|
||||
|
||||
## 验收
|
||||
verify-client-build.mjs 扩展:panellist/main 注册断言、PANEL_ID、order 30、
|
||||
降级分支(无 seat 时 apply 不抛)、glyph 语义锚点字符串。
|
||||
typecheck + build + verify-all 全绿。
|
||||
commit:feat(ui): left-rail Brain panel with overview and connection tabs
|
||||
|
||||
═══════════════════════════════════════════
|
||||
U2 · 记忆/部门页签(1 天,可与 U3 并行)
|
||||
═══════════════════════════════════════════
|
||||
|
||||
## API 契约(已实测响应形状)
|
||||
GET /dsh-brain/local-memory/status → {ok,provider:'local',globalRoot,projectRoot,spaces:{global,project},cloudSyncEnabled,localMemoryEnabled}
|
||||
GET /dsh-brain/local-memory/spaces → {ok,spaces:[…]}
|
||||
GET /dsh-brain/local-memory/documents → {ok,documents:[…]}
|
||||
GET /dsh-brain/local-memory/memories?limit&offset → {ok,total,items:[{id,scope,content,category,tags,source,revision,updatedAt}]}
|
||||
POST /dsh-brain/local-memory/forget {id,expectedRevision?} → 同源闸门
|
||||
GET /dsh-brain/departments/list?scope → {ok,departments:[Department]}
|
||||
POST /dsh-brain/departments/create {name,role?,scope?,skills?,allowedTools?,readGlobal?,readProject?,workspace?}
|
||||
POST /dsh-brain/departments/update {id,…patch,expectedRevision?,workspace?}
|
||||
POST /dsh-brain/departments/disable {id,expectedRevision?,workspace?}
|
||||
POST /dsh-brain/departments/checkpoint {id,currentTask?,handoff?,expectedRevision?,workspace?}
|
||||
GET /dsh-brain/departments/recall?id&query&k&workspace → {ok,hits:[{origin,record,content,contentSnippet}]}
|
||||
POST /dsh-brain/departments/resume {id,host?,hostSessionId?,workspace?}
|
||||
错误码:400 name-required/invalid-json;403 origin-rejected;404 department_not_found;
|
||||
409 revision_conflict/department_disabled;503 local-memory-disabled/departments-unavailable。
|
||||
|
||||
## 新文件
|
||||
src-client/panel/MemoryTab.tsx ← 空间状态卡 + 记忆列表(分页 limit 50)+ 前端搜索过滤
|
||||
+ forget 按钮(确认弹窗)+ 文档列表只读
|
||||
src-client/panel/DepartmentTab.tsx ← 部门列表(name/scope/active/currentTask/revision)
|
||||
+ 创建表单 + 详情抽屉(update/disable/checkpoint)
|
||||
+ recall 查询框(展示 contentSnippet,标注 origin)
|
||||
+ 409 → "数据已变化,请刷新" 提示条
|
||||
src-client/panel/useApi.ts ← 轮询/加载状态机助手(idle/loading/ready/error),
|
||||
错误条复用 Banner;visible=false 暂停
|
||||
workspace 取值:ctx.get('sessions') 面探测当前会话 cwd(参考 vendor session-binding.ts
|
||||
的 useMnemonSessionId 模式,简化为一次性读取);取不到则省略参数。
|
||||
|
||||
## 约束
|
||||
- 零新后端路由;不改 departments-routes.ts(保护期)。
|
||||
- recall k 输入框 max=5;snippet 展示直接用服务端 contentSnippet。
|
||||
- 所有 POST 走 postJson(同源自动满足)。
|
||||
|
||||
## 验收
|
||||
verify-client-build 断言两页签组件存在、API 路径字符串齐全;
|
||||
手工冒烟:起真实 server(参考 verify-brain-panel.mjs 夹具)核对每个消费路由 200。
|
||||
typecheck + build + verify-all 全绿。
|
||||
commit:feat(ui): memory and department tabs in the Brain panel
|
||||
|
||||
═══════════════════════════════════════════
|
||||
U3 · better-sidebar 项目记忆页签(0.5 天)
|
||||
═══════════════════════════════════════════
|
||||
|
||||
## 可抄源码
|
||||
vendor/dsh-mnemon/src/client/better-sidebar.tsx(全文 2.4KB 已核):
|
||||
mountBetterSidebarTab 的 reconcile 模式——ctx.get('betterSidebar') 探测 +
|
||||
ctx.on('internal/service', name => name==='betterSidebar' && reconcile()) 热插拔 +
|
||||
disposer 链。**整抄改前缀**,descriptor 换成本项目:
|
||||
{ id:'dsh-brain:memory', title:()=>'项目记忆',
|
||||
description:'当前会话项目的本地记忆:空间/条目/搜索/部门召回',
|
||||
icon:size=><BrainIcon size={size}/>, order:60, single:true,
|
||||
component:({scope,visible}) => <ProjectMemoryView scope={scope} visible={visible}/> }
|
||||
|
||||
## 新文件
|
||||
src-client/sidebar/register.ts ← mountBrainSidebarTab(ctx)(抄改)
|
||||
src-client/sidebar/ProjectMemoryView.tsx ← 只读视图:status + memories 列表 + 搜索
|
||||
+ recall 查询(部门选择下拉);
|
||||
visible=false 暂停轮询(契约);
|
||||
重操作按钮"去总面板"→ selectPanel('dsh-brain')
|
||||
src-client/sidebar/ProjectMemory.module.css ← betterSidebarSeat 骨架抄 vendor
|
||||
|
||||
## 降级链
|
||||
无 betterSidebar 服务 → reconcile 不注册,静默;服务后到 → internal/service 触发补注册;
|
||||
fiber 卸载 → disposer 自动清理。总面板不受影响。
|
||||
|
||||
## 验收
|
||||
verify-client-build 断言:registerTab 探测、descriptor id/order/single、
|
||||
internal/service 监听、visible 暂停分支、无服务时 apply 不抛。
|
||||
typecheck + build + verify-all 全绿。
|
||||
commit:feat(ui): project-memory tab for better-sidebar with graceful fallback
|
||||
|
||||
═══════════════════════════════════════════
|
||||
U4 · 彻底改名 + 迁移 + 终验(0.5 天)
|
||||
═══════════════════════════════════════════
|
||||
|
||||
## 改名清单(一处不漏,已实测现状)
|
||||
1. src/entries/settings-ui.ts → src/entries/ui.ts:
|
||||
export name='dsh-brain-ui';kernel.activate('ui')/deactivate('ui');
|
||||
effect 标签 'dsh-brain-ui: …';头注释更新。
|
||||
2. src/kernel.ts L48:BrainBundle 类型 'settings-ui'→'ui';L5 注释同步。
|
||||
3. package.json exports:加 './ui':'./lib/entries/ui.js';
|
||||
**保留 './settings-ui':'./lib/entries/ui.js'(别名指向新文件)**。
|
||||
4. cordis.patch.yml:insert 行 id:'dsh-brain-ui',name:'dsh-brain/ui'。
|
||||
5. src/index.ts compat root:import * as ui from './entries/ui.ts';ui.apply(...)。
|
||||
6. src/settings-ui/ 目录暂不改名(departments-routes.ts 保护期);
|
||||
entry 内 import 路径不变。目录搬迁留待复验通过后单独 commit。
|
||||
7. 旧 id 迁移探测:ui entry apply 开头读宿主 patch 面(若 ctx 暴露)或
|
||||
logger.info 提示"若你曾禁用 dsh-brain-settings-ui,请在设置→插件重新禁用 dsh-brain-ui"。
|
||||
**不自动改写宿主文件**。README 升级节写明。
|
||||
8. verify-plugin-entry.mjs:import './lib/entries/ui.js';断言文案改 ui;
|
||||
加一条兼容断言:import './lib/entries/settings-ui.js'(exports 别名)仍可用。
|
||||
9. README 五行表 id 列、docs/management-surface.md 提及同步。
|
||||
10. lib/ 产物:build 后 lib/entries/ui.js 新增;lib/entries/settings-ui.js 由
|
||||
exports 别名兜底——**物理文件也保留一份 re-export**(export * from './ui.js'),
|
||||
防老 profile 直接路径解析绕过 exports map。
|
||||
|
||||
## 终验(全绿才报完成)
|
||||
npm run typecheck && npm run build
|
||||
node scripts/verify-all.mjs && node verify-plugin-entry.mjs && node verify-client-build.mjs
|
||||
npm pack --dry-run # files 含 client/index.js、lib/entries/ui.js、lib/entries/settings-ui.js
|
||||
宿主冒烟(升级 profile 依赖后另行授权,不在本卡):
|
||||
左栏 Brain 行/总面板六页签/better-sidebar 页签/设置卡/独立页/legacy 别名 六处核对。
|
||||
commit:refactor(ui)!: rename settings-ui bundle to dsh-brain-ui with export alias
|
||||
|
||||
═══════════════════════════════════════════
|
||||
全局硬约束
|
||||
═══════════════════════════════════════════
|
||||
- 运行时零新依赖;tsdown/react 均已在 devDeps。
|
||||
- client 产物单文件 __ModuleLoader__ IIFE,id:'dsh-brain' 不变(row id 才改)。
|
||||
- 保护期禁改四文件(见头部);可 import 其导出。
|
||||
- 每卡独立 commit + 该卡验证命令;lib/ 与 client/index.js 产物随卡入库。
|
||||
- 样式走 --dsw-alias-* token,无纯白纯黑硬编码(verify-theme 会查)。
|
||||
- 与现状不符:停下报告差异,等规划侧修订,不自行改方案。
|
||||
- vendor 源码抄改处保留 MIT 出处注释(// Adapted from dsh-mnemon (MIT), see vendor/dsh-mnemon/LICENSE)。
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
# UI 改造 U0–U4 可执行任务卡(给 DeepSeek)
|
||||
|
||||
版本:v1(2026-11-24 23:35)
|
||||
基线:89e67d0(部门 FAIL 修复已入库推送,待 GPT 复验——**UI 开工不等复验,但不得触碰
|
||||
src/memory/departments-tools.ts、src/settings-ui/departments-routes.ts、src/skill-sync.ts**,
|
||||
避免与复验/修复线冲突)。
|
||||
决策已定(用户拍板):**选项 B 借壳不借芯** + **bundle id 彻底改名 dsh-brain-ui**。
|
||||
上游方案:UI_PLAN.md(§0.5 三选项评估、§2 改名边界、§3 切片)。
|
||||
**详细实施规格:UI_SPEC.md**(文件级改动清单、可抄源码位置、代码骨架、API 契约、逐卡验收命令)——执行以 UI_SPEC.md 为准,本卡为总览。
|
||||
|
||||
## 总览
|
||||
|
||||
| 卡 | 内容 | 依赖 | 预估 |
|
||||
| --- | --- | --- | --- |
|
||||
| U0 | client 构建链落地(tsdown,devDep 已有)+ 现有 client 迁 TS 源 | 无 | 0.5–1 天 |
|
||||
| U1 | 左栏总面板骨架(panellist+main 双 seat,抄 Mnemon 接入层) | U0 | 1 天 |
|
||||
| U2 | 记忆/部门页签并入总面板(消费既有 HTTP 路由) | U1 | 1 天 |
|
||||
| U3 | better-sidebar "项目记忆"页签(registerTab + 降级) | U1 | 0.5 天 |
|
||||
| U4 | bundle 彻底改名 settings-ui → ui(含迁移)+ 终验 | U1–U3 | 0.5 天 |
|
||||
| U5 | 诊断日志 .dsh/brain/logs(JSONL/脱敏/滚动),详见 LOGGING_SPEC.md | 可与 U2/U3 并行 | 0.5–1 天 |
|
||||
|
||||
每卡独立 commit;U2/U3/U5 可并行。总量约 4–5 天。
|
||||
升级批次(用户拍板 2026-11-24):**先不升级宿主**,U0–U5 全部完成 + GPT 部门复验通过后一次升级。
|
||||
|
||||
---
|
||||
|
||||
## U0 · client 构建链(先决)
|
||||
|
||||
现状:client/index.js 是 3735 行手写 IIFE(__ModuleLoader__ 契约);
|
||||
devDependencies **已含 tsdown ^0.22.2**(无需新增依赖!);vendor/dsh-mnemon/tsdown.config.ts
|
||||
有现成的 client 构建配置可抄(banner/footer/intro 包裹 __ModuleLoader__、css modules 内联插件、
|
||||
react externals)。
|
||||
|
||||
1. 新建 src-client/(或 client-src/)目录放 TS 源;把现有 client/index.js 的逻辑
|
||||
**原样迁为 TS**(第一步不求重构,求字节级行为等价):
|
||||
- 入口 src-client/index.ts,导出 { apply, inject, name:'dsh-brain' }。
|
||||
- 现有 SettingsCard 三页签、API 常量、request 助手、CardBoundary 全部搬入。
|
||||
2. 新建 tsdown.config.ts(根目录),client 段照抄 vendor 配置:
|
||||
- format:'cjs'、platform:'browser'、target:'es2022'、deps.neverBundle:[/^react(?:\/.*)?$/]
|
||||
- outputOptions.banner/intro/footer 生成 window.__ModuleLoader__.load({id:'dsh-brain',factory:(require)=>{…}})
|
||||
- 产物固定写 **client/index.js**(outDir:'client',entry:{index:'src-client/index.ts'},
|
||||
outExtensions 强制 .js;clean:false 防误删)。
|
||||
- css modules 内联插件从 vendor 抄(lightningcss transform → 注入 style),
|
||||
U1 起样式用 .module.css。
|
||||
3. package.json scripts 加 "build:client": "tsdown";"build" 改为
|
||||
"tsc -p tsconfig.build.json && tsdown"(host lib 与 client 一起出)。
|
||||
prepack 同步。tsconfig.json include 排除 src-client(走 tsdown 自己的转译,
|
||||
或单列 tsconfig.client.json——二选一,保证 npm run typecheck 仍覆盖 host src)。
|
||||
4. **等价门禁**:构建后 client/index.js 与迁移前手写版做行为对比——
|
||||
新增 verify-client-build.mjs:断言产物含 __ModuleLoader__.load、id:'dsh-brain'、
|
||||
settings.section/plugins.bundle.config 注册、三页签标签字符串;
|
||||
再起临时 http server 用 jsdom-free 方式静态 require 产物(react shim)验证 apply 不抛。
|
||||
旧手写版先备份到 artifacts/analysis/client-legacy.js(gitignore 内)供比对。
|
||||
5. .gitignore 确认 client/index.js **仍入库**(发布件),src-client/ 入库。
|
||||
|
||||
commit:build(client): migrate hand-written bundle to tsdown with byte-equivalent output
|
||||
验证:npm run typecheck && npm run build && node verify-client-build.mjs && verify-all 不回退。
|
||||
|
||||
## U1 · 左栏总面板骨架
|
||||
|
||||
抄 Mnemon 接入层(vendor/dsh-mnemon/src/client/):
|
||||
- native-sidebar.tsx:mountMnemonSidebarNavigation 的 panellist+main 双 slots.inject、
|
||||
usePanelInfo 激活判定、window-drag band、glyph 语义锚点。
|
||||
- shared/dom-seat.ts 的 HeldSeat、shared/store.ts 的 ExternalStore(小文件,直接搬改前缀)。
|
||||
- workspace-mount.tsx 的 coordinateSidebarPanels 协调逻辑按需简化。
|
||||
|
||||
落点(src-client/):
|
||||
1. panel.ts:PANEL_ID='dsh-brain';registerBrainPanel(ctx):
|
||||
- slots.inject('sidebar.panellist', () => slots.register({name:'sidebar.panellist',
|
||||
id:PANEL_ID, order:30, label:()=>'Brain'}, BrainPanelIcon))
|
||||
- slots.inject('main', () => slots.register({name:'main', key:PANEL_ID,
|
||||
inject:()=>({…})}, BrainPanel))
|
||||
- glyph svg 带 data-dsh-panel-entry="dsh-brain";面板根带 data-dsh-plugin="dsh-brain"。
|
||||
- seat 不存在时静默(slots.inject 回调不触发即天然降级),console.info 一次。
|
||||
2. BrainPanel 组件:页签壳(概览/记忆/部门/技能/MCP/连接与上报),
|
||||
本轮先实现"概览"(GET status+capabilities 聚合卡片)与"连接与上报"
|
||||
(现有 SettingsCard connection 页签内容搬入);其余页签占位"即将上线"。
|
||||
轮询仅面板激活时跑(usePanelInfo),15s 间隔沿用现状。
|
||||
3. 设置卡瘦身:settings.section 注册保留,内容改为状态摘要 + "打开总面板"按钮
|
||||
(经 ctx.layout.selectPanel(PANEL_ID)——该服务面参考 task-board/mnemon 用法,
|
||||
typeof 探测,不可用时回退 window.open('/dsh-brain'))。
|
||||
4. 样式:BrainPanel.module.css 布局抄 MnemonWorkspace.module.css 的骨架
|
||||
(nativeWorkspace/windowDragBand/entry 系列),配色用宿主中性 token,不硬编码纯白纯黑
|
||||
(verify-theme 口径)。
|
||||
|
||||
commit:feat(ui): left-rail Brain panel with overview and connection tabs
|
||||
验证:verify-client-build.mjs 扩展断言(panellist/main 注册、PANEL_ID、降级分支);
|
||||
typecheck+build+verify-all 全绿。宿主冒烟留 U4。
|
||||
|
||||
## U2 · 记忆/部门页签
|
||||
|
||||
数据面零新后端,全部既有路由(UI_PLAN §4):
|
||||
1. 记忆页签:GET /dsh-brain/local-memory/status|spaces|documents|memories?limit&offset;
|
||||
列表+搜索框(前端过滤当前页即可,不做服务端搜索新路由)+分页;
|
||||
forget 按钮走 POST /dsh-brain/local-memory/forget(同源天然满足)。
|
||||
2. 部门页签:GET /dsh-brain/departments/list;create/update/disable/checkpoint 表单
|
||||
POST 对应子路由;recall 查询框 GET /departments/recall?id&query&k&workspace;
|
||||
展示 contentSnippet(≤600)而非全文;revision 冲突 409 显示"数据已变化,请刷新"。
|
||||
3. 错误条组件复用 CardBoundary 模式:路由失败显示可行动文案,不白屏。
|
||||
4. workspace 参数:面板处于会话上下文时经 ctx sessions 面取当前会话 cwd 传入;
|
||||
取不到则省略(服务端回落 process.cwd() 语义)。
|
||||
|
||||
commit:feat(ui): memory and department tabs in the Brain panel
|
||||
验证:verify-client-build 断言两页签路由消费;手工冒烟脚本起真实 server 核对 JSON 形状;
|
||||
verify-all 不回退。**不得改 departments-routes.ts/departments-tools.ts**(复验保护期)。
|
||||
|
||||
## U3 · better-sidebar 项目记忆页签
|
||||
|
||||
抄 vendor better-sidebar.tsx 的 mountBetterSidebarTab 模式(reconcile + internal/service 监听):
|
||||
1. src-client/better-sidebar.ts:detect ctx.get('betterSidebar'),存在则
|
||||
ctx.effect(() => service.registerTab(descriptor));监听 'internal/service' 热插拔;
|
||||
不存在静默跳过(总面板不受影响)。
|
||||
2. descriptor:id:'dsh-brain:memory',title:'项目记忆',description:'当前会话项目的本地记忆:空间/条目/搜索/部门召回',
|
||||
single:true,order:60,icon 自绘脑形 svg(可参考 MnemonLogo/memory-icon 简化)。
|
||||
3. component(props:TabComponentProps):scope.sessionId/cwd → 项目空间只读视图
|
||||
(status+memories 列表+搜索+recall);**visible=false 暂停一切轮询**(契约);
|
||||
重操作(建部门/forget)引导"去总面板"按钮(selectPanel)。
|
||||
4. 降级链测试:无 betterSidebar 服务时 apply 不抛、无注册。
|
||||
|
||||
commit:feat(ui): project-memory tab for better-sidebar with graceful fallback
|
||||
验证:verify-client-build 断言 registerTab 探测/disposer/visible 暂停逻辑;verify-all 不回退。
|
||||
|
||||
## U4 · 彻底改名 settings-ui → ui + 迁移 + 终验
|
||||
|
||||
改名清单(一处不漏):
|
||||
1. src/entries/settings-ui.ts → src/entries/ui.ts;export name='dsh-brain-ui';
|
||||
kernel.activate('ui');effect 标签前缀改 'dsh-brain-ui:'。
|
||||
2. src/kernel.ts:BrainBundle 类型 'settings-ui'→'ui';注释同步。
|
||||
3. package.json exports:'./ui':'./lib/entries/ui.js';**保留 './settings-ui' 别名**
|
||||
指向同一文件(老 profile 行不断)。
|
||||
4. cordis.patch.yml:insert 行 id:'dsh-brain-ui',name:'dsh-brain/ui'。
|
||||
5. src/index.ts compat root:import * as ui from './entries/ui.ts'。
|
||||
6. src/settings-ui/ 目录(page.ts/routes.ts/departments-routes.ts)→ src/ui/?
|
||||
**注意:departments-routes.ts 在复验保护期,本卡只改 import 路径不改其内容**;
|
||||
若 GPT 复验尚未结束,目录搬迁推迟到复验通过后(改名先只动 entry/kernel/exports/patch 四处,
|
||||
目录名 settings-ui 暂留,单独后续 commit 搬)。
|
||||
7. **旧 id 迁移**:宿主 profile patch 里可能存在 '- id: dsh-brain-settings-ui' 禁用/配置行
|
||||
(本机实测 desktop/web 均无,但其他机器可能有)。在 ui entry apply 开头做一次迁移探测:
|
||||
读 ctx 配置面若发现旧 id 行,logger.warn 提示用户在新行重设;
|
||||
不自动改写宿主文件(越权)。README 升级说明写明此点。
|
||||
8. verify-plugin-entry.mjs:import 路径改 lib/entries/ui.js,断言名改 'ui entry …';
|
||||
兼容断言:require('./lib/entries/settings-ui.js') 别名仍可用(exports 别名生效)。
|
||||
9. README 五行表、docs/management-surface.md 的 id 提及同步。
|
||||
|
||||
终验(全绿才报完成):
|
||||
npm run typecheck && npm run build
|
||||
node scripts/verify-all.mjs # 39+ 脚本口径不回退
|
||||
node verify-plugin-entry.mjs
|
||||
node verify-client-build.mjs
|
||||
npm pack --dry-run # files 含 client/index.js + lib/entries/ui.js
|
||||
宿主冒烟(升级 profile 依赖后,另行授权):
|
||||
左栏 Brain 行 → 总面板六页签;better-sidebar + 菜单"项目记忆";
|
||||
设置卡仍在;/dsh-brain 独立页可达;旧 /cloud-memory 别名可达。
|
||||
|
||||
commit:refactor(ui)!: rename settings-ui bundle to dsh-brain-ui with export alias
|
||||
(breaking 标记仅指内部 id;exports 别名保证老 profile 不断。)
|
||||
|
||||
## 硬约束(全卡通用)
|
||||
|
||||
- 运行时零新依赖(tsdown 已在 devDeps;react 走宿主 shim externals)。
|
||||
- 复验保护期不碰:departments-tools.ts / departments-routes.ts / skill-sync.ts /
|
||||
src/local-memory/departments/。
|
||||
- client 产物必须仍是单文件 __ModuleLoader__ IIFE,id:'dsh-brain' 不变(client bundle id
|
||||
与子插件 row id 是两回事,后者才改 dsh-brain-ui)。
|
||||
- 每卡 commit 前跑该卡验证;lib/ 与 client/index.js 产物随卡入库。
|
||||
- 遇到与本卡不符的代码现状:停下报告差异,等规划侧修订。
|
||||
319
lib/api.js
319
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: {} };
|
||||
// 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 {
|
||||
return { ok: true, status: response.status, data: JSON.parse(text) };
|
||||
parsed = JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: 'response was not JSON' } };
|
||||
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 };
|
||||
}
|
||||
/** 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,29 +521,46 @@ 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}` } };
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Render a {@link CloudError} as one display line. */
|
||||
export function describeError(error) {
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import { readFile, readdir, stat } from 'node:fs/promises';
|
|||
import { homedir } from 'node:os';
|
||||
import { join, resolve, sep } from 'node:path';
|
||||
import { dshHome, migrateLegacyFile } from "./store.js";
|
||||
import { parseSkillFrontmatter } from "./skill-sync.js";
|
||||
import { parseSkillFrontmatter } from "./skills/shared.js";
|
||||
import { SkillAdmin } from "./skill-admin.js";
|
||||
/** Manual workspace additions live in the plugin's own metadata file. */
|
||||
export function manualWorkspacesPath() {
|
||||
|
|
@ -108,14 +108,10 @@ export class ClientRegistry {
|
|||
throw new Error('unknown_workspace');
|
||||
const skillsRoot = resolve(workspace.path, '.dsh', 'skills');
|
||||
const holdingDir = join(dshHome(), 'skills-workspace-disabled', workspace.id);
|
||||
const stateName = `${workspace.id.replace(/[^A-Za-z0-9_-]/g, '_')}.json`;
|
||||
const statePath = join(dshHome(), `dsh-brain-workspace-${stateName}`);
|
||||
migrateLegacyFile(statePath, join(dshHome(), `cloud-memory-workspace-${stateName}`));
|
||||
const admin = new SkillAdmin({
|
||||
skillsRoot: () => skillsRoot,
|
||||
holdingDir: () => holdingDir,
|
||||
syncStatePath: () => statePath,
|
||||
syncRunning: () => false,
|
||||
gate: () => ({ isRunning: () => false, provenance: async () => null }),
|
||||
log: () => { },
|
||||
});
|
||||
return { admin, workspace };
|
||||
|
|
|
|||
|
|
@ -0,0 +1,316 @@
|
|||
import { describeError, isSecureLoginTarget } from "./api.js";
|
||||
import { fail, json, jsonBody, readBody, sameOrigin } from "./http.js";
|
||||
/** Path constants — kept in sync with the ROUTES map in routes.ts by hand. */
|
||||
const PATHS = {
|
||||
login: '/dsh-brain/login',
|
||||
test: '/dsh-brain/test',
|
||||
flush: '/dsh-brain/flush',
|
||||
sync: '/dsh-brain/sync',
|
||||
};
|
||||
/** Last test run, kept in memory so the card can show "最后检查". */
|
||||
let lastCheck = null;
|
||||
/** The root status view reads the same probe memory; one source of truth. */
|
||||
export function getLastCheck() {
|
||||
return lastCheck;
|
||||
}
|
||||
/** Labels attached to the tokens this plugin asks the dashboard to mint. */
|
||||
const TOKEN_LABELS = {
|
||||
activity: 'DSH desktop 活动上报',
|
||||
memory: 'DSH desktop 记忆读写',
|
||||
summary: 'DSH desktop 对话摘要',
|
||||
};
|
||||
/** Map one failed credential probe onto a check state. */
|
||||
function checkState(error) {
|
||||
if (error.status === 0)
|
||||
return 'unreachable';
|
||||
if (error.status === 401)
|
||||
return 'invalid';
|
||||
if (error.status === 403)
|
||||
return 'forbidden';
|
||||
return 'error';
|
||||
}
|
||||
/** `POST /dsh-brain/test` — read-only checks, one per credential. */
|
||||
async function serveTest(deps, req, res) {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
const client = deps.client();
|
||||
const checks = [];
|
||||
const settings = deps.store.settings();
|
||||
const reach = await client.reach();
|
||||
checks.push({
|
||||
id: 'network',
|
||||
label: '服务地址',
|
||||
state: reach.ok ? 'ok' : 'unreachable',
|
||||
message: deps.store.describe().baseUrlConfigured === false ? '服务地址还是打包默认值,请先填写真实地址。' : reach.message,
|
||||
});
|
||||
const activityToken = deps.store.activityToken();
|
||||
if (activityToken === '') {
|
||||
checks.push({ id: 'activity', label: '活动上报权限(activity:write)', state: 'unconfigured', message: '未配置令牌' });
|
||||
}
|
||||
else {
|
||||
const probe = await client.probeActivity(activityToken);
|
||||
checks.push({
|
||||
id: 'activity',
|
||||
label: '活动上报权限(activity:write)',
|
||||
state: probe.ok ? 'ok' : checkState(probe.error),
|
||||
message: probe.ok ? '鉴权通过(只验证权限,不代表已写入一条上报)' : describeError(probe.error),
|
||||
});
|
||||
}
|
||||
const memoryToken = deps.store.memoryToken();
|
||||
if (memoryToken === '') {
|
||||
checks.push({ id: 'memory', label: '记忆读写权限(memory:write)', state: 'unconfigured', message: '未配置令牌' });
|
||||
}
|
||||
else {
|
||||
const probe = await client.projects();
|
||||
checks.push({
|
||||
id: 'memory',
|
||||
label: '记忆读写权限(memory:write)',
|
||||
state: probe.ok ? 'ok' : checkState(probe.error),
|
||||
message: probe.ok ? `鉴权通过(${(probe.data.projects ?? []).length} 个项目)` : describeError(probe.error),
|
||||
});
|
||||
}
|
||||
const summaryToken = deps.store.summaryToken();
|
||||
if (!settings.summaryEnabled) {
|
||||
checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '自动摘要已关闭' });
|
||||
}
|
||||
else if (summaryToken === '') {
|
||||
checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '未配置摘要令牌(可选)' });
|
||||
}
|
||||
else {
|
||||
const probe = await client.probeSummary(summaryToken);
|
||||
checks.push({
|
||||
id: 'summary',
|
||||
label: '摘要权限(summary:write)',
|
||||
state: probe.ok ? 'ok' : checkState(probe.error),
|
||||
message: probe.ok ? '鉴权通过(只进待确认队列)' : describeError(probe.error),
|
||||
});
|
||||
}
|
||||
lastCheck = { at: Date.now(), checks };
|
||||
json(res, 200, {
|
||||
ok: true,
|
||||
checkedAt: lastCheck.at,
|
||||
checks,
|
||||
// Kept for the older card/page shape; both views read the same probes.
|
||||
activity: { ok: checks[1]?.state === 'ok', message: checks[1]?.message ?? '' },
|
||||
memory: { ok: checks[2]?.state === 'ok', message: checks[2]?.message ?? '' },
|
||||
summary: { ok: checks[3]?.state === 'ok', message: checks[3]?.message ?? '' },
|
||||
});
|
||||
}
|
||||
/** `POST /dsh-brain/flush`. */
|
||||
async function serveFlush(deps, req, res) {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
const result = await deps.reporter.flush();
|
||||
json(res, 200, { ok: true, ...result });
|
||||
}
|
||||
/**
|
||||
* `POST /dsh-brain/login` — sign in with the cloud account and exchange it
|
||||
* for the scoped tokens.
|
||||
*
|
||||
* The password is used once, in memory, and never written anywhere: the flow is
|
||||
* password → short-lived session cookie → tokens → cookie dropped. Only the
|
||||
* tokens are persisted, so a later password change does not break the plugin
|
||||
* and revoking a token does not reveal the password.
|
||||
*/
|
||||
async function serveLogin(deps, req, res) {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
let raw;
|
||||
try {
|
||||
raw = await readBody(req);
|
||||
}
|
||||
catch {
|
||||
fail(res, 413, 'request-too-large');
|
||||
return;
|
||||
}
|
||||
let body;
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
||||
throw new Error('object required');
|
||||
body = parsed;
|
||||
}
|
||||
catch {
|
||||
fail(res, 400, 'invalid-json');
|
||||
return;
|
||||
}
|
||||
const username = typeof body.username === 'string' ? body.username.trim() : '';
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
if (username === '' || password === '') {
|
||||
json(res, 400, { ok: false, error: '请填写用户名和密码' });
|
||||
return;
|
||||
}
|
||||
if (username.length > 64 || password.length > 256) {
|
||||
json(res, 400, { ok: false, error: '用户名或密码过长' });
|
||||
return;
|
||||
}
|
||||
const client = deps.client();
|
||||
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, 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;
|
||||
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 });
|
||||
return;
|
||||
}
|
||||
const failed = activity.ok ? memory : activity;
|
||||
const partial = !activity.ok || !memory.ok;
|
||||
json(res, 200, {
|
||||
...deps.statusView(),
|
||||
login: {
|
||||
ok: true,
|
||||
partial,
|
||||
user: {
|
||||
username: typeof session.data.user.username === 'string' ? session.data.user.username : username,
|
||||
role: session.data.user.role,
|
||||
},
|
||||
activity: activity.ok,
|
||||
memory: memory.ok,
|
||||
summary: summary.ok,
|
||||
warning: failed.ok ? undefined : `部分令牌没有创建成功:${describeError(failed.error)}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Sync surface:
|
||||
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
|
||||
* `POST /dsh-brain/sync/run` trigger one pass now
|
||||
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
|
||||
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud }
|
||||
*/
|
||||
async function serveSync(deps, req, res) {
|
||||
const sync = deps.sync;
|
||||
if (sync === undefined) {
|
||||
fail(res, 404, 'sync-unavailable');
|
||||
return;
|
||||
}
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
const suffix = url.pathname.slice(PATHS.sync.length);
|
||||
try {
|
||||
if (suffix === '' || suffix === '/' || suffix === '/status') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, stats: sync.stats(), conflicts: await sync.conflictDetails() });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/run') {
|
||||
// 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;
|
||||
}
|
||||
if (suffix === '/resolve') {
|
||||
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, body.conflictId);
|
||||
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/resolve-all') {
|
||||
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, body.conflictIds);
|
||||
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() });
|
||||
return;
|
||||
}
|
||||
fail(res, 404, 'unknown-sync-route');
|
||||
}
|
||||
catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const known = ['invalid_name', 'invalid_action', 'no_local_copy', 'no_cloud_copy', 'stale_revision', 'sync_running', 'manifest_mismatch'];
|
||||
const code = known.includes(message) ? message : 'internal';
|
||||
const status = code === 'internal' ? 500
|
||||
: code === 'invalid_name' || code === 'invalid_action' ? 400
|
||||
: 409;
|
||||
json(res, status, { ok: false, code, error: message });
|
||||
}
|
||||
}
|
||||
/** Cloud-sync routes; the root aggregator decides the registration order. */
|
||||
export function createCloudSyncRoutes(deps) {
|
||||
return [
|
||||
{ kind: 'exact', path: PATHS.login, handler: (req, res) => serveLogin(deps, req, res) },
|
||||
{ kind: 'exact', path: PATHS.test, handler: (req, res) => serveTest(deps, req, res) },
|
||||
{ kind: 'exact', path: PATHS.flush, handler: (req, res) => serveFlush(deps, req, res) },
|
||||
{ kind: 'prefix', path: PATHS.sync, handler: (req, res) => serveSync(deps, req, res) },
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
/**
|
||||
* Cloud-sync bundle — the remote side of the memory feature.
|
||||
*
|
||||
* This module owns the concrete transport: one cloud client per connection,
|
||||
* with the package settings sidecar as the fallback for any field the
|
||||
* connection left empty. The memory bundle consumes the `MemoryRemote`
|
||||
* contract and never sees this file — the composition root injects the
|
||||
* factory, so swapping the transport never touches the tools or the
|
||||
* Mnemon provider.
|
||||
*/
|
||||
import { CloudClient } from "./api.js";
|
||||
import { SettingsStore } from "./store.js";
|
||||
/** Build a factory over live settings closures (the composition root's path). */
|
||||
export function createCloudMemoryRemoteFactory(deps) {
|
||||
let shared;
|
||||
return {
|
||||
current: () => {
|
||||
shared ??= new CloudClient({
|
||||
baseUrl: () => deps.settings().baseUrl,
|
||||
token: () => deps.memoryToken(),
|
||||
timeoutMs: () => deps.settings().requestTimeoutMs,
|
||||
});
|
||||
return shared;
|
||||
},
|
||||
forConnection: (connection) => new CloudClient({
|
||||
baseUrl: () => connection.endpoint ?? deps.settings().baseUrl,
|
||||
token: () => connection.token ?? deps.memoryToken(),
|
||||
timeoutMs: () => connection.timeoutMs ?? deps.settings().requestTimeoutMs,
|
||||
}),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* The standalone Mnemon-provider path: the same factory, backed lazily by
|
||||
* the settings sidecar so a provider constructed before any configuration
|
||||
* still resolves against live settings at call time.
|
||||
*/
|
||||
export function createSidecarMemoryRemoteFactory() {
|
||||
let store;
|
||||
const ensure = () => {
|
||||
store ??= new SettingsStore({});
|
||||
return store;
|
||||
};
|
||||
return createCloudMemoryRemoteFactory({
|
||||
settings: () => ensure().settings(),
|
||||
memoryToken: () => ensure().memoryToken(),
|
||||
});
|
||||
}
|
||||
|
|
@ -6,6 +6,8 @@
|
|||
/** Defaults written into cordis.patch.yml; also the fallback for missing keys. */
|
||||
export const DEFAULT_SETTINGS = {
|
||||
enabled: true,
|
||||
activityEnabled: true,
|
||||
memoryEnabled: true,
|
||||
baseUrl: 'https://your-memory-host/api/longmemory',
|
||||
clientId: 'dsh-desktop',
|
||||
requestTimeoutMs: 5000,
|
||||
|
|
@ -14,6 +16,20 @@ 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,
|
||||
/** Diagnostic JSONL logs under .dsh/brain/logs; defaults on, inherits enabled. */
|
||||
diagnosticsEnabled: true,
|
||||
};
|
||||
const MIN_TIMEOUT_MS = 1000;
|
||||
const MAX_TIMEOUT_MS = 60_000;
|
||||
|
|
@ -85,6 +101,10 @@ export function settingsFromConfig(raw) {
|
|||
const result = {};
|
||||
if (typeof source.enabled === 'boolean')
|
||||
result.enabled = source.enabled;
|
||||
if (typeof source.activityEnabled === 'boolean')
|
||||
result.activityEnabled = source.activityEnabled;
|
||||
if (typeof source.memoryEnabled === 'boolean')
|
||||
result.memoryEnabled = source.memoryEnabled;
|
||||
const baseUrl = normalizeBaseUrl(source.baseUrl);
|
||||
if (baseUrl !== undefined)
|
||||
result.baseUrl = baseUrl;
|
||||
|
|
@ -106,5 +126,20 @@ 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;
|
||||
if (typeof source.diagnosticsEnabled === 'boolean')
|
||||
result.diagnosticsEnabled = source.diagnosticsEnabled;
|
||||
const localMemoryK = boundedInt(source.localMemoryK, 1, 100);
|
||||
if (localMemoryK !== undefined)
|
||||
result.localMemoryK = localMemoryK;
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,153 @@
|
|||
/**
|
||||
* Diagnostic JSONL logging for dsh-brain.
|
||||
*
|
||||
* Layout: <root>/logs/brain-YYYY-MM-DD.log, with numbered rollover files when
|
||||
* one day's file exceeds the size cap. Global events go to $DSH_HOME/brain,
|
||||
* workspace-scoped events to <project>/.dsh/brain. Writes are asynchronous and
|
||||
* must never affect the operation they describe: every failure is swallowed
|
||||
* after one console.warn.
|
||||
*/
|
||||
import { appendFile, mkdir, readdir, rename, stat, unlink } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { containsSecret } from "./local-memory/storage.js";
|
||||
const MAX_FIELD_CHARS = 120;
|
||||
const MAX_ERR_CHARS = 300;
|
||||
const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
|
||||
const DEFAULT_RETENTION_DAYS = 14;
|
||||
function pad(value) { return value < 10 ? '0' + String(value) : String(value); }
|
||||
function dateStamp(date) { return String(date.getFullYear()) + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()); }
|
||||
/** Keep only small structured fields; long strings are truncated and secrets redacted. */
|
||||
function sanitizeValue(value) {
|
||||
if (typeof value === 'string') {
|
||||
if (containsSecret(value))
|
||||
return '[redacted]';
|
||||
return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS - 1) + '…' : value;
|
||||
}
|
||||
if (typeof value === 'number' || typeof value === 'boolean' || value === null)
|
||||
return value;
|
||||
if (Array.isArray(value))
|
||||
return value.slice(0, 20).map((item) => sanitizeValue(item));
|
||||
if (typeof value === 'object' && value !== undefined) {
|
||||
const record = {};
|
||||
for (const [key, item] of Object.entries(value))
|
||||
record[key] = sanitizeValue(item);
|
||||
return record;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function sanitizeDetail(detail) {
|
||||
if (detail === undefined)
|
||||
return undefined;
|
||||
const result = {};
|
||||
for (const [key, value] of Object.entries(detail)) {
|
||||
const sanitized = sanitizeValue(value);
|
||||
if (sanitized !== undefined)
|
||||
result[key] = sanitized;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export class BrainLogger {
|
||||
opts;
|
||||
queue = Promise.resolve();
|
||||
warned = false;
|
||||
constructor(options) {
|
||||
this.opts = {
|
||||
globalRoot: options.globalRoot,
|
||||
projectRootOf: options.projectRootOf,
|
||||
enabled: options.enabled,
|
||||
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
|
||||
retentionDays: options.retentionDays ?? DEFAULT_RETENTION_DAYS,
|
||||
now: options.now ?? (() => new Date()),
|
||||
};
|
||||
}
|
||||
/** Synchronous enqueue; asynchronous append. Never throws. */
|
||||
log(event) {
|
||||
try {
|
||||
if (!this.opts.enabled())
|
||||
return;
|
||||
const now = this.opts.now();
|
||||
const scope = event.scope ?? (event.workspace === undefined ? 'global' : 'project');
|
||||
const record = {
|
||||
ts: now.toISOString(),
|
||||
level: event.level ?? 'info',
|
||||
event: event.event,
|
||||
scope,
|
||||
};
|
||||
if (event.workspace !== undefined)
|
||||
record.workspace = event.workspace;
|
||||
if (event.sessionId !== undefined)
|
||||
record.sessionId = event.sessionId;
|
||||
const detail = sanitizeDetail(event.detail);
|
||||
if (detail !== undefined && Object.keys(detail).length > 0)
|
||||
record.detail = detail;
|
||||
if (event.err !== undefined) {
|
||||
const err = containsSecret(event.err) ? '[redacted]' : event.err.length > MAX_ERR_CHARS ? event.err.slice(0, MAX_ERR_CHARS - 1) + '…' : event.err;
|
||||
record.err = err;
|
||||
}
|
||||
const line = JSON.stringify(record) + '\n';
|
||||
const directory = this.directoryFor(scope, event.workspace);
|
||||
this.queue = this.queue.then(() => this.appendLine(directory, dateStamp(now), line)).catch(() => { this.warnOnce(); });
|
||||
}
|
||||
catch {
|
||||
this.warnOnce();
|
||||
}
|
||||
}
|
||||
/** Await all queued writes (tests / graceful shutdown). */
|
||||
async flush() {
|
||||
await this.queue.catch(() => { });
|
||||
}
|
||||
/** Start-of-boot retention sweep; fire-and-forget and never throws. */
|
||||
prune() {
|
||||
void this.pruneAsync().catch(() => { });
|
||||
}
|
||||
directoryFor(scope, workspace) {
|
||||
return scope === 'project' ? join(this.opts.projectRootOf(workspace), 'logs') : join(this.opts.globalRoot(), 'logs');
|
||||
}
|
||||
async appendLine(directory, stamp, line) {
|
||||
await mkdir(directory, { recursive: true });
|
||||
let file = join(directory, 'brain-' + stamp + '.log');
|
||||
try {
|
||||
const info = await stat(file);
|
||||
if (info.size > 0 && info.size + Buffer.byteLength(line) > this.opts.maxBytes) {
|
||||
let index = 1;
|
||||
while (true) {
|
||||
const candidate = join(directory, 'brain-' + stamp + '.' + String(index) + '.log');
|
||||
const exists = await stat(candidate).catch(() => undefined);
|
||||
if (exists === undefined) {
|
||||
await rename(file, candidate);
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
file = join(directory, 'brain-' + stamp + '.log');
|
||||
}
|
||||
}
|
||||
catch {
|
||||
/* first write of the day: the file does not exist yet */
|
||||
}
|
||||
await appendFile(file, line, { encoding: 'utf8' });
|
||||
}
|
||||
async pruneAsync() {
|
||||
const roots = new Set([this.opts.globalRoot(), this.opts.projectRootOf(undefined)]);
|
||||
const cutoff = this.opts.now().getTime() - this.opts.retentionDays * 24 * 60 * 60 * 1000;
|
||||
for (const root of roots) {
|
||||
const directory = join(root, 'logs');
|
||||
const entries = await readdir(directory).catch(() => []);
|
||||
for (const name of entries) {
|
||||
const match = /^brain-(\d{4}-\d{2}-\d{2})(?:\.\d+)?\.log$/.exec(name);
|
||||
if (match === null)
|
||||
continue;
|
||||
const stamp = Date.parse(match[1] + 'T00:00:00');
|
||||
if (Number.isFinite(stamp) && stamp < cutoff)
|
||||
await unlink(join(directory, name)).catch(() => { });
|
||||
}
|
||||
}
|
||||
}
|
||||
warnOnce() {
|
||||
if (this.warned)
|
||||
return;
|
||||
this.warned = true;
|
||||
if (typeof console !== 'undefined')
|
||||
console.warn('[dsh-brain] diagnostic log write failed; continuing without logs');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
import { brainKernel, VERSION } from "../kernel.js";
|
||||
import { buildStatusPayload, legacyAliases } from "../routes.js";
|
||||
import { createCloudSyncRoutes } from "../cloudsync-routes.js";
|
||||
export const name = 'dsh-brain-cloudsync';
|
||||
/** Services required before `apply` runs. */
|
||||
export const inject = ['webServer'];
|
||||
/** How often the skill directory is reconciled with the cloud center. */
|
||||
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
|
||||
/** How often queued reports are retried. */
|
||||
const RETRY_INTERVAL_MS = 30_000;
|
||||
/** Register the sub-plugin with the host. */
|
||||
export function apply(ctx, config) {
|
||||
const logger = ctx.logger('dsh-brain');
|
||||
const kernel = brainKernel(config, logger);
|
||||
kernel.activate('cloudsync');
|
||||
kernel.logEvent('boot.entry', { bundle: 'cloudsync' });
|
||||
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation');
|
||||
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
|
||||
// third-party bundle cannot rely on; bind the listener through a local shape.
|
||||
const onEvent = ctx.on;
|
||||
ctx.effect(() => onEvent('session/event', (session, event) => {
|
||||
try {
|
||||
kernel.reporter.handleEvent(session, event);
|
||||
}
|
||||
catch (error) {
|
||||
logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}), 'dsh-brain-cloudsync: turn reporting');
|
||||
ctx.effect(() => {
|
||||
const timer = setInterval(() => {
|
||||
if (kernel.store.activityToken() !== '' && kernel.settings().activityEnabled) {
|
||||
void kernel.reporter.flush().catch((error) => {
|
||||
logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
}
|
||||
}, RETRY_INTERVAL_MS);
|
||||
timer.unref?.();
|
||||
return () => clearInterval(timer);
|
||||
}, 'dsh-brain-cloudsync: retry timer');
|
||||
ctx.effect(() => {
|
||||
const run = () => {
|
||||
if (kernel.store.memoryToken() !== '')
|
||||
void kernel.skillSync.syncOnce().catch(() => { });
|
||||
};
|
||||
const first = setTimeout(run, 5_000);
|
||||
first.unref?.();
|
||||
const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS);
|
||||
timer.unref?.();
|
||||
return () => { clearTimeout(first); clearInterval(timer); };
|
||||
}, 'dsh-brain-cloudsync: skill sync timer');
|
||||
const webServer = ctx.webServer;
|
||||
if (webServer === undefined) {
|
||||
logger.warn('webServer service unavailable; cloud-sync routes stay disabled');
|
||||
return;
|
||||
}
|
||||
const routes = createCloudSyncRoutes({
|
||||
store: kernel.store,
|
||||
client: () => kernel.client,
|
||||
reporter: kernel.reporter,
|
||||
sync: kernel.skillSync,
|
||||
statusView: () => buildStatusPayload(kernel.routeDeps()),
|
||||
});
|
||||
routes.push(...legacyAliases(routes));
|
||||
for (const route of routes) {
|
||||
ctx.effect(() => webServer.register(route), `dsh-brain-cloudsync: route ${route.path}`);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import { brainKernel } from "../kernel.js";
|
||||
export const name = 'dsh-brain-mcp';
|
||||
/** Services required before `apply` runs (none: activation only). */
|
||||
export const inject = [];
|
||||
/** Register the sub-plugin with the host. */
|
||||
export function apply(ctx, config) {
|
||||
const kernel = brainKernel(config, ctx.logger('dsh-brain'));
|
||||
kernel.activate('mcp');
|
||||
kernel.logEvent('boot.entry', { bundle: 'mcp' });
|
||||
ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation');
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
import { brainKernel } from "../kernel.js";
|
||||
import { createMemoryTools } from "../memory/tools.js";
|
||||
import { createDepartmentTools } from "../memory/departments-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 logger = ctx.logger('dsh-brain');
|
||||
const kernel = brainKernel(config, logger);
|
||||
kernel.activate('memory');
|
||||
kernel.logEvent('boot.entry', { bundle: 'memory' });
|
||||
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation');
|
||||
ctx.inject(['tools'], (toolsCtx) => {
|
||||
const tools = toolsCtx.tools;
|
||||
if (tools === undefined)
|
||||
return;
|
||||
for (const tool of createMemoryTools(kernel.toolDeps())) {
|
||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`);
|
||||
}
|
||||
for (const tool of createDepartmentTools(kernel.departmentToolDeps())) {
|
||||
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');
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
/**
|
||||
* Backward-compatible entry alias: the bundle was renamed from
|
||||
* dsh-brain-settings-ui to dsh-brain-ui. The package exports map points the
|
||||
* old './settings-ui' subpath at lib/entries/ui.js; this physical module is a
|
||||
* second safety net for profiles that resolve the old file path directly.
|
||||
*/
|
||||
export * from "./ui.js";
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import { brainKernel, VERSION } from "../kernel.js";
|
||||
import { legacyAliases } from "../routes.js";
|
||||
import { createSkillRoutes } from "../skills/routes.js";
|
||||
import { createSkillTools } from "../tools.js";
|
||||
export const name = 'dsh-brain-skills';
|
||||
/** Services required before `apply` runs. */
|
||||
export const inject = ['tools', 'webServer'];
|
||||
/** Register the sub-plugin with the host. */
|
||||
export function apply(ctx, config) {
|
||||
const logger = ctx.logger('dsh-brain');
|
||||
const kernel = brainKernel(config, logger);
|
||||
kernel.activate('skills');
|
||||
kernel.logEvent('boot.entry', { bundle: 'skills' });
|
||||
ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation');
|
||||
ctx.inject(['tools'], (toolsCtx) => {
|
||||
const tools = toolsCtx.tools;
|
||||
if (tools === undefined)
|
||||
return;
|
||||
for (const tool of createSkillTools(kernel.toolDeps())) {
|
||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-skills: tool ${tool.name}`);
|
||||
}
|
||||
});
|
||||
const webServer = ctx.webServer;
|
||||
if (webServer === undefined) {
|
||||
logger.warn('webServer service unavailable; skill routes stay disabled');
|
||||
return;
|
||||
}
|
||||
const routes = createSkillRoutes({
|
||||
version: VERSION,
|
||||
admin: kernel.skillAdmin,
|
||||
groups: kernel.skillGroups,
|
||||
market: kernel.market,
|
||||
updates: kernel.updater,
|
||||
clients: kernel.clients,
|
||||
});
|
||||
routes.push(...legacyAliases(routes));
|
||||
for (const route of routes) {
|
||||
ctx.effect(() => webServer.register(route), `dsh-brain-skills: route ${route.path}`);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
import { brainKernel, VERSION } from "../kernel.js";
|
||||
import { createCoreRoutes, legacyAliases } from "../routes.js";
|
||||
import { createSettingsUiRoutes } from "../settings-ui/routes.js";
|
||||
export const name = 'dsh-brain-ui';
|
||||
/** Services required before `apply` runs. */
|
||||
export const inject = ['webServer'];
|
||||
/** The pre-rename row id; only used to point a stale profile at the new row. */
|
||||
const LEGACY_BUNDLE_ID = 'dsh-brain-settings-ui';
|
||||
function profileMentionsLegacyId(ctx) {
|
||||
try {
|
||||
const face = ctx;
|
||||
return [face.config, face.settings].some((value) => value !== undefined && JSON.stringify(value).includes(LEGACY_BUNDLE_ID));
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/** Register the sub-plugin with the host. */
|
||||
export function apply(ctx, config) {
|
||||
const logger = ctx.logger('dsh-brain');
|
||||
const kernel = brainKernel(config, logger);
|
||||
kernel.activate('ui');
|
||||
kernel.logEvent('boot.entry', { bundle: 'ui' });
|
||||
ctx.effect(() => () => kernel.deactivate('ui'), 'dsh-brain-ui: activation');
|
||||
// We never rewrite host files: if the old row is visible in the live config
|
||||
// face, tell the user which row to re-toggle after the rename.
|
||||
if (profileMentionsLegacyId(ctx)) {
|
||||
logger.info('detected the old plugin id ' + LEGACY_BUNDLE_ID + '; re-apply the plugin toggle under dsh-brain-ui in Settings → Plugins');
|
||||
}
|
||||
const webServer = ctx.webServer;
|
||||
if (webServer === undefined) {
|
||||
logger.warn('webServer service unavailable; the configuration page stays disabled');
|
||||
return;
|
||||
}
|
||||
const routes = [
|
||||
...createSettingsUiRoutes({ version: VERSION, store: kernel.store }),
|
||||
...createCoreRoutes(kernel.routeDeps()),
|
||||
];
|
||||
routes.push(...legacyAliases(routes));
|
||||
for (const route of routes) {
|
||||
ctx.effect(() => webServer.register(route), `dsh-brain-ui: route ${route.path}`);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
/** Largest request body we accept (a settings patch is tiny). */
|
||||
export const MAX_BODY_BYTES = 64 * 1024;
|
||||
/** Optional diagnostics hook for failed route responses (set by the kernel). */
|
||||
let routeErrorHook;
|
||||
export function setRouteErrorHook(hook) {
|
||||
routeErrorHook = hook;
|
||||
}
|
||||
/** Collect a request body as UTF-8 text. */
|
||||
export async function readBody(req, maxBytes = MAX_BODY_BYTES) {
|
||||
const chunks = [];
|
||||
let bytes = 0;
|
||||
for await (const chunk of req) {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
bytes += buffer.byteLength;
|
||||
if (bytes > maxBytes)
|
||||
throw new Error('request-too-large');
|
||||
chunks.push(buffer);
|
||||
}
|
||||
return Buffer.concat(chunks).toString('utf8');
|
||||
}
|
||||
/** Reject cross-origin browser writes. */
|
||||
export function sameOrigin(req) {
|
||||
const origin = req.headers.origin;
|
||||
const host = req.headers.host;
|
||||
if (origin === undefined || host === undefined)
|
||||
return true;
|
||||
return origin === `http://${host}` || origin === `https://${host}`;
|
||||
}
|
||||
/** Emit one JSON response with no caching. */
|
||||
export function json(res, status, body) {
|
||||
const text = JSON.stringify(body);
|
||||
res.writeHead(status, {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'cache-control': 'no-store',
|
||||
'content-length': Buffer.byteLength(text),
|
||||
});
|
||||
res.end(text);
|
||||
}
|
||||
/** Emit a plain-text error (page route) or JSON error (API routes). */
|
||||
export function fail(res, status, message, asHtml = false) {
|
||||
try {
|
||||
routeErrorHook?.('route.error', { status, error: message, html: asHtml });
|
||||
}
|
||||
catch {
|
||||
/* diagnostics must never change the response */
|
||||
}
|
||||
const text = asHtml
|
||||
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
|
||||
: JSON.stringify({ ok: false, error: message });
|
||||
res.writeHead(status, {
|
||||
'content-type': asHtml ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8',
|
||||
'cache-control': 'no-store',
|
||||
});
|
||||
res.end(text);
|
||||
}
|
||||
/**
|
||||
* Read one JSON object body, or answer the request and return undefined.
|
||||
*
|
||||
* The method, origin and content-type gates live here so every write route
|
||||
* cannot forget one of them.
|
||||
*/
|
||||
export async function jsonBody(req, res) {
|
||||
if (req.method !== 'POST' && req.method !== 'PUT') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return undefined;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return undefined;
|
||||
}
|
||||
const type = (req.headers['content-type'] ?? '').toLowerCase();
|
||||
if (!type.startsWith('application/json')) {
|
||||
fail(res, 415, 'json-required');
|
||||
return undefined;
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(await readBody(req));
|
||||
}
|
||||
catch (error) {
|
||||
fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json');
|
||||
return undefined;
|
||||
}
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
fail(res, 400, 'invalid-body');
|
||||
return undefined;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
174
lib/index.js
174
lib/index.js
|
|
@ -1,169 +1,17 @@
|
|||
/**
|
||||
* Plugin entry — host half.
|
||||
*
|
||||
* Responsibilities:
|
||||
* 1. report one activity record per finished conversation round,
|
||||
* 2. expose the memory tools to the agent,
|
||||
* 3. serve the configuration page under `/dsh-brain` (legacy `/cloud-memory` routes stay as aliases).
|
||||
*
|
||||
* Everything registers through `ctx.effect(...)` so a plugin reload tears down
|
||||
* its routes, timer, listeners, and tools without leftovers.
|
||||
*/
|
||||
import { CloudClient } from "./api.js";
|
||||
import { Reporter } from "./reporter.js";
|
||||
import { createLegacyRoutes, createRoutes } from "./routes.js";
|
||||
import { join } from 'node:path';
|
||||
import { SettingsStore, dshHome } from "./store.js";
|
||||
import { SkillSync, skillsStatePath } from "./skill-sync.js";
|
||||
import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js";
|
||||
import { SkillGroupManager, detectSources } from "./skill-groups.js";
|
||||
import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js";
|
||||
import { SkillUpdater } from "./skill-update.js";
|
||||
import { ClientRegistry } from "./clients.js";
|
||||
import { createMemoryTools, createSkillTools } from "./tools.js";
|
||||
import * as cloudsync from "./entries/cloudsync.js";
|
||||
import * as memory from "./entries/memory.js";
|
||||
import * as skills from "./entries/skills.js";
|
||||
import * as mcp from "./entries/mcp.js";
|
||||
import * as ui from "./entries/ui.js";
|
||||
/** Package name; also the client bundle id. */
|
||||
export const name = 'dsh-brain';
|
||||
/** Services required before `apply` runs. */
|
||||
export const inject = ['webServer'];
|
||||
/** Version reported by the status card. */
|
||||
const VERSION = '0.9.2';
|
||||
/** How often the skill directory is reconciled with the cloud center. */
|
||||
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
|
||||
/** How often queued reports are retried. */
|
||||
const RETRY_INTERVAL_MS = 30_000;
|
||||
/** Register the plugin with the host. */
|
||||
/** Register the plugin with the host: all five sub-entries at once. */
|
||||
export function apply(ctx, config) {
|
||||
const logger = ctx.logger('dsh-brain');
|
||||
const store = new SettingsStore(config);
|
||||
const settings = () => store.settings();
|
||||
// One client per instance; the settings closures keep it live across edits.
|
||||
const client = new CloudClient({
|
||||
baseUrl: () => settings().baseUrl,
|
||||
token: () => store.memoryToken(),
|
||||
timeoutMs: () => settings().requestTimeoutMs,
|
||||
});
|
||||
const reporter = new Reporter({
|
||||
client,
|
||||
settings: () => ({ enabled: settings().enabled, clientId: settings().clientId }),
|
||||
activityToken: () => store.activityToken(),
|
||||
summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }),
|
||||
summaryToken: () => store.summaryToken(),
|
||||
log: (message) => logger.warn(message),
|
||||
});
|
||||
const skillSync = new SkillSync({
|
||||
client: () => client,
|
||||
settings: () => ({
|
||||
enabled: settings().enabled,
|
||||
skillsSyncEnabled: settings().skillsSyncEnabled,
|
||||
skillsDir: settings().skillsDir,
|
||||
}),
|
||||
log: (message) => logger.info(message),
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
});
|
||||
const skillAdmin = new SkillAdmin({
|
||||
skillsRoot: () => skillSync.skillsRoot(),
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
syncStatePath: () => skillsStatePath(),
|
||||
syncRunning: () => skillSync.stats().running,
|
||||
log: (message) => logger.info(message),
|
||||
});
|
||||
// The tree's sources are detected per call so a directory created while the
|
||||
// process runs shows up on the next refresh.
|
||||
const skillGroups = new SkillGroupManager({
|
||||
sources: () => detectSources(),
|
||||
admin: skillAdmin,
|
||||
log: (message) => logger.info(message),
|
||||
});
|
||||
// One verified market source to start with: the Claude Code plugin marketplace
|
||||
// manifest that Anthropic publishes. Entry ids never carry a URL, so the card
|
||||
// cannot make the host fetch an arbitrary repository.
|
||||
const market = new MarketService([
|
||||
new ClaudePluginMarketplaceProvider({
|
||||
id: 'anthropic-skills',
|
||||
label: 'Anthropic Agent Skills',
|
||||
description: 'Anthropic 公开的 Claude 技能市场(.claude-plugin/marketplace.json)',
|
||||
repo: 'anthropics/skills',
|
||||
ref: 'main',
|
||||
}),
|
||||
]);
|
||||
const updater = new SkillUpdater({
|
||||
admin: skillAdmin,
|
||||
skillsRoot: () => skillSync.skillsRoot(),
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
syncRunning: () => skillSync.stats().running,
|
||||
log: (message) => logger.info(message),
|
||||
});
|
||||
// Cross-software / workspace inventory. Read-only for every client except DSH.
|
||||
const clients = new ClientRegistry();
|
||||
// Announce at most once per activation so a missing token is obvious in logs.
|
||||
const effective = settings();
|
||||
if (!effective.enabled) {
|
||||
logger.info('disabled by settings');
|
||||
}
|
||||
else if (store.activityToken() === '') {
|
||||
logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`);
|
||||
}
|
||||
else {
|
||||
logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`);
|
||||
}
|
||||
if (effective.summaryEnabled && store.summaryToken() === '') {
|
||||
logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged');
|
||||
}
|
||||
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
|
||||
// third-party bundle cannot rely on; bind the listener through a local shape.
|
||||
const onEvent = ctx.on;
|
||||
ctx.effect(() => onEvent('session/event', (session, event) => {
|
||||
try {
|
||||
reporter.handleEvent(session, event);
|
||||
}
|
||||
catch (error) {
|
||||
logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}), 'dsh-brain: turn reporting');
|
||||
ctx.inject(['tools'], (toolsCtx) => {
|
||||
const tools = toolsCtx.tools;
|
||||
if (tools === undefined)
|
||||
return;
|
||||
const toolDeps = {
|
||||
client: () => client,
|
||||
memoryToken: () => store.memoryToken(),
|
||||
settings: () => ({ enabled: settings().enabled, defaultK: settings().defaultK }),
|
||||
};
|
||||
for (const tool of [...createMemoryTools(toolDeps), ...createSkillTools(toolDeps)]) {
|
||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain: tool ${tool.name}`);
|
||||
}
|
||||
});
|
||||
const webServer = ctx.webServer;
|
||||
if (webServer === undefined) {
|
||||
logger.warn('webServer service unavailable; the configuration page stays disabled');
|
||||
}
|
||||
else {
|
||||
const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients });
|
||||
routes.push(...createLegacyRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients }));
|
||||
for (const route of routes) {
|
||||
ctx.effect(() => webServer.register(route), `dsh-brain: route ${route.path}`);
|
||||
}
|
||||
}
|
||||
ctx.effect(() => {
|
||||
const timer = setInterval(() => {
|
||||
if (store.activityToken() !== '' && settings().enabled) {
|
||||
void reporter.flush().catch((error) => {
|
||||
logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
}
|
||||
}, RETRY_INTERVAL_MS);
|
||||
timer.unref?.();
|
||||
return () => clearInterval(timer);
|
||||
}, 'dsh-brain: retry timer');
|
||||
ctx.effect(() => {
|
||||
const run = () => {
|
||||
if (store.memoryToken() !== '')
|
||||
void skillSync.syncOnce().catch(() => { });
|
||||
};
|
||||
const first = setTimeout(run, 5_000);
|
||||
first.unref?.();
|
||||
const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS);
|
||||
timer.unref?.();
|
||||
return () => { clearTimeout(first); clearInterval(timer); };
|
||||
}, 'dsh-brain: skill sync timer');
|
||||
cloudsync.apply(ctx, config);
|
||||
memory.apply(ctx, config);
|
||||
skills.apply(ctx, config);
|
||||
mcp.apply(ctx, config);
|
||||
ui.apply(ctx, config);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,339 @@
|
|||
/**
|
||||
* Shared kernel for the dsh-brain sub-plugins.
|
||||
*
|
||||
* The five bundle entries (dsh-brain/cloudsync, dsh-brain/memory,
|
||||
* dsh-brain/skills, dsh-brain/mcp, dsh-brain/ui) and the compat
|
||||
* root entry all load from the same package inside the same host process,
|
||||
* so this module's export resolves to a single instance: whichever entry
|
||||
* applies first builds the services, the rest reuse them.
|
||||
*
|
||||
* The kernel holds service OBJECTS only. Routes, tools, timers, and the
|
||||
* session listener belong to the entry that registers them through its own
|
||||
* `ctx.effect(...)`, so toggling a sub-plugin off in the host plugin
|
||||
* settings tears down exactly that slice and nothing else. `routeDeps()`
|
||||
* assembles the RouteDeps view from the currently active bundles, which is
|
||||
* how `/status` and `/capabilities` report what is actually enabled.
|
||||
*
|
||||
* Settings persist in `$DSH_HOME/dsh-brain.json`; the row config each
|
||||
* entry receives is only the first-boot seed, so any entry may seed the
|
||||
* kernel without diverging.
|
||||
*/
|
||||
import { join, resolve } from 'node:path';
|
||||
import { CloudClient } from "./api.js";
|
||||
import { BrainLogger } from "./diagnostics.js";
|
||||
import { setRouteErrorHook } from "./http.js";
|
||||
import { DepartmentManager, LocalMemoryManager, LocalMemoryRemote, globalBrainRoot, projectBrainRoot } 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";
|
||||
import { Reporter } from "./reporter.js";
|
||||
import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js";
|
||||
import { SkillGroupManager, detectSources } from "./skill-groups.js";
|
||||
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 (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;
|
||||
diagnostics;
|
||||
client;
|
||||
memoryRemoteFactory;
|
||||
localMemory;
|
||||
localMemoryRemote;
|
||||
departments;
|
||||
reporter;
|
||||
skillAdmin;
|
||||
skillRepository;
|
||||
skillSync;
|
||||
skillGroups;
|
||||
market;
|
||||
updater;
|
||||
clients;
|
||||
constructor(config, logger) {
|
||||
const store = new SettingsStore(config);
|
||||
this.store = store;
|
||||
const settings = () => store.settings();
|
||||
this.settingsOf = settings;
|
||||
this.diagnostics = new BrainLogger({
|
||||
globalRoot: globalBrainRoot,
|
||||
projectRootOf: (workspace) => projectBrainRoot(workspace),
|
||||
enabled: () => {
|
||||
const effective = settings();
|
||||
return effective.diagnosticsEnabled !== false && effective.enabled !== false;
|
||||
},
|
||||
});
|
||||
setRouteErrorHook((event, detail) => this.diagnostics.log({ event, level: 'warn', detail }));
|
||||
this.diagnostics.prune();
|
||||
// One client per instance; the settings closures keep it live across edits.
|
||||
const client = new CloudClient({
|
||||
baseUrl: () => settings().baseUrl,
|
||||
token: () => store.memoryToken(),
|
||||
timeoutMs: () => settings().requestTimeoutMs,
|
||||
});
|
||||
this.client = client;
|
||||
// The memory bundle sees the cloud through this factory only: the concrete
|
||||
// client stays a cloud-sync concern, injected here at the composition root.
|
||||
this.memoryRemoteFactory = createCloudMemoryRemoteFactory({
|
||||
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(),
|
||||
logger: this.diagnostics,
|
||||
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);
|
||||
this.departments = new DepartmentManager({ memory: 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({
|
||||
// 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
|
||||
// path and the parking area. The sync engine touches folders exclusively
|
||||
// through AdminSkillRepository below.
|
||||
const skillsRootDir = () => {
|
||||
const dir = settings().skillsDir;
|
||||
return dir !== '' ? resolve(dir) : join(dshHome(), 'skills');
|
||||
};
|
||||
// Built before the sync engine: the gate closures dereference skillSync
|
||||
// lazily, so the TDZ order here is safe.
|
||||
const skillAdmin = new SkillAdmin({
|
||||
skillsRoot: skillsRootDir,
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
gate: () => this.skillSync,
|
||||
log: (message) => logger.info(message),
|
||||
});
|
||||
this.skillAdmin = skillAdmin;
|
||||
this.skillRepository = new AdminSkillRepository({
|
||||
admin: skillAdmin,
|
||||
skillsRoot: skillsRootDir,
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
});
|
||||
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
|
||||
// the process runs shows up on the next refresh.
|
||||
this.skillGroups = new SkillGroupManager({
|
||||
sources: () => detectSources(),
|
||||
admin: skillAdmin,
|
||||
log: (message) => logger.info(message),
|
||||
});
|
||||
// One verified market source to start with: the Claude Code plugin
|
||||
// marketplace manifest that Anthropic publishes. Entry ids never carry a
|
||||
// URL, so the card cannot make the host fetch an arbitrary repository.
|
||||
this.market = new MarketService([
|
||||
new ClaudePluginMarketplaceProvider({
|
||||
id: 'anthropic-skills',
|
||||
label: 'Anthropic Agent Skills',
|
||||
description: 'Anthropic 公开的 Claude 技能市场(.claude-plugin/marketplace.json)',
|
||||
repo: 'anthropics/skills',
|
||||
ref: 'main',
|
||||
}),
|
||||
]);
|
||||
this.updater = new SkillUpdater({
|
||||
admin: skillAdmin,
|
||||
skillsRoot: skillsRootDir,
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
gate: () => this.skillSync,
|
||||
log: (message) => logger.info(message),
|
||||
});
|
||||
// Cross-software / workspace inventory. Read-only for every client but DSH.
|
||||
this.clients = new ClientRegistry();
|
||||
// Announce at most once per kernel so a missing token is obvious in logs.
|
||||
const effective = settings();
|
||||
if (!effective.activityEnabled) {
|
||||
logger.info('turn reporting disabled by settings');
|
||||
}
|
||||
else if (store.activityToken() === '') {
|
||||
logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`);
|
||||
}
|
||||
else {
|
||||
logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`);
|
||||
}
|
||||
if (effective.summaryEnabled && store.summaryToken() === '') {
|
||||
logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged');
|
||||
}
|
||||
this.diagnostics.log({
|
||||
event: 'boot.kernel',
|
||||
detail: {
|
||||
version: VERSION,
|
||||
localMemoryEnabled: effective.localMemoryEnabled !== false,
|
||||
cloudMemoryEnabled: effective.cloudMemoryEnabled === true,
|
||||
autoSummaryEnabled: effective.autoSummaryEnabled !== false,
|
||||
},
|
||||
});
|
||||
}
|
||||
/** Current settings snapshot (live: re-read on every call). */
|
||||
settings() {
|
||||
return this.settingsOf();
|
||||
}
|
||||
/** Emit one diagnostic event through the shared logger (entries and route wiring). */
|
||||
logEvent(event, detail, scope, workspace) {
|
||||
this.diagnostics.log({ event, detail, scope, workspace });
|
||||
}
|
||||
/** Mark a bundle's entry as applied; feeds `routeDeps()` gating. */
|
||||
activate(bundle) {
|
||||
this.active.add(bundle);
|
||||
}
|
||||
/** Drop a bundle from the active set (entry teardown). */
|
||||
deactivate(bundle) {
|
||||
this.active.delete(bundle);
|
||||
}
|
||||
/** Whether a bundle's entry is currently applied. */
|
||||
isActive(bundle) {
|
||||
return this.active.has(bundle);
|
||||
}
|
||||
/** Tool deps shared by the memory and skill entries. */
|
||||
departmentToolDeps() {
|
||||
return {
|
||||
departments: () => this.departments,
|
||||
memory: () => this.localMemory,
|
||||
settings: () => ({ localMemoryEnabled: this.settingsOf().localMemoryEnabled, memoryEnabled: this.settingsOf().memoryEnabled }),
|
||||
workspace: (exec) => workspaceFromExec(exec),
|
||||
};
|
||||
}
|
||||
toolDeps() {
|
||||
const store = this.store;
|
||||
const settings = this.settingsOf;
|
||||
return {
|
||||
// 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: () => {
|
||||
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),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* RouteDeps assembled from the currently active bundles: the status card
|
||||
* then reports exactly what is on, not what this build could do.
|
||||
*/
|
||||
routeDeps() {
|
||||
const skills = this.isActive('skills');
|
||||
const cloudsync = this.isActive('cloudsync');
|
||||
return {
|
||||
version: VERSION,
|
||||
store: this.store,
|
||||
reporter: this.reporter,
|
||||
client: () => this.client,
|
||||
skills: cloudsync ? () => this.skillSync.stats() : undefined,
|
||||
admin: skills ? this.skillAdmin : undefined,
|
||||
groups: skills ? this.skillGroups : undefined,
|
||||
market: skills ? this.market : undefined,
|
||||
sync: cloudsync ? this.skillSync : undefined,
|
||||
updates: skills ? this.updater : undefined,
|
||||
clients: skills ? this.clients : undefined,
|
||||
mcp: this.isActive('mcp'),
|
||||
localMemory: this.localMemory,
|
||||
departments: this.departments,
|
||||
bundles: {
|
||||
cloudsync: this.isActive('cloudsync'),
|
||||
memory: this.isActive('memory'),
|
||||
skills: this.isActive('skills'),
|
||||
mcp: this.isActive('mcp'),
|
||||
ui: this.isActive('ui'),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
let instance;
|
||||
/**
|
||||
* The process-wide kernel. The first entry to apply builds it (seeding from
|
||||
* that row's config; the sidecar file is authoritative afterwards); every
|
||||
* later entry — and the compat root — reuses the same instance.
|
||||
*/
|
||||
export function brainKernel(config, logger) {
|
||||
if (instance === undefined)
|
||||
instance = new BrainKernel(config, logger);
|
||||
return instance;
|
||||
}
|
||||
/** Test hook: drop the singleton so the next call rebuilds it. */
|
||||
export function resetBrainKernel() {
|
||||
instance = undefined;
|
||||
setRouteErrorHook(undefined);
|
||||
}
|
||||
|
|
@ -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,654 @@
|
|||
/** 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;
|
||||
loggerOf;
|
||||
constructor(options = {}) {
|
||||
this.cwdOf = options.cwd ?? (() => process.cwd());
|
||||
this.defaultWorkspaceOf = options.workspace;
|
||||
this.settingsOf = options.settings ?? (() => ({}));
|
||||
this.fixedGlobalRoot = options.globalRoot;
|
||||
this.fixedProjectRoot = options.projectRoot;
|
||||
this.loggerOf = options.logger === undefined ? undefined : { log: (event) => { try {
|
||||
options.logger.log(event);
|
||||
}
|
||||
catch { /* diagnostics must never break memory operations */ } } };
|
||||
}
|
||||
/** 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();
|
||||
this.loggerOf?.log({ event: 'memory.ensure', detail: { scope: 'global', root: this.globalRoot } });
|
||||
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);
|
||||
this.loggerOf?.log({ event: 'memory.ensure', scope: 'project', workspace: base, detail: { scope: 'project', root } });
|
||||
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 startedAt = Date.now();
|
||||
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) {
|
||||
this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: result.record.id, duplicate: true, category: input.category, durationMs: Date.now() - startedAt } });
|
||||
return result;
|
||||
}
|
||||
const outcome = { ...result, ...(await this.tryRegenerateProjections()) };
|
||||
this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: outcome.record.id, duplicate: false, category: input.category, durationMs: Date.now() - startedAt } });
|
||||
return outcome;
|
||||
}
|
||||
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 startedAt = Date.now();
|
||||
const hits = await this.collectHits(query, workspace, projectId);
|
||||
const limit = Math.max(1, Math.min(100, Math.trunc(k)));
|
||||
const result = hits.slice(0, limit);
|
||||
const sources = {};
|
||||
for (const hit of result)
|
||||
sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1;
|
||||
this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace: this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } });
|
||||
return result;
|
||||
}
|
||||
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();
|
||||
this.loggerOf?.log({ event: 'memory.forget', scope: 'global', detail: { recordId: id, revision: removed.revision } });
|
||||
return removed;
|
||||
}
|
||||
const store = await this.ensureProject(workspace);
|
||||
const removed = await store.forget(id, expectedRevision);
|
||||
await this.tryRegenerateProjections();
|
||||
this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace: this.workspacePath(workspace), detail: { recordId: id, revision: removed.revision } });
|
||||
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);
|
||||
this.loggerOf?.log({ event: 'memory.projection', detail: { root: this.globalRoot } });
|
||||
}
|
||||
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();
|
||||
this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } });
|
||||
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair };
|
||||
}
|
||||
this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } });
|
||||
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 });
|
||||
}
|
||||
this.loggerOf?.log({ event: 'memory.backup', detail: { path } });
|
||||
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 {};
|
||||
|
|
@ -12,7 +12,7 @@
|
|||
* it ships. Installing an entry reuses the same staged plan/commit pipeline as
|
||||
* a manual git install, pinned to the commit resolved here.
|
||||
*/
|
||||
import { parseSkillFrontmatter } from "./skill-sync.js";
|
||||
import { parseSkillFrontmatter } from "./skills/shared.js";
|
||||
/** Typed failure so routes can map it to a status code. */
|
||||
export class MarketError extends Error {
|
||||
code;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
/**
|
||||
* MCP bundle — the host half of the MCP management tab.
|
||||
*
|
||||
* In this package the MCP feature is a browser bridge, nothing more: the
|
||||
* client tab talks to the host `dsh-mcp-connector` plugin over
|
||||
* `/mcp-connector/api`, wrapping one JSON envelope per call, a fixed probe
|
||||
* timeout and an explicit host-unavailable state. Connections, credentials
|
||||
* and tool management belong to the host plugin; this bundle never stores
|
||||
* them and never syncs MCP configuration to the cloud.
|
||||
*/
|
||||
/**
|
||||
* The MCP bridge capability fragment owned by this bundle. `capabilities()`
|
||||
* in routes.ts aggregates it with the rest of the build's report; the MCP
|
||||
* text lives here so the bundle keeps its own surface in one place.
|
||||
*/
|
||||
export function mcpCapability() {
|
||||
return {
|
||||
bridge: 'host-plugin',
|
||||
notes: [
|
||||
'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。',
|
||||
'MCP 工具可见性与会话级激活分属两层:本卡展示连接与工具缓存,会话级“选择精确工具后激活”由宿主 session-tools 负责,本卡不伪造激活。',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,164 @@
|
|||
import { renderJson } from "./tools.js";
|
||||
export function departmentSnippet(text, limit = 600) {
|
||||
return text.length <= limit ? text : text.slice(0, Math.max(0, limit - 1)) + '…';
|
||||
}
|
||||
function inDepartmentWorkspace(deps, exec, job) {
|
||||
return deps.memory().withWorkspace(deps.workspace(exec), job);
|
||||
}
|
||||
function requireEnabled(deps) {
|
||||
const settings = deps.settings();
|
||||
if (settings.memoryEnabled === false || settings.localMemoryEnabled === false) {
|
||||
throw new Error('部门功能当前已禁用。请在 /dsh-brain 页面开启本地记忆和记忆功能后再试。');
|
||||
}
|
||||
}
|
||||
function list(value) {
|
||||
if (!Array.isArray(value))
|
||||
return undefined;
|
||||
return value.filter((item) => typeof item === 'string').slice(0, 50);
|
||||
}
|
||||
function text(value) { return typeof value === 'string' ? value : undefined; }
|
||||
function revision(value) { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined; }
|
||||
export function createDepartmentTools(deps) {
|
||||
const department_create = {
|
||||
name: 'department_create',
|
||||
description: '创建一个部门工作身份。部门拥有私有记忆空间;同名同 scope 幂等返回已有部门,不覆盖。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: '部门名称(必填)' },
|
||||
role: { type: 'string', description: '部门角色说明(可选,最多 12000 字符)' },
|
||||
scope: { type: 'string', enum: ['global', 'project'], description: '部门空间范围,默认 project' },
|
||||
skills: { type: 'array', items: { type: 'string' }, description: '关联技能名列表' },
|
||||
allowedTools: { type: 'array', items: { type: 'string' }, description: '允许使用的工具名列表' },
|
||||
readGlobal: { type: 'boolean', description: '是否允许读取全局记忆,默认 true' },
|
||||
readProject: { type: 'boolean', description: '是否允许读取项目记忆,默认 true' },
|
||||
},
|
||||
required: ['name'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args, exec) {
|
||||
requireEnabled(deps);
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
const name = text(args.name)?.trim() ?? '';
|
||||
if (name === '')
|
||||
throw new Error('部门名称不能为空。');
|
||||
const input = { name, ...(text(args.role) === undefined ? {} : { role: text(args.role) }), ...(args.scope === 'global' || args.scope === 'project' ? { scope: args.scope } : {}), ...(list(args.skills) === undefined ? {} : { skills: list(args.skills) }), ...(list(args.allowedTools) === undefined ? {} : { allowedTools: list(args.allowedTools) }), ...(typeof args.readGlobal === 'boolean' ? { readGlobal: args.readGlobal } : {}), ...(typeof args.readProject === 'boolean' ? { readProject: args.readProject } : {}) };
|
||||
const result = await deps.departments().create(input);
|
||||
return { id: result.department.id, name: result.department.name, scope: result.department.scope, created: result.created };
|
||||
});
|
||||
},
|
||||
};
|
||||
const department_list = {
|
||||
name: 'department_list',
|
||||
description: '列出部门及其精简状态;role 全文不返回,按需使用部门详情接口。',
|
||||
parameters: { type: 'object', properties: { scope: { type: 'string', enum: ['global', 'project'] } }, additionalProperties: false },
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args, exec) {
|
||||
requireEnabled(deps);
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
const scope = args.scope === 'global' || args.scope === 'project' ? args.scope : undefined;
|
||||
const rows = await deps.departments().list(scope);
|
||||
return { departments: rows.map((department) => ({ id: department.id, name: department.name, scope: department.scope, active: department.active, ...(department.currentTask === undefined ? {} : { currentTask: department.currentTask }), revision: department.revision })) };
|
||||
});
|
||||
},
|
||||
};
|
||||
const department_remember = {
|
||||
name: 'department_remember',
|
||||
description: '向一个部门的私有记忆空间写入记忆。秘密、令牌和密钥不得写入。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: { departmentId: { type: 'string' }, content: { type: 'string' }, category: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } },
|
||||
required: ['departmentId', 'content'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args, exec) {
|
||||
requireEnabled(deps);
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
const id = text(args.departmentId)?.trim() ?? '';
|
||||
const content = text(args.content)?.trim() ?? '';
|
||||
if (id === '')
|
||||
throw new Error('departmentId 不能为空。');
|
||||
if (content === '')
|
||||
throw new Error('content 不能为空。');
|
||||
const result = await deps.departments().remember(id, { content, ...(text(args.category) === undefined ? {} : { category: text(args.category) }), ...(list(args.tags) === undefined ? {} : { tags: list(args.tags) }) });
|
||||
return { id: result.record.id, duplicate: result.duplicate };
|
||||
});
|
||||
},
|
||||
};
|
||||
const department_recall = {
|
||||
name: 'department_recall',
|
||||
description: '从部门私有空间召回相关记忆,最多 5 条;返回内容为去敏后的短片段。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: { departmentId: { type: 'string' }, query: { type: 'string' }, k: { type: 'integer', minimum: 1, maximum: 5 } },
|
||||
required: ['departmentId', 'query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args, exec) {
|
||||
requireEnabled(deps);
|
||||
const ws = deps.workspace(exec);
|
||||
return deps.memory().withWorkspace(ws, async () => {
|
||||
const id = text(args.departmentId)?.trim() ?? '';
|
||||
const query = text(args.query)?.trim() ?? '';
|
||||
if (id === '')
|
||||
throw new Error('departmentId 不能为空。');
|
||||
if (query === '')
|
||||
throw new Error('query 不能为空。');
|
||||
const requested = revision(args.k) ?? 5;
|
||||
const k = Math.max(1, Math.min(5, requested));
|
||||
const hits = await deps.departments().recall(id, query, k, ws);
|
||||
return { hits: hits.map((hit) => ({ id: hit.record.id, origin: hit.origin, content: departmentSnippet(hit.record.content) })) };
|
||||
});
|
||||
},
|
||||
};
|
||||
const department_checkpoint = {
|
||||
name: 'department_checkpoint',
|
||||
description: '更新部门当前任务或交接说明,并返回新 revision。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: { departmentId: { type: 'string' }, currentTask: { type: 'string' }, handoff: { type: 'string' }, expectedRevision: { type: 'integer' } },
|
||||
required: ['departmentId'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args, exec) {
|
||||
requireEnabled(deps);
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
const id = text(args.departmentId)?.trim() ?? '';
|
||||
if (id === '')
|
||||
throw new Error('departmentId 不能为空。');
|
||||
const department = await deps.departments().checkpoint(id, { ...(text(args.currentTask) === undefined ? {} : { currentTask: text(args.currentTask) }), ...(text(args.handoff) === undefined ? {} : { handoff: text(args.handoff) }) }, revision(args.expectedRevision));
|
||||
return { revision: department.revision, updatedAt: department.updatedAt };
|
||||
});
|
||||
},
|
||||
};
|
||||
const department_resume = {
|
||||
name: 'department_resume',
|
||||
description: '获取部门可复用会话引用;传入 hostSessionId 时显式绑定宿主会话。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: { departmentId: { type: 'string' }, host: { type: 'string' }, hostSessionId: { type: 'string' } },
|
||||
required: ['departmentId'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args, exec) {
|
||||
requireEnabled(deps);
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
const id = text(args.departmentId)?.trim() ?? '';
|
||||
if (id === '')
|
||||
throw new Error('departmentId 不能为空。');
|
||||
const host = text(args.host)?.trim() || 'dsh';
|
||||
const hostSessionId = text(args.hostSessionId)?.trim();
|
||||
const sessionRef = hostSessionId !== undefined && hostSessionId !== ''
|
||||
? await deps.departments().attachSession(id, host, hostSessionId)
|
||||
: await deps.departments().resumeSession(id, host);
|
||||
return { sessionRef };
|
||||
});
|
||||
},
|
||||
};
|
||||
return [department_create, department_list, department_remember, department_recall, department_checkpoint, department_resume];
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export {};
|
||||
|
|
@ -0,0 +1,268 @@
|
|||
/**
|
||||
* Agent-facing memory tools — the memory bundle's tool face.
|
||||
*
|
||||
* Bundle rule: the remote is injected via MemoryRemoteFactory; this module
|
||||
* imports neither the concrete cloud client nor the settings sidecar.
|
||||
*
|
||||
* These definitions are hand-written `ToolDefinition` objects rather than
|
||||
* `defineTool(...)` calls: `defineTool` only compiles an authoring DSL into the
|
||||
* same raw JSON Schema, and importing `@deepseek-ai/dsh-tools` at runtime would
|
||||
* risk a second module instance (and a second class identity) inside a linked
|
||||
* plugin.
|
||||
*
|
||||
* Failure contract: `execute` throws and the registry turns that into
|
||||
* `isError: true`. A missing token is a normal, explainable failure — never a
|
||||
* crash in the host.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { describeError } from "../api.js";
|
||||
/** Sectors the service accepts for `metadata.primary_sector`. */
|
||||
export const SECTORS = ['semantic', 'episodic', 'procedural', 'emotional', 'reflective'];
|
||||
/** Trim a memory body down to a display-sized snippet. */
|
||||
function snippet(text, limit = 600) {
|
||||
if (typeof text !== 'string')
|
||||
return '';
|
||||
if (text.length <= limit)
|
||||
return text;
|
||||
return `${text.slice(0, limit)}…`;
|
||||
}
|
||||
/** Project one hit into the compact shape returned to the model. */
|
||||
function toHitView(hit) {
|
||||
return {
|
||||
id: hit.id,
|
||||
content: snippet(hit.content),
|
||||
tags: hit.tags ?? [],
|
||||
project_id: hit.project_id ?? null,
|
||||
sector: hit.primary_sector ?? null,
|
||||
revision: hit.revision ?? null,
|
||||
created_at: hit.created_at ?? null,
|
||||
};
|
||||
}
|
||||
/** Render any tool value as one JSON text block. */
|
||||
export function renderJson(_args, value) {
|
||||
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
|
||||
return [{ type: 'text', text }];
|
||||
}
|
||||
/** 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 页面开启后再试。');
|
||||
}
|
||||
// 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 !== '')
|
||||
return token;
|
||||
throw new Error('记忆功能未启用或未配置令牌。请在 /dsh-brain 页面开启本地记忆,或填入 mem_… / cmt_… 记忆令牌。');
|
||||
}
|
||||
/** Search stored memories by keyword. */
|
||||
function searchTool(deps) {
|
||||
return {
|
||||
name: 'memory_search',
|
||||
description: '在云端长期记忆库中按关键词检索历史记忆片段。返回命中的记忆 id、内容摘要、标签与所属项目;' +
|
||||
'需要更多正文时用 memory_read 按 id 取全文。纯关键词匹配,不会做语义相似度检索。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
||||
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
|
||||
project_id: { type: 'string', description: '可选:只在这些项目 id 内检索。' },
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string' },
|
||||
total: { type: 'number' },
|
||||
search_mode: { type: 'string' },
|
||||
matches: { type: 'array', items: { type: 'object' } },
|
||||
},
|
||||
required: ['query', 'matches'],
|
||||
additionalProperties: true,
|
||||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args, exec) {
|
||||
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, workspace);
|
||||
if (!result.ok)
|
||||
throw new Error(`检索失败:${describeError(result.error)}`);
|
||||
const matches = result.data.matches ?? [];
|
||||
return {
|
||||
query,
|
||||
total: result.data.total ?? matches.length,
|
||||
search_mode: result.data.search_mode ?? 'keyword',
|
||||
matches: matches.map(toHitView),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Read one memory by id. */
|
||||
function readTool(deps) {
|
||||
return {
|
||||
name: 'memory_read',
|
||||
description: '按 id 读取一条云端记忆的完整内容(正文、标签、项目、修订号与时间戳)。id 可先用 memory_search 或 memory_list 获得。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string', description: '记忆条目 id(必填)。' },
|
||||
},
|
||||
required: ['id'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: { type: 'object', properties: { id: { type: 'string' }, content: { type: 'string' } }, required: ['id'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
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, workspace);
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 404)
|
||||
throw new Error(`没有找到 id=${id} 的记忆(可能已删除)。`);
|
||||
throw new Error(`读取失败:${describeError(result.error)}`);
|
||||
}
|
||||
return result.data;
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Store one new memory. */
|
||||
function addTool(deps) {
|
||||
return {
|
||||
name: 'memory_add',
|
||||
description: '向云端长期记忆库写入一条新记忆。content 上限 7000 字节,适合存结论、决策、待办与可复用事实;' +
|
||||
'不要写入密钥、令牌或完整源码。写入用 operation_id 保证幂等,重复调用不会产生重复条目。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '可选标签,最多 30 个,每个不超过 100 字符。' },
|
||||
project_id: { type: 'string', description: '可选:归属项目 id(≤128 字符)。' },
|
||||
sector: { type: 'string', enum: [...SECTORS], description: '可选:记忆分类(semantic/episodic/procedural/emotional/reflective)。' },
|
||||
operation_id: { type: 'string', description: '可选:幂等键(uuid);省略时自动生成。重试同一次写入时请复用同一个值。' },
|
||||
},
|
||||
required: ['content'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
revision: { type: 'number' },
|
||||
remote_saved: { type: 'boolean' },
|
||||
state: { type: 'string' },
|
||||
operation_id: { type: 'string' },
|
||||
},
|
||||
required: ['id'],
|
||||
additionalProperties: true,
|
||||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
const content = typeof args.content === 'string' ? args.content : '';
|
||||
if (content.trim() === '')
|
||||
throw new Error('content 不能为空。');
|
||||
const bytes = Buffer.byteLength(content, 'utf8');
|
||||
if (bytes > 7000)
|
||||
throw new Error(`content 过大:${bytes} 字节,上限 7000 字节。`);
|
||||
const rawTags = Array.isArray(args.tags) ? args.tags : [];
|
||||
const tags = rawTags.filter((tag) => typeof tag === 'string' && tag !== '').slice(0, 30);
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
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 }, workspace);
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。');
|
||||
}
|
||||
throw new Error(`写入失败:${describeError(result.error)}`);
|
||||
}
|
||||
return {
|
||||
id: result.data.id,
|
||||
revision: result.data.revision,
|
||||
remote_saved: result.data.remote_saved,
|
||||
state: result.data.state,
|
||||
operation_id: result.data.operation_id ?? operationId,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
/** List recent memories. */
|
||||
function listTool(deps) {
|
||||
return {
|
||||
name: 'memory_list',
|
||||
description: '按时间倒序列出云端记忆(可分页,可按项目过滤)。适合浏览最近保存了什么,再决定是否 memory_read 取全文。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
|
||||
offset: { type: 'integer', description: '跳过条数,默认 0。' },
|
||||
project_id: { type: 'string', description: '可选:只看某个项目。' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: { type: 'object', properties: { total: { type: 'number' }, items: { type: 'array', items: { type: 'object' } } }, required: ['items'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
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 }, 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) };
|
||||
},
|
||||
};
|
||||
}
|
||||
/** List projects known to the account. */
|
||||
function projectsTool(deps) {
|
||||
return {
|
||||
name: 'memory_projects',
|
||||
description: '列出云端账号下的记忆项目(project_id 与名称),用于给 memory_add 选择归属项目。',
|
||||
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
||||
output: {
|
||||
schema: { type: 'object', properties: { projects: { type: 'array', items: { type: 'object' } } }, required: ['projects'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(_args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
const result = await deps.remote().projects(workspace);
|
||||
if (!result.ok)
|
||||
throw new Error(`项目列表读取失败:${describeError(result.error)}`);
|
||||
return { projects: result.data.projects ?? [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Build every memory tool for one plugin instance. */
|
||||
export function createMemoryTools(deps) {
|
||||
return [searchTool(deps), readTool(deps), addTool(deps), listTool(deps), projectsTool(deps)];
|
||||
}
|
||||
|
|
@ -10,16 +10,15 @@
|
|||
* Connection resolution, per call:
|
||||
* 1. the Mnemon connection for the space (service fields configured on
|
||||
* the Mnemon page, plus the space's own `projectId`),
|
||||
* 2. this package's own settings sidecar (`$DSH_HOME/dsh-brain.json`)
|
||||
* for any of endpoint/token the Mnemon side left empty — so a user
|
||||
* who already configured dsh-brain configures nothing twice.
|
||||
* 2. the injected `MemoryRemoteFactory` (cloud-sync bundle), which fills
|
||||
* any endpoint/token the Mnemon side left empty from this package's
|
||||
* settings sidecar — so a user who already configured dsh-brain
|
||||
* configures nothing twice.
|
||||
*
|
||||
* A Memory Space maps to one LongMemory project; the empty project is the
|
||||
* account-wide default scope.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { CloudClient } from "../api.js";
|
||||
import { SettingsStore } from "../store.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
/** Epoch (ms, or seconds on older payloads) → ISO string, when plausible. */
|
||||
function toIso(value) {
|
||||
|
|
@ -52,26 +51,57 @@ 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;
|
||||
remoteFactory;
|
||||
id = descriptor.id;
|
||||
/** LongMemory scores are its own scale; the host may only order by them. */
|
||||
scoreSemantics = { kind: 'provider-native' };
|
||||
store;
|
||||
constructor(authority, options = {}) {
|
||||
constructor(authority, options, remoteFactory) {
|
||||
this.authority = authority;
|
||||
this.options = options;
|
||||
}
|
||||
/** This package's settings sidecar, read lazily so edits apply live. */
|
||||
settings() {
|
||||
this.store ??= new SettingsStore({});
|
||||
return this.store;
|
||||
this.remoteFactory = remoteFactory;
|
||||
}
|
||||
/**
|
||||
* Merge the space's Mnemon connection over the package settings.
|
||||
* The authority is the source of merged service+space values; the space
|
||||
* record itself is the fallback for older hosts.
|
||||
* Merge the space's Mnemon connection fields (authority first, the space
|
||||
* record as fallback for older hosts). Fields left empty stay empty on
|
||||
* purpose: the injected factory owns the package-settings fallback.
|
||||
*/
|
||||
resolve(body, direct) {
|
||||
let connection = { ...(direct ?? {}) };
|
||||
|
|
@ -89,25 +119,22 @@ export class LongMemoryProvider {
|
|||
connection = { ...own, ...connection };
|
||||
}
|
||||
}
|
||||
const settings = this.settings().settings();
|
||||
const endpointRaw = typeof connection.endpoint === 'string' && connection.endpoint !== ''
|
||||
? connection.endpoint
|
||||
: settings.baseUrl;
|
||||
const token = typeof connection.token === 'string' && connection.token !== ''
|
||||
? connection.token
|
||||
: this.settings().memoryToken();
|
||||
const project = typeof connection.projectId === 'string' && connection.projectId !== ''
|
||||
? connection.projectId
|
||||
const endpoint = typeof connection.endpoint === 'string' && connection.endpoint !== ''
|
||||
? connection.endpoint.replace(/\/+$/, '')
|
||||
: undefined;
|
||||
return { endpoint: endpointRaw.replace(/\/+$/, ''), header: token, ...(project === undefined ? {} : { project }) };
|
||||
const token = typeof connection.token === 'string' && connection.token !== '' ? connection.token : undefined;
|
||||
const projectId = typeof connection.projectId === 'string' && connection.projectId !== '' ? connection.projectId : undefined;
|
||||
const timeoutMs = this.options.requestTimeoutMs;
|
||||
return {
|
||||
...(endpoint === undefined ? {} : { endpoint }),
|
||||
...(token === undefined ? {} : { token }),
|
||||
...(projectId === undefined ? {} : { projectId }),
|
||||
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
||||
};
|
||||
}
|
||||
/** A client bound to one resolved connection (clients here are cheap). */
|
||||
client(resolved) {
|
||||
return new CloudClient({
|
||||
baseUrl: () => resolved.endpoint,
|
||||
token: () => resolved.header,
|
||||
timeoutMs: () => this.options.requestTimeoutMs ?? this.settings().settings().requestTimeoutMs,
|
||||
});
|
||||
/** A remote bound to one resolved connection; the factory owns fallbacks. */
|
||||
client(connection) {
|
||||
return this.remoteFactory.forConnection(connection);
|
||||
}
|
||||
/** Enumerate the account's projects as Memory Spaces, plus the default scope. */
|
||||
async discover(connection, signal) {
|
||||
|
|
@ -139,9 +166,8 @@ export class LongMemoryProvider {
|
|||
async status(body, signal) {
|
||||
signal?.throwIfAborted();
|
||||
const resolved = this.resolve(body);
|
||||
if (resolved.header === '') {
|
||||
return { healthy: false, error: 'LongMemory memory token is not configured' };
|
||||
}
|
||||
// No local token short-circuit: the factory owns the sidecar fallback, so
|
||||
// only the live call can tell whether a token is configured anywhere.
|
||||
const result = await this.client(resolved).storageStatus();
|
||||
return result.ok
|
||||
? { healthy: true }
|
||||
|
|
@ -152,7 +178,7 @@ export class LongMemoryProvider {
|
|||
signal?.throwIfAborted();
|
||||
const resolved = this.resolve(body);
|
||||
const limit = Math.min(Math.max(request.limit ?? 10, 1), 100);
|
||||
const result = await this.client(resolved).search(request.query, limit, resolved.project);
|
||||
const result = await this.client(resolved).search(request.query, limit, resolved.projectId);
|
||||
if (!result.ok) {
|
||||
throw new Error(`LongMemory search failed: ${result.error.message}`);
|
||||
}
|
||||
|
|
@ -171,7 +197,7 @@ export class LongMemoryProvider {
|
|||
}
|
||||
const resolved = this.resolve(body);
|
||||
const limit = Math.min(Math.max(request.limit ?? 100, 1), 200);
|
||||
const result = await this.client(resolved).list({ limit, project: resolved.project });
|
||||
const result = await this.client(resolved).list({ limit, project: resolved.projectId });
|
||||
if (!result.ok) {
|
||||
throw new Error(`LongMemory list failed: ${result.error.message}`);
|
||||
}
|
||||
|
|
@ -186,19 +212,36 @@ export class LongMemoryProvider {
|
|||
const result = await this.client(resolved).add({
|
||||
content: request.content,
|
||||
...(request.tags === undefined ? {} : { tags: request.tags }),
|
||||
...(resolved.project === undefined ? {} : { project: resolved.project }),
|
||||
...(resolved.projectId === undefined ? {} : { project: resolved.projectId }),
|
||||
...(request.category === undefined ? {} : { sector: request.category }),
|
||||
operationId: `mnemon-${randomUUID()}`,
|
||||
});
|
||||
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. */
|
||||
|
|
@ -208,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,12 +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.2';
|
||||
/** 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,
|
||||
|
|
@ -36,7 +38,7 @@ export const definition = defineMemorySpaceProviderDefinition({
|
|||
secrets: descriptor.fields.filter((field) => field.input === 'secret').map((field) => field.key),
|
||||
scoreSemantics: 'provider-native',
|
||||
},
|
||||
create: (context) => new LongMemoryProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs }),
|
||||
create: (context) => new LongMemoryProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs }, createSidecarMemoryRemoteFactory()),
|
||||
});
|
||||
export default defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
|
|
|
|||
|
|
@ -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); },
|
||||
});
|
||||
220
lib/reporter.js
220
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);
|
||||
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);
|
||||
}
|
||||
/** 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));
|
||||
}
|
||||
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.
|
||||
*/
|
||||
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;
|
||||
|
|
|
|||
985
lib/routes.js
985
lib/routes.js
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,170 @@
|
|||
import { departmentSnippet } from "../memory/departments-tools.js";
|
||||
import { fail, json, readBody, sameOrigin } from "../http.js";
|
||||
function errorStatus(message) {
|
||||
if (message === 'department_not_found')
|
||||
return 404;
|
||||
if (message === 'revision_conflict')
|
||||
return 409;
|
||||
if (message === 'department_disabled')
|
||||
return 409;
|
||||
if (message === 'department_required_field' || message === 'department_invalid_host' || message === 'secret_not_allowed')
|
||||
return 400;
|
||||
return undefined;
|
||||
}
|
||||
function failDepartment(res, error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const status = errorStatus(message);
|
||||
if (status === undefined) {
|
||||
fail(res, 500, 'internal-error');
|
||||
return;
|
||||
}
|
||||
fail(res, status, message);
|
||||
}
|
||||
async function bodyObject(req, res) {
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(await readBody(req));
|
||||
}
|
||||
catch {
|
||||
fail(res, 400, 'invalid-json');
|
||||
return undefined;
|
||||
}
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||
fail(res, 400, 'invalid-body');
|
||||
return undefined;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function stringField(value) { return typeof value === 'string' ? value : undefined; }
|
||||
function revisionField(value) { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined; }
|
||||
export async function serveDepartments(deps, req, res) {
|
||||
const manager = deps.departments;
|
||||
if (manager === undefined) {
|
||||
fail(res, 503, 'departments-unavailable');
|
||||
return;
|
||||
}
|
||||
if (deps.store.settings().localMemoryEnabled === false) {
|
||||
fail(res, 503, 'local-memory-disabled');
|
||||
return;
|
||||
}
|
||||
const withWorkspace = (workspace, job) => deps.localMemory === undefined ? job() : deps.localMemory.withWorkspace(workspace, job);
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
const marker = '/departments';
|
||||
const at = url.pathname.indexOf(marker);
|
||||
const suffix = at < 0 ? '' : url.pathname.slice(at + marker.length);
|
||||
try {
|
||||
if (suffix === '' || suffix === '/' || suffix === '/list') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const scope = url.searchParams.get('scope') === 'global' ? 'global' : url.searchParams.get('scope') === 'project' ? 'project' : undefined;
|
||||
const workspace = url.searchParams.get('workspace')?.trim() || undefined;
|
||||
json(res, 200, { ok: true, departments: await withWorkspace(workspace, () => manager.list(scope)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/create') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
const body = await bodyObject(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const workspace = stringField(body.workspace)?.trim() || undefined;
|
||||
const name = stringField(body.name)?.trim() ?? '';
|
||||
if (name === '') {
|
||||
fail(res, 400, 'name-required');
|
||||
return;
|
||||
}
|
||||
const input = {
|
||||
name,
|
||||
...(stringField(body.role) === undefined ? {} : { role: stringField(body.role) }),
|
||||
...(body.scope === 'global' || body.scope === 'project' ? { scope: body.scope } : {}),
|
||||
...(Array.isArray(body.skills) ? { skills: body.skills.filter((item) => typeof item === 'string') } : {}),
|
||||
...(Array.isArray(body.allowedTools) ? { allowedTools: body.allowedTools.filter((item) => typeof item === 'string') } : {}),
|
||||
...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}),
|
||||
...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}),
|
||||
};
|
||||
json(res, 200, { ok: true, ...(await withWorkspace(workspace, () => manager.create(input))) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/update' || suffix === '/disable' || suffix === '/checkpoint' || suffix === '/resume') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
const body = await bodyObject(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const workspace = stringField(body.workspace)?.trim() || undefined;
|
||||
const id = stringField(body.id)?.trim() ?? '';
|
||||
if (id === '') {
|
||||
fail(res, 400, 'id-required');
|
||||
return;
|
||||
}
|
||||
const expectedRevision = revisionField(body.expectedRevision);
|
||||
if (suffix === '/update') {
|
||||
const patch = {
|
||||
...(stringField(body.name) === undefined ? {} : { name: stringField(body.name) }),
|
||||
...(stringField(body.role) === undefined ? {} : { role: stringField(body.role) }),
|
||||
...(Array.isArray(body.skills) ? { skills: body.skills.filter((item) => typeof item === 'string') } : {}),
|
||||
...(Array.isArray(body.allowedTools) ? { allowedTools: body.allowedTools.filter((item) => typeof item === 'string') } : {}),
|
||||
...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}),
|
||||
...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}),
|
||||
};
|
||||
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.update(id, patch, expectedRevision)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/disable') {
|
||||
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.disable(id, expectedRevision)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/checkpoint') {
|
||||
const input = {
|
||||
...(stringField(body.currentTask) === undefined ? {} : { currentTask: stringField(body.currentTask) }),
|
||||
...(stringField(body.handoff) === undefined ? {} : { handoff: stringField(body.handoff) }),
|
||||
};
|
||||
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.checkpoint(id, input, expectedRevision)) });
|
||||
return;
|
||||
}
|
||||
const host = stringField(body.host)?.trim() || 'dsh';
|
||||
const hostSessionId = stringField(body.hostSessionId)?.trim();
|
||||
const sessionRef = await withWorkspace(workspace, async () => hostSessionId !== undefined && hostSessionId !== ''
|
||||
? manager.attachSession(id, host, hostSessionId)
|
||||
: manager.resumeSession(id, host));
|
||||
json(res, 200, { ok: true, sessionRef });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/recall') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const id = (url.searchParams.get('id') ?? '').trim();
|
||||
if (id === '') {
|
||||
fail(res, 400, 'id-required');
|
||||
return;
|
||||
}
|
||||
const query = (url.searchParams.get('query') ?? '').trim();
|
||||
const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10);
|
||||
const k = Number.isFinite(requested) ? Math.max(1, Math.min(5, requested)) : 5;
|
||||
const workspace = url.searchParams.get('workspace')?.trim() || undefined;
|
||||
const hits = await withWorkspace(workspace, () => manager.recall(id, query, k, workspace));
|
||||
json(res, 200, { ok: true, hits: hits.map((hit) => ({ ...hit, content: hit.record.content, contentSnippet: departmentSnippet(hit.record.content) })) });
|
||||
return;
|
||||
}
|
||||
fail(res, 404, 'unknown-department-route');
|
||||
}
|
||||
catch (error) {
|
||||
failDepartment(res, error);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +1,16 @@
|
|||
/**
|
||||
* Standalone configuration page.
|
||||
* Settings UI bundle — standalone configuration page.
|
||||
*
|
||||
* This profile runs with the native settings surface disabled
|
||||
* (`ui-settings` is turned off in `cordis.patch.yml`), so the plugin ships its
|
||||
* own HTML page at `/dsh-brain`. It is deliberately dependency-free: no
|
||||
* bundler assets, no CDN, no fonts — one file the host web server can emit.
|
||||
*
|
||||
* The page is a pure view: every control reads and writes through the public
|
||||
* HTTP API (`GET /status`, `PUT /config`, `POST login/test/flush`) and never
|
||||
* touches SettingsStore, CloudClient, Reporter or SkillSync directly, so
|
||||
* removing the settings-ui bundle only loses the page.
|
||||
*
|
||||
* The page renders tokens as masked values only; the plaintext never leaves
|
||||
* `$DSH_HOME/dsh-brain.json`.
|
||||
*/
|
||||
|
|
@ -229,10 +234,6 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
<label for="requestTimeoutMs">请求超时(毫秒)</label>
|
||||
<input id="requestTimeoutMs" type="number" min="1000" max="60000" step="500" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="defaultK">默认检索条数</label>
|
||||
<input id="defaultK" type="number" min="1" max="100" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="toggles">
|
||||
<label class="toggle" for="enabled">
|
||||
|
|
@ -245,6 +246,11 @@ 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="activityEnabled">
|
||||
<input id="activityEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">活动上报开关</span><span class="tdesc">只控制每轮活动上报;未显式设置时跟随总开关</span></span>
|
||||
</label>
|
||||
<div class="inline-field">
|
||||
<label for="summaryMaxChars">单轮摘要字数上限</label>
|
||||
<input id="summaryMaxChars" type="number" min="1000" max="16000" step="500" />
|
||||
|
|
@ -252,6 +258,73 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
|
|||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card" id="memoryCard">
|
||||
<div class="card-head"><span class="chip">🧠</span><h2>记忆配置</h2><span class="desc">memory_* 工具</span></div>
|
||||
<div class="grid">
|
||||
<div>
|
||||
<label for="defaultK">默认检索条数 defaultK</label>
|
||||
<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">
|
||||
<input id="memoryEnabled" type="checkbox" />
|
||||
<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>
|
||||
|
||||
<section class="card" id="skillsCard">
|
||||
<div class="card-head"><span class="chip">🔄</span><h2>Skill 同步</h2><span class="desc">后台定时双向同步</span></div>
|
||||
<div class="grid">
|
||||
<div>
|
||||
<label for="skillsDir">技能目录(可选)</label>
|
||||
<input id="skillsDir" type="text" spellcheck="false" placeholder="默认 $DSH_HOME/skills" />
|
||||
<div class="hint">留空使用默认目录;保存后下一次同步生效,无需重启。</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="toggles">
|
||||
<label class="toggle" for="skillsSyncEnabled">
|
||||
<input id="skillsSyncEnabled" type="checkbox" />
|
||||
<span class="track"></span>
|
||||
<span><span class="ttitle">启用云端技能同步</span><span class="tdesc">下载云端技能库、上传本机新技能</span></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="tip">同步动作由后台定时执行(能力缺失时本卡片自动隐藏);这里只保存开关与目录。</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head"><span class="chip">🔑</span><h2>账号登录</h2><span class="desc">用账号一次性换取令牌,密码不保存</span></div>
|
||||
<div class="grid">
|
||||
|
|
@ -365,9 +438,21 @@ 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;
|
||||
el('summaryMaxChars').value = settings.summaryMaxChars || '';
|
||||
el('memoryEnabled').checked = settings.memoryEnabled === true;
|
||||
el('skillsSyncEnabled').checked = settings.skillsSyncEnabled === true;
|
||||
el('skillsDir').value = settings.skillsDir || '';
|
||||
var features = (view.capabilities && view.capabilities.features) || {};
|
||||
el('skillsCard').style.display = features.skillsSync === false ? 'none' : '';
|
||||
|
||||
el('activityTokenHint').innerHTML = '用于 POST /activity/turn。当前 ' +
|
||||
(tokens.activity && tokens.activity.configured
|
||||
|
|
@ -440,9 +525,19 @@ 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,
|
||||
summaryMaxChars: Number(el('summaryMaxChars').value)
|
||||
summaryMaxChars: Number(el('summaryMaxChars').value),
|
||||
memoryEnabled: el('memoryEnabled').checked,
|
||||
skillsSyncEnabled: el('skillsSyncEnabled').checked,
|
||||
skillsDir: el('skillsDir').value.trim()
|
||||
};
|
||||
var activity = el('activityToken').value.trim();
|
||||
var memory = el('memoryToken').value.trim();
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import { fail } from "../http.js";
|
||||
import { renderConfigPage } from "./page.js";
|
||||
/** Must match `ROUTES.page` in `src/routes.ts`. */
|
||||
const PAGE_PATH = '/dsh-brain';
|
||||
/** Serve the configuration page. */
|
||||
function servePage(deps, req, res) {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
fail(res, 405, 'method-not-allowed', true);
|
||||
return;
|
||||
}
|
||||
const html = renderConfigPage({ version: deps.version, settingsPath: deps.store.path });
|
||||
res.writeHead(200, {
|
||||
'content-type': 'text/html; charset=utf-8',
|
||||
'cache-control': 'no-store',
|
||||
'content-length': Buffer.byteLength(html),
|
||||
});
|
||||
if (req.method === 'HEAD')
|
||||
res.end();
|
||||
else
|
||||
res.end(html);
|
||||
}
|
||||
/** The exact route the root aggregator registers for the settings page. */
|
||||
export function createSettingsUiRoutes(deps) {
|
||||
return [
|
||||
{
|
||||
kind: 'exact',
|
||||
path: PAGE_PATH,
|
||||
handler: (req, res) => servePage(deps, req, res),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
@ -30,7 +30,7 @@ import { execFile } from 'node:child_process';
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
||||
import { parseSkillFrontmatter } from "./skill-sync.js";
|
||||
import { parseSkillFrontmatter } from "./skills/shared.js";
|
||||
import { dshHome, migrateLegacyFile } from "./store.js";
|
||||
/** The parking area for disabled skills. */
|
||||
export function skillsHoldingDir() {
|
||||
|
|
@ -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,25 +166,18 @@ export class SkillAdmin {
|
|||
return this.deps.stagingRoot?.() ?? skillsStagingDir();
|
||||
}
|
||||
guardSync() {
|
||||
if (this.deps.syncRunning())
|
||||
const gate = this.deps.gate();
|
||||
const busy = gate.busy === undefined ? gate.isRunning() : gate.busy();
|
||||
if (busy)
|
||||
fail('sync_running', '技能同步正在进行,请稍候再试。');
|
||||
}
|
||||
async uploaded() {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8'));
|
||||
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
const uploaded = parsed.uploaded;
|
||||
if (uploaded !== null && typeof uploaded === 'object' && !Array.isArray(uploaded)) {
|
||||
return uploaded;
|
||||
/** 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// No sidecar yet: nothing has been uploaded.
|
||||
}
|
||||
return {};
|
||||
}
|
||||
async describe(folder, dir, enabled, uploaded) {
|
||||
async describe(folder, dir, enabled, provenance) {
|
||||
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined);
|
||||
if (markdown === undefined)
|
||||
return undefined;
|
||||
|
|
@ -204,15 +197,10 @@ export class SkillAdmin {
|
|||
// A corrupt manifest still marks cloud origin.
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (const record of Object.values(uploaded)) {
|
||||
if (record.folder === folder) {
|
||||
else if (provenance?.origin === 'uploaded') {
|
||||
origin = 'uploaded';
|
||||
if (typeof record.revision === 'number')
|
||||
revision = record.revision;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (typeof provenance.revision === 'number')
|
||||
revision = provenance.revision;
|
||||
}
|
||||
const files = await walkFiles(dir);
|
||||
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
|
||||
|
|
@ -249,13 +237,12 @@ export class SkillAdmin {
|
|||
}
|
||||
/** Inventory of the skills root and the parking area. */
|
||||
async list() {
|
||||
const uploaded = await this.uploaded();
|
||||
const skills = [];
|
||||
const scan = async (area, enabled) => {
|
||||
for (const entry of await readdir(area, { withFileTypes: true }).catch(() => [])) {
|
||||
if (!entry.isDirectory() || entry.name.startsWith('.'))
|
||||
continue;
|
||||
const described = await this.describe(entry.name, join(area, entry.name), enabled, uploaded);
|
||||
const described = await this.describe(entry.name, join(area, entry.name), enabled, await this.deps.gate().provenance(entry.name));
|
||||
if (described !== undefined)
|
||||
skills.push(described);
|
||||
}
|
||||
|
|
@ -283,7 +270,7 @@ export class SkillAdmin {
|
|||
fail('not_found', `没有找到技能:${folder}`);
|
||||
if (await isSymlink(found.dir))
|
||||
fail('unsupported', `技能目录是链接,不在这里管理:${folder}`);
|
||||
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded());
|
||||
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.deps.gate().provenance(folder));
|
||||
if (entry === undefined)
|
||||
fail('not_found', `技能缺少 SKILL.md:${folder}`);
|
||||
const files = await walkFiles(found.dir);
|
||||
|
|
@ -300,7 +287,7 @@ export class SkillAdmin {
|
|||
}
|
||||
/** Enable (move back into the root) or disable (park) one skill. */
|
||||
async setEnabled(folderInput, enabled) {
|
||||
this.guardSync();
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput);
|
||||
const found = await this.locate(folder);
|
||||
if (found === undefined)
|
||||
|
|
@ -326,6 +313,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. */
|
||||
effectNote(enabled) {
|
||||
|
|
@ -341,7 +329,7 @@ export class SkillAdmin {
|
|||
fail('not_found', `没有找到技能:${folder}`);
|
||||
if (await isSymlink(found.dir))
|
||||
fail('unsupported', `技能目录是链接,不在这里删除:${folder}`);
|
||||
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded());
|
||||
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.deps.gate().provenance(folder));
|
||||
const files = await walkFiles(found.dir);
|
||||
return {
|
||||
folder,
|
||||
|
|
@ -363,7 +351,7 @@ export class SkillAdmin {
|
|||
* itself stays usable by the verification harness and by trusted callers.
|
||||
*/
|
||||
async remove(folderInput) {
|
||||
this.guardSync();
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput);
|
||||
const found = await this.locate(folder);
|
||||
if (found === undefined)
|
||||
|
|
@ -373,6 +361,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 };
|
||||
});
|
||||
}
|
||||
async readPlans() {
|
||||
try {
|
||||
|
|
@ -413,7 +402,7 @@ export class SkillAdmin {
|
|||
* root here; the caller picks folders and commits.
|
||||
*/
|
||||
async prepareInstall(urlInput, options = {}) {
|
||||
this.guardSync();
|
||||
return this.exclusive(async () => {
|
||||
if (typeof urlInput !== 'string')
|
||||
fail('invalid_url', '请提供仓库地址。');
|
||||
const url = urlInput.trim();
|
||||
|
|
@ -529,10 +518,11 @@ export class SkillAdmin {
|
|||
...(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();
|
||||
return this.exclusive(async () => {
|
||||
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
|
||||
if (planId === '')
|
||||
fail('invalid_plan', '缺少安装计划 id。');
|
||||
|
|
@ -563,7 +553,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.
|
||||
|
|
@ -603,6 +593,7 @@ export class SkillAdmin {
|
|||
await this.writePlans(file);
|
||||
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
|
||||
return { installed, skipped, remaining };
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Import one skill folder from another tool's skills directory (the
|
||||
|
|
@ -613,7 +604,7 @@ export class SkillAdmin {
|
|||
* like a git install does.
|
||||
*/
|
||||
async importFolder(fromDir, folderInput) {
|
||||
this.guardSync();
|
||||
return this.exclusive(async () => {
|
||||
const folder = checkFolder(folderInput);
|
||||
const existing = await this.locate(folder);
|
||||
if (existing !== undefined) {
|
||||
|
|
@ -632,9 +623,11 @@ 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) {
|
||||
return this.exclusive(async () => {
|
||||
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
|
||||
if (planId === '')
|
||||
fail('invalid_plan', '缺少安装计划 id。');
|
||||
|
|
@ -645,6 +638,7 @@ export class SkillAdmin {
|
|||
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`
|
||||
|
|
@ -670,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,
|
||||
|
|
|
|||
1094
lib/skill-sync.js
1094
lib/skill-sync.js
File diff suppressed because it is too large
Load Diff
|
|
@ -104,9 +104,17 @@ export class SkillUpdater {
|
|||
return this.deps.backupsDir?.() ?? skillBackupsDir();
|
||||
}
|
||||
guard() {
|
||||
if (this.deps.syncRunning())
|
||||
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,7 +195,7 @@ export class SkillUpdater {
|
|||
}
|
||||
/** Back up the current folder, then replace it with the source's latest. */
|
||||
async applyUpdate(folderInput, expectedCommit) {
|
||||
this.guard();
|
||||
return this.exclusive(async () => {
|
||||
const folder = typeof folderInput === 'string' ? folderInput : '';
|
||||
if (folder === '')
|
||||
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
|
||||
|
|
@ -199,10 +207,11 @@ 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) {
|
||||
this.guard();
|
||||
return this.exclusive(async () => {
|
||||
const folder = typeof folderInput === 'string' ? folderInput : '';
|
||||
if (folder === '')
|
||||
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
|
||||
|
|
@ -219,6 +228,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);
|
||||
|
|
@ -232,11 +242,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,
|
||||
|
|
@ -244,6 +253,7 @@ export class SkillUpdater {
|
|||
backup: backupDir,
|
||||
...diff,
|
||||
};
|
||||
});
|
||||
}
|
||||
/** Shared write path: backup, copy new tree, rewrite provenance. */
|
||||
async replaceWith(dir, source, next) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
// Skill bundle member — the seam between skill management and cloud sync.
|
||||
// The skill bundle owns the local skill folders and their receipts; the
|
||||
// cloud-sync engine (src/skill-sync.ts) reads and writes them only through
|
||||
// SkillRepository, and asks SkillSyncGate what it needs to know about the
|
||||
// sync pass. Nothing on the sync side touches a skill directory directly.
|
||||
//
|
||||
// Reserved convention: the `.manifest.json` file inside a skill folder is the
|
||||
// cloud delivery receipt. repository.read() reports it as `delivery`, never
|
||||
// as one of `files`; repository.write() writes it by default and clears it
|
||||
// with { delivery: false }. Dot-prefixed files are private to the skill side
|
||||
// and never take part in a sync.
|
||||
export {};
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
// Skill bundle member — SkillRepository over the skill admin.
|
||||
// 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 { randomUUID } from 'node:crypto';
|
||||
import { dirname, join, resolve, sep } from 'node:path';
|
||||
import { dshHome } from "../store.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 {
|
||||
return (await stat(path)).isDirectory();
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/** Walk a skill folder skipping dot-prefixed names — the reserved-file rule. */
|
||||
async function walkSkillFiles(dir) {
|
||||
const files = [];
|
||||
const walk = async (current, depth) => {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(current, { withFileTypes: true });
|
||||
}
|
||||
catch {
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.name.startsWith('.'))
|
||||
continue;
|
||||
const full = join(current, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
await walk(full, depth + 1);
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile())
|
||||
continue;
|
||||
files.push({
|
||||
rel: full.slice(dir.length + 1).replace(/\\/g, '/'),
|
||||
bytes: await readFile(full),
|
||||
mtimeMs: (await stat(full)).mtimeMs,
|
||||
});
|
||||
}
|
||||
};
|
||||
await walk(dir, 0);
|
||||
return files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
|
||||
}
|
||||
/** Parse the `.manifest.json` delivery receipt of one folder. */
|
||||
async function readDeliveryReceipt(dir) {
|
||||
try {
|
||||
const raw = JSON.parse(await readFile(join(dir, RECEIPT), 'utf8'));
|
||||
if (typeof raw !== 'object' || raw === null)
|
||||
return undefined;
|
||||
const record = raw;
|
||||
if (typeof record.name !== 'string' || typeof record.revision !== 'number' || typeof record.manifest_sha256 !== 'string')
|
||||
return undefined;
|
||||
const files = Array.isArray(record.files)
|
||||
? record.files.filter((file) => typeof file === 'object' && file !== null && typeof file.path === 'string' && typeof file.sha256 === 'string')
|
||||
: undefined;
|
||||
const delivery = { name: record.name, revision: record.revision, manifest: record.manifest_sha256 };
|
||||
if (files !== undefined && files.length > 0)
|
||||
delivery.files = files;
|
||||
if (typeof record.synced_at === 'string')
|
||||
delivery.syncedAt = record.synced_at;
|
||||
return delivery;
|
||||
}
|
||||
catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
export class AdminSkillRepository {
|
||||
deps;
|
||||
constructor(deps) {
|
||||
this.deps = deps;
|
||||
}
|
||||
async list() {
|
||||
const entries = [];
|
||||
// Root skips dot-prefixed folders, mirroring the upload scan; holding
|
||||
// takes every folder, mirroring the sync presence sweep.
|
||||
for (const entry of await readdir(this.deps.skillsRoot(), { withFileTypes: true }).catch(() => [])) {
|
||||
if (!entry.isDirectory() || entry.name.startsWith('.'))
|
||||
continue;
|
||||
entries.push({ name: entry.name, area: 'root', enabled: true });
|
||||
}
|
||||
for (const entry of await readdir(this.deps.holdingDir(), { withFileTypes: true }).catch(() => [])) {
|
||||
if (!entry.isDirectory())
|
||||
continue;
|
||||
entries.push({ name: entry.name, area: 'holding', enabled: false });
|
||||
}
|
||||
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.locate(name);
|
||||
if (found === undefined)
|
||||
return undefined;
|
||||
const area = found.area;
|
||||
const files = (await walkSkillFiles(found.dir)).map((file) => ({
|
||||
path: file.rel,
|
||||
sha256: sha256Hex(file.bytes),
|
||||
size: file.bytes.length,
|
||||
data: file.bytes.toString('base64'),
|
||||
mtimeMs: file.mtimeMs,
|
||||
}));
|
||||
return { name, area, files, delivery: await readDeliveryReceipt(found.dir) };
|
||||
}
|
||||
async write(name, bundle, options) {
|
||||
// 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 });
|
||||
// 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.
|
||||
// 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);
|
||||
if (options?.delivery === false) {
|
||||
await rm(receipt, { force: true });
|
||||
return;
|
||||
}
|
||||
const payload = { name, revision: bundle.revision, manifest_sha256: bundle.manifest_sha256, files: written, synced_at: new Date().toISOString() };
|
||||
const tmp = `${receipt}.tmp-${randomUUID()}`;
|
||||
await writeFile(tmp, JSON.stringify(payload, null, 2) + '\n');
|
||||
await rename(tmp, receipt);
|
||||
}
|
||||
async park(name) {
|
||||
await this.deps.admin.setEnabled(name, false);
|
||||
}
|
||||
async unpark(name) {
|
||||
await this.deps.admin.setEnabled(name, true);
|
||||
}
|
||||
async snapshot(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);
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await cp(found.dir, target, {
|
||||
recursive: true,
|
||||
filter: (source) => !source.split(/[\\/]/).includes('.git'),
|
||||
});
|
||||
return target;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,462 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { SkillAdminError } from "../skill-admin.js";
|
||||
import { SkillGroupError } from "../skill-groups.js";
|
||||
import { MarketError } from "../market.js";
|
||||
import { renderSkillsPage } from "../skill-page.js";
|
||||
import { fail, json, jsonBody } from "../http.js";
|
||||
/** Path constants — kept in sync with the ROUTES map in routes.ts by hand. */
|
||||
const PATHS = {
|
||||
skills: '/dsh-brain/skills',
|
||||
market: '/dsh-brain/market',
|
||||
clients: '/dsh-brain/clients',
|
||||
};
|
||||
/**
|
||||
* Uninstall confirmations.
|
||||
*
|
||||
* A preview issues a single-use token bound to one folder; the delete route
|
||||
* refuses without it, so a stray click cannot remove a skill.
|
||||
*/
|
||||
const uninstallTokens = new Map();
|
||||
const UNINSTALL_TOKEN_TTL_MS = 10 * 60_000;
|
||||
/** HTTP status for one skill-admin failure code. */
|
||||
function adminStatus(code) {
|
||||
switch (code) {
|
||||
case 'not_found': return 404;
|
||||
case 'invalid_name':
|
||||
case 'invalid_url':
|
||||
case 'invalid_plan': return 400;
|
||||
case 'collision':
|
||||
case 'sync_running':
|
||||
case 'plan_expired':
|
||||
case 'confirmation_required':
|
||||
case 'no_source':
|
||||
case 'up_to_date':
|
||||
case 'stale_plan':
|
||||
case 'unsupported': return 409;
|
||||
case 'no_backup': return 404;
|
||||
case 'no_skills_found': return 422;
|
||||
case 'git_failed': return 502;
|
||||
default: return 500;
|
||||
}
|
||||
}
|
||||
/** Issue the single-use token a delete needs. */
|
||||
function issueUninstallToken(folder) {
|
||||
const token = `uninstall_${randomUUID()}`;
|
||||
uninstallTokens.set(folder, { token, expiresAt: Date.now() + UNINSTALL_TOKEN_TTL_MS });
|
||||
return token;
|
||||
}
|
||||
/** Consume one uninstall token; false when it is missing, stale or foreign. */
|
||||
function useUninstallToken(folder, token) {
|
||||
const record = uninstallTokens.get(folder);
|
||||
if (record === undefined)
|
||||
return false;
|
||||
if (typeof token !== 'string' || token !== record.token)
|
||||
return false;
|
||||
if (record.expiresAt < Date.now()) {
|
||||
uninstallTokens.delete(folder);
|
||||
return false;
|
||||
}
|
||||
uninstallTokens.delete(folder);
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* The skill management surface, one prefix route:
|
||||
* `GET /dsh-brain/skills` the management page
|
||||
* `GET /dsh-brain/skills/api` inventory JSON (skills + plans)
|
||||
* `POST /dsh-brain/skills/detail` { folder } — one skill with SKILL.md
|
||||
* `POST /dsh-brain/skills/toggle` { folder, enabled }
|
||||
* `POST /dsh-brain/skills/install/plan` { url } — stage the repository
|
||||
* `POST /dsh-brain/skills/install/commit` { planId, folders }
|
||||
* `POST /dsh-brain/skills/install/cancel` { planId }
|
||||
* `POST /dsh-brain/skills/uninstall/plan` { folder } — impact preview
|
||||
* `POST /dsh-brain/skills/remove` { folder, token, confirmed: true }
|
||||
*/
|
||||
async function serveSkills(deps, req, res) {
|
||||
const admin = deps.admin;
|
||||
if (admin === undefined) {
|
||||
fail(res, 404, 'skills-admin-unavailable');
|
||||
return;
|
||||
}
|
||||
const suffix = (req.url ?? '').split('?')[0]?.slice(PATHS.skills.length) ?? '';
|
||||
if (suffix === '' || suffix === '/') {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
fail(res, 405, 'method-not-allowed', true);
|
||||
return;
|
||||
}
|
||||
const html = renderSkillsPage({ version: deps.version });
|
||||
res.writeHead(200, {
|
||||
'content-type': 'text/html; charset=utf-8',
|
||||
'cache-control': 'no-store',
|
||||
'content-length': Buffer.byteLength(html),
|
||||
});
|
||||
if (req.method === 'HEAD')
|
||||
res.end();
|
||||
else
|
||||
res.end(html);
|
||||
return;
|
||||
}
|
||||
if (suffix === '/api') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const inventory = await admin.list();
|
||||
json(res, 200, { ok: true, ...inventory, ...(await admin.listPlans()) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/sources') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const groups = deps.groups;
|
||||
if (groups === undefined) {
|
||||
fail(res, 404, 'skill-groups-unavailable');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, ...(await groups.overview()) });
|
||||
return;
|
||||
}
|
||||
const actions = {
|
||||
'/detail': async (body) => ({ ...(await admin.detail(body.folder)) }),
|
||||
'/toggle': async (body) => ({ ...(await admin.setEnabled(body.folder, body.enabled === true)) }),
|
||||
// One-shot install kept for the standalone page; the card uses plan/commit.
|
||||
'/install': async (body) => ({ ...(await admin.installFromGit(body.url)) }),
|
||||
'/install/plan': async (body) => ({ ...(await admin.prepareInstall(body.url)) }),
|
||||
'/install/commit': async (body) => ({ ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) }),
|
||||
'/install/cancel': async (body) => ({ ...(await admin.cancelInstall({ planId: body.planId })) }),
|
||||
'/uninstall/plan': async (body) => {
|
||||
const plan = await admin.uninstallPlan(body.folder);
|
||||
return { ...plan, token: issueUninstallToken(plan.folder) };
|
||||
},
|
||||
'/remove': async (body) => {
|
||||
if (body.confirmed !== true) {
|
||||
throw new SkillAdminError('confirmation_required', '删除必须显式确认:先预览影响,再传 confirmed=true。');
|
||||
}
|
||||
const folder = typeof body.folder === 'string' ? body.folder : '';
|
||||
if (!useUninstallToken(folder, body.token)) {
|
||||
throw new SkillAdminError('confirmation_required', '卸载确认已过期或与该技能不匹配,请重新预览。');
|
||||
}
|
||||
return { ...(await admin.remove(folder)) };
|
||||
},
|
||||
};
|
||||
// Update/rollback operate on skills with a `.skill-source.json` record. They
|
||||
// are optional: without the updater wired in the routes answer 404.
|
||||
const updateActions = {
|
||||
'/update/check': async (body) => ({ ...(await requireUpdates(deps).checkUpdate(body.folder)) }),
|
||||
'/update/apply': async (body) => ({ ...(await requireUpdates(deps).applyUpdate(body.folder, body.expectedCommit)) }),
|
||||
'/rollback': async (body) => ({ ...(await requireUpdates(deps).rollback(body.folder)) }),
|
||||
};
|
||||
// Category and source switches live in the same prefix so the card has one
|
||||
// base URL; they are grouped here because they never touch a skill folder
|
||||
// directly (except the DSH park/unpark the group manager delegates).
|
||||
const groupActions = {
|
||||
'/import': async (body) => ({ ...(await requireGroups(deps).importSkill(body.sourceId, body.folder)) }),
|
||||
'/groups/create': async (body) => ({ ...(await requireGroups(deps).createGroup(body.sourceId, body.name)) }),
|
||||
'/groups/rename': async (body) => ({ ...(await requireGroups(deps).renameGroup(body.sourceId, body.groupId, body.name)) }),
|
||||
'/groups/delete': async (body) => ({ ...(await requireGroups(deps).deleteGroup(body.sourceId, body.groupId)) }),
|
||||
'/groups/assign': async (body) => ({ ...(await requireGroups(deps).assign(body.sourceId, body.groupId, body.folders)) }),
|
||||
'/groups/toggle': async (body) => ({ ...(await requireGroups(deps).toggleGroup(body.sourceId, body.groupId, body.enabled === true)) }),
|
||||
'/source/toggle': async (body) => ({ ...(await requireGroups(deps).toggleSource(body.sourceId, body.enabled === true)) }),
|
||||
'/source/reveal': async (body) => ({ ...(await requireGroups(deps).reveal(body.sourceId)) }),
|
||||
};
|
||||
const action = actions[suffix] ?? groupActions[suffix] ?? updateActions[suffix];
|
||||
if (action === undefined) {
|
||||
fail(res, 404, 'unknown-skill-route');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
try {
|
||||
json(res, 200, { ok: true, ...(await action(body)) });
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof SkillAdminError) {
|
||||
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
|
||||
return;
|
||||
}
|
||||
if (error instanceof SkillGroupError) {
|
||||
json(res, groupStatus(error.code), { ok: false, code: error.code, error: error.message });
|
||||
return;
|
||||
}
|
||||
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
}
|
||||
/** The group manager is optional; the routes answer 404 when it is absent. */
|
||||
function requireGroups(deps) {
|
||||
if (deps.groups === undefined)
|
||||
throw new SkillGroupError('unavailable', '技能分组功能未启用。');
|
||||
return deps.groups;
|
||||
}
|
||||
/** HTTP status for one group failure code. */
|
||||
function groupStatus(code) {
|
||||
switch (code) {
|
||||
case 'not_found':
|
||||
case 'unknown_source': return 404;
|
||||
case 'invalid_name':
|
||||
case 'duplicate':
|
||||
case 'import_from_self':
|
||||
case 'invalid_skill':
|
||||
case 'too_many': return 400;
|
||||
case 'unavailable': return 503;
|
||||
default: return 500;
|
||||
}
|
||||
}
|
||||
/** The updater is optional; its routes answer 404 when it is absent. */
|
||||
function requireUpdates(deps) {
|
||||
if (deps.updates === undefined)
|
||||
throw new SkillAdminError('unsupported', '技能更新/回退未启用。');
|
||||
return deps.updates;
|
||||
}
|
||||
/** HTTP status for one market failure code. */
|
||||
function marketStatus(code) {
|
||||
switch (code) {
|
||||
case 'unknown_provider':
|
||||
case 'invalid_manifest': return 400;
|
||||
case 'not_found': return 404;
|
||||
case 'unreachable':
|
||||
case 'unavailable': return 502;
|
||||
default:
|
||||
return code.startsWith('http_') ? 502 : 500;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Market surface, one prefix route:
|
||||
* `GET /dsh-brain/market/providers` configured sources
|
||||
* `GET /dsh-brain/market/search` ?provider=&q=&cursor=
|
||||
* `POST /dsh-brain/market/detail` { provider, id }
|
||||
* `POST /dsh-brain/market/plan` { provider, id } — pin commit + stage a plan
|
||||
* `POST /dsh-brain/market/commit` { planId, folders }
|
||||
* `POST /dsh-brain/market/cancel` { planId }
|
||||
*/
|
||||
async function serveMarket(deps, req, res) {
|
||||
const market = deps.market;
|
||||
if (market === undefined) {
|
||||
fail(res, 404, 'market-unavailable');
|
||||
return;
|
||||
}
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
const suffix = url.pathname.slice(PATHS.market.length);
|
||||
try {
|
||||
if (suffix === '' || suffix === '/' || suffix === '/providers') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, providers: market.list() });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/search') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const providerId = url.searchParams.get('provider') ?? market.list()[0]?.id ?? '';
|
||||
const query = url.searchParams.get('q') ?? '';
|
||||
const cursorRaw = Number(url.searchParams.get('cursor') ?? '0');
|
||||
const cursor = Number.isFinite(cursorRaw) && cursorRaw > 0 ? cursorRaw : 0;
|
||||
const result = await market.search(providerId, query, cursor);
|
||||
json(res, 200, { ok: true, provider: market.get(providerId).info(), ...result });
|
||||
return;
|
||||
}
|
||||
const admin = deps.admin;
|
||||
const requireAdmin = () => {
|
||||
if (admin === undefined)
|
||||
throw new MarketError('unavailable', '技能管理未启用,无法安装。');
|
||||
return admin;
|
||||
};
|
||||
const actions = {
|
||||
'/detail': async (body) => ({ ...(await market.detail(String(body.provider ?? ''), String(body.id ?? ''))) }),
|
||||
'/plan': async (body) => {
|
||||
const providerId = String(body.provider ?? '');
|
||||
const id = String(body.id ?? '');
|
||||
const artifact = await market.resolve(providerId, id, typeof body.version === 'string' ? body.version : undefined);
|
||||
const plan = await requireAdmin().prepareInstall(artifact.repoUrl, {
|
||||
ref: artifact.ref,
|
||||
source: {
|
||||
provider: providerId,
|
||||
entryId: id,
|
||||
...(artifact.version === undefined ? {} : { version: artifact.version }),
|
||||
},
|
||||
});
|
||||
const wanted = new Set(artifact.folders);
|
||||
return {
|
||||
planId: plan.planId,
|
||||
...(plan.commit === undefined ? {} : { commit: plan.commit }),
|
||||
artifact,
|
||||
candidates: plan.candidates.filter((candidate) => wanted.has(candidate.folder)),
|
||||
totalInRepo: plan.candidates.length,
|
||||
};
|
||||
},
|
||||
'/commit': async (body) => ({ ...(await requireAdmin().commitInstall({ planId: body.planId, folders: body.folders })) }),
|
||||
'/cancel': async (body) => ({ ...(await requireAdmin().cancelInstall({ planId: body.planId })) }),
|
||||
};
|
||||
const action = actions[suffix];
|
||||
if (action === undefined) {
|
||||
fail(res, 404, 'unknown-market-route');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
json(res, 200, { ok: true, ...(await action(body)) });
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof MarketError) {
|
||||
json(res, marketStatus(error.code), { ok: false, code: error.code, error: error.message });
|
||||
return;
|
||||
}
|
||||
if (error instanceof SkillAdminError) {
|
||||
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
|
||||
return;
|
||||
}
|
||||
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
}
|
||||
/** Cross-software / workspace inventory routes. */
|
||||
async function serveClients(deps, req, res) {
|
||||
const registry = deps.clients;
|
||||
if (registry === undefined) {
|
||||
fail(res, 404, 'clients-unavailable');
|
||||
return;
|
||||
}
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
const suffix = url.pathname.slice(PATHS.clients.length);
|
||||
try {
|
||||
if (suffix === '' || suffix === '/' || suffix === '/overview') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
json(res, 200, { ok: true, ...(await registry.overview()) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/inventory') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const result = await registry.inventory(url.searchParams.get('software'), url.searchParams.get('scope'), url.searchParams.get('workspaceId') ?? undefined);
|
||||
json(res, 200, { ok: true, ...result });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/workspaces/add') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const workspace = await registry.addWorkspace(body.software, body.path, body.name);
|
||||
json(res, 200, { ok: true, workspace });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/workspaces/remove') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
json(res, 200, { ok: true, ...(await registry.removeWorkspace(body.software, body.id)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/workspace/inventory') {
|
||||
if (req.method !== 'GET') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const { admin, workspace } = await registry.workspaceSkillAdmin(url.searchParams.get('software'), url.searchParams.get('workspaceId'));
|
||||
json(res, 200, { ok: true, workspace, ...(await admin.list()) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/workspace/detail') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
|
||||
json(res, 200, { ok: true, ...(await admin.detail(body.folder)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/workspace/toggle') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
|
||||
json(res, 200, { ok: true, ...(await admin.setEnabled(body.folder, body.enabled === true)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/workspace/remove') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
if (body.confirmed !== true)
|
||||
throw new SkillAdminError('confirmation_required', '工作区技能删除必须显式 confirmed:true。');
|
||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
|
||||
json(res, 200, { ok: true, ...(await admin.remove(body.folder)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/workspace/install/plan') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
|
||||
json(res, 200, { ok: true, ...(await admin.prepareInstall(body.url)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/workspace/install/commit') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
|
||||
json(res, 200, { ok: true, ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) });
|
||||
return;
|
||||
}
|
||||
fail(res, 404, 'unknown-clients-route');
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof SkillAdminError) {
|
||||
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
|
||||
return;
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const known = ['invalid_software', 'invalid_path', 'duplicate', 'not_found', 'unknown_workspace', 'unsupported_workspace_write'];
|
||||
const code = known.includes(message) ? message : 'internal';
|
||||
const status = code === 'internal' ? 500
|
||||
: code === 'not_found' || code === 'unknown_workspace' ? 404
|
||||
: code === 'duplicate' ? 409
|
||||
: code === 'unsupported_workspace_write' ? 501 : 400;
|
||||
json(res, status, { ok: false, code, error: message });
|
||||
}
|
||||
}
|
||||
/** Skill-bundle routes; the root aggregator decides the registration order. */
|
||||
export function createSkillRoutes(deps) {
|
||||
return [
|
||||
{ kind: 'prefix', path: PATHS.skills, handler: (req, res) => serveSkills(deps, req, res) },
|
||||
{ kind: 'prefix', path: PATHS.market, handler: (req, res) => serveMarket(deps, req, res) },
|
||||
{ kind: 'prefix', path: PATHS.clients, handler: (req, res) => serveClients(deps, req, res) },
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
// Skill bundle member — the shared on-disk skill format helpers.
|
||||
// Both sides of the seam speak this vocabulary: the repository and admin
|
||||
// validate folder layouts with it, and the sync engine reuses the same
|
||||
// constants when it prepares uploads. Moved verbatim from skill-sync.ts.
|
||||
import { createHash } from 'node:crypto';
|
||||
export const CLOUD_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
||||
/** Layout contract of the cloud skill center (mirrors its store rules). */
|
||||
export const TEXT_EXT = new Set(['.md', '.txt', '.json', '.yaml', '.yml', '.py', '.sh', '.ps1', '.mjs', '.js', '.ts', '.tsx', '.css', '.html', '.csv']);
|
||||
export const BINARY_EXT = new Set(['.docx', '.xlsx', '.pptx', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.zip']);
|
||||
export const SCRIPT_EXT = new Set(['.py', '.sh', '.ps1', '.mjs']);
|
||||
const SKILL_DIRS = new Set(['references', 'scripts', 'assets']);
|
||||
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
export const MAX_FILES = 100;
|
||||
export const MAX_FILE_BYTES = 512 * 1024;
|
||||
export const MAX_SKILL_BYTES = 2 * 1024 * 1024;
|
||||
export const MAX_DEPTH = 3;
|
||||
/** SHA-256 of a buffer or UTF-8 string, hex-encoded. */
|
||||
export function sha256Hex(data) {
|
||||
return createHash('sha256').update(data).digest('hex');
|
||||
}
|
||||
/**
|
||||
* The center's linked bundle manifest: one `path\0sha256` line per file,
|
||||
* sorted, under a version header. Byte-identical to the platform's own
|
||||
* computation, so locally computed manifests compare directly.
|
||||
*/
|
||||
export function linkedSkillManifest(files) {
|
||||
const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort();
|
||||
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'));
|
||||
}
|
||||
/** True when the cloud center would accept this relative file path. */
|
||||
export function isCloudSkillPath(rel) {
|
||||
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//'))
|
||||
return false;
|
||||
const segments = rel.split('/');
|
||||
if (segments.length > MAX_DEPTH)
|
||||
return false;
|
||||
for (const segment of segments) {
|
||||
if (!SEGMENT.test(segment) || segment === '.' || segment === '..')
|
||||
return false;
|
||||
}
|
||||
const dot = rel.lastIndexOf('.');
|
||||
const ext = dot === -1 ? '' : rel.slice(dot).toLowerCase();
|
||||
if (!TEXT_EXT.has(ext) && !BINARY_EXT.has(ext))
|
||||
return false;
|
||||
const first = segments[0];
|
||||
if (segments.length === 1)
|
||||
return rel === 'SKILL.md';
|
||||
if (first === undefined || !SKILL_DIRS.has(first))
|
||||
return false;
|
||||
if (first === 'scripts' && !SCRIPT_EXT.has(ext))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
/** Minimal frontmatter reader for `name` / `description` (plain scalars). */
|
||||
export function parseSkillFrontmatter(markdown) {
|
||||
if (!markdown.startsWith('---'))
|
||||
return {};
|
||||
const end = markdown.indexOf('\n---', 3);
|
||||
if (end === -1)
|
||||
return {};
|
||||
const out = {};
|
||||
for (const line of markdown.slice(3, end).split('\n')) {
|
||||
const match = /^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(line);
|
||||
if (match === null)
|
||||
continue;
|
||||
const value = (match[2] ?? '').replace(/^["']|["']$/g, '');
|
||||
if (match[1] === 'name' && value !== '')
|
||||
out.name = value;
|
||||
if (match[1] === 'description' && value !== '')
|
||||
out.description = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
177
lib/store.js
177
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,6 +97,31 @@ 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;
|
||||
if (typeof source.diagnosticsEnabled === 'boolean')
|
||||
state.diagnosticsEnabled = source.diagnosticsEnabled;
|
||||
const localMemoryK = clampInt(source.localMemoryK, 1, 100);
|
||||
if (localMemoryK !== undefined)
|
||||
state.localMemoryK = localMemoryK;
|
||||
const baseUrl = normalizeBaseUrl(source.baseUrl);
|
||||
if (baseUrl !== undefined)
|
||||
state.baseUrl = baseUrl;
|
||||
|
|
@ -110,6 +148,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 {
|
||||
|
|
@ -127,11 +170,15 @@ export class SettingsStore {
|
|||
state;
|
||||
file;
|
||||
configDefaults;
|
||||
/** Config-level explicit values for the split gates (absent = inherit `enabled`). */
|
||||
configExplicit;
|
||||
constructor(rawConfig, file = settingsPath()) {
|
||||
this.file = file;
|
||||
if (file === settingsPath())
|
||||
migrateLegacyFile(file, legacySettingsPath());
|
||||
this.configDefaults = { ...DEFAULT_SETTINGS, ...settingsFromConfig(rawConfig) };
|
||||
const fromConfig = settingsFromConfig(rawConfig);
|
||||
this.configDefaults = { ...DEFAULT_SETTINGS, ...fromConfig };
|
||||
this.configExplicit = { activityEnabled: fromConfig.activityEnabled, memoryEnabled: fromConfig.memoryEnabled };
|
||||
this.state = this.read();
|
||||
}
|
||||
/** Absolute sidecar path (exposed for the status card). */
|
||||
|
|
@ -164,6 +211,10 @@ export class SettingsStore {
|
|||
const resolved = { ...this.configDefaults };
|
||||
if (this.state.enabled !== undefined)
|
||||
resolved.enabled = this.state.enabled;
|
||||
if (this.state.activityEnabled !== undefined)
|
||||
resolved.activityEnabled = this.state.activityEnabled;
|
||||
if (this.state.memoryEnabled !== undefined)
|
||||
resolved.memoryEnabled = this.state.memoryEnabled;
|
||||
if (this.state.baseUrl !== undefined)
|
||||
resolved.baseUrl = this.state.baseUrl;
|
||||
if (this.state.clientId !== undefined)
|
||||
|
|
@ -176,19 +227,74 @@ export class SettingsStore {
|
|||
resolved.summaryEnabled = this.state.summaryEnabled;
|
||||
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;
|
||||
if (this.state.diagnosticsEnabled !== undefined)
|
||||
resolved.diagnosticsEnabled = this.state.diagnosticsEnabled;
|
||||
// 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) {
|
||||
resolved.activityEnabled = resolved.enabled;
|
||||
}
|
||||
if (this.state.memoryEnabled === undefined && this.configExplicit.memoryEnabled === undefined) {
|
||||
resolved.memoryEnabled = resolved.enabled;
|
||||
}
|
||||
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() {
|
||||
|
|
@ -198,9 +304,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),
|
||||
|
|
@ -223,6 +329,16 @@ export class SettingsStore {
|
|||
return { ok: false, error: 'enabled must be a boolean' };
|
||||
next.enabled = patch.enabled;
|
||||
}
|
||||
if (patch.activityEnabled !== undefined) {
|
||||
if (typeof patch.activityEnabled !== 'boolean')
|
||||
return { ok: false, error: 'activityEnabled must be a boolean' };
|
||||
next.activityEnabled = patch.activityEnabled;
|
||||
}
|
||||
if (patch.memoryEnabled !== undefined) {
|
||||
if (typeof patch.memoryEnabled !== 'boolean')
|
||||
return { ok: false, error: 'memoryEnabled must be a boolean' };
|
||||
next.memoryEnabled = patch.memoryEnabled;
|
||||
}
|
||||
if (patch.baseUrl !== undefined) {
|
||||
const baseUrl = normalizeBaseUrl(patch.baseUrl);
|
||||
if (baseUrl === undefined)
|
||||
|
|
@ -241,6 +357,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) {
|
||||
|
|
@ -248,6 +365,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);
|
||||
|
|
@ -272,19 +390,55 @@ export class SettingsStore {
|
|||
return { ok: false, error: 'summaryMaxChars must be a number' };
|
||||
next.summaryMaxChars = summaryMaxChars;
|
||||
}
|
||||
if (patch.skillsSyncEnabled !== undefined) {
|
||||
if (typeof patch.skillsSyncEnabled !== 'boolean')
|
||||
return { ok: false, error: 'skillsSyncEnabled must be a boolean' };
|
||||
next.skillsSyncEnabled = patch.skillsSyncEnabled;
|
||||
}
|
||||
if (patch.skillsDir !== undefined) {
|
||||
if (typeof patch.skillsDir !== 'string')
|
||||
return { ok: false, error: 'skillsDir must be a string' };
|
||||
const skillsDir = patch.skillsDir.trim();
|
||||
if (skillsDir.length > 512)
|
||||
return { ok: false, error: 'skillsDir too long' };
|
||||
next.skillsDir = skillsDir;
|
||||
}
|
||||
for (const key of ['localMemoryEnabled', 'cloudMemoryEnabled', 'autoMemorySpaces', 'autoSummaryEnabled', 'autoProfileEnabled', 'diagnosticsEnabled']) {
|
||||
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.
|
||||
|
|
@ -302,6 +456,7 @@ export class SettingsStore {
|
|||
if (provided.includes(label))
|
||||
continue;
|
||||
delete next[key];
|
||||
markCleared(next, label);
|
||||
clearedTokens.push(label);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
256
lib/tools.js
256
lib/tools.js
|
|
@ -1,259 +1,5 @@
|
|||
/**
|
||||
* Agent-facing memory tools.
|
||||
*
|
||||
* These definitions are hand-written `ToolDefinition` objects rather than
|
||||
* `defineTool(...)` calls: `defineTool` only compiles an authoring DSL into the
|
||||
* same raw JSON Schema, and importing `@deepseek-ai/dsh-tools` at runtime would
|
||||
* risk a second module instance (and a second class identity) inside a linked
|
||||
* plugin.
|
||||
*
|
||||
* Failure contract: `execute` throws and the registry turns that into
|
||||
* `isError: true`. A missing token is a normal, explainable failure — never a
|
||||
* crash in the host.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { describeError } from "./api.js";
|
||||
/** Sectors the service accepts for `metadata.primary_sector`. */
|
||||
export const SECTORS = ['semantic', 'episodic', 'procedural', 'emotional', 'reflective'];
|
||||
/** Trim a memory body down to a display-sized snippet. */
|
||||
function snippet(text, limit = 600) {
|
||||
if (typeof text !== 'string')
|
||||
return '';
|
||||
if (text.length <= limit)
|
||||
return text;
|
||||
return `${text.slice(0, limit)}…`;
|
||||
}
|
||||
/** Project one hit into the compact shape returned to the model. */
|
||||
function toHitView(hit) {
|
||||
return {
|
||||
id: hit.id,
|
||||
content: snippet(hit.content),
|
||||
tags: hit.tags ?? [],
|
||||
project_id: hit.project_id ?? null,
|
||||
sector: hit.primary_sector ?? null,
|
||||
revision: hit.revision ?? null,
|
||||
created_at: hit.created_at ?? null,
|
||||
};
|
||||
}
|
||||
/** Render any tool value as one JSON text block. */
|
||||
function renderJson(_args, value) {
|
||||
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
|
||||
return [{ type: 'text', text }];
|
||||
}
|
||||
/** Assert the memory scope is usable, or throw a message the model can act on. */
|
||||
function requireMemoryToken(deps) {
|
||||
if (!deps.settings().enabled) {
|
||||
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。');
|
||||
}
|
||||
const token = deps.memoryToken();
|
||||
if (token === '') {
|
||||
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。');
|
||||
}
|
||||
return token;
|
||||
}
|
||||
/** Search stored memories by keyword. */
|
||||
function searchTool(deps) {
|
||||
return {
|
||||
name: 'memory_search',
|
||||
description: '在云端长期记忆库中按关键词检索历史记忆片段。返回命中的记忆 id、内容摘要、标签与所属项目;' +
|
||||
'需要更多正文时用 memory_read 按 id 取全文。纯关键词匹配,不会做语义相似度检索。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
||||
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
|
||||
project_id: { type: 'string', description: '可选:只在这些项目 id 内检索。' },
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string' },
|
||||
total: { type: 'number' },
|
||||
search_mode: { type: 'string' },
|
||||
matches: { type: 'array', items: { type: 'object' } },
|
||||
},
|
||||
required: ['query', 'matches'],
|
||||
additionalProperties: true,
|
||||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
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.client().search(query, k, project);
|
||||
if (!result.ok)
|
||||
throw new Error(`检索失败:${describeError(result.error)}`);
|
||||
const matches = result.data.matches ?? [];
|
||||
return {
|
||||
query,
|
||||
total: result.data.total ?? matches.length,
|
||||
search_mode: result.data.search_mode ?? 'keyword',
|
||||
matches: matches.map(toHitView),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Read one memory by id. */
|
||||
function readTool(deps) {
|
||||
return {
|
||||
name: 'memory_read',
|
||||
description: '按 id 读取一条云端记忆的完整内容(正文、标签、项目、修订号与时间戳)。id 可先用 memory_search 或 memory_list 获得。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string', description: '记忆条目 id(必填)。' },
|
||||
},
|
||||
required: ['id'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: { type: 'object', properties: { id: { type: 'string' }, content: { type: 'string' } }, required: ['id'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
requireMemoryToken(deps);
|
||||
const id = typeof args.id === 'string' ? args.id.trim() : '';
|
||||
if (id === '')
|
||||
throw new Error('id 不能为空。');
|
||||
const result = await deps.client().read(id);
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 404)
|
||||
throw new Error(`没有找到 id=${id} 的记忆(可能已删除)。`);
|
||||
throw new Error(`读取失败:${describeError(result.error)}`);
|
||||
}
|
||||
return result.data;
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Store one new memory. */
|
||||
function addTool(deps) {
|
||||
return {
|
||||
name: 'memory_add',
|
||||
description: '向云端长期记忆库写入一条新记忆。content 上限 7000 字节,适合存结论、决策、待办与可复用事实;' +
|
||||
'不要写入密钥、令牌或完整源码。写入用 operation_id 保证幂等,重复调用不会产生重复条目。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '可选标签,最多 30 个,每个不超过 100 字符。' },
|
||||
project_id: { type: 'string', description: '可选:归属项目 id(≤128 字符)。' },
|
||||
sector: { type: 'string', enum: [...SECTORS], description: '可选:记忆分类(semantic/episodic/procedural/emotional/reflective)。' },
|
||||
operation_id: { type: 'string', description: '可选:幂等键(uuid);省略时自动生成。重试同一次写入时请复用同一个值。' },
|
||||
},
|
||||
required: ['content'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
revision: { type: 'number' },
|
||||
remote_saved: { type: 'boolean' },
|
||||
state: { type: 'string' },
|
||||
operation_id: { type: 'string' },
|
||||
},
|
||||
required: ['id'],
|
||||
additionalProperties: true,
|
||||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
requireMemoryToken(deps);
|
||||
const content = typeof args.content === 'string' ? args.content : '';
|
||||
if (content.trim() === '')
|
||||
throw new Error('content 不能为空。');
|
||||
const bytes = Buffer.byteLength(content, 'utf8');
|
||||
if (bytes > 7000)
|
||||
throw new Error(`content 过大:${bytes} 字节,上限 7000 字节。`);
|
||||
const rawTags = Array.isArray(args.tags) ? args.tags : [];
|
||||
const tags = rawTags.filter((tag) => typeof tag === 'string' && tag !== '').slice(0, 30);
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
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.client().add({ content, tags, project, sector, operationId });
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。');
|
||||
}
|
||||
throw new Error(`写入失败:${describeError(result.error)}`);
|
||||
}
|
||||
return {
|
||||
id: result.data.id,
|
||||
revision: result.data.revision,
|
||||
remote_saved: result.data.remote_saved,
|
||||
state: result.data.state,
|
||||
operation_id: result.data.operation_id ?? operationId,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
/** List recent memories. */
|
||||
function listTool(deps) {
|
||||
return {
|
||||
name: 'memory_list',
|
||||
description: '按时间倒序列出云端记忆(可分页,可按项目过滤)。适合浏览最近保存了什么,再决定是否 memory_read 取全文。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
|
||||
offset: { type: 'integer', description: '跳过条数,默认 0。' },
|
||||
project_id: { type: 'string', description: '可选:只看某个项目。' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: { type: 'object', properties: { total: { type: 'number' }, items: { type: 'array', items: { type: 'object' } } }, required: ['items'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
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.client().list({ limit, offset, project });
|
||||
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) };
|
||||
},
|
||||
};
|
||||
}
|
||||
/** List projects known to the account. */
|
||||
function projectsTool(deps) {
|
||||
return {
|
||||
name: 'memory_projects',
|
||||
description: '列出云端账号下的记忆项目(project_id 与名称),用于给 memory_add 选择归属项目。',
|
||||
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
||||
output: {
|
||||
schema: { type: 'object', properties: { projects: { type: 'array', items: { type: 'object' } } }, required: ['projects'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute() {
|
||||
requireMemoryToken(deps);
|
||||
const result = await deps.client().projects();
|
||||
if (!result.ok)
|
||||
throw new Error(`项目列表读取失败:${describeError(result.error)}`);
|
||||
return { projects: result.data.projects ?? [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Build every memory tool for one plugin instance. */
|
||||
export function createMemoryTools(deps) {
|
||||
return [searchTool(deps), readTool(deps), addTool(deps), listTool(deps), projectsTool(deps)];
|
||||
}
|
||||
import { renderJson, requireMemoryToken } from "./memory/tools.js";
|
||||
/** List the cloud skill center inventory (skills sync keeps local copies current). */
|
||||
function skillListTool(deps) {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
32
package.json
32
package.json
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-brain",
|
||||
"version": "0.9.2",
|
||||
"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",
|
||||
|
|
@ -8,9 +8,17 @@
|
|||
"exports": {
|
||||
".": "./lib/index.js",
|
||||
"./client": "./client/index.js",
|
||||
"./cloudsync": "./lib/entries/cloudsync.js",
|
||||
"./memory": "./lib/entries/memory.js",
|
||||
"./skills": "./lib/entries/skills.js",
|
||||
"./mcp": "./lib/entries/mcp.js",
|
||||
"./ui": "./lib/entries/ui.js",
|
||||
"./settings-ui": "./lib/entries/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",
|
||||
|
|
@ -31,22 +39,21 @@
|
|||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"prepack": "tsc -p tsconfig.build.json",
|
||||
"prepublishOnly": "node scripts/pack-guard.mjs"
|
||||
"build": "tsc -p tsconfig.build.json && tsdown",
|
||||
"build:client": "tsdown",
|
||||
"verify": "node scripts/verify-all.mjs",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
|
||||
"prepack": "tsc -p tsconfig.build.json && tsdown",
|
||||
"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": {
|
||||
|
|
@ -62,8 +69,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,360 @@
|
|||
// Renders the redesigned 「从其他软件导入」 panel to a PNG so the layout can be
|
||||
// reviewed before DSH is restarted. It reads the *live* skill sources through
|
||||
// the built plugin (read-only), expands the import panel, and screenshots the
|
||||
// result with headless Chrome.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
|
||||
|
||||
// ── real data ───────────────────────────────────────────────────────────
|
||||
const { SkillAdmin, skillsHoldingDir } = await import('./lib/skill-admin.js')
|
||||
const { SkillGroupManager, detectSources } = await import('./lib/skill-groups.js')
|
||||
const { SettingsStore } = await import('./lib/store.js')
|
||||
|
||||
const store = new SettingsStore({})
|
||||
const admin = new SkillAdmin({
|
||||
skillsRoot: () => join(store.path, '..', 'skills'),
|
||||
holdingDir: () => skillsHoldingDir(),
|
||||
syncStatePath: () => join(store.path, '..', 'dsh-brain-skills.json'),
|
||||
syncRunning: () => false,
|
||||
log: () => {},
|
||||
})
|
||||
const groups = new SkillGroupManager({ sources: () => detectSources(), admin, log: () => {} })
|
||||
const overview = await groups.overview()
|
||||
|
||||
const statusBody = {
|
||||
ok: true,
|
||||
settings: {
|
||||
enabled: true,
|
||||
baseUrl: 'https://your-memory-host/api/longmemory',
|
||||
baseUrlConfigured: true,
|
||||
baseUrlOrigin: 'https://your-memory-host',
|
||||
clientId: 'dsh-desktop',
|
||||
requestTimeoutMs: 5000,
|
||||
defaultK: 10,
|
||||
summaryEnabled: true,
|
||||
summaryMaxChars: 6000,
|
||||
skillsSyncEnabled: true,
|
||||
skillsDir: '',
|
||||
},
|
||||
tokens: {
|
||||
activity: { configured: true, masked: 'cmt_9f2c1a…7d4e' },
|
||||
memory: { configured: true, masked: 'cmt_3b81cc…22a9' },
|
||||
summary: { configured: true, masked: 'cmt_71ad02…9f10' },
|
||||
},
|
||||
settingsPath: '%USERPROFILE%/.dsh/dsh-brain.json',
|
||||
reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] },
|
||||
lastCheck: {
|
||||
at: Date.now(),
|
||||
checks: [
|
||||
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 200)' },
|
||||
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'ok', message: '鉴权通过' },
|
||||
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(3 个项目)' },
|
||||
{ id: 'summary', label: '摘要权限(summary:write)', state: 'ok', message: '鉴权通过' },
|
||||
],
|
||||
},
|
||||
capabilities: { version: '0.9.7', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
|
||||
skills: { running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 },
|
||||
}
|
||||
|
||||
// ── minimal React + HTML serializer ─────────────────────────────────────
|
||||
let hooks = []
|
||||
let cursor = 0
|
||||
let pendingEffects = []
|
||||
let scheduled = false
|
||||
|
||||
const React = {
|
||||
createElement(type, props, ...children) {
|
||||
const flat = []
|
||||
const push = (value) => {
|
||||
if (Array.isArray(value)) value.forEach(push)
|
||||
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
|
||||
}
|
||||
push(children)
|
||||
return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat }
|
||||
},
|
||||
useState(initial) {
|
||||
const index = cursor++
|
||||
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
|
||||
const setter = (next) => {
|
||||
const value = typeof next === 'function' ? next(hooks[index]) : next
|
||||
if (value !== hooks[index]) {
|
||||
hooks[index] = value
|
||||
scheduled = true
|
||||
}
|
||||
}
|
||||
return [hooks[index], setter]
|
||||
},
|
||||
useEffect(fn) {
|
||||
pendingEffects.push(fn)
|
||||
},
|
||||
useCallback(fn) {
|
||||
return fn
|
||||
},
|
||||
Component: function Component(props) {
|
||||
this.props = props
|
||||
},
|
||||
}
|
||||
React.Component.prototype.setState = function setState(patch) {
|
||||
this.state = { ...this.state, ...patch }
|
||||
scheduled = true
|
||||
}
|
||||
|
||||
function walk(node, visit) {
|
||||
if (node === null || node === undefined || node === false || node === true) return
|
||||
if (typeof node === 'string' || typeof node === 'number') return
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach((child) => walk(child, visit))
|
||||
return
|
||||
}
|
||||
if (typeof node.type === 'function') {
|
||||
if (node.type.prototype && typeof node.type.prototype.render === 'function') {
|
||||
const instance = new node.type(node.props)
|
||||
instance.props = node.props
|
||||
if (instance.state === undefined) instance.state = {}
|
||||
instance.setState = function setState(patch) {
|
||||
instance.state = { ...instance.state, ...patch }
|
||||
scheduled = true
|
||||
}
|
||||
walk(instance.render(), visit)
|
||||
return
|
||||
}
|
||||
walk(node.type({ ...node.props, children: node.children }), visit)
|
||||
return
|
||||
}
|
||||
visit(node)
|
||||
node.children.forEach((child) => walk(child, visit))
|
||||
}
|
||||
|
||||
const UNITLESS = new Set(['fontWeight', 'opacity', 'lineHeight', 'flex', 'zIndex', 'flexGrow', 'flexShrink'])
|
||||
|
||||
function styleOf(style) {
|
||||
const parts = []
|
||||
for (const [key, value] of Object.entries(style ?? {})) {
|
||||
if (value === null || value === undefined) continue
|
||||
const name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
|
||||
parts.push(`${name}:${typeof value === 'number' && !UNITLESS.has(key) ? `${value}px` : String(value)}`)
|
||||
}
|
||||
return parts.join(';')
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
}
|
||||
|
||||
function toHtml(node) {
|
||||
if (node === null || node === undefined || node === false || node === true) return ''
|
||||
if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node)
|
||||
if (Array.isArray(node)) return node.map(toHtml).join('')
|
||||
const { type, props, children } = node
|
||||
if (typeof type === 'function') {
|
||||
if (type.prototype && typeof type.prototype.render === 'function') {
|
||||
const instance = new type(props)
|
||||
instance.props = props
|
||||
if (instance.state === undefined) instance.state = {}
|
||||
return toHtml(instance.render())
|
||||
}
|
||||
return toHtml(type({ ...props, children }))
|
||||
}
|
||||
const attrs = []
|
||||
const style = styleOf(props.style)
|
||||
if (style !== '') attrs.push(`style="${style}"`)
|
||||
if (props.id !== undefined) attrs.push(`id="${escapeHtml(props.id)}"`)
|
||||
if (props.role !== undefined) attrs.push(`role="${escapeHtml(props.role)}"`)
|
||||
if (props.title !== undefined) attrs.push(`title="${escapeHtml(props.title)}"`)
|
||||
if (props.disabled === true) attrs.push('disabled')
|
||||
if (props.type === 'checkbox') attrs.push(props.checked === true ? 'checked' : '')
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if (key.startsWith('aria-')) attrs.push(`${key}="${escapeHtml(value)}"`)
|
||||
}
|
||||
if (type === 'input') {
|
||||
attrs.push(`value="${escapeHtml(props.value === undefined ? '' : props.value)}"`)
|
||||
attrs.push(`placeholder="${escapeHtml(props.placeholder === undefined ? '' : props.placeholder)}"`)
|
||||
attrs.push(`type="${escapeHtml(props.type === undefined ? 'text' : props.type)}"`)
|
||||
return `<input ${attrs.filter(Boolean).join(' ')}>`
|
||||
}
|
||||
return `<${type} ${attrs.filter(Boolean).join(' ')}>${children.map(toHtml).join('')}</${type}>`
|
||||
}
|
||||
|
||||
// ── drive the real bundle ───────────────────────────────────────────────
|
||||
const localStorageStub = {
|
||||
getItem: (key) => (String(key).endsWith(':tab') ? 'skills' : null),
|
||||
setItem: () => {},
|
||||
}
|
||||
let registered = null
|
||||
globalThis.window = {
|
||||
localStorage: localStorageStub,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
__ModuleLoader__: {
|
||||
load(spec) {
|
||||
const exportsObject = spec.factory(requireShim)
|
||||
const captured = []
|
||||
exportsObject.apply({
|
||||
slots: {
|
||||
inject: (_seat, fn) => fn(),
|
||||
register: (_options, component) => {
|
||||
captured.push(component)
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
})
|
||||
registered = captured[0]
|
||||
},
|
||||
},
|
||||
}
|
||||
function requireShim(id) {
|
||||
if (id === 'react') return React
|
||||
throw new Error(`unexpected require: ${id}`)
|
||||
}
|
||||
|
||||
const fakeFetch = async (url) => {
|
||||
const path = String(url).split('?')[0]
|
||||
let body = { ok: false }
|
||||
if (path === '/dsh-brain/status') body = statusBody
|
||||
else if (path === '/dsh-brain/skills/sources') body = { ok: true, ...overview }
|
||||
else if (path === '/dsh-brain/sync/status') body = { ok: true, stats: { running: false, lastRunAt: Date.now(), uploaded: [], downloaded: [] }, conflicts: [] }
|
||||
else if (path.startsWith('/dsh-brain/skills/api')) {
|
||||
body = { ok: true, skills: overview.sources[0]?.groups.flatMap((group) => group.skills) ?? [], plans: [] }
|
||||
}
|
||||
return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) }
|
||||
}
|
||||
|
||||
function loadCard() {
|
||||
registered = null
|
||||
new Function('window', 'require', 'document', 'localStorage', 'fetch', 'console', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'AbortController', source)(
|
||||
globalThis.window,
|
||||
requireShim,
|
||||
{ visibilityState: 'visible' },
|
||||
localStorageStub,
|
||||
fakeFetch,
|
||||
{ warn: () => {}, log: () => {} },
|
||||
() => 0,
|
||||
() => {},
|
||||
() => 0,
|
||||
() => {},
|
||||
AbortController,
|
||||
)
|
||||
return registered
|
||||
}
|
||||
|
||||
async function settle(element, passes) {
|
||||
let text = ''
|
||||
for (let pass = 0; pass < passes; pass += 1) {
|
||||
cursor = 0
|
||||
pendingEffects = []
|
||||
scheduled = false
|
||||
text = toHtml(element)
|
||||
const effects = pendingEffects
|
||||
pendingEffects = []
|
||||
for (const effect of effects) {
|
||||
const cleanup = effect()
|
||||
if (typeof cleanup === 'function') cleanup()
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
if (!scheduled) break
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
function clickLabel(root, prefix) {
|
||||
let clicked = false
|
||||
walk(root, (node) => {
|
||||
if (clicked) return
|
||||
const props = node.props ?? {}
|
||||
const label = props['aria-label']
|
||||
const text = typeof props.children === 'string' ? props.children : ''
|
||||
const matches = (typeof label === 'string' && label.startsWith(prefix)) || text.startsWith(prefix)
|
||||
if (matches && typeof props.onClick === 'function') {
|
||||
props.onClick()
|
||||
clicked = true
|
||||
}
|
||||
})
|
||||
return clicked
|
||||
}
|
||||
|
||||
function typeInto(root, label, value) {
|
||||
let typed = false
|
||||
walk(root, (node) => {
|
||||
if (typed) return
|
||||
const props = node.props ?? {}
|
||||
if (props['aria-label'] === label && typeof props.onChange === 'function') {
|
||||
props.onChange({ target: { value } })
|
||||
typed = true
|
||||
}
|
||||
})
|
||||
return typed
|
||||
}
|
||||
|
||||
const card = loadCard()
|
||||
const treeEl = React.createElement(card, null)
|
||||
const firstBody = await settle(treeEl, 6)
|
||||
if (!firstBody.includes('技能文件夹')) console.log('debug body head:', firstBody.slice(0, 600))
|
||||
|
||||
cursor = 0
|
||||
pendingEffects = []
|
||||
if (!clickLabel(treeEl, '从其他软件导入')) throw new Error('preview: could not find the import button')
|
||||
const body = await settle(treeEl, 6)
|
||||
if (body.includes('渲染失败')) throw new Error('the card rendered its error boundary')
|
||||
|
||||
// Second view: search filters the candidate list, then select-all-matched.
|
||||
cursor = 0
|
||||
pendingEffects = []
|
||||
if (!typeInto(treeEl, '搜索要导入的技能', 'nature')) throw new Error('preview: could not find the import search box')
|
||||
await settle(treeEl, 6)
|
||||
cursor = 0
|
||||
pendingEffects = []
|
||||
if (!clickLabel(treeEl, '全选匹配可导入')) console.warn('preview: select-all was not clickable')
|
||||
const searchBody = await settle(treeEl, 6)
|
||||
|
||||
// Third view: dark theme, default (unfiltered) state.
|
||||
cursor = 0
|
||||
pendingEffects = []
|
||||
typeInto(treeEl, '搜索要导入的技能', '')
|
||||
clickLabel(treeEl, '清空已选')
|
||||
const darkBody = await settle(treeEl, 6)
|
||||
|
||||
const page = (content, theme) => `<!doctype html><html><head><meta charset="utf-8">
|
||||
<style>
|
||||
html,body{margin:0;padding:0}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",system-ui,sans-serif;
|
||||
background:${theme === 'dark' ? '#101216' : '#f3f5f9'};color:${theme === 'dark' ? '#e8eaee' : '#1a1d21'}}
|
||||
.frame{width:600px;margin:0 auto;padding:18px 20px 24px}
|
||||
.panel{border-radius:14px;padding:16px;
|
||||
background:${theme === 'dark' ? '#191c22' : '#ffffff'};
|
||||
box-shadow:0 10px 30px rgba(0,0,0,${theme === 'dark' ? '0.45' : '0.10'})}
|
||||
button{font-family:inherit}
|
||||
input{font-family:inherit;color:inherit}
|
||||
</style></head><body><div class="frame"><div class="panel">${content}</div></div></body></html>`
|
||||
|
||||
const outDir = join(here, '_preview')
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const lightPath = join(outDir, 'import-light.html')
|
||||
const searchPath = join(outDir, 'import-search.html')
|
||||
const darkPath = join(outDir, 'import-dark.html')
|
||||
writeFileSync(lightPath, page(body, 'light'), 'utf8')
|
||||
writeFileSync(searchPath, page(searchBody, 'light'), 'utf8')
|
||||
writeFileSync(darkPath, page(darkBody, 'dark'), 'utf8')
|
||||
|
||||
const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||
for (const [input, output, height] of [
|
||||
[lightPath, join(outDir, 'import-light.png'), 2600],
|
||||
[searchPath, join(outDir, 'import-search.png'), 1600],
|
||||
[darkPath, join(outDir, 'import-dark.png'), 2600],
|
||||
]) {
|
||||
execFileSync(chrome, [
|
||||
'--headless=new',
|
||||
'--disable-gpu',
|
||||
'--hide-scrollbars',
|
||||
'--force-device-scale-factor=2',
|
||||
`--window-size=640,${height}`,
|
||||
`--screenshot=${output}`,
|
||||
`file:///${input.replace(/\\/g, '/')}`,
|
||||
], { stdio: 'ignore' })
|
||||
console.log(`wrote ${output}`)
|
||||
}
|
||||
console.log('sources:', overview.sources.map((item) => `${item.label}=${item.total}`).join(', '))
|
||||
|
|
@ -0,0 +1,344 @@
|
|||
// Renders the MCP management tab to a PNG so the search / select-all / batch
|
||||
// layout can be reviewed before DSH is restarted. Data is a representative
|
||||
// catalogue (no real host bridge is called); the render tree is the real one.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
|
||||
|
||||
const statusBody = {
|
||||
ok: true,
|
||||
settings: {
|
||||
enabled: true,
|
||||
baseUrl: 'https://your-memory-host/api/longmemory',
|
||||
baseUrlConfigured: true,
|
||||
baseUrlOrigin: 'https://your-memory-host',
|
||||
clientId: 'dsh-desktop',
|
||||
requestTimeoutMs: 5000,
|
||||
defaultK: 10,
|
||||
summaryEnabled: true,
|
||||
summaryMaxChars: 6000,
|
||||
skillsSyncEnabled: true,
|
||||
skillsDir: '',
|
||||
},
|
||||
tokens: {
|
||||
activity: { configured: true, masked: 'cmt_9f2c1a…7d4e' },
|
||||
memory: { configured: true, masked: 'cmt_3b81cc…22a9' },
|
||||
summary: { configured: true, masked: 'cmt_71ad02…9f10' },
|
||||
},
|
||||
settingsPath: '%USERPROFILE%/.dsh/dsh-brain.json',
|
||||
reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] },
|
||||
lastCheck: {
|
||||
at: Date.now(),
|
||||
checks: [
|
||||
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 200)' },
|
||||
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'ok', message: '鉴权通过' },
|
||||
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(3 个项目)' },
|
||||
{ id: 'summary', label: '摘要权限(summary:write)', state: 'ok', message: '鉴权通过' },
|
||||
],
|
||||
},
|
||||
capabilities: { version: '0.9.7', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
|
||||
skills: { running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 },
|
||||
}
|
||||
|
||||
const connections = [
|
||||
{ key: 'github', connectorId: 'c-github', name: 'github', transport: 'streamable-http', authMode: 'bearer', injectionLabel: '会话级', connectionState: 'connected', enabled: true, scope: { visibility: 'workspace' }, healthCheckedAt: Date.now() - 120000, lastError: null },
|
||||
{ key: 'notion', connectorId: 'c-notion', name: 'notion', transport: 'streamable-http', authMode: 'oauth2', injectionLabel: '会话级', connectionState: 'connected', enabled: true, scope: { visibility: 'session' }, healthCheckedAt: Date.now() - 900000, lastError: null },
|
||||
{ key: 'chrome-devtools', connectorId: 'c-chrome', name: 'chrome-devtools', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'connected', enabled: true, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 60000, lastError: null },
|
||||
{ key: 'filesystem', connectorId: 'c-fs', name: 'filesystem', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'disabled', enabled: false, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 86400000, lastError: null },
|
||||
{ key: 'postgres', connectorId: 'c-pg', name: 'postgres', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'error', enabled: true, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 3600000, lastError: 'spawn postgres-mcp ENOENT' },
|
||||
{ key: 'brave-search', connectorId: 'c-brave', name: 'brave-search', transport: 'streamable-http', authMode: 'api-key', injectionLabel: '会话级', connectionState: 'unknown', enabled: true, scope: { visibility: 'session' }, healthCheckedAt: null, lastError: null },
|
||||
]
|
||||
|
||||
// ── minimal React + HTML serializer ─────────────────────────────────────
|
||||
let hooks = []
|
||||
let cursor = 0
|
||||
let pendingEffects = []
|
||||
let scheduled = false
|
||||
|
||||
const React = {
|
||||
createElement(type, props, ...children) {
|
||||
const flat = []
|
||||
const push = (value) => {
|
||||
if (Array.isArray(value)) value.forEach(push)
|
||||
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
|
||||
}
|
||||
push(children)
|
||||
return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat }
|
||||
},
|
||||
useState(initial) {
|
||||
const index = cursor++
|
||||
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
|
||||
const setter = (next) => {
|
||||
const value = typeof next === 'function' ? next(hooks[index]) : next
|
||||
if (value !== hooks[index]) {
|
||||
hooks[index] = value
|
||||
scheduled = true
|
||||
}
|
||||
}
|
||||
return [hooks[index], setter]
|
||||
},
|
||||
useEffect(fn) {
|
||||
pendingEffects.push(fn)
|
||||
},
|
||||
useCallback(fn) {
|
||||
return fn
|
||||
},
|
||||
Component: function Component(props) {
|
||||
this.props = props
|
||||
},
|
||||
}
|
||||
React.Component.prototype.setState = function setState(patch) {
|
||||
this.state = { ...this.state, ...patch }
|
||||
scheduled = true
|
||||
}
|
||||
|
||||
function walk(node, visit) {
|
||||
if (node === null || node === undefined || node === false || node === true) return
|
||||
if (typeof node === 'string' || typeof node === 'number') return
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach((child) => walk(child, visit))
|
||||
return
|
||||
}
|
||||
if (typeof node.type === 'function') {
|
||||
if (node.type.prototype && typeof node.type.prototype.render === 'function') {
|
||||
const instance = new node.type(node.props)
|
||||
instance.props = node.props
|
||||
if (instance.state === undefined) instance.state = {}
|
||||
instance.setState = function setState(patch) {
|
||||
instance.state = { ...instance.state, ...patch }
|
||||
scheduled = true
|
||||
}
|
||||
walk(instance.render(), visit)
|
||||
return
|
||||
}
|
||||
walk(node.type({ ...node.props, children: node.children }), visit)
|
||||
return
|
||||
}
|
||||
visit(node)
|
||||
node.children.forEach((child) => walk(child, visit))
|
||||
}
|
||||
|
||||
const UNITLESS = new Set(['fontWeight', 'opacity', 'lineHeight', 'flex', 'zIndex', 'flexGrow', 'flexShrink'])
|
||||
|
||||
function styleOf(style) {
|
||||
const parts = []
|
||||
for (const [key, value] of Object.entries(style ?? {})) {
|
||||
if (value === null || value === undefined) continue
|
||||
const name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
|
||||
parts.push(`${name}:${typeof value === 'number' && !UNITLESS.has(key) ? `${value}px` : String(value)}`)
|
||||
}
|
||||
return parts.join(';')
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
}
|
||||
|
||||
function toHtml(node) {
|
||||
if (node === null || node === undefined || node === false || node === true) return ''
|
||||
if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node)
|
||||
if (Array.isArray(node)) return node.map(toHtml).join('')
|
||||
const { type, props, children } = node
|
||||
if (typeof type === 'function') {
|
||||
if (type.prototype && typeof type.prototype.render === 'function') {
|
||||
const instance = new type(props)
|
||||
instance.props = props
|
||||
if (instance.state === undefined) instance.state = {}
|
||||
return toHtml(instance.render())
|
||||
}
|
||||
return toHtml(type({ ...props, children }))
|
||||
}
|
||||
const attrs = []
|
||||
const style = styleOf(props.style)
|
||||
if (style !== '') attrs.push(`style="${style}"`)
|
||||
if (props.id !== undefined) attrs.push(`id="${escapeHtml(props.id)}"`)
|
||||
if (props.role !== undefined) attrs.push(`role="${escapeHtml(props.role)}"`)
|
||||
if (props.title !== undefined) attrs.push(`title="${escapeHtml(props.title)}"`)
|
||||
if (props.disabled === true) attrs.push('disabled')
|
||||
if (props.type === 'checkbox') attrs.push(props.checked === true ? 'checked' : '')
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if (key.startsWith('aria-')) attrs.push(`${key}="${escapeHtml(value)}"`)
|
||||
}
|
||||
if (type === 'input') {
|
||||
attrs.push(`value="${escapeHtml(props.value === undefined ? '' : props.value)}"`)
|
||||
attrs.push(`placeholder="${escapeHtml(props.placeholder === undefined ? '' : props.placeholder)}"`)
|
||||
attrs.push(`type="${escapeHtml(props.type === undefined ? 'text' : props.type)}"`)
|
||||
return `<input ${attrs.filter(Boolean).join(' ')}>`
|
||||
}
|
||||
return `<${type} ${attrs.filter(Boolean).join(' ')}>${children.map(toHtml).join('')}</${type}>`
|
||||
}
|
||||
|
||||
// ── drive the real bundle ───────────────────────────────────────────────
|
||||
const localStorageStub = {
|
||||
getItem: (key) => (String(key).endsWith(':tab') ? 'mcp' : null),
|
||||
setItem: () => {},
|
||||
}
|
||||
let registered = null
|
||||
globalThis.window = {
|
||||
localStorage: localStorageStub,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
__ModuleLoader__: {
|
||||
load(spec) {
|
||||
const exportsObject = spec.factory(requireShim)
|
||||
const captured = []
|
||||
exportsObject.apply({
|
||||
slots: {
|
||||
inject: (_seat, fn) => fn(),
|
||||
register: (_options, component) => {
|
||||
captured.push(component)
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
})
|
||||
registered = captured[0]
|
||||
},
|
||||
},
|
||||
}
|
||||
function requireShim(id) {
|
||||
if (id === 'react') return React
|
||||
throw new Error(`unexpected require: ${id}`)
|
||||
}
|
||||
|
||||
const fakeFetch = async (url, init) => {
|
||||
const path = String(url).split('?')[0]
|
||||
let body = { ok: false }
|
||||
if (path === '/dsh-brain/status') body = statusBody
|
||||
else if (path === '/dsh-brain/sync/status') body = { ok: true, stats: { running: false, lastRunAt: Date.now(), uploaded: [], downloaded: [] }, conflicts: [] }
|
||||
else if (path === '/mcp-connector/api') {
|
||||
let method = 'status'
|
||||
try {
|
||||
method = JSON.parse(init?.body ?? '{}').method ?? 'status'
|
||||
} catch {
|
||||
method = 'status'
|
||||
}
|
||||
body = method === 'status'
|
||||
? { ok: true, message: '共 ' + connections.length + ' 条连接', detail: { items: connections, scope: {} } }
|
||||
: { ok: true, message: '演示数据:' + method + ' 已受理' }
|
||||
}
|
||||
return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) }
|
||||
}
|
||||
|
||||
function loadCard() {
|
||||
registered = null
|
||||
new Function('window', 'require', 'document', 'localStorage', 'fetch', 'console', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'AbortController', source)(
|
||||
globalThis.window,
|
||||
requireShim,
|
||||
{ visibilityState: 'visible' },
|
||||
localStorageStub,
|
||||
fakeFetch,
|
||||
{ warn: () => {}, log: () => {} },
|
||||
() => 0,
|
||||
() => {},
|
||||
() => 0,
|
||||
() => {},
|
||||
AbortController,
|
||||
)
|
||||
return registered
|
||||
}
|
||||
|
||||
async function settle(element, passes) {
|
||||
let text = ''
|
||||
for (let pass = 0; pass < passes; pass += 1) {
|
||||
cursor = 0
|
||||
pendingEffects = []
|
||||
scheduled = false
|
||||
text = toHtml(element)
|
||||
const effects = pendingEffects
|
||||
pendingEffects = []
|
||||
for (const effect of effects) {
|
||||
const cleanup = effect()
|
||||
if (typeof cleanup === 'function') cleanup()
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
if (!scheduled) break
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
function clickLabel(root, prefix) {
|
||||
let clicked = false
|
||||
walk(root, (node) => {
|
||||
if (clicked) return
|
||||
const props = node.props ?? {}
|
||||
const label = props['aria-label']
|
||||
const text = typeof props.children === 'string' ? props.children : ''
|
||||
if (((typeof label === 'string' && label.startsWith(prefix)) || text.startsWith(prefix)) && typeof props.onClick === 'function') {
|
||||
props.onClick()
|
||||
clicked = true
|
||||
}
|
||||
})
|
||||
return clicked
|
||||
}
|
||||
|
||||
function typeInto(root, label, value) {
|
||||
let typed = false
|
||||
walk(root, (node) => {
|
||||
if (typed) return
|
||||
const props = node.props ?? {}
|
||||
if (props['aria-label'] === label && typeof props.onChange === 'function') {
|
||||
props.onChange({ target: { value } })
|
||||
typed = true
|
||||
}
|
||||
})
|
||||
return typed
|
||||
}
|
||||
|
||||
const card = loadCard()
|
||||
const treeEl = React.createElement(card, null)
|
||||
const firstBody = await settle(treeEl, 6)
|
||||
if (!firstBody.includes('我的连接')) throw new Error('preview: MCP tab did not render')
|
||||
|
||||
// View 2: filter to streamable-http connections and select them all.
|
||||
cursor = 0
|
||||
pendingEffects = []
|
||||
typeInto(treeEl, '搜索 MCP 连接', 'search')
|
||||
await settle(treeEl, 6)
|
||||
cursor = 0
|
||||
pendingEffects = []
|
||||
clickLabel(treeEl, '全选匹配结果')
|
||||
const chosenBody = await settle(treeEl, 6)
|
||||
|
||||
const page = (content, theme) => `<!doctype html><html><head><meta charset="utf-8">
|
||||
<style>
|
||||
html,body{margin:0;padding:0}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",system-ui,sans-serif;
|
||||
background:${theme === 'dark' ? '#101216' : '#f3f5f9'};color:${theme === 'dark' ? '#e8eaee' : '#1a1d21'}}
|
||||
.frame{width:600px;margin:0 auto;padding:18px 20px 24px}
|
||||
.panel{border-radius:14px;padding:16px;
|
||||
background:${theme === 'dark' ? '#191c22' : '#ffffff'};
|
||||
box-shadow:0 10px 30px rgba(0,0,0,${theme === 'dark' ? '0.45' : '0.10'})}
|
||||
button{font-family:inherit}
|
||||
input{font-family:inherit;color:inherit}
|
||||
</style></head><body><div class="frame"><div class="panel">${content}</div></div></body></html>`
|
||||
|
||||
const outDir = join(here, '_preview')
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const lightPath = join(outDir, 'mcp-light.html')
|
||||
const chosenPath = join(outDir, 'mcp-selected.html')
|
||||
const darkPath = join(outDir, 'mcp-dark.html')
|
||||
writeFileSync(lightPath, page(firstBody, 'light'), 'utf8')
|
||||
writeFileSync(chosenPath, page(chosenBody, 'light'), 'utf8')
|
||||
writeFileSync(darkPath, page(chosenBody, 'dark'), 'utf8')
|
||||
|
||||
const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||
for (const [input, output, height] of [
|
||||
[lightPath, join(outDir, 'mcp-light.png'), 2200],
|
||||
[chosenPath, join(outDir, 'mcp-selected.png'), 2200],
|
||||
[darkPath, join(outDir, 'mcp-dark.png'), 2200],
|
||||
]) {
|
||||
execFileSync(chrome, [
|
||||
'--headless=new',
|
||||
'--disable-gpu',
|
||||
'--hide-scrollbars',
|
||||
'--force-device-scale-factor=2',
|
||||
`--window-size=640,${height}`,
|
||||
`--screenshot=${output}`,
|
||||
`file:///${input.replace(/\\/g, '/')}`,
|
||||
], { stdio: 'ignore' })
|
||||
console.log(`wrote ${output}`)
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,64 @@
|
|||
// Slim settings card: status summary + a jump into the Brain total panel.
|
||||
import * as React from 'react'
|
||||
import { API, request, messageOf } from './api'
|
||||
import { styles } from './styles'
|
||||
import { Pill, Banner, Btn } from './components'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export function SettingsSummaryCard(props: { ctx?: any }): any {
|
||||
const [status, setStatus] = React.useState<any>(null)
|
||||
const [error, setError] = React.useState<string | null>(null)
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled = false
|
||||
const load = (): void => {
|
||||
request(API.status).then(
|
||||
(result) => {
|
||||
if (cancelled) return
|
||||
if (result.status === 200 && result.body !== null && result.body.ok === true) {
|
||||
setStatus(result.body)
|
||||
setError(null)
|
||||
} else {
|
||||
setError('读取状态失败(HTTP ' + String(result.status) + ')')
|
||||
}
|
||||
},
|
||||
(failure) => { if (!cancelled) setError(messageOf(failure)) },
|
||||
)
|
||||
}
|
||||
load()
|
||||
const timer = setInterval(load, 15000)
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearInterval(timer)
|
||||
}
|
||||
}, [])
|
||||
|
||||
function openPanel(): void {
|
||||
const ctx = props.ctx
|
||||
const layout = ctx === undefined || ctx === null ? undefined : ctx.layout
|
||||
if (layout !== undefined && layout !== null && typeof layout.selectPanel === 'function') {
|
||||
layout.selectPanel('dsh-brain')
|
||||
return
|
||||
}
|
||||
if (typeof window !== 'undefined' && typeof window.open === 'function') window.open('/dsh-brain')
|
||||
}
|
||||
|
||||
const settings = status?.settings ?? {}
|
||||
return h('div', { style: styles.root, 'data-dsh-plugin': 'dsh-brain' },
|
||||
h('div', { style: styles.sectionHead },
|
||||
h('h4', { style: styles.sectionTitle }, '云端记忆'),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { variant: 'primary', label: '打开总面板', onClick: openPanel }),
|
||||
),
|
||||
),
|
||||
h('p', { style: styles.hint }, '设置与连接内容已收进左侧栏 Brain 总面板的「连接与上报」页签。这里保留状态摘要和快捷入口。'),
|
||||
error === null ? null : h(Banner, { tone: 'bad' }, error),
|
||||
status === null ? h('p', { style: styles.hint }, '正在读取状态…') : h('div', { style: styles.pills },
|
||||
h(Pill, { label: '服务', value: settings.baseUrlConfigured === false ? '未配置' : '已配置', tone: settings.baseUrlConfigured === false ? 'warn' : 'ok' }),
|
||||
h(Pill, { label: '上报', value: settings.activityEnabled === true ? '开' : '关', tone: settings.activityEnabled === true ? 'ok' : 'muted' }),
|
||||
h(Pill, { label: '记忆', value: settings.memoryEnabled === true ? '开' : '关', tone: settings.memoryEnabled === true ? 'ok' : 'muted' }),
|
||||
h(Pill, { label: '本地记忆', value: settings.localMemoryEnabled === false ? '关' : '开', tone: settings.localMemoryEnabled === false ? 'muted' : 'ok' }),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
// dsh-brain client API helpers.
|
||||
// Adapted from the original hand-written client bundle (dsh-brain).
|
||||
export const API = {
|
||||
status: '/dsh-brain/status',
|
||||
capabilities: '/dsh-brain/capabilities',
|
||||
config: '/dsh-brain/config',
|
||||
login: '/dsh-brain/login',
|
||||
test: '/dsh-brain/test',
|
||||
flush: '/dsh-brain/flush',
|
||||
skills: '/dsh-brain/skills',
|
||||
market: '/dsh-brain/market',
|
||||
sync: '/dsh-brain/sync',
|
||||
clients: '/dsh-brain/clients',
|
||||
migrate: '/dsh-brain/migrate',
|
||||
}
|
||||
|
||||
// ---- MCP bundle (browser bridge) ---------------------------------------
|
||||
// The MCP bridge is another plugin's public surface, not ours: it is probed
|
||||
// at runtime and the tab reports a capability gap when it is missing.
|
||||
// This bundle owns the tab, the request envelope, the probe timeout and
|
||||
// the host-unavailable state; connections, credentials, tool management
|
||||
// and any cloud-side sync belong to the host dsh-mcp-connector plugin.
|
||||
|
||||
export function request(url, init?) {
|
||||
var options = init || {}
|
||||
options.cache = 'no-store'
|
||||
options.headers = options.body === undefined
|
||||
? { accept: 'application/json' }
|
||||
: { accept: 'application/json', 'content-type': 'application/json' }
|
||||
return fetch(url, options).then(function (response) {
|
||||
return response.json().then(
|
||||
function (body) {
|
||||
return { status: response.status, body: body }
|
||||
},
|
||||
function () {
|
||||
return { status: response.status, body: null }
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export function postJson(url, payload?) {
|
||||
return request(url, { method: 'POST', body: JSON.stringify(payload === undefined ? {} : payload) })
|
||||
}
|
||||
|
||||
export function messageOf(error) {
|
||||
if (error === null || error === undefined) return '未知错误'
|
||||
if (typeof error === 'string') return error
|
||||
return typeof error.message === 'string' ? error.message : String(error)
|
||||
}
|
||||
|
||||
// One POST to the host MCP bridge. Used by the self-contained MCP panels
|
||||
// below; the dispatcher whitelist lives in dsh-mcp-connector.
|
||||
|
||||
export function statusText(status) {
|
||||
if (status === 404 || status === 405) {
|
||||
return '插件后端还没加载这个接口(HTTP ' + String(status) + '):请完全退出并重启 DSH 后再试。'
|
||||
}
|
||||
return 'HTTP ' + String(status)
|
||||
}
|
||||
|
||||
export function bodyError(result, fallback?) {
|
||||
if (result.body !== null && result.body !== undefined && typeof result.body.error === 'string' && result.body.error !== '') {
|
||||
return result.body.error
|
||||
}
|
||||
return fallback === undefined ? statusText(result.status) : fallback
|
||||
}
|
||||
|
||||
// ---- settings-ui bundle (configuration surface) ----
|
||||
// pickSettings + the SettingsCard draft/save/login/test/flush logic and the
|
||||
// 连接与上报 tab belong to the settings-ui bundle; the skills/mcp tabs
|
||||
// belong to their own bundles. The card only talks to the public HTTP API —
|
||||
// it never touches SettingsStore/CloudClient/Reporter/SkillSync directly.
|
||||
export function pickSettings(settings) {
|
||||
var source = settings === undefined || settings === null ? {} : settings
|
||||
return {
|
||||
enabled: source.enabled === true,
|
||||
baseUrl: String(source.baseUrl === undefined ? '' : source.baseUrl),
|
||||
baseUrlConfigured: source.baseUrlConfigured !== false,
|
||||
baseUrlOrigin: String(source.baseUrlOrigin === undefined ? '' : source.baseUrlOrigin),
|
||||
clientId: String(source.clientId === undefined ? '' : source.clientId),
|
||||
requestTimeoutMs: String(source.requestTimeoutMs === undefined ? 8000 : source.requestTimeoutMs),
|
||||
defaultK: String(source.defaultK === undefined ? 10 : source.defaultK),
|
||||
summaryEnabled: source.summaryEnabled === true,
|
||||
activityEnabled: source.activityEnabled === true,
|
||||
memoryEnabled: source.memoryEnabled === true,
|
||||
skillsDir: String(source.skillsDir === undefined ? '' : source.skillsDir),
|
||||
skillsSyncEnabled: source.skillsSyncEnabled === true,
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyTokens() {
|
||||
return { activity: '', memory: '', summary: '' }
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
// Host MCP bridge helpers (dsh-mcp-connector public surface).
|
||||
import { messageOf } from './api'
|
||||
export const MCP_BRIDGE = '/mcp-connector/api'
|
||||
export const MCP_PANEL = '/mcp-connector/ui'
|
||||
export const POLL_MS = 10000
|
||||
export const PROBE_TIMEOUT_MS = 5000
|
||||
|
||||
|
||||
export function bridgeCall(method, params) {
|
||||
var controller = typeof AbortController === 'function' ? new AbortController() : null
|
||||
var timer = controller === null ? null : setTimeout(function () { controller.abort() }, 20000)
|
||||
return fetch(MCP_BRIDGE, {
|
||||
method: 'POST',
|
||||
cache: 'no-store',
|
||||
headers: { accept: 'application/json', 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ method: method, params: params === undefined ? {} : params }),
|
||||
signal: controller === null ? undefined : controller.signal,
|
||||
}).then(function (response) {
|
||||
if (timer !== null) clearTimeout(timer)
|
||||
return response.json().then(
|
||||
function (body) { return { status: response.status, body: body } },
|
||||
function () { return { status: response.status, body: null } },
|
||||
)
|
||||
}, function (failure) {
|
||||
if (timer !== null) clearTimeout(timer)
|
||||
return { status: 0, body: null, error: messageOf(failure) }
|
||||
})
|
||||
}
|
||||
|
||||
export function bridgeMessage(result) {
|
||||
if (result.body !== null && typeof result.body.message === 'string' && result.body.message !== '') return result.body.message
|
||||
return 'HTTP ' + String(result.status) + (result.error === undefined ? '' : ':' + result.error)
|
||||
}
|
||||
|
||||
// A 404/405 here means the host half on disk is newer than the one this
|
||||
// window is talking to: the module is loaded into the running process and
|
||||
// does not hot-reload, so the answer is a restart, not a retry.
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
// dsh-brain client basic components.
|
||||
import * as React from 'react'
|
||||
import { messageOf } from './api'
|
||||
import { styles } from './styles'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export function Pill(props) {
|
||||
var tone = styles[props.tone] === undefined ? styles.muted : styles[props.tone]
|
||||
return h(
|
||||
'span',
|
||||
{ style: Object.assign({}, styles.pill, tone) },
|
||||
h('span', { style: { opacity: 0.75 } }, props.label),
|
||||
h('span', { style: { fontWeight: 600 } }, String(props.value)),
|
||||
)
|
||||
}
|
||||
|
||||
export function Banner(props) {
|
||||
var tone = styles[props.tone] === undefined ? styles.muted : styles[props.tone]
|
||||
return h('div', { style: Object.assign({}, styles.banner, tone), role: props.role }, props.children)
|
||||
}
|
||||
|
||||
export function Field(props) {
|
||||
return h(
|
||||
'label',
|
||||
{ style: styles.field },
|
||||
h('span', { style: styles.label }, props.label),
|
||||
h('input', {
|
||||
style: styles.input,
|
||||
type: props.type === undefined ? 'text' : props.type,
|
||||
value: props.value,
|
||||
placeholder: props.placeholder === undefined ? '' : props.placeholder,
|
||||
spellCheck: false,
|
||||
autoComplete: 'off',
|
||||
disabled: props.disabled === true,
|
||||
onChange: function (event) {
|
||||
props.onChange(event.target.value)
|
||||
},
|
||||
}),
|
||||
props.hint === undefined ? null : h('span', { style: styles.hint }, props.hint),
|
||||
)
|
||||
}
|
||||
|
||||
export function Btn(props) {
|
||||
var base = props.variant === 'primary' ? styles.buttonPrimary : props.variant === 'danger' ? styles.buttonDanger : props.variant === 'small' ? styles.buttonSmall : styles.button
|
||||
var style = props.disabled === true ? Object.assign({}, base, { opacity: 0.45, cursor: 'not-allowed' }) : base
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
style: style,
|
||||
disabled: props.disabled === true,
|
||||
onClick: props.onClick,
|
||||
'aria-label': props.ariaLabel,
|
||||
},
|
||||
props.label,
|
||||
)
|
||||
}
|
||||
|
||||
export function IconBtn(props) {
|
||||
var style = Object.assign({}, styles.iconBtn, props.danger === true ? styles.iconBtnDanger : null, props.disabled === true ? { opacity: 0.45, cursor: 'not-allowed' } : null)
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
style: style,
|
||||
disabled: props.disabled === true,
|
||||
onClick: props.disabled === true ? undefined : props.onClick,
|
||||
'aria-label': props.ariaLabel,
|
||||
title: props.ariaLabel,
|
||||
},
|
||||
props.glyph,
|
||||
)
|
||||
}
|
||||
|
||||
export function Switch(props) { return h(
|
||||
'div',
|
||||
{ style: styles.tabs, role: 'tablist', 'aria-label': props.ariaLabel },
|
||||
props.options.map(function (option) {
|
||||
var active = option.value === props.value
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
key: option.value,
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
'aria-selected': active,
|
||||
style: Object.assign({}, styles.tab, active ? styles.tabActive : null),
|
||||
onClick: function () {
|
||||
props.onChange(option.value)
|
||||
},
|
||||
},
|
||||
option.label,
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// A real switch, not a checkbox: the tree rows are dense and the state has
|
||||
// to be readable at a glance in both themes.
|
||||
export function Toggle(props) {
|
||||
var on = props.checked === true
|
||||
var disabled = props.disabled === true
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'switch',
|
||||
'aria-checked': on,
|
||||
'aria-label': props.label,
|
||||
title: props.label,
|
||||
disabled: disabled,
|
||||
style: {
|
||||
width: '38px',
|
||||
height: '22px',
|
||||
flex: '0 0 auto',
|
||||
padding: '2px',
|
||||
borderRadius: '999px',
|
||||
border: '1px solid ' + (on ? 'rgba(0,0,0,0.25)' : 'rgba(127,127,127,0.45)'),
|
||||
background: on ? '#3f3f46' : 'rgba(127,127,127,0.28)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: on ? 'flex-end' : 'flex-start',
|
||||
cursor: disabled ? 'not-allowed' : 'pointer',
|
||||
opacity: disabled ? 0.45 : 1,
|
||||
transition: 'background 120ms ease',
|
||||
},
|
||||
onClick: disabled ? undefined : props.onChange,
|
||||
},
|
||||
h('span', {
|
||||
style: {
|
||||
width: '16px',
|
||||
height: '16px',
|
||||
borderRadius: '999px',
|
||||
background: 'rgba(255,255,255,0.96)',
|
||||
boxShadow: '0 1px 2px rgba(0,0,0,0.25)',
|
||||
flex: '0 0 auto',
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export function Section(props) {
|
||||
return h(
|
||||
'div',
|
||||
{ style: styles.section },
|
||||
h(
|
||||
'div',
|
||||
{ style: styles.sectionHead },
|
||||
h('h4', { style: styles.sectionTitle }, props.title),
|
||||
props.aside === undefined ? null : h('div', { style: styles.actions }, props.aside),
|
||||
),
|
||||
props.hint === undefined ? null : h('p', { style: styles.hint }, props.hint),
|
||||
props.children,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
export function CardBoundary(props) {
|
||||
React.Component.call(this, props)
|
||||
this.state = { failure: null }
|
||||
}
|
||||
|
||||
CardBoundary.prototype = Object.create(React.Component.prototype)
|
||||
CardBoundary.prototype.constructor = CardBoundary
|
||||
|
||||
CardBoundary.getDerivedStateFromError = function (failure) {
|
||||
return { failure: failure }
|
||||
}
|
||||
|
||||
CardBoundary.prototype.render = function () {
|
||||
if (this.state.failure !== null) {
|
||||
return h(
|
||||
'div',
|
||||
{ style: Object.assign({}, styles.root) },
|
||||
h('div', { style: Object.assign({}, styles.banner, styles.bad) }, '云端记忆设置卡渲染失败:' + messageOf(this.state.failure)),
|
||||
h('p', { style: styles.hint }, '插件本身仍在运行,可改用 /dsh-brain 页面配置。'),
|
||||
)
|
||||
}
|
||||
return this.props.children
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
// dsh-brain client formatting helpers and label tables.
|
||||
export function formatTime(value) {
|
||||
if (typeof value !== 'number' || value <= 0) return '—'
|
||||
var date = new Date(value)
|
||||
var pad = function (n) {
|
||||
return n < 10 ? '0' + String(n) : String(n)
|
||||
}
|
||||
return pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds())
|
||||
}
|
||||
|
||||
export function formatIso(value) {
|
||||
if (typeof value !== 'string' || value === '') return '—'
|
||||
var stamp = Date.parse(value)
|
||||
if (!Number.isFinite(stamp)) return value
|
||||
return formatTime(stamp)
|
||||
}
|
||||
|
||||
export function formatBytes(value) {
|
||||
if (typeof value !== 'number' || value < 0) return '—'
|
||||
if (value < 1024) return String(value) + ' B'
|
||||
if (value < 1024 * 1024) return (value / 1024).toFixed(1) + ' KB'
|
||||
return (value / (1024 * 1024)).toFixed(2) + ' MB'
|
||||
}
|
||||
|
||||
export function shortHash(value) {
|
||||
if (typeof value !== 'string' || value === '') return '—'
|
||||
return value.slice(0, 12)
|
||||
}
|
||||
|
||||
export function readStored(key, fallback) {
|
||||
try {
|
||||
var raw = window.localStorage.getItem('dsh-brain:' + key)
|
||||
if (raw === null || raw === '') raw = window.localStorage.getItem('dsh-cloud-memory:' + key)
|
||||
return raw === null || raw === '' ? fallback : raw
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
export function store(key, value) {
|
||||
try {
|
||||
window.localStorage.setItem('dsh-brain:' + key, String(value))
|
||||
} catch {
|
||||
/* a locked-down window keeps the value in memory only */
|
||||
}
|
||||
}
|
||||
|
||||
export const OUTCOME_LABELS = {
|
||||
recorded: '已上报',
|
||||
duplicate: '重复忽略',
|
||||
failed: '失败',
|
||||
queued: '待重试',
|
||||
skipped: '已跳过',
|
||||
}
|
||||
|
||||
export const OUTCOME_TONES = {
|
||||
recorded: 'ok',
|
||||
duplicate: 'muted',
|
||||
failed: 'bad',
|
||||
queued: 'warn',
|
||||
skipped: 'muted',
|
||||
}
|
||||
|
||||
export const ORIGIN_LABELS = {
|
||||
cloud: '云端下发',
|
||||
uploaded: '本地已上传',
|
||||
local: '本机安装',
|
||||
unknown: '来源未知',
|
||||
}
|
||||
|
||||
export const CHECK_TONES = {
|
||||
ok: 'ok',
|
||||
unconfigured: 'muted',
|
||||
invalid: 'bad',
|
||||
forbidden: 'bad',
|
||||
unreachable: 'bad',
|
||||
error: 'bad',
|
||||
}
|
||||
|
||||
export const CHECK_LABELS = {
|
||||
ok: '可用',
|
||||
unconfigured: '未配置',
|
||||
invalid: '令牌失效',
|
||||
forbidden: '权限不足',
|
||||
unreachable: '不可达',
|
||||
error: '出错',
|
||||
}
|
||||
|
||||
export const MCP_STATE_LABELS = {
|
||||
connected: '已连接',
|
||||
connecting: '连接中',
|
||||
disabled: '已停用',
|
||||
error: '异常',
|
||||
expired: '授权过期',
|
||||
unknown: '未知',
|
||||
needs_auth: '待授权',
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
// dsh-brain client bundle entry — the __ModuleLoader__ module contract.
|
||||
import * as React from 'react'
|
||||
import { messageOf } from './api'
|
||||
import { CardBoundary } from './components'
|
||||
import { SettingsCard } from './SettingsCard'
|
||||
import { SettingsSummaryCard } from './SettingsSummaryCard'
|
||||
import { registerBrainPanel } from './panel/register'
|
||||
import { mountBrainSidebarTab } from './sidebar/register'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export const inject = ['slots']
|
||||
|
||||
export function apply(ctx: any): void {
|
||||
const summaryCard = function () {
|
||||
return h(CardBoundary as any, null, h(SettingsSummaryCard as any, { ctx }))
|
||||
}
|
||||
// The plugin bundle config page keeps the full settings card; the generic
|
||||
// settings section is now only the status summary with a jump button.
|
||||
const configCard = function () {
|
||||
return h(CardBoundary as any, null, h(SettingsCard as any, null))
|
||||
}
|
||||
|
||||
const register = function (seat: string, options: any, component: any) {
|
||||
try {
|
||||
ctx.slots.inject(seat, function () {
|
||||
return ctx.slots.register(options, component)
|
||||
})
|
||||
} catch (failure) {
|
||||
if (typeof console !== 'undefined') console.warn('[dsh-brain] slot ' + seat + ' unavailable: ' + messageOf(failure))
|
||||
}
|
||||
}
|
||||
|
||||
register('plugins.bundle.config', { name: 'plugins.bundle.config', key: 'dsh-brain' }, configCard)
|
||||
|
||||
register('settings.section', {
|
||||
name: 'settings.section',
|
||||
id: 'dsh-brain',
|
||||
order: 100,
|
||||
label: function () {
|
||||
return '云端记忆'
|
||||
},
|
||||
}, summaryCard)
|
||||
|
||||
try {
|
||||
if (typeof ctx.effect === 'function') ctx.effect(() => registerBrainPanel(ctx), 'dsh-brain: panel')
|
||||
else registerBrainPanel(ctx)
|
||||
} catch (failure) {
|
||||
if (typeof console !== 'undefined') console.warn('[dsh-brain] panel registration failed: ' + messageOf(failure))
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof ctx.effect === 'function') ctx.effect(() => mountBrainSidebarTab(ctx), 'dsh-brain: better-sidebar tab')
|
||||
else mountBrainSidebarTab(ctx)
|
||||
} catch (failure) {
|
||||
if (typeof console !== 'undefined') console.warn('[dsh-brain] better-sidebar tab registration failed: ' + messageOf(failure))
|
||||
}
|
||||
}
|
||||
|
||||
export const name = 'dsh-brain'
|
||||
|
|
@ -0,0 +1,225 @@
|
|||
/* Adapted from dsh-mnemon MnemonWorkspace.module.css (MIT), see vendor/dsh-mnemon/LICENSE. */
|
||||
.nativeWorkspace {
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
flex: 1 1 auto;
|
||||
padding-block-start: var(--dsh-frame-top-clearance, 0px);
|
||||
}
|
||||
|
||||
.nativeWorkspace > * {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.windowDragBand {
|
||||
position: absolute;
|
||||
inset: 0 0 auto;
|
||||
height: var(--dsh-frame-top-clearance, 0px);
|
||||
}
|
||||
|
||||
.panelInner {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
padding: 18px 20px 24px;
|
||||
overflow: auto;
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
color: var(--dsw-alias-label-primary, inherit);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.titleBlock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 650;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin: 0;
|
||||
font-size: 11.5px;
|
||||
opacity: 0.58;
|
||||
}
|
||||
|
||||
.tabBar {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 3px;
|
||||
border-radius: 13px;
|
||||
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));
|
||||
background: var(--dsw-alias-bg-subtle, rgba(127,127,127,0.06));
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.tab {
|
||||
flex: 1 1 auto;
|
||||
min-width: 88px;
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
padding: 7px 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tabActive {
|
||||
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));
|
||||
background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,0.14));
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.10);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.placeholder {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 48px 16px;
|
||||
border: 1px dashed var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));
|
||||
border-radius: 16px;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.placeholderTitle {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.placeholderHint {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.overviewGrid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));
|
||||
border-radius: 16px;
|
||||
padding: 16px 18px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cardHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.cardTitle {
|
||||
margin: 0;
|
||||
font-size: 13.5px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.pills {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.35));
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pillLabel {
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.pillValue {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ok { border-color: rgba(22,163,74,0.55); background: rgba(22,163,74,0.12); }
|
||||
.bad { border-color: rgba(220,38,38,0.55); background: rgba(220,38,38,0.12); }
|
||||
.warn { border-color: rgba(217,119,6,0.55); background: rgba(217,119,6,0.12); }
|
||||
.muted { }
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
font-size: 11.5px;
|
||||
opacity: 0.58;
|
||||
}
|
||||
|
||||
.error {
|
||||
padding: 10px 13px;
|
||||
border-radius: 11px;
|
||||
border: 1px solid rgba(220,38,38,0.55);
|
||||
background: rgba(220,38,38,0.12);
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.statRow {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.stat {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
padding-right: 18px;
|
||||
margin-right: 18px;
|
||||
border-right: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.20));
|
||||
}
|
||||
|
||||
.statLast {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.statNum {
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
// Brain total panel: the shell-rendered centre page of the dsh-brain bundle.
|
||||
import * as React from 'react'
|
||||
import { Overview } from './Overview'
|
||||
import { MemoryTab } from './MemoryTab'
|
||||
import { DepartmentTab } from './DepartmentTab'
|
||||
import { resolveWorkspace } from './workspace'
|
||||
import { SettingsCard } from '../SettingsCard'
|
||||
import styles from './BrainPanel.module.css'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
const TABS = [
|
||||
{ id: 'overview', label: '概览' },
|
||||
{ id: 'memory', label: '记忆' },
|
||||
{ id: 'departments', label: '部门' },
|
||||
{ id: 'skills', label: '技能' },
|
||||
{ id: 'mcp', label: 'MCP' },
|
||||
{ id: 'connection', label: '连接与上报' },
|
||||
] as const
|
||||
|
||||
function Placeholder(props: { title: string }): any {
|
||||
return h('div', { className: styles.placeholder },
|
||||
h('h3', { className: styles.placeholderTitle }, props.title),
|
||||
h('p', { className: styles.placeholderHint }, '即将上线'),
|
||||
)
|
||||
}
|
||||
|
||||
export function BrainPanel(props: { ctx?: any; panelId?: string; usePanelInfo?: any }): any {
|
||||
const [tab, setTab] = React.useState('overview')
|
||||
const panelId = props.panelId ?? 'dsh-brain'
|
||||
const usePanelInfo = props.usePanelInfo
|
||||
const active = usePanelInfo === undefined ? true : usePanelInfo((info: { activePanelId: string | null }) => info.activePanelId === panelId)
|
||||
let content: any
|
||||
if (tab === 'overview') content = h(Overview, { active })
|
||||
else if (tab === 'connection') content = h(SettingsCard, null)
|
||||
else if (tab === 'memory') {
|
||||
const workspace = resolveWorkspace(props.ctx)
|
||||
content = h(MemoryTab, { key: workspace ?? '', workspace, active })
|
||||
}
|
||||
else if (tab === 'departments') content = h(DepartmentTab, { ctx: props.ctx, active })
|
||||
else if (tab === 'skills') content = h(Placeholder, { title: '技能' })
|
||||
else content = h(Placeholder, { title: 'MCP' })
|
||||
return h('div', { className: styles.nativeWorkspace, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'brain-panel' },
|
||||
h('div', { className: styles.windowDragBand, 'data-window-drag': true, 'aria-hidden': 'true' }),
|
||||
h('div', { className: styles.panelInner },
|
||||
h('div', { className: styles.header },
|
||||
h('div', { className: styles.titleBlock },
|
||||
h('h3', { className: styles.title }, 'Brain'),
|
||||
h('p', { className: styles.subtitle }, '本地记忆、部门与连接的总面板'),
|
||||
),
|
||||
),
|
||||
h('div', { className: styles.tabBar, role: 'tablist', 'aria-label': 'Brain 面板页签' },
|
||||
TABS.map((item) => h('button', {
|
||||
key: item.id,
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
'aria-selected': tab === item.id,
|
||||
className: tab === item.id ? styles.tab + ' ' + styles.tabActive : styles.tab,
|
||||
onClick: () => setTab(item.id),
|
||||
}, item.label)),
|
||||
),
|
||||
h('div', { className: styles.content }, content),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,199 @@
|
|||
// Department tab: list, create, detail (update/disable/checkpoint), recall.
|
||||
import * as React from 'react'
|
||||
import { request, postJson, bodyError, messageOf } from '../api'
|
||||
import { formatIso } from '../format'
|
||||
import { styles } from '../styles'
|
||||
import { Banner, Btn, Field, Pill, Section } from '../components'
|
||||
import { useApi } from './useApi'
|
||||
import { resolveWorkspace, workspaceQuery } from './workspace'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
const EMPTY_CREATE = { name: '', role: '', scope: 'project', skills: '', allowedTools: '', readGlobal: true, readProject: true }
|
||||
|
||||
const ENDPOINTS = {
|
||||
list: '/dsh-brain/departments/list',
|
||||
create: '/dsh-brain/departments/create',
|
||||
update: '/dsh-brain/departments/update',
|
||||
disable: '/dsh-brain/departments/disable',
|
||||
checkpoint: '/dsh-brain/departments/checkpoint',
|
||||
recall: '/dsh-brain/departments/recall',
|
||||
} as const
|
||||
|
||||
export function DepartmentTab(props: { ctx?: any; active?: boolean }): any {
|
||||
const active = props.active !== false
|
||||
const workspace = resolveWorkspace(props.ctx)
|
||||
const [notice, setNotice] = React.useState<any>(null)
|
||||
const [busy, setBusy] = React.useState('')
|
||||
const [form, setForm] = React.useState<any>({ ...EMPTY_CREATE })
|
||||
const [selectedId, setSelectedId] = React.useState('')
|
||||
const [detail, setDetail] = React.useState<any>({ role: '', currentTask: '', handoff: '' })
|
||||
const [recallId, setRecallId] = React.useState('')
|
||||
const [recallQuery, setRecallQuery] = React.useState('')
|
||||
const [recallK, setRecallK] = React.useState('5')
|
||||
const [recallHits, setRecallHits] = React.useState<any[]>([])
|
||||
const [recallBusy, setRecallBusy] = React.useState(false)
|
||||
|
||||
const list = useApi(async () => {
|
||||
const result = await request(ENDPOINTS.list + workspaceQuery(workspace))
|
||||
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取部门列表失败'))
|
||||
return result.body
|
||||
}, { visible: active, pollMs: 15000 })
|
||||
|
||||
const departments: any[] = Array.isArray(list.data?.departments) ? list.data!.departments : []
|
||||
const selected = departments.filter((item) => item.id === selectedId)[0]
|
||||
|
||||
React.useEffect(() => {
|
||||
if (selected !== undefined) {
|
||||
setDetail({ role: selected.role ?? '', currentTask: selected.currentTask ?? '', handoff: selected.handoff ?? '' })
|
||||
}
|
||||
}, [selectedId, list.data])
|
||||
|
||||
const handleFailure = (result: any, fallback: string): boolean => {
|
||||
if (result.status === 409) {
|
||||
setNotice({ tone: 'warn', text: '数据已变化,请刷新' })
|
||||
list.reload()
|
||||
return false
|
||||
}
|
||||
setNotice({ tone: 'bad', text: bodyError(result, fallback) })
|
||||
return false
|
||||
}
|
||||
|
||||
const create = async (): Promise<void> => {
|
||||
if (String(form.name).trim() === '') { setNotice({ tone: 'warn', text: '请填写部门名称。' }); return }
|
||||
setBusy('create')
|
||||
try {
|
||||
const result = await postJson(ENDPOINTS.create, {
|
||||
name: String(form.name).trim(),
|
||||
role: String(form.role).trim() || undefined,
|
||||
scope: form.scope,
|
||||
skills: String(form.skills).split(/[,,\s]+/).filter((value) => value !== ''),
|
||||
allowedTools: String(form.allowedTools).split(/[,,\s]+/).filter((value) => value !== ''),
|
||||
readGlobal: form.readGlobal === true,
|
||||
readProject: form.readProject === true,
|
||||
workspace,
|
||||
})
|
||||
if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, '创建部门失败'); return }
|
||||
setNotice({ tone: 'ok', text: result.body.created === false ? '同名部门已存在,已复用。' : '部门已创建。' })
|
||||
setForm({ ...EMPTY_CREATE })
|
||||
list.reload()
|
||||
} catch (failure) {
|
||||
setNotice({ tone: 'bad', text: messageOf(failure) })
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const mutate = async (action: 'update' | 'disable' | 'checkpoint'): Promise<void> => {
|
||||
if (selected === undefined) return
|
||||
setBusy(action)
|
||||
const payload: any = { id: selected.id, expectedRevision: selected.revision, workspace }
|
||||
if (action === 'update') { payload.role = detail.role; payload.name = selected.name }
|
||||
if (action === 'checkpoint') { payload.currentTask = detail.currentTask; payload.handoff = detail.handoff }
|
||||
try {
|
||||
const result = await postJson(action === 'update' ? ENDPOINTS.update : action === 'disable' ? ENDPOINTS.disable : ENDPOINTS.checkpoint, payload)
|
||||
if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, '操作失败'); return }
|
||||
setNotice({ tone: 'ok', text: action === 'update' ? '部门已更新。' : action === 'checkpoint' ? '检查点已保存。' : '部门已停用。' })
|
||||
list.reload()
|
||||
} catch (failure) {
|
||||
setNotice({ tone: 'bad', text: messageOf(failure) })
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const recall = async (): Promise<void> => {
|
||||
if (recallId === '') { setNotice({ tone: 'warn', text: '请选择要召回的部门。' }); return }
|
||||
setRecallBusy(true)
|
||||
setRecallHits([])
|
||||
try {
|
||||
const query = ENDPOINTS.recall + '?id=' + encodeURIComponent(recallId) + '&query=' + encodeURIComponent(recallQuery) + '&k=' + encodeURIComponent(recallK) + (workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace))
|
||||
const result = await request(query)
|
||||
if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, '召回失败'); return }
|
||||
setRecallHits(Array.isArray(result.body.hits) ? result.body.hits : [])
|
||||
} catch (failure) {
|
||||
setNotice({ tone: 'bad', text: messageOf(failure) })
|
||||
} finally {
|
||||
setRecallBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
|
||||
notice === null ? null : h(Banner, { tone: notice.tone }, notice.text),
|
||||
list.error === null ? null : h(Banner, { tone: 'bad' }, list.error),
|
||||
h(Section, { title: '部门列表', hint: '部门是本机可复用的工作身份;列表显示 scope、状态、当前任务与 revision。', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => list.reload() }) },
|
||||
departments.length === 0 ? h('p', { style: styles.hint }, '还没有部门。可在下方创建。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
|
||||
departments.map((item) => h('div', { key: item.id, style: styles.row },
|
||||
h('div', { style: styles.rowHead },
|
||||
h('span', { style: styles.rowTitle }, String(item.name) + '(' + String(item.scope) + ')'),
|
||||
h('div', { style: styles.pills },
|
||||
h(Pill, { label: '状态', value: item.active === true ? '启用' : '停用', tone: item.active === true ? 'ok' : 'bad' }),
|
||||
h(Pill, { label: 'rev', value: item.revision ?? '—', tone: 'muted' }),
|
||||
),
|
||||
),
|
||||
h('p', { style: styles.hint }, '当前任务:' + String(item.currentTask ?? '—') + (item.handoff === undefined ? '' : ' · 交接:' + String(item.handoff))),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { label: selectedId === item.id ? '收起详情' : '详情 / 编辑', variant: 'small', onClick: () => setSelectedId(selectedId === item.id ? '' : item.id) }),
|
||||
h(Btn, { label: '设为召回对象', variant: 'small', onClick: () => setRecallId(item.id) }),
|
||||
),
|
||||
selectedId === item.id ? h('div', { style: styles.nested },
|
||||
h('div', { style: styles.grid },
|
||||
h(Field, { label: '角色', value: detail.role, onChange: (value) => setDetail({ ...detail, role: value }) }),
|
||||
h(Field, { label: '当前任务', value: detail.currentTask, onChange: (value) => setDetail({ ...detail, currentTask: value }) }),
|
||||
h(Field, { label: '交接说明', value: detail.handoff, onChange: (value) => setDetail({ ...detail, handoff: value }) }),
|
||||
),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { variant: 'primary', label: busy === 'update' ? '保存中…' : '保存角色', disabled: busy !== '', onClick: () => { void mutate('update') } }),
|
||||
h(Btn, { label: busy === 'checkpoint' ? '保存中…' : '保存检查点', disabled: busy !== '', onClick: () => { void mutate('checkpoint') } }),
|
||||
h(Btn, { variant: 'danger', label: busy === 'disable' ? '停用中…' : '停用部门', disabled: busy !== '' || item.active !== true, onClick: () => { void mutate('disable') } }),
|
||||
),
|
||||
h('p', { style: styles.hint }, '创建于 ' + formatIso(item.createdAt) + ' · 更新于 ' + formatIso(item.updatedAt)),
|
||||
) : null,
|
||||
)),
|
||||
),
|
||||
),
|
||||
h(Section, { title: '创建部门', hint: '同名部门会幂等复用,不会覆盖原角色。' },
|
||||
h('div', { style: styles.grid },
|
||||
h(Field, { label: '名称', value: form.name, onChange: (value) => setForm({ ...form, name: value }) }),
|
||||
h(Field, { label: '角色', value: form.role, onChange: (value) => setForm({ ...form, role: value }) }),
|
||||
h('div', { style: styles.field },
|
||||
h('span', { style: styles.label }, '范围'),
|
||||
h('select', { value: form.scope, style: styles.input, onChange: (event) => setForm({ ...form, scope: event.target.value }) },
|
||||
h('option', { value: 'project' }, '项目'),
|
||||
h('option', { value: 'global' }, '全局'),
|
||||
),
|
||||
),
|
||||
h(Field, { label: '技能(逗号分隔)', value: form.skills, onChange: (value) => setForm({ ...form, skills: value }) }),
|
||||
h(Field, { label: '允许工具(逗号分隔)', value: form.allowedTools, onChange: (value) => setForm({ ...form, allowedTools: value }) }),
|
||||
),
|
||||
h('div', { style: styles.checkboxRow },
|
||||
h('label', null, h('input', { type: 'checkbox', checked: form.readGlobal === true, onChange: (event) => setForm({ ...form, readGlobal: event.target.checked }) }), ' 可读全局记忆'),
|
||||
h('label', null, h('input', { type: 'checkbox', checked: form.readProject === true, onChange: (event) => setForm({ ...form, readProject: event.target.checked }) }), ' 可读项目记忆'),
|
||||
),
|
||||
h('div', { style: styles.actions }, h(Btn, { variant: 'primary', label: busy === 'create' ? '创建中…' : '创建部门', disabled: busy !== '', onClick: () => { void create() } })),
|
||||
),
|
||||
h(Section, { title: '部门召回', hint: '召回结果只展示服务端截断后的 contentSnippet(≤600 字符),并标注来源。' },
|
||||
h('div', { style: styles.grid },
|
||||
h('div', { style: styles.field },
|
||||
h('span', { style: styles.label }, '部门'),
|
||||
h('select', { value: recallId, style: styles.input, onChange: (event) => setRecallId(event.target.value) },
|
||||
h('option', { value: '' }, '选择部门…'),
|
||||
departments.map((item) => h('option', { key: item.id, value: item.id }, String(item.name))),
|
||||
),
|
||||
),
|
||||
h(Field, { label: '查询', value: recallQuery, onChange: setRecallQuery }),
|
||||
h(Field, { label: '数量(1-5)', type: 'number', value: recallK, onChange: setRecallK }),
|
||||
),
|
||||
h('div', { style: styles.actions }, h(Btn, { label: recallBusy ? '召回中…' : '查询召回', disabled: recallBusy, onClick: () => { void recall() } })),
|
||||
recallHits.length === 0 ? h('p', { style: styles.hint }, '暂无召回结果。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
|
||||
recallHits.map((hit: any, index: number) => h('div', { key: String(index), style: styles.row },
|
||||
h('div', { style: styles.rowHead }, h('div', { style: styles.pills },
|
||||
h(Pill, { label: '来源', value: hit.origin ?? '—', tone: 'muted' }),
|
||||
hit.record?.category === undefined ? null : h(Pill, { label: '分类', value: hit.record.category, tone: 'muted' }),
|
||||
)),
|
||||
h('div', { style: styles.clamp2 }, String(hit.contentSnippet ?? hit.content ?? '')),
|
||||
)),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
// Memory tab: local-memory spaces, paged memory list, read-only documents, forget.
|
||||
import * as React from 'react'
|
||||
import { API, request, postJson, bodyError, messageOf } from '../api'
|
||||
import { formatIso, formatTime } from '../format'
|
||||
import { styles } from '../styles'
|
||||
import { Banner, Btn, Field, Pill, Section } from '../components'
|
||||
import { useApi } from './useApi'
|
||||
import { workspaceQuery } from './workspace'
|
||||
|
||||
const h = React.createElement
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
function workspaceSuffix(workspace: string | undefined): string {
|
||||
return workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace)
|
||||
}
|
||||
|
||||
export function MemoryTab(props: { workspace?: string; active?: boolean }): any {
|
||||
const active = props.active !== false
|
||||
const workspace = props.workspace
|
||||
const [offset, setOffset] = React.useState(0)
|
||||
const [search, setSearch] = React.useState('')
|
||||
const [notice, setNotice] = React.useState<any>(null)
|
||||
const [pendingForget, setPendingForget] = React.useState<any>(null)
|
||||
const [busy, setBusy] = React.useState('')
|
||||
|
||||
const status = useApi(async () => {
|
||||
const result = await request('/dsh-brain/local-memory/status' + workspaceQuery(workspace))
|
||||
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取本地记忆状态失败'))
|
||||
return result.body
|
||||
}, { visible: active, pollMs: 15000 })
|
||||
|
||||
const memories = useApi(async () => {
|
||||
const result = await request('/dsh-brain/local-memory/memories?limit=' + String(PAGE_SIZE) + '&offset=' + String(offset) + workspaceSuffix(workspace))
|
||||
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取记忆列表失败'))
|
||||
return result.body
|
||||
}, { visible: active, deps: [offset] })
|
||||
|
||||
const documents = useApi(async () => {
|
||||
const result = await request('/dsh-brain/local-memory/documents' + workspaceQuery(workspace))
|
||||
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取文档列表失败'))
|
||||
return result.body
|
||||
}, { visible: active })
|
||||
|
||||
const items: any[] = Array.isArray(memories.data?.items) ? memories.data!.items : []
|
||||
const needle = String(search).trim().toLowerCase()
|
||||
const filtered = needle === '' ? items : items.filter((item) => {
|
||||
const hay = [item.content, item.category, item.scope, ...(Array.isArray(item.tags) ? item.tags : [])].join(' ').toLowerCase()
|
||||
return hay.indexOf(needle) >= 0
|
||||
})
|
||||
const total = memories.data?.total ?? 0
|
||||
|
||||
const forget = async (item: any): Promise<void> => {
|
||||
setBusy(item.id)
|
||||
try {
|
||||
const result = await postJson('/dsh-brain/local-memory/forget', { id: item.id, expectedRevision: item.revision, workspace })
|
||||
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
|
||||
setNotice({ tone: 'bad', text: bodyError(result, '删除失败') })
|
||||
} else {
|
||||
setNotice({ tone: 'ok', text: '已删除记忆条目。' })
|
||||
setPendingForget(null)
|
||||
memories.reload()
|
||||
}
|
||||
} catch (failure) {
|
||||
setNotice({ tone: 'bad', text: messageOf(failure) })
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const spaces = status.data?.spaces ?? {}
|
||||
const globalSpace = spaces.global
|
||||
const projectSpace = spaces.project
|
||||
|
||||
return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
|
||||
status.error === null ? null : h(Banner, { tone: 'bad' }, status.error),
|
||||
h(Section, { title: '本地记忆空间', hint: '全局空间与当前项目空间都由本机文件保存;云同步只影响上报,不改变本地存储。', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => { status.reload(); memories.reload(); documents.reload() } }) },
|
||||
h('div', { style: styles.pills },
|
||||
h(Pill, { label: 'provider', value: status.data?.provider ?? '—', tone: 'muted' }),
|
||||
h(Pill, { label: '全局空间', value: globalSpace === null || globalSpace === undefined ? '未创建' : (globalSpace.name ?? globalSpace.id ?? '就绪'), tone: globalSpace === null || globalSpace === undefined ? 'muted' : 'ok' }),
|
||||
h(Pill, { label: '项目空间', value: projectSpace === null || projectSpace === undefined ? '未创建' : (projectSpace.name ?? projectSpace.id ?? '就绪'), tone: projectSpace === null || projectSpace === undefined ? 'muted' : 'ok' }),
|
||||
h(Pill, { label: '本地记忆', value: status.data?.localMemoryEnabled === false ? '关' : '开', tone: status.data?.localMemoryEnabled === false ? 'bad' : 'ok' }),
|
||||
h(Pill, { label: '云同步', value: status.data?.cloudSyncEnabled === true ? '开' : '关', tone: status.data?.cloudSyncEnabled === true ? 'ok' : 'muted' }),
|
||||
),
|
||||
status.data?.globalRoot === undefined ? null : h('p', { style: styles.hint }, '全局:' + String(status.data.globalRoot) + (status.data?.projectRoot === undefined ? '' : ' · 项目:' + String(status.data.projectRoot))),
|
||||
),
|
||||
h(Section, { title: '记忆条目(' + String(total) + ')', hint: '只显示当前页;搜索只在当前页内过滤。删除需要二次确认并带 revision 校验。', aside: h('div', { style: styles.actions },
|
||||
h(Field, { label: '搜索当前页', value: search, onChange: setSearch }),
|
||||
h(Btn, { label: '刷新', variant: 'small', onClick: () => memories.reload() }),
|
||||
) },
|
||||
notice === null ? null : h(Banner, { tone: notice.tone }, notice.text),
|
||||
memories.error === null ? null : h(Banner, { tone: 'bad' }, memories.error),
|
||||
memories.status === 'loading' && items.length === 0 ? h('p', { style: styles.hint }, '正在读取记忆…') : null,
|
||||
filtered.length === 0 ? h('p', { style: styles.hint }, '当前页没有匹配的记忆条目。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
|
||||
filtered.map((item) => h('div', { key: item.id, style: styles.row },
|
||||
h('div', { style: styles.rowHead },
|
||||
h('div', { style: styles.pills },
|
||||
h(Pill, { label: 'scope', value: item.scope ?? '—', tone: 'muted' }),
|
||||
item.category === undefined ? null : h(Pill, { label: '分类', value: item.category, tone: 'muted' }),
|
||||
h(Pill, { label: 'rev', value: item.revision ?? '—', tone: 'muted' }),
|
||||
h(Pill, { label: '更新', value: formatIso(item.updatedAt), tone: 'muted' }),
|
||||
),
|
||||
h('div', { style: styles.actions },
|
||||
pendingForget === item.id ? null : h(Btn, { label: '删除…', variant: 'small', onClick: () => { setPendingForget(item.id); setNotice(null) } }),
|
||||
),
|
||||
),
|
||||
h('div', { style: styles.clamp2 }, String(item.content ?? '')),
|
||||
Array.isArray(item.tags) && item.tags.length > 0 ? h('p', { style: styles.hint }, '标签:' + item.tags.join('、')) : null,
|
||||
pendingForget === item.id ? h('div', { style: styles.nested },
|
||||
h('p', { style: styles.hint }, '确认删除这条记忆?此操作不可撤销。'),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { variant: 'danger', label: busy === item.id ? '删除中…' : '确认删除', disabled: busy !== '', onClick: () => { void forget(item) } }),
|
||||
h(Btn, { variant: 'small', label: '取消', disabled: busy !== '', onClick: () => setPendingForget(null) }),
|
||||
),
|
||||
) : null,
|
||||
)),
|
||||
),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { label: '上一页', variant: 'small', disabled: offset === 0 || memories.status === 'loading', onClick: () => setOffset(Math.max(0, offset - PAGE_SIZE)) }),
|
||||
h('span', { style: styles.hint }, '第 ' + String(Math.floor(offset / PAGE_SIZE) + 1) + ' 页 · 共 ' + String(total) + ' 条'),
|
||||
h(Btn, { label: '下一页', variant: 'small', disabled: offset + PAGE_SIZE >= total || memories.status === 'loading', onClick: () => setOffset(offset + PAGE_SIZE) }),
|
||||
),
|
||||
),
|
||||
h(Section, { title: '文档(只读)', hint: '项目文档由本地记忆库维护;这里只展示标题与摘要。' },
|
||||
documents.error === null ? null : h(Banner, { tone: 'bad' }, documents.error),
|
||||
(documents.data?.documents ?? []).length === 0 ? h('p', { style: styles.hint }, '当前项目还没有文档。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
|
||||
(documents.data?.documents ?? []).map((doc: any) => h('div', { key: doc.id, style: styles.row },
|
||||
h('div', { style: styles.rowHead },
|
||||
h('span', { style: styles.rowTitle }, String(doc.title ?? doc.id)),
|
||||
h('div', { style: styles.pills },
|
||||
h(Pill, { label: 'rev', value: doc.revision ?? '—', tone: 'muted' }),
|
||||
h(Pill, { label: '更新', value: formatIso(doc.updatedAt), tone: 'muted' }),
|
||||
),
|
||||
),
|
||||
h('div', { style: styles.clamp2 }, String(doc.content ?? '')),
|
||||
)),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
// Overview tab: status + capabilities aggregation.
|
||||
import * as React from 'react'
|
||||
import { API, request, messageOf } from '../api'
|
||||
import { formatTime } from '../format'
|
||||
import styles from './BrainPanel.module.css'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
const BUNDLE_LABELS: Record<string, string> = {
|
||||
cloudsync: '云同步',
|
||||
memory: '记忆',
|
||||
skills: '技能',
|
||||
mcp: 'MCP',
|
||||
'settings-ui': '设置 UI',
|
||||
ui: '设置 UI',
|
||||
}
|
||||
|
||||
function Pill(props: { label: string; value: any; tone?: 'ok' | 'bad' | 'warn' | 'muted' }): any {
|
||||
const tone = props.tone === undefined ? styles.muted : props.tone === 'ok' ? styles.ok : props.tone === 'bad' ? styles.bad : props.tone === 'warn' ? styles.warn : styles.muted
|
||||
return h('span', { className: styles.pill + ' ' + tone },
|
||||
h('span', { className: styles.pillLabel }, props.label),
|
||||
h('span', { className: styles.pillValue }, String(props.value)),
|
||||
)
|
||||
}
|
||||
|
||||
function Card(props: { title: string; children?: any }): any {
|
||||
return h('div', { className: styles.card },
|
||||
h('div', { className: styles.cardHead }, h('h4', { className: styles.cardTitle }, props.title)),
|
||||
props.children,
|
||||
)
|
||||
}
|
||||
|
||||
export function Overview(props: { active?: boolean }): any {
|
||||
const active = props.active !== false
|
||||
const [status, setStatus] = React.useState<any>(null)
|
||||
const [capabilities, setCapabilities] = React.useState<any>(null)
|
||||
const [memory, setMemory] = React.useState<any>(null)
|
||||
const [error, setError] = React.useState<string | null>(null)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!active) return
|
||||
let cancelled = false
|
||||
const load = async (): Promise<void> => {
|
||||
try {
|
||||
const [statusResult, capabilitiesResult, memoryResult] = await Promise.all([
|
||||
request(API.status),
|
||||
request(API.capabilities),
|
||||
request('/dsh-brain/local-memory/status'),
|
||||
])
|
||||
if (cancelled) return
|
||||
if (statusResult.status === 200 && statusResult.body !== null && statusResult.body.ok === true) {
|
||||
setStatus(statusResult.body)
|
||||
setError(null)
|
||||
} else {
|
||||
setError('读取插件状态失败(HTTP ' + String(statusResult.status) + ')')
|
||||
}
|
||||
if (capabilitiesResult.status === 200 && capabilitiesResult.body !== null && capabilitiesResult.body.ok === true) setCapabilities(capabilitiesResult.body)
|
||||
if (memoryResult.status === 200 && memoryResult.body !== null && memoryResult.body.ok === true) setMemory(memoryResult.body)
|
||||
else setMemory(null)
|
||||
} catch (failure) {
|
||||
if (!cancelled) setError(messageOf(failure))
|
||||
}
|
||||
}
|
||||
void load()
|
||||
const timer = setInterval(() => { void load() }, 15000)
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearInterval(timer)
|
||||
}
|
||||
}, [active])
|
||||
|
||||
const bundles: Record<string, boolean> = status?.bundles ?? {}
|
||||
const bundleKeys = Object.keys(bundles).length === 0 ? ['cloudsync', 'memory', 'skills', 'mcp', 'settings-ui'] : Object.keys(bundles)
|
||||
const settings = status?.settings ?? {}
|
||||
const reporter = status?.reporter ?? {}
|
||||
const skills = status?.skills ?? {}
|
||||
const memorySpaces = memory?.spaces ?? {}
|
||||
const version = capabilities?.version ?? status?.capabilities?.version ?? '—'
|
||||
|
||||
return h('div', { className: styles.overviewGrid },
|
||||
error === null ? null : h('div', { className: styles.error }, error),
|
||||
h(Card, { title: '版本与构建' },
|
||||
h('div', { className: styles.pills },
|
||||
h(Pill, { label: '版本', value: version }),
|
||||
h(Pill, { label: '服务', value: settings.baseUrlConfigured === false ? '未配置' : (settings.baseUrlOrigin || '已配置'), tone: settings.baseUrlConfigured === false ? 'warn' : 'muted' }),
|
||||
h(Pill, { label: '上报', value: settings.activityEnabled === true ? '开' : '关', tone: settings.activityEnabled === true ? 'ok' : 'muted' }),
|
||||
h(Pill, { label: '记忆', value: settings.memoryEnabled === true ? '开' : '关', tone: settings.memoryEnabled === true ? 'ok' : 'muted' }),
|
||||
h(Pill, { label: '诊断日志', value: settings.diagnosticsEnabled === false ? '关' : '开', tone: settings.diagnosticsEnabled === false ? 'muted' : 'ok' }),
|
||||
),
|
||||
h('p', { className: styles.hint }, '诊断日志位置:$DSH_HOME/brain/logs(全局)与 <项目>/.dsh/brain/logs(项目)'),
|
||||
status?.lastCheck === null || status?.lastCheck === undefined ? null : h('p', { className: styles.hint }, '最近检查:' + formatTime(status.lastCheck.at) + ' · ' + String(status.lastCheck.status ?? '')),
|
||||
),
|
||||
h(Card, { title: '五个 bundle 开关态' },
|
||||
h('div', { className: styles.pills },
|
||||
bundleKeys.map((key) => h(Pill, { key, label: BUNDLE_LABELS[key] ?? key, value: bundles[key] === true ? '启用' : bundles[key] === false ? '停用' : '未知', tone: bundles[key] === true ? 'ok' : bundles[key] === false ? 'bad' : 'muted' })),
|
||||
),
|
||||
),
|
||||
h(Card, { title: '本地记忆' },
|
||||
h('div', { className: styles.pills },
|
||||
h(Pill, { label: '状态', value: memory === null ? '不可用' : '已启用', tone: memory === null ? 'warn' : 'ok' }),
|
||||
h(Pill, { label: '全局空间', value: memorySpaces.global === null || memorySpaces.global === undefined ? '未创建' : '就绪', tone: memorySpaces.global === null || memorySpaces.global === undefined ? 'muted' : 'ok' }),
|
||||
h(Pill, { label: '项目空间', value: memorySpaces.project === null || memorySpaces.project === undefined ? '未创建' : '就绪', tone: memorySpaces.project === null || memorySpaces.project === undefined ? 'muted' : 'ok' }),
|
||||
h(Pill, { label: '云同步', value: memory?.cloudSyncEnabled === true ? '开' : '关', tone: memory?.cloudSyncEnabled === true ? 'ok' : 'muted' }),
|
||||
),
|
||||
memory === null ? h('p', { className: styles.hint }, '本地记忆状态路由不可用;启用「本地记忆」后此处会显示空间状态。') : null,
|
||||
),
|
||||
h(Card, { title: '同步统计' },
|
||||
h('div', { className: styles.statRow },
|
||||
h('span', { className: styles.stat }, h('span', { className: styles.statNum }, String(reporter.reportedTurns ?? 0)), h('span', { className: styles.hint }, '已上报回合')),
|
||||
h('span', { className: styles.stat }, h('span', { className: styles.statNum }, String(skills.downloaded?.length ?? 0)), h('span', { className: styles.hint }, '技能下载')),
|
||||
h('span', { className: styles.stat }, h('span', { className: styles.statNum }, String(skills.uploaded?.length ?? 0)), h('span', { className: styles.hint }, '技能上传')),
|
||||
h('span', { className: styles.statLast }, h('span', { className: styles.statNum }, String(skills.conflicts?.length ?? 0)), h('span', { className: styles.hint }, '待处理冲突')),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
// Adapted from dsh-mnemon memory-icon.tsx (MIT), see vendor/dsh-mnemon/LICENSE.
|
||||
import * as React from 'react'
|
||||
|
||||
const BRAIN_ICON_PATHS = [
|
||||
'M8 3.4C8 2.2 7.2 1.5 6.2 1.5C5.2 1.5 4.4 2.2 4.3 3.2C2.8 3.2 1.9 4.4 2.2 5.8C.9 6.8 1 8.8 2.4 9.6C2.1 11 3.1 12.2 4.5 12.2C4.8 14.7 8 14.9 8 12.3C8 14.9 11.2 14.7 11.5 12.2C12.9 12.2 13.9 11 13.6 9.6C15 8.8 15.1 6.8 13.8 5.8C14.1 4.4 13.2 3.2 11.7 3.2C11.6 2.2 10.8 1.5 9.8 1.5C8.8 1.5 8 2.2 8 3.4Z',
|
||||
'M8 3.4v8.9',
|
||||
'M4.3 3.2C4.2 4.1 4.7 4.8 5.5 5.1M11.7 3.2C11.8 4.1 11.3 4.8 10.5 5.1',
|
||||
'M2.4 9.6C3.2 10 4.4 9.7 4.8 8.8M13.6 9.6C12.8 10 11.6 9.7 11.2 8.8',
|
||||
'M4.5 12.2C4.4 11.2 4.9 10.5 5.7 10.2M11.5 12.2C11.6 11.2 11.1 10.5 10.3 10.2',
|
||||
] as const
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export function BrainIcon({ size = 18, ...marker }: { size?: number } & Record<string, unknown>): any {
|
||||
return h(
|
||||
'svg',
|
||||
{
|
||||
...marker,
|
||||
'data-dsh-panel-entry': 'dsh-brain',
|
||||
'data-dsh-plugin': 'dsh-brain',
|
||||
'data-dsh-part': 'sidebar-icon',
|
||||
'aria-hidden': 'true',
|
||||
viewBox: '0 0 16 16',
|
||||
width: size,
|
||||
height: size,
|
||||
fill: 'none',
|
||||
stroke: 'currentColor',
|
||||
strokeWidth: '1',
|
||||
strokeLinecap: 'round',
|
||||
strokeLinejoin: 'round',
|
||||
},
|
||||
BRAIN_ICON_PATHS.map((path) => h('path', { key: path, d: path })),
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
// Adapted from dsh-mnemon native-sidebar.tsx (MIT), see vendor/dsh-mnemon/LICENSE.
|
||||
// Registers the Brain panel on the two native shell seats:
|
||||
// sidebar.panellist -> the left-rail row (glyph only)
|
||||
// main -> the centre panel mounted while selected
|
||||
// Both are lazy seats: when the shell does not provide them the inject callback
|
||||
// simply never runs and the settings card fallback stays in place.
|
||||
import * as React from 'react'
|
||||
import { BrainIcon } from './brain-icon'
|
||||
import { BrainPanel } from './BrainPanel'
|
||||
|
||||
export const PANEL_ID = 'dsh-brain'
|
||||
export const PANEL_ORDER = 30
|
||||
|
||||
interface LayoutPanelInfo {
|
||||
getSnapshot(): { activePanelId: string | null }
|
||||
subscribe(listener: () => void): () => void
|
||||
}
|
||||
|
||||
export interface BrainPanelSeatFace {
|
||||
panelId: string
|
||||
ctx: any
|
||||
usePanelInfo?: <T>(selector: (info: { activePanelId: string | null }) => T) => T
|
||||
}
|
||||
|
||||
function makeUsePanelInfo(ctx: any, panelId: string): (<T>(selector: (info: { activePanelId: string | null }) => T) => T) {
|
||||
return function usePanelInfo<T>(selector: (info: { activePanelId: string | null }) => T): T {
|
||||
const panelInfo = ctx?.layout?.panelInfo as LayoutPanelInfo | undefined
|
||||
const read = (): T => selector(panelInfo === undefined ? { activePanelId: panelId } : panelInfo.getSnapshot())
|
||||
const [value, setValue] = React.useState<T>(read)
|
||||
React.useEffect(() => {
|
||||
if (panelInfo === undefined) return
|
||||
const update = (): void => setValue(read())
|
||||
update()
|
||||
return panelInfo.subscribe(update)
|
||||
}, [panelInfo, panelId])
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
export function registerBrainPanel(ctx: any): () => void {
|
||||
let stopNative: (() => void) | undefined
|
||||
let disposed = false
|
||||
try {
|
||||
stopNative = ctx.slots.inject('main', () =>
|
||||
ctx.slots.inject('sidebar.panellist', () => {
|
||||
const usePanelInfo = makeUsePanelInfo(ctx, PANEL_ID)
|
||||
const panel = (props: any) => React.createElement(BrainPanel, { ...props, ctx, panelId: PANEL_ID, usePanelInfo })
|
||||
const icon = (props: any) => React.createElement(BrainIcon, { size: props?.size ?? 18 })
|
||||
const stopMain = ctx.slots.register({ name: 'main', key: PANEL_ID, inject: () => ({ panelId: PANEL_ID }) }, panel as never)
|
||||
let stopIcon: (() => void) | undefined
|
||||
try {
|
||||
stopIcon = ctx.slots.register({
|
||||
name: 'sidebar.panellist',
|
||||
id: PANEL_ID,
|
||||
order: PANEL_ORDER,
|
||||
label: () => 'Brain',
|
||||
locale: 'dsh-brain',
|
||||
}, icon as never)
|
||||
} catch (failure) {
|
||||
stopMain?.()
|
||||
throw failure
|
||||
}
|
||||
return () => {
|
||||
stopIcon?.()
|
||||
stopMain?.()
|
||||
}
|
||||
}),
|
||||
)
|
||||
} catch (failure) {
|
||||
if (typeof console !== 'undefined') {
|
||||
console.info('[dsh-brain] sidebar panel seats unavailable; the settings card fallback stays active: ' + (failure instanceof Error ? failure.message : String(failure)))
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
if (disposed) return
|
||||
disposed = true
|
||||
try {
|
||||
stopNative?.()
|
||||
} catch {
|
||||
/* a seat disposer must never break plugin teardown */
|
||||
}
|
||||
stopNative = undefined
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
// Adapted from dsh-mnemon (MIT), see vendor/dsh-mnemon/LICENSE.
|
||||
// Minimal external-store / held-seat primitives used by the Brain panel seats.
|
||||
|
||||
export class ExternalStore<T> {
|
||||
protected snapshot: T
|
||||
private readonly listeners = new Set<() => void>()
|
||||
|
||||
constructor(initial: T) {
|
||||
this.snapshot = initial
|
||||
}
|
||||
|
||||
readonly getSnapshot = (): T => this.snapshot
|
||||
|
||||
readonly subscribe = (listener: () => void): (() => void) => {
|
||||
this.listeners.add(listener)
|
||||
return () => {
|
||||
this.listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
protected get listenerCount(): number {
|
||||
return this.listeners.size
|
||||
}
|
||||
|
||||
protected setSnapshot(next: T, force = false): void {
|
||||
if (!force && Object.is(next, this.snapshot)) return
|
||||
this.snapshot = next
|
||||
this.notify()
|
||||
}
|
||||
|
||||
protected notify(): void {
|
||||
for (const listener of [...this.listeners]) listener()
|
||||
}
|
||||
}
|
||||
|
||||
export class HeldSeat<T> extends ExternalStore<T | undefined> {
|
||||
private owner: symbol | undefined
|
||||
|
||||
constructor() {
|
||||
super(undefined)
|
||||
}
|
||||
|
||||
protected hold(value: T): () => void {
|
||||
const token = Symbol('held-seat')
|
||||
this.owner = token
|
||||
this.setSnapshot(value)
|
||||
return () => {
|
||||
if (this.owner !== token) return
|
||||
this.owner = undefined
|
||||
this.setSnapshot(undefined)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface RafCoalescer {
|
||||
schedule(): void
|
||||
flush(): void
|
||||
cancel(): void
|
||||
readonly pending: boolean
|
||||
}
|
||||
|
||||
export function createRafCoalescer(run: () => void): RafCoalescer {
|
||||
let frameId: number | undefined
|
||||
let microtaskToken: object | undefined
|
||||
return {
|
||||
schedule(): void {
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
if (frameId !== undefined) return
|
||||
frameId = requestAnimationFrame(() => { frameId = undefined; run() })
|
||||
return
|
||||
}
|
||||
if (microtaskToken !== undefined) return
|
||||
microtaskToken = {}
|
||||
queueMicrotask(() => { microtaskToken = undefined; run() })
|
||||
},
|
||||
flush(): void {
|
||||
this.cancel()
|
||||
run()
|
||||
},
|
||||
cancel(): void {
|
||||
if (frameId !== undefined && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frameId)
|
||||
frameId = undefined
|
||||
microtaskToken = undefined
|
||||
},
|
||||
get pending(): boolean {
|
||||
return frameId !== undefined || microtaskToken !== undefined
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
// Small data-loading state machine shared by the Brain panel tabs.
|
||||
import * as React from 'react'
|
||||
import { messageOf } from '../api'
|
||||
|
||||
export type ApiStatus = 'idle' | 'loading' | 'ready' | 'error'
|
||||
|
||||
export interface ApiState<T> {
|
||||
status: ApiStatus
|
||||
data: T | null
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export interface UseApiOptions {
|
||||
/** false pauses all loading and polling (used by better-sidebar visible=false). */
|
||||
visible?: boolean
|
||||
/** Optional polling interval in milliseconds. */
|
||||
pollMs?: number
|
||||
/** Extra dependencies that should trigger a reload. */
|
||||
deps?: unknown[]
|
||||
}
|
||||
|
||||
export function useApi<T>(loader: () => Promise<T>, options: UseApiOptions = {}): ApiState<T> & { reload: () => void; mutate: (data: T | null) => void } {
|
||||
const visible = options.visible !== false
|
||||
const loaderRef = React.useRef(loader)
|
||||
loaderRef.current = loader
|
||||
const [state, setState] = React.useState<ApiState<T>>({ status: 'idle', data: null, error: null })
|
||||
|
||||
const reload = React.useCallback((): void => {
|
||||
if (!visible) return
|
||||
setState((previous) => ({ status: previous.data === null ? 'loading' : 'ready', data: previous.data, error: null }))
|
||||
loaderRef.current().then(
|
||||
(data) => setState({ status: 'ready', data, error: null }),
|
||||
(failure) => setState((previous) => ({ status: 'error', data: previous.data, error: messageOf(failure) })),
|
||||
)
|
||||
}, [visible])
|
||||
|
||||
const dependencies = options.deps ?? []
|
||||
React.useEffect(() => {
|
||||
if (!visible) return
|
||||
reload()
|
||||
if (options.pollMs === undefined) return
|
||||
const timer = setInterval(reload, options.pollMs)
|
||||
return () => clearInterval(timer)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [visible, options.pollMs, reload, ...dependencies])
|
||||
|
||||
return {
|
||||
...state,
|
||||
reload,
|
||||
mutate: (data: T | null) => setState({ status: data === null ? 'idle' : 'ready', data, error: null }),
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
// Resolve the active session workspace from the optional host sessions face.
|
||||
// The probe is deliberately defensive: the panel must work without the service.
|
||||
export function resolveWorkspace(ctx: any): string | undefined {
|
||||
try {
|
||||
const sessions = ctx !== undefined && ctx !== null && typeof ctx.get === 'function' ? ctx.get('sessions') : undefined
|
||||
if (sessions === undefined || sessions === null) return undefined
|
||||
const current = typeof sessions.current === 'function' ? sessions.current() : sessions.current
|
||||
const candidates = [
|
||||
current?.cwd,
|
||||
current?.header?.cwd,
|
||||
current?.session?.cwd,
|
||||
current?.session?.header?.cwd,
|
||||
typeof sessions.cwd === 'function' ? sessions.cwd() : undefined,
|
||||
]
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && candidate.trim() !== '') return candidate
|
||||
}
|
||||
} catch {
|
||||
/* no sessions face -> omit the workspace argument */
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function workspaceQuery(workspace: string | undefined): string {
|
||||
return workspace === undefined ? '' : '?workspace=' + encodeURIComponent(workspace)
|
||||
}
|
||||
|
|
@ -0,0 +1,300 @@
|
|||
// dsh-brain client section component.
|
||||
import * as React from 'react'
|
||||
import { API, request, postJson, messageOf, bodyError } from '../api'
|
||||
import { formatTime, formatIso, formatBytes, shortHash, readStored, store, OUTCOME_LABELS, OUTCOME_TONES, ORIGIN_LABELS, CHECK_TONES, CHECK_LABELS, MCP_STATE_LABELS } from '../format'
|
||||
import { styles } from '../styles'
|
||||
import { Pill, Banner, Field, Btn, IconBtn, Switch, Toggle, Section, CardBoundary } from '../components'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export function ImportSection(props) {
|
||||
var onImported = props && typeof props.onImported === 'function' ? props.onImported : null
|
||||
var tuple = React.useState({ expanded: false, status: 'idle', sources: [], open: {}, busy: '', notice: null, imported: {}, search: '', selection: [], progress: null })
|
||||
var s = tuple[0]
|
||||
var set = tuple[1]
|
||||
function patch(next) { set(function (prev) { return Object.assign({}, prev, next) }) }
|
||||
function load() {
|
||||
patch({ status: 'loading', notice: null })
|
||||
request(API.skills + '/sources', { method: 'GET' }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
patch({ status: 'ready', sources: Array.isArray(res.body.sources) ? res.body.sources : [] })
|
||||
} else patch({ status: 'error', notice: { tone: 'bad', text: bodyError(res, '读取来源失败') } })
|
||||
}, function (error) { patch({ status: 'error', notice: { tone: 'bad', text: messageOf(error) } }) })
|
||||
}
|
||||
function openPanel() {
|
||||
patch({ expanded: true })
|
||||
if (s.status === 'idle' || s.status === 'error') load()
|
||||
}
|
||||
function closePanel() {
|
||||
patch({ expanded: false })
|
||||
}
|
||||
function dshFolders() {
|
||||
var found = {}
|
||||
s.sources.forEach(function (source) {
|
||||
if (!source.writable) return
|
||||
var groups = source.groups || []
|
||||
groups.forEach(function (group) {
|
||||
var skills = group.skills || []
|
||||
skills.forEach(function (skill) { found[skill.folder] = true })
|
||||
})
|
||||
})
|
||||
return found
|
||||
}
|
||||
function toggleSource(sourceId) {
|
||||
var next = Object.assign({}, s.open)
|
||||
var open = s.open[sourceId] !== false
|
||||
next[sourceId] = !open
|
||||
patch({ open: next })
|
||||
}
|
||||
var mine = dshFolders()
|
||||
var others = s.sources.filter(function (source) { return !source.writable })
|
||||
var needle = String(s.search).trim().toLowerCase()
|
||||
function skillsOf(source) {
|
||||
var list = []
|
||||
var groups = source.groups || []
|
||||
groups.forEach(function (group) {
|
||||
var items = group.skills || []
|
||||
items.forEach(function (skill) { list.push(skill) })
|
||||
})
|
||||
return list
|
||||
}
|
||||
function importedYet(skill) {
|
||||
return mine[skill.folder] === true || s.imported[skill.folder] === true
|
||||
}
|
||||
var candidates = []
|
||||
others.forEach(function (source) {
|
||||
if (!source.exists) return
|
||||
skillsOf(source).forEach(function (skill) {
|
||||
candidates.push({ source: source, skill: skill })
|
||||
})
|
||||
})
|
||||
var matches = needle === '' ? candidates : candidates.filter(function (entry) {
|
||||
var hay = String(entry.skill.name || '') + ' ' + String(entry.skill.folder || '') + ' ' + String(entry.skill.description || '')
|
||||
return hay.toLowerCase().indexOf(needle) >= 0
|
||||
})
|
||||
var importable = matches.filter(function (entry) { return !importedYet(entry.skill) })
|
||||
var alreadyCount = candidates.length - candidates.filter(function (entry) { return !importedYet(entry.skill) }).length
|
||||
function keyOf(entry) {
|
||||
return String(entry.source.id) + ':' + String(entry.skill.folder)
|
||||
}
|
||||
var chosen = s.selection
|
||||
function isChosen(entry) {
|
||||
return chosen.indexOf(keyOf(entry)) >= 0
|
||||
}
|
||||
function chooseMany(list, on) {
|
||||
var next = chosen.slice()
|
||||
list.forEach(function (entry) {
|
||||
var key = keyOf(entry)
|
||||
var at = next.indexOf(key)
|
||||
if (on === true && at < 0) next.push(key)
|
||||
if (on !== true && at >= 0) next.splice(at, 1)
|
||||
})
|
||||
patch({ selection: next })
|
||||
}
|
||||
var chosenEntries = candidates.filter(function (entry) {
|
||||
return chosen.indexOf(keyOf(entry)) >= 0 && !importedYet(entry.skill)
|
||||
})
|
||||
function importSelected() {
|
||||
var targets = chosenEntries
|
||||
if (targets.length === 0) return Promise.resolve()
|
||||
patch({ busy: 'batch', notice: null, progress: { done: 0, total: targets.length } })
|
||||
var done = 0
|
||||
var failures = []
|
||||
var importedMap = Object.assign({}, s.imported)
|
||||
var chain = Promise.resolve()
|
||||
targets.forEach(function (entry) {
|
||||
chain = chain.then(function () {
|
||||
return postJson(API.skills + '/import', { sourceId: entry.source.id, folder: entry.skill.folder }).then(
|
||||
function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
done += 1
|
||||
importedMap[entry.skill.folder] = true
|
||||
} else failures.push(String(entry.skill.name) + '(' + bodyError(res, '失败') + ')')
|
||||
patch({ progress: { done: done + failures.length, total: targets.length } })
|
||||
},
|
||||
function (error) {
|
||||
failures.push(String(entry.skill.name) + '(' + messageOf(error) + ')')
|
||||
patch({ progress: { done: done + failures.length, total: targets.length } })
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
return chain.then(function () {
|
||||
patch({
|
||||
busy: '',
|
||||
progress: null,
|
||||
selection: [],
|
||||
imported: importedMap,
|
||||
notice: {
|
||||
tone: failures.length === 0 ? 'ok' : 'warn',
|
||||
text: '已导入 ' + String(done) + ' / ' + String(targets.length) + ' 个技能到 DSH' + (failures.length === 0 ? '。' : ';失败:' + failures.join('、')),
|
||||
},
|
||||
})
|
||||
if (onImported !== null) onImported()
|
||||
load()
|
||||
})
|
||||
}
|
||||
if (!s.expanded) {
|
||||
return h(
|
||||
'div',
|
||||
{ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap' } },
|
||||
h(Btn, {
|
||||
label: '从其他软件导入',
|
||||
ariaLabel: '从其他软件导入',
|
||||
onClick: openPanel,
|
||||
}),
|
||||
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
|
||||
)
|
||||
}
|
||||
function describe(skill) {
|
||||
var text = String(skill.description === undefined || skill.description === null ? '' : skill.description).trim()
|
||||
if (/^[>|][+-]?$/.test(text)) return ''
|
||||
return text
|
||||
}
|
||||
var blocks = others.map(function (source) {
|
||||
var all = skillsOf(source)
|
||||
var visible = matches.filter(function (entry) { return entry.source.id === source.id })
|
||||
var open = s.open[source.id] !== false
|
||||
var selectable = visible.filter(function (entry) { return !importedYet(entry.skill) })
|
||||
return h('div', { key: source.id, style: styles.row },
|
||||
h('div', { style: styles.rowHead },
|
||||
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '8px', minWidth: 0 } },
|
||||
h('span', { style: styles.sourceGlyph }, String(source.label).slice(0, 1)),
|
||||
h('span', { style: styles.sourceTitle }, String(source.label)),
|
||||
h(
|
||||
'span',
|
||||
{ style: styles.hint },
|
||||
source.exists
|
||||
? String(all.length) + ' 个技能' + (needle === '' ? '' : ' · 匹配 ' + String(visible.length)) + ' · 可导入 ' + String(selectable.length)
|
||||
: '未安装',
|
||||
),
|
||||
),
|
||||
source.exists
|
||||
? h('div', { style: styles.actions },
|
||||
h(Btn, {
|
||||
label: '全选本来源(' + String(selectable.length) + ')',
|
||||
ariaLabel: '全选本来源 ' + String(source.label),
|
||||
variant: 'small',
|
||||
disabled: selectable.length === 0 || s.busy !== '',
|
||||
onClick: function () { chooseMany(visible, true) },
|
||||
}),
|
||||
h(Btn, { label: open ? '收起' : '展开', variant: 'small', onClick: function () { toggleSource(source.id) } }),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
h('span', { style: styles.mono }, String(source.root)),
|
||||
!source.exists || !open
|
||||
? null
|
||||
: visible.length === 0
|
||||
? h('p', { style: styles.hint }, needle === '' ? '这个来源里还没有技能。' : '没有匹配「' + s.search + '」的技能。')
|
||||
: h(
|
||||
'div',
|
||||
{ style: { display: 'flex', flexDirection: 'column', gap: '2px', maxHeight: '320px', overflow: 'auto' } },
|
||||
visible.map(function (entry) {
|
||||
var skill = entry.skill
|
||||
var has = importedYet(skill)
|
||||
return h(
|
||||
'label',
|
||||
{ key: String(skill.folder), style: styles.checkboxRow },
|
||||
h('input', {
|
||||
type: 'checkbox',
|
||||
checked: has || isChosen(entry),
|
||||
disabled: has || s.busy !== '',
|
||||
'aria-label': '选择技能 ' + String(skill.name),
|
||||
onChange: function (event) { chooseMany([entry], event.target.checked === true) },
|
||||
}),
|
||||
h(
|
||||
'span',
|
||||
{ style: { minWidth: 0, flex: '1 1 auto' } },
|
||||
h('span', { style: styles.rowTitle }, String(skill.name)),
|
||||
describe(skill) === '' ? null : h('span', { style: Object.assign({}, styles.hint, styles.clamp1) }, describe(skill)),
|
||||
),
|
||||
has ? h(Pill, { label: 'DSH', value: '已导入', tone: 'muted' }) : null,
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
return h(
|
||||
Section,
|
||||
{
|
||||
title: '从其他软件导入',
|
||||
hint: '把其他软件技能目录里的技能复制一份到 DSH,原目录不动;同名技能不能重复导入。',
|
||||
aside: h(
|
||||
'div',
|
||||
{ style: styles.actions },
|
||||
h(Btn, { label: '刷新', variant: 'small', onClick: load }),
|
||||
h(Btn, { label: '收起', variant: 'small', onClick: closePanel }),
|
||||
),
|
||||
},
|
||||
s.status === 'loading' ? h('p', { style: styles.hint }, '正在读取来源…')
|
||||
: others.length === 0 ? h('p', { style: styles.hint }, '没有检测到其他软件的技能目录。')
|
||||
: h(
|
||||
'div',
|
||||
{ style: styles.root },
|
||||
h(
|
||||
'div',
|
||||
{ style: styles.pills },
|
||||
h(Pill, { label: '来源', value: String(others.length), tone: 'muted' }),
|
||||
h(Pill, { label: '可导入', value: String(candidates.length - alreadyCount), tone: 'muted' }),
|
||||
s.search === '' ? null : h(Pill, { label: '匹配', value: String(matches.length), tone: matches.length === 0 ? 'muted' : 'ok' }),
|
||||
h(Pill, { label: '已选', value: String(chosenEntries.length), tone: chosenEntries.length === 0 ? 'muted' : 'ok' }),
|
||||
alreadyCount === 0 ? null : h(Pill, { label: '已在 DSH', value: String(alreadyCount), tone: 'muted' }),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ style: { display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' } },
|
||||
h('input', {
|
||||
type: 'search',
|
||||
style: Object.assign({}, styles.input, { flex: '1 1 220px', minWidth: 0 }),
|
||||
value: s.search,
|
||||
placeholder: '搜索技能:名称 / 目录 / 描述',
|
||||
'aria-label': '搜索要导入的技能',
|
||||
onChange: function (event) { patch({ search: event.target.value }) },
|
||||
}),
|
||||
s.search === '' ? null : h(Btn, {
|
||||
label: '清空搜索',
|
||||
variant: 'small',
|
||||
onClick: function () { patch({ search: '' }) },
|
||||
}),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ style: Object.assign({}, styles.actions, { flexWrap: 'wrap' }) },
|
||||
h(Btn, {
|
||||
label: '全选匹配可导入(' + String(importable.length) + ')',
|
||||
ariaLabel: '全选匹配可导入',
|
||||
variant: 'small',
|
||||
disabled: importable.length === 0 || s.busy !== '',
|
||||
onClick: function () { chooseMany(importable, true) },
|
||||
}),
|
||||
h(Btn, {
|
||||
label: '全选全部(' + String(candidates.length - alreadyCount) + ')',
|
||||
ariaLabel: '全选全部',
|
||||
variant: 'small',
|
||||
disabled: candidates.length - alreadyCount === 0 || s.busy !== '',
|
||||
onClick: function () {
|
||||
chooseMany(candidates.filter(function (entry) { return !importedYet(entry.skill) }), true)
|
||||
},
|
||||
}),
|
||||
h(Btn, {
|
||||
label: '清空已选',
|
||||
ariaLabel: '清空已选',
|
||||
variant: 'small',
|
||||
disabled: chosenEntries.length === 0,
|
||||
onClick: function () { patch({ selection: [] }) },
|
||||
}),
|
||||
h(Btn, {
|
||||
variant: 'primary',
|
||||
label: s.busy === 'batch' ? '导入中…' : '导入所选(' + String(chosenEntries.length) + ')',
|
||||
ariaLabel: '导入所选',
|
||||
disabled: s.busy !== '' || chosenEntries.length === 0,
|
||||
onClick: importSelected,
|
||||
}),
|
||||
),
|
||||
s.progress === null ? null : h('p', { style: styles.hint }, '正在导入:' + String(s.progress.done) + ' / ' + String(s.progress.total)),
|
||||
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, blocks),
|
||||
),
|
||||
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue