@magic6/dsh-web-fallback-chain 0.0.0-stage → 0.2.3

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.
package/src/client.js ADDED
@@ -0,0 +1,1655 @@
1
+ /**
2
+ * `dsh-web-fallback-chain` — Client half: the one settings page.
3
+ *
4
+ * This page is the reason four packages became one. Four packages meant four
5
+ * pages, each showing a third of the knobs, and a reader who had to know which
6
+ * page owned which switch. Everything a deployment can change is here.
7
+ *
8
+ * Everything visible is dsh's own client UI: `SettingsForm` for the chrome and
9
+ * its save/discard states, `SettingsValueField` for text inputs, `Switch` for the
10
+ * toggles. This file contains no stylesheet and no hand-made control — it only
11
+ * says which fields exist and how a draft becomes a value, so the page cannot
12
+ * drift away from the product's look.
13
+ *
14
+ * Every field below maps to a **real config key**. A synthetic field name would
15
+ * be written into the profile patch as a key the host schema does not know.
16
+ *
17
+ * @module dsh-web-fallback-chain/client
18
+ */
19
+
20
+ window.__ModuleLoader__.load({
21
+ id: 'dsh-web-fallback-chain',
22
+ factory: (require) => {
23
+ var module = { exports: {} };
24
+ var exports = module.exports;
25
+
26
+ const React = require('react');
27
+ const primitives = require('@deepseek-ai/dsh-client-ui-primitives');
28
+
29
+ // Styles adapted from dsh-client-ui-settings-web-search's card module: a
30
+ // toggle row is a two-column flex row, a hint is 12px tertiary text, and a
31
+ // group is a 6px-gap grid. Without these the fields read as one paragraph.
32
+ // Layout only. Every value here exists because the measured box model showed it
33
+ // missing: `SettingsForm` gives its children NO spacing (all margins came back
34
+ // 0), so without this the ladder rows touch each other and the section headings
35
+ // sit flush against the control above them.
36
+ //
37
+ // Rhythm: 24px between sections, 16px between fields, 8px between ladder rows.
38
+ const CSS = [
39
+ // ── Root: owns the column width and the outer padding ──────────────────
40
+ //
41
+ // The host draws this card into a 960px flex section with `padding: 0`, so
42
+ // without this the copy runs edge to edge against the panel border and the
43
+ // right half of the row is empty. 640px is the reading width the product's own
44
+ // settings pages use.
45
+ '.wfb-root{display:block;max-width:640px;padding:4px 0 8px}',
46
+ // ── Sections ──────────────────────────────────────────────────────────
47
+ '.wfb-sectionTitle{font-size:11px;font-weight:600;letter-spacing:.08em;text-transform:uppercase;color:var(--dsw-alias-label-tertiary);margin:28px 0 12px;padding-top:16px;border-top:.5px solid var(--dsw-alias-border-l2);display:flex;align-items:center;gap:8px}',
48
+ // A short rule before the label turns the heading into a section marker without
49
+ // needing a heavier type treatment.
50
+ '.wfb-sectionTitle:before{content:"";width:10px;height:1.5px;background:var(--dsw-alias-label-tertiary);flex:none;border-radius:1px}',
51
+ '.wfb-sectionTitle:first-child{margin-top:0;padding-top:0;border-top:0}',
52
+
53
+ // ── One labelled control ──────────────────────────────────────────────
54
+ '.wfb-field{display:block;margin:0 0 16px}',
55
+ '.wfb-label{display:block;font-size:13px;font-weight:500;line-height:18px;color:var(--dsw-alias-label-primary);margin:0 0 6px}',
56
+ '.wfb-hint{display:block;color:var(--dsw-alias-label-tertiary);margin:6px 0 0;font-size:12px;line-height:17px}',
57
+ '.wfb-note{display:block;color:var(--dsw-alias-label-tertiary);margin:20px 0 0;padding-top:14px;border-top:.5px solid var(--dsw-alias-border-l2);font-size:12px;line-height:17px}',
58
+
59
+ // ── A switch row: label left, control right ───────────────────────────
60
+ '.wfb-toggle{display:block;margin:0 0 16px}',
61
+ '.wfb-toggleRow{display:flex;justify-content:space-between;align-items:center;gap:16px;font-size:13px;font-weight:500;line-height:18px;color:var(--dsw-alias-label-primary)}',
62
+
63
+ // ── The ladder ────────────────────────────────────────────────────────
64
+ '.wfb-legs{list-style:none;margin:0;padding:0;display:block}',
65
+ '.wfb-leg{display:flex;align-items:center;gap:10px;padding:7px 8px 7px 0;border-radius:var(--dsw-radius-sm);min-height:34px}',
66
+ '.wfb-leg+.wfb-leg{border-top:.5px solid var(--dsw-alias-border-l2)}',
67
+ '.wfb-leg:hover{background:var(--dsw-alias-interactive-bg-hover)}',
68
+ '.wfb-legNum{flex:none;width:18px;height:18px;border-radius:50%;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:1;display:inline-flex;align-items:center;justify-content:center}',
69
+ '.wfb-legBody{display:flex;flex-direction:row;align-items:baseline;gap:10px;min-width:0;flex:1}',
70
+ '.wfb-legId{font-family:var(--ds-font-family-code);font-size:12px;line-height:17px;color:var(--dsw-alias-label-primary);white-space:nowrap;flex:none}',
71
+ '.wfb-legId:after{content:"";display:inline-block;width:1px;height:11px;background:var(--dsw-alias-border-l3);margin-left:10px;vertical-align:-1px}',
72
+ '.wfb-legNote{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:17px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
73
+ '.wfb-legSkipped{opacity:.45}',
74
+ '.wfb-legSkipped .wfb-legNote{font-style:italic}',
75
+
76
+ // ── Reorder arrows: revealed on hover so the list stays calm ──────────
77
+ '.wfb-arrows{display:inline-flex;gap:2px;flex:none;opacity:0;transition:opacity .12s var(--ds-ease-in-out)}',
78
+ '.wfb-leg:hover .wfb-arrows,.wfb-leg:focus-within .wfb-arrows{opacity:1}',
79
+ '.wfb-arrow{width:24px;height:24px;padding:0;display:inline-flex;align-items:center;justify-content:center;border-radius:var(--dsw-radius-sm);color:var(--dsw-alias-label-tertiary)}',
80
+ '.wfb-arrow:hover:not(:disabled){background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-primary)}',
81
+ '.wfb-arrow:disabled{opacity:.25;cursor:default}',
82
+
83
+ // ── Inline text action ────────────────────────────────────────────────
84
+ '.wfb-link{color:var(--dsw-alias-state-business-primary);font:inherit;cursor:pointer;background:0 0;border:0;padding:0;margin:10px 0 0;font-size:12px;display:inline-block}',
85
+ '.wfb-link:hover{text-decoration:underline}',
86
+ // ── The degraded panel, shown when the real form cannot render ─────────
87
+ // ── Hidden but present ─────────────────────────────────────────────────
88
+ //
89
+ // `display:none` rather than not rendering. Removing the node changes the number
90
+ // of hooks in this component, which React rejects with #300/#311 — the failure
91
+ // that made this page vanish when a tagged domain was picked.
92
+ '.wfb-hidden{display:none!important}',
93
+
94
+ // ── The mount list: one leg per line ───────────────────────────────────
95
+ //
96
+ // Rendered inline, five checkboxes with capability suffixes ran together
97
+ // ("deepseek-search-rich · searchdeepseek-fetch-rich · fetch") because each is an
98
+ // inline <label>. A grid puts one per row and keeps the ids aligned.
99
+ '.wfb-mount{display:grid;gap:7px;margin-top:2px}',
100
+ '.wfb-mount label{display:flex;align-items:center;gap:7px;font-size:13px;line-height:18px;cursor:pointer}',
101
+ '.wfb-mount label:has(input:disabled){cursor:default;opacity:.5}',
102
+
103
+ // ── Billing rows ───────────────────────────────────────────────────────
104
+ '.wfb-costRow{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:6px 0;border-bottom:.5px solid var(--dsw-alias-border-l2)}',
105
+ '.wfb-costRow:last-child{border-bottom:0}',
106
+ '.wfb-costId{font-family:var(--ds-font-family-code);font-size:12px;line-height:17px;color:var(--dsw-alias-label-primary)}',
107
+
108
+ '.wfb-fallback{display:block;padding:14px 16px;border:.5px solid var(--dsw-alias-state-error-primary);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-module-platform)}',
109
+ '.wfb-error{color:var(--dsw-alias-state-error-primary);margin:8px 0 0;font-family:var(--ds-font-family-code);font-size:12px;line-height:17px;word-break:break-word}',
110
+ ].join('');
111
+ const PLUGIN_ID = 'dsh-web-fallback-chain';
112
+ if (typeof document !== 'undefined' && document.querySelector(`style[data-plugin-css="${PLUGIN_ID}"]`) === null) {
113
+ const tag = document.createElement('style');
114
+ tag.dataset.plugin = PLUGIN_ID;
115
+ tag.dataset.pluginCss = PLUGIN_ID;
116
+ tag.textContent = CSS;
117
+ document.head.appendChild(tag);
118
+ }
119
+
120
+ /** Dictionary namespace owned by this client half. */
121
+ const NS = 'settings.webFallback';
122
+
123
+ /** Loader row id of the host half; also its settings namespace. */
124
+ const ENTRY_ID = 'web-fallback';
125
+
126
+ /**
127
+ * The npm package name, which is the identity 已安装插件 keys its config page on.
128
+ *
129
+ * Not the same string as `ENTRY_ID`: the settings namespace is the profile
130
+ * entry's local id (`web-fallback`), while this slot is addressed by the package
131
+ * name the plugin manager reports (`dsh-web-fallback-chain`).
132
+ */
133
+ const PACKAGE_NAME = 'dsh-web-fallback-chain';
134
+
135
+ /**
136
+ * The four read depths, duplicated here on purpose.
137
+ *
138
+ * The browser bundle cannot import the host half's `policy/modes.js` (different
139
+ * side of the seam, and a client bundle that pulls in server code does not load),
140
+ * so the list is repeated. `client.test.js` asserts it still matches the host's
141
+ * `MODES`, so the two cannot drift silently.
142
+ */
143
+ const MODES = ['brief', 'deep', 'list', 'page'];
144
+
145
+ /** The depth used when nothing else decides; mirrors the host default. */
146
+ const DEFAULT_MODE = 'brief';
147
+
148
+ /**
149
+ * The measured default order, duplicated for display.
150
+ *
151
+ * The browser bundle cannot import `policy/modes.js` (server side of the seam), so
152
+ * this table is a copy. `client.test.js` asserts it still matches the host's
153
+ * `DEFAULT_MODE_ORDERS`, so a policy change that is not mirrored here fails the
154
+ * suite instead of showing the user a chain the plugin will not run.
155
+ */
156
+ const LADDER = {
157
+ fetch: ['anysearch', 'tavily', 'deepseek-fetch-rich', 'http'],
158
+ search: ['deepseek-search-rich', 'anysearch', 'tavily'],
159
+ };
160
+
161
+ /** Which legs cost money, so the preview can mark them and freeOnly can hide them. */
162
+ const PAID = new Set(['deepseek-search-rich', 'deepseek-search-api', 'deepseek-fetch-rich', 'deepseek-fetch-api']);
163
+
164
+ /** One-line description per leg, for the chain preview. */
165
+ const LEGS = {
166
+ 'http': { zh: '直接抓 HTML', en: 'plain HTML fetch' },
167
+ 'anysearch': { zh: 'AnySearch 提取', en: 'AnySearch extract' },
168
+ 'tavily': { zh: 'Tavily 提取(能取 PDF)', en: 'Tavily extract (handles PDFs)' },
169
+ 'deepseek-search-rich': { zh: 'DeepSeek 搜索(收费,给成段答案)', en: 'DeepSeek search (paid, returns prose)' },
170
+ 'deepseek-search-api': { zh: 'DeepSeek 搜索 API(收费)', en: 'DeepSeek Search API (paid)' },
171
+ 'deepseek-fetch-rich': { zh: 'DeepSeek 抓取(收费)', en: 'DeepSeek fetch (paid)' },
172
+ 'deepseek-fetch-api': { zh: 'DeepSeek 抓取 API(收费)', en: 'DeepSeek Fetch API (paid)' },
173
+ };
174
+
175
+ /** Ids this plugin registers, and the values the seam must pin. */
176
+ const CHAIN_FETCH_ID = 'fetch-chain';
177
+ const CHAIN_SEARCH_ID = 'search-chain';
178
+
179
+ /** Entry id of the seam whose selection decides whether the chains run. */
180
+ const WEB_ENTRY_ID = 'web';
181
+
182
+ /** English copy. */
183
+ const en = {
184
+ title: 'Web fallback chain',
185
+ description: 'A ranked fallback chain for web search and web fetch, with a free-only switch.',
186
+
187
+ freeOnly: 'Use free tools only',
188
+ freeOnlyHint: 'Skips every provider that costs money. On by default: the billed fetch leg was measured answering "success" with only a site footer on several sites.',
189
+
190
+ depth: 'How deep to read',
191
+ mode_brief: 'brief · one fact',
192
+ mode_deep: 'deep · whole document',
193
+ mode_list: 'list · listing page',
194
+ mode_page: 'page · whole page',
195
+ depthHint: 'Which mode to use when intent is unclear. brief is 300 characters per result, deep 1200, list expects grouped items, page is untruncated.',
196
+
197
+ fetchOrder: 'Fetch priority',
198
+ fetchOrderHint: 'Comma separated, left first. Blank uses the shipped order.',
199
+ searchOrder: 'Search priority',
200
+ searchOrderHint: 'Comma separated, left first. Search and fetch rank independently. Blank uses the shipped order.',
201
+ annotateFallback: 'Annotate fallbacks',
202
+ annotateFallbackHint: 'When a later leg served, add one line saying which leg answered and why the earlier ones did not.',
203
+ keyDeepseek: 'DeepSeek API key',
204
+ keyDeepseekHint: 'Used by the billed legs deepseek-search-rich / deepseek-fetch-rich. Leave empty and those legs stay unavailable.',
205
+ keyAnysearch: 'AnySearch API key',
206
+ keyAnysearchHint: 'Used by the free anysearch leg, for both search and fetch.',
207
+ keyTavily: 'Tavily API key',
208
+ keyTavilyHint: 'Used by the free tavily leg, the only one here that extracts PDFs.',
209
+ keySet: 'Set',
210
+ keyUnset: 'Not set',
211
+ fetchChainTitle: 'Fetch order (in effect)',
212
+ fetchChainHint: 'Tried top to bottom; the first success wins. Ranked from measurement, so it needs no manual configuration.',
213
+ searchChainTitle: 'Search order (in effect)',
214
+ searchChainHint: 'Tried top to bottom; the first one with results wins. Use the arrows to change the order — the ranking above is the ranking used, and an edit here overrides the measured default for every mode.',
215
+ moveUp: 'Move up',
216
+ moveDown: 'Move down',
217
+ resetToMeasured: 'Restore measured order',
218
+ fetchChainCustom: 'This is your own ranking. Billed legs are hidden while free-only is on.',
219
+ searchChainCustom: 'This is your own ranking. Billed legs are hidden while free-only is on.',
220
+ saveNote: 'Saving rewrites this plugin\u2019s config block from what the page holds. Comments placed inside that block do not survive a save \u2014 keep notes here or in the README, not in the YAML.',
221
+ costTitle: 'Billing per leg',
222
+ costHint: 'Whether a leg bills per request. The free-only switch skips exactly the legs marked paid, so marking one free here stops it from being skipped. This does not reorder anything.',
223
+ cost: 'billing',
224
+ costFree: 'free',
225
+ costPaid: 'paid',
226
+ invalidNumber: 'Enter a number between 0 and 10.',
227
+ groupAdvanced: 'Advanced',
228
+ minBody200: '200 chars',
229
+ minBody600: '600 chars',
230
+ minBody2000: '2k chars',
231
+ minBodyOff: 'status only',
232
+ minBodyCharsLabel: 'Minimum body length',
233
+ minBodyCharsHint: 'Off by default: HTTP status alone decides, and a short answer is returned as fetched. Turning it on means "my sites are all long, so a stub means extraction failed" \u2014 a re-fetch trigger, not a quality rule. Length cannot tell a site footer (142\u2013332 chars) from a legitimately short page (example.com has 171), which is why this is off.',
234
+ timeoutMsLabel: 'Request timeout (ms)',
235
+ timeoutMsHint: 'How long one leg may take before the chain moves on. Measured default: 30000.',
236
+ enableLabel: 'Mounted legs',
237
+ enableHint: 'Which legs this plugin registers at all. All ticked (the default) means every leg is mounted. Unticking a leg removes it from both chains \u2014 useful when you never want a provider called, e.g. to keep a billed leg out of reach even with free-only switched off. A mounted leg with no key still registers and reports itself unavailable, so the chain names it instead of looking unconfigured.',
238
+ tagGeneral: 'general web',
239
+ anysearchParamsRequired: 'This domain requires: {keys}. The API rejects the request without them.',
240
+ anysearchParamsNotNeeded: 'The selected domain needs no parameters, so there is nothing to fill in.',
241
+ anysearchTagLabel: 'AnySearch vertical',
242
+ anysearchTagHint: 'A vertical domain such as code.doc or academic.paper; empty means general web search. A tag changes what the query MEANS, not just its ranking — the same query returns different sources.',
243
+ anysearchParamsLabel: 'AnySearch vertical params',
244
+ anysearchParamsHint: 'Required parameters for the chosen vertical, as key=value,key2=value2.',
245
+ deepseekNeedContentLabel: 'DeepSeek search: full text',
246
+ deepseekNeedContentHint: 'Ask DeepSeek search for full page text. Same price per call, but the response grows from about 5 KB to 45 KB.',
247
+ groupBasic: 'Basics',
248
+ groupChain: 'Fallback order',
249
+ groupKeys: 'API keys',
250
+ skippedByFreeOnly: 'skipped (billed)',
251
+
252
+ overridden: 'Overridden',
253
+ reset: 'Reset to default',
254
+ orderInvalid: 'Write at least one leg name, and never the chain itself.',
255
+
256
+ unavailable: 'This plugin is not loaded, so it cannot be configured right now.',
257
+ readOnly: 'This deployment stores settings read-only.',
258
+ saveFailed: 'The deployment did not accept these values; they were left for you to correct.',
259
+ save: 'Save',
260
+ saving: 'Saving…',
261
+ };
262
+
263
+ /** Simplified Chinese copy. */
264
+ const zh = {
265
+ title: '网页回退链',
266
+ description: '为网页搜索与网页抓取提供按实测排序的回退链,带一个「仅免费」开关。',
267
+
268
+ freeOnly: '仅使用免费工具',
269
+ freeOnlyHint: '打开后会跳过所有要花钱的档。默认打开:实测收费抓取档在多个站点上返回「成功」但正文只有站点页脚,等于没取到东西。',
270
+
271
+ depth: '需要读多深',
272
+ mode_brief: 'brief · 一句话事实',
273
+ mode_deep: 'deep · 整篇文档',
274
+ mode_list: 'list · 列表页',
275
+ mode_page: 'page · 整页',
276
+ depthHint: '判断不出意图时用哪一档。brief 每条 300 字,deep 1200 字,list 要成组条目,page 整页不截断。',
277
+
278
+ fetchOrder: '抓取优先顺序',
279
+ fetchOrderHint: '逗号分隔,左边先试。留空 = 使用内置顺序。',
280
+ searchOrder: '搜索优先顺序',
281
+ searchOrderHint: '逗号分隔,左边先试。搜索与抓取各自独立排序。留空 = 使用内置顺序。',
282
+ annotateFallback: '标注降级来源',
283
+ annotateFallbackHint: '换了备选档时,在结果里附一行说明是哪一档给的、前面几档为什么没成。',
284
+ keyDeepseek: 'DeepSeek API key',
285
+ keyDeepseekHint: '收费档 deepseek-search-rich / deepseek-fetch-rich 用这个。留空则这两档不可用。',
286
+ keyAnysearch: 'AnySearch API key',
287
+ keyAnysearchHint: '免费档 anysearch 用这个,搜索与抓取都靠它。',
288
+ keyTavily: 'Tavily API key',
289
+ keyTavilyHint: '免费档 tavily 用这个,唯一能取 PDF 的档。',
290
+ keySet: '已设置',
291
+ keyUnset: '未设置',
292
+ fetchChainTitle: '抓取顺序(当前生效)',
293
+ fetchChainHint: '从上往下试,第一个成功的就用。链由实测结果排定,不需要手动配置。',
294
+ searchChainTitle: '搜索顺序(当前生效)',
295
+ searchChainHint: '从上往下试,第一个有结果的就用。要调顺序用右边的箭头——这里显示的顺序就是实际生效的顺序,改过之后会覆盖所有模式的实测默认值。',
296
+ moveUp: '上移',
297
+ moveDown: '下移',
298
+ resetToMeasured: '恢复实测顺序',
299
+ fetchChainCustom: '这是你自己调整过的顺序。收费档在「仅使用免费工具」开启时会被隐藏。',
300
+ searchChainCustom: '这是你自己调整过的顺序。收费档在「仅使用免费工具」开启时会被隐藏。',
301
+ saveNote: '保存会用页面上的值重写本插件的配置块。写在这个块里的注释不会留到保存之后——要记笔记请写在这里或 README 里,不要写在 YAML 里。',
302
+ costTitle: '各档是否计费',
303
+ costHint: '这一档是否按次计费。「仅使用免费工具」跳过的正是标记为 paid 的档,所以把某档标成 free 后它就不会再被跳过。这里不改变排序。',
304
+ cost: '计费',
305
+ costFree: '免费',
306
+ costPaid: '收费',
307
+ invalidNumber: '请输入 0 到 10 之间的数字。',
308
+ groupAdvanced: '高级',
309
+ minBody200: '200 字',
310
+ minBody600: '600 字',
311
+ minBody2000: '2 千字',
312
+ minBodyOff: '只看状态',
313
+ minBodyCharsLabel: '正文最少字数',
314
+ minBodyCharsHint: '默认关闭:只看 HTTP 状态,拿回来多短都算成功。开启它的含义是「我的站点都很长,出现短文说明提取失败」——这是重试触发器,不是质量判据。长度分不清页脚(142–332 字)和合法的短页面(example.com 正文只有 171 字),所以才默认关掉。',
315
+ timeoutMsLabel: '单次超时(毫秒)',
316
+ timeoutMsHint: '一档最多等多久,超时后换下一档。实测默认 30000。',
317
+ enableLabel: '挂载哪些档',
318
+ enableHint: '这个插件到底注册哪些档。全部勾选(默认)就是全都挂载;取消某档会把它从搜索和抓取两条链里都移除——适用于你完全不希望某个来源被调用的情况,例如即使关掉「仅免费」也不想碰收费档。已挂载但没有 key 的档仍会注册并自报不可用,这样链里会点名它,而不是看起来没配置。',
319
+ tagGeneral: '通用搜索',
320
+ anysearchParamsRequired: '该垂直域必须提供:{keys}。缺少时 API 会直接拒绝请求。',
321
+ anysearchParamsNotNeeded: '当前选择的垂直域不需要参数,不用填任何东西。',
322
+ anysearchTagLabel: 'AnySearch 垂直域',
323
+ anysearchTagHint: '如 code.doc、academic.paper;留空为通用搜索。垂直域改变的是查询的语义,不只是排序——同一个 query 会命中不同来源。',
324
+ anysearchParamsLabel: 'AnySearch 垂直参数',
325
+ anysearchParamsHint: '所选垂直域的必填参数,格式 key=value,key2=value2。',
326
+ deepseekNeedContentLabel: 'DeepSeek 搜索返回全文',
327
+ deepseekNeedContentHint: '让 DeepSeek 搜索返回整页正文。按次计费不变,但响应会从约 5KB 涨到 45KB。',
328
+ groupBasic: '基本',
329
+ groupChain: '回退顺序',
330
+ groupKeys: 'API 密钥',
331
+ skippedByFreeOnly: '本次跳过(收费)',
332
+
333
+ overridden: '已覆盖',
334
+ reset: '恢复默认',
335
+ orderInvalid: '至少写一个档名,且不能写链自己的名字。',
336
+
337
+ unavailable: '该插件当前未加载,暂时无法配置。',
338
+ readOnly: '本部署的设置为只读。',
339
+ saveFailed: '本部署没有接受这些值,已保留供你修改。',
340
+ save: '保存',
341
+ saving: '保存中…',
342
+ };
343
+
344
+ /**
345
+ * The per-mode order overrides, as config-entry drafts.
346
+ *
347
+ * Each entry is one `modeOrders.<capability>.<mode>` override. The page no
348
+ * longer renders these as fields — a user who needs one edits the profile patch,
349
+ * which is the right place for a set-once value. They stay in the form model so
350
+ * an override written by hand is still read, staged and saved back intact rather
351
+ * than being dropped on the next save.
352
+ */
353
+ const MODE_FIELDS = [
354
+ { capability: 'fetch', mode: 'brief', key: 'modeFetchBrief' },
355
+ { capability: 'fetch', mode: 'deep', key: 'modeFetchDeep' },
356
+ { capability: 'fetch', mode: 'list', key: 'modeFetchList' },
357
+ { capability: 'fetch', mode: 'page', key: 'modeFetchPage' },
358
+ { capability: 'search', mode: 'brief', key: 'modeSearchBrief' },
359
+ { capability: 'search', mode: 'deep', key: 'modeSearchDeep' },
360
+ { capability: 'search', mode: 'list', key: 'modeSearchList' },
361
+ { capability: 'search', mode: 'page', key: 'modeSearchPage' },
362
+ ];
363
+
364
+ /**
365
+ * Assemble the `modeOrders` config value from the per-mode drafts.
366
+ *
367
+ * A field left empty is omitted rather than written as `[]`, so clearing a
368
+ * field restores the measured default for that mode instead of pinning an
369
+ * empty order that would fail at resolve time.
370
+ *
371
+ * @param drafts - the staged text of each mode field, keyed by `MODE_FIELDS.key`.
372
+ * @returns the `modeOrders` object the host accepts.
373
+ */
374
+ function modeOrdersFrom(drafts) {
375
+ const out = {};
376
+ for (const { capability, mode, key } of MODE_FIELDS) {
377
+ const ids = parseIds(drafts?.[key] ?? '');
378
+ if (ids.length === 0) continue;
379
+ if (out[capability] === undefined) out[capability] = {};
380
+ out[capability][mode] = ids;
381
+ }
382
+ return out;
383
+ }
384
+
385
+ /** Form chrome labels the shared form component requires. */
386
+ function formLabels(t) {
387
+ return {
388
+ unavailable: t('unavailable'),
389
+ readOnly: t('readOnly'),
390
+ saveFailed: t('saveFailed'),
391
+ save: t('save'),
392
+ saving: t('saving'),
393
+ };
394
+ }
395
+
396
+ /** Split an order draft into provider ids. */
397
+ function parseIds(text) {
398
+ return String(text ?? '')
399
+ .split(/[,\s]+/)
400
+ .map((part) => part.trim())
401
+ .filter((part) => part.length > 0);
402
+ }
403
+
404
+ /** Render provider ids the way the reader types them. */
405
+ function formatIds(ids) {
406
+ return Array.isArray(ids) ? ids.join(', ') : '';
407
+ }
408
+
409
+ /** Why an order draft is unacceptable, or `false` when it is fine. */
410
+ function orderError(text) {
411
+ const raw = String(text ?? '').trim();
412
+ if (raw === '') return false;
413
+ const ids = parseIds(raw);
414
+ return ids.length === 0 || ids.includes(CHAIN_FETCH_ID) || ids.includes(CHAIN_SEARCH_ID);
415
+ }
416
+
417
+ /**
418
+ * True when the depth draft is not one of the four known modes.
419
+ *
420
+ * Checked here rather than left to the host so a typo shows up under the field
421
+ * instead of as a save failure.
422
+ */
423
+ function modeError(text) {
424
+ const raw = String(text ?? '').trim();
425
+ if (raw === '') return false;
426
+ return !['brief', 'deep', 'list', 'page'].includes(raw);
427
+ }
428
+
429
+ /** Why a JSON-object draft is unacceptable, or `false` when it is fine. */
430
+ function jsonError(text) {
431
+ const raw = String(text ?? '').trim();
432
+ if (raw === '') return false;
433
+ try {
434
+ const value = JSON.parse(raw);
435
+ return value === null || typeof value !== 'object' || Array.isArray(value);
436
+ } catch {
437
+ return true;
438
+ }
439
+ }
440
+
441
+ /** Why a positive-integer draft is unacceptable, or `false` when it is fine. */
442
+ function numberError(text) {
443
+ const raw = String(text ?? '').trim();
444
+ if (raw === '') return false;
445
+ const n = Number(raw);
446
+ return !Number.isInteger(n) || n <= 0;
447
+ }
448
+
449
+ /** A text field that stages an array of provider ids. */
450
+ function orderField(key) {
451
+ return {
452
+ ...primitives.settingsTextField(key),
453
+ // BOTH halves must be replaced: `settingsTextField` is a *string* field and
454
+ // its `format` is `(v) => typeof v === 'string' ? v : ''`, so an array
455
+ // formats to the empty string. Without this the page rendered an empty box
456
+ // for a stored order and then SAVED THE EMPTY VALUE back — the setting looked
457
+ // applied and silently cleared itself.
458
+ format: (value) => (Array.isArray(value) ? formatIds(value) : typeof value === 'string' ? value : ''),
459
+ parse: (text) => (orderError(text) ? undefined : { kind: 'set', value: parseIds(text) }),
460
+ };
461
+ }
462
+
463
+ /** A text field that stages a positive integer. */
464
+ function numberField(key) {
465
+ return {
466
+ ...primitives.settingsTextField(key),
467
+ // ...and a number is not a string either.
468
+ format: (value) => (typeof value === 'number' && Number.isFinite(value) ? String(value) : typeof value === 'string' ? value : ''),
469
+ parse: (text) => {
470
+ const raw = String(text ?? '').trim();
471
+ if (raw === '') return { kind: 'unset' };
472
+ return numberError(raw) ? undefined : { kind: 'set', value: Number(raw) };
473
+ },
474
+ };
475
+ }
476
+
477
+ /** A text field that stages a JSON object. */
478
+ function jsonField(key) {
479
+ return {
480
+ ...primitives.settingsTextField(key),
481
+ // Same trap as `orderField`: an object is not a string, so the stock
482
+ // formatter yields '' and a save would overwrite the stored object with {}.
483
+ format: (value) => {
484
+ if (typeof value === 'string') return value
485
+ if (value === null || value === undefined) return ''
486
+ try {
487
+ return JSON.stringify(value)
488
+ } catch {
489
+ return ''
490
+ }
491
+ },
492
+ parse: (text) => {
493
+ const raw = String(text ?? '').trim();
494
+ if (raw === '') return { kind: 'set', value: {} };
495
+ if (jsonError(raw)) return undefined;
496
+ return { kind: 'set', value: JSON.parse(raw) };
497
+ },
498
+ };
499
+ }
500
+
501
+ /** A text field that stages a plain string. */
502
+ function textField(key, fallback) {
503
+ return {
504
+ ...primitives.settingsTextField(key),
505
+ parse: (text) => ({ kind: 'set', value: String(text ?? '').trim() || fallback }),
506
+ };
507
+ }
508
+
509
+ /**
510
+ * A boolean field.
511
+ *
512
+ * A boolean has no dedicated field primitive, so it rides a text draft that
513
+ * the official `Switch` renders: the control and its states are the product's,
514
+ * only the staged value is ours.
515
+ */
516
+ function booleanField(key) {
517
+ return {
518
+ ...primitives.settingsTextField(key),
519
+ // BOTH directions must override the text spec.
520
+ //
521
+ // `settingsTextField` is a string field: its `format` is
522
+ // format: (value) => typeof value === 'string' ? value : ''
523
+ // so a stored boolean `true` formats to `''`. The old spec overrode only
524
+ // `parse`, leaving the read side returning an empty string — which is why
525
+ // `freeOnly: true` rendered as an OFF switch. Both halves are replaced here:
526
+ // `format` renders the boolean as 'true'/'false', `parse` reads it back.
527
+ // `typeof value === 'boolean'` is the normal case; the string forms are
528
+ // accepted because a config written through the patch file can hold `'true'`
529
+ // and the descriptor would then hand it back as a string.
530
+ format: (value) => {
531
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
532
+ const raw = String(value ?? '').trim().toLowerCase();
533
+ return raw === 'true' || raw === '1' || raw === 'on' ? 'true' : 'false';
534
+ },
535
+ parse: (text) => {
536
+ const raw = String(text ?? '').trim().toLowerCase();
537
+ return { kind: 'set', value: raw === 'true' || raw === '1' || raw === 'on' };
538
+ },
539
+ };
540
+ }
541
+
542
+ /** A switch row: the product's Switch plus a label and a hint. */
543
+ /**
544
+ * The effective depth, normalized to one of {@link MODES}.
545
+ *
546
+ * An empty draft means "no override", which behaves as `brief`, so the control
547
+ * must show `brief` selected rather than nothing.
548
+ *
549
+ * @param field - the staged `defaultMode` field.
550
+ * @returns one of the four mode names.
551
+ */
552
+ function modeOf(field) {
553
+ const text = String(field?.text ?? field?.value ?? '').trim();
554
+ return MODES.includes(text) ? text : DEFAULT_MODE;
555
+ }
556
+
557
+ /**
558
+ * Read a boolean out of a staged field.
559
+ *
560
+ * The form model exposes a field's staged value as `text`. How a boolean is
561
+ * rendered into that string is the form model's business, not ours, so relying
562
+ * on `text === 'true'` made the switch read as OFF for a config that was
563
+ * genuinely `true` — exactly the reported symptom. Accept the value the field
564
+ * also carries (`value`) and treat any non-"false" text as on, so a
565
+ * differently-stringified true cannot flip the switch off.
566
+ *
567
+ * @param field - one staged field from the card snapshot.
568
+ * @returns whether the switch should render as on.
569
+ */
570
+ function boolOf(field) {
571
+ if (field === undefined || field === null) return false;
572
+ if (typeof field.value === 'boolean') return field.value;
573
+ const text = String(field.text ?? '').trim().toLowerCase();
574
+ return text === 'true' || text === '1' || text === 'on' || text === 'yes';
575
+ }
576
+
577
+ /**
578
+ * Render one capability's ladder with up/down reordering.
579
+ *
580
+ * ## Why arrows and not a text field
581
+ *
582
+ * The order IS this plugin's product, so it has to be adjustable — but a
583
+ * comma-separated box asks the user to retype an ordering the plugin already
584
+ * measured, and one typo silently reorders the chain. Two arrows per row make the
585
+ * operation the thing it actually is: move this leg one slot.
586
+ *
587
+ * ## What an edit writes
588
+ *
589
+ * Only the flat `order` / `searchOrder` list. That field is the documented
590
+ * "user's own ranking" and takes precedence over the shipped per-mode default, so
591
+ * one adjustment covers every mode at once — which is what someone dragging an
592
+ * arrow expects. Per-mode overrides stay in the config file for the rare case.
593
+ *
594
+ * @param capability - `fetch` or `search`.
595
+ * @param state - the card snapshot, for the freeOnly switch and current order.
596
+ * @param handlers - `{ edit, resetField, t, lang }`.
597
+ * @returns the ladder node.
598
+ */
599
+ function chainRow(capability, state, handlers) {
600
+ const { t, lang, edit, resetField } = handlers;
601
+ const freeOnly = boolOf(state.freeOnly);
602
+
603
+ // The user's own ranking when they have one, else the measured default. Billed
604
+ // legs are hidden — not reordered — under freeOnly, so flipping the switch back
605
+ // restores the same sequence.
606
+ const configuredField = capability === 'fetch' ? state.order : state.searchOrder;
607
+ const configured = parseIds(String(configuredField?.text ?? ''));
608
+ const base = configured.length > 0 ? configured : LADDER[capability];
609
+ // Every leg is shown, always. `freeOnly` does NOT reorder or hide: the host
610
+ // skips billed legs at call time while keeping the ranking, so the page must
611
+ // show the one ranking that is actually stored. Hiding them here made the list
612
+ // disagree with the config and made the switch look like it rewrote the order.
613
+ const legs = base;
614
+
615
+ const move = (from, to) => {
616
+ if (to < 0 || to >= legs.length) return;
617
+ const next = [...legs];
618
+ const [moved] = next.splice(from, 1);
619
+ next.splice(to, 0, moved);
620
+ // The whole ladder is visible, so the reordered list IS the new config value.
621
+ edit(capability === 'fetch' ? 'order' : 'searchOrder', next.join(','));
622
+ };
623
+
624
+ // `Button` is a `React.forwardRef` component, NOT a plain function. Calling it
625
+ // as `primitives.Button({...})` throws `TypeError: primitives.Button is not a
626
+ // function` and took the whole page down. Every other primitive here is a
627
+ // plain function, so this one alone must go through `createElement`.
628
+ //
629
+ // The icons ARE plain functions, so they stay on the call form.
630
+ const arrow = (index, direction) => {
631
+ const Icon = direction === 'up'
632
+ ? primitives.IconChevronUpOutlineRegular
633
+ : primitives.IconChevronDownOutlineRegular
634
+ return React.createElement(primitives.Button, {
635
+ variant: 'ghost',
636
+ className: 'wfb-arrow',
637
+ 'aria-label': t(direction === 'up' ? 'moveUp' : 'moveDown'),
638
+ disabled: direction === 'up' ? index === 0 : index === legs.length - 1,
639
+ onClick: () => move(index, direction === 'up' ? index - 1 : index + 1),
640
+ }, Icon({ size: 14 }))
641
+ }
642
+
643
+ const items = legs.map((id, index) => {
644
+ const billed = PAID.has(id);
645
+ const skipped = billed && freeOnly;
646
+ return React.createElement('li', {
647
+ key: id,
648
+ className: `wfb-leg${billed ? ' wfb-legPaid' : ''}${skipped ? ' wfb-legSkipped' : ''}`,
649
+ }, [
650
+ React.createElement('span', { key: 'n', className: 'wfb-legNum' }, String(index + 1)),
651
+ React.createElement('span', { key: 'body', className: 'wfb-legBody' }, [
652
+ React.createElement('span', { key: 'id', className: 'wfb-legId' }, id),
653
+ React.createElement('span', { key: 'note', className: 'wfb-legNote' }, skipped
654
+ ? `${LEGS[id]?.[lang] ?? ''} · ${t('skippedByFreeOnly')}`
655
+ : (LEGS[id]?.[lang] ?? '')),
656
+ ]),
657
+ React.createElement('span', { key: 'arrows', className: 'wfb-arrows' }, [arrow(index, 'up'), arrow(index, 'down')]),
658
+ ]);
659
+ });
660
+
661
+ const hasOverride = configured.length > 0;
662
+ return React.createElement('div', { key: `chain-${capability}`, className: 'wfb-field' }, [
663
+ React.createElement('span', { key: 'label', className: 'wfb-label' }, t(capability === 'fetch' ? 'fetchChainTitle' : 'searchChainTitle')),
664
+ React.createElement('ol', { key: 'list', className: 'wfb-legs' }, items),
665
+ React.createElement('p', { key: 'hint', className: 'wfb-hint' }, hasOverride
666
+ ? t(capability === 'fetch' ? 'fetchChainCustom' : 'searchChainCustom')
667
+ : t(capability === 'fetch' ? 'fetchChainHint' : 'searchChainHint')),
668
+ hasOverride
669
+ ? React.createElement('button', {
670
+ key: 'reset',
671
+ type: 'button',
672
+ className: 'wfb-link',
673
+ onClick: () => resetField(capability === 'fetch' ? 'order' : 'searchOrder'),
674
+ }, t('resetToMeasured'))
675
+ : null,
676
+ ]);
677
+ }
678
+
679
+ /**
680
+ * A quiet section heading inside the form.
681
+ *
682
+ * The page has three distinct jobs — behaviour switches, chain order, credentials —
683
+ * and without headings they read as one undifferentiated column of controls.
684
+ *
685
+ * @param key - React key.
686
+ * @param title - localized heading text.
687
+ * @returns the heading node.
688
+ */
689
+ /**
690
+ * The body-length floor, as named choices.
691
+ *
692
+ * Measured spread: a site footer is 142–332 characters, a real article 63k–100k.
693
+ * Because that cannot separate a footer from a legitimately short page, the shipped
694
+ * default is 0 (`status only`) and the other values are for deployments that know
695
+ * their sites are all long.
696
+ */
697
+ const MIN_BODY_CHOICES = (t) => [
698
+ { value: 0, label: t('minBodyOff') },
699
+ { value: 200, label: t('minBody200') },
700
+ { value: 600, label: t('minBody600') },
701
+ { value: 2000, label: t('minBody2000') },
702
+ ]
703
+
704
+ /** Per-leg timeout, as named choices. 30 s is the shipped default. */
705
+ const TIMEOUT_CHOICES = (t) => [
706
+ { value: 10000, label: '10s' },
707
+ { value: 30000, label: '30s' },
708
+ { value: 60000, label: '60s' },
709
+ ]
710
+
711
+ /**
712
+ * The built-in legs whose billing classification the user can override.
713
+ *
714
+ * `cost` is the one provider metadata field that changes behaviour the moment it is
715
+ * edited: it is exactly what `freeOnly` reads, and what `partitionByCost` partitions
716
+ * on. `quality` is deliberately NOT exposed — nothing at runtime reads it (it only
717
+ * documents how the shipped default order was derived), so an editable box for it
718
+ * would accept input and change nothing, which is worse than not offering it.
719
+ */
720
+ const COST_LEGS = [
721
+ { id: 'deepseek-search-rich', cost: 'paid' },
722
+ { id: 'anysearch', cost: 'free' },
723
+ { id: 'tavily', cost: 'free' },
724
+ { id: 'deepseek-fetch-rich', cost: 'paid' },
725
+ { id: 'http', cost: 'free' },
726
+ ]
727
+
728
+ /**
729
+ * One billing row per built-in leg.
730
+ *
731
+ * `providers` is a nested object, so it cannot ride a single text field without
732
+ * asking the user to write JSON by hand. Each row sets one value and the controller
733
+ * recomposes the object, preserving every other key on the entry.
734
+ *
735
+ * @param options - state, disabled, onEdit, onReset, t.
736
+ * @returns the rows.
737
+ */
738
+ function costRows(options) {
739
+ const { state, disabled, onEdit, t: tr } = options
740
+ const current = readProviders(state.providers)
741
+ return COST_LEGS.map(({ id, cost }) => React.createElement('div', { key: id, className: 'wfb-costRow' }, [
742
+ React.createElement('span', { key: 'id', className: 'wfb-costId' }, id),
743
+ primitives.SegmentedControl({
744
+ id: `plugin-config-web-fallback-cost-${id}`,
745
+ label: `${id} ${tr('cost')}`,
746
+ value: current[id]?.cost ?? cost,
747
+ disabled,
748
+ options: [
749
+ { value: 'free', label: tr('costFree') },
750
+ { value: 'paid', label: tr('costPaid') },
751
+ ],
752
+ onChange: (next) => onEdit(id, next),
753
+ }),
754
+ ]))
755
+ }
756
+
757
+ /**
758
+ * Read the stored `providers` object.
759
+ *
760
+ * Everything the entry carries is kept, not just `cost`, so an edit to one key
761
+ * cannot delete the others.
762
+ *
763
+ * @param field - the form-field snapshot for `providers`.
764
+ * @returns the parsed object, or `{}` when it is empty or malformed.
765
+ */
766
+ function readProviders(field) {
767
+ const raw = field?.text
768
+ if (typeof raw !== 'string' || raw.trim() === '') return {}
769
+ try {
770
+ const parsed = JSON.parse(raw)
771
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
772
+ } catch {
773
+ return {}
774
+ }
775
+ }
776
+
777
+ /**
778
+ * The AnySearch vertical domains, as verified against the live API.
779
+ *
780
+ * Every entry below was probed with a real request: `ok` means the tag works on its
781
+ * own, `needs` names the parameter the API rejects it without (the error text is
782
+ * literally `Missing required params for tag '<tag>': <names>`), and everything not
783
+ * listed here answered `Invalid tag`. That is why this is a fixed list rather than a
784
+ * text box — the valid vocabulary is small, closed, and not discoverable from the UI.
785
+ *
786
+ * `library` / `type` are free-form per the API, so they stay text; the row tells the
787
+ * user which key to use, which is the part that was previously unknowable.
788
+ */
789
+ const ANYSEARCH_TAGS = [
790
+ { tag: '', needs: null },
791
+ { tag: 'academic.paper', needs: null },
792
+ { tag: 'code.doc', needs: 'library' },
793
+ ]
794
+
795
+ /**
796
+ * Domains verified to work but left out of the control.
797
+ *
798
+ * A segmented control lays its segments on one line: eight domains measured 949px
799
+ * inside a 640px column, and the last three were clipped off the edge. The control
800
+ * is an `inline-grid` with a position indicator, so wrapping it with CSS moves the
801
+ * indicator out of alignment — the honest fix is fewer choices.
802
+ *
803
+ * The remaining domains are still honoured if present in the config; the page shows
804
+ * them as their own option. They are simply not offered, because the two above plus
805
+ * general search cover what this deployment is for.
806
+ *
807
+ * Verified working (probed against the live API): general.general, business.company
808
+ * (no params); finance.quote, health.drug (need `type`); travel.flight (needs
809
+ * date,arrival,depart). Invalid: legal.case, gaming.wiki, film.movie, security.cve,
810
+ * ip.patent, geo.place, finance.stock.
811
+ *
812
+ * Add one of the working domains to {@link ANYSEARCH_TAGS} if a deployment needs it;
813
+ * keep the list at four or fewer so the control stays on one line.
814
+ */
815
+
816
+ /**
817
+ * The parameters a vertical domain requires, or null when it needs none.
818
+ *
819
+ * @param tag - a value from {@link ANYSEARCH_TAGS}.
820
+ * @returns the parameter key list, or null.
821
+ */
822
+ function requiredParamsFor(tag) {
823
+ return ANYSEARCH_TAGS.find((item) => item.tag === tag)?.needs ?? null
824
+ }
825
+
826
+ /** Ids `enable` can name: the legs this plugin actually registers. */
827
+ const MOUNTABLE_LEGS = [
828
+ 'deepseek-search-rich',
829
+ 'deepseek-fetch-rich',
830
+ 'anysearch',
831
+ 'tavily',
832
+ 'http',
833
+ ]
834
+
835
+ /**
836
+ * Read `enable` as a set.
837
+ *
838
+ * Empty means "mount everything", so an empty set is not "mount nothing" — that
839
+ * distinction lives in the host (`enable.length === 0` mounts all).
840
+ *
841
+ * @param field - the form-field snapshot for `enable`.
842
+ * @returns the set of ids the field names.
843
+ */
844
+ function mountedSet(field) {
845
+ const raw = String(field?.text ?? '').trim()
846
+ // The host reads an EMPTY list as "mount everything", so the page must show every
847
+ // leg ticked for it. Showing them all unticked (which is what an empty list looks
848
+ // like if you read it literally) made the control state the opposite of the truth.
849
+ if (raw === '') return new Set(MOUNTABLE_LEGS)
850
+ const named = new Set(raw.split(',').map((id) => id.trim()).filter((id) => id !== ''))
851
+ return new Set(MOUNTABLE_LEGS.filter((id) => named.has(id)))
852
+ }
853
+
854
+ /**
855
+ * Which capability a leg serves, for the label.
856
+ *
857
+ * `http` serves fetch only, so mounting it alone leaves the search chain empty —
858
+ * a mistake the label now makes visible.
859
+ *
860
+ * @param id - provider id.
861
+ * @returns 'search' | 'fetch' | 'search+fetch' | null.
862
+ */
863
+ function legCapability(id) {
864
+ if (id === 'anysearch' || id === 'tavily') return 'search+fetch'
865
+ if (id === 'http') return 'fetch'
866
+ if (id.startsWith('deepseek-search')) return 'search'
867
+ if (id.startsWith('deepseek-fetch')) return 'fetch'
868
+ return null
869
+ }
870
+
871
+ /**
872
+ * Read a numeric field, falling back to the shipped default.
873
+ *
874
+ * @param field - the form-field snapshot.
875
+ * @param fallback - value used when the field is empty or unparseable.
876
+ * @returns the number.
877
+ */
878
+ function numberOr(field, fallback) {
879
+ const raw = String(field?.text ?? '').trim()
880
+ if (raw === '') return fallback
881
+ const value = Number(raw)
882
+ return Number.isFinite(value) ? value : fallback
883
+ }
884
+
885
+ /**
886
+ * A labelled row that offers named choices instead of a blank box.
887
+ *
888
+ * `minBodyChars` and `timeoutMs` were free-text number boxes, which asks the user to
889
+ * invent a threshold the plugin already measured. The measured spread is three
890
+ * orders of magnitude (a site footer is 142–332 chars; a real article is 63k–100k),
891
+ * so precision to the single character buys nothing — a handful of named choices
892
+ * covers every case and states what each one means.
893
+ *
894
+ * @param options - key, label, hint, value, options, disabled, onChange, t.
895
+ * @returns the row element.
896
+ */
897
+ function choiceRow(options) {
898
+ const { key, label, hint, value, choices, disabled, onChange } = options
899
+ const nodes = [
900
+ React.createElement('label', { key: 'label', className: 'wfb-label' }, label),
901
+ primitives.SegmentedControl({
902
+ id: `plugin-config-web-fallback-${key}`,
903
+ label,
904
+ value: String(value),
905
+ disabled,
906
+ options: choices.map((choice) => ({ value: String(choice.value), label: choice.label })),
907
+ onChange,
908
+ }),
909
+ ]
910
+ if (hint) nodes.push(React.createElement('p', { key: 'hint', className: 'wfb-hint' }, hint))
911
+ return React.createElement('div', { key, className: 'wfb-field' }, nodes)
912
+ }
913
+
914
+ /**
915
+ * A labelled value row for one config field.
916
+ *
917
+ * The page must be able to set EVERY field the schema declares. Seven of them used
918
+ * to be reachable only by hand-editing the profile patch — and that file is
919
+ * generated from the UI, so a value the UI cannot write is a value that drifts.
920
+ *
921
+ * The spread mirrors the product's own settings pages (`...state.<field>`): the
922
+ * field object carries `text`, `invalid` and `overridden`, and `SettingsValueField`
923
+ * needs all three to render the reset control and the invalid state. Passing
924
+ * `text` alone drops both.
925
+ *
926
+ * @param options - key, label, field (the form-field snapshot), numeric, placeholder,
927
+ * disabled, onEdit, onReset, t.
928
+ * @returns the row element.
929
+ */
930
+ function valueRow(options) {
931
+ const { key, label, field, numeric, placeholder, disabled, onEdit, onReset, t: tr } = options
932
+ return primitives.SettingsValueField({
933
+ id: `plugin-config-web-fallback-${key}`,
934
+ label,
935
+ placeholder,
936
+ overriddenLabel: tr('overridden'),
937
+ resetLabel: tr('reset'),
938
+ invalidLabel: tr('invalidNumber'),
939
+ numeric: numeric === true,
940
+ disabled,
941
+ ...field,
942
+ onEdit,
943
+ onReset,
944
+ })
945
+ }
946
+
947
+ function groupTitle(key, title) {
948
+ return React.createElement('p', { key: `group-${key}`, className: 'wfb-sectionTitle' }, title);
949
+ }
950
+
951
+ function switchRow(options) {
952
+ const { key, label, hint, checked, disabled, onEdit } = options;
953
+ const nodes = [
954
+ React.createElement('label', { key: 'label', className: 'wfb-toggleRow' }, [
955
+ React.createElement('span', { key: 'text' }, label),
956
+ primitives.Switch({
957
+ checked,
958
+ label,
959
+ disabled,
960
+ onChange: (next) => onEdit(next ? 'true' : 'false'),
961
+ }),
962
+ ]),
963
+ ];
964
+ if (hint) nodes.push(React.createElement('p', { key: 'hint', className: 'wfb-hint' }, hint));
965
+ return React.createElement('div', { key, className: 'wfb-toggle' }, nodes);
966
+ }
967
+
968
+
969
+ /**
970
+ * Render the one-liner or the settings form, as the Plugins page asks.
971
+ *
972
+ * The controls show the entry's **stored** values (read from the same
973
+ * configuration scope the form writes to) and stage edits through the shared
974
+ * form model, so what is on screen is what the deployment currently runs even
975
+ * right after a save.
976
+ *
977
+ * @param props - asked view, locale copy, the form snapshot, its actions, the
978
+ * entry's stored values, and the seam's pinned providers.
979
+ * @returns the summary text, or the form.
980
+ */
981
+ /**
982
+ * Render the settings card, degrading instead of disappearing.
983
+ *
984
+ * If anything in the rich layout throws — a primitive this shell does not
985
+ * export, a value shape the model did not produce — the plain form is shown
986
+ * instead. A card showing only a few switches is still usable; a card that
987
+ * renders nothing is not, and it is indistinguishable from a plugin that never
988
+ * loaded. Every "the page is gone" report so far was a render-time throw whose
989
+ * only evidence was in the browser console.
990
+ */
991
+ function FallbackSettings(props) {
992
+ if (props.view === 'summary') return props.t('description');
993
+ try {
994
+ return RichSettings(props);
995
+ } catch (error) {
996
+ if (typeof console !== 'undefined' && console.error) {
997
+ console.error('[dsh-web-fallback-chain] rich settings failed, showing the plain form:', error);
998
+ }
999
+ // The fallback used to call a `PlainSettings` that had been deleted, so the
1000
+ // one path meant to survive a render failure threw a ReferenceError of its
1001
+ // own and the card vanished with only a browser-console trace. A recovery
1002
+ // path that cannot run is worse than none: it hides the original error.
1003
+ // Now it renders what is always safe to render — the localized description
1004
+ // plus the underlying message, so a broken form is visible and diagnosable.
1005
+ try {
1006
+ return PlainSettings(props, error);
1007
+ } catch (again) {
1008
+ if (typeof console !== 'undefined' && console.error) {
1009
+ console.error('[dsh-web-fallback-chain] plain settings failed too:', again);
1010
+ }
1011
+ return props.t('description');
1012
+ }
1013
+ }
1014
+ }
1015
+
1016
+ /**
1017
+ * The last-resort rendering: never touches `props` state or primitives.
1018
+ *
1019
+ * It exists so a failure to render the real form produces something the user
1020
+ * can read in the page itself, instead of an empty card and a console message
1021
+ * they will never see.
1022
+ */
1023
+ function PlainSettings(props, cause) {
1024
+ const t = props.t;
1025
+ const message = String(cause && cause.message ? cause.message : cause || '');
1026
+ return React.createElement('div', { className: 'wfb-fallback' }, [
1027
+ React.createElement('p', { key: 'desc', className: 'wfb-hint' }, t('description')),
1028
+ React.createElement('p', { key: 'err', className: 'wfb-error' }, message),
1029
+ ]);
1030
+ }
1031
+
1032
+ function RichSettings(props) {
1033
+ const { t } = props;
1034
+ if (props.view === 'summary') return t('description');
1035
+
1036
+ const state = props.useFallbackCard((snapshot) => snapshot);
1037
+ const disabled = !state.writable;
1038
+ // The leg notes are prose, so they need the active language rather than a
1039
+ // dictionary key. `props.lang` comes from apply(), which owns the locale.
1040
+ const lang = props.lang === 'en' ? 'en' : 'zh';
1041
+ // The AnySearch domain and whether it demands parameters. Resolved once so the
1042
+ // control, the parameter row and the hint all read the same value.
1043
+ const tagValue = String(state.anysearchTag?.text ?? '').trim();
1044
+ const requiredParams = requiredParamsFor(tagValue);
1045
+ const paramsNeeded = requiredParams !== null;
1046
+
1047
+ /** One staged-text field, with the props every official page spreads. */
1048
+ const valueField = (options) => primitives.SettingsValueField({
1049
+ overriddenLabel: t('overridden'),
1050
+ resetLabel: t('reset'),
1051
+ numeric: false,
1052
+ disabled,
1053
+ ...options,
1054
+ });
1055
+
1056
+ // ── Why this page is five controls and not fourteen ────────────────────
1057
+ //
1058
+ // Every field here already has a measured default, so none of them is
1059
+ // something a user must fill in. Shipping all fourteen anyway produced the
1060
+ // exact complaint this rewrite answers: "一大堆框,根本不知道要填写什么".
1061
+ //
1062
+ // The official pages in this product top out at three inputs (web-search 3,
1063
+ // subagent 2, shell 2, agent-loop 1). This page keeps the five controls that
1064
+ // correspond to a real decision, and leaves the rest to the profile's
1065
+ // `cordis.patch.yml` — which is where a value you need to *change once* belongs,
1066
+ // not a form field you must scroll past on every visit.
1067
+ //
1068
+ // switches freeOnly, annotateFallback — the two behaviour toggles
1069
+ // choice defaultMode — how deep to read by default
1070
+ // order fetchOrder, searchOrder — the ranking, which is the point
1071
+ // of the plugin
1072
+ // One wrapper around `SettingsForm`: it owns the column width and the outer
1073
+ // padding. The host renders this card into a 960px flex section with zero
1074
+ // padding, so without a wrapper every control runs edge to edge and the copy
1075
+ // sits flush against the panel border.
1076
+ return React.createElement('div', { className: 'wfb-root' }, primitives.SettingsForm({
1077
+ labels: formLabels(t),
1078
+ state,
1079
+ onSave: props.save,
1080
+ onDiscard: props.discard,
1081
+ children: [
1082
+ groupTitle('basic', t('groupBasic')),
1083
+ switchRow({
1084
+ key: 'free-only',
1085
+ label: t('freeOnly'),
1086
+ hint: t('freeOnlyHint'),
1087
+ checked: boolOf(state.freeOnly),
1088
+ disabled,
1089
+ onEdit: (text) => props.edit('freeOnly', text),
1090
+ }),
1091
+ switchRow({
1092
+ key: 'annotate-fallback',
1093
+ label: t('annotateFallback'),
1094
+ hint: t('annotateFallbackHint'),
1095
+ checked: boolOf(state.annotateFallback),
1096
+ disabled,
1097
+ onEdit: (text) => props.edit('annotateFallback', text),
1098
+ }),
1099
+ // Four known values, so present them as four choices.
1100
+ //
1101
+ // This was a free-text box for a value that can only be `brief`, `deep`,
1102
+ // `list` or `page` — a typo was a save-time failure and the user had to know
1103
+ // the vocabulary. `SegmentedControl` is the product's own control for exactly
1104
+ // this (see dsh-client-ui-settings-models, its only other user).
1105
+ React.createElement('div', { key: 'depth', className: 'wfb-field' }, [
1106
+ React.createElement('label', { key: 'label', className: 'wfb-label' }, t('depth')),
1107
+ primitives.SegmentedControl({
1108
+ id: 'plugin-config-web-fallback-mode',
1109
+ label: t('depth'),
1110
+ value: modeOf(state.defaultMode),
1111
+ disabled,
1112
+ options: MODES.map((mode) => ({ value: mode, label: t(`mode_${mode}`) })),
1113
+ onChange: (next) => props.edit('defaultMode', next),
1114
+ }),
1115
+ React.createElement('p', { key: 'hint', className: 'wfb-hint' }, t('depthHint')),
1116
+ ]),
1117
+ // ── What the chain actually does ────────────────────────────────────
1118
+ //
1119
+ // These were two free-text boxes ("comma-separated, leftmost first") that
1120
+ // asked the user to retype an order the plugin had already measured. That is
1121
+ // the wrong question: the ranking IS the product, so the page's job is to
1122
+ // show the running ladder, not to hand over a text field and hope.
1123
+ //
1124
+ // `freeOnly` is the one thing that changes this list, so the preview is
1125
+ // rendered from the switch's current position.
1126
+ groupTitle('chain', t('groupChain')),
1127
+ chainRow('fetch', state, { t, lang, edit: props.edit, resetField: props.resetField }),
1128
+ chainRow('search', state, { t, lang, edit: props.edit, resetField: props.resetField }),
1129
+ // ── Credentials ────────────────────────────────────────────────────
1130
+ //
1131
+ // These were simply absent before: the page could toggle and reorder legs
1132
+ // but gave no way to see whether a leg had a key, let alone set one, so
1133
+ // "how do I configure the API key" had no answer in the GUI at all.
1134
+ //
1135
+ // One field per leg, showing SET / NOT SET from the Host and accepting a
1136
+ // replacement. `SettingsSecretField` never renders a stored value back —
1137
+ // `set` is write-only and `describe` returns presence only.
1138
+ // ── Advanced ────────────────────────────────────────────────────────
1139
+ //
1140
+ // Everything here has a measured default and most users never touch it —
1141
+ // but "rarely changed" is not "never changed", and the only other way to
1142
+ // change these was to hand-edit the profile patch that this page writes.
1143
+ // `minBodyChars` in particular is the fix for the most damaging failure the
1144
+ // benchmark found (a site footer counting as a successful fetch), so it has
1145
+ // to be reachable when a deployment's pages are unusually short.
1146
+ groupTitle('advanced', t('groupAdvanced')),
1147
+ choiceRow({
1148
+ key: 'min-body-chars',
1149
+ label: t('minBodyCharsLabel'),
1150
+ hint: t('minBodyCharsHint'),
1151
+ value: numberOr(state.minBodyChars, 0),
1152
+ disabled,
1153
+ choices: MIN_BODY_CHOICES(t),
1154
+ onChange: (next) => props.edit('minBodyChars', next),
1155
+ }),
1156
+ choiceRow({
1157
+ key: 'timeout-ms',
1158
+ label: t('timeoutMsLabel'),
1159
+ hint: t('timeoutMsHint'),
1160
+ value: numberOr(state.timeoutMs, 30000),
1161
+ disabled,
1162
+ choices: TIMEOUT_CHOICES(t),
1163
+ onChange: (next) => props.edit('timeoutMs', next),
1164
+ }),
1165
+ // Which legs to mount. A comma-separated id list asked the user to type
1166
+ // provider ids from memory — so instead every leg is a checkbox, and the
1167
+ // stored value is composed from what is ticked.
1168
+ React.createElement('div', { key: 'enable', className: 'wfb-field' }, [
1169
+ React.createElement('label', { key: 'label', className: 'wfb-label' }, t('enableLabel')),
1170
+ // One checkbox per leg. `Checkbox` is a plain function taking
1171
+ // {checked, onChange, label, disabled} — verified against the shipped bundle
1172
+ // rather than assumed.
1173
+ React.createElement('div', { key: 'mount', className: 'wfb-mount' },
1174
+ MOUNTABLE_LEGS.map((id) => primitives.Checkbox({
1175
+ key: id,
1176
+ label: `${id}${legCapability(id) === null ? '' : ` · ${legCapability(id)}`}`,
1177
+ checked: mountedSet(state.enable).has(id),
1178
+ disabled,
1179
+ onChange: (checked) => {
1180
+ const next = new Set(mountedSet(state.enable))
1181
+ if (checked) next.add(id); else next.delete(id)
1182
+ // All-on is stored as the empty list, because that is the host's
1183
+ // "mount everything" value. Anything less is stored as the explicit
1184
+ // allow-list. Unchecking the last leg cannot be expressed — `[]` means
1185
+ // all — so it is refused rather than silently mounting everything.
1186
+ if (next.size === 0) return
1187
+ props.edit('enable', next.size === MOUNTABLE_LEGS.length ? '' : [...next].join(','))
1188
+ },
1189
+ }))),
1190
+ React.createElement('p', { key: 'hint', className: 'wfb-hint' }, t('enableHint')),
1191
+ ]),
1192
+ // The vertical domain is a closed vocabulary validated against the live API, so
1193
+ // it is a choice, not a text box. Only the domain that needs parameters shows
1194
+ // the parameter row, and it says which key the API insists on.
1195
+ choiceRow({
1196
+ key: 'anysearch-tag',
1197
+ label: t('anysearchTagLabel'),
1198
+ hint: t('anysearchTagHint'),
1199
+ value: tagValue,
1200
+ disabled,
1201
+ choices: [
1202
+ ...ANYSEARCH_TAGS.map(({ tag }) => ({ value: tag, label: tag === '' ? t('tagGeneral') : tag })),
1203
+ // A tag set outside this list still has to be visible, or the control
1204
+ // would look like "general" while the config says something else.
1205
+ ...(ANYSEARCH_TAGS.some((item) => item.tag === tagValue)
1206
+ ? []
1207
+ : [{ value: tagValue, label: tagValue }]),
1208
+ ],
1209
+ onChange: (next) => {
1210
+ props.edit('anysearchTag', next)
1211
+ // A tag whose required params are not supplied is a guaranteed API error,
1212
+ // so switching away from one clears the params it belonged to.
1213
+ if (requiredParamsFor(next) === null) props.edit('anysearchParams', '')
1214
+ },
1215
+ }),
1216
+ // ALWAYS rendered, never conditionally.
1217
+ //
1218
+ // This row used to appear only for a domain that needs parameters. That made
1219
+ // the number of hooks in this component change with the selected tag, and
1220
+ // React aborts the whole slot when that happens — error #300 "rendered more
1221
+ // hooks than during the previous render" / #311 "fewer hooks", and the config
1222
+ // page simply vanished the moment you picked `code.doc`. A stable element
1223
+ // list that is merely disabled is the only safe shape here.
1224
+ // Kept in the element list unconditionally, and hidden with CSS when the
1225
+ // selected domain needs no parameters. Conditionally *rendering* it changed
1226
+ // the hook count and blanked the page (React #300/#311); hiding it with a
1227
+ // class changes nothing structural.
1228
+ React.createElement('div', {
1229
+ key: 'params',
1230
+ className: paramsNeeded ? 'wfb-field' : 'wfb-field wfb-hidden',
1231
+ }, [
1232
+ valueRow({
1233
+ key: 'anysearch-params',
1234
+ label: t('anysearchParamsLabel'),
1235
+ field: state.anysearchParams,
1236
+ disabled,
1237
+ onEdit: (text) => props.edit('anysearchParams', text),
1238
+ onReset: () => props.resetField('anysearchParams'),
1239
+ t,
1240
+ }),
1241
+ React.createElement('p', { key: 'params-hint', className: 'wfb-hint' },
1242
+ t('anysearchParamsRequired').replace('{keys}', requiredParams ?? '')),
1243
+ ]),
1244
+ React.createElement('p', {
1245
+ key: 'params-idle',
1246
+ className: paramsNeeded ? 'wfb-hint wfb-hidden' : 'wfb-hint',
1247
+ }, t('anysearchParamsNotNeeded')),
1248
+ // Billing classification per leg. This is the one `providers` field that
1249
+ // changes behaviour the moment it is edited: `freeOnly` reads exactly this.
1250
+ // Marking a leg free here makes the switch stop skipping it.
1251
+ React.createElement('div', { key: 'cost', className: 'wfb-field' }, [
1252
+ React.createElement('label', { key: 'label', className: 'wfb-label' }, t('costTitle')),
1253
+ React.createElement('p', { key: 'hint', className: 'wfb-hint' }, t('costHint')),
1254
+ ...costRows({
1255
+ state,
1256
+ disabled,
1257
+ onEdit: (id, next) => props.edit(`cost:${id}`, next),
1258
+ t,
1259
+ }),
1260
+ ]),
1261
+ switchRow({
1262
+ key: 'deepseek-need-content',
1263
+ label: t('deepseekNeedContentLabel'),
1264
+ hint: t('deepseekNeedContentHint'),
1265
+ checked: boolOf(state.deepseekNeedContent),
1266
+ disabled,
1267
+ onEdit: (text) => props.edit('deepseekNeedContent', text),
1268
+ }),
1269
+ groupTitle('keys', t('groupKeys')),
1270
+ ...CREDENTIALS.map(({ ref, labelKey, hintKey }) => primitives.SettingsSecretField({
1271
+ id: `plugin-config-web-fallback-key-${ref.toLowerCase().replaceAll('_', '-')}`,
1272
+ label: t(labelKey),
1273
+ hint: t(hintKey),
1274
+ disabled: state.credentials?.[ref]?.writable === false,
1275
+ text: state.credentialDrafts?.[ref] ?? '',
1276
+ configured: state.credentials?.[ref]?.configured === true,
1277
+ stateLabel: state.credentials?.[ref]?.configured === true ? t('keySet') : t('keyUnset'),
1278
+ onEdit: (text) => props.editCredential(ref, text),
1279
+ })),
1280
+
1281
+ // Says where the rest went, so a missing knob reads as "documented", not
1282
+ // as "the plugin forgot to expose it".
1283
+ React.createElement('p', { key: 'save-note', className: 'wfb-note' }, t('saveNote')),
1284
+ ],
1285
+ }));
1286
+ }
1287
+
1288
+ /** Services the page registers against. */
1289
+ // `remote.credentials` is a hard dependency on purpose, and it is what the
1290
+ // official web-search page declares too: without it the page could not show
1291
+ // whether a key is set, and a settings page that cannot answer that is the
1292
+ // state the user just rejected ("不知道怎么看 api key").
1293
+ const inject = ['slots', 'locale', 'configForms', 'remote', 'remote.credentials'];
1294
+
1295
+ /**
1296
+ * The credential references this plugin's legs read.
1297
+ *
1298
+ * Matches `policy/providers.js` `requiresKey` exactly: the leg asks the store
1299
+ * for this name, so the settings page must write the same one. `http` has no
1300
+ * key and is absent by design.
1301
+ */
1302
+ const CREDENTIALS = [
1303
+ { ref: 'DEEPSEEK_API_KEY', labelKey: 'keyDeepseek', hintKey: 'keyDeepseekHint', legs: 'deepseek-search-rich / deepseek-fetch-rich' },
1304
+ { ref: 'ANYSEARCH_API_KEY', labelKey: 'keyAnysearch', hintKey: 'keyAnysearchHint', legs: 'anysearch' },
1305
+ { ref: 'TAVILY_API_KEY', labelKey: 'keyTavily', hintKey: 'keyTavilyHint', legs: 'tavily' },
1306
+ ];
1307
+
1308
+ /**
1309
+ * Mount this bundle's configuration page.
1310
+ *
1311
+ * @param ctx - browser plugin context.
1312
+ */
1313
+ function apply(ctx) {
1314
+ const t = ctx.locale.bind(NS);
1315
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'web-fallback: dictionaries');
1316
+
1317
+ const card = new CardController(ctx.configForms.get(ENTRY_ID));
1318
+
1319
+ // The credential bridge. Its state is pushed into the card's snapshot so the
1320
+ // key fields re-render when a value is stored, without a second store.
1321
+ const credentialBridge = new CredentialController(ctx, (state) => card.setCredentials(state));
1322
+ card.bridge = credentialBridge;
1323
+ // `ctx.locale.current()` is the product's accessor for the active language.
1324
+ try {
1325
+ const current = typeof ctx.locale.current === 'function' ? ctx.locale.current() : undefined;
1326
+ card.lang = String(current ?? '').toLowerCase().startsWith('en') ? 'en' : 'zh';
1327
+ } catch {
1328
+ card.lang = 'zh';
1329
+ }
1330
+ credentialBridge.refresh();
1331
+ ctx.effect(() => () => card.dispose(), 'web-fallback: form subscription');
1332
+
1333
+ // Registered into `plugins.bundle.config`, keyed by PACKAGE name.
1334
+ //
1335
+ // The Plugins page has two different slots and they are not interchangeable:
1336
+ //
1337
+ // · `plugins.item` — cards for the harness's OWN built-in plugins
1338
+ // (the `extensions` group). A card registered here
1339
+ // is attached to a built-in plugin that does not
1340
+ // exist, which is why an earlier revision of this
1341
+ // file showed up under 「内置插件配置」 even though
1342
+ // this package is plainly an installed one.
1343
+ // · `plugins.bundle.config` — the configuration page of an INSTALLED package
1344
+ // (the `bundles` group, 「已安装插件」), matched by
1345
+ // the package name the manager passes as `entryKey`.
1346
+ //
1347
+ // Same mistake, same fix as an earlier plugin of ours (see the long note above its
1348
+ // own registration): use `key`, not `id`, and pass the package name — the string that
1349
+ // pairs this card with our row in 已安装插件.
1350
+ //
1351
+ // `whileServed` keeps its original job: it defers registration until the Host
1352
+ // serves one of our entries and re-runs when that changes, so the page never
1353
+ // shows a config section that resolves to `unavailable`. Its argument is the
1354
+ // CONFIG ENTRY id (`web-fallback`), not the package name.
1355
+ ctx.effect(
1356
+ () => ctx.configForms.whileServed([ENTRY_ID], () => ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
1357
+ name: 'plugins.bundle.config',
1358
+ key: PACKAGE_NAME,
1359
+ order: 40,
1360
+ locale: NS,
1361
+ inject: () => card.inject(),
1362
+ }, FallbackSettings))),
1363
+ 'web-fallback: page',
1364
+ );
1365
+ }
1366
+
1367
+ /**
1368
+ * The page's staged form over the plugin's settings namespace.
1369
+ *
1370
+ * Same shape as the official card controller: one `SettingsFormModel`, a bound
1371
+ * projection per field, and `inject()` handing the slot both the snapshot store
1372
+ * and the actions.
1373
+ */
1374
+ /**
1375
+ * Reads and writes the three credential references through the Host.
1376
+ *
1377
+ * Same shape as the official web-search page's bridge, deliberately: the value
1378
+ * never comes back over the wire (`set` only writes; `describe` answers
1379
+ * configured/writable), so the page can report "set / not set" and accept a new
1380
+ * value, and nothing more.
1381
+ */
1382
+ class CredentialController {
1383
+ /**
1384
+ * @param ctx - browser plugin context carrying `remote.credentials`.
1385
+ * @param onChange - called with the new `{ ref: {configured, writable} }` map.
1386
+ */
1387
+ constructor(ctx, onChange) {
1388
+ this.ctx = ctx;
1389
+ this.onChange = onChange;
1390
+ /** @type {Record<string, {configured: boolean, writable: boolean}>} */
1391
+ this.state = {};
1392
+ /** Staged text per ref, never persisted, never echoed back by the Host. */
1393
+ this.drafts = {};
1394
+ this.disposed = false;
1395
+ }
1396
+
1397
+ /** The refs this page manages. */
1398
+ refs() {
1399
+ return CREDENTIALS.map((entry) => entry.ref);
1400
+ }
1401
+
1402
+ /** Ask the Host which of our refs carry a value. */
1403
+ async refresh() {
1404
+ try {
1405
+ const response = await this.ctx.remote.credentials.describe(this.refs());
1406
+ if (this.disposed || !response?.ok) return;
1407
+ const next = {};
1408
+ for (const ref of this.refs()) {
1409
+ const view = response.value?.[ref];
1410
+ next[ref] = { configured: view?.configured === true, writable: view?.writable !== false };
1411
+ }
1412
+ this.state = next;
1413
+ this.onChange(this.state);
1414
+ } catch (error) {
1415
+ // A deployment without a credential provider is a supported state: the
1416
+ // keys then come from the environment only, and the page says so by
1417
+ // showing every field as unset rather than failing to render.
1418
+ if (typeof console !== 'undefined' && console.error) {
1419
+ console.error('[dsh-web-fallback-chain] credentials unavailable:', error);
1420
+ }
1421
+ }
1422
+ }
1423
+
1424
+ /** Stage a value for one ref; nothing is written until save. */
1425
+ edit(ref, text) {
1426
+ this.drafts[ref] = String(text ?? '');
1427
+ this.onChange(this.state);
1428
+ }
1429
+
1430
+ /** Write every staged value, then re-read what the Host now holds. */
1431
+ async commit() {
1432
+ for (const [ref, value] of Object.entries(this.drafts)) {
1433
+ if (value.length === 0) continue;
1434
+ await this.ctx.remote.credentials.set(ref, value);
1435
+ }
1436
+ this.drafts = {};
1437
+ await this.refresh();
1438
+ }
1439
+
1440
+ /** Whether anything is staged. */
1441
+ get dirty() {
1442
+ return Object.values(this.drafts).some((value) => value.length > 0);
1443
+ }
1444
+
1445
+ /** Drop staged values and event handlers. */
1446
+ dispose() {
1447
+ this.disposed = true;
1448
+ this.drafts = {};
1449
+ }
1450
+ }
1451
+
1452
+ class CardController {
1453
+ /**
1454
+ * @param scope - the bound settings scope for this plugin's namespace.
1455
+ */
1456
+ constructor(scope) {
1457
+ this.scope = scope;
1458
+ this.form = new primitives.SettingsFormModel(scope, [
1459
+ booleanField('freeOnly'),
1460
+ booleanField('annotateFallback'),
1461
+ textField('defaultMode', 'brief'),
1462
+ orderField('order'),
1463
+ orderField('searchOrder'),
1464
+ // NOTE: the eight `modeOrders.<capability>.<mode>` lists are deliberately NOT
1465
+ // registered here. They are not config fields — the schema has one
1466
+ // `modeOrders` object — so a spec under those names would stage edits the
1467
+ // host silently drops. `edit()` composes them into `modeOrders` directly.
1468
+ jsonField('providers'),
1469
+ numberField('minBodyChars'),
1470
+ numberField('timeoutMs'),
1471
+ // ─── fields the page used to leave to the patch file ───────────────
1472
+ //
1473
+ // Every one of these is read by the host (`readField`), so leaving them
1474
+ // out of the form meant they could only be changed by hand-editing YAML
1475
+ // that the UI itself generates. The rule is the other way round: if the
1476
+ // schema declares it, the page must be able to write it.
1477
+ booleanField('deepseekNeedContent'),
1478
+ textField('anysearchTag', ''),
1479
+ textField('anysearchParams', ''),
1480
+ orderField('enable'),
1481
+ ]);
1482
+ // Staged per-mode drafts, keyed by `MODE_FIELDS.key`. They exist because
1483
+ // eight inputs share one stored `modeOrders` object and the generic form
1484
+ // model stages one draft per *config field*.
1485
+ this.modeDrafts = this.draftsFromScope(scope);
1486
+ /** Credential presence, pushed in by the bridge after each Host read. */
1487
+ this.credentialState = {};
1488
+ /** Set by `apply` to the live credential bridge (write path for keys). */
1489
+ this.bridge = undefined;
1490
+ /** Active language for the few prose strings that are not dictionary keys. */
1491
+ this.lang = 'zh';
1492
+ this.store = this.form.bind(() => this.projection());
1493
+ }
1494
+
1495
+ /**
1496
+ * Receive credential presence from the bridge and republish the snapshot.
1497
+ *
1498
+ * @param state - `{ ref: {configured, writable} }` as the Host reported it.
1499
+ */
1500
+ setCredentials(state) {
1501
+ this.credentialState = state ?? {};
1502
+ // `store` is created in the constructor, but `setCredentials` can run from a
1503
+ // bridge callback that fires before the first render; guard rather than
1504
+ // throw, because losing a repaint is survivable and losing the page is not.
1505
+ if (this.store !== undefined && typeof this.store.set === 'function') {
1506
+ this.store.set(this.projection());
1507
+ }
1508
+ }
1509
+
1510
+ /**
1511
+ * Seed the per-mode drafts from what the namespace currently stores.
1512
+ *
1513
+ * Reading through `form.field` is not possible here — the form model keys
1514
+ * drafts by config field name, and these eight are not config fields — so the
1515
+ * scope's snapshot is read directly. A scope that cannot describe itself
1516
+ * (a read-only deployment, a test double) simply yields empty drafts, which
1517
+ * means "use the measured default".
1518
+ */
1519
+ draftsFromScope(scope) {
1520
+ const drafts = {};
1521
+ try {
1522
+ const snapshot = scope?.getSnapshot?.();
1523
+ const value = snapshot?.value ?? snapshot ?? {};
1524
+ const orders = value?.modeOrders ?? {};
1525
+ for (const { capability, mode, key } of MODE_FIELDS) {
1526
+ const ids = orders?.[capability]?.[mode];
1527
+ if (Array.isArray(ids) && ids.length > 0) drafts[key] = formatIds(ids);
1528
+ }
1529
+ } catch {
1530
+ // A snapshot that throws is not worth failing the page over: empty
1531
+ // drafts render the same controls with the defaults in effect.
1532
+ }
1533
+ return drafts;
1534
+ }
1535
+
1536
+ /**
1537
+ * The card's snapshot: the form shell plus each field's own staged state.
1538
+ *
1539
+ * `form.field(name)` is what the official pages spread straight into
1540
+ * `SettingsValueField` (`...state.maxParallelToolCalls`); reading raw values
1541
+ * instead would bypass the staged/edit-tracking behaviour the form needs.
1542
+ */
1543
+ projection() {
1544
+ return {
1545
+ ...this.form.shell(),
1546
+ freeOnly: this.form.field('freeOnly'),
1547
+ annotateFallback: this.form.field('annotateFallback'),
1548
+ defaultMode: this.form.field('defaultMode'),
1549
+ order: this.form.field('order'),
1550
+ searchOrder: this.form.field('searchOrder'),
1551
+ // Per-mode drafts are staged outside the form model (see the constructor note);
1552
+ // the page reads them from `modeDrafts`, not from `form.field`.
1553
+ ...Object.fromEntries(MODE_FIELDS.map(({ key }) => [key, { text: this.modeDrafts[key] ?? '' }])),
1554
+ providers: this.form.field('providers'),
1555
+ deepseekNeedContent: this.form.field('deepseekNeedContent'),
1556
+ anysearchTag: this.form.field('anysearchTag'),
1557
+ anysearchParams: this.form.field('anysearchParams'),
1558
+ enable: this.form.field('enable'),
1559
+ credentials: this.credentialState,
1560
+ minBodyChars: this.form.field('minBodyChars'),
1561
+ timeoutMs: this.form.field('timeoutMs'),
1562
+ };
1563
+ }
1564
+
1565
+ /**
1566
+ * Stage one leg's billing classification inside `providers`.
1567
+ *
1568
+ * Preserves every other key on the entry: `providers` also carries `maxChars`,
1569
+ * `requiresKey` and `note`, and rebuilding from `{ cost }` alone would delete
1570
+ * whichever of those the deployment had set.
1571
+ *
1572
+ * @param id - provider id.
1573
+ * @param text - 'paid' | 'free'; anything else removes the override.
1574
+ */
1575
+ editCost(id, text) {
1576
+ const value = String(text ?? '').trim()
1577
+ const next = { ...readProviders(this.projection().providers) }
1578
+ const entry = { ...(next[id] ?? {}) }
1579
+
1580
+ if (value === 'paid' || value === 'free') entry.cost = value
1581
+ else delete entry.cost
1582
+
1583
+ if (Object.keys(entry).length === 0) delete next[id]
1584
+ else next[id] = entry
1585
+ this.form.actions().edit('providers', JSON.stringify(next))
1586
+ }
1587
+
1588
+ /**
1589
+ * Build the face the slot registration injects.
1590
+ *
1591
+ * @returns the page's snapshot store and its form actions.
1592
+ */
1593
+ inject() {
1594
+ return {
1595
+ hooks: { fallbackCard: this.store },
1596
+ lang: this.lang,
1597
+ credentials: this.credentialState,
1598
+ editCredential: (ref, text) => this.bridge?.edit(ref, text),
1599
+ ...this.form.actions(),
1600
+ // One Save button for both halves of the page.
1601
+ //
1602
+ // The generic `save` only commits the config form; a staged API key would
1603
+ // be silently discarded, which is the worst possible outcome for a secret
1604
+ // the user just pasted. So the credentials are written first (a key that
1605
+ // fails to store must not look saved), then the config form commits.
1606
+ save: async () => {
1607
+ await this.bridge?.commit();
1608
+ await this.form.actions().save();
1609
+ },
1610
+ // The per-mode fields are drafts of ONE stored value, so the generic
1611
+ // `edit(key, text)` cannot write them: it would look up a config field
1612
+ // named `modeFetchBrief`, which does not exist. Each edit restages that
1613
+ // draft and recomposes the whole `modeOrders` object from all eight.
1614
+ edit: (key, text) => {
1615
+ // `quality:<id>` edits one number inside the nested `providers` object.
1616
+ // One row per leg beats a JSON box: the user types a score, not a schema.
1617
+ if (key.startsWith('cost:')) {
1618
+ this.editCost(key.slice('cost:'.length), text);
1619
+ return;
1620
+ }
1621
+ const modeField = MODE_FIELDS.find((field) => field.key === key);
1622
+ if (modeField === undefined) {
1623
+ this.form.actions().edit(key, text);
1624
+ return;
1625
+ }
1626
+ this.modeDrafts[modeField.key] = String(text ?? '');
1627
+ this.form.actions().edit('modeOrders', JSON.stringify(modeOrdersFrom(this.modeDrafts)));
1628
+ },
1629
+ resetField: (key) => {
1630
+ if (key.startsWith('cost:')) {
1631
+ this.editCost(key.slice('cost:'.length), '');
1632
+ return;
1633
+ }
1634
+ const modeField = MODE_FIELDS.find((field) => field.key === key);
1635
+ if (modeField === undefined) {
1636
+ this.form.actions().resetField(key);
1637
+ return;
1638
+ }
1639
+ delete this.modeDrafts[modeField.key];
1640
+ this.form.actions().edit('modeOrders', JSON.stringify(modeOrdersFrom(this.modeDrafts)));
1641
+ },
1642
+ };
1643
+ }
1644
+
1645
+ /** Release accepted-value subscriptions. */
1646
+ dispose() {
1647
+ this.form.dispose();
1648
+ }
1649
+ }
1650
+
1651
+ exports.apply = apply;
1652
+ exports.inject = inject;
1653
+ return module.exports;
1654
+ },
1655
+ });