dsh-union-search 0.15.0 → 0.16.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/README.md CHANGED
@@ -179,6 +179,16 @@ Error: configured web provider "ddg" is not registered
179
179
  > 对本插件的三个后果:①接管判据不受影响(未设置 → 仍是本插件的接管分支,`ddg` 两种出厂 id 仍在白名单内);②**钉选变得更要紧**——一旦 `settings.mutate` 没落地(settings 服务尚未挂载时本插件会延迟重试),`web_search` 不再报 `WEB_PROVIDER_AMBIGUOUS`,而是**静默**走官方通道,看起来像"插件没生效"却没有任何错误;③设置页的搜索 provider 菜单多出一个「自动」项(`AUTO_ID` 空串),选中它会 `resetField` 清掉 `searchProvider` 覆盖,于是本插件的钉选被解除、搜索回到官方通道——这不是 bug,是官方新语义,但要知道点了什么。
180
180
  > 自查:日志里出现 `union-search: pinned web entry config searchProvider=ddg` 才算接管成功;只有出现 `settings service not ready` / `could not pin` 才是没落地。
181
181
 
182
+ #### 接管残留自动回收(0.16.0)
183
+
184
+ 上面 `CONFIGURED_MISSING` 悬空的根因是「rc.2+ 唯一接管通道 `settings.mutate` 会落盘到 `cordis.patch.yml`」。0.16.0 起在「写」的两端自动补救,三种场景各有覆盖:
185
+
186
+ - **停用插件 = 自动清**:`autoRestoreOnDispose`(默认开)开启时,本插件在停用/dispose 时自动 `unset` 它自己写进 `web` 条目的 `searchProvider` / `fetchProvider` 钉选行——**只删自己写过的值**(回滚前比对当前值 === 写入值),你后来手改成别家 provider、或本就不是本插件写的,一律不动。
187
+ - **上次没清干净 = 启动自检**:崩溃/断电等未走 dispose 的情况,下次启动会在接管动作前自检当前钉选态:命中**本插件旧 id**(如改名前的 `web-search-free`)即安全清除;命中**能解析到已注册 provider** 的外部 id(你显式选的第三方)→ 静默不动;命中**解析不到的悬空 id**(别的已卸载插件留的)→ 打 ERROR 级日志给出修复命令,但**不自动删**(删别人的配置风险高于提示)。
188
+ - **卸载 = 需手跑 `bin/restore.js --apply`**:`pnpm remove` 之后插件代码已不在磁盘上,任何钩子都不会执行——这是执行模型的物理边界,无法靠开关绕过。卸载前请先在设置页关掉接管,或卸载后跑一次 `node node_modules/dsh-union-search/bin/restore.js --apply`(0.11.6+,只删本插件钉选行,默认 dry-run)。
189
+
190
+ 自检结论会反映到设置页「屏蔽系统自带搜索」抽屉底部的接管状态行(正常 / 悬空残留 / 外部占用),`autoRestoreOnDispose` 关掉后回滚登记与自检清除都停用,仅保留检测与提示。
191
+
182
192
  > 如果你曾按旧文档手动在 `profiles/<profile>/cordis.patch.yml` 里加过下面这段,而插件没有启用,就会看到上面那条错误——**删掉这段即可**(或重新启用插件):
183
193
 
