@nite07/dsh-search 0.0.0-stage → 0.1.1

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/dist/index.js ADDED
@@ -0,0 +1,968 @@
1
+ // src/index.ts
2
+ import z2 from "@deepseek-ai/schemastery";
3
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
+ import "@deepseek-ai/dsh-config-editor";
5
+
6
+ // src/catalog.ts
7
+ var text = (en, zh) => ({ en, zh });
8
+ var option = (key, label, zh, value, choices) => ({ key, type: choices ? "select" : typeof value, label: text(label, zh), help: text(`Native ${key} parameter. See the backend documentation.`, `\u539F\u751F ${key} \u53C2\u6570\uFF0C\u8BE6\u89C1\u540E\u7AEF\u6587\u6863\u3002`), default: value, ...choices ? { choices } : {} });
9
+ var mode = (access, endpoint, tier, en, zh, pricingUrl) => ({ mode: access, endpoint, tier, limits: text(en, zh), pricingUrl });
10
+ var backend = (id, title, docs, modes, options = [], capabilities = [], status = "documented", evidence = "documented") => ({ id, title, docs, modes, options, capabilities, status, evidence, verifiedAt: "2026-11-17" });
11
+ var catalog = [
12
+ backend("keenable", "Keenable", "https://docs.keenable.ai/api-reference/search.md", [mode("anonymous", "https://api.keenable.ai/v1/search/public", "free", "1,000 requests/hour and 10/second per IP/endpoint; public title header required.", "\u6BCF IP\uFF0F\u7AEF\u70B9 1000 \u6B21/\u5C0F\u65F6\u300110 \u6B21/\u79D2\uFF1B\u9700\u8981\u516C\u5F00\u8C03\u7528\u6807\u8BC6\u3002", "https://docs.keenable.ai/pricing.md"), mode("key", "https://api.keenable.ai/v1/search", "allowance", "100,000 searches/month free; then $4/1,000. Confirm current account terms.", "\u6BCF\u6708 10 \u4E07\u6B21\u514D\u8D39\uFF0C\u5176\u540E $4/\u5343\u6B21\uFF1B\u4EE5\u8D26\u6237\u5F53\u524D\u6761\u6B3E\u4E3A\u51C6\u3002", "https://docs.keenable.ai/pricing.md")], [option("clientTitle", "Client title", "\u8C03\u7528\u65B9\u540D\u79F0", "dsh-search"), option("snippet_max_length", "Snippet maximum length", "\u6458\u8981\u6700\u5927\u957F\u5EA6", 2e3)], ["includeDomains"], "documented", "live"),
13
+ backend("anysearch", "AnySearch", "https://anysearch.com/docs/api-endpoints/v1-search.md", [mode("anonymous", "https://api.anysearch.com/v1/search", "free", "Anonymous access needs no key, metered per IP with lower rate limits and a daily free reset (UTC). No account or credential is created automatically.", "\u533F\u540D\u8BBF\u95EE\u65E0\u9700\u5BC6\u94A5\uFF0C\u6309 IP \u8BA1\u91CF\u3001\u9650\u6D41\u66F4\u4F4E\u3001\u6BCF\u65E5\uFF08UTC\uFF09\u91CD\u7F6E\uFF1B\u4E0D\u4F1A\u81EA\u52A8\u521B\u5EFA\u8D26\u6237\u6216\u5BC6\u94A5\u3002", "https://anysearch.com/pricing.md"), mode("key", "https://api.anysearch.com/v1/search", "allowance", "Free plan: 1,000/day, 10 QPS; Pro calls have separate pricing.", "\u514D\u8D39\u6863 1000 \u6B21/\u5929\u300110 QPS\uFF1BPro \u8C03\u7528\u53E6\u884C\u8BA1\u8D39\u3002", "https://anysearch.com/pricing.md")], [option("zone", "Zone", "\u641C\u7D22\u533A\u57DF", "intl", ["intl", "cn"])], ["language"], "documented", "live"),
14
+ backend("linkup", "Linkup", "https://docs.linkup.so/pages/documentation/endpoints/search/reference.md", [mode("key", "https://api.linkup.so/v1/search", "allowance", "Eligible professional email accounts may receive $20/month. Raw search: $0.005/call; deep $0.05/call.", "\u7B26\u5408\u8D44\u683C\u7684\u4E13\u4E1A\u90AE\u7BB1\u8D26\u6237\u53EF\u80FD\u4EAB\u6709\u6BCF\u6708 $20\uFF1B\u666E\u901A\u641C\u7D22 $0.005/\u6B21\uFF0Cdeep $0.05/\u6B21\u3002", "https://docs.linkup.so/pages/documentation/platform/pricing.md")], [option("depth", "Search depth", "\u641C\u7D22\u6DF1\u5EA6", "standard", ["flash", "fast", "standard", "deep"])]),
15
+ backend("tavily", "Tavily", "https://docs.tavily.com/documentation/api-reference/endpoint/search", [mode("key", "https://api.tavily.com/search", "allowance", "1,000 free credits/month; basic 1 credit, advanced 2. PAYG $0.008/credit.", "\u6BCF\u6708\u514D\u8D39 1000 credits\uFF1Bbasic 1 credit\uFF0Cadvanced 2\uFF1B\u6309\u91CF $0.008/credit\u3002", "https://www.tavily.com/pricing")], [option("search_depth", "Search depth", "\u641C\u7D22\u6DF1\u5EA6", "basic", ["basic", "advanced"]), option("topic", "Topic", "\u4E3B\u9898", "general", ["general", "news", "finance"]), option("include_answer", "Include answer", "\u5305\u542B\u7B54\u6848", false)], ["includeDomains", "excludeDomains", "recency"]),
16
+ backend("exa", "Exa", "https://docs.exa.ai/reference/search", [mode("anonymous", "https://mcp.exa.ai/mcp", "free", "Official free keyless MCP: no API key or sign-in, search and fetch at a free rate limit (no published number). Keyless needs a direct IPv4 connection; proxied or IPv6 paths get 403. Result quality and latency were the best of the free tiers in local testing.", "\u5B98\u65B9\u514D\u8D39\u65E0 Key MCP\uFF1A\u65E0\u9700\u5BC6\u94A5\u6216\u767B\u5F55\uFF0C\u641C\u7D22\u4E0E\u6293\u53D6\u6309\u514D\u8D39\u9650\u6D41\uFF08\u672A\u516C\u5E03\u6570\u503C\uFF09\u3002\u65E0 Key \u9700\u8981\u76F4\u8FDE IPv4\uFF0C\u4EE3\u7406\u6216 IPv6 \u8DEF\u5F84\u4F1A\u8FD4\u56DE 403\u3002\u672C\u673A\u5B9E\u6D4B\u4E2D\u5176\u8D28\u91CF\u4E0E\u5EF6\u8FDF\u5728\u514D\u8D39\u6863\u91CC\u6700\u597D\u3002", "https://exa.ai/docs/get-started/exa-mcp"), mode("key", "https://api.exa.ai/search", "allowance", "$10 balance reset monthly; auto search $7/1,000 up to 10 results, extra results cost more.", "\u6BCF\u6708\u4F59\u989D\u91CD\u7F6E\u4E3A $10\uFF1Bauto \u641C\u7D22 $7/\u5343\u6B21\uFF08\u6700\u591A 10 \u7ED3\u679C\uFF09\uFF0C\u989D\u5916\u7ED3\u679C\u53E6\u8BA1\u8D39\u3002", "https://exa.ai/pricing")], [option("type", "Search type", "\u641C\u7D22\u7C7B\u578B", "auto", ["auto", "neural", "fast"]), option("textMaxCharacters", "Text maximum characters", "\u6B63\u6587\u6700\u5927\u5B57\u7B26\u6570", 2e3)], ["includeDomains", "excludeDomains", "recency"], "documented", "live"),
17
+ backend("parallel", "Parallel", "https://docs.parallel.ai/search/search-quickstart", [mode("anonymous", "https://mcp.parallel.ai/mcp", "free", "Free anonymous MCP with lower rate limits; numeric quota is not published.", "\u514D\u8D39\u533F\u540D MCP\uFF0C\u9650\u6D41\u66F4\u4F4E\uFF1B\u6570\u503C\u989D\u5EA6\u672A\u516C\u5E03\u3002", "https://parallel.ai/pricing"), mode("key", "https://api.parallel.ai/v1/search", "paid", "API usage is billed under account pricing; credits are not guaranteed.", "API \u6309\u8D26\u6237\u4EF7\u683C\u8BA1\u8D39\uFF0C\u4E0D\u4FDD\u8BC1\u8D60\u9001\u989D\u5EA6\u3002", "https://parallel.ai/pricing")], [option("mode", "Search mode", "\u641C\u7D22\u6A21\u5F0F", "fast", ["fast", "turbo", "basic", "advanced"]), option("maxCharactersPerResult", "Maximum characters per result", "\u6BCF\u6761\u7ED3\u679C\u6700\u5927\u5B57\u7B26\u6570", 2e3)], [], "documented", "live"),
18
+ backend("brave", "Brave Search", "https://api-dashboard.search.brave.com/app/documentation/web-search/get-started", [mode("key", "https://api.search.brave.com/res/v1/web/search", "allowance", "$5 monthly credits; $5/1,000 searches, 50 QPS. Check card/activation requirements.", "\u6BCF\u6708 $5 credits\uFF1B$5/\u5343\u6B21\u641C\u7D22\u300150 QPS\uFF1B\u9700\u6838\u5BF9\u7ED1\u5361\u4E0E\u6FC0\u6D3B\u8981\u6C42\u3002", "https://brave.com/search/api/")], [], ["language", "region", "recency", "safeSearch"]),
19
+ backend("searxng", "SearXNG", "https://docs.searxng.org/dev/search_api.html", [mode("anonymous", "http://127.0.0.1:8385/search", "self-hosted", "No vendor per-call fee; infrastructure costs and instance rate limits apply. JSON output must be enabled.", "\u65E0\u5382\u5546\u8C03\u7528\u8D39\uFF0C\u6709\u81EA\u5EFA\u8FD0\u884C\u6210\u672C\u53CA\u5B9E\u4F8B\u9650\u6D41\uFF1B\u9700\u5F00\u542F JSON \u8F93\u51FA\u3002", "https://docs.searxng.org/"), mode("key", "http://127.0.0.1:8385/search", "self-hosted", "For an instance explicitly protected by a Bearer-auth gateway; not a native SearXNG API-key feature.", "\u4EC5\u9002\u7528\u4E8E\u81EA\u884C\u914D\u7F6E Bearer \u9274\u6743\u7F51\u5173\u7684\u5B9E\u4F8B\uFF1B\u4E0D\u662F SearXNG \u539F\u751F Key \u529F\u80FD\u3002", "https://docs.searxng.org/")], [option("engines", "Engines", "\u5F15\u64CE\u5217\u8868", ""), option("categories", "Categories", "\u5206\u7C7B", "general")], ["language", "recency", "safeSearch"], "documented", "live"),
20
+ backend("ddg", "DuckDuckGo", "https://duckduckgo.com/duckduckgo-help-pages/results/syndication/", [mode("anonymous", "https://html.duckduckgo.com/html/", "free", "HTML discovery, no SLA or guaranteed quota; blocking/challenges may occur.", "HTML \u641C\u7D22\uFF0C\u65E0 SLA \u6216\u4FDD\u8BC1\u989D\u5EA6\uFF1B\u53EF\u80FD\u9650\u6D41\u6216\u51FA\u73B0\u9A8C\u8BC1\u7801\u3002", "https://duckduckgo.com/")]),
21
+ backend("mojeek", "Mojeek", "https://www.mojeek.com/services/search/web-search-api/", [mode("key", "https://api.mojeek.com/search", "paid", "API plan pricing applies. Do not assume a perpetual free quota.", "\u6309 API \u5957\u9910\u8BA1\u8D39\uFF0C\u4E0D\u627F\u8BFA\u957F\u671F\u514D\u8D39\u989D\u5EA6\u3002", "https://www.mojeek.com/services/search/web-search-api/")], [], []),
22
+ backend("anthropic", "Anthropic", "https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool", [mode("key", "https://api.anthropic.com/v1/messages", "paid", "Web search fees plus model input/output tokens.", "\u641C\u7D22\u5DE5\u5177\u8D39\u7528\u52A0\u6A21\u578B\u8F93\u5165\uFF0F\u8F93\u51FA token \u8D39\u7528\u3002", "https://platform.claude.com/docs/en/about-claude/pricing")], [option("model", "Model", "\u6A21\u578B", "claude-sonnet-4-6"), option("maxTokens", "Maximum output tokens", "\u6700\u5927\u8F93\u51FA tokens", 2048), option("maxUses", "Maximum search uses", "\u6700\u591A\u641C\u7D22\u6B21\u6570", 1)], ["includeDomains", "excludeDomains"]),
23
+ backend("openai", "OpenAI", "https://platform.openai.com/docs/guides/tools-web-search", [mode("key", "https://api.openai.com/v1/responses", "paid", "Web search/tool charges plus model tokens; account terms apply.", "\u641C\u7D22\u5DE5\u5177\u4E0E\u6A21\u578B token \u5206\u522B\u8BA1\u8D39\uFF0C\u4EE5\u8D26\u6237\u6761\u6B3E\u4E3A\u51C6\u3002", "https://openai.com/api/pricing/")], [option("model", "Model", "\u6A21\u578B", "gpt-4.1"), option("maxOutputTokens", "Maximum output tokens", "\u6700\u5927\u8F93\u51FA tokens", 2048)]),
24
+ backend("zhihu-web", "Zhihu global search", "https://developer.zhihu.com/docs?key=global_search", [mode("key", "https://developer.zhihu.com/api/v1/content/global_search", "allowance", "Limited-time daily free allowance shown in account console; then \xA55/1,000. Resets at 00:00 Asia/Shanghai.", "\u9650\u65F6\u6BCF\u65E5\u989D\u5EA6\u4EE5\u63A7\u5236\u53F0\u4E3A\u51C6\uFF0C\u5176\u540E \xA55/\u5343\u6B21\uFF1B\u5317\u4EAC\u65F6\u95F4\u96F6\u70B9\u91CD\u7F6E\u3002", "https://developer.zhihu.com/docs?key=billing_price")], [option("SearchDB", "Search database", "\u641C\u7D22\u6570\u636E\u5E93", "all", ["all", "realtime", "static"]), option("Filter", "Native filter expression", "\u539F\u751F\u7B5B\u9009\u8868\u8FBE\u5F0F", "")]),
25
+ backend("zhihu-site", "Zhihu site search", "https://developer.zhihu.com/docs?key=zhihu_search", [mode("key", "https://developer.zhihu.com/api/v1/content/zhihu_search", "allowance", "Limited-time daily allowance shown in account console; then \xA520/1,000. Shared across account secrets.", "\u9650\u65F6\u6BCF\u65E5\u989D\u5EA6\u4EE5\u63A7\u5236\u53F0\u4E3A\u51C6\uFF0C\u5176\u540E \xA520/\u5343\u6B21\uFF1B\u540C\u8D26\u6237\u5BC6\u94A5\u5171\u4EAB\u989D\u5EA6\u3002", "https://developer.zhihu.com/docs?key=billing_price")]),
26
+ backend("deepseek", "DeepSeek", "https://api-docs.deepseek.com/guides/search/", [mode("key", "https://api.deepseek.com/v1/tools/search", "paid", "$0.75/1,000 successful nonempty requests; 100 QPS/account.", "$0.75/\u5343\u6B21\u6210\u529F\u4E14\u975E\u7A7A\u8BF7\u6C42\uFF1B\u6BCF\u8D26\u6237 100 QPS\u3002", "https://api-docs.deepseek.com/guides/search/")], [option("need_content", "Retrieve content", "\u83B7\u53D6\u6B63\u6587", false)]),
27
+ backend("you", "You.com", "https://you.com/docs/api-reference/search/v1-search.md", [mode("anonymous", "https://api.you.com/mcp", "free", "Free MCP profile: 100 queries/day; shared rate limits may apply.", "\u514D\u8D39 MCP profile\uFF1A100 \u6B21/\u5929\uFF0C\u53EF\u80FD\u5B58\u5728\u5171\u4EAB\u9650\u6D41\u3002", "https://you.com/docs/agents/mcp-server.md"), mode("key", "https://ydc-index.io/v1/search", "paid", "$5/1,000 searches; optional full-page retrieval costs extra.", "$5/\u5343\u6B21\u641C\u7D22\uFF1B\u53EF\u9009\u5168\u6587\u83B7\u53D6\u53E6\u5916\u8BA1\u8D39\u3002", "https://you.com/docs/administration/billing.md")], [], ["language", "region", "recency"], "documented", "live"),
28
+ backend("baidu", "Baidu Qianfan", "https://cloud.baidu.cn/doc/qianfan/s/nmweljpt3", [mode("key", "https://qianfan.baidubce.com/v2/ai_search/web_search", "allowance", "1,500/month free, default 3 QPS; domestic standard \xA50.036/request, higher editions cost more.", "\u6BCF\u6708 1500 \u6B21\u514D\u8D39\uFF0C\u9ED8\u8BA4 3 QPS\uFF1B\u56FD\u5185 standard \xA50.036/\u6B21\uFF0C\u66F4\u9AD8\u7248\u672C\u4EF7\u683C\u66F4\u9AD8\u3002", "https://cloud.baidu.cn/doc/qianfan/s/nmweljpt3")], [option("edition", "Edition", "\u7248\u672C", "standard", ["standard", "enhanced", "flagship"])]),
29
+ backend("doubao", "Volcengine Doubao", "https://docs.volcengine.com/docs/networked-search/networked-search?lang=zh", [mode("key", "https://open.feedcoopapi.com/search_api/web_search", "allowance", "500/month shared free allowance, 10 QPS; usage-based web \xA50.020/request. Subscription keys have independent limits.", "\u6BCF\u6708\u5171\u4EAB 500 \u6B21\u514D\u8D39\uFF0C10 QPS\uFF1B\u6309\u91CF web \xA50.020/\u6B21\uFF1B\u8BA2\u9605 Key \u6709\u72EC\u7ACB\u9650\u5236\u3002", "https://docs.volcengine.com/docs/networked-search/online-search-product-billing?lang=zh")], [option("queryRewrite", "Provider query rewrite", "\u4F9B\u5E94\u5546\u6539\u5199\u67E5\u8BE2", false)]),
30
+ backend("open-websearch", "open-websearch", "https://github.com/Aas-ee/open-webSearch", [mode("anonymous", "http://127.0.0.1:3210/search", "self-hosted", "Self-hosted daemon; no guaranteed quota, engine blocking and infrastructure costs apply. Project personal-use restrictions apply.", "\u81EA\u5EFA daemon\uFF0C\u65E0\u4FDD\u8BC1\u989D\u5EA6\uFF1B\u6709\u5F15\u64CE\u9650\u6D41\u53CA\u8FD0\u884C\u6210\u672C\uFF0C\u6CE8\u610F\u9879\u76EE\u4E2A\u4EBA\u4F7F\u7528\u9650\u5236\u3002", "https://github.com/Aas-ee/open-webSearch")], [option("engine", "Fixed upstream engine", "\u56FA\u5B9A\u4E0A\u6E38\u5F15\u64CE", "duckduckgo"), option("searchMode", "Request strategy", "\u8BF7\u6C42\u65B9\u5F0F", "request", ["request", "playwright"])]),
31
+ backend("serpex", "Serpex", "https://serpex.dev/docs/api/search", [mode("key", "https://api.serpex.dev/api/search", "trial", "200 one-time credits; paid top-ups start around $0.80/1,000. Vendor routes internally; no fixed upstream engine.", "\u4E00\u6B21\u6027 200 credits\uFF1B\u5145\u503C\u7EA6 $0.80/\u5343\u6B21\u8D77\uFF1B\u4F9B\u5E94\u5546\u5185\u90E8\u8DEF\u7531\uFF0C\u4E0D\u80FD\u56FA\u5B9A\u5176\u4E0A\u6E38\u5F15\u64CE\u3002", "https://serpex.dev/docs/getting-started/pricing")]),
32
+ backend("tencent-wsa", "Tencent Cloud WSA", "https://cloud.tencent.com/document/product/1806/121811", [mode("key", "https://wsa.tencentcloudapi.com/", "paid", "\xA514/\xA520/\xA526 per 1,000 by tier. Store a JSON credential {secretId,secretKey}; no free allowance verified.", "\u5206\u6863 \xA514\uFF0F\xA520\uFF0F\xA526 \u6BCF\u5343\u6B21\u3002\u51ED\u8BC1\u586B\u5199 JSON {secretId,secretKey}\uFF1B\u514D\u8D39\u989D\u5EA6\u672A\u6838\u5B9E\u3002", "https://cloud.tencent.com/product/wsa")], [{ ...option("Mode", "Search mode", "\u641C\u7D22\u6A21\u5F0F", 0), min: 0, max: 2 }])
33
+ ];
34
+
35
+ // src/locale-map.ts
36
+ var LANGUAGES = ["", "en", "zh-Hans", "zh-Hant", "ja", "ko", "fr", "de", "es", "pt", "ru", "it", "ar", "nl", "pl", "tr", "vi", "th", "id"];
37
+ var REGIONS = ["", "US", "GB", "CN", "HK", "TW", "JP", "KR", "SG", "IN", "AU", "CA", "DE", "FR", "ES", "IT", "NL", "BR", "MX", "RU", "TR", "SA"];
38
+ var isLanguage = (value) => LANGUAGES.includes(value);
39
+ var isRegion = (value) => REGIONS.includes(value);
40
+ function languageFor(backendId, code) {
41
+ if (!code || !isLanguage(code)) return void 0;
42
+ switch (backendId) {
43
+ case "brave":
44
+ return code.toLowerCase();
45
+ case "serper":
46
+ return code === "zh-Hans" ? "zh-cn" : code === "zh-Hant" ? "zh-tw" : code.toLowerCase();
47
+ case "searxng":
48
+ return code === "zh-Hans" ? "zh-CN" : code === "zh-Hant" ? "zh-TW" : code;
49
+ case "anysearch":
50
+ return code.split("-")[0].toLowerCase();
51
+ case "you":
52
+ return code.split("-")[0].toUpperCase();
53
+ default:
54
+ return void 0;
55
+ }
56
+ }
57
+ function regionFor(backendId, code) {
58
+ if (!code || !isRegion(code)) return void 0;
59
+ switch (backendId) {
60
+ case "brave":
61
+ return code;
62
+ case "serper":
63
+ return code.toLowerCase();
64
+ case "you":
65
+ return code;
66
+ default:
67
+ return void 0;
68
+ }
69
+ }
70
+
71
+ // src/config.ts
72
+ function defaultConfig() {
73
+ return {
74
+ mode: "parallel",
75
+ singleBackend: "keenable",
76
+ maxResults: 8,
77
+ concurrency: 4,
78
+ overallTimeoutMs: 3e4,
79
+ language: "",
80
+ region: "",
81
+ recency: "any",
82
+ safeSearch: true,
83
+ includeDomains: [],
84
+ excludeDomains: [],
85
+ dedup: "url",
86
+ fusion: "rrf",
87
+ retry: { enabled: true, statuses: [408, 429, 500, 502, 503, 504], maxRetries: 2, initialDelayMs: 500, maxDelayMs: 5e3, networkErrors: false, timeouts: false },
88
+ cache: { enabled: true, ttlSeconds: 900, maxEntries: 100 },
89
+ breaker: { enabled: false, threshold: 3, cooldownMs: 6e4 },
90
+ diagnostics: { enabled: true, maxEntries: 50 },
91
+ backends: Object.fromEntries(catalog.map((d) => [d.id, { enabled: false, mode: d.modes[0].mode, endpoint: d.modes[0].endpoint, credentialRef: `DSH_SEARCH_${d.id.replaceAll("-", "_").toUpperCase()}_KEY`, timeoutMs: 15e3, rateLimitPerMinute: 0, dailyAttemptLimit: 0, options: Object.fromEntries(d.options.map((o) => [o.key, o.default])) }]))
92
+ };
93
+ }
94
+ function validateConfig(value) {
95
+ const issues = [];
96
+ const fail = (path, message) => issues.push({ path, message });
97
+ const object2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
98
+ if (!object2(value)) return [{ path: "config", message: "Expected a configuration object." }];
99
+ function shape(v, exemplar, path) {
100
+ if (Array.isArray(exemplar)) {
101
+ if (!Array.isArray(v)) {
102
+ fail(path, "Expected an array.");
103
+ return;
104
+ }
105
+ if (v.length > 200) fail(path, "Too many entries.");
106
+ if (path === "retry.statuses") {
107
+ if (v.some((n) => !Number.isInteger(n) || n < 400 || n > 599)) fail(path, "Expected HTTP error status codes (400\u2013599).");
108
+ } else if (v.some((x) => typeof x !== "string" || x.length > 253 || !/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/.test(x))) fail(path, "Expected domain names without scheme, path, or wildcards.");
109
+ } else if (object2(exemplar)) {
110
+ if (!object2(v)) {
111
+ fail(path, "Expected an object.");
112
+ return;
113
+ }
114
+ for (const k of Object.keys(v)) if (!(k in exemplar) && path !== "backends") fail(path ? `${path}.${k}` : k, "Unknown configuration field.");
115
+ for (const [k, e] of Object.entries(exemplar)) shape(v[k], e, path ? `${path}.${k}` : k);
116
+ } else if (typeof v !== typeof exemplar || typeof v === "number" && !Number.isFinite(v)) fail(path, `Expected ${typeof exemplar}.`);
117
+ else if (typeof v === "string" && v.length > 4096) fail(path, "Value is too long.");
118
+ }
119
+ shape(value, defaultConfig(), "");
120
+ if (issues.length) return issues;
121
+ const c = value;
122
+ const choice = (v, allowed, p) => {
123
+ if (!allowed.includes(v)) fail(p, "Unsupported selection.");
124
+ };
125
+ const num = (v, min, max, p) => {
126
+ if (!Number.isInteger(v) || v < min || v > max) fail(p, `Expected an integer between ${min} and ${max}.`);
127
+ };
128
+ if (c.language && !LANGUAGES.includes(c.language)) fail("language", "Unsupported language code.");
129
+ if (c.region && !REGIONS.includes(c.region)) fail("region", "Unsupported region code.");
130
+ choice(c.mode, ["single", "parallel"], "mode");
131
+ choice(c.singleBackend, catalog.map((x) => x.id), "singleBackend");
132
+ choice(c.recency, ["any", "day", "week", "month", "year"], "recency");
133
+ choice(c.dedup, ["url", "url-title"], "dedup");
134
+ choice(c.fusion, ["rrf", "ordered"], "fusion");
135
+ num(c.maxResults, 1, 50, "maxResults");
136
+ num(c.concurrency, 1, 20, "concurrency");
137
+ num(c.overallTimeoutMs, 1e3, 18e4, "overallTimeoutMs");
138
+ num(c.retry.maxRetries, 0, 5, "retry.maxRetries");
139
+ num(c.retry.initialDelayMs, 0, 6e4, "retry.initialDelayMs");
140
+ num(c.retry.maxDelayMs, 0, 12e4, "retry.maxDelayMs");
141
+ if (c.retry.initialDelayMs > c.retry.maxDelayMs) fail("retry.maxDelayMs", "Maximum delay must not be shorter than initial delay.");
142
+ num(c.cache.ttlSeconds, 1, 86400, "cache.ttlSeconds");
143
+ num(c.cache.maxEntries, 1, 1e3, "cache.maxEntries");
144
+ num(c.breaker.threshold, 1, 100, "breaker.threshold");
145
+ num(c.breaker.cooldownMs, 1e3, 36e5, "breaker.cooldownMs");
146
+ num(c.diagnostics.maxEntries, 1, 500, "diagnostics.maxEntries");
147
+ for (const d of catalog) {
148
+ const b = c.backends[d.id];
149
+ const p = `backends.${d.id}`;
150
+ choice(b.mode, d.modes.map((m) => m.mode), `${p}.mode`);
151
+ if (b.enabled && d.status === "unverified") fail(`${p}.enabled`, "Backend protocol is not verified.");
152
+ if (b.endpoint) {
153
+ try {
154
+ const url = new URL(b.endpoint);
155
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || url.search) throw 0;
156
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
157
+ if (url.protocol === "http:" && !local) throw 0;
158
+ } catch {
159
+ fail(`${p}.endpoint`, "Use an HTTPS endpoint without credentials, query, or fragment; HTTP is allowed only on loopback.");
160
+ }
161
+ } else if (b.enabled) fail(`${p}.endpoint`, "An endpoint is required.");
162
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(b.credentialRef)) fail(`${p}.credentialRef`, "Expected an environment-style credential reference.");
163
+ num(b.timeoutMs, 1e3, 12e4, `${p}.timeoutMs`);
164
+ num(b.rateLimitPerMinute, 0, 1e5, `${p}.rateLimitPerMinute`);
165
+ num(b.dailyAttemptLimit, 0, 1e6, `${p}.dailyAttemptLimit`);
166
+ for (const o of d.options) {
167
+ const v = b.options[o.key];
168
+ if (o.choices && !o.choices.includes(String(v))) fail(`${p}.options.${o.key}`, "Unsupported option.");
169
+ if (typeof v === "number") num(v, o.min ?? 1, o.max ?? 1e5, `${p}.options.${o.key}`);
170
+ }
171
+ }
172
+ return issues;
173
+ }
174
+ function parseConfig(value) {
175
+ const defaults = defaultConfig();
176
+ if (value && typeof value === "object" && !Array.isArray(value) && value.backends && typeof value.backends === "object") {
177
+ const raw = structuredClone(value);
178
+ for (const id of Object.keys(raw.backends)) if (!(id in defaults.backends)) delete raw.backends[id];
179
+ for (const [id, fallback] of Object.entries(defaults.backends)) if (!raw.backends[id]) raw.backends[id] = fallback;
180
+ value = raw;
181
+ }
182
+ const issues = validateConfig(value);
183
+ if (issues.length) throw new Error(issues.map((x) => `${x.path}: ${x.message}`).join("\n"));
184
+ return structuredClone(value);
185
+ }
186
+
187
+ // src/engine.ts
188
+ import { createHash as createHash2 } from "node:crypto";
189
+
190
+ // src/transport.ts
191
+ var SearchError = class extends Error {
192
+ constructor(kind, message, status, attempts = 0) {
193
+ super(message);
194
+ this.kind = kind;
195
+ this.status = status;
196
+ this.attempts = attempts;
197
+ this.name = "SearchError";
198
+ }
199
+ kind;
200
+ status;
201
+ attempts;
202
+ };
203
+ function abortError(signal) {
204
+ return new SearchError(signal.reason instanceof DOMException && signal.reason.name === "TimeoutError" ? "timeout" : "cancelled", "Request stopped by cancellation or deadline.");
205
+ }
206
+ async function delay(ms, signal) {
207
+ if (signal.aborted) throw abortError(signal);
208
+ await new Promise((resolve, reject) => {
209
+ const stop = () => {
210
+ clearTimeout(timer);
211
+ reject(abortError(signal));
212
+ };
213
+ const timer = setTimeout(() => {
214
+ signal.removeEventListener("abort", stop);
215
+ resolve();
216
+ }, ms);
217
+ signal.addEventListener("abort", stop, { once: true });
218
+ });
219
+ }
220
+ function retryAfter(value, now = Date.now()) {
221
+ if (!value) return;
222
+ const seconds = Number(value);
223
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
224
+ const time = Date.parse(value);
225
+ if (Number.isFinite(time)) return Math.max(0, time - now);
226
+ }
227
+ async function requestText(url, init, options) {
228
+ const fetcher = options.fetch ?? fetch;
229
+ let attempts = 0;
230
+ for (; ; ) {
231
+ if (options.signal.aborted) throw abortError(options.signal);
232
+ await options.beforeAttempt();
233
+ if (options.signal.aborted) throw abortError(options.signal);
234
+ attempts++;
235
+ options.onAttempt();
236
+ const timeout = AbortSignal.timeout(options.attemptTimeoutMs);
237
+ const signal = AbortSignal.any([options.signal, timeout]);
238
+ let error;
239
+ let wait;
240
+ try {
241
+ const response = await fetcher(url, { ...init, signal, redirect: "error" });
242
+ const reader = response.body?.getReader();
243
+ let text2 = "";
244
+ let bytes = 0;
245
+ if (reader) {
246
+ const decoder = new TextDecoder();
247
+ for (; ; ) {
248
+ const part = await reader.read();
249
+ if (part.done) break;
250
+ bytes += part.value.byteLength;
251
+ if (bytes > 4 * 1024 * 1024) {
252
+ await reader.cancel();
253
+ throw new SearchError("protocol", "Response exceeds the 4 MiB limit.", response.status, attempts);
254
+ }
255
+ text2 += decoder.decode(part.value, { stream: true });
256
+ }
257
+ text2 += decoder.decode();
258
+ }
259
+ if (response.ok) return text2;
260
+ const quota = response.status === 402 || /insufficient[_ -]?(balance|credit|fund)|quota[_ -]?(exhausted|exceeded)|credits?[_ -]?exhausted/i.test(text2.slice(0, 32768));
261
+ const kind = quota ? "quota" : [401, 403].includes(response.status) ? "authentication" : response.status === 429 ? "rate-limit" : "http";
262
+ error = new SearchError(kind, quota ? "Provider quota exhausted or balance insufficient." : `HTTP ${response.status}; check backend settings and account status.`, response.status, attempts);
263
+ if (quota || !options.retry.statuses.includes(response.status)) throw error;
264
+ if ([429, 503].includes(response.status)) wait = retryAfter(response.headers.get("retry-after"));
265
+ } catch (caught) {
266
+ if (options.signal.aborted) {
267
+ const e = abortError(options.signal);
268
+ e.attempts = attempts;
269
+ throw e;
270
+ }
271
+ if (caught instanceof SearchError) {
272
+ if (caught.kind === "quota" || caught.kind === "authentication" || caught.kind === "protocol" || !caught.status || !options.retry.statuses.includes(caught.status)) throw caught;
273
+ error = caught;
274
+ } else {
275
+ const timedOut = timeout.aborted;
276
+ error = new SearchError(timedOut ? "timeout" : "network", timedOut ? "Backend attempt timed out." : "Network request failed; check connectivity and endpoint.", void 0, attempts);
277
+ if (timedOut ? !options.retry.timeouts : !options.retry.networkErrors) throw error;
278
+ }
279
+ }
280
+ if (!options.retry.enabled || attempts > options.retry.maxRetries) throw error;
281
+ if (wait !== void 0 && wait > options.retry.maxDelayMs) throw new SearchError(error.kind, "Provider retry delay exceeds the configured maximum; no early retry was sent.", error.status, attempts);
282
+ await delay(wait ?? Math.min(options.retry.maxDelayMs, options.retry.initialDelayMs * 2 ** (attempts - 1) * (0.8 + Math.random() * 0.4)), options.signal);
283
+ }
284
+ }
285
+ async function requestJson(url, init, options) {
286
+ const text2 = await requestText(url, init, options);
287
+ try {
288
+ return JSON.parse(text2);
289
+ } catch {
290
+ throw new SearchError("protocol", "Provider returned invalid JSON.");
291
+ }
292
+ }
293
+
294
+ // src/mcp.ts
295
+ var row = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
296
+ async function callMcp(endpoint, tool, args, transport) {
297
+ const headers = { "Content-Type": "application/json", Accept: "application/json, text/event-stream" };
298
+ const rpc = async (method, params, id) => {
299
+ const text2 = await requestText(endpoint, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", ...id === void 0 ? {} : { id }, method, params }) }, method === "tools/call" ? transport : { ...transport, beforeAttempt: () => {
300
+ }, onAttempt: () => {
301
+ } });
302
+ if (!text2.trim() && id === void 0) return {};
303
+ let packets;
304
+ try {
305
+ packets = text2.trim().startsWith("{") ? [JSON.parse(text2)] : text2.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => {
306
+ try {
307
+ return JSON.parse(l.slice(5));
308
+ } catch {
309
+ return void 0;
310
+ }
311
+ });
312
+ } catch {
313
+ throw new SearchError("protocol", "MCP returned invalid JSON/SSE.");
314
+ }
315
+ const packet = packets.find((p) => row(p).id === id);
316
+ if (!packet || !("result" in row(packet)) && !("error" in row(packet))) throw new SearchError("protocol", "MCP response is missing the matching result.");
317
+ const response = row(packet);
318
+ if (response.error) throw new SearchError("protocol", "MCP server rejected the operation.");
319
+ return row(response.result);
320
+ };
321
+ const originalFetch = transport.fetch ?? fetch;
322
+ transport = { ...transport, fetch: (async (url, init) => {
323
+ const response = await originalFetch(url, init);
324
+ const session = response.headers.get("mcp-session-id");
325
+ if (session) headers["Mcp-Session-Id"] = session;
326
+ return response;
327
+ }) };
328
+ const initialized = await rpc("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "dsh-search", version: "0.1.0" } }, 1);
329
+ if (typeof initialized.protocolVersion !== "string") throw new SearchError("protocol", "MCP initialization did not negotiate a protocol version.");
330
+ headers["MCP-Protocol-Version"] = initialized.protocolVersion;
331
+ await rpc("notifications/initialized", {}, void 0);
332
+ const list = await rpc("tools/list", {}, 2);
333
+ const tools = Array.isArray(list.tools) ? list.tools : [];
334
+ const definition = tools.map(row).find((d) => d.name === tool);
335
+ if (!definition) throw new SearchError("protocol", "Configured MCP search tool is not advertised by the provider.");
336
+ const inputSchema = row(definition.inputSchema);
337
+ if (inputSchema.oneOf || inputSchema.anyOf) throw new SearchError("protocol", "MCP tool uses an unsupported composite input schema.");
338
+ const properties = row(inputSchema.properties);
339
+ for (const key of Object.keys(args)) if (!(key in properties) && inputSchema.additionalProperties !== true) throw new SearchError("protocol", `MCP tool does not support the configured ${key} parameter.`);
340
+ for (const required of Array.isArray(row(definition.inputSchema).required) ? row(definition.inputSchema).required : []) if (!(required in args)) throw new SearchError("protocol", "MCP tool requires an unsupported input parameter.");
341
+ const result = await rpc("tools/call", { name: tool, arguments: args }, 3);
342
+ if (result.isError) throw new SearchError("protocol", "MCP search tool reported failure; check account and quota.");
343
+ return result;
344
+ }
345
+
346
+ // src/tencent.ts
347
+ import { createHash, createHmac } from "node:crypto";
348
+ function object(value) {
349
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
350
+ }
351
+ function credentials(raw) {
352
+ try {
353
+ const value = object(JSON.parse(raw ?? ""));
354
+ if (value && typeof value.secretId === "string" && /^[A-Za-z0-9_-]+$/.test(value.secretId) && typeof value.secretKey === "string" && value.secretKey.trim() && !/[\r\n]/.test(value.secretKey)) {
355
+ return { secretId: value.secretId, secretKey: value.secretKey };
356
+ }
357
+ } catch {
358
+ }
359
+ throw new SearchError("configuration", "Tencent credentials must be a JSON object with non-empty secretId and secretKey strings.");
360
+ }
361
+ var hash = (text2) => createHash("sha256").update(text2).digest("hex");
362
+ var hmac = (key, text2) => createHmac("sha256", key).update(text2).digest();
363
+ function signedHeaders(secretId, secretKey, body, timestamp) {
364
+ const host = "wsa.tencentcloudapi.com";
365
+ const date = new Date(timestamp * 1e3).toISOString().slice(0, 10);
366
+ const scope = `${date}/wsa/tc3_request`;
367
+ const signed = "content-type;host;x-tc-action";
368
+ const canonical = `POST
369
+ /
370
+
371
+ content-type:application/json
372
+ host:${host}
373
+ x-tc-action:searchpro
374
+
375
+ ${signed}
376
+ ${hash(body)}`;
377
+ const toSign = `TC3-HMAC-SHA256
378
+ ${timestamp}
379
+ ${scope}
380
+ ${hash(canonical)}`;
381
+ const signingKey = hmac(hmac(hmac(`TC3${secretKey}`, date), "wsa"), "tc3_request");
382
+ const signature = createHmac("sha256", signingKey).update(toSign).digest("hex");
383
+ return {
384
+ "Content-Type": "application/json",
385
+ Host: host,
386
+ "X-TC-Action": "SearchPro",
387
+ "X-TC-Version": "2025-05-08",
388
+ "X-TC-Timestamp": String(timestamp),
389
+ Authorization: `TC3-HMAC-SHA256 Credential=${secretId}/${scope}, SignedHeaders=${signed}, Signature=${signature}`
390
+ };
391
+ }
392
+ function providerFailure(code) {
393
+ let kind = "protocol";
394
+ if (typeof code === "string") {
395
+ if (/^(AuthFailure|UnauthorizedOperation)/.test(code)) kind = "authentication";
396
+ else if (/^(RequestLimitExceeded|LimitExceeded)/.test(code)) kind = "rate-limit";
397
+ else if (/^(FailedOperation\.(Balance|Quota)|ResourceUnavailable\.(Balance|Quota))/.test(code)) kind = "quota";
398
+ }
399
+ return new SearchError(kind, "Tencent reported an application-level failure; check account permissions, quota, and configuration.");
400
+ }
401
+ async function searchTencent(i, t) {
402
+ if (i.backend.mode !== "key") throw new SearchError("configuration", "Tencent Search requires explicitly selected key access.");
403
+ const key = credentials(i.key);
404
+ let endpoint;
405
+ try {
406
+ endpoint = new URL(i.backend.endpoint);
407
+ } catch {
408
+ throw new SearchError("configuration", "Tencent endpoint must be the official HTTPS API root.");
409
+ }
410
+ if (endpoint.href !== "https://wsa.tencentcloudapi.com/") {
411
+ throw new SearchError("configuration", "Tencent endpoint must be the official HTTPS API root.");
412
+ }
413
+ if (!Number.isInteger(i.maxResults) || i.maxResults < 1 || i.maxResults > 50) {
414
+ throw new SearchError("configuration", "Tencent result count must be an integer between 1 and 50.");
415
+ }
416
+ const mode2 = i.backend.options.Mode;
417
+ if (mode2 !== void 0 && (typeof mode2 !== "number" || ![0, 1, 2].includes(mode2))) {
418
+ throw new SearchError("configuration", "Tencent Mode must be the number 0, 1, or 2.");
419
+ }
420
+ const body = JSON.stringify({ Query: i.query, Cnt: Math.ceil(i.maxResults / 10) * 10, ...mode2 === void 0 ? {} : { Mode: mode2 } });
421
+ const response = object(await requestJson(endpoint.href, {
422
+ method: "POST",
423
+ headers: signedHeaders(key.secretId, key.secretKey, body, Math.floor(Date.now() / 1e3)),
424
+ body
425
+ }, t));
426
+ const result = object(response?.Response);
427
+ if (!result) throw new SearchError("protocol", "Tencent response is missing its Response envelope.");
428
+ if (result.Error !== void 0) throw providerFailure(object(result.Error)?.Code);
429
+ if (!Array.isArray(result.Pages)) throw new SearchError("protocol", "Tencent response is missing its Pages array.");
430
+ const sources2 = [];
431
+ for (const encoded of result.Pages) {
432
+ let page;
433
+ try {
434
+ page = typeof encoded === "string" ? object(JSON.parse(encoded)) : void 0;
435
+ } catch {
436
+ throw new SearchError("protocol", "Tencent Pages contains invalid JSON.");
437
+ }
438
+ if (!page) throw new SearchError("protocol", "Tencent Pages must contain JSON-encoded objects.");
439
+ if (typeof page.url !== "string") continue;
440
+ try {
441
+ const url = new URL(page.url);
442
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) continue;
443
+ } catch {
444
+ continue;
445
+ }
446
+ sources2.push({
447
+ url: page.url,
448
+ ...typeof page.title === "string" ? { title: page.title } : {},
449
+ ...typeof page.passage === "string" ? { snippet: page.passage } : {},
450
+ ...typeof page.content === "string" ? { summary: page.content } : {},
451
+ ...typeof page.date === "string" ? { publishedAt: page.date } : {}
452
+ });
453
+ }
454
+ return { sources: sources2.slice(0, i.maxResults) };
455
+ }
456
+
457
+ // src/adapters.ts
458
+ var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
459
+ var array = (v) => Array.isArray(v) ? v : [];
460
+ var string = (v) => typeof v === "string" ? v : void 0;
461
+ function sources(rows, keys = { title: "title", url: "url", snippet: "snippet", date: "published_at" }) {
462
+ if (!Array.isArray(rows)) throw new SearchError("protocol", "Expected a results array from provider.");
463
+ return rows.flatMap((v) => {
464
+ const r = obj(v);
465
+ const url = string(r[keys.url]);
466
+ if (!url) return [];
467
+ try {
468
+ const u = new URL(url);
469
+ if (!["https:", "http:"].includes(u.protocol) || u.username || u.password) return [];
470
+ } catch {
471
+ return [];
472
+ }
473
+ return [{ url, title: string(r[keys.title]), snippet: string(r[keys.snippet]), publishedAt: string(r[keys.date]) }];
474
+ });
475
+ }
476
+ async function runAdapter(id, i, t) {
477
+ if (id === "tencent-wsa") return searchTencent(i, t);
478
+ const b = i.backend;
479
+ const o = b.options;
480
+ const c = i.config;
481
+ const headers = { "Content-Type": "application/json" };
482
+ const key = b.mode === "key" ? i.key : void 0;
483
+ const json = (body, h = headers) => requestJson(b.endpoint, { method: "POST", headers: h, body: JSON.stringify(body) }, t);
484
+ const get = (params, h = headers) => {
485
+ const url = new URL(b.endpoint);
486
+ for (const [k, v] of Object.entries(params)) if (v !== void 0 && v !== "") url.searchParams.set(k, String(v));
487
+ return requestJson(url.href, { headers: h }, t);
488
+ };
489
+ const bearer = () => {
490
+ if (key) headers.Authorization = `Bearer ${key}`;
491
+ };
492
+ if (id === "keenable") {
493
+ headers["X-Keenable-Title"] = String(o.clientTitle);
494
+ if (key) headers["X-API-Key"] = key;
495
+ const r = obj(await json({ query: i.query, max_results: i.maxResults, snippet_max_length: o.snippet_max_length, ...c.includeDomains.length ? { site: c.includeDomains.join(",") } : {} }));
496
+ return { sources: sources(r.results) };
497
+ }
498
+ if (id === "anysearch") {
499
+ bearer();
500
+ const r = obj(await json({ query: i.query, max_results: Math.min(i.maxResults, 10), zone: o.zone, format: "json", ...languageFor("anysearch", c.language) ? { language: languageFor("anysearch", c.language) } : {} }));
501
+ if (r.code !== void 0 && r.code !== 0 && r.code !== 200) throw new SearchError("protocol", "AnySearch reported an application-level error; inspect the account console.");
502
+ return { sources: sources(obj(r.data).results) };
503
+ }
504
+ if (id === "linkup") {
505
+ bearer();
506
+ const r = obj(await json({ q: i.query, depth: o.depth, outputType: "searchResults", maxResults: i.maxResults }));
507
+ return { sources: sources(r.results, { title: "name", url: "url", snippet: "content", date: "publishedAt" }) };
508
+ }
509
+ if (id === "tavily") {
510
+ bearer();
511
+ const r = obj(await json({ query: i.query, max_results: Math.min(i.maxResults, 20), search_depth: o.search_depth, auto_parameters: false, topic: o.topic, include_answer: o.include_answer, include_domains: c.includeDomains, exclude_domains: c.excludeDomains, ...c.recency !== "any" ? { time_range: c.recency } : {} }));
512
+ return { sources: sources(r.results, { title: "title", url: "url", snippet: "content", date: "published_date" }), content: string(r.answer) };
513
+ }
514
+ if (id === "brave") {
515
+ if (key) headers["X-Subscription-Token"] = key;
516
+ const r = obj(await get({ q: i.query, count: Math.min(i.maxResults, 20), search_lang: languageFor("brave", c.language), country: regionFor("brave", c.region), safesearch: c.safeSearch ? "strict" : "off", freshness: { any: void 0, day: "pd", week: "pw", month: "pm", year: "py" }[c.recency] }));
517
+ return { sources: sources(obj(r.web).results, { title: "title", url: "url", snippet: "description", date: "page_age" }) };
518
+ }
519
+ if (id === "serper") {
520
+ if (key) headers["X-API-KEY"] = key;
521
+ const r = obj(await json({ q: i.query, num: i.maxResults, hl: languageFor("serper", c.language), gl: regionFor("serper", c.region), tbs: { any: void 0, day: "qdr:d", week: "qdr:w", month: "qdr:m", year: "qdr:y" }[c.recency] }));
522
+ return { sources: sources(r.organic, { title: "title", url: "link", snippet: "snippet", date: "date" }) };
523
+ }
524
+ if (id === "searxng") {
525
+ bearer();
526
+ const r = obj(await get({ q: i.query, format: "json", language: languageFor("searxng", c.language) || "auto", time_range: c.recency === "any" ? void 0 : c.recency, safesearch: c.safeSearch ? 2 : 0, engines: o.engines, categories: o.categories }));
527
+ return { sources: sources(r.results, { title: "title", url: "url", snippet: "content", date: "publishedDate" }) };
528
+ }
529
+ if (id === "exa" && b.mode === "key") {
530
+ headers["x-api-key"] = key;
531
+ const date = c.recency === "any" ? void 0 : new Date(Date.now() - { day: 1, week: 7, month: 30, year: 365 }[c.recency] * 864e5).toISOString();
532
+ const r = obj(await json({ query: i.query, numResults: i.maxResults, type: o.type, includeDomains: c.includeDomains, excludeDomains: c.excludeDomains, startPublishedDate: date, contents: { text: { maxCharacters: o.textMaxCharacters } } }));
533
+ return { sources: sources(r.results, { title: "title", url: "url", snippet: "text", date: "publishedDate" }) };
534
+ }
535
+ if ((id === "exa" || id === "parallel" || id === "you") && b.mode === "anonymous") {
536
+ const tool = id === "exa" ? "web_search_exa" : id === "you" ? "you-search" : "web_search";
537
+ const args = id === "exa" ? { query: i.query, objective: i.query, numResults: i.maxResults } : id === "you" ? { query: i.query, count: i.maxResults } : { objective: i.query, search_queries: [i.query] };
538
+ const endpoint = new URL(b.endpoint);
539
+ if (id === "you") endpoint.searchParams.set("profile", "free");
540
+ if (id === "parallel") endpoint.searchParams.set("tools", "web_search");
541
+ const result = await callMcp(endpoint.href, tool, args, t);
542
+ const structured = obj(result.structuredContent);
543
+ if (Array.isArray(structured.results)) return { sources: sources(structured.results) };
544
+ const text2 = array(result.content).map((v) => string(obj(v).text) || "").join("\n");
545
+ if (!text2.trim()) throw new SearchError("protocol", "MCP search response has no recognized result payload.");
546
+ try {
547
+ const parsed = obj(JSON.parse(text2));
548
+ const list = [parsed.results, obj(parsed.data).results, obj(parsed.results).web].find(Array.isArray);
549
+ if (Array.isArray(list)) return { sources: sources(list) };
550
+ } catch (e) {
551
+ if (e instanceof SearchError) throw e;
552
+ }
553
+ const found = [];
554
+ const blocks = text2.split(/(?=Title:)/);
555
+ for (const block of blocks) {
556
+ const url = block.match(/URL:\s*(https?:\/\/\S+)/)?.[1];
557
+ if (url) found.push({ url, title: block.match(/Title:\s*(.+)/)?.[1], snippet: block.split(/(?:Text|Content):\s*/).slice(1).join(" ").slice(0, 4e3) });
558
+ }
559
+ if (!found.length && text2.trim()) throw new SearchError("protocol", "MCP result format contains no verifiable source URLs.");
560
+ return { sources: found };
561
+ }
562
+ if (id === "parallel") {
563
+ if (key) headers["x-api-key"] = key;
564
+ const r = obj(await json({ search_queries: [i.query], mode: o.mode, advanced_settings: { max_results: i.maxResults } }));
565
+ const rows = array(r.results).map((v) => {
566
+ const row2 = obj(v);
567
+ return { ...row2, excerpt: array(row2.excerpts).filter((x) => typeof x === "string").join("\n").slice(0, Number(o.maxCharactersPerResult)) };
568
+ });
569
+ return { sources: sources(rows, { title: "title", url: "url", snippet: "excerpt", date: "publish_date" }) };
570
+ }
571
+ if (id === "you") {
572
+ if (key) headers["X-API-Key"] = key;
573
+ const r = obj(await json({ query: i.query, count: i.maxResults, strict_operators: true, ...languageFor("you", c.language) ? { language: languageFor("you", c.language) } : {}, ...regionFor("you", c.region) ? { country: regionFor("you", c.region) } : {} }));
574
+ return { sources: sources(obj(r.results).web, { title: "title", url: "url", snippet: "description", date: "page_age" }) };
575
+ }
576
+ if (id === "baidu") {
577
+ bearer();
578
+ const r = obj(await json({ messages: [{ role: "user", content: i.query }], search_source: "baidu_search_v2", edition: o.edition, resource_type_filter: [{ type: "web", top_k: i.maxResults }] }));
579
+ return { sources: sources(r.references, { title: "title", url: "url", snippet: "snippet", date: "date" }) };
580
+ }
581
+ if (id === "doubao") {
582
+ bearer();
583
+ const r = obj(await json({ Query: i.query, SearchType: "web", Count: i.maxResults, Filter: { NeedUrl: true }, QueryControl: { QueryRewrite: o.queryRewrite } }));
584
+ if (obj(r.ResponseMetadata).Error) throw new SearchError("protocol", "Doubao returned an application-level error.");
585
+ return { sources: sources(obj(r.Result).WebResults, { title: "Title", url: "Url", snippet: "Snippet", date: "PublishTime" }) };
586
+ }
587
+ if (id === "zhihu-web" || id === "zhihu-site") {
588
+ bearer();
589
+ headers["X-Request-Timestamp"] = String(Math.floor(Date.now() / 1e3));
590
+ const r = obj(await get({ Query: i.query, Count: Math.min(i.maxResults, id === "zhihu-web" ? 20 : 10), ...id === "zhihu-web" ? { SearchDB: o.SearchDB, Filter: o.Filter } : {} }));
591
+ if (r.Code !== 0) throw new SearchError("protocol", "Zhihu reported an application-level failure; check Access Secret and account permissions.");
592
+ return { sources: sources(obj(r.Data).Items, { title: "Title", url: "Url", snippet: "ContentText", date: "PublishTime" }) };
593
+ }
594
+ if (id === "open-websearch") {
595
+ const r = obj(await json({ query: i.query, limit: i.maxResults, engines: [o.engine], searchMode: o.searchMode }));
596
+ if (r.status !== "ok") throw new SearchError("protocol", "Self-hosted search daemon reported failure.");
597
+ return { sources: sources(r.data, { title: "title", url: "url", snippet: "description", date: "date" }) };
598
+ }
599
+ if (id === "serpex") {
600
+ bearer();
601
+ const r = obj(await json({ q: i.query }));
602
+ return { sources: sources(r.results), warnings: ["Serpex controls its own internal upstream routing; the plugin did not switch providers."] };
603
+ }
604
+ if (id === "mojeek") {
605
+ const r = obj(await get({ q: i.query, api_key: key, fmt: "json" }));
606
+ const response = obj(r.response);
607
+ if (response.status !== "OK" && response.status !== 200 && response.status !== "200") throw new SearchError("protocol", "Mojeek reported an application-level error.");
608
+ return { sources: sources(response.results, { title: "title", url: "url", snippet: "desc", date: "date" }) };
609
+ }
610
+ if (id === "deepseek") {
611
+ bearer();
612
+ const r = obj(await json({ query: i.query, count: i.maxResults, need_content: o.need_content }));
613
+ return { sources: sources(r.results, { title: "title", url: "url", snippet: "snippet", date: "date" }) };
614
+ }
615
+ if (id === "anthropic") {
616
+ if (key) headers["x-api-key"] = key;
617
+ headers["anthropic-version"] = "2023-06-01";
618
+ const r = obj(await json({ model: o.model, max_tokens: o.maxTokens, tools: [{ type: "web_search_20250305", name: "web_search", max_uses: o.maxUses, ...c.includeDomains.length ? { allowed_domains: c.includeDomains } : {}, ...c.excludeDomains.length ? { blocked_domains: c.excludeDomains } : {} }], messages: [{ role: "user", content: i.query }] }));
619
+ const result = [];
620
+ for (const block of array(r.content)) {
621
+ const v = obj(block);
622
+ if (v.type === "web_search_tool_result") {
623
+ if (obj(v.content).type === "web_search_tool_result_error") throw new SearchError("protocol", "Anthropic search tool reported failure.");
624
+ for (const x of array(v.content)) {
625
+ const s = obj(x);
626
+ if (s.type === "web_search_result") result.push(...sources([s], { title: "title", url: "url", snippet: "page_content", date: "page_age" }));
627
+ }
628
+ }
629
+ }
630
+ return { sources: result };
631
+ }
632
+ if (id === "openai") {
633
+ bearer();
634
+ const r = obj(await json({ model: o.model, input: i.query, tools: [{ type: "web_search" }], tool_choice: "required", include: ["web_search_call.action.sources"], max_output_tokens: o.maxOutputTokens }));
635
+ if (r.error || r.status === "failed" || r.status === "incomplete") throw new SearchError("protocol", "OpenAI response did not complete.");
636
+ const result = [];
637
+ for (const output of array(r.output)) for (const block of array(obj(output).content)) for (const a of array(obj(block).annotations)) {
638
+ const citation = obj(a);
639
+ if (citation.type === "url_citation") result.push(...sources([citation]));
640
+ }
641
+ return { sources: result };
642
+ }
643
+ if (id === "ddg") {
644
+ const raw = await requestText(b.endpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ q: i.query }).toString() }, t);
645
+ if (/anomaly|challenge-form|bots use DuckDuckGo/i.test(raw)) throw new SearchError("rate-limit", "DuckDuckGo returned a challenge; no bypass was attempted.");
646
+ const decode = (s) => s.replace(/<[^>]*>/g, " ").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\s+/g, " ").trim();
647
+ const result = [];
648
+ for (const match of raw.matchAll(/<a\b[^>]*class="[^"]*result__a[^"]*"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/g)) {
649
+ let url = decode(match[1]);
650
+ try {
651
+ const u = new URL(url, "https://duckduckgo.com");
652
+ url = u.searchParams.get("uddg") || u.href;
653
+ } catch {
654
+ continue;
655
+ }
656
+ result.push(...sources([{ url, title: decode(match[2]) }]));
657
+ }
658
+ if (!result.length && !/No results found|result--no-result/.test(raw)) throw new SearchError("protocol", "DuckDuckGo HTML layout was not recognized.");
659
+ return { sources: result };
660
+ }
661
+ throw new SearchError("unverified", "Backend adapter is not verified and cannot be called.");
662
+ }
663
+
664
+ // src/engine.ts
665
+ function revision(config) {
666
+ return createHash2("sha256").update(JSON.stringify(config)).digest("hex");
667
+ }
668
+ var SearchEngine = class {
669
+ constructor(config, resolveKey, fetcher = fetch, reserveAttempt) {
670
+ this.config = config;
671
+ this.resolveKey = resolveKey;
672
+ this.fetcher = fetcher;
673
+ this.reserveAttempt = reserveAttempt;
674
+ }
675
+ config;
676
+ resolveKey;
677
+ fetcher;
678
+ reserveAttempt;
679
+ cache = /* @__PURE__ */ new Map();
680
+ history = [];
681
+ usage = /* @__PURE__ */ new Map();
682
+ failures = /* @__PURE__ */ new Map();
683
+ clearCache() {
684
+ this.cache.clear();
685
+ }
686
+ clearDiagnostics() {
687
+ this.history = [];
688
+ }
689
+ diagnostics() {
690
+ return structuredClone(this.history);
691
+ }
692
+ counters() {
693
+ return Object.fromEntries([...this.usage].map(([id, u]) => [id, { attempts: u.attempts, day: u.day }]));
694
+ }
695
+ async search(input, signal, onlyBackend) {
696
+ if (typeof input.query !== "string" || !input.query.trim() || input.query.length > 1e4) throw new SearchError("configuration", "Query must contain 1\u201310,000 characters.");
697
+ if (input.maxResults !== void 0 && (!Number.isInteger(input.maxResults) || input.maxResults < 1 || input.maxResults > 50)) throw new SearchError("configuration", "Result limit must be 1\u201350.");
698
+ const c = this.config;
699
+ const max = input.maxResults ?? c.maxResults;
700
+ const outer = signal ?? new AbortController().signal;
701
+ const deadline = AbortSignal.timeout(c.overallTimeoutMs);
702
+ const combined = AbortSignal.any([outer, deadline]);
703
+ const ids = onlyBackend ? [onlyBackend] : c.mode === "single" ? [c.singleBackend] : catalog.filter((d) => c.backends[d.id]?.enabled).map((d) => d.id);
704
+ const cacheKey = JSON.stringify([revision(c), input.query, max, ids]);
705
+ const hit = this.cache.get(cacheKey);
706
+ if (!onlyBackend && c.cache.enabled && hit && hit.expires > Date.now()) return { ...structuredClone(hit.result), cached: true, content: hit.result.content + "\n[Cache hit: no upstream requests were made.]" };
707
+ const outcomes = new Array(ids.length);
708
+ let cursor = 0;
709
+ const worker = async () => {
710
+ while (cursor < ids.length) {
711
+ const index = cursor++;
712
+ const id = ids[index];
713
+ outcomes[index] = await this.call(id, input.query, max, combined);
714
+ }
715
+ };
716
+ await Promise.all(Array.from({ length: Math.min(c.concurrency, ids.length) }, worker));
717
+ if (outer.aborted) throw abortError(outer);
718
+ const success = outcomes.filter((o) => o.ok);
719
+ const merged = /* @__PURE__ */ new Map();
720
+ let order = 0;
721
+ for (const outcome of success) for (const [rank, source] of outcome.sources.entries()) {
722
+ if (!domainAllowed(source.url, c)) continue;
723
+ const key = normalizeUrl(source.url);
724
+ let existing = merged.get(key);
725
+ if (!existing && c.dedup === "url-title" && source.title) existing = [...merged.values()].find((x) => x.source.title?.trim().toLowerCase() === source.title.trim().toLowerCase());
726
+ if (existing) existing.score += 1 / (60 + rank + 1);
727
+ else merged.set(key, { source, score: 1 / (60 + rank + 1), order: order++ });
728
+ }
729
+ const ranked = [...merged.values()].sort((a, b) => c.fusion === "rrf" ? b.score - a.score || a.order - b.order : a.order - b.order);
730
+ const sources2 = ranked.slice(0, max).map((x) => x.source);
731
+ const failed = outcomes.filter((o) => !o.ok);
732
+ const report = [];
733
+ if (!ids.length) report.push("Search failed: no backend is enabled. Ask the user to configure and enable a search backend.");
734
+ else if (!success.length) report.push("Search failed: every selected backend failed. This is not a successful search with no matches.");
735
+ if (failed.length) report.push("IMPORTANT: Inform the user of the following backend failures. No backend, access-mode, endpoint, or credential fallback was attempted.");
736
+ for (const o of outcomes) {
737
+ if (!o.ok) report.push(`[${o.backend}; mode=${o.mode}; attempts=${o.attempts}] FAILED ${o.error.kind}${o.error.status ? ` HTTP ${o.error.status}` : ""}: ${o.error.message}`);
738
+ for (const w of o.warnings) report.push(`[${o.backend}] ${w}`);
739
+ }
740
+ const result = { sources: sources2, content: report.join("\n"), truncated: ranked.length > max, outcomes, cached: false };
741
+ if (c.diagnostics.enabled) {
742
+ const at = Date.now();
743
+ this.history.push(...outcomes.map((o) => ({ ...o, sources: [], at })));
744
+ this.history = this.history.slice(-c.diagnostics.maxEntries);
745
+ }
746
+ if (!onlyBackend && c.cache.enabled && success.length && failed.length === 0) {
747
+ this.cache.set(cacheKey, { expires: Date.now() + c.cache.ttlSeconds * 1e3, result: structuredClone(result) });
748
+ while (this.cache.size > c.cache.maxEntries) this.cache.delete(this.cache.keys().next().value);
749
+ }
750
+ return result;
751
+ }
752
+ async call(id, query, maxResults, signal) {
753
+ const started = Date.now();
754
+ const d = catalog.find((x) => x.id === id);
755
+ const b = this.config.backends[id];
756
+ let attempts = 0;
757
+ const warnings = [];
758
+ const result = { backend: id, mode: b?.mode ?? "anonymous", ok: false, attempts: 0, durationMs: 0, sources: [], warnings };
759
+ try {
760
+ if (!d || !b || !b.enabled) throw new SearchError("configuration", "Backend is disabled or unknown.");
761
+ if (d.status === "unverified") throw new SearchError("unverified", "Backend protocol is not verified.");
762
+ if (signal.aborted) throw abortError(signal);
763
+ const circuit = this.failures.get(id);
764
+ if (this.config.breaker.enabled && circuit && circuit.until > Date.now()) throw new SearchError("circuit-open", "Backend circuit is open; no call or fallback was sent.");
765
+ const key = b.mode === "key" ? await this.resolveKey(b.credentialRef) : void 0;
766
+ if (b.mode === "key" && !key) throw new SearchError("configuration", "API-key mode selected but credential is missing. Ask the user to set the credential.");
767
+ for (const [field, active] of [["language", !!this.config.language], ["region", !!this.config.region], ["recency", this.config.recency !== "any"], ["safeSearch", this.config.safeSearch]]) if (active && !d.capabilities.includes(field)) warnings.push(`${field} is unsupported by this backend and was not applied upstream.`);
768
+ if (id === "deepseek" && query.length > 128) throw new SearchError("configuration", "DeepSeek search query must not exceed 128 characters.");
769
+ const response = await runAdapter(id, { query, maxResults, config: this.config, backend: b, key, signal }, { signal, retry: this.config.retry, attemptTimeoutMs: b.timeoutMs, fetch: this.fetcher, onAttempt: () => {
770
+ attempts++;
771
+ }, beforeAttempt: async () => {
772
+ if (this.reserveAttempt) {
773
+ const saved = await this.reserveAttempt(id, b.mode, b.rateLimitPerMinute, b.dailyAttemptLimit);
774
+ this.usage.set(id, { ...saved, recent: [] });
775
+ return;
776
+ }
777
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
778
+ let u = this.usage.get(id);
779
+ if (!u || u.day !== day) {
780
+ u = { attempts: 0, day, recent: [] };
781
+ this.usage.set(id, u);
782
+ }
783
+ u.recent = u.recent.filter((t) => t > Date.now() - 6e4);
784
+ if (b.dailyAttemptLimit && u.attempts >= b.dailyAttemptLimit) throw new SearchError("budget", "Local daily attempt cap reached (UTC reset; not provider balance).");
785
+ if (b.rateLimitPerMinute && u.recent.length >= b.rateLimitPerMinute) throw new SearchError("budget", "Local per-minute attempt limit reached.");
786
+ u.attempts++;
787
+ u.recent.push(Date.now());
788
+ } });
789
+ result.ok = true;
790
+ result.sources = response.sources;
791
+ warnings.push(...response.warnings ?? []);
792
+ this.failures.delete(id);
793
+ } catch (e) {
794
+ const error = e instanceof SearchError ? e : new SearchError("protocol", "Backend failed unexpectedly; inspect plugin diagnostics.");
795
+ result.error = { kind: error.kind, message: error.message, status: error.status };
796
+ if (attempts && this.config.breaker.enabled) {
797
+ const old = this.failures.get(id)?.count ?? 0;
798
+ this.failures.set(id, { count: old + 1, until: old + 1 >= this.config.breaker.threshold ? Date.now() + this.config.breaker.cooldownMs : 0 });
799
+ }
800
+ }
801
+ result.attempts = attempts;
802
+ result.durationMs = Date.now() - started;
803
+ return result;
804
+ }
805
+ };
806
+ function normalizeUrl(value) {
807
+ try {
808
+ const u = new URL(value);
809
+ u.hash = "";
810
+ for (const k of [...u.searchParams.keys()]) if (k.startsWith("utm_") || ["fbclid", "gclid"].includes(k)) u.searchParams.delete(k);
811
+ u.searchParams.sort();
812
+ return u.href.replace(/\/$/, "");
813
+ } catch {
814
+ return value;
815
+ }
816
+ }
817
+ function domainAllowed(value, c) {
818
+ try {
819
+ const host = new URL(value).hostname.toLowerCase();
820
+ const matches = (domain) => host === domain.toLowerCase() || host.endsWith("." + domain.toLowerCase());
821
+ return (!c.includeDomains.length || c.includeDomains.some(matches)) && !c.excludeDomains.some(matches);
822
+ } catch {
823
+ return false;
824
+ }
825
+ }
826
+
827
+ // src/usage.ts
828
+ import { defineDomain, domainTable } from "@deepseek-ai/dsh-storage-domain";
829
+ import { z } from "zod";
830
+ var spec = defineDomain({ name: "nite_search_usage", version: 1, tables: { attempts: domainTable(z.object({ day: z.string(), attempts: z.number().int().nonnegative(), recent: z.array(z.number()) })) } });
831
+ async function openUsage(ctx) {
832
+ const domain = await ctx.storageDomain.open(spec);
833
+ const table = domain.table("attempts");
834
+ let chain = Promise.resolve();
835
+ const reserve = (id, mode2, perMinute, daily) => {
836
+ const run = chain.then(async () => {
837
+ try {
838
+ const key = `${id}-${mode2}`;
839
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
840
+ const prior = table.get(key);
841
+ const attempts = prior?.day === day ? prior.attempts : 0;
842
+ const recent = (prior?.recent ?? []).filter((t) => t > Date.now() - 6e4);
843
+ if (daily && attempts >= daily) throw new SearchError("budget", "Local daily attempt cap reached (UTC reset; not provider balance).");
844
+ if (perMinute && recent.length >= perMinute) throw new SearchError("budget", "Local per-minute attempt limit reached.");
845
+ await table.put(key, { day, attempts: attempts + 1, recent: [...recent, Date.now()] });
846
+ return { day, attempts: attempts + 1 };
847
+ } catch (e) {
848
+ if (e instanceof SearchError) throw e;
849
+ throw new SearchError("budget", "Cannot durably reserve local attempt budget; no request was sent.");
850
+ }
851
+ });
852
+ chain = run.catch(() => {
853
+ });
854
+ return run;
855
+ };
856
+ return { reserve, counters: () => Object.fromEntries([...table.entries()].map(([key, v]) => [key, { attempts: v.attempts, day: v.day }])), close: async () => {
857
+ await chain;
858
+ await domain.close();
859
+ } };
860
+ }
861
+
862
+ // src/index.ts
863
+ var name = "nite-search";
864
+ var inject = ["web", "credentials", "configEditor", "connection", "tools", "storageDomain"];
865
+ function schema(value) {
866
+ if (Array.isArray(value)) return z2.array(typeof value[0] === "number" ? z2.number() : z2.string()).default(value);
867
+ if (value && typeof value === "object") return z2.object(Object.fromEntries(Object.entries(value).map(([k, v]) => [k, schema(v)]))).default(value);
868
+ if (typeof value === "number") return z2.number().default(value);
869
+ if (typeof value === "boolean") return z2.boolean().default(value);
870
+ return z2.string().default(value);
871
+ }
872
+ var Config = schema(defaultConfig());
873
+ async function apply(ctx, raw) {
874
+ const config = parseConfig(raw);
875
+ const usage = await openUsage(ctx);
876
+ ctx.effect(() => () => usage.close());
877
+ const engine = new SearchEngine(config, async (ref) => (await ctx.credentials.resolve(credentialRef(ref)))?.value, fetch, usage.reserve);
878
+ const lifetime = new AbortController();
879
+ ctx.effect(() => () => {
880
+ lifetime.abort();
881
+ engine.clearCache();
882
+ engine.clearDiagnostics();
883
+ });
884
+ ctx.effect(() => ctx.web.registerSearchProvider({ id: "nite-search", title: "DSH search", description: { en: "Explicit access modes and transparent backend failures.", zh: "\u56FA\u5B9A\u63A5\u5165\u6A21\u5F0F\uFF0C\u660E\u786E\u62A5\u544A\u5404\u540E\u7AEF\u8C03\u7528\u5931\u8D25\u3002" }, available: () => true, search: (request, signal) => engine.search(request, AbortSignal.any([lifetime.signal, ...signal ? [signal] : []])) }));
885
+ const currentRevision = revision(config);
886
+ async function snapshot() {
887
+ const credentials2 = {};
888
+ for (const d of catalog) {
889
+ const info = await ctx.credentials.describe(credentialRef(config.backends[d.id].credentialRef));
890
+ credentials2[d.id] = { configured: info.configured, writable: info.writable };
891
+ }
892
+ let searchProvider;
893
+ try {
894
+ const row2 = ctx.configEditor.configuration().find((item) => item.entry.options.id === "web");
895
+ searchProvider = { ...row2?.inherited, ...row2?.override }.searchProvider;
896
+ } catch {
897
+ }
898
+ return { config: structuredClone(config), defaults: defaultConfig(), revision: currentRevision, catalog, active: { ...searchProvider ? { searchProvider } : {}, isSelf: searchProvider === "nite-search" }, credentials: credentials2, diagnostics: engine.diagnostics(), counters: Object.fromEntries(catalog.map((d) => [d.id, usage.counters()[`${d.id}-${config.backends[d.id].mode}`] ?? { attempts: 0, day: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10) }])) };
899
+ }
900
+ async function operate(args, signal) {
901
+ if (args?.action === "settings") return snapshot();
902
+ if (args?.action === "activate") {
903
+ const web = ctx.configEditor.entries().find((e) => e.options.id === "web");
904
+ if (!web) throw new Error("Web provider entry is not addressable.");
905
+ await ctx.configEditor.edit(web, (current) => ({ ...current, searchProvider: "nite-search", fetchProvider: "http" }));
906
+ return { selected: "nite-search", fetchProvider: "http" };
907
+ }
908
+ if (args?.action === "save") {
909
+ if (args.expectedRevision !== currentRevision) throw new Error("Configuration revision conflict. Reload before saving.");
910
+ const candidate = parseConfig(args.config);
911
+ const entry = ctx.fiber.entry;
912
+ if (!entry) throw new Error("Configuration cannot be saved in this profile.");
913
+ await ctx.configEditor.edit(entry, () => candidate);
914
+ return { saved: true };
915
+ }
916
+ if (args?.action === "test") {
917
+ if (typeof args.backendId !== "string" || !config.backends[args.backendId]?.enabled) throw new Error("Backend must be saved and enabled before testing.");
918
+ return engine.search({ query: args.query }, signal, args.backendId);
919
+ }
920
+ if (args?.action === "clear-cache") {
921
+ engine.clearCache();
922
+ return { cleared: true };
923
+ }
924
+ if (args?.action === "clear-diagnostics") {
925
+ engine.clearDiagnostics();
926
+ return { cleared: true };
927
+ }
928
+ if (args?.action === "credential") {
929
+ const b = config.backends[args.backendId];
930
+ if (!b || args.ref !== b.credentialRef) throw new Error("Save the backend credential reference before editing its value.");
931
+ if (args.remove === true) await ctx.credentials.unset(credentialRef(b.credentialRef));
932
+ else {
933
+ if (typeof args.value !== "string" || !args.value.trim() || args.value.length > 16384) throw new Error("A nonempty credential is required.");
934
+ await ctx.credentials.set(credentialRef(b.credentialRef), args.value);
935
+ }
936
+ engine.clearCache();
937
+ return { saved: true };
938
+ }
939
+ throw new Error("Unsupported search management action.");
940
+ }
941
+ const connection = ctx.get("connection");
942
+ const route = (path, methods, handler) => ctx.effect(() => connection.fetch.register({ path: `/api/nite-search/${path}`, methods, requestBody: "buffered", fetch: async (request) => {
943
+ try {
944
+ return Response.json(await handler(request), { headers: { "Cache-Control": "no-store" } });
945
+ } catch {
946
+ return Response.json({ error: "Search management operation failed. Check configuration, revision, credentials, and enabled state." }, { status: 400, headers: { "Cache-Control": "no-store" } });
947
+ }
948
+ } }));
949
+ const body = async (request) => {
950
+ const text2 = await request.text();
951
+ if (text2.length > 262144) throw new Error("Request exceeds size limit.");
952
+ return JSON.parse(text2);
953
+ };
954
+ route("settings", ["GET", "POST"], async (r) => r.method === "GET" ? snapshot() : operate({ ...await body(r), action: "save" }, r.signal));
955
+ route("action", ["POST"], async (r) => operate(await body(r), r.signal));
956
+ route("credential", ["POST"], async (r) => operate({ ...await body(r), action: "credential" }, r.signal));
957
+ const tools = ctx.get("tools");
958
+ ctx.effect(() => tools.register({ name: "search_manage", description: "Inspect or configure the DSH search plugin, explicitly test an enabled backend (may incur charges), manage credentials, or clear caches/diagnostics. Configuration uses an expectedRevision from settings. Never enable a paid backend without user authorization. Credential values are never returned.", parameters: { type: "object", properties: { action: { type: "string", enum: ["settings", "save", "test", "clear-cache", "clear-diagnostics", "credential", "activate"] }, config: { type: "object", additionalProperties: true }, expectedRevision: { type: "string" }, backendId: { type: "string" }, query: { type: "string" }, ref: { type: "string" }, value: { type: "string" }, remove: { type: "boolean" } }, required: ["action"] }, output: { schema: { type: "object", additionalProperties: true }, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] }, execute: (args, exec) => operate(args, exec.signal) }));
959
+ }
960
+ export {
961
+ Config,
962
+ apply,
963
+ defaultConfig,
964
+ inject,
965
+ name,
966
+ validateConfig
967
+ };
968
+ //# sourceMappingURL=index.js.map