dsh-config-manager 0.4.3 → 0.5.0

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.
Files changed (254) hide show
  1. package/README.md +10 -0
  2. package/README.zh-CN.md +10 -0
  3. package/lib/adapters/mcp.d.ts +9 -0
  4. package/lib/adapters/mcp.js +37 -0
  5. package/lib/adapters/plugins.js +10 -2
  6. package/lib/adapters/pnpm-workspace.js +1 -1
  7. package/lib/adapters/self.d.ts +2 -0
  8. package/lib/adapters/self.js +18 -2
  9. package/lib/adapters/workspaces.js +1 -1
  10. package/lib/cli/restore-resume.js +1 -1
  11. package/lib/cli/web/page.js +2 -2
  12. package/lib/client.d.ts +14 -41
  13. package/lib/client.js +794 -716
  14. package/lib/core/backup.d.ts +11 -0
  15. package/lib/core/backup.js +27 -0
  16. package/lib/core/env-lock-lifecycle.d.ts +17 -3
  17. package/lib/core/env-lock-lifecycle.js +38 -0
  18. package/lib/core/external-failure.d.ts +9 -0
  19. package/lib/core/external-failure.js +50 -0
  20. package/lib/core/local-plugin-host.d.ts +9 -7
  21. package/lib/core/local-plugin-host.js +109 -15
  22. package/lib/core/local-plugin-pack.d.ts +20 -0
  23. package/lib/core/local-plugin-pack.js +18 -3
  24. package/lib/core/mcp-connector-store.d.ts +13 -0
  25. package/lib/core/mcp-connector-store.js +16 -1
  26. package/lib/core/messages-core.d.ts +45 -0
  27. package/lib/core/messages-core.js +92 -0
  28. package/lib/core/messages.d.ts +1 -0
  29. package/lib/core/messages.js +6 -0
  30. package/lib/core/model-tool-plans.d.ts +66 -0
  31. package/lib/core/model-tool-plans.js +128 -0
  32. package/lib/core/model-tools.d.ts +96 -8
  33. package/lib/core/model-tools.js +568 -31
  34. package/lib/core/phase3-host.js +10 -2
  35. package/lib/core/plugin-data-registry.d.ts +1 -1
  36. package/lib/core/plugin-data-registry.js +1 -1
  37. package/lib/core/restore-plan-fingerprint.d.ts +2 -0
  38. package/lib/core/restore-plan-fingerprint.js +18 -0
  39. package/lib/core/restore-resume.d.ts +1 -1
  40. package/lib/core/restore-resume.js +1 -1
  41. package/lib/core/restore.d.ts +5 -0
  42. package/lib/core/restore.js +4 -1
  43. package/lib/core/types.d.ts +12 -0
  44. package/lib/foreign/claude-sessions.d.ts +1 -1
  45. package/lib/foreign/claude-sessions.js +1 -1
  46. package/lib/foreign/registry.js +1 -1
  47. package/lib/foreign/types.d.ts +1 -1
  48. package/lib/index.d.ts +15 -15
  49. package/lib/index.js +60 -67
  50. package/lib/market/git-file-writer.js +1 -1
  51. package/lib/market/github-repos.js +1 -1
  52. package/lib/market/market-config.js +1 -1
  53. package/lib/market/messages-market.js +1 -1
  54. package/lib/market/my-repo.js +1 -1
  55. package/lib/market/prepare.js +1 -1
  56. package/lib/market/reader.js +2 -2
  57. package/lib/market/repo-url.d.ts +1 -1
  58. package/lib/market/security.js +2 -2
  59. package/lib/market/star-cache.d.ts +1 -1
  60. package/lib/market/types.d.ts +1 -1
  61. package/lib/market/types.js +1 -1
  62. package/lib/market/url.js +1 -1
  63. package/lib/routes/backup.js +17 -9
  64. package/lib/routes/index.d.ts +1 -1
  65. package/lib/routes/kit.d.ts +2 -2
  66. package/lib/routes/market.d.ts +1 -1
  67. package/lib/routes/market.js +3 -60
  68. package/lib/routes/model-tools-deps.d.ts +41 -0
  69. package/lib/routes/model-tools-deps.js +18 -0
  70. package/lib/routes/recovery.js +5 -3
  71. package/lib/routes/route-support.d.ts +18 -26
  72. package/lib/routes/route-support.js +19 -32
  73. package/lib/routes/snapshots.d.ts +1 -1
  74. package/lib/routes/snapshots.js +4 -40
  75. package/lib/routes/sync.js +40 -28
  76. package/lib/schema/index.d.ts +2 -2
  77. package/lib/schema/index.js +2 -2
  78. package/lib/schema/section-registry.d.ts +5 -3
  79. package/lib/schema/section-registry.js +7 -3
  80. package/lib/security/secret-scanner.js +1 -1
  81. package/lib/sync/apply-bundle.d.ts +50 -0
  82. package/lib/sync/apply-bundle.js +60 -0
  83. package/lib/sync/autosync-scheduler.d.ts +9 -0
  84. package/lib/sync/autosync-scheduler.js +118 -89
  85. package/lib/sync/backup-scheduler.js +5 -4
  86. package/lib/sync/blob-store.d.ts +2 -2
  87. package/lib/sync/git/git-transport.d.ts +12 -0
  88. package/lib/sync/git/git-transport.js +50 -2
  89. package/lib/sync/merge.d.ts +2 -0
  90. package/lib/sync/merge.js +28 -0
  91. package/lib/sync/messages.d.ts +4 -0
  92. package/lib/sync/messages.js +9 -2
  93. package/lib/sync/s3/s3-transport.d.ts +1 -1
  94. package/lib/sync/s3/s3-transport.js +1 -1
  95. package/lib/sync/sync-engine.d.ts +4 -4
  96. package/lib/sync/sync-engine.js +25 -26
  97. package/lib/sync/sync-scope-boot.d.ts +34 -0
  98. package/lib/sync/sync-scope-boot.js +71 -0
  99. package/lib/sync/sync-scope.d.ts +103 -0
  100. package/lib/sync/sync-scope.js +229 -0
  101. package/lib/sync/sync-selection.d.ts +17 -4
  102. package/lib/sync/sync-selection.js +40 -14
  103. package/lib/sync/transport.d.ts +4 -1
  104. package/lib/sync/transport.js +6 -0
  105. package/lib/sync/webdav/webdav-transport.js +1 -1
  106. package/lib/sync/workspace-merge.d.ts +36 -0
  107. package/lib/sync/workspace-merge.js +152 -0
  108. package/lib/ui/backup-schedule.d.ts +13 -2
  109. package/lib/ui/backup-schedule.js +3 -0
  110. package/lib/ui/snapshots-view.d.ts +16 -0
  111. package/lib/ui/snapshots-view.js +21 -0
  112. package/lib/utils/env-lock.d.ts +96 -0
  113. package/lib/utils/env-lock.js +332 -111
  114. package/lib/utils/messages-utils.d.ts +6 -0
  115. package/lib/utils/messages-utils.js +17 -1
  116. package/lib/utils/patch-yaml.js +1 -1
  117. package/lib/utils/zip.js +1 -1
  118. package/package.json +3 -2
  119. package/src/adapters/mcp.test.ts +28 -0
  120. package/src/adapters/mcp.ts +33 -0
  121. package/src/adapters/plugins.test.ts +49 -0
  122. package/src/adapters/plugins.ts +9 -1
  123. package/src/adapters/pnpm-workspace.ts +1 -1
  124. package/src/adapters/self.test.ts +39 -1
  125. package/src/adapters/self.ts +20 -2
  126. package/src/adapters/workspaces.ts +1 -1
  127. package/src/cli/restore-resume.ts +1 -1
  128. package/src/cli/web/page.ts +2 -2
  129. package/src/client/about/AboutPanel.tsx +1 -1
  130. package/src/client/about/about-view.test.ts +1 -1
  131. package/src/client/about/about-view.ts +1 -1
  132. package/src/client/api.ts +1 -6
  133. package/src/client/chat/chat-entry-view.test.ts +1 -1
  134. package/src/client/chat/chat-slots.ts +1 -1
  135. package/src/client/chat/rollback-diff-tab.ts +1 -1
  136. package/src/client/client-types.ts +1 -1
  137. package/src/client/common/routes.ts +1 -5
  138. package/src/client/css-scale-guard.test.ts +1 -1
  139. package/src/client/home/HomePanel.tsx +3 -0
  140. package/src/client/library/ArtifactRow.tsx +14 -2
  141. package/src/client/library/LibraryPanel.tsx +44 -0
  142. package/src/client/locales/overview.ts +10 -2
  143. package/src/client/locales/sessions.ts +3 -0
  144. package/src/client/market/MyConfigsView.tsx +1 -1
  145. package/src/client/market/market-api.ts +2 -14
  146. package/src/client/market/market-locales.ts +1 -1
  147. package/src/client/market/market-view.ts +3 -3
  148. package/src/client/market/my-configs-api.ts +1 -1
  149. package/src/client/market/my-configs-view.ts +1 -1
  150. package/src/client/recovery/recovery-locales.test.ts +1 -1
  151. package/src/client/run-store.ts +1 -1
  152. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -5
  153. package/src/client/sync/history-model.test.ts +28 -7
  154. package/src/client/sync/history-model.ts +6 -3
  155. package/src/client/sync/sync-locales.ts +10 -4
  156. package/src/client/sync/sync-view.ts +1 -1
  157. package/src/core/analyzer-cache.test.ts +1 -1
  158. package/src/core/backup.test.ts +45 -1
  159. package/src/core/backup.ts +25 -0
  160. package/src/core/disk-usage.test.ts +2 -0
  161. package/src/core/env-lock-lifecycle.ts +33 -3
  162. package/src/core/external-failure.test.ts +60 -0
  163. package/src/core/external-failure.ts +54 -0
  164. package/src/core/integrity-extra-entries.test.ts +1 -1
  165. package/src/core/local-plugin-host.test.ts +134 -0
  166. package/src/core/local-plugin-host.ts +122 -17
  167. package/src/core/local-plugin-pack.ts +39 -3
  168. package/src/core/mcp-connector-store.ts +26 -1
  169. package/src/core/messages-core.ts +94 -0
  170. package/src/core/messages.ts +6 -0
  171. package/src/core/model-tool-plans.test.ts +111 -0
  172. package/src/core/model-tool-plans.ts +170 -0
  173. package/src/core/model-tools.test.ts +212 -12
  174. package/src/core/model-tools.ts +710 -38
  175. package/src/core/phase3-host.ts +10 -2
  176. package/src/core/phase3-production-integration.test.ts +43 -0
  177. package/src/core/plugin-data-registry.ts +1 -1
  178. package/src/core/restore-plan-fingerprint.ts +19 -0
  179. package/src/core/restore-resume.ts +1 -1
  180. package/src/core/restore.ts +9 -1
  181. package/src/core/types.ts +12 -0
  182. package/src/foreign/claude-sessions.ts +3 -3
  183. package/src/foreign/registry.ts +1 -1
  184. package/src/foreign/types.ts +1 -1
  185. package/src/index.ts +91 -98
  186. package/src/market/git-file-writer.ts +1 -1
  187. package/src/market/github-repos.test.ts +1 -1
  188. package/src/market/github-repos.ts +1 -1
  189. package/src/market/market-config.ts +1 -1
  190. package/src/market/messages-market.ts +1 -1
  191. package/src/market/my-repo.test.ts +1 -1
  192. package/src/market/my-repo.ts +1 -1
  193. package/src/market/prepare.test.ts +1 -1
  194. package/src/market/prepare.ts +1 -1
  195. package/src/market/reader.ts +2 -2
  196. package/src/market/repo-url.ts +1 -1
  197. package/src/market/security.ts +2 -2
  198. package/src/market/star-cache.ts +1 -1
  199. package/src/market/types.ts +1 -1
  200. package/src/market/url.test.ts +1 -1
  201. package/src/market/url.ts +1 -1
  202. package/src/profiles/dsh-profile-copy-rollback.test.ts +1 -1
  203. package/src/routes/backup.ts +16 -9
  204. package/src/routes/index.ts +1 -1
  205. package/src/routes/kit.ts +2 -2
  206. package/src/routes/market.ts +2 -59
  207. package/src/routes/model-tools-deps.ts +56 -0
  208. package/src/routes/recovery.ts +5 -3
  209. package/src/routes/route-support.ts +49 -36
  210. package/src/routes/snapshots.ts +4 -40
  211. package/src/routes/sync.ts +39 -27
  212. package/src/schema/index.ts +2 -2
  213. package/src/schema/manifest-schema.test.ts +2 -2
  214. package/src/schema/registry.test.ts +1 -1
  215. package/src/schema/section-registry.ts +9 -4
  216. package/src/security/redaction.test.ts +1 -1
  217. package/src/security/secret-scanner.test.ts +2 -2
  218. package/src/security/secret-scanner.ts +1 -1
  219. package/src/sync/apply-bundle.ts +104 -0
  220. package/src/sync/autosync-scheduler.test.ts +180 -6
  221. package/src/sync/autosync-scheduler.ts +132 -92
  222. package/src/sync/backup-scheduler.test.ts +11 -4
  223. package/src/sync/backup-scheduler.ts +5 -4
  224. package/src/sync/blob-store.ts +2 -2
  225. package/src/sync/git/git-transport.test.ts +62 -0
  226. package/src/sync/git/git-transport.ts +54 -3
  227. package/src/sync/merge.ts +29 -0
  228. package/src/sync/messages.ts +9 -2
  229. package/src/sync/s3/s3-transport.ts +1 -1
  230. package/src/sync/sync-engine.test.ts +238 -2
  231. package/src/sync/sync-engine.ts +25 -26
  232. package/src/sync/sync-preview-push.test.ts +2 -1
  233. package/src/sync/sync-scope-boot.ts +87 -0
  234. package/src/sync/sync-scope.test.ts +154 -0
  235. package/src/sync/sync-scope.ts +256 -0
  236. package/src/sync/sync-selection.test.ts +76 -2
  237. package/src/sync/sync-selection.ts +40 -13
  238. package/src/sync/transport.test.ts +21 -1
  239. package/src/sync/transport.ts +12 -0
  240. package/src/sync/webdav/webdav-delete-index-unreadable.test.ts +2 -2
  241. package/src/sync/webdav/webdav-transport.ts +1 -1
  242. package/src/sync/workspace-merge.test.ts +110 -0
  243. package/src/sync/workspace-merge.ts +180 -0
  244. package/src/ui/backup-schedule.test.ts +5 -0
  245. package/src/ui/backup-schedule.ts +21 -2
  246. package/src/ui/session-issue-labels.ts +1 -1
  247. package/src/ui/snapshots-view.test.ts +32 -0
  248. package/src/ui/snapshots-view.ts +34 -0
  249. package/src/utils/env-lock.test.ts +242 -9
  250. package/src/utils/env-lock.ts +247 -13
  251. package/src/utils/messages-utils.ts +17 -1
  252. package/src/utils/patch-yaml.ts +1 -1
  253. package/src/utils/zip.ts +1 -1
  254. package/src/client/CLIENT_DEPENDENCIES.md +0 -94
