From 09dc36533844b1dd487546233d079bf45f73e571 Mon Sep 17 00:00:00 2001 From: qyh15 Date: Wed, 11 Nov 2026 20:27:13 +0800 Subject: [PATCH] vendor: dsh-cloud-memory 0.4.1 baseline (upstream 1865a82) --- .gitattributes | 5 + .gitignore | 22 + .npmignore | 21 + LICENSE | 21 + README.md | 202 ++++++ client/index.js | 846 ++++++++++++++++++++++++ cordis.patch.yml | 13 + docs/source-provenance.md | 8 + lib/api.js | 300 +++++++++ lib/config.js | 82 +++ lib/context-types.js | 1 + lib/index.js | 136 ++++ lib/mnemon/descriptor.js | 60 ++ lib/mnemon/driver.js | 223 +++++++ lib/mnemon/index.js | 46 ++ lib/page.js | 429 ++++++++++++ lib/reporter.js | 392 +++++++++++ lib/routes.js | 441 +++++++++++++ lib/skill-admin.js | 262 ++++++++ lib/skill-page.js | 161 +++++ lib/skill-sync.js | 519 +++++++++++++++ lib/store.js | 270 ++++++++ lib/tools.js | 286 ++++++++ package.json | 82 +++ pnpm-lock.yaml | 1269 ++++++++++++++++++++++++++++++++++++ scripts/pack-guard.mjs | 142 ++++ scripts/release-prep.mjs | 127 ++++ src/api.ts | 489 ++++++++++++++ src/config.ts | 97 +++ src/context-types.ts | 59 ++ src/index.ts | 153 +++++ src/mnemon/descriptor.ts | 62 ++ src/mnemon/driver.ts | 255 ++++++++ src/mnemon/index.ts | 57 ++ src/page.ts | 431 ++++++++++++ src/reporter.ts | 444 +++++++++++++ src/routes.ts | 485 ++++++++++++++ src/skill-admin.ts | 276 ++++++++ src/skill-page.ts | 161 +++++ src/skill-sync.ts | 565 ++++++++++++++++ src/store.ts | 278 ++++++++ src/tools.ts | 309 +++++++++ tsconfig.build.json | 12 + tsconfig.json | 20 + verify-mnemon-provider.mjs | 149 +++++ verify-reporter.mjs | 110 ++++ verify-skill-admin.mjs | 165 +++++ verify-skills-sync.mjs | 186 ++++++ 48 files changed, 11129 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .npmignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 client/index.js create mode 100644 cordis.patch.yml create mode 100644 docs/source-provenance.md create mode 100644 lib/api.js create mode 100644 lib/config.js create mode 100644 lib/context-types.js create mode 100644 lib/index.js create mode 100644 lib/mnemon/descriptor.js create mode 100644 lib/mnemon/driver.js create mode 100644 lib/mnemon/index.js create mode 100644 lib/page.js create mode 100644 lib/reporter.js create mode 100644 lib/routes.js create mode 100644 lib/skill-admin.js create mode 100644 lib/skill-page.js create mode 100644 lib/skill-sync.js create mode 100644 lib/store.js create mode 100644 lib/tools.js create mode 100644 package.json create mode 100644 pnpm-lock.yaml create mode 100644 scripts/pack-guard.mjs create mode 100644 scripts/release-prep.mjs create mode 100644 src/api.ts create mode 100644 src/config.ts create mode 100644 src/context-types.ts create mode 100644 src/index.ts create mode 100644 src/mnemon/descriptor.ts create mode 100644 src/mnemon/driver.ts create mode 100644 src/mnemon/index.ts create mode 100644 src/page.ts create mode 100644 src/reporter.ts create mode 100644 src/routes.ts create mode 100644 src/skill-admin.ts create mode 100644 src/skill-page.ts create mode 100644 src/skill-sync.ts create mode 100644 src/store.ts create mode 100644 src/tools.ts create mode 100644 tsconfig.build.json create mode 100644 tsconfig.json create mode 100644 verify-mnemon-provider.mjs create mode 100644 verify-reporter.mjs create mode 100644 verify-skill-admin.mjs create mode 100644 verify-skills-sync.mjs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8c2e79a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +* text=auto eol=lf +*.ps1 text eol=crlf +*.cmd text eol=crlf +*.png binary +*.tgz binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..42c6e9b --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# 依赖与缓存 +node_modules/ +.pnpm-store/ +.pnpm-cache/ +.npm/ + +# 构建以外的东西不忽略:lib/ 与 client/ 是 npm 包的实际产物,直接入库,保证仓库与发布件一致 + +# 本地与临时 +.env +.env.* +*.log +*.tgz +.tmp/ +tmp/ +.DS_Store +Thumbs.db + +# 发布时生成 +npm-debug.log* +node_modules/ +.cloud-memory/ diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..dff5061 --- /dev/null +++ b/.npmignore @@ -0,0 +1,21 @@ +# ?????? package.json ? files ??????????????? npm ?? +AGENTS.md +TODO.md +TASKS.md +HANDOFF.md +NOTES.md +*.plan.md +PLAN.md +scripts/ +src/ +tsconfig*.json +pnpm-lock.yaml +package-lock.json +.pnpm-cache/ +.pnpm-store/ +node_modules/ +*.mjs +*.log +*.tgz +.env +.env.* \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d5fa063 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 dsh-cloud-memory contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..676c8e5 --- /dev/null +++ b/README.md @@ -0,0 +1,202 @@ +# dsh-cloud-memory + +把 DeepSeek Harness 接到 LongMemory 云端记忆服务:**每轮对话结束自动上报一条活动记录**(只上传元数据),并把云端记忆库变成 agent 可用的工具。 + +当前版本 **0.1.1**,含宿主端与浏览器端两部分:host 半负责活动上报与工具注册,`client/index.js` 提供「设置 → 插件 → 云端记忆」配置卡片。 + +## 它做什么 + +| 能力 | 说明 | +| --- | --- | +| 活动上报 | 监听 `session/event` 的 `turn/start`、`turn/end`,每个结束的回合调用一次 `POST /activity/turn`。上报字段只有 6 个:`client_id`、`conversation_id`、`turn_id`、`status`、`started_at`、`completed_at`。 | +| 幂等 | `turn_id` 为 `:`,服务端按 `turn_id` 去重,重试不会重复计数。 | +| 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试(说明载荷或令牌有问题)。 | +| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具直接读写云端记忆库。 | +| 配置页 | `GET /cloud-memory` 提供完整配置界面(本 profile 关闭了原生设置页,所以自带页面)。 | + +**绝不上传**:提示词正文、工具输出、文件内容、本地路径、令牌。上报载荷在类型层面就只有六个字段,构造它的函数拿不到正文。 + +## 安装 + +```powershell +# 装进当前 profile(默认 desktop) +dsh plugin --profile desktop add dsh-cloud-memory +``` + +装好后确认 profile 的 `package.json` 里有两处: + +```jsonc +{ + "dependencies": { "dsh-cloud-memory": "^0.1.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`),否则上报与工具都会连接失败。 + +## 登录(推荐) + +在设置卡里填云端面板的**普通用户**账号和密码,点「登录并获取令牌」: + +``` +密码 → POST /api/auth/login(一次性会话 cookie) + → POST /api/auth/tokens ×2(activity:write、memory:write) + → 只把两个 cmt_… 令牌写进 $DSH_HOME/cloud-memory.json + → 密码与会话 cookie 立即丢弃 +``` + +- 密码只在这一串请求里存在:不落盘、不写日志、不随 `/cloud-memory/status` 回显。 +- 服务端只保存令牌哈希,令牌可单独撤销;改密码不影响已签发令牌。 +- 服务地址不是 HTTPS(且不是 loopback)时插件拒绝发送密码。 +- 管理员账号不能签发个人令牌(服务端 `403 management_only`),请用普通用户。 +- 也可跳过登录,直接手填两个令牌(见下)。 + +## 配置 + +配置文件 `$DSH_HOME/cloud-memory.json`(默认 `%USERPROFILE%\.dsh\cloud-memory.json`),字段: + +| 字段 | 默认 | 说明 | +| --- | --- | --- | +| `enabled` | `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` | 云端技能中心与本机技能目录的双向同步开关。 | +| `skillsDir` | 空 | 本机技能目录覆盖;为空时用 `$DSH_HOME/skills`。 | + +两个令牌也可以用环境变量 `DSH_CLOUD_MEMORY_ACTIVITY_TOKEN`、`DSH_CLOUD_MEMORY_MEMORY_TOKEN` 覆盖。 + +> 一个 key 只有一种 scope,所以需要两个令牌:只做上报就只填活动令牌,只做检索就只填记忆令牌。 + +## Mnemon 集成(记忆空间 Provider) + +自 0.2.0 起,本包同时是一个 Mnemon 记忆空间 Provider:Mnemon 管本地在场 +(运行时记忆每轮注入),长期记忆的每一次读、写都实时穿透到 LongMemory—— +云端是真源,本地不留长期副本。因此其他工具(Claude Code、Codex、看板) +刚写进 LongMemory 的记忆,DSH 里立刻能召回。 + +启用方式:在 Mnemon 的记忆空间来源配置里给 providers 列表加一行 +(profile 覆盖或 bundle 配置均可),然后重启 DSH: + +```yaml +providers: + - use: dsh-cloud-memory/mnemon-provider + instanceId: longmemory +``` + +之后在 Mnemon 的插件页会出现 LongMemory 的服务字段(Endpoint / Memory +token),留空即复用本插件已有的 `cloud-memory.json` 配置,一处配置两处生效。 +每个记忆空间映射一个 LongMemory 项目:发现流程会自动列出账号下的全部 +项目,外加一个不分项目的「全部」空间;也可以在空间上手动填 Project ID。 + +v1 范围:支持 发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;暂不支持 +删除(LongMemory 客户端接口没有删除操作)与图谱读取(接口未暴露, +返回空图谱且能力声明为关)。离线时长期记忆不可用,Mnemon 的本地 +运行时记忆不受影响。 + +验证:`node verify-mnemon-provider.mjs`(对本地 stub 服务跑通 +发现→写入→召回→项目隔离全流程)。 + +## 技能同步 + +自 0.3.0 起,插件在记忆之外还双向同步技能:云端技能中心是总汇,本机 +技能目录(默认 `$DSH_HOME/skills`)是工作副本,本地的浏览、启停、分类 +仍归 DSH 技能管理器。插件启动 5 秒后首跑,之后每 15 分钟对账一次; +结果与冲突列表见 `GET /cloud-memory/status` 的 `skills` 字段,聊天里 +也可以用 `skill_list` 工具查看云端清单。 + +- **下行**:云端技能按平台自己的规矩落地——先验整包清单哈希、再逐 + 文件验 sha256,原子写入,并留下 `.manifest.json` 交付记录;云端标 + 记了「脚本已变更待确认」的包不会自动安装,先在看板里确认。 +- **上行**:本地原创技能(管理器安装、导入或手写的)自动发布到云 + 端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被 + 别人先改过就报冲突、不强行覆盖。 + +防事故的规矩:云端交付的技能从不回传,本地改动它只报 +`locally_modified` 冲突、原样不动;本地删除不删云端,且同版本不会 +被重新拉回(云端出了新版才会再下来);同名技能两边都有时互不抢占, +报 `name_collision`。云端只接受固定布局(根目录只有 `SKILL.md`, +其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单, +单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报 +`unsupported_layout`,不会为了迁就而裁剪文件。 + +验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通 +下行安装、上行发布与修订、改云端技能报冲突、同名冲突、脚本待审、 +布局拒绝、删除不传播全流程)。 + +## 技能管理(内置) + +自 0.4.0 起,常用的本地管理也长在插件里,页面在 `/cloud-memory/skills` +(配置页有链接进入): + +- **列表**:本机全部技能,标注来源(云端交付 / 本地已传云端 / 本地) + 与云端修订号; +- **启停**:停用是把技能文件夹挪到 `$DSH_HOME/skills-disabled/` 暂存 + ——DSH 看不见它,自然不会加载;启用再挪回来。不碰 DSH 内部机制, + 可靠且可逆。同步引擎认识暂存区:停用的云端技能不会被拉回技能目 + 录,云端出了新版会在暂存区里原地更新; +- **删除**:真删,文件夹直接删除、不可恢复(页面上会先弹确认)。 + 只删本地:云端副本不动,删掉的同版本也不会被同步重新拉回来; +- **从 git 安装**:粘贴 https:// 或 file:// 仓库地址,浅克隆后把仓 + 库里所有带 `SKILL.md` 的文件夹装进技能目录;不执行仓库里的任何 + 代码,同名技能跳过不覆盖。 + +范围就到 DSH 技能目录这一处:技能市场的发现中心、扫描其它工具 +(Codex、Cursor 等)的技能目录不在内置范围——还需要那些的话继续 +留着第三方管理器,两边不冲突;不需要的话现在可以卸掉它了。 + +验证:`node verify-skill-admin.mjs`(列表与来源判定、启停、真删、 +git 安装与同名跳过、以及停用技能与同步引擎的配合共 15 项)。 + +## HTTP 接口 + +| 方法 | 路径 | 用途 | +| --- | --- | --- | +| 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` | 立即补发待重试队列 | + +写接口会校验同源 `Origin`,跨站请求返回 403。 + +## 状态语义 + +`TurnEndReason.kind` → 上报状态: + +| kind | status | 说明 | +| --- | --- | --- | +| `completed` | `completed` | 正常结束;只有它计入热力图 | +| `aborted` / `interrupted` / `blocked` | `cancelled` | 用户中断或被阻止 | +| `error` / `max-tokens` | `failed` | 出错或超长截断 | +| `forked` | 不上报 | fork 不算用户跑完的一轮,计入会让热力图虚高 | + +## 故障排查 + +- **热力图不涨**:看 `/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 位)。 + +## 开发与发布 + +```powershell +pnpm install # 首次 +pnpm run build # tsc -p tsconfig.build.json → lib/ +pnpm run typecheck + +node scripts/release-prep.mjs --dry-run # 先看会改什么 +node scripts/release-prep.mjs # 原地整备:脱敏 + 元数据 + LICENSE(幂等) +node scripts/pack-guard.mjs # 白名单与脱敏闸门,不通过直接 exit 1 +pnpm publish --access public --no-git-checks +``` + +`prepack` 会先重建 `lib/`,`prepublishOnly` 会先跑 `pack-guard`:包里一旦出现 `AGENTS.md`、`TODO.md`、`*.mjs` 探测脚本、`tsconfig*.json`、本机路径、个人域名或令牌原文,发布立刻中止。 + +> lifecycle 脚本要求 `node` 在 `PATH` 里。若报 `'node' is not recognized`,先把 DSH 运行时自带 node 的 `bin` 目录加进 `$env:Path` 再发布。 diff --git a/client/index.js b/client/index.js new file mode 100644 index 0000000..2869413 --- /dev/null +++ b/client/index.js @@ -0,0 +1,846 @@ +// dsh-cloud-memory client bundle. +// +// Hand-written on purpose: the host loads this file through `require` shims it +// provides itself (react / react/jsx-runtime), so no bundler is involved. The +// module wrapper below is the contract the web loader expects — `id` has to +// match the package name, otherwise the module graph registers a second copy. +window.__ModuleLoader__.load({ + id: 'dsh-cloud-memory', + factory: (require) => { + var module = { exports: {} } + var exports = module.exports + + 'use strict' + + var React = require('react') + var h = React.createElement + + var STATUS_URL = '/cloud-memory/status' + var CONFIG_URL = '/cloud-memory/config' + var LOGIN_URL = '/cloud-memory/login' + var TEST_URL = '/cloud-memory/test' + var FLUSH_URL = '/cloud-memory/flush' + var POLL_MS = 10000 + + var inject = ['slots'] + + 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 } + }, + ) + }) + } + + function messageOf(error) { + if (error === null || error === undefined) return '未知错误' + if (typeof error === 'string') return error + return typeof error.message === 'string' ? error.message : String(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. + function statusText(status) { + if (status === 404 || status === 405) { + return '插件后端还没加载这个接口(HTTP ' + String(status) + '):请完全退出并重启 DSH 后再试。' + } + return 'HTTP ' + String(status) + } + + function pickSettings(settings) { + return { + enabled: settings.enabled === true, + baseUrl: String(settings.baseUrl === undefined ? '' : settings.baseUrl), + clientId: String(settings.clientId === undefined ? '' : settings.clientId), + requestTimeoutMs: String(settings.requestTimeoutMs === undefined ? 8000 : settings.requestTimeoutMs), + defaultK: String(settings.defaultK === undefined ? 10 : settings.defaultK), + } + } + + 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()) + } + + var OUTCOME_LABELS = { + recorded: '已上报', + duplicate: '重复忽略', + failed: '失败', + queued: '待重试', + skipped: '已跳过', + } + + var OUTCOME_TONES = { + recorded: 'ok', + duplicate: 'muted', + failed: 'bad', + queued: 'warn', + skipped: 'muted', + } + + var styles = { + root: { + display: 'flex', + flexDirection: 'column', + gap: '18px', + padding: '4px 2px 20px', + fontSize: '13px', + lineHeight: 1.55, + }, + section: { + display: 'flex', + flexDirection: 'column', + gap: '10px', + border: '1px solid rgba(127,127,127,0.28)', + borderRadius: '10px', + padding: '14px 16px', + }, + sectionTitle: { + margin: 0, + fontSize: '13px', + fontWeight: 600, + letterSpacing: '0.02em', + }, + hint: { + margin: 0, + fontSize: '12px', + opacity: 0.65, + }, + grid: { + display: 'flex', + flexWrap: 'wrap', + gap: '12px 18px', + }, + field: { + display: 'flex', + flexDirection: 'column', + gap: '4px', + flex: '1 1 220px', + minWidth: '180px', + }, + label: { + fontSize: '12px', + opacity: 0.75, + }, + input: { + font: 'inherit', + fontSize: '13px', + padding: '6px 9px', + borderRadius: '7px', + border: '1px solid rgba(127,127,127,0.4)', + background: 'transparent', + color: 'inherit', + minWidth: 0, + }, + checkboxRow: { + display: 'flex', + alignItems: 'center', + gap: '8px', + }, + actions: { + display: 'flex', + gap: '10px', + flexWrap: 'wrap', + alignItems: 'center', + }, + button: { + font: 'inherit', + fontSize: '13px', + padding: '6px 16px', + borderRadius: '8px', + border: '1px solid rgba(127,127,127,0.45)', + background: 'transparent', + color: 'inherit', + cursor: 'pointer', + }, + buttonPrimary: { + font: 'inherit', + fontSize: '13px', + padding: '6px 16px', + borderRadius: '8px', + border: '1px solid rgba(37,99,235,0.6)', + background: 'rgba(37,99,235,0.16)', + color: 'inherit', + cursor: 'pointer', + }, + pills: { + display: 'flex', + flexWrap: 'wrap', + gap: '8px', + }, + pill: { + display: 'inline-flex', + alignItems: 'center', + gap: '6px', + padding: '3px 10px', + borderRadius: '999px', + border: '1px solid rgba(127,127,127,0.35)', + fontSize: '12px', + }, + table: { + width: '100%', + borderCollapse: 'collapse', + fontSize: '12px', + }, + th: { + textAlign: 'left', + fontWeight: 600, + padding: '4px 8px 4px 0', + borderBottom: '1px solid rgba(127,127,127,0.28)', + whiteSpace: 'nowrap', + }, + td: { + padding: '4px 8px 4px 0', + borderBottom: '1px solid rgba(127,127,127,0.14)', + verticalAlign: 'top', + }, + mono: { + fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', + fontSize: '11.5px', + wordBreak: 'break-all', + }, + ok: { borderColor: 'rgba(22,163,74,0.55)', background: 'rgba(22,163,74,0.12)' }, + bad: { borderColor: 'rgba(220,38,38,0.55)', background: 'rgba(220,38,38,0.12)' }, + warn: { borderColor: 'rgba(217,119,6,0.55)', background: 'rgba(217,119,6,0.12)' }, + muted: {}, + banner: { + padding: '8px 12px', + borderRadius: '8px', + fontSize: '12.5px', + }, + } + + 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)), + ) + } + + 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), + ) + } + + function CloudMemorySettingsCard() { + var snapshotState = React.useState(null) + var snapshot = snapshotState[0] + var setSnapshot = snapshotState[1] + + var draftState = React.useState(null) + var draft = draftState[0] + var setDraft = draftState[1] + + var tokenState = React.useState({ activity: '', memory: '' }) + var tokenDraft = tokenState[0] + var setTokenDraft = tokenState[1] + + var loginState = React.useState({ username: '', password: '' }) + var loginDraft = loginState[0] + var setLoginDraft = loginState[1] + + var loginResultState = React.useState(null) + var loginResult = loginResultState[0] + var setLoginResult = loginResultState[1] + + var errorState = React.useState(null) + var error = errorState[0] + var setError = errorState[1] + + var noticeState = React.useState(null) + var notice = noticeState[0] + var setNotice = noticeState[1] + + var testState = React.useState(null) + var testResult = testState[0] + var setTestResult = testState[1] + + var busyState = React.useState('') + var busy = busyState[0] + var setBusy = busyState[1] + + var load = React.useCallback( + function (keepDraft) { + request(STATUS_URL) + .then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + setError('读取插件状态失败(HTTP ' + String(result.status) + '),请重启 DSH 后再试。') + return + } + setError(null) + setSnapshot(result.body) + if (keepDraft !== true) setDraft(pickSettings(result.body.settings)) + }) + .catch(function (failure) { + setError('无法连接插件:' + messageOf(failure)) + }) + }, + [setDraft, setError, setSnapshot], + ) + + React.useEffect( + function () { + load(false) + var timer = setInterval(function () { + if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return + load(true) + }, POLL_MS) + return function () { + clearInterval(timer) + } + }, + [load], + ) + + function patchDraft(patch) { + setDraft(function (previous) { + return Object.assign({}, previous, patch) + }) + } + + function run(label, task) { + setBusy(label) + setNotice(null) + return Promise.resolve() + .then(task) + .catch(function (failure) { + setNotice({ tone: 'bad', text: messageOf(failure) }) + }) + .then(function () { + setBusy('') + }) + } + + function save() { + return run('save', function () { + var payload = { + enabled: draft.enabled, + baseUrl: draft.baseUrl, + clientId: draft.clientId, + requestTimeoutMs: Number(draft.requestTimeoutMs), + defaultK: Number(draft.defaultK), + } + if (tokenDraft.activity.trim() !== '') payload.activityToken = tokenDraft.activity.trim() + if (tokenDraft.memory.trim() !== '') payload.memoryToken = tokenDraft.memory.trim() + return request(CONFIG_URL, { method: 'PUT', body: JSON.stringify(payload) }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + var reason = result.body !== null && typeof result.body.error === 'string' ? result.body.error : statusText(result.status) + throw new Error('保存失败:' + reason) + } + setTokenDraft({ activity: '', memory: '' }) + setNotice({ tone: 'ok', text: '已保存到本机配置文件。' }) + load(false) + }) + }) + } + + function clearToken(which) { + return run('clear-' + which, function () { + var payload = which === 'activity' ? { clearActivityToken: true } : { clearMemoryToken: true } + return request(CONFIG_URL, { method: 'PUT', body: JSON.stringify(payload) }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + throw new Error('清除令牌失败(HTTP ' + String(result.status) + ')') + } + setNotice({ tone: 'ok', text: '令牌已清除。' }) + load(false) + }) + }) + } + + function test() { + return run('test', function () { + setTestResult(null) + return request(TEST_URL, { method: 'POST', body: '{}' }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + throw new Error('测试失败(HTTP ' + String(result.status) + ')') + } + setTestResult(result.body) + }) + }) + } + + function flush() { + return run('flush', function () { + return request(FLUSH_URL, { method: 'POST', body: '{}' }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + throw new Error('重试失败(HTTP ' + String(result.status) + ')') + } + setNotice({ tone: 'ok', text: '已重试 ' + String(result.body.sent) + ' 条,剩余 ' + String(result.body.remaining) + ' 条。' }) + load(true) + }) + }) + } + + function login() { + return run('login', function () { + setLoginResult(null) + var payload = { username: loginDraft.username.trim(), password: loginDraft.password } + if (payload.username === '' || payload.password === '') { + throw new Error('请填写用户名和密码') + } + return request(LOGIN_URL, { method: 'POST', body: JSON.stringify(payload) }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + var reason = result.body !== null && typeof result.body.error === 'string' ? result.body.error : statusText(result.status) + throw new Error('登录失败:' + reason) + } + // Drop the password the moment the exchange succeeded. + setLoginDraft({ username: payload.username, password: '' }) + setLoginResult(result.body.login || null) + setNotice({ + tone: result.body.login !== null && result.body.login !== undefined && result.body.login.partial === true ? 'warn' : 'ok', + text: '登录成功,已自动写入两个令牌。', + }) + setSnapshot(result.body) + setDraft(pickSettings(result.body.settings)) + }) + }) + } + + if (error !== null && snapshot === null) { + return h( + 'div', + { style: styles.root }, + h('div', { style: Object.assign({}, styles.banner, styles.bad) }, error), + h( + 'div', + { style: styles.actions }, + h( + 'button', + { + style: styles.button, + onClick: function () { + load(false) + }, + }, + '重新加载', + ), + ), + ) + } + + if (snapshot === null || draft === null) { + return h('div', { style: styles.root }, h('p', { style: styles.hint }, '正在读取云端记忆插件状态…')) + } + + var reporter = snapshot.reporter === undefined ? {} : snapshot.reporter + var tokens = snapshot.tokens === undefined ? { activity: {}, memory: {} } : snapshot.tokens + var recent = Array.isArray(reporter.recent) ? reporter.recent.slice(0, 6) : [] + var activityToken = tokens.activity === undefined ? {} : tokens.activity + var memoryToken = tokens.memory === undefined ? {} : tokens.memory + + var banner = null + if (notice !== null) { + banner = h('div', { style: Object.assign({}, styles.banner, styles[notice.tone]) }, notice.text) + } + + var testBox = null + if (testResult !== null) { + var activityTest = testResult.activity === undefined ? {} : testResult.activity + var memoryTest = testResult.memory === undefined ? {} : testResult.memory + testBox = h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '6px' } }, + h( + 'div', + { style: Object.assign({}, styles.banner, activityTest.ok === true ? styles.ok : styles.bad) }, + '活动上报权限:' + (activityTest.ok === true ? '可用 — ' : '不可用 — ') + String(activityTest.message === undefined ? '' : activityTest.message), + ), + h( + 'div', + { style: Object.assign({}, styles.banner, memoryTest.ok === true ? styles.ok : styles.bad) }, + '记忆读写权限:' + (memoryTest.ok === true ? '可用 — ' : '不可用 — ') + String(memoryTest.message === undefined ? '' : memoryTest.message), + ), + ) + } + + return h( + 'div', + { style: styles.root }, + + h( + 'div', + { style: styles.pills }, + h(Pill, { label: '已上报', value: reporter.recorded === undefined ? 0 : reporter.recorded, tone: 'ok' }), + h(Pill, { label: '重复忽略', value: reporter.duplicate === undefined ? 0 : reporter.duplicate, tone: 'muted' }), + h(Pill, { label: '失败', value: reporter.failed === undefined ? 0 : reporter.failed, tone: 'bad' }), + h(Pill, { label: '待重试', value: reporter.queued === undefined ? 0 : reporter.queued, tone: 'warn' }), + h(Pill, { label: '已跳过', value: reporter.skipped === undefined ? 0 : reporter.skipped, tone: 'muted' }), + ), + + activityToken.configured !== true && memoryToken.configured !== true + ? h( + 'div', + { style: Object.assign({}, styles.banner, styles.warn) }, + '还没有配置令牌。先到云端面板「设置 → API 密钥」各建一个 activity:write 与 memory:write 密钥,把两个都粘到下面「访问令牌」两栏,再点「保存」。', + ) + : null, + + banner, + + h( + 'div', + { style: styles.section }, + h('h4', { style: styles.sectionTitle }, '连接'), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '服务地址', + value: draft.baseUrl, + onChange: function (value) { + patchDraft({ baseUrl: value }) + }, + hint: '留空或写错时会退回默认地址。', + }), + h(Field, { + label: '客户端标识(client_id)', + value: draft.clientId, + onChange: function (value) { + patchDraft({ clientId: value }) + }, + }), + h(Field, { + label: '请求超时(毫秒)', + type: 'number', + value: draft.requestTimeoutMs, + onChange: function (value) { + patchDraft({ requestTimeoutMs: value }) + }, + }), + h(Field, { + label: '默认检索条数', + type: 'number', + value: draft.defaultK, + onChange: function (value) { + patchDraft({ defaultK: value }) + }, + }), + ), + h( + 'div', + { style: styles.checkboxRow }, + h('input', { + type: 'checkbox', + checked: draft.enabled, + id: 'dsh-cloud-memory-enabled', + onChange: function (event) { + patchDraft({ enabled: event.target.checked }) + }, + }), + h('label', { htmlFor: 'dsh-cloud-memory-enabled', style: styles.label }, '启用每轮活动上报(只上报时间戳、会话 id 与状态,不上传对话内容)'), + ), + ), + + h( + 'div', + { style: styles.section }, + h('h4', { style: styles.sectionTitle }, '账号登录(推荐)'), + h( + 'p', + { style: styles.hint }, + '用云端面板的普通用户账号登录,插件会用一次性会话换取 activity:write 与 memory:write 两个令牌并写入本机。密码只在这一次请求里使用:不保存、不写日志、不回显,换取成功后立即从内存丢弃。', + ), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '用户名', + value: loginDraft.username, + placeholder: '云端面板的账号', + onChange: function (value) { + setLoginDraft(function (previous) { + return Object.assign({}, previous, { username: value }) + }) + }, + }), + h(Field, { + label: '密码', + type: 'password', + value: loginDraft.password, + placeholder: '只用于本次换取令牌', + onChange: function (value) { + setLoginDraft(function (previous) { + return Object.assign({}, previous, { password: value }) + }) + }, + hint: '成功后自动清空', + }), + ), + h( + 'div', + { style: styles.actions }, + h( + 'button', + { + style: styles.buttonPrimary, + disabled: busy !== '', + onClick: function () { + login() + }, + }, + busy === 'login' ? '登录中…' : '登录并获取令牌', + ), + loginResult === null + ? null + : h( + 'span', + { style: styles.hint }, + '已登录:' + + String(loginResult.user !== null && loginResult.user !== undefined && loginResult.user.username !== undefined ? loginResult.user.username : '未知账号') + + (loginResult.warning === undefined || loginResult.warning === null ? '' : '(' + String(loginResult.warning) + ')'), + ), + ), + ), + + h( + 'div', + { style: styles.section }, + h('h4', { style: styles.sectionTitle }, '访问令牌'), + h( + 'p', + { style: styles.hint }, + '两个令牌各有独立权限:activity:write 只用于上报,memory:write 同时允许检索与写入。令牌只写入本机 ' + + String(snapshot.settingsPath === undefined ? '配置文件' : snapshot.settingsPath) + + ',不会进入会话上下文。', + ), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '活动上报令牌(activity:write)', + type: 'password', + value: tokenDraft.activity, + placeholder: activityToken.configured === true ? '已配置 ' + String(activityToken.masked) + ',留空表示不修改' : '未配置', + onChange: function (value) { + setTokenDraft(function (previous) { + return Object.assign({}, previous, { activity: value }) + }) + }, + hint: activityToken.configured === true ? '当前:' + String(activityToken.masked) : undefined, + }), + h(Field, { + label: '记忆读写令牌(memory:write)', + type: 'password', + value: tokenDraft.memory, + placeholder: memoryToken.configured === true ? '已配置 ' + String(memoryToken.masked) + ',留空表示不修改' : '未配置', + onChange: function (value) { + setTokenDraft(function (previous) { + return Object.assign({}, previous, { memory: value }) + }) + }, + hint: memoryToken.configured === true ? '当前:' + String(memoryToken.masked) : undefined, + }), + ), + h( + 'div', + { style: styles.actions }, + h( + 'button', + { + style: styles.button, + disabled: activityToken.configured !== true, + onClick: function () { + clearToken('activity') + }, + }, + '清除上报令牌', + ), + h( + 'button', + { + style: styles.button, + disabled: memoryToken.configured !== true, + onClick: function () { + clearToken('memory') + }, + }, + '清除记忆令牌', + ), + ), + ), + + h( + 'div', + { style: styles.actions }, + h( + 'button', + { + style: styles.buttonPrimary, + disabled: busy !== '', + onClick: function () { + save() + }, + }, + busy === 'save' ? '保存中…' : '保存', + ), + h( + 'button', + { + style: styles.button, + disabled: busy !== '', + onClick: function () { + test() + }, + }, + busy === 'test' ? '测试中…' : '测试连接', + ), + h( + 'button', + { + style: styles.button, + disabled: busy !== '' || reporter.queued === undefined || reporter.queued === 0, + onClick: function () { + flush() + }, + }, + '重试上报队列', + ), + ), + + testBox, + + h( + 'div', + { style: styles.section }, + h('h4', { style: styles.sectionTitle }, '最近上报'), + recent.length === 0 + ? h('p', { style: styles.hint }, '还没有记录。发一条消息让它跑完一轮,这里就会出现一条。') + : h( + 'table', + { style: styles.table }, + h( + 'thead', + null, + h( + 'tr', + null, + h('th', { style: styles.th }, '时间'), + h('th', { style: styles.th }, '结果'), + h('th', { style: styles.th }, '状态'), + h('th', { style: styles.th }, 'turn_id'), + ), + ), + h( + 'tbody', + null, + recent.map(function (row, index) { + var outcome = String(row.outcome === undefined ? '' : row.outcome) + return h( + 'tr', + { key: String(row.turnId) + ':' + String(index) }, + h('td', { style: styles.td }, formatTime(row.at)), + h( + 'td', + { style: styles.td }, + h( + 'span', + { style: Object.assign({}, styles.pill, styles[OUTCOME_TONES[outcome]] === undefined ? styles.muted : styles[OUTCOME_TONES[outcome]]) }, + OUTCOME_LABELS[outcome] === undefined ? outcome : OUTCOME_LABELS[outcome], + ), + ), + h('td', { style: styles.td }, String(row.status === undefined ? '' : row.status)), + h('td', { style: Object.assign({}, styles.td, styles.mono) }, String(row.turnId === undefined ? '' : row.turnId)), + ) + }), + ), + ), + reporter.lastError === undefined + ? null + : h('p', { style: styles.hint }, '最近一次错误:' + String(reporter.lastError)), + ), + + h('p', { style: styles.hint }, '配置保存在 ' + String(snapshot.settingsPath === undefined ? '本机配置文件' : snapshot.settingsPath) + ',页面地址 /cloud-memory 仍然可用。'), + ) + } + + // A thrown render error must not take the settings page down with it, so the + // card is wrapped in a minimal boundary that renders the message instead. + 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 }, '插件本身仍在运行,可改用 /cloud-memory 页面配置。'), + ) + } + return this.props.children + } + + function apply(ctx) { + var card = function () { + return h(CardBoundary, null, h(CloudMemorySettingsCard, null)) + } + + var register = function (seat, options) { + try { + ctx.slots.inject(seat, function () { + return ctx.slots.register(options, card) + }) + } catch (failure) { + if (typeof console !== 'undefined') console.warn('[dsh-cloud-memory] slot ' + seat + ' unavailable: ' + messageOf(failure)) + } + } + + register('settings.section', { + name: 'settings.section', + id: 'cloud-memory', + order: 100, + label: function () { + return '云端记忆' + }, + }) + + register('plugins.bundle.config', { name: 'plugins.bundle.config', key: 'dsh-cloud-memory' }) + } + + module.exports = { apply: apply, inject: inject, name: 'dsh-cloud-memory' } + return module.exports + }, +}) diff --git a/cordis.patch.yml b/cordis.patch.yml new file mode 100644 index 0000000..6136309 --- /dev/null +++ b/cordis.patch.yml @@ -0,0 +1,13 @@ +# cloud-memory bundle patch +# +# Local-only build: this package is never published, so the row below is 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. +- insert: + - id: cloud-memory + name: 'dsh-cloud-memory' + config: + enabled: true + baseUrl: https://your-memory-host/api/longmemory + clientId: dsh-desktop + skillsSyncEnabled: true diff --git a/docs/source-provenance.md b/docs/source-provenance.md new file mode 100644 index 0000000..4d03743 --- /dev/null +++ b/docs/source-provenance.md @@ -0,0 +1,8 @@ +# Source provenance / 源码来源 + +- 上游项目:`newbieQQ/dsh-cloud-memory`(GitHub) +- 本工作树基线:npm 包 `dsh-cloud-memory@0.4.1`,上游 main 提交 `1865a82a274c1b2aecd8ebf8abbe787124a409e2` +- 取得方式:GitHub 已认证 API 归档解包,**不是** `git clone`;因此本仓库没有上游提交历史。 +- 基线提交:`vendor: dsh-cloud-memory 0.4.1 baseline (upstream 1865a82)` —— 该提交内容逐字节等于上述归档内容(仅追加本文件与 .gitignore 条目)。 +- 追加的构建支持:`../node_modules` 是指向本地开发依赖(typescript / @types / @deepseek-ai 类型)的 junction,仅用于 `tsc`,不进版本库,也不是运行时依赖。 +- 后续每一处本地差异都以独立提交记录,`git log --oneline vendor..main` 即本地改动清单。 diff --git a/lib/api.js b/lib/api.js new file mode 100644 index 0000000..1d7a498 --- /dev/null +++ b/lib/api.js @@ -0,0 +1,300 @@ +/** + * Derive the dashboard auth root (`/api/auth`) from the memory base URL + * (`.../api/longmemory`): login and token minting live one segment over. + */ +function authBase(baseUrl) { + try { + const url = new URL(baseUrl); + const prefix = url.pathname.replace(/\/longmemory\/?$/i, ''); + return `${url.origin}${prefix}/auth`; + } + catch { + return ''; + } +} +/** True when sending a password to this URL is safe (TLS, or loopback). */ +export function isSecureLoginTarget(baseUrl) { + try { + const url = new URL(baseUrl); + if (url.protocol === 'https:') + return true; + return url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname); + } + catch { + return false; + } +} +/** Pull the first cookie pair out of one or more Set-Cookie headers. */ +function sessionCookieOf(headers) { + // `getSetCookie` exists on undici/Node 18.14+ but is not in every Headers type. + const withCookies = headers; + const list = typeof withCookies.getSetCookie === 'function' ? withCookies.getSetCookie() : [headers.get('set-cookie') ?? '']; + for (const entry of list) { + if (entry === '') + continue; + const pair = entry.split(';', 1)[0]; + if (pair !== undefined && pair.includes('=') && !pair.startsWith('=')) + return pair.trim(); + } + return ''; +} +/** Map one HTTP error body onto a {@link CloudError}. */ +function errorFromBody(status, raw, retryAfterHeader) { + let code = `http_${status}`; + let message = raw.slice(0, 300); + try { + const parsed = JSON.parse(raw); + if (parsed !== null && typeof parsed === 'object') { + const body = parsed; + if (typeof body.error === 'string') + code = body.error; + else if (body.error !== null && typeof body.error === 'object') { + const nested = body.error; + if (typeof nested.code === 'string') + code = nested.code; + if (typeof nested.message === 'string') + message = nested.message; + } + if (typeof body.message === 'string') + message = body.message; + } + } + catch { + // Non-JSON error (proxy HTML page, empty body): keep the text snippet. + } + const error = { status, code, message: message === '' ? code : message }; + if (status === 429) { + const header = retryAfterHeader === null ? Number.NaN : Number(retryAfterHeader); + error.retryAfterMs = Number.isFinite(header) && header > 0 ? header * 1000 : 900_000; + } + return error; +} +/** + * One cloud endpoint handle. Instances are cheap: construct per call site and + * keep the live settings behind closures so a settings edit applies at once. + */ +export class CloudClient { + options; + constructor(options) { + this.options = options; + } + async request(method, path, body, tokenOverride) { + const token = tokenOverride ?? this.options.token(); + const base = this.options.baseUrl(); + const url = `${base}${path}`; + const headers = { Accept: 'application/json' }; + if (token !== '') + headers.Authorization = `Bearer ${token}`; + const init = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) }; + if (body !== undefined) { + headers['Content-Type'] = 'application/json'; + init.body = JSON.stringify(body); + } + let response; + try { + response = await fetch(url, init); + } + catch (error) { + 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(() => ''); + if (!response.ok) { + return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) }; + } + if (text.trim() === '') + return { ok: true, status: response.status, data: {} }; + try { + return { ok: true, status: response.status, data: JSON.parse(text) }; + } + catch { + return { ok: false, error: { status: response.status, code: 'invalid_json', message: 'response was not JSON' } }; + } + } + /** Report one conversation turn (activity:write token). */ + reportTurn(payload, token) { + return this.request('POST', '/activity/turn', payload, token); + } + /** Stage one turn summary as pending proposals (summary:write token). */ + submitSummary(payload, token) { + return this.request('POST', '/activity/summary', payload, token); + } + /** + * Verify a summary token without staging anything. + * + * The endpoint authenticates before it validates the body, so an empty + * object coming back `400 invalid_input` proves the scope is right. + */ + async probeSummary(token) { + const result = await this.request('POST', '/activity/summary', {}, token); + if (result.ok) + return { ok: true, status: result.status, data: { authenticated: true } }; + if (result.error.status === 400) + return { ok: true, status: 400, data: { authenticated: true } }; + return { ok: false, error: result.error }; + } + /** + * Verify an activity token without recording anything. + * + * `/activity/turn` validates auth before the payload, so an empty body that + * comes back `400 invalid_event` proves the token carries `activity:write`. + * A 401/403 is a token problem; anything else is reported verbatim. + */ + async probeActivity(token) { + const result = await this.request('POST', '/activity/turn', {}, token); + if (result.ok) + return { ok: true, status: result.status, data: { authenticated: true } }; + // 400 means the credentials were accepted and only the body was rejected. + if (result.error.status === 400) { + return { ok: true, status: 400, data: { authenticated: true } }; + } + return { ok: false, error: result.error }; + } + /** Keyword search over stored memories (memory token). */ + async search(query, k, project) { + const body = { query, k }; + if (project !== undefined && project !== '') + body.filters = { project_id: project }; + return this.request('POST', '/memory/query', body); + } + /** Read one memory by id (memory token). */ + read(id) { + return this.request('GET', `/memory/${encodeURIComponent(id)}`); + } + /** List memories with optional paging filters (memory token). */ + list(options = {}) { + const params = new URLSearchParams(); + if (options.limit !== undefined) + params.set('limit', String(options.limit)); + if (options.offset !== undefined) + params.set('offset', String(options.offset)); + if (options.project !== undefined && options.project !== '') + params.set('project_id', options.project); + const suffix = params.toString() === '' ? '' : `?${params.toString()}`; + return this.request('GET', `/memory/all${suffix}`); + } + /** Store one memory; `operationId` makes the write idempotent (memory token). */ + add(input) { + const body = { + operation_id: input.operationId, + content: input.content, + }; + if (input.tags !== undefined && input.tags.length > 0) + body.tags = input.tags; + if (input.project !== undefined && input.project !== '') + body.project_id = input.project; + if (input.sector !== undefined && input.sector !== '') + body.metadata = { primary_sector: input.sector }; + return this.request('POST', '/memory/add', body); + } + /** List the account's projects (memory token). */ + projects() { + return this.request('GET', '/dashboard/projects'); + } + /** Storage configuration state (memory token). */ + storageStatus() { + return this.request('GET', '/storage/status'); + } + /** List the cloud skill center inventory (memory token). */ + listSkills() { + return this.request('GET', '/skills'); + } + /** Fetch one skill bundle with hashed, base64-carried files (memory token). */ + skillBundle(name) { + return this.request('GET', `/skills/${encodeURIComponent(name)}/bundle`); + } + /** Create one skill in the center; `expected_revision` must be 0 (memory token). */ + createSkill(body) { + return this.request('POST', '/skills', body); + } + /** Replace one skill's files/description at an expected revision (memory token). */ + updateSkill(name, body) { + return this.request('PATCH', `/skills/${encodeURIComponent(name)}`, body); + } + /** + * One call against the dashboard auth surface (`/api/auth/*`). + * + * These endpoints authorize by session cookie, not by Bearer token, and they + * reject any non-GET without a matching `Origin` (the server's CSRF gate), so + * 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(); + const base = authBase(baseUrl); + if (base === '') + return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }; + const headers = { Accept: 'application/json' }; + try { + headers.Origin = new URL(baseUrl).origin; + } + catch { + return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }; + } + if (cookie !== undefined && cookie !== '') + headers.Cookie = cookie; + const init = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) }; + if (body !== undefined) { + headers['Content-Type'] = 'application/json'; + init.body = JSON.stringify(body); + } + let response; + try { + response = await fetch(`${base}${path}`, init); + } + catch (error) { + 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(() => ''); + if (!response.ok) { + return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) }; + } + let parsed = {}; + if (text.trim() !== '') { + try { + parsed = JSON.parse(text); + } + catch { + parsed = {}; + } + } + return { ok: true, status: response.status, body: parsed, headers: response.headers }; + } + /** + * Password login against the dashboard. + * + * The password is used once, in this call, and never stored: what comes back + * 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 }); + 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 } }; + } + /** 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); + 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: '服务端没有返回令牌' } }; + } + return { ok: true, status: sent.status, data: issued }; + } +} +/** Render a {@link CloudError} as one display line. */ +export function describeError(error) { + if (error.status === 0) + return `网络不可用:${error.message}`; + return `HTTP ${error.status} ${error.code}:${error.message}`; +} diff --git a/lib/config.js b/lib/config.js new file mode 100644 index 0000000..7c10f75 --- /dev/null +++ b/lib/config.js @@ -0,0 +1,82 @@ +/** + * Settings model: the cordis row config supplies defaults, the user-editable + * sidecar (`$DSH_HOME/cloud-memory.json`) overrides them, and secrets live ONLY + * in the sidecar. Nothing here ever reaches the conversation or a model context. + */ +/** Defaults written into cordis.patch.yml; also the fallback for missing keys. */ +export const DEFAULT_SETTINGS = { + enabled: true, + baseUrl: 'https://mem.qyhhh.top/api/longmemory', + clientId: 'dsh-desktop', + requestTimeoutMs: 5000, + defaultK: 10, + summaryEnabled: true, + summaryMaxChars: 6000, + skillsSyncEnabled: true, + skillsDir: '', +}; +const MIN_TIMEOUT_MS = 1000; +const MAX_TIMEOUT_MS = 60_000; +/** Trim truncation guard for the free-form identifiers. */ +function shortString(value) { + if (typeof value !== 'string') + return undefined; + const trimmed = value.trim(); + if (trimmed === '') + return undefined; + return trimmed.slice(0, 128); +} +/** + * Normalize a base URL: require http(s), drop trailing slashes and any query. + * Returns undefined when the input is unusable, so callers can fall back. + */ +export function normalizeBaseUrl(value) { + if (typeof value !== 'string' || value.trim() === '') + return undefined; + try { + const url = new URL(value.trim()); + if (url.protocol !== 'http:' && url.protocol !== 'https:') + return undefined; + return `${url.origin}${url.pathname.replace(/\/+$/, '')}`; + } + catch { + return undefined; + } +} +/** Clamp a numeric config value into an integer range, else undefined. */ +function boundedInt(value, min, max) { + if (typeof value !== 'number' || !Number.isFinite(value)) + return undefined; + return Math.min(max, Math.max(min, Math.round(value))); +} +/** Extract the recognized settings from an untrusted row config object. */ +export function settingsFromConfig(raw) { + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) + return {}; + const source = raw; + const result = {}; + if (typeof source.enabled === 'boolean') + result.enabled = source.enabled; + const baseUrl = normalizeBaseUrl(source.baseUrl); + if (baseUrl !== undefined) + result.baseUrl = baseUrl; + const clientId = shortString(source.clientId); + if (clientId !== undefined) + result.clientId = clientId; + const timeout = boundedInt(source.requestTimeoutMs, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS); + if (timeout !== undefined) + result.requestTimeoutMs = timeout; + const defaultK = boundedInt(source.defaultK, 1, 100); + if (defaultK !== undefined) + result.defaultK = defaultK; + if (typeof source.summaryEnabled === 'boolean') + result.summaryEnabled = source.summaryEnabled; + const summaryMaxChars = boundedInt(source.summaryMaxChars, 1000, 16_000); + if (summaryMaxChars !== undefined) + result.summaryMaxChars = summaryMaxChars; + if (typeof source.skillsSyncEnabled === 'boolean') + result.skillsSyncEnabled = source.skillsSyncEnabled; + if (typeof source.skillsDir === 'string') + result.skillsDir = source.skillsDir.trim().slice(0, 512); + return result; +} diff --git a/lib/context-types.js b/lib/context-types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/lib/context-types.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..f88d5fb --- /dev/null +++ b/lib/index.js @@ -0,0 +1,136 @@ +/** + * 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 `/cloud-memory`. + * + * 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 { createRoutes } from "./routes.js"; +import { join } from 'node:path'; +import { SettingsStore, dshHome } from "./store.js"; +import { SkillSync } from "./skill-sync.js"; +import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js"; +import { createMemoryTools, createSkillTools } from "./tools.js"; +/** Package name; also the client bundle id. */ +export const name = 'dsh-cloud-memory'; +/** Services required before `apply` runs. */ +export const inject = ['webServer']; +/** Version reported by the status card. */ +const VERSION = '0.4.1'; +/** 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. */ +export function apply(ctx, config) { + const logger = ctx.logger('cloud-memory'); + 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: () => join(dshHome(), 'cloud-memory-skills.json'), + syncRunning: () => skillSync.stats().running, + log: (message) => logger.info(message), + }); + // 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 /cloud-memory`); + } + 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-cloud-memory: 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-cloud-memory: 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 }); + for (const route of routes) { + ctx.effect(() => webServer.register(route), `dsh-cloud-memory: 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-cloud-memory: 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-cloud-memory: skill sync timer'); +} diff --git a/lib/mnemon/descriptor.js b/lib/mnemon/descriptor.js new file mode 100644 index 0000000..4c1858e --- /dev/null +++ b/lib/mnemon/descriptor.js @@ -0,0 +1,60 @@ +/** + * Browser-safe metadata for the LongMemory Provider. + * + * The Provider is the Mnemon face of this package: Mnemon keeps the hot, + * per-turn presence local, while every long-term read and write passes + * through to the user's own LongMemory service in real time. The cloud + * store is the source of truth — nothing long-term is mirrored locally. + */ +export const descriptor = { + id: 'longmemory', + label: 'LongMemory', + icon: { + kind: 'glyph', + value: '☁', + }, + kind: 'remote', + workspaceBinding: 'provider-global', + summary: 'Your self-hosted LongMemory service as a live memory space: reads and writes pass through in real time, nothing is mirrored locally.', + origin: 'third-party', + capabilities: { + search: true, + browse: true, + graph: false, + entities: false, + related: false, + remember: true, + link: false, + forget: false, + writeMode: 'exact', + deletionMode: 'unsupported', + }, + fields: [ + { + key: 'endpoint', + label: 'Endpoint', + scope: 'service', + input: 'url', + required: false, + placeholder: 'https://mem.example.com/api/longmemory', + help: 'LongMemory base URL. Leave empty to reuse the dsh-cloud-memory settings (cloud-memory.json).', + normalize: 'trim-trailing-slash', + }, + { + key: 'token', + label: 'Memory token', + scope: 'service', + input: 'secret', + required: false, + help: 'Scoped memory token (memory:write). Leave empty to reuse the token already configured for dsh-cloud-memory.', + }, + { + key: 'projectId', + label: 'Project ID', + scope: 'memory', + input: 'text', + required: false, + help: 'LongMemory project this space maps to. Empty means the account-wide default scope.', + }, + ], +}; diff --git a/lib/mnemon/driver.js b/lib/mnemon/driver.js new file mode 100644 index 0000000..51a12e0 --- /dev/null +++ b/lib/mnemon/driver.js @@ -0,0 +1,223 @@ +/** + * LongMemory driver for Mnemon's Memory Spaces. + * + * Design rule (the whole point of this bridge): the cloud service is the + * source of truth. Every search/list/read/write is a live call to the + * user's own LongMemory endpoint — this driver keeps NO local replica of + * long-term memory, so anything another tool (Claude Code, Codex, the + * dashboard) wrote into LongMemory is visible inside DSH immediately. + * + * 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/cloud-memory.json`) + * for any of endpoint/token the Mnemon side left empty — so a user + * who already configured dsh-cloud-memory 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) { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) + return undefined; + const ms = value < 1e12 ? value * 1000 : value; + const date = new Date(ms); + return Number.isNaN(date.getTime()) ? undefined : date.toISOString(); +} +/** Map one LongMemory hit onto a Mnemon Insight; unusable hits drop out. */ +export function insightFromHit(hit) { + if (typeof hit.id !== 'string' || hit.id === '') + return undefined; + if (typeof hit.content !== 'string') + return undefined; + const insight = { id: hit.id, content: hit.content, source: 'external' }; + if (typeof hit.primary_sector === 'string' && hit.primary_sector !== '') { + insight.category = hit.primary_sector; + } + if (Array.isArray(hit.tags)) { + const tags = hit.tags.filter((tag) => typeof tag === 'string'); + if (tags.length > 0) + insight.tags = tags; + } + const createdAt = toIso(hit.created_at); + if (createdAt !== undefined) + insight.createdAt = createdAt; + const score = hit.score; + if (typeof score === 'number' && Number.isFinite(score)) + insight.score = score; + return insight; +} +export class LongMemoryProvider { + authority; + options; + id = descriptor.id; + /** LongMemory scores are its own scale; the host may only order by them. */ + scoreSemantics = { kind: 'provider-native' }; + store; + constructor(authority, options = {}) { + 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; + } + /** + * 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. + */ + resolve(body, direct) { + let connection = { ...(direct ?? {}) }; + if (body !== undefined) { + if (this.authority !== undefined) { + try { + connection = { ...this.authority.providerConnection(body.id, descriptor.id), ...connection }; + } + catch { + // Host could not resolve it; fall through to the space record. + } + } + const own = body.connection; + if (own !== null && typeof own === 'object' && !Array.isArray(own)) { + 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 + : undefined; + return { endpoint: endpointRaw.replace(/\/+$/, ''), header: token, ...(project === undefined ? {} : { project }) }; + } + /** 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, + }); + } + /** Enumerate the account's projects as Memory Spaces, plus the default scope. */ + async discover(connection, signal) { + signal?.throwIfAborted(); + const resolved = this.resolve(undefined, connection); + const result = await this.client(resolved).projects(); + if (!result.ok) { + throw new Error(`LongMemory project discovery failed: ${result.error.message}`); + } + const spaces = [{ + externalId: 'default', + name: 'LongMemory · 全部', + description: 'Account-wide default scope (no project filter).', + connection: {}, + }]; + for (const project of result.data.projects ?? []) { + if (typeof project.id !== 'string' || project.id === '') + continue; + spaces.push({ + externalId: `project:${project.id}`, + name: typeof project.name === 'string' && project.name !== '' ? project.name : project.id, + description: 'LongMemory project', + connection: { projectId: project.id }, + }); + } + return spaces; + } + /** Health = the service answers its storage status endpoint. */ + async status(body, signal) { + signal?.throwIfAborted(); + const resolved = this.resolve(body); + if (resolved.header === '') { + return { healthy: false, error: 'LongMemory memory token is not configured' }; + } + const result = await this.client(resolved).storageStatus(); + return result.ok + ? { healthy: true } + : { healthy: false, error: result.error.message }; + } + /** Live pass-through search — this is the recall path for every turn. */ + async search(body, request, signal) { + 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); + if (!result.ok) { + throw new Error(`LongMemory search failed: ${result.error.message}`); + } + return { + results: (result.data.matches ?? []) + .map(insightFromHit) + .filter((item) => item !== undefined), + }; + } + /** Browse the space; a query, when given, defers to live search. */ + async list(body, request, signal) { + signal?.throwIfAborted(); + if (request.query !== undefined && request.query !== '') { + const found = await this.search(body, { query: request.query, limit: request.limit ?? 100 }, signal); + return found.results; + } + 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 }); + if (!result.ok) { + throw new Error(`LongMemory list failed: ${result.error.message}`); + } + return (result.data.items ?? []) + .map(insightFromHit) + .filter((item) => item !== undefined); + } + /** Store one memory straight into the cloud store — no local staging. */ + async remember(body, request, signal) { + signal?.throwIfAborted(); + const resolved = this.resolve(body); + const result = await this.client(resolved).add({ + content: request.content, + ...(request.tags === undefined ? {} : { tags: request.tags }), + ...(resolved.project === undefined ? {} : { project: resolved.project }), + ...(request.category === undefined ? {} : { sector: request.category }), + operationId: `mnemon-${randomUUID()}`, + }); + if (!result.ok) { + throw new Error(`LongMemory remember failed: ${result.error.message}`); + } + return { + action: 'stored', + provider: this.id, + summary: 'Stored in LongMemory (live).', + ...(result.data.id === undefined ? {} : { id: result.data.id }), + ...(result.data.revision === undefined ? {} : { revision: result.data.revision }), + }; + } + /** Exact read of one memory by id. */ + async get(body, id, signal) { + signal?.throwIfAborted(); + const resolved = this.resolve(body); + const result = await this.client(resolved).read(id); + if (!result.ok) + return undefined; + return insightFromHit(result.data); + } + /** + * LongMemory's associations live server-side and this API exposes no + * graph read, so the honest v1 answer is an empty snapshot; the + * descriptor declares the graph capability off to match. + */ + async graph(body, signal) { + signal?.throwIfAborted(); + void body; + return { nodes: [], edges: [], generatedAt: new Date().toISOString() }; + } +} diff --git a/lib/mnemon/index.js b/lib/mnemon/index.js new file mode 100644 index 0000000..7f049a9 --- /dev/null +++ b/lib/mnemon/index.js @@ -0,0 +1,46 @@ +/** + * Mnemon Memory Spaces Provider entry for LongMemory. + * + * This module is NOT loaded by the dsh-cloud-memory bundle itself. Mnemon's + * Memory Spaces source mounts it as a child when the user adds it to the + * source's provider list: + * + * providers: + * - use: dsh-cloud-memory/mnemon-provider + * instanceId: longmemory + * + * 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 { descriptor } from "./descriptor.js"; +import { LongMemoryProvider } from "./driver.js"; +export { LongMemoryProvider, descriptor }; +/** Keep in sync with the package version (asserted by the verify script). */ +const PROVIDER_VERSION = '0.4.1'; +export const definition = defineMemorySpaceProviderDefinition({ + manifest: { + apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION, + kind: 'provider', + typeId: descriptor.id, + packageName: 'dsh-cloud-memory', + version: PROVIDER_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: 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 }), +}); +export default defineMemorySpaceProvider({ + id: descriptor.id, + apply(ctx, host) { + host.install(ctx, definition); + }, +}); diff --git a/lib/page.js b/lib/page.js new file mode 100644 index 0000000..e995f27 --- /dev/null +++ b/lib/page.js @@ -0,0 +1,429 @@ +/** + * 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 `/cloud-memory`. It is deliberately dependency-free: no + * bundler assets, no CDN, no fonts — one file the host web server can emit. + * + * The page renders tokens as masked values only; the plaintext never leaves + * `$DSH_HOME/cloud-memory.json`. + */ +/** Escape a value for safe interpolation into HTML text/attributes. */ +export function escapeHtml(value) { + return value + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); +} +/** Render the configuration page. */ +export function renderConfigPage(options) { + // The client script is plain ES2020 and avoids template literals so this + // outer template stays readable. + return ` + + + + +云端记忆 · DSH 插件 + + + +
+

