commit c9fa9efb47117c6f74769b81f8470805b7fb2b8b Author: 邱奕涵 <91305372+newbieQQ@users.noreply.github.com> Date: Sat Oct 31 17:53:17 2026 +0800 feat: dsh-cloud-memory 0.1.0 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8c2e79a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +* text=auto eol=lf +*.ps1 text eol=crlf +*.cmd text eol=crlf +*.png binary +*.tgz binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..16e19f2 --- /dev/null +++ b/.gitignore @@ -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* diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..dff5061 --- /dev/null +++ b/.npmignore @@ -0,0 +1,21 @@ +# ?????? package.json ? files ??????????????? npm ?? +AGENTS.md +TODO.md +TASKS.md +HANDOFF.md +NOTES.md +*.plan.md +PLAN.md +scripts/ +src/ +tsconfig*.json +pnpm-lock.yaml +package-lock.json +.pnpm-cache/ +.pnpm-store/ +node_modules/ +*.mjs +*.log +*.tgz +.env +.env.* \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d5fa063 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 dsh-cloud-memory contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..19e00e2 --- /dev/null +++ b/README.md @@ -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` 为 `:`,服务端按 `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` 再发布。 diff --git a/client/index.js b/client/index.js new file mode 100644 index 0000000..2869413 --- /dev/null +++ b/client/index.js @@ -0,0 +1,846 @@ +// dsh-cloud-memory client bundle. +// +// Hand-written on purpose: the host loads this file through `require` shims it +// provides itself (react / react/jsx-runtime), so no bundler is involved. The +// module wrapper below is the contract the web loader expects — `id` has to +// match the package name, otherwise the module graph registers a second copy. +window.__ModuleLoader__.load({ + id: 'dsh-cloud-memory', + factory: (require) => { + var module = { exports: {} } + var exports = module.exports + + 'use strict' + + var React = require('react') + var h = React.createElement + + var STATUS_URL = '/cloud-memory/status' + var CONFIG_URL = '/cloud-memory/config' + var LOGIN_URL = '/cloud-memory/login' + var TEST_URL = '/cloud-memory/test' + var FLUSH_URL = '/cloud-memory/flush' + var POLL_MS = 10000 + + var inject = ['slots'] + + function request(url, init) { + var options = init || {} + options.cache = 'no-store' + options.headers = options.body === undefined + ? { accept: 'application/json' } + : { accept: 'application/json', 'content-type': 'application/json' } + return fetch(url, options).then(function (response) { + return response.json().then( + function (body) { + return { status: response.status, body: body } + }, + function () { + return { status: response.status, body: null } + }, + ) + }) + } + + function messageOf(error) { + if (error === null || error === undefined) return '未知错误' + if (typeof error === 'string') return error + return typeof error.message === 'string' ? error.message : String(error) + } + + // A 404/405 here means the host half on disk is newer than the one this + // window is talking to: the module is loaded into the running process and + // does not hot-reload, so the answer is a restart, not a retry. + function statusText(status) { + if (status === 404 || status === 405) { + return '插件后端还没加载这个接口(HTTP ' + String(status) + '):请完全退出并重启 DSH 后再试。' + } + return 'HTTP ' + String(status) + } + + function pickSettings(settings) { + return { + enabled: settings.enabled === true, + baseUrl: String(settings.baseUrl === undefined ? '' : settings.baseUrl), + clientId: String(settings.clientId === undefined ? '' : settings.clientId), + requestTimeoutMs: String(settings.requestTimeoutMs === undefined ? 8000 : settings.requestTimeoutMs), + defaultK: String(settings.defaultK === undefined ? 10 : settings.defaultK), + } + } + + function formatTime(value) { + if (typeof value !== 'number' || value <= 0) return '—' + var date = new Date(value) + var pad = function (n) { + return n < 10 ? '0' + String(n) : String(n) + } + return pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()) + } + + var OUTCOME_LABELS = { + recorded: '已上报', + duplicate: '重复忽略', + failed: '失败', + queued: '待重试', + skipped: '已跳过', + } + + var OUTCOME_TONES = { + recorded: 'ok', + duplicate: 'muted', + failed: 'bad', + queued: 'warn', + skipped: 'muted', + } + + var styles = { + root: { + display: 'flex', + flexDirection: 'column', + gap: '18px', + padding: '4px 2px 20px', + fontSize: '13px', + lineHeight: 1.55, + }, + section: { + display: 'flex', + flexDirection: 'column', + gap: '10px', + border: '1px solid rgba(127,127,127,0.28)', + borderRadius: '10px', + padding: '14px 16px', + }, + sectionTitle: { + margin: 0, + fontSize: '13px', + fontWeight: 600, + letterSpacing: '0.02em', + }, + hint: { + margin: 0, + fontSize: '12px', + opacity: 0.65, + }, + grid: { + display: 'flex', + flexWrap: 'wrap', + gap: '12px 18px', + }, + field: { + display: 'flex', + flexDirection: 'column', + gap: '4px', + flex: '1 1 220px', + minWidth: '180px', + }, + label: { + fontSize: '12px', + opacity: 0.75, + }, + input: { + font: 'inherit', + fontSize: '13px', + padding: '6px 9px', + borderRadius: '7px', + border: '1px solid rgba(127,127,127,0.4)', + background: 'transparent', + color: 'inherit', + minWidth: 0, + }, + checkboxRow: { + display: 'flex', + alignItems: 'center', + gap: '8px', + }, + actions: { + display: 'flex', + gap: '10px', + flexWrap: 'wrap', + alignItems: 'center', + }, + button: { + font: 'inherit', + fontSize: '13px', + padding: '6px 16px', + borderRadius: '8px', + border: '1px solid rgba(127,127,127,0.45)', + background: 'transparent', + color: 'inherit', + cursor: 'pointer', + }, + buttonPrimary: { + font: 'inherit', + fontSize: '13px', + padding: '6px 16px', + borderRadius: '8px', + border: '1px solid rgba(37,99,235,0.6)', + background: 'rgba(37,99,235,0.16)', + color: 'inherit', + cursor: 'pointer', + }, + pills: { + display: 'flex', + flexWrap: 'wrap', + gap: '8px', + }, + pill: { + display: 'inline-flex', + alignItems: 'center', + gap: '6px', + padding: '3px 10px', + borderRadius: '999px', + border: '1px solid rgba(127,127,127,0.35)', + fontSize: '12px', + }, + table: { + width: '100%', + borderCollapse: 'collapse', + fontSize: '12px', + }, + th: { + textAlign: 'left', + fontWeight: 600, + padding: '4px 8px 4px 0', + borderBottom: '1px solid rgba(127,127,127,0.28)', + whiteSpace: 'nowrap', + }, + td: { + padding: '4px 8px 4px 0', + borderBottom: '1px solid rgba(127,127,127,0.14)', + verticalAlign: 'top', + }, + mono: { + fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', + fontSize: '11.5px', + wordBreak: 'break-all', + }, + ok: { borderColor: 'rgba(22,163,74,0.55)', background: 'rgba(22,163,74,0.12)' }, + bad: { borderColor: 'rgba(220,38,38,0.55)', background: 'rgba(220,38,38,0.12)' }, + warn: { borderColor: 'rgba(217,119,6,0.55)', background: 'rgba(217,119,6,0.12)' }, + muted: {}, + banner: { + padding: '8px 12px', + borderRadius: '8px', + fontSize: '12.5px', + }, + } + + function Pill(props) { + var tone = styles[props.tone] === undefined ? styles.muted : styles[props.tone] + return h( + 'span', + { style: Object.assign({}, styles.pill, tone) }, + h('span', { style: { opacity: 0.75 } }, props.label), + h('span', { style: { fontWeight: 600 } }, String(props.value)), + ) + } + + function Field(props) { + return h( + 'label', + { style: styles.field }, + h('span', { style: styles.label }, props.label), + h('input', { + style: styles.input, + type: props.type === undefined ? 'text' : props.type, + value: props.value, + placeholder: props.placeholder === undefined ? '' : props.placeholder, + spellCheck: false, + autoComplete: 'off', + disabled: props.disabled === true, + onChange: function (event) { + props.onChange(event.target.value) + }, + }), + props.hint === undefined ? null : h('span', { style: styles.hint }, props.hint), + ) + } + + function CloudMemorySettingsCard() { + var snapshotState = React.useState(null) + var snapshot = snapshotState[0] + var setSnapshot = snapshotState[1] + + var draftState = React.useState(null) + var draft = draftState[0] + var setDraft = draftState[1] + + var tokenState = React.useState({ activity: '', memory: '' }) + var tokenDraft = tokenState[0] + var setTokenDraft = tokenState[1] + + var loginState = React.useState({ username: '', password: '' }) + var loginDraft = loginState[0] + var setLoginDraft = loginState[1] + + var loginResultState = React.useState(null) + var loginResult = loginResultState[0] + var setLoginResult = loginResultState[1] + + var errorState = React.useState(null) + var error = errorState[0] + var setError = errorState[1] + + var noticeState = React.useState(null) + var notice = noticeState[0] + var setNotice = noticeState[1] + + var testState = React.useState(null) + var testResult = testState[0] + var setTestResult = testState[1] + + var busyState = React.useState('') + var busy = busyState[0] + var setBusy = busyState[1] + + var load = React.useCallback( + function (keepDraft) { + request(STATUS_URL) + .then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + setError('读取插件状态失败(HTTP ' + String(result.status) + '),请重启 DSH 后再试。') + return + } + setError(null) + setSnapshot(result.body) + if (keepDraft !== true) setDraft(pickSettings(result.body.settings)) + }) + .catch(function (failure) { + setError('无法连接插件:' + messageOf(failure)) + }) + }, + [setDraft, setError, setSnapshot], + ) + + React.useEffect( + function () { + load(false) + var timer = setInterval(function () { + if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return + load(true) + }, POLL_MS) + return function () { + clearInterval(timer) + } + }, + [load], + ) + + function patchDraft(patch) { + setDraft(function (previous) { + return Object.assign({}, previous, patch) + }) + } + + function run(label, task) { + setBusy(label) + setNotice(null) + return Promise.resolve() + .then(task) + .catch(function (failure) { + setNotice({ tone: 'bad', text: messageOf(failure) }) + }) + .then(function () { + setBusy('') + }) + } + + function save() { + return run('save', function () { + var payload = { + enabled: draft.enabled, + baseUrl: draft.baseUrl, + clientId: draft.clientId, + requestTimeoutMs: Number(draft.requestTimeoutMs), + defaultK: Number(draft.defaultK), + } + if (tokenDraft.activity.trim() !== '') payload.activityToken = tokenDraft.activity.trim() + if (tokenDraft.memory.trim() !== '') payload.memoryToken = tokenDraft.memory.trim() + return request(CONFIG_URL, { method: 'PUT', body: JSON.stringify(payload) }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + var reason = result.body !== null && typeof result.body.error === 'string' ? result.body.error : statusText(result.status) + throw new Error('保存失败:' + reason) + } + setTokenDraft({ activity: '', memory: '' }) + setNotice({ tone: 'ok', text: '已保存到本机配置文件。' }) + load(false) + }) + }) + } + + function clearToken(which) { + return run('clear-' + which, function () { + var payload = which === 'activity' ? { clearActivityToken: true } : { clearMemoryToken: true } + return request(CONFIG_URL, { method: 'PUT', body: JSON.stringify(payload) }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + throw new Error('清除令牌失败(HTTP ' + String(result.status) + ')') + } + setNotice({ tone: 'ok', text: '令牌已清除。' }) + load(false) + }) + }) + } + + function test() { + return run('test', function () { + setTestResult(null) + return request(TEST_URL, { method: 'POST', body: '{}' }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + throw new Error('测试失败(HTTP ' + String(result.status) + ')') + } + setTestResult(result.body) + }) + }) + } + + function flush() { + return run('flush', function () { + return request(FLUSH_URL, { method: 'POST', body: '{}' }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + throw new Error('重试失败(HTTP ' + String(result.status) + ')') + } + setNotice({ tone: 'ok', text: '已重试 ' + String(result.body.sent) + ' 条,剩余 ' + String(result.body.remaining) + ' 条。' }) + load(true) + }) + }) + } + + function login() { + return run('login', function () { + setLoginResult(null) + var payload = { username: loginDraft.username.trim(), password: loginDraft.password } + if (payload.username === '' || payload.password === '') { + throw new Error('请填写用户名和密码') + } + return request(LOGIN_URL, { method: 'POST', body: JSON.stringify(payload) }).then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + var reason = result.body !== null && typeof result.body.error === 'string' ? result.body.error : statusText(result.status) + throw new Error('登录失败:' + reason) + } + // Drop the password the moment the exchange succeeded. + setLoginDraft({ username: payload.username, password: '' }) + setLoginResult(result.body.login || null) + setNotice({ + tone: result.body.login !== null && result.body.login !== undefined && result.body.login.partial === true ? 'warn' : 'ok', + text: '登录成功,已自动写入两个令牌。', + }) + setSnapshot(result.body) + setDraft(pickSettings(result.body.settings)) + }) + }) + } + + if (error !== null && snapshot === null) { + return h( + 'div', + { style: styles.root }, + h('div', { style: Object.assign({}, styles.banner, styles.bad) }, error), + h( + 'div', + { style: styles.actions }, + h( + 'button', + { + style: styles.button, + onClick: function () { + load(false) + }, + }, + '重新加载', + ), + ), + ) + } + + if (snapshot === null || draft === null) { + return h('div', { style: styles.root }, h('p', { style: styles.hint }, '正在读取云端记忆插件状态…')) + } + + var reporter = snapshot.reporter === undefined ? {} : snapshot.reporter + var tokens = snapshot.tokens === undefined ? { activity: {}, memory: {} } : snapshot.tokens + var recent = Array.isArray(reporter.recent) ? reporter.recent.slice(0, 6) : [] + var activityToken = tokens.activity === undefined ? {} : tokens.activity + var memoryToken = tokens.memory === undefined ? {} : tokens.memory + + var banner = null + if (notice !== null) { + banner = h('div', { style: Object.assign({}, styles.banner, styles[notice.tone]) }, notice.text) + } + + var testBox = null + if (testResult !== null) { + var activityTest = testResult.activity === undefined ? {} : testResult.activity + var memoryTest = testResult.memory === undefined ? {} : testResult.memory + testBox = h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '6px' } }, + h( + 'div', + { style: Object.assign({}, styles.banner, activityTest.ok === true ? styles.ok : styles.bad) }, + '活动上报权限:' + (activityTest.ok === true ? '可用 — ' : '不可用 — ') + String(activityTest.message === undefined ? '' : activityTest.message), + ), + h( + 'div', + { style: Object.assign({}, styles.banner, memoryTest.ok === true ? styles.ok : styles.bad) }, + '记忆读写权限:' + (memoryTest.ok === true ? '可用 — ' : '不可用 — ') + String(memoryTest.message === undefined ? '' : memoryTest.message), + ), + ) + } + + return h( + 'div', + { style: styles.root }, + + h( + 'div', + { style: styles.pills }, + h(Pill, { label: '已上报', value: reporter.recorded === undefined ? 0 : reporter.recorded, tone: 'ok' }), + h(Pill, { label: '重复忽略', value: reporter.duplicate === undefined ? 0 : reporter.duplicate, tone: 'muted' }), + h(Pill, { label: '失败', value: reporter.failed === undefined ? 0 : reporter.failed, tone: 'bad' }), + h(Pill, { label: '待重试', value: reporter.queued === undefined ? 0 : reporter.queued, tone: 'warn' }), + h(Pill, { label: '已跳过', value: reporter.skipped === undefined ? 0 : reporter.skipped, tone: 'muted' }), + ), + + activityToken.configured !== true && memoryToken.configured !== true + ? h( + 'div', + { style: Object.assign({}, styles.banner, styles.warn) }, + '还没有配置令牌。先到云端面板「设置 → API 密钥」各建一个 activity:write 与 memory:write 密钥,把两个都粘到下面「访问令牌」两栏,再点「保存」。', + ) + : null, + + banner, + + h( + 'div', + { style: styles.section }, + h('h4', { style: styles.sectionTitle }, '连接'), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '服务地址', + value: draft.baseUrl, + onChange: function (value) { + patchDraft({ baseUrl: value }) + }, + hint: '留空或写错时会退回默认地址。', + }), + h(Field, { + label: '客户端标识(client_id)', + value: draft.clientId, + onChange: function (value) { + patchDraft({ clientId: value }) + }, + }), + h(Field, { + label: '请求超时(毫秒)', + type: 'number', + value: draft.requestTimeoutMs, + onChange: function (value) { + patchDraft({ requestTimeoutMs: value }) + }, + }), + h(Field, { + label: '默认检索条数', + type: 'number', + value: draft.defaultK, + onChange: function (value) { + patchDraft({ defaultK: value }) + }, + }), + ), + h( + 'div', + { style: styles.checkboxRow }, + h('input', { + type: 'checkbox', + checked: draft.enabled, + id: 'dsh-cloud-memory-enabled', + onChange: function (event) { + patchDraft({ enabled: event.target.checked }) + }, + }), + h('label', { htmlFor: 'dsh-cloud-memory-enabled', style: styles.label }, '启用每轮活动上报(只上报时间戳、会话 id 与状态,不上传对话内容)'), + ), + ), + + h( + 'div', + { style: styles.section }, + h('h4', { style: styles.sectionTitle }, '账号登录(推荐)'), + h( + 'p', + { style: styles.hint }, + '用云端面板的普通用户账号登录,插件会用一次性会话换取 activity:write 与 memory:write 两个令牌并写入本机。密码只在这一次请求里使用:不保存、不写日志、不回显,换取成功后立即从内存丢弃。', + ), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '用户名', + value: loginDraft.username, + placeholder: '云端面板的账号', + onChange: function (value) { + setLoginDraft(function (previous) { + return Object.assign({}, previous, { username: value }) + }) + }, + }), + h(Field, { + label: '密码', + type: 'password', + value: loginDraft.password, + placeholder: '只用于本次换取令牌', + onChange: function (value) { + setLoginDraft(function (previous) { + return Object.assign({}, previous, { password: value }) + }) + }, + hint: '成功后自动清空', + }), + ), + h( + 'div', + { style: styles.actions }, + h( + 'button', + { + style: styles.buttonPrimary, + disabled: busy !== '', + onClick: function () { + login() + }, + }, + busy === 'login' ? '登录中…' : '登录并获取令牌', + ), + loginResult === null + ? null + : h( + 'span', + { style: styles.hint }, + '已登录:' + + String(loginResult.user !== null && loginResult.user !== undefined && loginResult.user.username !== undefined ? loginResult.user.username : '未知账号') + + (loginResult.warning === undefined || loginResult.warning === null ? '' : '(' + String(loginResult.warning) + ')'), + ), + ), + ), + + h( + 'div', + { style: styles.section }, + h('h4', { style: styles.sectionTitle }, '访问令牌'), + h( + 'p', + { style: styles.hint }, + '两个令牌各有独立权限:activity:write 只用于上报,memory:write 同时允许检索与写入。令牌只写入本机 ' + + String(snapshot.settingsPath === undefined ? '配置文件' : snapshot.settingsPath) + + ',不会进入会话上下文。', + ), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '活动上报令牌(activity:write)', + type: 'password', + value: tokenDraft.activity, + placeholder: activityToken.configured === true ? '已配置 ' + String(activityToken.masked) + ',留空表示不修改' : '未配置', + onChange: function (value) { + setTokenDraft(function (previous) { + return Object.assign({}, previous, { activity: value }) + }) + }, + hint: activityToken.configured === true ? '当前:' + String(activityToken.masked) : undefined, + }), + h(Field, { + label: '记忆读写令牌(memory:write)', + type: 'password', + value: tokenDraft.memory, + placeholder: memoryToken.configured === true ? '已配置 ' + String(memoryToken.masked) + ',留空表示不修改' : '未配置', + onChange: function (value) { + setTokenDraft(function (previous) { + return Object.assign({}, previous, { memory: value }) + }) + }, + hint: memoryToken.configured === true ? '当前:' + String(memoryToken.masked) : undefined, + }), + ), + h( + 'div', + { style: styles.actions }, + h( + 'button', + { + style: styles.button, + disabled: activityToken.configured !== true, + onClick: function () { + clearToken('activity') + }, + }, + '清除上报令牌', + ), + h( + 'button', + { + style: styles.button, + disabled: memoryToken.configured !== true, + onClick: function () { + clearToken('memory') + }, + }, + '清除记忆令牌', + ), + ), + ), + + h( + 'div', + { style: styles.actions }, + h( + 'button', + { + style: styles.buttonPrimary, + disabled: busy !== '', + onClick: function () { + save() + }, + }, + busy === 'save' ? '保存中…' : '保存', + ), + h( + 'button', + { + style: styles.button, + disabled: busy !== '', + onClick: function () { + test() + }, + }, + busy === 'test' ? '测试中…' : '测试连接', + ), + h( + 'button', + { + style: styles.button, + disabled: busy !== '' || reporter.queued === undefined || reporter.queued === 0, + onClick: function () { + flush() + }, + }, + '重试上报队列', + ), + ), + + testBox, + + h( + 'div', + { style: styles.section }, + h('h4', { style: styles.sectionTitle }, '最近上报'), + recent.length === 0 + ? h('p', { style: styles.hint }, '还没有记录。发一条消息让它跑完一轮,这里就会出现一条。') + : h( + 'table', + { style: styles.table }, + h( + 'thead', + null, + h( + 'tr', + null, + h('th', { style: styles.th }, '时间'), + h('th', { style: styles.th }, '结果'), + h('th', { style: styles.th }, '状态'), + h('th', { style: styles.th }, 'turn_id'), + ), + ), + h( + 'tbody', + null, + recent.map(function (row, index) { + var outcome = String(row.outcome === undefined ? '' : row.outcome) + return h( + 'tr', + { key: String(row.turnId) + ':' + String(index) }, + h('td', { style: styles.td }, formatTime(row.at)), + h( + 'td', + { style: styles.td }, + h( + 'span', + { style: Object.assign({}, styles.pill, styles[OUTCOME_TONES[outcome]] === undefined ? styles.muted : styles[OUTCOME_TONES[outcome]]) }, + OUTCOME_LABELS[outcome] === undefined ? outcome : OUTCOME_LABELS[outcome], + ), + ), + h('td', { style: styles.td }, String(row.status === undefined ? '' : row.status)), + h('td', { style: Object.assign({}, styles.td, styles.mono) }, String(row.turnId === undefined ? '' : row.turnId)), + ) + }), + ), + ), + reporter.lastError === undefined + ? null + : h('p', { style: styles.hint }, '最近一次错误:' + String(reporter.lastError)), + ), + + h('p', { style: styles.hint }, '配置保存在 ' + String(snapshot.settingsPath === undefined ? '本机配置文件' : snapshot.settingsPath) + ',页面地址 /cloud-memory 仍然可用。'), + ) + } + + // A thrown render error must not take the settings page down with it, so the + // card is wrapped in a minimal boundary that renders the message instead. + function CardBoundary(props) { + React.Component.call(this, props) + this.state = { failure: null } + } + + CardBoundary.prototype = Object.create(React.Component.prototype) + CardBoundary.prototype.constructor = CardBoundary + + CardBoundary.getDerivedStateFromError = function (failure) { + return { failure: failure } + } + + CardBoundary.prototype.render = function () { + if (this.state.failure !== null) { + return h( + 'div', + { style: Object.assign({}, styles.root) }, + h('div', { style: Object.assign({}, styles.banner, styles.bad) }, '云端记忆设置卡渲染失败:' + messageOf(this.state.failure)), + h('p', { style: styles.hint }, '插件本身仍在运行,可改用 /cloud-memory 页面配置。'), + ) + } + return this.props.children + } + + function apply(ctx) { + var card = function () { + return h(CardBoundary, null, h(CloudMemorySettingsCard, null)) + } + + var register = function (seat, options) { + try { + ctx.slots.inject(seat, function () { + return ctx.slots.register(options, card) + }) + } catch (failure) { + if (typeof console !== 'undefined') console.warn('[dsh-cloud-memory] slot ' + seat + ' unavailable: ' + messageOf(failure)) + } + } + + register('settings.section', { + name: 'settings.section', + id: 'cloud-memory', + order: 100, + label: function () { + return '云端记忆' + }, + }) + + register('plugins.bundle.config', { name: 'plugins.bundle.config', key: 'dsh-cloud-memory' }) + } + + module.exports = { apply: apply, inject: inject, name: 'dsh-cloud-memory' } + return module.exports + }, +}) diff --git a/cordis.patch.yml b/cordis.patch.yml new file mode 100644 index 0000000..0fb82c8 --- /dev/null +++ b/cordis.patch.yml @@ -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 diff --git a/lib/api.js b/lib/api.js new file mode 100644 index 0000000..a35845f --- /dev/null +++ b/lib/api.js @@ -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}`; +} diff --git a/lib/config.js b/lib/config.js new file mode 100644 index 0000000..7fc077f --- /dev/null +++ b/lib/config.js @@ -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; +} diff --git a/lib/context-types.js b/lib/context-types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/lib/context-types.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..c20d145 --- /dev/null +++ b/lib/index.js @@ -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'); +} diff --git a/lib/page.js b/lib/page.js new file mode 100644 index 0000000..ccfe9f0 --- /dev/null +++ b/lib/page.js @@ -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('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); +} +/** Render the configuration page. */ +export function renderConfigPage(options) { + // The client script is plain ES2020 and avoids template literals so this + // outer template stays readable. + return ` + + + + +云端记忆 · DSH 插件 + + + +
+