@@ -1,30 +1,38 @@
1
1
  /**
2
- * dsh-config-manager — Agent 可调用的模型工具(P0-1)。
2
+ * dsh-config-manager — Agent 可调用的模型工具(P0-1 / D2–D6)。
3
3
  *
4
- * 在 host 半注册 5 个 Cordis 模型工具,让 Agent 能自主驱动配置运维:
5
- * config_backup 全量备份到 exports 目录(默认不含 secret;可选加密)
4
+ * 在 host 半注册 9 个 Cordis 模型工具,让 Agent 能自主驱动配置运维:
5
+ * config_backup 全量备份到 exports 目录(不含 secret;可选加密)
6
6
  * config_list_snapshots 列出本地回滚快照
7
- * config_restore 预览 / 执行恢复到某快照(默认只预览,confirm:true 才写入)
7
+ * config_restore 预览 / 执行恢复到某快照(预览给 planId;执行必须带回来)
8
8
  * config_sync_push 手动推送同步(写远端)
9
9
  * config_sync_pull 拉取差异预览(零写入)
10
+ * config_sync_preview 三方合并预览(只读:出 planId + 分区裁决清单)
11
+ * config_sync_apply 按分区裁决落地合并(必须带预览给的 planId)
12
+ * config_import_plan 分析备份归档并生成导入计划(只读:零写入)
13
+ * config_import_apply 执行导入计划(必须带 planId + confirm:true)
10
14
  *
11
15
  * 设计遵循 AGENTS.md 铁律:
12
16
  * - 所有业务逻辑为可独立测试的纯编排函数(createModelTools),
13
- * 复用 src/core 已解耦引擎(Exporter / restore / SyncEngine),不重复实现;
17
+ * 复用 src/core 已解耦引擎(Exporter / restore / SyncEngine / Importer),不重复实现;
14
18
  * - React / HTTP 壳不参与;本文件是「引擎侧编排」,不放浏览器 src/ui/;
15
19
  * - ctx.tools 服务用可选读取(ctx.get)守卫:未组合 tools 的部署不注册、不崩溃。
16
20
  *
17
21
  * 安全不变量(硬约束,勿破坏):
18
- * - secret 值永不进入工具入参/出参/render/日志;加密密码仅内存;
19
- * - config_restore 是最危险写操作:缺省只 planRestore(零写入),真实执行必须 confirm:true;
20
- * - config_sync_pull 零写入(只 analyze+plan 出差异);落地需另走确认导入管道;
21
- * - 分区/路径走既有白名单(SECTION_IDS 过滤;同步引擎 portable + FORBIDDEN_SECTIONS 双保险)。
22
+ * - secret 值与密码永不进入工具入参/出参/render/日志;agent 拿不到任何凭据值
23
+ * (config_sync_push 的 includeSecrets 恒 false 且传 true 直接拒绝,导入不接受 secretInputs);
24
+ * - 同步密码优先从 DSH credentials 槽位读(入参 password 保留但 deprecated:模型不该把明文写进会话);
25
+ * - 预览与执行必须同一份计划:预览返回 planId(= 计划指纹),执行时按当前磁盘/远端重算比对,
26
+ * 不一致 → 拒绝且零写入(等价 GUI 恢复路由的 409 plan-changed);
27
+ * - 恢复 / 合并落地 / 导入执行一律过 GLOBAL mutation lock(与 GUI 同一条锁);
28
+ * - config_sync_pull / config_sync_preview / config_import_plan 零写入;
29
+ * - 同步侧永不触碰 sessions 分区(agent 构造引擎时永久剔除:会话内容不因一次工具调用被上下行)。
22
30
  */
