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,997 @@
1
+ // Wiring between this page and Emma's configuration files.
2
+ //
3
+ // The page itself is the approved mock: what changes here is where the numbers come
4
+ // from and where they go. On load every bound control is filled from disk, and on
5
+ // save the page asks the service to plan the diff first, shows exactly that diff,
6
+ // and only then writes. With `--no-server` there is no service: the page turns the
7
+ // same values into a patch file for `/config apply`.
8
+ const $ = (selector, root = document) => root.querySelector(selector);
9
+ const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
10
+
11
+ // The native <select> stays in the DOM so value reads, change events and the writer
12
+ // contract are untouched; a button plus a list renders the same options in the page's
13
+ // own style instead of the OS popup.
14
+ function closeSel(wrap) {
15
+ if (wrap.classList.contains("segment-select")) return;
16
+ wrap.classList.remove("open");
17
+ const menu = $(".sel-menu", wrap);
18
+ menu?.hidePopover?.();
19
+ if (menu) menu.hidden = true;
20
+ const button = $(".sel-btn", wrap);
21
+ if (button) button.setAttribute("aria-expanded", "false");
22
+ }
23
+
24
+ function syncSel(select) {
25
+ const wrap = select.closest(".sel");
26
+ if (!wrap) return;
27
+ const current = select.selectedOptions[0];
28
+ const button = $(".sel-btn", wrap);
29
+ $(".sel-txt", wrap).textContent = current ? current.textContent : "";
30
+ button.disabled = select.disabled;
31
+ button.setAttribute("aria-label", (select.getAttribute("aria-label") ?? "选择") + ":" + (current?.textContent ?? ""));
32
+ const menu = $(".sel-menu", wrap);
33
+ const segmented = wrap.classList.contains("segment-select");
34
+ if (segmented) {
35
+ const options = [...select.options];
36
+ if (menu.children.length !== options.length || options.some((option, index) => menu.children[index]?.dataset.value !== option.value)) {
37
+ menu.replaceChildren(...options.map(option => {
38
+ const item = node("button", "", option.textContent);
39
+ item.type = "button";
40
+ item.dataset.value = option.value;
41
+ item.setAttribute("role", "radio");
42
+ item.onclick = () => { select.value = option.value; select.dispatchEvent(new Event("change", { bubbles: true })); };
43
+ return item;
44
+ }));
45
+ }
46
+ options.forEach((option, index) => {
47
+ const item = menu.children[index];
48
+ item.disabled = select.disabled || option.disabled;
49
+ item.setAttribute("aria-checked", String(index === select.selectedIndex));
50
+ item.setAttribute("aria-pressed", String(index === select.selectedIndex));
51
+ });
52
+ return;
53
+ }
54
+ menu.replaceChildren(...[...select.options].map((option, index) => {
55
+ const item = Object.assign(document.createElement("button"), {
56
+ type: "button", className: "sel-opt", textContent: option.textContent, role: "option",
57
+ });
58
+ item.disabled = option.disabled;
59
+ item.setAttribute("aria-selected", String(index === select.selectedIndex));
60
+ if (index === select.selectedIndex) item.classList.add("on");
61
+ item.addEventListener("click", () => {
62
+ select.selectedIndex = index;
63
+ closeSel(wrap);
64
+ button.focus();
65
+ select.dispatchEvent(new Event("change", { bubbles: true }));
66
+ });
67
+ return item;
68
+ }));
69
+ }
70
+
71
+ let selWired = false;
72
+ function enhanceSelect(select) {
73
+ if (select.closest(".sel")) return select;
74
+ const wrap = document.createElement("div");
75
+ wrap.className = "sel" + (select.dataset.segmented ? " segment-select" : "");
76
+ select.tabIndex = -1;
77
+ select.setAttribute("aria-hidden", "true");
78
+ select.before(wrap);
79
+ wrap.append(select);
80
+ const button = Object.assign(document.createElement("button"), { type: "button", className: "sel-btn" });
81
+ button.setAttribute("aria-haspopup", "listbox");
82
+ button.setAttribute("aria-expanded", "false");
83
+ button.id = select.id + "-trigger";
84
+ const label = document.querySelector('label[for="' + select.id + '"]');
85
+ if (label) label.htmlFor = button.id;
86
+ const segmented = Boolean(select.dataset.segmented);
87
+ const menu = Object.assign(document.createElement("div"), { className: "sel-menu" + (segmented ? " segmented" : ""), role: segmented ? "radiogroup" : "listbox" });
88
+ menu.setAttribute("aria-label", select.getAttribute("aria-label") ?? "选择");
89
+ menu.hidden = !segmented;
90
+ if (!segmented && typeof menu.showPopover === "function") menu.setAttribute("popover", "manual");
91
+ button.append(Object.assign(document.createElement("span"), { className: "sel-txt" }),
92
+ Object.assign(document.createElement("i"), { className: "sel-chev" }));
93
+ wrap.append(button, menu);
94
+ button.addEventListener("click", () => {
95
+ if (wrap.classList.contains("open")) return closeSel(wrap);
96
+ for (const other of $$(".sel.open")) closeSel(other);
97
+ syncSel(select);
98
+ menu.hidden = false;
99
+ menu.showPopover?.();
100
+ const rect = button.getBoundingClientRect();
101
+ const width = Math.min(Math.max(rect.width, menu.scrollWidth), innerWidth - 24);
102
+ menu.style.width = width + "px";
103
+ menu.style.left = Math.max(12, Math.min(rect.right - width, innerWidth - width - 12)) + "px";
104
+ menu.style.top = Math.max(12, Math.min(rect.bottom + 6, innerHeight - menu.offsetHeight - 12)) + "px";
105
+ wrap.classList.add("open");
106
+ button.setAttribute("aria-expanded", "true");
107
+ $(".sel-opt.on", menu)?.focus();
108
+ });
109
+ menu.addEventListener("keydown", event => {
110
+ const items = [...menu.children].filter(item => !item.disabled);
111
+ let index = items.indexOf(document.activeElement);
112
+ if (["ArrowDown", "ArrowRight"].includes(event.key)) index = (index + 1) % items.length;
113
+ else if (["ArrowUp", "ArrowLeft"].includes(event.key)) index = (index - 1 + items.length) % items.length;
114
+ else if (event.key === "Home") index = 0;
115
+ else if (event.key === "End") index = items.length - 1;
116
+ else return;
117
+ event.preventDefault();
118
+ items[index]?.focus();
119
+ if (segmented) items[index]?.click();
120
+ });
121
+ if (segmented) button.hidden = true;
122
+ select.addEventListener("change", () => syncSel(select));
123
+ wrap.addEventListener("focusout", () => queueMicrotask(() => { if (!wrap.contains(document.activeElement)) closeSel(wrap); }));
124
+ if (!selWired) {
125
+ selWired = true;
126
+ document.addEventListener("click", event => {
127
+ for (const other of $$(".sel.open")) if (!other.contains(event.target)) closeSel(other);
128
+ });
129
+ document.addEventListener("scroll", event => {
130
+ for (const other of $$(".sel.open")) if (!$(".sel-menu", other)?.contains(event.target)) closeSel(other);
131
+ }, true);
132
+ window.addEventListener("resize", () => { for (const other of $$(".sel.open")) closeSel(other); });
133
+ document.addEventListener("keydown", event => {
134
+ if (event.key !== "Escape") return;
135
+ for (const other of $$(".sel.open")) {
136
+ closeSel(other);
137
+ $(".sel-btn", other)?.focus();
138
+ }
139
+ });
140
+ }
141
+ syncSel(select);
142
+ return select;
143
+ }
144
+
145
+ function syncSelects() {
146
+ for (const select of $$(".sel select")) syncSel(select);
147
+ }
148
+
149
+ // Bindings are populated from the same registry schema used by the writer.
150
+ const BINDINGS = [];
151
+
152
+
153
+ const FILE_PANELS = { jev: 'review', jevPolicy: 'review', blackhole: 'compression', piCcExtensions: 'pi-cc-extensions', piFff: 'fff', piBtw: 'btw', mcp: 'mcp' };
154
+ const UI_LABELS = { rvEnabled: '启用评审门', rvUncertain: '不确定时', rvProtectedPaths: '额外保护路径', rvPolicy: '补充策略', cpEnabled: '启用原生压缩', webDefault: '默认搜索提供方', webToolActivation: '工具激活', enabledModels: '启用模型列表', rvTimeout: '判定超时(ms)', rvRetries: '失败重试(次)', rvMaxState: '状态上限(字符)', webInlineCap: '正文上限(字符)', webFetchTimeout: '抓取超时(ms)', btwRatio: '侧栏占比' };
155
+ const THRESHOLDS = ['thIntent','thPolicy','thLocal','thSecret','thDamage','thOutward','thPath','thFetch','thInject'];
156
+ const CALIBRATED = [.6,.8,.9,.97,.8,.9,.9,.9,.8];
157
+ const GROUP_ORDER = ['review-main','review-runtime','review-rules','review-thresholds','blackhole','native-compaction','web-main','web-fetch','web-tools','web-summary','web-safety','web-keys','agents-main','agents-roles','piCcExtensions','piFff','piBtw','mcp-main','mcp-servers','pi-core','appearance'];
158
+ const GROUP_LABELS = { 'review-main': '', 'review-runtime': '判定行为', 'review-rules': '命令与路径规则', 'review-thresholds': '评审阈值', blackhole:'pi-blackhole', 'native-compaction':'Pi 原生压缩', 'web-main':'搜索', 'web-fetch':'内容抓取', 'web-tools':'工具开关', 'web-summary':'摘要', 'web-safety':'安全与代理', 'web-keys':'Provider 凭据', 'agents-main':'全局调度', 'agents-roles':'角色覆盖', 'mcp-main':'工具与输出', 'mcp-servers':'MCP 服务' };
159
+ export function fieldPanel(field) { return FILE_PANELS[field.file] ?? (field.id.startsWith('cp') ? 'compression' : field.group); }
160
+ export function controlKind(field) {
161
+ if (field.kind === 'boolean') return 'switch';
162
+ if (field.kind === 'theme') return 'theme';
163
+ if (field.id === 'rvModel' || field.kind === 'enum') return 'select';
164
+ if (field.kind === 'string-list' || ['rvPolicy','webSummaryInstructions'].includes(field.id)) return 'textarea';
165
+ if (field.kind === 'mcp-servers') return 'mcp';
166
+ if (THRESHOLDS.includes(field.id)) return 'range';
167
+ return ['number','integer'].includes(field.kind) ? 'number' : 'text';
168
+ }
169
+ export function jevModelOptions(current = '') {
170
+ const options = [{ value: '', label: '自动跟随最新(jev-latest)' }];
171
+ if (current) options.push({ value: current, label: current === 'jev-latest' ? 'jev-latest' : current + '(已固定)' });
172
+ return options;
173
+ }
174
+ function fieldGroup(field) {
175
+ const id = field.id;
176
+ if (field.kind === 'theme') return 'appearance';
177
+ if (THRESHOLDS.includes(id)) return 'review-thresholds';
178
+ if (field.file === 'jevPolicy' || ['rvSafeCommands','rvAllowedCommands','rvDisallowedCommands','rvProtectedPaths'].includes(id)) return 'review-rules';
179
+ if (field.file === 'jev') return ['rvEnabled','rvModel'].includes(id) ? 'review-main' : 'review-runtime';
180
+ if (id.startsWith('cp')) return 'native-compaction';
181
+ if (field.group === 'agents') return id.startsWith('role') ? 'agents-roles' : 'agents-main';
182
+ if (field.file === 'mcp') return id === 'mcpServers' ? 'mcp-servers' : 'mcp-main';
183
+ if (field.group === 'web') {
184
+ if (field.kind === 'secret') return 'web-keys';
185
+ if (id.startsWith('webTool_') || id === 'webToolActivation') return 'web-tools';
186
+ if (id.includes('Summary') || id === 'webWorkflow') return 'web-summary';
187
+ if (['webProxy','webSsrfRanges','webTrustProxy','webBrowserCookies'].includes(id)) return 'web-safety';
188
+ if (id.includes('Fetch') || id === 'webInlineCap') return 'web-fetch';
189
+ return 'web-main';
190
+ }
191
+ return field.file === 'piSettings' ? 'pi-core' : field.file;
192
+ }
193
+ function node(tag, className, text) {
194
+ const element = document.createElement(tag); if (className) element.className = className; if (text !== undefined) element.textContent = text; return element;
195
+ }
196
+ function renderPluginControls(fields) {
197
+ // The server supplies every registered field, including its native enum and bounds.
198
+ // One renderer owns the reference's setting/group structure for all panels.
199
+ BINDINGS.splice(0);
200
+ const mounts = new Map();
201
+ const sorted = [...fields].sort((a,b) => GROUP_ORDER.indexOf(fieldGroup(a)) - GROUP_ORDER.indexOf(fieldGroup(b)) || (a.id === 'rvEnabled' ? -1 : b.id === 'rvEnabled' ? 1 : 0));
202
+ for (const field of sorted) {
203
+ if (['providers','credentials'].includes(field.kind)) continue;
204
+ const panel = fieldPanel(field); const section = $('section[data-group="' + panel + '"]');
205
+ if (!section) continue;
206
+ const baseKey = panel + ':' + fieldGroup(field);
207
+ let mount = mounts.get(baseKey);
208
+ if (!mount || field.section) {
209
+ const title = field.section ?? GROUP_LABELS[fieldGroup(field)];
210
+ if (title) section.append(node('div','subsection-label',title));
211
+ mount = node('div','group'); mount.dataset.pluginFields = field.file; section.append(mount); mounts.set(baseKey,mount);
212
+ if (fieldGroup(field) === 'review-thresholds') renderThresholdPresets(mount);
213
+ }
214
+ const row = node('div','setting row plugin-row'); row.dataset.fieldId = field.id;
215
+ const labelBox = node('div'); const label = node('label','setting-title lbl',UI_LABELS[field.id] ?? field.label);
216
+ label.htmlFor = 'config-' + field.id; labelBox.append(label);
217
+ const ctl = node('div','value ctl'); let control; const kind = controlKind(field);
218
+ const list = field.kind === 'string-list';
219
+ if (kind === 'switch') { control = node('input','switch switch-input'); control.type = 'checkbox'; control.setAttribute('role','switch'); }
220
+ else if (kind === 'select') {
221
+ control = node('select','select');
222
+ if (field.id !== 'rvModel' && field.values?.length <= 3) control.dataset.segmented = 'true';
223
+ const options = field.id === 'rvModel' ? jevModelOptions() : field.selectOptions ?? field.values.map(value => ({value,label:value || '继承 / 未设置'}));
224
+ control.append(...options.map(option => Object.assign(node('option','',option.label),{value:option.value})));
225
+ } else if (kind === 'textarea') {
226
+ control = node('textarea','text-area'); control.rows = field.id === 'rvPolicy' ? 4 : 3; row.classList.add('setting-stack');
227
+ if (list) control.dataset.lines = 'true';
228
+ } else if (kind === 'mcp') { control = node('div','mcp-list'); row.classList.add('setting-stack'); }
229
+ else if (kind === 'theme') {
230
+ // The value carrier stays a native select so fill/snapshot/diff keep one code
231
+ // path; the cards are the visible control and only mirror its value.
232
+ control = node('select','select theme-select');
233
+ control.hidden = true;
234
+ const themes = state.themes ?? [];
235
+ control.append(...themes.map(theme => Object.assign(node('option','',theme.name),{value:theme.name})));
236
+ const grid = node('div','theme-grid');
237
+ for (const theme of themes) {
238
+ const card = node('button','theme-card');
239
+ card.type = 'button';
240
+ card.dataset.value = theme.name;
241
+ card.setAttribute('aria-pressed','false');
242
+ card.append(themePreview(theme), node('span','theme-name',theme.name), node('span','theme-source',theme.source));
243
+ card.onclick = () => { control.value = theme.name; syncThemeCards(); syncDirty(); };
244
+ grid.append(card);
245
+ }
246
+ row.classList.add('setting-stack');
247
+ ctl.append(grid);
248
+ }
249
+ else {
250
+ control = node('input','text-input');
251
+ control.type = field.kind === 'secret' ? 'password' : kind === 'number' ? 'number' : kind === 'range' ? 'range' : 'text';
252
+ if (kind === 'range') { control.className = 'range'; control.dataset.th = ''; }
253
+ if (['range','number'].includes(kind)) { control.min = field.exclusiveMin ? String(field.min + .000001) : String(field.min); control.max = String(field.max); control.step = field.kind === 'integer' ? '1' : 'any'; }
254
+ if (field.kind === 'secret') { control.dataset.field = field.id; control.autocomplete = 'new-password'; }
255
+ }
256
+ control.id = 'config-' + field.id;
257
+ if (field.maxLength) control.maxLength = field.maxLength;
258
+ control.setAttribute('aria-label', UI_LABELS[field.id] ?? field.label);
259
+ if (field.placeholder) control.placeholder = field.placeholder;
260
+ if (list) control.placeholder = '每行一项';
261
+ if (field.empty === 'inherit') control.placeholder = '跟随当前会话模型';
262
+ if (field.id === 'webDefault') { control.id = 'webDefault'; control.setAttribute('list','webProviderList'); control.placeholder = 'auto 或选择搜索服务'; }
263
+ ctl.append(control); row.append(labelBox,ctl); mount.append(row);
264
+ if (kind === 'select') enhanceSelect(control);
265
+ if (kind === 'theme') BINDINGS.push([field.id,panel,field.label,'select','#' + control.id]);
266
+ if (kind === 'range') { const output = node('output','range-value val'); output.htmlFor = control.id; ctl.append(output); control.addEventListener('input', () => { output.value = Number(control.value).toFixed(2); }); }
267
+ if (field.kind !== 'secret' && kind !== 'theme') BINDINGS.push([field.id,panel,field.label,kind,'#' + control.id]);
268
+ }
269
+ const list = node('datalist'); list.id = 'webProviderList';
270
+ for (const value of fields.find(field => field.id === 'webDefault')?.values ?? []) list.append(Object.assign(node('option'),{value}));
271
+ document.body.append(list);
272
+ const jevGroup = $('section[data-group="review"] .group');
273
+ if (jevGroup) { const row = node('div','setting'); row.innerHTML = '<div><p class="setting-title">Jev 凭据</p></div><div class="value"><code>/jev-auto-mode login</code></div>'; jevGroup.append(row); }
274
+ }
275
+ function renderThresholdPresets(mount) {
276
+ const row = node('div','setting'); const text = node('div'); text.append(node('p','setting-title','阈值预设'));
277
+ const ctl = node('div','value'); const seg = node('div','segmented'); seg.id = 'threshold-presets';
278
+ for (const [label,values] of [['宽松',CALIBRATED.map(value => Math.max(.500001,value - .05))],['校准默认',CALIBRATED],['严格',CALIBRATED.map(value => Math.min(1,value + .05))]]) {
279
+ const button = node('button','',label); button.type='button'; button.dataset.values=JSON.stringify(values); button.setAttribute('aria-pressed','false');
280
+ button.onclick=() => { THRESHOLDS.forEach((id,index) => { const input = document.getElementById('config-' + id); if (input && !input.disabled) input.value=values[index]; }); syncVisuals(); }; seg.append(button);
281
+ }
282
+ ctl.append(seg); row.append(text,ctl); mount.append(row);
283
+ }
284
+
285
+
286
+ function showSources() {
287
+ for (const node of document.querySelectorAll("[data-config-source]")) node.remove();
288
+ const sourceBindings = [...BINDINGS, ...$$('[data-field]').map(input => [input.dataset.field, null, null, 'secret', '#' + input.id])];
289
+ for (const binding of sourceBindings) {
290
+ const [id] = binding;
291
+ const control = resolveControl(binding);
292
+ if (!control) continue;
293
+ const file = state.files[state.fields[id]];
294
+ if (!file) continue;
295
+ const warning = state.fieldMeta?.[id]?.warning;
296
+ const readonly = file.writable === false || Boolean(warning);
297
+ if (control.matches("input, select, textarea")) control.disabled = readonly;
298
+ else control.querySelectorAll("input,button,textarea,select").forEach(e => e.disabled = readonly);
299
+ control.dataset.configReadonly = String(readonly);
300
+ const row = control.closest(".row");
301
+ if (row) {
302
+ row.querySelector("[data-value-source]")?.remove();
303
+ if (warning) {
304
+ const hint = document.createElement("small"); hint.dataset.valueSource = "true"; hint.className = "key";
305
+ hint.textContent = "环境变量覆盖";
306
+ row.querySelector(".lbl")?.append(hint);
307
+ }
308
+ }
309
+ if (row) row.title = [file.path, file.version && "v" + file.version, file.warning, warning].filter(Boolean).join(" · ");
310
+ const section = control.closest('section[data-group]');
311
+ const noteText = file.writable === false ? file.warning : file.projectOverride ? "当前项目覆盖:" + file.projectOverride : null;
312
+ if (!section || !noteText) continue;
313
+ if (section.querySelector('[data-config-source="' + state.fields[id] + '"]')) continue;
314
+ const note = document.createElement("div");
315
+ note.dataset.configSource = state.fields[id];
316
+ note.className = "note";
317
+ note.textContent = noteText;
318
+ const header = section.querySelector(".page-head");
319
+ if (header) header.after(note);
320
+ else section.prepend(note);
321
+ }
322
+ syncSelects();
323
+ }
324
+
325
+ const state = { mode: "server", token: null, origin: null, values: {}, present: {}, files: {}, baseline: {} };
326
+
327
+ // A control's raw value is a string; the registry type decides what it means. Without
328
+ // this, every numeric field would look "changed" (4000 vs "4000") and be written on
329
+ // every save.
330
+ export function typedValue(kind, raw) {
331
+ if (kind === "number" || kind === "range") {
332
+ const numeric = Number(raw);
333
+ return Number.isFinite(numeric) ? numeric : raw;
334
+ }
335
+ return raw;
336
+ }
337
+
338
+ export function isChanged(baseline, next) {
339
+ return JSON.stringify(baseline) !== JSON.stringify(next);
340
+ }
341
+
342
+ const resolveControl = (binding) => document.querySelector(binding[4]);
343
+
344
+ const enumValue = (button) => {
345
+ const explicit = button.dataset.value;
346
+ if (explicit) return explicit;
347
+ const text = button.textContent.trim();
348
+ const cut = text.indexOf("(");
349
+ return cut > 0 ? text.slice(0, cut) : text;
350
+ };
351
+
352
+ function fill(restoredValues = null) {
353
+ for (const binding of BINDINGS) {
354
+ const [id,,,kind] = binding; const control = resolveControl(binding); if (!control) continue;
355
+ const value = restoredValues && Object.hasOwn(restoredValues, id) ? restoredValues[id] : state.values[id] ?? state.defaults?.[id];
356
+ const missing = value === undefined || value === null;
357
+ if (kind === 'switch') control.checked = value === true;
358
+ else if (kind === 'mcp') renderMcpPanel(control, state.values.mcpServers ?? {}, state.mcpDetail ?? {}, restoredValues?.mcpServers);
359
+ else if (control.dataset.lines) control.value = Array.isArray(value) ? value.join('\n') : '';
360
+ else if (kind === 'select') {
361
+ const chosen = missing ? '' : String(value);
362
+ if (id === 'rvModel') control.replaceChildren(...jevModelOptions(chosen).map(option => Object.assign(node('option','',option.label),{value:option.value})));
363
+ if (chosen && ![...control.options].some(option => option.value === chosen)) control.append(Object.assign(node('option','',chosen),{value:chosen}));
364
+ if (!chosen && ![...control.options].some(option => option.value === '')) control.prepend(Object.assign(node('option','','插件默认 / 未设置'),{value:''}));
365
+ control.value = chosen;
366
+ } else if (kind === 'range') control.value = String(missing ? CALIBRATED[THRESHOLDS.indexOf(id)] : value);
367
+ else control.value = missing ? '' : Array.isArray(value) ? JSON.stringify(value) : String(value);
368
+ }
369
+ fillSecrets(); fillProviders(); syncVisuals(); syncSelects();
370
+ }
371
+
372
+ // Refresh threshold readouts and the selected preset after load, reset and edits.
373
+ function syncVisuals() {
374
+ for (const range of $$('[data-th]')) { const out=range.parentElement.querySelector('.val'); if(out) out.value=Number(range.value).toFixed(2); }
375
+ const values=THRESHOLDS.map(id => Number(document.getElementById('config-' + id)?.value));
376
+ for (const button of $$('#threshold-presets button')) { const match=JSON.parse(button.dataset.values).every((value,index) => Math.abs(value-values[index]) < .0000001); button.setAttribute('aria-pressed',String(match)); button.disabled=THRESHOLDS.some(id => document.getElementById('config-' + id)?.disabled); }
377
+ syncCredentialHint();
378
+ syncThemeCards();
379
+ }
380
+
381
+ // The theme cards mirror the hidden select, so the select stays the single value owner.
382
+ function syncThemeCards() {
383
+ for (const card of $$('.theme-card')) {
384
+ const row = card.closest('[data-field-id]');
385
+ const select = row && document.getElementById('config-' + row.dataset.fieldId);
386
+ card.setAttribute('aria-pressed', String(select?.value === card.dataset.value));
387
+ }
388
+ }
389
+
390
+ function themePreview(theme) {
391
+ const box = node('span','theme-preview');
392
+ // A built-in theme has no file behind it, so its card keeps the neutral swatch.
393
+ const colors = theme.colors;
394
+ if (colors) {
395
+ box.style.setProperty('--t-bg', colors.bg);
396
+ box.style.setProperty('--t-fg', colors.fg);
397
+ if (colors.accent) box.style.setProperty('--t-accent', colors.accent);
398
+ if (colors.success) box.style.setProperty('--t-ok', colors.success);
399
+ }
400
+ box.append(node('span','t-line'), node('span','t-code'), node('span','t-status'));
401
+ return box;
402
+ }
403
+
404
+ // Pi credentials live in auth.json keyed by provider; the page is told which providers
405
+ // have one (names only), so the key box can say whether leaving it blank keeps a key.
406
+ function syncCredentialHint() {
407
+ const key = $("#pv-key");
408
+ const selected = $("#pv-list .pv-row.sel");
409
+ if (!key || !selected || $("#pv-detail")?.hidden) return;
410
+ key.placeholder = (state.credentials ?? []).includes(selected.dataset.id)
411
+ ? "已保存(留空则保持不变)"
412
+ : "粘贴密钥";
413
+ }
414
+
415
+ // Plugin list fields use the generic renderer above; no plugin-specific chip schema is assumed.
416
+
417
+ function fillSecrets() {
418
+ for (const input of $$('[data-field]')) { input.value=''; input.placeholder=state.present[input.dataset.field] ? '已保存(留空保持不变)' : '粘贴密钥'; }
419
+ $('#pv-key').value='';
420
+ }
421
+
422
+ // Providers come from models.json. Only changed drafts enter the write plan.
423
+ const API_FOR_PAGE = { "openai-completions": "chat", "openai-responses": "responses", "anthropic-messages": "anthropic" };
424
+
425
+ function fillProviders() {
426
+ const registry = state.values.providerRegistry ?? {};
427
+ const rows = Object.entries(registry).map(([id, provider]) => ({
428
+ id,
429
+ name: id,
430
+ url: provider.baseUrl,
431
+ api: API_FOR_PAGE[provider.api] ?? null,
432
+ key: "",
433
+ models: (provider.models ?? []).map((model) => model.id),
434
+ ctx: (provider.models ?? [])[0]?.contextWindow ?? 200000,
435
+ comp: "auto",
436
+ out: 32000,
437
+ icon: "",
438
+ builtin: false,
439
+ enabled: true,
440
+ fromDisk: true,
441
+ catalog: (provider.models ?? []).map((model) => model.id),
442
+ }));
443
+ const providers = window.__EMMA_PROVIDERS__;
444
+ if (!providers) return;
445
+ const added = providers.setProviders(rows);
446
+ if (added) providers.relayout();
447
+ }
448
+
449
+ // Every file-backed control's current value, typed. This is what the form would send
450
+ // and what the baseline is rebuilt from after a write.
451
+ function snapshot() {
452
+ const values = {};
453
+ for (const binding of BINDINGS) {
454
+ const [id, , , kind] = binding;
455
+ const control = resolveControl(binding);
456
+ if (!control) continue;
457
+ if (control.dataset.configReadonly === "true") continue;
458
+ const value = readControl(control, kind);
459
+ if (value !== undefined) values[id] = value;
460
+ }
461
+ return values;
462
+ }
463
+
464
+ // Only fields the user actually changed are sent: the page ships with display
465
+ // defaults for anything a file omits, and writing those back would invent values.
466
+ function collect() {
467
+ const values = {};
468
+ for (const [id, value] of Object.entries(snapshot())) {
469
+ if (isChanged(state.baseline[id], value)) values[id] = value;
470
+ }
471
+ collectSecrets(values);
472
+ collectProviderDraft(values);
473
+ return values;
474
+ }
475
+
476
+ // The footer hint and the save button both follow the real diff. It has to be rebuilt
477
+ // from the controls, never from the previous diff, or the second save invents values.
478
+ function syncDirty() {
479
+ const save = $("#save");
480
+ if (save) save.disabled = Object.keys(collect()).length === 0;
481
+ }
482
+
483
+ // The 模型与凭据 page keeps its own draft in memory; its 保存配置 must go through the
484
+ // same diff, so the open provider's panel is read into the registry value here.
485
+ function collectProviderDraft(values) {
486
+ const providers=window.__EMMA_PROVIDERS__;
487
+ if(!providers) return;
488
+ const drafts=providers.drafts();
489
+ const entries={}; const credentials={};
490
+ for(const draft of drafts) {
491
+ const loaded=(state.values.providerRegistry ?? {})[draft.id];
492
+ const shape={baseUrl:draft.baseUrl,api:API_BY_PAGE[draft.api],models:draft.models,contextWindow:draft.contextWindow};
493
+ const entry=providerDraft(loaded,shape);
494
+ const touched = isChanged(
495
+ { baseUrl: loaded?.baseUrl ?? '', api: loaded?.api, models: (loaded?.models ?? []).map(model => model.id), contextWindow: loaded?.models?.[0]?.contextWindow ?? SUGGESTED_CAPACITY },
496
+ { ...shape, api: shape.api ?? loaded?.api }
497
+ );
498
+ // An existing partial override is valid Pi config. Only new or edited drafts
499
+ // enter validation; never manufacture a write for an untouched override.
500
+ const entered = draft.fresh && Boolean(draft.id || draft.baseUrl || draft.models.length || draft.key);
501
+ const invalidCapacity = !Number.isInteger(draft.contextWindow) || draft.contextWindow < 1;
502
+ if (state.files.models?.writable !== false && (entered || (!draft.fresh && touched))) {
503
+ entries[draft.id] = invalidCapacity
504
+ ? { ...(entry ?? {}), baseUrl: draft.baseUrl, api: shape.api, models: draft.models.map(id => ({ id, contextWindow: draft.contextWindow })) }
505
+ : entry ?? { baseUrl: draft.baseUrl, api: shape.api, models: draft.models.map(id => ({ id })) };
506
+ }
507
+ if(draft.key && state.files.auth?.writable !== false) credentials[draft.id]={type:'api_key',key:draft.key};
508
+ }
509
+ if(Object.keys(entries).length) values.providerRegistry=entries;
510
+ if(Object.keys(credentials).length) values.credentialChanges=credentials;
511
+ }
512
+
513
+ // What a provider entry should become, given the panel's values, or null when the page
514
+ // owns nothing that differs. Pure so the rule can be tested without a browser.
515
+ export function providerDraft(loaded, { baseUrl, api, models, contextWindow, suggested = SUGGESTED_CAPACITY }) {
516
+ if (!baseUrl || !models.length) return null;
517
+
518
+ // The panel offers three of Pi's `KnownApi` values. A provider registered with any
519
+ // other api has no segment to change it in the page, so the page must carry the disk
520
+ // value rather than inventing `openai-completions` for it.
521
+ const effectiveApi = api ?? loaded?.api;
522
+
523
+ // Capacity is a single control over a per-model field, so it is only written when it
524
+ // moved away from what the file carries (or from the page's suggestion when the file
525
+ // says nothing). Unchanged models are sent without it, which is what lets the writer
526
+ // preserve each model's own capacity — a provider may legitimately have several.
527
+ const diskCapacity = (loaded?.models ?? [])[0]?.contextWindow;
528
+ const capacityMoved = contextWindow > 0 && contextWindow !== (diskCapacity ?? suggested);
529
+
530
+ // Compare a projection, not the disk entry: the entry also carries name, cost,
531
+ // maxTokens, compat and per-model capacities the page never edits, and comparing the
532
+ // whole object would report an untouched provider as changed.
533
+ const projection = (shape) => ({ baseUrl: shape.baseUrl, api: shape.api, models: shape.models, capacity: shape.capacity });
534
+ const before = projection({ baseUrl: loaded?.baseUrl, api: loaded?.api, models: (loaded?.models ?? []).map((model) => model.id), capacity: diskCapacity });
535
+ const after = projection({ baseUrl, api: effectiveApi, models, capacity: capacityMoved ? contextWindow : diskCapacity });
536
+ if (!isChanged(before, after)) return null;
537
+
538
+ return {
539
+ ...(baseUrl !== loaded?.baseUrl ? { baseUrl } : {}),
540
+ api: effectiveApi,
541
+ models: models.map((model) => (capacityMoved ? { id: model, contextWindow } : { id: model })),
542
+ };
543
+ }
544
+
545
+ export function readControl(control, kind) {
546
+ if (control.id === "webDefault" && control.value.trim().startsWith("[")) {
547
+ try { return JSON.parse(control.value); } catch { return control.value; }
548
+ }
549
+ if (control.dataset.lines) return control.value.split(/\r?\n/).map(value => value.trim()).filter(Boolean);
550
+ if (kind === "switch") return control.checked;
551
+ if (kind === "list") return control.value.split(/\r?\n/).map(value => value.trim()).filter(Boolean);
552
+ if (kind === "mcp") return readMcpPanel(control);
553
+ return typedValue(kind, control.value);
554
+ }
555
+
556
+ // The 服务 panel is rebuilt from disk: the design's mock list would otherwise show
557
+ // servers the user does not have and hide the ones they do. Each row owns the enable
558
+ // toggle and, when its address is not masked, that address — the page never receives
559
+ // env, headers or command arguments.
560
+ function renderMcpPanel(container, toggles, details, restored) {
561
+ container.replaceChildren();
562
+ if (!Object.keys(toggles).length) { container.append(node('p','helper','没有 MCP 服务')); return; }
563
+ for (const [id,enabled] of Object.entries(toggles)) {
564
+ const detail=details[id] ?? {}; const row=node('div','mcp-server'); row.dataset.server=id;
565
+ const heading=node('div','mcp-heading'); const label=node('label','',id); const toggle=node('input','switch switch-input'); toggle.type='checkbox'; toggle.checked=restored?.[id]?.enabled ?? enabled; toggle.setAttribute('role','switch'); toggle.id='mcp-server-' + Object.keys(toggles).indexOf(id); label.htmlFor=toggle.id;
566
+ heading.append(label,toggle); row.append(heading); row.append(node('p','helper',detail.transport ?? ''));
567
+ if (detail.url) { if (detail.urlEditable) { const input=node('input','text-input'); input.type='url'; input.dataset.mcp='url'; input.value=restored?.[id]?.url ?? detail.url; input.setAttribute('aria-label',id + ' 地址'); row.append(input); } else row.append(node('p','helper',detail.url)); }
568
+ if (detail.command) row.append(node('p','helper',detail.command));
569
+ if (detail.hasEnv || detail.hasHeaders) row.append(node('p','helper','环境变量与请求头已隐藏。'));
570
+ container.append(row);
571
+ }
572
+ }
573
+ function readMcpPanel(container) {
574
+ const servers={};
575
+ for (const row of $$('.mcp-server',container)) { const input=$('input[data-mcp="url"]',row); servers[row.dataset.server]={enabled:$('input[type=checkbox]',row).checked,...(input ? {url:input.value.trim()} : {})}; }
576
+ return servers;
577
+ }
578
+
579
+ // Secrets are addressed by an explicit data-field on the input: the providers on the
580
+ // 联网检索 page keep their key in a sibling panel, so walking the DOM would miss them.
581
+ function collectSecrets(values) {
582
+ $$("[data-field]").forEach((input) => {
583
+ const secret = input.value.trim();
584
+ const id = input.dataset.field;
585
+ const writable = state.files[state.fields[id]]?.writable !== false && !state.fieldMeta?.[id]?.warning;
586
+ if (secret && !input.disabled && writable) values[id] = secret;
587
+ });
588
+ }
589
+
590
+ const API_BY_PAGE = { chat: "openai-completions", responses: "openai-responses", anthropic: "anthropic-messages" };
591
+ // What the capacity control shows for a provider whose file carries no contextWindow.
592
+ const SUGGESTED_CAPACITY = 200000;
593
+
594
+ /* ---------- diff modal ---------- */
595
+ function showDiff(changes, problems, skipped = []) {
596
+ const body = $("#diffBody");
597
+ const skip = $("#diffSkip");
598
+ body.textContent = "";
599
+ skip.hidden = true;
600
+ let keys = 0;
601
+ for (const file of changes) {
602
+ const group = document.createElement("div");
603
+ group.className = "dgroup";
604
+ const head = document.createElement("div");
605
+ head.className = "fp";
606
+ const target = (file.path ?? file.sample) + (file.notice ? " · " + file.notice : "") + (file.reload ? " · " + file.reload : "");
607
+ head.append(file.conflict ? `${target} · 已被外部修改,本次跳过` : target);
608
+ head.append(Object.assign(document.createElement("span"), { className: "n", textContent: `${file.changes.length} 项` }));
609
+ group.append(head);
610
+ for (const change of file.changes) {
611
+ keys += 1;
612
+ const line = document.createElement("div");
613
+ line.className = "dline";
614
+ const key = document.createElement("div");
615
+ key.className = "k";
616
+ key.append(Object.assign(document.createElement("b"), { textContent: change.label }));
617
+ const value = document.createElement("div");
618
+ value.className = "v";
619
+ value.append(
620
+ Object.assign(document.createElement("del"), { textContent: change.from }),
621
+ Object.assign(document.createElement("span"), { className: "arrow", textContent: "→" }),
622
+ Object.assign(document.createElement("ins"), { textContent: change.to }),
623
+ );
624
+ line.append(key, value);
625
+ group.append(line);
626
+ }
627
+ body.append(group);
628
+ }
629
+ if (!changes.length) {
630
+ const empty = document.createElement("div");
631
+ empty.className = "dgroup";
632
+ empty.textContent = "没有需要写入的变更";
633
+ body.append(empty);
634
+ }
635
+ const notes = [...problems.map(problem => (problem.label ?? problem.id) + ':' + problem.reason), ...skipped.map(entry => entry.label + ':' + entry.reason)];
636
+ if (notes.length) { skip.hidden=false; skip.replaceChildren(...notes.map(text => node('p','',text))); }
637
+ $("#diffCount").textContent = `${keys} 项变更 · ${changes.length} 个文件`;
638
+ $("#diffOk").textContent = state.mode === "server" ? "确认写入" : "导出补丁";
639
+ $("#diffOk").disabled = problems.length > 0;
640
+ return keys;
641
+ }
642
+
643
+ const download = (name, payload) => {
644
+ const url = URL.createObjectURL(new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" }));
645
+ const link = document.createElement("a");
646
+ link.href = url;
647
+ link.download = name;
648
+ link.click();
649
+ URL.revokeObjectURL(url);
650
+ };
651
+
652
+ async function call(path, init) {
653
+ const response = await fetch(`${state.origin}${path}`, {
654
+ ...init,
655
+ headers: { "content-type": "application/json", "x-emma-token": state.token, ...(init?.headers ?? {}) },
656
+ });
657
+ const payload = await response.json();
658
+ if (!response.ok) throw new Error(payload.error ?? `HTTP ${response.status}`);
659
+ return payload;
660
+ }
661
+
662
+ function feedback(text, tone) {
663
+ const target = $("#runResult");
664
+ target.className = `res${tone === "err" ? " err" : ""}`;
665
+ target.textContent = text;
666
+ }
667
+
668
+ async function plan(values, version) {
669
+ if (state.mode !== "server") {
670
+ return { changes: localChanges(values), problems: [], skipped: localSkipped(values) };
671
+ }
672
+ return call("/api/plan", { method: "POST", body: JSON.stringify({ values, version }) });
673
+ }
674
+
675
+ // Without a service the page cannot ask which fields are read-only, so the list is
676
+ // injected with the boot payload.
677
+ function localSkipped(values) {
678
+ const readonly = state.readonly ?? [];
679
+ return Object.keys(values).filter((id) => readonly.includes(id))
680
+ .map((id) => ({ id, label: state.names?.[id] ?? id, reason: "本版只读:保存时跳过" }));
681
+ }
682
+
683
+ // Offline mode has no service to plan against, so the page describes the diff from
684
+ // the values it loaded: enough to review, and applying re-checks everything.
685
+ export function localChanges(values, view = state) {
686
+ const byFile = new Map();
687
+ const filename = (id) => view.fields[id]
688
+ ?? (id === "credentialChanges" ? "auth" : id === "providerRegistry" ? "models" : "other");
689
+ const describe = (id) => (id === "credentialChanges" ? "Pi 凭据" : id === "providerRegistry" ? "供应商注册" : id);
690
+ for (const [id, value] of Object.entries(values)) {
691
+ if (view.readonly?.includes(id)) continue;
692
+ const file = filename(id);
693
+ const before = view.baseline[id];
694
+ const semantics = view.semantics?.[id] ?? {};
695
+ const secret = semantics.kind === "secret" || semantics.kind === "credentials";
696
+ const removed = semantics.empty !== undefined && (value === semantics.empty || value === null || value === "");
697
+ const clearedText = semantics.kind === "text" && typeof value === "string" && value.trim() === "";
698
+ if (isChanged(before, value)) {
699
+ if (!byFile.has(file)) byFile.set(file, { path: view.files[file]?.path, sample: view.files[file]?.sample ?? file, conflict: false, changes: [] });
700
+ byFile.get(file).changes.push({
701
+ id, label: view.names?.[id] ?? describe(id),
702
+ from: secret ? "••••••" : render(before),
703
+ to: secret ? "••••••" : removed || clearedText ? "(未设置)" : render(value),
704
+ });
705
+ }
706
+ }
707
+ return [...byFile.values()];
708
+ }
709
+
710
+ const render = (value) => {
711
+ if (value === undefined || value === null) return "(未设置)";
712
+ if (typeof value === "boolean") return value ? "开" : "关";
713
+ if (Array.isArray(value)) return value.join(", ") || "(空)";
714
+ if (typeof value === "object") return `${Object.keys(value).length} 个条目`;
715
+ return String(value);
716
+ };
717
+ function wireSurface() {
718
+ if (window.__EMMA_PROVIDERS__) return;
719
+ for (const button of $$('.nav-button')) {
720
+ button.title = button.textContent.trim();
721
+ button.addEventListener('click', () => {
722
+ for (const item of $$('.nav-button')) item.setAttribute('aria-current',String(item === button));
723
+ for (const section of $$('section[data-group]')) section.hidden = section.dataset.group !== button.dataset.group;
724
+ $('#page-title').textContent = button.textContent.trim();
725
+ $('.main').scrollTop = 0;
726
+ history.replaceState(null,'','#' + button.dataset.group);
727
+ });
728
+ }
729
+ const initial = $$('.nav-button').find(button => '#' + button.dataset.group === location.hash);
730
+ initial?.click();
731
+ const drafts = new Map(); let selected = null; let sequence = 0;
732
+ const selectedDraft = () => drafts.get(selected);
733
+ function selectSegment(id,value) {
734
+ for (const button of $$(id + ' button')) {
735
+ const on = button.dataset.value === String(value);
736
+ button.setAttribute('aria-checked',String(on)); button.setAttribute('aria-pressed',String(on));
737
+ }
738
+ }
739
+ function renderModels() {
740
+ const draft = selectedDraft(); if (!draft) return;
741
+ const tags = $('#model-tags'); const options = $('#model-options'); tags.replaceChildren(); options.replaceChildren();
742
+ for (const id of draft.models) {
743
+ const tag = node('span','model-tag',id); const remove = node('button','','×'); remove.type='button'; remove.setAttribute('aria-label','移除 ' + id); remove.disabled = $('#pv-url').disabled;
744
+ remove.onclick=() => { draft.models=draft.models.filter(model => model !== id); renderModels(); renderList(); syncDirty(); };
745
+ tag.append(remove); tags.append(tag);
746
+ }
747
+ const query=$('#model-input').value.trim().toLowerCase();
748
+ const catalog = new Set([...(state.values.providerRegistry?.[draft.id]?.models ?? []).map(model => model.id),...draft.models]);
749
+ for (const id of catalog) {
750
+ if (!id.toLowerCase().includes(query) || draft.models.includes(id)) continue;
751
+ const button=node('button','model-option',id); button.type='button'; button.onclick=() => addModel(id); button.disabled=$('#pv-url').disabled; options.append(button);
752
+ }
753
+ }
754
+ function addModel(id) { const draft=selectedDraft(); id=id.trim(); if (!id || !draft) return; if (!draft.models.includes(id)) draft.models.push(id); $('#model-input').value=''; renderModels(); renderList(); syncDirty(); }
755
+ function renderList() {
756
+ const list=$('#pv-list'); list.replaceChildren(); $('#providers-empty')?.toggleAttribute('hidden', drafts.size > 0);
757
+ for (const [key,draft] of drafts) {
758
+ const button=node('button','provider-item pv-row' + (key === selected ? ' sel' : '')); button.type='button'; button.dataset.id=draft.id; button.setAttribute('aria-selected',String(key === selected));
759
+ const name=draft.id || '新 Provider'; const avatar=node('span','provider-avatar',name.slice(0,1).toUpperCase()); const text=node('span'); text.append(node('strong','',name),node('small','',draft.models.length + ' 个模型'));
760
+ button.append(avatar,text,node('span','provider-chevron','›')); button.onclick=() => open(key); list.append(button);
761
+ }
762
+ }
763
+ function renderModelFacts() {
764
+ const group=$('#model-settings'); group.replaceChildren();
765
+ for (const [title,value] of [
766
+ ['默认会话模型',[state.values.defProvider,state.values.defModel].filter(Boolean).join(' / ') || '未指定'],
767
+ ['已配置模型',Object.values(state.values.providerRegistry ?? {}).reduce((sum,provider) => sum+(provider.models?.length ?? 0),0) + ' 个模型']
768
+ ]) { const row=node('div','setting'); const text=node('div'); text.append(node('p','setting-title',title)); row.append(text,node('div','value',value)); group.append(row); }
769
+ }
770
+ function open(key) {
771
+ selected=key; const draft=selectedDraft(); if (!draft) return;
772
+ $('#provider-workspace').classList.add('is-editing'); $('#pv-detail').hidden=false; $('#pv-name').value=draft.id;
773
+ $('#pv-name').disabled=!draft.fresh; $('#pv-url').value=draft.baseUrl ?? ''; $('#pv-key').value=draft.key ?? '';
774
+ $('#provider-editor-title').textContent=draft.id || '新 Provider';
775
+ $('#provider-context').value=draft.contextWindow ?? ''; selectSegment('#pv-seg-api',draft.api); selectSegment('#pv-seg-ctx',draft.contextWindow);
776
+ const modelsReadonly=state.files.models?.writable === false; const authReadonly=state.files.auth?.writable === false;
777
+ for (const input of $$('#pv-detail input, #pv-detail button')) input.disabled=modelsReadonly;
778
+ $('#cancel-provider').disabled=false; $('#pv-key').disabled=authReadonly; $('#pv-name').disabled=modelsReadonly || !draft.fresh;
779
+ const status=$('#provider-status'); const hasCredential=(state.credentials ?? []).includes(draft.id);
780
+ status.textContent=modelsReadonly ? '配置只读' : hasCredential ? '凭据已配置' : '凭据未配置'; status.className='status' + (!hasCredential ? ' warning' : '');
781
+ $('#pv-key').placeholder=hasCredential ? '已保存(留空保持不变)' : '粘贴密钥';
782
+ $('#model-input').value=''; renderModels(); renderList(); syncCredentialHint();
783
+ }
784
+ function updateDraft() {
785
+ const draft=selectedDraft(); if (!draft) return;
786
+ draft.id=$('#pv-name').value.trim(); draft.baseUrl=$('#pv-url').value.trim(); draft.key=$('#pv-key').value.trim(); draft.contextWindow=Number($('#provider-context').value);
787
+ $('#provider-editor-title').textContent=draft.id || '新 Provider'; renderList(); syncDirty();
788
+ }
789
+ for (const id of ['pv-name','pv-url','pv-key','provider-context']) $('#' + id).addEventListener('input',updateDraft);
790
+ $('#provider-context').addEventListener('input',() => selectSegment('#pv-seg-ctx',$('#provider-context').value));
791
+ for (const button of $$('#pv-seg-api button, #pv-seg-ctx button')) button.onclick=() => {
792
+ const draft=selectedDraft(); if(!draft) return;
793
+ if (button.closest('#pv-seg-api')) { draft.api=button.dataset.value; selectSegment('#pv-seg-api',draft.api); }
794
+ else { draft.contextWindow=Number(button.dataset.value); $('#provider-context').value=draft.contextWindow; selectSegment('#pv-seg-ctx',draft.contextWindow); }
795
+ syncDirty();
796
+ };
797
+ $('#model-input').addEventListener('input',renderModels);
798
+ $('#model-input').addEventListener('keydown',event => { if(event.key === 'Enter') { event.preventDefault(); addModel(event.target.value); } });
799
+ $('#show-provider-form').onclick=() => {
800
+ const key='new-' + (++sequence); drafts.set(key,{id:'',fresh:true,baseUrl:'',api:'chat',models:[],contextWindow:200000,key:''}); renderList(); open(key); $('#pv-name').focus();
801
+ };
802
+ $('#cancel-provider').onclick=() => { selected=null; $('#pv-detail').hidden=true; $('#provider-workspace').classList.remove('is-editing'); renderList(); syncDirty(); };
803
+ window.__EMMA_PROVIDERS__={
804
+ setProviders(rows) {
805
+ const previous=selected; drafts.clear();
806
+ for(const row of rows) drafts.set(row.id,{id:row.id,baseUrl:row.url ?? '',api:row.api,models:[...row.models],contextWindow:row.ctx,key:'',fresh:false});
807
+ selected=null; $('#pv-detail').hidden=true; $('#provider-workspace').classList.remove('is-editing'); renderList(); renderModelFacts();
808
+ $('#show-provider-form').disabled=state.files.models?.writable === false;
809
+ if(previous && drafts.has(previous)) open(previous); return true;
810
+ },
811
+ relayout() {}, selectedModels() { return [...(selectedDraft()?.models ?? [])]; },
812
+ drafts() { return [...drafts.values()].map(draft => ({...draft,models:[...draft.models]})); }
813
+ };
814
+ // Controls inserted after bootstrap share native input/change events.
815
+ document.addEventListener('input',event => { if(event.target.matches('[data-th]')) syncVisuals(); });
816
+ document.addEventListener('keydown',event => {
817
+ if($('#diffmask').hidden || event.key !== 'Tab') return;
818
+ const focusable=$$('.diff button:not(:disabled), .diff [tabindex="0"]'); const first=focusable[0],last=focusable.at(-1);
819
+ if(event.shiftKey && (document.activeElement === first || document.activeElement === $('.diff'))) { event.preventDefault(); last?.focus(); }
820
+ else if(!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
821
+ });
822
+ }
823
+
824
+ async function boot() {
825
+ const boot = window.__EMMA_BOOT__ ?? {};
826
+ // The theme control renders before the state payload loads, so its catalog travels
827
+ // with the boot payload instead of the /api/state response.
828
+ state.themes = boot.themes ?? [];
829
+ for (const el of document.querySelectorAll("input[data-th]")) { el.min = "0.500001"; el.max = "1"; el.step = "any"; }
830
+ const stateLimit = document.getElementById("rvMaxState"); if (stateLimit) stateLimit.max = "1000000";
831
+ const timeout = document.getElementById("rvTimeout"); if (timeout) timeout.min = "250";
832
+ const params = new URLSearchParams(location.search);
833
+ state.mode = location.protocol === "file:" || !boot.token ? "export" : "server";
834
+ state.token = boot.token ?? params.get("token");
835
+ state.origin = location.origin;
836
+
837
+ let payload;
838
+ if (window.__EMMA_STATE__) {
839
+ payload = window.__EMMA_STATE__;
840
+ } else if (state.mode === "server") {
841
+ payload = await call("/api/state");
842
+ } else {
843
+ payload = { values: {}, present: {}, expectations: {}, files: {}, problems: [] };
844
+ }
845
+ renderPluginControls(boot.controls ?? []);
846
+ state.version = payload.version;
847
+ state.expectations = payload.expectations ?? {};
848
+ state.defaults = payload.defaults ?? {};
849
+ state.fieldMeta = payload.fieldMeta ?? {};
850
+ state.values = payload.values ?? {};
851
+ state.present = payload.present ?? {};
852
+ state.credentials = payload.credentials ?? [];
853
+ state.mcpDetail = payload.mcpDetail ?? {};
854
+ state.files = payload.files ?? {};
855
+ state.fields = boot.fields ?? {};
856
+ state.readonly = boot.readonly ?? [];
857
+ state.names = boot.names ?? {};
858
+ state.semantics = boot.semantics ?? {};
859
+
860
+ wireSurface();
861
+ fill();
862
+ showSources();
863
+ // Project-override notice: intentionally not rendered — the affected rows already
864
+ // carry a "项目覆盖" badge + tooltip, and openDiff() still confirms before saving.
865
+ // The baseline is what the form shows once loaded, so an untouched form collects
866
+ // nothing and a diff holds only the user's edits.
867
+ state.baseline = snapshot();
868
+ $("#diffmask").hidden = true;
869
+ if ((payload.problems ?? []).length) feedback(`${payload.problems.length} 个文件无法解析,已跳过`, "err");
870
+
871
+ const reset = $("#reset");
872
+ const resetFresh = reset.cloneNode(true);
873
+ reset.replaceWith(resetFresh);
874
+ resetFresh.addEventListener("click", resetEdits);
875
+ const save = $("#save");
876
+ // Bind to the existing node: the page's own scripts hold a reference to it and drive
877
+ // its disabled state, so replacing it would leave the visible button stuck disabled.
878
+ save.addEventListener("click", () => openDiff().catch(reportFailure));
879
+ // The provider page ships its own 保存配置 button that only touches memory; its
880
+ // listeners are replaced, and nothing else reads that node.
881
+ const providerSave = $("#pv-save");
882
+ if (providerSave) {
883
+ const providerFresh = providerSave.cloneNode(true);
884
+ providerSave.replaceWith(providerFresh);
885
+ providerFresh.addEventListener("click", () => openDiff().catch(reportFailure));
886
+ }
887
+ // Dirty state comes from the real diff, not from the page's own bookkeeping.
888
+ for (const type of ["input", "change", "click"])
889
+ document.addEventListener(type, () => queueMicrotask(syncDirty), true);
890
+ syncVisuals();
891
+ syncDirty();
892
+ $("#diffCancel").onclick = dismissPreview;
893
+ $("#diffOk").onclick = () => submit().catch(reportFailure);
894
+ $("#diffmask").addEventListener("click", (event) => {
895
+ if (event.target === $("#diffmask")) dismissPreview();
896
+ });
897
+ document.addEventListener("keydown", (event) => {
898
+ if (event.key === "Escape" && (!$("#diffmask").hidden || planning)) dismissPreview();
899
+ });
900
+ }
901
+
902
+ let pending = null;
903
+ let planning = null;
904
+ let saving = false;
905
+
906
+ function dismissPreview() {
907
+ pending = null;
908
+ planning = null;
909
+ $("#diffmask").hidden = true;
910
+ }
911
+
912
+ function resetEdits() {
913
+ dismissPreview();
914
+ fill(state.baseline);
915
+ showSources();
916
+ syncDirty();
917
+ feedback("已还原");
918
+ }
919
+
920
+ function reportFailure(error) {
921
+ feedback("保存未完成:" + error.message + ";编辑仍留在页面上。", "err");
922
+ }
923
+
924
+ async function openDiff() {
925
+ if (saving) return;
926
+ const overrides = Object.values(state.files ?? {}).filter(file => file.projectOverride);
927
+ if (overrides.length && !window.confirm(overrides.map(file => file.warning).join("\n") + "\n仍要编辑用户共享默认值吗?")) return;
928
+ dismissPreview();
929
+ const draft = { values: structuredClone(collect()), version: state.version, expectations: state.expectations };
930
+ if (!Object.keys(draft.values).length) return;
931
+ planning = draft;
932
+ try {
933
+ const result = await plan(draft.values, draft.version);
934
+ if (planning !== draft) return;
935
+ showDiff(result.changes ?? [], result.problems ?? [], result.skipped ?? []);
936
+ if (state.mode === "server" && !result.preview) $("#diffOk").disabled = true;
937
+ pending = { ...draft, preview: result.preview };
938
+ $("#diffmask").hidden = false;
939
+ $(".diff").focus();
940
+ } catch (error) {
941
+ if (planning === draft) throw error;
942
+ } finally {
943
+ if (planning === draft) planning = null;
944
+ }
945
+ }
946
+ async function submit() {
947
+ if (!pending || saving || $("#diffOk").disabled) return;
948
+ const { values, version, preview, expectations } = pending;
949
+ dismissPreview();
950
+ if (!sameDraft(values, collect())) throw new Error("编辑在预览后变化,请重新预览");
951
+ if (state.mode !== "server") {
952
+ download("emma-config-patch.json", { version: 2, kind: "vibe-emma-config-patch", createdAt: new Date().toISOString(), values, expectations });
953
+ feedback('已导出补丁 · 回到终端运行 /config apply "<下载文件的完整路径>" --dry-run,确认后去掉 --dry-run 再执行');
954
+ return;
955
+ }
956
+ saving = true;
957
+ const surface = $(".app");
958
+ surface.inert = true;
959
+ try {
960
+ const result = await call("/api/save", { method: "POST", body: JSON.stringify({ version, preview }) });
961
+ const entries = result.results ?? [];
962
+ if (result.failure) {
963
+ const details = entries.filter(entry => entry.status !== "blocked").map(entry => `${entry.path} (${entry.status})`).join(";");
964
+ const recovery = result.failure.stamp ? `;备份批次:${result.failure.stamp}` : "";
965
+ throw new Error(`${result.failure.message}${details ? `;${details}` : ""}${recovery}`);
966
+ }
967
+ if (!entries.length || entries.some(entry => entry.status !== "written")) throw new Error("配置已变化,未写入任何文件;请核对本页编辑后重新载入");
968
+ const onlyTheme = Object.keys(values).length === 1 && Object.hasOwn(values, "piTheme");
969
+ const reload = entries.some((entry) => entry.reload) && !onlyTheme;
970
+ feedback(`已保存${reload ? " · 部分项需重新加载 Pi" : ""}`);
971
+ let fresh;
972
+ try { fresh = await call("/api/state"); }
973
+ catch (error) { feedback(`已保存,但无法重新载入配置:${error.message};下次编辑前请刷新页面。`, "err"); return; }
974
+ state.version = fresh.version;
975
+ state.expectations = fresh.expectations ?? {};
976
+ state.defaults = fresh.defaults ?? {};
977
+ state.fieldMeta = fresh.fieldMeta ?? {};
978
+ state.values = fresh.values;
979
+ state.present = fresh.present;
980
+ state.credentials = fresh.credentials ?? [];
981
+ state.files = fresh.files ?? {};
982
+ state.mcpDetail = fresh.mcpDetail ?? {};
983
+ fill();
984
+ showSources();
985
+ state.baseline = snapshot();
986
+ syncDirty();
987
+ } finally {
988
+ surface.inert = false;
989
+ saving = false;
990
+ }
991
+ }
992
+
993
+ export const sameDraft = (previewed, current) => JSON.stringify(previewed) === JSON.stringify(current);
994
+
995
+ // A small hook for automated checks: helpers can be imported without a DOM.
996
+ if (typeof document !== 'undefined') boot().catch(error => { feedback('配置载入失败:' + error.message,'err'); $('#save').disabled=true; });
997
+ export { BINDINGS, enumValue, API_BY_PAGE, API_FOR_PAGE, fieldGroup };