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,73 @@
1
+ import { readdirSync, readFileSync, realpathSync, lstatSync } from 'node:fs';
2
+ import { resolve, relative, isAbsolute, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export const AGENTS = ['pi', 'claude-code', 'codex'];
6
+ const kinds = { pi: ['pi-package'], 'claude-code': ['claude-statusline', 'claude-ask-hook'], codex: ['codex-statusline-mcp'] };
7
+ const defaultRoot = fileURLToPath(new URL('./plugins/', import.meta.url));
8
+ export function ownedPath(root, name) {
9
+ if (typeof name !== 'string' || !name || isAbsolute(name)) throw new Error('Invalid local path');
10
+ const target = resolve(root, name), rel = relative(root, target);
11
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error(`Path escapes plugin: ${name}`);
12
+ const real = realpathSync(target), realRel = relative(realpathSync(root), real);
13
+ if (realRel === '..' || realRel.startsWith(`..${sep}`) || isAbsolute(realRel)) throw new Error(`Linked path escapes plugin: ${name}`);
14
+ return target;
15
+ }
16
+ export function localFiles(root, agent, target) {
17
+ const entry = ownedPath(root, target.entry);
18
+ if (!lstatSync(entry).isFile()) throw new Error(`Invalid entry: ${target.entry}`);
19
+ const pkg = agent === 'pi' ? JSON.parse(readFileSync(ownedPath(root, 'package.json'), 'utf8')) : null;
20
+ if (agent === 'pi' && (!Array.isArray(pkg?.pi?.extensions) || !pkg.pi.extensions.includes(target.entry))) {
21
+ throw new Error(`Pi 包未声明该入口:${target.entry}`);
22
+ }
23
+ const files = target.files === undefined ? pkg?.files : target.files;
24
+ if (!Array.isArray(files) || !files.length) throw new Error(`Missing or invalid runtime files: ${target.entry}`);
25
+ const entries = new Set();
26
+ let includesEntry = false;
27
+ for (const file of [...(agent === 'pi' ? ['package.json'] : []), ...files]) {
28
+ const path = ownedPath(root, file), info = lstatSync(path);
29
+ if (!info.isFile() && !info.isDirectory()) throw new Error(`Invalid runtime file: ${file}`);
30
+ entries.add(relative(root, path));
31
+ const rel = relative(path, entry);
32
+ if (!rel || (info.isDirectory() && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))) includesEntry = true;
33
+ }
34
+ if (!includesEntry) throw new Error(`安装文件未包含入口:${target.entry}`);
35
+ return [...entries];
36
+ }
37
+ export function discoverPlugins(root = defaultRoot) {
38
+ const plugins = [], ids = new Set();
39
+ for (const dir of readdirSync(root, { withFileTypes: true }).sort((a,b) => a.name.localeCompare(b.name))) {
40
+ if (!dir.isDirectory()) continue;
41
+ const folder = resolve(root, dir.name), file = resolve(folder, 'vc-extras.plugin.json');
42
+ if (!lstatSync(file, { throwIfNoEntry: false })) continue;
43
+ if (!lstatSync(file).isFile()) throw new Error(`Invalid manifest: ${file}`);
44
+ const m = JSON.parse(readFileSync(file, 'utf8'));
45
+ if (m.protocol !== 'vc-extras/plugin' || m.protocolVersion !== 1) throw new Error(`Unsupported plugin protocol: ${file}`);
46
+ if (typeof m.id !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(m.id) || ids.has(m.id)) throw new Error(`Invalid or duplicate plugin id: ${m.id}`);
47
+ if (!m.targets || typeof m.targets !== 'object' || Array.isArray(m.targets) || !Object.keys(m.targets).length) throw new Error(`Missing targets: ${m.id}`);
48
+ for (const [agent, target] of Object.entries(m.targets)) {
49
+ if (!AGENTS.includes(agent) || !target || !kinds[agent].includes(target.kind)) throw new Error(`Unsupported target: ${m.id}/${agent}`);
50
+ if (target.dependencies !== undefined && (agent !== 'pi' || typeof target.dependencies !== 'boolean')) throw new Error(`Invalid dependencies flag: ${m.id}`);
51
+ if (target.source !== undefined) {
52
+ if (agent !== 'pi' || typeof target.source !== 'string' || !/^npm:(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+(?:@[a-zA-Z0-9.*^~+-]+)?$/.test(target.source)) throw new Error(`Invalid package source: ${m.id}`);
53
+ } else localFiles(folder, agent, target);
54
+ }
55
+ ids.add(m.id); plugins.push({ ...m, root: folder });
56
+ }
57
+ return plugins;
58
+ }
59
+ export function targetChoices(agents, plugins = discoverPlugins()) {
60
+ if (!agents.every(a => AGENTS.includes(a))) throw new Error('Unknown agent');
61
+ return [...new Set(agents)].flatMap(agent => plugins.filter(p => p.targets[agent]).map(p => ({
62
+ id: `${p.id}:${agent}`, label: `${agent} · ${p.label || p.id}`, plugin: p.id, agent,
63
+ })));
64
+ }
65
+ export function createPlan(keys, plugins = discoverPlugins()) {
66
+ return [...new Set(keys)].map(key => {
67
+ const [id, agent, extra] = key.split(':');
68
+ const plugin = plugins.find(p => p.id === id);
69
+ if (extra !== undefined || !AGENTS.includes(agent) || !plugin || !Object.hasOwn(plugin.targets, agent)) throw new Error(`Unknown installation target: ${key}`);
70
+ const { kind, source, entry, files, dependencies } = plugin.targets[agent];
71
+ return { key, id, agent, root: plugin.root, label: plugin.label || id, kind, source, entry, files, dependencies };
72
+ });
73
+ }
@@ -0,0 +1,160 @@
1
+ // `/config` — the browser configuration page for Emma's files.
2
+ //
3
+ // Two paths, one writer:
4
+ // /config starts a loopback service, opens the page, and writes on
5
+ // save; the service exits after a save or ten idle minutes.
6
+ // /config --no-server writes the page under <agentDir>/emma-config, nothing else:
7
+ // saving downloads a patch file.
8
+ // /config apply <patch> applies such a patch from the terminal, with --dry-run.
9
+ import * as fs from "node:fs";
10
+ import * as os from "node:os";
11
+ import * as path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { shouldYieldToProject } from "./project-local-owner.ts";
14
+ import { resolveAgentDir } from "./lib/paths.mjs";
15
+ import { prepareSources } from "./lib/sources.mjs";
16
+ import { readPatch, applyPatch } from "./lib/patch.mjs";
17
+ import { openBrowser } from "./lib/open.mjs";
18
+ import { startConfigServer, inject } from "./lib/server.mjs";
19
+ import { inlinePage } from "./lib/page.mjs";
20
+ import { readState } from "./lib/state.mjs";
21
+ import { discoverThemes, themeWritten } from "./lib/themes.mjs";
22
+ import { listBackups, restoreBackups } from "./lib/writer.mjs";
23
+ import { parseArguments } from "./lib/arguments.mjs";
24
+
25
+ const PAGE_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "web");
26
+
27
+ // Both offline artifacts live under the agent directory, never in the project: a patch
28
+ // can carry a key the user just typed, and a project file is one `git add -A` away from
29
+ // being committed.
30
+ const exportDir = (configContext) => path.join(configContext.agentDir, "emma-config");
31
+
32
+ export default function configUi(pi) {
33
+ let lifetime = new AbortController();
34
+ const servers = new Set();
35
+ pi.on("session_shutdown", () => {
36
+ lifetime.abort();
37
+ for (const server of servers) server.close();
38
+ servers.clear();
39
+ });
40
+ // Pi has determined the trust state by session_start. On current Pi, the
41
+ // registered commands are collected after this event completes.
42
+ pi.on("session_start", (_event, context) => {
43
+ if (lifetime.signal.aborted) lifetime = new AbortController();
44
+ if (shouldYieldToProject(import.meta.url, "./runtime/config-ui/index.ts", context.cwd ?? process.cwd(), context.isProjectTrusted?.() === true)) return;
45
+ pi.registerCommand("config", command);
46
+ });
47
+ const command = {
48
+ description: "在浏览器中编辑 Emma 的配置文件(/config --no-server 仅导出补丁;/config apply <补丁> 应用补丁;/config restore <stamp> 从备份回滚)",
49
+ handler: async (args, context) => {
50
+ const { signal } = lifetime;
51
+ if (signal.aborted) return;
52
+ let argv;
53
+ try { argv = parseArguments(args); }
54
+ catch (error) { context.ui.notify(error.message, "error"); return; }
55
+ const cwd = context.cwd ?? process.cwd();
56
+ // Project-level writes only happen in a trusted project: the files are loaded by
57
+ // the next Pi session with the user's own permissions. A context that cannot
58
+ // answer is treated as untrusted — the guard fails closed.
59
+ const trusted = typeof context.isProjectTrusted === "function" ? context.isProjectTrusted() === true : false;
60
+ const configContext = await prepareSources({ agentDir: resolveAgentDir(), projectRoot: cwd, homeDir: os.homedir(), trusted, modelRegistry: context.modelRegistry });
61
+ // Pi owns theme resolution, so its own list is what the page offers and what a
62
+ // save is checked against — a name built from the directories could differ.
63
+ configContext.knownThemes = context.ui.getAllThemes?.() ?? [];
64
+ if (signal.aborted) return;
65
+
66
+ if (argv[0] === "apply") return applyFromTerminal(argv.slice(1), configContext, context);
67
+ if (argv[0] === "restore") return restoreFromTerminal(argv.slice(1), configContext, context);
68
+ if (argv.includes("--no-server")) return exportOnly(configContext, context);
69
+
70
+ let server;
71
+ try {
72
+ server = await startConfigServer({
73
+ context: configContext,
74
+ pageDir: PAGE_DIR,
75
+ signal,
76
+ onApplied: ({ values, results }) => {
77
+ if (!signal.aborted && themeWritten(results)) applyThemeLive(values?.piTheme, context);
78
+ },
79
+ onClose: () => {
80
+ if (server) servers.delete(server);
81
+ if (!signal.aborted) context.ui.notify("配置页服务已退出", "info");
82
+ },
83
+ });
84
+ } catch (error) {
85
+ if (signal.aborted) return;
86
+ throw error;
87
+ }
88
+ if (signal.aborted) { server.close(); return; }
89
+ servers.add(server);
90
+ context.ui.notify(`配置页已就绪:${server.url}(保存即写入;空闲 10 分钟或保存 30 秒后自动退出)`, "info");
91
+ await openBrowser(server.url);
92
+ },
93
+ };
94
+ }
95
+
96
+ async function exportOnly(configContext, context) {
97
+ const state = readState({ context: configContext });
98
+ const page = inlinePage(
99
+ fs.readFileSync(path.join(PAGE_DIR, "index.html"), "utf8"),
100
+ fs.readFileSync(path.join(PAGE_DIR, "app.mjs"), "utf8"),
101
+ );
102
+ const file = path.join(exportDir(configContext), "emma-config.html");
103
+ fs.mkdirSync(path.dirname(file), { recursive: true });
104
+ fs.writeFileSync(file, inject(page, { token: "", origin: "", state, themes: discoverThemes(configContext) }));
105
+ context.ui.notify(`已生成配置页:${file}。导出补丁后,运行 /config apply "<下载文件的完整路径>" --dry-run 检查。`, "info");
106
+ await openBrowser(`file:///${file.replace(/\\/g, "/")}`);
107
+ }
108
+
109
+ async function applyFromTerminal(argv, configContext, context) {
110
+ const dryRun = argv.includes("--dry-run");
111
+ const file = argv.filter((item) => !item.startsWith("--"))[0] ?? path.join(exportDir(configContext), "emma-config-patch.json");
112
+ const patch = readPatch(file);
113
+ const applied = applyPatch({ patch, context: configContext, dryRun });
114
+ const lines = applied.results.map((result) => `${result.status} · ${result.path}`).join("\n") || "没有需要写入的变更";
115
+ const skipped = applied.skipped?.length ? `\n跳过(只读):${applied.skipped.map((entry) => entry.label).join(", ")}` : "";
116
+ // A rejected value must say why: otherwise an invalid patch just reports "nothing to write".
117
+ const problems = applied.plan.problems.length
118
+ ? `\n被拒:${applied.plan.problems.map((problem) => `${problem.label ?? problem.id}(${problem.reason})`).join("; ")}`
119
+ : "";
120
+ const failure = describeFailure(applied.failure);
121
+ context.ui.notify(`${dryRun ? "[dry-run] " : ""}${lines}${problems}${skipped}${applied.unknown.length ? `\n忽略未知字段:${applied.unknown.join(", ")}` : ""}${failure}`, failure || problems || applied.results.some(result => result.status === "conflict") ? "warning" : "info");
122
+ // A patch applied from the terminal changes settings.json just as a save does.
123
+ if (!dryRun && themeWritten(applied.results)) applyThemeLive(patch.values.piTheme, context);
124
+ }
125
+
126
+ // Pi keeps its own in-memory theme; writing settings.json alone would leave the running
127
+ // session on the old colors until restart, so the change is pushed through the UI API.
128
+ function applyThemeLive(theme, context) {
129
+ if (!theme) return;
130
+ const result = context.ui.setTheme(theme);
131
+ if (result?.success === false) {
132
+ context.ui.notify(`主题已写入配置,但当前会话未能切换:${result.error ?? "未知原因"}`, "warning");
133
+ return;
134
+ }
135
+ context.ui.notify(`主题已切换:${theme}`, "info");
136
+ }
137
+
138
+ // `/config restore` rolls a registry file back to a backup taken before a save. The
139
+ // stamp addresses a directory, never a path: a backup cannot redirect a write.
140
+ async function restoreFromTerminal(argv, configContext, context) {
141
+ const dryRun = argv.includes("--dry-run");
142
+ const stamp = argv.filter((item) => !item.startsWith("--"))[0];
143
+ if (!stamp) {
144
+ const backups = listBackups(configContext);
145
+ const lines = backups.slice(0, 10).map((entry) => `${entry.stamp} · ${entry.files.length} 个文件`).join("\n");
146
+ context.ui.notify(backups.length ? `可回滚的备份:\n${lines}\n用法:/config restore <stamp> [--dry-run]` : "没有可回滚的备份", "info");
147
+ return;
148
+ }
149
+ const restored = restoreBackups({ context: configContext, stamp, dryRun });
150
+ const lines = restored.results.map((result) => `${result.status} · ${result.path}`).join("\n") || `备份 ${stamp} 与当前文件一致,无需回滚`;
151
+ const failure = describeFailure(restored.failure);
152
+ const incomplete = restored.results.some(result => !["planned", "restored"].includes(result.status));
153
+ context.ui.notify(`${dryRun ? "[dry-run] " : ""}${lines}${failure}`, failure || incomplete ? "warning" : "info");
154
+ }
155
+
156
+ function describeFailure(failure) {
157
+ if (!failure) return "";
158
+ const recovery = failure.stamp ? `\n恢复记录: ${failure.stamp}` : "";
159
+ return `\n未完成(${failure.phase}): ${failure.message}${recovery}`;
160
+ }
@@ -0,0 +1,24 @@
1
+ // Parse command arguments without treating Windows path backslashes as escapes.
2
+ export function parseArguments(input) {
3
+ const args = [];
4
+ let value = "";
5
+ let quote = null;
6
+ let started = false;
7
+ for (const char of String(input ?? "")) {
8
+ if (quote) {
9
+ if (char === quote) quote = null;
10
+ else value += char;
11
+ } else if (char === '"' || char === "'") {
12
+ quote = char;
13
+ started = true;
14
+ } else if (/\s/.test(char)) {
15
+ if (started) { args.push(value); value = ""; started = false; }
16
+ } else {
17
+ value += char;
18
+ started = true;
19
+ }
20
+ }
21
+ if (quote) throw new Error("路径引号未闭合。用法:/config apply \"完整路径\" [--dry-run]");
22
+ if (started) args.push(value);
23
+ return args;
24
+ }
@@ -0,0 +1,67 @@
1
+ import * as fs from "node:fs";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import * as toml from "smol-toml";
4
+ import { parse, modify, applyEdits } from "jsonc-parser";
5
+
6
+ export function parseDocument(raw, kind) {
7
+ try {
8
+ const clean = raw.replace(/^\uFEFF/, "");
9
+ let value;
10
+ if (kind === "toml") value = toml.parse(clean, { integersAsBigInt: true, unsafeKeyBehaviour: "throw" });
11
+ else if (kind === "jsonc") {
12
+ const errors = [];
13
+ value = parse(clean, errors, { allowTrailingComma: true });
14
+ if (errors.length) throw new Error("invalid JSONC");
15
+ } else value = JSON.parse(clean);
16
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected object");
17
+ return value;
18
+ } catch { throw new Error("配置语法或根对象不正确,请先修正文件;原文件未改动。"); }
19
+ }
20
+
21
+ export function readDocument(file, kind) {
22
+ const raw = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
23
+ return { raw, value: raw || fs.existsSync(file) ? parseDocument(raw, kind) : {} };
24
+ }
25
+
26
+ export function encodeDocument(raw, before, after, kind) {
27
+ if (kind === "toml") {
28
+ const encoded = toml.stringify(after, { numbersAsFloat: true });
29
+ if (!sameToml(toml.parse(encoded, { integersAsBigInt: true, unsafeKeyBehaviour: "throw" }), after))
30
+ throw new Error("TOML 值或类型无法无损保留,拒绝写入。");
31
+ return encoded;
32
+ }
33
+ if (kind === "jsonc") {
34
+ let next = raw || "{}";
35
+ const visit = (left, right, keys = []) => {
36
+ const record = v => v && typeof v === "object" && !Array.isArray(v);
37
+ if (record(left) && record(right)) {
38
+ for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) visit(left[key], right[key], [...keys, key]);
39
+ } else if (!isDeepStrictEqual(left, right)) {
40
+ next = applyEdits(next, modify(next, keys, right, { formattingOptions: { insertSpaces: true, tabSize: 2 } }));
41
+ }
42
+ };
43
+ visit(before, after);
44
+ return next.endsWith("\n") ? next : next + "\n";
45
+ }
46
+ return JSON.stringify(after, null, 2) + "\n";
47
+ }
48
+
49
+ function sameToml(left, right) {
50
+ if (Object.is(left, right)) return true;
51
+ if (left instanceof Date || right instanceof Date) return isDeepStrictEqual(left, right);
52
+ if (!left || !right || typeof left !== "object" || typeof right !== "object" || Array.isArray(left) !== Array.isArray(right)) return false;
53
+ const keys = Object.keys(left);
54
+ return keys.length === Object.keys(right).length && keys.every(key => Object.hasOwn(right, key) && sameToml(left[key], right[key]));
55
+ }
56
+
57
+ export function cloneDocument(value) {
58
+ if (Array.isArray(value)) return value.map(cloneDocument);
59
+ if (value instanceof Date) return value;
60
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cloneDocument(item)]));
61
+ return value;
62
+ }
63
+
64
+ export function pageValue(value) {
65
+ if (typeof value === "bigint") return value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : null;
66
+ return value;
67
+ }
@@ -0,0 +1,91 @@
1
+ // The two project files the agent page edits are Markdown documents with a YAML
2
+ // frontmatter block: `.pi/agents/<role>.md` overrides and `.agents/agents/reviewer.md`.
3
+ // Only a handful of top-level keys belong to the page, and everything else — the prompt
4
+ // body, comments, key order, blank lines, the original line endings — must survive a save
5
+ // byte-for-byte. A YAML round-trip would not promise that, so the block is edited as text.
6
+ const OPEN = /^(?:\uFEFF)?---[ \t]*\r?\n/;
7
+
8
+ export function splitFrontmatter(raw) {
9
+ const text = String(raw ?? "");
10
+ const open = OPEN.exec(text);
11
+ if (!open) return null;
12
+ const rest = text.slice(open[0].length);
13
+ const close = /^---[ \t]*(?:\r?\n|$)/m.exec(rest);
14
+ if (!close) return null;
15
+ return {
16
+ head: text.slice(0, open[0].length),
17
+ body: rest.slice(0, close.index),
18
+ tail: rest.slice(close.index),
19
+ };
20
+ }
21
+
22
+ // Scalar-only, one line per key: enough for `model` and `thinking`, and deliberately
23
+ // blind to nested blocks (they are other keys' business and stay untouched).
24
+ export function parseFrontmatter(raw) {
25
+ const parts = splitFrontmatter(raw);
26
+ if (!parts) return {};
27
+ const values = {};
28
+ for (const line of parts.body.split(/\r?\n/)) {
29
+ const match = /^([A-Za-z0-9_-]+):[ \t]*(.*)$/.exec(line);
30
+ if (match) values[match[1]] = parseScalar(match[2]);
31
+ }
32
+ return values;
33
+ }
34
+
35
+ function parseScalar(raw) {
36
+ const value = raw.trim();
37
+ if (value === "" || value === "~" || value === "null") return null;
38
+ if (value === "true") return true;
39
+ if (value === "false") return false;
40
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
41
+ if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'")))
42
+ return value.slice(1, -1);
43
+ if (value.startsWith("[") && value.endsWith("]"))
44
+ return value.slice(1, -1).split(",").map((item) => parseScalar(item)).filter((item) => item !== null);
45
+ return value;
46
+ }
47
+
48
+ function formatScalar(value) {
49
+ if (typeof value === "boolean" || typeof value === "number") return String(value);
50
+ const text = String(value);
51
+ return /[:#\[\]{}",]|^[\s]|[\s]$|^(true|false|null|~|-?\d+(\.\d+)?)$/.test(text) ? JSON.stringify(text) : text;
52
+ }
53
+
54
+ // `changes` maps a top-level key to its new value; `null` removes the key. Returns the
55
+ // document unchanged when there is nothing to do.
56
+ export function applyFrontmatterKeys(raw, changes) {
57
+ const text = String(raw ?? "");
58
+ const newline = text.includes("\r\n") ? "\r\n" : "\n";
59
+ const parts = splitFrontmatter(text);
60
+ const pending = Object.entries(changes);
61
+
62
+ if (!parts) {
63
+ if (!pending.length) return text;
64
+ const block = pending.map(([key, value]) => `${key}: ${formatScalar(value)}`).join(newline);
65
+ return `---${newline}${block}${newline}---${newline}${text}`;
66
+ }
67
+
68
+ const lines = parts.body.split(/\r?\n/);
69
+ const remaining = new Map(pending);
70
+ const kept = [];
71
+ for (const line of lines) {
72
+ const match = /^([A-Za-z0-9_-]+):/.exec(line);
73
+ if (!match || !remaining.has(match[1])) {
74
+ kept.push(line);
75
+ continue;
76
+ }
77
+ const value = remaining.get(match[1]);
78
+ remaining.delete(match[1]);
79
+ if (value !== null) kept.push(`${match[1]}: ${formatScalar(value)}`);
80
+ }
81
+
82
+ // New keys go after the last existing key so the file still reads like a header.
83
+ for (const [key, value] of remaining) {
84
+ if (value === null) continue;
85
+ let insert = kept.length;
86
+ while (insert > 0 && kept[insert - 1].trim() === "") insert -= 1;
87
+ kept.splice(insert, 0, `${key}: ${formatScalar(value)}`);
88
+ }
89
+
90
+ return `${parts.head}${kept.join(newline)}${parts.tail}`;
91
+ }
@@ -0,0 +1,17 @@
1
+ // Opening the page in the user's browser, without pulling in a dependency: each
2
+ // platform has one command for it. A failure to open is not fatal — the caller
3
+ // still prints the URL.
4
+ import { spawn } from "node:child_process";
5
+
6
+ export function openBrowser(url) {
7
+ const [command, args] = process.platform === "win32"
8
+ ? ["cmd", ["/c", "start", "", url]]
9
+ : process.platform === "darwin"
10
+ ? ["open", [url]]
11
+ : ["xdg-open", [url]];
12
+ return new Promise((resolve) => {
13
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
14
+ child.once("error", () => resolve(false));
15
+ child.once("spawn", () => { child.unref(); resolve(true); });
16
+ });
17
+ }
@@ -0,0 +1,99 @@
1
+ // Registering a project-level file that `/config` wrote, so Emma can roll it back.
2
+ //
3
+ // The published extension lives at `<project>/.emma/runtime/config-ui/lib/`, while the
4
+ // installer's `src/installer/project-install.js` is not part of that published tree —
5
+ // importing it would break the runtime. The state contract is therefore reproduced here,
6
+ // and `test/pi-core/config-ownership.test.mjs` pins this module against the installer's
7
+ // own `ownedFileEntry` so the two cannot drift.
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { createHash } from "node:crypto";
11
+
12
+ export const PROJECT_INSTALL_STATE = "project-install.json";
13
+ const STATE_KIND = "vibe-emma-project-install";
14
+
15
+ // The installer owns this set (src/installer/project-install.js `ownedProjectPath`).
16
+ // A path outside it must never be registered: the state file's validator rejects it.
17
+ const RETIRED_RENDERER_CONFIG = ".pi/compact-tools.json";
18
+ const OWNED_PATTERNS = [
19
+ /^\.pi\/agents\/[^/]+\.md$/,
20
+ /^\.agents\/agents\/[^/]+\.md$/,
21
+ /^\.emma\/agents\/[^/]+\.md$/,
22
+ /^\.emma\/agents\/web-modes\/[^/]+\.md$/,
23
+ /^\.pi\/extensions\/pi-permission-system\/config\.json$/,
24
+ /^\.pi\/automode\.json$/,
25
+ /^\.pi\/automode\.local\.json$/,
26
+ /^\.pi\/subagents\.json$/,
27
+ /^\.cortexkit\/magic-context\.jsonc$/,
28
+ ];
29
+
30
+ export const statePath = (projectRoot) => path.join(path.resolve(projectRoot), ".emma", PROJECT_INSTALL_STATE);
31
+
32
+ export function isOwnedProjectPath(relative) {
33
+ const normalized = String(relative).replace(/\\/g, "/").replace(/^\.\//, "");
34
+ return OWNED_PATTERNS.some((pattern) => pattern.test(normalized));
35
+ }
36
+
37
+ export function fileFingerprint(file) {
38
+ return `sha256:${createHash("sha256").update(fs.readFileSync(file)).digest("hex")}`;
39
+ }
40
+
41
+ // The entry shape the installer writes for a project-owned file.
42
+ export function ownedEntry(projectRoot, file) {
43
+ const root = path.resolve(projectRoot);
44
+ const absolute = path.resolve(file);
45
+ const relative = path.relative(root, absolute).replace(/\\/g, "/");
46
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative) || !isOwnedProjectPath(relative))
47
+ throw new Error(`Emma project-owned file is outside the managed path set: ${absolute}`);
48
+ if (!fs.existsSync(absolute) || !fs.lstatSync(absolute).isFile())
49
+ throw new Error(`Emma project-owned file is missing or not regular: ${absolute}`);
50
+ return { path: relative, fingerprint: fileFingerprint(absolute) };
51
+ }
52
+
53
+ function validState(value) {
54
+ return Boolean(
55
+ value && value.version === 1 && value.kind === STATE_KIND &&
56
+ typeof value.emmaVersion === "string" &&
57
+ Array.isArray(value.packages) && Array.isArray(value.files) &&
58
+ value.files.every((entry) =>
59
+ entry && typeof entry.path === "string" && typeof entry.fingerprint === "string" &&
60
+ (isOwnedProjectPath(entry.path) || entry.path === RETIRED_RENDERER_CONFIG)),
61
+ );
62
+ }
63
+
64
+ // Registers the written project files in the project install state. A project without
65
+ // Emma's install state is left alone: there is nothing to roll back into, and inventing
66
+ // a state file would fabricate a version and an ownership claim. A state that fails its
67
+ // own contract is reported rather than rewritten.
68
+ export function registerOwnedFiles(projectRoot, files) {
69
+ const file = statePath(projectRoot);
70
+ if (!files.length || !fs.existsSync(file)) return { registered: [], reason: fs.existsSync(file) ? "no files" : "no state" };
71
+
72
+ let state;
73
+ try {
74
+ state = JSON.parse(fs.readFileSync(file, "utf8"));
75
+ } catch (error) {
76
+ return { registered: [], reason: `invalid state: ${error instanceof Error ? error.message : String(error)}` };
77
+ }
78
+ if (!validState(state)) return { registered: [], reason: "invalid state" };
79
+
80
+ const byPath = new Map(state.files.filter(entry => entry.path !== RETIRED_RENDERER_CONFIG).map((entry) => [entry.path, entry]));
81
+ for (const target of files) {
82
+ const entry = ownedEntry(projectRoot, target);
83
+ byPath.set(entry.path, entry);
84
+ }
85
+ const next = {
86
+ ...state,
87
+ files: [...byPath.values()].sort((left, right) => left.path.localeCompare(right.path)),
88
+ };
89
+ if (JSON.stringify(next.files) === JSON.stringify(state.files)) return { registered: [], reason: "unchanged" };
90
+
91
+ const temporary = `${file}.tmp-${process.pid}-${Date.now()}`;
92
+ try {
93
+ fs.writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { flag: "wx", mode: 0o600 });
94
+ fs.renameSync(temporary, file);
95
+ } finally {
96
+ fs.rmSync(temporary, { force: true });
97
+ }
98
+ return { registered: byPath.size ? files.map((target) => ownedEntry(projectRoot, target).path) : [] };
99
+ }
@@ -0,0 +1,11 @@
1
+ // The offline page has to be one file: a module loaded from `file://` is refused by
2
+ // the browser, so `app.mjs` is inlined into the HTML.
3
+ //
4
+ // `String.replace` treats `$$` in a string replacement as an escape, and app.mjs uses
5
+ // `$$` as its query helper — passing the code as a replacement string silently
6
+ // corrupts it. A replacer function returns the code verbatim.
7
+ export function inlinePage(html, appCode) {
8
+ const marker = '<script type="module" src="./app.mjs"></script>';
9
+ if (!html.includes(marker)) throw new Error("配置页缺少 app.mjs 的 script 标记,无法生成离线页面");
10
+ return html.replace(marker, () => `<script type="module">${appCode}</script>`);
11
+ }
@@ -0,0 +1,36 @@
1
+ // The no-server path: the page saves a patch file instead of calling the local
2
+ // service, and the terminal applies it later. A patch carries only field ids and
3
+ // values, so a hand-edited file cannot address a path the registry does not own —
4
+ // unknown ids are reported and dropped rather than written.
5
+ import * as fs from "node:fs";
6
+ import { fieldById } from "./registry.mjs";
7
+ import { applyChanges, planChanges } from "./writer.mjs";
8
+
9
+ export const PATCH_KIND = "vibe-emma-config-patch";
10
+
11
+ export function createPatch({ values, expectations, createdAt = new Date().toISOString() }) {
12
+ return { version: 2, kind: PATCH_KIND, createdAt, values, expectations };
13
+ }
14
+
15
+ export function readPatch(file) {
16
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
17
+ if (parsed?.kind !== PATCH_KIND || parsed?.version !== 2 || !parsed.values || typeof parsed.values !== "object")
18
+ throw new Error(`不是 Emma 配置补丁:${file}`);
19
+ return parsed;
20
+ }
21
+
22
+ export function applyPatch({ patch, context, dryRun = false }) {
23
+ const values = {};
24
+ const unknown = [];
25
+ for (const [id, value] of Object.entries(patch.values)) {
26
+ if (fieldById(id)) values[id] = value;
27
+ else unknown.push(id);
28
+ }
29
+ const baseline = patch.expectations;
30
+ const missing = Object.keys(values).filter(id => !baseline?.[fieldById(id).file] || typeof baseline[fieldById(id).file].path !== "string");
31
+ const plan = missing.length
32
+ ? { files: [], skipped: [], problems: [{ id: "patch", reason: "补丁缺少导出时的目标和文件基线,请重新导出。" }] }
33
+ : planChanges({ values, context, expectations: baseline });
34
+ const applied = applyChanges(plan, { context, dryRun });
35
+ return { plan, unknown, results: applied.results, skipped: plan.skipped, ownership: applied.ownership, failure: applied.failure };
36
+ }
@@ -0,0 +1,14 @@
1
+ // Path resolution shared by the config UI runtime and the installer. The agent
2
+ // directory is where Pi keeps every user-level config file, and it is relocatable
3
+ // through PI_CODING_AGENT_DIR, so nothing may hardcode `~/.pi/agent`.
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+
7
+ export function resolveAgentDir(env = process.env, homeDir = os.homedir()) {
8
+ const home = path.resolve(homeDir);
9
+ const configured = env.PI_CODING_AGENT_DIR?.trim();
10
+ if (!configured) return path.join(home, ".pi", "agent");
11
+ if (configured === "~") return home;
12
+ if (configured.startsWith("~/")) return path.resolve(home, configured.slice(2));
13
+ return path.resolve(configured);
14
+ }