dsh-paoding 0.4.5 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,12 +19,13 @@ dsh-paoding(中文品牌「庖丁」,典出《庄子》——庖丁顺纹理
19
19
  - **按工作区各有各的班底**:不同项目可以配不同的主/子 agent——「庖丁配置」里选定工作区单独配置,每个工作区生成自己的预设(`orchestrator-<目录名>`),新建会话时选对应预设即可,全局默认不受影响。
20
20
  - **图形界面配置**:不习惯改配置文件的话,点开左侧栏底部动作条(设置行上方)的「庖丁配置」入口,整页点选即可,「保存并应用」即时重生成预设——与首装自动化同一条生成管线。
21
21
  - **工具条目支持通配符**:`*` 与 `?` 在生成期展开成具体工具名——`mcp__tavily__tavily_*` 一行顶五行,MCP 工具族不必逐个点名;零匹配有提醒,产物与运行时行为不变。
22
- - **保存前先体检**:预览/应用时自动过一遍检查——配置了但未挂载的工具、零工具角色、查无此名的模型、预设落后于配置,分级提示一目了然;CLI 侧 `dsh-paoding doctor` 六项只读自检(配置可解析、安装轨道、声明行托管块、孤儿目录、版本标记、预设漂移),一条命令查全身。
22
+ - **保存前先体检**:预览/应用时自动过一遍检查——配置了但未挂载的工具、零工具角色、查无此名的模型、预设落后于配置,分级提示一目了然;预览还顺带列出「本次变更」逐项明细与主 agent 工具面瘦身统计,改了什么、省了多少都在明面上。CLI 侧 `dsh-paoding doctor` 六项只读自检(配置可解析、安装轨道、声明行托管块、孤儿目录、版本标记、预设漂移),一条命令查全身;`--fix` 自动修孤儿目录与过期声明行两类安全项。
23
23
  - **场景模板一键换班底**:轻量(只留实现)、调研(只留检索)、全开(全员到齐、主 agent 带满检测库存)三档点一下就切,只动「谁在场 + 主 agent 额外带什么」,精调过的角色配置分毫不动。
24
- - **配置可导出可导入**:面板「更多」菜单一键下载 `dsh-paoding.config.yml`,换机迁移、备份整份拷走;导入先验格式,覆盖整体配置(含工作区段)需二次确认。
24
+ - **配置可导出可导入,还有后悔药**:面板「更多」菜单一键下载 `dsh-paoding.config.yml`,换机迁移、备份整份拷走;导入先验格式,覆盖整体配置(含工作区段)需二次确认。每次写盘前自动轮换备份三份,「恢复备份」二次确认即回退,误操作不用翻文件。
25
25
  - **HTTP 接口直连配置**:预设的列举、新增、更新、删除走 `/api/paoding/presets` 四条接口,随 DSH Web 服务同进程挂载、本机回环直调;与面板「保存并应用」同一条生成管线、同一把写盘互斥闸——脚本和自动化工具改班底,不必开浏览器。
26
26
  - **面板中英双语**:界面文案 zh/en 全覆盖,语言自动识别(显式选择 → 中文信号优先:浏览器语言、宿主页面语言、中文时区),「更多」菜单一键切换并记住。
27
27
  - **版本更新有提醒,面板一键升级**:面板会对比 npm registry(npmmirror 镜像、GitHub release 依次兜底)上的最新版本,发现新版就地提示并附上发布页链接;点「升级」就地换上新版(profile 自动探测:普通 profile 走 `dsh plugin update dsh-paoding`;desktop profile 被 dsh CLI 的 Electron 专属守卫挡住,改在 profile 目录直跑 `pnpm add dsh-paoding@<版本>`,pnpm 找不到时自动回落 `corepack pnpm`),重启 DSH 后生效,编排预设会在重启时按新版自动重生成。开发检出的 link 形态无法就地升级,面板会提示切回 registry 版的办法;检测失败时页头留一行「版本检测失败 · 重试」(完整原因与代理排查提示在悬浮提示里),不弹窗打扰。
28
+ - **委派效果可量化**:面板「委派效果」卡按角色统计调用数、平均耗时与失败数(近 30 天),数据读宿主会话存档本地聚合——哪个角色用得多、哪个常掉链子,一眼可见。
28
29
  - **来去自由**:不改 DSH 一行源码;装完新会话即用,卸载即删目录。
29
30
  - **两代宿主都兼容**:DSH 0.1.5 – 0.2.1 全支持(0.1.5 / 0.1.6 / 0.1.7-rc.1 / 0.1.7-rc.2 / 0.2.0-rc.1 / 0.2.0-rc.2 / 0.2.1-rc.2+)——两代宿主发现预设的机制不同(目录扫描 vs patch 声明行),安装器自动检测宿主版本选对落点;编排组合里的 workflow worker 行也按宿主版本自动适配(0.1.5 用 workflow-worker-thread,0.1.6+ 换 workflow-ptc——旧包 0.1.6 起已删除,残留行正是 0.2.0 面板上「加载失败」的元凶);DSH 0.2.1 起角色委派行同步换代(0.2.1 的 dsh-tool-subagent 拒绝内联 persona/toolFilter——人设与工具面改挂各角色的 AgentPreset,spawn 子代理按 agentPreset 选择子预设;0.2.0 及以下保持内联形状),宿主升级、降级后的首次保存/自愈自动迁移(工作区专属预设 orchestrator-<slug> 随同轮自愈一并换代),全程无感;0.2.1 的 prerelease 再细分——tool-subagent 守卫自 0.2.1-rc.2 落地,rc.0/rc.1 仍按内联形状生成。
30
31
 
@@ -95,9 +96,9 @@ curl http://127.0.0.1:19387/api/paoding/presets
95
96
  | 文档 | 内容 |
96
97
  |---|---|
97
98
  | [架构](docs/architecture.md) | 为什么这样设计——概述、成本账、角色与工具、对应 DSH 原生机制、Token 治理、已知边界。 |
98
- | [安装](docs/installation.md) | 官方插件通道一条命令安装、版本支持与预设落点双轨(DSH 0.1.5 – 0.2.1)、首装自动化与版本标记、升级、开发检出自装、host patch 检测机制、庖丁配置面板、卸载、排查。 |
99
+ | [安装](docs/installation.md) | 官方插件通道一条命令安装、版本支持与预设落点双轨(DSH 0.1.5 – 0.2.1)、首装自动化与版本标记、升级、开发检出自装、host patch 检测机制、庖丁配置面板、卸载(`dsh-paoding uninstall` 一条命令)、排查(doctor 可 `--fix`)。 |
99
100
  | [编排](docs/orchestration.md) | 编排总览、失败如何呈现与三层处理、one-shot vs continuable、上下文隔离。 |
100
- | [配置](docs/configuration.md) | 配置键全参考、工具条目通配符、内置角色微调、主 agent 工具与技能、自定义角色、按角色分模型、角色会话与启动方式、场景模板、配置导出导入、检查提示、HTTP 接口。 |
101
+ | [配置](docs/configuration.md) | 配置键全参考、工具条目通配符、内置角色微调、主 agent 工具与技能、自定义角色、按角色分模型、角色会话与启动方式、场景模板、配置导出导入与备份回滚、检查提示、HTTP 接口。 |
101
102
 
102
103
  ## 贡献
103
104
 
package/README_en.md CHANGED
@@ -19,9 +19,10 @@ dsh-paoding (Chinese brand 「庖丁」/ Pao Ding, from the Zhuangzi parable of
19
19
  - **A different lineup per workspace**: each project can carry its own main/sub-agent setup — pick the workspace in 庖丁配置, configure it separately, and it gets its own preset (`orchestrator-<basename>`); choose that preset when starting a session. The global default stays untouched.
20
20
  - **A visual configurator**: prefer clicking to editing YAML? the 庖丁配置 (Paoding Config) entry in the sidebar bottom action bar (above the Settings row) covers everything; Save & Apply regenerates the preset on the spot — the same generation pipeline as first-install automation.
21
21
  - **Tool entries support wildcards**: `*` and `?` expand into concrete tool names at generation time — one `mcp__tavily__tavily_*` line covers the whole family; zero-match patterns get a warning, and artifacts and runtime behavior stay unchanged.
22
- - **A health check before every save**: preview/apply runs a built-in check — tools configured but not mounted, zero-tool roles, unknown model names, a preset lagging behind the config — each flagged by severity; on the CLI side, `dsh-paoding doctor` runs six read-only checks (config parses, install track, managed declaration block, orphan directories, version marker, preset drift) in one command.
22
+ - **A health check before every save**: preview/apply runs a built-in check — tools configured but not mounted, zero-tool roles, unknown model names, a preset lagging behind the config — each flagged by severity; the preview also lists an itemized "changes since the last save" diff and the main-agent tool-surface stat, so what changed and what it saves are both on the table. On the CLI side, `dsh-paoding doctor` runs six read-only checks (config parses, install track, managed declaration block, orphan directories, version marker, preset drift) in one command; `--fix` automatically repairs the two safe categories (orphan directories, stale declaration rows).
23
23
  - **Scenario templates swap the roster in one click**: Lite (implement only), Research (search roles only), and Full (everyone on deck, main agent carrying the whole detected inventory) — templates only touch who is present and what the main agent carries; hand-tuned role settings are never touched.
24
- - **Config export & import**: download `dsh-paoding.config.yml` from the panel's More menu for migration or backup; imports are validated first, and overwriting the whole config (workspaces included) asks for confirmation.
24
+ - **Delegation stats you can act on**: the panel's "Delegation" card counts delegations, average duration, and failures per role (last 30 days), aggregated locally from the host session archive — which roles get used, and which keep dropping the ball, at a glance.
25
+ - **Config export & import, with an undo**: download `dsh-paoding.config.yml` from the panel's More menu for migration or backup; imports are validated first, and overwriting the whole config (workspaces included) asks for confirmation. Every write first rotates three automatic backups, and "Restore backup" puts one back after a confirming dialog — a mistake never means digging through files.
25
26
  - **Config over HTTP**: list, create, update, and delete presets through the four `/api/paoding/presets` endpoints, served in-process by the DSH web service and callable over loopback; they ride the panel's Save & Apply generation pipeline and share its write lock, so scripts and automation tools can reshape the roster without opening a browser.
26
27
  - **Panel in English and Chinese**: every UI string ships in both languages, auto-detected (explicit choice first, then Chinese signals — browser language, host page language, Chinese time zones — outrank English ones, since the Electron shell pins navigator to en-US regardless of the OS), switchable from the More menu and remembered.
27
28
  - **Notified of new releases, one-click upgrade in the panel**: the panel compares your local version against the latest npm registry publish (npmmirror and GitHub release as successive fallbacks) and points to the release page when a newer one is out. The Upgrade button swaps in the new version in place (profile auto-detected): regular profiles go through `dsh plugin update dsh-paoding`, while the Electron-owned desktop profile — which the dsh CLI guards against — gets a direct `pnpm add dsh-paoding@<version>` run in the profile directory, falling back to `corepack pnpm` when no bare pnpm is on PATH; a DSH restart applies it, and the orchestrator preset regenerates itself against the new version on startup. A dev checkout in link: form cannot be upgraded in place — the panel tells you how to switch back to the registry version. If the check fails (offline, rate-limited), a subdued "version check failed · retry" row stays in the header (full causes and proxy hints in its tooltip) without popping anything up.
@@ -95,9 +96,9 @@ Writes go through the same generation pipeline and write lock as the panel's Sav
95
96
  | Document | Contents |
96
97
  |---|---|
97
98
  | [Architecture](docs/architecture_en.md) | Why it is designed this way — overview, the cost ledger, roles and tools, mapping to DSH's native mechanisms, token governance, known limits. |
98
- | [Installation](docs/installation_en.md) | The single official channel (`dsh plugin add`), version support and the dual preset landing (DSH 0.1.5 – 0.2.1), first-install automation and the version marker, upgrading, dev-checkout install, host patch detection, the Paoding Config panel, uninstalling, troubleshooting. |
99
+ | [Installation](docs/installation_en.md) | The single official channel (`dsh plugin add`), version support and the dual preset landing (DSH 0.1.5 – 0.2.1), first-install automation and the version marker, upgrading, dev-checkout install, host patch detection, the Paoding Config panel, uninstalling (one `dsh-paoding uninstall` command), troubleshooting (doctor with `--fix`). |
99
100
  | [Orchestration](docs/orchestration_en.md) | Orchestration overview, how failures surface and the three recovery layers, one-shot vs continuable, context isolation. |
100
- | [Configuration](docs/configuration_en.md) | The full key reference, tool-entry wildcards, tuning built-in roles, main-agent tools and skills, custom roles, per-role models, per-role session and start modes, scenario templates, config export/import, health-check hints, the HTTP API. |
101
+ | [Configuration](docs/configuration_en.md) | The full key reference, tool-entry wildcards, tuning built-in roles, main-agent tools and skills, custom roles, per-role models, per-role session and start modes, scenario templates, config export/import and backup-rollback, health-check hints, the HTTP API. |
101
102
 
102
103
  ## Contributing
103
104
 
@@ -15,16 +15,27 @@ const REFUSE =
15
15
  const usage = `dsh-paoding 安装快捷方式(等价于 dsh plugin --profile <name> add dsh-paoding@<version>)
16
16
 
17
17
  用法:npx dsh-paoding@latest [--profile <name>]
18
- npx dsh-paoding@latest doctor [--profile <name>] [--config <file>]
18
+ npx dsh-paoding@latest doctor [--profile <name>] [--config <file>] [--fix] [--yes]
19
+ npx dsh-paoding@latest uninstall [--purge] [--yes] [--config <file>]
19
20
 
20
21
  子命令:
21
- doctor 本机安装体检(只读):配置文件 / 预设轨道 / 托管声明行 /
22
+ doctor 本机安装体检(默认只读):配置文件 / 预设轨道 / 托管声明行 /
22
23
  孤儿工作区预设 / 预设漂移 / 版本标记,结尾给汇总;
23
- 有错误级发现时退出码 1。
24
+ 有错误级发现时退出码 1。--fix 对其中可安全自动修的两类动手
25
+ (孤儿预设目录、孤儿/过期声明行;写盘前备份 .bak-1),其余
26
+ 发现只给处理建议,输出逐项标注「已修 / 需手动」。
27
+ uninstall 清理庖丁写进宿主目录的东西:cordis.patch.yml 托管声明块、
28
+ .agent-presets 下的 orchestrator* 预设目录、.generator-version
29
+ 标记。默认保留配置文件及其备份(用户数据),--purge 才连配置
30
+ 一起删;不碰插件包自身(包本体用 dsh plugin remove 卸载)。
31
+ 非交互终端(非 TTY)下没带 --yes 只列计划不执行,退出码 2。
24
32
 
25
33
  选项:
26
34
  --profile <name> 插件装入的 profile,默认 web(dsh web 的默认 profile)
27
- --config <file> 配置文件路径(仅 doctor 子命令使用)
35
+ --config <file> 配置文件路径(doctor / uninstall 子命令使用)
36
+ --purge uninstall 连配置文件及其备份一起删(默认保留)
37
+ --yes 跳过逐类确认直接执行(uninstall / doctor --fix)
38
+ --fix doctor 体检后自动修可安全处理的问题
28
39
  --help 显示本帮助
29
40
  --version 显示包版本
30
41
 
@@ -36,17 +47,18 @@ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.me
36
47
 
37
48
  const argv = process.argv.slice(2);
38
49
 
39
- // doctor 子命令:包不再携带独立 CLI,但 tools/ 随包发布(package.json files),
40
- // 体检逻辑本体在 tools/lib/cli.mjs——这里 dynamic import 转发(--profile /
41
- // --config 等参数原样透传,由它自己的 parseArgs 解析),退出码语义:
42
- // 无错误 0,有 error 级发现 1。放在参数循环之前:doctor 的参数不用本入口的
50
+ // doctor / uninstall 子命令:包不再携带独立 CLI,但 tools/ 随包发布
51
+ //(package.json files),逻辑本体在 tools/lib/cli.mjs——这里 dynamic import
52
+ // 转发(--profile / --config / --fix / --purge / --yes 等参数原样透传,由它
53
+ // 自己的 parseArgs 解析),退出码语义:成功 0,有 error 级发现或清理失败 1,
54
+ // 非 TTY 无 --yes 的防呆拒做 2。放在参数循环之前:子命令的参数不用本入口的
43
55
  // profile 解析兜底。
44
- if (argv.includes('doctor')) {
56
+ if (argv.includes('doctor') || argv.includes('uninstall')) {
45
57
  try {
46
58
  const { main } = await import('../tools/lib/cli.mjs');
47
59
  process.exit((await main({ argv })) ?? 0);
48
60
  } catch (err) {
49
- console.error(`doctor 运行失败:${err?.message ?? err}`);
61
+ console.error(`子命令运行失败:${err?.message ?? err}`);
50
62
  process.exit(1);
51
63
  }
52
64
  }
@@ -739,6 +739,8 @@ workspaces:
739
739
  - 落盘即改 mtime,面板的检测状态缓存按对账自动失效,视图随后按新配置重建。
740
740
  - 与「保存并应用」共用同一把写盘互斥闸:应用进行中导入(或反过来)会收到 409,稍后重试即可。
741
741
 
742
+ **备份与恢复**:凡是往配置文件写盘的动作(保存并应用、导入、恢复备份)都会先把当前文件轮换备份三份——`dsh-paoding.config.yml.bak-1`(最新)到 `.bak-3`,逐份后移、最旧的淘汰;备份与配置文件同目录,首次保存前没有旧值就不备份。回滚走「更多」→「恢复备份…」:列出各备份的生成时间与大小,二次确认后整份覆盖回当前配置(恢复前当前文件还会再自动备份一份,连按恢复也能原路退回);恢复同样先验格式(解析不出顶层映射的备份拒收),共用写盘互斥闸。没有面板时,手动把 `.bak-N` 拷回主文件名即可。
743
+
742
744
  ## 12. 检查提示(体检)
743
745
 
744
746
  预览或应用后,若服务端体检发现问题,预览区上方会出现一张**检查提示**卡:逐条列出示意,红(error)/ 琥珀(warn)/ 中性(info)三色分级,悬停可见检查项代号(排障用)。没有问题就没有这张卡,零占位。
@@ -755,6 +757,8 @@ workspaces:
755
757
 
756
758
  作废口径:**预览**产生的提示随配置草稿的任何改动一并作废(与预览同一逻辑);**应用**产生的提示描述的是已落盘结果,保留到下一次预览或应用。应用失败时错误 toast 照旧,同时卡片给出每条失败原因;应用成功但存在 warn/error 级提示时,成功 toast 会换成琥珀档「有 N 条检查提示,见下方」。
757
759
 
760
+ 体检之外,预览还带两样「看得见」的东西:一是**本次变更**——相对上次保存配置的逐项明细(角色增删、各角色工具与 persona、专用模型、启动方式、后台续跑、主 agent 工具增删、`roles_remove` 与 `main_agent_extra` 通道),没有任何改动就一行「与上次保存的配置一致」;二是**工具面瘦身统计**——主 agent 当前 allow 数对照单体全量数的百分比,页头常驻一份(按已保存配置),预览区再示一份(按当前未保存配置),保存前后各看各的。
761
+
758
762
  ## 13. HTTP 接口
759
763
 
760
764
  插件的 Web 后端随 DSH Web 服务同进程挂载在 `/api/paoding/*` 前缀下(回环地址 + 端口随部署,信任围栏与面板一致),面板能做的配置读写,脚本与自动化工具也能照做。预设对象的完整 CRUD 四条:
@@ -751,6 +751,8 @@ The header "More" menu offers export and import of the whole config file (the §
751
751
  - Writing changes the file's mtime, so the panel's detection-state cache invalidates automatically through the existing reconciliation, and the view rebuilds from the new config.
752
752
  - Import shares the same in-flight write gate as "save & apply": applying during an import (or the reverse) answers 409 — retry shortly.
753
753
 
754
+ **Backups and restore**: every action that writes the config file (save & apply, import, restore) first rotates the current file through three backups — `dsh-paoding.config.yml.bak-1` (newest) to `.bak-3`, each shifting one slot and the oldest falling off; backups live next to the config file, and a first-ever save with no previous file backs up nothing. Rollback runs through "More" → "Restore backup…": each backup is listed with its time and size, one confirming dialog puts it back in place (the current file is backed up once more first, so even a mistaken restore can be walked back); the restore validates the backup too (a backup that parses to a non-mapping is rejected) and shares the write gate. Without the panel, copy a `.bak-N` back over the main filename by hand.
755
+
754
756
  ## 12. Check messages (health review)
755
757
 
756
758
  After a preview or an apply, if the server-side health review finds problems, a **check messages** card appears above the preview area: one row per finding, color-coded red (error) / amber (warn) / neutral (info), with the check code available on hover for troubleshooting. No findings — no card, zero footprint.
@@ -767,6 +769,8 @@ Entries come from the structured health review (`tools/lib/health.mjs`); codes a
767
769
 
768
770
  Invalidation scope: messages from a **preview** are discarded together with the draft on any config edit (same rule as the preview itself); messages from an **apply** describe what has already been written and survive until the next preview or apply. When an apply fails, the error toast stays as usual and the card lists every reason; when an apply succeeds but warn/error-level findings exist, the success toast switches to the amber variant "N check messages, see below".
769
771
 
772
+ Beside the checks, a preview carries two more pieces of visibility. One is **changes since the last save** — an itemized diff against the saved config (roles added/removed, each role's tools and persona, dedicated model, start mode, background continuation, main-agent tool changes, the `roles_remove` and `main_agent_extra` channels); with nothing changed it collapses to a single "identical to the last saved config" line. The other is the **tool-surface stat** — the main agent's current allow count against the monolithic total as a percentage: one permanent line in the header (from the saved config) and one in the preview (from the unsaved config), one for each side of a save.
773
+
770
774
  ## 13. HTTP API
771
775
 
772
776
  The plugin's web backend is mounted under the `/api/paoding/*` prefix inside the DSH web server itself (loopback address + port per your deployment; the same trust fence as the panel). Anything the panel can do to the config, scripts and automation can do too. Full CRUD for preset objects:
@@ -191,22 +191,30 @@ patch 与配置文件用 **`yaml` 包**解析——通过 `createRequire` 从 `$
191
191
 
192
192
  ### 数据接口与安全
193
193
 
194
- 面板数据走**同源 `/api/paoding/*`**:Node 侧注册前缀路由——`GET /api/paoding/state`(带缓存的检测状态)、`GET /api/paoding/version`(最新版检测,版本/更新卡的数据源)、`GET /api/paoding/models`(宿主模型运行时的模型清单)、`GET` + `POST /api/paoding/workspaces`(工作区列表 / 添加工作区)、`POST /api/paoding/rescan`(强制重检测,含 MCP 握手)、`POST /api/paoding/preview`(不写盘生成)、`POST /api/paoding/apply`(安装并保存配置)、`POST /api/paoding/upgrade`(就地升级:普通 profile 走 `dsh plugin update`,desktop profile 直跑 `pnpm add`,pnpm 按「裸 pnpm → `corepack pnpm` → PNPM_HOME 落位」候选链解析)、`GET /api/paoding/config/export`(配置文件原文导出,下载/备份用)、`POST /api/paoding/config/import`(整份导入:先验格式、与「保存并应用」共用写盘闸)、`GET /api/paoding/client.css`(面板样式静态下发)——复用 `tools/` 的检测与生成管线(`plugins/paoding-config-ui/api-core.mjs`)。路由自带**浏览器信任围栏**:Host 必须回环或落在 `webRuntime.trustedHosts`,并拒绝 cross-site 请求(复刻 DSH `/api` 网关围栏语义,因为 `/api/paoding` 前缀更长会命中本插件而绕开网关)。面板**没有独立服务端/端口**:DSH Web 端口只监听 `127.0.0.1`,不对外网暴露。
194
+ 面板数据走**同源 `/api/paoding/*`**:Node 侧注册前缀路由——`GET /api/paoding/state`(带缓存的检测状态)、`GET /api/paoding/version`(最新版检测,版本/更新卡的数据源)、`GET /api/paoding/models`(宿主模型运行时的模型清单)、`GET` + `POST /api/paoding/workspaces`(工作区列表 / 添加工作区)、`POST /api/paoding/rescan`(强制重检测,含 MCP 握手)、`POST /api/paoding/preview`(不写盘生成)、`POST /api/paoding/apply`(安装并保存配置)、`POST /api/paoding/upgrade`(就地升级:普通 profile 走 `dsh plugin update`,desktop profile 直跑 `pnpm add`,pnpm 按「裸 pnpm → `corepack pnpm` → PNPM_HOME 落位」候选链解析)、`GET /api/paoding/config/export`(配置文件原文导出,下载/备份用)、`POST /api/paoding/config/import`(整份导入:先验格式、与「保存并应用」共用写盘闸)、`GET /api/paoding/config/backups`(自动备份清单)、`POST /api/paoding/config/restore`(恢复备份:文件名白名单防穿越,先验可解析再覆盖)、`GET /api/paoding/stats`(委派效果统计:冷读会话存档聚合,days 窗口与 project 过滤)、`GET /api/paoding/client.css`(面板样式静态下发)——复用 `tools/` 的检测与生成管线(`plugins/paoding-config-ui/api-core.mjs`)。路由自带**浏览器信任围栏**:Host 必须回环或落在 `webRuntime.trustedHosts`,并拒绝 cross-site 请求(复刻 DSH `/api` 网关围栏语义,因为 `/api/paoding` 前缀更长会命中本插件而绕开网关)。面板**没有独立服务端/端口**:DSH Web 端口只监听 `127.0.0.1`,不对外网暴露。
195
195
 
196
196
  ### 面板能力
197
197
 
198
- - **状态与操作**:页头是标题 + 版本/更新卡(新版就地提示与一键升级)+ 副标题,正文直接就是工作区与角色卡,没有单独的检测摘要与 chips 区;操作按钮「**保存并应用**」「预览生成」「重新检测」固定在面板底部悬浮操作坞(sticky bottom),滚动任意位置都可直接点击。
199
- - **Agent 工具分配卡片**:主 agent 一张固定卡(基础工具取消勾选 = 加入 `main_agent_remove` 从主 agent 剔除;MCP / 插件工具勾选 = 加入 `main_agent_extra`;技能「read 按需」与「内联全文」两组勾选;另有「人设追加」编辑区,可改、清空、恢复默认)+ `search_external` / `design` / `implement` 三张内置角色卡 + 任意自定义角色卡(带删除按钮);每张角色卡把工具按「基础工具 / MCP 工具 / 插件工具」三组呈现、可逐项勾选,并可编辑 persona。底部「新建自定义 agent 角色」。
198
+ - **状态与操作**:页头是标题 + 版本/更新卡(新版就地提示与一键升级)+ 副标题,副标题下一行常驻主 agent 工具面瘦身统计(当前 allow 数 / 单体全量数与瘦身百分比,配完第一次能看到省了多少),正文直接就是工作区与角色卡,没有单独的检测摘要与 chips 区;操作按钮「**保存并应用**」「预览生成」「重新检测」固定在面板底部悬浮操作坞(sticky bottom),滚动任意位置都可直接点击。
199
+ - **Agent 工具分配卡片**:主 agent 一张固定卡(基础工具取消勾选 = 加入 `main_agent_remove` 从主 agent 剔除;MCP / 插件工具勾选 = 加入 `main_agent_extra`;技能「read 按需」与「内联全文」两组勾选;另有「人设追加」编辑区,可改、清空、恢复默认)+ `search_external` / `design` / `implement` 三张内置角色卡 + 任意自定义角色卡(带删除按钮);每张角色卡把工具按「基础工具 / MCP 工具 / 插件工具」三组呈现、可逐项勾选(任一组超过 8 项时组顶出现筛选框,输入即滤),并可编辑 persona。底部「新建自定义 agent 角色」。
200
200
  - **技能分配**:每个 skill 一行,勾选分配给哪些 agent(写入对应 persona 的 `Available skills` 软引导;角色技能软引导,主 agent 技能另有 read 按需/内联两组)。
201
- - **预览生成**:不写盘生成 `agent.cordis.yml`,显示每个角色 allow 的 intent → kept 计数与生成全文。
201
+ - **预览生成**:不写盘生成 `agent.cordis.yml`,显示每个角色 allow 的 intent → kept 计数与生成全文;同时列「本次变更」——相对上次保存配置的逐项明细(角色增删、各角色工具与 persona、专用模型、启动方式、后台续跑、主 agent 工具增删),无改动时一行带过;瘦身统计在这里按当前未保存配置另示一行。
202
202
  - **保存并应用**:确认后写入 preset(覆盖 `$DSH_HOME/.agent-presets/orchestrator`)并按宿主版本同步登记——≤ 0.1.6 目录扫描即生效,≥ 0.1.7 同步维护 `$DSH_HOME/cordis.patch.yml` 里的声明行托管块(见第 2 节)——再把当前分配保存到 `$DSH_HOME/dsh-paoding.config.yml`;应用成功后提示重启 DSH 或新建会话生效(检测到 patch 比生成结果新时提示重启后生效)。打开面板时会加载既有配置文件作为当前值——手编过的选择直接可见、可改。
203
203
  - **场景模板**:页头三档切换(轻量:只留实现角色;调研:只留检索角色;全开:全员到齐、主 agent 额外工具带满检测库存),一键换「班底」;只动 `roles_remove` 与 `main_agent_extra`,各角色精调过的工具面、persona、模型、启动方式分毫不动,切回即原样复原。
204
204
  - **检查提示卡**:每次「预览生成 / 保存并应用」自动过一遍体检(配置了未挂载的工具、零工具角色、查无此名的模型、预设落后于配置),分级提示以卡片形式贴在页头下方,处理完再保存不迟。
205
- - **「更多」菜单**:配置导出(下载 `dsh-paoding.config.yml` 原文)/ 导入(先验格式,整份覆盖含工作区段,需二次确认)与面板语言切换(中英自动识别、手动选择优先并记住)。
205
+ - **备份与回滚**:保存、导入、恢复配置前都会自动把当前配置轮换备份三份(`config.yml.bak-1..3`,新压旧);「更多」→「恢复备份…」列时间与大小、二次确认后回退,恢复前当前配置还会再自动备份一份——误操作有后悔药。
206
+ - **委派效果统计**:页头「委派效果」卡按角色统计被委派的调用数、平均耗时与失败数(近 30 天,`days` 参数可调)。数据来自宿主会话存档的冷读——经宿主 `sessionPersistence` 服务逐会话抽摘要、本地聚合,不出机、不带负载;失败记的是子会话零轮次或轮次中断(spawn 后即死、中途终止两种形态)。宿主缺会话服务时整卡不渲染。
207
+ - **「更多」菜单**:配置导出(下载 `dsh-paoding.config.yml` 原文)/ 导入(先验格式,整份覆盖含工作区段,需二次确认)/ 恢复备份(见上条)与面板语言切换(中英自动识别、手动选择优先并记住)。
206
208
 
207
209
  ## 7. 卸载
208
210
 
209
- 三条命令,删得干干净净:
211
+ 先用一条命令清掉庖丁写进宿主目录的东西(托管声明块、`orchestrator*` 预设目录、版本标记;配置文件默认保留,`--purge` 才连配置与备份一起删;非交互终端需加 `--yes`):
212
+
213
+ ```bash
214
+ npx dsh-paoding@latest uninstall
215
+ ```
216
+
217
+ 包本体再按 profile 摘掉,三条命令删得干干净净:
210
218
 
211
219
  ```bash
212
220
  dsh plugin --profile web remove dsh-paoding
@@ -216,7 +224,7 @@ rm -rf "${DSH_HOME:-$HOME/.dsh}/.agent-presets"/orchestrator-*
216
224
 
217
225
  第一条摘掉插件与侧栏面板(只影响指定 profile),第二条删掉编排预设目录,第三条清掉按工作区配置时生成的各工作区预设目录(`orchestrator-<目录名>`;没用过按工作区配置就没有这类目录,通配不命中、无害)——基础 `orchestrator` 目录已由上一条命令删掉,不含在这个通配里。配置文件 `~/.dsh/dsh-paoding.config.yml` 不随之上删——留着或删掉都不影响 DSH 其它配置,重装时首装自动化会再次按它应用。
218
226
 
219
- 宿主为 DSH ≥ 0.1.7 时再多看一眼:`$DSH_HOME/cordis.patch.yml` 里可能还留着 dsh-paoding 托管块(起止标记注释包着 `- insert:` 声明行)。预设目录删掉后,块内声明行就成了指向已删目录的悬空引用,请把整个托管块(从 `# --- dsh-paoding presets (auto-generated; do not edit) ---` 起始行到 end 标记行)一并删去——块外内容不受影响。
227
+ (走了上面的 `uninstall` 就免了这一步和下一眼的托管块手删——它已一并清掉。)宿主为 DSH ≥ 0.1.7 时若手动删目录,再多看一眼:`$DSH_HOME/cordis.patch.yml` 里可能还留着 dsh-paoding 托管块(起止标记注释包着 `- insert:` 声明行)。预设目录删掉后,块内声明行就成了指向已删目录的悬空引用,请把整个托管块(从 `# --- dsh-paoding presets (auto-generated; do not edit) ---` 起始行到 end 标记行)一并删去——块外内容不受影响。
220
228
 
221
229
  卸载不影响 host 的其它内容(MCP、插件、会话等),与 DSH 源码零耦合;之后新建会话时「编排模式 (Orchestrator)」不再出现在预设选择器里。
222
230
 
@@ -232,6 +240,8 @@ npx dsh-paoding@latest doctor # 或仓库内:node tools/install.mjs d
232
240
 
233
241
  doctor 不改任何文件,逐项检查并给出 `✔ 正常 / ⚠ 警告 / ✘ 错误 / – 跳过` 四档结论:配置文件能否解析、预设安装轨道与宿主版本是否匹配、托管声明行有无孤儿行或损坏块、`.agent-presets/orchestrator-*` 有没有配置里已不引用的孤儿目录、已装预设与当前配置的再生成结果有无漂移、`.generator-version` 版本标记是否对得上。结尾有汇总;出现 ✘ 时退出码为 1,⚠ 与 – 不影响使用(跳过多见于全新机器,属正常)。`--config` / `--profile` 与安装时同义。
234
242
 
243
+ `doctor --fix` 会在这份诊断之后自动修两类可安全处理的问题——孤儿 `orchestrator-*` 预设目录、托管块里的孤儿/过期声明行(写盘前自动备份 `.bak-1`),其余发现只给处理建议不代做(预设漂移就提示跑 `--auto` 重新生成);输出逐项标注「已修 / 需手动」。非交互终端下 `--fix` 与 `uninstall` 都要显式 `--yes` 才落盘,否则只列计划、退出码 2。
244
+
235
245
  面板侧也有同源的保存时体检:每次「预览生成 / 保存并应用」的响应都带 `warnings` 字段(配置了未挂载工具、零工具角色、角色专用模型不在模型目录、预设落后于配置等),按条目提示处理即可,不用等运行时报错。
236
246
 
237
247
  **pnpm 缺失**
@@ -191,22 +191,30 @@ If you'd rather not hand-edit `dsh-paoding.config.yml`, open the **庖丁配置
191
191
 
192
192
  ### Data interface and security
193
193
 
194
- Panel data goes over the **same-origin `/api/paoding/*`**: the Node side registers prefix routes — `GET /api/paoding/state` (cached detection state), `GET /api/paoding/version` (latest-version check, the data source of the version/update card), `GET /api/paoding/models` (model list from the host LLM runtime), `GET` + `POST /api/paoding/workspaces` (list / add workspaces), `POST /api/paoding/rescan` (forced re-detection, MCP handshakes included), `POST /api/paoding/preview` (generate without writing), `POST /api/paoding/apply` (install and save config), `POST /api/paoding/upgrade` (in-place upgrade: `dsh plugin update` for regular profiles, a direct `pnpm add` for the desktop profile — pnpm is resolved through a candidate chain: bare `pnpm` → `corepack pnpm` → PNPM_HOME locations), `GET /api/paoding/config/export` (raw config file for download/backup), `POST /api/paoding/config/import` (whole-file import: validated first, shares the apply write mutex), `GET /api/paoding/client.css` (statically served panel stylesheet) — reusing the detection/generation pipeline in `tools/` (`plugins/paoding-config-ui/api-core.mjs`). The routes carry a **browser trust fence**: the Host must be loopback or listed in `webRuntime.trustedHosts`, and cross-site requests are rejected (mirroring DSH's `/api` gateway fence semantics, since the longer `/api/paoding` prefix would otherwise hit this plugin and bypass the gateway). The panel has **no separate server or port**: the DSH Web port listens on `127.0.0.1` only and is never exposed to the outside.
194
+ Panel data goes over the **same-origin `/api/paoding/*`**: the Node side registers prefix routes — `GET /api/paoding/state` (cached detection state), `GET /api/paoding/version` (latest-version check, the data source of the version/update card), `GET /api/paoding/models` (model list from the host LLM runtime), `GET` + `POST /api/paoding/workspaces` (list / add workspaces), `POST /api/paoding/rescan` (forced re-detection, MCP handshakes included), `POST /api/paoding/preview` (generate without writing), `POST /api/paoding/apply` (install and save config), `POST /api/paoding/upgrade` (in-place upgrade: `dsh plugin update` for regular profiles, a direct `pnpm add` for the desktop profile — pnpm is resolved through a candidate chain: bare `pnpm` → `corepack pnpm` → PNPM_HOME locations), `GET /api/paoding/config/export` (raw config file for download/backup), `POST /api/paoding/config/import` (whole-file import: validated first, shares the apply write mutex), `GET /api/paoding/config/backups` (automatic backup list), `POST /api/paoding/config/restore` (restore a backup: filename whitelist against path traversal, validated for parseability before overwriting), `GET /api/paoding/stats` (delegation stats: cold-read aggregation over the session archive, with a days window and project filter), `GET /api/paoding/client.css` (statically served panel stylesheet) — reusing the detection/generation pipeline in `tools/` (`plugins/paoding-config-ui/api-core.mjs`). The routes carry a **browser trust fence**: the Host must be loopback or listed in `webRuntime.trustedHosts`, and cross-site requests are rejected (mirroring DSH's `/api` gateway fence semantics, since the longer `/api/paoding` prefix would otherwise hit this plugin and bypass the gateway). The panel has **no separate server or port**: the DSH Web port listens on `127.0.0.1` only and is never exposed to the outside.
195
195
 
196
196
  ### Panel capabilities
197
197
 
198
- - **State and actions**: the page header is a title + version/update card (in-place new-version notice and one-click upgrade) + subtitle, and the body goes straight to the workspace and role cards with no separate detection-summary/chips section; the action buttons「**保存并应用**」(Save & Apply), Preview, and Rescan sit in a sticky bottom dock, clickable from any scroll position.
199
- - **Agent tool-assignment cards**: one fixed card for the main agent (unchecking a base tool adds it to `main_agent_remove`, dropping it from the main agent; checking an MCP / plugin tool adds it to `main_agent_extra`; skills in two groups, "read on demand" and "inline full text"; plus a "persona extra" editor — edit, clear, or restore the default) + three built-in role cards (`search_external` / `design` / `implement`) + any number of custom role cards (with a delete button); every role card presents its tools in three groups — base / MCP / plugin — with per-item checkboxes, and the persona is editable. "Create a custom agent role" at the bottom.
198
+ - **State and actions**: the page header is a title + version/update card (in-place new-version notice and one-click upgrade) + subtitle, with a permanent main-agent tool-surface line under the subtitle (current allow count vs the monolithic total, plus the slimming percentage — the first visible payoff of configuring), and the body goes straight to the workspace and role cards with no separate detection-summary/chips section; the action buttons「**保存并应用**」(Save & Apply), Preview, and Rescan sit in a sticky bottom dock, clickable from any scroll position.
199
+ - **Agent tool-assignment cards**: one fixed card for the main agent (unchecking a base tool adds it to `main_agent_remove`, dropping it from the main agent; checking an MCP / plugin tool adds it to `main_agent_extra`; skills in two groups, "read on demand" and "inline full text"; plus a "persona extra" editor — edit, clear, or restore the default) + three built-in role cards (`search_external` / `design` / `implement`) + any number of custom role cards (with a delete button); every role card presents its tools in three groups — base / MCP / plugin — with per-item checkboxes (any group over 8 items grows a filter box on top; type to narrow), and the persona is editable. "Create a custom agent role" at the bottom.
200
200
  - **Skill assignment**: one row per skill, check which agents it goes to (written into the matching personas as `Available skills` soft guidance; role skills are soft guidance, main-agent skills have the read-on-demand/inline groups).
201
- - **Preview**: generates `agent.cordis.yml` without writing, showing each role's intent → kept counts plus the full generated text.
201
+ - **Preview**: generates `agent.cordis.yml` without writing, showing each role's intent → kept counts plus the full generated text; it also lists "changes since the last save" — an itemized diff (roles added/removed, each role's tools and persona, dedicated model, start mode, background continuation, main-agent tool changes) reduced to a single line when nothing changed; the tool-surface stat appears here too, computed from the unsaved config.
202
202
  - **Save & Apply**: after confirmation, writes the preset (overwriting `$DSH_HOME/.agent-presets/orchestrator`) and registers it per host generation — on ≤ 0.1.6 the directory scan picks it up as-is, on ≥ 0.1.7 the declaration managed block in `$DSH_HOME/cordis.patch.yml` is maintained in the same pass (see §2) — then saves the current assignments to `$DSH_HOME/dsh-paoding.config.yml`; success asks you to restart DSH or start a new session (and flags when a patch is newer than the generated output). Opening the panel loads the existing config file as the current values — hand-edited choices are visible and editable right away.
203
203
  - **Scenario templates**: three one-click presets in the header (Lite: implement role only; Research: search roles only; Full: everyone on deck with the main agent carrying the whole detected inventory) swap the roster — they only touch `roles_remove` and `main_agent_extra`; each role's hand-tuned tools, persona, model, and start mode stay untouched and restore as-is when you switch back.
204
204
  - **Health-check card**: every Preview / Save & Apply runs a check pass (tools configured but not mounted, zero-tool roles, unknown model names, a preset lagging behind the config); findings show as a severity-tagged card under the header so you can fix them before saving.
205
- - **"More" menu**: config export (download the raw `dsh-paoding.config.yml`) / import (validated first; overwrites the whole file, workspaces included, with confirmation) and the panel language toggle (English/Chinese auto-detected, manual choice wins and is remembered).
205
+ - **Backups and rollback**: every write to the config (save & apply, import, restore) first rotates the current file through three backups — `config.yml.bak-1` (newest) through `.bak-3`; "More" → "Restore backup…" lists each backup's time and size and, after a confirming dialog, puts it back (the current file is backed up once more before the restore, so even a wrong restore can be undone).
206
+ - **Delegation stats**: the "Delegation" card in the header counts, per role, delegations, average duration, and failures (last 30 days, adjustable via `days`). The data is a cold read of the host session archive — summaries drawn per session through the host `sessionPersistence` service and aggregated locally; nothing leaves the machine and no payloads are read. A failure means the child session ran zero turns or was interrupted mid-turn (died right after spawn, or cut off). When the host lacks the session service the card simply doesn't render.
207
+ - **"More" menu**: config export (download the raw `dsh-paoding.config.yml`) / import (validated first; overwrites the whole file, workspaces included, with confirmation) / restore backup (see above) and the panel language toggle (English/Chinese auto-detected, manual choice wins and is remembered).
206
208
 
207
209
  ## 7. Uninstalling
208
210
 
209
- Three commands, and it's gone cleanly:
211
+ One command first clears what dsh-paoding wrote into the host directory (the managed declaration block, the `orchestrator*` preset directories, the version marker; the config file is kept unless `--purge`; non-interactive terminals need `--yes`):
212
+
213
+ ```bash
214
+ npx dsh-paoding@latest uninstall
215
+ ```
216
+
217
+ Then lift the package itself off the profile with three commands:Three commands, and it's gone cleanly:
210
218
 
211
219
  ```bash
212
220
  dsh plugin --profile web remove dsh-paoding
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-paoding",
3
- "version": "0.4.5",
3
+ "version": "0.4.6",
4
4
  "description": "庖丁 — DSH (DeepSeek Harness) 编排模式安装器:host 感知的角色工具过滤 + Web 设置页可视化配置器",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -8,14 +8,15 @@
8
8
  */
9
9
  import os from 'node:os'
10
10
  import path from 'node:path'
11
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
11
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
12
12
  import { readFile } from 'node:fs/promises'
13
13
  import { assignSlugs, collectState, generateAndInstall, presetIdOf } from '../../tools/install.mjs'
14
14
  import { autoAssignments, baseAssignments } from '../../tools/lib/alloc.mjs'
15
+ import { computeRestrictAllow } from '../../tools/lib/compose.mjs'
15
16
  import { loadConfig, normalizeConfig, normalizeTargetFields, saveConfig, serializeConfig, stripNonTargetKeys } from '../../tools/lib/config.mjs'
16
17
  import { parseYamlSubset, preprocessPatchText } from '../../tools/lib/yaml.mjs'
17
18
  import { captureWarnings, healthCheck } from '../../tools/lib/health.mjs'
18
- import { warn } from '../../tools/lib/util.mjs'
19
+ import { ROLES, warn } from '../../tools/lib/util.mjs'
19
20
  import {
20
21
  backfillHomePatchRows,
21
22
  detectAgentRolesFlavor,
@@ -288,10 +289,178 @@ export async function importConfigContent(content) {
288
289
  error.statusCode = 422
289
290
  throw error
290
291
  }
292
+ // 写盘前自动轮换备份(当前配置推入 bak-1,旧 bak 依次后移;首次保存无
293
+ // 「当前」则不备份)——apply / 工作区预设写盘 / 回滚同一口径,见下方备份节。
294
+ rotateConfigBackups()
291
295
  saveConfig(resolveConfigFile(), normalizeConfig(data))
292
296
  return { ok: true }
293
297
  }
294
298
 
299
+ // ── 配置自动备份与回滚(配置文件写路径的护栏,页头「更多」菜单服务端核心)──────
300
+ //
301
+ // 语义:凡面板写配置(apply / import / 工作区预设写盘 / 回滚本身)在落盘前先把
302
+ // 当前配置推入备份链:当前 → bak-1(最新),旧 bak 依次后移(bak-1→bak-2、
303
+ // bak-2→bak-3),bak-3(最老)淘汰。首次保存(配置文件尚不存在)没有「当前」
304
+ // 可备份,不产生任何 bak 文件。备份名 = 配置文件名 + .bak-N(默认配置即
305
+ // dsh-paoding.config.yml.bak-1/2/3),自定义配置名(DSH_PAODING_CONFIG)随之
306
+ // 派生,清单与还原按同一派生口径校验。
307
+
308
+ /** 备份名校验用正则:配置文件名转义后拼 .bak-N 后缀(N = 1..3 层)。 */
309
+ function configBackupRe() {
310
+ const stem = path.basename(resolveConfigFile()).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
311
+ return new RegExp(`^${stem}\\.bak-([123])$`)
312
+ }
313
+
314
+ /** 第 n 层备份的绝对路径(与配置文件同目录,文件名恒为单层 basename)。 */
315
+ function configBackupPath(n) {
316
+ return `${resolveConfigFile()}.bak-${n}`
317
+ }
318
+
319
+ /**
320
+ * 备份轮换:把当前配置推入 bak-1,旧 bak 依次后移,bak-3 淘汰。当前配置不
321
+ * 存在(首次保存)时不写任何文件、返回 false;轮换完成返回 true。当前文件
322
+ * 用拷贝而非改名进 bak-1——原地保留,读侧(生成管线 / 回滚校验)随时可读;
323
+ * 后移用改名,同一目录内 rename 是原子操作,中断也不产生半个备份。
324
+ */
325
+ export function rotateConfigBackups() {
326
+ const config = resolveConfigFile()
327
+ if (!existsSync(config)) return false
328
+ rmSync(configBackupPath(3), { force: true }) // 最老一层直接淘汰(不存在也无妨)
329
+ for (const [from, to] of [[2, 3], [1, 2]]) {
330
+ try {
331
+ renameSync(configBackupPath(from), configBackupPath(to))
332
+ } catch (err) {
333
+ if (err.code !== 'ENOENT') throw err // 该层尚无备份:正常,跳过
334
+ }
335
+ }
336
+ copyFileSync(config, configBackupPath(1))
337
+ return true
338
+ }
339
+
340
+ /**
341
+ * 备份清单(GET config/backups):{ file, mtimeMs, size }[],按新→旧排序
342
+ *(mtime 降序,同刻并列时层号小者在前)。只读不写;配置目录读不了 / 无备份
343
+ * 一律返回空数组,绝不让清单页 5xx。file 恒为 basename(还原路由只认配置
344
+ * 目录内的备份名,回传它即可防路径穿越)。
345
+ */
346
+ export function listConfigBackups() {
347
+ let names = []
348
+ try {
349
+ names = readdirSync(path.dirname(resolveConfigFile()))
350
+ } catch {
351
+ return [] // 目录不存在 / 不可读 = 无备份可言
352
+ }
353
+ const backupRe = configBackupRe()
354
+ return names
355
+ .map((name) => {
356
+ const m = backupRe.exec(name)
357
+ if (!m) return null
358
+ try {
359
+ const st = statSync(path.join(path.dirname(resolveConfigFile()), name))
360
+ return { file: name, mtimeMs: st.mtimeMs, size: st.size, layer: Number(m[1]) }
361
+ } catch {
362
+ return null // 列举途中被删 / stat 失败:跳过该条
363
+ }
364
+ })
365
+ .filter(Boolean)
366
+ .sort((a, b) => b.mtimeMs - a.mtimeMs || a.layer - b.layer)
367
+ .map(({ file, mtimeMs, size }) => ({ file, mtimeMs, size }))
368
+ }
369
+
370
+ /**
371
+ * 回滚配置(POST config/restore):file 须精确匹配「配置文件名.bak-1/2/3」,
372
+ * 显式拒任何含分隔符 / 上跳段的名字(防路径穿越);通过后先按 loadConfig 同一
373
+ * 口径验证备份可解析(坏备份拒绝覆盖,422;备份不存在 404——statusCode 由
374
+ * 路由层外层 catch 按其回状态码 + { error } 信封),再把「当前配置」按同款
375
+ * 轮换推入备份链(滚错了还能再滚回来),最后拷贝备份为当前。落盘即改 mtime,
376
+ * state 缓存靠既有对账自动失效,无需手动清理。
377
+ */
378
+ export async function restoreConfigBackup(file) {
379
+ const name = typeof file === 'string' ? file : ''
380
+ if (name === '' || name.includes('/') || name.includes('..') || !configBackupRe().test(name)) {
381
+ const error = new Error(`备份文件名不合法(须为 ${path.basename(resolveConfigFile())}.bak-1/2/3):${name === '' ? '(空)' : name}`)
382
+ error.statusCode = 422
383
+ throw error
384
+ }
385
+ const backupPath = path.join(path.dirname(resolveConfigFile()), name)
386
+ // 宿主 yaml 模块从 state 顺路取(collectState 已探测好);state 通道异常时
387
+ // 退化为仅内置解析器校验,与 importConfigContent 同款降级——宁严勿漏。
388
+ let yamlMod = null
389
+ try {
390
+ yamlMod = (await getState())?.yamlMod ?? null
391
+ } catch { /* 校验口径降级,见上 */ }
392
+ let parsed = null
393
+ try {
394
+ parsed = loadConfig(backupPath, yamlMod)
395
+ } catch (err) {
396
+ const error = new Error(`备份无法解析为合法配置,已拒绝回滚:${err.message}`)
397
+ error.statusCode = 422
398
+ throw error
399
+ }
400
+ if (parsed === null) {
401
+ const error = new Error(`备份不存在:${name}`)
402
+ error.statusCode = 404
403
+ throw error
404
+ }
405
+ // 先把选定备份的内容读进内存再轮换:轮换会把整条备份链后移一层,固定层号
406
+ // (bak-N)路径下的内容随之改变——后读的话落到「当前」的就不是用户选的
407
+ // 那份快照了。配置文件很小,整读零成本,顺序必须遵守。
408
+ const content = readFileSync(backupPath)
409
+ // 回滚本身也是一次写配置:先把「当前」按同款轮换推入备份链(滚错了还能
410
+ // 再滚回来),再落选定快照。mtime 变化令 state 缓存按既有对账自动失效,
411
+ // 无需手动清理。
412
+ rotateConfigBackups()
413
+ writeFileSync(resolveConfigFile(), content, { mode: 0o600 }) // 权限口径与 saveConfig 一致
414
+ return { ok: true }
415
+ }
416
+
417
+ // ── 工具面瘦身统计(slim:state / preview / apply 响应的派生字段)─────────────
418
+
419
+ /**
420
+ * 主 agent 工具面瘦身统计,口径与生成管线严格同源(composeGenerated):
421
+ * - total = 可用工具全集 = presetUniverse ∪ inventory 的名字数。presetUniverse
422
+ * = restrict.mjs 主 agent 白名单(restrictBase)∪ 源 preset 各角色 allow
423
+ * 自带面;inventory = 检测到的可用 MCP / 插件工具名。这正是单 agent 模式下
424
+ * 主 agent 名下可能挂着的一切工具(computeRestrictAllow / usableWith 判定
425
+ * 用的同一候选全集),即「不拆角色时的完整工具面」;
426
+ * - main = 当前 assignments 下主 agent 的有效 allow 计数:computeRestrictAllow
427
+ * (base ∪ extra ∪ 自定义角色名 − main_agent_remove − roles_remove,过可用
428
+ * 性过滤)的结果长度;结果与 base 全同时该函数返回 null,按 base 计数。
429
+ * state 收原始通道(blocks 为 Map、inventory 为 Set)与序列化视图(blocks 为
430
+ * 普通对象、inventory 为数组)两态,一律只读。assignments 先剥 profile /
431
+ * workspaces、过 normalizeTargetFields 再算——手写未规范化的提交也得到与
432
+ * 落盘一致的口径。
433
+ */
434
+ export function slimStatsOf(state, assignments) {
435
+ const restrictBase = Array.isArray(state?.restrictBase) ? state.restrictBase : []
436
+ // blocks 两种形态:原始 state 的 Map 值带 names 数组;序列化视图的值即名字数组
437
+ const blockValues = state?.blocks instanceof Map
438
+ ? [...state.blocks.values()]
439
+ : (state?.blocks && typeof state.blocks === 'object' ? Object.values(state.blocks) : [])
440
+ const presetUniverse = new Set(restrictBase)
441
+ for (const block of blockValues) {
442
+ for (const name of Array.isArray(block?.names) ? block.names : Array.isArray(block) ? block : []) {
443
+ presetUniverse.add(name)
444
+ }
445
+ }
446
+ const inventory = state?.inventory instanceof Set
447
+ ? state.inventory
448
+ : new Set(Array.isArray(state?.inventory) ? state.inventory : [])
449
+ const total = new Set([...presetUniverse, ...inventory]).size
450
+ const target = normalizeTargetFields(stripNonTargetKeys(assignments ?? {}))
451
+ const customToolNames = Object.keys(target.roles).filter((n) => !ROLES.includes(n))
452
+ const allow = computeRestrictAllow(
453
+ restrictBase,
454
+ presetUniverse,
455
+ inventory,
456
+ target.main_agent_extra,
457
+ target.main_agent_remove,
458
+ customToolNames,
459
+ target.roles_remove,
460
+ ) ?? restrictBase
461
+ return { total, main: allow.length }
462
+ }
463
+
295
464
  // ── 预设 CRUD(presets 路由族的服务端核心)──────────────────────────────────
296
465
  //
297
466
  // 面板 apply 只覆盖「全局 / 单个工作区视角的生成」,这里补齐预设对象本身的