23
31
  import { engineMsg } from './messages-core.ts';
24
32
  import type { Context } from '@deepseek-ai/cordis'
25
33
  import { defineTool } from '@deepseek-ai/dsh-tools'
26
34
  import { randomBytes } from 'node:crypto'
27
- import { join } from 'node:path'
35
+ import { join, resolve } from 'node:path'
28
36
 
29
37
  import type { JsonValue } from '@deepseek-ai/dsh-tools'
30
38
  import { Exporter } from './exporter.ts'
@@ -32,15 +40,29 @@ import { listSnapshots, planRestore, restore as executeRestore } from './restore
32
40
  import { probeRestoreResume, runRestoreWithResume } from './restore-resume.ts'
33
41
  import type { RestorePlan, RestoreReport } from './restore.ts'
34
42
  import type { RestoreJournalPort } from './restore-wal.ts'
35
- import type { SyncEngine } from '../sync/sync-engine.ts'
43
+ import type { ApplyMergeResolutionsReport, MergePreview, MergeResolution, SyncEngine } from '../sync/sync-engine.ts'
36
44
  import { createEncryptionProvider } from '../security/encryption.ts'
37
45
  import { SECTION_IDS } from '../schema/config.ts'
38
46
  import type { SectionId } from '../schema/types.ts'
39
47
  import { parseSyncChannel, readFullSyncConfig, readSyncConfigFor, SYNC_CHANNELS } from '../sync/sync-config.ts'
40
48
  import type { SyncConfig, SyncConfigIssue, SyncTransportType } from '../sync/sync-config.ts'
41
- import type { ConfigAdapter, HostContext, SecretScanner } from './types.ts'
49
+ import type {
50
+ ConfigAdapter,
51
+ HostContext,
52
+ ImportAnalysis,
53
+ ImportDecisions,
54
+ ImportPlan,
55
+ ImportResult,
56
+ ItemResolution,
57
+ PathMapping,
58
+ SecretScanner,
59
+ } from './types.ts'
60
+ import type { Importer } from './importer.ts'
42
61
  import { runWithMutationLock } from '../utils/env-lock.ts'
43
62
  import { formatDateStamp } from '../utils/time.ts'
63
+ import { isSameOrChild } from '../utils/paths.ts'
64
+ import { restorePlanFingerprint } from './restore-plan-fingerprint.ts'
65
+ import { importPlanFingerprint, ModelPlanStore, syncMergeFingerprint } from './model-tool-plans.ts'
44
66
 
45
67
  /* ------------------------------------------------------------ 依赖与类型 */
46
68
 
@@ -56,8 +78,12 @@ export interface ModelToolsDeps {
56
78
  snapshotsDir: string
57
79
  /** 同步状态目录($DSH_HOME/dsh-config-manager/sync) */
58
80
  syncDir: string
59
- /** SyncEngine 工厂(git/webdav 按配置分支构造传输;与 host 路由同一来源) */
60
- makeSyncEngine: (cfg: SyncConfig) => SyncEngine
81
+ /**
82
+ * SyncEngine 工厂(git/webdav 按配置分支构造传输;与 host 路由同一来源)。
83
+ * D5:agent 侧按工具决定 optInSections(仅合并类工具带用户放行的可选分区),
84
+ * 推送/拉取仍走缺省(= 只 portable),与改动前的工具行为逐字节一致。
85
+ */
86
+ makeSyncEngine: (cfg: SyncConfig, opts?: { optInSections?: readonly SectionId[] }) => SyncEngine
61
87
  /** 插件版本(manifest.exporter.version) */
62
88
  exporterVersion?: string
63
89
  /**
@@ -67,6 +93,25 @@ export interface ModelToolsDeps {
67
93
  * 可选:缺省落回 Exporter 的 defaultSecretScanner()(无 scanText → 文件类分区不扫描,与修复前一致)。
68
94
  */
69
95
  scanner?: SecretScanner
96
+ /**
97
+ * D3:按 DSH credentials 槽位读同步密码(ENCRYPT / DECRYPT + 通道)。
98
+ * 值只在宿主内存里交给引擎,绝不进工具返回 / render / 日志。缺省 = 未接凭据服务。
99
+ */
100
+ syncPassword?: (kind: 'ENCRYPT' | 'DECRYPT', channel: SyncTransportType) => Promise<string | undefined>
101
+ /**
102
+ * D5:用户逐分区放行的可选分区(宿主 = selectionOptInSections(channel, true) 的 'auto' 档)。
103
+ * 缺省 = 空集;agent 侧永远再剔除 sessions(会话内容不受工具调用摆布)。
104
+ */
105
+ optInSections?: (channel: SyncTransportType) => readonly SectionId[]
106
+ /** D6:导入引擎工厂(与 HTTP 导入路由同一来源)。缺省 = 导入类工具返回 import-unavailable。 */
107
+ makeImporter?: () => Importer
108
+ /**
109
+ * D6:受控路径根(导入 ZIP 必须落在其中;与 /analyze、/plan 同一判据 isControlledPath)。
110
+ * 缺省 = 一律拒绝(fail-closed:宁可让用户走 GUI,也不让 agent 把任意路径交给解析器)。
111
+ */
112
+ roots?: readonly string[]
113
+ /** 计划句柄表(单测可注入假时钟;缺省每次 createModelTools 新建一个进程内表)。 */
114
+ planStore?: ModelPlanStore
70
115
  }
71
116
 
72
117
  /** 快照 id 校验:拒绝路径分隔符与 `.`/`..`(防 join(snapshotsDir, id) 越界)。 */
@@ -97,11 +142,11 @@ function describeConfigIssues(issues: readonly SyncConfigIssue[], channel: SyncT
97
142
  return own.map((issue) => `config issue ${issue.code} (${issue.channel}): ${issue.message}`).join('; ')
98
143
  }
99
144
 