云端记忆 · DSH 插件

+

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

+ +
+

当前状态

+
+
加载中…
+
+ +
+

连接配置

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

账号登录

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

访问令牌

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

诊断

+
+ + + +
+
+
+ +
+

最近上报

+ + + + + +
时间状态结果HTTPturn_id
暂无记录
+
+
+
+ + +`; +} diff --git a/lib/reporter.js b/lib/reporter.js new file mode 100644 index 0000000..5b64a01 --- /dev/null +++ b/lib/reporter.js @@ -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], + }; + } +} diff --git a/lib/routes.js b/lib/routes.js new file mode 100644 index 0000000..5b47cc6 --- /dev/null +++ b/lib/routes.js @@ -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 + ? `云端记忆${message}` + : JSON.stringify({ ok: false, error: message }); + res.writeHead(status, { + 'content-type': asHtml ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8', + 'cache-control': 'no-store', + }); + res.end(text); +} +/** The payload the page and the client card both consume. */ +function statusPayload(deps) { + const view = deps.store.describe(); + const tokens = { + activity: view.activityToken, + memory: view.memoryToken, + }; + 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), + }, + ]; +} diff --git a/lib/store.js b/lib/store.js new file mode 100644 index 0000000..bf0631f --- /dev/null +++ b/lib/store.js @@ -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\` 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; + } + } +} diff --git a/lib/tools.js b/lib/tools.js new file mode 100644 index 0000000..7b05e4c --- /dev/null +++ b/lib/tools.js @@ -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)]; +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..0ffadc2 --- /dev/null +++ b/package.json @@ -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" +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..13402e2 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,1269 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@deepseek-ai/cordis': + specifier: ^4.0.4 + version: 4.0.5 + '@deepseek-ai/dsh-client-locale': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-client-ui-settings': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-client-ui-sidebar-right': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-client-ui-slots': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-host-webserver': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-tools': + specifier: 0.2.1-rc.3 + version: 0.2.1-rc.3(1f5d0a9b849aaa1244bc4f2e453f609a) + '@types/node': + specifier: ^22.20.0 + version: 22.20.5 + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + react: + specifier: ^18.2.0 + version: 18.3.1 + tsdown: + specifier: ^0.22.2 + version: 0.22.14(typescript@5.9.3) + typescript: + specifier: ^5.6.0 + version: 5.9.3 + +packages: + + '@deepseek-ai/cordis@4.0.5': + resolution: {integrity: sha512-Sktq5axy0owk9PdnivBRNOJjHEVEibCt0+TDDZcv0+UH2KS1M910fX4kn5y45YFsrpZIi1mJf/1s5VzywMUnyg==} + hasBin: true + peerDependencies: + '@deepseek-ai/cordis-plugin-include': ~1.0.10 + '@deepseek-ai/cordis-plugin-loader': ~1.0.6 + peerDependenciesMeta: + '@deepseek-ai/cordis-plugin-include': + optional: true + '@deepseek-ai/cordis-plugin-loader': + optional: true + + '@deepseek-ai/cosmokit@1.8.6': + resolution: {integrity: sha512-ZSD/fN52L498LBIOYwjIOlaLv5veY6ZEwI2yzvZUKQtctn0QAPqu8tKdJ+OF5+Tv6NBq1U+wJWH+QI6OGy5EvQ==} + + '@deepseek-ai/dsh-agent@0.2.1-rc.3': + resolution: {integrity: sha512-S6x/deneAsd+pOgecRLM1PC1No9O472kHjS9pS57nuTXi2Vtdo9l7qF+q7PfiHRezL5dxv5gUBQMORPmIYDNvQ==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + '@deepseek-ai/dsh-typert-protocol': 0.2.1-rc.3 + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3 + '@deepseek-ai/dsh-workspace': 0.2.1-rc.3 + peerDependenciesMeta: + '@deepseek-ai/dsh-workspace': + optional: true + + '@deepseek-ai/dsh-brand@0.2.1-rc.3': + resolution: {integrity: sha512-bPpKuu05gZj7gdW15z6PL2dz4+A4MDEafgWOrhexFO7f08g1NeI4fhE4YNOxd8N2ua+tZJjsKCMAIobFMAaGOw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-client-locale@0.2.1-rc.3': + resolution: {integrity: sha512-/WpBT8gEivbD/yndgefYM09SysDcLcd8/Ov5zmC+A1EPNv6UoQ+4avPT6tkwT46XaG4XoJXmVglDOmfg/vUFGg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-client-ui-settings@0.2.1-rc.3': + resolution: {integrity: sha512-vBH1A1DU85yeqZ02VeaOCZd5z7Pr77Bq0pSBH6ehFus2iZ88n4LuEhZxwMIYHf55LrRRxOQCpIbtEjmSbN5jzw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-client-ui-sidebar-right@0.2.1-rc.3': + resolution: {integrity: sha512-BmBbGjHwP/q+DoNc0suvVTFlqcU0Bv0QGZJ67pfKNNkUjMtQtt77+r43vJHsSfDQIO+EzxoXUSfTdnTWxE42Bg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-client-ui-slots@0.2.1-rc.3': + resolution: {integrity: sha512-KV/f/yOm4YXSuDK2N0XtKNWqHZRxMbmZdtblVpx/D2s3mKoLHOdAxEyVp4F+lgjzuhUCGUovQHWjBcVhho5WuA==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-fs@0.2.1-rc.3': + resolution: {integrity: sha512-tENLWe471WlAXMc13J4cns8xU6lFyu1smwpkSKR85vhGr6FyWZhTlpVohZYm66LbwKTmSWiDhd9Urk7VxN9B9w==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3 + + '@deepseek-ai/dsh-host-webserver@0.2.1-rc.3': + resolution: {integrity: sha512-zLv507HZ20pDoICxRH9+XOFzjZ/cNcVm/fy3QXHDAqXJWcl4buFmGc2BaYZtaWkWoBZ1YHj2+Dx7Wy8Q3H5q/g==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-llm@0.2.1-rc.3': + resolution: {integrity: sha512-7Fq7zS3yQb1J1PsaNmahQ1gHDdsb338UhTkmZCexlNecmc5I44c/PbkHcT5pJ5SO4hnLplJOdDhiIMFpvvyAaw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-ptc-runtime@0.2.1-rc.3': + resolution: {integrity: sha512-nFUzb1abLvCQfUsrp/fMKQMCYU+O+ttiwqUFMa+uO4rFE6Nd+xNjus3V5aaqyy78jdciyBzzNysblZeryJAcXQ==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3 + + '@deepseek-ai/dsh-sandbox-policy@0.2.1-rc.3': + resolution: {integrity: sha512-/PlQEx/F6pwjjC/eOEBCHWG9InCu+aSEIC1k9V32noS43B/KS/FRSgP+SZ0YkbjMfk6iyS27sgglJDIY7RG1zQ==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + + '@deepseek-ai/dsh-sandbox@0.2.1-rc.3': + resolution: {integrity: sha512-7JXzEw2FBNAD3hNhiMzpxCjm8Zedc6DpFfsJfvh1Uh4HuIzX2BFEtzjvEUSwXGSWA+pCZOEvaYD9v0sZoMx3fQ==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + + '@deepseek-ai/dsh-scope@0.2.1-rc.3': + resolution: {integrity: sha512-3oCu1zZhbJTzV9TtYXjVUyxc9yOaQOYzxSGQvMuZ/q/O7/1Y1ofIS2j2GETfc79mCoiQIoQAjr2gu/ncXSgALw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-session-projection@0.2.1-rc.3': + resolution: {integrity: sha512-kyDxXb0avo0m4ZmAb8P+X6T/963NOZCvH/MgrWl3AUs5fHkXA6NfeVnalj488o5RpkRtZdqI7KtCEFNkyKAEsA==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + + '@deepseek-ai/dsh-session@0.2.1-rc.3': + resolution: {integrity: sha512-z1Dfn6yB2YMm9iNThPHaIYCx0Y/mKjm+fMrWFtnPZmX0fJXVmTIr4RAfLF7ZFJk6qd52SUl8d2uX+uNbrPJESg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + + '@deepseek-ai/dsh-system-prompt@0.2.1-rc.3': + resolution: {integrity: sha512-2CXnigUF0N2Ps0AG/lOvvY9qeEhvo5uUCGCqvoGrH9IWbhoh/tfvzo9KTa5svyZIBW6mLMAyLyHOdi7f1T9tfg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + + '@deepseek-ai/dsh-timeout@0.2.1-rc.3': + resolution: {integrity: sha512-DOuGjmY5dMlXqXqhuXlHNgEVajTLTYuj/EabS5b8IIBC5VN36YDOtyPgaT8aq1+LI7XoReDMUYQRUHCI3SOXqw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-tools@0.2.1-rc.3': + resolution: {integrity: sha512-fHmhIFaztPt9+uvOlk3p4wXMU62F+TRe0ozVPasV3seIsFcxpca74QGSK5dFHICDhKIY1T9MUh0F3itMTdMi3A==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-ptc-runtime': 0.2.1-rc.3 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3 + '@deepseek-ai/dsh-sandbox-policy': 0.2.1-rc.3 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + '@deepseek-ai/dsh-user-approval': 0.2.1-rc.3 + '@deepseek-ai/dsh-working-directory': 0.2.1-rc.3 + + '@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3': + resolution: {integrity: sha512-ycKq2jF0h/iE/gwQFXn7Fx/pdKsVnPe6rkaA8F0SIZ8QfbAK8KcYmpG1Kn9zjwZAWPyb6pLMhD2GI/gXlM7f0Q==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-user-approval@0.2.1-rc.3': + resolution: {integrity: sha512-n2AG2Oh3/32UNStxdkoTOYwheOjSjrJWPj9pPvgISw6vBURPUYrquoVD0AmvmV8TeWpxaCKIGsFNO08yrP9ODw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-scope': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + + '@deepseek-ai/dsh-util-crypto@0.2.1-rc.3': + resolution: {integrity: sha512-AKznKjQmc2JHDQO+DV2Z68zwGrr3+0qAkxNqZE3SnuBTpO7TeTaS7v2cOzQi81EhZUlYFArmKEbmjcsCrsQvvw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-util-values@0.2.1-rc.3': + resolution: {integrity: sha512-YyHu30xQBdp7sIr4ZNUliNxm2S9yRNOwdUPiBvfQZ+KaRtekI2j+T8+TFy7qgyBiGM7YYiG0xzJVibS894WIrg==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + + '@deepseek-ai/dsh-working-directory@0.2.1-rc.3': + resolution: {integrity: sha512-Ec/MG+j4jWu/4+ym9UieB2zHt22mwSFfS2s2xZfnoCQIrxkIH5ayVcY1SNttrmHFYDwsyZEG4YY2dzYRtcuIfw==} + peerDependencies: + '@deepseek-ai/cordis': ~4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3 + '@deepseek-ai/dsh-fs': 0.2.1-rc.3 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3 + '@deepseek-ai/dsh-session': 0.2.1-rc.3 + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3 + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3 + + '@deepseek-ai/schemastery@3.18.5': + resolution: {integrity: sha512-Mnobvqf9rHsZYv4g5edj5ddxS1oF1kIdSlz0DunUgnY3LWG5F26MqvH3YOOsSaodCgyzJ16OMN9O99/s5Crtdw==} + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@quansync/fs@1.1.0': + resolution: {integrity: sha512-qAPG/t3HqML1TlN7sY/pTbEjzFVAKsMjNNMGheyDosro+kT4iw2KCUoHcVdmliwWjorm4elZbgNQyU2eD97eDg==} + + '@rolldown/binding-android-arm-eabi@1.2.16': + resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.16': + resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@types/node@22.20.5': + resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} + + '@types/prop-types@15.7.15': + resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==} + + '@types/react@18.3.31': + resolution: {integrity: sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==} + + '@yuku-codegen/binding-android-arm64@0.8.7': + resolution: {integrity: sha512-C/0zV5IhgVdYhGJTwrY0v8dknxlhiKwtVJkMUaexu9/QvRmzlV4vfU3hZlUSgqc2BxQHntL1mCVbDq8j0FRFDw==} + cpu: [arm64] + os: [android] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-darwin-arm64@0.8.7': + resolution: {integrity: sha512-/u+REDMI4a0/lsJXTM4c53/w31OGZLOReZIyg62uhgLs0kc8NHsj/nOcxTdlQjq5gi0zhdkccD9LaLTXcdzPvw==} + cpu: [arm64] + os: [darwin] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-darwin-x64@0.8.7': + resolution: {integrity: sha512-sMMzFOwCo4WXR+/6zIBThOocSC50iIIZZdfiIDbaLvj0Ax/rWt/iavyfEAqajyvzydLyCqR/ZItdLWSRlu1umw==} + cpu: [x64] + os: [darwin] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-freebsd-x64@0.8.7': + resolution: {integrity: sha512-MpdpKXix9P+Y1rKgjvcNeNtGjXeL1CmttNhYINrWls8kRpm4xM/oBGTmn6w7to8lAlwj5jm8q03dQPl5mRv4Qw==} + cpu: [x64] + os: [freebsd] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-arm-gnu@0.8.7': + resolution: {integrity: sha512-rr1srFLlPAmC1vtxfc9C1YLDe3iH09YjfSeeIidBqKhzx1MATjOAq4mjlRUOnhr/L27MotWIYOFKwVsd5JZFOg==} + cpu: [arm] + os: [linux] + libc: [glibc] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-arm-musl@0.8.7': + resolution: {integrity: sha512-eAufXh8qBRpiSO6ueaMDL+yyoXIGLhpUce72YbcACtZU2qhExwBIJyEtQf5kH2Ki0X2aqkSjSfog4OPtKXan3Q==} + cpu: [arm] + os: [linux] + libc: [musl] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-arm64-gnu@0.8.7': + resolution: {integrity: sha512-gw4w6wPoHObBrdIC4duVWLmJOvpdE25j5D7yrM5mACNlK4klRz/lv8hK+ssQk9EJHBgZjSaqZIJVFgqNYbfv7A==} + cpu: [arm64] + os: [linux] + libc: [glibc] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-arm64-musl@0.8.7': + resolution: {integrity: sha512-L68N6Y4XkqcIaKo3Ra88JEvBEH4AHff44A4INcrxeVWZ8CZtu2tCpfVxe3hR8qQQMcvBSQlDn24KpkCKEhVvfA==} + cpu: [arm64] + os: [linux] + libc: [musl] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-x64-gnu@0.8.7': + resolution: {integrity: sha512-dzyAbltJmf3Cqlb8HcFuYIf5Yn0fl1vTr3XJ9HiVNNvOlhqPSArOqtw9vI1p6/VTXTjrMLXlU+s+/kNHiIy/Cw==} + cpu: [x64] + os: [linux] + libc: [glibc] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-linux-x64-musl@0.8.7': + resolution: {integrity: sha512-Otw4MH3404q0Bbvl+YTdW9aoUV5vXmUw8260bWvt1XlaoIX/ceSgI4ygheRDMfBPoHt6FDayQaO9OLVUZAgkFA==} + cpu: [x64] + os: [linux] + libc: [musl] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-win32-arm64@0.8.7': + resolution: {integrity: sha512-qo/jyrzryiBuKEsFiuWaBCBe3tRMynQ0qFWFgOEjcCMQeZfBm+wKiVEUEFXXLc7bh8YezguAWp0Mtnhq4ARNyA==} + cpu: [arm64] + os: [win32] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-codegen/binding-win32-x64@0.8.7': + resolution: {integrity: sha512-D5lDsVDx6m00E6bWySlWdH72Ca4TPSaphDqB6QjU6MpuNLIJqoGoatYyq2rOmBE8Zv/kunot/o58KGL03P3eiA==} + cpu: [x64] + os: [win32] + deprecated: yuku-codegen is pure JavaScript since 0.14 + + '@yuku-parser/binding-android-arm64@0.8.7': + resolution: {integrity: sha512-eGKYiUDX7Y0V7tDTmg+JTVnXnjMqfXXsorZ+EDf5kxwchQ3Or1HS14MzI2fw+jFhHR85fCWt+mtX33Yao73hIQ==} + cpu: [arm64] + os: [android] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-darwin-arm64@0.8.7': + resolution: {integrity: sha512-Re0RHelKLnjEURulY2/KxW+Ngb8zuNA4BRZuMwgGQNzVumT6u4U2N2hc01oeYVNVof0i7GrXE4UCNBgbpRRnjQ==} + cpu: [arm64] + os: [darwin] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-darwin-x64@0.8.7': + resolution: {integrity: sha512-Hn8DROtQkjlA1ACbPgj4a7eP9IuVOI504oiTwpkWPbpaDWD9KdmnVYCqW+1LfenNK/g7O9NhWGpXEdaCNX7lIA==} + cpu: [x64] + os: [darwin] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-freebsd-x64@0.8.7': + resolution: {integrity: sha512-bAP2OV8wRuzplX/jYxv9+vvqQT8JxyNphI8fLfXGL054Xs+4/J5u33cIm3y4rxY8rdoLmmdiJs2Tq7r7lrDRfA==} + cpu: [x64] + os: [freebsd] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-arm-gnu@0.8.7': + resolution: {integrity: sha512-kTYwJQQgmZeAWdDIWabiReIZMpmfLueIj1tCmjStUtFGhR1Z0qwxonKVfUC4N7h/VhGGzLZ//7O1kgt1QKqgCg==} + cpu: [arm] + os: [linux] + libc: [glibc] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-arm-musl@0.8.7': + resolution: {integrity: sha512-uL4jE8HPT2BLlxAXyD10LqgPuXa9eDa0BKpCdSANmzIJghq/2eZo3/gQNtaxPZMupWoxjYzSad9IXrwu7aYPXQ==} + cpu: [arm] + os: [linux] + libc: [musl] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-arm64-gnu@0.8.7': + resolution: {integrity: sha512-3gVN4pWSKZmXiNX7cU164dR9MPvesCHnlH6nPfpK+yQsCuYphjKKplcb4SnZBrhiqmXbgb2HR0c2TS0IZUPhgA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-arm64-musl@0.8.7': + resolution: {integrity: sha512-S0mwfEjoLpxzXeZw802Wa4RaELsQiPtWqG6INcy8j4GtvNFtl4LCX3eGO1XLn9pyLAISLzTRyU3zUCBUPin8lg==} + cpu: [arm64] + os: [linux] + libc: [musl] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-x64-gnu@0.8.7': + resolution: {integrity: sha512-lnbWdPmerE5D1uH1G4IEZKnPzCrWCStRGrtgpSIe1RibAo5bZIjDbbbPYXmMHCEh4F+x/JaJpElh26a3r+BPbg==} + cpu: [x64] + os: [linux] + libc: [glibc] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-linux-x64-musl@0.8.7': + resolution: {integrity: sha512-769uwndMvMzUvATWbAcEvyLHKA+DzhHSCl/obBUrRdYfRo26yxui6S8y3z7uJ+Naup7UKrDxrpK7OnQkxkl9KQ==} + cpu: [x64] + os: [linux] + libc: [musl] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-win32-arm64@0.8.7': + resolution: {integrity: sha512-mEB/9PlaAkisJ6KWGz0zvywXoU6+80dTlR2LwS7s/jcXXoU6fm2+sitBZXtqu3+Q4DcDgPxM45uWMCzPs0TSRw==} + cpu: [arm64] + os: [win32] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-parser/binding-win32-x64@0.8.7': + resolution: {integrity: sha512-8vNB2DP0ou61nGb8tc/qfi41gfyDXz1MHr2zqL3nR+cJ6CEbiuWV/l/a/vv151gCgiZLLAyGkQGENpozdg716w==} + cpu: [x64] + os: [win32] + deprecated: yuku-parser runs on yuku-core since 0.14 + + '@yuku-toolchain/types@0.8.7': + resolution: {integrity: sha512-2Z53dNxAJL6UvFoIrDZvYf3zlO8s4VJK4O2hhaB4mXVwwpX/7ajtss3cmfqKvamlNLWyt9FSWs4eoYdlbxpnHA==} + + ansis@4.4.0: + resolution: {integrity: sha512-9k3v7xcHwgdO/DruxGIg4HtjvlAZlcnsX/mzqUb1t3NkYnl9kK2UJ+Gq0io+vQf7iT//BD/HB/NBkUR1LWxoeA==} + engines: {node: '>=14'} + + bytes@3.1.2: + resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} + engines: {node: '>= 0.8'} + + cac@7.1.0: + resolution: {integrity: sha512-LMDU/U2yA4IPIY8KT0NsNPWEYZvAMkbgyspxJ6btJaYV+WMDOHAZCmB0lsTObiHaRS1V/ztKAl7+TSkTqXyeoA==} + engines: {node: '>=20.19.0'} + + compressible@2.0.18: + resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==} + engines: {node: '>= 0.6'} + + compression@1.8.2: + resolution: {integrity: sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==} + engines: {node: '>= 0.8.0'} + + content-type@2.1.0: + resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} + engines: {node: '>=18'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + debug@2.6.9: + resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + defu@6.1.7: + resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} + + destroy@1.2.0: + resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==} + engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + + dts-resolver@3.0.0: + resolution: {integrity: sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q==} + engines: {node: ^22.18.0 || >=24.0.0} + peerDependencies: + oxc-resolver: '>=11.0.0' + peerDependenciesMeta: + oxc-resolver: + optional: true + + empathic@2.1.0: + resolution: {integrity: sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==} + engines: {node: '>=14'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + get-tsconfig@5.0.0-beta.5: + resolution: {integrity: sha512-/6gFNr0N04nob252sTQxyFLi3eKFRqIg1I87YcqAMT1i6SQrSF6KujUEQrtrjMV0H/eejTCltLdDSTEMzHbnsQ==} + engines: {node: '>=20.20.0'} + + hookable@6.1.2: + resolution: {integrity: sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg==} + + import-without-cache@0.4.1: + resolution: {integrity: sha512-vXoV9PjKHEednCUu01e98TkImxy67e3BJXbTIOmIq4Hyzw3IAwYRcuPkfeTzJzwyyts4kjuA73x+pWJLc4f86A==} + engines: {node: ^22.18.0 || >=24.0.0} + + ipaddr.js@2.5.0: + resolution: {integrity: sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==} + engines: {node: '>= 10'} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + loose-envify@1.4.0: + resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} + hasBin: true + + mime-db@1.54.0: + resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} + engines: {node: '>= 0.6'} + + ms@2.0.0: + resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==} + + negotiator@0.6.4: + resolution: {integrity: sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==} + engines: {node: '>= 0.6'} + + negotiator@1.1.0: + resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} + engines: {node: '>=18'} + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + on-headers@1.1.0: + resolution: {integrity: sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==} + engines: {node: '>= 0.8'} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + quansync@1.0.0: + resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==} + + react@18.3.1: + resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==} + engines: {node: '>=0.10.0'} + + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + + rolldown-plugin-dts@0.27.14: + resolution: {integrity: sha512-ZvuDDwoIpRK9RPxDXratCpklFO9QZZWndf/sd0VBFb4LEj0jj07UcHK9OCh7V4XiFz2Z89ziyBC2K6tJiDjrbw==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@typescript/native-preview': '*' + '@volar/typescript': ~2.4.0 + rolldown: ^1.0.0 + typescript: ^5.0.0 || ^6.0.0 || ~7.0.0 + vue-tsc: ~3.2.0 || ~3.3.0 + peerDependenciesMeta: + '@typescript/native-preview': + optional: true + '@volar/typescript': + optional: true + typescript: + optional: true + vue-tsc: + optional: true + + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + + tsdown@0.22.14: + resolution: {integrity: sha512-ule7Y+fsAN2iZbLDoo7C4KYljFJNJJ+fLshyn+9gozeTspVersWHxwdGB+Dm2hzA38s6muFnUTl0jK3vJm9ifQ==} + engines: {node: ^22.18.0 || >=24.11.0} + hasBin: true + peerDependencies: + '@arethetypeswrong/core': ^0.18.1 + '@tsdown/css': 0.22.14 + '@tsdown/exe': 0.22.14 + '@vitejs/devtools': '*' + publint: ^0.3.8 + tsx: '*' + typescript: ^5.0.0 || ^6.0.0 || ^7.0.0 + unplugin-unused: ^0.5.0 + unrun: '*' + peerDependenciesMeta: + '@arethetypeswrong/core': + optional: true + '@tsdown/css': + optional: true + '@tsdown/exe': + optional: true + '@vitejs/devtools': + optional: true + publint: + optional: true + tsx: + optional: true + typescript: + optional: true + unplugin-unused: + optional: true + unrun: + optional: true + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + unconfig-core@7.5.0: + resolution: {integrity: sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w==} + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + vary@1.1.2: + resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} + engines: {node: '>= 0.8'} + + verkit@0.3.2: + resolution: {integrity: sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg==} + engines: {node: '>=18.12.0'} + + yuku-ast@0.8.7: + resolution: {integrity: sha512-h6+4bDfyootiMB9vckk5uKo5r5j0GHrkr17FQTDNfEsFT3DWlN9uu1HJwQwc64pgmLCI945fWM3lbTIqxjT3GQ==} + + yuku-codegen@0.8.7: + resolution: {integrity: sha512-adwDZSh8oVDzhE6Du9PwVWxcOxeV0e2EVhUuMKWfhSY4wkrDq9eqixlxFF3l/XGUV1E7UFzhpz9393MUumkyNw==} + + yuku-parser@0.8.7: + resolution: {integrity: sha512-vRD9nwt4L3aYpxNqeSC4WqLv58xrXef0Ong1Mc45CTXTIpvLafx7JO05sczmQZwdLEZvywrLOGdNC5+Rp5N1BQ==} + + zod@4.4.3: + resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} + + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + +snapshots: + + '@deepseek-ai/cordis@4.0.5': + dependencies: + '@deepseek-ai/cosmokit': 1.8.6 + '@standard-schema/spec': 1.1.0 + + '@deepseek-ai/cosmokit@1.8.6': {} + + '@deepseek-ai/dsh-agent@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-typert-protocol': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + + '@deepseek-ai/dsh-brand@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-client-locale@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-client-ui-settings@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-client-ui-sidebar-right@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-client-ui-slots@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-fs@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-brand@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + + '@deepseek-ai/dsh-host-webserver@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/schemastery': 3.18.5 + compression: 1.8.2 + ipaddr.js: 2.5.0 + negotiator: 1.1.0 + transitivePeerDependencies: + - supports-color + + '@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-timeout': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-typert-protocol': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-util-crypto': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/schemastery': 3.18.5 + zod: 4.4.3 + + '@deepseek-ai/dsh-ptc-runtime@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + + '@deepseek-ai/dsh-sandbox-policy@0.2.1-rc.3(1809d3b5f9b8552c21c008788fe3c75e)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/schemastery': 3.18.5 + zod: 4.4.3 + + '@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + + '@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + zod: 4.4.3 + + '@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + + '@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-timeout@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-tools@0.2.1-rc.3(1f5d0a9b849aaa1244bc4f2e453f609a)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-ptc-runtime': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))) + '@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-sandbox-policy': 0.2.1-rc.3(1809d3b5f9b8552c21c008788fe3c75e) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-user-approval': 0.2.1-rc.3(f3a61cdc614c420235807a61121b4b4a) + '@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-working-directory': 0.2.1-rc.3(b3db524bc35e44edbf239e3bbf3fca0a) + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + zod: 4.6.7 + + '@deepseek-ai/dsh-user-approval@0.2.1-rc.3(f3a61cdc614c420235807a61121b4b4a)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/schemastery': 3.18.5 + + '@deepseek-ai/dsh-util-crypto@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + + '@deepseek-ai/dsh-working-directory@0.2.1-rc.3(b3db524bc35e44edbf239e3bbf3fca0a)': + dependencies: + '@deepseek-ai/cordis': 4.0.5 + '@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-fs': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-brand@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))) + '@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5) + '@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/dsh-session-projection': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))) + '@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)) + '@deepseek-ai/schemastery': 3.18.5 + zod: 4.6.7 + + '@deepseek-ai/schemastery@3.18.5': + dependencies: + '@deepseek-ai/cosmokit': 1.8.6 + '@standard-schema/spec': 1.1.0 + + '@oxc-project/types@0.156.0': {} + + '@quansync/fs@1.1.0': + dependencies: + quansync: 1.0.0 + + '@rolldown/binding-android-arm-eabi@1.2.16': + optional: true + + '@rolldown/binding-android-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-x64@1.2.16': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.16': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.16': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.16': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.16': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.16': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@standard-schema/spec@1.1.0': {} + + '@types/node@22.20.5': + dependencies: + undici-types: 6.21.0 + + '@types/prop-types@15.7.15': {} + + '@types/react@18.3.31': + dependencies: + '@types/prop-types': 15.7.15 + csstype: 3.2.3 + + '@yuku-codegen/binding-android-arm64@0.8.7': + optional: true + + '@yuku-codegen/binding-darwin-arm64@0.8.7': + optional: true + + '@yuku-codegen/binding-darwin-x64@0.8.7': + optional: true + + '@yuku-codegen/binding-freebsd-x64@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-arm-gnu@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-arm-musl@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-arm64-gnu@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-arm64-musl@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-x64-gnu@0.8.7': + optional: true + + '@yuku-codegen/binding-linux-x64-musl@0.8.7': + optional: true + + '@yuku-codegen/binding-win32-arm64@0.8.7': + optional: true + + '@yuku-codegen/binding-win32-x64@0.8.7': + optional: true + + '@yuku-parser/binding-android-arm64@0.8.7': + optional: true + + '@yuku-parser/binding-darwin-arm64@0.8.7': + optional: true + + '@yuku-parser/binding-darwin-x64@0.8.7': + optional: true + + '@yuku-parser/binding-freebsd-x64@0.8.7': + optional: true + + '@yuku-parser/binding-linux-arm-gnu@0.8.7': + optional: true + + '@yuku-parser/binding-linux-arm-musl@0.8.7': + optional: true + + '@yuku-parser/binding-linux-arm64-gnu@0.8.7': + optional: true + + '@yuku-parser/binding-linux-arm64-musl@0.8.7': + optional: true + + '@yuku-parser/binding-linux-x64-gnu@0.8.7': + optional: true + + '@yuku-parser/binding-linux-x64-musl@0.8.7': + optional: true + + '@yuku-parser/binding-win32-arm64@0.8.7': + optional: true + + '@yuku-parser/binding-win32-x64@0.8.7': + optional: true + + '@yuku-toolchain/types@0.8.7': {} + + ansis@4.4.0: {} + + bytes@3.1.2: {} + + cac@7.1.0: {} + + compressible@2.0.18: + dependencies: + mime-db: 1.54.0 + + compression@1.8.2: + dependencies: + bytes: 3.1.2 + compressible: 2.0.18 + debug: 2.6.9 + destroy: 1.2.0 + negotiator: 0.6.4 + on-headers: 1.1.0 + safe-buffer: 5.2.1 + vary: 1.1.2 + transitivePeerDependencies: + - supports-color + + content-type@2.1.0: {} + + csstype@3.2.3: {} + + debug@2.6.9: + dependencies: + ms: 2.0.0 + + defu@6.1.7: {} + + destroy@1.2.0: {} + + dts-resolver@3.0.0: {} + + empathic@2.1.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + get-tsconfig@5.0.0-beta.5: + dependencies: + resolve-pkg-maps: 1.0.0 + + hookable@6.1.2: {} + + import-without-cache@0.4.1: {} + + ipaddr.js@2.5.0: {} + + js-tokens@4.0.0: {} + + loose-envify@1.4.0: + dependencies: + js-tokens: 4.0.0 + + mime-db@1.54.0: {} + + ms@2.0.0: {} + + negotiator@0.6.4: {} + + negotiator@1.1.0: + dependencies: + content-type: 2.1.0 + + obug@2.2.1: {} + + on-headers@1.1.0: {} + + picomatch@4.0.7: {} + + quansync@1.0.0: {} + + react@18.3.1: + dependencies: + loose-envify: 1.4.0 + + resolve-pkg-maps@1.0.0: {} + + rolldown-plugin-dts@0.27.14(rolldown@1.2.16)(typescript@5.9.3): + dependencies: + dts-resolver: 3.0.0 + get-tsconfig: 5.0.0-beta.5 + obug: 2.2.1 + rolldown: 1.2.16 + yuku-ast: 0.8.7 + yuku-codegen: 0.8.7 + yuku-parser: 0.8.7 + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - oxc-resolver + + rolldown@1.2.16: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.16 + '@rolldown/binding-android-arm64': 1.2.16 + '@rolldown/binding-darwin-arm64': 1.2.16 + '@rolldown/binding-darwin-x64': 1.2.16 + '@rolldown/binding-freebsd-x64': 1.2.16 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.16 + '@rolldown/binding-linux-arm64-gnu': 1.2.16 + '@rolldown/binding-linux-arm64-musl': 1.2.16 + '@rolldown/binding-linux-ppc64-gnu': 1.2.16 + '@rolldown/binding-linux-s390x-gnu': 1.2.16 + '@rolldown/binding-linux-x64-gnu': 1.2.16 + '@rolldown/binding-linux-x64-musl': 1.2.16 + '@rolldown/binding-openharmony-arm64': 1.2.16 + '@rolldown/binding-win32-arm64-msvc': 1.2.16 + '@rolldown/binding-win32-x64-msvc': 1.2.16 + + safe-buffer@5.2.1: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tree-kill@1.2.2: {} + + tsdown@0.22.14(typescript@5.9.3): + dependencies: + ansis: 4.4.0 + cac: 7.1.0 + defu: 6.1.7 + empathic: 2.1.0 + hookable: 6.1.2 + import-without-cache: 0.4.1 + obug: 2.2.1 + picomatch: 4.0.7 + rolldown: 1.2.16 + rolldown-plugin-dts: 0.27.14(rolldown@1.2.16)(typescript@5.9.3) + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + tree-kill: 1.2.2 + unconfig-core: 7.5.0 + verkit: 0.3.2 + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - '@typescript/native-preview' + - '@volar/typescript' + - oxc-resolver + - vue-tsc + + typescript@5.9.3: {} + + unconfig-core@7.5.0: + dependencies: + '@quansync/fs': 1.1.0 + quansync: 1.0.0 + + undici-types@6.21.0: {} + + vary@1.1.2: {} + + verkit@0.3.2: {} + + yuku-ast@0.8.7: + dependencies: + '@yuku-toolchain/types': 0.8.7 + + yuku-codegen@0.8.7: + dependencies: + '@yuku-toolchain/types': 0.8.7 + optionalDependencies: + '@yuku-codegen/binding-android-arm64': 0.8.7 + '@yuku-codegen/binding-darwin-arm64': 0.8.7 + '@yuku-codegen/binding-darwin-x64': 0.8.7 + '@yuku-codegen/binding-freebsd-x64': 0.8.7 + '@yuku-codegen/binding-linux-arm-gnu': 0.8.7 + '@yuku-codegen/binding-linux-arm-musl': 0.8.7 + '@yuku-codegen/binding-linux-arm64-gnu': 0.8.7 + '@yuku-codegen/binding-linux-arm64-musl': 0.8.7 + '@yuku-codegen/binding-linux-x64-gnu': 0.8.7 + '@yuku-codegen/binding-linux-x64-musl': 0.8.7 + '@yuku-codegen/binding-win32-arm64': 0.8.7 + '@yuku-codegen/binding-win32-x64': 0.8.7 + + yuku-parser@0.8.7: + dependencies: + '@yuku-toolchain/types': 0.8.7 + yuku-ast: 0.8.7 + optionalDependencies: + '@yuku-parser/binding-android-arm64': 0.8.7 + '@yuku-parser/binding-darwin-arm64': 0.8.7 + '@yuku-parser/binding-darwin-x64': 0.8.7 + '@yuku-parser/binding-freebsd-x64': 0.8.7 + '@yuku-parser/binding-linux-arm-gnu': 0.8.7 + '@yuku-parser/binding-linux-arm-musl': 0.8.7 + '@yuku-parser/binding-linux-arm64-gnu': 0.8.7 + '@yuku-parser/binding-linux-arm64-musl': 0.8.7 + '@yuku-parser/binding-linux-x64-gnu': 0.8.7 + '@yuku-parser/binding-linux-x64-musl': 0.8.7 + '@yuku-parser/binding-win32-arm64': 0.8.7 + '@yuku-parser/binding-win32-x64': 0.8.7 + + zod@4.4.3: {} + + zod@4.6.7: {} diff --git a/scripts/pack-guard.mjs b/scripts/pack-guard.mjs new file mode 100644 index 0000000..56c04c5 --- /dev/null +++ b/scripts/pack-guard.mjs @@ -0,0 +1,142 @@ +#!/usr/bin/env node +/** + * pack-guard: 发布前白名单 + 脱敏闸门。 + * + * 在 `pnpm publish` 之前运行(已接进 `prepublishOnly`):按 package.json 的 + * `files` 白名单解析出「真正会被打进 tarball 的文件」,然后 + * 1) 文件名黑名单:AGENTS.md / TODO.md / HANDOFF.md / PLAN.md / *.mjs / tsconfig* / pnpm-lock.yaml … + * 2) 内容黑名单:个人域名、本机路径、用户名、令牌形状(cmt_… / _authToken)。 + * 任一条不满足就以 exit 1 中止发布。 + * + * 纯 fs 实现:不 spawn 子进程,不读网络,不写任何文件。 + */ +import { readdirSync, readFileSync, statSync } from 'node:fs' +import { join, relative, sep } from 'node:path' + +const ROOT = process.cwd() +const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) + +/** 任何情况下都必须出现在包里的文件(npm 的 always-include 子集)。 */ +const ALWAYS = ['package.json', 'README.md', 'LICENSE', 'LICENCE'] + +/** 文件名黑名单:笔记、规划、构建配置、探测脚本一律不进包。 */ +const BANNED_NAMES = [ + /^AGENTS?\.md$/i, + /^TODO\.md$/i, + /^TASKS\.md$/i, + /^HANDOFF\.md$/i, + /^NOTES?\.md$/i, + /PLAN\.md$/i, + /\.mjs$/i, + /^tsconfig.*\.json$/i, + /^pnpm-lock\.yaml$/i, + /^package-lock\.json$/i, + /^\.npmrc$/i, + /^\.env(\.|$)/i, + /\.tgz$/i, + /\.log$/i, +] + +/** 内容黑名单:一旦命中就说明有东西会随包外发。 */ +const BANNED_CONTENT = [ + [/mem\.qyhhh\.top/i, '个人域名 mem.qyhhh.top'], + [/qyh15/i, '本机用户名 qyh15'], + [/C:[\\/]Users[\\/](?!)(?!%USERPROFILE%)/i, '本机绝对路径 C:\\Users\\…'], + [/cmt_[A-Za-z0-9_-]{16,}/, '疑似活动令牌原文 cmt_…'], + [/_authToken/i, 'npm 凭据字段 _authToken'], +] + +const TEXT_EXT = /\.(json|md|js|mjs|cjs|ts|tsx|yml|yaml|css|html|txt)$/i +const SKIP_DIRS = new Set(['node_modules', '.git', '.pnpm-store', '.pnpm-cache']) + +function walk(entry, out) { + const abs = join(ROOT, entry) + let st + try { + st = statSync(abs) + } catch { + return + } + if (st.isDirectory()) { + for (const name of readdirSync(abs)) { + if (SKIP_DIRS.has(name)) continue + walk(join(entry, name), out) + } + return + } + out.push(entry) +} + +/** 真正会进包的文件 = files 白名单展开 + always-include。 */ +const files = new Set() +const collected = [] +for (const entry of pkg.files ?? []) walk(entry.replace(/^\.\//, ''), collected) +for (const f of collected) files.add(f) +for (const f of ALWAYS) { + try { + if (statSync(join(ROOT, f)).isFile()) files.add(f) + } catch { + /* 不存在就算了 */ + } +} + +const problems = [] +for (const file of [...files].sort()) { + const rel = relative(ROOT, join(ROOT, file)).split(sep).join('/') + const base = rel.split('/').pop() + for (const re of BANNED_NAMES) { + if (re.test(base)) problems.push(`文件名命中黑名单 ${re} → ${rel}`) + } + if (!TEXT_EXT.test(rel)) continue + const text = readFileSync(join(ROOT, rel), 'utf8') + for (const [re, label] of BANNED_CONTENT) { + const m = text.match(re) + if (m) { + const line = text.slice(0, m.index).split('\n').length + problems.push(`${rel}:${line} 命中「${label}」→ ${m[0].slice(0, 60)}`) + } + } +} + +const kb = ([...files].reduce((n, f) => n + statSync(join(ROOT, f)).size, 0) / 1024).toFixed(1) +console.log(`pack-guard: ${files.size} 个文件将被发布,共 ${kb} KB`) +for (const f of [...files].sort()) console.log(` · ${f}`) + +/** 信息项:目录里存在、但不进包的笔记与工程文件 —— 明确告知「已排除」,免得不放心。 */ +const NOTEISH = [ + /^AGENTS?\.md$/i, + /^TODO\.md$/i, + /^TASKS\.md$/i, + /^HANDOFF\.md$/i, + /^NOTES?\.md$/i, + /PLAN\.md$/i, + /\.mjs$/i, + /^tsconfig.*\.json$/i, + /^pnpm-lock\.yaml$/i, +] +const excluded = [] +;(function scan(dir) { + for (const name of readdirSync(dir)) { + if (SKIP_DIRS.has(name)) continue + const abs = join(dir, name) + const rel = relative(ROOT, abs).split(sep).join('/') + if (statSync(abs).isDirectory()) { + scan(abs) + continue + } + if (files.has(rel)) continue + if (NOTEISH.some((re) => re.test(name))) excluded.push(rel) + } +})(ROOT) + +if (excluded.length) { + console.log(`\npack-guard: 以下 ${excluded.length} 个文件在目录里,但不会进包(笔记/工程文件,已排除):`) + for (const f of excluded.sort()) console.log(` – ${f}`) +} + +if (problems.length) { + console.error(`\npack-guard: 发现 ${problems.length} 处不该外发的内容,已中止发布:`) + for (const p of problems) console.error(` ✗ ${p}`) + process.exit(1) +} +console.log('\npack-guard: 白名单与脱敏检查通过') diff --git a/scripts/release-prep.mjs b/scripts/release-prep.mjs new file mode 100644 index 0000000..94a8412 --- /dev/null +++ b/scripts/release-prep.mjs @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/** + * release-prep: 发布前一次性整备(脱敏 + package.json 元数据 + LICENSE)。 + * + * node scripts/release-prep.mjs --dry-run 只报告将要改什么 + * node scripts/release-prep.mjs 原地写入 + * + * 幂等:重复执行不会有二次改动。必须在插件目录(含 package.json 那一层)执行。 + * 用 Node 而不是 PowerShell,避开发行策略限制,并且能把 package.json 写成无 BOM 的 UTF-8。 + */ +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { join, dirname } from 'node:path' +import { fileURLToPath } from 'node:url' + +const ROOT = dirname(dirname(fileURLToPath(import.meta.url))) +const DRY = process.argv.includes('--dry-run') +const pkgPath = join(ROOT, 'package.json') + +if (!existsSync(pkgPath)) throw new Error(`没有找到 ${pkgPath} —— 请在 dsh-plugin 目录里执行。`) +const changes = [] +const write = (path, text, why) => { + changes.push(`${why} → ${path.slice(ROOT.length + 1)}`) + if (!DRY) writeFileSync(path, text, 'utf8') +} + +/** 1. 脱敏:个人域名与本机路径。src 也要改,否则下次构建会把域名写回 lib。 */ +const REDACTIONS = [ + ['https://mem.qyhhh.top/api/longmemory', 'https://your-memory-host/api/longmemory', '替换个人域名'], + ['C:\\Users\\qyh15\\云端记忆系统\\dsh-plugin', 'D:\\path\\to\\dsh-plugin', '抹掉本机安装路径'], + ['C:/Users/qyh15/云端记忆系统/dsh-plugin', 'D:/path/to/dsh-plugin', '抹掉 link 里的本机路径'], + ['C:\\Users\\qyh15\\.dsh\\cloud-memory.json', '%USERPROFILE%\\.dsh\\cloud-memory.json', '抹掉令牌文件路径'], +] +for (const rel of ['cordis.patch.yml', 'README.md', 'lib/config.js', 'lib/page.js', 'src/config.ts', 'src/page.ts']) { + const path = join(ROOT, rel) + if (!existsSync(path)) continue + let text = readFileSync(path, 'utf8') + let touched = false + for (const [from, to, why] of REDACTIONS) { + if (!text.includes(from)) continue + text = text.split(from).join(to) + touched = true + changes.push(`${why} → ${rel}`) + } + if (touched && !DRY) writeFileSync(path, text, 'utf8') +} + +/** 2. package.json 元数据。 */ +const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) +const before = JSON.stringify(pkg) +const add = [] +if (pkg.name !== 'dsh-cloud-memory') throw new Error(`package.json 的 name 是 ${pkg.name},疑似跑错目录,已中止。`) + +if ('private' in pkg) { + delete pkg.private + add.push('去掉 private:true(npm 会直接拒绝发布)') +} +if (!pkg.publishConfig) { + pkg.publishConfig = { registry: 'https://registry.npmjs.org/', access: 'public' } + add.push('加 publishConfig(registry + access public)') +} +if (!pkg.keywords) { + pkg.keywords = ['dsh', 'dsh-plugin', 'memory', 'cloud-memory', 'longmemory', 'agent'] + add.push('加 keywords') +} +if (!pkg.author) { + pkg.author = 'dsh-cloud-memory contributors' + add.push('加 author(中性署名,可换成你自己的名字与邮箱)') +} +pkg.scripts ??= {} +if (pkg.scripts.prepack !== 'tsc -p tsconfig.build.json') { + pkg.scripts.prepack = 'tsc -p tsconfig.build.json' + add.push('加 prepack 构建(保证 lib/ 与 src/ 同步)') +} +if (pkg.scripts.prepublishOnly !== 'node scripts/pack-guard.mjs') { + pkg.scripts.prepublishOnly = 'node scripts/pack-guard.mjs' + add.push('加 prepublishOnly 闸门(笔记/探测脚本/个人信息一律拦下)') +} +pkg.files ??= [] +if (!pkg.files.includes('LICENSE')) { + pkg.files.push('LICENSE') + add.push('files 增加 LICENSE') +} +if (JSON.stringify(pkg) !== before) { + write(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`, 'package.json 更新') + changes.push(...add) +} + +/** 3. LICENSE。 */ +const licensePath = join(ROOT, 'LICENSE') +if (!existsSync(licensePath)) { + write( + licensePath, + `MIT License + +Copyright (c) 2026 dsh-cloud-memory contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +`, + '新建 MIT LICENSE', + ) +} + +/** 4. 报告。 */ +if (!changes.length) { + console.log('release-prep: 没有需要改动的内容 —— 已是发布就绪状态。') +} else { + console.log(`release-prep: ${DRY ? '将改动' : '已改动'} ${changes.length} 项`) + for (const c of changes) console.log(` · ${c}`) +} +console.log('\n下一步:pnpm run build → node scripts/pack-guard.mjs → pnpm login → pnpm publish --access public --no-git-checks') +console.log('注意:发布不可撤销,0.1.0 一旦发布就不能再改同号。') diff --git a/src/api.ts b/src/api.ts new file mode 100644 index 0000000..537985f --- /dev/null +++ b/src/api.ts @@ -0,0 +1,376 @@ +/** + * Thin client for the LongMemory cloud API (`/api/longmemory`). + * + * - Every call carries `Authorization: Bearer `; the owner is injected + * server-side, so no request ever names a user. + * - Errors normalize to `{ status, code, message }`; a network failure is + * status 0 with code `network_error`, so callers can retry safely. + * - Only metadata ever leaves this process: turn ids, timestamps, statuses, and + * the memory content the user explicitly asked to save. + */ +import type { TurnStatus } from './reporter.ts' + +/** Normalized non-2xx outcome. */ +export interface CloudError { + /** HTTP status, or 0 for a transport failure. */ + status: number + /** Machine-readable code from the service, or a local fallback. */ + code: string + /** Human-readable message (already safe to show: never contains secrets). */ + message: string + /** Milliseconds the service asked us to wait (429 handling). */ + retryAfterMs?: number +} + +/** One request outcome. */ +export type CloudResult = { ok: true; status: number; data: T } | { ok: false; error: CloudError } + +/** Activity turn payload — exactly the six fields the service accepts. */ +export interface TurnPayload { + client_id: string + conversation_id: string + turn_id: string + status: TurnStatus + started_at: number + completed_at: number +} + +/** Activity turn outcome. */ +export interface TurnAck { + recorded?: boolean + duplicate?: boolean +} + +/** One 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 + if (typeof body.error === 'string') code = body.error + else if (body.error !== null && typeof body.error === 'object') { + const nested = body.error as Record + if (typeof nested.code === 'string') code = nested.code + if (typeof nested.message === 'string') message = nested.message + } + if (typeof body.message === 'string') message = body.message + } + } catch { + // Non-JSON error (proxy HTML page, empty body): keep the text snippet. + } + const error: CloudError = { status, code, message: message === '' ? code : message } + if (status === 429) { + const header = retryAfterHeader === null ? Number.NaN : Number(retryAfterHeader) + error.retryAfterMs = Number.isFinite(header) && header > 0 ? header * 1000 : 900_000 + } + return error +} + +/** + * One cloud endpoint handle. Instances are cheap: construct per call site and + * keep the live settings behind closures so a settings edit applies at once. + */ +export class CloudClient { + constructor(private readonly options: CloudClientOptions) {} + + private async request(method: string, path: string, body?: unknown, tokenOverride?: string): Promise> { + const token = tokenOverride ?? this.options.token() + const base = this.options.baseUrl() + const url = `${base}${path}` + const headers: Record = { Accept: 'application/json' } + if (token !== '') headers.Authorization = `Bearer ${token}` + const init: RequestInit = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) } + if (body !== undefined) { + headers['Content-Type'] = 'application/json' + init.body = JSON.stringify(body) + } + let response: Response + try { + response = await fetch(url, init) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + return { ok: false, error: { status: 0, code: 'network_error', message: `${method} ${path}: ${reason}` } } + } + const text = await response.text().catch(() => '') + if (!response.ok) { + return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) } + } + if (text.trim() === '') return { ok: true, status: response.status, data: {} as T } + try { + return { ok: true, status: response.status, data: JSON.parse(text) as T } + } catch { + return { ok: false, error: { status: response.status, code: 'invalid_json', message: 'response was not JSON' } } + } + } + + /** Report one conversation turn (activity:write token). */ + reportTurn(payload: TurnPayload, token: string): Promise> { + return this.request('POST', '/activity/turn', payload, token) + } + + /** + * Verify an activity token without recording anything. + * + * `/activity/turn` validates auth before the payload, so an empty body that + * comes back `400 invalid_event` proves the token carries `activity:write`. + * A 401/403 is a token problem; anything else is reported verbatim. + */ + async probeActivity(token: string): Promise> { + const result = await this.request('POST', '/activity/turn', {}, token) + if (result.ok) return { ok: true, status: result.status, data: { authenticated: true } } + // 400 means the credentials were accepted and only the body was rejected. + if (result.error.status === 400) { + return { ok: true, status: 400, data: { authenticated: true } } + } + return { ok: false, error: result.error } + } + + /** Keyword search over stored memories (memory token). */ + async search(query: string, k: number, project?: string): Promise> { + const body: Record = { query, k } + if (project !== undefined && project !== '') body.filters = { project_id: project } + return this.request('POST', '/memory/query', body) + } + + /** Read one memory by id (memory token). */ + read(id: string): Promise> { + return this.request('GET', `/memory/${encodeURIComponent(id)}`) + } + + /** List memories with optional paging filters (memory token). */ + list(options: { limit?: number; offset?: number; project?: string } = {}): Promise> { + const params = new URLSearchParams() + if (options.limit !== undefined) params.set('limit', String(options.limit)) + if (options.offset !== undefined) params.set('offset', String(options.offset)) + if (options.project !== undefined && options.project !== '') params.set('project_id', options.project) + const suffix = params.toString() === '' ? '' : `?${params.toString()}` + return this.request('GET', `/memory/all${suffix}`) + } + + /** Store one memory; `operationId` makes the write idempotent (memory token). */ + add(input: { content: string; tags?: string[]; project?: string; sector?: string; operationId: string }): Promise> { + const body: Record = { + operation_id: input.operationId, + content: input.content, + } + if (input.tags !== undefined && input.tags.length > 0) body.tags = input.tags + if (input.project !== undefined && input.project !== '') body.project_id = input.project + if (input.sector !== undefined && input.sector !== '') body.metadata = { primary_sector: input.sector } + return this.request('POST', '/memory/add', body) + } + + /** List the account's projects (memory token). */ + projects(): Promise> { + return this.request('GET', '/dashboard/projects') + } + + /** Storage configuration state (memory token). */ + storageStatus(): Promise>> { + return this.request>('GET', '/storage/status') + } + + /** + * One call against the dashboard auth surface (`/api/auth/*`). + * + * These endpoints authorize by session cookie, not by Bearer token, and they + * reject any non-GET without a matching `Origin` (the server's CSRF gate), so + * the origin of the configured base URL is sent explicitly — that is a header + * only a non-browser client can set, which is exactly what this is. + */ + private async authFetch( + method: string, + path: string, + body?: unknown, + cookie?: string, + ): Promise<{ ok: true; status: number; body: unknown; headers: Headers } | { ok: false; error: CloudError }> { + const baseUrl = this.options.baseUrl() + const base = authBase(baseUrl) + if (base === '') return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } } + const headers: Record = { Accept: 'application/json' } + try { + headers.Origin = new URL(baseUrl).origin + } catch { + return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } } + } + if (cookie !== undefined && cookie !== '') headers.Cookie = cookie + const init: RequestInit = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) } + if (body !== undefined) { + headers['Content-Type'] = 'application/json' + init.body = JSON.stringify(body) + } + let response: Response + try { + response = await fetch(`${base}${path}`, init) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + return { ok: false, error: { status: 0, code: 'network_error', message: `${method} /auth${path}: ${reason}` } } + } + const text = await response.text().catch(() => '') + if (!response.ok) { + return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) } + } + let parsed: unknown = {} + if (text.trim() !== '') { + try { + parsed = JSON.parse(text) + } catch { + parsed = {} + } + } + return { ok: true, status: response.status, body: parsed, headers: response.headers } + } + + /** + * Password login against the dashboard. + * + * The password is used once, in this call, and never stored: what comes back + * is a short-lived session cookie that the caller immediately spends on + * {@link CloudClient.mintToken} and then drops. + */ + async login(username: string, password: string): Promise> { + const sent = await this.authFetch('POST', '/login', { username, password }) + if (!sent.ok) return sent + const cookie = sessionCookieOf(sent.headers) + if (cookie === '') { + return { ok: false, error: { status: sent.status, code: 'no_session', message: '登录成功,但服务端没有下发会话' } } + } + const body = sent.body as { user?: AccountInfo } + return { ok: true, status: sent.status, data: { user: body.user ?? {}, sessionCookie: cookie } } + } + + /** Mint one scoped API token using a live session cookie. */ + async mintToken(sessionCookie: string, scope: string, label: string): Promise> { + const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie) + if (!sent.ok) return sent + const body = sent.body as { token?: IssuedToken } + const issued = body.token + if (issued === undefined || typeof issued.token !== 'string' || issued.token === '') { + return { ok: false, error: { status: sent.status, code: 'no_token', message: '服务端没有返回令牌' } } + } + return { ok: true, status: sent.status, data: issued } + } +} + +/** Render a {@link CloudError} as one display line. */ +export function describeError(error: CloudError): string { + if (error.status === 0) return `网络不可用:${error.message}` + return `HTTP ${error.status} ${error.code}:${error.message}` +} diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..c1c0700 --- /dev/null +++ b/src/config.ts @@ -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> + +const MIN_TIMEOUT_MS = 1000 +const MAX_TIMEOUT_MS = 60_000 + +/** Trim truncation guard for the free-form identifiers. */ +function shortString(value: unknown): string | undefined { + if (typeof value !== 'string') return undefined + const trimmed = value.trim() + if (trimmed === '') return undefined + return trimmed.slice(0, 128) +} + +/** + * Normalize a base URL: require http(s), drop trailing slashes and any query. + * Returns undefined when the input is unusable, so callers can fall back. + */ +export function normalizeBaseUrl(value: unknown): string | undefined { + if (typeof value !== 'string' || value.trim() === '') return undefined + try { + const url = new URL(value.trim()) + if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined + return `${url.origin}${url.pathname.replace(/\/+$/, '')}` + } catch { + return undefined + } +} + +/** Clamp a numeric config value into an integer range, else undefined. */ +function boundedInt(value: unknown, min: number, max: number): number | undefined { + if (typeof value !== 'number' || !Number.isFinite(value)) return undefined + return Math.min(max, Math.max(min, Math.round(value))) +} + +/** Extract the recognized settings from an untrusted row config object. */ +export function settingsFromConfig(raw: unknown): Partial { + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {} + const source = raw as RawConfig + const result: Partial = {} + if (typeof source.enabled === 'boolean') result.enabled = source.enabled + const baseUrl = normalizeBaseUrl(source.baseUrl) + if (baseUrl !== undefined) result.baseUrl = baseUrl + const clientId = shortString(source.clientId) + if (clientId !== undefined) result.clientId = clientId + const timeout = boundedInt(source.requestTimeoutMs, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS) + if (timeout !== undefined) result.requestTimeoutMs = timeout + const defaultK = boundedInt(source.defaultK, 1, 100) + if (defaultK !== undefined) result.defaultK = defaultK + return result +} diff --git a/src/context-types.ts b/src/context-types.ts new file mode 100644 index 0000000..6a00633 --- /dev/null +++ b/src/context-types.ts @@ -0,0 +1,59 @@ +/** + * Structural types for the cordis services this plugin consumes. + * + * A third-party plugin resolves outside the DSH monorepo's single cordis + * instance, so the upstream `declare module` augmentations never reach this + * Context. Every shape below mirrors only the members this plugin touches; + * drift is contained to this one file. + */ +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { Context } from '@deepseek-ai/cordis' + +/** One named webserver route (mirror of the host-webserver WebRoute). */ +export interface CloudMemoryWebRoute { + kind: 'exact' | 'prefix' + path: string + handler: (req: IncomingMessage, res: ServerResponse, body?: unknown) => void | Promise +} + +/** The webServer service face this plugin uses. */ +export interface CloudMemoryWebServer { + register(route: CloudMemoryWebRoute): () => void +} + +/** Minimal tool-definition shape accepted by the host tool registry. */ +export interface ToolDefinitionLike { + name: string + description: string + parameters: unknown + output?: { + schema: unknown + render: (args: unknown, value: unknown) => unknown[] + } + execute: (args: Record, exec?: unknown) => Promise +} + +/** The host tool registry face this plugin uses. */ +export interface ToolRegistryLike { + register(definition: ToolDefinitionLike): () => void +} + +/** Cordis Context augmented with the services this plugin needs. */ +export interface CloudMemoryContext extends Context { + webServer?: CloudMemoryWebServer + tools?: ToolRegistryLike +} + +/** The session object as far as turn reporting is concerned. */ +export interface SessionLike { + id?: string + sessionId?: string +} + +/** One `session/event` payload. */ +export interface SessionEventLike { + type?: string + seq?: number + time?: number | string + data?: Record +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..a5eb76c --- /dev/null +++ b/src/index.ts @@ -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') +} diff --git a/src/page.ts b/src/page.ts new file mode 100644 index 0000000..2e8fd66 --- /dev/null +++ b/src/page.ts @@ -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('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", ''') +} + +/** Render the configuration page. */ +export function renderConfigPage(options: { version: string; settingsPath: string }): string { + // The client script is plain ES2020 and avoids template literals so this + // outer template stays readable. + return ` + + + + +云端记忆 · DSH 插件 + + + +
+

云端记忆 · DSH 插件

+

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

+ +
+

当前状态

+
+
加载中…
+
+ +
+

连接配置

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

账号登录

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

访问令牌

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

诊断

+
+ + + +
+
+
+ +
+

最近上报

+ + + + + +
时间状态结果HTTPturn_id
暂无记录
+
+
+
+ + +` +} diff --git a/src/reporter.ts b/src/reporter.ts new file mode 100644 index 0000000..e231cdc --- /dev/null +++ b/src/reporter.ts @@ -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 | 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() + 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 { + 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], + } + } +} diff --git a/src/routes.ts b/src/routes.ts new file mode 100644 index 0000000..d7542b8 --- /dev/null +++ b/src/routes.ts @@ -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 { + const chunks: Buffer[] = [] + let bytes = 0 + for await (const chunk of req) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array) + bytes += buffer.byteLength + if (bytes > maxBytes) throw new Error('request-too-large') + chunks.push(buffer) + } + return Buffer.concat(chunks).toString('utf8') +} + +/** Reject cross-origin browser writes. */ +function sameOrigin(req: IncomingMessage): boolean { + const origin = req.headers.origin + const host = req.headers.host + if (origin === undefined || host === undefined) return true + return origin === `http://${host}` || origin === `https://${host}` +} + +/** Emit one JSON response with no caching. */ +function json(res: ServerResponse, status: number, body: unknown): void { + const text = JSON.stringify(body) + res.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + 'content-length': Buffer.byteLength(text), + }) + res.end(text) +} + +/** Emit a plain-text error (page route) or JSON error (API routes). */ +function fail(res: ServerResponse, status: number, message: string, asHtml = false): void { + const text = asHtml + ? `云端记忆${message}` + : JSON.stringify({ ok: false, error: message }) + res.writeHead(status, { + 'content-type': asHtml ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8', + 'cache-control': 'no-store', + }) + res.end(text) +} + +/** The payload the page and the client card both consume. */ +function statusPayload(deps: RouteDeps): Record { + const view = deps.store.describe() + const tokens: Record<'activity' | 'memory', 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 { + if (req.method !== 'PUT' && req.method !== 'POST') { + fail(res, 405, 'method-not-allowed') + return + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected') + return + } + const type = (req.headers['content-type'] ?? '').toLowerCase() + if (!type.startsWith('application/json')) { + fail(res, 415, 'json-required') + return + } + let patch: unknown + try { + patch = JSON.parse(await readBody(req)) + } catch (error) { + fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json') + return + } + if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { + fail(res, 400, 'invalid-patch') + return + } + const result = deps.store.patch(patch as Record) + if (!result.ok) { + fail(res, 400, result.error ?? 'invalid-patch') + return + } + json(res, 200, statusPayload(deps)) +} + +/** `POST /cloud-memory/test` — validate both tokens without recording anything. */ +async function serveTest(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + if (req.method !== 'POST') { + fail(res, 405, 'method-not-allowed') + return + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected') + return + } + const client = deps.client() + const activityToken = deps.store.activityToken() + const memoryToken = deps.store.memoryToken() + + const activity: { ok: boolean; message: string } = activityToken === '' + ? { ok: false, message: '还没填令牌:把 activity:write 密钥粘到下面「活动上报令牌」再点保存' } + : await (async () => { + const probe = await client.probeActivity(activityToken) + return probe.ok + ? { ok: true, message: '令牌有效(鉴权通过)' } + : { ok: false, message: describeError(probe.error) } + })() + + const memory: { ok: boolean; message: string } = memoryToken === '' + ? { ok: false, message: '还没填令牌:把 memory:write 密钥粘到下面「记忆读写令牌」再点保存' } + : await (async () => { + const probe = await client.projects() + return probe.ok + ? { ok: true, message: `令牌有效(${(probe.data.projects ?? []).length} 个项目)` } + : { ok: false, message: describeError(probe.error) } + })() + + json(res, 200, { ok: true, activity, memory }) +} + +/** `POST /cloud-memory/flush`. */ +async function serveFlush(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + if (req.method !== 'POST') { + fail(res, 405, 'method-not-allowed') + return + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected') + return + } + const result = await deps.reporter.flush() + json(res, 200, { ok: true, ...result }) +} + +/** Labels attached to the two tokens this plugin asks the dashboard to mint. */ +const TOKEN_LABELS = { + activity: 'DSH desktop 活动上报', + memory: 'DSH desktop 记忆读写', +} as const + +/** + * `POST /cloud-memory/login` — sign in with the cloud account and exchange it + * for the two scoped tokens. + * + * The password is used once, in memory, and never written anywhere: the flow is + * password → short-lived session cookie → two `cmt_…` tokens → cookie dropped. + * Only the tokens are persisted, so a later password change does not break the + * plugin and revoking a token does not reveal the password. + */ +async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + if (req.method !== 'POST') { + fail(res, 405, 'method-not-allowed') + return + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected') + return + } + const target = deps.store.settings().baseUrl + if (!isSecureLoginTarget(target)) { + // Refuse to put a password on a plaintext channel that is not loopback. + json(res, 400, { ok: false, error: '服务地址不是 HTTPS,拒绝在上面发送密码,请先把服务地址改成 https://' }) + return + } + let raw: string + try { + raw = await readBody(req) + } catch { + fail(res, 413, 'request-too-large') + return + } + let body: Record + try { + const parsed: unknown = JSON.parse(raw) + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('object required') + body = parsed as Record + } catch { + fail(res, 400, 'invalid-json') + return + } + const username = typeof body.username === 'string' ? body.username.trim() : '' + const password = typeof body.password === 'string' ? body.password : '' + if (username === '' || password === '') { + json(res, 400, { ok: false, error: '请填写用户名和密码' }) + return + } + if (username.length > 64 || password.length > 256) { + json(res, 400, { ok: false, error: '用户名或密码过长' }) + return + } + + const client = deps.client() + const session = await client.login(username, password) + if (!session.ok) { + const status = session.error.status === 429 ? 429 : 401 + json(res, status, { ok: false, error: describeError(session.error) }) + return + } + + const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity) + const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory) + if (!activity.ok && !memory.ok) { + const first = activity.ok ? memory : activity + const reason = first.ok ? '无法创建令牌' : describeError(first.error) + json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` }) + return + } + + const patch: Parameters[0] = {} + if (activity.ok && typeof activity.data.token === 'string') patch.activityToken = activity.data.token + if (memory.ok && typeof memory.data.token === 'string') patch.memoryToken = memory.data.token + 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), + }, + ] +} diff --git a/src/store.ts b/src/store.ts new file mode 100644 index 0000000..c7449f6 --- /dev/null +++ b/src/store.ts @@ -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\` 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 + 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): { 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 + } + } +} diff --git a/src/tools.ts b/src/tools.ts new file mode 100644 index 0000000..8cdf7c4 --- /dev/null +++ b/src/tools.ts @@ -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 { + return { + id: hit.id, + content: snippet(hit.content), + tags: hit.tags ?? [], + project_id: hit.project_id ?? null, + sector: hit.primary_sector ?? null, + revision: hit.revision ?? null, + created_at: hit.created_at ?? null, + } +} + +/** Render any tool value as one JSON text block. */ +function renderJson(_args: unknown, value: unknown): TextBlock[] { + const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2) + return [{ type: 'text', text }] +} + +/** Assert the memory scope is usable, or throw a message the model can act on. */ +function requireMemoryToken(deps: MemoryToolDeps): string { + if (!deps.settings().enabled) { + throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /cloud-memory 页面开启后再试。') + } + const token = deps.memoryToken() + if (token === '') { + throw new Error('未配置记忆令牌。请在 /cloud-memory 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。') + } + return token +} + +/** Search stored memories by keyword. */ +function searchTool(deps: MemoryToolDeps): ToolDefinitionLike { + return { + name: 'memory_search', + description: + '在云端长期记忆库中按关键词检索历史记忆片段。返回命中的记忆 id、内容摘要、标签与所属项目;' + + '需要更多正文时用 memory_read 按 id 取全文。纯关键词匹配,不会做语义相似度检索。', + parameters: { + type: 'object', + properties: { + query: { type: 'string', description: '检索关键词或短语(必填)。' }, + k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' }, + project_id: { type: 'string', description: '可选:只在这些项目 id 内检索。' }, + }, + required: ['query'], + additionalProperties: false, + }, + output: { + schema: { + type: 'object', + properties: { + query: { type: 'string' }, + total: { type: 'number' }, + search_mode: { type: 'string' }, + matches: { type: 'array', items: { type: 'object' } }, + }, + required: ['query', 'matches'], + additionalProperties: true, + }, + render: renderJson, + }, + async execute(args: Record): Promise { + requireMemoryToken(deps) + const query = typeof args.query === 'string' ? args.query.trim() : '' + if (query === '') throw new Error('query 不能为空。') + const requested = typeof args.k === 'number' && Number.isFinite(args.k) ? Math.trunc(args.k) : deps.settings().defaultK + const k = Math.min(1000, Math.max(1, requested)) + const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined + const result = await deps.client().search(query, k, project) + if (!result.ok) throw new Error(`检索失败:${describeError(result.error)}`) + const matches = result.data.matches ?? [] + return { + query, + total: result.data.total ?? matches.length, + search_mode: result.data.search_mode ?? 'keyword', + matches: matches.map(toHitView), + } + }, + } +} + +/** Read one memory by id. */ +function readTool(deps: MemoryToolDeps): ToolDefinitionLike { + return { + name: 'memory_read', + description: '按 id 读取一条云端记忆的完整内容(正文、标签、项目、修订号与时间戳)。id 可先用 memory_search 或 memory_list 获得。', + parameters: { + type: 'object', + properties: { + id: { type: 'string', description: '记忆条目 id(必填)。' }, + }, + required: ['id'], + additionalProperties: false, + }, + output: { + schema: { type: 'object', properties: { id: { type: 'string' }, content: { type: 'string' } }, required: ['id'], additionalProperties: true }, + render: renderJson, + }, + async execute(args: Record): Promise { + requireMemoryToken(deps) + const id = typeof args.id === 'string' ? args.id.trim() : '' + if (id === '') throw new Error('id 不能为空。') + const result = await deps.client().read(id) + if (!result.ok) { + if (result.error.status === 404) throw new Error(`没有找到 id=${id} 的记忆(可能已删除)。`) + throw new Error(`读取失败:${describeError(result.error)}`) + } + return result.data + }, + } +} + +/** Store one new memory. */ +function addTool(deps: MemoryToolDeps): ToolDefinitionLike { + return { + name: 'memory_add', + description: + '向云端长期记忆库写入一条新记忆。content 上限 7000 字节,适合存结论、决策、待办与可复用事实;' + + '不要写入密钥、令牌或完整源码。写入用 operation_id 保证幂等,重复调用不会产生重复条目。', + parameters: { + type: 'object', + properties: { + content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' }, + tags: { type: 'array', items: { type: 'string' }, description: '可选标签,最多 30 个,每个不超过 100 字符。' }, + project_id: { type: 'string', description: '可选:归属项目 id(≤128 字符)。' }, + sector: { type: 'string', enum: [...SECTORS], description: '可选:记忆分类(semantic/episodic/procedural/emotional/reflective)。' }, + operation_id: { type: 'string', description: '可选:幂等键(uuid);省略时自动生成。重试同一次写入时请复用同一个值。' }, + }, + required: ['content'], + additionalProperties: false, + }, + output: { + schema: { + type: 'object', + properties: { + id: { type: 'string' }, + revision: { type: 'number' }, + remote_saved: { type: 'boolean' }, + state: { type: 'string' }, + operation_id: { type: 'string' }, + }, + required: ['id'], + additionalProperties: true, + }, + render: renderJson, + }, + async execute(args: Record): Promise { + requireMemoryToken(deps) + const content = typeof args.content === 'string' ? args.content : '' + if (content.trim() === '') throw new Error('content 不能为空。') + const bytes = Buffer.byteLength(content, 'utf8') + if (bytes > 7000) throw new Error(`content 过大:${bytes} 字节,上限 7000 字节。`) + const rawTags = Array.isArray(args.tags) ? args.tags : [] + const tags = rawTags.filter((tag): tag is string => typeof tag === 'string' && tag !== '').slice(0, 30) + const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined + const sector = typeof args.sector === 'string' && (SECTORS as readonly string[]).includes(args.sector) ? args.sector : undefined + const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : '' + const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID() + const result = await deps.client().add({ content, tags, project, sector, operationId }) + if (!result.ok) { + if (result.error.status === 409 && result.error.code === 'storage_not_configured') { + throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。') + } + throw new Error(`写入失败:${describeError(result.error)}`) + } + return { + id: result.data.id, + revision: result.data.revision, + remote_saved: result.data.remote_saved, + state: result.data.state, + operation_id: result.data.operation_id ?? operationId, + } + }, + } +} + +/** List recent memories. */ +function listTool(deps: MemoryToolDeps): ToolDefinitionLike { + return { + name: 'memory_list', + description: '按时间倒序列出云端记忆(可分页,可按项目过滤)。适合浏览最近保存了什么,再决定是否 memory_read 取全文。', + parameters: { + type: 'object', + properties: { + limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' }, + offset: { type: 'integer', description: '跳过条数,默认 0。' }, + project_id: { type: 'string', description: '可选:只看某个项目。' }, + }, + additionalProperties: false, + }, + output: { + schema: { type: 'object', properties: { total: { type: 'number' }, items: { type: 'array', items: { type: 'object' } } }, required: ['items'], additionalProperties: true }, + render: renderJson, + }, + async execute(args: Record): Promise { + requireMemoryToken(deps) + const rawLimit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : 20 + const limit = Math.min(100, Math.max(1, rawLimit)) + const rawOffset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0 + const offset = Math.max(0, rawOffset) + const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined + const result = await deps.client().list({ limit, offset, project }) + if (!result.ok) throw new Error(`列表读取失败:${describeError(result.error)}`) + const items = result.data.items ?? [] + return { total: result.data.total ?? items.length, items: items.map(toHitView) } + }, + } +} + +/** List projects known to the account. */ +function projectsTool(deps: MemoryToolDeps): ToolDefinitionLike { + return { + name: 'memory_projects', + description: '列出云端账号下的记忆项目(project_id 与名称),用于给 memory_add 选择归属项目。', + parameters: { type: 'object', properties: {}, additionalProperties: false }, + output: { + schema: { type: 'object', properties: { projects: { type: 'array', items: { type: 'object' } } }, required: ['projects'], additionalProperties: true }, + render: renderJson, + }, + async execute(): Promise { + requireMemoryToken(deps) + const result = await deps.client().projects() + + if (!result.ok) throw new Error(`项目列表读取失败:${describeError(result.error)}`) + return { projects: result.data.projects ?? [] } + }, + } +} + +/** Build every memory tool for one plugin instance. */ +export function createMemoryTools(deps: MemoryToolDeps): ToolDefinitionLike[] { + return [searchTool(deps), readTool(deps), addTool(deps), listTool(deps), projectsTool(deps)] +} diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..8732656 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": false, + "declarationMap": false, + "sourceMap": false, + "outDir": "lib", + "rewriteRelativeImportExtensions": true + }, + "include": ["src"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..49277df --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": false, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "types": ["node"] + }, + "include": ["src"] +}