云端记忆 · DSH 插件

+

v${escapeHtml(options.version)} · 每轮结束上报活动计数 · 提供 memory_search / memory_read / memory_add 工具

+

技能管理(列表 · 启停 · 安装)→

+ +
+

当前状态

+
+
加载中…
+
+ +
+

连接配置

+
+
+ + +
不带结尾斜杠,路径为 /api/longmemory。
+
+
+ + +
上报时附带,便于区分来源设备。
+
+
+ + +
+
+ + +
+
+
+ +
+
+ +
+
+ + +
+
+ +
+

账号登录

+
+
+ + +
+
+ + +
+
+
+ +
+
+ 用云端面板的普通用户账号登录,插件会用一次性会话换取 activity:write 与 memory:write 两个令牌并写入本机。 + 密码只在这一次请求里使用:不保存、不写日志、不回显,换取成功后立即从内存丢弃。 + 管理员账号不能创建个人令牌,请用普通用户账号。 +
+
+ +
+

访问令牌

+
+
+ + +
用于 POST /activity/turn。
+
+
+ + +
memory:write 同时允许读取,一个令牌即可覆盖检索与写入;只有 memory:read 时写入会被拒。
+
+
+ + +
用于 POST /activity/summary:只把已脱敏摘要送进待确认队列。
+
+
+
+ + +
+
+ 在面板「设置 → API 密钥」里各建一个 activity:write 与 memory:write 密钥(一个密钥只有一种权限,所以需要两个)。
+ 令牌只写入本机 ${escapeHtml(options.settingsPath)}(进程退出不丢),不会进入会话上下文、不会上传到云端、也不会出现在本页回显里。 +
+
+ +
+

诊断

+
+ + + +
+
+
+ +
+

最近上报

