@herbertgao/pi-extensions 2026.10.11 → 2026.10.13

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 (221) hide show
  1. package/README.md +8 -8
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/node_modules/@herbertgao/pi-agency/README.md +5 -3
  4. package/node_modules/@herbertgao/pi-agency/package.json +1 -1
  5. package/node_modules/@herbertgao/pi-agency/src/index.ts +51 -7
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +6 -8
  7. package/node_modules/@herbertgao/pi-cc-extensions/README.md +6 -8
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +11 -2
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +28 -6
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +33 -12
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +16 -3
  12. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  13. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  14. package/node_modules/@herbertgao/pi-subagents/package.json +1 -1
  15. package/node_modules/@herbertgao/pi-subagents/src/agent-color.ts +11 -2
  16. package/node_modules/@herbertgao/pi-subagents/src/index.ts +10 -5
  17. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +3 -2
  18. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  19. package/node_modules/@herbertgao/pi-subagents/src/ui/fleet-list.ts +1 -0
  20. package/node_modules/@herbertgao/sol-pi/README.md +1 -1
  21. package/node_modules/@herbertgao/sol-pi/agents-install.md +2 -2
  22. package/node_modules/@narumitw/pi-btw/README.md +14 -5
  23. package/node_modules/@narumitw/pi-btw/dist/index.ts +1067 -560
  24. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +4 -4
  25. package/node_modules/@narumitw/pi-btw/docs/core-alignment.md +277 -0
  26. package/node_modules/@narumitw/pi-btw/docs/native-appearance.md +857 -0
  27. package/node_modules/@narumitw/pi-btw/docs/workflows.md +34 -13
  28. package/node_modules/@narumitw/pi-btw/package.json +4 -4
  29. package/node_modules/@narumitw/pi-btw/src/btw.ts +152 -108
  30. package/node_modules/@narumitw/pi-btw/src/conversation-chrome.ts +93 -0
  31. package/node_modules/@narumitw/pi-btw/src/fullscreen-renderer.ts +329 -0
  32. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +109 -315
  33. package/node_modules/@narumitw/pi-btw/src/keybindings.ts +100 -22
  34. package/node_modules/@narumitw/pi-btw/src/menu.ts +42 -27
  35. package/node_modules/@narumitw/pi-btw/src/session-lifetime.ts +66 -0
  36. package/node_modules/@narumitw/pi-btw/src/transcript-pager.ts +366 -164
  37. package/node_modules/@narumitw/pi-btw/src/workspace-layout.ts +96 -36
  38. package/node_modules/pi-lens/CHANGELOG.md +281 -0
  39. package/node_modules/pi-lens/README.md +13 -1
  40. package/node_modules/pi-lens/dist/{chunk-SS36ZX4J.js → chunk-24AKHFGP.js} +6 -6
  41. package/node_modules/pi-lens/dist/{chunk-JSQFTSC6.js → chunk-2FN63LPV.js} +11 -11
  42. package/node_modules/pi-lens/dist/{chunk-5UCAH366.js → chunk-2KXTHF3M.js} +20 -20
  43. package/node_modules/pi-lens/dist/{chunk-EU63SDCG.js → chunk-3DA2JDOL.js} +367 -281
  44. package/node_modules/pi-lens/dist/{chunk-RWWYJ623.js → chunk-3KAZU3VR.js} +1 -1
  45. package/node_modules/pi-lens/dist/chunk-3PTHXJXR.js +28 -0
  46. package/node_modules/pi-lens/dist/chunk-3QED2P4V.js +31 -0
  47. package/node_modules/pi-lens/dist/{chunk-N2H3ZPZY.js → chunk-3RKP3FMS.js} +1 -0
  48. package/node_modules/pi-lens/dist/{chunk-XVF2VVXP.js → chunk-5HSRT26B.js} +2 -2
  49. package/node_modules/pi-lens/dist/{chunk-MXGY6KPT.js → chunk-5IUSNGOC.js} +15 -15
  50. package/node_modules/pi-lens/dist/{chunk-EJIUXPBX.js → chunk-5OFV52AM.js} +1 -1
  51. package/node_modules/pi-lens/dist/{chunk-AW7R2GWG.js → chunk-5VSF4UUQ.js} +12 -7
  52. package/node_modules/pi-lens/dist/{chunk-6STA6Z7I.js → chunk-5WRPDP2A.js} +18 -18
  53. package/node_modules/pi-lens/dist/{chunk-YIUAVF7E.js → chunk-6DLWKFEX.js} +35 -34
  54. package/node_modules/pi-lens/dist/{chunk-WOA4LN2R.js → chunk-7D6L4MTX.js} +2 -2
  55. package/node_modules/pi-lens/dist/{chunk-GAEGEPOC.js → chunk-7HXE67BN.js} +2 -2
  56. package/node_modules/pi-lens/dist/chunk-AGSS7277.js +84 -0
  57. package/node_modules/pi-lens/dist/{chunk-R3PCY3YS.js → chunk-AMERCH6V.js} +13 -13
  58. package/node_modules/pi-lens/dist/{chunk-WU567RSC.js → chunk-ATKJFDQN.js} +14 -10
  59. package/node_modules/pi-lens/dist/{chunk-VSSBEUFT.js → chunk-AWSCPCN2.js} +16 -16
  60. package/node_modules/pi-lens/dist/{chunk-VCHXCQFG.js → chunk-BWD5EPKO.js} +3 -3
  61. package/node_modules/pi-lens/dist/{chunk-H6MF6EVN.js → chunk-CT4MN5IU.js} +1200 -230
  62. package/node_modules/pi-lens/dist/{chunk-FCSOVF55.js → chunk-CUHSHSB6.js} +6 -6
  63. package/node_modules/pi-lens/dist/{chunk-CHOW74WE.js → chunk-CYRKQRPM.js} +7 -10
  64. package/node_modules/pi-lens/dist/{chunk-Q7DUK4LX.js → chunk-DEL2U6CM.js} +5 -5
  65. package/node_modules/pi-lens/dist/{chunk-6C7JWPCP.js → chunk-DGUKIYSI.js} +26 -23
  66. package/node_modules/pi-lens/dist/{chunk-PHDMFAKM.js → chunk-DUO2TU77.js} +2 -2
  67. package/node_modules/pi-lens/dist/{chunk-MRXKYPCS.js → chunk-EBC36LNN.js} +2 -2
  68. package/node_modules/pi-lens/dist/{chunk-CSHFH5IN.js → chunk-ED36RF6Y.js} +1 -1
  69. package/node_modules/pi-lens/dist/{chunk-76MWC2K6.js → chunk-EUXZEFTV.js} +90 -97
  70. package/node_modules/pi-lens/dist/{chunk-QOZXJ4NA.js → chunk-FM4RDMKT.js} +11 -8
  71. package/node_modules/pi-lens/dist/{chunk-ACXEQZOU.js → chunk-GAQ7OQG6.js} +31 -28
  72. package/node_modules/pi-lens/dist/{chunk-XAGLWMJ4.js → chunk-GL5LUMZE.js} +23 -23
  73. package/node_modules/pi-lens/dist/{chunk-BKE7E7TC.js → chunk-GMX5OS7B.js} +9 -9
  74. package/node_modules/pi-lens/dist/{chunk-ZHFZWTZV.js → chunk-GSLNCYGG.js} +11 -11
  75. package/node_modules/pi-lens/dist/{chunk-3W7IEVVL.js → chunk-GSM5UU7A.js} +26 -34
  76. package/node_modules/pi-lens/dist/{chunk-724UL2TJ.js → chunk-GXFV6MYU.js} +3 -3
  77. package/node_modules/pi-lens/dist/chunk-HAD7QRQI.js +30 -0
  78. package/node_modules/pi-lens/dist/{chunk-QOBUHWHX.js → chunk-HRNHZA3N.js} +6 -6
  79. package/node_modules/pi-lens/dist/{chunk-VWCXW2E7.js → chunk-HWCCCQNX.js} +1 -1
  80. package/node_modules/pi-lens/dist/{chunk-7DYBLXYA.js → chunk-HYGZEMX6.js} +3 -3
  81. package/node_modules/pi-lens/dist/chunk-IJYGIDF4.js +186 -0
  82. package/node_modules/pi-lens/dist/{chunk-4W4VLAPJ.js → chunk-IQWN5JCP.js} +11 -11
  83. package/node_modules/pi-lens/dist/{chunk-SQ4TVJBR.js → chunk-IUE7SSKV.js} +7 -7
  84. package/node_modules/pi-lens/dist/{chunk-IBGIOBEE.js → chunk-IWDLU6K3.js} +68 -5
  85. package/node_modules/pi-lens/dist/{chunk-XCJN5IJU.js → chunk-IYNJ6YPZ.js} +4 -4
  86. package/node_modules/pi-lens/dist/{chunk-JAU72XNY.js → chunk-J64T55EI.js} +3 -3
  87. package/node_modules/pi-lens/dist/{chunk-2BBLFX75.js → chunk-J6MPGQTS.js} +5 -5
  88. package/node_modules/pi-lens/dist/chunk-JORED7EX.js +44 -0
  89. package/node_modules/pi-lens/dist/{chunk-6SDEP3AJ.js → chunk-JUKMK5Y4.js} +8 -8
  90. package/node_modules/pi-lens/dist/{chunk-FMSO6RDZ.js → chunk-JW3YWBVB.js} +15 -15
  91. package/node_modules/pi-lens/dist/{chunk-L3BLXZG7.js → chunk-KAPJINKN.js} +30 -69
  92. package/node_modules/pi-lens/dist/{chunk-2B73ZPOK.js → chunk-KN35K52N.js} +3 -3
  93. package/node_modules/pi-lens/dist/{chunk-C34ZXZ7O.js → chunk-KUA4OJ5Y.js} +24 -11
  94. package/node_modules/pi-lens/dist/chunk-KYUB6QDC.js +72 -0
  95. package/node_modules/pi-lens/dist/{chunk-67WMNWEE.js → chunk-LLJNQKQW.js} +12 -10
  96. package/node_modules/pi-lens/dist/chunk-LZSEQW6A.js +57 -0
  97. package/node_modules/pi-lens/dist/{chunk-ZANLILYD.js → chunk-M2IFVFWU.js} +2 -2
  98. package/node_modules/pi-lens/dist/chunk-M2UD3LPU.js +88 -0
  99. package/node_modules/pi-lens/dist/{chunk-XIJZVPD5.js → chunk-MBKQHGA7.js} +15 -15
  100. package/node_modules/pi-lens/dist/{chunk-P7266HLM.js → chunk-MPNJLASA.js} +2 -2
  101. package/node_modules/pi-lens/dist/{chunk-6GFRNVYR.js → chunk-MZGQNL3Y.js} +10 -10
  102. package/node_modules/pi-lens/dist/{chunk-ZWFS3OEF.js → chunk-N5FLEO7W.js} +33 -32
  103. package/node_modules/pi-lens/dist/{chunk-3JNKMP3B.js → chunk-O4NWQT6I.js} +4 -4
  104. package/node_modules/pi-lens/dist/{chunk-T6CPIZNT.js → chunk-OHKJ7PQF.js} +33 -32
  105. package/node_modules/pi-lens/dist/{chunk-VRZP76YM.js → chunk-P63GXC37.js} +4 -1
  106. package/node_modules/pi-lens/dist/{chunk-XTMJ7XDT.js → chunk-POMLXPMY.js} +1 -1
  107. package/node_modules/pi-lens/dist/{chunk-QQNQ7SJW.js → chunk-QBFBRV2B.js} +10 -4
  108. package/node_modules/pi-lens/dist/{chunk-CMMHNUZ2.js → chunk-R3T7CLQ2.js} +60 -38
  109. package/node_modules/pi-lens/dist/{chunk-23WOO7TX.js → chunk-R7YOCSNV.js} +10 -10
  110. package/node_modules/pi-lens/dist/{chunk-2CD5RS6M.js → chunk-RKBXZN3A.js} +23 -2
  111. package/node_modules/pi-lens/dist/{chunk-OCAGUNBC.js → chunk-RKKOYPRA.js} +12 -12
  112. package/node_modules/pi-lens/dist/{chunk-52FUZI6K.js → chunk-RMLC67LF.js} +1 -1
  113. package/node_modules/pi-lens/dist/{chunk-XMSXXAHW.js → chunk-ROYSX2S5.js} +2 -2
  114. package/node_modules/pi-lens/dist/{chunk-M6HSLBWY.js → chunk-RVK72CZX.js} +6507 -7514
  115. package/node_modules/pi-lens/dist/{chunk-FLKWCIZH.js → chunk-S2HEXIWI.js} +5 -5
  116. package/node_modules/pi-lens/dist/{chunk-UZ3TUTRV.js → chunk-S67KYG37.js} +1 -1
  117. package/node_modules/pi-lens/dist/{chunk-VCO24T4L.js → chunk-SD4I7ZO4.js} +14 -14
  118. package/node_modules/pi-lens/dist/{chunk-Z527N6YQ.js → chunk-SKAMFC7A.js} +12 -12
  119. package/node_modules/pi-lens/dist/{chunk-MQLUAEOC.js → chunk-SRYEJNES.js} +2 -2
  120. package/node_modules/pi-lens/dist/{chunk-BRGDSBJE.js → chunk-SYE6T2EB.js} +12 -12
  121. package/node_modules/pi-lens/dist/{chunk-GXW6K4YJ.js → chunk-T57LYLZT.js} +1 -1
  122. package/node_modules/pi-lens/dist/{chunk-ZXYDQ3TZ.js → chunk-T7FEBKXN.js} +48 -15
  123. package/node_modules/pi-lens/dist/{chunk-3EFKIGZN.js → chunk-TIQ2PKDW.js} +3 -3
  124. package/node_modules/pi-lens/dist/{chunk-QILIYSJF.js → chunk-TLX72JTG.js} +1 -1
  125. package/node_modules/pi-lens/dist/{chunk-TYM6OUIT.js → chunk-TOY6QKOH.js} +12 -12
  126. package/node_modules/pi-lens/dist/{chunk-IZSHAIJ7.js → chunk-TRETHTQO.js} +12 -12
  127. package/node_modules/pi-lens/dist/{chunk-3VPVG5SU.js → chunk-U44DJXQP.js} +10 -6
  128. package/node_modules/pi-lens/dist/{chunk-PNQDPDRC.js → chunk-UA7ZXYDR.js} +1 -1
  129. package/node_modules/pi-lens/dist/{chunk-OXXKQCSV.js → chunk-UBOQLVT2.js} +4 -4
  130. package/node_modules/pi-lens/dist/{chunk-QGQ5CCCG.js → chunk-UMS2MFPZ.js} +2 -2
  131. package/node_modules/pi-lens/dist/{chunk-QHJ6DQ2R.js → chunk-US7ECLD7.js} +55 -13
  132. package/node_modules/pi-lens/dist/{chunk-AB3YYG6N.js → chunk-UZ2XCLYS.js} +8 -8
  133. package/node_modules/pi-lens/dist/chunk-V35JG4JB.js +2667 -0
  134. package/node_modules/pi-lens/dist/{chunk-N3X6Q4YT.js → chunk-VOOAPROD.js} +3 -3
  135. package/node_modules/pi-lens/dist/{chunk-SAEFPSB6.js → chunk-W66O5E25.js} +21 -11
  136. package/node_modules/pi-lens/dist/{chunk-KBG47GHP.js → chunk-WMYE35PX.js} +15 -11
  137. package/node_modules/pi-lens/dist/{chunk-5NGR67U5.js → chunk-XBJVAEEO.js} +32 -5
  138. package/node_modules/pi-lens/dist/{chunk-YYOIQFRS.js → chunk-XHJBS436.js} +122 -44
  139. package/node_modules/pi-lens/dist/{chunk-GBPP5P7X.js → chunk-XTBDCR27.js} +4 -4
  140. package/node_modules/pi-lens/dist/{chunk-4UNXBNE2.js → chunk-XTFDJI3T.js} +11 -11
  141. package/node_modules/pi-lens/dist/{chunk-UXGETRP4.js → chunk-XYURS6EN.js} +13 -12
  142. package/node_modules/pi-lens/dist/{chunk-RPLINGVB.js → chunk-Y6GZHWSJ.js} +6 -6
  143. package/node_modules/pi-lens/dist/{chunk-2VUQMUMT.js → chunk-YCWYO6TQ.js} +41 -38
  144. package/node_modules/pi-lens/dist/{chunk-77M37OKR.js → chunk-YH5MVY2U.js} +7 -7
  145. package/node_modules/pi-lens/dist/{chunk-AOHZU2BM.js → chunk-YNE3RP52.js} +1 -1
  146. package/node_modules/pi-lens/dist/{chunk-YSZNHOBY.js → chunk-ZHH37KZL.js} +12 -12
  147. package/node_modules/pi-lens/dist/{chunk-ZGDGW2V3.js → chunk-ZIVJBOO3.js} +2 -2
  148. package/node_modules/pi-lens/dist/{chunk-RXCOMYPY.js → chunk-ZVUL7QYY.js} +29 -28
  149. package/node_modules/pi-lens/dist/index.js +11052 -5852
  150. package/node_modules/pi-lens/dist/mcp/analyze-cli.js +10 -9
  151. package/node_modules/pi-lens/dist/mcp/cli.js +41 -38
  152. package/node_modules/pi-lens/dist/mcp/server.js +1120 -474
  153. package/node_modules/pi-lens/dist/mcp/worker.js +61 -58
  154. package/node_modules/pi-lens/dist/probes/installer.js +19 -19
  155. package/node_modules/pi-lens/dist/workers/project-snapshot-persist-worker.js +28 -9
  156. package/node_modules/pi-lens/dist/workers/review-graph-persist-worker.js +1 -1
  157. package/node_modules/pi-lens/docs/configuration.md +11 -0
  158. package/node_modules/pi-lens/docs/engineering-principles.md +32 -0
  159. package/node_modules/pi-lens/docs/lsp-capability-matrix.md +1 -1
  160. package/node_modules/pi-lens/docs/lsp-idle-eviction.md +15 -26
  161. package/node_modules/pi-lens/docs/pi-lens-fixer.md +117 -13
  162. package/node_modules/pi-lens/docs/pi-lens-merge-policy.md +97 -7
  163. package/node_modules/pi-lens/docs/pi-lens-monitor.md +8 -2
  164. package/node_modules/pi-lens/docs/pi-lens-retro.md +4 -1
  165. package/node_modules/pi-lens/docs/pi-lens-reviewer.md +112 -4
  166. package/node_modules/pi-lens/docs/pi-lens-subagent.md +22 -14
  167. package/node_modules/pi-lens/docs/release-qa-baseline.md +3 -1
  168. package/node_modules/pi-lens/docs/servercapabilities.md +9 -19
  169. package/node_modules/pi-lens/package.json +7 -5
  170. package/node_modules/pi-lens/scripts/download-grammars.js +40 -7
  171. package/node_modules/pi-lens/scripts/lib/latency-log-phases.mjs +95 -0
  172. package/node_modules/pi-lens/scripts/rpc-load-check.mjs +570 -81
  173. package/node_modules/pi-provider-qoder/dist/index.js +545 -221
  174. package/node_modules/pi-provider-qoder/package.json +1 -1
  175. package/node_modules/pi-web-access/CHANGELOG.md +39 -0
  176. package/node_modules/pi-web-access/README.md +83 -12
  177. package/node_modules/pi-web-access/anysearch.ts +4 -3
  178. package/node_modules/pi-web-access/bocha.ts +4 -3
  179. package/node_modules/pi-web-access/brightdata-unlocker.ts +3 -2
  180. package/node_modules/pi-web-access/brightdata.ts +4 -3
  181. package/node_modules/pi-web-access/ceramic.ts +3 -2
  182. package/node_modules/pi-web-access/curator-page.ts +3 -1
  183. package/node_modules/pi-web-access/curator-server.ts +1 -0
  184. package/node_modules/pi-web-access/deepseek.ts +179 -6
  185. package/node_modules/pi-web-access/dist/index.js +1118 -688
  186. package/node_modules/pi-web-access/dist/mcp-cli.js +1081 -667
  187. package/node_modules/pi-web-access/extract.ts +58 -6
  188. package/node_modules/pi-web-access/gemini-search.ts +29 -6
  189. package/node_modules/pi-web-access/index.ts +20 -3
  190. package/node_modules/pi-web-access/jina-search.ts +6 -4
  191. package/node_modules/pi-web-access/kagi.ts +5 -4
  192. package/node_modules/pi-web-access/keenable.ts +3 -2
  193. package/node_modules/pi-web-access/linkup.ts +170 -0
  194. package/node_modules/pi-web-access/mistral-search.ts +4 -3
  195. package/node_modules/pi-web-access/ollama.ts +5 -4
  196. package/node_modules/pi-web-access/package.json +1 -1
  197. package/node_modules/pi-web-access/parallel.ts +7 -7
  198. package/node_modules/pi-web-access/perplexity.ts +5 -3
  199. package/node_modules/pi-web-access/querit.ts +4 -3
  200. package/node_modules/pi-web-access/search1api.ts +4 -3
  201. package/node_modules/pi-web-access/searchinfinity.ts +4 -3
  202. package/node_modules/pi-web-access/serpapi.ts +7 -5
  203. package/node_modules/pi-web-access/serpbase.ts +5 -4
  204. package/node_modules/pi-web-access/serpdive.ts +4 -3
  205. package/node_modules/pi-web-access/serper.ts +6 -4
  206. package/node_modules/pi-web-access/serply.ts +3 -2
  207. package/node_modules/pi-web-access/utils.ts +24 -1
  208. package/node_modules/pi-web-access/valyu.ts +4 -3
  209. package/node_modules/pi-web-access/web-tool-core.ts +5 -0
  210. package/node_modules/pi-web-access/xai-search.ts +49 -7
  211. package/node_modules/pi-web-access/xcrawl.ts +4 -3
  212. package/node_modules/pi-web-access/you.ts +3 -2
  213. package/package.json +10 -10
  214. package/node_modules/pi-lens/dist/chunk-3YN6V5TV.js +0 -85
  215. package/node_modules/pi-lens/dist/chunk-466Z26MG.js +0 -30
  216. package/node_modules/pi-lens/dist/chunk-EC47DWFA.js +0 -56
  217. package/node_modules/pi-lens/dist/chunk-KDERNTCQ.js +0 -28
  218. package/node_modules/pi-lens/dist/chunk-KSX3TXSZ.js +0 -69
  219. package/node_modules/pi-lens/dist/chunk-LOP6GRPH.js +0 -31
  220. package/node_modules/pi-lens/dist/chunk-UOPVJQ4N.js +0 -103
  221. /package/node_modules/pi-lens/dist/{chunk-FC4RP4I2.js → chunk-6HWVI6MI.js} +0 -0
@@ -74,8 +74,22 @@ function resolveApiBaseUrl(options) {
74
74
  url.pathname = url.pathname.replace(/\/+$/, "");
75
75
  return url.toString().replace(/\/+$/, "");
76
76
  }
