@herbertgao/pi-extensions 2026.10.13 → 2026.10.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/README.md +16 -14
  2. package/THIRD_PARTY_NOTICES.md +3 -3
  3. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/README.md +2 -2
  5. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +1 -0
  6. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +3 -6
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/context.ts +22 -5
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +44 -14
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/default-mode.ts +1 -5
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/index.ts +20 -5
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +4 -1
  12. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +42 -18
  13. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/layout.ts +12 -3
  14. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +131 -0
  15. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +217 -113
  16. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +12 -5
  17. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/subagent-notification.ts +556 -0
  18. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/ansi-text.ts +50 -0
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/format.ts +11 -0
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/patch-keys.ts +4 -0
  21. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  22. package/node_modules/@juicesharp/rpiv-ask-user-question/README.md +1 -0
  23. package/node_modules/@juicesharp/rpiv-ask-user-question/ask-user-question.ts +27 -3
  24. package/node_modules/@juicesharp/rpiv-ask-user-question/config.ts +23 -0
  25. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/configuration.md +15 -0
  26. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/keyboard.md +9 -2
  27. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/de.json +7 -4
  28. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/en.json +8 -5
  29. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/es.json +7 -4
  30. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/fr.json +7 -4
  31. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/pt-BR.json +7 -4
  32. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/pt.json +7 -4
  33. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/ru.json +7 -4
  34. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/uk.json +7 -4
  35. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/zh.json +7 -4
  36. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +4 -3
  37. package/node_modules/@juicesharp/rpiv-ask-user-question/presentation.ts +11 -1
  38. package/node_modules/@juicesharp/rpiv-ask-user-question/state/build-questionnaire.ts +6 -0
  39. package/node_modules/@juicesharp/rpiv-ask-user-question/state/key-router.ts +49 -8
  40. package/node_modules/@juicesharp/rpiv-ask-user-question/state/questionnaire-session.ts +6 -0
  41. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state-reducer.ts +13 -1
  42. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state.ts +2 -0
  43. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-block-renderer.ts +19 -7
  44. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-builder.ts +36 -7
  45. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-copy.ts +13 -2
  46. package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-content-strategy.ts +24 -8
  47. package/node_modules/@juicesharp/rpiv-ask-user-question/view/transcript.ts +144 -0
  48. package/node_modules/@narumitw/pi-btw/README.md +8 -3
  49. package/node_modules/@narumitw/pi-btw/dist/index.ts +448 -182
  50. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +4 -4
  51. package/node_modules/@narumitw/pi-btw/docs/core-alignment.md +10 -2
  52. package/node_modules/@narumitw/pi-btw/docs/main-context-runtime.md +45 -0
  53. package/node_modules/@narumitw/pi-btw/docs/workflows.md +48 -5
  54. package/node_modules/@narumitw/pi-btw/package.json +5 -5
  55. package/node_modules/@narumitw/pi-btw/src/btw.ts +39 -14
  56. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +83 -63
  57. package/node_modules/@narumitw/pi-btw/src/import-main-updates.ts +84 -0
  58. package/node_modules/@narumitw/pi-btw/src/keybindings.ts +29 -4
  59. package/node_modules/@narumitw/pi-btw/src/main-context-snapshot.ts +125 -0
  60. package/node_modules/@narumitw/pi-btw/src/menu.ts +1 -0
  61. package/node_modules/@narumitw/pi-btw/src/side-thread.ts +66 -17
  62. package/node_modules/@narumitw/pi-btw/src/transcript-markdown.ts +5 -5
  63. package/node_modules/@narumitw/pi-btw/src/transcript-pager.ts +47 -6
  64. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  65. package/node_modules/pi-lens/CHANGELOG.md +440 -0
  66. package/node_modules/pi-lens/README.md +13 -3
  67. package/node_modules/pi-lens/config/dependency-cruiser-eager-allowlist.json +1 -0
  68. package/node_modules/pi-lens/dist/chunk-22Y2BM7H.js +23 -0
  69. package/node_modules/pi-lens/dist/{chunk-ATKJFDQN.js → chunk-27VWVB23.js} +12 -14
  70. package/node_modules/pi-lens/dist/{chunk-S2HEXIWI.js → chunk-2FYKETQJ.js} +10 -6
  71. package/node_modules/pi-lens/dist/{chunk-SRYEJNES.js → chunk-2LDMXL2M.js} +2 -2
  72. package/node_modules/pi-lens/dist/{chunk-ZHH37KZL.js → chunk-2SDHYHHO.js} +17 -17
  73. package/node_modules/pi-lens/dist/chunk-2Y6OJRSI.js +38 -0
  74. package/node_modules/pi-lens/dist/chunk-3SNDVPOR.js +507 -0
  75. package/node_modules/pi-lens/dist/{chunk-5OFV52AM.js → chunk-3WCEHYOI.js} +1 -1
  76. package/node_modules/pi-lens/dist/chunk-44X7VIKR.js +73 -0
  77. package/node_modules/pi-lens/dist/{chunk-DEL2U6CM.js → chunk-4FHUGDKU.js} +16 -14
  78. package/node_modules/pi-lens/dist/{chunk-CT4MN5IU.js → chunk-4ODSZ35Z.js} +353 -359
  79. package/node_modules/pi-lens/dist/{chunk-ZIVJBOO3.js → chunk-4U7GDSZQ.js} +2 -2
  80. package/node_modules/pi-lens/dist/chunk-54NIOJJZ.js +25 -0
  81. package/node_modules/pi-lens/dist/{chunk-N5FLEO7W.js → chunk-5DKE4HGX.js} +37 -37
  82. package/node_modules/pi-lens/dist/{chunk-P63GXC37.js → chunk-5LRUKYFA.js} +31 -4
  83. package/node_modules/pi-lens/dist/{chunk-HRNHZA3N.js → chunk-63NMUNYP.js} +12 -16
  84. package/node_modules/pi-lens/dist/{chunk-HWCCCQNX.js → chunk-6XSESGWD.js} +13 -6
  85. package/node_modules/pi-lens/dist/{chunk-UMS2MFPZ.js → chunk-72J27ICO.js} +2 -3
  86. package/node_modules/pi-lens/dist/{chunk-ED36RF6Y.js → chunk-7FLRUH6B.js} +1 -1
  87. package/node_modules/pi-lens/dist/chunk-7IYC4ENJ.js +297 -0
  88. package/node_modules/pi-lens/dist/chunk-7WWQAW5P.js +30 -0
  89. package/node_modules/pi-lens/dist/{chunk-3DA2JDOL.js → chunk-7ZS7MC24.js} +551 -203
  90. package/node_modules/pi-lens/dist/{chunk-WMYE35PX.js → chunk-AHWA4AKM.js} +7 -5
  91. package/node_modules/pi-lens/dist/{chunk-JW3YWBVB.js → chunk-AI3GP74G.js} +17 -19
  92. package/node_modules/pi-lens/dist/{chunk-AGSS7277.js → chunk-APFJKOP6.js} +6 -23
  93. package/node_modules/pi-lens/dist/{chunk-ZVUL7QYY.js → chunk-ASRAO7KG.js} +29 -32
  94. package/node_modules/pi-lens/dist/{chunk-BW5KFIQC.js → chunk-AWQWXSW4.js} +1 -0
  95. package/node_modules/pi-lens/dist/{chunk-TLX72JTG.js → chunk-CG5V25HX.js} +1 -1
  96. package/node_modules/pi-lens/dist/chunk-CKEQFGLT.js +32 -0
  97. package/node_modules/pi-lens/dist/{chunk-Y6GZHWSJ.js → chunk-COOUUC5W.js} +6 -6
  98. package/node_modules/pi-lens/dist/{chunk-XTBDCR27.js → chunk-CPZ5JJW6.js} +4 -4
  99. package/node_modules/pi-lens/dist/{chunk-RKKOYPRA.js → chunk-DS2USX5G.js} +13 -15
  100. package/node_modules/pi-lens/dist/chunk-EA2ZRG44.js +27 -0
  101. package/node_modules/pi-lens/dist/{chunk-GSLNCYGG.js → chunk-EDMLIW6W.js} +13 -14
  102. package/node_modules/pi-lens/dist/{chunk-2EECBNC5.js → chunk-EIKRZ32J.js} +75 -0
  103. package/node_modules/pi-lens/dist/chunk-EKNWOL2I.js +27 -0
  104. package/node_modules/pi-lens/dist/{chunk-R3T7CLQ2.js → chunk-ELZRSR5N.js} +41 -41
  105. package/node_modules/pi-lens/dist/{chunk-GMX5OS7B.js → chunk-EN5AM7PX.js} +11 -12
  106. package/node_modules/pi-lens/dist/{chunk-3RKP3FMS.js → chunk-EWXXLS26.js} +226 -24
  107. package/node_modules/pi-lens/dist/chunk-EX4EXBW7.js +37 -0
  108. package/node_modules/pi-lens/dist/{chunk-XHJBS436.js → chunk-EXVXBSGN.js} +25 -25
  109. package/node_modules/pi-lens/dist/{chunk-MZGQNL3Y.js → chunk-F7BO6FWH.js} +12 -13
  110. package/node_modules/pi-lens/dist/{chunk-V35JG4JB.js → chunk-FEDWAYDS.js} +152 -334
  111. package/node_modules/pi-lens/dist/{chunk-J64T55EI.js → chunk-FWZRGGGY.js} +73 -9
  112. package/node_modules/pi-lens/dist/{chunk-T57LYLZT.js → chunk-G224FADB.js} +1 -1
  113. package/node_modules/pi-lens/dist/chunk-G5UCJFT7.js +26 -0
  114. package/node_modules/pi-lens/dist/{chunk-LLJNQKQW.js → chunk-GLW3YDZZ.js} +20 -13
  115. package/node_modules/pi-lens/dist/{chunk-GXFV6MYU.js → chunk-GTDSYEA2.js} +72 -39
  116. package/node_modules/pi-lens/dist/{chunk-DUO2TU77.js → chunk-GYRZ72R4.js} +10 -4
  117. package/node_modules/pi-lens/dist/chunk-HYVXA3BB.js +49 -0
  118. package/node_modules/pi-lens/dist/{chunk-W66O5E25.js → chunk-IEBJF3PN.js} +13 -15
  119. package/node_modules/pi-lens/dist/{chunk-GAQ7OQG6.js → chunk-IL7K66ZQ.js} +83 -94
  120. package/node_modules/pi-lens/dist/{chunk-T7FEBKXN.js → chunk-JWOVP5BL.js} +7 -9
  121. package/node_modules/pi-lens/dist/{chunk-UBOQLVT2.js → chunk-K2GUZ4DN.js} +4 -4
  122. package/node_modules/pi-lens/dist/{chunk-5VSF4UUQ.js → chunk-K4SZB56V.js} +34 -39
  123. package/node_modules/pi-lens/dist/{chunk-7D6L4MTX.js → chunk-KCBRHV5E.js} +3 -3
  124. package/node_modules/pi-lens/dist/{chunk-GSM5UU7A.js → chunk-KFXCL4OV.js} +38 -28
  125. package/node_modules/pi-lens/dist/{chunk-J6MPGQTS.js → chunk-KJJAVH3X.js} +81 -15
  126. package/node_modules/pi-lens/dist/{chunk-BWD5EPKO.js → chunk-KPVLQHCZ.js} +4 -6
  127. package/node_modules/pi-lens/dist/{chunk-MPNJLASA.js → chunk-KX56K73G.js} +10 -13
  128. package/node_modules/pi-lens/dist/{chunk-AWSCPCN2.js → chunk-LMCTHJ2H.js} +19 -19
  129. package/node_modules/pi-lens/dist/{chunk-IWDLU6K3.js → chunk-MEFLGBCS.js} +4 -6
  130. package/node_modules/pi-lens/dist/{chunk-TOY6QKOH.js → chunk-MKPCELNI.js} +17 -17
  131. package/node_modules/pi-lens/dist/{chunk-POMLXPMY.js → chunk-N3PLNNCW.js} +1 -1
  132. package/node_modules/pi-lens/dist/chunk-N5FBM25N.js +22 -0
  133. package/node_modules/pi-lens/dist/{chunk-CYRKQRPM.js → chunk-NFNVDDGB.js} +2 -4
  134. package/node_modules/pi-lens/dist/{chunk-RMLC67LF.js → chunk-NLIVE7L6.js} +2 -30
  135. package/node_modules/pi-lens/dist/{chunk-24AKHFGP.js → chunk-OMJ3OFBJ.js} +6 -6
  136. package/node_modules/pi-lens/dist/{chunk-IQWN5JCP.js → chunk-OZNCKLOX.js} +13 -14
  137. package/node_modules/pi-lens/dist/chunk-P5XUGPIX.js +31 -0
  138. package/node_modules/pi-lens/dist/{chunk-2KXTHF3M.js → chunk-PJXNTPB2.js} +253 -33
  139. package/node_modules/pi-lens/dist/chunk-PKOXJIVT.js +88 -0
  140. package/node_modules/pi-lens/dist/{chunk-DGUKIYSI.js → chunk-PP2A5V2T.js} +8 -10
  141. package/node_modules/pi-lens/dist/{chunk-KAPJINKN.js → chunk-Q42LJANT.js} +2 -2
  142. package/node_modules/pi-lens/dist/{chunk-UZ2XCLYS.js → chunk-Q4BKKOVC.js} +8 -8
  143. package/node_modules/pi-lens/dist/{chunk-TIQ2PKDW.js → chunk-QT66NEYN.js} +4 -4
  144. package/node_modules/pi-lens/dist/{chunk-U44DJXQP.js → chunk-RCHO5W7M.js} +15 -18
  145. package/node_modules/pi-lens/dist/{chunk-YH5MVY2U.js → chunk-RG3MXTRI.js} +7 -7
  146. package/node_modules/pi-lens/dist/chunk-RG7OODGM.js +57 -0
  147. package/node_modules/pi-lens/dist/{chunk-OHKJ7PQF.js → chunk-RU34BA4D.js} +43 -39
  148. package/node_modules/pi-lens/dist/{chunk-JMYYOTQG.js → chunk-S26LC76R.js} +13 -1
  149. package/node_modules/pi-lens/dist/{chunk-XBJVAEEO.js → chunk-S55TEC7I.js} +3 -2
  150. package/node_modules/pi-lens/dist/{chunk-RVK72CZX.js → chunk-SJHC3BCZ.js} +1397 -481
  151. package/node_modules/pi-lens/dist/{chunk-IYNJ6YPZ.js → chunk-SNEUMLM7.js} +4 -4
  152. package/node_modules/pi-lens/dist/{chunk-S67KYG37.js → chunk-T4NGVFYI.js} +2 -2
  153. package/node_modules/pi-lens/dist/{chunk-YCWYO6TQ.js → chunk-THEXI2QO.js} +48 -45
  154. package/node_modules/pi-lens/dist/{chunk-AMERCH6V.js → chunk-TL2TCJYL.js} +15 -16
  155. package/node_modules/pi-lens/dist/{chunk-KUA4OJ5Y.js → chunk-TPYYEDP5.js} +823 -350
  156. package/node_modules/pi-lens/dist/{chunk-YNE3RP52.js → chunk-TVZRLTG6.js} +8 -1
  157. package/node_modules/pi-lens/dist/{chunk-ROYSX2S5.js → chunk-UCVMSOXF.js} +2 -2
  158. package/node_modules/pi-lens/dist/chunk-UL5SXQVX.js +32 -0
  159. package/node_modules/pi-lens/dist/{chunk-7HXE67BN.js → chunk-UO66IMVP.js} +2 -2
  160. package/node_modules/pi-lens/dist/{chunk-VOOAPROD.js → chunk-UVY4TOJH.js} +3 -3
  161. package/node_modules/pi-lens/dist/{chunk-RKBXZN3A.js → chunk-VIDEKABZ.js} +2 -2
  162. package/node_modules/pi-lens/dist/{chunk-2FN63LPV.js → chunk-VITFDI3O.js} +13 -14
  163. package/node_modules/pi-lens/dist/{chunk-6DLWKFEX.js → chunk-VUAVE3QC.js} +41 -42
  164. package/node_modules/pi-lens/dist/{chunk-FM4RDMKT.js → chunk-WUY4BZEP.js} +10 -12
  165. package/node_modules/pi-lens/dist/{chunk-SD4I7ZO4.js → chunk-X3UTCXAA.js} +43 -53
  166. package/node_modules/pi-lens/dist/chunk-XHDBJODR.js +45 -0
  167. package/node_modules/pi-lens/dist/{chunk-5IUSNGOC.js → chunk-XHLK33VM.js} +28 -21
  168. package/node_modules/pi-lens/dist/{chunk-3KAZU3VR.js → chunk-XI34NWDI.js} +2 -2
  169. package/node_modules/pi-lens/dist/{chunk-QBFBRV2B.js → chunk-XWFIHYCH.js} +4 -2
  170. package/node_modules/pi-lens/dist/{chunk-JUKMK5Y4.js → chunk-Y2TPADJR.js} +10 -11
  171. package/node_modules/pi-lens/dist/{chunk-EBC36LNN.js → chunk-Y5KTA2OB.js} +17 -17
  172. package/node_modules/pi-lens/dist/{chunk-HYGZEMX6.js → chunk-YKVDBNPO.js} +11 -5
  173. package/node_modules/pi-lens/dist/{chunk-KN35K52N.js → chunk-YSDPVDFC.js} +3 -3
  174. package/node_modules/pi-lens/dist/chunk-YWNO5Q4R.js +44 -0
  175. package/node_modules/pi-lens/dist/{chunk-US7ECLD7.js → chunk-YWWG4AQA.js} +119 -28
  176. package/node_modules/pi-lens/dist/{chunk-O4NWQT6I.js → chunk-YXDCRUKQ.js} +4 -4
  177. package/node_modules/pi-lens/dist/{chunk-XYURS6EN.js → chunk-YXGRRORB.js} +15 -17
  178. package/node_modules/pi-lens/dist/{chunk-IUE7SSKV.js → chunk-ZAPSUBLU.js} +13 -7
  179. package/node_modules/pi-lens/dist/{chunk-EUXZEFTV.js → chunk-ZPJM7DID.js} +3 -3
  180. package/node_modules/pi-lens/dist/{chunk-5HSRT26B.js → chunk-ZSUX7KEM.js} +16 -15
  181. package/node_modules/pi-lens/dist/index.js +37155 -32210
  182. package/node_modules/pi-lens/dist/mcp/analyze-cli.js +11 -12
  183. package/node_modules/pi-lens/dist/mcp/cli.js +46 -45
  184. package/node_modules/pi-lens/dist/mcp/server.js +1210 -574
  185. package/node_modules/pi-lens/dist/mcp/worker.js +65 -65
  186. package/node_modules/pi-lens/dist/probes/installer.js +21 -23
  187. package/node_modules/pi-lens/docs/adr/0010-trace-validation-session-lifecycle.md +390 -0
  188. package/node_modules/pi-lens/docs/adr/README.md +1 -0
  189. package/node_modules/pi-lens/docs/ast-grep_rules_catalog.md +5 -3
  190. package/node_modules/pi-lens/docs/configuration.md +9 -0
  191. package/node_modules/pi-lens/docs/engineering-principles.md +12 -0
  192. package/node_modules/pi-lens/docs/environment-variables.md +20 -0
  193. package/node_modules/pi-lens/docs/features.md +16 -1
  194. package/node_modules/pi-lens/docs/globalconfig.md +37 -8
  195. package/node_modules/pi-lens/docs/lsp-capability-matrix.md +105 -12
  196. package/node_modules/pi-lens/docs/lsp-idle-eviction.md +37 -18
  197. package/node_modules/pi-lens/docs/pi-lens-fixer.md +22 -1
  198. package/node_modules/pi-lens/docs/pi-lens-investigator.md +14 -0
  199. package/node_modules/pi-lens/docs/pi-lens-merge-policy.md +23 -10
  200. package/node_modules/pi-lens/docs/pi-lens-monitor.md +64 -8
  201. package/node_modules/pi-lens/docs/pi-lens-retro.md +2 -2
  202. package/node_modules/pi-lens/docs/pi-lens-reviewer.md +48 -1
  203. package/node_modules/pi-lens/docs/pi-lens-subagent.md +8 -1
  204. package/node_modules/pi-lens/docs/release-qa-baseline.md +19 -7
  205. package/node_modules/pi-lens/docs/servercapabilities.md +47 -47
  206. package/node_modules/pi-lens/docs/settings.md +9 -5
  207. package/node_modules/pi-lens/docs/subagent-compat.md +1 -1
  208. package/node_modules/pi-lens/docs/usage.md +1 -0
  209. package/node_modules/pi-lens/package.json +6 -4
  210. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-return-value-in-generator-test.yml +17 -0
  211. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-js-test.yml +86 -0
  212. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-test.yml +86 -0
  213. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/unchecked-numeric-parse-python-test.yml +15 -0
  214. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-return-value-in-generator.yml +9 -4
  215. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-sql-in-code-execute-js.yml +119 -0
  216. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-sql-in-code-execute.yml +119 -0
  217. package/node_modules/pi-lens/rules/ast-grep-rules/rules/unchecked-numeric-parse-python.yml +13 -2
  218. package/node_modules/pi-lens/rules/rule-catalog.json +25 -1
  219. package/node_modules/pi-lens/scripts/analyze-pi-lens-logs.mjs +15 -5
  220. package/node_modules/pi-lens/scripts/lib/is-main-module.mjs +27 -0
  221. package/node_modules/pi-lens/scripts/lib/scratch-home-env.mjs +21 -0
  222. package/node_modules/pi-lens/scripts/rpc-load-check.mjs +4 -6
  223. package/node_modules/pi-lens/scripts/warm-loader-cache.mjs +2 -5
  224. package/node_modules/pi-next-cue/package.json +4 -1
  225. package/node_modules/pi-typesafe/README.md +6 -6
  226. package/node_modules/pi-typesafe/dist/ask.js +9 -2
  227. package/node_modules/pi-typesafe/dist/auth.d.ts +3 -2
  228. package/node_modules/pi-typesafe/dist/auth.js +2 -2
  229. package/node_modules/pi-typesafe/dist/backends.d.ts +20 -5
  230. package/node_modules/pi-typesafe/dist/backends.js +32 -8
  231. package/node_modules/pi-typesafe/dist/batch.d.ts +1 -1
  232. package/node_modules/pi-typesafe/dist/batch.js +2 -2
  233. package/node_modules/pi-typesafe/dist/client.d.ts +1 -1
  234. package/node_modules/pi-typesafe/dist/client.js +24 -12
  235. package/node_modules/pi-typesafe/dist/credentials.d.ts +8 -6
  236. package/node_modules/pi-typesafe/dist/credentials.js +70 -16
  237. package/node_modules/pi-typesafe/dist/extension.js +118 -26
  238. package/node_modules/pi-typesafe/dist/index.d.ts +1 -1
  239. package/node_modules/pi-typesafe/dist/index.js +1 -1
  240. package/node_modules/pi-typesafe/dist/key-prompt.d.ts +1 -1
  241. package/node_modules/pi-typesafe/dist/key-prompt.js +6 -6
  242. package/node_modules/pi-typesafe/dist/login.d.ts +11 -10
  243. package/node_modules/pi-typesafe/dist/login.js +24 -21
  244. package/node_modules/pi-typesafe/dist/schema.d.ts +8 -8
  245. package/node_modules/pi-typesafe/dist/schema.js +29 -7
  246. package/node_modules/pi-typesafe/package.json +2 -2
  247. package/node_modules/pi-web-access/CHANGELOG.md +40 -0
  248. package/node_modules/pi-web-access/README.md +96 -22
  249. package/node_modules/pi-web-access/brave-rate-limit.ts +2 -2
  250. package/node_modules/pi-web-access/curator-page.ts +3 -1
  251. package/node_modules/pi-web-access/curator-server.ts +1 -0
  252. package/node_modules/pi-web-access/dist/index.js +2607 -1674
  253. package/node_modules/pi-web-access/dist/mcp-cli.js +1119 -327
  254. package/node_modules/pi-web-access/duckduckgo-rate-limit.ts +95 -0
  255. package/node_modules/pi-web-access/duckduckgo.ts +51 -45
  256. package/node_modules/pi-web-access/exa.ts +48 -6
  257. package/node_modules/pi-web-access/extract.ts +2 -2
  258. package/node_modules/pi-web-access/fetch-params.ts +5 -4
  259. package/node_modules/pi-web-access/field-extract.ts +347 -0
  260. package/node_modules/pi-web-access/gemini-search.ts +151 -13
  261. package/node_modules/pi-web-access/index.ts +128 -125
  262. package/node_modules/pi-web-access/mistral-search.ts +1 -1
  263. package/node_modules/pi-web-access/ninerouter.ts +92 -0
  264. package/node_modules/pi-web-access/offtopic-judge.ts +72 -0
  265. package/node_modules/pi-web-access/openai-search.ts +36 -10
  266. package/node_modules/pi-web-access/package.json +1 -1
  267. package/node_modules/pi-web-access/perplexity.ts +1 -0
  268. package/node_modules/pi-web-access/query-rewrite.ts +39 -13
  269. package/node_modules/pi-web-access/source-check.ts +31 -15
  270. package/node_modules/pi-web-access/summary-model-scope.ts +19 -1
  271. package/node_modules/pi-web-access/summary-review.ts +13 -20
  272. package/node_modules/pi-web-access/tool-arguments.ts +1 -1
  273. package/node_modules/pi-web-access/upgrade-notice.ts +47 -0
  274. package/node_modules/pi-web-access/utils.ts +26 -1
  275. package/node_modules/pi-web-access/web-tool-contract.ts +4 -1
  276. package/node_modules/pi-web-access/web-tool-core.ts +99 -19
  277. package/node_modules/pi-web-access/xai-search.ts +3 -3
  278. package/package.json +15 -15
  279. package/node_modules/pi-lens/dist/chunk-3PTHXJXR.js +0 -28
  280. package/node_modules/pi-lens/dist/chunk-3QED2P4V.js +0 -31
  281. package/node_modules/pi-lens/dist/chunk-5WRPDP2A.js +0 -47
  282. package/node_modules/pi-lens/dist/chunk-ABBOA7UD.js +0 -157
  283. package/node_modules/pi-lens/dist/chunk-CUHSHSB6.js +0 -273
  284. package/node_modules/pi-lens/dist/chunk-GL5LUMZE.js +0 -51
  285. package/node_modules/pi-lens/dist/chunk-HAD7QRQI.js +0 -30
  286. package/node_modules/pi-lens/dist/chunk-JORED7EX.js +0 -44
  287. package/node_modules/pi-lens/dist/chunk-KYUB6QDC.js +0 -72
  288. package/node_modules/pi-lens/dist/chunk-LZSEQW6A.js +0 -57
  289. package/node_modules/pi-lens/dist/chunk-M2IFVFWU.js +0 -79
  290. package/node_modules/pi-lens/dist/chunk-M2UD3LPU.js +0 -88
  291. package/node_modules/pi-lens/dist/chunk-MBKQHGA7.js +0 -39
  292. package/node_modules/pi-lens/dist/chunk-R7YOCSNV.js +0 -23
  293. package/node_modules/pi-lens/dist/chunk-SKAMFC7A.js +0 -28
  294. package/node_modules/pi-lens/dist/chunk-SYE6T2EB.js +0 -28
  295. package/node_modules/pi-lens/dist/chunk-TRETHTQO.js +0 -26
  296. package/node_modules/pi-lens/dist/chunk-UA7ZXYDR.js +0 -184
  297. package/node_modules/pi-lens/dist/chunk-XTFDJI3T.js +0 -24
  298. package/node_modules/pi-lens/dist/chunk-Z3CCVDUB.js +0 -76
  299. package/node_modules/pi-next-cue/.github/workflows/publish.yml +0 -20