+ + + + + +
时间状态结果HTTPturn_id
暂无记录
+
+
+
+ + +`; +} diff --git a/lib/reporter.js b/lib/reporter.js new file mode 100644 index 0000000..5946895 --- /dev/null +++ b/lib/reporter.js @@ -0,0 +1,392 @@ +import { describeError } from "./api.js"; +/** Normalize an event timestamp (ms epoch or ISO string) into epoch ms. */ +export function toEpochMs(value) { + if (typeof value === 'number' && Number.isFinite(value)) { + // Accept seconds as well: anything below ~2001 in ms is almost certainly seconds. + return value < 1e11 ? Math.round(value * 1000) : Math.round(value); + } + if (typeof value === 'string' && value.trim() !== '') { + const parsed = Date.parse(value); + return Number.isNaN(parsed) ? undefined : parsed; + } + return undefined; +} +/** + * Map a DSH `TurnEndReason` onto a reportable status. + * + * `forked` is not a real completion: the child session starts a fresh turn, and + * counting the fork would inflate the heatmap with rounds the user never ran. + */ +export function statusForReason(reason) { + const kind = typeof reason === 'string' + ? reason + : reason !== null && typeof reason === 'object' + ? reason.kind + : undefined; + if (typeof kind !== 'string') + return 'completed'; + switch (kind) { + case 'completed': + return 'completed'; + case 'aborted': + case 'interrupted': + case 'blocked': + return 'cancelled'; + case 'error': + case 'max-tokens': + return 'failed'; + case 'forked': + return null; + default: + return 'completed'; + } +} +/** Extract the numeric turn id from a `turn/start` or `turn/end` payload. */ +function turnOf(data) { + if (data === undefined) + return undefined; + const value = data.turn; + if (typeof value === 'number' && Number.isFinite(value)) + return value; + if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) + return Number(value); + return undefined; +} +/** Conversation (session) id, tolerating both `id` and `sessionId` shapes. */ +export function conversationIdOf(session) { + if (session === undefined) + return undefined; + const value = session.id ?? session.sessionId; + return typeof value === 'string' && value !== '' ? value : undefined; +} +/** Text pulled out of one `user/message` or `assistant/message` payload. */ +export function textOf(value, depth = 0) { + if (depth > 5) + return undefined; + if (typeof value === 'string') + return value.trim() === '' ? undefined : value; + if (Array.isArray(value)) { + const parts = []; + for (const item of value) { + if (item !== null && typeof item === 'object') { + const part = item; + // Tool calls/results are never summarized: they can carry files and secrets. + if (part.type === 'tool_use' || part.type === 'tool_result' || part.type === 'image') + continue; + if (part.type === 'text' && typeof part.text === 'string') { + parts.push(part.text); + continue; + } + } + const nested = textOf(item, depth + 1); + if (nested !== undefined) + parts.push(nested); + } + return parts.length === 0 ? undefined : parts.join('\n'); + } + if (value === null || typeof value !== 'object') + return undefined; + const record = value; + for (const key of ['text', 'message', 'content', 'body']) { + const nested = textOf(record[key], depth + 1); + if (nested !== undefined) + return nested; + } + return undefined; +} +/** Local redaction: a summary must not carry credentials to the cloud. */ +const REDACTIONS = [ + [/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/g, '[已脱敏:私钥]'], + [/\b(sk|ghp|gho|ghs|xox[abprs]|cmt|cmr)_[A-Za-z0-9_-]{12,}/g, '[已脱敏:令牌]'], + [/\bBearer\s+[A-Za-z0-9._-]{16,}/gi, 'Bearer [已脱敏]'], + [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, '[已脱敏:JWT]'], + [/((?:password|passwd|pwd|secret|api[_-]?key|access[_-]?token)\s*[:=]\s*)[^\s,;]{6,}/gi, '$1[已脱敏]'], +]; +export function redactSecrets(text) { + let out = text; + for (const [pattern, replacement] of REDACTIONS) + out = out.replace(pattern, replacement); + return out; +} +/** + * Tracks open turns and reports each finished one. + * + * Reporting never blocks the agent loop: a failed POST is queued and retried by + * {@link flush}, and a service outage only shows up in the status card. + */ +/** A queued report is retried at most this many times before being dropped. */ +const MAX_RETRY_ATTEMPTS = 5; +export class Reporter { + options; + startedAt = new Map(); + queue = []; + retries = new Map(); + recent = []; + attempted = 0; + recorded = 0; + duplicate = 0; + failed = 0; + skipped = 0; + lastSentAt; + lastError; + draining = false; + /** Redacted message text per conversation, consumed at turn/end. */ + transcripts = new Map(); + summaryAttempted = 0; + summaryStaged = 0; + summaryFailed = 0; + lastSummaryError; + constructor(options) { + this.options = options; + } + /** Record a turn start so its duration can be reported later. */ + handleStart(session, event) { + const conversationId = conversationIdOf(session); + const turn = turnOf(event.data); + if (conversationId === undefined || turn === undefined) + return; + const at = toEpochMs(event.time) ?? Date.now(); + this.startedAt.set(`${conversationId}:${turn}`, at); + // Bound the map: a session that never ends must not leak forever. + if (this.startedAt.size > 500) { + const oldest = this.startedAt.keys().next(); + if (oldest.done !== true) + this.startedAt.delete(oldest.value); + } + } + /** Handle any `session/event`; only `turn/start` and `turn/end` matter here. */ + handleEvent(session, event) { + if (event === null || typeof event !== 'object') + return; + if (event.type === 'user/message' || event.type === 'assistant/message') { + this.collect(session, event); + return; + } + if (event.type === 'turn/start') { + this.handleStart(session, event); + return; + } + if (event.type !== 'turn/end') + return; + this.handleEnd(session, event); + } + handleEnd(session, event) { + const settings = this.options.settings(); + const conversationId = conversationIdOf(session); + const turn = turnOf(event.data); + if (conversationId === undefined || turn === undefined) + return; + const key = `${conversationId}:${turn}`; + const completedAt = toEpochMs(event.time) ?? Date.now(); + const startedAt = this.startedAt.get(key) ?? completedAt; + this.startedAt.delete(key); + const reason = event.data?.reason; + const status = statusForReason(reason); + if (status === null) { + this.push({ turnId: key, conversationId, status: 'cancelled', startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'forked turn is not reported' }); + this.skipped += 1; + return; + } + if (!settings.enabled) { + this.push({ turnId: key, conversationId, status, startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'reporting disabled' }); + this.skipped += 1; + return; + } + const token = this.options.activityToken(); + if (token === '') { + this.push({ turnId: key, conversationId, status, startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'activity token not configured' }); + this.skipped += 1; + return; + } + const payload = { + client_id: settings.clientId, + conversation_id: conversationId, + turn_id: key, + status, + started_at: Math.min(startedAt, completedAt), + completed_at: completedAt, + }; + void this.send(payload); + void this.sendSummary(conversationId, key, status); + } + /** Buffer one redacted message for the turn that is still open. */ + collect(session, event) { + const conversationId = conversationIdOf(session); + if (conversationId === undefined) + return; + const raw = textOf(event.data); + if (raw === undefined) + return; + const value = redactSecrets(raw).slice(0, 4000); + const buffer = this.transcripts.get(conversationId) ?? []; + buffer.push({ role: event.type === 'user/message' ? 'user' : 'assistant', text: value, turn: turnOf(event.data) }); + if (buffer.length > 120) + buffer.splice(0, buffer.length - 120); + this.transcripts.set(conversationId, buffer); + } + /** 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)); + const picked = []; + const rest = []; + for (const item of buffer) { + const matches = Number.isFinite(turn) && (item.turn === undefined || item.turn === turn); + if (matches) + picked.push({ role: item.role, text: item.text }); + else + rest.push(item); + } + this.transcripts.set(conversationId, rest); + const maxChars = Math.max(1000, this.options.summary().maxChars); + let total = 0; + const kept = []; + for (const message of picked) { + if (total + message.text.length > maxChars) + break; + kept.push(message); + total += message.text.length; + } + return kept; + } + /** Stage one summary; failures only surface in the status card. */ + async sendSummary(conversationId, turnKey, status) { + const summary = this.options.summary(); + const token = this.options.summaryToken(); + if (!summary.enabled || token === '' || status !== 'completed') + return; + const messages = this.takeTranscript(conversationId, turnKey); + if (messages.length === 0) + return; + const payload = { conversation_id: conversationId, turn_id: turnKey, messages }; + this.summaryAttempted += 1; + const result = await this.options.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); + if (retry.ok) { + this.summaryStaged += typeof retry.data.staged === 'number' ? retry.data.staged : 0; + return; + } + } + this.summaryFailed += 1; + this.lastSummaryError = describeError(result.error); + this.options.log(`cloud-memory: turn summary failed: ${this.lastSummaryError}`); + } + push(record) { + this.recent.unshift(record); + if (this.recent.length > 50) + this.recent.length = 50; + } + /** 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); + const now = Date.now(); + if (result.ok) { + const duplicate = result.data.duplicate === true || result.status === 200; + if (duplicate) + this.duplicate += 1; + else + this.recorded += 1; + this.retries.delete(payload.turn_id); + this.lastSentAt = now; + this.push({ + turnId: payload.turn_id, + conversationId: payload.conversation_id, + status: payload.status, + startedAt: payload.started_at, + completedAt: payload.completed_at, + at: now, + outcome: duplicate ? 'duplicate' : 'recorded', + httpStatus: result.status, + }); + return; + } + this.lastError = describeError(result.error); + this.failed += 1; + this.push({ + turnId: payload.turn_id, + conversationId: payload.conversation_id, + status: payload.status, + startedAt: payload.started_at, + completedAt: payload.completed_at, + at: now, + outcome: 'queued', + httpStatus: result.error.status, + error: this.lastError, + }); + // 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); + if (this.queue.length > 200) + this.queue.shift(); + } + this.options.log(`cloud-memory: turn report failed: ${this.lastError}`); + } + /** Retry queued reports; safe to call at any time. */ + async flush() { + if (this.draining) + return { sent: 0, remaining: this.queue.length }; + this.draining = true; + let sent = 0; + try { + while (this.queue.length > 0) { + const payload = this.queue[0]; + if (payload === undefined) + break; + this.attempted += 1; + const result = await this.options.client.reportTurn(payload, this.options.activityToken()); + if (!result.ok) { + this.lastError = describeError(result.error); + this.failed += 1; + const attempt = (this.retries.get(payload.turn_id) ?? 0) + 1; + if (attempt >= MAX_RETRY_ATTEMPTS) { + // Give up on this turn: a permanently failing endpoint must not keep + // an unbounded queue of metadata forever. + this.queue.shift(); + this.retries.delete(payload.turn_id); + this.options.log(`cloud-memory: dropping turn report after ${attempt} attempts: ${this.lastError}`); + continue; + } + this.retries.set(payload.turn_id, attempt); + break; + } + this.queue.shift(); + this.retries.delete(payload.turn_id); + sent += 1; + if (result.data.duplicate === true || result.status === 200) + this.duplicate += 1; + else + this.recorded += 1; + this.lastSentAt = Date.now(); + } + } + finally { + this.draining = false; + } + return { sent, remaining: this.queue.length }; + } + /** Counters + recent history. */ + snapshot() { + return { + attempted: this.attempted, + recorded: this.recorded, + duplicate: this.duplicate, + failed: this.failed, + skipped: this.skipped, + queued: this.queue.length, + summaryAttempted: this.summaryAttempted, + summaryStaged: this.summaryStaged, + summaryFailed: this.summaryFailed, + ...(this.lastSummaryError === undefined ? {} : { lastSummaryError: this.lastSummaryError }), + ...(this.lastSentAt === undefined ? {} : { lastSentAt: this.lastSentAt }), + ...(this.lastError === undefined ? {} : { lastError: this.lastError }), + recent: [...this.recent], + }; + } +} diff --git a/lib/routes.js b/lib/routes.js new file mode 100644 index 0000000..f41bf22 --- /dev/null +++ b/lib/routes.js @@ -0,0 +1,441 @@ +import { describeError, isSecureLoginTarget } from "./api.js"; +import { renderConfigPage } from "./page.js"; +import { SkillAdminError } from "./skill-admin.js"; +import { renderSkillsPage } from "./skill-page.js"; +/** Route constants — kept in one place so the client half can reuse them. */ +export const ROUTES = { + page: '/cloud-memory', + status: '/cloud-memory/status', + config: '/cloud-memory/config', + login: '/cloud-memory/login', + test: '/cloud-memory/test', + flush: '/cloud-memory/flush', + skills: '/cloud-memory/skills', +}; +/** Largest request body we accept (a settings patch is tiny). */ +const MAX_BODY_BYTES = 64 * 1024; +/** Collect a request body as UTF-8 text. */ +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. */ +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. */ +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). */ +function fail(res, status, message, asHtml = false) { + const text = asHtml + ? `云端记忆${message}` + : 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); +} +/** The payload the page and the client card both consume. */ +function statusPayload(deps) { + const view = deps.store.describe(); + const tokens = { + activity: view.activityToken, + memory: view.memoryToken, + summary: view.summaryToken, + }; + const settings = { + enabled: view.enabled, + baseUrl: view.baseUrl, + clientId: view.clientId, + requestTimeoutMs: view.requestTimeoutMs, + defaultK: view.defaultK, + summaryEnabled: view.summaryEnabled, + summaryMaxChars: view.summaryMaxChars, + skillsSyncEnabled: view.skillsSyncEnabled, + skillsDir: view.skillsDir, + }; + return { + ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot(), + ...(deps.skills === undefined ? {} : { skills: deps.skills() }), + }; +} +/** 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); +} +/** `GET /cloud-memory/status`. */ +function serveStatus(deps, req, res) { + if (req.method !== 'GET') { + fail(res, 405, 'method-not-allowed'); + return; + } + json(res, 200, statusPayload(deps)); +} +/** `PUT /cloud-memory/config`. */ +async function serveConfig(deps, req, res) { + if (req.method !== 'PUT' && req.method !== 'POST') { + fail(res, 405, 'method-not-allowed'); + return; + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected'); + return; + } + const type = (req.headers['content-type'] ?? '').toLowerCase(); + if (!type.startsWith('application/json')) { + fail(res, 415, 'json-required'); + return; + } + let patch; + try { + patch = JSON.parse(await readBody(req)); + } + catch (error) { + fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json'); + return; + } + if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { + fail(res, 400, 'invalid-patch'); + return; + } + const result = deps.store.patch(patch); + if (!result.ok) { + fail(res, 400, result.error ?? 'invalid-patch'); + return; + } + json(res, 200, statusPayload(deps)); +} +/** `POST /cloud-memory/test` — validate both tokens without recording anything. */ +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 activityToken = deps.store.activityToken(); + const memoryToken = deps.store.memoryToken(); + const activity = activityToken === '' + ? { ok: false, message: '还没填令牌:把 activity:write 密钥粘到下面「活动上报令牌」再点保存' } + : await (async () => { + const probe = await client.probeActivity(activityToken); + return probe.ok + ? { ok: true, message: '令牌有效(鉴权通过)' } + : { ok: false, message: describeError(probe.error) }; + })(); + const memory = memoryToken === '' + ? { ok: false, message: '还没填令牌:把 memory:write 密钥粘到下面「记忆读写令牌」再点保存' } + : await (async () => { + const probe = await client.projects(); + return probe.ok + ? { ok: true, message: `令牌有效(${(probe.data.projects ?? []).length} 个项目)` } + : { ok: false, message: describeError(probe.error) }; + })(); + const summaryToken = deps.store.summaryToken(); + const summary = !deps.store.settings().summaryEnabled + ? { ok: false, message: '自动摘要已关闭(可在下方勾选开启)' } + : summaryToken === '' + ? { ok: false, message: '未配置摘要令牌:留空则不做自动摘要' } + : await (async () => { + const probe = await client.probeSummary(summaryToken); + return probe.ok + ? { ok: true, message: '摘要令牌有效(只进待确认队列)' } + : { ok: false, message: describeError(probe.error) }; + })(); + json(res, 200, { ok: true, activity, memory, summary }); +} +/** `POST /cloud-memory/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 }); +} +/** Labels attached to the two tokens this plugin asks the dashboard to mint. */ +const TOKEN_LABELS = { + activity: 'DSH desktop 活动上报', + memory: 'DSH desktop 记忆读写', + summary: 'DSH desktop 对话摘要', +}; +/** + * `POST /cloud-memory/login` — sign in with the cloud account and exchange it + * for the two scoped tokens. + * + * The password is used once, in memory, and never written anywhere: the flow is + * password → short-lived session cookie → two `cmt_…` 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; + } + const target = deps.store.settings().baseUrl; + if (!isSecureLoginTarget(target)) { + // 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); + if (!session.ok) { + const status = session.error.status === 429 ? 429 : 401; + json(res, status, { ok: false, error: describeError(session.error) }); + return; + } + const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity); + const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory); + const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary); + 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; + } + 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; + 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, { + ...statusPayload(deps), + 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)}`, + }, + }); +} +/** HTTP status for one skill-admin failure code. */ +function adminStatus(code) { + switch (code) { + case 'not_found': return 404; + case 'invalid_name': + case 'invalid_url': return 400; + case 'collision': + case 'sync_running': return 409; + case 'no_skills_found': return 422; + case 'git_failed': return 502; + default: return 500; + } +} +/** + * The skill management surface, one prefix route: + * `GET /cloud-memory/skills` the management page + * `GET /cloud-memory/skills/api` inventory JSON (skills + trash) + * `POST /cloud-memory/skills/toggle` { folder, enabled } + * `POST /cloud-memory/skills/remove` { folder } + * `POST /cloud-memory/skills/install` { url } + */ +async function serveSkills(deps, req, res) { + if (deps.admin === undefined) { + fail(res, 404, 'skills-admin-unavailable'); + return; + } + const admin = deps.admin; + const suffix = (req.url ?? '').split('?')[0]?.slice(ROUTES.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; + } + json(res, 200, { ok: true, ...(await admin.list()) }); + return; + } + const actions = { + '/toggle': async (body) => admin.setEnabled(body.folder, body.enabled === true), + '/remove': async (body) => admin.remove(body.folder), + '/install': async (body) => admin.installFromGit(body.url), + }; + const action = actions[suffix]; + if (action === undefined) { + fail(res, 404, 'unknown-skill-route'); + return; + } + if (req.method !== 'POST') { + fail(res, 405, 'method-not-allowed'); + return; + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected'); + return; + } + const type = (req.headers['content-type'] ?? '').toLowerCase(); + if (!type.startsWith('application/json')) { + fail(res, 415, 'json-required'); + return; + } + let body; + try { + body = JSON.parse(await readBody(req)); + } + catch { + fail(res, 400, 'invalid-json'); + return; + } + if (body === null || typeof body !== 'object' || Array.isArray(body)) { + fail(res, 400, 'invalid-body'); + return; + } + 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 }); + } + else { + json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) }); + } + } +} +/** Build the exact-route table registered with the host web server. */ +export function createRoutes(deps) { + return [ + { + kind: 'exact', + path: ROUTES.page, + handler: (req, res) => servePage(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.status, + handler: (req, res) => serveStatus(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.config, + handler: (req, res) => serveConfig(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.login, + handler: (req, res) => serveLogin(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.test, + handler: (req, res) => serveTest(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.flush, + handler: (req, res) => serveFlush(deps, req, res), + }, + { + kind: 'prefix', + path: ROUTES.skills, + handler: (req, res) => serveSkills(deps, req, res), + }, + ]; +} diff --git a/lib/skill-admin.js b/lib/skill-admin.js new file mode 100644 index 0000000..9076c27 --- /dev/null +++ b/lib/skill-admin.js @@ -0,0 +1,262 @@ +/** + * Local skill management, built into the plugin: list, enable/disable, + * real delete, and install from a git repository. + * + * This covers the everyday subset of a full skills manager. It manages + * only the DSH skills root (plus its own parking and trash areas) — the + * cloud sync engine keeps owning everything beyond the local disk. + * + * Enable/disable is deliberately mechanical: a disabled skill's folder + * is parked in `$DSH_HOME/skills-disabled/`, outside the skills root, so + * DSH simply does not see it. No host internals are involved, which + * keeps the operation reversible and predictable. The sync engine knows + * about the parking area: parked skills are neither resurrected nor + * mistaken for deletions, and a parked cloud skill still receives its + * cloud updates in place. + * + * Delete is a real delete: the folder is removed recursively. The + * cloud copy is unaffected — local deletion never propagates to the + * center (the sync engine remembers the removal, so the same cloud + * version is not pulled back down either). + */ +import { execFile } from 'node:child_process'; +import { cp, mkdir, readFile, readdir, rename, rm, stat } from 'node:fs/promises'; +import { basename, join } from 'node:path'; +import { parseSkillFrontmatter } from "./skill-sync.js"; +import { dshHome } from "./store.js"; +/** The parking area for disabled skills. */ +export function skillsHoldingDir() { + return join(dshHome(), 'skills-disabled'); +} +/** A management failure with a stable machine-readable code. */ +export class SkillAdminError extends Error { + code; + constructor(code, message) { + super(message); + this.code = code; + this.name = 'SkillAdminError'; + } +} +function fail(code, message) { + throw new SkillAdminError(code, message); +} +async function isDirectory(path) { + return stat(path).then((s) => s.isDirectory()).catch(() => false); +} +/** Count files below a directory, capped so a stray tree cannot hang us. */ +async function countFiles(dir, cap = 2000) { + let count = 0; + const walk = async (sub) => { + if (count > cap) + return; + for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) { + if (entry.name === '.git') + continue; + const rel = sub === '' ? entry.name : `${sub}/${entry.name}`; + if (entry.isDirectory()) + await walk(rel); + else if (entry.isFile()) + count += 1; + } + }; + await walk(''); + return count; +} +/** A folder name we are willing to move around: one path segment, no tricks. */ +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)}`); + } + return folder; +} +export class SkillAdmin { + deps; + constructor(deps) { + this.deps = deps; + } + guardSync() { + if (this.deps.syncRunning()) + fail('sync_running', '技能同步正在进行,请稍候再试。'); + } + async syncUploaded() { + 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; + } + } + } + catch { + // No sidecar yet: nothing has been uploaded. + } + return {}; + } + async describe(folder, dir, enabled, uploaded) { + const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined); + if (markdown === undefined) + return undefined; + const frontmatter = parseSkillFrontmatter(markdown); + let origin = 'local'; + let revision; + const delivery = await readFile(join(dir, '.manifest.json'), 'utf8').catch(() => undefined); + if (delivery !== undefined) { + origin = 'cloud'; + try { + const parsed = JSON.parse(delivery); + const value = parsed.revision; + if (typeof value === 'number') + revision = value; + } + catch { /* a corrupt manifest still marks cloud origin */ } + } + else { + for (const record of Object.values(uploaded)) { + if (record.folder === folder) { + origin = 'uploaded'; + revision = record.revision; + break; + } + } + } + return { + folder, + name: frontmatter.name ?? folder, + description: (frontmatter.description ?? '').slice(0, 300), + enabled, + origin, + ...(revision === undefined ? {} : { revision }), + files: await countFiles(dir), + }; + } + /** Inventory of the skills root and the parking area. */ + async list() { + const uploaded = await this.syncUploaded(); + 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); + if (described !== undefined) + skills.push(described); + } + }; + await scan(this.deps.skillsRoot(), true); + await scan(this.deps.holdingDir(), false); + skills.sort((a, b) => (a.folder < b.folder ? -1 : 1)); + return { skills }; + } + /** Locate a skill folder across the root and the parking area. */ + async locate(folder) { + 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; + } + /** Enable (move back into the root) or disable (park) one skill. */ + async setEnabled(folderInput, enabled) { + this.guardSync(); + const folder = checkFolder(folderInput); + const found = await this.locate(folder); + if (found === undefined) + fail('not_found', `没有找到技能:${folder}`); + const targetArea = enabled ? 'root' : 'holding'; + if (found.area === targetArea) + return { folder, enabled }; + const targetRoot = enabled ? this.deps.skillsRoot() : this.deps.holdingDir(); + await mkdir(targetRoot, { recursive: true }); + const target = join(targetRoot, folder); + if (await isDirectory(target)) + fail('collision', `目标位置已存在同名技能:${folder}`); + await rename(found.dir, target); + this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`); + return { folder, enabled }; + } + /** Delete one skill for real: its folder is removed recursively. */ + async remove(folderInput) { + this.guardSync(); + const folder = checkFolder(folderInput); + const found = await this.locate(folder); + if (found === undefined) + fail('not_found', `没有找到技能:${folder}`); + await rm(found.dir, { recursive: true, force: true }); + this.deps.log(`skill deleted: ${folder}`); + return { folder }; + } + /** + * Install every skill found in a git repository (https:// or file://). + * The clone is shallow and never executes repository code; folders + * that collide with existing skills are skipped, never overwritten. + */ + async installFromGit(urlInput) { + this.guardSync(); + if (typeof urlInput !== 'string') + fail('invalid_url', '请提供仓库地址。'); + const url = urlInput.trim(); + if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) { + fail('invalid_url', '只接受 https:// 或 file:// 的 git 仓库地址。'); + } + const scratch = join(dshHome(), `.cloud-memory-clone-${process.pid}-${Date.now().toString(36)}`); + try { + await new Promise((resolvePromise, rejectPromise) => { + execFile('git', ['clone', '--depth', '1', '--no-tags', '--', url, scratch], { timeout: 120_000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 }, (error) => (error ? rejectPromise(error) : resolvePromise())); + }); + } + catch { + await rm(scratch, { recursive: true, force: true }).catch(() => { }); + fail('git_failed', '仓库克隆失败(地址不可达、需要登录,或本机没有 git)。'); + } + try { + const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill'; + const candidates = []; + const collect = async (dir, depth) => { + if (await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) !== undefined) { + candidates.push({ folder: dir === scratch ? repoName : basename(dir), dir }); + return; + } + if (depth >= 3) + return; + for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + if (entry.isDirectory() && entry.name !== '.git') + await collect(join(dir, entry.name), depth + 1); + } + }; + await collect(scratch, 0); + if (candidates.length === 0) + fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。'); + const installed = []; + const skipped = []; + await mkdir(this.deps.skillsRoot(), { recursive: true }); + for (const candidate of candidates) { + let folder = candidate.folder; + try { + folder = checkFolder(folder); + } + catch { + skipped.push({ name: candidate.folder, reason: 'invalid_name' }); + continue; + } + if ((await this.locate(folder)) !== undefined) { + skipped.push({ name: folder, reason: 'already_exists' }); + continue; + } + await cp(candidate.dir, join(this.deps.skillsRoot(), folder), { + recursive: true, + filter: (source) => !source.split(/[\\/]/).includes('.git'), + }); + installed.push(folder); + this.deps.log(`skill installed from git: ${folder}`); + } + return { installed, skipped }; + } + finally { + await rm(scratch, { recursive: true, force: true }).catch(() => { }); + } + } +} diff --git a/lib/skill-page.js b/lib/skill-page.js new file mode 100644 index 0000000..fa7c1c2 --- /dev/null +++ b/lib/skill-page.js @@ -0,0 +1,161 @@ +/** + * The local skill management page (`GET /cloud-memory/skills`). + * + * A thin shell: the browser fetches the JSON inventory from + * `/cloud-memory/skills/api` and renders it; every action is a small + * JSON POST back to the same prefix. All skill data is inserted with + * textContent, never as raw HTML. + */ +export function renderSkillsPage(options) { + return ` + + + + +技能管理 · 云端记忆插件 + + + +
+

技能管理

+

v${options.version} · 本机技能的列表、启停、安装;删除是真删、不可恢复(云端副本不受影响)。云端同步仍在后台自动进行。← 返回云端记忆设置

+ +
+

从 git 仓库安装

+
+ + +
+
+
+ +
+

本机技能

+
+
+
+
+ + + +`; +} diff --git a/lib/skill-sync.js b/lib/skill-sync.js new file mode 100644 index 0000000..3bd82d9 --- /dev/null +++ b/lib/skill-sync.js @@ -0,0 +1,519 @@ +/** + * Bidirectional skill sync between the cloud skill center and the local + * DSH skills directory (`$DSH_HOME/skills` by default). + * + * The cloud center is the hub, the local directory is a working copy, and + * the DSH skills manager keeps owning local management — this module only + * moves files, in both directions: + * + * - DOWN: cloud skills are installed exactly like the platform's own + * `skills-sync` tool does it — bundle hash and per-file checksums are + * verified before anything lands, writes are atomic per file, and a + * per-skill `.manifest.json` records what the cloud delivered. + * - UP: skills that originated locally (installed by the skills manager, + * imported, or written by hand) are published to the center as new + * revisions, guarded by the center's `expected_revision` check. + * + * Safety rules (deliberate, in order): + * 1. A cloud-delivered skill is never re-uploaded. If its local files no + * longer match the delivery manifest, the skill is flagged as a + * conflict and left completely alone. + * 2. A local deletion never deletes the cloud copy. + * 3. A name that already exists on the other side is never hijacked; + * it is reported as a conflict for a human to resolve. + * 4. Bundles whose scripts changed on the cloud side are not installed + * until the change is acknowledged in the dashboard, mirroring the + * center's own review flag. + * 5. Only the center's file layout is uploadable (SKILL.md at the root, + * everything else under references/, scripts/ or assets/, with the + * center's extension allowlist). Anything else is reported, never + * silently trimmed. + */ +import { createHash, randomUUID } from 'node:crypto'; +import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; +import { describeError } from "./api.js"; +import { dshHome } from "./store.js"; +/** Cloud skill names: lowercase kebab, at most 64 characters. */ +export const CLOUD_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/; +/** Layout contract of the cloud skill center (mirrors its store rules). */ +const TEXT_EXT = new Set(['.md', '.txt', '.json', '.yaml', '.yml', '.py', '.sh', '.ps1', '.mjs', '.js', '.ts', '.tsx', '.css', '.html', '.csv']); +const BINARY_EXT = new Set(['.docx', '.xlsx', '.pptx', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.zip']); +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}$/; +const MAX_FILES = 100; +const MAX_FILE_BYTES = 512 * 1024; +const MAX_SKILL_BYTES = 2 * 1024 * 1024; +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; +} +async function isDirectory(path) { + return stat(path).then((value) => value.isDirectory()).catch(() => false); +} +export class SkillSync { + deps; + running = false; + current = { + running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0, + }; + constructor(deps) { + this.deps = deps; + } + /** Stats of the latest pass, for the status endpoint. */ + stats() { + return this.current; + } + /** The local skills root this engine syncs. */ + skillsRoot() { + const dir = this.deps.settings().skillsDir; + return dir !== '' ? resolve(dir) : join(dshHome(), 'skills'); + } + /** The parking area where disabled skills wait, outside the root. */ + holdingRoot() { + return this.deps.holdingDir?.() ?? join(dshHome(), 'skills-disabled'); + } + statePath() { + return join(dshHome(), 'cloud-memory-skills.json'); + } + async loadState() { + const clean = { version: 1, uploaded: {}, delivered: {}, removed: {} }; + try { + const parsed = JSON.parse(await readFile(this.statePath(), 'utf8')); + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + const raw = parsed; + const map = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}; + return { + version: 1, + uploaded: map(raw.uploaded), + delivered: map(raw.delivered), + removed: map(raw.removed), + }; + } + } + catch { + // Missing or corrupt sidecar: start clean; the cloud is the truth. + } + return clean; + } + async saveState(state) { + const path = this.statePath(); + await mkdir(dirname(path), { recursive: true }); + const temporary = `${path}.tmp-${process.pid}`; + await writeFile(temporary, JSON.stringify(state, null, 2)); + await rename(temporary, path); + } + /** Read every syncable file of one skill directory (unsorted walk). */ + async readSkillFiles(dir) { + const out = []; + const walk = async (sub) => { + const entries = await readdir(join(dir, sub), { withFileTypes: true }); + for (const entry of entries) { + const rel = sub === '' ? entry.name : `${sub}/${entry.name}`; + if (entry.name.startsWith('.')) + continue; + if (entry.isDirectory()) { + await walk(rel); + } + else if (entry.isFile()) { + out.push({ rel, buffer: await readFile(join(dir, rel)) }); + } + } + }; + await walk(''); + return out.sort((a, b) => (a.rel < b.rel ? -1 : 1)); + } + /** True when a cloud-delivered directory still matches its manifest. */ + async deliveredIntact(dir, delivery) { + const recorded = delivery.files ?? []; + let files; + try { + files = await this.readSkillFiles(dir); + } + catch { + return false; + } + const current = files.filter((file) => file.rel !== '.manifest.json'); + if (current.length !== recorded.length) + return false; + const byPath = new Map(current.map((file) => [file.rel, sha256Hex(file.buffer)])); + return recorded.every((file) => byPath.get(file.path) === file.sha256); + } + /** Install or update one cloud skill into the local directory. */ + async install(item, bundle, root) { + const dir = join(root, item.name); + const previous = await this.readDelivery(dir); + const keep = new Set(bundle.files.map((file) => file.path)); + await mkdir(dir, { recursive: true }); + const written = []; + for (const file of bundle.files) { + const buffer = Buffer.from(file.data, 'base64'); + if (sha256Hex(buffer) !== file.sha256) + throw new Error(`checksum mismatch for ${file.path}`); + const target = join(dir, ...file.path.split('/')); + await mkdir(dirname(target), { recursive: true }); + const temporary = `${target}.tmp-${process.pid}`; + await writeFile(temporary, buffer); + await rename(temporary, target); + written.push({ path: file.path, sha256: file.sha256, size: buffer.length }); + } + for (const file of previous?.files ?? []) { + if (!keep.has(file.path)) + await rm(join(dir, ...file.path.split('/')), { force: true }); + } + const delivery = { + name: item.name, + revision: bundle.revision, + manifest_sha256: bundle.manifest_sha256, + files: written, + synced_at: new Date().toISOString(), + }; + await writeFile(join(dir, '.manifest.json'), JSON.stringify(delivery, null, 2)); + } + async readDelivery(dir) { + try { + const parsed = JSON.parse(await readFile(join(dir, '.manifest.json'), 'utf8')); + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + return parsed; + } + } + catch { + // Not a cloud-delivered skill. + } + return undefined; + } + /** One full pass; never throws — outcomes land in the stats. */ + async syncOnce() { + if (this.running) + return this.current; + const settings = this.deps.settings(); + if (!settings.enabled || !settings.skillsSyncEnabled) + return this.current; + this.running = true; + const stats = { + running: true, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0, + }; + this.current = stats; + try { + await this.pass(stats); + stats.lastRunAt = new Date().toISOString(); + } + catch (error) { + stats.lastError = error instanceof Error ? error.message : String(error); + this.deps.log(`skill sync failed: ${stats.lastError}`); + } + finally { + stats.running = false; + this.running = false; + this.current = stats; + } + return this.current; + } + /** Record a conflict once per pass, however many rules trip over it. */ + conflict(stats, name, reason) { + if (!stats.conflicts.some((item) => item.name === name && item.reason === reason)) { + stats.conflicts.push({ name, reason }); + } + } + async pass(stats) { + const client = this.deps.client(); + const listing = await client.listSkills(); + if (!listing.ok) + throw new Error(`skill listing failed: ${describeError(listing.error)}`); + const items = (listing.data.items ?? []).filter((item) => typeof item.name === 'string' && CLOUD_SKILL_NAME.test(item.name)); + const cloudByName = new Map(items.map((item) => [item.name, item])); + const root = this.skillsRoot(); + const state = await this.loadState(); + let stateDirty = false; + // ---- DOWN: cloud center -> local directory ------------------------- + for (const item of items) { + if (item.enabled === false) { + stats.skipped += 1; + continue; + } + // Locally-originated skills belong to the UP pass, even though the + // center lists them too once they are published. + if (state.uploaded[item.name] !== undefined) { + stats.skipped += 1; + continue; + } + const dir = join(root, item.name); + const parkedDir = join(this.holdingRoot(), item.name); + const inRoot = await isDirectory(dir); + const parked = !inRoot && (await isDirectory(parkedDir)); + const home = parked ? parkedDir : dir; + const exists = inRoot || parked; + const removed = state.removed[item.name]; + if (removed !== undefined && exists) { + // The user put it back by hand; the removal is over. + delete state.removed[item.name]; + stateDirty = true; + } + else if (removed !== undefined && item.manifest_sha256 === removed.manifest) { + // Deleted locally at this exact cloud version: keep it deleted. + stats.skipped += 1; + continue; + } + else if (removed !== undefined) { + // The cloud published a different version since the deletion. + delete state.removed[item.name]; + stateDirty = true; + } + const delivery = await this.readDelivery(home); + if (exists && delivery !== undefined) { + // Delivered before: local integrity is judged before any download. + if (!(await this.deliveredIntact(home, delivery))) { + this.conflict(stats, item.name, 'locally_modified'); + continue; + } + if (delivery.manifest_sha256 === item.manifest_sha256) { + if (state.delivered[item.name]?.manifest !== item.manifest_sha256) { + state.delivered[item.name] = { manifest: item.manifest_sha256 ?? '' }; + stateDirty = true; + } + stats.skipped += 1; + continue; + } + // Intact but the cloud moved on: fall through and install the update. + } + if (exists && delivery === undefined) { + this.conflict(stats, item.name, 'name_collision'); + continue; + } + if (item.script_changed === true) { + // The listing already carries the review flag; don't even fetch. + this.conflict(stats, item.name, 'script_review_required'); + continue; + } + const bundle = await client.skillBundle(item.name); + if (!bundle.ok) { + this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`); + continue; + } + if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) { + this.conflict(stats, item.name, 'manifest_mismatch'); + continue; + } + if (bundle.data.script_changed === true) { + this.conflict(stats, item.name, 'script_review_required'); + continue; + } + await this.install(item, bundle.data, parked ? this.holdingRoot() : root); + state.delivered[item.name] = { manifest: bundle.data.manifest_sha256 }; + stateDirty = true; + (exists ? stats.updated : stats.downloaded).push(item.name); + } + // ---- UP: local originals -> cloud center --------------------------- + const folders = await readdir(root, { withFileTypes: true }).catch(() => []); + const seenFolders = new Set(); + for (const entry of folders) { + if (!entry.isDirectory() || entry.name.startsWith('.')) + continue; + seenFolders.add(entry.name); + const dir = join(root, entry.name); + if ((await this.readDelivery(dir)) !== undefined) + continue; // cloud-origin: down pass owns it + const skill = await this.readLocalSkill(dir, entry.name); + if (skill === undefined) + continue; + if (typeof skill === 'string') { + this.conflict(stats, entry.name, skill); + continue; + } + const record = state.uploaded[skill.name]; + const cloud = cloudByName.get(skill.name); + if (cloud !== undefined && record === undefined) { + this.conflict(stats, skill.name, 'name_collision'); + continue; + } + if (record !== undefined && record.manifest === skill.manifest) { + stats.skipped += 1; + continue; + } + const files = skill.files.map((file) => { + const ext = file.rel.slice(file.rel.lastIndexOf('.')).toLowerCase(); + return TEXT_EXT.has(ext) + ? { path: file.rel, content: file.buffer.toString('utf8') } + : { path: file.rel, base64: file.buffer.toString('base64') }; + }); + const operationId = `dsh-skill-${randomUUID()}`; + if (record === undefined || cloud === undefined) { + const created = await client.createSkill({ + name: skill.name, + description: skill.description, + execution_mode: skill.hasScripts ? 'local-bundle' : 'prompt-only', + files, + expected_revision: 0, + operation_id: operationId, + }); + if (!created.ok) { + this.conflict(stats, skill.name, `upload_failed: ${describeError(created.error)}`); + continue; + } + state.uploaded[skill.name] = { + folder: entry.name, + revision: created.data.skill?.revision ?? created.data.revision ?? 1, + manifest: skill.manifest, + syncedAt: new Date().toISOString(), + }; + stateDirty = true; + stats.uploaded.push(skill.name); + } + else { + if (cloud.revision !== undefined && cloud.revision !== record.revision) { + this.conflict(stats, skill.name, 'cloud_newer'); + continue; + } + const updated = await client.updateSkill(skill.name, { + description: skill.description, + files, + expected_revision: record.revision, + operation_id: operationId, + }); + if (!updated.ok) { + const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`; + this.conflict(stats, skill.name, reason); + continue; + } + state.uploaded[skill.name] = { + folder: entry.name, + revision: updated.data.skill?.revision ?? updated.data.revision ?? record.revision + 1, + manifest: skill.manifest, + syncedAt: new Date().toISOString(), + }; + stateDirty = true; + stats.updated.push(skill.name); + } + } + // Presence counts the parking area too: a parked skill is disabled, + // not deleted. Anything missing from both is a deliberate removal + // (remembered, so it is not resurrected); the cloud copy stays. + const presentFolders = new Set(seenFolders); + for (const entry of await readdir(this.holdingRoot(), { withFileTypes: true }).catch(() => [])) { + if (entry.isDirectory()) + presentFolders.add(entry.name); + } + for (const [name, record] of Object.entries(state.uploaded)) { + if (!presentFolders.has(record.folder)) { + state.removed[name] = { manifest: cloudByName.get(name)?.manifest_sha256 ?? record.manifest }; + delete state.uploaded[name]; + stateDirty = true; + } + } + for (const [name, record] of Object.entries(state.delivered)) { + if (!presentFolders.has(name)) { + state.removed[name] = { manifest: record.manifest }; + delete state.delivered[name]; + stateDirty = true; + } + } + if (stateDirty) + await this.saveState(state); + const changed = stats.downloaded.length + stats.uploaded.length + stats.updated.length; + if (changed > 0 || stats.conflicts.length > 0) { + this.deps.log(`skill sync: ${stats.downloaded.length} downloaded, ${stats.uploaded.length} uploaded, ` + + `${stats.updated.length} updated, ${stats.conflicts.length} conflict(s)`); + } + } + /** + * Read one locally-originated skill for upload. Returns the skill, a + * conflict reason string, or undefined when the folder is not a skill. + */ + async readLocalSkill(dir, folder) { + let files; + try { + files = await this.readSkillFiles(dir); + } + catch { + return undefined; + } + const markdown = files.find((file) => file.rel === 'SKILL.md'); + if (markdown === undefined) + return undefined; + if (files.length > MAX_FILES) + return 'too_many_files'; + let total = 0; + for (const file of files) { + if (file.buffer.length > MAX_FILE_BYTES) + return 'file_too_large'; + total += file.buffer.length; + if (!isCloudSkillPath(file.rel)) + return 'unsupported_layout'; + } + if (total > MAX_SKILL_BYTES) + return 'skill_too_large'; + const frontmatter = parseSkillFrontmatter(markdown.buffer.toString('utf8')); + const name = frontmatter.name !== undefined && CLOUD_SKILL_NAME.test(frontmatter.name) + ? frontmatter.name + : CLOUD_SKILL_NAME.test(folder) + ? folder + : undefined; + if (name === undefined) + return 'invalid_name'; + const heading = /^#\s+(.+)$/m.exec(markdown.buffer.toString('utf8'))?.[1]?.trim(); + const description = (frontmatter.description ?? heading ?? name).slice(0, 500); + const manifest = linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) }))); + return { + name, + description, + files, + manifest, + hasScripts: files.some((file) => file.rel.startsWith('scripts/')), + }; + } +} diff --git a/lib/store.js b/lib/store.js new file mode 100644 index 0000000..b8d0cba --- /dev/null +++ b/lib/store.js @@ -0,0 +1,270 @@ +/** + * Settings sidecar: `$DSH_HOME/cloud-memory.json`. + * + * Why a file and not the DSH credentials service: the desktop profile has no + * stable host-side credentials face this plugin can depend on (the client-side + * `remote.credentials` proxy is a browser service), and a missed dependency + * would silently disable reporting. A 0600-ish file under the user's DSH home + * directory is the smallest thing that always works; Windows ACLs on + * `C:\Users\` already restrict it to that account. + * + * The file holds the two bearer tokens and the UI-editable overrides. It is + * NEVER uploaded, never printed, and `describe()` only exposes a mask. + */ +import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync, chmodSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { homedir } from 'node:os'; +import { DEFAULT_SETTINGS, normalizeBaseUrl, settingsFromConfig } from "./config.js"; +/** `$DSH_HOME` (or `~/.dsh`) — the same resolution DSH core uses. */ +export function dshHome() { + const fromEnv = process.env.DSH_HOME; + if (fromEnv !== undefined && fromEnv.trim() !== '') + return fromEnv; + return resolve(homedir(), '.dsh'); +} +/** Absolute path of the settings sidecar. */ +export function settingsPath() { + return resolve(dshHome(), 'cloud-memory.json'); +} +/** Read a token from an env var (an alternative to the sidecar for CI use). */ +function envToken(name) { + const value = process.env[name]; + if (value === undefined || value.trim() === '') + return undefined; + return value.trim(); +} +/** Mask a secret for display: `cmt_abc…9f2c`. */ +export function maskToken(token) { + if (token.length <= 12) + return `${token.slice(0, 3)}…`; + return `${token.slice(0, 7)}…${token.slice(-4)}`; +} +/** Validate one sidecar field; returns the normalized value or undefined. */ +function cleanString(value) { + if (typeof value !== 'string') + return undefined; + const trimmed = value.trim(); + return trimmed === '' ? undefined : trimmed; +} +/** Coerce one numeric field into a clamped integer. */ +function clampInt(value, min, max) { + const numeric = typeof value === 'string' ? Number(value) : value; + if (typeof numeric !== 'number' || !Number.isFinite(numeric)) + return undefined; + return Math.min(max, Math.max(min, Math.trunc(numeric))); +} +/** Parse an on-disk document defensively (a torn file must not break boot). */ +function parseState(raw) { + try { + const value = JSON.parse(raw); + if (value === null || typeof value !== 'object' || Array.isArray(value)) + return { version: 1 }; + const source = value; + const state = { version: 1 }; + if (typeof source.enabled === 'boolean') + state.enabled = source.enabled; + const baseUrl = normalizeBaseUrl(source.baseUrl); + if (baseUrl !== undefined) + state.baseUrl = baseUrl; + const clientId = cleanString(source.clientId); + if (clientId !== undefined) + state.clientId = clientId.slice(0, 128); + const requestTimeoutMs = clampInt(source.requestTimeoutMs, 1000, 60_000); + if (requestTimeoutMs !== undefined) + state.requestTimeoutMs = requestTimeoutMs; + const defaultK = clampInt(source.defaultK, 1, 100); + if (defaultK !== undefined) + state.defaultK = defaultK; + const activityToken = cleanString(source.activityToken); + if (activityToken !== undefined) + state.activityToken = activityToken; + const memoryToken = cleanString(source.memoryToken); + if (memoryToken !== undefined) + state.memoryToken = memoryToken; + if (typeof source.summaryEnabled === 'boolean') + state.summaryEnabled = source.summaryEnabled; + const summaryMaxChars = clampInt(source.summaryMaxChars, 1000, 16_000); + if (summaryMaxChars !== undefined) + state.summaryMaxChars = summaryMaxChars; + const summaryToken = cleanString(source.summaryToken); + if (summaryToken !== undefined) + state.summaryToken = summaryToken; + return state; + } + catch { + return { version: 1 }; + } +} +/** + * In-memory + on-disk settings holder. + * + * Writes are atomic (tmp file + rename) and best-effort chmod 0600; the reader + * is tolerant, so one corrupt document degrades to defaults instead of + * failing the whole plugin activation. + */ +export class SettingsStore { + state; + file; + configDefaults; + constructor(rawConfig, file = settingsPath()) { + this.file = file; + this.configDefaults = { ...DEFAULT_SETTINGS, ...settingsFromConfig(rawConfig) }; + this.state = this.read(); + } + /** Absolute sidecar path (exposed for the status card). */ + get path() { + return this.file; + } + read() { + try { + return parseState(readFileSync(this.file, 'utf8')); + } + catch { + return { version: 1 }; + } + } + write(next) { + const directory = dirname(this.file); + mkdirSync(directory, { recursive: true }); + const temporary = `${this.file}.tmp`; + writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }); + renameSync(temporary, this.file); + try { + chmodSync(this.file, 0o600); + } + catch { + // Windows has no POSIX mode bits; the profile ACL is the real boundary. + } + } + /** Effective settings: config defaults, overridden by sidecar values. */ + settings() { + const resolved = { ...this.configDefaults }; + if (this.state.enabled !== undefined) + resolved.enabled = this.state.enabled; + if (this.state.baseUrl !== undefined) + resolved.baseUrl = this.state.baseUrl; + if (this.state.clientId !== undefined) + resolved.clientId = this.state.clientId; + if (this.state.requestTimeoutMs !== undefined) + resolved.requestTimeoutMs = this.state.requestTimeoutMs; + if (this.state.defaultK !== undefined) + resolved.defaultK = this.state.defaultK; + if (this.state.summaryEnabled !== undefined) + resolved.summaryEnabled = this.state.summaryEnabled; + if (this.state.summaryMaxChars !== undefined) + resolved.summaryMaxChars = this.state.summaryMaxChars; + return resolved; + } + /** The activity:write bearer token (sidecar first, env fallback). */ + activityToken() { + return this.state.activityToken ?? envToken('DSH_CLOUD_MEMORY_ACTIVITY_TOKEN') ?? ''; + } + /** The memory:read / memory:write bearer token. */ + memoryToken() { + return this.state.memoryToken ?? envToken('DSH_CLOUD_MEMORY_MEMORY_TOKEN') ?? ''; + } + /** The summary:write bearer token (optional; absent disables summaries). */ + summaryToken() { + return this.state.summaryToken ?? envToken('DSH_CLOUD_MEMORY_SUMMARY_TOKEN') ?? ''; + } + /** Masked snapshot for the browser card. */ + describe() { + const settings = this.settings(); + const activity = this.activityToken(); + const memory = this.memoryToken(); + 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) }, + statePath: this.file, + }; + } + /** + * Apply a partial patch from the settings card. + * + * Token fields follow "absent means keep": only a non-empty string replaces a + * stored token, and an explicit boolean `clear*` flag removes one. That way + * the browser never has to round-trip a secret it cannot read. + */ + patch(patch) { + const next = { ...this.state }; + if (patch.enabled !== undefined) { + if (typeof patch.enabled !== 'boolean') + return { ok: false, error: 'enabled must be a boolean' }; + next.enabled = patch.enabled; + } + if (patch.baseUrl !== undefined) { + const baseUrl = normalizeBaseUrl(patch.baseUrl); + if (baseUrl === undefined) + return { ok: false, error: 'baseUrl must be an http(s) URL' }; + next.baseUrl = baseUrl; + } + if (patch.clientId !== undefined) { + const clientId = cleanString(patch.clientId); + if (clientId === undefined) + return { ok: false, error: 'clientId must be a non-empty string' }; + next.clientId = clientId.slice(0, 128); + } + const activityToken = cleanString(patch.activityToken); + if (activityToken !== undefined) { + if (!activityToken.startsWith('cmt_')) + return { ok: false, error: 'activity token must start with cmt_' }; + next.activityToken = activityToken; + } + const memoryToken = cleanString(patch.memoryToken); + if (memoryToken !== undefined) { + if (!memoryToken.startsWith('cmt_')) + return { ok: false, error: 'memory token must start with cmt_' }; + next.memoryToken = memoryToken; + } + if (patch.requestTimeoutMs !== undefined) { + const requestTimeoutMs = clampInt(patch.requestTimeoutMs, 1000, 60_000); + if (requestTimeoutMs === undefined) + return { ok: false, error: 'requestTimeoutMs must be a number' }; + next.requestTimeoutMs = requestTimeoutMs; + } + if (patch.defaultK !== undefined) { + const defaultK = clampInt(patch.defaultK, 1, 100); + if (defaultK === undefined) + return { ok: false, error: 'defaultK must be a number' }; + next.defaultK = defaultK; + } + if (patch.summaryEnabled !== undefined) { + if (typeof patch.summaryEnabled !== 'boolean') + return { ok: false, error: 'summaryEnabled must be a boolean' }; + next.summaryEnabled = patch.summaryEnabled; + } + if (patch.summaryMaxChars !== undefined) { + const summaryMaxChars = clampInt(patch.summaryMaxChars, 1000, 16_000); + if (summaryMaxChars === undefined) + return { ok: false, error: 'summaryMaxChars must be a number' }; + next.summaryMaxChars = summaryMaxChars; + } + 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; + } + if (patch.clearSummaryToken === true) + delete next.summaryToken; + if (patch.clearActivityToken === true) + delete next.activityToken; + if (patch.clearMemoryToken === true) + delete next.memoryToken; + this.write(next); + this.state = next; + return { ok: true }; + } + /** File size in bytes, for a "sidecar exists" hint in the card. */ + size() { + try { + return statSync(this.file).size; + } + catch { + return undefined; + } + } +} diff --git a/lib/tools.js b/lib/tools.js new file mode 100644 index 0000000..2895ee3 --- /dev/null +++ b/lib/tools.js @@ -0,0 +1,286 @@ +/** + * 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)。请在 /cloud-memory 页面开启后再试。'); + } + const token = deps.memoryToken(); + if (token === '') { + throw new Error('未配置记忆令牌。请在 /cloud-memory 页面填入 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)]; +} +/** List the cloud skill center inventory (skills sync keeps local copies current). */ +function skillListTool(deps) { + return { + name: 'skill_list', + description: '列出云端技能中心的全部技能(名称、说明、版本)。技能会自动同步到本机技能目录,由 DSH 直接加载;此工具只用于查看云端有哪些技能。', + parameters: { type: 'object', properties: {}, additionalProperties: false }, + output: { + schema: { type: 'object', properties: { skills: { type: 'array', items: { type: 'object' } } }, required: ['skills'], additionalProperties: true }, + render: renderJson, + }, + async execute() { + requireMemoryToken(deps); + const result = await deps.client().listSkills(); + if (!result.ok) + throw new Error(`技能列表读取失败:${describeError(result.error)}`); + const skills = (result.data.items ?? []).map((item) => ({ + name: item.name, + description: item.description ?? '', + revision: item.revision ?? null, + files: item.files ?? null, + enabled: item.enabled ?? true, + })); + return { skills }; + }, + }; +} +/** Build the skill-facing tools for one plugin instance. */ +export function createSkillTools(deps) { + return [skillListTool(deps)]; +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..24d894c --- /dev/null +++ b/package.json @@ -0,0 +1,82 @@ +{ + "name": "dsh-cloud-memory", + "version": "0.4.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", + "main": "lib/index.js", + "exports": { + ".": "./lib/index.js", + "./client": "./client/index.js", + "./cordis.patch.yml": "./cordis.patch.yml", + "./package.json": "./package.json", + "./mnemon-provider": "./lib/mnemon/index.js" + }, + "files": [ + "lib", + "client", + "cordis.patch.yml", + "README.md", + "LICENSE" + ], + "engines": { + "node": ">=20" + }, + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web" + } + }, + "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" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "^4.0.2", + "react": "^18.2.0", + "dsh-mnemon-source-memory-spaces": "^0.5.1" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "dsh-mnemon-source-memory-spaces": { + "optional": true + } + }, + "devDependencies": { + "@deepseek-ai/cordis": "^4.0.4", + "@deepseek-ai/dsh-client-locale": "0.2.1-rc.3", + "@deepseek-ai/dsh-client-ui-settings": "0.2.1-rc.3", + "@deepseek-ai/dsh-client-ui-sidebar-right": "0.2.1-rc.3", + "@deepseek-ai/dsh-client-ui-slots": "0.2.1-rc.3", + "@deepseek-ai/dsh-host-webserver": "0.2.1-rc.3", + "@deepseek-ai/dsh-session": "0.2.1-rc.3", + "@deepseek-ai/dsh-tools": "0.2.1-rc.3", + "@types/node": "^22.20.0", + "@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" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "keywords": [ + "agent", + "cloud-memory", + "dsh", + "dsh-plugin", + "longmemory", + "memory", + "mnemon" + ], + "author": "dsh-cloud-memory contributors" +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..13402e2 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,1269 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@deepseek-ai/cordis': + specifier: ^4.0.4 + version: 4.0.5 + '@deepseek-ai/dsh-client-locale': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-client-ui-settings': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-client-ui-sidebar-right': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-client-ui-slots': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-host-webserver': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-tools': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(1f5d0a9b849aaa1244bc4f2e453f609a) + '@types/node': + specifier: ^22.20.0 + version: 22.20.5 + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + react: + specifier: ^18.2.0 + version: 18.3.1 + tsdown: + specifier: ^0.22.2 + version: 0.22.14(typescript@5.9.3) + typescript: + specifier: ^5.6.0 + version: 5.9.3 + +packages: + + '@deepseek-ai/cordis@4.0.5': + resolution: {integrity: sha512-Sktq5axy0owk9PdnivBRNOJjHEVEibCt0+TDDZcv0+UH2KS1M910fX4kn5y45YFsrpZIi1mJf/1s5VzywMUnyg==} + hasBin: true + peerDependencies: + '@deepseek-ai/cordis-plugin-include': ~1.0.10 + '@deepseek-ai/cordis-plugin-loader': ~1.0.6 + peerDependenciesMeta: + '@deepseek-ai/cordis-plugin-include': + optional: true + '@deepseek-ai/cordis-plugin-loader': + optional: true + + '@deepseek-ai/cosmokit@1.8.6': + resolution: {integrity: sha512-ZSD/fN52L498LBIOYwjIOlaLv5veY6ZEwI2yzvZUKQtctn0QAPqu8tKdJ+OF5+Tv6NBq1U+wJWH+QI6OGy5EvQ==} + + '@deepseek-ai/dsh-agent@0.2.1-rc.3': + resolution: {integrity: sha512-S6x/deneAsd+pOgecRLM1PC1No9O472kHjS9pS57nuTXi2Vtdo9l7qF+q7PfiHRezL5dxv5gUBQMORPmIYDNvQ==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + '@deepseek-ai/dsh-typert-protocol': 0.2.1-rc.3 + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3 + '@deepseek-ai/dsh-workspace': 0.2.1-rc.3 + peerDependenciesMeta: + '@deepseek-ai/dsh-workspace': + optional: true + + '@deepseek-ai/dsh-brand@0.2.1-rc.3': + resolution: {integrity: sha512-bPpKuu05gZj7gdW15z6PL2dz4+A4MDEafgWOrhexFO7f08g1NeI4fhE4YNOxd8N2ua+tZJjsKCMAIobFMAaGOw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-client-locale@0.2.1-rc.3': + resolution: {integrity: sha512-/WpBT8gEivbD/yndgefYM09SysDcLcd8/Ov5zmC+A1EPNv6UoQ+4avPT6tkwT46XaG4XoJXmVglDOmfg/vUFGg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-client-ui-settings@0.2.1-rc.3': + resolution: {integrity: sha512-vBH1A1DU85yeqZ02VeaOCZd5z7Pr77Bq0pSBH6ehFus2iZ88n4LuEhZxwMIYHf55LrRRxOQCpIbtEjmSbN5jzw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-client-ui-sidebar-right@0.2.1-rc.3': + resolution: {integrity: sha512-BmBbGjHwP/q+DoNc0suvVTFlqcU0Bv0QGZJ67pfKNNkUjMtQtt77+r43vJHsSfDQIO+EzxoXUSfTdnTWxE42Bg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-client-ui-slots@0.2.1-rc.3': + resolution: {integrity: sha512-KV/f/yOm4YXSuDK2N0XtKNWqHZRxMbmZdtblVpx/D2s3mKoLHOdAxEyVp4F+lgjzuhUCGUovQHWjBcVhho5WuA==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-fs@0.2.1-rc.3': + resolution: {integrity: sha512-tENLWe471WlAXMc13J4cns8xU6lFyu1smwpkSKR85vhGr6FyWZhTlpVohZYm66LbwKTmSWiDhd9Urk7VxN9B9w==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3 + + '@deepseek-ai/dsh-host-webserver@0.2.1-rc.3': + resolution: {integrity: sha512-zLv507HZ20pDoICxRH9+XOFzjZ/cNcVm/fy3QXHDAqXJWcl4buFmGc2BaYZtaWkWoBZ1YHj2+Dx7Wy8Q3H5q/g==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-llm@0.2.1-rc.3': + resolution: {integrity: sha512-7Fq7zS3yQb1J1PsaNmahQ1gHDdsb338UhTkmZCexlNecmc5I44c/PbkHcT5pJ5SO4hnLplJOdDhiIMFpvvyAaw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-ptc-runtime@0.2.1-rc.3': + resolution: {integrity: sha512-nFUzb1abLvCQfUsrp/fMKQMCYU+O+ttiwqUFMa+uO4rFE6Nd+xNjus3V5aaqyy78jdciyBzzNysblZeryJAcXQ==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3 + + '@deepseek-ai/dsh-sandbox-policy@0.2.1-rc.3': + resolution: {integrity: sha512-/PlQEx/F6pwjjC/eOEBCHWG9InCu+aSEIC1k9V32noS43B/KS/FRSgP+SZ0YkbjMfk6iyS27sgglJDIY7RG1zQ==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + + '@deepseek-ai/dsh-sandbox@0.2.1-rc.3': + resolution: {integrity: sha512-7JXzEw2FBNAD3hNhiMzpxCjm8Zedc6DpFfsJfvh1Uh4HuIzX2BFEtzjvEUSwXGSWA+pCZOEvaYD9v0sZoMx3fQ==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + + '@deepseek-ai/dsh-scope@0.2.1-rc.3': + resolution: {integrity: sha512-3oCu1zZhbJTzV9TtYXjVUyxc9yOaQOYzxSGQvMuZ/q/O7/1Y1ofIS2j2GETfc79mCoiQIoQAjr2gu/ncXSgALw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-session-projection@0.2.1-rc.3': + resolution: {integrity: sha512-kyDxXb0avo0m4ZmAb8P+X6T/963NOZCvH/MgrWl3AUs5fHkXA6NfeVnalj488o5RpkRtZdqI7KtCEFNkyKAEsA==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + + '@deepseek-ai/dsh-session@0.2.1-rc.3': + resolution: {integrity: sha512-z1Dfn6yB2YMm9iNThPHaIYCx0Y/mKjm+fMrWFtnPZmX0fJXVmTIr4RAfLF7ZFJk6qd52SUl8d2uX+uNbrPJESg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + + '@deepseek-ai/dsh-system-prompt@0.2.1-rc.3': + resolution: {integrity: sha512-2CXnigUF0N2Ps0AG/lOvvY9qeEhvo5uUCGCqvoGrH9IWbhoh/tfvzo9KTa5svyZIBW6mLMAyLyHOdi7f1T9tfg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + + '@deepseek-ai/dsh-timeout@0.2.1-rc.3': + resolution: {integrity: sha512-DOuGjmY5dMlXqXqhuXlHNgEVajTLTYuj/EabS5b8IIBC5VN36YDOtyPgaT8aq1+LI7XoReDMUYQRUHCI3SOXqw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-tools@0.2.1-rc.3': + resolution: {integrity: sha512-fHmhIFaztPt9+uvOlk3p4wXMU62F+TRe0ozVPasV3seIsFcxpca74QGSK5dFHICDhKIY1T9MUh0F3itMTdMi3A==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-ptc-runtime': 0.2.1-rc.3 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3 + '@deepseek-ai/dsh-sandbox-policy': 0.2.1-rc.3 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + '@deepseek-ai/dsh-user-approval': 0.2.1-rc.3 + '@deepseek-ai/dsh-working-directory': 0.2.1-rc.3 + + '@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3': + resolution: {integrity: sha512-ycKq2jF0h/iE/gwQFXn7Fx/pdKsVnPe6rkaA8F0SIZ8QfbAK8KcYmpG1Kn9zjwZAWPyb6pLMhD2GI/gXlM7f0Q==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-user-approval@0.2.1-rc.3': + resolution: {integrity: sha512-n2AG2Oh3/32UNStxdkoTOYwheOjSjrJWPj9pPvgISw6vBURPUYrquoVD0AmvmV8TeWpxaCKIGsFNO08yrP9ODw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + + '@deepseek-ai/dsh-util-crypto@0.2.1-rc.3': + resolution: {integrity: sha512-AKznKjQmc2JHDQO+DV2Z68zwGrr3+0qAkxNqZE3SnuBTpO7TeTaS7v2cOzQi81EhZUlYFArmKEbmjcsCrsQvvw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-util-values@0.2.1-rc.3': + resolution: {integrity: sha512-YyHu30xQBdp7sIr4ZNUliNxm2S9yRNOwdUPiBvfQZ+KaRtekI2j+T8+TFy7qgyBiGM7YYiG0xzJVibS894WIrg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-working-directory@0.2.1-rc.3': + resolution: {integrity: sha512-Ec/MG+j4jWu/4+ym9UieB2zHt22mwSFfS2s2xZfnoCQIrxkIH5ayVcY1SNttrmHFYDwsyZEG4YY2dzYRtcuIfw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3 + '@deepseek-ai/dsh-fs': 0.2.1-rc.3 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + + '@deepseek-ai/schemastery@3.18.5': + resolution: {integrity: sha512-Mnobvqf9rHsZYv4g5edj5ddxS1oF1kIdSlz0DunUgnY3LWG5F26MqvH3YOOsSaodCgyzJ16OMN9O99/s5Crtdw==} + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@quansync/fs@1.1.0': + resolution: {integrity: sha512-qAPG/t3HqML1TlN7sY/pTbEjzFVAKsMjNNMGheyDosro+kT4iw2KCUoHcVdmliwWjorm4elZbgNQyU2eD97eDg==} + + '@rolldown/binding-android-arm-eabi@1.2.16': + resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.16': + resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@types/node@22.20.5': + resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} + + '@types/prop-types@15.7.15': + resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==} + + '@types/react@18.3.31': + resolution: {integrity: sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==} + + '@yuku-codegen/binding-android-arm64@0.8.7': + resolution: {integrity: sha512-C/0zV5IhgVdYhGJTwrY0v8dknxlhiKwtVJkMUaexu9/QvRmzlV4vfU3hZlUSgqc2BxQHntL1mCVbDq8j0FRFDw==} + cpu: [arm64] + os: [android] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-darwin-arm64@0.8.7': + resolution: {integrity: sha512-/u+REDMI4a0/lsJXTM4c53/w31OGZLOReZIyg62uhgLs0kc8NHsj/nOcxTdlQjq5gi0zhdkccD9LaLTXcdzPvw==} + cpu: [arm64] + os: [darwin] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-darwin-x64@0.8.7': + resolution: {integrity: sha512-sMMzFOwCo4WXR+/6zIBThOocSC50iIIZZdfiIDbaLvj0Ax/rWt/iavyfEAqajyvzydLyCqR/ZItdLWSRlu1umw==} + cpu: [x64] + os: [darwin] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-freebsd-x64@0.8.7': + resolution: {integrity: sha512-MpdpKXix9P+Y1rKgjvcNeNtGjXeL1CmttNhYINrWls8kRpm4xM/oBGTmn6w7to8lAlwj5jm8q03dQPl5mRv4Qw==} + cpu: [x64] + os: [freebsd] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-arm-gnu@0.8.7': + resolution: {integrity: sha512-rr1srFLlPAmC1vtxfc9C1YLDe3iH09YjfSeeIidBqKhzx1MATjOAq4mjlRUOnhr/L27MotWIYOFKwVsd5JZFOg==} + cpu: [arm] + os: [linux] + libc: [glibc] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-arm-musl@0.8.7': + resolution: {integrity: sha512-eAufXh8qBRpiSO6ueaMDL+yyoXIGLhpUce72YbcACtZU2qhExwBIJyEtQf5kH2Ki0X2aqkSjSfog4OPtKXan3Q==} + cpu: [arm] + os: [linux] + libc: [musl] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-arm64-gnu@0.8.7': + resolution: {integrity: sha512-gw4w6wPoHObBrdIC4duVWLmJOvpdE25j5D7yrM5mACNlK4klRz/lv8hK+ssQk9EJHBgZjSaqZIJVFgqNYbfv7A==} + cpu: [arm64] + os: [linux] + libc: [glibc] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-arm64-musl@0.8.7': + resolution: {integrity: sha512-L68N6Y4XkqcIaKo3Ra88JEvBEH4AHff44A4INcrxeVWZ8CZtu2tCpfVxe3hR8qQQMcvBSQlDn24KpkCKEhVvfA==} + cpu: [arm64] + os: [linux] + libc: [musl] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-x64-gnu@0.8.7': + resolution: {integrity: sha512-dzyAbltJmf3Cqlb8HcFuYIf5Yn0fl1vTr3XJ9HiVNNvOlhqPSArOqtw9vI1p6/VTXTjrMLXlU+s+/kNHiIy/Cw==} + cpu: [x64] + os: [linux] + libc: [glibc] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-x64-musl@0.8.7': + resolution: {integrity: sha512-Otw4MH3404q0Bbvl+YTdW9aoUV5vXmUw8260bWvt1XlaoIX/ceSgI4ygheRDMfBPoHt6FDayQaO9OLVUZAgkFA==} + cpu: [x64] + os: [linux] + libc: [musl] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-win32-arm64@0.8.7': + resolution: {integrity: sha512-qo/jyrzryiBuKEsFiuWaBCBe3tRMynQ0qFWFgOEjcCMQeZfBm+wKiVEUEFXXLc7bh8YezguAWp0Mtnhq4ARNyA==} + cpu: [arm64] + os: [win32] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-win32-x64@0.8.7': + resolution: {integrity: sha512-D5lDsVDx6m00E6bWySlWdH72Ca4TPSaphDqB6QjU6MpuNLIJqoGoatYyq2rOmBE8Zv/kunot/o58KGL03P3eiA==} + cpu: [x64] + os: [win32] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-parser/binding-android-arm64@0.8.7': + resolution: {integrity: sha512-eGKYiUDX7Y0V7tDTmg+JTVnXnjMqfXXsorZ+EDf5kxwchQ3Or1HS14MzI2fw+jFhHR85fCWt+mtX33Yao73hIQ==} + cpu: [arm64] + os: [android] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-darwin-arm64@0.8.7': + resolution: {integrity: sha512-Re0RHelKLnjEURulY2/KxW+Ngb8zuNA4BRZuMwgGQNzVumT6u4U2N2hc01oeYVNVof0i7GrXE4UCNBgbpRRnjQ==} + cpu: [arm64] + os: [darwin] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-darwin-x64@0.8.7': + resolution: {integrity: sha512-Hn8DROtQkjlA1ACbPgj4a7eP9IuVOI504oiTwpkWPbpaDWD9KdmnVYCqW+1LfenNK/g7O9NhWGpXEdaCNX7lIA==} + cpu: [x64] + os: [darwin] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-freebsd-x64@0.8.7': + resolution: {integrity: sha512-bAP2OV8wRuzplX/jYxv9+vvqQT8JxyNphI8fLfXGL054Xs+4/J5u33cIm3y4rxY8rdoLmmdiJs2Tq7r7lrDRfA==} + cpu: [x64] + os: [freebsd] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-arm-gnu@0.8.7': + resolution: {integrity: sha512-kTYwJQQgmZeAWdDIWabiReIZMpmfLueIj1tCmjStUtFGhR1Z0qwxonKVfUC4N7h/VhGGzLZ//7O1kgt1QKqgCg==} + cpu: [arm] + os: [linux] + libc: [glibc] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-arm-musl@0.8.7': + resolution: {integrity: sha512-uL4jE8HPT2BLlxAXyD10LqgPuXa9eDa0BKpCdSANmzIJghq/2eZo3/gQNtaxPZMupWoxjYzSad9IXrwu7aYPXQ==} + cpu: [arm] + os: [linux] + libc: [musl] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-arm64-gnu@0.8.7': + resolution: {integrity: sha512-3gVN4pWSKZmXiNX7cU164dR9MPvesCHnlH6nPfpK+yQsCuYphjKKplcb4SnZBrhiqmXbgb2HR0c2TS0IZUPhgA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-arm64-musl@0.8.7': + resolution: {integrity: sha512-S0mwfEjoLpxzXeZw802Wa4RaELsQiPtWqG6INcy8j4GtvNFtl4LCX3eGO1XLn9pyLAISLzTRyU3zUCBUPin8lg==} + cpu: [arm64] + os: [linux] + libc: [musl] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-x64-gnu@0.8.7': + resolution: {integrity: sha512-lnbWdPmerE5D1uH1G4IEZKnPzCrWCStRGrtgpSIe1RibAo5bZIjDbbbPYXmMHCEh4F+x/JaJpElh26a3r+BPbg==} + cpu: [x64] + os: [linux] + libc: [glibc] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-x64-musl@0.8.7': + resolution: {integrity: sha512-769uwndMvMzUvATWbAcEvyLHKA+DzhHSCl/obBUrRdYfRo26yxui6S8y3z7uJ+Naup7UKrDxrpK7OnQkxkl9KQ==} + cpu: [x64] + os: [linux] + libc: [musl] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-win32-arm64@0.8.7': + resolution: {integrity: sha512-mEB/9PlaAkisJ6KWGz0zvywXoU6+80dTlR2LwS7s/jcXXoU6fm2+sitBZXtqu3+Q4DcDgPxM45uWMCzPs0TSRw==} + cpu: [arm64] + os: [win32] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-win32-x64@0.8.7': + resolution: {integrity: sha512-8vNB2DP0ou61nGb8tc/qfi41gfyDXz1MHr2zqL3nR+cJ6CEbiuWV/l/a/vv151gCgiZLLAyGkQGENpozdg716w==} + cpu: [x64] + os: [win32] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-toolchain/types@0.8.7': + resolution: {integrity: sha512-2Z53dNxAJL6UvFoIrDZvYf3zlO8s4VJK4O2hhaB4mXVwwpX/7ajtss3cmfqKvamlNLWyt9FSWs4eoYdlbxpnHA==} + + ansis@4.4.0: + resolution: {integrity: sha512-9k3v7xcHwgdO/DruxGIg4HtjvlAZlcnsX/mzqUb1t3NkYnl9kK2UJ+Gq0io+vQf7iT//BD/HB/NBkUR1LWxoeA==} + engines: {node: '>=14'} + + bytes@3.1.2: + resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} + engines: {node: '>= 0.8'} + + cac@7.1.0: + resolution: {integrity: sha512-LMDU/U2yA4IPIY8KT0NsNPWEYZvAMkbgyspxJ6btJaYV+WMDOHAZCmB0lsTObiHaRS1V/ztKAl7+TSkTqXyeoA==} + engines: {node: '>=20.19.0'} + + compressible@2.0.18: + resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==} + engines: {node: '>= 0.6'} + + compression@1.8.2: + resolution: {integrity: sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==} + engines: {node: '>= 0.8.0'} + + content-type@2.1.0: + resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} + engines: {node: '>=18'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + debug@2.6.9: + resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + defu@6.1.7: + resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} + + destroy@1.2.0: + resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==} + engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + + dts-resolver@3.0.0: + resolution: {integrity: sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q==} + engines: {node: ^22.18.0 || >=24.0.0} + peerDependencies: + oxc-resolver: '>=11.0.0' + peerDependenciesMeta: + oxc-resolver: + optional: true + + empathic@2.1.0: + resolution: {integrity: sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==} + engines: {node: '>=14'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + get-tsconfig@5.0.0-beta.5: + resolution: {integrity: sha512-/6gFNr0N04nob252sTQxyFLi3eKFRqIg1I87YcqAMT1i6SQrSF6KujUEQrtrjMV0H/eejTCltLdDSTEMzHbnsQ==} + engines: {node: '>=20.20.0'} + + hookable@6.1.2: + resolution: {integrity: sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg==} + + import-without-cache@0.4.1: + resolution: {integrity: sha512-vXoV9PjKHEednCUu01e98TkImxy67e3BJXbTIOmIq4Hyzw3IAwYRcuPkfeTzJzwyyts4kjuA73x+pWJLc4f86A==} + engines: {node: ^22.18.0 || >=24.0.0} + + ipaddr.js@2.5.0: + resolution: {integrity: sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==} + engines: {node: '>= 10'} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + loose-envify@1.4.0: + resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} + hasBin: true + + mime-db@1.54.0: + resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} + engines: {node: '>= 0.6'} + + ms@2.0.0: + resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==} + + negotiator@0.6.4: + resolution: {integrity: sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==} + engines: {node: '>= 0.6'} + + negotiator@1.1.0: + resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} + engines: {node: '>=18'} + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + on-headers@1.1.0: + resolution: {integrity: sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==} + engines: {node: '>= 0.8'} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + quansync@1.0.0: + resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==} + + react@18.3.1: + resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==} + engines: {node: '>=0.10.0'} + + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + + rolldown-plugin-dts@0.27.14: + resolution: {integrity: sha512-ZvuDDwoIpRK9RPxDXratCpklFO9QZZWndf/sd0VBFb4LEj0jj07UcHK9OCh7V4XiFz2Z89ziyBC2K6tJiDjrbw==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@typescript/native-preview': '*' + '@volar/typescript': ~2.4.0 + rolldown: ^1.0.0 + typescript: ^5.0.0 || ^6.0.0 || ~7.0.0 + vue-tsc: ~3.2.0 || ~3.3.0 + peerDependenciesMeta: + '@typescript/native-preview': + optional: true + '@volar/typescript': + optional: true + typescript: + optional: true + vue-tsc: + optional: true + + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + + tsdown@0.22.14: + resolution: {integrity: sha512-ule7Y+fsAN2iZbLDoo7C4KYljFJNJJ+fLshyn+9gozeTspVersWHxwdGB+Dm2hzA38s6muFnUTl0jK3vJm9ifQ==} + engines: {node: ^22.18.0 || >=24.11.0} + hasBin: true + peerDependencies: + '@arethetypeswrong/core': ^0.18.1 + '@tsdown/css': 0.22.14 + '@tsdown/exe': 0.22.14 + '@vitejs/devtools': '*' + publint: ^0.3.8 + tsx: '*' + typescript: ^5.0.0 || ^6.0.0 || ^7.0.0 + unplugin-unused: ^0.5.0 + unrun: '*' + peerDependenciesMeta: + '@arethetypeswrong/core': + optional: true + '@tsdown/css': + optional: true + '@tsdown/exe': + optional: true + '@vitejs/devtools': + optional: true + publint: + optional: true + tsx: + optional: true + typescript: + optional: true + unplugin-unused: + optional: true + unrun: + optional: true + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + unconfig-core@7.5.0: + resolution: {integrity: sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w==} + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + vary@1.1.2: + resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} + engines: {node: '>= 0.8'} + + verkit@0.3.2: + resolution: {integrity: sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg==} + engines: {node: '>=18.12.0'} + + yuku-ast@0.8.7: + resolution: {integrity: sha512-h6+4bDfyootiMB9vckk5uKo5r5j0GHrkr17FQTDNfEsFT3DWlN9uu1HJwQwc64pgmLCI945fWM3lbTIqxjT3GQ==} + + yuku-codegen@0.8.7: + resolution: {integrity: sha512-adwDZSh8oVDzhE6Du9PwVWxcOxeV0e2EVhUuMKWfhSY4wkrDq9eqixlxFF3l/XGUV1E7UFzhpz9393MUumkyNw==} + + yuku-parser@0.8.7: + resolution: {integrity: sha512-vRD9nwt4L3aYpxNqeSC4WqLv58xrXef0Ong1Mc45CTXTIpvLafx7JO05sczmQZwdLEZvywrLOGdNC5+Rp5N1BQ==} + + zod@4.4.3: + resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} + + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + +snapshots: + + '@deepseek-ai/cordis@4.0.5': + dependencies: + '@deepseek-ai/cosmokit': 1.8.6 + '@standard-schema/spec': 1.1.0 + + '@deepseek-ai/cosmokit@1.8.6': {} + + '@deepseek-ai/dsh-agent@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-typert-protocol': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + + '@deepseek-ai/dsh-brand@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-client-locale@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-client-ui-settings@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-client-ui-sidebar-right@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-client-ui-slots@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-fs@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-brand@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + + '@deepseek-ai/dsh-host-webserver@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/schemastery': 3.18.5 + compression: 1.8.2 + ipaddr.js: 2.5.0 + negotiator: 1.1.0 + transitivePeerDependencies: + - supports-color + + '@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-timeout': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-typert-protocol': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-util-crypto': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/schemastery': 3.18.5 + zod: 4.4.3 + + '@deepseek-ai/dsh-ptc-runtime@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + + '@deepseek-ai/dsh-sandbox-policy@0.2.1-rc.3(1809d3b5f9b8552c21c008788fe3c75e)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/schemastery': 3.18.5 + zod: 4.4.3 + + '@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + + '@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + zod: 4.4.3 + + '@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + + '@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-timeout@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-tools@0.2.1-rc.3(1f5d0a9b849aaa1244bc4f2e453f609a)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-ptc-runtime': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))) + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-sandbox-policy': 0.2.1-rc.3(1809d3b5f9b8552c21c008788fe3c75e) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-user-approval': 0.2.1-rc.3(f3a61cdc614c420235807a61121b4b4a) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-working-directory': 0.2.1-rc.3(b3db524bc35e44edbf239e3bbf3fca0a) + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + zod: 4.6.7 + + '@deepseek-ai/dsh-user-approval@0.2.1-rc.3(f3a61cdc614c420235807a61121b4b4a)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-util-crypto@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-working-directory@0.2.1-rc.3(b3db524bc35e44edbf239e3bbf3fca0a)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-fs': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-brand@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/schemastery': 3.18.5 + zod: 4.6.7 + + '@deepseek-ai/schemastery@3.18.5': + dependencies: + '@deepseek-ai/cosmokit': 1.8.6 + '@standard-schema/spec': 1.1.0 + + '@oxc-project/types@0.156.0': {} + + '@quansync/fs@1.1.0': + dependencies: + quansync: 1.0.0 + + '@rolldown/binding-android-arm-eabi@1.2.16': + optional: true + + '@rolldown/binding-android-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-x64@1.2.16': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.16': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.16': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.16': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.16': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.16': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@standard-schema/spec@1.1.0': {} + + '@types/node@22.20.5': + dependencies: + undici-types: 6.21.0 + + '@types/prop-types@15.7.15': {} + + '@types/react@18.3.31': + dependencies: + '@types/prop-types': 15.7.15 + csstype: 3.2.3 + + '@yuku-codegen/binding-android-arm64@0.8.7': + optional: true + + '@yuku-codegen/binding-darwin-arm64@0.8.7': + optional: true + + '@yuku-codegen/binding-darwin-x64@0.8.7': + optional: true + + '@yuku-codegen/binding-freebsd-x64@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-arm-gnu@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-arm-musl@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-arm64-gnu@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-arm64-musl@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-x64-gnu@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-x64-musl@0.8.7': + optional: true + + '@yuku-codegen/binding-win32-arm64@0.8.7': + optional: true + + '@yuku-codegen/binding-win32-x64@0.8.7': + optional: true + + '@yuku-parser/binding-android-arm64@0.8.7': + optional: true + + '@yuku-parser/binding-darwin-arm64@0.8.7': + optional: true + + '@yuku-parser/binding-darwin-x64@0.8.7': + optional: true + + '@yuku-parser/binding-freebsd-x64@0.8.7': + optional: true + + '@yuku-parser/binding-linux-arm-gnu@0.8.7': + optional: true + + '@yuku-parser/binding-linux-arm-musl@0.8.7': + optional: true + + '@yuku-parser/binding-linux-arm64-gnu@0.8.7': + optional: true + + '@yuku-parser/binding-linux-arm64-musl@0.8.7': + optional: true + + '@yuku-parser/binding-linux-x64-gnu@0.8.7': + optional: true + + '@yuku-parser/binding-linux-x64-musl@0.8.7': + optional: true + + '@yuku-parser/binding-win32-arm64@0.8.7': + optional: true + + '@yuku-parser/binding-win32-x64@0.8.7': + optional: true + + '@yuku-toolchain/types@0.8.7': {} + + ansis@4.4.0: {} + + bytes@3.1.2: {} + + cac@7.1.0: {} + + compressible@2.0.18: + dependencies: + mime-db: 1.54.0 + + compression@1.8.2: + dependencies: + bytes: 3.1.2 + compressible: 2.0.18 + debug: 2.6.9 + destroy: 1.2.0 + negotiator: 0.6.4 + on-headers: 1.1.0 + safe-buffer: 5.2.1 + vary: 1.1.2 + transitivePeerDependencies: + - supports-color + + content-type@2.1.0: {} + + csstype@3.2.3: {} + + debug@2.6.9: + dependencies: + ms: 2.0.0 + + defu@6.1.7: {} + + destroy@1.2.0: {} + + dts-resolver@3.0.0: {} + + empathic@2.1.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + get-tsconfig@5.0.0-beta.5: + dependencies: + resolve-pkg-maps: 1.0.0 + + hookable@6.1.2: {} + + import-without-cache@0.4.1: {} + + ipaddr.js@2.5.0: {} + + js-tokens@4.0.0: {} + + loose-envify@1.4.0: + dependencies: + js-tokens: 4.0.0 + + mime-db@1.54.0: {} + + ms@2.0.0: {} + + negotiator@0.6.4: {} + + negotiator@1.1.0: + dependencies: + content-type: 2.1.0 + + obug@2.2.1: {} + + on-headers@1.1.0: {} + + picomatch@4.0.7: {} + + quansync@1.0.0: {} + + react@18.3.1: + dependencies: + loose-envify: 1.4.0 + + resolve-pkg-maps@1.0.0: {} + + rolldown-plugin-dts@0.27.14(rolldown@1.2.16)(typescript@5.9.3): + dependencies: + dts-resolver: 3.0.0 + get-tsconfig: 5.0.0-beta.5 + obug: 2.2.1 + rolldown: 1.2.16 + yuku-ast: 0.8.7 + yuku-codegen: 0.8.7 + yuku-parser: 0.8.7 + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - oxc-resolver + + rolldown@1.2.16: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.16 + '@rolldown/binding-android-arm64': 1.2.16 + '@rolldown/binding-darwin-arm64': 1.2.16 + '@rolldown/binding-darwin-x64': 1.2.16 + '@rolldown/binding-freebsd-x64': 1.2.16 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.16 + '@rolldown/binding-linux-arm64-gnu': 1.2.16 + '@rolldown/binding-linux-arm64-musl': 1.2.16 + '@rolldown/binding-linux-ppc64-gnu': 1.2.16 + '@rolldown/binding-linux-s390x-gnu': 1.2.16 + '@rolldown/binding-linux-x64-gnu': 1.2.16 + '@rolldown/binding-linux-x64-musl': 1.2.16 + '@rolldown/binding-openharmony-arm64': 1.2.16 + '@rolldown/binding-win32-arm64-msvc': 1.2.16 + '@rolldown/binding-win32-x64-msvc': 1.2.16 + + safe-buffer@5.2.1: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tree-kill@1.2.2: {} + + tsdown@0.22.14(typescript@5.9.3): + dependencies: + ansis: 4.4.0 + cac: 7.1.0 + defu: 6.1.7 + empathic: 2.1.0 + hookable: 6.1.2 + import-without-cache: 0.4.1 + obug: 2.2.1 + picomatch: 4.0.7 + rolldown: 1.2.16 + rolldown-plugin-dts: 0.27.14(rolldown@1.2.16)(typescript@5.9.3) + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + tree-kill: 1.2.2 + unconfig-core: 7.5.0 + verkit: 0.3.2 + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - '@typescript/native-preview' + - '@volar/typescript' + - oxc-resolver + - vue-tsc + + typescript@5.9.3: {} + + unconfig-core@7.5.0: + dependencies: + '@quansync/fs': 1.1.0 + quansync: 1.0.0 + + undici-types@6.21.0: {} + + vary@1.1.2: {} + + verkit@0.3.2: {} + + yuku-ast@0.8.7: + dependencies: + '@yuku-toolchain/types': 0.8.7 + + yuku-codegen@0.8.7: + dependencies: + '@yuku-toolchain/types': 0.8.7 + optionalDependencies: + '@yuku-codegen/binding-android-arm64': 0.8.7 + '@yuku-codegen/binding-darwin-arm64': 0.8.7 + '@yuku-codegen/binding-darwin-x64': 0.8.7 + '@yuku-codegen/binding-freebsd-x64': 0.8.7 + '@yuku-codegen/binding-linux-arm-gnu': 0.8.7 + '@yuku-codegen/binding-linux-arm-musl': 0.8.7 + '@yuku-codegen/binding-linux-arm64-gnu': 0.8.7 + '@yuku-codegen/binding-linux-arm64-musl': 0.8.7 + '@yuku-codegen/binding-linux-x64-gnu': 0.8.7 + '@yuku-codegen/binding-linux-x64-musl': 0.8.7 + '@yuku-codegen/binding-win32-arm64': 0.8.7 + '@yuku-codegen/binding-win32-x64': 0.8.7 + + yuku-parser@0.8.7: + dependencies: + '@yuku-toolchain/types': 0.8.7 + yuku-ast: 0.8.7 + optionalDependencies: + '@yuku-parser/binding-android-arm64': 0.8.7 + '@yuku-parser/binding-darwin-arm64': 0.8.7 + '@yuku-parser/binding-darwin-x64': 0.8.7 + '@yuku-parser/binding-freebsd-x64': 0.8.7 + '@yuku-parser/binding-linux-arm-gnu': 0.8.7 + '@yuku-parser/binding-linux-arm-musl': 0.8.7 + '@yuku-parser/binding-linux-arm64-gnu': 0.8.7 + '@yuku-parser/binding-linux-arm64-musl': 0.8.7 + '@yuku-parser/binding-linux-x64-gnu': 0.8.7 + '@yuku-parser/binding-linux-x64-musl': 0.8.7 + '@yuku-parser/binding-win32-arm64': 0.8.7 + '@yuku-parser/binding-win32-x64': 0.8.7 + + zod@4.4.3: {} + + zod@4.6.7: {} diff --git a/scripts/pack-guard.mjs b/scripts/pack-guard.mjs new file mode 100644 index 0000000..56c04c5 --- /dev/null +++ b/scripts/pack-guard.mjs @@ -0,0 +1,142 @@ +#!/usr/bin/env node +/** + * pack-guard: 发布前白名单 + 脱敏闸门。 + * + * 在 `pnpm publish` 之前运行(已接进 `prepublishOnly`):按 package.json 的 + * `files` 白名单解析出「真正会被打进 tarball 的文件」,然后 + * 1) 文件名黑名单:AGENTS.md / TODO.md / HANDOFF.md / PLAN.md / *.mjs / tsconfig* / pnpm-lock.yaml … + * 2) 内容黑名单:个人域名、本机路径、用户名、令牌形状(cmt_… / _authToken)。 + * 任一条不满足就以 exit 1 中止发布。 + * + * 纯 fs 实现:不 spawn 子进程,不读网络,不写任何文件。 + */ +import { readdirSync, readFileSync, statSync } from 'node:fs' +import { join, relative, sep } from 'node:path' + +const ROOT = process.cwd() +const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) + +/** 任何情况下都必须出现在包里的文件(npm 的 always-include 子集)。 */ +const ALWAYS = ['package.json', 'README.md', 'LICENSE', 'LICENCE'] + +/** 文件名黑名单:笔记、规划、构建配置、探测脚本一律不进包。 */ +const BANNED_NAMES = [ + /^AGENTS?\.md$/i, + /^TODO\.md$/i, + /^TASKS\.md$/i, + /^HANDOFF\.md$/i, + /^NOTES?\.md$/i, + /PLAN\.md$/i, + /\.mjs$/i, + /^tsconfig.*\.json$/i, + /^pnpm-lock\.yaml$/i, + /^package-lock\.json$/i, + /^\.npmrc$/i, + /^\.env(\.|$)/i, + /\.tgz$/i, + /\.log$/i, +] + +/** 内容黑名单:一旦命中就说明有东西会随包外发。 */ +const BANNED_CONTENT = [ + [/mem\.qyhhh\.top/i, '个人域名 mem.qyhhh.top'], + [/qyh15/i, '本机用户名 qyh15'], + [/C:[\\/]Users[\\/](?!)(?!%USERPROFILE%)/i, '本机绝对路径 C:\\Users\\…'], + [/cmt_[A-Za-z0-9_-]{16,}/, '疑似活动令牌原文 cmt_…'], + [/_authToken/i, 'npm 凭据字段 _authToken'], +] + +const TEXT_EXT = /\.(json|md|js|mjs|cjs|ts|tsx|yml|yaml|css|html|txt)$/i +const SKIP_DIRS = new Set(['node_modules', '.git', '.pnpm-store', '.pnpm-cache']) + +function walk(entry, out) { + const abs = join(ROOT, entry) + let st + try { + st = statSync(abs) + } catch { + return + } + if (st.isDirectory()) { + for (const name of readdirSync(abs)) { + if (SKIP_DIRS.has(name)) continue + walk(join(entry, name), out) + } + return + } + out.push(entry) +} + +/** 真正会进包的文件 = files 白名单展开 + always-include。 */ +const files = new Set() +const collected = [] +for (const entry of pkg.files ?? []) walk(entry.replace(/^\.\//, ''), collected) +for (const f of collected) files.add(f) +for (const f of ALWAYS) { + try { + if (statSync(join(ROOT, f)).isFile()) files.add(f) + } catch { + /* 不存在就算了 */ + } +} + +const problems = [] +for (const file of [...files].sort()) { + const rel = relative(ROOT, join(ROOT, file)).split(sep).join('/') + const base = rel.split('/').pop() + for (const re of BANNED_NAMES) { + if (re.test(base)) problems.push(`文件名命中黑名单 ${re} → ${rel}`) + } + if (!TEXT_EXT.test(rel)) continue + const text = readFileSync(join(ROOT, rel), 'utf8') + for (const [re, label] of BANNED_CONTENT) { + const m = text.match(re) + if (m) { + const line = text.slice(0, m.index).split('\n').length + problems.push(`${rel}:${line} 命中「${label}」→ ${m[0].slice(0, 60)}`) + } + } +} + +const kb = ([...files].reduce((n, f) => n + statSync(join(ROOT, f)).size, 0) / 1024).toFixed(1) +console.log(`pack-guard: ${files.size} 个文件将被发布,共 ${kb} KB`) +for (const f of [...files].sort()) console.log(` · ${f}`) + +/** 信息项:目录里存在、但不进包的笔记与工程文件 —— 明确告知「已排除」,免得不放心。 */ +const NOTEISH = [ + /^AGENTS?\.md$/i, + /^TODO\.md$/i, + /^TASKS\.md$/i, + /^HANDOFF\.md$/i, + /^NOTES?\.md$/i, + /PLAN\.md$/i, + /\.mjs$/i, + /^tsconfig.*\.json$/i, + /^pnpm-lock\.yaml$/i, +] +const excluded = [] +;(function scan(dir) { + for (const name of readdirSync(dir)) { + if (SKIP_DIRS.has(name)) continue + const abs = join(dir, name) + const rel = relative(ROOT, abs).split(sep).join('/') + if (statSync(abs).isDirectory()) { + scan(abs) + continue + } + if (files.has(rel)) continue + if (NOTEISH.some((re) => re.test(name))) excluded.push(rel) + } +})(ROOT) + +if (excluded.length) { + console.log(`\npack-guard: 以下 ${excluded.length} 个文件在目录里,但不会进包(笔记/工程文件,已排除):`) + for (const f of excluded.sort()) console.log(` – ${f}`) +} + +if (problems.length) { + console.error(`\npack-guard: 发现 ${problems.length} 处不该外发的内容,已中止发布:`) + for (const p of problems) console.error(` ✗ ${p}`) + process.exit(1) +} +console.log('\npack-guard: 白名单与脱敏检查通过') diff --git a/scripts/release-prep.mjs b/scripts/release-prep.mjs new file mode 100644 index 0000000..94a8412 --- /dev/null +++ b/scripts/release-prep.mjs @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/** + * release-prep: 发布前一次性整备(脱敏 + package.json 元数据 + LICENSE)。 + * + * node scripts/release-prep.mjs --dry-run 只报告将要改什么 + * node scripts/release-prep.mjs 原地写入 + * + * 幂等:重复执行不会有二次改动。必须在插件目录(含 package.json 那一层)执行。 + * 用 Node 而不是 PowerShell,避开发行策略限制,并且能把 package.json 写成无 BOM 的 UTF-8。 + */ +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { join, dirname } from 'node:path' +import { fileURLToPath } from 'node:url' + +const ROOT = dirname(dirname(fileURLToPath(import.meta.url))) +const DRY = process.argv.includes('--dry-run') +const pkgPath = join(ROOT, 'package.json') + +if (!existsSync(pkgPath)) throw new Error(`没有找到 ${pkgPath} —— 请在 dsh-plugin 目录里执行。`) +const changes = [] +const write = (path, text, why) => { + changes.push(`${why} → ${path.slice(ROOT.length + 1)}`) + if (!DRY) writeFileSync(path, text, 'utf8') +} + +/** 1. 脱敏:个人域名与本机路径。src 也要改,否则下次构建会把域名写回 lib。 */ +const REDACTIONS = [ + ['https://mem.qyhhh.top/api/longmemory', 'https://your-memory-host/api/longmemory', '替换个人域名'], + ['C:\\Users\\qyh15\\云端记忆系统\\dsh-plugin', 'D:\\path\\to\\dsh-plugin', '抹掉本机安装路径'], + ['C:/Users/qyh15/云端记忆系统/dsh-plugin', 'D:/path/to/dsh-plugin', '抹掉 link 里的本机路径'], + ['C:\\Users\\qyh15\\.dsh\\cloud-memory.json', '%USERPROFILE%\\.dsh\\cloud-memory.json', '抹掉令牌文件路径'], +] +for (const rel of ['cordis.patch.yml', 'README.md', 'lib/config.js', 'lib/page.js', 'src/config.ts', 'src/page.ts']) { + const path = join(ROOT, rel) + if (!existsSync(path)) continue + let text = readFileSync(path, 'utf8') + let touched = false + for (const [from, to, why] of REDACTIONS) { + if (!text.includes(from)) continue + text = text.split(from).join(to) + touched = true + changes.push(`${why} → ${rel}`) + } + if (touched && !DRY) writeFileSync(path, text, 'utf8') +} + +/** 2. package.json 元数据。 */ +const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) +const before = JSON.stringify(pkg) +const add = [] +if (pkg.name !== 'dsh-cloud-memory') throw new Error(`package.json 的 name 是 ${pkg.name},疑似跑错目录,已中止。`) + +if ('private' in pkg) { + delete pkg.private + add.push('去掉 private:true(npm 会直接拒绝发布)') +} +if (!pkg.publishConfig) { + pkg.publishConfig = { registry: 'https://registry.npmjs.org/', access: 'public' } + add.push('加 publishConfig(registry + access public)') +} +if (!pkg.keywords) { + pkg.keywords = ['dsh', 'dsh-plugin', 'memory', 'cloud-memory', 'longmemory', 'agent'] + add.push('加 keywords') +} +if (!pkg.author) { + pkg.author = 'dsh-cloud-memory contributors' + add.push('加 author(中性署名,可换成你自己的名字与邮箱)') +} +pkg.scripts ??= {} +if (pkg.scripts.prepack !== 'tsc -p tsconfig.build.json') { + pkg.scripts.prepack = 'tsc -p tsconfig.build.json' + add.push('加 prepack 构建(保证 lib/ 与 src/ 同步)') +} +if (pkg.scripts.prepublishOnly !== 'node scripts/pack-guard.mjs') { + pkg.scripts.prepublishOnly = 'node scripts/pack-guard.mjs' + add.push('加 prepublishOnly 闸门(笔记/探测脚本/个人信息一律拦下)') +} +pkg.files ??= [] +if (!pkg.files.includes('LICENSE')) { + pkg.files.push('LICENSE') + add.push('files 增加 LICENSE') +} +if (JSON.stringify(pkg) !== before) { + write(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`, 'package.json 更新') + changes.push(...add) +} + +/** 3. LICENSE。 */ +const licensePath = join(ROOT, 'LICENSE') +if (!existsSync(licensePath)) { + write( + licensePath, + `MIT License + +Copyright (c) 2026 dsh-cloud-memory contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +`, + '新建 MIT LICENSE', + ) +} + +/** 4. 报告。 */ +if (!changes.length) { + console.log('release-prep: 没有需要改动的内容 —— 已是发布就绪状态。') +} else { + console.log(`release-prep: ${DRY ? '将改动' : '已改动'} ${changes.length} 项`) + for (const c of changes) console.log(` · ${c}`) +} +console.log('\n下一步:pnpm run build → node scripts/pack-guard.mjs → pnpm login → pnpm publish --access public --no-git-checks') +console.log('注意:发布不可撤销,0.1.0 一旦发布就不能再改同号。') diff --git a/src/api.ts b/src/api.ts new file mode 100644 index 0000000..ae844a1 --- /dev/null +++ b/src/api.ts @@ -0,0 +1,489 @@ +/** + * Thin client for the LongMemory cloud API (`/api/longmemory`). + * + * - Every call carries `Authorization: Bearer `; the owner is injected + * server-side, so no request ever names a user. + * - Errors normalize to `{ status, code, message }`; a network failure is + * status 0 with code `network_error`, so callers can retry safely. + * - Only metadata ever leaves this process: turn ids, timestamps, statuses, and + * the memory content the user explicitly asked to save. + */ +import type { TurnStatus } from './reporter.ts' + +/** Normalized non-2xx outcome. */ +export interface CloudError { + /** HTTP status, or 0 for a transport failure. */ + status: number + /** Machine-readable code from the service, or a local fallback. */ + code: string + /** Human-readable message (already safe to show: never contains secrets). */ + message: string + /** Milliseconds the service asked us to wait (429 handling). */ + retryAfterMs?: number +} + +/** One request outcome. */ +export type CloudResult = { ok: true; status: number; data: T } | { ok: false; error: CloudError } + +/** Activity turn payload — exactly the six fields the service accepts. */ +export interface TurnPayload { + client_id: string + conversation_id: string + turn_id: string + status: TurnStatus + started_at: number + completed_at: number +} + +/** Activity turn outcome. */ +export interface TurnAck { + recorded?: boolean + duplicate?: boolean +} + +/** One transcript message sent for turn summarization (text only). */ +export interface SummaryMessage { + role: 'user' | 'assistant' + text: string +} + +/** `POST /activity/summary` request body. */ +export interface SummaryPayload { + conversation_id: string + turn_id: string + messages: SummaryMessage[] +} + +/** Staging outcome: how many proposals were queued for confirmation. */ +export interface SummaryAck { + staged?: number + skipped?: number + full?: boolean +} + +/** One search hit as the service indexes it. */ +export interface MemoryHit { + id?: string + content?: string + tags?: string[] + project_id?: string | null + primary_sector?: string + revision?: number + created_at?: number + updated_at?: number + [key: string]: unknown +} + +/** `POST /memory/query` response. */ +export interface SearchResponse { + matches?: MemoryHit[] + total?: number + search_mode?: string + [key: string]: unknown +} + +/** `GET /memory/all` response. */ +export interface ListResponse { + items?: MemoryHit[] + total?: number + [key: string]: unknown +} + +/** `GET /dashboard/projects` response. */ +export interface ProjectsResponse { + projects?: { id?: string; name?: string; [key: string]: unknown }[] + [key: string]: unknown +} + +/** `POST /memory/add` response. */ +export interface AddResponse { + id?: string + revision?: number + deleted?: boolean + state?: string + remote_saved?: boolean + memory?: MemoryHit | null + [key: string]: unknown +} + +/** One skill as the cloud skill center lists it (`GET /skills` item). */ +export interface SkillSummary { + name: string + description?: string + category?: string | null + execution_mode?: string + enabled?: boolean + revision?: number + manifest_sha256?: string + files?: number + bytes?: number + script_changed?: boolean + [key: string]: unknown +} + +/** `GET /skills` response. */ +export interface SkillListing { + items?: SkillSummary[] + total?: number + trash_total?: number + [key: string]: unknown +} + +/** One file inside a skill bundle (`GET /skills/:name/bundle`). */ +export interface SkillBundleFile { + path: string + sha256: string + size?: number + encoding?: string + /** Base64 payload; present on every bundle file. */ + data: string +} + +/** `GET /skills/:name/bundle` response. */ +export interface SkillBundle { + name: string + revision: number + manifest_sha256: string + script_changed?: boolean + script_changes?: string[] + files: SkillBundleFile[] + [key: string]: unknown +} + +/** One file in a skill write payload: text inline, or base64 for binaries. */ +export type SkillUploadFile = { path: string; content: string } | { path: string; base64: string } + +/** `POST /skills` / `PATCH /skills/:name` outcome. */ +export interface SkillWriteResult { + skill?: SkillSummary + revision?: number + manifest_sha256?: string + [key: string]: unknown +} + +/** One dashboard account as the login endpoint returns it. */ +export interface AccountInfo { + id?: string + username?: string + role?: string + [key: string]: unknown +} + +/** Outcome of a password login: the account plus the session cookie to spend. */ +export interface LoginOutcome { + user: AccountInfo + /** `name=value` pair ready for a Cookie header; never leaves this process. */ + sessionCookie: string +} + +/** One freshly minted API token. */ +export interface IssuedToken { + id?: string + token?: string + scope?: string + label?: string +} + +/** + * Derive the dashboard auth root (`/api/auth`) from the memory base URL + * (`.../api/longmemory`): login and token minting live one segment over. + */ +function authBase(baseUrl: string): string { + try { + const url = new URL(baseUrl) + const prefix = url.pathname.replace(/\/longmemory\/?$/i, '') + return `${url.origin}${prefix}/auth` + } catch { + return '' + } +} + +/** True when sending a password to this URL is safe (TLS, or loopback). */ +export function isSecureLoginTarget(baseUrl: string): boolean { + try { + const url = new URL(baseUrl) + if (url.protocol === 'https:') return true + return url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) + } catch { + return false + } +} + +/** Pull the first cookie pair out of one or more Set-Cookie headers. */ +function sessionCookieOf(headers: Headers): string { + // `getSetCookie` exists on undici/Node 18.14+ but is not in every Headers type. + const withCookies = headers as Headers & { getSetCookie?: () => string[] } + const list = typeof withCookies.getSetCookie === 'function' ? withCookies.getSetCookie() : [headers.get('set-cookie') ?? ''] + for (const entry of list) { + if (entry === '') continue + const pair = entry.split(';', 1)[0] + if (pair !== undefined && pair.includes('=') && !pair.startsWith('=')) return pair.trim() + } + return '' +} + +/** Options for one {@link CloudClient}. */ +export interface CloudClientOptions { + /** Effective base URL (no trailing slash). */ + baseUrl: () => string + /** Bearer token for the call's scope. */ + token: () => string + /** Request timeout in milliseconds. */ + timeoutMs: () => number +} + +/** Map one HTTP error body onto a {@link CloudError}. */ +function errorFromBody(status: number, raw: string, retryAfterHeader: string | null): CloudError { + let code = `http_${status}` + let message = raw.slice(0, 300) + try { + const parsed: unknown = JSON.parse(raw) + if (parsed !== null && typeof parsed === 'object') { + const body = parsed as Record + if (typeof body.error === 'string') code = body.error + else if (body.error !== null && typeof body.error === 'object') { + const nested = body.error as Record + if (typeof nested.code === 'string') code = nested.code + if (typeof nested.message === 'string') message = nested.message + } + if (typeof body.message === 'string') message = body.message + } + } catch { + // Non-JSON error (proxy HTML page, empty body): keep the text snippet. + } + const error: CloudError = { status, code, message: message === '' ? code : message } + if (status === 429) { + const header = retryAfterHeader === null ? Number.NaN : Number(retryAfterHeader) + error.retryAfterMs = Number.isFinite(header) && header > 0 ? header * 1000 : 900_000 + } + return error +} + +/** + * One cloud endpoint handle. Instances are cheap: construct per call site and + * keep the live settings behind closures so a settings edit applies at once. + */ +export class CloudClient { + constructor(private readonly options: CloudClientOptions) {} + + private async request(method: string, path: string, body?: unknown, tokenOverride?: string): Promise> { + const token = tokenOverride ?? this.options.token() + const base = this.options.baseUrl() + const url = `${base}${path}` + const headers: Record = { Accept: 'application/json' } + if (token !== '') headers.Authorization = `Bearer ${token}` + const init: RequestInit = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) } + if (body !== undefined) { + headers['Content-Type'] = 'application/json' + init.body = JSON.stringify(body) + } + let response: Response + try { + response = await fetch(url, init) + } catch (error) { + 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(() => '') + if (!response.ok) { + return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) } + } + if (text.trim() === '') return { ok: true, status: response.status, data: {} as T } + try { + return { ok: true, status: response.status, data: JSON.parse(text) as T } + } catch { + return { ok: false, error: { status: response.status, code: 'invalid_json', message: 'response was not JSON' } } + } + } + + /** Report one conversation turn (activity:write token). */ + reportTurn(payload: TurnPayload, token: string): Promise> { + return this.request('POST', '/activity/turn', payload, token) + } + + /** Stage one turn summary as pending proposals (summary:write token). */ + submitSummary(payload: SummaryPayload, token: string): Promise> { + return this.request('POST', '/activity/summary', payload, token) + } + + /** + * Verify a summary token without staging anything. + * + * The endpoint authenticates before it validates the body, so an empty + * object coming back `400 invalid_input` proves the scope is right. + */ + async probeSummary(token: string): Promise> { + const result = await this.request('POST', '/activity/summary', {}, token) + if (result.ok) return { ok: true, status: result.status, data: { authenticated: true } } + if (result.error.status === 400) return { ok: true, status: 400, data: { authenticated: true } } + return { ok: false, error: result.error } + } + + /** + * Verify an activity token without recording anything. + * + * `/activity/turn` validates auth before the payload, so an empty body that + * comes back `400 invalid_event` proves the token carries `activity:write`. + * A 401/403 is a token problem; anything else is reported verbatim. + */ + async probeActivity(token: string): Promise> { + const result = await this.request('POST', '/activity/turn', {}, token) + if (result.ok) return { ok: true, status: result.status, data: { authenticated: true } } + // 400 means the credentials were accepted and only the body was rejected. + if (result.error.status === 400) { + return { ok: true, status: 400, data: { authenticated: true } } + } + return { ok: false, error: result.error } + } + + /** Keyword search over stored memories (memory token). */ + async search(query: string, k: number, project?: string): Promise> { + const body: Record = { query, k } + if (project !== undefined && project !== '') body.filters = { project_id: project } + return this.request('POST', '/memory/query', body) + } + + /** Read one memory by id (memory token). */ + read(id: string): Promise> { + return this.request('GET', `/memory/${encodeURIComponent(id)}`) + } + + /** List memories with optional paging filters (memory token). */ + list(options: { limit?: number; offset?: number; project?: string } = {}): Promise> { + const params = new URLSearchParams() + if (options.limit !== undefined) params.set('limit', String(options.limit)) + if (options.offset !== undefined) params.set('offset', String(options.offset)) + if (options.project !== undefined && options.project !== '') params.set('project_id', options.project) + const suffix = params.toString() === '' ? '' : `?${params.toString()}` + return this.request('GET', `/memory/all${suffix}`) + } + + /** Store one memory; `operationId` makes the write idempotent (memory token). */ + add(input: { content: string; tags?: string[]; project?: string; sector?: string; operationId: string }): Promise> { + const body: Record = { + operation_id: input.operationId, + content: input.content, + } + if (input.tags !== undefined && input.tags.length > 0) body.tags = input.tags + if (input.project !== undefined && input.project !== '') body.project_id = input.project + if (input.sector !== undefined && input.sector !== '') body.metadata = { primary_sector: input.sector } + return this.request('POST', '/memory/add', body) + } + + /** List the account's projects (memory token). */ + projects(): Promise> { + return this.request('GET', '/dashboard/projects') + } + + /** Storage configuration state (memory token). */ + storageStatus(): Promise>> { + return this.request>('GET', '/storage/status') + } + + /** List the cloud skill center inventory (memory token). */ + listSkills(): Promise> { + return this.request('GET', '/skills') + } + + /** Fetch one skill bundle with hashed, base64-carried files (memory token). */ + skillBundle(name: string): Promise> { + return this.request('GET', `/skills/${encodeURIComponent(name)}/bundle`) + } + + /** Create one skill in the center; `expected_revision` must be 0 (memory token). */ + createSkill(body: Record): Promise> { + return this.request('POST', '/skills', body) + } + + /** Replace one skill's files/description at an expected revision (memory token). */ + updateSkill(name: string, body: Record): Promise> { + return this.request('PATCH', `/skills/${encodeURIComponent(name)}`, body) + } + + /** + * One call against the dashboard auth surface (`/api/auth/*`). + * + * These endpoints authorize by session cookie, not by Bearer token, and they + * reject any non-GET without a matching `Origin` (the server's CSRF gate), so + * 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. + */ + private async authFetch( + method: string, + path: string, + body?: unknown, + cookie?: string, + ): Promise<{ ok: true; status: number; body: unknown; headers: Headers } | { ok: false; error: CloudError }> { + const baseUrl = this.options.baseUrl() + const base = authBase(baseUrl) + if (base === '') return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } } + const headers: Record = { Accept: 'application/json' } + try { + headers.Origin = new URL(baseUrl).origin + } catch { + return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } } + } + if (cookie !== undefined && cookie !== '') headers.Cookie = cookie + const init: RequestInit = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) } + if (body !== undefined) { + headers['Content-Type'] = 'application/json' + init.body = JSON.stringify(body) + } + let response: Response + try { + response = await fetch(`${base}${path}`, init) + } catch (error) { + 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(() => '') + if (!response.ok) { + return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) } + } + let parsed: unknown = {} + if (text.trim() !== '') { + try { + parsed = JSON.parse(text) + } catch { + parsed = {} + } + } + return { ok: true, status: response.status, body: parsed, headers: response.headers } + } + + /** + * Password login against the dashboard. + * + * The password is used once, in this call, and never stored: what comes back + * is a short-lived session cookie that the caller immediately spends on + * {@link CloudClient.mintToken} and then drops. + */ + async login(username: string, password: string): Promise> { + const sent = await this.authFetch('POST', '/login', { username, password }) + if (!sent.ok) return sent + const cookie = sessionCookieOf(sent.headers) + if (cookie === '') { + return { ok: false, error: { status: sent.status, code: 'no_session', message: '登录成功,但服务端没有下发会话' } } + } + const body = sent.body as { user?: AccountInfo } + return { ok: true, status: sent.status, data: { user: body.user ?? {}, sessionCookie: cookie } } + } + + /** Mint one scoped API token using a live session cookie. */ + async mintToken(sessionCookie: string, scope: string, label: string): Promise> { + const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie) + if (!sent.ok) return sent + const body = sent.body as { token?: IssuedToken } + const issued = body.token + if (issued === undefined || typeof issued.token !== 'string' || issued.token === '') { + return { ok: false, error: { status: sent.status, code: 'no_token', message: '服务端没有返回令牌' } } + } + return { ok: true, status: sent.status, data: issued } + } +} + +/** Render a {@link CloudError} as one display line. */ +export function describeError(error: CloudError): string { + if (error.status === 0) return `网络不可用:${error.message}` + return `HTTP ${error.status} ${error.code}:${error.message}` +} diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..ddc9bfc --- /dev/null +++ b/src/config.ts @@ -0,0 +1,97 @@ +/** + * Settings model: the cordis row config supplies defaults, the user-editable + * sidecar (`$DSH_HOME/cloud-memory.json`) overrides them, and secrets live ONLY + * in the sidecar. Nothing here ever reaches the conversation or a model context. + */ + +/** Defaults written into cordis.patch.yml; also the fallback for missing keys. */ +export const DEFAULT_SETTINGS: Settings = { + enabled: true, + baseUrl: 'https://mem.qyhhh.top/api/longmemory', + clientId: 'dsh-desktop', + requestTimeoutMs: 5000, + defaultK: 10, + summaryEnabled: true, + summaryMaxChars: 6000, + skillsSyncEnabled: true, + skillsDir: '', +} + +/** Effective, fully-resolved settings. */ +export interface Settings { + /** Master switch for turn reporting AND memory tools. */ + enabled: boolean + /** Base URL of the cloud memory service, without a trailing slash. */ + baseUrl: string + /** Stable client identifier sent with every activity turn. */ + clientId: string + /** Per-request HTTP timeout in milliseconds. */ + requestTimeoutMs: number + /** Default result count for `memory_search`. */ + defaultK: number + /** Stage a turn summary as pending proposals after each completed round. */ + summaryEnabled: boolean + /** Maximum transcript characters sent for one summary (privacy/cost cap). */ + summaryMaxChars: number + /** Bidirectional skill sync between the cloud skill center and the local skills directory. */ + skillsSyncEnabled: boolean + /** Local skills directory override; empty means `$DSH_HOME/skills`. */ + skillsDir: string +} + +/** Raw row config as it comes out of the cordis loader. */ +export type RawConfig = Partial> + +const MIN_TIMEOUT_MS = 1000 +const MAX_TIMEOUT_MS = 60_000 + +/** Trim truncation guard for the free-form identifiers. */ +function shortString(value: unknown): string | undefined { + if (typeof value !== 'string') return undefined + const trimmed = value.trim() + if (trimmed === '') return undefined + return trimmed.slice(0, 128) +} + +/** + * Normalize a base URL: require http(s), drop trailing slashes and any query. + * Returns undefined when the input is unusable, so callers can fall back. + */ +export function normalizeBaseUrl(value: unknown): string | undefined { + if (typeof value !== 'string' || value.trim() === '') return undefined + try { + const url = new URL(value.trim()) + if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined + return `${url.origin}${url.pathname.replace(/\/+$/, '')}` + } catch { + return undefined + } +} + +/** Clamp a numeric config value into an integer range, else undefined. */ +function boundedInt(value: unknown, min: number, max: number): number | undefined { + if (typeof value !== 'number' || !Number.isFinite(value)) return undefined + return Math.min(max, Math.max(min, Math.round(value))) +} + +/** Extract the recognized settings from an untrusted row config object. */ +export function settingsFromConfig(raw: unknown): Partial { + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {} + const source = raw as RawConfig + const result: Partial = {} + if (typeof source.enabled === 'boolean') result.enabled = source.enabled + const baseUrl = normalizeBaseUrl(source.baseUrl) + if (baseUrl !== undefined) result.baseUrl = baseUrl + const clientId = shortString(source.clientId) + if (clientId !== undefined) result.clientId = clientId + const timeout = boundedInt(source.requestTimeoutMs, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS) + if (timeout !== undefined) result.requestTimeoutMs = timeout + const defaultK = boundedInt(source.defaultK, 1, 100) + if (defaultK !== undefined) result.defaultK = defaultK + if (typeof source.summaryEnabled === 'boolean') result.summaryEnabled = source.summaryEnabled + const summaryMaxChars = boundedInt(source.summaryMaxChars, 1000, 16_000) + if (summaryMaxChars !== undefined) result.summaryMaxChars = summaryMaxChars + if (typeof source.skillsSyncEnabled === 'boolean') result.skillsSyncEnabled = source.skillsSyncEnabled + if (typeof source.skillsDir === 'string') result.skillsDir = source.skillsDir.trim().slice(0, 512) + return result +} diff --git a/src/context-types.ts b/src/context-types.ts new file mode 100644 index 0000000..6a00633 --- /dev/null +++ b/src/context-types.ts @@ -0,0 +1,59 @@ +/** + * Structural types for the cordis services this plugin consumes. + * + * A third-party plugin resolves outside the DSH monorepo's single cordis + * instance, so the upstream `declare module` augmentations never reach this + * Context. Every shape below mirrors only the members this plugin touches; + * drift is contained to this one file. + */ +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { Context } from '@deepseek-ai/cordis' + +/** One named webserver route (mirror of the host-webserver WebRoute). */ +export interface CloudMemoryWebRoute { + kind: 'exact' | 'prefix' + path: string + handler: (req: IncomingMessage, res: ServerResponse, body?: unknown) => void | Promise +} + +/** The webServer service face this plugin uses. */ +export interface CloudMemoryWebServer { + register(route: CloudMemoryWebRoute): () => void +} + +/** Minimal tool-definition shape accepted by the host tool registry. */ +export interface ToolDefinitionLike { + name: string + description: string + parameters: unknown + output?: { + schema: unknown + render: (args: unknown, value: unknown) => unknown[] + } + execute: (args: Record, exec?: unknown) => Promise +} + +/** The host tool registry face this plugin uses. */ +export interface ToolRegistryLike { + register(definition: ToolDefinitionLike): () => void +} + +/** Cordis Context augmented with the services this plugin needs. */ +export interface CloudMemoryContext extends Context { + webServer?: CloudMemoryWebServer + tools?: ToolRegistryLike +} + +/** The session object as far as turn reporting is concerned. */ +export interface SessionLike { + id?: string + sessionId?: string +} + +/** One `session/event` payload. */ +export interface SessionEventLike { + type?: string + seq?: number + time?: number | string + data?: Record +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..4c5434e --- /dev/null +++ b/src/index.ts @@ -0,0 +1,153 @@ +/** + * 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 `/cloud-memory`. + * + * Everything registers through `ctx.effect(...)` so a plugin reload tears down + * its routes, timer, listeners, and tools without leftovers. + */ +import { CloudClient } from './api.ts' +import type { CloudMemoryContext, SessionEventLike, SessionLike } from './context-types.ts' +import { Reporter } from './reporter.ts' +import { createRoutes } from './routes.ts' +import { join } from 'node:path' +import { SettingsStore, dshHome } from './store.ts' +import { SkillSync } from './skill-sync.ts' +import { SkillAdmin, skillsHoldingDir } from './skill-admin.ts' +import { createMemoryTools, createSkillTools } from './tools.ts' + +/** Package name; also the client bundle id. */ +export const name = 'dsh-cloud-memory' + +/** Services required before `apply` runs. */ +export const inject = ['webServer'] + +/** Version reported by the status card. */ +const VERSION = '0.4.1' + +/** 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. */ +export function apply(ctx: CloudMemoryContext, config: unknown): void { + const logger = ctx.logger('cloud-memory') + 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: () => join(dshHome(), 'cloud-memory-skills.json'), + syncRunning: () => skillSync.stats().running, + log: (message) => logger.info(message), + }) + // 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 /cloud-memory`) + } 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 as unknown as ( + name: 'session/event', + listener: (session: SessionLike, event: SessionEventLike) => void, + ) => () => void + + 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-cloud-memory: turn reporting', + ) + + ctx.inject(['tools'], (toolsCtx) => { + const tools = (toolsCtx as CloudMemoryContext).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-cloud-memory: 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 }) + for (const route of routes) { + ctx.effect(() => webServer.register(route), `dsh-cloud-memory: route ${route.path}`) + } + } + + ctx.effect(() => { + const timer = setInterval(() => { + if (store.activityToken() !== '' && settings().enabled) { + void reporter.flush().catch((error: unknown) => { + logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`) + }) + } + }, RETRY_INTERVAL_MS) + timer.unref?.() + return () => clearInterval(timer) + }, 'dsh-cloud-memory: 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-cloud-memory: skill sync timer') +} diff --git a/src/mnemon/descriptor.ts b/src/mnemon/descriptor.ts new file mode 100644 index 0000000..6ffb336 --- /dev/null +++ b/src/mnemon/descriptor.ts @@ -0,0 +1,62 @@ +import type { MemoryProviderDescriptor } from 'dsh-mnemon-source-memory-spaces/provider-sdk' + +/** + * Browser-safe metadata for the LongMemory Provider. + * + * The Provider is the Mnemon face of this package: Mnemon keeps the hot, + * per-turn presence local, while every long-term read and write passes + * through to the user's own LongMemory service in real time. The cloud + * store is the source of truth — nothing long-term is mirrored locally. + */ +export const descriptor: MemoryProviderDescriptor = { + id: 'longmemory', + label: 'LongMemory', + icon: { + kind: 'glyph', + value: '☁', + }, + kind: 'remote', + workspaceBinding: 'provider-global', + summary: 'Your self-hosted LongMemory service as a live memory space: reads and writes pass through in real time, nothing is mirrored locally.', + origin: 'third-party', + capabilities: { + search: true, + browse: true, + graph: false, + entities: false, + related: false, + remember: true, + link: false, + forget: false, + writeMode: 'exact', + deletionMode: 'unsupported', + }, + fields: [ + { + key: 'endpoint', + label: 'Endpoint', + scope: 'service', + input: 'url', + required: false, + placeholder: 'https://mem.example.com/api/longmemory', + help: 'LongMemory base URL. Leave empty to reuse the dsh-cloud-memory settings (cloud-memory.json).', + normalize: 'trim-trailing-slash', + }, + { + key: 'token', + label: 'Memory token', + scope: 'service', + input: 'secret', + required: false, + help: 'Scoped memory token (memory:write). Leave empty to reuse the token already configured for dsh-cloud-memory.', + }, + { + key: 'projectId', + label: 'Project ID', + scope: 'memory', + input: 'text', + required: false, + help: 'LongMemory project this space maps to. Empty means the account-wide default scope.', + }, + ], +} diff --git a/src/mnemon/driver.ts b/src/mnemon/driver.ts new file mode 100644 index 0000000..f8c23c7 --- /dev/null +++ b/src/mnemon/driver.ts @@ -0,0 +1,255 @@ +/** + * LongMemory driver for Mnemon's Memory Spaces. + * + * Design rule (the whole point of this bridge): the cloud service is the + * source of truth. Every search/list/read/write is a live call to the + * user's own LongMemory endpoint — this driver keeps NO local replica of + * long-term memory, so anything another tool (Claude Code, Codex, the + * dashboard) wrote into LongMemory is visible inside DSH immediately. + * + * 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/cloud-memory.json`) + * for any of endpoint/token the Mnemon side left empty — so a user + * who already configured dsh-cloud-memory 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 type { + Insight, + JsonValue, + MemoryGraphSnapshot, + MemoryListRequest, + MemoryProviderAdapter, + MemoryProviderConnection, + MemorySpace, + MemorySpaceAuthority, + ProviderMemorySpace, + ProviderSearchResult, + ProviderSpaceStatus, + RememberRequest, + SearchRequest, +} from 'dsh-mnemon-source-memory-spaces/provider-sdk' +import { CloudClient, type MemoryHit } from '../api.ts' +import { SettingsStore } from '../store.ts' +import { descriptor } from './descriptor.ts' + +/** Options handed over by the provider factory. */ +export interface LongMemoryProviderOptions { + /** Per-request timeout from the Memory Spaces host config. */ + requestTimeoutMs?: number +} + +/** One fully-resolved connection: everything a call needs. */ +interface ResolvedConnection { + endpoint: string + header: string + project?: string +} + +/** Epoch (ms, or seconds on older payloads) → ISO string, when plausible. */ +function toIso(value: unknown): string | undefined { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined + const ms = value < 1e12 ? value * 1000 : value + const date = new Date(ms) + return Number.isNaN(date.getTime()) ? undefined : date.toISOString() +} + +/** Map one LongMemory hit onto a Mnemon Insight; unusable hits drop out. */ +export function insightFromHit(hit: MemoryHit): Insight | undefined { + if (typeof hit.id !== 'string' || hit.id === '') return undefined + if (typeof hit.content !== 'string') return undefined + const insight: Insight = { id: hit.id, content: hit.content, source: 'external' } + if (typeof hit.primary_sector === 'string' && hit.primary_sector !== '') { + insight.category = hit.primary_sector + } + if (Array.isArray(hit.tags)) { + const tags = hit.tags.filter((tag): tag is string => typeof tag === 'string') + if (tags.length > 0) insight.tags = tags + } + const createdAt = toIso(hit.created_at) + if (createdAt !== undefined) insight.createdAt = createdAt + const score = (hit as Record).score + if (typeof score === 'number' && Number.isFinite(score)) insight.score = score + return insight +} + +export class LongMemoryProvider implements MemoryProviderAdapter { + readonly id = descriptor.id + /** LongMemory scores are its own scale; the host may only order by them. */ + readonly scoreSemantics = { kind: 'provider-native' } as const + + private store: SettingsStore | undefined + + constructor( + private readonly authority: MemorySpaceAuthority | undefined, + private readonly options: LongMemoryProviderOptions = {}, + ) {} + + /** This package's settings sidecar, read lazily so edits apply live. */ + private settings(): SettingsStore { + this.store ??= new SettingsStore({}) + return this.store + } + + /** + * 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. + */ + private resolve(body?: MemorySpace, direct?: MemoryProviderConnection): ResolvedConnection { + let connection: MemoryProviderConnection = { ...(direct ?? {}) } + if (body !== undefined) { + if (this.authority !== undefined) { + try { + connection = { ...this.authority.providerConnection(body.id, descriptor.id), ...connection } + } catch { + // Host could not resolve it; fall through to the space record. + } + } + const own = (body as { connection?: unknown }).connection + if (own !== null && typeof own === 'object' && !Array.isArray(own)) { + connection = { ...(own as MemoryProviderConnection), ...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 + : undefined + return { endpoint: endpointRaw.replace(/\/+$/, ''), header: token, ...(project === undefined ? {} : { project }) } + } + + /** A client bound to one resolved connection (clients here are cheap). */ + private client(resolved: ResolvedConnection): CloudClient { + return new CloudClient({ + baseUrl: () => resolved.endpoint, + token: () => resolved.header, + timeoutMs: () => this.options.requestTimeoutMs ?? this.settings().settings().requestTimeoutMs, + }) + } + + /** Enumerate the account's projects as Memory Spaces, plus the default scope. */ + async discover(connection: MemoryProviderConnection, signal?: AbortSignal): Promise { + signal?.throwIfAborted() + const resolved = this.resolve(undefined, connection) + const result = await this.client(resolved).projects() + if (!result.ok) { + throw new Error(`LongMemory project discovery failed: ${result.error.message}`) + } + const spaces: ProviderMemorySpace[] = [{ + externalId: 'default', + name: 'LongMemory · 全部', + description: 'Account-wide default scope (no project filter).', + connection: {}, + }] + for (const project of result.data.projects ?? []) { + if (typeof project.id !== 'string' || project.id === '') continue + spaces.push({ + externalId: `project:${project.id}`, + name: typeof project.name === 'string' && project.name !== '' ? project.name : project.id, + description: 'LongMemory project', + connection: { projectId: project.id }, + }) + } + return spaces + } + + /** Health = the service answers its storage status endpoint. */ + async status(body: MemorySpace, signal?: AbortSignal): Promise { + signal?.throwIfAborted() + const resolved = this.resolve(body) + if (resolved.header === '') { + return { healthy: false, error: 'LongMemory memory token is not configured' } + } + const result = await this.client(resolved).storageStatus() + return result.ok + ? { healthy: true } + : { healthy: false, error: result.error.message } + } + + /** Live pass-through search — this is the recall path for every turn. */ + async search(body: MemorySpace, request: SearchRequest, signal?: AbortSignal): Promise { + 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) + if (!result.ok) { + throw new Error(`LongMemory search failed: ${result.error.message}`) + } + return { + results: (result.data.matches ?? []) + .map(insightFromHit) + .filter((item): item is Insight => item !== undefined), + } + } + + /** Browse the space; a query, when given, defers to live search. */ + async list(body: MemorySpace, request: MemoryListRequest, signal?: AbortSignal): Promise { + signal?.throwIfAborted() + if (request.query !== undefined && request.query !== '') { + const found = await this.search(body, { query: request.query, limit: request.limit ?? 100 }, signal) + return found.results + } + 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 }) + if (!result.ok) { + throw new Error(`LongMemory list failed: ${result.error.message}`) + } + return (result.data.items ?? []) + .map(insightFromHit) + .filter((item): item is Insight => item !== undefined) + } + + /** Store one memory straight into the cloud store — no local staging. */ + async remember(body: MemorySpace, request: RememberRequest, signal?: AbortSignal): Promise { + signal?.throwIfAborted() + const resolved = this.resolve(body) + const result = await this.client(resolved).add({ + content: request.content, + ...(request.tags === undefined ? {} : { tags: request.tags }), + ...(resolved.project === undefined ? {} : { project: resolved.project }), + ...(request.category === undefined ? {} : { sector: request.category }), + operationId: `mnemon-${randomUUID()}`, + }) + if (!result.ok) { + throw new Error(`LongMemory remember failed: ${result.error.message}`) + } + return { + action: 'stored', + provider: this.id, + summary: 'Stored in LongMemory (live).', + ...(result.data.id === undefined ? {} : { id: result.data.id }), + ...(result.data.revision === undefined ? {} : { revision: result.data.revision }), + } + } + + /** Exact read of one memory by id. */ + async get(body: MemorySpace, id: string, signal?: AbortSignal): Promise { + signal?.throwIfAborted() + const resolved = this.resolve(body) + const result = await this.client(resolved).read(id) + if (!result.ok) return undefined + return insightFromHit(result.data) + } + + /** + * LongMemory's associations live server-side and this API exposes no + * graph read, so the honest v1 answer is an empty snapshot; the + * descriptor declares the graph capability off to match. + */ + async graph(body: MemorySpace, signal?: AbortSignal): Promise { + signal?.throwIfAborted() + void body + return { nodes: [], edges: [], generatedAt: new Date().toISOString() } + } +} diff --git a/src/mnemon/index.ts b/src/mnemon/index.ts new file mode 100644 index 0000000..7b632b7 --- /dev/null +++ b/src/mnemon/index.ts @@ -0,0 +1,57 @@ +/** + * Mnemon Memory Spaces Provider entry for LongMemory. + * + * This module is NOT loaded by the dsh-cloud-memory bundle itself. Mnemon's + * Memory Spaces source mounts it as a child when the user adds it to the + * source's provider list: + * + * providers: + * - use: dsh-cloud-memory/mnemon-provider + * instanceId: longmemory + * + * 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 { descriptor } from './descriptor.ts' +import { LongMemoryProvider } from './driver.ts' + +export { LongMemoryProvider, descriptor } + +/** Keep in sync with the package version (asserted by the verify script). */ +const PROVIDER_VERSION = '0.4.1' + +export const definition = defineMemorySpaceProviderDefinition({ + manifest: { + apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION, + kind: 'provider', + typeId: descriptor.id, + packageName: 'dsh-cloud-memory', + version: PROVIDER_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: 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 }, + ), +}) + +export default defineMemorySpaceProvider({ + id: descriptor.id, + apply(ctx, host) { + host.install(ctx, definition) + }, +}) diff --git a/src/page.ts b/src/page.ts new file mode 100644 index 0000000..5a223ca --- /dev/null +++ b/src/page.ts @@ -0,0 +1,431 @@ +/** + * 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 `/cloud-memory`. It is deliberately dependency-free: no + * bundler assets, no CDN, no fonts — one file the host web server can emit. + * + * The page renders tokens as masked values only; the plaintext never leaves + * `$DSH_HOME/cloud-memory.json`. + */ + +/** Escape a value for safe interpolation into HTML text/attributes. */ +export function escapeHtml(value: string): string { + return value + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", ''') +} + +/** Render the configuration page. */ +export function renderConfigPage(options: { version: string; settingsPath: string }): string { + // The client script is plain ES2020 and avoids template literals so this + // outer template stays readable. + return ` + + + + +云端记忆 · DSH 插件 + + + +
+