184
194
  ```yaml
@@ -586,6 +596,16 @@ Without that override, a disabled plugin leaves `web.searchProvider` at the ship
586
596
  > Three consequences for this plugin: ① the takeover criterion is unaffected (unset → still this plugin's takeover branch, and both shipped ids stay in the whitelist); ② **the pin matters more than before** — if `settings.mutate` never lands (this plugin defers and retries when the settings service is not mounted yet), `web_search` no longer raises `WEB_PROVIDER_AMBIGUOUS`; it **silently** goes to the official provider, so it looks like "the plugin did nothing" with no error at all; ③ the search-provider menu on the settings page gained an "Automatic" entry (empty id), and picking it calls `resetField`, clearing the `searchProvider` override — i.e. it releases this plugin's pin and search returns to the official provider. That is official behaviour, not a bug, but be aware of what the click does.
587
597
  > Self-check: takeover only succeeded when the log shows `union-search: pinned web entry config searchProvider=ddg`; seeing `settings service not ready` / `could not pin` means it did not land.
588
598
 
599
+ #### Takeover residue auto-reclaim (0.16.0)
600
+
601
+ The root cause of the `CONFIGURED_MISSING` dangling above is that on rc.2+ the only takeover channel, `settings.mutate`, persists into `cordis.patch.yml`. From 0.16.0 the plugin patches both ends of that write, one mechanism per scenario:
602
+
603
+ - **Plugin disable = auto-clear**: with `autoRestoreOnDispose` (on by default), disabling this plugin un-pins the `searchProvider` / `fetchProvider` rows it wrote into the `web` entry — **it only removes values it wrote itself** (it compares current === pinned before un-setting), so a value you later hand-switched to another provider, or anything this plugin never wrote, is left intact.
604
+ - **Unclean previous exit = startup self-check**: for crashes / power loss that skip dispose, the next start runs a self-check before takeover. A hit on **this plugin's legacy id** (e.g. the pre-rename `web-search-free`) is cleared safely; a hit on an **external id that resolves to a registered provider** (a third party you picked on purpose) is left silently alone; a hit on an **unresolvable dangling id** (left by some other uninstalled plugin) logs an ERROR with the repair command but is **not auto-deleted** (removing someone else's config is riskier than warning).
605
+ - **Uninstall = run `bin/restore.js --apply` by hand**: after `pnpm remove` the plugin code is gone from disk, so no hook can run — a physical limit of the execution model, not something a toggle can bypass. Turn off takeover on the settings page before uninstalling, or run `node node_modules/dsh-union-search/bin/restore.js --apply` afterwards (since 0.11.6, removes only this plugin's pinned rows, dry-run by default).
606
+
607
+ The self-check verdict surfaces on the "Block built-in system search" drawer as a takeover-status line (OK / dangling / external). With `autoRestoreOnDispose` off, both the dispose rollback and the self-check clearing are disabled — only detection and the warning remain.
608
+
589
609
  > If you previously added the snippet below by hand to `profiles/<profile>/cordis.patch.yml` *and* the plugin is not enabled, you will see that error — **just remove the snippet** (or re-enable the plugin):
590
610
 
591
611
  ```yaml
