Compare commits
No commits in common. "main" and "fix/skill-sync-source-state" have entirely different histories.
main
...
fix/skill-
17
README.md
17
README.md
|
|
@ -125,20 +125,17 @@ v1 范围:支持 发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;
|
||||||
端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被
|
端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被
|
||||||
别人先改过就报冲突、不强行覆盖。
|
别人先改过就报冲突、不强行覆盖。
|
||||||
|
|
||||||
防事故的规矩:先比内容,本地与云端逐字节一致时直接补交付记录,不传
|
防事故的规矩:云端交付的技能从不回传,本地改动它只报
|
||||||
不覆盖;内容不同时按时间自动取较新的一边——云端 `updated_at` 更新就
|
`locally_modified` 冲突、原样不动;本地删除不删云端,且同版本不会
|
||||||
先备份本地再覆盖,本地文件 mtime 更新就发布新修订;只有时间相同或缺
|
被重新拉回(云端出了新版才会再下来);同名技能两边都有时互不抢占,
|
||||||
失时才报冲突(`locally_modified` / `name_collision` / `cloud_newer`),
|
报 `name_collision`。云端只接受固定布局(根目录只有 `SKILL.md`,
|
||||||
等面板里逐项确认。本地删除不删云端,且同版本不会被重新拉回(云端出
|
|
||||||
了新版才会再下来)。面板里可逐项处理,也可用「全部保留本地 / 全部采用
|
|
||||||
云端」批量处理(有二次确认,失败项会逐条汇总)。云端只接受固定布局(根目录只有 `SKILL.md`,
|
|
||||||
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
|
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
|
||||||
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
|
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
|
||||||
`unsupported_layout`,不会为了迁就而裁剪文件。
|
`unsupported_layout`,不会为了迁就而裁剪文件。
|
||||||
|
|
||||||
验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通
|
验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通
|
||||||
下行安装、上行发布与修订、按时间自动上行/下行、内容一致自动认领、
|
下行安装、上行发布与修订、改云端技能报冲突、同名冲突、脚本待审、
|
||||||
同名同时间保留冲突、脚本待审、布局拒绝、删除不传播全流程)。
|
布局拒绝、删除不传播全流程)。
|
||||||
|
|
||||||
## 技能管理(内置)
|
## 技能管理(内置)
|
||||||
|
|
||||||
|
|
@ -222,7 +219,7 @@ pnpm publish --access public --no-git-checks
|
||||||
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
|
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
|
||||||
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。
|
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。
|
||||||
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
|
- **更新/回退(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 导入、配置编辑、作用域与治理策略。
|
- **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`)。
|
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。
|
||||||
|
|
|
||||||
1055
client/index.js
1055
client/index.js
File diff suppressed because it is too large
Load Diff
|
|
@ -74,7 +74,7 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
|
||||||
- 技能市场:无经验证来源,`features.skillsMarketplace=false`。
|
- 技能市场:无经验证来源,`features.skillsMarketplace=false`。
|
||||||
- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。
|
- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。
|
||||||
- 自动更新与版本回退:未实现(无来源清单与制品基线)。
|
- 自动更新与版本回退:未实现(无来源清单与制品基线)。
|
||||||
- MCP 市场的内嵌浏览与安装:**0.9.6 起从卡片移除**(宿主 `catalog` 返回 405,只留错误条没有意义),目录浏览回到宿主插件市场。
|
- MCP 市场的内嵌浏览与安装:未实现,只给宿主面板位置。
|
||||||
- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。
|
- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。
|
||||||
- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。
|
- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。
|
||||||
|
|
||||||
|
|
@ -165,24 +165,23 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
|
||||||
|
|
||||||
### 6.3 同步冲突交互
|
### 6.3 同步冲突交互
|
||||||
|
|
||||||
`SkillSync` 先自动处置:内容一致直接认领,内容不同按「本地文件 mtime vs 云端 `updated_at`」自动采用较新的一边(下行覆盖前备份到 `$DSH_HOME/.dsh-brain-backups/sync/`);只有时间相同/缺失、或本地布局无法上传时才留下冲突,并暴露两侧信息允许人工处置:
|
`SkillSync` 仍然只按原策略暂停冲突项,但会暴露两侧信息并允许人工处置:
|
||||||
|
|
||||||
| 方法 | 路径 | 说明 |
|
| 方法 | 路径 | 说明 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
|
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
|
||||||
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
|
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
|
||||||
| POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` |
|
| 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`。
|
- `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`:只返回两侧信息,不改任何文件。
|
- `manual`:只返回两侧信息,不改任何文件。
|
||||||
|
|
||||||
### 6.4 验证
|
### 6.4 验证
|
||||||
|
|
||||||
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
|
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
|
||||||
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
|
- `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)
|
## 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` 批量导入 |
|
| 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 |
|
||||||
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
|
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
|
||||||
| 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 |
|
| 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 |
|
||||||
|
|
@ -237,7 +236,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
|
||||||
| `skills/install/plan` `install/commit` | `sync_running` |
|
| `skills/install/plan` `install/commit` | `sync_running` |
|
||||||
| `skills/toggle` `skills/remove` | `sync_running` |
|
| `skills/toggle` `skills/remove` | `sync_running` |
|
||||||
| `skills/update/apply` `skills/rollback` | `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 + 同步结束后放行)。
|
HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ export const name = 'dsh-brain';
|
||||||
/** Services required before `apply` runs. */
|
/** Services required before `apply` runs. */
|
||||||
export const inject = ['webServer'];
|
export const inject = ['webServer'];
|
||||||
/** Version reported by the status card. */
|
/** Version reported by the status card. */
|
||||||
const VERSION = '0.9.10';
|
const VERSION = '0.9.0';
|
||||||
/** How often the skill directory is reconciled with the cloud center. */
|
/** How often the skill directory is reconciled with the cloud center. */
|
||||||
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
|
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
|
||||||
/** How often queued reports are retried. */
|
/** How often queued reports are retried. */
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ import { descriptor } from "./descriptor.js";
|
||||||
import { LongMemoryProvider } from "./driver.js";
|
import { LongMemoryProvider } from "./driver.js";
|
||||||
export { LongMemoryProvider, descriptor };
|
export { LongMemoryProvider, descriptor };
|
||||||
/** Keep in sync with the package version (asserted by the verify script). */
|
/** Keep in sync with the package version (asserted by the verify script). */
|
||||||
const PROVIDER_VERSION = '0.9.8';
|
const PROVIDER_VERSION = '0.9.0';
|
||||||
export const definition = defineMemorySpaceProviderDefinition({
|
export const definition = defineMemorySpaceProviderDefinition({
|
||||||
manifest: {
|
manifest: {
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||||
|
|
|
||||||
|
|
@ -749,7 +749,6 @@ async function serveMarket(deps, req, res) {
|
||||||
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
|
* `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/run` trigger one pass now
|
||||||
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
|
* `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
|
|
||||||
*/
|
*/
|
||||||
async function serveSync(deps, req, res) {
|
async function serveSync(deps, req, res) {
|
||||||
const sync = deps.sync;
|
const sync = deps.sync;
|
||||||
|
|
@ -789,18 +788,6 @@ async function serveSync(deps, req, res) {
|
||||||
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
|
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
|
||||||
return;
|
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');
|
fail(res, 404, 'unknown-sync-route');
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
|
|
|
||||||
|
|
@ -15,14 +15,12 @@
|
||||||
* revisions, guarded by the center's `expected_revision` check.
|
* revisions, guarded by the center's `expected_revision` check.
|
||||||
*
|
*
|
||||||
* Safety rules (deliberate, in order):
|
* Safety rules (deliberate, in order):
|
||||||
* 1. A cloud-delivered skill is never re-uploaded unless its local copy is
|
* 1. A cloud-delivered skill is never re-uploaded. If its local files no
|
||||||
* newer than the center's `updated_at`; before any cloud overwrite the
|
* longer match the delivery manifest, the skill is flagged as a
|
||||||
* local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
|
* conflict and left completely alone.
|
||||||
* 2. A local deletion never deletes the cloud copy.
|
* 2. A local deletion never deletes the cloud copy.
|
||||||
* 3. A same-name skill is never hijacked silently: byte-identical copies are
|
* 3. A name that already exists on the other side is never hijacked;
|
||||||
* adopted in place, otherwise the newer side (local file mtime vs center
|
* it is reported as a conflict for a human to resolve.
|
||||||
* `updated_at`) wins; only equal or missing timestamps are reported as a
|
|
||||||
* conflict for a human to resolve.
|
|
||||||
* 4. Bundles whose scripts changed on the cloud side are not installed
|
* 4. Bundles whose scripts changed on the cloud side are not installed
|
||||||
* until the change is acknowledged in the dashboard, mirroring the
|
* until the change is acknowledged in the dashboard, mirroring the
|
||||||
* center's own review flag.
|
* center's own review flag.
|
||||||
|
|
@ -61,24 +59,6 @@ export function linkedSkillManifest(files) {
|
||||||
const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort();
|
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'));
|
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. */
|
/** True when the cloud center would accept this relative file path. */
|
||||||
export function isCloudSkillPath(rel) {
|
export function isCloudSkillPath(rel) {
|
||||||
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//'))
|
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//'))
|
||||||
|
|
@ -217,10 +197,7 @@ export class SkillSync {
|
||||||
await walk(rel);
|
await walk(rel);
|
||||||
}
|
}
|
||||||
else if (entry.isFile()) {
|
else if (entry.isFile()) {
|
||||||
const absolute = join(dir, rel);
|
out.push({ rel, buffer: await readFile(join(dir, rel)) });
|
||||||
const buffer = await readFile(absolute);
|
|
||||||
const info = await stat(absolute);
|
|
||||||
out.push({ rel, buffer, mtimeMs: info.mtimeMs });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
@ -286,145 +263,6 @@ export class SkillSync {
|
||||||
}
|
}
|
||||||
return undefined;
|
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. */
|
/** One full pass; never throws — outcomes land in the stats. */
|
||||||
async syncOnce() {
|
async syncOnce() {
|
||||||
if (this.running)
|
if (this.running)
|
||||||
|
|
@ -528,11 +366,6 @@ export class SkillSync {
|
||||||
if (exists && delivery !== undefined) {
|
if (exists && delivery !== undefined) {
|
||||||
// Delivered before: local integrity is judged before any download.
|
// Delivered before: local integrity is judged before any download.
|
||||||
if (!(await this.deliveredIntact(home, delivery))) {
|
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');
|
this.conflict(stats, item.name, 'locally_modified');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -547,14 +380,6 @@ export class SkillSync {
|
||||||
// Intact but the cloud moved on: fall through and install the update.
|
// Intact but the cloud moved on: fall through and install the update.
|
||||||
}
|
}
|
||||||
if (exists && delivery === undefined) {
|
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');
|
this.conflict(stats, item.name, 'name_collision');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -582,10 +407,6 @@ export class SkillSync {
|
||||||
(exists ? stats.updated : stats.downloaded).push(item.name);
|
(exists ? stats.updated : stats.downloaded).push(item.name);
|
||||||
}
|
}
|
||||||
// ---- UP: local originals -> cloud center ---------------------------
|
// ---- 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 folders = await readdir(root, { withFileTypes: true }).catch(() => []);
|
||||||
const seenFolders = new Set();
|
const seenFolders = new Set();
|
||||||
for (const entry of folders) {
|
for (const entry of folders) {
|
||||||
|
|
@ -599,37 +420,12 @@ export class SkillSync {
|
||||||
if (skill === undefined)
|
if (skill === undefined)
|
||||||
continue;
|
continue;
|
||||||
if (typeof skill === 'string') {
|
if (typeof skill === 'string') {
|
||||||
if (!knownConflicts.has(entry.name))
|
this.conflict(stats, entry.name, skill);
|
||||||
this.conflict(stats, entry.name, skill);
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const record = state.uploaded[skill.name];
|
const record = state.uploaded[skill.name];
|
||||||
const cloud = cloudByName.get(skill.name);
|
const cloud = cloudByName.get(skill.name);
|
||||||
if (cloud !== undefined && record === undefined) {
|
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');
|
this.conflict(stats, skill.name, 'name_collision');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -668,33 +464,7 @@ export class SkillSync {
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
|
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
|
||||||
// The center moved on since the last upload. Identical bytes just
|
this.conflict(stats, skill.name, 'cloud_newer');
|
||||||
// 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');
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const updated = await client.updateSkill(skill.name, {
|
const updated = await client.updateSkill(skill.name, {
|
||||||
|
|
@ -807,31 +577,6 @@ export class SkillSync {
|
||||||
dropConflict(name) {
|
dropConflict(name) {
|
||||||
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== 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.
|
* Both sides of every conflict from the last pass, so a human can decide.
|
||||||
* Read-only: it never changes a file or uploads anything.
|
* Read-only: it never changes a file or uploads anything.
|
||||||
|
|
@ -896,7 +641,7 @@ export class SkillSync {
|
||||||
},
|
},
|
||||||
canKeepLocal: location !== 'none',
|
canKeepLocal: location !== 'none',
|
||||||
canTakeCloud: cloudItem !== undefined,
|
canTakeCloud: cloudItem !== undefined,
|
||||||
note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
|
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "dsh-brain",
|
"name": "dsh-brain",
|
||||||
"version": "0.9.10",
|
"version": "0.9.1",
|
||||||
"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.",
|
"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",
|
"type": "module",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|
|
||||||
|
|
@ -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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
||||||
}
|
|
||||||
|
|
||||||
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(', '))
|
|
||||||
344
preview-mcp.mjs
344
preview-mcp.mjs
|
|
@ -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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
||||||
}
|
|
||||||
|
|
||||||
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}`)
|
|
||||||
}
|
|
||||||
|
|
@ -118,10 +118,6 @@ export interface SkillSummary {
|
||||||
files?: number
|
files?: number
|
||||||
bytes?: number
|
bytes?: number
|
||||||
script_changed?: boolean
|
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
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,7 @@ export const name = 'dsh-brain'
|
||||||
export const inject = ['webServer']
|
export const inject = ['webServer']
|
||||||
|
|
||||||
/** Version reported by the status card. */
|
/** Version reported by the status card. */
|
||||||
const VERSION = '0.9.10'
|
const VERSION = '0.9.0'
|
||||||
|
|
||||||
/** How often the skill directory is reconciled with the cloud center. */
|
/** How often the skill directory is reconciled with the cloud center. */
|
||||||
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000
|
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ import { LongMemoryProvider } from './driver.ts'
|
||||||
export { LongMemoryProvider, descriptor }
|
export { LongMemoryProvider, descriptor }
|
||||||
|
|
||||||
/** Keep in sync with the package version (asserted by the verify script). */
|
/** Keep in sync with the package version (asserted by the verify script). */
|
||||||
const PROVIDER_VERSION = '0.9.8'
|
const PROVIDER_VERSION = '0.9.0'
|
||||||
|
|
||||||
export const definition = defineMemorySpaceProviderDefinition({
|
export const definition = defineMemorySpaceProviderDefinition({
|
||||||
manifest: {
|
manifest: {
|
||||||
|
|
|
||||||
|
|
@ -838,7 +838,6 @@ async function serveMarket(deps: RouteDeps, req: IncomingMessage, res: ServerRes
|
||||||
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
|
* `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/run` trigger one pass now
|
||||||
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
|
* `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
|
|
||||||
*/
|
*/
|
||||||
async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||||
const sync = deps.sync
|
const sync = deps.sync
|
||||||
|
|
@ -868,14 +867,6 @@ async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerRespo
|
||||||
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() })
|
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() })
|
||||||
return
|
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')
|
fail(res, 404, 'unknown-sync-route')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(error)
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
|
|
||||||
|
|
@ -15,14 +15,12 @@
|
||||||
* revisions, guarded by the center's `expected_revision` check.
|
* revisions, guarded by the center's `expected_revision` check.
|
||||||
*
|
*
|
||||||
* Safety rules (deliberate, in order):
|
* Safety rules (deliberate, in order):
|
||||||
* 1. A cloud-delivered skill is never re-uploaded unless its local copy is
|
* 1. A cloud-delivered skill is never re-uploaded. If its local files no
|
||||||
* newer than the center's `updated_at`; before any cloud overwrite the
|
* longer match the delivery manifest, the skill is flagged as a
|
||||||
* local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
|
* conflict and left completely alone.
|
||||||
* 2. A local deletion never deletes the cloud copy.
|
* 2. A local deletion never deletes the cloud copy.
|
||||||
* 3. A same-name skill is never hijacked silently: byte-identical copies are
|
* 3. A name that already exists on the other side is never hijacked;
|
||||||
* adopted in place, otherwise the newer side (local file mtime vs center
|
* it is reported as a conflict for a human to resolve.
|
||||||
* `updated_at`) wins; only equal or missing timestamps are reported as a
|
|
||||||
* conflict for a human to resolve.
|
|
||||||
* 4. Bundles whose scripts changed on the cloud side are not installed
|
* 4. Bundles whose scripts changed on the cloud side are not installed
|
||||||
* until the change is acknowledged in the dashboard, mirroring the
|
* until the change is acknowledged in the dashboard, mirroring the
|
||||||
* center's own review flag.
|
* center's own review flag.
|
||||||
|
|
@ -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'))
|
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. */
|
/** True when the cloud center would accept this relative file path. */
|
||||||
export function isCloudSkillPath(rel: string): boolean {
|
export function isCloudSkillPath(rel: string): boolean {
|
||||||
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) return false
|
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) return false
|
||||||
|
|
@ -169,8 +150,6 @@ interface SyncState {
|
||||||
interface LocalFile {
|
interface LocalFile {
|
||||||
rel: string
|
rel: string
|
||||||
buffer: Buffer
|
buffer: Buffer
|
||||||
/** Last-modified time; the automatic newer-side winner is chosen from these. */
|
|
||||||
mtimeMs: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Dependencies of one sync engine instance. */
|
/** Dependencies of one sync engine instance. */
|
||||||
|
|
@ -194,14 +173,6 @@ interface DeliveryManifest {
|
||||||
files?: { path: string; sha256: string }[]
|
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 {
|
export class SkillSync {
|
||||||
private running = false
|
private running = false
|
||||||
private current: SkillSyncStats = {
|
private current: SkillSyncStats = {
|
||||||
|
|
@ -291,10 +262,7 @@ export class SkillSync {
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
await walk(rel)
|
await walk(rel)
|
||||||
} else if (entry.isFile()) {
|
} else if (entry.isFile()) {
|
||||||
const absolute = join(dir, rel)
|
out.push({ rel, buffer: await readFile(join(dir, rel)) })
|
||||||
const buffer = await readFile(absolute)
|
|
||||||
const info = await stat(absolute)
|
|
||||||
out.push({ rel, buffer, mtimeMs: info.mtimeMs })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -359,175 +327,6 @@ export class SkillSync {
|
||||||
return undefined
|
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. */
|
/** One full pass; never throws — outcomes land in the stats. */
|
||||||
async syncOnce(): Promise<SkillSyncStats> {
|
async syncOnce(): Promise<SkillSyncStats> {
|
||||||
if (this.running) return this.current
|
if (this.running) return this.current
|
||||||
|
|
@ -621,11 +420,6 @@ export class SkillSync {
|
||||||
if (exists && delivery !== undefined) {
|
if (exists && delivery !== undefined) {
|
||||||
// Delivered before: local integrity is judged before any download.
|
// Delivered before: local integrity is judged before any download.
|
||||||
if (!(await this.deliveredIntact(home, delivery))) {
|
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')
|
this.conflict(stats, item.name, 'locally_modified')
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
@ -640,14 +434,6 @@ export class SkillSync {
|
||||||
// Intact but the cloud moved on: fall through and install the update.
|
// Intact but the cloud moved on: fall through and install the update.
|
||||||
}
|
}
|
||||||
if (exists && delivery === undefined) {
|
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')
|
this.conflict(stats, item.name, 'name_collision')
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
@ -676,10 +462,6 @@ export class SkillSync {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- UP: local originals -> cloud center ---------------------------
|
// ---- 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 folders = await readdir(root, { withFileTypes: true }).catch(() => [])
|
||||||
const seenFolders = new Set<string>()
|
const seenFolders = new Set<string>()
|
||||||
for (const entry of folders) {
|
for (const entry of folders) {
|
||||||
|
|
@ -690,35 +472,12 @@ export class SkillSync {
|
||||||
const skill = await this.readLocalSkill(dir, entry.name)
|
const skill = await this.readLocalSkill(dir, entry.name)
|
||||||
if (skill === undefined) continue
|
if (skill === undefined) continue
|
||||||
if (typeof skill === 'string') {
|
if (typeof skill === 'string') {
|
||||||
if (!knownConflicts.has(entry.name)) this.conflict(stats, entry.name, skill)
|
this.conflict(stats, entry.name, skill)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
const record = state.uploaded[skill.name]
|
const record = state.uploaded[skill.name]
|
||||||
const cloud = cloudByName.get(skill.name)
|
const cloud = cloudByName.get(skill.name)
|
||||||
if (cloud !== undefined && record === undefined) {
|
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')
|
this.conflict(stats, skill.name, 'name_collision')
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
@ -753,32 +512,7 @@ export class SkillSync {
|
||||||
stats.uploaded.push(skill.name)
|
stats.uploaded.push(skill.name)
|
||||||
} else {
|
} else {
|
||||||
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
|
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
|
||||||
// The center moved on since the last upload. Identical bytes just
|
this.conflict(stats, skill.name, 'cloud_newer')
|
||||||
// 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')
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
const updated = await client.updateSkill(skill.name, {
|
const updated = await client.updateSkill(skill.name, {
|
||||||
|
|
@ -892,29 +626,6 @@ export class SkillSync {
|
||||||
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== 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: 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.
|
* Both sides of every conflict from the last pass, so a human can decide.
|
||||||
* Read-only: it never changes a file or uploads anything.
|
* Read-only: it never changes a file or uploads anything.
|
||||||
|
|
@ -972,7 +683,7 @@ export class SkillSync {
|
||||||
},
|
},
|
||||||
canKeepLocal: location !== 'none',
|
canKeepLocal: location !== 'none',
|
||||||
canTakeCloud: cloudItem !== undefined,
|
canTakeCloud: cloudItem !== undefined,
|
||||||
note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
|
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
|
|
@ -1101,10 +812,3 @@ export interface SyncResolveResult {
|
||||||
backup?: string
|
backup?: string
|
||||||
note: 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 }[]
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -475,28 +475,8 @@ check('the tree is DSH-only: no source card, no foreign sources',
|
||||||
!skillsText.includes('C:/Users/test/.dsh/skills') && !skillsText.includes('由 Codex 自行加载'))
|
!skillsText.includes('C:/Users/test/.dsh/skills') && !skillsText.includes('由 Codex 自行加载'))
|
||||||
check('categories render with their counts', skillsText.includes('QQ-Skill') && skillsText.includes('1 项 · 1/1 启用') && skillsText.includes('未分类'))
|
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('the metadata-only promise is on screen', skillsText.includes('分类只记在这个来源里,不移动文件'))
|
||||||
check('foreign sources start collapsed behind the import button',
|
check('foreign sources appear only as import candidates',
|
||||||
!skillsText.includes('Codex') && !skillsText.includes('仅本卡'))
|
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'))
|
|
||||||
|
|
||||||
// Categories start collapsed; expanding one must reveal its skills.
|
// Categories start collapsed; expanding one must reveal its skills.
|
||||||
const expandedSkills = await drive('skills', true, '展开或收起 未分类')
|
const expandedSkills = await drive('skills', true, '展开或收起 未分类')
|
||||||
|
|
@ -510,26 +490,9 @@ check('no render boundary error on the skills tab', !skillsText.includes('渲染
|
||||||
|
|
||||||
const mcpText = await drive('mcp', true)
|
const mcpText = await drive('mcp', true)
|
||||||
check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp'))
|
check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp'))
|
||||||
check('collapsed rows keep only name, state and transport',
|
check('MCP state, transport and auth are shown', mcpText.includes('已连接') && mcpText.includes('http') && mcpText.includes('bearer'))
|
||||||
mcpText.includes('已连接') && mcpText.includes('http') && !mcpText.includes('bearer'))
|
check('MCP actions are offered', mcpText.includes('健康检查') && mcpText.includes('工具列表') && mcpText.includes('移除连接'))
|
||||||
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('the injected tools cache starts empty', 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)
|
const missing = await drive('mcp', false)
|
||||||
check('a missing bridge becomes a stated capability gap', missing.includes('MCP 管理当前不可用') && missing.includes('MCP 服务器配置'))
|
check('a missing bridge becomes a stated capability gap', missing.includes('MCP 管理当前不可用') && missing.includes('MCP 服务器配置'))
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,7 @@ async function post(path, body) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const caps = await get('/dsh-brain/capabilities')
|
const caps = await get('/dsh-brain/capabilities')
|
||||||
check('capabilities answers with 0.9.8', caps.body?.version === '0.9.8', String(caps.body?.version))
|
check('capabilities answers with 0.8.0', caps.body?.version === '0.9.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 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('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 === 'ready')
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
// bundles, linked manifest) — no DSH host, no real service, no real token.
|
// bundles, linked manifest) — no DSH host, no real service, no real token.
|
||||||
import http from 'node:http'
|
import http from 'node:http'
|
||||||
import { createHash } from 'node:crypto'
|
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 { tmpdir } from 'node:os'
|
||||||
import { join } from 'node:path'
|
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') }
|
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) {
|
function summaryOf(skill) {
|
||||||
return {
|
return {
|
||||||
name: skill.name, description: skill.description, execution_mode: skill.execution_mode,
|
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,
|
enabled: true, revision: skill.revision, manifest_sha256: linked(skill.files), files: skill.files.length,
|
||||||
script_changed: skill.script_changed,
|
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 = {}) {
|
function seed(name, files, extra = {}) {
|
||||||
const stored = storeFiles(files)
|
const stored = storeFiles(files)
|
||||||
center.set(name, {
|
center.set(name, { name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored, script_changed: false, ...extra })
|
||||||
name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored,
|
|
||||||
script_changed: false, created_at: CLOUD_OLD, updated_at: CLOUD_OLD, ...extra,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
seed('cloud-one', [
|
seed('cloud-one', [
|
||||||
{ path: 'SKILL.md', content: '# cloud-one\n\n云端技能一。' },
|
{ path: 'SKILL.md', content: '# cloud-one\n\n云端技能一。' },
|
||||||
|
|
@ -81,11 +73,7 @@ const server = http.createServer((req, res) => {
|
||||||
const body = await readBody()
|
const body = await readBody()
|
||||||
if (body.expected_revision !== 0) return send(400, { error: 'invalid_input', message: '必须提供 expected_revision' })
|
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: '同名技能已存在' })
|
if (center.has(body.name)) return send(409, { error: 'skill_exists', message: '同名技能已存在' })
|
||||||
const skill = {
|
const skill = { name: body.name, description: body.description, execution_mode: body.execution_mode ?? 'prompt-only', revision: 1, files: storeFiles(body.files ?? []), script_changed: false }
|
||||||
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(),
|
|
||||||
}
|
|
||||||
center.set(skill.name, skill)
|
center.set(skill.name, skill)
|
||||||
return send(201, { skill: summaryOf(skill), revision: 1, manifest_sha256: linked(skill.files) })
|
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.files) skill.files = storeFiles(body.files)
|
||||||
if (body.description !== undefined) skill.description = body.description
|
if (body.description !== undefined) skill.description = body.description
|
||||||
skill.revision += 1
|
skill.revision += 1
|
||||||
skill.updated_at = Date.now()
|
|
||||||
return send(200, { skill: summaryOf(skill), revision: skill.revision, manifest_sha256: linked(skill.files) })
|
return send(200, { skill: summaryOf(skill), revision: skill.revision, manifest_sha256: linked(skill.files) })
|
||||||
}
|
}
|
||||||
return send(404, { error: 'unknown_route', path })
|
return send(404, { error: 'unknown_route', path })
|
||||||
|
|
@ -119,12 +106,11 @@ const engine = new SkillSync({
|
||||||
})
|
})
|
||||||
const root = join(process.env.DSH_HOME, 'skills')
|
const root = join(process.env.DSH_HOME, 'skills')
|
||||||
const skillDir = (name) => join(root, name)
|
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)) {
|
for (const [rel, content] of Object.entries(files)) {
|
||||||
const target = join(skillDir(name), ...rel.split('/'))
|
const target = join(skillDir(name), ...rel.split('/'))
|
||||||
mkdirSync(join(target, '..'), { recursive: true })
|
mkdirSync(join(target, '..'), { recursive: true })
|
||||||
writeFileSync(target, content)
|
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()
|
stats = await engine.syncOnce()
|
||||||
check('edited local skill updates the center', stats.updated.includes('local-one') && center.get('local-one')?.revision === 2)
|
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.
|
// 4. A locally modified cloud skill is flagged, never overwritten or uploaded.
|
||||||
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' }, Date.now())
|
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' })
|
||||||
stats = await engine.syncOnce()
|
stats = await engine.syncOnce()
|
||||||
check('local edit newer than cloud auto-uploads',
|
check('local edit of a cloud skill becomes a conflict',
|
||||||
stats.updated.includes('cloud-one') && center.get('cloud-one')?.revision === 2, JSON.stringify(stats.conflicts))
|
stats.conflicts.some((c) => c.name === 'cloud-one' && c.reason === 'locally_modified'), JSON.stringify(stats.conflicts))
|
||||||
check('the newer local edit stays on disk',
|
check('the local edit is left untouched',
|
||||||
readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('我改了云端技能'))
|
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.
|
// 5. A name collision on both sides is flagged, both copies untouched.
|
||||||
{
|
seed('clash', [{ path: 'SKILL.md', content: '# clash cloud' }])
|
||||||
const cloud = center.get('cloud-one')
|
writeLocal('clash', { 'SKILL.md': '# clash local\n' })
|
||||||
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)
|
|
||||||
stats = await engine.syncOnce()
|
stats = await engine.syncOnce()
|
||||||
check('identical collision auto-adopts without a conflict',
|
check('name collision is flagged', stats.conflicts.some((c) => c.name === 'clash' && c.reason === 'name_collision'))
|
||||||
!stats.conflicts.some((c) => c.name === 'clash-same') && existsSync(join(skillDir('clash-same'), '.manifest.json')))
|
check('collision leaves local files alone', readFileSync(join(skillDir('clash'), 'SKILL.md'), 'utf8').includes('clash local'))
|
||||||
check('identical collision uploads nothing', center.get('clash-same')?.revision === 1)
|
check('collision leaves the center alone', center.get('clash')?.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))
|
|
||||||
|
|
||||||
// 6. Script-changed cloud bundles wait for review.
|
// 6. Script-changed cloud bundles wait for review.
|
||||||
check('script-changed bundle is not installed',
|
check('script-changed bundle is not installed',
|
||||||
|
|
|
||||||
|
|
@ -98,59 +98,6 @@ check('keep_local refuses a stale cloud revision', stale)
|
||||||
const remaining = await sync.conflictDetails()
|
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)
|
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
|
const passed = results.filter((r) => r.ok).length
|
||||||
console.log(`\n${passed}/${results.length} passed`)
|
console.log(`\n${passed}/${results.length} passed`)
|
||||||
process.exit(passed === results.length ? 0 : 1)
|
process.exit(passed === results.length ? 0 : 1)
|
||||||
|
|
|
||||||
|
|
@ -74,7 +74,7 @@ for (const name of readdirSync(libDir)) {
|
||||||
}
|
}
|
||||||
check('no personal domain remains in shipped lib/', leaked.length === 0, leaked.join(','))
|
check('no personal domain remains in shipped lib/', leaked.length === 0, leaked.join(','))
|
||||||
const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8'))
|
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.9.0', pkg.version)
|
||||||
|
|
||||||
const passed = results.filter((r) => r.ok).length
|
const passed = results.filter((r) => r.ok).length
|
||||||
console.log(`\n${passed}/${results.length} passed`)
|
console.log(`\n${passed}/${results.length} passed`)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue