Compare commits

..

No commits in common. "main" and "unified-management-0.7.0" have entirely different histories.

61 changed files with 1118 additions and 4210 deletions

View File

@ -1,16 +1,8 @@
# dsh-brain
> **0.8.0 统一版(2026-11-11)**:本地开发线(0.7.0,含技能市场 / MCP 市场 /
> 多来源技能树 / 跨软件工作区清单 / 工作区级技能写)与云端线(0.5.1,完成
> dsh-brain 改名的部署半区)在此合流。插件现以 **dsh-brain** 发布:
> 包名、页面路由(`/dsh-brain/*`,旧 `/cloud-memory/*` 保留为别名)、
> 客户端模块 id、设置侧车(`dsh-brain.json` 等)全部切换;旧侧车在首次
> 加载时自动复制迁移、原文件保留;令牌环境变量 `DSH_BRAIN_*` 优先、
> 旧名继续有效。Mnemon provider 引用改为 `dsh-brain/mnemon-provider`。
# dsh-cloud-memory
把 DeepSeek Harness 接到 LongMemory 云端记忆服务:**每轮对话结束自动上报一条活动记录**(只上传元数据),并把云端记忆库变成 agent 可用的工具。
当前版本 **0.8.0**,含宿主端与浏览器端两部分:host 半负责活动上报与工具注册,`client/index.js` 提供「设置 → 插件 → 云端记忆」配置卡片。
当前版本 **0.1.1**,含宿主端与浏览器端两部分:host 半负责活动上报与工具注册,`client/index.js` 提供「设置 → 插件 → 云端记忆」配置卡片。
## 它做什么
@ -20,7 +12,7 @@
| 幂等 | `turn_id` 为 `<sessionId>:<turn>`,服务端按 `turn_id` 去重,重试不会重复计数。 |
| 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试(说明载荷或令牌有问题)。 |
| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具直接读写云端记忆库。 |
| 配置页 | `GET /dsh-brain` 提供完整配置界面(本 profile 关闭了原生设置页,所以自带页面)。 |
| 配置页 | `GET /cloud-memory` 提供完整配置界面(本 profile 关闭了原生设置页,所以自带页面)。 |
**绝不上传**:提示词正文、工具输出、文件内容、本地路径、令牌。上报载荷在类型层面就只有六个字段,构造它的函数拿不到正文。
@ -28,14 +20,14 @@
```powershell
# 装进当前 profile(默认 desktop)
dsh plugin --profile desktop add dsh-brain
dsh plugin --profile desktop add dsh-cloud-memory
```
装好后确认 profile 的 `package.json` 里有两处:
```jsonc
{
"dependencies": { "dsh-brain": "^0.8.0" },
"dependencies": { "dsh-cloud-memory": "^0.1.0" },
"dsh": { "profile": { "bundles": [ /* ..., */ "dsh-cloud-memory" ] } }
}
```
@ -125,20 +117,17 @@ v1 范围:支持 发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;
端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被
别人先改过就报冲突、不强行覆盖。
防事故的规矩:先比内容,本地与云端逐字节一致时直接补交付记录,不传
不覆盖;内容不同时按时间自动取较新的一边——云端 `updated_at` 更新就
先备份本地再覆盖,本地文件 mtime 更新就发布新修订;只有时间相同或缺
失时才报冲突(`locally_modified` / `name_collision` / `cloud_newer`),
等面板里逐项确认。本地删除不删云端,且同版本不会被重新拉回(云端出
了新版才会再下来)。面板里可逐项处理,也可用「全部保留本地 / 全部采用
云端」批量处理(有二次确认,失败项会逐条汇总)。云端只接受固定布局(根目录只有 `SKILL.md`,
防事故的规矩:云端交付的技能从不回传,本地改动它只报
`locally_modified` 冲突、原样不动;本地删除不删云端,且同版本不会
被重新拉回(云端出了新版才会再下来);同名技能两边都有时互不抢占,
报 `name_collision`。云端只接受固定布局(根目录只有 `SKILL.md`,
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
`unsupported_layout`,不会为了迁就而裁剪文件。
验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通
下行安装、上行发布与修订、按时间自动上行/下行、内容一致自动认领、
同名同时间保留冲突、脚本待审、布局拒绝、删除不传播全流程)。
下行安装、上行发布与修订、改云端技能报冲突、同名冲突、脚本待审、
布局拒绝、删除不传播全流程)。
## 技能管理(内置)
@ -222,7 +211,7 @@ pnpm publish --access public --no-git-checks
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
- **同步冲突(P3)**:`sync/status|run|resolve|resolve-all` 提供两侧信息;面板支持逐项「保留本地 / 采用云端 / 手动合并」,也支持「全部保留本地 / 全部采用云端」批量处理(二次确认,逐项失败会汇总提示)。
- **同步冲突(P3)**:`sync/status|run|resolve` 提供两侧信息,逐项「保留本地 / 采用云端 / 手动合并」。
- **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治理策略。
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,11 @@
# dsh-brain bundle patch
# cloud-memory bundle patch
#
# Local-only build: this package is never published, so the row below is the
# only way the plugin reaches the desktop profile tree. The host Loader
# resolves the row `name` as a package from the profile node_modules.
- insert:
- id: dsh-brain
name: 'dsh-brain'
- id: cloud-memory
name: 'dsh-cloud-memory'
config:
enabled: true
baseUrl: https://your-memory-host/api/longmemory

View File

@ -74,7 +74,7 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
- 技能市场:无经验证来源,`features.skillsMarketplace=false`。
- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。
- 自动更新与版本回退:未实现(无来源清单与制品基线)。
- MCP 市场的内嵌浏览与安装:**0.9.6 起从卡片移除**(宿主 `catalog` 返回 405,只留错误条没有意义),目录浏览回到宿主插件市场。
- MCP 市场的内嵌浏览与安装:未实现,只给宿主面板位置。
- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。
- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。
@ -165,24 +165,23 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
### 6.3 同步冲突交互
`SkillSync` 先自动处置:内容一致直接认领,内容不同按「本地文件 mtime vs 云端 `updated_at`」自动采用较新的一边(下行覆盖前备份到 `$DSH_HOME/.dsh-brain-backups/sync/`);只有时间相同/缺失、或本地布局无法上传时才留下冲突,并暴露两侧信息允许人工处置:
`SkillSync` 仍然只按原策略暂停冲突项,但会暴露两侧信息并允许人工处置:
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
| POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` |
| POST | `/cloud-memory/sync/resolve-all` | `{action}`:对当前全部冲突批量 `keep_local` / `take_cloud`,返回 `{resolved[], failed[{name,error}]}` |
- `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.dsh-brain-backups/sync/<name>/<时间>`,再写入云端 bundle。
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.cloud-memory-backups/sync/<name>/<时间>`,再写入云端 bundle。
- `manual`:只返回两侧信息,不改任何文件。
### 6.4 验证
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
- `verify-sync-resolve.mjs`:23 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝、批量成功与部分失败)。
- `verify-sync-resolve.mjs`:12 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝)。
## 7. P4:MCP 管理与市场(0.6.0)
@ -200,8 +199,8 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
| 区块 | 能力 |
|---|---|
| 我的连接 | 默认一行骨架(名称 + 状态 + 传输 + 「详情」),展开后才显示鉴权/注入/范围/健康检查/最近错误与单条操作;上方有搜索、状态筛选、多选与全选、批量健康检查/启用/停用/重连/两段式批量移除 |
| ~~MCP 市场~~ | **0.9.6 已删除**:宿主的 `catalog` 方法在当前 dsh-mcp-connector 上返回 `HTTP 405`,内嵌面板只能显示错误条。目录浏览与安装回到宿主自己的插件市场,本卡不再渲染该区块 |
| 我的连接 | 读取连接(名称/传输/鉴权/启用/状态/注入方式/范围/健康时间/最近错误)、健康检查、工具缓存、启停、重连、两段式移除 |
| MCP 市场 | `catalog` 目录浏览与搜索;无认证直接 `connect`;OAuth 走浏览器授权 `connect`;bearer / api-key 通过 `configure` 填凭据(只写宿主,不回显) |
| 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 |
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
| 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 |
@ -237,7 +236,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
| `skills/install/plan` `install/commit` | `sync_running` |
| `skills/toggle` `skills/remove` | `sync_running` |
| `skills/update/apply` `skills/rollback` | `sync_running` |
| `sync/resolve` `sync/resolve-all` | `sync_running` |
| `sync/resolve` | `sync_running` |
HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。
@ -282,9 +281,9 @@ HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8
### 9.4 dsh-brain 数据迁移(RENAME-01 数据半区)
- `GET /dsh-brain/migrate/brain` 报告旧文件与目标文件状态、`packageRename: done`(0.8.0 起包改名已完成;旧 `/cloud-memory/*` 路由保留为别名)。
- `POST /dsh-brain/migrate/brain` 把 `cloud-memory.json / -skills.json / -skill-groups.json / -workspaces.json / .cloud-memory-plans.json` 复制为 `dsh-brain*` 对应名,**保留旧文件、不覆盖已存在目标、幂等**;各加载路径首次使用时也会自动做同样的复制迁移。
- 实际包名、客户端模块 id 与 profile 加载入口的切换已在 **0.8.0 统一版**完成(部署步骤,切换后需完全重启 DSH)。
- `GET /cloud-memory/migrate/brain` 报告旧文件与目标文件状态、`packageRename: pending-deploy`。
- `POST /cloud-memory/migrate/brain` 把 `cloud-memory.json / -skills.json / -skill-groups.json` 复制为 `dsh-brain*.json`,**保留旧文件、不覆盖已存在目标、幂等**。
- 实际包名、客户端模块 id 与 profile 加载入口的切换是**部署步骤**,需要完全重启 DSH;不在运行中的会话里静默改名,避免同时注册或丢配置。
### 9.5 验证

View File

@ -1,10 +1,10 @@
/**
* dsh-cloud-memory → dsh-brain naming migration (v1.1 §15.1, RENAME-01).
*
* The 0.8.0 unification build ships AS `dsh-brain`: the package rename
* (the deploy step RENAME-01 deferred) has been performed, and the load
* paths read the `dsh-brain` names. What is implemented here is the
* *data* half, which is what RENAME-01 asserts:
* This build still ships as `dsh-cloud-memory`; renaming the live package and
* its profile link is a deploy step that needs a full DSH restart, so it is not
* performed from inside a running session. What is implemented here is the
* *data* half, which is what RENAME-01 actually asserts:
*
* - copy the legacy sidecars to the `dsh-brain` names when the target is
* missing, never deleting or modifying the legacy files;
@ -24,8 +24,6 @@ const PAIRS = [
['cloud-memory.json', 'dsh-brain.json'],
['cloud-memory-skills.json', 'dsh-brain-skills.json'],
['cloud-memory-skill-groups.json', 'dsh-brain-skill-groups.json'],
['cloud-memory-workspaces.json', 'dsh-brain-workspaces.json'],
['.cloud-memory-plans.json', '.dsh-brain-plans.json'],
];
async function exists(path) {
return stat(path).then((value) => value.isFile()).catch(() => false);
@ -47,7 +45,7 @@ export async function brainStatus() {
legacyPackage: BRAIN.legacyPackage,
files,
migrationNeeded: files.some((file) => file.needsMigration),
packageRename: 'done',
packageRename: 'pending-deploy',
};
}
/** Copy legacy sidecars to the new names. Existing targets are never overwritten. */

View File

@ -16,14 +16,12 @@ import { existsSync } from 'node:fs';
import { readFile, readdir, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, resolve, sep } from 'node:path';
import { dshHome, migrateLegacyFile } from "./store.js";
import { dshHome } from "./store.js";
import { parseSkillFrontmatter } from "./skill-sync.js";
import { SkillAdmin } from "./skill-admin.js";
/** Manual workspace additions live in the plugin's own metadata file. */
export function manualWorkspacesPath() {
const target = join(dshHome(), 'dsh-brain-workspaces.json');
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-workspaces.json'));
return target;
return join(dshHome(), 'cloud-memory-workspaces.json');
}
function rootsOf(home) {
return {
@ -108,9 +106,7 @@ export class ClientRegistry {
throw new Error('unknown_workspace');
const skillsRoot = resolve(workspace.path, '.dsh', 'skills');
const holdingDir = join(dshHome(), 'skills-workspace-disabled', workspace.id);
const stateName = `${workspace.id.replace(/[^A-Za-z0-9_-]/g, '_')}.json`;
const statePath = join(dshHome(), `dsh-brain-workspace-${stateName}`);
migrateLegacyFile(statePath, join(dshHome(), `cloud-memory-workspace-${stateName}`));
const statePath = join(dshHome(), `cloud-memory-workspace-${workspace.id.replace(/[^A-Za-z0-9_-]/g, '_')}.json`);
const admin = new SkillAdmin({
skillsRoot: () => skillsRoot,
holdingDir: () => holdingDir,

View File

@ -1,6 +1,6 @@
/**
* Settings model: the cordis row config supplies defaults, the user-editable
* sidecar (`$DSH_HOME/dsh-brain.json`) overrides them, and secrets live ONLY
* sidecar (`$DSH_HOME/cloud-memory.json`) overrides them, and secrets live ONLY
* in the sidecar. Nothing here ever reaches the conversation or a model context.
*/
/** Defaults written into cordis.patch.yml; also the fallback for missing keys. */

View File

@ -4,17 +4,17 @@
* Responsibilities:
* 1. report one activity record per finished conversation round,
* 2. expose the memory tools to the agent,
* 3. serve the configuration page under `/dsh-brain` (legacy `/cloud-memory` routes stay as aliases).
* 3. serve the configuration page under `/cloud-memory`.
*
* Everything registers through `ctx.effect(...)` so a plugin reload tears down
* its routes, timer, listeners, and tools without leftovers.
*/
import { CloudClient } from "./api.js";
import { Reporter } from "./reporter.js";
import { createLegacyRoutes, createRoutes } from "./routes.js";
import { createRoutes } from "./routes.js";
import { join } from 'node:path';
import { SettingsStore, dshHome } from "./store.js";
import { SkillSync, skillsStatePath } from "./skill-sync.js";
import { SkillSync } from "./skill-sync.js";
import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js";
import { SkillGroupManager, detectSources } from "./skill-groups.js";
import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js";
@ -22,18 +22,18 @@ import { SkillUpdater } from "./skill-update.js";
import { ClientRegistry } from "./clients.js";
import { createMemoryTools, createSkillTools } from "./tools.js";
/** Package name; also the client bundle id. */
export const name = 'dsh-brain';
export const name = 'dsh-cloud-memory';
/** Services required before `apply` runs. */
export const inject = ['webServer'];
/** Version reported by the status card. */
const VERSION = '0.9.10';
const VERSION = '0.7.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. */
const RETRY_INTERVAL_MS = 30_000;
/** Register the plugin with the host. */
export function apply(ctx, config) {
const logger = ctx.logger('dsh-brain');
const logger = ctx.logger('cloud-memory');
const store = new SettingsStore(config);
const settings = () => store.settings();
// One client per instance; the settings closures keep it live across edits.
@ -63,7 +63,7 @@ export function apply(ctx, config) {
const skillAdmin = new SkillAdmin({
skillsRoot: () => skillSync.skillsRoot(),
holdingDir: () => skillsHoldingDir(),
syncStatePath: () => skillsStatePath(),
syncStatePath: () => join(dshHome(), 'cloud-memory-skills.json'),
syncRunning: () => skillSync.stats().running,
log: (message) => logger.info(message),
});
@ -101,7 +101,7 @@ export function apply(ctx, config) {
logger.info('disabled by settings');
}
else if (store.activityToken() === '') {
logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`);
logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /cloud-memory`);
}
else {
logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`);
@ -119,7 +119,7 @@ export function apply(ctx, config) {
catch (error) {
logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`);
}
}), 'dsh-brain: turn reporting');
}), 'dsh-cloud-memory: turn reporting');
ctx.inject(['tools'], (toolsCtx) => {
const tools = toolsCtx.tools;
if (tools === undefined)
@ -130,7 +130,7 @@ export function apply(ctx, config) {
settings: () => ({ enabled: settings().enabled, defaultK: settings().defaultK }),
};
for (const tool of [...createMemoryTools(toolDeps), ...createSkillTools(toolDeps)]) {
toolsCtx.effect(() => tools.register(tool), `dsh-brain: tool ${tool.name}`);
toolsCtx.effect(() => tools.register(tool), `dsh-cloud-memory: tool ${tool.name}`);
}
});
const webServer = ctx.webServer;
@ -139,9 +139,8 @@ export function apply(ctx, config) {
}
else {
const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients });
routes.push(...createLegacyRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients }));
for (const route of routes) {
ctx.effect(() => webServer.register(route), `dsh-brain: route ${route.path}`);
ctx.effect(() => webServer.register(route), `dsh-cloud-memory: route ${route.path}`);
}
}
ctx.effect(() => {
@ -154,7 +153,7 @@ export function apply(ctx, config) {
}, RETRY_INTERVAL_MS);
timer.unref?.();
return () => clearInterval(timer);
}, 'dsh-brain: retry timer');
}, 'dsh-cloud-memory: retry timer');
ctx.effect(() => {
const run = () => {
if (store.memoryToken() !== '')
@ -165,5 +164,5 @@ export function apply(ctx, config) {
const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS);
timer.unref?.();
return () => { clearTimeout(first); clearInterval(timer); };
}, 'dsh-brain: skill sync timer');
}, 'dsh-cloud-memory: skill sync timer');
}

View File

