feat: dsh-cloud-memory 0.1.0

This commit is contained in:
邱奕涵 2026-10-31 17:53:17 +08:00
commit c9fa9efb47
31 changed files with 6762 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

20
.gitignore vendored Normal file
View File

@ -0,0 +1,20 @@
# 依赖与缓存
node_modules/
.pnpm-store/
.pnpm-cache/
.npm/
# 构建以外的东西不忽略:lib/ 与 client/ 是 npm 包的实际产物,直接入库,保证仓库与发布件一致
# 本地与临时
.env
.env.*
*.log
*.tgz
.tmp/
tmp/
.DS_Store
Thumbs.db
# 发布时生成
npm-debug.log*

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.

120
README.md Normal file
View File

@ -0,0 +1,120 @@
# dsh-cloud-memory
把 DeepSeek Harness 接到 LongMemory 云端记忆服务:**每轮对话结束自动上报一条活动记录**(只上传元数据),并把云端记忆库变成 agent 可用的工具。
当前版本 **0.1.0**,含宿主端与浏览器端两部分: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_…`。 |
两个令牌也可以用环境变量 `DSH_CLOUD_MEMORY_ACTIVITY_TOKEN`、`DSH_CLOUD_MEMORY_MEMORY_TOKEN` 覆盖。
> 一个 key 只有一种 scope,所以需要两个令牌:只做上报就只填活动令牌,只做检索就只填记忆令牌。
## 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
},
})

12
cordis.patch.yml Normal file
View File

@ -0,0 +1,12 @@
# 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

266
lib/api.js Normal file
View File

@ -0,0 +1,266 @@
/**
* 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);
}
/**
* 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');
}
/**
* 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}`;
}

69
lib/config.js Normal file
View File

@ -0,0 +1,69 @@
/**
* 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://your-memory-host/api/longmemory',
clientId: 'dsh-desktop',
requestTimeoutMs: 8000,
defaultK: 10,
};
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;
return result;
}

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

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

97
lib/index.js Normal file
View File

@ -0,0 +1,97 @@
/**
* 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 { SettingsStore } from "./store.js";
import { createMemoryTools } 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.1.0';
/** 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(),
log: (message) => logger.warn(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}`);
}
// 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;
for (const tool of createMemoryTools({
client: () => client,
memoryToken: () => store.memoryToken(),
settings: () => ({ enabled: settings().enabled, defaultK: settings().defaultK }),
})) {
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 });
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');
}

401
lib/page.js Normal file
View File

@ -0,0 +1,401 @@
/**
* 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>
<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://your-memory-host/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>
</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>
<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('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', '未配置'));
var stats = [
['上报成功', reporter.recorded || 0],
['重复忽略', reporter.duplicate || 0],
['失败', reporter.failed || 0],
['已跳过', reporter.skipped || 0],
['待重试', reporter.queued || 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
};
var activity = el('activityToken').value.trim();
var memory = el('memoryToken').value.trim();
if (activity !== '') patch.activityToken = activity;
if (memory !== '') patch.memoryToken = memory;
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 = '';
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>`;
}

246
lib/reporter.js Normal file
View File

@ -0,0 +1,246 @@
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;
}
/**
* 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.
*/
export class Reporter {
options;
startedAt = new Map();
queue = [];
recent = [];
attempted = 0;
recorded = 0;
duplicate = 0;
failed = 0;
skipped = 0;
lastSentAt;
lastError;
draining = false;
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 === '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);
}
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.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;
break;
}
this.queue.shift();
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,
...(this.lastSentAt === undefined ? {} : { lastSentAt: this.lastSentAt }),
...(this.lastError === undefined ? {} : { lastError: this.lastError }),
recent: [...this.recent],
};
}
}

309
lib/routes.js Normal file
View File

@ -0,0 +1,309 @@
import { describeError, isSecureLoginTarget } from "./api.js";
import { renderConfigPage } from "./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',
};
/** 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,
};
const settings = {
enabled: view.enabled,
baseUrl: view.baseUrl,
clientId: view.clientId,
requestTimeoutMs: view.requestTimeoutMs,
defaultK: view.defaultK,
};
return { ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot() };
}
/** 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) };
})();
json(res, 200, { ok: true, activity, memory });
}
/** `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 记忆读写',
};
/**
* `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);
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;
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,
warning: failed.ok ? undefined : `部分令牌没有创建成功:${describeError(failed.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),
},
];
}

233
lib/store.js Normal file
View File

@ -0,0 +1,233 @@
/**
* 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;
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;
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') ?? '';
}
/** Masked snapshot for the browser card. */
describe() {
const settings = this.settings();
const activity = this.activityToken();
const memory = this.memoryToken();
return {
...settings,
activityToken: { configured: activity !== '', masked: activity === '' ? '' : maskToken(activity) },
memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory) },
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.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;
}
}
}

