vc-extras 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +70 -2
  2. package/agents/tester.md +23 -0
  3. package/install-extras.mjs +134 -0
  4. package/install-menu.mjs +63 -0
  5. package/install-skills.mjs +112 -0
  6. package/package.json +26 -4
  7. package/plugins/config-ui/index.ts +160 -0
  8. package/plugins/config-ui/lib/arguments.mjs +24 -0
  9. package/plugins/config-ui/lib/documents.mjs +67 -0
  10. package/plugins/config-ui/lib/frontmatter.mjs +91 -0
  11. package/plugins/config-ui/lib/open.mjs +17 -0
  12. package/plugins/config-ui/lib/ownership.mjs +99 -0
  13. package/plugins/config-ui/lib/page.mjs +11 -0
  14. package/plugins/config-ui/lib/patch.mjs +36 -0
  15. package/plugins/config-ui/lib/paths.mjs +14 -0
  16. package/plugins/config-ui/lib/plugin-fields.mjs +86 -0
  17. package/plugins/config-ui/lib/plugin-validation.mjs +28 -0
  18. package/plugins/config-ui/lib/redaction.mjs +8 -0
  19. package/plugins/config-ui/lib/registry.mjs +282 -0
  20. package/plugins/config-ui/lib/secrets.mjs +45 -0
  21. package/plugins/config-ui/lib/server.mjs +251 -0
  22. package/plugins/config-ui/lib/sources.mjs +96 -0
  23. package/plugins/config-ui/lib/state.mjs +157 -0
  24. package/plugins/config-ui/lib/themes.mjs +113 -0
  25. package/plugins/config-ui/lib/writer.mjs +691 -0
  26. package/plugins/config-ui/package.json +12 -0
  27. package/plugins/config-ui/project-local-owner.ts +106 -0
  28. package/plugins/config-ui/web/app.mjs +997 -0
  29. package/plugins/config-ui/web/index.html +342 -0
  30. package/plugins/essrj/context.ts +47 -0
  31. package/plugins/essrj/data.ts +190 -0
  32. package/plugins/essrj/index.ts +139 -0
  33. package/plugins/essrj/package.json +12 -0
  34. package/plugins/essrj/project-local-owner.ts +106 -0
  35. package/plugins/essrj/render.ts +217 -0
  36. package/plugins/essrj/types.ts +40 -0
  37. package/plugins.json +38 -0
  38. package/skills/animate/LICENSE +21 -0
  39. package/skills/animate/RECIPES.md +324 -0
  40. package/skills/animate/SKILL.md +208 -0
  41. package/skills/animate/UPSTREAM.md +19 -0
  42. package/skills/animation-performance/LICENSE +21 -0
  43. package/skills/animation-performance/SKILL.md +223 -0
  44. package/skills/animation-performance/UPSTREAM.md +19 -0
  45. package/skills/answer-me-with-html/SKILL.md +174 -0
  46. package/skills/answer-me-with-html/scripts/am.mjs +12896 -0
  47. package/skills/apple-design/LICENSE +21 -0
  48. package/skills/apple-design/SKILL.md +291 -0
  49. package/skills/apple-design/UPSTREAM.md +19 -0
  50. package/skills/bad-smell/SKILL.md +44 -0
  51. package/skills/commit/SKILL.md +90 -0
  52. package/skills/emil-design-eng/LICENSE +21 -0
  53. package/skills/emil-design-eng/SKILL.md +677 -0
  54. package/skills/emil-design-eng/UPSTREAM.md +19 -0
  55. package/skills/find-the-truth/SKILL.md +38 -0
  56. package/skills/find-the-truth/references/trace-method.md +48 -0
  57. package/skills/find-the-truth/references/truth-method.md +39 -0
  58. package/skills/gestures/LICENSE +21 -0
  59. package/skills/gestures/SKILL.md +107 -0
  60. package/skills/gestures/UPSTREAM.md +19 -0
  61. package/skills/humanizer-zh/LICENSE +21 -0
  62. package/skills/humanizer-zh/SKILL.md +409 -0
  63. package/skills/humanizer-zh/UPSTREAM.md +7 -0
  64. package/skills/impeccable/LICENSE +191 -0
  65. package/skills/impeccable/NOTICE.md +11 -0
  66. package/skills/impeccable/SKILL.md +90 -0
  67. package/skills/impeccable/licenses/modern-screenshot-MIT.txt +9 -0
  68. package/skills/impeccable/licenses/platform-design-skills-MIT.txt +21 -0
  69. package/skills/impeccable/reference/adapt.md +318 -0
  70. package/skills/impeccable/reference/adapt.native.md +58 -0
  71. package/skills/impeccable/reference/android.md +46 -0
  72. package/skills/impeccable/reference/animate.md +89 -0
  73. package/skills/impeccable/reference/audit.md +139 -0
  74. package/skills/impeccable/reference/audit.native.md +139 -0
  75. package/skills/impeccable/reference/bolder.md +33 -0
  76. package/skills/impeccable/reference/clarify.md +94 -0
  77. package/skills/impeccable/reference/colorize.md +86 -0
  78. package/skills/impeccable/reference/component-review.md +63 -0
  79. package/skills/impeccable/reference/craft-floor.md +44 -0
  80. package/skills/impeccable/reference/craft.md +5 -0
  81. package/skills/impeccable/reference/critique.md +819 -0
  82. package/skills/impeccable/reference/degraded/asset-producer.md +42 -0
  83. package/skills/impeccable/reference/degraded/documenter.md +24 -0
  84. package/skills/impeccable/reference/degraded/finish-reviewer.md +38 -0
  85. package/skills/impeccable/reference/degraded/manual-edit-applier.md +93 -0
  86. package/skills/impeccable/reference/delight.md +70 -0
  87. package/skills/impeccable/reference/distill.md +111 -0
  88. package/skills/impeccable/reference/doctor.md +54 -0
  89. package/skills/impeccable/reference/document.md +416 -0
  90. package/skills/impeccable/reference/extract.md +69 -0
  91. package/skills/impeccable/reference/generate.md +101 -0
  92. package/skills/impeccable/reference/harden.md +362 -0
  93. package/skills/impeccable/reference/hooks.md +114 -0
  94. package/skills/impeccable/reference/init.md +131 -0
  95. package/skills/impeccable/reference/ios.md +51 -0
  96. package/skills/impeccable/reference/layout.md +84 -0
  97. package/skills/impeccable/reference/live-setup.md +104 -0
  98. package/skills/impeccable/reference/live.md +327 -0
  99. package/skills/impeccable/reference/mode-operate.md +21 -0
  100. package/skills/impeccable/reference/mode-persuade.md +19 -0
  101. package/skills/impeccable/reference/mode-read.md +21 -0
  102. package/skills/impeccable/reference/new-work.md +152 -0
  103. package/skills/impeccable/reference/onboard.md +234 -0
  104. package/skills/impeccable/reference/operate.md +61 -0
  105. package/skills/impeccable/reference/optimize.md +257 -0
  106. package/skills/impeccable/reference/overdrive.md +127 -0
  107. package/skills/impeccable/reference/polish.md +105 -0
  108. package/skills/impeccable/reference/quieter.md +99 -0
  109. package/skills/impeccable/reference/region-map.md +26 -0
  110. package/skills/impeccable/reference/routing.md +24 -0
  111. package/skills/impeccable/reference/shape.md +59 -0
  112. package/skills/impeccable/reference/typeset.md +90 -0
  113. package/skills/impeccable/reference/visualize.md +47 -0
  114. package/skills/impeccable/scripts/VERSION +1 -0
  115. package/skills/impeccable/scripts/command-metadata.json +98 -0
  116. package/skills/impeccable/scripts/data/font-index-failures.json +121 -0
  117. package/skills/impeccable/scripts/data/font-index.json +1 -0
  118. package/skills/impeccable/scripts/engine-checksums.txt +9 -0
  119. package/skills/impeccable/scripts/impeccable +249 -0
  120. package/skills/impeccable/scripts/impeccable.cmd +278 -0
  121. package/skills/impeccable/scripts/live-browser-dom.js +320 -0
  122. package/skills/impeccable/scripts/live-browser-ignores.js +246 -0
  123. package/skills/impeccable/scripts/live-browser-session.js +183 -0
  124. package/skills/impeccable/scripts/live-browser.js +13862 -0
  125. package/skills/impeccable/scripts/modern-screenshot.umd.js +14 -0
  126. package/skills/improve-animations/AUDIT.md +115 -0
  127. package/skills/improve-animations/LICENSE +21 -0
  128. package/skills/improve-animations/PLAN-TEMPLATE.md +73 -0
  129. package/skills/improve-animations/SKILL.md +110 -0
  130. package/skills/improve-animations/UPSTREAM.md +19 -0
  131. package/skills/pick-ui-library/LICENSE +21 -0
  132. package/skills/pick-ui-library/SKILL.md +85 -0
  133. package/skills/pick-ui-library/UPSTREAM.md +19 -0
  134. package/skills/review-animations/LICENSE +21 -0
  135. package/skills/review-animations/SKILL.md +120 -0
  136. package/skills/review-animations/STANDARDS.md +187 -0
  137. package/skills/review-animations/UPSTREAM.md +19 -0
  138. package/skills/test/SKILL.md +29 -0
  139. package/skills/test/references/test-method.md +60 -0
  140. package/skills/write-doc/SKILL.md +115 -0
  141. package/skills/write-doc/examples/result-report.md +53 -0
  142. package/skills/write-doc/examples/task-summary.md +45 -0
  143. package/skills/write-doc/references/terminology.md +147 -0
  144. package/specs/design-demo.md +1102 -0
  145. package/specs/frontend-immersive.md +28 -0
  146. package/specs/web-modes/explore.md +31 -0
  147. package/specs/web-modes/risk.md +15 -0
  148. package/specs/web-modes/verify.md +16 -0
  149. package/vc-extras.mjs +78 -0
