@herbertgao/pi-extensions 2026.10.14 → 2026.10.15

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.
Files changed (41) hide show
  1. package/README.md +8 -6
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/node_modules/@narumitw/pi-btw/README.md +1 -1
  4. package/node_modules/@narumitw/pi-btw/dist/index.ts +77 -64
  5. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
  6. package/node_modules/@narumitw/pi-btw/docs/core-alignment.md +10 -2
  7. package/node_modules/@narumitw/pi-btw/package.json +5 -5
  8. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +83 -63
  9. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  10. package/node_modules/pi-web-access/CHANGELOG.md +40 -0
  11. package/node_modules/pi-web-access/README.md +96 -22
  12. package/node_modules/pi-web-access/brave-rate-limit.ts +2 -2
  13. package/node_modules/pi-web-access/curator-page.ts +3 -1
  14. package/node_modules/pi-web-access/curator-server.ts +1 -0
  15. package/node_modules/pi-web-access/dist/index.js +2607 -1674
  16. package/node_modules/pi-web-access/dist/mcp-cli.js +1119 -327
  17. package/node_modules/pi-web-access/duckduckgo-rate-limit.ts +95 -0
  18. package/node_modules/pi-web-access/duckduckgo.ts +51 -45
  19. package/node_modules/pi-web-access/exa.ts +48 -6
  20. package/node_modules/pi-web-access/extract.ts +2 -2
  21. package/node_modules/pi-web-access/fetch-params.ts +5 -4
  22. package/node_modules/pi-web-access/field-extract.ts +347 -0
  23. package/node_modules/pi-web-access/gemini-search.ts +151 -13
  24. package/node_modules/pi-web-access/index.ts +128 -125
  25. package/node_modules/pi-web-access/mistral-search.ts +1 -1
  26. package/node_modules/pi-web-access/ninerouter.ts +92 -0
  27. package/node_modules/pi-web-access/offtopic-judge.ts +72 -0
  28. package/node_modules/pi-web-access/openai-search.ts +36 -10
  29. package/node_modules/pi-web-access/package.json +1 -1
  30. package/node_modules/pi-web-access/perplexity.ts +1 -0
  31. package/node_modules/pi-web-access/query-rewrite.ts +39 -13
  32. package/node_modules/pi-web-access/source-check.ts +31 -15
  33. package/node_modules/pi-web-access/summary-model-scope.ts +19 -1
  34. package/node_modules/pi-web-access/summary-review.ts +13 -20
  35. package/node_modules/pi-web-access/tool-arguments.ts +1 -1
  36. package/node_modules/pi-web-access/upgrade-notice.ts +47 -0
  37. package/node_modules/pi-web-access/utils.ts +26 -1
  38. package/node_modules/pi-web-access/web-tool-contract.ts +4 -1
  39. package/node_modules/pi-web-access/web-tool-core.ts +99 -19
  40. package/node_modules/pi-web-access/xai-search.ts +3 -3
  41. package/package.json +6 -6
@@ -300,6 +300,29 @@ function isLoopbackHostname(hostnameValue) {
300
300
  const normalized = hostnameValue.replace(/^\[|\]$/g, "").replace(/\.$/, "").toLowerCase();
301
301
  return normalized === "localhost" || normalized === "::1" || isIP(normalized) === 4 && normalized.split(".", 1)[0] === "127";
302
302
  }