云端记忆 · DSH 插件

+

v${escapeHtml(options.version)} · 每轮结束上报活动计数 · 提供 memory_search / memory_read / memory_add 工具

+

技能管理(列表 · 启停 · 安装)→

+ +
+

当前状态

+
+
加载中…
+
+ +
+

连接配置

+
+
+ + +
不带结尾斜杠,路径为 /api/longmemory。
+
+
+ + +
上报时附带,便于区分来源设备。
+
+
+ + +
+
+ + +
+
+
+ +
+
+ +
+
+ + +
+
+ +
+

账号登录

+
+
+ + +
+
+ + +
+
+
+ +
+
+ 用云端面板的普通用户账号登录,插件会用一次性会话换取 activity:write 与 memory:write 两个令牌并写入本机。 + 密码只在这一次请求里使用:不保存、不写日志、不回显,换取成功后立即从内存丢弃。 + 管理员账号不能创建个人令牌,请用普通用户账号。 +
+
+ +
+

访问令牌

+
+
+ + +
用于 POST /activity/turn。
+
+
+ + +
memory:write 同时允许读取,一个令牌即可覆盖检索与写入;只有 memory:read 时写入会被拒。
+
+
+ + +
用于 POST /activity/summary:只把已脱敏摘要送进待确认队列。
+
+
+
+ + +
+
+ 在面板「设置 → API 密钥」里各建一个 activity:write 与 memory:write 密钥(一个密钥只有一种权限,所以需要两个)。
+ 令牌只写入本机 ${escapeHtml(options.settingsPath)}(进程退出不丢),不会进入会话上下文、不会上传到云端、也不会出现在本页回显里。 +
+
+ +
+

