@maricgeer/dsh-websearch 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -3,10 +3,13 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renam
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { lookup } from "node:dns/promises";
6
- import { isIP } from "node:net";
6
+ import { connect, isIP } from "node:net";
7
7
  import { WebError } from "@deepseek-ai/dsh-web";
8
8
  import z from "@deepseek-ai/schemastery";
9
9
  import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
10
+ import * as dnsNamespace from "node:dns";
11
+ import { request } from "node:https";
12
+ import { connect as connect$1 } from "node:tls";
10
13
  //#region src/errors.ts
11
14
  /**
12
15
  * Error vocabulary for dsh-websearch. Every error carries a stable string
@@ -115,6 +118,28 @@ function createChainExhaustedError(failures) {
115
118
  const last = failures.at(-1);
116
119
  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
120
  }
121
+ /**
122
+ * DNS resilience diagnostic codes (S35, ADR-0022 D11). Diagnostic-level only:
123
+ * they ride log lines, the trace ring, and the remote status face — they never
124
+ * join the chain failure path (a resolution failure keeps the member-failure
125
+ * → chain-degradation semantics of ADR-0002).
126
+ */
127
+ const DNS_ERROR_CODES = {
128
+ /** The lazy canary found reserved-range evidence and armed the DoH layer. */
129
+ autoEnabled: "DSHWS_DNS_AUTO_ENABLED",
130
+ /** The canary proved a clean network; the patch uninstalled (zero-patch). */
131
+ autoSkipped: "DSHWS_DNS_AUTO_SKIPPED",
132
+ /** Some or all canary samples failed system resolution; recorded as diagnostics (enables only when ALL samples failed). */
133
+ detectInconclusive: "DSHWS_DNS_DETECT_INCONCLUSIVE",
134
+ /** Every DoH node failed for a resolution; the degradation chain begins. */
135
+ dohUnreachable: "DSHWS_DNS_DOH_UNREACHABLE",
136
+ /** The precheck dropped every candidate; the original list was kept (宁多勿无). */
137
+ probeAllFailed: "DSHWS_DNS_PROBE_ALL_FAILED",
138
+ /** A proxy environment suspended the layer for this host. */
139
+ suspendedProxy: "DSHWS_DNS_SUSPENDED_PROXY",
140
+ /** The resolution fell back to the original system lookup (never-worse). */
141
+ fallbackSystem: "DSHWS_DNS_FALLBACK_SYSTEM"
142
+ };
118
143
  //#endregion
119
144
  //#region src/chain/core.ts
120
145
  /**
@@ -195,6 +220,8 @@ var ChainCore = class ChainCore {
195
220
  * across those draws (S14u), so redrawing never multiplies the budget.
196
221
  */
197
222
  static MEMBER_DRAWS = 3;
223
+ /** Connect-level attempts per member (plan 037): initial + one fresh-resolution retry. */
224
+ static CONNECT_ATTEMPT_CAP = 2;
198
225
  /** Draws for members with a multi-key pool; single-key members get 1. */
199
226
  #drawsFor(member) {
200
227
  return member.multiKeyPool === true ? ChainCore.MEMBER_DRAWS : 1;