256
lib/tools.js Normal file
View File

@ -0,0 +1,256 @@
/**
* 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)];
}

75
package.json Normal file
View File

@ -0,0 +1,75 @@
{
"name": "dsh-cloud-memory",
"version": "0.1.0",
"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"
},
"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"
},
"peerDependenciesMeta": {
"react": {
"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"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"keywords": [
"dsh",
"dsh-plugin",
"memory",
"cloud-memory",
"longmemory",
"agent"
],
"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 一旦发布就不能再改同号。')

376
src/api.ts Normal file
View File

@ -0,0 +1,376 @@
/**
* 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 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 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)
}
/**
* 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')
}
/**
* 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}`
}

80
src/config.ts Normal file
View File

@ -0,0 +1,80 @@
/**
* 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://your-memory-host/api/longmemory',
clientId: 'dsh-desktop',
requestTimeoutMs: 8000,
defaultK: 10,
}
/** 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
}
/** 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
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>
}

112
src/index.ts Normal file
View File

@ -0,0 +1,112 @@
/**
* 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 { SettingsStore } from './store.ts'
import { createMemoryTools } 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.1.0'
/** 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(),
log: (message) => logger.warn(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}`)
}
// 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
for (const tool of createMemoryTools({
client: () => client,
memoryToken: () => store.memoryToken(),
settings: () => ({ enabled: settings().enabled, defaultK: settings().defaultK }),
})) {
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 })
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')
}

403
src/page.ts Normal file
View File

@ -0,0 +1,403 @@
/**
* 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>
<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://your-memory-host/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>
</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>
<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('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', '未配置'));
var stats = [
['上报成功', reporter.recorded || 0],
['重复忽略', reporter.duplicate || 0],
['失败', reporter.failed || 0],
['已跳过', reporter.skipped || 0],
['待重试', reporter.queued || 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
};
var activity = el('activityToken').value.trim();
var memory = el('memoryToken').value.trim();
if (activity !== '') patch.activityToken = activity;
if (memory !== '') patch.memoryToken = memory;
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 = '';
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>`
}

292
src/reporter.ts Normal file
View File

@ -0,0 +1,292 @@
/**
* 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, 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
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
/** 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
}
/**
* 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.
*/
export class Reporter {
private readonly startedAt = new Map<string, number>()
private readonly queue: TurnPayload[] = []
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
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 === '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)
}
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.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
break
}
this.queue.shift()
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,
...(this.lastSentAt === undefined ? {} : { lastSentAt: this.lastSentAt }),
...(this.lastError === undefined ? {} : { lastError: this.lastError }),
recent: [...this.recent],
}
}
}

349
src/routes.ts Normal file
View File

@ -0,0 +1,349 @@
/**
* 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'
/** 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',
} 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
}
/** 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', TokenView> = {
activity: view.activityToken,
memory: view.memoryToken,
}
const settings = {
enabled: view.enabled,
baseUrl: view.baseUrl,
clientId: view.clientId,
requestTimeoutMs: view.requestTimeoutMs,
defaultK: view.defaultK,
}
return { ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot() }
}
/** 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) }
})()
json(res, 200, { ok: true, activity, memory })
}
/** `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 记忆读写',
} 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)
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
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,
warning: failed.ok ? undefined : `部分令牌没有创建成功:${describeError(failed.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),
},
]
}

245
src/store.ts Normal file
View File

@ -0,0 +1,245 @@
/**
* 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
}
/** 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
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
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
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') ?? ''
}
/** Masked snapshot for the browser card. */
describe(): SettingsView {
const settings = this.settings()
const activity = this.activityToken()
const memory = this.memoryToken()
return {
...settings,
activityToken: { configured: activity !== '', masked: activity === '' ? '' : maskToken(activity) },
memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory) },
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.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
}
}
}

278
src/tools.ts Normal file
View File

@ -0,0 +1,278 @@
/**
* 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)]
}

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