100
- /** 解析同步引擎:channel 缺省取已配置的活动通道(git/webdav),未配置则抛可操作错误。 */
101
- async function resolveEngine(
145
+ /** 解析同步目标(通道 + 配置):channel 缺省取已配置的活动通道(git/webdav),未配置则抛可操作错误。 */
146
+ async function resolveSyncTarget(
102
147
  deps: ModelToolsDeps,
103
148
  channel?: SyncTransportType,
104
- ): Promise<{ engine: SyncEngine; channel: SyncTransportType }> {
149
+ ): Promise<{ cfg: SyncConfig; channel: SyncTransportType }> {
105
150
  // SEC-03:两处读取都收集 issues —— 否则「地址被安全校验拒掉」会被报成
106
151
  // 「sync-config.json 缺失或损坏」,让模型/用户反复重填同一个被拒地址。
107
152
  const issues: SyncConfigIssue[] = []
@@ -115,13 +160,211 @@ async function resolveEngine(
115
160
  // 无 issue = 真的没配(保持原文案);有 issue = 说清成因,绝不吞掉
116
161
  throw new Error(detail === '' ? base : `${base} — ${detail}`)
117
162
  }
118
- return { engine: deps.makeSyncEngine(cfg), channel: ch }
163
+ return { cfg, channel: ch }
164
+ }
165
+
166
+ /** 解析同步引擎(推送 / 拉取:缺省只同步 portable 分区,与改动前行为逐字节一致)。 */
167
+ async function resolveEngine(
168
+ deps: ModelToolsDeps,
169
+ channel?: SyncTransportType,
170
+ ): Promise<{ engine: SyncEngine; channel: SyncTransportType }> {
171
+ const target = await resolveSyncTarget(deps, channel)
172
+ return { engine: deps.makeSyncEngine(target.cfg), channel: target.channel }
173
+ }
174
+
175
+ /* ------------------------------------------------------------ 结构化结论与摘要 */
176
+
177
+ /** agent 侧永久排除的同步分区(sessions = 会话内容:路径/cwd/对话,绝不因一次工具调用被上下行)。 */
178
+ const AGENT_EXCLUDED_SECTIONS: readonly SectionId[] = ['sessions']
179
+
180
+ /**
181
+ * 工具失败的统一形状:模型据此判断「能不能重试、下一步做什么」,不需要解析自然语言。
182
+ * 成功路径保留各自业务字段(含 ok:true)。
183
+ */
184
+ export interface ModelToolFailure extends Record<string, JsonValue> {
185
+ ok: false
186
+ code: string
187
+ message: string
188
+ retryable: boolean
189
+ nextAction: string
190
+ }
191
+
192
+ function failure(
193
+ code: string,
194
+ messageKey: string,
195
+ nextActionKey: string,
196
+ retryable: boolean,
197
+ params?: Record<string, string>,
198
+ ): ModelToolFailure {
199
+ return {
200
+ ok: false,
201
+ code,
202
+ message: engineMsg(messageKey, params),
203
+ retryable,
204
+ nextAction: engineMsg(nextActionKey),
205
+ }
206
+ }
207
+
208
+ /** agent 侧可用可选分区:用户放行的 'auto' 档 ∩ 非永久排除项(顺序不变,供引擎判档)。 */
209
+ function agentOptInSections(deps: ModelToolsDeps, channel: SyncTransportType): SectionId[] {
210
+ const allowed = deps.optInSections?.(channel) ?? []
211
+ return allowed.filter((id) => !AGENT_EXCLUDED_SECTIONS.includes(id))
212
+ }
213
+
214
+ /**
215
+ * 导入 ZIP 必须落在受控根内:与 src/routes/route-support.ts 的 isControlledPath 同一判据
216
+ * (resolve + isSameOrChild)。roots 缺失 = 一律拒绝(fail-closed)。
217
+ */
218
+ function isControlledZipPath(zipPath: string, roots: readonly string[] | undefined): boolean {
219
+ if (roots === undefined || roots.length === 0) return false
220
+ const target = resolve(zipPath)
221
+ return roots.some((root) => isSameOrChild(target, resolve(root)))
222
+ }
223
+
224
+ /** 导入计划摘要里返回的条数上限:整份 items 可能上百条,全量下发会淹掉模型上下文。 */
225
+ const MAX_PLAN_ITEMS_RETURNED = 50
226
+
227
+ /** 分析摘要:只出判定 + 计数 + 文案(凭据只出 ref 名,值从不出现)。 */
228
+ function summarizeAnalysis(analysis: ImportAnalysis): JsonValue {
229
+ return {
230
+ valid: analysis.valid,
231
+ compatibility: analysis.compatibility,
232
+ encrypted: analysis.encrypted,
233
+ secretCount: analysis.secretCount,
234
+ sectionsInZip: analysis.sectionsInZip,
235
+ errorCount: analysis.errors.length,
236
+ errors: analysis.errors,
237
+ warnings: analysis.warnings,
238
+ pathIssueCount: analysis.pathIssues.length,
239
+ plugins: { installed: analysis.pluginSummary.installed, toInstall: analysis.pluginSummary.toInstall },
240
+ ...(analysis.sessionFormats === undefined
241
+ ? {}
242
+ : {
243
+ sessionFormats: {
244
+ target: analysis.sessionFormats.target,
245
+ unreadable: analysis.sessionFormats.unreadable.length,
246
+ sampled: analysis.sessionFormats.sampled,
247
+ },
248
+ }),
249
+ }
250
+ }
251
+
252
+ /** 计划摘要:按 kind 计数 + 前 MAX_PLAN_ITEMS_RETURNED 条 + 缺口计数(itemsTruncated)。 */
253
+ function summarizePlan(plan: ImportPlan): JsonValue {
254
+ const counts: Record<string, number> = {}
255
+ for (const item of plan.items) counts[item.kind] = (counts[item.kind] ?? 0) + 1
256
+ const items = plan.items.slice(0, MAX_PLAN_ITEMS_RETURNED).map((item) => ({
257
+ id: item.id,
258
+ kind: item.kind,
259
+ adapter: item.adapter,
260
+ description: item.description,
261
+ severity: item.severity,
262
+ ...(item.target === undefined ? {} : { target: item.target.ref }),
263
+ }))
264
+ return {
265
+ needsRestart: plan.needsRestart,
266
+ estimatedActions: plan.estimatedActions,
267
+ globalStrategy: plan.globalStrategy,
268
+ counts,
269
+ items,
270
+ itemsTruncated: plan.items.length - items.length,
271
+ missingSecrets: plan.missingSecrets.map((secret) => secret.ref),
272
+ }
273
+ }
274
+
275
+ /** 执行结果摘要:ok/回滚/重启 + 计数(逐项明细留在 journal 与 GUI 运行中心)。 */
276
+ function summarizeImportResult(result: ImportResult): JsonValue {
277
+ return {
278
+ ok: result.ok,
279
+ snapshotId: result.snapshotId ?? '',
280
+ needsRestart: result.needsRestart,
281
+ executedCount: result.executed.length,
282
+ missingSecrets: result.missingSecrets.length,
283
+ warnings: result.warnings,
284
+ rolledBack: result.rollback !== null,
285
+ ...(result.rollback === null ? {} : { rollbackFull: result.rollback.full }),
286
+ ...(result.ineffective === undefined ? {} : { ineffectiveCount: result.ineffective.length }),
287
+ }
288
+ }
289
+
290
+ /**
291
+ * 合并预览摘要:**不下发** localPreview / remotePreview / ancestorPreview 三列 ——
292
+ * 那是给 GUI 做逐键对比用的分段文本(每段 ≤2KiB),对模型只是噪声且可能带真实配置片段。
293
+ * 只给路径 + 冲突种类 + 原因,模型据此向用户转述「哪些分区要人裁决」。
294
+ */
295
+ function summarizeMergePreview(preview: MergePreview): JsonValue {
296
+ return {
297
+ snapshotId: preview.snapshotId,
298
+ hasAncestor: preview.hasAncestor,
299
+ summary: preview.summary,
300
+ sections: preview.sections.map((section) => ({
301
+ id: section.id,
302
+ decision: section.decision,
303
+ conflictCount: section.conflictCount,
304
+ ...(section.autoMerged === undefined ? {} : { autoMerged: section.autoMerged }),
305
+ conflicts: section.conflicts.map((conflict) => ({
306
+ path: conflict.path,
307
+ kind: conflict.kind,
308
+ ...(conflict.reason === undefined ? {} : { reason: conflict.reason }),
309
+ })),
310
+ })),
311
+ ...(preview.message === undefined ? {} : { message: preview.message }),
312
+ ...(preview.reason === undefined ? {} : { reason: preview.reason }),
313
+ }
314
+ }
315
+
316
+ /* ------------------------------------------------------------ 裁决值归一(D5/D6) */
317
+
318
+ const MERGE_ACTIONS = ['keepLocal', 'useRemote', 'useMerged', 'skip'] as const
319
+
320
+ function isMergeAction(value: string): value is MergeResolution['action'] {
321
+ return (MERGE_ACTIONS as readonly string[]).includes(value)
322
+ }
323
+
324
+ const ITEM_RESOLUTIONS = ['keepCurrent', 'useImported', 'review'] as const
325
+
326
+ /** 只接受已知裁决值:乱填的键值一律丢弃(宁缺不乱,createImportPlan 按缺省语义处理)。 */
327
+ function normalizeResolutions(input: Record<string, JsonValue> | undefined): Record<string, ItemResolution> {
328
+ const out: Record<string, ItemResolution> = {}
329
+ if (input === undefined) return out
330
+ for (const [key, value] of Object.entries(input)) {
331
+ if (typeof value !== 'string') continue
332
+ if (!(ITEM_RESOLUTIONS as readonly string[]).includes(value)) continue
333
+ out[key] = value as ItemResolution
334
+ }
335
+ return out
336
+ }
337
+
338
+ const MAPPING_TARGETS = ['workspaces', 'mcp', 'pluginConfig', 'skills'] as const
339
+
340
+ type MappingTarget = (typeof MAPPING_TARGETS)[number]
341
+
342
+ function isMappingTarget(value: string): value is MappingTarget {
343
+ return (MAPPING_TARGETS as readonly string[]).includes(value)
344
+ }
345
+
346
+ /** 只留非空映射,并丢弃非法的 appliesTo 取值(缺省 / 空 appliesTo 合法 = 不作用到任何分区)。 */
347
+ function normalizePathMappings(
348
+ input: readonly { oldPrefix: string; newPrefix: string; appliesTo?: readonly string[] }[] | undefined,
349
+ ): PathMapping[] {
350
+ if (input === undefined) return []
351
+ return input
352
+ .filter((mapping) => mapping.oldPrefix !== '' && mapping.newPrefix !== '')
353
+ .map((mapping) => ({
354
+ oldPrefix: mapping.oldPrefix,
355
+ newPrefix: mapping.newPrefix,
356
+ appliesTo: (mapping.appliesTo ?? []).filter(isMappingTarget),
357
+ }))
119
358
  }
120
359
 
121
360
  /* ------------------------------------------------------------ 纯编排函数 */
122
361
 
123
- /** 5 个工具的纯编排实现(可独立测试,不依赖 Cordis ctx)。所有返回均为 JsonValue(可序列化、无 undefined)。 */
362
+ /** 9 个工具的纯编排实现(可独立测试,不依赖 Cordis ctx)。所有返回均为 JsonValue(可序列化、无 undefined)。 */
124
363
  export function createModelTools(deps: ModelToolsDeps) {
364
+ // 计划句柄表(D2/D5/D6):进程内、30 分钟 TTL、上限 8。只存「重放材料」——
365
+ // 恢复 → 快照 id;合并 → 通道 + 快照 id;导入 → ZIP 路径 + 决策 JSON。
366
+ // 绝不放密码或凭据值:凭据只在宿主内单次调用栈上出现,不落表、不落盘。
367
+ const plans = deps.planStore ?? new ModelPlanStore()
125
368
  return {
126
369
  /** 全量备份到 exports 目录(默认不含 secret;password 可选加密,仅内存)。 */
127
370
  async backup(input: { only?: SectionId[]; password?: string }): Promise<JsonValue> {
@@ -178,11 +421,11 @@ export function createModelTools(deps: ModelToolsDeps) {
178
421
  },
179
422
 
180
423
  /**
181
- * 恢复到指定快照。缺省只 planRestore(零写入)预览;
182
- * confirm:true 才真实执行 restore(覆盖/删除 $DSH_HOME 文件并卸载导入期间新增插件)。
424
+ * 恢复到指定快照。缺省只 planRestore(零写入)预览并**返回 planId**;
425
+ * 真实执行必须 confirm:true 且带回预览给的 planId —— 计划在预览后变了就拒绝(零写入)。
183
426
  */
184
- async restore(input: { snapshotId: string; confirm?: boolean }): Promise<JsonValue> {
185
- const { snapshotId, confirm } = input
427
+ async restore(input: { snapshotId: string; planId?: string; confirm?: boolean }): Promise<JsonValue> {
428
+ const { snapshotId, planId, confirm } = input
186
429
  assertValidSnapshotId(snapshotId)
187
430
  if (!(await snapshotDirExists(deps, snapshotId))) {
188
431
  throw new Error(engineMsg('core.modelTools.snapshotNotFound', { id: snapshotId }))
@@ -203,10 +446,14 @@ export function createModelTools(deps: ModelToolsDeps) {
203
446
  currentDshVersion: deps.host.dshVersion,
204
447
  }
205
448
  const plan: RestorePlan = await planRestore(restoreOpts)
449
+ const fingerprint = restorePlanFingerprint(plan)
206
450
  if (confirm !== true) {
451
+ // 预览即登记计划(供执行侧比对);同一份盘面重复预览 → 同一 planId(覆盖写入,幂等)。
452
+ plans.set('restore', fingerprint, { snapshotId })
207
453
  return {
208
454
  dryRun: true,
209
455
  snapshotId: plan.snapshotId,
456
+ planId: fingerprint,
210
457
  createdAt: plan.createdAt,
211
458
  summary: {
212
459
  hostFileRestores: plan.summary.hostFileRestores,
@@ -225,6 +472,14 @@ export function createModelTools(deps: ModelToolsDeps) {
225
472
  })),
226
473
  }
227
474
  }
475
+ // D2 预览-执行一致性:执行必须带预览给的 planId(缺 = plan-required,不符 = plan-changed)。
476
+ // 两处都在**写盘之前**判定;锁内还会按当前盘面重算一次(GUI 恢复路由 409 的同款语义)。
477
+ if (planId === undefined || planId === '') {
478
+ return failure('plan-required', 'core.modelTools.errPlanRequired', 'core.modelTools.nextRepreview', true)
479
+ }
480
+ if (planId !== fingerprint) {
481
+ return failure('plan-changed', 'core.modelTools.errPlanChanged', 'core.modelTools.nextRepreview', true)
482
+ }
228
483
  // Step 3 P0-A:真实 model-restore 在已持锁下创建 journal(不 double-acquire)
229
484
  // ctx = journal 上下文(可选):交给 restore() 逐动作 WAL,崩溃后 reconcile 可判进度
230
485
  const doRestore = async (ctx?: RestoreJournalPort): Promise<RestoreReport> =>
@@ -236,20 +491,30 @@ export function createModelTools(deps: ModelToolsDeps) {
236
491
  ? null
237
492
  : await probeRestoreResume({ store: phase3.store, restoreOpts, allowedOperationTypes: ['model-restore'] })
238
493
  const resumeAllowed = resumeProbe !== null && resumeProbe.ok
239
- const report: RestoreReport = await runWithMutationLock(
494
+ // 锁内重算:预览到执行之间盘面可能变了 —— 判定放在持锁之后(GUI 恢复路由 409 的同一位置)。
495
+ type RestoreOutcome = { kind: 'ok'; report: RestoreReport } | { kind: 'changed' }
496
+ const outcome: RestoreOutcome = await runWithMutationLock(
240
497
  deps.host.mutationLock,
241
498
  { op: 'model-restore', target: snapshotId, isBlocked: () => (deps.host.safeModeIsBlocked?.() ?? false) && !resumeAllowed },
242
- async (lockCtx) => {
499
+ async (lockCtx): Promise<RestoreOutcome> => {
500
+ const fresh = await planRestore(restoreOpts)
501
+ if (restorePlanFingerprint(fresh) !== planId) return { kind: 'changed' }
243
502
  if (phase3 !== undefined && lockCtx !== null) {
244
503
  const out = await runRestoreWithResume<RestoreReport>({
245
504
  store: phase3.store, restoreOpts, operationType: 'model-restore',
246
505
  allowedOperationTypes: ['model-restore'], lockCtx, phase3,
247
506
  })
248
- return out.report
507
+ return { kind: 'ok', report: out.report }
249
508
  }
250
- return doRestore()
509
+ return { kind: 'ok', report: await doRestore() }
251
510
  },
252
511
  )
512
+ if (outcome.kind === 'changed') {
513
+ return failure('plan-changed', 'core.modelTools.errPlanChanged', 'core.modelTools.nextRepreview', true)
514
+ }
515
+ // 计划已消费:同一 planId 不能重放(否则「执行两次」与「执行一次」无法区分)。
516
+ plans.delete(planId)
517
+ const report = outcome.report
253
518
  return {
254
519
  dryRun: false,
255
520
  snapshotId: report.snapshotId,
@@ -261,25 +526,50 @@ export function createModelTools(deps: ModelToolsDeps) {
261
526
  }
262
527
  },
263
528
 
264
- /** 手动推送同步(写远端)。encrypt/includeSecrets 由引擎强制约束(密钥绝不明文进通道)。 */
529
+ /**
530
+ * 手动推送同步(写远端)。密钥绝不明文进通道:
531
+ * D4 起 includeSecrets 恒 false —— agent 传 true 直接拒绝(模型无权让凭据值上行)。
532
+ */
265
533
  async syncPush(input: {
266
534
  channel?: SyncTransportType
267
535
  sections?: SectionId[]
268
536
  encrypt?: boolean
269
537
  includeSecrets?: boolean
270
538
  password?: string
539
+ force?: boolean
271
540
  }): Promise<JsonValue> {
272
- const { engine } = await resolveEngine(deps, input.channel)
541
+ // D4:agent 永不触发凭据上行。参数保留在 schema 只为给出**可读的拒绝**,
542
+ // 而不是让模型猜「为什么 includeSecrets 没生效」。
543
+ if (input.includeSecrets === true) {
544
+ return failure(
545
+ 'include-secrets-forbidden',
546
+ 'core.modelTools.errIncludeSecrets',
547
+ 'core.modelTools.nextRetryWithoutSecrets',
548
+ false,
549
+ )
550
+ }
551
+ const { engine, channel } = await resolveEngine(deps, input.channel)
273
552
  const sections = input.sections === undefined ? undefined : filterSectionIds(input.sections)
274
553
  const encrypt = input.encrypt === true
275
- const includeSecrets = input.includeSecrets === true
554
+ // D3:密码来源优先级 = 已保存的 DSH credentials 槽位 → 入参 password(deprecated)→ 缺失即拒绝。
555
+ // 顺序刻意:模型不该把明文密码写进工具入参(那会进会话历史);已存槽位才是常态来源。
556
+ const stored = encrypt ? await deps.syncPassword?.('ENCRYPT', channel) : undefined
557
+ const password = stored ?? (input.password === undefined || input.password === '' ? undefined : input.password)
558
+ if (encrypt && password === undefined) {
559
+ return failure(
560
+ 'sync-password-missing',
561
+ 'core.modelTools.errSyncPasswordMissing',
562
+ 'core.modelTools.nextSaveSyncPassword',
563
+ true,
564
+ { channel },
565
+ )
566
+ }
276
567
  // Phase 2 锁:push 写远端 + 本地散文件 + sync-state,属 GLOBAL mutation。
277
568
  // Step 3 P0-A:外部 push 记 intent journal(crash 后不可证明 → NEEDS_ATTENTION,不自动重推)。
278
569
  const doPush = () => engine.push({
279
570
  ...(sections === undefined ? {} : { sections }),
280
- ...(encrypt || includeSecrets
281
- ? { encrypt: true, includeSecrets, password: input.password ?? '' }
282
- : {}),
571
+ ...(encrypt ? { encrypt: true, includeSecrets: false, password: password ?? '' } : {}),
572
+ ...(input.force === true ? { force: true } : {}),
283
573
  })
284
574
  const report = await runWithMutationLock(deps.host.mutationLock, { op: 'model-sync-push', isBlocked: () => deps.host.safeModeIsBlocked?.() ?? false }, async (lockCtx) => {
285
575
  if (deps.host.phase3Recovery !== undefined && lockCtx !== null) {
@@ -298,23 +588,30 @@ export function createModelTools(deps: ModelToolsDeps) {
298
588
  snapshotId: report.snapshotId,
299
589
  sections: report.sections,
300
590
  warnings: report.warnings,
591
+ // 前置检测拒绝(远端已被别的设备推进)不是通道故障:必须显式透传,
592
+ // 否则模型会把它当成「推送成功但内容为空」继续往下走。
593
+ ...(report.conflict === true ? { conflict: true } : {}),
594
+ ...(report.adoptedBase === undefined ? {} : { adoptedBase: report.adoptedBase }),
301
595
  ...(report.message === undefined ? {} : { message: report.message }),
596
+ ...(encrypt ? { passwordSource: stored === undefined ? 'argument' : 'stored' } : {}),
302
597
  }
303
598
  },
304
599
 
305
- /** 拉取差异预览(零写入:只下载 + analyze + plan 出差异报告)。 */
600
+ /** 拉取差异预览(零写入:只下载 + analyze + plan 出差异报告)。解密密码同样优先取已存槽位(D3)。 */
306
601
  async syncPull(input: {
307
602
  channel?: SyncTransportType
308
603
  snapshotId?: string
309
604
  strategy?: 'merge' | 'replace' | 'skipExisting'
310
605
  password?: string
311
606
  }): Promise<JsonValue> {
312
- const { engine } = await resolveEngine(deps, input.channel)
607
+ const { engine, channel } = await resolveEngine(deps, input.channel)
313
608
  const strategy = input.strategy === 'replace' || input.strategy === 'skipExisting' ? input.strategy : 'merge'
609
+ const stored = await deps.syncPassword?.('DECRYPT', channel)
610
+ const password = stored ?? (input.password === undefined || input.password === '' ? undefined : input.password)
314
611
  const report = await engine.pull({
315
612
  strategy,
316
613
  ...(input.snapshotId === undefined || input.snapshotId === '' ? {} : { snapshotId: input.snapshotId }),
317
- ...(input.password === undefined || input.password === '' ? {} : { password: input.password }),
614
+ ...(password === undefined ? {} : { password }),
318
615
  })
319
616
  return {
320
617
  ok: report.ok,
@@ -330,6 +627,210 @@ export function createModelTools(deps: ModelToolsDeps) {
330
627
  ...(report.message === undefined ? {} : { message: report.message }),
331
628
  }
332
629
  },
630
+
631
+ /* ---------------- D5:三方合并(落地开放,sessions 永久排除) ---------------- */
632
+
633
+ /**
634
+ * 三方合并预览(只读):下载远端快照 + 分类 + 出裁决清单,零写入。
635
+ * 返回的 planId 是这份预览的指纹:config_sync_apply 必须带回来,落地前在锁内重跑预览比对。
636
+ * 刻意不下发 localPreview / remotePreview / ancestorPreview —— 那是 GUI 逐键对比用的分段文本。
637
+ */
638
+ async syncPreview(input: { channel?: SyncTransportType; snapshotId?: string; password?: string }): Promise<JsonValue> {
639
+ const { cfg, channel } = await resolveSyncTarget(deps, input.channel)
640
+ // D5:只按用户放行的 'auto' 档分区建引擎;sessions 已在 agentOptInSections 里永久剔除。
641
+ const engine = deps.makeSyncEngine(cfg, { optInSections: agentOptInSections(deps, channel) })
642
+ const stored = await deps.syncPassword?.('DECRYPT', channel)
643
+ const password = stored ?? (input.password === undefined || input.password === '' ? undefined : input.password)
644
+ const opts = {
645
+ ...(input.snapshotId === undefined || input.snapshotId === '' ? {} : { snapshotId: input.snapshotId }),
646
+ ...(password === undefined ? {} : { password }),
647
+ }
648
+ const preview = await engine.previewMerge(opts)
649
+ const planId = syncMergeFingerprint(preview)
650
+ plans.set('sync-merge', planId, {
651
+ channel,
652
+ ...(input.snapshotId === undefined ? {} : { snapshotId: input.snapshotId }),
653
+ })
654
+ return { ok: preview.ok, planId, preview: summarizeMergePreview(preview) }
655
+ },
656
+
657
+ /**
658
+ * 落地三方合并:必须带 config_sync_preview 返回的 planId(缺失/过期 → plan-*,零写入)。
659
+ * 锁内重跑预览比对指纹 —— 预览后远端或本机变了就拒绝,不把旧裁决硬套到新盘面。
660
+ */
661
+ async syncApply(input: {
662
+ planId: string
663
+ resolutions: { id: string; action: string }[]
664
+ password?: string
665
+ }): Promise<JsonValue> {
666
+ const record = plans.get(input.planId)
667
+ if (record === undefined || record.kind !== 'sync-merge') {
668
+ return failure('plan-expired', 'core.modelTools.errPlanExpired', 'core.modelTools.nextRepreview', true)
669
+ }
670
+ const channel = parseSyncChannel(record.payload.channel ?? '')
671
+ if (channel === null || channel === undefined) {
672
+ return failure('plan-expired', 'core.modelTools.errPlanExpired', 'core.modelTools.nextRepreview', true)
673
+ }
674
+ const resolutions: MergeResolution[] = []
675
+ for (const entry of input.resolutions) {
676
+ if (!isMergeAction(entry.action)) {
677
+ return failure(
678
+ 'invalid-resolution',
679
+ 'core.modelTools.errInvalidResolution',
680
+ 'core.modelTools.nextFixResolution',
681
+ true,
682
+ { action: entry.action },
683
+ )
684
+ }
685
+ resolutions.push({ id: entry.id as SectionId, action: entry.action })
686
+ }
687
+ const { cfg } = await resolveSyncTarget(deps, channel)
688
+ const engine = deps.makeSyncEngine(cfg, { optInSections: agentOptInSections(deps, channel) })
689
+ const stored = await deps.syncPassword?.('DECRYPT', channel)
690
+ const password = stored ?? (input.password === undefined || input.password === '' ? undefined : input.password)
691
+ const snapshotId = record.payload.snapshotId
692
+ const opts = {
693
+ ...(snapshotId === undefined || snapshotId === '' ? {} : { snapshotId }),
694
+ ...(password === undefined ? {} : { password }),
695
+ }
696
+ type ApplyOutcome =
697
+ | { kind: 'changed' }
698
+ | { kind: 'ok'; report: ApplyMergeResolutionsReport; ignored: string[] }
699
+ const outcome: ApplyOutcome = await runWithMutationLock(
700
+ deps.host.mutationLock,
701
+ { op: 'model-sync-apply', target: channel, isBlocked: () => deps.host.safeModeIsBlocked?.() ?? false },
702
+ async (): Promise<ApplyOutcome> => {
703
+ const fresh = await engine.previewMerge(opts)
704
+ if (syncMergeFingerprint(fresh) !== input.planId) return { kind: 'changed' }
705
+ const known = new Set(fresh.sections.map((section) => section.id))
706
+ const decisions = resolutions.filter((resolution) => known.has(resolution.id))
707
+ const ignored = resolutions
708
+ .filter((resolution) => !known.has(resolution.id))
709
+ .map((resolution) => resolution.id as string)
710
+ const report = await engine.applyMergeResolutions(decisions, opts)
711
+ return { kind: 'ok', report, ignored }
712
+ },
713
+ )
714
+ if (outcome.kind === 'changed') {
715
+ return failure('plan-changed', 'core.modelTools.errPlanChanged', 'core.modelTools.nextRepreview', true)
716
+ }
717
+ plans.delete(input.planId)
718
+ const report = outcome.report
719
+ return {
720
+ ok: report.ok,
721
+ applied: report.applied,
722
+ restoreId: report.restoreId,
723
+ rolledBack: report.rolledBack,
724
+ ...(report.rollbackFull === undefined ? {} : { rollbackFull: report.rollbackFull }),
725
+ warnings: report.warnings,
726
+ pendingConflicts: report.pendingConflicts,
727
+ ...(outcome.ignored.length === 0 ? {} : { ignoredResolutions: outcome.ignored }),
728
+ }
729
+ },
730
+
731
+ /* ---------------- D6:导入计划 + 执行(句柄 + 结构化决策,不接受密码/凭据值) ---------------- */
732
+
733
+ /**
734
+ * 生成导入计划(只读):分析归档 + 合并冲突决策 / 路径映射,零写入。
735
+ * 加密归档直接拒绝 —— 解密需要密码,而密码不进 agent 面(该场景走 GUI 导入)。
736
+ */
737
+ async importPlan(input: {
738
+ zipPath: string
739
+ strategy?: 'merge' | 'replace' | 'skipExisting'
740
+ resolutions?: Record<string, JsonValue>
741
+ pathMappings?: readonly { oldPrefix: string; newPrefix: string; appliesTo?: readonly string[] }[]
742
+ }): Promise<JsonValue> {
743
+ const importer = deps.makeImporter?.()
744
+ if (importer === undefined) {
745
+ return failure('import-unavailable', 'core.modelTools.errImportUnavailable', 'core.modelTools.nextUseGuiImport', false)
746
+ }
747
+ if (!isControlledZipPath(input.zipPath, deps.roots)) {
748
+ return failure(
749
+ 'path-not-controlled',
750
+ 'core.modelTools.errPathNotControlled',
751
+ 'core.modelTools.nextPickControlledZip',
752
+ false,
753
+ { path: input.zipPath },
754
+ )
755
+ }
756
+ const decisions: ImportDecisions = {
757
+ strategy: input.strategy === 'replace' || input.strategy === 'skipExisting' ? input.strategy : 'merge',
758
+ resolutions: normalizeResolutions(input.resolutions),
759
+ pathMappings: normalizePathMappings(input.pathMappings),
760
+ }
761
+ const analysis = await importer.analyzeImport(input.zipPath)
762
+ if (analysis.encrypted) {
763
+ return failure('encrypted-archive', 'core.modelTools.errEncryptedArchive', 'core.modelTools.nextUseGuiImport', false)
764
+ }
765
+ if (!analysis.valid) {
766
+ return {
767
+ ok: false,
768
+ code: 'archive-invalid',
769
+ message: analysis.errors.join('; '),
770
+ retryable: false,
771
+ nextAction: engineMsg('core.modelTools.nextUseGuiImport'),
772
+ analysis: summarizeAnalysis(analysis),
773
+ }
774
+ }
775
+ const plan = await importer.createImportPlan(input.zipPath, decisions)
776
+ const planId = importPlanFingerprint(plan, decisions)
777
+ plans.set('import', planId, { zipPath: input.zipPath, decisionsJson: JSON.stringify(decisions) })
778
+ return {
779
+ ok: true,
780
+ planId,
781
+ zipPath: input.zipPath,
782
+ analysis: summarizeAnalysis(analysis),
783
+ plan: summarizePlan(plan),
784
+ }
785
+ },
786
+
787
+ /**
788
+ * 执行导入计划:必须带 config_import_plan 返回的 planId + confirm:true。
789
+ * 执行前按存档决策重算计划比对指纹(归档被换 / 本机状态变了 → 拒绝,零写入)。
790
+ */
791
+ async importApply(input: { planId: string; confirm?: boolean; rollbackOnError?: boolean }): Promise<JsonValue> {
792
+ if (input.confirm !== true) {
793
+ return failure('confirm-required', 'core.modelTools.errConfirmRequired', 'core.modelTools.nextPassConfirm', true)
794
+ }
795
+ const record = plans.get(input.planId)
796
+ if (record === undefined || record.kind !== 'import') {
797
+ return failure('plan-expired', 'core.modelTools.errPlanExpired', 'core.modelTools.nextRepreview', true)
798
+ }
799
+ const importer = deps.makeImporter?.()
800
+ if (importer === undefined) {
801
+ return failure('import-unavailable', 'core.modelTools.errImportUnavailable', 'core.modelTools.nextUseGuiImport', false)
802
+ }
803
+ const zipPath = record.payload.zipPath ?? ''
804
+ if (!isControlledZipPath(zipPath, deps.roots)) {
805
+ return failure(
806
+ 'path-not-controlled',
807
+ 'core.modelTools.errPathNotControlled',
808
+ 'core.modelTools.nextPickControlledZip',
809
+ false,
810
+ { path: zipPath },
811
+ )
812
+ }
813
+ let decisions: ImportDecisions
814
+ try {
815
+ decisions = JSON.parse(record.payload.decisionsJson ?? '') as ImportDecisions
816
+ } catch {
817
+ return failure('plan-expired', 'core.modelTools.errPlanExpired', 'core.modelTools.nextRepreview', true)
818
+ }
819
+ const fresh = await importer.createImportPlan(zipPath, decisions)
820
+ if (importPlanFingerprint(fresh, decisions) !== input.planId) {
821
+ return failure('plan-changed', 'core.modelTools.errPlanChanged', 'core.modelTools.nextRepreview', true)
822
+ }
823
+ const result = await runWithMutationLock(
824
+ deps.host.mutationLock,
825
+ { op: 'model-import-apply', target: zipPath, isBlocked: () => deps.host.safeModeIsBlocked?.() ?? false },
826
+ async () => importer.executeImportPlan(zipPath, fresh, {
827
+ confirm: true,
828
+ ...(input.rollbackOnError === undefined ? {} : { rollbackOnError: input.rollbackOnError }),
829
+ }),
830
+ )
831
+ plans.delete(input.planId)
832
+ return summarizeImportResult(result)
833
+ },
333
834
  }
334
835
  }
335
836
 
@@ -337,7 +838,7 @@ export function createModelTools(deps: ModelToolsDeps) {
337
838
 
338
839
  type ModelTools = ReturnType<typeof createModelTools>
339
840
 
340
- /** 把 5 个模型工具注册进 ctx.tools;tools 服务未组合时静默跳过(不崩溃)。 */
841
+ /** 把 9 个模型工具注册进 ctx.tools;tools 服务未组合时静默跳过(不崩溃)。 */
341
842
  export function registerModelTools(ctx: Context, deps: ModelToolsDeps): void {
342
843
  const toolsSvc = ctx.get('tools')
343
844
  if (toolsSvc === null || toolsSvc === undefined || typeof toolsSvc !== 'object') {
@@ -383,6 +884,8 @@ export function registerModelTools(ctx: Context, deps: ModelToolsDeps): void {
383
884
  name: 'config_list_snapshots',
384
885
  description: engineMsg('core.modelTools.listSnapshotsToolDesc'),
385
886
  parameters: {},
887
+ // 只读工具:并发调用安全(宿主可并行调度)。
888
+ isConcurrencySafe: () => true,
386
889
  output: {
387
890
  schema: {
388
891
  type: 'json',
@@ -405,6 +908,10 @@ export function registerModelTools(ctx: Context, deps: ModelToolsDeps): void {
405
908
  required: true,
406
909
  description: engineMsg('core.modelTools.restoreSnapshotIdParam'),
407
910
  },
911
+ planId: {
912
+ type: 'string',
913
+ description: engineMsg('core.modelTools.restorePlanIdParam'),
914
+ },
408
915
  confirm: {
409
916
  type: 'boolean',
410
917
  description: engineMsg('core.modelTools.restoreConfirmParam'),
@@ -444,7 +951,11 @@ export function registerModelTools(ctx: Context, deps: ModelToolsDeps): void {
444
951
  },
445
952
  password: {
446
953
  type: 'string',
447
- description: engineMsg('core.modelTools.syncPushPasswordParam'),
954
+ description: engineMsg('core.modelTools.syncPushPasswordDeprecatedParam'),
955
+ },
956
+ force: {
957
+ type: 'boolean',
958
+ description: engineMsg('core.modelTools.syncPushForceParam'),
448
959
  },
449
960
  },
450
961
  output: {
@@ -480,6 +991,8 @@ export function registerModelTools(ctx: Context, deps: ModelToolsDeps): void {
480
991
  description: engineMsg('core.modelTools.syncPullPasswordParam'),
481
992
  },
482
993
  },
994
+ // 只读工具:pull 只下载 + 分析,零写入(并发调用安全)。
995
+ isConcurrencySafe: () => true,
483
996
  output: {
484
997
  schema: { type: 'json', description: engineMsg('core.modelTools.syncPullOutputDesc') },
485
998
  render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
@@ -489,5 +1002,164 @@ export function registerModelTools(ctx: Context, deps: ModelToolsDeps): void {
489
1002
  },
490
1003
  }))
491
1004
 
1005
+ register(defineTool({
1006
+ name: 'config_sync_preview',
1007
+ description:
1008
+ engineMsg('core.modelTools.syncPreviewToolDesc'),
1009
+ parameters: {
1010
+ channel: {
1011
+ type: 'string',
1012
+ enum: [...SYNC_CHANNELS],
1013
+ description: engineMsg('core.modelTools.channelParam'),
1014
+ },
1015
+ snapshotId: {
1016
+ type: 'string',
1017
+ description: engineMsg('core.modelTools.syncPreviewSnapshotIdParam'),
1018
+ },
1019
+ password: {
1020
+ type: 'string',
1021
+ description: engineMsg('core.modelTools.syncPreviewPasswordParam'),
1022
+ },
1023
+ },
1024
+ isConcurrencySafe: () => true,
1025
+ output: {
1026
+ schema: { type: 'json', description: engineMsg('core.modelTools.syncPreviewOutputDesc') },
1027
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
1028
+ },
1029
+ async execute(args) {
1030
+ return tools.syncPreview(args)
1031
+ },
1032
+ }))
1033
+
1034
+ register(defineTool({
1035
+ name: 'config_sync_apply',
1036
+ description:
1037
+ engineMsg('core.modelTools.syncApplyToolDesc'),
1038
+ parameters: {
1039
+ planId: {
1040
+ type: 'string',
1041
+ required: true,
1042
+ description: engineMsg('core.modelTools.syncApplyPlanIdParam'),
1043
+ },
1044
+ resolutions: {
1045
+ type: 'array',
1046
+ required: true,
1047
+ items: {
1048
+ type: 'object',
1049
+ properties: {
1050
+ id: {
1051
+ type: 'string',
1052
+ required: true,
1053
+ description: engineMsg('core.modelTools.syncApplyResolutionIdParam'),
1054
+ },
1055
+ action: {
1056
+ type: 'string',
1057
+ required: true,
1058
+ enum: [...MERGE_ACTIONS],
1059
+ description: engineMsg('core.modelTools.syncApplyResolutionActionParam'),
1060
+ },
1061
+ },
1062
+ additionalProperties: false,
1063
+ },
1064
+ description: engineMsg('core.modelTools.syncApplyResolutionsParam'),
1065
+ },
1066
+ password: {
1067
+ type: 'string',
1068
+ description: engineMsg('core.modelTools.syncApplyPasswordParam'),
1069
+ },
1070
+ },
1071
+ output: {
1072
+ schema: { type: 'json', description: engineMsg('core.modelTools.syncApplyOutputDesc') },
1073
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
1074
+ },
1075
+ async execute(args) {
1076
+ return tools.syncApply(args)
1077
+ },
1078
+ }))
1079
+
1080
+ register(defineTool({
1081
+ name: 'config_import_plan',
1082
+ description:
1083
+ engineMsg('core.modelTools.importPlanToolDesc'),
1084
+ parameters: {
1085
+ zipPath: {
1086
+ type: 'string',
1087
+ required: true,
1088
+ description: engineMsg('core.modelTools.importPlanZipPathParam'),
1089
+ },
1090
+ strategy: {
1091
+ type: 'string',
1092
+ enum: ['merge', 'replace', 'skipExisting'],
1093
+ description: engineMsg('core.modelTools.importPlanStrategyParam'),
1094
+ },
1095
+ resolutions: {
1096
+ type: 'object',
1097
+ additionalProperties: true,
1098
+ description: engineMsg('core.modelTools.importPlanResolutionsParam'),
1099
+ },
1100
+ pathMappings: {
1101
+ type: 'array',
1102
+ items: {
1103
+ type: 'object',
1104
+ properties: {
1105
+ oldPrefix: {
1106
+ type: 'string',
1107
+ required: true,
1108
+ description: engineMsg('core.modelTools.importPlanMappingOldParam'),
1109
+ },
1110
+ newPrefix: {
1111
+ type: 'string',
1112
+ required: true,
1113
+ description: engineMsg('core.modelTools.importPlanMappingNewParam'),
1114
+ },
1115
+ appliesTo: {
1116
+ type: 'array',
1117
+ items: { type: 'string', enum: [...MAPPING_TARGETS] },
1118
+ description: engineMsg('core.modelTools.importPlanMappingAppliesToParam'),
1119
+ },
1120
+ },
1121
+ additionalProperties: false,
1122
+ },
1123
+ description: engineMsg('core.modelTools.importPlanPathMappingsParam'),
1124
+ },
1125
+ },
1126
+ isConcurrencySafe: () => true,
1127
+ output: {
1128
+ schema: { type: 'json', description: engineMsg('core.modelTools.importPlanOutputDesc') },
1129
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
1130
+ },
1131
+ async execute(args) {
1132
+ return tools.importPlan(args)
1133
+ },
1134
+ }))
1135
+
1136
+ register(defineTool({
1137
+ name: 'config_import_apply',
1138
+ description:
1139
+ engineMsg('core.modelTools.importApplyToolDesc'),
1140
+ parameters: {
1141
+ planId: {
1142
+ type: 'string',
1143
+ required: true,
1144
+ description: engineMsg('core.modelTools.importApplyPlanIdParam'),
1145
+ },
1146
+ confirm: {
1147
+ type: 'boolean',
1148
+ description: engineMsg('core.modelTools.importApplyConfirmParam'),
1149
+ },
1150
+ rollbackOnError: {
1151
+ type: 'boolean',
1152
+ description: engineMsg('core.modelTools.importApplyRollbackOnErrorParam'),
1153
+ },
1154
+ },
1155
+ output: {
1156
+ schema: { type: 'json', description: engineMsg('core.modelTools.importApplyOutputDesc') },
1157
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
1158
+ },
1159
+ async execute(args) {
1160
+ return tools.importApply(args)
1161
+ },
1162
+ }))
1163
+
492
1164
  ctx.effect(() => () => { for (const d of disposers) d() }, 'config-manager: model tools')
493
1165
  }