303
+ function isRecord(value) {
304
+ return typeof value === "object" && value !== null && !Array.isArray(value);
305
+ }
306
+ function allowsHttpBaseUrls() {
307
+ const environmentValue = process.env.PI_WEB_ACCESS_ALLOW_HTTP_BASE_URLS;
308
+ if (environmentValue !== void 0) {
309
+ const value2 = environmentValue.trim().toLowerCase();
310
+ if (value2 === "true" || value2 === "1") return true;
311
+ if (value2 === "false" || value2 === "0") return false;
312
+ throw new Error("Invalid configuration: PI_WEB_ACCESS_ALLOW_HTTP_BASE_URLS must be true, false, 1, or 0");
313
+ }
314
+ const path = getWebSearchConfigPath();
315
+ if (!existsSync2(path)) return false;
316
+ let raw;
317
+ try {
318
+ raw = JSON.parse(readFileSync(path, "utf-8"));
319
+ } catch (err) {
320
+ throw new Error(`Failed to parse ${path}: ${err instanceof Error ? err.message : String(err)}`);
321
+ }
322
+ const value = isRecord(raw) ? raw.allowHttpBaseUrls : void 0;
323
+ if (value !== void 0 && typeof value !== "boolean") throw new Error(`allowHttpBaseUrls in ${path} must be a boolean`);
324
+ return value === true;
325
+ }
303
326
  function resolveApiBaseUrl(options) {
304
327
  const fromEnvironment = options.environmentValue !== void 0;
305
328
  const value = fromEnvironment ? options.environmentValue : options.configuredValue;
@@ -314,7 +337,7 @@ function resolveApiBaseUrl(options) {
314
337
  } catch {
315
338
  throw new Error(`${source} must be an absolute HTTP(S) URL`);
316
339
  }
317
- if (url.protocol !== "https:" && (url.protocol !== "http:" || !isLoopbackHostname(url.hostname))) {
340
+ if (url.protocol !== "https:" && (url.protocol !== "http:" || !isLoopbackHostname(url.hostname) && !allowsHttpBaseUrls())) {
318
341
  throw new Error(`${source} must be an absolute HTTPS URL`);
319
342
  }
320
343
  if (url.username || url.password) {
@@ -4918,23 +4941,23 @@ var init_ollama = __esm({
4918
4941
  });
4919
4942
 
4920
4943
  // deepseek.ts
4921
- import { existsSync as existsSync41, readFileSync as readFileSync41 } from "node:fs";
4922
- function loadConfig36() {
4944
+ import { existsSync as existsSync42, readFileSync as readFileSync42 } from "node:fs";
4945
+ function loadConfig37() {
4923
4946
  if (cachedConfig35) return cachedConfig35;
4924
- if (!existsSync41(CONFIG_PATH38)) {
4947
+ if (!existsSync42(CONFIG_PATH39)) {
4925
4948
  cachedConfig35 = {};
4926
4949
  return cachedConfig35;
4927
4950
  }
4928
- const raw = readFileSync41(CONFIG_PATH38, "utf-8");
4951
+ const raw = readFileSync42(CONFIG_PATH39, "utf-8");
4929
4952
  let parsed;
4930
4953
  try {
4931
4954
  parsed = JSON.parse(raw);
4932
4955
  } catch (err) {
4933
4956
  const message = err instanceof Error ? err.message : String(err);
4934
- throw new Error(`Failed to parse ${CONFIG_PATH38}: ${message}`);
4957
+ throw new Error(`Failed to parse ${CONFIG_PATH39}: ${message}`);
4935
4958
  }
4936
4959
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
4937
- throw new Error(`Invalid config in ${CONFIG_PATH38}: expected a JSON object`);
4960
+ throw new Error(`Invalid config in ${CONFIG_PATH39}: expected a JSON object`);
4938
4961
  }
4939
4962
  cachedConfig35 = parsed;
4940
4963
  return cachedConfig35;
@@ -4942,14 +4965,14 @@ function loadConfig36() {
4942
4965
  async function requireApiKey15(signal) {
4943
4966
  const apiKey = await resolveCredential({
4944
4967
  provider: "DeepSeek",
4945
- configuredValue: loadConfig36().deepseekApiKey,
4968
+ configuredValue: loadConfig37().deepseekApiKey,
4946
4969
  environmentValue: process.env.DEEPSEEK_API_KEY,
4947
4970
  signal
4948
4971
  });
4949
4972
  if (!apiKey) {
4950
4973
  throw new Error(
4951
4974
  `DeepSeek API key not found. Either:
4952
- 1. Create ${CONFIG_PATH38} with { "deepseekApiKey": "your-key" }
4975
+ 1. Create ${CONFIG_PATH39} with { "deepseekApiKey": "your-key" }
4953
4976
  2. Set DEEPSEEK_API_KEY environment variable
4954
4977
  Get a key at https://platform.deepseek.com/api_keys`
4955
4978
  );
@@ -5050,7 +5073,7 @@ function describeError2(body) {
5050
5073
  return body;
5051
5074
  }
5052
5075
  function isDeepSeekAvailable() {
5053
- return hasCredentialSource({ provider: "DeepSeek", configuredValue: loadConfig36().deepseekApiKey, environmentValue: process.env.DEEPSEEK_API_KEY });
5076
+ return hasCredentialSource({ provider: "DeepSeek", configuredValue: loadConfig37().deepseekApiKey, environmentValue: process.env.DEEPSEEK_API_KEY });
5054
5077
  }
5055
5078
  async function searchWithDeepSeek(query, options = {}) {
5056
5079
  const builtQuery = buildQuery8(query, options);
@@ -5061,7 +5084,7 @@ async function searchWithDeepSeek(query, options = {}) {
5061
5084
  let response;
5062
5085
  let entries;
5063
5086
  try {
5064
- response = await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek", DEEPSEEK_SEARCH_URL, loadConfig36().deepseekBaseUrl), {
5087
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek", DEEPSEEK_SEARCH_URL, loadConfig37().deepseekBaseUrl), {
5065
5088
  method: "POST",
5066
5089
  headers: {
5067
5090
  Accept: "application/json",
@@ -5120,7 +5143,7 @@ async function searchWithDeepSeek(query, options = {}) {
5120
5143
  results.push({
5121
5144
  title,
5122
5145
  url: resultUrl.href,
5123
- snippet: (text5(entry.summary) || text5(entry.snippet)).slice(0, MAX_SNIPPET_CHARS4)
5146
+ snippet: (text5(entry.summary) || text5(entry.snippet)).slice(0, MAX_SNIPPET_CHARS5)
5124
5147
  });
5125
5148
  if (options.includeContent) {
5126
5149
  const content = typeof entry.content === "string" ? entry.content.trim() : "";
@@ -5146,7 +5169,7 @@ async function extractWithDeepSeek(url, signal, options = {}) {
5146
5169
  domainPolicy: loadFetchContentDomainPolicy(),
5147
5170
  ...options.lookup ? { lookup: options.lookup } : {}
5148
5171
  });
5149
- const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek", DEEPSEEK_FETCH_URL, loadConfig36().deepseekBaseUrl), {
5172
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek", DEEPSEEK_FETCH_URL, loadConfig37().deepseekBaseUrl), {
5150
5173
  method: "POST",
5151
5174
  headers: {
5152
5175
  Accept: "application/json",
@@ -5201,7 +5224,7 @@ async function extractWithDeepSeek(url, signal, options = {}) {
5201
5224
  throw redactedError;
5202
5225
  }
5203
5226
  }
5204
- var DEEPSEEK_SEARCH_URL, DEEPSEEK_FETCH_URL, CONFIG_PATH38, SEARCH_TIMEOUT_MS33, FETCH_TIMEOUT_MS2, MAX_QUERY_CHARS, MAX_SNIPPET_CHARS4, RECENCY_DAYS2, cachedConfig35, ERROR_TITLE;
5227
+ var DEEPSEEK_SEARCH_URL, DEEPSEEK_FETCH_URL, CONFIG_PATH39, SEARCH_TIMEOUT_MS33, FETCH_TIMEOUT_MS2, MAX_QUERY_CHARS, MAX_SNIPPET_CHARS5, RECENCY_DAYS2, cachedConfig35, ERROR_TITLE;
5205
5228
  var init_deepseek = __esm({
5206
5229
  "deepseek.ts"() {
5207
5230
  init_activity();
@@ -5213,11 +5236,11 @@ var init_deepseek = __esm({
5213
5236
  init_utils();
5214
5237
  DEEPSEEK_SEARCH_URL = "https://api.deepseek.com/v1/tools/search";
5215
5238
  DEEPSEEK_FETCH_URL = "https://api.deepseek.com/v1/tools/fetch";
5216
- CONFIG_PATH38 = getWebSearchConfigPath();
5239
+ CONFIG_PATH39 = getWebSearchConfigPath();
5217
5240
  SEARCH_TIMEOUT_MS33 = 3e4;
5218
5241
  FETCH_TIMEOUT_MS2 = 6e4;
5219
5242
  MAX_QUERY_CHARS = 128;
5220
- MAX_SNIPPET_CHARS4 = 800;
5243
+ MAX_SNIPPET_CHARS5 = 800;
5221
5244
  RECENCY_DAYS2 = {
5222
5245
  day: 1,
5223
5246
  week: 7,
@@ -5230,7 +5253,7 @@ var init_deepseek = __esm({
5230
5253
  });
5231
5254
 
5232
5255
  // auth-fetch.ts
5233
- import { existsSync as existsSync44, readFileSync as readFileSync44 } from "node:fs";
5256
+ import { existsSync as existsSync45, readFileSync as readFileSync45 } from "node:fs";
5234
5257
  function resolveAuthFetchProfile(request) {
5235
5258
  const profiles = loadAuthFetchProfiles();
5236
5259
  if (profiles.length === 0) {
@@ -5268,8 +5291,8 @@ function authFetchRedirectGuard(profile, from, to) {
5268
5291
  }
5269
5292
  }
5270
5293
  function loadAuthFetchProfiles() {
5271
- if (!existsSync44(WEB_SEARCH_CONFIG_PATH2)) return [];
5272
- const raw = readFileSync44(WEB_SEARCH_CONFIG_PATH2, "utf-8");
5294
+ if (!existsSync45(WEB_SEARCH_CONFIG_PATH2)) return [];
5295
+ const raw = readFileSync45(WEB_SEARCH_CONFIG_PATH2, "utf-8");
5273
5296
  let parsed;
5274
5297
  try {
5275
5298
  const value = JSON.parse(raw);
@@ -5669,20 +5692,20 @@ var init_rsc_extract = __esm({
5669
5692
  });
5670
5693
 
5671
5694
  // datalab-pdf-extract.ts
5672
- import { existsSync as existsSync45, readFileSync as readFileSync46 } from "node:fs";
5673
- function loadConfig38() {
5695
+ import { existsSync as existsSync46, readFileSync as readFileSync47 } from "node:fs";
5696
+ function loadConfig39() {
5674
5697
  if (cachedConfig37) return cachedConfig37;
5675
- if (!existsSync45(CONFIG_PATH41)) {
5698
+ if (!existsSync46(CONFIG_PATH42)) {
5676
5699
  cachedConfig37 = {};
5677
5700
  return cachedConfig37;
5678
5701
  }
5679
- const rawText = readFileSync46(CONFIG_PATH41, "utf-8");
5702
+ const rawText = readFileSync47(CONFIG_PATH42, "utf-8");
5680
5703
  try {
5681
5704
  cachedConfig37 = JSON.parse(rawText);
5682
5705
  return cachedConfig37;
5683
5706
  } catch (err) {
5684
5707
  const message = err instanceof Error ? err.message : String(err);
5685
- throw new Error(`Failed to parse ${CONFIG_PATH41}: ${message}`);
5708
+ throw new Error(`Failed to parse ${CONFIG_PATH42}: ${message}`);
5686
5709
  }
5687
5710
  }
5688
5711
  function normalizeString(value) {
@@ -5697,14 +5720,14 @@ function normalizeFileId(value) {
5697
5720
  function isDatalabApiAvailable() {
5698
5721
  return hasCredentialSource({
5699
5722
  provider: "Datalab",
5700
- configuredValue: loadConfig38().datalabApiKey,
5723
+ configuredValue: loadConfig39().datalabApiKey,
5701
5724
  environmentValue: process.env.DATALAB_API_KEY
5702
5725
  });
5703
5726
  }
5704
5727
  async function getDatalabApiKey(signal) {
5705
5728
  return resolveCredential({
5706
5729
  provider: "Datalab",
5707
- configuredValue: loadConfig38().datalabApiKey,
5730
+ configuredValue: loadConfig39().datalabApiKey,
5708
5731
  environmentValue: process.env.DATALAB_API_KEY,
5709
5732
  signal
5710
5733
  });
@@ -5746,7 +5769,7 @@ async function extractPDFViaDatalab(buffer, options) {
5746
5769
  }
5747
5770
  const mode = options.mode ?? normalizeDatalabMode(process.env.DATALAB_MODE);
5748
5771
  const processingLocation = options.processingLocation ?? getDatalabProcessingLocation();
5749
- const timeoutMs = typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? Math.floor(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
5772
+ const timeoutMs = typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? Math.floor(options.timeoutMs) : DEFAULT_TIMEOUT_MS2;
5750
5773
  const deadline = Date.now() + timeoutMs;
5751
5774
  const upload = await requestUploadUrl({
5752
5775
  apiKey,
@@ -6029,19 +6052,19 @@ async function readResponseText(response) {
6029
6052
  function datalabFilename(title) {
6030
6053
  return title.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "document";
6031
6054
  }
6032
- var DEFAULT_API_HOST2, API_PREFIX, DEFAULT_TIMEOUT_MS, DEFAULT_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES, MAX_ERROR_BODY_BYTES, CLEANUP_TIMEOUT_MS, CONFIG_PATH41, DATALAB_MODE_VALUES, DATALAB_LOCATION_VALUES, DEFAULT_DATALAB_MODE, DEFAULT_PROCESSING_LOCATION, DEFAULT_DATALAB_TIMEOUT_MS, cachedConfig37;
6055
+ var DEFAULT_API_HOST2, API_PREFIX, DEFAULT_TIMEOUT_MS2, DEFAULT_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES, MAX_ERROR_BODY_BYTES, CLEANUP_TIMEOUT_MS, CONFIG_PATH42, DATALAB_MODE_VALUES, DATALAB_LOCATION_VALUES, DEFAULT_DATALAB_MODE, DEFAULT_PROCESSING_LOCATION, DEFAULT_DATALAB_TIMEOUT_MS, cachedConfig37;
6033
6056
  var init_datalab_pdf_extract = __esm({
6034
6057
  "datalab-pdf-extract.ts"() {
6035
6058
  init_credential_source();
6036
6059
  init_utils();
6037
6060
  DEFAULT_API_HOST2 = "https://www.datalab.to";
6038
6061
  API_PREFIX = "/api/v1";
6039
- DEFAULT_TIMEOUT_MS = 12e4;
6062
+ DEFAULT_TIMEOUT_MS2 = 12e4;
6040
6063
  DEFAULT_POLL_INTERVAL_MS = 1500;
6041
6064
  MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
6042
6065
  MAX_ERROR_BODY_BYTES = 300;
6043
6066
  CLEANUP_TIMEOUT_MS = 5e3;
6044
- CONFIG_PATH41 = getWebSearchConfigPath();
6067
+ CONFIG_PATH42 = getWebSearchConfigPath();
6045
6068
  DATALAB_MODE_VALUES = /* @__PURE__ */ new Set([
6046
6069
  "fast",
6047
6070
  "balanced",
@@ -6053,22 +6076,22 @@ var init_datalab_pdf_extract = __esm({
6053
6076
  ]);
6054
6077
  DEFAULT_DATALAB_MODE = "balanced";
6055
6078
  DEFAULT_PROCESSING_LOCATION = "us";
6056
- DEFAULT_DATALAB_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
6079
+ DEFAULT_DATALAB_TIMEOUT_MS = DEFAULT_TIMEOUT_MS2;
6057
6080
  cachedConfig37 = null;
6058
6081
  }
6059
6082
  });
6060
6083
 
6061
6084
  // endpoint-pdf-extract.ts
6062
- import { existsSync as existsSync46, readFileSync as readFileSync47 } from "node:fs";
6085
+ import { existsSync as existsSync47, readFileSync as readFileSync48 } from "node:fs";
6063
6086
  import { setTimeout as sleep2 } from "node:timers/promises";
6064
6087
  function pdfSection() {
6065
- if (!existsSync46(CONFIG_PATH42)) return {};
6088
+ if (!existsSync47(CONFIG_PATH43)) return {};
6066
6089
  let parsed;
6067
6090
  try {
6068
- parsed = JSON.parse(readFileSync47(CONFIG_PATH42, "utf-8"));
6091
+ parsed = JSON.parse(readFileSync48(CONFIG_PATH43, "utf-8"));
6069
6092
  } catch (err) {
6070
6093
  const message = err instanceof Error ? err.message : String(err);
6071
- throw new Error(`Failed to parse ${CONFIG_PATH42}: ${message}`);
6094
+ throw new Error(`Failed to parse ${CONFIG_PATH43}: ${message}`);
6072
6095
  }
6073
6096
  const pdf = parsed?.pdf;
6074
6097
  return pdf && typeof pdf === "object" ? pdf : {};
@@ -6094,7 +6117,7 @@ function getEndpointTimeoutMs() {
6094
6117
  if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
6095
6118
  return Math.min(configured, 3e5);
6096
6119
  }
6097
- return DEFAULT_TIMEOUT_MS2;
6120
+ return DEFAULT_TIMEOUT_MS3;
6098
6121
  }
6099
6122
  function isEndpointApiAvailable() {
6100
6123
  try {
@@ -6220,16 +6243,16 @@ async function extractPDFViaEndpoint(buffer, options) {
6220
6243
  }
6221
6244
  throw new Error("PDF parser endpoint job timed out");
6222
6245
  }
6223
- var DEFAULT_TIMEOUT_MS2, MAX_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES2, MAX_ERROR_BODY_BYTES2, CONFIG_PATH42;
6246
+ var DEFAULT_TIMEOUT_MS3, MAX_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES2, MAX_ERROR_BODY_BYTES2, CONFIG_PATH43;
6224
6247
  var init_endpoint_pdf_extract = __esm({
6225
6248
  "endpoint-pdf-extract.ts"() {
6226
6249
  init_ssrf_protection();
6227
6250
  init_utils();
6228
- DEFAULT_TIMEOUT_MS2 = 12e4;
6251
+ DEFAULT_TIMEOUT_MS3 = 12e4;
6229
6252
  MAX_POLL_INTERVAL_MS = 3e3;
6230
6253
  MAX_RESPONSE_BYTES2 = 4 * 1024 * 1024;
6231
6254
  MAX_ERROR_BODY_BYTES2 = 300;
6232
- CONFIG_PATH42 = getWebSearchConfigPath();
6255
+ CONFIG_PATH43 = getWebSearchConfigPath();
6233
6256
  }
6234
6257
  });
6235
6258
 
@@ -6244,7 +6267,7 @@ async function extractPDFViaGemini(buffer, options) {
6244
6267
  PDF_MIME_TYPE,
6245
6268
  {
6246
6269
  signal: options.signal,
6247
- timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS3
6270
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS4
6248
6271
  }
6249
6272
  );
6250
6273
  if (result.blockReason) {
@@ -6308,23 +6331,23 @@ function removeDuplicateInitialTitle(markdown, title) {
6308
6331
  function normalizeTitle(value) {
6309
6332
  return value.normalize("NFKC").toLocaleLowerCase().replace(/[`*_~]/g, "").replace(/[\p{P}\p{S}\s]+/gu, "");
6310
6333
  }
6311
- var PDF_MIME_TYPE, DEFAULT_TIMEOUT_MS3, PAGE_MARKER_PATTERN;
6334
+ var PDF_MIME_TYPE, DEFAULT_TIMEOUT_MS4, PAGE_MARKER_PATTERN;
6312
6335
  var init_gemini_pdf_extract = __esm({
6313
6336
  "gemini-pdf-extract.ts"() {
6314
6337
  init_gemini_api();
6315
6338
  PDF_MIME_TYPE = "application/pdf";
6316
- DEFAULT_TIMEOUT_MS3 = 12e4;
6339
+ DEFAULT_TIMEOUT_MS4 = 12e4;
6317
6340
  PAGE_MARKER_PATTERN = /^<!-- Page (\d+) -->$/gm;
6318
6341
  }
6319
6342
  });
6320
6343
 
6321
6344
  // pdf-extract.ts
6322
- import { existsSync as existsSync47, readFileSync as readFileSync48 } from "node:fs";
6345
+ import { existsSync as existsSync48, readFileSync as readFileSync49 } from "node:fs";
6323
6346
  import { writeFile as writeFile2, mkdir } from "node:fs/promises";
6324
6347
  import { join as join5, basename as basename2 } from "node:path";
6325
6348
  import { tmpdir as tmpdir3 } from "node:os";
6326
6349
  function loadPDFConfig() {
6327
- if (!existsSync47(CONFIG_PATH43)) {
6350
+ if (!existsSync48(CONFIG_PATH44)) {
6328
6351
  return {
6329
6352
  enabled: true,
6330
6353
  maxSizeMB: DEFAULT_PDF_MAX_SIZE_MB,
@@ -6334,13 +6357,13 @@ function loadPDFConfig() {
6334
6357
  datalabTimeoutMs: DEFAULT_DATALAB_TIMEOUT_MS
6335
6358
  };
6336
6359
  }
6337
- const rawText = readFileSync48(CONFIG_PATH43, "utf-8");
6360
+ const rawText = readFileSync49(CONFIG_PATH44, "utf-8");
6338
6361
  let raw;
6339
6362
  try {
6340
6363
  raw = JSON.parse(rawText);
6341
6364
  } catch (err) {
6342
6365
  const message = err instanceof Error ? err.message : String(err);
6343
- throw new Error(`Failed to parse ${CONFIG_PATH43}: ${message}`);
6366
+ throw new Error(`Failed to parse ${CONFIG_PATH44}: ${message}`);
6344
6367
  }
6345
6368
  const root = raw && typeof raw === "object" ? raw : {};
6346
6369
  const pdf = root.pdf && typeof root.pdf === "object" ? root.pdf : {};
@@ -6576,7 +6599,7 @@ function isPDF(url, contentType) {
6576
6599
  return false;
6577
6600
  }
6578
6601
  }
6579
- var PDF_PROVIDER_VALUES, DEFAULT_PDF_MAX_SIZE_MB, MAX_PDF_MAX_SIZE_MB, MAX_DATALAB_TIMEOUT_MS, DEFAULT_MAX_PAGES, DEFAULT_OUTPUT_DIR, CONFIG_PATH43, PAGE_MARKER_PATTERN2;
6602
+ var PDF_PROVIDER_VALUES, DEFAULT_PDF_MAX_SIZE_MB, MAX_PDF_MAX_SIZE_MB, MAX_DATALAB_TIMEOUT_MS, DEFAULT_MAX_PAGES, DEFAULT_OUTPUT_DIR, CONFIG_PATH44, PAGE_MARKER_PATTERN2;
6580
6603
  var init_pdf_extract = __esm({
6581
6604
  "pdf-extract.ts"() {
6582
6605
  init_credential_source();
@@ -6597,7 +6620,7 @@ var init_pdf_extract = __esm({
6597
6620
  MAX_DATALAB_TIMEOUT_MS = 3e5;
6598
6621
  DEFAULT_MAX_PAGES = 100;
6599
6622
  DEFAULT_OUTPUT_DIR = join5(tmpdir3(), "pi-web-pdf");
6600
- CONFIG_PATH43 = getWebSearchConfigPath();
6623
+ CONFIG_PATH44 = getWebSearchConfigPath();
6601
6624
  PAGE_MARKER_PATTERN2 = /^<!-- Page (\d+) -->$/gm;
6602
6625
  }
6603
6626
  });
@@ -6775,7 +6798,7 @@ var init_github_api = __esm({
6775
6798
  });
6776
6799
 
6777
6800
  // github-extract.ts
6778
- import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync48, lstatSync as lstatSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, openSync as openSync2, readFileSync as readFileSync49, readSync, readdirSync as readdirSync3, realpathSync as realpathSync2, rmSync as rmSync2, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
6801
+ import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync49, lstatSync as lstatSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, openSync as openSync2, readFileSync as readFileSync50, readSync, readdirSync as readdirSync3, realpathSync as realpathSync2, rmSync as rmSync2, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
6779
6802
  import { lstat as lstatAsync, open as openAsync, opendir as opendirAsync, readFile as readFileAsync, realpath as realpathAsync, rm as rmAsync } from "node:fs/promises";
6780
6803
  import { execFile as execFile4, spawn as spawn2 } from "node:child_process";
6781
6804
  import { createHash as createHash2 } from "node:crypto";
@@ -6811,17 +6834,17 @@ function loadGitHubConfig() {
6811
6834
  cloneTimeoutSeconds: 30,
6812
6835
  clonePath: "/tmp/pi-github-repos"
6813
6836
  };
6814
- if (!existsSync48(CONFIG_PATH44)) {
6837
+ if (!existsSync49(CONFIG_PATH45)) {
6815
6838
  cachedConfig38 = defaults2;
6816
6839
  return cachedConfig38;
6817
6840
  }
6818
- const rawText = readFileSync49(CONFIG_PATH44, "utf-8");
6841
+ const rawText = readFileSync50(CONFIG_PATH45, "utf-8");
6819
6842
  let raw;
6820
6843
  try {
6821
6844
  raw = JSON.parse(rawText);
6822
6845
  } catch (err) {
6823
6846
  const message = err instanceof Error ? err.message : String(err);
6824
- throw new Error(`Failed to parse ${CONFIG_PATH44}: ${message}`);
6847
+ throw new Error(`Failed to parse ${CONFIG_PATH45}: ${message}`);
6825
6848
  }
6826
6849
  const gc = raw.githubClone ?? {};
6827
6850
  cachedConfig38 = {
@@ -6881,7 +6904,7 @@ function cacheKey(owner, repo, ref) {
6881
6904
  }
6882
6905
  function readLinuxBootId() {
6883
6906
  try {
6884
- const bootId = readFileSync49("/proc/sys/kernel/random/boot_id", "utf-8").trim();
6907
+ const bootId = readFileSync50("/proc/sys/kernel/random/boot_id", "utf-8").trim();
6885
6908
  return bootId.length > 0 ? bootId : null;
6886
6909
  } catch {
6887
6910
  return null;
@@ -6906,7 +6929,7 @@ function parseLinuxProcessInfo(stat) {
6906
6929
  }
6907
6930
  function readLinuxProcessInfo(pid) {
6908
6931
  try {
6909
- return parseLinuxProcessInfo(readFileSync49(`/proc/${pid}/stat`, "utf-8"));
6932
+ return parseLinuxProcessInfo(readFileSync50(`/proc/${pid}/stat`, "utf-8"));
6910
6933
  } catch (err) {
6911
6934
  if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") {
6912
6935
  return { state: "", startTime: null, dead: true };
@@ -7244,7 +7267,7 @@ function resolveWithinRepo(rootPath, relativePath) {
7244
7267
  const rootPrefix = normalizedRoot.endsWith(pathSep) ? normalizedRoot : normalizedRoot + pathSep;
7245
7268
  if (!candidate.startsWith(rootPrefix)) return null;
7246
7269
  }
7247
- if (!existsSync48(candidate)) return candidate;
7270
+ if (!existsSync49(candidate)) return candidate;
7248
7271
  try {
7249
7272
  const realRoot = realpathSync2(normalizedRoot);
7250
7273
  const realCandidate = realpathSync2(candidate);
@@ -7257,7 +7280,7 @@ function resolveWithinRepo(rootPath, relativePath) {
7257
7280
  }
7258
7281
  function readTextFile(path) {
7259
7282
  try {
7260
- return readFileSync49(path, "utf-8");
7283
+ return readFileSync50(path, "utf-8");
7261
7284
  } catch {
7262
7285
  return null;
7263
7286
  }
@@ -7340,9 +7363,9 @@ function readReadme(localPath) {
7340
7363
  const candidates = ["README.md", "readme.md", "README", "README.txt", "README.rst"];
7341
7364
  for (const name of candidates) {
7342
7365
  const readmePath = join6(localPath, name);
7343
- if (existsSync48(readmePath)) {
7366
+ if (existsSync49(readmePath)) {
7344
7367
  try {
7345
- const content = readFileSync49(readmePath, "utf-8");
7368
+ const content = readFileSync50(readmePath, "utf-8");
7346
7369
  return content.length > 8192 ? content.slice(0, 8192) + "\n\n[README truncated at 8K chars]" : content;
7347
7370
  } catch {
7348
7371
  continue;
@@ -7371,7 +7394,7 @@ function generateContent(localPath, info) {
7371
7394
  if (info.type === "tree") {
7372
7395
  const dirPath = info.path || "";
7373
7396
  const fullDirPath = resolveWithinRepo(localPath, dirPath);
7374
- if (!fullDirPath || !existsSync48(fullDirPath)) {
7397
+ if (!fullDirPath || !existsSync49(fullDirPath)) {
7375
7398
  lines.push(`Path \`${dirPath}\` not found in clone. Showing repository root instead.`);
7376
7399
  lines.push("");
7377
7400
  lines.push("## Structure");
@@ -7387,7 +7410,7 @@ function generateContent(localPath, info) {
7387
7410
  if (info.type === "blob") {
7388
7411
  const filePath = info.path || "";
7389
7412
  const fullFilePath = resolveWithinRepo(localPath, filePath);
7390
- if (!fullFilePath || !existsSync48(fullFilePath)) {
7413
+ if (!fullFilePath || !existsSync49(fullFilePath)) {
7391
7414
  lines.push(`Path \`${filePath}\` not found in clone. Showing repository root instead.`);
7392
7415
  lines.push("");
7393
7416
  lines.push("## Structure");
@@ -7549,13 +7572,13 @@ async function extractGitHub(url, signal, forceClone) {
7549
7572
  const title = info.path ? `${owner}/${repo} - ${info.path}` : `${owner}/${repo}`;
7550
7573
  return { url, title, content, error: null };
7551
7574
  }
7552
- var CONFIG_PATH44, BINARY_EXTENSIONS, NOISE_DIRS, MAX_INLINE_FILE_CHARS2, MAX_TREE_ENTRIES2, CLONE_RUNTIME_OWNER_FILENAME, CLONE_RUNTIME_OWNER_VERSION, MAX_CLONE_RUNTIME_OWNER_BYTES, cloneCache, startedCloneRuntimeCleanups, cachedConfig38, cloneRuntime, NON_CODE_SEGMENTS, PROCESS_KILL_GRACE_MS;
7575
+ var CONFIG_PATH45, BINARY_EXTENSIONS, NOISE_DIRS, MAX_INLINE_FILE_CHARS2, MAX_TREE_ENTRIES2, CLONE_RUNTIME_OWNER_FILENAME, CLONE_RUNTIME_OWNER_VERSION, MAX_CLONE_RUNTIME_OWNER_BYTES, cloneCache, startedCloneRuntimeCleanups, cachedConfig38, cloneRuntime, NON_CODE_SEGMENTS, PROCESS_KILL_GRACE_MS;
7553
7576
  var init_github_extract = __esm({
7554
7577
  "github-extract.ts"() {
7555
7578
  init_activity();
7556
7579
  init_github_api();
7557
7580
  init_utils();
7558
- CONFIG_PATH44 = getWebSearchConfigPath();
7581
+ CONFIG_PATH45 = getWebSearchConfigPath();
7559
7582
  BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
7560
7583
  ".png",
7561
7584
  ".jpg",
@@ -7682,25 +7705,25 @@ var init_github_extract = __esm({
7682
7705
 
7683
7706
  // github-issue-pr.ts
7684
7707
  import { execFile as execFile5 } from "node:child_process";
7685
- import { existsSync as existsSync49, readFileSync as readFileSync50 } from "node:fs";
7686
- function loadConfig39() {
7708
+ import { existsSync as existsSync50, readFileSync as readFileSync51 } from "node:fs";
7709
+ function loadConfig40() {
7687
7710
  if (cachedConfig39) return cachedConfig39;
7688
7711
  const defaults2 = { enabled: true };
7689
- if (!existsSync49(CONFIG_PATH45)) {
7712
+ if (!existsSync50(CONFIG_PATH46)) {
7690
7713
  cachedConfig39 = defaults2;
7691
7714
  return cachedConfig39;
7692
7715
  }
7693
7716
  let parsed;
7694
7717
  try {
7695
- parsed = JSON.parse(readFileSync50(CONFIG_PATH45, "utf-8"));
7718
+ parsed = JSON.parse(readFileSync51(CONFIG_PATH46, "utf-8"));
7696
7719
  } catch (err) {
7697
7720
  const message = err instanceof Error ? err.message : String(err);
7698
- throw new Error(`Failed to parse ${CONFIG_PATH45}: ${message}`);
7721
+ throw new Error(`Failed to parse ${CONFIG_PATH46}: ${message}`);
7699
7722
  }
7700
7723
  const root = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
7701
7724
  const value = root.githubPrIssue;
7702
7725
  if (value !== void 0 && (typeof value !== "object" || value === null || Array.isArray(value))) {
7703
- throw new Error(`githubPrIssue in ${CONFIG_PATH45} must be an object`);
7726
+ throw new Error(`githubPrIssue in ${CONFIG_PATH46} must be an object`);
7704
7727
  }
7705
7728
  const enabled = typeof value?.enabled === "boolean" ? value.enabled : true;
7706
7729
  cachedConfig39 = { enabled };
@@ -8026,11 +8049,11 @@ function storeOmitted(appendix, section, items) {
8026
8049
 
8027
8050
  ${items.join("\n")}`);
8028
8051
  }
8029
- function omissionMarker(section, noun, shown, fetched, atLeast, tool, gh = "the gh command below") {
8030
- const stored = fetched > shown && tool ? `${fetched - shown} more stored under "${section} (continued)": use ${tool} findText or offset` : "";
8031
- if (atLeast !== null) return `[${shown} ${noun} shown from at least ${atLeast}; ${stored ? `${stored}; for the rest ` : ""}use ${gh}]`;
8032
- if (fetched <= shown) return null;
8033
- return `[${shown} of ${fetched} ${noun} shown; ${stored ? `${stored}, or ${gh}` : `use ${gh}`}]`;
8052
+ function omissionMarker(section, noun, shown2, fetched, atLeast, tool, gh = "the gh command below") {
8053
+ const stored = fetched > shown2 && tool ? `${fetched - shown2} more stored under "${section} (continued)": use ${tool} findText or offset` : "";
8054
+ if (atLeast !== null) return `[${shown2} ${noun} shown from at least ${atLeast}; ${stored ? `${stored}; for the rest ` : ""}use ${gh}]`;
8055
+ if (fetched <= shown2) return null;
8056
+ return `[${shown2} of ${fetched} ${noun} shown; ${stored ? `${stored}, or ${gh}` : `use ${gh}`}]`;
8034
8057
  }
8035
8058
  function appendLimitedSection(lines, title, items, max, marker, appendix, tool) {
8036
8059
  lines.push(`## ${title}`);
@@ -8250,7 +8273,7 @@ function renderGitHubPrIssue(data) {
8250
8273
  async function extractGitHubIssuePr(url, signal, options) {
8251
8274
  const info = parseGitHubIssuePrUrl(url);
8252
8275
  if (!info) return null;
8253
- if (!loadConfig39().enabled) return null;
8276
+ if (!loadConfig40().enabled) return null;
8254
8277
  if (signal?.aborted) return { url, title: "", content: "", error: "Aborted" };
8255
8278
  const retrievalTool = options?.toolNames ? options.toolNames.getSearchContent ?? null : void 0;
8256
8279
  const ghAvailable2 = await checkGhAvailable(signal);
@@ -8274,13 +8297,13 @@ async function extractGitHubIssuePr(url, signal, options) {
8274
8297
  if ("data" in fallback) return renderGitHubPrIssue({ ...fallback.data, retrievalTool });
8275
8298
  return fallback;
8276
8299
  }
8277
- var CONFIG_PATH45, GH_TIMEOUT_MS, GH_TOTAL_TIMEOUT_MS, MAX_DOC_CHARS, BODY_INLINE_CHARS, COMMENT_INLINE_CHARS, MAX_INLINE_COMMENTS, MAX_INLINE_REVIEWS, MAX_INLINE_CHECKS, MAX_INLINE_FILES, MAX_INLINE_COMMITS, MAX_INLINE_REVIEW_THREADS, REST_HEADERS, PR_SUBPATHS, PR_FIELDS, PR_CORE_FIELDS, ISSUE_FIELDS, ISSUE_CORE_FIELDS, cachedConfig39;
8300
+ var CONFIG_PATH46, GH_TIMEOUT_MS, GH_TOTAL_TIMEOUT_MS, MAX_DOC_CHARS, BODY_INLINE_CHARS, COMMENT_INLINE_CHARS, MAX_INLINE_COMMENTS, MAX_INLINE_REVIEWS, MAX_INLINE_CHECKS, MAX_INLINE_FILES, MAX_INLINE_COMMITS, MAX_INLINE_REVIEW_THREADS, REST_HEADERS, PR_SUBPATHS, PR_FIELDS, PR_CORE_FIELDS, ISSUE_FIELDS, ISSUE_CORE_FIELDS, cachedConfig39;
8278
8301
  var init_github_issue_pr = __esm({
8279
8302
  "github-issue-pr.ts"() {
8280
8303
  init_github_api();
8281
8304
  init_ssrf_protection();
8282
8305
  init_utils();
8283
- CONFIG_PATH45 = getWebSearchConfigPath();
8306
+ CONFIG_PATH46 = getWebSearchConfigPath();
8284
8307
  GH_TIMEOUT_MS = 1e4;
8285
8308
  GH_TOTAL_TIMEOUT_MS = 2e4;
8286
8309
  MAX_DOC_CHARS = 15e4;
@@ -8366,15 +8389,15 @@ var init_github_issue_pr = __esm({
8366
8389
  });
8367
8390
 
8368
8391
  // feature-config.ts
8369
- import { existsSync as existsSync50, readFileSync as readFileSync51 } from "node:fs";
8392
+ import { existsSync as existsSync51, readFileSync as readFileSync52 } from "node:fs";
8370
8393
  function loadFeatureConfig() {
8371
- if (!existsSync50(CONFIG_PATH46)) return {};
8394
+ if (!existsSync51(CONFIG_PATH47)) return {};
8372
8395
  try {
8373
- const raw = JSON.parse(readFileSync51(CONFIG_PATH46, "utf-8"));
8396
+ const raw = JSON.parse(readFileSync52(CONFIG_PATH47, "utf-8"));
8374
8397
  return raw && typeof raw === "object" ? raw : {};
8375
8398
  } catch (err) {
8376
8399
  const message = err instanceof Error ? err.message : String(err);
8377
- throw new Error(`Failed to parse ${CONFIG_PATH46}: ${message}`);
8400
+ throw new Error(`Failed to parse ${CONFIG_PATH47}: ${message}`);
8378
8401
  }
8379
8402
  }
8380
8403
  function isImageEnabled() {
@@ -8387,17 +8410,17 @@ function canAttachImages() {
8387
8410
  return false;
8388
8411
  }
8389
8412
  }
8390
- var CONFIG_PATH46;
8413
+ var CONFIG_PATH47;
8391
8414
  var init_feature_config = __esm({
8392
8415
  "feature-config.ts"() {
8393
8416
  init_utils();
8394
- CONFIG_PATH46 = getWebSearchConfigPath();
8417
+ CONFIG_PATH47 = getWebSearchConfigPath();
8395
8418
  }
8396
8419
  });
8397
8420
 
8398
8421
  // youtube-extract.ts
8399
8422
  import { execFileSync } from "node:child_process";
8400
- import { existsSync as existsSync51, readFileSync as readFileSync52 } from "node:fs";
8423
+ import { existsSync as existsSync52, readFileSync as readFileSync53 } from "node:fs";
8401
8424
  function errorMessage30(err) {
8402
8425
  return err instanceof Error ? err.message : String(err);
8403
8426
  }
@@ -8418,17 +8441,17 @@ function normalizeEnabled2(value, fallback) {
8418
8441
  }
8419
8442
  function loadYouTubeConfig() {
8420
8443
  if (cachedConfig40) return cachedConfig40;
8421
- if (!existsSync51(CONFIG_PATH47)) {
8444
+ if (!existsSync52(CONFIG_PATH48)) {
8422
8445
  cachedConfig40 = { ...defaults };
8423
8446
  return cachedConfig40;
8424
8447
  }
8425
- const rawText = readFileSync52(CONFIG_PATH47, "utf-8");
8448
+ const rawText = readFileSync53(CONFIG_PATH48, "utf-8");
8426
8449
  let raw;
8427
8450
  try {
8428
8451
  raw = JSON.parse(rawText);
8429
8452
  } catch (err) {
8430
8453
  const message = err instanceof Error ? err.message : String(err);
8431
- throw new Error(`Failed to parse ${CONFIG_PATH47}: ${message}`);
8454
+ throw new Error(`Failed to parse ${CONFIG_PATH48}: ${message}`);
8432
8455
  }
8433
8456
  const yt = raw.youtube ?? {};
8434
8457
  cachedConfig40 = {
@@ -8627,7 +8650,7 @@ ${answer}
8627
8650
  return null;
8628
8651
  }
8629
8652
  }
8630
- var CONFIG_PATH47, YOUTUBE_PROMPT, YOUTUBE_REGEX, defaults, cachedConfig40;
8653
+ var CONFIG_PATH48, YOUTUBE_PROMPT, YOUTUBE_REGEX, defaults, cachedConfig40;
8631
8654
  var init_youtube_extract = __esm({
8632
8655
  "youtube-extract.ts"() {
8633
8656
  init_activity();
@@ -8637,7 +8660,7 @@ var init_youtube_extract = __esm({
8637
8660
  init_perplexity();
8638
8661
  init_extract();
8639
8662
  init_utils();
8640
- CONFIG_PATH47 = getWebSearchConfigPath();
8663
+ CONFIG_PATH48 = getWebSearchConfigPath();
8641
8664
  YOUTUBE_PROMPT = `Extract the complete content of this YouTube video. Include:
8642
8665
  1. Video title, channel name, and duration
8643
8666
  2. A brief summary (2-3 sentences)
@@ -8749,23 +8772,23 @@ URL: `;
8749
8772
  });
8750
8773
 
8751
8774
  // crawl4ai.ts
8752
- import { existsSync as existsSync52, readFileSync as readFileSync53 } from "node:fs";
8753
- function loadConfig40() {
8775
+ import { existsSync as existsSync53, readFileSync as readFileSync54 } from "node:fs";
8776
+ function loadConfig41() {
8754
8777
  if (cachedConfig41) return cachedConfig41;
8755
- if (!existsSync52(CONFIG_PATH48)) {
8778
+ if (!existsSync53(CONFIG_PATH49)) {
8756
8779
  cachedConfig41 = {};
8757
8780
  return cachedConfig41;
8758
8781
  }
8759
- const raw = readFileSync53(CONFIG_PATH48, "utf8");
8782
+ const raw = readFileSync54(CONFIG_PATH49, "utf8");
8760
8783
  let parsed;
8761
8784
  try {
8762
8785
  parsed = JSON.parse(raw);
8763
8786
  } catch (err) {
8764
8787
  const message = err instanceof Error ? err.message : String(err);
8765
- throw new Error(`Failed to parse ${CONFIG_PATH48}: ${message}`);
8788
+ throw new Error(`Failed to parse ${CONFIG_PATH49}: ${message}`);
8766
8789
  }
8767
8790
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
8768
- throw new Error(`Invalid config in ${CONFIG_PATH48}: expected a JSON object`);
8791
+ throw new Error(`Invalid config in ${CONFIG_PATH49}: expected a JSON object`);
8769
8792
  }
8770
8793
  cachedConfig41 = parsed;
8771
8794
  return cachedConfig41;
@@ -8778,13 +8801,13 @@ function normalizeBaseUrl5(value) {
8778
8801
  try {
8779
8802
  parsed = new URL(trimmed);
8780
8803
  } catch {
8781
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: expected an HTTP or HTTPS URL`);
8804
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH49}: expected an HTTP or HTTPS URL`);
8782
8805
  }
8783
8806
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
8784
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: expected an HTTP or HTTPS URL`);
8807
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH49}: expected an HTTP or HTTPS URL`);
8785
8808
  }
8786
8809
  if (parsed.username || parsed.password) {
8787
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: URL credentials are not allowed`);
8810
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH49}: URL credentials are not allowed`);
8788
8811
  }
8789
8812
  parsed.pathname = parsed.pathname.replace(/\/+$/, "");
8790
8813
  parsed.search = "";
@@ -8792,14 +8815,14 @@ function normalizeBaseUrl5(value) {
8792
8815
  return parsed.toString().replace(/\/+$/, "");
8793
8816
  }
8794
8817
  function getBaseUrl4() {
8795
- return normalizeBaseUrl5(process.env.CRAWL4AI_BASE_URL) ?? normalizeBaseUrl5(loadConfig40().crawl4aiBaseUrl);
8818
+ return normalizeBaseUrl5(process.env.CRAWL4AI_BASE_URL) ?? normalizeBaseUrl5(loadConfig41().crawl4aiBaseUrl);
8796
8819
  }
8797
8820
  function requireBaseUrl4() {
8798
8821
  const baseUrl = getBaseUrl4();
8799
8822
  if (!baseUrl) {
8800
8823
  throw new Error(
8801
8824
  `Crawl4AI base URL not configured. Either:
8802
- 1. Set crawl4aiBaseUrl in ${CONFIG_PATH48}
8825
+ 1. Set crawl4aiBaseUrl in ${CONFIG_PATH49}
8803
8826
  2. Set CRAWL4AI_BASE_URL environment variable`
8804
8827
  );
8805
8828
  }
@@ -8808,7 +8831,7 @@ function requireBaseUrl4() {
8808
8831
  async function getApiToken(signal) {
8809
8832
  return resolveCredential({
8810
8833
  provider: "Crawl4AI",
8811
- configuredValue: loadConfig40().crawl4aiApiToken,
8834
+ configuredValue: loadConfig41().crawl4aiApiToken,
8812
8835
  environmentValue: process.env.CRAWL4AI_API_TOKEN,
8813
8836
  signal
8814
8837
  });
@@ -8898,14 +8921,14 @@ async function extractWithCrawl4ai(url, signal, options) {
8898
8921
  throw err;
8899
8922
  }
8900
8923
  }
8901
- var CONFIG_PATH48, EXTRACT_TIMEOUT_MS2, MARKDOWN_FILTER, cachedConfig41;
8924
+ var CONFIG_PATH49, EXTRACT_TIMEOUT_MS2, MARKDOWN_FILTER, cachedConfig41;
8902
8925
  var init_crawl4ai = __esm({
8903
8926
  "crawl4ai.ts"() {
8904
8927
  init_activity();
8905
8928
  init_credential_source();
8906
8929
  init_ssrf_protection();
8907
8930
  init_utils();
8908
- CONFIG_PATH48 = getWebSearchConfigPath();
8931
+ CONFIG_PATH49 = getWebSearchConfigPath();
8909
8932
  EXTRACT_TIMEOUT_MS2 = 6e4;
8910
8933
  MARKDOWN_FILTER = "fit";
8911
8934
  cachedConfig41 = null;
@@ -8913,27 +8936,27 @@ var init_crawl4ai = __esm({
8913
8936
  });
8914
8937
 
8915
8938
  // brightdata-unlocker.ts
8916
- import { existsSync as existsSync53, readFileSync as readFileSync54 } from "node:fs";
8939
+ import { existsSync as existsSync54, readFileSync as readFileSync55 } from "node:fs";
8917
8940
  function parseFailureDetail(err) {
8918
8941
  const message = err instanceof Error ? err.message : String(err);
8919
8942
  const position = message.match(/at position \d+(?: \(line \d+ column \d+\))?/);
8920
8943
  return position ? `invalid JSON ${position[0]}` : "invalid JSON";
8921
8944
  }
8922
- function loadConfig41() {
8945
+ function loadConfig42() {
8923
8946
  if (cachedConfig42) return cachedConfig42;
8924
- if (!existsSync53(CONFIG_PATH49)) {
8947
+ if (!existsSync54(CONFIG_PATH50)) {
8925
8948
  cachedConfig42 = {};
8926
8949
  return cachedConfig42;
8927
8950
  }
8928
- const raw = readFileSync54(CONFIG_PATH49, "utf8");
8951
+ const raw = readFileSync55(CONFIG_PATH50, "utf8");
8929
8952
  let parsed;
8930
8953
  try {
8931
8954
  parsed = JSON.parse(raw);
8932
8955
  } catch (err) {
8933
- throw new Error(`Failed to parse ${CONFIG_PATH49}: ${parseFailureDetail(err)}`);
8956
+ throw new Error(`Failed to parse ${CONFIG_PATH50}: ${parseFailureDetail(err)}`);
8934
8957
  }
8935
8958
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
8936
- throw new Error(`Invalid config in ${CONFIG_PATH49}: expected a JSON object`);
8959
+ throw new Error(`Invalid config in ${CONFIG_PATH50}: expected a JSON object`);
8937
8960
  }
8938
8961
  cachedConfig42 = parsed;
8939
8962
  return cachedConfig42;
@@ -8947,8 +8970,8 @@ function normalizeZone2(value) {
8947
8970
  function zoneSetting() {
8948
8971
  const fromEnv = process.env.BRIGHTDATA_UNLOCKER_ZONE;
8949
8972
  if (typeof fromEnv === "string" && fromEnv.trim()) return { raw: fromEnv.trim(), label: "BRIGHTDATA_UNLOCKER_ZONE" };
8950
- const configured = loadConfig41().brightdataUnlockerZone;
8951
- if (typeof configured === "string" && configured.trim()) return { raw: configured.trim(), label: `brightdataUnlockerZone in ${CONFIG_PATH49}` };
8973
+ const configured = loadConfig42().brightdataUnlockerZone;
8974
+ if (typeof configured === "string" && configured.trim()) return { raw: configured.trim(), label: `brightdataUnlockerZone in ${CONFIG_PATH50}` };
8952
8975
  return null;
8953
8976
  }
8954
8977
  function getZone() {
@@ -8966,7 +8989,7 @@ function requireZone() {
8966
8989
  }
8967
8990
  throw new Error(
8968
8991
  `Bright Data Web Unlocker zone not configured. Either:
8969
- 1. Set brightdataUnlockerZone in ${CONFIG_PATH49}
8992
+ 1. Set brightdataUnlockerZone in ${CONFIG_PATH50}
8970
8993
  2. Set BRIGHTDATA_UNLOCKER_ZONE environment variable
8971
8994
  The zone must be of type "unblocker"; a SERP zone will not serve Web Unlocker requests.`
8972
8995
  );
@@ -8974,14 +8997,14 @@ The zone must be of type "unblocker"; a SERP zone will not serve Web Unlocker re
8974
8997
  async function getApiKey27(signal) {
8975
8998
  const apiKey = await resolveCredential({
8976
8999
  provider: "Bright Data",
8977
- configuredValue: loadConfig41().brightdataApiKey,
9000
+ configuredValue: loadConfig42().brightdataApiKey,
8978
9001
  environmentValue: process.env.BRIGHTDATA_API_KEY,
8979
9002
  signal
8980
9003
  });
8981
9004
  if (!apiKey) {
8982
9005
  throw new Error(
8983
9006
  `Bright Data API key not found. Either:
8984
- 1. Create ${CONFIG_PATH49} with { "brightdataApiKey": "your-key" }
9007
+ 1. Create ${CONFIG_PATH50} with { "brightdataApiKey": "your-key" }
8985
9008
  2. Set BRIGHTDATA_API_KEY environment variable
8986
9009
  Get a key at https://brightdata.com/cp/setting/users`
8987
9010
  );
@@ -9045,7 +9068,7 @@ async function brightDataRequest(url, zone, signal, options) {
9045
9068
  };
9046
9069
  const activityId = activityMonitor.logStart({ type: "fetch", url });
9047
9070
  try {
9048
- const response = await fetchBrightDataApi(resolveProviderApiUrl("brightdata", BRIGHTDATA_REQUEST_URL, loadConfig41().brightdataBaseUrl), {
9071
+ const response = await fetchBrightDataApi(resolveProviderApiUrl("brightdata", BRIGHTDATA_REQUEST_URL, loadConfig42().brightdataBaseUrl), {
9049
9072
  method: "POST",
9050
9073
  headers,
9051
9074
  body: JSON.stringify(unlockerBody(url, zone)),
@@ -9078,7 +9101,7 @@ function isBrightDataUnlockerAvailable() {
9078
9101
  if (getZone() === null) return false;
9079
9102
  return hasCredentialSource({
9080
9103
  provider: "Bright Data",
9081
- configuredValue: loadConfig41().brightdataApiKey,
9104
+ configuredValue: loadConfig42().brightdataApiKey,
9082
9105
  environmentValue: process.env.BRIGHTDATA_API_KEY
9083
9106
  });
9084
9107
  }
@@ -9090,14 +9113,14 @@ async function extractWithBrightDataUnlocker(url, signal, options) {
9090
9113
  if (!content) return null;
9091
9114
  return { url, title: headingTitle(content), content, error: null };
9092
9115
  }
9093
- var CONFIG_PATH49, BRIGHTDATA_REQUEST_URL, EXTRACT_TIMEOUT_MS3, DEFAULT_MAX_REDIRECTS3, REDIRECT_STATUSES3, ZONE_PATTERN2, cachedConfig42;
9116
+ var CONFIG_PATH50, BRIGHTDATA_REQUEST_URL, EXTRACT_TIMEOUT_MS3, DEFAULT_MAX_REDIRECTS3, REDIRECT_STATUSES3, ZONE_PATTERN2, cachedConfig42;
9094
9117
  var init_brightdata_unlocker = __esm({
9095
9118
  "brightdata-unlocker.ts"() {
9096
9119
  init_activity();
9097
9120
  init_credential_source();
9098
9121
  init_ssrf_protection();
9099
9122
  init_utils();
9100
- CONFIG_PATH49 = getWebSearchConfigPath();
9123
+ CONFIG_PATH50 = getWebSearchConfigPath();
9101
9124
  BRIGHTDATA_REQUEST_URL = "https://api.brightdata.com/request";
9102
9125
  EXTRACT_TIMEOUT_MS3 = 6e4;
9103
9126
  DEFAULT_MAX_REDIRECTS3 = 5;
@@ -9109,7 +9132,7 @@ var init_brightdata_unlocker = __esm({
9109
9132
 
9110
9133
  // video-extract.ts
9111
9134
  import { execFileSync as execFileSync2 } from "node:child_process";
9112
- import { existsSync as existsSync54, readFileSync as readFileSync55, readdirSync as readdirSync4, statSync as statSync3 } from "node:fs";
9135
+ import { existsSync as existsSync55, readFileSync as readFileSync56, readdirSync as readdirSync4, statSync as statSync3 } from "node:fs";
9113
9136
  import { readFile as readFile2 } from "node:fs/promises";
9114
9137
  import { resolve, extname as extname2, basename as basename4, join as join7, dirname as dirname2 } from "node:path";
9115
9138
  function shouldRethrow3(err) {
@@ -9130,17 +9153,17 @@ function normalizeMaxSizeMB(value, fallback) {
9130
9153
  }
9131
9154
  function loadVideoConfig() {
9132
9155
  if (cachedVideoConfig) return cachedVideoConfig;
9133
- if (!existsSync54(CONFIG_PATH50)) {
9156
+ if (!existsSync55(CONFIG_PATH51)) {
9134
9157
  cachedVideoConfig = { ...VIDEO_CONFIG_DEFAULTS };
9135
9158
  return cachedVideoConfig;
9136
9159
  }
9137
- const rawText = readFileSync55(CONFIG_PATH50, "utf-8");
9160
+ const rawText = readFileSync56(CONFIG_PATH51, "utf-8");
9138
9161
  let raw;
9139
9162
  try {
9140
9163
  raw = JSON.parse(rawText);
9141
9164
  } catch (err) {
9142
9165
  const message = err instanceof Error ? err.message : String(err);
9143
- throw new Error(`Failed to parse ${CONFIG_PATH50}: ${message}`);
9166
+ throw new Error(`Failed to parse ${CONFIG_PATH51}: ${message}`);
9144
9167
  }
9145
9168
  const v = raw.video ?? {};
9146
9169
  cachedVideoConfig = {
@@ -9186,10 +9209,10 @@ function isVideoFile(input) {
9186
9209
  }
9187
9210
  function resolveFilePath(filePath) {
9188
9211
  const absolutePath = resolve(filePath);
9189
- if (existsSync54(absolutePath)) return absolutePath;
9212
+ if (existsSync55(absolutePath)) return absolutePath;
9190
9213
  const dir = dirname2(absolutePath);
9191
9214
  const base = basename4(absolutePath);
9192
- if (!existsSync54(dir)) return null;
9215
+ if (!existsSync55(dir)) return null;
9193
9216
  try {
9194
9217
  const normalizedBase = normalizeSpaces(base);
9195
9218
  const match = readdirSync4(dir).find((f) => normalizeSpaces(f) === normalizedBase);
@@ -9388,7 +9411,7 @@ function deleteGeminiFile(fileName, apiKey) {
9388
9411
  function extractVideoTitle(text6, filePath) {
9389
9412
  return extractHeadingTitle(text6) ?? basename4(filePath, extname2(filePath));
9390
9413
  }
9391
- var CONFIG_PATH50, DEFAULT_VIDEO_PROMPT, VIDEO_EXTENSIONS, VIDEO_CONFIG_DEFAULTS, cachedVideoConfig;
9414
+ var CONFIG_PATH51, DEFAULT_VIDEO_PROMPT, VIDEO_EXTENSIONS, VIDEO_CONFIG_DEFAULTS, cachedVideoConfig;
9392
9415
  var init_video_extract = __esm({
9393
9416
  "video-extract.ts"() {
9394
9417
  init_activity();
@@ -9397,7 +9420,7 @@ var init_video_extract = __esm({
9397
9420
  init_gemini_api();
9398
9421
  init_extract();
9399
9422
  init_utils();
9400
- CONFIG_PATH50 = getWebSearchConfigPath();
9423
+ CONFIG_PATH51 = getWebSearchConfigPath();
9401
9424
  DEFAULT_VIDEO_PROMPT = `Extract the complete content of this video. Include:
9402
9425
  1. Video title (infer from content if not explicit), duration
9403
9426
  2. A brief summary (2-3 sentences)
@@ -9882,13 +9905,13 @@ __export(extract_exports, {
9882
9905
  readPDFResponseBuffer: () => readPDFResponseBuffer,
9883
9906
  resolveFetchTimeoutMs: () => resolveFetchTimeoutMs
9884
9907
  });
9885
- import { existsSync as existsSync55, readFileSync as readFileSync56 } from "node:fs";
9908
+ import { existsSync as existsSync56, readFileSync as readFileSync57 } from "node:fs";
9886
9909
  import pLimit from "p-limit";
9887
9910
  function loadFetchTimeoutMs() {
9888
- if (!existsSync55(WEB_SEARCH_CONFIG_PATH3)) return DEFAULT_TIMEOUT_MS4;
9911
+ if (!existsSync56(WEB_SEARCH_CONFIG_PATH3)) return DEFAULT_TIMEOUT_MS5;
9889
9912
  let raw;
9890
9913
  try {
9891
- raw = JSON.parse(readFileSync56(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
9914
+ raw = JSON.parse(readFileSync57(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
9892
9915
  } catch (err) {
9893
9916
  const message = err instanceof Error ? err.message : String(err);
9894
9917
  throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH3}: ${message}`);
@@ -9897,12 +9920,12 @@ function loadFetchTimeoutMs() {
9897
9920
  throw new Error(`Invalid config in ${WEB_SEARCH_CONFIG_PATH3}: expected a JSON object`);
9898
9921
  }
9899
9922
  const fetchConfig = raw.fetch;
9900
- if (fetchConfig === void 0) return DEFAULT_TIMEOUT_MS4;
9923
+ if (fetchConfig === void 0) return DEFAULT_TIMEOUT_MS5;
9901
9924
  if (!fetchConfig || typeof fetchConfig !== "object" || Array.isArray(fetchConfig)) {
9902
9925
  throw new Error(`fetch in ${WEB_SEARCH_CONFIG_PATH3} must be an object`);
9903
9926
  }
9904
9927
  const value = fetchConfig.timeout;
9905
- if (value === void 0) return DEFAULT_TIMEOUT_MS4;
9928
+ if (value === void 0) return DEFAULT_TIMEOUT_MS5;
9906
9929
  if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
9907
9930
  throw new Error(`Invalid fetch.timeout in ${WEB_SEARCH_CONFIG_PATH3}: expected a positive finite number of seconds, got ${JSON.stringify(value)}`);
9908
9931
  }
@@ -10027,12 +10050,12 @@ async function fetchAuthenticatedRemoteUrl(url, init, validationOptions, profile
10027
10050
  throw new Error(`Too many redirects fetching ${current.toString()}`);
10028
10051
  }
10029
10052
  function loadFetchRouting() {
10030
- if (!existsSync55(WEB_SEARCH_CONFIG_PATH3)) {
10053
+ if (!existsSync56(WEB_SEARCH_CONFIG_PATH3)) {
10031
10054
  return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
10032
10055
  }
10033
10056
  let raw;
10034
10057
  try {
10035
- const parsed = JSON.parse(readFileSync56(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
10058
+ const parsed = JSON.parse(readFileSync57(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
10036
10059
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
10037
10060
  throw new Error("expected a JSON object");
10038
10061
  }
@@ -10946,7 +10969,7 @@ async function extractViaHttp(url, timeoutMs, signal, options, preferMarkdown =
10946
10969
  return {
10947
10970
  url,
10948
10971
  title: result.title,
10949
- content: options?.mode === "answer" ? result.content : `PDF extracted and saved to: ${result.outputPath}
10972
+ content: options?.mode === "answer" || options?.mode === "extract" ? result.content : `PDF extracted and saved to: ${result.outputPath}
10950
10973
 
10951
10974
  ${result.pages > 0 ? `Pages: ${result.pages}
10952
10975
  ` : ""}Characters: ${result.chars}`,
@@ -11134,7 +11157,7 @@ async function fetchAllContent(urls, signal, options) {
11134
11157
  return sanitized.omissions.length > 0 ? { ...result, content: sanitized.text } : result;
11135
11158
  });
11136
11159
  }
11137
- var DEFAULT_TIMEOUT_MS4, MAX_CONFIGURED_TIMEOUT_MS, CONCURRENT_LIMIT, WEB_SEARCH_CONFIG_PATH3, NON_RECOVERABLE_ERRORS, MIN_USEFUL_CONTENT2, SUPPORTED_IMAGE_TYPES, FETCH_PROVIDERS, DEFAULT_FETCH_PROVIDER_ORDER, REMOTE_HOSTED_FETCH_PROVIDERS, REDIRECT_STATUSES4, turndownInstance, fetchLimit, JINA_READER_BASE, DEFAULT_RANGE_FRAMES, MIN_FRAME_INTERVAL, JAVASCRIPT_MIME_TYPES, BROWSER_ACCEPT, MARKDOWN_FIRST_ACCEPT;
11160
+ var DEFAULT_TIMEOUT_MS5, MAX_CONFIGURED_TIMEOUT_MS, CONCURRENT_LIMIT, WEB_SEARCH_CONFIG_PATH3, NON_RECOVERABLE_ERRORS, MIN_USEFUL_CONTENT2, SUPPORTED_IMAGE_TYPES, FETCH_PROVIDERS, DEFAULT_FETCH_PROVIDER_ORDER, REMOTE_HOSTED_FETCH_PROVIDERS, REDIRECT_STATUSES4, turndownInstance, fetchLimit, JINA_READER_BASE, DEFAULT_RANGE_FRAMES, MIN_FRAME_INTERVAL, JAVASCRIPT_MIME_TYPES, BROWSER_ACCEPT, MARKDOWN_FIRST_ACCEPT;
11138
11161
  var init_extract = __esm({
11139
11162
  "extract.ts"() {
11140
11163
  init_activity();
@@ -11165,7 +11188,7 @@ var init_extract = __esm({
11165
11188
  init_chrome_cookies();
11166
11189
  init_data_uri_sanitize();
11167
11190
  init_ssrf_protection();
11168
- DEFAULT_TIMEOUT_MS4 = 3e4;
11191
+ DEFAULT_TIMEOUT_MS5 = 3e4;
11169
11192
  MAX_CONFIGURED_TIMEOUT_MS = 2147483647;
11170
11193
  CONCURRENT_LIMIT = 3;
11171
11194
  WEB_SEARCH_CONFIG_PATH3 = getWebSearchConfigPath();
@@ -11209,7 +11232,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
11209
11232
  // package.json
11210
11233
  var package_default = {
11211
11234
  name: "pi-web-access",
11212
- version: "0.44.0",
11235
+ version: "0.45.0",
11213
11236
  description: "Web search, URL fetching, GitHub repo cloning, PDF extraction, YouTube video understanding, and local video analysis for Pi coding agent. Supports OpenAI, Brave, Parallel, TinyFish, Search1API, Searchinfinity, Querit, Tavily, Firecrawl, Crawl4AI, Jina, SERPdive, Kagi, Ollama, AnySearch, Bright Data SERP, SerpBase, SerpApi, Serply, You.com, SearXNG, degoog, Exa, Perplexity, Gemini, Kimi, and Mistral.",
11214
11237
  type: "module",
11215
11238
  bin: {
@@ -19779,6 +19802,28 @@ __export(value_exports, {
19779
19802
  Repair: () => Repair
19780
19803
  });
19781
19804
 
19805
+ // gemini-search.ts
19806
+ import { existsSync as existsSync44, readFileSync as readFileSync44 } from "node:fs";
19807
+
19808
+ // abortable.ts
19809
+ async function awaitWithAbort(operation, signal) {
19810
+ if (!signal) return operation;
19811
+ let onAbort = () => {
19812
+ };
19813
+ const aborted = new Promise((_resolve, reject) => {
19814
+ onAbort = () => reject(new Error("Aborted"));
19815
+ signal.addEventListener("abort", onAbort, { once: true });
19816
+ if (signal.aborted) onAbort();
19817
+ });
19818
+ try {
19819
+ const result = await Promise.race([operation, aborted]);
19820
+ if (signal.aborted) throw new Error("Aborted");
19821
+ return result;
19822
+ } finally {
19823
+ signal.removeEventListener("abort", onAbort);
19824
+ }
19825
+ }
19826
+
19782
19827
  // gemini-search.ts
19783
19828
  init_activity();
19784
19829
  init_credential_source();
@@ -19786,7 +19831,58 @@ init_gemini_api();
19786
19831
  init_gemini_adc();
19787
19832
  init_gemini_web();
19788
19833
  init_perplexity();
19789
- import { existsSync as existsSync43, readFileSync as readFileSync43 } from "node:fs";
19834
+ init_domain_filter_normalization();
19835
+
19836
+ // offtopic-judge.ts
19837
+ init_utils();
19838
+ var LABELS = ["addresses", "off_topic"];
19839
+ var INSTRUCTIONS = "A search engine returned this answer and these results for the query. addresses: the answer or at least one result is about what the query asks for, even if incomplete or outdated. off_topic: nothing is about what the query asks for, including results that only share words with it, a different meaning of the same word, or a different product.";
19840
+ var OFFTOPIC_JUDGE_MODELS = {
19841
+ "cloudflare-workers-ai/@cf/cloudflare/clef": 0.85,
19842
+ "typesafe/jev-latest": 0.85,
19843
+ "cloudflare-workers-ai/typesafe/jev-1.14.0": 0.85
19844
+ };
19845
+ var TIMEOUT_MS = 1e4;
19846
+ var MAX_RESULTS = 10;
19847
+ var MAX_ANSWER_CHARS = 4e3;
19848
+ var MAX_SNIPPET_CHARS = 500;
19849
+ var PROBABILITY_SUM_TOLERANCE = 0.02;
19850
+ async function judgeOffTopic(model, query, response, modelRegistry, signal) {
19851
+ if (typeof modelRegistry.findOfType !== "function" || typeof modelRegistry.classify !== "function") return { error: "this Pi version cannot run classifier models; update Pi" };
19852
+ const slash = model.indexOf("/");
19853
+ const classifier = modelRegistry.findOfType("classifier", model.slice(0, slash), model.slice(slash + 1));
19854
+ if (!classifier) return { error: `${model} is not in this Pi's classifier catalog` };
19855
+ const context = {
19856
+ state: {
19857
+ query,
19858
+ answer: response.answer.slice(0, MAX_ANSWER_CHARS),
19859
+ results: response.results.slice(0, MAX_RESULTS).map(({ title, url, snippet }) => ({ title, url, snippet: snippet.slice(0, MAX_SNIPPET_CHARS) }))
19860
+ },
19861
+ // Null criteria: empty strings changed Clef's answers.
19862
+ questions: { relevance: { type: "choice", instructions: INSTRUCTIONS, criteria: { addresses: null, off_topic: null } } }
19863
+ };
19864
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
19865
+ try {
19866
+ const result = await modelRegistry.classify(classifier, context, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
19867
+ signal?.throwIfAborted();
19868
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1e3} s` };
19869
+ if (result.stopReason !== "stop") return { error: result.errorMessage || `the model stopped with ${result.stopReason}` };
19870
+ const answer = result.answers?.relevance;
19871
+ const probabilities = isRecord(answer) ? answer.probabilities : void 0;
19872
+ if (!isRecord(answer) || !LABELS.includes(answer.choice) || !isRecord(probabilities)) return { error: "the response is invalid: relevance choice is not one of its labels" };
19873
+ const keys = Object.keys(probabilities);
19874
+ const values = LABELS.map((label) => probabilities[label]);
19875
+ if (keys.length !== LABELS.length || !values.every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1)) {
19876
+ return { error: "the response is invalid: relevance probabilities do not match the labels" };
19877
+ }
19878
+ if (Math.abs(values.reduce((total, value) => total + value, 0) - 1) > PROBABILITY_SUM_TOLERANCE) return { error: "the response is invalid: relevance probabilities do not sum to 1" };
19879
+ return { probabilities };
19880
+ } catch (err) {
19881
+ signal?.throwIfAborted();
19882
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1e3} s` };
19883
+ return { error: err instanceof Error ? err.message : String(err) };
19884
+ }
19885
+ }
19790
19886
 
19791
19887
  // exa.ts
19792
19888
  init_activity();
@@ -19798,6 +19894,7 @@ var EXA_MCP_URL = "https://mcp.exa.ai/mcp";
19798
19894
  var CONFIG_PATH5 = getWebSearchConfigPath();
19799
19895
  var EXA_MCP_ADVANCED_TOOL = "web_search_advanced_exa";
19800
19896
  var EXA_MCP_BASIC_TOOL = "web_search_exa";
19897
+ var MAX_LISTED_AUTHORS = 3;
19801
19898
  var cachedConfig5 = null;
19802
19899
  function loadConfig5() {
19803
19900
  if (cachedConfig5) return cachedConfig5;
@@ -19885,6 +19982,32 @@ function fallbackSourceLabel(url, index) {
19885
19982
  }
19886
19983
  return `Source ${index + 1}`;
19887
19984
  }
19985
+ function nonEmptyString(value) {
19986
+ return typeof value === "string" && value.trim().length > 0 && value.trim() !== "N/A" ? value.trim() : null;
19987
+ }
19988
+ function publicationProperties(entities) {
19989
+ const entity = Array.isArray(entities) ? entities.find((item) => isRecord(item) && item.type === "publication") : void 0;
19990
+ return isRecord(entity) && isRecord(entity.properties) ? entity.properties : null;
19991
+ }
19992
+ function listAuthors(names) {
19993
+ if (names.length === 0) return null;
19994
+ const listed = names.slice(0, MAX_LISTED_AUTHORS).join(", ");
19995
+ return names.length > MAX_LISTED_AUTHORS ? `${listed} et al.` : listed;
19996
+ }
19997
+ function formatResultMetadata(item) {
19998
+ const paper = publicationProperties(item.entities);
19999
+ const parts = [];
20000
+ const date = (nonEmptyString(item.publishedDate) ?? nonEmptyString(paper?.date))?.slice(0, 10) ?? (typeof paper?.year === "number" ? String(paper.year) : null);
20001
+ if (date) parts.push(`Published: ${date}`);
20002
+ const paperAuthors = Array.isArray(paper?.authors) ? paper.authors.flatMap((author) => nonEmptyString(isRecord(author) ? author.name : null) ?? []) : [];
20003
+ const authors = listAuthors(paperAuthors) ?? listAuthors(nonEmptyString(item.author)?.split(", ").map((name) => name.trim()).filter(Boolean) ?? []);
20004
+ if (authors) parts.push(`Authors: ${authors}`);
20005
+ if (typeof paper?.citationCount === "number") parts.push(`Citations: ${paper.citationCount}`);
20006
+ const doi = nonEmptyString(paper?.doi);
20007
+ if (doi) parts.push(`DOI: ${doi}`);
20008
+ return parts.length > 0 ? `
20009
+ ${parts.join(" | ")}` : "";
20010
+ }
19888
20011
  function buildAnswerFromSearchResults(results) {
19889
20012
  if (!results?.length) return "";
19890
20013
  const parts = [];
@@ -19896,7 +20019,7 @@ function buildAnswerFromSearchResults(results) {
19896
20019
  if (!content) continue;
19897
20020
  const sourceTitle = item.title || fallbackSourceLabel(item.url, i);
19898
20021
  parts.push(`${content}
19899
- Source: ${sourceTitle} (${item.url})`);
20022
+ Source: ${sourceTitle} (${item.url})${formatResultMetadata(item)}`);
19900
20023
  }
19901
20024
  return parts.join("\n\n");
19902
20025
  }
@@ -19999,17 +20122,23 @@ function parseMcpResults(text6) {
19999
20122
  const title = block.match(/^Title: (.+)/m)?.[1]?.trim() ?? "";
20000
20123
  const url = block.match(/^URL: (.+)/m)?.[1]?.trim() ?? "";
20001
20124
  let content = "";
20125
+ let contentStart = block.length;
20002
20126
  const textStart = block.indexOf("\nText: ");
20003
20127
  if (textStart >= 0) {
20004
20128
  content = block.slice(textStart + 7).trim();
20129
+ contentStart = textStart;
20005
20130
  } else {
20006
20131
  const hlMatch = block.match(/\nHighlights:\s*\n/);
20007
20132
  if (hlMatch?.index != null) {
20008
20133
  content = block.slice(hlMatch.index + hlMatch[0].length).trim();
20134
+ contentStart = hlMatch.index;
20009
20135
  }
20010
20136
  }
20011
20137
  content = content.replace(/\n---\s*$/, "").trim();
20012
- return { title, url, content };
20138
+ const header = block.slice(0, contentStart);
20139
+ const publishedDate = header.match(/^Published: (.+)/m)?.[1]?.trim();
20140
+ const author = header.match(/^Author: (.+)/m)?.[1]?.trim();
20141
+ return { title, url, content, publishedDate, author };
20013
20142
  }).filter((result) => result.url.length > 0);
20014
20143
  return parsed.length > 0 ? parsed : null;
20015
20144
  }
@@ -20022,7 +20151,7 @@ function buildAnswerFromMcpResults(results) {
20022
20151
  if (!snippet) continue;
20023
20152
  const sourceTitle = result.title || fallbackSourceLabel(result.url, i);
20024
20153
  parts.push(`${snippet}
20025
- Source: ${sourceTitle} (${result.url})`);
20154
+ Source: ${sourceTitle} (${result.url})${formatResultMetadata(result)}`);
20026
20155
  }
20027
20156
  return parts.join("\n\n");
20028
20157
  }
@@ -20538,6 +20667,9 @@ var CustomOpenAIBaseUrlError = class extends Error {
20538
20667
  };
20539
20668
  var OpenAIAlphaSearchUnsupportedError = class extends Error {
20540
20669
  };
20670
+ function isAzureResponsesUrl(url) {
20671
+ return url.protocol === "https:" && [".openai.azure.com", ".cognitiveservices.azure.com", ".services.ai.azure.com"].some((suffix) => url.hostname.endsWith(suffix)) && /^\/openai\/v1(?:\/responses)?\/?$/u.test(url.pathname);
20672
+ }
20541
20673
  function resolveCurrentModelSearchTarget(model) {
20542
20674
  const url = new URL(model.baseUrl);
20543
20675
  if (url.protocol !== "https:") throw new Error("Current model base URL must use HTTPS");
@@ -20549,7 +20681,11 @@ function resolveCurrentModelSearchTarget(model) {
20549
20681
  if (model.provider === "openai-codex" && model.api === "openai-codex-responses" && url.hostname.toLowerCase() === "chatgpt.com" && url.pathname.replace(/\/+$/u, "") === "/backend-api") {
20550
20682
  return { responsesUrl: CODEX_RESPONSES_URL, useCodexEndpoint: true };
20551
20683
  }
20552
- throw new Error("Current model is not backed by an official OpenAI Responses endpoint");
20684
+ if ((model.api === "openai-responses" || model.api === "azure-openai-responses") && isAzureResponsesUrl(url)) {
20685
+ url.pathname = "/openai/v1/responses";
20686
+ return { responsesUrl: url.toString(), useCodexEndpoint: false };
20687
+ }
20688
+ throw new Error("Current model is not backed by an official OpenAI or Azure Responses endpoint");
20553
20689
  }
20554
20690
  function isOpenAISubscriptionModelSelected(ctx) {
20555
20691
  const model = ctx?.model;
@@ -20558,10 +20694,10 @@ function isOpenAISubscriptionModelSelected(ctx) {
20558
20694
  }
20559
20695
  function isCurrentModelHostedSearchEligible(ctx) {
20560
20696
  const model = ctx?.model;
20561
- if (!model || !/^gpt-/iu.test(model.id)) return false;
20697
+ if (!model) return false;
20562
20698
  try {
20563
20699
  resolveCurrentModelSearchTarget(model);
20564
- return true;
20700
+ return /^gpt-/iu.test(model.id) || isAzureResponsesUrl(new URL(model.baseUrl));
20565
20701
  } catch {
20566
20702
  return false;
20567
20703
  }
@@ -20757,11 +20893,11 @@ async function resolvePiAuth(ctx, responsesUrl, providers, modelOverride, hasExp
20757
20893
  if (invalidProviderUrlError) throw invalidProviderUrlError;
20758
20894
  return void 0;
20759
20895
  }
20760
- async function resolveOpenAIAuth(ctx, signal) {
20896
+ async function resolveOpenAIAuth(ctx, signal, model) {
20761
20897
  const config = loadConfig7();
20762
20898
  const responsesUrl = resolveConfiguredResponsesUrl(config.openaiResponsesUrl);
20763
20899
  const useProviderBaseUrl = resolveUseProviderBaseUrl(config);
20764
- const modelOverride = resolveConfiguredSearchModel(config.openaiSearchModel);
20900
+ const modelOverride = model ?? resolveConfiguredSearchModel(config.openaiSearchModel);
20765
20901
  const providers = resolveConfiguredSearchProviders(config.openaiSearchProviders);
20766
20902
  if (ctx) {
20767
20903
  const auth = await resolvePiAuth(ctx, responsesUrl, providers, modelOverride, config.openaiResponsesUrl !== void 0, useProviderBaseUrl);
@@ -20805,13 +20941,13 @@ async function isOpenAISearchAvailable(ctx) {
20805
20941
  async function resolveCurrentModelAuth(ctx, signal) {
20806
20942
  const model = ctx.model;
20807
20943
  if (!model || !isCurrentModelHostedSearchEligible(ctx)) {
20808
- throw new Error("Current model is not eligible for official OpenAI Hosted web search");
20944
+ throw new Error("Current model is not eligible for OpenAI or Azure hosted web search");
20809
20945
  }
20810
- const target = resolveCurrentModelSearchTarget(model);
20811
20946
  const resolved = await ctx.modelRegistry.getApiKeyAndHeaders(model);
20812
20947
  if (signal?.aborted) signal.throwIfAborted();
20813
20948
  if (!resolved.ok) throw new Error(`OpenAI current model authentication failed: ${resolved.error}`);
20814
20949
  if (!resolved.apiKey) throw new Error("OpenAI current model authentication failed: API key unavailable");
20950
+ const target = resolveCurrentModelSearchTarget({ ...model, baseUrl: resolved.baseUrl ?? model.baseUrl });
20815
20951
  return {
20816
20952
  provider: "openai",
20817
20953
  apiKey: resolved.apiKey,
@@ -21083,9 +21219,13 @@ async function parseAlphaSearchResponse(response, numResults = 5) {
21083
21219
  }
21084
21220
  async function runOpenAISearch(query, options, auth, ctx) {
21085
21221
  const useAlphaSearch = isAlphaSearchEnabled();
21086
- if (useAlphaSearch) options.signal?.throwIfAborted();
21087
21222
  const useCodexEndpoint = auth.useCodexEndpoint ?? (auth.provider === "openai-codex" || isCodexJwt(auth.apiKey));
21088
21223
  const responsesUrl = useCodexEndpoint && !auth.useProviderBaseUrl ? CODEX_RESPONSES_URL : auth.responsesUrl;
21224
+ const isAzure = isAzureResponsesUrl(new URL(responsesUrl));
21225
+ if (isAzure && useAlphaSearch) {
21226
+ throw new OpenAIAlphaSearchUnsupportedError("Azure OpenAI does not support Codex alpha/search; disable openaiUseAlphaSearch to use hosted web_search");
21227
+ }
21228
+ if (useAlphaSearch) options.signal?.throwIfAborted();
21089
21229
  const requestUrl = useAlphaSearch ? resolveAlphaSearchUrl(responsesUrl) : responsesUrl;
21090
21230
  const body = useAlphaSearch ? buildAlphaSearchBody(query, options, auth.model) : {
21091
21231
  model: auth.model,
@@ -21115,13 +21255,21 @@ async function runOpenAISearch(query, options, auth, ctx) {
21115
21255
  requestUrl,
21116
21256
  ctx
21117
21257
  );
21258
+ if (isAzure) {
21259
+ for (const name of ["Authorization", "api-key", "OpenAI-Beta", "chatgpt-account-id", "originator"]) requestHeaders.delete(name);
21260
+ if (decodeJwtPayload(auth.apiKey)) {
21261
+ requestHeaders.set("Authorization", `Bearer ${auth.apiKey}`);
21262
+ } else {
21263
+ requestHeaders.set("api-key", auth.apiKey);
21264
+ }
21265
+ }
21118
21266
  try {
21119
21267
  const response = await fetchWithCredentialRedirects(requestUrl, {
21120
21268
  method: "POST",
21121
21269
  headers: requestHeaders,
21122
21270
  body: JSON.stringify(body),
21123
21271
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS3), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS3)
21124
- }, ["Authorization", "x-opencode-session", "x-opencode-client", "chatgpt-account-id", ...Object.keys(auth.headers)]);
21272
+ }, ["Authorization", "api-key", "x-opencode-session", "x-opencode-client", "chatgpt-account-id", ...Object.keys(auth.headers)]);
21125
21273
  if (!response.ok) {
21126
21274
  activityMonitor.logError(activityId, `HTTP ${response.status}`);
21127
21275
  const errorText = redactCredential(await response.text(), auth.apiKey);
@@ -21158,7 +21306,7 @@ async function runOpenAISearch(query, options, auth, ctx) {
21158
21306
  }
21159
21307
  }
21160
21308
  async function searchWithOpenAI(query, options = {}, ctx) {
21161
- const auth = await resolveOpenAIAuth(ctx, options.signal);
21309
+ const auth = await resolveOpenAIAuth(ctx, options.signal, options.model);
21162
21310
  if (!auth) {
21163
21311
  throw new Error(
21164
21312
  `OpenAI web search unavailable. Either:
@@ -22779,9 +22927,81 @@ async function searchWithDegoog(query, options = {}) {
22779
22927
  // duckduckgo.ts
22780
22928
  init_activity();
22781
22929
  init_domain_filter_normalization();
22930
+
22931
+ // duckduckgo-rate-limit.ts
22932
+ var DEFAULT_MIN_INTERVAL_MS = 2e3;
22933
+ var DEFAULT_COOLDOWN_MS = 5 * 6e4;
22934
+ var DEFAULT_MAX_COOLDOWN_MS = 60 * 6e4;
22935
+ var DEFAULT_TIMEOUT_MS = 3e4;
22936
+ var DuckDuckGoBotCheckError = class extends Error {
22937
+ constructor(status) {
22938
+ super(`DuckDuckGo blocked the request with a bot check (HTTP ${status}, rate limited); use another search provider`);
22939
+ this.name = "DuckDuckGoBotCheckError";
22940
+ }
22941
+ };
22942
+ var DuckDuckGoRateLimit = class {
22943
+ queue = Promise.resolve();
22944
+ lastStart = Number.NEGATIVE_INFINITY;
22945
+ blockedUntil = 0;
22946
+ nextCooldownMs;
22947
+ now;
22948
+ sleep;
22949
+ minIntervalMs;
22950
+ cooldownMs;
22951
+ maxCooldownMs;
22952
+ timeoutMs;
22953
+ constructor(options = {}) {
22954
+ this.now = options.now ?? Date.now;
22955
+ this.sleep = options.sleep ?? defaultSleep;
22956
+ this.minIntervalMs = options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
22957
+ this.cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS;
22958
+ this.maxCooldownMs = options.maxCooldownMs ?? DEFAULT_MAX_COOLDOWN_MS;
22959
+ this.nextCooldownMs = this.cooldownMs;
22960
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
22961
+ }
22962
+ /**
22963
+ * Queues `operation` and passes it a signal that fires on the caller's abort or when
22964
+ * the deadline passes. A passed deadline rejects with a "timed out" error rather than
22965
+ * an abort, so search routing treats it as a network failure and can fall back.
22966
+ */
22967
+ run(operation, callerSignal) {
22968
+ if (callerSignal?.aborted) return Promise.reject(new Error("Aborted"));
22969
+ const deadline = AbortSignal.timeout(this.timeoutMs);
22970
+ const signal = callerSignal ? AbortSignal.any([deadline, callerSignal]) : deadline;
22971
+ const scheduled = this.queue.then(() => this.runNow(operation, signal));
22972
+ this.queue = scheduled.then(() => void 0, () => void 0);
22973
+ return awaitWithAbort(scheduled, signal).catch((error) => {
22974
+ if (deadline.aborted && !callerSignal?.aborted) {
22975
+ throw new Error(`DuckDuckGo request timed out after ${formatWait(this.timeoutMs)}`);
22976
+ }
22977
+ throw error;
22978
+ });
22979
+ }
22980
+ async runNow(operation, signal) {
22981
+ if (signal.aborted) throw new Error("Aborted");
22982
+ const remainingMs = this.blockedUntil - this.now();
22983
+ if (remainingMs > 0) throw new Error(`DuckDuckGo showed a bot check recently; not retrying for ${formatWait(remainingMs)} (rate limited); use another search provider`);
22984
+ const waitMs = this.lastStart + this.minIntervalMs - this.now();
22985
+ if (waitMs > 0) await this.sleep(waitMs, signal);
22986
+ this.lastStart = this.now();
22987
+ try {
22988
+ const result = await operation(signal);
22989
+ this.nextCooldownMs = this.cooldownMs;
22990
+ return result;
22991
+ } catch (error) {
22992
+ if (error instanceof DuckDuckGoBotCheckError) {
22993
+ this.blockedUntil = this.now() + this.nextCooldownMs;
22994
+ this.nextCooldownMs = Math.min(this.nextCooldownMs * 2, this.maxCooldownMs);
22995
+ }
22996
+ throw error;
22997
+ }
22998
+ }
22999
+ };
23000
+
23001
+ // duckduckgo.ts
22782
23002
  init_search_result_count_normalization();
22783
23003
  var SEARCH_URL = "https://html.duckduckgo.com/html/";
22784
- var SEARCH_TIMEOUT_MS19 = 3e4;
23004
+ var rateLimit = new DuckDuckGoRateLimit();
22785
23005
  function normalizeDomainFilters5(domainFilter) {
22786
23006
  const filters = { allowed: [], blocked: [] };
22787
23007
  for (const raw of domainFilter ?? []) {
@@ -22819,46 +23039,48 @@ async function searchWithDuckDuckGo(query, options = {}) {
22819
23039
  url.searchParams.set("q", query);
22820
23040
  const activityId = activityMonitor.logStart({ type: "api", query });
22821
23041
  try {
22822
- const response = await fetch(url, {
22823
- method: "GET",
22824
- headers: {
22825
- Accept: "text/html",
22826
- "User-Agent": "Mozilla/5.0 (compatible; pi-web-access/1.0; +https://github.com/nicobailon/pi-web-access)"
22827
- },
22828
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS19), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS19)
22829
- });
22830
- if (!response.ok) {
22831
- const body = await response.text();
22832
- throw new Error(`DuckDuckGo search error ${response.status}: ${body.slice(0, 300)}`);
22833
- }
22834
- const { parseHTML } = await import("linkedom");
22835
- const { document } = parseHTML(await response.text());
22836
- if (response.status === 202 || document.querySelector(".anomaly-modal__box, #challenge-form")) {
22837
- throw new Error(`DuckDuckGo blocked the request with a bot check (HTTP ${response.status}, rate limited); use another search provider`);
22838
- }
22839
- const filters = normalizeDomainFilters5(options.domainFilter);
22840
- const results = [];
22841
- let parseableResults = 0;
22842
- for (const container of document.querySelectorAll(".result")) {
22843
- if (container.classList.contains("result--ad")) continue;
22844
- const anchor = container.querySelector(".result__a");
22845
- const title = anchor?.textContent?.trim() ?? "";
22846
- const href = anchor?.getAttribute("href")?.trim() ?? "";
22847
- const resultUrl = href ? decodeResultUrl(href) : null;
22848
- if (!title || !resultUrl) continue;
22849
- parseableResults++;
22850
- if (!matchesDomainFilters4(resultUrl, filters)) continue;
22851
- const snippet = container.querySelector(".result__snippet")?.textContent?.trim() ?? "";
22852
- results.push({ title, url: resultUrl, snippet });
22853
- if (results.length >= normalizeSearchResultCount(options.numResults)) break;
22854
- }
22855
- if (parseableResults === 0 && !document.querySelector(".no-results__message")) {
22856
- throw new Error("DuckDuckGo returned no parseable results (invalid response)");
22857
- }
22858
- activityMonitor.logComplete(activityId, response.status);
22859
- const answer = results.map((result) => result.snippet ? `${result.snippet}
23042
+ return await rateLimit.run(async (signal) => {
23043
+ const response = await fetch(url, {
23044
+ method: "GET",
23045
+ headers: {
23046
+ Accept: "text/html",
23047
+ "User-Agent": "Mozilla/5.0 (compatible; pi-web-access/1.0; +https://github.com/nicobailon/pi-web-access)"
23048
+ },
23049
+ signal
23050
+ });
23051
+ if (!response.ok) {
23052
+ const body = await response.text();
23053
+ throw new Error(`DuckDuckGo search error ${response.status}: ${body.slice(0, 300)}`);
23054
+ }
23055
+ const { parseHTML } = await import("linkedom");
23056
+ const { document } = parseHTML(await response.text());
23057
+ if (response.status === 202 || document.querySelector(".anomaly-modal__box, #challenge-form")) {
23058
+ throw new DuckDuckGoBotCheckError(response.status);
23059
+ }
23060
+ const filters = normalizeDomainFilters5(options.domainFilter);
23061
+ const results = [];
23062
+ let parseableResults = 0;
23063
+ for (const container of document.querySelectorAll(".result")) {
23064
+ if (container.classList.contains("result--ad")) continue;
23065
+ const anchor = container.querySelector(".result__a");
23066
+ const title = anchor?.textContent?.trim() ?? "";
23067
+ const href = anchor?.getAttribute("href")?.trim() ?? "";
23068
+ const resultUrl = href ? decodeResultUrl(href) : null;
23069
+ if (!title || !resultUrl) continue;
23070
+ parseableResults++;
23071
+ if (!matchesDomainFilters4(resultUrl, filters)) continue;
23072
+ const snippet = container.querySelector(".result__snippet")?.textContent?.trim() ?? "";
23073
+ results.push({ title, url: resultUrl, snippet });
23074
+ if (results.length >= normalizeSearchResultCount(options.numResults)) break;
23075
+ }
23076
+ if (parseableResults === 0 && !document.querySelector(".no-results__message")) {
23077
+ throw new Error("DuckDuckGo returned no parseable results (invalid response)");
23078
+ }
23079
+ activityMonitor.logComplete(activityId, response.status);
23080
+ const answer = results.map((result) => result.snippet ? `${result.snippet}
22860
23081
  Source: ${result.title} (${result.url})` : `Source: ${result.title} (${result.url})`).join("\n\n");
22861
- return { answer, results };
23082
+ return { answer, results };
23083
+ }, options.signal);
22862
23084
  } catch (err) {
22863
23085
  const message = err instanceof Error ? err.message : String(err);
22864
23086
  if (message.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
@@ -22876,7 +23098,7 @@ init_utils();
22876
23098
  import { existsSync as existsSync27, readFileSync as readFileSync27 } from "node:fs";
22877
23099
  var ANYSEARCH_API_URL = "https://api.anysearch.com/v1/search";
22878
23100
  var CONFIG_PATH24 = getWebSearchConfigPath();
22879
- var SEARCH_TIMEOUT_MS20 = 3e4;
23101
+ var SEARCH_TIMEOUT_MS19 = 3e4;
22880
23102
  var cachedConfig23 = null;
22881
23103
  function loadConfig23() {
22882
23104
  if (cachedConfig23) return cachedConfig23;
@@ -22961,7 +23183,7 @@ async function searchWithAnySearch(query, options = {}) {
22961
23183
  "Content-Type": "application/json"
22962
23184
  },
22963
23185
  body: JSON.stringify(body),
22964
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS20), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS20)
23186
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS19), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS19)
22965
23187
  }, ["Authorization"]);
22966
23188
  } catch (err) {
22967
23189
  const message = errorMessage16(err);
@@ -23016,7 +23238,7 @@ init_utils();
23016
23238
  import { existsSync as existsSync28, readFileSync as readFileSync28 } from "node:fs";
23017
23239
  var XCRAWL_API_URL = "https://run.xcrawl.com/v1/serp";
23018
23240
  var CONFIG_PATH25 = getWebSearchConfigPath();
23019
- var SEARCH_TIMEOUT_MS21 = 6e4;
23241
+ var SEARCH_TIMEOUT_MS20 = 6e4;
23020
23242
  var cachedConfig24 = null;
23021
23243
  function loadConfig24() {
23022
23244
  if (cachedConfig24) return cachedConfig24;
@@ -23136,7 +23358,7 @@ async function searchWithXCrawl(query, options = {}) {
23136
23358
  }
23137
23359
  const body = { engine: "google_search", q: query };
23138
23360
  const activityId = activityMonitor.logStart({ type: "api", query });
23139
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS21);
23361
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS20);
23140
23362
  let response;
23141
23363
  try {
23142
23364
  response = await fetchWithCredentialRedirects(resolveProviderApiUrl("xcrawl", XCRAWL_API_URL, loadConfig24().xcrawlBaseUrl), {
@@ -23157,7 +23379,7 @@ async function searchWithXCrawl(query, options = {}) {
23157
23379
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
23158
23380
  let outgoing;
23159
23381
  if (providerTimeout) {
23160
- outgoing = new Error(`XCrawl search request timed out after ${Math.round(SEARCH_TIMEOUT_MS21 / 1e3)}s`);
23382
+ outgoing = new Error(`XCrawl search request timed out after ${Math.round(SEARCH_TIMEOUT_MS20 / 1e3)}s`);
23161
23383
  } else {
23162
23384
  const redactedMessage = redactCredential(message, apiKey);
23163
23385
  outgoing = redactedMessage === message && err instanceof Error ? err : new Error(redactedMessage);
@@ -23293,9 +23515,9 @@ async function resolvePiAuth2(ctx, modelOverride, tools) {
23293
23515
  }
23294
23516
  return void 0;
23295
23517
  }
23296
- async function resolveXaiAuth(ctx, signal) {
23518
+ async function resolveXaiAuth(ctx, signal, model) {
23297
23519
  const config = loadConfig25();
23298
- const modelOverride = resolveConfiguredSearchModel2(config.xaiSearchModel);
23520
+ const modelOverride = model ?? resolveConfiguredSearchModel2(config.xaiSearchModel);
23299
23521
  const tools = resolveConfiguredSearchTools(config.xaiSearchTools);
23300
23522
  if (ctx && resolveConfiguredResponsesUrl2(config.xaiResponsesUrl) === void 0) {
23301
23523
  const auth = await resolvePiAuth2(ctx, modelOverride, tools);
@@ -23461,7 +23683,7 @@ async function searchWithXai(query, options = {}, ctx) {
23461
23683
  const tools = resolveConfiguredSearchTools(config.xaiSearchTools);
23462
23684
  const customUrl = resolveConfiguredResponsesUrl2(config.xaiResponsesUrl);
23463
23685
  const timeoutMs = resolveConfiguredSearchTimeoutMs(config.xaiSearchTimeoutMs);
23464
- const auth = await resolveXaiAuth(ctx, options.signal);
23686
+ const auth = await resolveXaiAuth(ctx, options.signal, options.model);
23465
23687
  if (!auth) {
23466
23688
  if (customUrl) {
23467
23689
  throw new Error(
@@ -23536,7 +23758,7 @@ init_utils();
23536
23758
  import { existsSync as existsSync30, readFileSync as readFileSync30 } from "node:fs";
23537
23759
  var BRIGHTDATA_API_URL = "https://api.brightdata.com/request";
23538
23760
  var CONFIG_PATH27 = getWebSearchConfigPath();
23539
- var SEARCH_TIMEOUT_MS22 = 6e4;
23761
+ var SEARCH_TIMEOUT_MS21 = 6e4;
23540
23762
  var ZONE_PATTERN = /^[A-Za-z0-9_-]+$/;
23541
23763
  var RECENCY_TBS = {
23542
23764
  day: "qdr:d",
@@ -23675,7 +23897,7 @@ function passesDomainFilters4(url, filters) {
23675
23897
  return filters.include.some((domain) => domainMatches4(hostname2, domain));
23676
23898
  }
23677
23899
  function requestSignal12(signal) {
23678
- const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS22);
23900
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS21);
23679
23901
  return signal ? AbortSignal.any([signal, timeout]) : timeout;
23680
23902
  }
23681
23903
  function errorMessage18(err) {
@@ -23833,7 +24055,7 @@ init_utils();
23833
24055
  import { existsSync as existsSync31, readFileSync as readFileSync31 } from "node:fs";
23834
24056
  var SERPBASE_API_URL = "https://api.serpbase.dev/google/search";
23835
24057
  var CONFIG_PATH28 = getWebSearchConfigPath();
23836
- var SEARCH_TIMEOUT_MS23 = 6e4;
24058
+ var SEARCH_TIMEOUT_MS22 = 6e4;
23837
24059
  var RECENCY_TBS2 = {
23838
24060
  day: "qdr:d",
23839
24061
  week: "qdr:w",
@@ -23952,7 +24174,7 @@ async function searchWithSerpBase(query, options = {}) {
23952
24174
  try {
23953
24175
  response = await fetchWithCredentialRedirects(String(url), {
23954
24176
  headers: { Accept: "application/json" },
23955
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS23), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS23)
24177
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS22), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS22)
23956
24178
  }, [], ["api_key"]);
23957
24179
  } catch (err) {
23958
24180
  const message = errorMessage19(err);
@@ -24002,7 +24224,7 @@ init_utils();
24002
24224
  import { existsSync as existsSync32, readFileSync as readFileSync32 } from "node:fs";
24003
24225
  var SERPAPI_API_BASE_URL = "https://serpapi.com";
24004
24226
  var CONFIG_PATH29 = getWebSearchConfigPath();
24005
- var SEARCH_TIMEOUT_MS24 = 6e4;
24227
+ var SEARCH_TIMEOUT_MS23 = 6e4;
24006
24228
  var RECENCY_TBS3 = {
24007
24229
  day: "qdr:d",
24008
24230
  week: "qdr:w",
@@ -24108,7 +24330,7 @@ async function searchWithSerpApi(query, options = {}) {
24108
24330
  url.searchParams.set("num", String(requestCount));
24109
24331
  if (options.recencyFilter) url.searchParams.set("tbs", RECENCY_TBS3[options.recencyFilter]);
24110
24332
  const activityId = activityMonitor.logStart({ type: "api", query });
24111
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS24);
24333
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS23);
24112
24334
  let response;
24113
24335
  let entries;
24114
24336
  try {
@@ -24135,7 +24357,7 @@ async function searchWithSerpApi(query, options = {}) {
24135
24357
  }
24136
24358
  const message = errorMessage20(err);
24137
24359
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
24138
- const outgoing = providerTimeout ? new Error(`SerpApi request timed out after ${Math.round(SEARCH_TIMEOUT_MS24 / 1e3)}s`) : (() => {
24360
+ const outgoing = providerTimeout ? new Error(`SerpApi request timed out after ${Math.round(SEARCH_TIMEOUT_MS23 / 1e3)}s`) : (() => {
24139
24361
  const redactedMessage = redactCredential(message, apiKey);
24140
24362
  if (redactedMessage === message && err instanceof Error) return err;
24141
24363
  const redactedError = new Error(redactedMessage);
@@ -24171,7 +24393,7 @@ init_utils();
24171
24393
  import { existsSync as existsSync33, readFileSync as readFileSync33 } from "node:fs";
24172
24394
  var SERPER_API_BASE_URL = "https://google.serper.dev";
24173
24395
  var CONFIG_PATH30 = getWebSearchConfigPath();
24174
- var SEARCH_TIMEOUT_MS25 = 6e4;
24396
+ var SEARCH_TIMEOUT_MS24 = 6e4;
24175
24397
  var RECENCY_TBS4 = {
24176
24398
  day: "qdr:d",
24177
24399
  week: "qdr:w",
@@ -24276,7 +24498,7 @@ async function searchWithSerper(query, options = {}) {
24276
24498
  method: "POST",
24277
24499
  headers: { "X-API-KEY": apiKey, "Content-Type": "application/json", Accept: "application/json" },
24278
24500
  body: JSON.stringify({ q: buildQuery4(query, filters), num: requestCount, ...options.recencyFilter ? { tbs: RECENCY_TBS4[options.recencyFilter] } : {} }),
24279
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS25), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS25)
24501
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS24), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS24)
24280
24502
  }, ["X-API-KEY"]);
24281
24503
  } catch (err) {
24282
24504
  const message = errorMessage21(err);
@@ -24333,7 +24555,7 @@ init_utils();
24333
24555
  import { existsSync as existsSync34, readFileSync as readFileSync34 } from "node:fs";
24334
24556
  var SERPLY_SEARCH_URL = "https://api.serply.io/v1/search";
24335
24557
  var CONFIG_PATH31 = getWebSearchConfigPath();
24336
- var SEARCH_TIMEOUT_MS26 = 6e4;
24558
+ var SEARCH_TIMEOUT_MS25 = 6e4;
24337
24559
  var RECENCY_TBS5 = {
24338
24560
  day: "qdr:d",
24339
24561
  week: "qdr:w",
@@ -24431,7 +24653,7 @@ async function searchWithSerply(query, options = {}) {
24431
24653
  url.searchParams.set("num", String(requestCount));
24432
24654
  if (options.recencyFilter) url.searchParams.set("tbs", RECENCY_TBS5[options.recencyFilter]);
24433
24655
  const activityId = activityMonitor.logStart({ type: "api", query });
24434
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS26);
24656
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS25);
24435
24657
  let response;
24436
24658
  let entries;
24437
24659
  try {
@@ -24458,7 +24680,7 @@ async function searchWithSerply(query, options = {}) {
24458
24680
  }
24459
24681
  const message = errorMessage22(err);
24460
24682
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
24461
- const outgoing = providerTimeout ? new Error(`Serply request timed out after ${Math.round(SEARCH_TIMEOUT_MS26 / 1e3)}s`) : (() => {
24683
+ const outgoing = providerTimeout ? new Error(`Serply request timed out after ${Math.round(SEARCH_TIMEOUT_MS25 / 1e3)}s`) : (() => {
24462
24684
  const redactedMessage = redactCredential(message, apiKey);
24463
24685
  if (redactedMessage === message && err instanceof Error) return err;
24464
24686
  const redactedError = new Error(redactedMessage);
@@ -24500,7 +24722,7 @@ init_utils();
24500
24722
  import { existsSync as existsSync35, readFileSync as readFileSync35 } from "node:fs";
24501
24723
  import { isIP as isIP2 } from "node:net";
24502
24724
  var MCP_URL = "https://agent-toolkit.app.baizhi.cloud/mcp";
24503
- var SEARCH_TIMEOUT_MS27 = 6e4;
24725
+ var SEARCH_TIMEOUT_MS26 = 6e4;
24504
24726
  var CONFIG_PATH32 = getWebSearchConfigPath();
24505
24727
  function credentialOptions() {
24506
24728
  let config = {};
@@ -24543,7 +24765,7 @@ function searchArguments(query, options) {
24543
24765
  }
24544
24766
  async function searchWithBaizhi(query, options = {}) {
24545
24767
  const args = searchArguments(query, options);
24546
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS27);
24768
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS26);
24547
24769
  const signal = options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
24548
24770
  if (signal.aborted) throw new Error("Aborted");
24549
24771
  const apiKey = await resolveCredential({ ...credentialOptions(), signal });
@@ -24571,8 +24793,8 @@ async function searchWithBaizhi(query, options = {}) {
24571
24793
  const client = new Client({ name: "pi-web-access-baizhi", version: "1.0.0" });
24572
24794
  const activityId = activityMonitor.logStart({ type: "api", query });
24573
24795
  try {
24574
- await client.connect(transport2, { signal, timeout: SEARCH_TIMEOUT_MS27 });
24575
- const result = await client.callTool({ name: "websearch_search", arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS27 });
24796
+ await client.connect(transport2, { signal, timeout: SEARCH_TIMEOUT_MS26 });
24797
+ const result = await client.callTool({ name: "websearch_search", arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS26 });
24576
24798
  if (result.isError) throw new Error("Baizhi search tool returned an error");
24577
24799
  const parts = [];
24578
24800
  if (result.structuredContent !== void 0) parts.push(JSON.stringify(result.structuredContent, null, 2));
@@ -24616,7 +24838,7 @@ var MCP_URLS = {
24616
24838
  china: "https://open.bigmodel.cn/api/mcp/web_search_prime/mcp"
24617
24839
  };
24618
24840
  var RECENCY = { day: "oneDay", week: "oneWeek", month: "oneMonth", year: "oneYear" };
24619
- var SEARCH_TIMEOUT_MS28 = 6e4;
24841
+ var SEARCH_TIMEOUT_MS27 = 6e4;
24620
24842
  var CONFIG_PATH33 = getWebSearchConfigPath();
24621
24843
  function loadConfig31() {
24622
24844
  if (!existsSync36(CONFIG_PATH33)) return {};
@@ -24687,7 +24909,7 @@ async function searchWithZai(query, options = {}) {
24687
24909
  const mcpUrl = endpointUrl(config);
24688
24910
  const args = searchArguments2(query, options);
24689
24911
  const limit = normalizeSearchResultCount(options.numResults);
24690
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS28);
24912
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS27);
24691
24913
  const signal = options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
24692
24914
  if (signal.aborted) throw new Error("Aborted");
24693
24915
  const apiKey = await resolveCredential({ ...credentialOptions2(config), signal });
@@ -24715,11 +24937,11 @@ async function searchWithZai(query, options = {}) {
24715
24937
  const client = new Client({ name: "pi-web-access-zai", version: "1.0.0" });
24716
24938
  const activityId = activityMonitor.logStart({ type: "api", query });
24717
24939
  try {
24718
- await client.connect(transport2, { signal, timeout: SEARCH_TIMEOUT_MS28 });
24719
- const { tools } = await client.listTools(void 0, { signal, timeout: SEARCH_TIMEOUT_MS28 });
24940
+ await client.connect(transport2, { signal, timeout: SEARCH_TIMEOUT_MS27 });
24941
+ const { tools } = await client.listTools(void 0, { signal, timeout: SEARCH_TIMEOUT_MS27 });
24720
24942
  const toolName = tools.find((tool) => tool.name === "web_search_prime" || tool.name === "webSearchPrime")?.name;
24721
24943
  if (!toolName) throw new Error("Z.ai returned invalid response: web search tool not listed");
24722
- const result = await client.callTool({ name: toolName, arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS28 });
24944
+ const result = await client.callTool({ name: toolName, arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS27 });
24723
24945
  if (result.isError) throw new Error("Z.ai search tool returned an error");
24724
24946
  const text6 = (Array.isArray(result.content) ? result.content : []).find((item) => item.type === "text" && typeof item.text === "string");
24725
24947
  if (!text6) throw new Error("Z.ai returned invalid response: no search text");
@@ -24756,8 +24978,8 @@ init_utils();
24756
24978
  import { existsSync as existsSync37, readFileSync as readFileSync37 } from "node:fs";
24757
24979
  var VALYU_SEARCH_URL = "https://api.valyu.ai/v1/search";
24758
24980
  var CONFIG_PATH34 = getWebSearchConfigPath();
24759
- var SEARCH_TIMEOUT_MS29 = 6e4;
24760
- var MAX_SNIPPET_CHARS = 2500;
24981
+ var SEARCH_TIMEOUT_MS28 = 6e4;
24982
+ var MAX_SNIPPET_CHARS2 = 2500;
24761
24983
  var MAX_CONTENT_CHARS = 4e3;
24762
24984
  var cachedConfig31 = null;
24763
24985
  function loadConfig32() {
@@ -24850,7 +25072,7 @@ async function searchWithValyu(query, options = {}) {
24850
25072
  method: "POST",
24851
25073
  headers: { "x-api-key": apiKey, "Content-Type": "application/json", Accept: "application/json" },
24852
25074
  body: JSON.stringify({ query, max_num_results: numResults, ...mapDomainFilter9(options.domainFilter), ...startDate ? { start_date: startDate } : {} }),
24853
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS29), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS29)
25075
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS28), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS28)
24854
25076
  }, ["x-api-key"]);
24855
25077
  } catch (err) {
24856
25078
  const message = errorMessage23(err);
@@ -24890,8 +25112,8 @@ async function searchWithValyu(query, options = {}) {
24890
25112
  if (!url) continue;
24891
25113
  const title = text(entry.title, Number.MAX_SAFE_INTEGER) || `Source ${results.length + 1}`;
24892
25114
  const content = text(entry.content, MAX_CONTENT_CHARS);
24893
- const description = text(entry.description, MAX_SNIPPET_CHARS);
24894
- results.push({ title, url, snippet: (content || description).slice(0, MAX_SNIPPET_CHARS) });
25115
+ const description = text(entry.description, MAX_SNIPPET_CHARS2);
25116
+ results.push({ title, url, snippet: (content || description).slice(0, MAX_SNIPPET_CHARS2) });
24895
25117
  if (options.includeContent && content) inlineContent.push({ url, title, content, error: null });
24896
25118
  if (results.length >= numResults) break;
24897
25119
  }
@@ -24910,9 +25132,9 @@ var KEENABLE_SEARCH_URL = "https://api.keenable.ai/v1/search";
24910
25132
  var KEENABLE_PUBLIC_SEARCH_URL = "https://api.keenable.ai/v1/search/public";
24911
25133
  var KEENABLE_CLIENT_TITLE = "pi-web-access";
24912
25134
  var CONFIG_PATH35 = getWebSearchConfigPath();
24913
- var SEARCH_TIMEOUT_MS30 = 3e4;
25135
+ var SEARCH_TIMEOUT_MS29 = 3e4;
24914
25136
  var MAX_REQUEST_RESULTS = 50;
24915
- var MAX_SNIPPET_CHARS2 = 500;
25137
+ var MAX_SNIPPET_CHARS3 = 500;
24916
25138
  var RECENCY_DAYS = {
24917
25139
  day: 1,
24918
25140
  week: 7,
@@ -25001,7 +25223,7 @@ async function searchWithKeenable(query, options = {}) {
25001
25223
  const body = {
25002
25224
  query: buildQuery6(query, filters, site),
25003
25225
  max_results: hasDomainClauses ? Math.min(MAX_REQUEST_RESULTS, numResults + 5) : numResults,
25004
- snippet_max_length: MAX_SNIPPET_CHARS2,
25226
+ snippet_max_length: MAX_SNIPPET_CHARS3,
25005
25227
  ...site ? { site } : {},
25006
25228
  ...options.recencyFilter ? { published_after: publishedAfter(options.recencyFilter) } : {}
25007
25229
  };
@@ -25012,7 +25234,7 @@ async function searchWithKeenable(query, options = {}) {
25012
25234
  ...apiKey ? { "X-API-Key": apiKey } : {}
25013
25235
  };
25014
25236
  const activityId = activityMonitor.logStart({ type: "api", query });
25015
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS30);
25237
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS29);
25016
25238
  let response;
25017
25239
  let entries;
25018
25240
  try {
@@ -25042,7 +25264,7 @@ async function searchWithKeenable(query, options = {}) {
25042
25264
  }
25043
25265
  const message = errorMessage24(err);
25044
25266
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
25045
- const outgoing = providerTimeout ? new Error(`Keenable request timed out after ${Math.round(SEARCH_TIMEOUT_MS30 / 1e3)}s`) : (() => {
25267
+ const outgoing = providerTimeout ? new Error(`Keenable request timed out after ${Math.round(SEARCH_TIMEOUT_MS29 / 1e3)}s`) : (() => {
25046
25268
  const redactedMessage = redactCredential(message, apiKey);
25047
25269
  if (redactedMessage === message && err instanceof Error) return err;
25048
25270
  const redactedError = new Error(redactedMessage);
@@ -25072,7 +25294,7 @@ async function searchWithKeenable(query, options = {}) {
25072
25294
  results.push({
25073
25295
  title: text2(entry.title) || `Source ${results.length + 1}`,
25074
25296
  url: resultUrl.href,
25075
- snippet: snippet.slice(0, MAX_SNIPPET_CHARS2)
25297
+ snippet: snippet.slice(0, MAX_SNIPPET_CHARS3)
25076
25298
  });
25077
25299
  if (results.length >= numResults) break;
25078
25300
  }
@@ -25089,10 +25311,10 @@ init_utils();
25089
25311
  import { existsSync as existsSync39, readFileSync as readFileSync39 } from "node:fs";
25090
25312
  var CERAMIC_SEARCH_URL = "https://api.ceramic.ai/search";
25091
25313
  var CONFIG_PATH36 = getWebSearchConfigPath();
25092
- var SEARCH_TIMEOUT_MS31 = 3e4;
25314
+ var SEARCH_TIMEOUT_MS30 = 3e4;
25093
25315
  var MAX_REQUEST_RESULTS2 = 20;
25094
25316
  var REQUEST_DESCRIPTION_CHARS = 1e3;
25095
- var MAX_SNIPPET_CHARS3 = 500;
25317
+ var MAX_SNIPPET_CHARS4 = 500;
25096
25318
  var cachedConfig33 = null;
25097
25319
  function loadConfig34() {
25098
25320
  if (cachedConfig33) return cachedConfig33;
@@ -25193,7 +25415,7 @@ async function searchWithCeramic(query, options = {}) {
25193
25415
  maxDescriptionLength: REQUEST_DESCRIPTION_CHARS
25194
25416
  };
25195
25417
  const activityId = activityMonitor.logStart({ type: "api", query });
25196
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS31);
25418
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS30);
25197
25419
  let response;
25198
25420
  let entries;
25199
25421
  try {
@@ -25226,7 +25448,7 @@ async function searchWithCeramic(query, options = {}) {
25226
25448
  }
25227
25449
  const message = errorMessage25(err);
25228
25450
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
25229
- const outgoing = providerTimeout ? new Error(`Ceramic request timed out after ${Math.round(SEARCH_TIMEOUT_MS31 / 1e3)}s`) : (() => {
25451
+ const outgoing = providerTimeout ? new Error(`Ceramic request timed out after ${Math.round(SEARCH_TIMEOUT_MS30 / 1e3)}s`) : (() => {
25230
25452
  const redactedMessage = redactCredential(message, apiKey);
25231
25453
  if (redactedMessage === message && err instanceof Error) return err;
25232
25454
  const redactedError = new Error(redactedMessage);
@@ -25255,7 +25477,7 @@ async function searchWithCeramic(query, options = {}) {
25255
25477
  results.push({
25256
25478
  title: text3(entry.title) || `Source ${results.length + 1}`,
25257
25479
  url: resultUrl.href,
25258
- snippet: text3(entry.description).slice(0, MAX_SNIPPET_CHARS3)
25480
+ snippet: text3(entry.description).slice(0, MAX_SNIPPET_CHARS4)
25259
25481
  });
25260
25482
  if (results.length >= numResults) break;
25261
25483
  }
@@ -25272,7 +25494,7 @@ init_utils();
25272
25494
  import { existsSync as existsSync40, readFileSync as readFileSync40 } from "node:fs";
25273
25495
  var LINKUP_SEARCH_URL = "https://api.linkup.so/v1/search";
25274
25496
  var CONFIG_PATH37 = getWebSearchConfigPath();
25275
- var SEARCH_TIMEOUT_MS32 = 6e4;
25497
+ var SEARCH_TIMEOUT_MS31 = 6e4;
25276
25498
  var DEPTHS = ["flash", "fast", "standard", "deep"];
25277
25499
  var cachedConfig34;
25278
25500
  function loadConfig35() {
@@ -25342,7 +25564,7 @@ async function searchWithLinkup(query, options = {}) {
25342
25564
  }
25343
25565
  const numResults = normalizeSearchResultCount(options.numResults);
25344
25566
  const fromDate = recencyToDate(options.recencyFilter);
25345
- const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS32);
25567
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS31);
25346
25568
  const signal = options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
25347
25569
  const activityId = activityMonitor.logStart({ type: "api", query });
25348
25570
  let entries;
@@ -25410,6 +25632,97 @@ async function searchWithLinkup(query, options = {}) {
25410
25632
  return { answer: formatSearchResultsAsAnswer(results), results, ...inlineContent.length ? { inlineContent } : {} };
25411
25633
  }
25412
25634
 
25635
+ // ninerouter.ts
25636
+ init_activity();
25637
+ init_credential_source();
25638
+ init_domain_filter_normalization();
25639
+ init_search_answer_formatting();
25640
+ init_search_result_count_normalization();
25641
+ init_utils();
25642
+ import { existsSync as existsSync41, readFileSync as readFileSync41 } from "node:fs";
25643
+ var CONFIG_PATH38 = getWebSearchConfigPath();
25644
+ var SEARCH_TIMEOUT_MS32 = 3e4;
25645
+ function loadConfig36() {
25646
+ if (!existsSync41(CONFIG_PATH38)) return {};
25647
+ let parsed;
25648
+ try {
25649
+ parsed = JSON.parse(readFileSync41(CONFIG_PATH38, "utf-8"));
25650
+ } catch {
25651
+ parsed = void 0;
25652
+ }
25653
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`Invalid config in ${CONFIG_PATH38}: expected a JSON object`);
25654
+ return parsed;
25655
+ }
25656
+ function isNineRouterAvailable() {
25657
+ const base = process.env.NINEROUTER_BASE_URL ?? loadConfig36().ninerouterBaseUrl;
25658
+ return typeof base === "string" && base.trim().length > 0;
25659
+ }
25660
+ async function searchWithNineRouter(query, options = {}) {
25661
+ const config = loadConfig36();
25662
+ const base = resolveApiBaseUrl({ configKey: "ninerouterBaseUrl", configuredValue: config.ninerouterBaseUrl, defaultValue: "", environmentKey: "NINEROUTER_BASE_URL", environmentValue: process.env.NINEROUTER_BASE_URL });
25663
+ if (!base) throw new Error(`9router base URL not found. Set ninerouterBaseUrl in ${CONFIG_PATH38} or NINEROUTER_BASE_URL (e.g. https://your-router/v1)`);
25664
+ const provider = process.env.NINEROUTER_SEARCH_PROVIDER || config.ninerouterProvider || "serper";
25665
+ if (typeof provider !== "string") throw new Error(`ninerouterProvider in ${CONFIG_PATH38} must be a string`);
25666
+ const apiKey = await resolveCredential({ provider: "9router", configuredValue: config.ninerouterApiKey, environmentValue: process.env.NINEROUTER_API_KEY, signal: options.signal });
25667
+ const include = [];
25668
+ const exclude = [];
25669
+ for (const raw of options.domainFilter ?? []) {
25670
+ const domain = normalizeDomain(raw);
25671
+ if (domain) (raw.trim().startsWith("-") ? exclude : include).push(domain);
25672
+ }
25673
+ const numResults = normalizeSearchResultCount(options.numResults);
25674
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS32);
25675
+ const activityId = activityMonitor.logStart({ type: "api", query });
25676
+ let data;
25677
+ try {
25678
+ const response = await fetchWithCredentialRedirects(`${base}/search`, {
25679
+ method: "POST",
25680
+ headers: { ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {}, "Content-Type": "application/json", Accept: "application/json" },
25681
+ body: JSON.stringify({
25682
+ provider,
25683
+ query,
25684
+ max_results: numResults,
25685
+ ...options.recencyFilter ? { time_range: options.recencyFilter } : {},
25686
+ ...include.length ? { domain_filter: include } : {}
25687
+ }),
25688
+ signal: options.signal ? AbortSignal.any([timeout, options.signal]) : timeout
25689
+ }, ["Authorization"]);
25690
+ if (!response.ok) throw new Error(`9router error ${response.status}: ${redactCredential(await response.text(), apiKey).slice(0, 300)}`);
25691
+ data = await response.json().catch((err) => {
25692
+ throw err instanceof SyntaxError ? new Error("9router returned invalid JSON") : err;
25693
+ });
25694
+ activityMonitor.logComplete(activityId, response.status);
25695
+ } catch (err) {
25696
+ if (!options.signal?.aborted && (timeout.aborted || err instanceof Error && err.name === "TimeoutError")) {
25697
+ const message2 = `9router request timed out after ${SEARCH_TIMEOUT_MS32 / 1e3}s`;
25698
+ activityMonitor.logError(activityId, message2);
25699
+ throw new Error(message2);
25700
+ }
25701
+ const message = redactCredential(err instanceof Error ? err.message : String(err), apiKey);
25702
+ activityMonitor.logError(activityId, message);
25703
+ if (err instanceof Error && err.message === message) throw err;
25704
+ throw new Error(message);
25705
+ }
25706
+ if (!Array.isArray(data?.results)) throw new Error("9router returned invalid response: expected results array");
25707
+ const results = [];
25708
+ for (const entry of data.results) {
25709
+ let url;
25710
+ try {
25711
+ url = new URL(String(entry?.url));
25712
+ } catch {
25713
+ continue;
25714
+ }
25715
+ if (url.protocol !== "https:" && url.protocol !== "http:") continue;
25716
+ const matches = (domain) => url.hostname === domain || url.hostname.endsWith(`.${domain}`);
25717
+ if (exclude.some(matches) || include.length && !include.some(matches)) continue;
25718
+ const title = typeof entry.title === "string" && entry.title.trim() ? entry.title.trim() : `Source ${results.length + 1}`;
25719
+ results.push({ title, url: url.href, snippet: typeof entry.snippet === "string" ? entry.snippet : "" });
25720
+ if (results.length >= numResults) break;
25721
+ }
25722
+ const answer = typeof data.answer === "string" ? data.answer.trim() : "";
25723
+ return { answer: answer || formatSearchResultsAsAnswer(results), results };
25724
+ }
25725
+
25413
25726
  // gemini-search.ts
25414
25727
  init_deepseek();
25415
25728
 
@@ -25589,30 +25902,30 @@ init_activity();
25589
25902
  init_domain_filter_normalization();
25590
25903
  init_credential_source();
25591
25904
  init_utils();
25592
- import { existsSync as existsSync42, readFileSync as readFileSync42 } from "node:fs";
25905
+ import { existsSync as existsSync43, readFileSync as readFileSync43 } from "node:fs";
25593
25906
  var MISTRAL_CONVERSATIONS_URL = "https://api.mistral.ai/v1/conversations";
25594
- var CONFIG_PATH39 = getWebSearchConfigPath();
25907
+ var CONFIG_PATH40 = getWebSearchConfigPath();
25595
25908
  var SEARCH_TIMEOUT_MS35 = 6e4;
25596
25909
  var DEFAULT_SEARCH_MODEL = "mistral-small-latest";
25597
25910
  var DEFAULT_SEARCH_TOOL = "web_search";
25598
- var MAX_RESULTS = 20;
25911
+ var MAX_RESULTS2 = 20;
25599
25912
  var cachedConfig36 = null;
25600
- function loadConfig37() {
25913
+ function loadConfig38() {
25601
25914
  if (cachedConfig36) return cachedConfig36;
25602
- if (!existsSync42(CONFIG_PATH39)) {
25915
+ if (!existsSync43(CONFIG_PATH40)) {
25603
25916
  cachedConfig36 = {};
25604
25917
  return cachedConfig36;
25605
25918
  }
25606
- const raw = readFileSync42(CONFIG_PATH39, "utf-8");
25919
+ const raw = readFileSync43(CONFIG_PATH40, "utf-8");
25607
25920
  let parsed;
25608
25921
  try {
25609
25922
  parsed = JSON.parse(raw);
25610
25923
  } catch (err) {
25611
25924
  const message = err instanceof Error ? err.message : String(err);
25612
- throw new Error(`Failed to parse ${CONFIG_PATH39}: ${message}`);
25925
+ throw new Error(`Failed to parse ${CONFIG_PATH40}: ${message}`);
25613
25926
  }
25614
25927
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
25615
- throw new Error(`Invalid config in ${CONFIG_PATH39}: expected a JSON object`);
25928
+ throw new Error(`Invalid config in ${CONFIG_PATH40}: expected a JSON object`);
25616
25929
  }
25617
25930
  cachedConfig36 = parsed;
25618
25931
  return cachedConfig36;
@@ -25620,20 +25933,20 @@ function loadConfig37() {
25620
25933
  function resolveSearchModel(value) {
25621
25934
  if (value === void 0) return DEFAULT_SEARCH_MODEL;
25622
25935
  if (typeof value !== "string" || value.trim().length === 0) {
25623
- throw new Error(`mistralSearchModel in ${CONFIG_PATH39} must be a non-empty string`);
25936
+ throw new Error(`mistralSearchModel in ${CONFIG_PATH40} must be a non-empty string`);
25624
25937
  }
25625
25938
  return value.trim();
25626
25939
  }
25627
25940
  function resolveSearchTool(value) {
25628
25941
  if (value === void 0) return DEFAULT_SEARCH_TOOL;
25629
25942
  if (value !== "web_search" && value !== "web_search_premium") {
25630
- throw new Error(`mistralSearchTool in ${CONFIG_PATH39} must be either web_search or web_search_premium`);
25943
+ throw new Error(`mistralSearchTool in ${CONFIG_PATH40} must be either web_search or web_search_premium`);
25631
25944
  }
25632
25945
  return value;
25633
25946
  }
25634
25947
  function normalizeCount4(value) {
25635
25948
  if (typeof value !== "number" || !Number.isFinite(value)) return 5;
25636
- return Math.max(1, Math.min(Math.floor(value), MAX_RESULTS));
25949
+ return Math.max(1, Math.min(Math.floor(value), MAX_RESULTS2));
25637
25950
  }
25638
25951
  function parseDomainFilters(domainFilter) {
25639
25952
  const filters = { include: [], exclude: [] };
@@ -25734,14 +26047,14 @@ function parseConversationResponse(value, options, numResults) {
25734
26047
  async function getApiKey26(signal) {
25735
26048
  const apiKey = await resolveCredential({
25736
26049
  provider: "Mistral",
25737
- configuredValue: loadConfig37().mistralApiKey,
26050
+ configuredValue: loadConfig38().mistralApiKey,
25738
26051
  environmentValue: process.env.MISTRAL_API_KEY,
25739
26052
  signal
25740
26053
  });
25741
26054
  if (!apiKey) {
25742
26055
  throw new Error(
25743
26056
  `Mistral API key not found. Either:
25744
- 1. Create ${CONFIG_PATH39} with { "mistralApiKey": "your-key" }
26057
+ 1. Create ${CONFIG_PATH40} with { "mistralApiKey": "your-key" }
25745
26058
  2. Set MISTRAL_API_KEY environment variable
25746
26059
  Get a key at https://console.mistral.ai/api-keys`
25747
26060
  );
@@ -25750,7 +26063,7 @@ Get a key at https://console.mistral.ai/api-keys`
25750
26063
  }
25751
26064
  function isMistralAvailable() {
25752
26065
  try {
25753
- const config = loadConfig37();
26066
+ const config = loadConfig38();
25754
26067
  resolveSearchModel(config.mistralSearchModel);
25755
26068
  resolveSearchTool(config.mistralSearchTool);
25756
26069
  return hasCredentialSource({
@@ -25763,15 +26076,15 @@ function isMistralAvailable() {
25763
26076
  }
25764
26077
  }
25765
26078
  async function searchWithMistral(query, options = {}) {
25766
- const config = loadConfig37();
25767
- const model = resolveSearchModel(config.mistralSearchModel);
26079
+ const config = loadConfig38();
26080
+ const model = options.model ?? resolveSearchModel(config.mistralSearchModel);
25768
26081
  const tool = resolveSearchTool(config.mistralSearchTool);
25769
26082
  const numResults = normalizeCount4(options.numResults);
25770
26083
  const apiKey = await getApiKey26(options.signal);
25771
26084
  const requestSignal15 = options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS35), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS35);
25772
26085
  const activityId = activityMonitor.logStart({ type: "api", query });
25773
26086
  try {
25774
- const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("mistralSearch", MISTRAL_CONVERSATIONS_URL, loadConfig37().mistralSearchBaseUrl), {
26087
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("mistralSearch", MISTRAL_CONVERSATIONS_URL, loadConfig38().mistralSearchBaseUrl), {
25775
26088
  method: "POST",
25776
26089
  headers: {
25777
26090
  Authorization: `Bearer ${apiKey}`,
@@ -25815,7 +26128,7 @@ async function searchWithMistral(query, options = {}) {
25815
26128
 
25816
26129
  // gemini-search.ts
25817
26130
  init_utils();
25818
- var RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "serpdive", "kagi", "ollama", "anysearch", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "bocha", "xcrawl", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup"];
26131
+ var RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "serpdive", "kagi", "ollama", "anysearch", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "bocha", "xcrawl", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup", "ninerouter"];
25819
26132
  var SEARCH_PROVIDERS = ["auto", "all", ...RESOLVED_SEARCH_PROVIDERS];
25820
26133
  var SearchProviderError = class extends Error {
25821
26134
  provider;
@@ -25831,18 +26144,19 @@ var SearchProviderError = class extends Error {
25831
26144
  this.causeError = cause;
25832
26145
  }
25833
26146
  };
25834
- var CONFIG_PATH40 = getWebSearchConfigPath();
26147
+ var CONFIG_PATH41 = getWebSearchConfigPath();
25835
26148
  var DEFAULT_SEARCH_MODEL2 = "gemini-3.6-flash";
25836
26149
  var ALL_SEARCH_PROVIDERS = ["searxng", "openai", "exa", "brave", "parallel", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "serpdive", "kagi", "ollama", "perplexity", "gemini", "bocha"];
25837
- var VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported"];
26150
+ var VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported", "empty", "domain-miss", "off-topic"];
26151
+ var MAX_ROUTING_TIMEOUT_MS = 6e5;
25838
26152
  var cachedSearchConfig = null;
25839
26153
  function getSearchConfig() {
25840
26154
  if (cachedSearchConfig) return cachedSearchConfig;
25841
- if (!existsSync43(CONFIG_PATH40)) {
26155
+ if (!existsSync44(CONFIG_PATH41)) {
25842
26156
  cachedSearchConfig = { searchProvider: "auto", searchProviderConfigured: false };
25843
26157
  return cachedSearchConfig;
25844
26158
  }
25845
- const rawText = readFileSync43(CONFIG_PATH40, "utf-8");
26159
+ const rawText = readFileSync44(CONFIG_PATH41, "utf-8");
25846
26160
  let raw;
25847
26161
  try {
25848
26162
  const parsed = JSON.parse(rawText);
@@ -25852,25 +26166,25 @@ function getSearchConfig() {
25852
26166
  raw = parsed;
25853
26167
  } catch (err) {
25854
26168
  const message = err instanceof Error ? err.message : String(err);
25855
- throw new Error(`Failed to parse ${CONFIG_PATH40}: ${message}`);
26169
+ throw new Error(`Failed to parse ${CONFIG_PATH41}: ${message}`);
25856
26170
  }
25857
26171
  const searchModel = normalizeSearchModel(raw.searchModel);
25858
26172
  const webSearch = raw.webSearch;
25859
26173
  if (webSearch !== void 0 && (!webSearch || typeof webSearch !== "object" || Array.isArray(webSearch))) {
25860
- throw new Error(`webSearch in ${CONFIG_PATH40} must be an object`);
26174
+ throw new Error(`webSearch in ${CONFIG_PATH41} must be an object`);
25861
26175
  }
25862
- const allowedProviders = webSearch && Object.hasOwn(webSearch, "allowedProviders") ? normalizeResolvedProviderList(webSearch.allowedProviders, `webSearch.allowedProviders in ${CONFIG_PATH40}`) : void 0;
26176
+ const allowedProviders = webSearch && Object.hasOwn(webSearch, "allowedProviders") ? normalizeResolvedProviderList(webSearch.allowedProviders, `webSearch.allowedProviders in ${CONFIG_PATH41}`) : void 0;
25863
26177
  const searchProviderConfigured = Object.hasOwn(raw, "searchProvider") || Object.hasOwn(raw, "provider");
25864
- const searchProvider = normalizeSearchProviderSelection(raw.searchProvider ?? raw.provider, `provider in ${CONFIG_PATH40}`);
26178
+ const searchProvider = normalizeSearchProviderSelection(raw.searchProvider ?? raw.provider, `provider in ${CONFIG_PATH41}`);
25865
26179
  const searchRouting = Object.hasOwn(raw, "searchRouting") ? normalizeSearchRouting(raw.searchRouting) : void 0;
25866
26180
  if (allowedProviders) {
25867
26181
  if (Object.hasOwn(raw, "searchProvider")) {
25868
- assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.searchProvider), `searchProvider in ${CONFIG_PATH40}`, allowedProviders);
26182
+ assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.searchProvider), `searchProvider in ${CONFIG_PATH41}`, allowedProviders);
25869
26183
  }
25870
26184
  if (Object.hasOwn(raw, "provider")) {
25871
- assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.provider), `provider in ${CONFIG_PATH40}`, allowedProviders);
26185
+ assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.provider), `provider in ${CONFIG_PATH41}`, allowedProviders);
25872
26186
  }
25873
- if (searchRouting) assertSearchProviderSelectionAllowed(searchRouting.providers, `searchRouting.providers in ${CONFIG_PATH40}`, allowedProviders);
26187
+ if (searchRouting) assertSearchProviderSelectionAllowed(searchRouting.providers, `searchRouting.providers in ${CONFIG_PATH41}`, allowedProviders);
25874
26188
  }
25875
26189
  cachedSearchConfig = {
25876
26190
  searchProvider,
@@ -25883,30 +26197,43 @@ function getSearchConfig() {
25883
26197
  }
25884
26198
  function normalizeSearchRouting(value) {
25885
26199
  if (!value || typeof value !== "object" || Array.isArray(value)) {
25886
- throw new Error(`searchRouting in ${CONFIG_PATH40} must be an object`);
26200
+ throw new Error(`searchRouting in ${CONFIG_PATH41} must be an object`);
25887
26201
  }
25888
26202
  const raw = value;
25889
- const providers = normalizeResolvedProviderList(raw.providers, `searchRouting.providers in ${CONFIG_PATH40}`);
26203
+ const providers = normalizeResolvedProviderList(raw.providers, `searchRouting.providers in ${CONFIG_PATH41}`);
25890
26204
  const useCurrentModel = raw.useCurrentModel;
25891
26205
  if (useCurrentModel !== void 0 && typeof useCurrentModel !== "boolean") {
25892
- throw new Error(`searchRouting.useCurrentModel in ${CONFIG_PATH40} must be a boolean`);
26206
+ throw new Error(`searchRouting.useCurrentModel in ${CONFIG_PATH41} must be a boolean`);
25893
26207
  }
25894
26208
  if (!Array.isArray(raw.fallbackOn) || raw.fallbackOn.length === 0) {
25895
- throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH40} must be a non-empty array`);
26209
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH41} must be a non-empty array`);
25896
26210
  }
25897
26211
  const fallbackOn = [];
25898
26212
  for (const kind of raw.fallbackOn) {
25899
26213
  if (typeof kind !== "string" || !VALID_ROUTING_KINDS.includes(kind)) {
25900
- throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH40} may only contain transient, quota, network, invalid-response, or unsupported`);
26214
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH41} may only contain transient, quota, network, invalid-response, unsupported, empty, domain-miss, or off-topic`);
25901
26215
  }
25902
26216
  if (!fallbackOn.includes(kind)) {
25903
26217
  fallbackOn.push(kind);
25904
26218
  }
25905
26219
  }
26220
+ const timeoutMs = raw.timeoutMs;
26221
+ if (timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_ROUTING_TIMEOUT_MS)) {
26222
+ throw new Error(`searchRouting.timeoutMs in ${CONFIG_PATH41} must be an integer from 1 through ${MAX_ROUTING_TIMEOUT_MS}`);
26223
+ }
26224
+ const offTopicModel = raw.offTopicModel;
26225
+ if (offTopicModel !== void 0 && (typeof offTopicModel !== "string" || !Object.hasOwn(OFFTOPIC_JUDGE_MODELS, offTopicModel))) {
26226
+ throw new Error(`searchRouting.offTopicModel in ${CONFIG_PATH41} must be one of ${Object.keys(OFFTOPIC_JUDGE_MODELS).join(", ")}`);
26227
+ }
26228
+ if (fallbackOn.includes("off-topic") && offTopicModel === void 0) {
26229
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH41} lists off-topic, which needs searchRouting.offTopicModel`);
26230
+ }
25906
26231
  return {
25907
26232
  providers,
25908
26233
  ...useCurrentModel !== void 0 ? { useCurrentModel } : {},
25909
- fallbackOn
26234
+ fallbackOn,
26235
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
26236
+ ...offTopicModel !== void 0 ? { offTopicModel } : {}
25910
26237
  };
25911
26238
  }
25912
26239
  function normalizeSearchModel(value) {
@@ -25947,6 +26274,51 @@ function normalizeSearchProviderSelection(value, label = "provider") {
25947
26274
  const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
25948
26275
  return SEARCH_PROVIDERS.includes(normalized) ? normalized : "auto";
25949
26276
  }
26277
+ function parseProviderArgument(value) {
26278
+ if (value === void 0) return void 0;
26279
+ if (Array.isArray(value)) return normalizeResolvedProviderList(value, "provider");
26280
+ const unknown = (name) => new Error(`Unknown search provider "${name}". Use auto, all, or one or more comma-separated names: ${getAllowedSearchProviders().join(", ")}`);
26281
+ if (typeof value !== "string") throw unknown(String(value));
26282
+ const normalized = value.trim().toLowerCase();
26283
+ if (normalized === "") return void 0;
26284
+ let names;
26285
+ if (normalized.startsWith("[")) {
26286
+ let parsed;
26287
+ try {
26288
+ parsed = JSON.parse(normalized);
26289
+ } catch {
26290
+ throw new Error("provider must be a provider name or comma-separated names; the given value is not valid JSON");
26291
+ }
26292
+ names = parsed.map((entry) => String(entry).trim());
26293
+ } else {
26294
+ names = normalized.split(",").map((name) => name.trim()).filter(Boolean);
26295
+ if (names.length < 2) {
26296
+ if (!SEARCH_PROVIDERS.includes(names[0])) throw unknown(names[0] ?? value);
26297
+ return names[0];
26298
+ }
26299
+ }
26300
+ if (names.some((name) => name === "auto" || name === "all")) {
26301
+ throw new Error('"auto" and "all" cannot be combined with provider names');
26302
+ }
26303
+ const invalid = names.find((name) => !RESOLVED_SEARCH_PROVIDERS.includes(name));
26304
+ if (invalid !== void 0) throw unknown(invalid);
26305
+ return normalizeResolvedProviderList(names, "provider");
26306
+ }
26307
+ function validateSearchModelOverride(provider, model) {
26308
+ if (model === void 0) return void 0;
26309
+ if (typeof model !== "string" || !model.trim()) {
26310
+ throw new Error("model must be a non-empty model ID");
26311
+ }
26312
+ const selected = parseProviderArgument(provider);
26313
+ if (selected === void 0 || Array.isArray(selected) || selected === "auto" || selected === "all") {
26314
+ throw new Error("model requires one explicit provider: openai, xai, mistral, or gemini (API only); omitted, auto, all, and provider lists are ambiguous");
26315
+ }
26316
+ if (!["openai", "xai", "mistral", "gemini"].includes(selected)) {
26317
+ throw new Error(`model is not supported for provider ${JSON.stringify(selected)}; use openai, xai, mistral, or gemini (API only)`);
26318
+ }
26319
+ assertSearchProviderSelectionAllowed(selected, "Requested provider");
26320
+ return model.trim();
26321
+ }
25950
26322
  function errorMessage28(err) {
25951
26323
  return err instanceof Error ? err.message : String(err);
25952
26324
  }
@@ -25966,6 +26338,11 @@ async function tryOpenAIInAuto(query, options, fallbackErrors, take) {
25966
26338
  return null;
25967
26339
  }
25968
26340
  async function searchWithGemini(query, options, strictErrors) {
26341
+ if (options.model !== void 0) {
26342
+ const result = await searchWithGeminiApi(query, options);
26343
+ if (result) return result;
26344
+ throw new Error("Gemini API search unavailable: an explicit model requires API-path authentication (API key, ADC, or gateway), not browser cookies");
26345
+ }
25969
26346
  const errors = [];
25970
26347
  try {
25971
26348
  const apiResult = await searchWithGeminiApi(query, options);
@@ -26074,6 +26451,7 @@ async function searchWithResolvedProvider(provider, query, options, useCurrentMo
26074
26451
  if (provider === "keenable") return { ...await searchWithKeenable(query, options), provider };
26075
26452
  if (provider === "ceramic") return { ...await searchWithCeramic(query, options), provider };
26076
26453
  if (provider === "linkup") return { ...await searchWithLinkup(query, options), provider };
26454
+ if (provider === "ninerouter") return { ...await searchWithNineRouter(query, options), provider };
26077
26455
  if (provider === "deepseek") return { ...await searchWithDeepSeek(query, options), provider };
26078
26456
  if (provider === "xcrawl") return { ...await searchWithXCrawl(query, options), provider };
26079
26457
  if (provider === "perplexity") return { ...await searchWithPerplexity(query, options), provider };
@@ -26086,7 +26464,7 @@ async function searchWithResolvedProvider(provider, query, options, useCurrentMo
26086
26464
  if (result2) return { ...result2, provider };
26087
26465
  throw new Error(
26088
26466
  `Gemini search unavailable. Either:
26089
- 1. Configure geminiApiKey in ${CONFIG_PATH40} or set GEMINI_API_KEY
26467
+ 1. Configure geminiApiKey in ${CONFIG_PATH41} or set GEMINI_API_KEY
26090
26468
  2. Set GOOGLE_GEMINI_BASE_URL + CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing
26091
26469
  3. Set geminiAuth to "adc" in web-search.json with a Google Cloud ADC + project/location
26092
26470
  4. Sign into gemini.google.com in a supported Chromium-based browser`
@@ -26129,6 +26507,7 @@ async function isResolvedProviderAvailable(provider, options, useCurrentModel =
26129
26507
  if (provider === "keenable") return isKeenableAvailable();
26130
26508
  if (provider === "ceramic") return isCeramicAvailable();
26131
26509
  if (provider === "linkup") return isLinkupAvailable();
26510
+ if (provider === "ninerouter") return isNineRouterAvailable();
26132
26511
  if (provider === "deepseek") return isDeepSeekAvailable();
26133
26512
  if (provider === "xcrawl") return isXcrawlAvailable();
26134
26513
  if (provider === "perplexity") return isPerplexityAvailable();
@@ -26177,6 +26556,7 @@ function providerLabel(provider) {
26177
26556
  if (provider === "keenable") return "Keenable";
26178
26557
  if (provider === "ceramic") return "Ceramic";
26179
26558
  if (provider === "linkup") return "Linkup";
26559
+ if (provider === "ninerouter") return "9router";
26180
26560
  if (provider === "deepseek") return "DeepSeek";
26181
26561
  return provider.charAt(0).toUpperCase() + provider.slice(1);
26182
26562
  }
@@ -26193,7 +26573,7 @@ async function searchWithProviders(query, options, selectedProviders, routing) {
26193
26573
  available: provider === "gemini" ? isGeminiApiAvailable() : await isResolvedProviderAvailable(provider, options)
26194
26574
  })))).filter((entry) => entry.available).map((entry) => entry.provider);
26195
26575
  if (providers.length === 0) {
26196
- throw new Error('No configured search provider available for provider "all". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, XCrawl, Keenable, Ceramic, DeepSeek, and Linkup are excluded.');
26576
+ throw new Error('No configured search provider available for provider "all". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, XCrawl, Keenable, Ceramic, DeepSeek, Linkup, and 9router are excluded.');
26197
26577
  }
26198
26578
  const settled = await Promise.allSettled(
26199
26579
  providers.map((provider) => selectedProviders ? searchWithResolvedProvider(provider, query, options) : searchWithAllProvider(provider, query, options))
@@ -26263,17 +26643,65 @@ ${failures.map(({ provider, error }) => `- **${providerLabel(provider)}:** ${err
26263
26643
  ...inlineContent.length > 0 ? { inlineContent } : {}
26264
26644
  };
26265
26645
  }
26266
- async function searchWithConfiguredRouting(query, options, routing) {
26646
+ function weakResult(response, domainFilter) {
26647
+ const empty = response.results.length === 0 && !response.answer.trim();
26648
+ const wanted = (domainFilter ?? []).filter((domain) => !domain.trim().startsWith("-")).flatMap((domain) => normalizeDomain(domain) ?? []);
26649
+ const domainMiss = wanted.length > 0 && !response.results.some((result) => {
26650
+ const host = URL.parse(result.url)?.hostname;
26651
+ return host !== void 0 && wanted.some((domain) => host === domain || host.endsWith(`.${domain}`));
26652
+ });
26653
+ return { empty, domainMiss };
26654
+ }
26655
+ async function searchWithConfiguredRouting(query, callerOptions, routing) {
26656
+ const deadline = routing.timeoutMs ? AbortSignal.timeout(routing.timeoutMs) : void 0;
26657
+ const signal = deadline && (callerOptions.signal ? AbortSignal.any([callerOptions.signal, deadline]) : deadline);
26658
+ const options = signal ? { ...callerOptions, signal } : callerOptions;
26659
+ const timedOut = () => deadline?.aborted === true && callerOptions.signal?.aborted !== true;
26660
+ const untilDeadline = (work) => awaitWithAbort(work, signal);
26267
26661
  const diagnostics = [];
26662
+ let firstWeak;
26268
26663
  for (const provider of routing.providers) {
26664
+ if (timedOut()) {
26665
+ diagnostics.push(`routing timeout after ${routing.timeoutMs}ms`);
26666
+ break;
26667
+ }
26269
26668
  const useCurrentModel = provider === "openai" && routing.useCurrentModel === true;
26270
- if (!await isResolvedProviderAvailable(provider, options, useCurrentModel)) {
26669
+ const available = await untilDeadline(isResolvedProviderAvailable(provider, options, useCurrentModel)).catch((err) => {
26670
+ if (timedOut()) return void 0;
26671
+ throw err;
26672
+ });
26673
+ if (available === void 0) {
26674
+ diagnostics.push(`${provider}: routing timeout after ${routing.timeoutMs}ms`);
26675
+ break;
26676
+ }
26677
+ if (!available) {
26271
26678
  diagnostics.push(`${provider}: unavailable`);
26272
26679
  continue;
26273
26680
  }
26274
26681
  try {
26275
- return await searchWithResolvedProvider(provider, query, options, useCurrentModel);
26682
+ const response = await untilDeadline(searchWithResolvedProvider(provider, query, options, useCurrentModel));
26683
+ const weak = weakResult(response, options.domainFilter);
26684
+ let kind = weak.empty && routing.fallbackOn.includes("empty") ? "empty" : weak.domainMiss && routing.fallbackOn.includes("domain-miss") ? "domain-miss" : void 0;
26685
+ const registry = options.extensionContext?.modelRegistry;
26686
+ if (!kind && !weak.empty && routing.offTopicModel && routing.fallbackOn.includes("off-topic") && registry) {
26687
+ const judgment = await untilDeadline(judgeOffTopic(routing.offTopicModel, query, response, registry, options.signal)).catch((err) => {
26688
+ if (timedOut()) return { error: `routing timeout after ${routing.timeoutMs}ms` };
26689
+ throw err;
26690
+ });
26691
+ if ("error" in judgment) {
26692
+ const line = `${provider}: off-topic check failed: ${judgment.error}`;
26693
+ diagnostics.push(line);
26694
+ activityMonitor.logError(activityMonitor.logStart({ type: "api", query }), line);
26695
+ } else if (judgment.probabilities.off_topic >= OFFTOPIC_JUDGE_MODELS[routing.offTopicModel]) kind = "off-topic";
26696
+ }
26697
+ if (!kind) return response;
26698
+ diagnostics.push(`${provider} [${kind}]`);
26699
+ firstWeak ??= response;
26276
26700
  } catch (err) {
26701
+ if (timedOut()) {
26702
+ diagnostics.push(`${provider}: routing timeout after ${routing.timeoutMs}ms`);
26703
+ break;
26704
+ }
26277
26705
  const classified = classifyProviderError(provider, err);
26278
26706
  diagnostics.push(`${provider} [${classified.kind}]: ${errorMessage28(err)}`);
26279
26707
  if (!routing.fallbackOn.includes(classified.kind)) {
@@ -26281,6 +26709,7 @@ async function searchWithConfiguredRouting(query, options, routing) {
26281
26709
  }
26282
26710
  }
26283
26711
  }
26712
+ if (firstWeak) return firstWeak;
26284
26713
  throw new Error(`Configured search routing exhausted:
26285
26714
  - ${diagnostics.join("\n - ")}`);
26286
26715
  }
@@ -26358,11 +26787,11 @@ async function search(query, options = {}) {
26358
26787
  throw new Error(
26359
26788
  `No search provider available. Either:
26360
26789
  1. Use /login to sign in with a Codex subscription for OpenAI web search
26361
- 2. Set openaiApiKey, braveApiKey, parallelApiKey, tinyfishApiKey, search1apiApiKey, searchinfinityApiKey, queritApiKey, tavilyApiKey, firecrawlBaseUrl, jinaApiKey, serpdiveApiKey, kagiApiKey, ollamaApiKey, searxngBaseUrl, perplexityApiKey, exaApiKey, geminiApiKey, bochaApiKey, or cloudflareApiKey in ${CONFIG_PATH40}
26790
+ 2. Set openaiApiKey, braveApiKey, parallelApiKey, tinyfishApiKey, search1apiApiKey, searchinfinityApiKey, queritApiKey, tavilyApiKey, firecrawlBaseUrl, jinaApiKey, serpdiveApiKey, kagiApiKey, ollamaApiKey, searxngBaseUrl, perplexityApiKey, exaApiKey, geminiApiKey, bochaApiKey, or cloudflareApiKey in ${CONFIG_PATH41}
26362
26791
  3. Set OPENAI_API_KEY, BRAVE_API_KEY, PARALLEL_API_KEY, TINYFISH_API_KEY, SEARCH1API_KEY, SEARCHINFINITY_API_KEY, QUERIT_API_KEY, TAVILY_API_KEY, FIRECRAWL_BASE_URL, JINA_API_KEY, SERPDIVE_API_KEY, KAGI_API_KEY, BOCHA_API_KEY, OLLAMA_API_KEY, SEARXNG_BASE_URL, EXA_API_KEY, PERPLEXITY_API_KEY, GEMINI_API_KEY, or CLOUDFLARE_API_KEY env vars
26363
26792
  4. Set GOOGLE_GEMINI_BASE_URL with CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing
26364
26793
  5. Sign into gemini.google.com in a supported Chromium-based browser
26365
- 6. Explicitly select provider: "anysearch" for anonymous AnySearch, "xcrawl" for XCrawl, "xai" for Grok, "mistral" for Mistral Conversations web search, "brightdata" with brightdataSerpZone for paid Bright Data SERP, "serpbase", "serpapi", "serper", or "serply" for Google SERP, "you" for You.com, "zai" for Z.ai GLM Coding Plan search, "valyu" for research search, "keenable" for keyless Keenable search, "ceramic" for Ceramic search, "deepseek" for DeepSeek search, or "linkup" for Linkup search`
26794
+ 6. Explicitly select provider: "anysearch" for anonymous AnySearch, "xcrawl" for XCrawl, "xai" for Grok, "mistral" for Mistral Conversations web search, "brightdata" with brightdataSerpZone for paid Bright Data SERP, "serpbase", "serpapi", "serper", or "serply" for Google SERP, "you" for You.com, "zai" for Z.ai GLM Coding Plan search, "valyu" for research search, "keenable" for keyless Keenable search, "ceramic" for Ceramic search, "deepseek" for DeepSeek search, "linkup" for Linkup search, or "ninerouter" for a 9router gateway`
26366
26795
  );
26367
26796
  }
26368
26797
  async function searchWithGeminiApi(query, options = {}) {
@@ -26374,12 +26803,12 @@ async function searchWithGeminiApi(query, options = {}) {
26374
26803
  if (!apiKey && !isGatewayConfigured() && !isGeminiAdcAvailable()) return null;
26375
26804
  const activityId = activityMonitor.logStart({ type: "api", query });
26376
26805
  try {
26377
- const model = getSearchConfig().searchModel ?? DEFAULT_SEARCH_MODEL2;
26806
+ const model = options.model ?? getSearchConfig().searchModel ?? DEFAULT_SEARCH_MODEL2;
26378
26807
  const body = {
26379
26808
  contents: [{ role: "user", parts: [{ text: query }] }],
26380
26809
  tools: [{ google_search: {} }]
26381
26810
  };
26382
- const res = await fetchGeminiApi(`${getVersionedApiBase()}/models/${model}:generateContent`, {
26811
+ const res = await fetchGeminiApi(`${getVersionedApiBase()}/models/${options.model !== void 0 ? encodeURIComponent(model) : model}:generateContent`, {
26383
26812
  method: "POST",
26384
26813
  headers: { "Content-Type": "application/json" },
26385
26814
  body: JSON.stringify(body),
@@ -26394,7 +26823,10 @@ async function searchWithGeminiApi(query, options = {}) {
26394
26823
  const answer = data.candidates?.[0]?.content?.parts?.map((p) => p.text).filter(Boolean).join("\n") ?? "";
26395
26824
  const metadata = data.candidates?.[0]?.groundingMetadata;
26396
26825
  const results = await resolveGroundingChunks(metadata?.groundingChunks, options.signal);
26397
- if (!answer && results.length === 0) return null;
26826
+ if (!answer && results.length === 0) {
26827
+ if (options.model !== void 0) throw new Error("Gemini API returned no answer or sources");
26828
+ return null;
26829
+ }
26398
26830
  return { answer, results };
26399
26831
  } catch (err) {
26400
26832
  const message = err instanceof Error ? err.message : String(err);
@@ -26635,7 +27067,7 @@ function createMcpServer(core2, info, enabledTools) {
26635
27067
  }
26636
27068
 
26637
27069
  // web-tool-core.ts
26638
- import { existsSync as existsSync56, readFileSync as readFileSync57 } from "node:fs";
27070
+ import { existsSync as existsSync57, readFileSync as readFileSync58 } from "node:fs";
26639
27071
  import pLimit2 from "p-limit";
26640
27072
 
26641
27073
  // fetch-params.ts
@@ -26686,8 +27118,8 @@ function normalizeOptionalString(value) {
26686
27118
  }
26687
27119
  function normalizeMode(value) {
26688
27120
  if (value === void 0) return void 0;
26689
- if (value === "readable" || value === "raw" || value === "answer") return value;
26690
- throw new Error('mode must be "readable", "raw", or "answer"');
27121
+ if (value === "readable" || value === "raw" || value === "answer" || value === "extract") return value;
27122
+ throw new Error('mode must be "readable", "raw", "answer", or "extract"');
26691
27123
  }
26692
27124
  function normalizeRedirects(value) {
26693
27125
  if (value === void 0) return void 0;
@@ -26942,11 +27374,294 @@ Showing 0 of ${matches.length} matches.`;
26942
27374
  return formatRanges(ranges, true, omitted);
26943
27375
  }
26944
27376
 
27377
+ // field-extract.ts
27378
+ init_credential_source();
27379
+ init_utils();
27380
+ var MAX_FIELDS = 16;
27381
+ var MAX_PAGE_CHARS = 2e5;
27382
+ var EXTRACT_THRESHOLD = 0.8;
27383
+ var TIMEOUT_MS2 = 3e4;
27384
+ var DURATION_UNITS = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
27385
+ function parseExtractFields(fields) {
27386
+ if (!isRecord(fields)) throw new Error("fields must be an object mapping names to types");
27387
+ const entries = Object.entries(fields);
27388
+ if (entries.length === 0 || entries.length > MAX_FIELDS) throw new Error(`fields must list 1 to ${MAX_FIELDS} fields`);
27389
+ const specs = /* @__PURE__ */ Object.create(null);
27390
+ for (const [name, raw] of entries) {
27391
+ if (!/^[A-Za-z0-9_]{1,64}$/.test(name)) throw new Error(`field name "${name}" must be 1 to 64 letters, digits, or underscores`);
27392
+ if (typeof raw !== "string") throw new Error(`field ${name} must be a string such as "number" or "date: when it ships"`);
27393
+ const colon = raw.indexOf(":");
27394
+ const type = (colon === -1 ? raw : raw.slice(0, colon)).trim();
27395
+ const instructions = colon === -1 ? "" : raw.slice(colon + 1).trim();
27396
+ const [base, sub, extra] = type.split(".");
27397
+ let spec;
27398
+ if (sub === void 0 && ["text", "number", "date", "time", "datetime", "duration"].includes(base)) spec = { type: base };
27399
+ else if (sub === void 0 && base === "integer") spec = { type: "number", integer: true };
27400
+ else if (sub === void 0 && base === "list") spec = { type: "list", items: "text" };
27401
+ else if (base === "duration" && DURATION_UNITS.includes(sub)) spec = { type: "duration", unit: sub };
27402
+ else if (base === "list" && (sub === "number" || sub === "date")) spec = { type: "list", items: sub };
27403
+ if (!spec || extra !== void 0) {
27404
+ throw new Error(`field ${name} has unknown type "${type}"; use text, number, integer, date, time, datetime, duration, duration.<${DURATION_UNITS.join("|")}>, list, list.number, or list.date`);
27405
+ }
27406
+ specs[name] = instructions ? { ...spec, instructions } : spec;
27407
+ }
27408
+ return specs;
27409
+ }
27410
+ function realDate(text6) {
27411
+ const [year, month, day] = text6.split("-").map(Number);
27412
+ const date = new Date(Date.UTC(year, month - 1, day));
27413
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
27414
+ }
27415
+ function realTime(text6) {
27416
+ const [hours, minutes, seconds = 0] = text6.split(":").map(Number);
27417
+ return hours <= 23 && minutes <= 59 && seconds <= 59;
27418
+ }
27419
+ function matchesType(spec, value) {
27420
+ switch (spec.type) {
27421
+ case "text":
27422
+ return typeof value === "string" && value.trim() !== "";
27423
+ case "number":
27424
+ return typeof value === "number" && Number.isFinite(value) && (!spec.integer || Number.isInteger(value));
27425
+ case "duration":
27426
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
27427
+ case "date":
27428
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && realDate(value);
27429
+ case "time":
27430
+ return typeof value === "string" && /^\d{2}:\d{2}(:\d{2})?$/.test(value) && realTime(value);
27431
+ case "datetime": {
27432
+ const match = typeof value === "string" ? /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-](\d{2}:\d{2}))?$/.exec(value) : null;
27433
+ return match !== null && realDate(match[1]) && realTime(match[2]) && (match[3] === void 0 || realTime(match[3]));
27434
+ }
27435
+ case "list":
27436
+ return Array.isArray(value) && value.every((item) => matchesType({ type: spec.items }, item));
27437
+ }
27438
+ }
27439
+ function fieldResult(spec, answer) {
27440
+ if (!isRecord(answer)) throw new Error("the response is invalid: a field answer is missing");
27441
+ const { value = null, confidence: rawConfidence } = answer;
27442
+ if (value === null) return { status: "null" };
27443
+ const confidence = typeof rawConfidence === "number" && rawConfidence >= 0 && rawConfidence <= 1 ? rawConfidence : void 0;
27444
+ if (confidence !== void 0 && confidence >= EXTRACT_THRESHOLD && matchesType(spec, value)) return { status: "extracted", value, confidence };
27445
+ return { status: "uncertain", guess: value, ...confidence !== void 0 ? { confidence } : {} };
27446
+ }
27447
+ var MAX_LINE_CHARS = 200;
27448
+ var MAX_LINK_TARGET_CHARS = 2048;
27449
+ var SEPARATORS = /* @__PURE__ */ new Set([",", ".", " ", "\xA0", "\u202F", "'"]);
27450
+ var isDigit = (char) => char !== void 0 && char >= "0" && char <= "9";
27451
+ function closingParens(line) {
27452
+ const close = /* @__PURE__ */ new Map();
27453
+ const open = [];
27454
+ for (let i = 0; i < line.length; i++) {
27455
+ if (line[i] === "(") open.push(i);
27456
+ else if (line[i] === ")" && open.length) {
27457
+ const start = open.pop();
27458
+ if (i - start <= MAX_LINK_TARGET_CHARS) close.set(start, i);
27459
+ }
27460
+ }
27461
+ return close;
27462
+ }
27463
+ function comparable(raw, visible) {
27464
+ const close = visible ? closingParens(raw) : void 0;
27465
+ let text6 = "";
27466
+ const map = [];
27467
+ let space = false;
27468
+ const emit = (chars, at) => {
27469
+ const folded = chars.normalize("NFKC");
27470
+ for (const char of folded.length > 4 * chars.length ? chars : folded) {
27471
+ const plain = /[‘’‚‛′]/.test(char) ? "'" : /[“”„‟″]/.test(char) ? '"' : /[‐-―]/.test(char) ? "-" : char;
27472
+ if (/[*_`[\]]/.test(plain)) continue;
27473
+ if (/\s/.test(plain)) {
27474
+ if (text6 && !space) {
27475
+ text6 += " ";
27476
+ map.push(at);
27477
+ space = true;
27478
+ }
27479
+ continue;
27480
+ }
27481
+ const lower = plain.toLowerCase();
27482
+ text6 += lower;
27483
+ if (lower) space = false;
27484
+ for (let unit = 0; unit < lower.length; unit++) map.push(at);
27485
+ }
27486
+ };
27487
+ for (let i = 0; i < raw.length; ) {
27488
+ if (raw[i] === "\\" && i + 1 < raw.length && /[!-/:-@[-`{-~]/.test(raw[i + 1])) {
27489
+ emit(raw[i + 1], i + 1);
27490
+ i += 2;
27491
+ continue;
27492
+ }
27493
+ const target = close && raw[i] === "]" && raw[i + 1] === "(" ? close.get(i + 1) : void 0;
27494
+ if (target !== void 0) {
27495
+ i = target + 1;
27496
+ continue;
27497
+ }
27498
+ let next = i + String.fromCodePoint(raw.codePointAt(i)).length;
27499
+ while (next < raw.length && new RegExp("\\p{M}", "u").test(String.fromCodePoint(raw.codePointAt(next)))) next += raw.codePointAt(next) > 65535 ? 2 : 1;
27500
+ emit(raw.slice(i, next), i);
27501
+ i = next;
27502
+ }
27503
+ if (space) {
27504
+ text6 = text6.slice(0, -1);
27505
+ map.pop();
27506
+ }
27507
+ return { text: text6, map };
27508
+ }
27509
+ function indexLines(page) {
27510
+ const lines = page.split("\n");
27511
+ const forms = lines.map((line) => {
27512
+ const visible = comparable(line, true);
27513
+ return [visible, line.includes("](") ? comparable(line, false) : visible];
27514
+ });
27515
+ const whole = [0, 1].map((form) => forms.map((pair) => pair[form].text).filter(Boolean).join(" "));
27516
+ return { lines, forms, whole };
27517
+ }
27518
+ function cite(line, start, end) {
27519
+ if (line.length <= MAX_LINE_CHARS) return line.replace(/\s+/g, " ").trim();
27520
+ const size = MAX_LINE_CHARS - 2;
27521
+ const from = Math.max(0, Math.min(line.length - size, end - start >= size ? start : start - Math.floor((size - (end - start)) / 2)));
27522
+ return `${from > 0 ? "\u2026" : ""}${line.slice(from, from + size).replace(/\s+/g, " ").trim()}${from + size < line.length ? "\u2026" : ""}`;
27523
+ }
27524
+ function locateText(value, page) {
27525
+ const wanted = comparable(value, false).text;
27526
+ if (!wanted) return null;
27527
+ for (const [index, pair] of page.forms.entries()) {
27528
+ for (const form of pair) {
27529
+ const at = form.text.indexOf(wanted);
27530
+ if (at !== -1) return cite(page.lines[index], form.map[at], form.map[at + wanted.length - 1] + 1);
27531
+ }
27532
+ }
27533
+ return page.whole.some((text6) => text6.includes(wanted)) ? null : void 0;
27534
+ }
27535
+ function readings(groups, separators) {
27536
+ const thousands = (parts) => parts.slice(1).every((part) => part.length === 3);
27537
+ const values = [];
27538
+ if (thousands(groups)) values.push(Number(groups.join("")));
27539
+ const decimal = separators.at(-1);
27540
+ if ((decimal === "." || decimal === ",") && separators.slice(0, -1).every((separator) => separator !== decimal) && thousands(groups.slice(0, -1))) {
27541
+ values.push(Number(`${groups.slice(0, -1).join("")}.${groups.at(-1)}`));
27542
+ }
27543
+ return values;
27544
+ }
27545
+ function locateNumber(value, lines) {
27546
+ for (const line of lines) {
27547
+ for (let i = 0; i < line.length; ) {
27548
+ if (!isDigit(line[i])) {
27549
+ i++;
27550
+ continue;
27551
+ }
27552
+ const groups = [];
27553
+ const separators = [];
27554
+ let end = i;
27555
+ for (; ; ) {
27556
+ const from = end;
27557
+ while (isDigit(line[end])) end++;
27558
+ groups.push(line.slice(from, end));
27559
+ if (!SEPARATORS.has(line[end]) || !isDigit(line[end + 1])) break;
27560
+ separators.push(line[end]);
27561
+ end++;
27562
+ }
27563
+ let sign = i - 1;
27564
+ if (/[$€£¥]/.test(line[sign] ?? "")) sign--;
27565
+ const negative = (line[sign] === "-" || line[sign] === "\u2212") && !/[\p{L}\p{N}]/u.test(line[sign - 1] ?? "");
27566
+ if (readings(groups, separators).some((reading) => (negative ? -reading : reading) === value)) return cite(line, negative ? sign : i, end);
27567
+ i = end;
27568
+ }
27569
+ }
27570
+ return void 0;
27571
+ }
27572
+ function withPageLine(spec, result, page) {
27573
+ if (result.status === "null") return result;
27574
+ const value = result.status === "extracted" ? result.value : result.guess;
27575
+ if (spec.type === "number" && typeof value === "number") {
27576
+ const line2 = locateNumber(value, page().lines);
27577
+ return line2 ? { ...result, line: line2 } : result;
27578
+ }
27579
+ if (spec.type !== "text" || typeof value !== "string") return result;
27580
+ const line = locateText(value, page());
27581
+ if (line) return { ...result, line };
27582
+ if (line === void 0 && result.status === "extracted") return { status: "uncertain", guess: result.value, confidence: result.confidence, notFound: true };
27583
+ return result;
27584
+ }
27585
+ async function runClairic(body, modelRegistry, signal) {
27586
+ if (!modelRegistry) throw new Error("extract mode runs only inside Pi");
27587
+ if (typeof modelRegistry.getProviderAuth !== "function") throw new Error("this Pi version cannot supply the Cloudflare credential; update Pi");
27588
+ const credential = await modelRegistry.getProviderAuth("cloudflare-workers-ai");
27589
+ const apiKey = credential?.auth.apiKey;
27590
+ const accountId = credential?.env?.CLOUDFLARE_ACCOUNT_ID;
27591
+ if (!apiKey || !accountId) throw new Error("Cloudflare Workers AI is not set up in Pi; set CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID");
27592
+ const gatewayId = (await modelRegistry.getProviderAuth("cloudflare-ai-gateway"))?.env?.CLOUDFLARE_GATEWAY_ID ?? process.env.CLOUDFLARE_GATEWAY_ID;
27593
+ let parsed;
27594
+ try {
27595
+ const response = await fetchWithCredentialRedirects(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/ai/run/@cf/cloudflare/clairic`, {
27596
+ method: "POST",
27597
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", ...gatewayId ? { "cf-aig-gateway-id": gatewayId } : {} },
27598
+ body,
27599
+ signal
27600
+ }, ["Authorization"]);
27601
+ const text6 = await response.text();
27602
+ if (!response.ok) {
27603
+ const detail = redactCredential(text6, apiKey).trim().slice(0, 200);
27604
+ throw new Error(`Cloudflare Workers AI returned HTTP ${response.status}${detail ? `: ${detail}` : ""}`);
27605
+ }
27606
+ try {
27607
+ parsed = JSON.parse(text6);
27608
+ } catch {
27609
+ throw new Error("the response is invalid: it is not JSON");
27610
+ }
27611
+ } catch (err) {
27612
+ throw new Error(redactCredential(err instanceof Error ? err.message : String(err), apiKey));
27613
+ }
27614
+ if (!isRecord(parsed) || parsed.success !== true || !isRecord(parsed.result)) throw new Error("Cloudflare Workers AI reported an unsuccessful response");
27615
+ return parsed.result;
27616
+ }
27617
+ async function extractPageFields(page, fields, context, signal, referenceDate = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)) {
27618
+ const cut = page.length > MAX_PAGE_CHARS;
27619
+ const state = cut ? page.slice(0, MAX_PAGE_CHARS) : page;
27620
+ const body = JSON.stringify({
27621
+ model: "clairic",
27622
+ state,
27623
+ fields,
27624
+ reference_date: referenceDate
27625
+ });
27626
+ const timeout = AbortSignal.timeout(TIMEOUT_MS2);
27627
+ try {
27628
+ const result = await runClairic(body, context.modelRegistry, signal ? AbortSignal.any([signal, timeout]) : timeout);
27629
+ const answers = result.answers;
27630
+ if (!isRecord(answers)) throw new Error("the response is invalid: answers are missing");
27631
+ let lines;
27632
+ const page2 = () => lines ??= indexLines(state);
27633
+ const results = Object.fromEntries(Object.entries(fields).map(([name, spec]) => [name, withPageLine(spec, fieldResult(spec, Object.hasOwn(answers, name) ? answers[name] : void 0), page2)]));
27634
+ return { fields: results, cut: cut || result.truncated === true };
27635
+ } catch (err) {
27636
+ signal?.throwIfAborted();
27637
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS2 / 1e3} s` };
27638
+ return { error: err instanceof Error ? err.message : String(err) };
27639
+ }
27640
+ }
27641
+ var MAX_SHOWN_VALUE_CHARS = 1e3;
27642
+ var shown = (value) => {
27643
+ const text6 = typeof value === "string" ? value : JSON.stringify(value);
27644
+ return text6.length > MAX_SHOWN_VALUE_CHARS ? `${text6.slice(0, MAX_SHOWN_VALUE_CHARS)}\u2026 [${text6.length} characters; the rest is in the stored page]` : text6;
27645
+ };
27646
+ function formatPageExtraction(extraction) {
27647
+ if ("error" in extraction) return `Extraction failed: ${extraction.error}
27648
+ `;
27649
+ const lines = Object.entries(extraction.fields).map(([name, result]) => {
27650
+ const from = result.status !== "null" && result.line ? ` from "${result.line}"` : "";
27651
+ if (result.status === "extracted") return `${name}: ${shown(result.value)} (${result.confidence.toFixed(2)})${from}`;
27652
+ if (result.status === "uncertain") return `${name}: uncertain (guess ${shown(result.guess)}${result.confidence !== void 0 ? `, ${result.confidence.toFixed(2)}` : ""}${result.notFound ? "; not found on the page" : ""})${from}`;
27653
+ return `${name}: not on the page`;
27654
+ });
27655
+ if (extraction.cut) lines.push(`(Only the first part of the page was read; it is longer than the model accepts.)`);
27656
+ return `${lines.join("\n")}
27657
+ `;
27658
+ }
27659
+
26945
27660
  // web-tool-core.ts
26946
27661
  init_utils();
26947
27662
 
26948
27663
  // storage.ts
26949
- import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync as readFileSync45, readdirSync as readdirSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
27664
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync as readFileSync46, readdirSync as readdirSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
26950
27665
  init_utils();
26951
27666
  import { join as join4 } from "node:path";
26952
27667
  var CACHE_TTL_MS = 60 * 60 * 1e3;
@@ -27107,7 +27822,7 @@ function readCachedFetchData(data) {
27107
27822
  const opened = openRegularFile(path);
27108
27823
  fd = opened.fd;
27109
27824
  enforceMode(fd, 384);
27110
- const parsed = JSON.parse(readFileSync45(fd, "utf8"));
27825
+ const parsed = JSON.parse(readFileSync46(fd, "utf8"));
27111
27826
  if (!isValidStoredData(parsed) || parsed.type !== "fetch" || parsed.id !== data.id || !isInlineFetchData(parsed)) {
27112
27827
  return unavailableFetchData(data, "Cached fetched content is invalid");
27113
27828
  }
@@ -27203,27 +27918,36 @@ function hashContent(text6) {
27203
27918
  return `sha256:${createHash("sha256").update(text6, "utf8").digest("hex")}`;
27204
27919
  }
27205
27920
  function tokenize(value) {
27206
- return [...new Set(value.toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length > 3))];
27921
+ return [...new Set(value.split(/[^A-Za-z0-9]+/).filter((term) => term.length > 3 || term.length > 1 && /^[A-Z0-9]+$/.test(term)).map((term) => term.length > 3 ? term.toLowerCase() : term))];
27207
27922
  }
27208
- function extractRelevantSpans(content, hint) {
27923
+ function countMatches(terms, text6) {
27924
+ const lower = text6.toLowerCase();
27925
+ const words = new Set(text6.split(/[^A-Za-z0-9]+/));
27926
+ return terms.filter((term) => term.length > 3 ? lower.includes(term) : words.has(term)).length;
27927
+ }
27928
+ function extractRelevantSpans(content, claim, snippet) {
27209
27929
  const sentences = [];
27210
- const sentencePattern = /[^.!?]+(?:[.!?]+(?=\s|$)|$)/g;
27211
- for (const match of content.matchAll(sentencePattern)) {
27212
- const raw = match[0];
27930
+ const boundary = /(?<![.!?])[.!?]+(?:["'”’)\]*_]|\[\d+\])*(?=\s|$)/g;
27931
+ let segmentStart = 0;
27932
+ const addSentence = (end) => {
27933
+ const raw = content.slice(segmentStart, end);
27213
27934
  const text6 = raw.trim();
27214
27935
  if (text6.length > 0 && text6.length <= 400) {
27215
- const start = (match.index ?? 0) + raw.indexOf(text6);
27936
+ const start = segmentStart + raw.indexOf(text6);
27216
27937
  sentences.push({ text: text6, start, end: start + text6.length });
27217
27938
  }
27218
- }
27219
- const terms = tokenize(hint);
27220
- if (terms.length === 0) return [];
27221
- return sentences.map((sentence, index) => ({ sentence, index, score: terms.filter((term) => sentence.text.toLowerCase().includes(term)).length })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score || a.index - b.index).slice(0, 3).map(({ sentence }) => sentence);
27939
+ segmentStart = end;
27940
+ };
27941
+ for (const match of content.matchAll(boundary)) addSentence(match.index + match[0].length);
27942
+ addSentence(content.length);
27943
+ const claimTerms = tokenize(claim);
27944
+ const snippetTerms = tokenize(snippet);
27945
+ return sentences.map((sentence, index) => ({ sentence, index, claim: countMatches(claimTerms, sentence.text), snippet: countMatches(snippetTerms, sentence.text) })).filter((item) => item.claim + item.snippet > 0).sort((a, b) => b.claim - a.claim || b.snippet - a.snippet || a.index - b.index).slice(0, 3).map(({ sentence }) => sentence);
27222
27946
  }
27223
27947
  function passageId(sourceRank, index) {
27224
27948
  return `p-${sourceRank}-${index}`;
27225
27949
  }
27226
- function buildPassages(sources, fetched = [], hint = "") {
27950
+ function buildPassages(sources, fetched = [], claim = "") {
27227
27951
  const passages = [];
27228
27952
  const fetchedByUrl = new Map(fetched.map((item) => [item.url, item]));
27229
27953
  for (const source of sources) {
@@ -27238,8 +27962,7 @@ function buildPassages(sources, fetched = [], hint = "") {
27238
27962
  }
27239
27963
  const page = fetchedByUrl.get(source.url);
27240
27964
  if (page && !page.error && page.content) {
27241
- const passageHint = source.snippet?.trim() || hint;
27242
- for (const [index, span] of extractRelevantSpans(page.content, passageHint).entries()) {
27965
+ for (const [index, span] of extractRelevantSpans(page.content, claim, source.snippet ?? "").entries()) {
27243
27966
  passages.push({
27244
27967
  passage_id: passageId(source.rank, index + 1),
27245
27968
  source_url: source.url,
@@ -27336,9 +28059,9 @@ function parseConfigRoot(raw) {
27336
28059
  }
27337
28060
  return parsed;
27338
28061
  }
27339
- function loadConfig42() {
27340
- if (!existsSync56(WEB_SEARCH_CONFIG_PATH4)) return {};
27341
- return parseConfigRoot(readFileSync57(WEB_SEARCH_CONFIG_PATH4, "utf-8"));
28062
+ function loadConfig43() {
28063
+ if (!existsSync57(WEB_SEARCH_CONFIG_PATH4)) return {};
28064
+ return parseConfigRoot(readFileSync58(WEB_SEARCH_CONFIG_PATH4, "utf-8"));
27342
28065
  }
27343
28066
  var DEFAULT_TOOL_NAMES = {
27344
28067
  webSearch: "web_search",
@@ -27347,11 +28070,12 @@ var DEFAULT_TOOL_NAMES = {
27347
28070
  getSearchContent: "get_search_content"
27348
28071
  };
27349
28072
  var SEARCH_QUERY_CONCURRENCY = 3;
27350
- var FETCH_MODES = ["readable", "raw", "answer"];
28073
+ var FETCH_MODES = ["readable", "raw", "answer", "extract"];
28074
+ var DEFAULT_FETCH_MODES = ["readable", "raw", "answer"];
27351
28075
  function resolveFetchModeConfig(config) {
27352
- const configuredModes = config.fetch?.allowedModes ?? FETCH_MODES;
28076
+ const configuredModes = config.fetch?.allowedModes ?? DEFAULT_FETCH_MODES;
27353
28077
  if (!Array.isArray(configuredModes) || configuredModes.length === 0 || configuredModes.some((mode) => !FETCH_MODES.includes(mode))) {
27354
- throw new Error(`fetch.allowedModes in ${WEB_SEARCH_CONFIG_PATH4} must be a non-empty array containing only "readable", "raw", or "answer"`);
28078
+ throw new Error(`fetch.allowedModes in ${WEB_SEARCH_CONFIG_PATH4} must be a non-empty array containing only "readable", "raw", "answer", or "extract"`);
27355
28079
  }
27356
28080
  const allowedModes = configuredModes;
27357
28081
  const duplicateMode = allowedModes.find((mode, index) => allowedModes.indexOf(mode) !== index);
@@ -27359,6 +28083,9 @@ function resolveFetchModeConfig(config) {
27359
28083
  throw new Error(`fetch.allowedModes in ${WEB_SEARCH_CONFIG_PATH4} must not contain duplicates: "${duplicateMode}"`);
27360
28084
  }
27361
28085
  const defaultMode = config.fetch?.defaultMode ?? "readable";
28086
+ if (defaultMode === "extract") {
28087
+ throw new Error(`fetch.defaultMode in ${WEB_SEARCH_CONFIG_PATH4} cannot be "extract", because extract needs fields on each call`);
28088
+ }
27362
28089
  if (!allowedModes.includes(defaultMode)) {
27363
28090
  throw new Error(`fetch.defaultMode in ${WEB_SEARCH_CONFIG_PATH4} must be one of fetch.allowedModes`);
27364
28091
  }
@@ -27384,12 +28111,12 @@ function normalizeProviderInput(value, label = "provider") {
27384
28111
  return normalizeSearchProviderSelection(value, label);
27385
28112
  }
27386
28113
  function resolveRequestedProvider(requested) {
27387
- const normalizedRequested = normalizeProviderInput(requested);
28114
+ const normalizedRequested = parseProviderArgument(requested);
27388
28115
  if (normalizedRequested && normalizedRequested !== "auto") {
27389
28116
  assertSearchProviderSelectionAllowed(normalizedRequested, "Requested provider");
27390
28117
  return normalizedRequested;
27391
28118
  }
27392
- const config = loadConfig42();
28119
+ const config = loadConfig43();
27393
28120
  const provider = normalizeProviderInput(config.searchProvider ?? config.provider, `provider in ${WEB_SEARCH_CONFIG_PATH4}`) ?? "auto";
27394
28121
  assertSearchProviderSelectionAllowed(provider, `configured provider in ${WEB_SEARCH_CONFIG_PATH4}`);
27395
28122
  return provider;
@@ -27452,7 +28179,7 @@ function isAbortError6(err) {
27452
28179
  var DEFAULT_MAX_INLINE_CONTENT_CHARS = 3e4;
27453
28180
  var MIN_INLINE_CONTENT_CHARS = 1e3;
27454
28181
  var MAX_INLINE_CONTENT_CHARS = 2e5;
27455
- function getMaxInlineContentChars(config = loadConfig42()) {
28182
+ function getMaxInlineContentChars(config = loadConfig43()) {
27456
28183
  const value = config.maxInlineContentChars;
27457
28184
  if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value < MIN_INLINE_CONTENT_CHARS) {
27458
28185
  return DEFAULT_MAX_INLINE_CONTENT_CHARS;
@@ -27553,14 +28280,26 @@ function formatSourceCheckResult(artifact, getSearchContentTool = DEFAULT_TOOL_N
27553
28280
  if (assessment) {
27554
28281
  lines.push(`**Status:** ${assessment.status} (confidence ${assessment.confidence.toFixed(2)})`);
27555
28282
  lines.push(`**Rationale:** ${assessment.rationale}`);
27556
- if (assessment.supporting_passages.length > 0) lines.push(`**Supporting passages:** ${assessment.supporting_passages.join(", ")}`);
27557
- if (assessment.contradicting_passages.length > 0) lines.push(`**Contradicting passages:** ${assessment.contradicting_passages.join(", ")}`);
27558
28283
  lines.push("");
27559
28284
  }
27560
28285
  if (artifact.sources.length > 0) {
27561
28286
  lines.push("## Sources");
27562
- for (const source of artifact.sources) lines.push(`${source.rank}. [${source.quality}] ${source.title}
28287
+ let budget = 4e3;
28288
+ let omitted = 0;
28289
+ for (const source of artifact.sources) {
28290
+ lines.push(`${source.rank}. [${source.quality}] ${source.title}
27563
28291
  ${source.url}`);
28292
+ for (const passage of artifact.passages.filter((candidate) => candidate.source_rank === source.rank)) {
28293
+ const flat = passage.text.replace(/\s+/g, " ").trim();
28294
+ const text6 = flat.length > 400 ? `${flat.slice(0, 400).replace(/[\uD800-\uDBFF]$/, "")}\u2026` : flat;
28295
+ if (text6.length > budget) omitted++;
28296
+ else {
28297
+ budget -= text6.length;
28298
+ lines.push(` - ${passage.passage_id}: ${text6}`);
28299
+ }
28300
+ }
28301
+ }
28302
+ if (omitted > 0) lines.push(`${omitted} more passage${omitted === 1 ? "" : "s"} in the artifact.`);
27564
28303
  lines.push("");
27565
28304
  }
27566
28305
  if (artifact.errors?.length) lines.push(`Search errors: ${artifact.errors.map((entry) => `${entry.query}: ${entry.error}`).join("; ")}`);
@@ -27817,6 +28556,7 @@ Full search results are stored as responseId "${searchId}". `;
27817
28556
  };
27818
28557
  }
27819
28558
  async function webSearch(params, signal, call = {}) {
28559
+ const model = validateSearchModelOverride(params.provider, params.model);
27820
28560
  const { extensionContext: ctx, onUpdate } = call;
27821
28561
  return runWithProxy(typeof params.proxy === "string" ? params.proxy : void 0, async () => {
27822
28562
  const rawQueryList = Array.isArray(params.queries) ? params.queries : params.query !== void 0 ? expandQueryString(params.query) : [];
@@ -27832,7 +28572,7 @@ Full search results are stored as responseId "${searchId}". `;
27832
28572
  const allUrls = [];
27833
28573
  const allInlineContent = [];
27834
28574
  const resolvedProvider = resolveRequestedProvider(params.provider);
27835
- const providerFromConfig = (normalizeProviderInput(params.provider) ?? "auto") === "auto";
28575
+ const providerFromConfig = (parseProviderArgument(params.provider) ?? "auto") === "auto";
27836
28576
  const queryResponses = await runSearchQueries(queryList, async (query) => {
27837
28577
  signal?.throwIfAborted();
27838
28578
  onUpdate?.({
@@ -27842,6 +28582,7 @@ Full search results are stored as responseId "${searchId}". `;
27842
28582
  try {
27843
28583
  const { answer, results, inlineContent: inlineContent2, provider, providerResponses } = await search(query, {
27844
28584
  provider: resolvedProvider,
28585
+ model,
27845
28586
  providerFromConfig,
27846
28587
  numResults: params.numResults,
27847
28588
  recencyFilter,
@@ -27927,7 +28668,7 @@ Full search results are stored as responseId "${searchId}". `;
27927
28668
  try {
27928
28669
  const response = await search(query, {
27929
28670
  provider: resolveRequestedProvider(params.provider),
27930
- providerFromConfig: (normalizeProviderInput(params.provider) ?? "auto") === "auto",
28671
+ providerFromConfig: (parseProviderArgument(params.provider) ?? "auto") === "auto",
27931
28672
  numResults,
27932
28673
  recencyFilter,
27933
28674
  domainFilter,
@@ -28007,8 +28748,21 @@ Full search results are stored as responseId "${searchId}". `;
28007
28748
  if (mode === "answer" && options.model) {
28008
28749
  return { content: [{ type: "text", text: "Error: use answerModel, not model, with mode answer." }], details: { error: "model is incompatible with mode answer" } };
28009
28750
  }
28010
- if (mode === "answer" && options.auth !== void 0) {
28011
- return { content: [{ type: "text", text: "Error: auth cannot be combined with mode answer." }], details: { error: "auth cannot be combined with mode answer" } };
28751
+ if ((mode === "answer" || mode === "extract") && options.auth !== void 0) {
28752
+ return { content: [{ type: "text", text: `Error: auth cannot be combined with mode ${mode}.` }], details: { error: `auth cannot be combined with mode ${mode}` } };
28753
+ }
28754
+ if (mode !== "extract" && params.fields !== void 0) {
28755
+ return { content: [{ type: "text", text: "Error: fields requires mode extract." }], details: { error: "fields requires mode extract" } };
28756
+ }
28757
+ let extractFields;
28758
+ if (mode === "extract") {
28759
+ try {
28760
+ if (params.fields === void 0) throw new Error("mode extract requires fields");
28761
+ extractFields = parseExtractFields(params.fields);
28762
+ } catch (err) {
28763
+ const error = err instanceof Error ? err.message : String(err);
28764
+ return { content: [{ type: "text", text: `Error: ${error}.` }], details: { error } };
28765
+ }
28012
28766
  }
28013
28767
  let authFetchProfile;
28014
28768
  if (options.auth !== void 0) {
@@ -28036,11 +28790,9 @@ Full search results are stored as responseId "${searchId}". `;
28036
28790
  ...authFetchProfile ? { authFetchProfile } : {}
28037
28791
  };
28038
28792
  const fetchResults = await fetchAllContent2(urlList, signal, fetchOptions(requestOptions, options.proxy));
28039
- const presentedResults = mode === "answer" ? await Promise.all(fetchResults.map(async (result) => {
28793
+ const textResults = mode === "answer" || mode === "extract" ? fetchResults.map((result) => !result.error && (result.mimeType?.startsWith("image/") || result.frames?.length) ? { ...result, error: `${mode === "answer" ? "Page answer" : "Field extraction"} requires textual fetched content` } : result) : fetchResults;
28794
+ const presentedResults = mode === "answer" ? await Promise.all(textResults.map(async (result) => {
28040
28795
  if (result.error) return result;
28041
- if (result.mimeType?.startsWith("image/") || result.frames?.length) {
28042
- return { ...result, error: "Page answer requires textual fetched content" };
28043
- }
28044
28796
  try {
28045
28797
  if (!host.answerFromPage) throw new Error("this host cannot answer from fetched pages");
28046
28798
  const answer = await host.answerFromPage({
@@ -28053,7 +28805,9 @@ Full search results are stored as responseId "${searchId}". `;
28053
28805
  } catch (err) {
28054
28806
  return { ...result, error: `Page answer failed: ${err instanceof Error ? err.message : String(err)}` };
28055
28807
  }
28056
- })) : fetchResults;
28808
+ })) : textResults;
28809
+ const extractLimit = pLimit2(3);
28810
+ const extractions = extractFields ? await Promise.all(presentedResults.map((result) => result.error ? void 0 : extractLimit(() => extractPageFields(result.content, extractFields, { modelRegistry: ctx?.modelRegistry }, signal)))) : void 0;
28057
28811
  const successful = presentedResults.filter((r) => !r.error).length;
28058
28812
  const totalChars = presentedResults.reduce((sum, r) => sum + r.content.length, 0);
28059
28813
  const responseId = generateId();
@@ -28065,6 +28819,44 @@ Full search results are stored as responseId "${searchId}". `;
28065
28819
  };
28066
28820
  const storedContent = storeFetchResult(responseId, data, authFetchProfile);
28067
28821
  const structuredContent = fetchStructuredContent(storedContent ? responseId : null, presentedResults);
28822
+ if (extractions) {
28823
+ structuredContent.urls.forEach((entry, index) => {
28824
+ if (extractions[index]) entry.extraction = extractions[index];
28825
+ });
28826
+ let output2 = "## Extracted fields\n";
28827
+ presentedResults.forEach((result, index) => {
28828
+ output2 += `
28829
+ ### ${result.title || result.url}
28830
+ `;
28831
+ output2 += result.error ? `Error: ${result.error}
28832
+ ` : formatPageExtraction(extractions[index]);
28833
+ });
28834
+ const outputLimit = getMaxInlineContentChars();
28835
+ if (output2.length > outputLimit) output2 = `${output2.slice(0, outputLimit)}
28836
+
28837
+ [Results cut at ${outputLimit} characters; ask for fewer fields or URLs.]
28838
+ `;
28839
+ const anyUncertain = extractions.some((extraction) => extraction && "fields" in extraction && Object.values(extraction.fields).some((field) => field.status === "uncertain"));
28840
+ output2 += getSearchContentEnabled ? `
28841
+ ---
28842
+ The fetched pages are stored as responseId "${responseId}". Use ${toolNames.getSearchContent}({ responseId: "${responseId}", urlIndex: 0 }) to read the first one; urlIndex follows the order above.${anyUncertain ? " To check an uncertain value, add findText with its guess." : ""}` : "\n---\nContent retrieval is not registered.";
28843
+ return {
28844
+ // A page that fetched but could not be extracted still counts as fetched: its content is stored.
28845
+ ...successful === 0 ? { isError: true } : {},
28846
+ content: [{ type: "text", text: output2 }],
28847
+ structuredContent,
28848
+ details: {
28849
+ urls: urlList,
28850
+ urlCount: urlList.length,
28851
+ successful,
28852
+ mode,
28853
+ responseId,
28854
+ // The TUI summarizes a single URL from these, as for the other modes.
28855
+ ...urlList.length === 1 ? { title: presentedResults[0].title, totalChars: presentedResults[0].content.length, ...presentedResults[0].error ? { error: presentedResults[0].error } : {} } : {},
28856
+ extractions: presentedResults.map((result, index) => ({ url: result.url, ...result.error ? { error: result.error } : extractions[index] }))
28857
+ }
28858
+ };
28859
+ }
28068
28860
  if (urlList.length === 1) {
28069
28861
  const result = presentedResults[0];
28070
28862
  if (result.error) {
@@ -28147,13 +28939,13 @@ ${storedLabel} is stored as responseId "${responseId}". Use ${toolNames.getSearc
28147
28939
  Error: ${error}
28148
28940
  `;
28149
28941
  } else {
28150
- const shown = content.slice(0, budget);
28151
- budget -= shown.length;
28152
- const marker = shown.length === content.length ? "" : `
28153
- [answer ${shown.length ? "truncated at the output limit;" : "omitted; earlier answers used the output limit,"} fetch fewer URLs per call for complete answers]`;
28942
+ const shown2 = content.slice(0, budget);
28943
+ budget -= shown2.length;
28944
+ const marker = shown2.length === content.length ? "" : `
28945
+ [answer ${shown2.length ? "truncated at the output limit;" : "omitted; earlier answers used the output limit,"} fetch fewer URLs per call for complete answers]`;
28154
28946
  output += `
28155
28947
  ### ${title || url}
28156
- ${shown}${marker}
28948
+ ${shown2}${marker}
28157
28949
  `;
28158
28950
  }
28159
28951
  }
@@ -28500,7 +29292,7 @@ function standaloneFetchRejection(params, fetchModes) {
28500
29292
  return void 0;
28501
29293
  }
28502
29294
  function createStandaloneWebToolCore() {
28503
- const config = loadConfig42();
29295
+ const config = loadConfig43();
28504
29296
  const settings2 = {
28505
29297
  toolNames: { ...DEFAULT_TOOL_NAMES },
28506
29298
  enabledTools: {