@wjm200509/dsh-web-search 0.0.0-stage → 0.4.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JiaMingWang-CN
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,135 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # dsh-web-search
2
+
3
+ **中文** · 第三方网页搜索插件:为 DSH 的 `web_search` 工具增加 **Tavily / 模型自带联网**
4
+ 两个后端,并在设置侧边栏的"第三方搜索"页面提供**总开关**。关闭开关即交回 DSH 内置搜索,
5
+ 开启后 `web_search` 走所选第三方后端,无需重启。不修改 DSH 源码,卸载即恢复内置行为。
6
+
7
+ ## 搜索工具
8
+
9
+ | 引擎 | 计费 | 说明 |
10
+ | --- | --- | --- |
11
+ | **Tavily(默认、推荐)** | **免费 1000 次/月** | LLM 优化搜索,返回摘要 + AI 答案;在 <https://app.tavily.com> 注册并创建 API Key |
12
+ | **模型自带联网** | 约 ¥16/千次 + token 费 | 借 MiMo API 服务端 `web_search`;需在 MiMo 控制台(Console → Plugin Management)开通「Web Search 插件」;本插件固定单次 1 个关键词以控制费用 |
13
+
14
+ 关闭总开关后,`web_search` 交回 DSH 内置的 DeepSeek 搜索:
15
+
16
+ - 默认回到 `deepseek-official`(Messages 联网搜索);
17
+ - 如果之前在 DSH 内置的 Web search 页选过新版 Search API,插件会记住并恢复到
18
+ `deepseek-search-api`(`/v1/tools/search`)。
19
+
20
+ 官方搜索的认证、参数和计费完全由 DSH 内置 provider 负责,本插件不重复实现。
21
+
22
+ ## 安装
23
+
24
+ ```powershell
25
+ # 从 npm
26
+ dsh plugin --profile web add -w "@wjm200509/dsh-web-search"
27
+
28
+ # 从 GitHub(源码目录)
29
+ dsh plugin --profile web add -w "github:JiaMingWang-CN/dsh-bundles#path:dsh-web-search"
30
+
31
+ # 本地目录
32
+ dsh plugin --profile web add -w C:\path\to\dsh-bundles\dsh-web-search
33
+
34
+ # link: 安装不会自动安装包内依赖,需在本目录执行一次:
35
+ cd dsh-web-search
36
+ pnpm install
37
+ ```
38
+
39
+ 安装后**重启 DSH**。确认组合生效:
40
+
41
+ ```powershell
42
+ dsh --profile web --dump-config
43
+ # 期望:web 行 config.searchProvider: web-search(fetchProvider: http)
44
+ # web-search 行存在
45
+ # web-search-deepseek 行保持启用(关闭开关后的内置后端)
46
+ ```
47
+
48
+ ## 使用
49
+
50
+ 1. 打开 DSH 设置,在侧边栏进入 **第三方搜索**(同一页面也可在 设置 → 插件 → dsh-web-search 的行配置中打开);
51
+ 2. 顶部开关默认**已开启**;选择 Tavily / 模型自带联网,填入 API Key 与参数,保存;
52
+ 3. 需要回到内置搜索时,关闭顶部开关即可,下一次 `web_search` 立即改用内置 provider。
53
+
54
+ 开启前需要当前引擎至少有一个已保存的 Key。关闭状态下 Key 输入框仍可填写,方便先配置再开启。
55
+
56
+ ## 开关如何工作
57
+
58
+ - 插件 patch 层把 `web` 行设为 `searchProvider: web-search`,这是**默认开启**的来源;
59
+ - **开启**:客户端对 `web` 的 `searchProvider` / `fetchProvider` 两个字段执行 `unset`。DSH 的设置服务
60
+ 会把 `unset` 解析为继承值;当整条配置与继承层完全相等时,用户层覆盖会被自动删除。因此
61
+ `web-search` 不会被写进用户配置;
62
+ - **关闭**:按插件区的 `builtin` 记忆写入内置的一组 provider:
63
+ - `messages` → `deepseek-official` + `http`;
64
+ - `api` → `deepseek-search-api` + `deepseek-fetch-api`;
65
+ - 插件页的开关状态由 `web.searchProvider === "web-search"` 推算,不另存布尔值。在内置页切换
66
+ provider 时,插件页会同步显示为"已关闭"。
67
+
68
+ ### 卸载行为
69
+
70
+ | 卸载时状态 | 用户层 `web` | 结果 |
71
+ | --- | --- | --- |
72
+ | 开启 | 无覆盖 | 插件层随 bundle 消失,回到 DSH 默认值,零残留 |
73
+ | 关闭 | 内置的一组 id | 指向 DSH 自带 provider,搜索正常 |
74
+ | 从未切换 | 无 | 零残留 |
75
+
76
+ 插件自己的 `web-search` 配置行(引擎、Key 引用等)在卸载后仍会留在用户层,这不影响 `web`,
77
+ 也不会造成悬空 provider。
78
+
79
+ ## 行为细节
80
+
81
+ - **密钥安全**:API Key 经 credentials 域写入(`$DSH_HOME/.credentials.yaml`),不写入
82
+ profile 设置文件、界面不回显明文;留空保持当前密钥。解析顺序:设置中的明文字段 →
83
+ credentials/launch-environment 中的凭证引用(默认 `TAVILY_API_KEY` / `MIMO1_API_KEY`)。
84
+ - **结果契约**:适配器只解析结构化结果(Tavily `results`/`answer`、MiMo `url_citation` 注解与
85
+ `search_results`),绝不从模型文本里抓 URL;来源数上限(默认 8)由 `dsh-tool-web`/web 接缝截断。
86
+ - **错误码**:`WEB_PROVIDER_CREDENTIAL_MISSING`(缺密钥/密钥被拒)、`WEB_PROVIDER_ERROR`
87
+ (传输/配额/响应不可解析)、`WEB_ABORTED`(取消)。缺 Key 的报错会同时提示两条出路:填 Key,
88
+ 或关闭第三方搜索改用内置。
89
+ - **模型引擎成本控制**:请求固定 `max_keyword: 1`(MiMo 按关键词次数计费)。
90
+ - **零修改 DSH 本体**:生效完全通过 loader 组合补丁(`patch.yml`:插入本插件行、把 `web` 行
91
+ 指向 `web-search`)和设置服务的公开写入接口;不修改 `app.asar`,卸载即完整还原。
92
+
93
+ ## 已接受的限制
94
+
95
+ 1. **刚装好、还没填 Key 时,搜索会报错。** patch 层默认开启,而 seam 没有回退;缺 Key 时会抛
96
+ `WEB_PROVIDER_CREDENTIAL_MISSING`,报错文案会提示填 Key 或关闭开关。`available()` 保持
97
+ 返回 `true`,避免变成含义更模糊的 `CONFIGURED_UNAVAILABLE`。
98
+ 2. **插件开启时,内置 Web search 页的开关显示为 "Messages 搜索"。** 内置页只认它自己的两组 id,
99
+ 实际后端以插件页的开关为准。
100
+ 3. **开启插件时 `fetchProvider` 回到 `http`。** 插件层固定为 `http`;之前选了新版 Search API 的
101
+ 用户,开启期间也用 HTTP 抓取,关闭后按 `builtin` 恢复 `deepseek-fetch-api`。
102
+ 4. **旧配置 `engine: deepseek` 仍然能加载**,但会归一化为 Tavily;这是为了不让旧配置让插件
103
+ 加载失败、连关闭开关的入口都没有。
104
+
105
+ ## 版本与兼容
106
+
107
+ - 0.4.0:从"接管"改为"补充";删除插件内的 DeepSeek 官方引擎,交由 DSH 内置 provider 处理。
108
+ - 适配 DSH **0.2.2-rc.1**(当前最新);测试依赖固定到该版本,peer 范围同时保留
109
+ `0.1.7-rc.2`、`0.2.0-rc.2` 与 `0.2.1-alpha.x`。
110
+ - 官方 Search API 文档:<https://api-docs.deepseek.com/api/search>。
111
+
112
+ ## 本地开发
113
+
114
+ ```powershell
115
+ cd dsh-web-search
116
+ pnpm install
117
+ node --test
118
+ ```
119
+
120
+ 引擎映射、分发和选项归一化保持为纯逻辑;Host 入口显式依赖公开的
121
+ `@deepseek-ai/dsh-web`、`@deepseek-ai/dsh-launch-environment` 与 `@deepseek-ai/schemastery` 契约。
122
+
123
+ ```text
124
+ dsh-web-search/
125
+ ├── patch.yml # loader 组合补丁(insert + web provider 指向)
126
+ ├── lib/
127
+ │ ├── index.js # 宿主半边:Config 设置表单 + 注册搜索提供方
128
+ │ ├── client.js # 浏览器半边:总开关 + plugins.row.config「第三方搜索」页
129
+ │ ├── dispatch.js # 按设置分发到所选引擎(每次搜索入口快照配置)
130
+ │ ├── options.js # 设置归一化 + 可用性检查
131
+ │ ├── http.js # JSON POST / 取消分类
132
+ │ ├── errors.js # HarnessError 形状的错误工厂
133
+ │ └── engines/ # tavily / model-native 适配器
134
+ └── test/ # node --test 单测
135
+ ```
package/lib/client.js ADDED
@@ -0,0 +1,461 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-web-search",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let react = require("react");
8
+ const React = react;
9
+ //#region lib/client.js
10
+ /** Stable Cordis plugin name. */
11
+ const name = "web-search";
12
+ /** Slots mount the row's config page; configForms and the credentials
13
+ * remote back it, and the `web` form carries the provider selection. */
14
+ const inject = ["slots", "configForms", "remote", "remote.credentials"];
15
+ /** Provider id this bundle registers; also the "on" marker in `web`. */
16
+ const WEB_SEARCH_ID = "web-search";
17
+ /** Built-in provider groups the master switch can fall back to. */
18
+ const BUILTIN_GROUPS = {
19
+ messages: { searchProvider: "deepseek-official", fetchProvider: "http" },
20
+ api: { searchProvider: "deepseek-search-api", fetchProvider: "deepseek-fetch-api" }
21
+ };
22
+ /** Card chrome + fields stylesheet, mirroring the shipped PluginCard skin (alias tokens). */
23
+ const CSS = '.dsh-ws-card{border:.5px solid var(--dsw-alias-border-l4);background:var(--dsw-alias-bg-layer-3);border-radius:16px;list-style:none;transition:border-color .16s,background .16s}' +
24
+ '.dsh-ws-card:hover{border-color:var(--dsw-alias-label-dimmed)}' +
25
+ '.dsh-ws-cardOpen{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-label-dimmed)}' +
26
+ '.dsh-ws-header{appearance:none;width:100%;font:inherit;color:inherit;text-align:left;cursor:pointer;background:0 0;border:0;border-radius:12px;align-items:center;gap:12px;padding:14px 16px;display:flex}' +
27
+ '.dsh-ws-header:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}' +
28
+ '.dsh-ws-headText{flex-direction:column;flex:1;gap:4px;min-width:0;display:flex}' +
29
+ '.dsh-ws-name{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:1.4}' +
30
+ '.dsh-ws-description{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.5}' +
31
+ '.dsh-ws-pending{flex:none;background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-secondary);border-radius:6px;padding:1px 8px;font-size:11px;line-height:1.6;white-space:nowrap}' +
32
+ '.dsh-ws-chevron{color:var(--dsw-alias-label-tertiary);flex:none;transition:transform .16s;display:inline-flex}' +
33
+ '.dsh-ws-chevronOpen{transform:rotate(180deg)}' +
34
+ '.dsh-ws-body{max-width:720px;display:flex;flex-direction:column;gap:0;padding-bottom:8px}' +
35
+ '.dsh-ws-readOnly{color:var(--dsw-alias-label-tertiary);margin:12px 0 0;font-size:12px;line-height:1.5}' +
36
+ '.dsh-ws-footer{border-top:.5px solid var(--dsw-alias-border-l2);justify-content:flex-end;align-items:center;gap:8px;padding:12px 0 4px;display:flex}' +
37
+ '.dsh-ws-failed{min-width:0;color:var(--dsw-alias-label-error);flex:1;margin:0;font-size:12px;line-height:1.5}' +
38
+ '.dsh-ws-discard,.dsh-ws-save{appearance:none;font:inherit;cursor:pointer;border:1px solid #0000;border-radius:8px;padding:5px 14px;font-size:13px;line-height:1.5}' +
39
+ '.dsh-ws-discard{border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);background:0 0}' +
40
+ '.dsh-ws-discard:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}' +
41
+ '.dsh-ws-save{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}' +
42
+ '.dsh-ws-discard:disabled,.dsh-ws-save:disabled{opacity:.4;cursor:default}' +
43
+ '.dsh-ws-discard:focus-visible,.dsh-ws-save:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}' +
44
+ '.dsh-ws-field{flex-direction:column;gap:6px;padding:12px 0;display:flex}' +
45
+ '.dsh-ws-field+.dsh-ws-field{border-top:.5px solid var(--dsw-alias-border-l2)}' +
46
+ '.dsh-ws-head{align-items:center;gap:8px;display:flex}' +
47
+ '.dsh-ws-label{min-width:0;color:var(--dsw-alias-label-primary);flex:1;font-size:13px;font-weight:500;line-height:1.5}' +
48
+ '.dsh-ws-badges{align-items:center;gap:8px;display:inline-flex}' +
49
+ '.dsh-ws-badge{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:1.5;white-space:nowrap}' +
50
+ '.dsh-ws-badgeOn{color:var(--dsw-alias-state-success-primary,#10b981)}' +
51
+ '.dsh-ws-input{border:.5px solid var(--dsw-alias-border-l4);background:var(--dsw-alias-bg-layer-3);height:34px;font:inherit;color:var(--dsw-alias-label-primary);border-radius:8px;padding:0 12px;font-size:13px;line-height:1.5;width:100%;box-sizing:border-box}' +
52
+ '.dsh-ws-input:focus-visible{border-color:var(--dsw-alias-brand-primary);outline:none}' +
53
+ '.dsh-ws-input:disabled{color:var(--dsw-alias-label-tertiary);cursor:default}' +
54
+ '.dsh-ws-invalid{color:var(--dsw-alias-label-error);margin:0;font-size:12px;line-height:1.5}' +
55
+ '.dsh-ws-hint{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}' +
56
+ '.dsh-ws-seg{display:flex;gap:8px;flex-wrap:wrap}' +
57
+ '.dsh-ws-segbtn{appearance:none;font:inherit;box-sizing:border-box;padding:3px 12px;border-radius:14px;font-size:12px;line-height:1.6;cursor:pointer;background:var(--dsw-alias-bg-layer-3);border:.5px solid var(--dsw-alias-border-l4);color:var(--dsw-alias-label-secondary);transition:background .15s,border-color .15s,color .15s}' +
58
+ '.dsh-ws-segbtn:hover{border-color:var(--dsw-alias-label-dimmed)}' +
59
+ '.dsh-ws-segbtn.on{background:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}' +
60
+ '.dsh-ws-segbtn:disabled{opacity:.4;cursor:default}' +
61
+ '.dsh-ws-switch{position:relative;box-sizing:border-box;width:40px;height:22px;border-radius:11px;padding:0;cursor:pointer;flex:none;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);transition:background .15s,border-color .15s}' +
62
+ '.dsh-ws-switch.on{background:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary)}' +
63
+ '.dsh-ws-switch:disabled{opacity:.4;cursor:default}' +
64
+ '.dsh-ws-switch:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}' +
65
+ '.dsh-ws-knob{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-bg-overlay,#fff);box-shadow:0 1px 2px rgba(0,0,0,.2);transition:transform .15s}' +
66
+ '.dsh-ws-switch.on .dsh-ws-knob{transform:translateX(18px)}';
67
+ /** Third-party engines in display order, with their short labels. */
68
+ const ENGINE_OPTIONS = [
69
+ { id: "tavily", label: "Tavily(免费)" },
70
+ { id: "model", label: "模型自带联网" }
71
+ ];
72
+ /** Per-engine copy: what it is and what it costs (selector hint). */
73
+ const ENGINE_INFO = {
74
+ tavily: "Tavily 免费档:每月 1000 次搜索、零运维。在 app.tavily.com 注册并创建 API Key。",
75
+ model: "模型自带联网搜索(MiMo 服务端 web_search,需在 MiMo 控制台开通「Web Search 插件」)。按次计费约 ¥16/千次 + token 费;已固定单次 1 个关键词以控制费用。"
76
+ };
77
+ /** Credential reference field per engine, with its default. */
78
+ const KEY_ENV_FIELDS = {
79
+ tavily: { field: "tavilyApiKeyEnv", fallback: "TAVILY_API_KEY" },
80
+ model: { field: "modelApiKeyEnv", fallback: "MIMO1_API_KEY" }
81
+ };
82
+ /** Non-secret fields edited by each engine's form, with copy. */
83
+ const VALUE_FIELDS = {
84
+ tavily: [
85
+ { field: "tavilySearchDepth", label: "搜索深度", hint: "advanced 相关性更高,但每次按 2 个额度计费。" }
86
+ ],
87
+ model: [
88
+ { field: "modelBaseUrl", label: "接口地址", hint: "openai 兼容接口的 /v1 基址;留空则使用默认地址。" },
89
+ { field: "modelId", label: "模型", hint: "用于检索摘要的模型;留空则使用默认模型。" }
90
+ ]
91
+ };
92
+ /** Row summary and introductory copy. */
93
+ const DESCRIPTION = "\u4E3A web_search \u589E\u52A0 Tavily / MiMo \u540E\u7AEF\uFF1B\u5173\u95ED\u5F00\u5173\u5373\u4EA4\u56DE DSH \u5185\u7F6E\u641C\u7D22\u3002";
94
+ /** Small copy used across the form. */
95
+ const COPY = {
96
+ thirdParty: "\u4F7F\u7528\u7B2C\u4E09\u65B9\u641C\u7D22",
97
+ on: "\u5DF2\u5F00\u542F",
98
+ off: "\u5DF2\u5173\u95ED",
99
+ onHint: "web_search \u8D70\u6240\u9009\u7B2C\u4E09\u65B9\u540E\u7AEF\uFF1B\u5173\u95ED\u540E\u6539\u7528 DSH \u5185\u7F6E\u641C\u7D22\u3002",
100
+ offHint: "\u5F53\u524D\u4F7F\u7528 DSH \u5185\u7F6E\u641C\u7D22\uFF1B\u5F00\u542F\u540E web_search \u8D70\u6240\u9009\u7B2C\u4E09\u65B9\u540E\u7AEF\u3002",
101
+ needKey: "\u5148\u4FDD\u5B58\u5F53\u524D\u540E\u7AEF\u7684 API Key\uFF0C\u518D\u5F00\u542F\u7B2C\u4E09\u65B9\u641C\u7D22\u3002",
102
+ missingOnHint: "\u5F53\u524D\u540E\u7AEF\u8FD8\u672A\u914D\u7F6E API Key\uFF0C\u641C\u7D22\u4F1A\u62A5\u9519\uFF1B\u8BF7\u5728\u4E0B\u65B9\u4FDD\u5B58 Key\uFF0C\u6216\u5173\u95ED\u5F00\u5173\u6539\u7528\u5185\u7F6E\u3002",
103
+ switchFailed: "\u5207\u6362\u6CA1\u6709\u751F\u6548\uFF0C\u8BF7\u91CD\u8BD5\uFF1B\u8BBE\u7F6E\u53EF\u80FD\u88AB\u66F4\u9AD8\u4F18\u5148\u7EA7\u7684\u914D\u7F6E\u56FA\u5B9A\u3002",
104
+ builtinNote: "\u5F00\u542F\u671F\u95F4\u5185\u7F6E\u9875\u53EF\u80FD\u663E\u793A\u4E3A Messages \u641C\u7D22\uFF0C\u5B9E\u9645\u540E\u7AEF\u4EE5\u672C\u5F00\u5173\u4E3A\u51C6\u3002",
105
+ engine: "\u7B2C\u4E09\u65B9\u540E\u7AEF",
106
+ apiKey: "API Key",
107
+ keyHint: "\u4E0D\u5199\u5165\u8BBE\u7F6E\u6587\u4EF6\u3002\u7559\u7A7A\u8868\u793A\u4FDD\u6301\u5F53\u524D\u5BC6\u94A5\u3002",
108
+ keySet: "\u5DF2\u914D\u7F6E\u5BC6\u94A5",
109
+ keyUnset: "\u672A\u914D\u7F6E\u5BC6\u94A5",
110
+ discard: "\u653E\u5F03\u4FEE\u6539",
111
+ save: "\u4FDD\u5B58",
112
+ saving: "\u4FDD\u5B58\u4E2D\u2026",
113
+ saveFailed: "\u672C\u90E8\u7F72\u6CA1\u6709\u63A5\u53D7\u8FD9\u4E9B\u503C\uFF0C\u5DF2\u4FDD\u7559\u4F9B\u4F60\u4FEE\u6539\u3002",
114
+ readOnly: "\u672C\u90E8\u7F72\u7684\u8BBE\u7F6E\u4E3A\u53EA\u8BFB\u3002",
115
+ unsaved: "\u672A\u4FDD\u5B58"
116
+ };
117
+ /** Maximum time to wait for the settings mirror to publish a completed write. */
118
+ const SETTINGS_SETTLE_MS = 250;
119
+ /** The value a field should reach after one write operation. */
120
+ function expectedValue(form, op) {
121
+ if (op.op === "set") return op.value;
122
+ const base = form.getSnapshot().base ?? {};
123
+ return op.path.reduce((node, key) => node == null ? undefined : node[key], base);
124
+ }
125
+ /** Whether every requested setting is visible in the scope snapshot. */
126
+ function settingsApplied(form, expected) {
127
+ const stored = form.getSnapshot().value ?? {};
128
+ return expected.every((item) => Object.is(item.path.reduce((node, key) => node == null ? undefined : node[key], stored), item.value));
129
+ }
130
+ /** Wait for an asynchronously published settings snapshot, or reject a silent refusal. */
131
+ function waitForSettings(form, ops) {
132
+ const expected = ops.map((op) => ({ path: op.path, value: expectedValue(form, op) }));
133
+ if (settingsApplied(form, expected)) return Promise.resolve();
134
+ return new Promise((resolve, reject) => {
135
+ let settled = false;
136
+ let timer;
137
+ let dispose = () => {};
138
+ const finish = (error) => {
139
+ if (settled) return;
140
+ settled = true;
141
+ if (timer !== undefined) clearTimeout(timer);
142
+ dispose();
143
+ if (error === undefined) resolve();
144
+ else reject(error);
145
+ };
146
+ const check = () => {
147
+ if (settingsApplied(form, expected)) finish();
148
+ };
149
+ dispose = form.subscribe(check);
150
+ if (settled) {
151
+ dispose();
152
+ return;
153
+ }
154
+ timer = setTimeout(() => finish(new Error("settings write was not published")), SETTINGS_SETTLE_MS);
155
+ check();
156
+ });
157
+ }
158
+ /**
159
+ * The third-party search configuration page the bundle's row opens
160
+ * (`plugins.row.config`) and the Settings sidebar page. It owns the
161
+ * master switch over `web` (the DSH provider selection) plus the
162
+ * engine/key form over this bundle's `web-search` namespace.
163
+ *
164
+ * Turning the switch on writes both `web` fields as `unset`, which the
165
+ * DSH settings service resolves to the inherited bundle-patch values and
166
+ * then prunes from the user layer. Turning it off writes the remembered
167
+ * built-in group, so the plugin id never has to live in user settings.
168
+ */
169
+ function WebSearchCard(props) {
170
+ const host = props.host;
171
+ const webHost = props.webHost;
172
+ const remote = props.remote;
173
+ const writable = host.getSnapshot().writable !== false;
174
+ const [section, setSection] = React.useState(() => host.getSnapshot().value ?? {});
175
+ const [draft, setDraft] = React.useState(() => ({ ...(host.getSnapshot().value ?? {}) }));
176
+ const [dirty, setDirty] = React.useState(false);
177
+ const [saving, setSaving] = React.useState(false);
178
+ const [failed, setFailed] = React.useState(false);
179
+ const [keyDraft, setKeyDraft] = React.useState("");
180
+ const [configured, setConfigured] = React.useState(false);
181
+ const [webState, setWebState] = React.useState(() => webHost.getSnapshot());
182
+ const [switching, setSwitching] = React.useState(false);
183
+ const [switchFailed, setSwitchFailed] = React.useState(false);
184
+ const thirdParty = webState.value?.searchProvider === WEB_SEARCH_ID;
185
+ const webWritable = webState.writable !== false;
186
+ const engine = ENGINE_OPTIONS.some((option) => option.id === draft.engine) ? draft.engine : "tavily";
187
+ const refOf = (id) => {
188
+ const spec = KEY_ENV_FIELDS[id];
189
+ const declared = section[spec.field];
190
+ return typeof declared === "string" && declared.length > 0 ? declared : spec.fallback;
191
+ };
192
+ React.useEffect(() => host.subscribe(() => {
193
+ const value = host.getSnapshot().value ?? {};
194
+ setSection(value);
195
+ if (!dirty && !saving) setDraft({ ...value });
196
+ }), [host, dirty, saving]);
197
+ React.useEffect(() => webHost.subscribe(() => setWebState(webHost.getSnapshot())), [webHost]);
198
+ const credentialRef = refOf(engine);
199
+ /* Re-read only when the reference changes; a reply for a reference the
200
+ * card has since left (engine switch) is dropped, not shown. */
201
+ React.useEffect(() => {
202
+ let current = true;
203
+ remote.credentials.describe([credentialRef]).then((response) => {
204
+ if (current && response.ok) setConfigured(response.value[credentialRef]?.configured === true);
205
+ }).catch(() => {});
206
+ return () => { current = false; };
207
+ }, [remote, credentialRef]);
208
+ const switchEngine = (id) => {
209
+ setDraft((prev) => ({ ...prev, engine: id }));
210
+ setKeyDraft("");
211
+ setDirty(true);
212
+ };
213
+ const edit = (field, value) => {
214
+ setDraft((prev) => ({ ...prev, [field]: value }));
215
+ setDirty(true);
216
+ };
217
+ /** Remember which built-in group is active before taking over. */
218
+ const captureBuiltin = async () => {
219
+ const current = webHost.getSnapshot().value?.searchProvider;
220
+ const next = current === "deepseek-search-api" ? "api" : current === "deepseek-official" ? "messages" : undefined;
221
+ if (next === undefined) return;
222
+ if (host.getSnapshot().value?.builtin === next) return;
223
+ const ops = [{ op: "set", path: ["builtin"], value: next }];
224
+ await host.mutate(ops);
225
+ await waitForSettings(host, ops);
226
+ };
227
+ /** Enable third-party search: drop the user-layer `web` override. */
228
+ const enableThirdParty = async () => {
229
+ if (!webWritable || switching) return;
230
+ setSwitching(true);
231
+ setSwitchFailed(false);
232
+ try {
233
+ await captureBuiltin();
234
+ const ops = [
235
+ { op: "unset", path: ["searchProvider"] },
236
+ { op: "unset", path: ["fetchProvider"] }
237
+ ];
238
+ await webHost.mutate(ops);
239
+ await waitForSettings(webHost, ops);
240
+ } catch {
241
+ setSwitchFailed(true);
242
+ } finally {
243
+ setSwitching(false);
244
+ }
245
+ };
246
+ /** Disable third-party search: restore the remembered built-in group. */
247
+ const disableThirdParty = async () => {
248
+ if (!webWritable || switching) return;
249
+ const builtin = host.getSnapshot().value?.builtin === "api" ? "api" : "messages";
250
+ const group = BUILTIN_GROUPS[builtin];
251
+ setSwitching(true);
252
+ setSwitchFailed(false);
253
+ try {
254
+ const ops = [
255
+ { op: "set", path: ["searchProvider"], value: group.searchProvider },
256
+ { op: "set", path: ["fetchProvider"], value: group.fetchProvider }
257
+ ];
258
+ await webHost.mutate(ops);
259
+ await waitForSettings(webHost, ops);
260
+ } catch {
261
+ setSwitchFailed(true);
262
+ } finally {
263
+ setSwitching(false);
264
+ }
265
+ };
266
+ const toggleThirdParty = () => thirdParty ? disableThirdParty() : enableThirdParty();
267
+ const switchDisabled = !webWritable || switching || saving || (!thirdParty && (!configured || !writable));
268
+ const blocked = !writable || !dirty || saving || switching;
269
+ const save = async () => {
270
+ if (blocked) return;
271
+ setSaving(true);
272
+ setFailed(false);
273
+ try {
274
+ const fields = [{ field: "engine" }, ...Object.values(VALUE_FIELDS).flat()];
275
+ const ops = [];
276
+ for (const spec of fields) {
277
+ const raw = spec.field === "engine" ? engine : draft[spec.field];
278
+ if (raw === undefined || raw === "") continue;
279
+ if (Object.is(raw, section[spec.field])) continue;
280
+ ops.push({ op: "set", path: [spec.field], value: raw });
281
+ }
282
+ if (ops.length > 0) {
283
+ await host.mutate(ops);
284
+ await waitForSettings(host, ops);
285
+ }
286
+ if (keyDraft.length > 0) {
287
+ const response = await remote.credentials.set(credentialRef, keyDraft);
288
+ if (!response.ok) throw new Error(response.error.message);
289
+ setKeyDraft("");
290
+ setConfigured(true);
291
+ }
292
+ setDirty(false);
293
+ } catch {
294
+ setFailed(true);
295
+ } finally {
296
+ setSaving(false);
297
+ }
298
+ };
299
+ const discard = () => {
300
+ setDraft({ ...section });
301
+ setKeyDraft("");
302
+ setDirty(false);
303
+ setFailed(false);
304
+ };
305
+ const valueField = (spec) => {
306
+ const value = draft[spec.field] ?? "";
307
+ return React.createElement("div", { className: "dsh-ws-field", key: spec.field },
308
+ React.createElement("div", { className: "dsh-ws-head" },
309
+ React.createElement("span", { className: "dsh-ws-label" }, spec.label),
310
+ ),
311
+ React.createElement("input", {
312
+ className: "dsh-ws-input",
313
+ type: "text",
314
+ disabled: !writable || !thirdParty,
315
+ value,
316
+ onChange: (event) => edit(spec.field, event.target.value),
317
+ }),
318
+ React.createElement("p", { className: "dsh-ws-hint" }, spec.hint),
319
+ );
320
+ };
321
+ const keyField = React.createElement("div", { className: "dsh-ws-field", key: "apiKey" },
322
+ React.createElement("div", { className: "dsh-ws-head" },
323
+ React.createElement("span", { className: "dsh-ws-label" }, COPY.apiKey),
324
+ React.createElement("span", { className: "dsh-ws-badges" },
325
+ React.createElement("span", { className: "dsh-ws-badge" + (configured ? " dsh-ws-badgeOn" : "") },
326
+ configured ? COPY.keySet : COPY.keyUnset),
327
+ ),
328
+ ),
329
+ React.createElement("input", {
330
+ className: "dsh-ws-input",
331
+ type: "password",
332
+ disabled: !writable,
333
+ placeholder: "\u7559\u7A7A\u4FDD\u6301\u5F53\u524D\u5BC6\u94A5",
334
+ value: keyDraft,
335
+ onChange: (event) => {
336
+ setKeyDraft(event.target.value);
337
+ setDirty(true);
338
+ },
339
+ }),
340
+ React.createElement("p", { className: "dsh-ws-hint" }, COPY.keyHint),
341
+ );
342
+ const engineField = React.createElement("div", { className: "dsh-ws-field", key: "engine" },
343
+ React.createElement("div", { className: "dsh-ws-head" },
344
+ React.createElement("span", { className: "dsh-ws-label" }, COPY.engine),
345
+ React.createElement("span", { className: "dsh-ws-seg" },
346
+ ENGINE_OPTIONS.map((option) => React.createElement("button", {
347
+ key: option.id,
348
+ type: "button",
349
+ disabled: !writable,
350
+ className: "dsh-ws-segbtn" + (engine === option.id ? " on" : ""),
351
+ onClick: () => switchEngine(option.id),
352
+ }, option.label)),
353
+ ),
354
+ ),
355
+ React.createElement("p", { className: "dsh-ws-hint" }, ENGINE_INFO[engine]),
356
+ );
357
+ const depthField = engine === "tavily" ? React.createElement("div", { className: "dsh-ws-field", key: "depth" },
358
+ React.createElement("div", { className: "dsh-ws-head" },
359
+ React.createElement("span", { className: "dsh-ws-label" }, VALUE_FIELDS.tavily[0].label),
360
+ React.createElement("span", { className: "dsh-ws-seg" },
361
+ [{ id: "basic", label: "basic" }, { id: "advanced", label: "advanced" }].map((option) => React.createElement("button", {
362
+ key: option.id,
363
+ type: "button",
364
+ disabled: !writable || !thirdParty,
365
+ className: "dsh-ws-segbtn" + ((draft.tavilySearchDepth ?? "basic") === option.id ? " on" : ""),
366
+ onClick: () => edit("tavilySearchDepth", option.id),
367
+ }, option.label)),
368
+ ),
369
+ ),
370
+ React.createElement("p", { className: "dsh-ws-hint" }, VALUE_FIELDS.tavily[0].hint),
371
+ ) : null;
372
+ const masterField = React.createElement("div", { className: "dsh-ws-field", key: "thirdParty" },
373
+ React.createElement("div", { className: "dsh-ws-head" },
374
+ React.createElement("span", { className: "dsh-ws-label" }, COPY.thirdParty),
375
+ React.createElement("span", { className: "dsh-ws-badges" },
376
+ React.createElement("span", { className: "dsh-ws-badge" + (thirdParty ? " dsh-ws-badgeOn" : "") }, thirdParty ? COPY.on : COPY.off),
377
+ React.createElement("button", {
378
+ type: "button",
379
+ role: "switch",
380
+ "aria-checked": thirdParty ? "true" : "false",
381
+ "aria-label": COPY.thirdParty,
382
+ className: "dsh-ws-switch" + (thirdParty ? " on" : ""),
383
+ disabled: switchDisabled,
384
+ onClick: toggleThirdParty,
385
+ }, React.createElement("span", { className: "dsh-ws-knob" })),
386
+ ),
387
+ ),
388
+ React.createElement("p", { className: "dsh-ws-hint" }, thirdParty ? COPY.onHint : COPY.offHint),
389
+ !thirdParty && !configured ? React.createElement("p", { className: "dsh-ws-invalid" }, COPY.needKey) : null,
390
+ thirdParty && !configured ? React.createElement("p", { className: "dsh-ws-invalid" }, COPY.missingOnHint) : null,
391
+ switchFailed ? React.createElement("p", { className: "dsh-ws-failed", role: "status" }, COPY.switchFailed) : null,
392
+ thirdParty ? React.createElement("p", { className: "dsh-ws-hint" }, COPY.builtinNote) : null,
393
+ );
394
+ const bodyFields = engine === "tavily"
395
+ ? [keyField, depthField]
396
+ : [keyField, ...VALUE_FIELDS[engine].map(valueField)];
397
+ /* The page's heading chrome belongs to the plugins page owner. */
398
+ return React.createElement("div", { className: "dsh-ws-body" },
399
+ !writable || !webWritable ? React.createElement("p", { className: "dsh-ws-readOnly", role: "status" }, COPY.readOnly) : null,
400
+ masterField,
401
+ engineField,
402
+ bodyFields,
403
+ React.createElement("div", { className: "dsh-ws-footer" },
404
+ dirty ? React.createElement("span", { className: "dsh-ws-pending" }, COPY.unsaved) : null,
405
+ failed ? React.createElement("p", { className: "dsh-ws-failed", role: "status" }, COPY.saveFailed) : null,
406
+ React.createElement("button", {
407
+ type: "button",
408
+ className: "dsh-ws-discard",
409
+ disabled: blocked,
410
+ onClick: discard,
411
+ }, COPY.discard),
412
+ React.createElement("button", {
413
+ type: "button",
414
+ className: "dsh-ws-save",
415
+ disabled: blocked,
416
+ onClick: save,
417
+ }, saving ? COPY.saving : COPY.save),
418
+ ),
419
+ );
420
+ }
421
+ /**
422
+ * Client plugin body: the stylesheet plus the configuration page for the
423
+ * bundle's `web-search` row, keyed `<package>#<row id>` as the
424
+ * `plugins.row.config` slot contract spells it, AND a `settings.section`
425
+ * page so the Settings sidebar lists 第三方搜索 beside the sibling bundle
426
+ * pages. Both render the same form over the `web-search` settings
427
+ * namespace and the `web` provider selection.
428
+ * @param ctx - client root context.
429
+ */
430
+ function apply(ctx) {
431
+ const host = ctx.configForms.get(name);
432
+ const webHost = ctx.configForms.get("web");
433
+ ctx.effect(() => {
434
+ const tag = document.createElement("style");
435
+ tag.textContent = CSS;
436
+ document.head.append(tag);
437
+ return () => tag.remove();
438
+ }, "web-search: styles");
439
+ ctx.effect(() => ctx.configForms.whileServed([name], () => {
440
+ const offRow = ctx.slots.inject("plugins.row.config", () => ctx.slots.register(
441
+ { name: "plugins.row.config", key: "@wjm200509/dsh-web-search#web-search" },
442
+ /* `summary` is the row's static one-liner: no form, no credential lookup. */
443
+ (props) => props.view === "summary" ? DESCRIPTION : React.createElement(WebSearchCard, { ...props, host, webHost, remote: ctx.remote }),
444
+ ));
445
+ const offSection = ctx.slots.inject("settings.section", () => ctx.slots.register(
446
+ { name: "settings.section", id: "web-search", order: 32, label: "第三方搜索" },
447
+ () => React.createElement(WebSearchCard, { view: "page", host, webHost, remote: ctx.remote }),
448
+ ));
449
+ return () => {
450
+ offRow();
451
+ offSection();
452
+ };
453
+ }), "web-search: config page");
454
+ }
455
+ //#endregion
456
+ exports.apply = apply;
457
+ exports.inject = inject;
458
+ exports.name = name;
459
+ return module.exports;
460
+ }
461
+ });