vc-extras 0.0.0-stage → 0.1.1

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 (243) hide show
  1. package/README.md +128 -3
  2. package/agent-install.mjs +159 -0
  3. package/agents/tester.md +23 -0
  4. package/install-extras.mjs +66 -0
  5. package/install-menu.mjs +42 -0
  6. package/install-skills.mjs +112 -0
  7. package/package.json +72 -6
  8. package/plugin-registry.mjs +73 -0
  9. package/plugins/config-ui/index.ts +160 -0
  10. package/plugins/config-ui/lib/arguments.mjs +24 -0
  11. package/plugins/config-ui/lib/documents.mjs +67 -0
  12. package/plugins/config-ui/lib/frontmatter.mjs +91 -0
  13. package/plugins/config-ui/lib/open.mjs +17 -0
  14. package/plugins/config-ui/lib/ownership.mjs +99 -0
  15. package/plugins/config-ui/lib/page.mjs +11 -0
  16. package/plugins/config-ui/lib/patch.mjs +36 -0
  17. package/plugins/config-ui/lib/paths.mjs +14 -0
  18. package/plugins/config-ui/lib/plugin-fields.mjs +86 -0
  19. package/plugins/config-ui/lib/plugin-validation.mjs +28 -0
  20. package/plugins/config-ui/lib/redaction.mjs +8 -0
  21. package/plugins/config-ui/lib/registry.mjs +282 -0
  22. package/plugins/config-ui/lib/secrets.mjs +45 -0
  23. package/plugins/config-ui/lib/server.mjs +251 -0
  24. package/plugins/config-ui/lib/sources.mjs +96 -0
  25. package/plugins/config-ui/lib/state.mjs +157 -0
  26. package/plugins/config-ui/lib/themes.mjs +113 -0
  27. package/plugins/config-ui/lib/writer.mjs +691 -0
  28. package/plugins/config-ui/package.json +12 -0
  29. package/plugins/config-ui/project-local-owner.ts +106 -0
  30. package/plugins/config-ui/vc-extras.plugin.json +13 -0
  31. package/plugins/config-ui/web/app.mjs +997 -0
  32. package/plugins/config-ui/web/index.html +342 -0
  33. package/plugins/pi-blackhole/vc-extras.plugin.json +12 -0
  34. package/plugins/pi-btw/vc-extras.plugin.json +12 -0
  35. package/plugins/pi-claude-code/vc-extras.plugin.json +12 -0
  36. package/plugins/pi-fff/vc-extras.plugin.json +12 -0
  37. package/plugins/pi-jev-auto-mode/vc-extras.plugin.json +12 -0
  38. package/plugins/pi-mcp-adapter/vc-extras.plugin.json +12 -0
  39. package/plugins/pi-web-access/vc-extras.plugin.json +12 -0
  40. package/plugins/vc-ask/claude-hook.mjs +37 -0
  41. package/plugins/vc-ask/codex-native.mjs +28 -0
  42. package/plugins/vc-ask/host-channel.mjs +75 -0
  43. package/plugins/vc-ask/index.ts +57 -0
  44. package/plugins/vc-ask/native-questions.mjs +33 -0
  45. package/plugins/vc-ask/package.json +10 -0
  46. package/plugins/vc-ask/payload.ts +170 -0
  47. package/plugins/vc-ask/questionnaire/LICENSE.ask-user-question +21 -0
  48. package/plugins/vc-ask/questionnaire/UPSTREAM.md +104 -0
  49. package/plugins/vc-ask/questionnaire/answer-channel.ts +135 -0
  50. package/plugins/vc-ask/questionnaire/config.ts +180 -0
  51. package/plugins/vc-ask/questionnaire/events.ts +154 -0
  52. package/plugins/vc-ask/questionnaire/execute.ts +688 -0
  53. package/plugins/vc-ask/questionnaire/i18n.ts +73 -0
  54. package/plugins/vc-ask/questionnaire/inline-entry.ts +312 -0
  55. package/plugins/vc-ask/questionnaire/locales/de.json +43 -0
  56. package/plugins/vc-ask/questionnaire/locales/en.json +42 -0
  57. package/plugins/vc-ask/questionnaire/locales/es.json +43 -0
  58. package/plugins/vc-ask/questionnaire/locales/fr.json +43 -0
  59. package/plugins/vc-ask/questionnaire/locales/pt-BR.json +43 -0
  60. package/plugins/vc-ask/questionnaire/locales/pt.json +43 -0
  61. package/plugins/vc-ask/questionnaire/locales/ru.json +43 -0
  62. package/plugins/vc-ask/questionnaire/locales/uk.json +43 -0
  63. package/plugins/vc-ask/questionnaire/locales/zh.json +46 -0
  64. package/plugins/vc-ask/questionnaire/presentation.ts +11 -0
  65. package/plugins/vc-ask/questionnaire/question-preview.ts +6 -0
  66. package/plugins/vc-ask/questionnaire/rpc.ts +221 -0
  67. package/plugins/vc-ask/questionnaire/session-timeout.ts +67 -0
  68. package/plugins/vc-ask/questionnaire/state/build-questionnaire.ts +144 -0
  69. package/plugins/vc-ask/questionnaire/state/external-editor.ts +62 -0
  70. package/plugins/vc-ask/questionnaire/state/geometry.ts +131 -0
  71. package/plugins/vc-ask/questionnaire/state/key-router.ts +382 -0
  72. package/plugins/vc-ask/questionnaire/state/panel-router.ts +32 -0
  73. package/plugins/vc-ask/questionnaire/state/questionnaire-session.ts +642 -0
  74. package/plugins/vc-ask/questionnaire/state/row-intent.ts +143 -0
  75. package/plugins/vc-ask/questionnaire/state/selectors/contract.ts +24 -0
  76. package/plugins/vc-ask/questionnaire/state/selectors/derivations.ts +40 -0
  77. package/plugins/vc-ask/questionnaire/state/selectors/focus.ts +17 -0
  78. package/plugins/vc-ask/questionnaire/state/selectors/projections.ts +99 -0
  79. package/plugins/vc-ask/questionnaire/state/state-reducer.ts +455 -0
  80. package/plugins/vc-ask/questionnaire/state/state.ts +90 -0
  81. package/plugins/vc-ask/questionnaire/state/vertical.ts +158 -0
  82. package/plugins/vc-ask/questionnaire/timeout.ts +59 -0
  83. package/plugins/vc-ask/questionnaire/tool/external-answer.ts +103 -0
  84. package/plugins/vc-ask/questionnaire/tool/format-answer.ts +24 -0
  85. package/plugins/vc-ask/questionnaire/tool/normalize-params.ts +37 -0
  86. package/plugins/vc-ask/questionnaire/tool/response-envelope.ts +75 -0
  87. package/plugins/vc-ask/questionnaire/tool/types.ts +74 -0
  88. package/plugins/vc-ask/questionnaire/tool/validate-questionnaire.ts +75 -0
  89. package/plugins/vc-ask/questionnaire/view/card-theme.ts +245 -0
  90. package/plugins/vc-ask/questionnaire/view/components/inline-input.ts +66 -0
  91. package/plugins/vc-ask/questionnaire/view/components/multi-select-view.ts +177 -0
  92. package/plugins/vc-ask/questionnaire/view/components/option-list-view.ts +65 -0
  93. package/plugins/vc-ask/questionnaire/view/components/preview/markdown-content-cache.ts +101 -0
  94. package/plugins/vc-ask/questionnaire/view/components/preview/preview-block-renderer.ts +130 -0
  95. package/plugins/vc-ask/questionnaire/view/components/preview/preview-box-renderer.ts +86 -0
  96. package/plugins/vc-ask/questionnaire/view/components/preview/preview-layout-decider.ts +204 -0
  97. package/plugins/vc-ask/questionnaire/view/components/preview/preview-pane.ts +257 -0
  98. package/plugins/vc-ask/questionnaire/view/components/submit-picker.ts +65 -0
  99. package/plugins/vc-ask/questionnaire/view/components/tab-bar.ts +57 -0
  100. package/plugins/vc-ask/questionnaire/view/components/wrapping-select.ts +269 -0
  101. package/plugins/vc-ask/questionnaire/view/dialog-builder.ts +319 -0
  102. package/plugins/vc-ask/questionnaire/view/document-theme.ts +53 -0
  103. package/plugins/vc-ask/questionnaire/view/document-view.ts +306 -0
  104. package/plugins/vc-ask/questionnaire/view/panel-chrome.ts +133 -0
  105. package/plugins/vc-ask/questionnaire/view/props-adapter.ts +77 -0
  106. package/plugins/vc-ask/questionnaire/view/stateful-view.ts +24 -0
  107. package/plugins/vc-ask/questionnaire/view/tab-components.ts +16 -0
  108. package/plugins/vc-ask/questionnaire/view/tab-content-strategy.ts +280 -0
  109. package/plugins/vc-ask/questionnaire/view/vertical-view.ts +218 -0
  110. package/plugins/vc-ask/user-input-events.ts +34 -0
  111. package/plugins/vc-ask/vc-extras.plugin.json +18 -0
  112. package/plugins/vc-footer/agents/claude-code/adapter.mjs +29 -0
  113. package/plugins/vc-footer/agents/claude-code/cli.mjs +23 -0
  114. package/plugins/vc-footer/agents/claude-code/renderer.mjs +1 -0
  115. package/plugins/vc-footer/agents/claude-code/types.d.ts +38 -0
  116. package/plugins/vc-footer/agents/codex/adapter.mjs +13 -0
  117. package/plugins/vc-footer/agents/codex/mcp.mjs +45 -0
  118. package/plugins/vc-footer/agents/codex/native.mjs +19 -0
  119. package/plugins/vc-footer/agents/codex/renderer.mjs +2 -0
  120. package/plugins/vc-footer/agents/pi/adapter.mjs +23 -0
  121. package/plugins/vc-footer/agents/pi/index.js +84 -0
  122. package/plugins/vc-footer/agents/pi/project-local-owner.mjs +97 -0
  123. package/plugins/vc-footer/agents/pi/renderer.mjs +5 -0
  124. package/plugins/vc-footer/core/data.mjs +218 -0
  125. package/plugins/vc-footer/core/render.mjs +291 -0
  126. package/plugins/vc-footer/core/types.d.ts +29 -0
  127. package/plugins/vc-footer/package.json +22 -0
  128. package/plugins/vc-footer/vc-extras.plugin.json +32 -0
  129. package/skills/animate/LICENSE +21 -0
  130. package/skills/animate/RECIPES.md +324 -0
  131. package/skills/animate/SKILL.md +208 -0
  132. package/skills/animate/UPSTREAM.md +19 -0
  133. package/skills/animation-performance/LICENSE +21 -0
  134. package/skills/animation-performance/SKILL.md +223 -0
  135. package/skills/animation-performance/UPSTREAM.md +19 -0
  136. package/skills/answer-me-with-html/SKILL.md +174 -0
  137. package/skills/answer-me-with-html/scripts/am.mjs +12896 -0
  138. package/skills/apple-design/LICENSE +21 -0
  139. package/skills/apple-design/SKILL.md +291 -0
  140. package/skills/apple-design/UPSTREAM.md +19 -0
  141. package/skills/bad-smell/SKILL.md +44 -0
  142. package/skills/commit/SKILL.md +90 -0
  143. package/skills/emil-design-eng/LICENSE +21 -0
  144. package/skills/emil-design-eng/SKILL.md +677 -0
  145. package/skills/emil-design-eng/UPSTREAM.md +19 -0
  146. package/skills/find-the-truth/SKILL.md +38 -0
  147. package/skills/find-the-truth/references/trace-method.md +48 -0
  148. package/skills/find-the-truth/references/truth-method.md +39 -0
  149. package/skills/gestures/LICENSE +21 -0
  150. package/skills/gestures/SKILL.md +107 -0
  151. package/skills/gestures/UPSTREAM.md +19 -0
  152. package/skills/humanizer-zh/LICENSE +21 -0
  153. package/skills/humanizer-zh/SKILL.md +409 -0
  154. package/skills/humanizer-zh/UPSTREAM.md +7 -0
  155. package/skills/impeccable/LICENSE +191 -0
  156. package/skills/impeccable/NOTICE.md +11 -0
  157. package/skills/impeccable/SKILL.md +90 -0
  158. package/skills/impeccable/licenses/modern-screenshot-MIT.txt +9 -0
  159. package/skills/impeccable/licenses/platform-design-skills-MIT.txt +21 -0
  160. package/skills/impeccable/reference/adapt.md +318 -0
  161. package/skills/impeccable/reference/adapt.native.md +58 -0
  162. package/skills/impeccable/reference/android.md +46 -0
  163. package/skills/impeccable/reference/animate.md +89 -0
  164. package/skills/impeccable/reference/audit.md +139 -0
  165. package/skills/impeccable/reference/audit.native.md +139 -0
  166. package/skills/impeccable/reference/bolder.md +33 -0
  167. package/skills/impeccable/reference/clarify.md +94 -0
  168. package/skills/impeccable/reference/colorize.md +86 -0
  169. package/skills/impeccable/reference/component-review.md +63 -0
  170. package/skills/impeccable/reference/craft-floor.md +44 -0
  171. package/skills/impeccable/reference/craft.md +5 -0
  172. package/skills/impeccable/reference/critique.md +819 -0
  173. package/skills/impeccable/reference/degraded/asset-producer.md +42 -0
  174. package/skills/impeccable/reference/degraded/documenter.md +24 -0
  175. package/skills/impeccable/reference/degraded/finish-reviewer.md +38 -0
  176. package/skills/impeccable/reference/degraded/manual-edit-applier.md +93 -0
  177. package/skills/impeccable/reference/delight.md +70 -0
  178. package/skills/impeccable/reference/distill.md +111 -0
  179. package/skills/impeccable/reference/doctor.md +54 -0
  180. package/skills/impeccable/reference/document.md +416 -0
  181. package/skills/impeccable/reference/extract.md +69 -0
  182. package/skills/impeccable/reference/generate.md +101 -0
  183. package/skills/impeccable/reference/harden.md +362 -0
  184. package/skills/impeccable/reference/hooks.md +114 -0
  185. package/skills/impeccable/reference/init.md +131 -0
  186. package/skills/impeccable/reference/ios.md +51 -0
  187. package/skills/impeccable/reference/layout.md +84 -0
  188. package/skills/impeccable/reference/live-setup.md +104 -0
  189. package/skills/impeccable/reference/live.md +327 -0
  190. package/skills/impeccable/reference/mode-operate.md +21 -0
  191. package/skills/impeccable/reference/mode-persuade.md +19 -0
  192. package/skills/impeccable/reference/mode-read.md +21 -0
  193. package/skills/impeccable/reference/new-work.md +152 -0
  194. package/skills/impeccable/reference/onboard.md +234 -0
  195. package/skills/impeccable/reference/operate.md +61 -0
  196. package/skills/impeccable/reference/optimize.md +257 -0
  197. package/skills/impeccable/reference/overdrive.md +127 -0
  198. package/skills/impeccable/reference/polish.md +105 -0
  199. package/skills/impeccable/reference/quieter.md +99 -0
  200. package/skills/impeccable/reference/region-map.md +26 -0
  201. package/skills/impeccable/reference/routing.md +24 -0
  202. package/skills/impeccable/reference/shape.md +59 -0
  203. package/skills/impeccable/reference/typeset.md +90 -0
  204. package/skills/impeccable/reference/visualize.md +47 -0
  205. package/skills/impeccable/scripts/VERSION +1 -0
  206. package/skills/impeccable/scripts/command-metadata.json +98 -0
  207. package/skills/impeccable/scripts/data/font-index-failures.json +121 -0
  208. package/skills/impeccable/scripts/data/font-index.json +1 -0
  209. package/skills/impeccable/scripts/engine-checksums.txt +9 -0
  210. package/skills/impeccable/scripts/impeccable +249 -0
  211. package/skills/impeccable/scripts/impeccable.cmd +278 -0
  212. package/skills/impeccable/scripts/live-browser-dom.js +320 -0
  213. package/skills/impeccable/scripts/live-browser-ignores.js +246 -0
  214. package/skills/impeccable/scripts/live-browser-session.js +183 -0
  215. package/skills/impeccable/scripts/live-browser.js +13862 -0
  216. package/skills/impeccable/scripts/modern-screenshot.umd.js +14 -0
  217. package/skills/improve-animations/AUDIT.md +115 -0
  218. package/skills/improve-animations/LICENSE +21 -0
  219. package/skills/improve-animations/PLAN-TEMPLATE.md +73 -0
  220. package/skills/improve-animations/SKILL.md +110 -0
  221. package/skills/improve-animations/UPSTREAM.md +19 -0
  222. package/skills/pick-ui-library/LICENSE +21 -0
  223. package/skills/pick-ui-library/SKILL.md +85 -0
  224. package/skills/pick-ui-library/UPSTREAM.md +19 -0
  225. package/skills/review-animations/LICENSE +21 -0
  226. package/skills/review-animations/SKILL.md +120 -0
  227. package/skills/review-animations/STANDARDS.md +187 -0
  228. package/skills/review-animations/UPSTREAM.md +19 -0
  229. package/skills/test/SKILL.md +29 -0
  230. package/skills/test/references/test-method.md +60 -0
  231. package/skills/write-doc/SKILL.md +115 -0
  232. package/skills/write-doc/examples/result-report.md +53 -0
  233. package/skills/write-doc/examples/task-summary.md +45 -0
  234. package/skills/write-doc/references/terminology.md +147 -0
  235. package/specs/ask-host-protocol-v1.md +58 -0
  236. package/specs/design-demo.md +1102 -0
  237. package/specs/frontend-immersive.md +28 -0
  238. package/specs/plugin-install-v2.md +123 -0
  239. package/specs/plugin-install.md +38 -0
  240. package/specs/web-modes/explore.md +31 -0
  241. package/specs/web-modes/risk.md +15 -0
  242. package/specs/web-modes/verify.md +16 -0
  243. package/vc-extras.mjs +62 -0
