dsh-free-search 0.9.31 → 0.9.33
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 +12 -3
- package/lib/client.js +171 -1
- package/lib/fetch_provider.js +6 -5
- package/lib/index.js +170 -19
- package/lib/safe_text.js +67 -0
- package/lib/serp_engines.js +5 -2
- package/lib/vertical.js +5 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -33,6 +33,8 @@ dsh 默认的搜索 provider 依赖 DeepSeek 官方 API key(`DEEPSEEK_API_KEY`
|
|
|
33
33
|
- **5 个 HTML 搜索页引擎(默认关闭)** —— 把传统搜索页并入同一套引擎 / 回退 / 冷却 / 设置体系:`baidu-html`(百度网页)、`so360`、`sogou`、`wechat`(微信文章)、`toutiao`。免 key、免额度,代价是抓页面:验证码/反爬按 `bot-wall` 归类并让整个家族冷却 10 分钟(整段出口 IP 都会被打标),结果也没有 API 摘要。它们默认不进 auto / 回退链 / 语言池,只在显式 `engine=` 或加入语言池时运行。
|
|
34
34
|
- **按 key 冷却与诊断** —— 429 与额度错误按 key 分别冷却,同一引擎的其他 key 不受牵连;冷却状态写入磁盘,重启后仍在;失败信息和日志里的 key 一律打码;设置页底部的「诊断」按钮列出每个引擎当前为什么不可用、冷却还剩多久
|
|
35
35
|
- **引擎白名单** —— 设置页「只使用勾选的引擎」开启后,只有勾选的引擎可用,升级新增的引擎默认不启用;配置里对应 `allowedEngines`(非空时等价于把其余引擎全部禁用)
|
|
36
|
+
- **自带更新** —— 卡片底部显示当前版本和「检查更新」;npm 安装的版本可一键升级到 latest,本地 link 开发模式改为跳转 npm 页面并提示 git pull
|
|
37
|
+
- **截断安全** —— 标题和摘要按码点截断,搜索结果、工具输出和 web_fetch 正文在离开插件前统一清除孤立代理;含 emoji 的结果不会再让会话历史出现无法序列化的字符(#108)
|
|
36
38
|
- **网页设置页** —— 引擎切换 + API key 配置(UI 中 key 脱敏显示"已配置")+ 中英文切换;入口在左侧「插件」页的组件行配置(`plugins.row.config`,DSH 0.1.7-rc.1+)。远程访问(VPS / 反向代理 / 自定义域名)下也能用:桥接接口沿用宿主的 Host 围栏,`--trusted-host` 与 `--public-url` 声明的地址会放行(#84)
|
|
37
39
|
- **右侧浮动目录** —— 卡片右侧的页面留白里浮出「引擎 / 回退 / 语言池 / 搜索行为 / 抓取 / 性能 / 提示词管理」七个快捷跳转,滚动自动高亮当前项、点击平滑跳转;不占用正文宽度(正文布局与 0.9.6 一致),右侧留白不足时自动隐藏;每项都是真链接(`#/panel/plugins/dsh-free-search/<分区>`),可复制、可开新标签,见下方「分区链接契约」
|
|
38
40
|
|
|
@@ -537,7 +539,7 @@ Search engine test:
|
|
|
537
539
|
|
|
538
540
|
#### 离线自检断言(tools/)
|
|
539
541
|
|
|
540
|
-
仓库自带 **
|
|
542
|
+
仓库自带 **44 个**零依赖断言脚本(合计 **762 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑:
|
|
541
543
|
|
|
542
544
|
| 脚本 | 覆盖 | 运行(项数) |
|
|
543
545
|
|---|---|---|
|
|
@@ -575,6 +577,9 @@ Search engine test:
|
|
|
575
577
|
| `assert-doctor.mjs` | 诊断报告:时长格式化、头部版本 / Node / DSH 主目录 / 生效默认 / 提示词字数、每个引擎的标记与原因、冷却原因去重列出、提示词未注入的提示 | `node tools/assert-doctor.mjs`(5) |
|
|
576
578
|
| `assert-agy.mjs` | Antigravity CLI:提示词查询 / 条数 / JSON 契约、structuredOutput 与 response 两种信封、非 SUCCESS 透出上游原因、URL 过滤与截断、CLI 参数、注入 runner 跳过 PATH 检查 | `node tools/assert-agy.mjs`(6) |
|
|
577
579
|
| `assert-allowed-engines.mjs` | 引擎白名单(#106):条目归一化、空名单保持原状、非空时禁用其余全部(含未来新增)、显式禁用优先、错拼不锁死搜索、白名单内引擎可入链(HTML 家族 / 按次计费)、auto 只路由白名单、内置提示词只列白名单且回退为 none、schema 默认空 | `node tools/assert-allowed-engines.mjs`(9) |
|
|
580
|
+
| `assert-updater.mjs` | 自带更新:版本比较、registry 探测(成功 / 非 200 / 网络失败返回 null)、安装模式识别(真实安装优先于 link)、客户端按钮与桥接、服务端两条路由与 pnpm 升级命令、卡片版本跟 package.json 一致 | `node tools/assert-updater.mjs`(9) |
|
|
581
|
+
| `assert-inject.mjs` | 旧版 Cordis 兼容(#107):静态 inject 声明 web / settings / tools / systemPrompt、可选服务只走 `ctx.get`、回调上下文的属性读取都在 inject 里、动态依赖列表没有未知服务 | `node tools/assert-inject.mjs`(4) |
|
|
582
|
+
| `assert-safe-text.mjs` | UTF-16 截断安全(#108):孤立高低代理清理、有效代理对保留、码点截断不切开 emoji、`cleanSnippet` 300 边界落在整字符、结果/来源/错误脱敏、web_fetch 各层正文兜底、源码守卫 | `node tools/assert-safe-text.mjs`(9) |
|
|
578
583
|
| `assert-degoog.mjs` | degoog 自建实例(#85):`/api/search` URL 规范化、查询编码、`time`/`lang` 参数、注册表位置、无需凭据 | `node tools/assert-degoog.mjs`(7) |
|
|
579
584
|
| `assert-multikey.mjs` | 多 key 字段:单 key 不变、逗号/分号/换行分隔、空白项丢弃、空输入为空数组 | `node tools/assert-multikey.mjs`(3) |
|
|
580
585
|
| `assert-firecrawl-keyless.mjs` | Firecrawl keyless 出口判定:403 + VPN/proxy 文案才算拒绝、普通 403 与 401/429/500 不算、冷却初始未触发 | `node tools/assert-firecrawl-keyless.mjs`(5) |
|
|
@@ -662,7 +667,8 @@ Adding a section takes three steps: put `data-dsh-section="<new id>"` on the con
|
|
|
662
667
|
- **Time Filtering** — The `advanced_search` tool supports `timeRange`: fixed tiers, custom relative values, or an absolute date (details below)
|
|
663
668
|
- **System Prompt Injection** — The agent is aware of the currently active engine and which engines require API keys; it is also told that all search output is **untrusted external data** and must never be executed as instructions
|
|
664
669
|
- **Prompt-Injection Guard (untrusted-data boundary)** — Web-derived text from the plugin's own tools (`advanced_search` / `platform_search` / `free_search_test`) is wrapped in an explicit `<untrusted-web-content>` boundary (look-alike tags inside the text are stripped to prevent early closure); the core `web_search` / `web_fetch` tools carry DSH core's own notice (`External web content follows...`); every snippet is cleaned and capped at 300 characters
|
|
665
|
-
- **
|
|
670
|
+
- **Built-in updater** — the card footer shows the version and a Check update button; npm installs upgrade to latest in one click, while a local link install links to the npm page and points at git pull instead
|
|
671
|
+
- **Truncation safety** — titles and snippets are cut by code point, and search results, tool output and web_fetch bodies are stripped of lone surrogates before leaving the plugin; an emoji can no longer make history unserializable (#108)
|
|
666
672
|
- **Result Caching** — Identical queries (same engine / time-filter args) hit an LRU cache (50 entries) for up to 5 minutes, protecting free engines from rate-limiting and saving paid quota; the TTL is configurable from 0-5 minutes in the settings UI (0 disables caching)
|
|
667
673
|
- **Domain blocklist & safe search** — `blockedDomains` keeps matching domains out of every result; `safeSearch` (`off` / `moderate` / `strict`) adds a filter layer for Bing / DuckDuckGo
|
|
668
674
|
- **Visual Badges** — Free engines feature a green `FREE` badge, while paid engines show an orange `API KEY` badge in the settings UI
|
|
@@ -1139,7 +1145,7 @@ Restart `dsh web` after switching to apply changes.
|
|
|
1139
1145
|
|
|
1140
1146
|
#### Offline self-check assertions (`tools/`)
|
|
1141
1147
|
|
|
1142
|
-
**Forty-
|
|
1148
|
+
**Forty-four** zero-dependency assertion scripts ship with the repo (**762 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20:
|
|
1143
1149
|
|
|
1144
1150
|
| Script | Covers | Run (count) |
|
|
1145
1151
|
|---|---|---|
|
|
@@ -1177,6 +1183,9 @@ Restart `dsh web` after switching to apply changes.
|
|
|
1177
1183
|
| `assert-doctor.mjs` | Doctor report: duration formatting, version / Node / DSH home / effective default / prompt size header, a mark and reason per engine, cooldown reasons listed once, a warning when the prompt is not injected | `node tools/assert-doctor.mjs` (5) |
|
|
1178
1184
|
| `assert-agy.mjs` | Antigravity CLI: query / cap / JSON contract in the prompt, structuredOutput and response envelopes, upstream reason on non-SUCCESS, URL filtering and truncation, CLI flags, injected runner skips the PATH check | `node tools/assert-agy.mjs` (6) |
|
|
1179
1185
|
| `assert-allowed-engines.mjs` | Engine whitelist (#106): entries normalised, an empty list changes nothing, a non-empty list disables everything else (including future engines), explicit disables win, a typo does not brick search, whitelisted engines join the chain (HTML family / billed), Auto only routes allowed engines, the built-in prompt lists only them with a none fallback, and the schema defaults to empty | `node tools/assert-allowed-engines.mjs` (9) |
|
|
1186
|
+
| `assert-updater.mjs` | Built-in updater: version comparison, registry probe (success / non-200 / network failure yields null), install-mode detection (a real install beats a link), the client button and bridge helper, both server routes with the pnpm upgrade command, and the card version matching package.json | `node tools/assert-updater.mjs` (9) |
|
|
1187
|
+
| `assert-inject.mjs` | Older Cordis compatibility (#107): the static inject list declares web / settings / tools / systemPrompt, optional services are read through `ctx.get`, every property read on a callback context is declared, and dynamic dependency lists contain no unknown services | `node tools/assert-inject.mjs` (4) |
|
|
1188
|
+
| `assert-safe-text.mjs` | UTF-16 truncation safety (#108): lone high/low surrogates replaced, valid pairs kept, code-point slicing never splits an emoji, `cleanSnippet`'s 300 boundary lands on a whole character, results/sources/errors sanitized, every web_fetch tier covered, plus source guards | `node tools/assert-safe-text.mjs` (9) |
|
|
1180
1189
|
| `assert-degoog.mjs` | degoog self-hosted instance (#85): `/api/search` URL normalisation, query encoding, `time`/`lang` parameters, registry placement, no credentials needed | `node tools/assert-degoog.mjs` (7) |
|
|
1181
1190
|
| `assert-multikey.mjs` | multi-key fields: a single key is unchanged, comma/semicolon/newline separate keys, blank entries are dropped, empty input yields none | `node tools/assert-multikey.mjs` (3) |
|
|
1182
1191
|
| `assert-firecrawl-keyless.mjs` | Firecrawl keyless egress refusal: only a 403 with the VPN/proxy wording counts, plain 403 and 401/429/500 do not, and the cooldown starts inactive | `node tools/assert-firecrawl-keyless.mjs` (5) |
|
package/lib/client.js
CHANGED
|
@@ -272,6 +272,17 @@ window.__ModuleLoader__.load({
|
|
|
272
272
|
".dshfs-update{color:#cc7a00;flex:none;font-size:12px;white-space:nowrap;border:1px solid rgba(255,149,0,.3);background:rgba(255,149,0,.12);border-radius:999px;padding:2px 8px}",
|
|
273
273
|
"@media (prefers-color-scheme: dark){.dshfs-update{color:#ff9f0a}}",
|
|
274
274
|
".dshfs-updateLine{display:flex;align-items:center;gap:10px;flex-wrap:wrap}",
|
|
275
|
+
".dshfs-upgrade{border:1px solid rgba(52,199,89,.4);background:rgba(52,199,89,.15);color:#248a3d}",
|
|
276
|
+
"@media (prefers-color-scheme: dark){.dshfs-upgrade{color:#30d158}}",
|
|
277
|
+
".dshfs-upgrade:hover:not(:disabled){background:rgba(52,199,89,.25)}",
|
|
278
|
+
".dshfs-updateOk{color:#248a3d;flex:none;font-size:12px;white-space:nowrap;border:1px solid rgba(52,199,89,.3);background:rgba(52,199,89,.12);border-radius:999px;padding:2px 8px}",
|
|
279
|
+
"@media (prefers-color-scheme: dark){.dshfs-updateOk{color:#30d158}}",
|
|
280
|
+
".dshfs-updatePill{display:inline-flex;align-items:center;gap:6px;border:1px solid rgba(0,113,227,.2);background:rgba(0,113,227,.1);color:#0071e3;font:inherit;font-size:13px;font-weight:500;line-height:1;cursor:pointer;padding:6px 12px;border-radius:999px;text-decoration:none;white-space:nowrap;transition:all 180ms cubic-bezier(.4,0,.2,1)}",
|
|
281
|
+
"@media (prefers-color-scheme: dark){.dshfs-updatePill{color:#0a84ff;background:rgba(10,132,255,.15);border-color:rgba(10,132,255,.25)}}",
|
|
282
|
+
".dshfs-updatePill:hover:not(:disabled){background:rgba(0,113,227,.15);border-color:rgba(0,113,227,.3)}",
|
|
283
|
+
"@media (prefers-color-scheme: dark){.dshfs-updatePill:hover:not(:disabled){background:rgba(10,132,255,.2);border-color:rgba(10,132,255,.4)}}",
|
|
284
|
+
".dshfs-updatePill:disabled{opacity:.5;cursor:default}",
|
|
285
|
+
".dshfs-updateIcon{flex:none;display:block}",
|
|
275
286
|
".dshfs-version{color:#6e6e73;font-size:12px;font-variant-numeric:tabular-nums;white-space:nowrap}",
|
|
276
287
|
"@media (prefers-color-scheme: dark){.dshfs-version{color:#a1a1a6}}"
|
|
277
288
|
].join("");
|
|
@@ -385,6 +396,18 @@ window.__ModuleLoader__.load({
|
|
|
385
396
|
testOk: (r) => `✓ ${r.count} 条结果(引擎: ${r.engine})${r.content ? ` — ${r.content}` : ""}${r.sample ? ` · 例如 "${r.sample.slice(0, 40)}"` : ""}`,
|
|
386
397
|
testFail: (e) => `✗ ${e}`,
|
|
387
398
|
toggleLang: "EN",
|
|
399
|
+
checkUpdate: "检查更新",
|
|
400
|
+
checkingUpdate: "检查中…",
|
|
401
|
+
updateAvailable: (c, l) => `发现新版本 v${l}(当前 v${c})`,
|
|
402
|
+
updateLatest: (c) => `已是最新版本 v${c}`,
|
|
403
|
+
updateCheckFailed: "检查更新失败(无法访问 npm registry)",
|
|
404
|
+
updateView: "查看 →",
|
|
405
|
+
hasUpdate: "有更新",
|
|
406
|
+
upgrade: "升级",
|
|
407
|
+
upgrading: "升级中…",
|
|
408
|
+
upgradeLinkMode: "(本地开发模式,升级请用 git pull)",
|
|
409
|
+
upgradeDone: (l) => `升级到 v${l} 完成,重启 dsh 后生效`,
|
|
410
|
+
upgradeFailed: (m) => `升级失败:${m}`,
|
|
388
411
|
safeSearchLabel: "安全搜索过滤 (adlt)",
|
|
389
412
|
safeSearchOff: "关闭 —— 引擎默认(不加参数)",
|
|
390
413
|
safeSearchModerate: "中等 —— Bing 默认",
|
|
@@ -521,6 +544,18 @@ window.__ModuleLoader__.load({
|
|
|
521
544
|
testOk: (r) => `✓ ${r.count} results (engine: ${r.engine})${r.content ? ` — ${r.content}` : ""}${r.sample ? ` · e.g. "${r.sample.slice(0, 40)}"` : ""}`,
|
|
522
545
|
testFail: (e) => `✗ ${e}`,
|
|
523
546
|
toggleLang: "中文",
|
|
547
|
+
checkUpdate: "Check update",
|
|
548
|
+
checkingUpdate: "Checking…",
|
|
549
|
+
updateAvailable: (c, l) => `New version v${l} available (current v${c})`,
|
|
550
|
+
updateLatest: (c) => `You're on the latest version v${c}`,
|
|
551
|
+
updateCheckFailed: "Update check failed (cannot reach npm registry)",
|
|
552
|
+
updateView: "View →",
|
|
553
|
+
hasUpdate: "Update available",
|
|
554
|
+
upgrade: "Upgrade",
|
|
555
|
+
upgrading: "Upgrading…",
|
|
556
|
+
upgradeLinkMode: "(local dev install - use git pull to update)",
|
|
557
|
+
upgradeDone: (l) => `Upgraded to v${l} - restart dsh to apply`,
|
|
558
|
+
upgradeFailed: (m) => `Upgrade failed: ${m}`,
|
|
524
559
|
safeSearchLabel: "Safe search filter (adlt)",
|
|
525
560
|
safeSearchOff: "Off - engine default (no filtering)",
|
|
526
561
|
safeSearchModerate: "Moderate - Bing default",
|
|
@@ -578,7 +613,7 @@ window.__ModuleLoader__.load({
|
|
|
578
613
|
"cache_search",
|
|
579
614
|
"domain_search",
|
|
580
615
|
];
|
|
581
|
-
const PLUGIN_VERSION = "0.9.
|
|
616
|
+
const PLUGIN_VERSION = "0.9.33";
|
|
582
617
|
const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
|
|
583
618
|
// 右侧浮动目录(#85):条目顺序即页面顺序,anchor 是页面里对应 field 的 id。
|
|
584
619
|
const NAV_ITEMS = [
|
|
@@ -709,6 +744,15 @@ window.__ModuleLoader__.load({
|
|
|
709
744
|
return { domains, stats };
|
|
710
745
|
};
|
|
711
746
|
|
|
747
|
+
async function bridgeCheckUpdate() {
|
|
748
|
+
const response = await fetch(`${BRIDGE_PREFIX}/check-update`, {
|
|
749
|
+
method: "POST",
|
|
750
|
+
headers: { "content-type": "application/json" },
|
|
751
|
+
body: "{}",
|
|
752
|
+
});
|
|
753
|
+
return response.json();
|
|
754
|
+
}
|
|
755
|
+
|
|
712
756
|
// 诊断文本由服务端拼好,客户端只负责显示。
|
|
713
757
|
async function bridgeDoctor() {
|
|
714
758
|
const response = await fetch(`${BRIDGE_PREFIX}/doctor`, {
|
|
@@ -897,6 +941,9 @@ window.__ModuleLoader__.load({
|
|
|
897
941
|
const [saveError, setSaveError] = react.useState("");
|
|
898
942
|
const [testing, setTesting] = react.useState(false);
|
|
899
943
|
const [testResult, setTestResult] = react.useState(null);
|
|
944
|
+
const [checkingUpdate, setCheckingUpdate] = react.useState(false);
|
|
945
|
+
const [upgrading, setUpgrading] = react.useState(false);
|
|
946
|
+
const [updateInfo, setUpdateInfo] = react.useState(null);
|
|
900
947
|
const [doctorText, setDoctorText] = react.useState("");
|
|
901
948
|
const [doctorRunning, setDoctorRunning] = react.useState(false);
|
|
902
949
|
// 回退优先级/池列表行内 key 输入:引擎 id → [当前值, setter](zhihu 两引擎共享 ZHIHU_API_KEY)
|
|
@@ -1195,6 +1242,49 @@ window.__ModuleLoader__.load({
|
|
|
1195
1242
|
setSaveError("");
|
|
1196
1243
|
};
|
|
1197
1244
|
|
|
1245
|
+
const runCheckUpdate = async () => {
|
|
1246
|
+
setCheckingUpdate(true);
|
|
1247
|
+
setUpdateInfo(null);
|
|
1248
|
+
setFailed(false);
|
|
1249
|
+
setSaveError("");
|
|
1250
|
+
try {
|
|
1251
|
+
const result = await bridgeCheckUpdate();
|
|
1252
|
+
if (result.ok && result.value && typeof result.value.current === "string" && typeof result.value.latest === "string") {
|
|
1253
|
+
setUpdateInfo({ ok: true, ...result.value });
|
|
1254
|
+
} else {
|
|
1255
|
+
setUpdateInfo({ ok: false });
|
|
1256
|
+
}
|
|
1257
|
+
} catch {
|
|
1258
|
+
setUpdateInfo({ ok: false });
|
|
1259
|
+
} finally {
|
|
1260
|
+
setCheckingUpdate(false);
|
|
1261
|
+
}
|
|
1262
|
+
};
|
|
1263
|
+
|
|
1264
|
+
const runUpdate = async () => {
|
|
1265
|
+
setUpgrading(true);
|
|
1266
|
+
setUpdateInfo(null);
|
|
1267
|
+
setFailed(false);
|
|
1268
|
+
setSaveError("");
|
|
1269
|
+
try {
|
|
1270
|
+
const response = await fetch(`${BRIDGE_PREFIX}/update`, {
|
|
1271
|
+
method: "POST",
|
|
1272
|
+
headers: { "content-type": "application/json" },
|
|
1273
|
+
body: "{}",
|
|
1274
|
+
});
|
|
1275
|
+
const result = await response.json();
|
|
1276
|
+
if (result.ok) {
|
|
1277
|
+
setUpdateInfo({ ok: true, hasUpdate: false, upgraded: true, message: result.value.message, latest: result.value.latest });
|
|
1278
|
+
} else {
|
|
1279
|
+
setUpdateInfo({ ok: false, upgradeFailed: result.message ?? "upgrade failed" });
|
|
1280
|
+
}
|
|
1281
|
+
} catch {
|
|
1282
|
+
setUpdateInfo({ ok: false, upgradeFailed: "request failed" });
|
|
1283
|
+
} finally {
|
|
1284
|
+
setUpgrading(false);
|
|
1285
|
+
}
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1198
1288
|
const runDoctor = async () => {
|
|
1199
1289
|
setDoctorRunning(true);
|
|
1200
1290
|
setDoctorText("");
|
|
@@ -2404,6 +2494,86 @@ react_jsx_runtime.jsx("div", {
|
|
|
2404
2494
|
className: "dshfs-footerLeft",
|
|
2405
2495
|
children: [
|
|
2406
2496
|
react_jsx_runtime.jsx("span", { className: "dshfs-version", children: "v" + PLUGIN_VERSION }),
|
|
2497
|
+
updateInfo && updateInfo.ok && updateInfo.hasUpdate && !updateInfo.installable
|
|
2498
|
+
? react_jsx_runtime.jsx("a", {
|
|
2499
|
+
className: "dshfs-updatePill",
|
|
2500
|
+
href: updateInfo.updateUrl,
|
|
2501
|
+
target: "_blank",
|
|
2502
|
+
rel: "noopener noreferrer",
|
|
2503
|
+
title: t.updateAvailable(updateInfo.current, updateInfo.latest),
|
|
2504
|
+
children: [
|
|
2505
|
+
react_jsx_runtime.jsx("svg", {
|
|
2506
|
+
className: "dshfs-updateIcon",
|
|
2507
|
+
viewBox: "0 0 16 16",
|
|
2508
|
+
width: 14,
|
|
2509
|
+
height: 14,
|
|
2510
|
+
"aria-hidden": "true",
|
|
2511
|
+
children: react_jsx_runtime.jsx("path", {
|
|
2512
|
+
d: "M8 2.2v6.4M5.2 6.4 8 9.2l2.8-2.8M3 10.8v1.4c0 .9.7 1.6 1.6 1.6h6.8c.9 0 1.6-.7 1.6-1.6v-1.4",
|
|
2513
|
+
fill: "none",
|
|
2514
|
+
stroke: "currentColor",
|
|
2515
|
+
strokeWidth: 1.6,
|
|
2516
|
+
strokeLinecap: "round",
|
|
2517
|
+
strokeLinejoin: "round",
|
|
2518
|
+
}),
|
|
2519
|
+
}),
|
|
2520
|
+
t.hasUpdate,
|
|
2521
|
+
],
|
|
2522
|
+
})
|
|
2523
|
+
: react_jsx_runtime.jsx("button", {
|
|
2524
|
+
className: "dshfs-updatePill",
|
|
2525
|
+
type: "button",
|
|
2526
|
+
title: updateInfo && updateInfo.ok && updateInfo.hasUpdate ? t.updateAvailable(updateInfo.current, updateInfo.latest) : undefined,
|
|
2527
|
+
onClick: updateInfo && updateInfo.ok && updateInfo.hasUpdate ? runUpdate : runCheckUpdate,
|
|
2528
|
+
disabled: upgrading || checkingUpdate || saving || !ready,
|
|
2529
|
+
children: [
|
|
2530
|
+
react_jsx_runtime.jsx("svg", {
|
|
2531
|
+
className: "dshfs-updateIcon",
|
|
2532
|
+
viewBox: "0 0 16 16",
|
|
2533
|
+
width: 14,
|
|
2534
|
+
height: 14,
|
|
2535
|
+
"aria-hidden": "true",
|
|
2536
|
+
children: react_jsx_runtime.jsx("path", {
|
|
2537
|
+
d: "M8 2.2v6.4M5.2 6.4 8 9.2l2.8-2.8M3 10.8v1.4c0 .9.7 1.6 1.6 1.6h6.8c.9 0 1.6-.7 1.6-1.6v-1.4",
|
|
2538
|
+
fill: "none",
|
|
2539
|
+
stroke: "currentColor",
|
|
2540
|
+
strokeWidth: 1.6,
|
|
2541
|
+
strokeLinecap: "round",
|
|
2542
|
+
strokeLinejoin: "round",
|
|
2543
|
+
}),
|
|
2544
|
+
}),
|
|
2545
|
+
upgrading
|
|
2546
|
+
? t.upgrading
|
|
2547
|
+
: checkingUpdate
|
|
2548
|
+
? t.checkingUpdate
|
|
2549
|
+
: updateInfo && updateInfo.ok && updateInfo.hasUpdate
|
|
2550
|
+
? t.hasUpdate
|
|
2551
|
+
: t.checkUpdate,
|
|
2552
|
+
],
|
|
2553
|
+
}),
|
|
2554
|
+
updateInfo && updateInfo.ok
|
|
2555
|
+
? updateInfo.upgraded
|
|
2556
|
+
? react_jsx_runtime.jsx("span", {
|
|
2557
|
+
className: "dshfs-updateOk",
|
|
2558
|
+
children: t.upgradeDone(updateInfo.latest),
|
|
2559
|
+
})
|
|
2560
|
+
: updateInfo.hasUpdate
|
|
2561
|
+
? updateInfo.installable
|
|
2562
|
+
? null
|
|
2563
|
+
: react_jsx_runtime.jsx("span", {
|
|
2564
|
+
className: "dshfs-version",
|
|
2565
|
+
children: t.upgradeLinkMode,
|
|
2566
|
+
})
|
|
2567
|
+
: react_jsx_runtime.jsx("span", {
|
|
2568
|
+
className: "dshfs-updateOk",
|
|
2569
|
+
children: t.updateLatest(updateInfo.current),
|
|
2570
|
+
})
|
|
2571
|
+
: updateInfo && !updateInfo.ok
|
|
2572
|
+
? react_jsx_runtime.jsx("span", {
|
|
2573
|
+
className: "dshfs-failed",
|
|
2574
|
+
children: updateInfo.upgradeFailed ? t.upgradeFailed(updateInfo.upgradeFailed) : t.updateCheckFailed,
|
|
2575
|
+
})
|
|
2576
|
+
: null,
|
|
2407
2577
|
|
|
2408
2578
|
],
|
|
2409
2579
|
}),
|
package/lib/fetch_provider.js
CHANGED
|
@@ -12,6 +12,7 @@ import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
|
12
12
|
import { tmpdir } from "node:os";
|
|
13
13
|
import { join } from "node:path";
|
|
14
14
|
import { callExa, callFirecrawl, callCrawl4ai } from "./fetch_upstream.js";
|
|
15
|
+
import { stripLoneSurrogates } from "./safe_text.js";
|
|
15
16
|
|
|
16
17
|
const T1_MIN_CHARS = 300;
|
|
17
18
|
const TEXTUAL = /text\/|json|xml|javascript|application\/json/i;
|
|
@@ -308,7 +309,7 @@ export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = ()
|
|
|
308
309
|
try {
|
|
309
310
|
const r = await httpsGetFollow(url, { headers: browserishHeaders(acceptLanguage()), signal });
|
|
310
311
|
if (r.status < 400 && TEXTUAL.test(r.contentType) && r.text.length >= T1_MIN_CHARS) {
|
|
311
|
-
return { url: r.url, statusCode: r.status, body: { kind: "html", content: r.text }, truncated: false };
|
|
312
|
+
return { url: r.url, statusCode: r.status, body: { kind: "html", content: stripLoneSurrogates(r.text) }, truncated: false };
|
|
312
313
|
}
|
|
313
314
|
if (r.status >= 400) errors.push(`direct HTTP ${r.status}`);
|
|
314
315
|
else errors.push(`direct: ${r.contentType || "unknown type"} ${r.text.length}B`);
|
|
@@ -320,7 +321,7 @@ export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = ()
|
|
|
320
321
|
try {
|
|
321
322
|
const html = await browserDumpDom(browserPath, url, { signal });
|
|
322
323
|
if (html && html.length >= T1_MIN_CHARS && !/403 Forbidden|\bcaptcha\b/i.test(html.slice(0, 3000))) {
|
|
323
|
-
return { url, statusCode: 200, body: { kind: "html", content: html }, truncated: false };
|
|
324
|
+
return { url, statusCode: 200, body: { kind: "html", content: stripLoneSurrogates(html) }, truncated: false };
|
|
324
325
|
}
|
|
325
326
|
errors.push(html ? `browser: short or challenge page (${html.length}B)` : "browser: no output (timeout or launch failure)");
|
|
326
327
|
} catch (e) {
|
|
@@ -333,7 +334,7 @@ export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = ()
|
|
|
333
334
|
if (exaKey) {
|
|
334
335
|
try {
|
|
335
336
|
const text = await callExa(url, exaKey, signal);
|
|
336
|
-
if (text.trim().length >= T1_MIN_CHARS) return { url, statusCode: 200, body: { kind: "text", content: text }, truncated: false };
|
|
337
|
+
if (text.trim().length >= T1_MIN_CHARS) return { url, statusCode: 200, body: { kind: "text", content: stripLoneSurrogates(text) }, truncated: false };
|
|
337
338
|
errors.push("exa: short content");
|
|
338
339
|
} catch (e) { errors.push(`exa: ${e.message}`); }
|
|
339
340
|
}
|
|
@@ -342,7 +343,7 @@ export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = ()
|
|
|
342
343
|
if (firecrawlKey) {
|
|
343
344
|
try {
|
|
344
345
|
const md = await callFirecrawl(url, firecrawlKey, signal);
|
|
345
|
-
if (md.trim().length >= T1_MIN_CHARS) return { url, statusCode: 200, body: { kind: "text", content: md }, truncated: false };
|
|
346
|
+
if (md.trim().length >= T1_MIN_CHARS) return { url, statusCode: 200, body: { kind: "text", content: stripLoneSurrogates(md) }, truncated: false };
|
|
346
347
|
errors.push("firecrawl: short content");
|
|
347
348
|
} catch (e) { errors.push(`firecrawl: ${e.message}`); }
|
|
348
349
|
}
|
|
@@ -351,7 +352,7 @@ export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = ()
|
|
|
351
352
|
if (crawl4aiKey) {
|
|
352
353
|
try {
|
|
353
354
|
const text = await callCrawl4ai(url, crawl4aiKey, signal);
|
|
354
|
-
if (text.trim().length >= T1_MIN_CHARS) return { url, statusCode: 200, body: { kind: "text", content: text }, truncated: false };
|
|
355
|
+
if (text.trim().length >= T1_MIN_CHARS) return { url, statusCode: 200, body: { kind: "text", content: stripLoneSurrogates(text) }, truncated: false };
|
|
355
356
|
errors.push("crawl4ai: short content");
|
|
356
357
|
} catch (e) { errors.push(`crawl4ai: ${e.message}`); }
|
|
357
358
|
}
|
package/lib/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import z from "@deepseek-ai/schemastery";
|
|
|
4
4
|
import fs from "node:fs";
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import path from "node:path";
|
|
7
|
-
import { execFile } from "node:child_process";
|
|
7
|
+
import { exec, execFile } from "node:child_process";
|
|
8
8
|
import { mcpCall, mcpContentText, parseMcpResponseText } from "./mcp_adapter.js";
|
|
9
9
|
import { registerResearchTool } from "./research.js";
|
|
10
10
|
import { registerDomainSearchTool } from "./vertical.js";
|
|
@@ -16,6 +16,7 @@ import { selectEngines, planTopUp, resolveMinSources, describeTarget, credential
|
|
|
16
16
|
import { promptLanguageOf, systemCopy, toolDescription, toolParam, localizedEffect, effectivePromptText, normalizePromptPages, PROMPT_SEGMENTS } from "./prompt_i18n.js";
|
|
17
17
|
import { SERP_ENGINE_IDS, SERP_FAMILY, SERP_TIME_ENGINES, searchSerpEngine } from "./serp_engines.js";
|
|
18
18
|
import { createCooldownStore, cooldownDelayFor, isRegionLocked, keyCooldownId, SESSION, SHORT_COOLDOWN_MS } from "./cooldown.js";
|
|
19
|
+
import { stripLoneSurrogates, truncateText, sanitizeSource, sanitizeSources, sanitizeSearchResult, sanitizeError } from "./safe_text.js";
|
|
19
20
|
import { rememberSecret, redactSecrets, environmentSecrets } from "./redact.js";
|
|
20
21
|
import { buildDoctorReport } from "./doctor.js";
|
|
21
22
|
import { searchAgy, agyAvailable } from "./agy.js";
|
|
@@ -526,6 +527,63 @@ function routeEngines(query, { timeRange, disabledEngines = [], fallbackOrder =
|
|
|
526
527
|
|
|
527
528
|
|
|
528
529
|
|
|
530
|
+
const NPM_REGISTRY_URL = "https://registry.npmjs.org/dsh-free-search/latest";
|
|
531
|
+
const PLUGIN_NPM_URL = "https://www.npmjs.com/package/dsh-free-search";
|
|
532
|
+
const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
|
|
533
|
+
|
|
534
|
+
// 查询 npm registry 的最新版本;失败返回 null(网络/代理问题不阻塞设置页)
|
|
535
|
+
async function fetchLatestVersion(signal) {
|
|
536
|
+
const controller = new AbortController();
|
|
537
|
+
const timer = setTimeout(() => controller.abort(), 10000);
|
|
538
|
+
const onAbort = () => controller.abort();
|
|
539
|
+
signal?.addEventListener("abort", onAbort);
|
|
540
|
+
try {
|
|
541
|
+
const response = await fetch(NPM_REGISTRY_URL, {
|
|
542
|
+
headers: { accept: "application/json", "user-agent": "deepseek-harness/free-search" },
|
|
543
|
+
signal: controller.signal,
|
|
544
|
+
});
|
|
545
|
+
if (!response.ok) return null;
|
|
546
|
+
const data = await response.json();
|
|
547
|
+
return typeof data.version === "string" ? data.version : null;
|
|
548
|
+
} catch {
|
|
549
|
+
return null;
|
|
550
|
+
} finally {
|
|
551
|
+
clearTimeout(timer);
|
|
552
|
+
signal?.removeEventListener("abort", onAbort);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// 简单 semver 比较(只处理 x.y.z,忽略预发布标签):a>b 返回 1,a<b 返回 -1,相等 0
|
|
557
|
+
function compareVersions(a, b) {
|
|
558
|
+
const na = String(a).split(".").map((n) => parseInt(n, 10) || 0);
|
|
559
|
+
const nb = String(b).split(".").map((n) => parseInt(n, 10) || 0);
|
|
560
|
+
for (let i = 0; i < 3; i++) {
|
|
561
|
+
if ((na[i] ?? 0) > (nb[i] ?? 0)) return 1;
|
|
562
|
+
if ((na[i] ?? 0) < (nb[i] ?? 0)) return -1;
|
|
563
|
+
}
|
|
564
|
+
return 0;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// 安装模式:profiles/*/node_modules/dsh-free-search 是符号链接(link: 本地开发)还是真实安装。
|
|
568
|
+
// 真实安装优先:有一个 profile 是 npm 安装的,就升级那一份;全是 link 才按本地开发处理。
|
|
569
|
+
function detectInstallMode(root = path.join(dshHomeDir(), "profiles")) {
|
|
570
|
+
let linked = null;
|
|
571
|
+
try {
|
|
572
|
+
for (const name of fs.readdirSync(root)) {
|
|
573
|
+
const pkgPath = path.join(root, name, "node_modules", "dsh-free-search");
|
|
574
|
+
if (!fs.existsSync(pkgPath)) continue;
|
|
575
|
+
let isLink = false;
|
|
576
|
+
try {
|
|
577
|
+
isLink = fs.lstatSync(pkgPath).isSymbolicLink();
|
|
578
|
+
} catch {}
|
|
579
|
+
const entry = { profileDir: path.join(root, name), isLink };
|
|
580
|
+
if (!isLink) return entry;
|
|
581
|
+
if (linked === null) linked = entry;
|
|
582
|
+
}
|
|
583
|
+
} catch {}
|
|
584
|
+
return linked;
|
|
585
|
+
}
|
|
586
|
+
|
|
529
587
|
// time_range 支持:固定档 day/week/month/year,或自定义(相对 12h/3d/2mo/1y、绝对 YYYY-MM-DD)
|
|
530
588
|
const TIME_RANGES = ["day", "week", "month", "year"];
|
|
531
589
|
const DAYS_BY_RANGE = { day: 1, week: 7, month: 30, year: 365 };
|
|
@@ -609,12 +667,13 @@ const SNIPPET_NOISE =
|
|
|
609
667
|
|
|
610
668
|
function cleanSnippet(text, max = 300) {
|
|
611
669
|
if (!text) return text;
|
|
612
|
-
|
|
670
|
+
const cleaned = String(text)
|
|
613
671
|
.replace(SNIPPET_NOISE, " ")
|
|
614
672
|
.replace(/^\s*(#{1,6}\s*|\[\s*x?\s*\]\s*|-\s*\[\s*x?\s*\]\s*|>\s*)/gm, " ")
|
|
615
673
|
.replace(/\s+/g, " ")
|
|
616
|
-
.trim()
|
|
617
|
-
|
|
674
|
+
.trim();
|
|
675
|
+
// #108: cut by code point, never through a surrogate pair
|
|
676
|
+
return truncateText(cleaned, max);
|
|
618
677
|
}
|
|
619
678
|
|
|
620
679
|
// 各引擎的摘要展示上限:豆包搜索返回的是千字级 Summary(实测 1300-1800 字),放宽到 2000;
|
|
@@ -640,7 +699,10 @@ function stripBoundaryTags(text) {
|
|
|
640
699
|
}
|
|
641
700
|
|
|
642
701
|
function wrapUntrustedBlock(text) {
|
|
643
|
-
|
|
702
|
+
// #108: engine text can carry a lone surrogate after UTF-16 truncation; strip it
|
|
703
|
+
// once here so every wrapped tool output is safe to put into session history.
|
|
704
|
+
const safe = stripLoneSurrogates(typeof text === "string" ? text : String(text ?? ""));
|
|
705
|
+
return `${UNTRUSTED_BOUNDARY_OPEN}\n${stripBoundaryTags(safe)}\n${UNTRUSTED_BOUNDARY_CLOSE}`;
|
|
644
706
|
}
|
|
645
707
|
|
|
646
708
|
function stripTags(html) {
|
|
@@ -675,7 +737,7 @@ function uniqueSources(sources, limit) {
|
|
|
675
737
|
}
|
|
676
738
|
if (out.length >= limit) break;
|
|
677
739
|
}
|
|
678
|
-
return out;
|
|
740
|
+
return out.map(sanitizeSource);
|
|
679
741
|
}
|
|
680
742
|
|
|
681
743
|
async function fetchHtml(url, signal, acceptLang) {
|
|
@@ -3497,6 +3559,65 @@ function makeBridgeRoutes(settings, search, testEngine, getCredentials, getConfi
|
|
|
3497
3559
|
.map((descriptor) => String(descriptor.ns));
|
|
3498
3560
|
|
|
3499
3561
|
const handlers = {
|
|
3562
|
+
async checkUpdate() {
|
|
3563
|
+
const latest = await fetchLatestVersion();
|
|
3564
|
+
if (latest === null) {
|
|
3565
|
+
return {
|
|
3566
|
+
ok: false,
|
|
3567
|
+
code: "update-check-failed",
|
|
3568
|
+
message: "could not reach the npm registry (network/proxy) - check your connection",
|
|
3569
|
+
};
|
|
3570
|
+
}
|
|
3571
|
+
const cmp = compareVersions(latest, PACKAGE_VERSION);
|
|
3572
|
+
const mode = detectInstallMode();
|
|
3573
|
+
return {
|
|
3574
|
+
ok: true,
|
|
3575
|
+
value: {
|
|
3576
|
+
current: PACKAGE_VERSION,
|
|
3577
|
+
latest,
|
|
3578
|
+
hasUpdate: cmp > 0,
|
|
3579
|
+
updateUrl: PLUGIN_NPM_URL,
|
|
3580
|
+
repoUrl: PLUGIN_REPO_URL,
|
|
3581
|
+
// 可一键升级:npm 真安装时 true;本地 link 开发模式 false(升级请 git pull 源码)
|
|
3582
|
+
installable: mode !== null && !mode.isLink,
|
|
3583
|
+
installMode: mode?.isLink ? "link" : mode !== null ? "registry" : "unknown",
|
|
3584
|
+
},
|
|
3585
|
+
};
|
|
3586
|
+
},
|
|
3587
|
+
// 一键升级:仅在 npm 真安装模式下执行 pnpm 升级;link 模式拒绝,避免破坏本地开发链路。
|
|
3588
|
+
async updatePlugin() {
|
|
3589
|
+
const mode = detectInstallMode();
|
|
3590
|
+
if (mode === null) {
|
|
3591
|
+
return { ok: false, code: "install-not-found", message: "could not locate dsh-free-search in any profile" };
|
|
3592
|
+
}
|
|
3593
|
+
if (mode.isLink) {
|
|
3594
|
+
return {
|
|
3595
|
+
ok: false,
|
|
3596
|
+
code: "local-link-mode",
|
|
3597
|
+
message: "local development install (symlink) - update the source repo instead (git pull), then restart dsh",
|
|
3598
|
+
};
|
|
3599
|
+
}
|
|
3600
|
+
try {
|
|
3601
|
+
const result = await new Promise((resolve, reject) => {
|
|
3602
|
+
exec("pnpm add dsh-free-search@latest", { cwd: mode.profileDir, timeout: 120000 }, (error, stdout, stderr) => {
|
|
3603
|
+
if (error) reject(new Error(`upgrade failed: ${(stderr || stdout || error.message).trim().slice(0, 300)}`));
|
|
3604
|
+
else resolve(stdout);
|
|
3605
|
+
});
|
|
3606
|
+
});
|
|
3607
|
+
const latest = await fetchLatestVersion();
|
|
3608
|
+
return {
|
|
3609
|
+
ok: true,
|
|
3610
|
+
value: {
|
|
3611
|
+
updated: true,
|
|
3612
|
+
latest: latest ?? "unknown",
|
|
3613
|
+
message: "upgraded to latest - restart dsh to apply",
|
|
3614
|
+
output: String(result).trim().slice(0, 200),
|
|
3615
|
+
},
|
|
3616
|
+
};
|
|
3617
|
+
} catch (error) {
|
|
3618
|
+
return { ok: false, code: "upgrade-failed", message: error instanceof Error ? error.message : String(error) };
|
|
3619
|
+
}
|
|
3620
|
+
},
|
|
3500
3621
|
async rawSearch(request) {
|
|
3501
3622
|
if (request === null || typeof request !== "object" || typeof request.query !== "string" || request.query.length === 0) {
|
|
3502
3623
|
return { ok: false, code: "search-rejected", message: "malformed bridge search request (query is required)" };
|
|
@@ -3726,6 +3847,22 @@ function makeBridgeRoutes(settings, search, testEngine, getCredentials, getConfi
|
|
|
3726
3847
|
writeJson(res, 200, await handlers.doctorReport());
|
|
3727
3848
|
},
|
|
3728
3849
|
},
|
|
3850
|
+
{
|
|
3851
|
+
kind: "exact",
|
|
3852
|
+
path: `${BRIDGE_PREFIX}/check-update`,
|
|
3853
|
+
handler: async (req, res) => {
|
|
3854
|
+
if (!guard(req, res)) return;
|
|
3855
|
+
writeJson(res, 200, await handlers.checkUpdate());
|
|
3856
|
+
},
|
|
3857
|
+
},
|
|
3858
|
+
{
|
|
3859
|
+
kind: "exact",
|
|
3860
|
+
path: `${BRIDGE_PREFIX}/update`,
|
|
3861
|
+
handler: async (req, res) => {
|
|
3862
|
+
if (!guard(req, res)) return;
|
|
3863
|
+
writeJson(res, 200, await handlers.updatePlugin());
|
|
3864
|
+
},
|
|
3865
|
+
},
|
|
3729
3866
|
{
|
|
3730
3867
|
kind: "exact",
|
|
3731
3868
|
path: `${BRIDGE_PREFIX}/raw-search`,
|
|
@@ -3812,7 +3949,10 @@ export function buildBuiltinPromptBlocks(cfg) {
|
|
|
3812
3949
|
}
|
|
3813
3950
|
|
|
3814
3951
|
const name = "web-search-free";
|
|
3815
|
-
|
|
3952
|
+
// settings / tools / systemPrompt are core DSH services and are touched inside
|
|
3953
|
+
// inject() callbacks; older Cordis builds (DSH 0.2.1-rc.2) refuse undeclared
|
|
3954
|
+
// property access, so declare them here as well (#107).
|
|
3955
|
+
const inject = ["web", "settings", "tools", "systemPrompt"];
|
|
3816
3956
|
|
|
3817
3957
|
// 引擎 key 与凭据中心 ref 的映射(白名单:只允许这些 ref 被 UI 读写凭据中心)
|
|
3818
3958
|
const KEY_REF_MAP = {
|
|
@@ -4327,17 +4467,23 @@ function apply(ctx, config) {
|
|
|
4327
4467
|
},
|
|
4328
4468
|
// 单 query 结果缓存:key=query+maxResults+timeRangeLabel+preferred,Map 天然 LRU
|
|
4329
4469
|
async search(request, signal) {
|
|
4330
|
-
//
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
|
|
4335
|
-
|
|
4336
|
-
|
|
4337
|
-
|
|
4470
|
+
// #108: every result and error leaving the provider must be valid Unicode —
|
|
4471
|
+
// a lone surrogate in the history rejects every later request upstream.
|
|
4472
|
+
try {
|
|
4473
|
+
// 轮换时机:首次失败后 keyRings 已经填充,此时再判断有几把 key。
|
|
4474
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
4475
|
+
try {
|
|
4476
|
+
return sanitizeSearchResult(await provider.searchOnce(request, signal));
|
|
4477
|
+
} catch (error) {
|
|
4478
|
+
const keys = maxKeyRingLength();
|
|
4479
|
+
if (keys <= 1 || attempt >= keys - 1 || !isKeyRotationCandidate(error)) throw error;
|
|
4480
|
+
logger.warn(`free-search: retrying with the next API key (${error?.message ?? error})`);
|
|
4481
|
+
}
|
|
4338
4482
|
}
|
|
4483
|
+
throw new Error("all search engines failed");
|
|
4484
|
+
} catch (error) {
|
|
4485
|
+
throw sanitizeError(error);
|
|
4339
4486
|
}
|
|
4340
|
-
throw new Error("all search engines failed");
|
|
4341
4487
|
},
|
|
4342
4488
|
async searchOnce(request, signal) {
|
|
4343
4489
|
// 公共咽喉校验:web_search / advanced_search / raw-search 三条路径都经过这里
|
|
@@ -4892,7 +5038,7 @@ function apply(ctx, config) {
|
|
|
4892
5038
|
getCredentials,
|
|
4893
5039
|
current,
|
|
4894
5040
|
doctorReport
|
|
4895
|
-
).map((route) => registerOnce(() => sctx.webServer.register(route), { id: route.path }, "bridge route"));
|
|
5041
|
+
).map((route) => registerOnce(() => sctx.get("webServer").register(route), { id: route.path }, "bridge route"));
|
|
4896
5042
|
return () => {
|
|
4897
5043
|
for (const dispose of disposers) dispose();
|
|
4898
5044
|
};
|
|
@@ -5455,8 +5601,9 @@ function apply(ctx, config) {
|
|
|
5455
5601
|
|
|
5456
5602
|
return {
|
|
5457
5603
|
provider: "multi_search",
|
|
5458
|
-
|
|
5459
|
-
|
|
5604
|
+
// #108: the multi tool bypasses provider.search, so sanitize here as well
|
|
5605
|
+
content: stripLoneSurrogates(`Note: ${notes.join("; ")}`),
|
|
5606
|
+
sources: sanitizeSources(finalSources),
|
|
5460
5607
|
truncated: false,
|
|
5461
5608
|
};
|
|
5462
5609
|
};
|
|
@@ -6092,6 +6239,10 @@ export {
|
|
|
6092
6239
|
hasCustomFallbackOrder,
|
|
6093
6240
|
normalizeDisabledEngines,
|
|
6094
6241
|
normalizeAllowedEngines,
|
|
6242
|
+
cleanSnippet,
|
|
6243
|
+
compareVersions,
|
|
6244
|
+
detectInstallMode,
|
|
6245
|
+
fetchLatestVersion,
|
|
6095
6246
|
effectiveDisabledEngines,
|
|
6096
6247
|
normalizeFallbackOrder,
|
|
6097
6248
|
ANYSEARCH_URL,
|
package/lib/safe_text.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UTF-16 safety for tool results (#108).
|
|
3
|
+
*
|
|
4
|
+
* `String.prototype.slice` cuts on code units. A cut inside a surrogate pair
|
|
5
|
+
* leaves a lone surrogate, which is valid JavaScript but not valid Unicode:
|
|
6
|
+
* serialized as an unpaired \ud83d it makes the upstream Messages endpoint
|
|
7
|
+
* reject the whole request, and because the poisoned text is stored in the
|
|
8
|
+
* session history every later turn fails too.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
|
|
12
|
+
|
|
13
|
+
export function stripLoneSurrogates(text) {
|
|
14
|
+
if (typeof text !== "string" || text.length === 0) return text;
|
|
15
|
+
return text.replace(LONE_SURROGATE, "\uFFFD");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Cut by code point so a surrogate pair is never split. */
|
|
19
|
+
export function sliceByCodePoint(text, max) {
|
|
20
|
+
if (typeof text !== "string") return text;
|
|
21
|
+
const limit = Math.floor(Number(max));
|
|
22
|
+
if (!Number.isFinite(limit) || limit < 0) return text;
|
|
23
|
+
const chars = Array.from(text);
|
|
24
|
+
if (chars.length <= limit) return text;
|
|
25
|
+
return chars.slice(0, limit).join("");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Strip stray surrogates first, then cut by code point. */
|
|
29
|
+
export function truncateText(text, max) {
|
|
30
|
+
const safe = stripLoneSurrogates(typeof text === "string" ? text : String(text));
|
|
31
|
+
return sliceByCodePoint(safe, max);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function sanitizeSource(source) {
|
|
35
|
+
if (source === null || typeof source !== "object") return source;
|
|
36
|
+
const out = { ...source };
|
|
37
|
+
for (const key of ["title", "url", "snippet", "content"]) {
|
|
38
|
+
if (typeof out[key] === "string") out[key] = stripLoneSurrogates(out[key]);
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function sanitizeSources(sources) {
|
|
44
|
+
return Array.isArray(sources) ? sources.map(sanitizeSource) : sources;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Sanitize a search result (sources + the note that accompanies them). */
|
|
48
|
+
export function sanitizeSearchResult(result) {
|
|
49
|
+
if (result === null || typeof result !== "object") return result;
|
|
50
|
+
const out = { ...result };
|
|
51
|
+
if (Array.isArray(out.sources)) out.sources = sanitizeSources(out.sources);
|
|
52
|
+
for (const key of ["content", "note", "provider", "engine"]) {
|
|
53
|
+
if (typeof out[key] === "string") out[key] = stripLoneSurrogates(out[key]);
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Keep an error's message and stack free of lone surrogates. */
|
|
59
|
+
export function sanitizeError(error) {
|
|
60
|
+
if (!(error instanceof Error)) return error;
|
|
61
|
+
const message = stripLoneSurrogates(error.message);
|
|
62
|
+
if (message === error.message) return error;
|
|
63
|
+
const wrapped = new Error(message);
|
|
64
|
+
wrapped.name = error.name;
|
|
65
|
+
if (typeof error.stack === "string") wrapped.stack = stripLoneSurrogates(error.stack);
|
|
66
|
+
return wrapped;
|
|
67
|
+
}
|
package/lib/serp_engines.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { normalizeUrlForDedupe } from "./url_norm.js";
|
|
20
|
+
import { truncateText, stripLoneSurrogates, sliceByCodePoint } from "./safe_text.js";
|
|
20
21
|
|
|
21
22
|
export const SERP_UA =
|
|
22
23
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
|
|
@@ -84,12 +85,14 @@ export function stripTags(html) {
|
|
|
84
85
|
}
|
|
85
86
|
|
|
86
87
|
function cleanTitle(title) {
|
|
87
|
-
return stripTags(title).replace(/^[\s\-–—|·•]+|[\s\-–—|·•]+$/g, "")
|
|
88
|
+
return truncateText(stripTags(title).replace(/^[\s\-–—|·•]+|[\s\-–—|·•]+$/g, ""), 240);
|
|
88
89
|
}
|
|
89
90
|
|
|
90
91
|
function cleanSnippet(snippet) {
|
|
91
92
|
const text = stripTags(snippet);
|
|
92
|
-
|
|
93
|
+
const safe = stripLoneSurrogates(text);
|
|
94
|
+
const cut = sliceByCodePoint(safe, 400);
|
|
95
|
+
return cut.length < safe.length ? `${cut}…` : cut;
|
|
93
96
|
}
|
|
94
97
|
|
|
95
98
|
function unescapeAttr(value) {
|
package/lib/vertical.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
6
6
|
import { httpsJson, htmlToText } from "./fetch_upstream.js";
|
|
7
|
+
import { stripLoneSurrogates } from "./safe_text.js";
|
|
7
8
|
import { promptLanguageOf, toolDescription, toolParam, localizedEffect } from "./prompt_i18n.js";
|
|
8
9
|
|
|
9
10
|
const UA = { "User-Agent": "dsh-free-search/0.8 (plugin)", Accept: "application/json" };
|
|
@@ -686,7 +687,10 @@ export function registerDomainSearchTool(ctx, { wrapUntrustedBlock, getConfig =
|
|
|
686
687
|
},
|
|
687
688
|
},
|
|
688
689
|
render(_args, value) {
|
|
689
|
-
if (value.error)
|
|
690
|
+
if (value.error) {
|
|
691
|
+
const message = stripLoneSurrogates(String(value.error));
|
|
692
|
+
return [{ type: "text", text: `domain_search (${value.engine}) failed: ${message}` }];
|
|
693
|
+
}
|
|
690
694
|
const lines = value.sources.map((s, i) => `- [${i + 1}] ${s.title} — ${s.url}${s.publishedAt ? ` _(${s.publishedAt})_` : ""}${s.snippet ? `\n ${s.snippet}` : ""}`);
|
|
691
695
|
return [{ type: "text", text: wrapUntrustedBlock(`domain_search ${value.engine} — ${value.query}:\n${lines.join("\n") || "No results."}`) }];
|
|
692
696
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-free-search",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.33",
|
|
4
4
|
"description": "Free web search for DeepSeek Harness: 27 engines (Bing/DuckDuckGo/AnySearch/SearXNG/Exa/Tavily/Keenable/Firecrawl/Parallel/You.com keyless; Zhihu global/site via MCP and Perplexity/SerpBase/DeepSeek (official + native tools/search)/Baidu/Kimi/Aliyun/Doubao with key; OpenAI/Gemini/Claude model built-in search, explicit-only) + auto smart routing + global engine enable/disable & fallback priority + editable zh/en language pools + multi mode (parallel full language-pool merge) + multi_search cross-source tool + failure-aware fallback (quota/auth cooldown, transient retry, fallbackOn) + time filtering + platform search + domain blocklist (blockedDomains) + web_fetch, with web settings UI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|