package/lib/client.js CHANGED
@@ -209,6 +209,12 @@ window.__ModuleLoader__.load({
209
209
  browserFetchAllowHostsHint: "逗号分隔域名后缀(含子域),如 linkedin.com,weibo.com;空 = 不限制(仍受上方总开关控制)。建议只钉登录墙域名,避免任意 URL 都被带 cookie 访问。",
210
210
  deepseekToolsBaseUrl: "DeepSeek Tools 端点(可选)",
211
211
  deepseekToolsBaseUrlHint: "默认直连官方 https://api.deepseek.com/v1/tools/search;自建网关可填 base(自动补 /v1/tools/search)或完整端点 URL(走 /v1/search 的网关填完整 URL);留空 = 官方默认,保存即热生效。",
212
+ autoRestoreOnDispose: "停用插件时自动回收接管钉选",
213
+ autoRestoreOnDisposeHint: "开启后:停用本插件时自动清除写进 web 条目的 searchProvider/fetchProvider 钉选,启动时还会自检上次未清干净的遗留(只删本插件写过的值,外部第三方 provider 永不误删)。关闭后退回纯手动:跑 node bin/restore.js --apply。注意:卸载场景任何取值都无法自动回收(插件代码已不存在),必须手跑 restore.js。",
214
+ takeoverOk: "接管状态:正常(未钉选 / 本插件在用 / 宿主出厂)",
215
+ takeoverDangling: "接管状态:发现悬空残留(本插件旧钉选或无主 id)——日志里有修复命令",
216
+ takeoverForeign: "接管状态:外部 provider 占用(非本插件写入,不会动它)",
217
+ takeoverPinnedBy: "当前钉选",
212
218
  sec_engines: "引擎与回退链",
213
219
  sec_behavior: "搜索行为",
214
220
  sec_keys: "API Key",
@@ -354,6 +360,12 @@ window.__ModuleLoader__.load({
354
360
  browserFetchAllowHostsHint: "Comma-separated domain suffixes (subdomains included), e.g. linkedin.com,weibo.com; empty = unrestricted (still gated by the master switch above). Recommended: pin only the login-walled domains so arbitrary URLs never get fetched with your cookies.",
355
361
  deepseekToolsBaseUrl: "DeepSeek Tools endpoint (optional)",
356
362
  deepseekToolsBaseUrlHint: "Defaults to the official https://api.deepseek.com/v1/tools/search; a custom gateway accepts either a base URL (…/v1/tools/search is appended) or the full endpoint URL (fill the full URL for gateways serving /v1/search); empty = official default, takes effect on save.",
363
+ autoRestoreOnDispose: "Auto-reclaim takeover pins on plugin disable",
364
+ autoRestoreOnDisposeHint: "When on, disabling this plugin un-pins the searchProvider/fetchProvider it wrote into the web entry, and a startup self-check repairs leftovers from unclean exits (only values this plugin wrote are touched — third-party providers are never removed). When off, clean up manually: node bin/restore.js --apply. Note: uninstall is never covered automatically by either setting (plugin code no longer exists) — restore.js must be run by hand.",
365
+ takeoverOk: "Takeover state: OK (unpinned / owned by this plugin / shipped default)",
366
+ takeoverDangling: "Takeover state: dangling pin detected (legacy value from this plugin or an unregistered id) — repair command in the logs",
367
+ takeoverForeign: "Takeover state: held by an external provider (not written by this plugin, left untouched)",
368
+ takeoverPinnedBy: "Current pins",
357
369
  sec_engines: "Engines & fallback chain",
358
370
  sec_behavior: "Search behaviour",
359
371
  sec_keys: "API keys",
@@ -538,6 +550,16 @@ window.__ModuleLoader__.load({
538
550
  return response.json();
539
551
  }
540
552
 
553
+ // 接管状态自检结果(0.16.0):health 三态数据源,load 后异步刷新
554
+ async function bridgeTakeoverStatus() {
555
+ const response = await fetch(`${BRIDGE_PREFIX}/takeover-status`, {
556
+ method: "POST",
557
+ headers: { "content-type": "application/json" },
558
+ body: "{}",
559
+ });
560
+ return response.json();
561
+ }
562
+
541
563
  async function bridgeCheckUpdate() {
542
564
  const response = await fetch(`${BRIDGE_PREFIX}/check-update`, {
543
565
  method: "POST",
@@ -987,6 +1009,8 @@ window.__ModuleLoader__.load({
987
1009
  const [cacheTtl, setCacheTtl] = react.useState(5);
988
1010
  // 屏蔽系统自带搜索(blockSystemSearch):强制接管 + 剔除出厂 deepseek-official
989
1011
  const [blockSystemSearch, setBlockSystemSearch] = react.useState(false);
1012
+ const [autoRestoreOnDispose, setAutoRestoreOnDispose] = react.useState(true);
1013
+ const [takeoverStatus, setTakeoverStatus] = react.useState(null);
990
1014
  const [fetchTakeover, setFetchTakeover] = react.useState(false);
991
1015
  const [browserFetchTier, setBrowserFetchTier] = react.useState(false);
992
1016
  const [browserFetchAllowHosts, setBrowserFetchAllowHosts] = react.useState("");
@@ -1073,6 +1097,7 @@ window.__ModuleLoader__.load({
1073
1097
  setPlatforms(Array.isArray(v.platforms) && v.platforms.length > 0 ? v.platforms : ["github", "v2ex", "bilibili", "reddit", "hn", "stackoverflow", "wikipedia", "npm", "youtube", "vimeo"]);
1074
1098
  setCacheTtl(v.cacheTtl === undefined ? 5 : Math.min(Math.max(Number(v.cacheTtl) ?? 5, 0), 5));
1075
1099
  setBlockSystemSearch(v.blockSystemSearch === true);
1100
+ setAutoRestoreOnDispose(v.autoRestoreOnDispose !== false);
1076
1101
  setFetchTakeover(v.fetchTakeover === true);
1077
1102
  setBrowserFetchTier(v.browserFetchTier === true);
1078
1103
  setBrowserFetchAllowHosts(typeof v.browserFetchAllowHosts === "string" ? v.browserFetchAllowHosts : "");
@@ -1126,6 +1151,11 @@ window.__ModuleLoader__.load({
1126
1151
  setCredConfigured(cc);
1127
1152
  }
1128
1153
  } catch {}
1154
+ // 接管自检态(0.16.0):失败静默(旧宿主无该 bridge 路由)
1155
+ try {
1156
+ const ts = await bridgeTakeoverStatus();
1157
+ if (ts && ts.ok && ts.value) setTakeoverStatus(ts.value);
1158
+ } catch {}
1129
1159
  } else {
1130
1160
  setState({ status: "unavailable" });
1131
1161
  }
@@ -1308,6 +1338,7 @@ window.__ModuleLoader__.load({
1308
1338
  ops.push({ op: "set", path: ["platforms"], value: platforms });
1309
1339
  ops.push({ op: "set", path: ["cacheTtl"], value: Math.min(Math.max(Number(cacheTtl) ?? 5, 0), 5) });
1310
1340
  ops.push({ op: "set", path: ["blockSystemSearch"], value: blockSystemSearch });
1341
+ ops.push({ op: "set", path: ["autoRestoreOnDispose"], value: autoRestoreOnDispose });
1311
1342
  ops.push({ op: "set", path: ["fetchTakeover"], value: fetchTakeover });
1312
1343
  ops.push({ op: "set", path: ["browserFetchTier"], value: browserFetchTier });
1313
1344
  ops.push({ op: "set", path: ["browserFetchAllowHosts"], value: String(browserFetchAllowHosts).trim() });
@@ -2447,6 +2478,44 @@ react_jsx_runtime.jsx(Section, { id: "block", title: t.sec_block, defaultOpen: f
2447
2478
  }),
2448
2479
  ],
2449
2480
  }),
2481
+ react_jsx_runtime.jsx("div", {
2482
+ className: "dshfs-field",
2483
+ children: [
2484
+ react_jsx_runtime.jsx("label", {
2485
+ className: "dshfs-platform",
2486
+ children: [
2487
+ react_jsx_runtime.jsx("input", {
2488
+ type: "checkbox",
2489
+ checked: autoRestoreOnDispose,
2490
+ disabled: !ready || saving,
2491
+ onChange: (e) => {
2492
+ setAutoRestoreOnDispose(e.target.checked);
2493
+ setDirty(true);
2494
+ setFailed(false);
2495
+ setSaveError("");
2496
+ },
2497
+ }),
2498
+ t.autoRestoreOnDispose,
2499
+ ],
2500
+ }),
2501
+ react_jsx_runtime.jsx("p", {
2502
+ className: "dshfs-hint",
2503
+ children: t.autoRestoreOnDisposeHint,
2504
+ }),
2505
+ takeoverStatus && takeoverStatus.ran
2506
+ ? react_jsx_runtime.jsx("p", {
2507
+ className: "dshfs-hint" + (takeoverStatus.state === "dangling" ? " dshfs-danger" : ""),
2508
+ children: (takeoverStatus.state === "dangling" ? t.takeoverDangling : takeoverStatus.state === "foreign" ? t.takeoverForeign : t.takeoverOk) +
2509
+ ((takeoverStatus.search && takeoverStatus.search.value) || (takeoverStatus.fetch && takeoverStatus.fetch.value)
2510
+ ? " — " + t.takeoverPinnedBy + ": " +
2511
+ [takeoverStatus.search ? "searchProvider=" + (takeoverStatus.search.value || "-") + " (" + takeoverStatus.search.kind + ")" : "",
2512
+ takeoverStatus.fetch ? "fetchProvider=" + (takeoverStatus.fetch.value || "-") + " (" + takeoverStatus.fetch.kind + ")" : ""]
2513
+ .filter(Boolean).join(", ")
2514
+ : ""),
2515
+ })
2516
+ : null,
2517
+ ],
2518
+ }),
2450
2519
  ] }),
2451
2520
  react_jsx_runtime.jsx(Section, { id: "fetch", title: t.sec_fetch, defaultOpen: false, children: [
2452
2521
  react_jsx_runtime.jsx("div", {
package/lib/index.js CHANGED
@@ -200,6 +200,72 @@ function dedupeSameBilling(engines) {
200
200
  return { kept, dedupedSameBilling };
201
201
  }
202
202
 
203
+ // 接管残留自动回收(0.16.0,上游 #159):本插件历史上写进 web 条配置的全部 provider id。
204
+ // "ddg" = 现行 provider.id;"web-search-free" = dsh-free-search 时代旧 id(改名前装机残留)。
205
+ // 启动自检命中名单即可安全清除(只删自己写过的值,宁可不删不可误删)。
206
+ const OUR_LEGACY_PROVIDER_IDS = ["web-search-free"];
207
+
208
+ // pin 值五分类(纯函数,单测覆盖):absent=未配置 / ours=本插件在用 / shipped=宿主出厂 id /
209
+ // our-legacy=本插件旧 id(可清) / foreign=外部未知 id(只能由调用方按「能否解析到已注册
210
+ // provider」再判 dangling 或第三方占用,绝不自删)
211
+ function classifyPin(value, oursId, shippedIds, legacyIds) {
212
+ if (value === undefined || value === null) return "absent";
213
+ if (value === oursId) return "ours";
214
+ if ((shippedIds ?? []).includes(value)) return "shipped";
215
+ if ((legacyIds ?? []).includes(value)) return "our-legacy";
216
+ return "foreign";
217
+ }
218
+
219
+ // 字段级分类汇总成接管总态(healthCheck/设置页三态):悬空 > 外部占用 > 正常;
220
+ // 第三方已注册的 fetch 占用(kind=foreign)计入 foreign 总态;absent/shipped 归 ok。
221
+ function computeTakeoverState(fields) {
222
+ const kinds = Object.values(fields ?? {}).map((f) => (typeof f === "string" ? f : f && f.kind));
223
+ if (kinds.includes("our-legacy") || kinds.includes("foreign-unregistered")) return "dangling";
224
+ if (kinds.includes("foreign")) return "foreign";
225
+ return "ok";
226
+ }
227
+
228
+ // 回滚决策核心(模块级纯逻辑,依赖全由 opts 注入,便于单测):逐字段仅当
229
+ // getCurrent(field) === 我们写入值才生成 unset;已变更/已不存在的字段只记日志跳过。
230
+ // 有操作 → mutate(主路径);mutate 抛错 → textCleanup(回落);回落也抛 → failed。
231
+ // 本函数不碰任何外部状态;幂等性与快照清理由调用方管理。
232
+ async function rollbackPinnedFields(snapshot, { getCurrent, mutate, textCleanup, log } = {}) {
233
+ const logger = log ?? console;
234
+ const ops = [];
235
+ for (const [field, pinnedValue] of Object.entries(snapshot ?? {})) {
236
+ const value = getCurrent ? getCurrent(field) : undefined;
237
+ if (value === undefined || value === null) {
238
+ logger.info(`union-search: takeover rollback skips ${field} (field already absent, idempotent)`);
239
+ continue;
240
+ }
241
+ if (value !== pinnedValue) {
242
+ logger.info(`union-search: takeover rollback keeps ${field}="${value}" (no longer our pinned "${pinnedValue}", user/third-party choice left intact)`);
243
+ continue;
244
+ }
245
+ ops.push({ op: "unset", path: [field] });
246
+ }
247
+ if (ops.length === 0) return { status: "noop", reason: "no-matching-fields" };
248
+ try {
249
+ await mutate(ops);
250
+ logger.info(`union-search: takeover rolled back via settings unset (${ops.map((o) => o.path.join(".")).join(", ")})`);
251
+ return { status: "api", ops };
252
+ } catch (error) {
253
+ const message = error instanceof Error ? error.message : String(error);
254
+ logger.warn(`union-search: takeover rollback via settings failed (${message}); falling back to patch text cleanup`);
255
+ try {
256
+ const removedCount = await textCleanup();
257
+ logger.info(`union-search: takeover rollback via patch text removed ${removedCount} line(s); restart dsh to apply`);
258
+ return { status: "text", removedCount };
259
+ } catch (error2) {
260
+ logger.warn(
261
+ `union-search: takeover rollback text fallback failed too (${error2 instanceof Error ? error2.message : String(error2)}); ` +
262
+ `run node bin/restore.js --apply manually to clear the dangling web pins`
263
+ );
264
+ return { status: "failed" };
265
+ }
266
+ }
267
+ }
268
+
203
269
  // blockSystemSearch 开关(0.10.0):屏蔽系统自带搜索 = 把出厂的 deepseek-official 引擎
204
270
  // 并入“已禁用”集合,路由/回退链/引擎测试/提示词全部生效。
205
271
  function effectiveDisabledEngines(cfg) {
@@ -3891,7 +3957,7 @@ function toView(descriptor) {
3891
3957
  };
3892
3958
  }
3893
3959
 
3894
- function makeBridgeRoutes(settings, search, testEngine, runEngineTests, getCredentials) {
3960
+ function makeBridgeRoutes(settings, search, testEngine, runEngineTests, getCredentials, takeoverStatus) {
3895
3961
  const allowlisted = () =>
3896
3962
  settings
3897
3963
  .describe({ redactSecrets: true })
@@ -4225,6 +4291,14 @@ function makeBridgeRoutes(settings, search, testEngine, runEngineTests, getCrede
4225
4291
  writeJson(res, 200, await handlers.mutate(body));
4226
4292
  },
4227
4293
  },
4294
+ {
4295
+ kind: "exact",
4296
+ path: `${BRIDGE_PREFIX}/takeover-status`,
4297
+ handler: async (req, res) => {
4298
+ if (!guard(req, res)) return;
4299
+ writeJson(res, 200, typeof takeoverStatus === "function" ? { ok: true, value: takeoverStatus() } : { ok: false, code: "not-wired", message: "takeover status unavailable" });
4300
+ },
4301
+ },
4228
4302
  {
4229
4303
  kind: "exact",
4230
4304
  path: `${BRIDGE_PREFIX}/credentials-status`,
@@ -4384,6 +4458,9 @@ const Config = z.object({
4384
4458
  cacheTtl: z.number().default(5).volatile(), // 缓存时长(分钟),0-5 可配置(使用处再 clamp)
4385
4459
  // 屏蔽系统自带搜索(0.10.0):强制接管 web_search + 把出厂 deepseek-official 引擎移出引擎链
4386
4460
  blockSystemSearch: z.boolean().default(false).volatile(),
4461
+ // 接管残留自动回收(0.16.0,热生效):true=停用插件时自动 unset 本插件写过的 web 钉选 +
4462
+ // 启动自检遗留;false=退回纯手动(bin/restore.js)。卸载场景任何取值都需手跑 restore.js。
4463
+ autoRestoreOnDispose: z.boolean().default(true).volatile(),
4387
4464
  // fetch provider 接管(0.12.0,热生效):开启后注册并钉选 web.fetchProvider = union-search,
4388
4465
  // web_fetch 出口改走本插件抓取栈(ALPN 直连 + 宿主同款 markdown 优化器,kind:text 抢在宿主
4389
4466
  // 「先 2e5 截断再 HTML→MD」之前完成转换)。关闭时 available()=false,完全不参与宿主选择。
@@ -5241,7 +5318,8 @@ function apply(ctx, config) {
5241
5318
  return runEngineTest(engine, query, timeRange);
5242
5319
  },
5243
5320
  (args) => runEngineTests(args),
5244
- getCredentials
5321
+ getCredentials,
5322
+ () => ({ ...takeoverSelfCheck, autoRestore: current().autoRestoreOnDispose !== false, pinned: pinnedSnapshot })
5245
5323
  ).map((route) => sctx.webServer.register(route));
5246
5324
  return () => {
5247
5325
  for (const dispose of disposers) dispose();
@@ -5275,6 +5353,81 @@ function apply(ctx, config) {
5275
5353
  const SHIPPED_METERED_FETCH_ID = "deepseek-fetch-api";
5276
5354
  const FREE_FETCH_ID = "http";
5277
5355
 
5356
+ // ── 接管残留自动回收(0.16.0,上游 #159,dispose 钩子 + 启动自检双保险)──
5357
+ // 根因:rc.2+ 唯一接管通道 settings.mutate 落 cordis.patch.yml(持久),停用/崩溃后悬空。
5358
+ // 宿主探测(0.2.3-alpha.2)证实无非持久化 pin 通道,故在「写」的两端补救:
5359
+ // dispose 时回滚自己写的字段 + 启动时自检遗留。卸载不在覆盖范围(插件代码已不存在)。
5360
+ let pinnedSnapshot = null; // { searchProvider?, fetchProvider? } 只记我们真正写过的值
5361
+ let autoRollbackRegistered = false;
5362
+ let takeoverAutoCleared = false;
5363
+ let takeoverSelfCheck = { ran: false, search: null, fetch: null, state: "ok" };
5364
+ const getRegisteredProviderIds = () => {
5365
+ try {
5366
+ const list = ctx.web && typeof ctx.web.listProviders === "function" ? ctx.web.listProviders() : null;
5367
+ if (!list || typeof list.then === "function") return null; // @Remote 异步形态:本轮不判(留 null=解析未知)
5368
+ const items = Array.isArray(list) ? list : Array.isArray(list.providers) ? list.providers : null;
5369
+ if (!items) return null;
5370
+ return new Set(items.map((p) => (p && typeof p === "object" ? p.id : p)).filter(Boolean).map(String));
5371
+ } catch {
5372
+ return null;
5373
+ }
5374
+ };
5375
+ // 幂等回滚包装:取当前快照,仅当 getCurrent(field) === 我们写入值才 unset;
5376
+ // 主路径 settings.mutate、失败回落 bin/restore.js 文本(逻辑在模块级 rollbackPinnedFields)。
5377
+ // 成功后才推 takeoverAutoCleared / 清空 pinnedSnapshot(重复调用第二次已无快照→noop)。
5378
+ // opts 仅供单测注入 snapshot/getCurrent/mutate/textCleanup/log。
5379
+ const rollbackPinnedConfig = async (opts = {}) => {
5380
+ const explicit = opts.snapshot !== undefined;
5381
+ const snapshot = explicit ? opts.snapshot : pinnedSnapshot;
5382
+ if (!explicit && takeoverAutoCleared) {
5383
+ (opts.log ?? logger).info("union-search: takeover rollback already applied this session, skipped (idempotent)");
5384
+ return { status: "noop", reason: "already-cleared" };
5385
+ }
5386
+ if (!snapshot || Object.keys(snapshot).length === 0) return { status: "noop", reason: "nothing-pinned" };
5387
+ const res = await rollbackPinnedFields(snapshot, {
5388
+ getCurrent: opts.getCurrent ?? ((field) => getWebConfigId(field)),
5389
+ mutate: opts.mutate ?? (async (webOps) => {
5390
+ let settingsSvc;
5391
+ try { settingsSvc = ctx.get("settings"); } catch { settingsSvc = null; }
5392
+ if (!settingsSvc || typeof settingsSvc.mutate !== "function") throw new Error("settings service unavailable");
5393
+ await settingsSvc.mutate("web", webOps);
5394
+ }),
5395
+ textCleanup: opts.textCleanup ?? (async () => {
5396
+ // 回落路径:动态 import 包内 bin/restore.js 的纯函数(加载期零开销),直接清 patch 文本。
5397
+ const here = opts.metaUrl ?? import.meta.url;
5398
+ const { pathToFileURL } = await import("node:url");
5399
+ const libDir = here.slice(0, here.lastIndexOf("/"));
5400
+ const restore = await import(pathToFileURL(libDir + "/../bin/restore.js").href);
5401
+ const files = restore.findPatchFiles(opts.profilesDir ?? path.join(dshHomeDir(), "profiles"));
5402
+ let removedTotal = 0;
5403
+ for (const file of files) {
5404
+ const before = fs.readFileSync(file, "utf8");
5405
+ const { text, removed } = restore.processPatchText(before, { includeFetch: true });
5406
+ if (removed.length > 0) {
5407
+ fs.writeFileSync(file, text);
5408
+ removedTotal += removed.length;
5409
+ }
5410
+ }
5411
+ return removedTotal;
5412
+ }),
5413
+ log: opts.log ?? logger,
5414
+ });
5415
+ if (!explicit && (res.status === "api" || res.status === "text")) {
5416
+ takeoverAutoCleared = true;
5417
+ pinnedSnapshot = null;
5418
+ }
5419
+ return res;
5420
+ };
5421
+ const registerAutoRollback = () => {
5422
+ if (autoRollbackRegistered) return;
5423
+ autoRollbackRegistered = true;
5424
+ ctx.effect(() => () => {
5425
+ void rollbackPinnedConfig({ log: logger }).catch((error) => {
5426
+ logger.warn(`union-search: dispose rollback threw (non-fatal): ${error instanceof Error ? error.message : String(error)}`);
5427
+ });
5428
+ }, "union-search: takeover rollback on dispose");
5429
+ };
5430
+
5278
5431
  ctx.web.registerSearchProvider(provider);
5279
5432
 
5280
5433
  // fetch provider 注册(0.12.0,上游 #161 结构性免疫):把内置 advanceFetch 栈接到宿主
@@ -5404,6 +5557,9 @@ function apply(ctx, config) {
5404
5557
  Promise.resolve(settingsSvc.mutate("web", ops))
5405
5558
  .then(() => {
5406
5559
  logger.info(`union-search: pinned web entry config ${ops.map((o) => `${o.path.join(".")}=${o.value}`).join(", ")}`);
5560
+ // 与 pin 写入成对:只记我们自己写的值,dispose 回滚据此比对(autoRestoreOnDispose 关闭时不登记)
5561
+ for (const o of ops) pinnedSnapshot = { ...(pinnedSnapshot ?? {}), [o.path.join(".")]: o.value };
5562
+ if (current().autoRestoreOnDispose !== false) registerAutoRollback();
5407
5563
  })
5408
5564
  .catch((error) => {
5409
5565
  lastPinnedSignature = "";
@@ -5424,8 +5580,48 @@ function apply(ctx, config) {
5424
5580
  : `union-search: taking over from the default provider "${previous}" as "${provider.id}"`
5425
5581
  );
5426
5582
  };
5583
+ // 启动自检(接管动作之前):只查 rc.2+ 持久化线(旧线 searchProviderId 不落盘无残留)。
5584
+ // 五分类:absent/ours/shipped 静默;foreign 能解析到已注册 provider = 第三方在用,不动;
5585
+ // 解析不到 = 悬空 → ERROR 给修复命令(foreign 不自删,our-legacy 可清)。
5586
+ // 正常态零日志(防启动刷屏)。
5587
+ const runTakeoverSelfCheck = () => {
5588
+ if (typeof ctx.web !== "object" || ctx.web === null) return;
5589
+ if ("searchProviderId" in ctx.web) return;
5590
+ const oursId = provider.id;
5591
+ const registered = getRegisteredProviderIds();
5592
+ const result = {};
5593
+ let dangling = false;
5594
+ for (const [field, shippedIds, ours] of [["searchProvider", SHIPPED_SEARCH_PROVIDER_IDS, oursId], ["fetchProvider", [SHIPPED_METERED_FETCH_ID, FREE_FETCH_ID], "union-search"]]) {
5595
+ const value = getWebConfigId(field);
5596
+ let kind = classifyPin(value, ours, shippedIds, OUR_LEGACY_PROVIDER_IDS);
5597
+ if (kind === "foreign" && registered && !registered.has(value)) kind = "foreign-unregistered";
5598
+ result[field] = { value: value ?? null, kind };
5599
+ if (kind === "our-legacy" || kind === "foreign-unregistered") dangling = true;
5600
+ if (kind === "our-legacy") {
5601
+ if (current().autoRestoreOnDispose !== false) {
5602
+ logger.warn(`union-search: startup self-check found our legacy pin ${field}: "${value}" (from a pre-rename install) - clearing it`);
5603
+ void rollbackPinnedConfig({ snapshot: { [field]: value }, getCurrent: (f) => (f === field ? value : undefined) }).then((r) => {
5604
+ if (r.status === "noop" || r.status === "failed") logger.warn("union-search: legacy pin clear incomplete; run node bin/restore.js --apply manually");
5605
+ });
5606
+ } else {
5607
+ logger.warn(`union-search: startup self-check found our legacy pin ${field}: "${value}" but autoRestoreOnDispose is off - run node bin/restore.js --apply to clear`);
5608
+ }
5609
+ } else if (kind === "foreign-unregistered") {
5610
+ logger.error(
5611
+ `union-search: startup self-check found dangling ${field}: "${value}" (no registered provider answers to this id; ` +
5612
+ `web_search/web_fetch will fail with CONFIGURED_MISSING). If it belongs to another plugin leave it to that owner; ` +
5613
+ `to clear the pin run: node node_modules/dsh-union-search/bin/restore.js --apply (from the profile directory), then restart dsh`
5614
+ );
5615
+ }
5616
+ }
5617
+ takeoverSelfCheck = { ran: true, search: result.searchProvider, fetch: result.fetchProvider, state: computeTakeoverState(result) };
5618
+ };
5619
+
5427
5620
  // [0.10.17] fallback: if inject does not fire (no webServer), try here.
5428
5621
  // Safe: applySearchTakeover early-returns if settings unavailable (0.10.16 guard).
5622
+ try { runTakeoverSelfCheck(); } catch (e) {
5623
+ logger.warn(`union-search: initial takeover self-check error (non-fatal): ${e?.message ?? e}`);
5624
+ }
5429
5625
  try { applySearchTakeover(); } catch (e) {
5430
5626
  logger.warn(`union-search: initial takeover error (non-fatal): ${e?.message ?? e}`);
5431
5627
  }
@@ -6376,6 +6572,10 @@ function apply(ctx, config) {
6376
6572
 
6377
6573
  export {
6378
6574
  ALL_ENGINES,
6575
+ OUR_LEGACY_PROVIDER_IDS,
6576
+ classifyPin,
6577
+ computeTakeoverState,
6578
+ rollbackPinnedFields,
6379
6579
  DEEPSEEK_TOOLS_DEFAULT_ENDPOINT,
6380
6580
  dedupeSameBilling,
6381
6581
  resolveDeepSeekToolsEndpoint,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-union-search",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "Union web search for DeepSeek Harness (renamed from dsh-free-search): free keyless engines + many professional paid search APIs — 28 engines (Bing/DuckDuckGo/AnySearch/SearXNG multi-instance union/Exa/Tavily/Keenable/Firecrawl/Parallel keyless; Zhihu global/site via MCP and Perplexity/SerpBase/Serply/DeepSeek official/You.com/Baidu/Kimi/Aliyun/Doubao/Zhipu/Bocha/Metaso with key; OpenAI/Gemini/Claude/Grok model built-in search, explicit-only) + auto smart routing + global engine enable/disable & fallback priority + multi mode (parallel top-3 merge) + multi_search cross-source tool + failure-aware fallback + block system built-in search toggle + experimental free advance_fetch (no API key, no billing; host-twin GitHub-Flavored Markdown conversion + CSS selector/fields structured extraction) + time filtering + platform search + web_fetch, with web settings UI.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -8,7 +8,7 @@
8
8
  "dsh-union-search-restore": "bin/restore.js"
9
9
  },
10
10
  "scripts": {
11
- "test": "node --test test/md.test.mjs test/egress.test.mjs test/relevance.test.mjs test/upgrade.test.mjs test/alpn.test.mjs test/restore.test.mjs test/fetch-provider.test.mjs test/browser-tier.test.mjs test/deepseek-tools.test.mjs test/credentials.test.mjs test/tool-face.test.mjs test/notes-channel.test.mjs"
11
+ "test": "node --test test/md.test.mjs test/egress.test.mjs test/relevance.test.mjs test/upgrade.test.mjs test/alpn.test.mjs test/restore.test.mjs test/fetch-provider.test.mjs test/browser-tier.test.mjs test/deepseek-tools.test.mjs test/restore-auto.test.mjs test/credentials.test.mjs test/tool-face.test.mjs test/notes-channel.test.mjs"
12
12
  },
13
13
  "exports": {
14
14
  ".": "./lib/index.js",