@@ -0,0 +1,347 @@
1
+ // fetch_content mode "extract": typed values read from a fetched page by Cloudflare's Clairic model.
2
+ import type { JsonValue } from "@earendil-works/pi-ai";
3
+ import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
4
+ import { redactCredential } from "./credential-source.ts";
5
+ import { fetchWithCredentialRedirects, isRecord } from "./utils.ts";
6
+
7
+ const MAX_FIELDS = 16;
8
+ const MAX_PAGE_CHARS = 200_000;
9
+ // Measured on the extraction fixtures: no wrong value reached 0.80, so lower confidence is shown only as a guess.
10
+ const EXTRACT_THRESHOLD = 0.8;
11
+ const TIMEOUT_MS = 30_000;
12
+ const DURATION_UNITS = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
13
+
14
+ type ItemType = "text" | "number" | "date";
15
+ interface FieldSpec {
16
+ type: "text" | "number" | "date" | "time" | "datetime" | "duration" | "list";
17
+ integer?: true;
18
+ unit?: string;
19
+ items?: ItemType;
20
+ instructions?: string;
21
+ }
22
+
23
+ export type FieldResult =
24
+ | { status: "extracted"; value: JsonValue; confidence: number; line?: string }
25
+ | { status: "uncertain"; guess: JsonValue; confidence?: number; line?: string; notFound?: true }
26
+ | { status: "null" };
27
+
28
+ export type PageExtraction =
29
+ | { fields: Record<string, FieldResult>; cut: boolean }
30
+ | { error: string };
31
+
32
+ export function parseExtractFields(fields: unknown): Record<string, FieldSpec> {
33
+ if (!isRecord(fields)) throw new Error("fields must be an object mapping names to types");
34
+ const entries = Object.entries(fields);
35
+ if (entries.length === 0 || entries.length > MAX_FIELDS) throw new Error(`fields must list 1 to ${MAX_FIELDS} fields`);
36
+ // No prototype, so a field named "__proto__" or "constructor" is an ordinary key.
37
+ const specs: Record<string, FieldSpec> = Object.create(null);
38
+ for (const [name, raw] of entries) {
39
+ if (!/^[A-Za-z0-9_]{1,64}$/.test(name)) throw new Error(`field name "${name}" must be 1 to 64 letters, digits, or underscores`);
40
+ if (typeof raw !== "string") throw new Error(`field ${name} must be a string such as "number" or "date: when it ships"`);
41
+ const colon = raw.indexOf(":");
42
+ const type = (colon === -1 ? raw : raw.slice(0, colon)).trim();
43
+ const instructions = colon === -1 ? "" : raw.slice(colon + 1).trim();
44
+ const [base, sub, extra] = type.split(".");
45
+ let spec: FieldSpec | undefined;
46
+ if (sub === undefined && ["text", "number", "date", "time", "datetime", "duration"].includes(base)) spec = { type: base as FieldSpec["type"] };
47
+ else if (sub === undefined && base === "integer") spec = { type: "number", integer: true };
48
+ else if (sub === undefined && base === "list") spec = { type: "list", items: "text" };
49
+ else if (base === "duration" && DURATION_UNITS.includes(sub)) spec = { type: "duration", unit: sub };
50
+ else if (base === "list" && (sub === "number" || sub === "date")) spec = { type: "list", items: sub };
51
+ if (!spec || extra !== undefined) {
52
+ throw new Error(`field ${name} has unknown type "${type}"; use text, number, integer, date, time, datetime, duration, duration.<${DURATION_UNITS.join("|")}>, list, list.number, or list.date`);
53
+ }
54
+ specs[name] = instructions ? { ...spec, instructions } : spec;
55
+ }
56
+ return specs;
57
+ }
58
+
59
+ function realDate(text: string): boolean {
60
+ const [year, month, day] = text.split("-").map(Number);
61
+ const date = new Date(Date.UTC(year, month - 1, day));
62
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
63
+ }
64
+
65
+ function realTime(text: string): boolean {
66
+ const [hours, minutes, seconds = 0] = text.split(":").map(Number);
67
+ return hours <= 23 && minutes <= 59 && seconds <= 59;
68
+ }
69
+
70
+ /** Whether the value has the field's type; dates and times must also exist on the calendar and clock. */
71
+ function matchesType(spec: FieldSpec, value: unknown): boolean {
72
+ switch (spec.type) {
73
+ case "text": return typeof value === "string" && value.trim() !== "";
74
+ case "number": return typeof value === "number" && Number.isFinite(value) && (!spec.integer || Number.isInteger(value));
75
+ case "duration": return typeof value === "number" && Number.isFinite(value) && value >= 0;
76
+ case "date": return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && realDate(value);
77
+ case "time": return typeof value === "string" && /^\d{2}:\d{2}(:\d{2})?$/.test(value) && realTime(value);
78
+ case "datetime": {
79
+ const match = typeof value === "string" ? /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-](\d{2}:\d{2}))?$/.exec(value) : null;
80
+ return match !== null && realDate(match[1]) && realTime(match[2]) && (match[3] === undefined || realTime(match[3]));
81
+ }
82
+ case "list": return Array.isArray(value) && value.every((item) => matchesType({ type: spec.items! }, item));
83
+ }
84
+ }
85
+
86
+ function fieldResult(spec: FieldSpec, answer: unknown): FieldResult {
87
+ if (!isRecord(answer)) throw new Error("the response is invalid: a field answer is missing");
88
+ // Clairic may send only p_null when nothing was found.
89
+ // The answer was parsed from Clairic's JSON response, so its value is JSON.
90
+ const { value = null, confidence: rawConfidence } = answer as { value?: JsonValue; confidence?: unknown };
91
+ // A null value is Clairic's "not on the page" verdict; the guess it still sends then is a fallback, not evidence.
92
+ if (value === null) return { status: "null" };
93
+ const confidence = typeof rawConfidence === "number" && rawConfidence >= 0 && rawConfidence <= 1 ? rawConfidence : undefined;
94
+ if (confidence !== undefined && confidence >= EXTRACT_THRESHOLD && matchesType(spec, value)) return { status: "extracted", value, confidence };
95
+ return { status: "uncertain", guess: value, ...(confidence !== undefined ? { confidence } : {}) };
96
+ }
97
+
98
+ const MAX_LINE_CHARS = 200;
99
+ // A link target longer than this is kept as text.
100
+ const MAX_LINK_TARGET_CHARS = 2_048;
101
+ // Thousands separators seen on pages: comma, period, space, no-break and narrow no-break space, apostrophe.
102
+ const SEPARATORS = new Set([",", ".", " ", " ", " ", "'"]);
103
+ const isDigit = (char: string | undefined) => char !== undefined && char >= "0" && char <= "9";
104
+
105
+ /** A line reduced for comparison, with the raw index each of its UTF-16 units came from. */
106
+ interface Comparable { text: string; map: number[] }
107
+
108
+ // For each "(" on the line, the index of its ")" when it closes within the link bound. One pass with a stack.
109
+ function closingParens(line: string): Map<number, number> {
110
+ const close = new Map<number, number>();
111
+ const open: number[] = [];
112
+ for (let i = 0; i < line.length; i++) {
113
+ if (line[i] === "(") open.push(i);
114
+ else if (line[i] === ")" && open.length) {
115
+ const start = open.pop()!;
116
+ if (i - start <= MAX_LINK_TARGET_CHARS) close.set(start, i);
117
+ }
118
+ }
119
+ return close;
120
+ }
121
+
122
+ /**
123
+ * One pass over the text: NFKC, lowercase, markdown backslash escapes removed (Turndown writes `my\_package`,
124
+ * `\[beta\]`), curly quotes and dashes made plain, `* _ \` [ ]` dropped, whitespace collapsed. With `visible`, a
125
+ * link or image target `](…)` (nested parentheses and a quoted title included) is skipped, leaving the text a reader sees.
126
+ * The same steps run on the value, so matching only ever gets looser on the page side.
127
+ */
128
+ function comparable(raw: string, visible: boolean): Comparable {
129
+ const close = visible ? closingParens(raw) : undefined;
130
+ let text = "";
131
+ const map: number[] = [];
132
+ let space = false;
133
+ const emit = (chars: string, at: number) => {
134
+ // A character whose NFKC form is much longer (U+FDFA is 18 characters) stays as it is, on both sides.
135
+ const folded = chars.normalize("NFKC");
136
+ for (const char of folded.length > 4 * chars.length ? chars : folded) {
137
+ const plain = /[‘’‚‛′]/.test(char) ? "'" : /[“”„‟″]/.test(char) ? '"' : /[‐-―]/.test(char) ? "-" : char;
138
+ if (/[*_`[\]]/.test(plain)) continue;
139
+ if (/\s/.test(plain)) {
140
+ if (text && !space) { text += " "; map.push(at); space = true; }
141
+ continue;
142
+ }
143
+ const lower = plain.toLowerCase();
144
+ text += lower;
145
+ if (lower) space = false;
146
+ for (let unit = 0; unit < lower.length; unit++) map.push(at);
147
+ }
148
+ };
149
+ for (let i = 0; i < raw.length;) {
150
+ if (raw[i] === "\\" && i + 1 < raw.length && /[!-/:-@[-`{-~]/.test(raw[i + 1])) {
151
+ emit(raw[i + 1], i + 1);
152
+ i += 2;
153
+ continue;
154
+ }
155
+ const target = close && raw[i] === "]" && raw[i + 1] === "(" ? close.get(i + 1) : undefined;
156
+ if (target !== undefined) {
157
+ i = target + 1;
158
+ continue;
159
+ }
160
+ // A character with its combining marks normalizes as one unit, so "e" + U+0301 meets "é".
161
+ let next = i + String.fromCodePoint(raw.codePointAt(i)!).length;
162
+ while (next < raw.length && /\p{M}/u.test(String.fromCodePoint(raw.codePointAt(next)!))) next += raw.codePointAt(next)! > 0xffff ? 2 : 1;
163
+ emit(raw.slice(i, next), i);
164
+ i = next;
165
+ }
166
+ if (space) { text = text.slice(0, -1); map.pop(); }
167
+ return { text, map };
168
+ }
169
+
170
+ interface PageLines { lines: string[]; forms: Comparable[][]; whole: string[] }
171
+
172
+ function indexLines(page: string): PageLines {
173
+ const lines = page.split("\n");
174
+ // Without "](" there is no link target to skip, so both forms are the same.
175
+ const forms = lines.map((line) => { const visible = comparable(line, true); return [visible, line.includes("](") ? comparable(line, false) : visible]; });
176
+ // Both forms of every line joined, for a value that wraps onto the next line.
177
+ const whole = [0, 1].map((form) => forms.map((pair) => pair[form].text).filter(Boolean).join(" "));
178
+ return { lines, forms, whole };
179
+ }
180
+
181
+ /** The line, or a window of it that holds raw[start, end), at most MAX_LINE_CHARS including ellipses. */
182
+ function cite(line: string, start: number, end: number): string {
183
+ if (line.length <= MAX_LINE_CHARS) return line.replace(/\s+/g, " ").trim();
184
+ const size = MAX_LINE_CHARS - 2;
185
+ const from = Math.max(0, Math.min(line.length - size, end - start >= size ? start : start - Math.floor((size - (end - start)) / 2)));
186
+ return `${from > 0 ? "…" : ""}${line.slice(from, from + size).replace(/\s+/g, " ").trim()}${from + size < line.length ? "…" : ""}`;
187
+ }
188
+
189
+ /** undefined: not on the page; null: on the page with no single line to cite, or nothing comparable in the value. */
190
+ function locateText(value: string, page: PageLines): string | null | undefined {
191
+ const wanted = comparable(value, false).text;
192
+ if (!wanted) return null;
193
+ for (const [index, pair] of page.forms.entries()) {
194
+ for (const form of pair) {
195
+ const at = form.text.indexOf(wanted);
196
+ if (at !== -1) return cite(page.lines[index], form.map[at], form.map[at + wanted.length - 1] + 1);
197
+ }
198
+ }
199
+ return page.whole.some((text) => text.includes(wanted)) ? null : undefined;
200
+ }
201
+
202
+ // The values a digit run with separators can mean: "1.299" is 1.299 or 1299, "1.299,00" is 1299, "5.3.1" is nothing.
203
+ function readings(groups: string[], separators: string[]): number[] {
204
+ const thousands = (parts: string[]) => parts.slice(1).every((part) => part.length === 3);
205
+ const values: number[] = [];
206
+ if (thousands(groups)) values.push(Number(groups.join("")));
207
+ const decimal = separators.at(-1);
208
+ if ((decimal === "." || decimal === ",") && separators.slice(0, -1).every((separator) => separator !== decimal) && thousands(groups.slice(0, -1))) {
209
+ values.push(Number(`${groups.slice(0, -1).join("")}.${groups.at(-1)}`));
210
+ }
211
+ return values;
212
+ }
213
+
214
+ /** The first line holding the whole number, sign included: 299 is not in "1 299", and -42 is not "42". */
215
+ function locateNumber(value: number, lines: string[]): string | undefined {
216
+ for (const line of lines) {
217
+ for (let i = 0; i < line.length;) {
218
+ if (!isDigit(line[i])) { i++; continue; }
219
+ const groups: string[] = [];
220
+ const separators: string[] = [];
221
+ let end = i;
222
+ for (;;) {
223
+ const from = end;
224
+ while (isDigit(line[end])) end++;
225
+ groups.push(line.slice(from, end));
226
+ if (!SEPARATORS.has(line[end]) || !isDigit(line[end + 1])) break;
227
+ separators.push(line[end]);
228
+ end++;
229
+ }
230
+ // A minus, optionally before a currency sign, that does not join two words or numbers ("2026-11", "a-1").
231
+ let sign = i - 1;
232
+ if (/[$€£¥]/.test(line[sign] ?? "")) sign--;
233
+ const negative = (line[sign] === "-" || line[sign] === "−") && !/[\p{L}\p{N}]/u.test(line[sign - 1] ?? "");
234
+ if (readings(groups, separators).some((reading) => (negative ? -reading : reading) === value)) return cite(line, negative ? sign : i, end);
235
+ i = end;
236
+ }
237
+ }
238
+ return undefined;
239
+ }
240
+
241
+ /**
242
+ * Adds the page line a text or number value was found on (dates, times and durations are rewritten by Clairic, so
243
+ * they have none). A number match only cites; it never changes the status.
244
+ */
245
+ function withPageLine(spec: FieldSpec, result: FieldResult, page: () => PageLines): FieldResult {
246
+ if (result.status === "null") return result;
247
+ const value = result.status === "extracted" ? result.value : result.guess;
248
+ if (spec.type === "number" && typeof value === "number") {
249
+ const line = locateNumber(value, page().lines);
250
+ return line ? { ...result, line } : result;
251
+ }
252
+ if (spec.type !== "text" || typeof value !== "string") return result;
253
+ const line = locateText(value, page());
254
+ if (line) return { ...result, line };
255
+ // Text that is not on the page was not read from it, however confident the model is.
256
+ if (line === undefined && result.status === "extracted") return { status: "uncertain", guess: result.value, confidence: result.confidence, notFound: true };
257
+ return result;
258
+ }
259
+
260
+ /**
261
+ * Clairic is not in Pi's model catalog, so it is called directly with Pi's `cloudflare-workers-ai` credential.
262
+ * When Pi has an AI Gateway id (`CLOUDFLARE_GATEWAY_ID`), the request goes through that gateway.
263
+ */
264
+ async function runClairic(body: string, modelRegistry: Pick<ModelRegistry, "getProviderAuth"> | undefined, signal: AbortSignal): Promise<Record<string, unknown>> {
265
+ if (!modelRegistry) throw new Error("extract mode runs only inside Pi");
266
+ if (typeof modelRegistry.getProviderAuth !== "function") throw new Error("this Pi version cannot supply the Cloudflare credential; update Pi");
267
+ const credential = await modelRegistry.getProviderAuth("cloudflare-workers-ai");
268
+ const apiKey = credential?.auth.apiKey;
269
+ const accountId = credential?.env?.CLOUDFLARE_ACCOUNT_ID;
270
+ if (!apiKey || !accountId) throw new Error("Cloudflare Workers AI is not set up in Pi; set CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID");
271
+ const gatewayId = (await modelRegistry.getProviderAuth("cloudflare-ai-gateway"))?.env?.CLOUDFLARE_GATEWAY_ID ?? process.env.CLOUDFLARE_GATEWAY_ID;
272
+ let parsed: unknown;
273
+ try {
274
+ const response = await fetchWithCredentialRedirects(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/ai/run/@cf/cloudflare/clairic`, {
275
+ method: "POST",
276
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", ...(gatewayId ? { "cf-aig-gateway-id": gatewayId } : {}) },
277
+ body,
278
+ signal,
279
+ }, ["Authorization"]);
280
+ const text = await response.text();
281
+ if (!response.ok) {
282
+ // Redact before cutting, so a key straddling the cut can't leave a partial copy behind.
283
+ const detail = redactCredential(text, apiKey).trim().slice(0, 200);
284
+ throw new Error(`Cloudflare Workers AI returned HTTP ${response.status}${detail ? `: ${detail}` : ""}`);
285
+ }
286
+ try {
287
+ parsed = JSON.parse(text);
288
+ } catch {
289
+ throw new Error("the response is invalid: it is not JSON");
290
+ }
291
+ } catch (err) {
292
+ throw new Error(redactCredential(err instanceof Error ? err.message : String(err), apiKey));
293
+ }
294
+ if (!isRecord(parsed) || parsed.success !== true || !isRecord(parsed.result)) throw new Error("Cloudflare Workers AI reported an unsuccessful response");
295
+ return parsed.result;
296
+ }
297
+
298
+ /** Provider failures, including Cloudflare not being set up in Pi, become `{ error }`; a caller abort is rethrown. */
299
+ export async function extractPageFields(
300
+ page: string,
301
+ fields: Record<string, FieldSpec>,
302
+ context: { modelRegistry?: Pick<ModelRegistry, "getProviderAuth"> },
303
+ signal?: AbortSignal,
304
+ referenceDate = new Date().toISOString().slice(0, 10),
305
+ ): Promise<PageExtraction> {
306
+ const cut = page.length > MAX_PAGE_CHARS;
307
+ const state = cut ? page.slice(0, MAX_PAGE_CHARS) : page;
308
+ const body = JSON.stringify({
309
+ model: "clairic",
310
+ state,
311
+ fields,
312
+ reference_date: referenceDate,
313
+ });
314
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
315
+ try {
316
+ const result = await runClairic(body, context.modelRegistry, signal ? AbortSignal.any([signal, timeout]) : timeout);
317
+ const answers = result.answers;
318
+ if (!isRecord(answers)) throw new Error("the response is invalid: answers are missing");
319
+ let lines: PageLines | undefined;
320
+ const page = () => lines ??= indexLines(state);
321
+ const results = Object.fromEntries(Object.entries(fields).map(([name, spec]) => [name, withPageLine(spec, fieldResult(spec, Object.hasOwn(answers, name) ? answers[name] : undefined), page)]));
322
+ return { fields: results, cut: cut || result.truncated === true };
323
+ } catch (err) {
324
+ signal?.throwIfAborted();
325
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1000} s` };
326
+ return { error: err instanceof Error ? err.message : String(err) };
327
+ }
328
+ }
329
+
330
+ const MAX_SHOWN_VALUE_CHARS = 1_000;
331
+ // One long value must not push the other fields and pages out of the text the model sees.
332
+ const shown = (value: unknown) => {
333
+ const text = typeof value === "string" ? value : JSON.stringify(value);
334
+ return text.length > MAX_SHOWN_VALUE_CHARS ? `${text.slice(0, MAX_SHOWN_VALUE_CHARS)}… [${text.length} characters; the rest is in the stored page]` : text;
335
+ };
336
+
337
+ export function formatPageExtraction(extraction: PageExtraction): string {
338
+ if ("error" in extraction) return `Extraction failed: ${extraction.error}\n`;
339
+ const lines = Object.entries(extraction.fields).map(([name, result]) => {
340
+ const from = result.status !== "null" && result.line ? ` from "${result.line}"` : "";
341
+ if (result.status === "extracted") return `${name}: ${shown(result.value)} (${result.confidence.toFixed(2)})${from}`;
342
+ if (result.status === "uncertain") return `${name}: uncertain (guess ${shown(result.guess)}${result.confidence !== undefined ? `, ${result.confidence.toFixed(2)}` : ""}${result.notFound ? "; not found on the page" : ""})${from}`;
343
+ return `${name}: not on the page`;
344
+ });
345
+ if (extraction.cut) lines.push(`(Only the first part of the page was read; it is longer than the model accepts.)`);
346
+ return `${lines.join("\n")}\n`;
347
+ }
@@ -1,11 +1,14 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { awaitWithAbort } from "./abortable.ts";
3
4
  import { activityMonitor } from "./activity.ts";
4
5
  import { CredentialResolutionError } from "./credential-source.ts";
5
6
  import { getApiKey, getVersionedApiBase, fetchGeminiApi, isGatewayConfigured, isGeminiApiAvailable, redactGeminiApiResponse } from "./gemini-api.ts";
6
7
  import { isGeminiAdcAvailable } from "./gemini-adc.ts";
7
8
  import { getGeminiWebAvailabilityDiagnostic, isGeminiWebAvailable, queryWithCookies } from "./gemini-web.ts";
8
9
  import { isPerplexityAvailable, searchWithPerplexity, type SearchResult, type SearchResponse, type SearchOptions } from "./perplexity.ts";
10
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
11
+ import { judgeOffTopic, OFFTOPIC_JUDGE_MODELS, type OffTopicJudgeModel } from "./offtopic-judge.ts";
9
12
  import { isExaAvailable, searchWithExa } from "./exa.ts";
10
13
  import { isBraveAvailable, searchWithBrave } from "./brave.ts";
11
14
  import {
@@ -47,12 +50,13 @@ import { isValyuAvailable, searchWithValyu } from "./valyu.ts";
47
50
  import { isKeenableAvailable, searchWithKeenable } from "./keenable.ts";
48
51
  import { isCeramicAvailable, searchWithCeramic } from "./ceramic.ts";
49
52
  import { isLinkupAvailable, searchWithLinkup } from "./linkup.ts";
53
+ import { isNineRouterAvailable, searchWithNineRouter } from "./ninerouter.ts";
50
54
  import { isDeepSeekAvailable, searchWithDeepSeek } from "./deepseek.ts";
51
55
  import { isKimiSearchAvailable, searchWithKimi } from "./kimi-search.ts";
52
56
  import { isMistralAvailable, searchWithMistral } from "./mistral-search.ts";
53
57
  import { getWebSearchConfigPath } from "./utils.ts";
54
58
 
55
- export const 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"] as const;
59
+ export const RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "serpdive", "kagi", "ollama", "anysearch", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "bocha", "xcrawl", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup", "ninerouter"] as const;
56
60
  export const SEARCH_PROVIDERS = ["auto", "all", ...RESOLVED_SEARCH_PROVIDERS] as const;
57
61
 
58
62
  export type ResolvedSearchProvider = typeof RESOLVED_SEARCH_PROVIDERS[number];
@@ -75,7 +79,11 @@ export type SearchProviderErrorKind =
75
79
  export interface SearchRoutingConfig {
76
80
  providers: ResolvedSearchProvider[];
77
81
  useCurrentModel?: boolean;
78
- fallbackOn: Array<Extract<SearchProviderErrorKind, "transient" | "quota" | "network" | "invalid-response" | "unsupported">>;
82
+ fallbackOn: Array<typeof VALID_ROUTING_KINDS[number]>;
83
+ /** Total budget for one routed search across every candidate, in milliseconds. */
84
+ timeoutMs?: number;
85
+ /** Classifier that judges the "off-topic" fallback; required when fallbackOn lists it. */
86
+ offTopicModel?: OffTopicJudgeModel;
79
87
  }
80
88
 
81
89
  export class SearchProviderError extends Error {
@@ -117,10 +125,11 @@ export interface AttributedSearchResponse extends SearchResponse {
117
125
 
118
126
  const CONFIG_PATH = getWebSearchConfigPath();
119
127
  const DEFAULT_SEARCH_MODEL = "gemini-3.6-flash";
120
- // Explicit-only providers (Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, XCrawl, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, Keenable, Ceramic, DeepSeek, Linkup) are deliberately absent:
128
+ // Explicit-only providers (Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, XCrawl, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, Keenable, Ceramic, DeepSeek, Linkup, 9router) are deliberately absent:
121
129
  // `all` must never fan out to an opt-in or paid provider without the user asking for it.
122
130
  export const ALL_SEARCH_PROVIDERS: ResolvedSearchProvider[] = ["searxng", "openai", "exa", "brave", "parallel", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "serpdive", "kagi", "ollama", "perplexity", "gemini", "bocha"];
123
- const VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported"] as const;
131
+ const VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported", "empty", "domain-miss", "off-topic"] as const;
132
+ const MAX_ROUTING_TIMEOUT_MS = 600_000;
124
133
 
125
134
  type SearchConfig = {
126
135
  searchProvider: SearchProviderSelection;
@@ -198,16 +207,29 @@ function normalizeSearchRouting(value: unknown): SearchRoutingConfig {
198
207
  const fallbackOn: SearchRoutingConfig["fallbackOn"] = [];
199
208
  for (const kind of raw.fallbackOn) {
200
209
  if (typeof kind !== "string" || !VALID_ROUTING_KINDS.includes(kind as typeof VALID_ROUTING_KINDS[number])) {
201
- throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} may only contain transient, quota, network, invalid-response, or unsupported`);
210
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} may only contain transient, quota, network, invalid-response, unsupported, empty, domain-miss, or off-topic`);
202
211
  }
203
212
  if (!fallbackOn.includes(kind as SearchRoutingConfig["fallbackOn"][number])) {
204
213
  fallbackOn.push(kind as SearchRoutingConfig["fallbackOn"][number]);
205
214
  }
206
215
  }
216
+ const timeoutMs = raw.timeoutMs;
217
+ if (timeoutMs !== undefined && (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_ROUTING_TIMEOUT_MS)) {
218
+ throw new Error(`searchRouting.timeoutMs in ${CONFIG_PATH} must be an integer from 1 through ${MAX_ROUTING_TIMEOUT_MS}`);
219
+ }
220
+ const offTopicModel = raw.offTopicModel;
221
+ if (offTopicModel !== undefined && (typeof offTopicModel !== "string" || !Object.hasOwn(OFFTOPIC_JUDGE_MODELS, offTopicModel))) {
222
+ throw new Error(`searchRouting.offTopicModel in ${CONFIG_PATH} must be one of ${Object.keys(OFFTOPIC_JUDGE_MODELS).join(", ")}`);
223
+ }
224
+ if (fallbackOn.includes("off-topic") && offTopicModel === undefined) {
225
+ throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} lists off-topic, which needs searchRouting.offTopicModel`);
226
+ }
207
227
  return {
208
228
  providers,
209
229
  ...(useCurrentModel !== undefined ? { useCurrentModel: useCurrentModel as boolean } : {}),
210
230
  fallbackOn,
231
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
232
+ ...(offTopicModel !== undefined ? { offTopicModel: offTopicModel as OffTopicJudgeModel } : {}),
211
233
  };
212
234
  }
213
235
 
@@ -265,6 +287,55 @@ export function normalizeSearchProviderSelection(value: unknown, label = "provid
265
287
  return SEARCH_PROVIDERS.includes(normalized as SearchProvider) ? normalized as SearchProvider : "auto";
266
288
  }
267
289
 
290
+ /** Strict parser for tool-call `provider` arguments; config values keep the lenient normalizer. */
291
+ export function parseProviderArgument(value: unknown): SearchProviderSelection | undefined {
292
+ if (value === undefined) return undefined;
293
+ if (Array.isArray(value)) return normalizeResolvedProviderList(value, "provider");
294
+ const unknown = (name: string) => new Error(`Unknown search provider "${name}". Use auto, all, or one or more comma-separated names: ${getAllowedSearchProviders().join(", ")}`);
295
+ if (typeof value !== "string") throw unknown(String(value));
296
+ const normalized = value.trim().toLowerCase();
297
+ if (normalized === "") return undefined;
298
+ let names: string[];
299
+ if (normalized.startsWith("[")) {
300
+ let parsed: unknown[];
301
+ try {
302
+ parsed = JSON.parse(normalized);
303
+ } catch {
304
+ throw new Error("provider must be a provider name or comma-separated names; the given value is not valid JSON");
305
+ }
306
+ names = parsed.map(entry => String(entry).trim());
307
+ } else {
308
+ names = normalized.split(",").map(name => name.trim()).filter(Boolean);
309
+ if (names.length < 2) {
310
+ if (!SEARCH_PROVIDERS.includes(names[0] as SearchProvider)) throw unknown(names[0] ?? value);
311
+ return names[0] as SearchProvider;
312
+ }
313
+ }
314
+ if (names.some(name => name === "auto" || name === "all")) {
315
+ throw new Error('"auto" and "all" cannot be combined with provider names');
316
+ }
317
+ const invalid = names.find(name => !RESOLVED_SEARCH_PROVIDERS.includes(name as ResolvedSearchProvider));
318
+ if (invalid !== undefined) throw unknown(invalid);
319
+ return normalizeResolvedProviderList(names, "provider");
320
+ }
321
+
322
+ /** Validate the original arguments, before config can supply an implicit provider. */
323
+ export function validateSearchModelOverride(provider: unknown, model: unknown): string | undefined {
324
+ if (model === undefined) return undefined;
325
+ if (typeof model !== "string" || !model.trim()) {
326
+ throw new Error("model must be a non-empty model ID");
327
+ }
328
+ const selected = parseProviderArgument(provider);
329
+ if (selected === undefined || Array.isArray(selected) || selected === "auto" || selected === "all") {
330
+ throw new Error("model requires one explicit provider: openai, xai, mistral, or gemini (API only); omitted, auto, all, and provider lists are ambiguous");
331
+ }
332
+ if (!["openai", "xai", "mistral", "gemini"].includes(selected)) {
333
+ throw new Error(`model is not supported for provider ${JSON.stringify(selected)}; use openai, xai, mistral, or gemini (API only)`);
334
+ }
335
+ assertSearchProviderSelectionAllowed(selected, "Requested provider");
336
+ return model.trim();
337
+ }
338
+
268
339
  export interface FullSearchOptions extends SearchOptions {
269
340
  provider?: SearchProviderSelection;
270
341
  /** The caller already substituted the configured default for an omitted or "auto" provider. */
@@ -303,6 +374,12 @@ async function searchWithGemini(
303
374
  options: SearchOptions,
304
375
  strictErrors: boolean,
305
376
  ): Promise<SearchResponse | null> {
377
+ // Gemini Web cannot honor an explicit model, so never fall back to it.
378
+ if (options.model !== undefined) {
379
+ const result = await searchWithGeminiApi(query, options);
380
+ if (result) return result;
381
+ throw new Error("Gemini API search unavailable: an explicit model requires API-path authentication (API key, ADC, or gateway), not browser cookies");
382
+ }
306
383
  const errors: string[] = [];
307
384
 
308
385
  try {
@@ -433,6 +510,7 @@ async function searchWithResolvedProvider(
433
510
  if (provider === "keenable") return { ...(await searchWithKeenable(query, options)), provider };
434
511
  if (provider === "ceramic") return { ...(await searchWithCeramic(query, options)), provider };
435
512
  if (provider === "linkup") return { ...(await searchWithLinkup(query, options)), provider };
513
+ if (provider === "ninerouter") return { ...(await searchWithNineRouter(query, options)), provider };
436
514
  if (provider === "deepseek") return { ...(await searchWithDeepSeek(query, options)), provider };
437
515
  if (provider === "xcrawl") return { ...(await searchWithXCrawl(query, options)), provider };
438
516
  if (provider === "perplexity") return { ...(await searchWithPerplexity(query, options)), provider };
@@ -491,6 +569,7 @@ async function isResolvedProviderAvailable(provider: ResolvedSearchProvider, opt
491
569
  if (provider === "keenable") return isKeenableAvailable();
492
570
  if (provider === "ceramic") return isCeramicAvailable();
493
571
  if (provider === "linkup") return isLinkupAvailable();
572
+ if (provider === "ninerouter") return isNineRouterAvailable();
494
573
  if (provider === "deepseek") return isDeepSeekAvailable();
495
574
  if (provider === "xcrawl") return isXcrawlAvailable();
496
575
  if (provider === "perplexity") return isPerplexityAvailable();
@@ -541,6 +620,7 @@ export function providerLabel(provider: ResolvedSearchProvider): string {
541
620
  if (provider === "keenable") return "Keenable";
542
621
  if (provider === "ceramic") return "Ceramic";
543
622
  if (provider === "linkup") return "Linkup";
623
+ if (provider === "ninerouter") return "9router";
544
624
  if (provider === "deepseek") return "DeepSeek";
545
625
  return provider.charAt(0).toUpperCase() + provider.slice(1);
546
626
  }
@@ -570,7 +650,7 @@ async function searchWithProviders(
570
650
  : await isResolvedProviderAvailable(provider, options),
571
651
  })))).filter((entry) => entry.available).map((entry) => entry.provider);
572
652
  if (providers.length === 0) {
573
- 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.");
653
+ throw new Error("No configured search provider available for provider \"all\". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, XCrawl, Keenable, Ceramic, DeepSeek, Linkup, and 9router are excluded.");
574
654
  }
575
655
 
576
656
  const settled = await Promise.allSettled(
@@ -644,21 +724,74 @@ async function searchWithProviders(
644
724
  };
645
725
  }
646
726
 
727
+ /** A successful response a route may still move past: no results and no answer (`empty`), or no result on a requested domain (`domain-miss`). */
728
+ function weakResult(response: SearchResponse, domainFilter: string[] | undefined): { empty: boolean; domainMiss: boolean } {
729
+ const empty = response.results.length === 0 && !response.answer.trim();
730
+ const wanted = (domainFilter ?? [])
731
+ .filter((domain) => !domain.trim().startsWith("-"))
732
+ .flatMap((domain) => normalizeDomain(domain) ?? []);
733
+ const domainMiss = wanted.length > 0 && !response.results.some((result) => {
734
+ const host = URL.parse(result.url)?.hostname;
735
+ return host !== undefined && wanted.some((domain) => host === domain || host.endsWith(`.${domain}`));
736
+ });
737
+ return { empty, domainMiss };
738
+ }
739
+
647
740
  async function searchWithConfiguredRouting(
648
741
  query: string,
649
- options: FullSearchOptions,
742
+ callerOptions: FullSearchOptions,
650
743
  routing: SearchRoutingConfig,
651
744
  ): Promise<AttributedSearchResponse> {
745
+ const deadline = routing.timeoutMs ? AbortSignal.timeout(routing.timeoutMs) : undefined;
746
+ const signal = deadline && (callerOptions.signal ? AbortSignal.any([callerOptions.signal, deadline]) : deadline);
747
+ const options: FullSearchOptions = signal ? { ...callerOptions, signal } : callerOptions;
748
+ const timedOut = () => deadline?.aborted === true && callerOptions.signal?.aborted !== true;
749
+ // Availability checks, Pi auth, and cookie scans ignore the signal, so race each step against it (caller abort or deadline); abandoned work finishes in the background and is ignored.
750
+ const untilDeadline = <T>(work: Promise<T>): Promise<T> => awaitWithAbort(work, signal);
652
751
  const diagnostics: string[] = [];
752
+ let firstWeak: AttributedSearchResponse | undefined;
653
753
  for (const provider of routing.providers) {
754
+ if (timedOut()) {
755
+ diagnostics.push(`routing timeout after ${routing.timeoutMs}ms`);
756
+ break;
757
+ }
654
758
  const useCurrentModel = provider === "openai" && routing.useCurrentModel === true;
655
- if (!(await isResolvedProviderAvailable(provider, options, useCurrentModel))) {
759
+ const available = await untilDeadline(isResolvedProviderAvailable(provider, options, useCurrentModel)).catch((err) => {
760
+ if (timedOut()) return undefined;
761
+ throw err;
762
+ });
763
+ if (available === undefined) {
764
+ diagnostics.push(`${provider}: routing timeout after ${routing.timeoutMs}ms`);
765
+ break;
766
+ }
767
+ if (!available) {
656
768
  diagnostics.push(`${provider}: unavailable`);
657
769
  continue;
658
770
  }
659
771
  try {
660
- return await searchWithResolvedProvider(provider, query, options, useCurrentModel);
772
+ const response = await untilDeadline(searchWithResolvedProvider(provider, query, options, useCurrentModel));
773
+ const weak = weakResult(response, options.domainFilter);
774
+ let kind = weak.empty && routing.fallbackOn.includes("empty") ? "empty" : weak.domainMiss && routing.fallbackOn.includes("domain-miss") ? "domain-miss" : undefined;
775
+ // Over MCP there is no Pi model registry, so the off-topic check is inactive there.
776
+ const registry = options.extensionContext?.modelRegistry;
777
+ if (!kind && !weak.empty && routing.offTopicModel && routing.fallbackOn.includes("off-topic") && registry) {
778
+ // A deadline during the check keeps the response: it is still a success.
779
+ const judgment = await untilDeadline(judgeOffTopic(routing.offTopicModel, query, response, registry, options.signal))
780
+ .catch((err) => { if (timedOut()) return { error: `routing timeout after ${routing.timeoutMs}ms` }; throw err; });
781
+ if ("error" in judgment) {
782
+ const line = `${provider}: off-topic check failed: ${judgment.error}`;
783
+ diagnostics.push(line);
784
+ activityMonitor.logError(activityMonitor.logStart({ type: "api", query }), line);
785
+ } else if (judgment.probabilities.off_topic >= OFFTOPIC_JUDGE_MODELS[routing.offTopicModel]) kind = "off-topic";
786
+ }
787
+ if (!kind) return response;
788
+ diagnostics.push(`${provider} [${kind}]`);
789
+ firstWeak ??= response;
661
790
  } catch (err) {
791
+ if (timedOut()) {
792
+ diagnostics.push(`${provider}: routing timeout after ${routing.timeoutMs}ms`);
793
+ break;
794
+ }
662
795
  const classified = classifyProviderError(provider, err);
663
796
  diagnostics.push(`${provider} [${classified.kind}]: ${errorMessage(err)}`);
664
797
  if (!routing.fallbackOn.includes(classified.kind as SearchRoutingConfig["fallbackOn"][number])) {
@@ -666,6 +799,8 @@ async function searchWithConfiguredRouting(
666
799
  }
667
800
  }
668
801
  }
802
+ // Like the built-in auto chain, hand back the first weak response rather than an error.
803
+ if (firstWeak) return firstWeak;
669
804
  throw new Error(`Configured search routing exhausted:\n - ${diagnostics.join("\n - ")}`);
670
805
  }
671
806
 
@@ -759,7 +894,7 @@ export async function search(query: string, options: FullSearchOptions = {}): Pr
759
894
  " 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\n" +
760
895
  " 4. Set GOOGLE_GEMINI_BASE_URL with CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing\n" +
761
896
  " 5. Sign into gemini.google.com in a supported Chromium-based browser\n" +
762
- " 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"
897
+ " 6. Explicitly select provider: \"anysearch\" for anonymous AnySearch, \"xcrawl\" for XCrawl, \"xai\" for Grok, \"mistral\" for Mistral Conversations web search, \"brightdata\" with brightdataSerpZone for paid Bright Data SERP, \"serpbase\", \"serpapi\", \"serper\", or \"serply\" for Google SERP, \"you\" for You.com, \"zai\" for Z.ai GLM Coding Plan search, \"valyu\" for research search, \"keenable\" for keyless Keenable search, \"ceramic\" for Ceramic search, \"deepseek\" for DeepSeek search, \"linkup\" for Linkup search, or \"ninerouter\" for a 9router gateway"
763
898
  );
764
899
  }
765
900
 
@@ -774,13 +909,13 @@ async function searchWithGeminiApi(query: string, options: SearchOptions = {}):
774
909
  const activityId = activityMonitor.logStart({ type: "api", query });
775
910
 
776
911
  try {
777
- const model = getSearchConfig().searchModel ?? DEFAULT_SEARCH_MODEL;
912
+ const model = options.model ?? getSearchConfig().searchModel ?? DEFAULT_SEARCH_MODEL;
778
913
  const body = {
779
914
  contents: [{ role: "user", parts: [{ text: query }] }],
780
915
  tools: [{ google_search: {} }],
781
916
  };
782
917
 
783
- const res = await fetchGeminiApi(`${getVersionedApiBase()}/models/${model}:generateContent`, {
918
+ const res = await fetchGeminiApi(`${getVersionedApiBase()}/models/${options.model !== undefined ? encodeURIComponent(model) : model}:generateContent`, {
784
919
  method: "POST",
785
920
  headers: { "Content-Type": "application/json" },
786
921
  body: JSON.stringify(body),
@@ -801,7 +936,10 @@ async function searchWithGeminiApi(query: string, options: SearchOptions = {}):
801
936
  const metadata = data.candidates?.[0]?.groundingMetadata;
802
937
  const results = await resolveGroundingChunks(metadata?.groundingChunks, options.signal);
803
938
 
804
- if (!answer && results.length === 0) return null;
939
+ if (!answer && results.length === 0) {
940
+ if (options.model !== undefined) throw new Error("Gemini API returned no answer or sources");
941
+ return null;
942
+ }
805
943
  return { answer, results };
806
944
  } catch (err) {
807
945
  const message = err instanceof Error ? err.message : String(err);