@@ -0,0 +1,691 @@
1
+ // Writing configuration is a one-way door: the user's own edits must survive, and a
2
+ // half-written file must never be left behind. Every write therefore follows the
3
+ // same path — validate, compare against what is on disk, back up, then replace the
4
+ // file atomically. `--dry-run` stops after the comparison.
5
+ import * as fs from "node:fs";
6
+ import * as path from "node:path";
7
+ import { randomUUID, createHash } from "node:crypto";
8
+ import { isDeepStrictEqual } from "node:util";
9
+ import { spawnSync } from "node:child_process";
10
+ import { FIELDS, FILES, fileDefinition, readField, isReadonly } from "./registry.mjs";
11
+ import { maskSecret, mergeCredentials, readCredentials } from "./secrets.mjs";
12
+ import { applyFrontmatterKeys, parseFrontmatter } from "./frontmatter.mjs";
13
+ import { registerOwnedFiles } from "./ownership.mjs";
14
+ import { readDocument, encodeDocument, cloneDocument, pageValue } from "./documents.mjs";
15
+ import { pluginValueProblem, documentProblem, ratio, SEARCH_PROVIDERS } from "./plugin-validation.mjs";
16
+ import { sourceStatus } from "./sources.mjs";
17
+ import { themeNames } from "./themes.mjs";
18
+ import { safeUrl } from "./redaction.mjs";
19
+
20
+ const text = (value) => `${JSON.stringify(value, null, 2)}\n`;
21
+
22
+ export function validateValue(field, value, context = null) {
23
+ if (value === null && field.empty !== undefined) return null;
24
+ if (value === null && field.empty === undefined) return "该字段不能清空";
25
+ if ((field.kind === "string-list" && Array.isArray(value) && value.every(item => typeof item === "string")) || (field.kind === "text" && typeof value === "string")) {
26
+ const problem = pluginValueProblem(field, value);
27
+ if (problem) return problem;
28
+ }
29
+ switch (field.kind) {
30
+ case "ratio":
31
+ return ratio(value) > 0 && ratio(value) <= 1 ? null : "需要 (0,1] 比例或百分比,如 75%";
32
+ case "provider-selection":
33
+ return typeof value === "string" && ["auto", "all", ...SEARCH_PROVIDERS].includes(value) || Array.isArray(value) && value.length && new Set(value).size === value.length && value.every(v => SEARCH_PROVIDERS.includes(v)) ? null : "需要有效供应商或无重复的供应商列表";
34
+ case "boolean":
35
+ return typeof value === "boolean" ? null : "需要 true 或 false";
36
+ case "integer":
37
+ return Number.isSafeInteger(value) && value >= field.min && value <= field.max
38
+ ? null : `需要 ${field.min}–${field.max} 之间的整数`;
39
+ case "number":
40
+ return typeof value === "number" && Number.isFinite(value) && (field.exclusiveMin ? value > field.min : value >= field.min) && value <= field.max
41
+ ? null : `需要 ${field.exclusiveMin ? "大于" : "至少"} ${field.min} 且不超过 ${field.max} 的数值`;
42
+ case "enum":
43
+ return field.values.includes(value) ? null : `需要 ${field.values.join(" / ")} 之一`;
44
+ case "theme": {
45
+ if (typeof value !== "string" || value.trim() === "") return "需要主题名";
46
+ // A name Pi cannot resolve would leave the terminal without a theme at startup,
47
+ // so the list is checked against what is installed instead of a pattern.
48
+ if (!context) return "缺少配置上下文,无法校验主题";
49
+ return themeNames(context).includes(value) ? null : `本机没有安装主题 ${value}`;
50
+ }
51
+ case "string-list":
52
+ return Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "")
53
+ ? null : "需要字符串列表";
54
+ case "text":
55
+ return typeof value === "string" && (!field.maxLength || value.length <= field.maxLength)
56
+ ? null : `需要不超过 ${field.maxLength} 字符的文本`;
57
+ case "secret":
58
+ return typeof value === "string" ? null : "需要字符串";
59
+ case "providers":
60
+ return validProviderMap(value) ? null : "供应商条目格式不正确";
61
+ case "credentials":
62
+ return value && typeof value === "object" && !Array.isArray(value) ? null : "凭据格式不正确";
63
+ case "mcp-servers":
64
+ return validServerToggles(value) ? null : "MCP 服务配置格式不正确";
65
+ default:
66
+ return `未知字段类型 ${field.kind}`;
67
+ }
68
+ }
69
+
70
+ // models.json stores providers as an object keyed by id, so the page's list is
71
+ // converted to that shape and back — never a positional array.
72
+ function validProviderMap(map) {
73
+ if (!map || typeof map !== "object" || Array.isArray(map)) return false;
74
+ return Object.entries(map).every(([id, provider]) =>
75
+ id.trim() !== "" && provider && typeof provider === "object" && !Array.isArray(provider) &&
76
+ (provider.baseUrl === undefined || typeof provider.baseUrl === "string" && /^https?:\/\//.test(provider.baseUrl) && !provider.baseUrl.includes("[敏感路径或参数已隐藏]") && !provider.baseUrl.includes("[地址已隐藏]")) &&
77
+ typeof provider.api === "string" && provider.api.trim() !== "" &&
78
+ (provider.apiKey === undefined || typeof provider.apiKey === "string") &&
79
+ Array.isArray(provider.models) &&
80
+ provider.models.length > 0 &&
81
+ provider.models.every((model) => model && typeof model === "object" && typeof model.id === "string" && model.id.trim() !== "" &&
82
+ (model.contextWindow === undefined || (Number.isInteger(model.contextWindow) && model.contextWindow > 0)) &&
83
+ (model.maxTokens === undefined || (Number.isInteger(model.maxTokens) && model.maxTokens > 0))));
84
+ }
85
+
86
+ // `auth.json`, `models.json` and the rest of the JSON files must keep the exact text
87
+ // shape Emma already uses elsewhere, so the writer never re-serializes by hand here.
88
+ // A masked address is what the page shows when the stored url carries credentials, a
89
+ // query or a fragment. Writing it back would replace the real endpoint with the mask.
90
+ const MASKED_URL = /\[(?:地址已隐藏|敏感路径或参数已隐藏)\]/;
91
+
92
+ function validServerToggles(value) {
93
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
94
+ return Object.entries(value).every(([id, entry]) => {
95
+ if (id.trim() === "") return false;
96
+ if (typeof entry === "boolean") return true;
97
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false;
98
+ if (entry.enabled !== undefined && typeof entry.enabled !== "boolean") return false;
99
+ if (entry.url !== undefined && (typeof entry.url !== "string" || !/^https?:\/\//.test(entry.url) || MASKED_URL.test(entry.url))) return false;
100
+ return true;
101
+ });
102
+ }
103
+
104
+ function readTextFile(file) {
105
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
106
+ }
107
+
108
+ // The diff the user reviews and the bytes that land on disk come from the same
109
+ // description, computed once against what is currently on disk. Fields the registry
110
+ // marks read-only never reach a file: they are reported as skipped so the confirm dialog
111
+ // can say so instead of silently dropping the user's edit.
112
+ export function planChanges({ values, context, expectations = {} }) {
113
+ const plan = { files: [], problems: [], skipped: [] };
114
+ const byFile = new Map();
115
+
116
+ for (const field of FIELDS) {
117
+ if (!Object.hasOwn(values, field.id)) continue;
118
+ if (isReadonly(field)) {
119
+ plan.skipped.push({
120
+ id: field.id,
121
+ label: field.label,
122
+ file: fileDefinition(field.file).sample,
123
+ reason: "只读:内置角色由 Emma 管理,请在子代理页编辑用户覆盖,保存时跳过",
124
+ });
125
+ continue;
126
+ }
127
+ const invalid = validateValue(field, values[field.id], context);
128
+ if (invalid) plan.problems.push({ id: field.id, label: field.label, reason: invalid });
129
+ }
130
+ if (plan.problems.length) return plan;
131
+
132
+ for (const field of FIELDS) {
133
+ if (!Object.hasOwn(values, field.id)) continue;
134
+ if (isReadonly(field)) continue;
135
+ if (!byFile.has(field.file)) byFile.set(field.file, []);
136
+ byFile.get(field.file).push(field);
137
+ }
138
+
139
+ for (const [fileKey, fields] of byFile) {
140
+ const definition = fileDefinition(fileKey);
141
+ // A project file is only written when the project is trusted: an untrusted checkout
142
+ // must not be able to change files that run with the user's next Pi session.
143
+ if (definition.scope === "project" && context.trusted === false) {
144
+ for (const field of fields)
145
+ plan.skipped.push({ id: field.id, label: field.label, file: definition.sample, reason: "项目未受信任,项目级写入被拒" });
146
+ continue;
147
+ }
148
+ let entry;
149
+ const source = sourceStatus(context, fileKey);
150
+ if (source.writable === false) {
151
+ plan.problems.push({ id: fileKey, label: definition.sample, reason: source.warning || "无法核实配置来源,拒绝写入" });
152
+ continue;
153
+ }
154
+ if (fileKey === "webSearch" && source.version === "0.37.0") {
155
+ const addedProviders = ["ceramic", "deepseek", "linkup"];
156
+ if (values.webToolActivation === "none" || [values.webDefault, values.webAllowedProviders].flat().some(value => addedProviders.includes(value))) {
157
+ plan.problems.push({ id: fileKey, label: definition.sample, reason: "此选项需要已适配的 pi-web-access 0.44.0" });
158
+ continue;
159
+ }
160
+ }
161
+ try {
162
+ const target = definition.resolve(context);
163
+ const before = fileSnapshot(target);
164
+ const expected = expectations[fileKey];
165
+ const base = { key: fileKey, path: target, sample: definition.sample, scope: definition.scope, changes: [] };
166
+ entry = matchesExpectation(target, before, expected, source.version)
167
+ ? buildFilePlan(fileKey, fields, values, context)
168
+ : { ...base, conflict: true };
169
+ entry.before = before;
170
+ entry.sourceVersion = source.version;
171
+ if (!isDeepStrictEqual(fileSnapshot(target), before) || path.resolve(entry.path) !== path.resolve(target)) {
172
+ entry = { ...base, conflict: true };
173
+ }
174
+ } catch (error) {
175
+ // A file we cannot interpret is a problem to show, not a crash to swallow.
176
+ plan.problems.push({ id: fileKey, label: definition.sample, reason: error instanceof Error ? error.message : String(error) });
177
+ continue;
178
+ }
179
+ // A conflicting or rejected file is reported, never silently dropped.
180
+ if (entry.changes.length || entry.conflict) plan.files.push(entry);
181
+ }
182
+ if (plan.problems.length) plan.files = [];
183
+ return plan;
184
+ }
185
+
186
+ function buildFilePlan(fileKey, fields, values, context) {
187
+ const definition = fileDefinition(fileKey);
188
+ const target = definition.resolve(context);
189
+ const entry = { key: fileKey, path: target, sample: definition.sample, scope: definition.scope, mode: definition.mode, reload: "需重新加载 Pi", changes: [] };
190
+
191
+ if (fileKey === "auth") {
192
+ const wanted = values.credentialChanges ?? {};
193
+ const current = readCredentials(target);
194
+ const merged = mergeCredentials(current, wanted);
195
+ for (const [provider, value] of Object.entries(wanted)) {
196
+ if (!value || typeof value.key !== "string" || value.key === "") continue;
197
+ entry.changes.push({ id: `credential:${provider}`, label: `Pi 凭据 · ${provider}`, from: maskSecret(current[provider]?.key), to: maskSecret(value.key) });
198
+ }
199
+ if (!entry.changes.length) return entry;
200
+ entry.next = text(merged);
201
+ entry.mode = definition.mode;
202
+ return entry;
203
+ }
204
+
205
+ if (definition.kind === "frontmatter") return buildFrontmatterPlan(fileKey, definition, fields, values, context);
206
+
207
+ if (definition.kind === "text") {
208
+ const field = fields[0];
209
+ const current = readTextFile(target);
210
+ const next = values[field.id];
211
+ if (typeof next === "string" && next !== current)
212
+ entry.changes.push({ id: field.id, label: field.label, from: summarize(current), to: summarize(next) });
213
+ if (!entry.changes.length) return entry;
214
+ entry.next = next.endsWith("\n") ? next : `${next}\n`;
215
+ return entry;
216
+ }
217
+
218
+ const document = readDocument(target, definition.kind);
219
+ const current = document.value;
220
+ const next = cloneDocument(current);
221
+ for (const field of fields) {
222
+ if (field.kind === "providers") {
223
+ const before = current.providers ?? {};
224
+ const wanted = values[field.id] ?? {};
225
+ const merged = mergeProviderMap(before, wanted);
226
+ for (const change of providerChanges(before, merged)) entry.changes.push(change);
227
+ if (JSON.stringify(before) === JSON.stringify(merged)) continue;
228
+ setPath(next, field.key, merged);
229
+ continue;
230
+ }
231
+ // mcp-adapter.json keeps each server's command, url and env. The page owns the
232
+ // enabled flag and — when the address is not masked — the url; everything else in
233
+ // the entry is copied through untouched, so a save never drops env or headers.
234
+ if (field.kind === "mcp-servers") {
235
+ const before = readField(current, field) ?? {};
236
+ const wanted = values[field.id] ?? {};
237
+ let touched = false;
238
+ for (const [id, raw] of Object.entries(wanted)) {
239
+ const server = before[id];
240
+ if (!server || typeof server !== "object") continue;
241
+ const want = typeof raw === "boolean" ? { enabled: raw } : raw ?? {};
242
+ const nextServer = { ...server };
243
+ let changed = false;
244
+ if (typeof want.enabled === "boolean" && (server.disabled !== true) !== want.enabled) {
245
+ if (want.enabled) delete nextServer.disabled;
246
+ else nextServer.disabled = true;
247
+ entry.changes.push({ id: `mcp:${id}`, label: `MCP 服务 · ${id}`, from: want.enabled ? "已禁用" : "已启用", to: want.enabled ? "已启用" : "已禁用" });
248
+ changed = true;
249
+ }
250
+ const url = typeof want.url === "string" ? want.url.trim() : "";
251
+ if (url && url !== server.url) {
252
+ nextServer.url = url;
253
+ entry.changes.push({ id: `mcp:${id}:url`, label: `MCP 服务 · ${id} · 地址`, from: safeUrl(server.url), to: safeUrl(url) });
254
+ changed = true;
255
+ }
256
+ if (!changed) continue;
257
+ next[current.mcpServers !== undefined ? "mcpServers" : "mcp-servers"][id] = nextServer;
258
+ touched = true;
259
+ }
260
+ if (!touched) continue;
261
+ continue;
262
+ }
263
+ const value = values[field.id];
264
+ if (field.kind === "secret") {
265
+ const original = readField(current, field);
266
+ if (original === value) continue;
267
+ const before = maskSecret(original);
268
+ const after = maskSecret(value);
269
+ setPath(next, field.key, value);
270
+ entry.changes.push({ id: field.id, label: field.label, from: before, to: after });
271
+ continue;
272
+ }
273
+ const before = pageValue(readField(current, field));
274
+ if (isDeepStrictEqual(before, value)) continue;
275
+ // A picker's "inherit" and a cleared text box both mean "do not carry this key":
276
+ // the plugin falls back to its own default, and writing the sentinel (or "") would
277
+ // hand it a value it rejects. A list keeps its empty array — that is a value.
278
+ if (isRemoved(field, value)) {
279
+ deletePath(next, field.key);
280
+ entry.changes.push({ id: field.id, label: field.label, from: fieldDisplay(field, before), to: "(未设置)" });
281
+ continue;
282
+ }
283
+ setPath(next, field.key, definition.kind === "toml" && field.kind === "integer" ? BigInt(value) : value);
284
+ entry.changes.push({ id: field.id, label: field.label, from: fieldDisplay(field, before), to: fieldDisplay(field, value) });
285
+ }
286
+ if (!entry.changes.length) return entry;
287
+ const invalid = documentProblem(fileKey, next);
288
+ if (invalid) throw new Error(invalid);
289
+ entry.next = encodeDocument(document.raw, current, next, definition.kind);
290
+ if (definition.kind === "toml") entry.notice = "TOML 排版将规范化,注释会移除;原文已备份。";
291
+ return entry;
292
+ }
293
+
294
+ // A frontmatter document is edited as text: only the keys the page owns move, and the
295
+ // prompt body, comments and every other key stay exactly as they were. A role without an
296
+ // override file is created from the built-in definition, which is what "覆盖" means.
297
+ function buildFrontmatterPlan(fileKey, definition, fields, values, context) {
298
+ const target = definition.resolve(context);
299
+ const entry = { key: fileKey, path: target, sample: definition.sample, scope: definition.scope, changes: [] };
300
+ let raw = fs.existsSync(target) ? fs.readFileSync(target, "utf8") : null;
301
+ if (raw === null) {
302
+ const builtin = definition.builtin?.(context);
303
+ if (!builtin || !fs.existsSync(builtin))
304
+ throw new Error(fileKey === "roleTester"
305
+ ? `找不到可信的 Tester 模板;请先在 ${definition.sample} 准备用户角色。`
306
+ : `找不到内置定义,无法新建覆盖文件:${definition.builtin?.sample ?? definition.sample}`);
307
+ raw = fs.readFileSync(builtin, "utf8");
308
+ }
309
+ const before = parseFrontmatter(raw);
310
+ const changes = {};
311
+ for (const field of fields) {
312
+ const wanted = normalizeFrontmatterValue(field, values[field.id]);
313
+ const current = before[field.key] ?? null;
314
+ if (JSON.stringify(current) === JSON.stringify(wanted)) continue;
315
+ changes[field.key] = wanted;
316
+ entry.changes.push({ id: field.id, label: field.label, from: display(current), to: display(wanted) });
317
+ }
318
+ if (!entry.changes.length) return entry;
319
+ entry.next = applyFrontmatterKeys(raw, changes);
320
+ return entry;
321
+ }
322
+
323
+ // `inherit` is the picker's "no override" state: it removes the key rather than writing
324
+ // a literal the plugin would not understand.
325
+ function normalizeFrontmatterValue(field, value) {
326
+ if (field.empty && (value === field.empty || value === "")) return null;
327
+ return value === "" ? null : value;
328
+ }
329
+
330
+ // models.json entries carry more than the page edits — apiKey literals, compat and
331
+ // thinkingLevelMap, per-model cost, names — so a save merges the page's fields into
332
+ // what is already there instead of replacing the entry. Providers the page does not
333
+ // mention are left alone: nothing removes a provider behind the user's back.
334
+ function mergeProviderMap(before, wanted) {
335
+ const next = { ...before };
336
+ for (const [id, desired] of Object.entries(wanted)) {
337
+ const existing = before[id] ?? {};
338
+ if (desired.baseUrl === undefined && typeof existing.baseUrl !== "string") throw new Error("新供应商需要有效端点");
339
+ next[id] = {
340
+ ...existing,
341
+ baseUrl: desired.baseUrl === undefined ? existing.baseUrl : desired.baseUrl,
342
+ api: desired.api,
343
+ models: desired.models.map((model) => mergeModel((existing.models ?? []).find((entry) => entry.id === model.id), model)),
344
+ };
345
+ }
346
+ return next;
347
+ }
348
+
349
+ function mergeModel(existing, desired) {
350
+ const next = { ...(existing ?? {}) };
351
+ next.id = desired.id;
352
+ if (desired.contextWindow !== undefined) next.contextWindow = desired.contextWindow;
353
+ if (desired.maxTokens !== undefined) next.maxTokens = desired.maxTokens;
354
+ if (desired.name !== undefined && existing?.name === undefined) next.name = desired.name;
355
+ return next;
356
+ }
357
+
358
+ // One line per provider tells the user what actually moves: a new endpoint, a new
359
+ // API shape, or a changed model list.
360
+ function providerChanges(before, after) {
361
+ const changes = [];
362
+ for (const id of Object.keys(after)) {
363
+ const previous = before[id];
364
+ const current = after[id];
365
+ if (!previous) {
366
+ changes.push({ id: `provider:${id}`, label: `供应商 · ${id}`, from: "(未注册)", to: `${current.models.length} 个模型` });
367
+ continue;
368
+ }
369
+ if (previous.baseUrl !== current.baseUrl || previous.api !== current.api)
370
+ changes.push({ id: `provider:${id}:endpoint`, label: `供应商 · ${id} 端点`, from: `${previous.api} ${safeUrl(previous.baseUrl)}`, to: `${current.api} ${safeUrl(current.baseUrl)}` });
371
+ const beforeModels = (previous.models ?? []).map((model) => model.id);
372
+ const afterModels = (current.models ?? []).map((model) => model.id);
373
+ if (JSON.stringify(beforeModels) !== JSON.stringify(afterModels))
374
+ changes.push({ id: `provider:${id}:models`, label: `供应商 · ${id} 模型`, from: beforeModels.join(", ") || "(无)", to: afterModels.join(", ") });
375
+ const resized = (current.models ?? []).filter((model) => {
376
+ const previousModel = (previous.models ?? []).find((entry) => entry.id === model.id);
377
+ return previousModel && (previousModel.contextWindow !== model.contextWindow || previousModel.maxTokens !== model.maxTokens);
378
+ });
379
+ for (const model of resized)
380
+ changes.push({ id: `provider:${id}:size:${model.id}`, label: `供应商 · ${id} · ${model.id} 容量`, from: `${(previous.models ?? []).find((entry) => entry.id === model.id).contextWindow ?? "默认"}`, to: `${model.contextWindow ?? "默认"}` });
381
+ }
382
+ return changes;
383
+ }
384
+
385
+ function setPath(container, key, value) {
386
+ const segments = key.split(".");
387
+ let current = container;
388
+ for (const segment of segments.slice(0, -1)) {
389
+ if (current[segment] === null || typeof current[segment] !== "object" || Array.isArray(current[segment]))
390
+ current[segment] = {};
391
+ current = current[segment];
392
+ }
393
+ current[segments[segments.length - 1]] = value;
394
+ }
395
+
396
+ function deletePath(container, key) {
397
+ const segments = key.split(".");
398
+ let current = container;
399
+ for (const segment of segments.slice(0, -1)) {
400
+ // Nothing to remove when the parent is not an object we own.
401
+ if (current[segment] === null || typeof current[segment] !== "object" || Array.isArray(current[segment])) return;
402
+ current = current[segment];
403
+ }
404
+ delete current[segments[segments.length - 1]];
405
+ }
406
+
407
+ // Only JSON files reach here (a text file is a whole document, and arrays carry meaning).
408
+ function isRemoved(field, value) {
409
+ if (value === null) return true;
410
+ if (field.empty !== undefined && value === field.empty) return true;
411
+ return typeof value === "string" && value.trim() === "";
412
+ }
413
+
414
+ // Snapshot bytes and file identity; a same-size edit with a restored timestamp
415
+ // is still a conflict. These snapshots stay on the server/in the local journal.
416
+ const digest = bytes => createHash("sha256").update(bytes).digest("hex");
417
+
418
+ export function fileSnapshot(file) {
419
+ let stat;
420
+ try { stat = fs.lstatSync(file); }
421
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
422
+ if (!stat.isFile()) throw new Error(`配置路径不是普通文件:${file}`);
423
+ return { dev: stat.dev, ino: stat.ino, mtimeMs: stat.mtimeMs, size: stat.size, mode: stat.mode & 0o777,
424
+ hash: digest(fs.readFileSync(file)) };
425
+ }
426
+
427
+ function matchesExpectation(target, before, expected, version) {
428
+ if (!expected) return true;
429
+ if (expected.path && path.resolve(expected.path) !== path.resolve(target)) return false;
430
+ if (expected.version && expected.version !== version) return false;
431
+ if (Object.hasOwn(expected, "snapshot")) return isDeepStrictEqual(before, expected.snapshot);
432
+ return expected.missing ? before === null : before?.mtimeMs === expected.mtimeMs && before?.size === expected.size;
433
+ }
434
+
435
+ function currentMatches(entry, context) {
436
+ const definition = Object.hasOwn(FILES, entry.key) ? FILES[entry.key] : null;
437
+ if (entry.conflict || !definition || (context && (path.resolve(definition.resolve(context)) !== path.resolve(entry.path) ||
438
+ definition.scope !== entry.scope || definition.scope === "project" && context.trusted === false))) return false;
439
+ if (context) {
440
+ const source = sourceStatus(context, entry.key);
441
+ if (source.writable === false || Object.hasOwn(entry, "sourceVersion") && source.version !== entry.sourceVersion) return false;
442
+ }
443
+ return isDeepStrictEqual(fileSnapshot(entry.path), entry.before);
444
+ }
445
+
446
+ const resultFor = (entry, status) => ({ key: entry.key, path: entry.path, status });
447
+ const backupRootFor = (entry, options) => options.backupRoot ?? backupRoots(options.context)[entry.scope === "project" ? 1 : 0];
448
+ const validStamp = (stamp) => typeof stamp === "string" && /^[A-Za-z0-9_-]+$/.test(stamp);
449
+
450
+ export function applyChanges(plan, options = {}) {
451
+ if (plan.problems.length) return { results: [], ownership: null };
452
+ return transact(plan.files, options);
453
+ }
454
+
455
+ // Prepare every replacement and its recovery record before the first rename. On
456
+ // error, undo only the replacements that are still ours, in reverse order.
457
+ function transact(entries, options, { success = "written", stamp = options.stamp ?? `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}` } = {}) {
458
+ if (!validStamp(stamp)) throw new Error("Invalid backup stamp");
459
+ const { context, dryRun = false } = options;
460
+ const files = entries.map(entry => ({ ...entry }));
461
+ const results = files.map(entry => resultFor(entry, "blocked"));
462
+ const records = new Map();
463
+ const committed = [];
464
+ let index = 0;
465
+ let phase = "preflight";
466
+ let ownership = null;
467
+ let failure;
468
+ try {
469
+ for (; index < files.length; index++) {
470
+ const entry = files[index];
471
+ if (!Object.hasOwn(entry, "before") && !entry.conflict) entry.before = fileSnapshot(entry.path);
472
+ if (!currentMatches(entry, context)) results[index].status = "conflict";
473
+ }
474
+ if (results.some(result => result.status === "conflict")) return { results, ownership };
475
+ if (dryRun) return { results: files.map(entry => ({ ...resultFor(entry, "planned"), changes: entry.changes.length, ...(entry.source ? { source: entry.source } : {}) })), ownership };
476
+ phase = "prepare";
477
+ for (index = 0; index < files.length; index++) {
478
+ const entry = files[index];
479
+ if (!currentMatches(entry, context)) { results[index].status = "conflict"; return { results, ownership }; }
480
+ const directory = path.join(backupRootFor(entry, options), stamp);
481
+ if (!records.has(directory)) {
482
+ fs.mkdirSync(path.dirname(directory), { recursive: true, mode: 0o700 });
483
+ fs.mkdirSync(directory, { mode: 0o700 });
484
+ records.set(directory, {});
485
+ }
486
+ if (entry.before) {
487
+ const backup = path.join(directory, `${backupName(entry.key)}-${path.basename(entry.path)}`);
488
+ const previous = fs.readFileSync(entry.path);
489
+ if (digest(previous) !== entry.before.hash) throw new Error("配置在备份时变化,拒绝覆盖。");
490
+ copyProtected(backup, entry.path, previous, entry.before.mode);
491
+ entry.backup = backup;
492
+ }
493
+ if (entry.next !== null) {
494
+ const protectFrom = Object.hasOwn(entry, "protectFrom") ? entry.protectFrom : entry.before ? entry.path : null;
495
+ entry.temporary = stageFile(entry.path, entry.next, entry.mode, protectFrom);
496
+ entry.after = fileSnapshot(entry.temporary);
497
+ } else entry.after = null;
498
+ records.get(directory)[entry.key] = { path: path.resolve(entry.path), mode: entry.before?.mode,
499
+ before: entry.before, after: entry.after, sourceVersion: entry.sourceVersion };
500
+ }
501
+ for (const [directory, manifest] of records) {
502
+ const file = path.join(directory, "targets.json");
503
+ fs.writeFileSync(file, "", { flag: "wx", mode: 0o600 });
504
+ protectLike(file, directory, 0o600, true);
505
+ writeContent(file, text(manifest));
506
+ }
507
+ // Re-check the complete set after staging so most concurrent conflicts do not
508
+ // require rollback at all; check each file again at its commit boundary.
509
+ for (index = 0; index < files.length; index++) {
510
+ if (!currentMatches(files[index], context)) results[index].status = "conflict";
511
+ }
512
+ if (results.some(result => result.status === "conflict")) return { results, ownership };
513
+ phase = "commit";
514
+ for (index = 0; index < files.length; index++) {
515
+ const entry = files[index];
516
+ if (!currentMatches(entry, context)) {
517
+ results[index].status = "conflict";
518
+ throw new Error("配置文件已变化,拒绝覆盖。");
519
+ }
520
+ if (entry.next === null) fs.unlinkSync(entry.path);
521
+ else if (!entry.before) fs.linkSync(entry.temporary, entry.path); // no replace if another process created it
522
+ else fs.renameSync(entry.temporary, entry.path);
523
+ committed.push(index);
524
+ results[index] = { ...resultFor(entry, success), backup: entry.backup ?? null, changes: entry.changes.length,
525
+ ...(entry.source ? { source: entry.source } : {}), reload: entry.reload };
526
+ }
527
+ phase = "ownership";
528
+ const projectFiles = files.filter(entry => entry.scope === "project" && entry.next !== null).map(entry => entry.path);
529
+ if (projectFiles.length && context?.projectRoot) ownership = registerOwnedFiles(context.projectRoot, projectFiles);
530
+ } catch (error) {
531
+ // Direct raw-plan callers historically receive pre-write I/O exceptions.
532
+ if (!committed.length && entries.every(entry => !Object.hasOwn(entry, "before") && !entry.conflict)) throw error;
533
+ failure = { phase, stamp: committed.length ? stamp : null, message: error instanceof Error ? error.message : String(error) };
534
+ if (results[index]?.status === "blocked") results[index].status = "failed";
535
+ for (const completedIndex of committed.reverse()) {
536
+ const entry = files[completedIndex];
537
+ const result = results[completedIndex];
538
+ try {
539
+ result.status = undo(entry) ? "rolled-back" : "rollback-conflict";
540
+ } catch { result.status = "rollback-failed"; }
541
+ }
542
+ } finally {
543
+ for (const entry of files) if (entry.temporary) removeTemporary(entry.temporary);
544
+ if (!committed.length) for (const directory of records.keys()) removeTemporary(directory, true);
545
+ }
546
+ return { results, ownership, ...(failure ? { failure } : {}) };
547
+ }
548
+
549
+ function undo(entry) {
550
+ const stillOurs = () => isDeepStrictEqual(fileSnapshot(entry.path), entry.after);
551
+ if (!stillOurs()) return false;
552
+ if (!entry.before) { fs.unlinkSync(entry.path); return true; }
553
+ if (fileSnapshot(entry.backup)?.hash !== entry.before.hash) throw new Error("备份内容已变化。");
554
+ const temporary = stageFile(entry.path, fs.readFileSync(entry.backup), entry.before.mode, entry.backup);
555
+ try {
556
+ if (!stillOurs()) return false;
557
+ if (entry.after) fs.renameSync(temporary, entry.path);
558
+ else fs.linkSync(temporary, entry.path);
559
+ return true;
560
+ } finally { removeTemporary(temporary); }
561
+ }
562
+
563
+ // A registry key is a safe filename; this keeps a malformed one from escaping the
564
+ // backup directory even if a future entry stops being a plain identifier.
565
+ const backupName = (key) => String(key).replace(/[^A-Za-z0-9._-]/g, "_");
566
+
567
+ // Backups are addressed by registry file key, so a restore can only put a file back
568
+ // where the registry says it belongs — a hand-renamed backup cannot redirect a write.
569
+ function backupRoots(context) {
570
+ return [
571
+ path.join(context.agentDir, ".emma-config-backups"),
572
+ path.join(context.projectRoot, ".emma", ".backups"),
573
+ ];
574
+ }
575
+
576
+ export function listBackups(context) {
577
+ const stamps = new Map();
578
+ for (const root of backupRoots(context)) {
579
+ if (!fs.existsSync(root)) continue;
580
+ for (const name of fs.readdirSync(root)) {
581
+ const directory = path.join(root, name);
582
+ if (!fs.statSync(directory).isDirectory()) continue;
583
+ const files = fs.readdirSync(directory);
584
+ stamps.set(name, [...new Set([...(stamps.get(name) ?? []), ...files])]);
585
+ }
586
+ }
587
+ return [...stamps.entries()]
588
+ .map(([stamp, files]) => ({ stamp, files }))
589
+ .sort((left, right) => right.stamp.localeCompare(left.stamp));
590
+ }
591
+
592
+ // New journals describe what this transaction installed, including absence.
593
+ // Historical backups lack that guard and retain their explicit restore semantics.
594
+ export function restoreBackups({ context, stamp, dryRun = false }) {
595
+ if (!validStamp(stamp)) throw new Error("Invalid backup stamp");
596
+ const roots = backupRoots(context);
597
+ const manifests = roots.map(root => {
598
+ const file = path.join(root, stamp, "targets.json");
599
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : {};
600
+ });
601
+ const entries = [];
602
+ const blockers = [];
603
+ for (const [key, definition] of Object.entries(FILES)) {
604
+ const index = definition.scope === "project" ? 1 : 0;
605
+ const original = manifests[index][key];
606
+ const target = definition.resolve(context);
607
+ const source = path.join(roots[index], stamp, `${backupName(key)}-${path.basename(target)}`);
608
+ const journaled = original && Object.hasOwn(original, "before") && Object.hasOwn(original, "after");
609
+ if (!original && !fs.existsSync(source)) continue;
610
+ const entry = { key, path: target, scope: definition.scope, changes: [], source: journaled && original.before === null ? null : source };
611
+ if ((definition.dynamic && !original) || (original && (typeof original.path !== "string" || path.resolve(original.path) !== path.resolve(target)))) {
612
+ blockers.push(resultFor(entry, "target-changed")); continue;
613
+ }
614
+ if (definition.scope === "project" && context.trusted !== true) { blockers.push(resultFor(entry, "untrusted")); continue; }
615
+ const status = sourceStatus(context, key);
616
+ if (status.writable === false || (original?.sourceVersion && status.version !== original.sourceVersion)) { blockers.push(resultFor(entry, "source-changed")); continue; }
617
+ try {
618
+ entry.before = fileSnapshot(target);
619
+ entry.sourceVersion = status.version;
620
+ if (journaled) {
621
+ if (entry.before?.hash === original.before?.hash && entry.before?.mode === original.before?.mode) continue;
622
+ if (!isDeepStrictEqual(entry.before, original.after)) { blockers.push(resultFor(entry, "conflict")); continue; }
623
+ }
624
+ if (entry.source) {
625
+ const saved = fileSnapshot(source);
626
+ if (!saved || journaled && saved.hash !== original.before?.hash) { blockers.push(resultFor(entry, "backup-changed")); continue; }
627
+ if (entry.before?.hash === saved.hash && !journaled) continue;
628
+ entry.next = fs.readFileSync(source);
629
+ if (digest(entry.next) !== saved.hash) { blockers.push(resultFor(entry, "backup-changed")); continue; }
630
+ entry.protectFrom = journaled ? source : entry.before ? target : null;
631
+ entry.mode = original?.mode ?? definition.mode;
632
+ } else entry.next = null;
633
+ entries.push(entry);
634
+ } catch { blockers.push(resultFor(entry, "failed")); }
635
+ }
636
+ if (blockers.length) return { results: [...blockers, ...entries.map(entry => resultFor(entry, "blocked"))], ownership: null };
637
+ return transact(entries, { context, dryRun }, { success: "restored", stamp: `restore-${randomUUID()}` });
638
+ }
639
+
640
+ function writeContent(file, contents) {
641
+ const fd = fs.openSync(file, "r+");
642
+ try {
643
+ fs.writeFileSync(fd, contents);
644
+ fs.fsyncSync(fd);
645
+ } finally { fs.closeSync(fd); }
646
+ }
647
+
648
+ function copyProtected(file, source, contents, mode) {
649
+ fs.writeFileSync(file, "", { flag: "wx", mode: 0o600 });
650
+ try {
651
+ protectLike(file, source ?? path.dirname(file), mode, source === null);
652
+ writeContent(file, contents);
653
+ } catch (error) { removeTemporary(file); throw error; }
654
+ }
655
+
656
+ function stageFile(file, contents, mode, source) {
657
+ fs.mkdirSync(path.dirname(file), { recursive: true });
658
+ const temporary = `${file}.${randomUUID()}.tmp`;
659
+ copyProtected(temporary, source, contents, mode);
660
+ return temporary;
661
+ }
662
+
663
+ function removeTemporary(file, recursive = false) {
664
+ try { fs.rmSync(file, { force: true, recursive }); } catch {}
665
+ }
666
+
667
+ function protectLike(target, source, mode, directorySource = false) {
668
+ if (process.platform !== "win32") {
669
+ const original = directorySource ? mode ?? 0o600 : fs.statSync(source).mode & 0o777;
670
+ fs.chmodSync(target, original & (mode ?? 0o777));
671
+ return;
672
+ }
673
+ const quote = value => "\x27" + value.replaceAll("\x27", "\x27\x27") + "\x27";
674
+ // Set-Acl may add only SE_DACL_AUTO_INHERITED bookkeeping. Compare every other
675
+ // descriptor flag plus owner/group and exact ACEs; never ignore DACL protection.
676
+ const script = directorySource
677
+ ? "$ErrorActionPreference=\x27Stop\x27;$p=" + quote(target) + ";$a=Get-Acl -LiteralPath $p;$a.SetAccessRuleProtection($true,$false);$s=[Security.Principal.WindowsIdentity]::GetCurrent().User;$r=[Security.AccessControl.FileSystemAccessRule]::new($s,\x27FullControl\x27,\x27Allow\x27);$a.SetAccessRule($r);Set-Acl -LiteralPath $p -AclObject $a"
678
+ : "$ErrorActionPreference=\x27Stop\x27;$a=Get-Acl -LiteralPath " + quote(source) + ";Set-Acl -LiteralPath " + quote(target) + " -AclObject $a;$b=Get-Acl -LiteralPath " + quote(target) + ";$x=[Security.AccessControl.RawSecurityDescriptor]::new($a.Sddl);$y=[Security.AccessControl.RawSecurityDescriptor]::new($b.Sddl);$mask=-bnot [int][Security.AccessControl.ControlFlags]::DiscretionaryAclAutoInherited;$x.SetFlags([Security.AccessControl.ControlFlags]([int]$x.ControlFlags -band $mask));$y.SetFlags([Security.AccessControl.ControlFlags]([int]$y.ControlFlags -band $mask));if($x.GetSddlForm([Security.AccessControl.AccessControlSections]::All) -cne $y.GetSddlForm([Security.AccessControl.AccessControlSections]::All)){throw \x27ACL mismatch\x27}";
679
+ const result = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", windowsHide: true, timeout: 10000, env: Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "psmodulepath")) });
680
+ if (result.status !== 0) throw new Error("无法保持配置文件 ACL,已拒绝替换原文件。");
681
+ }
682
+
683
+ const summarize = (value) => (value.length > 40 ? `${value.slice(0, 40)}...` : value || "(空)");
684
+
685
+ const fieldDisplay = (field, value) => display(["webProxy"].includes(field.id) && value ? safeUrl(value) : value);
686
+
687
+ function display(value) {
688
+ if (value === undefined) return "(未设置)";
689
+ if (typeof value === "string") return summarize(value);
690
+ return typeof value === "bigint" ? String(value) : JSON.stringify(value) ?? "(空)";
691
+ }