@maricgeer/dsh-websearch 0.1.2

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/lib/index.js ADDED
@@ -0,0 +1,2470 @@
1
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { lookup } from "node:dns/promises";
6
+ import { isIP } from "node:net";
7
+ import { WebError } from "@deepseek-ai/dsh-web";
8
+ import z from "@deepseek-ai/schemastery";
9
+ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
10
+ //#region src/errors.ts
11
+ /**
12
+ * Error vocabulary for dsh-websearch. Every error carries a stable string
13
+ * code prefixed `DSHWS_` so tool output and host logs stay machine-routable
14
+ * (AGENTS.md 插件开发规范). Chain-level codes are final here; member-level
15
+ * namespaces are claimed now and each provider adds its concrete codes when
16
+ * it lands (S04/S05a).
17
+ *
18
+ * @module dsh-websearch/errors
19
+ */
20
+ /** Chain-level codes owned by the chain meta providers (`src/chain/`). */
21
+ const CHAIN_ERROR_CODES = {
22
+ /** Every member on the chain was tried and failed. Terminal, fail-loud. */
23
+ exhausted: "DSHWS_CHAIN_EXHAUSTED",
24
+ /** No member on the chain passed the selection-level gates (unregistered, disabled, missing credentials, `available() === false`). */
25
+ noMemberConfigured: "DSHWS_NO_MEMBER_CONFIGURED",
26
+ /** Log code recorded when a member exceeds its `perMemberTimeoutMs` budget and the chain degrades to the next member. */
27
+ memberTimeout: "DSHWS_MEMBER_TIMEOUT"
28
+ };
29
+ /**
30
+ * Member-level code families. Every landed provider family carries its five
31
+ * concrete codes (S05a: five families landed as objects; the S14e fetch-search
32
+ * family was removed with its member in ADR-0014).
33
+ */
34
+ const MEMBER_ERROR_CODES = {
35
+ deepseek: {
36
+ credentialMissing: "DSHWS_DEEPSEEK_CREDENTIAL_MISSING",
37
+ requestFailed: "DSHWS_DEEPSEEK_REQUEST_FAILED",
38
+ httpError: "DSHWS_DEEPSEEK_HTTP_ERROR",
39
+ badResponse: "DSHWS_DEEPSEEK_BAD_RESPONSE",
40
+ aborted: "DSHWS_DEEPSEEK_ABORTED"
41
+ },
42
+ tavily: {
43
+ credentialMissing: "DSHWS_TAVILY_CREDENTIAL_MISSING",
44
+ requestFailed: "DSHWS_TAVILY_REQUEST_FAILED",
45
+ httpError: "DSHWS_TAVILY_HTTP_ERROR",
46
+ badResponse: "DSHWS_TAVILY_BAD_RESPONSE",
47
+ aborted: "DSHWS_TAVILY_ABORTED"
48
+ },
49
+ firecrawl: {
50
+ credentialMissing: "DSHWS_FIRECRAWL_CREDENTIAL_MISSING",
51
+ requestFailed: "DSHWS_FIRECRAWL_REQUEST_FAILED",
52
+ httpError: "DSHWS_FIRECRAWL_HTTP_ERROR",
53
+ badResponse: "DSHWS_FIRECRAWL_BAD_RESPONSE",
54
+ aborted: "DSHWS_FIRECRAWL_ABORTED"
55
+ },
56
+ exa: {
57
+ credentialMissing: "DSHWS_EXA_CREDENTIAL_MISSING",
58
+ requestFailed: "DSHWS_EXA_REQUEST_FAILED",
59
+ httpError: "DSHWS_EXA_HTTP_ERROR",
60
+ badResponse: "DSHWS_EXA_BAD_RESPONSE",
61
+ aborted: "DSHWS_EXA_ABORTED"
62
+ },
63
+ anysearch: {
64
+ credentialMissing: "DSHWS_ANYSEARCH_CREDENTIAL_MISSING",
65
+ requestFailed: "DSHWS_ANYSEARCH_REQUEST_FAILED",
66
+ httpError: "DSHWS_ANYSEARCH_HTTP_ERROR",
67
+ badResponse: "DSHWS_ANYSEARCH_BAD_RESPONSE",
68
+ aborted: "DSHWS_ANYSEARCH_ABORTED"
69
+ }
70
+ };
71
+ /** Domain error with a machine-routable string code and the standard `cause` slot. */
72
+ var DshwsError = class extends Error {
73
+ /** Stable `DSHWS_*` code; consumers must tolerate member-specific codes. */
74
+ code;
75
+ /** HTTP status of the failing response, when the failure came from one; drives the request-level vs credential-level redraw split (S14y). */
76
+ httpStatus;
77
+ constructor(code, message, options) {
78
+ super(message, options);
79
+ this.name = "DshwsError";
80
+ this.code = code;
81
+ this.httpStatus = options?.httpStatus;
82
+ }
83
+ };
84
+ /**
85
+ * HTTP statuses that hold for the REQUEST regardless of which pool key sent
86
+ * it — malformed body, missing route, unprocessable payload (S14y split of
87
+ * the former S14u set). The chain degrades at once: no key can change the
88
+ * verdict.
89
+ */
90
+ const REQUEST_LEVEL_HTTP_STATUSES = /* @__PURE__ */ new Set([
91
+ 400,
92
+ 404,
93
+ 422
94
+ ]);
95
+ /**
96
+ * HTTP statuses that fail THIS credential but not necessarily the others in
97
+ * the pool — 401/403 mean the drawn key is invalid or barred, and pool keys
98
+ * are independent credentials (live finding 2026-09-09: one expired key
99
+ * poisoned every second search once 401 skipped redraws). The chain redraws
100
+ * another key first and degrades only when the draw budget is spent.
101
+ */
102
+ const CREDENTIAL_LEVEL_HTTP_STATUSES = /* @__PURE__ */ new Set([401, 403]);
103
+ /**
104
+ * Build the terminal `DSHWS_CHAIN_EXHAUSTED` error. The message embeds ONE
105
+ * line per failed member — a multi-draw member lists its draws inline, so
106
+ * the member count stays truthful; the last member's last-draw error (when
107
+ * any) is chained as `cause` so the terminal diagnostics keep the deepest
108
+ * failure (ADR-0002 Decision 3).
109
+ */
110
+ function createChainExhaustedError(failures) {
111
+ const lines = failures.map((failure) => {
112
+ const detail = failure.drawReasons.length > 1 ? `failed (${failure.drawReasons.length} draws: ${failure.drawReasons.join("; ")})` : failure.drawReasons[0] ?? "failed";
113
+ return `- ${failure.memberId}: ${detail}`;
114
+ });
115
+ const last = failures.at(-1);
116
+ return new DshwsError(CHAIN_ERROR_CODES.exhausted, `${CHAIN_ERROR_CODES.exhausted}: all ${failures.length} configured chain members failed\n${lines.join("\n")}`, last?.error !== void 0 ? { cause: last.error } : void 0);
117
+ }
118
+ //#endregion
119
+ //#region src/chain/core.ts
120
+ /**
121
+ * Plugin-owned registry of bundled members. The host's provider registry is
122
+ * private and not enumerable (ADR-0003), so the plugin keeps its own: every
123
+ * bundled member registers here AND with `ctx.web` under the same `dshws-`
124
+ * id, which is what lets users pin one member directly via the selection
125
+ * scalar — direct connections bypass the chain entirely (ADR-0002 Decision 5).
126
+ *
127
+ * Bundled members register with real gates (config-enabled + credential
128
+ * state), which is what replaced the S03 constant-true facade: a member
129
+ * without its credentials configured now resolves as not ready and the chain
130
+ * skips it. Gate-less registration stays enabled/ready by design for members
131
+ * with no credential concept (loopback stubs, test fakes) — bundled members
132
+ * must always pass gates, or the skipped-when-unconfigured semantics die.
133
+ */
134
+ var MemberRegistry = class {
135
+ #providers = /* @__PURE__ */ new Map();
136
+ #gates = /* @__PURE__ */ new Map();
137
+ /** Register one member with its state gates; returns the disposer. */
138
+ register(provider, gates) {
139
+ this.#providers.set(provider.id, provider);
140
+ this.#gates.set(provider.id, gates);
141
+ return () => {
142
+ this.#providers.delete(provider.id);
143
+ this.#gates.delete(provider.id);
144
+ };
145
+ }
146
+ /** Chain-facing view; gates are read at each resolve, so flips apply to the next call. */
147
+ toResolver() {
148
+ return { resolve: (id) => {
149
+ const provider = this.#providers.get(id);
150
+ if (provider === void 0) return void 0;
151
+ const gates = this.#gates.get(id);
152
+ return {
153
+ id,
154
+ provider,
155
+ enabled: gates?.enabled?.() ?? true,
156
+ credentialsReady: gates?.credentialsReady?.() ?? true,
157
+ multiKeyPool: gates?.multiKeyPool?.() ?? false
158
+ };
159
+ } };
160
+ }
161
+ };
162
+ /**
163
+ * Capability-neutral orchestrator (architecture §4): selection-level skips,
164
+ * runtime degradation, per-member timeout budgets, terminal exhaustion, and
165
+ * the served-by log line. The result transform is the capability's
166
+ * attribution policy (search: content prefix, D2; fetch: log only, D3).
167
+ */
168
+ var ChainCore = class ChainCore {
169
+ #options;
170
+ #transform;
171
+ constructor(options, transform) {
172
+ this.#options = options;
173
+ this.#transform = transform;
174
+ }
175
+ /** Cheap local check (§4): true when at least one enabled member has credentials ready. */
176
+ available() {
177
+ return this.#options.order.some((id) => {
178
+ const member = this.#options.members.resolve(id);
179
+ return member !== void 0 && member.enabled && member.credentialsReady;
180
+ });
181
+ }
182
+ /** Selection-level gates: an unusable member is skipped without being called. */
183
+ #isUsable(member) {
184
+ if (member === void 0) return false;
185
+ if (!member.enabled) return false;
186
+ if (!member.credentialsReady) return false;
187
+ return member.provider.available();
188
+ }
189
+ /**
190
+ * Per-member key-redraw budget (S14r, user ruling): a failing key may be
191
+ * network/quota noise specific to THAT key, so the chain redraws another
192
+ * key from the member's pool (a fresh `invoke` re-reads the pool policy)
193
+ * before degrading to the next member. Three draws per member cap the
194
+ * added latency; the per-member timeout budget is ONE shared deadline
195
+ * across those draws (S14u), so redrawing never multiplies the budget.
196
+ */
197
+ static MEMBER_DRAWS = 3;
198
+ /** Draws for members with a multi-key pool; single-key members get 1. */
199
+ #drawsFor(member) {
200
+ return member.multiKeyPool === true ? ChainCore.MEMBER_DRAWS : 1;
201
+ }
202
+ /** Try members in configured order; per member one shared timeout budget across up to MEMBER_DRAWS key redraws, then degrade. */
203
+ async run(request, signal, invoke) {
204
+ const failures = [];
205
+ for (const id of this.#options.order) {
206
+ const member = this.#options.members.resolve(id);
207
+ if (!this.#isUsable(member)) continue;
208
+ const draws = this.#drawsFor(member);
209
+ const deadline = Date.now() + this.#options.perMemberTimeoutMs;
210
+ const drawReasons = [];
211
+ let lastError;
212
+ for (let draw = 1; draw <= ChainCore.MEMBER_DRAWS; draw += 1) {
213
+ const remaining = deadline - Date.now();
214
+ if (remaining <= 0) {
215
+ const reason = `${CHAIN_ERROR_CODES.memberTimeout}: member budget of ${this.#options.perMemberTimeoutMs}ms spent after ${drawReasons.length} draw(s)`;
216
+ drawReasons.push(reason);
217
+ this.#options.log?.(`[dshws-chain] member ${id} failed (${reason}); degrading to next member`);
218
+ break;
219
+ }
220
+ try {
221
+ const controller = new AbortController();
222
+ const abortFromOuter = () => controller.abort(signal?.reason);
223
+ signal?.addEventListener("abort", abortFromOuter, { once: true });
224
+ if (signal?.aborted) abortFromOuter();
225
+ let fireTimeout = () => {};
226
+ const timedOut = new Promise((_, reject) => {
227
+ fireTimeout = () => reject(MEMBER_TIMED_OUT);
228
+ });
229
+ const timer = setTimeout(() => {
230
+ controller.abort();
231
+ fireTimeout();
232
+ }, remaining);
233
+ try {
234
+ const memberPromise = invoke(member.provider, request, controller.signal);
235
+ memberPromise.catch(() => {});
236
+ const result = await Promise.race([memberPromise, timedOut]);
237
+ this.#options.log?.(`[dshws-chain] served-by: ${id}`);
238
+ return this.#transform(id, result);
239
+ } finally {
240
+ clearTimeout(timer);
241
+ signal?.removeEventListener("abort", abortFromOuter);
242
+ }
243
+ } catch (error) {
244
+ if (signal?.aborted && error !== MEMBER_TIMED_OUT) throw error;
245
+ const isTimeout = error === MEMBER_TIMED_OUT;
246
+ const status = !isTimeout && error instanceof DshwsError ? error.httpStatus : void 0;
247
+ const requestLevelStatus = status !== void 0 && REQUEST_LEVEL_HTTP_STATUSES.has(status) ? status : void 0;
248
+ const credentialLevelStatus = status !== void 0 && CREDENTIAL_LEVEL_HTTP_STATUSES.has(status) ? status : void 0;
249
+ const reason = isTimeout ? `${CHAIN_ERROR_CODES.memberTimeout}: no result within the member budget of ${this.#options.perMemberTimeoutMs}ms` : error instanceof Error ? error.message : String(error);
250
+ drawReasons.push(reason);
251
+ if (!isTimeout) lastError = error;
252
+ const redrawCap = credentialLevelStatus !== void 0 ? ChainCore.MEMBER_DRAWS : draws;
253
+ const drawNote = isTimeout || requestLevelStatus !== void 0 || draw >= redrawCap ? `; degrading to next member${requestLevelStatus !== void 0 ? ` (request-level HTTP ${requestLevelStatus})` : ""}` : `; redrawing key (${draw + 1}/${redrawCap})${credentialLevelStatus !== void 0 ? ` (credential-level HTTP ${credentialLevelStatus}: another key may be valid)` : ""}`;
254
+ this.#options.log?.(`[dshws-chain] member ${id} failed (${reason})${drawNote}`);
255
+ if (isTimeout) break;
256
+ if (requestLevelStatus !== void 0) break;
257
+ if (draw >= redrawCap) break;
258
+ continue;
259
+ }
260
+ }
261
+ if (drawReasons.length > 0) failures.push(lastError !== void 0 ? {
262
+ memberId: id,
263
+ drawReasons,
264
+ error: lastError
265
+ } : {
266
+ memberId: id,
267
+ drawReasons
268
+ });
269
+ }
270
+ if (failures.length === 0) throw noMemberConfigured(this.#options.order);
271
+ throw createChainExhaustedError(failures);
272
+ }
273
+ };
274
+ /** Internal sentinel: the member's `perMemberTimeoutMs` budget expired before a result. */
275
+ const MEMBER_TIMED_OUT = Symbol("dshws.member-timed-out");
276
+ /**
277
+ * Build the fail-loud error for a chain whose members were all selection-skipped.
278
+ * The list is the chain ORDER — skipped members are typically unconfigured, so
279
+ * labeling them "configured" read as a lie; the message names the order and
280
+ * points at the remediation (settings page, or the shared-key DeepSeek floor).
281
+ */
282
+ function noMemberConfigured(order) {
283
+ return new DshwsError(CHAIN_ERROR_CODES.noMemberConfigured, `${CHAIN_ERROR_CODES.noMemberConfigured}: no usable member on the chain (chain order: ${order.join(", ")}); enable or configure a member on the dsh-websearch settings page, or select the DeepSeek paid fallback there when fewer than two tools are ready (Models-page key required)`);
284
+ }
285
+ /**
286
+ * Attribution carrier (ADR-0002 Decision 4): the seam's `WebSearchResult` is
287
+ * closed, so the serving member is named in a `[served-by: <id>]` first line
288
+ * of `content` — the slot provider-generated text already lives in. Members
289
+ * without content get the line alone, so attribution never disappears.
290
+ */
291
+ function withServedBy(memberId, result) {
292
+ const line = `[served-by: ${memberId}]`;
293
+ return {
294
+ ...result,
295
+ content: result.content === void 0 ? line : `${line}\n${result.content}`
296
+ };
297
+ }
298
+ /** Search chain meta provider, registered as `dshws-chain` (ADR-0002). */
299
+ var ChainSearchProvider = class {
300
+ id = "dshws-chain";
301
+ #core;
302
+ /**
303
+ * The caller's options object is kept by reference (never spread): getters
304
+ * on it — the settings hot path — must be re-read on every run.
305
+ */
306
+ constructor(options) {
307
+ this.#core = new ChainCore(options, withServedBy);
308
+ }
309
+ available() {
310
+ return this.#core.available();
311
+ }
312
+ search(request, signal) {
313
+ return this.#core.run(request, signal, (provider, req, sig) => provider.search(req, sig));
314
+ }
315
+ };
316
+ /**
317
+ * Fetch attribution carrier (S28, superseding the D3 log-only decision): the
318
+ * seam's `WebFetchResult` is closed like `WebSearchResult`, so the serving
319
+ * member is named in a `[served-by: <id>]` line prepended to `body.content`.
320
+ * Head placement survives the host's head-preserving truncation layers; the
321
+ * html kind's turndown escaping (`\[served-by: …\]`) shapes what the client
322
+ * regex tolerates.
323
+ */
324
+ function withFetchServedBy(memberId, result) {
325
+ const line = `[served-by: ${memberId}]`;
326
+ return {
327
+ ...result,
328
+ body: {
329
+ ...result.body,
330
+ content: `${line}\n${result.body.content}`
331
+ }
332
+ };
333
+ }
334
+ /** Fetch chain meta provider, registered as `dshws-chain-fetch`. */
335
+ var ChainFetchProvider = class {
336
+ id = "dshws-chain-fetch";
337
+ #core;
338
+ /** Kept by reference for the same hot-read reason as the search shell. */
339
+ constructor(options) {
340
+ this.#core = new ChainCore(options, withFetchServedBy);
341
+ }
342
+ available() {
343
+ return this.#core.available();
344
+ }
345
+ fetch(request, signal) {
346
+ return this.#core.run(request, signal, (provider, req, sig) => provider.fetch(req, sig));
347
+ }
348
+ };
349
+ //#endregion
350
+ //#region src/chain-log.ts
351
+ /**
352
+ * Plugin-owned chain log file (S14z): the chain's observability lines
353
+ * (draws, key rotation, degradation, served-by) already exist, but the host
354
+ * CLI service attaches no info-level console exporter — they were emitted
355
+ * into the void. This sink appends every line to
356
+ * `<dshHome>/logs/dsh-websearch.log` so troubleshooting is a `tail` away,
357
+ * independent of host logging configuration.
358
+ *
359
+ * @module dsh-websearch/chain-log
360
+ */
361
+ /** Rotate the log once it passes this size at sink construction (one `.old` generation kept). */
362
+ const ROTATE_ABOVE_BYTES = 1e6;
363
+ /** Resolve the harness home the same way shipped plugins do: `$DSH_HOME` or `~/.dsh`. */
364
+ function dshHome$1() {
365
+ return process.env.DSH_HOME ?? join(homedir(), ".dsh");
366
+ }
367
+ /**
368
+ * Create the chain file sink. Best-effort by design: a read-only home or a
369
+ * full disk must never take the search chain down — a failing append is
370
+ * swallowed after the first attempt and the sink turns into a no-op.
371
+ *
372
+ * @param enabled - false disables the sink entirely (the Config knob).
373
+ * @param home - overrides the home resolution (tests).
374
+ */
375
+ function createChainFileLog(enabled = true, home = dshHome$1()) {
376
+ const noop = Object.assign(() => {}, { path: "" });
377
+ if (!enabled) return noop;
378
+ const dir = join(home, "logs");
379
+ const path = join(dir, "dsh-websearch.log");
380
+ try {
381
+ mkdirSync(dir, { recursive: true });
382
+ if (existsSync(path) && statSync(path).size > ROTATE_ABOVE_BYTES) renameSync(path, `${path}.old`);
383
+ if (!existsSync(path)) writeFileSync(path, "", "utf8");
384
+ } catch {
385
+ return noop;
386
+ }
387
+ let broken = false;
388
+ return Object.assign((message) => {
389
+ if (broken) return;
390
+ try {
391
+ appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, "utf8");
392
+ } catch {
393
+ broken = true;
394
+ }
395
+ }, { path });
396
+ }
397
+ //#endregion
398
+ //#region src/preset-authoring.ts
399
+ /**
400
+ * Install-time web_fetch removal (S14z2 → S15a, user ruling "装即接管"):
401
+ * the web_fetch TOOL is registered by the agent preset, so the takeover
402
+ * authors search-only copies of every shipped preset that carries tool-web
403
+ * with fetch enabled (standard/ptc/cordis; minimal has none). Each copy is
404
+ * regenerated at load from the INSTALLED shipped preset (zero drift), written
405
+ * into the harness-home user root, and the roster default is switched THROUGH
406
+ * THE SETTINGS SERVICE only after the standard copy's write succeeded.
407
+ *
408
+ * S15a additions over S14z2: (a) multi-preset coverage — ptc and cordis also
409
+ * get copies, with cordis's skills/ directory carried along (the composition
410
+ * references it relatively); (b) explicit clear() for the settings toggle's
411
+ * OFF path; (c) standard's copy id stays `dshws-search-only` (zero migration
412
+ * from S14z2 installs — the review's M4 ruling).
413
+ *
414
+ * Residue (honest trade-off vs ADR-0013's auto-restore): uninstalling the
415
+ * plugin leaves the settings default and the authored preset directories in
416
+ * place — sessions keep composing fully working search-only presets. Recovery
417
+ * is one picker action or deleting `$DSH_HOME/.agent-presets/dshws-*-search-only`.
418
+ *
419
+ * @module dsh-websearch/preset-authoring
420
+ */
421
+ /** Resolve the harness home the same way shipped plugins do: `$DSH_HOME` or `~/.dsh`. */
422
+ function dshHome() {
423
+ return process.env.DSH_HOME ?? join(homedir(), ".dsh");
424
+ }
425
+ /**
426
+ * Remove ALL plugin-authored preset copies and any auxiliary files (S15a
427
+ * toggle OFF path). Only directories carrying our version marker are touched;
428
+ * user-authored content under the same ids is left alone. The caller MUST
429
+ * restore the roster default BEFORE calling this — a default pointing at a
430
+ * deleted preset makes session creation throw.
431
+ *
432
+ * @param home - overrides home resolution (tests).
433
+ * @returns the ids actually removed.
434
+ */
435
+ function clearAllSearchOnlyPresets(home = dshHome()) {
436
+ const removed = [];
437
+ const root = join(home, ".agent-presets");
438
+ if (!existsSync(root)) return removed;
439
+ try {
440
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
441
+ if (!entry.isDirectory()) continue;
442
+ const presetPath = join(root, entry.name, "preset.yml");
443
+ if (!existsSync(presetPath)) continue;
444
+ if (!readFileSync(presetPath, "utf8").includes(`authored (v`)) continue;
445
+ rmSync(join(root, entry.name), {
446
+ recursive: true,
447
+ force: true
448
+ });
449
+ removed.push(entry.name);
450
+ }
451
+ } catch {}
452
+ return removed;
453
+ }
454
+ //#endregion
455
+ //#region src/fetch-gate.ts
456
+ /**
457
+ * The web_fetch gateway provider (S15a Layer C, review M1+M2 ruling): a
458
+ * always-registered, always-available fetch provider pinned by the plugin
459
+ * patch (`fetchProvider: dshws-fetch-gate`). Its behavior follows the live
460
+ * takeover toggle —
461
+ *
462
+ * ON: `fetch()` rejects with a guidance error naming web_search as the
463
+ * replacement, so the model reads the instruction and reroutes. This is the
464
+ * only path where the tool's outcome is fully ours — the seam's
465
+ * registered-but-unavailable message has no room for custom copy (M2).
466
+ *
467
+ * OFF: `fetch()` delegates to a plain HTTP fetch — the plugin's own
468
+ * implementation of the official anonymous-fetch behavior, so the gateway is
469
+ * a transparent pass-through and web_fetch keeps working exactly as the
470
+ * host shipped it. Uninstalling the plugin removes the patch pin entirely
471
+ * (the seam falls back to auto-selecting the host's own `http` provider),
472
+ * so OFF state never outlives the plugin.
473
+ *
474
+ * @module dsh-websearch/fetch-gate
475
+ */
476
+ /** Stable id this provider registers under; the plugin patch pins `fetchProvider` here. */
477
+ const FETCH_GATE_PROVIDER_ID = "dshws-fetch-gate";
478
+ /** Cap the delegated body, matching the official provider's default budget. */
479
+ const MAX_DELEGATED_CHARS = 2e5;
480
+ /** Content types the official provider rejects as undecodable binary. */
481
+ const BINARY_CONTENT_TYPE = /^(application\/octet-stream|image\/|audio\/|video\/|application\/pdf|application\/zip)/i;
482
+ /**
483
+ * Plain HTTP fetch delegation (OFF state): an anonymous GET with the same
484
+ * public-network guard the official provider enforces — resolve once, reject
485
+ * non-public destinations, pin the connection to the validated address. The
486
+ * redirect policy stays 'error' so a cross-origin hop cannot silently bypass
487
+ * the check (the official provider limits same-origin hops; refusing all
488
+ * redirects is the conservative subset).
489
+ *
490
+ * @throws WebError with a stable code for each rejection class.
491
+ */
492
+ async function delegateFetch(request, signal) {
493
+ const url = new URL(request.url);
494
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
495
+ const literal = isIP(hostname);
496
+ let addresses;
497
+ if (literal) addresses = [hostname];
498
+ else addresses = (await lookup(hostname, { all: true })).map((entry) => entry.address);
499
+ for (const address of addresses) if (!isPublicAddress(address)) throw new WebError(`URL hostname resolves to a non-public address (${address})`, "WEB_FETCH_BLOCKED");
500
+ const response = await fetch(url, {
501
+ method: "GET",
502
+ redirect: "error",
503
+ ...signal !== void 0 ? { signal } : {}
504
+ });
505
+ const contentType = response.headers.get("content-type") ?? "";
506
+ if (BINARY_CONTENT_TYPE.test(contentType)) throw new WebError(`unsupported content type "${contentType}"`, "WEB_UNSUPPORTED_CONTENT_TYPE");
507
+ const full = await response.text();
508
+ const truncated = full.length > MAX_DELEGATED_CHARS;
509
+ const text = truncated ? full.slice(0, MAX_DELEGATED_CHARS) : full;
510
+ const isHtml = contentType.includes("text/html") || /^\s*<(!doctype|html)/i.test(text);
511
+ return {
512
+ url: response.url || url.href,
513
+ statusCode: response.status,
514
+ body: {
515
+ kind: isHtml ? "html" : "text",
516
+ content: text
517
+ },
518
+ truncated
519
+ };
520
+ }
521
+ /** Whether an address is globally reachable unicast (the official SSRF bar). */
522
+ function isPublicAddress(address) {
523
+ if (isIP(address) === 6) {
524
+ const lower = address.toLowerCase();
525
+ if (lower === "::1" || lower.startsWith("fe80:") || lower.startsWith("fc") || lower.startsWith("fd")) return false;
526
+ return true;
527
+ }
528
+ const [a, b] = address.split(".").map(Number);
529
+ if (a === 10 || a === 127 || a === 0) return false;
530
+ if (a === 172 && b !== void 0 && b >= 16 && b <= 31) return false;
531
+ if (a === 192 && b === 168) return false;
532
+ if (a === 169 && b === 254) return false;
533
+ if (a === 198 && (b === 18 || b === 19)) return false;
534
+ return true;
535
+ }
536
+ /**
537
+ * The gateway provider, S21 a runtime ROUTER: ON delegates to the plugin's
538
+ * internal fetch chain (Firecrawl → Tavily → AnySearch degradation); OFF
539
+ * falls through to the built-in http fetch below — an official-behavior
540
+ * equivalent stand-in (redirect:'error', 200k cap, binary refusal, the same
541
+ * SSRF checks), because the pinned patch means the official provider instance
542
+ * is never selected. `takeoverActive` is read per call so the settings toggle
543
+ * is hot on the next web_fetch invocation.
544
+ */
545
+ var FetchGateProvider = class {
546
+ isTakeoverActive;
547
+ chainFetch;
548
+ id = FETCH_GATE_PROVIDER_ID;
549
+ constructor(isTakeoverActive, chainFetch) {
550
+ this.isTakeoverActive = isTakeoverActive;
551
+ this.chainFetch = chainFetch;
552
+ }
553
+ /** Always true: the pin guarantees selection, so availability is ours to own (review M2). */
554
+ available() {
555
+ return true;
556
+ }
557
+ async fetch(request, signal) {
558
+ if (this.isTakeoverActive()) return await this.chainFetch(request, signal);
559
+ return await delegateFetch(request, signal);
560
+ }
561
+ };
562
+ //#endregion
563
+ //#region src/config.ts
564
+ /**
565
+ * Plugin configuration: the schemastery schema the loader validates against,
566
+ * plus `resolveConfig`, which turns the all-optional user config into a fully
567
+ * defaulted specification. Defaulting lives here explicitly — the schema never
568
+ * injects defaults (explicit > implicit at the owning boundary).
569
+ *
570
+ * @module dsh-websearch/config
571
+ */
572
+ /**
573
+ * Orderable search members (S14c, user ruling): the five tool members users may
574
+ * reorder; DeepSeek is NOT orderable — it is the paid fallback pinned to the
575
+ * chain tail (see {@link DEEPSEEK_FALLBACK_MEMBER_ID}).
576
+ */
577
+ const ORDERABLE_SEARCH_MEMBER_ORDER = [
578
+ "dshws-tavily",
579
+ "dshws-exa",
580
+ "dshws-firecrawl",
581
+ "dshws-anysearch"
582
+ ];
583
+ /**
584
+ * The DeepSeek member id — the paid fallback candidate (ADR-0014). It is not
585
+ * orderable and joins the chain only when designated AND eligible (see the
586
+ * participation guard in src/index.ts: at most one ready tool member).
587
+ */
588
+ const DEEPSEEK_FALLBACK_MEMBER_ID = "dshws-deepseek";
589
+ /**
590
+ * Effective built-in search order (ADR-0014): the orderable five only — the
591
+ * chain's last ready member is the fallback; no member is appended by default.
592
+ */
593
+ const BUILT_IN_MEMBER_ORDER = [...ORDERABLE_SEARCH_MEMBER_ORDER];
594
+ /**
595
+ * Effective built-in fetch order (S21, ADR-0019): the fetch-capable members
596
+ * only — Exa has no upstream URL-fetch capability and never joins this chain.
597
+ */
598
+ const FETCH_CHAIN_DEFAULT_ORDER = [
599
+ "dshws-firecrawl",
600
+ "dshws-tavily",
601
+ "dshws-anysearch"
602
+ ];
603
+ /**
604
+ * Compose the search chain for the designated fallback (ADR-0014): a
605
+ * designated TOOL member is stripped from the orderable span and pinned at
606
+ * the tail — its only role is fallback. `'auto'` keeps the span as ordered;
607
+ * designating DeepSeek does NOT statically append it — its participation is
608
+ * a runtime eligibility rule (order getter in src/index.ts), so the static
609
+ * layer yields the span and the guard appends when eligible.
610
+ */
611
+ function withDesignatedFallback(chain, fallbackMember) {
612
+ const span = chain.filter((id) => id !== "dshws-deepseek" && id !== "dshws-fetch-search");
613
+ if (fallbackMember === "auto" || fallbackMember === "dshws-deepseek") return span;
614
+ return [...span.filter((id) => id !== fallbackMember), fallbackMember];
615
+ }
616
+ /** Per-member timeout budget applied when the config omits one (ADR-0002). */
617
+ const DEFAULT_PER_MEMBER_TIMEOUT_MS = 3e4;
618
+ /**
619
+ * Unwrap a runtime config into the plain {@link Config} shape: handle fields
620
+ * read through `get()` (snapshot at call time), plain fields pass through.
621
+ * Shallow by construction — volatile marks sit exactly on the top-level
622
+ * fields and the five member objects, never deeper.
623
+ * @param runtime - the config object the host handed the plugin.
624
+ * @returns the plain snapshot for one resolve pass.
625
+ */
626
+ function materializeConfig(runtime) {
627
+ const out = {};
628
+ for (const key of Object.keys(runtime)) {
629
+ const value = runtime[key];
630
+ out[key] = value !== null && typeof value === "object" && typeof value.get === "function" ? value.get() : value;
631
+ }
632
+ return out;
633
+ }
634
+ /**
635
+ * Validation schema the cordis loader applies to the `dsh-websearch` config
636
+ * section. Every editable field is `.volatile()` (S32, ADR-0021): on 0.1.7+
637
+ * hosts that registers the namespace as a live settings form (the whole
638
+ * subtree under a volatile node is form-editable, upstream `volatileForm`);
639
+ * on 0.1.5/0.1.6 hosts the marker is inert metadata and values arrive plain
640
+ * (see {@link ConfigRuntime}).
641
+ */
642
+ function buildConfigSchema(markVolatile) {
643
+ const vol = (node) => markVolatile ? node.volatile() : node;
644
+ return z.object({
645
+ searchChain: vol(z.array(z.string())),
646
+ fallbackMember: vol(z.union([
647
+ "auto",
648
+ "dshws-tavily",
649
+ "dshws-exa",
650
+ "dshws-perplexity",
651
+ "dshws-firecrawl",
652
+ "dshws-anysearch",
653
+ "dshws-deepseek"
654
+ ])),
655
+ fallbackProvider: vol(z.union([
656
+ "deepseek",
657
+ "none",
658
+ "auto",
659
+ "fetch"
660
+ ])),
661
+ chainLogFile: vol(z.boolean()),
662
+ fetchTakeover: vol(z.boolean()),
663
+ searchCountry: vol(z.string()),
664
+ searchLanguage: vol(z.string()),
665
+ searchIncludeDomains: vol(z.string()),
666
+ searchExcludeDomains: vol(z.string()),
667
+ fetchChain: vol(z.array(z.string())),
668
+ perMemberTimeoutMs: vol(z.number().step(1).min(1)),
669
+ deepseek: vol(z.object({
670
+ enabled: z.boolean(),
671
+ apiKeyEnv: z.string(),
672
+ baseURL: z.string(),
673
+ model: z.string(),
674
+ maxTokens: z.number().step(1).min(1),
675
+ maxUses: z.number().step(1).min(1),
676
+ keySelection: z.union([
677
+ "order",
678
+ "round-robin",
679
+ "random"
680
+ ])
681
+ })),
682
+ tavily: vol(z.object({
683
+ enabled: z.boolean(),
684
+ apiKeyEnv: z.string(),
685
+ baseURL: z.string(),
686
+ maxResults: z.number().step(1).min(1),
687
+ topic: z.union([
688
+ "",
689
+ "general",
690
+ "news",
691
+ "finance"
692
+ ]),
693
+ timeRange: z.union([
694
+ "",
695
+ "day",
696
+ "week",
697
+ "month",
698
+ "year"
699
+ ]),
700
+ searchDepth: z.union([
701
+ "",
702
+ "basic",
703
+ "advanced",
704
+ "fast",
705
+ "ultra-fast"
706
+ ]),
707
+ includeAnswer: z.union(["basic", "advanced"]),
708
+ chunksPerSource: z.number().step(1).min(1).max(3),
709
+ filterByLanguage: z.boolean(),
710
+ includeDomainsMode: z.union(["filter", "boost"]),
711
+ startDate: z.string(),
712
+ endDate: z.string(),
713
+ exactMatch: z.boolean(),
714
+ keySelection: z.union([
715
+ "order",
716
+ "round-robin",
717
+ "random"
718
+ ])
719
+ })),
720
+ firecrawl: vol(z.object({
721
+ enabled: z.boolean(),
722
+ apiKeyEnv: z.string(),
723
+ baseURL: z.string(),
724
+ tbs: z.string(),
725
+ safe: z.boolean(),
726
+ location: z.string(),
727
+ sources: z.union([
728
+ "",
729
+ "news",
730
+ "web+news"
731
+ ]),
732
+ categories: z.union([
733
+ "",
734
+ "developer",
735
+ "research",
736
+ "pdf"
737
+ ]),
738
+ keySelection: z.union([
739
+ "order",
740
+ "round-robin",
741
+ "random"
742
+ ])
743
+ })),
744
+ exa: vol(z.object({
745
+ enabled: z.boolean(),
746
+ apiKeyEnv: z.string(),
747
+ baseURL: z.string(),
748
+ numResults: z.number().step(1).min(1),
749
+ type: z.union([
750
+ "instant",
751
+ "fast",
752
+ "auto",
753
+ "deep-lite",
754
+ "deep",
755
+ "deep-reasoning"
756
+ ]),
757
+ textFallback: z.boolean(),
758
+ startPublishedDate: z.string(),
759
+ category: z.union([
760
+ "",
761
+ "company",
762
+ "publication",
763
+ "news",
764
+ "personal site",
765
+ "financial report",
766
+ "people"
767
+ ]),
768
+ maxAgeHours: z.number().step(1).min(-1).max(720),
769
+ endPublishedDate: z.string(),
770
+ textVerbosity: z.union([
771
+ "",
772
+ "compact",
773
+ "standard",
774
+ "full"
775
+ ]),
776
+ includeSections: z.string(),
777
+ excludeSections: z.string(),
778
+ keySelection: z.union([
779
+ "order",
780
+ "round-robin",
781
+ "random"
782
+ ])
783
+ })),
784
+ anysearch: vol(z.object({
785
+ enabled: z.boolean(),
786
+ apiKeyEnv: z.string(),
787
+ baseURL: z.string(),
788
+ zone: z.union(["cn", "intl"]),
789
+ keySelection: z.union([
790
+ "order",
791
+ "round-robin",
792
+ "random"
793
+ ])
794
+ }))
795
+ });
796
+ }
797
+ /**
798
+ * Validation schema the cordis loader applies to the `dsh-websearch` config
799
+ * section — every editable field volatile-marked (S32, ADR-0021): 0.1.7+
800
+ * hosts register the namespace as a live settings form from these marks and
801
+ * resolve the fields into `Volatile` handles.
802
+ */
803
+ const Config = buildConfigSchema(true);
804
+ /**
805
+ * The 0.1.5/0.1.6 `installSection` face of the same schema — identical
806
+ * fields with the volatile marks stripped, because a legacy host's settings
807
+ * GUI would serialize a `Volatile` handle as an empty object (ADR-0021).
808
+ */
809
+ const ConfigLegacy = buildConfigSchema(false);
810
+ /** Split a comma-separated domain list into trimmed non-blank entries. */
811
+ function splitDomainList(value) {
812
+ if (value === void 0) return [];
813
+ return value.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
814
+ }
815
+ /**
816
+ * The include-vs-exclude exclusivity rule (ADR-0018): both lists set at once is
817
+ * rejected — on the settings path through the installSection validate hook
818
+ * (before persist, error surfaced to the committer) and on the cordis.yml load
819
+ * path through this throw. A resolveConfig throw must NOT be relied on for the
820
+ * settings path: the host swallows watcher throws into a warn, persisting the
821
+ * invalid value and bricking the plugin on restart (S20 stage-2 M-1 evidence).
822
+ */
823
+ function validateUnifiedDomainRule(value) {
824
+ if (value.searchIncludeDomains?.trim().length && value.searchExcludeDomains?.trim().length) throw new Error("searchIncludeDomains and searchExcludeDomains are mutually exclusive — set only one (ADR-0018)");
825
+ }
826
+ /**
827
+ * The Exa section-filter freshness rule (S22 P3): `contents.text` section filters officially
828
+ * require a fresh crawl (`maxAgeHours: 0`; `-1` never-recrawl also bypasses cache). Sections
829
+ * configured while `maxAgeHours` is absent or positive are rejected — dual-path like the ADR-0018
830
+ * domain rule: the settings write path through the installSection validate hook (before persist)
831
+ * and the cordis.yml load path through the `resolveConfig` throw (a watcher throw would otherwise
832
+ * be swallowed into a warn and brick the restart, see {@link validateUnifiedDomainRule}).
833
+ */
834
+ const TBS_TOKEN = /^(qdr:[hdwmy]|sbd:1|cdr:1|cd_min:\d{2}\/\d{2}\/\d{4}|cd_max:\d{2}\/\d{2}\/\d{4})$/;
835
+ /**
836
+ * The Firecrawl `tbs` grammar rule (S22 P3): comma-combined tokens from the official forms —
837
+ * `qdr:*` presets, `sbd:1` date sort, `cdr:1` requiring both `cd_min`/`cd_max` `MM/DD/YYYY`
838
+ * bounds. Anything else is rejected, dual-path like the ADR-0018 domain rule (settings validate
839
+ * hook before persist + resolveConfig throw on load).
840
+ */
841
+ function validateFirecrawlTbsRule(value) {
842
+ const raw = value.firecrawl?.tbs?.trim();
843
+ if (raw === void 0 || raw.length === 0) return;
844
+ const tokens = raw.split(",").map((token) => token.trim()).filter((token) => token.length > 0);
845
+ if (tokens.length === 0 || tokens.some((token) => !TBS_TOKEN.test(token))) throw new Error(`firecrawl.tbs "${raw}" is not a valid tbs expression — combine qdr:* presets, sbd:1, and cdr:1 with cd_min/cd_max MM/DD/YYYY bounds`);
846
+ const hasCdr = tokens.includes("cdr:1");
847
+ const hasMin = tokens.some((token) => token.startsWith("cd_min:"));
848
+ const hasMax = tokens.some((token) => token.startsWith("cd_max:"));
849
+ if (hasCdr && (!hasMin || !hasMax)) throw new Error("firecrawl.tbs cdr:1 requires both cd_min:MM/DD/YYYY and cd_max:MM/DD/YYYY bounds");
850
+ if (!hasCdr && (hasMin || hasMax)) throw new Error("firecrawl.tbs cd_min/cd_max bounds are only valid together with cdr:1");
851
+ }
852
+ function validateExaSectionFilterRule(value) {
853
+ const exa = value.exa;
854
+ if (exa === void 0) return;
855
+ const sectionsConfigured = (exa.includeSections?.trim().length ?? 0) > 0 || (exa.excludeSections?.trim().length ?? 0) > 0;
856
+ const freshness = exa.maxAgeHours;
857
+ if (sectionsConfigured && (freshness === void 0 || freshness > 0)) throw new Error("exa.includeSections/excludeSections require exa.maxAgeHours = 0 (fresh crawl) or -1 (never recrawl) — official constraint");
858
+ }
859
+ /**
860
+ * Apply every default explicitly: empty chains become the built-in member
861
+ * order, a missing timeout budget becomes 30s, and each member section gets
862
+ * `enabled: true` plus its credential-ref env name. Provider-specific option
863
+ * defaults (base URLs, models, result counts) stay with the provider
864
+ * implementations (S04/S05a); their values pass through untouched. Input is
865
+ * normalized through {@link materializeConfig} first, so plain configs and
866
+ * 0.1.7+ handle-wrapped runtime configs resolve identically (ADR-0021).
867
+ */
868
+ function resolveConfig(config) {
869
+ const plain = materializeConfig(config);
870
+ validateUnifiedDomainRule(plain);
871
+ validateExaSectionFilterRule(plain);
872
+ validateFirecrawlTbsRule(plain);
873
+ const fallbackMember = plain.fallbackMember === "dshws-perplexity" ? "auto" : plain.fallbackMember !== void 0 ? plain.fallbackMember : plain.fallbackProvider === "deepseek" ? DEEPSEEK_FALLBACK_MEMBER_ID : "auto";
874
+ return {
875
+ searchChain: withDesignatedFallback(plain.searchChain?.length ? [...plain.searchChain] : ORDERABLE_SEARCH_MEMBER_ORDER, fallbackMember),
876
+ fallbackMember,
877
+ fetchTakeover: plain.fetchTakeover ?? true,
878
+ searchCountry: plain.searchCountry?.trim().length ? plain.searchCountry.trim().toUpperCase() : void 0,
879
+ searchLanguage: plain.searchLanguage?.trim().length ? plain.searchLanguage.trim().toLowerCase() : void 0,
880
+ searchIncludeDomains: splitDomainList(plain.searchIncludeDomains),
881
+ searchExcludeDomains: splitDomainList(plain.searchExcludeDomains),
882
+ fetchChain: plain.fetchChain?.length ? [...plain.fetchChain].filter((id) => id !== DEEPSEEK_FALLBACK_MEMBER_ID) : [...FETCH_CHAIN_DEFAULT_ORDER],
883
+ perMemberTimeoutMs: plain.perMemberTimeoutMs ?? 3e4,
884
+ deepseek: {
885
+ enabled: plain.deepseek?.enabled ?? false,
886
+ apiKeyEnv: plain.deepseek?.apiKeyEnv ?? "DEEPSEEK_API_KEY",
887
+ keySelection: plain.deepseek?.keySelection ?? "round-robin",
888
+ baseURL: plain.deepseek?.baseURL?.trim() === "" ? void 0 : plain.deepseek?.baseURL,
889
+ model: plain.deepseek?.model,
890
+ maxTokens: plain.deepseek?.maxTokens,
891
+ maxUses: plain.deepseek?.maxUses
892
+ },
893
+ tavily: {
894
+ enabled: plain.tavily?.enabled ?? true,
895
+ apiKeyEnv: plain.tavily?.apiKeyEnv ?? "TAVILY_API_KEY",
896
+ keySelection: plain.tavily?.keySelection ?? "round-robin",
897
+ baseURL: plain.tavily?.baseURL?.trim() === "" ? void 0 : plain.tavily?.baseURL,
898
+ maxResults: plain.tavily?.maxResults,
899
+ topic: plain.tavily?.topic || void 0,
900
+ timeRange: plain.tavily?.timeRange || void 0,
901
+ searchDepth: plain.tavily?.searchDepth || void 0,
902
+ includeAnswer: plain.tavily?.includeAnswer ?? "basic",
903
+ chunksPerSource: plain.tavily?.chunksPerSource,
904
+ filterByLanguage: plain.tavily?.filterByLanguage,
905
+ startDate: plain.tavily?.startDate?.trim().length ? plain.tavily.startDate.trim() : void 0,
906
+ endDate: plain.tavily?.endDate?.trim().length ? plain.tavily.endDate.trim() : void 0,
907
+ exactMatch: plain.tavily?.exactMatch,
908
+ includeDomainsMode: plain.tavily?.includeDomainsMode
909
+ },
910
+ firecrawl: {
911
+ enabled: plain.firecrawl?.enabled ?? true,
912
+ apiKeyEnv: plain.firecrawl?.apiKeyEnv ?? "FIRECRAWL_API_KEY",
913
+ keySelection: plain.firecrawl?.keySelection ?? "round-robin",
914
+ baseURL: plain.firecrawl?.baseURL?.trim() === "" ? void 0 : plain.firecrawl?.baseURL,
915
+ tbs: plain.firecrawl?.tbs?.trim().length ? plain.firecrawl.tbs.trim() : void 0,
916
+ safe: plain.firecrawl?.safe,
917
+ sources: plain.firecrawl?.sources || void 0,
918
+ categories: plain.firecrawl?.categories || void 0,
919
+ location: plain.firecrawl?.location?.trim() === "" ? void 0 : plain.firecrawl?.location
920
+ },
921
+ exa: {
922
+ enabled: plain.exa?.enabled ?? true,
923
+ apiKeyEnv: plain.exa?.apiKeyEnv ?? "EXA_API_KEY",
924
+ keySelection: plain.exa?.keySelection ?? "round-robin",
925
+ baseURL: plain.exa?.baseURL?.trim() === "" ? void 0 : plain.exa?.baseURL,
926
+ numResults: plain.exa?.numResults,
927
+ type: plain.exa?.type,
928
+ textFallback: plain.exa?.textFallback ?? true,
929
+ startPublishedDate: plain.exa?.startPublishedDate?.trim().length ? plain.exa.startPublishedDate.trim() : void 0,
930
+ category: plain.exa?.category || void 0,
931
+ maxAgeHours: plain.exa?.maxAgeHours,
932
+ endPublishedDate: plain.exa?.endPublishedDate?.trim().length ? plain.exa.endPublishedDate.trim() : void 0,
933
+ textVerbosity: plain.exa?.textVerbosity || void 0,
934
+ includeSections: plain.exa?.includeSections?.trim().length ? plain.exa.includeSections.trim() : void 0,
935
+ excludeSections: plain.exa?.excludeSections?.trim().length ? plain.exa.excludeSections.trim() : void 0
936
+ },
937
+ anysearch: {
938
+ enabled: plain.anysearch?.enabled ?? true,
939
+ apiKeyEnv: plain.anysearch?.apiKeyEnv ?? "ANYSEARCH_API_KEY",
940
+ baseURL: plain.anysearch?.baseURL?.trim() === "" ? void 0 : plain.anysearch?.baseURL,
941
+ zone: plain.anysearch?.zone,
942
+ keySelection: plain.anysearch?.keySelection ?? "round-robin"
943
+ }
944
+ };
945
+ }
946
+ //#endregion
947
+ //#region src/credentials.ts
948
+ /**
949
+ * Credential gate: the hot-read `credentialsReady` source for chain members.
950
+ * It caches the credentials service's `describe` answer per watched reference
951
+ * and refreshes the cache on `credentials/reference-updated`, so chain
952
+ * availability tracks the user storing or removing a key without a restart.
953
+ *
954
+ * Only the describe fact is cached — never a key value. Members resolve the
955
+ * secret fresh at each operation (the service's per-operation contract); this
956
+ * gate carries the cheap, value-free readiness signal `available()` needs.
957
+ *
958
+ * The cache starts empty and an unknown reference reads as not ready: before
959
+ * a describe there is no fact, and readiness without a fact is the S03
960
+ * facade again. `describe` failures read as not-ready plus a log line — the
961
+ * conservative answer can only skip a member, never leak readiness.
962
+ *
963
+ * @module dsh-websearch/credentials
964
+ */
965
+ var CredentialGate = class {
966
+ #credentials;
967
+ #log;
968
+ #watched = /* @__PURE__ */ new Set();
969
+ #ready = /* @__PURE__ */ new Map();
970
+ constructor(ports) {
971
+ this.#credentials = ports.credentials;
972
+ this.#log = ports.log;
973
+ ports.subscribe((ref) => void this.#refresh(String(ref)));
974
+ }
975
+ /**
976
+ * Validate the configured references (a name outside the credential
977
+ * grammar throws here — misconfiguration fails loud at load), then describe
978
+ * each and cache the result. Resolves once the initial cache is filled.
979
+ */
980
+ async prime(refNames) {
981
+ const refs = refNames.map((name) => String(credentialRef(name)));
982
+ for (const ref of refs) this.#watched.add(ref);
983
+ await Promise.all(refs.map((ref) => this.#refresh(ref)));
984
+ }
985
+ /** Whether the ref currently describes as configured; unknown refs are not ready. */
986
+ isReady(refName) {
987
+ return this.#ready.get(refName) === true;
988
+ }
989
+ /** Re-describe one watched ref; events for unwatched refs are ignored. */
990
+ async #refresh(ref) {
991
+ if (!this.#watched.has(ref)) return;
992
+ try {
993
+ const info = await this.#credentials.describe(credentialRef(ref));
994
+ this.#ready.set(ref, info.configured);
995
+ } catch (error) {
996
+ this.#ready.set(ref, false);
997
+ this.#log?.(`[dshws-websearch] credential describe failed for ${ref}: ${String(error)}`);
998
+ }
999
+ }
1000
+ };
1001
+ //#endregion
1002
+ //#region src/providers/shared.ts
1003
+ /**
1004
+ * Shared member-provider scaffolding: the mechanical cancellation, config
1005
+ * check, and error-unfold plumbing every bundled provider needs. Families
1006
+ * supply their code object and a display label; only extraction lives here —
1007
+ * request mapping, response mapping, and each backend's availability contract
1008
+ * stay in the provider files (a shared base class would obscure which fields
1009
+ * make a given backend usable).
1010
+ *
1011
+ * @module dsh-websearch/providers/shared
1012
+ */
1013
+ /** True for a fetch/`AbortSignal` abort, surfaced as the member's aborted code. */
1014
+ function isAbortError(error) {
1015
+ return error instanceof DOMException && error.name === "AbortError";
1016
+ }
1017
+ /** Build the member's stable cancellation error while retaining the caller's reason. */
1018
+ function memberAborted(codes, label, signal, fallback) {
1019
+ return new DshwsError(codes.aborted, `${label} search aborted`, { cause: signal?.aborted === true ? signal.reason : fallback });
1020
+ }
1021
+ /** Throw the member's stable cancellation error when the caller already aborted. */
1022
+ function throwIfMemberAborted(codes, label, signal) {
1023
+ if (signal?.aborted === true) throw memberAborted(codes, label, signal);
1024
+ }
1025
+ /** Classify one fetch throw: caller cancellation keeps its own error, the rest is a request failure. */
1026
+ function memberFetchFailure(codes, label, error, signal) {
1027
+ if (signal?.aborted === true || isAbortError(error)) return memberAborted(codes, label, signal, error);
1028
+ return new DshwsError(codes.requestFailed, `${label} search request failed: ${String(error)}`, { cause: error });
1029
+ }
1030
+ /** Wrap an unprocessable success body (bad JSON, unexpected shape) as the member's bad-response error. */
1031
+ function memberBadResponse(codes, label, error) {
1032
+ return new DshwsError(codes.badResponse, `${label} returned an unprocessable response body: ${String(error)}`, { cause: error });
1033
+ }
1034
+ /**
1035
+ * First non-empty detail string among the wire error shapes seen across
1036
+ * providers: `error` (string or `{ message }`), `detail` (string or
1037
+ * `{ message }`), then top-level `message`. Non-JSON bodies never reach this
1038
+ * (the caller's `response.json()` throws first).
1039
+ */
1040
+ function unfoldHttpErrorDetail(parsed) {
1041
+ const pick = (value) => typeof value === "string" ? value : value?.message;
1042
+ return [
1043
+ pick(parsed.error),
1044
+ pick(parsed.detail),
1045
+ parsed.message
1046
+ ].find((candidate) => candidate !== void 0 && candidate.length > 0);
1047
+ }
1048
+ /** True for a request limit that can be sent to the provider (a positive whole number). */
1049
+ function isPositiveInteger(value) {
1050
+ return Number.isInteger(value) && value > 0;
1051
+ }
1052
+ /**
1053
+ * Resolve one operation's key without retaining it (the credentials service's
1054
+ * per-operation contract). A missing key is a loud credential error naming the
1055
+ * ref; a rejecting resolver is a request failure; a caller abort wins over both.
1056
+ */
1057
+ async function resolveMemberApiKey(options) {
1058
+ const { codes, label, apiKeyRef, resolveApiKey, signal } = options;
1059
+ throwIfMemberAborted(codes, label, signal);
1060
+ let resolved;
1061
+ try {
1062
+ resolved = await resolveApiKey();
1063
+ } catch (error) {
1064
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes, label, signal, error);
1065
+ throw new DshwsError(codes.requestFailed, `${label} credential resolution failed: ${String(error)}`, { cause: error });
1066
+ }
1067
+ if (resolved !== void 0 && resolved.length > 0) return resolved;
1068
+ throw new DshwsError(codes.credentialMissing, `${label} search has no API key for "${apiKeyRef}"; store it through the dsh credentials page or export it in the launching environment`);
1069
+ }
1070
+ /** Split one comma value into the trimmed, non-empty key sequence. */
1071
+ function splitKeys(value) {
1072
+ return value.split(",").map((key) => key.trim()).filter((key) => key.length > 0);
1073
+ }
1074
+ var KeyPool = class KeyPool {
1075
+ #ports;
1076
+ /** Round-robin cursor over the key sequence; modulo-applied per call. */
1077
+ #cursor = 0;
1078
+ /** Keys in the pool as of the LAST resolve (S14r retry gate; 0 = never drawn). */
1079
+ #lastKeyCount = 0;
1080
+ /** Without-replacement deck for `random` (ADR-0012); a permutation of the last seen split. */
1081
+ #deck = [];
1082
+ /** Next deck index to draw; `>= deck.length` means the cycle is exhausted. */
1083
+ #deckPos = 0;
1084
+ constructor(ports) {
1085
+ this.#ports = ports;
1086
+ }
1087
+ /**
1088
+ * Whether the next draw could yield a DIFFERENT key (S14r/S14u): needs
1089
+ * more than one key AND a policy that advances the selection — `order`
1090
+ * always returns keys[0], so its "redraws" would retry the SAME key and
1091
+ * the retry gate must refuse (blind-retry guard extended to policies).
1092
+ * Before the first draw this reports false — the gate warms up after the
1093
+ * first request, so the very first request degrades on single-key members.
1094
+ */
1095
+ hasMultiKeyPool() {
1096
+ return this.#lastKeyCount > 1 && this.#ports.selection() !== "order";
1097
+ }
1098
+ /** The live ref name (gate priming and diagnostics). */
1099
+ refs() {
1100
+ return [this.#ports.ref()];
1101
+ }
1102
+ /**
1103
+ * Whether the member's credential ref currently describes as configured —
1104
+ * the member-gate readiness (`credentialsReady`). The comma value counts
1105
+ * as configured whenever a value is stored; emptiness inside it fails
1106
+ * loud at resolve time (ADR-0011).
1107
+ */
1108
+ ready() {
1109
+ return this.#ports.isReady(this.#ports.ref());
1110
+ }
1111
+ /** The provider-facing thunk: resolve the value, split, select one key. */
1112
+ async resolveApiKey(signal) {
1113
+ const { label, codes } = this.#ports;
1114
+ throwIfMemberAborted(codes, label, signal);
1115
+ const ref = this.#ports.ref();
1116
+ let value;
1117
+ try {
1118
+ value = await this.#ports.resolve(ref);
1119
+ } catch (error) {
1120
+ if (signal?.aborted === true || error instanceof DOMException && error.name === "AbortError") throw new DshwsError(codes.aborted, `${label} search aborted`, { cause: error });
1121
+ throw new DshwsError(codes.requestFailed, `${label} credential resolution failed: ${String(error)}`, { cause: error });
1122
+ }
1123
+ const keys = splitKeys(value ?? "");
1124
+ this.#lastKeyCount = keys.length;
1125
+ if (keys.length === 0) throw new DshwsError(codes.credentialMissing, `${label} search has no API key for "${ref}"; store it (comma-separated for multiple keys) through the dsh credentials page or export it in the launching environment`);
1126
+ if (keys.length > 10) throw new DshwsError(codes.requestFailed, `${label} key pool exceeds the limit: ${keys.length} keys configured for "${ref}" (max 10); trim the comma-separated value`);
1127
+ const selected = this.#select(keys);
1128
+ return resolveMemberApiKey({
1129
+ codes,
1130
+ label,
1131
+ apiKeyRef: ref,
1132
+ resolveApiKey: async () => selected,
1133
+ signal
1134
+ });
1135
+ }
1136
+ /**
1137
+ * Draw one key per policy. `random` draws from a shuffled deck without
1138
+ * replacement (ADR-0012): mid-cycle draws walk the deck; an exhausted deck
1139
+ * or a split whose multiset no longer matches the deck (hot value change)
1140
+ * reshuffles first. A failed request consumes its draw; whether the chain
1141
+ * redraws another key within the member (S14r: up to MEMBER_DRAWS draws,
1142
+ * multi-key pools with a switching policy only) is chain policy.
1143
+ */
1144
+ #select(keys) {
1145
+ const selection = this.#ports.selection();
1146
+ if (selection === "random") {
1147
+ const rng = this.#ports.rng ?? Math.random;
1148
+ if (this.#deckPos >= this.#deck.length || !KeyPool.#sameMultiset(this.#deck, keys)) {
1149
+ this.#deck = KeyPool.#shuffle(keys, rng);
1150
+ this.#deckPos = 0;
1151
+ }
1152
+ return this.#deck[this.#deckPos++];
1153
+ }
1154
+ if (selection === "round-robin") {
1155
+ const picked = keys[this.#cursor % keys.length];
1156
+ this.#cursor += 1;
1157
+ return picked;
1158
+ }
1159
+ return keys[0];
1160
+ }
1161
+ /** Fisher-Yates (ascending form): `rng ≡ 0` yields the identity permutation. */
1162
+ static #shuffle(keys, rng) {
1163
+ const deck = [...keys];
1164
+ for (let i = 0; i < deck.length - 1; i += 1) {
1165
+ const j = i + Math.floor(rng() * (deck.length - i));
1166
+ [deck[i], deck[j]] = [deck[j], deck[i]];
1167
+ }
1168
+ return deck;
1169
+ }
1170
+ /** Whether both sequences contain exactly the same keys with the same multiplicities. */
1171
+ static #sameMultiset(a, b) {
1172
+ if (a.length !== b.length) return false;
1173
+ const counts = /* @__PURE__ */ new Map();
1174
+ for (const key of a) counts.set(key, (counts.get(key) ?? 0) + 1);
1175
+ for (const key of b) {
1176
+ const left = counts.get(key);
1177
+ if (left === void 0 || left <= 0) return false;
1178
+ counts.set(key, left - 1);
1179
+ }
1180
+ return true;
1181
+ }
1182
+ };
1183
+ //#endregion
1184
+ //#region src/key-counts.ts
1185
+ /** Wire namespace of this plugin's Remote (`remote.dshws-websearch` client-side). */
1186
+ const KEY_COUNTS_NAMESPACE = "dshws-websearch";
1187
+ /** Count one ref's keys; a resolve failure answers the conservative 0. */
1188
+ async function countKeys(resolve, ref) {
1189
+ try {
1190
+ const value = await resolve(ref);
1191
+ return value === void 0 ? 0 : splitKeys(value).length;
1192
+ } catch {
1193
+ return 0;
1194
+ }
1195
+ }
1196
+ /**
1197
+ * Host service exposing the per-ref key counts to the settings page. The
1198
+ * gateway discovers it through its `typertRemote` binding (source-mode
1199
+ * discovery), so no assembly change is needed on the host side.
1200
+ *
1201
+ * The gateway invokes Remote methods with the context's traceable proxy as
1202
+ * the receiver, so the method body reads only public members — no `#private`
1203
+ * state (private-field access through that proxy throws).
1204
+ */
1205
+ var DshWsKeyCountsRemote = class extends TypertRemoteService {
1206
+ ports;
1207
+ /** @param ctx - owning Cordis Context (the plugin's fiber owns disposal). */
1208
+ constructor(ctx, ports) {
1209
+ super(ctx, "dshwsKeyCounts", { namespace: KEY_COUNTS_NAMESPACE });
1210
+ this.ports = ports;
1211
+ for (const initializer of keyCountsInitializers) initializer.call(this);
1212
+ }
1213
+ /**
1214
+ * Count the configured keys for several references. Counts only — the
1215
+ * stored value stays in the host process.
1216
+ * @param refs - reference names; a name outside the member whitelist answers 0.
1217
+ * @returns one count per requested name, keyed by that name.
1218
+ */
1219
+ async describeKeyCounts(refs) {
1220
+ const ports = this.ports;
1221
+ const allowed = ports.allowedRefs();
1222
+ const entries = await Promise.all([...new Set(refs)].map(async (ref) => [ref, allowed.has(ref) ? await countKeys(ports.resolve, ref) : 0]));
1223
+ return Object.fromEntries(entries);
1224
+ }
1225
+ };
1226
+ /** Constructor-phase initializers captured by the runtime `Remote` marking below. */
1227
+ const keyCountsInitializers = [];
1228
+ Remote(Object.getOwnPropertyDescriptor(DshWsKeyCountsRemote.prototype, "describeKeyCounts").value, {
1229
+ kind: "method",
1230
+ name: "describeKeyCounts",
1231
+ static: false,
1232
+ private: false,
1233
+ access: {
1234
+ has: (target) => target.describeKeyCounts !== void 0,
1235
+ get: (target) => target.describeKeyCounts
1236
+ },
1237
+ addInitializer: (initializer) => {
1238
+ keyCountsInitializers.push(initializer);
1239
+ },
1240
+ metadata: {}
1241
+ });
1242
+ //#endregion
1243
+ //#region src/providers/anysearch.ts
1244
+ /** Stable id this member registers under (chain + direct pin, `dshws-` prefixed). */
1245
+ const ANYSEARCH_MEMBER_ID = "dshws-anysearch";
1246
+ const codes$4 = MEMBER_ERROR_CODES.anysearch;
1247
+ /** Attribution header sent on every request; bump with the package version. */
1248
+ const USER_AGENT$4 = "dsh-websearch/0.1.0";
1249
+ /**
1250
+ * Explicit defaulting at the owning boundary (explicit > implicit): the base
1251
+ * URL default lands here, config passthrough stays untouched.
1252
+ */
1253
+ function resolveAnysearchMemberOptions(config, resolveApiKey, fanout) {
1254
+ return {
1255
+ apiKeyRef: config.apiKeyEnv,
1256
+ resolveApiKey,
1257
+ baseURL: config.baseURL ?? "https://api.anysearch.com",
1258
+ zone: config.zone,
1259
+ language: fanout?.language !== void 0 ? toAnysearchLanguage(fanout.language) : void 0
1260
+ };
1261
+ }
1262
+ /**
1263
+ * Map the unified entry's region-less ISO 639-1 value (stored lower-case) to
1264
+ * the BCP-47 form the API expects: `zh` gains the default `CN` region, any
1265
+ * other value keeps its subtag but the region part is re-cased to upper
1266
+ * (`zh-tw` -> `zh-TW`); a bare language passes through unchanged (S22 P3).
1267
+ */
1268
+ function toAnysearchLanguage(language) {
1269
+ if (language === "zh") return "zh-CN";
1270
+ const [primary, region] = language.split("-");
1271
+ return region !== void 0 ? `${primary}-${region.toUpperCase()}` : primary;
1272
+ }
1273
+ /**
1274
+ * Map one Anysearch result to a normalized source. The portable snippet is
1275
+ * `snippet`, falling back to `content` (the official mapping drops content —
1276
+ * ADR-0009 Decision 2 keeps it); blank optional fields are omitted rather
1277
+ * than emitted as empty. Entries without a `url` are dropped — a source
1278
+ * always has a URL.
1279
+ */
1280
+ function mapAnysearchResult(item) {
1281
+ if (item.url === void 0 || item.url.length === 0) return void 0;
1282
+ const snippet = [item.snippet, item.content].find((candidate) => candidate !== void 0 && candidate.trim().length > 0);
1283
+ return {
1284
+ url: item.url,
1285
+ ...item.title != null && item.title.length > 0 ? { title: item.title } : {},
1286
+ ...snippet !== void 0 ? { snippet } : {}
1287
+ };
1288
+ }
1289
+ /** Map an envelope data payload to a normalized result (no provider-side truncation). */
1290
+ function mapAnysearchResponse(data) {
1291
+ return {
1292
+ sources: (data.results ?? []).map(mapAnysearchResult).filter((source) => source !== void 0),
1293
+ truncated: false
1294
+ };
1295
+ }
1296
+ /**
1297
+ * Map an /v1/extract envelope data payload to a fetch result (S21, probe
1298
+ * contract docs/notes/2026-09-10-s21-anysearch-extract-probe.md): the
1299
+ * denoised markdown `content` becomes the text body; the probe-measured
1300
+ * ~50k cap (49,934 on an over-long page) maps to `truncated` through a
1301
+ * 49,900 defensive band.
1302
+ */
1303
+ function mapAnysearchExtractData(requestUrl, data) {
1304
+ if (data.content === void 0 || data.content.length === 0) throw new DshwsError(codes$4.badResponse, "AnySearch extract returned no content on a code-0 envelope");
1305
+ return {
1306
+ url: data.url ?? requestUrl,
1307
+ statusCode: 200,
1308
+ body: {
1309
+ kind: "text",
1310
+ content: data.content
1311
+ },
1312
+ truncated: data.content.length >= 49900
1313
+ };
1314
+ }
1315
+ /** The Anysearch-backed chain member on both capability faces (search + extract, S21). */
1316
+ var AnysearchSearchProvider = class {
1317
+ options;
1318
+ id = ANYSEARCH_MEMBER_ID;
1319
+ constructor(options) {
1320
+ this.options = options;
1321
+ }
1322
+ /** Cheap local config check (no network, no key dimension — the gate owns that). */
1323
+ available() {
1324
+ return URL.canParse(this.options.baseURL);
1325
+ }
1326
+ async search(request, signal) {
1327
+ throwIfMemberAborted(codes$4, "Anysearch", signal);
1328
+ const apiKey = await this.#apiKey(signal);
1329
+ throwIfMemberAborted(codes$4, "Anysearch", signal);
1330
+ const maxResults = request.maxResults;
1331
+ let response;
1332
+ try {
1333
+ response = await fetch(`${this.options.baseURL}/v1/search`, {
1334
+ method: "POST",
1335
+ redirect: "error",
1336
+ headers: {
1337
+ "authorization": `Bearer ${apiKey}`,
1338
+ "content-type": "application/json",
1339
+ "accept": "application/json",
1340
+ "user-agent": USER_AGENT$4
1341
+ },
1342
+ body: JSON.stringify({
1343
+ query: request.query,
1344
+ ...maxResults !== void 0 ? { max_results: maxResults } : {},
1345
+ ...this.options.zone !== void 0 ? { zone: this.options.zone } : {},
1346
+ ...this.options.language !== void 0 ? { language: this.options.language } : {}
1347
+ }),
1348
+ ...signal !== void 0 ? { signal } : {}
1349
+ });
1350
+ } catch (error) {
1351
+ throw memberFetchFailure(codes$4, "Anysearch", error, signal);
1352
+ }
1353
+ if (!response.ok) {
1354
+ const status = response.status;
1355
+ let message = `Anysearch API error (HTTP ${status})`;
1356
+ try {
1357
+ const detail = unfoldHttpErrorDetail(await response.json());
1358
+ if (detail !== void 0 && detail.length > 0) message += `: ${detail}`;
1359
+ } catch (error) {
1360
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$4, "Anysearch", signal, error);
1361
+ }
1362
+ throw new DshwsError(codes$4.httpError, message, { httpStatus: status });
1363
+ }
1364
+ let envelope;
1365
+ try {
1366
+ envelope = await response.json();
1367
+ } catch (error) {
1368
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$4, "Anysearch", signal, error);
1369
+ throw memberBadResponse(codes$4, "Anysearch", error);
1370
+ }
1371
+ if (envelope.code !== 0) {
1372
+ const requestId = envelope.request_id !== void 0 ? ` (request_id: ${envelope.request_id})` : "";
1373
+ throw new DshwsError(codes$4.httpError, `Anysearch API error (code ${envelope.code})${envelope.message !== void 0 ? `: ${envelope.message}` : ""}${requestId}`);
1374
+ }
1375
+ return mapAnysearchResponse(envelope.data ?? {});
1376
+ }
1377
+ /** Resolve one operation's key without retaining it; a missing key is a loud member error. */
1378
+ /**
1379
+ * The extract face (S21, probe-backed): `POST /v1/extract` with a single
1380
+ * `{url}` body — the probe rejected the array form. Envelope `code !== 0`
1381
+ * rides the established business-error path (chain degradation).
1382
+ */
1383
+ async fetch(request, signal) {
1384
+ throwIfMemberAborted(codes$4, "AnySearch", signal);
1385
+ const apiKey = await this.#apiKey(signal);
1386
+ throwIfMemberAborted(codes$4, "AnySearch", signal);
1387
+ let response;
1388
+ try {
1389
+ response = await fetch(`${this.options.baseURL}/v1/extract`, {
1390
+ method: "POST",
1391
+ redirect: "error",
1392
+ headers: {
1393
+ "authorization": `Bearer ${apiKey}`,
1394
+ "content-type": "application/json",
1395
+ "accept": "application/json",
1396
+ "user-agent": USER_AGENT$4
1397
+ },
1398
+ body: JSON.stringify({ url: request.url }),
1399
+ ...signal !== void 0 ? { signal } : {}
1400
+ });
1401
+ } catch (error) {
1402
+ throw memberFetchFailure(codes$4, "AnySearch", error, signal);
1403
+ }
1404
+ if (!response.ok) {
1405
+ const status = response.status;
1406
+ throw new DshwsError(codes$4.httpError, `Anysearch API error (HTTP ${status})`, { httpStatus: status });
1407
+ }
1408
+ let envelope;
1409
+ try {
1410
+ envelope = await response.json();
1411
+ } catch (error) {
1412
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$4, "AnySearch", signal, error);
1413
+ throw memberBadResponse(codes$4, "AnySearch", error);
1414
+ }
1415
+ if (envelope.code !== 0) {
1416
+ const requestId = envelope.request_id !== void 0 ? ` (request_id: ${envelope.request_id})` : "";
1417
+ throw new DshwsError(codes$4.httpError, `Anysearch API error (code ${envelope.code})${envelope.message !== void 0 ? `: ${envelope.message}` : ""}${requestId}`);
1418
+ }
1419
+ return mapAnysearchExtractData(request.url, envelope.data ?? {});
1420
+ }
1421
+ #apiKey(signal) {
1422
+ return resolveMemberApiKey({
1423
+ codes: codes$4,
1424
+ label: "Anysearch",
1425
+ apiKeyRef: this.options.apiKeyRef,
1426
+ resolveApiKey: this.options.resolveApiKey,
1427
+ signal
1428
+ });
1429
+ }
1430
+ };
1431
+ //#endregion
1432
+ //#region src/providers/deepseek.ts
1433
+ /** Stable id this member registers under (chain + direct pin, `dshws-` prefixed). */
1434
+ const DEEPSEEK_MEMBER_ID = "dshws-deepseek";
1435
+ /** `anthropic-version` header value; fixed wire constant. */
1436
+ const DEEPSEEK_API_VERSION = "2023-06-01";
1437
+ const codes$3 = MEMBER_ERROR_CODES.deepseek;
1438
+ /** Attribution header sent on every request; bump with the package version. */
1439
+ const USER_AGENT$3 = "dsh-websearch/0.1.0";
1440
+ /**
1441
+ * Explicit defaulting at the owning boundary (explicit > implicit): omitted
1442
+ * config fields become the provider constants here, not via schema injection.
1443
+ */
1444
+ function resolveDeepSeekMemberOptions(config, resolveApiKey) {
1445
+ return {
1446
+ apiKeyRef: config.apiKeyEnv,
1447
+ resolveApiKey,
1448
+ baseURL: config.baseURL ?? "https://api.deepseek.com/anthropic/v1",
1449
+ model: config.model ?? "deepseek-v4-flash",
1450
+ maxTokens: config.maxTokens ?? 4096,
1451
+ maxUses: config.maxUses ?? 10
1452
+ };
1453
+ }
1454
+ function isTextBlock(block) {
1455
+ return block.type === "text";
1456
+ }
1457
+ function isResultBlock(block) {
1458
+ return block.type === "web_search_tool_result";
1459
+ }
1460
+ /**
1461
+ * Build a `url → cited_text` map from every text block's citations. The
1462
+ * excerpt lives in a separate text block keyed by `url`; first occurrence
1463
+ * wins.
1464
+ */
1465
+ function citationSnippets(blocks) {
1466
+ const map = /* @__PURE__ */ new Map();
1467
+ for (const block of blocks) {
1468
+ if (!isTextBlock(block)) continue;
1469
+ for (const cite of block.citations ?? []) if (cite.url != null && cite.url.length > 0 && cite.cited_text != null && cite.cited_text.length > 0 && !map.has(cite.url)) map.set(cite.url, cite.cited_text);
1470
+ }
1471
+ return map;
1472
+ }
1473
+ /**
1474
+ * Map a Messages response to a normalized search result: walk
1475
+ * `web_search_tool_result` blocks for citeable items, join citation excerpts
1476
+ * as `snippet`, dedupe by `url`. The web service owns final `maxResults`
1477
+ * truncation, so `truncated` is always `false` here; no generated answer
1478
+ * text exists, so `content` stays omitted.
1479
+ * @throws {@link DshwsError} code `DSHWS_DEEPSEEK_BAD_RESPONSE` when no result block came back.
1480
+ */
1481
+ function mapDeepSeekResponse(response) {
1482
+ const blocks = response.content ?? [];
1483
+ const resultBlocks = blocks.filter(isResultBlock);
1484
+ if (resultBlocks.length === 0) throw new DshwsError(codes$3.badResponse, "DeepSeek returned no web_search_tool_result blocks; the request may not have triggered native web search");
1485
+ const snippets = citationSnippets(blocks);
1486
+ const seen = /* @__PURE__ */ new Set();
1487
+ const sources = [];
1488
+ for (const block of resultBlocks) for (const item of block.content ?? []) {
1489
+ if (item.type !== "web_search_result" || item.url.length === 0 || seen.has(item.url)) continue;
1490
+ seen.add(item.url);
1491
+ const snippet = snippets.get(item.url);
1492
+ sources.push({
1493
+ url: item.url,
1494
+ ...item.title != null && item.title.length > 0 ? { title: item.title } : {},
1495
+ ...snippet !== void 0 && snippet.length > 0 ? { snippet } : {},
1496
+ ...item.page_age != null && item.page_age.length > 0 ? { publishedAt: item.page_age } : {}
1497
+ });
1498
+ }
1499
+ return {
1500
+ sources,
1501
+ truncated: false
1502
+ };
1503
+ }
1504
+ /** The DeepSeek-backed chain member; redirects fail as a request failure. */
1505
+ var DeepSeekSearchProvider = class {
1506
+ options;
1507
+ id = DEEPSEEK_MEMBER_ID;
1508
+ constructor(options) {
1509
+ this.options = options;
1510
+ }
1511
+ /** Cheap local config check (no network, no key dimension — the gate owns that). */
1512
+ available() {
1513
+ return URL.canParse(this.options.baseURL) && isPositiveInteger(this.options.maxTokens);
1514
+ }
1515
+ async search(request, signal) {
1516
+ throwIfMemberAborted(codes$3, "DeepSeek", signal);
1517
+ const apiKey = await this.#apiKey(signal);
1518
+ throwIfMemberAborted(codes$3, "DeepSeek", signal);
1519
+ const endpoint = `${this.options.baseURL}/messages`;
1520
+ const body = {
1521
+ model: this.options.model,
1522
+ max_tokens: this.options.maxTokens,
1523
+ messages: [{
1524
+ role: "user",
1525
+ content: [{
1526
+ type: "text",
1527
+ text: `Perform a web search for the query: ${request.query}`
1528
+ }]
1529
+ }],
1530
+ tools: [{
1531
+ type: "web_search_20250305",
1532
+ name: "web_search",
1533
+ max_uses: this.options.maxUses
1534
+ }]
1535
+ };
1536
+ let response;
1537
+ try {
1538
+ response = await fetch(endpoint, {
1539
+ method: "POST",
1540
+ redirect: "error",
1541
+ headers: {
1542
+ "x-api-key": apiKey,
1543
+ "authorization": `Bearer ${apiKey}`,
1544
+ "anthropic-version": DEEPSEEK_API_VERSION,
1545
+ "content-type": "application/json",
1546
+ "accept": "application/json",
1547
+ "user-agent": USER_AGENT$3
1548
+ },
1549
+ body: JSON.stringify(body),
1550
+ ...signal !== void 0 ? { signal } : {}
1551
+ });
1552
+ } catch (error) {
1553
+ throw memberFetchFailure(codes$3, "DeepSeek", error, signal);
1554
+ }
1555
+ if (!response.ok) {
1556
+ const status = response.status;
1557
+ let message = `DeepSeek API error (HTTP ${status})`;
1558
+ try {
1559
+ const detail = unfoldHttpErrorDetail(await response.json());
1560
+ if (detail !== void 0 && detail.length > 0) message += `: ${detail}`;
1561
+ } catch (error) {
1562
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$3, "DeepSeek", signal, error);
1563
+ }
1564
+ throw new DshwsError(codes$3.httpError, message, { httpStatus: status });
1565
+ }
1566
+ try {
1567
+ return mapDeepSeekResponse(await response.json());
1568
+ } catch (error) {
1569
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$3, "DeepSeek", signal, error);
1570
+ if (error instanceof DshwsError) throw error;
1571
+ throw memberBadResponse(codes$3, "DeepSeek", error);
1572
+ }
1573
+ }
1574
+ /** Resolve one operation's key without retaining it; a missing key is a loud member error. */
1575
+ #apiKey(signal) {
1576
+ return resolveMemberApiKey({
1577
+ codes: codes$3,
1578
+ label: "DeepSeek",
1579
+ apiKeyRef: this.options.apiKeyRef,
1580
+ resolveApiKey: this.options.resolveApiKey,
1581
+ signal
1582
+ });
1583
+ }
1584
+ };
1585
+ //#endregion
1586
+ //#region src/providers/exa.ts
1587
+ /** Stable id this member registers under (chain + direct pin, `dshws-` prefixed). */
1588
+ const EXA_MEMBER_ID = "dshws-exa";
1589
+ /** Text-fallback excerpt budget per result in characters (S17 P1; official range 1-10000). */
1590
+ const EXA_TEXT_FALLBACK_MAX_CHARACTERS = 1e3;
1591
+ const codes$2 = MEMBER_ERROR_CODES.exa;
1592
+ /** Attribution header sent on every request; bump with the package version. */
1593
+ const USER_AGENT$2 = "dsh-websearch/0.1.0";
1594
+ /**
1595
+ * Normalize a stored publication-date floor to the ISO date-time form the API
1596
+ * expects: a date-only `YYYY-MM-DD` value (the GUI date input's shape) gains
1597
+ * a midnight-UTC time; a full date-time string passes through.
1598
+ */
1599
+ function normalizeStartPublishedDate(value) {
1600
+ return /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value;
1601
+ }
1602
+ /**
1603
+ * Explicit defaulting at the owning boundary (explicit > implicit): the base
1604
+ * URL default lands here, config passthrough stays untouched.
1605
+ */
1606
+ function resolveExaMemberOptions(config, resolveApiKey, fanout) {
1607
+ return {
1608
+ apiKeyRef: config.apiKeyEnv,
1609
+ resolveApiKey,
1610
+ baseURL: config.baseURL ?? "https://api.exa.ai",
1611
+ numResults: config.numResults,
1612
+ type: config.type ?? "auto",
1613
+ textFallback: config.textFallback ?? true,
1614
+ startPublishedDate: config.startPublishedDate !== void 0 ? normalizeStartPublishedDate(config.startPublishedDate) : void 0,
1615
+ userLocation: fanout?.country,
1616
+ includeDomains: fanout?.includeDomains?.length ? fanout.includeDomains : void 0,
1617
+ excludeDomains: fanout?.excludeDomains?.length ? fanout.excludeDomains : void 0,
1618
+ category: config.category || void 0,
1619
+ maxAgeHours: config.maxAgeHours,
1620
+ endPublishedDate: config.endPublishedDate !== void 0 ? normalizeStartPublishedDate(config.endPublishedDate) : void 0,
1621
+ textVerbosity: config.textVerbosity,
1622
+ includeSections: config.includeSections !== void 0 ? config.includeSections.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0) : void 0,
1623
+ excludeSections: config.excludeSections !== void 0 ? config.excludeSections.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0) : void 0
1624
+ };
1625
+ }
1626
+ /**
1627
+ * Map one Exa result to a normalized source, or `undefined` when it carries
1628
+ * no portable excerpt: the first non-blank highlight becomes `snippet`, with
1629
+ * the full-text `text` as the fallback (S17 P1); an entry with neither is
1630
+ * dropped.
1631
+ */
1632
+ function mapExaResult(result) {
1633
+ const snippet = result.highlights?.find((h) => h.trim().length > 0) ?? (result.text !== void 0 && result.text.trim().length > 0 ? result.text : void 0);
1634
+ if (snippet === void 0 || result.url === void 0 || result.url.length === 0) return void 0;
1635
+ return {
1636
+ url: result.url,
1637
+ ...result.title != null && result.title.length > 0 ? { title: result.title } : {},
1638
+ snippet,
1639
+ ...result.publishedDate != null && result.publishedDate.length > 0 ? { publishedAt: result.publishedDate } : {}
1640
+ };
1641
+ }
1642
+ /**
1643
+ * Map an Exa response envelope to a normalized search result: snippet-less
1644
+ * entries are dropped ({@link mapExaResult}), no generated answer, no
1645
+ * provider-side truncation (the web service owns that).
1646
+ */
1647
+ function mapExaResponse(response) {
1648
+ return {
1649
+ sources: (response.results ?? []).map(mapExaResult).filter((source) => source !== void 0),
1650
+ truncated: false
1651
+ };
1652
+ }
1653
+ /** The Exa-backed chain member; redirects fail as a request failure. */
1654
+ var ExaSearchProvider = class {
1655
+ options;
1656
+ id = EXA_MEMBER_ID;
1657
+ constructor(options) {
1658
+ this.options = options;
1659
+ }
1660
+ /** Cheap local config check (no network, no key dimension — the gate owns that). */
1661
+ available() {
1662
+ return URL.canParse(this.options.baseURL) && (this.options.numResults === void 0 || isPositiveInteger(this.options.numResults));
1663
+ }
1664
+ async search(request, signal) {
1665
+ throwIfMemberAborted(codes$2, "Exa", signal);
1666
+ const apiKey = await this.#apiKey(signal);
1667
+ throwIfMemberAborted(codes$2, "Exa", signal);
1668
+ const numResults = request.maxResults ?? this.options.numResults;
1669
+ let response;
1670
+ const dateFloor = this.options.category === "company" || this.options.category === "people" ? void 0 : this.options.startPublishedDate;
1671
+ const excludeDomains = this.options.category === "company" || this.options.category === "people" ? void 0 : this.options.excludeDomains;
1672
+ try {
1673
+ response = await fetch(`${this.options.baseURL}/search`, {
1674
+ method: "POST",
1675
+ redirect: "error",
1676
+ headers: {
1677
+ "authorization": `Bearer ${apiKey}`,
1678
+ "content-type": "application/json",
1679
+ "accept": "application/json",
1680
+ "user-agent": USER_AGENT$2
1681
+ },
1682
+ body: JSON.stringify({
1683
+ query: request.query,
1684
+ type: this.options.type,
1685
+ contents: {
1686
+ ...this.options.maxAgeHours !== void 0 ? { maxAgeHours: this.options.maxAgeHours } : {},
1687
+ highlights: {
1688
+ query: request.query,
1689
+ maxCharacters: 400
1690
+ },
1691
+ ...this.options.textFallback || this.options.textVerbosity !== void 0 || this.options.includeSections !== void 0 || this.options.excludeSections !== void 0 ? { text: {
1692
+ ...this.options.textFallback ? { maxCharacters: EXA_TEXT_FALLBACK_MAX_CHARACTERS } : {},
1693
+ ...this.options.textVerbosity !== void 0 ? { verbosity: this.options.textVerbosity } : {},
1694
+ ...this.options.includeSections !== void 0 ? { includeSections: [...this.options.includeSections] } : {},
1695
+ ...this.options.excludeSections !== void 0 ? { excludeSections: [...this.options.excludeSections] } : {}
1696
+ } } : {}
1697
+ },
1698
+ ...numResults !== void 0 ? { numResults } : {},
1699
+ ...this.options.category !== void 0 ? { category: this.options.category } : {},
1700
+ ...dateFloor !== void 0 ? { startPublishedDate: dateFloor } : {},
1701
+ ...this.options.endPublishedDate !== void 0 ? { endPublishedDate: this.options.endPublishedDate } : {},
1702
+ ...this.options.userLocation !== void 0 ? { userLocation: this.options.userLocation } : {},
1703
+ ...this.options.includeDomains !== void 0 ? { includeDomains: [...this.options.includeDomains] } : {},
1704
+ ...excludeDomains !== void 0 ? { excludeDomains: [...excludeDomains] } : {}
1705
+ }),
1706
+ ...signal !== void 0 ? { signal } : {}
1707
+ });
1708
+ } catch (error) {
1709
+ throw memberFetchFailure(codes$2, "Exa", error, signal);
1710
+ }
1711
+ if (!response.ok) {
1712
+ const status = response.status;
1713
+ let message = `Exa API error (HTTP ${status})`;
1714
+ try {
1715
+ const detail = unfoldHttpErrorDetail(await response.json());
1716
+ if (detail !== void 0 && detail.length > 0) message += `: ${detail}`;
1717
+ } catch (error) {
1718
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$2, "Exa", signal, error);
1719
+ }
1720
+ throw new DshwsError(codes$2.httpError, message, { httpStatus: status });
1721
+ }
1722
+ try {
1723
+ return mapExaResponse(await response.json());
1724
+ } catch (error) {
1725
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$2, "Exa", signal, error);
1726
+ throw memberBadResponse(codes$2, "Exa", error);
1727
+ }
1728
+ }
1729
+ /** Resolve one operation's key without retaining it; a missing key is a loud member error. */
1730
+ #apiKey(signal) {
1731
+ return resolveMemberApiKey({
1732
+ codes: codes$2,
1733
+ label: "Exa",
1734
+ apiKeyRef: this.options.apiKeyRef,
1735
+ resolveApiKey: this.options.resolveApiKey,
1736
+ signal
1737
+ });
1738
+ }
1739
+ };
1740
+ //#endregion
1741
+ //#region src/providers/firecrawl.ts
1742
+ /** Search-face timeout cap: the chain budget is 30s per member, so the server stops at 20s (S20 P2). */
1743
+ const FIRECRAWL_SEARCH_TIMEOUT_MS = 2e4;
1744
+ /** Stable id this member registers under (search + fetch, `dshws-` prefixed). */
1745
+ const FIRECRAWL_MEMBER_ID = "dshws-firecrawl";
1746
+ const codes$1 = MEMBER_ERROR_CODES.firecrawl;
1747
+ /** Attribution header sent on every request; bump with the package version. */
1748
+ const USER_AGENT$1 = "dsh-websearch/0.1.0";
1749
+ /**
1750
+ * Firecrawl accepts bare hostnames only (no protocol/path/wildcard): URL-like
1751
+ * entries collapse to their host; any wildcard entry makes the whole list an
1752
+ * Exa-only capability, so this member's domain fan-out is skipped entirely
1753
+ * (sending it would 400 — the same defensive-skip shape as the Exa category
1754
+ * guard). Evaluated once per options resolution.
1755
+ */
1756
+ function normalizeFirecrawlDomains(fanout) {
1757
+ const raw = fanout?.includeDomains?.length ? fanout.includeDomains : fanout?.excludeDomains?.length ? fanout.excludeDomains : void 0;
1758
+ if (raw === void 0) return {};
1759
+ if (raw.some((entry) => entry.includes("*"))) return {};
1760
+ const normalized = raw.map((entry) => {
1761
+ if (!entry.includes("://") && !entry.includes("/")) return entry;
1762
+ try {
1763
+ return new URL(entry.includes("://") ? entry : `https://${entry}`).host;
1764
+ } catch {
1765
+ return entry;
1766
+ }
1767
+ });
1768
+ return fanout?.includeDomains?.length ? { includeDomains: normalized } : { excludeDomains: normalized };
1769
+ }
1770
+ /**
1771
+ * Explicit defaulting at the owning boundary (explicit > implicit): the base
1772
+ * URL default lands here, config passthrough stays untouched.
1773
+ */
1774
+ function resolveFirecrawlMemberOptions(config, resolveApiKey, fanout) {
1775
+ return {
1776
+ apiKeyRef: config.apiKeyEnv,
1777
+ resolveApiKey,
1778
+ baseURL: config.baseURL ?? "https://api.firecrawl.dev",
1779
+ tbs: config.tbs,
1780
+ safe: config.safe,
1781
+ location: config.location,
1782
+ country: fanout?.country,
1783
+ ...normalizeFirecrawlDomains(fanout),
1784
+ sources: config.sources || void 0,
1785
+ categories: config.categories || void 0
1786
+ };
1787
+ }
1788
+ /**
1789
+ * Map a v2 search response to a normalized search result: `data.web[]` →
1790
+ * sources with `description` as the snippet (entries without a `url` are
1791
+ * dropped); no generated answer, no provider-side truncation. A 2xx envelope
1792
+ * carrying `success: false` is outside the documented wire shape and reads as
1793
+ * a bad response.
1794
+ */
1795
+ function mapFirecrawlSearchResponse(response) {
1796
+ if (response.success === false) throw new DshwsError(codes$1.badResponse, "Firecrawl search reported success:false on a 2xx response");
1797
+ const webSources = (response.data?.web ?? []).map((item) => {
1798
+ if (item.url === void 0 || item.url.length === 0) return void 0;
1799
+ return {
1800
+ url: item.url,
1801
+ ...item.title != null && item.title.length > 0 ? { title: item.title } : {},
1802
+ ...item.description != null && item.description.length > 0 ? { snippet: item.description } : {}
1803
+ };
1804
+ }).filter((source) => source !== void 0);
1805
+ const newsSources = (response.data?.news ?? []).map((item) => {
1806
+ if (item.url === void 0 || item.url.length === 0) return void 0;
1807
+ return {
1808
+ url: item.url,
1809
+ ...item.title != null && item.title.length > 0 ? { title: item.title } : {},
1810
+ ...item.snippet != null && item.snippet.length > 0 ? { snippet: item.snippet } : {},
1811
+ ...item.date != null && item.date.length > 0 ? { publishedAt: item.date } : {}
1812
+ };
1813
+ }).filter((source) => source !== void 0);
1814
+ return {
1815
+ sources: [...webSources, ...newsSources],
1816
+ truncated: false
1817
+ };
1818
+ }
1819
+ /**
1820
+ * Map a v2 scrape response to a normalized fetch result: markdown becomes the
1821
+ * `text` body kind, the page's own status becomes the result's status code,
1822
+ * and the final URL falls back through `metadata.url` → `metadata.sourceURL` →
1823
+ * the request URL. Missing markdown is a bad response — `formats` explicitly
1824
+ * requested it.
1825
+ */
1826
+ function mapFirecrawlScrapeResponse(requestUrl, response) {
1827
+ if (response.success === false) throw new DshwsError(codes$1.badResponse, "Firecrawl scrape reported success:false on a 2xx response");
1828
+ const markdown = response.data?.markdown;
1829
+ if (markdown === void 0) throw new DshwsError(codes$1.badResponse, "Firecrawl scrape returned no markdown though formats requested it");
1830
+ const metadata = response.data?.metadata;
1831
+ return {
1832
+ url: metadata?.url ?? metadata?.sourceURL ?? requestUrl,
1833
+ statusCode: metadata?.statusCode ?? 200,
1834
+ body: {
1835
+ kind: "text",
1836
+ content: markdown
1837
+ },
1838
+ truncated: false
1839
+ };
1840
+ }
1841
+ /**
1842
+ * The Firecrawl-backed chain member on both capability faces: one class, one
1843
+ * credential, one gate — registered with the search AND fetch registries.
1844
+ */
1845
+ var FirecrawlProvider = class {
1846
+ options;
1847
+ id = FIRECRAWL_MEMBER_ID;
1848
+ constructor(options) {
1849
+ this.options = options;
1850
+ }
1851
+ /** Cheap local config check (no network, no key dimension — the gate owns that). */
1852
+ available() {
1853
+ return URL.canParse(this.options.baseURL);
1854
+ }
1855
+ async search(request, signal) {
1856
+ throwIfMemberAborted(codes$1, "Firecrawl", signal);
1857
+ const apiKey = await this.#apiKey(signal);
1858
+ throwIfMemberAborted(codes$1, "Firecrawl", signal);
1859
+ const limit = request.maxResults;
1860
+ let response;
1861
+ try {
1862
+ response = await fetch(`${this.options.baseURL}/v2/search`, {
1863
+ method: "POST",
1864
+ redirect: "error",
1865
+ headers: this.#headers(apiKey),
1866
+ body: JSON.stringify({
1867
+ query: request.query,
1868
+ ...limit !== void 0 ? { limit } : {},
1869
+ timeout: FIRECRAWL_SEARCH_TIMEOUT_MS,
1870
+ ...this.options.sources !== void 0 ? { sources: this.options.sources === "news" ? [{ type: "news" }] : [{ type: "web" }, { type: "news" }] } : {},
1871
+ ...this.options.categories !== void 0 ? { categories: [{ type: this.options.categories }] } : {},
1872
+ ...this.options.tbs !== void 0 ? { tbs: this.options.tbs } : {},
1873
+ ...this.options.safe === true ? { safe: true } : {},
1874
+ ...this.options.location !== void 0 ? { location: this.options.location } : {},
1875
+ ...this.options.country !== void 0 ? { country: this.options.country } : {},
1876
+ ...this.options.includeDomains !== void 0 ? { includeDomains: [...this.options.includeDomains] } : {},
1877
+ ...this.options.excludeDomains !== void 0 ? { excludeDomains: [...this.options.excludeDomains] } : {}
1878
+ }),
1879
+ ...signal !== void 0 ? { signal } : {}
1880
+ });
1881
+ } catch (error) {
1882
+ throw memberFetchFailure(codes$1, "Firecrawl", error, signal);
1883
+ }
1884
+ return mapFirecrawlSearchResponse(await this.#parse(response, signal, "Firecrawl search"));
1885
+ }
1886
+ async fetch(request, signal) {
1887
+ throwIfMemberAborted(codes$1, "Firecrawl", signal);
1888
+ const apiKey = await this.#apiKey(signal);
1889
+ throwIfMemberAborted(codes$1, "Firecrawl", signal);
1890
+ let response;
1891
+ try {
1892
+ response = await fetch(`${this.options.baseURL}/v2/scrape`, {
1893
+ method: "POST",
1894
+ redirect: "error",
1895
+ headers: this.#headers(apiKey),
1896
+ body: JSON.stringify({
1897
+ url: request.url,
1898
+ formats: ["markdown"],
1899
+ timeout: 2e4
1900
+ }),
1901
+ ...signal !== void 0 ? { signal } : {}
1902
+ });
1903
+ } catch (error) {
1904
+ throw memberFetchFailure(codes$1, "Firecrawl", error, signal);
1905
+ }
1906
+ const payload = await this.#parse(response, signal, "Firecrawl scrape");
1907
+ return mapFirecrawlScrapeResponse(request.url, payload);
1908
+ }
1909
+ /** Resolve one operation's key without retaining it; a missing key is a loud member error. */
1910
+ #apiKey(signal) {
1911
+ return resolveMemberApiKey({
1912
+ codes: codes$1,
1913
+ label: "Firecrawl",
1914
+ apiKeyRef: this.options.apiKeyRef,
1915
+ resolveApiKey: this.options.resolveApiKey,
1916
+ signal
1917
+ });
1918
+ }
1919
+ #headers(apiKey) {
1920
+ return {
1921
+ "authorization": `Bearer ${apiKey}`,
1922
+ "content-type": "application/json",
1923
+ "accept": "application/json",
1924
+ "user-agent": USER_AGENT$1
1925
+ };
1926
+ }
1927
+ /**
1928
+ * Shared response pipeline for both faces: non-2xx → HTTP error (tolerant
1929
+ * body unfold), abort mid-body → aborted, bad JSON → bad response.
1930
+ */
1931
+ async #parse(response, signal, label) {
1932
+ if (!response.ok) {
1933
+ const status = response.status;
1934
+ let message = `Firecrawl API error (HTTP ${status})`;
1935
+ try {
1936
+ const detail = unfoldHttpErrorDetail(await response.json());
1937
+ if (detail !== void 0 && detail.length > 0) message += `: ${detail}`;
1938
+ } catch (error) {
1939
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$1, label, signal, error);
1940
+ }
1941
+ throw new DshwsError(codes$1.httpError, message, { httpStatus: status });
1942
+ }
1943
+ try {
1944
+ return await response.json();
1945
+ } catch (error) {
1946
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes$1, label, signal, error);
1947
+ throw memberBadResponse(codes$1, label, error);
1948
+ }
1949
+ }
1950
+ };
1951
+ //#endregion
1952
+ //#region src/providers/tavily.ts
1953
+ /** Stable id this member registers under (chain + direct pin, `dshws-` prefixed). */
1954
+ const TAVILY_MEMBER_ID = "dshws-tavily";
1955
+ const codes = MEMBER_ERROR_CODES.tavily;
1956
+ /** Attribution header sent on every request; bump with the package version. */
1957
+ const USER_AGENT = "dsh-websearch/0.1.0";
1958
+ /**
1959
+ * Explicit defaulting at the owning boundary (explicit > implicit): the base
1960
+ * URL default lands here, config passthrough stays untouched. The geo entry
1961
+ * contributes only the language — Tavily's `country` expects country-name
1962
+ * strings (ISO-code compatibility unverified), so v1 does not fan the region
1963
+ * out here (ADR-0015).
1964
+ */
1965
+ function resolveTavilyMemberOptions(config, resolveApiKey, fanout) {
1966
+ return {
1967
+ apiKeyRef: config.apiKeyEnv,
1968
+ resolveApiKey,
1969
+ baseURL: config.baseURL ?? "https://api.tavily.com",
1970
+ maxResults: config.maxResults,
1971
+ topic: config.topic,
1972
+ timeRange: config.timeRange,
1973
+ searchDepth: config.searchDepth,
1974
+ includeAnswer: config.includeAnswer ?? "basic",
1975
+ language: fanout?.language,
1976
+ includeDomains: fanout?.includeDomains?.length ? fanout.includeDomains : void 0,
1977
+ excludeDomains: fanout?.excludeDomains?.length ? fanout.excludeDomains : void 0,
1978
+ domainsHaveWildcard: (fanout?.includeDomains ?? []).some((entry) => entry.includes("*")) || (fanout?.excludeDomains ?? []).some((entry) => entry.includes("*")),
1979
+ chunksPerSource: config.chunksPerSource,
1980
+ filterByLanguage: config.filterByLanguage,
1981
+ includeDomainsMode: config.includeDomainsMode,
1982
+ startDate: config.startDate?.trim().length ? config.startDate.trim() : void 0,
1983
+ endDate: config.endDate?.trim().length ? config.endDate.trim() : void 0,
1984
+ exactMatch: config.exactMatch
1985
+ };
1986
+ }
1987
+ /**
1988
+ * Map one Tavily result to a normalized source. `content` is the excerpt and
1989
+ * maps to `snippet`; blank optional fields are omitted rather than emitted
1990
+ * as empty. Entries without a `url` are dropped — a source always has a URL.
1991
+ */
1992
+ function mapTavilyResult(item) {
1993
+ if (item.url === void 0 || item.url.length === 0) return void 0;
1994
+ return {
1995
+ url: item.url,
1996
+ ...item.title != null && item.title.length > 0 ? { title: item.title } : {},
1997
+ ...item.content != null && item.content.trim().length > 0 ? { snippet: item.content } : {},
1998
+ ...item.published_date != null && item.published_date.length > 0 ? { publishedAt: item.published_date } : {}
1999
+ };
2000
+ }
2001
+ /**
2002
+ * Map a search response envelope to a normalized result: the generated
2003
+ * `answer` (requested by default, S17 D4) becomes `content` — blank stays
2004
+ * omitted; no provider-side truncation (the web service owns that).
2005
+ */
2006
+ function mapTavilyResponse(response) {
2007
+ const sources = (response.results ?? []).map(mapTavilyResult).filter((source) => source !== void 0);
2008
+ return {
2009
+ ...response.answer != null && response.answer.trim().length > 0 ? { content: response.answer } : {},
2010
+ sources,
2011
+ truncated: false
2012
+ };
2013
+ }
2014
+ /**
2015
+ * Map an /extract response to a fetch result: the entry's raw_content
2016
+ * (markdown by request) becomes the text body; a failed_results entry is a
2017
+ * member error so the chain degrades instead of faking a success.
2018
+ */
2019
+ function mapTavilyExtractResponse(requestUrl, response) {
2020
+ const failed = response.failed_results?.find((entry) => entry.url === requestUrl) ?? response.failed_results?.[0];
2021
+ if (failed !== void 0) throw new DshwsError(codes.httpError, `Tavily extract failed for ${failed.url ?? requestUrl}${failed.error !== void 0 ? `: ${failed.error}` : ""}`);
2022
+ const entry = response.results?.find((item) => item.url === requestUrl) ?? response.results?.[0];
2023
+ if (entry?.raw_content === void 0 || entry.raw_content.length === 0) throw new DshwsError(codes.badResponse, "Tavily extract returned no content though the URL was not in failed_results");
2024
+ return {
2025
+ url: entry.url ?? requestUrl,
2026
+ statusCode: 200,
2027
+ body: {
2028
+ kind: "text",
2029
+ content: entry.raw_content
2030
+ },
2031
+ truncated: false
2032
+ };
2033
+ }
2034
+ /**
2035
+ * The Tavily-backed chain member on both capability faces: search (`/search`)
2036
+ * and fetch (`/extract`, S21 — markdown by request, single URL per the seam's
2037
+ * one-URL contract). Redirects fail as a request failure.
2038
+ */
2039
+ var TavilySearchProvider = class {
2040
+ options;
2041
+ id = TAVILY_MEMBER_ID;
2042
+ constructor(options) {
2043
+ this.options = options;
2044
+ }
2045
+ /** Cheap local config check (no network, no key dimension — the gate owns that). */
2046
+ available() {
2047
+ return URL.canParse(this.options.baseURL) && (this.options.maxResults === void 0 || isPositiveInteger(this.options.maxResults));
2048
+ }
2049
+ async search(request, signal) {
2050
+ throwIfMemberAborted(codes, "Tavily", signal);
2051
+ const apiKey = await this.#apiKey(signal);
2052
+ throwIfMemberAborted(codes, "Tavily", signal);
2053
+ const maxResults = request.maxResults ?? this.options.maxResults;
2054
+ let response;
2055
+ try {
2056
+ response = await fetch(`${this.options.baseURL}/search`, {
2057
+ method: "POST",
2058
+ redirect: "error",
2059
+ headers: {
2060
+ "authorization": `Bearer ${apiKey}`,
2061
+ "content-type": "application/json",
2062
+ "accept": "application/json",
2063
+ "user-agent": USER_AGENT
2064
+ },
2065
+ body: JSON.stringify({
2066
+ query: request.query,
2067
+ ...maxResults !== void 0 ? { max_results: maxResults } : {},
2068
+ ...this.options.topic !== void 0 ? { topic: this.options.topic } : {},
2069
+ ...this.options.timeRange !== void 0 ? { time_range: this.options.timeRange } : {},
2070
+ ...this.options.searchDepth !== void 0 ? { search_depth: this.options.searchDepth } : {},
2071
+ include_answer: this.options.includeAnswer,
2072
+ ...this.options.language !== void 0 ? { language: this.options.language } : {},
2073
+ ...this.options.includeDomains !== void 0 && !this.options.domainsHaveWildcard ? { include_domains: [...this.options.includeDomains] } : {},
2074
+ ...this.options.excludeDomains !== void 0 && !this.options.domainsHaveWildcard ? { exclude_domains: [...this.options.excludeDomains] } : {},
2075
+ ...this.options.chunksPerSource !== void 0 && this.options.searchDepth !== "ultra-fast" ? { chunks_per_source: this.options.chunksPerSource } : {},
2076
+ ...this.options.filterByLanguage === true && this.options.language !== void 0 ? { filter_by_language: true } : {},
2077
+ ...this.options.includeDomainsMode !== void 0 && this.options.includeDomains !== void 0 ? { include_domains_mode: this.options.includeDomainsMode } : {},
2078
+ ...this.options.startDate !== void 0 ? { start_date: this.options.startDate } : {},
2079
+ ...this.options.endDate !== void 0 ? { end_date: this.options.endDate } : {},
2080
+ ...this.options.exactMatch === true ? { exact_match: true } : {}
2081
+ }),
2082
+ ...signal !== void 0 ? { signal } : {}
2083
+ });
2084
+ } catch (error) {
2085
+ throw memberFetchFailure(codes, "Tavily", error, signal);
2086
+ }
2087
+ if (!response.ok) {
2088
+ const status = response.status;
2089
+ let message = `Tavily API error (HTTP ${status})`;
2090
+ try {
2091
+ const detail = unfoldHttpErrorDetail(await response.json());
2092
+ if (detail !== void 0 && detail.length > 0) message += `: ${detail}`;
2093
+ } catch (error) {
2094
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes, "Tavily", signal, error);
2095
+ }
2096
+ throw new DshwsError(codes.httpError, message, { httpStatus: status });
2097
+ }
2098
+ try {
2099
+ return mapTavilyResponse(await response.json());
2100
+ } catch (error) {
2101
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes, "Tavily", signal, error);
2102
+ throw memberBadResponse(codes, "Tavily", error);
2103
+ }
2104
+ }
2105
+ /**
2106
+ * The extract face (S21): one URL in, markdown out. Billing is per success
2107
+ * (1 credit / 5 URLs basic); the chain's per-member budget governs — no
2108
+ * extra timeout field is sent (the API default 10s sits well inside it).
2109
+ */
2110
+ async fetch(request, signal) {
2111
+ throwIfMemberAborted(codes, "Tavily", signal);
2112
+ const apiKey = await this.#apiKey(signal);
2113
+ throwIfMemberAborted(codes, "Tavily", signal);
2114
+ let response;
2115
+ try {
2116
+ response = await fetch(`${this.options.baseURL}/extract`, {
2117
+ method: "POST",
2118
+ redirect: "error",
2119
+ headers: {
2120
+ "authorization": `Bearer ${apiKey}`,
2121
+ "content-type": "application/json",
2122
+ "accept": "application/json",
2123
+ "user-agent": USER_AGENT
2124
+ },
2125
+ body: JSON.stringify({
2126
+ urls: [request.url],
2127
+ format: "markdown"
2128
+ }),
2129
+ ...signal !== void 0 ? { signal } : {}
2130
+ });
2131
+ } catch (error) {
2132
+ throw memberFetchFailure(codes, "Tavily", error, signal);
2133
+ }
2134
+ if (!response.ok) {
2135
+ const status = response.status;
2136
+ let message = `Tavily API error (HTTP ${status})`;
2137
+ try {
2138
+ const detail = unfoldHttpErrorDetail(await response.json());
2139
+ if (detail !== void 0 && detail.length > 0) message += `: ${detail}`;
2140
+ } catch (error) {
2141
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes, "Tavily", signal, error);
2142
+ }
2143
+ throw new DshwsError(codes.httpError, message, { httpStatus: status });
2144
+ }
2145
+ try {
2146
+ const payload = await response.json();
2147
+ return mapTavilyExtractResponse(request.url, payload);
2148
+ } catch (error) {
2149
+ if (error instanceof DshwsError) throw error;
2150
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes, "Tavily", signal, error);
2151
+ throw memberBadResponse(codes, "Tavily", error);
2152
+ }
2153
+ }
2154
+ /** Resolve one operation's key without retaining it; a missing key is a loud member error. */
2155
+ #apiKey(signal) {
2156
+ return resolveMemberApiKey({
2157
+ codes,
2158
+ label: "Tavily",
2159
+ apiKeyRef: this.options.apiKeyRef,
2160
+ resolveApiKey: this.options.resolveApiKey,
2161
+ signal
2162
+ });
2163
+ }
2164
+ };
2165
+ //#endregion
2166
+ //#region src/settings.ts
2167
+ /** The plugin's settings namespace (lowercase kebab, seam grammar). */
2168
+ const SETTINGS_NAMESPACE = "dsh-websearch";
2169
+ /**
2170
+ * One hot state holder. `setSource` swaps the authoritative source and
2171
+ * recomputes (the service's attach/detach hook); `refresh` recomputes from
2172
+ * the current source (the committed-change hook, whose source thunk re-reads
2173
+ * the section). Every recompute runs `resolveConfig`, so settings-sourced
2174
+ * sections get the same explicit defaulting as cordis.yml config.
2175
+ */
2176
+ var LiveResolvedConfig = class {
2177
+ #source;
2178
+ #current;
2179
+ #volatile = false;
2180
+ constructor(config) {
2181
+ this.#source = () => config;
2182
+ this.#current = resolveConfig(config);
2183
+ }
2184
+ /** The currently authoritative resolved state (chain getters read per call). */
2185
+ current() {
2186
+ if (this.#volatile) this.#recompute();
2187
+ return this.#current;
2188
+ }
2189
+ /** Swap the authoritative source and recompute — the `setSource` hook. */
2190
+ setSource(source) {
2191
+ this.#source = source;
2192
+ this.#volatile = false;
2193
+ this.#recompute();
2194
+ }
2195
+ /**
2196
+ * Adopt read-time evaluation — the 0.1.7+ volatile hook: the source thunk
2197
+ * unwraps live handles on every call, so `current()` stays fresh without
2198
+ * commit events.
2199
+ */
2200
+ setVolatileSource(source) {
2201
+ this.#source = source;
2202
+ this.#volatile = true;
2203
+ this.#recompute();
2204
+ }
2205
+ /** Recompute from the current source — the `onChange` hook. */
2206
+ refresh() {
2207
+ this.#recompute();
2208
+ }
2209
+ #recompute() {
2210
+ this.#current = resolveConfig(this.#source());
2211
+ }
2212
+ };
2213
+ /**
2214
+ * Attach the plugin's settings section on the host's settings model
2215
+ * (ADR-0021 dual path):
2216
+ *
2217
+ * - 0.1.5/0.1.6 — the service exposes `installSection`; the hooks hand the
2218
+ * live config the authoritative source and recompute on every committed
2219
+ * change, and the custom validators (ADR-0018 domain exclusivity, Firecrawl
2220
+ * tbs, Exa section filter) reject invalid writes before persist.
2221
+ * - 0.1.7+ — no `installSection`; the volatile-marked Config registers the
2222
+ * namespace as a live form by itself. The live config adopts read-time
2223
+ * evaluation (handles unwrap the live configuration per read), and the
2224
+ * commit-side hook rides `settings/document-updated` for this namespace —
2225
+ * schema-level validation is the host's, so the plugin's custom validators
2226
+ * degrade to resolve-time loud failures on this path.
2227
+ *
2228
+ * Without a settings service at all, a no-op: the entry config stays
2229
+ * authoritative and the plugin must not fail to load. Disposal is bound to
2230
+ * the calling fiber by the surrounding effects.
2231
+ */
2232
+ function attachSettingsSection(ctx, entry, live, commitHooks) {
2233
+ ctx.inject(["settings"], (settingsCtx) => {
2234
+ const legacy = settingsCtx.settings.installSection;
2235
+ if (typeof legacy === "function") {
2236
+ legacy.call(settingsCtx.settings, ctx, SETTINGS_NAMESPACE, ConfigLegacy, materializeConfig(entry), {
2237
+ validate: (value) => {
2238
+ const section = value;
2239
+ validateUnifiedDomainRule(section);
2240
+ validateExaSectionFilterRule(section);
2241
+ validateFirecrawlTbsRule(section);
2242
+ },
2243
+ setSource: (source) => {
2244
+ live.setSource(source);
2245
+ },
2246
+ onChange: () => {
2247
+ live.refresh();
2248
+ commitHooks?.onCommitted?.();
2249
+ }
2250
+ });
2251
+ return;
2252
+ }
2253
+ live.setVolatileSource(() => materializeConfig(entry));
2254
+ ctx.on("settings/document-updated", (ns) => {
2255
+ if (ns === "dsh-websearch") commitHooks?.onCommitted?.();
2256
+ });
2257
+ });
2258
+ }
2259
+ //#endregion
2260
+ //#region src/index.ts
2261
+ /** Cordis plugin name used by loader diagnostics. */
2262
+ const name = "dsh-websearch";
2263
+ /** The seams this plugin binds to: provider registration, per-operation credential resolution, hot settings. */
2264
+ const inject = ["web", "credentials"];
2265
+ /** The five member section keys, iteration order for live-ref whitelisting. */
2266
+ const MEMBER_KEYS = [
2267
+ "tavily",
2268
+ "exa",
2269
+ "firecrawl",
2270
+ "deepseek",
2271
+ "anysearch"
2272
+ ];
2273
+ /**
2274
+ * Plugin entry point: build the priority chains and the five bundled members,
2275
+ * wire the credential gate and the hot settings state, and register
2276
+ * everything with `ctx.web`. Disposal is bound to the calling fiber by the
2277
+ * seam's registration effects (including the gate's event subscription and
2278
+ * the settings section).
2279
+ */
2280
+ /** Defensive: the gate's chain thunk ran before the chain was assigned — cannot happen (registration order), but a loud beat beats a silent undefined. */
2281
+ function throwMissingChain() {
2282
+ throw new Error("dsh-websearch: fetch chain not constructed before first gated call");
2283
+ }
2284
+ function apply(ctx, config) {
2285
+ const entry = materializeConfig(config);
2286
+ const live = new LiveResolvedConfig(entry);
2287
+ const resolved = resolveConfig(entry);
2288
+ /**
2289
+ * Hot-backed member options (S17 D1): every property read re-resolves
2290
+ * through the live config, so a committed settings change reaches the next
2291
+ * search without re-registration — the chain-order getter precedent
2292
+ * (below) applied to the member option objects. `build` may read any slice
2293
+ * of the live snapshot (the member section and, from the S17 unified
2294
+ * language/region entry, root fields as well); it stays a pure resolution,
2295
+ * cheap to re-run per read. Providers hold this object by reference and
2296
+ * read fields per call, so delegation through the proxy is invisible to
2297
+ * them. Limitation (intentional, stage-5 verified): the proxy answers
2298
+ * plain property reads only — `JSON.stringify`, spread, `Object.keys`, and
2299
+ * `in` all silently see an empty object, so never enumerate or serialize
2300
+ * member options; read named fields directly.
2301
+ */
2302
+ const hotMemberOptions = (build) => new Proxy({}, { get: (_target, property, receiver) => Reflect.get(build(), property, receiver) });
2303
+ /** The unified language/region entry (ADR-0015) read live per call, fed to the members whose APIs accept it. */
2304
+ const fanoutOf = () => {
2305
+ const current = live.current();
2306
+ return {
2307
+ country: current.searchCountry,
2308
+ language: current.searchLanguage,
2309
+ includeDomains: current.searchIncludeDomains.length ? current.searchIncludeDomains : void 0,
2310
+ excludeDomains: current.searchExcludeDomains.length ? current.searchExcludeDomains : void 0
2311
+ };
2312
+ };
2313
+ const credentials = ctx.credentials;
2314
+ const fileLog = createChainFileLog(config.chainLogFile !== false);
2315
+ const fetchTakeoverActive = () => live.current().fetchTakeover !== false;
2316
+ let fetchChainInstance;
2317
+ ctx.web.registerFetchProvider(new FetchGateProvider(fetchTakeoverActive, (request, signal) => (fetchChainInstance ?? throwMissingChain()).fetch(request, signal)));
2318
+ ctx.inject(["settings"], (settingsCtx) => {
2319
+ if (((settingsCtx.settings.describe().find((descriptor) => descriptor.ns === "agent-presets")?.value)?.default ?? "standard") === "dshws-search-only") settingsCtx.settings.update("agent-presets", { default: "standard" }).then(() => {
2320
+ clearAllSearchOnlyPresets();
2321
+ }).catch(() => {});
2322
+ else clearAllSearchOnlyPresets();
2323
+ });
2324
+ const log = (message) => {
2325
+ ctx.logger.info(message);
2326
+ fileLog(message);
2327
+ };
2328
+ for (const member of [
2329
+ resolved.tavily,
2330
+ resolved.exa,
2331
+ resolved.firecrawl,
2332
+ resolved.deepseek,
2333
+ resolved.anysearch
2334
+ ]) credentialRef(member.apiKeyEnv);
2335
+ new DshWsKeyCountsRemote(ctx, {
2336
+ allowedRefs: () => new Set(MEMBER_KEYS.map((key) => live.current()[key].apiKeyEnv)),
2337
+ resolve: async (ref) => (await credentials.resolve(credentialRef(ref)))?.value
2338
+ });
2339
+ const gate = new CredentialGate({
2340
+ credentials,
2341
+ subscribe: (handler) => ctx.on("credentials/reference-updated", handler),
2342
+ log
2343
+ });
2344
+ const keyPool = (memberKey, label, codes) => new KeyPool({
2345
+ ref: () => live.current()[memberKey].apiKeyEnv,
2346
+ selection: () => live.current()[memberKey].keySelection ?? "round-robin",
2347
+ isReady: (ref) => gate.isReady(ref),
2348
+ resolve: async (ref) => (await credentials.resolve(credentialRef(ref)))?.value,
2349
+ label,
2350
+ codes
2351
+ });
2352
+ const tracedPool = (memberKey, pool) => ({
2353
+ resolveApiKey: async () => {
2354
+ const key = await pool.resolveApiKey();
2355
+ if (key !== void 0) log(`[dsh-websearch] key draw dshws-${memberKey} …${key.slice(-4)}`);
2356
+ return key;
2357
+ },
2358
+ ready: () => pool.ready(),
2359
+ hasMultiKeyPool: () => pool.hasMultiKeyPool()
2360
+ });
2361
+ const pools = {
2362
+ tavily: keyPool("tavily", "Tavily", MEMBER_ERROR_CODES.tavily),
2363
+ exa: keyPool("exa", "Exa", MEMBER_ERROR_CODES.exa),
2364
+ firecrawl: keyPool("firecrawl", "Firecrawl", MEMBER_ERROR_CODES.firecrawl),
2365
+ deepseek: keyPool("deepseek", "DeepSeek", MEMBER_ERROR_CODES.deepseek),
2366
+ anysearch: keyPool("anysearch", "Anysearch", MEMBER_ERROR_CODES.anysearch)
2367
+ };
2368
+ const traced = {
2369
+ tavily: tracedPool("tavily", pools.tavily),
2370
+ exa: tracedPool("exa", pools.exa),
2371
+ firecrawl: tracedPool("firecrawl", pools.firecrawl),
2372
+ deepseek: tracedPool("deepseek", pools.deepseek),
2373
+ anysearch: tracedPool("anysearch", pools.anysearch)
2374
+ };
2375
+ const gates = (memberKey, pool) => ({
2376
+ enabled: () => memberKey === "deepseek" ? true : live.current()[memberKey].enabled,
2377
+ credentialsReady: () => pool.ready(),
2378
+ multiKeyPool: () => pool.hasMultiKeyPool()
2379
+ });
2380
+ const searchMembers = new MemberRegistry();
2381
+ /**
2382
+ * Ready TOOL members (ADR-0014): enabled five-tool members whose key gate is
2383
+ * armed, read live per call. DeepSeek is excluded BY SPEC — the paid floor's
2384
+ * eligibility rule counts only the tools it would back up, so 'one ready
2385
+ * tool + selected DeepSeek' stays eligible instead of counting itself to 2.
2386
+ */
2387
+ const readyToolMemberCount = () => {
2388
+ const current = live.current();
2389
+ return ORDERABLE_SEARCH_MEMBER_ORDER.filter((id) => {
2390
+ const key = id.replace("dshws-", "");
2391
+ return current[key].enabled && pools[key].ready();
2392
+ }).length;
2393
+ };
2394
+ ctx.web.registerSearchProvider(new ChainSearchProvider({
2395
+ members: searchMembers.toResolver(),
2396
+ get order() {
2397
+ const current = live.current();
2398
+ const chain = [...current.searchChain];
2399
+ if (current.fallbackMember === "dshws-deepseek" && readyToolMemberCount() <= 1 && pools.deepseek.ready()) chain.push(DEEPSEEK_FALLBACK_MEMBER_ID);
2400
+ return chain;
2401
+ },
2402
+ get perMemberTimeoutMs() {
2403
+ return live.current().perMemberTimeoutMs;
2404
+ },
2405
+ log
2406
+ }));
2407
+ const firecrawl = new FirecrawlProvider(hotMemberOptions(() => resolveFirecrawlMemberOptions(live.current().firecrawl, () => traced.firecrawl.resolveApiKey(), fanoutOf())));
2408
+ const anysearch = new AnysearchSearchProvider(hotMemberOptions(() => resolveAnysearchMemberOptions(live.current().anysearch, () => traced.anysearch.resolveApiKey(), fanoutOf())));
2409
+ const tavily = new TavilySearchProvider(hotMemberOptions(() => resolveTavilyMemberOptions(live.current().tavily, () => traced.tavily.resolveApiKey(), fanoutOf())));
2410
+ const members = [
2411
+ {
2412
+ provider: tavily,
2413
+ memberKey: "tavily",
2414
+ pool: pools.tavily
2415
+ },
2416
+ {
2417
+ provider: new ExaSearchProvider(hotMemberOptions(() => resolveExaMemberOptions(live.current().exa, () => traced.exa.resolveApiKey(), fanoutOf()))),
2418
+ memberKey: "exa",
2419
+ pool: pools.exa
2420
+ },
2421
+ {
2422
+ provider: firecrawl,
2423
+ memberKey: "firecrawl",
2424
+ pool: pools.firecrawl
2425
+ },
2426
+ {
2427
+ provider: new DeepSeekSearchProvider(hotMemberOptions(() => resolveDeepSeekMemberOptions(live.current().deepseek, () => traced.deepseek.resolveApiKey()))),
2428
+ memberKey: "deepseek",
2429
+ pool: pools.deepseek
2430
+ },
2431
+ {
2432
+ provider: anysearch,
2433
+ memberKey: "anysearch",
2434
+ pool: pools.anysearch
2435
+ }
2436
+ ];
2437
+ for (const { provider, memberKey, pool } of members) {
2438
+ ctx.web.registerSearchProvider(provider);
2439
+ searchMembers.register(provider, gates(memberKey, pool));
2440
+ }
2441
+ const fetchMembers = new MemberRegistry();
2442
+ for (const member of [
2443
+ firecrawl,
2444
+ tavily,
2445
+ anysearch
2446
+ ]) {
2447
+ const key = member.id.replace("dshws-", "");
2448
+ fetchMembers.register(member, gates(key, pools[key]));
2449
+ }
2450
+ fetchChainInstance = new ChainFetchProvider({
2451
+ members: fetchMembers.toResolver(),
2452
+ get order() {
2453
+ return [...live.current().fetchChain];
2454
+ },
2455
+ get perMemberTimeoutMs() {
2456
+ return live.current().perMemberTimeoutMs;
2457
+ },
2458
+ log
2459
+ });
2460
+ attachSettingsSection(ctx, config, live, { onCommitted: () => {
2461
+ gate.prime(Object.values(pools).flatMap((pool) => pool.refs())).catch((error) => {
2462
+ log(`[dshws-websearch] credential gate re-priming failed unexpectedly: ${String(error)}`);
2463
+ });
2464
+ } });
2465
+ gate.prime(Object.values(pools).flatMap((pool) => pool.refs())).catch((error) => {
2466
+ log(`[dshws-websearch] credential gate priming failed unexpectedly: ${String(error)}`);
2467
+ });
2468
+ }
2469
+ //#endregion
2470
+ export { ANYSEARCH_MEMBER_ID, AnysearchSearchProvider, BUILT_IN_MEMBER_ORDER, CHAIN_ERROR_CODES, Config, CredentialGate, DEEPSEEK_MEMBER_ID, DEFAULT_PER_MEMBER_TIMEOUT_MS, DeepSeekSearchProvider, DshWsKeyCountsRemote, DshwsError, EXA_MEMBER_ID, ExaSearchProvider, FIRECRAWL_MEMBER_ID, FirecrawlProvider, KEY_COUNTS_NAMESPACE, LiveResolvedConfig, MEMBER_ERROR_CODES, SETTINGS_NAMESPACE, TAVILY_MEMBER_ID, TavilySearchProvider, apply, attachSettingsSection, inject, name, resolveAnysearchMemberOptions, resolveDeepSeekMemberOptions, resolveExaMemberOptions, resolveFirecrawlMemberOptions, resolveTavilyMemberOptions };