From 1a3a6fb23b24d4307b83329dab50856fad0d7390 Mon Sep 17 00:00:00 2001 From: qyh15 Date: Wed, 11 Nov 2026 20:41:34 +0800 Subject: [PATCH] feat: unified management card (tabs, auth switch, skill plans, MCP bridge) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - settings card: 连接与上报 / 技能管理 / MCP 管理 三页签,身份验证卡内切换 - config: 服务 origin 变更时清除旧令牌并返回 credentialsCleared - status: capabilities、lastCheck、baseUrlConfigured/origin - skills: detail / install plan+commit+cancel / uninstall plan + 一次性 token - mcp: 通过宿主 /mcp-connector/api 读写连接,探测不到时明确缺口 - tests: verify-brain-panel.mjs (53) + verify-skill-admin.mjs (15) 全过 - docs: management-surface.md --- README.md | 13 + client/index.js | 1791 ++++++++++++++++++++++++++++-------- docs/management-surface.md | 79 ++ lib/api.js | 19 + lib/config.js | 28 + lib/index.js | 2 +- lib/routes.js | 309 +++++-- lib/skill-admin.js | 468 ++++++++-- lib/store.js | 32 +- package.json | 2 +- src/api.ts | 19 + src/config.ts | 27 + src/index.ts | 2 +- src/routes.ts | 382 ++++++-- src/skill-admin.ts | 604 +++++++++--- src/store.ts | 37 +- verify-brain-panel.mjs | 238 +++++ 17 files changed, 3311 insertions(+), 741 deletions(-) create mode 100644 docs/management-surface.md create mode 100644 verify-brain-panel.mjs diff --git a/README.md b/README.md index 676c8e5..72d7a89 100644 --- a/README.md +++ b/README.md @@ -200,3 +200,16 @@ 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` 再发布。 + +## 统一管理卡(0.5.0) + +「设置 → 云端记忆」现在是三个页签:**连接与上报 / 技能管理 / MCP 管理**。 + +- 身份验证卡内切换「账号登录 / 手动令牌」,切换不清凭据、不发请求。 +- 服务地址换 origin 时,旧令牌一律清除(`credentialsCleared`),要求重新认证。 +- 技能安装是两步:`install/plan` 把仓库克隆到隔离暂存目录并列出候选(含冲突、脚本、体积),`install/commit` 只写入选中的目录;`.git` 与符号链接不复制,仓库脚本不执行。 +- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。 +- MCP 管理读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;探测不到时明确显示能力缺口,不改它的托管配置。 +- 技能市场本版未接入经验证来源:`capabilities.features.skillsMarketplace = false`,界面不显示假条目。 + +接口清单见 `docs/management-surface.md`,验收脚本是 `verify-brain-panel.mjs` 与 `verify-skill-admin.mjs`。 diff --git a/client/index.js b/client/index.js index 2869413..2b24072 100644 --- a/client/index.js +++ b/client/index.js @@ -4,6 +4,10 @@ // 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. +// +// Three tabs: 连接与上报 / 技能管理 / MCP 管理. Nothing here invents data: every +// number and state comes from the plugin's own routes or, for MCP, from the +// host `dsh-mcp-connector` plugin's public bridge on the same origin. window.__ModuleLoader__.load({ id: 'dsh-cloud-memory', factory: (require) => { @@ -15,12 +19,22 @@ window.__ModuleLoader__.load({ 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 API = { + status: '/cloud-memory/status', + capabilities: '/cloud-memory/capabilities', + config: '/cloud-memory/config', + login: '/cloud-memory/login', + test: '/cloud-memory/test', + flush: '/cloud-memory/flush', + skills: '/cloud-memory/skills', + } + + // The MCP bridge is another plugin's public surface, not ours: it is probed + // at runtime and the tab reports a capability gap when it is missing. + var MCP_BRIDGE = '/mcp-connector/api' + var MCP_PANEL = '/mcp-connector/ui' var POLL_MS = 10000 + var PROBE_TIMEOUT_MS = 5000 var inject = ['slots'] @@ -42,6 +56,10 @@ window.__ModuleLoader__.load({ }) } + function postJson(url, payload) { + return request(url, { method: 'POST', body: JSON.stringify(payload === undefined ? {} : payload) }) + } + function messageOf(error) { if (error === null || error === undefined) return '未知错误' if (typeof error === 'string') return error @@ -58,14 +76,30 @@ window.__ModuleLoader__.load({ 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 bodyError(result, fallback) { + if (result.body !== null && result.body !== undefined && typeof result.body.error === 'string' && result.body.error !== '') { + return result.body.error } + return fallback === undefined ? statusText(result.status) : fallback + } + + function pickSettings(settings) { + var source = settings === undefined || settings === null ? {} : settings + return { + enabled: source.enabled === true, + baseUrl: String(source.baseUrl === undefined ? '' : source.baseUrl), + baseUrlConfigured: source.baseUrlConfigured !== false, + baseUrlOrigin: String(source.baseUrlOrigin === undefined ? '' : source.baseUrlOrigin), + clientId: String(source.clientId === undefined ? '' : source.clientId), + requestTimeoutMs: String(source.requestTimeoutMs === undefined ? 8000 : source.requestTimeoutMs), + defaultK: String(source.defaultK === undefined ? 10 : source.defaultK), + summaryEnabled: source.summaryEnabled === true, + skillsSyncEnabled: source.skillsSyncEnabled === true, + } + } + + function emptyTokens() { + return { activity: '', memory: '', summary: '' } } function formatTime(value) { @@ -77,6 +111,42 @@ window.__ModuleLoader__.load({ return pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()) } + function formatIso(value) { + if (typeof value !== 'string' || value === '') return '—' + var stamp = Date.parse(value) + if (!Number.isFinite(stamp)) return value + return formatTime(stamp) + } + + function formatBytes(value) { + if (typeof value !== 'number' || value < 0) return '—' + if (value < 1024) return String(value) + ' B' + if (value < 1024 * 1024) return (value / 1024).toFixed(1) + ' KB' + return (value / (1024 * 1024)).toFixed(2) + ' MB' + } + + function shortHash(value) { + if (typeof value !== 'string' || value === '') return '—' + return value.slice(0, 12) + } + + function readStored(key, fallback) { + try { + var raw = window.localStorage.getItem('dsh-cloud-memory:' + key) + return raw === null || raw === '' ? fallback : raw + } catch { + return fallback + } + } + + function store(key, value) { + try { + window.localStorage.setItem('dsh-cloud-memory:' + key, String(value)) + } catch { + /* a locked-down window keeps the value in memory only */ + } + } + var OUTCOME_LABELS = { recorded: '已上报', duplicate: '重复忽略', @@ -93,22 +163,93 @@ window.__ModuleLoader__.load({ skipped: 'muted', } + var ORIGIN_LABELS = { + cloud: '云端下发', + uploaded: '本地已上传', + local: '本机安装', + unknown: '来源未知', + } + + var CHECK_TONES = { + ok: 'ok', + unconfigured: 'muted', + invalid: 'bad', + forbidden: 'bad', + unreachable: 'bad', + error: 'bad', + } + + var CHECK_LABELS = { + ok: '可用', + unconfigured: '未配置', + invalid: '令牌失效', + forbidden: '权限不足', + unreachable: '不可达', + error: '出错', + } + + var MCP_STATE_LABELS = { + connected: '已连接', + connecting: '连接中', + disabled: '已停用', + error: '异常', + expired: '授权过期', + unknown: '未知', + needs_auth: '待授权', + } + var styles = { root: { display: 'flex', flexDirection: 'column', - gap: '18px', + gap: '16px', padding: '4px 2px 20px', fontSize: '13px', lineHeight: 1.55, + minWidth: 0, + }, + tabs: { + display: 'flex', + gap: '4px', + padding: '3px', + borderRadius: '12px', + border: '1px solid rgba(127,127,127,0.28)', + background: 'rgba(127,127,127,0.08)', + flexWrap: 'wrap', + }, + tab: { + flex: '1 1 auto', + minWidth: '88px', + font: 'inherit', + fontSize: '12.5px', + padding: '6px 12px', + borderRadius: '9px', + border: '1px solid transparent', + background: 'transparent', + color: 'inherit', + cursor: 'pointer', + whiteSpace: 'nowrap', + }, + tabActive: { + border: '1px solid rgba(37,99,235,0.5)', + background: 'rgba(37,99,235,0.16)', + fontWeight: 600, }, section: { display: 'flex', flexDirection: 'column', gap: '10px', border: '1px solid rgba(127,127,127,0.28)', - borderRadius: '10px', + borderRadius: '12px', padding: '14px 16px', + minWidth: 0, + }, + sectionHead: { + display: 'flex', + alignItems: 'center', + justifyContent: 'space-between', + gap: '10px', + flexWrap: 'wrap', }, sectionTitle: { margin: 0, @@ -131,7 +272,7 @@ window.__ModuleLoader__.load({ flexDirection: 'column', gap: '4px', flex: '1 1 220px', - minWidth: '180px', + minWidth: 0, }, label: { fontSize: '12px', @@ -141,15 +282,17 @@ window.__ModuleLoader__.load({ font: 'inherit', fontSize: '13px', padding: '6px 9px', - borderRadius: '7px', + borderRadius: '8px', border: '1px solid rgba(127,127,127,0.4)', background: 'transparent', color: 'inherit', minWidth: 0, + width: '100%', + boxSizing: 'border-box', }, checkboxRow: { display: 'flex', - alignItems: 'center', + alignItems: 'flex-start', gap: '8px', }, actions: { @@ -162,7 +305,7 @@ window.__ModuleLoader__.load({ font: 'inherit', fontSize: '13px', padding: '6px 16px', - borderRadius: '8px', + borderRadius: '9px', border: '1px solid rgba(127,127,127,0.45)', background: 'transparent', color: 'inherit', @@ -172,11 +315,32 @@ window.__ModuleLoader__.load({ font: 'inherit', fontSize: '13px', padding: '6px 16px', - borderRadius: '8px', + borderRadius: '9px', border: '1px solid rgba(37,99,235,0.6)', background: 'rgba(37,99,235,0.16)', color: 'inherit', cursor: 'pointer', + fontWeight: 600, + }, + buttonDanger: { + font: 'inherit', + fontSize: '13px', + padding: '6px 16px', + borderRadius: '9px', + border: '1px solid rgba(220,38,38,0.6)', + background: 'rgba(220,38,38,0.14)', + color: 'inherit', + cursor: 'pointer', + }, + buttonSmall: { + font: 'inherit', + fontSize: '12px', + padding: '3px 10px', + borderRadius: '7px', + border: '1px solid rgba(127,127,127,0.45)', + background: 'transparent', + color: 'inherit', + cursor: 'pointer', }, pills: { display: 'flex', @@ -191,11 +355,13 @@ window.__ModuleLoader__.load({ borderRadius: '999px', border: '1px solid rgba(127,127,127,0.35)', fontSize: '12px', + maxWidth: '100%', }, table: { width: '100%', borderCollapse: 'collapse', fontSize: '12px', + tableLayout: 'fixed', }, th: { textAlign: 'left', @@ -208,6 +374,7 @@ window.__ModuleLoader__.load({ padding: '4px 8px 4px 0', borderBottom: '1px solid rgba(127,127,127,0.14)', verticalAlign: 'top', + overflowWrap: 'anywhere', }, mono: { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', @@ -220,9 +387,68 @@ window.__ModuleLoader__.load({ muted: {}, banner: { padding: '8px 12px', - borderRadius: '8px', + borderRadius: '10px', fontSize: '12.5px', }, + row: { + display: 'flex', + flexDirection: 'column', + gap: '6px', + border: '1px solid rgba(127,127,127,0.22)', + borderRadius: '10px', + padding: '10px 12px', + minWidth: 0, + }, + rowHead: { + display: 'flex', + alignItems: 'baseline', + justifyContent: 'space-between', + gap: '8px', + flexWrap: 'wrap', + }, + rowTitle: { + fontWeight: 600, + overflowWrap: 'anywhere', + }, + code: { + fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', + fontSize: '11.5px', + whiteSpace: 'pre-wrap', + wordBreak: 'break-word', + maxHeight: '260px', + overflow: 'auto', + margin: 0, + padding: '10px', + borderRadius: '8px', + background: 'rgba(127,127,127,0.1)', + }, + chips: { + display: 'flex', + gap: '6px', + flexWrap: 'wrap', + }, + chip: { + font: 'inherit', + fontSize: '12px', + padding: '2px 10px', + borderRadius: '999px', + border: '1px solid rgba(127,127,127,0.35)', + background: 'transparent', + color: 'inherit', + cursor: 'pointer', + }, + chipActive: { + border: '1px solid rgba(37,99,235,0.6)', + background: 'rgba(37,99,235,0.16)', + }, + nested: { + display: 'flex', + flexDirection: 'column', + gap: '8px', + paddingLeft: '12px', + borderLeft: '2px solid rgba(127,127,127,0.2)', + minWidth: 0, + }, } function Pill(props) { @@ -235,6 +461,11 @@ window.__ModuleLoader__.load({ ) } + function Banner(props) { + var tone = styles[props.tone] === undefined ? styles.muted : styles[props.tone] + return h('div', { style: Object.assign({}, styles.banner, tone), role: props.role }, props.children) + } + function Field(props) { return h( 'label', @@ -256,7 +487,71 @@ window.__ModuleLoader__.load({ ) } - function CloudMemorySettingsCard() { + function Btn(props) { + var style = props.variant === 'primary' ? styles.buttonPrimary : props.variant === 'danger' ? styles.buttonDanger : props.variant === 'small' ? styles.buttonSmall : styles.button + return h( + 'button', + { + type: 'button', + style: style, + disabled: props.disabled === true, + onClick: props.onClick, + 'aria-label': props.ariaLabel, + }, + props.label, + ) + } + + function Switch(props) { + return h( + 'div', + { style: styles.tabs, role: 'tablist', 'aria-label': props.ariaLabel }, + props.options.map(function (option) { + var active = option.value === props.value + return h( + 'button', + { + key: option.value, + type: 'button', + role: 'tab', + 'aria-selected': active, + style: Object.assign({}, styles.tab, active ? styles.tabActive : null), + onClick: function () { + props.onChange(option.value) + }, + }, + option.label, + ) + }), + ) + } + + function Section(props) { + return h( + 'div', + { style: styles.section }, + h( + 'div', + { style: styles.sectionHead }, + h('h4', { style: styles.sectionTitle }, props.title), + props.aside === undefined ? null : h('div', { style: styles.actions }, props.aside), + ), + props.hint === undefined ? null : h('p', { style: styles.hint }, props.hint), + props.children, + ) + } + + function findCheck(source, id) { + if (source === null || source === undefined || !Array.isArray(source.checks)) return undefined + for (var index = 0; index < source.checks.length; index += 1) { + if (source.checks[index] !== null && typeof source.checks[index] === 'object' && source.checks[index].id === id) { + return source.checks[index] + } + } + return undefined + } + + function SettingsCard() { var snapshotState = React.useState(null) var snapshot = snapshotState[0] var setSnapshot = snapshotState[1] @@ -265,10 +560,14 @@ window.__ModuleLoader__.load({ var draft = draftState[0] var setDraft = draftState[1] - var tokenState = React.useState({ activity: '', memory: '' }) + var tokenState = React.useState(emptyTokens()) var tokenDraft = tokenState[0] var setTokenDraft = tokenState[1] + var identityState = React.useState(readStored('identity', 'account')) + var identity = identityState[0] + var setIdentity = identityState[1] + var loginState = React.useState({ username: '', password: '' }) var loginDraft = loginState[0] var setLoginDraft = loginState[1] @@ -293,9 +592,37 @@ window.__ModuleLoader__.load({ var busy = busyState[0] var setBusy = busyState[1] + var tabState = React.useState(readStored('tab', 'connection')) + var tab = tabState[0] + var setTab = tabState[1] + + var advancedState = React.useState(readStored('advanced', 'closed') === 'open') + var advanced = advancedState[0] + var setAdvanced = advancedState[1] + + var skillsState = React.useState({ status: 'idle', data: null, error: null, detail: null, uninstall: null, plan: null, selection: [], installUrl: '', search: '', filter: 'all', busy: '' }) + var skills = skillsState[0] + var setSkills = skillsState[1] + + var mcpState = React.useState({ status: 'idle', items: [], error: null, tools: {}, busy: '', confirm: null }) + var mcp = mcpState[0] + var setMcp = mcpState[1] + + function patchSkills(patch) { + setSkills(function (previous) { + return Object.assign({}, previous, patch) + }) + } + + function patchMcp(patch) { + setMcp(function (previous) { + return Object.assign({}, previous, patch) + }) + } + var load = React.useCallback( function (keepDraft) { - request(STATUS_URL) + return request(API.status) .then(function (result) { if (result.status !== 200 || result.body === null || result.body.ok !== true) { setError('读取插件状态失败(HTTP ' + String(result.status) + '),请重启 DSH 后再试。') @@ -309,7 +636,7 @@ window.__ModuleLoader__.load({ setError('无法连接插件:' + messageOf(failure)) }) }, - [setDraft, setError, setSnapshot], + [], ) React.useEffect( @@ -326,12 +653,36 @@ window.__ModuleLoader__.load({ [load], ) + var dirty = snapshot !== null && draft !== null && JSON.stringify(draft) !== JSON.stringify(pickSettings(snapshot.settings)) + + React.useEffect( + function () { + if (!dirty) return undefined + var guard = function (event) { + event.preventDefault() + event.returnValue = '有未保存的改动' + return event.returnValue + } + window.addEventListener('beforeunload', guard) + return function () { + window.removeEventListener('beforeunload', guard) + } + }, + [dirty], + ) + function patchDraft(patch) { setDraft(function (previous) { return Object.assign({}, previous, patch) }) } + function patchTokens(patch) { + setTokenDraft(function (previous) { + return Object.assign({}, previous, patch) + }) + } + function run(label, task) { setBusy(label) setNotice(null) @@ -353,30 +704,38 @@ window.__ModuleLoader__.load({ clientId: draft.clientId, requestTimeoutMs: Number(draft.requestTimeoutMs), defaultK: Number(draft.defaultK), + summaryEnabled: draft.summaryEnabled, } 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 (tokenDraft.summary.trim() !== '') payload.summaryToken = tokenDraft.summary.trim() + return request(API.config, { 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) + throw new Error('保存失败:' + bodyError(result)) } - setTokenDraft({ activity: '', memory: '' }) - setNotice({ tone: 'ok', text: '已保存到本机配置文件。' }) - load(false) + setTokenDraft(emptyTokens()) + var cleared = Array.isArray(result.body.credentialsCleared) ? result.body.credentialsCleared : [] + setNotice( + cleared.length === 0 + ? { tone: 'ok', text: '已保存到本机配置文件。' } + : { tone: 'warn', text: '服务地址的 origin 已变更,旧地址的令牌已清除(' + cleared.join('、') + '),请重新登录或填写新令牌。' }, + ) + setSnapshot(result.body) + setDraft(pickSettings(result.body.settings)) }) }) } 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) { + var payload = which === 'activity' ? { clearActivityToken: true } : which === 'memory' ? { clearMemoryToken: true } : { clearSummaryToken: true } + return request(API.config, { 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) + ')') + throw new Error('清除令牌失败:' + bodyError(result)) } setNotice({ tone: 'ok', text: '令牌已清除。' }) - load(false) + setSnapshot(result.body) + setDraft(pickSettings(result.body.settings)) }) }) } @@ -384,18 +743,19 @@ window.__ModuleLoader__.load({ function test() { return run('test', function () { setTestResult(null) - return request(TEST_URL, { method: 'POST', body: '{}' }).then(function (result) { + return request(API.test, { 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) + load(true) }) }) } function flush() { return run('flush', function () { - return request(FLUSH_URL, { method: 'POST', body: '{}' }).then(function (result) { + return request(API.flush, { method: 'POST', body: '{}' }).then(function (result) { if (result.status !== 200 || result.body === null || result.body.ok !== true) { throw new Error('重试失败(HTTP ' + String(result.status) + ')') } @@ -412,17 +772,16 @@ window.__ModuleLoader__.load({ if (payload.username === '' || payload.password === '') { throw new Error('请填写用户名和密码') } - return request(LOGIN_URL, { method: 'POST', body: JSON.stringify(payload) }).then(function (result) { + return request(API.login, { 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) + throw new Error('登录失败:' + bodyError(result)) } // 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: '登录成功,已自动写入两个令牌。', + text: '登录成功,已写入可用的令牌。', }) setSnapshot(result.body) setDraft(pickSettings(result.body.settings)) @@ -430,24 +789,223 @@ window.__ModuleLoader__.load({ }) } + function switchIdentity(next) { + setIdentity(next) + store('identity', next) + setLoginResult(null) + setNotice(null) + } + + function switchTab(next) { + setTab(next) + store('tab', next) + if (next === 'skills' && skills.status === 'idle') loadSkills() + if (next === 'mcp' && mcp.status === 'idle') probeMcp() + } + + function toggleAdvanced() { + setAdvanced(function (previous) { + store('advanced', previous ? 'closed' : 'open') + return !previous + }) + } + + // ---- skills ------------------------------------------------------- + + function loadSkills() { + patchSkills({ status: 'loading', error: null }) + return request(API.skills + '/api') + .then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + patchSkills({ status: 'error', error: '读取技能列表失败:' + statusText(result.status) }) + return + } + patchSkills({ status: 'ready', data: result.body, error: null }) + }) + .catch(function (failure) { + patchSkills({ status: 'error', error: '无法读取技能列表:' + messageOf(failure) }) + }) + } + + function skillAction(path, payload, label) { + patchSkills({ busy: label }) + return postJson(API.skills + path, payload) + .then(function (result) { + patchSkills({ busy: '' }) + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + throw new Error(bodyError(result, statusText(result.status))) + } + return result.body + }) + .catch(function (failure) { + patchSkills({ busy: '' }) + patchSkills({ error: messageOf(failure) }) + setNotice({ tone: 'bad', text: messageOf(failure) }) + throw failure + }) + } + + function openDetail(folder) { + patchSkills({ detail: { folder: folder, data: null, error: null } }) + return skillAction('/detail', { folder: folder }, 'detail').then( + function (body) { + patchSkills({ detail: { folder: folder, data: body, error: null } }) + }, + function () { + patchSkills({ detail: { folder: folder, data: null, error: '无法读取详情' } }) + }, + ) + } + + function toggleSkill(folder, enabled) { + return skillAction('/toggle', { folder: folder, enabled: enabled }, 'toggle').then(function (body) { + setNotice({ tone: 'ok', text: body.note === undefined ? '已更新。' : String(body.note) }) + return loadSkills() + }, function () {}) + } + + function planUninstall(folder) { + return skillAction('/uninstall/plan', { folder: folder }, 'uninstall').then(function (body) { + patchSkills({ uninstall: body }) + }, function () {}) + } + + function confirmUninstall() { + if (skills.uninstall === null) return Promise.resolve() + return skillAction('/remove', { folder: skills.uninstall.folder, token: skills.uninstall.token, confirmed: true }, 'remove').then(function (body) { + patchSkills({ uninstall: null }) + setNotice({ tone: 'ok', text: '已删除本机技能 ' + String(body.folder) + '(' + String(body.files) + ' 个文件)。' }) + return loadSkills() + }, function () {}) + } + + function prepareInstall() { + var url = String(skills.installUrl).trim() + if (url === '') { + setNotice({ tone: 'bad', text: '请填写 git 仓库地址。' }) + return Promise.resolve() + } + return skillAction('/install/plan', { url: url }, 'plan').then(function (body) { + var selection = (body.candidates || []) + .filter(function (candidate) { + return candidate.conflict !== true && candidate.problem === undefined + }) + .map(function (candidate) { + return candidate.folder + }) + patchSkills({ plan: body, selection: selection }) + }, function () {}) + } + + function commitInstall() { + if (skills.plan === null) return Promise.resolve() + return skillAction('/install/commit', { planId: skills.plan.planId, folders: skills.selection }, 'commit').then(function (body) { + var installed = Array.isArray(body.installed) ? body.installed : [] + var skipped = Array.isArray(body.skipped) ? body.skipped : [] + patchSkills({ plan: null, selection: [] }) + setNotice({ + tone: skipped.length === 0 ? 'ok' : 'warn', + text: '已安装 ' + String(installed.length) + ' 个技能' + (skipped.length === 0 ? '。' : ',跳过 ' + String(skipped.length) + ' 个:' + skipped.map(function (item) { return String(item.folder) + '(' + String(item.reason) + ')' }).join('、')), + }) + return loadSkills() + }, function () {}) + } + + function cancelInstall() { + if (skills.plan === null) return Promise.resolve() + return skillAction('/install/cancel', { planId: skills.plan.planId }, 'cancel').then(function () { + patchSkills({ plan: null, selection: [] }) + }, function () {}) + } + + // ---- mcp ---------------------------------------------------------- + + function mcpCall(method, params) { + var controller = typeof AbortController === 'function' ? new AbortController() : null + var timer = controller === null ? null : setTimeout(function () { + controller.abort() + }, PROBE_TIMEOUT_MS) + return fetch(MCP_BRIDGE, { + method: 'POST', + cache: 'no-store', + headers: { accept: 'application/json', 'content-type': 'application/json' }, + body: JSON.stringify({ method: method, params: params === undefined ? {} : params }), + signal: controller === null ? undefined : controller.signal, + }) + .then(function (response) { + if (timer !== null) clearTimeout(timer) + return response.json().then( + function (body) { + return { status: response.status, body: body } + }, + function () { + return { status: response.status, body: null } + }, + ) + }) + .catch(function (failure) { + if (timer !== null) clearTimeout(timer) + return { status: 0, body: null, error: messageOf(failure) } + }) + } + + function probeMcp() { + patchMcp({ status: 'probe', error: null }) + return mcpCall('status', {}).then(function (result) { + if (result.status === 200 && result.body !== null && result.body.ok === true && result.body.detail !== undefined) { + patchMcp({ status: 'ok', items: Array.isArray(result.body.detail.items) ? result.body.detail.items : [], error: null }) + return + } + patchMcp({ + status: 'missing', + items: [], + error: result.status === 0 ? '探测超时或连接被拒绝' : '接口返回 HTTP ' + String(result.status) + (result.body !== null && typeof result.body.message === 'string' ? ':' + result.body.message : ''), + }) + }) + } + + function mcpAction(label, method, params) { + patchMcp({ busy: label }) + return mcpCall(method, params).then(function (result) { + patchMcp({ busy: '' }) + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + var reason = result.body !== null && typeof result.body.message === 'string' ? result.body.message : 'HTTP ' + String(result.status) + setNotice({ tone: 'bad', text: 'MCP 操作失败:' + reason }) + return null + } + setNotice({ tone: 'ok', text: 'MCP 操作已完成:' + label }) + return result.body + }) + } + + function loadTools(item) { + return mcpAction('读取工具列表', 'toolsList', { connectorId: item.connectorId, connectionKey: item.key, cachedOnly: true }).then(function (body) { + if (body === null) return + var list = body.detail !== undefined && Array.isArray(body.detail.tools) ? body.detail.tools : Array.isArray(body.tools) ? body.tools : [] + patchMcp(function (previous) { + var tools = Object.assign({}, previous.tools) + tools[item.key] = { items: list, at: Date.now() } + return Object.assign({}, previous, { tools: tools }) + }) + }) + } + + // ---- render ------------------------------------------------------- + if (error !== null && snapshot === null) { return h( 'div', { style: styles.root }, - h('div', { style: Object.assign({}, styles.banner, styles.bad) }, error), + h(Banner, { tone: 'bad' }, error), h( 'div', { style: styles.actions }, - h( - 'button', - { - style: styles.button, - onClick: function () { - load(false) - }, + h(Btn, { + label: '重新加载', + onClick: function () { + load(false) }, - '重新加载', - ), + }), ), ) } @@ -456,33 +1014,829 @@ window.__ModuleLoader__.load({ 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 reporter = snapshot.reporter === undefined || snapshot.reporter === null ? {} : snapshot.reporter + var tokens = snapshot.tokens === undefined || snapshot.tokens === null ? { activity: {}, memory: {}, summary: {} } : snapshot.tokens + var caps = snapshot.capabilities === undefined || snapshot.capabilities === null ? { features: {} } : snapshot.capabilities + var features = caps.features === undefined ? {} : caps.features + var checkSource = testResult !== null ? testResult : snapshot.lastCheck === null || snapshot.lastCheck === undefined ? null : snapshot.lastCheck + var recent = Array.isArray(reporter.recent) ? reporter.recent.slice(0, 8) : [] var activityToken = tokens.activity === undefined ? {} : tokens.activity var memoryToken = tokens.memory === undefined ? {} : tokens.memory + var summaryToken = tokens.summary === undefined ? {} : tokens.summary + var checkedAt = checkSource === null ? '—' : formatTime(checkSource.at === undefined ? checkSource.checkedAt : checkSource.at) - var banner = null - if (notice !== null) { - banner = h('div', { style: Object.assign({}, styles.banner, styles[notice.tone]) }, notice.text) + var connectivity = !draft.baseUrlConfigured + ? { tone: 'warn', text: '未配置服务' } + : checkSource === null + ? { tone: 'muted', text: '未测试' } + : findCheck(checkSource, 'network') === undefined + ? { tone: 'muted', text: '未测试' } + : findCheck(checkSource, 'network').state === 'ok' + ? { tone: 'ok', text: '可达' } + : { tone: 'bad', text: '不可达' } + + var header = h( + 'div', + { style: styles.section, key: 'header' }, + h( + 'div', + { style: styles.sectionHead }, + h('h4', { style: styles.sectionTitle }, '云端记忆 · v' + String(caps.version === undefined ? '—' : caps.version)), + h( + 'div', + { style: styles.pills }, + h(Pill, { label: '连接', value: connectivity.text, tone: connectivity.tone }), + h(Pill, { label: '最后检查', value: checkedAt, tone: 'muted' }), + dirty ? h(Pill, { label: '草稿', value: '未保存', tone: 'warn' }) : null, + ), + ), + h( + 'div', + { style: styles.pills }, + h(Pill, { label: '已上报', value: reporter.recorded === undefined ? 0 : reporter.recorded, tone: 'ok' }), + h(Pill, { label: '待重试', value: reporter.queued === undefined ? 0 : reporter.queued, tone: reporter.queued > 0 ? 'warn' : 'muted' }), + h(Pill, { label: '失败', value: reporter.failed === undefined ? 0 : reporter.failed, tone: reporter.failed > 0 ? 'bad' : 'muted' }), + ), + ) + + var tabBar = h(Switch, { + key: 'tabs', + ariaLabel: '云端记忆管理页签', + value: tab, + onChange: switchTab, + options: [ + { value: 'connection', label: '连接与上报' }, + { value: 'skills', label: '技能管理' }, + { value: 'mcp', label: 'MCP 管理' }, + ], + }) + + var noticeBox = notice === null ? null : h(Banner, { tone: notice.tone, role: 'status', key: 'notice' }, notice.text) + + var connectionTab = null + if (tab === 'connection') { + var changedOrigin = draft.baseUrlConfigured && draft.baseUrlOrigin !== '' && String(draft.baseUrl) !== '' && String(draft.baseUrl).indexOf(draft.baseUrlOrigin) !== 0 + connectionTab = h( + 'div', + { style: styles.root, key: 'connection' }, + + h( + Section, + { + title: '身份验证', + hint: '两种方式最终更新同一组配置;切换不会清除任何一种方式已保存的凭据,也不会自动发起请求。', + aside: h(Switch, { + ariaLabel: '身份验证方式', + value: identity, + onChange: switchIdentity, + options: [ + { value: 'account', label: '账号登录' }, + { value: 'token', label: '手动令牌' }, + ], + }), + }, + + identity === 'account' + ? h( + 'div', + { style: styles.nested }, + h( + 'p', + { style: styles.hint }, + '用云端面板的普通用户账号登录,插件会用一次性会话换取活动与记忆令牌并写入本机。密码只在这一次请求里使用:不保存、不写日志、不回显。', + ), + 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: '只用于本次换取令牌', + hint: '成功后自动清空', + onChange: function (value) { + setLoginDraft(function (previous) { + return Object.assign({}, previous, { password: value }) + }) + }, + }), + ), + h( + 'div', + { style: styles.actions }, + h(Btn, { + variant: 'primary', + label: busy === 'login' ? '登录中…' : '登录并获取令牌', + disabled: busy !== '', + onClick: login, + }), + loginResult === null + ? null + : h( + 'span', + { style: styles.hint }, + '当前账号:' + String(loginResult.user !== undefined && loginResult.user !== null && loginResult.user.username !== undefined ? loginResult.user.username : '未知') + (loginResult.warning === undefined ? '' : '(' + String(loginResult.warning) + ')'), + ), + ), + ) + : h( + 'div', + { style: styles.nested }, + h( + 'p', + { style: styles.hint }, + '三个令牌各有独立权限:activity:write 只用于上报,memory:write 同时允许检索与写入,summary:write 用于自动摘要(可选)。空值表示不修改;清除是独立动作。', + ), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '活动上报令牌(activity:write)', + type: 'password', + value: tokenDraft.activity, + placeholder: activityToken.configured === true ? '已配置 ' + String(activityToken.masked) + ',留空表示不修改' : '未配置', + hint: activityToken.configured === true ? '当前:' + String(activityToken.masked) : undefined, + onChange: function (value) { + patchTokens({ activity: value }) + }, + }), + h(Field, { + label: '记忆读写令牌(memory:write)', + type: 'password', + value: tokenDraft.memory, + placeholder: memoryToken.configured === true ? '已配置 ' + String(memoryToken.masked) + ',留空表示不修改' : '未配置', + hint: memoryToken.configured === true ? '当前:' + String(memoryToken.masked) : undefined, + onChange: function (value) { + patchTokens({ memory: value }) + }, + }), + h(Field, { + label: '摘要令牌(summary:write,可选)', + type: 'password', + value: tokenDraft.summary, + placeholder: summaryToken.configured === true ? '已配置 ' + String(summaryToken.masked) + ',留空表示不修改' : '未配置', + hint: summaryToken.configured === true ? '当前:' + String(summaryToken.masked) : undefined, + onChange: function (value) { + patchTokens({ summary: value }) + }, + }), + ), + h( + 'div', + { style: styles.actions }, + h(Btn, { + label: '清除上报令牌', + variant: 'small', + disabled: activityToken.configured !== true || busy !== '', + onClick: function () { + clearToken('activity') + }, + }), + h(Btn, { + label: '清除记忆令牌', + variant: 'small', + disabled: memoryToken.configured !== true || busy !== '', + onClick: function () { + clearToken('memory') + }, + }), + h(Btn, { + label: '清除摘要令牌', + variant: 'small', + disabled: summaryToken.configured !== true || busy !== '', + onClick: function () { + clearToken('summary') + }, + }), + ), + ), + ), + + h( + Section, + { + title: '服务地址', + hint: '账号登录会把密码发到该地址:仅接受 HTTPS(本机回环除外)。不同 origin 不会复用旧令牌。', + }, + h(Field, { + label: '服务地址(baseUrl)', + value: draft.baseUrl, + placeholder: 'https://<你的域名>/api/longmemory', + hint: changedOrigin ? '地址已改成另一个 origin(当前 ' + draft.baseUrlOrigin + '):保存后旧令牌会被清除,需要重新认证。' : '当前 origin:' + (draft.baseUrlOrigin === '' ? '未配置' : draft.baseUrlOrigin), + onChange: function (value) { + patchDraft({ baseUrl: value }) + }, + }), + advanced + ? h( + 'div', + { style: styles.nested }, + h( + 'div', + { style: styles.grid }, + 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, + hint: '只限制一次搜索返回多少条,不限制可搜索的历史范围。默认 10。', + 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.checkboxRow }, + h('input', { + type: 'checkbox', + checked: draft.summaryEnabled, + id: 'dsh-cloud-memory-summary', + onChange: function (event) { + patchDraft({ summaryEnabled: event.target.checked }) + }, + }), + h('label', { htmlFor: 'dsh-cloud-memory-summary', style: styles.label }, '启用自动摘要(会把该轮对话文本上传为待确认提案;与上面的元数据上报是两件事)'), + ), + ) + : h( + 'div', + { style: styles.actions }, + h(Btn, { label: '高级设置', variant: 'small', onClick: toggleAdvanced }), + ), + ), + + h( + Section, + { + title: '连接与权限检查', + aside: h( + 'div', + { style: styles.actions }, + h(Btn, { variant: 'primary', label: busy === 'save' ? '保存中…' : '保存', disabled: busy !== '', onClick: save }), + h(Btn, { label: busy === 'test' ? '测试中…' : '测试连接', disabled: busy !== '', onClick: test }), + h(Btn, { + label: '重试上报队列', + disabled: busy !== '' || reporter.queued === undefined || reporter.queued === 0, + onClick: flush, + }), + ), + }, + checkSource === null + ? h('p', { style: styles.hint }, '还没有检查记录。点「测试连接」做一次只读检查:网络 → 活动权限 → 记忆权限 → 摘要权限。') + : h( + 'div', + { style: styles.pills }, + (checkSource.checks || []).map(function (check) { + return h(Pill, { + key: String(check.id), + label: String(check.label === undefined ? check.id : check.label), + value: CHECK_LABELS[check.state] === undefined ? String(check.state) : CHECK_LABELS[check.state], + tone: CHECK_TONES[check.state] === undefined ? 'muted' : CHECK_TONES[check.state], + }) + }), + ), + checkSource === null + ? null + : h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '6px' } }, + (checkSource.checks || []).map(function (check) { + return h( + 'div', + { + key: 'detail-' + String(check.id), + style: Object.assign({}, styles.banner, styles[CHECK_TONES[check.state]] === undefined ? styles.muted : styles[CHECK_TONES[check.state]]), + }, + String(check.label === undefined ? check.id : check.label) + ':' + String(check.message), + ) + }), + ), + h('p', { style: styles.hint }, '鉴权通过只代表令牌有效,不代表已经成功写入一条上报;两者在下面分开显示。'), + ), + + h( + Section, + { title: '最近上报' }, + 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 }, '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: 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 仍然可用。', + ), + ) } - var testBox = null - if (testResult !== null) { - var activityTest = testResult.activity === undefined ? {} : testResult.activity - var memoryTest = testResult.memory === undefined ? {} : testResult.memory - testBox = h( + var skillsTab = null + if (tab === 'skills') { + var skillList = skills.data !== null && Array.isArray(skills.data.skills) ? skills.data.skills : [] + var filter = skills.filter + var keyword = String(skills.search).trim().toLowerCase() + var filtered = skillList.filter(function (skill) { + if (filter === 'enabled' && skill.enabled !== true) return false + if (filter === 'disabled' && skill.enabled === true) return false + if (filter === 'cloud' && skill.origin !== 'cloud' && skill.origin !== 'uploaded') return false + if (keyword === '') return true + return (String(skill.folder) + ' ' + String(skill.name) + ' ' + String(skill.description)).toLowerCase().indexOf(keyword) >= 0 + }) + + var detailBox = null + if (skills.detail !== null) { + var detail = skills.detail.data + detailBox = h( + 'div', + { style: styles.row }, + h( + 'div', + { style: styles.rowHead }, + h('span', { style: styles.rowTitle }, '详情:' + String(skills.detail.folder)), + h(Btn, { + label: '关闭', + variant: 'small', + onClick: function () { + patchSkills({ detail: null }) + }, + }), + ), + detail === null + ? h('p', { style: styles.hint }, '正在读取…') + : h( + 'div', + { style: styles.nested }, + h( + 'div', + { style: styles.grid }, + h(Field, { label: '目录', value: detail.dir, onChange: function () {} }), + h(Field, { label: 'SKILL.md 哈希', value: String(detail.skill !== undefined ? detail.skill.skillSha256 : ''), onChange: function () {} }), + ), + h('p', { style: styles.hint }, '文件:' + String(Array.isArray(detail.files) ? detail.files.length : 0) + ' 个,共 ' + formatBytes(detail.totalBytes) + (detail.truncated ? '(SKILL.md 过长,已截断显示)' : '')), + h('pre', { style: styles.code }, String(detail.skillMd === undefined ? '' : detail.skillMd)), + h( + 'p', + { style: styles.hint }, + '文件清单:' + (Array.isArray(detail.files) ? detail.files.map(function (file) { return String(file.path) + (file.script ? '(脚本)' : '') }).join('、') : ''), + ), + ), + ) + } + + var uninstallBox = null + if (skills.uninstall !== null) { + uninstallBox = h( + 'div', + { style: Object.assign({}, styles.row, styles.warn) }, + h('div', { style: styles.rowHead }, h('span', { style: styles.rowTitle }, '卸载确认:' + String(skills.uninstall.folder))), + h( + 'p', + { style: styles.hint }, + '将实际删除:' + String(skills.uninstall.dir) + '\n影响:' + String(skills.uninstall.files) + ' 个文件 / ' + formatBytes(skills.uninstall.bytes) + (Array.isArray(skills.uninstall.scripts) && skills.uninstall.scripts.length > 0 ? ';含脚本:' + skills.uninstall.scripts.join('、') : ''), + ), + h('p', { style: styles.hint }, String(skills.uninstall.note)), + h( + 'div', + { style: styles.actions }, + h(Btn, { variant: 'danger', label: skills.busy === 'remove' ? '删除中…' : '确认删除(不可恢复)', disabled: skills.busy !== '', onClick: confirmUninstall }), + h(Btn, { + label: '取消', + disabled: skills.busy !== '', + onClick: function () { + patchSkills({ uninstall: null }) + }, + }), + ), + ) + } + + var planBox = null + if (skills.plan !== null) { + var candidates = Array.isArray(skills.plan.candidates) ? skills.plan.candidates : [] + planBox = h( + 'div', + { style: styles.row }, + h('div', { style: styles.rowHead }, h('span', { style: styles.rowTitle }, '安装预览:' + String(skills.plan.url))), + h( + 'p', + { style: styles.hint }, + '计划 ' + String(skills.plan.planId) + ' 有效到 ' + formatTime(skills.plan.expiresAt) + '。默认不勾选冲突项;只安装勾选的技能,来源中的安装脚本不会执行。', + ), + h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '6px' } }, + candidates.map(function (candidate) { + var selected = skills.selection.indexOf(candidate.folder) >= 0 + var blocked = candidate.conflict === true || candidate.problem !== undefined + return h( + 'label', + { key: String(candidate.id), style: styles.checkboxRow }, + h('input', { + type: 'checkbox', + checked: selected, + disabled: blocked, + onChange: function (event) { + var next = skills.selection.slice() + var at = next.indexOf(candidate.folder) + if (event.target.checked && at < 0) next.push(candidate.folder) + if (!event.target.checked && at >= 0) next.splice(at, 1) + patchSkills({ selection: next }) + }, + }), + h( + 'span', + { style: { minWidth: 0 } }, + h('span', { style: { fontWeight: 600 } }, String(candidate.name)), + h('span', { style: styles.hint }, ' · ' + String(candidate.folder) + ' · ' + String(candidate.files) + ' 个文件 · ' + formatBytes(candidate.bytes) + (candidate.conflict === true ? ' · 已存在(' + String(candidate.conflictLocation === 'holding' ? '已停用目录' : '技能目录') + '),不覆盖' : '') + (candidate.problem === undefined ? '' : ' · ' + String(candidate.problem)) + (Array.isArray(candidate.scripts) && candidate.scripts.length > 0 ? ' · 含脚本:' + candidate.scripts.join('、') : '')), + ), + ) + }), + ), + h( + 'div', + { style: styles.actions }, + h(Btn, { + variant: 'primary', + label: skills.busy === 'commit' ? '安装中…' : '安装所选(' + String(skills.selection.length) + ')', + disabled: skills.busy !== '' || skills.selection.length === 0, + onClick: commitInstall, + }), + h(Btn, { label: '放弃计划', variant: 'small', disabled: skills.busy !== '', onClick: cancelInstall }), + ), + ) + } + + skillsTab = h( 'div', - { style: { display: 'flex', flexDirection: 'column', gap: '6px' } }, + { style: styles.root, key: 'skills' }, + h( - 'div', - { style: Object.assign({}, styles.banner, activityTest.ok === true ? styles.ok : styles.bad) }, - '活动上报权限:' + (activityTest.ok === true ? '可用 — ' : '不可用 — ') + String(activityTest.message === undefined ? '' : activityTest.message), + Section, + { + title: '本机技能', + hint: '启停是把目录移进 / 移出技能目录,属于新会话生效;卸载是真实删除,没有回收站。', + aside: h(Btn, { label: skills.status === 'loading' ? '刷新中…' : '刷新', variant: 'small', disabled: skills.status === 'loading', onClick: loadSkills }), + }, + skills.error === null ? null : h(Banner, { tone: 'bad' }, skills.error), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '搜索', + value: skills.search, + placeholder: '按名称、目录或描述筛选', + onChange: function (value) { + patchSkills({ search: value }) + }, + }), + ), + h( + 'div', + { style: styles.chips, role: 'group', 'aria-label': '技能筛选' }, + [ + { value: 'all', label: '全部' }, + { value: 'enabled', label: '已启用' }, + { value: 'disabled', label: '已停用' }, + { value: 'cloud', label: '云端来源' }, + ].map(function (option) { + return h( + 'button', + { + key: option.value, + type: 'button', + style: Object.assign({}, styles.chip, filter === option.value ? styles.chipActive : null), + onClick: function () { + patchSkills({ filter: option.value }) + }, + }, + option.label, + ) + }), + ), + skills.status === 'loading' && skills.data === null + ? h('p', { style: styles.hint }, '正在读取技能目录…') + : filtered.length === 0 + ? h('p', { style: styles.hint }, skillList.length === 0 ? '技能目录里没有技能。' : '没有符合筛选条件的技能。') + : h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, + filtered.map(function (skill) { + return h( + 'div', + { key: String(skill.folder), style: styles.row }, + h( + 'div', + { style: styles.rowHead }, + h( + 'span', + { style: styles.rowTitle }, + String(skill.name) + ' ', + h('span', { style: styles.hint }, '· ' + String(skill.folder)), + ), + h( + 'div', + { style: styles.pills }, + h(Pill, { label: '状态', value: skill.enabled === true ? '已启用' : '已停用', tone: skill.enabled === true ? 'ok' : 'muted' }), + h(Pill, { label: '来源', value: ORIGIN_LABELS[skill.origin] === undefined ? String(skill.origin) : ORIGIN_LABELS[skill.origin], tone: skill.origin === 'cloud' ? 'warn' : 'muted' }), + skill.revision === undefined ? null : h(Pill, { label: 'revision', value: skill.revision, tone: 'muted' }), + ), + ), + skill.description === '' ? null : h('p', { style: styles.hint }, String(skill.description)), + h( + 'p', + { style: styles.hint }, + String(skill.files) + ' 个文件 · ' + formatBytes(skill.bytes) + ' · 安装于 ' + formatIso(skill.installedAt) + ' · 所有者 ' + String(skill.ownerManager), + ), + h( + 'div', + { style: styles.actions }, + h(Btn, { label: '详情', variant: 'small', disabled: skills.busy !== '', onClick: function () { openDetail(skill.folder) } }), + h(Btn, { + label: skill.enabled === true ? '停用' : '启用', + variant: 'small', + disabled: skills.busy !== '', + onClick: function () { + toggleSkill(skill.folder, skill.enabled !== true) + }, + }), + h(Btn, { label: '卸载…', variant: 'small', disabled: skills.busy !== '', onClick: function () { planUninstall(skill.folder) } }), + ), + ) + }), + ), ), + + detailBox, + uninstallBox, + h( - 'div', - { style: Object.assign({}, styles.banner, memoryTest.ok === true ? styles.ok : styles.bad) }, - '记忆读写权限:' + (memoryTest.ok === true ? '可用 — ' : '不可用 — ') + String(memoryTest.message === undefined ? '' : memoryTest.message), + Section, + { + title: '从 Git 仓库安装', + hint: '先克隆到隔离暂存目录并列出候选技能,确认后才写入技能目录;不执行仓库里的任何脚本,符号链接不会跟随。仓库地址只接受 https:// 或 file://。', + }, + h(Field, { + label: '仓库地址', + value: skills.installUrl, + placeholder: 'https://github.com//.git', + onChange: function (value) { + patchSkills({ installUrl: value }) + }, + }), + h( + 'div', + { style: styles.actions }, + h(Btn, { + variant: 'primary', + label: skills.busy === 'plan' ? '拉取中…' : '拉取并预览', + disabled: skills.busy !== '', + onClick: prepareInstall, + }), + h(Btn, { label: '刷新列表', variant: 'small', disabled: skills.status === 'loading', onClick: loadSkills }), + ), + planBox, + ), + + h( + Section, + { + title: '技能市场', + hint: '本版没有接入经验证的市场来源,因此不提供搜索与安装入口,也不显示任何示例条目。', + }, + h( + 'p', + { style: styles.hint }, + features.skillsMarketplace === true + ? 'capabilities 报告市场可用。' + : '能力缺口:capabilities.features.skillsMarketplace = false。下一步接入一个来源(MarketProvider:search / getDetail / resolveArtifact / checkUpdates)后再开放。', + ), + ), + + h( + Section, + { + title: '云端同步状态', + hint: '同步仍由现有引擎负责:本地改动与云端改动冲突时会暂停该项,不会被覆盖。', + }, + snapshot.skills === undefined || snapshot.skills === null + ? h('p', { style: styles.hint }, '同步引擎未启用。') + : h( + 'div', + { style: styles.pills }, + h(Pill, { label: '运行中', value: snapshot.skills.running === true ? '是' : '否', tone: snapshot.skills.running === true ? 'warn' : 'muted' }), + h(Pill, { label: '上次运行', value: formatIso(snapshot.skills.lastRunAt), tone: 'muted' }), + h(Pill, { label: '下载', value: (snapshot.skills.downloaded || []).length, tone: 'muted' }), + h(Pill, { label: '上传', value: (snapshot.skills.uploaded || []).length, tone: 'muted' }), + h(Pill, { label: '冲突', value: (snapshot.skills.conflicts || []).length, tone: (snapshot.skills.conflicts || []).length > 0 ? 'warn' : 'muted' }), + ), + snapshot.skills === undefined || snapshot.skills === null || snapshot.skills.lastError === undefined + ? null + : h('p', { style: styles.hint }, '最近一次同步错误:' + String(snapshot.skills.lastError)), + ), + ) + } + + var mcpTab = null + if (tab === 'mcp') { + var items = Array.isArray(mcp.items) ? mcp.items : [] + var bridgeBox = null + if (mcp.status === 'missing') { + bridgeBox = h( + Banner, + { tone: 'warn' }, + 'MCP 管理当前不可用:没有探测到宿主 dsh-mcp-connector 的公开接口(' + MCP_BRIDGE + ')。' + (mcp.error === null ? '' : '原因:' + String(mcp.error)) + '。自定义 MCP Server 的权威位置仍是「设置 → 插件配置 → MCP 服务器配置」,本卡不会修改它的托管配置。', + ) + } + + mcpTab = h( + 'div', + { style: styles.root, key: 'mcp' }, + h( + Section, + { + title: '我的连接', + hint: '数据来自宿主 dsh-mcp-connector 插件(同一 origin 的公开接口);本卡不保存任何 MCP 凭据,也不回显启动命令与密钥。', + aside: h(Btn, { label: mcp.status === 'probe' ? '探测中…' : '重新探测', variant: 'small', disabled: mcp.busy !== '', onClick: probeMcp }), + }, + bridgeBox, + mcp.status === 'ok' && items.length === 0 ? h('p', { style: styles.hint }, '宿主还没有登记任何 MCP 连接。') : null, + mcp.status === 'ok' + ? h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, + items.map(function (item) { + var state = String(item.connectionState === undefined ? 'unknown' : item.connectionState) + var tools = mcp.tools[item.key] + return h( + 'div', + { key: String(item.key), style: styles.row }, + h( + 'div', + { style: styles.rowHead }, + h('span', { style: styles.rowTitle }, String(item.name === undefined ? item.key : item.name)), + h( + 'div', + { style: styles.pills }, + h(Pill, { label: '状态', value: MCP_STATE_LABELS[state] === undefined ? state : MCP_STATE_LABELS[state], tone: state === 'connected' ? 'ok' : state === 'disabled' ? 'muted' : 'warn' }), + h(Pill, { label: '传输', value: String(item.transport === undefined ? '—' : item.transport), tone: 'muted' }), + h(Pill, { label: '鉴权', value: String(item.authMode === undefined ? 'none' : item.authMode), tone: 'muted' }), + h(Pill, { label: '注入', value: String(item.injectionLabel === undefined ? '—' : item.injectionLabel), tone: 'muted' }), + ), + ), + h( + 'p', + { style: styles.hint }, + '范围:' + (item.scope === undefined || item.scope === null ? '未知' : String(item.scope.visibility === undefined ? JSON.stringify(item.scope) : item.scope.visibility)) + ' · 健康检查:' + formatIso(item.healthCheckedAt) + (item.lastError === null || item.lastError === undefined ? '' : ' · 最近错误:' + String(item.lastError)), + ), + h( + 'div', + { style: styles.actions }, + h(Btn, { + label: '健康检查', + variant: 'small', + disabled: mcp.busy !== '', + onClick: function () { + mcpAction('健康检查 ' + String(item.name), 'healthCheck', { connectorId: item.connectorId }).then(function () { + probeMcp() + }) + }, + }), + h(Btn, { + label: '工具列表', + variant: 'small', + disabled: mcp.busy !== '', + onClick: function () { + loadTools(item) + }, + }), + h(Btn, { + label: item.enabled === false ? '启用' : '停用', + variant: 'small', + disabled: mcp.busy !== '', + onClick: function () { + mcpAction(item.enabled === false ? '启用连接' : '停用连接', 'setEnabled', { key: item.key, enabled: item.enabled === false }).then(function () { + probeMcp() + }) + }, + }), + h(Btn, { + label: '重连', + variant: 'small', + disabled: mcp.busy !== '', + onClick: function () { + mcpAction('重连', 'reconnect', { key: item.key }).then(function () { + probeMcp() + }) + }, + }), + mcp.confirm === item.key + ? h(Btn, { + label: '确认移除', + variant: 'danger', + disabled: mcp.busy !== '', + onClick: function () { + mcpAction('移除连接', 'disconnect', { key: item.key }).then(function () { + patchMcp({ confirm: null }) + probeMcp() + }) + }, + }) + : h(Btn, { + label: '移除连接…', + variant: 'small', + disabled: mcp.busy !== '', + onClick: function () { + patchMcp({ confirm: item.key }) + setNotice({ tone: 'warn', text: '再次点击「确认移除」才会断开该连接定义。' }) + }, + }), + ), + tools === undefined + ? null + : h( + 'div', + { style: styles.nested }, + h('p', { style: styles.hint }, '工具缓存(' + formatTime(tools.at) + '):' + (tools.items.length === 0 ? '空' : tools.items.map(function (tool) { return String(tool.name === undefined ? tool : tool.name) }).join('、'))), + h('p', { style: styles.hint }, '工具可见不等于业务可调用:连接状态与工具缓存分开显示。'), + ), + ) + }), + ) + : null, + ), + + h( + Section, + { + title: 'MCP 市场', + hint: '目录浏览与安装仍由宿主插件负责;本卡只在能确认其公开接口时提供跳转,不以内嵌面板冒充完成。', + }, + h('p', { style: styles.hint }, '宿主 MCP 面板地址:' + MCP_PANEL + '(由 dsh-mcp-connector 提供)。目录条目、示例与远端文本都视为不可信内容。'), ), ) } @@ -490,300 +1844,11 @@ window.__ModuleLoader__.load({ 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 仍然可用。'), + header, + tabBar, + noticeBox, + error === null ? null : h(Banner, { tone: 'bad' }, error), + tab === 'connection' ? connectionTab : tab === 'skills' ? skillsTab : mcpTab, ) } @@ -815,7 +1880,7 @@ window.__ModuleLoader__.load({ function apply(ctx) { var card = function () { - return h(CardBoundary, null, h(CloudMemorySettingsCard, null)) + return h(CardBoundary, null, h(SettingsCard, null)) } var register = function (seat, options) { diff --git a/docs/management-surface.md b/docs/management-surface.md new file mode 100644 index 0000000..ec78fe8 --- /dev/null +++ b/docs/management-surface.md @@ -0,0 +1,79 @@ +# 统一管理卡接口与契约(0.5.0) + +本文件记录 0.5.0 交付的「连接与上报 / 技能管理 / MCP 管理」三页签所依赖的真实接口、约束与验证结果。凡是未实现的能力都在这里写明,不在界面上假装可用。 + +## 1. 路由 + +| 方法 | 路径 | 说明 | +|---|---|---| +| GET | `/cloud-memory` | 自带配置页(旧入口,保留) | +| GET | `/cloud-memory/status` | 设置 + 令牌掩码 + 上报计数 + `lastCheck` + `capabilities` | +| GET | `/cloud-memory/capabilities` | 能力清单与缺口说明 | +| PUT | `/cloud-memory/config` | 写配置;换 origin 时返回 `credentialsCleared` | +| POST | `/cloud-memory/login` | 账号一次性换取令牌 | +| POST | `/cloud-memory/test` | 只读分项检查:`network` / `activity` / `memory` / `summary` | +| POST | `/cloud-memory/flush` | 重试上报队列 | +| GET | `/cloud-memory/skills/api` | 技能清单 + `plans`(未完成安装计划) | +| POST | `/cloud-memory/skills/detail` | `{folder}` → SKILL.md、文件清单、哈希 | +| POST | `/cloud-memory/skills/toggle` | `{folder, enabled}` → 目录移动 + 生效范围说明 | +| POST | `/cloud-memory/skills/install/plan` | `{url}` → 暂存克隆 + 候选描述 | +| POST | `/cloud-memory/skills/install/commit` | `{planId, folders}` → 只装选中项 | +| POST | `/cloud-memory/skills/install/cancel` | `{planId}` → 丢弃暂存 | +| POST | `/cloud-memory/skills/install` | 旧页面用的一次性安装(等于 plan + 全部非冲突项) | +| POST | `/cloud-memory/skills/uninstall/plan` | `{folder}` → 影响预览 + 一次性 token | +| POST | `/cloud-memory/skills/remove` | `{folder, token, confirmed:true}` → 真实删除 | + +## 2. 契约要点 + +### 2.1 服务地址与凭据 + +- `settings.baseUrlConfigured=false` 表示地址仍是打包占位符,界面必须显示「未配置服务」。 +- 写入配置时若 `new origin != old origin`:本次请求没有显式提供新值的令牌全部删除,响应带 `credentialsCleared: ['activity','memory','summary']`。旧服务的 bearer token 绝不会被发往新 origin。 +- 令牌只以掩码形式出现在 `status`;清除是独立动作(`clear*Token`)。 + +### 2.2 检查状态 + +`POST /test` 返回 `checks[]`,每项 `{id,label,state,message}`,`state ∈ ok | unconfigured | invalid | forbidden | unreachable | error`。鉴权通过与「已写入一条上报」分开显示;`:reach()` 只证明服务可达。 + +### 2.3 技能安装 + +1. `plan`:只接受 `https://` / `file://`;`git clone --depth 1` 到 `$DSH_HOME/.cloud-memory-staging/`;候选深度 ≤ 3、≤ 60 个;描述含 `files`、`bytes`、`scripts`、`conflict`、`problem`。 +2. 计划记录只保存 `planId / url / createdAt / expiresAt / stagingDir / candidates` 元数据,TTL 30 分钟;过期计划连暂存目录一起清理。 +3. `commit`:只安装 `folders` 里且计划中存在的候选;`conflict`/`problem` 一律跳过;`.git` 与符号链接在 `cp` filter 中被剔除;源与目标都校验在各自根目录内(`path_escape`)。 +4. 不执行仓库里的任何脚本、钩子或依赖命令;需要执行时由用户另行决定。 + +### 2.4 技能卸载 + +`uninstall/plan` 返回真实目录、文件数、字节数、含脚本列表、`recoverable:false` 与提示,并签发绑定该目录的一次性 token(10 分钟);`remove` 必须同时满足 `confirmed:true` + 该 folder 的 token,token 用后即废,换目录无效。没有回收站,删除即不可恢复,界面必须原样说明。 + +### 2.5 启停 + +启停仍是把目录移进/移出 `$DSH_HOME/skills-disabled/`,属于**新会话生效**;已加载会话不受影响。接口在响应里带这条说明,界面不得宣称立即生效。 + +### 2.6 MCP 桥接 + +MCP 页签不新建凭据库,读取宿主 `dsh-mcp-connector`(0.2.88)同源公开接口: + +``` +POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "setEnabled" | "reconnect" | "disconnect" | ..., "params": {...} } +``` + +- 探测失败(404/超时/非 200)→ 界面显示能力缺口,并指向「设置 → 插件配置 → MCP 服务器配置」这一权威入口。 +- 只展示 `name / transport / authMode / enabled / connectionState / injectionLabel / scope / healthCheckedAt / lastError`;不回显 stdio 启动命令、env、token 或敏感 header。 +- 工具缓存与连接状态分开显示:工具可见 ≠ 业务可调用。 +- 市场条目与远端文本视为不可信内容,不内嵌执行。 + +## 3. 已执行验证(Windows,本机 Node v24.21.0) + +- `verify-brain-panel.mjs`:53 项全过(status/capabilities、config 换 origin 清凭据、方法/Origin/Content-Type 闸门、技能清单与详情、安装计划与选择、冲突跳过、计划过期、暂存清理、卸载预览与一次性 token、路径穿越拒绝)。 +- `verify-skill-admin.mjs`:15 项全过(含与同步引擎的联动:已停用技能不被云端更新重新启用)。 +- `tsc -p tsconfig.build.json` 与 `tsc -p tsconfig.json --noEmit`:无错误。 + +## 4. 明确未完成 + +- 技能市场:无经验证来源,`features.skillsMarketplace=false`。 +- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。 +- 自动更新与版本回退:未实现(无来源清单与制品基线)。 +- MCP 市场的内嵌浏览与安装:未实现,只给宿主面板位置。 +- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。 +- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。 diff --git a/lib/api.js b/lib/api.js index 1d7a498..57ffb5b 100644 --- a/lib/api.js +++ b/lib/api.js @@ -115,6 +115,25 @@ export class CloudClient { reportTurn(payload, token) { return this.request('POST', '/activity/turn', payload, token); } + /** + * Read-only reachability probe: any HTTP answer (even 401 or 404) proves the + * host is up. This is what separates "服务不可达" from "令牌无效" in the card, + * and it never sends a credential. + */ + async reach() { + try { + const response = await fetch(`${this.options.baseUrl()}/status`, { + method: 'GET', + headers: { Accept: 'application/json' }, + signal: AbortSignal.timeout(this.options.timeoutMs()), + }); + return { ok: true, status: response.status, message: `服务可达(HTTP ${response.status})` }; + } + catch (error) { + const reason = error instanceof Error ? error.message : String(error); + return { ok: false, status: 0, message: `服务不可达:${reason}` }; + } + } /** Stage one turn summary as pending proposals (summary:write token). */ submitSummary(payload, token) { return this.request('POST', '/activity/summary', payload, token); diff --git a/lib/config.js b/lib/config.js index 7c10f75..06d028b 100644 --- a/lib/config.js +++ b/lib/config.js @@ -43,6 +43,34 @@ export function normalizeBaseUrl(value) { return undefined; } } +/** + * A packaged default that was never replaced by a real service. + * + * `cordis.patch.yml` ships `https://your-memory-host/...` so a fresh profile + * boots without touching a production endpoint. Such an address must be shown + * as "未配置服务" — never as a healthy connection. + */ +export function isPlaceholderBaseUrl(value) { + const normalized = normalizeBaseUrl(value); + if (normalized === undefined) + return true; + try { + const host = new URL(normalized).hostname.toLowerCase(); + return host === 'your-memory-host' || host === 'example.com'; + } + catch { + return true; + } +} +/** Service origin of one base URL, or '' when it cannot be parsed. */ +export function originOf(value) { + try { + return new URL(value).origin; + } + catch { + return ''; + } +} /** Clamp a numeric config value into an integer range, else undefined. */ function boundedInt(value, min, max) { if (typeof value !== 'number' || !Number.isFinite(value)) diff --git a/lib/index.js b/lib/index.js index f88d5fb..153ed61 100644 --- a/lib/index.js +++ b/lib/index.js @@ -22,7 +22,7 @@ export const name = 'dsh-cloud-memory'; /** Services required before `apply` runs. */ export const inject = ['webServer']; /** Version reported by the status card. */ -const VERSION = '0.4.1'; +const VERSION = '0.5.0'; /** How often the skill directory is reconciled with the cloud center. */ const SKILL_SYNC_INTERVAL_MS = 15 * 60_000; /** How often queued reports are retried. */ diff --git a/lib/routes.js b/lib/routes.js index f41bf22..1179654 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -2,10 +2,12 @@ import { describeError, isSecureLoginTarget } from "./api.js"; import { renderConfigPage } from "./page.js"; import { SkillAdminError } from "./skill-admin.js"; import { renderSkillsPage } from "./skill-page.js"; +import { randomUUID } from 'node:crypto'; /** Route constants — kept in one place so the client half can reuse them. */ export const ROUTES = { page: '/cloud-memory', status: '/cloud-memory/status', + capabilities: '/cloud-memory/capabilities', config: '/cloud-memory/config', login: '/cloud-memory/login', test: '/cloud-memory/test', @@ -14,6 +16,30 @@ export const ROUTES = { }; /** Largest request body we accept (a settings patch is tiny). */ const MAX_BODY_BYTES = 64 * 1024; +/** What this build actually implements, stated per feature. */ +function capabilities(deps) { + return { + version: deps.version, + features: { + connection: true, + identitySwitch: true, + skills: deps.admin !== undefined, + skillInstallPlans: deps.admin !== undefined, + skillUninstallPlan: deps.admin !== undefined, + skillsSync: deps.skills !== undefined, + // No verified marketplace provider is wired in this build; the card says + // so instead of showing a fake search box. + skillsMarketplace: false, + // The MCP bridge is provided by the host `dsh-mcp-connector` plugin over + // the same origin; the browser half probes it at runtime. + mcpBridge: 'host-plugin', + }, + notes: [ + '技能市场尚未接入经验证的来源,本版不提供搜索与安装闭环。', + 'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。', + ], + }; +} /** Collect a request body as UTF-8 text. */ async function readBody(req, maxBytes = MAX_BODY_BYTES) { const chunks = []; @@ -56,6 +82,50 @@ function fail(res, status, message, asHtml = false) { }); res.end(text); } +/** + * Read one JSON object body, or answer the request and return undefined. + * + * The method, origin and content-type gates live here so every write route + * cannot forget one of them. + */ +async function jsonBody(req, res) { + if (req.method !== 'POST' && req.method !== 'PUT') { + fail(res, 405, 'method-not-allowed'); + return undefined; + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected'); + return undefined; + } + const type = (req.headers['content-type'] ?? '').toLowerCase(); + if (!type.startsWith('application/json')) { + fail(res, 415, 'json-required'); + return undefined; + } + let parsed; + try { + parsed = JSON.parse(await readBody(req)); + } + catch (error) { + fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json'); + return undefined; + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + fail(res, 400, 'invalid-body'); + return undefined; + } + return parsed; +} +/** Last test run, kept in memory so the card can show "最后检查". */ +let lastCheck = null; +/** + * Uninstall confirmations. + * + * A preview issues a single-use token bound to one folder; the delete route + * refuses without it, so a stray click cannot remove a skill. + */ +const uninstallTokens = new Map(); +const UNINSTALL_TOKEN_TTL_MS = 10 * 60_000; /** The payload the page and the client card both consume. */ function statusPayload(deps) { const view = deps.store.describe(); @@ -67,6 +137,8 @@ function statusPayload(deps) { const settings = { enabled: view.enabled, baseUrl: view.baseUrl, + baseUrlConfigured: view.baseUrlConfigured, + baseUrlOrigin: view.baseUrlOrigin, clientId: view.clientId, requestTimeoutMs: view.requestTimeoutMs, defaultK: view.defaultK, @@ -76,7 +148,13 @@ function statusPayload(deps) { skillsDir: view.skillsDir, }; return { - ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot(), + ok: true, + settings, + tokens, + settingsPath: view.statePath, + reporter: deps.reporter.snapshot(), + lastCheck, + capabilities: capabilities(deps), ...(deps.skills === undefined ? {} : { skills: deps.skills() }), }; } @@ -105,6 +183,14 @@ function serveStatus(deps, req, res) { } json(res, 200, statusPayload(deps)); } +/** `GET /cloud-memory/capabilities`. */ +function serveCapabilities(deps, req, res) { + if (req.method !== 'GET') { + fail(res, 405, 'method-not-allowed'); + return; + } + json(res, 200, { ok: true, ...capabilities(deps) }); +} /** `PUT /cloud-memory/config`. */ async function serveConfig(deps, req, res) { if (req.method !== 'PUT' && req.method !== 'POST') { @@ -137,9 +223,22 @@ async function serveConfig(deps, req, res) { fail(res, 400, result.error ?? 'invalid-patch'); return; } - json(res, 200, statusPayload(deps)); + json(res, 200, { + ...statusPayload(deps), + ...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }), + }); } -/** `POST /cloud-memory/test` — validate both tokens without recording anything. */ +/** Map one failed credential probe onto a check state. */ +function checkState(error) { + if (error.status === 0) + return 'unreachable'; + if (error.status === 401) + return 'invalid'; + if (error.status === 403) + return 'forbidden'; + return 'error'; +} +/** `POST /cloud-memory/test` — read-only checks, one per credential. */ async function serveTest(deps, req, res) { if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); @@ -150,36 +249,67 @@ async function serveTest(deps, req, res) { return; } const client = deps.client(); + const checks = []; + const settings = deps.store.settings(); + const reach = await client.reach(); + checks.push({ + id: 'network', + label: '服务地址', + state: reach.ok ? 'ok' : 'unreachable', + message: deps.store.describe().baseUrlConfigured === false ? '服务地址还是打包默认值,请先填写真实地址。' : reach.message, + }); const activityToken = deps.store.activityToken(); + if (activityToken === '') { + checks.push({ id: 'activity', label: '活动上报权限(activity:write)', state: 'unconfigured', message: '未配置令牌' }); + } + else { + const probe = await client.probeActivity(activityToken); + checks.push({ + id: 'activity', + label: '活动上报权限(activity:write)', + state: probe.ok ? 'ok' : checkState(probe.error), + message: probe.ok ? '鉴权通过(只验证权限,不代表已写入一条上报)' : describeError(probe.error), + }); + } const memoryToken = deps.store.memoryToken(); - 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) }; - })(); + if (memoryToken === '') { + checks.push({ id: 'memory', label: '记忆读写权限(memory:write)', state: 'unconfigured', message: '未配置令牌' }); + } + else { + const probe = await client.projects(); + checks.push({ + id: 'memory', + label: '记忆读写权限(memory:write)', + state: probe.ok ? 'ok' : checkState(probe.error), + message: probe.ok ? `鉴权通过(${(probe.data.projects ?? []).length} 个项目)` : describeError(probe.error), + }); + } const summaryToken = deps.store.summaryToken(); - const summary = !deps.store.settings().summaryEnabled - ? { ok: false, message: '自动摘要已关闭(可在下方勾选开启)' } - : summaryToken === '' - ? { ok: false, message: '未配置摘要令牌:留空则不做自动摘要' } - : await (async () => { - const probe = await client.probeSummary(summaryToken); - return probe.ok - ? { ok: true, message: '摘要令牌有效(只进待确认队列)' } - : { ok: false, message: describeError(probe.error) }; - })(); - json(res, 200, { ok: true, activity, memory, summary }); + if (!settings.summaryEnabled) { + checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '自动摘要已关闭' }); + } + else if (summaryToken === '') { + checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '未配置摘要令牌(可选)' }); + } + else { + const probe = await client.probeSummary(summaryToken); + checks.push({ + id: 'summary', + label: '摘要权限(summary:write)', + state: probe.ok ? 'ok' : checkState(probe.error), + message: probe.ok ? '鉴权通过(只进待确认队列)' : describeError(probe.error), + }); + } + lastCheck = { at: Date.now(), checks }; + json(res, 200, { + ok: true, + checkedAt: lastCheck.at, + checks, + // Kept for the older card/page shape; both views read the same probes. + activity: { ok: checks[1]?.state === 'ok', message: checks[1]?.message ?? '' }, + memory: { ok: checks[2]?.state === 'ok', message: checks[2]?.message ?? '' }, + summary: { ok: checks[3]?.state === 'ok', message: checks[3]?.message ?? '' }, + }); } /** `POST /cloud-memory/flush`. */ async function serveFlush(deps, req, res) { @@ -194,7 +324,7 @@ async function serveFlush(deps, req, res) { 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. */ +/** Labels attached to the tokens this plugin asks the dashboard to mint. */ const TOKEN_LABELS = { activity: 'DSH desktop 活动上报', memory: 'DSH desktop 记忆读写', @@ -202,12 +332,12 @@ const TOKEN_LABELS = { }; /** * `POST /cloud-memory/login` — sign in with the cloud account and exchange it - * for the two scoped tokens. + * for the 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. + * password → short-lived session cookie → tokens → cookie dropped. Only the + * tokens are persisted, so a later password change does not break the plugin + * and revoking a token does not reveal the password. */ async function serveLogin(deps, req, res) { if (req.method !== 'POST') { @@ -304,28 +434,56 @@ function adminStatus(code) { switch (code) { case 'not_found': return 404; case 'invalid_name': - case 'invalid_url': return 400; + case 'invalid_url': + case 'invalid_plan': return 400; case 'collision': - case 'sync_running': return 409; + case 'sync_running': + case 'plan_expired': + case 'confirmation_required': + case 'unsupported': return 409; case 'no_skills_found': return 422; case 'git_failed': return 502; default: return 500; } } +/** Issue the single-use token a delete needs. */ +function issueUninstallToken(folder) { + const token = `uninstall_${randomUUID()}`; + uninstallTokens.set(folder, { token, expiresAt: Date.now() + UNINSTALL_TOKEN_TTL_MS }); + return token; +} +/** Consume one uninstall token; false when it is missing, stale or foreign. */ +function useUninstallToken(folder, token) { + const record = uninstallTokens.get(folder); + if (record === undefined) + return false; + if (typeof token !== 'string' || token !== record.token) + return false; + if (record.expiresAt < Date.now()) { + uninstallTokens.delete(folder); + return false; + } + uninstallTokens.delete(folder); + return true; +} /** * The skill management surface, one prefix route: - * `GET /cloud-memory/skills` the management page - * `GET /cloud-memory/skills/api` inventory JSON (skills + trash) - * `POST /cloud-memory/skills/toggle` { folder, enabled } - * `POST /cloud-memory/skills/remove` { folder } - * `POST /cloud-memory/skills/install` { url } + * `GET /cloud-memory/skills` the management page + * `GET /cloud-memory/skills/api` inventory JSON (skills + plans) + * `POST /cloud-memory/skills/detail` { folder } — one skill with SKILL.md + * `POST /cloud-memory/skills/toggle` { folder, enabled } + * `POST /cloud-memory/skills/install/plan` { url } — stage the repository + * `POST /cloud-memory/skills/install/commit` { planId, folders } + * `POST /cloud-memory/skills/install/cancel` { planId } + * `POST /cloud-memory/skills/uninstall/plan` { folder } — impact preview + * `POST /cloud-memory/skills/remove` { folder, token, confirmed: true } */ async function serveSkills(deps, req, res) { - if (deps.admin === undefined) { + const admin = deps.admin; + if (admin === undefined) { fail(res, 404, 'skills-admin-unavailable'); return; } - const admin = deps.admin; const suffix = (req.url ?? '').split('?')[0]?.slice(ROUTES.skills.length) ?? ''; if (suffix === '' || suffix === '/') { if (req.method !== 'GET' && req.method !== 'HEAD') { @@ -349,54 +507,50 @@ async function serveSkills(deps, req, res) { fail(res, 405, 'method-not-allowed'); return; } - json(res, 200, { ok: true, ...(await admin.list()) }); + const inventory = await admin.list(); + json(res, 200, { ok: true, ...inventory, ...(await admin.listPlans()) }); return; } const actions = { - '/toggle': async (body) => admin.setEnabled(body.folder, body.enabled === true), - '/remove': async (body) => admin.remove(body.folder), - '/install': async (body) => admin.installFromGit(body.url), + '/detail': async (body) => ({ ...(await admin.detail(body.folder)) }), + '/toggle': async (body) => ({ ...(await admin.setEnabled(body.folder, body.enabled === true)) }), + // One-shot install kept for the standalone page; the card uses plan/commit. + '/install': async (body) => ({ ...(await admin.installFromGit(body.url)) }), + '/install/plan': async (body) => ({ ...(await admin.prepareInstall(body.url)) }), + '/install/commit': async (body) => ({ ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) }), + '/install/cancel': async (body) => ({ ...(await admin.cancelInstall({ planId: body.planId })) }), + '/uninstall/plan': async (body) => { + const plan = await admin.uninstallPlan(body.folder); + return { ...plan, token: issueUninstallToken(plan.folder) }; + }, + '/remove': async (body) => { + if (body.confirmed !== true) { + throw new SkillAdminError('confirmation_required', '删除必须显式确认:先预览影响,再传 confirmed=true。'); + } + const folder = typeof body.folder === 'string' ? body.folder : ''; + if (!useUninstallToken(folder, body.token)) { + throw new SkillAdminError('confirmation_required', '卸载确认已过期或与该技能不匹配,请重新预览。'); + } + return { ...(await admin.remove(folder)) }; + }, }; const action = actions[suffix]; if (action === undefined) { fail(res, 404, 'unknown-skill-route'); return; } - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); + const body = await jsonBody(req, res); + if (body === undefined) return; - } - if (!sameOrigin(req)) { - fail(res, 403, 'origin-rejected'); - return; - } - const type = (req.headers['content-type'] ?? '').toLowerCase(); - if (!type.startsWith('application/json')) { - fail(res, 415, 'json-required'); - return; - } - let body; - try { - body = JSON.parse(await readBody(req)); - } - catch { - fail(res, 400, 'invalid-json'); - return; - } - if (body === null || typeof body !== 'object' || Array.isArray(body)) { - fail(res, 400, 'invalid-body'); - return; - } try { json(res, 200, { ok: true, ...(await action(body)) }); } catch (error) { if (error instanceof SkillAdminError) { json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message }); + return; } - else { - json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) }); - } + json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) }); } } /** Build the exact-route table registered with the host web server. */ @@ -412,6 +566,11 @@ export function createRoutes(deps) { path: ROUTES.status, handler: (req, res) => serveStatus(deps, req, res), }, + { + kind: 'exact', + path: ROUTES.capabilities, + handler: (req, res) => serveCapabilities(deps, req, res), + }, { kind: 'exact', path: ROUTES.config, diff --git a/lib/skill-admin.js b/lib/skill-admin.js index 9076c27..daeca73 100644 --- a/lib/skill-admin.js +++ b/lib/skill-admin.js @@ -1,9 +1,9 @@ /** - * Local skill management, built into the plugin: list, enable/disable, - * real delete, and install from a git repository. + * Local skill management, built into the plugin: list, inspect, enable/disable, + * previewed install, previewed uninstall. * * This covers the everyday subset of a full skills manager. It manages - * only the DSH skills root (plus its own parking and trash areas) — the + * only the DSH skills root (plus its own parking and staging areas) — the * cloud sync engine keeps owning everything beyond the local disk. * * Enable/disable is deliberately mechanical: a disabled skill's folder @@ -14,20 +14,36 @@ * mistaken for deletions, and a parked cloud skill still receives its * cloud updates in place. * - * Delete is a real delete: the folder is removed recursively. The - * cloud copy is unaffected — local deletion never propagates to the - * center (the sync engine remembers the removal, so the same cloud - * version is not pulled back down either). + * Delete is a real delete: the folder is removed recursively. It is only + * reachable through a two-step contract (plan → confirm) because there is no + * trash area and nothing can be restored. The cloud copy is unaffected — + * local deletion never propagates to the center. + * + * Installation is staged: the repository is cloned into an isolated scratch + * directory, candidates are enumerated and described, and nothing enters the + * skills root until the caller commits an explicit selection. Repository code + * is never executed (no hooks, no install scripts), symlinks are never + * followed, and a colliding folder is always skipped instead of overwritten. */ +import { lstatSync } from 'node:fs'; import { execFile } from 'node:child_process'; -import { cp, mkdir, readFile, readdir, rename, rm, stat } from 'node:fs/promises'; -import { basename, join } from 'node:path'; +import { createHash, randomUUID } from 'node:crypto'; +import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { basename, dirname, join, resolve, sep } from 'node:path'; import { parseSkillFrontmatter } from "./skill-sync.js"; import { dshHome } from "./store.js"; /** The parking area for disabled skills. */ export function skillsHoldingDir() { return join(dshHome(), 'skills-disabled'); } +/** Isolated scratch space for staged installs; never inside the skills root. */ +export function skillsStagingDir() { + return join(dshHome(), '.cloud-memory-staging'); +} +/** Persisted plan records (metadata only: ids, counts, timestamps). */ +export function skillPlansPath() { + return join(dshHome(), '.cloud-memory-plans.json'); +} /** A management failure with a stable machine-readable code. */ export class SkillAdminError extends Error { code; @@ -40,27 +56,55 @@ export class SkillAdminError extends Error { function fail(code, message) { throw new SkillAdminError(code, message); } +/** Hard caps so one hostile repository cannot exhaust the disk. */ +const MAX_SKILL_FILES = 1500; +const MAX_SKILL_BYTES = 4 * 1024 * 1024; +const MAX_CANDIDATES = 60; +const MAX_SKILL_MD_BYTES = 256 * 1024; +const PLAN_TTL_MS = 30 * 60_000; async function isDirectory(path) { return stat(path).then((s) => s.isDirectory()).catch(() => false); } -/** Count files below a directory, capped so a stray tree cannot hang us. */ -async function countFiles(dir, cap = 2000) { - let count = 0; +async function isSymlink(path) { + return lstat(path).then((s) => s.isSymbolicLink()).catch(() => false); +} +/** Synchronous variant, used inside `cp` filters where no await is possible. */ +function isSymlinkSync(path) { + try { + return lstatSync(path).isSymbolicLink(); + } + catch { + return true; + } +} +/** Files under one skill folder, skipping `.git` and never following links. */ +async function walkFiles(dir, cap = MAX_SKILL_FILES + 1) { + const out = []; const walk = async (sub) => { - if (count > cap) + if (out.length > cap) return; for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) { if (entry.name === '.git') continue; const rel = sub === '' ? entry.name : `${sub}/${entry.name}`; - if (entry.isDirectory()) + const abs = join(dir, rel); + if (entry.isSymbolicLink()) { + out.push({ path: rel, bytes: 0, script: false }); + continue; + } + if (entry.isDirectory()) { await walk(rel); - else if (entry.isFile()) - count += 1; + continue; + } + if (!entry.isFile()) + continue; + const size = await stat(abs).then((s) => s.size).catch(() => 0); + out.push({ path: rel, bytes: size, script: /\.(mjs|cjs|js|ts|ps1|sh|bat|cmd|py|rb|exe|dll)$/i.test(entry.name) }); } }; await walk(''); - return count; + out.sort((a, b) => (a.path < b.path ? -1 : 1)); + return out; } /** A folder name we are willing to move around: one path segment, no tricks. */ function checkFolder(folder) { @@ -75,11 +119,17 @@ export class SkillAdmin { constructor(deps) { this.deps = deps; } + plansFile() { + return this.deps.plansPath?.() ?? skillPlansPath(); + } + stagingRoot() { + return this.deps.stagingRoot?.() ?? skillsStagingDir(); + } guardSync() { if (this.deps.syncRunning()) fail('sync_running', '技能同步正在进行,请稍候再试。'); } - async syncUploaded() { + async uploaded() { try { const parsed = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8')); if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { @@ -106,34 +156,47 @@ export class SkillAdmin { origin = 'cloud'; try { const parsed = JSON.parse(delivery); - const value = parsed.revision; + const value = parsed?.revision; if (typeof value === 'number') revision = value; } - catch { /* a corrupt manifest still marks cloud origin */ } + catch { + // A corrupt manifest still marks cloud origin. + } } else { for (const record of Object.values(uploaded)) { if (record.folder === folder) { origin = 'uploaded'; - revision = record.revision; + if (typeof record.revision === 'number') + revision = record.revision; break; } } } + const files = await walkFiles(dir); + const bytes = files.reduce((sum, file) => sum + file.bytes, 0); + const installedAt = await stat(join(dir, 'SKILL.md')).then((s) => new Date(s.mtimeMs).toISOString()).catch(() => undefined); + const name = frontmatter.name; return { folder, - name: frontmatter.name ?? folder, - description: (frontmatter.description ?? '').slice(0, 300), + name: typeof name === 'string' && name !== '' ? name : folder, + description: String(frontmatter.description ?? '').slice(0, 300), enabled, origin, ...(revision === undefined ? {} : { revision }), - files: await countFiles(dir), + files: files.length, + bytes, + ...(installedAt === undefined ? {} : { installedAt }), + skillSha256: createHash('sha256').update(markdown).digest('hex'), + location: enabled ? 'root' : 'holding', + ownerManager: 'dsh-cloud-memory', + writable: true, }; } /** Inventory of the skills root and the parking area. */ async list() { - const uploaded = await this.syncUploaded(); + const uploaded = await this.uploaded(); const skills = []; const scan = async (area, enabled) => { for (const entry of await readdir(area, { withFileTypes: true }).catch(() => [])) { @@ -147,7 +210,7 @@ export class SkillAdmin { await scan(this.deps.skillsRoot(), true); await scan(this.deps.holdingDir(), false); skills.sort((a, b) => (a.folder < b.folder ? -1 : 1)); - return { skills }; + return { skills, root: this.deps.skillsRoot(), holding: this.deps.holdingDir(), staging: this.stagingRoot() }; } /** Locate a skill folder across the root and the parking area. */ async locate(folder) { @@ -159,6 +222,29 @@ export class SkillAdmin { return { area: 'holding', dir: parkedDir }; return undefined; } + /** Everything one skill panel needs, including its SKILL.md text. */ + async detail(folderInput) { + const folder = checkFolder(folderInput); + const found = await this.locate(folder); + if (found === undefined) + fail('not_found', `没有找到技能:${folder}`); + if (await isSymlink(found.dir)) + fail('unsupported', `技能目录是链接,不在这里管理:${folder}`); + const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded()); + if (entry === undefined) + fail('not_found', `技能缺少 SKILL.md:${folder}`); + const files = await walkFiles(found.dir); + const raw = await readFile(join(found.dir, 'SKILL.md'), 'utf8').catch(() => ''); + const truncated = Buffer.byteLength(raw) > MAX_SKILL_MD_BYTES; + return { + skill: entry, + dir: found.dir, + files, + totalBytes: files.reduce((sum, file) => sum + file.bytes, 0), + truncated, + skillMd: truncated ? Buffer.from(raw).subarray(0, MAX_SKILL_MD_BYTES).toString('utf8') : raw, + }; + } /** Enable (move back into the root) or disable (park) one skill. */ async setEnabled(folderInput, enabled) { this.guardSync(); @@ -168,33 +254,112 @@ export class SkillAdmin { fail('not_found', `没有找到技能:${folder}`); const targetArea = enabled ? 'root' : 'holding'; if (found.area === targetArea) - return { folder, enabled }; + return { folder, enabled, note: this.effectNote(enabled) }; const targetRoot = enabled ? this.deps.skillsRoot() : this.deps.holdingDir(); await mkdir(targetRoot, { recursive: true }); const target = join(targetRoot, folder); if (await isDirectory(target)) fail('collision', `目标位置已存在同名技能:${folder}`); - await rename(found.dir, target); + try { + await rename(found.dir, target); + } + catch (error) { + // A cross-device move must not leave the skill half-copied: fall back to a + // plain copy only for EXDEV, and only then remove the source. + if (error.code !== 'EXDEV') + throw error; + await cp(found.dir, target, { recursive: true, filter: (source) => !source.split(/[\\/]/).includes('.git') }); + await rm(found.dir, { recursive: true, force: true }); + } this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`); - return { folder, enabled }; + return { folder, enabled, note: this.effectNote(enabled) }; } - /** Delete one skill for real: its folder is removed recursively. */ + /** The enable/disable mechanism is a directory move, not a live switch. */ + effectNote(enabled) { + return enabled + ? '已放回技能目录:新会话可见;已在运行的会话可能仍保留旧状态。' + : '已移出技能目录:新会话不再加载;已经加载的会话不受影响。'; + } + /** Preview of what an uninstall would remove. Nothing is deleted yet. */ + async uninstallPlan(folderInput) { + const folder = checkFolder(folderInput); + const found = await this.locate(folder); + if (found === undefined) + fail('not_found', `没有找到技能:${folder}`); + if (await isSymlink(found.dir)) + fail('unsupported', `技能目录是链接,不在这里删除:${folder}`); + const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded()); + const files = await walkFiles(found.dir); + return { + folder, + dir: found.dir, + area: found.area, + files: files.length, + bytes: files.reduce((sum, file) => sum + file.bytes, 0), + scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20), + origin: entry?.origin ?? 'unknown', + ...(entry?.revision === undefined ? {} : { cloudRevision: entry.revision }), + recoverable: false, + note: '本机删除不可恢复(没有回收站)。云端副本不受影响,同步引擎也不会把同一版本再次拉回。', + }; + } + /** + * Delete one skill for real: its folder is removed recursively. + * + * The route layer requires a plan token plus `confirmed: true`; this method + * itself stays usable by the verification harness and by trusted callers. + */ async remove(folderInput) { this.guardSync(); const folder = checkFolder(folderInput); const found = await this.locate(folder); if (found === undefined) fail('not_found', `没有找到技能:${folder}`); + const files = await walkFiles(found.dir); + const bytes = files.reduce((sum, file) => sum + file.bytes, 0); await rm(found.dir, { recursive: true, force: true }); this.deps.log(`skill deleted: ${folder}`); - return { folder }; + return { folder, dir: found.dir, files: files.length, bytes }; + } + async readPlans() { + try { + const parsed = JSON.parse(await readFile(this.plansFile(), 'utf8')); + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + const plans = parsed.plans; + if (Array.isArray(plans)) + return { version: 1, plans: plans }; + } + } + catch { + // Missing or torn file: no plans. + } + return { version: 1, plans: [] }; + } + async writePlans(file) { + const path = this.plansFile(); + await mkdir(dirname(path), { recursive: true }); + const temporary = `${path}.tmp`; + await writeFile(temporary, `${JSON.stringify(file, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }); + await rename(temporary, path); + } + /** Drop expired plans and their staging trees. */ + async sweepPlans(file) { + const now = Date.now(); + const live = []; + for (const plan of file.plans) { + if (plan.expiresAt > now) { + live.push(plan); + continue; + } + await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { }); + } + return { version: 1, plans: live }; } /** - * Install every skill found in a git repository (https:// or file://). - * The clone is shallow and never executes repository code; folders - * that collide with existing skills are skipped, never overwritten. + * Stage a git repository and describe its skills. Nothing enters the skills + * root here; the caller picks folders and commits. */ - async installFromGit(urlInput) { + async prepareInstall(urlInput) { this.guardSync(); if (typeof urlInput !== 'string') fail('invalid_url', '请提供仓库地址。'); @@ -202,61 +367,198 @@ export class SkillAdmin { if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) { fail('invalid_url', '只接受 https:// 或 file:// 的 git 仓库地址。'); } - const scratch = join(dshHome(), `.cloud-memory-clone-${process.pid}-${Date.now().toString(36)}`); + const stagingRoot = this.stagingRoot(); + await mkdir(stagingRoot, { recursive: true }); + const planId = `plan_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`; + const stagingDir = join(stagingRoot, planId); try { await new Promise((resolvePromise, rejectPromise) => { - execFile('git', ['clone', '--depth', '1', '--no-tags', '--', url, scratch], { timeout: 120_000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 }, (error) => (error ? rejectPromise(error) : resolvePromise())); + execFile('git', ['clone', '--depth', '1', '--no-tags', '--', url, stagingDir], { timeout: 120_000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 }, (error) => (error ? rejectPromise(error) : resolvePromise())); }); } - catch { - await rm(scratch, { recursive: true, force: true }).catch(() => { }); - fail('git_failed', '仓库克隆失败(地址不可达、需要登录,或本机没有 git)。'); + catch (error) { + await rm(stagingDir, { recursive: true, force: true }).catch(() => { }); + const code = error.code; + fail('git_failed', code === 'ENOENT' + ? '本机没有 git 命令,无法从仓库安装技能。' + : '仓库克隆失败(地址不可达、需要登录,或不是 git 仓库)。'); } - try { - const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill'; - const candidates = []; - const collect = async (dir, depth) => { - if (await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) !== undefined) { - candidates.push({ folder: dir === scratch ? repoName : basename(dir), dir }); - return; - } - if (depth >= 3) - return; - for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { - if (entry.isDirectory() && entry.name !== '.git') - await collect(join(dir, entry.name), depth + 1); - } - }; - await collect(scratch, 0); - if (candidates.length === 0) - fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。'); - const installed = []; - const skipped = []; - await mkdir(this.deps.skillsRoot(), { recursive: true }); - for (const candidate of candidates) { - let folder = candidate.folder; - try { - folder = checkFolder(folder); - } - catch { - skipped.push({ name: candidate.folder, reason: 'invalid_name' }); - continue; - } - if ((await this.locate(folder)) !== undefined) { - skipped.push({ name: folder, reason: 'already_exists' }); - continue; - } - await cp(candidate.dir, join(this.deps.skillsRoot(), folder), { - recursive: true, - filter: (source) => !source.split(/[\\/]/).includes('.git'), - }); - installed.push(folder); - this.deps.log(`skill installed from git: ${folder}`); + const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill'; + const found = []; + const collect = async (dir, depth) => { + if (found.length >= MAX_CANDIDATES) + return; + const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined); + if (markdown !== undefined) { + found.push({ folder: dir === stagingDir ? repoName : basename(dir), dir }); + return; } - return { installed, skipped }; + if (depth >= 3) + return; + for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + if (entry.isDirectory() && entry.name !== '.git' && !entry.isSymbolicLink()) { + await collect(join(dir, entry.name), depth + 1); + } + } + }; + await collect(stagingDir, 0); + if (found.length === 0) { + await rm(stagingDir, { recursive: true, force: true }).catch(() => { }); + fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。'); } - finally { - await rm(scratch, { recursive: true, force: true }).catch(() => { }); + const candidates = []; + for (const candidate of found) { + const markdown = await readFile(join(candidate.dir, 'SKILL.md'), 'utf8').catch(() => ''); + const frontmatter = parseSkillFrontmatter(markdown); + const files = await walkFiles(candidate.dir); + const bytes = files.reduce((sum, file) => sum + file.bytes, 0); + const existing = await this.locate(candidate.folder); + let problem; + try { + checkFolder(candidate.folder); + } + catch { + problem = '目录名不合法,不能作为技能目录'; + } + if (problem === undefined && files.length > MAX_SKILL_FILES) + problem = `文件过多(>${MAX_SKILL_FILES})`; + if (problem === undefined && bytes > MAX_SKILL_BYTES) + problem = `体积过大(>${MAX_SKILL_BYTES} 字节)`; + const name = frontmatter.name; + candidates.push({ + folder: candidate.folder, + name: typeof name === 'string' && name !== '' ? name : candidate.folder, + description: String(frontmatter.description ?? '').slice(0, 300), + files: files.length, + bytes, + scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20), + conflict: existing !== undefined, + ...(existing === undefined ? {} : { conflictLocation: existing.area }), + ...(problem === undefined ? {} : { problem }), + }); } + const plan = { + id: planId, + kind: 'install', + url, + createdAt: Date.now(), + expiresAt: Date.now() + PLAN_TTL_MS, + stagingDir, + candidates, + }; + const file = await this.sweepPlans(await this.readPlans()); + file.plans.push(plan); + await this.writePlans(file); + this.deps.log(`skill install staged: ${url} -> ${planId} (${candidates.length} candidates)`); + return { + planId, + url, + expiresAt: plan.expiresAt, + candidates: candidates.map((candidate) => ({ ...candidate, id: candidate.folder })), + }; + } + /** Install the folders the user picked from a staged plan. */ + async commitInstall(planInput) { + this.guardSync(); + const planId = typeof planInput.planId === 'string' ? planInput.planId : ''; + if (planId === '') + fail('invalid_plan', '缺少安装计划 id。'); + const selection = Array.isArray(planInput.folders) ? planInput.folders : []; + const file = await this.sweepPlans(await this.readPlans()); + const plan = file.plans.find((item) => item.id === planId); + if (plan === undefined) { + await this.writePlans(file); + fail('plan_expired', '安装计划已过期或不存在,请重新拉取仓库。'); + } + const wanted = selection.map((value) => checkFolder(value)); + const installed = []; + const skipped = []; + const skillsRoot = resolve(this.deps.skillsRoot()); + await mkdir(skillsRoot, { recursive: true }); + for (const candidate of plan.candidates) { + if (!wanted.includes(candidate.folder)) + continue; + if (candidate.problem !== undefined) { + skipped.push({ folder: candidate.folder, reason: candidate.problem }); + continue; + } + const existing = await this.locate(candidate.folder); + if (existing !== undefined) { + skipped.push({ folder: candidate.folder, reason: existing.area === 'holding' ? 'already_exists_disabled' : 'already_exists' }); + continue; + } + const stagingRoot = resolve(plan.stagingDir); + const source = candidate.folder === basename(plan.stagingDir) ? stagingRoot : resolve(stagingRoot, candidate.folder); + const target = resolve(skillsRoot, candidate.folder); + // Both sides must stay inside their own root: a crafted plan file cannot + // make this write outside the skills directory. + if (!source.startsWith(stagingRoot) || !target.startsWith(`${skillsRoot}${sep}`)) { + skipped.push({ folder: candidate.folder, reason: 'path_escape' }); + continue; + } + await cp(source, target, { + recursive: true, + // `.git` never travels with a skill, and a link could point outside the + // repository: both are dropped rather than copied. + filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath), + }); + installed.push(candidate.folder); + this.deps.log(`skill installed from git: ${candidate.folder}`); + } + const remaining = plan.candidates + .filter((candidate) => !installed.includes(candidate.folder)) + .map((candidate) => candidate.folder); + file.plans = file.plans.filter((item) => item.id !== planId); + await this.writePlans(file); + await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { }); + return { installed, skipped, remaining }; + } + /** Throw away a staged plan and its clone. */ + async cancelInstall(planInput) { + const planId = typeof planInput.planId === 'string' ? planInput.planId : ''; + if (planId === '') + fail('invalid_plan', '缺少安装计划 id。'); + const file = await this.sweepPlans(await this.readPlans()); + const plan = file.plans.find((item) => item.id === planId); + file.plans = file.plans.filter((item) => item.id !== planId); + await this.writePlans(file); + if (plan !== undefined) + await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { }); + return { cancelled: planId }; + } + /** + * Legacy one-shot install, kept for the standalone `/cloud-memory/skills` + * page: stage the repository, then install every candidate that neither + * collides with an existing skill nor trips a limit. It still never + * overwrites and never executes repository content. + */ + async installFromGit(urlInput) { + const plan = await this.prepareInstall(urlInput); + const folders = plan.candidates + .filter((candidate) => candidate.conflict !== true && candidate.problem === undefined) + .map((candidate) => candidate.folder); + const result = await this.commitInstall({ planId: plan.planId, folders }); + const skipped = plan.candidates + .filter((candidate) => !result.installed.includes(candidate.folder)) + .map((candidate) => ({ + name: candidate.folder, + reason: candidate.conflict === true + ? (candidate.conflictLocation === 'holding' ? 'already_exists_disabled' : 'already_exists') + : candidate.problem ?? 'skipped', + })); + return { installed: result.installed, skipped }; + } + /** Pending plans, so a reloaded page can resume a staged install. */ + async listPlans() { + const file = await this.sweepPlans(await this.readPlans()); + await this.writePlans(file); + return { + plans: file.plans.map((plan) => ({ + planId: plan.id, + url: plan.url, + expiresAt: plan.expiresAt, + folders: plan.candidates.map((candidate) => candidate.folder), + })), + }; } } diff --git a/lib/store.js b/lib/store.js index b8d0cba..4af23f9 100644 --- a/lib/store.js +++ b/lib/store.js @@ -14,7 +14,7 @@ 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"; +import { DEFAULT_SETTINGS, isPlaceholderBaseUrl, normalizeBaseUrl, originOf, settingsFromConfig } from "./config.js"; /** `$DSH_HOME` (or `~/.dsh`) — the same resolution DSH core uses. */ export function dshHome() { const fromEnv = process.env.DSH_HOME; @@ -179,6 +179,8 @@ export class SettingsStore { memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory) }, summaryToken: { configured: summary !== '', masked: summary === '' ? '' : maskToken(summary) }, statePath: this.file, + baseUrlConfigured: !isPlaceholderBaseUrl(settings.baseUrl), + baseUrlOrigin: originOf(settings.baseUrl), }; } /** @@ -190,6 +192,9 @@ export class SettingsStore { */ patch(patch) { const next = { ...this.state }; + const beforeOrigin = originOf(this.settings().baseUrl); + /** Tokens this very request supplied; they survive an address change. */ + const provided = []; if (patch.enabled !== undefined) { if (typeof patch.enabled !== 'boolean') return { ok: false, error: 'enabled must be a boolean' }; @@ -212,12 +217,14 @@ export class SettingsStore { if (!activityToken.startsWith('cmt_')) return { ok: false, error: 'activity token must start with cmt_' }; next.activityToken = activityToken; + provided.push('activity'); } 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; + provided.push('memory'); } if (patch.requestTimeoutMs !== undefined) { const requestTimeoutMs = clampInt(patch.requestTimeoutMs, 1000, 60_000); @@ -247,6 +254,7 @@ export class SettingsStore { if (!summaryToken.startsWith('cmt_')) return { ok: false, error: 'summary token must start with cmt_' }; next.summaryToken = summaryToken; + provided.push('summary'); } if (patch.clearSummaryToken === true) delete next.summaryToken; @@ -254,9 +262,29 @@ export class SettingsStore { delete next.activityToken; if (patch.clearMemoryToken === true) delete next.memoryToken; + // Switching the service origin must not hand the previous service's + // bearer tokens to the new one: everything this request did not explicitly + // replace is dropped, and the caller is told so it can ask to re-authenticate. + const afterOrigin = originOf(next.baseUrl ?? this.configDefaults.baseUrl); + const clearedTokens = []; + if (beforeOrigin !== '' && afterOrigin !== '' && beforeOrigin !== afterOrigin) { + const credentials = [ + ['activity', 'activityToken'], + ['memory', 'memoryToken'], + ['summary', 'summaryToken'], + ]; + for (const [label, key] of credentials) { + if (next[key] === undefined) + continue; + if (provided.includes(label)) + continue; + delete next[key]; + clearedTokens.push(label); + } + } this.write(next); this.state = next; - return { ok: true }; + return clearedTokens.length === 0 ? { ok: true } : { ok: true, clearedTokens }; } /** File size in bytes, for a "sidecar exists" hint in the card. */ size() { diff --git a/package.json b/package.json index 24d894c..fd56cfc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-cloud-memory", - "version": "0.4.1", + "version": "0.5.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", diff --git a/src/api.ts b/src/api.ts index ae844a1..557a100 100644 --- a/src/api.ts +++ b/src/api.ts @@ -301,6 +301,25 @@ export class CloudClient { return this.request('POST', '/activity/turn', payload, token) } + /** + * Read-only reachability probe: any HTTP answer (even 401 or 404) proves the + * host is up. This is what separates "服务不可达" from "令牌无效" in the card, + * and it never sends a credential. + */ + async reach(): Promise<{ ok: boolean; status: number; message: string }> { + try { + const response = await fetch(`${this.options.baseUrl()}/status`, { + method: 'GET', + headers: { Accept: 'application/json' }, + signal: AbortSignal.timeout(this.options.timeoutMs()), + }) + return { ok: true, status: response.status, message: `服务可达(HTTP ${response.status})` } + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + return { ok: false, status: 0, message: `服务不可达:${reason}` } + } + } + /** Stage one turn summary as pending proposals (summary:write token). */ submitSummary(payload: SummaryPayload, token: string): Promise> { return this.request('POST', '/activity/summary', payload, token) diff --git a/src/config.ts b/src/config.ts index ddc9bfc..cc67ce1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -68,6 +68,33 @@ export function normalizeBaseUrl(value: unknown): string | undefined { } } +/** + * A packaged default that was never replaced by a real service. + * + * `cordis.patch.yml` ships `https://your-memory-host/...` so a fresh profile + * boots without touching a production endpoint. Such an address must be shown + * as "未配置服务" — never as a healthy connection. + */ +export function isPlaceholderBaseUrl(value: string): boolean { + const normalized = normalizeBaseUrl(value) + if (normalized === undefined) return true + try { + const host = new URL(normalized).hostname.toLowerCase() + return host === 'your-memory-host' || host === 'example.com' + } catch { + return true + } +} + +/** Service origin of one base URL, or '' when it cannot be parsed. */ +export function originOf(value: string): string { + try { + return new URL(value).origin + } catch { + return '' + } +} + /** 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 diff --git a/src/index.ts b/src/index.ts index 4c5434e..b31b314 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,7 +26,7 @@ export const name = 'dsh-cloud-memory' export const inject = ['webServer'] /** Version reported by the status card. */ -const VERSION = '0.4.1' +const VERSION = '0.5.0' /** How often the skill directory is reconciled with the cloud center. */ const SKILL_SYNC_INTERVAL_MS = 15 * 60_000 diff --git a/src/routes.ts b/src/routes.ts index a85bb90..933a1aa 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -2,16 +2,22 @@ * 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) + * - `GET /cloud-memory` configuration page (HTML) + * - `GET /cloud-memory/status` settings + reporter counters + capabilities + * - `GET /cloud-memory/capabilities` what this build can and cannot do + * - `PUT /cloud-memory/config` apply a settings patch + * - `POST /cloud-memory/login` password sign-in, mints the tokens + * - `POST /cloud-memory/test` read-only checks, per credential + * - `POST /cloud-memory/flush` retry the queued reports + * - `GET /cloud-memory/skills/api` skill inventory + pending plans + * - `POST /cloud-memory/skills/*` detail / toggle / install plan / commit / uninstall * * 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. + * + * Skill writes follow a plan → commit contract: a destructive operation is + * never reachable in one request, and a client-supplied path is never trusted. */ import type { IncomingMessage, ServerResponse } from 'node:http' import type { CloudClient } from './api.ts' @@ -24,11 +30,13 @@ import type { SkillSyncStats } from './skill-sync.ts' import { SkillAdminError } from './skill-admin.ts' import type { SkillAdmin } from './skill-admin.ts' import { renderSkillsPage } from './skill-page.ts' +import { randomUUID } from 'node:crypto' /** Route constants — kept in one place so the client half can reuse them. */ export const ROUTES = { page: '/cloud-memory', status: '/cloud-memory/status', + capabilities: '/cloud-memory/capabilities', config: '/cloud-memory/config', login: '/cloud-memory/login', test: '/cloud-memory/test', @@ -47,10 +55,51 @@ export interface RouteDeps { client: () => CloudClient /** Latest skill-sync stats, when the engine is wired in. */ skills?: () => SkillSyncStats - /** Local skill management (list / toggle / trash / install), when wired in. */ + /** Local skill management (list / toggle / install / uninstall), when wired in. */ admin?: SkillAdmin } +/** One feature flag the card reads before it renders a control. */ +export interface CapabilityReport { + version: string + features: { + connection: boolean + identitySwitch: boolean + skills: boolean + skillInstallPlans: boolean + skillUninstallPlan: boolean + skillsSync: boolean + skillsMarketplace: boolean + mcpBridge: 'host-plugin' | 'unavailable' + } + notes: string[] +} + +/** What this build actually implements, stated per feature. */ +function capabilities(deps: RouteDeps): CapabilityReport { + return { + version: deps.version, + features: { + connection: true, + identitySwitch: true, + skills: deps.admin !== undefined, + skillInstallPlans: deps.admin !== undefined, + skillUninstallPlan: deps.admin !== undefined, + skillsSync: deps.skills !== undefined, + // No verified marketplace provider is wired in this build; the card says + // so instead of showing a fake search box. + skillsMarketplace: false, + // The MCP bridge is provided by the host `dsh-mcp-connector` plugin over + // the same origin; the browser half probes it at runtime. + mcpBridge: 'host-plugin', + }, + notes: [ + '技能市场尚未接入经验证的来源,本版不提供搜索与安装闭环。', + 'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。', + ], + } +} + /** Collect a request body as UTF-8 text. */ async function readBody(req: IncomingMessage, maxBytes = MAX_BODY_BYTES): Promise { const chunks: Buffer[] = [] @@ -95,17 +144,75 @@ function fail(res: ServerResponse, status: number, message: string, asHtml = fal res.end(text) } +/** + * Read one JSON object body, or answer the request and return undefined. + * + * The method, origin and content-type gates live here so every write route + * cannot forget one of them. + */ +async function jsonBody(req: IncomingMessage, res: ServerResponse): Promise | undefined> { + if (req.method !== 'POST' && req.method !== 'PUT') { + fail(res, 405, 'method-not-allowed') + return undefined + } + if (!sameOrigin(req)) { + fail(res, 403, 'origin-rejected') + return undefined + } + const type = (req.headers['content-type'] ?? '').toLowerCase() + if (!type.startsWith('application/json')) { + fail(res, 415, 'json-required') + return undefined + } + let parsed: unknown + try { + parsed = JSON.parse(await readBody(req)) + } catch (error) { + fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json') + return undefined + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + fail(res, 400, 'invalid-body') + return undefined + } + return parsed as Record +} + +/** One credential check as the card renders it. */ +type CheckState = 'ok' | 'unconfigured' | 'invalid' | 'forbidden' | 'unreachable' | 'error' + +interface CheckItem { + id: string + label: string + state: CheckState + message: string +} + +/** Last test run, kept in memory so the card can show "最后检查". */ +let lastCheck: { at: number; checks: CheckItem[] } | null = null + +/** + * Uninstall confirmations. + * + * A preview issues a single-use token bound to one folder; the delete route + * refuses without it, so a stray click cannot remove a skill. + */ +const uninstallTokens = new Map() +const UNINSTALL_TOKEN_TTL_MS = 10 * 60_000 + /** The payload the page and the client card both consume. */ function statusPayload(deps: RouteDeps): Record { - const view = deps.store.describe() - const tokens: Record<'activity' | 'memory' | 'summary', TokenView> = { - activity: view.activityToken, - memory: view.memoryToken, - summary: view.summaryToken, + const view: SettingsView = deps.store.describe() + const tokens = { + activity: view.activityToken as TokenView, + memory: view.memoryToken as TokenView, + summary: view.summaryToken as TokenView, } const settings = { enabled: view.enabled, baseUrl: view.baseUrl, + baseUrlConfigured: view.baseUrlConfigured, + baseUrlOrigin: view.baseUrlOrigin, clientId: view.clientId, requestTimeoutMs: view.requestTimeoutMs, defaultK: view.defaultK, @@ -115,7 +222,13 @@ function statusPayload(deps: RouteDeps): Record { skillsDir: view.skillsDir, } return { - ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot(), + ok: true, + settings, + tokens, + settingsPath: view.statePath, + reporter: deps.reporter.snapshot(), + lastCheck, + capabilities: capabilities(deps), ...(deps.skills === undefined ? {} : { skills: deps.skills() }), } } @@ -145,6 +258,15 @@ function serveStatus(deps: RouteDeps, req: IncomingMessage, res: ServerResponse) json(res, 200, statusPayload(deps)) } +/** `GET /cloud-memory/capabilities`. */ +function serveCapabilities(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): void { + if (req.method !== 'GET') { + fail(res, 405, 'method-not-allowed') + return + } + json(res, 200, { ok: true, ...capabilities(deps) }) +} + /** `PUT /cloud-memory/config`. */ async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { if (req.method !== 'PUT' && req.method !== 'POST') { @@ -176,10 +298,21 @@ async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerRes fail(res, 400, result.error ?? 'invalid-patch') return } - json(res, 200, statusPayload(deps)) + json(res, 200, { + ...statusPayload(deps), + ...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }), + }) } -/** `POST /cloud-memory/test` — validate both tokens without recording anything. */ +/** Map one failed credential probe onto a check state. */ +function checkState(error: { status: number; code: string }): CheckState { + if (error.status === 0) return 'unreachable' + if (error.status === 401) return 'invalid' + if (error.status === 403) return 'forbidden' + return 'error' +} + +/** `POST /cloud-memory/test` — read-only checks, one per credential. */ async function serveTest(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed') @@ -190,40 +323,68 @@ async function serveTest(deps: RouteDeps, req: IncomingMessage, res: ServerRespo return } const client = deps.client() + const checks: CheckItem[] = [] + const settings = deps.store.settings() + + const reach = await client.reach() + checks.push({ + id: 'network', + label: '服务地址', + state: reach.ok ? 'ok' : 'unreachable', + message: deps.store.describe().baseUrlConfigured === false ? '服务地址还是打包默认值,请先填写真实地址。' : reach.message, + }) + const activityToken = deps.store.activityToken() + if (activityToken === '') { + checks.push({ id: 'activity', label: '活动上报权限(activity:write)', state: 'unconfigured', message: '未配置令牌' }) + } else { + const probe = await client.probeActivity(activityToken) + checks.push({ + id: 'activity', + label: '活动上报权限(activity:write)', + state: probe.ok ? 'ok' : checkState(probe.error), + message: probe.ok ? '鉴权通过(只验证权限,不代表已写入一条上报)' : describeError(probe.error), + }) + } + const memoryToken = deps.store.memoryToken() - - 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) } - })() + if (memoryToken === '') { + checks.push({ id: 'memory', label: '记忆读写权限(memory:write)', state: 'unconfigured', message: '未配置令牌' }) + } else { + const probe = await client.projects() + checks.push({ + id: 'memory', + label: '记忆读写权限(memory:write)', + state: probe.ok ? 'ok' : checkState(probe.error), + message: probe.ok ? `鉴权通过(${(probe.data.projects ?? []).length} 个项目)` : describeError(probe.error), + }) + } const summaryToken = deps.store.summaryToken() - const summary = !deps.store.settings().summaryEnabled - ? { ok: false, message: '自动摘要已关闭(可在下方勾选开启)' } - : summaryToken === '' - ? { ok: false, message: '未配置摘要令牌:留空则不做自动摘要' } - : await (async () => { - const probe = await client.probeSummary(summaryToken) - return probe.ok - ? { ok: true, message: '摘要令牌有效(只进待确认队列)' } - : { ok: false, message: describeError(probe.error) } - })() + if (!settings.summaryEnabled) { + checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '自动摘要已关闭' }) + } else if (summaryToken === '') { + checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '未配置摘要令牌(可选)' }) + } else { + const probe = await client.probeSummary(summaryToken) + checks.push({ + id: 'summary', + label: '摘要权限(summary:write)', + state: probe.ok ? 'ok' : checkState(probe.error), + message: probe.ok ? '鉴权通过(只进待确认队列)' : describeError(probe.error), + }) + } - json(res, 200, { ok: true, activity, memory, summary }) + lastCheck = { at: Date.now(), checks } + json(res, 200, { + ok: true, + checkedAt: lastCheck.at, + checks, + // Kept for the older card/page shape; both views read the same probes. + activity: { ok: checks[1]?.state === 'ok', message: checks[1]?.message ?? '' }, + memory: { ok: checks[2]?.state === 'ok', message: checks[2]?.message ?? '' }, + summary: { ok: checks[3]?.state === 'ok', message: checks[3]?.message ?? '' }, + }) } /** `POST /cloud-memory/flush`. */ @@ -240,21 +401,21 @@ async function serveFlush(deps: RouteDeps, req: IncomingMessage, res: ServerResp json(res, 200, { ok: true, ...result }) } -/** Labels attached to the two tokens this plugin asks the dashboard to mint. */ +/** Labels attached to the tokens this plugin asks the dashboard to mint. */ const TOKEN_LABELS = { activity: 'DSH desktop 活动上报', memory: 'DSH desktop 记忆读写', summary: 'DSH desktop 对话摘要', -} as const +} /** * `POST /cloud-memory/login` — sign in with the cloud account and exchange it - * for the two scoped tokens. + * for the 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. + * password → short-lived session cookie → tokens → cookie dropped. Only the + * tokens are persisted, so a later password change does not break the plugin + * and revoking a token does not reveal the password. */ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { if (req.method !== 'POST') { @@ -297,7 +458,6 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp json(res, 400, { ok: false, error: '用户名或密码过长' }) return } - const client = deps.client() const session = await client.login(username, password) if (!session.ok) { @@ -305,7 +465,6 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp json(res, status, { ok: false, error: describeError(session.error) }) return } - const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity) const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory) const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary) @@ -315,8 +474,7 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` }) return } - - const patch: Parameters[0] = {} + const patch: Record = {} if (activity.ok && typeof activity.data.token === 'string') patch.activityToken = activity.data.token if (memory.ok && typeof memory.data.token === 'string') patch.memoryToken = memory.data.token if (summary.ok && typeof summary.data.token === 'string') patch.summaryToken = summary.data.token @@ -325,7 +483,6 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp json(res, 500, { ok: false, error: applied.error }) return } - const failed = activity.ok ? memory : activity const partial = !activity.ok || !memory.ok json(res, 200, { @@ -345,35 +502,62 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp }) } - /** HTTP status for one skill-admin failure code. */ function adminStatus(code: string): number { switch (code) { case 'not_found': return 404 case 'invalid_name': - case 'invalid_url': return 400 + case 'invalid_url': + case 'invalid_plan': return 400 case 'collision': - case 'sync_running': return 409 + case 'sync_running': + case 'plan_expired': + case 'confirmation_required': + case 'unsupported': return 409 case 'no_skills_found': return 422 case 'git_failed': return 502 default: return 500 } } +/** Issue the single-use token a delete needs. */ +function issueUninstallToken(folder: string): string { + const token = `uninstall_${randomUUID()}` + uninstallTokens.set(folder, { token, expiresAt: Date.now() + UNINSTALL_TOKEN_TTL_MS }) + return token +} + +/** Consume one uninstall token; false when it is missing, stale or foreign. */ +function useUninstallToken(folder: string, token: unknown): boolean { + const record = uninstallTokens.get(folder) + if (record === undefined) return false + if (typeof token !== 'string' || token !== record.token) return false + if (record.expiresAt < Date.now()) { + uninstallTokens.delete(folder) + return false + } + uninstallTokens.delete(folder) + return true +} + /** * The skill management surface, one prefix route: - * `GET /cloud-memory/skills` the management page - * `GET /cloud-memory/skills/api` inventory JSON (skills + trash) - * `POST /cloud-memory/skills/toggle` { folder, enabled } - * `POST /cloud-memory/skills/remove` { folder } - * `POST /cloud-memory/skills/install` { url } + * `GET /cloud-memory/skills` the management page + * `GET /cloud-memory/skills/api` inventory JSON (skills + plans) + * `POST /cloud-memory/skills/detail` { folder } — one skill with SKILL.md + * `POST /cloud-memory/skills/toggle` { folder, enabled } + * `POST /cloud-memory/skills/install/plan` { url } — stage the repository + * `POST /cloud-memory/skills/install/commit` { planId, folders } + * `POST /cloud-memory/skills/install/cancel` { planId } + * `POST /cloud-memory/skills/uninstall/plan` { folder } — impact preview + * `POST /cloud-memory/skills/remove` { folder, token, confirmed: true } */ async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { - if (deps.admin === undefined) { + const admin = deps.admin + if (admin === undefined) { fail(res, 404, 'skills-admin-unavailable') return } - const admin = deps.admin const suffix = (req.url ?? '').split('?')[0]?.slice(ROUTES.skills.length) ?? '' if (suffix === '' || suffix === '/') { if (req.method !== 'GET' && req.method !== 'HEAD') { @@ -395,51 +579,50 @@ async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerRes fail(res, 405, 'method-not-allowed') return } - json(res, 200, { ok: true, ...(await admin.list()) }) + const inventory = await admin.list() + json(res, 200, { ok: true, ...inventory, ...(await admin.listPlans()) }) return } - const actions: Record) => Promise>> = { - '/toggle': async (body) => admin.setEnabled(body.folder, body.enabled === true), - '/remove': async (body) => admin.remove(body.folder), - '/install': async (body) => admin.installFromGit(body.url), + + type Handler = (body: Record) => Promise> + const actions: Record = { + '/detail': async (body) => ({ ...(await admin.detail(body.folder)) }), + '/toggle': async (body) => ({ ...(await admin.setEnabled(body.folder, body.enabled === true)) }), + // One-shot install kept for the standalone page; the card uses plan/commit. + '/install': async (body) => ({ ...(await admin.installFromGit(body.url)) }), + '/install/plan': async (body) => ({ ...(await admin.prepareInstall(body.url)) }), + '/install/commit': async (body) => ({ ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) }), + '/install/cancel': async (body) => ({ ...(await admin.cancelInstall({ planId: body.planId })) }), + '/uninstall/plan': async (body) => { + const plan = await admin.uninstallPlan(body.folder) + return { ...plan, token: issueUninstallToken(plan.folder) } + }, + '/remove': async (body) => { + if (body.confirmed !== true) { + throw new SkillAdminError('confirmation_required', '删除必须显式确认:先预览影响,再传 confirmed=true。') + } + const folder = typeof body.folder === 'string' ? body.folder : '' + if (!useUninstallToken(folder, body.token)) { + throw new SkillAdminError('confirmation_required', '卸载确认已过期或与该技能不匹配,请重新预览。') + } + return { ...(await admin.remove(folder)) } + }, } const action = actions[suffix] if (action === undefined) { fail(res, 404, 'unknown-skill-route') return } - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed') - return - } - if (!sameOrigin(req)) { - fail(res, 403, 'origin-rejected') - return - } - const type = (req.headers['content-type'] ?? '').toLowerCase() - if (!type.startsWith('application/json')) { - fail(res, 415, 'json-required') - return - } - let body: unknown + const body = await jsonBody(req, res) + if (body === undefined) return try { - body = JSON.parse(await readBody(req)) - } catch { - fail(res, 400, 'invalid-json') - return - } - if (body === null || typeof body !== 'object' || Array.isArray(body)) { - fail(res, 400, 'invalid-body') - return - } - try { - json(res, 200, { ok: true, ...(await action(body as Record)) }) + json(res, 200, { ok: true, ...(await action(body)) }) } catch (error) { if (error instanceof SkillAdminError) { json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message }) - } else { - json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) }) + return } + json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) }) } } @@ -456,6 +639,11 @@ export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] { path: ROUTES.status, handler: (req, res) => serveStatus(deps, req, res), }, + { + kind: 'exact', + path: ROUTES.capabilities, + handler: (req, res) => serveCapabilities(deps, req, res), + }, { kind: 'exact', path: ROUTES.config, diff --git a/src/skill-admin.ts b/src/skill-admin.ts index 49709e1..9541bb3 100644 --- a/src/skill-admin.ts +++ b/src/skill-admin.ts @@ -1,9 +1,9 @@ /** - * Local skill management, built into the plugin: list, enable/disable, - * real delete, and install from a git repository. + * Local skill management, built into the plugin: list, inspect, enable/disable, + * previewed install, previewed uninstall. * * This covers the everyday subset of a full skills manager. It manages - * only the DSH skills root (plus its own parking and trash areas) — the + * only the DSH skills root (plus its own parking and staging areas) — the * cloud sync engine keeps owning everything beyond the local disk. * * Enable/disable is deliberately mechanical: a disabled skill's folder @@ -14,14 +14,22 @@ * mistaken for deletions, and a parked cloud skill still receives its * cloud updates in place. * - * Delete is a real delete: the folder is removed recursively. The - * cloud copy is unaffected — local deletion never propagates to the - * center (the sync engine remembers the removal, so the same cloud - * version is not pulled back down either). + * Delete is a real delete: the folder is removed recursively. It is only + * reachable through a two-step contract (plan → confirm) because there is no + * trash area and nothing can be restored. The cloud copy is unaffected — + * local deletion never propagates to the center. + * + * Installation is staged: the repository is cloned into an isolated scratch + * directory, candidates are enumerated and described, and nothing enters the + * skills root until the caller commits an explicit selection. Repository code + * is never executed (no hooks, no install scripts), symlinks are never + * followed, and a colliding folder is always skipped instead of overwritten. */ +import { lstatSync } from 'node:fs' import { execFile } from 'node:child_process' -import { cp, mkdir, readFile, readdir, rename, rm, stat } from 'node:fs/promises' -import { basename, join } from 'node:path' +import { createHash, randomUUID } from 'node:crypto' +import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises' +import { basename, dirname, join, resolve, sep } from 'node:path' import { parseSkillFrontmatter } from './skill-sync.ts' import { dshHome } from './store.ts' @@ -30,10 +38,22 @@ export function skillsHoldingDir(): string { return join(dshHome(), 'skills-disabled') } +/** Isolated scratch space for staged installs; never inside the skills root. */ +export function skillsStagingDir(): string { + return join(dshHome(), '.cloud-memory-staging') +} + +/** Persisted plan records (metadata only: ids, counts, timestamps). */ +export function skillPlansPath(): string { + return join(dshHome(), '.cloud-memory-plans.json') +} + /** A management failure with a stable machine-readable code. */ export class SkillAdminError extends Error { - constructor(readonly code: string, message: string) { + code: string + constructor(code: string, message: string) { super(message) + this.code = code this.name = 'SkillAdminError' } } @@ -42,8 +62,96 @@ function fail(code: string, message: string): never { throw new SkillAdminError(code, message) } -/** One skill as the management page shows it. */ -export interface AdminSkill { +/** Hard caps so one hostile repository cannot exhaust the disk. */ +const MAX_SKILL_FILES = 1500 +const MAX_SKILL_BYTES = 4 * 1024 * 1024 +const MAX_CANDIDATES = 60 +const MAX_SKILL_MD_BYTES = 256 * 1024 +const PLAN_TTL_MS = 30 * 60_000 + +async function isDirectory(path: string): Promise { + return stat(path).then((s) => s.isDirectory()).catch(() => false) +} + +async function isSymlink(path: string): Promise { + return lstat(path).then((s) => s.isSymbolicLink()).catch(() => false) +} + +/** Synchronous variant, used inside `cp` filters where no await is possible. */ +function isSymlinkSync(path: string): boolean { + try { + return lstatSync(path).isSymbolicLink() + } catch { + return true + } +} + +/** Files under one skill folder, skipping `.git` and never following links. */ +async function walkFiles(dir: string, cap = MAX_SKILL_FILES + 1): Promise<{ path: string; bytes: number; script: boolean }[]> { + const out: { path: string; bytes: number; script: boolean }[] = [] + const walk = async (sub: string): Promise => { + if (out.length > cap) return + for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) { + if (entry.name === '.git') continue + const rel = sub === '' ? entry.name : `${sub}/${entry.name}` + const abs = join(dir, rel) + if (entry.isSymbolicLink()) { + out.push({ path: rel, bytes: 0, script: false }) + continue + } + if (entry.isDirectory()) { + await walk(rel) + continue + } + if (!entry.isFile()) continue + const size = await stat(abs).then((s) => s.size).catch(() => 0) + out.push({ path: rel, bytes: size, script: /\.(mjs|cjs|js|ts|ps1|sh|bat|cmd|py|rb|exe|dll)$/i.test(entry.name) }) + } + } + await walk('') + out.sort((a, b) => (a.path < b.path ? -1 : 1)) + return out +} + +/** A folder name we are willing to move around: one path segment, no tricks. */ +function checkFolder(folder: unknown): string { + if (typeof folder !== 'string' || folder === '' || folder.length > 128 || + folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0')) { + fail('invalid_name', `技能目录名无效:${String(folder)}`) + } + return folder +} + +/** One planned install candidate (metadata only). */ +interface InstallPlanCandidate { + folder: string + name: string + description: string + files: number + bytes: number + scripts: string[] + conflict: boolean + conflictLocation?: 'root' | 'holding' + problem?: string +} + +interface InstallPlan { + id: string + kind: 'install' + url: string + createdAt: number + expiresAt: number + stagingDir: string + candidates: InstallPlanCandidate[] +} + +interface PlansFile { + version: 1 + plans: InstallPlan[] +} + +/** The inventory row the card renders. */ +export interface SkillEntry { folder: string name: string description: string @@ -51,58 +159,45 @@ export interface AdminSkill { origin: 'cloud' | 'uploaded' | 'local' revision?: number files: number + bytes: number + installedAt?: string + skillSha256?: string + location: 'root' | 'holding' + ownerManager: string + writable: boolean } -/** Dependencies of one admin instance. */ export interface SkillAdminDeps { skillsRoot: () => string holdingDir: () => string - /** The sync sidecar (read-only here) for origin and revision facts. */ syncStatePath: () => string - /** True while a sync pass is running; mutations refuse meanwhile. */ syncRunning: () => boolean log: (message: string) => void -} - -async function isDirectory(path: string): Promise { - return stat(path).then((s) => s.isDirectory()).catch(() => false) -} - -/** Count files below a directory, capped so a stray tree cannot hang us. */ -async function countFiles(dir: string, cap = 2000): Promise { - let count = 0 - const walk = async (sub: string): Promise => { - if (count > cap) return - for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) { - if (entry.name === '.git') continue - const rel = sub === '' ? entry.name : `${sub}/${entry.name}` - if (entry.isDirectory()) await walk(rel) - else if (entry.isFile()) count += 1 - } - } - await walk('') - return count -} - -/** A folder name we are willing to move around: one path segment, no tricks. */ -function checkFolder(folder: unknown): string { - if ( - typeof folder !== 'string' || folder === '' || folder.length > 128 || - folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0') - ) { - fail('invalid_name', `技能目录名无效:${String(folder)}`) - } - return folder + /** Where plan metadata is persisted; defaults to `$DSH_HOME/.cloud-memory-plans.json`. */ + plansPath?: () => string + /** Where staged clones live; defaults to `$DSH_HOME/.cloud-memory-staging`. */ + stagingRoot?: () => string } export class SkillAdmin { - constructor(private readonly deps: SkillAdminDeps) {} + private readonly deps: SkillAdminDeps + constructor(deps: SkillAdminDeps) { + this.deps = deps + } + + private plansFile(): string { + return this.deps.plansPath?.() ?? skillPlansPath() + } + + private stagingRoot(): string { + return this.deps.stagingRoot?.() ?? skillsStagingDir() + } private guardSync(): void { if (this.deps.syncRunning()) fail('sync_running', '技能同步正在进行,请稍候再试。') } - private async syncUploaded(): Promise> { + private async uploaded(): Promise> { try { const parsed: unknown = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8')) if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { @@ -117,44 +212,61 @@ export class SkillAdmin { return {} } - private async describe(folder: string, dir: string, enabled: boolean, uploaded: Record): Promise { + private async describe( + folder: string, + dir: string, + enabled: boolean, + uploaded: Record, + ): Promise { const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) if (markdown === undefined) return undefined const frontmatter = parseSkillFrontmatter(markdown) - let origin: AdminSkill['origin'] = 'local' + let origin: SkillEntry['origin'] = 'local' let revision: number | undefined const delivery = await readFile(join(dir, '.manifest.json'), 'utf8').catch(() => undefined) if (delivery !== undefined) { origin = 'cloud' try { const parsed: unknown = JSON.parse(delivery) - const value = (parsed as { revision?: unknown }).revision + const value = (parsed as { revision?: unknown } | null)?.revision if (typeof value === 'number') revision = value - } catch { /* a corrupt manifest still marks cloud origin */ } + } catch { + // A corrupt manifest still marks cloud origin. + } } else { for (const record of Object.values(uploaded)) { if (record.folder === folder) { origin = 'uploaded' - revision = record.revision + if (typeof record.revision === 'number') revision = record.revision break } } } + const files = await walkFiles(dir) + const bytes = files.reduce((sum, file) => sum + file.bytes, 0) + const installedAt = await stat(join(dir, 'SKILL.md')).then((s) => new Date(s.mtimeMs).toISOString()).catch(() => undefined) + const name = frontmatter.name return { folder, - name: frontmatter.name ?? folder, - description: (frontmatter.description ?? '').slice(0, 300), + name: typeof name === 'string' && name !== '' ? name : folder, + description: String(frontmatter.description ?? '').slice(0, 300), enabled, origin, ...(revision === undefined ? {} : { revision }), - files: await countFiles(dir), + files: files.length, + bytes, + ...(installedAt === undefined ? {} : { installedAt }), + skillSha256: createHash('sha256').update(markdown).digest('hex'), + location: enabled ? 'root' : 'holding', + ownerManager: 'dsh-cloud-memory', + writable: true, } } /** Inventory of the skills root and the parking area. */ - async list(): Promise<{ skills: AdminSkill[] }> { - const uploaded = await this.syncUploaded() - const skills: AdminSkill[] = [] + async list(): Promise<{ skills: SkillEntry[]; root: string; holding: string; staging: string }> { + const uploaded = await this.uploaded() + const skills: SkillEntry[] = [] const scan = async (area: string, enabled: boolean): Promise => { for (const entry of await readdir(area, { withFileTypes: true }).catch(() => [])) { if (!entry.isDirectory() || entry.name.startsWith('.')) continue @@ -165,11 +277,11 @@ export class SkillAdmin { await scan(this.deps.skillsRoot(), true) await scan(this.deps.holdingDir(), false) skills.sort((a, b) => (a.folder < b.folder ? -1 : 1)) - return { skills } + return { skills, root: this.deps.skillsRoot(), holding: this.deps.holdingDir(), staging: this.stagingRoot() } } /** Locate a skill folder across the root and the parking area. */ - private async locate(folder: string): Promise<{ area: 'root' | 'holding'; dir: string } | undefined> { + async locate(folder: string): Promise<{ area: 'root' | 'holding'; dir: string } | undefined> { const rootDir = join(this.deps.skillsRoot(), folder) if (await isDirectory(rootDir)) return { area: 'root', dir: rootDir } const parkedDir = join(this.deps.holdingDir(), folder) @@ -177,100 +289,362 @@ export class SkillAdmin { return undefined } + /** Everything one skill panel needs, including its SKILL.md text. */ + async detail(folderInput: unknown): Promise<{ + skill: SkillEntry + dir: string + files: { path: string; bytes: number; script: boolean }[] + totalBytes: number + truncated: boolean + skillMd: string + }> { + const folder = checkFolder(folderInput) + const found = await this.locate(folder) + if (found === undefined) fail('not_found', `没有找到技能:${folder}`) + if (await isSymlink(found.dir)) fail('unsupported', `技能目录是链接,不在这里管理:${folder}`) + const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded()) + if (entry === undefined) fail('not_found', `技能缺少 SKILL.md:${folder}`) + const files = await walkFiles(found.dir) + const raw = await readFile(join(found.dir, 'SKILL.md'), 'utf8').catch(() => '') + const truncated = Buffer.byteLength(raw) > MAX_SKILL_MD_BYTES + return { + skill: entry, + dir: found.dir, + files, + totalBytes: files.reduce((sum, file) => sum + file.bytes, 0), + truncated, + skillMd: truncated ? Buffer.from(raw).subarray(0, MAX_SKILL_MD_BYTES).toString('utf8') : raw, + } + } + /** Enable (move back into the root) or disable (park) one skill. */ - async setEnabled(folderInput: unknown, enabled: boolean): Promise<{ folder: string; enabled: boolean }> { + async setEnabled(folderInput: unknown, enabled: boolean): Promise<{ folder: string; enabled: boolean; note: string }> { this.guardSync() const folder = checkFolder(folderInput) const found = await this.locate(folder) if (found === undefined) fail('not_found', `没有找到技能:${folder}`) - const targetArea = enabled ? 'root' : 'holding' - if (found.area === targetArea) return { folder, enabled } + const targetArea: 'root' | 'holding' = enabled ? 'root' : 'holding' + if (found.area === targetArea) return { folder, enabled, note: this.effectNote(enabled) } const targetRoot = enabled ? this.deps.skillsRoot() : this.deps.holdingDir() await mkdir(targetRoot, { recursive: true }) const target = join(targetRoot, folder) if (await isDirectory(target)) fail('collision', `目标位置已存在同名技能:${folder}`) - await rename(found.dir, target) + try { + await rename(found.dir, target) + } catch (error) { + // A cross-device move must not leave the skill half-copied: fall back to a + // plain copy only for EXDEV, and only then remove the source. + if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error + await cp(found.dir, target, { recursive: true, filter: (source) => !source.split(/[\\/]/).includes('.git') }) + await rm(found.dir, { recursive: true, force: true }) + } this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`) - return { folder, enabled } + return { folder, enabled, note: this.effectNote(enabled) } } - /** Delete one skill for real: its folder is removed recursively. */ - async remove(folderInput: unknown): Promise<{ folder: string }> { + /** The enable/disable mechanism is a directory move, not a live switch. */ + private effectNote(enabled: boolean): string { + return enabled + ? '已放回技能目录:新会话可见;已在运行的会话可能仍保留旧状态。' + : '已移出技能目录:新会话不再加载;已经加载的会话不受影响。' + } + + /** Preview of what an uninstall would remove. Nothing is deleted yet. */ + async uninstallPlan(folderInput: unknown): Promise<{ + folder: string + dir: string + area: 'root' | 'holding' + files: number + bytes: number + scripts: string[] + origin: SkillEntry['origin'] | 'unknown' + cloudRevision?: number + recoverable: false + note: string + }> { + const folder = checkFolder(folderInput) + const found = await this.locate(folder) + if (found === undefined) fail('not_found', `没有找到技能:${folder}`) + if (await isSymlink(found.dir)) fail('unsupported', `技能目录是链接,不在这里删除:${folder}`) + const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded()) + const files = await walkFiles(found.dir) + return { + folder, + dir: found.dir, + area: found.area, + files: files.length, + bytes: files.reduce((sum, file) => sum + file.bytes, 0), + scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20), + origin: entry?.origin ?? 'unknown', + ...(entry?.revision === undefined ? {} : { cloudRevision: entry.revision }), + recoverable: false, + note: '本机删除不可恢复(没有回收站)。云端副本不受影响,同步引擎也不会把同一版本再次拉回。', + } + } + + /** + * Delete one skill for real: its folder is removed recursively. + * + * The route layer requires a plan token plus `confirmed: true`; this method + * itself stays usable by the verification harness and by trusted callers. + */ + async remove(folderInput: unknown): Promise<{ folder: string; dir: string; files: number; bytes: number }> { this.guardSync() const folder = checkFolder(folderInput) const found = await this.locate(folder) if (found === undefined) fail('not_found', `没有找到技能:${folder}`) + const files = await walkFiles(found.dir) + const bytes = files.reduce((sum, file) => sum + file.bytes, 0) await rm(found.dir, { recursive: true, force: true }) this.deps.log(`skill deleted: ${folder}`) - return { folder } + return { folder, dir: found.dir, files: files.length, bytes } + } + + private async readPlans(): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(this.plansFile(), 'utf8')) + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + const plans = (parsed as { plans?: unknown }).plans + if (Array.isArray(plans)) return { version: 1, plans: plans as InstallPlan[] } + } + } catch { + // Missing or torn file: no plans. + } + return { version: 1, plans: [] } + } + + private async writePlans(file: PlansFile): Promise { + const path = this.plansFile() + await mkdir(dirname(path), { recursive: true }) + const temporary = `${path}.tmp` + await writeFile(temporary, `${JSON.stringify(file, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }) + await rename(temporary, path) + } + + /** Drop expired plans and their staging trees. */ + private async sweepPlans(file: PlansFile): Promise { + const now = Date.now() + const live: InstallPlan[] = [] + for (const plan of file.plans) { + if (plan.expiresAt > now) { + live.push(plan) + continue + } + await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => {}) + } + return { version: 1, plans: live } } /** - * Install every skill found in a git repository (https:// or file://). - * The clone is shallow and never executes repository code; folders - * that collide with existing skills are skipped, never overwritten. + * Stage a git repository and describe its skills. Nothing enters the skills + * root here; the caller picks folders and commits. */ - async installFromGit(urlInput: unknown): Promise<{ installed: string[]; skipped: { name: string; reason: string }[] }> { + async prepareInstall(urlInput: unknown): Promise<{ + planId: string + url: string + expiresAt: number + candidates: (InstallPlanCandidate & { id: string })[] + }> { this.guardSync() if (typeof urlInput !== 'string') fail('invalid_url', '请提供仓库地址。') const url = urlInput.trim() if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) { fail('invalid_url', '只接受 https:// 或 file:// 的 git 仓库地址。') } - const scratch = join(dshHome(), `.cloud-memory-clone-${process.pid}-${Date.now().toString(36)}`) + const stagingRoot = this.stagingRoot() + await mkdir(stagingRoot, { recursive: true }) + const planId = `plan_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}` + const stagingDir = join(stagingRoot, planId) try { await new Promise((resolvePromise, rejectPromise) => { execFile( 'git', - ['clone', '--depth', '1', '--no-tags', '--', url, scratch], + ['clone', '--depth', '1', '--no-tags', '--', url, stagingDir], { timeout: 120_000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 }, (error) => (error ? rejectPromise(error) : resolvePromise()), ) }) - } catch { - await rm(scratch, { recursive: true, force: true }).catch(() => {}) - fail('git_failed', '仓库克隆失败(地址不可达、需要登录,或本机没有 git)。') + } catch (error) { + await rm(stagingDir, { recursive: true, force: true }).catch(() => {}) + const code = (error as NodeJS.ErrnoException).code + fail('git_failed', code === 'ENOENT' + ? '本机没有 git 命令,无法从仓库安装技能。' + : '仓库克隆失败(地址不可达、需要登录,或不是 git 仓库)。') } - try { - const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill' - const candidates: { folder: string; dir: string }[] = [] - const collect = async (dir: string, depth: number): Promise => { - if (await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) !== undefined) { - candidates.push({ folder: dir === scratch ? repoName : basename(dir), dir }) - return - } - if (depth >= 3) return - for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { - if (entry.isDirectory() && entry.name !== '.git') await collect(join(dir, entry.name), depth + 1) + const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill' + const found: { folder: string; dir: string }[] = [] + const collect = async (dir: string, depth: number): Promise => { + if (found.length >= MAX_CANDIDATES) return + const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) + if (markdown !== undefined) { + found.push({ folder: dir === stagingDir ? repoName : basename(dir), dir }) + return + } + if (depth >= 3) return + for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + if (entry.isDirectory() && entry.name !== '.git' && !entry.isSymbolicLink()) { + await collect(join(dir, entry.name), depth + 1) } } - await collect(scratch, 0) - if (candidates.length === 0) fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。') - const installed: string[] = [] - const skipped: { name: string; reason: string }[] = [] - await mkdir(this.deps.skillsRoot(), { recursive: true }) - for (const candidate of candidates) { - let folder = candidate.folder - try { - folder = checkFolder(folder) - } catch { - skipped.push({ name: candidate.folder, reason: 'invalid_name' }) - continue - } - if ((await this.locate(folder)) !== undefined) { - skipped.push({ name: folder, reason: 'already_exists' }) - continue - } - await cp(candidate.dir, join(this.deps.skillsRoot(), folder), { - recursive: true, - filter: (source) => !source.split(/[\\/]/).includes('.git'), - }) - installed.push(folder) - this.deps.log(`skill installed from git: ${folder}`) + } + await collect(stagingDir, 0) + if (found.length === 0) { + await rm(stagingDir, { recursive: true, force: true }).catch(() => {}) + fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。') + } + const candidates: InstallPlanCandidate[] = [] + for (const candidate of found) { + const markdown = await readFile(join(candidate.dir, 'SKILL.md'), 'utf8').catch(() => '') + const frontmatter = parseSkillFrontmatter(markdown) + const files = await walkFiles(candidate.dir) + const bytes = files.reduce((sum, file) => sum + file.bytes, 0) + const existing = await this.locate(candidate.folder) + let problem: string | undefined + try { + checkFolder(candidate.folder) + } catch { + problem = '目录名不合法,不能作为技能目录' } - return { installed, skipped } - } finally { - await rm(scratch, { recursive: true, force: true }).catch(() => {}) + if (problem === undefined && files.length > MAX_SKILL_FILES) problem = `文件过多(>${MAX_SKILL_FILES})` + if (problem === undefined && bytes > MAX_SKILL_BYTES) problem = `体积过大(>${MAX_SKILL_BYTES} 字节)` + const name = frontmatter.name + candidates.push({ + folder: candidate.folder, + name: typeof name === 'string' && name !== '' ? name : candidate.folder, + description: String(frontmatter.description ?? '').slice(0, 300), + files: files.length, + bytes, + scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20), + conflict: existing !== undefined, + ...(existing === undefined ? {} : { conflictLocation: existing.area }), + ...(problem === undefined ? {} : { problem }), + }) + } + const plan: InstallPlan = { + id: planId, + kind: 'install', + url, + createdAt: Date.now(), + expiresAt: Date.now() + PLAN_TTL_MS, + stagingDir, + candidates, + } + const file = await this.sweepPlans(await this.readPlans()) + file.plans.push(plan) + await this.writePlans(file) + this.deps.log(`skill install staged: ${url} -> ${planId} (${candidates.length} candidates)`) + return { + planId, + url, + expiresAt: plan.expiresAt, + candidates: candidates.map((candidate) => ({ ...candidate, id: candidate.folder })), + } + } + + /** Install the folders the user picked from a staged plan. */ + async commitInstall(planInput: { planId?: unknown; folders?: unknown }): Promise<{ + installed: string[] + skipped: { folder: string; reason: string }[] + remaining: string[] + }> { + this.guardSync() + const planId = typeof planInput.planId === 'string' ? planInput.planId : '' + if (planId === '') fail('invalid_plan', '缺少安装计划 id。') + const selection = Array.isArray(planInput.folders) ? planInput.folders : [] + const file = await this.sweepPlans(await this.readPlans()) + const plan = file.plans.find((item) => item.id === planId) + if (plan === undefined) { + await this.writePlans(file) + fail('plan_expired', '安装计划已过期或不存在,请重新拉取仓库。') + } + const wanted = selection.map((value) => checkFolder(value)) + const installed: string[] = [] + const skipped: { folder: string; reason: string }[] = [] + const skillsRoot = resolve(this.deps.skillsRoot()) + await mkdir(skillsRoot, { recursive: true }) + for (const candidate of plan.candidates) { + if (!wanted.includes(candidate.folder)) continue + if (candidate.problem !== undefined) { + skipped.push({ folder: candidate.folder, reason: candidate.problem }) + continue + } + const existing = await this.locate(candidate.folder) + if (existing !== undefined) { + skipped.push({ folder: candidate.folder, reason: existing.area === 'holding' ? 'already_exists_disabled' : 'already_exists' }) + continue + } + const stagingRoot = resolve(plan.stagingDir) + const source = candidate.folder === basename(plan.stagingDir) ? stagingRoot : resolve(stagingRoot, candidate.folder) + const target = resolve(skillsRoot, candidate.folder) + // Both sides must stay inside their own root: a crafted plan file cannot + // make this write outside the skills directory. + if (!source.startsWith(stagingRoot) || !target.startsWith(`${skillsRoot}${sep}`)) { + skipped.push({ folder: candidate.folder, reason: 'path_escape' }) + continue + } + await cp(source, target, { + recursive: true, + // `.git` never travels with a skill, and a link could point outside the + // repository: both are dropped rather than copied. + filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath), + }) + installed.push(candidate.folder) + this.deps.log(`skill installed from git: ${candidate.folder}`) + } + const remaining = plan.candidates + .filter((candidate) => !installed.includes(candidate.folder)) + .map((candidate) => candidate.folder) + file.plans = file.plans.filter((item) => item.id !== planId) + await this.writePlans(file) + await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => {}) + return { installed, skipped, remaining } + } + + /** Throw away a staged plan and its clone. */ + async cancelInstall(planInput: { planId?: unknown }): Promise<{ cancelled: string }> { + const planId = typeof planInput.planId === 'string' ? planInput.planId : '' + if (planId === '') fail('invalid_plan', '缺少安装计划 id。') + const file = await this.sweepPlans(await this.readPlans()) + const plan = file.plans.find((item) => item.id === planId) + file.plans = file.plans.filter((item) => item.id !== planId) + await this.writePlans(file) + if (plan !== undefined) await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => {}) + return { cancelled: planId } + } + + /** + * Legacy one-shot install, kept for the standalone `/cloud-memory/skills` + * page: stage the repository, then install every candidate that neither + * collides with an existing skill nor trips a limit. It still never + * overwrites and never executes repository content. + */ + async installFromGit(urlInput: unknown): Promise<{ installed: string[]; skipped: { name: string; reason: string }[] }> { + const plan = await this.prepareInstall(urlInput) + const folders = plan.candidates + .filter((candidate) => candidate.conflict !== true && candidate.problem === undefined) + .map((candidate) => candidate.folder) + const result = await this.commitInstall({ planId: plan.planId, folders }) + const skipped = plan.candidates + .filter((candidate) => !result.installed.includes(candidate.folder)) + .map((candidate) => ({ + name: candidate.folder, + reason: candidate.conflict === true + ? (candidate.conflictLocation === 'holding' ? 'already_exists_disabled' : 'already_exists') + : candidate.problem ?? 'skipped', + })) + return { installed: result.installed, skipped } + } + + /** Pending plans, so a reloaded page can resume a staged install. */ + async listPlans(): Promise<{ plans: { planId: string; url: string; expiresAt: number; folders: string[] }[] }> { const file = await this.sweepPlans(await this.readPlans()) + await this.writePlans(file) + return { + plans: file.plans.map((plan) => ({ + planId: plan.id, + url: plan.url, + expiresAt: plan.expiresAt, + folders: plan.candidates.map((candidate) => candidate.folder), + })), } } } diff --git a/src/store.ts b/src/store.ts index 4223c74..dfc3c0e 100644 --- a/src/store.ts +++ b/src/store.ts @@ -14,7 +14,7 @@ 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' +import { DEFAULT_SETTINGS, isPlaceholderBaseUrl, normalizeBaseUrl, originOf, settingsFromConfig, type Settings } from './config.ts' /** Persisted document schema. */ export interface PersistedState { @@ -43,6 +43,10 @@ export interface SettingsView extends Settings { memoryToken: TokenView summaryToken: TokenView statePath: string + /** False when the address is still the packaged placeholder. */ + baseUrlConfigured: boolean + /** Origin of the effective address, for the change-confirmation UI. */ + baseUrlOrigin: string } /** `$DSH_HOME` (or `~/.dsh`) — the same resolution DSH core uses. */ @@ -199,6 +203,8 @@ export class SettingsStore { memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory) }, summaryToken: { configured: summary !== '', masked: summary === '' ? '' : maskToken(summary) }, statePath: this.file, + baseUrlConfigured: !isPlaceholderBaseUrl(settings.baseUrl), + baseUrlOrigin: originOf(settings.baseUrl), } } @@ -209,8 +215,11 @@ export class SettingsStore { * 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 } { + patch(patch: Record): { ok: boolean; error?: string; clearedTokens?: string[] } { const next: PersistedState = { ...this.state } + const beforeOrigin = originOf(this.settings().baseUrl) + /** Tokens this very request supplied; they survive an address change. */ + const provided: string[] = [] if (patch.enabled !== undefined) { if (typeof patch.enabled !== 'boolean') return { ok: false, error: 'enabled must be a boolean' } next.enabled = patch.enabled @@ -229,11 +238,13 @@ export class SettingsStore { if (activityToken !== undefined) { if (!activityToken.startsWith('cmt_')) return { ok: false, error: 'activity token must start with cmt_' } next.activityToken = activityToken + provided.push('activity') } 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 + provided.push('memory') } if (patch.requestTimeoutMs !== undefined) { const requestTimeoutMs = clampInt(patch.requestTimeoutMs, 1000, 60_000) @@ -258,13 +269,33 @@ export class SettingsStore { if (summaryToken !== undefined) { if (!summaryToken.startsWith('cmt_')) return { ok: false, error: 'summary token must start with cmt_' } next.summaryToken = summaryToken + provided.push('summary') } if (patch.clearSummaryToken === true) delete next.summaryToken if (patch.clearActivityToken === true) delete next.activityToken if (patch.clearMemoryToken === true) delete next.memoryToken + + // Switching the service origin must not hand the previous service's + // bearer tokens to the new one: everything this request did not explicitly + // replace is dropped, and the caller is told so it can ask to re-authenticate. + const afterOrigin = originOf(next.baseUrl ?? this.configDefaults.baseUrl) + const clearedTokens: string[] = [] + if (beforeOrigin !== '' && afterOrigin !== '' && beforeOrigin !== afterOrigin) { + const credentials = [ + ['activity', 'activityToken'], + ['memory', 'memoryToken'], + ['summary', 'summaryToken'], + ] as const + for (const [label, key] of credentials) { + if (next[key] === undefined) continue + if (provided.includes(label)) continue + delete next[key] + clearedTokens.push(label) + } + } this.write(next) this.state = next - return { ok: true } + return clearedTokens.length === 0 ? { ok: true } : { ok: true, clearedTokens } } /** File size in bytes, for a "sidecar exists" hint in the card. */ diff --git a/verify-brain-panel.mjs b/verify-brain-panel.mjs new file mode 100644 index 0000000..77182f8 --- /dev/null +++ b/verify-brain-panel.mjs @@ -0,0 +1,238 @@ +// Runtime verification for the v0.5 management surface (P1 + P2): +// * status / capabilities payloads the card renders +// * config writes: origin change must not hand old tokens to a new service +// * skill inventory / detail / toggle +// * staged install: preview, explicit selection, conflict skip, plan expiry +// * uninstall: impact preview + single-use confirmation token +// * route gates: method, origin, content-type, path traversal +// +// Everything runs against the real route table wired to a real HTTP server and +// a throwaway $DSH_HOME; nothing touches the user's skills or config. +import http from 'node:http' +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-home-')) + +const results = [] +function check(name, ok, detail) { + results.push({ name, ok }) + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`) +} + +const root = join(process.env.DSH_HOME, 'skills') +const holding = join(process.env.DSH_HOME, 'skills-disabled') +const writeSkill = (area, folder, files) => { + for (const [rel, content] of Object.entries(files)) { + const target = join(area, folder, ...rel.split('/')) + mkdirSync(join(target, '..'), { recursive: true }) + writeFileSync(target, content) + } +} + +const { SettingsStore } = await import('./lib/store.js') +const { Reporter } = await import('./lib/reporter.js') +const { SkillAdmin } = await import('./lib/skill-admin.js') +const { createRoutes } = await import('./lib/routes.js') + +// A placeholder address the packaged patch ships: the card must call it +// "未配置服务", never a healthy connection. +const store = new SettingsStore( + { baseUrl: 'https://your-memory-host/api/longmemory', clientId: 'test-client', requestTimeoutMs: 2000, defaultK: 7 }, + join(process.env.DSH_HOME, 'cloud-memory.json'), +) +const reporter = new Reporter({ + client: () => ({ + reportTurn: async () => ({ ok: true, status: 200, data: {} }), + submitSummary: async () => ({ ok: true, status: 200, data: {} }), + }), + settings: () => ({ enabled: true, clientId: 'test-client' }), + activityToken: () => '', + summary: () => ({ enabled: false, maxChars: 1000 }), + summaryToken: () => '', + log: () => {}, +}) +const admin = new SkillAdmin({ + skillsRoot: () => root, + holdingDir: () => holding, + syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), + syncRunning: () => false, + log: () => {}, +}) +const routes = createRoutes({ + version: '0.5.0-test', + store, + reporter, + client: () => ({ + reach: async () => ({ ok: false, status: 0, message: 'stub' }), + probeActivity: async () => ({ ok: false, error: { status: 0, code: 'network_error', message: 'stub' } }), + projects: async () => ({ ok: false, error: { status: 0, code: 'network_error', message: 'stub' } }), + probeSummary: async () => ({ ok: false, error: { status: 0, code: 'network_error', message: 'stub' } }), + login: async () => ({ ok: false, error: { status: 401, code: 'unauthorized', message: 'stub' } }), + }), + skills: () => ({ running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 }), + admin, +}) + +const server = http.createServer((req, res) => { + const path = (req.url ?? '/').split('?')[0] + for (const route of routes) { + if (route.kind === 'exact' && path === route.path) return route.handler(req, res) + if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res) + } + res.writeHead(404, { 'content-type': 'application/json' }) + res.end('{"ok":false,"error":"no-route"}') +}) +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) +const origin = `http://127.0.0.1:${server.address().port}` + +async function call(method, path, body, extraHeaders) { + const headers = { accept: 'application/json', ...(extraHeaders ?? {}) } + let payload + if (body !== undefined) { + headers['content-type'] = headers['content-type'] ?? 'application/json' + payload = typeof body === 'string' ? body : JSON.stringify(body) + } + const response = await fetch(`${origin}${path}`, { method, headers, body: payload }) + const text = await response.text() + let parsed = null + try { + parsed = JSON.parse(text) + } catch { + parsed = null + } + return { status: response.status, body: parsed, text } +} + +// ── A. status / capabilities ──────────────────────────────────────────── +let status = await call('GET', '/cloud-memory/status') +check('status is 200 with ok:true', status.status === 200 && status.body?.ok === true) +check('a placeholder address is reported as unconfigured', status.body?.settings?.baseUrlConfigured === false, String(status.body?.settings?.baseUrlConfigured)) +check('the effective origin is exposed for the change warning', status.body?.settings?.baseUrlOrigin === 'https://your-memory-host') +check('capabilities carry the plugin version', status.body?.capabilities?.version === '0.5.0-test') +check('the market is reported unavailable instead of faked off', status.body?.capabilities?.features?.skillsMarketplace === false) +check('the MCP bridge is declared as a host-plugin surface', status.body?.capabilities?.features?.mcpBridge === 'host-plugin') +check('no check has run yet', status.body?.lastCheck === null) + +const caps = await call('GET', '/cloud-memory/capabilities') +check('capabilities route answers on its own', caps.status === 200 && caps.body?.features?.skills === true) +check('capabilities notes state the gaps', Array.isArray(caps.body?.notes) && caps.body.notes.length === 2) + +// ── B. config writes ──────────────────────────────────────────────────── +check('GET on the config route is refused', (await call('GET', '/cloud-memory/config')).status === 405) +const evil = await call('PUT', '/cloud-memory/config', { clientId: 'x' }, { origin: 'https://evil.example' }) +check('a foreign Origin is rejected', evil.status === 403 && evil.body?.error === 'origin-rejected') +const plain = await call('PUT', '/cloud-memory/config', 'clientId=x', { 'content-type': 'text/plain' }) +check('a non-JSON body is refused', plain.status === 415) + +store.patch({ activityToken: 'cmt_activity_token_1', memoryToken: 'cmt_memory_token_1', summaryToken: 'cmt_summary_token_1' }) +const switched = await call('PUT', '/cloud-memory/config', { baseUrl: 'https://memory.example.org/api/longmemory' }, { origin }) +check('changing the service origin is accepted', switched.status === 200 && switched.body?.ok === true) +check('the old origin tokens are cleared on a service switch', + Array.isArray(switched.body?.credentialsCleared) && switched.body.credentialsCleared.sort().join(',') === 'activity,memory,summary', + JSON.stringify(switched.body?.credentialsCleared)) +check('the cleared tokens are really gone from the store', + store.activityToken() === '' && store.memoryToken() === '' && store.summaryToken() === '') +const sameOriginSave = await call('PUT', '/cloud-memory/config', { activityToken: 'cmt_new_activity' }, { origin }) +check('a token supplied with the new origin is kept', sameOriginSave.status === 200 && store.activityToken() === 'cmt_new_activity') +const noChange = await call('PUT', '/cloud-memory/config', { defaultK: 25 }, { origin }) +check('an ordinary save does not touch credentials', noChange.body?.credentialsCleared === undefined && store.activityToken() === 'cmt_new_activity') +check('defaultK is renamed in the payload but still bounded', store.settings().defaultK === 25) + +// ── C. skill inventory / detail / toggle ──────────────────────────────── +writeSkill(root, 'gamma', { 'SKILL.md': '---\nname: gamma\ndescription: 演示技能\n---\n\n# gamma\n', 'references/a.md': '说明' }) +writeSkill(holding, 'parked-one', { 'SKILL.md': '# parked-one\n' }) +let inventory = await call('GET', '/cloud-memory/skills/api') +check('inventory lists root and parked skills', inventory.body?.skills?.length === 2) +const gamma = inventory.body?.skills?.find((skill) => skill.folder === 'gamma') +check('inventory carries owner, hash and install time', + gamma?.ownerManager === 'dsh-cloud-memory' && typeof gamma?.skillSha256 === 'string' && typeof gamma?.installedAt === 'string') +check('inventory carries a byte size and file count', gamma?.files === 2 && gamma?.bytes > 0) +check('parked skills are marked disabled', inventory.body?.skills?.find((skill) => skill.folder === 'parked-one')?.enabled === false) +check('pending plans come with the inventory', Array.isArray(inventory.body?.plans)) + +const detail = await call('POST', '/cloud-memory/skills/detail', { folder: 'gamma' }) +check('detail returns the SKILL.md text', detail.status === 200 && String(detail.body?.skillMd).includes('# gamma')) +check('detail returns the file list', Array.isArray(detail.body?.files) && detail.body.files.length === 2) +const traversal = await call('POST', '/cloud-memory/skills/toggle', { folder: '../escape', enabled: false }) +check('a traversal folder name is refused', traversal.status === 400 && traversal.body?.code === 'invalid_name') + +const toggled = await call('POST', '/cloud-memory/skills/toggle', { folder: 'gamma', enabled: false }) +check('disable parks the folder', toggled.status === 200 && existsSync(join(holding, 'gamma')) && !existsSync(join(root, 'gamma'))) +check('the toggle answer explains the effect scope', String(toggled.body?.note).includes('新会话')) +const enabled = await call('POST', '/cloud-memory/skills/toggle', { folder: 'gamma', enabled: true }) +check('enable brings it back', enabled.status === 200 && existsSync(join(root, 'gamma'))) + +// ── D. staged install ─────────────────────────────────────────────────── +const repo = mkdtempSync(join(tmpdir(), 'brain-repo-')) +writeSkill(repo, 'alpha', { 'SKILL.md': '# alpha\n', 'run.mjs': 'console.log(1)' }) +writeSkill(repo, 'beta', { 'SKILL.md': '# beta\n' }) +writeSkill(repo, 'gamma', { 'SKILL.md': '# gamma from repo\n' }) +execFileSync('git', ['init', '-q', repo]) +execFileSync('git', ['-C', repo, 'add', '-A']) +execFileSync('git', ['-C', repo, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'fixture']) + +const badPlan = await call('POST', '/cloud-memory/skills/install/plan', { url: 'javascript:alert(1)' }) +check('a non-git URL never reaches the stager', badPlan.status === 400 && badPlan.body?.code === 'invalid_url') + +const plan = await call('POST', '/cloud-memory/skills/install/plan', { url: `file://${repo}` }) +check('staging a repository answers with a plan', plan.status === 200 && typeof plan.body?.planId === 'string') +const candidates = Array.isArray(plan.body?.candidates) ? plan.body.candidates : [] +check('every candidate is described before it is installed', + candidates.length === 3 && candidates.every((item) => typeof item.files === 'number' && typeof item.id === 'string')) +check('an existing skill shows up as a conflict', + candidates.find((item) => item.folder === 'gamma')?.conflict === true) +check('candidates list the scripts they carry', + Array.isArray(candidates.find((item) => item.folder === 'alpha')?.scripts) && + candidates.find((item) => item.folder === 'alpha').scripts.includes('run.mjs')) +check('staging does not write into the skills root yet', + !existsSync(join(root, 'alpha')) && !existsSync(join(root, 'beta'))) + +const committed = await call('POST', '/cloud-memory/skills/install/commit', { planId: plan.body.planId, folders: ['alpha'] }) +check('only the selected folder is installed', + committed.status === 200 && committed.body?.installed?.join(',') === 'alpha' && !existsSync(join(root, 'beta'))) +check('the unselected candidate stays pending', committed.body?.remaining?.includes('beta')) +check('the staged clone is removed after the commit', + readdirSync(join(process.env.DSH_HOME, '.cloud-memory-staging')).length === 0) +const again = await call('POST', '/cloud-memory/skills/install/plan', { url: `file://${repo}` }) +const collide = await call('POST', '/cloud-memory/skills/install/commit', { planId: again.body.planId, folders: ['alpha'] }) +check('a second install of the same folder is skipped, never overwritten', + collide.body?.installed?.length === 0 && collide.body?.skipped?.[0]?.reason === 'already_exists') +const expired = await call('POST', '/cloud-memory/skills/install/commit', { planId: 'plan_missing', folders: ['alpha'] }) +check('an unknown plan id is refused with plan_expired', expired.status === 409 && expired.body?.code === 'plan_expired') +check('the second plan was cleaned up as well', + readdirSync(join(process.env.DSH_HOME, '.cloud-memory-staging')).length === 0) + +// ── E. uninstall: preview then single-use token ───────────────────────── +const noConfirm = await call('POST', '/cloud-memory/skills/remove', { folder: 'alpha' }) +check('remove without confirmation is refused', noConfirm.status === 409 && noConfirm.body?.code === 'confirmation_required') +const noToken = await call('POST', '/cloud-memory/skills/remove', { folder: 'alpha', confirmed: true }) +check('remove without a preview token is refused', noToken.status === 409 && noToken.body?.code === 'confirmation_required') +const impact = await call('POST', '/cloud-memory/skills/uninstall/plan', { folder: 'alpha' }) +check('the impact preview names the real directory and files', + impact.status === 200 && impact.body.dir === join(root, 'alpha') && impact.body.files === 2) +check('the preview states that deletion is irreversible', impact.body.recoverable === false && String(impact.body.note).includes('不可恢复')) +check('the preview names the scripts that would be deleted', impact.body.scripts.includes('run.mjs')) +const wrongFolder = await call('POST', '/cloud-memory/skills/remove', { folder: 'beta', token: impact.body.token, confirmed: true }) +check('a token issued for one skill cannot delete another', wrongFolder.status === 409) +const removed = await call('POST', '/cloud-memory/skills/remove', { folder: 'alpha', token: impact.body.token, confirmed: true }) +check('a confirmed remove with the right token deletes the folder', removed.status === 200 && !existsSync(join(root, 'alpha'))) +const reused = await call('POST', '/cloud-memory/skills/remove', { folder: 'gamma', token: impact.body.token, confirmed: true }) +check('the confirmation token is single-use', reused.status === 409) +check('deleting one skill leaves the others alone', existsSync(join(root, 'gamma')) && existsSync(join(holding, 'parked-one'))) + +// ── F. route gates on the skills prefix ───────────────────────────────── +const wrongMethod = await call('GET', '/cloud-memory/skills/toggle') +check('a GET on a write action is refused', wrongMethod.status === 405) +const wrongType = await call('POST', '/cloud-memory/skills/detail', 'folder=gamma', { 'content-type': 'text/plain' }) +check('a form-encoded write is refused', wrongType.status === 415) +const unknown = await call('POST', '/cloud-memory/skills/nope', {}) +check('an unknown skill subroute is a 404', unknown.status === 404) + +server.close() + +const failed = results.filter((item) => !item.ok).length +console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`) +process.exit(failed === 0 ? 0 : 1)