feat: unified management card (tabs, auth switch, skill plans, MCP bridge)

- 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
This commit is contained in:
qyh15 2026-11-11 20:41:34 +08:00
parent 09dc365338
commit 1a3a6fb23b
17 changed files with 3311 additions and 741 deletions

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -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/<planId>`;候选深度 ≤ 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 后由用户在界面确认。

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -301,6 +301,25 @@ export class CloudClient {
return this.request<TurnAck>('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<CloudResult<SummaryAck>> {
return this.request<SummaryAck>('POST', '/activity/summary', payload, token)

View File

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

View File

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

View File

@ -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<string> {
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<Record<string, unknown> | 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<string, unknown>
}
/** 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<string, { token: string; expiresAt: number }>()
const UNINSTALL_TOKEN_TTL_MS = 10 * 60_000
/** The payload the page and the client card both consume. */
function statusPayload(deps: RouteDeps): Record<string, unknown> {
const view = deps.store.describe()
const tokens: Record<'activity' | 'memory' | 'summary', TokenView> = {
activity: view.activityToken,
memory: view.memoryToken,
summary: view.summaryToken,
const 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<string, unknown> {
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<void> {
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<void> {
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<void> {
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<SettingsStore['patch']>[0] = {}
const patch: Record<string, unknown> = {}
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<void> {
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<string, (body: Record<string, unknown>) => Promise<Record<string, unknown>>> = {
'/toggle': async (body) => admin.setEnabled(body.folder, body.enabled === true),
'/remove': async (body) => admin.remove(body.folder),
'/install': async (body) => admin.installFromGit(body.url),
type Handler = (body: Record<string, unknown>) => Promise<Record<string, unknown>>
const actions: Record<string, Handler> = {
'/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<string, unknown>)) })
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,

View File

@ -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<boolean> {
return stat(path).then((s) => s.isDirectory()).catch(() => false)
}
async function isSymlink(path: string): Promise<boolean> {
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<void> => {
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<boolean> {
return stat(path).then((s) => s.isDirectory()).catch(() => false)
}
/** Count files below a directory, capped so a stray tree cannot hang us. */
async function countFiles(dir: string, cap = 2000): Promise<number> {
let count = 0
const walk = async (sub: string): Promise<void> => {
if (count > cap) return
for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) {
if (entry.name === '.git') continue
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`
if (entry.isDirectory()) await walk(rel)
else if (entry.isFile()) count += 1
}
}
await walk('')
return count
}
/** A folder name we are willing to move around: one path segment, no tricks. */
function checkFolder(folder: unknown): string {
if (
typeof folder !== 'string' || folder === '' || folder.length > 128 ||
folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0')
) {
fail('invalid_name', `技能目录名无效:${String(folder)}`)
}
return folder
/** 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<Record<string, { folder?: string; revision?: number }>> {
private async uploaded(): Promise<Record<string, { folder?: string; revision?: number }>> {
try {
const parsed: unknown = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8'))
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
@ -117,44 +212,61 @@ export class SkillAdmin {
return {}
}
private async describe(folder: string, dir: string, enabled: boolean, uploaded: Record<string, { folder?: string; revision?: number }>): Promise<AdminSkill | undefined> {
private async describe(
folder: string,
dir: string,
enabled: boolean,
uploaded: Record<string, { folder?: string; revision?: number }>,
): Promise<SkillEntry | undefined> {
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined)
if (markdown === undefined) return undefined
const frontmatter = parseSkillFrontmatter(markdown)
let origin: AdminSkill['origin'] = 'local'
let 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<void> => {
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<PlansFile> {
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<void> {
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<PlansFile> {
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<void>((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<void> => {
if (await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) !== undefined) {
candidates.push({ folder: dir === scratch ? repoName : basename(dir), dir })
return
}
if (depth >= 3) return
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (entry.isDirectory() && entry.name !== '.git') await collect(join(dir, entry.name), depth + 1)
const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill'
const found: { folder: string; dir: string }[] = []
const collect = async (dir: string, depth: number): Promise<void> => {
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),
})),
}
}
}

View File

@ -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<string, unknown>): { ok: boolean; error?: string } {
patch(patch: Record<string, unknown>): { 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. */

238
verify-brain-panel.mjs Normal file
View File

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