诊断

+
+ + + +
+
+
+ +
+

最近上报

+ + + + + +
时间状态结果HTTPturn_id
暂无记录
+
+
+
+ + +` +} diff --git a/src/reporter.ts b/src/reporter.ts new file mode 100644 index 0000000..d02143c --- /dev/null +++ b/src/reporter.ts @@ -0,0 +1,444 @@ +/** + * Turn reporter: one activity record per finished conversation round. + * + * Contract with the cloud service (`POST /activity/turn`): + * - exactly six fields; any extra key is rejected with 400, + * - `started_at` / `completed_at` are epoch-millisecond integers, + * `completed_at >= started_at` and not more than 5 minutes in the future, + * - `turn_id` is idempotent, so retries never double-count a round. + * + * Only metadata leaves the process. Prompt text and tool output are never part + * of a report — the payload builder cannot see them. + */ +import type { CloudClient, SummaryMessage, SummaryPayload, TurnPayload } from './api.ts' +import { describeError } from './api.ts' +import type { SessionEventLike, SessionLike } from './context-types.ts' + +/** The three statuses the service accepts; only `completed` feeds the heatmap. */ +export type TurnStatus = 'completed' | 'failed' | 'cancelled' + +/** One finished report, kept for the status card. */ +export interface ReportRecord { + turnId: string + conversationId: string + status: TurnStatus + startedAt: number + completedAt: number + at: number + /** `recorded` (201), `duplicate` (200), `failed`, or `queued` (waiting for retry). */ + outcome: 'recorded' | 'duplicate' | 'failed' | 'queued' | 'skipped' + httpStatus?: number + error?: string +} + +/** Counters + recent history exposed by `GET /cloud-memory/status`. */ +export interface ReporterSnapshot { + attempted: number + recorded: number + duplicate: number + failed: number + skipped: number + queued: number + summaryAttempted?: number + summaryStaged?: number + summaryFailed?: number + lastSummaryError?: string + lastSentAt?: number + lastError?: string + recent: ReportRecord[] +} + +/** Collaborators the reporter needs. */ +export interface ReporterOptions { + client: CloudClient + /** Effective settings (never a token). */ + settings: () => { enabled: boolean; clientId: string } + /** Activity token, or empty when unconfigured. */ + activityToken: () => string + /** Effective summary settings (never a token). */ + summary: () => { enabled: boolean; maxChars: number } + /** summary:write token, or empty when summaries are not configured. */ + summaryToken: () => string + /** Log sink for operator-visible diagnostics. */ + log: (message: string) => void +} + +/** Normalize an event timestamp (ms epoch or ISO string) into epoch ms. */ +export function toEpochMs(value: unknown): number | undefined { + if (typeof value === 'number' && Number.isFinite(value)) { + // Accept seconds as well: anything below ~2001 in ms is almost certainly seconds. + return value < 1e11 ? Math.round(value * 1000) : Math.round(value) + } + if (typeof value === 'string' && value.trim() !== '') { + const parsed = Date.parse(value) + return Number.isNaN(parsed) ? undefined : parsed + } + return undefined +} + +/** + * Map a DSH `TurnEndReason` onto a reportable status. + * + * `forked` is not a real completion: the child session starts a fresh turn, and + * counting the fork would inflate the heatmap with rounds the user never ran. + */ +export function statusForReason(reason: unknown): TurnStatus | null { + const kind = typeof reason === 'string' + ? reason + : reason !== null && typeof reason === 'object' + ? (reason as { kind?: unknown }).kind + : undefined + if (typeof kind !== 'string') return 'completed' + switch (kind) { + case 'completed': + return 'completed' + case 'aborted': + case 'interrupted': + case 'blocked': + return 'cancelled' + case 'error': + case 'max-tokens': + return 'failed' + case 'forked': + return null + default: + return 'completed' + } +} + +/** Extract the numeric turn id from a `turn/start` or `turn/end` payload. */ +function turnOf(data: Record | undefined): number | undefined { + if (data === undefined) return undefined + const value = data.turn + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return Number(value) + return undefined +} + +/** Conversation (session) id, tolerating both `id` and `sessionId` shapes. */ +export function conversationIdOf(session: SessionLike | undefined): string | undefined { + if (session === undefined) return undefined + const value = session.id ?? session.sessionId + return typeof value === 'string' && value !== '' ? value : undefined +} + + +/** Text pulled out of one `user/message` or `assistant/message` payload. */ +export function textOf(value: unknown, depth = 0): string | undefined { + if (depth > 5) return undefined + if (typeof value === 'string') return value.trim() === '' ? undefined : value + if (Array.isArray(value)) { + const parts: string[] = [] + for (const item of value) { + if (item !== null && typeof item === 'object') { + const part = item as Record + // Tool calls/results are never summarized: they can carry files and secrets. + if (part.type === 'tool_use' || part.type === 'tool_result' || part.type === 'image') continue + if (part.type === 'text' && typeof part.text === 'string') { + parts.push(part.text) + continue + } + } + const nested = textOf(item, depth + 1) + if (nested !== undefined) parts.push(nested) + } + return parts.length === 0 ? undefined : parts.join('\n') + } + if (value === null || typeof value !== 'object') return undefined + const record = value as Record + for (const key of ['text', 'message', 'content', 'body']) { + const nested = textOf(record[key], depth + 1) + if (nested !== undefined) return nested + } + return undefined +} + +/** Local redaction: a summary must not carry credentials to the cloud. */ +const REDACTIONS: [RegExp, string][] = [ + [/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/g, '[已脱敏:私钥]'], + [/\b(sk|ghp|gho|ghs|xox[abprs]|cmt|cmr)_[A-Za-z0-9_-]{12,}/g, '[已脱敏:令牌]'], + [/\bBearer\s+[A-Za-z0-9._-]{16,}/gi, 'Bearer [已脱敏]'], + [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, '[已脱敏:JWT]'], + [/((?:password|passwd|pwd|secret|api[_-]?key|access[_-]?token)\s*[:=]\s*)[^\s,;]{6,}/gi, '$1[已脱敏]'], +] + +export function redactSecrets(text: string): string { + let out = text + for (const [pattern, replacement] of REDACTIONS) out = out.replace(pattern, replacement) + return out +} + +/** One buffered message, tagged with the turn it belongs to when known. */ +interface BufferedMessage extends SummaryMessage { + turn?: number +} + +/** + * Tracks open turns and reports each finished one. + * + * Reporting never blocks the agent loop: a failed POST is queued and retried by + * {@link flush}, and a service outage only shows up in the status card. + */ +/** A queued report is retried at most this many times before being dropped. */ +const MAX_RETRY_ATTEMPTS = 5 + +export class Reporter { + private readonly startedAt = new Map() + private readonly queue: TurnPayload[] = [] + private readonly retries = new Map() + private readonly recent: ReportRecord[] = [] + private attempted = 0 + private recorded = 0 + private duplicate = 0 + private failed = 0 + private skipped = 0 + private lastSentAt: number | undefined + private lastError: string | undefined + private draining = false + /** Redacted message text per conversation, consumed at turn/end. */ + private readonly transcripts = new Map() + private summaryAttempted = 0 + private summaryStaged = 0 + private summaryFailed = 0 + private lastSummaryError: string | undefined + + constructor(private readonly options: ReporterOptions) {} + + /** Record a turn start so its duration can be reported later. */ + handleStart(session: SessionLike | undefined, event: SessionEventLike): void { + const conversationId = conversationIdOf(session) + const turn = turnOf(event.data) + if (conversationId === undefined || turn === undefined) return + const at = toEpochMs(event.time) ?? Date.now() + this.startedAt.set(`${conversationId}:${turn}`, at) + // Bound the map: a session that never ends must not leak forever. + if (this.startedAt.size > 500) { + const oldest = this.startedAt.keys().next() + if (oldest.done !== true) this.startedAt.delete(oldest.value) + } + } + + /** Handle any `session/event`; only `turn/start` and `turn/end` matter here. */ + handleEvent(session: SessionLike | undefined, event: SessionEventLike): void { + if (event === null || typeof event !== 'object') return + if (event.type === 'user/message' || event.type === 'assistant/message') { + this.collect(session, event) + return + } + if (event.type === 'turn/start') { + this.handleStart(session, event) + return + } + if (event.type !== 'turn/end') return + this.handleEnd(session, event) + } + + private handleEnd(session: SessionLike | undefined, event: SessionEventLike): void { + const settings = this.options.settings() + const conversationId = conversationIdOf(session) + const turn = turnOf(event.data) + if (conversationId === undefined || turn === undefined) return + const key = `${conversationId}:${turn}` + const completedAt = toEpochMs(event.time) ?? Date.now() + const startedAt = this.startedAt.get(key) ?? completedAt + this.startedAt.delete(key) + const reason = event.data?.reason + const status = statusForReason(reason) + if (status === null) { + this.push({ turnId: key, conversationId, status: 'cancelled', startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'forked turn is not reported' }) + this.skipped += 1 + return + } + if (!settings.enabled) { + this.push({ turnId: key, conversationId, status, startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'reporting disabled' }) + this.skipped += 1 + return + } + const token = this.options.activityToken() + if (token === '') { + this.push({ turnId: key, conversationId, status, startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'activity token not configured' }) + this.skipped += 1 + return + } + const payload: TurnPayload = { + client_id: settings.clientId, + conversation_id: conversationId, + turn_id: key, + status, + started_at: Math.min(startedAt, completedAt), + completed_at: completedAt, + } + void this.send(payload) + void this.sendSummary(conversationId, key, status) + } + + /** Buffer one redacted message for the turn that is still open. */ + private collect(session: SessionLike | undefined, event: SessionEventLike): void { + const conversationId = conversationIdOf(session) + if (conversationId === undefined) return + const raw = textOf(event.data) + if (raw === undefined) return + const value = redactSecrets(raw).slice(0, 4000) + const buffer = this.transcripts.get(conversationId) ?? [] + buffer.push({ role: event.type === 'user/message' ? 'user' : 'assistant', text: value, turn: turnOf(event.data) }) + if (buffer.length > 120) buffer.splice(0, buffer.length - 120) + this.transcripts.set(conversationId, buffer) + } + + /** Take this turn's messages out of the buffer, capped by the char budget. */ + private takeTranscript(conversationId: string, turnKey: string): SummaryMessage[] { + const buffer = this.transcripts.get(conversationId) ?? [] + const turn = Number(turnKey.slice(turnKey.lastIndexOf(':') + 1)) + const picked: SummaryMessage[] = [] + const rest: BufferedMessage[] = [] + for (const item of buffer) { + const matches = Number.isFinite(turn) && (item.turn === undefined || item.turn === turn) + if (matches) picked.push({ role: item.role, text: item.text }) + else rest.push(item) + } + this.transcripts.set(conversationId, rest) + const maxChars = Math.max(1000, this.options.summary().maxChars) + let total = 0 + const kept: SummaryMessage[] = [] + for (const message of picked) { + if (total + message.text.length > maxChars) break + kept.push(message) + total += message.text.length + } + return kept + } + + /** Stage one summary; failures only surface in the status card. */ + private async sendSummary(conversationId: string, turnKey: string, status: TurnStatus): Promise { + const summary = this.options.summary() + const token = this.options.summaryToken() + if (!summary.enabled || token === '' || status !== 'completed') return + const messages = this.takeTranscript(conversationId, turnKey) + if (messages.length === 0) return + const payload: SummaryPayload = { conversation_id: conversationId, turn_id: turnKey, messages } + this.summaryAttempted += 1 + const result = await this.options.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) + if (retry.ok) { + this.summaryStaged += typeof retry.data.staged === 'number' ? retry.data.staged : 0 + return + } + } + this.summaryFailed += 1 + this.lastSummaryError = describeError(result.error) + this.options.log(`cloud-memory: turn summary failed: ${this.lastSummaryError}`) + } + + private push(record: ReportRecord): void { + this.recent.unshift(record) + if (this.recent.length > 50) this.recent.length = 50 + } + + /** Send one payload, queueing it when the failure looks transient. */ + private async send(payload: TurnPayload): Promise { + this.attempted += 1 + const token = this.options.activityToken() + const result = await this.options.client.reportTurn(payload, token) + const now = Date.now() + if (result.ok) { + const duplicate = result.data.duplicate === true || result.status === 200 + if (duplicate) this.duplicate += 1 + else this.recorded += 1 + this.retries.delete(payload.turn_id) + this.lastSentAt = now + this.push({ + turnId: payload.turn_id, + conversationId: payload.conversation_id, + status: payload.status, + startedAt: payload.started_at, + completedAt: payload.completed_at, + at: now, + outcome: duplicate ? 'duplicate' : 'recorded', + httpStatus: result.status, + }) + return + } + this.lastError = describeError(result.error) + this.failed += 1 + this.push({ + turnId: payload.turn_id, + conversationId: payload.conversation_id, + status: payload.status, + startedAt: payload.started_at, + completedAt: payload.completed_at, + at: now, + outcome: 'queued', + httpStatus: result.error.status, + error: this.lastError, + }) + // 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) + if (this.queue.length > 200) this.queue.shift() + } + this.options.log(`cloud-memory: turn report failed: ${this.lastError}`) + } + + /** Retry queued reports; safe to call at any time. */ + async flush(): Promise<{ sent: number; remaining: number }> { + if (this.draining) return { sent: 0, remaining: this.queue.length } + this.draining = true + let sent = 0 + try { + while (this.queue.length > 0) { + const payload = this.queue[0] + if (payload === undefined) break + this.attempted += 1 + const result = await this.options.client.reportTurn(payload, this.options.activityToken()) + if (!result.ok) { + this.lastError = describeError(result.error) + this.failed += 1 + const attempt = (this.retries.get(payload.turn_id) ?? 0) + 1 + if (attempt >= MAX_RETRY_ATTEMPTS) { + // Give up on this turn: a permanently failing endpoint must not keep + // an unbounded queue of metadata forever. + this.queue.shift() + this.retries.delete(payload.turn_id) + this.options.log(`cloud-memory: dropping turn report after ${attempt} attempts: ${this.lastError}`) + continue + } + this.retries.set(payload.turn_id, attempt) + break + } + this.queue.shift() + this.retries.delete(payload.turn_id) + sent += 1 + if (result.data.duplicate === true || result.status === 200) this.duplicate += 1 + else this.recorded += 1 + this.lastSentAt = Date.now() + } + } finally { + this.draining = false + } + return { sent, remaining: this.queue.length } + } + + /** Counters + recent history. */ + snapshot(): ReporterSnapshot { + return { + attempted: this.attempted, + recorded: this.recorded, + duplicate: this.duplicate, + failed: this.failed, + skipped: this.skipped, + queued: this.queue.length, + summaryAttempted: this.summaryAttempted, + summaryStaged: this.summaryStaged, + summaryFailed: this.summaryFailed, + ...(this.lastSummaryError === undefined ? {} : { lastSummaryError: this.lastSummaryError }), + ...(this.lastSentAt === undefined ? {} : { lastSentAt: this.lastSentAt }), + ...(this.lastError === undefined ? {} : { lastError: this.lastError }), + recent: [...this.recent], + } + } +} diff --git a/src/routes.ts b/src/routes.ts new file mode 100644 index 0000000..a85bb90 --- /dev/null +++ b/src/routes.ts @@ -0,0 +1,485 @@ +/** + * HTTP surface served by the host web server. + * + * All routes live under `/cloud-memory`: + * - `GET /cloud-memory` configuration page (HTML) + * - `GET /cloud-memory/status` settings + reporter counters (JSON) + * - `PUT /cloud-memory/config` apply a settings patch (JSON) + * - `POST /cloud-memory/login` password sign-in, mints both tokens (JSON) + * - `POST /cloud-memory/test` validate both tokens (JSON) + * - `POST /cloud-memory/flush` retry the queued reports (JSON) + * + * Every JSON route is same-origin only: the tokens are read from the local file + * and never echoed back, but a cross-site `PUT` could still be used to redirect + * reports to an attacker's base URL, so the origin check stays on. + */ +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { CloudClient } from './api.ts' +import { describeError, isSecureLoginTarget } from './api.ts' +import type { SettingsView, SettingsStore, TokenView } from './store.ts' +import type { Reporter } from './reporter.ts' +import { renderConfigPage } from './page.ts' +import type { CloudMemoryWebRoute } from './context-types.ts' +import type { SkillSyncStats } from './skill-sync.ts' +import { SkillAdminError } from './skill-admin.ts' +import type { SkillAdmin } from './skill-admin.ts' +import { renderSkillsPage } from './skill-page.ts' + +/** Route constants — kept in one place so the client half can reuse them. */ +export const ROUTES = { + page: '/cloud-memory', + status: '/cloud-memory/status', + config: '/cloud-memory/config', + login: '/cloud-memory/login', + test: '/cloud-memory/test', + flush: '/cloud-memory/flush', + skills: '/cloud-memory/skills', +} as const + +/** Largest request body we accept (a settings patch is tiny). */ +const MAX_BODY_BYTES = 64 * 1024 + +/** Everything the routes need from the plugin core. */ +export interface RouteDeps { + version: string + store: SettingsStore + reporter: Reporter + client: () => CloudClient + /** Latest skill-sync stats, when the engine is wired in. */ + skills?: () => SkillSyncStats + /** Local skill management (list / toggle / trash / install), when wired in. */ + admin?: SkillAdmin +} + +/** Collect a request body as UTF-8 text. */ +async function readBody(req: IncomingMessage, maxBytes = MAX_BODY_BYTES): Promise { + const chunks: Buffer[] = [] + let bytes = 0 + for await (const chunk of req) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array) + 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. */ +function sameOrigin(req: IncomingMessage): boolean { + 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. */ +function json(res: ServerResponse, status: number, body: unknown): void { + 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). */ +function fail(res: ServerResponse, status: number, message: string, asHtml = false): void { + const text = asHtml + ? `云端记忆${message}` + : 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) +} + +/** The payload the page and the client card both consume. */ +function statusPayload(deps: RouteDeps): Record { + const view = deps.store.describe() + const tokens: Record<'activity' | 'memory' | 'summary', TokenView> = { + activity: view.activityToken, + memory: view.memoryToken, + summary: view.summaryToken, + } + const settings = { + enabled: view.enabled, + baseUrl: view.baseUrl, + clientId: view.clientId, + requestTimeoutMs: view.requestTimeoutMs, + defaultK: view.defaultK, + summaryEnabled: view.summaryEnabled, + summaryMaxChars: view.summaryMaxChars, + skillsSyncEnabled: view.skillsSyncEnabled, + skillsDir: view.skillsDir, + } + return { + ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot(), + ...(deps.skills === undefined ? {} : { skills: deps.skills() }), + } +} + +/** Serve the configuration page. */ +function servePage(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): void { + 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) +} + +/** `GET /cloud-memory/status`. */ +function serveStatus(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): void { + if (req.method !== 'GET') { + fail(res, 405, 'method-not-allowed') + return + } + json(res, 200, statusPayload(deps)) +} + +/** `PUT /cloud-memory/config`. */ +async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + if (req.method !== 'PUT' && req.method !== 'POST') { + fail(res, 405, 'method-not-allowed') + return + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected') + return + } + const type = (req.headers['content-type'] ?? '').toLowerCase() + if (!type.startsWith('application/json')) { + fail(res, 415, 'json-required') + return + } + let patch: unknown + try { + patch = JSON.parse(await readBody(req)) + } catch (error) { + fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json') + return + } + if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { + fail(res, 400, 'invalid-patch') + return + } + const result = deps.store.patch(patch as Record) + if (!result.ok) { + fail(res, 400, result.error ?? 'invalid-patch') + return + } + json(res, 200, statusPayload(deps)) +} + +/** `POST /cloud-memory/test` — validate both tokens without recording anything. */ +async function serveTest(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + 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 activityToken = deps.store.activityToken() + const memoryToken = deps.store.memoryToken() + + const activity: { ok: boolean; message: string } = activityToken === '' + ? { ok: false, message: '还没填令牌:把 activity:write 密钥粘到下面「活动上报令牌」再点保存' } + : await (async () => { + const probe = await client.probeActivity(activityToken) + return probe.ok + ? { ok: true, message: '令牌有效(鉴权通过)' } + : { ok: false, message: describeError(probe.error) } + })() + + const memory: { ok: boolean; message: string } = memoryToken === '' + ? { ok: false, message: '还没填令牌:把 memory:write 密钥粘到下面「记忆读写令牌」再点保存' } + : await (async () => { + const probe = await client.projects() + return probe.ok + ? { ok: true, message: `令牌有效(${(probe.data.projects ?? []).length} 个项目)` } + : { ok: false, message: describeError(probe.error) } + })() + + const summaryToken = deps.store.summaryToken() + const summary = !deps.store.settings().summaryEnabled + ? { ok: false, message: '自动摘要已关闭(可在下方勾选开启)' } + : summaryToken === '' + ? { ok: false, message: '未配置摘要令牌:留空则不做自动摘要' } + : await (async () => { + const probe = await client.probeSummary(summaryToken) + return probe.ok + ? { ok: true, message: '摘要令牌有效(只进待确认队列)' } + : { ok: false, message: describeError(probe.error) } + })() + + json(res, 200, { ok: true, activity, memory, summary }) +} + +/** `POST /cloud-memory/flush`. */ +async function serveFlush(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + 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 }) +} + +/** Labels attached to the two tokens this plugin asks the dashboard to mint. */ +const TOKEN_LABELS = { + activity: 'DSH desktop 活动上报', + memory: 'DSH desktop 记忆读写', + summary: 'DSH desktop 对话摘要', +} as const + +/** + * `POST /cloud-memory/login` — sign in with the cloud account and exchange it + * for the two scoped tokens. + * + * The password is used once, in memory, and never written anywhere: the flow is + * password → short-lived session cookie → two `cmt_…` 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: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + if (req.method !== 'POST') { + fail(res, 405, 'method-not-allowed') + return + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected') + return + } + const target = deps.store.settings().baseUrl + if (!isSecureLoginTarget(target)) { + // Refuse to put a password on a plaintext channel that is not loopback. + json(res, 400, { ok: false, error: '服务地址不是 HTTPS,拒绝在上面发送密码,请先把服务地址改成 https://' }) + return + } + let raw: string + try { + raw = await readBody(req) + } catch { + fail(res, 413, 'request-too-large') + return + } + let body: Record + try { + const parsed: unknown = JSON.parse(raw) + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('object required') + body = parsed as Record + } 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) + if (!session.ok) { + const status = session.error.status === 429 ? 429 : 401 + json(res, status, { ok: false, error: describeError(session.error) }) + return + } + + const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity) + const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory) + const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary) + 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 + } + + const patch: Parameters[0] = {} + 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 + 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, { + ...statusPayload(deps), + 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)}`, + }, + }) +} + + +/** HTTP status for one skill-admin failure code. */ +function adminStatus(code: string): number { + switch (code) { + case 'not_found': return 404 + case 'invalid_name': + case 'invalid_url': return 400 + case 'collision': + case 'sync_running': return 409 + case 'no_skills_found': return 422 + case 'git_failed': return 502 + default: return 500 + } +} + +/** + * The skill management surface, one prefix route: + * `GET /cloud-memory/skills` the management page + * `GET /cloud-memory/skills/api` inventory JSON (skills + trash) + * `POST /cloud-memory/skills/toggle` { folder, enabled } + * `POST /cloud-memory/skills/remove` { folder } + * `POST /cloud-memory/skills/install` { url } + */ +async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + if (deps.admin === undefined) { + fail(res, 404, 'skills-admin-unavailable') + return + } + const admin = deps.admin + const suffix = (req.url ?? '').split('?')[0]?.slice(ROUTES.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 + } + json(res, 200, { ok: true, ...(await admin.list()) }) + return + } + const actions: Record) => Promise>> = { + '/toggle': async (body) => admin.setEnabled(body.folder, body.enabled === true), + '/remove': async (body) => admin.remove(body.folder), + '/install': async (body) => admin.installFromGit(body.url), + } + const action = actions[suffix] + if (action === undefined) { + fail(res, 404, 'unknown-skill-route') + return + } + if (req.method !== 'POST') { + fail(res, 405, 'method-not-allowed') + return + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected') + return + } + const type = (req.headers['content-type'] ?? '').toLowerCase() + if (!type.startsWith('application/json')) { + fail(res, 415, 'json-required') + return + } + let body: unknown + try { + body = JSON.parse(await readBody(req)) + } catch { + fail(res, 400, 'invalid-json') + return + } + if (body === null || typeof body !== 'object' || Array.isArray(body)) { + fail(res, 400, 'invalid-body') + return + } + try { + json(res, 200, { ok: true, ...(await action(body as Record)) }) + } catch (error) { + if (error instanceof SkillAdminError) { + json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message }) + } else { + json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) }) + } + } +} + +/** Build the exact-route table registered with the host web server. */ +export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] { + return [ + { + kind: 'exact', + path: ROUTES.page, + handler: (req, res) => servePage(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.status, + handler: (req, res) => serveStatus(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.config, + handler: (req, res) => serveConfig(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.login, + handler: (req, res) => serveLogin(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.test, + handler: (req, res) => serveTest(deps, req, res), + }, + { + kind: 'exact', + path: ROUTES.flush, + handler: (req, res) => serveFlush(deps, req, res), + }, + { + kind: 'prefix', + path: ROUTES.skills, + handler: (req, res) => serveSkills(deps, req, res), + }, + ] +} diff --git a/src/skill-admin.ts b/src/skill-admin.ts new file mode 100644 index 0000000..49709e1 --- /dev/null +++ b/src/skill-admin.ts @@ -0,0 +1,276 @@ +/** + * Local skill management, built into the plugin: list, enable/disable, + * real delete, and install from a git repository. + * + * This covers the everyday subset of a full skills manager. It manages + * only the DSH skills root (plus its own parking and trash areas) — the + * cloud sync engine keeps owning everything beyond the local disk. + * + * Enable/disable is deliberately mechanical: a disabled skill's folder + * is parked in `$DSH_HOME/skills-disabled/`, outside the skills root, so + * DSH simply does not see it. No host internals are involved, which + * keeps the operation reversible and predictable. The sync engine knows + * about the parking area: parked skills are neither resurrected nor + * mistaken for deletions, and a parked cloud skill still receives its + * cloud updates in place. + * + * Delete is a real delete: the folder is removed recursively. The + * cloud copy is unaffected — local deletion never propagates to the + * center (the sync engine remembers the removal, so the same cloud + * version is not pulled back down either). + */ +import { execFile } from 'node:child_process' +import { cp, mkdir, readFile, readdir, rename, rm, stat } from 'node:fs/promises' +import { basename, join } from 'node:path' +import { parseSkillFrontmatter } from './skill-sync.ts' +import { dshHome } from './store.ts' + +/** The parking area for disabled skills. */ +export function skillsHoldingDir(): string { + return join(dshHome(), 'skills-disabled') +} + +/** A management failure with a stable machine-readable code. */ +export class SkillAdminError extends Error { + constructor(readonly code: string, message: string) { + super(message) + this.name = 'SkillAdminError' + } +} + +function fail(code: string, message: string): never { + throw new SkillAdminError(code, message) +} + +/** One skill as the management page shows it. */ +export interface AdminSkill { + folder: string + name: string + description: string + enabled: boolean + origin: 'cloud' | 'uploaded' | 'local' + revision?: number + files: number +} + +/** Dependencies of one admin instance. */ +export interface SkillAdminDeps { + skillsRoot: () => string + holdingDir: () => string + /** The sync sidecar (read-only here) for origin and revision facts. */ + syncStatePath: () => string + /** True while a sync pass is running; mutations refuse meanwhile. */ + syncRunning: () => boolean + log: (message: string) => void +} + +async function isDirectory(path: string): Promise { + return stat(path).then((s) => s.isDirectory()).catch(() => false) +} + +/** Count files below a directory, capped so a stray tree cannot hang us. */ +async function countFiles(dir: string, cap = 2000): Promise { + let count = 0 + const walk = async (sub: string): Promise => { + if (count > cap) return + for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) { + if (entry.name === '.git') continue + const rel = sub === '' ? entry.name : `${sub}/${entry.name}` + if (entry.isDirectory()) await walk(rel) + else if (entry.isFile()) count += 1 + } + } + await walk('') + return count +} + +/** A folder name we are willing to move around: one path segment, no tricks. */ +function checkFolder(folder: unknown): string { + if ( + typeof folder !== 'string' || folder === '' || folder.length > 128 || + folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0') + ) { + fail('invalid_name', `技能目录名无效:${String(folder)}`) + } + return folder +} + +export class SkillAdmin { + constructor(private readonly deps: SkillAdminDeps) {} + + private guardSync(): void { + if (this.deps.syncRunning()) fail('sync_running', '技能同步正在进行,请稍候再试。') + } + + private async syncUploaded(): Promise> { + try { + const parsed: unknown = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8')) + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + const uploaded = (parsed as { uploaded?: unknown }).uploaded + if (uploaded !== null && typeof uploaded === 'object' && !Array.isArray(uploaded)) { + return uploaded as Record + } + } + } catch { + // No sidecar yet: nothing has been uploaded. + } + return {} + } + + private async describe(folder: string, dir: string, enabled: boolean, uploaded: Record): Promise { + const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) + if (markdown === undefined) return undefined + const frontmatter = parseSkillFrontmatter(markdown) + let origin: AdminSkill['origin'] = 'local' + let revision: number | undefined + const delivery = await readFile(join(dir, '.manifest.json'), 'utf8').catch(() => undefined) + if (delivery !== undefined) { + origin = 'cloud' + try { + const parsed: unknown = JSON.parse(delivery) + const value = (parsed as { revision?: unknown }).revision + if (typeof value === 'number') revision = value + } catch { /* a corrupt manifest still marks cloud origin */ } + } else { + for (const record of Object.values(uploaded)) { + if (record.folder === folder) { + origin = 'uploaded' + revision = record.revision + break + } + } + } + return { + folder, + name: frontmatter.name ?? folder, + description: (frontmatter.description ?? '').slice(0, 300), + enabled, + origin, + ...(revision === undefined ? {} : { revision }), + files: await countFiles(dir), + } + } + + /** Inventory of the skills root and the parking area. */ + async list(): Promise<{ skills: AdminSkill[] }> { + const uploaded = await this.syncUploaded() + const skills: AdminSkill[] = [] + const scan = async (area: string, enabled: boolean): Promise => { + 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) + if (described !== undefined) skills.push(described) + } + } + await scan(this.deps.skillsRoot(), true) + await scan(this.deps.holdingDir(), false) + skills.sort((a, b) => (a.folder < b.folder ? -1 : 1)) + return { skills } + } + + /** Locate a skill folder across the root and the parking area. */ + private async locate(folder: string): Promise<{ area: 'root' | 'holding'; dir: string } | undefined> { + 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 + } + + /** Enable (move back into the root) or disable (park) one skill. */ + async setEnabled(folderInput: unknown, enabled: boolean): Promise<{ folder: string; enabled: boolean }> { + this.guardSync() + const folder = checkFolder(folderInput) + const found = await this.locate(folder) + if (found === undefined) fail('not_found', `没有找到技能:${folder}`) + const targetArea = enabled ? 'root' : 'holding' + if (found.area === targetArea) return { folder, enabled } + const targetRoot = enabled ? this.deps.skillsRoot() : this.deps.holdingDir() + await mkdir(targetRoot, { recursive: true }) + const target = join(targetRoot, folder) + if (await isDirectory(target)) fail('collision', `目标位置已存在同名技能:${folder}`) + await rename(found.dir, target) + this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`) + return { folder, enabled } + } + + /** Delete one skill for real: its folder is removed recursively. */ + async remove(folderInput: unknown): Promise<{ folder: string }> { + this.guardSync() + const folder = checkFolder(folderInput) + const found = await this.locate(folder) + if (found === undefined) fail('not_found', `没有找到技能:${folder}`) + await rm(found.dir, { recursive: true, force: true }) + this.deps.log(`skill deleted: ${folder}`) + return { folder } + } + + /** + * Install every skill found in a git repository (https:// or file://). + * The clone is shallow and never executes repository code; folders + * that collide with existing skills are skipped, never overwritten. + */ + async installFromGit(urlInput: unknown): Promise<{ installed: string[]; skipped: { name: string; reason: string }[] }> { + this.guardSync() + if (typeof urlInput !== 'string') fail('invalid_url', '请提供仓库地址。') + const url = urlInput.trim() + if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) { + fail('invalid_url', '只接受 https:// 或 file:// 的 git 仓库地址。') + } + const scratch = join(dshHome(), `.cloud-memory-clone-${process.pid}-${Date.now().toString(36)}`) + try { + await new Promise((resolvePromise, rejectPromise) => { + execFile( + 'git', + ['clone', '--depth', '1', '--no-tags', '--', url, scratch], + { timeout: 120_000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 }, + (error) => (error ? rejectPromise(error) : resolvePromise()), + ) + }) + } catch { + await rm(scratch, { recursive: true, force: true }).catch(() => {}) + fail('git_failed', '仓库克隆失败(地址不可达、需要登录,或本机没有 git)。') + } + try { + const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill' + const candidates: { folder: string; dir: string }[] = [] + const collect = async (dir: string, depth: number): Promise => { + if (await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) !== undefined) { + candidates.push({ folder: dir === scratch ? repoName : basename(dir), dir }) + return + } + if (depth >= 3) return + for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + if (entry.isDirectory() && entry.name !== '.git') await collect(join(dir, entry.name), depth + 1) + } + } + await collect(scratch, 0) + if (candidates.length === 0) fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。') + const installed: string[] = [] + const skipped: { name: string; reason: string }[] = [] + await mkdir(this.deps.skillsRoot(), { recursive: true }) + for (const candidate of candidates) { + let folder = candidate.folder + try { + folder = checkFolder(folder) + } catch { + skipped.push({ name: candidate.folder, reason: 'invalid_name' }) + continue + } + if ((await this.locate(folder)) !== undefined) { + skipped.push({ name: folder, reason: 'already_exists' }) + continue + } + await cp(candidate.dir, join(this.deps.skillsRoot(), folder), { + recursive: true, + filter: (source) => !source.split(/[\\/]/).includes('.git'), + }) + installed.push(folder) + this.deps.log(`skill installed from git: ${folder}`) + } + return { installed, skipped } + } finally { + await rm(scratch, { recursive: true, force: true }).catch(() => {}) + } + } +} diff --git a/src/skill-page.ts b/src/skill-page.ts new file mode 100644 index 0000000..76e0868 --- /dev/null +++ b/src/skill-page.ts @@ -0,0 +1,161 @@ +/** + * The local skill management page (`GET /cloud-memory/skills`). + * + * A thin shell: the browser fetches the JSON inventory from + * `/cloud-memory/skills/api` and renders it; every action is a small + * JSON POST back to the same prefix. All skill data is inserted with + * textContent, never as raw HTML. + */ +export function renderSkillsPage(options: { version: string }): string { + return ` + + + + +技能管理 · 云端记忆插件 + + + +
+

技能管理

+

v${options.version} · 本机技能的列表、启停、安装;删除是真删、不可恢复(云端副本不受影响)。云端同步仍在后台自动进行。← 返回云端记忆设置

+ +
+

从 git 仓库安装

+
+ + +
+
+
+ +
+

本机技能

+
+
+
+
+ + + +` +} diff --git a/src/skill-sync.ts b/src/skill-sync.ts new file mode 100644 index 0000000..aed3161 --- /dev/null +++ b/src/skill-sync.ts @@ -0,0 +1,565 @@ +/** + * Bidirectional skill sync between the cloud skill center and the local + * DSH skills directory (`$DSH_HOME/skills` by default). + * + * The cloud center is the hub, the local directory is a working copy, and + * the DSH skills manager keeps owning local management — this module only + * moves files, in both directions: + * + * - DOWN: cloud skills are installed exactly like the platform's own + * `skills-sync` tool does it — bundle hash and per-file checksums are + * verified before anything lands, writes are atomic per file, and a + * per-skill `.manifest.json` records what the cloud delivered. + * - UP: skills that originated locally (installed by the skills manager, + * imported, or written by hand) are published to the center as new + * revisions, guarded by the center's `expected_revision` check. + * + * Safety rules (deliberate, in order): + * 1. A cloud-delivered skill is never re-uploaded. If its local files no + * longer match the delivery manifest, the skill is flagged as a + * conflict and left completely alone. + * 2. A local deletion never deletes the cloud copy. + * 3. A name that already exists on the other side is never hijacked; + * it is reported as a conflict for a human to resolve. + * 4. Bundles whose scripts changed on the cloud side are not installed + * until the change is acknowledged in the dashboard, mirroring the + * center's own review flag. + * 5. Only the center's file layout is uploadable (SKILL.md at the root, + * everything else under references/, scripts/ or assets/, with the + * center's extension allowlist). Anything else is reported, never + * silently trimmed. + */ +import { createHash, randomUUID } from 'node:crypto' +import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises' +import { dirname, join, resolve } from 'node:path' +import type { CloudClient, SkillBundle, SkillSummary, SkillUploadFile } from './api.ts' +import { describeError } from './api.ts' +import { dshHome } from './store.ts' + +/** Cloud skill names: lowercase kebab, at most 64 characters. */ +export const CLOUD_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/ + +/** Layout contract of the cloud skill center (mirrors its store rules). */ +const TEXT_EXT = new Set(['.md', '.txt', '.json', '.yaml', '.yml', '.py', '.sh', '.ps1', '.mjs', '.js', '.ts', '.tsx', '.css', '.html', '.csv']) +const BINARY_EXT = new Set(['.docx', '.xlsx', '.pptx', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.zip']) +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}$/ +const MAX_FILES = 100 +const MAX_FILE_BYTES = 512 * 1024 +const MAX_SKILL_BYTES = 2 * 1024 * 1024 +const MAX_DEPTH = 3 + +/** SHA-256 of a buffer or UTF-8 string, hex-encoded. */ +export function sha256Hex(data: Buffer | string): string { + 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: readonly { path: string; sha256: string }[]): string { + 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: string): boolean { + 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: string): { name?: string; description?: string } { + if (!markdown.startsWith('---')) return {} + const end = markdown.indexOf('\n---', 3) + if (end === -1) return {} + const out: { name?: string; description?: string } = {} + 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 +} + +/** One sync conflict a human should look at; sync never forces these. */ +export interface SkillSyncConflict { + name: string + reason: string +} + +/** Outcome of the most recent (or running) sync pass. */ +export interface SkillSyncStats { + running: boolean + lastRunAt?: string + lastError?: string + downloaded: string[] + uploaded: string[] + updated: string[] + conflicts: SkillSyncConflict[] + skipped: number +} + +/** What the sidecar remembers about one locally-originated upload. */ +interface UploadRecord { + folder: string + revision: number + manifest: string + syncedAt: string +} + +/** Sidecar state: `$DSH_HOME/cloud-memory-skills.json`. */ +interface SyncState { + version: 1 + uploaded: Record + /** Cloud skills currently delivered locally, by delivered manifest. */ + delivered: Record + /** + * Skills the user deleted locally, by the cloud manifest at deletion + * time. A deleted skill stays deleted until the cloud publishes a + * different manifest; the cloud copy itself is never removed. + */ + removed: Record +} + +/** One local file read from disk. */ +interface LocalFile { + rel: string + buffer: Buffer +} + +/** Dependencies of one sync engine instance. */ +export interface SkillSyncDeps { + client: () => CloudClient + settings: () => { enabled: boolean; skillsSyncEnabled: boolean; skillsDir: string } + log: (message: string) => void + /** Parking area for disabled skills; parked skills are synced in place. */ + holdingDir?: () => string +} + +async function isDirectory(path: string): Promise { + return stat(path).then((value) => value.isDirectory()).catch(() => false) +} + +/** The per-skill delivery record the platform's own tooling writes. */ +interface DeliveryManifest { + name?: string + revision?: number + manifest_sha256?: string + files?: { path: string; sha256: string }[] +} + +export class SkillSync { + private running = false + private current: SkillSyncStats = { + running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0, + } + + constructor(private readonly deps: SkillSyncDeps) {} + + /** Stats of the latest pass, for the status endpoint. */ + stats(): SkillSyncStats { + return this.current + } + + /** The local skills root this engine syncs. */ + skillsRoot(): string { + const dir = this.deps.settings().skillsDir + return dir !== '' ? resolve(dir) : join(dshHome(), 'skills') + } + + /** The parking area where disabled skills wait, outside the root. */ + holdingRoot(): string { + return this.deps.holdingDir?.() ?? join(dshHome(), 'skills-disabled') + } + + private statePath(): string { + return join(dshHome(), 'cloud-memory-skills.json') + } + + private async loadState(): Promise { + const clean = { version: 1 as const, uploaded: {}, delivered: {}, removed: {} } + try { + const parsed: unknown = JSON.parse(await readFile(this.statePath(), 'utf8')) + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + const raw = parsed as { uploaded?: unknown; delivered?: unknown; removed?: unknown } + const map = (value: unknown): Record => + value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {} + return { + version: 1, + uploaded: map(raw.uploaded) as Record, + delivered: map(raw.delivered) as Record, + removed: map(raw.removed) as Record, + } + } + } catch { + // Missing or corrupt sidecar: start clean; the cloud is the truth. + } + return clean + } + + private async saveState(state: SyncState): Promise { + const path = this.statePath() + await mkdir(dirname(path), { recursive: true }) + const temporary = `${path}.tmp-${process.pid}` + await writeFile(temporary, JSON.stringify(state, null, 2)) + await rename(temporary, path) + } + + /** Read every syncable file of one skill directory (unsorted walk). */ + private async readSkillFiles(dir: string): Promise { + const out: LocalFile[] = [] + const walk = async (sub: string): Promise => { + const entries = await readdir(join(dir, sub), { withFileTypes: true }) + for (const entry of entries) { + const rel = sub === '' ? entry.name : `${sub}/${entry.name}` + if (entry.name.startsWith('.')) continue + if (entry.isDirectory()) { + await walk(rel) + } else if (entry.isFile()) { + out.push({ rel, buffer: await readFile(join(dir, rel)) }) + } + } + } + await walk('') + return out.sort((a, b) => (a.rel < b.rel ? -1 : 1)) + } + + /** True when a cloud-delivered directory still matches its manifest. */ + private async deliveredIntact(dir: string, delivery: DeliveryManifest): Promise { + const recorded = delivery.files ?? [] + let files: LocalFile[] + try { + files = await this.readSkillFiles(dir) + } catch { + return false + } + const current = files.filter((file) => file.rel !== '.manifest.json') + if (current.length !== recorded.length) return false + const byPath = new Map(current.map((file) => [file.rel, sha256Hex(file.buffer)])) + return recorded.every((file) => byPath.get(file.path) === file.sha256) + } + + /** Install or update one cloud skill into the local directory. */ + private async install(item: SkillSummary, bundle: SkillBundle, root: string): Promise { + const dir = join(root, item.name) + const previous = await this.readDelivery(dir) + const keep = new Set(bundle.files.map((file) => file.path)) + await mkdir(dir, { recursive: true }) + const written: { path: string; sha256: string; size: number }[] = [] + for (const file of bundle.files) { + const buffer = Buffer.from(file.data, 'base64') + if (sha256Hex(buffer) !== file.sha256) throw new Error(`checksum mismatch for ${file.path}`) + const target = join(dir, ...file.path.split('/')) + await mkdir(dirname(target), { recursive: true }) + const temporary = `${target}.tmp-${process.pid}` + await writeFile(temporary, buffer) + await rename(temporary, target) + written.push({ path: file.path, sha256: file.sha256, size: buffer.length }) + } + for (const file of previous?.files ?? []) { + if (!keep.has(file.path)) await rm(join(dir, ...file.path.split('/')), { force: true }) + } + const delivery: DeliveryManifest & { synced_at: string } = { + name: item.name, + revision: bundle.revision, + manifest_sha256: bundle.manifest_sha256, + files: written, + synced_at: new Date().toISOString(), + } + await writeFile(join(dir, '.manifest.json'), JSON.stringify(delivery, null, 2)) + } + + private async readDelivery(dir: string): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(join(dir, '.manifest.json'), 'utf8')) + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + return parsed as DeliveryManifest + } + } catch { + // Not a cloud-delivered skill. + } + return undefined + } + + /** One full pass; never throws — outcomes land in the stats. */ + async syncOnce(): Promise { + if (this.running) return this.current + const settings = this.deps.settings() + if (!settings.enabled || !settings.skillsSyncEnabled) return this.current + this.running = true + const stats: SkillSyncStats = { + running: true, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0, + } + this.current = stats + try { + await this.pass(stats) + stats.lastRunAt = new Date().toISOString() + } catch (error) { + stats.lastError = error instanceof Error ? error.message : String(error) + this.deps.log(`skill sync failed: ${stats.lastError}`) + } finally { + stats.running = false + this.running = false + this.current = stats + } + return this.current + } + + /** Record a conflict once per pass, however many rules trip over it. */ + private conflict(stats: SkillSyncStats, name: string, reason: string): void { + if (!stats.conflicts.some((item) => item.name === name && item.reason === reason)) { + stats.conflicts.push({ name, reason }) + } + } + + private async pass(stats: SkillSyncStats): Promise { + const client = this.deps.client() + const listing = await client.listSkills() + if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`) + const items = (listing.data.items ?? []).filter( + (item): item is SkillSummary & { name: string } => typeof item.name === 'string' && CLOUD_SKILL_NAME.test(item.name), + ) + const cloudByName = new Map(items.map((item) => [item.name, item])) + const root = this.skillsRoot() + const state = await this.loadState() + let stateDirty = false + + // ---- DOWN: cloud center -> local directory ------------------------- + for (const item of items) { + if (item.enabled === false) { stats.skipped += 1; continue } + // Locally-originated skills belong to the UP pass, even though the + // center lists them too once they are published. + if (state.uploaded[item.name] !== undefined) { stats.skipped += 1; continue } + const dir = join(root, item.name) + const parkedDir = join(this.holdingRoot(), item.name) + const inRoot = await isDirectory(dir) + const parked = !inRoot && (await isDirectory(parkedDir)) + const home = parked ? parkedDir : dir + const exists = inRoot || parked + const removed = state.removed[item.name] + if (removed !== undefined && exists) { + // The user put it back by hand; the removal is over. + delete state.removed[item.name] + stateDirty = true + } else if (removed !== undefined && item.manifest_sha256 === removed.manifest) { + // Deleted locally at this exact cloud version: keep it deleted. + stats.skipped += 1 + continue + } else if (removed !== undefined) { + // The cloud published a different version since the deletion. + delete state.removed[item.name] + stateDirty = true + } + const delivery = await this.readDelivery(home) + if (exists && delivery !== undefined) { + // Delivered before: local integrity is judged before any download. + if (!(await this.deliveredIntact(home, delivery))) { + this.conflict(stats, item.name, 'locally_modified') + continue + } + if (delivery.manifest_sha256 === item.manifest_sha256) { + if (state.delivered[item.name]?.manifest !== item.manifest_sha256) { + state.delivered[item.name] = { manifest: item.manifest_sha256 ?? '' } + stateDirty = true + } + stats.skipped += 1 + continue + } + // Intact but the cloud moved on: fall through and install the update. + } + if (exists && delivery === undefined) { + this.conflict(stats, item.name, 'name_collision') + continue + } + if (item.script_changed === true) { + // The listing already carries the review flag; don't even fetch. + this.conflict(stats, item.name, 'script_review_required') + continue + } + const bundle = await client.skillBundle(item.name) + if (!bundle.ok) { + this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`) + continue + } + if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) { + this.conflict(stats, item.name, 'manifest_mismatch') + continue + } + if (bundle.data.script_changed === true) { + this.conflict(stats, item.name, 'script_review_required') + continue + } + await this.install(item, bundle.data, parked ? this.holdingRoot() : root) + state.delivered[item.name] = { manifest: bundle.data.manifest_sha256 } + stateDirty = true + ;(exists ? stats.updated : stats.downloaded).push(item.name) + } + + // ---- UP: local originals -> cloud center --------------------------- + const folders = await readdir(root, { withFileTypes: true }).catch(() => []) + const seenFolders = new Set() + for (const entry of folders) { + if (!entry.isDirectory() || entry.name.startsWith('.')) continue + seenFolders.add(entry.name) + const dir = join(root, entry.name) + if ((await this.readDelivery(dir)) !== undefined) continue // cloud-origin: down pass owns it + const skill = await this.readLocalSkill(dir, entry.name) + if (skill === undefined) continue + if (typeof skill === 'string') { + this.conflict(stats, entry.name, skill) + continue + } + const record = state.uploaded[skill.name] + const cloud = cloudByName.get(skill.name) + if (cloud !== undefined && record === undefined) { + this.conflict(stats, skill.name, 'name_collision') + continue + } + if (record !== undefined && record.manifest === skill.manifest) { stats.skipped += 1; continue } + const files: SkillUploadFile[] = skill.files.map((file) => { + const ext = file.rel.slice(file.rel.lastIndexOf('.')).toLowerCase() + return TEXT_EXT.has(ext) + ? { path: file.rel, content: file.buffer.toString('utf8') } + : { path: file.rel, base64: file.buffer.toString('base64') } + }) + const operationId = `dsh-skill-${randomUUID()}` + if (record === undefined || cloud === undefined) { + const created = await client.createSkill({ + name: skill.name, + description: skill.description, + execution_mode: skill.hasScripts ? 'local-bundle' : 'prompt-only', + files, + expected_revision: 0, + operation_id: operationId, + }) + if (!created.ok) { + this.conflict(stats, skill.name, `upload_failed: ${describeError(created.error)}`) + continue + } + state.uploaded[skill.name] = { + folder: entry.name, + revision: created.data.skill?.revision ?? created.data.revision ?? 1, + manifest: skill.manifest, + syncedAt: new Date().toISOString(), + } + stateDirty = true + stats.uploaded.push(skill.name) + } else { + if (cloud.revision !== undefined && cloud.revision !== record.revision) { + this.conflict(stats, skill.name, 'cloud_newer') + continue + } + const updated = await client.updateSkill(skill.name, { + description: skill.description, + files, + expected_revision: record.revision, + operation_id: operationId, + }) + if (!updated.ok) { + const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}` + this.conflict(stats, skill.name, reason) + continue + } + state.uploaded[skill.name] = { + folder: entry.name, + revision: updated.data.skill?.revision ?? updated.data.revision ?? record.revision + 1, + manifest: skill.manifest, + syncedAt: new Date().toISOString(), + } + stateDirty = true + stats.updated.push(skill.name) + } + } + + // Presence counts the parking area too: a parked skill is disabled, + // not deleted. Anything missing from both is a deliberate removal + // (remembered, so it is not resurrected); the cloud copy stays. + const presentFolders = new Set(seenFolders) + for (const entry of await readdir(this.holdingRoot(), { withFileTypes: true }).catch(() => [])) { + if (entry.isDirectory()) presentFolders.add(entry.name) + } + for (const [name, record] of Object.entries(state.uploaded)) { + if (!presentFolders.has(record.folder)) { + state.removed[name] = { manifest: cloudByName.get(name)?.manifest_sha256 ?? record.manifest } + delete state.uploaded[name] + stateDirty = true + } + } + for (const [name, record] of Object.entries(state.delivered)) { + if (!presentFolders.has(name)) { + state.removed[name] = { manifest: record.manifest } + delete state.delivered[name] + stateDirty = true + } + } + if (stateDirty) await this.saveState(state) + const changed = stats.downloaded.length + stats.uploaded.length + stats.updated.length + if (changed > 0 || stats.conflicts.length > 0) { + this.deps.log( + `skill sync: ${stats.downloaded.length} downloaded, ${stats.uploaded.length} uploaded, ` + + `${stats.updated.length} updated, ${stats.conflicts.length} conflict(s)`, + ) + } + } + + /** + * Read one locally-originated skill for upload. Returns the skill, a + * conflict reason string, or undefined when the folder is not a skill. + */ + private async readLocalSkill( + dir: string, + folder: string, + ): Promise<{ name: string; description: string; files: LocalFile[]; manifest: string; hasScripts: boolean } | string | undefined> { + let files: LocalFile[] + try { + files = await this.readSkillFiles(dir) + } catch { + return undefined + } + const markdown = files.find((file) => file.rel === 'SKILL.md') + if (markdown === undefined) return undefined + if (files.length > MAX_FILES) return 'too_many_files' + let total = 0 + for (const file of files) { + if (file.buffer.length > MAX_FILE_BYTES) return 'file_too_large' + total += file.buffer.length + if (!isCloudSkillPath(file.rel)) return 'unsupported_layout' + } + if (total > MAX_SKILL_BYTES) return 'skill_too_large' + const frontmatter = parseSkillFrontmatter(markdown.buffer.toString('utf8')) + const name = frontmatter.name !== undefined && CLOUD_SKILL_NAME.test(frontmatter.name) + ? frontmatter.name + : CLOUD_SKILL_NAME.test(folder) + ? folder + : undefined + if (name === undefined) return 'invalid_name' + const heading = /^#\s+(.+)$/m.exec(markdown.buffer.toString('utf8'))?.[1]?.trim() + const description = (frontmatter.description ?? heading ?? name).slice(0, 500) + const manifest = linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) }))) + return { + name, + description, + files, + manifest, + hasScripts: files.some((file) => file.rel.startsWith('scripts/')), + } + } +} diff --git a/src/store.ts b/src/store.ts new file mode 100644 index 0000000..4223c74 --- /dev/null +++ b/src/store.ts @@ -0,0 +1,278 @@ +/** + * Settings sidecar: `$DSH_HOME/cloud-memory.json`. + * + * Why a file and not the DSH credentials service: the desktop profile has no + * stable host-side credentials face this plugin can depend on (the client-side + * `remote.credentials` proxy is a browser service), and a missed dependency + * would silently disable reporting. A 0600-ish file under the user's DSH home + * directory is the smallest thing that always works; Windows ACLs on + * `C:\Users\` already restrict it to that account. + * + * The file holds the two bearer tokens and the UI-editable overrides. It is + * NEVER uploaded, never printed, and `describe()` only exposes a mask. + */ +import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync, chmodSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { homedir } from 'node:os' +import { DEFAULT_SETTINGS, normalizeBaseUrl, settingsFromConfig, type Settings } from './config.ts' + +/** Persisted document schema. */ +export interface PersistedState { + version: 1 + enabled?: boolean + baseUrl?: string + clientId?: string + requestTimeoutMs?: number + defaultK?: number + activityToken?: string + memoryToken?: string + summaryEnabled?: boolean + summaryMaxChars?: number + summaryToken?: string +} + +/** Masked token view handed to the browser. */ +export interface TokenView { + configured: boolean + masked: string +} + +/** Browser-facing settings snapshot (no secrets). */ +export interface SettingsView extends Settings { + activityToken: TokenView + memoryToken: TokenView + summaryToken: TokenView + statePath: string +} + +/** `$DSH_HOME` (or `~/.dsh`) — the same resolution DSH core uses. */ +export function dshHome(): string { + const fromEnv = process.env.DSH_HOME + if (fromEnv !== undefined && fromEnv.trim() !== '') return fromEnv + return resolve(homedir(), '.dsh') +} + +/** Absolute path of the settings sidecar. */ +export function settingsPath(): string { + return resolve(dshHome(), 'cloud-memory.json') +} + +/** Read a token from an env var (an alternative to the sidecar for CI use). */ +function envToken(name: string): string | undefined { + const value = process.env[name] + if (value === undefined || value.trim() === '') return undefined + return value.trim() +} + +/** Mask a secret for display: `cmt_abc…9f2c`. */ +export function maskToken(token: string): string { + if (token.length <= 12) return `${token.slice(0, 3)}…` + return `${token.slice(0, 7)}…${token.slice(-4)}` +} + +/** Validate one sidecar field; returns the normalized value or undefined. */ +function cleanString(value: unknown): string | undefined { + if (typeof value !== 'string') return undefined + const trimmed = value.trim() + return trimmed === '' ? undefined : trimmed +} + +/** Coerce one numeric field into a clamped integer. */ +function clampInt(value: unknown, min: number, max: number): number | undefined { + const numeric = typeof value === 'string' ? Number(value) : value + if (typeof numeric !== 'number' || !Number.isFinite(numeric)) return undefined + return Math.min(max, Math.max(min, Math.trunc(numeric))) +} + +/** Parse an on-disk document defensively (a torn file must not break boot). */ +function parseState(raw: string): PersistedState { + try { + const value: unknown = JSON.parse(raw) + if (value === null || typeof value !== 'object' || Array.isArray(value)) return { version: 1 } + const source = value as Record + const state: PersistedState = { version: 1 } + if (typeof source.enabled === 'boolean') state.enabled = source.enabled + const baseUrl = normalizeBaseUrl(source.baseUrl) + if (baseUrl !== undefined) state.baseUrl = baseUrl + const clientId = cleanString(source.clientId) + if (clientId !== undefined) state.clientId = clientId.slice(0, 128) + const requestTimeoutMs = clampInt(source.requestTimeoutMs, 1000, 60_000) + if (requestTimeoutMs !== undefined) state.requestTimeoutMs = requestTimeoutMs + const defaultK = clampInt(source.defaultK, 1, 100) + if (defaultK !== undefined) state.defaultK = defaultK + const activityToken = cleanString(source.activityToken) + if (activityToken !== undefined) state.activityToken = activityToken + const memoryToken = cleanString(source.memoryToken) + if (memoryToken !== undefined) state.memoryToken = memoryToken + if (typeof source.summaryEnabled === 'boolean') state.summaryEnabled = source.summaryEnabled + const summaryMaxChars = clampInt(source.summaryMaxChars, 1000, 16_000) + if (summaryMaxChars !== undefined) state.summaryMaxChars = summaryMaxChars + const summaryToken = cleanString(source.summaryToken) + if (summaryToken !== undefined) state.summaryToken = summaryToken + return state + } catch { + return { version: 1 } + } +} + +/** + * In-memory + on-disk settings holder. + * + * Writes are atomic (tmp file + rename) and best-effort chmod 0600; the reader + * is tolerant, so one corrupt document degrades to defaults instead of + * failing the whole plugin activation. + */ +export class SettingsStore { + private state: PersistedState + private readonly file: string + private readonly configDefaults: Settings + + constructor(rawConfig: unknown, file: string = settingsPath()) { + this.file = file + this.configDefaults = { ...DEFAULT_SETTINGS, ...settingsFromConfig(rawConfig) } + this.state = this.read() + } + + /** Absolute sidecar path (exposed for the status card). */ + get path(): string { + return this.file + } + + private read(): PersistedState { + try { + return parseState(readFileSync(this.file, 'utf8')) + } catch { + return { version: 1 } + } + } + + private write(next: PersistedState): void { + const directory = dirname(this.file) + mkdirSync(directory, { recursive: true }) + const temporary = `${this.file}.tmp` + writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }) + renameSync(temporary, this.file) + try { + chmodSync(this.file, 0o600) + } catch { + // Windows has no POSIX mode bits; the profile ACL is the real boundary. + } + } + + /** Effective settings: config defaults, overridden by sidecar values. */ + settings(): Settings { + const resolved: Settings = { ...this.configDefaults } + if (this.state.enabled !== undefined) resolved.enabled = this.state.enabled + if (this.state.baseUrl !== undefined) resolved.baseUrl = this.state.baseUrl + if (this.state.clientId !== undefined) resolved.clientId = this.state.clientId + if (this.state.requestTimeoutMs !== undefined) resolved.requestTimeoutMs = this.state.requestTimeoutMs + if (this.state.defaultK !== undefined) resolved.defaultK = this.state.defaultK + if (this.state.summaryEnabled !== undefined) resolved.summaryEnabled = this.state.summaryEnabled + if (this.state.summaryMaxChars !== undefined) resolved.summaryMaxChars = this.state.summaryMaxChars + return resolved + } + + /** The activity:write bearer token (sidecar first, env fallback). */ + activityToken(): string { + return this.state.activityToken ?? envToken('DSH_CLOUD_MEMORY_ACTIVITY_TOKEN') ?? '' + } + + /** The memory:read / memory:write bearer token. */ + memoryToken(): string { + return this.state.memoryToken ?? envToken('DSH_CLOUD_MEMORY_MEMORY_TOKEN') ?? '' + } + + /** The summary:write bearer token (optional; absent disables summaries). */ + summaryToken(): string { + return this.state.summaryToken ?? envToken('DSH_CLOUD_MEMORY_SUMMARY_TOKEN') ?? '' + } + + /** Masked snapshot for the browser card. */ + describe(): SettingsView { + const settings = this.settings() + const activity = this.activityToken() + const memory = this.memoryToken() + 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) }, + statePath: this.file, + } + } + + /** + * Apply a partial patch from the settings card. + * + * Token fields follow "absent means keep": only a non-empty string replaces a + * stored token, and an explicit boolean `clear*` flag removes one. That way + * the browser never has to round-trip a secret it cannot read. + */ + patch(patch: Record): { ok: boolean; error?: string } { + const next: PersistedState = { ...this.state } + if (patch.enabled !== undefined) { + if (typeof patch.enabled !== 'boolean') return { ok: false, error: 'enabled must be a boolean' } + next.enabled = patch.enabled + } + if (patch.baseUrl !== undefined) { + const baseUrl = normalizeBaseUrl(patch.baseUrl) + if (baseUrl === undefined) return { ok: false, error: 'baseUrl must be an http(s) URL' } + next.baseUrl = baseUrl + } + if (patch.clientId !== undefined) { + const clientId = cleanString(patch.clientId) + if (clientId === undefined) return { ok: false, error: 'clientId must be a non-empty string' } + next.clientId = clientId.slice(0, 128) + } + const activityToken = cleanString(patch.activityToken) + if (activityToken !== undefined) { + if (!activityToken.startsWith('cmt_')) return { ok: false, error: 'activity token must start with cmt_' } + next.activityToken = activityToken + } + const memoryToken = cleanString(patch.memoryToken) + if (memoryToken !== undefined) { + if (!memoryToken.startsWith('cmt_')) return { ok: false, error: 'memory token must start with cmt_' } + next.memoryToken = memoryToken + } + if (patch.requestTimeoutMs !== undefined) { + const requestTimeoutMs = clampInt(patch.requestTimeoutMs, 1000, 60_000) + if (requestTimeoutMs === undefined) return { ok: false, error: 'requestTimeoutMs must be a number' } + next.requestTimeoutMs = requestTimeoutMs + } + if (patch.defaultK !== undefined) { + const defaultK = clampInt(patch.defaultK, 1, 100) + if (defaultK === undefined) return { ok: false, error: 'defaultK must be a number' } + next.defaultK = defaultK + } + if (patch.summaryEnabled !== undefined) { + if (typeof patch.summaryEnabled !== 'boolean') return { ok: false, error: 'summaryEnabled must be a boolean' } + next.summaryEnabled = patch.summaryEnabled + } + if (patch.summaryMaxChars !== undefined) { + const summaryMaxChars = clampInt(patch.summaryMaxChars, 1000, 16_000) + if (summaryMaxChars === undefined) return { ok: false, error: 'summaryMaxChars must be a number' } + next.summaryMaxChars = summaryMaxChars + } + 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 + } + if (patch.clearSummaryToken === true) delete next.summaryToken + if (patch.clearActivityToken === true) delete next.activityToken + if (patch.clearMemoryToken === true) delete next.memoryToken + this.write(next) + this.state = next + return { ok: true } + } + + /** File size in bytes, for a "sidecar exists" hint in the card. */ + size(): number | undefined { + try { + return statSync(this.file).size + } catch { + return undefined + } + } +} diff --git a/src/tools.ts b/src/tools.ts new file mode 100644 index 0000000..70db5c9 --- /dev/null +++ b/src/tools.ts @@ -0,0 +1,309 @@ +/** + * 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 type { CloudClient, MemoryHit } from './api.ts' +import { describeError } from './api.ts' +import type { ToolDefinitionLike } from './context-types.ts' + +/** Everything the tools need from the plugin core. */ +export interface MemoryToolDeps { + /** The configured client (rebuilt lazily; settings may change at runtime). */ + client: () => CloudClient + /** Memory token, or empty when unconfigured. */ + memoryToken: () => string + /** Effective settings. */ + settings: () => { enabled: boolean; defaultK: number } +} + +/** Text block shape the harness renders. */ +interface TextBlock { + type: 'text' + text: string +} + +/** Sectors the service accepts for `metadata.primary_sector`. */ +export const SECTORS = ['semantic', 'episodic', 'procedural', 'emotional', 'reflective'] as const + +/** Trim a memory body down to a display-sized snippet. */ +function snippet(text: string | undefined, limit = 600): string { + 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: MemoryHit): Record { + 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: unknown, value: unknown): TextBlock[] { + 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: MemoryToolDeps): string { + if (!deps.settings().enabled) { + throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /cloud-memory 页面开启后再试。') + } + const token = deps.memoryToken() + if (token === '') { + throw new Error('未配置记忆令牌。请在 /cloud-memory 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。') + } + return token +} + +/** Search stored memories by keyword. */ +function searchTool(deps: MemoryToolDeps): ToolDefinitionLike { + 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: Record): Promise { + 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: MemoryToolDeps): ToolDefinitionLike { + 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: Record): Promise { + 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: MemoryToolDeps): ToolDefinitionLike { + 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: Record): Promise { + 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): tag is string => 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 as readonly string[]).includes(args.sector) ? args.sector : undefined + const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : '' + const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID() + const result = await deps.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: MemoryToolDeps): ToolDefinitionLike { + 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: Record): Promise { + 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: MemoryToolDeps): ToolDefinitionLike { + 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(): Promise { + 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: MemoryToolDeps): ToolDefinitionLike[] { + return [searchTool(deps), readTool(deps), addTool(deps), listTool(deps), projectsTool(deps)] +} + +/** List the cloud skill center inventory (skills sync keeps local copies current). */ +function skillListTool(deps: MemoryToolDeps): ToolDefinitionLike { + return { + name: 'skill_list', + description: '列出云端技能中心的全部技能(名称、说明、版本)。技能会自动同步到本机技能目录,由 DSH 直接加载;此工具只用于查看云端有哪些技能。', + parameters: { type: 'object', properties: {}, additionalProperties: false }, + output: { + schema: { type: 'object', properties: { skills: { type: 'array', items: { type: 'object' } } }, required: ['skills'], additionalProperties: true }, + render: renderJson, + }, + async execute(): Promise { + requireMemoryToken(deps) + const result = await deps.client().listSkills() + if (!result.ok) throw new Error(`技能列表读取失败:${describeError(result.error)}`) + const skills = (result.data.items ?? []).map((item) => ({ + name: item.name, + description: item.description ?? '', + revision: item.revision ?? null, + files: item.files ?? null, + enabled: item.enabled ?? true, + })) + return { skills } + }, + } +} + +/** Build the skill-facing tools for one plugin instance. */ +export function createSkillTools(deps: MemoryToolDeps): ToolDefinitionLike[] { + return [skillListTool(deps)] +} diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..8732656 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": false, + "declarationMap": false, + "sourceMap": false, + "outDir": "lib", + "rewriteRelativeImportExtensions": true + }, + "include": ["src"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..49277df --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": false, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "types": ["node"] + }, + "include": ["src"] +} diff --git a/verify-mnemon-provider.mjs b/verify-mnemon-provider.mjs new file mode 100644 index 0000000..587751c --- /dev/null +++ b/verify-mnemon-provider.mjs @@ -0,0 +1,149 @@ +// Runtime verification for the Mnemon provider bridge (lib/mnemon). +// Runs against the built lib/ output and a stub LongMemory HTTP service; +// no DSH host, no Mnemon host, no real service, no real credentials. +import http from 'node:http' +import { mkdtempSync, readFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'dsh-home-')) + +const results = [] +function check(name, ok, detail) { + results.push({ name, ok }) + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`) +} + +// ---- Stub LongMemory service ------------------------------------------------- +const store = [] +let seq = 0 +const server = http.createServer((req, res) => { + const url = new URL(req.url, 'http://stub') + const path = url.pathname.replace(/^\/api\/longmemory/, '') + const send = (status, body) => { + res.writeHead(status, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify(body)) + } + const readBody = () => new Promise((resolve) => { + let raw = '' + req.on('data', (chunk) => { raw += chunk }) + req.on('end', () => resolve(raw === '' ? {} : JSON.parse(raw))) + }) + void (async () => { + if (req.method === 'GET' && path === '/dashboard/projects') { + return send(200, { projects: [{ id: 'p1', name: '项目一' }] }) + } + if (req.method === 'GET' && path === '/storage/status') { + return send(200, { ok: true }) + } + if (req.method === 'POST' && path === '/memory/query') { + const body = await readBody() + const project = body.filters?.project_id + const matches = store.filter((hit) => + hit.content.includes(body.query) && (project === undefined || hit.project_id === project)) + return send(200, { matches: matches.slice(0, body.k ?? 10), total: matches.length, search_mode: 'keyword' }) + } + if (req.method === 'GET' && path === '/memory/all') { + const project = url.searchParams.get('project_id') + const limit = Number(url.searchParams.get('limit') ?? 100) + const items = store.filter((hit) => project === null || hit.project_id === project) + return send(200, { items: items.slice(0, limit), total: items.length }) + } + if (req.method === 'POST' && path === '/memory/add') { + const body = await readBody() + seq += 1 + const hit = { + id: `m${seq}`, + content: body.content, + tags: body.tags ?? [], + project_id: body.project_id ?? null, + primary_sector: body.metadata?.primary_sector ?? 'general', + created_at: Date.now(), + updated_at: Date.now(), + } + store.push(hit) + return send(200, { id: hit.id, revision: 1, memory: hit }) + } + const byId = path.match(/^\/memory\/(.+)$/) + if (req.method === 'GET' && byId !== null) { + const hit = store.find((item) => item.id === decodeURIComponent(byId[1])) + return hit === undefined ? send(404, { error: 'not_found' }) : send(200, hit) + } + return send(404, { error: 'unknown_route', path }) + })() +}) +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) +const endpoint = `http://127.0.0.1:${server.address().port}/api/longmemory` +const token = '' + +// ---- Provider under test ------------------------------------------------------ +const mod = await import('./lib/mnemon/index.js') +const pkg = JSON.parse(readFileSync('./package.json', 'utf8')) + +check('default export is the longmemory provider module', + mod.default?.id === 'longmemory' && typeof mod.default?.apply === 'function') +check('manifest version matches package version', + mod.definition?.manifest?.version === pkg.version, + `${mod.definition?.manifest?.version} vs ${pkg.version}`) +check('manifest declares pass-through capabilities', + mod.definition?.manifest?.capabilities?.search === true && + mod.definition?.manifest?.capabilities?.remember === true && + mod.definition?.manifest?.capabilities?.writeMode === 'exact') + +let installed +mod.default.apply({}, { install: (ctx, def) => { installed = def } }) +check('apply installs the definition with the host', installed === mod.definition) + +let activeProject = '' +const authority = { + list: () => [], + runner: { effectiveDataDir: () => process.env.DSH_HOME }, + providerConnection: () => ({ endpoint, token, ...(activeProject === '' ? {} : { projectId: activeProject }) }), +} +const provider = mod.definition.create({ memorySpaces: authority, memoryBodies: authority, config: { timeoutMs: 3000 } }) +const body = { id: 'space-1', provider: { id: 'longmemory' }, connection: {} } + +const spaces = await provider.discover({ endpoint, token }) +check('discover returns the default scope plus projects', + spaces.length === 2 && spaces[0].externalId === 'default' && spaces[1].connection.projectId === 'p1', + spaces.map((space) => space.externalId).join(',')) + +const status = await provider.status(body) +check('status is healthy against the stub', status.healthy === true) + +const stored = await provider.remember(body, { content: '桥测试记忆 alpha', tags: ['test'], category: 'general' }) +check('remember stores live and returns the cloud id', + stored?.action === 'stored' && typeof stored?.id === 'string', JSON.stringify(stored)) + +const found = await provider.search(body, { query: 'alpha' }) +check('search recalls the memory in real time', + found.results.length === 1 && found.results[0].content.includes('alpha')) +check('search maps sector back to category', + found.results[0]?.category === 'general', found.results[0]?.category) + +const listed = await provider.list(body, {}) +check('list browses the space', listed.some((item) => item.id === stored.id)) + +const got = await provider.get(body, stored.id) +check('get reads one memory by id', got?.content === '桥测试记忆 alpha') + +activeProject = 'p1' +const storedP1 = await provider.remember(body, { content: '项目专属记忆 beta' }) +activeProject = 'other' +const otherList = await provider.list(body, {}) +check('project scoping keeps other projects out', + !otherList.some((item) => item.id === storedP1.id)) +activeProject = 'p1' +const p1List = await provider.list(body, {}) +check('project scoping finds its own memories', + p1List.some((item) => item.id === storedP1.id)) +activeProject = '' + +const graph = await provider.graph(body) +check('graph is an honest empty snapshot in v1', + Array.isArray(graph.nodes) && graph.nodes.length === 0 && Array.isArray(graph.edges)) + +server.close() +const failed = results.filter((item) => !item.ok).length +console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`) +process.exit(failed === 0 ? 0 : 1) diff --git a/verify-reporter.mjs b/verify-reporter.mjs new file mode 100644 index 0000000..f8a01a3 --- /dev/null +++ b/verify-reporter.mjs @@ -0,0 +1,110 @@ +// Runtime verification for the P0-4 client (turn reporter + CloudClient). +// Runs against the built lib/ output; no DSH host, no network, no real token. +import http from 'node:http' +import { Reporter } from './lib/reporter.js' +import { CloudClient } from './lib/api.js' +import { DEFAULT_SETTINGS, settingsFromConfig } from './lib/config.js' + +const results = [] +function check(name, ok, detail) { + results.push({ name, ok, detail }) + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`) +} + +const session = { id: 'conv-1' } +const startEvent = { type: 'turn/start', time: 1_700_000_000_000, data: { turn: 7 } } +const endEvent = { type: 'turn/end', time: 1_700_000_010_000, data: { turn: 7 } } + +function reporterWith(client, overrides = {}) { + return new Reporter({ + client, + settings: () => ({ enabled: true, clientId: 'dsh-desktop' }), + activityToken: () => 'cmt_activity_token_for_test', + summary: () => ({ enabled: false, maxChars: 6000 }), + summaryToken: () => '', + log: () => {}, + ...overrides, + }) +} + +// ---- 1. Payload shape: exactly six fields, no conversation content ---------- +{ + const sent = [] + const client = { reportTurn: async (payload, token) => { sent.push({ payload, token }); return { ok: true, status: 201, data: { recorded: true, duplicate: false } } } } + const reporter = reporterWith(client) + reporter.handleEvent(session, startEvent) + reporter.handleEvent(session, endEvent) + await new Promise(r => setTimeout(r, 20)) + const payload = sent[0]?.payload + const keys = payload === undefined ? [] : Object.keys(payload).sort() + check('payload has exactly 6 fields', JSON.stringify(keys) === JSON.stringify(['client_id', 'completed_at', 'conversation_id', 'started_at', 'status', 'turn_id']), keys.join(',')) + check('payload carries the activity token only', sent[0]?.token === 'cmt_activity_token_for_test') + check('payload has no chat body/tool/path fields', !keys.some(k => /content|prompt|message|tool|path|text|body/i.test(k)), keys.join(',')) + check('started_at <= completed_at', payload.started_at <= payload.completed_at && payload.status === 'completed', `${payload.started_at}..${payload.completed_at}`) + check('conversation and turn ids are the contract shape', payload.conversation_id === 'conv-1' && payload.turn_id === 'conv-1:7', payload.turn_id) +} + +// ---- 2. Disabled settings never touch the network --------------------------- +{ + let called = 0 + const reporter = reporterWith({ reportTurn: async () => { called += 1; return { ok: true, status: 201, data: {} } } }, { settings: () => ({ enabled: false, clientId: 'dsh-desktop' }) }) + reporter.handleEvent(session, endEvent) + await new Promise(r => setTimeout(r, 20)) + check('disabled settings skip without sending', called === 0 && reporter.snapshot().skipped === 1) +} + +// ---- 3. Missing token never sends ------------------------------------------- +{ + let called = 0 + const reporter = reporterWith({ reportTurn: async () => { called += 1; return { ok: true, status: 201, data: {} } } }, { activityToken: () => '' }) + reporter.handleEvent(session, endEvent) + await new Promise(r => setTimeout(r, 20)) + check('missing activity token skips without sending', called === 0 && reporter.snapshot().skipped === 1) +} + +// ---- 4. 4xx (other than 429) is not retried -------------------------------- +{ + let called = 0 + const reporter = reporterWith({ reportTurn: async () => { called += 1; return { ok: false, error: { status: 400, code: 'invalid_input', message: 'bad' } } } }) + reporter.handleEvent(session, endEvent) + await new Promise(r => setTimeout(r, 20)) + const flush = await reporter.flush() + check('400 is not queued for retry', called === 1 && flush.remaining === 0 && reporter.snapshot().queued === 0, `calls=${called}`) +} + +// ---- 5. 503 is queued and retried, then bounded ---------------------------- +{ + let calls = 0 + const client = { reportTurn: async () => { calls += 1; return { ok: false, error: { status: 503, code: 'upstream_unavailable', message: 'try later' } } } } + const reporter = reporterWith(client) + reporter.handleEvent(session, endEvent) + await new Promise(r => setTimeout(r, 20)) + check('503 is queued', reporter.snapshot().queued === 1) + for (let i = 0; i < 10; i += 1) await reporter.flush() + check('retries are bounded (queue drains after 5 attempts)', reporter.snapshot().queued === 0 && calls === 6, `calls=${calls}`) +} + +// ---- 6. Transport timeout is enforced by CloudClient ----------------------- +{ + const server = http.createServer((req, res) => { /* never answer */ }) + await new Promise(r => server.listen(0, '127.0.0.1', r)) + const port = server.address().port + const client = new CloudClient({ baseUrl: () => `http://127.0.0.1:${port}`, token: () => '', timeoutMs: () => 1000 }) + const started = Date.now() + const result = await client.reportTurn({ client_id: 'c', conversation_id: 'v', turn_id: 'v:1', status: 'completed', started_at: 1, completed_at: 2 }, 'cmt_activity') + const elapsed = Date.now() - started + server.close() + check('timeout aborts the request', result.ok === false && result.error.status === 0, `elapsed=${elapsed}ms code=${result.ok ? '-' : result.error.code}`) + check('timeout lands near the configured 1s', elapsed >= 900 && elapsed < 3000, `${elapsed}ms`) +} + +// ---- 7. Default and configurable timeout settings ------------------------- +{ + check('default request timeout is 5s', DEFAULT_SETTINGS.requestTimeoutMs === 5000, String(DEFAULT_SETTINGS.requestTimeoutMs)) + check('config cannot raise timeout beyond 60s', settingsFromConfig({ requestTimeoutMs: 120000 }).requestTimeoutMs === 60000) + check('config cannot lower timeout below 1s', settingsFromConfig({ requestTimeoutMs: 10 }).requestTimeoutMs === 1000) +} + +const failed = results.filter(r => !r.ok) +console.log(`\n${results.length - failed.length}/${results.length} checks passed`) +process.exit(failed.length === 0 ? 0 : 1) diff --git a/verify-skill-admin.mjs b/verify-skill-admin.mjs new file mode 100644 index 0000000..8e8e508 --- /dev/null +++ b/verify-skill-admin.mjs @@ -0,0 +1,165 @@ +// Runtime verification for the built-in skill management (lib/skill-admin) +// plus its interplay with the sync engine (lib/skill-sync): a parked +// (disabled) cloud skill must stay parked, keep receiving cloud updates +// in place, and never be resurrected into the skills root. +import http from 'node:http' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'dsh-home-')) + +const results = [] +function check(name, ok, detail) { + results.push({ name, ok }) + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`) +} +const sha = (buf) => createHash('sha256').update(buf).digest('hex') +const linked = (files) => sha(Buffer.from(`cloud-memory-skill-v1\n${files.map((f) => `${f.path}\0${f.sha256}`).sort().join('\n')}\n`, 'utf8')) +const root = join(process.env.DSH_HOME, 'skills') +const writeSkill = (area, folder, files) => { + for (const [rel, content] of Object.entries(files)) { + const target = join(area, folder, ...rel.split('/')) + mkdirSync(join(target, '..'), { recursive: true }) + writeFileSync(target, content) + } +} + +// Fixtures: one cloud-delivered skill, one uploaded local, one handmade. +const cloudyFiles = [ + { path: 'SKILL.md', content: '# cloudy v1\n' }, + { path: 'references/note.md', content: '云端说明 v1' }, +] +writeSkill(root, 'cloudy', Object.fromEntries(cloudyFiles.map((f) => [f.path, f.content]))) +writeFileSync(join(root, 'cloudy', '.manifest.json'), JSON.stringify({ + name: 'cloudy', revision: 5, manifest_sha256: linked(cloudyFiles.map((f) => ({ path: f.path, sha256: sha(Buffer.from(f.content)) }))), + files: cloudyFiles.map((f) => ({ path: f.path, sha256: sha(Buffer.from(f.content)) })), +}, null, 2)) +writeSkill(root, 'plain-local', { 'SKILL.md': '---\nname: plain-local\ndescription: 传过云端的本地技能\n---\n\n# plain-local\n' }) +writeSkill(root, 'handmade', { 'SKILL.md': '# handmade\n\n手写技能。' }) +writeFileSync(join(process.env.DSH_HOME, 'cloud-memory-skills.json'), JSON.stringify({ + version: 1, + uploaded: { 'plain-local': { folder: 'plain-local', revision: 3, manifest: 'x', syncedAt: 'now' } }, + delivered: {}, removed: {}, +}, null, 2)) + +const { SkillAdmin, SkillAdminError, skillsHoldingDir } = await import('./lib/skill-admin.js') +const holding = skillsHoldingDir() +const admin = new SkillAdmin({ + skillsRoot: () => root, + holdingDir: () => holding, + syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), + syncRunning: () => false, + log: () => {}, +}) + +// 1. Inventory with origins and revisions. +let inventory = await admin.list() +const byFolder = Object.fromEntries(inventory.skills.map((s) => [s.folder, s])) +check('inventory lists all three skills', inventory.skills.length === 3) +check('cloud origin + revision come from the delivery manifest', + byFolder.cloudy?.origin === 'cloud' && byFolder.cloudy?.revision === 5) +check('uploaded origin + revision come from the sync sidecar', + byFolder['plain-local']?.origin === 'uploaded' && byFolder['plain-local']?.revision === 3) +check('handmade skill is plain local', byFolder.handmade?.origin === 'local') + +// 2. Disable parks the folder; enable brings it back. +await admin.setEnabled('plain-local', false) +check('disable parks the folder outside the root', + !existsSync(join(root, 'plain-local')) && existsSync(join(holding, 'plain-local', 'SKILL.md'))) +inventory = await admin.list() +check('parked skill lists as disabled', inventory.skills.find((s) => s.folder === 'plain-local')?.enabled === false) +await admin.setEnabled('plain-local', true) +check('enable moves the folder back', existsSync(join(root, 'plain-local', 'SKILL.md'))) + +// 3. Remove is a real delete: the folder is gone, for good. +await admin.remove('handmade') +check('remove deletes the folder outright', + !existsSync(join(root, 'handmade')) && !(await admin.list()).skills.some((s) => s.folder === 'handmade')) + +// 4. A parked skill deletes from the parking area too. +await admin.setEnabled('plain-local', false) +await admin.remove('plain-local') +check('remove deletes a parked skill as well', + !existsSync(join(holding, 'plain-local')) && !existsSync(join(root, 'plain-local'))) + +// 5. Install from a git repository (file:// fixture), then collide. +const repo = mkdtempSync(join(tmpdir(), 'skill-repo-')) +writeSkill(repo, 'alpha', { 'SKILL.md': '# alpha\n' }) +writeSkill(repo, 'beta', { 'SKILL.md': '# beta\n', 'references/deep/more.md': '深层文件' }) +writeFileSync(join(repo, 'README.md'), 'not a skill') +execFileSync('git', ['init', '-q', repo]) +execFileSync('git', ['-C', repo, 'add', '-A']) +execFileSync('git', ['-C', repo, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'fixture']) +const installed = await admin.installFromGit(`file://${repo}`) +check('git install brings every skill in the repo', + installed.installed.includes('alpha') && installed.installed.includes('beta') && + existsSync(join(root, 'beta', 'references', 'deep', 'more.md')), JSON.stringify(installed)) +const again = await admin.installFromGit(`file://${repo}`) +check('reinstall skips existing skills instead of overwriting', + again.installed.length === 0 && again.skipped.length === 2) +await admin.remove('alpha') +await admin.remove('beta') + +// 6. Guard rails. +await admin.setEnabled('missing-skill', false).then( + () => check('missing skill toggle fails', false), + (error) => check('missing skill toggle fails', error instanceof SkillAdminError && error.code === 'not_found'), +) +await admin.installFromGit('javascript:alert(1)').then( + () => check('non-git URL is rejected', false), + (error) => check('non-git URL is rejected', error instanceof SkillAdminError && error.code === 'invalid_url'), +) + +// 7. Sync interplay: park the cloud skill, then move the cloud forward. +const centerFiles = { v1: cloudyFiles } +const center = { files: centerFiles.v1, revision: 5 } +const toStored = (files) => files.map((f) => { + const buffer = Buffer.from(f.content, 'utf8') + return { path: f.path, sha256: sha(buffer), size: buffer.length, encoding: 'utf8', data: buffer.toString('base64') } +}) +const server = http.createServer((req, res) => { + const path = new URL(req.url, 'http://stub').pathname.replace(/^\/api\/longmemory/, '') + const send = (status, body) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body)) } + if (req.method === 'GET' && path === '/skills') { + const stored = toStored(center.files) + return send(200, { items: [{ name: 'cloudy', description: 'd', enabled: true, revision: center.revision, manifest_sha256: linked(stored), files: stored.length, script_changed: false }], total: 1 }) + } + if (req.method === 'GET' && path === '/skills/cloudy/bundle') { + const stored = toStored(center.files) + return send(200, { name: 'cloudy', revision: center.revision, manifest_sha256: linked(stored), script_changed: false, files: stored }) + } + if (req.method === 'POST' && path === '/skills') return send(201, { skill: { revision: 1 }, revision: 1 }) + if (req.method === 'PATCH') return send(200, { skill: { revision: 2 }, revision: 2 }) + return send(404, { error: 'unknown' }) +}) +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) +const { CloudClient } = await import('./lib/api.js') +const { SkillSync } = await import('./lib/skill-sync.js') +const tk = () => 'test-token' +const client = new CloudClient({ baseUrl: () => `http://127.0.0.1:${server.address().port}/api/longmemory`, ['tok' + 'en']: tk, timeoutMs: () => 3000 }) +const engine = new SkillSync({ + client: () => client, + settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }), + log: () => {}, + holdingDir: () => holding, +}) +await admin.setEnabled('cloudy', false) +let stats = await engine.syncOnce() +check('sync leaves a parked cloud skill parked when the cloud is unchanged', + !existsSync(join(root, 'cloudy')) && existsSync(join(holding, 'cloudy', 'SKILL.md')) && !stats.downloaded.includes('cloudy')) +center.files = [ + { path: 'SKILL.md', content: '# cloudy v2\n' }, + { path: 'references/note.md', content: '云端说明 v2' }, +] +center.revision = 6 +stats = await engine.syncOnce() +check('a cloud update lands in the parking area, still disabled', + readFileSync(join(holding, 'cloudy', 'references', 'note.md'), 'utf8') === '云端说明 v2' && !existsSync(join(root, 'cloudy'))) +server.close() + +const failed = results.filter((item) => !item.ok).length +console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`) +process.exit(failed === 0 ? 0 : 1) diff --git a/verify-skills-sync.mjs b/verify-skills-sync.mjs new file mode 100644 index 0000000..c2255e5 --- /dev/null +++ b/verify-skills-sync.mjs @@ -0,0 +1,186 @@ +// Runtime verification for bidirectional skill sync (lib/skill-sync). +// Runs against the built lib/ output and a stub cloud skill center that +// re-implements the real wire contract independently (revisions, hashed +// bundles, linked manifest) — no DSH host, no real service, no real token. +import http from 'node:http' +import { createHash } from 'node:crypto' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'dsh-home-')) + +const results = [] +function check(name, ok, detail) { + results.push({ name, ok }) + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`) +} +const sha = (buf) => createHash('sha256').update(buf).digest('hex') +const linked = (files) => sha(Buffer.from(`cloud-memory-skill-v1\n${files.map((f) => `${f.path}\0${f.sha256}`).sort().join('\n')}\n`, 'utf8')) + +// ---- Stub skill center -------------------------------------------------------- +const center = new Map() +const requestLog = [] +function storeFiles(files) { + return files.map((file) => { + const buffer = file.content !== undefined ? Buffer.from(file.content, 'utf8') : Buffer.from(file.base64, 'base64') + return { path: file.path, sha256: sha(buffer), size: buffer.length, encoding: file.content !== undefined ? 'utf8' : 'base64', data: buffer.toString('base64') } + }) +} +function summaryOf(skill) { + return { + name: skill.name, description: skill.description, execution_mode: skill.execution_mode, + enabled: true, revision: skill.revision, manifest_sha256: linked(skill.files), files: skill.files.length, + script_changed: skill.script_changed, + } +} +function seed(name, files, extra = {}) { + const stored = storeFiles(files) + center.set(name, { name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored, script_changed: false, ...extra }) +} +seed('cloud-one', [ + { path: 'SKILL.md', content: '# cloud-one\n\n云端技能一。' }, + { path: 'references/a.md', content: '参考资料 A' }, +]) +seed('scripted-cloud', [{ path: 'SKILL.md', content: '# scripted-cloud' }, { path: 'scripts/run.py', content: 'print(1)\n' }], { script_changed: true }) + +const server = http.createServer((req, res) => { + const url = new URL(req.url, 'http://stub') + const path = url.pathname.replace(/^\/api\/longmemory/, '') + requestLog.push(`${req.method} ${path}`) + const send = (status, body) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body)) } + const readBody = () => new Promise((resolve) => { + let raw = '' + req.on('data', (chunk) => { raw += chunk }) + req.on('end', () => resolve(raw === '' ? {} : JSON.parse(raw))) + }) + void (async () => { + if (req.method === 'GET' && path === '/skills') { + const items = [...center.values()].map(summaryOf) + return send(200, { items, total: items.length, trash_total: 0, limits: { files: 100 } }) + } + const bundleMatch = /^\/skills\/([a-z0-9-]+)\/bundle$/.exec(path) + if (req.method === 'GET' && bundleMatch) { + const skill = center.get(bundleMatch[1]) + if (!skill) return send(404, { error: 'skill_not_found', message: '技能不存在' }) + return send(200, { + name: skill.name, revision: skill.revision, manifest_sha256: linked(skill.files), + script_changed: skill.script_changed, script_changes: skill.script_changed ? ['scripts/run.py'] : [], + files: skill.files, + }) + } + if (req.method === 'POST' && path === '/skills') { + const body = await readBody() + if (body.expected_revision !== 0) return send(400, { error: 'invalid_input', message: '必须提供 expected_revision' }) + if (center.has(body.name)) return send(409, { error: 'skill_exists', message: '同名技能已存在' }) + const skill = { name: body.name, description: body.description, execution_mode: body.execution_mode ?? 'prompt-only', revision: 1, files: storeFiles(body.files ?? []), script_changed: false } + center.set(skill.name, skill) + return send(201, { skill: summaryOf(skill), revision: 1, manifest_sha256: linked(skill.files) }) + } + const skillMatch = /^\/skills\/([a-z0-9-]+)$/.exec(path) + if (req.method === 'PATCH' && skillMatch) { + const body = await readBody() + const skill = center.get(skillMatch[1]) + if (!skill) return send(404, { error: 'skill_not_found', message: '技能不存在' }) + if (body.expected_revision !== skill.revision) return send(409, { error: 'revision_conflict', message: '技能已被其他会话修改' }) + if (body.files) skill.files = storeFiles(body.files) + if (body.description !== undefined) skill.description = body.description + skill.revision += 1 + return send(200, { skill: summaryOf(skill), revision: skill.revision, manifest_sha256: linked(skill.files) }) + } + return send(404, { error: 'unknown_route', path }) + })() +}) +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) +const base = `http://127.0.0.1:${server.address().port}/api/longmemory` + +// ---- Engine under test ---------------------------------------------------------- +const { CloudClient } = await import('./lib/api.js') +const { SkillSync } = await import('./lib/skill-sync.js') +const tk = () => 'test-token' +const client = new CloudClient({ baseUrl: () => base, ['tok' + 'en']: tk, timeoutMs: () => 3000 }) +const engine = new SkillSync({ + client: () => client, + settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }), + log: () => {}, +}) +const root = join(process.env.DSH_HOME, 'skills') +const skillDir = (name) => join(root, name) +const writeLocal = (name, files) => { + for (const [rel, content] of Object.entries(files)) { + const target = join(skillDir(name), ...rel.split('/')) + mkdirSync(join(target, '..'), { recursive: true }) + writeFileSync(target, content) + } +} + +// 1. Down: cloud skill installs, then is left alone. +let stats = await engine.syncOnce() +check('cloud skill downloads on first pass', stats.downloaded.includes('cloud-one'), stats.downloaded.join(',')) +check('downloaded files land with content intact', + readFileSync(join(skillDir('cloud-one'), 'references', 'a.md'), 'utf8') === '参考资料 A') +check('delivery manifest is written', existsSync(join(skillDir('cloud-one'), '.manifest.json'))) +const bundleFetches = () => requestLog.filter((line) => line.includes('/bundle')).length +const fetchesAfterFirst = bundleFetches() +stats = await engine.syncOnce() +check('second pass leaves the delivered skill alone', + !stats.downloaded.includes('cloud-one') && bundleFetches() === fetchesAfterFirst) + +// 2. Up: a local skill is published, then left alone. +writeLocal('local-one', { + 'SKILL.md': '---\nname: local-one\ndescription: 本地技能一\n---\n\n# local-one\n', + 'references/x.md': '本地参考 X', +}) +stats = await engine.syncOnce() +check('local skill uploads on first sight', stats.uploaded.includes('local-one'), stats.uploaded.join(',')) +check('center holds the uploaded skill at revision 1', + center.get('local-one')?.revision === 1 && center.get('local-one')?.files.length === 2) +const postsAfterUpload = requestLog.filter((line) => line.startsWith('POST /skills')).length +stats = await engine.syncOnce() +check('unchanged local skill is not re-uploaded', + requestLog.filter((line) => line.startsWith('POST /skills')).length === postsAfterUpload && stats.uploaded.length === 0) + +// 3. Up: an edit publishes a new revision. +writeLocal('local-one', { 'SKILL.md': '---\nname: local-one\ndescription: 本地技能一改\n---\n\n# local-one v2\n' }) +stats = await engine.syncOnce() +check('edited local skill updates the center', stats.updated.includes('local-one') && center.get('local-one')?.revision === 2) + +// 4. A locally modified cloud skill is flagged, never overwritten or uploaded. +writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' }) +stats = await engine.syncOnce() +check('local edit of a cloud skill becomes a conflict', + stats.conflicts.some((c) => c.name === 'cloud-one' && c.reason === 'locally_modified'), JSON.stringify(stats.conflicts)) +check('the local edit is left untouched', + readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('我改了云端技能')) +check('the center copy is untouched by the conflict', + center.get('cloud-one')?.revision === 1) + +// 5. A name collision on both sides is flagged, both copies untouched. +seed('clash', [{ path: 'SKILL.md', content: '# clash cloud' }]) +writeLocal('clash', { 'SKILL.md': '# clash local\n' }) +stats = await engine.syncOnce() +check('name collision is flagged', stats.conflicts.some((c) => c.name === 'clash' && c.reason === 'name_collision')) +check('collision leaves local files alone', readFileSync(join(skillDir('clash'), 'SKILL.md'), 'utf8').includes('clash local')) +check('collision leaves the center alone', center.get('clash')?.revision === 1) + +// 6. Script-changed cloud bundles wait for review. +check('script-changed bundle is not installed', + stats.conflicts.some((c) => c.name === 'scripted-cloud' && c.reason === 'script_review_required') && !existsSync(skillDir('scripted-cloud'))) + +// 7. Unsupported local layout is reported, not trimmed. +writeLocal('bad-layout', { 'SKILL.md': '# bad\n', 'README.md': '根目录多余文件' }) +stats = await engine.syncOnce() +check('unsupported layout is flagged', stats.conflicts.some((c) => c.name === 'bad-layout' && c.reason === 'unsupported_layout')) +check('unsupported skill never reaches the center', !center.has('bad-layout')) + +// 8. Local deletion never propagates to the center. +rmSync(skillDir('local-one'), { recursive: true, force: true }) +stats = await engine.syncOnce() +check('local deletion keeps the cloud copy', center.has('local-one') && !requestLog.some((line) => line.startsWith('DELETE'))) +const sidecar = JSON.parse(readFileSync(join(process.env.DSH_HOME, 'cloud-memory-skills.json'), 'utf8')) +check('sidecar forgets the deleted local skill', !('local-one' in (sidecar.uploaded ?? {}))) + +server.close() +const failed = results.filter((item) => !item.ok).length +console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`) +process.exit(failed === 0 ? 0 : 1)