@240xu/dsh-websearch 2.9.0 → 2.9.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/README.md +6 -6
- package/lib/cache.js +40 -14
- package/lib/client.js +73 -37
- package/lib/history.js +2 -2
- package/lib/index.js +5 -5
- package/lib/provider.js +45 -18
- package/lib/util/egress-fetch.js +4 -0
- package/lib/util/rank.js +5 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -92,7 +92,7 @@ pnpm install
|
|
|
92
92
|
> 每个 API Key 字段旁有 **「获取 Key ↗」** 直达对应平台控制台;保存即写入凭证库并立即生效。
|
|
93
93
|
|
|
94
94
|
|
|
95
|
-
插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑
|
|
95
|
+
插件向 DSH 设置面板注册 `unified-search` namespace(Settings → Unified Search),面板可编辑 24 个开关/参数;缓存、熔断、历史、多查询、BaseURL、Model 与 `*ApiKeyEnv` 等其余字段通过 profile patch 配置:
|
|
96
96
|
|
|
97
97
|
**全局**
|
|
98
98
|
|
|
@@ -101,7 +101,7 @@ pnpm install
|
|
|
101
101
|
| `intervention` | balanced | 搜索介入程度:`official` / `balanced` / `thorough`(见下表) |
|
|
102
102
|
| `numResults` | 10 | 每次搜索返回结果数(1-50;official 档沿用宿主工具的条数上限) |
|
|
103
103
|
| `concurrency` | 6 | 并发后端数(1-10) |
|
|
104
|
-
| `backendTimeoutMs` |
|
|
104
|
+
| `backendTimeoutMs` | 24000 | 单后端超时毫秒(为宿主 30s 工具超时预留余量) |
|
|
105
105
|
| `recency` | any | 时间范围过滤:day / week / month / year(映射到各后端原生参数) |
|
|
106
106
|
| `language` | 空 | 搜索语言,如 en、zh-CN(SearXNG/Brave/Serper 支持) |
|
|
107
107
|
| `safeSearch` | true | 安全搜索开关(SearXNG/Brave 支持) |
|
|
@@ -170,7 +170,7 @@ pnpm install
|
|
|
170
170
|
|
|
171
171
|
### 4. per-backend 超时上限(P2)
|
|
172
172
|
|
|
173
|
-
- `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)
|
|
173
|
+
- `ddg` / `searxng` 专属超时上限 8s(`min(8s, backendTimeoutMs)`,全局默认 24s、配置更短则以配置为准)——不可达后端不再拖住整个扇出尾。实测见 docs/real-call-2.8.0.md。
|
|
174
174
|
|
|
175
175
|
## v2.7.3 兼容修复 | What's new in v2.7.3
|
|
176
176
|
|
|
@@ -227,7 +227,7 @@ pnpm install
|
|
|
227
227
|
- **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
228
|
- **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
229
|
- **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
|
|
230
|
+
- **Concurrency & Timeout Control**: `concurrency` (default 6) limits simultaneous calls; `backendTimeoutMs` (default 24s) caps each backend.
|
|
231
231
|
- **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
232
|
- **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
233
|
|
|
@@ -264,7 +264,7 @@ tests/
|
|
|
264
264
|
node --test tests/
|
|
265
265
|
```
|
|
266
266
|
|
|
267
|
-
当前
|
|
267
|
+
当前 218/218 pass(`node --test tests/*.test.js`;`tests/up-health.test.mjs` 单独跑)。
|
|
268
268
|
|
|
269
269
|
### Test-only dependencies
|
|
270
270
|
|
|
@@ -277,7 +277,7 @@ live service before running the suite:
|
|
|
277
277
|
```bash
|
|
278
278
|
bash tests/relink-test-deps.sh # derives the scope from dsh-web.service MainPID
|
|
279
279
|
find node_modules/@deepseek-ai -xtype l # expect no output
|
|
280
|
-
node --test tests/*.test.js #
|
|
280
|
+
node --test tests/*.test.js # 218/218
|
|
281
281
|
```
|
|
282
282
|
|
|
283
283
|
v2.7.0 起共 76+ tests pass(`node --test "tests/*.test.js" "test/*.test.mjs"`)〔历史快照;当前口径见上〕。
|
package/lib/cache.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
159
|
-
|
|
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 —
|
|
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:
|
|
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) {
|
|
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
|
-
|
|
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,18 +666,14 @@ 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 === "") {
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
|
@@ -664,14 +685,23 @@ window.__ModuleLoader__.load({
|
|
|
664
685
|
backendTimeoutMs: [1000, 120000],
|
|
665
686
|
};
|
|
666
687
|
const [lo, hi] = BOUNDS[field] ?? [-Infinity, Infinity];
|
|
667
|
-
if (!Number.
|
|
668
|
-
|
|
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
|
-
|
|
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:
|
|
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]?.
|
|
791
|
-
readOnly && react_jsx_runtime.jsx("span", { className: "wsc-badge",
|
|
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
|
|
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:
|
|
802
|
-
placeholder:
|
|
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]?.
|
|
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",
|
|
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
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
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
|
@@ -165,7 +165,7 @@ export const Config = z.object({
|
|
|
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(
|
|
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
|
|
@@ -190,7 +190,7 @@ export const Config = z.object({
|
|
|
190
190
|
// spelled out (秒 / 毫秒) and grouping follows the field order below.
|
|
191
191
|
cacheEnabled: z.boolean().default(true)
|
|
192
192
|
.description("启用搜索结果缓存【缓存】:相同查询+过滤+条数在有效期内直接命中,不再请求后端"),
|
|
193
|
-
cacheTtl: z.number().step(30).min(
|
|
193
|
+
cacheTtl: z.number().step(30).min(0).max(86400).default(900)
|
|
194
194
|
.description("缓存有效期【缓存】(单位:秒):默认 900 秒;不想用缓存请直接关闭上一项"),
|
|
195
195
|
breakerEnabled: z.boolean().default(true)
|
|
196
196
|
.description("后端熔断器【熔断】:连续失败达阈值后暂停该后端一段时间;全部暂停时自动放行,不会让搜索更差"),
|
|
@@ -308,7 +308,7 @@ Config.meta = { ...Config.meta, volatile: true };
|
|
|
308
308
|
const FIELD_LABELS = {
|
|
309
309
|
intervention: "搜索介入程度",
|
|
310
310
|
cacheEnabled: "启用搜索结果缓存",
|
|
311
|
-
cacheTtl: "
|
|
311
|
+
cacheTtl: "缓存有效期(秒);0 = 不缓存(no-store)",
|
|
312
312
|
breakerEnabled: "后端熔断器",
|
|
313
313
|
breakerThreshold: "熔断阈值(连续失败次数)",
|
|
314
314
|
breakerCooldownMs: "熔断冷却时长(毫秒)",
|
|
@@ -410,7 +410,7 @@ export function resolveOptions(ctx, config) {
|
|
|
410
410
|
// the user's explicit count (and still never exceed the host cap).
|
|
411
411
|
numResults: official ? undefined : (config?.numResults ?? 10),
|
|
412
412
|
concurrency: config?.concurrency ?? 6,
|
|
413
|
-
backendTimeoutMs: config?.backendTimeoutMs ??
|
|
413
|
+
backendTimeoutMs: config?.backendTimeoutMs ?? 24000,
|
|
414
414
|
// v2.1 shaping options consumed by the provider merge pipeline.
|
|
415
415
|
dedupStrategy: config?.dedupStrategy === "url+title" ? "url+title" : "url",
|
|
416
416
|
rerank: thorough || (!official && config?.rerank === true),
|
|
@@ -418,7 +418,7 @@ export function resolveOptions(ctx, config) {
|
|
|
418
418
|
resultTelemetry: official ? false : config?.resultTelemetry !== false,
|
|
419
419
|
// v2.7.0 cache / breaker / history
|
|
420
420
|
cacheEnabled: config?.cacheEnabled !== false,
|
|
421
|
-
cacheTtlS: Math.max(
|
|
421
|
+
cacheTtlS: config?.cacheTtl == null ? CACHE_DEFAULTS.ttlMs / 1000 : Math.max(0, Math.floor(Number(config.cacheTtl))),
|
|
422
422
|
breakerEnabled: config?.breakerEnabled !== false,
|
|
423
423
|
breakerThreshold: Math.max(1, Math.floor(Number(config?.breakerThreshold) || BREAKER_DEFAULTS.threshold)),
|
|
424
424
|
breakerCooldownMs: config?.breakerCooldownMs != null
|
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 ??
|
|
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.
|
|
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:
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
535
|
-
|
|
536
|
-
|
|
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) ||
|
|
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 (
|
|
592
|
+
for (let variantIndex = 0; variantIndex < variants.length; variantIndex += 1) {
|
|
593
|
+
const variantQuery = variants[variantIndex];
|
|
575
594
|
const remaining = searchDeadline - Date.now();
|
|
576
|
-
|
|
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,
|
|
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) {
|
|
@@ -662,7 +689,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
662
689
|
if (cacheKey && cache) {
|
|
663
690
|
cache.set(cacheKey, {
|
|
664
691
|
sources, content: outContent,
|
|
665
|
-
truncated: ordered.length >
|
|
692
|
+
truncated: maxResults === seamBound && ordered.length > maxResults,
|
|
666
693
|
backendsOk: historyOk, backendsTotal: historyTotal,
|
|
667
694
|
});
|
|
668
695
|
}
|
|
@@ -705,7 +732,7 @@ export function createUnifiedSearchProvider({ ctx, resolveOptions, backends, cac
|
|
|
705
732
|
return {
|
|
706
733
|
sources,
|
|
707
734
|
...(outContent !== undefined ? { content: outContent } : {}),
|
|
708
|
-
truncated: ordered.length >
|
|
735
|
+
truncated: maxResults === seamBound && ordered.length > maxResults,
|
|
709
736
|
};
|
|
710
737
|
}
|
|
711
738
|
|
package/lib/util/egress-fetch.js
CHANGED
|
@@ -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
|
-
|
|
66
|
+
if (u.pathname === "/") u.pathname = "";
|
|
67
|
+
return u.toString();
|
|
66
68
|
} catch {
|
|
67
|
-
|
|
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.
|
|
3
|
+
"version": "2.9.1",
|
|
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",
|