@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
@@ -91,8 +91,8 @@ var init_activity = __esm({
91
91
  import { exec, execFile } from "node:child_process";
92
92
  import { existsSync } from "node:fs";
93
93
  import { promisify } from "node:util";
94
- function redactCredential(text5, credential) {
95
- return credential ? text5.split(credential).join("[redacted]") : text5;
94
+ function redactCredential(text6, credential) {
95
+ return credential ? text6.split(credential).join("[redacted]") : text6;
96
96
  }
97
97
  function normalize(value) {
98
98
  if (typeof value !== "string") return null;
@@ -328,8 +328,22 @@ function resolveApiBaseUrl(options) {
328
328
  url.pathname = url.pathname.replace(/\/+$/, "");
329
329
  return url.toString().replace(/\/+$/, "");
330
330
  }
331
- async function fetchWithCredentialRedirects(url, init, credentialHeaders) {
331
+ function resolveProviderApiUrl(configStem, defaultUrl, configuredValue) {
332
+ const official = new URL(defaultUrl);
333
+ const environmentKey = (PI_PREFIXED_ENVIRONMENT_STEMS.has(configStem) ? "PI_" : "") + configStem.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase() + "_BASE_URL";
334
+ const baseUrl = resolveApiBaseUrl({
335
+ configKey: configStem + "BaseUrl",
336
+ configuredValue,
337
+ defaultValue: official.origin,
338
+ environmentKey,
339
+ environmentValue: process.env[environmentKey]
340
+ });
341
+ return baseUrl + official.pathname + official.search;
342
+ }
343
+ async function fetchWithCredentialRedirects(url, init, credentialHeaders, credentialQueryParams = []) {
332
344
  let current = new URL(url);
345
+ const source = new URL(url);
346
+ for (const name of credentialQueryParams) source.searchParams.delete(name);
333
347
  let requestInit = init;
334
348
  for (let redirects = 0; ; redirects++) {
335
349
  const response = await fetch(current, { ...requestInit, redirect: "manual" });
@@ -337,7 +351,7 @@ async function fetchWithCredentialRedirects(url, init, credentialHeaders) {
337
351
  const location = response.headers.get("location");
338
352
  if (!location) return response;
339
353
  if (redirects === MAX_API_REDIRECTS) {
340
- throw new Error(`Too many API redirects from ${url}`);
354
+ throw new Error(`Too many API redirects from ${source}`);
341
355
  }
342
356
  const next = new URL(location, current);
343
357
  if (next.protocol !== "http:" && next.protocol !== "https:") {
@@ -351,6 +365,7 @@ async function fetchWithCredentialRedirects(url, init, credentialHeaders) {
351
365
  requestInit = { ...withoutBody, method: "GET", headers };
352
366
  }
353
367
  if (next.origin !== current.origin) {
368
+ for (const name of credentialQueryParams) next.searchParams.delete(name);
354
369
  const headers = new Headers(requestInit.headers);
355
370
  for (const name of credentialHeaders) headers.delete(name);
356
371
  requestInit = { ...requestInit, headers };
@@ -383,8 +398,8 @@ function isTimeoutError(err) {
383
398
  const message = err.message ?? "";
384
399
  return name === "AbortError" || code === "ETIMEDOUT" || message.toLowerCase().includes("timed out");
385
400
  }
386
- function trimErrorText(text5) {
387
- return text5.replace(/\s+/g, " ").trim().slice(0, 200);
401
+ function trimErrorText(text6) {
402
+ return text6.replace(/\s+/g, " ").trim().slice(0, 200);
388
403
  }
389
404
  function mapFfmpegError(err) {
390
405
  const { code, stderr, message } = readExecError(err);
@@ -684,9 +699,10 @@ async function fetchViaCurlOnce(url, init, proxyUrl) {
684
699
  Object.defineProperty(response, "redirected", { value: redirected, configurable: true });
685
700
  return response;
686
701
  }
687
- var cachedWebSearchConfigDir, API_REDIRECT_STATUSES, API_REQUEST_BODY_HEADERS, MAX_API_REDIRECTS, proxyStorage, CurlTransportError;
702
+ var cachedWebSearchConfigDir, PI_PREFIXED_ENVIRONMENT_STEMS, API_REDIRECT_STATUSES, API_REQUEST_BODY_HEADERS, MAX_API_REDIRECTS, proxyStorage, CurlTransportError;
688
703
  var init_utils = __esm({
689
704
  "utils.ts"() {
705
+ PI_PREFIXED_ENVIRONMENT_STEMS = /* @__PURE__ */ new Set(["ollama", "deepseek"]);
690
706
  API_REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
691
707
  API_REQUEST_BODY_HEADERS = ["Content-Encoding", "Content-Language", "Content-Location", "Content-Type"];
692
708
  MAX_API_REDIRECTS = 5;
@@ -798,10 +814,10 @@ function parseAdcFile(raw) {
798
814
  }
799
815
  return { type };
800
816
  }
801
- function parseTokenExchangeResponse(text5, context) {
817
+ function parseTokenExchangeResponse(text6, context) {
802
818
  let raw;
803
819
  try {
804
- raw = JSON.parse(text5);
820
+ raw = JSON.parse(text6);
805
821
  } catch (err) {
806
822
  const message = err instanceof Error ? err.message : String(err);
807
823
  throw new Error(`${context} returned invalid JSON: ${message}`);
@@ -848,11 +864,11 @@ async function exchangeRefreshToken(cfg, signal) {
848
864
  body,
849
865
  signal
850
866
  });
851
- const text5 = await res.text();
867
+ const text6 = await res.text();
852
868
  if (!res.ok) {
853
- throwOnTokenExchangeFailure(res, text5, res.status);
869
+ throwOnTokenExchangeFailure(res, text6, res.status);
854
870
  }
855
- return parseTokenExchangeResponse(text5, "Gemini ADC token exchange");
871
+ return parseTokenExchangeResponse(text6, "Gemini ADC token exchange");
856
872
  }
857
873
  async function exchangeServiceAccountJwt(cfg, signal) {
858
874
  if (!cfg.client_email || !cfg.private_key) {
@@ -884,11 +900,11 @@ async function exchangeServiceAccountJwt(cfg, signal) {
884
900
  body,
885
901
  signal
886
902
  });
887
- const text5 = await res.text();
903
+ const text6 = await res.text();
888
904
  if (!res.ok) {
889
- throwOnTokenExchangeFailure(res, text5, res.status);
905
+ throwOnTokenExchangeFailure(res, text6, res.status);
890
906
  }
891
- return parseTokenExchangeResponse(text5, "Gemini ADC service account token exchange");
907
+ return parseTokenExchangeResponse(text6, "Gemini ADC service account token exchange");
892
908
  }
893
909
  async function fetchMetadataToken(signal) {
894
910
  const url = `http://${getMetadataHost()}/computeMetadata/v1/instance/service-accounts/default/token`;
@@ -903,14 +919,14 @@ async function fetchMetadataToken(signal) {
903
919
  const message = err instanceof Error ? err.message : String(err);
904
920
  throw new Error(`Gemini ADC metadata server token request failed: ${message}`);
905
921
  }
906
- const text5 = await res.text();
922
+ const text6 = await res.text();
907
923
  if (!res.ok) {
908
924
  if (res.status === 401 || res.status === 403) {
909
925
  throw new CredentialResolutionError("Gemini ADC", "oauth-credential-rejected");
910
926
  }
911
- throw new Error(`Gemini ADC metadata server token request failed (HTTP ${res.status}): ${text5.slice(0, 300)}`);
927
+ throw new Error(`Gemini ADC metadata server token request failed (HTTP ${res.status}): ${text6.slice(0, 300)}`);
912
928
  }
913
- return parseTokenExchangeResponse(text5, "Gemini ADC metadata server token");
929
+ return parseTokenExchangeResponse(text6, "Gemini ADC metadata server token");
914
930
  }
915
931
  async function getAdcAccessToken(signal) {
916
932
  if (cachedToken && cachedToken.expiresAt > Date.now()) {
@@ -1057,14 +1073,14 @@ function buildAuthHeaders(apiKey = null, cloudflareApiKey = getLegacyCloudflareA
1057
1073
  if (!isCloudflareGateway()) return apiKey ? { "x-goog-api-key": apiKey } : {};
1058
1074
  return cloudflareApiKey ? { "cf-aig-authorization": `Bearer ${cloudflareApiKey}` } : {};
1059
1075
  }
1060
- function redactGeminiCredentials(text5, apiKey, cloudflareApiKey, adcToken) {
1061
- let out = redactCredential(redactCredential(text5, apiKey), cloudflareApiKey);
1076
+ function redactGeminiCredentials(text6, apiKey, cloudflareApiKey, adcToken) {
1077
+ let out = redactCredential(redactCredential(text6, apiKey), cloudflareApiKey);
1062
1078
  if (adcToken) out = redactCredential(out, adcToken);
1063
1079
  return out;
1064
1080
  }
1065
- function redactGeminiApiResponse(response, text5, apiKey, adcToken) {
1081
+ function redactGeminiApiResponse(response, text6, apiKey, adcToken) {
1066
1082
  const credentials = responseCredentials.get(response);
1067
- return redactGeminiCredentials(text5, credentials?.apiKey ?? apiKey, credentials?.cloudflareApiKey, credentials?.adcToken ?? adcToken);
1083
+ return redactGeminiCredentials(text6, credentials?.apiKey ?? apiKey, credentials?.cloudflareApiKey, credentials?.adcToken ?? adcToken);
1068
1084
  }
1069
1085
  async function fetchGeminiApi(url, init = {}, apiKey) {
1070
1086
  const parsedUrl = new URL(url);
@@ -1164,9 +1180,9 @@ async function queryGeminiApiWithInlineData(prompt, data, mimeType, options = {}
1164
1180
  }
1165
1181
  const response = await res.json();
1166
1182
  const candidate = response.candidates?.[0];
1167
- const text5 = candidate?.content?.parts?.map((part) => part.text).filter((part) => typeof part === "string" && part.length > 0).join("\n") ?? "";
1183
+ const text6 = candidate?.content?.parts?.map((part) => part.text).filter((part) => typeof part === "string" && part.length > 0).join("\n") ?? "";
1168
1184
  return {
1169
- text: text5,
1185
+ text: text6,
1170
1186
  ...candidate?.finishReason ? { finishReason: candidate.finishReason } : {},
1171
1187
  ...response.promptFeedback?.blockReason ? { blockReason: response.promptFeedback.blockReason } : {}
1172
1188
  };
@@ -1207,9 +1223,9 @@ async function queryGeminiApiWithVideo(prompt, videoUri, options = {}) {
1207
1223
  throw new Error(`Gemini API error ${res.status}: ${errorText.slice(0, 300)}`);
1208
1224
  }
1209
1225
  const data = await res.json();
1210
- const text5 = data.candidates?.[0]?.content?.parts?.map((p) => p.text).filter(Boolean).join("\n");
1211
- if (!text5) throw new Error("Gemini API returned empty response");
1212
- return text5;
1226
+ const text6 = data.candidates?.[0]?.content?.parts?.map((p) => p.text).filter(Boolean).join("\n");
1227
+ if (!text6) throw new Error("Gemini API returned empty response");
1228
+ return text6;
1213
1229
  }
1214
1230
  var DEFAULT_API_HOST, API_VERSION, API_BASE, CONFIG_PATH2, DEFAULT_MODEL, cachedConfig2, responseCredentials;
1215
1231
  var init_gemini_api = __esm({
@@ -2099,8 +2115,8 @@ Content-Type: ${file.mimeType}\r
2099
2115
  signal
2100
2116
  });
2101
2117
  if (!res.ok) {
2102
- const text5 = await res.text();
2103
- throw new Error(`File upload failed: ${res.status} (${text5.slice(0, 200)})`);
2118
+ const text6 = await res.text();
2119
+ throw new Error(`File upload failed: ${res.status} (${text6.slice(0, 200)})`);
2104
2120
  }
2105
2121
  return { id: await res.text(), name: fileName };
2106
2122
  }
@@ -2125,13 +2141,13 @@ function getNestedValue(value, pathParts) {
2125
2141
  }
2126
2142
  return current;
2127
2143
  }
2128
- function trimJsonEnvelope(text5) {
2129
- const start = text5.indexOf("[");
2130
- const end = text5.lastIndexOf("]");
2144
+ function trimJsonEnvelope(text6) {
2145
+ const start = text6.indexOf("[");
2146
+ const end = text6.lastIndexOf("]");
2131
2147
  if (start === -1 || end === -1 || end <= start) {
2132
2148
  throw new Error("Gemini response did not contain a JSON payload.");
2133
2149
  }
2134
- return text5.slice(start, end + 1);
2150
+ return text6.slice(start, end + 1);
2135
2151
  }
2136
2152
  function extractErrorCode(responseJson) {
2137
2153
  const code = getNestedValue(responseJson, [0, 5, 2, 0, 1, 0]);
@@ -2139,12 +2155,12 @@ function extractErrorCode(responseJson) {
2139
2155
  }
2140
2156
  function extractCandidateText(candidate) {
2141
2157
  const textRaw = getNestedValue(candidate, [1, 0]);
2142
- let text5 = typeof textRaw === "string" ? textRaw : "";
2143
- if (/^http:\/\/googleusercontent\.com\/card_content\/\d+/.test(text5)) {
2158
+ let text6 = typeof textRaw === "string" ? textRaw : "";
2159
+ if (/^http:\/\/googleusercontent\.com\/card_content\/\d+/.test(text6)) {
2144
2160
  const alt = getNestedValue(candidate, [22, 0]);
2145
- if (typeof alt === "string" && alt.length > 0) text5 = alt;
2161
+ if (typeof alt === "string" && alt.length > 0) text6 = alt;
2146
2162
  }
2147
- return text5;
2163
+ return text6;
2148
2164
  }
2149
2165
  function parseStreamGenerateResponse(rawText) {
2150
2166
  const responseJson = JSON.parse(trimJsonEnvelope(rawText));
@@ -2161,13 +2177,13 @@ function parseStreamGenerateResponse(rawText) {
2161
2177
  if (!Array.isArray(candidateList) || candidateList.length === 0) continue;
2162
2178
  const firstCandidate = candidateList[0];
2163
2179
  if (firstCandidateSeen === void 0) firstCandidateSeen = firstCandidate;
2164
- const text6 = extractCandidateText(firstCandidate);
2165
- if (text6.length > 0) latestNonEmptyText = text6;
2180
+ const text7 = extractCandidateText(firstCandidate);
2181
+ if (text7.length > 0) latestNonEmptyText = text7;
2166
2182
  } catch {
2167
2183
  }
2168
2184
  }
2169
- const text5 = latestNonEmptyText.length > 0 ? latestNonEmptyText : extractCandidateText(firstCandidateSeen);
2170
- return { text: text5, errorCode };
2185
+ const text6 = latestNonEmptyText.length > 0 ? latestNonEmptyText : extractCandidateText(firstCandidateSeen);
2186
+ return { text: text6, errorCode };
2171
2187
  }
2172
2188
  var GEMINI_APP_URL, GEMINI_STREAM_GENERATE_URL, GEMINI_UPLOAD_URL, GEMINI_UPLOAD_PUSH_ID, USER_AGENT, MODEL_HEADER_NAME, DEFAULT_GEMINI_WEB_MODEL, MODEL_HEADERS, REQUIRED_COOKIES, geminiFetchImpl, geminiFetchOverride, GEMINI_MAX_HEADER_SIZE;
2173
2189
  var init_gemini_web = __esm({
@@ -2263,6 +2279,7 @@ function isPerplexityAvailable() {
2263
2279
  });
2264
2280
  }
2265
2281
  async function postPerplexity(url, body, options) {
2282
+ const apiUrl = resolveProviderApiUrl("perplexity", url, loadConfig4().perplexityBaseUrl);
2266
2283
  checkRateLimit();
2267
2284
  const activityId = activityMonitor.logStart({ type: "api", query: options.activityQuery });
2268
2285
  activityMonitor.updateRateLimit({
@@ -2277,7 +2294,7 @@ async function postPerplexity(url, body, options) {
2277
2294
  const timeoutError = () => new Error("Perplexity API error 408: request timed out");
2278
2295
  let response;
2279
2296
  try {
2280
- response = await fetch(url, {
2297
+ response = await fetchWithCredentialRedirects(apiUrl, {
2281
2298
  method: "POST",
2282
2299
  headers: {
2283
2300
  Authorization: `Bearer ${apiKey}`,
@@ -2285,7 +2302,7 @@ async function postPerplexity(url, body, options) {
2285
2302
  },
2286
2303
  body: JSON.stringify(body),
2287
2304
  signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout
2288
- });
2305
+ }, ["Authorization"]);
2289
2306
  } catch (err) {
2290
2307
  if (timedOut()) {
2291
2308
  activityMonitor.logError(activityId, "request timed out");
@@ -2616,13 +2633,13 @@ function hasExtractUrlError(errors, url) {
2616
2633
  });
2617
2634
  }
2618
2635
  async function fetchAndMapExtractResult(url, body, signal) {
2619
- const data = await parallelFetch(PARALLEL_EXTRACT_URL, body, signal);
2636
+ const data = await parallelFetch(resolveProviderApiUrl("parallel", `${PARALLEL_API_BASE_URL}/v1/extract`, loadConfig8().parallelBaseUrl), body, signal);
2620
2637
  if (hasExtractUrlError(data.errors, url)) return { mapped: null, result: void 0 };
2621
2638
  const result = findExtractResult(data.results, url);
2622
2639
  return { mapped: mapExtractResult(result), result };
2623
2640
  }
2624
2641
  async function searchWithParallel(query, options = {}) {
2625
- const data = await parallelFetch(PARALLEL_SEARCH_URL, buildSearchRequestBody(query, options), options.signal);
2642
+ const data = await parallelFetch(resolveProviderApiUrl("parallel", `${PARALLEL_API_BASE_URL}/v1/search`, loadConfig8().parallelBaseUrl), buildSearchRequestBody(query, options), options.signal);
2626
2643
  const results = data.results;
2627
2644
  const response = {
2628
2645
  answer: buildAnswerFromExcerpts(results),
@@ -2646,7 +2663,7 @@ async function parallelFetch(url, body, signal) {
2646
2663
  const activityId = activityMonitor.logStart(activityContext(url, body));
2647
2664
  let response;
2648
2665
  try {
2649
- response = await fetch(url, {
2666
+ response = await fetchWithCredentialRedirects(url, {
2650
2667
  method: "POST",
2651
2668
  headers: {
2652
2669
  "x-api-key": apiKey,
@@ -2654,7 +2671,7 @@ async function parallelFetch(url, body, signal) {
2654
2671
  },
2655
2672
  body: JSON.stringify(body),
2656
2673
  signal: requestSignal2(signal)
2657
- });
2674
+ }, ["x-api-key"]);
2658
2675
  } catch (err) {
2659
2676
  const message = errorMessage(err);
2660
2677
  const redactedMessage = redactCredential(message, apiKey);
@@ -2679,15 +2696,14 @@ async function parallelFetch(url, body, signal) {
2679
2696
  throw new Error(`Parallel API returned invalid JSON: ${errorMessage(err)}`);
2680
2697
  }
2681
2698
  }
2682
- var PARALLEL_SEARCH_URL, PARALLEL_EXTRACT_URL, CONFIG_PATH8, MIN_PARALLEL_API_KEY_LENGTH, MIN_USEFUL_CONTENT, SEARCH_TIMEOUT_MS4, PLACEHOLDER_API_KEY_DENYLIST, cachedConfig8;
2699
+ var PARALLEL_API_BASE_URL, CONFIG_PATH8, MIN_PARALLEL_API_KEY_LENGTH, MIN_USEFUL_CONTENT, SEARCH_TIMEOUT_MS4, PLACEHOLDER_API_KEY_DENYLIST, cachedConfig8;
2683
2700
  var init_parallel = __esm({
2684
2701
  "parallel.ts"() {
2685
2702
  init_activity();
2686
2703
  init_domain_filter_normalization();
2687
2704
  init_credential_source();
2688
2705
  init_utils();
2689
- PARALLEL_SEARCH_URL = "https://api.parallel.ai/v1/search";
2690
- PARALLEL_EXTRACT_URL = "https://api.parallel.ai/v1/extract";
2706
+ PARALLEL_API_BASE_URL = "https://api.parallel.ai";
2691
2707
  CONFIG_PATH8 = getWebSearchConfigPath();
2692
2708
  MIN_PARALLEL_API_KEY_LENGTH = 8;
2693
2709
  MIN_USEFUL_CONTENT = 500;
@@ -2808,20 +2824,20 @@ async function callParallelMcp(toolName, args, signal) {
2808
2824
  throw new Error(`Parallel MCP error${code}: ${message}`);
2809
2825
  }
2810
2826
  if (parsed.result?.isError) {
2811
- const text6 = parsed.result.content?.find((item) => item.type === "text" && typeof item.text === "string")?.text?.trim() || "Parallel MCP returned an error";
2812
- throw new Error(apiKey ? redactCredential(text6, apiKey) : text6);
2827
+ const text7 = parsed.result.content?.find((item) => item.type === "text" && typeof item.text === "string")?.text?.trim() || "Parallel MCP returned an error";
2828
+ throw new Error(apiKey ? redactCredential(text7, apiKey) : text7);
2813
2829
  }
2814
2830
  if (parsed.result?.structuredContent && typeof parsed.result.structuredContent === "object") return parsed.result.structuredContent;
2815
- const text5 = parsed.result?.content?.find((item) => item.type === "text" && typeof item.text === "string" && item.text.trim())?.text;
2816
- if (!text5) throw new Error("Parallel MCP returned empty content");
2831
+ const text6 = parsed.result?.content?.find((item) => item.type === "text" && typeof item.text === "string" && item.text.trim())?.text;
2832
+ if (!text6) throw new Error("Parallel MCP returned empty content");
2817
2833
  try {
2818
- return JSON.parse(text5);
2834
+ return JSON.parse(text6);
2819
2835
  } catch {
2820
- return text5;
2836
+ return text6;
2821
2837
  }
2822
2838
  }
2823
- function parseTextResults(text5) {
2824
- return text5.split(/(?=^Title: )/m).flatMap((block) => {
2839
+ function parseTextResults(text6) {
2840
+ return text6.split(/(?=^Title: )/m).flatMap((block) => {
2825
2841
  const url = block.match(/^URL: (.+)/m)?.[1]?.trim();
2826
2842
  if (!url) return [];
2827
2843
  const title = block.match(/^Title: (.+)/m)?.[1]?.trim() ?? "";
@@ -3278,7 +3294,7 @@ function buildSearchBody(query, options) {
3278
3294
  async function search1APIJsonRequest(label, url, apiKey, body, timeoutMs, signal) {
3279
3295
  let response;
3280
3296
  try {
3281
- response = await fetch(url, {
3297
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("search1api", url, loadConfig10().search1apiBaseUrl), {
3282
3298
  method: "POST",
3283
3299
  headers: {
3284
3300
  Authorization: `Bearer ${apiKey}`,
@@ -3286,7 +3302,7 @@ async function search1APIJsonRequest(label, url, apiKey, body, timeoutMs, signal
3286
3302
  },
3287
3303
  body: JSON.stringify(body),
3288
3304
  signal: requestSignal5(signal, timeoutMs)
3289
- });
3305
+ }, ["Authorization"]);
3290
3306
  } catch (err) {
3291
3307
  const message = errorMessage4(err);
3292
3308
  const redactedMessage = redactCredential(message, apiKey);
@@ -3527,7 +3543,7 @@ function buildContentsBody(urls, options = {}) {
3527
3543
  async function queritJsonRequest(label, url, apiKey, body, timeoutMs, signal) {
3528
3544
  let response;
3529
3545
  try {
3530
- response = await fetch(url, {
3546
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("querit", url, loadConfig12().queritBaseUrl), {
3531
3547
  method: "POST",
3532
3548
  headers: {
3533
3549
  Authorization: `Bearer ${apiKey}`,
@@ -3536,7 +3552,7 @@ async function queritJsonRequest(label, url, apiKey, body, timeoutMs, signal) {
3536
3552
  },
3537
3553
  body: JSON.stringify(body),
3538
3554
  signal: requestSignal7(signal, timeoutMs)
3539
- });
3555
+ }, ["Authorization"]);
3540
3556
  } catch (err) {
3541
3557
  const message = errorMessage6(err);
3542
3558
  const isRequestAbort = err instanceof Error ? err.name === "AbortError" || err.name === "TimeoutError" || /abort|timeout/i.test(message) : /abort|timeout/i.test(message);
@@ -4391,8 +4407,8 @@ async function firecrawlFetch(endpoint, body, signal, options, label = endpoint,
4391
4407
  signal: requestSignal9(options?.timeoutMs ?? EXTRACT_TIMEOUT_MS, signal)
4392
4408
  }, options);
4393
4409
  if (!response.ok) {
4394
- const text5 = await response.text().catch(() => "");
4395
- throw new Error(`Firecrawl ${label} error ${response.status}: ${redactCredential(text5.slice(0, 300), apiKey)}`);
4410
+ const text6 = await response.text().catch(() => "");
4411
+ throw new Error(`Firecrawl ${label} error ${response.status}: ${redactCredential(text6.slice(0, 300), apiKey)}`);
4396
4412
  }
4397
4413
  let data;
4398
4414
  try {
@@ -4600,12 +4616,12 @@ async function searchWithKagi(query, options = {}) {
4600
4616
  const activityId = activityMonitor.logStart({ type: "api", query });
4601
4617
  let response;
4602
4618
  try {
4603
- response = await fetch(KAGI_SEARCH_URL, {
4619
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("kagi", KAGI_SEARCH_URL, loadConfig18().kagiBaseUrl), {
4604
4620
  method: "POST",
4605
4621
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
4606
4622
  body: JSON.stringify({ query, limit: numResults }),
4607
4623
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS14), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS14)
4608
- });
4624
+ }, ["Authorization"]);
4609
4625
  } catch (err) {
4610
4626
  const message = errorMessage12(err);
4611
4627
  const redactedMessage = redactCredential(message, apiKey);
@@ -4655,7 +4671,7 @@ async function extractWithKagi(url, signal, options = {}) {
4655
4671
  const activityId = activityMonitor.logStart({ type: "api", query: `kagi extract: ${url}` });
4656
4672
  let response;
4657
4673
  try {
4658
- response = await fetchRemoteUrl(KAGI_EXTRACT_URL, {
4674
+ response = await fetchRemoteUrl(resolveProviderApiUrl("kagi", KAGI_EXTRACT_URL, loadConfig18().kagiBaseUrl), {
4659
4675
  method: "POST",
4660
4676
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
4661
4677
  body: JSON.stringify({ pages: [{ url }] }),
@@ -4792,12 +4808,12 @@ async function searchWithOllama(query, options = {}) {
4792
4808
  const activityId = activityMonitor.logStart({ type: "api", query });
4793
4809
  let response;
4794
4810
  try {
4795
- response = await fetch(OLLAMA_SEARCH_URL, {
4811
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("ollama", OLLAMA_SEARCH_URL, loadConfig20().ollamaBaseUrl), {
4796
4812
  method: "POST",
4797
4813
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
4798
4814
  body: JSON.stringify({ query, max_results: numResults }),
4799
4815
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS16), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS16)
4800
- });
4816
+ }, ["Authorization"]);
4801
4817
  } catch (err) {
4802
4818
  const message = errorMessage14(err);
4803
4819
  const redactedMessage = redactCredential(message, apiKey);
@@ -4846,7 +4862,7 @@ async function extractWithOllama(url, signal, options = {}) {
4846
4862
  const activityId = activityMonitor.logStart({ type: "api", query: `ollama fetch: ${url}` });
4847
4863
  let response;
4848
4864
  try {
4849
- response = await fetchRemoteUrl(OLLAMA_FETCH_URL, {
4865
+ response = await fetchRemoteUrl(resolveProviderApiUrl("ollama", OLLAMA_FETCH_URL, loadConfig20().ollamaBaseUrl), {
4850
4866
  method: "POST",
4851
4867
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
4852
4868
  body: JSON.stringify({ url }),
@@ -4901,8 +4917,320 @@ var init_ollama = __esm({
4901
4917
  }
4902
4918
  });
4903
4919
 
4920
+ // deepseek.ts
4921
+ import { existsSync as existsSync41, readFileSync as readFileSync41 } from "node:fs";
4922
+ function loadConfig36() {
4923
+ if (cachedConfig35) return cachedConfig35;
4924
+ if (!existsSync41(CONFIG_PATH38)) {
4925
+ cachedConfig35 = {};
4926
+ return cachedConfig35;
4927
+ }
4928
+ const raw = readFileSync41(CONFIG_PATH38, "utf-8");
4929
+ let parsed;
4930
+ try {
4931
+ parsed = JSON.parse(raw);
4932
+ } catch (err) {
4933
+ const message = err instanceof Error ? err.message : String(err);
4934
+ throw new Error(`Failed to parse ${CONFIG_PATH38}: ${message}`);
4935
+ }
4936
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
4937
+ throw new Error(`Invalid config in ${CONFIG_PATH38}: expected a JSON object`);
4938
+ }
4939
+ cachedConfig35 = parsed;
4940
+ return cachedConfig35;
4941
+ }
4942
+ async function requireApiKey15(signal) {
4943
+ const apiKey = await resolveCredential({
4944
+ provider: "DeepSeek",
4945
+ configuredValue: loadConfig36().deepseekApiKey,
4946
+ environmentValue: process.env.DEEPSEEK_API_KEY,
4947
+ signal
4948
+ });
4949
+ if (!apiKey) {
4950
+ throw new Error(
4951
+ `DeepSeek API key not found. Either:
4952
+ 1. Create ${CONFIG_PATH38} with { "deepseekApiKey": "your-key" }
4953
+ 2. Set DEEPSEEK_API_KEY environment variable
4954
+ Get a key at https://platform.deepseek.com/api_keys`
4955
+ );
4956
+ }
4957
+ return apiKey;
4958
+ }
4959
+ function buildQuery8(query, options) {
4960
+ const include = [];
4961
+ const exclude = [];
4962
+ for (const raw of options.domainFilter ?? []) {
4963
+ const domain = normalizeDomain(raw);
4964
+ if (!domain) continue;
4965
+ const target = raw.trim().startsWith("-") ? exclude : include;
4966
+ if (!target.includes(domain)) target.push(domain);
4967
+ }
4968
+ const parts = [query.trim()];
4969
+ if (include.length > 0) parts.push(include.map((domain) => `site:${domain}`).join(" OR "));
4970
+ for (const domain of exclude) parts.push(`-site:${domain}`);
4971
+ if (options.recencyFilter) {
4972
+ const after = new Date(Date.now() - RECENCY_DAYS2[options.recencyFilter] * 864e5).toISOString().slice(0, 10);
4973
+ parts.push(`after:${after}`);
4974
+ }
4975
+ const built = parts.join(" ");
4976
+ const length = [...built].length;
4977
+ if (length > MAX_QUERY_CHARS) {
4978
+ throw new Error(`DeepSeek invalid request: the query is ${length} characters with domain and date filters; DeepSeek accepts at most ${MAX_QUERY_CHARS}`);
4979
+ }
4980
+ return built;
4981
+ }
4982
+ function text5(value) {
4983
+ return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
4984
+ }
4985
+ function errorMessage26(err) {
4986
+ return err instanceof Error ? err.message : String(err);
4987
+ }
4988
+ function unescapeMarkdownSegment(segment) {
4989
+ return segment.replace(/\\([/.,:()&+#>|!_\-"'])/g, (match, char, offset, whole) => {
4990
+ if (char === "!" && whole[offset + 2] === "[") return match;
4991
+ return char;
4992
+ });
4993
+ }
4994
+ function normalizeInlineMarkdown(line) {
4995
+ return line.split(/(`+[^`]*`+)/g).map((part, index) => index % 2 === 0 ? unescapeMarkdownSegment(part) : part).join("");
4996
+ }
4997
+ function normalizeDeepSeekMarkdown(markdown) {
4998
+ let fence = null;
4999
+ return markdown.split("\n").map((line) => {
5000
+ const match = line.match(/^\s{0,3}(`{3,}|~{3,})/);
5001
+ if (match) {
5002
+ const marker = match[1];
5003
+ if (fence === null) {
5004
+ fence = { char: marker[0], length: marker.length };
5005
+ } else if (marker[0] === fence.char && marker.length >= fence.length && line.slice(match[0].length).trim() === "") {
5006
+ fence = null;
5007
+ }
5008
+ return line;
5009
+ }
5010
+ return fence === null ? normalizeInlineMarkdown(line) : line;
5011
+ }).join("\n");
5012
+ }
5013
+ function firstMarkdownHeading(content) {
5014
+ let fence = null;
5015
+ for (const line of content.split("\n")) {
5016
+ const fenceMatch = line.match(/^\s{0,3}(`{3,}|~{3,})/);
5017
+ if (fenceMatch) {
5018
+ const marker = fenceMatch[1];
5019
+ if (fence === null) {
5020
+ fence = { char: marker[0], length: marker.length };
5021
+ } else if (marker[0] === fence.char && marker.length >= fence.length && line.slice(fenceMatch[0].length).trim() === "") {
5022
+ fence = null;
5023
+ }
5024
+ continue;
5025
+ }
5026
+ if (fence !== null) continue;
5027
+ const heading = line.match(/^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/);
5028
+ if (heading) return heading[1].trim();
5029
+ }
5030
+ return "";
5031
+ }
5032
+ function isUnusableDeepSeekPage(title, content) {
5033
+ if (content.length >= 500) return false;
5034
+ const heading = firstMarkdownHeading(content);
5035
+ if (heading !== "" && ERROR_TITLE.test(heading)) return true;
5036
+ return ERROR_TITLE.test(text5(title)) && /\b(?:404|page not found|not found)\b/i.test(content.slice(0, 200));
5037
+ }
5038
+ function parseResponse12(value) {
5039
+ const results = value && typeof value === "object" && !Array.isArray(value) ? value.results : void 0;
5040
+ if (!Array.isArray(results)) throw new Error("DeepSeek returned invalid response: expected a results array");
5041
+ return results;
5042
+ }
5043
+ function describeError2(body) {
5044
+ try {
5045
+ const error = JSON.parse(body).error;
5046
+ const message = text5(error?.message);
5047
+ if (message) return message;
5048
+ } catch {
5049
+ }
5050
+ return body;
5051
+ }
5052
+ function isDeepSeekAvailable() {
5053
+ return hasCredentialSource({ provider: "DeepSeek", configuredValue: loadConfig36().deepseekApiKey, environmentValue: process.env.DEEPSEEK_API_KEY });
5054
+ }
5055
+ async function searchWithDeepSeek(query, options = {}) {
5056
+ const builtQuery = buildQuery8(query, options);
5057
+ const apiKey = await requireApiKey15(options.signal);
5058
+ const numResults = normalizeSearchResultCount(options.numResults);
5059
+ const activityId = activityMonitor.logStart({ type: "api", query });
5060
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS33);
5061
+ let response;
5062
+ let entries;
5063
+ try {
5064
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek", DEEPSEEK_SEARCH_URL, loadConfig36().deepseekBaseUrl), {
5065
+ method: "POST",
5066
+ headers: {
5067
+ Accept: "application/json",
5068
+ "Content-Type": "application/json",
5069
+ Authorization: `Bearer ${apiKey}`
5070
+ },
5071
+ body: JSON.stringify({ query: builtQuery, count: numResults, ...options.includeContent ? { need_content: true } : {} }),
5072
+ signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal
5073
+ }, ["Authorization"]);
5074
+ if (!response.ok) {
5075
+ const errorText = redactCredential(describeError2(await response.text()), apiKey).slice(0, 300);
5076
+ throw new Error(`DeepSeek error ${response.status}: ${errorText}`);
5077
+ }
5078
+ let rawData;
5079
+ try {
5080
+ rawData = await response.json();
5081
+ } catch (err) {
5082
+ if (err instanceof Error && err.name === "TimeoutError") throw err;
5083
+ throw new Error(`DeepSeek returned invalid JSON: ${errorMessage26(err)}`);
5084
+ }
5085
+ entries = parseResponse12(rawData);
5086
+ } catch (err) {
5087
+ if (options.signal?.aborted) {
5088
+ activityMonitor.logComplete(activityId, 0);
5089
+ throw new Error("Aborted");
5090
+ }
5091
+ const message = errorMessage26(err);
5092
+ const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
5093
+ const outgoing = providerTimeout ? new Error(`DeepSeek request timed out after ${Math.round(SEARCH_TIMEOUT_MS33 / 1e3)}s`) : (() => {
5094
+ const redactedMessage = redactCredential(message, apiKey);
5095
+ if (redactedMessage === message && err instanceof Error) return err;
5096
+ const redactedError = new Error(redactedMessage);
5097
+ if (err instanceof Error) redactedError.name = err.name;
5098
+ return redactedError;
5099
+ })();
5100
+ activityMonitor.logError(activityId, redactCredential(errorMessage26(outgoing), apiKey));
5101
+ throw outgoing;
5102
+ }
5103
+ activityMonitor.logComplete(activityId, response.status);
5104
+ const results = [];
5105
+ const inlineContent = [];
5106
+ const seen = /* @__PURE__ */ new Set();
5107
+ for (const entry of entries) {
5108
+ if (!entry || typeof entry !== "object") continue;
5109
+ if (typeof entry.url !== "string" || !entry.url) continue;
5110
+ let resultUrl;
5111
+ try {
5112
+ resultUrl = new URL(entry.url);
5113
+ } catch {
5114
+ continue;
5115
+ }
5116
+ if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
5117
+ if (seen.has(resultUrl.href)) continue;
5118
+ seen.add(resultUrl.href);
5119
+ const title = text5(entry.title) || `Source ${results.length + 1}`;
5120
+ results.push({
5121
+ title,
5122
+ url: resultUrl.href,
5123
+ snippet: (text5(entry.summary) || text5(entry.snippet)).slice(0, MAX_SNIPPET_CHARS4)
5124
+ });
5125
+ if (options.includeContent) {
5126
+ const content = typeof entry.content === "string" ? entry.content.trim() : "";
5127
+ if (content) inlineContent.push({ url: resultUrl.href, title, content, error: null });
5128
+ }
5129
+ if (results.length >= numResults) break;
5130
+ }
5131
+ if (entries.length > 0 && results.length === 0) throw new Error("DeepSeek returned invalid response: no result had an http(s) URL");
5132
+ const searchResponse = { answer: formatSearchResultsAsAnswer(results), results };
5133
+ if (inlineContent.length > 0) searchResponse.inlineContent = inlineContent;
5134
+ return searchResponse;
5135
+ }
5136
+ async function extractWithDeepSeek(url, signal, options = {}) {
5137
+ const apiKey = await requireApiKey15(signal);
5138
+ const activityId = activityMonitor.logStart({ type: "fetch", url });
5139
+ const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS2;
5140
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
5141
+ try {
5142
+ const ssrf = loadSsrfConfig();
5143
+ await validateRemoteUrl(url, {
5144
+ allowRanges: ssrf.allowRanges,
5145
+ trustEnvProxy: ssrf.trustEnvProxy,
5146
+ domainPolicy: loadFetchContentDomainPolicy(),
5147
+ ...options.lookup ? { lookup: options.lookup } : {}
5148
+ });
5149
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek", DEEPSEEK_FETCH_URL, loadConfig36().deepseekBaseUrl), {
5150
+ method: "POST",
5151
+ headers: {
5152
+ Accept: "application/json",
5153
+ "Content-Type": "application/json",
5154
+ Authorization: `Bearer ${apiKey}`
5155
+ },
5156
+ body: JSON.stringify({ url }),
5157
+ signal: signal ? AbortSignal.any([timeoutSignal, signal]) : timeoutSignal
5158
+ }, ["Authorization"]);
5159
+ if (!response.ok) {
5160
+ const errorText = redactCredential(describeError2(await response.text()), apiKey).slice(0, 300);
5161
+ throw new Error(`DeepSeek Fetch error ${response.status}: ${errorText}`);
5162
+ }
5163
+ let rawData;
5164
+ try {
5165
+ rawData = await response.json();
5166
+ } catch (err) {
5167
+ if (err instanceof Error && err.name === "TimeoutError") throw err;
5168
+ throw new Error(`DeepSeek Fetch returned invalid JSON: ${errorMessage26(err)}`);
5169
+ }
5170
+ if (!rawData || typeof rawData !== "object" || Array.isArray(rawData)) {
5171
+ throw new Error("DeepSeek Fetch returned an unexpected response shape");
5172
+ }
5173
+ const page = rawData;
5174
+ const title = typeof page.title === "string" ? page.title.trim() : "";
5175
+ const content = typeof page.content === "string" ? normalizeDeepSeekMarkdown(page.content).trim() : "";
5176
+ if (!content || isUnusableDeepSeekPage(title, content)) {
5177
+ activityMonitor.logComplete(activityId, response.status);
5178
+ return null;
5179
+ }
5180
+ activityMonitor.logComplete(activityId, response.status);
5181
+ return {
5182
+ url,
5183
+ title,
5184
+ content,
5185
+ error: null
5186
+ };
5187
+ } catch (err) {
5188
+ const message = errorMessage26(err);
5189
+ if (signal?.aborted) {
5190
+ activityMonitor.logComplete(activityId, 0);
5191
+ throw new Error("Aborted");
5192
+ }
5193
+ activityMonitor.logError(activityId, redactCredential(message, apiKey));
5194
+ if (err instanceof Error && err.name === "TimeoutError") {
5195
+ throw new Error(`DeepSeek Fetch request timed out after ${Math.round(timeoutMs / 1e3)}s`);
5196
+ }
5197
+ const redactedMessage = redactCredential(message, apiKey);
5198
+ if (redactedMessage === message) throw err;
5199
+ const redactedError = new Error(redactedMessage);
5200
+ if (err instanceof Error) redactedError.name = err.name;
5201
+ throw redactedError;
5202
+ }
5203
+ }
5204
+ var DEEPSEEK_SEARCH_URL, DEEPSEEK_FETCH_URL, CONFIG_PATH38, SEARCH_TIMEOUT_MS33, FETCH_TIMEOUT_MS2, MAX_QUERY_CHARS, MAX_SNIPPET_CHARS4, RECENCY_DAYS2, cachedConfig35, ERROR_TITLE;
5205
+ var init_deepseek = __esm({
5206
+ "deepseek.ts"() {
5207
+ init_activity();
5208
+ init_domain_filter_normalization();
5209
+ init_search_answer_formatting();
5210
+ init_search_result_count_normalization();
5211
+ init_credential_source();
5212
+ init_ssrf_protection();
5213
+ init_utils();
5214
+ DEEPSEEK_SEARCH_URL = "https://api.deepseek.com/v1/tools/search";
5215
+ DEEPSEEK_FETCH_URL = "https://api.deepseek.com/v1/tools/fetch";
5216
+ CONFIG_PATH38 = getWebSearchConfigPath();
5217
+ SEARCH_TIMEOUT_MS33 = 3e4;
5218
+ FETCH_TIMEOUT_MS2 = 6e4;
5219
+ MAX_QUERY_CHARS = 128;
5220
+ MAX_SNIPPET_CHARS4 = 800;
5221
+ RECENCY_DAYS2 = {
5222
+ day: 1,
5223
+ week: 7,
5224
+ month: 30,
5225
+ year: 365
5226
+ };
5227
+ cachedConfig35 = null;
5228
+ ERROR_TITLE = /^(?:404\b|page not found\b|not found\b)/i;
5229
+ }
5230
+ });
5231
+
4904
5232
  // auth-fetch.ts
4905
- import { existsSync as existsSync43, readFileSync as readFileSync43 } from "node:fs";
5233
+ import { existsSync as existsSync44, readFileSync as readFileSync44 } from "node:fs";
4906
5234
  function resolveAuthFetchProfile(request) {
4907
5235
  const profiles = loadAuthFetchProfiles();
4908
5236
  if (profiles.length === 0) {
@@ -4940,8 +5268,8 @@ function authFetchRedirectGuard(profile, from, to) {
4940
5268
  }
4941
5269
  }
4942
5270
  function loadAuthFetchProfiles() {
4943
- if (!existsSync43(WEB_SEARCH_CONFIG_PATH2)) return [];
4944
- const raw = readFileSync43(WEB_SEARCH_CONFIG_PATH2, "utf-8");
5271
+ if (!existsSync44(WEB_SEARCH_CONFIG_PATH2)) return [];
5272
+ const raw = readFileSync44(WEB_SEARCH_CONFIG_PATH2, "utf-8");
4945
5273
  let parsed;
4946
5274
  try {
4947
5275
  const value = JSON.parse(raw);
@@ -5275,8 +5603,8 @@ function extractRSCContent(html) {
5275
5603
  if (!Array.isArray(node)) return;
5276
5604
  if (node[0] === "$" && (node[1] === "td" || node[1] === "th")) {
5277
5605
  const cellProps = node[3] || {};
5278
- const text5 = extractNode(cellProps.children, { inTable: true, inCode: false }).trim().replace(/\n/g, " ").replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
5279
- cells.push(text5);
5606
+ const text6 = extractNode(cellProps.children, { inTable: true, inCode: false }).trim().replace(/\n/g, " ").replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
5607
+ cells.push(text6);
5280
5608
  } else if (node[0] === "$" && typeof node[1] === "string" && node[1].startsWith("$L")) {
5281
5609
  const refId = node[1].slice(2);
5282
5610
  if (!visitedRefs.has(refId)) {
@@ -5316,9 +5644,9 @@ function extractRSCContent(html) {
5316
5644
  const parsed = getParsedChunk(id);
5317
5645
  if (!parsed) continue;
5318
5646
  visitedRefs.clear();
5319
- const text5 = extractNode(parsed);
5320
- if (text5.trim().length > 50 && !text5.includes("page was not found") && !text5.includes("404")) {
5321
- contentParts.push({ order: parseInt(id, 16), text: text5.trim() });
5647
+ const text6 = extractNode(parsed);
5648
+ if (text6.trim().length > 50 && !text6.includes("page was not found") && !text6.includes("404")) {
5649
+ contentParts.push({ order: parseInt(id, 16), text: text6.trim() });
5322
5650
  }
5323
5651
  }
5324
5652
  if (contentParts.length === 0) return null;
@@ -5341,20 +5669,20 @@ var init_rsc_extract = __esm({
5341
5669
  });
5342
5670
 
5343
5671
  // datalab-pdf-extract.ts
5344
- import { existsSync as existsSync44, readFileSync as readFileSync45 } from "node:fs";
5345
- function loadConfig37() {
5346
- if (cachedConfig36) return cachedConfig36;
5347
- if (!existsSync44(CONFIG_PATH40)) {
5348
- cachedConfig36 = {};
5349
- return cachedConfig36;
5672
+ import { existsSync as existsSync45, readFileSync as readFileSync46 } from "node:fs";
5673
+ function loadConfig38() {
5674
+ if (cachedConfig37) return cachedConfig37;
5675
+ if (!existsSync45(CONFIG_PATH41)) {
5676
+ cachedConfig37 = {};
5677
+ return cachedConfig37;
5350
5678
  }
5351
- const rawText = readFileSync45(CONFIG_PATH40, "utf-8");
5679
+ const rawText = readFileSync46(CONFIG_PATH41, "utf-8");
5352
5680
  try {
5353
- cachedConfig36 = JSON.parse(rawText);
5354
- return cachedConfig36;
5681
+ cachedConfig37 = JSON.parse(rawText);
5682
+ return cachedConfig37;
5355
5683
  } catch (err) {
5356
5684
  const message = err instanceof Error ? err.message : String(err);
5357
- throw new Error(`Failed to parse ${CONFIG_PATH40}: ${message}`);
5685
+ throw new Error(`Failed to parse ${CONFIG_PATH41}: ${message}`);
5358
5686
  }
5359
5687
  }
5360
5688
  function normalizeString(value) {
@@ -5369,14 +5697,14 @@ function normalizeFileId(value) {
5369
5697
  function isDatalabApiAvailable() {
5370
5698
  return hasCredentialSource({
5371
5699
  provider: "Datalab",
5372
- configuredValue: loadConfig37().datalabApiKey,
5700
+ configuredValue: loadConfig38().datalabApiKey,
5373
5701
  environmentValue: process.env.DATALAB_API_KEY
5374
5702
  });
5375
5703
  }
5376
5704
  async function getDatalabApiKey(signal) {
5377
5705
  return resolveCredential({
5378
5706
  provider: "Datalab",
5379
- configuredValue: loadConfig37().datalabApiKey,
5707
+ configuredValue: loadConfig38().datalabApiKey,
5380
5708
  environmentValue: process.env.DATALAB_API_KEY,
5381
5709
  signal
5382
5710
  });
@@ -5648,18 +5976,18 @@ async function fetchDatalab(url, init, apiKey) {
5648
5976
  }
5649
5977
  }
5650
5978
  async function readJsonResponse(response, apiKey) {
5651
- const text5 = await readResponseText(response);
5979
+ const text6 = await readResponseText(response);
5652
5980
  if (!response.ok) {
5653
- const detail = text5.trim().slice(0, MAX_ERROR_BODY_BYTES);
5981
+ const detail = text6.trim().slice(0, MAX_ERROR_BODY_BYTES);
5654
5982
  const message = detail ? `Datalab PDF conversion failed: HTTP ${response.status} ${response.statusText}: ${detail}` : `Datalab PDF conversion failed: HTTP ${response.status} ${response.statusText}`;
5655
5983
  throw new Error(redactCredential(message, apiKey));
5656
5984
  }
5657
- return parseJsonRecord(text5);
5985
+ return parseJsonRecord(text6);
5658
5986
  }
5659
- function parseJsonRecord(text5) {
5987
+ function parseJsonRecord(text6) {
5660
5988
  let parsed;
5661
5989
  try {
5662
- parsed = JSON.parse(text5);
5990
+ parsed = JSON.parse(text6);
5663
5991
  } catch (error) {
5664
5992
  throw new Error("Datalab PDF conversion returned invalid JSON", { cause: error });
5665
5993
  }
@@ -5701,7 +6029,7 @@ async function readResponseText(response) {
5701
6029
  function datalabFilename(title) {
5702
6030
  return title.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "document";
5703
6031
  }
5704
- var DEFAULT_API_HOST2, API_PREFIX, DEFAULT_TIMEOUT_MS, DEFAULT_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES, MAX_ERROR_BODY_BYTES, CLEANUP_TIMEOUT_MS, CONFIG_PATH40, DATALAB_MODE_VALUES, DATALAB_LOCATION_VALUES, DEFAULT_DATALAB_MODE, DEFAULT_PROCESSING_LOCATION, DEFAULT_DATALAB_TIMEOUT_MS, cachedConfig36;
6032
+ var DEFAULT_API_HOST2, API_PREFIX, DEFAULT_TIMEOUT_MS, DEFAULT_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES, MAX_ERROR_BODY_BYTES, CLEANUP_TIMEOUT_MS, CONFIG_PATH41, DATALAB_MODE_VALUES, DATALAB_LOCATION_VALUES, DEFAULT_DATALAB_MODE, DEFAULT_PROCESSING_LOCATION, DEFAULT_DATALAB_TIMEOUT_MS, cachedConfig37;
5705
6033
  var init_datalab_pdf_extract = __esm({
5706
6034
  "datalab-pdf-extract.ts"() {
5707
6035
  init_credential_source();
@@ -5713,7 +6041,7 @@ var init_datalab_pdf_extract = __esm({
5713
6041
  MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
5714
6042
  MAX_ERROR_BODY_BYTES = 300;
5715
6043
  CLEANUP_TIMEOUT_MS = 5e3;
5716
- CONFIG_PATH40 = getWebSearchConfigPath();
6044
+ CONFIG_PATH41 = getWebSearchConfigPath();
5717
6045
  DATALAB_MODE_VALUES = /* @__PURE__ */ new Set([
5718
6046
  "fast",
5719
6047
  "balanced",
@@ -5726,21 +6054,21 @@ var init_datalab_pdf_extract = __esm({
5726
6054
  DEFAULT_DATALAB_MODE = "balanced";
5727
6055
  DEFAULT_PROCESSING_LOCATION = "us";
5728
6056
  DEFAULT_DATALAB_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
5729
- cachedConfig36 = null;
6057
+ cachedConfig37 = null;
5730
6058
  }
5731
6059
  });
5732
6060
 
5733
6061
  // endpoint-pdf-extract.ts
5734
- import { existsSync as existsSync45, readFileSync as readFileSync46 } from "node:fs";
6062
+ import { existsSync as existsSync46, readFileSync as readFileSync47 } from "node:fs";
5735
6063
  import { setTimeout as sleep2 } from "node:timers/promises";
5736
6064
  function pdfSection() {
5737
- if (!existsSync45(CONFIG_PATH41)) return {};
6065
+ if (!existsSync46(CONFIG_PATH42)) return {};
5738
6066
  let parsed;
5739
6067
  try {
5740
- parsed = JSON.parse(readFileSync46(CONFIG_PATH41, "utf-8"));
6068
+ parsed = JSON.parse(readFileSync47(CONFIG_PATH42, "utf-8"));
5741
6069
  } catch (err) {
5742
6070
  const message = err instanceof Error ? err.message : String(err);
5743
- throw new Error(`Failed to parse ${CONFIG_PATH41}: ${message}`);
6071
+ throw new Error(`Failed to parse ${CONFIG_PATH42}: ${message}`);
5744
6072
  }
5745
6073
  const pdf = parsed?.pdf;
5746
6074
  return pdf && typeof pdf === "object" ? pdf : {};
@@ -5779,11 +6107,11 @@ async function readCapped(response, maxBytes, overflowThrows) {
5779
6107
  const reader = response.body?.getReader();
5780
6108
  if (!reader) return "";
5781
6109
  const decoder = new TextDecoder();
5782
- let text5 = "";
6110
+ let text6 = "";
5783
6111
  let received = 0;
5784
6112
  for (; ; ) {
5785
6113
  const { done, value } = await reader.read();
5786
- if (done) return text5 + decoder.decode();
6114
+ if (done) return text6 + decoder.decode();
5787
6115
  const room = maxBytes - received;
5788
6116
  received += value.byteLength;
5789
6117
  if (received >= maxBytes) {
@@ -5791,15 +6119,15 @@ async function readCapped(response, maxBytes, overflowThrows) {
5791
6119
  if (overflowThrows && received > maxBytes) {
5792
6120
  throw new Error("PDF parser endpoint returned an oversized response");
5793
6121
  }
5794
- return text5 + decoder.decode(value.subarray(0, room));
6122
+ return text6 + decoder.decode(value.subarray(0, room));
5795
6123
  }
5796
- text5 += decoder.decode(value, { stream: true });
6124
+ text6 += decoder.decode(value, { stream: true });
5797
6125
  }
5798
6126
  }
5799
6127
  async function readJson(response) {
5800
- const text5 = await readCapped(response, MAX_RESPONSE_BYTES2, true);
6128
+ const text6 = await readCapped(response, MAX_RESPONSE_BYTES2, true);
5801
6129
  try {
5802
- const parsed = JSON.parse(text5);
6130
+ const parsed = JSON.parse(text6);
5803
6131
  if (parsed && typeof parsed === "object") return parsed;
5804
6132
  } catch {
5805
6133
  }
@@ -5807,8 +6135,8 @@ async function readJson(response) {
5807
6135
  }
5808
6136
  async function errorBody(response) {
5809
6137
  try {
5810
- const text5 = await readCapped(response, MAX_ERROR_BODY_BYTES2, false);
5811
- return text5 ? `: ${text5}` : "";
6138
+ const text6 = await readCapped(response, MAX_ERROR_BODY_BYTES2, false);
6139
+ return text6 ? `: ${text6}` : "";
5812
6140
  } catch {
5813
6141
  return "";
5814
6142
  }
@@ -5892,7 +6220,7 @@ async function extractPDFViaEndpoint(buffer, options) {
5892
6220
  }
5893
6221
  throw new Error("PDF parser endpoint job timed out");
5894
6222
  }
5895
- var DEFAULT_TIMEOUT_MS2, MAX_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES2, MAX_ERROR_BODY_BYTES2, CONFIG_PATH41;
6223
+ var DEFAULT_TIMEOUT_MS2, MAX_POLL_INTERVAL_MS, MAX_RESPONSE_BYTES2, MAX_ERROR_BODY_BYTES2, CONFIG_PATH42;
5896
6224
  var init_endpoint_pdf_extract = __esm({
5897
6225
  "endpoint-pdf-extract.ts"() {
5898
6226
  init_ssrf_protection();
@@ -5901,7 +6229,7 @@ var init_endpoint_pdf_extract = __esm({
5901
6229
  MAX_POLL_INTERVAL_MS = 3e3;
5902
6230
  MAX_RESPONSE_BYTES2 = 4 * 1024 * 1024;
5903
6231
  MAX_ERROR_BODY_BYTES2 = 300;
5904
- CONFIG_PATH41 = getWebSearchConfigPath();
6232
+ CONFIG_PATH42 = getWebSearchConfigPath();
5905
6233
  }
5906
6234
  });
5907
6235
 
@@ -5991,12 +6319,12 @@ var init_gemini_pdf_extract = __esm({
5991
6319
  });
5992
6320
 
5993
6321
  // pdf-extract.ts
5994
- import { existsSync as existsSync46, readFileSync as readFileSync47 } from "node:fs";
6322
+ import { existsSync as existsSync47, readFileSync as readFileSync48 } from "node:fs";
5995
6323
  import { writeFile as writeFile2, mkdir } from "node:fs/promises";
5996
6324
  import { join as join5, basename as basename2 } from "node:path";
5997
6325
  import { tmpdir as tmpdir3 } from "node:os";
5998
6326
  function loadPDFConfig() {
5999
- if (!existsSync46(CONFIG_PATH42)) {
6327
+ if (!existsSync47(CONFIG_PATH43)) {
6000
6328
  return {
6001
6329
  enabled: true,
6002
6330
  maxSizeMB: DEFAULT_PDF_MAX_SIZE_MB,
@@ -6006,13 +6334,13 @@ function loadPDFConfig() {
6006
6334
  datalabTimeoutMs: DEFAULT_DATALAB_TIMEOUT_MS
6007
6335
  };
6008
6336
  }
6009
- const rawText = readFileSync47(CONFIG_PATH42, "utf-8");
6337
+ const rawText = readFileSync48(CONFIG_PATH43, "utf-8");
6010
6338
  let raw;
6011
6339
  try {
6012
6340
  raw = JSON.parse(rawText);
6013
6341
  } catch (err) {
6014
6342
  const message = err instanceof Error ? err.message : String(err);
6015
- throw new Error(`Failed to parse ${CONFIG_PATH42}: ${message}`);
6343
+ throw new Error(`Failed to parse ${CONFIG_PATH43}: ${message}`);
6016
6344
  }
6017
6345
  const root = raw && typeof raw === "object" ? raw : {};
6018
6346
  const pdf = root.pdf && typeof root.pdf === "object" ? root.pdf : {};
@@ -6248,7 +6576,7 @@ function isPDF(url, contentType) {
6248
6576
  return false;
6249
6577
  }
6250
6578
  }
6251
- 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_PATH42, PAGE_MARKER_PATTERN2;
6579
+ var PDF_PROVIDER_VALUES, DEFAULT_PDF_MAX_SIZE_MB, MAX_PDF_MAX_SIZE_MB, MAX_DATALAB_TIMEOUT_MS, DEFAULT_MAX_PAGES, DEFAULT_OUTPUT_DIR, CONFIG_PATH43, PAGE_MARKER_PATTERN2;
6252
6580
  var init_pdf_extract = __esm({
6253
6581
  "pdf-extract.ts"() {
6254
6582
  init_credential_source();
@@ -6269,7 +6597,7 @@ var init_pdf_extract = __esm({
6269
6597
  MAX_DATALAB_TIMEOUT_MS = 3e5;
6270
6598
  DEFAULT_MAX_PAGES = 100;
6271
6599
  DEFAULT_OUTPUT_DIR = join5(tmpdir3(), "pi-web-pdf");
6272
- CONFIG_PATH42 = getWebSearchConfigPath();
6600
+ CONFIG_PATH43 = getWebSearchConfigPath();
6273
6601
  PAGE_MARKER_PATTERN2 = /^<!-- Page (\d+) -->$/gm;
6274
6602
  }
6275
6603
  });
@@ -6447,7 +6775,7 @@ var init_github_api = __esm({
6447
6775
  });
6448
6776
 
6449
6777
  // github-extract.ts
6450
- import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync47, lstatSync as lstatSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, openSync as openSync2, readFileSync as readFileSync48, readSync, readdirSync as readdirSync3, realpathSync as realpathSync2, rmSync as rmSync2, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
6778
+ import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync48, lstatSync as lstatSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, openSync as openSync2, readFileSync as readFileSync49, readSync, readdirSync as readdirSync3, realpathSync as realpathSync2, rmSync as rmSync2, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
6451
6779
  import { lstat as lstatAsync, open as openAsync, opendir as opendirAsync, readFile as readFileAsync, realpath as realpathAsync, rm as rmAsync } from "node:fs/promises";
6452
6780
  import { execFile as execFile4, spawn as spawn2 } from "node:child_process";
6453
6781
  import { createHash as createHash2 } from "node:crypto";
@@ -6476,33 +6804,33 @@ function normalizeClonePath(value, fallback) {
6476
6804
  return expandPath(normalized);
6477
6805
  }
6478
6806
  function loadGitHubConfig() {
6479
- if (cachedConfig37) return cachedConfig37;
6807
+ if (cachedConfig38) return cachedConfig38;
6480
6808
  const defaults2 = {
6481
6809
  enabled: true,
6482
6810
  maxRepoSizeMB: 350,
6483
6811
  cloneTimeoutSeconds: 30,
6484
6812
  clonePath: "/tmp/pi-github-repos"
6485
6813
  };
6486
- if (!existsSync47(CONFIG_PATH43)) {
6487
- cachedConfig37 = defaults2;
6488
- return cachedConfig37;
6814
+ if (!existsSync48(CONFIG_PATH44)) {
6815
+ cachedConfig38 = defaults2;
6816
+ return cachedConfig38;
6489
6817
  }
6490
- const rawText = readFileSync48(CONFIG_PATH43, "utf-8");
6818
+ const rawText = readFileSync49(CONFIG_PATH44, "utf-8");
6491
6819
  let raw;
6492
6820
  try {
6493
6821
  raw = JSON.parse(rawText);
6494
6822
  } catch (err) {
6495
6823
  const message = err instanceof Error ? err.message : String(err);
6496
- throw new Error(`Failed to parse ${CONFIG_PATH43}: ${message}`);
6824
+ throw new Error(`Failed to parse ${CONFIG_PATH44}: ${message}`);
6497
6825
  }
6498
6826
  const gc = raw.githubClone ?? {};
6499
- cachedConfig37 = {
6827
+ cachedConfig38 = {
6500
6828
  enabled: normalizeEnabled(gc.enabled, defaults2.enabled),
6501
6829
  maxRepoSizeMB: normalizePositiveNumber(gc.maxRepoSizeMB, defaults2.maxRepoSizeMB),
6502
6830
  cloneTimeoutSeconds: normalizePositiveNumber(gc.cloneTimeoutSeconds, defaults2.cloneTimeoutSeconds),
6503
6831
  clonePath: normalizeClonePath(gc.clonePath, defaults2.clonePath)
6504
6832
  };
6505
- return cachedConfig37;
6833
+ return cachedConfig38;
6506
6834
  }
6507
6835
  function parseGitHubUrl(url) {
6508
6836
  let parsed;
@@ -6553,7 +6881,7 @@ function cacheKey(owner, repo, ref) {
6553
6881
  }
6554
6882
  function readLinuxBootId() {
6555
6883
  try {
6556
- const bootId = readFileSync48("/proc/sys/kernel/random/boot_id", "utf-8").trim();
6884
+ const bootId = readFileSync49("/proc/sys/kernel/random/boot_id", "utf-8").trim();
6557
6885
  return bootId.length > 0 ? bootId : null;
6558
6886
  } catch {
6559
6887
  return null;
@@ -6578,7 +6906,7 @@ function parseLinuxProcessInfo(stat) {
6578
6906
  }
6579
6907
  function readLinuxProcessInfo(pid) {
6580
6908
  try {
6581
- return parseLinuxProcessInfo(readFileSync48(`/proc/${pid}/stat`, "utf-8"));
6909
+ return parseLinuxProcessInfo(readFileSync49(`/proc/${pid}/stat`, "utf-8"));
6582
6910
  } catch (err) {
6583
6911
  if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") {
6584
6912
  return { state: "", startTime: null, dead: true };
@@ -6620,10 +6948,10 @@ function writeCloneRuntimeOwner(runtimePath) {
6620
6948
  mode: 384
6621
6949
  });
6622
6950
  }
6623
- function parseCloneRuntimeOwner(text5) {
6951
+ function parseCloneRuntimeOwner(text6) {
6624
6952
  let parsed;
6625
6953
  try {
6626
- parsed = JSON.parse(text5);
6954
+ parsed = JSON.parse(text6);
6627
6955
  } catch {
6628
6956
  return null;
6629
6957
  }
@@ -6916,7 +7244,7 @@ function resolveWithinRepo(rootPath, relativePath) {
6916
7244
  const rootPrefix = normalizedRoot.endsWith(pathSep) ? normalizedRoot : normalizedRoot + pathSep;
6917
7245
  if (!candidate.startsWith(rootPrefix)) return null;
6918
7246
  }
6919
- if (!existsSync47(candidate)) return candidate;
7247
+ if (!existsSync48(candidate)) return candidate;
6920
7248
  try {
6921
7249
  const realRoot = realpathSync2(normalizedRoot);
6922
7250
  const realCandidate = realpathSync2(candidate);
@@ -6929,7 +7257,7 @@ function resolveWithinRepo(rootPath, relativePath) {
6929
7257
  }
6930
7258
  function readTextFile(path) {
6931
7259
  try {
6932
- return readFileSync48(path, "utf-8");
7260
+ return readFileSync49(path, "utf-8");
6933
7261
  } catch {
6934
7262
  return null;
6935
7263
  }
@@ -7012,9 +7340,9 @@ function readReadme(localPath) {
7012
7340
  const candidates = ["README.md", "readme.md", "README", "README.txt", "README.rst"];
7013
7341
  for (const name of candidates) {
7014
7342
  const readmePath = join6(localPath, name);
7015
- if (existsSync47(readmePath)) {
7343
+ if (existsSync48(readmePath)) {
7016
7344
  try {
7017
- const content = readFileSync48(readmePath, "utf-8");
7345
+ const content = readFileSync49(readmePath, "utf-8");
7018
7346
  return content.length > 8192 ? content.slice(0, 8192) + "\n\n[README truncated at 8K chars]" : content;
7019
7347
  } catch {
7020
7348
  continue;
@@ -7043,7 +7371,7 @@ function generateContent(localPath, info) {
7043
7371
  if (info.type === "tree") {
7044
7372
  const dirPath = info.path || "";
7045
7373
  const fullDirPath = resolveWithinRepo(localPath, dirPath);
7046
- if (!fullDirPath || !existsSync47(fullDirPath)) {
7374
+ if (!fullDirPath || !existsSync48(fullDirPath)) {
7047
7375
  lines.push(`Path \`${dirPath}\` not found in clone. Showing repository root instead.`);
7048
7376
  lines.push("");
7049
7377
  lines.push("## Structure");
@@ -7059,7 +7387,7 @@ function generateContent(localPath, info) {
7059
7387
  if (info.type === "blob") {
7060
7388
  const filePath = info.path || "";
7061
7389
  const fullFilePath = resolveWithinRepo(localPath, filePath);
7062
- if (!fullFilePath || !existsSync47(fullFilePath)) {
7390
+ if (!fullFilePath || !existsSync48(fullFilePath)) {
7063
7391
  lines.push(`Path \`${filePath}\` not found in clone. Showing repository root instead.`);
7064
7392
  lines.push("");
7065
7393
  lines.push("## Structure");
@@ -7221,13 +7549,13 @@ async function extractGitHub(url, signal, forceClone) {
7221
7549
  const title = info.path ? `${owner}/${repo} - ${info.path}` : `${owner}/${repo}`;
7222
7550
  return { url, title, content, error: null };
7223
7551
  }
7224
- var CONFIG_PATH43, BINARY_EXTENSIONS, NOISE_DIRS, MAX_INLINE_FILE_CHARS2, MAX_TREE_ENTRIES2, CLONE_RUNTIME_OWNER_FILENAME, CLONE_RUNTIME_OWNER_VERSION, MAX_CLONE_RUNTIME_OWNER_BYTES, cloneCache, startedCloneRuntimeCleanups, cachedConfig37, cloneRuntime, NON_CODE_SEGMENTS, PROCESS_KILL_GRACE_MS;
7552
+ var CONFIG_PATH44, BINARY_EXTENSIONS, NOISE_DIRS, MAX_INLINE_FILE_CHARS2, MAX_TREE_ENTRIES2, CLONE_RUNTIME_OWNER_FILENAME, CLONE_RUNTIME_OWNER_VERSION, MAX_CLONE_RUNTIME_OWNER_BYTES, cloneCache, startedCloneRuntimeCleanups, cachedConfig38, cloneRuntime, NON_CODE_SEGMENTS, PROCESS_KILL_GRACE_MS;
7225
7553
  var init_github_extract = __esm({
7226
7554
  "github-extract.ts"() {
7227
7555
  init_activity();
7228
7556
  init_github_api();
7229
7557
  init_utils();
7230
- CONFIG_PATH43 = getWebSearchConfigPath();
7558
+ CONFIG_PATH44 = getWebSearchConfigPath();
7231
7559
  BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
7232
7560
  ".png",
7233
7561
  ".jpg",
@@ -7315,7 +7643,7 @@ var init_github_extract = __esm({
7315
7643
  MAX_CLONE_RUNTIME_OWNER_BYTES = 1024;
7316
7644
  cloneCache = /* @__PURE__ */ new Map();
7317
7645
  startedCloneRuntimeCleanups = /* @__PURE__ */ new Set();
7318
- cachedConfig37 = null;
7646
+ cachedConfig38 = null;
7319
7647
  cloneRuntime = null;
7320
7648
  NON_CODE_SEGMENTS = /* @__PURE__ */ new Set([
7321
7649
  "issues",
@@ -7354,29 +7682,29 @@ var init_github_extract = __esm({
7354
7682
 
7355
7683
  // github-issue-pr.ts
7356
7684
  import { execFile as execFile5 } from "node:child_process";
7357
- import { existsSync as existsSync48, readFileSync as readFileSync49 } from "node:fs";
7358
- function loadConfig38() {
7359
- if (cachedConfig38) return cachedConfig38;
7685
+ import { existsSync as existsSync49, readFileSync as readFileSync50 } from "node:fs";
7686
+ function loadConfig39() {
7687
+ if (cachedConfig39) return cachedConfig39;
7360
7688
  const defaults2 = { enabled: true };
7361
- if (!existsSync48(CONFIG_PATH44)) {
7362
- cachedConfig38 = defaults2;
7363
- return cachedConfig38;
7689
+ if (!existsSync49(CONFIG_PATH45)) {
7690
+ cachedConfig39 = defaults2;
7691
+ return cachedConfig39;
7364
7692
  }
7365
7693
  let parsed;
7366
7694
  try {
7367
- parsed = JSON.parse(readFileSync49(CONFIG_PATH44, "utf-8"));
7695
+ parsed = JSON.parse(readFileSync50(CONFIG_PATH45, "utf-8"));
7368
7696
  } catch (err) {
7369
7697
  const message = err instanceof Error ? err.message : String(err);
7370
- throw new Error(`Failed to parse ${CONFIG_PATH44}: ${message}`);
7698
+ throw new Error(`Failed to parse ${CONFIG_PATH45}: ${message}`);
7371
7699
  }
7372
7700
  const root = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
7373
7701
  const value = root.githubPrIssue;
7374
7702
  if (value !== void 0 && (typeof value !== "object" || value === null || Array.isArray(value))) {
7375
- throw new Error(`githubPrIssue in ${CONFIG_PATH44} must be an object`);
7703
+ throw new Error(`githubPrIssue in ${CONFIG_PATH45} must be an object`);
7376
7704
  }
7377
7705
  const enabled = typeof value?.enabled === "boolean" ? value.enabled : true;
7378
- cachedConfig38 = { enabled };
7379
- return cachedConfig38;
7706
+ cachedConfig39 = { enabled };
7707
+ return cachedConfig39;
7380
7708
  }
7381
7709
  function validOwner(owner) {
7382
7710
  return /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(owner) && !owner.includes("--");
@@ -7682,14 +8010,14 @@ function milestoneTitle(value) {
7682
8010
  if (!value || typeof value !== "object" || Array.isArray(value)) return "none";
7683
8011
  return stringValue(value.title) || "none";
7684
8012
  }
7685
- function truncateText(text5, limit, label, appendix, tool) {
7686
- if (text5.length <= limit) return text5;
7687
- const lastSpace = text5.slice(0, limit + 1).search(/\s\S*$/);
8013
+ function truncateText(text6, limit, label, appendix, tool) {
8014
+ if (text6.length <= limit) return text6;
8015
+ const lastSpace = text6.slice(0, limit + 1).search(/\s\S*$/);
7688
8016
  const cut = lastSpace > limit * 0.8 ? lastSpace : limit;
7689
8017
  appendix.push(`## ${label} (continued)
7690
8018
 
7691
- ${text5.slice(cut)}`);
7692
- return `${text5.slice(0, cut)}
8019
+ ${text6.slice(cut)}`);
8020
+ return `${text6.slice(0, cut)}
7693
8021
 
7694
8022
  [${label} truncated; ${tool ? `the rest is stored under "${label} (continued)": use ${tool} findText or offset` : "use the gh escalation commands below for the rest"}]`;
7695
8023
  }
@@ -7735,9 +8063,9 @@ function renderComments(comments, anchor, appendix, tool) {
7735
8063
  const render = (comment, inline) => {
7736
8064
  const body = stringValue(comment.body);
7737
8065
  const label = `comment ${commentId(comment) || comments.indexOf(comment) + 1}`;
7738
- const text5 = inline ? truncateText(body, COMMENT_INLINE_CHARS, label, appendix, tool) : body;
8066
+ const text6 = inline ? truncateText(body, COMMENT_INLINE_CHARS, label, appendix, tool) : body;
7739
8067
  return `- ${authorLogin(comment.author ?? comment.user)} at ${stringValue(comment.createdAt) || stringValue(comment.created_at)}${forced === comment ? " [anchored]" : ""}:
7740
- ${text5.replace(/\n/g, "\n ")}`;
8068
+ ${text6.replace(/\n/g, "\n ")}`;
7741
8069
  };
7742
8070
  const lines = selected.map((comment) => render(comment, true));
7743
8071
  storeOmitted(appendix, "Conversation comments", comments.slice(MAX_INLINE_COMMENTS).filter((comment) => comment !== forced).map((comment) => render(comment, false)));
@@ -7830,8 +8158,8 @@ function renderReviewThreads(comments, anchor, appendix, tool, total, bounded, u
7830
8158
  const render = (comment, inline) => {
7831
8159
  const path = stringValue(comment.path) || "unknown path";
7832
8160
  const line = numberValue(comment.line) ?? numberValue(comment.original_line) ?? numberValue(comment.position) ?? "?";
7833
- const text5 = stringValue(comment.body);
7834
- const body = inline ? truncateText(text5, COMMENT_INLINE_CHARS, `review thread comment ${commentId(comment) || comments.indexOf(comment) + 1}`, appendix, tool) : text5;
8161
+ const text6 = stringValue(comment.body);
8162
+ const body = inline ? truncateText(text6, COMMENT_INLINE_CHARS, `review thread comment ${commentId(comment) || comments.indexOf(comment) + 1}`, appendix, tool) : text6;
7835
8163
  return `- ${path}:${line} \u2014 ${authorLogin(comment.user ?? comment.author)}${forced === comment ? " [anchored]" : ""} (resolution state unknown):
7836
8164
  ${body.replace(/\n/g, "\n ")}`;
7837
8165
  };
@@ -7922,7 +8250,7 @@ function renderGitHubPrIssue(data) {
7922
8250
  async function extractGitHubIssuePr(url, signal, options) {
7923
8251
  const info = parseGitHubIssuePrUrl(url);
7924
8252
  if (!info) return null;
7925
- if (!loadConfig38().enabled) return null;
8253
+ if (!loadConfig39().enabled) return null;
7926
8254
  if (signal?.aborted) return { url, title: "", content: "", error: "Aborted" };
7927
8255
  const retrievalTool = options?.toolNames ? options.toolNames.getSearchContent ?? null : void 0;
7928
8256
  const ghAvailable2 = await checkGhAvailable(signal);
@@ -7946,13 +8274,13 @@ async function extractGitHubIssuePr(url, signal, options) {
7946
8274
  if ("data" in fallback) return renderGitHubPrIssue({ ...fallback.data, retrievalTool });
7947
8275
  return fallback;
7948
8276
  }
7949
- 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;
8277
+ var CONFIG_PATH45, GH_TIMEOUT_MS, GH_TOTAL_TIMEOUT_MS, MAX_DOC_CHARS, BODY_INLINE_CHARS, COMMENT_INLINE_CHARS, MAX_INLINE_COMMENTS, MAX_INLINE_REVIEWS, MAX_INLINE_CHECKS, MAX_INLINE_FILES, MAX_INLINE_COMMITS, MAX_INLINE_REVIEW_THREADS, REST_HEADERS, PR_SUBPATHS, PR_FIELDS, PR_CORE_FIELDS, ISSUE_FIELDS, ISSUE_CORE_FIELDS, cachedConfig39;
7950
8278
  var init_github_issue_pr = __esm({
7951
8279
  "github-issue-pr.ts"() {
7952
8280
  init_github_api();
7953
8281
  init_ssrf_protection();
7954
8282
  init_utils();
7955
- CONFIG_PATH44 = getWebSearchConfigPath();
8283
+ CONFIG_PATH45 = getWebSearchConfigPath();
7956
8284
  GH_TIMEOUT_MS = 1e4;
7957
8285
  GH_TOTAL_TIMEOUT_MS = 2e4;
7958
8286
  MAX_DOC_CHARS = 15e4;
@@ -8033,20 +8361,20 @@ var init_github_issue_pr = __esm({
8033
8361
  "url"
8034
8362
  ];
8035
8363
  ISSUE_CORE_FIELDS = ["title", "number", "state", "author", "createdAt", "closedAt", "labels", "assignees", "milestone", "comments", "body", "url"];
8036
- cachedConfig38 = null;
8364
+ cachedConfig39 = null;
8037
8365
  }
8038
8366
  });
8039
8367
 
8040
8368
  // feature-config.ts
8041
- import { existsSync as existsSync49, readFileSync as readFileSync50 } from "node:fs";
8369
+ import { existsSync as existsSync50, readFileSync as readFileSync51 } from "node:fs";
8042
8370
  function loadFeatureConfig() {
8043
- if (!existsSync49(CONFIG_PATH45)) return {};
8371
+ if (!existsSync50(CONFIG_PATH46)) return {};
8044
8372
  try {
8045
- const raw = JSON.parse(readFileSync50(CONFIG_PATH45, "utf-8"));
8373
+ const raw = JSON.parse(readFileSync51(CONFIG_PATH46, "utf-8"));
8046
8374
  return raw && typeof raw === "object" ? raw : {};
8047
8375
  } catch (err) {
8048
8376
  const message = err instanceof Error ? err.message : String(err);
8049
- throw new Error(`Failed to parse ${CONFIG_PATH45}: ${message}`);
8377
+ throw new Error(`Failed to parse ${CONFIG_PATH46}: ${message}`);
8050
8378
  }
8051
8379
  }
8052
8380
  function isImageEnabled() {
@@ -8059,17 +8387,17 @@ function canAttachImages() {
8059
8387
  return false;
8060
8388
  }
8061
8389
  }
8062
- var CONFIG_PATH45;
8390
+ var CONFIG_PATH46;
8063
8391
  var init_feature_config = __esm({
8064
8392
  "feature-config.ts"() {
8065
8393
  init_utils();
8066
- CONFIG_PATH45 = getWebSearchConfigPath();
8394
+ CONFIG_PATH46 = getWebSearchConfigPath();
8067
8395
  }
8068
8396
  });
8069
8397
 
8070
8398
  // youtube-extract.ts
8071
8399
  import { execFileSync } from "node:child_process";
8072
- import { existsSync as existsSync50, readFileSync as readFileSync51 } from "node:fs";
8400
+ import { existsSync as existsSync51, readFileSync as readFileSync52 } from "node:fs";
8073
8401
  function errorMessage30(err) {
8074
8402
  return err instanceof Error ? err.message : String(err);
8075
8403
  }
@@ -8089,25 +8417,25 @@ function normalizeEnabled2(value, fallback) {
8089
8417
  return typeof value === "boolean" ? value : fallback;
8090
8418
  }
8091
8419
  function loadYouTubeConfig() {
8092
- if (cachedConfig39) return cachedConfig39;
8093
- if (!existsSync50(CONFIG_PATH46)) {
8094
- cachedConfig39 = { ...defaults };
8095
- return cachedConfig39;
8420
+ if (cachedConfig40) return cachedConfig40;
8421
+ if (!existsSync51(CONFIG_PATH47)) {
8422
+ cachedConfig40 = { ...defaults };
8423
+ return cachedConfig40;
8096
8424
  }
8097
- const rawText = readFileSync51(CONFIG_PATH46, "utf-8");
8425
+ const rawText = readFileSync52(CONFIG_PATH47, "utf-8");
8098
8426
  let raw;
8099
8427
  try {
8100
8428
  raw = JSON.parse(rawText);
8101
8429
  } catch (err) {
8102
8430
  const message = err instanceof Error ? err.message : String(err);
8103
- throw new Error(`Failed to parse ${CONFIG_PATH46}: ${message}`);
8431
+ throw new Error(`Failed to parse ${CONFIG_PATH47}: ${message}`);
8104
8432
  }
8105
8433
  const yt = raw.youtube ?? {};
8106
- cachedConfig39 = {
8434
+ cachedConfig40 = {
8107
8435
  enabled: normalizeEnabled2(yt.enabled, defaults.enabled),
8108
8436
  preferredModel: normalizePreferredModel(yt.preferredModel, defaults.preferredModel)
8109
8437
  };
8110
- return cachedConfig39;
8438
+ return cachedConfig40;
8111
8439
  }
8112
8440
  function isYouTubeURL(url) {
8113
8441
  try {
@@ -8237,7 +8565,7 @@ async function tryGeminiWeb(url, prompt, model, signal, attemptErrors) {
8237
8565
  const cookies = await isGeminiWebAvailable();
8238
8566
  if (!cookies) return null;
8239
8567
  if (signal?.aborted) return null;
8240
- const text5 = await queryWithCookies(prompt, cookies, {
8568
+ const text6 = await queryWithCookies(prompt, cookies, {
8241
8569
  youtubeUrl: url,
8242
8570
  ...model !== "gemini-3.6-flash" ? { model } : {},
8243
8571
  signal,
@@ -8245,8 +8573,8 @@ async function tryGeminiWeb(url, prompt, model, signal, attemptErrors) {
8245
8573
  });
8246
8574
  return {
8247
8575
  url,
8248
- title: extractHeadingTitle(text5) ?? "YouTube Video",
8249
- content: text5,
8576
+ title: extractHeadingTitle(text6) ?? "YouTube Video",
8577
+ content: text6,
8250
8578
  error: null
8251
8579
  };
8252
8580
  } catch (err) {
@@ -8259,15 +8587,15 @@ async function tryGeminiApi(url, prompt, model, signal, attemptErrors) {
8259
8587
  try {
8260
8588
  if (!isGeminiApiAvailableWithVideo()) return null;
8261
8589
  if (signal?.aborted) return null;
8262
- const text5 = await queryGeminiApiWithVideo(prompt, url, {
8590
+ const text6 = await queryGeminiApiWithVideo(prompt, url, {
8263
8591
  model,
8264
8592
  signal,
8265
8593
  timeoutMs: 12e4
8266
8594
  });
8267
8595
  return {
8268
8596
  url,
8269
- title: extractHeadingTitle(text5) ?? "YouTube Video",
8270
- content: text5,
8597
+ title: extractHeadingTitle(text6) ?? "YouTube Video",
8598
+ content: text6,
8271
8599
  error: null
8272
8600
  };
8273
8601
  } catch (err) {
@@ -8299,7 +8627,7 @@ ${answer}
8299
8627
  return null;
8300
8628
  }
8301
8629
  }
8302
- var CONFIG_PATH46, YOUTUBE_PROMPT, YOUTUBE_REGEX, defaults, cachedConfig39;
8630
+ var CONFIG_PATH47, YOUTUBE_PROMPT, YOUTUBE_REGEX, defaults, cachedConfig40;
8303
8631
  var init_youtube_extract = __esm({
8304
8632
  "youtube-extract.ts"() {
8305
8633
  init_activity();
@@ -8309,7 +8637,7 @@ var init_youtube_extract = __esm({
8309
8637
  init_perplexity();
8310
8638
  init_extract();
8311
8639
  init_utils();
8312
- CONFIG_PATH46 = getWebSearchConfigPath();
8640
+ CONFIG_PATH47 = getWebSearchConfigPath();
8313
8641
  YOUTUBE_PROMPT = `Extract the complete content of this YouTube video. Include:
8314
8642
  1. Video title, channel name, and duration
8315
8643
  2. A brief summary (2-3 sentences)
@@ -8319,7 +8647,7 @@ var init_youtube_extract = __esm({
8319
8647
  Format as markdown.`;
8320
8648
  YOUTUBE_REGEX = /(?:(?:www\.|m\.)?youtube\.com\/(?:watch\?.*v=|shorts\/|live\/|embed\/|v\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
8321
8649
  defaults = { enabled: true, preferredModel: "gemini-3.6-flash" };
8322
- cachedConfig39 = null;
8650
+ cachedConfig40 = null;
8323
8651
  }
8324
8652
  });
8325
8653
 
@@ -8381,14 +8709,14 @@ async function extractWithGeminiWeb(url, signal) {
8381
8709
  if (!cookies) return null;
8382
8710
  const activityId = activityMonitor.logStart({ type: "api", query: `gemini_web: ${url}` });
8383
8711
  try {
8384
- const text5 = await queryWithCookies(EXTRACTION_PROMPT + url, cookies, {
8712
+ const text6 = await queryWithCookies(EXTRACTION_PROMPT + url, cookies, {
8385
8713
  signal,
8386
8714
  timeoutMs: 6e4
8387
8715
  });
8388
8716
  activityMonitor.logComplete(activityId, 200);
8389
- if (!text5 || text5.length < 50) return null;
8390
- const title = extractTitleFromContent(text5, url);
8391
- return { url, title, content: text5, error: null };
8717
+ if (!text6 || text6.length < 50) return null;
8718
+ const title = extractTitleFromContent(text6, url);
8719
+ return { url, title, content: text6, error: null };
8392
8720
  } catch (err) {
8393
8721
  if (shouldRethrow2(err)) throw err;
8394
8722
  const message = err instanceof Error ? err.message : String(err);
@@ -8400,8 +8728,8 @@ async function extractWithGeminiWeb(url, signal) {
8400
8728
  return null;
8401
8729
  }
8402
8730
  }
8403
- function extractTitleFromContent(text5, url) {
8404
- return extractHeadingTitle(text5) ?? (new URL(url).pathname.split("/").pop() || url);
8731
+ function extractTitleFromContent(text6, url) {
8732
+ return extractHeadingTitle(text6) ?? (new URL(url).pathname.split("/").pop() || url);
8405
8733
  }
8406
8734
  var EXTRACTION_PROMPT;
8407
8735
  var init_gemini_url_context = __esm({
@@ -8421,26 +8749,26 @@ URL: `;
8421
8749
  });
8422
8750
 
8423
8751
  // crawl4ai.ts
8424
- import { existsSync as existsSync51, readFileSync as readFileSync52 } from "node:fs";
8425
- function loadConfig39() {
8426
- if (cachedConfig40) return cachedConfig40;
8427
- if (!existsSync51(CONFIG_PATH47)) {
8428
- cachedConfig40 = {};
8429
- return cachedConfig40;
8752
+ import { existsSync as existsSync52, readFileSync as readFileSync53 } from "node:fs";
8753
+ function loadConfig40() {
8754
+ if (cachedConfig41) return cachedConfig41;
8755
+ if (!existsSync52(CONFIG_PATH48)) {
8756
+ cachedConfig41 = {};
8757
+ return cachedConfig41;
8430
8758
  }
8431
- const raw = readFileSync52(CONFIG_PATH47, "utf8");
8759
+ const raw = readFileSync53(CONFIG_PATH48, "utf8");
8432
8760
  let parsed;
8433
8761
  try {
8434
8762
  parsed = JSON.parse(raw);
8435
8763
  } catch (err) {
8436
8764
  const message = err instanceof Error ? err.message : String(err);
8437
- throw new Error(`Failed to parse ${CONFIG_PATH47}: ${message}`);
8765
+ throw new Error(`Failed to parse ${CONFIG_PATH48}: ${message}`);
8438
8766
  }
8439
8767
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
8440
- throw new Error(`Invalid config in ${CONFIG_PATH47}: expected a JSON object`);
8768
+ throw new Error(`Invalid config in ${CONFIG_PATH48}: expected a JSON object`);
8441
8769
  }
8442
- cachedConfig40 = parsed;
8443
- return cachedConfig40;
8770
+ cachedConfig41 = parsed;
8771
+ return cachedConfig41;
8444
8772
  }
8445
8773
  function normalizeBaseUrl5(value) {
8446
8774
  if (typeof value !== "string") return null;
@@ -8450,13 +8778,13 @@ function normalizeBaseUrl5(value) {
8450
8778
  try {
8451
8779
  parsed = new URL(trimmed);
8452
8780
  } catch {
8453
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH47}: expected an HTTP or HTTPS URL`);
8781
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: expected an HTTP or HTTPS URL`);
8454
8782
  }
8455
8783
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
8456
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH47}: expected an HTTP or HTTPS URL`);
8784
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: expected an HTTP or HTTPS URL`);
8457
8785
  }
8458
8786
  if (parsed.username || parsed.password) {
8459
- throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH47}: URL credentials are not allowed`);
8787
+ throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH48}: URL credentials are not allowed`);
8460
8788
  }
8461
8789
  parsed.pathname = parsed.pathname.replace(/\/+$/, "");
8462
8790
  parsed.search = "";
@@ -8464,14 +8792,14 @@ function normalizeBaseUrl5(value) {
8464
8792
  return parsed.toString().replace(/\/+$/, "");
8465
8793
  }
8466
8794
  function getBaseUrl4() {
8467
- return normalizeBaseUrl5(process.env.CRAWL4AI_BASE_URL) ?? normalizeBaseUrl5(loadConfig39().crawl4aiBaseUrl);
8795
+ return normalizeBaseUrl5(process.env.CRAWL4AI_BASE_URL) ?? normalizeBaseUrl5(loadConfig40().crawl4aiBaseUrl);
8468
8796
  }
8469
8797
  function requireBaseUrl4() {
8470
8798
  const baseUrl = getBaseUrl4();
8471
8799
  if (!baseUrl) {
8472
8800
  throw new Error(
8473
8801
  `Crawl4AI base URL not configured. Either:
8474
- 1. Set crawl4aiBaseUrl in ${CONFIG_PATH47}
8802
+ 1. Set crawl4aiBaseUrl in ${CONFIG_PATH48}
8475
8803
  2. Set CRAWL4AI_BASE_URL environment variable`
8476
8804
  );
8477
8805
  }
@@ -8480,7 +8808,7 @@ function requireBaseUrl4() {
8480
8808
  async function getApiToken(signal) {
8481
8809
  return resolveCredential({
8482
8810
  provider: "Crawl4AI",
8483
- configuredValue: loadConfig39().crawl4aiApiToken,
8811
+ configuredValue: loadConfig40().crawl4aiApiToken,
8484
8812
  environmentValue: process.env.CRAWL4AI_API_TOKEN,
8485
8813
  signal
8486
8814
  });
@@ -8537,8 +8865,8 @@ async function extractWithCrawl4ai(url, signal, options) {
8537
8865
  }
8538
8866
  });
8539
8867
  if (!response.ok) {
8540
- const text5 = await response.text().catch(() => "");
8541
- throw new Error(`Crawl4AI md error ${response.status}: ${redactCredential(text5, token).slice(0, 300)}`);
8868
+ const text6 = await response.text().catch(() => "");
8869
+ throw new Error(`Crawl4AI md error ${response.status}: ${redactCredential(text6, token).slice(0, 300)}`);
8542
8870
  }
8543
8871
  let data;
8544
8872
  try {
@@ -8570,45 +8898,45 @@ async function extractWithCrawl4ai(url, signal, options) {
8570
8898
  throw err;
8571
8899
  }
8572
8900
  }
8573
- var CONFIG_PATH47, EXTRACT_TIMEOUT_MS2, MARKDOWN_FILTER, cachedConfig40;
8901
+ var CONFIG_PATH48, EXTRACT_TIMEOUT_MS2, MARKDOWN_FILTER, cachedConfig41;
8574
8902
  var init_crawl4ai = __esm({
8575
8903
  "crawl4ai.ts"() {
8576
8904
  init_activity();
8577
8905
  init_credential_source();
8578
8906
  init_ssrf_protection();
8579
8907
  init_utils();
8580
- CONFIG_PATH47 = getWebSearchConfigPath();
8908
+ CONFIG_PATH48 = getWebSearchConfigPath();
8581
8909
  EXTRACT_TIMEOUT_MS2 = 6e4;
8582
8910
  MARKDOWN_FILTER = "fit";
8583
- cachedConfig40 = null;
8911
+ cachedConfig41 = null;
8584
8912
  }
8585
8913
  });
8586
8914
 
8587
8915
  // brightdata-unlocker.ts
8588
- import { existsSync as existsSync52, readFileSync as readFileSync53 } from "node:fs";
8916
+ import { existsSync as existsSync53, readFileSync as readFileSync54 } from "node:fs";
8589
8917
  function parseFailureDetail(err) {
8590
8918
  const message = err instanceof Error ? err.message : String(err);
8591
8919
  const position = message.match(/at position \d+(?: \(line \d+ column \d+\))?/);
8592
8920
  return position ? `invalid JSON ${position[0]}` : "invalid JSON";
8593
8921
  }
8594
- function loadConfig40() {
8595
- if (cachedConfig41) return cachedConfig41;
8596
- if (!existsSync52(CONFIG_PATH48)) {
8597
- cachedConfig41 = {};
8598
- return cachedConfig41;
8922
+ function loadConfig41() {
8923
+ if (cachedConfig42) return cachedConfig42;
8924
+ if (!existsSync53(CONFIG_PATH49)) {
8925
+ cachedConfig42 = {};
8926
+ return cachedConfig42;
8599
8927
  }
8600
- const raw = readFileSync53(CONFIG_PATH48, "utf8");
8928
+ const raw = readFileSync54(CONFIG_PATH49, "utf8");
8601
8929
  let parsed;
8602
8930
  try {
8603
8931
  parsed = JSON.parse(raw);
8604
8932
  } catch (err) {
8605
- throw new Error(`Failed to parse ${CONFIG_PATH48}: ${parseFailureDetail(err)}`);
8933
+ throw new Error(`Failed to parse ${CONFIG_PATH49}: ${parseFailureDetail(err)}`);
8606
8934
  }
8607
8935
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
8608
- throw new Error(`Invalid config in ${CONFIG_PATH48}: expected a JSON object`);
8936
+ throw new Error(`Invalid config in ${CONFIG_PATH49}: expected a JSON object`);
8609
8937
  }
8610
- cachedConfig41 = parsed;
8611
- return cachedConfig41;
8938
+ cachedConfig42 = parsed;
8939
+ return cachedConfig42;
8612
8940
  }
8613
8941
  function normalizeZone2(value) {
8614
8942
  if (typeof value !== "string") return null;
@@ -8619,8 +8947,8 @@ function normalizeZone2(value) {
8619
8947
  function zoneSetting() {
8620
8948
  const fromEnv = process.env.BRIGHTDATA_UNLOCKER_ZONE;
8621
8949
  if (typeof fromEnv === "string" && fromEnv.trim()) return { raw: fromEnv.trim(), label: "BRIGHTDATA_UNLOCKER_ZONE" };
8622
- const configured = loadConfig40().brightdataUnlockerZone;
8623
- if (typeof configured === "string" && configured.trim()) return { raw: configured.trim(), label: `brightdataUnlockerZone in ${CONFIG_PATH48}` };
8950
+ const configured = loadConfig41().brightdataUnlockerZone;
8951
+ if (typeof configured === "string" && configured.trim()) return { raw: configured.trim(), label: `brightdataUnlockerZone in ${CONFIG_PATH49}` };
8624
8952
  return null;
8625
8953
  }
8626
8954
  function getZone() {
@@ -8638,7 +8966,7 @@ function requireZone() {
8638
8966
  }
8639
8967
  throw new Error(
8640
8968
  `Bright Data Web Unlocker zone not configured. Either:
8641
- 1. Set brightdataUnlockerZone in ${CONFIG_PATH48}
8969
+ 1. Set brightdataUnlockerZone in ${CONFIG_PATH49}
8642
8970
  2. Set BRIGHTDATA_UNLOCKER_ZONE environment variable
8643
8971
  The zone must be of type "unblocker"; a SERP zone will not serve Web Unlocker requests.`
8644
8972
  );
@@ -8646,14 +8974,14 @@ The zone must be of type "unblocker"; a SERP zone will not serve Web Unlocker re
8646
8974
  async function getApiKey27(signal) {
8647
8975
  const apiKey = await resolveCredential({
8648
8976
  provider: "Bright Data",
8649
- configuredValue: loadConfig40().brightdataApiKey,
8977
+ configuredValue: loadConfig41().brightdataApiKey,
8650
8978
  environmentValue: process.env.BRIGHTDATA_API_KEY,
8651
8979
  signal
8652
8980
  });
8653
8981
  if (!apiKey) {
8654
8982
  throw new Error(
8655
8983
  `Bright Data API key not found. Either:
8656
- 1. Create ${CONFIG_PATH48} with { "brightdataApiKey": "your-key" }
8984
+ 1. Create ${CONFIG_PATH49} with { "brightdataApiKey": "your-key" }
8657
8985
  2. Set BRIGHTDATA_API_KEY environment variable
8658
8986
  Get a key at https://brightdata.com/cp/setting/users`
8659
8987
  );
@@ -8717,7 +9045,7 @@ async function brightDataRequest(url, zone, signal, options) {
8717
9045
  };
8718
9046
  const activityId = activityMonitor.logStart({ type: "fetch", url });
8719
9047
  try {
8720
- const response = await fetchBrightDataApi(BRIGHTDATA_REQUEST_URL, {
9048
+ const response = await fetchBrightDataApi(resolveProviderApiUrl("brightdata", BRIGHTDATA_REQUEST_URL, loadConfig41().brightdataBaseUrl), {
8721
9049
  method: "POST",
8722
9050
  headers,
8723
9051
  body: JSON.stringify(unlockerBody(url, zone)),
@@ -8727,9 +9055,9 @@ async function brightDataRequest(url, zone, signal, options) {
8727
9055
  const errorText = await response.text().catch(() => "");
8728
9056
  throw new Error(`Bright Data Web Unlocker error ${response.status}: ${redactCredential(errorText, apiKey).slice(0, 300)}`);
8729
9057
  }
8730
- const text5 = await response.text();
9058
+ const text6 = await response.text();
8731
9059
  activityMonitor.logComplete(activityId, response.status);
8732
- return text5;
9060
+ return text6;
8733
9061
  } catch (err) {
8734
9062
  const message = errorMessage32(err);
8735
9063
  const redactedMessage = redactCredential(message, apiKey);
@@ -8741,8 +9069,8 @@ async function brightDataRequest(url, zone, signal, options) {
8741
9069
  throw redactedError;
8742
9070
  }
8743
9071
  }
8744
- function headingTitle(text5) {
8745
- const match = text5.match(/^#{1,2}\s+(.+)/m);
9072
+ function headingTitle(text6) {
9073
+ const match = text6.match(/^#{1,2}\s+(.+)/m);
8746
9074
  if (!match) return "";
8747
9075
  return match[1].replace(/\*+/g, "").trim();
8748
9076
  }
@@ -8750,7 +9078,7 @@ function isBrightDataUnlockerAvailable() {
8750
9078
  if (getZone() === null) return false;
8751
9079
  return hasCredentialSource({
8752
9080
  provider: "Bright Data",
8753
- configuredValue: loadConfig40().brightdataApiKey,
9081
+ configuredValue: loadConfig41().brightdataApiKey,
8754
9082
  environmentValue: process.env.BRIGHTDATA_API_KEY
8755
9083
  });
8756
9084
  }
@@ -8762,26 +9090,26 @@ async function extractWithBrightDataUnlocker(url, signal, options) {
8762
9090
  if (!content) return null;
8763
9091
  return { url, title: headingTitle(content), content, error: null };
8764
9092
  }
8765
- var CONFIG_PATH48, BRIGHTDATA_REQUEST_URL, EXTRACT_TIMEOUT_MS3, DEFAULT_MAX_REDIRECTS3, REDIRECT_STATUSES3, ZONE_PATTERN2, cachedConfig41;
9093
+ var CONFIG_PATH49, BRIGHTDATA_REQUEST_URL, EXTRACT_TIMEOUT_MS3, DEFAULT_MAX_REDIRECTS3, REDIRECT_STATUSES3, ZONE_PATTERN2, cachedConfig42;
8766
9094
  var init_brightdata_unlocker = __esm({
8767
9095
  "brightdata-unlocker.ts"() {
8768
9096
  init_activity();
8769
9097
  init_credential_source();
8770
9098
  init_ssrf_protection();
8771
9099
  init_utils();
8772
- CONFIG_PATH48 = getWebSearchConfigPath();
9100
+ CONFIG_PATH49 = getWebSearchConfigPath();
8773
9101
  BRIGHTDATA_REQUEST_URL = "https://api.brightdata.com/request";
8774
9102
  EXTRACT_TIMEOUT_MS3 = 6e4;
8775
9103
  DEFAULT_MAX_REDIRECTS3 = 5;
8776
9104
  REDIRECT_STATUSES3 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
8777
9105
  ZONE_PATTERN2 = /^[a-z0-9_-]+$/i;
8778
- cachedConfig41 = null;
9106
+ cachedConfig42 = null;
8779
9107
  }
8780
9108
  });
8781
9109
 
8782
9110
  // video-extract.ts
8783
9111
  import { execFileSync as execFileSync2 } from "node:child_process";
8784
- import { existsSync as existsSync53, readFileSync as readFileSync54, readdirSync as readdirSync4, statSync as statSync3 } from "node:fs";
9112
+ import { existsSync as existsSync54, readFileSync as readFileSync55, readdirSync as readdirSync4, statSync as statSync3 } from "node:fs";
8785
9113
  import { readFile as readFile2 } from "node:fs/promises";
8786
9114
  import { resolve, extname as extname2, basename as basename4, join as join7, dirname as dirname2 } from "node:path";
8787
9115
  function shouldRethrow3(err) {
@@ -8802,17 +9130,17 @@ function normalizeMaxSizeMB(value, fallback) {
8802
9130
  }
8803
9131
  function loadVideoConfig() {
8804
9132
  if (cachedVideoConfig) return cachedVideoConfig;
8805
- if (!existsSync53(CONFIG_PATH49)) {
9133
+ if (!existsSync54(CONFIG_PATH50)) {
8806
9134
  cachedVideoConfig = { ...VIDEO_CONFIG_DEFAULTS };
8807
9135
  return cachedVideoConfig;
8808
9136
  }
8809
- const rawText = readFileSync54(CONFIG_PATH49, "utf-8");
9137
+ const rawText = readFileSync55(CONFIG_PATH50, "utf-8");
8810
9138
  let raw;
8811
9139
  try {
8812
9140
  raw = JSON.parse(rawText);
8813
9141
  } catch (err) {
8814
9142
  const message = err instanceof Error ? err.message : String(err);
8815
- throw new Error(`Failed to parse ${CONFIG_PATH49}: ${message}`);
9143
+ throw new Error(`Failed to parse ${CONFIG_PATH50}: ${message}`);
8816
9144
  }
8817
9145
  const v = raw.video ?? {};
8818
9146
  cachedVideoConfig = {
@@ -8858,10 +9186,10 @@ function isVideoFile(input) {
8858
9186
  }
8859
9187
  function resolveFilePath(filePath) {
8860
9188
  const absolutePath = resolve(filePath);
8861
- if (existsSync53(absolutePath)) return absolutePath;
9189
+ if (existsSync54(absolutePath)) return absolutePath;
8862
9190
  const dir = dirname2(absolutePath);
8863
9191
  const base = basename4(absolutePath);
8864
- if (!existsSync53(dir)) return null;
9192
+ if (!existsSync54(dir)) return null;
8865
9193
  try {
8866
9194
  const normalizedBase = normalizeSpaces(base);
8867
9195
  const match = readdirSync4(dir).find((f) => normalizeSpaces(f) === normalizedBase);
@@ -8953,7 +9281,7 @@ async function tryVideoGeminiWeb(info, prompt, model, signal) {
8953
9281
  const cookies = await isGeminiWebAvailable();
8954
9282
  if (!cookies) return null;
8955
9283
  if (signal?.aborted) return null;
8956
- const text5 = await queryWithCookies(prompt, cookies, {
9284
+ const text6 = await queryWithCookies(prompt, cookies, {
8957
9285
  files: [{ path: info.absolutePath, mimeType: info.mimeType }],
8958
9286
  ...model !== "gemini-3.6-flash" ? { model } : {},
8959
9287
  signal,
@@ -8961,8 +9289,8 @@ async function tryVideoGeminiWeb(info, prompt, model, signal) {
8961
9289
  });
8962
9290
  return {
8963
9291
  url: info.absolutePath,
8964
- title: extractVideoTitle(text5, info.absolutePath),
8965
- content: text5,
9292
+ title: extractVideoTitle(text6, info.absolutePath),
9293
+ content: text6,
8966
9294
  error: null
8967
9295
  };
8968
9296
  } catch (err) {
@@ -8979,7 +9307,7 @@ async function tryVideoGeminiApi(info, prompt, model, signal) {
8979
9307
  const uploaded = await uploadToFilesApi(info, apiKey, signal);
8980
9308
  fileName = uploaded.name;
8981
9309
  await pollFileState(fileName, apiKey, signal, 12e4);
8982
- const text5 = await queryGeminiApiWithVideo(prompt, uploaded.uri, {
9310
+ const text6 = await queryGeminiApiWithVideo(prompt, uploaded.uri, {
8983
9311
  apiKey,
8984
9312
  model,
8985
9313
  mimeType: info.mimeType,
@@ -8988,8 +9316,8 @@ async function tryVideoGeminiApi(info, prompt, model, signal) {
8988
9316
  });
8989
9317
  return {
8990
9318
  url: info.absolutePath,
8991
- title: extractVideoTitle(text5, info.absolutePath),
8992
- content: text5,
9319
+ title: extractVideoTitle(text6, info.absolutePath),
9320
+ content: text6,
8993
9321
  error: null
8994
9322
  };
8995
9323
  } catch (err) {
@@ -9014,8 +9342,8 @@ async function uploadToFilesApi(info, apiKey, signal) {
9014
9342
  signal
9015
9343
  }, apiKey);
9016
9344
  if (!initRes.ok) {
9017
- const text5 = redactGeminiApiResponse(initRes, await initRes.text(), apiKey);
9018
- throw new Error(`File upload init failed: ${initRes.status} (${text5.slice(0, 200)})`);
9345
+ const text6 = redactGeminiApiResponse(initRes, await initRes.text(), apiKey);
9346
+ throw new Error(`File upload init failed: ${initRes.status} (${text6.slice(0, 200)})`);
9019
9347
  }
9020
9348
  const uploadUrl = initRes.headers.get("x-goog-upload-url");
9021
9349
  if (!uploadUrl) throw new Error("No upload URL in response headers");
@@ -9032,8 +9360,8 @@ async function uploadToFilesApi(info, apiKey, signal) {
9032
9360
  signal
9033
9361
  }, apiKey);
9034
9362
  if (!uploadRes.ok) {
9035
- const text5 = redactGeminiApiResponse(uploadRes, await uploadRes.text(), apiKey);
9036
- throw new Error(`File upload failed: ${uploadRes.status} (${text5.slice(0, 200)})`);
9363
+ const text6 = redactGeminiApiResponse(uploadRes, await uploadRes.text(), apiKey);
9364
+ throw new Error(`File upload failed: ${uploadRes.status} (${text6.slice(0, 200)})`);
9037
9365
  }
9038
9366
  const result = await uploadRes.json();
9039
9367
  return result.file;
@@ -9057,10 +9385,10 @@ function deleteGeminiFile(fileName, apiKey) {
9057
9385
  console.error(`Failed to delete Gemini file ${fileName}: ${message}`);
9058
9386
  });
9059
9387
  }
9060
- function extractVideoTitle(text5, filePath) {
9061
- return extractHeadingTitle(text5) ?? basename4(filePath, extname2(filePath));
9388
+ function extractVideoTitle(text6, filePath) {
9389
+ return extractHeadingTitle(text6) ?? basename4(filePath, extname2(filePath));
9062
9390
  }
9063
- var CONFIG_PATH49, DEFAULT_VIDEO_PROMPT, VIDEO_EXTENSIONS, VIDEO_CONFIG_DEFAULTS, cachedVideoConfig;
9391
+ var CONFIG_PATH50, DEFAULT_VIDEO_PROMPT, VIDEO_EXTENSIONS, VIDEO_CONFIG_DEFAULTS, cachedVideoConfig;
9064
9392
  var init_video_extract = __esm({
9065
9393
  "video-extract.ts"() {
9066
9394
  init_activity();
@@ -9069,7 +9397,7 @@ var init_video_extract = __esm({
9069
9397
  init_gemini_api();
9070
9398
  init_extract();
9071
9399
  init_utils();
9072
- CONFIG_PATH49 = getWebSearchConfigPath();
9400
+ CONFIG_PATH50 = getWebSearchConfigPath();
9073
9401
  DEFAULT_VIDEO_PROMPT = `Extract the complete content of this video. Include:
9074
9402
  1. Video title (infer from content if not explicit), duration
9075
9403
  2. A brief summary (2-3 sentences)
@@ -9259,33 +9587,33 @@ function sha256Bytes(value) {
9259
9587
  function asciiLowerCode(code) {
9260
9588
  return code >= 65 && code <= 90 ? code + 32 : code;
9261
9589
  }
9262
- function matchesDataScheme(text5, index) {
9263
- 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;
9590
+ function matchesDataScheme(text6, index) {
9591
+ 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;
9264
9592
  }
9265
- function isSchemeBoundary(text5, index) {
9593
+ function isSchemeBoundary(text6, index) {
9266
9594
  if (index === 0) return true;
9267
- const code = text5.charCodeAt(index - 1);
9595
+ const code = text6.charCodeAt(index - 1);
9268
9596
  const alphaNumeric = code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
9269
9597
  return !alphaNumeric && code !== 43 && code !== 45 && code !== 46;
9270
9598
  }
9271
- function findNextDataScheme(text5, from) {
9272
- for (let i = from; i + 5 <= text5.length; i++) {
9273
- if (matchesDataScheme(text5, i) && isSchemeBoundary(text5, i)) return i;
9599
+ function findNextDataScheme(text6, from) {
9600
+ for (let i = from; i + 5 <= text6.length; i++) {
9601
+ if (matchesDataScheme(text6, i) && isSchemeBoundary(text6, i)) return i;
9274
9602
  }
9275
9603
  return -1;
9276
9604
  }
9277
- function dataUriEnclosure(text5, start) {
9605
+ function dataUriEnclosure(text6, start) {
9278
9606
  if (start === 0) return null;
9279
9607
  const immediateIndex = start - 1;
9280
- const immediate = text5[immediateIndex];
9608
+ const immediate = text6[immediateIndex];
9281
9609
  if (immediate === '"' || immediate === "'" || immediate === "`") {
9282
- const beforeQuote = immediateIndex > 0 ? text5[immediateIndex - 1] : "";
9610
+ const beforeQuote = immediateIndex > 0 ? text6[immediateIndex - 1] : "";
9283
9611
  const likelyOpeningQuote = immediateIndex === 0 || beforeQuote === "=" || beforeQuote === "(" || beforeQuote === "[" || beforeQuote === "{" || beforeQuote === ":" || beforeQuote === "," || /\s/.test(beforeQuote);
9284
9612
  if (likelyOpeningQuote) return { kind: "quote", close: immediate };
9285
9613
  }
9286
9614
  let openerIndex = immediateIndex;
9287
- while (openerIndex >= 0 && (text5[openerIndex] === " " || text5[openerIndex] === " ")) openerIndex--;
9288
- const opener = text5[openerIndex];
9615
+ while (openerIndex >= 0 && (text6[openerIndex] === " " || text6[openerIndex] === " ")) openerIndex--;
9616
+ const opener = text6[openerIndex];
9289
9617
  if (opener === "(") return { kind: "parentheses" };
9290
9618
  if (opener === "<") return { kind: "angle" };
9291
9619
  return null;
@@ -9294,13 +9622,13 @@ function isBareDataUriTerminator(ch) {
9294
9622
  const code = ch.charCodeAt(0);
9295
9623
  return code <= 32 || code === 127 || ch === '"' || ch === "`" || ch === "<" || ch === ">";
9296
9624
  }
9297
- function scanDataUriCandidate(text5, start) {
9298
- const enclosure = dataUriEnclosure(text5, start);
9625
+ function scanDataUriCandidate(text6, start) {
9626
+ const enclosure = dataUriEnclosure(text6, start);
9299
9627
  let comma = -1;
9300
9628
  let depth = enclosure?.kind === "parentheses" ? 1 : 0;
9301
9629
  let index = start + 5;
9302
- for (; index < text5.length; index++) {
9303
- const ch = text5[index];
9630
+ for (; index < text6.length; index++) {
9631
+ const ch = text6[index];
9304
9632
  if (enclosure?.kind === "quote") {
9305
9633
  if (ch === enclosure.close) break;
9306
9634
  } else if (enclosure?.kind === "parentheses") {
@@ -9319,16 +9647,16 @@ function scanDataUriCandidate(text5, start) {
9319
9647
  }
9320
9648
  return { end: index, comma, enclosure };
9321
9649
  }
9322
- function headerEndsWithBase64(text5, headerStart, comma) {
9650
+ function headerEndsWithBase64(text6, headerStart, comma) {
9323
9651
  let end = comma;
9324
- while (end > headerStart && (text5[end - 1] === " " || text5[end - 1] === " ")) end--;
9652
+ while (end > headerStart && (text6[end - 1] === " " || text6[end - 1] === " ")) end--;
9325
9653
  const token = "base64";
9326
9654
  if (end - headerStart < token.length + 1) return false;
9327
9655
  const tokenStart = end - token.length;
9328
9656
  for (let i = 0; i < token.length; i++) {
9329
- if (asciiLowerCode(text5.charCodeAt(tokenStart + i)) !== token.charCodeAt(i)) return false;
9657
+ if (asciiLowerCode(text6.charCodeAt(tokenStart + i)) !== token.charCodeAt(i)) return false;
9330
9658
  }
9331
- return tokenStart > headerStart && text5[tokenStart - 1] === ";";
9659
+ return tokenStart > headerStart && text6[tokenStart - 1] === ";";
9332
9660
  }
9333
9661
  function isMimeTokenChar(code) {
9334
9662
  if (code < 33 || code > 126) return false;
@@ -9367,14 +9695,14 @@ function isMimeTokenChar(code) {
9367
9695
  return true;
9368
9696
  }
9369
9697
  }
9370
- function normalizeMimeType(text5, headerStart, comma) {
9698
+ function normalizeMimeType(text6, headerStart, comma) {
9371
9699
  let end = headerStart;
9372
- while (end < comma && text5[end] !== ";") end++;
9700
+ while (end < comma && text6[end] !== ";") end++;
9373
9701
  if (end === headerStart) return "text/plain";
9374
9702
  if (end - headerStart > MAX_MIME_CHARS) return "application/octet-stream";
9375
9703
  let slashCount = 0;
9376
9704
  for (let i = headerStart; i < end; i++) {
9377
- const code = text5.charCodeAt(i);
9705
+ const code = text6.charCodeAt(i);
9378
9706
  if (code === 47) {
9379
9707
  slashCount++;
9380
9708
  if (i === headerStart || i === end - 1) return "application/octet-stream";
@@ -9383,7 +9711,7 @@ function normalizeMimeType(text5, headerStart, comma) {
9383
9711
  if (!isMimeTokenChar(code)) return "application/octet-stream";
9384
9712
  }
9385
9713
  if (slashCount !== 1) return "application/octet-stream";
9386
- return text5.slice(headerStart, end).toLowerCase();
9714
+ return text6.slice(headerStart, end).toLowerCase();
9387
9715
  }
9388
9716
  function hexValue(code) {
9389
9717
  if (code >= 48 && code <= 57) return code - 48;
@@ -9457,15 +9785,15 @@ function buildDataUriMarker(omission) {
9457
9785
  const decodeError = omission.decodeError ? `; decodeError=${omission.decodeError}` : "";
9458
9786
  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]`;
9459
9787
  }
9460
- function sanitizeTextInternal(text5, sourcePath, state) {
9788
+ function sanitizeTextInternal(text6, sourcePath, state) {
9461
9789
  let scanFrom = 0;
9462
9790
  let retainedFrom = 0;
9463
9791
  let outputLength = 0;
9464
9792
  const pieces = [];
9465
- while (scanFrom < text5.length) {
9466
- const start = findNextDataScheme(text5, scanFrom);
9793
+ while (scanFrom < text6.length) {
9794
+ const start = findNextDataScheme(text6, scanFrom);
9467
9795
  if (start < 0) break;
9468
- const candidate = scanDataUriCandidate(text5, start);
9796
+ const candidate = scanDataUriCandidate(text6, start);
9469
9797
  const end = candidate.end;
9470
9798
  const headerStart = start + 5;
9471
9799
  const missingComma = candidate.comma < 0;
@@ -9475,9 +9803,9 @@ function sanitizeTextInternal(text5, sourcePath, state) {
9475
9803
  }
9476
9804
  const headerEnd = missingComma ? end : candidate.comma;
9477
9805
  const headerLength = headerEnd - headerStart;
9478
- const encoding = headerEndsWithBase64(text5, headerStart, headerEnd) ? "base64" : "percent-encoded";
9479
- const mimeType = normalizeMimeType(text5, headerStart, headerEnd);
9480
- const payload = missingComma ? text5.slice(headerStart, end) : text5.slice(candidate.comma + 1, end);
9806
+ const encoding = headerEndsWithBase64(text6, headerStart, headerEnd) ? "base64" : "percent-encoded";
9807
+ const mimeType = normalizeMimeType(text6, headerStart, headerEnd);
9808
+ const payload = missingComma ? text6.slice(headerStart, end) : text6.slice(candidate.comma + 1, end);
9481
9809
  const encodedBytes = Buffer3.byteLength(payload, "utf8");
9482
9810
  let decodedBytes = null;
9483
9811
  let decodeError;
@@ -9513,7 +9841,7 @@ function sanitizeTextInternal(text5, sourcePath, state) {
9513
9841
  retrieval: "not-retained"
9514
9842
  };
9515
9843
  const marker = buildDataUriMarker(omission);
9516
- const prefix = text5.slice(retainedFrom, start);
9844
+ const prefix = text6.slice(retainedFrom, start);
9517
9845
  pieces.push(prefix, marker);
9518
9846
  outputLength += prefix.length;
9519
9847
  const markerStart = outputLength;
@@ -9522,13 +9850,13 @@ function sanitizeTextInternal(text5, sourcePath, state) {
9522
9850
  retainedFrom = end;
9523
9851
  scanFrom = end;
9524
9852
  }
9525
- if (state.omissions.length === 0 && retainedFrom === 0) return text5;
9526
- pieces.push(text5.slice(retainedFrom));
9853
+ if (state.omissions.length === 0 && retainedFrom === 0) return text6;
9854
+ pieces.push(text6.slice(retainedFrom));
9527
9855
  return pieces.join("");
9528
9856
  }
9529
- function sanitizeInlineDataUris(text5, sourcePath) {
9857
+ function sanitizeInlineDataUris(text6, sourcePath) {
9530
9858
  const state = { nextOrdinal: 1, omissions: [] };
9531
- const sanitized = sanitizeTextInternal(text5, sourcePath, state);
9859
+ const sanitized = sanitizeTextInternal(text6, sourcePath, state);
9532
9860
  return {
9533
9861
  text: sanitized,
9534
9862
  omissions: state.omissions.map(({ markerStart: _start, markerEnd: _end, ...omission }) => omission)
@@ -9554,13 +9882,13 @@ __export(extract_exports, {
9554
9882
  readPDFResponseBuffer: () => readPDFResponseBuffer,
9555
9883
  resolveFetchTimeoutMs: () => resolveFetchTimeoutMs
9556
9884
  });
9557
- import { existsSync as existsSync54, readFileSync as readFileSync55 } from "node:fs";
9885
+ import { existsSync as existsSync55, readFileSync as readFileSync56 } from "node:fs";
9558
9886
  import pLimit from "p-limit";
9559
9887
  function loadFetchTimeoutMs() {
9560
- if (!existsSync54(WEB_SEARCH_CONFIG_PATH3)) return DEFAULT_TIMEOUT_MS4;
9888
+ if (!existsSync55(WEB_SEARCH_CONFIG_PATH3)) return DEFAULT_TIMEOUT_MS4;
9561
9889
  let raw;
9562
9890
  try {
9563
- raw = JSON.parse(readFileSync55(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
9891
+ raw = JSON.parse(readFileSync56(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
9564
9892
  } catch (err) {
9565
9893
  const message = err instanceof Error ? err.message : String(err);
9566
9894
  throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH3}: ${message}`);
@@ -9588,10 +9916,10 @@ function isDefuddleConsoleError(args) {
9588
9916
  const prefix = args[0];
9589
9917
  return prefix === "Defuddle" || typeof prefix === "string" && /^Defuddle(?:\s|:)/.test(prefix);
9590
9918
  }
9591
- async function extractWithDefuddle(text5, url) {
9919
+ async function extractWithDefuddle(text6, url) {
9592
9920
  const { Defuddle } = await import("defuddle/node");
9593
9921
  const { parseHTML } = await import("linkedom");
9594
- const { document } = parseHTML(text5);
9922
+ const { document } = parseHTML(text6);
9595
9923
  Object.defineProperty(document, "location", {
9596
9924
  value: new URL(url),
9597
9925
  configurable: true
@@ -9699,12 +10027,12 @@ async function fetchAuthenticatedRemoteUrl(url, init, validationOptions, profile
9699
10027
  throw new Error(`Too many redirects fetching ${current.toString()}`);
9700
10028
  }
9701
10029
  function loadFetchRouting() {
9702
- if (!existsSync54(WEB_SEARCH_CONFIG_PATH3)) {
10030
+ if (!existsSync55(WEB_SEARCH_CONFIG_PATH3)) {
9703
10031
  return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
9704
10032
  }
9705
10033
  let raw;
9706
10034
  try {
9707
- const parsed = JSON.parse(readFileSync55(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
10035
+ const parsed = JSON.parse(readFileSync56(WEB_SEARCH_CONFIG_PATH3, "utf-8"));
9708
10036
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
9709
10037
  throw new Error("expected a JSON object");
9710
10038
  }
@@ -10184,6 +10512,7 @@ async function extractContent(url, signal, options) {
10184
10512
  let parallelError = null;
10185
10513
  let parallelMcpError = null;
10186
10514
  let brightdataError = null;
10515
+ let deepseekError = null;
10187
10516
  if (remoteUrl && providerOrder[0] !== "http") {
10188
10517
  const httpGateResult = await runHttpProvider();
10189
10518
  if (httpGateResult) return httpGateResult;
@@ -10365,6 +10694,22 @@ async function extractContent(url, signal, options) {
10365
10694
  }
10366
10695
  if (geminiResult) return withDeclaredLinks(geminiResult);
10367
10696
  }
10697
+ if (provider === "deepseek") {
10698
+ try {
10699
+ if (isDeepSeekAvailable()) {
10700
+ const deepseekResult = await extractWithDeepSeek(url, signal, {
10701
+ timeoutMs: options?.timeoutMs,
10702
+ ...options?.lookup ? { lookup: options.lookup } : {}
10703
+ });
10704
+ if (deepseekResult) return withDeclaredLinks(deepseekResult);
10705
+ }
10706
+ } catch (err) {
10707
+ if (isAbortError5(err)) return abortedResult(url);
10708
+ deepseekError = errorMessage33(err);
10709
+ if (isConfigParseError(err)) return parseErrorResult(deepseekError);
10710
+ }
10711
+ continue;
10712
+ }
10368
10713
  }
10369
10714
  if (signal?.aborted) return abortedResult(url);
10370
10715
  const finalHttpResult = httpResult;
@@ -10387,6 +10732,7 @@ async function extractContent(url, signal, options) {
10387
10732
  ...parallelError ? [`Parallel fallback failed: ${parallelError}`] : [],
10388
10733
  ...parallelMcpError ? [`Parallel MCP fallback failed: ${parallelMcpError}`] : [],
10389
10734
  ...brightdataError ? [`Bright Data fallback failed: ${brightdataError}`] : [],
10735
+ ...deepseekError ? [`DeepSeek fallback failed: ${deepseekError}`] : [],
10390
10736
  "",
10391
10737
  "Fallback options:",
10392
10738
  ...jinaHint ? [jinaHint] : [],
@@ -10399,23 +10745,28 @@ async function extractContent(url, signal, options) {
10399
10745
  ` \u2022 Set ollamaApiKey in ${WEB_SEARCH_CONFIG_PATH3} or OLLAMA_API_KEY`,
10400
10746
  ` \u2022 Set parallelApiKey in ${WEB_SEARCH_CONFIG_PATH3} or PARALLEL_API_KEY`,
10401
10747
  ` \u2022 Set brightdataApiKey and brightdataUnlockerZone in ${WEB_SEARCH_CONFIG_PATH3} or BRIGHTDATA_API_KEY and BRIGHTDATA_UNLOCKER_ZONE`,
10748
+ ` \u2022 Set deepseekApiKey in ${WEB_SEARCH_CONFIG_PATH3} or DEEPSEEK_API_KEY and add "deepseek" to fetchRouting.providers`,
10402
10749
  ` \u2022 Set GEMINI_API_KEY in ${WEB_SEARCH_CONFIG_PATH3}`,
10403
10750
  " \u2022 Sign into gemini.google.com in Chrome",
10404
10751
  ...searchToolName ? [` \u2022 Use ${searchToolName} to find content about this topic`] : []
10405
10752
  ].join("\n");
10406
10753
  return { ...finalHttpResult ?? { url, title: "", content: "", error: null }, error: guidance };
10407
10754
  }
10408
- function isCloudflareChallenge(response, text5, isHTML) {
10755
+ function isCloudflareChallenge(response, text6, isHTML) {
10409
10756
  if (response.status !== 200) return false;
10410
10757
  if (response.headers.get("cf-mitigated") === "challenge") return true;
10411
- return isHTML && /<title>\s*Just a moment\.\.\.\s*<\/title>/i.test(text5) && text5.includes("window._cf_chl_opt") && text5.includes("/cdn-cgi/challenge-platform/");
10758
+ return isHTML && /<title>\s*Just a moment\.\.\.\s*<\/title>/i.test(text6) && text6.includes("window._cf_chl_opt") && text6.includes("/cdn-cgi/challenge-platform/");
10759
+ }
10760
+ function isExecutableScriptType(type) {
10761
+ const mime = (type ?? "").split(";")[0].trim().toLowerCase();
10762
+ return mime === "" || mime === "module" || JAVASCRIPT_MIME_TYPES.has(mime);
10412
10763
  }
10413
10764
  function isLikelyJSRendered(html) {
10414
10765
  const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
10415
10766
  if (!bodyMatch) return false;
10416
10767
  const bodyHtml = bodyMatch[1];
10417
10768
  const textContent = bodyHtml.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
10418
- const scriptCount = (html.match(/<script/gi) || []).length;
10769
+ const scriptCount = [...html.matchAll(/<script\b([^>]*)>/gi)].filter(([, attrs]) => isExecutableScriptType(attrs.match(/\btype\s*=\s*["']?([^"'\s>]+)/i)?.[1] ?? null)).length;
10419
10770
  return textContent.length < 500 && scriptCount > 3;
10420
10771
  }
10421
10772
  async function readPDFResponseBuffer(response, maxSizeMB) {
@@ -10550,9 +10901,9 @@ async function extractViaHttp(url, timeoutMs, signal, options, preferMarkdown =
10550
10901
  const hint = isPDFContent ? '; retry without mode for Markdown, or with mode "answer" and a prompt' : "";
10551
10902
  return { url, title: "", content: "", error: `Unsupported content type in raw mode: ${mimeType || "missing"}${hint}`, mimeType, status: response.status };
10552
10903
  }
10553
- const text6 = await readTextResponseWithLimit(response, maxResponseSize);
10904
+ const text7 = await readTextResponseWithLimit(response, maxResponseSize);
10554
10905
  activityMonitor.logComplete(activityId, response.status);
10555
- return { url, title: extractTextTitle(text6, url), content: text6, error: null, mimeType, status: response.status };
10906
+ return { url, title: extractTextTitle(text7, url), content: text7, error: null, mimeType, status: response.status };
10556
10907
  }
10557
10908
  if (SUPPORTED_IMAGE_TYPES.has(mimeType)) {
10558
10909
  const disabled = imageGateError();
@@ -10622,19 +10973,19 @@ ${result.pages > 0 ? `Pages: ${result.pages}
10622
10973
  error: `Unsupported content type: ${contentType.split(";")[0]}`
10623
10974
  };
10624
10975
  }
10625
- const text5 = await readTextResponseWithLimit(response, maxResponseSize);
10976
+ const text6 = await readTextResponseWithLimit(response, maxResponseSize);
10626
10977
  const isHTML = contentType.includes("text/html") || contentType.includes("application/xhtml+xml");
10627
- if (isCloudflareChallenge(response, text5, isHTML)) {
10978
+ if (isCloudflareChallenge(response, text6, isHTML)) {
10628
10979
  activityMonitor.logComplete(activityId, response.status);
10629
10980
  return { url, title: "", content: "", error: `HTTP ${response.status}: Blocked by Cloudflare challenge page`, status: response.status };
10630
10981
  }
10631
10982
  if (!isHTML) {
10632
10983
  activityMonitor.logComplete(activityId, response.status);
10633
- const title = extractTextTitle(text5, url);
10634
- if (mimeType !== "text/markdown" && mimeType !== "text/x-markdown") return { url, title, content: text5, error: null };
10984
+ const title = extractTextTitle(text6, url);
10985
+ if (mimeType !== "text/markdown" && mimeType !== "text/x-markdown") return { url, title, content: text6, error: null };
10635
10986
  const declaredLinks2 = discoverDeclaredWebLinks(null, response.headers.get("link"), response.url || url);
10636
- const markdown2 = { url, title, content: appendDeclaredWebLinks(text5, declaredLinks2), error: null, declaredLinks: declaredLinks2 };
10637
- if (!preferMarkdown || text5.trim().length >= MIN_USEFUL_CONTENT2) return markdown2;
10987
+ const markdown2 = { url, title, content: appendDeclaredWebLinks(text6, declaredLinks2), error: null, declaredLinks: declaredLinks2 };
10988
+ if (!preferMarkdown || text6.trim().length >= MIN_USEFUL_CONTENT2) return markdown2;
10638
10989
  const normal = await extractViaHttp(url, Math.max(1, timeoutMs - (Date.now() - startedAt)), signal, options, false);
10639
10990
  if (signal?.aborted || isNonRecoverableHttpError(normal.error) || normal.status === 404 || normal.status === 410 || isAbortError5(normal.error)) return normal;
10640
10991
  const normalHasBody = normal.content.trim() !== appendDeclaredWebLinks("", normal.declaredLinks ?? []).trim();
@@ -10647,7 +10998,7 @@ Browser retry failed: ${normal.error}` : "")
10647
10998
  };
10648
10999
  }
10649
11000
  const { parseHTML } = await import("linkedom");
10650
- const { document } = parseHTML(text5);
11001
+ const { document } = parseHTML(text6);
10651
11002
  const documentTitle = document.title?.trim() ?? "";
10652
11003
  const declaredLinks = discoverDeclaredWebLinks(
10653
11004
  document,
@@ -10658,7 +11009,7 @@ Browser retry failed: ${normal.error}` : "")
10658
11009
  const reader = new Readability(document);
10659
11010
  const article = reader.parse();
10660
11011
  if (!article) {
10661
- const rscResult = extractRSCContent(text5);
11012
+ const rscResult = extractRSCContent(text6);
10662
11013
  if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT2) {
10663
11014
  activityMonitor.logComplete(activityId, response.status);
10664
11015
  return {
@@ -10670,7 +11021,7 @@ Browser retry failed: ${normal.error}` : "")
10670
11021
  };
10671
11022
  }
10672
11023
  controller.signal.throwIfAborted();
10673
- const defuddleResult = await extractWithDefuddle(text5, response.url || url);
11024
+ const defuddleResult = await extractWithDefuddle(text6, response.url || url);
10674
11025
  controller.signal.throwIfAborted();
10675
11026
  if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT2) {
10676
11027
  activityMonitor.logComplete(activityId, response.status);
@@ -10683,7 +11034,7 @@ Browser retry failed: ${normal.error}` : "")
10683
11034
  };
10684
11035
  }
10685
11036
  activityMonitor.logComplete(activityId, response.status);
10686
- const jsRendered = isLikelyJSRendered(text5);
11037
+ const jsRendered = isLikelyJSRendered(text6);
10687
11038
  const errorMsg = jsRendered ? "Page appears to be JavaScript-rendered (content loads dynamically)" : "Could not extract readable content from HTML structure";
10688
11039
  return {
10689
11040
  url,
@@ -10699,7 +11050,7 @@ Browser retry failed: ${normal.error}` : "")
10699
11050
  const markdown = (await getTurndown()).turndown(article.content);
10700
11051
  activityMonitor.logComplete(activityId, response.status);
10701
11052
  if (markdown.length < MIN_USEFUL_CONTENT2) {
10702
- const rscResult = extractRSCContent(text5);
11053
+ const rscResult = extractRSCContent(text6);
10703
11054
  if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT2) {
10704
11055
  return {
10705
11056
  url,
@@ -10710,7 +11061,7 @@ Browser retry failed: ${normal.error}` : "")
10710
11061
  };
10711
11062
  }
10712
11063
  controller.signal.throwIfAborted();
10713
- const defuddleResult = await extractWithDefuddle(text5, response.url || url);
11064
+ const defuddleResult = await extractWithDefuddle(text6, response.url || url);
10714
11065
  controller.signal.throwIfAborted();
10715
11066
  if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT2) {
10716
11067
  return {
@@ -10721,11 +11072,23 @@ Browser retry failed: ${normal.error}` : "")
10721
11072
  declaredLinks
10722
11073
  };
10723
11074
  }
11075
+ let error = "Page appears to be JavaScript-rendered (content loads dynamically)";
11076
+ if (!isLikelyJSRendered(text6)) {
11077
+ const { document: original } = parseHTML(text6);
11078
+ const hasExecutableScript = [...original.querySelectorAll("script")].some((script) => isExecutableScriptType(script.getAttribute("type")));
11079
+ for (const node of original.querySelectorAll("script, style, noscript, template")) node.remove();
11080
+ const visibleChars = (original.body?.textContent ?? "").replace(/\s+/g, " ").trim().length;
11081
+ const extractedChars = markdown.trim().length;
11082
+ const counts = `Extracted content appears incomplete: extracted ${extractedChars} characters from a page with ${visibleChars} characters of visible text`;
11083
+ if (visibleChars >= MIN_USEFUL_CONTENT2) error = counts;
11084
+ 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`;
11085
+ else error = extractedChars > 0 ? null : counts;
11086
+ }
10724
11087
  return {
10725
11088
  url,
10726
11089
  title: article.title || documentTitle,
10727
11090
  content: appendDeclaredWebLinks(markdown, declaredLinks),
10728
- error: isLikelyJSRendered(text5) ? "Page appears to be JavaScript-rendered (content loads dynamically)" : "Extracted content appears incomplete",
11091
+ error,
10729
11092
  declaredLinks
10730
11093
  };
10731
11094
  }
@@ -10753,14 +11116,14 @@ Browser retry failed: ${normal.error}` : "")
10753
11116
  }
10754
11117
  }
10755
11118
  }
10756
- function extractHeadingTitle(text5) {
10757
- const match = text5.match(/^#{1,2}\s+(.+)/m);
11119
+ function extractHeadingTitle(text6) {
11120
+ const match = text6.match(/^#{1,2}\s+(.+)/m);
10758
11121
  if (!match) return null;
10759
11122
  const cleaned = match[1].replace(/\*+/g, "").trim();
10760
11123
  return cleaned || null;
10761
11124
  }
10762
- function extractTextTitle(text5, url) {
10763
- return extractHeadingTitle(text5) ?? (new URL(url).pathname.split("/").pop() || url);
11125
+ function extractTextTitle(text6, url) {
11126
+ return extractHeadingTitle(text6) ?? (new URL(url).pathname.split("/").pop() || url);
10764
11127
  }
10765
11128
  async function fetchAllContent(urls, signal, options) {
10766
11129
  const results = await Promise.all(urls.map((url) => fetchLimit(() => extractContent(url, signal, options))));
@@ -10771,7 +11134,7 @@ async function fetchAllContent(urls, signal, options) {
10771
11134
  return sanitized.omissions.length > 0 ? { ...result, content: sanitized.text } : result;
10772
11135
  });
10773
11136
  }
10774
- 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;
11137
+ var DEFAULT_TIMEOUT_MS4, MAX_CONFIGURED_TIMEOUT_MS, CONCURRENT_LIMIT, WEB_SEARCH_CONFIG_PATH3, NON_RECOVERABLE_ERRORS, MIN_USEFUL_CONTENT2, SUPPORTED_IMAGE_TYPES, FETCH_PROVIDERS, DEFAULT_FETCH_PROVIDER_ORDER, REMOTE_HOSTED_FETCH_PROVIDERS, REDIRECT_STATUSES4, turndownInstance, fetchLimit, JINA_READER_BASE, DEFAULT_RANGE_FRAMES, MIN_FRAME_INTERVAL, JAVASCRIPT_MIME_TYPES, BROWSER_ACCEPT, MARKDOWN_FIRST_ACCEPT;
10775
11138
  var init_extract = __esm({
10776
11139
  "extract.ts"() {
10777
11140
  init_activity();
@@ -10785,6 +11148,7 @@ var init_extract = __esm({
10785
11148
  init_parallel();
10786
11149
  init_parallel_mcp();
10787
11150
  init_tinyfish();
11151
+ init_deepseek();
10788
11152
  init_search1api();
10789
11153
  init_querit();
10790
11154
  init_kagi();
@@ -10808,14 +11172,32 @@ var init_extract = __esm({
10808
11172
  NON_RECOVERABLE_ERRORS = ["Unsupported content type", "Response too large", "PDF extraction is disabled", "Image fetching is disabled"];
10809
11173
  MIN_USEFUL_CONTENT2 = 500;
10810
11174
  SUPPORTED_IMAGE_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
10811
- FETCH_PROVIDERS = ["http", "firecrawl", "crawl4ai", "jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini"];
11175
+ FETCH_PROVIDERS = ["http", "firecrawl", "crawl4ai", "jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini", "deepseek"];
10812
11176
  DEFAULT_FETCH_PROVIDER_ORDER = ["http", "firecrawl", "crawl4ai", "jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "brightdata", "gemini"];
10813
- REMOTE_HOSTED_FETCH_PROVIDERS = /* @__PURE__ */ new Set(["jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini"]);
11177
+ REMOTE_HOSTED_FETCH_PROVIDERS = /* @__PURE__ */ new Set(["jina", "tinyfish", "search1api", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini", "deepseek"]);
10814
11178
  REDIRECT_STATUSES4 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
10815
11179
  fetchLimit = pLimit(CONCURRENT_LIMIT);
10816
11180
  JINA_READER_BASE = "https://r.jina.ai/";
10817
11181
  DEFAULT_RANGE_FRAMES = 6;
10818
11182
  MIN_FRAME_INTERVAL = 5;
11183
+ JAVASCRIPT_MIME_TYPES = /* @__PURE__ */ new Set([
11184
+ "application/ecmascript",
11185
+ "application/javascript",
11186
+ "application/x-ecmascript",
11187
+ "application/x-javascript",
11188
+ "text/ecmascript",
11189
+ "text/javascript",
11190
+ "text/javascript1.0",
11191
+ "text/javascript1.1",
11192
+ "text/javascript1.2",
11193
+ "text/javascript1.3",
11194
+ "text/javascript1.4",
11195
+ "text/javascript1.5",
11196
+ "text/jscript",
11197
+ "text/livescript",
11198
+ "text/x-ecmascript",
11199
+ "text/x-javascript"
11200
+ ]);
10819
11201
  BROWSER_ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8";
10820
11202
  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";
10821
11203
  }
@@ -10827,7 +11209,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
10827
11209
  // package.json
10828
11210
  var package_default = {
10829
11211
  name: "pi-web-access",
10830
- version: "0.42.0",
11212
+ version: "0.44.0",
10831
11213
  description: "Web search, URL fetching, GitHub repo cloning, PDF extraction, YouTube video understanding, and local video analysis for Pi coding agent. Supports OpenAI, Brave, Parallel, TinyFish, Search1API, Searchinfinity, Querit, Tavily, Firecrawl, Crawl4AI, Jina, SERPdive, Kagi, Ollama, AnySearch, Bright Data SERP, SerpBase, SerpApi, Serply, You.com, SearXNG, degoog, Exa, Perplexity, Gemini, Kimi, and Mistral.",
10832
11214
  type: "module",
10833
11215
  bin: {
@@ -10917,7 +11299,7 @@ var package_default = {
10917
11299
  },
10918
11300
  pi: {
10919
11301
  extensions: [
10920
- "./dist"
11302
+ "./index.ts"
10921
11303
  ],
10922
11304
  video: "https://github.com/nicobailon/pi-web-access/raw/refs/heads/main/pi-web-fetch-demo.mp4"
10923
11305
  }
@@ -19404,7 +19786,7 @@ init_gemini_api();
19404
19786
  init_gemini_adc();
19405
19787
  init_gemini_web();
19406
19788
  init_perplexity();
19407
- import { existsSync as existsSync42, readFileSync as readFileSync42 } from "node:fs";
19789
+ import { existsSync as existsSync43, readFileSync as readFileSync43 } from "node:fs";
19408
19790
 
19409
19791
  // exa.ts
19410
19792
  init_activity();
@@ -19605,14 +19987,14 @@ async function callExaMcp(toolName, args, signal) {
19605
19987
  const message = parsed.result.content?.find((item) => item.type === "text" && typeof item.text === "string")?.text?.trim();
19606
19988
  throw new Error(message || "Exa MCP returned an error");
19607
19989
  }
19608
- const text5 = parsed.result?.content?.find((item) => item.type === "text" && typeof item.text === "string" && item.text.trim().length > 0)?.text;
19609
- if (!text5) {
19990
+ const text6 = parsed.result?.content?.find((item) => item.type === "text" && typeof item.text === "string" && item.text.trim().length > 0)?.text;
19991
+ if (!text6) {
19610
19992
  throw new Error("Exa MCP returned empty content");
19611
19993
  }
19612
- return text5;
19994
+ return text6;
19613
19995
  }
19614
- function parseMcpResults(text5) {
19615
- const blocks = text5.split(/(?=^Title: )/m).filter((block) => block.trim().length > 0);
19996
+ function parseMcpResults(text6) {
19997
+ const blocks = text6.split(/(?=^Title: )/m).filter((block) => block.trim().length > 0);
19616
19998
  const parsed = blocks.map((block) => {
19617
19999
  const title = block.match(/^Title: (.+)/m)?.[1]?.trim() ?? "";
19618
20000
  const url = block.match(/^URL: (.+)/m)?.[1]?.trim() ?? "";
@@ -19677,17 +20059,17 @@ function buildMcpQuery(query, options) {
19677
20059
  function isAbortMessage(message) {
19678
20060
  return message.toLowerCase().includes("abort");
19679
20061
  }
19680
- function parseJsonMcpResults(text5) {
20062
+ function parseJsonMcpResults(text6) {
19681
20063
  try {
19682
- const results = JSON.parse(text5).results;
20064
+ const results = JSON.parse(text6).results;
19683
20065
  return Array.isArray(results) && results.length > 0 ? results : null;
19684
20066
  } catch {
19685
20067
  return null;
19686
20068
  }
19687
20069
  }
19688
20070
  async function searchWithExaMcpTool(tool, args, options) {
19689
- const text5 = await callExaMcp(tool, args, options.signal);
19690
- const jsonResults = parseJsonMcpResults(text5);
20071
+ const text6 = await callExaMcp(tool, args, options.signal);
20072
+ const jsonResults = parseJsonMcpResults(text6);
19691
20073
  if (jsonResults) {
19692
20074
  return toSearchResponse(
19693
20075
  buildAnswerFromSearchResults(jsonResults),
@@ -19695,7 +20077,7 @@ async function searchWithExaMcpTool(tool, args, options) {
19695
20077
  options.includeContent ? mapInlineContent(jsonResults) : null
19696
20078
  );
19697
20079
  }
19698
- const textResults = parseMcpResults(text5);
20080
+ const textResults = parseMcpResults(text6);
19699
20081
  if (!textResults) return null;
19700
20082
  return toSearchResponse(
19701
20083
  buildAnswerFromMcpResults(textResults),
@@ -20047,7 +20429,7 @@ Get a key at https://brave.com/search/api/`
20047
20429
  );
20048
20430
  }
20049
20431
  const numResults = normalizeSearchResultCount(options.numResults);
20050
- const domainFilters = normalizeDomainFilters(options.domainFilter);
20432
+ const domainFilters2 = normalizeDomainFilters(options.domainFilter);
20051
20433
  const searchQuery = buildBraveQuery(query, options.domainFilter);
20052
20434
  const activityId = activityMonitor.logStart({ type: "api", query: searchQuery });
20053
20435
  const params = new URLSearchParams({
@@ -20097,7 +20479,7 @@ Get a key at https://brave.com/search/api/`
20097
20479
  activityMonitor.logComplete(activityId, response.status);
20098
20480
  const results = [];
20099
20481
  for (const item of data.web?.results ?? []) {
20100
- if (!item.url || !matchesDomainFilters(item.url, domainFilters)) continue;
20482
+ if (!item.url || !matchesDomainFilters(item.url, domainFilters2)) continue;
20101
20483
  results.push({
20102
20484
  title: stripHtml(item.title || "") || item.url,
20103
20485
  url: item.url,
@@ -20476,8 +20858,8 @@ function isWebSearchCall(item) {
20476
20858
  return !!item && typeof item === "object" && item.type === "web_search_call";
20477
20859
  }
20478
20860
  async function parseOpenAIResponse(response) {
20479
- const text5 = await response.text();
20480
- const trimmed = text5.trim();
20861
+ const text6 = await response.text();
20862
+ const trimmed = text6.trim();
20481
20863
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
20482
20864
  try {
20483
20865
  const parsed = JSON.parse(trimmed);
@@ -20493,7 +20875,7 @@ async function parseOpenAIResponse(response) {
20493
20875
  let completedResponse = null;
20494
20876
  let webSearchCallSeen = false;
20495
20877
  let streamError = null;
20496
- for (const line of text5.split("\n")) {
20878
+ for (const line of text6.split("\n")) {
20497
20879
  if (!line.startsWith("data: ")) continue;
20498
20880
  const data = line.slice(6).trim();
20499
20881
  if (!data || data === "[DONE]") continue;
@@ -20545,11 +20927,11 @@ function cleanSourceUrl(rawUrl) {
20545
20927
  return rawUrl.replace(/[?&]utm_source=openai$/, "");
20546
20928
  }
20547
20929
  }
20548
- function extractSnippetAround(text5, start, end) {
20549
- if (typeof start !== "number" || typeof end !== "number" || !text5) return "";
20930
+ function extractSnippetAround(text6, start, end) {
20931
+ if (typeof start !== "number" || typeof end !== "number" || !text6) return "";
20550
20932
  const before = Math.max(0, start - 100);
20551
- const after = Math.min(text5.length, end + 100);
20552
- const snippet = text5.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
20933
+ const after = Math.min(text6.length, end + 100);
20934
+ const snippet = text6.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
20553
20935
  return snippet.length > 300 ? `${snippet.slice(0, 297)}...` : snippet;
20554
20936
  }
20555
20937
  function addResult(results, seen, url, title, snippet = "") {
@@ -20572,7 +20954,7 @@ function extractSearchResults(output, numResults) {
20572
20954
  if (!Array.isArray(content)) continue;
20573
20955
  for (const part of content) {
20574
20956
  if (!part || typeof part !== "object") continue;
20575
- const text5 = typeof part.text === "string" ? part.text : "";
20957
+ const text6 = typeof part.text === "string" ? part.text : "";
20576
20958
  const annotations = part.annotations;
20577
20959
  if (!Array.isArray(annotations)) continue;
20578
20960
  for (const annotation of annotations) {
@@ -20582,7 +20964,7 @@ function extractSearchResults(output, numResults) {
20582
20964
  seenUrls,
20583
20965
  annotation.url,
20584
20966
  annotation.title,
20585
- extractSnippetAround(text5, annotation.start_index, annotation.end_index)
20967
+ extractSnippetAround(text6, annotation.start_index, annotation.end_index)
20586
20968
  );
20587
20969
  }
20588
20970
  }
@@ -20614,8 +20996,8 @@ function extractAnswer(output) {
20614
20996
  if (!Array.isArray(content)) continue;
20615
20997
  for (const part of content) {
20616
20998
  if (!part || typeof part !== "object") continue;
20617
- const text5 = part.text;
20618
- if (typeof text5 === "string" && text5.trim().length > 0) parts.push(text5);
20999
+ const text6 = part.text;
21000
+ if (typeof text6 === "string" && text6.trim().length > 0) parts.push(text6);
20619
21001
  }
20620
21002
  }
20621
21003
  return parts.join("\n").trim();
@@ -20667,10 +21049,10 @@ function buildAlphaSearchHeaders(headers, apiKey) {
20667
21049
  return result;
20668
21050
  }
20669
21051
  async function parseAlphaSearchResponse(response, numResults = 5) {
20670
- const text5 = await response.text();
21052
+ const text6 = await response.text();
20671
21053
  let payload;
20672
21054
  try {
20673
- payload = JSON.parse(text5);
21055
+ payload = JSON.parse(text6);
20674
21056
  } catch {
20675
21057
  throw new Error("OpenAI alpha/search returned invalid JSON");
20676
21058
  }
@@ -20900,7 +21282,7 @@ function businessErrorStatus(codeN, code, message) {
20900
21282
  async function searchinfinityJsonRequest(apiKey, body, signal) {
20901
21283
  let response;
20902
21284
  try {
20903
- response = await fetch(SEARCHINFINITY_SEARCH_URL, {
21285
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("searchinfinity", SEARCHINFINITY_SEARCH_URL, loadConfig11().searchinfinityBaseUrl), {
20904
21286
  method: "POST",
20905
21287
  headers: {
20906
21288
  Authorization: `Bearer ${apiKey}`,
@@ -20908,7 +21290,7 @@ async function searchinfinityJsonRequest(apiKey, body, signal) {
20908
21290
  },
20909
21291
  body: JSON.stringify(body),
20910
21292
  signal: requestSignal6(signal, SEARCH_TIMEOUT_MS7)
20911
- });
21293
+ }, ["Authorization"]);
20912
21294
  } catch (err) {
20913
21295
  const message = errorMessage5(err);
20914
21296
  const redactedMessage = redactCredential(message, apiKey);
@@ -21278,7 +21660,7 @@ async function searchWithYou(query, options = {}) {
21278
21660
  let response;
21279
21661
  let entries;
21280
21662
  try {
21281
- response = await fetchWithCredentialRedirects(YOU_SEARCH_URL, {
21663
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("you", YOU_SEARCH_URL, loadConfig14().youBaseUrl), {
21282
21664
  method: "POST",
21283
21665
  headers: { Accept: "application/json", "Content-Type": "application/json", "X-API-Key": apiKey },
21284
21666
  body: JSON.stringify(body),
@@ -21419,7 +21801,8 @@ function buildSearchRequest(query, options, numResults) {
21419
21801
  const recency = options.recencyFilter ? ` published in the past ${options.recencyFilter}` : "";
21420
21802
  const exclusions = filters.excludes.map((domain) => ` -site:${domain}`).join("");
21421
21803
  const constrainedQuery = `${query.trim()}${exclusions}${recency}`.trim();
21422
- const url = new URL(encodeURIComponent(constrainedQuery), JINA_SEARCH_BASE_URL);
21804
+ if (/^\.{1,2}$/.test(constrainedQuery)) throw new Error("Jina Search query must not be a dot path segment");
21805
+ const url = new URL(encodeURIComponent(constrainedQuery), resolveProviderApiUrl("jinaSearch", JINA_SEARCH_BASE_URL, loadConfig16().jinaSearchBaseUrl));
21423
21806
  url.searchParams.set("count", String(numResults));
21424
21807
  for (const domain of filters.includes) url.searchParams.append("site", domain);
21425
21808
  return { url: url.toString(), filters };
@@ -21506,7 +21889,7 @@ async function searchWithJina(query, options = {}) {
21506
21889
  const request = requestSignal10(options.signal);
21507
21890
  let response;
21508
21891
  try {
21509
- response = await fetch(url, {
21892
+ response = await fetchWithCredentialRedirects(String(url), {
21510
21893
  headers: {
21511
21894
  "Accept": "application/json",
21512
21895
  "Authorization": `Bearer ${apiKey}`,
@@ -21515,7 +21898,7 @@ async function searchWithJina(query, options = {}) {
21515
21898
  "X-Retain-Images": "none"
21516
21899
  },
21517
21900
  signal: request.signal
21518
- });
21901
+ }, ["Authorization"]);
21519
21902
  } catch (err) {
21520
21903
  rethrowRequestError(err, apiKey, activityId, request, options.signal);
21521
21904
  }
@@ -21718,7 +22101,7 @@ async function searchWithSerpdive(query, options = {}) {
21718
22101
  const activityId = activityMonitor.logStart({ type: "api", query });
21719
22102
  let response;
21720
22103
  try {
21721
- response = await fetch(SERPDIVE_API_URL, {
22104
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("serpdive", SERPDIVE_API_URL, loadConfig17().serpdiveBaseUrl), {
21722
22105
  method: "POST",
21723
22106
  headers: {
21724
22107
  "Authorization": `Bearer ${apiKey}`,
@@ -21726,7 +22109,7 @@ async function searchWithSerpdive(query, options = {}) {
21726
22109
  },
21727
22110
  body: JSON.stringify(body),
21728
22111
  signal: requestSignal11(options.signal)
21729
- });
22112
+ }, ["Authorization"]);
21730
22113
  } catch (err) {
21731
22114
  const message = errorMessage11(err);
21732
22115
  const redactedMessage = redactCredential(message, apiKey);
@@ -21900,12 +22283,12 @@ async function searchWithBocha(query, options = {}) {
21900
22283
  const activityId = activityMonitor.logStart({ type: "api", query });
21901
22284
  let response;
21902
22285
  try {
21903
- response = await fetch(BOCHA_SEARCH_URL, {
22286
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("bocha", BOCHA_SEARCH_URL, loadConfig19().bochaBaseUrl), {
21904
22287
  method: "POST",
21905
22288
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
21906
22289
  body: JSON.stringify({ query, count: numResults, freshness: mapFreshness(options.recencyFilter), summary: true }),
21907
22290
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS15), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS15)
21908
- });
22291
+ }, ["Authorization"]);
21909
22292
  } catch (err) {
21910
22293
  const message = errorMessage13(err);
21911
22294
  const redactedMessage = redactCredential(message, apiKey);
@@ -22289,8 +22672,8 @@ function parseResponse(value) {
22289
22672
  if (!Array.isArray(envelope.results)) throw invalidResponse4("expected a results array");
22290
22673
  return envelope.results;
22291
22674
  }
22292
- function redactSecrets(text5, secrets) {
22293
- let redacted = text5;
22675
+ function redactSecrets(text6, secrets) {
22676
+ let redacted = text6;
22294
22677
  for (const secret of secrets) redacted = redactCredential(redacted, secret);
22295
22678
  return redacted;
22296
22679
  }
@@ -22571,7 +22954,7 @@ async function searchWithAnySearch(query, options = {}) {
22571
22954
  const activityId = activityMonitor.logStart({ type: "api", query });
22572
22955
  let response;
22573
22956
  try {
22574
- response = await fetch(ANYSEARCH_API_URL, {
22957
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("anysearch", ANYSEARCH_API_URL, loadConfig23().anysearchBaseUrl), {
22575
22958
  method: "POST",
22576
22959
  headers: {
22577
22960
  ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
@@ -22579,7 +22962,7 @@ async function searchWithAnySearch(query, options = {}) {
22579
22962
  },
22580
22963
  body: JSON.stringify(body),
22581
22964
  signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS20), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS20)
22582
- });
22965
+ }, ["Authorization"]);
22583
22966
  } catch (err) {
22584
22967
  const message = errorMessage16(err);
22585
22968
  const redactedMessage = redactCredential(message, apiKey);
@@ -22756,7 +23139,7 @@ async function searchWithXCrawl(query, options = {}) {
22756
23139
  const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS21);
22757
23140
  let response;
22758
23141
  try {
22759
- response = await fetch(XCRAWL_API_URL, {
23142
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("xcrawl", XCRAWL_API_URL, loadConfig24().xcrawlBaseUrl), {
22760
23143
  method: "POST",
22761
23144
  headers: {
22762
23145
  Authorization: `Bearer ${apiKey}`,
@@ -22764,7 +23147,7 @@ async function searchWithXCrawl(query, options = {}) {
22764
23147
  },
22765
23148
  body: JSON.stringify(body),
22766
23149
  signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal
22767
- });
23150
+ }, ["Authorization"]);
22768
23151
  } catch (err) {
22769
23152
  const message = errorMessage17(err);
22770
23153
  if (options.signal?.aborted) {
@@ -22818,7 +23201,8 @@ init_utils();
22818
23201
  import { existsSync as existsSync29, readFileSync as readFileSync29 } from "node:fs";
22819
23202
  var XAI_RESPONSES_URL = "https://api.x.ai/v1/responses";
22820
23203
  var CONFIG_PATH26 = getWebSearchConfigPath();
22821
- var SEARCH_TIMEOUT_MS22 = 6e4;
23204
+ var DEFAULT_SEARCH_TIMEOUT_MS = 6e4;
23205
+ var MAX_SEARCH_TIMEOUT_MS = 6e5;
22822
23206
  var WEB_SEARCH_AUTH_MODEL_CANDIDATES = ["grok-4.5", "grok-4.3", "grok-build-0.1"];
22823
23207
  var X_SEARCH_AUTH_MODEL_CANDIDATES = ["grok-4.6", ...WEB_SEARCH_AUTH_MODEL_CANDIDATES];
22824
23208
  var DEFAULT_XAI_SEARCH_TOOLS = ["web_search"];
@@ -22845,6 +23229,29 @@ function resolveConfiguredSearchModel2(value) {
22845
23229
  }
22846
23230
  return value.trim();
22847
23231
  }
23232
+ function resolveConfiguredResponsesUrl2(value) {
23233
+ if (value === void 0) return void 0;
23234
+ if (typeof value !== "string" || value.trim().length === 0) {
23235
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH26} must be an absolute http(s) URL`);
23236
+ }
23237
+ let url;
23238
+ try {
23239
+ url = new URL(value.trim());
23240
+ } catch {
23241
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH26} must be an absolute http(s) URL`);
23242
+ }
23243
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
23244
+ throw new Error(`xaiResponsesUrl in ${CONFIG_PATH26} must use http or https`);
23245
+ }
23246
+ return url.toString();
23247
+ }
23248
+ function resolveConfiguredSearchTimeoutMs(value) {
23249
+ if (value === void 0) return DEFAULT_SEARCH_TIMEOUT_MS;
23250
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
23251
+ throw new Error(`xaiSearchTimeoutMs in ${CONFIG_PATH26} must be a positive integer`);
23252
+ }
23253
+ return Math.min(value, MAX_SEARCH_TIMEOUT_MS);
23254
+ }
22848
23255
  function resolveConfiguredSearchTools(value) {
22849
23256
  if (value === void 0) return [...DEFAULT_XAI_SEARCH_TOOLS];
22850
23257
  if (!Array.isArray(value) || value.length === 0) {
@@ -22890,7 +23297,7 @@ async function resolveXaiAuth(ctx, signal) {
22890
23297
  const config = loadConfig25();
22891
23298
  const modelOverride = resolveConfiguredSearchModel2(config.xaiSearchModel);
22892
23299
  const tools = resolveConfiguredSearchTools(config.xaiSearchTools);
22893
- if (ctx) {
23300
+ if (ctx && resolveConfiguredResponsesUrl2(config.xaiResponsesUrl) === void 0) {
22894
23301
  const auth = await resolvePiAuth2(ctx, modelOverride, tools);
22895
23302
  if (auth) return auth;
22896
23303
  }
@@ -22911,13 +23318,16 @@ async function resolveXaiAuth(ctx, signal) {
22911
23318
  async function isXaiSearchAvailable(ctx) {
22912
23319
  let config;
22913
23320
  let tools;
23321
+ let customUrl;
22914
23322
  try {
22915
23323
  config = loadConfig25();
22916
23324
  tools = resolveConfiguredSearchTools(config.xaiSearchTools);
23325
+ customUrl = resolveConfiguredResponsesUrl2(config.xaiResponsesUrl);
23326
+ resolveConfiguredSearchTimeoutMs(config.xaiSearchTimeoutMs);
22917
23327
  } catch {
22918
23328
  return false;
22919
23329
  }
22920
- if (ctx && await resolvePiAuth2(ctx, void 0, tools)) return true;
23330
+ if (ctx && customUrl === void 0 && await resolvePiAuth2(ctx, void 0, tools)) return true;
22921
23331
  return hasCredentialSource({
22922
23332
  provider: "xAI",
22923
23333
  configuredValue: config.xaiApiKey,
@@ -22986,11 +23396,11 @@ function addSources(results, seen, sources) {
22986
23396
  if (!Array.isArray(sources)) return;
22987
23397
  for (const source of sources) addSource(results, seen, source);
22988
23398
  }
22989
- function extractSnippetAround2(text5, start, end) {
22990
- if (typeof start !== "number" || typeof end !== "number" || !text5) return "";
23399
+ function extractSnippetAround2(text6, start, end) {
23400
+ if (typeof start !== "number" || typeof end !== "number" || !text6) return "";
22991
23401
  const before = Math.max(0, start - 100);
22992
- const after = Math.min(text5.length, end + 100);
22993
- const snippet = text5.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
23402
+ const after = Math.min(text6.length, end + 100);
23403
+ const snippet = text6.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
22994
23404
  return snippet.length > 300 ? `${snippet.slice(0, 297)}...` : snippet;
22995
23405
  }
22996
23406
  function extractAnswer2(output) {
@@ -23001,8 +23411,8 @@ function extractAnswer2(output) {
23001
23411
  if (!Array.isArray(content)) continue;
23002
23412
  for (const part of content) {
23003
23413
  if (!part || typeof part !== "object") continue;
23004
- const text5 = part.text;
23005
- if (typeof text5 === "string" && text5.trim().length > 0) parts.push(text5);
23414
+ const text6 = part.text;
23415
+ if (typeof text6 === "string" && text6.trim().length > 0) parts.push(text6);
23006
23416
  }
23007
23417
  }
23008
23418
  return parts.join("\n").trim();
@@ -23016,7 +23426,7 @@ function extractSearchResults2(output, citations, numResults) {
23016
23426
  if (!Array.isArray(content)) continue;
23017
23427
  for (const part of content) {
23018
23428
  if (!part || typeof part !== "object") continue;
23019
- const text5 = typeof part.text === "string" ? part.text : "";
23429
+ const text6 = typeof part.text === "string" ? part.text : "";
23020
23430
  const annotations = part.annotations;
23021
23431
  if (!Array.isArray(annotations)) continue;
23022
23432
  for (const annotation of annotations) {
@@ -23027,7 +23437,7 @@ function extractSearchResults2(output, citations, numResults) {
23027
23437
  seenUrls,
23028
23438
  annotation.url,
23029
23439
  annotation.title,
23030
- extractSnippetAround2(text5, annotation.start_index, annotation.end_index)
23440
+ extractSnippetAround2(text6, annotation.start_index, annotation.end_index)
23031
23441
  );
23032
23442
  }
23033
23443
  }
@@ -23047,9 +23457,17 @@ function extractSearchResults2(output, citations, numResults) {
23047
23457
  return results;
23048
23458
  }
23049
23459
  async function searchWithXai(query, options = {}, ctx) {
23050
- const tools = resolveConfiguredSearchTools(loadConfig25().xaiSearchTools);
23460
+ const config = loadConfig25();
23461
+ const tools = resolveConfiguredSearchTools(config.xaiSearchTools);
23462
+ const customUrl = resolveConfiguredResponsesUrl2(config.xaiResponsesUrl);
23463
+ const timeoutMs = resolveConfiguredSearchTimeoutMs(config.xaiSearchTimeoutMs);
23051
23464
  const auth = await resolveXaiAuth(ctx, options.signal);
23052
23465
  if (!auth) {
23466
+ if (customUrl) {
23467
+ throw new Error(
23468
+ `xAI search unavailable: xaiResponsesUrl is set, so Pi's xAI sign-in is not used. Set xaiApiKey in ${CONFIG_PATH26} or the XAI_API_KEY environment variable to the key for that endpoint.`
23469
+ );
23470
+ }
23053
23471
  throw new Error(
23054
23472
  `xAI search unavailable. Either:
23055
23473
  1. Use /login to sign in with a SuperGrok or X Premium subscription
@@ -23059,7 +23477,7 @@ async function searchWithXai(query, options = {}, ctx) {
23059
23477
  }
23060
23478
  const activityId = activityMonitor.logStart({ type: "api", query });
23061
23479
  try {
23062
- const response = await fetch(XAI_RESPONSES_URL, {
23480
+ const response = await fetch(customUrl ?? XAI_RESPONSES_URL, {
23063
23481
  method: "POST",
23064
23482
  headers: {
23065
23483
  ...toRequestHeaders2(auth.headers),
@@ -23071,7 +23489,7 @@ async function searchWithXai(query, options = {}, ctx) {
23071
23489
  input: buildInput(query, options, tools),
23072
23490
  tools: tools.map((type) => ({ type }))
23073
23491
  }),
23074
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS22), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS22)
23492
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(timeoutMs), options.signal]) : AbortSignal.timeout(timeoutMs)
23075
23493
  });
23076
23494
  if (!response.ok) {
23077
23495
  activityMonitor.logError(activityId, `HTTP ${response.status}`);
@@ -23118,7 +23536,7 @@ init_utils();
23118
23536
  import { existsSync as existsSync30, readFileSync as readFileSync30 } from "node:fs";
23119
23537
  var BRIGHTDATA_API_URL = "https://api.brightdata.com/request";
23120
23538
  var CONFIG_PATH27 = getWebSearchConfigPath();
23121
- var SEARCH_TIMEOUT_MS23 = 6e4;
23539
+ var SEARCH_TIMEOUT_MS22 = 6e4;
23122
23540
  var ZONE_PATTERN = /^[A-Za-z0-9_-]+$/;
23123
23541
  var RECENCY_TBS = {
23124
23542
  day: "qdr:d",
@@ -23257,7 +23675,7 @@ function passesDomainFilters4(url, filters) {
23257
23675
  return filters.include.some((domain) => domainMatches4(hostname2, domain));
23258
23676
  }
23259
23677
  function requestSignal12(signal) {
23260
- const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS23);
23678
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS22);
23261
23679
  return signal ? AbortSignal.any([signal, timeout]) : timeout;
23262
23680
  }
23263
23681
  function errorMessage18(err) {
@@ -23265,8 +23683,8 @@ function errorMessage18(err) {
23265
23683
  }
23266
23684
  var STATUS_SHAPED_PATTERN = /\b(?:error|status|http)[\s:=-]{1,4}(\d{3})\b/gi;
23267
23685
  var QUOTA_SHAPED_PATTERN = /rate limit|quota|too many requests/gi;
23268
- function untrustedText(text5, limit = 300) {
23269
- return text5.replace(/\s+/g, " ").trim().slice(0, limit).replace(STATUS_SHAPED_PATTERN, "upstream $1").replace(QUOTA_SHAPED_PATTERN, "upstream rate-limit notice");
23686
+ function untrustedText(text6, limit = 300) {
23687
+ return text6.replace(/\s+/g, " ").trim().slice(0, limit).replace(STATUS_SHAPED_PATTERN, "upstream $1").replace(QUOTA_SHAPED_PATTERN, "upstream rate-limit notice");
23270
23688
  }
23271
23689
  function invalidResponse7(zone, message) {
23272
23690
  return new Error(`Bright Data API returned invalid response for zone ${zone}: ${message}`);
@@ -23357,7 +23775,7 @@ async function searchWithBrightData(query, options = {}) {
23357
23775
  const activityId = activityMonitor.logStart({ type: "api", query: searchQuery });
23358
23776
  let response;
23359
23777
  try {
23360
- response = await fetch(BRIGHTDATA_API_URL, {
23778
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("brightdata", BRIGHTDATA_API_URL, loadConfig26().brightdataBaseUrl), {
23361
23779
  method: "POST",
23362
23780
  headers: {
23363
23781
  "Authorization": `Bearer ${apiKey}`,
@@ -23365,7 +23783,7 @@ async function searchWithBrightData(query, options = {}) {
23365
23783
  },
23366
23784
  body: JSON.stringify(body),
23367
23785
  signal: requestSignal12(options.signal)
23368
- });
23786
+ }, ["Authorization"]);
23369
23787
  } catch (err) {
23370
23788
  const message = errorMessage18(err);
23371
23789
  const redactedMessage = redactCredential(message, apiKey);
@@ -23415,7 +23833,7 @@ init_utils();
23415
23833
  import { existsSync as existsSync31, readFileSync as readFileSync31 } from "node:fs";
23416
23834
  var SERPBASE_API_URL = "https://api.serpbase.dev/google/search";
23417
23835
  var CONFIG_PATH28 = getWebSearchConfigPath();
23418
- var SEARCH_TIMEOUT_MS24 = 6e4;
23836
+ var SEARCH_TIMEOUT_MS23 = 6e4;
23419
23837
  var RECENCY_TBS2 = {
23420
23838
  day: "qdr:d",
23421
23839
  week: "qdr:w",
@@ -23524,7 +23942,7 @@ async function searchWithSerpBase(query, options = {}) {
23524
23942
  const apiKey = await requireApiKey9(options.signal);
23525
23943
  const numResults = normalizeCount3(options.numResults);
23526
23944
  const filters = parseDomainFilter5(options.domainFilter);
23527
- const url = new URL(SERPBASE_API_URL);
23945
+ const url = new URL(resolveProviderApiUrl("serpbase", SERPBASE_API_URL, loadConfig27().serpbaseBaseUrl));
23528
23946
  url.searchParams.set("q", buildQuery2(query, filters));
23529
23947
  url.searchParams.set("api_key", apiKey);
23530
23948
  url.searchParams.set("num", String(numResults));
@@ -23532,10 +23950,10 @@ async function searchWithSerpBase(query, options = {}) {
23532
23950
  const activityId = activityMonitor.logStart({ type: "api", query });
23533
23951
  let response;
23534
23952
  try {
23535
- response = await fetch(url, {
23953
+ response = await fetchWithCredentialRedirects(String(url), {
23536
23954
  headers: { Accept: "application/json" },
23537
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS24), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS24)
23538
- });
23955
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS23), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS23)
23956
+ }, [], ["api_key"]);
23539
23957
  } catch (err) {
23540
23958
  const message = errorMessage19(err);
23541
23959
  const redactedMessage = redactCredential(message, apiKey);
@@ -23582,9 +24000,9 @@ init_search_result_count_normalization();
23582
24000
  init_credential_source();
23583
24001
  init_utils();
23584
24002
  import { existsSync as existsSync32, readFileSync as readFileSync32 } from "node:fs";
23585
- var SERPAPI_SEARCH_URL = "https://serpapi.com/search.json";
24003
+ var SERPAPI_API_BASE_URL = "https://serpapi.com";
23586
24004
  var CONFIG_PATH29 = getWebSearchConfigPath();
23587
- var SEARCH_TIMEOUT_MS25 = 6e4;
24005
+ var SEARCH_TIMEOUT_MS24 = 6e4;
23588
24006
  var RECENCY_TBS3 = {
23589
24007
  day: "qdr:d",
23590
24008
  week: "qdr:w",
@@ -23678,25 +24096,26 @@ function isSerpApiAvailable() {
23678
24096
  return hasCredentialSource({ provider: "SerpApi", configuredValue: loadConfig28().serpapiApiKey, environmentValue: process.env.SERPAPI_KEY });
23679
24097
  }
23680
24098
  async function searchWithSerpApi(query, options = {}) {
24099
+ const apiUrl = resolveProviderApiUrl("serpapi", `${SERPAPI_API_BASE_URL}/search.json`, loadConfig28().serpapiBaseUrl);
23681
24100
  const apiKey = await requireApiKey10(options.signal);
23682
24101
  const numResults = normalizeSearchResultCount(options.numResults);
23683
24102
  const filters = parseDomainFilter6(options.domainFilter);
23684
24103
  const requestCount = options.domainFilter?.length ? Math.min(20, numResults + 5) : numResults;
23685
- const url = new URL(SERPAPI_SEARCH_URL);
24104
+ const url = new URL(apiUrl);
23686
24105
  url.searchParams.set("engine", "google");
23687
24106
  url.searchParams.set("q", buildQuery3(query, filters));
23688
24107
  url.searchParams.set("api_key", apiKey);
23689
24108
  url.searchParams.set("num", String(requestCount));
23690
24109
  if (options.recencyFilter) url.searchParams.set("tbs", RECENCY_TBS3[options.recencyFilter]);
23691
24110
  const activityId = activityMonitor.logStart({ type: "api", query });
23692
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS25);
24111
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS24);
23693
24112
  let response;
23694
24113
  let entries;
23695
24114
  try {
23696
- response = await fetch(url, {
24115
+ response = await fetchWithCredentialRedirects(url.toString(), {
23697
24116
  headers: { Accept: "application/json" },
23698
24117
  signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal
23699
- });
24118
+ }, [], ["api_key"]);
23700
24119
  if (!response.ok) {
23701
24120
  const errorText = await response.text();
23702
24121
  throw new Error(`SerpApi error ${response.status}: ${redactCredential(errorText, apiKey).slice(0, 300)}`);
@@ -23716,7 +24135,7 @@ async function searchWithSerpApi(query, options = {}) {
23716
24135
  }
23717
24136
  const message = errorMessage20(err);
23718
24137
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
23719
- const outgoing = providerTimeout ? new Error(`SerpApi request timed out after ${Math.round(SEARCH_TIMEOUT_MS25 / 1e3)}s`) : (() => {
24138
+ const outgoing = providerTimeout ? new Error(`SerpApi request timed out after ${Math.round(SEARCH_TIMEOUT_MS24 / 1e3)}s`) : (() => {
23720
24139
  const redactedMessage = redactCredential(message, apiKey);
23721
24140
  if (redactedMessage === message && err instanceof Error) return err;
23722
24141
  const redactedError = new Error(redactedMessage);
@@ -23750,9 +24169,9 @@ init_search_result_count_normalization();
23750
24169
  init_credential_source();
23751
24170
  init_utils();
23752
24171
  import { existsSync as existsSync33, readFileSync as readFileSync33 } from "node:fs";
23753
- var SERPER_SEARCH_URL = "https://google.serper.dev/search";
24172
+ var SERPER_API_BASE_URL = "https://google.serper.dev";
23754
24173
  var CONFIG_PATH30 = getWebSearchConfigPath();
23755
- var SEARCH_TIMEOUT_MS26 = 6e4;
24174
+ var SEARCH_TIMEOUT_MS25 = 6e4;
23756
24175
  var RECENCY_TBS4 = {
23757
24176
  day: "qdr:d",
23758
24177
  week: "qdr:w",
@@ -23845,6 +24264,7 @@ function isSerperAvailable() {
23845
24264
  return hasCredentialSource({ provider: "Serper", configuredValue: loadConfig29().serperApiKey, environmentValue: process.env.SERPER_API_KEY });
23846
24265
  }
23847
24266
  async function searchWithSerper(query, options = {}) {
24267
+ const apiUrl = resolveProviderApiUrl("serper", `${SERPER_API_BASE_URL}/search`, loadConfig29().serperBaseUrl);
23848
24268
  const apiKey = await requireApiKey11(options.signal);
23849
24269
  const numResults = normalizeSearchResultCount(options.numResults);
23850
24270
  const filters = parseDomainFilter7(options.domainFilter);
@@ -23852,12 +24272,12 @@ async function searchWithSerper(query, options = {}) {
23852
24272
  const activityId = activityMonitor.logStart({ type: "api", query });
23853
24273
  let response;
23854
24274
  try {
23855
- response = await fetch(SERPER_SEARCH_URL, {
24275
+ response = await fetchWithCredentialRedirects(apiUrl, {
23856
24276
  method: "POST",
23857
24277
  headers: { "X-API-KEY": apiKey, "Content-Type": "application/json", Accept: "application/json" },
23858
24278
  body: JSON.stringify({ q: buildQuery4(query, filters), num: requestCount, ...options.recencyFilter ? { tbs: RECENCY_TBS4[options.recencyFilter] } : {} }),
23859
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS26), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS26)
23860
- });
24279
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS25), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS25)
24280
+ }, ["X-API-KEY"]);
23861
24281
  } catch (err) {
23862
24282
  const message = errorMessage21(err);
23863
24283
  const redactedMessage = redactCredential(message, apiKey);
@@ -23913,7 +24333,7 @@ init_utils();
23913
24333
  import { existsSync as existsSync34, readFileSync as readFileSync34 } from "node:fs";
23914
24334
  var SERPLY_SEARCH_URL = "https://api.serply.io/v1/search";
23915
24335
  var CONFIG_PATH31 = getWebSearchConfigPath();
23916
- var SEARCH_TIMEOUT_MS27 = 6e4;
24336
+ var SEARCH_TIMEOUT_MS26 = 6e4;
23917
24337
  var RECENCY_TBS5 = {
23918
24338
  day: "qdr:d",
23919
24339
  week: "qdr:w",
@@ -24006,12 +24426,12 @@ async function searchWithSerply(query, options = {}) {
24006
24426
  const numResults = normalizeSearchResultCount(options.numResults);
24007
24427
  const filters = parseDomainFilter8(options.domainFilter);
24008
24428
  const requestCount = options.domainFilter?.length ? Math.min(20, numResults + 5) : numResults;
24009
- const url = new URL(SERPLY_SEARCH_URL);
24429
+ const url = new URL(resolveProviderApiUrl("serply", SERPLY_SEARCH_URL, loadConfig30().serplyBaseUrl));
24010
24430
  url.searchParams.set("q", buildQuery5(query, filters));
24011
24431
  url.searchParams.set("num", String(requestCount));
24012
24432
  if (options.recencyFilter) url.searchParams.set("tbs", RECENCY_TBS5[options.recencyFilter]);
24013
24433
  const activityId = activityMonitor.logStart({ type: "api", query });
24014
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS27);
24434
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS26);
24015
24435
  let response;
24016
24436
  let entries;
24017
24437
  try {
@@ -24038,7 +24458,7 @@ async function searchWithSerply(query, options = {}) {
24038
24458
  }
24039
24459
  const message = errorMessage22(err);
24040
24460
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
24041
- const outgoing = providerTimeout ? new Error(`Serply request timed out after ${Math.round(SEARCH_TIMEOUT_MS27 / 1e3)}s`) : (() => {
24461
+ const outgoing = providerTimeout ? new Error(`Serply request timed out after ${Math.round(SEARCH_TIMEOUT_MS26 / 1e3)}s`) : (() => {
24042
24462
  const redactedMessage = redactCredential(message, apiKey);
24043
24463
  if (redactedMessage === message && err instanceof Error) return err;
24044
24464
  const redactedError = new Error(redactedMessage);
@@ -24080,7 +24500,7 @@ init_utils();
24080
24500
  import { existsSync as existsSync35, readFileSync as readFileSync35 } from "node:fs";
24081
24501
  import { isIP as isIP2 } from "node:net";
24082
24502
  var MCP_URL = "https://agent-toolkit.app.baizhi.cloud/mcp";
24083
- var SEARCH_TIMEOUT_MS28 = 6e4;
24503
+ var SEARCH_TIMEOUT_MS27 = 6e4;
24084
24504
  var CONFIG_PATH32 = getWebSearchConfigPath();
24085
24505
  function credentialOptions() {
24086
24506
  let config = {};
@@ -24123,7 +24543,7 @@ function searchArguments(query, options) {
24123
24543
  }
24124
24544
  async function searchWithBaizhi(query, options = {}) {
24125
24545
  const args = searchArguments(query, options);
24126
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS28);
24546
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS27);
24127
24547
  const signal = options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
24128
24548
  if (signal.aborted) throw new Error("Aborted");
24129
24549
  const apiKey = await resolveCredential({ ...credentialOptions(), signal });
@@ -24151,8 +24571,8 @@ async function searchWithBaizhi(query, options = {}) {
24151
24571
  const client = new Client({ name: "pi-web-access-baizhi", version: "1.0.0" });
24152
24572
  const activityId = activityMonitor.logStart({ type: "api", query });
24153
24573
  try {
24154
- await client.connect(transport2, { signal, timeout: SEARCH_TIMEOUT_MS28 });
24155
- const result = await client.callTool({ name: "websearch_search", arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS28 });
24574
+ await client.connect(transport2, { signal, timeout: SEARCH_TIMEOUT_MS27 });
24575
+ const result = await client.callTool({ name: "websearch_search", arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS27 });
24156
24576
  if (result.isError) throw new Error("Baizhi search tool returned an error");
24157
24577
  const parts = [];
24158
24578
  if (result.structuredContent !== void 0) parts.push(JSON.stringify(result.structuredContent, null, 2));
@@ -24196,7 +24616,7 @@ var MCP_URLS = {
24196
24616
  china: "https://open.bigmodel.cn/api/mcp/web_search_prime/mcp"
24197
24617
  };
24198
24618
  var RECENCY = { day: "oneDay", week: "oneWeek", month: "oneMonth", year: "oneYear" };
24199
- var SEARCH_TIMEOUT_MS29 = 6e4;
24619
+ var SEARCH_TIMEOUT_MS28 = 6e4;
24200
24620
  var CONFIG_PATH33 = getWebSearchConfigPath();
24201
24621
  function loadConfig31() {
24202
24622
  if (!existsSync36(CONFIG_PATH33)) return {};
@@ -24235,8 +24655,8 @@ function searchArguments2(query, options) {
24235
24655
  ...domain ? { search_domain_filter: domain } : {}
24236
24656
  };
24237
24657
  }
24238
- function parseResults(text5, limit, domain) {
24239
- let value = JSON.parse(text5);
24658
+ function parseResults(text6, limit, domain) {
24659
+ let value = JSON.parse(text6);
24240
24660
  if (typeof value === "string") value = JSON.parse(value);
24241
24661
  if (!Array.isArray(value)) throw new Error("Z.ai returned invalid response: expected a result list");
24242
24662
  const results = [];
@@ -24267,7 +24687,7 @@ async function searchWithZai(query, options = {}) {
24267
24687
  const mcpUrl = endpointUrl(config);
24268
24688
  const args = searchArguments2(query, options);
24269
24689
  const limit = normalizeSearchResultCount(options.numResults);
24270
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS29);
24690
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS28);
24271
24691
  const signal = options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
24272
24692
  if (signal.aborted) throw new Error("Aborted");
24273
24693
  const apiKey = await resolveCredential({ ...credentialOptions2(config), signal });
@@ -24295,15 +24715,15 @@ async function searchWithZai(query, options = {}) {
24295
24715
  const client = new Client({ name: "pi-web-access-zai", version: "1.0.0" });
24296
24716
  const activityId = activityMonitor.logStart({ type: "api", query });
24297
24717
  try {
24298
- await client.connect(transport2, { signal, timeout: SEARCH_TIMEOUT_MS29 });
24299
- const { tools } = await client.listTools(void 0, { signal, timeout: SEARCH_TIMEOUT_MS29 });
24718
+ await client.connect(transport2, { signal, timeout: SEARCH_TIMEOUT_MS28 });
24719
+ const { tools } = await client.listTools(void 0, { signal, timeout: SEARCH_TIMEOUT_MS28 });
24300
24720
  const toolName = tools.find((tool) => tool.name === "web_search_prime" || tool.name === "webSearchPrime")?.name;
24301
24721
  if (!toolName) throw new Error("Z.ai returned invalid response: web search tool not listed");
24302
- const result = await client.callTool({ name: toolName, arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS29 });
24722
+ const result = await client.callTool({ name: toolName, arguments: args }, void 0, { signal, timeout: SEARCH_TIMEOUT_MS28 });
24303
24723
  if (result.isError) throw new Error("Z.ai search tool returned an error");
24304
- const text5 = (Array.isArray(result.content) ? result.content : []).find((item) => item.type === "text" && typeof item.text === "string");
24305
- if (!text5) throw new Error("Z.ai returned invalid response: no search text");
24306
- const results = parseResults(text5.text, limit, args.search_domain_filter);
24724
+ const text6 = (Array.isArray(result.content) ? result.content : []).find((item) => item.type === "text" && typeof item.text === "string");
24725
+ if (!text6) throw new Error("Z.ai returned invalid response: no search text");
24726
+ const results = parseResults(text6.text, limit, args.search_domain_filter);
24307
24727
  activityMonitor.logComplete(activityId, 200);
24308
24728
  return { answer: formatSearchResultsAsAnswer(results), results };
24309
24729
  } catch (err) {
@@ -24336,7 +24756,7 @@ init_utils();
24336
24756
  import { existsSync as existsSync37, readFileSync as readFileSync37 } from "node:fs";
24337
24757
  var VALYU_SEARCH_URL = "https://api.valyu.ai/v1/search";
24338
24758
  var CONFIG_PATH34 = getWebSearchConfigPath();
24339
- var SEARCH_TIMEOUT_MS30 = 6e4;
24759
+ var SEARCH_TIMEOUT_MS29 = 6e4;
24340
24760
  var MAX_SNIPPET_CHARS = 2500;
24341
24761
  var MAX_CONTENT_CHARS = 4e3;
24342
24762
  var cachedConfig31 = null;
@@ -24426,12 +24846,12 @@ async function searchWithValyu(query, options = {}) {
24426
24846
  const activityId = activityMonitor.logStart({ type: "api", query });
24427
24847
  let response;
24428
24848
  try {
24429
- response = await fetch(VALYU_SEARCH_URL, {
24849
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("valyu", VALYU_SEARCH_URL, loadConfig32().valyuBaseUrl), {
24430
24850
  method: "POST",
24431
24851
  headers: { "x-api-key": apiKey, "Content-Type": "application/json", Accept: "application/json" },
24432
24852
  body: JSON.stringify({ query, max_num_results: numResults, ...mapDomainFilter9(options.domainFilter), ...startDate ? { start_date: startDate } : {} }),
24433
- signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS30), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS30)
24434
- });
24853
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS29), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS29)
24854
+ }, ["x-api-key"]);
24435
24855
  } catch (err) {
24436
24856
  const message = errorMessage23(err);
24437
24857
  const redactedMessage = redactCredential(message, apiKey);
@@ -24490,7 +24910,7 @@ var KEENABLE_SEARCH_URL = "https://api.keenable.ai/v1/search";
24490
24910
  var KEENABLE_PUBLIC_SEARCH_URL = "https://api.keenable.ai/v1/search/public";
24491
24911
  var KEENABLE_CLIENT_TITLE = "pi-web-access";
24492
24912
  var CONFIG_PATH35 = getWebSearchConfigPath();
24493
- var SEARCH_TIMEOUT_MS31 = 3e4;
24913
+ var SEARCH_TIMEOUT_MS30 = 3e4;
24494
24914
  var MAX_REQUEST_RESULTS = 50;
24495
24915
  var MAX_SNIPPET_CHARS2 = 500;
24496
24916
  var RECENCY_DAYS = {
@@ -24592,11 +25012,11 @@ async function searchWithKeenable(query, options = {}) {
24592
25012
  ...apiKey ? { "X-API-Key": apiKey } : {}
24593
25013
  };
24594
25014
  const activityId = activityMonitor.logStart({ type: "api", query });
24595
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS31);
25015
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS30);
24596
25016
  let response;
24597
25017
  let entries;
24598
25018
  try {
24599
- response = await fetchWithCredentialRedirects(apiKey ? KEENABLE_SEARCH_URL : KEENABLE_PUBLIC_SEARCH_URL, {
25019
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("keenable", apiKey ? KEENABLE_SEARCH_URL : KEENABLE_PUBLIC_SEARCH_URL, loadConfig33().keenableBaseUrl), {
24600
25020
  method: "POST",
24601
25021
  headers,
24602
25022
  body: JSON.stringify(body),
@@ -24622,7 +25042,7 @@ async function searchWithKeenable(query, options = {}) {
24622
25042
  }
24623
25043
  const message = errorMessage24(err);
24624
25044
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
24625
- const outgoing = providerTimeout ? new Error(`Keenable request timed out after ${Math.round(SEARCH_TIMEOUT_MS31 / 1e3)}s`) : (() => {
25045
+ const outgoing = providerTimeout ? new Error(`Keenable request timed out after ${Math.round(SEARCH_TIMEOUT_MS30 / 1e3)}s`) : (() => {
24626
25046
  const redactedMessage = redactCredential(message, apiKey);
24627
25047
  if (redactedMessage === message && err instanceof Error) return err;
24628
25048
  const redactedError = new Error(redactedMessage);
@@ -24669,7 +25089,7 @@ init_utils();
24669
25089
  import { existsSync as existsSync39, readFileSync as readFileSync39 } from "node:fs";
24670
25090
  var CERAMIC_SEARCH_URL = "https://api.ceramic.ai/search";
24671
25091
  var CONFIG_PATH36 = getWebSearchConfigPath();
24672
- var SEARCH_TIMEOUT_MS32 = 3e4;
25092
+ var SEARCH_TIMEOUT_MS31 = 3e4;
24673
25093
  var MAX_REQUEST_RESULTS2 = 20;
24674
25094
  var REQUEST_DESCRIPTION_CHARS = 1e3;
24675
25095
  var MAX_SNIPPET_CHARS3 = 500;
@@ -24773,11 +25193,11 @@ async function searchWithCeramic(query, options = {}) {
24773
25193
  maxDescriptionLength: REQUEST_DESCRIPTION_CHARS
24774
25194
  };
24775
25195
  const activityId = activityMonitor.logStart({ type: "api", query });
24776
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS32);
25196
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS31);
24777
25197
  let response;
24778
25198
  let entries;
24779
25199
  try {
24780
- response = await fetchWithCredentialRedirects(CERAMIC_SEARCH_URL, {
25200
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("ceramic", CERAMIC_SEARCH_URL, loadConfig34().ceramicBaseUrl), {
24781
25201
  method: "POST",
24782
25202
  headers: {
24783
25203
  Accept: "application/json",
@@ -24806,7 +25226,7 @@ async function searchWithCeramic(query, options = {}) {
24806
25226
  }
24807
25227
  const message = errorMessage25(err);
24808
25228
  const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
24809
- const outgoing = providerTimeout ? new Error(`Ceramic request timed out after ${Math.round(SEARCH_TIMEOUT_MS32 / 1e3)}s`) : (() => {
25229
+ const outgoing = providerTimeout ? new Error(`Ceramic request timed out after ${Math.round(SEARCH_TIMEOUT_MS31 / 1e3)}s`) : (() => {
24810
25230
  const redactedMessage = redactCredential(message, apiKey);
24811
25231
  if (redactedMessage === message && err instanceof Error) return err;
24812
25232
  const redactedError = new Error(redactedMessage);
@@ -24842,183 +25262,157 @@ async function searchWithCeramic(query, options = {}) {
24842
25262
  return { answer: formatSearchResultsAsAnswer(results), results };
24843
25263
  }
24844
25264
 
24845
- // deepseek.ts
25265
+ // linkup.ts
24846
25266
  init_activity();
25267
+ init_credential_source();
24847
25268
  init_domain_filter_normalization();
24848
25269
  init_search_answer_formatting();
24849
25270
  init_search_result_count_normalization();
24850
- init_credential_source();
24851
25271
  init_utils();
24852
25272
  import { existsSync as existsSync40, readFileSync as readFileSync40 } from "node:fs";
24853
- var DEEPSEEK_SEARCH_URL = "https://api.deepseek.com/v1/tools/search";
25273
+ var LINKUP_SEARCH_URL = "https://api.linkup.so/v1/search";
24854
25274
  var CONFIG_PATH37 = getWebSearchConfigPath();
24855
- var SEARCH_TIMEOUT_MS33 = 3e4;
24856
- var MAX_QUERY_CHARS = 128;
24857
- var MAX_SNIPPET_CHARS4 = 800;
24858
- var RECENCY_DAYS2 = {
24859
- day: 1,
24860
- week: 7,
24861
- month: 30,
24862
- year: 365
24863
- };
24864
- var cachedConfig34 = null;
25275
+ var SEARCH_TIMEOUT_MS32 = 6e4;
25276
+ var DEPTHS = ["flash", "fast", "standard", "deep"];
25277
+ var cachedConfig34;
24865
25278
  function loadConfig35() {
24866
25279
  if (cachedConfig34) return cachedConfig34;
24867
- if (!existsSync40(CONFIG_PATH37)) {
24868
- cachedConfig34 = {};
24869
- return cachedConfig34;
24870
- }
24871
- const raw = readFileSync40(CONFIG_PATH37, "utf-8");
25280
+ if (!existsSync40(CONFIG_PATH37)) return cachedConfig34 = {};
24872
25281
  let parsed;
24873
25282
  try {
24874
- parsed = JSON.parse(raw);
24875
- } catch (err) {
24876
- const message = err instanceof Error ? err.message : String(err);
24877
- throw new Error(`Failed to parse ${CONFIG_PATH37}: ${message}`);
25283
+ parsed = JSON.parse(readFileSync40(CONFIG_PATH37, "utf-8"));
25284
+ } catch {
25285
+ throw new Error(`Failed to parse ${CONFIG_PATH37}: expected valid JSON`);
24878
25286
  }
24879
25287
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
24880
25288
  throw new Error(`Invalid config in ${CONFIG_PATH37}: expected a JSON object`);
24881
25289
  }
24882
- cachedConfig34 = parsed;
24883
- return cachedConfig34;
25290
+ return cachedConfig34 = parsed;
24884
25291
  }
24885
- async function requireApiKey15(signal) {
24886
- const apiKey = await resolveCredential({
24887
- provider: "DeepSeek",
24888
- configuredValue: loadConfig35().deepseekApiKey,
24889
- environmentValue: process.env.DEEPSEEK_API_KEY,
24890
- signal
24891
- });
24892
- if (!apiKey) {
24893
- throw new Error(
24894
- `DeepSeek API key not found. Either:
24895
- 1. Create ${CONFIG_PATH37} with { "deepseekApiKey": "your-key" }
24896
- 2. Set DEEPSEEK_API_KEY environment variable
24897
- Get a key at https://platform.deepseek.com/api_keys`
24898
- );
25292
+ function getDepth() {
25293
+ const value = loadConfig35().linkupDepth;
25294
+ if (value === void 0) return "fast";
25295
+ if (typeof value !== "string" || !DEPTHS.includes(value)) {
25296
+ throw new Error(`linkupDepth in ${CONFIG_PATH37} must be one of: ${DEPTHS.join(", ")}`);
24899
25297
  }
24900
- return apiKey;
25298
+ return value;
24901
25299
  }
24902
- function buildQuery8(query, options) {
25300
+ function domainFilters(values) {
24903
25301
  const include = [];
24904
25302
  const exclude = [];
24905
- for (const raw of options.domainFilter ?? []) {
25303
+ for (const raw of values ?? []) {
24906
25304
  const domain = normalizeDomain(raw);
24907
25305
  if (!domain) continue;
24908
25306
  const target = raw.trim().startsWith("-") ? exclude : include;
24909
25307
  if (!target.includes(domain)) target.push(domain);
24910
25308
  }
24911
- const parts = [query.trim()];
24912
- if (include.length > 0) parts.push(include.map((domain) => `site:${domain}`).join(" OR "));
24913
- for (const domain of exclude) parts.push(`-site:${domain}`);
24914
- if (options.recencyFilter) {
24915
- const after = new Date(Date.now() - RECENCY_DAYS2[options.recencyFilter] * 864e5).toISOString().slice(0, 10);
24916
- parts.push(`after:${after}`);
24917
- }
24918
- const built = parts.join(" ");
24919
- const length = [...built].length;
24920
- if (length > MAX_QUERY_CHARS) {
24921
- throw new Error(`DeepSeek invalid request: the query is ${length} characters with domain and date filters; DeepSeek accepts at most ${MAX_QUERY_CHARS}`);
25309
+ if (include.length > 100 || exclude.length > 100) {
25310
+ throw new Error("Linkup domainFilter must contain at most 100 included and 100 excluded domains");
24922
25311
  }
24923
- return built;
25312
+ return { include, exclude };
25313
+ }
25314
+ function recencyToDate(filter) {
25315
+ if (!filter) return void 0;
25316
+ const days = { day: 1, week: 7, month: 30, year: 365 }[filter];
25317
+ return new Date(Date.now() - days * 864e5).toISOString().slice(0, 10);
24924
25318
  }
24925
25319
  function text4(value) {
24926
25320
  return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
24927
25321
  }
24928
- function errorMessage26(err) {
24929
- return err instanceof Error ? err.message : String(err);
24930
- }
24931
25322
  function parseResponse11(value) {
24932
- const results = value && typeof value === "object" && !Array.isArray(value) ? value.results : void 0;
24933
- if (!Array.isArray(results)) throw new Error("DeepSeek returned invalid response: expected a results array");
24934
- return results;
24935
- }
24936
- function describeError2(body) {
24937
- try {
24938
- const error = JSON.parse(body).error;
24939
- const message = text4(error?.message);
24940
- if (message) return message;
24941
- } catch {
25323
+ if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.results)) {
25324
+ throw new Error("Linkup returned invalid response: expected results array");
24942
25325
  }
24943
- return body;
25326
+ return value.results;
24944
25327
  }
24945
- function isDeepSeekAvailable() {
24946
- return hasCredentialSource({ provider: "DeepSeek", configuredValue: loadConfig35().deepseekApiKey, environmentValue: process.env.DEEPSEEK_API_KEY });
25328
+ function isLinkupAvailable() {
25329
+ return hasCredentialSource({ provider: "Linkup", configuredValue: loadConfig35().linkupApiKey, environmentValue: process.env.LINKUP_API_KEY });
24947
25330
  }
24948
- async function searchWithDeepSeek(query, options = {}) {
24949
- const builtQuery = buildQuery8(query, options);
24950
- const apiKey = await requireApiKey15(options.signal);
25331
+ async function searchWithLinkup(query, options = {}) {
25332
+ const depth = getDepth();
25333
+ const filters = domainFilters(options.domainFilter);
25334
+ const apiKey = await resolveCredential({
25335
+ provider: "Linkup",
25336
+ configuredValue: loadConfig35().linkupApiKey,
25337
+ environmentValue: process.env.LINKUP_API_KEY,
25338
+ signal: options.signal
25339
+ });
25340
+ if (!apiKey) {
25341
+ throw new Error(`Linkup API key not found. Set linkupApiKey in ${CONFIG_PATH37} or LINKUP_API_KEY. Get a key at https://app.linkup.so`);
25342
+ }
24951
25343
  const numResults = normalizeSearchResultCount(options.numResults);
25344
+ const fromDate = recencyToDate(options.recencyFilter);
25345
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS32);
25346
+ const signal = options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
24952
25347
  const activityId = activityMonitor.logStart({ type: "api", query });
24953
- const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS33);
24954
- let response;
24955
25348
  let entries;
24956
25349
  try {
24957
- response = await fetchWithCredentialRedirects(DEEPSEEK_SEARCH_URL, {
25350
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("linkup", LINKUP_SEARCH_URL, loadConfig35().linkupBaseUrl), {
24958
25351
  method: "POST",
24959
- headers: {
24960
- Accept: "application/json",
24961
- "Content-Type": "application/json",
24962
- Authorization: `Bearer ${apiKey}`
24963
- },
24964
- body: JSON.stringify({ query: builtQuery, count: numResults }),
24965
- signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal
25352
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
25353
+ body: JSON.stringify({
25354
+ q: query,
25355
+ depth,
25356
+ outputType: "searchResults",
25357
+ maxResults: numResults,
25358
+ ...fromDate ? { fromDate } : {},
25359
+ ...filters.include.length ? { includeDomains: filters.include } : {},
25360
+ ...filters.exclude.length ? { excludeDomains: filters.exclude } : {}
25361
+ }),
25362
+ signal
24966
25363
  }, ["Authorization"]);
24967
25364
  if (!response.ok) {
24968
- const errorText = redactCredential(describeError2(await response.text()), apiKey).slice(0, 300);
24969
- throw new Error(`DeepSeek error ${response.status}: ${errorText}`);
25365
+ const body = redactCredential(await response.text(), apiKey).slice(0, 300);
25366
+ throw new Error(`Linkup error ${response.status}: ${body}`);
24970
25367
  }
24971
- let rawData;
25368
+ let data;
24972
25369
  try {
24973
- rawData = await response.json();
25370
+ data = await response.json();
24974
25371
  } catch (err) {
24975
- if (err instanceof Error && err.name === "TimeoutError") throw err;
24976
- throw new Error(`DeepSeek returned invalid JSON: ${errorMessage26(err)}`);
25372
+ if (!(err instanceof SyntaxError)) throw err;
25373
+ throw new Error("Linkup returned invalid JSON");
24977
25374
  }
24978
- entries = parseResponse11(rawData);
25375
+ entries = parseResponse11(data);
25376
+ activityMonitor.logComplete(activityId, response.status);
24979
25377
  } catch (err) {
24980
25378
  if (options.signal?.aborted) {
24981
25379
  activityMonitor.logComplete(activityId, 0);
24982
25380
  throw new Error("Aborted");
24983
25381
  }
24984
- const message = errorMessage26(err);
24985
- const providerTimeout = timeoutSignal.aborted || err instanceof Error && err.name === "TimeoutError";
24986
- const outgoing = providerTimeout ? new Error(`DeepSeek request timed out after ${Math.round(SEARCH_TIMEOUT_MS33 / 1e3)}s`) : (() => {
24987
- const redactedMessage = redactCredential(message, apiKey);
24988
- if (redactedMessage === message && err instanceof Error) return err;
24989
- const redactedError = new Error(redactedMessage);
24990
- if (err instanceof Error) redactedError.name = err.name;
24991
- return redactedError;
24992
- })();
24993
- activityMonitor.logError(activityId, redactCredential(errorMessage26(outgoing), apiKey));
25382
+ 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);
25383
+ activityMonitor.logError(activityId, message);
25384
+ const outgoing = err instanceof TypeError ? new TypeError(message) : new Error(message);
25385
+ if (err instanceof Error && !timeout.aborted) outgoing.name = err.name;
24994
25386
  throw outgoing;
24995
25387
  }
24996
- activityMonitor.logComplete(activityId, response.status);
24997
25388
  const results = [];
25389
+ const inlineContent = [];
24998
25390
  const seen = /* @__PURE__ */ new Set();
24999
25391
  for (const entry of entries) {
25000
- if (!entry || typeof entry !== "object") continue;
25001
- if (typeof entry.url !== "string" || !entry.url) continue;
25002
- let resultUrl;
25392
+ if (!entry || typeof entry !== "object" || entry.type !== "text" || typeof entry.url !== "string") continue;
25393
+ let url;
25003
25394
  try {
25004
- resultUrl = new URL(entry.url);
25395
+ url = new URL(entry.url);
25005
25396
  } catch {
25006
25397
  continue;
25007
25398
  }
25008
- if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
25009
- if (seen.has(resultUrl.href)) continue;
25010
- seen.add(resultUrl.href);
25011
- results.push({
25012
- title: text4(entry.title) || `Source ${results.length + 1}`,
25013
- url: resultUrl.href,
25014
- snippet: (text4(entry.summary) || text4(entry.snippet)).slice(0, MAX_SNIPPET_CHARS4)
25015
- });
25399
+ if (url.protocol !== "http:" && url.protocol !== "https:") continue;
25400
+ const matches = (domain) => url.hostname === domain || url.hostname.endsWith(`.${domain}`);
25401
+ if (filters.exclude.some(matches) || filters.include.length && !filters.include.some(matches)) continue;
25402
+ if (seen.has(url.href)) continue;
25403
+ seen.add(url.href);
25404
+ const title = text4(entry.name) || `Source ${results.length + 1}`;
25405
+ const content = typeof entry.content === "string" ? entry.content.trim().slice(0, 4e3) : "";
25406
+ results.push({ title, url: url.href, snippet: text4(content).slice(0, 500) });
25407
+ if (options.includeContent && content) inlineContent.push({ url: url.href, title, content, error: null });
25016
25408
  if (results.length >= numResults) break;
25017
25409
  }
25018
- if (entries.length > 0 && results.length === 0) throw new Error("DeepSeek returned invalid response: no result had an http(s) URL");
25019
- return { answer: formatSearchResultsAsAnswer(results), results };
25410
+ return { answer: formatSearchResultsAsAnswer(results), results, ...inlineContent.length ? { inlineContent } : {} };
25020
25411
  }
25021
25412
 
25413
+ // gemini-search.ts
25414
+ init_deepseek();
25415
+
25022
25416
  // kimi-search.ts
25023
25417
  init_activity();
25024
25418
  init_domain_filter_normalization();
@@ -25195,45 +25589,45 @@ init_activity();
25195
25589
  init_domain_filter_normalization();
25196
25590
  init_credential_source();
25197
25591
  init_utils();
25198
- import { existsSync as existsSync41, readFileSync as readFileSync41 } from "node:fs";
25592
+ import { existsSync as existsSync42, readFileSync as readFileSync42 } from "node:fs";
25199
25593
  var MISTRAL_CONVERSATIONS_URL = "https://api.mistral.ai/v1/conversations";
25200
- var CONFIG_PATH38 = getWebSearchConfigPath();
25594
+ var CONFIG_PATH39 = getWebSearchConfigPath();
25201
25595
  var SEARCH_TIMEOUT_MS35 = 6e4;
25202
25596
  var DEFAULT_SEARCH_MODEL = "mistral-small-latest";
25203
25597
  var DEFAULT_SEARCH_TOOL = "web_search";
25204
25598
  var MAX_RESULTS = 20;
25205
- var cachedConfig35 = null;
25206
- function loadConfig36() {
25207
- if (cachedConfig35) return cachedConfig35;
25208
- if (!existsSync41(CONFIG_PATH38)) {
25209
- cachedConfig35 = {};
25210
- return cachedConfig35;
25599
+ var cachedConfig36 = null;
25600
+ function loadConfig37() {
25601
+ if (cachedConfig36) return cachedConfig36;
25602
+ if (!existsSync42(CONFIG_PATH39)) {
25603
+ cachedConfig36 = {};
25604
+ return cachedConfig36;
25211
25605
  }
25212
- const raw = readFileSync41(CONFIG_PATH38, "utf-8");
25606
+ const raw = readFileSync42(CONFIG_PATH39, "utf-8");
25213
25607
  let parsed;
25214
25608
  try {
25215
25609
  parsed = JSON.parse(raw);
25216
25610
  } catch (err) {
25217
25611
  const message = err instanceof Error ? err.message : String(err);
25218
- throw new Error(`Failed to parse ${CONFIG_PATH38}: ${message}`);
25612
+ throw new Error(`Failed to parse ${CONFIG_PATH39}: ${message}`);
25219
25613
  }
25220
25614
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
25221
- throw new Error(`Invalid config in ${CONFIG_PATH38}: expected a JSON object`);
25615
+ throw new Error(`Invalid config in ${CONFIG_PATH39}: expected a JSON object`);
25222
25616
  }
25223
- cachedConfig35 = parsed;
25224
- return cachedConfig35;
25617
+ cachedConfig36 = parsed;
25618
+ return cachedConfig36;
25225
25619
  }
25226
25620
  function resolveSearchModel(value) {
25227
25621
  if (value === void 0) return DEFAULT_SEARCH_MODEL;
25228
25622
  if (typeof value !== "string" || value.trim().length === 0) {
25229
- throw new Error(`mistralSearchModel in ${CONFIG_PATH38} must be a non-empty string`);
25623
+ throw new Error(`mistralSearchModel in ${CONFIG_PATH39} must be a non-empty string`);
25230
25624
  }
25231
25625
  return value.trim();
25232
25626
  }
25233
25627
  function resolveSearchTool(value) {
25234
25628
  if (value === void 0) return DEFAULT_SEARCH_TOOL;
25235
25629
  if (value !== "web_search" && value !== "web_search_premium") {
25236
- throw new Error(`mistralSearchTool in ${CONFIG_PATH38} must be either web_search or web_search_premium`);
25630
+ throw new Error(`mistralSearchTool in ${CONFIG_PATH39} must be either web_search or web_search_premium`);
25237
25631
  }
25238
25632
  return value;
25239
25633
  }
@@ -25306,7 +25700,7 @@ function parseConversationResponse(value, options, numResults) {
25306
25700
  const answerParts = [];
25307
25701
  const results = [];
25308
25702
  const seenUrls = /* @__PURE__ */ new Set();
25309
- const domainFilters = parseDomainFilters(options.domainFilter);
25703
+ const domainFilters2 = parseDomainFilters(options.domainFilter);
25310
25704
  for (const output of outputs) {
25311
25705
  if (!output || typeof output !== "object" || Array.isArray(output)) continue;
25312
25706
  const entry = output;
@@ -25326,7 +25720,7 @@ function parseConversationResponse(value, options, numResults) {
25326
25720
  }
25327
25721
  if (part.type !== "tool_reference" || results.length >= numResults) continue;
25328
25722
  const url = normalizeResultUrl2(part.url);
25329
- if (!url || !passesDomainFilters11(url, domainFilters) || seenUrls.has(url)) continue;
25723
+ if (!url || !passesDomainFilters11(url, domainFilters2) || seenUrls.has(url)) continue;
25330
25724
  seenUrls.add(url);
25331
25725
  const title = typeof part.title === "string" && part.title.trim() ? part.title.trim() : url;
25332
25726
  const snippet = typeof part.description === "string" ? part.description : "";
@@ -25340,14 +25734,14 @@ function parseConversationResponse(value, options, numResults) {
25340
25734
  async function getApiKey26(signal) {
25341
25735
  const apiKey = await resolveCredential({
25342
25736
  provider: "Mistral",
25343
- configuredValue: loadConfig36().mistralApiKey,
25737
+ configuredValue: loadConfig37().mistralApiKey,
25344
25738
  environmentValue: process.env.MISTRAL_API_KEY,
25345
25739
  signal
25346
25740
  });
25347
25741
  if (!apiKey) {
25348
25742
  throw new Error(
25349
25743
  `Mistral API key not found. Either:
25350
- 1. Create ${CONFIG_PATH38} with { "mistralApiKey": "your-key" }
25744
+ 1. Create ${CONFIG_PATH39} with { "mistralApiKey": "your-key" }
25351
25745
  2. Set MISTRAL_API_KEY environment variable
25352
25746
  Get a key at https://console.mistral.ai/api-keys`
25353
25747
  );
@@ -25356,7 +25750,7 @@ Get a key at https://console.mistral.ai/api-keys`
25356
25750
  }
25357
25751
  function isMistralAvailable() {
25358
25752
  try {
25359
- const config = loadConfig36();
25753
+ const config = loadConfig37();
25360
25754
  resolveSearchModel(config.mistralSearchModel);
25361
25755
  resolveSearchTool(config.mistralSearchTool);
25362
25756
  return hasCredentialSource({
@@ -25369,7 +25763,7 @@ function isMistralAvailable() {
25369
25763
  }
25370
25764
  }
25371
25765
  async function searchWithMistral(query, options = {}) {
25372
- const config = loadConfig36();
25766
+ const config = loadConfig37();
25373
25767
  const model = resolveSearchModel(config.mistralSearchModel);
25374
25768
  const tool = resolveSearchTool(config.mistralSearchTool);
25375
25769
  const numResults = normalizeCount4(options.numResults);
@@ -25377,7 +25771,7 @@ async function searchWithMistral(query, options = {}) {
25377
25771
  const requestSignal15 = options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS35), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS35);
25378
25772
  const activityId = activityMonitor.logStart({ type: "api", query });
25379
25773
  try {
25380
- const response = await fetch(MISTRAL_CONVERSATIONS_URL, {
25774
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("mistralSearch", MISTRAL_CONVERSATIONS_URL, loadConfig37().mistralSearchBaseUrl), {
25381
25775
  method: "POST",
25382
25776
  headers: {
25383
25777
  Authorization: `Bearer ${apiKey}`,
@@ -25390,7 +25784,7 @@ async function searchWithMistral(query, options = {}) {
25390
25784
  tools: [{ type: tool }]
25391
25785
  }),
25392
25786
  signal: requestSignal15
25393
- });
25787
+ }, ["Authorization"]);
25394
25788
  if (!response.ok) {
25395
25789
  const errorText = redactCredential(await response.text(), apiKey);
25396
25790
  throw new Error(`Mistral API error ${response.status}: ${errorText.slice(0, 300)}`);
@@ -25421,7 +25815,7 @@ async function searchWithMistral(query, options = {}) {
25421
25815
 
25422
25816
  // gemini-search.ts
25423
25817
  init_utils();
25424
- 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"];
25818
+ var RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "serpdive", "kagi", "ollama", "anysearch", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "bocha", "xcrawl", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup"];
25425
25819
  var SEARCH_PROVIDERS = ["auto", "all", ...RESOLVED_SEARCH_PROVIDERS];
25426
25820
  var SearchProviderError = class extends Error {
25427
25821
  provider;
@@ -25437,18 +25831,18 @@ var SearchProviderError = class extends Error {
25437
25831
  this.causeError = cause;
25438
25832
  }
25439
25833
  };
25440
- var CONFIG_PATH39 = getWebSearchConfigPath();
25834
+ var CONFIG_PATH40 = getWebSearchConfigPath();
25441
25835
  var DEFAULT_SEARCH_MODEL2 = "gemini-3.6-flash";
25442
25836
  var ALL_SEARCH_PROVIDERS = ["searxng", "openai", "exa", "brave", "parallel", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "serpdive", "kagi", "ollama", "perplexity", "gemini", "bocha"];
25443
25837
  var VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported"];
25444
25838
  var cachedSearchConfig = null;
25445
25839
  function getSearchConfig() {
25446
25840
  if (cachedSearchConfig) return cachedSearchConfig;
25447
- if (!existsSync42(CONFIG_PATH39)) {
25841
+ if (!existsSync43(CONFIG_PATH40)) {
25448
25842
  cachedSearchConfig = { searchProvider: "auto", searchProviderConfigured: false };
25449
25843
  return cachedSearchConfig;
25450
25844
  }
25451
- const rawText = readFileSync42(CONFIG_PATH39, "utf-8");
25845
+ const rawText = readFileSync43(CONFIG_PATH40, "utf-8");
25452
25846
  let raw;
25453
25847
  try {
25454
25848
  const parsed = JSON.parse(rawText);
@@ -25458,25 +25852,25 @@ function getSearchConfig() {
25458
25852
  raw = parsed;
25459
25853
  } catch (err) {
25460
25854
  const message = err instanceof Error ? err.message : String(err);
25461
- throw new Error(`Failed to parse ${CONFIG_PATH39}: ${message}`);
25855
+ throw new Error(`Failed to parse ${CONFIG_PATH40}: ${message}`);
25462
25856
  }
25463
25857
  const searchModel = normalizeSearchModel(raw.searchModel);
25464
25858
  const webSearch = raw.webSearch;
25465
25859
  if (webSearch !== void 0 && (!webSearch || typeof webSearch !== "object" || Array.isArray(webSearch))) {
25466
- throw new Error(`webSearch in ${CONFIG_PATH39} must be an object`);
25860
+ throw new Error(`webSearch in ${CONFIG_PATH40} must be an object`);
25467
25861
  }
25468
- const allowedProviders = webSearch && Object.hasOwn(webSearch, "allowedProviders") ? normalizeResolvedProviderList(webSearch.allowedProviders, `webSearch.allowedProviders in ${CONFIG_PATH39}`) : void 0;
25862
+ const allowedProviders = webSearch && Object.hasOwn(webSearch, "allowedProviders") ? normalizeResolvedProviderList(webSearch.allowedProviders, `webSearch.allowedProviders in ${CONFIG_PATH40}`) : void 0;
25469
25863
  const searchProviderConfigured = Object.hasOwn(raw, "searchProvider") || Object.hasOwn(raw, "provider");
25470
- const searchProvider = normalizeSearchProviderSelection(raw.searchProvider ?? raw.provider, `provider in ${CONFIG_PATH39}`);
25864
+ const searchProvider = normalizeSearchProviderSelection(raw.searchProvider ?? raw.provider, `provider in ${CONFIG_PATH40}`);
25471
25865
  const searchRouting = Object.hasOwn(raw, "searchRouting") ? normalizeSearchRouting(raw.searchRouting) : void 0;
25472
25866
  if (allowedProviders) {
25473
25867
  if (Object.hasOwn(raw, "searchProvider")) {
25474
- assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.searchProvider), `searchProvider in ${CONFIG_PATH39}`, allowedProviders);
25868
+ assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.searchProvider), `searchProvider in ${CONFIG_PATH40}`, allowedProviders);
25475
25869
  }
25476
25870
  if (Object.hasOwn(raw, "provider")) {
25477
- assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.provider), `provider in ${CONFIG_PATH39}`, allowedProviders);
25871
+ assertSearchProviderSelectionAllowed(normalizeSearchProviderSelection(raw.provider), `provider in ${CONFIG_PATH40}`, allowedProviders);
25478
25872
  }
25479
- if (searchRouting) assertSearchProviderSelectionAllowed(searchRouting.providers, `searchRouting.providers in ${CONFIG_PATH39}`, allowedProviders);
25873
+ if (searchRouting) assertSearchProviderSelectionAllowed(searchRouting.providers, `searchRouting.providers in ${CONFIG_PATH40}`, allowedProviders);
25480
25874
  }
25481
25875
  cachedSearchConfig = {
25482
25876
  searchProvider,
@@ -25489,21 +25883,21 @@ function getSearchConfig() {
25489
25883
  }
25490
25884
  function normalizeSearchRouting(value) {
25491
25885
  if (!value || typeof value !== "object" || Array.isArray(value)) {
25492
- throw new Error(`searchRouting in ${CONFIG_PATH39} must be an object`);
25886
+ throw new Error(`searchRouting in ${CONFIG_PATH40} must be an object`);
25493
25887
  }
25494
25888
  const raw = value;
25495
- const providers = normalizeResolvedProviderList(raw.providers, `searchRouting.providers in ${CONFIG_PATH39}`);
25889
+ const providers = normalizeResolvedProviderList(raw.providers, `searchRouting.providers in ${CONFIG_PATH40}`);
25496
25890
  const useCurrentModel = raw.useCurrentModel;
25497
25891
  if (useCurrentModel !== void 0 && typeof useCurrentModel !== "boolean") {
25498
- throw new Error(`searchRouting.useCurrentModel in ${CONFIG_PATH39} must be a boolean`);
25892
+ throw new Error(`searchRouting.useCurrentModel in ${CONFIG_PATH40} must be a boolean`);
25499
25893
  }
25500
25894
  if (!Array.isArray(raw.fallbackOn) || raw.fallbackOn.length === 0) {
25501
- throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH39} must be a non-empty array`);
25895
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH40} must be a non-empty array`);
25502
25896
  }
25503
25897
  const fallbackOn = [];
25504
25898
  for (const kind of raw.fallbackOn) {
25505
25899
  if (typeof kind !== "string" || !VALID_ROUTING_KINDS.includes(kind)) {
25506
- throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH39} may only contain transient, quota, network, invalid-response, or unsupported`);
25900
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH40} may only contain transient, quota, network, invalid-response, or unsupported`);
25507
25901
  }
25508
25902
  if (!fallbackOn.includes(kind)) {
25509
25903
  fallbackOn.push(kind);
@@ -25606,7 +26000,7 @@ function classifyProviderError(provider, err) {
25606
26000
  const lower = message.toLowerCase();
25607
26001
  const status = providerErrorStatus(message);
25608
26002
  const openAIStreamError = provider === "openai" && lower.includes("openai api stream error");
25609
- const text5 = openAIStreamError ? lower.replace(/_/g, " ") : lower;
26003
+ const text6 = openAIStreamError ? lower.replace(/_/g, " ") : lower;
25610
26004
  let kind = "unknown";
25611
26005
  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);
25612
26006
  if (err instanceof CredentialResolutionError || /(?:api )?key (?:not found|missing)|credential resolution/.test(lower)) {
@@ -25627,19 +26021,19 @@ function classifyProviderError(provider, err) {
25627
26021
  kind = "quota";
25628
26022
  } else if (status !== void 0 && (status === 408 || status === 425 || status >= 500)) {
25629
26023
  kind = "transient";
25630
- } else if (/rate limit|quota|too many requests/.test(text5) || openAIStreamError && /usage limit/.test(text5)) {
26024
+ } else if (/rate limit|quota|too many requests/.test(text6) || openAIStreamError && /usage limit/.test(text6)) {
25631
26025
  kind = "quota";
25632
- } else if (/unauthorized|forbidden|permission denied/.test(text5) || openAIStreamError && /authentication error|permission error|invalid api key/.test(text5)) {
26026
+ } else if (/unauthorized|forbidden|permission denied/.test(text6) || openAIStreamError && /authentication error|permission error|invalid api key/.test(text6)) {
25633
26027
  kind = "auth";
25634
- } else if (/bad request|invalid request/.test(text5)) {
26028
+ } else if (/bad request|invalid request/.test(text6)) {
25635
26029
  kind = "invalid-request";
25636
- } else if (/invalid json|no parseable response|no parseable results|invalid response|returned empty response|no web_search_call/.test(text5)) {
26030
+ } else if (/invalid json|no parseable response|no parseable results|invalid response|returned empty response|no web_search_call/.test(text6)) {
25637
26031
  kind = "invalid-response";
25638
- } else if (/temporar|service unavailable|server error/.test(text5) || openAIStreamError && /internal error|\bapi error|overloaded/.test(text5)) {
26032
+ } else if (/temporar|service unavailable|server error/.test(text6) || openAIStreamError && /internal error|\bapi error|overloaded/.test(text6)) {
25639
26033
  kind = "transient";
25640
- } else if (err instanceof TypeError || /fetch failed|network|econnreset|econnrefused|enotfound|etimedout|timed out|socket/.test(text5)) {
26034
+ } else if (err instanceof TypeError || /fetch failed|network|econnreset|econnrefused|enotfound|etimedout|timed out|socket/.test(text6)) {
25641
26035
  kind = "network";
25642
- } else if (/invalid or missing|invalid config|failed to parse|must be an? |configuration/.test(text5)) {
26036
+ } else if (/invalid or missing|invalid config|failed to parse|must be an? |configuration/.test(text6)) {
25643
26037
  kind = "config";
25644
26038
  } else if (openAIStreamError) {
25645
26039
  kind = "invalid-response";
@@ -25679,6 +26073,7 @@ async function searchWithResolvedProvider(provider, query, options, useCurrentMo
25679
26073
  if (provider === "valyu") return { ...await searchWithValyu(query, options), provider };
25680
26074
  if (provider === "keenable") return { ...await searchWithKeenable(query, options), provider };
25681
26075
  if (provider === "ceramic") return { ...await searchWithCeramic(query, options), provider };
26076
+ if (provider === "linkup") return { ...await searchWithLinkup(query, options), provider };
25682
26077
  if (provider === "deepseek") return { ...await searchWithDeepSeek(query, options), provider };
25683
26078
  if (provider === "xcrawl") return { ...await searchWithXCrawl(query, options), provider };
25684
26079
  if (provider === "perplexity") return { ...await searchWithPerplexity(query, options), provider };
@@ -25691,7 +26086,7 @@ async function searchWithResolvedProvider(provider, query, options, useCurrentMo
25691
26086
  if (result2) return { ...result2, provider };
25692
26087
  throw new Error(
25693
26088
  `Gemini search unavailable. Either:
25694
- 1. Configure geminiApiKey in ${CONFIG_PATH39} or set GEMINI_API_KEY
26089
+ 1. Configure geminiApiKey in ${CONFIG_PATH40} or set GEMINI_API_KEY
25695
26090
  2. Set GOOGLE_GEMINI_BASE_URL + CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing
25696
26091
  3. Set geminiAuth to "adc" in web-search.json with a Google Cloud ADC + project/location
25697
26092
  4. Sign into gemini.google.com in a supported Chromium-based browser`
@@ -25733,6 +26128,7 @@ async function isResolvedProviderAvailable(provider, options, useCurrentModel =
25733
26128
  if (provider === "valyu") return isValyuAvailable();
25734
26129
  if (provider === "keenable") return isKeenableAvailable();
25735
26130
  if (provider === "ceramic") return isCeramicAvailable();
26131
+ if (provider === "linkup") return isLinkupAvailable();
25736
26132
  if (provider === "deepseek") return isDeepSeekAvailable();
25737
26133
  if (provider === "xcrawl") return isXcrawlAvailable();
25738
26134
  if (provider === "perplexity") return isPerplexityAvailable();
@@ -25780,6 +26176,7 @@ function providerLabel(provider) {
25780
26176
  if (provider === "valyu") return "Valyu";
25781
26177
  if (provider === "keenable") return "Keenable";
25782
26178
  if (provider === "ceramic") return "Ceramic";
26179
+ if (provider === "linkup") return "Linkup";
25783
26180
  if (provider === "deepseek") return "DeepSeek";
25784
26181
  return provider.charAt(0).toUpperCase() + provider.slice(1);
25785
26182
  }
@@ -25789,14 +26186,14 @@ async function searchWithAllProvider(provider, query, options) {
25789
26186
  if (result) return { ...result, provider };
25790
26187
  throw new Error("Gemini API search returned no results.");
25791
26188
  }
25792
- async function searchWithProviders(query, options, selectedProviders) {
26189
+ async function searchWithProviders(query, options, selectedProviders, routing) {
25793
26190
  const allowed = getAllowedSearchProviders();
25794
26191
  const providers = selectedProviders ?? (await Promise.all(ALL_SEARCH_PROVIDERS.filter((provider) => allowed.includes(provider)).map(async (provider) => ({
25795
26192
  provider,
25796
26193
  available: provider === "gemini" ? isGeminiApiAvailable() : await isResolvedProviderAvailable(provider, options)
25797
26194
  })))).filter((entry) => entry.available).map((entry) => entry.provider);
25798
26195
  if (providers.length === 0) {
25799
- 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.');
26196
+ throw new Error('No configured search provider available for provider "all". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, XCrawl, Keenable, Ceramic, DeepSeek, and Linkup are excluded.');
25800
26197
  }
25801
26198
  const settled = await Promise.allSettled(
25802
26199
  providers.map((provider) => selectedProviders ? searchWithResolvedProvider(provider, query, options) : searchWithAllProvider(provider, query, options))
@@ -25814,8 +26211,20 @@ async function searchWithProviders(query, options, selectedProviders) {
25814
26211
  }
25815
26212
  if (successes.length === 0) {
25816
26213
  const label = selectedProviders ? "Selected-provider" : "All-provider";
25817
- throw new Error(`${label} search failed:
25818
- - ${failures.map(({ provider, error }) => `${providerLabel(provider)}: ${error}`).join("\n - ")}`);
26214
+ const failureMessage = `${label} search failed:
26215
+ - ${failures.map(({ provider, error }) => `${providerLabel(provider)}: ${error}`).join("\n - ")}`;
26216
+ if (!routing || !settled.every((outcome, index) => outcome.status === "rejected" && routing.fallbackOn.includes(classifyProviderError(providers[index], outcome.reason).kind))) {
26217
+ throw new Error(failureMessage);
26218
+ }
26219
+ const untried = routing.providers.filter((provider) => !providers.includes(provider));
26220
+ try {
26221
+ if (untried.length === 0) throw new Error("Configured search routing has no untried providers");
26222
+ return await searchWithConfiguredRouting(query, options, { ...routing, providers: untried });
26223
+ } catch (err) {
26224
+ if (isAbortError2(err)) throw err;
26225
+ throw new Error(`${failureMessage}
26226
+ ${errorMessage28(err)}`);
26227
+ }
25819
26228
  }
25820
26229
  const results = [];
25821
26230
  const seenResultUrls = /* @__PURE__ */ new Set();
@@ -25880,7 +26289,9 @@ async function search(query, options = {}) {
25880
26289
  const provider = options.provider === void 0 || options.provider === "auto" ? config.searchProvider : options.provider;
25881
26290
  assertSearchProviderSelectionAllowed(provider, "Requested provider");
25882
26291
  if (Array.isArray(provider)) {
25883
- return searchWithProviders(query, options, normalizeResolvedProviderList(provider, "provider"));
26292
+ const fromConfig = options.providerFromConfig === true || options.provider === void 0 || options.provider === "auto";
26293
+ const routing = fromConfig ? config.searchRouting : void 0;
26294
+ return searchWithProviders(query, options, normalizeResolvedProviderList(provider, "provider"), routing);
25884
26295
  }
25885
26296
  if (provider === "all") return searchWithProviders(query, options);
25886
26297
  if (provider !== "auto") return searchWithResolvedProvider(provider, query, options);
@@ -25947,11 +26358,11 @@ async function search(query, options = {}) {
25947
26358
  throw new Error(
25948
26359
  `No search provider available. Either:
25949
26360
  1. Use /login to sign in with a Codex subscription for OpenAI web search
25950
- 2. Set openaiApiKey, braveApiKey, parallelApiKey, tinyfishApiKey, search1apiApiKey, searchinfinityApiKey, queritApiKey, tavilyApiKey, firecrawlBaseUrl, jinaApiKey, serpdiveApiKey, kagiApiKey, ollamaApiKey, searxngBaseUrl, perplexityApiKey, exaApiKey, geminiApiKey, bochaApiKey, or cloudflareApiKey in ${CONFIG_PATH39}
26361
+ 2. Set openaiApiKey, braveApiKey, parallelApiKey, tinyfishApiKey, search1apiApiKey, searchinfinityApiKey, queritApiKey, tavilyApiKey, firecrawlBaseUrl, jinaApiKey, serpdiveApiKey, kagiApiKey, ollamaApiKey, searxngBaseUrl, perplexityApiKey, exaApiKey, geminiApiKey, bochaApiKey, or cloudflareApiKey in ${CONFIG_PATH40}
25951
26362
  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
25952
26363
  4. Set GOOGLE_GEMINI_BASE_URL with CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing
25953
26364
  5. Sign into gemini.google.com in a supported Chromium-based browser
25954
- 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`
26365
+ 6. Explicitly select provider: "anysearch" for anonymous AnySearch, "xcrawl" for XCrawl, "xai" for Grok, "mistral" for Mistral Conversations web search, "brightdata" with brightdataSerpZone for paid Bright Data SERP, "serpbase", "serpapi", "serper", or "serply" for Google SERP, "you" for You.com, "zai" for Z.ai GLM Coding Plan search, "valyu" for research search, "keenable" for keyless Keenable search, "ceramic" for Ceramic search, "deepseek" for DeepSeek search, or "linkup" for Linkup search`
25955
26366
  );
25956
26367
  }
25957
26368
  async function searchWithGeminiApi(query, options = {}) {
@@ -26001,13 +26412,13 @@ async function searchWithGeminiWeb(query, options = {}) {
26001
26412
  const prompt = buildSearchPrompt2(query, options);
26002
26413
  const activityId = activityMonitor.logStart({ type: "api", query });
26003
26414
  try {
26004
- const text5 = await queryWithCookies(prompt, cookies, {
26415
+ const text6 = await queryWithCookies(prompt, cookies, {
26005
26416
  signal: options.signal,
26006
26417
  timeoutMs: 12e4
26007
26418
  });
26008
26419
  activityMonitor.logComplete(activityId, 200);
26009
- const results = extractSourceUrls(text5);
26010
- return { answer: text5, results };
26420
+ const results = extractSourceUrls(text6);
26421
+ return { answer: text6, results };
26011
26422
  } catch (err) {
26012
26423
  const message = err instanceof Error ? err.message : String(err);
26013
26424
  if (message.toLowerCase().includes("abort")) {
@@ -26188,8 +26599,8 @@ var TOOL_RUNNERS = {
26188
26599
  get_search_content: (core2, args, signal) => core2.getSearchContent(args, signal),
26189
26600
  source_check: (core2, args, signal) => core2.sourceCheck(args, signal)
26190
26601
  };
26191
- function errorResult(text5) {
26192
- return { content: [{ type: "text", text: text5 }], isError: true };
26602
+ function errorResult(text6) {
26603
+ return { content: [{ type: "text", text: text6 }], isError: true };
26193
26604
  }
26194
26605
  function toCallToolResult(result) {
26195
26606
  return { content: result.content, ...result.isError && { isError: true } };
@@ -26224,7 +26635,7 @@ function createMcpServer(core2, info, enabledTools) {
26224
26635
  }
26225
26636
 
26226
26637
  // web-tool-core.ts
26227
- import { existsSync as existsSync55, readFileSync as readFileSync56 } from "node:fs";
26638
+ import { existsSync as existsSync56, readFileSync as readFileSync57 } from "node:fs";
26228
26639
  import pLimit2 from "p-limit";
26229
26640
 
26230
26641
  // fetch-params.ts
@@ -26335,8 +26746,8 @@ function editDistanceWithin(left, right, maximum) {
26335
26746
  }
26336
26747
  return previous[right.length] <= maximum;
26337
26748
  }
26338
- function literalMatches(text5, query, caseInsensitive) {
26339
- const haystack = caseInsensitive ? text5.toLocaleLowerCase() : text5;
26749
+ function literalMatches(text6, query, caseInsensitive) {
26750
+ const haystack = caseInsensitive ? text6.toLocaleLowerCase() : text6;
26340
26751
  const needle = caseInsensitive ? query.toLocaleLowerCase() : query;
26341
26752
  const matches = [];
26342
26753
  for (let start = haystack.indexOf(needle); start >= 0; start = haystack.indexOf(needle, start + Math.max(needle.length, 1))) {
@@ -26344,12 +26755,12 @@ function literalMatches(text5, query, caseInsensitive) {
26344
26755
  }
26345
26756
  return matches;
26346
26757
  }
26347
- function fuzzyMatches(text5, query) {
26758
+ function fuzzyMatches(text6, query) {
26348
26759
  const queryTokens = normalize2(query).match(/[\p{L}\p{N}]+/gu) ?? [];
26349
26760
  if (queryTokens.length === 0) return [];
26350
26761
  const matches = [];
26351
26762
  const paragraphs = /[^\n]+(?:\n(?!\n)[^\n]+)*/g;
26352
- for (const paragraph of text5.matchAll(paragraphs)) {
26763
+ for (const paragraph of text6.matchAll(paragraphs)) {
26353
26764
  const paragraphText = paragraph[0];
26354
26765
  if (paragraphText.trim().length === 0 || paragraph.index === void 0) continue;
26355
26766
  const tokens = [...paragraphText.matchAll(/[\p{L}\p{N}]+/gu)];
@@ -26408,10 +26819,10 @@ function upperBound(values, target) {
26408
26819
  }
26409
26820
  return low;
26410
26821
  }
26411
- function findContent(text5, queries, mode) {
26822
+ function findContent(text6, queries, mode) {
26412
26823
  const normalizedQueries = [...new Set(queries.map((query) => query.trim()).filter(Boolean))];
26413
26824
  const occurrences = normalizedQueries.map((query) => {
26414
- const matches2 = mode === "fuzzy" ? fuzzyMatches(text5, query) : literalMatches(text5, query, mode === "case-insensitive");
26825
+ const matches2 = mode === "fuzzy" ? fuzzyMatches(text6, query) : literalMatches(text6, query, mode === "case-insensitive");
26415
26826
  return { query, matches: matches2, starts: matches2.map((match) => match.start), ends: matches2.map((match) => match.end) };
26416
26827
  });
26417
26828
  const matches = occurrences.flatMap((result) => result.matches);
@@ -26423,7 +26834,7 @@ function findContent(text5, queries, mode) {
26423
26834
  id: `Q${index + 1}`,
26424
26835
  order: index
26425
26836
  }));
26426
- const whitespaceRuns = [...text5.matchAll(/\s+/g)].map((run) => ({ start: run.index, end: run.index + run[0].length }));
26837
+ const whitespaceRuns = [...text6.matchAll(/\s+/g)].map((run) => ({ start: run.index, end: run.index + run[0].length }));
26427
26838
  const whitespaceStarts = whitespaceRuns.map((run) => run.start);
26428
26839
  const whitespaceEnds = whitespaceRuns.map((run) => run.end);
26429
26840
  const whitespaceSavings = [0];
@@ -26456,7 +26867,7 @@ function findContent(text5, queries, mode) {
26456
26867
  const counts = rangeCounts(range);
26457
26868
  if (counts.length === 0) continue;
26458
26869
  const labelsLength = counts.reduce((total, result) => total + (overflow ? result.id.length : result.query.length + 2) + 2 + String(result.count).length, 2 * (counts.length - 1));
26459
- const snippetLength = normalizedLength(range.start, range.end) + (range.start > 0 ? 1 : 0) + (range.end < text5.length ? 1 : 0);
26870
+ const snippetLength = normalizedLength(range.start, range.end) + (range.start > 0 ? 1 : 0) + (range.end < text6.length ? 1 : 0);
26460
26871
  length += 2 + String(index + 1).length + 2 + labelsLength + 1 + snippetLength;
26461
26872
  returnedMatches += counts.reduce((total, result) => total + result.count, 0);
26462
26873
  }
@@ -26473,8 +26884,8 @@ function findContent(text5, queries, mode) {
26473
26884
  const contained = rangeCounts(range);
26474
26885
  if (contained.length === 0) continue;
26475
26886
  const prefix = range.start > 0 ? "\u2026" : "";
26476
- const suffix = range.end < text5.length ? "\u2026" : "";
26477
- const snippet = `${prefix}${text5.slice(range.start, range.end).replace(/[\uD800-\uDFFF]/gu, "\uFFFD").replace(/\s+/g, " ").trim()}${suffix}`;
26887
+ const suffix = range.end < text6.length ? "\u2026" : "";
26888
+ const snippet = `${prefix}${text6.slice(range.start, range.end).replace(/[\uD800-\uDFFF]/gu, "\uFFFD").replace(/\s+/g, " ").trim()}${suffix}`;
26478
26889
  const counts = contained.map((result) => `${overflow ? result.id : `"${result.query}"`} \xD7${result.count}`).join(", ");
26479
26890
  sections.push(`${index + 1}. ${counts}
26480
26891
  ${snippet}`);
@@ -26485,18 +26896,18 @@ ${snippet}`);
26485
26896
  if (returnedMatches < matches.length) sections.push(`Showing ${returnedMatches} of ${matches.length} matches.`);
26486
26897
  return { text: sections.join("\n\n"), matchCount: matches.length, returnedMatches, queryResults };
26487
26898
  }
26488
- const fullRanges = contextRanges(text5.length, matches);
26899
+ const fullRanges = contextRanges(text6.length, matches);
26489
26900
  const full = measure(fullRanges);
26490
26901
  if (full.returnedMatches === matches.length && full.length <= MAX_OUTPUT_CHARS) return formatRanges(fullRanges);
26491
26902
  let ranges = [];
26492
26903
  let omitted = matchingQueries.map((result) => result.id);
26493
26904
  if (measure(ranges, true, omitted).length > MAX_OUTPUT_CHARS) {
26494
- const text6 = `${heading}
26905
+ const text7 = `${heading}
26495
26906
 
26496
26907
  Unable to format bounded excerpts: query metadata exceeds ${MAX_OUTPUT_CHARS} characters.
26497
26908
 
26498
26909
  Showing 0 of ${matches.length} matches.`;
26499
- return { text: text6, matchCount: matches.length, returnedMatches: 0, queryResults };
26910
+ return { text: text7, matchCount: matches.length, returnedMatches: 0, queryResults };
26500
26911
  }
26501
26912
  const witnesses = [];
26502
26913
  for (const { id, matches: queryMatches } of matchingQueries) {
@@ -26522,7 +26933,7 @@ Showing 0 of ${matches.length} matches.`;
26522
26933
  for (const witness of witnesses) {
26523
26934
  const proposed = mergeRanges([...ranges, {
26524
26935
  start: Math.max(0, witness.start - CONTEXT_CHARS),
26525
- end: Math.min(text5.length, witness.end + CONTEXT_CHARS)
26936
+ end: Math.min(text6.length, witness.end + CONTEXT_CHARS)
26526
26937
  }]);
26527
26938
  if (measure(proposed, true, omitted).length <= MAX_OUTPUT_CHARS) ranges = proposed;
26528
26939
  }
@@ -26535,7 +26946,7 @@ Showing 0 of ${matches.length} matches.`;
26535
26946
  init_utils();
26536
26947
 
26537
26948
  // storage.ts
26538
- import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync as readFileSync44, readdirSync as readdirSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
26949
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync as readFileSync45, readdirSync as readdirSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
26539
26950
  init_utils();
26540
26951
  import { join as join4 } from "node:path";
26541
26952
  var CACHE_TTL_MS = 60 * 60 * 1e3;
@@ -26696,7 +27107,7 @@ function readCachedFetchData(data) {
26696
27107
  const opened = openRegularFile(path);
26697
27108
  fd = opened.fd;
26698
27109
  enforceMode(fd, 384);
26699
- const parsed = JSON.parse(readFileSync44(fd, "utf8"));
27110
+ const parsed = JSON.parse(readFileSync45(fd, "utf8"));
26700
27111
  if (!isValidStoredData(parsed) || parsed.type !== "fetch" || parsed.id !== data.id || !isInlineFetchData(parsed)) {
26701
27112
  return unavailableFetchData(data, "Cached fetched content is invalid");
26702
27113
  }
@@ -26788,8 +27199,8 @@ function classifySource(url) {
26788
27199
  if (BLOG_HOSTS.test(host) || BLOG_PATHS.test(path)) return "blog";
26789
27200
  return "unknown";
26790
27201
  }
26791
- function hashContent(text5) {
26792
- return `sha256:${createHash("sha256").update(text5, "utf8").digest("hex")}`;
27202
+ function hashContent(text6) {
27203
+ return `sha256:${createHash("sha256").update(text6, "utf8").digest("hex")}`;
26793
27204
  }
26794
27205
  function tokenize(value) {
26795
27206
  return [...new Set(value.toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length > 3))];
@@ -26799,10 +27210,10 @@ function extractRelevantSpans(content, hint) {
26799
27210
  const sentencePattern = /[^.!?]+(?:[.!?]+(?=\s|$)|$)/g;
26800
27211
  for (const match of content.matchAll(sentencePattern)) {
26801
27212
  const raw = match[0];
26802
- const text5 = raw.trim();
26803
- if (text5.length > 0 && text5.length <= 400) {
26804
- const start = (match.index ?? 0) + raw.indexOf(text5);
26805
- sentences.push({ text: text5, start, end: start + text5.length });
27213
+ const text6 = raw.trim();
27214
+ if (text6.length > 0 && text6.length <= 400) {
27215
+ const start = (match.index ?? 0) + raw.indexOf(text6);
27216
+ sentences.push({ text: text6, start, end: start + text6.length });
26806
27217
  }
26807
27218
  }
26808
27219
  const terms = tokenize(hint);
@@ -26925,9 +27336,9 @@ function parseConfigRoot(raw) {
26925
27336
  }
26926
27337
  return parsed;
26927
27338
  }
26928
- function loadConfig41() {
26929
- if (!existsSync55(WEB_SEARCH_CONFIG_PATH4)) return {};
26930
- return parseConfigRoot(readFileSync56(WEB_SEARCH_CONFIG_PATH4, "utf-8"));
27339
+ function loadConfig42() {
27340
+ if (!existsSync56(WEB_SEARCH_CONFIG_PATH4)) return {};
27341
+ return parseConfigRoot(readFileSync57(WEB_SEARCH_CONFIG_PATH4, "utf-8"));
26931
27342
  }
26932
27343
  var DEFAULT_TOOL_NAMES = {
26933
27344
  webSearch: "web_search",
@@ -26978,7 +27389,7 @@ function resolveRequestedProvider(requested) {
26978
27389
  assertSearchProviderSelectionAllowed(normalizedRequested, "Requested provider");
26979
27390
  return normalizedRequested;
26980
27391
  }
26981
- const config = loadConfig41();
27392
+ const config = loadConfig42();
26982
27393
  const provider = normalizeProviderInput(config.searchProvider ?? config.provider, `provider in ${WEB_SEARCH_CONFIG_PATH4}`) ?? "auto";
26983
27394
  assertSearchProviderSelectionAllowed(provider, `configured provider in ${WEB_SEARCH_CONFIG_PATH4}`);
26984
27395
  return provider;
@@ -27041,7 +27452,7 @@ function isAbortError6(err) {
27041
27452
  var DEFAULT_MAX_INLINE_CONTENT_CHARS = 3e4;
27042
27453
  var MIN_INLINE_CONTENT_CHARS = 1e3;
27043
27454
  var MAX_INLINE_CONTENT_CHARS = 2e5;
27044
- function getMaxInlineContentChars(config = loadConfig41()) {
27455
+ function getMaxInlineContentChars(config = loadConfig42()) {
27045
27456
  const value = config.maxInlineContentChars;
27046
27457
  if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value < MIN_INLINE_CONTENT_CHARS) {
27047
27458
  return DEFAULT_MAX_INLINE_CONTENT_CHARS;
@@ -27077,14 +27488,14 @@ function initialContentSlice(content, maxChars) {
27077
27488
  const lineBreak = content.lastIndexOf("\n", endOffset);
27078
27489
  if (lineBreak >= Math.floor(maxChars * 0.8)) endOffset = lineBreak + 1;
27079
27490
  }
27080
- const text5 = content.slice(0, endOffset);
27491
+ const text6 = content.slice(0, endOffset);
27081
27492
  return {
27082
- text: text5,
27493
+ text: text6,
27083
27494
  endOffset,
27084
27495
  totalBytes: Buffer.byteLength(content),
27085
27496
  totalLines: content.length === 0 ? 0 : content.split("\n").length,
27086
- shownBytes: Buffer.byteLength(text5),
27087
- shownLines: text5.length === 0 ? 0 : text5.split("\n").length
27497
+ shownBytes: Buffer.byteLength(text6),
27498
+ shownLines: text6.length === 0 ? 0 : text6.split("\n").length
27088
27499
  };
27089
27500
  }
27090
27501
  function normalizeFindQueries(value) {
@@ -27203,23 +27614,23 @@ ${r.snippet}` : ""}
27203
27614
  }
27204
27615
  return output;
27205
27616
  }
27206
- function boundSearchPresentation(text5, guidance, truncationGuidance, maxChars) {
27207
- const fullText = `${text5}${guidance}`;
27617
+ function boundSearchPresentation(text6, guidance, truncationGuidance, maxChars) {
27618
+ const fullText = `${text6}${guidance}`;
27208
27619
  if (fullText.length <= maxChars) {
27209
- return { text: fullText, truncated: false, originalChars: text5.length, returnedChars: text5.length, omittedChars: 0 };
27620
+ return { text: fullText, truncated: false, originalChars: text6.length, returnedChars: text6.length, omittedChars: 0 };
27210
27621
  }
27211
27622
  const marker = `
27212
27623
 
27213
27624
  ---
27214
27625
  [Output truncated.]${truncationGuidance}`;
27215
27626
  const prefixLength = maxChars - marker.length;
27216
- const bounded = `${text5.slice(0, prefixLength)}${marker}`;
27627
+ const bounded = `${text6.slice(0, prefixLength)}${marker}`;
27217
27628
  return {
27218
27629
  text: bounded,
27219
27630
  truncated: true,
27220
- originalChars: text5.length,
27631
+ originalChars: text6.length,
27221
27632
  returnedChars: prefixLength,
27222
- omittedChars: text5.length - prefixLength
27633
+ omittedChars: text6.length - prefixLength
27223
27634
  };
27224
27635
  }
27225
27636
  function registeredFetchToolNames(settings2) {
@@ -27421,6 +27832,7 @@ Full search results are stored as responseId "${searchId}". `;
27421
27832
  const allUrls = [];
27422
27833
  const allInlineContent = [];
27423
27834
  const resolvedProvider = resolveRequestedProvider(params.provider);
27835
+ const providerFromConfig = (normalizeProviderInput(params.provider) ?? "auto") === "auto";
27424
27836
  const queryResponses = await runSearchQueries(queryList, async (query) => {
27425
27837
  signal?.throwIfAborted();
27426
27838
  onUpdate?.({
@@ -27430,6 +27842,7 @@ Full search results are stored as responseId "${searchId}". `;
27430
27842
  try {
27431
27843
  const { answer, results, inlineContent: inlineContent2, provider, providerResponses } = await search(query, {
27432
27844
  provider: resolvedProvider,
27845
+ providerFromConfig,
27433
27846
  numResults: params.numResults,
27434
27847
  recencyFilter,
27435
27848
  domainFilter: params.domainFilter,
@@ -27514,6 +27927,7 @@ Full search results are stored as responseId "${searchId}". `;
27514
27927
  try {
27515
27928
  const response = await search(query, {
27516
27929
  provider: resolveRequestedProvider(params.provider),
27930
+ providerFromConfig: (normalizeProviderInput(params.provider) ?? "auto") === "auto",
27517
27931
  numResults,
27518
27932
  recencyFilter,
27519
27933
  domainFilter,
@@ -27783,9 +28197,9 @@ ${retrievalHint}` : "\n---\nContent retrieval is not registered." : "\n---\nAuth
27783
28197
  if (params.findText !== void 0) {
27784
28198
  try {
27785
28199
  const found = findContent(serialized, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
27786
- const { text: text6, ...findDetails } = found;
28200
+ const { text: text7, ...findDetails } = found;
27787
28201
  return {
27788
- content: [{ type: "text", text: text6 }],
28202
+ content: [{ type: "text", text: text7 }],
27789
28203
  details: { responseId: artifact.id, type: "research", contentLength: serialized.length, findMode: params.findMode ?? "case-insensitive", ...findDetails }
27790
28204
  };
27791
28205
  } catch (err) {
@@ -27816,13 +28230,13 @@ ${retrievalHint}` : "\n---\nContent retrieval is not registered." : "\n---\nAuth
27816
28230
  details: { error: "Offset out of range", offset, contentLength: serialized.length }
27817
28231
  };
27818
28232
  }
27819
- const { endOffset, text: text5 } = sliceWithContinuation(serialized, offset, limit, maxInlineContentChars, (end) => `
28233
+ const { endOffset, text: text6 } = sliceWithContinuation(serialized, offset, limit, maxInlineContentChars, (end) => `
27820
28234
 
27821
28235
  ---
27822
28236
  Showing chars ${offset}-${end} of ${serialized.length}. Use ${toolNames.getSearchContent}({ responseId: "${artifact.id}", offset: ${end}, limit: ${limit} }) for the next slice.`);
27823
28237
  const hasMore = endOffset < serialized.length;
27824
28238
  return {
27825
- content: [{ type: "text", text: text5 }],
28239
+ content: [{ type: "text", text: text6 }],
27826
28240
  details: { responseId: artifact.id, type: "research", contentLength: serialized.length, offset, limit, returnedChars: endOffset - offset, nextOffset: hasMore ? endOffset : null, truncated: hasMore }
27827
28241
  };
27828
28242
  }
@@ -27863,9 +28277,9 @@ Showing chars ${offset}-${end} of ${serialized.length}. Use ${toolNames.getSearc
27863
28277
  if (params.findText !== void 0) {
27864
28278
  try {
27865
28279
  const found = findContent(fullResults, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
27866
- const { text: text6, ...findDetails } = found;
28280
+ const { text: text7, ...findDetails } = found;
27867
28281
  return {
27868
- content: [{ type: "text", text: text6 }],
28282
+ content: [{ type: "text", text: text7 }],
27869
28283
  details: { responseId: params.responseId, query: queryData.query, resultCount: queryData.results.length, contentLength: fullResults.length, findMode: params.findMode ?? "case-insensitive", ...findDetails }
27870
28284
  };
27871
28285
  } catch (err) {
@@ -27897,14 +28311,14 @@ Showing chars ${offset}-${end} of ${serialized.length}. Use ${toolNames.getSearc
27897
28311
  };
27898
28312
  }
27899
28313
  const queryIndex = data.queries.indexOf(queryData);
27900
- const { endOffset, text: text5 } = sliceWithContinuation(fullResults, offset, limit, maxInlineContentChars, (end) => `
28314
+ const { endOffset, text: text6 } = sliceWithContinuation(fullResults, offset, limit, maxInlineContentChars, (end) => `
27901
28315
 
27902
28316
  ---
27903
28317
  Showing chars ${offset}-${end} of ${fullResults.length}. Use ${toolNames.getSearchContent}({ responseId: "${params.responseId}", queryIndex: ${queryIndex}, offset: ${end}, limit: ${limit} }) for the next slice.`);
27904
28318
  const returnedChars = endOffset - offset;
27905
28319
  const hasMore = endOffset < fullResults.length;
27906
28320
  return {
27907
- content: [{ type: "text", text: text5 }],
28321
+ content: [{ type: "text", text: text6 }],
27908
28322
  details: {
27909
28323
  responseId: params.responseId,
27910
28324
  query: queryData.query,
@@ -27965,11 +28379,11 @@ Use one of the available indexes.` }],
27965
28379
  if (params.findText !== void 0) {
27966
28380
  try {
27967
28381
  const found = findContent(urlData.content, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
27968
- const { text: text6, ...findDetails } = found;
28382
+ const { text: text7, ...findDetails } = found;
27969
28383
  return {
27970
28384
  content: [{ type: "text", text: `# ${urlData.title || urlData.url}
27971
28385
 
27972
- ${text6}` }],
28386
+ ${text7}` }],
27973
28387
  details: { url: urlData.url, title: urlData.title, contentLength: urlData.content.length, findMode: params.findMode ?? "case-insensitive", ...findDetails }
27974
28388
  };
27975
28389
  } catch (err) {
@@ -28003,20 +28417,20 @@ ${text6}` }],
28003
28417
  const endOffset = pageEnd(urlData.content, offset, Math.min(offset + limit, urlData.content.length));
28004
28418
  const contentSlice = urlData.content.slice(offset, endOffset);
28005
28419
  const hasMore = endOffset < urlData.content.length;
28006
- let text5 = `# ${urlData.title || urlData.url}
28420
+ let text6 = `# ${urlData.title || urlData.url}
28007
28421
 
28008
28422
  ${contentSlice}`;
28009
28423
  if (hasMore || offset > 0) {
28010
- text5 += `
28424
+ text6 += `
28011
28425
 
28012
28426
  ---
28013
28427
  Showing chars ${offset}-${endOffset} of ${urlData.content.length}.`;
28014
28428
  if (hasMore) {
28015
- text5 += ` Use ${toolNames.getSearchContent}({ responseId: "${params.responseId}", urlIndex: ${selectedUrlIndex}, offset: ${endOffset}, limit: ${limit} }) for the next slice.`;
28429
+ text6 += ` Use ${toolNames.getSearchContent}({ responseId: "${params.responseId}", urlIndex: ${selectedUrlIndex}, offset: ${endOffset}, limit: ${limit} }) for the next slice.`;
28016
28430
  }
28017
28431
  }
28018
28432
  return {
28019
- content: [{ type: "text", text: text5 }],
28433
+ content: [{ type: "text", text: text6 }],
28020
28434
  details: {
28021
28435
  url: urlData.url,
28022
28436
  title: urlData.title,
@@ -28086,7 +28500,7 @@ function standaloneFetchRejection(params, fetchModes) {
28086
28500
  return void 0;
28087
28501
  }
28088
28502
  function createStandaloneWebToolCore() {
28089
- const config = loadConfig41();
28503
+ const config = loadConfig42();
28090
28504
  const settings2 = {
28091
28505
  toolNames: { ...DEFAULT_TOOL_NAMES },
28092
28506
  enabledTools: {