@240xu/dsh-websearch 2.9.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -92,16 +92,18 @@ pnpm install
92
92
  > 每个 API Key 字段旁有 **「获取 Key ↗」** 直达对应平台控制台;保存即写入凭证库并立即生效。
93
93
 
94
94
 
95
- 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 23 个开关/参数;缓存、熔断、历史、多查询、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 profile patch 配置:
95
+ 插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 24 个开关/参数(共 60 个配置字段);缓存、熔断、历史、多查询、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 profile patch 配置:
96
96
 
97
97
  **全局**
98
98
 
99
99
  | 字段 | 默认 | 说明 |
100
100
  |---|---|---|
101
101
  | `intervention` | balanced | 搜索介入程度:`official` / `balanced` / `thorough`(见下表) |
102
- | `numResults` | 10 | 每次搜索返回结果数(1-50;official 档沿用宿主工具的条数上限) |
102
+ | `numResults` | 10 | 每次搜索返回结果数(1-100;Exa 上限 100,official 档沿用宿主工具的条数上限) |
103
+ | `includeDomains` | 空 | 仅允许这些域名(逗号/空格分隔,最多 20;OpenAI/Anthropic 原生后端生效) |
104
+ | `excludeDomains` | 空 | 排除这些域名(最多 20;同时设置时原生后端优先 allow) |
103
105
  | `concurrency` | 6 | 并发后端数(1-10) |
104
- | `backendTimeoutMs` | 30000 | 单后端超时毫秒 |
106
+ | `backendTimeoutMs` | 24000 | 单后端超时毫秒(为宿主 30s 工具超时预留余量) |
105
107
  | `recency` | any | 时间范围过滤:day / week / month / year(映射到各后端原生参数) |
106
108
  | `language` | 空 | 搜索语言,如 en、zh-CN(SearXNG/Brave/Serper 支持) |
107
109
  | `safeSearch` | true | 安全搜索开关(SearXNG/Brave 支持) |
@@ -170,7 +172,7 @@ pnpm install
170
172
 
171
173
  ### 4. per-backend 超时上限(P2)
172
174
 
173
- - `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)`,全局默认仍 30s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
175
+ - `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)`,全局默认 24s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
174
176
 
175
177
  ## v2.7.3 兼容修复 | What's new in v2.7.3
176
178
 
@@ -227,7 +229,7 @@ pnpm install
227
229
  - **Dedup strategies**: `url` keeps the historical URL-key merge with cross-backend field fill-in; `url+title` additionally collapses same-story syndicated mirrors (title Jaccard >= 0.9, CJK-aware tokenizer) while still enriching the kept entry.
228
230
  - **Deterministic rerank (optional)**: query-term overlap scoring (title x3 / snippet x2 / URL x1); stable ties preserve fan-out priority — same input always yields the same order.
229
231
  - **Honest timeouts**: each backend runs under an internal abort controller merged into the caller signal; when only the internal timer fires, the failure is reclassified as WEB_PROVIDER_ERROR ("backend <id> timed out") instead of being masked as a user cancellation.
230
- - **Concurrency & Timeout Control**: `concurrency` (default 6) limits simultaneous calls; `backendTimeoutMs` (default 30s) caps each backend.
232
+ - **Concurrency & Timeout Control**: `concurrency` (default 6) limits simultaneous calls; `backendTimeoutMs` (default 24s) caps each backend.
231
233
  - **Streamable-http MCP, custom handshake**: `lib/util/mcp-client.js` implements `initialize → notifications/initialized → tools/call` with `Mcp-Session-Id` header caching and `MCP-Protocol-Version` after initialization, against Exa, Parallel, Firecrawl and TinyFish — no dependency on the full MCP SDK.
232
234
  - **Host-logger diagnostics**: each backend routes request/outcome through lib/util/log.js to the host logger (ctx.logger), best-effort and never thrown - deliberately NOT session events: the session event vocabulary is a closed set third-party plugins must not extend (an unknown envelope type makes the whole session log unreadable).
233
235
 
@@ -264,7 +266,7 @@ tests/
264
266
  node --test tests/
265
267
  ```
266
268
 
267
- 当前 213/213 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
269
+ 当前 220/220 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
268
270
 
269
271
  ### Test-only dependencies
270
272
 
@@ -277,7 +279,7 @@ live service before running the suite:
277
279
  ```bash
278
280
  bash tests/relink-test-deps.sh # derives the scope from dsh-web.service MainPID
279
281
  find node_modules/@deepseek-ai -xtype l # expect no output
280
- node --test tests/*.test.js # 213/213
282
+ node --test tests/*.test.js # 220/220
281
283
  ```
282
284
 
283
285
  v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)〔历史快照;当前口径见上〕。
@@ -86,6 +86,11 @@ export function createAnthropicLikeBackend(spec) {
86
86
  const maxUses = options.maxUses ?? 5;
87
87
  const endpoint = `${baseURL.replace(/\/$/, "")}/messages`;
88
88
 
89
+ const domainArgs = Array.isArray(options?.includeDomains) && options.includeDomains.length > 0
90
+ ? { allowed_domains: options.includeDomains }
91
+ : Array.isArray(options?.excludeDomains) && options.excludeDomains.length > 0
92
+ ? { blocked_domains: options.excludeDomains }
93
+ : {};
89
94
  const body = {
90
95
  model,
91
96
  max_tokens: maxTokens,
@@ -100,7 +105,7 @@ export function createAnthropicLikeBackend(spec) {
100
105
  ],
101
106
  },
102
107
  ],
103
- tools: [{ type: toolName, name: "web_search", max_uses: maxUses }],
108
+ tools: [{ type: toolName, name: "web_search", max_uses: maxUses, ...domainArgs }],
104
109
  };
105
110
 
106
111
  hooks.recordRequest?.({
@@ -41,7 +41,7 @@ export const exaBackend = {
41
41
  async search(request, signal, options, hooks = {}) {
42
42
  const args = {
43
43
  query: request.query,
44
- numResults: request.maxResults ?? 8,
44
+ numResults: Math.max(1, Math.min(Number(request.maxResults) || 10, 100)),
45
45
  };
46
46
  // v2.8.0: category inference — deepCoverage-gated like tavily (searchDepth
47
47
  // advanced) and searxng (category sweep): 2.8.1 审计发现此处漏了门控,
@@ -78,7 +78,7 @@ export const exaBackend = {
78
78
  throw new WebError(`exa returned an MCP error: ${message}`, "WEB_PROVIDER_ERROR");
79
79
  }
80
80
 
81
- const sources = parseExaResult(result, request.maxResults ?? 8);
81
+ const sources = parseExaResult(result, Math.max(1, Math.min(Number(request.maxResults) || 10, 100)));
82
82
  hooks.recordOutcome?.({ status: "ok", count: sources.length });
83
83
 
84
84
  return { sources, content: undefined, truncated: false };
@@ -53,9 +53,15 @@ export const openaiBackend = {
53
53
  const model = options.model || "gpt-4o";
54
54
  const endpoint = `${baseURL}/responses`;
55
55
 
56
+ const domainFilters = {};
57
+ if (Array.isArray(options?.includeDomains) && options.includeDomains.length > 0) domainFilters.allowed_domains = options.includeDomains;
58
+ if (Array.isArray(options?.excludeDomains) && options.excludeDomains.length > 0) domainFilters.blocked_domains = options.excludeDomains;
56
59
  const body = {
57
60
  model,
58
- tools: [{ type: "web_search" }],
61
+ tools: [{
62
+ type: "web_search",
63
+ ...(Object.keys(domainFilters).length > 0 ? { filters: domainFilters } : {}),
64
+ }],
59
65
  input: request.query,
60
66
  };
61
67
 
package/lib/cache.js CHANGED
@@ -30,13 +30,13 @@ export const CACHE_DEFAULTS = {
30
30
  /**
31
31
  * Compute the deterministic cache key for a search.
32
32
  * The key covers the shaped query, filters, the effective maxResults, the
33
- * enabledBackends set (sorted), the cache mode, and every non-function result
34
- * option: switching the backend mix or editing a result-affecting setting
35
- * must never serve a stale result within the TTL (arch-review P1-1).
33
+ * enabledBackends selection **in fan-out order**, the cache mode, and every
34
+ * non-function result option: switching the mix or reordering it can change
35
+ * which duplicate's title/snippet wins, so both must miss (arch-review P1-1).
36
36
  * Pure function; exported for tests and host reuse.
37
37
  */