@@ -0,0 +1,282 @@
1
+ // The field registry is the single source of truth behind the browser form: every
2
+ // form control names the file and the key path it owns, so what the page shows,
3
+ // what the diff previews and what the writer commits can never drift apart.
4
+ //
5
+ // Two kinds of secrets exist and they belong in different places:
6
+ // - Pi's own credentials live in <agentDir>/auth.json (keyed by provider);
7
+ // - plugin keys must live in that plugin's own config file, because the plugin
8
+ // reads nothing else (pi-web-access reads `braveApiKey` from web-search.json).
9
+ // Putting a plugin key in auth.json would look saved and change nothing.
10
+ import * as fs from "node:fs";
11
+ import * as path from "node:path";
12
+ import { webConfigPath, mcpConfigPath } from "./sources.mjs";
13
+ import { PLUGIN_FIELDS } from "./plugin-fields.mjs";
14
+ import { SEARCH_PROVIDERS } from "./plugin-validation.mjs";
15
+
16
+ const agentFile = (c, name) => path.join(c.agentDir, name);
17
+ const projectFile = (c, name) => path.join(c.projectRoot, name);
18
+
19
+ export const FILES = {
20
+ jev: {
21
+ sample: "~/.pi/agent/jev-auto-mode.json",
22
+ scope: "user",
23
+ kind: "json",
24
+ resolve: (c) => agentFile(c, "jev-auto-mode.json"),
25
+ },
26
+ jevPolicy: {
27
+ sample: "~/.pi/agent/jev-auto-mode-policy.md",
28
+ scope: "user",
29
+ kind: "text",
30
+ resolve: (c) => agentFile(c, "jev-auto-mode-policy.md"),
31
+ },
32
+ piSettings: {
33
+ sample: "~/.pi/agent/settings.json",
34
+ scope: "user",
35
+ kind: "json",
36
+ resolve: (c) => agentFile(c, "settings.json"),
37
+ },
38
+ blackhole: {
39
+ sample: "~/.pi/agent/pi-blackhole/pi-blackhole-config.json",
40
+ scope: "user",
41
+ kind: "json",
42
+ resolve: (c) => agentFile(c, path.join("pi-blackhole", "pi-blackhole-config.json")),
43
+ },
44
+ models: {
45
+ sample: "~/.pi/agent/models.json",
46
+ scope: "user",
47
+ kind: "json",
48
+ resolve: (c) => agentFile(c, "models.json"),
49
+ },
50
+ auth: {
51
+ sample: "~/.pi/agent/auth.json",
52
+ scope: "user",
53
+ kind: "credentials",
54
+ mode: 0o600,
55
+ resolve: (c) => agentFile(c, "auth.json"),
56
+ },
57
+ webSearch: {
58
+ sample: "~/.pi/agent/web-search.json",
59
+ scope: "user",
60
+ kind: "json",
61
+ resolve: webConfigPath,
62
+ dynamic: true,
63
+ mode: 0o600,
64
+ },
65
+ // ---------- 插件与 MCP ----------
66
+ piFff: {
67
+ sample: "~/.pi/agent/pi-fff.json",
68
+ scope: "user",
69
+ kind: "json",
70
+ resolve: (c) => agentFile(c, "pi-fff.json"),
71
+ },
72
+ piBtw: {
73
+ sample: "~/.pi/agent/pi-btw.json",
74
+ scope: "user",
75
+ kind: "json",
76
+ resolve: (c) => agentFile(c, "pi-btw.json"),
77
+ },
78
+ mcp: {
79
+ sample: "由已安装 MCP 解析路径",
80
+ scope: "user",
81
+ kind: "jsonc",
82
+ dynamic: true,
83
+ mode: 0o600,
84
+ resolve: mcpConfigPath,
85
+ },
86
+ piCcExtensions: {
87
+ sample: "~/.pi/agent/pi-cc-extensions.json",
88
+ scope: "user",
89
+ kind: "json",
90
+ resolve: (c) => agentFile(c, "pi-cc-extensions.json"),
91
+ },
92
+ // ---------- 子代理 ----------
93
+ subagents: {
94
+ sample: "~/.pi/agent/subagents.json",
95
+ scope: "user",
96
+ kind: "json",
97
+ resolve: (c) => agentFile(c, "subagents.json"),
98
+ projectOverrides: (c) => [projectFile(c, ".pi/subagents.json")],
99
+ },
100
+ roleExplorer: roleFile("explorer"),
101
+ roleResearcher: roleFile("researcher"),
102
+ roleReviewer: roleFile("reviewer"),
103
+ roleTester: roleFile("tester"),
104
+ roleExpert: roleFile("expert"),
105
+ };
106
+
107
+ // User roles are shared defaults; project .agents/agents and .pi/agents retain
108
+ // upstream precedence. The editor only touches its two frontmatter keys.
109
+ function roleFile(name) {
110
+ const builtin = (c) => {
111
+ // Tester belongs to vc-extras, not Emma. This independently installed plugin
112
+ // does not bundle that role; never synthesize it from a different role source.
113
+ if (name === "tester") return null;
114
+ const installed = agentFile(c, path.join("vc-packages", "current", "emma", "workflow", "agents", `${name}.md`));
115
+ return fs.existsSync(installed) ? installed : agentFile(c, path.join("emma", "agents", `${name}.md`));
116
+ };
117
+ return {
118
+ sample: `~/.pi/agent/agents/${name}.md`,
119
+ scope: "user",
120
+ kind: "frontmatter",
121
+ builtin,
122
+ projectOverrides: (c) => [projectFile(c, `.pi/agents/${name}.md`), projectFile(c, `.agents/agents/${name}.md`)],
123
+ resolve: (c) => agentFile(c, path.join("agents", `${name}.md`)),
124
+ };
125
+ }
126
+
127
+ // `thinking` lives in the file as low/medium/high; the page shows 低/中/高 through its
128
+ // three-bar signal meter.
129
+ export const THINKING_LEVELS = ["low", "medium", "high"];
130
+
131
+ // The five roles the page lists, in the order the design shows them.
132
+ export const ROLE_NAMES = ["Explorer", "Researcher", "Reviewer", "Tester", "Expert"];
133
+
134
+ export const roleFileKey = (name) => `role${name}`;
135
+
136
+ // pi-jev-auto-mode's calibrated defaults. The thresholds are per-rule confidence
137
+ // bars: a rule the engine scores below its bar counts as not satisfied.
138
+ export const JEV_THRESHOLD_RULES = [
139
+ { id: "thIntent", key: "intent_coverage", label: "意图一致", calibrated: 0.6 },
140
+ { id: "thPolicy", key: "policy_compliance", label: "符合策略", calibrated: 0.8 },
141
+ { id: "thLocal", key: "local_scope", label: "局部操作", calibrated: 0.9 },
142
+ { id: "thSecret", key: "no_secret_egress", label: "无密钥外泄", calibrated: 0.97 },
143
+ { id: "thDamage", key: "no_irreversible_damage", label: "无不可逆破坏", calibrated: 0.8 },
144
+ { id: "thOutward", key: "no_outward_effect", label: "无对外影响", calibrated: 0.9 },
145
+ { id: "thPath", key: "path_not_protected", label: "路径未受保护", calibrated: 0.9 },
146
+ { id: "thFetch", key: "no_fetched_code_execution", label: "不执行取回代码", calibrated: 0.9 },
147
+ { id: "thInject", key: "prompt_injection_absent", label: "无提示注入", calibrated: 0.8 },
148
+ ];
149
+
150
+ export const WEB_PROVIDER_KEYS = [
151
+ { id: "brave", key: "braveApiKey" },
152
+ { id: "exa", key: "exaApiKey" },
153
+ { id: "tavily", key: "tavilyApiKey" },
154
+ { id: "serper", key: "serperApiKey" },
155
+ { id: "jina", key: "jinaApiKey" },
156
+ { id: "firecrawl", key: "firecrawlApiKey" },
157
+ { id: "perplexity", key: "perplexityApiKey" },
158
+ { id: "openai", key: "openaiApiKey" },
159
+ { id: "gemini", key: "geminiApiKey" },
160
+ ];
161
+
162
+ const field = (value) => Object.freeze(value);
163
+
164
+ export const FIELDS = Object.freeze([
165
+ // ---------- 命令评审: pi-jev-auto-mode ----------
166
+ field({ id: "rvEnabled", group: "review", label: "启用", file: "jev", key: "enabled", kind: "boolean" }),
167
+ field({ id: "rvTimeout", group: "review", label: "判定超时", file: "jev", key: "timeoutMs", kind: "integer", min: 250, max: 60000 }),
168
+ field({ id: "rvRetries", group: "review", label: "失败重试", file: "jev", key: "maxRetries", kind: "integer", min: 0, max: 5 }),
169
+ field({ id: "rvMaxState", group: "review", label: "状态上限", file: "jev", key: "maxStateCharacters", kind: "integer", min: 1000, max: 1000000 }),
170
+ field({ id: "rvUncertain", group: "review", label: "中间带", file: "jev", key: "uncertain", kind: "enum", values: ["deny", "ask", "allow"] }),
171
+ field({ id: "rvGateScope", group: "review", label: "语义覆盖面", file: "jev", key: "gateScope", kind: "enum", values: ["all", "matched"] }),
172
+ field({ id: "rvDisplay", group: "review", label: "记录展示", file: "jev", key: "display", kind: "enum", values: ["compact", "full"] }),
173
+ field({ id: "rvSafeCommands", group: "review", label: "免记录放行", file: "jev", key: "safeCommands", kind: "string-list" }),
174
+ field({ id: "rvAllowedCommands", group: "review", label: "总能过", file: "jev", key: "allowedCommands", kind: "string-list" }),
175
+ field({ id: "rvDisallowedCommands", group: "review", label: "直接拦", file: "jev", key: "disallowedCommands", kind: "string-list" }),
176
+ field({ id: "rvProtectedPaths", group: "review", label: "写入即评审", file: "jev", key: "extraProtectedPaths", kind: "string-list" }),
177
+ field({ id: "rvPolicy", group: "review", label: "补充约束", file: "jevPolicy", kind: "text", maxLength: 8000 }),
178
+ ...JEV_THRESHOLD_RULES.map((rule) =>
179
+ field({ id: rule.id, group: "review", label: rule.label, file: "jev", key: `thresholds.${rule.key}`, kind: "number", min: 0.5, exclusiveMin: true, max: 1 })),
180
+
181
+ // ---------- Pi 核心: <agentDir>/settings.json ----------
182
+ field({ id: "defProvider", group: "pi-core", label: "默认 Provider", file: "piSettings", key: "defaultProvider", kind: "text" }),
183
+ field({ id: "defModel", group: "pi-core", label: "默认模型", file: "piSettings", key: "defaultModel", kind: "text" }),
184
+ field({ id: "defThinking", group: "pi-core", label: "思考等级", file: "piSettings", key: "defaultThinkingLevel", kind: "enum", values: ["off", "minimal", "low", "medium", "high", "xhigh", "max"] }),
185
+ field({ id: "enabledModels", group: "pi-core", label: "启用列表", file: "piSettings", key: "enabledModels", kind: "string-list" }),
186
+ field({ id: "cpReserve", group: "pi-core", label: "预留 tokens", file: "piSettings", key: "compaction.reserveTokens", kind: "integer", min: 1024, max: 1000000 }),
187
+ field({ id: "cpKeepRecent", group: "pi-core", label: "保留最近 tokens", file: "piSettings", key: "compaction.keepRecentTokens", kind: "integer", min: 1024, max: 1000000 }),
188
+ field({ id: "cpEnabled", group: "pi-core", label: "启用", file: "piSettings", key: "compaction.enabled", kind: "boolean" }),
189
+ field({ id: "piTheme", group: "appearance", label: "主题", file: "piSettings", key: "theme", kind: "theme", help: "列出 Pi 当前可加载的主题;保存后立即应用到当前会话,并写入 settings.json。" }),
190
+
191
+ // ---------- 模型与凭据: providers (non-secret) + credentials ----------
192
+ // models.json keys providers by id: { "<id>": { baseUrl, api, models: [{ id }] } }.
193
+ // The display name is cosmetic and stays in the page, and the provider key lives
194
+ // in auth.json, so neither is written back here.
195
+ field({ id: "providerRegistry", group: "model", label: "供应商注册", file: "models", key: "providers", kind: "providers" }),
196
+ field({ id: "credentialChanges", group: "model", label: "Pi 凭据", file: "auth", kind: "credentials" }),
197
+
198
+ // ---------- 联网检索 ----------
199
+ // The keys and value spaces here follow pi-web-access' documented schema
200
+ // (`pi-web-access/README.md`, "Configuration"): the default provider is the
201
+ // top-level `provider` (not `searchRouting.default`), the proxy is top-level
202
+ // `proxy`, `summaryModel` is the curator/auto-summary model (while
203
+ // `fetch.answerProvider` + `fetch.answerModel` are a pair for fetch_content answer
204
+ // mode), `allowBrowserCookies` is a top-level boolean (`authFetch` is a profile map),
205
+ // `ssrf.allowRanges` must be a string array (the plugin throws on a string), and
206
+ // `toolActivation` accepts auto/dynamic/eager.
207
+ field({ id: "webDefault", group: "web", label: "自动选择", file: "webSearch", key: "searchProvider", kind: "provider-selection", values: ["auto", "all", ...SEARCH_PROVIDERS] }),
208
+ field({ id: "webProxy", group: "web", label: "代理", file: "webSearch", key: "proxy", kind: "text" }),
209
+ field({ id: "webSummaryModel", group: "web", label: "摘要模型", file: "webSearch", key: "summaryModel", kind: "text", empty: "inherit" }),
210
+ field({ id: "webWorkflow", group: "web", label: "检索流程", file: "webSearch", key: "workflow", kind: "enum", values: ["none", "summary-review", "auto-summary"] }),
211
+ field({ id: "webInlineCap", group: "web", label: "正文上限", file: "webSearch", key: "maxInlineContentChars", kind: "integer", min: 1000, max: 200000 }),
212
+ field({ id: "webFetchTimeout", group: "web", label: "抓取超时", file: "webSearch", key: "fetch.timeout", kind: "number", min: 0, exclusiveMin: true, max: Number.MAX_SAFE_INTEGER }),
213
+ field({ id: "webToolActivation", group: "web", label: "动态激活", file: "webSearch", key: "toolActivation", kind: "enum", values: ["auto", "dynamic", "eager", "none"] }),
214
+ field({ id: "webSsrfRanges", group: "web", label: "SSRF 放行", file: "webSearch", key: "ssrf.allowRanges", kind: "string-list" }),
215
+ field({ id: "webTrustProxy", group: "web", label: "信任环境代理", file: "webSearch", key: "ssrf.trustEnvProxy", kind: "boolean" }),
216
+ field({ id: "webBrowserCookies", group: "web", label: "浏览器 Cookie", file: "webSearch", key: "allowBrowserCookies", kind: "boolean" }),
217
+ ...WEB_PROVIDER_KEYS.map((entry) =>
218
+ field({ id: `webKey_${entry.id}`, group: "web", label: `${entry.id} API 密钥`, file: "webSearch", key: entry.key, kind: "secret" })),
219
+
220
+ // ---------- 插件与 MCP ----------
221
+ field({ id: "fffHomeScan", group: "plugins", label: "主页扫描", file: "piFff", key: "enableHomeDirScanning", kind: "boolean" }),
222
+ field({ id: "fffWarnHomeScan", group: "plugins", label: "扫描告警", file: "piFff", key: "warnOnHomeDirScan", kind: "boolean" }),
223
+ field({ id: "fffFollowSymlinks", group: "plugins", label: "跟随符号链接", file: "piFff", key: "followSymlinks", kind: "boolean" }),
224
+ // The picker's "跟随当前会话模型" is the plugin's own "no override" state: the key is
225
+ // removed rather than filled with the literal sentinel, which pi-btw would reject as
226
+ // an invalid model reference and treat the whole settings file as invalid.
227
+ field({ id: "btwModel", group: "plugins", label: "侧模型", file: "piBtw", key: "model", kind: "text", maxLength: 400, empty: "inherit" }),
228
+ field({ id: "btwLayout", group: "plugins", label: "布局", file: "piBtw", key: "layout", kind: "enum", values: ["fullscreen", "left-pane", "right-pane"] }),
229
+ // The file stores a 0.2–0.8 fraction; the page shows the same value as a percentage.
230
+ field({ id: "btwRatio", group: "plugins", label: "侧栏占比", file: "piBtw", key: "sidePaneRatio", kind: "number", min: 0.2, max: 0.8, page: "percent" }),
231
+ field({ id: "mcpServers", group: "plugins", label: "服务", file: "mcp", key: "mcpServers", kind: "mcp-servers" }),
232
+
233
+ ...PLUGIN_FIELDS,
234
+
235
+ // ---------- 子代理 ----------
236
+ field({ id: "saDisableDefaults", group: "agents", label: "禁用默认角色", file: "subagents", key: "disableDefaultAgents", kind: "boolean" }),
237
+ field({ id: "saFallback", group: "agents", label: "未知角色回落", file: "subagents", key: "fallbackSubagent", kind: "enum", values: ["none", "general-purpose"] }),
238
+ field({ id: "saWorkflows", group: "agents", label: "工作流脚本", file: "subagents", key: "workflowsEnabled", kind: "boolean" }),
239
+ ...ROLE_NAMES.flatMap((name) => [
240
+ field({ id: `role${name}Model`, group: "agents", label: `${name} 模型`, file: roleFileKey(name), key: "model", kind: "text", maxLength: 400, empty: "inherit" }),
241
+ field({ id: `role${name}Thinking`, group: "agents", label: `${name} 思考级别`, file: roleFileKey(name), key: "thinking", kind: "enum", values: THINKING_LEVELS }),
242
+ ]),
243
+
244
+ ]);
245
+
246
+ const BY_ID = new Map(FIELDS.map((entry) => [entry.id, entry]));
247
+
248
+ export function fieldById(id) {
249
+ return BY_ID.get(id) ?? null;
250
+ }
251
+
252
+ export function isReadonly(field) {
253
+ return field.strategy === "readonly";
254
+ }
255
+
256
+ // A field whose file is a frontmatter document is written through the document-level
257
+ // editor, not the JSON one; `key` names a top-level YAML key there.
258
+ export function isFrontmatter(field) {
259
+ return FILES[field.file]?.kind === "frontmatter";
260
+ }
261
+
262
+ export function fileDefinition(fileKey) {
263
+ const definition = FILES[fileKey];
264
+ if (!definition) throw new Error(`Unknown config file: ${fileKey}`);
265
+ return definition;
266
+ }
267
+
268
+ // A field's key is a dotted path; `thresholds.intent_coverage` writes one level in.
269
+ export function keyPath(field) {
270
+ return field.key ? field.key.split(".") : [];
271
+ }
272
+
273
+ export function readField(container, field) {
274
+ if (field.id === "webDefault") return container.searchProvider ?? container.provider;
275
+ if (field.kind === "mcp-servers") return container.mcpServers ?? container["mcp-servers"];
276
+ let current = container;
277
+ for (const segment of keyPath(field)) {
278
+ if (current === null || typeof current !== "object") return undefined;
279
+ current = current[segment];
280
+ }
281
+ return current;
282
+ }
@@ -0,0 +1,45 @@
1
+ // Two different secret stores, on purpose:
2
+ // - Pi's own provider credentials live in <agentDir>/auth.json and are keyed by
3
+ // provider; a write merges that one provider and leaves every other entry byte
4
+ // for byte alone.
5
+ // - Plugin keys belong to the plugin's own config file (handled by the writer),
6
+ // because a plugin never reads auth.json.
7
+ // Nothing here ever prints a key: diffs carry a mask, and the value only exists in
8
+ // the file being written.
9
+ import * as fs from "node:fs";
10
+
11
+ export const MASK = "••••••••";
12
+
13
+ export function maskSecret(value) {
14
+ return typeof value === "string" && value !== "" ? MASK : "(未设置)";
15
+ }
16
+
17
+ export function readCredentials(file) {
18
+ if (!fs.existsSync(file)) return {};
19
+ const raw = fs.readFileSync(file, "utf8");
20
+ try {
21
+ const value = JSON.parse(raw.replace(/^\uFEFF/, ""));
22
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
23
+ } catch {
24
+ throw new Error(`无法解析 ${file}:请先修正该文件的 JSON 语法`);
25
+ }
26
+ }
27
+
28
+ // A credential entry keeps the shape already on disk (Pi versions differ in which
29
+ // fields they store), and an unknown shape is refused instead of guessed.
30
+ export function mergeCredentials(current, wanted) {
31
+ const next = { ...current };
32
+ for (const [provider, value] of Object.entries(wanted)) {
33
+ if (!value || typeof value.key !== "string" || value.key === "") continue;
34
+ const existing = current[provider];
35
+ if (existing && typeof existing !== "object") throw new Error(`auth.json 中 ${provider} 的条目不是对象,拒绝覆盖`);
36
+ // A stored entry decides its own shape. Only an api_key entry can be replaced by a
37
+ // pasted key; anything else (oauth and future types) needs its own flow, so it is
38
+ // reported instead of being overwritten with a key it cannot use.
39
+ const type = existing?.type ?? value.type;
40
+ if (typeof type !== "string" || type === "") throw new Error(`无法确定 ${provider} 的凭据类型,拒绝写入 auth.json`);
41
+ if (type !== "api_key") throw new Error(`auth.json 中 ${provider} 是 ${type} 类型的凭据,不能用 API 密钥覆盖`);
42
+ next[provider] = { ...(existing ?? {}), type, key: value.key };
43
+ }
44
+ return next;
45
+ }
@@ -0,0 +1,251 @@
1
+ // The local service exists so that clicking 保存 actually writes. That is a real
2
+ // network surface, so it is kept as small as possible: loopback only, a random
3
+ // port, a one-time token that the page must echo, an Origin check, a small body
4
+ // cap, and an idle exit so the process does not keep listening forever.
5
+ import * as fs from "node:fs";
6
+ import * as http from "node:http";
7
+ import * as path from "node:path";
8
+ import { randomBytes } from "node:crypto";
9
+ import { readState } from "./state.mjs";
10
+ import { applyChanges, fileSnapshot, planChanges } from "./writer.mjs";
11
+ import { FIELDS, FILES } from "./registry.mjs";
12
+ import { discoverThemes } from "./themes.mjs";
13
+
14
+ const FIELD_FILES = Object.fromEntries(FIELDS.map((field) => [field.id, field.file]));
15
+ // The offline page has no service to ask which fields are read-only, so the ids travel
16
+ // with the boot payload; the labels make the skip note readable.
17
+ const FIELD_READONLY = FIELDS.filter((field) => field.strategy === "readonly").map((field) => field.id);
18
+ const FIELD_NAMES = Object.fromEntries(FIELDS.map((field) => [field.id, field.label]));
19
+ const FIELD_SEMANTICS = Object.fromEntries(FIELDS.map(({ id, kind, empty }) => [id, { kind, empty }]));
20
+
21
+ const MAX_BODY = 512 * 1024;
22
+ const IDLE_TIMEOUT_MS = 10 * 60 * 1000;
23
+ const EXIT_AFTER_SAVE_MS = 30 * 1000;
24
+
25
+ export function createToken() {
26
+ return randomBytes(24).toString("hex");
27
+ }
28
+
29
+ export async function startConfigServer(options) {
30
+ const { context, pageDir, idleTimeoutMs = IDLE_TIMEOUT_MS, exitAfterSaveMs = EXIT_AFTER_SAVE_MS } = options;
31
+ // Port 0 means an ephemeral port, so two projects never collide.
32
+ const wantedPort = options.port ?? 0;
33
+ const token = options.token ?? createToken();
34
+ const signal = options.signal;
35
+ signal?.throwIfAborted();
36
+ const versions = new Map();
37
+ const previews = new Map();
38
+ let idleTimer;
39
+ let saveTimer;
40
+ let stopped = false;
41
+
42
+ // Keep recent snapshots per load and only a small number of reviewed plans
43
+ // (which contain the edited values, including any newly typed secrets).
44
+ function remember(map, value, maximum) {
45
+ const id = createToken();
46
+ map.set(id, value);
47
+ while (map.size > maximum) map.delete(map.keys().next().value);
48
+ return id;
49
+ }
50
+
51
+ const server = http.createServer((request, response) => {
52
+ handle(request, response).catch((error) => send(response, 500, { error: error instanceof Error ? error.message : String(error) }));
53
+ });
54
+
55
+ const stop = () => {
56
+ if (stopped) return;
57
+ stopped = true;
58
+ clearTimeout(idleTimer);
59
+ clearTimeout(saveTimer);
60
+ versions.clear();
61
+ previews.clear();
62
+ signal?.removeEventListener("abort", stop);
63
+ server.close();
64
+ options.onClose?.();
65
+ };
66
+ const touch = () => {
67
+ clearTimeout(idleTimer);
68
+ idleTimer = setTimeout(stop, idleTimeoutMs);
69
+ };
70
+ server.on("close", () => { clearTimeout(idleTimer); clearTimeout(saveTimer); });
71
+ await new Promise((resolve, reject) => {
72
+ server.once("error", reject);
73
+ server.listen(wantedPort, "127.0.0.1", () => { server.removeListener("error", reject); resolve(); });
74
+ });
75
+ if (signal?.aborted) { stop(); signal.throwIfAborted(); }
76
+ signal?.addEventListener("abort", stop, { once: true });
77
+ touch();
78
+ const { port } = server.address();
79
+ const origin = `http://127.0.0.1:${port}`;
80
+
81
+ async function handle(request, response) {
82
+ if (stopped) return send(response, 503, { error: "配置服务已关闭" });
83
+ touch();
84
+ const url = new URL(request.url ?? "/", origin);
85
+ const frame = request.headers.origin;
86
+ if (frame && frame !== origin) return send(response, 403, { error: "origin 不被接受" });
87
+ // Host pins the request to this listener too, so a DNS-rebinding name cannot reach it.
88
+ const host = (request.headers.host ?? "").replace(/^\[|\]$/g, "");
89
+ if (host && host !== `127.0.0.1:${port}` && host !== "127.0.0.1" && host !== `localhost:${port}` && host !== "localhost")
90
+ return send(response, 403, { error: "host 不被接受" });
91
+ if (url.pathname === "/") return sendPage(response, url);
92
+ if (url.pathname === "/favicon.ico" && request.method === "GET") { response.writeHead(204); return response.end(); }
93
+ if (request.method === "GET" && /^\/[\w.-]+\.(mjs|js|css|svg)$/.test(url.pathname)) return sendAsset(response, url.pathname);
94
+ if (request.headers["x-emma-token"] !== token) return send(response, 401, { error: "令牌无效" });
95
+ if (url.pathname === "/api/state" && request.method === "GET") {
96
+ const before = snapshotExpectations();
97
+ const state = readState({ context });
98
+ const after = snapshotExpectations();
99
+ // An external edit while loading must not create a fresh but stale baseline.
100
+ if (JSON.stringify(before) !== JSON.stringify(after)) return send(response, 409, { error: "配置在读取时变化,请重新载入" });
101
+ const expectations = Object.fromEntries(Object.entries(after).map(([key, value]) => [key, { ...state.expectations[key], path: value.target, snapshot: value.snapshot }]));
102
+ return send(response, 200, { ...state, version: remember(versions, expectations, 64) });
103
+ }
104
+ // Planning is a separate call on purpose: the user reviews the diff before
105
+ // anything is written, and the diff they review is the one the writer would do.
106
+ if (url.pathname === "/api/plan" && request.method === "POST") return plan(request, response);
107
+ if (url.pathname === "/api/save" && request.method === "POST") return save(request, response);
108
+ return send(response, 404, { error: "not found" });
109
+ }
110
+
111
+ function sendPage(response, url) {
112
+ const file = path.join(pageDir, "index.html");
113
+ if (!fs.existsSync(file)) return send(response, 500, { error: `缺少配置页文件:${file}` });
114
+ // The page needs the token to call the API, so it is injected at serve time
115
+ // rather than shipped in the file.
116
+ const html = inject(fs.readFileSync(file, "utf8"), { token, origin, themes: discoverThemes(context) });
117
+ void url;
118
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
119
+ response.end(html);
120
+ }
121
+
122
+ function snapshotExpectations() {
123
+ return Object.fromEntries(Object.entries(FILES).map(([key, definition]) => {
124
+ const target = definition.resolve(context);
125
+ try { return [key, { target, snapshot: fileSnapshot(target) }]; }
126
+ catch { return [key, { target, unavailable: true }]; }
127
+ }));
128
+ }
129
+
130
+ async function readPayload(request, response) {
131
+ const body = await readBody(request);
132
+ if (body === null) {
133
+ send(response, 413, { error: "请求体过大" });
134
+ return null;
135
+ }
136
+ let payload;
137
+ try {
138
+ payload = JSON.parse(body);
139
+ } catch {
140
+ send(response, 400, { error: "请求体不是 JSON" });
141
+ return null;
142
+ }
143
+ if (stopped) { send(response, 503, { error: "配置服务已关闭" }); return null; }
144
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
145
+ send(response, 400, { error: "请求格式不正确" });
146
+ return null;
147
+ }
148
+ return payload;
149
+ }
150
+
151
+ async function plan(request, response) {
152
+ const payload = await readPayload(request, response);
153
+ if (!payload) return;
154
+ const { values, version } = payload;
155
+ if (!values || typeof values !== "object" || Array.isArray(values)) return send(response, 400, { error: "缺少 values" });
156
+ const expectations = versions.get(version);
157
+ if (!expectations) return send(response, 409, { error: "页面版本已失效,请重新载入" });
158
+ const planned = planChanges({ values, context, expectations });
159
+ const preview = !planned.problems.length && planned.files.length && !planned.files.some(entry => entry.conflict)
160
+ ? remember(previews, { version, values, planned }, 16) : null;
161
+ return send(response, 200, { problems: planned.problems, skipped: planned.skipped, changes: describe(planned), preview });
162
+ }
163
+
164
+ // The page is served from the disk so `app.mjs` can be a real module next to it.
165
+ function sendAsset(response, pathname) {
166
+ const file = path.join(pageDir, path.basename(pathname));
167
+ if (!fs.existsSync(file)) return send(response, 404, { error: "not found" });
168
+ const type = file.endsWith(".mjs") || file.endsWith(".js") ? "text/javascript; charset=utf-8"
169
+ : file.endsWith(".css") ? "text/css; charset=utf-8"
170
+ : file.endsWith(".svg") ? "image/svg+xml" : "application/octet-stream";
171
+ response.writeHead(200, { "content-type": type, "cache-control": "no-store" });
172
+ response.end(fs.readFileSync(file));
173
+ }
174
+
175
+ async function save(request, response) {
176
+ const payload = await readPayload(request, response);
177
+ if (!payload) return;
178
+ const { preview, version } = payload;
179
+ const reviewed = previews.get(preview);
180
+ if (!reviewed || reviewed.version !== version || !versions.has(version) || Object.hasOwn(payload, "values"))
181
+ return send(response, 409, { error: "没有有效的预览,请重新预览" });
182
+ previews.delete(preview);
183
+ const { values, planned } = reviewed;
184
+ const { results, failure } = applyChanges(planned, { context });
185
+ if (!failure && results.some(result => result.status === "written")) {
186
+ versions.delete(version);
187
+ for (const [id, item] of previews) if (item.version === version) previews.delete(id);
188
+ clearTimeout(saveTimer);
189
+ if (exitAfterSaveMs > 0) saveTimer = setTimeout(stop, exitAfterSaveMs);
190
+ // A live-apply failure cannot change the disk outcome.
191
+ try { options.onApplied?.({ values, results }); } catch {}
192
+ }
193
+ send(response, 200, { results, failure, skipped: planned.skipped, changes: describe(planned) });
194
+ }
195
+
196
+ return { url: `${origin}/?token=${token}`, origin, port, token, close: stop };
197
+ }
198
+
199
+ // Over-sized bodies are drained rather than aborted: killing the socket would take
200
+ // the 413 response down with it, and the caller would see a network error instead
201
+ // of a reason.
202
+ // The page needs its token and the field→file map; both are injected at serve time
203
+ // instead of living in the file.
204
+ export function inject(html, { token = "", origin = "", state = null, themes = null }) {
205
+ const boot = { token, origin, fields: FIELD_FILES, readonly: FIELD_READONLY, names: FIELD_NAMES, semantics: FIELD_SEMANTICS, controls: FIELDS, themes };
206
+ const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
207
+ const payload = `<script>window.__EMMA_BOOT__=${scriptJson(boot)};`
208
+ + (state ? `window.__EMMA_STATE__=${scriptJson(state)};` : "")
209
+ + "</script>";
210
+ // A replacement function, not a string: `$$`, `$&`, `$'` in the payload (policy text
211
+ // and paths are free-form) would otherwise be expanded while injecting.
212
+ return html.replace("<!--__EMMA_BOOT__-->", () => payload);
213
+ }
214
+
215
+ function describe(plan) {
216
+ return plan.files.map((entry) => ({
217
+ key: entry.key,
218
+ path: entry.path,
219
+ sample: entry.sample,
220
+ conflict: entry.conflict === true,
221
+ notice: entry.notice,
222
+ reload: entry.reload,
223
+ changes: entry.changes,
224
+ }));
225
+ }
226
+
227
+ function readBody(request) {
228
+ return new Promise((resolve, reject) => {
229
+ let size = 0;
230
+ let tooLarge = false;
231
+ const chunks = [];
232
+ request.on("data", (chunk) => {
233
+ size += chunk.length;
234
+ if (size > MAX_BODY) {
235
+ tooLarge = true;
236
+ chunks.length = 0;
237
+ return;
238
+ }
239
+ chunks.push(chunk);
240
+ });
241
+ request.on("end", () => resolve(tooLarge ? null : Buffer.concat(chunks).toString("utf8")));
242
+ request.on("error", reject);
243
+ });
244
+ }
245
+
246
+ function send(response, status, payload) {
247
+ if (response.writableEnded) return;
248
+ const body = `${JSON.stringify(payload)}\n`;
249
+ response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "content-length": Buffer.byteLength(body) });
250
+ response.end(body);
251
+ }