77
- async function fetchWithCredentialRedirects(url, init, credentialHeaders) {
77
+ function resolveProviderApiUrl(configStem, defaultUrl, configuredValue) {
78
+ const official = new URL(defaultUrl);
79
+ const environmentKey = (PI_PREFIXED_ENVIRONMENT_STEMS.has(configStem) ? "PI_" : "") + configStem.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase() + "_BASE_URL";
80
+ const baseUrl = resolveApiBaseUrl({
81
+ configKey: configStem + "BaseUrl",
82
+ configuredValue,
83
+ defaultValue: official.origin,
84
+ environmentKey,
85
+ environmentValue: process.env[environmentKey]
86
+ });
87
+ return baseUrl + official.pathname + official.search;
88
+ }
89
+ async function fetchWithCredentialRedirects(url, init, credentialHeaders, credentialQueryParams = []) {
78
90
  let current = new URL(url);
91
+ const source = new URL(url);
92
+ for (const name of credentialQueryParams) source.searchParams.delete(name);
79
93
  let requestInit = init;
80
94
  for (let redirects = 0; ; redirects++) {
81
95
  const response = await fetch(current, { ...requestInit, redirect: "manual" });
@@ -83,7 +97,7 @@ async function fetchWithCredentialRedirects(url, init, credentialHeaders) {
83
97
  const location = response.headers.get("location");
84
98
  if (!location) return response;
85
99
  if (redirects === MAX_API_REDIRECTS) {
86
- throw new Error(`Too many API redirects from ${url}`);
100
+ throw new Error(`Too many API redirects from ${source}`);
87
101
  }
88
102
  const next = new URL(location, current);
89
103
  if (next.protocol !== "http:" && next.protocol !== "https:") {
@@ -97,6 +111,7 @@ async function fetchWithCredentialRedirects(url, init, credentialHeaders) {
97
111
  requestInit = { ...withoutBody, method: "GET", headers };
98
112
  }
99
113
  if (next.origin !== current.origin) {
114
+ for (const name of credentialQueryParams) next.searchParams.delete(name);
100
115
  const headers = new Headers(requestInit.headers);
101
116
  for (const name of credentialHeaders) headers.delete(name);
102
117
  requestInit = { ...requestInit, headers };
@@ -156,8 +171,8 @@ function isTimeoutError(err) {
156
171
  const message = err.message ?? "";
157
172
  return name === "AbortError" || code === "ETIMEDOUT" || message.toLowerCase().includes("timed out");
158
173
  }
159
- function trimErrorText(text5) {
160
- return text5.replace(/\s+/g, " ").trim().slice(0, 200);
174
+ function trimErrorText(text6) {
175
+ return text6.replace(/\s+/g, " ").trim().slice(0, 200);
161
176
  }
162
177
  function mapFfmpegError(err) {
163
178
  const { code, stderr, message } = readExecError(err);
@@ -457,9 +472,10 @@ async function fetchViaCurlOnce(url, init, proxyUrl) {
457
472
  Object.defineProperty(response, "redirected", { value: redirected, configurable: true });
458
473
  return response;
459
474
  }
460
- var cachedWebSearchConfigDir, API_REDIRECT_STATUSES, API_REQUEST_BODY_HEADERS, MAX_API_REDIRECTS, LOCAL_CURATOR_NETWORK_DEFAULTS, proxyStorage, CurlTransportError;
475
+ var cachedWebSearchConfigDir, PI_PREFIXED_ENVIRONMENT_STEMS, API_REDIRECT_STATUSES, API_REQUEST_BODY_HEADERS, MAX_API_REDIRECTS, LOCAL_CURATOR_NETWORK_DEFAULTS, proxyStorage, CurlTransportError;
461
476
  var init_utils = __esm({
462
477
  "utils.ts"() {
478
+ PI_PREFIXED_ENVIRONMENT_STEMS = /* @__PURE__ */ new Set(["ollama", "deepseek"]);
463
479
  API_REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
464
480
  API_REQUEST_BODY_HEADERS = ["Content-Encoding", "Content-Language", "Content-Location", "Content-Type"];
465
481
  MAX_API_REDIRECTS = 5;
@@ -889,10 +905,10 @@ function writeCloneRuntimeOwner(runtimePath) {
889
905
  mode: 384
890
906
  });
891
907
  }
892
- function parseCloneRuntimeOwner(text5) {
908
+ function parseCloneRuntimeOwner(text6) {
893
909
  let parsed;
894
910
  try {
895
- parsed = JSON.parse(text5);
911
+ parsed = JSON.parse(text6);
896
912
  } catch {
897
913
  return null;
898
914
  }
@@ -1652,8 +1668,8 @@ var init_github_extract = __esm({
1652
1668
  import { exec, execFile as execFile3 } from "node:child_process";
1653
1669
  import { existsSync as existsSync4 } from "node:fs";
1654
1670
  import { promisify } from "node:util";
1655
- function redactCredential(text5, credential) {
1656
- return credential ? text5.split(credential).join("[redacted]") : text5;
1671
+ function redactCredential(text6, credential) {
1672
+ return credential ? text6.split(credential).join("[redacted]") : text6;
1657
1673
  }
1658
1674
  function normalize(value) {
1659
1675
  if (typeof value !== "string") return null;
@@ -1930,10 +1946,10 @@ function parseAdcFile(raw) {
1930
1946
  }
1931
1947
  return { type };
1932
1948
  }
1933
- function parseTokenExchangeResponse(text5, context) {
1949
+ function parseTokenExchangeResponse(text6, context) {
1934
1950
  let raw;
1935
1951
  try {
1936
- raw = JSON.parse(text5);
1952
+ raw = JSON.parse(text6);
1937
1953
  } catch (err) {
1938
1954
  const message = err instanceof Error ? err.message : String(err);
1939
1955
  throw new Error(`${context} returned invalid JSON: ${message}`);
@@ -1980,11 +1996,11 @@ async function exchangeRefreshToken(cfg, signal) {
1980
1996
  body,
1981
1997
  signal
1982
1998
  });
1983
- const text5 = await res.text();
1999
+ const text6 = await res.text();
1984
2000
  if (!res.ok) {
1985
- throwOnTokenExchangeFailure(res, text5, res.status);
2001
+ throwOnTokenExchangeFailure(res, text6, res.status);
1986
2002
  }
1987
- return parseTokenExchangeResponse(text5, "Gemini ADC token exchange");
2003
+ return parseTokenExchangeResponse(text6, "Gemini ADC token exchange");
1988
2004
  }
1989
2005
  async function exchangeServiceAccountJwt(cfg, signal) {
1990
2006
  if (!cfg.client_email || !cfg.private_key) {
@@ -2016,11 +2032,11 @@ async function exchangeServiceAccountJwt(cfg, signal) {
2016
2032
  body,
2017
2033
  signal
2018
2034
  });
2019
- const text5 = await res.text();
2035
+ const text6 = await res.text();
2020
2036
  if (!res.ok) {
2021
- throwOnTokenExchangeFailure(res, text5, res.status);
2037
+ throwOnTokenExchangeFailure(res, text6, res.status);
2022
2038
  }
2023
- return parseTokenExchangeResponse(text5, "Gemini ADC service account token exchange");
2039
+ return parseTokenExchangeResponse(text6, "Gemini ADC service account token exchange");
2024
2040
  }
2025
2041
  async function fetchMetadataToken(signal) {
2026
2042
  const url = `http://${getMetadataHost()}/computeMetadata/v1/instance/service-accounts/default/token`;
@@ -2035,14 +2051,14 @@ async function fetchMetadataToken(signal) {
2035
2051
  const message = err instanceof Error ? err.message : String(err);
2036
2052
  throw new Error(`Gemini ADC metadata server token request failed: ${message}`);
2037
2053
  }
2038
- const text5 = await res.text();
2054
+ const text6 = await res.text();
2039
2055
  if (!res.ok) {
2040
2056
  if (res.status === 401 || res.status === 403) {
2041
2057
  throw new CredentialResolutionError("Gemini ADC", "oauth-credential-rejected");
2042
2058
  }
2043
- throw new Error(`Gemini ADC metadata server token request failed (HTTP ${res.status}): ${text5.slice(0, 300)}`);
2059
+ throw new Error(`Gemini ADC metadata server token request failed (HTTP ${res.status}): ${text6.slice(0, 300)}`);
2044
2060
  }
2045
- return parseTokenExchangeResponse(text5, "Gemini ADC metadata server token");
2061
+ return parseTokenExchangeResponse(text6, "Gemini ADC metadata server token");
2046
2062
  }
2047
2063
  async function getAdcAccessToken(signal) {
2048
2064
  if (cachedToken && cachedToken.expiresAt > Date.now()) {
@@ -2189,14 +2205,14 @@ function buildAuthHeaders(apiKey = null, cloudflareApiKey = getLegacyCloudflareA
2189
2205
  if (!isCloudflareGateway()) return apiKey ? { "x-goog-api-key": apiKey } : {};
2190
2206
  return cloudflareApiKey ? { "cf-aig-authorization": `Bearer ${cloudflareApiKey}` } : {};
2191
2207
  }
2192
- function redactGeminiCredentials(text5, apiKey, cloudflareApiKey, adcToken) {
2193
- let out = redactCredential(redactCredential(text5, apiKey), cloudflareApiKey);
2208
+ function redactGeminiCredentials(text6, apiKey, cloudflareApiKey, adcToken) {
2209
+ let out = redactCredential(redactCredential(text6, apiKey), cloudflareApiKey);
2194
2210
  if (adcToken) out = redactCredential(out, adcToken);
2195
2211
  return out;
2196
2212
  }
2197
- function redactGeminiApiResponse(response, text5, apiKey, adcToken) {
2213
+ function redactGeminiApiResponse(response, text6, apiKey, adcToken) {
2198
2214
  const credentials = responseCredentials.get(response);
2199
- return redactGeminiCredentials(text5, credentials?.apiKey ?? apiKey, credentials?.cloudflareApiKey, credentials?.adcToken ?? adcToken);
2215
+ return redactGeminiCredentials(text6, credentials?.apiKey ?? apiKey, credentials?.cloudflareApiKey, credentials?.adcToken ?? adcToken);
2200
2216
  }
2201
2217
  async function fetchGeminiApi(url, init = {}, apiKey) {
2202
2218
  const parsedUrl = new URL(url);
@@ -2296,9 +2312,9 @@ async function queryGeminiApiWithInlineData(prompt, data, mimeType, options = {}
2296
2312
  }
2297
2313
  const response = await res.json();
2298
2314
  const candidate = response.candidates?.[0];
2299
- const text5 = candidate?.content?.parts?.map((part) => part.text).filter((part) => typeof part === "string" && part.length > 0).join("\n") ?? "";
2315
+ const text6 = candidate?.content?.parts?.map((part) => part.text).filter((part) => typeof part === "string" && part.length > 0).join("\n") ?? "";
2300
2316
  return {
2301
- text: text5,
2317
+ text: text6,
2302
2318
  ...candidate?.finishReason ? { finishReason: candidate.finishReason } : {},
2303
2319
  ...response.promptFeedback?.blockReason ? { blockReason: response.promptFeedback.blockReason } : {}
2304
2320
  };
@@ -2339,9 +2355,9 @@ async function queryGeminiApiWithVideo(prompt, videoUri, options = {}) {
2339
2355
  throw new Error(`Gemini API error ${res.status}: ${errorText.slice(0, 300)}`);
2340
2356
  }
2341
2357
  const data = await res.json();
2342
- const text5 = data.candidates?.[0]?.content?.parts?.map((p) => p.text).filter(Boolean).join("\n");
2343
- if (!text5) throw new Error("Gemini API returned empty response");
2344
- return text5;
2358
+ const text6 = data.candidates?.[0]?.content?.parts?.map((p) => p.text).filter(Boolean).join("\n");
2359
+ if (!text6) throw new Error("Gemini API returned empty response");
2360
+ return text6;
2345
2361
  }
2346
2362
  var DEFAULT_API_HOST, API_VERSION, API_BASE, CONFIG_PATH3, DEFAULT_MODEL, cachedConfig3, responseCredentials;
2347
2363
  var init_gemini_api = __esm({
@@ -3253,8 +3269,8 @@ function extractEmailFromGeminiHtml(html) {
3253
3269
  }
3254
3270
  return findFirstEmail(html);
3255
3271
  }
3256
- function extractEmailFromListAccounts(text5) {
3257
- const trimmed = text5.replace(/^\)\]\}'\s*/, "");
3272
+ function extractEmailFromListAccounts(text6) {
3273
+ const trimmed = text6.replace(/^\)\]\}'\s*/, "");
3258
3274
  try {
3259
3275
  return findEmailInValue(JSON.parse(trimmed)) ?? findFirstEmail(trimmed);
3260
3276
  } catch {
@@ -3278,8 +3294,8 @@ function findEmailInValue(value) {
3278
3294
  }
3279
3295
  return null;
3280
3296
  }
3281
- function findFirstEmail(text5) {
3282
- const normalized = decodeEmailEscapes(text5);
3297
+ function findFirstEmail(text6) {
3298
+ const normalized = decodeEmailEscapes(text6);
3283
3299
  const match = normalized.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i);
3284
3300
  return match?.[0] ?? null;
3285
3301
  }
@@ -3321,8 +3337,8 @@ Content-Type: ${file.mimeType}\r
3321
3337
  signal
3322
3338
  });
3323
3339
  if (!res.ok) {
3324
- const text5 = await res.text();
3325
- throw new Error(`File upload failed: ${res.status} (${text5.slice(0, 200)})`);
3340
+ const text6 = await res.text();
3341
+ throw new Error(`File upload failed: ${res.status} (${text6.slice(0, 200)})`);
3326
3342
  }
3327
3343
  return { id: await res.text(), name: fileName };
3328
3344
  }
@@ -3347,13 +3363,13 @@ function getNestedValue(value, pathParts) {
3347
3363
  }
3348
3364
  return current;
3349
3365
  }
3350
- function trimJsonEnvelope(text5) {
3351
- const start = text5.indexOf("[");
3352
- const end = text5.lastIndexOf("]");
3366
+ function trimJsonEnvelope(text6) {
3367
+ const start = text6.indexOf("[");
3368
+ const end = text6.lastIndexOf("]");
3353
3369
  if (start === -1 || end === -1 || end <= start) {
3354
3370
  throw new Error("Gemini response did not contain a JSON payload.");
3355
3371
  }
3356
- return text5.slice(start, end + 1);
3372
+ return text6.slice(start, end + 1);
3357
3373
  }
3358
3374
  function extractErrorCode(responseJson) {
3359
3375
  const code = getNestedValue(responseJson, [0, 5, 2, 0, 1, 0]);
@@ -3361,12 +3377,12 @@ function extractErrorCode(responseJson) {
3361
3377
  }
3362
3378
  function extractCandidateText(candidate) {
3363
3379
  const textRaw = getNestedValue(candidate, [1, 0]);
3364
- let text5 = typeof textRaw === "string" ? textRaw : "";
3365
- if (/^http:\/\/googleusercontent\.com\/card_content\/\d+/.test(text5)) {
3380
+ let text6 = typeof textRaw === "string" ? textRaw : "";
3381
+ if (/^http:\/\/googleusercontent\.com\/card_content\/\d+/.test(text6)) {
3366
3382
  const alt = getNestedValue(candidate, [22, 0]);
3367
- if (typeof alt === "string" && alt.length > 0) text5 = alt;
3383
+ if (typeof alt === "string" && alt.length > 0) text6 = alt;
3368
3384
  }
3369
- return text5;
3385
+ return text6;
3370
3386
  }
3371
3387
  function parseStreamGenerateResponse(rawText) {
3372
3388
  const responseJson = JSON.parse(trimJsonEnvelope(rawText));
@@ -3383,13 +3399,13 @@ function parseStreamGenerateResponse(rawText) {
3383
3399
  if (!Array.isArray(candidateList) || candidateList.length === 0) continue;
3384
3400
  const firstCandidate = candidateList[0];
3385
3401
  if (firstCandidateSeen === void 0) firstCandidateSeen = firstCandidate;
3386
- const text6 = extractCandidateText(firstCandidate);
3387
- if (text6.length > 0) latestNonEmptyText = text6;
3402
+ const text7 = extractCandidateText(firstCandidate);
3403
+ if (text7.length > 0) latestNonEmptyText = text7;
3388
3404
  } catch {
3389
3405
  }
3390
3406
  }
3391
- const text5 = latestNonEmptyText.length > 0 ? latestNonEmptyText : extractCandidateText(firstCandidateSeen);
3392
- return { text: text5, errorCode };
3407
+ const text6 = latestNonEmptyText.length > 0 ? latestNonEmptyText : extractCandidateText(firstCandidateSeen);
3408
+ return { text: text6, errorCode };
3393
3409
  }
3394
3410
  var GEMINI_APP_URL, GEMINI_STREAM_GENERATE_URL, GEMINI_UPLOAD_URL, GEMINI_UPLOAD_PUSH_ID, GOOGLE_LIST_ACCOUNTS_URL, USER_AGENT, MODEL_HEADER_NAME, DEFAULT_GEMINI_WEB_MODEL, MODEL_HEADERS, REQUIRED_COOKIES, geminiFetchImpl, geminiFetchOverride, GEMINI_MAX_HEADER_SIZE;
3395
3411
  var init_gemini_web = __esm({
@@ -3486,6 +3502,7 @@ function isPerplexityAvailable() {
3486
3502
  });
3487
3503
  }
3488
3504
  async function postPerplexity(url, body, options) {
3505
+ const apiUrl = resolveProviderApiUrl("perplexity", url, loadConfig4().perplexityBaseUrl);
3489
3506
  checkRateLimit();
3490
3507
  const activityId = activityMonitor.logStart({ type: "api", query: options.activityQuery });
3491
3508
  activityMonitor.updateRateLimit({
@@ -3500,7 +3517,7 @@ async function postPerplexity(url, body, options) {
3500
3517
  const timeoutError = () => new Error("Perplexity API error 408: request timed out");
3501
3518
  let response;
3502
3519
  try {
3503
- response = await fetch(url, {
3520
+ response = await fetchWithCredentialRedirects(apiUrl, {
3504
3521
  method: "POST",
3505
3522
  headers: {
3506
3523
  Authorization: `Bearer ${apiKey}`,
@@ -3508,7 +3525,7 @@ async function postPerplexity(url, body, options) {
3508
3525
  },
3509
3526
  body: JSON.stringify(body),
3510
3527
  signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout
3511
- });
3528
+ }, ["Authorization"]);
3512
3529
  } catch (err) {
3513
3530
  if (timedOut()) {
3514
3531
  activityMonitor.logError(activityId, "request timed out");
@@ -3839,13 +3856,13 @@ function hasExtractUrlError(errors, url) {
3839
3856
  });
3840
3857
  }
3841
3858
  async function fetchAndMapExtractResult(url, body, signal) {
3842
- const data = await parallelFetch(PARALLEL_EXTRACT_URL, body, signal);
3859
+ const data = await parallelFetch(resolveProviderApiUrl("parallel", `${PARALLEL_API_BASE_URL}/v1/extract`, loadConfig8().parallelBaseUrl), body, signal);
3843
3860
  if (hasExtractUrlError(data.errors, url)) return { mapped: null, result: void 0 };
3844
3861
  const result = findExtractResult(data.results, url);
3845
3862
  return { mapped: mapExtractResult(result), result };
3846
3863
  }
3847
3864
  async function searchWithParallel(query, options = {}) {
3848
- const data = await parallelFetch(PARALLEL_SEARCH_URL, buildSearchRequestBody(query, options), options.signal);
3865
+ const data = await parallelFetch(resolveProviderApiUrl("parallel", `${PARALLEL_API_BASE_URL}/v1/search`, loadConfig8().parallelBaseUrl), buildSearchRequestBody(query, options), options.signal);
3849
3866
  const results = data.results;
3850
3867
  const response = {
3851
3868
  answer: buildAnswerFromExcerpts(results),
@@ -3869,7 +3886,7 @@ async function parallelFetch(url, body, signal) {
3869
3886
  const activityId = activityMonitor.logStart(activityContext(url, body));
3870
3887
  let response;
3871
3888
  try {
3872
- response = await fetch(url, {
3889
+ response = await fetchWithCredentialRedirects(url, {
3873
3890
  method: "POST",
3874
3891
  headers: {
3875
3892
  "x-api-key": apiKey,
@@ -3877,7 +3894,7 @@ async function parallelFetch(url, body, signal) {
3877
3894
  },
3878
3895
  body: JSON.stringify(body),
3879
3896
  signal: requestSignal2(signal)
3880
- });
3897
+ }, ["x-api-key"]);
3881
3898
  } catch (err) {
3882
3899
  const message = errorMessage(err);
3883
3900
  const redactedMessage = redactCredential(message, apiKey);
@@ -3902,15 +3919,14 @@ async function parallelFetch(url, body, signal) {
3902
3919
  throw new Error(`Parallel API returned invalid JSON: ${errorMessage(err)}`);
3903
3920
  }
3904
3921
  }
3905
- var PARALLEL_SEARCH_URL, PARALLEL_EXTRACT_URL, CONFIG_PATH9, MIN_PARALLEL_API_KEY_LENGTH, MIN_USEFUL_CONTENT, SEARCH_TIMEOUT_MS4, PLACEHOLDER_API_KEY_DENYLIST, cachedConfig9;
3922
+ var PARALLEL_API_BASE_URL, CONFIG_PATH9, MIN_PARALLEL_API_KEY_LENGTH, MIN_USEFUL_CONTENT, SEARCH_TIMEOUT_MS4, PLACEHOLDER_API_KEY_DENYLIST, cachedConfig9;
3906
3923
  var init_parallel = __esm({
3907
3924
  "parallel.ts"() {
3908
3925
  init_activity();
3909
3926
  init_domain_filter_normalization();
3910
3927
  init_credential_source();
3911
3928
  init_utils();
3912
- PARALLEL_SEARCH_URL = "https://api.parallel.ai/v1/search";
3913
- PARALLEL_EXTRACT_URL = "https://api.parallel.ai/v1/extract";
3929
+ PARALLEL_API_BASE_URL = "https://api.parallel.ai";
3914
3930
  CONFIG_PATH9 = getWebSearchConfigPath();
3915
3931
  MIN_PARALLEL_API_KEY_LENGTH = 8;
3916
3932
  MIN_USEFUL_CONTENT = 500;
@@ -4031,20 +4047,20 @@ async function callParallelMcp(toolName, args, signal) {
4031
4047
  throw new Error(`Parallel MCP error${code}: ${message}`);
4032
4048
  }
4033
4049
  if (parsed.result?.isError) {
4034
- const text6 = parsed.result.content?.find((item) => item.type === "text" && typeof item.text === "string")?.text?.trim() || "Parallel MCP returned an error";
4035
- throw new Error(apiKey ? redactCredential(text6, apiKey) : text6);
4050
+ const text7 = parsed.result.content?.find((item) => item.type === "text" && typeof item.text === "string")?.text?.trim() || "Parallel MCP returned an error";
4051
+ throw new Error(apiKey ? redactCredential(text7, apiKey) : text7);
4036
4052
  }
4037
4053
  if (parsed.result?.structuredContent && typeof parsed.result.structuredContent === "object") return parsed.result.structuredContent;
4038
- const text5 = parsed.result?.content?.find((item) => item.type === "text" && typeof item.text === "string" && item.text.trim())?.text;
4039
- if (!text5) throw new Error("Parallel MCP returned empty content");
4054
+ const text6 = parsed.result?.content?.find((item) => item.type === "text" && typeof item.text === "string" && item.text.trim())?.text;
4055
+ if (!text6) throw new Error("Parallel MCP returned empty content");
4040
4056
  try {
4041
- return JSON.parse(text5);
4057
+ return JSON.parse(text6);
4042
4058
  } catch {
4043
- return text5;
4059
+ return text6;
4044
4060
  }
4045
4061
  }
4046
- function parseTextResults(text5) {
4047
- return text5.split(/(?=^Title: )/m).flatMap((block) => {
4062
+ function parseTextResults(text6) {
4063
+ return text6.split(/(?=^Title: )/m).flatMap((block) => {
4048
4064
  const url = block.match(/^URL: (.+)/m)?.[1]?.trim();
4049
4065
  if (!url) return [];
4050
4066
  const title = block.match(/^Title: (.+)/m)?.[1]?.trim() ?? "";
@@ -4501,7 +4517,7 @@ function buildSearchBody(query, options) {
4501
4517
  async function search1APIJsonRequest(label, url, apiKey, body, timeoutMs, signal) {
4502
4518
  let response;
4503
4519
  try {
4504
- response = await fetch(url, {
4520
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("search1api", url, loadConfig10().search1apiBaseUrl), {
4505
4521
  method: "POST",
4506
4522
  headers: {
4507
4523
  Authorization: `Bearer ${apiKey}`,
@@ -4509,7 +4525,7 @@ async function search1APIJsonRequest(label, url, apiKey, body, timeoutMs, signal
4509
4525
  },
4510
4526
  body: JSON.stringify(body),
4511
4527
  signal: requestSignal5(signal, timeoutMs)
4512
- });
4528
+ }, ["Authorization"]);
4513
4529
  } catch (err) {
4514
4530
  const message = errorMessage4(err);
4515
4531
  const redactedMessage = redactCredential(message, apiKey);
@@ -4750,7 +4766,7 @@ function buildContentsBody(urls, options = {}) {
4750
4766
  async function queritJsonRequest(label, url, apiKey, body, timeoutMs, signal) {
4751
4767
  let response;
4752
4768
  try {
4753
- response = await fetch(url, {
4769
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("querit", url, loadConfig12().queritBaseUrl), {
4754
4770
  method: "POST",
4755
4771
  headers: {
4756
4772
  Authorization: `Bearer ${apiKey}`,
@@ -4759,7 +4775,7 @@ async function queritJsonRequest(label, url, apiKey, body, timeoutMs, signal) {
4759
4775
  },
4760
4776
  body: JSON.stringify(body),
4761
4777
  signal: requestSignal7(signal, timeoutMs)
4762
- });
4778
+ }, ["Authorization"]);
4763
4779
  } catch (err) {
4764
4780
  const message = errorMessage6(err);
4765
4781
  const isRequestAbort = err instanceof Error ? err.name === "AbortError" || err.name === "TimeoutError" || /abort|timeout/i.test(message) : /abort|timeout/i.test(message);
@@ -5614,8 +5630,8 @@ async function firecrawlFetch(endpoint, body, signal, options, label = endpoint,
5614
5630
  signal: requestSignal9(options?.timeoutMs ?? EXTRACT_TIMEOUT_MS, signal)
5615
5631
  }, options);
5616
5632
  if (!response.ok) {
5617
- const text5 = await response.text().catch(() => "");
5618
- throw new Error(`Firecrawl ${label} error ${response.status}: ${redactCredential(text5.slice(0, 300), apiKey)}`);
5633
+ const text6 = await response.text().catch(() => "");
5634
+ throw new Error(`Firecrawl ${label} error ${response.status}: ${redactCredential(text6.slice(0, 300), apiKey)}`);
5619
5635
  }
5620
5636
  let data;
5621
5637
  try {
@@ -5823,12 +5839,12 @@ async function searchWithKagi(query, options = {}) {
5823
5839
  const activityId = activityMonitor.logStart({ type: "api", query });
5824
5840
  let response;
5825
5841
  try {
5826
- response = await fetch(KAGI_SEARCH_URL, {
5842
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("kagi", KAGI_SEARCH_URL, loadConfig18().kagiBaseUrl), {
5827
5843
  method: "POST",
5828
5844
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
5829
5845
  body: JSON.stringify({ query, limit: numResults }),
5830
5846
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS14), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS14)
5831
- });
5847
+ }, ["Authorization"]);
5832
5848
  } catch (err) {
5833
5849
  const message = errorMessage12(err);
5834
5850
  const redactedMessage = redactCredential(message, apiKey);
@@ -5878,7 +5894,7 @@ async function extractWithKagi(url, signal, options = {}) {
5878
5894
  const activityId = activityMonitor.logStart({ type: "api", query: `kagi extract: ${url}` });
5879
5895
  let response;
5880
5896
  try {
5881
- response = await fetchRemoteUrl(KAGI_EXTRACT_URL, {
5897
+ response = await fetchRemoteUrl(resolveProviderApiUrl("kagi", KAGI_EXTRACT_URL, loadConfig18().kagiBaseUrl), {
5882
5898
  method: "POST",
5883
5899
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
5884
5900
  body: JSON.stringify({ pages: [{ url }] }),
@@ -6015,12 +6031,12 @@ async function searchWithOllama(query, options = {}) {
6015
6031
  const activityId = activityMonitor.logStart({ type: "api", query });
6016
6032
  let response;
6017
6033
  try {
6018
- response = await fetch(OLLAMA_SEARCH_URL, {
6034
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("ollama", OLLAMA_SEARCH_URL, loadConfig20().ollamaBaseUrl), {
6019
6035
  method: "POST",
6020
6036
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
6021
6037
  body: JSON.stringify({ query, max_results: numResults }),
6022
6038
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS16), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS16)
6023
- });
6039
+ }, ["Authorization"]);
6024
6040
  } catch (err) {
6025
6041
  const message = errorMessage14(err);
6026
6042
  const redactedMessage = redactCredential(message, apiKey);
@@ -6069,7 +6085,7 @@ async function extractWithOllama(url, signal, options = {}) {
6069
6085
  const activityId = activityMonitor.logStart({ type: "api", query: `ollama fetch: ${url}` });
6070
6086
  let response;
6071
6087
  try {
6072
- response = await fetchRemoteUrl(OLLAMA_FETCH_URL, {
6088
+ response = await fetchRemoteUrl(resolveProviderApiUrl("ollama", OLLAMA_FETCH_URL, loadConfig20().ollamaBaseUrl), {
6073
6089
  method: "POST",
6074
6090
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
6075
6091
  body: JSON.stringify({ url }),
@@ -6124,8 +6140,320 @@ var init_ollama = __esm({
6124
6140
  }
6125
6141
  });
6126
6142
 
6143
+ // deepseek.ts
6144
+ import { existsSync as existsSync43, readFileSync as readFileSync43 } from "node:fs";
6145
+ function loadConfig36() {
6146
+ if (cachedConfig36) return cachedConfig36;
6147
+ if (!existsSync43(CONFIG_PATH39)) {
6148
+ cachedConfig36 = {};
6149
+ return cachedConfig36;
6150
+ }
6151
+ const raw = readFileSync43(CONFIG_PATH39, "utf-8");
6152
+ let parsed;
6153
+ try {
6154
+ parsed = JSON.parse(raw);
6155
+ } catch (err) {
6156
+ const message = err instanceof Error ? err.message : String(err);
6157
+ throw new Error(`Failed to parse ${CONFIG_PATH39}: ${message}`);
6158
+ }
6159
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6160
+ throw new Error(`Invalid config in ${CONFIG_PATH39}: expected a JSON object`);
6161
+ }
6162
+ cachedConfig36 = parsed;
6163
+ return cachedConfig36;
6164
+ }
6165
+ async function requireApiKey15(signal) {
6166
+ const apiKey = await resolveCredential({
6167
+ provider: "DeepSeek",
6168
+ configuredValue: loadConfig36().deepseekApiKey,
6169
+ environmentValue: process.env.DEEPSEEK_API_KEY,
6170
+ signal
6171
+ });
6172
+ if (!apiKey) {
6173
+ throw new Error(
6174
+ `DeepSeek API key not found. Either:
6175
+ 1. Create ${CONFIG_PATH39} with { "deepseekApiKey": "your-key" }
6176
+ 2. Set DEEPSEEK_API_KEY environment variable
6177
+ Get a key at https://platform.deepseek.com/api_keys`
6178
+ );
6179
+ }
6180
+ return apiKey;
6181
+ }
6182
+ function buildQuery8(query, options) {
6183
+ const include = [];
6184
+ const exclude = [];
6185
+ for (const raw of options.domainFilter ?? []) {
6186
+ const domain = normalizeDomain(raw);
6187
+ if (!domain) continue;
6188
+ const target = raw.trim().startsWith("-") ? exclude : include;
6189
+ if (!target.includes(domain)) target.push(domain);
6190
+ }
6191
+ const parts = [query.trim()];
6192
+ if (include.length > 0) parts.push(include.map((domain) => `site:${domain}`).join(" OR "));
6193
+ for (const domain of exclude) parts.push(`-site:${domain}`);
6194
+ if (options.recencyFilter) {
6195
+ const after = new Date(Date.now() - RECENCY_DAYS2[options.recencyFilter] * 864e5).toISOString().slice(0, 10);
6196
+ parts.push(`after:${after}`);
6197
+ }
6198
+ const built = parts.join(" ");
6199
+ const length = [...built].length;
6200
+ if (length > MAX_QUERY_CHARS) {
6201
+ throw new Error(`DeepSeek invalid request: the query is ${length} characters with domain and date filters; DeepSeek accepts at most ${MAX_QUERY_CHARS}`);
6202
+ }
6203
+ return built;
6204
+ }
6205
+ function text5(value) {
6206
+ return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
6207
+ }
6208
+ function errorMessage26(err) {
6209
+ return err instanceof Error ? err.message : String(err);
6210
+ }
6211
+ function unescapeMarkdownSegment(segment) {
6212
+ return segment.replace(/\\([/.,:()&+#>|!_\-"'])/g, (match, char, offset, whole) => {
6213
+ if (char === "!" && whole[offset + 2] === "[") return match;
6214
+ return char;
6215
+ });
6216
+ }
6217
+ function normalizeInlineMarkdown(line) {
6218
+ return line.split(/(`+[^`]*`+)/g).map((part, index) => index % 2 === 0 ? unescapeMarkdownSegment(part) : part).join("");
6219
+ }
6220
+ function normalizeDeepSeekMarkdown(markdown) {
6221
+ let fence = null;
6222
+ return markdown.split("\n").map((line) => {
6223
+ const match = line.match(/^\s{0,3}(`{3,}|~{3,})/);
6224
+ if (match) {
6225
+ const marker = match[1];
6226
+ if (fence === null) {
6227
+ fence = { char: marker[0], length: marker.length };
6228
+ } else if (marker[0] === fence.char && marker.length >= fence.length && line.slice(match[0].length).trim() === "") {
6229
+ fence = null;
6230
+ }
6231
+ return line;
6232
+ }
6233
+ return fence === null ? normalizeInlineMarkdown(line) : line;
6234
+ }).join("\n");
6235
+ }
6236
+ function firstMarkdownHeading(content) {
6237
+ let fence = null;
6238
+ for (const line of content.split("\n")) {
6239
+ const fenceMatch = line.match(/^\s{0,3}(`{3,}|~{3,})/);
6240
+ if (fenceMatch) {
6241
+ const marker = fenceMatch[1];
6242
+ if (fence === null) {
6243
+ fence = { char: marker[0], length: marker.length };
6244
+ } else if (marker[0] === fence.char && marker.length >= fence.length && line.slice(fenceMatch[0].length).trim() === "") {
6245
+ fence = null;
6246
+ }
6247
+ continue;
6248
+ }
6249
+ if (fence !== null) continue;
6250
+ const heading = line.match(/^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/);
6251
+ if (heading) return heading[1].trim();
6252
+ }
6253
+ return "";
6254
+ }
6255
+ function isUnusableDeepSeekPage(title, content) {
6256
+ if (content.length >= 500) return false;
6257
+ const heading = firstMarkdownHeading(content);
6258
+ if (heading !== "" && ERROR_TITLE.test(heading)) return true;
6259
+ return ERROR_TITLE.test(text5(title)) && /\b(?:404|page not found|not found)\b/i.test(content.slice(0, 200));
6260
+ }
6261
+ function parseResponse12(value) {
6262
+ const results = value && typeof value === "object" && !Array.isArray(value) ? value.results : void 0;
6263
+ if (!Array.isArray(results)) throw new Error("DeepSeek returned invalid response: expected a results array");
6264
+ return results;
6265
+ }
6266
+ function describeError2(body) {
6267
+ try {
6268
+ const error = JSON.parse(body).error;
6269
+ const message = text5(error?.message);
6270
+ if (message) return message;
6271
+ } catch {
6272
+ }
6273
+ return body;
6274
+ }
6275
+ function isDeepSeekAvailable() {
6276
+ return hasCredentialSource({ provider: "DeepSeek", configuredValue: loadConfig36().deepseekApiKey, environmentValue: process.env.DEEPSEEK_API_KEY });
6277
+ }
6278
+ async function searchWithDeepSeek(query, options = {}) {
6279
+ const builtQuery = buildQuery8(query, options);
6280
+ const apiKey = await requireApiKey15(options.signal);
6281
+ const numResults = normalizeSearchResultCount(options.numResults);
6282
+ const activityId = activityMonitor.logStart({ type: "api", query });
6283
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS33);
6284
+ let response;
6285
+ let entries;
6286
+ try {
6287
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek", DEEPSEEK_SEARCH_URL, loadConfig36().deepseekBaseUrl), {
6288
+ method: "POST",
6289
+ headers: {
6290
+ Accept: "application/json",
6291
+ "Content-Type": "application/json",
6292
+ Authorization: `Bearer ${apiKey}`
6293
+ },
6294
+ body: JSON.stringify({ query: builtQuery, count: numResults, ...options.includeContent ? { need_content: true } : {} }),
6295
+ signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal
6296
+ }, ["Authorization"]);
6297
+ if (!response.ok) {
6298
+ const errorText = redactCredential(describeError2(await response.text()), apiKey).slice(0, 300);
6299
+ throw new Error(`DeepSeek error ${response.status}: ${errorText}`);
6300
+ }
6301
+ let rawData;
6302
+ try {
6303
+ rawData = await response.json();
6304
+ } catch (err) {
6305
+ if (err instanceof Error && err.name === "TimeoutError") throw err;
6306
+ throw new Error(`DeepSeek returned invalid JSON: ${errorMessage26(err)}`);
6307
+ }
6308
+ entries = parseResponse12(rawData);
6309
+ } catch (err) {
6310
+ if (options.signal?.aborted) {
6311
+ activityMonitor.logComplete(activityId, 0);
6312
+ throw new Error("Aborted");
6313
+ }
6314
+ const message = errorMessage26(err);
6315
+ const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
6316
+ const outgoing = providerTimeout ? new Error(`DeepSeek request timed out after ${Math.round(SEARCH_TIMEOUT_MS33 / 1e3)}s`) : (() => {
6317
+ const redactedMessage = redactCredential(message, apiKey);
6318
+ if (redactedMessage === message && err instanceof Error) return err;
6319
+ const redactedError = new Error(redactedMessage);
6320
+ if (err instanceof Error) redactedError.name = err.name;
6321
+ return redactedError;
6322
+ })();
6323
+ activityMonitor.logError(activityId, redactCredential(errorMessage26(outgoing), apiKey));
6324
+ throw outgoing;
6325
+ }
6326
+ activityMonitor.logComplete(activityId, response.status);
6327
+ const results = [];
6328
+ const inlineContent = [];
6329
+ const seen = /* @__PURE__ */ new Set();
6330
+ for (const entry of entries) {
6331
+ if (!entry || typeof entry !== "object") continue;
6332
+ if (typeof entry.url !== "string" || !entry.url) continue;
6333
+ let resultUrl;
6334
+ try {
6335
+ resultUrl = new URL(entry.url);
6336
+ } catch {
6337
+ continue;
6338
+ }
6339
+ if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
6340
+ if (seen.has(resultUrl.href)) continue;
6341
+ seen.add(resultUrl.href);
6342
+ const title = text5(entry.title) || `Source ${results.length + 1}`;
6343
+ results.push({
6344
+ title,
6345
+ url: resultUrl.href,
6346
+ snippet: (text5(entry.summary) || text5(entry.snippet)).slice(0, MAX_SNIPPET_CHARS4)
6347
+ });
6348
+ if (options.includeContent) {
6349
+ const content = typeof entry.content === "string" ? entry.content.trim() : "";
6350
+ if (content) inlineContent.push({ url: resultUrl.href, title, content, error: null });
6351
+ }
6352
+ if (results.length >= numResults) break;
6353
+ }
6354
+ if (entries.length > 0 && results.length === 0) throw new Error("DeepSeek returned invalid response: no result had an http(s) URL");
6355
+ const searchResponse = { answer: formatSearchResultsAsAnswer(results), results };
6356
+ if (inlineContent.length > 0) searchResponse.inlineContent = inlineContent;
6357
+ return searchResponse;
6358
+ }
6359
+ async function extractWithDeepSeek(url, signal, options = {}) {
6360
+ const apiKey = await requireApiKey15(signal);
6361
+ const activityId = activityMonitor.logStart({ type: "fetch", url });
6362
+ const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS2;
6363
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
6364
+ try {
6365
+ const ssrf = loadSsrfConfig();
6366
+ await validateRemoteUrl(url, {
6367
+ allowRanges: ssrf.allowRanges,
6368
+ trustEnvProxy: ssrf.trustEnvProxy,
6369
+ domainPolicy: loadFetchContentDomainPolicy(),
6370
+ ...options.lookup ? { lookup: options.lookup } : {}
6371
+ });
6372
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek", DEEPSEEK_FETCH_URL, loadConfig36().deepseekBaseUrl), {
6373
+ method: "POST",
6374
+ headers: {
6375
+ Accept: "application/json",
6376
+ "Content-Type": "application/json",
6377
+ Authorization: `Bearer ${apiKey}`
6378
+ },
6379
+ body: JSON.stringify({ url }),
6380
+ signal: signal ? AbortSignal.any([timeoutSignal, signal]) : timeoutSignal
6381
+ }, ["Authorization"]);
6382
+ if (!response.ok) {
6383
+ const errorText = redactCredential(describeError2(await response.text()), apiKey).slice(0, 300);
6384
+ throw new Error(`DeepSeek Fetch error ${response.status}: ${errorText}`);
6385
+ }
6386
+ let rawData;
6387
+ try {
6388
+ rawData = await response.json();
6389
+ } catch (err) {
6390
+ if (err instanceof Error && err.name === "TimeoutError") throw err;
6391
+ throw new Error(`DeepSeek Fetch returned invalid JSON: ${errorMessage26(err)}`);
6392
+ }
6393
+ if (!rawData || typeof rawData !== "object" || Array.isArray(rawData)) {
6394
+ throw new Error("DeepSeek Fetch returned an unexpected response shape");
6395
+ }
6396
+ const page = rawData;
6397
+ const title = typeof page.title === "string" ? page.title.trim() : "";
6398
+ const content = typeof page.content === "string" ? normalizeDeepSeekMarkdown(page.content).trim() : "";
6399
+ if (!content || isUnusableDeepSeekPage(title, content)) {
6400
+ activityMonitor.logComplete(activityId, response.status);
6401
+ return null;
6402
+ }
6403
+ activityMonitor.logComplete(activityId, response.status);
6404
+ return {
6405
+ url,
6406
+ title,
6407
+ content,
6408
+ error: null
6409
+ };
6410
+ } catch (err) {
6411
+ const message = errorMessage26(err);
6412
+ if (signal?.aborted) {
6413
+ activityMonitor.logComplete(activityId, 0);
6414
+ throw new Error("Aborted");
6415
+ }
6416
+ activityMonitor.logError(activityId, redactCredential(message, apiKey));
6417
+ if (err instanceof Error && err.name === "TimeoutError") {
6418
+ throw new Error(`DeepSeek Fetch request timed out after ${Math.round(timeoutMs / 1e3)}s`);
6419
+ }
6420
+ const redactedMessage = redactCredential(message, apiKey);
6421
+ if (redactedMessage === message) throw err;
6422
+ const redactedError = new Error(redactedMessage);
6423
+ if (err instanceof Error) redactedError.name = err.name;
6424
+ throw redactedError;
6425
+ }
6426
+ }
6427
+ var DEEPSEEK_SEARCH_URL, DEEPSEEK_FETCH_URL, CONFIG_PATH39, SEARCH_TIMEOUT_MS33, FETCH_TIMEOUT_MS2, MAX_QUERY_CHARS, MAX_SNIPPET_CHARS4, RECENCY_DAYS2, cachedConfig36, ERROR_TITLE;
6428
+ var init_deepseek = __esm({
6429
+ "deepseek.ts"() {
6430
+ init_activity();
6431
+ init_domain_filter_normalization();
6432
+ init_search_answer_formatting();
6433
+ init_search_result_count_normalization();
6434
+ init_credential_source();
6435
+ init_ssrf_protection();
6436
+ init_utils();
6437
+ DEEPSEEK_SEARCH_URL = "https://api.deepseek.com/v1/tools/search";
6438
+ DEEPSEEK_FETCH_URL = "https://api.deepseek.com/v1/tools/fetch";
6439
+ CONFIG_PATH39 = getWebSearchConfigPath();
6440
+ SEARCH_TIMEOUT_MS33 = 3e4;
6441
+ FETCH_TIMEOUT_MS2 = 6e4;
6442
+ MAX_QUERY_CHARS = 128;
6443
+ MAX_SNIPPET_CHARS4 = 800;
6444
+ RECENCY_DAYS2 = {
6445
+ day: 1,
6446
+ week: 7,
6447
+ month: 30,
6448
+ year: 365
6449
+ };
6450
+ cachedConfig36 = null;
6451
+ ERROR_TITLE = /^(?:404\b|page not found\b|not found\b)/i;
6452
+ }
6453
+ });
6454
+
6127
6455
  // auth-fetch.ts
6128
- import { existsSync as existsSync45, readFileSync as readFileSync46 } from "node:fs";
6456
+ import { existsSync as existsSync46, readFileSync as readFileSync47 } from "node:fs";
6129
6457
  function resolveAuthFetchProfile(request) {
6130
6458
  const profiles = loadAuthFetchProfiles();
6131
6459
  if (profiles.length === 0) {
@@ -6163,8 +6491,8 @@ function authFetchRedirectGuard(profile, from, to) {
6163
6491
  }
6164
6492
  }
6165
6493
  function loadAuthFetchProfiles() {
6166
- if (!existsSync45(WEB_SEARCH_CONFIG_PATH2)) return [];
6167
- const raw = readFileSync46(WEB_SEARCH_CONFIG_PATH2, "utf-8");
6494
+ if (!existsSync46(WEB_SEARCH_CONFIG_PATH2)) return [];
6495
+ const raw = readFileSync47(WEB_SEARCH_CONFIG_PATH2, "utf-8");
6168
6496
  let parsed;
6169
6497
  try {
6170
6498
  const value = JSON.parse(raw);
@@ -6498,8 +6826,8 @@ function extractRSCContent(html) {
6498
6826
  if (!Array.isArray(node)) return;
6499
6827
  if (node[0] === "$" && (node[1] === "td" || node[1] === "th")) {
6500
6828
  const cellProps = node[3] || {};
6501
- const text5 = extractNode(cellProps.children, { inTable: true, inCode: false }).trim().replace(/\n/g, " ").replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
6502
- cells.push(text5);
6829
+ const text6 = extractNode(cellProps.children, { inTable: true, inCode: false }).trim().replace(/\n/g, " ").replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
6830
+ cells.push(text6);
6503
6831
  } else if (node[0] === "$" && typeof node[1] === "string" && node[1].startsWith("$L")) {
6504
6832
  const refId = node[1].slice(2);
6505
6833
  if (!visitedRefs.has(refId)) {
@@ -6539,9 +6867,9 @@ function extractRSCContent(html) {
6539
6867
  const parsed = getParsedChunk(id);
6540
6868
  if (!parsed) continue;
6541
6869
  visitedRefs.clear();
6542
- const text5 = extractNode(parsed);
6543
- if (text5.trim().length > 50 && !text5.includes("page was not found") && !text5.includes("404")) {
6544
- contentParts.push({ order: parseInt(id, 16), text: text5.trim() });
6870
+ const text6 = extractNode(parsed);
6871
+ if (text6.trim().length > 50 && !text6.includes("page was not found") && !text6.includes("404")) {
6872
+ contentParts.push({ order: parseInt(id, 16), text: text6.trim() });
6545
6873
  }
6546
6874
  }
6547
6875
  if (contentParts.length === 0) return null;
@@ -6564,20 +6892,20 @@ var init_rsc_extract = __esm({
6564
6892
  });
6565
6893
 
6566
6894
  // datalab-pdf-extract.ts
6567
- import { existsSync as existsSync46, readFileSync as readFileSync47 } from "node:fs";
6568
- function loadConfig37() {
6569
- if (cachedConfig37) return cachedConfig37;
6570
- if (!existsSync46(CONFIG_PATH41)) {
6571
- cachedConfig37 = {};
6572
- return cachedConfig37;
6895
+ import { existsSync as existsSync47, readFileSync as readFileSync48 } from "node:fs";
6896
+ function loadConfig38() {
6897
+ if (cachedConfig38) return cachedConfig38;
6898
+ if (!existsSync47(CONFIG_PATH42)) {
6899
+ cachedConfig38 = {};
6900
+ return cachedConfig38;
6573
6901
  }
6574
- const rawText = readFileSync47(CONFIG_PATH41, "utf-8");
6902
+ const rawText = readFileSync48(CONFIG_PATH42, "utf-8");
6575
6903
  try {
6576
- cachedConfig37 = JSON.parse(rawText);
6577
- return cachedConfig37;
6904
+ cachedConfig38 = JSON.parse(rawText);
6905
+ return cachedConfig38;
6578
6906
  } catch (err) {
6579
6907
  const message = err instanceof Error ? err.message : String(err);
6580
- throw new Error(`Failed to parse ${CONFIG_PATH41}: ${message}`);
6908
+ throw new Error(`Failed to parse ${CONFIG_PATH42}: ${message}`);
6581
6909
  }
6582
6910
  }
6583
6911
  function normalizeString(value) {
@@ -6592,14 +6920,14 @@ function normalizeFileId(value) {
6592
6920
  function isDatalabApiAvailable() {
6593
6921
  return hasCredentialSource({
6594
6922
  provider: "Datalab",
6595
- configuredValue: loadConfig37().datalabApiKey,
6923
+ configuredValue: loadConfig38().datalabApiKey,
6596
6924
  environmentValue: process.env.DATALAB_API_KEY
6597
6925
  });
6598
6926
  }
6599
6927
  async function getDatalabApiKey(signal) {
6600
6928
  return resolveCredential({
6601
6929
  provider: "Datalab",
6602
- configuredValue: loadConfig37().datalabApiKey,
6930
+ configuredValue: loadConfig38().datalabApiKey,
6603
6931
  environmentValue: process.env.DATALAB_API_KEY,
6604
6932
  signal
6605
6933
  });
@@ -6871,18 +7199,18 @@ async function fetchDatalab(url, init, apiKey) {
6871
7199
  }
6872
7200
  }
6873
7201
  async function readJsonResponse(response, apiKey) {
6874
- const text5 = await readResponseText(response);
7202
+ const text6 = await readResponseText(response);
6875
7203
  if (!response.ok) {
6876
- const detail = text5.trim().slice(0, MAX_ERROR_BODY_BYTES);
7204
+ const detail = text6.trim().slice(0, MAX_ERROR_BODY_BYTES);
6877
7205
  const message = detail ? `Datalab PDF conversion failed: HTTP ${response.status} ${response.statusText}: ${detail}` : `Datalab PDF conversion failed: HTTP ${response.status} ${response.statusText}`;
6878
7206
  throw new Error(redactCredential(message, apiKey));
6879
7207
  }
6880
- return parseJsonRecord(text5);
7208
+ return parseJsonRecord(text6);
6881
7209
  }
6882
- function parseJsonRecord(text5) {
7210
+ function parseJsonRecord(text6) {
6883
7211
  let parsed;
6884
7212
  try {
6885
- parsed = JSON.parse(text5);
7213
+ parsed = JSON.parse(text6);
6886
7214
  } catch (error) {
6887
7215
  throw new Error("Datalab PDF conversion returned invalid JSON", { cause: error });
6888
7216
  }
@@ -6924,7 +7252,7 @@ async function readResponseText(response) {
6924
7252
  function datalabFilename(title) {
6925
7253
  return title.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "document";
6926
7254
  }
6927
- 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;
7255
+ var DEFAULT_API_HOST2, API_PREFIX, DEFAULT_TIMEOUT_MS, 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, cachedConfig38;
6928
7256
  var init_datalab_pdf_extract = __esm({
6929
7257
  "datalab-pdf-extract.ts"() {
6930
7258
  init_credential_source();
@@ -6936,7 +7264,7 @@ var init_datalab_pdf_extract = __esm({
6936
7264
  MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
6937
7265
  MAX_ERROR_BODY_BYTES = 300;
6938
7266
  CLEANUP_TIMEOUT_MS = 5e3;
6939
- CONFIG_PATH41 = getWebSearchConfigPath();
7267
+ CONFIG_PATH42 = getWebSearchConfigPath();
6940
7268
  DATALAB_MODE_VALUES = /* @__PURE__ */ new Set([
6941
7269
  "fast",
6942
7270
  "balanced",
@@ -6949,21 +7277,21 @@ var init_datalab_pdf_extract = __esm({
6949
7277
  DEFAULT_DATALAB_MODE = "balanced";
6950
7278
  DEFAULT_PROCESSING_LOCATION = "us";
6951
7279
  DEFAULT_DATALAB_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
6952
- cachedConfig37 = null;
7280
+ cachedConfig38 = null;
6953
7281
  }
6954
7282
  });
6955
7283
 
6956
7284
  // endpoint-pdf-extract.ts
6957
- import { existsSync as existsSync47, readFileSync as readFileSync48 } from "node:fs";
7285
+ import { existsSync as existsSync48, readFileSync as readFileSync49 } from "node:fs";
6958
7286
  import { setTimeout as sleep2 } from "node:timers/promises";
6959
7287
  function pdfSection() {
6960
- if (!existsSync47(CONFIG_PATH42)) return {};
7288
+ if (!existsSync48(CONFIG_PATH43)) return {};
6961
7289
  let parsed;
6962
7290
  try {
6963
- parsed = JSON.parse(readFileSync48(CONFIG_PATH42, "utf-8"));
7291
+ parsed = JSON.parse(readFileSync49(CONFIG_PATH43, "utf-8"));
6964
7292
  } catch (err) {
6965
7293
  const message = err instanceof Error ? err.message : String(err);
6966
- throw new Error(`Failed to parse ${CONFIG_PATH42}: ${message}`);
7294
+ throw new Error(`Failed to parse ${CONFIG_PATH43}: ${message}`);
6967
7295
  }
6968
7296
  const pdf = parsed?.pdf;
6969
7297
  return pdf && typeof pdf === "object" ? pdf : {};
@@ -7002,11 +7330,11 @@ async function readCapped(response, maxBytes, overflowThrows) {
7002
7330
  const reader = response.body?.getReader();
7003
7331
  if (!reader) return "";
7004
7332
  const decoder = new TextDecoder();
7005
- let text5 = "";
7333
+ let text6 = "";
7006
7334
  let received = 0;
7007
7335
  for (; ; ) {
7008
7336
  const { done, value } = await reader.read();
7009
- if (done) return text5 + decoder.decode();
7337
+ if (done) return text6 + decoder.decode();
7010
7338
  const room = maxBytes - received;
7011
7339
  received += value.byteLength;
7012
7340
  if (received >= maxBytes) {
@@ -7014,15 +7342,15 @@ async function readCapped(response, maxBytes, overflowThrows) {
7014
7342
  if (overflowThrows && received > maxBytes) {
7015
7343
  throw new Error("PDF parser endpoint returned an oversized response");
7016
7344
  }
7017
- return text5 + decoder.decode(value.subarray(0, room));
7345
+ return text6 + decoder.decode(value.subarray(0, room));
7018
7346
  }
7019
- text5 += decoder.decode(value, { stream: true });
7347
+ text6 += decoder.decode(value, { stream: true });
7020
7348
  }
7021
7349
  }
7022
7350
  async function readJson(response) {
7023
- const text5 = await readCapped(response, MAX_RESPONSE_BYTES2, true);
7351
+ const text6 = await readCapped(response, MAX_RESPONSE_BYTES2, true);
7024
7352
  try {
7025
- const parsed = JSON.parse(text5);
7353
+ const parsed = JSON.parse(text6);
7026
7354
  if (parsed && typeof parsed === "object") return parsed;
7027
7355
  } catch {
7028
7356
  }
@@ -7030,8 +7358,8 @@ async function readJson(response) {
7030
7358
  }
7031
7359
  async function errorBody(response) {
7032
7360
  try {
7033
- const text5 = await readCapped(response, MAX_ERROR_BODY_BYTES2, false);
7034
- return text5 ? `: ${text5}` : "";
7361
+ const text6 = await readCapped(response, MAX_ERROR_BODY_BYTES2, false);
7362
+ return text6 ? `: ${text6}` : "";
7035
7363
  } catch {
7036
7364
  return "";
7037
7365
  }
@@ -7115,7 +7443,7 @@ async function extractPDFViaEndpoint(buffer, options) {
7115
7443
  }
7116
7444
  throw new Error("PDF parser endpoint job timed out");
7117
7445
  }
7118
- var DEFAULT_TIMEOUT_MS2, MAX_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES2, MAX_ERROR_BODY_BYTES2, CONFIG_PATH42;
7446
+ var DEFAULT_TIMEOUT_MS2, MAX_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES2, MAX_ERROR_BODY_BYTES2, CONFIG_PATH43;
7119
7447
  var init_endpoint_pdf_extract = __esm({
7120
7448
  "endpoint-pdf-extract.ts"() {
7121
7449
  init_ssrf_protection();
@@ -7124,7 +7452,7 @@ var init_endpoint_pdf_extract = __esm({
7124
7452
  MAX_POLL_INTERVAL_MS = 3e3;
7125
7453
  MAX_RESPONSE_BYTES2 = 4 * 1024 * 1024;
7126
7454
  MAX_ERROR_BODY_BYTES2 = 300;
7127
- CONFIG_PATH42 = getWebSearchConfigPath();
7455
+ CONFIG_PATH43 = getWebSearchConfigPath();
7128
7456
  }
7129
7457
  });
7130
7458
 
@@ -7214,12 +7542,12 @@ var init_gemini_pdf_extract = __esm({
7214
7542
  });
7215
7543
 
7216
7544
  // pdf-extract.ts
7217
- import { existsSync as existsSync48, readFileSync as readFileSync49 } from "node:fs";
7545
+ import { existsSync as existsSync49, readFileSync as readFileSync50 } from "node:fs";
7218
7546
  import { writeFile as writeFile2, mkdir } from "node:fs/promises";
7219
7547
  import { join as join6, basename as basename3 } from "node:path";
7220
7548
  import { tmpdir as tmpdir3 } from "node:os";
7221
7549
  function loadPDFConfig() {
7222
- if (!existsSync48(CONFIG_PATH43)) {
7550
+ if (!existsSync49(CONFIG_PATH44)) {
7223
7551
  return {
7224
7552
  enabled: true,
7225
7553
  maxSizeMB: DEFAULT_PDF_MAX_SIZE_MB,
@@ -7229,13 +7557,13 @@ function loadPDFConfig() {
7229
7557
  datalabTimeoutMs: DEFAULT_DATALAB_TIMEOUT_MS
7230
7558
  };
7231
7559
  }
7232
- const rawText = readFileSync49(CONFIG_PATH43, "utf-8");
7560
+ const rawText = readFileSync50(CONFIG_PATH44, "utf-8");
7233
7561
  let raw;
7234
7562
  try {
7235
7563
  raw = JSON.parse(rawText);
7236
7564
  } catch (err) {
7237
7565
  const message = err instanceof Error ? err.message : String(err);
7238
- throw new Error(`Failed to parse ${CONFIG_PATH43}: ${message}`);
7566
+ throw new Error(`Failed to parse ${CONFIG_PATH44}: ${message}`);
7239
7567
  }
7240
7568
  const root = raw && typeof raw === "object" ? raw : {};
7241
7569
  const pdf = root.pdf && typeof root.pdf === "object" ? root.pdf : {};
@@ -7471,7 +7799,7 @@ function isPDF(url, contentType) {
7471
7799
  return false;
7472
7800
  }
7473
7801
  }
7474
- 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;
7802
+ 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;
7475
7803
  var init_pdf_extract = __esm({
7476
7804
  "pdf-extract.ts"() {
7477
7805
  init_credential_source();
@@ -7492,36 +7820,36 @@ var init_pdf_extract = __esm({
7492
7820
  MAX_DATALAB_TIMEOUT_MS = 3e5;
7493
7821
  DEFAULT_MAX_PAGES = 100;
7494
7822
  DEFAULT_OUTPUT_DIR = join6(tmpdir3(), "pi-web-pdf");
7495
- CONFIG_PATH43 = getWebSearchConfigPath();
7823
+ CONFIG_PATH44 = getWebSearchConfigPath();
7496
7824
  PAGE_MARKER_PATTERN2 = /^<!-- Page (\d+) -->$/gm;
7497
7825
  }
7498
7826
  });
7499
7827
 
7500
7828
  // github-issue-pr.ts
7501
7829
  import { execFile as execFile5 } from "node:child_process";
7502
- import { existsSync as existsSync49, readFileSync as readFileSync50 } from "node:fs";
7503
- function loadConfig38() {
7504
- if (cachedConfig38) return cachedConfig38;
7830
+ import { existsSync as existsSync50, readFileSync as readFileSync51 } from "node:fs";
7831
+ function loadConfig39() {
7832
+ if (cachedConfig39) return cachedConfig39;
7505
7833
  const defaults2 = { enabled: true };
7506
- if (!existsSync49(CONFIG_PATH44)) {
7507
- cachedConfig38 = defaults2;
7508
- return cachedConfig38;
7834
+ if (!existsSync50(CONFIG_PATH45)) {
7835
+ cachedConfig39 = defaults2;
7836
+ return cachedConfig39;
7509
7837
  }
7510
7838
  let parsed;
7511
7839
  try {
7512
- parsed = JSON.parse(readFileSync50(CONFIG_PATH44, "utf-8"));
7840
+ parsed = JSON.parse(readFileSync51(CONFIG_PATH45, "utf-8"));
7513
7841
  } catch (err) {
7514
7842
  const message = err instanceof Error ? err.message : String(err);
7515
- throw new Error(`Failed to parse ${CONFIG_PATH44}: ${message}`);
7843
+ throw new Error(`Failed to parse ${CONFIG_PATH45}: ${message}`);
7516
7844
  }
7517
7845
  const root = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
7518
7846
  const value = root.githubPrIssue;
7519
7847
  if (value !== void 0 && (typeof value !== "object" || value === null || Array.isArray(value))) {
7520
- throw new Error(`githubPrIssue in ${CONFIG_PATH44} must be an object`);
7848
+ throw new Error(`githubPrIssue in ${CONFIG_PATH45} must be an object`);
7521
7849
  }
7522
7850
  const enabled = typeof value?.enabled === "boolean" ? value.enabled : true;
7523
- cachedConfig38 = { enabled };
7524
- return cachedConfig38;
7851
+ cachedConfig39 = { enabled };
7852
+ return cachedConfig39;
7525
7853
  }
7526
7854
  function validOwner(owner) {
7527
7855
  return /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(owner) && !owner.includes("--");
@@ -7827,14 +8155,14 @@ function milestoneTitle(value) {
7827
8155
  if (!value || typeof value !== "object" || Array.isArray(value)) return "none";
7828
8156
  return stringValue(value.title) || "none";
7829
8157
  }
7830
- function truncateText(text5, limit, label, appendix, tool) {
7831
- if (text5.length <= limit) return text5;
7832
- const lastSpace = text5.slice(0, limit + 1).search(/\s\S*$/);
8158
+ function truncateText(text6, limit, label, appendix, tool) {
8159
+ if (text6.length <= limit) return text6;
8160
+ const lastSpace = text6.slice(0, limit + 1).search(/\s\S*$/);
7833
8161
  const cut = lastSpace > limit * 0.8 ? lastSpace : limit;
7834
8162
  appendix.push(`## ${label} (continued)
7835
8163
 
7836
- ${text5.slice(cut)}`);
7837
- return `${text5.slice(0, cut)}
8164
+ ${text6.slice(cut)}`);
8165
+ return `${text6.slice(0, cut)}
7838
8166
 
7839
8167
  [${label} truncated; ${tool ? `the rest is stored under "${label} (continued)": use ${tool} findText or offset` : "use the gh escalation commands below for the rest"}]`;
7840
8168
  }
@@ -7880,9 +8208,9 @@ function renderComments(comments, anchor, appendix, tool) {
7880
8208
  const render = (comment, inline) => {
7881
8209
  const body = stringValue(comment.body);
7882
8210
  const label = `comment ${commentId(comment) || comments.indexOf(comment) + 1}`;
7883
- const text5 = inline ? truncateText(body, COMMENT_INLINE_CHARS, label, appendix, tool) : body;
8211
+ const text6 = inline ? truncateText(body, COMMENT_INLINE_CHARS, label, appendix, tool) : body;
7884
8212
  return `- ${authorLogin(comment.author ?? comment.user)} at ${stringValue(comment.createdAt) || stringValue(comment.created_at)}${forced === comment ? " [anchored]" : ""}:
7885
- ${text5.replace(/\n/g, "\n ")}`;
8213
+ ${text6.replace(/\n/g, "\n ")}`;
7886
8214
  };
7887
8215
  const lines = selected.map((comment) => render(comment, true));
7888
8216
  storeOmitted(appendix, "Conversation comments", comments.slice(MAX_INLINE_COMMENTS).filter((comment) => comment !== forced).map((comment) => render(comment, false)));
@@ -7975,8 +8303,8 @@ function renderReviewThreads(comments, anchor, appendix, tool, total, bounded, u
7975
8303
  const render = (comment, inline) => {
7976
8304
  const path = stringValue(comment.path) || "unknown path";
7977
8305
  const line = numberValue(comment.line) ?? numberValue(comment.original_line) ?? numberValue(comment.position) ?? "?";
7978
- const text5 = stringValue(comment.body);
7979
- const body = inline ? truncateText(text5, COMMENT_INLINE_CHARS, `review thread comment ${commentId(comment) || comments.indexOf(comment) + 1}`, appendix, tool) : text5;
8306
+ const text6 = stringValue(comment.body);
8307
+ const body = inline ? truncateText(text6, COMMENT_INLINE_CHARS, `review thread comment ${commentId(comment) || comments.indexOf(comment) + 1}`, appendix, tool) : text6;
7980
8308
  return `- ${path}:${line} \u2014 ${authorLogin(comment.user ?? comment.author)}${forced === comment ? " [anchored]" : ""} (resolution state unknown):
7981
8309
  ${body.replace(/\n/g, "\n ")}`;
7982
8310
  };
@@ -8067,7 +8395,7 @@ function renderGitHubPrIssue(data) {
8067
8395
  async function extractGitHubIssuePr(url, signal, options) {
8068
8396
  const info = parseGitHubIssuePrUrl(url);
8069
8397
  if (!info) return null;
8070
- if (!loadConfig38().enabled) return null;
8398
+ if (!loadConfig39().enabled) return null;
8071
8399
  if (signal?.aborted) return { url, title: "", content: "", error: "Aborted" };
8072
8400
  const retrievalTool = options?.toolNames ? options.toolNames.getSearchContent ?? null : void 0;
8073
8401
  const ghAvailable2 = await checkGhAvailable(signal);
@@ -8091,13 +8419,13 @@ async function extractGitHubIssuePr(url, signal, options) {
8091
8419
  if ("data" in fallback) return renderGitHubPrIssue({ ...fallback.data, retrievalTool });
8092
8420
  return fallback;
8093
8421
  }
8094
- var CONFIG_PATH44, 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, cachedConfig38;
8422
+ 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;
8095
8423
  var init_github_issue_pr = __esm({
8096
8424
  "github-issue-pr.ts"() {
8097
8425
  init_github_api();
8098
8426
  init_ssrf_protection();
8099
8427
  init_utils();
8100
- CONFIG_PATH44 = getWebSearchConfigPath();
8428
+ CONFIG_PATH45 = getWebSearchConfigPath();
8101
8429
  GH_TIMEOUT_MS = 1e4;
8102
8430
  GH_TOTAL_TIMEOUT_MS = 2e4;
8103
8431
  MAX_DOC_CHARS = 15e4;
@@ -8178,20 +8506,20 @@ var init_github_issue_pr = __esm({
8178
8506
  "url"
8179
8507
  ];
8180
8508
  ISSUE_CORE_FIELDS = ["title", "number", "state", "author", "createdAt", "closedAt", "labels", "assignees", "milestone", "comments", "body", "url"];
8181
- cachedConfig38 = null;
8509
+ cachedConfig39 = null;
8182
8510
  }
8183
8511
  });
8184
8512
 
8185
8513
  // feature-config.ts
8186
- import { existsSync as existsSync50, readFileSync as readFileSync51 } from "node:fs";
8514
+ import { existsSync as existsSync51, readFileSync as readFileSync52 } from "node:fs";
8187
8515
  function loadFeatureConfig() {
8188
- if (!existsSync50(CONFIG_PATH45)) return {};
8516
+ if (!existsSync51(CONFIG_PATH46)) return {};
8189
8517
  try {
8190
- const raw = JSON.parse(readFileSync51(CONFIG_PATH45, "utf-8"));
8518
+ const raw = JSON.parse(readFileSync52(CONFIG_PATH46, "utf-8"));
8191
8519
  return raw && typeof raw === "object" ? raw : {};
8192
8520
  } catch (err) {
8193
8521
  const message = err instanceof Error ? err.message : String(err);
8194
- throw new Error(`Failed to parse ${CONFIG_PATH45}: ${message}`);
8522
+ throw new Error(`Failed to parse ${CONFIG_PATH46}: ${message}`);
8195
8523
  }
8196
8524
  }
8197
8525
  function isImageEnabled() {
@@ -8204,17 +8532,17 @@ function canAttachImages() {
8204
8532
  return false;
8205
8533
  }
8206
8534
  }
8207
- var CONFIG_PATH45;
8535
+ var CONFIG_PATH46;
8208
8536
  var init_feature_config = __esm({
8209
8537
  "feature-config.ts"() {
8210
8538
  init_utils();
8211
- CONFIG_PATH45 = getWebSearchConfigPath();
8539
+ CONFIG_PATH46 = getWebSearchConfigPath();
8212
8540
  }
8213
8541
  });
8214
8542
 
8215
8543
  // youtube-extract.ts
8216
8544
  import { execFileSync } from "node:child_process";
8217
- import { existsSync as existsSync51, readFileSync as readFileSync52 } from "node:fs";
8545
+ import { existsSync as existsSync52, readFileSync as readFileSync53 } from "node:fs";
8218
8546
  function errorMessage30(err) {
8219
8547
  return err instanceof Error ? err.message : String(err);
8220
8548
  }
@@ -8234,25 +8562,25 @@ function normalizeEnabled2(value, fallback) {
8234
8562
  return typeof value === "boolean" ? value : fallback;
8235
8563
  }
8236
8564
  function loadYouTubeConfig() {
8237
- if (cachedConfig39) return cachedConfig39;
8238
- if (!existsSync51(CONFIG_PATH46)) {
8239
- cachedConfig39 = { ...defaults };
8240
- return cachedConfig39;
8565
+ if (cachedConfig40) return cachedConfig40;
8566
+ if (!existsSync52(CONFIG_PATH47)) {
8567
+ cachedConfig40 = { ...defaults };
8568
+ return cachedConfig40;
8241
8569
  }
8242
- const rawText = readFileSync52(CONFIG_PATH46, "utf-8");
8570
+ const rawText = readFileSync53(CONFIG_PATH47, "utf-8");
8243
8571
  let raw;
8244
8572
  try {
8245
8573
  raw = JSON.parse(rawText);
8246
8574
  } catch (err) {
8247
8575
  const message = err instanceof Error ? err.message : String(err);
8248
- throw new Error(`Failed to parse ${CONFIG_PATH46}: ${message}`);
8576
+ throw new Error(`Failed to parse ${CONFIG_PATH47}: ${message}`);
8249
8577
  }
8250
8578
  const yt = raw.youtube ?? {};
8251
- cachedConfig39 = {
8579
+ cachedConfig40 = {
8252
8580
  enabled: normalizeEnabled2(yt.enabled, defaults.enabled),
8253
8581
  preferredModel: normalizePreferredModel(yt.preferredModel, defaults.preferredModel)
8254
8582
  };
8255
- return cachedConfig39;
8583
+ return cachedConfig40;
8256
8584
  }
8257
8585
  function isYouTubeURL(url) {
8258
8586
  try {
@@ -8382,7 +8710,7 @@ async function tryGeminiWeb(url, prompt, model, signal, attemptErrors) {
8382
8710
  const cookies = await isGeminiWebAvailable();
8383
8711
  if (!cookies) return null;
8384
8712
  if (signal?.aborted) return null;
8385
- const text5 = await queryWithCookies(prompt, cookies, {
8713
+ const text6 = await queryWithCookies(prompt, cookies, {
8386
8714
  youtubeUrl: url,
8387
8715
  ...model !== "gemini-3.6-flash" ? { model } : {},
8388
8716
  signal,
@@ -8390,8 +8718,8 @@ async function tryGeminiWeb(url, prompt, model, signal, attemptErrors) {
8390
8718
  });
8391
8719
  return {
8392
8720
  url,
8393
- title: extractHeadingTitle(text5) ?? "YouTube Video",
8394
- content: text5,
8721
+ title: extractHeadingTitle(text6) ?? "YouTube Video",
8722
+ content: text6,
8395
8723
  error: null
8396
8724
  };
8397
8725
  } catch (err) {
@@ -8404,15 +8732,15 @@ async function tryGeminiApi(url, prompt, model, signal, attemptErrors) {
8404
8732
  try {
8405
8733
  if (!isGeminiApiAvailableWithVideo()) return null;
8406
8734
  if (signal?.aborted) return null;
8407
- const text5 = await queryGeminiApiWithVideo(prompt, url, {
8735
+ const text6 = await queryGeminiApiWithVideo(prompt, url, {
8408
8736
  model,
8409
8737
  signal,
8410
8738
  timeoutMs: 12e4
8411
8739
  });
8412
8740
  return {
8413
8741
  url,
8414
- title: extractHeadingTitle(text5) ?? "YouTube Video",
8415
- content: text5,
8742
+ title: extractHeadingTitle(text6) ?? "YouTube Video",
8743
+ content: text6,
8416
8744
  error: null
8417
8745
  };
8418
8746
  } catch (err) {
@@ -8444,7 +8772,7 @@ ${answer}
8444
8772
  return null;
8445
8773
  }
8446
8774
  }
8447
- var CONFIG_PATH46, YOUTUBE_PROMPT, YOUTUBE_REGEX, defaults, cachedConfig39;
8775
+ var CONFIG_PATH47, YOUTUBE_PROMPT, YOUTUBE_REGEX, defaults, cachedConfig40;
8448
8776
  var init_youtube_extract = __esm({
8449
8777
  "youtube-extract.ts"() {
8450
8778
  init_activity();
@@ -8454,7 +8782,7 @@ var init_youtube_extract = __esm({
8454
8782
  init_perplexity();
8455
8783
  init_extract();
8456
8784
  init_utils();
8457
- CONFIG_PATH46 = getWebSearchConfigPath();
8785
+ CONFIG_PATH47 = getWebSearchConfigPath();
8458
8786
  YOUTUBE_PROMPT = `Extract the complete content of this YouTube video. Include:
8459
8787
  1. Video title, channel name, and duration
8460
8788
  2. A brief summary (2-3 sentences)
@@ -8464,7 +8792,7 @@ var init_youtube_extract = __esm({
8464
8792
  Format as markdown.`;
8465
8793
  YOUTUBE_REGEX = /(?:(?:www\.|m\.)?youtube\.com\/(?:watch\?.*v=|shorts\/|live\/|embed\/|v\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
8466
8794
  defaults = { enabled: true, preferredModel: "gemini-3.6-flash" };
8467
- cachedConfig39 = null;
8795
+ cachedConfig40 = null;
8468
8796
  }
8469
8797
  });
8470
8798
 
@@ -8526,14 +8854,14 @@ async function extractWithGeminiWeb(url, signal) {
8526
8854
  if (!cookies) return null;
8527
8855
  const activityId = activityMonitor.logStart({ type: "api", query: `gemini_web: ${url}` });
8528
8856
  try {
8529
- const text5 = await queryWithCookies(EXTRACTION_PROMPT + url, cookies, {
8857
+ const text6 = await queryWithCookies(EXTRACTION_PROMPT + url, cookies, {
8530
8858
  signal,
8531
8859
  timeoutMs: 6e4
8532
8860
  });
8533
8861
  activityMonitor.logComplete(activityId, 200);
8534
- if (!text5 || text5.length < 50) return null;
8535
- const title = extractTitleFromContent(text5, url);
8536
- return { url, title, content: text5, error: null };
8862
+ if (!text6 || text6.length < 50) return null;
8863
+ const title = extractTitleFromContent(text6, url);
8864
+ return { url, title, content: text6, error: null };
8537
8865
  } catch (err) {
8538
8866
  if (shouldRethrow2(err)) throw err;
8539
8867
  const message = err instanceof Error ? err.message : String(err);
@@ -8545,8 +8873,8 @@ async function extractWithGeminiWeb(url, signal) {
8545
8873
  return null;
8546
8874
  }
8547
8875
  }
8548
- function extractTitleFromContent(text5, url) {
8549
- return extractHeadingTitle(text5) ?? (new URL(url).pathname.split("/").pop() || url);
8876
+ function extractTitleFromContent(text6, url) {
8877
+ return extractHeadingTitle(text6) ?? (new URL(url).pathname.split("/").pop() || url);
8550
8878
  }
8551
8879
  var EXTRACTION_PROMPT;
8552
8880
  var init_gemini_url_context = __esm({
@@ -8566,26 +8894,26 @@ URL: `;
8566
8894
  });
8567
8895
 
8568
8896
  // crawl4ai.ts
8569
- import { existsSync as existsSync52, readFileSync as readFileSync53 } from "node:fs";
8570
- function loadConfig39() {
8571
- if (cachedConfig40) return cachedConfig40;
8572
- if (!existsSync52(CONFIG_PATH47)) {
8573
- cachedConfig40 = {};
8574
- return cachedConfig40;
8897
+ import { existsSync as existsSync53, readFileSync as readFileSync54 } from "node:fs";
8898
+ function loadConfig40() {
8899
+ if (cachedConfig41) return cachedConfig41;
8900
+ if (!existsSync53(CONFIG_PATH48)) {
8901
+ cachedConfig41 = {};
8902
+ return cachedConfig41;
8575
8903
  }
8576
- const raw = readFileSync53(CONFIG_PATH47, "utf8");
8904
+ const raw = readFileSync54(CONFIG_PATH48, "utf8");
8577
8905
  let parsed;
8578
8906
  try {
8579
8907
  parsed = JSON.parse(raw);
8580
8908
  } catch (err) {
8581
8909
  const message = err instanceof Error ? err.message : String(err);
8582
- throw new Error(`Failed to parse ${CONFIG_PATH47}: ${message}`);
8910
+ throw new Error(`Failed to parse ${CONFIG_PATH48}: ${message}`);
8583
8911
  }
8584
8912
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
8585
- throw new Error(`Invalid config in ${CONFIG_PATH47}: expected a JSON object`);
8913
+ throw new Error(`Invalid config in ${CONFIG_PATH48}: expected a JSON object`);
8586
8914
  }
8587
- cachedConfig40 = parsed;
8588
- return cachedConfig40;
8915
+ cachedConfig41 = parsed;
8916
+ return cachedConfig41;
8589
8917
  }
8590
8918
  function normalizeBaseUrl5(value) {
8591
8919
  if (typeof value !== "string") return null;
@@ -8595,13 +8923,13 @@ function normalizeBaseUrl5(value) {
8595
8923
  try {
8596
8924
  parsed = new URL(trimmed);
8597
8925
  } catch {
8598
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH47}: expected an HTTP or HTTPS URL`);
8926
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: expected an HTTP or HTTPS URL`);
8599
8927
  }
8600
8928
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
8601
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH47}: expected an HTTP or HTTPS URL`);
8929
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: expected an HTTP or HTTPS URL`);
8602
8930
  }
8603
8931
  if (parsed.username || parsed.password) {
8604
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH47}: URL credentials are not allowed`);
8932
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: URL credentials are not allowed`);
8605
8933
  }
8606
8934
  parsed.pathname = parsed.pathname.replace(/\/+$/, "");
8607
8935
  parsed.search = "";
@@ -8609,14 +8937,14 @@ function normalizeBaseUrl5(value) {
8609
8937
  return parsed.toString().replace(/\/+$/, "");
8610
8938
  }
8611
8939
  function getBaseUrl4() {
8612
- return normalizeBaseUrl5(process.env.CRAWL4AI_BASE_URL) ?? normalizeBaseUrl5(loadConfig39().crawl4aiBaseUrl);
8940
+ return normalizeBaseUrl5(process.env.CRAWL4AI_BASE_URL) ?? normalizeBaseUrl5(loadConfig40().crawl4aiBaseUrl);
8613
8941
  }
8614
8942
  function requireBaseUrl4() {
8615
8943
  const baseUrl = getBaseUrl4();
8616
8944
  if (!baseUrl) {
8617
8945
  throw new Error(
8618
8946
  `Crawl4AI base URL not configured. Either:
8619
- 1. Set crawl4aiBaseUrl in ${CONFIG_PATH47}
8947
+ 1. Set crawl4aiBaseUrl in ${CONFIG_PATH48}
8620
8948
  2. Set CRAWL4AI_BASE_URL environment variable`
8621
8949
  );
8622
8950
  }
@@ -8625,7 +8953,7 @@ function requireBaseUrl4() {
8625
8953
  async function getApiToken(signal) {
8626
8954
  return resolveCredential({
8627
8955
  provider: "Crawl4AI",
8628
- configuredValue: loadConfig39().crawl4aiApiToken,
8956
+ configuredValue: loadConfig40().crawl4aiApiToken,
8629
8957
  environmentValue: process.env.CRAWL4AI_API_TOKEN,
8630
8958
  signal
8631
8959
  });
@@ -8682,8 +9010,8 @@ async function extractWithCrawl4ai(url, signal, options) {
8682
9010
  }
8683
9011
  });
8684
9012
  if (!response.ok) {
8685
- const text5 = await response.text().catch(() => "");
8686
- throw new Error(`Crawl4AI md error ${response.status}: ${redactCredential(text5, token).slice(0, 300)}`);
9013
+ const text6 = await response.text().catch(() => "");
9014
+ throw new Error(`Crawl4AI md error ${response.status}: ${redactCredential(text6, token).slice(0, 300)}`);
8687
9015
  }
8688
9016
  let data;
8689
9017
  try {
@@ -8715,45 +9043,45 @@ async function extractWithCrawl4ai(url, signal, options) {
8715
9043
  throw err;
8716
9044
  }
8717
9045
  }
8718
- var CONFIG_PATH47, EXTRACT_TIMEOUT_MS2, MARKDOWN_FILTER, cachedConfig40;
9046
+ var CONFIG_PATH48, EXTRACT_TIMEOUT_MS2, MARKDOWN_FILTER, cachedConfig41;
8719
9047
  var init_crawl4ai = __esm({
8720
9048
  "crawl4ai.ts"() {
8721
9049
  init_activity();
8722
9050
  init_credential_source();
8723
9051
  init_ssrf_protection();
8724
9052
  init_utils();
8725
- CONFIG_PATH47 = getWebSearchConfigPath();
9053
+ CONFIG_PATH48 = getWebSearchConfigPath();
8726
9054
  EXTRACT_TIMEOUT_MS2 = 6e4;
8727
9055
  MARKDOWN_FILTER = "fit";
8728
- cachedConfig40 = null;
9056
+ cachedConfig41 = null;
8729
9057
  }
8730
9058
  });
8731
9059
 
8732
9060
  // brightdata-unlocker.ts
8733
- import { existsSync as existsSync53, readFileSync as readFileSync54 } from "node:fs";
9061
+ import { existsSync as existsSync54, readFileSync as readFileSync55 } from "node:fs";
8734
9062
  function parseFailureDetail(err) {
8735
9063
  const message = err instanceof Error ? err.message : String(err);
8736
9064
  const position = message.match(/at position \d+(?: \(line \d+ column \d+\))?/);
8737
9065
  return position ? `invalid JSON ${position[0]}` : "invalid JSON";
8738
9066
  }
8739
- function loadConfig40() {
8740
- if (cachedConfig41) return cachedConfig41;
8741
- if (!existsSync53(CONFIG_PATH48)) {
8742
- cachedConfig41 = {};
8743
- return cachedConfig41;
9067
+ function loadConfig41() {
9068
+ if (cachedConfig42) return cachedConfig42;
9069
+ if (!existsSync54(CONFIG_PATH49)) {
9070
+ cachedConfig42 = {};
9071
+ return cachedConfig42;
8744
9072
  }
8745
- const raw = readFileSync54(CONFIG_PATH48, "utf8");
9073
+ const raw = readFileSync55(CONFIG_PATH49, "utf8");
8746
9074
  let parsed;
8747
9075
  try {
8748
9076
  parsed = JSON.parse(raw);
8749
9077
  } catch (err) {
8750
- throw new Error(`Failed to parse ${CONFIG_PATH48}: ${parseFailureDetail(err)}`);
9078
+ throw new Error(`Failed to parse ${CONFIG_PATH49}: ${parseFailureDetail(err)}`);
8751
9079
  }
8752
9080
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
8753
- throw new Error(`Invalid config in ${CONFIG_PATH48}: expected a JSON object`);
9081
+ throw new Error(`Invalid config in ${CONFIG_PATH49}: expected a JSON object`);
8754
9082
  }
8755
- cachedConfig41 = parsed;
8756
- return cachedConfig41;
9083
+ cachedConfig42 = parsed;
9084
+ return cachedConfig42;
8757
9085
  }
8758
9086
  function normalizeZone2(value) {
8759
9087
  if (typeof value !== "string") return null;
@@ -8764,8 +9092,8 @@ function normalizeZone2(value) {
8764
9092
  function zoneSetting() {
8765
9093
  const fromEnv = process.env.BRIGHTDATA_UNLOCKER_ZONE;
8766
9094
  if (typeof fromEnv === "string" && fromEnv.trim()) return { raw: fromEnv.trim(), label: "BRIGHTDATA_UNLOCKER_ZONE" };
8767
- const configured = loadConfig40().brightdataUnlockerZone;
8768
- if (typeof configured === "string" && configured.trim()) return { raw: configured.trim(), label: `brightdataUnlockerZone in ${CONFIG_PATH48}` };
9095
+ const configured = loadConfig41().brightdataUnlockerZone;
9096
+ if (typeof configured === "string" && configured.trim()) return { raw: configured.trim(), label: `brightdataUnlockerZone in ${CONFIG_PATH49}` };
8769
9097
  return null;
8770
9098
  }
8771
9099
  function getZone() {
@@ -8783,7 +9111,7 @@ function requireZone() {
8783
9111
  }
8784
9112
  throw new Error(
8785
9113
  `Bright Data Web Unlocker zone not configured. Either:
8786
- 1. Set brightdataUnlockerZone in ${CONFIG_PATH48}
9114
+ 1. Set brightdataUnlockerZone in ${CONFIG_PATH49}
8787
9115
  2. Set BRIGHTDATA_UNLOCKER_ZONE environment variable
8788
9116
  The zone must be of type "unblocker"; a SERP zone will not serve Web Unlocker requests.`
8789
9117
  );
@@ -8791,14 +9119,14 @@ The zone must be of type "unblocker"; a SERP zone will not serve Web Unlocker re
8791
9119
  async function getApiKey27(signal) {
8792
9120
  const apiKey = await resolveCredential({
8793
9121
  provider: "Bright Data",
8794
- configuredValue: loadConfig40().brightdataApiKey,
9122
+ configuredValue: loadConfig41().brightdataApiKey,
8795
9123
  environmentValue: process.env.BRIGHTDATA_API_KEY,
8796
9124
  signal
8797
9125
  });
8798
9126
  if (!apiKey) {
8799
9127
  throw new Error(
8800
9128
  `Bright Data API key not found. Either:
8801
- 1. Create ${CONFIG_PATH48} with { "brightdataApiKey": "your-key" }
9129
+ 1. Create ${CONFIG_PATH49} with { "brightdataApiKey": "your-key" }
8802
9130
  2. Set BRIGHTDATA_API_KEY environment variable
8803
9131
  Get a key at https://brightdata.com/cp/setting/users`
8804
9132
  );
@@ -8862,7 +9190,7 @@ async function brightDataRequest(url, zone, signal, options) {
8862
9190
  };
8863
9191
  const activityId = activityMonitor.logStart({ type: "fetch", url });
8864
9192
  try {
8865
- const response = await fetchBrightDataApi(BRIGHTDATA_REQUEST_URL, {
9193
+ const response = await fetchBrightDataApi(resolveProviderApiUrl("brightdata", BRIGHTDATA_REQUEST_URL, loadConfig41().brightdataBaseUrl), {
8866
9194
  method: "POST",
8867
9195
  headers,
8868
9196
  body: JSON.stringify(unlockerBody(url, zone)),
@@ -8872,9 +9200,9 @@ async function brightDataRequest(url, zone, signal, options) {
8872
9200
  const errorText = await response.text().catch(() => "");
8873
9201
  throw new Error(`Bright Data Web Unlocker error ${response.status}: ${redactCredential(errorText, apiKey).slice(0, 300)}`);
8874
9202
  }
8875
- const text5 = await response.text();
9203
+ const text6 = await response.text();
8876
9204
  activityMonitor.logComplete(activityId, response.status);
8877
- return text5;
9205
+ return text6;
8878
9206
  } catch (err) {
8879
9207
  const message = errorMessage32(err);
8880
9208
  const redactedMessage = redactCredential(message, apiKey);
@@ -8886,8 +9214,8 @@ async function brightDataRequest(url, zone, signal, options) {
8886
9214
  throw redactedError;
8887
9215
  }
8888
9216
  }
8889
- function headingTitle(text5) {
8890
- const match = text5.match(/^#{1,2}\s+(.+)/m);
9217
+ function headingTitle(text6) {
9218
+ const match = text6.match(/^#{1,2}\s+(.+)/m);
8891
9219
  if (!match) return "";
8892
9220
  return match[1].replace(/\*+/g, "").trim();
8893
9221
  }
@@ -8895,7 +9223,7 @@ function isBrightDataUnlockerAvailable() {
8895
9223
  if (getZone() === null) return false;
8896
9224
  return hasCredentialSource({
8897
9225
  provider: "Bright Data",
8898
- configuredValue: loadConfig40().brightdataApiKey,
9226
+ configuredValue: loadConfig41().brightdataApiKey,
8899
9227
  environmentValue: process.env.BRIGHTDATA_API_KEY
8900
9228
  });
8901
9229
  }
@@ -8907,26 +9235,26 @@ async function extractWithBrightDataUnlocker(url, signal, options) {
8907
9235
  if (!content) return null;
8908
9236
  return { url, title: headingTitle(content), content, error: null };
8909
9237
  }
8910
- var CONFIG_PATH48, BRIGHTDATA_REQUEST_URL, EXTRACT_TIMEOUT_MS3, DEFAULT_MAX_REDIRECTS3, REDIRECT_STATUSES3, ZONE_PATTERN2, cachedConfig41;
9238
+ var CONFIG_PATH49, BRIGHTDATA_REQUEST_URL, EXTRACT_TIMEOUT_MS3, DEFAULT_MAX_REDIRECTS3, REDIRECT_STATUSES3, ZONE_PATTERN2, cachedConfig42;
8911
9239
  var init_brightdata_unlocker = __esm({
8912
9240
  "brightdata-unlocker.ts"() {
8913
9241
  init_activity();
8914
9242
  init_credential_source();
8915
9243
  init_ssrf_protection();
8916
9244
  init_utils();
8917
- CONFIG_PATH48 = getWebSearchConfigPath();
9245
+ CONFIG_PATH49 = getWebSearchConfigPath();
8918
9246
  BRIGHTDATA_REQUEST_URL = "https://api.brightdata.com/request";
8919
9247
  EXTRACT_TIMEOUT_MS3 = 6e4;
8920
9248
  DEFAULT_MAX_REDIRECTS3 = 5;
8921
9249
  REDIRECT_STATUSES3 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
8922
9250
  ZONE_PATTERN2 = /^[a-z0-9_-]+$/i;
8923
- cachedConfig41 = null;
9251
+ cachedConfig42 = null;
8924
9252
  }
8925
9253
  });
8926
9254
 
8927
9255
  // video-extract.ts
8928
9256
  import { execFileSync as execFileSync2 } from "node:child_process";
8929
- import { existsSync as existsSync54, readFileSync as readFileSync55, readdirSync as readdirSync4, statSync as statSync3 } from "node:fs";
9257
+ import { existsSync as existsSync55, readFileSync as readFileSync56, readdirSync as readdirSync4, statSync as statSync3 } from "node:fs";
8930
9258
  import { readFile as readFile2 } from "node:fs/promises";
8931
9259
  import { resolve, extname as extname2, basename as basename4, join as join7, dirname as dirname2 } from "node:path";
8932
9260
  function shouldRethrow3(err) {
@@ -8947,17 +9275,17 @@ function normalizeMaxSizeMB(value, fallback) {
8947
9275
  }
8948
9276
  function loadVideoConfig() {
8949
9277
  if (cachedVideoConfig) return cachedVideoConfig;
8950
- if (!existsSync54(CONFIG_PATH49)) {
9278
+ if (!existsSync55(CONFIG_PATH50)) {
8951
9279
  cachedVideoConfig = { ...VIDEO_CONFIG_DEFAULTS };
8952
9280
  return cachedVideoConfig;
8953
9281
  }
8954
- const rawText = readFileSync55(CONFIG_PATH49, "utf-8");
9282
+ const rawText = readFileSync56(CONFIG_PATH50, "utf-8");
8955
9283
  let raw;
8956
9284
  try {
8957
9285
  raw = JSON.parse(rawText);
8958
9286
  } catch (err) {
8959
9287
  const message = err instanceof Error ? err.message : String(err);
8960
- throw new Error(`Failed to parse ${CONFIG_PATH49}: ${message}`);
9288
+ throw new Error(`Failed to parse ${CONFIG_PATH50}: ${message}`);
8961
9289
  }
8962
9290
  const v = raw.video ?? {};
8963
9291
  cachedVideoConfig = {
@@ -9003,10 +9331,10 @@ function isVideoFile(input) {
9003
9331
  }
9004
9332
  function resolveFilePath(filePath) {
9005
9333
  const absolutePath = resolve(filePath);
9006
- if (existsSync54(absolutePath)) return absolutePath;
9334
+ if (existsSync55(absolutePath)) return absolutePath;
9007
9335
  const dir = dirname2(absolutePath);
9008
9336
  const base = basename4(absolutePath);
9009
- if (!existsSync54(dir)) return null;
9337
+ if (!existsSync55(dir)) return null;
9010
9338
  try {
9011
9339
  const normalizedBase = normalizeSpaces(base);
9012
9340
  const match = readdirSync4(dir).find((f) => normalizeSpaces(f) === normalizedBase);
@@ -9098,7 +9426,7 @@ async function tryVideoGeminiWeb(info, prompt, model, signal) {
9098
9426
  const cookies = await isGeminiWebAvailable();
9099
9427
  if (!cookies) return null;
9100
9428
  if (signal?.aborted) return null;
9101
- const text5 = await queryWithCookies(prompt, cookies, {
9429
+ const text6 = await queryWithCookies(prompt, cookies, {
9102
9430
  files: [{ path: info.absolutePath, mimeType: info.mimeType }],
9103
9431
  ...model !== "gemini-3.6-flash" ? { model } : {},
9104
9432
  signal,
@@ -9106,8 +9434,8 @@ async function tryVideoGeminiWeb(info, prompt, model, signal) {
9106
9434
  });
9107
9435
  return {
9108
9436
  url: info.absolutePath,
9109
- title: extractVideoTitle(text5, info.absolutePath),
9110
- content: text5,
9437
+ title: extractVideoTitle(text6, info.absolutePath),
9438
+ content: text6,
9111
9439
  error: null
9112
9440
  };
9113
9441
  } catch (err) {
@@ -9124,7 +9452,7 @@ async function tryVideoGeminiApi(info, prompt, model, signal) {
9124
9452
  const uploaded = await uploadToFilesApi(info, apiKey, signal);
9125
9453
  fileName = uploaded.name;
9126
9454
  await pollFileState(fileName, apiKey, signal, 12e4);
9127
- const text5 = await queryGeminiApiWithVideo(prompt, uploaded.uri, {
9455
+ const text6 = await queryGeminiApiWithVideo(prompt, uploaded.uri, {
9128
9456
  apiKey,
9129
9457
  model,
9130
9458
  mimeType: info.mimeType,
@@ -9133,8 +9461,8 @@ async function tryVideoGeminiApi(info, prompt, model, signal) {
9133
9461
  });
9134
9462
  return {
9135
9463
  url: info.absolutePath,
9136
- title: extractVideoTitle(text5, info.absolutePath),
9137
- content: text5,
9464
+ title: extractVideoTitle(text6, info.absolutePath),
9465
+ content: text6,
9138
9466
  error: null
9139
9467
  };
9140
9468
  } catch (err) {
@@ -9159,8 +9487,8 @@ async function uploadToFilesApi(info, apiKey, signal) {
9159
9487
  signal
9160
9488
  }, apiKey);
9161
9489
  if (!initRes.ok) {
9162
- const text5 = redactGeminiApiResponse(initRes, await initRes.text(), apiKey);
9163
- throw new Error(`File upload init failed: ${initRes.status} (${text5.slice(0, 200)})`);
9490
+ const text6 = redactGeminiApiResponse(initRes, await initRes.text(), apiKey);
9491
+ throw new Error(`File upload init failed: ${initRes.status} (${text6.slice(0, 200)})`);
9164
9492
  }
9165
9493
  const uploadUrl = initRes.headers.get("x-goog-upload-url");
9166
9494
  if (!uploadUrl) throw new Error("No upload URL in response headers");
@@ -9177,8 +9505,8 @@ async function uploadToFilesApi(info, apiKey, signal) {
9177
9505
  signal
9178
9506
  }, apiKey);
9179
9507
  if (!uploadRes.ok) {
9180
- const text5 = redactGeminiApiResponse(uploadRes, await uploadRes.text(), apiKey);
9181
- throw new Error(`File upload failed: ${uploadRes.status} (${text5.slice(0, 200)})`);
9508
+ const text6 = redactGeminiApiResponse(uploadRes, await uploadRes.text(), apiKey);
9509
+ throw new Error(`File upload failed: ${uploadRes.status} (${text6.slice(0, 200)})`);
9182
9510
  }
9183
9511
  const result = await uploadRes.json();
9184
9512
  return result.file;
@@ -9202,10 +9530,10 @@ function deleteGeminiFile(fileName, apiKey) {
9202
9530
  console.error(`Failed to delete Gemini file ${fileName}: ${message}`);
9203
9531
  });
9204
9532
  }
9205
- function extractVideoTitle(text5, filePath) {
9206
- return extractHeadingTitle(text5) ?? basename4(filePath, extname2(filePath));
9533
+ function extractVideoTitle(text6, filePath) {
9534
+ return extractHeadingTitle(text6) ?? basename4(filePath, extname2(filePath));
9207
9535
  }
9208
- var CONFIG_PATH49, DEFAULT_VIDEO_PROMPT, VIDEO_EXTENSIONS, VIDEO_CONFIG_DEFAULTS, cachedVideoConfig;
9536
+ var CONFIG_PATH50, DEFAULT_VIDEO_PROMPT, VIDEO_EXTENSIONS, VIDEO_CONFIG_DEFAULTS, cachedVideoConfig;
9209
9537
  var init_video_extract = __esm({
9210
9538
  "video-extract.ts"() {
9211
9539
  init_activity();
@@ -9214,7 +9542,7 @@ var init_video_extract = __esm({
9214
9542
  init_gemini_api();
9215
9543
  init_extract();
9216
9544
  init_utils();
9217
- CONFIG_PATH49 = getWebSearchConfigPath();
9545
+ CONFIG_PATH50 = getWebSearchConfigPath();
9218
9546
  DEFAULT_VIDEO_PROMPT = `Extract the complete content of this video. Include:
9219
9547
  1. Video title (infer from content if not explicit), duration
9220
9548
  2. A brief summary (2-3 sentences)
@@ -9404,33 +9732,33 @@ function sha256Bytes(value) {
9404
9732
  function asciiLowerCode(code) {
9405
9733
  return code >= 65 && code <= 90 ? code + 32 : code;
9406
9734
  }
9407
- function matchesDataScheme(text5, index) {
9408
- return index + 5 <= text5.length && asciiLowerCode(text5.charCodeAt(index)) === 100 && asciiLowerCode(text5.charCodeAt(index + 1)) === 97 && asciiLowerCode(text5.charCodeAt(index + 2)) === 116 && asciiLowerCode(text5.charCodeAt(index + 3)) === 97 && text5.charCodeAt(index + 4) === 58;
9735
+ function matchesDataScheme(text6, index) {
9736
+ return index + 5 <= text6.length && asciiLowerCode(text6.charCodeAt(index)) === 100 && asciiLowerCode(text6.charCodeAt(index + 1)) === 97 && asciiLowerCode(text6.charCodeAt(index + 2)) === 116 && asciiLowerCode(text6.charCodeAt(index + 3)) === 97 && text6.charCodeAt(index + 4) === 58;
9409
9737
  }
9410
- function isSchemeBoundary(text5, index) {
9738
+ function isSchemeBoundary(text6, index) {
9411
9739
  if (index === 0) return true;
9412
- const code = text5.charCodeAt(index - 1);
9740
+ const code = text6.charCodeAt(index - 1);
9413
9741
  const alphaNumeric = code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
9414
9742
  return !alphaNumeric && code !== 43 && code !== 45 && code !== 46;
9415
9743
  }
9416
- function findNextDataScheme(text5, from) {
9417
- for (let i = from; i + 5 <= text5.length; i++) {
9418
- if (matchesDataScheme(text5, i) && isSchemeBoundary(text5, i)) return i;
9744
+ function findNextDataScheme(text6, from) {
9745
+ for (let i = from; i + 5 <= text6.length; i++) {
9746
+ if (matchesDataScheme(text6, i) && isSchemeBoundary(text6, i)) return i;
9419
9747
  }
9420
9748
  return -1;
9421
9749
  }
9422
- function dataUriEnclosure(text5, start) {
9750
+ function dataUriEnclosure(text6, start) {
9423
9751
  if (start === 0) return null;
9424
9752
  const immediateIndex = start - 1;
9425
- const immediate = text5[immediateIndex];
9753
+ const immediate = text6[immediateIndex];
9426
9754
  if (immediate === '"' || immediate === "'" || immediate === "`") {
9427
- const beforeQuote = immediateIndex > 0 ? text5[immediateIndex - 1] : "";
9755
+ const beforeQuote = immediateIndex > 0 ? text6[immediateIndex - 1] : "";
9428
9756
  const likelyOpeningQuote = immediateIndex === 0 || beforeQuote === "=" || beforeQuote === "(" || beforeQuote === "[" || beforeQuote === "{" || beforeQuote === ":" || beforeQuote === "," || /\s/.test(beforeQuote);
9429
9757
  if (likelyOpeningQuote) return { kind: "quote", close: immediate };
9430
9758
  }
9431
9759
  let openerIndex = immediateIndex;
9432
- while (openerIndex >= 0 && (text5[openerIndex] === " " || text5[openerIndex] === " ")) openerIndex--;
9433
- const opener = text5[openerIndex];
9760
+ while (openerIndex >= 0 && (text6[openerIndex] === " " || text6[openerIndex] === " ")) openerIndex--;
9761
+ const opener = text6[openerIndex];
9434
9762
  if (opener === "(") return { kind: "parentheses" };
9435
9763
  if (opener === "<") return { kind: "angle" };
9436
9764
  return null;
@@ -9439,13 +9767,13 @@ function isBareDataUriTerminator(ch) {
9439
9767
  const code = ch.charCodeAt(0);
9440
9768
  return code <= 32 || code === 127 || ch === '"' || ch === "`" || ch === "<" || ch === ">";
9441
9769
  }
9442
- function scanDataUriCandidate(text5, start) {
9443
- const enclosure = dataUriEnclosure(text5, start);
9770
+ function scanDataUriCandidate(text6, start) {
9771
+ const enclosure = dataUriEnclosure(text6, start);
9444
9772
  let comma = -1;
9445
9773
  let depth = enclosure?.kind === "parentheses" ? 1 : 0;
9446
9774
  let index = start + 5;
9447
- for (; index < text5.length; index++) {
9448
- const ch = text5[index];
9775
+ for (; index < text6.length; index++) {
9776
+ const ch = text6[index];
9449
9777
  if (enclosure?.kind === "quote") {
9450
9778
  if (ch === enclosure.close) break;
9451
9779
  } else if (enclosure?.kind === "parentheses") {
@@ -9464,16 +9792,16 @@ function scanDataUriCandidate(text5, start) {
9464
9792
  }
9465
9793
  return { end: index, comma, enclosure };
9466
9794
  }
9467
- function headerEndsWithBase64(text5, headerStart, comma) {
9795
+ function headerEndsWithBase64(text6, headerStart, comma) {
9468
9796
  let end = comma;
9469
- while (end > headerStart && (text5[end - 1] === " " || text5[end - 1] === " ")) end--;
9797
+ while (end > headerStart && (text6[end - 1] === " " || text6[end - 1] === " ")) end--;
9470
9798
  const token = "base64";
9471
9799
  if (end - headerStart < token.length + 1) return false;
9472
9800
  const tokenStart = end - token.length;
9473
9801
  for (let i = 0; i < token.length; i++) {
9474
- if (asciiLowerCode(text5.charCodeAt(tokenStart + i)) !== token.charCodeAt(i)) return false;
9802
+ if (asciiLowerCode(text6.charCodeAt(tokenStart + i)) !== token.charCodeAt(i)) return false;
9475
9803
  }
9476
- return tokenStart > headerStart && text5[tokenStart - 1] === ";";
9804
+ return tokenStart > headerStart && text6[tokenStart - 1] === ";";
9477
9805
  }
9478
9806
  function isMimeTokenChar(code) {
9479
9807
  if (code < 33 || code > 126) return false;
@@ -9512,14 +9840,14 @@ function isMimeTokenChar(code) {
9512
9840
  return true;
9513
9841
  }
9514
9842
  }
9515
- function normalizeMimeType(text5, headerStart, comma) {
9843
+ function normalizeMimeType(text6, headerStart, comma) {
9516
9844
  let end = headerStart;
9517
- while (end < comma && text5[end] !== ";") end++;
9845
+ while (end < comma && text6[end] !== ";") end++;
9518
9846
  if (end === headerStart) return "text/plain";
9519
9847
  if (end - headerStart > MAX_MIME_CHARS) return "application/octet-stream";
9520
9848
  let slashCount = 0;
9521
9849
  for (let i = headerStart; i < end; i++) {
9522
- const code = text5.charCodeAt(i);
9850
+ const code = text6.charCodeAt(i);
9523
9851
  if (code === 47) {
9524
9852
  slashCount++;
9525
9853
  if (i === headerStart || i === end - 1) return "application/octet-stream";
@@ -9528,7 +9856,7 @@ function normalizeMimeType(text5, headerStart, comma) {
9528
9856
  if (!isMimeTokenChar(code)) return "application/octet-stream";
9529
9857
  }
9530
9858
  if (slashCount !== 1) return "application/octet-stream";
9531
- return text5.slice(headerStart, end).toLowerCase();
9859
+ return text6.slice(headerStart, end).toLowerCase();
9532
9860
  }
9533
9861
  function hexValue(code) {
9534
9862
  if (code >= 48 && code <= 57) return code - 48;
@@ -9602,15 +9930,15 @@ function buildDataUriMarker(omission) {
9602
9930
  const decodeError = omission.decodeError ? `; decodeError=${omission.decodeError}` : "";
9603
9931
  return `[pi-web-access inline data URI omitted; ordinal=${omission.ordinal}; source=${omission.sourcePath}; mime=${omission.mimeType}; encoding=${omission.encoding}; encodedBytes=${omission.encodedBytes}; decodedBytes=${decoded}${decodeError}; sha256=${omission.sha256}; digestBasis=${omission.digestBasis}; retrieval=not-retained]`;
9604
9932
  }
9605
- function sanitizeTextInternal(text5, sourcePath, state) {
9933
+ function sanitizeTextInternal(text6, sourcePath, state) {
9606
9934
  let scanFrom = 0;
9607
9935
  let retainedFrom = 0;
9608
9936
  let outputLength = 0;
9609
9937
  const pieces = [];
9610
- while (scanFrom < text5.length) {
9611
- const start = findNextDataScheme(text5, scanFrom);
9938
+ while (scanFrom < text6.length) {
9939
+ const start = findNextDataScheme(text6, scanFrom);
9612
9940
  if (start < 0) break;
9613
- const candidate = scanDataUriCandidate(text5, start);
9941
+ const candidate = scanDataUriCandidate(text6, start);
9614
9942
  const end = candidate.end;
9615
9943
  const headerStart = start + 5;
9616
9944
  const missingComma = candidate.comma < 0;
@@ -9620,9 +9948,9 @@ function sanitizeTextInternal(text5, sourcePath, state) {
9620
9948
  }
9621
9949
  const headerEnd = missingComma ? end : candidate.comma;
9622
9950
  const headerLength = headerEnd - headerStart;
9623
- const encoding = headerEndsWithBase64(text5, headerStart, headerEnd) ? "base64" : "percent-encoded";
9624
- const mimeType = normalizeMimeType(text5, headerStart, headerEnd);
9625
- const payload = missingComma ? text5.slice(headerStart, end) : text5.slice(candidate.comma + 1, end);
9951
+ const encoding = headerEndsWithBase64(text6, headerStart, headerEnd) ? "base64" : "percent-encoded";
9952
+ const mimeType = normalizeMimeType(text6, headerStart, headerEnd);
9953
+ const payload = missingComma ? text6.slice(headerStart, end) : text6.slice(candidate.comma + 1, end);
9626
9954
  const encodedBytes = Buffer3.byteLength(payload, "utf8");
9627
9955
  let decodedBytes = null;
9628
9956
  let decodeError;
@@ -9658,7 +9986,7 @@ function sanitizeTextInternal(text5, sourcePath, state) {
9658
9986
  retrieval: "not-retained"
9659
9987
  };
9660
9988
  const marker = buildDataUriMarker(omission);
9661
- const prefix = text5.slice(retainedFrom, start);
9989
+ const prefix = text6.slice(retainedFrom, start);
9662
9990
  pieces.push(prefix, marker);
9663
9991
  outputLength += prefix.length;
9664
9992
  const markerStart = outputLength;
@@ -9667,13 +9995,13 @@ function sanitizeTextInternal(text5, sourcePath, state) {
9667
9995
  retainedFrom = end;
9668
9996
  scanFrom = end;
9669
9997
  }
9670
- if (state.omissions.length === 0 && retainedFrom === 0) return text5;
9671
- pieces.push(text5.slice(retainedFrom));
9998
+ if (state.omissions.length === 0 && retainedFrom === 0) return text6;
9999
+ pieces.push(text6.slice(retainedFrom));
9672
10000
  return pieces.join("");
9673
10001
  }
9674
- function sanitizeInlineDataUris(text5, sourcePath) {
10002
+ function sanitizeInlineDataUris(text6, sourcePath) {
9675
10003
  const state = { nextOrdinal: 1, omissions: [] };
9676
- const sanitized = sanitizeTextInternal(text5, sourcePath, state);
10004
+ const sanitized = sanitizeTextInternal(text6, sourcePath, state);
9677
10005
  return {
9678
10006
  text: sanitized,
9679
10007
  omissions: state.omissions.map(({ markerStart: _start, markerEnd: _end, ...omission }) => omission)
@@ -9699,13 +10027,13 @@ __export(extract_exports, {
9699
10027
  readPDFResponseBuffer: () => readPDFResponseBuffer,
9700
10028
  resolveFetchTimeoutMs: () => resolveFetchTimeoutMs
9701
10029
  });
9702
- import { existsSync as existsSync55, readFileSync as readFileSync56 } from "node:fs";
10030
+ import { existsSync as existsSync56, readFileSync as readFileSync57 } from "node:fs";
9703
10031
  import pLimit from "p-limit";
9704
10032
  function loadFetchTimeoutMs() {
9705
- if (!existsSync55(WEB_SEARCH_CONFIG_PATH3)) return DEFAULT_TIMEOUT_MS4;
10033
+ if (!existsSync56(WEB_SEARCH_CONFIG_PATH3)) return DEFAULT_TIMEOUT_MS4;
9706
10034
  let raw;
9707
10035
  try {
9708
- raw = JSON.parse(readFileSync56(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
10036
+ raw = JSON.parse(readFileSync57(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
9709
10037
  } catch (err) {
9710
10038
  const message = err instanceof Error ? err.message : String(err);
9711
10039
  throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH3}: ${message}`);
@@ -9733,10 +10061,10 @@ function isDefuddleConsoleError(args) {
9733
10061
  const prefix = args[0];
9734
10062
  return prefix === "Defuddle" || typeof prefix === "string" && /^Defuddle(?:\s|:)/.test(prefix);
9735
10063
  }
9736
- async function extractWithDefuddle(text5, url) {
10064
+ async function extractWithDefuddle(text6, url) {
9737
10065
  const { Defuddle } = await import("defuddle/node");
9738
10066
  const { parseHTML } = await import("linkedom");
9739
- const { document } = parseHTML(text5);
10067
+ const { document } = parseHTML(text6);
9740
10068
  Object.defineProperty(document, "location", {
9741
10069
  value: new URL(url),
9742
10070
  configurable: true
@@ -9844,12 +10172,12 @@ async function fetchAuthenticatedRemoteUrl(url, init, validationOptions, profile
9844
10172
  throw new Error(`Too many redirects fetching ${current.toString()}`);
9845
10173
  }
9846
10174
  function loadFetchRouting() {
9847
- if (!existsSync55(WEB_SEARCH_CONFIG_PATH3)) {
10175
+ if (!existsSync56(WEB_SEARCH_CONFIG_PATH3)) {
9848
10176
  return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
9849
10177
  }
9850
10178
  let raw;
9851
10179
  try {
9852
- const parsed = JSON.parse(readFileSync56(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
10180
+ const parsed = JSON.parse(readFileSync57(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
9853
10181
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
9854
10182
  throw new Error("expected a JSON object");
9855
10183
  }
@@ -10329,6 +10657,7 @@ async function extractContent(url, signal, options) {
10329
10657
  let parallelError = null;
10330
10658
  let parallelMcpError = null;
10331
10659
  let brightdataError = null;
10660
+ let deepseekError = null;
10332
10661
  if (remoteUrl && providerOrder[0] !== "http") {
10333
10662
  const httpGateResult = await runHttpProvider();
10334
10663
  if (httpGateResult) return httpGateResult;
@@ -10510,6 +10839,22 @@ async function extractContent(url, signal, options) {
10510
10839
  }
10511
10840
  if (geminiResult) return withDeclaredLinks(geminiResult);
10512
10841
  }
10842
+ if (provider === "deepseek") {
10843
+ try {
10844
+ if (isDeepSeekAvailable()) {
10845
+ const deepseekResult = await extractWithDeepSeek(url, signal, {
10846
+ timeoutMs: options?.timeoutMs,
10847
+ ...options?.lookup ? { lookup: options.lookup } : {}
10848
+ });
10849
+ if (deepseekResult) return withDeclaredLinks(deepseekResult);
10850
+ }
10851
+ } catch (err) {
10852
+ if (isAbortError6(err)) return abortedResult(url);
10853
+ deepseekError = errorMessage33(err);
10854
+ if (isConfigParseError(err)) return parseErrorResult(deepseekError);
10855
+ }
10856
+ continue;
10857
+ }
10513
10858
  }
10514
10859
  if (signal?.aborted) return abortedResult(url);
10515
10860
  const finalHttpResult = httpResult;
@@ -10532,6 +10877,7 @@ async function extractContent(url, signal, options) {
10532
10877
  ...parallelError ? [`Parallel fallback failed: ${parallelError}`] : [],
10533
10878
  ...parallelMcpError ? [`Parallel MCP fallback failed: ${parallelMcpError}`] : [],
10534
10879
  ...brightdataError ? [`Bright Data fallback failed: ${brightdataError}`] : [],
10880
+ ...deepseekError ? [`DeepSeek fallback failed: ${deepseekError}`] : [],
10535
10881
  "",
10536
10882
  "Fallback options:",
10537
10883
  ...jinaHint ? [jinaHint] : [],
@@ -10544,23 +10890,28 @@ async function extractContent(url, signal, options) {
10544
10890
  ` \u2022 Set ollamaApiKey in ${WEB_SEARCH_CONFIG_PATH3} or OLLAMA_API_KEY`,
10545
10891
  ` \u2022 Set parallelApiKey in ${WEB_SEARCH_CONFIG_PATH3} or PARALLEL_API_KEY`,
10546
10892
  ` \u2022 Set brightdataApiKey and brightdataUnlockerZone in ${WEB_SEARCH_CONFIG_PATH3} or BRIGHTDATA_API_KEY and BRIGHTDATA_UNLOCKER_ZONE`,
10893
+ ` \u2022 Set deepseekApiKey in ${WEB_SEARCH_CONFIG_PATH3} or DEEPSEEK_API_KEY and add "deepseek" to fetchRouting.providers`,
10547
10894
  ` \u2022 Set GEMINI_API_KEY in ${WEB_SEARCH_CONFIG_PATH3}`,
10548
10895
  " \u2022 Sign into gemini.google.com in Chrome",
10549
10896
  ...searchToolName ? [` \u2022 Use ${searchToolName} to find content about this topic`] : []
10550
10897
  ].join("\n");
10551
10898
  return { ...finalHttpResult ?? { url, title: "", content: "", error: null }, error: guidance };
10552
10899
  }
10553
- function isCloudflareChallenge(response, text5, isHTML) {
10900
+ function isCloudflareChallenge(response, text6, isHTML) {
10554
10901
  if (response.status !== 200) return false;
10555
10902
  if (response.headers.get("cf-mitigated") === "challenge") return true;
10556
- return isHTML && /<title>\s*Just a moment\.\.\.\s*<\/title>/i.test(text5) && text5.includes("window._cf_chl_opt") && text5.includes("/cdn-cgi/challenge-platform/");
10903
+ return isHTML && /<title>\s*Just a moment\.\.\.\s*<\/title>/i.test(text6) && text6.includes("window._cf_chl_opt") && text6.includes("/cdn-cgi/challenge-platform/");
10904
+ }
10905
+ function isExecutableScriptType(type) {
10906
+ const mime = (type ?? "").split(";")[0].trim().toLowerCase();
10907
+ return mime === "" || mime === "module" || JAVASCRIPT_MIME_TYPES.has(mime);
10557
10908
  }
10558
10909
  function isLikelyJSRendered(html) {
10559
10910
  const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
10560
10911
  if (!bodyMatch) return false;
10561
10912
  const bodyHtml = bodyMatch[1];
10562
10913
  const textContent = bodyHtml.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
10563
- const scriptCount = (html.match(/<script/gi) || []).length;
10914
+ const scriptCount = [...html.matchAll(/<script\b([^>]*)>/gi)].filter(([, attrs]) => isExecutableScriptType(attrs.match(/\btype\s*=\s*["']?([^"'\s>]+)/i)?.[1] ?? null)).length;
10564
10915
  return textContent.length < 500 && scriptCount > 3;
10565
10916
  }
10566
10917
  async function readPDFResponseBuffer(response, maxSizeMB) {
@@ -10695,9 +11046,9 @@ async function extractViaHttp(url, timeoutMs, signal, options, preferMarkdown =
10695
11046
  const hint = isPDFContent ? '; retry without mode for Markdown, or with mode "answer" and a prompt' : "";
10696
11047
  return { url, title: "", content: "", error: `Unsupported content type in raw mode: ${mimeType || "missing"}${hint}`, mimeType, status: response.status };
10697
11048
  }
10698
- const text6 = await readTextResponseWithLimit(response, maxResponseSize);
11049
+ const text7 = await readTextResponseWithLimit(response, maxResponseSize);
10699
11050
  activityMonitor.logComplete(activityId, response.status);
10700
- return { url, title: extractTextTitle(text6, url), content: text6, error: null, mimeType, status: response.status };
11051
+ return { url, title: extractTextTitle(text7, url), content: text7, error: null, mimeType, status: response.status };
10701
11052
  }
10702
11053
  if (SUPPORTED_IMAGE_TYPES.has(mimeType)) {
10703
11054
  const disabled = imageGateError();
@@ -10767,19 +11118,19 @@ ${result.pages > 0 ? `Pages: ${result.pages}
10767
11118
  error: `Unsupported content type: ${contentType.split(";")[0]}`
10768
11119
  };
10769
11120
  }
10770
- const text5 = await readTextResponseWithLimit(response, maxResponseSize);
11121
+ const text6 = await readTextResponseWithLimit(response, maxResponseSize);
10771
11122
  const isHTML = contentType.includes("text/html") || contentType.includes("application/xhtml+xml");
10772
- if (isCloudflareChallenge(response, text5, isHTML)) {
11123
+ if (isCloudflareChallenge(response, text6, isHTML)) {
10773
11124
  activityMonitor.logComplete(activityId, response.status);
10774
11125
  return { url, title: "", content: "", error: `HTTP ${response.status}: Blocked by Cloudflare challenge page`, status: response.status };
10775
11126
  }
10776
11127
  if (!isHTML) {
10777
11128
  activityMonitor.logComplete(activityId, response.status);
10778
- const title = extractTextTitle(text5, url);
10779
- if (mimeType !== "text/markdown" && mimeType !== "text/x-markdown") return { url, title, content: text5, error: null };
11129
+ const title = extractTextTitle(text6, url);
11130
+ if (mimeType !== "text/markdown" && mimeType !== "text/x-markdown") return { url, title, content: text6, error: null };
10780
11131
  const declaredLinks2 = discoverDeclaredWebLinks(null, response.headers.get("link"), response.url || url);
10781
- const markdown2 = { url, title, content: appendDeclaredWebLinks(text5, declaredLinks2), error: null, declaredLinks: declaredLinks2 };
10782
- if (!preferMarkdown || text5.trim().length >= MIN_USEFUL_CONTENT2) return markdown2;
11132
+ const markdown2 = { url, title, content: appendDeclaredWebLinks(text6, declaredLinks2), error: null, declaredLinks: declaredLinks2 };
11133
+ if (!preferMarkdown || text6.trim().length >= MIN_USEFUL_CONTENT2) return markdown2;
10783
11134
  const normal = await extractViaHttp(url, Math.max(1, timeoutMs - (Date.now() - startedAt)), signal, options, false);
10784
11135
  if (signal?.aborted || isNonRecoverableHttpError(normal.error) || normal.status === 404 || normal.status === 410 || isAbortError6(normal.error)) return normal;
10785
11136
  const normalHasBody = normal.content.trim() !== appendDeclaredWebLinks("", normal.declaredLinks ?? []).trim();
@@ -10792,7 +11143,7 @@ Browser retry failed: ${normal.error}` : "")
10792
11143
  };
10793
11144
  }
10794
11145
  const { parseHTML } = await import("linkedom");
10795
- const { document } = parseHTML(text5);
11146
+ const { document } = parseHTML(text6);
10796
11147
  const documentTitle = document.title?.trim() ?? "";
10797
11148
  const declaredLinks = discoverDeclaredWebLinks(
10798
11149
  document,
@@ -10803,7 +11154,7 @@ Browser retry failed: ${normal.error}` : "")
10803
11154
  const reader = new Readability(document);
10804
11155
  const article = reader.parse();
10805
11156
  if (!article) {
10806
- const rscResult = extractRSCContent(text5);
11157
+ const rscResult = extractRSCContent(text6);
10807
11158
  if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT2) {
10808
11159
  activityMonitor.logComplete(activityId, response.status);
10809
11160
  return {
@@ -10815,7 +11166,7 @@ Browser retry failed: ${normal.error}` : "")
10815
11166
  };
10816
11167
  }
10817
11168
  controller.signal.throwIfAborted();
10818
- const defuddleResult = await extractWithDefuddle(text5, response.url || url);
11169
+ const defuddleResult = await extractWithDefuddle(text6, response.url || url);
10819
11170
  controller.signal.throwIfAborted();
10820
11171
  if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT2) {
10821
11172
  activityMonitor.logComplete(activityId, response.status);
@@ -10828,7 +11179,7 @@ Browser retry failed: ${normal.error}` : "")
10828
11179
  };
10829
11180
  }
10830
11181
  activityMonitor.logComplete(activityId, response.status);
10831
- const jsRendered = isLikelyJSRendered(text5);
11182
+ const jsRendered = isLikelyJSRendered(text6);
10832
11183
  const errorMsg = jsRendered ? "Page appears to be JavaScript-rendered (content loads dynamically)" : "Could not extract readable content from HTML structure";
10833
11184
  return {
10834
11185
  url,
@@ -10844,7 +11195,7 @@ Browser retry failed: ${normal.error}` : "")
10844
11195
  const markdown = (await getTurndown()).turndown(article.content);
10845
11196
  activityMonitor.logComplete(activityId, response.status);
10846
11197
  if (markdown.length < MIN_USEFUL_CONTENT2) {
10847
- const rscResult = extractRSCContent(text5);
11198
+ const rscResult = extractRSCContent(text6);
10848
11199
  if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT2) {
10849
11200
  return {
10850
11201
  url,
@@ -10855,7 +11206,7 @@ Browser retry failed: ${normal.error}` : "")
10855
11206
  };
10856
11207
  }
10857
11208
  controller.signal.throwIfAborted();
10858
- const defuddleResult = await extractWithDefuddle(text5, response.url || url);
11209
+ const defuddleResult = await extractWithDefuddle(text6, response.url || url);
10859
11210
  controller.signal.throwIfAborted();
10860
11211
  if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT2) {
10861
11212
  return {
@@ -10866,11 +11217,23 @@ Browser retry failed: ${normal.error}` : "")
10866
11217
  declaredLinks
10867
11218
  };
10868
11219
  }
11220
+ let error = "Page appears to be JavaScript-rendered (content loads dynamically)";
11221
+ if (!isLikelyJSRendered(text6)) {
11222
+ const { document: original } = parseHTML(text6);
11223
+ const hasExecutableScript = [...original.querySelectorAll("script")].some((script) => isExecutableScriptType(script.getAttribute("type")));
11224
+ for (const node of original.querySelectorAll("script, style, noscript, template")) node.remove();
11225
+ const visibleChars = (original.body?.textContent ?? "").replace(/\s+/g, " ").trim().length;
11226
+ const extractedChars = markdown.trim().length;
11227
+ const counts = `Extracted content appears incomplete: extracted ${extractedChars} characters from a page with ${visibleChars} characters of visible text`;
11228
+ if (visibleChars >= MIN_USEFUL_CONTENT2) error = counts;
11229
+ else if (hasExecutableScript) error = `Extracted content appears incomplete: the page has only ${visibleChars} characters of visible text and runs scripts, so content may load dynamically`;
11230
+ else error = extractedChars > 0 ? null : counts;
11231
+ }
10869
11232
  return {
10870
11233
  url,
10871
11234
  title: article.title || documentTitle,
10872
11235
  content: appendDeclaredWebLinks(markdown, declaredLinks),
10873
- error: isLikelyJSRendered(text5) ? "Page appears to be JavaScript-rendered (content loads dynamically)" : "Extracted content appears incomplete",
11236
+ error,
10874
11237
  declaredLinks
10875
11238
  };
10876
11239
  }
@@ -10898,14 +11261,14 @@ Browser retry failed: ${normal.error}` : "")
10898
11261
  }
10899
11262
  }
10900
11263
  }
10901
- function extractHeadingTitle(text5) {
10902
- const match = text5.match(/^#{1,2}\s+(.+)/m);
11264
+ function extractHeadingTitle(text6) {
11265
+ const match = text6.match(/^#{1,2}\s+(.+)/m);
10903
11266
  if (!match) return null;
10904
11267
  const cleaned = match[1].replace(/\*+/g, "").trim();
10905
11268
  return cleaned || null;
10906
11269
  }
10907
- function extractTextTitle(text5, url) {
10908
- return extractHeadingTitle(text5) ?? (new URL(url).pathname.split("/").pop() || url);
11270
+ function extractTextTitle(text6, url) {
11271
+ return extractHeadingTitle(text6) ?? (new URL(url).pathname.split("/").pop() || url);
10909
11272
  }
10910
11273
  async function fetchAllContent(urls, signal, options) {
10911
11274
  const results = await Promise.all(urls.map((url) => fetchLimit(() => extractContent(url, signal, options))));
@@ -10916,7 +11279,7 @@ async function fetchAllContent(urls, signal, options) {
10916
11279
  return sanitized.omissions.length > 0 ? { ...result, content: sanitized.text } : result;
10917
11280
  });
10918
11281
  }
10919
- 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, BROWSER_ACCEPT, MARKDOWN_FIRST_ACCEPT;
11282
+ 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;
10920
11283
  var init_extract = __esm({
10921
11284
  "extract.ts"() {
10922
11285
  init_activity();
@@ -10930,6 +11293,7 @@ var init_extract = __esm({
10930
11293
  init_parallel();
10931
11294
  init_parallel_mcp();
10932
11295
  init_tinyfish();
11296
+ init_deepseek();
10933
11297
  init_search1api();
10934
11298
  init_querit();
10935
11299
  init_kagi();
@@ -10953,14 +11317,32 @@ var init_extract = __esm({
10953
11317
  NON_RECOVERABLE_ERRORS = ["Unsupported content type", "Response too large", "PDF extraction is disabled", "Image fetching is disabled"];
10954
11318
  MIN_USEFUL_CONTENT2 = 500;
10955
11319
  SUPPORTED_IMAGE_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
10956
- FETCH_PROVIDERS = ["http", "firecrawl", "crawl4ai", "jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini"];
11320
+ FETCH_PROVIDERS = ["http", "firecrawl", "crawl4ai", "jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini", "deepseek"];
10957
11321
  DEFAULT_FETCH_PROVIDER_ORDER = ["http", "firecrawl", "crawl4ai", "jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "brightdata", "gemini"];
10958
- REMOTE_HOSTED_FETCH_PROVIDERS = /* @__PURE__ */ new Set(["jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini"]);
11322
+ REMOTE_HOSTED_FETCH_PROVIDERS = /* @__PURE__ */ new Set(["jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini", "deepseek"]);
10959
11323
  REDIRECT_STATUSES4 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
10960
11324
  fetchLimit = pLimit(CONCURRENT_LIMIT);
10961
11325
  JINA_READER_BASE = "https://r.jina.ai/";
10962
11326
  DEFAULT_RANGE_FRAMES = 6;
10963
11327
  MIN_FRAME_INTERVAL = 5;
11328
+ JAVASCRIPT_MIME_TYPES = /* @__PURE__ */ new Set([
11329
+ "application/ecmascript",
11330
+ "application/javascript",
11331
+ "application/x-ecmascript",
11332
+ "application/x-javascript",
11333
+ "text/ecmascript",
11334
+ "text/javascript",
11335
+ "text/javascript1.0",
11336
+ "text/javascript1.1",
11337
+ "text/javascript1.2",
11338
+ "text/javascript1.3",
11339
+ "text/javascript1.4",
11340
+ "text/javascript1.5",
11341
+ "text/jscript",
11342
+ "text/livescript",
11343
+ "text/x-ecmascript",
11344
+ "text/x-javascript"
11345
+ ]);
10964
11346
  BROWSER_ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8";
10965
11347
  MARKDOWN_FIRST_ACCEPT = "text/markdown,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,image/avif;q=0.9,image/webp;q=0.9,image/apng;q=0.9,*/*;q=0.7";
10966
11348
  }
@@ -11199,12 +11581,12 @@ async function answerFromPage(input, ctx, signal) {
11199
11581
  const response = completeFn ? await completeFn(model, context, usesRegistryComplete ? options : { apiKey: auth.apiKey, headers: auth.headers, ...options }) : await registry.streamSimple(model, context, options).result();
11200
11582
  if (response.stopReason === "aborted") throw new Error("Aborted");
11201
11583
  if (response.stopReason === "error") throw new Error(response.errorMessage || "Page answer model failed");
11202
- const text5 = responseText(response.content);
11203
- if (!text5) throw new Error("Page answer model returned an empty response");
11584
+ const text6 = responseText(response.content);
11585
+ if (!text6) throw new Error("Page answer model returned an empty response");
11204
11586
  return {
11205
- text: truncated ? `${text5}
11587
+ text: truncated ? `${text6}
11206
11588
 
11207
- Note: The source page was truncated to ${pageText.length} of ${input.pageText.length} characters for model context.` : text5,
11589
+ Note: The source page was truncated to ${pageText.length} of ${input.pageText.length} characters for model context.` : text6,
11208
11590
  model: `${model.provider}/${model.id}`,
11209
11591
  inputChars: pageText.length,
11210
11592
  originalInputChars: input.pageText.length,
@@ -11246,9 +11628,9 @@ Query: ${query}` }],
11246
11628
  const response = completeFn ? await completeFn(model, context, usesRegistryComplete ? { signal } : { apiKey, headers, signal }) : await registry.streamSimple(model, context, { signal }).result();
11247
11629
  if (response.stopReason === "aborted") throw new Error("Aborted");
11248
11630
  const contentParts = Array.isArray(response.content) ? response.content : [];
11249
- const text5 = contentParts.map((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string" ? part.text : "").join("").trim();
11250
- if (!text5) throw new Error("Rewrite returned empty response");
11251
- return text5;
11631
+ const text6 = contentParts.map((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string" ? part.text : "").join("").trim();
11632
+ if (!text6) throw new Error("Rewrite returned empty response");
11633
+ return text6;
11252
11634
  }
11253
11635
 
11254
11636
  // index.ts
@@ -11261,7 +11643,7 @@ init_gemini_api();
11261
11643
  init_gemini_adc();
11262
11644
  init_gemini_web();
11263
11645
  init_perplexity();
11264
- import { existsSync as existsSync44, readFileSync as readFileSync44 } from "node:fs";
11646
+ import { existsSync as existsSync45, readFileSync as readFileSync45 } from "node:fs";
11265
11647
 
11266
11648
  // exa.ts
11267
11649
  init_activity();
@@ -11462,14 +11844,14 @@ async function callExaMcp(toolName, args, signal) {
11462
11844
  const message = parsed.result.content?.find((item) => item.type === "text" && typeof item.text === "string")?.text?.trim();
11463
11845
  throw new Error(message || "Exa MCP returned an error");
11464
11846
  }
11465
- const text5 = parsed.result?.content?.find((item) => item.type === "text" && typeof item.text === "string" && item.text.trim().length > 0)?.text;
11466
- if (!text5) {
11847
+ const text6 = parsed.result?.content?.find((item) => item.type === "text" && typeof item.text === "string" && item.text.trim().length > 0)?.text;
11848
+ if (!text6) {
11467
11849
  throw new Error("Exa MCP returned empty content");
11468
11850
  }
11469
- return text5;
11851
+ return text6;
11470
11852
  }
11471
- function parseMcpResults(text5) {
11472
- const blocks = text5.split(/(?=^Title: )/m).filter((block) => block.trim().length > 0);
11853
+ function parseMcpResults(text6) {
11854
+ const blocks = text6.split(/(?=^Title: )/m).filter((block) => block.trim().length > 0);
11473
11855
  const parsed = blocks.map((block) => {
11474
11856
  const title = block.match(/^Title: (.+)/m)?.[1]?.trim() ?? "";
11475
11857
  const url = block.match(/^URL: (.+)/m)?.[1]?.trim() ?? "";
@@ -11534,17 +11916,17 @@ function buildMcpQuery(query, options) {
11534
11916
  function isAbortMessage(message) {
11535
11917
  return message.toLowerCase().includes("abort");
11536
11918
  }
11537
- function parseJsonMcpResults(text5) {
11919
+ function parseJsonMcpResults(text6) {
11538
11920
  try {
11539
- const results = JSON.parse(text5).results;
11921
+ const results = JSON.parse(text6).results;
11540
11922
  return Array.isArray(results) && results.length > 0 ? results : null;
11541
11923
  } catch {
11542
11924
  return null;
11543
11925
  }
11544
11926
  }
11545
11927
  async function searchWithExaMcpTool(tool, args, options) {
11546
- const text5 = await callExaMcp(tool, args, options.signal);
11547
- const jsonResults = parseJsonMcpResults(text5);
11928
+ const text6 = await callExaMcp(tool, args, options.signal);
11929
+ const jsonResults = parseJsonMcpResults(text6);
11548
11930
  if (jsonResults) {
11549
11931
  return toSearchResponse(
11550
11932
  buildAnswerFromSearchResults(jsonResults),
@@ -11552,7 +11934,7 @@ async function searchWithExaMcpTool(tool, args, options) {
11552
11934
  options.includeContent ? mapInlineContent(jsonResults) : null
11553
11935
  );
11554
11936
  }
11555
- const textResults = parseMcpResults(text5);
11937
+ const textResults = parseMcpResults(text6);
11556
11938
  if (!textResults) return null;
11557
11939
  return toSearchResponse(
11558
11940
  buildAnswerFromMcpResults(textResults),
@@ -11904,7 +12286,7 @@ Get a key at https://brave.com/search/api/`
11904
12286
  );
11905
12287
  }
11906
12288
  const numResults = normalizeSearchResultCount(options.numResults);
11907
- const domainFilters = normalizeDomainFilters(options.domainFilter);
12289
+ const domainFilters2 = normalizeDomainFilters(options.domainFilter);
11908
12290
  const searchQuery = buildBraveQuery(query, options.domainFilter);
11909
12291
  const activityId = activityMonitor.logStart({ type: "api", query: searchQuery });
11910
12292
  const params = new URLSearchParams({
@@ -11954,7 +12336,7 @@ Get a key at https://brave.com/search/api/`
11954
12336
  activityMonitor.logComplete(activityId, response.status);
11955
12337
  const results = [];
11956
12338
  for (const item of data.web?.results ?? []) {
11957
- if (!item.url || !matchesDomainFilters(item.url, domainFilters)) continue;
12339
+ if (!item.url || !matchesDomainFilters(item.url, domainFilters2)) continue;
11958
12340
  results.push({
11959
12341
  title: stripHtml(item.title || "") || item.url,
11960
12342
  url: item.url,
@@ -12333,8 +12715,8 @@ function isWebSearchCall(item) {
12333
12715
  return !!item && typeof item === "object" && item.type === "web_search_call";
12334
12716
  }
12335
12717
  async function parseOpenAIResponse(response) {
12336
- const text5 = await response.text();
12337
- const trimmed = text5.trim();
12718
+ const text6 = await response.text();
12719
+ const trimmed = text6.trim();
12338
12720
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
12339
12721
  try {
12340
12722
  const parsed = JSON.parse(trimmed);
@@ -12350,7 +12732,7 @@ async function parseOpenAIResponse(response) {
12350
12732
  let completedResponse = null;
12351
12733
  let webSearchCallSeen = false;
12352
12734
  let streamError = null;
12353
- for (const line of text5.split("\n")) {
12735
+ for (const line of text6.split("\n")) {
12354
12736
  if (!line.startsWith("data: ")) continue;
12355
12737
  const data = line.slice(6).trim();
12356
12738
  if (!data || data === "[DONE]") continue;
@@ -12402,11 +12784,11 @@ function cleanSourceUrl(rawUrl) {
12402
12784
  return rawUrl.replace(/[?&]utm_source=openai$/, "");
12403
12785
  }
12404
12786
  }
12405
- function extractSnippetAround(text5, start, end) {
12406
- if (typeof start !== "number" || typeof end !== "number" || !text5) return "";
12787
+ function extractSnippetAround(text6, start, end) {
12788
+ if (typeof start !== "number" || typeof end !== "number" || !text6) return "";
12407
12789
  const before = Math.max(0, start - 100);
12408
- const after = Math.min(text5.length, end + 100);
12409
- const snippet = text5.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
12790
+ const after = Math.min(text6.length, end + 100);
12791
+ const snippet = text6.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
12410
12792
  return snippet.length > 300 ? `${snippet.slice(0, 297)}...` : snippet;
12411
12793
  }
12412
12794
  function addResult(results, seen, url, title, snippet = "") {
@@ -12429,7 +12811,7 @@ function extractSearchResults(output, numResults) {
12429
12811
  if (!Array.isArray(content)) continue;
12430
12812
  for (const part of content) {
12431
12813
  if (!part || typeof part !== "object") continue;
12432
- const text5 = typeof part.text === "string" ? part.text : "";
12814
+ const text6 = typeof part.text === "string" ? part.text : "";
12433
12815
  const annotations = part.annotations;
12434
12816
  if (!Array.isArray(annotations)) continue;
12435
12817
  for (const annotation of annotations) {
@@ -12439,7 +12821,7 @@ function extractSearchResults(output, numResults) {
12439
12821
  seenUrls,
12440
12822
  annotation.url,
12441
12823
  annotation.title,
12442
- extractSnippetAround(text5, annotation.start_index, annotation.end_index)
12824
+ extractSnippetAround(text6, annotation.start_index, annotation.end_index)
12443
12825
  );
12444
12826
  }
12445
12827
  }
@@ -12471,8 +12853,8 @@ function extractAnswer(output) {
12471
12853
  if (!Array.isArray(content)) continue;
12472
12854
  for (const part of content) {
12473
12855
  if (!part || typeof part !== "object") continue;
12474
- const text5 = part.text;
12475
- if (typeof text5 === "string" && text5.trim().length > 0) parts.push(text5);
12856
+ const text6 = part.text;
12857
+ if (typeof text6 === "string" && text6.trim().length > 0) parts.push(text6);
12476
12858
  }
12477
12859
  }
12478
12860
  return parts.join("\n").trim();
@@ -12524,10 +12906,10 @@ function buildAlphaSearchHeaders(headers, apiKey) {
12524
12906
  return result;
12525
12907
  }
12526
12908
  async function parseAlphaSearchResponse(response, numResults = 5) {
12527
- const text5 = await response.text();
12909
+ const text6 = await response.text();
12528
12910
  let payload;
12529
12911
  try {
12530
- payload = JSON.parse(text5);
12912
+ payload = JSON.parse(text6);
12531
12913
  } catch {
12532
12914
  throw new Error("OpenAI alpha/search returned invalid JSON");
12533
12915
  }
@@ -12757,7 +13139,7 @@ function businessErrorStatus(codeN, code, message) {
12757
13139
  async function searchinfinityJsonRequest(apiKey, body, signal) {
12758
13140
  let response;
12759
13141
  try {
12760
- response = await fetch(SEARCHINFINITY_SEARCH_URL, {
13142
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("searchinfinity", SEARCHINFINITY_SEARCH_URL, loadConfig11().searchinfinityBaseUrl), {
12761
13143
  method: "POST",
12762
13144
  headers: {
12763
13145
  Authorization: `Bearer ${apiKey}`,
@@ -12765,7 +13147,7 @@ async function searchinfinityJsonRequest(apiKey, body, signal) {
12765
13147
  },
12766
13148
  body: JSON.stringify(body),
12767
13149
  signal: requestSignal6(signal, SEARCH_TIMEOUT_MS7)
12768
- });
13150
+ }, ["Authorization"]);
12769
13151
  } catch (err) {
12770
13152
  const message = errorMessage5(err);
12771
13153
  const redactedMessage = redactCredential(message, apiKey);
@@ -13135,7 +13517,7 @@ async function searchWithYou(query, options = {}) {
13135
13517
  let response;
13136
13518
  let entries;
13137
13519
  try {
13138
- response = await fetchWithCredentialRedirects(YOU_SEARCH_URL, {
13520
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("you", YOU_SEARCH_URL, loadConfig14().youBaseUrl), {
13139
13521
  method: "POST",
13140
13522
  headers: { Accept: "application/json", "Content-Type": "application/json", "X-API-Key": apiKey },
13141
13523
  body: JSON.stringify(body),
@@ -13276,7 +13658,8 @@ function buildSearchRequest(query, options, numResults) {
13276
13658
  const recency = options.recencyFilter ? ` published in the past ${options.recencyFilter}` : "";
13277
13659
  const exclusions = filters.excludes.map((domain) => ` -site:${domain}`).join("");
13278
13660
  const constrainedQuery = `${query.trim()}${exclusions}${recency}`.trim();
13279
- const url = new URL(encodeURIComponent(constrainedQuery), JINA_SEARCH_BASE_URL);
13661
+ if (/^\.{1,2}$/.test(constrainedQuery)) throw new Error("Jina Search query must not be a dot path segment");
13662
+ const url = new URL(encodeURIComponent(constrainedQuery), resolveProviderApiUrl("jinaSearch", JINA_SEARCH_BASE_URL, loadConfig16().jinaSearchBaseUrl));
13280
13663
  url.searchParams.set("count", String(numResults));
13281
13664
  for (const domain of filters.includes) url.searchParams.append("site", domain);
13282
13665
  return { url: url.toString(), filters };
@@ -13363,7 +13746,7 @@ async function searchWithJina(query, options = {}) {
13363
13746
  const request = requestSignal10(options.signal);
13364
13747
  let response;
13365
13748
  try {
13366
- response = await fetch(url, {
13749
+ response = await fetchWithCredentialRedirects(String(url), {
13367
13750
  headers: {
13368
13751
  "Accept": "application/json",
13369
13752
  "Authorization": `Bearer ${apiKey}`,
@@ -13372,7 +13755,7 @@ async function searchWithJina(query, options = {}) {
13372
13755
  "X-Retain-Images": "none"
13373
13756
  },
13374
13757
  signal: request.signal
13375
- });
13758
+ }, ["Authorization"]);
13376
13759
  } catch (err) {
13377
13760
  rethrowRequestError(err, apiKey, activityId, request, options.signal);
13378
13761
  }
@@ -13575,7 +13958,7 @@ async function searchWithSerpdive(query, options = {}) {
13575
13958
  const activityId = activityMonitor.logStart({ type: "api", query });
13576
13959
  let response;
13577
13960
  try {
13578
- response = await fetch(SERPDIVE_API_URL, {
13961
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("serpdive", SERPDIVE_API_URL, loadConfig17().serpdiveBaseUrl), {
13579
13962
  method: "POST",
13580
13963
  headers: {
13581
13964
  "Authorization": `Bearer ${apiKey}`,
@@ -13583,7 +13966,7 @@ async function searchWithSerpdive(query, options = {}) {
13583
13966
  },
13584
13967
  body: JSON.stringify(body),
13585
13968
  signal: requestSignal11(options.signal)
13586
- });
13969
+ }, ["Authorization"]);
13587
13970
  } catch (err) {
13588
13971
  const message = errorMessage11(err);
13589
13972
  const redactedMessage = redactCredential(message, apiKey);
@@ -13757,12 +14140,12 @@ async function searchWithBocha(query, options = {}) {
13757
14140
  const activityId = activityMonitor.logStart({ type: "api", query });
13758
14141
  let response;
13759
14142
  try {
13760
- response = await fetch(BOCHA_SEARCH_URL, {
14143
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("bocha", BOCHA_SEARCH_URL, loadConfig19().bochaBaseUrl), {
13761
14144
  method: "POST",
13762
14145
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
13763
14146
  body: JSON.stringify({ query, count: numResults, freshness: mapFreshness(options.recencyFilter), summary: true }),
13764
14147
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS15), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS15)
13765
- });
14148
+ }, ["Authorization"]);
13766
14149
  } catch (err) {
13767
14150
  const message = errorMessage13(err);
13768
14151
  const redactedMessage = redactCredential(message, apiKey);
@@ -14146,8 +14529,8 @@ function parseResponse(value) {
14146
14529
  if (!Array.isArray(envelope.results)) throw invalidResponse4("expected a results array");
14147
14530
  return envelope.results;
14148
14531
  }
14149
- function redactSecrets(text5, secrets) {
14150
- let redacted = text5;
14532
+ function redactSecrets(text6, secrets) {
14533
+ let redacted = text6;
14151
14534
  for (const secret of secrets) redacted = redactCredential(redacted, secret);
14152
14535
  return redacted;
14153
14536
  }
@@ -14428,7 +14811,7 @@ async function searchWithAnySearch(query, options = {}) {
14428
14811
  const activityId = activityMonitor.logStart({ type: "api", query });
14429
14812
  let response;
14430
14813
  try {
14431
- response = await fetch(ANYSEARCH_API_URL, {
14814
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("anysearch", ANYSEARCH_API_URL, loadConfig23().anysearchBaseUrl), {
14432
14815
  method: "POST",
14433
14816
  headers: {
14434
14817
  ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
@@ -14436,7 +14819,7 @@ async function searchWithAnySearch(query, options = {}) {
14436
14819
  },
14437
14820
  body: JSON.stringify(body),
14438
14821
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS20), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS20)
14439
- });
14822
+ }, ["Authorization"]);
14440
14823
  } catch (err) {
14441
14824
  const message = errorMessage16(err);
14442
14825
  const redactedMessage = redactCredential(message, apiKey);
@@ -14613,7 +14996,7 @@ async function searchWithXCrawl(query, options = {}) {
14613
14996
  const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS21);
14614
14997
  let response;
14615
14998
  try {
14616
- response = await fetch(XCRAWL_API_URL, {
14999
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("xcrawl", XCRAWL_API_URL, loadConfig24().xcrawlBaseUrl), {
14617
15000
  method: "POST",
14618
15001
  headers: {
14619
15002
  Authorization: `Bearer ${apiKey}`,
@@ -14621,7 +15004,7 @@ async function searchWithXCrawl(query, options = {}) {
14621
15004
  },
14622
15005
  body: JSON.stringify(body),
14623
15006
  signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal
14624
- });
15007
+ }, ["Authorization"]);
14625
15008
  } catch (err) {
14626
15009
  const message = errorMessage17(err);
14627
15010
  if (options.signal?.aborted) {
@@ -14675,7 +15058,8 @@ init_utils();
14675
15058
  import { existsSync as existsSync31, readFileSync as readFileSync31 } from "node:fs";
14676
15059
  var XAI_RESPONSES_URL = "https://api.x.ai/v1/responses";
14677
15060
  var CONFIG_PATH27 = getWebSearchConfigPath();
14678
- var SEARCH_TIMEOUT_MS22 = 6e4;
15061
+ var DEFAULT_SEARCH_TIMEOUT_MS = 6e4;
15062
+ var MAX_SEARCH_TIMEOUT_MS = 6e5;
14679
15063
  var WEB_SEARCH_AUTH_MODEL_CANDIDATES = ["grok-4.5", "grok-4.3", "grok-build-0.1"];
14680
15064
  var X_SEARCH_AUTH_MODEL_CANDIDATES = ["grok-4.6", ...WEB_SEARCH_AUTH_MODEL_CANDIDATES];
14681
15065
  var DEFAULT_XAI_SEARCH_TOOLS = ["web_search"];
@@ -14702,6 +15086,29 @@ function resolveConfiguredSearchModel2(value) {
14702
15086
  }
14703
15087
  return value.trim();
14704
15088
  }
15089
+ function resolveConfiguredResponsesUrl2(value) {
15090
+ if (value === void 0) return void 0;
15091
+ if (typeof value !== "string" || value.trim().length === 0) {
15092
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH27} must be an absolute http(s) URL`);
15093
+ }
15094
+ let url;
15095
+ try {
15096
+ url = new URL(value.trim());
15097
+ } catch {
15098
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH27} must be an absolute http(s) URL`);
15099
+ }
15100
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
15101
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH27} must use http or https`);
15102
+ }
15103
+ return url.toString();
15104
+ }
15105
+ function resolveConfiguredSearchTimeoutMs(value) {
15106
+ if (value === void 0) return DEFAULT_SEARCH_TIMEOUT_MS;
15107
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
15108
+ throw new Error(`xaiSearchTimeoutMs in ${CONFIG_PATH27} must be a positive integer`);
15109
+ }
15110
+ return Math.min(value, MAX_SEARCH_TIMEOUT_MS);
15111
+ }
14705
15112
  function resolveConfiguredSearchTools(value) {
14706
15113
  if (value === void 0) return [...DEFAULT_XAI_SEARCH_TOOLS];
14707
15114
  if (!Array.isArray(value) || value.length === 0) {
@@ -14747,7 +15154,7 @@ async function resolveXaiAuth(ctx, signal) {
14747
15154
  const config = loadConfig25();
14748
15155
  const modelOverride = resolveConfiguredSearchModel2(config.xaiSearchModel);
14749
15156
  const tools = resolveConfiguredSearchTools(config.xaiSearchTools);
14750
- if (ctx) {
15157
+ if (ctx && resolveConfiguredResponsesUrl2(config.xaiResponsesUrl) === void 0) {
14751
15158
  const auth = await resolvePiAuth2(ctx, modelOverride, tools);
14752
15159
  if (auth) return auth;
14753
15160
  }
@@ -14768,13 +15175,16 @@ async function resolveXaiAuth(ctx, signal) {
14768
15175
  async function isXaiSearchAvailable(ctx) {
14769
15176
  let config;
14770
15177
  let tools;
15178
+ let customUrl;
14771
15179
  try {
14772
15180
  config = loadConfig25();
14773
15181
  tools = resolveConfiguredSearchTools(config.xaiSearchTools);
15182
+ customUrl = resolveConfiguredResponsesUrl2(config.xaiResponsesUrl);
15183
+ resolveConfiguredSearchTimeoutMs(config.xaiSearchTimeoutMs);
14774
15184
  } catch {
14775
15185
  return false;
14776
15186
  }
14777
- if (ctx && await resolvePiAuth2(ctx, void 0, tools)) return true;
15187
+ if (ctx && customUrl === void 0 && await resolvePiAuth2(ctx, void 0, tools)) return true;
14778
15188
  return hasCredentialSource({
14779
15189
  provider: "xAI",
14780
15190
  configuredValue: config.xaiApiKey,
@@ -14843,11 +15253,11 @@ function addSources(results, seen, sources) {
14843
15253
  if (!Array.isArray(sources)) return;
14844
15254
  for (const source of sources) addSource(results, seen, source);
14845
15255
  }
14846
- function extractSnippetAround2(text5, start, end) {
14847
- if (typeof start !== "number" || typeof end !== "number" || !text5) return "";
15256
+ function extractSnippetAround2(text6, start, end) {
15257
+ if (typeof start !== "number" || typeof end !== "number" || !text6) return "";
14848
15258
  const before = Math.max(0, start - 100);
14849
- const after = Math.min(text5.length, end + 100);
14850
- const snippet = text5.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
15259
+ const after = Math.min(text6.length, end + 100);
15260
+ const snippet = text6.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
14851
15261
  return snippet.length > 300 ? `${snippet.slice(0, 297)}...` : snippet;
14852
15262
  }
14853
15263
  function extractAnswer2(output) {
@@ -14858,8 +15268,8 @@ function extractAnswer2(output) {
14858
15268
  if (!Array.isArray(content)) continue;
14859
15269
  for (const part of content) {
14860
15270
  if (!part || typeof part !== "object") continue;
14861
- const text5 = part.text;
14862
- if (typeof text5 === "string" && text5.trim().length > 0) parts.push(text5);
15271
+ const text6 = part.text;
15272
+ if (typeof text6 === "string" && text6.trim().length > 0) parts.push(text6);
14863
15273
  }
14864
15274
  }
14865
15275
  return parts.join("\n").trim();
@@ -14873,7 +15283,7 @@ function extractSearchResults2(output, citations, numResults) {
14873
15283
  if (!Array.isArray(content)) continue;
14874
15284
  for (const part of content) {
14875
15285
  if (!part || typeof part !== "object") continue;
14876
- const text5 = typeof part.text === "string" ? part.text : "";
15286
+ const text6 = typeof part.text === "string" ? part.text : "";
14877
15287
  const annotations = part.annotations;
14878
15288
  if (!Array.isArray(annotations)) continue;
14879
15289
  for (const annotation of annotations) {
@@ -14884,7 +15294,7 @@ function extractSearchResults2(output, citations, numResults) {
14884
15294
  seenUrls,
14885
15295
  annotation.url,
14886
15296
  annotation.title,
14887
- extractSnippetAround2(text5, annotation.start_index, annotation.end_index)
15297
+ extractSnippetAround2(text6, annotation.start_index, annotation.end_index)
14888
15298
  );
14889
15299
  }
14890
15300
  }
@@ -14904,9 +15314,17 @@ function extractSearchResults2(output, citations, numResults) {
14904
15314
  return results;
14905
15315
  }
14906
15316
  async function searchWithXai(query, options = {}, ctx) {
14907
- const tools = resolveConfiguredSearchTools(loadConfig25().xaiSearchTools);
15317
+ const config = loadConfig25();
15318
+ const tools = resolveConfiguredSearchTools(config.xaiSearchTools);
15319
+ const customUrl = resolveConfiguredResponsesUrl2(config.xaiResponsesUrl);
15320
+ const timeoutMs = resolveConfiguredSearchTimeoutMs(config.xaiSearchTimeoutMs);
14908
15321
  const auth = await resolveXaiAuth(ctx, options.signal);
14909
15322
  if (!auth) {
15323
+ if (customUrl) {
15324
+ throw new Error(
15325
+ `xAI search unavailable: xaiResponsesUrl is set, so Pi's xAI sign-in is not used. Set xaiApiKey in ${CONFIG_PATH27} or the XAI_API_KEY environment variable to the key for that endpoint.`
15326
+ );
15327
+ }
14910
15328
  throw new Error(
14911
15329
  `xAI search unavailable. Either:
14912
15330
  1. Use /login to sign in with a SuperGrok or X Premium subscription
@@ -14916,7 +15334,7 @@ async function searchWithXai(query, options = {}, ctx) {
14916
15334
  }
14917
15335
  const activityId = activityMonitor.logStart({ type: "api", query });
14918
15336
  try {
14919
- const response = await fetch(XAI_RESPONSES_URL, {
15337
+ const response = await fetch(customUrl ?? XAI_RESPONSES_URL, {
14920
15338
  method: "POST",
14921
15339
  headers: {
14922
15340
  ...toRequestHeaders2(auth.headers),
@@ -14928,7 +15346,7 @@ async function searchWithXai(query, options = {}, ctx) {
14928
15346
  input: buildInput(query, options, tools),
14929
15347
  tools: tools.map((type) => ({ type }))
14930
15348
  }),
14931
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS22), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS22)
15349
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(timeoutMs), options.signal]) : AbortSignal.timeout(timeoutMs)
14932
15350
  });
14933
15351
  if (!response.ok) {
14934
15352
  activityMonitor.logError(activityId, `HTTP ${response.status}`);
@@ -14975,7 +15393,7 @@ init_utils();
14975
15393
  import { existsSync as existsSync32, readFileSync as readFileSync32 } from "node:fs";
14976
15394
  var BRIGHTDATA_API_URL = "https://api.brightdata.com/request";
14977
15395
  var CONFIG_PATH28 = getWebSearchConfigPath();
14978
- var SEARCH_TIMEOUT_MS23 = 6e4;
15396
+ var SEARCH_TIMEOUT_MS22 = 6e4;
14979
15397
  var ZONE_PATTERN = /^[A-Za-z0-9_-]+$/;
14980
15398
  var RECENCY_TBS = {
14981
15399
  day: "qdr:d",
@@ -15114,7 +15532,7 @@ function passesDomainFilters4(url, filters) {
15114
15532
  return filters.include.some((domain) => domainMatches4(hostname2, domain));
15115
15533
  }
15116
15534
  function requestSignal12(signal) {
15117
- const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS23);
15535
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS22);
15118
15536
  return signal ? AbortSignal.any([signal, timeout]) : timeout;
15119
15537
  }
15120
15538
  function errorMessage18(err) {
@@ -15122,8 +15540,8 @@ function errorMessage18(err) {
15122
15540
  }
15123
15541
  var STATUS_SHAPED_PATTERN = /\b(?:error|status|http)[\s:=-]{1,4}(\d{3})\b/gi;
15124
15542
  var QUOTA_SHAPED_PATTERN = /rate limit|quota|too many requests/gi;
15125
- function untrustedText(text5, limit = 300) {
15126
- return text5.replace(/\s+/g, " ").trim().slice(0, limit).replace(STATUS_SHAPED_PATTERN, "upstream $1").replace(QUOTA_SHAPED_PATTERN, "upstream rate-limit notice");
15543
+ function untrustedText(text6, limit = 300) {
15544
+ return text6.replace(/\s+/g, " ").trim().slice(0, limit).replace(STATUS_SHAPED_PATTERN, "upstream $1").replace(QUOTA_SHAPED_PATTERN, "upstream rate-limit notice");
15127
15545
  }
15128
15546
  function invalidResponse7(zone, message) {
15129
15547
  return new Error(`Bright Data API returned invalid response for zone ${zone}: ${message}`);
@@ -15214,7 +15632,7 @@ async function searchWithBrightData(query, options = {}) {
15214
15632
  const activityId = activityMonitor.logStart({ type: "api", query: searchQuery });
15215
15633
  let response;
15216
15634
  try {
15217
- response = await fetch(BRIGHTDATA_API_URL, {
15635
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("brightdata", BRIGHTDATA_API_URL, loadConfig26().brightdataBaseUrl), {
15218
15636
  method: "POST",
15219
15637
  headers: {
15220
15638
  "Authorization": `Bearer ${apiKey}`,
@@ -15222,7 +15640,7 @@ async function searchWithBrightData(query, options = {}) {
15222
15640
  },
15223
15641
  body: JSON.stringify(body),
15224
15642
  signal: requestSignal12(options.signal)
15225
- });
15643
+ }, ["Authorization"]);
15226
15644
  } catch (err) {
15227
15645
  const message = errorMessage18(err);
15228
15646
  const redactedMessage = redactCredential(message, apiKey);
@@ -15272,7 +15690,7 @@ init_utils();
15272
15690
  import { existsSync as existsSync33, readFileSync as readFileSync33 } from "node:fs";
15273
15691
  var SERPBASE_API_URL = "https://api.serpbase.dev/google/search";
15274
15692
  var CONFIG_PATH29 = getWebSearchConfigPath();
15275
- var SEARCH_TIMEOUT_MS24 = 6e4;
15693
+ var SEARCH_TIMEOUT_MS23 = 6e4;
15276
15694
  var RECENCY_TBS2 = {
15277
15695
  day: "qdr:d",
15278
15696
  week: "qdr:w",
@@ -15381,7 +15799,7 @@ async function searchWithSerpBase(query, options = {}) {
15381
15799
  const apiKey = await requireApiKey9(options.signal);
15382
15800
  const numResults = normalizeCount3(options.numResults);
15383
15801
  const filters = parseDomainFilter5(options.domainFilter);
15384
- const url = new URL(SERPBASE_API_URL);
15802
+ const url = new URL(resolveProviderApiUrl("serpbase", SERPBASE_API_URL, loadConfig27().serpbaseBaseUrl));
15385
15803
  url.searchParams.set("q", buildQuery2(query, filters));
15386
15804
  url.searchParams.set("api_key", apiKey);
15387
15805
  url.searchParams.set("num", String(numResults));
@@ -15389,10 +15807,10 @@ async function searchWithSerpBase(query, options = {}) {
15389
15807
  const activityId = activityMonitor.logStart({ type: "api", query });
15390
15808
  let response;
15391
15809
  try {
15392
- response = await fetch(url, {
15810
+ response = await fetchWithCredentialRedirects(String(url), {
15393
15811
  headers: { Accept: "application/json" },
15394
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS24), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS24)
15395
- });
15812
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS23), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS23)
15813
+ }, [], ["api_key"]);
15396
15814
  } catch (err) {
15397
15815
  const message = errorMessage19(err);
15398
15816
  const redactedMessage = redactCredential(message, apiKey);
@@ -15439,9 +15857,9 @@ init_search_result_count_normalization();
15439
15857
  init_credential_source();
15440
15858
  init_utils();
15441
15859
  import { existsSync as existsSync34, readFileSync as readFileSync34 } from "node:fs";
15442
- var SERPAPI_SEARCH_URL = "https://serpapi.com/search.json";
15860
+ var SERPAPI_API_BASE_URL = "https://serpapi.com";
15443
15861
  var CONFIG_PATH30 = getWebSearchConfigPath();
15444
- var SEARCH_TIMEOUT_MS25 = 6e4;
15862
+ var SEARCH_TIMEOUT_MS24 = 6e4;
15445
15863
  var RECENCY_TBS3 = {
15446
15864
  day: "qdr:d",
15447
15865
  week: "qdr:w",
@@ -15535,25 +15953,26 @@ function isSerpApiAvailable() {
15535
15953
  return hasCredentialSource({ provider: "SerpApi", configuredValue: loadConfig28().serpapiApiKey, environmentValue: process.env.SERPAPI_KEY });
15536
15954
  }
15537
15955
  async function searchWithSerpApi(query, options = {}) {
15956
+ const apiUrl = resolveProviderApiUrl("serpapi", `${SERPAPI_API_BASE_URL}/search.json`, loadConfig28().serpapiBaseUrl);
15538
15957
  const apiKey = await requireApiKey10(options.signal);
15539
15958
  const numResults = normalizeSearchResultCount(options.numResults);
15540
15959
  const filters = parseDomainFilter6(options.domainFilter);
15541
15960
  const requestCount = options.domainFilter?.length ? Math.min(20, numResults + 5) : numResults;
15542
- const url = new URL(SERPAPI_SEARCH_URL);
15961
+ const url = new URL(apiUrl);
15543
15962
  url.searchParams.set("engine", "google");
15544
15963
  url.searchParams.set("q", buildQuery3(query, filters));
15545
15964
  url.searchParams.set("api_key", apiKey);
15546
15965
  url.searchParams.set("num", String(requestCount));
15547
15966
  if (options.recencyFilter) url.searchParams.set("tbs", RECENCY_TBS3[options.recencyFilter]);
15548
15967
  const activityId = activityMonitor.logStart({ type: "api", query });
15549
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS25);
15968
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS24);
15550
15969
  let response;
15551
15970
  let entries;
15552
15971
  try {
15553
- response = await fetch(url, {
15972
+ response = await fetchWithCredentialRedirects(url.toString(), {
15554
15973
  headers: { Accept: "application/json" },
15555
15974
  signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal
15556
- });
15975
+ }, [], ["api_key"]);
15557
15976
  if (!response.ok) {
15558
15977
  const errorText = await response.text();
15559
15978
  throw new Error(`SerpApi error ${response.status}: ${redactCredential(errorText, apiKey).slice(0, 300)}`);
@@ -15573,7 +15992,7 @@ async function searchWithSerpApi(query, options = {}) {
15573
15992
  }
15574
15993
  const message = errorMessage20(err);
15575
15994
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
15576
- const outgoing = providerTimeout ? new Error(`SerpApi request timed out after ${Math.round(SEARCH_TIMEOUT_MS25 / 1e3)}s`) : (() => {
15995
+ const outgoing = providerTimeout ? new Error(`SerpApi request timed out after ${Math.round(SEARCH_TIMEOUT_MS24 / 1e3)}s`) : (() => {
15577
15996
  const redactedMessage = redactCredential(message, apiKey);
15578
15997
  if (redactedMessage === message && err instanceof Error) return err;
15579
15998
  const redactedError = new Error(redactedMessage);
@@ -15607,9 +16026,9 @@ init_search_result_count_normalization();
15607
16026
  init_credential_source();
15608
16027
  init_utils();
15609
16028
  import { existsSync as existsSync35, readFileSync as readFileSync35 } from "node:fs";
15610
- var SERPER_SEARCH_URL = "https://google.serper.dev/search";
16029
+ var SERPER_API_BASE_URL = "https://google.serper.dev";
15611
16030
  var CONFIG_PATH31 = getWebSearchConfigPath();
15612
- var SEARCH_TIMEOUT_MS26 = 6e4;
16031
+ var SEARCH_TIMEOUT_MS25 = 6e4;
15613
16032
  var RECENCY_TBS4 = {
15614
16033
  day: "qdr:d",
15615
16034
  week: "qdr:w",
@@ -15702,6 +16121,7 @@ function isSerperAvailable() {
15702
16121
  return hasCredentialSource({ provider: "Serper", configuredValue: loadConfig29().serperApiKey, environmentValue: process.env.SERPER_API_KEY });
15703
16122
  }
15704
16123
  async function searchWithSerper(query, options = {}) {
16124
+ const apiUrl = resolveProviderApiUrl("serper", `${SERPER_API_BASE_URL}/search`, loadConfig29().serperBaseUrl);
15705
16125
  const apiKey = await requireApiKey11(options.signal);
15706
16126
  const numResults = normalizeSearchResultCount(options.numResults);
15707
16127
  const filters = parseDomainFilter7(options.domainFilter);
@@ -15709,12 +16129,12 @@ async function searchWithSerper(query, options = {}) {
15709
16129
  const activityId = activityMonitor.logStart({ type: "api", query });
15710
16130
  let response;
15711
16131
  try {
15712
- response = await fetch(SERPER_SEARCH_URL, {
16132
+ response = await fetchWithCredentialRedirects(apiUrl, {
15713
16133
  method: "POST",
15714
16134
  headers: { "X-API-KEY": apiKey, "Content-Type": "application/json", Accept: "application/json" },
15715
16135
  body: JSON.stringify({ q: buildQuery4(query, filters), num: requestCount, ...options.recencyFilter ? { tbs: RECENCY_TBS4[options.recencyFilter] } : {} }),
15716
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS26), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS26)
15717
- });
16136
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS25), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS25)
16137
+ }, ["X-API-KEY"]);
15718
16138
  } catch (err) {
15719
16139
  const message = errorMessage21(err);
15720
16140
  const redactedMessage = redactCredential(message, apiKey);
@@ -15770,7 +16190,7 @@ init_utils();
15770
16190
  import { existsSync as existsSync36, readFileSync as readFileSync36 } from "node:fs";
15771
16191
  var SERPLY_SEARCH_URL = "https://api.serply.io/v1/search";
15772
16192
  var CONFIG_PATH32 = getWebSearchConfigPath();
15773
- var SEARCH_TIMEOUT_MS27 = 6e4;
16193
+ var SEARCH_TIMEOUT_MS26 = 6e4;
15774
16194
  var RECENCY_TBS5 = {
15775
16195
  day: "qdr:d",
15776
16196
  week: "qdr:w",
@@ -15863,12 +16283,12 @@ async function searchWithSerply(query, options = {}) {
15863
16283
  const numResults = normalizeSearchResultCount(options.numResults);
15864
16284
  const filters = parseDomainFilter8(options.domainFilter);
15865
16285
  const requestCount = options.domainFilter?.length ? Math.min(20, numResults + 5) : numResults;
15866
- const url = new URL(SERPLY_SEARCH_URL);
16286
+ const url = new URL(resolveProviderApiUrl("serply", SERPLY_SEARCH_URL, loadConfig30().serplyBaseUrl));
15867
16287
  url.searchParams.set("q", buildQuery5(query, filters));
15868
16288
  url.searchParams.set("num", String(requestCount));
15869
16289
  if (options.recencyFilter) url.searchParams.set("tbs", RECENCY_TBS5[options.recencyFilter]);
15870
16290
  const activityId = activityMonitor.logStart({ type: "api", query });
15871
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS27);
16291
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS26);
15872
16292
  let response;
15873
16293
  let entries;
15874
16294
  try {
@@ -15895,7 +16315,7 @@ async function searchWithSerply(query, options = {}) {
15895
16315
  }
15896
16316
  const message = errorMessage22(err);
15897
16317
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
15898
- const outgoing = providerTimeout ? new Error(`Serply request timed out after ${Math.round(SEARCH_TIMEOUT_MS27 / 1e3)}s`) : (() => {
16318
+ const outgoing = providerTimeout ? new Error(`Serply request timed out after ${Math.round(SEARCH_TIMEOUT_MS26 / 1e3)}s`) : (() => {
15899
16319
  const redactedMessage = redactCredential(message, apiKey);
15900
16320
  if (redactedMessage === message && err instanceof Error) return err;
15901
16321
  const redactedError = new Error(redactedMessage);
@@ -15937,7 +16357,7 @@ init_utils();
15937
16357
  import { existsSync as existsSync37, readFileSync as readFileSync37 } from "node:fs";
15938
16358
  import { isIP as isIP2 } from "node:net";
15939
16359
  var MCP_URL = "https://agent-toolkit.app.baizhi.cloud/mcp";
15940
- var SEARCH_TIMEOUT_MS28 = 6e4;
16360
+ var SEARCH_TIMEOUT_MS27 = 6e4;
15941
16361
  var CONFIG_PATH33 = getWebSearchConfigPath();
15942
16362
  function credentialOptions() {
15943
16363
  let config = {};
@@ -15980,7 +16400,7 @@ function searchArguments(query, options) {
15980
16400
  }
15981
16401
  async function searchWithBaizhi(query, options = {}) {
15982
16402
  const args = searchArguments(query, options);
15983
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS28);
16403
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS27);
15984
16404
  const signal = options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
15985
16405
  if (signal.aborted) throw new Error("Aborted");
15986
16406
  const apiKey = await resolveCredential({ ...credentialOptions(), signal });
@@ -16008,8 +16428,8 @@ async function searchWithBaizhi(query, options = {}) {
16008
16428
  const client = new Client({ name: "pi-web-access-baizhi", version: "1.0.0" });
16009
16429
  const activityId = activityMonitor.logStart({ type: "api", query });
16010
16430
  try {
16011
- await client.connect(transport, { signal, timeout: SEARCH_TIMEOUT_MS28 });
16012
- const result = await client.callTool({ name: "websearch_search", arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS28 });
16431
+ await client.connect(transport, { signal, timeout: SEARCH_TIMEOUT_MS27 });
16432
+ const result = await client.callTool({ name: "websearch_search", arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS27 });
16013
16433
  if (result.isError) throw new Error("Baizhi search tool returned an error");
16014
16434
  const parts = [];
16015
16435
  if (result.structuredContent !== void 0) parts.push(JSON.stringify(result.structuredContent, null, 2));
@@ -16053,7 +16473,7 @@ var MCP_URLS = {
16053
16473
  china: "https://open.bigmodel.cn/api/mcp/web_search_prime/mcp"
16054
16474
  };
16055
16475
  var RECENCY = { day: "oneDay", week: "oneWeek", month: "oneMonth", year: "oneYear" };
16056
- var SEARCH_TIMEOUT_MS29 = 6e4;
16476
+ var SEARCH_TIMEOUT_MS28 = 6e4;
16057
16477
  var CONFIG_PATH34 = getWebSearchConfigPath();
16058
16478
  function loadConfig31() {
16059
16479
  if (!existsSync38(CONFIG_PATH34)) return {};
@@ -16092,8 +16512,8 @@ function searchArguments2(query, options) {
16092
16512
  ...domain ? { search_domain_filter: domain } : {}
16093
16513
  };
16094
16514
  }
16095
- function parseResults(text5, limit, domain) {
16096
- let value = JSON.parse(text5);
16515
+ function parseResults(text6, limit, domain) {
16516
+ let value = JSON.parse(text6);
16097
16517
  if (typeof value === "string") value = JSON.parse(value);
16098
16518
  if (!Array.isArray(value)) throw new Error("Z.ai returned invalid response: expected a result list");
16099
16519
  const results = [];
@@ -16124,7 +16544,7 @@ async function searchWithZai(query, options = {}) {
16124
16544
  const mcpUrl = endpointUrl(config);
16125
16545
  const args = searchArguments2(query, options);
16126
16546
  const limit = normalizeSearchResultCount(options.numResults);
16127
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS29);
16547
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS28);
16128
16548
  const signal = options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
16129
16549
  if (signal.aborted) throw new Error("Aborted");
16130
16550
  const apiKey = await resolveCredential({ ...credentialOptions2(config), signal });
@@ -16152,15 +16572,15 @@ async function searchWithZai(query, options = {}) {
16152
16572
  const client = new Client({ name: "pi-web-access-zai", version: "1.0.0" });
16153
16573
  const activityId = activityMonitor.logStart({ type: "api", query });
16154
16574
  try {
16155
- await client.connect(transport, { signal, timeout: SEARCH_TIMEOUT_MS29 });
16156
- const { tools } = await client.listTools(void 0, { signal, timeout: SEARCH_TIMEOUT_MS29 });
16575
+ await client.connect(transport, { signal, timeout: SEARCH_TIMEOUT_MS28 });
16576
+ const { tools } = await client.listTools(void 0, { signal, timeout: SEARCH_TIMEOUT_MS28 });
16157
16577
  const toolName = tools.find((tool) => tool.name === "web_search_prime" || tool.name === "webSearchPrime")?.name;
16158
16578
  if (!toolName) throw new Error("Z.ai returned invalid response: web search tool not listed");
16159
- const result = await client.callTool({ name: toolName, arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS29 });
16579
+ const result = await client.callTool({ name: toolName, arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS28 });
16160
16580
  if (result.isError) throw new Error("Z.ai search tool returned an error");
16161
- const text5 = (Array.isArray(result.content) ? result.content : []).find((item) => item.type === "text" && typeof item.text === "string");
16162
- if (!text5) throw new Error("Z.ai returned invalid response: no search text");
16163
- const results = parseResults(text5.text, limit, args.search_domain_filter);
16581
+ const text6 = (Array.isArray(result.content) ? result.content : []).find((item) => item.type === "text" && typeof item.text === "string");
16582
+ if (!text6) throw new Error("Z.ai returned invalid response: no search text");
16583
+ const results = parseResults(text6.text, limit, args.search_domain_filter);
16164
16584
  activityMonitor.logComplete(activityId, 200);
16165
16585
  return { answer: formatSearchResultsAsAnswer(results), results };
16166
16586
  } catch (err) {
@@ -16193,7 +16613,7 @@ init_utils();
16193
16613
  import { existsSync as existsSync39, readFileSync as readFileSync39 } from "node:fs";
16194
16614
  var VALYU_SEARCH_URL = "https://api.valyu.ai/v1/search";
16195
16615
  var CONFIG_PATH35 = getWebSearchConfigPath();
16196
- var SEARCH_TIMEOUT_MS30 = 6e4;
16616
+ var SEARCH_TIMEOUT_MS29 = 6e4;
16197
16617
  var MAX_SNIPPET_CHARS = 2500;
16198
16618
  var MAX_CONTENT_CHARS = 4e3;
16199
16619
  var cachedConfig32 = null;
@@ -16283,12 +16703,12 @@ async function searchWithValyu(query, options = {}) {
16283
16703
  const activityId = activityMonitor.logStart({ type: "api", query });
16284
16704
  let response;
16285
16705
  try {
16286
- response = await fetch(VALYU_SEARCH_URL, {
16706
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("valyu", VALYU_SEARCH_URL, loadConfig32().valyuBaseUrl), {
16287
16707
  method: "POST",
16288
16708
  headers: { "x-api-key": apiKey, "Content-Type": "application/json", Accept: "application/json" },
16289
16709
  body: JSON.stringify({ query, max_num_results: numResults, ...mapDomainFilter9(options.domainFilter), ...startDate ? { start_date: startDate } : {} }),
16290
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS30), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS30)
16291
- });
16710
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS29), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS29)
16711
+ }, ["x-api-key"]);
16292
16712
  } catch (err) {
16293
16713
  const message = errorMessage23(err);
16294
16714
  const redactedMessage = redactCredential(message, apiKey);
@@ -16347,7 +16767,7 @@ var KEENABLE_SEARCH_URL = "https://api.keenable.ai/v1/search";
16347
16767
  var KEENABLE_PUBLIC_SEARCH_URL = "https://api.keenable.ai/v1/search/public";
16348
16768
  var KEENABLE_CLIENT_TITLE = "pi-web-access";
16349
16769
  var CONFIG_PATH36 = getWebSearchConfigPath();
16350
- var SEARCH_TIMEOUT_MS31 = 3e4;
16770
+ var SEARCH_TIMEOUT_MS30 = 3e4;
16351
16771
  var MAX_REQUEST_RESULTS = 50;
16352
16772
  var MAX_SNIPPET_CHARS2 = 500;
16353
16773
  var RECENCY_DAYS = {
@@ -16449,11 +16869,11 @@ async function searchWithKeenable(query, options = {}) {
16449
16869
  ...apiKey ? { "X-API-Key": apiKey } : {}
16450
16870
  };
16451
16871
  const activityId = activityMonitor.logStart({ type: "api", query });
16452
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS31);
16872
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS30);
16453
16873
  let response;
16454
16874
  let entries;
16455
16875
  try {
16456
- response = await fetchWithCredentialRedirects(apiKey ? KEENABLE_SEARCH_URL : KEENABLE_PUBLIC_SEARCH_URL, {
16876
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("keenable", apiKey ? KEENABLE_SEARCH_URL : KEENABLE_PUBLIC_SEARCH_URL, loadConfig33().keenableBaseUrl), {
16457
16877
  method: "POST",
16458
16878
  headers,
16459
16879
  body: JSON.stringify(body),
@@ -16479,7 +16899,7 @@ async function searchWithKeenable(query, options = {}) {
16479
16899
  }
16480
16900
  const message = errorMessage24(err);
16481
16901
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
16482
- const outgoing = providerTimeout ? new Error(`Keenable request timed out after ${Math.round(SEARCH_TIMEOUT_MS31 / 1e3)}s`) : (() => {
16902
+ const outgoing = providerTimeout ? new Error(`Keenable request timed out after ${Math.round(SEARCH_TIMEOUT_MS30 / 1e3)}s`) : (() => {
16483
16903
  const redactedMessage = redactCredential(message, apiKey);
16484
16904
  if (redactedMessage === message && err instanceof Error) return err;
16485
16905
  const redactedError = new Error(redactedMessage);
@@ -16526,7 +16946,7 @@ init_utils();
16526
16946
  import { existsSync as existsSync41, readFileSync as readFileSync41 } from "node:fs";
16527
16947
  var CERAMIC_SEARCH_URL = "https://api.ceramic.ai/search";
16528
16948
  var CONFIG_PATH37 = getWebSearchConfigPath();
16529
- var SEARCH_TIMEOUT_MS32 = 3e4;
16949
+ var SEARCH_TIMEOUT_MS31 = 3e4;
16530
16950
  var MAX_REQUEST_RESULTS2 = 20;
16531
16951
  var REQUEST_DESCRIPTION_CHARS = 1e3;
16532
16952
  var MAX_SNIPPET_CHARS3 = 500;
@@ -16630,11 +17050,11 @@ async function searchWithCeramic(query, options = {}) {
16630
17050
  maxDescriptionLength: REQUEST_DESCRIPTION_CHARS
16631
17051
  };
16632
17052
  const activityId = activityMonitor.logStart({ type: "api", query });
16633
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS32);
17053
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS31);
16634
17054
  let response;
16635
17055
  let entries;
16636
17056
  try {
16637
- response = await fetchWithCredentialRedirects(CERAMIC_SEARCH_URL, {
17057
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("ceramic", CERAMIC_SEARCH_URL, loadConfig34().ceramicBaseUrl), {
16638
17058
  method: "POST",
16639
17059
  headers: {
16640
17060
  Accept: "application/json",
@@ -16663,7 +17083,7 @@ async function searchWithCeramic(query, options = {}) {
16663
17083
  }
16664
17084
  const message = errorMessage25(err);
16665
17085
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
16666
- const outgoing = providerTimeout ? new Error(`Ceramic request timed out after ${Math.round(SEARCH_TIMEOUT_MS32 / 1e3)}s`) : (() => {
17086
+ const outgoing = providerTimeout ? new Error(`Ceramic request timed out after ${Math.round(SEARCH_TIMEOUT_MS31 / 1e3)}s`) : (() => {
16667
17087
  const redactedMessage = redactCredential(message, apiKey);
16668
17088
  if (redactedMessage === message && err instanceof Error) return err;
16669
17089
  const redactedError = new Error(redactedMessage);
@@ -16699,183 +17119,157 @@ async function searchWithCeramic(query, options = {}) {
16699
17119
  return { answer: formatSearchResultsAsAnswer(results), results };
16700
17120
  }
16701
17121
 
16702
- // deepseek.ts
17122
+ // linkup.ts
16703
17123
  init_activity();
17124
+ init_credential_source();
16704
17125
  init_domain_filter_normalization();
16705
17126
  init_search_answer_formatting();
16706
17127
  init_search_result_count_normalization();
16707
- init_credential_source();
16708
17128
  init_utils();
16709
17129
  import { existsSync as existsSync42, readFileSync as readFileSync42 } from "node:fs";
16710
- var DEEPSEEK_SEARCH_URL = "https://api.deepseek.com/v1/tools/search";
17130
+ var LINKUP_SEARCH_URL = "https://api.linkup.so/v1/search";
16711
17131
  var CONFIG_PATH38 = getWebSearchConfigPath();
16712
- var SEARCH_TIMEOUT_MS33 = 3e4;
16713
- var MAX_QUERY_CHARS = 128;
16714
- var MAX_SNIPPET_CHARS4 = 800;
16715
- var RECENCY_DAYS2 = {
16716
- day: 1,
16717
- week: 7,
16718
- month: 30,
16719
- year: 365
16720
- };
16721
- var cachedConfig35 = null;
17132
+ var SEARCH_TIMEOUT_MS32 = 6e4;
17133
+ var DEPTHS = ["flash", "fast", "standard", "deep"];
17134
+ var cachedConfig35;
16722
17135
  function loadConfig35() {
16723
17136
  if (cachedConfig35) return cachedConfig35;
16724
- if (!existsSync42(CONFIG_PATH38)) {
16725
- cachedConfig35 = {};
16726
- return cachedConfig35;
16727
- }
16728
- const raw = readFileSync42(CONFIG_PATH38, "utf-8");
17137
+ if (!existsSync42(CONFIG_PATH38)) return cachedConfig35 = {};
16729
17138
  let parsed;
16730
17139
  try {
16731
- parsed = JSON.parse(raw);
16732
- } catch (err) {
16733
- const message = err instanceof Error ? err.message : String(err);
16734
- throw new Error(`Failed to parse ${CONFIG_PATH38}: ${message}`);
17140
+ parsed = JSON.parse(readFileSync42(CONFIG_PATH38, "utf-8"));
17141
+ } catch {
17142
+ throw new Error(`Failed to parse ${CONFIG_PATH38}: expected valid JSON`);
16735
17143
  }
16736
17144
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
16737
17145
  throw new Error(`Invalid config in ${CONFIG_PATH38}: expected a JSON object`);
16738
17146
  }
16739
- cachedConfig35 = parsed;
16740
- return cachedConfig35;
17147
+ return cachedConfig35 = parsed;
16741
17148
  }
16742
- async function requireApiKey15(signal) {
16743
- const apiKey = await resolveCredential({
16744
- provider: "DeepSeek",
16745
- configuredValue: loadConfig35().deepseekApiKey,
16746
- environmentValue: process.env.DEEPSEEK_API_KEY,
16747
- signal
16748
- });
16749
- if (!apiKey) {
16750
- throw new Error(
16751
- `DeepSeek API key not found. Either:
16752
- 1. Create ${CONFIG_PATH38} with { "deepseekApiKey": "your-key" }
16753
- 2. Set DEEPSEEK_API_KEY environment variable
16754
- Get a key at https://platform.deepseek.com/api_keys`
16755
- );
17149
+ function getDepth() {
17150
+ const value = loadConfig35().linkupDepth;
17151
+ if (value === void 0) return "fast";
17152
+ if (typeof value !== "string" || !DEPTHS.includes(value)) {
17153
+ throw new Error(`linkupDepth in ${CONFIG_PATH38} must be one of: ${DEPTHS.join(", ")}`);
16756
17154
  }
16757
- return apiKey;
17155
+ return value;
16758
17156
  }
16759
- function buildQuery8(query, options) {
17157
+ function domainFilters(values) {
16760
17158
  const include = [];
16761
17159
  const exclude = [];
16762
- for (const raw of options.domainFilter ?? []) {
17160
+ for (const raw of values ?? []) {
16763
17161
  const domain = normalizeDomain(raw);
16764
17162
  if (!domain) continue;
16765
17163
  const target = raw.trim().startsWith("-") ? exclude : include;
16766
17164
  if (!target.includes(domain)) target.push(domain);
16767
17165
  }
16768
- const parts = [query.trim()];
16769
- if (include.length > 0) parts.push(include.map((domain) => `site:${domain}`).join(" OR "));
16770
- for (const domain of exclude) parts.push(`-site:${domain}`);
16771
- if (options.recencyFilter) {
16772
- const after = new Date(Date.now() - RECENCY_DAYS2[options.recencyFilter] * 864e5).toISOString().slice(0, 10);
16773
- parts.push(`after:${after}`);
16774
- }
16775
- const built = parts.join(" ");
16776
- const length = [...built].length;
16777
- if (length > MAX_QUERY_CHARS) {
16778
- throw new Error(`DeepSeek invalid request: the query is ${length} characters with domain and date filters; DeepSeek accepts at most ${MAX_QUERY_CHARS}`);
17166
+ if (include.length > 100 || exclude.length > 100) {
17167
+ throw new Error("Linkup domainFilter must contain at most 100 included and 100 excluded domains");
16779
17168
  }
16780
- return built;
17169
+ return { include, exclude };
17170
+ }
17171
+ function recencyToDate(filter) {
17172
+ if (!filter) return void 0;
17173
+ const days = { day: 1, week: 7, month: 30, year: 365 }[filter];
17174
+ return new Date(Date.now() - days * 864e5).toISOString().slice(0, 10);
16781
17175
  }
16782
17176
  function text4(value) {
16783
17177
  return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
16784
17178
  }
16785
- function errorMessage26(err) {
16786
- return err instanceof Error ? err.message : String(err);
16787
- }
16788
17179
  function parseResponse11(value) {
16789
- const results = value && typeof value === "object" && !Array.isArray(value) ? value.results : void 0;
16790
- if (!Array.isArray(results)) throw new Error("DeepSeek returned invalid response: expected a results array");
16791
- return results;
16792
- }
16793
- function describeError2(body) {
16794
- try {
16795
- const error = JSON.parse(body).error;
16796
- const message = text4(error?.message);
16797
- if (message) return message;
16798
- } catch {
17180
+ if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.results)) {
17181
+ throw new Error("Linkup returned invalid response: expected results array");
16799
17182
  }
16800
- return body;
17183
+ return value.results;
16801
17184
  }
16802
- function isDeepSeekAvailable() {
16803
- return hasCredentialSource({ provider: "DeepSeek", configuredValue: loadConfig35().deepseekApiKey, environmentValue: process.env.DEEPSEEK_API_KEY });
17185
+ function isLinkupAvailable() {
17186
+ return hasCredentialSource({ provider: "Linkup", configuredValue: loadConfig35().linkupApiKey, environmentValue: process.env.LINKUP_API_KEY });
16804
17187
  }
16805
- async function searchWithDeepSeek(query, options = {}) {
16806
- const builtQuery = buildQuery8(query, options);
16807
- const apiKey = await requireApiKey15(options.signal);
17188
+ async function searchWithLinkup(query, options = {}) {
17189
+ const depth = getDepth();
17190
+ const filters = domainFilters(options.domainFilter);
17191
+ const apiKey = await resolveCredential({
17192
+ provider: "Linkup",
17193
+ configuredValue: loadConfig35().linkupApiKey,
17194
+ environmentValue: process.env.LINKUP_API_KEY,
17195
+ signal: options.signal
17196
+ });
17197
+ if (!apiKey) {
17198
+ throw new Error(`Linkup API key not found. Set linkupApiKey in ${CONFIG_PATH38} or LINKUP_API_KEY. Get a key at https://app.linkup.so`);
17199
+ }
16808
17200
  const numResults = normalizeSearchResultCount(options.numResults);
17201
+ const fromDate = recencyToDate(options.recencyFilter);
17202
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS32);
17203
+ const signal = options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
16809
17204
  const activityId = activityMonitor.logStart({ type: "api", query });
16810
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS33);
16811
- let response;
16812
17205
  let entries;
16813
17206
  try {
16814
- response = await fetchWithCredentialRedirects(DEEPSEEK_SEARCH_URL, {
17207
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("linkup", LINKUP_SEARCH_URL, loadConfig35().linkupBaseUrl), {
16815
17208
  method: "POST",
16816
- headers: {
16817
- Accept: "application/json",
16818
- "Content-Type": "application/json",
16819
- Authorization: `Bearer ${apiKey}`
16820
- },
16821
- body: JSON.stringify({ query: builtQuery, count: numResults }),
16822
- signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal
17209
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
17210
+ body: JSON.stringify({
17211
+ q: query,
17212
+ depth,
17213
+ outputType: "searchResults",
17214
+ maxResults: numResults,
17215
+ ...fromDate ? { fromDate } : {},
17216
+ ...filters.include.length ? { includeDomains: filters.include } : {},
17217
+ ...filters.exclude.length ? { excludeDomains: filters.exclude } : {}
17218
+ }),
17219
+ signal
16823
17220
  }, ["Authorization"]);
16824
17221
  if (!response.ok) {
16825
- const errorText = redactCredential(describeError2(await response.text()), apiKey).slice(0, 300);
16826
- throw new Error(`DeepSeek error ${response.status}: ${errorText}`);
17222
+ const body = redactCredential(await response.text(), apiKey).slice(0, 300);
17223
+ throw new Error(`Linkup error ${response.status}: ${body}`);
16827
17224
  }
16828
- let rawData;
17225
+ let data;
16829
17226
  try {
16830
- rawData = await response.json();
17227
+ data = await response.json();
16831
17228
  } catch (err) {
16832
- if (err instanceof Error && err.name === "TimeoutError") throw err;
16833
- throw new Error(`DeepSeek returned invalid JSON: ${errorMessage26(err)}`);
17229
+ if (!(err instanceof SyntaxError)) throw err;
17230
+ throw new Error("Linkup returned invalid JSON");
16834
17231
  }
16835
- entries = parseResponse11(rawData);
17232
+ entries = parseResponse11(data);
17233
+ activityMonitor.logComplete(activityId, response.status);
16836
17234
  } catch (err) {
16837
17235
  if (options.signal?.aborted) {
16838
17236
  activityMonitor.logComplete(activityId, 0);
16839
17237
  throw new Error("Aborted");
16840
17238
  }
16841
- const message = errorMessage26(err);
16842
- const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
16843
- const outgoing = providerTimeout ? new Error(`DeepSeek request timed out after ${Math.round(SEARCH_TIMEOUT_MS33 / 1e3)}s`) : (() => {
16844
- const redactedMessage = redactCredential(message, apiKey);
16845
- if (redactedMessage === message && err instanceof Error) return err;
16846
- const redactedError = new Error(redactedMessage);
16847
- if (err instanceof Error) redactedError.name = err.name;
16848
- return redactedError;
16849
- })();
16850
- activityMonitor.logError(activityId, redactCredential(errorMessage26(outgoing), apiKey));
17239
+ const message = timeout.aborted || err instanceof Error && err.name === "TimeoutError" ? "Linkup request timed out after 60s" : redactCredential(err instanceof Error ? err.message : String(err), apiKey);
17240
+ activityMonitor.logError(activityId, message);
17241
+ const outgoing = err instanceof TypeError ? new TypeError(message) : new Error(message);
17242
+ if (err instanceof Error && !timeout.aborted) outgoing.name = err.name;
16851
17243
  throw outgoing;
16852
17244
  }
16853
- activityMonitor.logComplete(activityId, response.status);
16854
17245
  const results = [];
17246
+ const inlineContent = [];
16855
17247
  const seen = /* @__PURE__ */ new Set();
16856
17248
  for (const entry of entries) {
16857
- if (!entry || typeof entry !== "object") continue;
16858
- if (typeof entry.url !== "string" || !entry.url) continue;
16859
- let resultUrl;
17249
+ if (!entry || typeof entry !== "object" || entry.type !== "text" || typeof entry.url !== "string") continue;
17250
+ let url;
16860
17251
  try {
16861
- resultUrl = new URL(entry.url);
17252
+ url = new URL(entry.url);
16862
17253
  } catch {
16863
17254
  continue;
16864
17255
  }
16865
- if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
16866
- if (seen.has(resultUrl.href)) continue;
16867
- seen.add(resultUrl.href);
16868
- results.push({
16869
- title: text4(entry.title) || `Source ${results.length + 1}`,
16870
- url: resultUrl.href,
16871
- snippet: (text4(entry.summary) || text4(entry.snippet)).slice(0, MAX_SNIPPET_CHARS4)
16872
- });
17256
+ if (url.protocol !== "http:" && url.protocol !== "https:") continue;
17257
+ const matches = (domain) => url.hostname === domain || url.hostname.endsWith(`.${domain}`);
17258
+ if (filters.exclude.some(matches) || filters.include.length && !filters.include.some(matches)) continue;
17259
+ if (seen.has(url.href)) continue;
17260
+ seen.add(url.href);
17261
+ const title = text4(entry.name) || `Source ${results.length + 1}`;
17262
+ const content = typeof entry.content === "string" ? entry.content.trim().slice(0, 4e3) : "";
17263
+ results.push({ title, url: url.href, snippet: text4(content).slice(0, 500) });
17264
+ if (options.includeContent && content) inlineContent.push({ url: url.href, title, content, error: null });
16873
17265
  if (results.length >= numResults) break;
16874
17266
  }
16875
- if (entries.length > 0 && results.length === 0) throw new Error("DeepSeek returned invalid response: no result had an http(s) URL");
16876
- return { answer: formatSearchResultsAsAnswer(results), results };
17267
+ return { answer: formatSearchResultsAsAnswer(results), results, ...inlineContent.length ? { inlineContent } : {} };
16877
17268
  }
16878
17269
 
17270
+ // gemini-search.ts
17271
+ init_deepseek();
17272
+
16879
17273
  // kimi-search.ts
16880
17274
  init_activity();
16881
17275
  init_domain_filter_normalization();
@@ -17052,45 +17446,45 @@ init_activity();
17052
17446
  init_domain_filter_normalization();
17053
17447
  init_credential_source();
17054
17448
  init_utils();
17055
- import { existsSync as existsSync43, readFileSync as readFileSync43 } from "node:fs";
17449
+ import { existsSync as existsSync44, readFileSync as readFileSync44 } from "node:fs";
17056
17450
  var MISTRAL_CONVERSATIONS_URL = "https://api.mistral.ai/v1/conversations";
17057
- var CONFIG_PATH39 = getWebSearchConfigPath();
17451
+ var CONFIG_PATH40 = getWebSearchConfigPath();
17058
17452
  var SEARCH_TIMEOUT_MS35 = 6e4;
17059
17453
  var DEFAULT_SEARCH_MODEL = "mistral-small-latest";
17060
17454
  var DEFAULT_SEARCH_TOOL = "web_search";
17061
17455
  var MAX_RESULTS = 20;
17062
- var cachedConfig36 = null;
17063
- function loadConfig36() {
17064
- if (cachedConfig36) return cachedConfig36;
17065
- if (!existsSync43(CONFIG_PATH39)) {
17066
- cachedConfig36 = {};
17067
- return cachedConfig36;
17456
+ var cachedConfig37 = null;
17457
+ function loadConfig37() {
17458
+ if (cachedConfig37) return cachedConfig37;
17459
+ if (!existsSync44(CONFIG_PATH40)) {
17460
+ cachedConfig37 = {};
17461
+ return cachedConfig37;
17068
17462
  }
17069
- const raw = readFileSync43(CONFIG_PATH39, "utf-8");
17463
+ const raw = readFileSync44(CONFIG_PATH40, "utf-8");
17070
17464
  let parsed;
17071
17465
  try {
17072
17466
  parsed = JSON.parse(raw);
17073
17467
  } catch (err) {
17074
17468
  const message = err instanceof Error ? err.message : String(err);
17075
- throw new Error(`Failed to parse ${CONFIG_PATH39}: ${message}`);
17469
+ throw new Error(`Failed to parse ${CONFIG_PATH40}: ${message}`);
17076
17470
  }
17077
17471
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
17078
- throw new Error(`Invalid config in ${CONFIG_PATH39}: expected a JSON object`);
17472
+ throw new Error(`Invalid config in ${CONFIG_PATH40}: expected a JSON object`);
17079
17473
  }
17080
- cachedConfig36 = parsed;
17081
- return cachedConfig36;
17474
+ cachedConfig37 = parsed;
17475
+ return cachedConfig37;
17082
17476
  }
17083
17477
  function resolveSearchModel(value) {
17084
17478
  if (value === void 0) return DEFAULT_SEARCH_MODEL;
17085
17479
  if (typeof value !== "string" || value.trim().length === 0) {
17086
- throw new Error(`mistralSearchModel in ${CONFIG_PATH39} must be a non-empty string`);
17480
+ throw new Error(`mistralSearchModel in ${CONFIG_PATH40} must be a non-empty string`);
17087
17481
  }
17088
17482
  return value.trim();
17089
17483
  }
17090
17484
  function resolveSearchTool(value) {
17091
17485
  if (value === void 0) return DEFAULT_SEARCH_TOOL;
17092
17486
  if (value !== "web_search" && value !== "web_search_premium") {
17093
- throw new Error(`mistralSearchTool in ${CONFIG_PATH39} must be either web_search or web_search_premium`);
17487
+ throw new Error(`mistralSearchTool in ${CONFIG_PATH40} must be either web_search or web_search_premium`);
17094
17488
  }
17095
17489
  return value;
17096
17490
  }
@@ -17163,7 +17557,7 @@ function parseConversationResponse(value, options, numResults) {
17163
17557
  const answerParts = [];
17164
17558
  const results = [];
17165
17559
  const seenUrls = /* @__PURE__ */ new Set();
17166
- const domainFilters = parseDomainFilters(options.domainFilter);
17560
+ const domainFilters2 = parseDomainFilters(options.domainFilter);
17167
17561
  for (const output of outputs) {
17168
17562
  if (!output || typeof output !== "object" || Array.isArray(output)) continue;
17169
17563
  const entry = output;
@@ -17183,7 +17577,7 @@ function parseConversationResponse(value, options, numResults) {
17183
17577
  }
17184
17578
  if (part.type !== "tool_reference" || results.length >= numResults) continue;
17185
17579
  const url = normalizeResultUrl2(part.url);
17186
- if (!url || !passesDomainFilters11(url, domainFilters) || seenUrls.has(url)) continue;
17580
+ if (!url || !passesDomainFilters11(url, domainFilters2) || seenUrls.has(url)) continue;
17187
17581
  seenUrls.add(url);
17188
17582
  const title = typeof part.title === "string" && part.title.trim() ? part.title.trim() : url;
17189
17583
  const snippet = typeof part.description === "string" ? part.description : "";
@@ -17197,14 +17591,14 @@ function parseConversationResponse(value, options, numResults) {
17197
17591
  async function getApiKey26(signal) {
17198
17592
  const apiKey = await resolveCredential({
17199
17593
  provider: "Mistral",
17200
- configuredValue: loadConfig36().mistralApiKey,
17594
+ configuredValue: loadConfig37().mistralApiKey,
17201
17595
  environmentValue: process.env.MISTRAL_API_KEY,
17202
17596
  signal
17203
17597
  });
17204
17598
  if (!apiKey) {
17205
17599
  throw new Error(
17206
17600
  `Mistral API key not found. Either:
17207
- 1. Create ${CONFIG_PATH39} with { "mistralApiKey": "your-key" }
17601
+ 1. Create ${CONFIG_PATH40} with { "mistralApiKey": "your-key" }
17208
17602
  2. Set MISTRAL_API_KEY environment variable
17209
17603
  Get a key at https://console.mistral.ai/api-keys`
17210
17604
  );
@@ -17213,7 +17607,7 @@ Get a key at https://console.mistral.ai/api-keys`
17213
17607
  }
17214
17608
  function isMistralAvailable() {
17215
17609
  try {
17216
- const config = loadConfig36();
17610
+ const config = loadConfig37();
17217
17611
  resolveSearchModel(config.mistralSearchModel);
17218
17612
  resolveSearchTool(config.mistralSearchTool);
17219
17613
  return hasCredentialSource({
@@ -17226,7 +17620,7 @@ function isMistralAvailable() {
17226
17620
  }
17227
17621
  }
17228
17622
  async function searchWithMistral(query, options = {}) {
17229
- const config = loadConfig36();
17623
+ const config = loadConfig37();
17230
17624
  const model = resolveSearchModel(config.mistralSearchModel);
17231
17625
  const tool = resolveSearchTool(config.mistralSearchTool);
17232
17626
  const numResults = normalizeCount4(options.numResults);
@@ -17234,7 +17628,7 @@ async function searchWithMistral(query, options = {}) {
17234
17628
  const requestSignal15 = options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS35), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS35);
17235
17629
  const activityId = activityMonitor.logStart({ type: "api", query });
17236
17630
  try {
17237
- const response = await fetch(MISTRAL_CONVERSATIONS_URL, {
17631
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("mistralSearch", MISTRAL_CONVERSATIONS_URL, loadConfig37().mistralSearchBaseUrl), {
17238
17632
  method: "POST",
17239
17633
  headers: {
17240
17634
  Authorization: `Bearer ${apiKey}`,
@@ -17247,7 +17641,7 @@ async function searchWithMistral(query, options = {}) {
17247
17641
  tools: [{ type: tool }]
17248
17642
  }),
17249
17643
  signal: requestSignal15
17250
- });
17644
+ }, ["Authorization"]);
17251
17645
  if (!response.ok) {
17252
17646
  const errorText = redactCredential(await response.text(), apiKey);
17253
17647
  throw new Error(`Mistral API error ${response.status}: ${errorText.slice(0, 300)}`);
@@ -17278,7 +17672,7 @@ async function searchWithMistral(query, options = {}) {
17278
17672
 
17279
17673
  // gemini-search.ts
17280
17674
  init_utils();
17281
- 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"];
17675
+ 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"];
17282
17676
  var SEARCH_PROVIDERS = ["auto", "all", ...RESOLVED_SEARCH_PROVIDERS];
17283
17677
  var SearchProviderError = class extends Error {
17284
17678
  provider;
@@ -17294,18 +17688,18 @@ var SearchProviderError = class extends Error {
17294
17688
  this.causeError = cause;
17295
17689
  }
17296
17690
  };
17297
- var CONFIG_PATH40 = getWebSearchConfigPath();
17691
+ var CONFIG_PATH41 = getWebSearchConfigPath();
17298
17692
  var DEFAULT_SEARCH_MODEL2 = "gemini-3.6-flash";
17299
17693
  var ALL_SEARCH_PROVIDERS = ["searxng", "openai", "exa", "brave", "parallel", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "serpdive", "kagi", "ollama", "perplexity", "gemini", "bocha"];
17300
17694
  var VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported"];
17301
17695
  var cachedSearchConfig = null;
17302
17696
  function getSearchConfig() {
17303
17697
  if (cachedSearchConfig) return cachedSearchConfig;
17304
- if (!existsSync44(CONFIG_PATH40)) {
17698
+ if (!existsSync45(CONFIG_PATH41)) {
17305
17699
  cachedSearchConfig = { searchProvider: "auto", searchProviderConfigured: false };
17306
17700
  return cachedSearchConfig;
17307
17701
  }
17308
- const rawText = readFileSync44(CONFIG_PATH40, "utf-8");
17702
+ const rawText = readFileSync45(CONFIG_PATH41, "utf-8");
17309
17703
  let raw;
17310
17704
  try {
17311
17705
  const parsed = JSON.parse(rawText);
@@ -17315,25 +17709,25 @@ function getSearchConfig() {
17315
17709
  raw = parsed;
17316
17710
  } catch (err) {
17317
17711
  const message = err instanceof Error ? err.message : String(err);
17318
- throw new Error(`Failed to parse ${CONFIG_PATH40}: ${message}`);
17712
+ throw new Error(`Failed to parse ${CONFIG_PATH41}: ${message}`);
17319
17713
  }
17320
17714
  const searchModel = normalizeSearchModel(raw.searchModel);
17321
17715
  const webSearch = raw.webSearch;
17322
17716
  if (webSearch !== void 0 && (!webSearch || typeof webSearch !== "object" || Array.isArray(webSearch))) {
17323
- throw new Error(`webSearch in ${CONFIG_PATH40} must be an object`);
17717
+ throw new Error(`webSearch in ${CONFIG_PATH41} must be an object`);
17324
17718
  }
17325
- const allowedProviders = webSearch && Object.hasOwn(webSearch, "allowedProviders") ? normalizeResolvedProviderList(webSearch.allowedProviders, `webSearch.allowedProviders in ${CONFIG_PATH40}`) : void 0;
17719
+ const allowedProviders = webSearch && Object.hasOwn(webSearch, "allowedProviders") ? normalizeResolvedProviderList(webSearch.allowedProviders, `webSearch.allowedProviders in ${CONFIG_PATH41}`) : void 0;
17326
17720
  const searchProviderConfigured = Object.hasOwn(raw, "searchProvider") || Object.hasOwn(raw, "provider");
17327
- const searchProvider = normalizeSearchProviderSelection(raw.searchProvider ?? raw.provider, `provider in ${CONFIG_PATH40}`);
17721
+ const searchProvider = normalizeSearchProviderSelection(raw.searchProvider ?? raw.provider, `provider in ${CONFIG_PATH41}`);
17328
17722
  const searchRouting = Object.hasOwn(raw, "searchRouting") ? normalizeSearchRouting(raw.searchRouting) : void 0;
17329
17723
  if (allowedProviders) {
17330
17724
  if (Object.hasOwn(raw, "searchProvider")) {
17331
- assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.searchProvider), `searchProvider in ${CONFIG_PATH40}`, allowedProviders);
17725
+ assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.searchProvider), `searchProvider in ${CONFIG_PATH41}`, allowedProviders);
17332
17726
  }
17333
17727
  if (Object.hasOwn(raw, "provider")) {
17334
- assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.provider), `provider in ${CONFIG_PATH40}`, allowedProviders);
17728
+ assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.provider), `provider in ${CONFIG_PATH41}`, allowedProviders);
17335
17729
  }
17336
- if (searchRouting) assertSearchProviderSelectionAllowed(searchRouting.providers, `searchRouting.providers in ${CONFIG_PATH40}`, allowedProviders);
17730
+ if (searchRouting) assertSearchProviderSelectionAllowed(searchRouting.providers, `searchRouting.providers in ${CONFIG_PATH41}`, allowedProviders);
17337
17731
  }
17338
17732
  cachedSearchConfig = {
17339
17733
  searchProvider,
@@ -17346,21 +17740,21 @@ function getSearchConfig() {
17346
17740
  }
17347
17741
  function normalizeSearchRouting(value) {
17348
17742
  if (!value || typeof value !== "object" || Array.isArray(value)) {
17349
- throw new Error(`searchRouting in ${CONFIG_PATH40} must be an object`);
17743
+ throw new Error(`searchRouting in ${CONFIG_PATH41} must be an object`);
17350
17744
  }
17351
17745
  const raw = value;
17352
- const providers = normalizeResolvedProviderList(raw.providers, `searchRouting.providers in ${CONFIG_PATH40}`);
17746
+ const providers = normalizeResolvedProviderList(raw.providers, `searchRouting.providers in ${CONFIG_PATH41}`);
17353
17747
  const useCurrentModel = raw.useCurrentModel;
17354
17748
  if (useCurrentModel !== void 0 && typeof useCurrentModel !== "boolean") {
17355
- throw new Error(`searchRouting.useCurrentModel in ${CONFIG_PATH40} must be a boolean`);
17749
+ throw new Error(`searchRouting.useCurrentModel in ${CONFIG_PATH41} must be a boolean`);
17356
17750
  }
17357
17751
  if (!Array.isArray(raw.fallbackOn) || raw.fallbackOn.length === 0) {
17358
- throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH40} must be a non-empty array`);
17752
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH41} must be a non-empty array`);
17359
17753
  }
17360
17754
  const fallbackOn = [];
17361
17755
  for (const kind of raw.fallbackOn) {
17362
17756
  if (typeof kind !== "string" || !VALID_ROUTING_KINDS.includes(kind)) {
17363
- throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH40} may only contain transient, quota, network, invalid-response, or unsupported`);
17757
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH41} may only contain transient, quota, network, invalid-response, or unsupported`);
17364
17758
  }
17365
17759
  if (!fallbackOn.includes(kind)) {
17366
17760
  fallbackOn.push(kind);
@@ -17467,7 +17861,7 @@ function classifyProviderError(provider, err) {
17467
17861
  const lower = message.toLowerCase();
17468
17862
  const status = providerErrorStatus(message);
17469
17863
  const openAIStreamError = provider === "openai" && lower.includes("openai api stream error");
17470
- const text5 = openAIStreamError ? lower.replace(/_/g, " ") : lower;
17864
+ const text6 = openAIStreamError ? lower.replace(/_/g, " ") : lower;
17471
17865
  let kind = "unknown";
17472
17866
  const mentionsUnsupportedWebSearch = /(?:web[_ -]?search|web[_ -]?search_preview|(?:the )?tool)\b.*\b(?:unsupported|not supported|does not support|doesn't support|unknown|unrecognized|unavailable|not found)|\b(?:unsupported|not supported|does not support|doesn't support|unknown|unrecognized|unavailable|not found)\b.*\b(?:web[_ -]?search|web[_ -]?search_preview|(?:the )?tool)/i.test(lower);
17473
17867
  if (err instanceof CredentialResolutionError || /(?:api )?key (?:not found|missing)|credential resolution/.test(lower)) {
@@ -17488,19 +17882,19 @@ function classifyProviderError(provider, err) {
17488
17882
  kind = "quota";
17489
17883
  } else if (status !== void 0 && (status === 408 || status === 425 || status >= 500)) {
17490
17884
  kind = "transient";
17491
- } else if (/rate limit|quota|too many requests/.test(text5) || openAIStreamError && /usage limit/.test(text5)) {
17885
+ } else if (/rate limit|quota|too many requests/.test(text6) || openAIStreamError && /usage limit/.test(text6)) {
17492
17886
  kind = "quota";
17493
- } else if (/unauthorized|forbidden|permission denied/.test(text5) || openAIStreamError && /authentication error|permission error|invalid api key/.test(text5)) {
17887
+ } else if (/unauthorized|forbidden|permission denied/.test(text6) || openAIStreamError && /authentication error|permission error|invalid api key/.test(text6)) {
17494
17888
  kind = "auth";
17495
- } else if (/bad request|invalid request/.test(text5)) {
17889
+ } else if (/bad request|invalid request/.test(text6)) {
17496
17890
  kind = "invalid-request";
17497
- } else if (/invalid json|no parseable response|no parseable results|invalid response|returned empty response|no web_search_call/.test(text5)) {
17891
+ } else if (/invalid json|no parseable response|no parseable results|invalid response|returned empty response|no web_search_call/.test(text6)) {
17498
17892
  kind = "invalid-response";
17499
- } else if (/temporar|service unavailable|server error/.test(text5) || openAIStreamError && /internal error|\bapi error|overloaded/.test(text5)) {
17893
+ } else if (/temporar|service unavailable|server error/.test(text6) || openAIStreamError && /internal error|\bapi error|overloaded/.test(text6)) {
17500
17894
  kind = "transient";
17501
- } else if (err instanceof TypeError || /fetch failed|network|econnreset|econnrefused|enotfound|etimedout|timed out|socket/.test(text5)) {
17895
+ } else if (err instanceof TypeError || /fetch failed|network|econnreset|econnrefused|enotfound|etimedout|timed out|socket/.test(text6)) {
17502
17896
  kind = "network";
17503
- } else if (/invalid or missing|invalid config|failed to parse|must be an? |configuration/.test(text5)) {
17897
+ } else if (/invalid or missing|invalid config|failed to parse|must be an? |configuration/.test(text6)) {
17504
17898
  kind = "config";
17505
17899
  } else if (openAIStreamError) {
17506
17900
  kind = "invalid-response";
@@ -17540,6 +17934,7 @@ async function searchWithResolvedProvider(provider, query, options, useCurrentMo
17540
17934
  if (provider === "valyu") return { ...await searchWithValyu(query, options), provider };
17541
17935
  if (provider === "keenable") return { ...await searchWithKeenable(query, options), provider };
17542
17936
  if (provider === "ceramic") return { ...await searchWithCeramic(query, options), provider };
17937
+ if (provider === "linkup") return { ...await searchWithLinkup(query, options), provider };
17543
17938
  if (provider === "deepseek") return { ...await searchWithDeepSeek(query, options), provider };
17544
17939
  if (provider === "xcrawl") return { ...await searchWithXCrawl(query, options), provider };
17545
17940
  if (provider === "perplexity") return { ...await searchWithPerplexity(query, options), provider };
@@ -17552,7 +17947,7 @@ async function searchWithResolvedProvider(provider, query, options, useCurrentMo
17552
17947
  if (result2) return { ...result2, provider };
17553
17948
  throw new Error(
17554
17949
  `Gemini search unavailable. Either:
17555
- 1. Configure geminiApiKey in ${CONFIG_PATH40} or set GEMINI_API_KEY
17950
+ 1. Configure geminiApiKey in ${CONFIG_PATH41} or set GEMINI_API_KEY
17556
17951
  2. Set GOOGLE_GEMINI_BASE_URL + CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing
17557
17952
  3. Set geminiAuth to "adc" in web-search.json with a Google Cloud ADC + project/location
17558
17953
  4. Sign into gemini.google.com in a supported Chromium-based browser`
@@ -17594,6 +17989,7 @@ async function isResolvedProviderAvailable(provider, options, useCurrentModel =
17594
17989
  if (provider === "valyu") return isValyuAvailable();
17595
17990
  if (provider === "keenable") return isKeenableAvailable();
17596
17991
  if (provider === "ceramic") return isCeramicAvailable();
17992
+ if (provider === "linkup") return isLinkupAvailable();
17597
17993
  if (provider === "deepseek") return isDeepSeekAvailable();
17598
17994
  if (provider === "xcrawl") return isXcrawlAvailable();
17599
17995
  if (provider === "perplexity") return isPerplexityAvailable();
@@ -17641,6 +18037,7 @@ function providerLabel(provider) {
17641
18037
  if (provider === "valyu") return "Valyu";
17642
18038
  if (provider === "keenable") return "Keenable";
17643
18039
  if (provider === "ceramic") return "Ceramic";
18040
+ if (provider === "linkup") return "Linkup";
17644
18041
  if (provider === "deepseek") return "DeepSeek";
17645
18042
  return provider.charAt(0).toUpperCase() + provider.slice(1);
17646
18043
  }
@@ -17650,14 +18047,14 @@ async function searchWithAllProvider(provider, query, options) {
17650
18047
  if (result) return { ...result, provider };
17651
18048
  throw new Error("Gemini API search returned no results.");
17652
18049
  }
17653
- async function searchWithProviders(query, options, selectedProviders) {
18050
+ async function searchWithProviders(query, options, selectedProviders, routing) {
17654
18051
  const allowed = getAllowedSearchProviders();
17655
18052
  const providers = selectedProviders ?? (await Promise.all(ALL_SEARCH_PROVIDERS.filter((provider) => allowed.includes(provider)).map(async (provider) => ({
17656
18053
  provider,
17657
18054
  available: provider === "gemini" ? isGeminiApiAvailable() : await isResolvedProviderAvailable(provider, options)
17658
18055
  })))).filter((entry) => entry.available).map((entry) => entry.provider);
17659
18056
  if (providers.length === 0) {
17660
- 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, and DeepSeek are excluded.');
18057
+ 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.');
17661
18058
  }
17662
18059
  const settled = await Promise.allSettled(
17663
18060
  providers.map((provider) => selectedProviders ? searchWithResolvedProvider(provider, query, options) : searchWithAllProvider(provider, query, options))
@@ -17675,8 +18072,20 @@ async function searchWithProviders(query, options, selectedProviders) {
17675
18072
  }
17676
18073
  if (successes.length === 0) {
17677
18074
  const label = selectedProviders ? "Selected-provider" : "All-provider";
17678
- throw new Error(`${label} search failed:
17679
- - ${failures.map(({ provider, error }) => `${providerLabel(provider)}: ${error}`).join("\n - ")}`);
18075
+ const failureMessage = `${label} search failed:
18076
+ - ${failures.map(({ provider, error }) => `${providerLabel(provider)}: ${error}`).join("\n - ")}`;
18077
+ if (!routing || !settled.every((outcome, index) => outcome.status === "rejected" && routing.fallbackOn.includes(classifyProviderError(providers[index], outcome.reason).kind))) {
18078
+ throw new Error(failureMessage);
18079
+ }
18080
+ const untried = routing.providers.filter((provider) => !providers.includes(provider));
18081
+ try {
18082
+ if (untried.length === 0) throw new Error("Configured search routing has no untried providers");
18083
+ return await searchWithConfiguredRouting(query, options, { ...routing, providers: untried });
18084
+ } catch (err) {
18085
+ if (isAbortError2(err)) throw err;
18086
+ throw new Error(`${failureMessage}
18087
+ ${errorMessage28(err)}`);
18088
+ }
17680
18089
  }
17681
18090
  const results = [];
17682
18091
  const seenResultUrls = /* @__PURE__ */ new Set();
@@ -17741,7 +18150,9 @@ async function search(query, options = {}) {
17741
18150
  const provider = options.provider === void 0 || options.provider === "auto" ? config.searchProvider : options.provider;
17742
18151
  assertSearchProviderSelectionAllowed(provider, "Requested provider");
17743
18152
  if (Array.isArray(provider)) {
17744
- return searchWithProviders(query, options, normalizeResolvedProviderList(provider, "provider"));
18153
+ const fromConfig = options.providerFromConfig === true || options.provider === void 0 || options.provider === "auto";
18154
+ const routing = fromConfig ? config.searchRouting : void 0;
18155
+ return searchWithProviders(query, options, normalizeResolvedProviderList(provider, "provider"), routing);
17745
18156
  }
17746
18157
  if (provider === "all") return searchWithProviders(query, options);
17747
18158
  if (provider !== "auto") return searchWithResolvedProvider(provider, query, options);
@@ -17808,11 +18219,11 @@ async function search(query, options = {}) {
17808
18219
  throw new Error(
17809
18220
  `No search provider available. Either:
17810
18221
  1. Use /login to sign in with a Codex subscription for OpenAI web search
17811
- 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}
18222
+ 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}
17812
18223
  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
17813
18224
  4. Set GOOGLE_GEMINI_BASE_URL with CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing
17814
18225
  5. Sign into gemini.google.com in a supported Chromium-based browser
17815
- 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, or "deepseek" for DeepSeek search`
18226
+ 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`
17816
18227
  );
17817
18228
  }
17818
18229
  async function searchWithGeminiApi(query, options = {}) {
@@ -17862,13 +18273,13 @@ async function searchWithGeminiWeb(query, options = {}) {
17862
18273
  const prompt = buildSearchPrompt2(query, options);
17863
18274
  const activityId = activityMonitor.logStart({ type: "api", query });
17864
18275
  try {
17865
- const text5 = await queryWithCookies(prompt, cookies, {
18276
+ const text6 = await queryWithCookies(prompt, cookies, {
17866
18277
  signal: options.signal,
17867
18278
  timeoutMs: 12e4
17868
18279
  });
17869
18280
  activityMonitor.logComplete(activityId, 200);
17870
- const results = extractSourceUrls(text5);
17871
- return { answer: text5, results };
18281
+ const results = extractSourceUrls(text6);
18282
+ return { answer: text6, results };
17872
18283
  } catch (err) {
17873
18284
  const message = err instanceof Error ? err.message : String(err);
17874
18285
  if (message.toLowerCase().includes("abort")) {
@@ -17957,7 +18368,7 @@ init_utils();
17957
18368
 
17958
18369
  // storage.ts
17959
18370
  init_utils();
17960
- import { closeSync as closeSync2, constants, fchmodSync, fstatSync as fstatSync2, fsyncSync, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync45, readdirSync as readdirSync3, renameSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
18371
+ import { closeSync as closeSync2, constants, fchmodSync, fstatSync as fstatSync2, fsyncSync, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync46, readdirSync as readdirSync3, renameSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
17961
18372
  import { randomBytes } from "node:crypto";
17962
18373
  import { join as join5 } from "node:path";
17963
18374
  var CACHE_TTL_MS = 60 * 60 * 1e3;
@@ -18247,7 +18658,7 @@ function readCachedFetchData(data) {
18247
18658
  const opened = openRegularFile(path);
18248
18659
  fd = opened.fd;
18249
18660
  enforceMode(fd, 384);
18250
- const parsed = JSON.parse(readFileSync45(fd, "utf8"));
18661
+ const parsed = JSON.parse(readFileSync46(fd, "utf8"));
18251
18662
  if (!isValidStoredData(parsed) || parsed.type !== "fetch" || parsed.id !== data.id || !isInlineFetchData(parsed)) {
18252
18663
  return unavailableFetchData(data, "Cached fetched content is invalid");
18253
18664
  }
@@ -18427,6 +18838,7 @@ function buildProviderButtons(available, selected, hasInitialQueries) {
18427
18838
  { value: "valyu", label: "Valyu", available: available.valyu },
18428
18839
  { value: "keenable", label: "Keenable", available: available.keenable },
18429
18840
  { value: "ceramic", label: "Ceramic", available: available.ceramic },
18841
+ { value: "linkup", label: "Linkup", available: available.linkup },
18430
18842
  { value: "deepseek", label: "DeepSeek", available: available.deepseek }
18431
18843
  ];
18432
18844
  return providers.filter((p) => p.available).map((p) => {
@@ -19837,7 +20249,7 @@ var SCRIPT = `(function() {
19837
20249
  var token = DATA.sessionToken;
19838
20250
  var timeoutSec = DATA.timeout;
19839
20251
  var queries = Array.isArray(DATA.queries) ? DATA.queries : [];
19840
- var providers = ["auto", "all", "openai", "exa", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "serpdive", "kagi", "bocha", "ollama", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "anysearch", "xcrawl", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "baizhi", "you", "zai", "keenable", "ceramic", "deepseek"];
20252
+ var providers = ["auto", "all", "openai", "exa", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "serpdive", "kagi", "bocha", "ollama", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "anysearch", "xcrawl", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "baizhi", "you", "zai", "keenable", "ceramic", "deepseek", "linkup"];
19841
20253
  var availProviders = DATA.availableProviders && typeof DATA.availableProviders === "object" ? DATA.availableProviders : {};
19842
20254
  var workflow = "summary-review";
19843
20255
  var initialDefaultProvider = typeof DATA.defaultProvider === "string" ? DATA.defaultProvider : "exa";
@@ -20079,6 +20491,7 @@ var SCRIPT = `(function() {
20079
20491
  if (provider === "valyu") return "Valyu";
20080
20492
  if (provider === "keenable") return "Keenable";
20081
20493
  if (provider === "ceramic") return "Ceramic";
20494
+ if (provider === "linkup") return "Linkup";
20082
20495
  if (provider === "deepseek") return "DeepSeek";
20083
20496
  return "Unknown";
20084
20497
  }
@@ -22193,6 +22606,7 @@ function startCuratorServer(options, callbacks) {
22193
22606
  if (provider === "valyu") return availableProviders.valyu;
22194
22607
  if (provider === "keenable") return availableProviders.keenable;
22195
22608
  if (provider === "ceramic") return availableProviders.ceramic;
22609
+ if (provider === "linkup") return availableProviders.linkup;
22196
22610
  if (provider === "deepseek") return availableProviders.deepseek;
22197
22611
  return false;
22198
22612
  }
@@ -22632,8 +23046,8 @@ var PREFERRED_SUMMARY_MODELS = [
22632
23046
  { provider: "deepseek", id: "deepseek-v4-flash" }
22633
23047
  ];
22634
23048
  var SUMMARY_GENERATION_DEADLINE_MS = 3e4;
22635
- function estimateTokens(text5) {
22636
- const trimmed = text5.trim();
23049
+ function estimateTokens(text6) {
23050
+ const trimmed = text6.trim();
22637
23051
  if (trimmed.length === 0) return 0;
22638
23052
  return Math.max(1, Math.ceil(trimmed.length / 4));
22639
23053
  }
@@ -22658,10 +23072,10 @@ Error: ${result.error}`;
22658
23072
  for (let i = 0; i < result.results.length; i++) {
22659
23073
  const source = result.results[i];
22660
23074
  lines.push(`${i + 1}. ${source.title} \u2014 ${source.url}`);
22661
- const text5 = (source.snippet ?? "").replace(/\s+/g, " ").trim();
23075
+ const text6 = (source.snippet ?? "").replace(/\s+/g, " ").trim();
22662
23076
  const limit = Math.min(perSource, budgetLeft);
22663
- if (!text5 || limit <= 0) continue;
22664
- const snippet = text5.length <= limit ? text5 : `${text5.slice(0, limit - 1)}\u2026`;
23077
+ if (!text6 || limit <= 0) continue;
23078
+ const snippet = text6.length <= limit ? text6 : `${text6.slice(0, limit - 1)}\u2026`;
22665
23079
  budgetLeft -= snippet.length;
22666
23080
  lines.push(` ${snippet}`);
22667
23081
  }
@@ -22702,12 +23116,12 @@ function buildSummaryPrompt(results, feedback, instructions) {
22702
23116
  return sections.join("\n");
22703
23117
  }
22704
23118
  function buildDeterministicAnswerPreview(answer) {
22705
- let text5 = answer.replace(/\s+/g, " ").trim();
22706
- if (text5.length === 0) return "";
22707
- const sourceMarker = text5.search(/\bSources?\s*:/i);
22708
- if (sourceMarker >= 0) text5 = text5.slice(0, sourceMarker).trim();
22709
- if (text5.length === 0) return "";
22710
- return text5.length > 240 ? `${text5.slice(0, 237)}...` : text5;
23119
+ let text6 = answer.replace(/\s+/g, " ").trim();
23120
+ if (text6.length === 0) return "";
23121
+ const sourceMarker = text6.search(/\bSources?\s*:/i);
23122
+ if (sourceMarker >= 0) text6 = text6.slice(0, sourceMarker).trim();
23123
+ if (text6.length === 0) return "";
23124
+ return text6.length > 240 ? `${text6.slice(0, 237)}...` : text6;
22711
23125
  }
22712
23126
  function buildDeterministicSummaryLines(results) {
22713
23127
  if (results.length === 0) {
@@ -22946,7 +23360,7 @@ async function generateSummaryDraft(results, ctx, signal, modelOverride, feedbac
22946
23360
  throw new Error("Aborted");
22947
23361
  }
22948
23362
  const contentParts = Array.isArray(response.content) ? response.content : [];
22949
- const summary = contentParts.map((part) => getTextFromContentPart(part)).filter((text5) => text5.trim().length > 0).join("\n").trim();
23363
+ const summary = contentParts.map((part) => getTextFromContentPart(part)).filter((text6) => text6.trim().length > 0).join("\n").trim();
22950
23364
  if (summary.length === 0) {
22951
23365
  const partTypes = contentParts.map((part) => getContentPartType(part));
22952
23366
  const typesLabel = partTypes.length > 0 ? partTypes.join(", ") : "none";
@@ -22992,7 +23406,7 @@ import { randomUUID as randomUUID3 } from "node:crypto";
22992
23406
  import { execFileSync as execFileSync3, spawn as spawn3 } from "node:child_process";
22993
23407
  import { createRequire } from "node:module";
22994
23408
  import { platform } from "node:os";
22995
- import { existsSync as existsSync57, readFileSync as readFileSync58, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3 } from "node:fs";
23409
+ import { existsSync as existsSync58, readFileSync as readFileSync59, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3 } from "node:fs";
22996
23410
  import { join as join8 } from "node:path";
22997
23411
  init_gemini_api();
22998
23412
  init_gemini_web();
@@ -23028,10 +23442,11 @@ init_querit();
23028
23442
  init_firecrawl();
23029
23443
  init_kagi();
23030
23444
  init_ollama();
23445
+ init_deepseek();
23031
23446
 
23032
23447
  // render-search-error.ts
23033
- function truncate(text5, max) {
23034
- return text5.length > max ? text5.slice(0, max - 1) + "\u2026" : text5;
23448
+ function truncate(text6, max) {
23449
+ return text6.length > max ? text6.slice(0, max - 1) + "\u2026" : text6;
23035
23450
  }
23036
23451
  function buildSearchErrorPlan(details) {
23037
23452
  if (!details || !details.error && !details.cancelled) {
@@ -23269,7 +23684,7 @@ function registerWebToolActivation(pi, tools, mode) {
23269
23684
  }
23270
23685
 
23271
23686
  // web-tool-core.ts
23272
- import { existsSync as existsSync56, readFileSync as readFileSync57 } from "node:fs";
23687
+ import { existsSync as existsSync57, readFileSync as readFileSync58 } from "node:fs";
23273
23688
  import pLimit2 from "p-limit";
23274
23689
  init_auth_fetch();
23275
23690
 
@@ -23299,8 +23714,8 @@ function editDistanceWithin(left, right, maximum) {
23299
23714
  }
23300
23715
  return previous[right.length] <= maximum;
23301
23716
  }
23302
- function literalMatches(text5, query, caseInsensitive) {
23303
- const haystack = caseInsensitive ? text5.toLocaleLowerCase() : text5;
23717
+ function literalMatches(text6, query, caseInsensitive) {
23718
+ const haystack = caseInsensitive ? text6.toLocaleLowerCase() : text6;
23304
23719
  const needle = caseInsensitive ? query.toLocaleLowerCase() : query;
23305
23720
  const matches = [];
23306
23721
  for (let start = haystack.indexOf(needle); start >= 0; start = haystack.indexOf(needle, start + Math.max(needle.length, 1))) {
@@ -23308,12 +23723,12 @@ function literalMatches(text5, query, caseInsensitive) {
23308
23723
  }
23309
23724
  return matches;
23310
23725
  }
23311
- function fuzzyMatches(text5, query) {
23726
+ function fuzzyMatches(text6, query) {
23312
23727
  const queryTokens = normalize2(query).match(/[\p{L}\p{N}]+/gu) ?? [];
23313
23728
  if (queryTokens.length === 0) return [];
23314
23729
  const matches = [];
23315
23730
  const paragraphs = /[^\n]+(?:\n(?!\n)[^\n]+)*/g;
23316
- for (const paragraph of text5.matchAll(paragraphs)) {
23731
+ for (const paragraph of text6.matchAll(paragraphs)) {
23317
23732
  const paragraphText = paragraph[0];
23318
23733
  if (paragraphText.trim().length === 0 || paragraph.index === void 0) continue;
23319
23734
  const tokens = [...paragraphText.matchAll(/[\p{L}\p{N}]+/gu)];
@@ -23372,10 +23787,10 @@ function upperBound(values, target) {
23372
23787
  }
23373
23788
  return low;
23374
23789
  }
23375
- function findContent(text5, queries, mode) {
23790
+ function findContent(text6, queries, mode) {
23376
23791
  const normalizedQueries = [...new Set(queries.map((query) => query.trim()).filter(Boolean))];
23377
23792
  const occurrences = normalizedQueries.map((query) => {
23378
- const matches2 = mode === "fuzzy" ? fuzzyMatches(text5, query) : literalMatches(text5, query, mode === "case-insensitive");
23793
+ const matches2 = mode === "fuzzy" ? fuzzyMatches(text6, query) : literalMatches(text6, query, mode === "case-insensitive");
23379
23794
  return { query, matches: matches2, starts: matches2.map((match) => match.start), ends: matches2.map((match) => match.end) };
23380
23795
  });
23381
23796
  const matches = occurrences.flatMap((result) => result.matches);
@@ -23387,7 +23802,7 @@ function findContent(text5, queries, mode) {
23387
23802
  id: `Q${index + 1}`,
23388
23803
  order: index
23389
23804
  }));
23390
- const whitespaceRuns = [...text5.matchAll(/\s+/g)].map((run) => ({ start: run.index, end: run.index + run[0].length }));
23805
+ const whitespaceRuns = [...text6.matchAll(/\s+/g)].map((run) => ({ start: run.index, end: run.index + run[0].length }));
23391
23806
  const whitespaceStarts = whitespaceRuns.map((run) => run.start);
23392
23807
  const whitespaceEnds = whitespaceRuns.map((run) => run.end);
23393
23808
  const whitespaceSavings = [0];
@@ -23420,7 +23835,7 @@ function findContent(text5, queries, mode) {
23420
23835
  const counts = rangeCounts(range);
23421
23836
  if (counts.length === 0) continue;
23422
23837
  const labelsLength = counts.reduce((total, result) => total + (overflow ? result.id.length : result.query.length + 2) + 2 + String(result.count).length, 2 * (counts.length - 1));
23423
- const snippetLength = normalizedLength(range.start, range.end) + (range.start > 0 ? 1 : 0) + (range.end < text5.length ? 1 : 0);
23838
+ const snippetLength = normalizedLength(range.start, range.end) + (range.start > 0 ? 1 : 0) + (range.end < text6.length ? 1 : 0);
23424
23839
  length += 2 + String(index + 1).length + 2 + labelsLength + 1 + snippetLength;
23425
23840
  returnedMatches += counts.reduce((total, result) => total + result.count, 0);
23426
23841
  }
@@ -23437,8 +23852,8 @@ function findContent(text5, queries, mode) {
23437
23852
  const contained = rangeCounts(range);
23438
23853
  if (contained.length === 0) continue;
23439
23854
  const prefix = range.start > 0 ? "\u2026" : "";
23440
- const suffix = range.end < text5.length ? "\u2026" : "";
23441
- const snippet = `${prefix}${text5.slice(range.start, range.end).replace(/[\uD800-\uDFFF]/gu, "\uFFFD").replace(/\s+/g, " ").trim()}${suffix}`;
23855
+ const suffix = range.end < text6.length ? "\u2026" : "";
23856
+ const snippet = `${prefix}${text6.slice(range.start, range.end).replace(/[\uD800-\uDFFF]/gu, "\uFFFD").replace(/\s+/g, " ").trim()}${suffix}`;
23442
23857
  const counts = contained.map((result) => `${overflow ? result.id : `"${result.query}"`} \xD7${result.count}`).join(", ");
23443
23858
  sections.push(`${index + 1}. ${counts}
23444
23859
  ${snippet}`);
@@ -23449,18 +23864,18 @@ ${snippet}`);
23449
23864
  if (returnedMatches < matches.length) sections.push(`Showing ${returnedMatches} of ${matches.length} matches.`);
23450
23865
  return { text: sections.join("\n\n"), matchCount: matches.length, returnedMatches, queryResults };
23451
23866
  }
23452
- const fullRanges = contextRanges(text5.length, matches);
23867
+ const fullRanges = contextRanges(text6.length, matches);
23453
23868
  const full = measure(fullRanges);
23454
23869
  if (full.returnedMatches === matches.length && full.length <= MAX_OUTPUT_CHARS) return formatRanges(fullRanges);
23455
23870
  let ranges = [];
23456
23871
  let omitted = matchingQueries.map((result) => result.id);
23457
23872
  if (measure(ranges, true, omitted).length > MAX_OUTPUT_CHARS) {
23458
- const text6 = `${heading}
23873
+ const text7 = `${heading}
23459
23874
 
23460
23875
  Unable to format bounded excerpts: query metadata exceeds ${MAX_OUTPUT_CHARS} characters.
23461
23876
 
23462
23877
  Showing 0 of ${matches.length} matches.`;
23463
- return { text: text6, matchCount: matches.length, returnedMatches: 0, queryResults };
23878
+ return { text: text7, matchCount: matches.length, returnedMatches: 0, queryResults };
23464
23879
  }
23465
23880
  const witnesses = [];
23466
23881
  for (const { id, matches: queryMatches } of matchingQueries) {
@@ -23486,7 +23901,7 @@ Showing 0 of ${matches.length} matches.`;
23486
23901
  for (const witness of witnesses) {
23487
23902
  const proposed = mergeRanges([...ranges, {
23488
23903
  start: Math.max(0, witness.start - CONTEXT_CHARS),
23489
- end: Math.min(text5.length, witness.end + CONTEXT_CHARS)
23904
+ end: Math.min(text6.length, witness.end + CONTEXT_CHARS)
23490
23905
  }]);
23491
23906
  if (measure(proposed, true, omitted).length <= MAX_OUTPUT_CHARS) ranges = proposed;
23492
23907
  }
@@ -23528,8 +23943,8 @@ function classifySource(url) {
23528
23943
  if (BLOG_HOSTS.test(host) || BLOG_PATHS.test(path)) return "blog";
23529
23944
  return "unknown";
23530
23945
  }
23531
- function hashContent(text5) {
23532
- return `sha256:${createHash2("sha256").update(text5, "utf8").digest("hex")}`;
23946
+ function hashContent(text6) {
23947
+ return `sha256:${createHash2("sha256").update(text6, "utf8").digest("hex")}`;
23533
23948
  }
23534
23949
  function tokenize(value) {
23535
23950
  return [...new Set(value.toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length > 3))];
@@ -23539,10 +23954,10 @@ function extractRelevantSpans(content, hint) {
23539
23954
  const sentencePattern = /[^.!?]+(?:[.!?]+(?=\s|$)|$)/g;
23540
23955
  for (const match of content.matchAll(sentencePattern)) {
23541
23956
  const raw = match[0];
23542
- const text5 = raw.trim();
23543
- if (text5.length > 0 && text5.length <= 400) {
23544
- const start = (match.index ?? 0) + raw.indexOf(text5);
23545
- sentences.push({ text: text5, start, end: start + text5.length });
23957
+ const text6 = raw.trim();
23958
+ if (text6.length > 0 && text6.length <= 400) {
23959
+ const start = (match.index ?? 0) + raw.indexOf(text6);
23960
+ sentences.push({ text: text6, start, end: start + text6.length });
23546
23961
  }
23547
23962
  }
23548
23963
  const terms = tokenize(hint);
@@ -23665,9 +24080,9 @@ function parseConfigRoot(raw) {
23665
24080
  }
23666
24081
  return parsed;
23667
24082
  }
23668
- function loadConfig41() {
23669
- if (!existsSync56(WEB_SEARCH_CONFIG_PATH4)) return {};
23670
- return parseConfigRoot(readFileSync57(WEB_SEARCH_CONFIG_PATH4, "utf-8"));
24083
+ function loadConfig42() {
24084
+ if (!existsSync57(WEB_SEARCH_CONFIG_PATH4)) return {};
24085
+ return parseConfigRoot(readFileSync58(WEB_SEARCH_CONFIG_PATH4, "utf-8"));
23671
24086
  }
23672
24087
  var DEFAULT_TOOL_NAMES = {
23673
24088
  webSearch: "web_search",
@@ -23718,7 +24133,7 @@ function resolveRequestedProvider(requested) {
23718
24133
  assertSearchProviderSelectionAllowed(normalizedRequested, "Requested provider");
23719
24134
  return normalizedRequested;
23720
24135
  }
23721
- const config = loadConfig41();
24136
+ const config = loadConfig42();
23722
24137
  const provider = normalizeProviderInput(config.searchProvider ?? config.provider, `provider in ${WEB_SEARCH_CONFIG_PATH4}`) ?? "auto";
23723
24138
  assertSearchProviderSelectionAllowed(provider, `configured provider in ${WEB_SEARCH_CONFIG_PATH4}`);
23724
24139
  return provider;
@@ -23781,7 +24196,7 @@ function isAbortError7(err) {
23781
24196
  var DEFAULT_MAX_INLINE_CONTENT_CHARS = 3e4;
23782
24197
  var MIN_INLINE_CONTENT_CHARS = 1e3;
23783
24198
  var MAX_INLINE_CONTENT_CHARS = 2e5;
23784
- function getMaxInlineContentChars(config = loadConfig41()) {
24199
+ function getMaxInlineContentChars(config = loadConfig42()) {
23785
24200
  const value = config.maxInlineContentChars;
23786
24201
  if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value < MIN_INLINE_CONTENT_CHARS) {
23787
24202
  return DEFAULT_MAX_INLINE_CONTENT_CHARS;
@@ -23817,14 +24232,14 @@ function initialContentSlice(content, maxChars) {
23817
24232
  const lineBreak = content.lastIndexOf("\n", endOffset);
23818
24233
  if (lineBreak >= Math.floor(maxChars * 0.8)) endOffset = lineBreak + 1;
23819
24234
  }
23820
- const text5 = content.slice(0, endOffset);
24235
+ const text6 = content.slice(0, endOffset);
23821
24236
  return {
23822
- text: text5,
24237
+ text: text6,
23823
24238
  endOffset,
23824
24239
  totalBytes: Buffer.byteLength(content),
23825
24240
  totalLines: content.length === 0 ? 0 : content.split("\n").length,
23826
- shownBytes: Buffer.byteLength(text5),
23827
- shownLines: text5.length === 0 ? 0 : text5.split("\n").length
24241
+ shownBytes: Buffer.byteLength(text6),
24242
+ shownLines: text6.length === 0 ? 0 : text6.split("\n").length
23828
24243
  };
23829
24244
  }
23830
24245
  function normalizeFindQueries(value) {
@@ -23943,23 +24358,23 @@ ${r.snippet}` : ""}
23943
24358
  }
23944
24359
  return output;
23945
24360
  }
23946
- function boundSearchPresentation(text5, guidance, truncationGuidance, maxChars) {
23947
- const fullText = `${text5}${guidance}`;
24361
+ function boundSearchPresentation(text6, guidance, truncationGuidance, maxChars) {
24362
+ const fullText = `${text6}${guidance}`;
23948
24363
  if (fullText.length <= maxChars) {
23949
- return { text: fullText, truncated: false, originalChars: text5.length, returnedChars: text5.length, omittedChars: 0 };
24364
+ return { text: fullText, truncated: false, originalChars: text6.length, returnedChars: text6.length, omittedChars: 0 };
23950
24365
  }
23951
24366
  const marker = `
23952
24367
 
23953
24368
  ---
23954
24369
  [Output truncated.]${truncationGuidance}`;
23955
24370
  const prefixLength = maxChars - marker.length;
23956
- const bounded = `${text5.slice(0, prefixLength)}${marker}`;
24371
+ const bounded = `${text6.slice(0, prefixLength)}${marker}`;
23957
24372
  return {
23958
24373
  text: bounded,
23959
24374
  truncated: true,
23960
- originalChars: text5.length,
24375
+ originalChars: text6.length,
23961
24376
  returnedChars: prefixLength,
23962
- omittedChars: text5.length - prefixLength
24377
+ omittedChars: text6.length - prefixLength
23963
24378
  };
23964
24379
  }
23965
24380
  function registeredFetchToolNames(settings) {
@@ -24161,6 +24576,7 @@ Full search results are stored as responseId "${searchId}". `;
24161
24576
  const allUrls = [];
24162
24577
  const allInlineContent = [];
24163
24578
  const resolvedProvider = resolveRequestedProvider(params.provider);
24579
+ const providerFromConfig = (normalizeProviderInput(params.provider) ?? "auto") === "auto";
24164
24580
  const queryResponses = await runSearchQueries(queryList, async (query) => {
24165
24581
  signal?.throwIfAborted();
24166
24582
  onUpdate?.({
@@ -24170,6 +24586,7 @@ Full search results are stored as responseId "${searchId}". `;
24170
24586
  try {
24171
24587
  const { answer, results, inlineContent: inlineContent2, provider, providerResponses } = await search(query, {
24172
24588
  provider: resolvedProvider,
24589
+ providerFromConfig,
24173
24590
  numResults: params.numResults,
24174
24591
  recencyFilter,
24175
24592
  domainFilter: params.domainFilter,
@@ -24254,6 +24671,7 @@ Full search results are stored as responseId "${searchId}". `;
24254
24671
  try {
24255
24672
  const response = await search(query, {
24256
24673
  provider: resolveRequestedProvider(params.provider),
24674
+ providerFromConfig: (normalizeProviderInput(params.provider) ?? "auto") === "auto",
24257
24675
  numResults,
24258
24676
  recencyFilter,
24259
24677
  domainFilter,
@@ -24523,9 +24941,9 @@ ${retrievalHint}` : "\n---\nContent retrieval is not registered." : "\n---\nAuth
24523
24941
  if (params.findText !== void 0) {
24524
24942
  try {
24525
24943
  const found = findContent(serialized, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
24526
- const { text: text6, ...findDetails } = found;
24944
+ const { text: text7, ...findDetails } = found;
24527
24945
  return {
24528
- content: [{ type: "text", text: text6 }],
24946
+ content: [{ type: "text", text: text7 }],
24529
24947
  details: { responseId: artifact.id, type: "research", contentLength: serialized.length, findMode: params.findMode ?? "case-insensitive", ...findDetails }
24530
24948
  };
24531
24949
  } catch (err) {
@@ -24556,13 +24974,13 @@ ${retrievalHint}` : "\n---\nContent retrieval is not registered." : "\n---\nAuth
24556
24974
  details: { error: "Offset out of range", offset, contentLength: serialized.length }
24557
24975
  };
24558
24976
  }
24559
- const { endOffset, text: text5 } = sliceWithContinuation(serialized, offset, limit, maxInlineContentChars, (end) => `
24977
+ const { endOffset, text: text6 } = sliceWithContinuation(serialized, offset, limit, maxInlineContentChars, (end) => `
24560
24978
 
24561
24979
  ---
24562
24980
  Showing chars ${offset}-${end} of ${serialized.length}. Use ${toolNames.getSearchContent}({ responseId: "${artifact.id}", offset: ${end}, limit: ${limit} }) for the next slice.`);
24563
24981
  const hasMore = endOffset < serialized.length;
24564
24982
  return {
24565
- content: [{ type: "text", text: text5 }],
24983
+ content: [{ type: "text", text: text6 }],
24566
24984
  details: { responseId: artifact.id, type: "research", contentLength: serialized.length, offset, limit, returnedChars: endOffset - offset, nextOffset: hasMore ? endOffset : null, truncated: hasMore }
24567
24985
  };
24568
24986
  }
@@ -24603,9 +25021,9 @@ Showing chars ${offset}-${end} of ${serialized.length}. Use ${toolNames.getSearc
24603
25021
  if (params.findText !== void 0) {
24604
25022
  try {
24605
25023
  const found = findContent(fullResults, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
24606
- const { text: text6, ...findDetails } = found;
25024
+ const { text: text7, ...findDetails } = found;
24607
25025
  return {
24608
- content: [{ type: "text", text: text6 }],
25026
+ content: [{ type: "text", text: text7 }],
24609
25027
  details: { responseId: params.responseId, query: queryData.query, resultCount: queryData.results.length, contentLength: fullResults.length, findMode: params.findMode ?? "case-insensitive", ...findDetails }
24610
25028
  };
24611
25029
  } catch (err) {
@@ -24637,14 +25055,14 @@ Showing chars ${offset}-${end} of ${serialized.length}. Use ${toolNames.getSearc
24637
25055
  };
24638
25056
  }
24639
25057
  const queryIndex = data.queries.indexOf(queryData);
24640
- const { endOffset, text: text5 } = sliceWithContinuation(fullResults, offset, limit, maxInlineContentChars, (end) => `
25058
+ const { endOffset, text: text6 } = sliceWithContinuation(fullResults, offset, limit, maxInlineContentChars, (end) => `
24641
25059
 
24642
25060
  ---
24643
25061
  Showing chars ${offset}-${end} of ${fullResults.length}. Use ${toolNames.getSearchContent}({ responseId: "${params.responseId}", queryIndex: ${queryIndex}, offset: ${end}, limit: ${limit} }) for the next slice.`);
24644
25062
  const returnedChars = endOffset - offset;
24645
25063
  const hasMore = endOffset < fullResults.length;
24646
25064
  return {
24647
- content: [{ type: "text", text: text5 }],
25065
+ content: [{ type: "text", text: text6 }],
24648
25066
  details: {
24649
25067
  responseId: params.responseId,
24650
25068
  query: queryData.query,
@@ -24705,11 +25123,11 @@ Use one of the available indexes.` }],
24705
25123
  if (params.findText !== void 0) {
24706
25124
  try {
24707
25125
  const found = findContent(urlData.content, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
24708
- const { text: text6, ...findDetails } = found;
25126
+ const { text: text7, ...findDetails } = found;
24709
25127
  return {
24710
25128
  content: [{ type: "text", text: `# ${urlData.title || urlData.url}
24711
25129
 
24712
- ${text6}` }],
25130
+ ${text7}` }],
24713
25131
  details: { url: urlData.url, title: urlData.title, contentLength: urlData.content.length, findMode: params.findMode ?? "case-insensitive", ...findDetails }
24714
25132
  };
24715
25133
  } catch (err) {
@@ -24743,20 +25161,20 @@ ${text6}` }],
24743
25161
  const endOffset = pageEnd(urlData.content, offset, Math.min(offset + limit, urlData.content.length));
24744
25162
  const contentSlice = urlData.content.slice(offset, endOffset);
24745
25163
  const hasMore = endOffset < urlData.content.length;
24746
- let text5 = `# ${urlData.title || urlData.url}
25164
+ let text6 = `# ${urlData.title || urlData.url}
24747
25165
 
24748
25166
  ${contentSlice}`;
24749
25167
  if (hasMore || offset > 0) {
24750
- text5 += `
25168
+ text6 += `
24751
25169
 
24752
25170
  ---
24753
25171
  Showing chars ${offset}-${endOffset} of ${urlData.content.length}.`;
24754
25172
  if (hasMore) {
24755
- text5 += ` Use ${toolNames.getSearchContent}({ responseId: "${params.responseId}", urlIndex: ${selectedUrlIndex}, offset: ${endOffset}, limit: ${limit} }) for the next slice.`;
25173
+ text6 += ` Use ${toolNames.getSearchContent}({ responseId: "${params.responseId}", urlIndex: ${selectedUrlIndex}, offset: ${endOffset}, limit: ${limit} }) for the next slice.`;
24756
25174
  }
24757
25175
  }
24758
25176
  return {
24759
- content: [{ type: "text", text: text5 }],
25177
+ content: [{ type: "text", text: text6 }],
24760
25178
  details: {
24761
25179
  url: urlData.url,
24762
25180
  title: urlData.title,
@@ -24838,12 +25256,12 @@ function renderSearchErrorPlan(plan, expanded, theme) {
24838
25256
  }
24839
25257
  function saveConfig(updates) {
24840
25258
  let config = {};
24841
- if (existsSync57(WEB_SEARCH_CONFIG_PATH4)) {
24842
- config = parseConfigRoot(readFileSync58(WEB_SEARCH_CONFIG_PATH4, "utf-8"));
25259
+ if (existsSync58(WEB_SEARCH_CONFIG_PATH4)) {
25260
+ config = parseConfigRoot(readFileSync59(WEB_SEARCH_CONFIG_PATH4, "utf-8"));
24843
25261
  }
24844
25262
  Object.assign(config, updates);
24845
25263
  const dir = getWebSearchConfigDir();
24846
- if (!existsSync57(dir)) mkdirSync3(dir, { recursive: true });
25264
+ if (!existsSync58(dir)) mkdirSync3(dir, { recursive: true });
24847
25265
  writeFileSync3(WEB_SEARCH_CONFIG_PATH4, JSON.stringify(config, null, 2) + "\n");
24848
25266
  }
24849
25267
  var TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
@@ -24900,7 +25318,7 @@ function resolveToolNames(config) {
24900
25318
  }
24901
25319
  function loadConfigForExtensionInit() {
24902
25320
  try {
24903
- return loadConfig41();
25321
+ return loadConfig42();
24904
25322
  } catch (err) {
24905
25323
  const message = err instanceof Error ? err.message : String(err);
24906
25324
  console.error(`[pi-web-access] ${message}`);
@@ -24919,20 +25337,20 @@ function normalizeCuratorTimeoutSeconds(value) {
24919
25337
  return Math.min(normalized, MAX_CURATOR_TIMEOUT_SECONDS);
24920
25338
  }
24921
25339
  function getCuratorTimeoutSeconds() {
24922
- const source = loadConfig41();
25340
+ const source = loadConfig42();
24923
25341
  const explicit = normalizeCuratorTimeoutSeconds(source.curatorTimeoutSeconds);
24924
25342
  if (explicit !== void 0) return explicit;
24925
25343
  return resolveCuratorNetworkConfig().enabled ? DEFAULT_REMOTE_CURATOR_TIMEOUT_SECONDS : DEFAULT_CURATOR_TIMEOUT_SECONDS;
24926
25344
  }
24927
25345
  function getSummaryGenerationDeadlineMs() {
24928
- const value = loadConfig41().summaryGenerationDeadlineMs;
25346
+ const value = loadConfig42().summaryGenerationDeadlineMs;
24929
25347
  if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
24930
25348
  return SUMMARY_GENERATION_DEADLINE_MS;
24931
25349
  }
24932
25350
  return Math.min(value, MAX_SUMMARY_GENERATION_DEADLINE_MS);
24933
25351
  }
24934
25352
  function getSummaryInstructions() {
24935
- const value = loadConfig41().summaryInstructions;
25353
+ const value = loadConfig42().summaryInstructions;
24936
25354
  if (typeof value !== "string") return void 0;
24937
25355
  const trimmed = value.trim();
24938
25356
  return trimmed.length > 0 ? trimmed : void 0;
@@ -24984,6 +25402,7 @@ async function getProviderAvailability(ctx) {
24984
25402
  valyu: allowedProviders.has("valyu") && isValyuAvailable(),
24985
25403
  keenable: allowedProviders.has("keenable") && isKeenableAvailable(),
24986
25404
  ceramic: allowedProviders.has("ceramic") && isCeramicAvailable(),
25405
+ linkup: allowedProviders.has("linkup") && isLinkupAvailable(),
24987
25406
  deepseek: allowedProviders.has("deepseek") && isDeepSeekAvailable()
24988
25407
  };
24989
25408
  return {
@@ -25130,7 +25549,7 @@ function findGlimpseMjs() {
25130
25549
  try {
25131
25550
  const globalRoot = execFileSync3("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
25132
25551
  const entry = join8(globalRoot, "glimpseui", "src", "glimpse.mjs");
25133
- if (existsSync57(entry)) return entry;
25552
+ if (existsSync58(entry)) return entry;
25134
25553
  } catch {
25135
25554
  }
25136
25555
  return null;
@@ -25271,8 +25690,8 @@ function index_default(pi) {
25271
25690
  const initConfig = loadConfigForExtensionInit();
25272
25691
  const fetchModeConfig = resolveFetchModeConfig(initConfig);
25273
25692
  const toolActivation = initConfig.toolActivation ?? "auto";
25274
- if (toolActivation !== "auto" && toolActivation !== "dynamic" && toolActivation !== "eager") {
25275
- throw new Error(`toolActivation in ${WEB_SEARCH_CONFIG_PATH4} must be "auto", "dynamic", or "eager"`);
25693
+ if (toolActivation !== "auto" && toolActivation !== "dynamic" && toolActivation !== "eager" && toolActivation !== "none") {
25694
+ throw new Error(`toolActivation in ${WEB_SEARCH_CONFIG_PATH4} must be "auto", "dynamic", "eager", or "none"`);
25276
25695
  }
25277
25696
  const toolExposure = initConfig.toolExposure ?? "direct";
25278
25697
  if (toolExposure !== "direct" && toolExposure !== "deferred") {
@@ -25281,6 +25700,9 @@ function index_default(pi) {
25281
25700
  if (toolExposure === "deferred" && toolActivation === "eager") {
25282
25701
  throw new Error(`toolExposure "deferred" in ${WEB_SEARCH_CONFIG_PATH4} cannot be combined with toolActivation "eager"`);
25283
25702
  }
25703
+ if (toolActivation === "none" && toolExposure !== "deferred") {
25704
+ throw new Error(`toolActivation "none" in ${WEB_SEARCH_CONFIG_PATH4} requires toolExposure "deferred"`);
25705
+ }
25284
25706
  const allowedSearchProviders = initConfig.webSearch?.allowedProviders === void 0 ? RESOLVED_SEARCH_PROVIDERS : getAllowedSearchProviders();
25285
25707
  const allEligibleProviders = allowedSearchProviders.filter((provider) => ALL_SEARCH_PROVIDERS.includes(provider));
25286
25708
  const allExcludedProviders = allowedSearchProviders.filter((provider) => !ALL_SEARCH_PROVIDERS.includes(provider));
@@ -25499,7 +25921,7 @@ function index_default(pi) {
25499
25921
  if (summaryContext.model && currentModelValue && !seen.has(currentModelValue) && isModelInScope(summaryContext.model, summaryContext.scopedModels)) {
25500
25922
  addModel(summaryContext.model.provider, summaryContext.model.id);
25501
25923
  }
25502
- const config = loadConfig41();
25924
+ const config = loadConfig42();
25503
25925
  const configuredSummaryModel = typeof config.summaryModel === "string" ? config.summaryModel.trim() : "";
25504
25926
  const preferredDefaults = [
25505
25927
  { provider: "anthropic", id: "claude-haiku-4-5" },
@@ -25722,6 +26144,7 @@ Open manually: ${handle.url}` }],
25722
26144
  const requestedProvider = resolveCuratorSearchProvider(provider, pc.searchProvider);
25723
26145
  const response = await search(query, {
25724
26146
  provider: requestedProvider,
26147
+ providerFromConfig: requestedProvider === pc.configDefaultProvider,
25725
26148
  numResults: pc.numResults,
25726
26149
  recencyFilter: pc.recencyFilter,
25727
26150
  domainFilter: pc.domainFilter,
@@ -25780,7 +26203,7 @@ Open manually: ${handle.url}` }],
25780
26203
  shortcut: curateKey
25781
26204
  }
25782
26205
  });
25783
- if (!shouldAutoOpenCuratorBrowser(loadConfig41())) {
26206
+ if (!shouldAutoOpenCuratorBrowser(loadConfig42())) {
25784
26207
  sendCuratorFallbackUpdate("Search curator is running. Open the curator URL manually.");
25785
26208
  return;
25786
26209
  }
@@ -25926,6 +26349,7 @@ Open manually: ${handle.url}` }],
25926
26349
  const searchSignal = signal ? AbortSignal.any([signal, searchAbort.signal]) : searchAbort.signal;
25927
26350
  let cancelled = false;
25928
26351
  const requestedProvider = resolveRequestedProvider(params.provider);
26352
+ const providerFromConfig = (normalizeProviderInput(params.provider) ?? "auto") === "auto";
25929
26353
  const bootstrap = await loadCuratorBootstrap(requestedProvider, ctx, {
25930
26354
  numResults: params.numResults,
25931
26355
  recencyFilter
@@ -25958,6 +26382,7 @@ Open manually: ${handle.url}` }],
25958
26382
  availableProviders,
25959
26383
  defaultProvider,
25960
26384
  searchProvider,
26385
+ configDefaultProvider: providerFromConfig ? searchProvider : void 0,
25961
26386
  summaryModels: summaryModelChoices.summaryModels,
25962
26387
  defaultSummaryModel: summaryModelChoices.defaultSummaryModel,
25963
26388
  timeoutSeconds: curatorTimeoutSeconds,
@@ -26009,6 +26434,8 @@ Open manually: ${handle.url}` }],
26009
26434
  try {
26010
26435
  const response = await search(query, {
26011
26436
  provider: requestedProvider2,
26437
+ // A provider picked in the curator UI replaces this value and stays strict.
26438
+ providerFromConfig: requestedProvider2 === pc.configDefaultProvider,
26012
26439
  numResults: params.numResults,
26013
26440
  recencyFilter,
26014
26441
  domainFilter: params.domainFilter,
@@ -26573,7 +27000,7 @@ Open manually: ${handle.url}` }],
26573
27000
  }
26574
27001
  });
26575
27002
  }
26576
- if (toolActivation !== "eager") registerWebToolActivation(pi, [
27003
+ if (toolActivation !== "eager" && toolActivation !== "none") registerWebToolActivation(pi, [
26577
27004
  ...webSearchEnabled ? [{ name: toolNames.webSearch, capability: "search" }] : [],
26578
27005
  ...sourceCheckEnabled ? [{ name: toolNames.sourceCheck, capability: "source-check" }] : [],
26579
27006
  ...fetchContentEnabled ? [{ name: toolNames.fetchContent, capability: "fetch" }] : [],
@@ -26599,12 +27026,13 @@ Open manually: ${handle.url}` }],
26599
27026
  const initialProvider = bootstrap.defaultProvider;
26600
27027
  const curatorTimeoutSeconds = bootstrap.timeoutSeconds;
26601
27028
  let currentProvider = initialProvider;
26602
- const commandConfig = loadConfig41();
27029
+ const commandConfig = loadConfig42();
26603
27030
  const rawSearchProvider = normalizeProviderInput(
26604
27031
  commandConfig.searchProvider ?? commandConfig.provider ?? "auto",
26605
27032
  `provider in ${WEB_SEARCH_CONFIG_PATH4}`
26606
27033
  ) ?? "auto";
26607
27034
  let currentSearchProvider = Array.isArray(rawSearchProvider) ? rawSearchProvider : rawSearchProvider === "auto" ? "auto" : initialProvider;
27035
+ const configDefaultProvider = currentSearchProvider;
26608
27036
  const summaryContext = {
26609
27037
  model: ctx.model,
26610
27038
  modelRegistry: ctx.modelRegistry,
@@ -26717,6 +27145,7 @@ Open manually: ${handle.url}` }],
26717
27145
  const requestedProvider = resolveCuratorSearchProvider(provider, currentSearchProvider);
26718
27146
  const response = await search(query, {
26719
27147
  provider: requestedProvider,
27148
+ providerFromConfig: requestedProvider === configDefaultProvider,
26720
27149
  signal: searchAbort.signal,
26721
27150
  extensionContext: ctx
26722
27151
  });
@@ -26743,7 +27172,7 @@ Open manually: ${handle.url}` }],
26743
27172
  commandHandle = handle;
26744
27173
  activeCurators.set(commandCallId, handle);
26745
27174
  let browserOpenError = null;
26746
- if (!shouldAutoOpenCuratorBrowser(loadConfig41())) {
27175
+ if (!shouldAutoOpenCuratorBrowser(loadConfig42())) {
26747
27176
  ctx.ui.notify(`Search curator is running. Open manually: ${handle.url}`, "info");
26748
27177
  } else {
26749
27178
  const open = platform() === "darwin" ? await getGlimpseOpen() : null;
@@ -26787,6 +27216,7 @@ Open manually: ${handle.url}` }],
26787
27216
  try {
26788
27217
  const response = await runWithProxy(void 0, () => search(query, {
26789
27218
  provider: requestedProvider,
27219
+ providerFromConfig: requestedProvider === configDefaultProvider,
26790
27220
  signal: searchAbort.signal,
26791
27221
  extensionContext: ctx
26792
27222
  }));
@@ -26878,20 +27308,20 @@ Open manually: ${handle.url}` }],
26878
27308
  const diagnostic = getGeminiWebAvailabilityDiagnostic();
26879
27309
  const diagnosticDetails = getGeminiWebAvailabilityDiagnosticDetails();
26880
27310
  const attempted = formatCookieAttempts(diagnosticDetails?.attempts ?? []);
26881
- const text6 = diagnostic ? `Gemini Web is unavailable: ${diagnostic}${attempted ? ` Attempted browser profiles: ${attempted}.` : ""}` : "Gemini Web is unavailable. Sign into gemini.google.com in a supported Chromium-based browser.";
27311
+ const text7 = diagnostic ? `Gemini Web is unavailable: ${diagnostic}${attempted ? ` Attempted browser profiles: ${attempted}.` : ""}` : "Gemini Web is unavailable. Sign into gemini.google.com in a supported Chromium-based browser.";
26882
27312
  pi.sendMessage({
26883
27313
  customType: "google-account",
26884
- content: [{ type: "text", text: text6 }],
27314
+ content: [{ type: "text", text: text7 }],
26885
27315
  display: true,
26886
27316
  details: { available: false, cookieAccessAllowed: true, diagnostic, cookieDiagnostic: diagnosticDetails }
26887
27317
  }, { triggerTurn: true, deliverAs: "followUp" });
26888
27318
  return;
26889
27319
  }
26890
27320
  const email = await getActiveGoogleEmail(cookies);
26891
- const text5 = email ? `Active Google account: ${email}` : "Gemini Web is available, but the active Google account could not be determined.";
27321
+ const text6 = email ? `Active Google account: ${email}` : "Gemini Web is available, but the active Google account could not be determined.";
26892
27322
  pi.sendMessage({
26893
27323
  customType: "google-account",
26894
- content: [{ type: "text", text: text5 }],
27324
+ content: [{ type: "text", text: text6 }],
26895
27325
  display: true,
26896
27326
  details: { available: true, email: email ?? null }
26897
27327
  }, { triggerTurn: true, deliverAs: "followUp" });