38
38
  export function cacheKeyFor({ query, filters, maxResults, backends, mode, resultOptions }) {
39
- const backendSet = Array.isArray(backends) ? [...backends].sort().join(",") : "";
39
+ const backendSet = Array.isArray(backends) ? backends.join(",") : "";
40
40
  let shaped = {};
41
41
  if (resultOptions && typeof resultOptions === "object") {
42
42
  const keys = Object.keys(resultOptions).filter((k) =>
@@ -71,12 +71,18 @@ function ageSeconds(record, nowMs) {
71
71
  export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntries = CACHE_DEFAULTS.maxEntries }) {
72
72
  // ttlMs may be a number or () => number (settings can change at runtime).
73
73
  const ttlOf = typeof ttlMs === "function" ? ttlMs : () => Number(ttlMs) || 0;
74
+ // ttl 0 means "do not store": no read, no write, no diagnostic note.
75
+ const noStore = () => {
76
+ try { return Math.max(0, Number(ttlOf()) || 0) === 0; } catch { return false; }
77
+ };
74
78
  const cap = Math.max(1, Math.floor(Number(maxEntries) || CACHE_DEFAULTS.maxEntries));
75
79
 
76
80
  const fileFor = (key) => path.join(dir, `${key}.json`);
77
81
 
78
82
  function ensureDir() {
79
- mkdirSync(dir, { recursive: true });
83
+ // Query text and results are user data; keep them owner-only.
84
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
85
+ try { chmodSync(dir, 0o700); } catch { /* existing dir owned by another mode */ }
80
86
  }
81
87
 
82
88
  /**
@@ -87,7 +93,7 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
87
93
  function atomicWrite(file, data) {
88
94
  const tmp = `${file}.${process.pid}.tmp`;
89
95
  try {
90
- writeFileSync(tmp, data, "utf8");
96
+ writeFileSync(tmp, data, { encoding: "utf8", mode: 0o600 });
91
97
  renameSync(tmp, file);
92
98
  } catch (err) {
93
99
  // A failed rename must not leave an orphan tmp counted outside the cap.
@@ -126,7 +132,21 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
126
132
  // an over-cap write pays the stat() of every entry. Trimming to a low-water
127
133
  // mark (10%, at least one) keeps that scan amortized over ~cap/10 writes
128
134
  // instead of running synchronously on every single write.
135
+ /** Remove crash-orphaned tmp files; the cap only counts `.json`. */
136
+ function sweepTmp(maxAgeMs = 3600_000) {
137
+ if (!existsSync(dir)) return;
138
+ const now = Date.now();
139
+ for (const name of readdirSync(dir)) {
140
+ if (!name.includes(".tmp")) continue;
141
+ const file = path.join(dir, name);
142
+ try {
143
+ if (now - statSync(file).mtimeMs >= maxAgeMs) unlinkSync(file);
144
+ } catch { /* raced */ }
145
+ }
146
+ }
147
+
129
148
  function evict() {
149
+ sweepTmp();
130
150
  if (countEntries() <= cap) return;
131
151
  const entries = listEntries();
132
152
  const lowWater = Math.max(1, cap - Math.max(1, Math.ceil(cap * 0.1)));
@@ -142,27 +162,32 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
142
162
  * @returns {{ value: object, age: number } | null} age in seconds; null on miss/expiry
143
163
  */
144
164
  get(key, nowMs = Date.now()) {
165
+ if (noStore()) return null;
166
+ const file = fileFor(key);
167
+ let record;
145
168
  try {
146
- const file = fileFor(key);
147
169
  if (!existsSync(file)) return null;
148
- const record = JSON.parse(readFileSync(file, "utf8"));
149
- if (!record || typeof record !== "object" || !record.value) return null;
150
- const age = ageSeconds(record, nowMs);
151
- const ttl = Math.max(0, Number(ttlOf()) || 0);
152
- if (age * 1000 > ttl) {
153
- try { unlinkSync(file); } catch { /* raced */ }
154
- return null;
155
- }
156
- return { value: record.value, age };
170
+ record = JSON.parse(readFileSync(file, "utf8"));
157
171
  } catch {
158
- // A corrupt/unreadable entry is re-parsed on every get; drop it.
159
- try { unlinkSync(fileFor(key)); } catch { /* raced */ }
172
+ // Corrupt/unreadable entry: drop it. A transient TTL error below must
173
+ // NOT delete a valid entry, so it is outside this catch.
174
+ try { unlinkSync(file); } catch { /* raced */ }
175
+ return null;
176
+ }
177
+ if (!record || typeof record !== "object" || !record.value) {
178
+ try { unlinkSync(file); } catch { /* raced */ }
160
179
  return null;
161
180
  }
181
+ let ttl;
182
+ try { ttl = Math.max(0, Number(ttlOf()) || 0); } catch { return null; }
183
+ const age = ageSeconds(record, nowMs);
184
+ if (age * 1000 > ttl) return null;
185
+ return { value: record.value, age };
162
186
  },
163
187
 
164
188
  /** Store a result (best-effort; fs errors are swallowed). */
165
189
  set(key, value, nowMs = Date.now()) {
190
+ if (noStore()) return;
166
191
  try {
167
192
  ensureDir();
168
193
  atomicWrite(fileFor(key), JSON.stringify({ key, time: nowMs, value }));
@@ -175,6 +200,7 @@ export function createSearchCache({ dir, ttlMs = CACHE_DEFAULTS.ttlMs, maxEntrie
175
200
  /** Drop every cached entry (best-effort). */
176
201
  clear() {
177
202
  try {
203
+ sweepTmp(0);
178
204
  for (const e of listEntries()) {
179
205
  try { unlinkSync(e.file); } catch { /* raced */ }
180
206
  }
package/lib/client.js CHANGED
@@ -108,13 +108,14 @@ window.__ModuleLoader__.load({
108
108
  keySaveModeHint: "开关即时生效;密钥填写后需点「保存」写入凭证库",
109
109
  keySet: "已配置",
110
110
  keyUnset: "未配置",
111
+ keyChecking: "检查中…",
111
112
  togglesTitle: "启用后端",
112
113
  globalsTitle: "全局参数",
113
114
  numResultsLabel: "结果条数",
114
115
  concurrencyLabel: "并发数",
115
116
  timeoutLabel: "后端超时 (ms)",
116
117
  saveFailed: "保存失败",
117
- conflictHint: "其他端已修改,请先刷新",
118
+ conflictHint: "其他端已修改,已重新载入;请再次保存",
118
119
  shapingTitle: "结果策略",
119
120
  recencyLabel: "时间范围",
120
121
  langLabel: "搜索语言",
@@ -145,6 +146,7 @@ window.__ModuleLoader__.load({
145
146
  interventionHint: "official 把查询与结果呈现完全交给官方工具;balanced 只剥明确的口语前缀;thorough 会重排并扩大后端请求,延迟与额度消耗更高。内部多查询仍是独立开关。",
146
147
  unavailable: "设置暂不可用:宿主没有返回配置快照(服务未就绪或路由未挂载)。",
147
148
  retry: "重试",
149
+ loading: "载入中…",
148
150
  toggleFailed: "开关未生效",
149
151
  optionalTitle: "可选 Key(私有实例 / 提升计量型额度)",
150
152
  };
@@ -191,13 +193,14 @@ window.__ModuleLoader__.load({
191
193
  keySaveModeHint: "The switch applies immediately; the key is written to the credential store when you press Save",
192
194
  keySet: "configured",
193
195
  keyUnset: "not set",
196
+ keyChecking: "Checking…",
194
197
  togglesTitle: "Enabled backends",
195
198
  globalsTitle: "Global parameters",
196
199
  numResultsLabel: "Results",
197
200
  concurrencyLabel: "Concurrency",
198
201
  timeoutLabel: "Backend timeout (ms)",
199
202
  saveFailed: "Save failed",
200
- conflictHint: "Changed elsewhere — refresh first",
203
+ conflictHint: "Changed elsewhere — reloaded; press Save again",
201
204
  shapingTitle: "Result shaping",
202
205
  recencyLabel: "Recency",
203
206
  langLabel: "Language",
@@ -231,12 +234,13 @@ window.__ModuleLoader__.load({
231
234
  interventionHint: "official leaves query construction and presentation to the host tool; balanced strips only explicit conversational prefixes; thorough reranks and widens backend requests, costing more latency and quota. Internal multi-query stays a separate opt-in.",
232
235
  unavailable: "Settings are unavailable: the host returned no configuration snapshot (service not ready or route not mounted).",
233
236
  retry: "Retry",
237
+ loading: "Loading…",
234
238
  toggleFailed: "Toggle failed",
235
239
  optionalTitle: "Optional keys (private instance / higher metered limits)",
236
240
  };
237
241
 
238
242
  //#region styles
239
- const css = ".wsc-card{display:flex;flex-direction:column;gap:8px}.wsc-sectionTitle{margin:24px 0 0;font-size:14px;font-weight:500;line-height:20px;color:var(--dsw-alias-label-primary)}.wsc-toggles{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:6px}.wsc-toggle{display:flex;align-items:center;gap:8px;padding:7px 10px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);cursor:pointer;font-size:13px;color:var(--dsw-alias-label-primary);background:0 0;transition:background-color .16s,border-color .16s}@media (hover:hover){.wsc-toggle:hover{background:var(--dsw-alias-interactive-bg-hover)}}.wsc-toggle input{accent-color:var(--dsw-alias-brand-primary)}.wsc-toggle:has(input:focus-visible){outline:none;box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.wsc-toggle input:focus-visible{outline:none}.wsc-input,.wsc-keyInput{box-sizing:border-box;height:34px;width:100%;padding:0 12px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:13px;font-family:inherit}.wsc-input:focus,.wsc-keyInput:focus{outline:none;border-color:var(--dsw-alias-state-business-primary)}.wsc-input:disabled,.wsc-keyInput:disabled{opacity:.6;cursor:default}.wsc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px}.wsc-fieldHead{display:flex;justify-content:space-between;align-items:center;margin-bottom:3px}.wsc-label{font-size:13px;font-weight:500;color:var(--dsw-alias-label-primary)}.wsc-badge{font-size:11px;padding:1px 8px;border-radius:var(--dsw-radius-xs);border:.5px solid var(--dsw-alias-border-l3);color:var(--dsw-alias-label-secondary)}.wsc-badgeOn{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-state-success-primary)}.wsc-hint{font-size:12px;line-height:1.5;color:var(--dsw-alias-label-secondary);margin:3px 0 0}.wsc-error{color:var(--dsw-alias-state-error-primary);font-size:12px}.wsc-warn{color:var(--dsw-alias-state-warn-label);font-size:12px}.wsc-strip{border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm);background:var(--dsw-alias-bg-module-platform)}.wsc-keyCard{border:.5px solid var(--dsw-alias-settings-card-stroke);border-radius:var(--dsw-radius-xl);background:var(--dsw-alias-settings-card-fill)}.wsc-actions{position:sticky;bottom:0;display:flex;gap:8px;align-items:center;padding:8px 0;background:var(--dsw-alias-bg-layer-2);border-top:.5px solid var(--dsw-alias-border-l2)}.wsc-btn{box-sizing:border-box;cursor:pointer;border:none;border-radius:var(--dsw-radius-md);height:36px;padding:0 14px;font-size:14px;line-height:22px;font-family:inherit;background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground)}.wsc-btn:hover:not(.wsc-btnGhost):not(:disabled){background:var(--dsw-alias-button-primary-hover)}.wsc-btn:focus-visible{outline:none;box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.wsc-btnGhost{background:0 0;color:var(--dsw-alias-label-primary);border:.5px solid var(--dsw-alias-border-l3)}.wsc-btnGhost:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover-solid);color:var(--dsw-alias-label-primary)}.wsc-btn:disabled{opacity:.4;cursor:default}.wsc-status{font-size:12px;color:var(--dsw-alias-label-secondary)}.wsc-dot{width:8px;height:8px;border-radius:50%;display:inline-block}.wsc-dotOn{background:var(--dsw-alias-state-success-primary)}.wsc-dotWarn{background:var(--dsw-alias-state-warn-primary)}.wsc-dotOff{background:var(--dsw-alias-label-tertiary)}.wsc-link:hover{text-decoration:underline}.wsc-card fieldset[disabled] .wsc-toggle{opacity:.6;cursor:default}";
243
+ const css = ".wsc-card{display:flex;flex-direction:column;gap:8px}.wsc-sectionTitle{margin:24px 0 0;font-size:14px;font-weight:500;line-height:20px;color:var(--dsw-alias-label-primary)}.wsc-toggles{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:6px}.wsc-toggle{display:flex;align-items:center;gap:8px;padding:7px 10px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);cursor:pointer;font-size:13px;color:var(--dsw-alias-label-primary);background:0 0;transition:background-color .16s,border-color .16s}@media (hover:hover){.wsc-toggle:hover{background:var(--dsw-alias-interactive-bg-hover)}}.wsc-toggle input{accent-color:var(--dsw-alias-brand-primary)}.wsc-toggle:has(input:focus-visible){outline:none;box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.wsc-toggle input:focus-visible{outline:none}.wsc-input,.wsc-keyInput{box-sizing:border-box;height:32px;width:100%;padding:0 10px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:14px;line-height:22px;font-family:inherit}select.wsc-input{cursor:pointer;max-width:240px}.wsc-input:focus,.wsc-keyInput:focus{outline:none;border-color:var(--dsw-alias-state-business-primary)}.wsc-input:disabled,.wsc-keyInput:disabled{opacity:.6;cursor:default}.wsc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px}.wsc-fieldHead{display:flex;justify-content:space-between;align-items:center;margin-bottom:3px}.wsc-label{font-size:13px;font-weight:500;color:var(--dsw-alias-label-primary)}.wsc-badge{font-size:11px;padding:1px 8px;border-radius:var(--dsw-radius-xs);border:.5px solid var(--dsw-alias-border-l3);color:var(--dsw-alias-label-secondary)}.wsc-badgeOn{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-state-success-primary)}.wsc-hint{font-size:12px;line-height:1.5;color:var(--dsw-alias-label-secondary);margin:3px 0 0}.wsc-error{color:color-mix(in srgb,var(--dsw-alias-state-error-primary) 85%,var(--dsw-alias-label-primary));font-size:12px}.wsc-warn{color:color-mix(in srgb,var(--dsw-alias-state-warn-label) 65%,var(--dsw-alias-label-primary));font-size:12px}.wsc-strip{border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm);background:var(--dsw-alias-bg-module-platform)}.wsc-keyCard{border:.5px solid var(--dsw-alias-settings-card-stroke);border-radius:var(--dsw-radius-xl);background:var(--dsw-alias-settings-card-fill)}.wsc-live{display:flex;gap:8px;align-items:center;flex-wrap:wrap;min-height:16px}.wsc-actionsStatic{position:static;border-top:0;padding:0;background:transparent}.wsc-actions{position:sticky;bottom:0;display:flex;gap:8px;align-items:center;padding:8px 0;background:var(--dsw-alias-bg-layer-2);border-top:.5px solid var(--dsw-alias-border-l2)}.wsc-btn{box-sizing:border-box;cursor:pointer;border:none;border-radius:var(--dsw-radius-md);height:36px;padding:0 14px;font-size:14px;line-height:22px;font-family:inherit;background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground)}.wsc-btn:hover:not(.wsc-btnGhost):not(:disabled){background:var(--dsw-alias-button-primary-hover)}.wsc-btn:focus-visible{outline:none;box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.wsc-btnGhost{background:0 0;color:var(--dsw-alias-label-primary);border:.5px solid var(--dsw-alias-border-l3)}.wsc-btnGhost:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover-solid);color:var(--dsw-alias-label-primary)}.wsc-btn:disabled{opacity:.4;cursor:default}.wsc-status{font-size:12px;color:var(--dsw-alias-label-secondary)}.wsc-status.wsc-error{color:color-mix(in srgb,var(--dsw-alias-state-error-primary) 85%,var(--dsw-alias-label-primary))}.wsc-status.wsc-warn{color:color-mix(in srgb,var(--dsw-alias-state-warn-label) 65%,var(--dsw-alias-label-primary))}.wsc-dot{width:8px;height:8px;border-radius:50%;display:inline-block}.wsc-dotOn{background:var(--dsw-alias-state-success-primary)}.wsc-dotWarn{background:var(--dsw-alias-state-warn-primary)}.wsc-dotOff{background:var(--dsw-alias-label-tertiary)}.wsc-link{color:color-mix(in srgb,var(--dsw-alias-link) 90%,var(--dsw-alias-label-primary));text-decoration:none;border-radius:var(--dsw-radius-xs)}.wsc-link:hover{text-decoration:underline}.wsc-card fieldset[disabled] .wsc-toggle{opacity:.6;cursor:default}.wsc-card fieldset[disabled] .wsc-toggle:hover{background:transparent}";
240
244
  if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=\"dsh-websearch/card\"]") === null) {
241
245
  const tag = document.createElement("style");
242
246
  tag.dataset.plugin = "@240xu/dsh-websearch";
@@ -376,6 +380,8 @@ window.__ModuleLoader__.load({
376
380
 
377
381
  set(field, value) { return this.write([{ op: "set", path: [field], value }]); }
378
382
  unset(field) { return this.write([{ op: "unset", path: [field] }]); }
383
+ /** One POST for all staged field ops; the route accepts up to 64. */
384
+ setMany(ops) { return this.write(ops); }
379
385
  }
380
386
 
381
387
  /**
@@ -483,7 +489,17 @@ window.__ModuleLoader__.load({
483
489
  }
484
490
 
485
491
  /** Stage a field edit (clears the saved marker so the card shows "unsaved"). */
486
- edit(field, text) { this.savedAt = 0; this.staged.set(field, { text }); this.republish(); }
492
+ edit(field, text) {
493
+ const committed = String(this.sectionValue(field) ?? "");
494
+ if (String(text) === committed) {
495
+ // Reverting to the stored value is not a pending write.
496
+ if (this.staged.delete(field)) this.republish();
497
+ return;
498
+ }
499
+ this.savedAt = 0;
500
+ this.staged.set(field, { text });
501
+ this.republish();
502
+ }
487
503
  /** Drop a staged field edit; the stored value is untouched. */
488
504
  reset(field) { this.staged.delete(field); this.republish(); }
489
505
  /** Stage a credential draft; a blank draft is never staged so Save can drain. */
@@ -532,7 +548,6 @@ window.__ModuleLoader__.load({
532
548
  let reason;
533
549
  // A badge must not claim "not set" before the first read lands.
534
550
  this.keyState.set(ref, { ...(this.keyState.get(ref) ?? {}), pending: true });
535
- this.republish();
536
551
  try {
537
552
  let view;
538
553
  // Guard the namespace access: an undeclared remote service throws on
@@ -578,7 +593,12 @@ window.__ModuleLoader__.load({
578
593
  this.readErrors.set(ref, safeFailureReason({ code: reason }));
579
594
  }
580
595
  if (seq === this.credSeq.get(ref)) {
581
- this.keyState.set(ref, { ...(this.keyState.get(ref) ?? {}), pending: false });
596
+ const prev = this.keyState.get(ref) ?? {};
597
+ this.keyState.set(ref, {
598
+ ...prev,
599
+ ...(prev.configured === undefined ? { configured: false } : {}),
600
+ pending: false,
601
+ });
582
602
  }
583
603
  this.republish();
584
604
  }
@@ -634,6 +654,11 @@ window.__ModuleLoader__.load({
634
654
  const savedFieldRefs = new Map();
635
655
  const savedKeyRefs = new Map();
636
656
  try {
657
+ // Validate every staged field first, then commit the whole set in
658
+ // one POST (the route applies up to 64 ops atomically). Falling
659
+ // back to the per-field API keeps older hosts working.
660
+ const fieldOps = [];
661
+ const fieldOpNames = [];
637
662
  for (const [field, staged] of this.staged) {
638
663
  // Snapshot the entry BEFORE any await. edit() replaces the staged
639
664
  // entry with a new object, so identity comparison later detects an edit
@@ -641,37 +666,42 @@ window.__ModuleLoader__.load({
641
666
  // await would capture the NEW edit and delete it as if saved.
642
667
  savedFieldRefs.set(field, staged);
643
668
  // Empty draft clears the override so the schema default applies again.
644
- if (staged.clear || staged.text === "") { await this.scope.unset(field); doneFields.push(field); continue; }
669
+ if (staged.clear || staged.text === "") { fieldOps.push({ op: "unset", path: [field] }); fieldOpNames.push(field); continue; }
645
670
  if (SELECT_FIELDS[field]) {
646
671
  if (!SELECT_FIELDS[field].includes(staged.text)) { this.failed = true; this.failedFields.add(field); continue; }
647
- await this.scope.set(field, staged.text);
648
- doneFields.push(field);
649
- continue;
672
+ fieldOps.push({ op: "set", path: [field], value: staged.text }); fieldOpNames.push(field); continue;
650
673
  }
651
674
  if (BOOLEAN_FIELDS.includes(field)) {
652
675
  if (staged.text !== "true" && staged.text !== "false") { this.failed = true; this.failedFields.add(field); continue; }
653
- await this.scope.set(field, staged.text === "true");
654
- doneFields.push(field);
655
- continue;
676
+ fieldOps.push({ op: "set", path: [field], value: staged.text === "true" }); fieldOpNames.push(field); continue;
656
677
  }
657
678
  if (GLOBAL_FIELDS.includes(field)) {
658
679
  const num = Number(staged.text);
659
680
  // Mirror the server schema bounds client-side so bad input is
660
681
  // caught in the UI instead of a failed Host round-trip.
661
682
  const BOUNDS = {
662
- numResults: [1, 50],
683
+ numResults: [1, 100],
663
684
  concurrency: [1, 10],
664
685
  backendTimeoutMs: [1000, 120000],
665
686
  };
666
687
  const [lo, hi] = BOUNDS[field] ?? [-Infinity, Infinity];
667
- if (!Number.isFinite(num) || num < lo || num > hi) { this.failed = true; this.failedFields.add(field); continue; }
668
- await this.scope.set(field, num);
669
- doneFields.push(field);
688
+ if (!Number.isInteger(num) || num < lo || num > hi) { this.failed = true; this.failedFields.add(field); continue; }
689
+ fieldOps.push({ op: "set", path: [field], value: num }); fieldOpNames.push(field);
670
690
  } else {
671
- await this.scope.set(field, staged.text);
672
- doneFields.push(field);
691
+ fieldOps.push({ op: "set", path: [field], value: staged.text }); fieldOpNames.push(field);
673
692
  }
674
693
  }
694
+ if (fieldOps.length > 0) {
695
+ if (typeof this.scope.setMany === "function") {
696
+ await this.scope.setMany(fieldOps);
697
+ } else {
698
+ for (const op of fieldOps) {
699
+ if (op.op === "unset") await this.scope.unset(op.path[0]);
700
+ else await this.scope.set(op.path[0], op.value);
701
+ }
702
+ }
703
+ doneFields.push(...fieldOpNames);
704
+ }
675
705
  for (const [ref, staged] of this.stagedKeys) {
676
706
  // Snapshot before any await, same reason as the field loop.
677
707
  savedKeyRefs.set(ref, staged);
@@ -755,6 +785,7 @@ window.__ModuleLoader__.load({
755
785
  react_jsx_runtime.jsx("span", { className: dotClass }),
756
786
  react_jsx_runtime.jsx("span", { children: props.t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }),
757
787
  needsKey && checked && react_jsx_runtime.jsx("span", { style: { fontSize: 10, opacity: .65 }, children: props.t("keyMissing") }),
788
+ props.toggleError && react_jsx_runtime.jsx("span", { className: "wsc-hint wsc-error", children: props.t("toggleFailed") }),
758
789
  ] });
759
790
  }
760
791
 
@@ -773,13 +804,14 @@ window.__ModuleLoader__.load({
773
804
  const checked = props.value === true;
774
805
  const configured = !!state.keyState[b.keyEnv]?.configured;
775
806
  const readOnly = configured && state.keyState[b.keyEnv]?.writable === false;
807
+ const locked = readOnly || props.locked === true;
776
808
  // failedKeys is an array of { ref, reason }, NOT an array of strings.
777
809
  const failure = (state.failedKeys ?? []).find((f) => f && f.ref === b.keyEnv);
778
810
  const readFailure = (state.readErrors ?? []).find((f) => f && f.ref === b.keyEnv);
779
811
  const needsKey = !configured;
780
812
  const dotClass = "wsc-dot " + (needsKey ? (checked ? "wsc-dotWarn" : "wsc-dotOff") : "wsc-dotOn");
781
813
  return react_jsx_runtime.jsxs("div", { className: "wsc-keyCard", style: { display: "flex", flexDirection: "column", gap: 6, padding: "9px 10px" }, children: [
782
- react_jsx_runtime.jsxs("label", { className: "wsc-toggle", style: { display: "flex", alignItems: "center", gap: 8, cursor: "pointer", padding: 0, border: "none", borderRadius: 0 }, children: [
814
+ react_jsx_runtime.jsxs("label", { className: "wsc-toggle", style: { display: "flex", alignItems: "center", gap: 8, cursor: "pointer", padding: 0, border: "none", borderRadius: "var(--dsw-radius-sm)" }, children: [
783
815
  react_jsx_runtime.jsx("input", { type: "checkbox", checked, onChange: (e) => props.onToggle(e.target.checked) }),
784
816
  react_jsx_runtime.jsx("span", { className: dotClass }),
785
817
  react_jsx_runtime.jsx("span", { children: props.t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }),
@@ -787,19 +819,19 @@ window.__ModuleLoader__.load({
787
819
  ] }),
788
820
  props.toggleError && react_jsx_runtime.jsx("p", { className: "wsc-hint wsc-error", children: props.t("toggleFailed") }),
789
821
  react_jsx_runtime.jsxs("div", { style: { display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }, children: [
790
- react_jsx_runtime.jsx("span", { className: "wsc-badge" + (configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.pending === true ? props.t("keyChecking") : configured ? props.t("keySet") : props.t("keyUnset") }),
791
- readOnly && react_jsx_runtime.jsx("span", { className: "wsc-badge", style: { opacity: .75 }, children: props.t("envProvided") }),
822
+ react_jsx_runtime.jsx("span", { className: "wsc-badge" + (configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.configured === undefined ? props.t("keyChecking") : configured ? props.t("keySet") : props.t("keyUnset") }),
823
+ readOnly && react_jsx_runtime.jsx("span", { className: "wsc-badge", children: props.t("envProvided") }),
792
824
  KEY_URLS[b.id] && react_jsx_runtime.jsx("a", {
793
- href: KEY_URLS[b.id], target: "_blank", rel: "noreferrer",
794
- style: { fontSize: 11, color: "var(--dsw-alias-link)", textDecoration: "none" },
825
+ href: KEY_URLS[b.id], target: "_blank", rel: "noreferrer", className: "wsc-link",
826
+ style: { fontSize: 11 },
795
827
  children: props.t("getKey"),
796
828
  }),
797
829
  ] }),
798
830
  react_jsx_runtime.jsx("input", {
799
831
  className: "wsc-keyInput", type: "password", autoComplete: "off",
800
832
  "aria-label": props.t("keyLabel", { id: props.t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }),
801
- disabled: readOnly,
802
- placeholder: readOnly ? props.t("readOnly") : b.keyEnv,
833
+ disabled: locked,
834
+ placeholder: locked ? props.t("readOnly") : b.keyEnv,
803
835
  value: state.stagedKeys[b.keyEnv] ?? "",
804
836
  onChange: (e) => props.onEditKey(b.keyEnv, e.target.value),
805
837
  }),
@@ -873,6 +905,7 @@ window.__ModuleLoader__.load({
873
905
  react_jsx_runtime.jsx(KeyedBackendCard, {
874
906
  backend: b,
875
907
  state,
908
+ locked: state.writable === false,
876
909
  value: state.value[toggleField(b.id)],
877
910
  t,
878
911
  onToggle: (checked) => card.setToggle(b.id, checked),
@@ -987,13 +1020,13 @@ window.__ModuleLoader__.load({
987
1020
  return react_jsx_runtime.jsxs("div", { children: [
988
1021
  react_jsx_runtime.jsxs("div", { className: "wsc-fieldHead", children: [
989
1022
  react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("keyLabel", { id: t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }) }),
990
- react_jsx_runtime.jsx("span", { className: "wsc-badge" + (state.keyState[b.keyEnv]?.configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.pending === true ? t("keyChecking") : state.keyState[b.keyEnv]?.configured ? t("keySet") : t("keyUnset") }),
1023
+ react_jsx_runtime.jsx("span", { className: "wsc-badge" + (state.keyState[b.keyEnv]?.configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.configured === undefined ? t("keyChecking") : state.keyState[b.keyEnv]?.configured ? t("keySet") : t("keyUnset") }),
991
1024
  ] }),
992
1025
  react_jsx_runtime.jsx("input", {
993
1026
  className: "wsc-keyInput", type: "password", autoComplete: "off",
994
1027
  "aria-label": t("keyLabel", { id: t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }),
995
- disabled: state.keyState[b.keyEnv]?.configured && state.keyState[b.keyEnv]?.writable === false,
996
- placeholder: b.keyEnv,
1028
+ disabled: state.writable === false || (state.keyState[b.keyEnv]?.configured && state.keyState[b.keyEnv]?.writable === false),
1029
+ placeholder: state.writable === false ? t("readOnly") : b.keyEnv,
997
1030
  value: state.stagedKeys[b.keyEnv] ?? "",
998
1031
  onChange: (e) => card.editKey(b.keyEnv, e.target.value),
999
1032
  }),
@@ -1003,31 +1036,34 @@ window.__ModuleLoader__.load({
1003
1036
  ] }, b.id);
1004
1037
  }) }),
1005
1038
  state.stagedCount > 0 && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .65 }, children: t("unsavedHint") }),
1006
- react_jsx_runtime.jsxs("div", { className: "wsc-actions", role: "status", "aria-live": "polite", children: [
1039
+ react_jsx_runtime.jsxs("div", { className: "wsc-actions", children: [
1007
1040
  react_jsx_runtime.jsx("button", { className: "wsc-btn", disabled: state.saving || state.stagedCount === 0 || state.writable === false, onClick: () => card.save(), children: state.saving ? t("saving") : t("save") }),
1008
1041
  (state.stagedCount > 0) && react_jsx_runtime.jsx("button", { className: "wsc-btn wsc-btnGhost", disabled: state.saving, onClick: () => card.discard(), children: t("discard") }),
1009
- state.failed && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-error", children: state.conflict ? t("conflict") : t("saveFailed") }),
1010
- state.toggleFailed && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-error", children: t("toggleFailed") + (state.toggleConflict ? " — " + t("conflict") : "") }),
1011
- (state.failedFields.length > 0) && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-warn", children: t("invalidFields") + " " + state.failedFields.join(", ") }),
1012
- state.conflict && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-warn", children: t("conflictHint") }),
1013
- !state.failed && !state.saving && state.savedAt > 0 && react_jsx_runtime.jsx("span", { className: "wsc-status", children: t("savedOk") }),
1042
+ react_jsx_runtime.jsxs("span", { className: "wsc-live", role: "status", "aria-live": "polite", children: [
1043
+ state.failed && !state.conflict && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-error", children: t("saveFailed") }),
1044
+ state.toggleFailed && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-error", children: t("toggleFailed") + (state.toggleConflict ? " — " + t("conflict") : "") }),
1045
+ (state.failedFields.length > 0) && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-warn", children: t("invalidFields") + " " + state.failedFields.join(", ") }),
1046
+ state.conflict && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-warn", children: t("conflictHint") }),
1047
+ state.conflict && react_jsx_runtime.jsx("button", { className: "wsc-btn wsc-btnGhost", disabled: state.saving, onClick: () => card.retry(), children: t("retry") }),
1048
+ !state.failed && !state.saving && state.savedAt > 0 && react_jsx_runtime.jsx("span", { className: "wsc-status", children: t("savedOk") }),
1049
+ ] }),
1014
1050
  ] }),
1015
1051
  ] });
1016
1052
  }
1017
1053
 
1018
1054
  function UnifiedSearchSection(props) {
1019
1055
  const state = props.useUnifiedSearchCard((snapshot) => snapshot);
1020
- const card = { edit: props.edit, setToggle: props.setToggle, reset: props.reset, editKey: props.editKey, save: props.save, discard: props.discard };
1056
+ const card = { edit: props.edit, setToggle: props.setToggle, reset: props.reset, editKey: props.editKey, save: props.save, discard: props.discard, retry: props.retry };
1021
1057
  // Occupants of settings.plugin.item render inside the tab's <ul>; use <li>.
1022
1058
  if (!state.ready) {
1023
- return react_jsx_runtime.jsx("div", { className: "wsc-card", style: { fontSize: 12, opacity: .6 }, children: "…" });
1059
+ return react_jsx_runtime.jsx("div", { className: "wsc-card", style: { fontSize: 12, opacity: .6 }, role: "status", "aria-live": "polite", children: props.t("loading") });
1024
1060
  }
1025
1061
  // No snapshot at all (404/503): showing "0/13 enabled" plus live
1026
1062
  // controls would be a fabricated state. Explain it and offer a retry.
1027
1063
  if (state.unavailable) {
1028
1064
  return react_jsx_runtime.jsxs("div", { className: "wsc-card", children: [
1029
1065
  react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .75 }, children: props.t("unavailable") }),
1030
- react_jsx_runtime.jsx("div", { className: "wsc-actions", children: react_jsx_runtime.jsx("button", { className: "wsc-btn", onClick: () => props.retry(), children: props.t("retry") }) }),
1066
+ react_jsx_runtime.jsx("div", { className: "wsc-actions wsc-actionsStatic", children: react_jsx_runtime.jsx("button", { className: "wsc-btn", onClick: () => props.retry(), children: props.t("retry") }) }),
1031
1067
  ] });
1032
1068
  }
1033
1069
 
package/lib/history.js CHANGED
@@ -54,10 +54,10 @@ export function createHistoryStore({ dir, maxEntries = HISTORY_MAX_ENTRIES }) {
54
54
  }
55
55
 
56
56
  function atomicWriteAll(list) {
57
- mkdirSync(dir, { recursive: true });
57
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
58
58
  const f = file();
59
59
  const tmp = `${f}.${process.pid}.tmp`;
60
- writeFileSync(tmp, JSON.stringify(list, null, 2), "utf8");
60
+ writeFileSync(tmp, JSON.stringify(list, null, 2), { encoding: "utf8", mode: 0o600 });
61
61
  renameSync(tmp, f);
62
62
  }
63
63
 
package/lib/index.js CHANGED
@@ -161,11 +161,11 @@ export const Config = z.object({
161
161
  // Global
162
162
  intervention: z.union(["official", "balanced", "thorough"]).default("balanced")
163
163
  .description("搜索介入程度【策略】:official=只做官方 provider 该做的(原样查询、不加结果头/遥测、沿用工具的条数上限);balanced=确定性去噪 + 去重/遥测(默认);thorough=额外启用相关性重排与深度覆盖(内部多查询仍是独立开关,默认关)"),
164
- numResults: z.number().step(1).min(1).max(50).default(10)
164
+ numResults: z.number().step(1).min(1).max(100).default(10)
165
165
  .description("每次搜索返回的最大结果数(official 档沿用宿主工具的条数上限)"),
166
166
  concurrency: z.number().step(1).min(1).max(10).default(6)
167
167
  .description("同时并发的后端数量"),
168
- backendTimeoutMs: z.number().step(1000).min(1000).max(120000).default(30000)
168
+ backendTimeoutMs: z.number().step(1000).min(1000).max(120000).default(24000)
169
169
  .description("单后端最大等待时间(毫秒);ddg/searxng 另受 8s 专属上限约束"),
170
170
 
171
171
  // v2.1 result shaping
@@ -175,6 +175,10 @@ export const Config = z.object({
175
175
  .description("搜索语言(如 en、zh-CN;留空用各后端默认)"),
176
176
  safeSearch: z.boolean().default(true)
177
177
  .description("安全搜索(SearXNG / Brave 支持开关,其余后端忽略)"),
178
+ includeDomains: z.string().default("")
179
+ .description("只允许这些域名(逗号/空格分隔,最多 20 个;OpenAI/Anthropic 原生后端生效)"),
180
+ excludeDomains: z.string().default("")
181
+ .description("排除这些域名(逗号/空格分隔,最多 20 个;与 includeDomains 同时设置时原生后端优先 include)"),
178
182
  dedupStrategy: z.union(["url", "url+title"]).default("url")
179
183
  .description("去重策略:url 仅按链接;url+title 额外合并同标题的转载镜像"),
180
184
  rerank: z.boolean().default(false)
@@ -190,14 +194,14 @@ export const Config = z.object({
190
194
  // spelled out (秒 / 毫秒) and grouping follows the field order below.
191
195
  cacheEnabled: z.boolean().default(true)
192
196
  .description("启用搜索结果缓存【缓存】:相同查询+过滤+条数在有效期内直接命中,不再请求后端"),
193
- cacheTtl: z.number().step(30).min(30).max(86400).default(900)
197
+ cacheTtl: z.number().step(30).min(0).max(86400).default(900)
194
198
  .description("缓存有效期【缓存】(单位:秒):默认 900 秒;不想用缓存请直接关闭上一项"),
195
199
  breakerEnabled: z.boolean().default(true)
196
200
  .description("后端熔断器【熔断】:连续失败达阈值后暂停该后端一段时间;全部暂停时自动放行,不会让搜索更差"),
197
201
  breakerThreshold: z.number().step(1).min(1).max(20).default(BREAKER_DEFAULTS.threshold)
198
202
  .description("熔断阈值【熔断】:连续失败多少次后触发(默认 3 次)"),
199
203
  breakerCooldownMs: z.number().step(1000).min(0).max(3600000).default(BREAKER_DEFAULTS.cooldownMs)
200
- .description("熔断冷却时长【熔断】(单位:毫秒):默认 60000;设为 0 表示关闭冷却(熔断仅计数)"),
204
+ .description("熔断冷却时长【熔断】(单位:毫秒):默认 60000;0 关闭按阈值的冷却,带 Retry-After 的 429 仍按该窗口冷却"),
201
205
  historyEnabled: z.boolean().default(true)
202
206
  .description("记录搜索历史【历史】:只追加,最多 50 条;可在设置 → 搜索 中查看与清空"),
203
207
 
@@ -308,7 +312,7 @@ Config.meta = { ...Config.meta, volatile: true };
308
312
  const FIELD_LABELS = {
309
313
  intervention: "搜索介入程度",
310
314
  cacheEnabled: "启用搜索结果缓存",
311
- cacheTtl: "缓存有效期(秒)",
315
+ cacheTtl: "缓存有效期(秒);0 = 不缓存(no-store)",
312
316
  breakerEnabled: "后端熔断器",
313
317
  breakerThreshold: "熔断阈值(连续失败次数)",
314
318
  breakerCooldownMs: "熔断冷却时长(毫秒)",
@@ -327,6 +331,26 @@ for (const [key, label] of Object.entries(FIELD_LABELS)) {
327
331
  * serves its NEXT search with. Key resolution: credentialRef -> credentials
328
332
  * service -> env.
329
333
  */
334
+ /** Normalize a comma/space-domain setting into lowercase bare hostnames. */
335
+ function normalizeDomainList(raw) {
336
+ if (typeof raw !== "string" || raw.trim() === "") return [];
337
+ const out = [];
338
+ for (const piece of raw.split(/[,\s]+/)) {
339
+ const item = piece.trim().toLowerCase();
340
+ if (item === "") continue;
341
+ let host = item;
342
+ try {
343
+ const u = new URL(item.includes("://") ? item : "https://" + item);
344
+ host = u.hostname;
345
+ } catch { /* keep the raw token and validate below */ }
346
+ host = host.replace(/^\[|\]$/g, "");
347
+ if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(host)) continue;
348
+ if (!out.includes(host)) out.push(host);
349
+ if (out.length >= 20) break;
350
+ }
351
+ return out;
352
+ }
353
+
330
354
  export function resolveOptions(ctx, config) {
331
355
  // 1. Determine enabled backends: explicit list > toggles > env > defaults.
332
356
  // The four keyless toggles default to true, so the env fallback is reachable
@@ -377,6 +401,8 @@ export function resolveOptions(ctx, config) {
377
401
  : [],
378
402
  } : {}),
379
403
  safeSearch: config?.safeSearch !== false,
404
+ includeDomains: normalizeDomainList(config?.includeDomains),
405
+ excludeDomains: normalizeDomainList(config?.excludeDomains),
380
406
  label: DEFAULT_LABELS[id] ?? id,
381
407
  requiresKey: DEFAULT_KEY_ENV[id] !== undefined && !OPTIONAL_KEY_IDS.has(id),
382
408
  optionalKey: OPTIONAL_KEY_IDS.has(id),
@@ -410,7 +436,7 @@ export function resolveOptions(ctx, config) {
410
436
  // the user's explicit count (and still never exceed the host cap).
411
437
  numResults: official ? undefined : (config?.numResults ?? 10),
412
438
  concurrency: config?.concurrency ?? 6,
413
- backendTimeoutMs: config?.backendTimeoutMs ?? 30000,
439
+ backendTimeoutMs: config?.backendTimeoutMs ?? 24000,
414
440
  // v2.1 shaping options consumed by the provider merge pipeline.
415
441
  dedupStrategy: config?.dedupStrategy === "url+title" ? "url+title" : "url",
416
442
  rerank: thorough || (!official && config?.rerank === true),
@@ -418,7 +444,7 @@ export function resolveOptions(ctx, config) {
418
444
  resultTelemetry: official ? false : config?.resultTelemetry !== false,
419
445
  // v2.7.0 cache / breaker / history
420
446
  cacheEnabled: config?.cacheEnabled !== false,
421
- cacheTtlS: Math.max(30, Math.floor(Number(config?.cacheTtl) || CACHE_DEFAULTS.ttlMs / 1000)),
447
+ cacheTtlS: config?.cacheTtl == null ? CACHE_DEFAULTS.ttlMs / 1000 : Math.max(0, Math.floor(Number(config.cacheTtl))),
422
448
  breakerEnabled: config?.breakerEnabled !== false,
423
449
  breakerThreshold: Math.max(1, Math.floor(Number(config?.breakerThreshold) || BREAKER_DEFAULTS.threshold)),
424
450
  breakerCooldownMs: config?.breakerCooldownMs != null
@@ -432,6 +458,8 @@ export function resolveOptions(ctx, config) {
432
458
  // invisibly.
433
459
  multiQueryEnabled: !official && config?.multiQueryEnabled === true,
434
460
  deepCoverage: thorough || (!official && config?.deepCoverage === true),
461
+ includeDomains: normalizeDomainList(config?.includeDomains),
462
+ excludeDomains: normalizeDomainList(config?.excludeDomains),
435
463
  filters: {
436
464
  recency: typeof config?.recency === "string" && config.recency !== "any" ? config.recency : undefined,
437
465
  lang: language.length > 0 ? language : undefined,
package/lib/provider.js CHANGED
@@ -279,7 +279,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
279
279
  // a preference, not seam truncation.
280
280
  const seamBound = Number.isFinite(hostCap) && hostCap > 0 ? hostCap : Number.POSITIVE_INFINITY;
281
281
  const concurrency = opts.concurrency ?? 6;
282
- const backendTimeoutMs = opts.backendTimeoutMs ?? 30000;
282
+ const backendTimeoutMs = opts.backendTimeoutMs ?? 24000;
283
283
 
284
284
  // v2.8.0 coverage / multiQuery gates (both default OFF; arXiv:2404.01037
285
285
  // warns blind multi-query degrades, so the gate is deliberately strict).
@@ -331,6 +331,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
331
331
  }
332
332
  }
333
333
  resultOptions.queryLanguage = queryLanguage;
334
+ // The same min(host,user) can come from different host bounds; the
335
+ // truncated flag is relative to the host bound, so key it too.
336
+ resultOptions.hostMaxResults = Number.isFinite(hostCap) && hostCap > 0 ? hostCap : null;
334
337
  cacheKey = cacheKeyFor({ query: effReq.query, filters, maxResults, backends: opts.enabledBackends, mode: cacheMode, resultOptions });
335
338
  const hit = cache.get(cacheKey);
336
339
  if (hit && Array.isArray(hit.value?.sources) && hit.value.sources.length > 0) {
@@ -347,7 +350,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
347
350
  // `official` promises no provider-added text (the consumer owns
348
351
  // presentation), so the diagnostic cache note is gated with the
349
352
  // header rather than appended unconditionally.
350
- if (opts.resultHeader !== false) {
353
+ if (opts.resultTelemetry !== false) {
351
354
  const cacheNote = `[websearch cache] cache hit, age ${hit.age}s`;
352
355
  hitContent = hitContent === undefined ? cacheNote : hitContent + "\n\n" + cacheNote;
353
356
  }
@@ -426,7 +429,6 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
426
429
  "WEB_PROVIDER_ERROR",
427
430
  );
428
431
  }
429
- recordHistory(history, request?.query, 0, 0, candidates.length);
430
432
  throw new WebError(
431
433
  `unified search: all backends are rate-limited; retry after ~${waitS}s`,
432
434
  "WEB_PROVIDER_ERROR",
@@ -442,7 +444,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
442
444
  if (eligible.length === 0) {
443
445
  recordHistory(history, request?.query, 0, 0, candidates.length);
444
446
  throw new WebError(
445
- "unified search: no enabled backend is available (configure a backend or set an API key)",
447
+ "unified search: none of the enabled backend ids is registered",
446
448
  "WEB_PROVIDER_UNAVAILABLE",
447
449
  );
448
450
  }
@@ -450,7 +452,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
450
452
  // Run ONE query variant through the full fan-out: breaker-aware backend
451
453
  // execution under the per-variant limiter, then PHASE 1 collect. The
452
454
  // internal abort/timeout semantics are unchanged from v2.7.
453
- const fanoutVariant = async (variantReq, variantBudgetMs = Number.POSITIVE_INFINITY) => {
455
+ const fanoutVariant = async (variantReq, variantBudgetMs = Number.POSITIVE_INFINITY, deadline = Number.POSITIVE_INFINITY) => {
454
456
  const telemetry = [];
455
457
  // Health is folded once per backend per SEARCH, after every variant
456
458
  // finished: recording per variant let one multi-query search trip the
@@ -472,7 +474,11 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
472
474
  const mergedSignal = signal
473
475
  ? AbortSignal.any([signal, controller.signal])
474
476
  : controller.signal;
475
- const effectiveTimeoutMs = Math.max(1, Math.min(effectiveBackendTimeoutMs(id, backendTimeoutMs), variantBudgetMs));
477
+ const remainingNow = Number.isFinite(deadline) ? deadline - Date.now() : Number.POSITIVE_INFINITY;
478
+ if (remainingNow <= 0) {
479
+ return Promise.reject(new WebError(`backend "${id}" not started: search budget exhausted`, "WEB_PROVIDER_ERROR"));
480
+ }
481
+ const effectiveTimeoutMs = Math.max(1, Math.min(effectiveBackendTimeoutMs(id, backendTimeoutMs), variantBudgetMs, remainingNow));
476
482
  const timeoutId = setTimeout(() => controller.abort(), effectiveTimeoutMs);
477
483
  // A backend that ignores its signal (blackholed TCP, stuck proxy)
478
484
  // must not hold the whole fan-out past its budget. Race the call
@@ -497,7 +503,9 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
497
503
  // SearXNG's multi-instance split needs the effective budget to
498
504
  // divide it across candidates; without it the backend saw an
499
505
  // undefined budget and every instance got its own 4.5s.
500
- backend.search(variantReq, mergedSignal, { ...beOpts, backendTimeoutMs: effectiveTimeoutMs }, hooks),
506
+ Promise.resolve().then(() =>
507
+ backend.search(variantReq, mergedSignal, { ...beOpts, backendTimeoutMs: effectiveTimeoutMs }, hooks),
508
+ ),
501
509
  guard,
502
510
  ])
503
511
  .then(
@@ -506,7 +514,12 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
506
514
  // contract violation, not a successful zero-hit search; route
507
515
  // it through the failure path so telemetry/health agree.
508
516
  if (value === null || typeof value !== "object" || !Array.isArray(value.sources)) {
509
- throw new WebError(`backend "${id}" returned no sources[]`, "WEB_PROVIDER_ERROR");
517
+ // A throw from the fulfilment handler bypasses the sibling
518
+ // rejection handler, so record the failure here as well.
519
+ const reason = `backend "${id}" returned no sources[]`;
520
+ telemetry.push({ id, ok: false, ms: Date.now() - startedAtMs, error: reason });
521
+ health.push({ id, ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: reason });
522
+ throw new WebError(reason, "WEB_PROVIDER_ERROR");
510
523
  }
511
524
  telemetry.push({ id, ok: true, ms: Date.now() - startedAtMs, count: value.sources.length });
512
525
  health.push({ id, ok: true, at: Date.now(), ms: Date.now() - startedAtMs, count: value?.sources?.length ?? 0 });
@@ -531,10 +544,15 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
531
544
  : String(err instanceof Error ? err.message : err);
532
545
  const msg = sanitizeError(reason, 80);
533
546
  telemetry.push({ id, ok: false, ms: Date.now() - startedAtMs, error: msg });
534
- health.push({
535
- id, ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg,
536
- rateLimited: rateLimited(err), keylessRejected: keylessRejected(err), retryAfterMs: retryAfterMsFrom(err),
537
- });
547
+ // A missing API key is a configuration state, not an outage:
548
+ // folding it would cool the breaker and paint /health red for
549
+ // a backend the operator can fix in Settings.
550
+ if (!(err instanceof WebError && err.code === "WEB_PROVIDER_CREDENTIAL_MISSING")) {
551
+ health.push({
552
+ id, ok: false, at: Date.now(), ms: Date.now() - startedAtMs, error: msg,
553
+ rateLimited: rateLimited(err), keylessRejected: keylessRejected(err), retryAfterMs: retryAfterMsFrom(err),
554
+ });
555
+ }
538
556
  throw timedOut
539
557
  ? new WebError(reason, "WEB_PROVIDER_ERROR", { cause: err instanceof Error ? err : undefined })
540
558
  : err;
@@ -565,22 +583,31 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
565
583
  // One search-wide budget: sequential variants must not multiply the
566
584
  // per-backend timeout into N × 30s (which also exceeds the host's 30s
567
585
  // tool deadline). Later variants get only the time still left.
568
- const searchBudgetMs = Math.max(1, Number(opts.backendTimeoutMs) || 30000);
586
+ const searchBudgetMs = Math.max(1, Number(opts.backendTimeoutMs) || 24000);
569
587
  const searchDeadline = Date.now() + searchBudgetMs;
570
588
  let hardError = null;
571
589
  // Final outcome per backend across every variant. Success wins; otherwise
572
590
  // keep the latest failure and the most severe quota classification.
573
591
  const searchHealth = new Map();
574
- for (const variantQuery of variants) {
592
+ for (let variantIndex = 0; variantIndex < variants.length; variantIndex += 1) {
593
+ const variantQuery = variants[variantIndex];
575
594
  const remaining = searchDeadline - Date.now();
576
- if (remaining <= 0) break;
595
+ // Do not start a variant that cannot get a meaningful slice: its
596
+ // "timeout" would be budget exhaustion, not a backend outage, and
597
+ // would contradict a success from the same backend in variant 1.
598
+ const minVariantBudgetMs = Math.min(Number(opts.backendTimeoutMs) || 24000, 2000);
599
+ if (remaining < minVariantBudgetMs) break;
600
+ // Split the remaining budget across the variants still owed, so one
601
+ // slow variant cannot starve the rest (the old code gave each variant
602
+ // the full budget, and each backend inside it).
603
+ const share = Math.max(1, Math.floor(remaining / Math.max(1, variants.length - variantIndex)));
577
604
  const variantReq = {
578
605
  ...effReq,
579
606
  query: variantQuery,
580
607
  maxResults: backendMaxResults,
581
608
  ...(coverage ? { deepCoverage: true } : {}),
582
609
  };
583
- const fold = await fanoutVariant(variantReq, remaining);
610
+ const fold = await fanoutVariant(variantReq, share, searchDeadline);
584
611
  for (const outcome of fold.health) {
585
612
  const prev = searchHealth.get(outcome.id);
586
613
  if (prev === undefined || outcome.ok === true) {
@@ -627,7 +654,29 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
627
654
  // finished by this point so the array no longer grows. History counts
628
655
  // unique backends, not attempts: multi-query fans one backend out once
629
656
  // per variant, which used to report `backendsTotal` as variants × backends.
630
- const okCount = allTelemetry.filter((t) => t.ok).length;
657
+ // One display segment per backend, not per variant: a multi-query
658
+ // search otherwise repeats the same backend N times and can hide a
659
+ // backend beyond the 12-slot cap while health/history show it once.
660
+ const foldedTelemetry = [];
661
+ const telemetryById = new Map();
662
+ for (const t of allTelemetry) {
663
+ const prev = telemetryById.get(t.id);
664
+ if (prev === undefined) {
665
+ const copy = { ...t };
666
+ telemetryById.set(t.id, copy);
667
+ foldedTelemetry.push(copy);
668
+ continue;
669
+ }
670
+ if (t.ok === true) {
671
+ prev.ok = true;
672
+ prev.count = Math.max(prev.count ?? 0, t.count ?? 0);
673
+ prev.error = undefined;
674
+ } else if (prev.ok !== true) {
675
+ prev.error = t.error;
676
+ }
677
+ prev.ms = Math.max(prev.ms ?? 0, t.ms ?? 0);
678
+ }
679
+ const okCount = foldedTelemetry.filter((t) => t.ok).length;
631
680
  const historyOk = new Set(allTelemetry.filter((t) => t.ok).map((t) => t.id)).size;
632
681
  const historyTotal = new Set(allTelemetry.map((t) => t.id)).size;
633
682
 
@@ -662,7 +711,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
662
711
  if (cacheKey && cache) {
663
712
  cache.set(cacheKey, {
664
713
  sources, content: outContent,
665
- truncated: ordered.length > seamBound,
714
+ truncated: maxResults === seamBound && ordered.length > maxResults,
666
715
  backendsOk: historyOk, backendsTotal: historyTotal,
667
716
  });
668
717
  }
@@ -689,7 +738,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
689
738
  // labels (route6 P2); the raw text remains the fallback, and a
690
739
  // backend that just crossed the breaker threshold is annotated as
691
740
  // cooled on this same line.
692
- const parts = allTelemetry
741
+ const parts = foldedTelemetry
693
742
  .slice(0, 12)
694
743
  .map((t) => {
695
744
  if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
@@ -698,14 +747,14 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
698
747
  return t.id + " ✗" + t.ms + "ms" + (label ? " (" + label + ")" : "") + (cooledNow ? " " + cooledNow : "");
699
748
  })
700
749
  .concat(cooledParts);
701
- if (allTelemetry.length > 12) parts.push(`… +${allTelemetry.length - 12}`);
750
+ if (foldedTelemetry.length > 12) parts.push(`… +${foldedTelemetry.length - 12}`);
702
751
  const line = "[websearch backends]" + TELEMETRY_TAG + " " + parts.join(" · ");
703
752
  outContent = outContent === undefined ? line : outContent + "\n\n" + line;
704
753
  }
705
754
  return {
706
755
  sources,
707
756
  ...(outContent !== undefined ? { content: outContent } : {}),
708
- truncated: ordered.length > seamBound,
757
+ truncated: maxResults === seamBound && ordered.length > maxResults,
709
758
  };
710
759
  }
711
760
 
@@ -725,12 +774,12 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
725
774
  emptyContent = header + "\n\n" + emptyContent;
726
775
  }
727
776
  if (opts.resultTelemetry !== false && allFailures.length > 0) {
728
- const parts = allTelemetry.slice(0, 12).map((t) => {
777
+ const parts = foldedTelemetry.slice(0, 12).map((t) => {
729
778
  if (t.ok) return t.id + " ✓" + t.ms + "ms/" + t.count;
730
779
  const label = failureLabel(t.id, t.error) ?? (t.error ? String(t.error).slice(0, 40) : "");
731
780
  return t.id + " ✗" + t.ms + "ms" + (label ? " (" + label + ")" : "");
732
781
  });
733
- if (allTelemetry.length > 12) parts.push(`… +${allTelemetry.length - 12}`);
782
+ if (foldedTelemetry.length > 12) parts.push(`… +${foldedTelemetry.length - 12}`);
734
783
  const line = "[websearch backends]" + TELEMETRY_TAG + " " + parts.join(" · ");
735
784
  emptyContent = emptyContent === undefined ? line : emptyContent + "\n\n" + line;
736
785
  }
@@ -220,6 +220,10 @@ function inNoProxy(target, raw) {
220
220
  }
221
221
 
222
222
  function splitHostPort(item) {
223
+ // A bare IPv6 literal ("::1") has many colons and no port; only the
224
+ // bracket form can carry one. Splitting on the last colon made "::1" a
225
+ // host of ":" with port "1", so NO_PROXY never matched.
226
+ if (!item.startsWith("[") && (item.match(/:/g)?.length ?? 0) > 1) return [item, ""];
223
227
  if (item.startsWith("[")) {
224
228
  const close = item.indexOf("]");
225
229
  if (close === -1) return [item.replace(/^\[/, ""), ""];
package/lib/util/rank.js CHANGED
@@ -58,13 +58,16 @@ function canonicalUrlKey(raw) {
58
58
  try {
59
59
  const u = new URL(raw);
60
60
  u.hash = "";
61
+ // Hosts are case-insensitive; paths are not (`/A` and `/a` can differ).
61
62
  u.hostname = u.hostname.toLowerCase();
62
63
  for (const name of [...u.searchParams.keys()]) {
63
64
  if (/^utm_/i.test(name) || /^(fbclid|gclid|mc_cid|mc_eid)$/i.test(name)) u.searchParams.delete(name);
64
65
  }
65
- return u.toString().replace(/\/$/, "").toLowerCase();
66
+ if (u.pathname === "/") u.pathname = "";
67
+ return u.toString();
66
68
  } catch {
67
- return raw.toLowerCase();
69
+ // A malformed URL still needs a stable key; only the origin is case-insensitive.
70
+ return raw.replace(/#.*$/, "").toLowerCase();
68
71
  }
69
72
  }
70
73
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-websearch",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "Unified web search provider for DeepSeek Harness (ctx.web): 13 backends — Exa + Parallel + DDG + SearXNG (keyless), DeepSeek + Anthropic + OpenAI + Brave + Tavily + Serper + Mojeek (key-gated via Settings credentials), Firecrawl + TinyFish (metered keyless, opt-in). Registers provider id \"unified\" for zero-config web_search. 统一网页搜索聚合:13 后端并发扇出、去重合并。See CHANGELOG.md for version history.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",