@@ -202,6 +229,7 @@ var ChainCore = class ChainCore {
202
229
  /** Try members in configured order; per member one shared timeout budget across up to MEMBER_DRAWS key redraws, then degrade. */
203
230
  async run(request, signal, invoke) {
204
231
  const failures = [];
232
+ const runKey = nextRunKey();
205
233
  for (const id of this.#options.order) {
206
234
  const member = this.#options.members.resolve(id);
207
235
  if (!this.#isUsable(member)) continue;
@@ -243,6 +271,8 @@ var ChainCore = class ChainCore {
243
271
  } catch (error) {
244
272
  if (signal?.aborted && error !== MEMBER_TIMED_OUT) throw error;
245
273
  const isTimeout = error === MEMBER_TIMED_OUT;
274
+ const connectLevel = !isTimeout && isConnectLevelFailure(error);
275
+ if (isTimeout || connectLevel) this.#options.onMemberConnectFailure?.(id);
246
276
  const status = !isTimeout && error instanceof DshwsError ? error.httpStatus : void 0;
247
277
  const requestLevelStatus = status !== void 0 && REQUEST_LEVEL_HTTP_STATUSES.has(status) ? status : void 0;
248
278
  const credentialLevelStatus = status !== void 0 && CREDENTIAL_LEVEL_HTTP_STATUSES.has(status) ? status : void 0;
@@ -250,10 +280,18 @@ var ChainCore = class ChainCore {
250
280
  drawReasons.push(reason);
251
281
  if (!isTimeout) lastError = error;
252
282
  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}`);
283
+ const connectDegrade = connectLevel && draw >= ChainCore.CONNECT_ATTEMPT_CAP;
284
+ const degrading = isTimeout || requestLevelStatus !== void 0 || connectDegrade || draw >= redrawCap;
285
+ if (connectLevel && requestLevelStatus === void 0) {
286
+ const flapArrow = !degrading ? "retry(fresh-resolve)" : connectDegrade ? "degrade(retry-cap)" : "degrade(no-pool)";
287
+ this.#options.log?.(`[dshws-chain] connect-flap ${id} ${connectCauseCode(error)} → ${flapArrow} #${runKey}`);
288
+ } else {
289
+ const drawNote = degrading ? `; 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)` : ""}`;
290
+ this.#options.log?.(`[dshws-chain] member ${id} failed (${reason})${drawNote}`);
291
+ }
255
292
  if (isTimeout) break;
256
293
  if (requestLevelStatus !== void 0) break;
294
+ if (connectDegrade) break;
257
295
  if (draw >= redrawCap) break;
258
296
  continue;
259
297
  }
@@ -271,6 +309,46 @@ var ChainCore = class ChainCore {
271
309
  throw createChainExhaustedError(failures);
272
310
  }
273
311
  };
312
+ /** Connection-level cause codes (plan 036): an address/path problem a fresh resolution might fix. */
313
+ const CONNECT_LEVEL_CODES = /* @__PURE__ */ new Set([
314
+ "ECONNREFUSED",
315
+ "ETIMEDOUT",
316
+ "ECONNRESET",
317
+ "EHOSTUNREACH",
318
+ "ENETUNREACH",
319
+ "EPIPE",
320
+ "EAI_AGAIN"
321
+ ]);
322
+ /** Extract the first connect-level cause code for compact connect-flap log lines. */
323
+ function connectCauseCode(error) {
324
+ let current = error;
325
+ let hops = 0;
326
+ while (typeof current === "object" && current !== null && hops < 8) {
327
+ const code = current.code;
328
+ if (typeof code === "string" && (CONNECT_LEVEL_CODES.has(code) || code.startsWith("UND_ERR_"))) return code;
329
+ current = current.cause;
330
+ hops += 1;
331
+ }
332
+ return "CONNECT";
333
+ }
334
+ /** Per-run 4-hex key so concurrent chain runs' connect-flap lines stay attributable (plan 038). */
335
+ let runKeyCounter = 0;
336
+ function nextRunKey() {
337
+ runKeyCounter = runKeyCounter + 1 >>> 0;
338
+ return runKeyCounter.toString(16).padStart(4, "0").slice(-4);
339
+ }
340
+ /** Whether any error in the cause chain carries a connect-level code (UND_ERR_* undici codes included). */
341
+ function isConnectLevelFailure(error) {
342
+ let current = error;
343
+ let hops = 0;
344
+ while (typeof current === "object" && current !== null && hops < 8) {
345
+ const code = current.code;
346
+ if (typeof code === "string" && (CONNECT_LEVEL_CODES.has(code) || code.startsWith("UND_ERR_"))) return true;
347
+ current = current.cause;
348
+ hops += 1;
349
+ }
350
+ return false;
351
+ }
274
352
  /** Internal sentinel: the member's `perMemberTimeoutMs` budget expired before a result. */
275
353
  const MEMBER_TIMED_OUT = Symbol("dshws.member-timed-out");
276
354
  /**
@@ -489,13 +567,14 @@ const BINARY_CONTENT_TYPE = /^(application\/octet-stream|image\/|audio\/|video\/
489
567
  *
490
568
  * @throws WebError with a stable code for each rejection class.
491
569
  */
492
- async function delegateFetch(request, signal) {
570
+ /** Default SSRF-guard resolution: the untouched system resolver — `dns.promises.lookup` is never patched (ADR-0022 D1), so this stays the system truth when no dns layer is armed. */
571
+ async function systemResolve(hostname) {
572
+ return (await lookup(hostname, { all: true })).map((entry) => entry.address);
573
+ }
574
+ async function delegateFetch(resolution, request, signal) {
493
575
  const url = new URL(request.url);
494
576
  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);
577
+ const addresses = isIP(hostname) ? [hostname] : await resolution(hostname);
499
578
  for (const address of addresses) if (!isPublicAddress(address)) throw new WebError(`URL hostname resolves to a non-public address (${address})`, "WEB_FETCH_BLOCKED");
500
579
  const response = await fetch(url, {
501
580
  method: "GET",
@@ -518,7 +597,11 @@ async function delegateFetch(request, signal) {
518
597
  truncated
519
598
  };
520
599
  }
521
- /** Whether an address is globally reachable unicast (the official SSRF bar). */
600
+ /**
601
+ * Whether an address is globally reachable unicast (the official SSRF bar).
602
+ * Exported since S35 stage 5: the dns egress precheck reuses the same bar to
603
+ * avoid SYN-probing private ranges a rebinding answer might carry.
604
+ */
522
605
  function isPublicAddress(address) {
523
606
  if (isIP(address) === 6) {
524
607
  const lower = address.toLowerCase();
@@ -545,10 +628,12 @@ function isPublicAddress(address) {
545
628
  var FetchGateProvider = class {
546
629
  isTakeoverActive;
547
630
  chainFetch;
631
+ resolveHostname;
548
632
  id = FETCH_GATE_PROVIDER_ID;
549
- constructor(isTakeoverActive, chainFetch) {
633
+ constructor(isTakeoverActive, chainFetch, resolveHostname = systemResolve) {
550
634
  this.isTakeoverActive = isTakeoverActive;
551
635
  this.chainFetch = chainFetch;
636
+ this.resolveHostname = resolveHostname;
552
637
  }
553
638
  /** Always true: the pin guarantees selection, so availability is ours to own (review M2). */
554
639
  available() {
@@ -556,7 +641,7 @@ var FetchGateProvider = class {
556
641
  }
557
642
  async fetch(request, signal) {
558
643
  if (this.isTakeoverActive()) return await this.chainFetch(request, signal);
559
- return await delegateFetch(request, signal);
644
+ return await delegateFetch(this.resolveHostname, request, signal);
560
645
  }
561
646
  };
562
647
  //#endregion
@@ -615,6 +700,14 @@ function withDesignatedFallback(chain, fallbackMember) {
615
700
  }
616
701
  /** Per-member timeout budget applied when the config omits one (ADR-0002). */
617
702
  const DEFAULT_PER_MEMBER_TIMEOUT_MS = 3e4;
703
+ /** Default poison ranges: RFC 2544 benchmarking + RFC 5737 documentation + this-network-observed blackhole segments. */
704
+ const DEFAULT_DNS_POISON_RANGES = [
705
+ "198.18.0.0/15",
706
+ "192.0.2.0/24",
707
+ "203.0.113.0/24",
708
+ "0.0.0.0/8",
709
+ "240.0.0.0/4"
710
+ ];
618
711
  /**
619
712
  * Unwrap a runtime config into the plain {@link Config} shape: handle fields
620
713
  * read through `get()` (snapshot at call time), plain fields pass through.
@@ -707,7 +800,12 @@ function buildConfigSchema(markVolatile) {
707
800
  includeAnswer: z.union(["basic", "advanced"]),
708
801
  chunksPerSource: z.number().step(1).min(1).max(3),
709
802
  filterByLanguage: z.boolean(),
710
- includeDomainsMode: z.union(["filter", "boost"]),
803
+ includeDomainsMode: z.union([
804
+ "filter",
805
+ "boost",
806
+ "restrict",
807
+ "prefer"
808
+ ]),
711
809
  startDate: z.string(),
712
810
  endDate: z.string(),
713
811
  exactMatch: z.boolean(),
@@ -733,7 +831,8 @@ function buildConfigSchema(markVolatile) {
733
831
  "",
734
832
  "developer",
735
833
  "research",
736
- "pdf"
834
+ "pdf",
835
+ "alexandria"
737
836
  ]),
738
837
  keySelection: z.union([
739
838
  "order",
@@ -791,6 +890,39 @@ function buildConfigSchema(markVolatile) {
791
890
  "round-robin",
792
891
  "random"
793
892
  ])
893
+ })),
894
+ dns: vol(z.object({
895
+ mode: z.union([
896
+ "auto",
897
+ "on",
898
+ "off"
899
+ ]),
900
+ scope: z.union(["members", "all"]),
901
+ preset: z.union([
902
+ "auto",
903
+ "cn",
904
+ "global",
905
+ "custom"
906
+ ]),
907
+ nodeTimeoutMs: z.number().step(1).min(50).max(5e3),
908
+ nodes: z.array(z.object({
909
+ host: z.string(),
910
+ sni: z.string(),
911
+ path: z.string(),
912
+ port: z.number().step(1).min(1).max(65535)
913
+ })),
914
+ probe: z.object({
915
+ enabled: z.boolean(),
916
+ timeoutMs: z.number().step(1).min(50).max(5e3),
917
+ cacheTtlS: z.number().step(1).min(1).max(600),
918
+ method: z.union(["tcp", "tls-hello"])
919
+ }),
920
+ cache: z.object({
921
+ posMinS: z.number().step(1).min(1).max(3600),
922
+ posMaxS: z.number().step(1).min(1).max(86400),
923
+ negS: z.number().step(1).min(1).max(600)
924
+ }),
925
+ poisonRanges: z.array(z.string())
794
926
  }))
795
927
  });
796
928
  }
@@ -849,12 +981,41 @@ function validateFirecrawlTbsRule(value) {
849
981
  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
982
  if (!hasCdr && (hasMin || hasMax)) throw new Error("firecrawl.tbs cd_min/cd_max bounds are only valid together with cdr:1");
851
983
  }
984
+ const EXA_SECTION_VALUES = /* @__PURE__ */ new Set([
985
+ "header",
986
+ "navigation",
987
+ "banner",
988
+ "sidebar",
989
+ "body",
990
+ "footer",
991
+ "metadata"
992
+ ]);
852
993
  function validateExaSectionFilterRule(value) {
853
994
  const exa = value.exa;
854
995
  if (exa === void 0) return;
855
996
  const sectionsConfigured = (exa.includeSections?.trim().length ?? 0) > 0 || (exa.excludeSections?.trim().length ?? 0) > 0;
856
997
  const freshness = exa.maxAgeHours;
857
998
  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");
999
+ for (const [field, text] of [["exa.includeSections", exa.includeSections], ["exa.excludeSections", exa.excludeSections]]) {
1000
+ if (text === void 0) continue;
1001
+ const invalid = text.split(",").map((part) => part.trim()).filter((part) => part.length > 0 && !EXA_SECTION_VALUES.has(part));
1002
+ if (invalid.length > 0) throw new Error(`${field} accepts only the official closed set header|navigation|banner|sidebar|body|footer|metadata — got: ${invalid.join(", ")}`);
1003
+ }
1004
+ }
1005
+ /**
1006
+ * The dns custom-preset node rule (ADR-0022 D6): `preset: 'custom'` requires a
1007
+ * non-empty node list with a non-blank `host` and `sni` on every node. Dual-path
1008
+ * like the ADR-0018 domain rule — the settings write path rejects through the
1009
+ * installSection validate hook before persist, the cordis.yml load path throws
1010
+ * here inside `resolveConfig` (a watcher throw must not be relied on for the
1011
+ * settings path; see {@link validateUnifiedDomainRule}).
1012
+ * @param value - the config section carrying the dns settings.
1013
+ */
1014
+ function validateDnsPresetRule(value) {
1015
+ const dns = value.dns;
1016
+ if (dns === void 0 || dns.preset !== "custom") return;
1017
+ const nodes = dns.nodes ?? [];
1018
+ if (nodes.length === 0 || nodes.some((node) => (node.host?.trim().length ?? 0) === 0 || (node.sni?.trim().length ?? 0) === 0)) throw new Error("dns.preset \"custom\" requires a non-empty nodes list with host and sni on every node (ADR-0022 D6)");
858
1019
  }
859
1020
  /**
860
1021
  * Apply every default explicitly: empty chains become the built-in member
@@ -865,11 +1026,29 @@ function validateExaSectionFilterRule(value) {
865
1026
  * normalized through {@link materializeConfig} first, so plain configs and
866
1027
  * 0.1.7+ handle-wrapped runtime configs resolve identically (ADR-0021).
867
1028
  */
1029
+ /**
1030
+ * Normalize the Tavily include-domains mode to the upstream enum (S37 T1): the wire only
1031
+ * accepts `restrict`/`prefer`; the legacy `filter`/`boost` values map 1:1 onto them so
1032
+ * stored settings from older plugin versions keep resolving without a migration.
1033
+ */
1034
+ function normalizeIncludeDomainsMode(value) {
1035
+ if (value === void 0) return void 0;
1036
+ return value === "filter" ? "restrict" : value === "boost" ? "prefer" : value;
1037
+ }
1038
+ /** Member wire id (`dshws-tavily`) to member key (`tavily`) — replaces string surgery at the seam (S37 T14). */
1039
+ const MEMBER_ID_TO_KEY = {
1040
+ "dshws-tavily": "tavily",
1041
+ "dshws-exa": "exa",
1042
+ "dshws-firecrawl": "firecrawl",
1043
+ "dshws-anysearch": "anysearch",
1044
+ "dshws-deepseek": "deepseek"
1045
+ };
868
1046
  function resolveConfig(config) {
869
1047
  const plain = materializeConfig(config);
870
1048
  validateUnifiedDomainRule(plain);
871
1049
  validateExaSectionFilterRule(plain);
872
1050
  validateFirecrawlTbsRule(plain);
1051
+ validateDnsPresetRule(plain);
873
1052
  const fallbackMember = plain.fallbackMember === "dshws-perplexity" ? "auto" : plain.fallbackMember !== void 0 ? plain.fallbackMember : plain.fallbackProvider === "deepseek" ? DEEPSEEK_FALLBACK_MEMBER_ID : "auto";
874
1053
  return {
875
1054
  searchChain: withDesignatedFallback(plain.searchChain?.length ? [...plain.searchChain] : ORDERABLE_SEARCH_MEMBER_ORDER, fallbackMember),
@@ -905,7 +1084,7 @@ function resolveConfig(config) {
905
1084
  startDate: plain.tavily?.startDate?.trim().length ? plain.tavily.startDate.trim() : void 0,
906
1085
  endDate: plain.tavily?.endDate?.trim().length ? plain.tavily.endDate.trim() : void 0,
907
1086
  exactMatch: plain.tavily?.exactMatch,
908
- includeDomainsMode: plain.tavily?.includeDomainsMode
1087
+ includeDomainsMode: normalizeIncludeDomainsMode(plain.tavily?.includeDomainsMode)
909
1088
  },
910
1089
  firecrawl: {
911
1090
  enabled: plain.firecrawl?.enabled ?? true,
@@ -940,6 +1119,30 @@ function resolveConfig(config) {
940
1119
  baseURL: plain.anysearch?.baseURL?.trim() === "" ? void 0 : plain.anysearch?.baseURL,
941
1120
  zone: plain.anysearch?.zone,
942
1121
  keySelection: plain.anysearch?.keySelection ?? "round-robin"
1122
+ },
1123
+ dns: {
1124
+ mode: plain.dns?.mode ?? "auto",
1125
+ scope: plain.dns?.scope ?? "members",
1126
+ preset: plain.dns?.preset ?? "auto",
1127
+ nodeTimeoutMs: plain.dns?.nodeTimeoutMs ?? 350,
1128
+ nodes: plain.dns?.nodes?.length ? plain.dns.nodes.map((node) => ({
1129
+ host: node.host,
1130
+ sni: node.sni,
1131
+ path: node.path,
1132
+ port: node.port
1133
+ })) : [],
1134
+ probe: {
1135
+ enabled: plain.dns?.probe?.enabled ?? true,
1136
+ timeoutMs: plain.dns?.probe?.timeoutMs ?? 350,
1137
+ cacheTtlS: plain.dns?.probe?.cacheTtlS ?? 30,
1138
+ method: plain.dns?.probe?.method ?? "tcp"
1139
+ },
1140
+ cache: {
1141
+ posMinS: plain.dns?.cache?.posMinS ?? 30,
1142
+ posMaxS: plain.dns?.cache?.posMaxS ?? 300,
1143
+ negS: plain.dns?.cache?.negS ?? 10
1144
+ },
1145
+ poisonRanges: plain.dns?.poisonRanges?.length ? [...plain.dns.poisonRanges] : [...DEFAULT_DNS_POISON_RANGES]
943
1146
  }
944
1147
  };
945
1148
  }
@@ -1032,18 +1235,78 @@ function memberBadResponse(codes, label, error) {
1032
1235
  return new DshwsError(codes.badResponse, `${label} returned an unprocessable response body: ${String(error)}`, { cause: error });
1033
1236
  }
1034
1237
  /**
1238
+ * Read a member response body once, mapping both failure legs to the member
1239
+ * error family: a non-2xx status throws the HTTP error with the unfolded
1240
+ * upstream detail (plus the optional `decorate` diagnostics suffix), a 2xx
1241
+ * body parses as `T`, and an unparseable 2xx body is the bad-response error.
1242
+ * An abort firing mid-body always surfaces as the member's aborted error.
1243
+ * @param response - the settled fetch Response.
1244
+ * @param deps - error family + label; `decorate` appends extra diagnostics
1245
+ * (anysearch rides error_code/request_id here, S37 T4).
1246
+ * @returns the parsed 2xx envelope.
1247
+ */
1248
+ async function readMemberEnvelope(response, deps) {
1249
+ const { codes, label, signal, decorate } = deps;
1250
+ if (!response.ok) {
1251
+ const status = response.status;
1252
+ let message = `${label} API error (HTTP ${status})`;
1253
+ if (status === 429) {
1254
+ const retryAfter = response.headers.get("retry-after");
1255
+ if (retryAfter !== null) message += ` (retry-after: ${retryAfter}s)`;
1256
+ const remaining = response.headers.get("x-ratelimit-remaining");
1257
+ if (remaining !== null) message += ` (remaining: ${remaining})`;
1258
+ }
1259
+ let parsed;
1260
+ try {
1261
+ parsed = await response.json();
1262
+ const detail = unfoldHttpErrorDetail(parsed);
1263
+ if (detail !== void 0 && detail.length > 0) message += `: ${detail}`;
1264
+ if (decorate !== void 0) message += decorate(parsed);
1265
+ } catch (error) {
1266
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes, label, signal, error);
1267
+ }
1268
+ throw new DshwsError(codes.httpError, message, { httpStatus: status });
1269
+ }
1270
+ try {
1271
+ return await response.json();
1272
+ } catch (error) {
1273
+ if (signal?.aborted === true || isAbortError(error)) throw memberAborted(codes, label, signal, error);
1274
+ throw memberBadResponse(codes, label, error);
1275
+ }
1276
+ }
1277
+ /**
1278
+ * Attribution header sent on every provider request. Pinned here once and
1279
+ * drift-guarded by tests/user-agent.test.ts against package.json's version —
1280
+ * a version bump that forgets this constant fails the guard loudly.
1281
+ */
1282
+ const USER_AGENT = "dsh-websearch/0.2.1";
1283
+ /**
1035
1284
  * 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).
1285
+ * providers: `error` (string or `{ message }` or `{ error }`), `detail`
1286
+ * (same three forms, or the FastAPI validation array whose first entry
1287
+ * renders as `msg @loc.loc`), then top-level `message`. The nested
1288
+ * `{ error }` form is the live Tavily 401 body and the array form is the
1289
+ * live Tavily 422 body (both verified 2026-09-28) — narrower picks
1290
+ * silently degrade those responses to a bare status. A top-level `code`
1291
+ * (Firecrawl 408/500: `TIMEOUT`/`UNKNOWN_ERROR`) appends as `[code]` when
1292
+ * present. Non-JSON bodies never reach this (the caller's
1293
+ * `response.json()` throws first).
1039
1294
  */
1040
1295
  function unfoldHttpErrorDetail(parsed) {
1041
- const pick = (value) => typeof value === "string" ? value : value?.message;
1042
- return [
1296
+ const pick = (value) => typeof value === "string" ? value : value?.message ?? (typeof value?.error === "string" ? value.error : void 0);
1297
+ const pickArray = (entries) => {
1298
+ const first = entries.find((entry) => entry.msg !== void 0 && entry.msg.length > 0);
1299
+ if (first === void 0) return void 0;
1300
+ return first.loc !== void 0 && first.loc.length > 0 ? `${first.msg} @${first.loc.join(".")}` : first.msg;
1301
+ };
1302
+ const detail = Array.isArray(parsed.detail) ? pickArray(parsed.detail) : pick(parsed.detail);
1303
+ const base = [
1043
1304
  pick(parsed.error),
1044
- pick(parsed.detail),
1305
+ detail,
1045
1306
  parsed.message
1046
1307
  ].find((candidate) => candidate !== void 0 && candidate.length > 0);
1308
+ if (base === void 0) return parsed.code;
1309
+ return parsed.code !== void 0 && parsed.code.length > 0 ? `${base} [${parsed.code}]` : base;
1047
1310
  }
1048
1311
  /** True for a request limit that can be sent to the provider (a positive whole number). */
1049
1312
  function isPositiveInteger(value) {
@@ -1243,9 +1506,9 @@ Remote(Object.getOwnPropertyDescriptor(DshWsKeyCountsRemote.prototype, "describe
1243
1506
  //#region src/providers/anysearch.ts
1244
1507
  /** Stable id this member registers under (chain + direct pin, `dshws-` prefixed). */
1245
1508
  const ANYSEARCH_MEMBER_ID = "dshws-anysearch";
1509
+ /** Default Anysearch API base; `/v1/search` is the operation. */
1510
+ const ANYSEARCH_DEFAULT_BASE_URL = "https://api.anysearch.com";
1246
1511
  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
1512
  /**
1250
1513
  * Explicit defaulting at the owning boundary (explicit > implicit): the base
1251
1514
  * URL default lands here, config passthrough stays untouched.
@@ -1313,6 +1576,12 @@ function mapAnysearchExtractData(requestUrl, data) {
1313
1576
  };
1314
1577
  }
1315
1578
  /** The Anysearch-backed chain member on both capability faces (search + extract, S21). */
1579
+ /** S37 T4: append the envelope diagnostics the upstream documents on every error. */
1580
+ function anysearchErrorDiagnostics(parsed) {
1581
+ const envelope = parsed;
1582
+ const requestId = envelope?.request_id !== void 0 ? ` (request_id: ${envelope.request_id})` : "";
1583
+ return `${envelope?.error_code !== void 0 ? ` [${envelope.error_code}]` : ""}${requestId}`;
1584
+ }
1316
1585
  var AnysearchSearchProvider = class {
1317
1586
  options;
1318
1587
  id = ANYSEARCH_MEMBER_ID;
@@ -1324,10 +1593,10 @@ var AnysearchSearchProvider = class {
1324
1593
  return URL.canParse(this.options.baseURL);
1325
1594
  }
1326
1595
  async search(request, signal) {
1327
- throwIfMemberAborted(codes$4, "Anysearch", signal);
1596
+ throwIfMemberAborted(codes$4, "AnySearch", signal);
1328
1597
  const apiKey = await this.#apiKey(signal);
1329
- throwIfMemberAborted(codes$4, "Anysearch", signal);
1330
- const maxResults = request.maxResults;
1598
+ throwIfMemberAborted(codes$4, "AnySearch", signal);
1599
+ const maxResults = request.maxResults === void 0 ? void 0 : Math.min(20, Math.max(1, Math.round(request.maxResults)));
1331
1600
  let response;
1332
1601
  try {
1333
1602
  response = await fetch(`${this.options.baseURL}/v1/search`, {
@@ -1337,7 +1606,7 @@ var AnysearchSearchProvider = class {
1337
1606
  "authorization": `Bearer ${apiKey}`,
1338
1607
  "content-type": "application/json",
1339
1608
  "accept": "application/json",
1340
- "user-agent": USER_AGENT$4
1609
+ "user-agent": USER_AGENT
1341
1610
  },
1342
1611
  body: JSON.stringify({
1343
1612
  query: request.query,
@@ -1350,24 +1619,12 @@ var AnysearchSearchProvider = class {
1350
1619
  } catch (error) {
1351
1620
  throw memberFetchFailure(codes$4, "Anysearch", error, signal);
1352
1621
  }
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
- }
1622
+ const envelope = await readMemberEnvelope(response, {
1623
+ codes: codes$4,
1624
+ label: "AnySearch",
1625
+ signal,
1626
+ decorate: anysearchErrorDiagnostics
1627
+ });
1371
1628
  if (envelope.code !== 0) {
1372
1629
  const requestId = envelope.request_id !== void 0 ? ` (request_id: ${envelope.request_id})` : "";
1373
1630
  throw new DshwsError(codes$4.httpError, `Anysearch API error (code ${envelope.code})${envelope.message !== void 0 ? `: ${envelope.message}` : ""}${requestId}`);
@@ -1393,7 +1650,7 @@ var AnysearchSearchProvider = class {
1393
1650
  "authorization": `Bearer ${apiKey}`,
1394
1651
  "content-type": "application/json",
1395
1652
  "accept": "application/json",
1396
- "user-agent": USER_AGENT$4
1653
+ "user-agent": USER_AGENT
1397
1654
  },
1398
1655
  body: JSON.stringify({ url: request.url }),
1399
1656
  ...signal !== void 0 ? { signal } : {}
@@ -1401,17 +1658,12 @@ var AnysearchSearchProvider = class {
1401
1658
  } catch (error) {
1402
1659
  throw memberFetchFailure(codes$4, "AnySearch", error, signal);
1403
1660
  }
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
- }
1661
+ const envelope = await readMemberEnvelope(response, {
1662
+ codes: codes$4,
1663
+ label: "AnySearch",
1664
+ signal,
1665
+ decorate: anysearchErrorDiagnostics
1666
+ });
1415
1667
  if (envelope.code !== 0) {
1416
1668
  const requestId = envelope.request_id !== void 0 ? ` (request_id: ${envelope.request_id})` : "";
1417
1669
  throw new DshwsError(codes$4.httpError, `Anysearch API error (code ${envelope.code})${envelope.message !== void 0 ? `: ${envelope.message}` : ""}${requestId}`);
@@ -1432,11 +1684,15 @@ var AnysearchSearchProvider = class {
1432
1684
  //#region src/providers/deepseek.ts
1433
1685
  /** Stable id this member registers under (chain + direct pin, `dshws-` prefixed). */
1434
1686
  const DEEPSEEK_MEMBER_ID = "dshws-deepseek";
1687
+ /**
1688
+ * Default endpoint: DeepSeek's Anthropic-compatible API, `/v1` included
1689
+ * (`/messages` is appended). NOT the chat-completions base — only the API
1690
+ * key is shared with the chat side.
1691
+ */
1692
+ const DEEPSEEK_DEFAULT_BASE_URL = "https://api.deepseek.com/anthropic/v1";
1435
1693
  /** `anthropic-version` header value; fixed wire constant. */
1436
1694
  const DEEPSEEK_API_VERSION = "2023-06-01";
1437
1695
  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
1696
  /**
1441
1697
  * Explicit defaulting at the owning boundary (explicit > implicit): omitted
1442
1698
  * config fields become the provider constants here, not via schema injection.
@@ -1544,7 +1800,7 @@ var DeepSeekSearchProvider = class {
1544
1800
  "anthropic-version": DEEPSEEK_API_VERSION,
1545
1801
  "content-type": "application/json",
1546
1802
  "accept": "application/json",
1547
- "user-agent": USER_AGENT$3
1803
+ "user-agent": USER_AGENT
1548
1804
  },
1549
1805
  body: JSON.stringify(body),
1550
1806
  ...signal !== void 0 ? { signal } : {}
@@ -1552,24 +1808,11 @@ var DeepSeekSearchProvider = class {
1552
1808
  } catch (error) {
1553
1809
  throw memberFetchFailure(codes$3, "DeepSeek", error, signal);
1554
1810
  }
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
- }
1811
+ return mapDeepSeekResponse(await readMemberEnvelope(response, {
1812
+ codes: codes$3,
1813
+ label: "DeepSeek",
1814
+ signal
1815
+ }));
1573
1816
  }
1574
1817
  /** Resolve one operation's key without retaining it; a missing key is a loud member error. */
1575
1818
  #apiKey(signal) {
@@ -1586,11 +1829,11 @@ var DeepSeekSearchProvider = class {
1586
1829
  //#region src/providers/exa.ts
1587
1830
  /** Stable id this member registers under (chain + direct pin, `dshws-` prefixed). */
1588
1831
  const EXA_MEMBER_ID = "dshws-exa";
1832
+ /** Default Exa search endpoint; `/search` is the operation. */
1833
+ const EXA_DEFAULT_BASE_URL = "https://api.exa.ai";
1589
1834
  /** Text-fallback excerpt budget per result in characters (S17 P1; official range 1-10000). */
1590
1835
  const EXA_TEXT_FALLBACK_MAX_CHARACTERS = 1e3;
1591
1836
  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
1837
  /**
1595
1838
  * Normalize a stored publication-date floor to the ISO date-time form the API
1596
1839
  * expects: a date-only `YYYY-MM-DD` value (the GUI date input's shape) gains
@@ -1667,8 +1910,10 @@ var ExaSearchProvider = class {
1667
1910
  throwIfMemberAborted(codes$2, "Exa", signal);
1668
1911
  const numResults = request.maxResults ?? this.options.numResults;
1669
1912
  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;
1913
+ const specialCategory = this.options.category === "company" || this.options.category === "people";
1914
+ const dateFloor = specialCategory ? void 0 : this.options.startPublishedDate;
1915
+ const dateCeiling = specialCategory ? void 0 : this.options.endPublishedDate;
1916
+ const excludeDomains = specialCategory ? void 0 : this.options.excludeDomains;
1672
1917
  try {
1673
1918
  response = await fetch(`${this.options.baseURL}/search`, {
1674
1919
  method: "POST",
@@ -1677,7 +1922,7 @@ var ExaSearchProvider = class {
1677
1922
  "authorization": `Bearer ${apiKey}`,
1678
1923
  "content-type": "application/json",
1679
1924
  "accept": "application/json",
1680
- "user-agent": USER_AGENT$2
1925
+ "user-agent": USER_AGENT
1681
1926
  },
1682
1927
  body: JSON.stringify({
1683
1928
  query: request.query,
@@ -1698,7 +1943,7 @@ var ExaSearchProvider = class {
1698
1943
  ...numResults !== void 0 ? { numResults } : {},
1699
1944
  ...this.options.category !== void 0 ? { category: this.options.category } : {},
1700
1945
  ...dateFloor !== void 0 ? { startPublishedDate: dateFloor } : {},
1701
- ...this.options.endPublishedDate !== void 0 ? { endPublishedDate: this.options.endPublishedDate } : {},
1946
+ ...dateCeiling !== void 0 ? { endPublishedDate: dateCeiling } : {},
1702
1947
  ...this.options.userLocation !== void 0 ? { userLocation: this.options.userLocation } : {},
1703
1948
  ...this.options.includeDomains !== void 0 ? { includeDomains: [...this.options.includeDomains] } : {},
1704
1949
  ...excludeDomains !== void 0 ? { excludeDomains: [...excludeDomains] } : {}
@@ -1708,23 +1953,11 @@ var ExaSearchProvider = class {
1708
1953
  } catch (error) {
1709
1954
  throw memberFetchFailure(codes$2, "Exa", error, signal);
1710
1955
  }
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
- }
1956
+ return mapExaResponse(await readMemberEnvelope(response, {
1957
+ codes: codes$2,
1958
+ label: "Exa",
1959
+ signal
1960
+ }));
1728
1961
  }
1729
1962
  /** Resolve one operation's key without retaining it; a missing key is a loud member error. */
1730
1963
  #apiKey(signal) {
@@ -1743,9 +1976,9 @@ var ExaSearchProvider = class {
1743
1976
  const FIRECRAWL_SEARCH_TIMEOUT_MS = 2e4;
1744
1977
  /** Stable id this member registers under (search + fetch, `dshws-` prefixed). */
1745
1978
  const FIRECRAWL_MEMBER_ID = "dshws-firecrawl";
1979
+ /** Default Firecrawl API base; `/v2/search` and `/v2/scrape` are the operations. */
1980
+ const FIRECRAWL_DEFAULT_BASE_URL = "https://api.firecrawl.dev";
1746
1981
  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
1982
  /**
1750
1983
  * Firecrawl accepts bare hostnames only (no protocol/path/wildcard): URL-like
1751
1984
  * entries collapse to their host; any wildcard entry makes the whole list an
@@ -1895,8 +2128,8 @@ var FirecrawlProvider = class {
1895
2128
  headers: this.#headers(apiKey),
1896
2129
  body: JSON.stringify({
1897
2130
  url: request.url,
1898
- formats: ["markdown"],
1899
- timeout: 2e4
2131
+ formats: [{ type: "markdown" }],
2132
+ timeout: FIRECRAWL_SEARCH_TIMEOUT_MS
1900
2133
  }),
1901
2134
  ...signal !== void 0 ? { signal } : {}
1902
2135
  });
@@ -1921,7 +2154,7 @@ var FirecrawlProvider = class {
1921
2154
  "authorization": `Bearer ${apiKey}`,
1922
2155
  "content-type": "application/json",
1923
2156
  "accept": "application/json",
1924
- "user-agent": USER_AGENT$1
2157
+ "user-agent": USER_AGENT
1925
2158
  };
1926
2159
  }
1927
2160
  /**
@@ -1929,32 +2162,20 @@ var FirecrawlProvider = class {
1929
2162
  * body unfold), abort mid-body → aborted, bad JSON → bad response.
1930
2163
  */
1931
2164
  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
- }
2165
+ return readMemberEnvelope(response, {
2166
+ codes: codes$1,
2167
+ label,
2168
+ signal
2169
+ });
1949
2170
  }
1950
2171
  };
1951
2172
  //#endregion
1952
2173
  //#region src/providers/tavily.ts
1953
2174
  /** Stable id this member registers under (chain + direct pin, `dshws-` prefixed). */
1954
2175
  const TAVILY_MEMBER_ID = "dshws-tavily";
2176
+ /** Default Tavily API base; `/search` is the operation. */
2177
+ const TAVILY_DEFAULT_BASE_URL = "https://api.tavily.com";
1955
2178
  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
2179
  /**
1959
2180
  * Explicit defaulting at the owning boundary (explicit > implicit): the base
1960
2181
  * URL default lands here, config passthrough stays untouched. The geo entry
@@ -2084,23 +2305,11 @@ var TavilySearchProvider = class {
2084
2305
  } catch (error) {
2085
2306
  throw memberFetchFailure(codes, "Tavily", error, signal);
2086
2307
  }
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
- }
2308
+ return mapTavilyResponse(await readMemberEnvelope(response, {
2309
+ codes,
2310
+ label: "Tavily",
2311
+ signal
2312
+ }));
2104
2313
  }
2105
2314
  /**
2106
2315
  * The extract face (S21): one URL in, markdown out. Billing is per success
@@ -2131,25 +2340,12 @@ var TavilySearchProvider = class {
2131
2340
  } catch (error) {
2132
2341
  throw memberFetchFailure(codes, "Tavily", error, signal);
2133
2342
  }
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
- }
2343
+ const payload = await readMemberEnvelope(response, {
2344
+ codes,
2345
+ label: "Tavily",
2346
+ signal
2347
+ });
2348
+ return mapTavilyExtractResponse(request.url, payload);
2153
2349
  }
2154
2350
  /** Resolve one operation's key without retaining it; a missing key is a loud member error. */
2155
2351
  #apiKey(signal) {
@@ -2239,6 +2435,7 @@ function attachSettingsSection(ctx, entry, live, commitHooks) {
2239
2435
  validateUnifiedDomainRule(section);
2240
2436
  validateExaSectionFilterRule(section);
2241
2437
  validateFirecrawlTbsRule(section);
2438
+ validateDnsPresetRule(section);
2242
2439
  },
2243
2440
  setSource: (source) => {
2244
2441
  live.setSource(source);
@@ -2257,6 +2454,1288 @@ function attachSettingsSection(ctx, entry, live, commitHooks) {
2257
2454
  });
2258
2455
  }
2259
2456
  //#endregion
2457
+ //#region src/dns/ranges.ts
2458
+ /** Parse one dotted-quad into an unsigned 32-bit integer; -1 for anything else (v6, garbage). */
2459
+ function ipv4ToInt(address) {
2460
+ const parts = address.split(".");
2461
+ if (parts.length !== 4) return -1;
2462
+ let value = 0;
2463
+ for (const part of parts) {
2464
+ if (!/^\d{1,3}$/.test(part)) return -1;
2465
+ const octet = Number(part);
2466
+ if (octet > 255) return -1;
2467
+ value = value << 8 | octet;
2468
+ }
2469
+ return value >>> 0;
2470
+ }
2471
+ /**
2472
+ * Parse CIDR strings into matchable ranges; unparseable entries drop out
2473
+ * loudly-by-absence (a bad range never silently matches everything).
2474
+ * @param cidrs - the configured reserved ranges (e.g. `198.18.0.0/15`).
2475
+ * @returns the parsed ranges.
2476
+ */
2477
+ function parseIpv4Ranges(cidrs) {
2478
+ return cidrs.flatMap((cidr) => {
2479
+ const [base, prefixText] = cidr.split("/");
2480
+ const prefix = prefixText === void 0 ? 32 : Number(prefixText);
2481
+ const baseInt = ipv4ToInt(base);
2482
+ if (baseInt < 0 || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) return [];
2483
+ const mask = prefix === 0 ? 0 : 4294967295 << 32 - prefix >>> 0;
2484
+ return [{
2485
+ base: (baseInt & mask) >>> 0,
2486
+ mask
2487
+ }];
2488
+ });
2489
+ }
2490
+ /**
2491
+ * Whether the address falls inside any range; v6 and malformed inputs never match.
2492
+ * @param address - the answer address under test.
2493
+ * @param ranges - the parsed reserved ranges.
2494
+ * @returns reserved-range membership.
2495
+ */
2496
+ function isReservedIpv4(address, ranges) {
2497
+ const value = ipv4ToInt(address);
2498
+ if (value < 0) return false;
2499
+ return ranges.some((range) => (value & range.mask) >>> 0 === range.base);
2500
+ }
2501
+ //#endregion
2502
+ //#region src/dns/transport.ts
2503
+ /**
2504
+ * DoH JSON transport (ADR-0022 D1/D6): one DNS question against one node over
2505
+ * HTTPS, with SNI and the connect target separated — the connect goes to the
2506
+ * node host (an IP literal, so the resolver never needs itself to resolve),
2507
+ * while `servername` and the HTTP `Host` header carry the TLS name. The accept
2508
+ * header is the fixed `application/dns-json` constant (harmless for the
2509
+ * path-style JSON endpoints AliDNS/Google expose).
2510
+ *
2511
+ * @module dsh-websearch/dns/transport
2512
+ */
2513
+ /**
2514
+ * The fixed JSON-DoH accept header every vendor's JSON face honors (Quad9's
2515
+ * documented form even works without it); path-style endpoints ignore it.
2516
+ */
2517
+ const DOH_JSON_ACCEPT = "application/dns-json";
2518
+ /** A classified transport failure; `kind` drives node cooldown and fallback. */
2519
+ var DohTransportError = class extends Error {
2520
+ kind;
2521
+ constructor(kind, message) {
2522
+ super(message);
2523
+ this.name = "DohTransportError";
2524
+ this.kind = kind;
2525
+ }
2526
+ };
2527
+ /**
2528
+ * Pull the requested family's address rows out of a NOERROR envelope, keeping
2529
+ * the CNAME chain traversed on the way (the anysearch GTM shape). Non-NOERROR
2530
+ * envelopes yield empty records — NXDOMAIN respect is the resolver layer's
2531
+ * decision, not the extractor's.
2532
+ * @param envelope - the parsed DoH JSON body.
2533
+ * @param type - the requested family (1 = A, 28 = AAAA).
2534
+ * @returns the address rows and CNAME chain for that family.
2535
+ */
2536
+ function extractDohRecords(envelope, type) {
2537
+ if (envelope.Status !== 0) return {
2538
+ addresses: [],
2539
+ cnameChain: []
2540
+ };
2541
+ const family = type === 28 ? 6 : 4;
2542
+ const cnameChain = [];
2543
+ const addresses = [];
2544
+ for (const row of envelope.Answer ?? []) {
2545
+ if (row.type === 5) {
2546
+ cnameChain.push(row.data);
2547
+ continue;
2548
+ }
2549
+ if (row.type === type) addresses.push({
2550
+ address: row.data,
2551
+ family,
2552
+ ttl: Math.max(1, Math.floor(row.TTL ?? 60))
2553
+ });
2554
+ }
2555
+ return {
2556
+ addresses,
2557
+ cnameChain
2558
+ };
2559
+ }
2560
+ /**
2561
+ * Build the https.request options for one query: connect to the node host,
2562
+ * SNI and HTTP Host both to the TLS name — the separation that reaches real
2563
+ * resolvers through (SNI, IP)-filtered egress paths.
2564
+ * @param node - the complete endpoint.
2565
+ * @param path - the query path with encoded name and type.
2566
+ * @returns the request options for node:https.
2567
+ */
2568
+ function buildRequestOptions(node, path) {
2569
+ return {
2570
+ host: node.host,
2571
+ port: node.port,
2572
+ servername: node.sni,
2573
+ method: "GET",
2574
+ path,
2575
+ headers: {
2576
+ host: node.sni,
2577
+ accept: DOH_JSON_ACCEPT
2578
+ }
2579
+ };
2580
+ }
2581
+ /**
2582
+ * The production send: one https GET against the node with the timeout
2583
+ * enforced on the socket. Network and timeout failures leave as classified
2584
+ * {@link DohTransportError}s; HTTP status and body pass through for
2585
+ * {@link dohQuery} to classify.
2586
+ * @param node - the complete endpoint.
2587
+ * @param path - the query path.
2588
+ * @param timeoutMs - the per-node budget.
2589
+ * @returns the HTTP status and body.
2590
+ */
2591
+ async function httpsSend(node, path, timeoutMs) {
2592
+ return await new Promise((resolve, reject) => {
2593
+ const req = request(buildRequestOptions(node, path), (res) => {
2594
+ const chunks = [];
2595
+ res.on("data", (chunk) => chunks.push(chunk));
2596
+ res.on("end", () => resolve({
2597
+ status: res.statusCode ?? 0,
2598
+ body: Buffer.concat(chunks).toString("utf8")
2599
+ }));
2600
+ res.on("error", (err) => reject(new DohTransportError("network", `doh response stream failed: ${err.message}`)));
2601
+ });
2602
+ req.setTimeout(timeoutMs, () => {
2603
+ req.destroy(new DohTransportError("timeout", `doh node ${node.host} timed out after ${timeoutMs}ms`));
2604
+ });
2605
+ req.on("error", (err) => {
2606
+ reject(err instanceof DohTransportError ? err : new DohTransportError("network", `doh node ${node.host} unreachable: ${err.message}`));
2607
+ });
2608
+ req.end();
2609
+ });
2610
+ }
2611
+ /**
2612
+ * Run one query against one node and parse the JSON envelope. Non-200 bodies
2613
+ * classify as `http`, malformed bodies as `parse`; errors the send layer
2614
+ * already classified (timeout/network) propagate unchanged.
2615
+ * @param node - the complete endpoint.
2616
+ * @param query - the DNS question.
2617
+ * @param timeoutMs - the per-node budget handed to the send layer.
2618
+ * @param send - the transport function; the production https send by default.
2619
+ * @returns the parsed envelope (Status/Answer subset).
2620
+ */
2621
+ async function dohQuery(node, query, timeoutMs, send = httpsSend) {
2622
+ const { status, body } = await send(node, `${node.path}?name=${encodeURIComponent(query.name)}&type=${query.type}`, timeoutMs);
2623
+ if (status !== 200) throw new DohTransportError("http", `doh node ${node.host} answered HTTP ${status}`);
2624
+ try {
2625
+ return JSON.parse(body);
2626
+ } catch (err) {
2627
+ throw new DohTransportError("parse", `doh node ${node.host} returned a malformed JSON body: ${err.message}`);
2628
+ }
2629
+ }
2630
+ //#endregion
2631
+ //#region src/dns/detect.ts
2632
+ /**
2633
+ * Canary auto-detection, pool bootstrap, and proxy-environment suspension
2634
+ * (ADR-0022 D4/D6/D7). The detector runs the ORIGINAL system lookup against
2635
+ * the member host set — reserved-range membership is the only enabling signal
2636
+ * (probe failures never are, guarding against the side-router's flaky virtual
2637
+ * endpoints); the decision table's five branches live here, the lazy trigger
2638
+ * timing (first in-scope lookup, never apply()) lives in the intercept layer.
2639
+ *
2640
+ * @module dsh-websearch/dns/detect
2641
+ */
2642
+ /**
2643
+ * Run the canary decision table over the member host set:
2644
+ * ① all clean → skip/clean; ② any reserved-range hit → enable/poisoned (hits
2645
+ * are the evidence); ③ every sample unobtainable → enable/inconclusive (a
2646
+ * blind resolver beats a poisoned one); ④ mixed clean+failed with zero hits →
2647
+ * skip/clean (a clean sample proves no poisoning; failures record as
2648
+ * diagnostics); ⑤ empty canary set → skip/empty without probing.
2649
+ * @param hosts - the canary set (the live member baseURL hosts).
2650
+ * @param options - the system lookup and reserved ranges.
2651
+ * @returns the decision with its evidence.
2652
+ */
2653
+ async function runCanary(hosts, options) {
2654
+ if (hosts.length === 0) return {
2655
+ action: "skip",
2656
+ verdict: "empty",
2657
+ hits: [],
2658
+ failures: []
2659
+ };
2660
+ const ranges = parseIpv4Ranges(options.poisonRanges);
2661
+ const hits = [];
2662
+ const failures = [];
2663
+ for (const host of hosts) try {
2664
+ const poisoned = (await options.systemLookup(host)).filter((address) => isReservedIpv4(address, ranges));
2665
+ if (poisoned.length > 0) hits.push({
2666
+ host,
2667
+ addresses: poisoned
2668
+ });
2669
+ } catch (err) {
2670
+ failures.push({
2671
+ host,
2672
+ reason: err.message
2673
+ });
2674
+ }
2675
+ if (hits.length > 0) return {
2676
+ action: "enable",
2677
+ verdict: "poisoned",
2678
+ hits,
2679
+ failures
2680
+ };
2681
+ if (failures.length === hosts.length) return {
2682
+ action: "enable",
2683
+ verdict: "inconclusive",
2684
+ hits,
2685
+ failures
2686
+ };
2687
+ return {
2688
+ action: "skip",
2689
+ verdict: "clean",
2690
+ hits,
2691
+ failures
2692
+ };
2693
+ }
2694
+ /**
2695
+ * Probe every pool node in parallel with one neutral query and rank the
2696
+ * Status-0 responders by measured RTT; unreachable nodes drop out. The
2697
+ * trimmed list becomes the resolver's node order.
2698
+ * @param pool - the candidate nodes.
2699
+ * @param options - budget, seams, and the take count.
2700
+ * @returns the reachable nodes, fastest first.
2701
+ */
2702
+ async function bootstrapNodes(pool, options) {
2703
+ const clock = options.clock ?? Date.now;
2704
+ const probeName = "example.com";
2705
+ return (await Promise.all(pool.map(async (node) => {
2706
+ const startedAt = clock();
2707
+ try {
2708
+ if ((await dohQuery(node, {
2709
+ name: probeName,
2710
+ type: 1
2711
+ }, options.timeoutMs, options.send)).Status !== 0) return null;
2712
+ return {
2713
+ node,
2714
+ rttMs: clock() - startedAt
2715
+ };
2716
+ } catch {
2717
+ return null;
2718
+ }
2719
+ }))).filter((entry) => entry !== null).sort((a, b) => a.rttMs - b.rttMs).slice(0, options.take ?? 2).map((entry) => entry.node);
2720
+ }
2721
+ /** The proxy variable names the suspension honors (upper and lower case). */
2722
+ const PROXY_VARS = [
2723
+ "HTTPS_PROXY",
2724
+ "https_proxy",
2725
+ "HTTP_PROXY",
2726
+ "http_proxy",
2727
+ "ALL_PROXY",
2728
+ "all_proxy"
2729
+ ];
2730
+ /** The no-proxy variable names read in order. */
2731
+ const NO_PROXY_VARS = ["NO_PROXY", "no_proxy"];
2732
+ /**
2733
+ * Whether any standard proxy variable is set to a non-blank value.
2734
+ * @param env - the environment to read (process.env by default at the caller).
2735
+ * @returns proxy-environment presence.
2736
+ */
2737
+ function proxyEnvActive(env) {
2738
+ return PROXY_VARS.some((name) => (env[name] ?? "").trim().length > 0);
2739
+ }
2740
+ /**
2741
+ * NO_PROXY matching (ADR-0022 D7): a CSV list; an entry matches by equality or
2742
+ * dot-suffix (`api.tavily.com` matches `tavily.com`, not `avily.com`); `*`
2743
+ * exempts everything; matching is case-insensitive.
2744
+ * @param host - the host the resolution targets.
2745
+ * @param noProxy - the raw NO_PROXY value.
2746
+ * @returns exemption from the proxy suspension.
2747
+ */
2748
+ function matchesNoProxy(host, noProxy) {
2749
+ const raw = (noProxy ?? "").trim();
2750
+ if (raw.length === 0) return false;
2751
+ const target = host.toLowerCase();
2752
+ return raw.split(",").some((entryRaw) => {
2753
+ const entry = entryRaw.trim().toLowerCase();
2754
+ if (entry.length === 0) return false;
2755
+ if (entry === "*") return true;
2756
+ return target === entry || target.endsWith(`.${entry}`);
2757
+ });
2758
+ }
2759
+ /**
2760
+ * Whether the DNS layer must suspend for this host: a proxy environment is
2761
+ * present AND the host is not NO_PROXY-exempt (under a proxy, resolution and
2762
+ * the TCP precheck both move to the proxy side — local DoH is meaningless and
2763
+ * the precheck would misread).
2764
+ * @param host - the host the resolution targets.
2765
+ * @param env - the environment to read.
2766
+ * @returns suspension verdict for this resolution.
2767
+ */
2768
+ function proxySuspendsFor(host, env) {
2769
+ if (!proxyEnvActive(env)) return false;
2770
+ return !NO_PROXY_VARS.some((name) => matchesNoProxy(host, env[name]));
2771
+ }
2772
+ //#endregion
2773
+ //#region src/dns/probe.ts
2774
+ /**
2775
+ * Egress reachability precheck (ADR-0022 D3): a bare TCP handshake per
2776
+ * candidate address — no TLS, no SNI, no HTTP — so the service's application
2777
+ * layer never sees it (zero quota consumption, zero risk-control signal, zero
2778
+ * interaction with the multi-key pools). Verdicts cache per IP for cacheTtlS;
2779
+ * an all-failed probe keeps the original list (the precheck must never become
2780
+ * the outage itself).
2781
+ *
2782
+ * @module dsh-websearch/dns/probe
2783
+ */
2784
+ /**
2785
+ * The production handshake: TCP connect with the budget enforced on the
2786
+ * socket, destroyed the moment the verdict is known.
2787
+ * @param ip - the candidate address.
2788
+ * @param port - the destination port.
2789
+ * @param timeoutMs - the handshake budget.
2790
+ * @returns whether the TCP three-way handshake completed.
2791
+ */
2792
+ async function tcpConnect(ip, port, timeoutMs) {
2793
+ return await new Promise((resolve) => {
2794
+ const socket = connect({
2795
+ host: ip,
2796
+ port
2797
+ });
2798
+ let settled = false;
2799
+ const finish = (ok) => {
2800
+ if (settled) return;
2801
+ settled = true;
2802
+ socket.destroy();
2803
+ resolve(ok);
2804
+ };
2805
+ socket.setTimeout(timeoutMs, () => finish(false));
2806
+ socket.once("connect", () => finish(true));
2807
+ socket.once("error", () => finish(false));
2808
+ });
2809
+ }
2810
+ /**
2811
+ * S39 (plan 038 T3): the SNI-aware probe transport. Sends a TLS ClientHello
2812
+ * with the hostname as servername so the (SNI, IP)-filtered egress path
2813
+ * (side-router class) can match the tuple and the probe signal reflects
2814
+ * the real fetch path. Destroys immediately after secureConnect.
2815
+ */
2816
+ function tlsHelloConnect(ip, port, timeoutMs, servername) {
2817
+ return new Promise((resolve) => {
2818
+ const socket = connect$1({
2819
+ host: ip,
2820
+ port,
2821
+ servername,
2822
+ rejectUnauthorized: false
2823
+ });
2824
+ let settled = false;
2825
+ const finish = (ok) => {
2826
+ if (settled) return;
2827
+ settled = true;
2828
+ socket.destroy();
2829
+ resolve(ok);
2830
+ };
2831
+ socket.setTimeout(timeoutMs, () => finish(false));
2832
+ socket.once("secureConnect", () => finish(true));
2833
+ socket.once("error", () => finish(false));
2834
+ });
2835
+ }
2836
+ /** The egress precheck; one instance owns the per-IP verdict cache. */
2837
+ var EgressProbe = class {
2838
+ #port;
2839
+ #timeoutMs;
2840
+ #cacheTtlMs;
2841
+ #connect;
2842
+ #clock;
2843
+ #verdicts = /* @__PURE__ */ new Map();
2844
+ #method;
2845
+ #hostname;
2846
+ #tlsConnect;
2847
+ constructor(options) {
2848
+ this.#port = options.port;
2849
+ this.#timeoutMs = options.timeoutMs;
2850
+ this.#cacheTtlMs = options.cacheTtlS * 1e3;
2851
+ this.#connect = options.connect ?? tcpConnect;
2852
+ this.#clock = options.clock ?? Date.now;
2853
+ this.#method = options.method ?? "tcp";
2854
+ this.#hostname = options.hostname;
2855
+ this.#tlsConnect = options.tlsConnect ?? tlsHelloConnect;
2856
+ }
2857
+ /**
2858
+ * Filter one address list down to the egress-reachable entries. Every
2859
+ * uncached address is probed in parallel; a verdict cache hit skips the
2860
+ * handshake entirely. When nothing survives, the original list returns
2861
+ * intact (宁多勿无) with the drops recorded for diagnostics.
2862
+ * @param addresses - the candidate addresses for one resolution.
2863
+ * @returns the kept/dropped split and whether any live handshake ran.
2864
+ */
2865
+ async filterReachable(addresses) {
2866
+ if (addresses.length === 0) return {
2867
+ kept: [],
2868
+ dropped: [],
2869
+ cached: true
2870
+ };
2871
+ const now = this.#clock();
2872
+ const live = [];
2873
+ const outcomes = await Promise.all(addresses.map(async (address) => {
2874
+ const hit = this.#verdicts.get(address);
2875
+ if (hit !== void 0 && hit.expiresAt > now) return {
2876
+ address,
2877
+ ok: hit.ok,
2878
+ fresh: false
2879
+ };
2880
+ live.push(address);
2881
+ const ok = this.#method === "tls-hello" && this.#hostname !== void 0 ? await this.#tlsConnect(address, this.#port, this.#timeoutMs, this.#hostname) : await this.#connect(address, this.#port, this.#timeoutMs);
2882
+ this.#verdicts.set(address, {
2883
+ ok,
2884
+ expiresAt: this.#clock() + this.#cacheTtlMs
2885
+ });
2886
+ return {
2887
+ address,
2888
+ ok,
2889
+ fresh: true
2890
+ };
2891
+ }));
2892
+ const kept = outcomes.filter((outcome) => outcome.ok).map((outcome) => outcome.address);
2893
+ const dropped = outcomes.filter((outcome) => !outcome.ok).map((outcome) => outcome.address);
2894
+ return {
2895
+ kept: kept.length > 0 ? kept : [...addresses],
2896
+ dropped,
2897
+ cached: live.length === 0
2898
+ };
2899
+ }
2900
+ };
2901
+ //#endregion
2902
+ //#region src/dns/pool.ts
2903
+ /** China-mainland-reachable pool (JSON faces verified 2026-09-27, see tests/dns/fixtures/README.md). */
2904
+ const CN_POOL = [
2905
+ {
2906
+ host: "223.5.5.5",
2907
+ sni: "dns.alidns.com",
2908
+ path: "/resolve",
2909
+ port: 443
2910
+ },
2911
+ {
2912
+ host: "223.6.6.6",
2913
+ sni: "dns.alidns.com",
2914
+ path: "/resolve",
2915
+ port: 443
2916
+ },
2917
+ {
2918
+ host: "120.53.53.53",
2919
+ sni: "doh.pub",
2920
+ path: "/dns-query",
2921
+ port: 443
2922
+ },
2923
+ {
2924
+ host: "119.29.29.29",
2925
+ sni: "doh.pub",
2926
+ path: "/dns-query",
2927
+ port: 443
2928
+ }
2929
+ ];
2930
+ /** Overseas pool; Quad9's JSON API lives on the documented non-standard port 5053. */
2931
+ const GLOBAL_POOL = [
2932
+ {
2933
+ host: "1.1.1.1",
2934
+ sni: "cloudflare-dns.com",
2935
+ path: "/dns-query",
2936
+ port: 443
2937
+ },
2938
+ {
2939
+ host: "1.0.0.1",
2940
+ sni: "cloudflare-dns.com",
2941
+ path: "/dns-query",
2942
+ port: 443
2943
+ },
2944
+ {
2945
+ host: "8.8.8.8",
2946
+ sni: "dns.google",
2947
+ path: "/resolve",
2948
+ port: 443
2949
+ },
2950
+ {
2951
+ host: "8.8.4.4",
2952
+ sni: "dns.google",
2953
+ path: "/resolve",
2954
+ port: 443
2955
+ },
2956
+ {
2957
+ host: "9.9.9.9",
2958
+ sni: "dns.quad9.net",
2959
+ path: "/dns-query",
2960
+ port: 5053
2961
+ }
2962
+ ];
2963
+ /** The auto preset's candidate set: cn first (this network's only reachable tier), overseas after. */
2964
+ const FULL_POOL = [...CN_POOL, ...GLOBAL_POOL];
2965
+ /**
2966
+ * Map a preset onto its node list. Custom nodes get the path/port defaults
2967
+ * filled (`/dns-query`, 443); the custom-non-empty cross-field rule itself is
2968
+ * validated in config (dual-path).
2969
+ * @param preset - the configured region preset.
2970
+ * @param customNodes - the user-supplied node list (custom preset only).
2971
+ * @returns the complete endpoints for the resolver.
2972
+ */
2973
+ function nodesForPreset(preset, customNodes) {
2974
+ if (preset === "cn") return CN_POOL;
2975
+ if (preset === "global") return GLOBAL_POOL;
2976
+ if (preset === "custom") return customNodes.map((node) => ({
2977
+ path: "/dns-query",
2978
+ port: 443,
2979
+ ...node
2980
+ }));
2981
+ return FULL_POOL;
2982
+ }
2983
+ //#endregion
2984
+ //#region src/dns/resolver.ts
2985
+ /**
2986
+ * The core DoH resolver (ADR-0022 D2): cache → nodes in order with a
2987
+ * per-node budget (3 consecutive failures cool a node for 30s) → NXDOMAIN
2988
+ * respected as a deterministic answer (no node retry) → reserved-range poison
2989
+ * filtering (keep the unfiltered list when everything matches — the filter
2990
+ * must not become the outage) → every node failed returns `null` so the
2991
+ * caller falls back to the original system lookup (never-worse principle).
2992
+ *
2993
+ * @module dsh-websearch/dns/resolver
2994
+ */
2995
+ /** A node failure streak becomes a cooldown after this many consecutive transport/SERVFAIL outcomes. */
2996
+ const DEFAULT_COOLDOWN = {
2997
+ failThreshold: 3,
2998
+ cooldownS: 30
2999
+ };
3000
+ /**
3001
+ * The DoH resolver core. One instance owns the cache, the per-node failure
3002
+ * streaks, and the cooldown bookkeeping; the intercept layer (ADR-0022 D10)
3003
+ * constructs and disposes it with the patch lifecycle.
3004
+ */
3005
+ var DohResolver = class {
3006
+ #nodes;
3007
+ #nodeTimeoutMs;
3008
+ #cacheSpec;
3009
+ #cooldown;
3010
+ #send;
3011
+ #clock;
3012
+ #ranges;
3013
+ #cache = /* @__PURE__ */ new Map();
3014
+ #failStreaks = /* @__PURE__ */ new Map();
3015
+ #cooldownUntil = /* @__PURE__ */ new Map();
3016
+ constructor(options) {
3017
+ this.#nodes = options.nodes;
3018
+ this.#nodeTimeoutMs = options.nodeTimeoutMs;
3019
+ this.#cacheSpec = options.cache;
3020
+ this.#cooldown = options.cooldown ?? DEFAULT_COOLDOWN;
3021
+ this.#send = options.send;
3022
+ this.#clock = options.clock ?? Date.now;
3023
+ this.#ranges = parseIpv4Ranges(options.poisonRanges);
3024
+ }
3025
+ /**
3026
+ * S36 (plan 036) negative feedback: drop every cached POSITIVE entry for
3027
+ * the name across all three family keys — the next resolve re-queries DoH
3028
+ * for a fresh rotation. Negative entries stay (NXDOMAIN is respected and
3029
+ * its TTL is 10s).
3030
+ * @param name - the hostname whose positive cache entries drop.
3031
+ */
3032
+ invalidate(name) {
3033
+ const lowered = name.toLowerCase();
3034
+ for (const key of [
3035
+ `${lowered}:0`,
3036
+ `${lowered}:4`,
3037
+ `${lowered}:6`
3038
+ ]) {
3039
+ const entry = this.#cache.get(key);
3040
+ if (entry !== void 0 && !entry.resolution.negative) this.#cache.delete(key);
3041
+ }
3042
+ }
3043
+ /** Whether a reserved-range membership drops this v4 address; v6 passes untouched (H7 follow-up owns v6 probing). */
3044
+ #isPoisoned(address) {
3045
+ return isReservedIpv4(address, this.#ranges);
3046
+ }
3047
+ /**
3048
+ * Resolve one name for one family ask. `null` means the DoH plane is
3049
+ * unusable right now (every node failed) — the caller must fall back to the
3050
+ * original system lookup; a returned resolution (negative included) is the
3051
+ * real resolver's answer and is trusted as-is.
3052
+ * @param name - the hostname (never an IP literal; the intercept layer filters those).
3053
+ * @param family - 4, 6, or 0 for the merged both-families answer (v4 first).
3054
+ * @returns the resolution, or null for an all-nodes-dead DoH plane.
3055
+ */
3056
+ async resolve(name, family) {
3057
+ const key = `${name.toLowerCase()}:${family}`;
3058
+ const hit = this.#cache.get(key);
3059
+ const now = this.#clock();
3060
+ if (hit !== void 0 && hit.expiresAt > now) return {
3061
+ ...hit.resolution,
3062
+ via: "cache",
3063
+ latencyMs: 0
3064
+ };
3065
+ const startedAt = now;
3066
+ const types = family === 6 ? [28] : family === 4 ? [1] : [1, 28];
3067
+ const merged = [];
3068
+ const dropped = [];
3069
+ let winningVia = "";
3070
+ let minTtlS = Number.POSITIVE_INFINITY;
3071
+ let allNegative = true;
3072
+ for (const type of types) {
3073
+ const perFamily = await this.#queryOneFamily(name, type);
3074
+ if (perFamily === null) return null;
3075
+ if (!perFamily.negative) allNegative = false;
3076
+ if (perFamily.via !== "" && winningVia === "") winningVia = perFamily.via;
3077
+ const filtered = perFamily.records.addresses.filter((entry) => {
3078
+ if (entry.family === 6 || !this.#isPoisoned(entry.address)) return true;
3079
+ dropped.push(entry.address);
3080
+ return false;
3081
+ });
3082
+ const kept = filtered.length > 0 ? filtered : perFamily.records.addresses;
3083
+ for (const entry of kept) merged.push({
3084
+ address: entry.address,
3085
+ family: entry.family
3086
+ });
3087
+ for (const entry of perFamily.records.addresses) minTtlS = Math.min(minTtlS, entry.ttl);
3088
+ }
3089
+ const negative = allNegative;
3090
+ const resolution = {
3091
+ addresses: merged,
3092
+ negative,
3093
+ droppedPoisoned: dropped
3094
+ };
3095
+ const ttlS = negative ? this.#cacheSpec.negS : Math.min(Math.max(Math.ceil(minTtlS), this.#cacheSpec.posMinS), this.#cacheSpec.posMaxS);
3096
+ this.#cache.set(key, {
3097
+ resolution,
3098
+ expiresAt: this.#clock() + ttlS * 1e3
3099
+ });
3100
+ return {
3101
+ ...resolution,
3102
+ via: winningVia,
3103
+ latencyMs: this.#clock() - startedAt
3104
+ };
3105
+ }
3106
+ /**
3107
+ * Query one record type across the node list, honoring cooldowns. NXDOMAIN
3108
+ * and NOERROR are deterministic answers from the first node that produces
3109
+ * one; transport errors and SERVFAIL move to the next node and feed the
3110
+ * failure streak. An empty NOERROR answer counts as negative (NODATA).
3111
+ * @returns the node outcome, or null when every usable node failed.
3112
+ */
3113
+ async #queryOneFamily(name, type) {
3114
+ const now = this.#clock();
3115
+ for (const node of this.#nodes) {
3116
+ const cooledUntil = this.#cooldownUntil.get(node.host);
3117
+ if (cooledUntil !== void 0 && cooledUntil > now) continue;
3118
+ let envelope;
3119
+ try {
3120
+ envelope = await dohQuery(node, {
3121
+ name,
3122
+ type
3123
+ }, this.#nodeTimeoutMs, this.#send);
3124
+ } catch {
3125
+ this.#registerFailure(node.host);
3126
+ continue;
3127
+ }
3128
+ if (envelope.Status === 2) {
3129
+ this.#registerFailure(node.host);
3130
+ continue;
3131
+ }
3132
+ this.#failStreaks.delete(node.host);
3133
+ if (envelope.Status !== 0) return {
3134
+ negative: true,
3135
+ via: node.host,
3136
+ records: {
3137
+ addresses: [],
3138
+ cnameChain: []
3139
+ }
3140
+ };
3141
+ const records = extractDohRecords(envelope, type);
3142
+ if (records.addresses.length === 0) return {
3143
+ negative: true,
3144
+ via: node.host,
3145
+ records
3146
+ };
3147
+ return {
3148
+ negative: false,
3149
+ via: node.host,
3150
+ records
3151
+ };
3152
+ }
3153
+ return null;
3154
+ }
3155
+ #registerFailure(host) {
3156
+ const streak = (this.#failStreaks.get(host) ?? 0) + 1;
3157
+ this.#failStreaks.set(host, streak);
3158
+ if (streak >= this.#cooldown.failThreshold) {
3159
+ this.#cooldownUntil.set(host, this.#clock() + this.#cooldown.cooldownS * 1e3);
3160
+ this.#failStreaks.delete(host);
3161
+ }
3162
+ }
3163
+ };
3164
+ //#endregion
3165
+ //#region src/dns/intercept.ts
3166
+ /**
3167
+ * The process-level dns.lookup interception (ADR-0022 D1/D4/D5/D7/D10): one
3168
+ * patch face on the callback-form `dns.lookup` module export — the seam the
3169
+ * spike proved undici's fetch consults per call (docs/sessions/audit-logs/
3170
+ * 2026-09-27-s35-t0-spike/). Everything routes through live-read config:
3171
+ * mode off / IP literals / out-of-scope hosts / proxy-suspended hosts pass
3172
+ * straight to the captured original; armed resolutions answer from the DoH
3173
+ * resolver with the egress precheck; a dead DoH plane falls back to the
3174
+ * original exactly once (never-worse). Auto mode triggers the canary lazily
3175
+ * on the FIRST in-scope lookup — never at apply — so装配-class tests stay
3176
+ * hermetic, and a skip decision uninstalls the patch entirely (zero-patch).
3177
+ *
3178
+ * @module dsh-websearch/dns/intercept
3179
+ */
3180
+ const dnsModule = dnsNamespace.default ?? dnsNamespace;
3181
+ /** The one installed layer at a time — a defensive reinstall disposes its predecessor (HMR single-layer guarantee). */
3182
+ let activeLayer = null;
3183
+ /** Promisify one original-lookup call into the all-form address list. */
3184
+ function systemAddresses(systemLookup, hostname) {
3185
+ return new Promise((resolve, reject) => {
3186
+ systemLookup(hostname, {
3187
+ all: true,
3188
+ family: 0
3189
+ }, (err, addresses) => {
3190
+ if (err !== null) reject(err);
3191
+ else resolve(addresses.map((entry) => entry.address));
3192
+ });
3193
+ });
3194
+ }
3195
+ /**
3196
+ * The boot-warmup gate (plan 036): warm only outside a vitest worker — the
3197
+ * warmup is a network side effect and the unit-suite hermeticity red line
3198
+ * (ADR-0022 D4) outranks it. New-introduced pattern for this repo, declared
3199
+ * in the ADR addendum.
3200
+ * @param env - the environment to consult (process.env in production).
3201
+ * @returns the warmup delay in ms, or undefined to never warm.
3202
+ */
3203
+ function resolveWarmupDelayMs(env) {
3204
+ return env.VITEST === void 0 ? 2500 : void 0;
3205
+ }
3206
+ /**
3207
+ * Install the interception. Auto mode installs the (pass-through) wrapper now
3208
+ * and decides lazily; mode on arms asynchronously (bootstrap for the auto
3209
+ * preset trims the pool); mode off never installs. Disposal restores the
3210
+ * original export no matter which state the layer reached.
3211
+ * @param deps - the live config/scope/env seams.
3212
+ * @returns the layer handle.
3213
+ */
3214
+ /**
3215
+ * Wrap the event sink so a hostile throwing `onEvent` (volatile-path write,
3216
+ * stage-5 S-1) can never reject `settling` or fail a lookup — events are
3217
+ * observability-only; process-wide resolution outranks them.
3218
+ */
3219
+ function makeSafeEmitter(onEvent) {
3220
+ return (event) => {
3221
+ try {
3222
+ onEvent?.(event);
3223
+ } catch {}
3224
+ };
3225
+ }
3226
+ function installDnsLayer(deps) {
3227
+ const emit = makeSafeEmitter(deps.onEvent);
3228
+ activeLayer?.dispose();
3229
+ const restoreTarget = dnsModule.lookup;
3230
+ const originalLookup = deps.systemLookup ?? restoreTarget;
3231
+ const makeResolver = deps.makeResolver ?? ((nodes) => new DohResolver({
3232
+ nodes,
3233
+ nodeTimeoutMs: deps.config().nodeTimeoutMs,
3234
+ cache: deps.config().cache,
3235
+ poisonRanges: deps.config().poisonRanges
3236
+ }));
3237
+ const bootstrap = deps.bootstrap ?? (async (pool, options) => await bootstrapNodes(pool, {
3238
+ timeoutMs: options.timeoutMs,
3239
+ take: options.take ?? 2
3240
+ }));
3241
+ let installed = false;
3242
+ let disposed = false;
3243
+ let armed = false;
3244
+ let decision = null;
3245
+ let resolver = null;
3246
+ let settling = null;
3247
+ let armingPromise = null;
3248
+ let dohInFlight = 0;
3249
+ let warmupTimer;
3250
+ const env = () => deps.env ?? process.env;
3251
+ function install() {
3252
+ if (installed || disposed) return;
3253
+ installed = true;
3254
+ dnsModule.lookup = layerLookup;
3255
+ }
3256
+ function uninstall() {
3257
+ if (!installed) return;
3258
+ installed = false;
3259
+ dnsModule.lookup = restoreTarget;
3260
+ }
3261
+ /**
3262
+ * Prewarm one pass over the scope hosts (plan 036): each host goes through
3263
+ * the PUBLIC lookup path — the same family-0 cache key the first real
3264
+ * search will use, and the same resolve-event stream into the chain log —
3265
+ * with a no-op consumer discarding the answer. Serial by design so the
3266
+ * dohInFlight self-recursion guard never sees its own warm traffic.
3267
+ */
3268
+ async function prewarm() {
3269
+ if (disposed || !armed || resolver === null) return;
3270
+ for (const host of deps.scopeHosts()) {
3271
+ if (disposed) return;
3272
+ await new Promise((resolve) => {
3273
+ layerLookup(host, { all: true }, () => resolve());
3274
+ });
3275
+ }
3276
+ }
3277
+ /**
3278
+ * The eager boot pass (plan 036): run the lazy machinery ahead of the first
3279
+ * user search. Mode on already armed at install, so the timer only waits
3280
+ * for that arming; auto triggers the canary (a settled decision makes this
3281
+ * a no-op). Prewarm runs unconditionally after — a skip decision leaves it
3282
+ * a harmless system-path pass through the uninstalled wrapper.
3283
+ */
3284
+ function scheduleWarmup() {
3285
+ if (deps.warmupDelayMs === void 0 || disposed) return;
3286
+ warmupTimer = setTimeout(() => {
3287
+ warmupTimer = void 0;
3288
+ (async () => {
3289
+ if (disposed) return;
3290
+ let mode;
3291
+ try {
3292
+ mode = deps.config().mode;
3293
+ } catch {
3294
+ return;
3295
+ }
3296
+ if (mode === "off") return;
3297
+ if (mode === "on") {
3298
+ if (armingPromise !== null) await armingPromise;
3299
+ } else await triggerDetection();
3300
+ if (disposed) return;
3301
+ await prewarm();
3302
+ })();
3303
+ }, deps.warmupDelayMs);
3304
+ }
3305
+ async function arm() {
3306
+ armingPromise ??= (async () => {
3307
+ const config = deps.config();
3308
+ let nodes;
3309
+ if (config.preset === "auto") {
3310
+ const trimmed = await bootstrap(FULL_POOL, {
3311
+ timeoutMs: config.nodeTimeoutMs,
3312
+ take: 2
3313
+ });
3314
+ nodes = trimmed.length > 0 ? trimmed : FULL_POOL;
3315
+ } else nodes = nodesForPreset(config.preset, config.nodes);
3316
+ if (disposed) return;
3317
+ resolver = makeResolver(nodes);
3318
+ armed = true;
3319
+ })();
3320
+ return armingPromise;
3321
+ }
3322
+ function triggerDetection() {
3323
+ if (settling !== null || disposed) return settling ?? Promise.resolve();
3324
+ settling = (async () => {
3325
+ const outcome = await runCanary(deps.scopeHosts(), {
3326
+ systemLookup: deps.canarySystemLookup ?? (async (host) => await systemAddresses(originalLookup, host)),
3327
+ poisonRanges: deps.config().poisonRanges
3328
+ });
3329
+ decision = outcome;
3330
+ emit({
3331
+ kind: "decision",
3332
+ outcome
3333
+ });
3334
+ if (outcome.action === "enable") await arm();
3335
+ else uninstall();
3336
+ })();
3337
+ return settling;
3338
+ }
3339
+ function inScope(hostname) {
3340
+ try {
3341
+ return deps.config().scope === "all" || deps.scopeHosts().includes(hostname);
3342
+ } catch {
3343
+ return false;
3344
+ }
3345
+ }
3346
+ /** Delegate one call to the captured original with the caller's exact arguments. */
3347
+ function delegate(args) {
3348
+ originalLookup.apply(this, args);
3349
+ }
3350
+ function layerLookup(...args) {
3351
+ if (disposed || dohInFlight > 0) return delegate.call(this, args);
3352
+ const [hostname, options, maybeCallback] = args;
3353
+ const callback = typeof options === "function" ? options : maybeCallback;
3354
+ if (typeof hostname !== "string" || typeof callback !== "function" || typeof options === "number" || isIP(hostname) > 0) return delegate.call(this, args);
3355
+ let config;
3356
+ try {
3357
+ config = deps.config();
3358
+ } catch {
3359
+ return delegate.call(this, args);
3360
+ }
3361
+ if (config.mode === "off" || proxySuspendsFor(hostname, env()) || !inScope(hostname)) {
3362
+ if (config.mode !== "off" && proxySuspendsFor(hostname, env())) emit({
3363
+ kind: "suspend",
3364
+ host: hostname
3365
+ });
3366
+ return delegate.call(this, args);
3367
+ }
3368
+ if (!armed) {
3369
+ if (config.mode === "on") arm();
3370
+ else if (decision === null) triggerDetection();
3371
+ return delegate.call(this, args);
3372
+ }
3373
+ const lookupOptions = options ?? {};
3374
+ const family = lookupOptions.family === 4 ? 4 : lookupOptions.family === 6 ? 6 : 0;
3375
+ const startedWallMs = Date.now();
3376
+ (async () => {
3377
+ try {
3378
+ dohInFlight += 1;
3379
+ const resolution = resolver !== null ? await resolver.resolve(hostname, family) : null;
3380
+ if (resolution === null) {
3381
+ emit({
3382
+ kind: "fallback",
3383
+ host: hostname,
3384
+ reason: "doh-dead"
3385
+ });
3386
+ return delegate.call(this, args);
3387
+ }
3388
+ if (resolution.negative) {
3389
+ const error = Object.assign(/* @__PURE__ */ new Error(`getaddrinfo ENOTFOUND ${hostname}`), { code: "ENOTFOUND" });
3390
+ emit({
3391
+ kind: "fallback",
3392
+ host: hostname,
3393
+ reason: "neg"
3394
+ });
3395
+ callback(error);
3396
+ return;
3397
+ }
3398
+ let candidates = resolution.addresses;
3399
+ if (family === 4 || family === 6) candidates = candidates.filter((entry) => entry.family === family);
3400
+ if (candidates.length === 0) {
3401
+ emit({
3402
+ kind: "fallback",
3403
+ host: hostname,
3404
+ reason: "error"
3405
+ });
3406
+ return delegate.call(this, args);
3407
+ }
3408
+ let kept = candidates;
3409
+ let probeOutcome = null;
3410
+ if (config.probe.enabled) {
3411
+ const probeBudget = Math.max(50, config.nodeTimeoutMs - (Date.now() - startedWallMs));
3412
+ const probe = new EgressProbe({
3413
+ port: 443,
3414
+ timeoutMs: Math.min(config.probe.timeoutMs, probeBudget),
3415
+ cacheTtlS: config.probe.cacheTtlS,
3416
+ method: config.probe.method,
3417
+ hostname
3418
+ });
3419
+ const publicCandidates = candidates.filter((entry) => isPublicAddress(entry.address));
3420
+ dohInFlight -= 1;
3421
+ try {
3422
+ if (publicCandidates.length > 0) {
3423
+ const verdict = await probe.filterReachable(publicCandidates.map((entry) => entry.address));
3424
+ const verdictKept = new Set(verdict.kept);
3425
+ kept = candidates.filter((entry) => !isPublicAddress(entry.address) || verdictKept.has(entry.address));
3426
+ probeOutcome = verdict;
3427
+ }
3428
+ } finally {
3429
+ dohInFlight += 1;
3430
+ }
3431
+ }
3432
+ emit({
3433
+ kind: "resolve",
3434
+ host: hostname,
3435
+ via: resolution.via,
3436
+ latencyMs: resolution.latencyMs,
3437
+ kept: kept.length,
3438
+ dropped: resolution.droppedPoisoned.length,
3439
+ probeDropped: probeOutcome?.dropped ?? []
3440
+ });
3441
+ if (lookupOptions.all === true) callback(null, kept.map((entry) => ({
3442
+ address: entry.address,
3443
+ family: entry.family
3444
+ })));
3445
+ else callback(null, kept[0].address, kept[0].family);
3446
+ } catch {
3447
+ emit({
3448
+ kind: "fallback",
3449
+ host: hostname,
3450
+ reason: "error"
3451
+ });
3452
+ delegate.call(this, args);
3453
+ } finally {
3454
+ dohInFlight -= 1;
3455
+ }
3456
+ })();
3457
+ }
3458
+ const layer = {
3459
+ lookup: layerLookup,
3460
+ state: () => ({
3461
+ armed,
3462
+ decision,
3463
+ proxyActive: [
3464
+ "HTTPS_PROXY",
3465
+ "https_proxy",
3466
+ "HTTP_PROXY",
3467
+ "http_proxy",
3468
+ "ALL_PROXY",
3469
+ "all_proxy"
3470
+ ].some((name) => (env()[name] ?? "").trim().length > 0)
3471
+ }),
3472
+ whenSettled: async () => {
3473
+ if (settling !== null) await settling;
3474
+ },
3475
+ whenArmed: async () => {
3476
+ if (armingPromise !== null) await armingPromise;
3477
+ },
3478
+ recheck: async () => {
3479
+ if (disposed) throw new Error("dns layer disposed");
3480
+ decision = null;
3481
+ settling = null;
3482
+ install();
3483
+ await triggerDetection();
3484
+ if (decision === null) throw new Error("dns canary decision missing after recheck");
3485
+ return decision;
3486
+ },
3487
+ invalidateHost: (hostname) => {
3488
+ resolver?.invalidate?.(hostname);
3489
+ },
3490
+ resolveForGuard: async (hostname) => {
3491
+ if (isIP(hostname) > 0) return [hostname];
3492
+ let config;
3493
+ try {
3494
+ config = deps.config();
3495
+ } catch {
3496
+ return await systemAddresses(originalLookup, hostname);
3497
+ }
3498
+ if (config.mode === "off" || !armed || resolver === null || proxySuspendsFor(hostname, env()) || !inScope(hostname)) return await systemAddresses(originalLookup, hostname);
3499
+ dohInFlight += 1;
3500
+ try {
3501
+ const resolution = await resolver.resolve(hostname, 0);
3502
+ if (resolution === null) return await systemAddresses(originalLookup, hostname);
3503
+ if (resolution.negative) throw Object.assign(/* @__PURE__ */ new Error(`getaddrinfo ENOTFOUND ${hostname}`), { code: "ENOTFOUND" });
3504
+ return resolution.addresses.map((entry) => entry.address);
3505
+ } finally {
3506
+ dohInFlight -= 1;
3507
+ }
3508
+ },
3509
+ dispose: () => {
3510
+ disposed = true;
3511
+ if (warmupTimer !== void 0) {
3512
+ clearTimeout(warmupTimer);
3513
+ warmupTimer = void 0;
3514
+ }
3515
+ uninstall();
3516
+ armed = false;
3517
+ resolver = null;
3518
+ decision = null;
3519
+ settling = null;
3520
+ if (activeLayer === layer) activeLayer = null;
3521
+ }
3522
+ };
3523
+ activeLayer = layer;
3524
+ const initialMode = deps.config().mode;
3525
+ if (initialMode === "off") {} else {
3526
+ install();
3527
+ if (initialMode === "on") arm();
3528
+ }
3529
+ scheduleWarmup();
3530
+ return layer;
3531
+ }
3532
+ //#endregion
3533
+ //#region src/dns/observability.ts
3534
+ /**
3535
+ * Build the host sanitizer: non-sensitive hosts pass verbatim (the member
3536
+ * baseURLs are configuration, not secrets); sensitive hosts — any host while
3537
+ * `scope: 'all'` that is not a member host — reduce to a stable 4-hex prefix
3538
+ * plus the last two labels, so traces stay groupable without leaking names.
3539
+ * @param isSensitiveHost - live predicate (scope=all && not a member host).
3540
+ * @returns the sanitizing function every surface routes through.
3541
+ */
3542
+ function sanitizeHostFactory(isSensitiveHost) {
3543
+ return (host) => {
3544
+ if (!isSensitiveHost(host)) return host;
3545
+ let hash = 2166136261;
3546
+ for (let i = 0; i < host.length; i++) {
3547
+ hash ^= host.charCodeAt(i);
3548
+ hash = Math.imul(hash, 16777619) >>> 0;
3549
+ }
3550
+ const labels = host.split(".").filter((label) => label.length > 0);
3551
+ const tail = labels.length >= 2 ? `${labels.at(-2)}.${labels.at(-1)}` : labels.at(-1) ?? "host";
3552
+ return `${hash.toString(16).slice(0, 4).padStart(4, "0")}…${tail}`;
3553
+ };
3554
+ }
3555
+ /** Render one entry as the single-line log form. */
3556
+ function renderLine(entry) {
3557
+ const parts = [`[dshws-dns] ${entry.kind}`];
3558
+ if (entry.host.length > 0) parts.push(`host=${entry.host}`);
3559
+ if (entry.via !== void 0) parts.push(`via=${entry.via}`);
3560
+ if (entry.kept !== void 0) parts.push(`kept=${entry.kept}`);
3561
+ if (entry.dropped !== void 0 && entry.dropped > 0) parts.push(`dropped=${entry.dropped}`);
3562
+ if (entry.detail !== void 0 && entry.detail.length > 0) parts.push(entry.detail);
3563
+ if (entry.latencyMs !== void 0) parts.push(`latencyMs=${entry.latencyMs}`);
3564
+ if (entry.code !== void 0) parts.push(`code=${entry.code}`);
3565
+ return parts.join(" ");
3566
+ }
3567
+ /** The sink: one instance owns the ring; the log seam goes to the chain-log line and the host logger alike. */
3568
+ var DnsObservability = class {
3569
+ #log;
3570
+ #ringLimit;
3571
+ #now;
3572
+ #ring = [];
3573
+ constructor(options) {
3574
+ this.#log = options.log;
3575
+ this.#ringLimit = options.ringLimit ?? 50;
3576
+ this.#now = options.now ?? Date.now;
3577
+ }
3578
+ /**
3579
+ * Record one layer event: sanitize the host, derive the diagnostic code,
3580
+ * append the ring entries (a doh-dead fallback yields the
3581
+ * DOH_UNREACHABLE → FALLBACK_SYSTEM pair), and emit the log lines.
3582
+ * @param event - the layer event.
3583
+ * @param sanitize - the host sanitizer (see {@link sanitizeHostFactory}).
3584
+ */
3585
+ record(event, sanitize) {
3586
+ for (const entry of this.#entriesFor(event, sanitize)) {
3587
+ this.#ring.push(entry);
3588
+ while (this.#ring.length > this.#ringLimit) this.#ring.shift();
3589
+ this.#log(renderLine(entry));
3590
+ }
3591
+ }
3592
+ /** The sanitized ring, oldest first. */
3593
+ trace() {
3594
+ return [...this.#ring];
3595
+ }
3596
+ #entriesFor(event, sanitize) {
3597
+ const at = this.#now();
3598
+ switch (event.kind) {
3599
+ case "resolve": {
3600
+ const probeDrop = event.probeDropped.length;
3601
+ const probeAllFailed = probeDrop > 0 && probeDrop === event.kept;
3602
+ return [{
3603
+ at,
3604
+ kind: "resolve",
3605
+ host: sanitize(event.host),
3606
+ via: event.via,
3607
+ latencyMs: event.latencyMs,
3608
+ kept: event.kept,
3609
+ dropped: event.dropped,
3610
+ ...probeDrop > 0 ? { detail: `probeDrop=${probeDrop}` } : {},
3611
+ ...probeAllFailed ? { code: DNS_ERROR_CODES.probeAllFailed } : {}
3612
+ }];
3613
+ }
3614
+ case "decision": {
3615
+ const code = event.outcome.verdict === "poisoned" ? DNS_ERROR_CODES.autoEnabled : event.outcome.verdict === "inconclusive" ? DNS_ERROR_CODES.detectInconclusive : DNS_ERROR_CODES.autoSkipped;
3616
+ const hits = event.outcome.hits.map((hit) => `${sanitize(hit.host)}→${hit.addresses.join(",")}`).join(" ");
3617
+ const failures = event.outcome.failures.length > 0 ? ` failures=${event.outcome.failures.map((failure) => `${sanitize(failure.host)}:${failure.reason}`).join(",")}` : "";
3618
+ return [{
3619
+ at,
3620
+ kind: "decision",
3621
+ host: "",
3622
+ code,
3623
+ detail: `${event.outcome.action}/${event.outcome.verdict}${hits.length > 0 ? ` hits=${hits}` : ""}${failures}`
3624
+ }];
3625
+ }
3626
+ case "fallback":
3627
+ if (event.reason === "doh-dead") return [{
3628
+ at,
3629
+ kind: "fallback",
3630
+ host: sanitize(event.host),
3631
+ code: DNS_ERROR_CODES.dohUnreachable,
3632
+ detail: "reason=doh-dead"
3633
+ }, {
3634
+ at,
3635
+ kind: "fallback",
3636
+ host: sanitize(event.host),
3637
+ code: DNS_ERROR_CODES.fallbackSystem,
3638
+ detail: "reason=doh-dead"
3639
+ }];
3640
+ return [{
3641
+ at,
3642
+ kind: "fallback",
3643
+ host: sanitize(event.host),
3644
+ detail: `reason=${event.reason}`
3645
+ }];
3646
+ case "suspend": return [{
3647
+ at,
3648
+ kind: "suspend",
3649
+ host: sanitize(event.host),
3650
+ code: DNS_ERROR_CODES.suspendedProxy
3651
+ }];
3652
+ }
3653
+ }
3654
+ };
3655
+ //#endregion
3656
+ //#region src/dns/remote.ts
3657
+ /** The wire namespace this Remote joins (same namespace as the key-count face). */
3658
+ const DNS_REMOTE_NAMESPACE = "dshws-websearch";
3659
+ /**
3660
+ * Host service for the DNS resilience UI. The gateway invokes Remote methods
3661
+ * with the context's traceable proxy as the receiver, so method bodies read
3662
+ * only public members — no `#private` state.
3663
+ */
3664
+ var DshWsDnsRemote = class extends TypertRemoteService {
3665
+ ports;
3666
+ /** @param ctx - owning Cordis Context (the plugin's fiber owns disposal). */
3667
+ constructor(ctx, ports) {
3668
+ super(ctx, "dshwsDns", { namespace: DNS_REMOTE_NAMESPACE });
3669
+ this.ports = ports;
3670
+ for (const initializer of dnsRemoteInitializers) initializer.call(this);
3671
+ }
3672
+ /** Compose the current status for the settings block. */
3673
+ async describeDnsStatus() {
3674
+ return snapshotOf(this.ports);
3675
+ }
3676
+ /** The sanitized trace ring, oldest first. */
3677
+ async readDnsTrace() {
3678
+ return this.ports.trace();
3679
+ }
3680
+ /** Force a fresh canary pass and answer the refreshed status. */
3681
+ async requestDnsRecheck() {
3682
+ await this.ports.recheck();
3683
+ return snapshotOf(this.ports);
3684
+ }
3685
+ };
3686
+ /**
3687
+ * Compose the status snapshot. A module function, not a class member: the
3688
+ * gateway invokes Remote methods with the context's traceable proxy as the
3689
+ * receiver, and private-member access through that proxy throws (the
3690
+ * key-counts Remote's documented rule — DshWsDnsRemote violated it and the
3691
+ * stage-T4 retest caught both status methods failing with
3692
+ * "Receiver must be an instance of class anonymous" while the public-only
3693
+ * readDnsTrace worked).
3694
+ * @param ports - the Remote's public ports.
3695
+ * @returns the composed, sanitized status face.
3696
+ */
3697
+ function snapshotOf(ports) {
3698
+ const state = ports.status();
3699
+ const decision = state.decision === null ? null : {
3700
+ action: state.decision.action,
3701
+ verdict: state.decision.verdict,
3702
+ hits: state.decision.hits.map((hit) => ({
3703
+ host: ports.sanitize(hit.host),
3704
+ addresses: hit.addresses
3705
+ })),
3706
+ failures: state.decision.failures.map((failure) => ({
3707
+ host: ports.sanitize(failure.host),
3708
+ reason: failure.reason
3709
+ }))
3710
+ };
3711
+ return {
3712
+ ...ports.config(),
3713
+ armed: state.armed,
3714
+ proxyActive: state.proxyActive,
3715
+ decision
3716
+ };
3717
+ }
3718
+ /** Constructor-phase initializers captured by the runtime `Remote` marking below (rolldown keeps stage-3 decorators out). */
3719
+ const dnsRemoteInitializers = [];
3720
+ for (const method of [
3721
+ "describeDnsStatus",
3722
+ "readDnsTrace",
3723
+ "requestDnsRecheck"
3724
+ ]) Remote(Object.getOwnPropertyDescriptor(DshWsDnsRemote.prototype, method).value, {
3725
+ kind: "method",
3726
+ name: method,
3727
+ static: false,
3728
+ private: false,
3729
+ access: {
3730
+ has: (target) => target[method] !== void 0,
3731
+ get: (target) => target[method]
3732
+ },
3733
+ addInitializer: (initializer) => {
3734
+ dnsRemoteInitializers.push(initializer);
3735
+ },
3736
+ metadata: {}
3737
+ });
3738
+ //#endregion
2260
3739
  //#region src/index.ts
2261
3740
  /** Cordis plugin name used by loader diagnostics. */
2262
3741
  const name = "dsh-websearch";
@@ -2313,8 +3792,18 @@ function apply(ctx, config) {
2313
3792
  const credentials = ctx.credentials;
2314
3793
  const fileLog = createChainFileLog(config.chainLogFile !== false);
2315
3794
  const fetchTakeoverActive = () => live.current().fetchTakeover !== false;
2316
- let fetchChainInstance;
2317
- ctx.web.registerFetchProvider(new FetchGateProvider(fetchTakeoverActive, (request, signal) => (fetchChainInstance ?? throwMissingChain()).fetch(request, signal)));
3795
+ const dnsScopeHosts = () => {
3796
+ const current = live.current();
3797
+ const hosts = /* @__PURE__ */ new Set();
3798
+ for (const base of [
3799
+ current.tavily.baseURL ?? "https://api.tavily.com",
3800
+ current.exa.baseURL ?? "https://api.exa.ai",
3801
+ current.firecrawl.baseURL ?? "https://api.firecrawl.dev",
3802
+ current.anysearch.baseURL ?? "https://api.anysearch.com",
3803
+ current.deepseek.baseURL ?? "https://api.deepseek.com/anthropic/v1"
3804
+ ]) if (URL.canParse(base)) hosts.add(new URL(base).hostname.toLowerCase());
3805
+ return [...hosts];
3806
+ };
2318
3807
  ctx.inject(["settings"], (settingsCtx) => {
2319
3808
  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
3809
  clearAllSearchOnlyPresets();
@@ -2325,6 +3814,53 @@ function apply(ctx, config) {
2325
3814
  ctx.logger.info(message);
2326
3815
  fileLog(message);
2327
3816
  };
3817
+ /** S36 (plan 036): one member id -> its live resolved base-URL host (for cache invalidation feedback). */
3818
+ const dnsHostOfMember = (memberId) => {
3819
+ const key = MEMBER_ID_TO_KEY[memberId];
3820
+ const section = live.current()[key];
3821
+ const fallback = {
3822
+ tavily: TAVILY_DEFAULT_BASE_URL,
3823
+ exa: EXA_DEFAULT_BASE_URL,
3824
+ firecrawl: FIRECRAWL_DEFAULT_BASE_URL,
3825
+ anysearch: ANYSEARCH_DEFAULT_BASE_URL,
3826
+ deepseek: DEEPSEEK_DEFAULT_BASE_URL
3827
+ }[key];
3828
+ const base = section?.baseURL ?? fallback;
3829
+ if (base === void 0) return void 0;
3830
+ return URL.canParse(base) ? new URL(base).hostname.toLowerCase() : void 0;
3831
+ };
3832
+ const dnsSanitize = sanitizeHostFactory((host) => live.current().dns.scope === "all" && !dnsScopeHosts().includes(host));
3833
+ const dnsObservability = new DnsObservability({ log });
3834
+ const dnsLayer = installDnsLayer({
3835
+ config: () => live.current().dns,
3836
+ scopeHosts: dnsScopeHosts,
3837
+ onEvent: (event) => dnsObservability.record(event, dnsSanitize),
3838
+ warmupDelayMs: resolveWarmupDelayMs(process.env)
3839
+ });
3840
+ ctx.effect(() => () => dnsLayer.dispose());
3841
+ new DshWsDnsRemote(ctx, {
3842
+ status: () => {
3843
+ const state = dnsLayer.state();
3844
+ return {
3845
+ armed: state.armed,
3846
+ decision: state.decision,
3847
+ proxyActive: state.proxyActive
3848
+ };
3849
+ },
3850
+ config: () => {
3851
+ const dns = live.current().dns;
3852
+ return {
3853
+ mode: dns.mode,
3854
+ scope: dns.scope,
3855
+ preset: dns.preset
3856
+ };
3857
+ },
3858
+ trace: () => dnsObservability.trace(),
3859
+ recheck: () => dnsLayer.recheck(),
3860
+ sanitize: dnsSanitize
3861
+ });
3862
+ let fetchChainInstance;
3863
+ ctx.web.registerFetchProvider(new FetchGateProvider(fetchTakeoverActive, (request, signal) => (fetchChainInstance ?? throwMissingChain()).fetch(request, signal), dnsLayer.resolveForGuard));
2328
3864
  for (const member of [
2329
3865
  resolved.tavily,
2330
3866
  resolved.exa,
@@ -2387,12 +3923,17 @@ function apply(ctx, config) {
2387
3923
  const readyToolMemberCount = () => {
2388
3924
  const current = live.current();
2389
3925
  return ORDERABLE_SEARCH_MEMBER_ORDER.filter((id) => {
2390
- const key = id.replace("dshws-", "");
3926
+ const key = MEMBER_ID_TO_KEY[id];
2391
3927
  return current[key].enabled && pools[key].ready();
2392
3928
  }).length;
2393
3929
  };
3930
+ const onMemberConnectFailure = (memberId) => {
3931
+ const host = dnsHostOfMember(memberId);
3932
+ if (host !== void 0) dnsLayer.invalidateHost(host);
3933
+ };
2394
3934
  ctx.web.registerSearchProvider(new ChainSearchProvider({
2395
3935
  members: searchMembers.toResolver(),
3936
+ onMemberConnectFailure,
2396
3937
  get order() {
2397
3938
  const current = live.current();
2398
3939
  const chain = [...current.searchChain];
@@ -2444,11 +3985,12 @@ function apply(ctx, config) {
2444
3985
  tavily,
2445
3986
  anysearch
2446
3987
  ]) {
2447
- const key = member.id.replace("dshws-", "");
3988
+ const key = MEMBER_ID_TO_KEY[member.id];
2448
3989
  fetchMembers.register(member, gates(key, pools[key]));
2449
3990
  }
2450
3991
  fetchChainInstance = new ChainFetchProvider({
2451
3992
  members: fetchMembers.toResolver(),
3993
+ onMemberConnectFailure,
2452
3994
  get order() {
2453
3995
  return [...live.current().fetchChain];
2454
3996
  },