vendor: dsh-cloud-memory 0.4.1 baseline (upstream 1865a82)

This commit is contained in:
qyh15 2026-11-11 20:27:13 +08:00
commit 09dc365338
48 changed files with 11129 additions and 0 deletions

5
.gitattributes vendored Normal file
View File

@ -0,0 +1,5 @@
* text=auto eol=lf
*.ps1 text eol=crlf
*.cmd text eol=crlf
*.png binary
*.tgz binary

22
.gitignore vendored Normal file
View File

@ -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/

21
.npmignore Normal file
View File

@ -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.*

21
LICENSE Normal file
View File

@ -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.

202
README.md Normal file
View File

@ -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` 为 `<sessionId>:<turn>`,服务端按 `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` 再发布。

846
client/index.js Normal file
View File

@ -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
},
})

13
cordis.patch.yml Normal file
View File

@ -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

View File

@ -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` 即本地改动清单。

300
lib/api.js Normal file
View File

@ -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}`;
}

82
lib/config.js Normal file
View File

@ -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;
}

1
lib/context-types.js Normal file
View File

@ -0,0 +1 @@
export {};

136
lib/index.js Normal file
View File

@ -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');
}

60
lib/mnemon/descriptor.js Normal file
View File

@ -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.',
},
],
};

223
lib/mnemon/driver.js Normal file
View File

@ -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() };
}
}

46
lib/mnemon/index.js Normal file
View File

@ -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);
},
});

429
lib/page.js Normal file
View File

@ -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('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
/** 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 `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>云端记忆 · DSH 插件</title>
<style>
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
body {
margin: 0;
padding: 32px 24px 64px;
font: 14px/1.6 -apple-system, "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
background: #f6f7f9;
color: #1c1f23;
}
@media (prefers-color-scheme: dark) {
body { background: #14161a; color: #e6e8eb; }
.card { background: #1c1f24 !important; border-color: #2b303a !important; }
input, select { background: #12141a !important; color: #e6e8eb !important; border-color: #333a45 !important; }
th { color: #9aa3af !important; }
tr + tr td { border-color: #262b33 !important; }
.muted { color: #8b949e !important; }
code { background: #22262d !important; }
}
.wrap { max-width: 980px; margin: 0 auto; }
h1 { font-size: 20px; margin: 0 0 4px; letter-spacing: .2px; }
h2 { font-size: 14px; margin: 0 0 14px; font-weight: 600; letter-spacing: .3px; }
.sub { margin: 0 0 24px; color: #5c6672; font-size: 13px; }
@media (prefers-color-scheme: dark) { .sub { color: #8b949e; } }
.card {
background: #fff; border: 1px solid #e3e6ea; border-radius: 12px;
padding: 20px 22px; margin-bottom: 18px;
}
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 18px; }
@media (max-width: 720px) { .grid { grid-template-columns: 1fr; } }
label { display: block; font-size: 12px; font-weight: 600; color: #4a5361; margin-bottom: 6px; }
@media (prefers-color-scheme: dark) { label { color: #a7b0bb; } }
input[type=text], input[type=password], input[type=number] {
width: 100%; padding: 9px 11px; font: inherit; font-size: 13px;
border: 1px solid #d7dbe1; border-radius: 8px; background: #fdfdfe; color: inherit;
}
input:focus { outline: 2px solid #4b7bec33; border-color: #4b7bec; }
.hint { font-size: 12px; color: #6b7480; margin-top: 5px; }
.muted { color: #6b7480; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
button {
font: inherit; font-size: 13px; padding: 9px 16px; border-radius: 8px;
border: 1px solid #d7dbe1; background: #fff; color: inherit; cursor: pointer;
transition: background .15s ease, border-color .15s ease;
}
button:hover { background: #f2f4f7; }
button.primary { background: #2f6fed; border-color: #2f6fed; color: #fff; }
button.primary:hover { background: #255fd4; }
button:disabled { opacity: .55; cursor: default; }
.stats { display: flex; flex-wrap: wrap; gap: 10px; margin: 6px 0 2px; }
.stat { flex: 1 1 120px; border: 1px solid #e6e9ee; border-radius: 9px; padding: 10px 12px; }
@media (prefers-color-scheme: dark) { .stat { border-color: #2b303a; } }
.stat .k { font-size: 11px; letter-spacing: .4px; color: #6b7480; text-transform: uppercase; }
.stat .v { font-size: 18px; font-weight: 600; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
th { text-align: left; font-size: 11px; letter-spacing: .4px; text-transform: uppercase; color: #6b7480; padding: 6px 8px; }
td { padding: 7px 8px; border-top: 1px solid #eef1f4; vertical-align: top; }
code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; background: #f1f3f6; padding: 1px 5px; border-radius: 4px; }
.pill { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 600; }
.ok { background: #e6f6ec; color: #1c7c43; }
.bad { background: #fdeaea; color: #b3261e; }
.warn { background: #fff5e0; color: #92600a; }
.sk { background: #eef1f5; color: #55606d; }
.tip { margin-top: 14px; font-size: 12px; color: #6b7480; }
.toast {
position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%);
background: #1c1f23; color: #fff; padding: 10px 18px; border-radius: 999px;
font-size: 13px; opacity: 0; pointer-events: none; transition: opacity .2s ease;
max-width: 80vw; text-align: center;
}
.toast.show { opacity: .95; }
</style>
</head>
<body>
<div class="wrap">
<h1>云端记忆 · DSH 插件</h1>
<p class="sub">v${escapeHtml(options.version)} · 每轮结束上报活动计数 · 提供 memory_search / memory_read / memory_add 工具</p>
<p class="sub"><a href="/cloud-memory/skills">技能管理(列表 · 启停 · 安装)→</a></p>
<section class="card">
<h2>当前状态</h2>
<div class="stats" id="stats"></div>
<div class="tip" id="statDetail">加载中…</div>
</section>
<section class="card">
<h2>连接配置</h2>
<div class="grid">
<div>
<label for="baseUrl">服务基址</label>
<input id="baseUrl" type="text" spellcheck="false" placeholder="https://mem.qyhhh.top/api/longmemory" />
<div class="hint">不带结尾斜杠,路径为 /api/longmemory。</div>
</div>
<div>
<label for="clientId">客户端标识 client_id</label>
<input id="clientId" type="text" spellcheck="false" placeholder="dsh-desktop" />
<div class="hint">上报时附带,便于区分来源设备。</div>
</div>
<div>
<label for="requestTimeoutMs">请求超时(毫秒)</label>
<input id="requestTimeoutMs" type="number" min="1000" max="60000" step="500" />
</div>
<div>
<label for="defaultK">默认检索条数</label>
<input id="defaultK" type="number" min="1" max="100" />
</div>
</div>
<div class="row" style="margin-top:14px">
<label style="margin:0;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500">
<input id="enabled" type="checkbox" style="width:auto" /> 启用插件(关闭后不上报、不提供工具)
</label>
</div>
<div class="row" style="margin-top:10px">
<label style="margin:0;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500">
<input id="summaryEnabled" type="checkbox" style="width:auto" /> 轮次结束后自动生成待确认摘要(只进入待确认队列,确认后才写云端)
</label>
</div>
<div class="row" style="margin-top:10px;align-items:center;gap:10px">
<label for="summaryMaxChars" style="margin:0;font-size:13px;font-weight:500">单轮摘要字数上限</label>
<input id="summaryMaxChars" type="number" min="1000" max="16000" step="500" style="max-width:140px" />
</div>
</section>
<section class="card">
<h2>账号登录</h2>
<div class="grid">
<div>
<label for="username">用户名</label>
<input id="username" type="text" spellcheck="false" autocomplete="username" placeholder="云端面板的账号" />
</div>
<div>
<label for="password">密码</label>
<input id="password" type="password" spellcheck="false" autocomplete="current-password" placeholder="只用于本次换取令牌" />
</div>
</div>
<div class="row" style="margin-top:14px">
<button class="primary" id="login">登录并获取令牌</button>
</div>
<div class="tip">
用云端面板的普通用户账号登录,插件会用一次性会话换取 <code>activity:write</code> 与 <code>memory:write</code> 两个令牌并写入本机。
密码只在这一次请求里使用:不保存、不写日志、不回显,换取成功后立即从内存丢弃。
管理员账号不能创建个人令牌,请用普通用户账号。
</div>
</section>
<section class="card">
<h2>访问令牌</h2>
<div class="grid">
<div>
<label for="activityToken">活动上报令牌(activity:write)</label>
<input id="activityToken" type="password" spellcheck="false" autocomplete="off" placeholder="留空表示不修改" />
<div class="hint" id="activityTokenHint">用于 POST /activity/turn。</div>
</div>
<div>
<label for="memoryToken">记忆读写令牌(memory:write)</label>
<input id="memoryToken" type="password" spellcheck="false" autocomplete="off" placeholder="留空表示不修改" />
<div class="hint" id="memoryTokenHint">memory:write 同时允许读取,一个令牌即可覆盖检索与写入;只有 memory:read 时写入会被拒。</div>
</div>
<div>
<label for="summaryToken">对话摘要令牌(summary:write,可选)</label>
<input id="summaryToken" type="password" spellcheck="false" autocomplete="off" placeholder="留空表示不修改" />
<div class="hint" id="summaryTokenHint">用于 POST /activity/summary:只把已脱敏摘要送进待确认队列。</div>
</div>
</div>
<div class="row" style="margin-top:14px">
<button class="primary" id="save">保存配置</button>
<button id="clearTokens">清除已存令牌</button>
</div>
<div class="tip">
在面板「设置 → API 密钥」里各建一个 <code>activity:write</code> 与 <code>memory:write</code> 密钥(一个密钥只有一种权限,所以需要两个)。<br />
令牌只写入本机 <code>${escapeHtml(options.settingsPath)}</code>(进程退出不丢),不会进入会话上下文、不会上传到云端、也不会出现在本页回显里。
</div>
</section>
<section class="card">
<h2>诊断</h2>
<div class="row">
<button id="test">测试连接</button>
<button id="flush">重试上报队列</button>
<button id="reload">刷新</button>
</div>
<div class="tip" id="testResult"></div>
</section>
<section class="card">
<h2>最近上报</h2>
<table>
<thead>
<tr><th>时间</th><th>状态</th><th>结果</th><th>HTTP</th><th>turn_id</th></tr>
</thead>
<tbody id="recent"><tr><td colspan="5" class="muted">暂无记录</td></tr></tbody>
</table>
</section>
</div>
<div class="toast" id="toast"></div>
<script>
(function () {
'use strict';
var state = { view: null };
function el(id) { return document.getElementById(id); }
function toast(text) {
var node = el('toast');
node.textContent = text;
node.classList.add('show');
clearTimeout(toast._timer);
toast._timer = setTimeout(function () { node.classList.remove('show'); }, 2600);
}
function pill(kind, text) {
return '<span class="pill ' + kind + '">' + text + '</span>';
}
function fmtTime(ms) {
if (typeof ms !== 'number' || !isFinite(ms)) return '—';
var d = new Date(ms);
var pad = function (n) { return String(n).padStart(2, '0'); };
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' +
pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
}
function render(view) {
state.view = view;
var settings = view.settings || {};
var tokens = view.tokens || {};
var reporter = view.reporter || {};
el('baseUrl').value = settings.baseUrl || '';
el('clientId').value = settings.clientId || '';
el('requestTimeoutMs').value = settings.requestTimeoutMs || '';
el('defaultK').value = settings.defaultK || '';
el('enabled').checked = settings.enabled === true;
el('summaryEnabled').checked = settings.summaryEnabled === true;
el('summaryMaxChars').value = settings.summaryMaxChars || '';
el('activityTokenHint').innerHTML = '用于 POST /activity/turn。当前 ' +
(tokens.activity && tokens.activity.configured
? pill('ok', '已配置 ' + tokens.activity.masked)
: pill('bad', '未配置'));
el('memoryTokenHint').innerHTML = '用于记忆检索、读取与写入工具。当前 ' +
(tokens.memory && tokens.memory.configured
? pill('ok', '已配置 ' + tokens.memory.masked)
: pill('bad', '未配置'));
el('summaryTokenHint').innerHTML = '用于轮次结束后的自动摘要(只进待确认队列)。当前 ' +
(tokens.summary && tokens.summary.configured
? pill('ok', '已配置 ' + tokens.summary.masked)
: pill('sk', '未配置,自动摘要不会触发'));
var stats = [
['上报成功', reporter.recorded || 0],
['重复忽略', reporter.duplicate || 0],
['失败', reporter.failed || 0],
['已跳过', reporter.skipped || 0],
['待重试', reporter.queued || 0],
['摘要待确认', reporter.summaryStaged || 0],
['摘要失败', reporter.summaryFailed || 0]
];
el('stats').innerHTML = stats.map(function (pair) {
return '<div class="stat"><div class="k">' + pair[0] + '</div><div class="v">' + pair[1] + '</div></div>';
}).join('');
var detail = [];
detail.push(settings.enabled ? pill('ok', '插件已启用') : pill('warn', '插件已禁用'));
detail.push('最近一次成功上报:' + fmtTime(reporter.lastSentAt));
if (reporter.lastError) detail.push(pill('bad', '最近错误:' + reporter.lastError));
detail.push('配置文件:<code>' + (view.settingsPath || '') + '</code>');
el('statDetail').innerHTML = detail.join(' · ');
var recent = reporter.recent || [];
if (recent.length === 0) {
el('recent').innerHTML = '<tr><td colspan="5" class="muted">暂无记录</td></tr>';
return;
}
el('recent').innerHTML = recent.slice(0, 12).map(function (row) {
var outcome = row.outcome === 'recorded' ? pill('ok', '已记录')
: row.outcome === 'duplicate' ? pill('sk', '重复')
: row.outcome === 'queued' ? pill('warn', '待重试')
: row.outcome === 'skipped' ? pill('sk', '跳过')
: pill('bad', '失败');
var status = row.status === 'completed' ? pill('ok', 'completed')
: row.status === 'failed' ? pill('bad', 'failed')
: pill('warn', String(row.status || '—'));
var turn = String(row.turnId || '');
if (turn.length > 46) turn = turn.slice(0, 46) + '…';
var tip = row.error ? ' title="' + String(row.error).replace(/"/g, '&quot;') + '"' : '';
return '<tr' + tip + '><td>' + fmtTime(row.at) + '</td><td>' + status + '</td><td>' + outcome +
'</td><td>' + (row.httpStatus == null ? '—' : row.httpStatus) + '</td><td><code>' + turn + '</code></td></tr>';
}).join('');
}
function load() {
return fetch('/cloud-memory/status', { headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) throw new Error((body && body.error) || 'status failed');
render(body);
})
.catch(function (error) { toast('读取状态失败:' + error.message); });
}
function save() {
var patch = {
baseUrl: el('baseUrl').value.trim(),
clientId: el('clientId').value.trim(),
requestTimeoutMs: Number(el('requestTimeoutMs').value),
defaultK: Number(el('defaultK').value),
enabled: el('enabled').checked,
summaryEnabled: el('summaryEnabled').checked,
summaryMaxChars: Number(el('summaryMaxChars').value)
};
var activity = el('activityToken').value.trim();
var memory = el('memoryToken').value.trim();
var summary = el('summaryToken').value.trim();
if (activity !== '') patch.activityToken = activity;
if (memory !== '') patch.memoryToken = memory;
if (summary !== '') patch.summaryToken = summary;
fetch('/cloud-memory/config', {
method: 'PUT',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify(patch)
}).then(function (res) { return res.json(); }).then(function (body) {
if (!body || body.ok !== true) { toast('保存失败:' + ((body && body.error) || 'unknown')); return; }
el('activityToken').value = '';
el('memoryToken').value = '';
el('summaryToken').value = '';
render(body);
toast('已保存');
}).catch(function (error) { toast('保存失败:' + error.message); });
}
function test() {
var node = el('testResult');
node.textContent = '测试中…';
fetch('/cloud-memory/test', { method: 'POST', headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) { node.textContent = '测试失败:' + ((body && body.error) || 'unknown'); return; }
var lines = [];
lines.push((body.activity && body.activity.ok ? '✅ ' : '❌ ') + '活动令牌:' + (body.activity && body.activity.message));
lines.push((body.memory && body.memory.ok ? '✅ ' : '❌ ') + '记忆令牌:' + (body.memory && body.memory.message));
node.innerHTML = lines.join('<br />');
})
.catch(function (error) { node.textContent = '测试失败:' + error.message; });
}
function flush() {
fetch('/cloud-memory/flush', { method: 'POST', headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) { toast('重试失败:' + ((body && body.error) || 'unknown')); return; }
toast('已补发 ' + body.sent + ' 条,剩余 ' + body.remaining + ' 条');
return load();
})
.catch(function (error) { toast('重试失败:' + error.message); });
}
function clearTokens() {
fetch('/cloud-memory/config', {
method: 'PUT',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ clearActivityToken: true, clearMemoryToken: true })
}).then(function (res) { return res.json(); }).then(function (body) {
if (!body || body.ok !== true) { toast('清除失败:' + ((body && body.error) || 'unknown')); return; }
render(body);
toast('已清除本地令牌');
}).catch(function (error) { toast('清除失败:' + error.message); });
}
function login() {
var username = el('username').value.trim();
var password = el('password').value;
if (username === '' || password === '') { toast('请填写用户名和密码'); return; }
fetch('/cloud-memory/login', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ username: username, password: password })
}).then(function (res) { return res.json(); }).then(function (body) {
if (!body || body.ok !== true) { toast('登录失败:' + ((body && body.error) || 'unknown')); return; }
el('password').value = '';
render(body);
var warning = body.login && body.login.warning ? '(' + body.login.warning + ')' : '';
toast('登录成功,已自动写入两个令牌' + warning);
}).catch(function (error) { toast('登录失败:' + error.message); });
}
el('save').addEventListener('click', save);
el('login').addEventListener('click', login);
el('test').addEventListener('click', test);
el('flush').addEventListener('click', flush);
el('clearTokens').addEventListener('click', clearTokens);
el('reload').addEventListener('click', function () { load(); toast('已刷新'); });
load();
setInterval(load, 15000);
})();
</script>
</body>
</html>`;
}

392
lib/reporter.js Normal file
View File

@ -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],
};
}
}

441
lib/routes.js Normal file
View File

@ -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
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
: JSON.stringify({ ok: false, error: message });
res.writeHead(status, {
'content-type': asHtml ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8',
'cache-control': 'no-store',
});
res.end(text);
}
/** 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),
},
];
}

262
lib/skill-admin.js Normal file
View File

@ -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(() => { });
}
}
}

161
lib/skill-page.js Normal file
View File

@ -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 `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>技能管理 · 云端记忆插件</title>
<style>
body { font-family: system-ui, -apple-system, "Segoe UI", sans-serif; margin: 0; background: #f6f7f9; color: #1c2333; }
.wrap { max-width: 880px; margin: 0 auto; padding: 24px 16px 48px; }
h1 { font-size: 20px; margin: 0 0 4px; }
.sub { color: #5b6478; font-size: 13px; margin: 0 0 16px; }
.card { background: #fff; border: 1px solid #e2e6ee; border-radius: 10px; padding: 16px; margin-bottom: 16px; }
.card h2 { font-size: 15px; margin: 0 0 12px; }
.row { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; border-top: 1px solid #eef1f6; }
.row:first-of-type { border-top: none; }
.grow { flex: 1; min-width: 0; }
.name { font-weight: 600; font-size: 14px; }
.desc { color: #5b6478; font-size: 13px; margin-top: 2px; word-break: break-word; }
.badge { display: inline-block; font-size: 11px; padding: 1px 7px; border-radius: 999px; background: #eef1f6; color: #44506a; margin-left: 6px; vertical-align: 1px; }
.badge.off { background: #fdecec; color: #9c2b2b; }
.badge.cloud { background: #e7f0fe; color: #1c4fa0; }
button { font-size: 13px; padding: 5px 12px; border-radius: 7px; border: 1px solid #c9d2e3; background: #fff; cursor: pointer; white-space: nowrap; }
button:hover { background: #f0f3f9; }
button.danger { border-color: #e3c2c2; color: #9c2b2b; }
button.primary { background: #1c4fa0; border-color: #1c4fa0; color: #fff; }
input[type="text"] { flex: 1; font-size: 13px; padding: 7px 10px; border: 1px solid #c9d2e3; border-radius: 7px; min-width: 0; }
.flex { display: flex; gap: 8px; }
.msg { font-size: 13px; min-height: 18px; margin-top: 8px; }
.msg.err { color: #9c2b2b; }
.empty { color: #8a93a6; font-size: 13px; padding: 8px 0; }
a { color: #1c4fa0; }
</style>
</head>
<body>
<div class="wrap">
<h1>技能管理</h1>
<p class="sub">v${options.version} · 本机技能的列表、启停、安装;删除是真删、不可恢复(云端副本不受影响)。云端同步仍在后台自动进行。<a href="/cloud-memory">← 返回云端记忆设置</a></p>
<section class="card">
<h2>从 git 仓库安装</h2>
<div class="flex">
<input id="git-url" type="text" placeholder="https://github.com/作者/仓库">
<button class="primary" id="install-btn">安装</button>
</div>
<div class="msg" id="install-msg"></div>
</section>
<section class="card">
<h2>本机技能</h2>
<div id="skills"></div>
<div class="msg" id="skills-msg"></div>
</section>
</div>
<script>
const $ = (id) => document.getElementById(id);
function badge(text, cls) {
const span = document.createElement('span');
span.className = 'badge' + (cls ? ' ' + cls : '');
span.textContent = text;
return span;
}
function button(text, cls, onClick) {
const btn = document.createElement('button');
if (cls) btn.className = cls;
btn.textContent = text;
btn.addEventListener('click', onClick);
return btn;
}
async function post(path, body) {
const response = await fetch('/cloud-memory/skills' + path, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
const data = await response.json().catch(() => ({}));
if (!response.ok || data.ok === false) throw new Error(data.error || ('HTTP ' + response.status));
return data;
}
async function act(path, body, msgEl) {
msgEl.textContent = '';
msgEl.className = 'msg';
try {
await post(path, body);
await load();
} catch (error) {
msgEl.textContent = error.message;
msgEl.className = 'msg err';
}
}
async function load() {
const response = await fetch('/cloud-memory/skills/api');
const data = await response.json();
const skillsBox = $('skills');
skillsBox.textContent = '';
if (!data.skills || data.skills.length === 0) {
const empty = document.createElement('div');
empty.className = 'empty';
empty.textContent = '本机还没有技能。云端技能会在同步后自动出现,也可以从上面的仓库安装。';
skillsBox.appendChild(empty);
}
for (const skill of data.skills || []) {
const row = document.createElement('div');
row.className = 'row';
const grow = document.createElement('div');
grow.className = 'grow';
const name = document.createElement('div');
name.className = 'name';
name.textContent = skill.name;
name.appendChild(badge(skill.origin === 'cloud' ? '云端' : skill.origin === 'uploaded' ? '本地 · 已传云端' : '本地', skill.origin === 'cloud' ? 'cloud' : ''));
if (skill.revision) name.appendChild(badge('v' + skill.revision));
if (!skill.enabled) name.appendChild(badge('已停用', 'off'));
grow.appendChild(name);
const desc = document.createElement('div');
desc.className = 'desc';
desc.textContent = skill.description || skill.folder;
grow.appendChild(desc);
row.appendChild(grow);
const msg = $('skills-msg');
row.appendChild(button(skill.enabled ? '停用' : '启用', '', () => act('/toggle', { folder: skill.folder, enabled: !skill.enabled }, msg)));
row.appendChild(button('删除', 'danger', () => {
if (window.confirm('真删「' + skill.name + '」?本地文件不可恢复(云端副本不受影响)。')) {
void act('/remove', { folder: skill.folder }, msg);
}
}));
skillsBox.appendChild(row);
}
}
$('install-btn').addEventListener('click', async () => {
const msg = $('install-msg');
const url = $('git-url').value.trim();
if (!url) { msg.textContent = '先填仓库地址。'; msg.className = 'msg err'; return; }
msg.textContent = '正在克隆并安装…';
msg.className = 'msg';
try {
const data = await post('/install', { url });
const parts = [];
if (data.installed && data.installed.length) parts.push('已安装:' + data.installed.join('、'));
if (data.skipped && data.skipped.length) parts.push('跳过:' + data.skipped.map((s) => s.name).join('、'));
msg.textContent = parts.join(';') || '没有装上任何技能。';
$('git-url').value = '';
await load();
} catch (error) {
msg.textContent = error.message;
msg.className = 'msg err';
}
});
load().catch((error) => { $('skills-msg').textContent = error.message; $('skills-msg').className = 'msg err'; });
</script>
</body>
</html>
`;
}

519
lib/skill-sync.js Normal file
View File

@ -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/')),
};
}
}

270
lib/store.js Normal file
View File

@ -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\<user>` 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;
}
}
}

286
lib/tools.js Normal file
View File

@ -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)];
}

82
package.json Normal file
View File

@ -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"
}

1269
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

142
scripts/pack-guard.mjs Normal file
View File

@ -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[\\/](?!<user>)(?!%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: 白名单与脱敏检查通过')

127
scripts/release-prep.mjs Normal file
View File

@ -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 一旦发布就不能再改同号。')

489
src/api.ts Normal file
View File

@ -0,0 +1,489 @@
/**
* Thin client for the LongMemory cloud API (`/api/longmemory`).
*
* - Every call carries `Authorization: Bearer <token>`; 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<T> = { 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<string, unknown>
if (typeof body.error === 'string') code = body.error
else if (body.error !== null && typeof body.error === 'object') {
const nested = body.error as Record<string, unknown>
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<T>(method: string, path: string, body?: unknown, tokenOverride?: string): Promise<CloudResult<T>> {
const token = tokenOverride ?? this.options.token()
const base = this.options.baseUrl()
const url = `${base}${path}`
const headers: Record<string, string> = { 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<CloudResult<TurnAck>> {
return this.request<TurnAck>('POST', '/activity/turn', payload, token)
}
/** Stage one turn summary as pending proposals (summary:write token). */
submitSummary(payload: SummaryPayload, token: string): Promise<CloudResult<SummaryAck>> {
return this.request<SummaryAck>('POST', '/activity/summary', payload, token)
}
/**
* 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<CloudResult<{ authenticated: true }>> {
const result = await this.request<unknown>('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<CloudResult<{ authenticated: true }>> {
const result = await this.request<unknown>('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<CloudResult<SearchResponse>> {
const body: Record<string, unknown> = { query, k }
if (project !== undefined && project !== '') body.filters = { project_id: project }
return this.request<SearchResponse>('POST', '/memory/query', body)
}
/** Read one memory by id (memory token). */
read(id: string): Promise<CloudResult<MemoryHit>> {
return this.request<MemoryHit>('GET', `/memory/${encodeURIComponent(id)}`)
}
/** List memories with optional paging filters (memory token). */
list(options: { limit?: number; offset?: number; project?: string } = {}): Promise<CloudResult<ListResponse>> {
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<ListResponse>('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<CloudResult<AddResponse>> {
const body: Record<string, unknown> = {
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<AddResponse>('POST', '/memory/add', body)
}
/** List the account's projects (memory token). */
projects(): Promise<CloudResult<ProjectsResponse>> {
return this.request<ProjectsResponse>('GET', '/dashboard/projects')
}
/** Storage configuration state (memory token). */
storageStatus(): Promise<CloudResult<Record<string, unknown>>> {
return this.request<Record<string, unknown>>('GET', '/storage/status')
}
/** List the cloud skill center inventory (memory token). */
listSkills(): Promise<CloudResult<SkillListing>> {
return this.request<SkillListing>('GET', '/skills')
}
/** Fetch one skill bundle with hashed, base64-carried files (memory token). */
skillBundle(name: string): Promise<CloudResult<SkillBundle>> {
return this.request<SkillBundle>('GET', `/skills/${encodeURIComponent(name)}/bundle`)
}
/** Create one skill in the center; `expected_revision` must be 0 (memory token). */
createSkill(body: Record<string, unknown>): Promise<CloudResult<SkillWriteResult>> {
return this.request<SkillWriteResult>('POST', '/skills', body)
}
/** Replace one skill's files/description at an expected revision (memory token). */
updateSkill(name: string, body: Record<string, unknown>): Promise<CloudResult<SkillWriteResult>> {
return this.request<SkillWriteResult>('PATCH', `/skills/${encodeURIComponent(name)}`, body)
}
/**
* 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<string, string> = { 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<CloudResult<LoginOutcome>> {
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<CloudResult<IssuedToken>> {
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}`
}

97
src/config.ts Normal file
View File

@ -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<Record<keyof Settings, unknown>>
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<Settings> {
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {}
const source = raw as RawConfig
const result: Partial<Settings> = {}
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
}

59
src/context-types.ts Normal file
View File

@ -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<void>
}
/** 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<string, unknown>, exec?: unknown) => Promise<unknown>
}
/** 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<string, unknown>
}

153
src/index.ts Normal file
View File

@ -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')
}

62
src/mnemon/descriptor.ts Normal file
View File

@ -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.',
},
],
}

255
src/mnemon/driver.ts Normal file
View File

@ -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<string, unknown>).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<ProviderMemorySpace[]> {
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<ProviderSpaceStatus> {
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<ProviderSearchResult> {
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<Insight[]> {
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<JsonValue> {
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<Insight | undefined> {
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<MemoryGraphSnapshot> {
signal?.throwIfAborted()
void body
return { nodes: [], edges: [], generatedAt: new Date().toISOString() }
}
}

57
src/mnemon/index.ts Normal file
View File

@ -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<undefined>({
id: descriptor.id,
apply(ctx, host) {
host.install(ctx, definition)
},
})

431
src/page.ts Normal file
View File

@ -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('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;')
}
/** 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 `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>云端记忆 · DSH 插件</title>
<style>
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
body {
margin: 0;
padding: 32px 24px 64px;
font: 14px/1.6 -apple-system, "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
background: #f6f7f9;
color: #1c1f23;
}
@media (prefers-color-scheme: dark) {
body { background: #14161a; color: #e6e8eb; }
.card { background: #1c1f24 !important; border-color: #2b303a !important; }
input, select { background: #12141a !important; color: #e6e8eb !important; border-color: #333a45 !important; }
th { color: #9aa3af !important; }
tr + tr td { border-color: #262b33 !important; }
.muted { color: #8b949e !important; }
code { background: #22262d !important; }
}
.wrap { max-width: 980px; margin: 0 auto; }
h1 { font-size: 20px; margin: 0 0 4px; letter-spacing: .2px; }
h2 { font-size: 14px; margin: 0 0 14px; font-weight: 600; letter-spacing: .3px; }
.sub { margin: 0 0 24px; color: #5c6672; font-size: 13px; }
@media (prefers-color-scheme: dark) { .sub { color: #8b949e; } }
.card {
background: #fff; border: 1px solid #e3e6ea; border-radius: 12px;
padding: 20px 22px; margin-bottom: 18px;
}
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 18px; }
@media (max-width: 720px) { .grid { grid-template-columns: 1fr; } }
label { display: block; font-size: 12px; font-weight: 600; color: #4a5361; margin-bottom: 6px; }
@media (prefers-color-scheme: dark) { label { color: #a7b0bb; } }
input[type=text], input[type=password], input[type=number] {
width: 100%; padding: 9px 11px; font: inherit; font-size: 13px;
border: 1px solid #d7dbe1; border-radius: 8px; background: #fdfdfe; color: inherit;
}
input:focus { outline: 2px solid #4b7bec33; border-color: #4b7bec; }
.hint { font-size: 12px; color: #6b7480; margin-top: 5px; }
.muted { color: #6b7480; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
button {
font: inherit; font-size: 13px; padding: 9px 16px; border-radius: 8px;
border: 1px solid #d7dbe1; background: #fff; color: inherit; cursor: pointer;
transition: background .15s ease, border-color .15s ease;
}
button:hover { background: #f2f4f7; }
button.primary { background: #2f6fed; border-color: #2f6fed; color: #fff; }
button.primary:hover { background: #255fd4; }
button:disabled { opacity: .55; cursor: default; }
.stats { display: flex; flex-wrap: wrap; gap: 10px; margin: 6px 0 2px; }
.stat { flex: 1 1 120px; border: 1px solid #e6e9ee; border-radius: 9px; padding: 10px 12px; }
@media (prefers-color-scheme: dark) { .stat { border-color: #2b303a; } }
.stat .k { font-size: 11px; letter-spacing: .4px; color: #6b7480; text-transform: uppercase; }
.stat .v { font-size: 18px; font-weight: 600; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
th { text-align: left; font-size: 11px; letter-spacing: .4px; text-transform: uppercase; color: #6b7480; padding: 6px 8px; }
td { padding: 7px 8px; border-top: 1px solid #eef1f4; vertical-align: top; }
code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; background: #f1f3f6; padding: 1px 5px; border-radius: 4px; }
.pill { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 600; }
.ok { background: #e6f6ec; color: #1c7c43; }
.bad { background: #fdeaea; color: #b3261e; }
.warn { background: #fff5e0; color: #92600a; }
.sk { background: #eef1f5; color: #55606d; }
.tip { margin-top: 14px; font-size: 12px; color: #6b7480; }
.toast {
position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%);
background: #1c1f23; color: #fff; padding: 10px 18px; border-radius: 999px;
font-size: 13px; opacity: 0; pointer-events: none; transition: opacity .2s ease;
max-width: 80vw; text-align: center;
}
.toast.show { opacity: .95; }
</style>
</head>
<body>
<div class="wrap">
<h1>云端记忆 · DSH 插件</h1>
<p class="sub">v${escapeHtml(options.version)} · 每轮结束上报活动计数 · 提供 memory_search / memory_read / memory_add 工具</p>
<p class="sub"><a href="/cloud-memory/skills">技能管理(列表 · 启停 · 安装)→</a></p>
<section class="card">
<h2>当前状态</h2>
<div class="stats" id="stats"></div>
<div class="tip" id="statDetail">加载中…</div>
</section>
<section class="card">
<h2>连接配置</h2>
<div class="grid">
<div>
<label for="baseUrl">服务基址</label>
<input id="baseUrl" type="text" spellcheck="false" placeholder="https://mem.qyhhh.top/api/longmemory" />
<div class="hint">不带结尾斜杠,路径为 /api/longmemory。</div>
</div>
<div>
<label for="clientId">客户端标识 client_id</label>
<input id="clientId" type="text" spellcheck="false" placeholder="dsh-desktop" />
<div class="hint">上报时附带,便于区分来源设备。</div>
</div>
<div>
<label for="requestTimeoutMs">请求超时(毫秒)</label>
<input id="requestTimeoutMs" type="number" min="1000" max="60000" step="500" />
</div>
<div>
<label for="defaultK">默认检索条数</label>
<input id="defaultK" type="number" min="1" max="100" />
</div>
</div>
<div class="row" style="margin-top:14px">
<label style="margin:0;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500">
<input id="enabled" type="checkbox" style="width:auto" /> 启用插件(关闭后不上报、不提供工具)
</label>
</div>
<div class="row" style="margin-top:10px">
<label style="margin:0;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500">
<input id="summaryEnabled" type="checkbox" style="width:auto" /> 轮次结束后自动生成待确认摘要(只进入待确认队列,确认后才写云端)
</label>
</div>
<div class="row" style="margin-top:10px;align-items:center;gap:10px">
<label for="summaryMaxChars" style="margin:0;font-size:13px;font-weight:500">单轮摘要字数上限</label>
<input id="summaryMaxChars" type="number" min="1000" max="16000" step="500" style="max-width:140px" />
</div>
</section>
<section class="card">
<h2>账号登录</h2>
<div class="grid">
<div>
<label for="username">用户名</label>
<input id="username" type="text" spellcheck="false" autocomplete="username" placeholder="云端面板的账号" />
</div>
<div>
<label for="password">密码</label>
<input id="password" type="password" spellcheck="false" autocomplete="current-password" placeholder="只用于本次换取令牌" />
</div>
</div>
<div class="row" style="margin-top:14px">
<button class="primary" id="login">登录并获取令牌</button>
</div>
<div class="tip">
用云端面板的普通用户账号登录,插件会用一次性会话换取 <code>activity:write</code> 与 <code>memory:write</code> 两个令牌并写入本机。
密码只在这一次请求里使用:不保存、不写日志、不回显,换取成功后立即从内存丢弃。
管理员账号不能创建个人令牌,请用普通用户账号。
</div>
</section>
<section class="card">
<h2>访问令牌</h2>
<div class="grid">
<div>
<label for="activityToken">活动上报令牌(activity:write)</label>
<input id="activityToken" type="password" spellcheck="false" autocomplete="off" placeholder="留空表示不修改" />
<div class="hint" id="activityTokenHint">用于 POST /activity/turn。</div>
</div>
<div>
<label for="memoryToken">记忆读写令牌(memory:write)</label>
<input id="memoryToken" type="password" spellcheck="false" autocomplete="off" placeholder="留空表示不修改" />
<div class="hint" id="memoryTokenHint">memory:write 同时允许读取,一个令牌即可覆盖检索与写入;只有 memory:read 时写入会被拒。</div>
</div>
<div>
<label for="summaryToken">对话摘要令牌(summary:write,可选)</label>
<input id="summaryToken" type="password" spellcheck="false" autocomplete="off" placeholder="留空表示不修改" />
<div class="hint" id="summaryTokenHint">用于 POST /activity/summary:只把已脱敏摘要送进待确认队列。</div>
</div>
</div>
<div class="row" style="margin-top:14px">
<button class="primary" id="save">保存配置</button>
<button id="clearTokens">清除已存令牌</button>
</div>
<div class="tip">
在面板「设置 → API 密钥」里各建一个 <code>activity:write</code> 与 <code>memory:write</code> 密钥(一个密钥只有一种权限,所以需要两个)。<br />
令牌只写入本机 <code>${escapeHtml(options.settingsPath)}</code>(进程退出不丢),不会进入会话上下文、不会上传到云端、也不会出现在本页回显里。
</div>
</section>
<section class="card">
<h2>诊断</h2>
<div class="row">
<button id="test">测试连接</button>
<button id="flush">重试上报队列</button>
<button id="reload">刷新</button>
</div>
<div class="tip" id="testResult"></div>
</section>
<section class="card">
<h2>最近上报</h2>
<table>
<thead>
<tr><th>时间</th><th>状态</th><th>结果</th><th>HTTP</th><th>turn_id</th></tr>
</thead>
<tbody id="recent"><tr><td colspan="5" class="muted">暂无记录</td></tr></tbody>
</table>
</section>
</div>
<div class="toast" id="toast"></div>
<script>
(function () {
'use strict';
var state = { view: null };
function el(id) { return document.getElementById(id); }
function toast(text) {
var node = el('toast');
node.textContent = text;
node.classList.add('show');
clearTimeout(toast._timer);
toast._timer = setTimeout(function () { node.classList.remove('show'); }, 2600);
}
function pill(kind, text) {
return '<span class="pill ' + kind + '">' + text + '</span>';
}
function fmtTime(ms) {
if (typeof ms !== 'number' || !isFinite(ms)) return '—';
var d = new Date(ms);
var pad = function (n) { return String(n).padStart(2, '0'); };
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' +
pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
}
function render(view) {
state.view = view;
var settings = view.settings || {};
var tokens = view.tokens || {};
var reporter = view.reporter || {};
el('baseUrl').value = settings.baseUrl || '';
el('clientId').value = settings.clientId || '';
el('requestTimeoutMs').value = settings.requestTimeoutMs || '';
el('defaultK').value = settings.defaultK || '';
el('enabled').checked = settings.enabled === true;
el('summaryEnabled').checked = settings.summaryEnabled === true;
el('summaryMaxChars').value = settings.summaryMaxChars || '';
el('activityTokenHint').innerHTML = '用于 POST /activity/turn。当前 ' +
(tokens.activity && tokens.activity.configured
? pill('ok', '已配置 ' + tokens.activity.masked)
: pill('bad', '未配置'));
el('memoryTokenHint').innerHTML = '用于记忆检索、读取与写入工具。当前 ' +
(tokens.memory && tokens.memory.configured
? pill('ok', '已配置 ' + tokens.memory.masked)
: pill('bad', '未配置'));
el('summaryTokenHint').innerHTML = '用于轮次结束后的自动摘要(只进待确认队列)。当前 ' +
(tokens.summary && tokens.summary.configured
? pill('ok', '已配置 ' + tokens.summary.masked)
: pill('sk', '未配置,自动摘要不会触发'));
var stats = [
['上报成功', reporter.recorded || 0],
['重复忽略', reporter.duplicate || 0],
['失败', reporter.failed || 0],
['已跳过', reporter.skipped || 0],
['待重试', reporter.queued || 0],
['摘要待确认', reporter.summaryStaged || 0],
['摘要失败', reporter.summaryFailed || 0]
];
el('stats').innerHTML = stats.map(function (pair) {
return '<div class="stat"><div class="k">' + pair[0] + '</div><div class="v">' + pair[1] + '</div></div>';
}).join('');
var detail = [];
detail.push(settings.enabled ? pill('ok', '插件已启用') : pill('warn', '插件已禁用'));
detail.push('最近一次成功上报:' + fmtTime(reporter.lastSentAt));
if (reporter.lastError) detail.push(pill('bad', '最近错误:' + reporter.lastError));
detail.push('配置文件:<code>' + (view.settingsPath || '') + '</code>');
el('statDetail').innerHTML = detail.join(' · ');
var recent = reporter.recent || [];
if (recent.length === 0) {
el('recent').innerHTML = '<tr><td colspan="5" class="muted">暂无记录</td></tr>';
return;
}
el('recent').innerHTML = recent.slice(0, 12).map(function (row) {
var outcome = row.outcome === 'recorded' ? pill('ok', '已记录')
: row.outcome === 'duplicate' ? pill('sk', '重复')
: row.outcome === 'queued' ? pill('warn', '待重试')
: row.outcome === 'skipped' ? pill('sk', '跳过')
: pill('bad', '失败');
var status = row.status === 'completed' ? pill('ok', 'completed')
: row.status === 'failed' ? pill('bad', 'failed')
: pill('warn', String(row.status || '—'));
var turn = String(row.turnId || '');
if (turn.length > 46) turn = turn.slice(0, 46) + '…';
var tip = row.error ? ' title="' + String(row.error).replace(/"/g, '&quot;') + '"' : '';
return '<tr' + tip + '><td>' + fmtTime(row.at) + '</td><td>' + status + '</td><td>' + outcome +
'</td><td>' + (row.httpStatus == null ? '—' : row.httpStatus) + '</td><td><code>' + turn + '</code></td></tr>';
}).join('');
}
function load() {
return fetch('/cloud-memory/status', { headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) throw new Error((body && body.error) || 'status failed');
render(body);
})
.catch(function (error) { toast('读取状态失败:' + error.message); });
}
function save() {
var patch = {
baseUrl: el('baseUrl').value.trim(),
clientId: el('clientId').value.trim(),
requestTimeoutMs: Number(el('requestTimeoutMs').value),
defaultK: Number(el('defaultK').value),
enabled: el('enabled').checked,
summaryEnabled: el('summaryEnabled').checked,
summaryMaxChars: Number(el('summaryMaxChars').value)
};
var activity = el('activityToken').value.trim();
var memory = el('memoryToken').value.trim();
var summary = el('summaryToken').value.trim();
if (activity !== '') patch.activityToken = activity;
if (memory !== '') patch.memoryToken = memory;
if (summary !== '') patch.summaryToken = summary;
fetch('/cloud-memory/config', {
method: 'PUT',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify(patch)
}).then(function (res) { return res.json(); }).then(function (body) {
if (!body || body.ok !== true) { toast('保存失败:' + ((body && body.error) || 'unknown')); return; }
el('activityToken').value = '';
el('memoryToken').value = '';
el('summaryToken').value = '';
render(body);
toast('已保存');
}).catch(function (error) { toast('保存失败:' + error.message); });
}
function test() {
var node = el('testResult');
node.textContent = '测试中…';
fetch('/cloud-memory/test', { method: 'POST', headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) { node.textContent = '测试失败:' + ((body && body.error) || 'unknown'); return; }
var lines = [];
lines.push((body.activity && body.activity.ok ? '✅ ' : '❌ ') + '活动令牌:' + (body.activity && body.activity.message));
lines.push((body.memory && body.memory.ok ? '✅ ' : '❌ ') + '记忆令牌:' + (body.memory && body.memory.message));
node.innerHTML = lines.join('<br />');
})
.catch(function (error) { node.textContent = '测试失败:' + error.message; });
}
function flush() {
fetch('/cloud-memory/flush', { method: 'POST', headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) { toast('重试失败:' + ((body && body.error) || 'unknown')); return; }
toast('已补发 ' + body.sent + ' 条,剩余 ' + body.remaining + ' 条');
return load();
})
.catch(function (error) { toast('重试失败:' + error.message); });
}
function clearTokens() {
fetch('/cloud-memory/config', {
method: 'PUT',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ clearActivityToken: true, clearMemoryToken: true })
}).then(function (res) { return res.json(); }).then(function (body) {
if (!body || body.ok !== true) { toast('清除失败:' + ((body && body.error) || 'unknown')); return; }
render(body);
toast('已清除本地令牌');
}).catch(function (error) { toast('清除失败:' + error.message); });
}
function login() {
var username = el('username').value.trim();
var password = el('password').value;
if (username === '' || password === '') { toast('请填写用户名和密码'); return; }
fetch('/cloud-memory/login', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ username: username, password: password })
}).then(function (res) { return res.json(); }).then(function (body) {
if (!body || body.ok !== true) { toast('登录失败:' + ((body && body.error) || 'unknown')); return; }
el('password').value = '';
render(body);
var warning = body.login && body.login.warning ? '(' + body.login.warning + ')' : '';
toast('登录成功,已自动写入两个令牌' + warning);
}).catch(function (error) { toast('登录失败:' + error.message); });
}
el('save').addEventListener('click', save);
el('login').addEventListener('click', login);
el('test').addEventListener('click', test);
el('flush').addEventListener('click', flush);
el('clearTokens').addEventListener('click', clearTokens);
el('reload').addEventListener('click', function () { load(); toast('已刷新'); });
load();
setInterval(load, 15000);
})();
</script>
</body>
</html>`
}

444
src/reporter.ts Normal file
View File

@ -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<string, unknown> | 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<string, unknown>
// 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<string, unknown>
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<string, number>()
private readonly queue: TurnPayload[] = []
private readonly retries = new Map<string, number>()
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<string, BufferedMessage[]>()
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<void> {
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<void> {
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],
}
}
}

485
src/routes.ts Normal file
View File

@ -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<string> {
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
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
: JSON.stringify({ ok: false, error: message })
res.writeHead(status, {
'content-type': asHtml ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8',
'cache-control': 'no-store',
})
res.end(text)
}
/** The payload the page and the client card both consume. */
function statusPayload(deps: RouteDeps): Record<string, unknown> {
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<void> {
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<string, unknown>)
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<void> {
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<void> {
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<void> {
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<string, unknown>
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<string, unknown>
} 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<SettingsStore['patch']>[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<void> {
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<string, (body: Record<string, unknown>) => Promise<Record<string, unknown>>> = {
'/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<string, unknown>)) })
} 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),
},
]
}

276
src/skill-admin.ts Normal file
View File

@ -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<boolean> {
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<number> {
let count = 0
const walk = async (sub: string): Promise<void> => {
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<Record<string, { folder?: string; revision?: number }>> {
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<string, { folder?: string; revision?: number }>
}
}
} catch {
// No sidecar yet: nothing has been uploaded.
}
return {}
}
private async describe(folder: string, dir: string, enabled: boolean, uploaded: Record<string, { folder?: string; revision?: number }>): Promise<AdminSkill | undefined> {
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<void> => {
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<void>((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<void> => {
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(() => {})
}
}
}

161
src/skill-page.ts Normal file
View File

@ -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 `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>技能管理 · 云端记忆插件</title>
<style>
body { font-family: system-ui, -apple-system, "Segoe UI", sans-serif; margin: 0; background: #f6f7f9; color: #1c2333; }
.wrap { max-width: 880px; margin: 0 auto; padding: 24px 16px 48px; }
h1 { font-size: 20px; margin: 0 0 4px; }
.sub { color: #5b6478; font-size: 13px; margin: 0 0 16px; }
.card { background: #fff; border: 1px solid #e2e6ee; border-radius: 10px; padding: 16px; margin-bottom: 16px; }
.card h2 { font-size: 15px; margin: 0 0 12px; }
.row { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; border-top: 1px solid #eef1f6; }
.row:first-of-type { border-top: none; }
.grow { flex: 1; min-width: 0; }
.name { font-weight: 600; font-size: 14px; }
.desc { color: #5b6478; font-size: 13px; margin-top: 2px; word-break: break-word; }
.badge { display: inline-block; font-size: 11px; padding: 1px 7px; border-radius: 999px; background: #eef1f6; color: #44506a; margin-left: 6px; vertical-align: 1px; }
.badge.off { background: #fdecec; color: #9c2b2b; }
.badge.cloud { background: #e7f0fe; color: #1c4fa0; }
button { font-size: 13px; padding: 5px 12px; border-radius: 7px; border: 1px solid #c9d2e3; background: #fff; cursor: pointer; white-space: nowrap; }
button:hover { background: #f0f3f9; }
button.danger { border-color: #e3c2c2; color: #9c2b2b; }
button.primary { background: #1c4fa0; border-color: #1c4fa0; color: #fff; }
input[type="text"] { flex: 1; font-size: 13px; padding: 7px 10px; border: 1px solid #c9d2e3; border-radius: 7px; min-width: 0; }
.flex { display: flex; gap: 8px; }
.msg { font-size: 13px; min-height: 18px; margin-top: 8px; }
.msg.err { color: #9c2b2b; }
.empty { color: #8a93a6; font-size: 13px; padding: 8px 0; }
a { color: #1c4fa0; }
</style>
</head>
<body>
<div class="wrap">
<h1>技能管理</h1>
<p class="sub">v${options.version} · 本机技能的列表、启停、安装;删除是真删、不可恢复(云端副本不受影响)。云端同步仍在后台自动进行。<a href="/cloud-memory">← 返回云端记忆设置</a></p>
<section class="card">
<h2>从 git 仓库安装</h2>
<div class="flex">
<input id="git-url" type="text" placeholder="https://github.com/作者/仓库">
<button class="primary" id="install-btn">安装</button>
</div>
<div class="msg" id="install-msg"></div>
</section>
<section class="card">
<h2>本机技能</h2>
<div id="skills"></div>
<div class="msg" id="skills-msg"></div>
</section>
</div>
<script>
const $ = (id) => document.getElementById(id);
function badge(text, cls) {
const span = document.createElement('span');
span.className = 'badge' + (cls ? ' ' + cls : '');
span.textContent = text;
return span;
}
function button(text, cls, onClick) {
const btn = document.createElement('button');
if (cls) btn.className = cls;
btn.textContent = text;
btn.addEventListener('click', onClick);
return btn;
}
async function post(path, body) {
const response = await fetch('/cloud-memory/skills' + path, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
const data = await response.json().catch(() => ({}));
if (!response.ok || data.ok === false) throw new Error(data.error || ('HTTP ' + response.status));
return data;
}
async function act(path, body, msgEl) {
msgEl.textContent = '';
msgEl.className = 'msg';
try {
await post(path, body);
await load();
} catch (error) {
msgEl.textContent = error.message;
msgEl.className = 'msg err';
}
}
async function load() {
const response = await fetch('/cloud-memory/skills/api');
const data = await response.json();
const skillsBox = $('skills');
skillsBox.textContent = '';
if (!data.skills || data.skills.length === 0) {
const empty = document.createElement('div');
empty.className = 'empty';
empty.textContent = '本机还没有技能。云端技能会在同步后自动出现,也可以从上面的仓库安装。';
skillsBox.appendChild(empty);
}
for (const skill of data.skills || []) {
const row = document.createElement('div');
row.className = 'row';
const grow = document.createElement('div');
grow.className = 'grow';
const name = document.createElement('div');
name.className = 'name';
name.textContent = skill.name;
name.appendChild(badge(skill.origin === 'cloud' ? '云端' : skill.origin === 'uploaded' ? '本地 · 已传云端' : '本地', skill.origin === 'cloud' ? 'cloud' : ''));
if (skill.revision) name.appendChild(badge('v' + skill.revision));
if (!skill.enabled) name.appendChild(badge('已停用', 'off'));
grow.appendChild(name);
const desc = document.createElement('div');
desc.className = 'desc';
desc.textContent = skill.description || skill.folder;
grow.appendChild(desc);
row.appendChild(grow);
const msg = $('skills-msg');
row.appendChild(button(skill.enabled ? '停用' : '启用', '', () => act('/toggle', { folder: skill.folder, enabled: !skill.enabled }, msg)));
row.appendChild(button('删除', 'danger', () => {
if (window.confirm('真删「' + skill.name + '」?本地文件不可恢复(云端副本不受影响)。')) {
void act('/remove', { folder: skill.folder }, msg);
}
}));
skillsBox.appendChild(row);
}
}
$('install-btn').addEventListener('click', async () => {
const msg = $('install-msg');
const url = $('git-url').value.trim();
if (!url) { msg.textContent = '先填仓库地址。'; msg.className = 'msg err'; return; }
msg.textContent = '正在克隆并安装…';
msg.className = 'msg';
try {
const data = await post('/install', { url });
const parts = [];
if (data.installed && data.installed.length) parts.push('已安装:' + data.installed.join('、'));
if (data.skipped && data.skipped.length) parts.push('跳过:' + data.skipped.map((s) => s.name).join('、'));
msg.textContent = parts.join(';') || '没有装上任何技能。';
$('git-url').value = '';
await load();
} catch (error) {
msg.textContent = error.message;
msg.className = 'msg err';
}
});
load().catch((error) => { $('skills-msg').textContent = error.message; $('skills-msg').className = 'msg err'; });
</script>
</body>
</html>
`
}

565
src/skill-sync.ts Normal file
View File

@ -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<string, UploadRecord>
/** Cloud skills currently delivered locally, by delivered manifest. */
delivered: Record<string, { manifest: string }>
/**
* 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<string, { manifest: string }>
}
/** 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<boolean> {
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<SyncState> {
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<string, never> =>
value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, never>) : {}
return {
version: 1,
uploaded: map(raw.uploaded) as Record<string, UploadRecord>,
delivered: map(raw.delivered) as Record<string, { manifest: string }>,
removed: map(raw.removed) as Record<string, { manifest: string }>,
}
}
} catch {
// Missing or corrupt sidecar: start clean; the cloud is the truth.
}
return clean
}
private async saveState(state: SyncState): Promise<void> {
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<LocalFile[]> {
const out: LocalFile[] = []
const walk = async (sub: string): Promise<void> => {
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<boolean> {
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<void> {
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<DeliveryManifest | undefined> {
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<SkillSyncStats> {
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<void> {
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<string>()
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/')),
}
}
}

278
src/store.ts Normal file
View File

@ -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\<user>` 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<string, unknown>
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<string, unknown>): { 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
}
}
}

309
src/tools.ts Normal file
View File

@ -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<string, unknown> {
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<string, unknown>): Promise<unknown> {
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<string, unknown>): Promise<unknown> {
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<string, unknown>): Promise<unknown> {
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<string, unknown>): Promise<unknown> {
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<unknown> {
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<unknown> {
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)]
}

12
tsconfig.build.json Normal file
View File

@ -0,0 +1,12 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"declaration": false,
"declarationMap": false,
"sourceMap": false,
"outDir": "lib",
"rewriteRelativeImportExtensions": true
},
"include": ["src"]
}

20
tsconfig.json Normal file
View File

@ -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"]
}

149
verify-mnemon-provider.mjs Normal file
View File

@ -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 = '<redacted>'
// ---- 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)

110
verify-reporter.mjs Normal file
View File

@ -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)

165
verify-skill-admin.mjs Normal file
View File

@ -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)

186
verify-skills-sync.mjs Normal file
View File

@ -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)