dsh-free-search 0.9.38 → 0.9.39
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 +20 -10
- package/lib/client.js +42 -2
- package/lib/doctor.js +7 -0
- package/lib/engine_meta.js +3 -0
- package/lib/engine_runtime.js +106 -0
- package/lib/engines/google.js +112 -0
- package/lib/index.js +4164 -4119
- package/lib/multi_policy.js +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
#### 引擎与切换
|
|
35
35
|
|
|
36
36
|
- **零成本** —— 多个免费引擎,无需 key、无需注册
|
|
37
|
-
- **
|
|
37
|
+
- **36 个引擎可选**:DuckDuckGo(html/lite)、Bing、SearXNG(元搜索,支持自定义实例)、AnySearch、Exa、Tavily、Keenable、Firecrawl、Parallel、Perplexity、SerpBase、Serply、Outcrawl、Google 自定义搜索(`google`,需 API key + CSE ID)、DeepSeek 官方、DeepSeek 原生搜索 API、You.com、百度千帆、Kimi、阿里云百炼、火山联网搜索(豆包搜索)、知乎全网/站内(`zhihu_global`/`zhihu_site`,经知乎开放平台 MCP)、Antigravity CLI 搜索(`agy`,需本机安装)、OpenAI / Gemini / Claude 模型内置搜索。默认自动回退链覆盖其中 28 个;5 个 HTML SERP 引擎默认不参与,OpenAI / Gemini / Claude 三个按次计费引擎只在显式点名时运行。
|
|
38
38
|
- **5 个 HTML 搜索页引擎(默认关闭)** —— 把传统搜索页并入同一套引擎 / 回退 / 冷却 / 设置体系:`baidu-html`(百度网页)、`so360`、`sogou`、`wechat`(微信文章)、`toutiao`。免 key、免额度,代价是抓页面:验证码/反爬按 `bot-wall` 归类并让整个家族冷却 10 分钟(整段出口 IP 都会被打标),结果也没有 API 摘要。它们默认不进 auto / 回退链 / 语言池,只在显式 `engine=` 或加入语言池时运行。
|
|
39
39
|
- **引擎白名单** —— 设置页「只使用勾选的引擎」开启后,只有勾选的引擎可用,升级新增的引擎默认不启用;配置里对应 `allowedEngines`(非空时等价于把其余引擎全部禁用)。
|
|
40
40
|
- **全局引擎开关与回退优先级** —— 设置页可勾选/取消引擎(取消后全局生效:普通搜索 / Auto / `advanced_search` / `multi_search` / 引擎测试都不再用它),并可用 ↑↓ 调整全局回退顺序(一键恢复默认)。
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
|
|
49
49
|
- **统一引擎回退** —— 任何引擎失败(付费/免费,缺 key/401/限流/网络)自动轮流尝试下一个引擎:首选引擎 → 其他引擎(exa/tavily/keenable/firecrawl/parallel/you 无 key 也会尝试,因为它们自带 keyless 免费额度)→ 剩余免费引擎,搜索永不直接失败;结果顶部注明实际生效的引擎(如 `Note: perplexity unavailable or failed, using exa.`);失败按类别处理:额度/鉴权失败 → 本会话冷却该引擎,反爬 → 短退避,超时/5xx/限流 → 同引擎重试一次,解析失败/0 结果 → 不冷却(详见下文「失败分类与引擎冷却」)。
|
|
50
50
|
- **多 key 轮换** —— 任何 key 字段(或对应环境变量)都可以用逗号 / 分号 / 换行分隔多把 key;平时按请求轮流使用(round-robin,避免单 key 撞 QPS/RPM 风控),遇到 401/402/429(鉴权失败、额度耗尽、限流)先轮换同一引擎的下一把,再走引擎回退;`multi` 模式同样生效(#96)。
|
|
51
|
-
- **按 key 冷却与诊断** —— 429 与额度错误按 key 分别冷却,同一引擎的其他 key 不受牵连;冷却状态写入磁盘,重启后仍在;失败信息和日志里的 key
|
|
51
|
+
- **按 key 冷却与诊断** —— 429 与额度错误按 key 分别冷却,同一引擎的其他 key 不受牵连;冷却状态写入磁盘,重启后仍在;失败信息和日志里的 key 一律打码;设置页底部的「诊断」按钮列出每个引擎当前为什么不可用、冷却还剩多久,以及本次进程内的调用次数、成功/空/失败和平均耗时;同一引擎并发超过 2 会排队(HTML SERP 为 1),避免免费引擎被同时打爆。
|
|
52
52
|
- **自带更新** —— 卡片底部显示当前版本和「检查更新」;npm 安装的版本可一键升级到 latest,本地 link 开发模式改为跳转 npm 页面并提示 `git pull`。
|
|
53
53
|
- **引擎测试** —— `free_search_test` 工具让 agent 一键测试所有引擎;设置页也有「测试引擎」按钮(直测当前引擎,不走回退链,付费引擎无 key 会明确报错)。
|
|
54
54
|
- **截断安全** —— 标题和摘要按码点截断,搜索结果、工具输出和 `web_fetch` 正文在离开插件前统一清除孤立代理;含 emoji 的结果不会再让会话历史出现无法序列化的字符(#108)。
|
|
@@ -147,6 +147,7 @@
|
|
|
147
147
|
| `serpbase` | SerpBase | 付费 | 需 `SERPBASE_API_KEY`(serpbase.dev,注册送 100 次免费额度) |
|
|
148
148
|
| `serply` | Serply | 付费 | 需 `SERPLY_API_KEY`(serply.io,新账户 30 天内 2,500 次免费额度);Google 网页结果,按设置页语言本地化 |
|
|
149
149
|
| `outcrawl` | Outcrawl | 付费 | 需 `OUTCRAWL_API_KEY`(outcrawl.ai,每月 1,000 credits 免费额度);网页搜索结果(标题/链接/摘要),单次最多 20 条 |
|
|
150
|
+
| `google` | Google 自定义搜索 | 免费额度 | 需 `GOOGLE_CSE_API_KEY` 和 Programmable Search Engine ID(`googleCseId` / cx);Google 官方 Custom Search JSON API,每天 100 次免费,按次计费超额;支持 `hl`、安全搜索和 `dateRestrict` 时间过滤 |
|
|
150
151
|
| `deepseek-official` | DeepSeek 官方 | 付费 | 需 `DEEPSEEK_API_KEY`;走 Anthropic 兼容的 `web_search` 服务端工具,每次搜索是一整个模型轮次(慢、耗 token) |
|
|
151
152
|
| `deepseek-tools` | DeepSeek 原生搜索 API | 付费 | 需 `DEEPSEEK_API_KEY`(与上一档共用);直接 `POST /v1/tools/search`,无模型参与,返回结构化 `results[]`(`title`/`url`/`summary`/`date`),同 query 实测 ~0.3s vs 上一档 ~5-6s |
|
|
152
153
|
| `baidu` | 百度千帆 AI 搜索 | 额度 | 需 `BAIDU_API_KEY`(千帆 AI 搜索,每日赠 50 次,超额按量后付费);中文全网,支持时间过滤 |
|
|
@@ -277,7 +278,7 @@ DSH 0.2.1 设置 → 网页搜索 → **DeepSeek 搜索 API** 开关会和本插
|
|
|
277
278
|
配置页提供:
|
|
278
279
|
|
|
279
280
|
- **Search engine**:下拉框切换引擎,保存即生效
|
|
280
|
-
- **API keys**:为 Exa / Tavily / Keenable / Firecrawl / Parallel / Perplexity / DeepSeek / SerpBase / Serply / Outcrawl / You.com 填写 key(密码框,保存后只显示"已配置";Exa / Tavily / Keenable / Firecrawl / Parallel / You.com 不填也可免 key 使用)
|
|
281
|
+
- **API keys**:为 Exa / Tavily / Keenable / Firecrawl / Parallel / Perplexity / DeepSeek / SerpBase / Serply / Outcrawl / Google CSE / You.com 填写 key(密码框,保存后只显示"已配置";Exa / Tavily / Keenable / Firecrawl / Parallel / You.com 不填也可免 key 使用)
|
|
281
282
|
- **推荐**:付费引擎 key 建议写入 harness 凭据中心 `~/.dsh/.credentials.yaml`(如 `DEEPSEEK_API_KEY: sk-...`,与官方 LLM provider 一致,一处管理所有 key)。插件读取优先级:凭据中心 > 设置页 > 环境变量,设置页填的 key 仅作为遗留兼容。
|
|
282
283
|
- **Test engine**:直测当前引擎可用性(不走回退链,付费引擎无 key 会明确报错)
|
|
283
284
|
- **Use Bing default**:把当前搜索引擎切回稳定的免费 Bing;`Discard` 只撤销尚未保存的编辑
|
|
@@ -421,6 +422,8 @@ perplexityApiKey: ...
|
|
|
421
422
|
serpbaseApiKey: ... # 或通过设置页填写
|
|
422
423
|
serplyApiKey: ... # 或通过设置页填写
|
|
423
424
|
outcrawlApiKey: ... # 或通过设置页填写
|
|
425
|
+
googleCseApiKey: ... # Google Custom Search API key
|
|
426
|
+
googleCseId: "..." # Programmable Search Engine 的 cx
|
|
424
427
|
deepseekApiKey: ...
|
|
425
428
|
```
|
|
426
429
|
|
|
@@ -582,7 +585,7 @@ Search engine test:
|
|
|
582
585
|
|
|
583
586
|
#### 离线自检断言(tools/)
|
|
584
587
|
|
|
585
|
-
仓库自带 **
|
|
588
|
+
仓库自带 **50 个**零依赖断言脚本(合计 **796 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑:
|
|
586
589
|
|
|
587
590
|
| 脚本 | 覆盖 | 运行(项数) |
|
|
588
591
|
|---|---|---|
|
|
@@ -593,7 +596,7 @@ Search engine test:
|
|
|
593
596
|
| `assert-multi-policy.mjs` | multi 执行策略:并发上限是天花板 / 目标成功源非硬下限 / 凭据资格在上限之前分流 / **Fast·Balanced·Deep 档位** | `node tools/assert-multi-policy.mjs`(146) |
|
|
594
597
|
| `assert-multi-limit.mjs` | multi 结果上限(#109):默认 20 / 硬上限 100 / 配置归一化、单次 maxResults 受上限约束、工具参数与本段提示词写明生效上限、设置页字段与保存 | `node tools/assert-multi-limit.mjs`(6) |
|
|
595
598
|
| `assert-maintenance.mjs` | 维护面:CI 在 Node 20/22/24 跑全部断言并过打包闸门、发布脚本会 bump / 校验 / 打 tag / 可发布、恢复官方 provider 的桥接与设置页按钮 | `node tools/assert-maintenance.mjs`(4) |
|
|
596
|
-
| `assert-engine-modules.mjs` | 引擎分层:实现文件存在且被 index 引用、引擎函数已迁出 index、设置页引擎 id 与服务端清单一致、清单覆盖
|
|
599
|
+
| `assert-engine-modules.mjs` | 引擎分层:实现文件存在且被 index 引用、引擎函数已迁出 index、设置页引擎 id 与服务端清单一致、清单覆盖 36 个引擎且免费/按次标记正确 | `node tools/assert-engine-modules.mjs`(4) |
|
|
597
600
|
| `assert-result-ranking.mjs` | 合并排序:**eTLD+1 同域判定** / 域名轮转 / `seenIn` 降为末位 / 时效仅带时间过滤时生效 | `node tools/assert-result-ranking.mjs`(31) |
|
|
598
601
|
| `assert-url-norm.mjs` | URL 规范化:只剔已审计的 tracking 参数,保留可能区分资源的参数 | `node tools/assert-url-norm.mjs`(72) |
|
|
599
602
|
| `assert-prompt-contract.mjs` | 系统提示词契约:**检索≠抓取**、不可信边界、模型内置搜索只在显式选中时运行 | `node tools/assert-prompt-contract.mjs`(9) |
|
|
@@ -601,6 +604,8 @@ Search engine test:
|
|
|
601
604
|
| `assert-research-call-wrappers.mjs` | research 四个 `call*` 包装层的替身/底层透传(#75 回归) | `node tools/assert-research-call-wrappers.mjs`(23) |
|
|
602
605
|
| `assert-fetch-chain.mjs` | `fs-quality-fetch` 四层链序、任一层命中即停、exa 失败静默降级 firecrawl、全层失败聚合报错 | `node tools/assert-fetch-chain.mjs`(8) |
|
|
603
606
|
| `assert-fetch-ssrf.mjs` | 抓取 SSRF 防护:公网/私网/保留地址判定、DNS 解析到私网拒绝、localhost 与 IP 字面量拒绝、非 HTTPS 与带凭据 URL 拒绝、provider 接线与设置项 | `node tools/assert-fetch-ssrf.mjs`(6) |
|
|
607
|
+
| `assert-google-cse.mjs` | Google Custom Search:key+ID 必填、请求参数(q/num/start/hl/safe/dateRestrict)、结果映射与发布日期、超过 10 条分页、403/429/400 错误分类、时间档映射、全链路注册 | `node tools/assert-google-cse.mjs`(6) |
|
|
608
|
+
| `assert-engine-runtime.mjs` | 引擎运行时:按引擎并发上限(普通 2 / HTML SERP 1)、排队与 abort 清理、成功/空/失败/平均耗时统计、provider 与 runEngineTest 两条路径接线、诊断报告带 stats | `node tools/assert-engine-runtime.mjs`(4) |
|
|
604
609
|
| `assert-single-fetch-layer.mjs` | 抓取层全库只有一份实现、依赖单向、替身键不串层 | `node tools/assert-single-fetch-layer.mjs`(22) |
|
|
605
610
|
| `assert-vertical.mjs` | `domain_search` 41 引擎注册表、每引擎 desc、未知引擎报错、不依赖 research | `node tools/assert-vertical.mjs`(8) |
|
|
606
611
|
| `assert-free-search-test-schema.mjs` | `free_search_test` 输出 schema 与真实产出一致(含 auto/multi 虚拟模式) | `node tools/assert-free-search-test-schema.mjs`(8) |
|
|
@@ -685,7 +690,7 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
|
|
|
685
690
|
#### Engines and switching
|
|
686
691
|
|
|
687
692
|
- **Zero Cost** — Multiple free engines with no API key or registration required
|
|
688
|
-
- **
|
|
693
|
+
- **36 engines available** — DuckDuckGo (HTML / Lite), Bing, AnySearch AI, SearXNG (meta-search with custom instances), Exa, Tavily, Keenable, Firecrawl, Parallel, Perplexity, SerpBase, Serply, Outcrawl, Google Programmable Search (`google`, needs an API key plus a CSE ID), DeepSeek Official, DeepSeek Native Search API, You.com, Baidu Qianfan, Kimi, Aliyun Bailian, Volcano Doubao, Zhihu web-wide/site search (`zhihu_global`/`zhihu_site`, via the Zhihu open-platform MCP), Antigravity CLI search (`agy`, requires the local CLI), and the model-based OpenAI / Gemini / Claude searches. The default auto-fallback chain covers 28 of them; the 5 HTML SERP engines stay out by default and the per-call billed OpenAI / Gemini / Claude engines run only when explicitly named.
|
|
689
694
|
- **5 HTML SERP engines (off by default)** — Traditional result pages join the same engine / fallback / cooldown / settings machinery: `baidu-html` (Baidu web), `so360`, `sogou`, `wechat` (WeChat articles) and `toutiao`. No key, no quota — the trade-off is scraping: captcha/anti-bot pages are classified as `bot-wall` and cool the whole family down for 10 minutes (the egress IP gets flagged as a whole), and results carry no API snippets. They never join auto routing, the fallback chain or the language pools; they only run when named via `engine=` or added to a pool.
|
|
690
695
|
- **Engine whitelist** — turn on Use only the checked engines and only those engines stay usable; engines added by later versions stay off. It maps to `allowedEngines` in the config (a non-empty list is equivalent to disabling every other engine).
|
|
691
696
|
- **Global engine enable/disable & fallback priority** — uncheck engines you never want (applies everywhere: web_search fallback, Auto routing, advanced_search, multi_search, engine tests) and reorder the global fallback chain with ↑↓ (one-click reset).
|
|
@@ -699,7 +704,7 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
|
|
|
699
704
|
|
|
700
705
|
- **Unified Engine Fallback** — Any engine failure (paid or free, missing key, 401, rate limit, network error) automatically tries the next engine: the configured engine first, then other engines (exa/tavily/keenable/firecrawl/parallel/you are tried even without a key because they have built-in keyless quota), then the remaining free engines (Bing/AnySearch etc.) — with a note attached to the results naming the engine that actually served them (e.g. `Note: perplexity unavailable or failed, using exa.`). Failures are classified: quota/auth failures cool the engine down for the session, anti-bot walls back off briefly, timeout/5xx/rate-limit failures retry the same engine once, and parse errors / 0 results are reported without cooling it down. Search never fails outright.
|
|
701
706
|
- **Multi-key rotation** — Any key field (or its env var) accepts several keys separated by commas, semicolons or newlines. Keys are used round-robin per request, and on 401/402/429 the same engine retries with the next key before the engine-level fallback runs. This also applies inside `multi` mode (#96).
|
|
702
|
-
- **Per-key cooldowns and diagnostics** — a 429 or quota error cools the key that hit it, not every other key of the same engine; the state is written to disk and survives a restart; keys are masked in failure text and logs; the Diagnose button at the bottom of the settings page lists why each engine is currently unavailable
|
|
707
|
+
- **Per-key cooldowns and diagnostics** — a 429 or quota error cools the key that hit it, not every other key of the same engine; the state is written to disk and survives a restart; keys are masked in failure text and logs; the Diagnose button at the bottom of the settings page lists why each engine is currently unavailable, how long its cooldown has left, and the in-process call count, success/empty/failure split and average latency; concurrent calls to one engine queue beyond 2 (1 for HTML SERP), so a free engine is not hammered in the same second.
|
|
703
708
|
- **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.
|
|
704
709
|
- **Engine Testing** — `free_search_test` for the agent to check all engines in one call; the settings UI also has a "Test engine" button that tests the selected engine directly (no fallback chain; paid engines without a key report an explicit error).
|
|
705
710
|
- **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).
|
|
@@ -799,6 +804,7 @@ If this plugin has been helpful, a ⭐ on [GitHub](https://github.com/DDDMUC/dsh
|
|
|
799
804
|
| `serpbase` | SerpBase | Paid | Requires `SERPBASE_API_KEY` (serpbase.dev, 100 free queries on signup) |
|
|
800
805
|
| `serply` | Serply | Paid | Requires `SERPLY_API_KEY` (serply.io, 2,500 free credits for the first 30 days); Google web results localized to the settings language |
|
|
801
806
|
| `outcrawl` | Outcrawl | Paid | Requires `OUTCRAWL_API_KEY` (outcrawl.ai, free tier of 1,000 credits a month); web results with title, URL and snippet, up to 20 per search |
|
|
807
|
+
| `google` | Google Programmable Search | Free quota | Requires `GOOGLE_CSE_API_KEY` and a Programmable Search Engine ID (`googleCseId` / cx); official Custom Search JSON API, 100 free queries/day then billed; supports `hl`, safe search and `dateRestrict` time filtering |
|
|
802
808
|
| `deepseek-official` | DeepSeek Official | Paid | Requires `DEEPSEEK_API_KEY`; uses the Anthropic-compatible `web_search` server tool, so every search is a full model turn (slow, token-billed) |
|
|
803
809
|
| `deepseek-tools` | DeepSeek Native Search API | Paid | Requires `DEEPSEEK_API_KEY` (shared with the row above); calls `POST /v1/tools/search` directly, no model involved, returns structured `results[]` (`title`/`url`/`summary`/`date`) — measured ~0.3s vs ~5-6s for the row above on the same query |
|
|
804
810
|
| `baidu` | Baidu Qianfan AI Search | Quota | Requires `BAIDU_API_KEY` (Qianfan AI Search, 50 free calls/day then pay-as-you-go); Chinese web-wide, supports time filtering |
|
|
@@ -930,7 +936,7 @@ After installation, open the config page (DSH 0.2.1-rc.2+):
|
|
|
930
936
|
The config page provides:
|
|
931
937
|
|
|
932
938
|
- **Search engine**: Select an engine from the dropdown; changes take effect immediately upon saving.
|
|
933
|
-
- **API keys**: Enter keys for Exa / Tavily / Keenable / Firecrawl / Parallel / Perplexity / DeepSeek / You.com (password fields; displayed as "configured" once saved; Exa / Tavily / Keenable / Firecrawl / Parallel / You.com work without a key too).
|
|
939
|
+
- **API keys**: Enter keys for Exa / Tavily / Keenable / Firecrawl / Parallel / Perplexity / DeepSeek / Google CSE / You.com (password fields; displayed as "configured" once saved; Exa / Tavily / Keenable / Firecrawl / Parallel / You.com work without a key too).
|
|
934
940
|
- **Recommended**: store paid-engine keys in the harness credential center `~/.dsh/.credentials.yaml` (e.g. `DEEPSEEK_API_KEY: sk-...`, same as the official LLM providers — one place for all keys). Resolution order: credentials center > settings page > environment variable; the settings-page fields remain for backward compatibility.
|
|
935
941
|
- **Test engine**: Tests the selected engine directly (no fallback chain; paid engines without a key report an explicit error).
|
|
936
942
|
- **Use Bing default**: stage a switch back to the stable free Bing engine; `Discard` only cancels unsaved edits
|
|
@@ -1074,6 +1080,8 @@ perplexityApiKey: ...
|
|
|
1074
1080
|
serpbaseApiKey: ... # Or configure via the web settings UI
|
|
1075
1081
|
serplyApiKey: ... # Or configure via the web settings UI
|
|
1076
1082
|
outcrawlApiKey: ... # Or configure via the web settings UI
|
|
1083
|
+
googleCseApiKey: ... # Google Custom Search API key
|
|
1084
|
+
googleCseId: "..." # Programmable Search Engine cx
|
|
1077
1085
|
deepseekApiKey: ...
|
|
1078
1086
|
```
|
|
1079
1087
|
|
|
@@ -1235,7 +1243,7 @@ Restart `dsh web` after switching to apply changes.
|
|
|
1235
1243
|
|
|
1236
1244
|
#### Offline self-check assertions (`tools/`)
|
|
1237
1245
|
|
|
1238
|
-
**
|
|
1246
|
+
**Fifty** zero-dependency assertion scripts ship with the repo (**796 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20:
|
|
1239
1247
|
|
|
1240
1248
|
| Script | Covers | Run (count) |
|
|
1241
1249
|
|---|---|---|
|
|
@@ -1246,7 +1254,7 @@ Restart `dsh web` after switching to apply changes.
|
|
|
1246
1254
|
| `assert-multi-policy.mjs` | multi execution policy: ceiling semantics / target-is-not-a-hard-minimum / credential eligibility before the ceiling / **Fast·Balanced·Deep presets** | `node tools/assert-multi-policy.mjs` (146) |
|
|
1247
1255
|
| `assert-multi-limit.mjs` | Multi result ceiling (#109): default 20 / hard max 100 / config normalisation, per-call maxResults clamped to the ceiling, tool copy and prompt state name the effective limit, settings field and save path | `node tools/assert-multi-limit.mjs` (6) |
|
|
1248
1256
|
| `assert-maintenance.mjs` | Maintenance surface: CI runs every assertion on Node 20/22/24 plus the packaging gate, the release script bumps / verifies / tags / can publish, and the restore-official-provider bridge and settings button are wired | `node tools/assert-maintenance.mjs` (4) |
|
|
1249
|
-
| `assert-engine-modules.mjs` | Engine layout: module files exist and are imported, implementations have left index.js, the client engine ids match the server catalog, and the catalog covers
|
|
1257
|
+
| `assert-engine-modules.mjs` | Engine layout: module files exist and are imported, implementations have left index.js, the client engine ids match the server catalog, and the catalog covers 36 engines with the right free/explicit flags | `node tools/assert-engine-modules.mjs` (4) |
|
|
1250
1258
|
| `assert-result-ranking.mjs` | merged ranking: **eTLD+1 same-site detection** / domain round-robin / `seenIn` demoted / freshness only under a time filter | `node tools/assert-result-ranking.mjs` (31) |
|
|
1251
1259
|
| `assert-url-norm.mjs` | URL normalization: strips only audited tracking params, keeps params that may identify different resources | `node tools/assert-url-norm.mjs` (72) |
|
|
1252
1260
|
| `assert-prompt-contract.mjs` | system-prompt contract: **search ≠ fetch**, untrusted-data boundary, model engines only when explicitly selected | `node tools/assert-prompt-contract.mjs` (9) |
|
|
@@ -1254,6 +1262,8 @@ Restart `dsh web` after switching to apply changes.
|
|
|
1254
1262
|
| `assert-research-call-wrappers.mjs` | the four research `call*` wrappers proxy to stubs / the real layer (#75 regression) | `node tools/assert-research-call-wrappers.mjs` (23) |
|
|
1255
1263
|
| `assert-fetch-chain.mjs` | `fs-quality-fetch` tier ordering, stop-on-first-success, silent firecrawl degradation, aggregated all-tiers failure | `node tools/assert-fetch-chain.mjs` (8) |
|
|
1256
1264
|
| `assert-fetch-ssrf.mjs` | Fetch SSRF guard: public/private/reserved address classification, DNS resolving to a private address rejected, localhost and IP literals rejected, non-HTTPS and credential URLs rejected, provider wiring and settings | `node tools/assert-fetch-ssrf.mjs` (6) |
|
|
1265
|
+
| `assert-google-cse.mjs` | Google Custom Search: key + ID required, request params (q/num/start/hl/safe/dateRestrict), result mapping with dates, pagination past ten results, 403/429/400 classification, time-range mapping, full registration | `node tools/assert-google-cse.mjs` (6) |
|
|
1266
|
+
| `assert-engine-runtime.mjs` | Engine runtime: per-engine concurrency caps (2 normally, 1 for HTML SERP), queueing with abort cleanup, ok/empty/fail/average-latency stats, wiring on both the provider and runEngineTest paths, and stats in the doctor report | `node tools/assert-engine-runtime.mjs` (4) |
|
|
1257
1267
|
| `assert-single-fetch-layer.mjs` | exactly one fetch implementation repo-wide, one-way deps, seams owned by the right layer | `node tools/assert-single-fetch-layer.mjs` (22) |
|
|
1258
1268
|
| `assert-vertical.mjs` | `domain_search` registry of 41 engines, per-engine descriptions, unknown-engine errors, no research dependency | `node tools/assert-vertical.mjs` (8) |
|
|
1259
1269
|
| `assert-free-search-test-schema.mjs` | `free_search_test` output schema matches real output (incl. auto/multi virtual modes) | `node tools/assert-free-search-test-schema.mjs` (8) |
|
package/lib/client.js
CHANGED
|
@@ -435,6 +435,8 @@ window.__ModuleLoader__.load({
|
|
|
435
435
|
fetchPreferExa: "Exa 优先",
|
|
436
436
|
fetchPreferFirecrawl: "Firecrawl 优先",
|
|
437
437
|
fetchPreferHint: "直连和浏览器都失败后先试哪个;只有两个都配了 key 时才有区别。",
|
|
438
|
+
googleCseIdLabel: "Google 搜索引擎 ID",
|
|
439
|
+
googleCseIdHint: "Programmable Search Engine 的 cx(形如 0123…:abc…);配合 GOOGLE_CSE_API_KEY 使用,免费 100 次/天。",
|
|
438
440
|
restoreOfficial: "恢复官方搜索",
|
|
439
441
|
restoreOfficialHint: "把 web.searchProvider 改回 deepseek-official、web.fetchProvider 改回 http。停用或卸载本插件前建议先点一次,避免宿主报 configured web provider \"ddg\" is not registered。",
|
|
440
442
|
restoringOfficial: "恢复中…",
|
|
@@ -597,6 +599,8 @@ window.__ModuleLoader__.load({
|
|
|
597
599
|
fetchPreferExa: "Exa first",
|
|
598
600
|
fetchPreferFirecrawl: "Firecrawl first",
|
|
599
601
|
fetchPreferHint: "Which keyed tier to try first after direct and browser both fail; only matters when both keys are configured.",
|
|
602
|
+
googleCseIdLabel: "Google Programmable Search engine ID",
|
|
603
|
+
googleCseIdHint: "The cx from Programmable Search Engine (looks like 0123…:abc…); used with GOOGLE_CSE_API_KEY, free 100 queries/day.",
|
|
600
604
|
restoreOfficial: "Restore official search",
|
|
601
605
|
restoreOfficialHint: "Sets web.searchProvider back to deepseek-official and web.fetchProvider back to http. Run this before disabling or uninstalling the plugin, otherwise the host reports configured web provider \"ddg\" is not registered.",
|
|
602
606
|
restoringOfficial: "Restoring…",
|
|
@@ -646,7 +650,7 @@ window.__ModuleLoader__.load({
|
|
|
646
650
|
"cache_search",
|
|
647
651
|
"domain_search",
|
|
648
652
|
];
|
|
649
|
-
const PLUGIN_VERSION = "0.9.
|
|
653
|
+
const PLUGIN_VERSION = "0.9.39";
|
|
650
654
|
const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
|
|
651
655
|
// 右侧浮动目录(#85):条目顺序即页面顺序,anchor 是页面里对应 field 的 id。
|
|
652
656
|
const NAV_ITEMS = [
|
|
@@ -686,6 +690,7 @@ window.__ModuleLoader__.load({
|
|
|
686
690
|
{ id: "serpbase", label: "SerpBase · Google", badge: "API KEY", link: "https://serpbase.dev" },
|
|
687
691
|
{ id: "serply", label: "Serply · Google", badge: "API KEY", link: "https://serply.io" },
|
|
688
692
|
{ id: "outcrawl", label: "Outcrawl", badge: "API KEY", link: "https://outcrawl.ai" },
|
|
693
|
+
{ id: "google", label: "Google · 自定义搜索", badge: "API KEY", link: "https://developers.google.com/custom-search/v1/overview" },
|
|
689
694
|
{ id: "deepseek-official", label: "DeepSeek Official", badge: "API KEY", link: "https://platform.deepseek.com/api_keys" },
|
|
690
695
|
{ id: "deepseek-tools", label: "DeepSeek Tools API", badge: "API KEY", link: "https://api-docs.deepseek.com/zh-cn/guides/search" },
|
|
691
696
|
{ id: "you", label: "You.com", badge: "FREE", link: "https://you.com/platform/api-keys" },
|
|
@@ -923,6 +928,8 @@ window.__ModuleLoader__.load({
|
|
|
923
928
|
const [serpbaseKey, setSerpbaseKey] = react.useState("");
|
|
924
929
|
const [serplyKey, setSerplyKey] = react.useState("");
|
|
925
930
|
const [outcrawlKey, setOutcrawlKey] = react.useState("");
|
|
931
|
+
const [googleKey, setGoogleKey] = react.useState("");
|
|
932
|
+
const [googleCx, setGoogleCx] = react.useState("");
|
|
926
933
|
const [youcomKey, setYoucomKey] = react.useState("");
|
|
927
934
|
const [baiduKey, setBaiduKey] = react.useState("");
|
|
928
935
|
const [kimiKey, setKimiKey] = react.useState("");
|
|
@@ -1007,6 +1014,7 @@ window.__ModuleLoader__.load({
|
|
|
1007
1014
|
serpbase: [serpbaseKey, setSerpbaseKey],
|
|
1008
1015
|
serply: [serplyKey, setSerplyKey],
|
|
1009
1016
|
outcrawl: [outcrawlKey, setOutcrawlKey],
|
|
1017
|
+
google: [googleKey, setGoogleKey],
|
|
1010
1018
|
you: [youcomKey, setYoucomKey],
|
|
1011
1019
|
baidu: [baiduKey, setBaiduKey],
|
|
1012
1020
|
kimi: [kimiKey, setKimiKey],
|
|
@@ -1095,6 +1103,8 @@ window.__ModuleLoader__.load({
|
|
|
1095
1103
|
setSerpbaseKey(v.serpbaseApiKey ?? "");
|
|
1096
1104
|
setSerplyKey(v.serplyApiKey ?? "");
|
|
1097
1105
|
setOutcrawlKey(v.outcrawlApiKey ?? "");
|
|
1106
|
+
setGoogleKey(v.googleCseApiKey ?? "");
|
|
1107
|
+
setGoogleCx(v.googleCseId ?? "");
|
|
1098
1108
|
setYoucomKey(v.youcomApiKey ?? "");
|
|
1099
1109
|
setBaiduKey(v.baiduApiKey ?? "");
|
|
1100
1110
|
setKimiKey(v.kimiApiKey ?? "");
|
|
@@ -1143,6 +1153,7 @@ window.__ModuleLoader__.load({
|
|
|
1143
1153
|
if (path === "jinaApiKey") configured.jina = true;
|
|
1144
1154
|
if (path === "searxngBearerToken") configured.searxng = true;
|
|
1145
1155
|
if (path === "degoogApiKey") configured.degoog = true;
|
|
1156
|
+
if (path === "googleCseApiKey") configured.google = true;
|
|
1146
1157
|
}
|
|
1147
1158
|
}
|
|
1148
1159
|
setKeysConfigured(configured);
|
|
@@ -1154,7 +1165,7 @@ window.__ModuleLoader__.load({
|
|
|
1154
1165
|
const cred = await bridgeCredentialsStatus();
|
|
1155
1166
|
if (cred.ok) {
|
|
1156
1167
|
const cc = {};
|
|
1157
|
-
const map = { anysearchApiKey: "anysearch", exaApiKey: "exa", tavilyApiKey: "tavily", keenableApiKey: "keenable", firecrawlApiKey: "firecrawl", parallelApiKey: "parallel", perplexityApiKey: "perplexity", deepseekApiKey: "deepseek", serpbaseApiKey: "serpbase", serplyApiKey: "serply", outcrawlApiKey: "outcrawl", youcomApiKey: "youcom", degoogApiKey: "degoog", baiduApiKey: "baidu", kimiApiKey: "kimi", aliyunApiKey: "aliyun", doubaoApiKey: "doubao", openaiApiKey: "openai", geminiApiKey: "gemini", claudeApiKey: "claude", zhihuApiKey: "zhihu", tinyfishApiKey: "tinyfish", jinaApiKey: "jina", searxngBearerToken: "searxng" };
|
|
1168
|
+
const map = { anysearchApiKey: "anysearch", exaApiKey: "exa", tavilyApiKey: "tavily", keenableApiKey: "keenable", firecrawlApiKey: "firecrawl", parallelApiKey: "parallel", perplexityApiKey: "perplexity", deepseekApiKey: "deepseek", serpbaseApiKey: "serpbase", serplyApiKey: "serply", outcrawlApiKey: "outcrawl", youcomApiKey: "youcom", degoogApiKey: "degoog", googleCseApiKey: "google", baiduApiKey: "baidu", kimiApiKey: "kimi", aliyunApiKey: "aliyun", doubaoApiKey: "doubao", openaiApiKey: "openai", geminiApiKey: "gemini", claudeApiKey: "claude", zhihuApiKey: "zhihu", tinyfishApiKey: "tinyfish", jinaApiKey: "jina", searxngBearerToken: "searxng" };
|
|
1158
1169
|
for (const [k, v] of Object.entries(cred.value.configured ?? {})) {
|
|
1159
1170
|
if (map[k]) cc[map[k]] = v;
|
|
1160
1171
|
}
|
|
@@ -1202,6 +1213,7 @@ window.__ModuleLoader__.load({
|
|
|
1202
1213
|
["serpbaseApiKey", serpbaseKey],
|
|
1203
1214
|
["serplyApiKey", serplyKey],
|
|
1204
1215
|
["outcrawlApiKey", outcrawlKey],
|
|
1216
|
+
["googleCseApiKey", googleKey],
|
|
1205
1217
|
["youcomApiKey", youcomKey],
|
|
1206
1218
|
["baiduApiKey", baiduKey],
|
|
1207
1219
|
["kimiApiKey", kimiKey],
|
|
@@ -1247,6 +1259,7 @@ window.__ModuleLoader__.load({
|
|
|
1247
1259
|
ops.push({ op: "set", path: ["safeSearch"], value: safeSearch });
|
|
1248
1260
|
ops.push({ op: "set", path: ["bingMarket"], value: bingMarket });
|
|
1249
1261
|
ops.push({ op: "set", path: ["fetchProviderTakeover"], value: fetchProviderTakeover });
|
|
1262
|
+
ops.push({ op: "set", path: ["googleCseId"], value: googleCx.trim() });
|
|
1250
1263
|
ops.push({ op: "set", path: ["browserFetch"], value: browserFetch });
|
|
1251
1264
|
ops.push({ op: "set", path: ["fetchPrefer"], value: fetchPrefer === "firecrawl" ? "firecrawl" : "exa" });
|
|
1252
1265
|
if (keyStorage !== "credentials") {
|
|
@@ -1994,6 +2007,33 @@ react_jsx_runtime.jsx("div", {
|
|
|
1994
2007
|
}),
|
|
1995
2008
|
],
|
|
1996
2009
|
}),
|
|
2010
|
+
react_jsx_runtime.jsx("div", {
|
|
2011
|
+
className: "dshfs-field",
|
|
2012
|
+
children: [
|
|
2013
|
+
react_jsx_runtime.jsx("div", {
|
|
2014
|
+
className: "dshfs-label",
|
|
2015
|
+
children: t.googleCseIdLabel,
|
|
2016
|
+
}),
|
|
2017
|
+
react_jsx_runtime.jsx("input", {
|
|
2018
|
+
className: "dshfs-input",
|
|
2019
|
+
type: "text",
|
|
2020
|
+
value: googleCx,
|
|
2021
|
+
spellCheck: false,
|
|
2022
|
+
placeholder: "0123456789:abcdef",
|
|
2023
|
+
disabled: !ready || saving,
|
|
2024
|
+
onChange: (e) => {
|
|
2025
|
+
setGoogleCx(e.target.value);
|
|
2026
|
+
setDirty(true);
|
|
2027
|
+
setFailed(false);
|
|
2028
|
+
setSaveError("");
|
|
2029
|
+
},
|
|
2030
|
+
}),
|
|
2031
|
+
react_jsx_runtime.jsx("p", {
|
|
2032
|
+
className: "dshfs-hint",
|
|
2033
|
+
children: t.googleCseIdHint,
|
|
2034
|
+
}),
|
|
2035
|
+
],
|
|
2036
|
+
}),
|
|
1997
2037
|
react_jsx_runtime.jsx("div", {
|
|
1998
2038
|
className: "dshfs-field",
|
|
1999
2039
|
id: "dshfs-anchor-fallback",
|
package/lib/doctor.js
CHANGED
|
@@ -55,6 +55,13 @@ export function buildDoctorReport({
|
|
|
55
55
|
}
|
|
56
56
|
const mark = engine.disabled || engine.credential?.configured === false || (engine.cooling?.remainingMs ?? 0) > 0 ? " " : "*";
|
|
57
57
|
lines.push(` ${mark} ${engine.id.padEnd(16)} ${flags.join(" · ") || "ready"}`);
|
|
58
|
+
if (engine.stats && engine.stats.calls > 0) {
|
|
59
|
+
const stats = engine.stats;
|
|
60
|
+
const last = stats.lastErrorClass ? ` · last ${stats.lastErrorClass}` : "";
|
|
61
|
+
lines.push(
|
|
62
|
+
` calls ${stats.calls} · ok ${stats.ok} · empty ${stats.empty} · fail ${stats.fail} · avg ${stats.avgMs}ms${last}`
|
|
63
|
+
);
|
|
64
|
+
}
|
|
58
65
|
}
|
|
59
66
|
|
|
60
67
|
if (engines.some((engine) => engine.cooling?.reason)) {
|
package/lib/engine_meta.js
CHANGED
|
@@ -23,6 +23,7 @@ const BASE_ENGINES = [
|
|
|
23
23
|
{ id: "serpbase", free: false, time: false },
|
|
24
24
|
{ id: "serply", free: false, time: false },
|
|
25
25
|
{ id: "outcrawl", free: false, time: false },
|
|
26
|
+
{ id: "google", free: false, time: true },
|
|
26
27
|
{ id: "deepseek-official", free: false, time: false },
|
|
27
28
|
{ id: "deepseek-tools", free: false, time: true },
|
|
28
29
|
{ id: "you", free: false, time: false },
|
|
@@ -56,6 +57,7 @@ export const TIME_ENGINES = [
|
|
|
56
57
|
"exa",
|
|
57
58
|
"keenable",
|
|
58
59
|
"firecrawl",
|
|
60
|
+
"google",
|
|
59
61
|
"parallel",
|
|
60
62
|
"searxng",
|
|
61
63
|
"degoog",
|
|
@@ -80,6 +82,7 @@ export const DEFAULT_FALLBACK_ORDER = [
|
|
|
80
82
|
"serpbase",
|
|
81
83
|
"serply",
|
|
82
84
|
"outcrawl",
|
|
85
|
+
"google",
|
|
83
86
|
"agy",
|
|
84
87
|
"deepseek-tools",
|
|
85
88
|
"deepseek-official",
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-engine concurrency limit and in-process call statistics.
|
|
3
|
+
*
|
|
4
|
+
* Multi mode and overlapping user calls can hit the same engine at once; without
|
|
5
|
+
* a gate a free HTML engine gets several requests in the same second and starts
|
|
6
|
+
* serving captchas. The stats feed the doctor report ("why is this engine not
|
|
7
|
+
* being used" plus how it has been behaving).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export function createEngineRuntime({ now = () => Date.now() } = {}) {
|
|
11
|
+
const active = new Map();
|
|
12
|
+
const waiters = new Map();
|
|
13
|
+
const stats = new Map();
|
|
14
|
+
|
|
15
|
+
const ensure = (engine) => {
|
|
16
|
+
if (!stats.has(engine)) stats.set(engine, { calls: 0, ok: 0, empty: 0, fail: 0, totalMs: 0, lastErrorClass: "" });
|
|
17
|
+
return stats.get(engine);
|
|
18
|
+
};
|
|
19
|
+
const bucket = (engine) => {
|
|
20
|
+
if (!active.has(engine)) active.set(engine, 0);
|
|
21
|
+
if (!waiters.has(engine)) waiters.set(engine, []);
|
|
22
|
+
return { waiters: waiters.get(engine), active };
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function acquire(engine, limit, signal) {
|
|
26
|
+
const state = bucket(engine);
|
|
27
|
+
if ((active.get(engine) ?? 0) < limit) {
|
|
28
|
+
active.set(engine, (active.get(engine) ?? 0) + 1);
|
|
29
|
+
return Promise.resolve();
|
|
30
|
+
}
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
const waiter = () => {
|
|
33
|
+
cleanup();
|
|
34
|
+
active.set(engine, (active.get(engine) ?? 0) + 1);
|
|
35
|
+
resolve();
|
|
36
|
+
};
|
|
37
|
+
const onAbort = () => {
|
|
38
|
+
cleanup();
|
|
39
|
+
const list = state.waiters;
|
|
40
|
+
const at = list.indexOf(waiter);
|
|
41
|
+
if (at >= 0) list.splice(at, 1);
|
|
42
|
+
reject(signal?.reason instanceof Error ? signal.reason : new Error("aborted"));
|
|
43
|
+
};
|
|
44
|
+
const cleanup = () => signal?.removeEventListener("abort", onAbort);
|
|
45
|
+
if (signal) {
|
|
46
|
+
if (signal.aborted) {
|
|
47
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error("aborted"));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
51
|
+
}
|
|
52
|
+
state.waiters.push(waiter);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function release(engine) {
|
|
57
|
+
active.set(engine, Math.max(0, (active.get(engine) ?? 1) - 1));
|
|
58
|
+
const list = waiters.get(engine) ?? [];
|
|
59
|
+
const next = list.shift();
|
|
60
|
+
if (next) next();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function run(engine, limit, fn, { signal } = {}) {
|
|
64
|
+
await acquire(engine, Math.max(1, limit), signal);
|
|
65
|
+
try {
|
|
66
|
+
return await fn();
|
|
67
|
+
} finally {
|
|
68
|
+
release(engine);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function record(engine, { ms, sources = 0, error } = {}) {
|
|
73
|
+
const entry = ensure(engine);
|
|
74
|
+
entry.calls += 1;
|
|
75
|
+
if (error) {
|
|
76
|
+
entry.fail += 1;
|
|
77
|
+
if (typeof error.class === "string") entry.lastErrorClass = error.class;
|
|
78
|
+
} else if (sources > 0) {
|
|
79
|
+
entry.ok += 1;
|
|
80
|
+
} else {
|
|
81
|
+
entry.empty += 1;
|
|
82
|
+
}
|
|
83
|
+
if (Number.isFinite(ms) && ms >= 0) entry.totalMs += ms;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function snapshot() {
|
|
87
|
+
const out = {};
|
|
88
|
+
for (const [engine, entry] of stats) {
|
|
89
|
+
out[engine] = {
|
|
90
|
+
calls: entry.calls,
|
|
91
|
+
ok: entry.ok,
|
|
92
|
+
empty: entry.empty,
|
|
93
|
+
fail: entry.fail,
|
|
94
|
+
avgMs: entry.calls > 0 ? Math.round(entry.totalMs / entry.calls) : 0,
|
|
95
|
+
lastErrorClass: entry.lastErrorClass,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return { run, record, snapshot, now };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Default limit per engine: scraped HTML pages are more fragile than APIs. */
|
|
105
|
+
export const ENGINE_CONCURRENCY_LIMIT = 2;
|
|
106
|
+
export const SERP_CONCURRENCY_LIMIT = 1;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Google Programmable Search (Custom Search JSON API).
|
|
2
|
+
// Needs both an API key (GOOGLE_CSE_API_KEY / settings googleCseApiKey) and the
|
|
3
|
+
// search engine ID (cx / config googleCseId). Free tier: 100 queries/day.
|
|
4
|
+
import { uniqueSources } from "./shared.js";
|
|
5
|
+
|
|
6
|
+
const GOOGLE_CSE_URL = "https://www.googleapis.com/customsearch/v1";
|
|
7
|
+
const MAX_RESULTS = 30;
|
|
8
|
+
const PAGE_SIZE = 10;
|
|
9
|
+
|
|
10
|
+
const HL_BY_LANG = {
|
|
11
|
+
zh: "zh-CN",
|
|
12
|
+
en: "en",
|
|
13
|
+
ru: "ru",
|
|
14
|
+
ja: "ja",
|
|
15
|
+
de: "de",
|
|
16
|
+
fr: "fr",
|
|
17
|
+
es: "es",
|
|
18
|
+
ko: "ko",
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** Map our normalized timeRange to the CSE dateRestrict grammar. */
|
|
22
|
+
export function googleDateRestrict(timeRange) {
|
|
23
|
+
if (!timeRange) return "";
|
|
24
|
+
if (timeRange.after) return "";
|
|
25
|
+
const days = Number(timeRange.days);
|
|
26
|
+
if (!Number.isFinite(days) || days <= 0) return "";
|
|
27
|
+
if (days <= 31) return `d${Math.max(1, Math.ceil(days))}`;
|
|
28
|
+
if (days <= 365) return `m${Math.max(1, Math.ceil(days / 30))}`;
|
|
29
|
+
return `y${Math.max(1, Math.ceil(days / 365))}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function googleErrorMessage(status, detail) {
|
|
33
|
+
let upstream = "";
|
|
34
|
+
try {
|
|
35
|
+
upstream = JSON.parse(detail)?.error?.message ?? "";
|
|
36
|
+
} catch {}
|
|
37
|
+
const suffix = upstream ? `: ${upstream.slice(0, 200)}` : "";
|
|
38
|
+
if (status === 400) {
|
|
39
|
+
return `Google Custom Search request failed (HTTP 400)${suffix} - check GOOGLE_CSE_API_KEY and googleCseId`;
|
|
40
|
+
}
|
|
41
|
+
if (status === 401 || status === 403) {
|
|
42
|
+
return `Google API key is invalid, or the Custom Search API is not enabled for it (HTTP ${status})${suffix}`;
|
|
43
|
+
}
|
|
44
|
+
if (status === 429) return `Google Custom Search quota exceeded (HTTP 429)${suffix}`;
|
|
45
|
+
return `Google API error (HTTP ${status})${suffix}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function searchGoogle(query, maxResults, apiKey, cseId, timeRange, options, signal) {
|
|
49
|
+
if (!apiKey) throw new Error("Google search requires GOOGLE_CSE_API_KEY");
|
|
50
|
+
if (!cseId) throw new Error("Google Custom Search requires a Programmable Search Engine ID (googleCseId)");
|
|
51
|
+
const limit = Math.min(Math.max(Number(maxResults) || 10, 1), MAX_RESULTS);
|
|
52
|
+
|
|
53
|
+
const controller = new AbortController();
|
|
54
|
+
const timer = setTimeout(() => controller.abort(), 20000);
|
|
55
|
+
const onAbort = () => controller.abort();
|
|
56
|
+
signal?.addEventListener("abort", onAbort);
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
const sources = [];
|
|
60
|
+
for (let start = 1; start <= limit; start += PAGE_SIZE) {
|
|
61
|
+
const num = Math.min(PAGE_SIZE, limit - sources.length);
|
|
62
|
+
const params = new URLSearchParams({
|
|
63
|
+
key: apiKey,
|
|
64
|
+
cx: cseId,
|
|
65
|
+
q: query,
|
|
66
|
+
num: String(num),
|
|
67
|
+
start: String(start),
|
|
68
|
+
fields: "items(title,link,snippet,pagemap/metatags)",
|
|
69
|
+
});
|
|
70
|
+
const hl = HL_BY_LANG[String(options?.lang ?? "").toLowerCase()];
|
|
71
|
+
if (hl) params.set("hl", hl);
|
|
72
|
+
if (options?.safeSearch && options.safeSearch !== "off") params.set("safe", "active");
|
|
73
|
+
const dateRestrict = googleDateRestrict(timeRange);
|
|
74
|
+
if (dateRestrict) params.set("dateRestrict", dateRestrict);
|
|
75
|
+
|
|
76
|
+
let response;
|
|
77
|
+
try {
|
|
78
|
+
response = await fetch(`${GOOGLE_CSE_URL}?${params}`, {
|
|
79
|
+
signal: controller.signal,
|
|
80
|
+
redirect: "error",
|
|
81
|
+
});
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (signal?.aborted) throw error;
|
|
84
|
+
throw new Error(`Google request failed: ${error?.message ?? String(error)}`);
|
|
85
|
+
}
|
|
86
|
+
if (!response.ok) {
|
|
87
|
+
const detail = await response.text().catch(() => "");
|
|
88
|
+
throw new Error(googleErrorMessage(response.status, detail));
|
|
89
|
+
}
|
|
90
|
+
const data = await response.json();
|
|
91
|
+
const items = Array.isArray(data.items) ? data.items : [];
|
|
92
|
+
for (const item of items) {
|
|
93
|
+
if (!item || typeof item.link !== "string" || !item.link) continue;
|
|
94
|
+
const metatags = item.pagemap?.metatags?.[0] ?? {};
|
|
95
|
+
const published = metatags["article:published_time"] ?? metatags["og:updated_time"] ?? "";
|
|
96
|
+
sources.push({
|
|
97
|
+
url: item.link,
|
|
98
|
+
...(item.title ? { title: String(item.title) } : {}),
|
|
99
|
+
...(item.snippet ? { snippet: String(item.snippet) } : {}),
|
|
100
|
+
...(typeof published === "string" && /^\d{4}-\d{2}-\d{2}/.test(published)
|
|
101
|
+
? { publishedAt: published.slice(0, 10) }
|
|
102
|
+
: {}),
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
if (items.length < num) break;
|
|
106
|
+
}
|
|
107
|
+
return { sources: uniqueSources(sources, limit), truncated: false };
|
|
108
|
+
} finally {
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
signal?.removeEventListener("abort", onAbort);
|
|
111
|
+
}
|
|
112
|
+
}
|