@ -60,7 +60,7 @@ export class ClaudePluginMarketplaceProvider {
let response;
try {
response = await this.fetchImpl(url, {
headers: { accept: 'application/json, text/plain, */*', 'user-agent': 'dsh-brain-market' },
headers: { accept: 'application/json, text/plain, */*', 'user-agent': 'dsh-cloud-memory-market' },
signal: AbortSignal.timeout(this.timeoutMs()),
});
}

View File

@ -37,7 +37,7 @@ export const descriptor = {
input: 'url',
required: false,
placeholder: 'https://mem.example.com/api/longmemory',
help: 'LongMemory base URL. Leave empty to reuse the dsh-brain settings (dsh-brain.json).',
help: 'LongMemory base URL. Leave empty to reuse the dsh-cloud-memory settings (cloud-memory.json).',
normalize: 'trim-trailing-slash',
},
{
@ -46,7 +46,7 @@ export const descriptor = {
scope: 'service',
input: 'secret',
required: false,
help: 'Scoped memory token (memory:write). Leave empty to reuse the token already configured for dsh-brain.',
help: 'Scoped memory token (memory:write). Leave empty to reuse the token already configured for dsh-cloud-memory.',
},
{
key: 'projectId',

View File

@ -10,9 +10,9 @@
* Connection resolution, per call:
* 1. the Mnemon connection for the space (service fields configured on
* the Mnemon page, plus the space's own `projectId`),
* 2. this package's own settings sidecar (`$DSH_HOME/dsh-brain.json`)
* 2. this package's own settings sidecar (`$DSH_HOME/cloud-memory.json`)
* for any of endpoint/token the Mnemon side left empty — so a user
* who already configured dsh-brain configures nothing twice.
* who already configured dsh-cloud-memory configures nothing twice.
*
* A Memory Space maps to one LongMemory project; the empty project is the
* account-wide default scope.

View File

@ -1,12 +1,12 @@
/**
* Mnemon Memory Spaces Provider entry for LongMemory.
*
* This module is NOT loaded by the dsh-brain bundle itself. Mnemon's
* This module is NOT loaded by the dsh-cloud-memory bundle itself. Mnemon's
* Memory Spaces source mounts it as a child when the user adds it to the
* source's provider list:
*
* providers:
* - use: dsh-brain/mnemon-provider
* - use: dsh-cloud-memory/mnemon-provider
* instanceId: longmemory
*
* Registration is deliberately a user step: until then this file is inert
@ -17,13 +17,13 @@ import { descriptor } from "./descriptor.js";
import { LongMemoryProvider } from "./driver.js";
export { LongMemoryProvider, descriptor };
/** Keep in sync with the package version (asserted by the verify script). */
const PROVIDER_VERSION = '0.9.8';
const PROVIDER_VERSION = '0.7.0';
export const definition = defineMemorySpaceProviderDefinition({
manifest: {
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
kind: 'provider',
typeId: descriptor.id,
packageName: 'dsh-brain',
packageName: 'dsh-cloud-memory',
version: PROVIDER_VERSION,
label: descriptor.label,
icon: descriptor.icon,

View File

@ -3,11 +3,11 @@
*
* This profile runs with the native settings surface disabled
* (`ui-settings` is turned off in `cordis.patch.yml`), so the plugin ships its
* own HTML page at `/dsh-brain`. It is deliberately dependency-free: no
* own HTML page at `/cloud-memory`. It is deliberately dependency-free: no
* bundler assets, no CDN, no fonts — one file the host web server can emit.
*
* The page renders tokens as masked values only; the plaintext never leaves
* `$DSH_HOME/dsh-brain.json`.
* `$DSH_HOME/cloud-memory.json`.
*/
/** Escape a value for safe interpolation into HTML text/attributes. */
export function escapeHtml(value) {
@ -27,193 +27,94 @@ export function renderConfigPage(options) {
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>DSH Brain · 云端记忆</title>
<title>云端记忆 · DSH 插件</title>
<style>
:root {
color-scheme: light dark;
--bg: #f4f5fa; --card: #ffffff; --ink: #191c22; --ink2: #5b6472; --ink3: #8a93a3;
--line: #e4e7f0; --field: #fbfbfe; --field-line: #d8dce8;
--brand: #6366f1; --brand2: #8b5cf6; --brand-ink: #4f46e5;
--shadow: 0 1px 2px rgba(23, 25, 60, .04), 0 8px 24px -12px rgba(23, 25, 60, .12);
--ok-bg: #e5f7ec; --ok: #177245; --bad-bg: #fdecec; --bad: #b3261e;
--warn-bg: #fff4d6; --warn: #8a5a00; --sk-bg: #edf0f6; --sk: #55606d;
--code-bg: #eef0f7; --track: #d5d9e6;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #101218; --card: #171a21; --ink: #e8eaf0; --ink2: #a3abb9; --ink3: #767f8f;
--line: #262b36; --field: #12151c; --field-line: #313947;
--brand-ink: #a5b4fc; --shadow: 0 1px 2px rgba(0,0,0,.4), 0 10px 28px -12px rgba(0,0,0,.5);
--ok-bg: #123324; --ok: #4ade80; --bad-bg: #3d1a17; --bad: #f28b82;
--warn-bg: #3a2f10; --warn: #fbbf24; --sk-bg: #232833; --sk: #9aa3af;
--code-bg: #22262f; --track: #39415a;
}
}
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
body {
margin: 0; padding: 40px 24px 56px;
font: 14px/1.65 -apple-system, "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
color: var(--ink);
background:
radial-gradient(720px 300px at 12% -60px, rgba(99,102,241,.13), transparent 70%),
radial-gradient(640px 280px at 88% -40px, rgba(139,92,246,.10), transparent 70%),
var(--bg);
background-attachment: fixed;
margin: 0;
padding: 32px 24px 64px;
font: 14px/1.6 -apple-system, "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
background: #f6f7f9;
color: #1c1f23;
}
.wrap { max-width: 1020px; margin: 0 auto; }
a { color: var(--brand-ink); text-decoration: none; }
a:hover { text-decoration: underline; }
/* ---------- masthead ---------- */
.masthead { display: flex; align-items: center; gap: 16px; margin-bottom: 8px; }
.logo {
width: 54px; height: 54px; border-radius: 16px; flex: none;
display: flex; align-items: center; justify-content: center; font-size: 28px;
background: linear-gradient(135deg, var(--brand), var(--brand2));
box-shadow: 0 8px 20px -6px rgba(99,102,241,.55);
@media (prefers-color-scheme: dark) {
body { background: #14161a; color: #e6e8eb; }
.card { background: #1c1f24 !important; border-color: #2b303a !important; }
input, select { background: #12141a !important; color: #e6e8eb !important; border-color: #333a45 !important; }
th { color: #9aa3af !important; }
tr + tr td { border-color: #262b33 !important; }
.muted { color: #8b949e !important; }
code { background: #22262d !important; }
}
.masthead h1 { font-size: 24px; margin: 0; letter-spacing: .2px; line-height: 1.25; }
.masthead h1 .thin { font-weight: 500; color: var(--ink2); }
.ver {
font-size: 11.5px; font-weight: 600; color: var(--brand-ink);
background: color-mix(in srgb, var(--brand) 12%, transparent);
padding: 2px 9px; border-radius: 999px; vertical-align: 3px; margin-left: 8px; white-space: nowrap;
}
.tagline { margin: 2px 0 0; color: var(--ink2); font-size: 13px; }
.mast-actions { margin-left: auto; flex: none; }
.btn-link {
display: inline-flex; align-items: center; gap: 7px;
padding: 9px 16px; border-radius: 999px; font-size: 13px; font-weight: 600;
color: #fff; background: linear-gradient(135deg, var(--brand), var(--brand2));
box-shadow: 0 6px 16px -6px rgba(99,102,241,.6);
}
.btn-link:hover { text-decoration: none; filter: brightness(1.06); }
.rule { height: 3px; border-radius: 3px; margin: 18px 0 22px;
background: linear-gradient(90deg, var(--brand), var(--brand2), transparent 75%); opacity: .55; }
/* ---------- cards ---------- */
.wrap { max-width: 980px; margin: 0 auto; }
h1 { font-size: 20px; margin: 0 0 4px; letter-spacing: .2px; }
h2 { font-size: 14px; margin: 0 0 14px; font-weight: 600; letter-spacing: .3px; }
.sub { margin: 0 0 24px; color: #5c6672; font-size: 13px; }
@media (prefers-color-scheme: dark) { .sub { color: #8b949e; } }
.card {
background: var(--card); border: 1px solid var(--line); border-radius: 16px;
padding: 22px 24px; margin-bottom: 16px; box-shadow: var(--shadow);
background: #fff; border: 1px solid #e3e6ea; border-radius: 12px;
padding: 20px 22px; margin-bottom: 18px;
}
.card-head { display: flex; align-items: center; gap: 11px; margin-bottom: 16px; }
.chip {
width: 32px; height: 32px; border-radius: 10px; flex: none; font-size: 16px;
display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--brand) 12%, transparent);
}
.card-head h2 { font-size: 15px; margin: 0; font-weight: 650; letter-spacing: .2px; }
.card-head .desc { margin-left: auto; font-size: 12px; color: var(--ink3); text-align: right; }
/* ---------- forms ---------- */
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px 20px; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 18px; }
@media (max-width: 720px) { .grid { grid-template-columns: 1fr; } }
label { display: block; font-size: 12.5px; font-weight: 600; color: var(--ink2); margin-bottom: 6px; }
label { display: block; font-size: 12px; font-weight: 600; color: #4a5361; margin-bottom: 6px; }
@media (prefers-color-scheme: dark) { label { color: #a7b0bb; } }
input[type=text], input[type=password], input[type=number] {
width: 100%; padding: 10px 12px; font: inherit; font-size: 13.5px;
border: 1px solid var(--field-line); border-radius: 10px; background: var(--field); color: var(--ink);
transition: border-color .15s ease, box-shadow .15s ease;
width: 100%; padding: 9px 11px; font: inherit; font-size: 13px;
border: 1px solid #d7dbe1; border-radius: 8px; background: #fdfdfe; color: inherit;
}
input:focus { outline: none; border-color: var(--brand); box-shadow: 0 0 0 3px color-mix(in srgb, var(--brand) 22%, transparent); }
.hint { font-size: 12px; color: var(--ink3); margin-top: 6px; }
.muted { color: var(--ink3); }
input:focus { outline: 2px solid #4b7bec33; border-color: #4b7bec; }
.hint { font-size: 12px; color: #6b7480; margin-top: 5px; }
.muted { color: #6b7480; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.tip { margin-top: 14px; font-size: 12.5px; color: var(--ink2); }
code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; background: var(--code-bg); padding: 1px 6px; border-radius: 5px; }
/* ---------- toggles ---------- */
.toggles { margin-top: 18px; border-top: 1px dashed var(--line); padding-top: 6px; }
.toggle { display: flex; align-items: center; gap: 12px; padding: 10px 2px; cursor: pointer; margin: 0; }
.toggle input { position: absolute; opacity: 0; width: 0; height: 0; }
.toggle .track {
width: 40px; height: 22px; border-radius: 999px; flex: none; position: relative;
background: var(--track); transition: background .18s ease;
}
.toggle .track::after {
content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%;
background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.3); transition: transform .18s ease;
}
.toggle input:checked + .track { background: linear-gradient(135deg, var(--brand), var(--brand2)); }
.toggle input:checked + .track::after { transform: translateX(18px); }
.toggle input:focus-visible + .track { box-shadow: 0 0 0 3px color-mix(in srgb, var(--brand) 30%, transparent); }
.toggle .ttitle { display: block; font-size: 13.5px; font-weight: 600; color: var(--ink); }
.toggle .tdesc { display: block; font-size: 12px; color: var(--ink3); font-weight: 400; }
.inline-field { display: flex; align-items: center; gap: 12px; padding: 8px 2px 2px; }
.inline-field label { margin: 0; font-size: 13.5px; font-weight: 600; color: var(--ink); }
.inline-field input { max-width: 150px; }
/* ---------- buttons ---------- */
button {
font: inherit; font-size: 13.5px; font-weight: 550; padding: 9px 18px; border-radius: 10px;
border: 1px solid var(--field-line); background: var(--card); color: var(--ink); cursor: pointer;
transition: all .15s ease;
font: inherit; font-size: 13px; padding: 9px 16px; border-radius: 8px;
border: 1px solid #d7dbe1; background: #fff; color: inherit; cursor: pointer;
transition: background .15s ease, border-color .15s ease;
}
button:hover { border-color: var(--brand); color: var(--brand-ink); transform: translateY(-1px); }
button.primary {
background: linear-gradient(135deg, var(--brand), var(--brand2)); border: none; color: #fff;
box-shadow: 0 6px 16px -6px rgba(99,102,241,.55); padding: 10px 20px;
}
button.primary:hover { color: #fff; filter: brightness(1.07); }
button:disabled { opacity: .55; cursor: default; transform: none; }
/* ---------- stats ---------- */
.stats { display: flex; flex-wrap: wrap; gap: 10px; }
.stat {
flex: 1 1 118px; border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px 10px;
background: linear-gradient(180deg, color-mix(in srgb, var(--brand) 4%, transparent), transparent 65%);
position: relative; overflow: hidden;
}
.stat::before { content: ""; position: absolute; top: 0; left: 0; right: 0; height: 3px;
background: linear-gradient(90deg, var(--brand), var(--brand2)); opacity: .35; }
.stat:nth-child(3)::before, .stat:nth-child(7)::before { background: linear-gradient(90deg, #f59e0b, #ef4444); }
.stat .k { font-size: 11.5px; letter-spacing: .5px; color: var(--ink3); font-weight: 600; }
.stat .v { font-size: 21px; font-weight: 700; margin-top: 1px; font-variant-numeric: tabular-nums; }
/* ---------- pills / table ---------- */
.pill { display: inline-block; padding: 1.5px 9px; border-radius: 999px; font-size: 11.5px; font-weight: 600; }
.ok { background: var(--ok-bg); color: var(--ok); }
.bad { background: var(--bad-bg); color: var(--bad); }
.warn { background: var(--warn-bg); color: var(--warn); }
.sk { background: var(--sk-bg); color: var(--sk); }
.table-wrap { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
button:hover { background: #f2f4f7; }
button.primary { background: #2f6fed; border-color: #2f6fed; color: #fff; }
button.primary:hover { background: #255fd4; }
button:disabled { opacity: .55; cursor: default; }
.stats { display: flex; flex-wrap: wrap; gap: 10px; margin: 6px 0 2px; }
.stat { flex: 1 1 120px; border: 1px solid #e6e9ee; border-radius: 9px; padding: 10px 12px; }
@media (prefers-color-scheme: dark) { .stat { border-color: #2b303a; } }
.stat .k { font-size: 11px; letter-spacing: .4px; color: #6b7480; text-transform: uppercase; }
.stat .v { font-size: 18px; font-weight: 600; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
th { text-align: left; font-size: 11px; letter-spacing: .6px; color: var(--ink3); font-weight: 600;
padding: 9px 12px; background: color-mix(in srgb, var(--brand) 5%, transparent); }
td { padding: 8px 12px; border-top: 1px solid var(--line); vertical-align: top; }
tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent); }
.foot { text-align: center; color: var(--ink3); font-size: 12px; margin-top: 26px; }
th { text-align: left; font-size: 11px; letter-spacing: .4px; text-transform: uppercase; color: #6b7480; padding: 6px 8px; }
td { padding: 7px 8px; border-top: 1px solid #eef1f4; vertical-align: top; }
code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; background: #f1f3f6; padding: 1px 5px; border-radius: 4px; }
.pill { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 600; }
.ok { background: #e6f6ec; color: #1c7c43; }
.bad { background: #fdeaea; color: #b3261e; }
.warn { background: #fff5e0; color: #92600a; }
.sk { background: #eef1f5; color: #55606d; }
.tip { margin-top: 14px; font-size: 12px; color: #6b7480; }
.toast {
position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%);
background: #1c1f23; color: #fff; padding: 11px 20px; border-radius: 999px;
background: #1c1f23; color: #fff; padding: 10px 18px; border-radius: 999px;
font-size: 13px; opacity: 0; pointer-events: none; transition: opacity .2s ease;
max-width: 80vw; text-align: center; box-shadow: 0 12px 32px rgba(0,0,0,.3); z-index: 10;
max-width: 80vw; text-align: center;
}
.toast.show { opacity: .97; }
.toast.show { opacity: .95; }
</style>
</head>
<body>
<div class="wrap">
<header class="masthead">
<div class="logo">🧠</div>
<div>
<h1>DSH Brain<span class="thin"> · 云端记忆</span><span class="ver">v${escapeHtml(options.version)}</span></h1>
<p class="tagline">每轮结束上报活动计数 · 提供 memory_search / memory_read / memory_add 工具</p>
</div>
<div class="mast-actions">
<a class="btn-link" href="/dsh-brain/skills">技能管理 →</a>
</div>
</header>
<div class="rule"></div>
<h1>云端记忆 · DSH 插件</h1>
<p class="sub">v${escapeHtml(options.version)} · 每轮结束上报活动计数 · 提供 memory_search / memory_read / memory_add 工具</p>
<p class="sub"><a href="/cloud-memory/skills">技能管理(列表 · 启停 · 安装)→</a></p>
<section class="card">
<div class="card-head"><span class="chip">📊</span><h2>当前状态</h2><span class="desc">每 15 秒自动刷新</span></div>
<h2>当前状态</h2>
<div class="stats" id="stats"></div>
<div class="tip" id="statDetail">加载中…</div>
</section>
<section class="card">
<div class="card-head"><span class="chip">🔌</span><h2>连接配置</h2></div>
<h2>连接配置</h2>
<div class="grid">
<div>
<label for="baseUrl">服务基址</label>
@ -234,26 +135,24 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
<input id="defaultK" type="number" min="1" max="100" />
</div>
</div>
<div class="toggles">
<label class="toggle" for="enabled">
<input id="enabled" type="checkbox" />
<span class="track"></span>
<span><span class="ttitle">启用插件</span><span class="tdesc">关闭后不上报、不提供工具</span></span>
<div class="row" style="margin-top:14px">
<label style="margin:0;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500">
<input id="enabled" type="checkbox" style="width:auto" /> 启用插件(关闭后不上报、不提供工具)
</label>
<label class="toggle" for="summaryEnabled">
<input id="summaryEnabled" type="checkbox" />
<span class="track"></span>
<span><span class="ttitle">轮次结束后自动生成待确认摘要</span><span class="tdesc">只进入待确认队列,确认后才写云端</span></span>
</div>
<div class="row" style="margin-top:10px">
<label style="margin:0;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500">
<input id="summaryEnabled" type="checkbox" style="width:auto" /> 轮次结束后自动生成待确认摘要(只进入待确认队列,确认后才写云端)
</label>
<div class="inline-field">
<label for="summaryMaxChars">单轮摘要字数上限</label>
<input id="summaryMaxChars" type="number" min="1000" max="16000" step="500" />
</div>
</div>
<div class="row" style="margin-top:10px;align-items:center;gap:10px">
<label for="summaryMaxChars" style="margin:0;font-size:13px;font-weight:500">单轮摘要字数上限</label>
<input id="summaryMaxChars" type="number" min="1000" max="16000" step="500" style="max-width:140px" />
</div>
</section>
<section class="card">
<div class="card-head"><span class="chip">🔑</span><h2>账号登录</h2><span class="desc">用账号一次性换取令牌,密码不保存</span></div>
<h2>账号登录</h2>
<div class="grid">
<div>
<label for="username">用户名</label>
@ -264,7 +163,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
<input id="password" type="password" spellcheck="false" autocomplete="current-password" placeholder="只用于本次换取令牌" />
</div>
</div>
<div class="row" style="margin-top:16px">
<div class="row" style="margin-top:14px">
<button class="primary" id="login">登录并获取令牌</button>
</div>
<div class="tip">
@ -275,7 +174,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
</section>
<section class="card">
<div class="card-head"><span class="chip">🎫</span><h2>访问令牌</h2><span class="desc">只存本机,页面只显示掩码</span></div>
<h2>访问令牌</h2>
<div class="grid">
<div>
<label for="activityToken">活动上报令牌(activity:write)</label>
@ -293,7 +192,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
<div class="hint" id="summaryTokenHint">用于 POST /activity/summary:只把已脱敏摘要送进待确认队列。</div>
</div>
</div>
<div class="row" style="margin-top:16px">
<div class="row" style="margin-top:14px">
<button class="primary" id="save">保存配置</button>
<button id="clearTokens">清除已存令牌</button>
</div>
@ -304,7 +203,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
</section>
<section class="card">
<div class="card-head"><span class="chip">🩺</span><h2>诊断</h2></div>
<h2>诊断</h2>
<div class="row">
<button id="test">测试连接</button>
<button id="flush">重试上报队列</button>
@ -314,18 +213,14 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
</section>
<section class="card">
<div class="card-head"><span class="chip">🕘</span><h2>最近上报</h2></div>
<div class="table-wrap">
<table>
<thead>
<tr><th>时间</th><th>状态</th><th>结果</th><th>HTTP</th><th>turn_id</th></tr>
</thead>
<tbody id="recent"><tr><td colspan="5" class="muted">暂无记录</td></tr></tbody>
</table>
</div>
<h2>最近上报</h2>
<table>
<thead>
<tr><th>时间</th><th>状态</th><th>结果</th><th>HTTP</th><th>turn_id</th></tr>
</thead>
<tbody id="recent"><tr><td colspan="5" class="muted">暂无记录</td></tr></tbody>
</table>
</section>
<p class="foot">DSH Brain · 云端记忆插件 — 配置只保存在这台机器上</p>
</div>
<div class="toast" id="toast"></div>
<script>
@ -425,7 +320,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
}
function load() {
return fetch('/dsh-brain/status', { headers: { accept: 'application/json' } })
return fetch('/cloud-memory/status', { headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) throw new Error((body && body.error) || 'status failed');
@ -450,7 +345,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
if (activity !== '') patch.activityToken = activity;
if (memory !== '') patch.memoryToken = memory;
if (summary !== '') patch.summaryToken = summary;
fetch('/dsh-brain/config', {
fetch('/cloud-memory/config', {
method: 'PUT',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify(patch)
@ -467,7 +362,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
function test() {
var node = el('testResult');
node.textContent = '测试中…';
fetch('/dsh-brain/test', { method: 'POST', headers: { accept: 'application/json' } })
fetch('/cloud-memory/test', { method: 'POST', headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) { node.textContent = '测试失败:' + ((body && body.error) || 'unknown'); return; }
@ -480,7 +375,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
}
function flush() {
fetch('/dsh-brain/flush', { method: 'POST', headers: { accept: 'application/json' } })
fetch('/cloud-memory/flush', { method: 'POST', headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) { toast('重试失败:' + ((body && body.error) || 'unknown')); return; }
@ -491,7 +386,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
}
function clearTokens() {
fetch('/dsh-brain/config', {
fetch('/cloud-memory/config', {
method: 'PUT',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ clearActivityToken: true, clearMemoryToken: true })
@ -506,7 +401,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
var username = el('username').value.trim();
var password = el('password').value;
if (username === '' || password === '') { toast('请填写用户名和密码'); return; }
fetch('/dsh-brain/login', {
fetch('/cloud-memory/login', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ username: username, password: password })

View File

@ -274,7 +274,7 @@ export class Reporter {
}
this.summaryFailed += 1;
this.lastSummaryError = describeError(result.error);
this.options.log(`dsh-brain: turn summary failed: ${this.lastSummaryError}`);
this.options.log(`cloud-memory: turn summary failed: ${this.lastSummaryError}`);
}
push(record) {
this.recent.unshift(record);
@ -326,7 +326,7 @@ export class Reporter {
if (this.queue.length > 200)
this.queue.shift();
}
this.options.log(`dsh-brain: turn report failed: ${this.lastError}`);
this.options.log(`cloud-memory: turn report failed: ${this.lastError}`);
}
/** Retry queued reports; safe to call at any time. */
async flush() {
@ -350,7 +350,7 @@ export class Reporter {
// an unbounded queue of metadata forever.
this.queue.shift();
this.retries.delete(payload.turn_id);
this.options.log(`dsh-brain: dropping turn report after ${attempt} attempts: ${this.lastError}`);
this.options.log(`cloud-memory: dropping turn report after ${attempt} attempts: ${this.lastError}`);
continue;
}
this.retries.set(payload.turn_id, attempt);

View File

@ -8,18 +8,18 @@ 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: '/dsh-brain',
status: '/dsh-brain/status',
capabilities: '/dsh-brain/capabilities',
config: '/dsh-brain/config',
login: '/dsh-brain/login',
test: '/dsh-brain/test',
flush: '/dsh-brain/flush',
skills: '/dsh-brain/skills',
market: '/dsh-brain/market',
sync: '/dsh-brain/sync',
clients: '/dsh-brain/clients',
migrate: '/dsh-brain/migrate',
page: '/cloud-memory',
status: '/cloud-memory/status',
capabilities: '/cloud-memory/capabilities',
config: '/cloud-memory/config',
login: '/cloud-memory/login',
test: '/cloud-memory/test',
flush: '/cloud-memory/flush',
skills: '/cloud-memory/skills',
market: '/cloud-memory/market',
sync: '/cloud-memory/sync',
clients: '/cloud-memory/clients',
migrate: '/cloud-memory/migrate',
};
/** Largest request body we accept (a settings patch is tiny). */
const MAX_BODY_BYTES = 64 * 1024;
@ -40,7 +40,7 @@ function capabilities(deps) {
skillUpdate: deps.updates !== undefined,
syncResolve: deps.sync !== undefined,
multiClient: deps.clients !== undefined,
brainMigration: 'ready',
brainMigration: 'pending-deploy',
// 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',
@ -194,7 +194,7 @@ function servePage(deps, req, res) {
else
res.end(html);
}
/** `GET /dsh-brain/status`. */
/** `GET /cloud-memory/status`. */
function serveStatus(deps, req, res) {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
@ -202,7 +202,7 @@ function serveStatus(deps, req, res) {
}
json(res, 200, statusPayload(deps));
}
/** `GET /dsh-brain/capabilities`. */
/** `GET /cloud-memory/capabilities`. */
function serveCapabilities(deps, req, res) {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
@ -210,7 +210,7 @@ function serveCapabilities(deps, req, res) {
}
json(res, 200, { ok: true, ...capabilities(deps) });
}
/** `PUT /dsh-brain/config`. */
/** `PUT /cloud-memory/config`. */
async function serveConfig(deps, req, res) {
if (req.method !== 'PUT' && req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
@ -257,7 +257,7 @@ function checkState(error) {
return 'forbidden';
return 'error';
}
/** `POST /dsh-brain/test` — read-only checks, one per credential. */
/** `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');
@ -330,7 +330,7 @@ async function serveTest(deps, req, res) {
summary: { ok: checks[3]?.state === 'ok', message: checks[3]?.message ?? '' },
});
}
/** `POST /dsh-brain/flush`. */
/** `POST /cloud-memory/flush`. */
async function serveFlush(deps, req, res) {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
@ -350,7 +350,7 @@ const TOKEN_LABELS = {
summary: 'DSH desktop 对话摘要',
};
/**
* `POST /dsh-brain/login` — sign in with the cloud account and exchange it
* `POST /cloud-memory/login` — sign in with the cloud account and exchange it
* for the scoped tokens.
*
* The password is used once, in memory, and never written anywhere: the flow is
@ -491,15 +491,15 @@ function useUninstallToken(folder, token) {
}
/**
* The skill management surface, one prefix route:
* `GET /dsh-brain/skills` the management page
* `GET /dsh-brain/skills/api` inventory JSON (skills + plans)
* `POST /dsh-brain/skills/detail` { folder } — one skill with SKILL.md
* `POST /dsh-brain/skills/toggle` { folder, enabled }
* `POST /dsh-brain/skills/install/plan` { url } — stage the repository
* `POST /dsh-brain/skills/install/commit` { planId, folders }
* `POST /dsh-brain/skills/install/cancel` { planId }
* `POST /dsh-brain/skills/uninstall/plan` { folder } — impact preview
* `POST /dsh-brain/skills/remove` { folder, token, confirmed: true }
* `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) {
const admin = deps.admin;
@ -581,7 +581,6 @@ async function serveSkills(deps, req, res) {
// base URL; they are grouped here because they never touch a skill folder
// directly (except the DSH park/unpark the group manager delegates).
const groupActions = {
'/import': async (body) => ({ ...(await requireGroups(deps).importSkill(body.sourceId, body.folder)) }),
'/groups/create': async (body) => ({ ...(await requireGroups(deps).createGroup(body.sourceId, body.name)) }),
'/groups/rename': async (body) => ({ ...(await requireGroups(deps).renameGroup(body.sourceId, body.groupId, body.name)) }),
'/groups/delete': async (body) => ({ ...(await requireGroups(deps).deleteGroup(body.sourceId, body.groupId)) }),
@ -626,8 +625,6 @@ function groupStatus(code) {
case 'unknown_source': return 404;
case 'invalid_name':
case 'duplicate':
case 'import_from_self':
case 'invalid_skill':
case 'too_many': return 400;
case 'unavailable': return 503;
default: return 500;
@ -653,12 +650,12 @@ function marketStatus(code) {
}
/**
* Market surface, one prefix route:
* `GET /dsh-brain/market/providers` configured sources
* `GET /dsh-brain/market/search` ?provider=&q=&cursor=
* `POST /dsh-brain/market/detail` { provider, id }
* `POST /dsh-brain/market/plan` { provider, id } — pin commit + stage a plan
* `POST /dsh-brain/market/commit` { planId, folders }
* `POST /dsh-brain/market/cancel` { planId }
* `GET /cloud-memory/market/providers` configured sources
* `GET /cloud-memory/market/search` ?provider=&q=&cursor=
* `POST /cloud-memory/market/detail` { provider, id }
* `POST /cloud-memory/market/plan` { provider, id } — pin commit + stage a plan
* `POST /cloud-memory/market/commit` { planId, folders }
* `POST /cloud-memory/market/cancel` { planId }
*/
async function serveMarket(deps, req, res) {
const market = deps.market;
@ -746,10 +743,9 @@ async function serveMarket(deps, req, res) {
}
/**
* Sync surface:
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
* `POST /dsh-brain/sync/run` trigger one pass now
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud } for every conflict
* `GET /cloud-memory/sync/status` latest stats + both sides of each conflict
* `POST /cloud-memory/sync/run` trigger one pass now
* `POST /cloud-memory/sync/resolve` { name, action: keep_local | take_cloud | manual }
*/
async function serveSync(deps, req, res) {
const sync = deps.sync;
@ -789,18 +785,6 @@ async function serveSync(deps, req, res) {
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
return;
}
if (suffix === '/resolve-all') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const result = await sync.resolveConflicts(body.action);
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() });
return;
}
fail(res, 404, 'unknown-sync-route');
}
catch (error) {
@ -972,10 +956,6 @@ async function serveMigrate(_deps, req, res) {
fail(res, 404, 'unknown-migrate-route');
}
/** Build the exact-route table registered with the host web server. */
/** Pre-rename aliases (0.8.0): the same handlers under the old `/cloud-memory` prefix. */
export function createLegacyRoutes(deps) {
return createRoutes(deps).map((route) => ({ ...route, path: route.path.replace('/dsh-brain', '/cloud-memory') }));
}
export function createRoutes(deps) {
return [
{

View File

@ -31,24 +31,18 @@ import { createHash, randomUUID } from 'node:crypto';
import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
import { parseSkillFrontmatter } from "./skill-sync.js";
import { dshHome, migrateLegacyFile } from "./store.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(), '.dsh-brain-staging');
return join(dshHome(), '.cloud-memory-staging');
}
/** Persisted plan records (metadata only: ids, counts, timestamps). */
/** Plans sidecar path, carrying the pre-rename file over on first use. */
export function plansPath() {
const target = join(dshHome(), '.dsh-brain-plans.json');
migrateLegacyFile(target, join(dshHome(), '.cloud-memory-plans.json'));
return target;
}
function skillPlansPath() {
return plansPath();
export function skillPlansPath() {
return join(dshHome(), '.cloud-memory-plans.json');
}
/** A management failure with a stable machine-readable code. */
export class SkillAdminError extends Error {
@ -231,7 +225,7 @@ export class SkillAdmin {
...(installedAt === undefined ? {} : { installedAt }),
skillSha256: createHash('sha256').update(markdown).digest('hex'),
location: enabled ? 'root' : 'holding',
ownerManager: 'dsh-brain',
ownerManager: 'dsh-cloud-memory',
writable: true,
...(source === undefined
? {}
@ -604,35 +598,6 @@ export class SkillAdmin {
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
return { installed, skipped, remaining };
}
/**
* Import one skill folder from another tool's skills directory (the
* "从其他软件导入" action). The caller (the group manager) has already
* resolved and vetted the source directory; this side owns the target:
* the name is validated, an existing skill — enabled or parked — is
* never overwritten, and the copy drops `.git` and symlinks exactly
* like a git install does.
*/
async importFolder(fromDir, folderInput) {
this.guardSync();
const folder = checkFolder(folderInput);
const existing = await this.locate(folder);
if (existing !== undefined) {
fail('already_exists', existing.area === 'holding'
? `DSH 里已有一个停用中的同名技能(${folder}),先处理它再导入。`
: `DSH 里已有同名技能(${folder}),不重复导入。`);
}
const skillsRoot = resolve(this.deps.skillsRoot());
await mkdir(skillsRoot, { recursive: true });
const target = resolve(skillsRoot, folder);
if (!target.startsWith(`${skillsRoot}${sep}`))
fail('path_escape', '导入目标越出技能目录。');
await cp(fromDir, target, {
recursive: true,
filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath),
});
this.deps.log(`skill imported from another tool: ${folder}`);
return { folder };
}
/** Throw away a staged plan and its clone. */
async cancelInstall(planInput) {
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
@ -647,7 +612,7 @@ export class SkillAdmin {
return { cancelled: planId };
}
/**
* Legacy one-shot install, kept for the standalone `/dsh-brain/skills`
* 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.

View File

@ -18,18 +18,16 @@
*/
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
import { readdir, readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, resolve, sep } from 'node:path';
import { dshHome, migrateLegacyFile } from "./store.js";
import { join, resolve } from 'node:path';
import { dshHome } from "./store.js";
const MAX_GROUP_NAME = 40;
const MAX_GROUPS_PER_SOURCE = 40;
/** Sidecar path. */
export function skillGroupsPath() {
const target = join(dshHome(), 'dsh-brain-skill-groups.json');
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-skill-groups.json'));
return target;
return join(dshHome(), 'cloud-memory-skill-groups.json');
}
/**
* The known sources.
@ -290,50 +288,6 @@ export class SkillGroupManager {
};
}
/** Create one category inside a source. */
/**
* Import one skill from another tool's source into the DSH skills root
* (the card's 「从其他软件导入」). The source directory itself is never
* modified: the source side is vetted here (real directory, no symlink,
* stays inside its own root, carries a real SKILL.md) and the copy is
* delegated to the admin, which owns the target-side rules.
*/
async importSkill(sourceInput, folderInput) {
const source = this.source(sourceInput);
if (source.writable) {
throw new SkillGroupError('import_from_self', 'DSH 来源就是导入目标,不需要导入。');
}
const folder = typeof folderInput === 'string' ? folderInput : '';
if (folder === '' || folder.length > 128 || folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0')) {
throw new SkillGroupError('invalid_name', `技能目录名无效:${String(folderInput)}`);
}
const dir = join(source.root, folder);
let stat;
try {
stat = lstatSync(dir);
}
catch {
throw new SkillGroupError('not_found', `来源里没有这个技能:${folder}`);
}
if (!stat.isDirectory() || stat.isSymbolicLink()) {
throw new SkillGroupError('invalid_skill', `来源技能不是普通目录:${folder}`);
}
const rootReal = realpathSync(source.root);
const dirReal = realpathSync(dir);
if (!dirReal.startsWith(`${rootReal}${sep}`)) {
throw new SkillGroupError('invalid_skill', `来源技能越出来源目录:${folder}`);
}
let marker;
try {
marker = lstatSync(join(dir, 'SKILL.md'));
}
catch {
throw new SkillGroupError('invalid_skill', `来源技能缺少 SKILL.md:${folder}`);
}
if (!marker.isFile() || marker.isSymbolicLink()) {
throw new SkillGroupError('invalid_skill', `来源技能的 SKILL.md 不是普通文件:${folder}`);
}
return this.deps.admin.importFolder(dirReal, folder);
}
async createGroup(sourceInput, nameInput) {
const source = this.source(sourceInput);
const name = cleanGroupName(nameInput);

View File

@ -1,8 +1,8 @@
/**
* The local skill management page (`GET /dsh-brain/skills`).
* The local skill management page (`GET /cloud-memory/skills`).
*
* A thin shell: the browser fetches the JSON inventory from
* `/dsh-brain/skills/api` and renders it; every action is a small
* `/cloud-memory/skills/api` and renders it; every action is a small
* JSON POST back to the same prefix. All skill data is inserted with
* textContent, never as raw HTML.
*/
@ -43,7 +43,7 @@ export function renderSkillsPage(options) {
<body>
<div class="wrap">
<h1>技能管理</h1>
<p class="sub">v${options.version} · 本机技能的列表、启停、安装;删除是真删、不可恢复(云端副本不受影响)。云端同步仍在后台自动进行。<a href="/dsh-brain">← 返回云端记忆设置</a></p>
<p class="sub">v${options.version} · 本机技能的列表、启停、安装;删除是真删、不可恢复(云端副本不受影响)。云端同步仍在后台自动进行。<a href="/cloud-memory">← 返回云端记忆设置</a></p>
<section class="card">
<h2>从 git 仓库安装</h2>
@ -76,7 +76,7 @@ export function renderSkillsPage(options) {
return btn;
}
async function post(path, body) {
const response = await fetch('/dsh-brain/skills' + path, {
const response = await fetch('/cloud-memory/skills' + path, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
@ -97,7 +97,7 @@ export function renderSkillsPage(options) {
}
}
async function load() {
const response = await fetch('/dsh-brain/skills/api');
const response = await fetch('/cloud-memory/skills/api');
const data = await response.json();
const skillsBox = $('skills');
skillsBox.textContent = '';

View File

@ -15,14 +15,12 @@
* revisions, guarded by the center's `expected_revision` check.
*
* Safety rules (deliberate, in order):
* 1. A cloud-delivered skill is never re-uploaded unless its local copy is
* newer than the center's `updated_at`; before any cloud overwrite the
* local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
* 1. A cloud-delivered skill is never re-uploaded. If its local files no
* longer match the delivery manifest, the skill is flagged as a
* conflict and left completely alone.
* 2. A local deletion never deletes the cloud copy.
* 3. A same-name skill is never hijacked silently: byte-identical copies are
* adopted in place, otherwise the newer side (local file mtime vs center
* `updated_at`) wins; only equal or missing timestamps are reported as a
* conflict for a human to resolve.
* 3. A name that already exists on the other side is never hijacked;
* it is reported as a conflict for a human to resolve.
* 4. Bundles whose scripts changed on the cloud side are not installed
* until the change is acknowledged in the dashboard, mirroring the
* center's own review flag.
@ -35,7 +33,7 @@ import { createHash, randomUUID } from 'node:crypto';
import { mkdir, cp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { describeError } from "./api.js";
import { dshHome, migrateLegacyFile } from "./store.js";
import { dshHome } from "./store.js";
/** Cloud skill names: lowercase kebab, at most 64 characters. */
export const CLOUD_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
/** Layout contract of the cloud skill center (mirrors its store rules). */
@ -61,24 +59,6 @@ export function linkedSkillManifest(files) {
const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort();
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'));
}
/** Epoch milliseconds from a center timestamp (ISO string or epoch seconds/ms). */
function timestampMs(value) {
if (typeof value === 'number' && Number.isFinite(value))
return value < 1e12 ? value * 1000 : value;
if (typeof value === 'string' && value !== '') {
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
return undefined;
}
/** Newest local file mtime in one skill folder (0 when the folder has no files). */
function newestMtime(files) {
let newest = 0;
for (const file of files)
if (file.mtimeMs > newest)
newest = file.mtimeMs;
return newest;
}
/** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel) {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//'))
@ -123,13 +103,6 @@ export function parseSkillFrontmatter(markdown) {
}
return out;
}
/** Sidecar state: `$DSH_HOME/dsh-brain-skills.json` (legacy `cloud-memory-skills.json` migrates on first use). */
/** Absolute sidecar path, carrying the pre-rename file over on first use. */
export function skillsStatePath() {
const target = join(dshHome(), 'dsh-brain-skills.json');
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-skills.json'));
return target;
}
async function isDirectory(path) {
return stat(path).then((value) => value.isDirectory()).catch(() => false);
}
@ -156,26 +129,7 @@ export class SkillSync {
return this.deps.holdingDir?.() ?? join(dshHome(), 'skills-disabled');
}
statePath() {
return skillsStatePath();
}
/**
* Record a cloud-delivered skill. Upload provenance is cleared in the same
* transition: a skill has exactly one source of truth. Keeping both marks
* makes the DOWN pass skip the name (uploaded) while the UP pass skips its
* local folder (delivery manifest), so neither side ever syncs again.
*/
markDelivered(state, name, manifest) {
state.delivered[name] = { manifest };
delete state.uploaded[name];
}
/**
* Record a locally-originated upload. The delivery marker is cleared in the
* same transition, so the next local edit is uploaded again instead of being
* skipped as cloud-origin.
*/
markUploaded(state, name, record) {
state.uploaded[name] = record;
delete state.delivered[name];
return join(dshHome(), 'cloud-memory-skills.json');
}
async loadState() {
const clean = { version: 1, uploaded: {}, delivered: {}, removed: {} };
@ -217,10 +171,7 @@ export class SkillSync {
await walk(rel);
}
else if (entry.isFile()) {
const absolute = join(dir, rel);
const buffer = await readFile(absolute);
const info = await stat(absolute);
out.push({ rel, buffer, mtimeMs: info.mtimeMs });
out.push({ rel, buffer: await readFile(join(dir, rel)) });
}
}
};
@ -286,145 +237,6 @@ export class SkillSync {
}
return undefined;
}
/** Center's last-change time for one listed skill (ISO string or epoch). */
cloudUpdatedAt(item) {
return timestampMs(item.updated_at) ?? timestampMs(item.created_at);
}
/** Manifest over every local file, including files the center would reject. */
localManifest(files) {
return linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })));
}
/** Copy a local skill aside before an automatic cloud overwrite. */
async backupLocal(dir, name) {
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp);
await mkdir(join(backup, '..'), { recursive: true });
await cp(dir, backup, { recursive: true, filter: (path) => !path.split(/[\\/]/).includes('.git') });
return backup;
}
/**
* Local and cloud already carry the same bytes: record the delivery marker
* without a transfer, so the next pass treats the folder as cloud-origin and
* the user is not asked to pick between two identical copies.
*/
async adoptIdenticalDelivery(home, item, files) {
const delivery = {
name: item.name,
...(item.revision === undefined ? {} : { revision: item.revision }),
...(item.manifest_sha256 === undefined ? {} : { manifest_sha256: item.manifest_sha256 }),
files: files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })),
synced_at: new Date().toISOString(),
};
await writeFile(join(home, '.manifest.json'), JSON.stringify(delivery, null, 2));
}
/** Fetch, verify and install the cloud copy, backing the local one up first. */
async autoTakeCloud(item, home, installRoot, state, stats, client) {
if (item.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
return 'conflict';
}
const bundle = await client.skillBundle(item.name);
if (!bundle.ok) {
this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`);
return 'conflict';
}
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
this.conflict(stats, item.name, 'manifest_mismatch');
return 'conflict';
}
if (bundle.data.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
return 'conflict';
}
await this.backupLocal(home, item.name);
await this.install(item, bundle.data, installRoot);
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
delete state.removed[item.name];
stats.updated.push(item.name);
return 'resolved';
}
/** Upload the locally-newer copy as the next cloud revision. */
async autoUploadLocal(skill, folder, dir, cloud, state, stats, client) {
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files: this.toUploadFiles(skill.files),
expected_revision: cloud.revision ?? 0,
operation_id: `dsh-skill-${randomUUID()}`,
});
if (!updated.ok) {
const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`;
this.conflict(stats, skill.name, reason);
return 'conflict';
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
await rm(join(dir, '.manifest.json'), { force: true });
this.markUploaded(state, skill.name, {
folder,
revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
delete state.removed[skill.name];
stats.updated.push(skill.name);
return 'resolved';
}
/**
* Same-name skill on both sides without a delivery record. Identical bytes
* are adopted silently; different bytes go to whichever side is newer;
* equal/missing timestamps stay unresolved for a human decision.
*/
async autoResolveCollision(item, home, installRoot, state, stats, client) {
const localFiles = await this.readSkillFiles(home).catch(() => []);
if (!localFiles.some((file) => file.rel === 'SKILL.md'))
return 'unresolved';
if (item.manifest_sha256 !== undefined && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles);
this.markDelivered(state, item.name, item.manifest_sha256);
stats.skipped += 1;
return 'resolved';
}
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(localFiles);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, home, installRoot, state, stats, client);
const skill = await this.readLocalSkill(home, item.name);
if (skill === undefined)
return 'unresolved';
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill);
return 'conflict';
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client);
}
/**
* Cloud-delivered skill edited locally. Identical bytes refresh the marker;
* otherwise the newer side wins (cloud overwrite is backed up first).
*/
async autoResolveLocalDrift(item, home, state, stats, client, installRoot) {
const localFiles = await this.readSkillFiles(home).catch(() => []);
if (item.manifest_sha256 !== undefined && localFiles.length > 0 && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles);
this.markDelivered(state, item.name, item.manifest_sha256);
stats.skipped += 1;
return 'resolved';
}
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(localFiles);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, home, installRoot, state, stats, client);
const skill = await this.readLocalSkill(home, item.name);
if (skill === undefined)
return 'unresolved';
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill);
return 'conflict';
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client);
}
/** One full pass; never throws — outcomes land in the stats. */
async syncOnce() {
if (this.running)
@ -468,28 +280,6 @@ export class SkillSync {
const root = this.skillsRoot();
const state = await this.loadState();
let stateDirty = false;
// Self-heal sidecars written before source provenance became exclusive:
// a folder carrying a delivery manifest is cloud-delivered, even if an old
// `uploaded` record survived. Clearing the stale upload marker lets the
// DOWN pass judge local integrity (and surface a conflict) instead of
// skipping both directions forever.
for (const name of Object.keys(state.uploaded)) {
let delivery = undefined;
for (const area of [root, this.holdingRoot()]) {
const dir = join(area, name);
if (!(await isDirectory(dir)))
continue;
delivery = await this.readDelivery(dir);
if (delivery !== undefined)
break;
}
if (delivery !== undefined) {
this.markDelivered(state, name, delivery.manifest_sha256 ?? '');
stateDirty = true;
}
}
if (stateDirty)
await this.saveState(state);
// ---- DOWN: cloud center -> local directory -------------------------
for (const item of items) {
if (item.enabled === false) {
@ -528,17 +318,12 @@ export class SkillSync {
if (exists && delivery !== undefined) {
// Delivered before: local integrity is judged before any download.
if (!(await this.deliveredIntact(home, delivery))) {
const auto = await this.autoResolveLocalDrift(item, home, state, stats, client, parked ? this.holdingRoot() : root);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
this.conflict(stats, item.name, 'locally_modified');
continue;
}
if (delivery.manifest_sha256 === item.manifest_sha256) {
if (state.delivered[item.name]?.manifest !== item.manifest_sha256) {
this.markDelivered(state, item.name, item.manifest_sha256 ?? '');
state.delivered[item.name] = { manifest: item.manifest_sha256 ?? '' };
stateDirty = true;
}
stats.skipped += 1;
@ -547,14 +332,6 @@ export class SkillSync {
// Intact but the cloud moved on: fall through and install the update.
}
if (exists && delivery === undefined) {
// Same name on both sides with no delivery proof. Identical bytes are
// adopted; otherwise the newer side wins by timestamp. Only an equal
// or missing timestamp becomes a human conflict.
const auto = await this.autoResolveCollision(item, home, parked ? this.holdingRoot() : root, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
this.conflict(stats, item.name, 'name_collision');
continue;
}
@ -577,15 +354,11 @@ export class SkillSync {
continue;
}
await this.install(item, bundle.data, parked ? this.holdingRoot() : root);
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
state.delivered[item.name] = { manifest: bundle.data.manifest_sha256 };
stateDirty = true;
(exists ? stats.updated : stats.downloaded).push(item.name);
}
// ---- UP: local originals -> cloud center ---------------------------
// The DOWN pass already had the chance to resolve a same-name folder;
// don't repeat the same skill with a second reason (the panel used to show
// one card per reason for the same name).
const knownConflicts = new Set(stats.conflicts.map((entry) => entry.name));
const folders = await readdir(root, { withFileTypes: true }).catch(() => []);
const seenFolders = new Set();
for (const entry of folders) {
@ -599,37 +372,12 @@ export class SkillSync {
if (skill === undefined)
continue;
if (typeof skill === 'string') {
if (!knownConflicts.has(entry.name))
this.conflict(stats, entry.name, skill);
this.conflict(stats, entry.name, skill);
continue;
}
const record = state.uploaded[skill.name];
const cloud = cloudByName.get(skill.name);
if (cloud !== undefined && record === undefined) {
if (knownConflicts.has(skill.name))
continue;
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
// Same bytes already in the center: adopt the cloud identity without
// an upload, so the next pass compares revisions instead of names.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
const cloudAt = this.cloudUpdatedAt(cloud);
const localAt = newestMtime(skill.files);
if (cloudAt !== undefined && localAt > 0 && localAt > cloudAt) {
const auto = await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
this.conflict(stats, skill.name, 'name_collision');
continue;
}
@ -657,44 +405,18 @@ export class SkillSync {
this.conflict(stats, skill.name, `upload_failed: ${describeError(created.error)}`);
continue;
}
this.markUploaded(state, skill.name, {
state.uploaded[skill.name] = {
folder: entry.name,
revision: created.data.skill?.revision ?? created.data.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
};
stateDirty = true;
stats.uploaded.push(skill.name);
}
else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
// The center moved on since the last upload. Identical bytes just
// re-pin the revision; otherwise the newer side wins and only an
// equal/missing timestamp stays a conflict.
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
const cloudAt = this.cloudUpdatedAt(cloud);
const localAt = newestMtime(skill.files);
if (cloudAt !== undefined && localAt > 0 && cloudAt !== localAt) {
const auto = cloudAt > localAt
? await this.autoTakeCloud(cloud, dir, root, state, stats, client)
: await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
if (!knownConflicts.has(skill.name))
this.conflict(stats, skill.name, 'cloud_newer');
this.conflict(stats, skill.name, 'cloud_newer');
continue;
}
const updated = await client.updateSkill(skill.name, {
@ -708,12 +430,12 @@ export class SkillSync {
this.conflict(stats, skill.name, reason);
continue;
}
this.markUploaded(state, skill.name, {
state.uploaded[skill.name] = {
folder: entry.name,
revision: updated.data.skill?.revision ?? updated.data.revision ?? record.revision + 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
};
stateDirty = true;
stats.updated.push(skill.name);
}
@ -807,31 +529,6 @@ export class SkillSync {
dropConflict(name) {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) };
}
/**
* Resolve every current conflict with one action (`keep_local` or
* `take_cloud`). Partial failures are collected instead of aborting the
* whole batch, so the UI can show "N done, M failed" in one shot.
*/
async resolveConflicts(actionInput) {
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : '';
if (action === '')
throw new Error('invalid_action');
if (this.running)
throw new Error('sync_running');
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))];
const resolved = [];
const failed = [];
for (const name of names) {
try {
await this.resolveConflict(name, action);
resolved.push(name);
}
catch (error) {
failed.push({ name, error: error instanceof Error ? error.message : String(error) });
}
}
return { action, resolved, failed };
}
/**
* Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything.
@ -896,7 +593,7 @@ export class SkillSync {
},
canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined,
note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。',
});
}
return out;
@ -954,10 +651,7 @@ export class SkillSync {
if (!created.ok)
throw new Error(`upload_failed: ${describeError(created.error)}`);
const revision = created.data.skill?.revision ?? created.data.revision ?? 1;
// The local copy is now the upload source of truth: drop any stale
// cloud-delivery marker before committing the success state.
await rm(join(dir, '.manifest.json'), { force: true });
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() };
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
@ -975,8 +669,7 @@ export class SkillSync {
throw new Error(`upload_failed: ${describeError(updated.error)}`);
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
await rm(join(dir, '.manifest.json'), { force: true });
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() };
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
@ -993,12 +686,12 @@ export class SkillSync {
let backup = '';
if (dir !== '') {
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp);
backup = join(dshHome(), '.cloud-memory-backups', 'sync', name, stamp);
await mkdir(join(backup, '..'), { recursive: true });
await cp(dir, backup, { recursive: true, filter: (p) => !p.split(/[\\/]/).includes('.git') });
}
await this.install(cloud, bundle.data, parked ? this.holdingRoot() : root);
this.markDelivered(state, name, bundle.data.manifest_sha256);
state.delivered[name] = { manifest: bundle.data.manifest_sha256 };
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);

View File

@ -8,7 +8,7 @@
*
* Safety rules baked in:
* - the source record is the only thing trusted for a repository URL;
* - a fresh clone happens in `$DSH_HOME/.dsh-brain-staging` and the copy is
* - a fresh clone happens in `$DSH_HOME/.cloud-memory-staging` and the copy is
* filtered (no `.git`, no symlinks);
* - a backup is always taken before an update so rollback is possible even
* when the update is interrupted;
@ -24,7 +24,7 @@ import { readSkillSourceRecord, SkillAdminError } from "./skill-admin.js";
import { dshHome } from "./store.js";
/** Where pre-update backups are kept (one folder per skill, one dir per run). */
export function skillBackupsDir() {
return join(dshHome(), '.dsh-brain-backups');
return join(dshHome(), '.cloud-memory-backups');
}
/** Run git and return stdout. */
function git(args, timeoutMs = 120_000) {
@ -119,7 +119,7 @@ export class SkillUpdater {
}
/** Clone the pinned source at its latest commit into a scratch directory. */
async cloneLatest(source) {
const root = join(dshHome(), '.dsh-brain-staging');
const root = join(dshHome(), '.cloud-memory-staging');
await mkdir(root, { recursive: true });
const dir = join(root, `update_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`);
try {

View File

@ -1,5 +1,5 @@
/**
* Settings sidecar: `$DSH_HOME/dsh-brain.json` (pre-rename `cloud-memory.json` is migrated on first load).
* Settings sidecar: `$DSH_HOME/cloud-memory.json`.
*
* Why a file and not the DSH credentials service: the desktop profile has no
* stable host-side credentials face this plugin can depend on (the client-side
@ -11,7 +11,7 @@
* The file holds the two bearer tokens and the UI-editable overrides. It is
* NEVER uploaded, never printed, and `describe()` only exposes a mask.
*/
import { existsSync, copyFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, chmodSync } from 'node:fs';
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync, chmodSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { homedir } from 'node:os';
import { DEFAULT_SETTINGS, isPlaceholderBaseUrl, normalizeBaseUrl, originOf, settingsFromConfig } from "./config.js";
@ -24,29 +24,8 @@ export function dshHome() {
}
/** Absolute path of the settings sidecar. */
export function settingsPath() {
return resolve(dshHome(), 'dsh-brain.json');
}
/** Pre-rename (<=0.7.x) settings sidecar name. */
export function legacySettingsPath() {
return resolve(dshHome(), 'cloud-memory.json');
}
/**
* One-time rename carry-over: when `target` does not exist yet but the
* pre-rename `legacy` file does, copy it over so settings and tokens survive
* the dsh-cloud-memory -> dsh-brain rename. The legacy file is left in place
* (never deleted automatically). Returns true when a copy happened.
*/
export function migrateLegacyFile(target, legacy) {
try {
if (target === legacy || existsSync(target) || !existsSync(legacy))
return false;
copyFileSync(legacy, target);
return true;
}
catch {
return false;
}
}
/** Read a token from an env var (an alternative to the sidecar for CI use). */
function envToken(name) {
const value = process.env[name];
@ -129,8 +108,6 @@ export class SettingsStore {
configDefaults;
constructor(rawConfig, file = settingsPath()) {
this.file = file;
if (file === settingsPath())
migrateLegacyFile(file, legacySettingsPath());
this.configDefaults = { ...DEFAULT_SETTINGS, ...settingsFromConfig(rawConfig) };
this.state = this.read();
}
@ -180,15 +157,15 @@ export class SettingsStore {
}
/** The activity:write bearer token (sidecar first, env fallback). */
activityToken() {
return this.state.activityToken ?? envToken('DSH_BRAIN_ACTIVITY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_ACTIVITY_TOKEN') ?? '';
return this.state.activityToken ?? envToken('DSH_CLOUD_MEMORY_ACTIVITY_TOKEN') ?? '';
}
/** The memory:read / memory:write bearer token. */
memoryToken() {
return this.state.memoryToken ?? envToken('DSH_BRAIN_MEMORY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_MEMORY_TOKEN') ?? '';
return this.state.memoryToken ?? envToken('DSH_CLOUD_MEMORY_MEMORY_TOKEN') ?? '';
}
/** The summary:write bearer token (optional; absent disables summaries). */
summaryToken() {
return this.state.summaryToken ?? envToken('DSH_BRAIN_SUMMARY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_SUMMARY_TOKEN') ?? '';
return this.state.summaryToken ?? envToken('DSH_CLOUD_MEMORY_SUMMARY_TOKEN') ?? '';
}
/** Masked snapshot for the browser card. */
describe() {

View File

@ -43,11 +43,11 @@ function renderJson(_args, value) {
/** Assert the memory scope is usable, or throw a message the model can act on. */
function requireMemoryToken(deps) {
if (!deps.settings().enabled) {
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。');
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /cloud-memory 页面开启后再试。');
}
const token = deps.memoryToken();
if (token === '') {
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。');
throw new Error('未配置记忆令牌。请在 /cloud-memory 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。');
}
return token;
}

View File

@ -1,6 +1,6 @@
{
"name": "dsh-brain",
"version": "0.9.10",
"name": "dsh-cloud-memory",
"version": "0.7.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",
@ -71,12 +71,12 @@
},
"keywords": [
"agent",
"dsh-brain",
"cloud-memory",
"dsh",
"dsh-plugin",
"longmemory",
"memory",
"mnemon"
],
"author": "dsh-brain contributors"
"author": "dsh-cloud-memory contributors"
}

View File

@ -31,16 +31,13 @@ importers:
version: 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-tools':
specifier: 0.2.1-rc.3
version: 0.2.1-rc.3(de40247fb3fe9a96f927bc6c0d05f9e2)
version: 0.2.1-rc.3(1f5d0a9b849aaa1244bc4f2e453f609a)
'@types/node':
specifier: ^22.20.0
version: 22.20.5
'@types/react':
specifier: ~18.3.1
version: 18.3.31
dsh-mnemon-source-memory-spaces:
specifier: ^0.5.11
version: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
react:
specifier: ^18.2.0
version: 18.3.1
@ -552,162 +549,6 @@ packages:
resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==}
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
dsh-mnemon-provider-byterover@0.5.7:
resolution: {integrity: sha512-HSo1NbmLLh8PqWaVvsqbqh6Ay0uFmafq1ukCeAsdJ/IuzjUSu5cuKmKdlsoOD8vBhXCwzmnb96UgEb3cZUod0A==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-provider-hindsight@0.5.7:
resolution: {integrity: sha512-sOEThpl56k6DuqSvOrma9ZFMAFmfll/XuUOLZkJ/4nB4M5z/fYvKMTMAmJ2PXUhWPO3KEnOj5m+V5axmrZefbg==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-provider-holographic@0.5.7:
resolution: {integrity: sha512-WFzAILBve6zhG1+ZFOxHBNRacMdKyeh3VebfARhQglKRqXYiw4JQAFEFaPwqYx7dZfL6XYySQN/EiLF0idMn9Q==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-provider-honcho@0.5.5:
resolution: {integrity: sha512-TKtpODsQ6MeLZ1zCgca37s656u9q89M1SimTqSvT6/GCRiqi9A0mAbqAj1uzAMcbTuHOYAr3hFSAQYo55TbcXQ==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-provider-mem0@0.5.5:
resolution: {integrity: sha512-rxCSNx/TTMeaj7BjneMYtQOUjzNFiYB/7rFPZitBzQGdJmzVrm1KVDPZplXvHZaZ2XdQ86yfT1R+Le7NLjvrsQ==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-provider-mnemon-native@0.5.11:
resolution: {integrity: sha512-rS/XVk6kd6JWXg+qM2zzm+ycRWQrTg9aBBSn56ZgJbL5y8l1+LTBTPslc1rJ4tWSHwtqYPBjWmeY9IYvRWMLMA==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-provider-openviking@0.5.10:
resolution: {integrity: sha512-S/e/zdEOHvHcuY7yrQuvAX2OKRXVRLqg+2CJU0ZM0EHT1G6/uscO8PsCbwXAjTcTvCO8fzkzbnC0TmkPXxIObg==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-provider-retaindb@0.5.6:
resolution: {integrity: sha512-NyvMiF3G+WEmEYFyWrI7FhWdQAGYQnPWzLY2/K42ip5eV9ycVvMkeA6igowwvPbvVWuN7zdCFOGPHg+iNYT3Bw==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-provider-supermemory@0.5.5:
resolution: {integrity: sha512-IvBpeRV1Gl/gACasyQZ9UmdsJhEoO3frzi2+SrOBqDuMqfus4kgdcadBMFcZJzrtq65h30arIRcSIIB3ZZda+w==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon-source-memory-spaces: ^0.5.1
dsh-mnemon-source-documents@0.6.0:
resolution: {integrity: sha512-QMBavZq3GrVW1n/ByDhEaSBjOIGxysf1iXKM1I4KZiFN+TmmSeLDSpLI2vRS0ern2FbZ6hiPaojRX32eFQjuWA==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.40
react: ^18.2.0
peerDependenciesMeta:
react:
optional: true
dsh-mnemon-source-memory-spaces@0.5.27:
resolution: {integrity: sha512-Vha4m0Acu1cwoKMJzeVb4kqiFVjHWYihrkFxMM7ouhWGKBE9+33DjXfWDD0aCi4AT4bNAWere63/8v/at8IwOg==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.19
react: ^18.2.0
peerDependenciesMeta:
react:
optional: true
dsh-mnemon-source-runtime@0.5.19:
resolution: {integrity: sha512-FcHkcn9v53cwYS5Mp7Nhn2PH6hzV945Ua6PKGXUUlyz96+1bvk/VJkG4UYI/89HEMq7WiwwNE9aJI7sHD5OznA==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.43
react: ^18.2.0
peerDependenciesMeta:
react:
optional: true
dsh-mnemon-source-skills@0.5.11:
resolution: {integrity: sha512-p1KL2VgMpwCr5otdQSmLvMD8D+7nlDqTF0bImIZ3e2y/KUf+1Pyn6ie8e9E0BuY8pu5IINc3lFMcH6qaspUdLw==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.37
react: ^18.2.0
peerDependenciesMeta:
react:
optional: true
dsh-mnemon-strategy-auto-capture@0.5.5:
resolution: {integrity: sha512-jSCjednHJmDatWavhhDly8dnoNuclImx2H0U0EB8OgMw00xXXL/nWOHQLxKabOJnEykaDdl2EX7rTBX5xTuOJw==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.17
dsh-mnemon-strategy-default-three-tier@0.5.13:
resolution: {integrity: sha512-02/CEgd1fKqnD18nwxkiZsWXSmXIAuL/SlPOAioRPrqbB2py6lWhJEsgXZfmaGidwtUfwsyr/t6V04bA2noDPQ==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.43
dsh-mnemon-strategy-general@0.5.2:
resolution: {integrity: sha512-8pbutlZ9Lo4T5MY7rLf6zCbwUzRoDtYLxot/Vsb0KMirHc2Ec/Tckao/OPm9StxtJ71K5RRGexZQve17Yh6ZGA==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.43
dsh-mnemon-strategy-light-context@0.5.6:
resolution: {integrity: sha512-rpuIqIiFQpWQEveQehLaO3b1wX1NeAEMUKChZ8NFa4+RwcPAX47t081VgRAWNnw4NgclenAenp9mTAQXOzmmxA==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.17
dsh-mnemon-strategy-scoped@0.5.5:
resolution: {integrity: sha512-HyJRpv4s8DzE9GZm7FnKUhxtwjv0eD9xcsYt5zQUbX1pH0e7jtkqaeozPfPgp0DHvjmv2nOaKOxDLzaw3B01qg==}
engines: {node: '>=20'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1
dsh-mnemon: ^0.5.17
dsh-mnemon@0.5.44:
resolution: {integrity: sha512-J4W+x8jMk7NMCkdpm8CcfjUjQdb/AzdQ/q0EjpphfDDVVYEMVdhMao281/ArLixo5Xqomw431SZ/EEfmoP85eA==}
engines: {dsh: '>=0.2.0-rc.2 <0.2.1-0 || >=0.2.1-rc.1 <0.3.0-0', node: '>=20'}
hasBin: true
peerDependencies:
'@deepseek-ai/cordis': ^4.0.4
'@deepseek-ai/dsh-app-boot': '>=0.2.0-rc.2 <0.2.1-0 || >=0.2.1-rc.1 <0.3.0-0'
'@deepseek-ai/dsh-typert-protocol': '>=0.2.0-rc.2 <0.2.1-0 || >=0.2.1-rc.1 <0.3.0-0'
react: ^18.2.0
react-dom: ^18.2.0
peerDependenciesMeta:
'@deepseek-ai/dsh-app-boot':
optional: true
dts-resolver@3.0.0:
resolution: {integrity: sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q==}
engines: {node: ^22.18.0 || >=24.0.0}
@ -730,9 +571,6 @@ packages:
picomatch:
optional: true
fflate@0.8.3:
resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
get-tsconfig@5.0.0-beta.5:
resolution: {integrity: sha512-/6gFNr0N04nob252sTQxyFLi3eKFRqIg1I87YcqAMT1i6SQrSF6KujUEQrtrjMV0H/eejTCltLdDSTEMzHbnsQ==}
engines: {node: '>=20.20.0'}
@ -755,15 +593,6 @@ packages:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
markdown-to-jsx@7.7.17:
resolution: {integrity: sha512-7mG/1feQ0TX5I7YyMZVDgCC/y2I3CiEhIRQIhyov9nGBP5eoVrOXXHuL5ZP8GRfxVZKRiXWJgwXkb9It+nQZfQ==}
engines: {node: '>= 10'}
peerDependencies:
react: '>= 0.14.0'
peerDependenciesMeta:
react:
optional: true
mime-db@1.54.0:
resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}
engines: {node: '>= 0.6'}
@ -794,11 +623,6 @@ packages:
quansync@1.0.0:
resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==}
react-dom@18.3.1:
resolution: {integrity: sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==}
peerDependencies:
react: ^18.3.1
react@18.3.1:
resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
engines: {node: '>=0.10.0'}
@ -833,9 +657,6 @@ packages:
safe-buffer@5.2.1:
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
scheduler@0.23.2:
resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==}
tinyexec@1.3.1:
resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==}
engines: {node: '>=18'}
@ -901,11 +722,6 @@ packages:
resolution: {integrity: sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg==}
engines: {node: '>=18.12.0'}
yaml@2.9.1:
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
engines: {node: '>= 14.6'}
hasBin: true
yuku-ast@0.8.7:
resolution: {integrity: sha512-h6+4bDfyootiMB9vckk5uKo5r5j0GHrkr17FQTDNfEsFT3DWlN9uu1HJwQwc64pgmLCI945fWM3lbTIqxjT3GQ==}
@ -930,7 +746,7 @@ snapshots:
'@deepseek-ai/cosmokit@1.8.6': {}
'@deepseek-ai/dsh-agent@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))':
'@deepseek-ai/dsh-agent@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))':
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
@ -938,6 +754,7 @@ snapshots:
'@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-session-projection': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))
'@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-typert-protocol': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-brand@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)':
@ -995,10 +812,10 @@ snapshots:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))
'@deepseek-ai/dsh-sandbox-policy@0.2.1-rc.3(932a8c9290b147b4006ae83c0c80e8b7)':
'@deepseek-ai/dsh-sandbox-policy@0.2.1-rc.3(1809d3b5f9b8552c21c008788fe3c75e)':
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))
'@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-session-projection': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))
@ -1042,21 +859,21 @@ snapshots:
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/dsh-tools@0.2.1-rc.3(de40247fb3fe9a96f927bc6c0d05f9e2)':
'@deepseek-ai/dsh-tools@0.2.1-rc.3(1f5d0a9b849aaa1244bc4f2e453f609a)':
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-ptc-runtime': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))
'@deepseek-ai/dsh-sandbox': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))
'@deepseek-ai/dsh-sandbox-policy': 0.2.1-rc.3(932a8c9290b147b4006ae83c0c80e8b7)
'@deepseek-ai/dsh-sandbox-policy': 0.2.1-rc.3(1809d3b5f9b8552c21c008788fe3c75e)
'@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-system-prompt': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-user-approval': 0.2.1-rc.3(856328efff7c71cc58c5b7a4d588f39f)
'@deepseek-ai/dsh-user-approval': 0.2.1-rc.3(f3a61cdc614c420235807a61121b4b4a)
'@deepseek-ai/dsh-util-values': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-working-directory': 0.2.1-rc.3(2a45e52deb8cccc1107ad1bfba7ff2c5)
'@deepseek-ai/dsh-working-directory': 0.2.1-rc.3(b3db524bc35e44edbf239e3bbf3fca0a)
'@deepseek-ai/schemastery': 3.18.5
'@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)':
@ -1065,10 +882,10 @@ snapshots:
'@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
zod: 4.6.7
'@deepseek-ai/dsh-user-approval@0.2.1-rc.3(856328efff7c71cc58c5b7a4d588f39f)':
'@deepseek-ai/dsh-user-approval@0.2.1-rc.3(f3a61cdc614c420235807a61121b4b4a)':
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-brand': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-scope': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
@ -1084,10 +901,10 @@ snapshots:
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/dsh-working-directory@0.2.1-rc.3(2a45e52deb8cccc1107ad1bfba7ff2c5)':
'@deepseek-ai/dsh-working-directory@0.2.1-rc.3(b3db524bc35e44edbf239e3bbf3fca0a)':
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-agent': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session-projection@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-system-prompt@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)))(@deepseek-ai/dsh-typert-protocol@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-util-values@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
'@deepseek-ai/dsh-fs': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-brand@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-sandbox@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-llm@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))(@deepseek-ai/dsh-session@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))))
'@deepseek-ai/dsh-llm': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)
'@deepseek-ai/dsh-session': 0.2.1-rc.3(@deepseek-ai/cordis@4.0.5)(@deepseek-ai/dsh-scope@0.2.1-rc.3(@deepseek-ai/cordis@4.0.5))
@ -1276,139 +1093,6 @@ snapshots:
destroy@1.2.0: {}
dsh-mnemon-provider-byterover@0.5.7(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-provider-hindsight@0.5.7(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-provider-holographic@0.5.7(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-provider-honcho@0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-provider-mem0@0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-provider-mnemon-native@0.5.11(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-provider-openviking@0.5.10(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-provider-retaindb@0.5.6(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-provider-supermemory@0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-source-documents@0.6.0(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1):
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/schemastery': 3.18.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
markdown-to-jsx: 7.7.17(react@18.3.1)
optionalDependencies:
react: 18.3.1
dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1):
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/schemastery': 3.18.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
optionalDependencies:
react: 18.3.1
dsh-mnemon-source-runtime@0.5.19(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1):
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/schemastery': 3.18.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
optionalDependencies:
react: 18.3.1
dsh-mnemon-source-skills@0.5.11(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
markdown-to-jsx: 7.7.17(react@18.3.1)
yaml: 2.9.1
optionalDependencies:
react: 18.3.1
dsh-mnemon-strategy-auto-capture@0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
dsh-mnemon-strategy-default-three-tier@0.5.13(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
dsh-mnemon-strategy-general@0.5.2(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
dsh-mnemon-strategy-light-context@0.5.6(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
dsh-mnemon-strategy-scoped@0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)):
dependencies:
'@deepseek-ai/cordis': 4.0.5
dsh-mnemon: 0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
dependencies:
'@deepseek-ai/cordis': 4.0.5
'@deepseek-ai/cosmokit': 1.8.6
'@deepseek-ai/schemastery': 3.18.5
dsh-mnemon-provider-byterover: 0.5.7(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-provider-hindsight: 0.5.7(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-provider-holographic: 0.5.7(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-provider-honcho: 0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-provider-mem0: 0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-provider-mnemon-native: 0.5.11(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-provider-openviking: 0.5.10(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-provider-retaindb: 0.5.6(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-provider-supermemory: 0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon-source-memory-spaces@0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1))
dsh-mnemon-source-documents: 0.6.0(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-source-memory-spaces: 0.5.27(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-source-runtime: 0.5.19(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-source-skills: 0.5.11(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
dsh-mnemon-strategy-auto-capture: 0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))
dsh-mnemon-strategy-default-three-tier: 0.5.13(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))
dsh-mnemon-strategy-general: 0.5.2(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))
dsh-mnemon-strategy-light-context: 0.5.6(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))
dsh-mnemon-strategy-scoped: 0.5.5(@deepseek-ai/cordis@4.0.5)(dsh-mnemon@0.5.44(@deepseek-ai/cordis@4.0.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))
fflate: 0.8.3
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
yaml: 2.9.1
zod: 4.6.7
dts-resolver@3.0.0: {}
empathic@2.1.0: {}
@ -1417,8 +1101,6 @@ snapshots:
optionalDependencies:
picomatch: 4.0.7
fflate@0.8.3: {}
get-tsconfig@5.0.0-beta.5:
dependencies:
resolve-pkg-maps: 1.0.0
@ -1435,10 +1117,6 @@ snapshots:
dependencies:
js-tokens: 4.0.0
markdown-to-jsx@7.7.17(react@18.3.1):
optionalDependencies:
react: 18.3.1
mime-db@1.54.0: {}
ms@2.0.0: {}
@ -1457,12 +1135,6 @@ snapshots:
quansync@1.0.0: {}
react-dom@18.3.1(react@18.3.1):
dependencies:
loose-envify: 1.4.0
react: 18.3.1
scheduler: 0.23.2
react@18.3.1:
dependencies:
loose-envify: 1.4.0
@ -1506,10 +1178,6 @@ snapshots:
safe-buffer@5.2.1: {}
scheduler@0.23.2:
dependencies:
loose-envify: 1.4.0
tinyexec@1.3.1: {}
tinyglobby@0.2.17:
@ -1557,8 +1225,6 @@ snapshots:
verkit@0.3.2: {}
yaml@2.9.1: {}
yuku-ast@0.8.7:
dependencies:
'@yuku-toolchain/types': 0.8.7

View File

@ -19,7 +19,7 @@ const store = new SettingsStore({})
const admin = new SkillAdmin({
skillsRoot: () => join(store.path, '..', 'skills'),
holdingDir: () => skillsHoldingDir(),
syncStatePath: () => join(store.path, '..', 'dsh-brain-skills.json'),
syncStatePath: () => join(store.path, '..', 'cloud-memory-skills.json'),
syncRunning: () => false,
log: () => {},
})
@ -46,7 +46,7 @@ const statusBody = {
memory: { configured: true, masked: 'cmt_3b81cc…22a9' },
summary: { configured: true, masked: 'cmt_71ad02…9f10' },
},
settingsPath: 'C:/Users/qyh15/.dsh/dsh-brain.json',
settingsPath: 'C:/Users/qyh15/.dsh/cloud-memory.json',
reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] },
lastCheck: {
at: Date.now(),
@ -215,9 +215,9 @@ function requireShim(id) {
async function fakeFetch(url) {
const path = String(url).split('?')[0]
let body = { ok: false }
if (path === '/dsh-brain/status') body = statusBody
else if (path === '/dsh-brain/skills/sources') body = { ok: true, ...overview }
else if (path.startsWith('/dsh-brain/skills/api')) body = { ok: true, skills: overview.sources[0]?.groups.flatMap((group) => group.skills) ?? [], plans: [] }
if (path === '/cloud-memory/status') body = statusBody
else if (path === '/cloud-memory/skills/sources') body = { ok: true, ...overview }
else if (path.startsWith('/cloud-memory/skills/api')) body = { ok: true, skills: overview.sources[0]?.groups.flatMap((group) => group.skills) ?? [], plans: [] }
return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) }
}

View File

@ -1,360 +0,0 @@
// Renders the redesigned 「从其他软件导入」 panel to a PNG so the layout can be
// reviewed before DSH is restarted. It reads the *live* skill sources through
// the built plugin (read-only), expands the import panel, and screenshots the
// result with headless Chrome.
import { execFileSync } from 'node:child_process'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
// ── real data ───────────────────────────────────────────────────────────
const { SkillAdmin, skillsHoldingDir } = await import('./lib/skill-admin.js')
const { SkillGroupManager, detectSources } = await import('./lib/skill-groups.js')
const { SettingsStore } = await import('./lib/store.js')
const store = new SettingsStore({})
const admin = new SkillAdmin({
skillsRoot: () => join(store.path, '..', 'skills'),
holdingDir: () => skillsHoldingDir(),
syncStatePath: () => join(store.path, '..', 'dsh-brain-skills.json'),
syncRunning: () => false,
log: () => {},
})
const groups = new SkillGroupManager({ sources: () => detectSources(), admin, log: () => {} })
const overview = await groups.overview()
const statusBody = {
ok: true,
settings: {
enabled: true,
baseUrl: 'https://your-memory-host/api/longmemory',
baseUrlConfigured: true,
baseUrlOrigin: 'https://your-memory-host',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
summaryEnabled: true,
summaryMaxChars: 6000,
skillsSyncEnabled: true,
skillsDir: '',
},
tokens: {
activity: { configured: true, masked: 'cmt_9f2c1a…7d4e' },
memory: { configured: true, masked: 'cmt_3b81cc…22a9' },
summary: { configured: true, masked: 'cmt_71ad02…9f10' },
},
settingsPath: '%USERPROFILE%/.dsh/dsh-brain.json',
reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] },
lastCheck: {
at: Date.now(),
checks: [
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 200)' },
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'ok', message: '鉴权通过' },
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(3 个项目)' },
{ id: 'summary', label: '摘要权限(summary:write)', state: 'ok', message: '鉴权通过' },
],
},
capabilities: { version: '0.9.7', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
skills: { running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 },
}
// ── minimal React + HTML serializer ─────────────────────────────────────
let hooks = []
let cursor = 0
let pendingEffects = []
let scheduled = false
const React = {
createElement(type, props, ...children) {
const flat = []
const push = (value) => {
if (Array.isArray(value)) value.forEach(push)
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
}
push(children)
return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat }
},
useState(initial) {
const index = cursor++
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
const setter = (next) => {
const value = typeof next === 'function' ? next(hooks[index]) : next
if (value !== hooks[index]) {
hooks[index] = value
scheduled = true
}
}
return [hooks[index], setter]
},
useEffect(fn) {
pendingEffects.push(fn)
},
useCallback(fn) {
return fn
},
Component: function Component(props) {
this.props = props
},
}
React.Component.prototype.setState = function setState(patch) {
this.state = { ...this.state, ...patch }
scheduled = true
}
function walk(node, visit) {
if (node === null || node === undefined || node === false || node === true) return
if (typeof node === 'string' || typeof node === 'number') return
if (Array.isArray(node)) {
node.forEach((child) => walk(child, visit))
return
}
if (typeof node.type === 'function') {
if (node.type.prototype && typeof node.type.prototype.render === 'function') {
const instance = new node.type(node.props)
instance.props = node.props
if (instance.state === undefined) instance.state = {}
instance.setState = function setState(patch) {
instance.state = { ...instance.state, ...patch }
scheduled = true
}
walk(instance.render(), visit)
return
}
walk(node.type({ ...node.props, children: node.children }), visit)
return
}
visit(node)
node.children.forEach((child) => walk(child, visit))
}
const UNITLESS = new Set(['fontWeight', 'opacity', 'lineHeight', 'flex', 'zIndex', 'flexGrow', 'flexShrink'])
function styleOf(style) {
const parts = []
for (const [key, value] of Object.entries(style ?? {})) {
if (value === null || value === undefined) continue
const name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
parts.push(`${name}:${typeof value === 'number' && !UNITLESS.has(key) ? `${value}px` : String(value)}`)
}
return parts.join(';')
}
function escapeHtml(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
function toHtml(node) {
if (node === null || node === undefined || node === false || node === true) return ''
if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node)
if (Array.isArray(node)) return node.map(toHtml).join('')
const { type, props, children } = node
if (typeof type === 'function') {
if (type.prototype && typeof type.prototype.render === 'function') {
const instance = new type(props)
instance.props = props
if (instance.state === undefined) instance.state = {}
return toHtml(instance.render())
}
return toHtml(type({ ...props, children }))
}
const attrs = []
const style = styleOf(props.style)
if (style !== '') attrs.push(`style="${style}"`)
if (props.id !== undefined) attrs.push(`id="${escapeHtml(props.id)}"`)
if (props.role !== undefined) attrs.push(`role="${escapeHtml(props.role)}"`)
if (props.title !== undefined) attrs.push(`title="${escapeHtml(props.title)}"`)
if (props.disabled === true) attrs.push('disabled')
if (props.type === 'checkbox') attrs.push(props.checked === true ? 'checked' : '')
for (const [key, value] of Object.entries(props)) {
if (key.startsWith('aria-')) attrs.push(`${key}="${escapeHtml(value)}"`)
}
if (type === 'input') {
attrs.push(`value="${escapeHtml(props.value === undefined ? '' : props.value)}"`)
attrs.push(`placeholder="${escapeHtml(props.placeholder === undefined ? '' : props.placeholder)}"`)
attrs.push(`type="${escapeHtml(props.type === undefined ? 'text' : props.type)}"`)
return `<input ${attrs.filter(Boolean).join(' ')}>`
}
return `<${type} ${attrs.filter(Boolean).join(' ')}>${children.map(toHtml).join('')}</${type}>`
}
// ── drive the real bundle ───────────────────────────────────────────────
const localStorageStub = {
getItem: (key) => (String(key).endsWith(':tab') ? 'skills' : null),
setItem: () => {},
}
let registered = null
globalThis.window = {
localStorage: localStorageStub,
addEventListener: () => {},
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({
slots: {
inject: (_seat, fn) => fn(),
register: (_options, component) => {
captured.push(component)
return () => {}
},
},
})
registered = captured[0]
},
},
}
function requireShim(id) {
if (id === 'react') return React
throw new Error(`unexpected require: ${id}`)
}
const fakeFetch = async (url) => {
const path = String(url).split('?')[0]
let body = { ok: false }
if (path === '/dsh-brain/status') body = statusBody
else if (path === '/dsh-brain/skills/sources') body = { ok: true, ...overview }
else if (path === '/dsh-brain/sync/status') body = { ok: true, stats: { running: false, lastRunAt: Date.now(), uploaded: [], downloaded: [] }, conflicts: [] }
else if (path.startsWith('/dsh-brain/skills/api')) {
body = { ok: true, skills: overview.sources[0]?.groups.flatMap((group) => group.skills) ?? [], plans: [] }
}
return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) }
}
function loadCard() {
registered = null
new Function('window', 'require', 'document', 'localStorage', 'fetch', 'console', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'AbortController', source)(
globalThis.window,
requireShim,
{ visibilityState: 'visible' },
localStorageStub,
fakeFetch,
{ warn: () => {}, log: () => {} },
() => 0,
() => {},
() => 0,
() => {},
AbortController,
)
return registered
}
async function settle(element, passes) {
let text = ''
for (let pass = 0; pass < passes; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
text = toHtml(element)
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
return text
}
function clickLabel(root, prefix) {
let clicked = false
walk(root, (node) => {
if (clicked) return
const props = node.props ?? {}
const label = props['aria-label']
const text = typeof props.children === 'string' ? props.children : ''
const matches = (typeof label === 'string' && label.startsWith(prefix)) || text.startsWith(prefix)
if (matches && typeof props.onClick === 'function') {
props.onClick()
clicked = true
}
})
return clicked
}
function typeInto(root, label, value) {
let typed = false
walk(root, (node) => {
if (typed) return
const props = node.props ?? {}
if (props['aria-label'] === label && typeof props.onChange === 'function') {
props.onChange({ target: { value } })
typed = true
}
})
return typed
}
const card = loadCard()
const treeEl = React.createElement(card, null)
const firstBody = await settle(treeEl, 6)
if (!firstBody.includes('技能文件夹')) console.log('debug body head:', firstBody.slice(0, 600))
cursor = 0
pendingEffects = []
if (!clickLabel(treeEl, '从其他软件导入')) throw new Error('preview: could not find the import button')
const body = await settle(treeEl, 6)
if (body.includes('渲染失败')) throw new Error('the card rendered its error boundary')
// Second view: search filters the candidate list, then select-all-matched.
cursor = 0
pendingEffects = []
if (!typeInto(treeEl, '搜索要导入的技能', 'nature')) throw new Error('preview: could not find the import search box')
await settle(treeEl, 6)
cursor = 0
pendingEffects = []
if (!clickLabel(treeEl, '全选匹配可导入')) console.warn('preview: select-all was not clickable')
const searchBody = await settle(treeEl, 6)
// Third view: dark theme, default (unfiltered) state.
cursor = 0
pendingEffects = []
typeInto(treeEl, '搜索要导入的技能', '')
clickLabel(treeEl, '清空已选')
const darkBody = await settle(treeEl, 6)
const page = (content, theme) => `<!doctype html><html><head><meta charset="utf-8">
<style>
html,body{margin:0;padding:0}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",system-ui,sans-serif;
background:${theme === 'dark' ? '#101216' : '#f3f5f9'};color:${theme === 'dark' ? '#e8eaee' : '#1a1d21'}}
.frame{width:600px;margin:0 auto;padding:18px 20px 24px}
.panel{border-radius:14px;padding:16px;
background:${theme === 'dark' ? '#191c22' : '#ffffff'};
box-shadow:0 10px 30px rgba(0,0,0,${theme === 'dark' ? '0.45' : '0.10'})}
button{font-family:inherit}
input{font-family:inherit;color:inherit}
</style></head><body><div class="frame"><div class="panel">${content}</div></div></body></html>`
const outDir = join(here, '_preview')
mkdirSync(outDir, { recursive: true })
const lightPath = join(outDir, 'import-light.html')
const searchPath = join(outDir, 'import-search.html')
const darkPath = join(outDir, 'import-dark.html')
writeFileSync(lightPath, page(body, 'light'), 'utf8')
writeFileSync(searchPath, page(searchBody, 'light'), 'utf8')
writeFileSync(darkPath, page(darkBody, 'dark'), 'utf8')
const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
for (const [input, output, height] of [
[lightPath, join(outDir, 'import-light.png'), 2600],
[searchPath, join(outDir, 'import-search.png'), 1600],
[darkPath, join(outDir, 'import-dark.png'), 2600],
]) {
execFileSync(chrome, [
'--headless=new',
'--disable-gpu',
'--hide-scrollbars',
'--force-device-scale-factor=2',
`--window-size=640,${height}`,
`--screenshot=${output}`,
`file:///${input.replace(/\\/g, '/')}`,
], { stdio: 'ignore' })
console.log(`wrote ${output}`)
}
console.log('sources:', overview.sources.map((item) => `${item.label}=${item.total}`).join(', '))

View File

@ -1,344 +0,0 @@
// Renders the MCP management tab to a PNG so the search / select-all / batch
// layout can be reviewed before DSH is restarted. Data is a representative
// catalogue (no real host bridge is called); the render tree is the real one.
import { execFileSync } from 'node:child_process'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
const statusBody = {
ok: true,
settings: {
enabled: true,
baseUrl: 'https://your-memory-host/api/longmemory',
baseUrlConfigured: true,
baseUrlOrigin: 'https://your-memory-host',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
summaryEnabled: true,
summaryMaxChars: 6000,
skillsSyncEnabled: true,
skillsDir: '',
},
tokens: {
activity: { configured: true, masked: 'cmt_9f2c1a…7d4e' },
memory: { configured: true, masked: 'cmt_3b81cc…22a9' },
summary: { configured: true, masked: 'cmt_71ad02…9f10' },
},
settingsPath: '%USERPROFILE%/.dsh/dsh-brain.json',
reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] },
lastCheck: {
at: Date.now(),
checks: [
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 200)' },
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'ok', message: '鉴权通过' },
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(3 个项目)' },
{ id: 'summary', label: '摘要权限(summary:write)', state: 'ok', message: '鉴权通过' },
],
},
capabilities: { version: '0.9.7', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
skills: { running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 },
}
const connections = [
{ key: 'github', connectorId: 'c-github', name: 'github', transport: 'streamable-http', authMode: 'bearer', injectionLabel: '会话级', connectionState: 'connected', enabled: true, scope: { visibility: 'workspace' }, healthCheckedAt: Date.now() - 120000, lastError: null },
{ key: 'notion', connectorId: 'c-notion', name: 'notion', transport: 'streamable-http', authMode: 'oauth2', injectionLabel: '会话级', connectionState: 'connected', enabled: true, scope: { visibility: 'session' }, healthCheckedAt: Date.now() - 900000, lastError: null },
{ key: 'chrome-devtools', connectorId: 'c-chrome', name: 'chrome-devtools', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'connected', enabled: true, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 60000, lastError: null },
{ key: 'filesystem', connectorId: 'c-fs', name: 'filesystem', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'disabled', enabled: false, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 86400000, lastError: null },
{ key: 'postgres', connectorId: 'c-pg', name: 'postgres', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'error', enabled: true, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 3600000, lastError: 'spawn postgres-mcp ENOENT' },
{ key: 'brave-search', connectorId: 'c-brave', name: 'brave-search', transport: 'streamable-http', authMode: 'api-key', injectionLabel: '会话级', connectionState: 'unknown', enabled: true, scope: { visibility: 'session' }, healthCheckedAt: null, lastError: null },
]
// ── minimal React + HTML serializer ─────────────────────────────────────
let hooks = []
let cursor = 0
let pendingEffects = []
let scheduled = false
const React = {
createElement(type, props, ...children) {
const flat = []
const push = (value) => {
if (Array.isArray(value)) value.forEach(push)
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
}
push(children)
return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat }
},
useState(initial) {
const index = cursor++
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
const setter = (next) => {
const value = typeof next === 'function' ? next(hooks[index]) : next
if (value !== hooks[index]) {
hooks[index] = value
scheduled = true
}
}
return [hooks[index], setter]
},
useEffect(fn) {
pendingEffects.push(fn)
},
useCallback(fn) {
return fn
},
Component: function Component(props) {
this.props = props
},
}
React.Component.prototype.setState = function setState(patch) {
this.state = { ...this.state, ...patch }
scheduled = true
}
function walk(node, visit) {
if (node === null || node === undefined || node === false || node === true) return
if (typeof node === 'string' || typeof node === 'number') return
if (Array.isArray(node)) {
node.forEach((child) => walk(child, visit))
return
}
if (typeof node.type === 'function') {
if (node.type.prototype && typeof node.type.prototype.render === 'function') {
const instance = new node.type(node.props)
instance.props = node.props
if (instance.state === undefined) instance.state = {}
instance.setState = function setState(patch) {
instance.state = { ...instance.state, ...patch }
scheduled = true
}
walk(instance.render(), visit)
return
}
walk(node.type({ ...node.props, children: node.children }), visit)
return
}
visit(node)
node.children.forEach((child) => walk(child, visit))
}
const UNITLESS = new Set(['fontWeight', 'opacity', 'lineHeight', 'flex', 'zIndex', 'flexGrow', 'flexShrink'])
function styleOf(style) {
const parts = []
for (const [key, value] of Object.entries(style ?? {})) {
if (value === null || value === undefined) continue
const name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
parts.push(`${name}:${typeof value === 'number' && !UNITLESS.has(key) ? `${value}px` : String(value)}`)
}
return parts.join(';')
}
function escapeHtml(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
function toHtml(node) {
if (node === null || node === undefined || node === false || node === true) return ''
if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node)
if (Array.isArray(node)) return node.map(toHtml).join('')
const { type, props, children } = node
if (typeof type === 'function') {
if (type.prototype && typeof type.prototype.render === 'function') {
const instance = new type(props)
instance.props = props
if (instance.state === undefined) instance.state = {}
return toHtml(instance.render())
}
return toHtml(type({ ...props, children }))
}
const attrs = []
const style = styleOf(props.style)
if (style !== '') attrs.push(`style="${style}"`)
if (props.id !== undefined) attrs.push(`id="${escapeHtml(props.id)}"`)
if (props.role !== undefined) attrs.push(`role="${escapeHtml(props.role)}"`)
if (props.title !== undefined) attrs.push(`title="${escapeHtml(props.title)}"`)
if (props.disabled === true) attrs.push('disabled')
if (props.type === 'checkbox') attrs.push(props.checked === true ? 'checked' : '')
for (const [key, value] of Object.entries(props)) {
if (key.startsWith('aria-')) attrs.push(`${key}="${escapeHtml(value)}"`)
}
if (type === 'input') {
attrs.push(`value="${escapeHtml(props.value === undefined ? '' : props.value)}"`)
attrs.push(`placeholder="${escapeHtml(props.placeholder === undefined ? '' : props.placeholder)}"`)
attrs.push(`type="${escapeHtml(props.type === undefined ? 'text' : props.type)}"`)
return `<input ${attrs.filter(Boolean).join(' ')}>`
}
return `<${type} ${attrs.filter(Boolean).join(' ')}>${children.map(toHtml).join('')}</${type}>`
}
// ── drive the real bundle ───────────────────────────────────────────────
const localStorageStub = {
getItem: (key) => (String(key).endsWith(':tab') ? 'mcp' : null),
setItem: () => {},
}
let registered = null
globalThis.window = {
localStorage: localStorageStub,
addEventListener: () => {},
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({
slots: {
inject: (_seat, fn) => fn(),
register: (_options, component) => {
captured.push(component)
return () => {}
},
},
})
registered = captured[0]
},
},
}
function requireShim(id) {
if (id === 'react') return React
throw new Error(`unexpected require: ${id}`)
}
const fakeFetch = async (url, init) => {
const path = String(url).split('?')[0]
let body = { ok: false }
if (path === '/dsh-brain/status') body = statusBody
else if (path === '/dsh-brain/sync/status') body = { ok: true, stats: { running: false, lastRunAt: Date.now(), uploaded: [], downloaded: [] }, conflicts: [] }
else if (path === '/mcp-connector/api') {
let method = 'status'
try {
method = JSON.parse(init?.body ?? '{}').method ?? 'status'
} catch {
method = 'status'
}
body = method === 'status'
? { ok: true, message: '共 ' + connections.length + ' 条连接', detail: { items: connections, scope: {} } }
: { ok: true, message: '演示数据:' + method + ' 已受理' }
}
return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) }
}
function loadCard() {
registered = null
new Function('window', 'require', 'document', 'localStorage', 'fetch', 'console', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'AbortController', source)(
globalThis.window,
requireShim,
{ visibilityState: 'visible' },
localStorageStub,
fakeFetch,
{ warn: () => {}, log: () => {} },
() => 0,
() => {},
() => 0,
() => {},
AbortController,
)
return registered
}
async function settle(element, passes) {
let text = ''
for (let pass = 0; pass < passes; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
text = toHtml(element)
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
return text
}
function clickLabel(root, prefix) {
let clicked = false
walk(root, (node) => {
if (clicked) return
const props = node.props ?? {}
const label = props['aria-label']
const text = typeof props.children === 'string' ? props.children : ''
if (((typeof label === 'string' && label.startsWith(prefix)) || text.startsWith(prefix)) && typeof props.onClick === 'function') {
props.onClick()
clicked = true
}
})
return clicked
}
function typeInto(root, label, value) {
let typed = false
walk(root, (node) => {
if (typed) return
const props = node.props ?? {}
if (props['aria-label'] === label && typeof props.onChange === 'function') {
props.onChange({ target: { value } })
typed = true
}
})
return typed
}
const card = loadCard()
const treeEl = React.createElement(card, null)
const firstBody = await settle(treeEl, 6)
if (!firstBody.includes('我的连接')) throw new Error('preview: MCP tab did not render')
// View 2: filter to streamable-http connections and select them all.
cursor = 0
pendingEffects = []
typeInto(treeEl, '搜索 MCP 连接', 'search')
await settle(treeEl, 6)
cursor = 0
pendingEffects = []
clickLabel(treeEl, '全选匹配结果')
const chosenBody = await settle(treeEl, 6)
const page = (content, theme) => `<!doctype html><html><head><meta charset="utf-8">
<style>
html,body{margin:0;padding:0}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",system-ui,sans-serif;
background:${theme === 'dark' ? '#101216' : '#f3f5f9'};color:${theme === 'dark' ? '#e8eaee' : '#1a1d21'}}
.frame{width:600px;margin:0 auto;padding:18px 20px 24px}
.panel{border-radius:14px;padding:16px;
background:${theme === 'dark' ? '#191c22' : '#ffffff'};
box-shadow:0 10px 30px rgba(0,0,0,${theme === 'dark' ? '0.45' : '0.10'})}
button{font-family:inherit}
input{font-family:inherit;color:inherit}
</style></head><body><div class="frame"><div class="panel">${content}</div></div></body></html>`
const outDir = join(here, '_preview')
mkdirSync(outDir, { recursive: true })
const lightPath = join(outDir, 'mcp-light.html')
const chosenPath = join(outDir, 'mcp-selected.html')
const darkPath = join(outDir, 'mcp-dark.html')
writeFileSync(lightPath, page(firstBody, 'light'), 'utf8')
writeFileSync(chosenPath, page(chosenBody, 'light'), 'utf8')
writeFileSync(darkPath, page(chosenBody, 'dark'), 'utf8')
const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
for (const [input, output, height] of [
[lightPath, join(outDir, 'mcp-light.png'), 2200],
[chosenPath, join(outDir, 'mcp-selected.png'), 2200],
[darkPath, join(outDir, 'mcp-dark.png'), 2200],
]) {
execFileSync(chrome, [
'--headless=new',
'--disable-gpu',
'--hide-scrollbars',
'--force-device-scale-factor=2',
`--window-size=640,${height}`,
`--screenshot=${output}`,
`file:///${input.replace(/\\/g, '/')}`,
], { stdio: 'ignore' })
console.log(`wrote ${output}`)
}

View File

@ -118,10 +118,6 @@ export interface SkillSummary {
files?: number
bytes?: number
script_changed?: boolean
/** Center creation time (ISO string; older servers may send epoch seconds). */
created_at?: string | number
/** Center last-change time — the timestamp the sync engine compares against local mtimes. */
updated_at?: string | number
[key: string]: unknown
}

View File

@ -1,10 +1,10 @@
/**
* dsh-cloud-memory → dsh-brain naming migration (v1.1 §15.1, RENAME-01).
*
* The 0.8.0 unification build ships AS `dsh-brain`: the package rename
* (the deploy step RENAME-01 deferred) has been performed, and the load
* paths read the `dsh-brain` names. What is implemented here is the
* *data* half, which is what RENAME-01 asserts:
* This build still ships as `dsh-cloud-memory`; renaming the live package and
* its profile link is a deploy step that needs a full DSH restart, so it is not
* performed from inside a running session. What is implemented here is the
* *data* half, which is what RENAME-01 actually asserts:
*
* - copy the legacy sidecars to the `dsh-brain` names when the target is
* missing, never deleting or modifying the legacy files;
@ -26,8 +26,6 @@ const PAIRS: [string, string][] = [
['cloud-memory.json', 'dsh-brain.json'],
['cloud-memory-skills.json', 'dsh-brain-skills.json'],
['cloud-memory-skill-groups.json', 'dsh-brain-skill-groups.json'],
['cloud-memory-workspaces.json', 'dsh-brain-workspaces.json'],
['.cloud-memory-plans.json', '.dsh-brain-plans.json'],
]
async function exists(path: string): Promise<boolean> {
@ -42,7 +40,7 @@ export interface BrainMigrationStatus {
files: { legacy: string; target: string; legacyExists: boolean; targetExists: boolean; needsMigration: boolean }[]
migrationNeeded: boolean
/** The package rename itself is a deploy step, not done in-session. */
packageRename: 'done'
packageRename: 'pending-deploy'
}
export async function brainStatus(): Promise<BrainMigrationStatus> {
@ -62,7 +60,7 @@ export async function brainStatus(): Promise<BrainMigrationStatus> {
legacyPackage: BRAIN.legacyPackage,
files,
migrationNeeded: files.some((file) => file.needsMigration),
packageRename: 'done',
packageRename: 'pending-deploy',
}
}

View File

@ -16,7 +16,7 @@ import { existsSync } from 'node:fs'
import { readFile, readdir, stat } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, resolve, sep } from 'node:path'
import { dshHome, migrateLegacyFile } from './store.ts'
import { dshHome } from './store.ts'
import { parseSkillFrontmatter } from './skill-sync.ts'
import { SkillAdmin } from './skill-admin.ts'
@ -74,9 +74,7 @@ interface Roots {
/** Manual workspace additions live in the plugin's own metadata file. */
export function manualWorkspacesPath(): string {
const target = join(dshHome(), 'dsh-brain-workspaces.json')
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-workspaces.json'))
return target
return join(dshHome(), 'cloud-memory-workspaces.json')
}
interface ManualFile {
@ -178,9 +176,7 @@ export class ClientRegistry {
if (workspace === undefined) throw new Error('unknown_workspace')
const skillsRoot = resolve(workspace.path, '.dsh', 'skills')
const holdingDir = join(dshHome(), 'skills-workspace-disabled', workspace.id)
const stateName = `${workspace.id.replace(/[^A-Za-z0-9_-]/g, '_')}.json`
const statePath = join(dshHome(), `dsh-brain-workspace-${stateName}`)
migrateLegacyFile(statePath, join(dshHome(), `cloud-memory-workspace-${stateName}`))
const statePath = join(dshHome(), `cloud-memory-workspace-${workspace.id.replace(/[^A-Za-z0-9_-]/g, '_')}.json`)
const admin = new SkillAdmin({
skillsRoot: () => skillsRoot,
holdingDir: () => holdingDir,

View File

@ -1,6 +1,6 @@
/**
* Settings model: the cordis row config supplies defaults, the user-editable
* sidecar (`$DSH_HOME/dsh-brain.json`) overrides them, and secrets live ONLY
* sidecar (`$DSH_HOME/cloud-memory.json`) overrides them, and secrets live ONLY
* in the sidecar. Nothing here ever reaches the conversation or a model context.
*/

View File

@ -4,7 +4,7 @@
* Responsibilities:
* 1. report one activity record per finished conversation round,
* 2. expose the memory tools to the agent,
* 3. serve the configuration page under `/dsh-brain` (legacy `/cloud-memory` routes stay as aliases).
* 3. serve the configuration page under `/cloud-memory`.
*
* Everything registers through `ctx.effect(...)` so a plugin reload tears down
* its routes, timer, listeners, and tools without leftovers.
@ -12,10 +12,10 @@
import { CloudClient } from './api.ts'
import type { CloudMemoryContext, SessionEventLike, SessionLike } from './context-types.ts'
import { Reporter } from './reporter.ts'
import { createLegacyRoutes, createRoutes } from './routes.ts'
import { createRoutes } from './routes.ts'
import { join } from 'node:path'
import { SettingsStore, dshHome } from './store.ts'
import { SkillSync , skillsStatePath } from './skill-sync.ts'
import { SkillSync } from './skill-sync.ts'
import { SkillAdmin, skillsHoldingDir } from './skill-admin.ts'
import { SkillGroupManager, detectSources } from './skill-groups.ts'
import { ClaudePluginMarketplaceProvider, MarketService } from './market.ts'
@ -24,13 +24,13 @@ import { ClientRegistry } from './clients.ts'
import { createMemoryTools, createSkillTools } from './tools.ts'
/** Package name; also the client bundle id. */
export const name = 'dsh-brain'
export const name = 'dsh-cloud-memory'
/** Services required before `apply` runs. */
export const inject = ['webServer']
/** Version reported by the status card. */
const VERSION = '0.9.10'
const VERSION = '0.7.0'
/** How often the skill directory is reconciled with the cloud center. */
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000
@ -40,7 +40,7 @@ const RETRY_INTERVAL_MS = 30_000
/** Register the plugin with the host. */
export function apply(ctx: CloudMemoryContext, config: unknown): void {
const logger = ctx.logger('dsh-brain')
const logger = ctx.logger('cloud-memory')
const store = new SettingsStore(config)
const settings = () => store.settings()
@ -74,7 +74,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
const skillAdmin = new SkillAdmin({
skillsRoot: () => skillSync.skillsRoot(),
holdingDir: () => skillsHoldingDir(),
syncStatePath: () => skillsStatePath(),
syncStatePath: () => join(dshHome(), 'cloud-memory-skills.json'),
syncRunning: () => skillSync.stats().running,
log: (message) => logger.info(message),
})
@ -115,7 +115,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
if (!effective.enabled) {
logger.info('disabled by settings')
} else if (store.activityToken() === '') {
logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`)
logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /cloud-memory`)
} else {
logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`)
}
@ -138,7 +138,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`)
}
}),
'dsh-brain: turn reporting',
'dsh-cloud-memory: turn reporting',
)
ctx.inject(['tools'], (toolsCtx) => {
@ -150,7 +150,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
settings: () => ({ enabled: settings().enabled, defaultK: settings().defaultK }),
}
for (const tool of [...createMemoryTools(toolDeps), ...createSkillTools(toolDeps)]) {
toolsCtx.effect(() => tools.register(tool), `dsh-brain: tool ${tool.name}`)
toolsCtx.effect(() => tools.register(tool), `dsh-cloud-memory: tool ${tool.name}`)
}
})
@ -159,9 +159,8 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
logger.warn('webServer service unavailable; the configuration page stays disabled')
} else {
const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients })
routes.push(...createLegacyRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients }))
for (const route of routes) {
ctx.effect(() => webServer.register(route), `dsh-brain: route ${route.path}`)
ctx.effect(() => webServer.register(route), `dsh-cloud-memory: route ${route.path}`)
}
}
@ -175,7 +174,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
}, RETRY_INTERVAL_MS)
timer.unref?.()
return () => clearInterval(timer)
}, 'dsh-brain: retry timer')
}, 'dsh-cloud-memory: retry timer')
ctx.effect(() => {
const run = () => {
@ -186,5 +185,5 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS)
timer.unref?.()
return () => { clearTimeout(first); clearInterval(timer) }
}, 'dsh-brain: skill sync timer')
}, 'dsh-cloud-memory: skill sync timer')
}

View File

@ -145,7 +145,7 @@ export class ClaudePluginMarketplaceProvider implements MarketProvider {
let response: Response
try {
response = await this.fetchImpl(url, {
headers: { accept: 'application/json, text/plain, */*', 'user-agent': 'dsh-brain-market' },
headers: { accept: 'application/json, text/plain, */*', 'user-agent': 'dsh-cloud-memory-market' },
signal: AbortSignal.timeout(this.timeoutMs()),
})
} catch (error) {

View File

@ -39,7 +39,7 @@ export const descriptor: MemoryProviderDescriptor = {
input: 'url',
required: false,
placeholder: 'https://mem.example.com/api/longmemory',
help: 'LongMemory base URL. Leave empty to reuse the dsh-brain settings (dsh-brain.json).',
help: 'LongMemory base URL. Leave empty to reuse the dsh-cloud-memory settings (cloud-memory.json).',
normalize: 'trim-trailing-slash',
},
{
@ -48,7 +48,7 @@ export const descriptor: MemoryProviderDescriptor = {
scope: 'service',
input: 'secret',
required: false,
help: 'Scoped memory token (memory:write). Leave empty to reuse the token already configured for dsh-brain.',
help: 'Scoped memory token (memory:write). Leave empty to reuse the token already configured for dsh-cloud-memory.',
},
{
key: 'projectId',

View File

@ -10,9 +10,9 @@
* Connection resolution, per call:
* 1. the Mnemon connection for the space (service fields configured on
* the Mnemon page, plus the space's own `projectId`),
* 2. this package's own settings sidecar (`$DSH_HOME/dsh-brain.json`)
* 2. this package's own settings sidecar (`$DSH_HOME/cloud-memory.json`)
* for any of endpoint/token the Mnemon side left empty — so a user
* who already configured dsh-brain configures nothing twice.
* who already configured dsh-cloud-memory configures nothing twice.
*
* A Memory Space maps to one LongMemory project; the empty project is the
* account-wide default scope.

View File

@ -1,12 +1,12 @@
/**
* Mnemon Memory Spaces Provider entry for LongMemory.
*
* This module is NOT loaded by the dsh-brain bundle itself. Mnemon's
* This module is NOT loaded by the dsh-cloud-memory bundle itself. Mnemon's
* Memory Spaces source mounts it as a child when the user adds it to the
* source's provider list:
*
* providers:
* - use: dsh-brain/mnemon-provider
* - use: dsh-cloud-memory/mnemon-provider
* instanceId: longmemory
*
* Registration is deliberately a user step: until then this file is inert
@ -23,14 +23,14 @@ import { LongMemoryProvider } from './driver.ts'
export { LongMemoryProvider, descriptor }
/** Keep in sync with the package version (asserted by the verify script). */
const PROVIDER_VERSION = '0.9.8'
const PROVIDER_VERSION = '0.7.0'
export const definition = defineMemorySpaceProviderDefinition({
manifest: {
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
kind: 'provider',
typeId: descriptor.id,
packageName: 'dsh-brain',
packageName: 'dsh-cloud-memory',
version: PROVIDER_VERSION,
label: descriptor.label,
icon: descriptor.icon,

View File

@ -3,11 +3,11 @@
*
* This profile runs with the native settings surface disabled
* (`ui-settings` is turned off in `cordis.patch.yml`), so the plugin ships its
* own HTML page at `/dsh-brain`. It is deliberately dependency-free: no
* own HTML page at `/cloud-memory`. It is deliberately dependency-free: no
* bundler assets, no CDN, no fonts — one file the host web server can emit.
*
* The page renders tokens as masked values only; the plaintext never leaves
* `$DSH_HOME/dsh-brain.json`.
* `$DSH_HOME/cloud-memory.json`.
*/
/** Escape a value for safe interpolation into HTML text/attributes. */
@ -29,193 +29,94 @@ export function renderConfigPage(options: { version: string; settingsPath: strin
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>DSH Brain · 云端记忆</title>
<title>云端记忆 · DSH 插件</title>
<style>
:root {
color-scheme: light dark;
--bg: #f4f5fa; --card: #ffffff; --ink: #191c22; --ink2: #5b6472; --ink3: #8a93a3;
--line: #e4e7f0; --field: #fbfbfe; --field-line: #d8dce8;
--brand: #6366f1; --brand2: #8b5cf6; --brand-ink: #4f46e5;
--shadow: 0 1px 2px rgba(23, 25, 60, .04), 0 8px 24px -12px rgba(23, 25, 60, .12);
--ok-bg: #e5f7ec; --ok: #177245; --bad-bg: #fdecec; --bad: #b3261e;
--warn-bg: #fff4d6; --warn: #8a5a00; --sk-bg: #edf0f6; --sk: #55606d;
--code-bg: #eef0f7; --track: #d5d9e6;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #101218; --card: #171a21; --ink: #e8eaf0; --ink2: #a3abb9; --ink3: #767f8f;
--line: #262b36; --field: #12151c; --field-line: #313947;
--brand-ink: #a5b4fc; --shadow: 0 1px 2px rgba(0,0,0,.4), 0 10px 28px -12px rgba(0,0,0,.5);
--ok-bg: #123324; --ok: #4ade80; --bad-bg: #3d1a17; --bad: #f28b82;
--warn-bg: #3a2f10; --warn: #fbbf24; --sk-bg: #232833; --sk: #9aa3af;
--code-bg: #22262f; --track: #39415a;
}
}
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
body {
margin: 0; padding: 40px 24px 56px;
font: 14px/1.65 -apple-system, "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
color: var(--ink);
background:
radial-gradient(720px 300px at 12% -60px, rgba(99,102,241,.13), transparent 70%),
radial-gradient(640px 280px at 88% -40px, rgba(139,92,246,.10), transparent 70%),
var(--bg);
background-attachment: fixed;
margin: 0;
padding: 32px 24px 64px;
font: 14px/1.6 -apple-system, "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
background: #f6f7f9;
color: #1c1f23;
}
.wrap { max-width: 1020px; margin: 0 auto; }
a { color: var(--brand-ink); text-decoration: none; }
a:hover { text-decoration: underline; }
/* ---------- masthead ---------- */
.masthead { display: flex; align-items: center; gap: 16px; margin-bottom: 8px; }
.logo {
width: 54px; height: 54px; border-radius: 16px; flex: none;
display: flex; align-items: center; justify-content: center; font-size: 28px;
background: linear-gradient(135deg, var(--brand), var(--brand2));
box-shadow: 0 8px 20px -6px rgba(99,102,241,.55);
@media (prefers-color-scheme: dark) {
body { background: #14161a; color: #e6e8eb; }
.card { background: #1c1f24 !important; border-color: #2b303a !important; }
input, select { background: #12141a !important; color: #e6e8eb !important; border-color: #333a45 !important; }
th { color: #9aa3af !important; }
tr + tr td { border-color: #262b33 !important; }
.muted { color: #8b949e !important; }
code { background: #22262d !important; }
}
.masthead h1 { font-size: 24px; margin: 0; letter-spacing: .2px; line-height: 1.25; }
.masthead h1 .thin { font-weight: 500; color: var(--ink2); }
.ver {
font-size: 11.5px; font-weight: 600; color: var(--brand-ink);
background: color-mix(in srgb, var(--brand) 12%, transparent);
padding: 2px 9px; border-radius: 999px; vertical-align: 3px; margin-left: 8px; white-space: nowrap;
}
.tagline { margin: 2px 0 0; color: var(--ink2); font-size: 13px; }
.mast-actions { margin-left: auto; flex: none; }
.btn-link {
display: inline-flex; align-items: center; gap: 7px;
padding: 9px 16px; border-radius: 999px; font-size: 13px; font-weight: 600;
color: #fff; background: linear-gradient(135deg, var(--brand), var(--brand2));
box-shadow: 0 6px 16px -6px rgba(99,102,241,.6);
}
.btn-link:hover { text-decoration: none; filter: brightness(1.06); }
.rule { height: 3px; border-radius: 3px; margin: 18px 0 22px;
background: linear-gradient(90deg, var(--brand), var(--brand2), transparent 75%); opacity: .55; }
/* ---------- cards ---------- */
.wrap { max-width: 980px; margin: 0 auto; }
h1 { font-size: 20px; margin: 0 0 4px; letter-spacing: .2px; }
h2 { font-size: 14px; margin: 0 0 14px; font-weight: 600; letter-spacing: .3px; }
.sub { margin: 0 0 24px; color: #5c6672; font-size: 13px; }
@media (prefers-color-scheme: dark) { .sub { color: #8b949e; } }
.card {
background: var(--card); border: 1px solid var(--line); border-radius: 16px;
padding: 22px 24px; margin-bottom: 16px; box-shadow: var(--shadow);
background: #fff; border: 1px solid #e3e6ea; border-radius: 12px;
padding: 20px 22px; margin-bottom: 18px;
}
.card-head { display: flex; align-items: center; gap: 11px; margin-bottom: 16px; }
.chip {
width: 32px; height: 32px; border-radius: 10px; flex: none; font-size: 16px;
display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--brand) 12%, transparent);
}
.card-head h2 { font-size: 15px; margin: 0; font-weight: 650; letter-spacing: .2px; }
.card-head .desc { margin-left: auto; font-size: 12px; color: var(--ink3); text-align: right; }
/* ---------- forms ---------- */
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px 20px; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 18px; }
@media (max-width: 720px) { .grid { grid-template-columns: 1fr; } }
label { display: block; font-size: 12.5px; font-weight: 600; color: var(--ink2); margin-bottom: 6px; }
label { display: block; font-size: 12px; font-weight: 600; color: #4a5361; margin-bottom: 6px; }
@media (prefers-color-scheme: dark) { label { color: #a7b0bb; } }
input[type=text], input[type=password], input[type=number] {
width: 100%; padding: 10px 12px; font: inherit; font-size: 13.5px;
border: 1px solid var(--field-line); border-radius: 10px; background: var(--field); color: var(--ink);
transition: border-color .15s ease, box-shadow .15s ease;
width: 100%; padding: 9px 11px; font: inherit; font-size: 13px;
border: 1px solid #d7dbe1; border-radius: 8px; background: #fdfdfe; color: inherit;
}
input:focus { outline: none; border-color: var(--brand); box-shadow: 0 0 0 3px color-mix(in srgb, var(--brand) 22%, transparent); }
.hint { font-size: 12px; color: var(--ink3); margin-top: 6px; }
.muted { color: var(--ink3); }
input:focus { outline: 2px solid #4b7bec33; border-color: #4b7bec; }
.hint { font-size: 12px; color: #6b7480; margin-top: 5px; }
.muted { color: #6b7480; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.tip { margin-top: 14px; font-size: 12.5px; color: var(--ink2); }
code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; background: var(--code-bg); padding: 1px 6px; border-radius: 5px; }
/* ---------- toggles ---------- */
.toggles { margin-top: 18px; border-top: 1px dashed var(--line); padding-top: 6px; }
.toggle { display: flex; align-items: center; gap: 12px; padding: 10px 2px; cursor: pointer; margin: 0; }
.toggle input { position: absolute; opacity: 0; width: 0; height: 0; }
.toggle .track {
width: 40px; height: 22px; border-radius: 999px; flex: none; position: relative;
background: var(--track); transition: background .18s ease;
}
.toggle .track::after {
content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%;
background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.3); transition: transform .18s ease;
}
.toggle input:checked + .track { background: linear-gradient(135deg, var(--brand), var(--brand2)); }
.toggle input:checked + .track::after { transform: translateX(18px); }
.toggle input:focus-visible + .track { box-shadow: 0 0 0 3px color-mix(in srgb, var(--brand) 30%, transparent); }
.toggle .ttitle { display: block; font-size: 13.5px; font-weight: 600; color: var(--ink); }
.toggle .tdesc { display: block; font-size: 12px; color: var(--ink3); font-weight: 400; }
.inline-field { display: flex; align-items: center; gap: 12px; padding: 8px 2px 2px; }
.inline-field label { margin: 0; font-size: 13.5px; font-weight: 600; color: var(--ink); }
.inline-field input { max-width: 150px; }
/* ---------- buttons ---------- */
button {
font: inherit; font-size: 13.5px; font-weight: 550; padding: 9px 18px; border-radius: 10px;
border: 1px solid var(--field-line); background: var(--card); color: var(--ink); cursor: pointer;
transition: all .15s ease;
font: inherit; font-size: 13px; padding: 9px 16px; border-radius: 8px;
border: 1px solid #d7dbe1; background: #fff; color: inherit; cursor: pointer;
transition: background .15s ease, border-color .15s ease;
}
button:hover { border-color: var(--brand); color: var(--brand-ink); transform: translateY(-1px); }
button.primary {
background: linear-gradient(135deg, var(--brand), var(--brand2)); border: none; color: #fff;
box-shadow: 0 6px 16px -6px rgba(99,102,241,.55); padding: 10px 20px;
}
button.primary:hover { color: #fff; filter: brightness(1.07); }
button:disabled { opacity: .55; cursor: default; transform: none; }
/* ---------- stats ---------- */
.stats { display: flex; flex-wrap: wrap; gap: 10px; }
.stat {
flex: 1 1 118px; border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px 10px;
background: linear-gradient(180deg, color-mix(in srgb, var(--brand) 4%, transparent), transparent 65%);
position: relative; overflow: hidden;
}
.stat::before { content: ""; position: absolute; top: 0; left: 0; right: 0; height: 3px;
background: linear-gradient(90deg, var(--brand), var(--brand2)); opacity: .35; }
.stat:nth-child(3)::before, .stat:nth-child(7)::before { background: linear-gradient(90deg, #f59e0b, #ef4444); }
.stat .k { font-size: 11.5px; letter-spacing: .5px; color: var(--ink3); font-weight: 600; }
.stat .v { font-size: 21px; font-weight: 700; margin-top: 1px; font-variant-numeric: tabular-nums; }
/* ---------- pills / table ---------- */
.pill { display: inline-block; padding: 1.5px 9px; border-radius: 999px; font-size: 11.5px; font-weight: 600; }
.ok { background: var(--ok-bg); color: var(--ok); }
.bad { background: var(--bad-bg); color: var(--bad); }
.warn { background: var(--warn-bg); color: var(--warn); }
.sk { background: var(--sk-bg); color: var(--sk); }
.table-wrap { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
button:hover { background: #f2f4f7; }
button.primary { background: #2f6fed; border-color: #2f6fed; color: #fff; }
button.primary:hover { background: #255fd4; }
button:disabled { opacity: .55; cursor: default; }
.stats { display: flex; flex-wrap: wrap; gap: 10px; margin: 6px 0 2px; }
.stat { flex: 1 1 120px; border: 1px solid #e6e9ee; border-radius: 9px; padding: 10px 12px; }
@media (prefers-color-scheme: dark) { .stat { border-color: #2b303a; } }
.stat .k { font-size: 11px; letter-spacing: .4px; color: #6b7480; text-transform: uppercase; }
.stat .v { font-size: 18px; font-weight: 600; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
th { text-align: left; font-size: 11px; letter-spacing: .6px; color: var(--ink3); font-weight: 600;
padding: 9px 12px; background: color-mix(in srgb, var(--brand) 5%, transparent); }
td { padding: 8px 12px; border-top: 1px solid var(--line); vertical-align: top; }
tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent); }
.foot { text-align: center; color: var(--ink3); font-size: 12px; margin-top: 26px; }
th { text-align: left; font-size: 11px; letter-spacing: .4px; text-transform: uppercase; color: #6b7480; padding: 6px 8px; }
td { padding: 7px 8px; border-top: 1px solid #eef1f4; vertical-align: top; }
code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; background: #f1f3f6; padding: 1px 5px; border-radius: 4px; }
.pill { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 600; }
.ok { background: #e6f6ec; color: #1c7c43; }
.bad { background: #fdeaea; color: #b3261e; }
.warn { background: #fff5e0; color: #92600a; }
.sk { background: #eef1f5; color: #55606d; }
.tip { margin-top: 14px; font-size: 12px; color: #6b7480; }
.toast {
position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%);
background: #1c1f23; color: #fff; padding: 11px 20px; border-radius: 999px;
background: #1c1f23; color: #fff; padding: 10px 18px; border-radius: 999px;
font-size: 13px; opacity: 0; pointer-events: none; transition: opacity .2s ease;
max-width: 80vw; text-align: center; box-shadow: 0 12px 32px rgba(0,0,0,.3); z-index: 10;
max-width: 80vw; text-align: center;
}
.toast.show { opacity: .97; }
.toast.show { opacity: .95; }
</style>
</head>
<body>
<div class="wrap">
<header class="masthead">
<div class="logo">🧠</div>
<div>
<h1>DSH Brain<span class="thin"> · 云端记忆</span><span class="ver">v${escapeHtml(options.version)}</span></h1>
<p class="tagline">每轮结束上报活动计数 · 提供 memory_search / memory_read / memory_add 工具</p>
</div>
<div class="mast-actions">
<a class="btn-link" href="/dsh-brain/skills">技能管理 →</a>
</div>
</header>
<div class="rule"></div>
<h1>云端记忆 · DSH 插件</h1>
<p class="sub">v${escapeHtml(options.version)} · 每轮结束上报活动计数 · 提供 memory_search / memory_read / memory_add 工具</p>
<p class="sub"><a href="/cloud-memory/skills">技能管理(列表 · 启停 · 安装)→</a></p>
<section class="card">
<div class="card-head"><span class="chip">📊</span><h2>当前状态</h2><span class="desc">每 15 秒自动刷新</span></div>
<h2>当前状态</h2>
<div class="stats" id="stats"></div>
<div class="tip" id="statDetail">加载中…</div>
</section>
<section class="card">
<div class="card-head"><span class="chip">🔌</span><h2>连接配置</h2></div>
<h2>连接配置</h2>
<div class="grid">
<div>
<label for="baseUrl">服务基址</label>
@ -236,26 +137,24 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
<input id="defaultK" type="number" min="1" max="100" />
</div>
</div>
<div class="toggles">
<label class="toggle" for="enabled">
<input id="enabled" type="checkbox" />
<span class="track"></span>
<span><span class="ttitle">启用插件</span><span class="tdesc">关闭后不上报、不提供工具</span></span>
<div class="row" style="margin-top:14px">
<label style="margin:0;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500">
<input id="enabled" type="checkbox" style="width:auto" /> 启用插件(关闭后不上报、不提供工具)
</label>
<label class="toggle" for="summaryEnabled">
<input id="summaryEnabled" type="checkbox" />
<span class="track"></span>
<span><span class="ttitle">轮次结束后自动生成待确认摘要</span><span class="tdesc">只进入待确认队列,确认后才写云端</span></span>
</div>
<div class="row" style="margin-top:10px">
<label style="margin:0;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500">
<input id="summaryEnabled" type="checkbox" style="width:auto" /> 轮次结束后自动生成待确认摘要(只进入待确认队列,确认后才写云端)
</label>
<div class="inline-field">
<label for="summaryMaxChars">单轮摘要字数上限</label>
<input id="summaryMaxChars" type="number" min="1000" max="16000" step="500" />
</div>
</div>
<div class="row" style="margin-top:10px;align-items:center;gap:10px">
<label for="summaryMaxChars" style="margin:0;font-size:13px;font-weight:500">单轮摘要字数上限</label>
<input id="summaryMaxChars" type="number" min="1000" max="16000" step="500" style="max-width:140px" />
</div>
</section>
<section class="card">
<div class="card-head"><span class="chip">🔑</span><h2>账号登录</h2><span class="desc">用账号一次性换取令牌,密码不保存</span></div>
<h2>账号登录</h2>
<div class="grid">
<div>
<label for="username">用户名</label>
@ -266,7 +165,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
<input id="password" type="password" spellcheck="false" autocomplete="current-password" placeholder="只用于本次换取令牌" />
</div>
</div>
<div class="row" style="margin-top:16px">
<div class="row" style="margin-top:14px">
<button class="primary" id="login">登录并获取令牌</button>
</div>
<div class="tip">
@ -277,7 +176,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
</section>
<section class="card">
<div class="card-head"><span class="chip">🎫</span><h2>访问令牌</h2><span class="desc">只存本机,页面只显示掩码</span></div>
<h2>访问令牌</h2>
<div class="grid">
<div>
<label for="activityToken">活动上报令牌(activity:write)</label>
@ -295,7 +194,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
<div class="hint" id="summaryTokenHint">用于 POST /activity/summary:只把已脱敏摘要送进待确认队列。</div>
</div>
</div>
<div class="row" style="margin-top:16px">
<div class="row" style="margin-top:14px">
<button class="primary" id="save">保存配置</button>
<button id="clearTokens">清除已存令牌</button>
</div>
@ -306,7 +205,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
</section>
<section class="card">
<div class="card-head"><span class="chip">🩺</span><h2>诊断</h2></div>
<h2>诊断</h2>
<div class="row">
<button id="test">测试连接</button>
<button id="flush">重试上报队列</button>
@ -316,18 +215,14 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
</section>
<section class="card">
<div class="card-head"><span class="chip">🕘</span><h2>最近上报</h2></div>
<div class="table-wrap">
<table>
<thead>
<tr><th>时间</th><th>状态</th><th>结果</th><th>HTTP</th><th>turn_id</th></tr>
</thead>
<tbody id="recent"><tr><td colspan="5" class="muted">暂无记录</td></tr></tbody>
</table>
</div>
<h2>最近上报</h2>
<table>
<thead>
<tr><th>时间</th><th>状态</th><th>结果</th><th>HTTP</th><th>turn_id</th></tr>
</thead>
<tbody id="recent"><tr><td colspan="5" class="muted">暂无记录</td></tr></tbody>
</table>
</section>
<p class="foot">DSH Brain · 云端记忆插件 — 配置只保存在这台机器上</p>
</div>
<div class="toast" id="toast"></div>
<script>
@ -427,7 +322,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
}
function load() {
return fetch('/dsh-brain/status', { headers: { accept: 'application/json' } })
return fetch('/cloud-memory/status', { headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) throw new Error((body && body.error) || 'status failed');
@ -452,7 +347,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
if (activity !== '') patch.activityToken = activity;
if (memory !== '') patch.memoryToken = memory;
if (summary !== '') patch.summaryToken = summary;
fetch('/dsh-brain/config', {
fetch('/cloud-memory/config', {
method: 'PUT',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify(patch)
@ -469,7 +364,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
function test() {
var node = el('testResult');
node.textContent = '测试中…';
fetch('/dsh-brain/test', { method: 'POST', headers: { accept: 'application/json' } })
fetch('/cloud-memory/test', { method: 'POST', headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) { node.textContent = '测试失败:' + ((body && body.error) || 'unknown'); return; }
@ -482,7 +377,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
}
function flush() {
fetch('/dsh-brain/flush', { method: 'POST', headers: { accept: 'application/json' } })
fetch('/cloud-memory/flush', { method: 'POST', headers: { accept: 'application/json' } })
.then(function (res) { return res.json(); })
.then(function (body) {
if (!body || body.ok !== true) { toast('重试失败:' + ((body && body.error) || 'unknown')); return; }
@ -493,7 +388,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
}
function clearTokens() {
fetch('/dsh-brain/config', {
fetch('/cloud-memory/config', {
method: 'PUT',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ clearActivityToken: true, clearMemoryToken: true })
@ -508,7 +403,7 @@ tbody tr:hover td { background: color-mix(in srgb, var(--brand) 4%, transparent)
var username = el('username').value.trim();
var password = el('password').value;
if (username === '' || password === '') { toast('请填写用户名和密码'); return; }
fetch('/dsh-brain/login', {
fetch('/cloud-memory/login', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ username: username, password: password })

View File

@ -31,7 +31,7 @@ export interface ReportRecord {
error?: string
}
/** Counters + recent history exposed by `GET /dsh-brain/status`. */
/** Counters + recent history exposed by `GET /cloud-memory/status`. */
export interface ReporterSnapshot {
attempted: number
recorded: number
@ -331,7 +331,7 @@ export class Reporter {
}
this.summaryFailed += 1
this.lastSummaryError = describeError(result.error)
this.options.log(`dsh-brain: turn summary failed: ${this.lastSummaryError}`)
this.options.log(`cloud-memory: turn summary failed: ${this.lastSummaryError}`)
}
private push(record: ReportRecord): void {
@ -381,7 +381,7 @@ export class Reporter {
this.queue.push(payload)
if (this.queue.length > 200) this.queue.shift()
}
this.options.log(`dsh-brain: turn report failed: ${this.lastError}`)
this.options.log(`cloud-memory: turn report failed: ${this.lastError}`)
}
/** Retry queued reports; safe to call at any time. */
@ -404,7 +404,7 @@ export class Reporter {
// an unbounded queue of metadata forever.
this.queue.shift()
this.retries.delete(payload.turn_id)
this.options.log(`dsh-brain: dropping turn report after ${attempt} attempts: ${this.lastError}`)
this.options.log(`cloud-memory: dropping turn report after ${attempt} attempts: ${this.lastError}`)
continue
}
this.retries.set(payload.turn_id, attempt)

View File

@ -1,16 +1,16 @@
/**
* HTTP surface served by the host web server.
*
* All routes live under `/dsh-brain`:
* - `GET /dsh-brain` configuration page (HTML)
* - `GET /dsh-brain/status` settings + reporter counters + capabilities
* - `GET /dsh-brain/capabilities` what this build can and cannot do
* - `PUT /dsh-brain/config` apply a settings patch
* - `POST /dsh-brain/login` password sign-in, mints the tokens
* - `POST /dsh-brain/test` read-only checks, per credential
* - `POST /dsh-brain/flush` retry the queued reports
* - `GET /dsh-brain/skills/api` skill inventory + pending plans
* - `POST /dsh-brain/skills/*` detail / toggle / install plan / commit / uninstall
* All routes live under `/cloud-memory`:
* - `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
@ -41,18 +41,18 @@ import { randomUUID } from 'node:crypto'
/** Route constants — kept in one place so the client half can reuse them. */
export const ROUTES = {
page: '/dsh-brain',
status: '/dsh-brain/status',
capabilities: '/dsh-brain/capabilities',
config: '/dsh-brain/config',
login: '/dsh-brain/login',
test: '/dsh-brain/test',
flush: '/dsh-brain/flush',
skills: '/dsh-brain/skills',
market: '/dsh-brain/market',
sync: '/dsh-brain/sync',
clients: '/dsh-brain/clients',
migrate: '/dsh-brain/migrate',
page: '/cloud-memory',
status: '/cloud-memory/status',
capabilities: '/cloud-memory/capabilities',
config: '/cloud-memory/config',
login: '/cloud-memory/login',
test: '/cloud-memory/test',
flush: '/cloud-memory/flush',
skills: '/cloud-memory/skills',
market: '/cloud-memory/market',
sync: '/cloud-memory/sync',
clients: '/cloud-memory/clients',
migrate: '/cloud-memory/migrate',
} as const
/** Largest request body we accept (a settings patch is tiny). */
@ -123,7 +123,7 @@ function capabilities(deps: RouteDeps): CapabilityReport {
skillUpdate: deps.updates !== undefined,
syncResolve: deps.sync !== undefined,
multiClient: deps.clients !== undefined,
brainMigration: 'ready',
brainMigration: 'pending-deploy',
// 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',
@ -292,7 +292,7 @@ function servePage(deps: RouteDeps, req: IncomingMessage, res: ServerResponse):
else res.end(html)
}
/** `GET /dsh-brain/status`. */
/** `GET /cloud-memory/status`. */
function serveStatus(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): void {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed')
@ -301,7 +301,7 @@ function serveStatus(deps: RouteDeps, req: IncomingMessage, res: ServerResponse)
json(res, 200, statusPayload(deps))
}
/** `GET /dsh-brain/capabilities`. */
/** `GET /cloud-memory/capabilities`. */
function serveCapabilities(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): void {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed')
@ -310,7 +310,7 @@ function serveCapabilities(deps: RouteDeps, req: IncomingMessage, res: ServerRes
json(res, 200, { ok: true, ...capabilities(deps) })
}
/** `PUT /dsh-brain/config`. */
/** `PUT /cloud-memory/config`. */
async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method !== 'PUT' && req.method !== 'POST') {
fail(res, 405, 'method-not-allowed')
@ -355,7 +355,7 @@ function checkState(error: { status: number; code: string }): CheckState {
return 'error'
}
/** `POST /dsh-brain/test` — read-only checks, one per credential. */
/** `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')
@ -430,7 +430,7 @@ async function serveTest(deps: RouteDeps, req: IncomingMessage, res: ServerRespo
})
}
/** `POST /dsh-brain/flush`. */
/** `POST /cloud-memory/flush`. */
async function serveFlush(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed')
@ -452,7 +452,7 @@ const TOKEN_LABELS = {
}
/**
* `POST /dsh-brain/login` — sign in with the cloud account and exchange it
* `POST /cloud-memory/login` — sign in with the cloud account and exchange it
* for the scoped tokens.
*
* The password is used once, in memory, and never written anywhere: the flow is
@ -589,15 +589,15 @@ function useUninstallToken(folder: string, token: unknown): boolean {
/**
* The skill management surface, one prefix route:
* `GET /dsh-brain/skills` the management page
* `GET /dsh-brain/skills/api` inventory JSON (skills + plans)
* `POST /dsh-brain/skills/detail` { folder } — one skill with SKILL.md
* `POST /dsh-brain/skills/toggle` { folder, enabled }
* `POST /dsh-brain/skills/install/plan` { url } — stage the repository
* `POST /dsh-brain/skills/install/commit` { planId, folders }
* `POST /dsh-brain/skills/install/cancel` { planId }
* `POST /dsh-brain/skills/uninstall/plan` { folder } — impact preview
* `POST /dsh-brain/skills/remove` { folder, token, confirmed: true }
* `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> {
const admin = deps.admin
@ -679,7 +679,6 @@ async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerRes
// base URL; they are grouped here because they never touch a skill folder
// directly (except the DSH park/unpark the group manager delegates).
const groupActions: Record<string, Handler> = {
'/import': async (body) => ({ ...(await requireGroups(deps).importSkill(body.sourceId, body.folder)) }),
'/groups/create': async (body) => ({ ...(await requireGroups(deps).createGroup(body.sourceId, body.name)) }),
'/groups/rename': async (body) => ({ ...(await requireGroups(deps).renameGroup(body.sourceId, body.groupId, body.name)) }),
'/groups/delete': async (body) => ({ ...(await requireGroups(deps).deleteGroup(body.sourceId, body.groupId)) }),
@ -723,8 +722,6 @@ function groupStatus(code: string): number {
case 'unknown_source': return 404
case 'invalid_name':
case 'duplicate':
case 'import_from_self':
case 'invalid_skill':
case 'too_many': return 400
case 'unavailable': return 503
default: return 500
@ -752,12 +749,12 @@ function marketStatus(code: string): number {
/**
* Market surface, one prefix route:
* `GET /dsh-brain/market/providers` configured sources
* `GET /dsh-brain/market/search` ?provider=&q=&cursor=
* `POST /dsh-brain/market/detail` { provider, id }
* `POST /dsh-brain/market/plan` { provider, id } — pin commit + stage a plan
* `POST /dsh-brain/market/commit` { planId, folders }
* `POST /dsh-brain/market/cancel` { planId }
* `GET /cloud-memory/market/providers` configured sources
* `GET /cloud-memory/market/search` ?provider=&q=&cursor=
* `POST /cloud-memory/market/detail` { provider, id }
* `POST /cloud-memory/market/plan` { provider, id } — pin commit + stage a plan
* `POST /cloud-memory/market/commit` { planId, folders }
* `POST /cloud-memory/market/cancel` { planId }
*/
async function serveMarket(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
const market = deps.market
@ -835,10 +832,9 @@ async function serveMarket(deps: RouteDeps, req: IncomingMessage, res: ServerRes
/**
* Sync surface:
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
* `POST /dsh-brain/sync/run` trigger one pass now
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud } for every conflict
* `GET /cloud-memory/sync/status` latest stats + both sides of each conflict
* `POST /cloud-memory/sync/run` trigger one pass now
* `POST /cloud-memory/sync/resolve` { name, action: keep_local | take_cloud | manual }
*/
async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
const sync = deps.sync
@ -868,14 +864,6 @@ async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerRespo
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() })
return
}
if (suffix === '/resolve-all') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
const result = await sync.resolveConflicts(body.action)
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() })
return
}
fail(res, 404, 'unknown-sync-route')
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
@ -1006,11 +994,6 @@ async function serveMigrate(_deps: RouteDeps, req: IncomingMessage, res: ServerR
}
/** Build the exact-route table registered with the host web server. */
/** Pre-rename aliases (0.8.0): the same handlers under the old `/cloud-memory` prefix. */
export function createLegacyRoutes(deps: RouteDeps): CloudMemoryWebRoute[] {
return createRoutes(deps).map((route) => ({ ...route, path: route.path.replace('/dsh-brain', '/cloud-memory') }))
}
export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] {
return [
{

View File

@ -31,7 +31,7 @@ import { createHash, randomUUID } from 'node:crypto'
import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
import { parseSkillFrontmatter } from './skill-sync.ts'
import { dshHome, migrateLegacyFile } from './store.ts'
import { dshHome } from './store.ts'
/** The parking area for disabled skills. */
export function skillsHoldingDir(): string {
@ -40,20 +40,12 @@ export function skillsHoldingDir(): string {
/** Isolated scratch space for staged installs; never inside the skills root. */
export function skillsStagingDir(): string {
return join(dshHome(), '.dsh-brain-staging')
return join(dshHome(), '.cloud-memory-staging')
}
/** Persisted plan records (metadata only: ids, counts, timestamps). */
/** Plans sidecar path, carrying the pre-rename file over on first use. */
export function plansPath(): string {
const target = join(dshHome(), '.dsh-brain-plans.json')
migrateLegacyFile(target, join(dshHome(), '.cloud-memory-plans.json'))
return target
}
function skillPlansPath(): string {
return plansPath()
export function skillPlansPath(): string {
return join(dshHome(), '.cloud-memory-plans.json')
}
/** A management failure with a stable machine-readable code. */
@ -257,9 +249,9 @@ export interface SkillAdminDeps {
syncStatePath: () => string
syncRunning: () => boolean
log: (message: string) => void
/** Where plan metadata is persisted; defaults to `$DSH_HOME/.dsh-brain-plans.json`. */
/** Where plan metadata is persisted; defaults to `$DSH_HOME/.cloud-memory-plans.json`. */
plansPath?: () => string
/** Where staged clones live; defaults to `$DSH_HOME/.dsh-brain-staging`. */
/** Where staged clones live; defaults to `$DSH_HOME/.cloud-memory-staging`. */
stagingRoot?: () => string
}
@ -343,7 +335,7 @@ export class SkillAdmin {
...(installedAt === undefined ? {} : { installedAt }),
skillSha256: createHash('sha256').update(markdown).digest('hex'),
location: enabled ? 'root' : 'holding',
ownerManager: 'dsh-brain',
ownerManager: 'dsh-cloud-memory',
writable: true,
...(source === undefined
? {}
@ -729,35 +721,6 @@ export class SkillAdmin {
return { installed, skipped, remaining }
}
/**
* Import one skill folder from another tool's skills directory (the
* "从其他软件导入" action). The caller (the group manager) has already
* resolved and vetted the source directory; this side owns the target:
* the name is validated, an existing skill — enabled or parked — is
* never overwritten, and the copy drops `.git` and symlinks exactly
* like a git install does.
*/
async importFolder(fromDir: string, folderInput: unknown): Promise<{ folder: string }> {
this.guardSync()
const folder = checkFolder(folderInput)
const existing = await this.locate(folder)
if (existing !== undefined) {
fail('already_exists', existing.area === 'holding'
? `DSH 里已有一个停用中的同名技能(${folder}),先处理它再导入。`
: `DSH 里已有同名技能(${folder}),不重复导入。`)
}
const skillsRoot = resolve(this.deps.skillsRoot())
await mkdir(skillsRoot, { recursive: true })
const target = resolve(skillsRoot, folder)
if (!target.startsWith(`${skillsRoot}${sep}`)) fail('path_escape', '导入目标越出技能目录。')
await cp(fromDir, target, {
recursive: true,
filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath),
})
this.deps.log(`skill imported from another tool: ${folder}`)
return { folder }
}
/** Throw away a staged plan and its clone. */
async cancelInstall(planInput: { planId?: unknown }): Promise<{ cancelled: string }> {
const planId = typeof planInput.planId === 'string' ? planInput.planId : ''
@ -771,7 +734,7 @@ export class SkillAdmin {
}
/**
* Legacy one-shot install, kept for the standalone `/dsh-brain/skills`
* 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.

View File

@ -18,11 +18,11 @@
*/
import { execFile } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs'
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
import { readdir, readFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, resolve, sep } from 'node:path'
import { dshHome, migrateLegacyFile } from './store.ts'
import { join, resolve } from 'node:path'
import { dshHome } from './store.ts'
import type { SkillAdmin, SkillEntry } from './skill-admin.ts'
/** One directory the tree can show. */
@ -92,9 +92,7 @@ const MAX_GROUPS_PER_SOURCE = 40
/** Sidecar path. */
export function skillGroupsPath(): string {
const target = join(dshHome(), 'dsh-brain-skill-groups.json')
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-skill-groups.json'))
return target
return join(dshHome(), 'cloud-memory-skill-groups.json')
}
/**
@ -363,49 +361,6 @@ export class SkillGroupManager {
}
/** Create one category inside a source. */
/**
* Import one skill from another tool's source into the DSH skills root
* (the card's 「从其他软件导入」). The source directory itself is never
* modified: the source side is vetted here (real directory, no symlink,
* stays inside its own root, carries a real SKILL.md) and the copy is
* delegated to the admin, which owns the target-side rules.
*/
async importSkill(sourceInput: unknown, folderInput: unknown): Promise<{ folder: string }> {
const source = this.source(sourceInput)
if (source.writable) {
throw new SkillGroupError('import_from_self', 'DSH 来源就是导入目标,不需要导入。')
}
const folder = typeof folderInput === 'string' ? folderInput : ''
if (folder === '' || folder.length > 128 || folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0')) {
throw new SkillGroupError('invalid_name', `技能目录名无效:${String(folderInput)}`)
}
const dir = join(source.root, folder)
let stat
try {
stat = lstatSync(dir)
} catch {
throw new SkillGroupError('not_found', `来源里没有这个技能:${folder}`)
}
if (!stat.isDirectory() || stat.isSymbolicLink()) {
throw new SkillGroupError('invalid_skill', `来源技能不是普通目录:${folder}`)
}
const rootReal = realpathSync(source.root)
const dirReal = realpathSync(dir)
if (!dirReal.startsWith(`${rootReal}${sep}`)) {
throw new SkillGroupError('invalid_skill', `来源技能越出来源目录:${folder}`)
}
let marker
try {
marker = lstatSync(join(dir, 'SKILL.md'))
} catch {
throw new SkillGroupError('invalid_skill', `来源技能缺少 SKILL.md:${folder}`)
}
if (!marker.isFile() || marker.isSymbolicLink()) {
throw new SkillGroupError('invalid_skill', `来源技能的 SKILL.md 不是普通文件:${folder}`)
}
return this.deps.admin.importFolder(dirReal, folder)
}
async createGroup(sourceInput: unknown, nameInput: unknown): Promise<{ groupId: string; name: string }> {
const source = this.source(sourceInput)
const name = cleanGroupName(nameInput)

View File

@ -1,8 +1,8 @@
/**
* The local skill management page (`GET /dsh-brain/skills`).
* The local skill management page (`GET /cloud-memory/skills`).
*
* A thin shell: the browser fetches the JSON inventory from
* `/dsh-brain/skills/api` and renders it; every action is a small
* `/cloud-memory/skills/api` and renders it; every action is a small
* JSON POST back to the same prefix. All skill data is inserted with
* textContent, never as raw HTML.
*/
@ -43,7 +43,7 @@ export function renderSkillsPage(options: { version: string }): string {
<body>
<div class="wrap">
<h1>技能管理</h1>
<p class="sub">v${options.version} · 本机技能的列表、启停、安装;删除是真删、不可恢复(云端副本不受影响)。云端同步仍在后台自动进行。<a href="/dsh-brain">← 返回云端记忆设置</a></p>
<p class="sub">v${options.version} · 本机技能的列表、启停、安装;删除是真删、不可恢复(云端副本不受影响)。云端同步仍在后台自动进行。<a href="/cloud-memory">← 返回云端记忆设置</a></p>
<section class="card">
<h2>从 git 仓库安装</h2>
@ -76,7 +76,7 @@ export function renderSkillsPage(options: { version: string }): string {
return btn;
}
async function post(path, body) {
const response = await fetch('/dsh-brain/skills' + path, {
const response = await fetch('/cloud-memory/skills' + path, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
@ -97,7 +97,7 @@ export function renderSkillsPage(options: { version: string }): string {
}
}
async function load() {
const response = await fetch('/dsh-brain/skills/api');
const response = await fetch('/cloud-memory/skills/api');
const data = await response.json();
const skillsBox = $('skills');
skillsBox.textContent = '';

View File

@ -15,14 +15,12 @@
* revisions, guarded by the center's `expected_revision` check.
*
* Safety rules (deliberate, in order):
* 1. A cloud-delivered skill is never re-uploaded unless its local copy is
* newer than the center's `updated_at`; before any cloud overwrite the
* local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
* 1. A cloud-delivered skill is never re-uploaded. If its local files no
* longer match the delivery manifest, the skill is flagged as a
* conflict and left completely alone.
* 2. A local deletion never deletes the cloud copy.
* 3. A same-name skill is never hijacked silently: byte-identical copies are
* adopted in place, otherwise the newer side (local file mtime vs center
* `updated_at`) wins; only equal or missing timestamps are reported as a
* conflict for a human to resolve.
* 3. A name that already exists on the other side is never hijacked;
* it is reported as a conflict for a human to resolve.
* 4. Bundles whose scripts changed on the cloud side are not installed
* until the change is acknowledged in the dashboard, mirroring the
* center's own review flag.
@ -36,7 +34,7 @@ import { mkdir, cp, readFile, readdir, rename, rm, stat, writeFile } from 'node:
import { dirname, join, resolve } from 'node:path'
import type { CloudClient, SkillBundle, SkillSummary, SkillUploadFile } from './api.ts'
import { describeError } from './api.ts'
import { dshHome, migrateLegacyFile } from './store.ts'
import { dshHome } from './store.ts'
/** Cloud skill names: lowercase kebab, at most 64 characters. */
export const CLOUD_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/
@ -67,23 +65,6 @@ export function linkedSkillManifest(files: readonly { path: string; sha256: stri
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'))
}
/** Epoch milliseconds from a center timestamp (ISO string or epoch seconds/ms). */
function timestampMs(value: unknown): number | undefined {
if (typeof value === 'number' && Number.isFinite(value)) return value < 1e12 ? value * 1000 : value
if (typeof value === 'string' && value !== '') {
const parsed = Date.parse(value)
return Number.isFinite(parsed) ? parsed : undefined
}
return undefined
}
/** Newest local file mtime in one skill folder (0 when the folder has no files). */
function newestMtime(files: readonly { mtimeMs: number }[]): number {
let newest = 0
for (const file of files) if (file.mtimeMs > newest) newest = file.mtimeMs
return newest
}
/** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel: string): boolean {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) return false
@ -144,14 +125,7 @@ interface UploadRecord {
syncedAt: string
}
/** Sidecar state: `$DSH_HOME/dsh-brain-skills.json` (legacy `cloud-memory-skills.json` migrates on first use). */
/** Absolute sidecar path, carrying the pre-rename file over on first use. */
export function skillsStatePath(): string {
const target = join(dshHome(), 'dsh-brain-skills.json')
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-skills.json'))
return target
}
/** Sidecar state: `$DSH_HOME/cloud-memory-skills.json`. */
interface SyncState {
version: 1
uploaded: Record<string, UploadRecord>
@ -169,8 +143,6 @@ interface SyncState {
interface LocalFile {
rel: string
buffer: Buffer
/** Last-modified time; the automatic newer-side winner is chosen from these. */
mtimeMs: number
}
/** Dependencies of one sync engine instance. */
@ -194,14 +166,6 @@ interface DeliveryManifest {
files?: { path: string; sha256: string }[]
}
/**
* Result of an automatic two-sided resolution:
* - resolved: the newer side won and the state was updated;
* - conflict: a specific conflict was recorded (e.g. script review);
* - unresolved: timestamps missing/equal — the caller records a conflict.
*/
type AutoResolution = 'resolved' | 'conflict' | 'unresolved'
export class SkillSync {
private running = false
private current: SkillSyncStats = {
@ -227,28 +191,7 @@ export class SkillSync {
}
private statePath(): string {
return skillsStatePath()
}
/**
* Record a cloud-delivered skill. Upload provenance is cleared in the same
* transition: a skill has exactly one source of truth. Keeping both marks
* makes the DOWN pass skip the name (uploaded) while the UP pass skips its
* local folder (delivery manifest), so neither side ever syncs again.
*/
private markDelivered(state: SyncState, name: string, manifest: string): void {
state.delivered[name] = { manifest }
delete state.uploaded[name]
}
/**
* Record a locally-originated upload. The delivery marker is cleared in the
* same transition, so the next local edit is uploaded again instead of being
* skipped as cloud-origin.
*/
private markUploaded(state: SyncState, name: string, record: UploadRecord): void {
state.uploaded[name] = record
delete state.delivered[name]
return join(dshHome(), 'cloud-memory-skills.json')
}
private async loadState(): Promise<SyncState> {
@ -291,10 +234,7 @@ export class SkillSync {
if (entry.isDirectory()) {
await walk(rel)
} else if (entry.isFile()) {
const absolute = join(dir, rel)
const buffer = await readFile(absolute)
const info = await stat(absolute)
out.push({ rel, buffer, mtimeMs: info.mtimeMs })
out.push({ rel, buffer: await readFile(join(dir, rel)) })
}
}
}
@ -359,175 +299,6 @@ export class SkillSync {
return undefined
}
/** Center's last-change time for one listed skill (ISO string or epoch). */
private cloudUpdatedAt(item: SkillSummary): number | undefined {
return timestampMs(item.updated_at) ?? timestampMs(item.created_at)
}
/** Manifest over every local file, including files the center would reject. */
private localManifest(files: readonly LocalFile[]): string {
return linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })))
}
/** Copy a local skill aside before an automatic cloud overwrite. */
private async backupLocal(dir: string, name: string): Promise<string> {
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
const backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp)
await mkdir(join(backup, '..'), { recursive: true })
await cp(dir, backup, { recursive: true, filter: (path) => !path.split(/[\\/]/).includes('.git') })
return backup
}
/**
* Local and cloud already carry the same bytes: record the delivery marker
* without a transfer, so the next pass treats the folder as cloud-origin and
* the user is not asked to pick between two identical copies.
*/
private async adoptIdenticalDelivery(home: string, item: SkillSummary, files: readonly LocalFile[]): Promise<void> {
const delivery: DeliveryManifest & { synced_at: string } = {
name: item.name,
...(item.revision === undefined ? {} : { revision: item.revision }),
...(item.manifest_sha256 === undefined ? {} : { manifest_sha256: item.manifest_sha256 }),
files: files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })),
synced_at: new Date().toISOString(),
}
await writeFile(join(home, '.manifest.json'), JSON.stringify(delivery, null, 2))
}
/** Fetch, verify and install the cloud copy, backing the local one up first. */
private async autoTakeCloud(
item: SkillSummary,
home: string,
installRoot: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
if (item.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required')
return 'conflict'
}
const bundle = await client.skillBundle(item.name)
if (!bundle.ok) {
this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`)
return 'conflict'
}
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
this.conflict(stats, item.name, 'manifest_mismatch')
return 'conflict'
}
if (bundle.data.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required')
return 'conflict'
}
await this.backupLocal(home, item.name)
await this.install(item, bundle.data, installRoot)
this.markDelivered(state, item.name, bundle.data.manifest_sha256)
delete state.removed[item.name]
stats.updated.push(item.name)
return 'resolved'
}
/** Upload the locally-newer copy as the next cloud revision. */
private async autoUploadLocal(
skill: { name: string; description: string; files: LocalFile[]; manifest: string; hasScripts: boolean },
folder: string,
dir: string,
cloud: SkillSummary,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files: this.toUploadFiles(skill.files),
expected_revision: cloud.revision ?? 0,
operation_id: `dsh-skill-${randomUUID()}`,
})
if (!updated.ok) {
const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`
this.conflict(stats, skill.name, reason)
return 'conflict'
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1
await rm(join(dir, '.manifest.json'), { force: true })
this.markUploaded(state, skill.name, {
folder,
revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
delete state.removed[skill.name]
stats.updated.push(skill.name)
return 'resolved'
}
/**
* Same-name skill on both sides without a delivery record. Identical bytes
* are adopted silently; different bytes go to whichever side is newer;
* equal/missing timestamps stay unresolved for a human decision.
*/
private async autoResolveCollision(
item: SkillSummary,
home: string,
installRoot: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
const localFiles = await this.readSkillFiles(home).catch(() => [])
if (!localFiles.some((file) => file.rel === 'SKILL.md')) return 'unresolved'
if (item.manifest_sha256 !== undefined && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles)
this.markDelivered(state, item.name, item.manifest_sha256)
stats.skipped += 1
return 'resolved'
}
const cloudAt = this.cloudUpdatedAt(item)
const localAt = newestMtime(localFiles)
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt) return 'unresolved'
if (cloudAt > localAt) return this.autoTakeCloud(item, home, installRoot, state, stats, client)
const skill = await this.readLocalSkill(home, item.name)
if (skill === undefined) return 'unresolved'
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill)
return 'conflict'
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client)
}
/**
* Cloud-delivered skill edited locally. Identical bytes refresh the marker;
* otherwise the newer side wins (cloud overwrite is backed up first).
*/
private async autoResolveLocalDrift(
item: SkillSummary,
home: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
installRoot: string,
): Promise<AutoResolution> {
const localFiles = await this.readSkillFiles(home).catch(() => [])
if (item.manifest_sha256 !== undefined && localFiles.length > 0 && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles)
this.markDelivered(state, item.name, item.manifest_sha256)
stats.skipped += 1
return 'resolved'
}
const cloudAt = this.cloudUpdatedAt(item)
const localAt = newestMtime(localFiles)
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt) return 'unresolved'
if (cloudAt > localAt) return this.autoTakeCloud(item, home, installRoot, state, stats, client)
const skill = await this.readLocalSkill(home, item.name)
if (skill === undefined) return 'unresolved'
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill)
return 'conflict'
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client)
}
/** One full pass; never throws — outcomes land in the stats. */
async syncOnce(): Promise<SkillSyncStats> {
if (this.running) return this.current
@ -571,26 +342,6 @@ export class SkillSync {
const state = await this.loadState()
let stateDirty = false
// Self-heal sidecars written before source provenance became exclusive:
// a folder carrying a delivery manifest is cloud-delivered, even if an old
// `uploaded` record survived. Clearing the stale upload marker lets the
// DOWN pass judge local integrity (and surface a conflict) instead of
// skipping both directions forever.
for (const name of Object.keys(state.uploaded)) {
let delivery = undefined
for (const area of [root, this.holdingRoot()]) {
const dir = join(area, name)
if (!(await isDirectory(dir))) continue
delivery = await this.readDelivery(dir)
if (delivery !== undefined) break
}
if (delivery !== undefined) {
this.markDelivered(state, name, delivery.manifest_sha256 ?? '')
stateDirty = true
}
}
if (stateDirty) await this.saveState(state)
// ---- DOWN: cloud center -> local directory -------------------------
for (const item of items) {
if (item.enabled === false) { stats.skipped += 1; continue }
@ -621,17 +372,12 @@ export class SkillSync {
if (exists && delivery !== undefined) {
// Delivered before: local integrity is judged before any download.
if (!(await this.deliveredIntact(home, delivery))) {
const auto = await this.autoResolveLocalDrift(item, home, state, stats, client, parked ? this.holdingRoot() : root)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
this.conflict(stats, item.name, 'locally_modified')
continue
}
if (delivery.manifest_sha256 === item.manifest_sha256) {
if (state.delivered[item.name]?.manifest !== item.manifest_sha256) {
this.markDelivered(state, item.name, item.manifest_sha256 ?? '')
state.delivered[item.name] = { manifest: item.manifest_sha256 ?? '' }
stateDirty = true
}
stats.skipped += 1
@ -640,14 +386,6 @@ export class SkillSync {
// Intact but the cloud moved on: fall through and install the update.
}
if (exists && delivery === undefined) {
// Same name on both sides with no delivery proof. Identical bytes are
// adopted; otherwise the newer side wins by timestamp. Only an equal
// or missing timestamp becomes a human conflict.
const auto = await this.autoResolveCollision(item, home, parked ? this.holdingRoot() : root, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
this.conflict(stats, item.name, 'name_collision')
continue
}
@ -670,16 +408,12 @@ export class SkillSync {
continue
}
await this.install(item, bundle.data, parked ? this.holdingRoot() : root)
this.markDelivered(state, item.name, bundle.data.manifest_sha256)
state.delivered[item.name] = { manifest: bundle.data.manifest_sha256 }
stateDirty = true
;(exists ? stats.updated : stats.downloaded).push(item.name)
}
// ---- UP: local originals -> cloud center ---------------------------
// The DOWN pass already had the chance to resolve a same-name folder;
// don't repeat the same skill with a second reason (the panel used to show
// one card per reason for the same name).
const knownConflicts = new Set(stats.conflicts.map((entry) => entry.name))
const folders = await readdir(root, { withFileTypes: true }).catch(() => [])
const seenFolders = new Set<string>()
for (const entry of folders) {
@ -690,35 +424,12 @@ export class SkillSync {
const skill = await this.readLocalSkill(dir, entry.name)
if (skill === undefined) continue
if (typeof skill === 'string') {
if (!knownConflicts.has(entry.name)) this.conflict(stats, entry.name, skill)
this.conflict(stats, entry.name, skill)
continue
}
const record = state.uploaded[skill.name]
const cloud = cloudByName.get(skill.name)
if (cloud !== undefined && record === undefined) {
if (knownConflicts.has(skill.name)) continue
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
// Same bytes already in the center: adopt the cloud identity without
// an upload, so the next pass compares revisions instead of names.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
stateDirty = true
stats.skipped += 1
continue
}
const cloudAt = this.cloudUpdatedAt(cloud)
const localAt = newestMtime(skill.files)
if (cloudAt !== undefined && localAt > 0 && localAt > cloudAt) {
const auto = await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
}
this.conflict(stats, skill.name, 'name_collision')
continue
}
@ -743,42 +454,17 @@ export class SkillSync {
this.conflict(stats, skill.name, `upload_failed: ${describeError(created.error)}`)
continue
}
this.markUploaded(state, skill.name, {
state.uploaded[skill.name] = {
folder: entry.name,
revision: created.data.skill?.revision ?? created.data.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
}
stateDirty = true
stats.uploaded.push(skill.name)
} else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
// The center moved on since the last upload. Identical bytes just
// re-pin the revision; otherwise the newer side wins and only an
// equal/missing timestamp stays a conflict.
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
stateDirty = true
stats.skipped += 1
continue
}
const cloudAt = this.cloudUpdatedAt(cloud)
const localAt = newestMtime(skill.files)
if (cloudAt !== undefined && localAt > 0 && cloudAt !== localAt) {
const auto = cloudAt > localAt
? await this.autoTakeCloud(cloud, dir, root, state, stats, client)
: await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
}
if (!knownConflicts.has(skill.name)) this.conflict(stats, skill.name, 'cloud_newer')
this.conflict(stats, skill.name, 'cloud_newer')
continue
}
const updated = await client.updateSkill(skill.name, {
@ -792,12 +478,12 @@ export class SkillSync {
this.conflict(stats, skill.name, reason)
continue
}
this.markUploaded(state, skill.name, {
state.uploaded[skill.name] = {
folder: entry.name,
revision: updated.data.skill?.revision ?? updated.data.revision ?? record.revision + 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
}
stateDirty = true
stats.updated.push(skill.name)
}
@ -892,29 +578,6 @@ export class SkillSync {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) }
}
/**
* Resolve every current conflict with one action (`keep_local` or
* `take_cloud`). Partial failures are collected instead of aborting the
* whole batch, so the UI can show "N done, M failed" in one shot.
*/
async resolveConflicts(actionInput: unknown): Promise<SyncResolveBatchResult> {
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : ''
if (action === '') throw new Error('invalid_action')
if (this.running) throw new Error('sync_running')
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))]
const resolved: string[] = []
const failed: { name: string; error: string }[] = []
for (const name of names) {
try {
await this.resolveConflict(name, action)
resolved.push(name)
} catch (error) {
failed.push({ name, error: error instanceof Error ? error.message : String(error) })
}
}
return { action, resolved, failed }
}
/**
* Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything.
@ -972,7 +635,7 @@ export class SkillSync {
},
canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined,
note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。',
})
}
return out
@ -1025,10 +688,7 @@ export class SkillSync {
})
if (!created.ok) throw new Error(`upload_failed: ${describeError(created.error)}`)
const revision = created.data.skill?.revision ?? created.data.revision ?? 1
// The local copy is now the upload source of truth: drop any stale
// cloud-delivery marker before committing the success state.
await rm(join(dir, '.manifest.json'), { force: true })
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() })
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() }
delete state.removed[name]
await this.saveState(state)
this.dropConflict(name)
@ -1045,8 +705,7 @@ export class SkillSync {
throw new Error(`upload_failed: ${describeError(updated.error)}`)
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1
await rm(join(dir, '.manifest.json'), { force: true })
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() })
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() }
delete state.removed[name]
await this.saveState(state)
this.dropConflict(name)
@ -1061,12 +720,12 @@ export class SkillSync {
let backup = ''
if (dir !== '') {
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp)
backup = join(dshHome(), '.cloud-memory-backups', 'sync', name, stamp)
await mkdir(join(backup, '..'), { recursive: true })
await cp(dir, backup, { recursive: true, filter: (p) => !p.split(/[\\/]/).includes('.git') })
}
await this.install(cloud, bundle.data, parked ? this.holdingRoot() : root)
this.markDelivered(state, name, bundle.data.manifest_sha256)
state.delivered[name] = { manifest: bundle.data.manifest_sha256 }
delete state.removed[name]
await this.saveState(state)
this.dropConflict(name)
@ -1101,10 +760,3 @@ export interface SyncResolveResult {
backup?: string
note: string
}
/** Outcome of resolving every current conflict with one action. */
export interface SyncResolveBatchResult {
action: 'keep_local' | 'take_cloud'
resolved: string[]
failed: { name: string; error: string }[]
}

View File

@ -8,7 +8,7 @@
*
* Safety rules baked in:
* - the source record is the only thing trusted for a repository URL;
* - a fresh clone happens in `$DSH_HOME/.dsh-brain-staging` and the copy is
* - a fresh clone happens in `$DSH_HOME/.cloud-memory-staging` and the copy is
* filtered (no `.git`, no symlinks);
* - a backup is always taken before an update so rollback is possible even
* when the update is interrupted;
@ -26,7 +26,7 @@ import { dshHome } from './store.ts'
/** Where pre-update backups are kept (one folder per skill, one dir per run). */
export function skillBackupsDir(): string {
return join(dshHome(), '.dsh-brain-backups')
return join(dshHome(), '.cloud-memory-backups')
}
/** One file on disk with its hash, used for diffing two trees. */
@ -166,7 +166,7 @@ export class SkillUpdater {
/** Clone the pinned source at its latest commit into a scratch directory. */
private async cloneLatest(source: SkillSourceRecord): Promise<{ dir: string; commit: string; cleanup: () => Promise<void> }> {
const root = join(dshHome(), '.dsh-brain-staging')
const root = join(dshHome(), '.cloud-memory-staging')
await mkdir(root, { recursive: true })
const dir = join(root, `update_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`)
try {

View File

@ -1,5 +1,5 @@
/**
* Settings sidecar: `$DSH_HOME/dsh-brain.json` (pre-rename `cloud-memory.json` is migrated on first load).
* Settings sidecar: `$DSH_HOME/cloud-memory.json`.
*
* Why a file and not the DSH credentials service: the desktop profile has no
* stable host-side credentials face this plugin can depend on (the client-side
@ -11,7 +11,7 @@
* The file holds the two bearer tokens and the UI-editable overrides. It is
* NEVER uploaded, never printed, and `describe()` only exposes a mask.
*/
import { existsSync, copyFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, chmodSync } from 'node:fs'
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync, chmodSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { homedir } from 'node:os'
import { DEFAULT_SETTINGS, isPlaceholderBaseUrl, normalizeBaseUrl, originOf, settingsFromConfig, type Settings } from './config.ts'
@ -58,30 +58,9 @@ export function dshHome(): string {
/** Absolute path of the settings sidecar. */
export function settingsPath(): string {
return resolve(dshHome(), 'dsh-brain.json')
}
/** Pre-rename (<=0.7.x) settings sidecar name. */
export function legacySettingsPath(): string {
return resolve(dshHome(), 'cloud-memory.json')
}
/**
* One-time rename carry-over: when `target` does not exist yet but the
* pre-rename `legacy` file does, copy it over so settings and tokens survive
* the dsh-cloud-memory -> dsh-brain rename. The legacy file is left in place
* (never deleted automatically). Returns true when a copy happened.
*/
export function migrateLegacyFile(target: string, legacy: string): boolean {
try {
if (target === legacy || existsSync(target) || !existsSync(legacy)) return false
copyFileSync(legacy, target)
return true
} catch {
return false
}
}
/** Read a token from an env var (an alternative to the sidecar for CI use). */
function envToken(name: string): string | undefined {
const value = process.env[name]
@ -154,7 +133,6 @@ export class SettingsStore {
constructor(rawConfig: unknown, file: string = settingsPath()) {
this.file = file
if (file === settingsPath()) migrateLegacyFile(file, legacySettingsPath())
this.configDefaults = { ...DEFAULT_SETTINGS, ...settingsFromConfig(rawConfig) }
this.state = this.read()
}
@ -200,17 +178,17 @@ export class SettingsStore {
/** The activity:write bearer token (sidecar first, env fallback). */
activityToken(): string {
return this.state.activityToken ?? envToken('DSH_BRAIN_ACTIVITY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_ACTIVITY_TOKEN') ?? ''
return this.state.activityToken ?? envToken('DSH_CLOUD_MEMORY_ACTIVITY_TOKEN') ?? ''
}
/** The memory:read / memory:write bearer token. */
memoryToken(): string {
return this.state.memoryToken ?? envToken('DSH_BRAIN_MEMORY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_MEMORY_TOKEN') ?? ''
return this.state.memoryToken ?? envToken('DSH_CLOUD_MEMORY_MEMORY_TOKEN') ?? ''
}
/** The summary:write bearer token (optional; absent disables summaries). */
summaryToken(): string {
return this.state.summaryToken ?? envToken('DSH_BRAIN_SUMMARY_TOKEN') ?? envToken('DSH_CLOUD_MEMORY_SUMMARY_TOKEN') ?? ''
return this.state.summaryToken ?? envToken('DSH_CLOUD_MEMORY_SUMMARY_TOKEN') ?? ''
}
/** Masked snapshot for the browser card. */

View File

@ -64,11 +64,11 @@ function renderJson(_args: unknown, value: unknown): TextBlock[] {
/** Assert the memory scope is usable, or throw a message the model can act on. */
function requireMemoryToken(deps: MemoryToolDeps): string {
if (!deps.settings().enabled) {
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。')
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /cloud-memory 页面开启后再试。')
}
const token = deps.memoryToken()
if (token === '') {
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。')
throw new Error('未配置记忆令牌。请在 /cloud-memory 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。')
}
return token
}

View File

@ -41,7 +41,7 @@ const { createRoutes } = await import('./lib/routes.js')
// "未配置服务", 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, 'dsh-brain.json'),
join(process.env.DSH_HOME, 'cloud-memory.json'),
)
const reporter = new Reporter({
client: () => ({
@ -57,7 +57,7 @@ const reporter = new Reporter({
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'),
syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'),
syncRunning: () => false,
log: () => {},
})
@ -107,7 +107,7 @@ async function call(method, path, body, extraHeaders) {
}
// ── A. status / capabilities ────────────────────────────────────────────
let status = await call('GET', '/dsh-brain/status')
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')
@ -116,53 +116,53 @@ check('the market is reported unavailable instead of faked off', status.body?.ca
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', '/dsh-brain/capabilities')
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', '/dsh-brain/config')).status === 405)
const evil = await call('PUT', '/dsh-brain/config', { clientId: 'x' }, { origin: 'https://evil.example' })
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', '/dsh-brain/config', 'clientId=x', { 'content-type': 'text/plain' })
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', '/dsh-brain/config', { baseUrl: 'https://memory.example.org/api/longmemory' }, { origin })
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', '/dsh-brain/config', { activityToken: 'cmt_new_activity' }, { origin })
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', '/dsh-brain/config', { defaultK: 25 }, { origin })
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', '/dsh-brain/skills/api')
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-brain' && typeof gamma?.skillSha256 === 'string' && typeof gamma?.installedAt === 'string')
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', '/dsh-brain/skills/detail', { folder: 'gamma' })
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', '/dsh-brain/skills/toggle', { folder: '../escape', enabled: false })
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', '/dsh-brain/skills/toggle', { folder: 'gamma', enabled: false })
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', '/dsh-brain/skills/toggle', { folder: 'gamma', enabled: true })
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 ───────────────────────────────────────────────────
@ -174,10 +174,10 @@ 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', '/dsh-brain/skills/install/plan', { url: 'javascript:alert(1)' })
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', '/dsh-brain/skills/install/plan', { url: `file://${repo}` })
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',
@ -190,45 +190,45 @@ check('candidates list the scripts they carry',
check('staging does not write into the skills root yet',
!existsSync(join(root, 'alpha')) && !existsSync(join(root, 'beta')))
const committed = await call('POST', '/dsh-brain/skills/install/commit', { planId: plan.body.planId, folders: ['alpha'] })
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, '.dsh-brain-staging')).length === 0)
const again = await call('POST', '/dsh-brain/skills/install/plan', { url: `file://${repo}` })
const collide = await call('POST', '/dsh-brain/skills/install/commit', { planId: again.body.planId, folders: ['alpha'] })
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', '/dsh-brain/skills/install/commit', { planId: 'plan_missing', folders: ['alpha'] })
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, '.dsh-brain-staging')).length === 0)
readdirSync(join(process.env.DSH_HOME, '.cloud-memory-staging')).length === 0)
// ── E. uninstall: preview then single-use token ─────────────────────────
const noConfirm = await call('POST', '/dsh-brain/skills/remove', { folder: 'alpha' })
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', '/dsh-brain/skills/remove', { folder: 'alpha', confirmed: true })
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', '/dsh-brain/skills/uninstall/plan', { folder: 'alpha' })
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', '/dsh-brain/skills/remove', { folder: 'beta', token: impact.body.token, confirmed: true })
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', '/dsh-brain/skills/remove', { folder: 'alpha', token: impact.body.token, confirmed: true })
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', '/dsh-brain/skills/remove', { folder: 'gamma', token: impact.body.token, confirmed: true })
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', '/dsh-brain/skills/toggle')
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', '/dsh-brain/skills/detail', 'folder=gamma', { 'content-type': 'text/plain' })
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', '/dsh-brain/skills/nope', {})
const unknown = await call('POST', '/cloud-memory/skills/nope', {})
check('an unknown skill subroute is a 404', unknown.status === 404)
server.close()

View File

@ -117,7 +117,7 @@ const statusBody = {
memory: { configured: true, masked: 'cmt_abc…9f2c' },
summary: { configured: false, masked: '' },
},
settingsPath: 'C:/Users/test/.dsh/dsh-brain.json',
settingsPath: 'C:/Users/test/.dsh/cloud-memory.json',
reporter: {
attempted: 3,
recorded: 2,
@ -155,7 +155,7 @@ const skillsBody = {
installedAt: new Date().toISOString(),
skillSha256: 'abcdef0123456789',
location: 'root',
ownerManager: 'dsh-brain',
ownerManager: 'dsh-cloud-memory',
writable: true,
},
{
@ -169,13 +169,13 @@ const skillsBody = {
installedAt: new Date().toISOString(),
skillSha256: 'ffeedd00112233',
location: 'holding',
ownerManager: 'dsh-brain',
ownerManager: 'dsh-cloud-memory',
writable: true,
},
],
root: 'C:/Users/test/.dsh/skills',
holding: 'C:/Users/test/.dsh/skills-disabled',
staging: 'C:/Users/test/.dsh/.dsh-brain-staging',
staging: 'C:/Users/test/.dsh/.cloud-memory-staging',
plans: [],
}
@ -208,10 +208,10 @@ async function fakeFetch(url, init) {
const path = String(url).split('?')[0]
let body = { ok: false, error: 'not-found' }
let status = 404
if (path === '/dsh-brain/status') {
if (path === '/cloud-memory/status') {
body = statusBody
status = 200
} else if (path.startsWith('/dsh-brain/skills/api')) {
} else if (path.startsWith('/cloud-memory/skills/api')) {
body = skillsBody
status = 200
} else if (path === '/mcp-connector/api') {
@ -239,7 +239,7 @@ globalThis.window = {
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
if (spec.id !== 'dsh-brain') throw new Error(`unexpected module id ${spec.id}`)
if (spec.id !== 'dsh-cloud-memory') throw new Error(`unexpected module id ${spec.id}`)
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({

View File

@ -160,7 +160,7 @@ const statusBody = {
memory: { configured: true, masked: 'cmt_abc…9f2c' },
summary: { configured: false, masked: '' },
},
settingsPath: 'C:/Users/test/.dsh/dsh-brain.json',
settingsPath: 'C:/Users/test/.dsh/cloud-memory.json',
reporter: {
attempted: 3,
recorded: 2,
@ -198,7 +198,7 @@ const skillsBody = {
installedAt: new Date().toISOString(),
skillSha256: 'abcdef0123456789',
location: 'root',
ownerManager: 'dsh-brain',
ownerManager: 'dsh-cloud-memory',
writable: true,
},
{
@ -212,13 +212,13 @@ const skillsBody = {
installedAt: new Date().toISOString(),
skillSha256: 'ffeedd00112233',
location: 'holding',
ownerManager: 'dsh-brain',
ownerManager: 'dsh-cloud-memory',
writable: true,
},
],
root: 'C:/Users/test/.dsh/skills',
holding: 'C:/Users/test/.dsh/skills-disabled',
staging: 'C:/Users/test/.dsh/.dsh-brain-staging',
staging: 'C:/Users/test/.dsh/.cloud-memory-staging',
plans: [],
}
@ -325,13 +325,13 @@ async function fakeFetch(url, init) {
const path = String(url).split('?')[0]
let body = { ok: false, error: 'not-found' }
let status = 404
if (path === '/dsh-brain/status') {
if (path === '/cloud-memory/status') {
body = statusBody
status = 200
} else if (path === '/dsh-brain/skills/sources') {
} else if (path === '/cloud-memory/skills/sources') {
body = treeBody
status = 200
} else if (path.startsWith('/dsh-brain/skills/api')) {
} else if (path.startsWith('/cloud-memory/skills/api')) {
body = skillsBody
status = 200
} else if (path === '/mcp-connector/api') {
@ -359,7 +359,7 @@ globalThis.window = {
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
if (spec.id !== 'dsh-brain') throw new Error(`unexpected module id ${spec.id}`)
if (spec.id !== 'dsh-cloud-memory') throw new Error(`unexpected module id ${spec.id}`)
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({
@ -470,66 +470,31 @@ check('the search limit is renamed and reachable', connection.includes('单次
check('no render boundary error on the connection tab', !connection.includes('渲染失败'))
const skillsText = await drive('skills', true)
check('the skills tab renders its sections', ['从其他软件导入', '技能文件夹', '从 Git 仓库安装', '技能市场', '云端同步与冲突'].every((label) => skillsText.includes(label)))
check('the tree is DSH-only: no source card, no foreign sources',
!skillsText.includes('C:/Users/test/.dsh/skills') && !skillsText.includes('由 Codex 自行加载'))
check('the skills tab renders its sections', ['技能文件夹', '从 Git 仓库安装', '技能市场', '云端同步与冲突'].every((label) => skillsText.includes(label)))
check('the tree shows every detected source with its path',
skillsText.includes('DSH') && skillsText.includes('Codex') && skillsText.includes('C:/Users/test/.dsh/skills') && skillsText.includes('2 个技能'))
check('categories render with their counts', skillsText.includes('QQ-Skill') && skillsText.includes('1 项 · 1/1 启用') && skillsText.includes('未分类'))
check('the metadata-only promise is on screen', skillsText.includes('分类只记在这个来源里,不移动文件'))
check('foreign sources start collapsed behind the import button',
!skillsText.includes('Codex') && !skillsText.includes('仅本卡'))
const openedImport = await drive('skills', true, '从其他软件导入')
check('clicking the import button reveals foreign sources as import candidates',
openedImport.includes('Codex') && openedImport.includes('收起') && !openedImport.includes('仅本卡'))
check('the import panel has search, select-all and batch import',
openedImport.includes('全选匹配可导入') &&
openedImport.includes('全选全部') &&
openedImport.includes('清空已选') &&
openedImport.includes('导入所选') &&
openedImport.includes('全选本来源'))
const openedAssign = await drive('skills', true, '把技能加入 QQ-Skill')
check('clicking + on a category opens the inline skill assignment picker with search',
openedAssign.includes('加入分类:QQ-Skill') &&
openedAssign.includes('可分配') &&
openedAssign.includes('全选匹配结果') &&
openedAssign.includes('全选全部') &&
openedAssign.includes('清空已选') &&
openedAssign.includes('保存分类') &&
openedAssign.includes('parked-one'))
check('a foreign source is marked card-only', skillsText.includes('仅本卡') && skillsText.includes('本卡不修改'))
// Categories start collapsed; expanding one must reveal its skills.
const expandedSkills = await drive('skills', true, '展开或收起 未分类')
check('a collapsed category hides its skills', !skillsText.includes('parked-one'))
check('expanding a category reveals its skill rows',
expandedSkills.includes('parked-one'))
check('skill rows stay slim: no inline meta line or text actions',
!expandedSkills.includes('32 B') && !expandedSkills.includes('卸载…'))
expandedSkills.includes('parked-one') && expandedSkills.includes('32 B'))
check('a DSH skill row offers detail, a switch and uninstall',
expandedSkills.includes('详情') && expandedSkills.includes('卸载…'))
const foreignSkills = await drive('skills', true, '展开或收起 未分类', 1)
check('a foreign skill row is marked read-only',
foreignSkills.includes('codex-one') && foreignSkills.includes('只读'))
check('the market gap is stated instead of simulated', skillsText.includes('能力缺口') || skillsText.includes('没有接入经验证的市场来源'))
check('no render boundary error on the skills tab', !skillsText.includes('渲染失败'))
const mcpText = await drive('mcp', true)
check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp'))
check('collapsed rows keep only name, state and transport',
mcpText.includes('已连接') && mcpText.includes('http') && !mcpText.includes('bearer'))
check('the heavier MCP sections start collapsed',
!mcpText.includes('校验并保存连接') && !mcpText.includes('预览作用域') && mcpText.includes('展开'))
const mcpDetail = await drive('mcp', true, '详情 demo-mcp')
check('expanding a connection reveals auth, scope and actions',
mcpDetail.includes('bearer') && mcpDetail.includes('健康检查') && mcpDetail.includes('工具列表') && mcpDetail.includes('移除连接'))
check('MCP state, transport and auth are shown', mcpText.includes('已连接') && mcpText.includes('http') && mcpText.includes('bearer'))
check('MCP actions are offered', mcpText.includes('健康检查') && mcpText.includes('工具列表') && mcpText.includes('移除连接'))
check('the injected tools cache starts empty', mcpText.includes('工具可见不等于业务可调用'))
check('the MCP list has search, filters and select-all',
mcpText.includes('全选匹配结果') &&
mcpText.includes('全选全部') &&
mcpText.includes('清空已选') &&
mcpText.includes('筛选:全部') &&
mcpText.includes('勾选左侧连接后'))
const mcpChosen = await drive('mcp', true, '全选匹配结果')
check('selecting all matched connections reveals the batch actions',
mcpChosen.includes('批量操作(已选 1)') && mcpChosen.includes('移除…'))
check('the removed MCP marketplace panel no longer renders', !mcpText.includes('MCP 市场') && !mcpText.includes('读取 MCP 市场失败'))
const missing = await drive('mcp', false)
check('a missing bridge becomes a stated capability gap', missing.includes('MCP 管理当前不可用') && missing.includes('MCP 服务器配置'))

View File

@ -31,7 +31,7 @@ writeFileSync(join(DSH, 'workspace-groups.manual.json'), JSON.stringify({ assign
const { ClientRegistry } = await import('./lib/clients.js')
const registry = new ClientRegistry({
home: () => HOME,
manualPath: () => join(DSH, 'dsh-brain-workspaces.json'),
manualPath: () => join(DSH, 'cloud-memory-workspaces.json'),
dshRegistryPath: () => join(DSH, 'workspace-groups.folders.json'),
dshManualPath: () => join(DSH, 'workspace-groups.manual.json'),
})
@ -70,7 +70,7 @@ const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const store = new SettingsStore({ clientId: 't' }, join(DSH, 'c.json'))
const reporter = new Reporter({ client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }), submitSummary: async () => ({ ok: true, status: 200, data: {} }) }), settings: () => ({ enabled: true, clientId: 't' }), activityToken: () => '', summary: () => ({ enabled: false, maxChars: 1 }), summaryToken: () => '', log: () => {} })
const routes = createRoutes({ version: '0.8.0', store, reporter, client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'x' }), listSkills: async () => ({ ok: true, status: 200, data: { items: [] } }) }), clients: registry })
const routes = createRoutes({ version: '0.7.0', store, reporter, client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'x' }), listSkills: async () => ({ ok: true, status: 200, data: { items: [] } }) }), clients: registry })
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
@ -81,11 +81,11 @@ const server = http.createServer((req, res) => {
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
const capsRes = await fetch(`${origin}/dsh-brain/capabilities`).then((r) => r.json())
check('capabilities advertise multiClient', capsRes.features?.multiClient === true && capsRes.features?.brainMigration === 'ready')
const overview = await fetch(`${origin}/dsh-brain/clients/overview`).then((r) => r.json())
const capsRes = await fetch(`${origin}/cloud-memory/capabilities`).then((r) => r.json())
check('capabilities advertise multiClient', capsRes.features?.multiClient === true && capsRes.features?.brainMigration === 'pending-deploy')
const overview = await fetch(`${origin}/cloud-memory/clients/overview`).then((r) => r.json())
check('overview route lists adapters and workspaces', overview.ok === true && overview.adapters.length === 6 && Array.isArray(overview.workspaces.dsh))
const invRoute = await fetch(`${origin}/dsh-brain/clients/inventory?software=codex&scope=global`).then((r) => r.json())
const invRoute = await fetch(`${origin}/cloud-memory/clients/inventory?software=codex&scope=global`).then((r) => r.json())
check('inventory route returns codex skills', invRoute.ok === true && invRoute.items.length === 1)
await new Promise((resolve) => server.close(resolve))
@ -93,7 +93,7 @@ await new Promise((resolve) => server.close(resolve))
const { brainStatus, migrateLegacyFiles } = await import('./lib/brain-migration.js')
writeFileSync(join(DSH, 'cloud-memory.json'), JSON.stringify({ version: 1, baseUrl: 'https://x/api/longmemory', activityToken: 'cmt_aaaaaaaaaaaaaaaaaaaa' }))
const st = await brainStatus()
check('migration is needed when only legacy files exist', st.migrationNeeded === true && st.packageRename === 'done')
check('migration is needed when only legacy files exist', st.migrationNeeded === true && st.packageRename === 'pending-deploy')
const onceRun = await migrateLegacyFiles()
check('legacy config is copied to dsh-brain.json', onceRun.copied.includes('dsh-brain.json') && existsSync(join(DSH, 'dsh-brain.json')))
check('legacy file is retained', existsSync(join(DSH, 'cloud-memory.json')))

View File

@ -28,7 +28,7 @@ mkdirSync(join(root, 'alpha'), { recursive: true })
writeFileSync(join(root, 'alpha', 'SKILL.md'), '# alpha\n')
let running = true
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'), syncRunning: () => running, log: () => {} })
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), syncRunning: () => running, log: () => {} })
const updater = new SkillUpdater({ admin, skillsRoot: () => root, holdingDir: () => holding, syncRunning: () => running, log: () => {} })
async function expectCode(fn, code) {
@ -55,7 +55,7 @@ const server = http.createServer((req, res) => {
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
const response = await fetch(`${origin}/dsh-brain/skills/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ folder: 'alpha', enabled: false }) })
const response = await fetch(`${origin}/cloud-memory/skills/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ folder: 'alpha', enabled: false }) })
const body = await response.json()
check('route answers 409 sync_running during a sync', response.status === 409 && body.code === 'sync_running', JSON.stringify(body))
await new Promise((resolve) => server.close(resolve))

View File

@ -1,6 +1,6 @@
// Whole-plugin load test: activate the real `apply()` against a host-shaped
// context, then serve the exact routes it registered over a real HTTP server and
// query them. This proves the 0.9.0 build loads and serves every surface a DSH
// query them. This proves the 0.7.0 build loads and serves every surface a DSH
// restart will expose, without needing to restart the desktop app.
import http from 'node:http'
import { mkdtempSync } from 'node:fs'
@ -56,25 +56,25 @@ async function post(path, body) {
return { status: response.status, body: await response.json().catch(() => null) }
}
const caps = await get('/dsh-brain/capabilities')
check('capabilities answers with 0.9.8', caps.body?.version === '0.9.8', String(caps.body?.version))
const caps = await get('/cloud-memory/capabilities')
check('capabilities answers with 0.7.0', caps.body?.version === '0.7.0', String(caps.body?.version))
check('P3 market is advertised with one provider', caps.body?.features?.skillsMarketplace === true && caps.body?.features?.marketProviders === 1)
check('P3 update and sync-resolve are advertised', caps.body?.features?.skillUpdate === true && caps.body?.features?.syncResolve === true)
check('P4/P5/v1.1 flags are advertised', caps.body?.features?.multiClient === true && caps.body?.features?.brainMigration === 'ready')
check('P4/P5/v1.1 flags are advertised', caps.body?.features?.multiClient === true && caps.body?.features?.brainMigration === 'pending-deploy')
const providers = await get('/dsh-brain/market/providers')
const providers = await get('/cloud-memory/market/providers')
check('market providers route lists the verified source', providers.body?.providers?.[0]?.id === 'anthropic-skills', JSON.stringify(providers.body?.providers))
const sync = await get('/dsh-brain/sync/status')
const sync = await get('/cloud-memory/sync/status')
check('sync status route answers', sync.body?.ok === true && Array.isArray(sync.body?.conflicts))
const clients = await get('/dsh-brain/clients/overview')
const clients = await get('/cloud-memory/clients/overview')
check('clients overview lists six adapters', clients.body?.ok === true && clients.body?.adapters?.length === 6)
const brain = await get('/dsh-brain/migrate/brain')
check('brain migration status answers', brain.body?.ok === true && brain.body?.product === 'DSH Brain' && brain.body?.packageRename === 'done')
const inv = await get('/dsh-brain/clients/inventory?software=dsh&scope=global')
const brain = await get('/cloud-memory/migrate/brain')
check('brain migration status answers', brain.body?.ok === true && brain.body?.product === 'DSH Brain' && brain.body?.packageRename === 'pending-deploy')
const inv = await get('/cloud-memory/clients/inventory?software=dsh&scope=global')
check('inventory route answers for DSH', inv.body?.ok === true && Array.isArray(inv.body?.items))
const skills = await get('/dsh-brain/skills/api')
const skills = await get('/cloud-memory/skills/api')
check('skill inventory route answers', skills.body?.ok === true && Array.isArray(skills.body?.skills))
const status = await get('/dsh-brain/status')
const status = await get('/cloud-memory/status')
check('status route answers', status.body?.ok === true && status.body?.settings?.baseUrlConfigured === false)
await new Promise((resolve) => server.close(resolve))

View File

@ -87,12 +87,12 @@ const { Reporter } = await import('./lib/reporter.js')
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { createRoutes } = await import('./lib/routes.js')
const store = new SettingsStore({ clientId: 'test', requestTimeoutMs: 2000, defaultK: 10 }, join(process.env.DSH_HOME, 'dsh-brain.json'))
const store = new SettingsStore({ clientId: 'test', requestTimeoutMs: 2000, defaultK: 10 }, 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' }), activityToken: () => '', summary: () => ({ enabled: false, maxChars: 1 }), summaryToken: () => '', log: () => {},
})
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'), syncRunning: () => false, log: () => {} })
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), syncRunning: () => false, log: () => {} })
const entry = { id: 'alpha', providerId: 'fake', name: 'alpha', description: 'fake alpha', skills: ['alpha'], skillPaths: ['./skills/alpha'], sourceRepo: 'local/repo', sourceUrl: 'file://x' }
const fakeProvider = {
info: () => ({ id: 'fake', label: 'Fake', description: 'local', source: 'local/repo', homepage: 'https://example' }),
@ -124,22 +124,22 @@ async function call(method, path, body) {
return { status: response.status, body: await response.json().catch(() => null) }
}
const caps = await call('GET', '/dsh-brain/capabilities')
const caps = await call('GET', '/cloud-memory/capabilities')
check('capabilities advertise the wired market', caps.body?.features?.skillsMarketplace === true && caps.body?.features?.marketProviders === 1)
const providers = await call('GET', '/dsh-brain/market/providers')
const providers = await call('GET', '/cloud-memory/market/providers')
check('providers route lists the provider', providers.body?.providers?.[0]?.id === 'fake')
const search = await call('GET', '/dsh-brain/market/search?provider=fake&q=alp')
const search = await call('GET', '/cloud-memory/market/search?provider=fake&q=alp')
check('search route returns entries', search.status === 200 && search.body?.entries?.length === 1)
const unknown = await call('GET', '/dsh-brain/market/search?provider=nope&q=')
const unknown = await call('GET', '/cloud-memory/market/search?provider=nope&q=')
check('unknown provider is a 400', unknown.status === 400 && unknown.body?.code === 'unknown_provider')
const det = await call('POST', '/dsh-brain/market/detail', { provider: 'fake', id: 'alpha' })
const det = await call('POST', '/cloud-memory/market/detail', { provider: 'fake', id: 'alpha' })
check('detail route returns skill metadata', det.status === 200 && det.body?.skillDetails?.[0]?.name === 'alpha')
const plan = await call('POST', '/dsh-brain/market/plan', { provider: 'fake', id: 'alpha' })
const plan = await call('POST', '/cloud-memory/market/plan', { provider: 'fake', id: 'alpha' })
check('plan route returns a staged plan', plan.status === 200 && typeof plan.body?.planId === 'string', JSON.stringify(plan.body).slice(0, 120))
check('plan pins the resolved commit', plan.body?.commit === commit)
check('plan only exposes the entry folders (beta excluded)', Array.isArray(plan.body?.candidates) && plan.body.candidates.length === 1 && plan.body.candidates[0].folder === 'alpha')
const commitRes = await call('POST', '/dsh-brain/market/commit', { planId: plan.body?.planId, folders: ['alpha'] })
const commitRes = await call('POST', '/cloud-memory/market/commit', { planId: plan.body?.planId, folders: ['alpha'] })
check('commit installs the selected skill', commitRes.status === 200 && commitRes.body?.installed?.includes('alpha'), JSON.stringify(commitRes.body))
check('installed skill has a SKILL.md', existsSync(join(root, 'alpha', 'SKILL.md')))
check('beta was never installed', !existsSync(join(root, 'beta')))

View File

@ -1,45 +0,0 @@
// 0.8.0 unification: the completed rename carries legacy state over.
// Legacy sidecars (settings with tokens, skills sync state, skill groups)
// are copied to the dsh-brain names on first load; legacy files are kept;
// legacy env token names still work, new names win.
import assert from 'node:assert'
import { mkdtempSync, writeFileSync, existsSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const home = mkdtempSync(join(tmpdir(), 'dsh-brain-mig-'))
process.env.DSH_HOME = home
writeFileSync(join(home, 'cloud-memory.json'), JSON.stringify({
version: 1, baseUrl: 'https://example.test/api/longmemory', clientId: 'mig-client',
activityToken: 'cmt_act_mig', memoryToken: 'cmt_mem_mig', summaryToken: 'cmt_sum_mig',
}))
writeFileSync(join(home, 'cloud-memory-skills.json'), JSON.stringify({ uploaded: { demo: { revision: 3 } } }))
writeFileSync(join(home, 'cloud-memory-skill-groups.json'), JSON.stringify({ groups: [] }))
process.env.DSH_CLOUD_MEMORY_MEMORY_TOKEN = 'cmt_env_legacy'
const { SettingsStore } = await import('./lib/store.js')
const { skillsStatePath } = await import('./lib/skill-sync.js')
const { skillGroupsPath } = await import('./lib/skill-groups.js')
const store = new SettingsStore({})
assert.ok(store.path.endsWith('dsh-brain.json'), 'new settings path')
assert.equal(store.settings().baseUrl, 'https://example.test/api/longmemory')
assert.equal(store.activityToken(), 'cmt_act_mig', 'token migrated from legacy file')
assert.ok(existsSync(join(home, 'dsh-brain.json')), 'new sidecar written')
assert.ok(existsSync(join(home, 'cloud-memory.json')), 'legacy sidecar preserved')
const p = skillsStatePath()
assert.ok(p.endsWith('dsh-brain-skills.json'))
assert.deepEqual(JSON.parse(readFileSync(p, 'utf8')), { uploaded: { demo: { revision: 3 } } })
const g = skillGroupsPath()
assert.ok(g.endsWith('dsh-brain-skill-groups.json'))
assert.ok(existsSync(join(home, 'dsh-brain-skill-groups.json')), 'groups sidecar migrated')
const store2 = new SettingsStore({}, join(home, 'fresh.json'))
assert.equal(store2.memoryToken(), 'cmt_env_legacy', 'legacy env name honored')
process.env.DSH_BRAIN_MEMORY_TOKEN = 'cmt_env_new'
assert.equal(store2.memoryToken(), 'cmt_env_new', 'new env name wins')
rmSync(home, { recursive: true, force: true })
console.log('verify-rename-migration: all checks passed')

View File

@ -1,144 +0,0 @@
// Verification for 「从其他软件导入」 (import a skill from another tool).
//
// The promises asserted here are the ones the card makes: the source
// directory is never modified, a same-name skill in DSH (enabled or
// parked) is never overwritten, and the copy is as strict as a git
// install — symlinks and `.git` never travel.
import http from 'node:http'
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-import-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
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 root = join(process.env.DSH_HOME, 'skills')
const holding = join(process.env.DSH_HOME, 'skills-disabled')
const foreignRoot = join(tmpdir(), `foreign-codex-${Date.now()}`)
mkdirSync(root, { recursive: true })
mkdirSync(holding, { recursive: true })
mkdirSync(foreignRoot, { recursive: true })
writeSkill(foreignRoot, 'good-skill', {
'SKILL.md': '---\nname: good-skill\ndescription: 好技能\n---\n\n# good-skill\n',
'references/notes.md': 'notes',
})
writeSkill(foreignRoot, 'with-link', { 'SKILL.md': '# with-link\n' })
symlinkSync(join(foreignRoot, 'good-skill', 'SKILL.md'), join(foreignRoot, 'with-link', 'escape.md'))
writeSkill(foreignRoot, 'with-git', { 'SKILL.md': '# with-git\n', '.git/objects/pack': 'x' })
writeSkill(foreignRoot, 'no-marker', { 'README.md': 'no skill marker' })
writeSkill(foreignRoot, 'real-target', { 'SKILL.md': '# real\n' })
symlinkSync(join(foreignRoot, 'real-target'), join(foreignRoot, 'link-skill'))
writeSkill(holding, 'parked-one', { 'SKILL.md': '# parked\n' })
writeSkill(foreignRoot, 'parked-one', { 'SKILL.md': '# parked clone\n' })
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { SkillGroupManager } = await import('./lib/skill-groups.js')
const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const { createRoutes } = await import('./lib/routes.js')
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'),
syncRunning: () => false,
log: () => {},
})
const sources = () => [
{ id: 'dsh', label: 'DSH', root, writable: true, manager: 'DSH' },
{ id: 'codex', label: 'Codex', root: foreignRoot, writable: false, manager: 'Codex' },
]
const manager = new SkillGroupManager({ sources, admin, storePath: () => join(process.env.DSH_HOME, 'dsh-brain-skill-groups.json'), log: () => {} })
const codeOf = async (promise) => {
try {
await promise
return 'no-throw'
} catch (error) {
return error.code ?? error.message
}
}
// ── happy path ────────────────────────────────────────────────────────
const imported = await manager.importSkill('codex', 'good-skill')
check('import returns the folder', imported.folder === 'good-skill')
check('the skill lands in the DSH root with its files',
readFileSync(join(root, 'good-skill', 'references', 'notes.md'), 'utf8') === 'notes' &&
readFileSync(join(root, 'good-skill', 'SKILL.md'), 'utf8').includes('good-skill'))
check('the source directory is untouched',
existsSync(join(foreignRoot, 'good-skill', 'SKILL.md')) && !existsSync(join(foreignRoot, 'good-skill', 'references', 'moved')))
const listed = await admin.list()
check('the imported skill shows in the DSH inventory', listed.skills.some((skill) => skill.folder === 'good-skill'))
// ── refusals ──────────────────────────────────────────────────────────
check('a second import of the same skill is refused', await codeOf(manager.importSkill('codex', 'good-skill')) === 'already_exists')
check('importing over a parked same-name skill is refused', await codeOf(manager.importSkill('codex', 'parked-one')) === 'already_exists')
check('importing from the DSH source itself is refused', await codeOf(manager.importSkill('dsh', 'good-skill')) === 'import_from_self')
check('a traversal folder name is refused', await codeOf(manager.importSkill('codex', '../escape')) === 'invalid_name')
check('a skill without SKILL.md is refused', await codeOf(manager.importSkill('codex', 'no-marker')) === 'invalid_skill')
check('a symlinked skill directory is refused', await codeOf(manager.importSkill('codex', 'link-skill')) === 'invalid_skill')
check('an unknown source is refused', await codeOf(manager.importSkill('nope', 'good-skill')) === 'unknown_source')
check('a missing skill is a 404-style refusal', await codeOf(manager.importSkill('codex', 'ghost')) === 'not_found')
// ── copy hygiene ──────────────────────────────────────────────────────
await manager.importSkill('codex', 'with-link')
check('symlinks inside a skill are dropped, not copied',
existsSync(join(root, 'with-link', 'SKILL.md')) && !existsSync(join(root, 'with-link', 'escape.md')))
await manager.importSkill('codex', 'with-git')
check('.git never travels with an import',
existsSync(join(root, 'with-git', 'SKILL.md')) && !existsSync(join(root, 'with-git', '.git')))
// ── route surface ─────────────────────────────────────────────────────
const store = new SettingsStore({ baseUrl: 'https://memory.example.org/api/longmemory' }, join(process.env.DSH_HOME, 'dsh-brain.json'))
const reporter = new Reporter({
client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }) }),
settings: () => ({ enabled: true, clientId: 'import' }),
activityToken: () => '',
summary: () => ({ enabled: false, maxChars: 1000 }),
summaryToken: () => '',
log: () => {},
})
const routes = createRoutes({ version: 'test', store, reporter, client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'stub' }) }), admin, groups: manager })
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}')
})
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) {
const response = await fetch(`${origin}${path}`, {
method,
headers: { accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
body: body === undefined ? undefined : JSON.stringify(body),
})
return { status: response.status, body: await response.json().catch(() => null) }
}
writeSkill(foreignRoot, 'route-skill', { 'SKILL.md': '# route\n' })
const viaRoute = await call('POST', '/dsh-brain/skills/import', { sourceId: 'codex', folder: 'route-skill' })
check('POST /skills/import imports through the real route', viaRoute.status === 200 && viaRoute.body?.ok === true && existsSync(join(root, 'route-skill', 'SKILL.md')))
const dupe = await call('POST', '/dsh-brain/skills/import', { sourceId: 'codex', folder: 'route-skill' })
check('the route maps a duplicate import to a client error', dupe.status >= 400 && dupe.body?.code === 'already_exists')
server.close()
const failed = results.filter((item) => !item.ok)
console.log(failed.length === 0 ? `ALL ${results.length} CHECKS PASSED` : `${failed.length}/${results.length} CHECKS FAILED`)
process.exit(failed.length === 0 ? 0 : 1)

View File

@ -38,7 +38,7 @@ const { createRoutes } = await import('./lib/routes.js')
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'),
syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'),
syncRunning: () => false,
log: () => {},
})
@ -60,7 +60,7 @@ const sources = () => [
note: '由 Codex 自行加载,本卡不修改它的目录',
},
]
const storePath = join(process.env.DSH_HOME, 'dsh-brain-skill-groups.json')
const storePath = join(process.env.DSH_HOME, 'cloud-memory-skill-groups.json')
const manager = new SkillGroupManager({ sources, admin, storePath: () => storePath })
// ── A. overview ─────────────────────────────────────────────────────────
@ -166,7 +166,7 @@ check('categories survive a manager restart',
check('the sidecar holds metadata only, never a file path',
!readFileSync(storePath, 'utf8').includes('SKILL.md'))
const store = new SettingsStore({ baseUrl: 'https://memory.example.org/api/longmemory' }, join(process.env.DSH_HOME, 'dsh-brain.json'))
const store = new SettingsStore({ baseUrl: 'https://memory.example.org/api/longmemory' }, join(process.env.DSH_HOME, 'cloud-memory.json'))
const reporter = new Reporter({
client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }) }),
settings: () => ({ enabled: true, clientId: 'tree' }),
@ -213,18 +213,18 @@ async function call(method, path, body) {
return { status: response.status, body: parsed }
}
const sourcesResponse = await call('GET', '/dsh-brain/skills/sources')
const sourcesResponse = await call('GET', '/cloud-memory/skills/sources')
check('the sources route answers with the tree', sourcesResponse.status === 200 && Array.isArray(sourcesResponse.body?.sources))
check('the tree carries the metadata-only note', String(sourcesResponse.body?.note).includes('不移动文件'))
check('POST on the sources route is refused', (await call('POST', '/dsh-brain/skills/sources', {}))?.status === 405)
check('POST on the sources route is refused', (await call('POST', '/cloud-memory/skills/sources', {}))?.status === 405)
const viaRoute = await call('POST', '/dsh-brain/skills/groups/create', { sourceId: 'dsh', name: '路由组' })
const viaRoute = await call('POST', '/cloud-memory/skills/groups/create', { sourceId: 'dsh', name: '路由组' })
check('a category can be created over HTTP', viaRoute.status === 200 && typeof viaRoute.body?.groupId === 'string')
const dupViaRoute = await call('POST', '/dsh-brain/skills/groups/create', { sourceId: 'dsh', name: '路由组' })
const dupViaRoute = await call('POST', '/cloud-memory/skills/groups/create', { sourceId: 'dsh', name: '路由组' })
check('a duplicate over HTTP is a 400', dupViaRoute.status === 400 && dupViaRoute.body?.code === 'duplicate')
const missingGroup = await call('POST', '/dsh-brain/skills/groups/delete', { sourceId: 'dsh', groupId: 'g_missing' })
const missingGroup = await call('POST', '/cloud-memory/skills/groups/delete', { sourceId: 'dsh', groupId: 'g_missing' })
check('an unknown category is a 404', missingGroup.status === 404)
const revealMissing = await call('POST', '/dsh-brain/skills/source/reveal', { sourceId: 'agents' })
const revealMissing = await call('POST', '/cloud-memory/skills/source/reveal', { sourceId: 'agents' })
check('revealing a missing directory reports not_found instead of failing silently', revealMissing.status === 404 || revealMissing.status === 200)
server.close()

View File

@ -4,7 +4,7 @@
// bundles, linked manifest) — no DSH host, no real service, no real token.
import http from 'node:http'
import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@ -27,24 +27,16 @@ function storeFiles(files) {
return { path: file.path, sha256: sha(buffer), size: buffer.length, encoding: file.content !== undefined ? 'utf8' : 'base64', data: buffer.toString('base64') }
})
}
const DAY = 24 * 60 * 60 * 1000
const CLOUD_OLD = Date.parse('2026-01-01T00:00:00.000Z')
const CLOUD_EQUAL = Date.parse('2026-06-01T00:00:00.000Z')
const iso = (value) => new Date(value).toISOString()
function summaryOf(skill) {
return {
name: skill.name, description: skill.description, execution_mode: skill.execution_mode,
enabled: true, revision: skill.revision, manifest_sha256: linked(skill.files), files: skill.files.length,
script_changed: skill.script_changed,
created_at: iso(skill.created_at ?? CLOUD_OLD), updated_at: iso(skill.updated_at ?? CLOUD_OLD),
}
}
function seed(name, files, extra = {}) {
const stored = storeFiles(files)
center.set(name, {
name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored,
script_changed: false, created_at: CLOUD_OLD, updated_at: CLOUD_OLD, ...extra,
})
center.set(name, { name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored, script_changed: false, ...extra })
}
seed('cloud-one', [
{ path: 'SKILL.md', content: '# cloud-one\n\n云端技能一。' },
@ -81,11 +73,7 @@ const server = http.createServer((req, res) => {
const body = await readBody()
if (body.expected_revision !== 0) return send(400, { error: 'invalid_input', message: '必须提供 expected_revision' })
if (center.has(body.name)) return send(409, { error: 'skill_exists', message: '同名技能已存在' })
const skill = {
name: body.name, description: body.description, execution_mode: body.execution_mode ?? 'prompt-only',
revision: 1, files: storeFiles(body.files ?? []), script_changed: false,
created_at: Date.now(), updated_at: Date.now(),
}
const skill = { name: body.name, description: body.description, execution_mode: body.execution_mode ?? 'prompt-only', revision: 1, files: storeFiles(body.files ?? []), script_changed: false }
center.set(skill.name, skill)
return send(201, { skill: summaryOf(skill), revision: 1, manifest_sha256: linked(skill.files) })
}
@ -98,7 +86,6 @@ const server = http.createServer((req, res) => {
if (body.files) skill.files = storeFiles(body.files)
if (body.description !== undefined) skill.description = body.description
skill.revision += 1
skill.updated_at = Date.now()
return send(200, { skill: summaryOf(skill), revision: skill.revision, manifest_sha256: linked(skill.files) })
}
return send(404, { error: 'unknown_route', path })
@ -119,12 +106,11 @@ const engine = new SkillSync({
})
const root = join(process.env.DSH_HOME, 'skills')
const skillDir = (name) => join(root, name)
const writeLocal = (name, files, mtime = Date.now()) => {
const writeLocal = (name, files) => {
for (const [rel, content] of Object.entries(files)) {
const target = join(skillDir(name), ...rel.split('/'))
mkdirSync(join(target, '..'), { recursive: true })
writeFileSync(target, content)
utimesSync(target, new Date(mtime), new Date(mtime))
}
}
@ -159,71 +145,23 @@ writeLocal('local-one', { 'SKILL.md': '---\nname: local-one\ndescription: 本地
stats = await engine.syncOnce()
check('edited local skill updates the center', stats.updated.includes('local-one') && center.get('local-one')?.revision === 2)
// 4. A local edit newer than the cloud is uploaded automatically.
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' }, Date.now())
// 4. A locally modified cloud skill is flagged, never overwritten or uploaded.
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' })
stats = await engine.syncOnce()
check('local edit newer than cloud auto-uploads',
stats.updated.includes('cloud-one') && center.get('cloud-one')?.revision === 2, JSON.stringify(stats.conflicts))
check('the newer local edit stays on disk',
check('local edit of a cloud skill becomes a conflict',
stats.conflicts.some((c) => c.name === 'cloud-one' && c.reason === 'locally_modified'), JSON.stringify(stats.conflicts))
check('the local edit is left untouched',
readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('我改了云端技能'))
check('newer local edit is not a conflict', !stats.conflicts.some((c) => c.name === 'cloud-one'))
check('the center copy is untouched by the conflict',
center.get('cloud-one')?.revision === 1)
// 4b. Cloud newer than a stale local copy: auto-download with a local backup.
{
const cloud = center.get('cloud-one')
cloud.revision += 1
cloud.files = storeFiles([{ path: 'SKILL.md', content: '# cloud-one v3 (cloud newer)' }])
cloud.updated_at = Date.now() + DAY
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one local stale\n' }, Date.now() - DAY)
stats = await engine.syncOnce()
check('cloud newer auto-downloads over a stale local copy',
readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('cloud newer'))
const backupRoot = join(process.env.DSH_HOME, '.dsh-brain-backups', 'sync', 'cloud-one')
check('auto overwrite backs the local copy up', existsSync(backupRoot))
check('cloud newer overwrite is not a conflict', !stats.conflicts.some((c) => c.name === 'cloud-one'))
}
// 5a. Identical bytes on both sides: adopt silently, no transfer, no conflict.
seed('clash-same', [{ path: 'SKILL.md', content: '# clash same' }], { updated_at: CLOUD_OLD })
writeLocal('clash-same', { 'SKILL.md': '# clash same' }, CLOUD_OLD - DAY)
// 5. A name collision on both sides is flagged, both copies untouched.
seed('clash', [{ path: 'SKILL.md', content: '# clash cloud' }])
writeLocal('clash', { 'SKILL.md': '# clash local\n' })
stats = await engine.syncOnce()
check('identical collision auto-adopts without a conflict',
!stats.conflicts.some((c) => c.name === 'clash-same') && existsSync(join(skillDir('clash-same'), '.manifest.json')))
check('identical collision uploads nothing', center.get('clash-same')?.revision === 1)
// 5b. Local newer wins the collision.
seed('clash-local', [{ path: 'SKILL.md', content: '# clash cloud' }], { updated_at: CLOUD_OLD })
writeLocal('clash-local', { 'SKILL.md': '# clash local newer' }, CLOUD_OLD + DAY)
stats = await engine.syncOnce()
check('local newer collision auto-uploads',
center.get('clash-local')?.revision === 2 && stats.updated.includes('clash-local'))
check('local newer collision keeps the local file',
readFileSync(join(skillDir('clash-local'), 'SKILL.md'), 'utf8').includes('local newer'))
// 5c. Cloud newer wins the collision.
seed('clash-cloud', [{ path: 'SKILL.md', content: '# clash cloud newer' }], { updated_at: Date.now() + DAY })
writeLocal('clash-cloud', { 'SKILL.md': '# clash local stale' }, Date.now() - DAY)
stats = await engine.syncOnce()
check('cloud newer collision auto-downloads',
readFileSync(join(skillDir('clash-cloud'), 'SKILL.md'), 'utf8').includes('cloud newer'))
check('cloud newer collision is not a conflict', !stats.conflicts.some((c) => c.name === 'clash-cloud'))
// 5d. Same timestamp on both sides: still a human decision.
seed('clash-equal', [{ path: 'SKILL.md', content: '# clash cloud same-time' }], { updated_at: CLOUD_EQUAL })
writeLocal('clash-equal', { 'SKILL.md': '# clash local same-time' }, CLOUD_EQUAL)
stats = await engine.syncOnce()
check('equal timestamps keep the name collision conflict',
stats.conflicts.some((c) => c.name === 'clash-equal' && c.reason === 'name_collision'))
check('equal-timestamp collision leaves both sides untouched',
readFileSync(join(skillDir('clash-equal'), 'SKILL.md'), 'utf8').includes('same-time') && center.get('clash-equal')?.revision === 1)
// 5e. A same-name conflict is reported once, not once per reason.
seed('bad-clash', [{ path: 'SKILL.md', content: '# bad cloud' }], { updated_at: CLOUD_EQUAL })
writeLocal('bad-clash', { 'SKILL.md': '# bad local', 'README.md': 'root file' }, CLOUD_EQUAL)
stats = await engine.syncOnce()
const badClashConflicts = stats.conflicts.filter((c) => c.name === 'bad-clash')
check('one card per same-name conflict',
badClashConflicts.length === 1 && badClashConflicts[0]?.reason === 'name_collision', JSON.stringify(badClashConflicts))
check('name collision is flagged', stats.conflicts.some((c) => c.name === 'clash' && c.reason === 'name_collision'))
check('collision leaves local files alone', readFileSync(join(skillDir('clash'), 'SKILL.md'), 'utf8').includes('clash local'))
check('collision leaves the center alone', center.get('clash')?.revision === 1)
// 6. Script-changed cloud bundles wait for review.
check('script-changed bundle is not installed',
@ -239,7 +177,7 @@ check('unsupported skill never reaches the center', !center.has('bad-layout'))
rmSync(skillDir('local-one'), { recursive: true, force: true })
stats = await engine.syncOnce()
check('local deletion keeps the cloud copy', center.has('local-one') && !requestLog.some((line) => line.startsWith('DELETE')))
const sidecar = JSON.parse(readFileSync(join(process.env.DSH_HOME, 'dsh-brain-skills.json'), 'utf8'))
const sidecar = JSON.parse(readFileSync(join(process.env.DSH_HOME, 'cloud-memory-skills.json'), 'utf8'))
check('sidecar forgets the deleted local skill', !('local-one' in (sidecar.uploaded ?? {})))
server.close()

View File

@ -73,18 +73,13 @@ const take = await sync.resolveConflict('demo', 'take_cloud')
check('take_cloud applies and backs up', take.applied === true && typeof take.backup === 'string' && existsSync(take.backup), JSON.stringify(take))
check('take_cloud overwrote SKILL.md with the cloud copy', readFileSync(join(root, 'demo', 'SKILL.md'), 'utf8').includes('CLOUD'))
check('take_cloud backup holds the old file', readFileSync(join(take.backup, 'SKILL.md'), 'utf8').includes('local'))
const afterTake = JSON.parse(readFileSync(join(process.env.DSH_HOME, 'dsh-brain-skills.json'), 'utf8'))
check('take_cloud clears upload provenance', afterTake.uploaded?.demo === undefined && afterTake.delivered?.demo !== undefined)
check('take_cloud writes a delivery manifest', existsSync(join(root, 'demo', '.manifest.json')))
// keep_local
const keep = await sync.resolveConflict('demo2', 'keep_local')
check('keep_local uploads and bumps revision', keep.applied === true && keep.revision === 6, JSON.stringify(keep))
check('keep_local used the cloud revision as expected_revision', updateCalls.some((c) => c.name === 'demo2' && c.expected === 5), JSON.stringify(updateCalls))
const state = JSON.parse(readFileSync(join(process.env.DSH_HOME, 'dsh-brain-skills.json'), 'utf8'))
const state = JSON.parse(readFileSync(join(process.env.DSH_HOME, 'cloud-memory-skills.json'), 'utf8'))
check('keep_local recorded the upload in the sidecar', state.uploaded?.demo2?.revision === 6)
check('keep_local clears cloud delivery provenance', state.delivered?.demo2 === undefined)
check('keep_local removes the cloud delivery manifest', !existsSync(join(root, 'demo2', '.manifest.json')))
// manual
const manual = await sync.resolveConflict('demo3', 'manual')
@ -98,59 +93,6 @@ check('keep_local refuses a stale cloud revision', stale)
const remaining = await sync.conflictDetails()
check('resolved conflicts drop out of the list', remaining.some((d) => d.name === 'demo') === false && remaining.some((d) => d.name === 'demo2') === false)
// Batch: partial failures are reported per item, not fatal.
const batchKeep = await sync.resolveConflicts('keep_local')
check('batch keep_local resolves the good item and reports the stale one',
batchKeep.resolved.includes('demo3') && batchKeep.failed.some((f) => f.name === 'demo4' && f.error === 'stale_revision'),
JSON.stringify(batchKeep))
const afterBatch = await sync.conflictDetails()
check('batch leaves only the failed conflict', afterBatch.length === 1 && afterBatch[0].name === 'demo4')
let badAction = false
try { await sync.resolveConflicts('manual') } catch (error) { badAction = error.message === 'invalid_action' }
check('batch refuses a non-batch action', badAction)
// Second home: a clean batch over every conflict succeeds.
const secondHome = mkdtempSync(join(tmpdir(), 'brain-sync-batch-'))
process.env.DSH_HOME = secondHome
const root2 = join(secondHome, 'skills')
mkdirSync(root2, { recursive: true })
const cloudBody2 = '---\nname: b1\n---\n# b1 CLOUD\n'
const files2 = [{ path: 'SKILL.md', sha256: sha256Hex(cloudBody2), data: Buffer.from(cloudBody2).toString('base64') }]
const manifest2 = linkedSkillManifest(files2)
const items2 = [
{ name: 'b1', enabled: true, revision: 2, manifest_sha256: manifest2, files: 1, bytes: cloudBody2.length },
{ name: 'b2', enabled: true, revision: 2, manifest_sha256: manifest2, files: 1, bytes: cloudBody2.length },
]
function makeDrift(rootDir, folder) {
mkdirSync(join(rootDir, folder), { recursive: true })
writeFileSync(join(rootDir, folder, 'SKILL.md'), `# ${folder} local\n`)
writeFileSync(join(rootDir, folder, '.manifest.json'), JSON.stringify({
name: folder, revision: 1, manifest_sha256: 'old', files: [{ path: 'SKILL.md', sha256: 'deadbeef' }],
}))
}
makeDrift(root2, 'b1')
makeDrift(root2, 'b2')
const client2 = {
listSkills: async () => ({ ok: true, status: 200, data: { items: items2 } }),
skillBundle: async (name) => ({ ok: true, status: 200, data: { name, revision: 2, manifest_sha256: manifest2, files: [{ ...files2[0] }] } }),
createSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 1 } } }),
updateSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 3 } } }),
}
const sync2 = new SkillSync({
client: () => client2,
settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }),
log: () => {},
})
const stats2 = await sync2.syncOnce()
check('second pass reports two drift conflicts', stats2.conflicts.length === 2, JSON.stringify(stats2.conflicts))
const batchTake = await sync2.resolveConflicts('take_cloud')
check('batch take_cloud resolves every conflict',
batchTake.resolved.length === 2 && batchTake.failed.length === 0, JSON.stringify(batchTake))
const remaining2 = await sync2.conflictDetails()
check('batch take_cloud empties the conflict list', remaining2.length === 0)
check('batch take_cloud overwrote the local files', readFileSync(join(root2, 'b1', 'SKILL.md'), 'utf8').includes('CLOUD'))
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)

View File

@ -14,14 +14,14 @@ function check(name, ok, detail) {
const source = readFileSync('./client/index.js', 'utf8')
const hardcoded = source.match(/(?:background|borderColor)\s*:\s*['"]#(?:fff(?:fff)?|000(?:000)?)['"]/gi)
const hardcoded = source.match(/(?:background|color|borderColor)\s*:\s*['"]#(?:fff(?:fff)?|000(?:000)?)['"]/gi)
check('no hard-coded pure white/black colours', hardcoded === null, hardcoded === null ? '' : hardcoded.join(','))
const neutralTokens = (source.match(/rgba\(127,127,127/gi) ?? []).length
check('theme-neutral colour tokens are used throughout', neutralTokens >= 5, `${neutralTokens} uses`)
const accentTokens = (source.match(/#3f3f46/g) ?? []).length
check('accent colour is the shared charcoal token', accentTokens >= 2, `${accentTokens} uses`)
const accentTokens = (source.match(/rgba\(37,99,235/gi) ?? []).length
check('accent colour is the shared blue token', accentTokens >= 2, `${accentTokens} uses`)
const wrapCount = (source.match(/flexWrap\s*:\s*['"]wrap['"]/g) ?? []).length
check('long rows wrap instead of scrolling sideways', wrapCount >= 4, `${wrapCount} wrapping rows`)

View File

@ -21,7 +21,7 @@ const { SettingsStore } = await import('./lib/store.js')
const { DEFAULT_SETTINGS } = await import('./lib/config.js')
// ── 1. A 0.4.1-shaped sidecar survives the upgrade ──────────────────────
const file = join(process.env.DSH_HOME, 'dsh-brain.json')
const file = join(process.env.DSH_HOME, 'cloud-memory.json')
const old = {
version: 1,
enabled: true,
@ -74,7 +74,7 @@ for (const name of readdirSync(libDir)) {
}
check('no personal domain remains in shipped lib/', leaked.length === 0, leaked.join(','))
const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8'))
check('package version is the delivery version', pkg.version === '0.9.8', pkg.version)
check('package version is the delivery version', pkg.version === '0.7.0', pkg.version)
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)

View File

@ -40,7 +40,7 @@ writeFileSync(join(DSH, 'workspace-groups.manual.json'), JSON.stringify({ assign
const { ClientRegistry } = await import('./lib/clients.js')
const registry = new ClientRegistry({
home: () => HOME,
manualPath: () => join(DSH, 'dsh-brain-workspaces.json'),
manualPath: () => join(DSH, 'cloud-memory-workspaces.json'),
dshRegistryPath: () => join(DSH, 'workspace-groups.folders.json'),
dshManualPath: () => join(DSH, 'workspace-groups.manual.json'),
})
@ -85,7 +85,7 @@ const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const store = new SettingsStore({ clientId: 't' }, join(DSH, 'c.json'))
const reporter = new Reporter({ client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }), submitSummary: async () => ({ ok: true, status: 200, data: {} }) }), settings: () => ({ enabled: true, clientId: 't' }), activityToken: () => '', summary: () => ({ enabled: false, maxChars: 1 }), summaryToken: () => '', log: () => {} })
const routes = createRoutes({ version: '0.8.0', store, reporter, client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'x' }), listSkills: async () => ({ ok: true, status: 200, data: { items: [] } }) }), clients: registry })
const routes = createRoutes({ version: '0.7.0', store, reporter, client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'x' }), listSkills: async () => ({ ok: true, status: 200, data: { items: [] } }) }), clients: registry })
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
@ -96,11 +96,11 @@ const server = http.createServer((req, res) => {
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
const invRoute = await fetch(`${origin}/dsh-brain/clients/workspace/inventory?software=dsh&workspaceId=ws-a`).then((r) => r.json())
const invRoute = await fetch(`${origin}/cloud-memory/clients/workspace/inventory?software=dsh&workspaceId=ws-a`).then((r) => r.json())
check('workspace inventory route answers', invRoute.ok === true && Array.isArray(invRoute.skills))
const toggle = await fetch(`${origin}/dsh-brain/clients/workspace/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ software: 'dsh', workspaceId: 'ws-a', folder: 'a-skill', enabled: false }) }).then((r) => r.json())
const toggle = await fetch(`${origin}/cloud-memory/clients/workspace/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ software: 'dsh', workspaceId: 'ws-a', folder: 'a-skill', enabled: false }) }).then((r) => r.json())
check('workspace toggle route applies', toggle.ok === true && toggle.enabled === false)
const cross = await fetch(`${origin}/dsh-brain/clients/workspace/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ software: 'codex', workspaceId: 'ws-a', folder: 'x', enabled: false }) })
const cross = await fetch(`${origin}/cloud-memory/clients/workspace/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ software: 'codex', workspaceId: 'ws-a', folder: 'x', enabled: false }) })
check('workspace write route rejects non-DSH with 501', cross.status === 501)
await new Promise((resolve) => server.close(resolve))