@jshookmcp/jshook 0.3.1 → 0.3.3

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 (249) hide show
  1. package/LICENSE +661 -661
  2. package/README.md +11 -3
  3. package/README.zh.md +11 -3
  4. package/dist/{AntiCheatDetector-CGVGNfy5.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
  5. package/dist/BrowserSessionCoordinator-QIt3tetp.mjs +1 -0
  6. package/dist/CodeInjector-Btj9upnf.mjs +1 -0
  7. package/dist/ConsoleMonitor-DIjN5Afa.mjs +306 -0
  8. package/dist/{DarwinAPI-DC4HGGLl.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
  9. package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
  10. package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
  11. package/dist/{FingerprintManager-N7BZqjxP.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
  12. package/dist/{HardwareBreakpoint-OcJqNFVc.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
  13. package/dist/{HeapAnalyzer-CqAxZzeS.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
  14. package/dist/MCPServer.activation.ttl-CEGNBycZ.mjs +1 -0
  15. package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
  16. package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
  17. package/dist/MemoryController-DjtgiING.mjs +2 -0
  18. package/dist/{MemoryScanSession-CaxAjZJf.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
  19. package/dist/MemoryScanner-Dxd657li.mjs +1 -0
  20. package/dist/{NativeMemoryManager.utils-DM4NC3FE.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
  21. package/dist/{PEAnalyzer-DJyaJTQJ.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
  22. package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
  23. package/dist/ProcessRegistry-D5y1yuP2.mjs +1 -0
  24. package/dist/{ResponseBuilder-B2lu4KEl.mjs → ResponseBuilder-nPXl_khE.mjs} +1 -1
  25. package/dist/{ReverseEvidenceGraph-B931HeoW.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
  26. package/dist/RingBuffer-B6RTHmij.mjs +1 -0
  27. package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
  28. package/dist/{Speedhack-l6s8L2Qw.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
  29. package/dist/{StructureAnalyzer-A-WamfYE.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
  30. package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
  31. package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
  32. package/dist/ToolProbe-DQiREmNp.mjs +1 -0
  33. package/dist/ToolRegistry-eMZEBiR1.mjs +1 -0
  34. package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
  35. package/dist/{TraceRecorder-Dd8jLXpi.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
  36. package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
  37. package/dist/{Win32API-Bhi5xFBe.mjs → Win32API-DoP3MMHS.mjs} +1 -1
  38. package/dist/{Win32Debug-CQteFL4F.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
  39. package/dist/{WorkflowEngine-CxEp2WXH.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
  40. package/dist/analysis-C-ln0Brh.mjs +6 -0
  41. package/dist/antidebug-CsnpOR9z.mjs +1 -0
  42. package/dist/{artifactRetention-NBdncOEW.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
  43. package/dist/{artifacts-B5xQuEa_.mjs → artifacts-D-4pSS_N.mjs} +1 -1
  44. package/dist/betterSqlite3-Bdo_ifuJ.mjs +1 -0
  45. package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
  46. package/dist/{boringssl-inspector-BST5vtKx.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
  47. package/dist/browser-BUaB25bk.mjs +11 -0
  48. package/dist/{handlers-pVNpaw4A.mjs → canvas-396ieNv5.mjs} +22 -22
  49. package/dist/collector-CB2syQEg.mjs +1 -0
  50. package/dist/constants-DMv3svps.mjs +2 -0
  51. package/dist/coordination-Dbohmj6D.mjs +1 -0
  52. package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
  53. package/dist/debugger-CLzkObIO.mjs +1 -0
  54. package/dist/{definitions-CCP9gphV.mjs → definitions-0hxnrDU72.mjs} +1 -1
  55. package/dist/definitions-B3a9QC2t.mjs +1 -0
  56. package/dist/{definitions-DtE0XLrT.mjs → definitions-BOvju5t2.mjs} +1 -1
  57. package/dist/definitions-CXj_cEVt.mjs +1 -0
  58. package/dist/definitions-Co6AvTjH.mjs +1 -0
  59. package/dist/{definitions-Dds_zrWx.mjs → definitions-Cv5r8xwq.mjs} +1 -1
  60. package/dist/definitions-DBYSxChX.mjs +1 -0
  61. package/dist/{definitions-DI9YXsJk.mjs → definitions-D_dTDX9B.mjs} +1 -1
  62. package/dist/{definitions-Dgrg7f3D.mjs → definitions-Db9t2ddh.mjs} +1 -1
  63. package/dist/{definitions-DZ8uKusP.mjs → definitions-DbN2CjI2.mjs} +1 -1
  64. package/dist/{definitions-jXPaVy4P.mjs → definitions-DlmmHmZc.mjs} +1 -1
  65. package/dist/definitions-DnYpoGig.mjs +1 -0
  66. package/dist/{definitions-CYFbewnd.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
  67. package/dist/{definitions-CuJRsJ6N.mjs → definitions-DuIPS8gq.mjs} +1 -1
  68. package/dist/{definitions-BbxOUiP-.mjs → definitions-DywfwPMb.mjs} +1 -1
  69. package/dist/definitions-EGmqr85H.mjs +1 -0
  70. package/dist/{definitions-LaYTuwQd.mjs → definitions-Fetw_Cge.mjs} +3 -3
  71. package/dist/{definitions-NoVp_9Pm.mjs → definitions-LdkeuOeA.mjs} +1 -1
  72. package/dist/{definitions-DJklW2sS.mjs → definitions-Ym8niHDb.mjs} +1 -1
  73. package/dist/{definitions-BGwNSkVm.mjs → definitions-aeRd5DAR.mjs} +1 -1
  74. package/dist/{definitions-CIO9O-Sw.mjs → definitions-cnG6tj17.mjs} +1 -1
  75. package/dist/{encoding-DGcr6Aj_.mjs → encoding-B4xZWErf.mjs} +2 -2
  76. package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
  77. package/dist/{factory-Cx_1LorX.mjs → factory-BxNdBiZa.mjs} +1 -1
  78. package/dist/{graphql-HLf3MS8H.mjs → graphql-GBWsZ9xC.mjs} +4 -4
  79. package/dist/{handlers-DW5AbYs5.mjs → handlers-5nzR8B0a.mjs} +3 -3
  80. package/dist/handlers-6iNsXOVT.mjs +7 -0
  81. package/dist/{handlers-BZoPla6E.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
  82. package/dist/{handlers-Dv_runVv.mjs → handlers-BbLxNbbT.mjs} +1 -1
  83. package/dist/{handlers-BP12ZsWc.mjs → handlers-BbS4hssc.mjs} +2 -2
  84. package/dist/{handlers-BggKiVx9.mjs → handlers-CIKOP4aI.mjs} +2 -2
  85. package/dist/handlers-CWKBBjai.mjs +1 -0
  86. package/dist/handlers-Cmb6SoRC.mjs +1 -0
  87. package/dist/handlers-CrJsKnEI.mjs +1 -0
  88. package/dist/{antidebug-BOTZH6-0.mjs → handlers-DB6xVVWq.mjs} +4 -4
  89. package/dist/{handlers-DmQzIc44.mjs → handlers-DOOCWUNR.mjs} +3 -3
  90. package/dist/{handlers-BLMa4X7l.mjs → handlers-Z_B5aVaU.mjs} +2 -2
  91. package/dist/handlers-gVscChvl.mjs +1 -0
  92. package/dist/handlers-xFvI9P_y.mjs +1 -0
  93. package/dist/handlers.impl-BsFTW6SD.mjs +1 -0
  94. package/dist/{hooks-DDKppogd.mjs → hooks-DPouiS7I.mjs} +9 -9
  95. package/dist/index.mjs +11 -15
  96. package/dist/macro-p8kuJVcm.mjs +2 -0
  97. package/dist/maintenance-DAqADb6Z.mjs +302 -0
  98. package/dist/manifest-4lmM6MZR.mjs +1 -0
  99. package/dist/{manifest-D610kxZr.mjs → manifest-AxaxRSt6.mjs} +2 -2
  100. package/dist/{manifest-CDeUZGUZ.mjs → manifest-BIqRE1Qz.mjs} +1 -1
  101. package/dist/{manifest-Dm0o3i2U.mjs → manifest-Box-jWfr.mjs} +1 -1
  102. package/dist/manifest-Bp33di0Q.mjs +1 -0
  103. package/dist/{manifest-CGq4NpqH2.mjs → manifest-BvRX4nRP.mjs} +1 -1
  104. package/dist/{manifest-yu2xiQqe.mjs → manifest-C6KoB1XE.mjs} +1 -1
  105. package/dist/manifest-C7TdXCWY.mjs +1 -0
  106. package/dist/manifest-CM-n64K0.mjs +1 -0
  107. package/dist/{manifest-DWUUWBz0.mjs → manifest-CUokxCUN.mjs} +1 -1
  108. package/dist/manifest-CWJS45iO.mjs +1 -0
  109. package/dist/{manifest-D44TaRJU.mjs → manifest-Cdxdgo-D.mjs} +1 -1
  110. package/dist/{manifest-DKUorv5M.mjs → manifest-Cf6SmamD.mjs} +1 -1
  111. package/dist/manifest-Cgxu2qdv.mjs +1 -0
  112. package/dist/manifest-CowGSURa2.mjs +1 -0
  113. package/dist/manifest-CsGIrh34.mjs +1 -0
  114. package/dist/manifest-CvDpVToN.mjs +1 -0
  115. package/dist/manifest-D8TL9RLE.mjs +1 -0
  116. package/dist/{manifest-C7qV1z7F.mjs → manifest-DIhtCBe6.mjs} +1 -1
  117. package/dist/{manifest-CeQmtQOY.mjs → manifest-DJbruNOg.mjs} +1 -1
  118. package/dist/manifest-DLGtZH-0.mjs +1 -0
  119. package/dist/manifest-DXHdPt2T.mjs +1 -0
  120. package/dist/{manifest-DMJlcsTR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
  121. package/dist/{manifest-C1nZkTkO.mjs → manifest-DzGoTS0R.mjs} +1 -1
  122. package/dist/manifest-G2H52LKz.mjs +131 -0
  123. package/dist/manifest-P0Futrgb.mjs +1 -0
  124. package/dist/{manifest-CDiCtaQT.mjs → manifest-Qw7xgvjv.mjs} +1 -1
  125. package/dist/{manifest-Dgh0uDW-.mjs → manifest-W3qvVrP2.mjs} +1 -1
  126. package/dist/manifest-dG6MuR1U.mjs +1 -0
  127. package/dist/manifest-nWXtgq5Y2.mjs +1 -0
  128. package/dist/{manifest-BPuE6oH2.mjs → manifest-vp1upSSq.mjs} +1 -1
  129. package/dist/modules-DO3jXCgj.mjs +333 -0
  130. package/dist/{mojo-ipc-VGlv3Qyp.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
  131. package/dist/native/scripts/linux/enum-windows.sh +12 -12
  132. package/dist/native/scripts/macos/enum-windows.applescript +22 -22
  133. package/dist/native-g095qhpK.mjs +961 -0
  134. package/dist/network-Dvxm7eEI.mjs +7 -0
  135. package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
  136. package/dist/{parse-args-Cuk7-xUt.mjs → parse-args-ngRrvF9e.mjs} +1 -1
  137. package/dist/platform-DjWbuiF8.mjs +93 -0
  138. package/dist/process-Dq5I-KZW.mjs +2 -0
  139. package/dist/proxy-DPNgM7TE.mjs +2 -0
  140. package/dist/{registry-DUHIPE-v.mjs → registry-xB8Wgmyj.mjs} +1 -1
  141. package/dist/renderer-pid-7jbTR8f5.mjs +1 -0
  142. package/dist/search-defaults-CJik67or.mjs +1 -0
  143. package/dist/server/plugin-api.d.mts +19 -36
  144. package/dist/server/plugin-api.mjs +1 -1
  145. package/dist/sourcemap-DqEW15Ao.mjs +1 -0
  146. package/dist/streaming-Dbk4eStJ.mjs +1 -0
  147. package/dist/transform-D-peM3aO.mjs +103 -0
  148. package/dist/wasm-CZajRaad.mjs +174 -0
  149. package/dist/{webcrack-CsLLJIs9.mjs → webcrack-phEfVt5y.mjs} +3 -3
  150. package/dist/{workflow-CYIXtrWD.mjs → workflow-wkXb3x-U.mjs} +4 -4
  151. package/package.json +16 -15
  152. package/src/native/scripts/linux/enum-windows.sh +12 -12
  153. package/src/native/scripts/macos/enum-windows.applescript +22 -22
  154. package/dist/CodeInjector-BlgyqTOk.mjs +0 -1
  155. package/dist/ConsoleMonitor-Dkqc0HNi.mjs +0 -490
  156. package/dist/DOMInspector-BYY_EJ0C.mjs +0 -95
  157. package/dist/DetailedDataManager-BniBJlVv.mjs +0 -1
  158. package/dist/ExtensionManager-erMpqcLk.mjs +0 -1
  159. package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +0 -1
  160. package/dist/MemoryController-BaqstM5w.mjs +0 -2
  161. package/dist/MemoryScanner-BLYnMJy6.mjs +0 -1
  162. package/dist/NativeMemoryManager.impl-CI554XbY.mjs +0 -1
  163. package/dist/PageController-D9jVkH0i.mjs +0 -1
  164. package/dist/PointerChainEngine-5nF9eNlu.mjs +0 -1
  165. package/dist/PrerequisiteError-Bl3dK8XA.mjs +0 -1
  166. package/dist/ProcessRegistry-Hf12LlR9.mjs +0 -1
  167. package/dist/ScriptManager-fgqiALgj.mjs +0 -7
  168. package/dist/ToolCatalog-D_IKl1Hu.mjs +0 -1
  169. package/dist/ToolProbe-xsfALmN3.mjs +0 -1
  170. package/dist/ToolRegistry-B0Zs-phN.mjs +0 -1
  171. package/dist/ToolRouter.policy-CFHoN_Lw.mjs +0 -4
  172. package/dist/VersionDetector-DMoUWyNm.mjs +0 -9
  173. package/dist/analysis-BuR-NgX8.mjs +0 -5
  174. package/dist/betterSqlite3-CGaxz4AX.mjs +0 -1
  175. package/dist/binary-instrument-Cf9qqLlM.mjs +0 -7
  176. package/dist/browser-C4Le3xqA.mjs +0 -11
  177. package/dist/collector-CKO8RPK8.mjs +0 -1
  178. package/dist/constants-Cp6hBrrx.mjs +0 -1
  179. package/dist/coordination-BbijHEHH.mjs +0 -1
  180. package/dist/debugger-CRJq_krh.mjs +0 -1
  181. package/dist/definitions-BGobEDQa.mjs +0 -1
  182. package/dist/definitions-CdWEuIkI.mjs +0 -1
  183. package/dist/definitions-CoQFbggH.mjs +0 -1
  184. package/dist/definitions-OvGsfxdt.mjs +0 -1
  185. package/dist/ensure-browser-core-Buls24LQ.mjs +0 -1
  186. package/dist/flat-target-session-CO5g78k3.mjs +0 -1
  187. package/dist/handlers-D3iev8g1.mjs +0 -1
  188. package/dist/handlers-D49r1-1P.mjs +0 -1
  189. package/dist/handlers-DCE45Ww8.mjs +0 -2
  190. package/dist/handlers-De5u62Ga2.mjs +0 -1
  191. package/dist/handlers-DnJRGp7t.mjs +0 -302
  192. package/dist/handlers-S9Ws0IGy.mjs +0 -2
  193. package/dist/handlers.impl-CD2_kOcC.mjs +0 -1
  194. package/dist/maintenance-CutEO84j.mjs +0 -1
  195. package/dist/manifest-BFGxlDRh.mjs +0 -123
  196. package/dist/manifest-BXry5N09.mjs +0 -1
  197. package/dist/manifest-BeP_zJGb2.mjs +0 -1
  198. package/dist/manifest-C0g67k6U.mjs +0 -1
  199. package/dist/manifest-CFn0359q2.mjs +0 -1
  200. package/dist/manifest-CJMGt7Qy.mjs +0 -1
  201. package/dist/manifest-CRIJq4Hs.mjs +0 -1
  202. package/dist/manifest-C_hEIjSx.mjs +0 -1
  203. package/dist/manifest-Cq0j7GZt.mjs +0 -1
  204. package/dist/manifest-CtPmHAdn.mjs +0 -1
  205. package/dist/manifest-Cx2IVMUY.mjs +0 -1
  206. package/dist/manifest-D16xPXro.mjs +0 -1
  207. package/dist/manifest-DC-SMF6b.mjs +0 -1
  208. package/dist/manifest-DD3rtxvV.mjs +0 -1
  209. package/dist/manifest-De-6Wf2R.mjs +0 -1
  210. package/dist/manifest-DsVh7Y4U.mjs +0 -1
  211. package/dist/manifest-DtEFSRaq.mjs +0 -1
  212. package/dist/manifest-H-EpAyZQ.mjs +0 -1
  213. package/dist/manifest-ais9Afrw.mjs +0 -1
  214. package/dist/manifest-tmb54wmA.mjs +0 -1
  215. package/dist/manifest-zrbrpKCC.mjs +0 -1
  216. package/dist/matchesWildcardPattern-BGqLSmEs.mjs +0 -1
  217. package/dist/modules-p-PUNv9r.mjs +0 -332
  218. package/dist/network-BjZ1Y-GB.mjs +0 -7
  219. package/dist/outputPaths-BonGThuc.mjs +0 -2
  220. package/dist/platform-C446Lf97.mjs +0 -93
  221. package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +0 -1
  222. package/dist/process-C9f2A5zk.mjs +0 -962
  223. package/dist/proxy-CvRepxgV.mjs +0 -1
  224. package/dist/search-defaults-D2bY-rzH.mjs +0 -1
  225. package/dist/shared-state-board-Cyg-xh_k.mjs +0 -1
  226. package/dist/sourcemap-D6Q1UuAp.mjs +0 -1
  227. package/dist/streaming-CTX58tbb.mjs +0 -1
  228. package/dist/transform-Cv9P2vVD.mjs +0 -103
  229. package/dist/types-DtThH00r.mjs +0 -1
  230. package/dist/wasm-DaJa8J0V.mjs +0 -174
  231. /package/dist/{CacheAdapters-CdAxBmVW.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
  232. /package/dist/{EventBus-DgciURGg.mjs → EventBus-Cm-t-B65.mjs} +0 -0
  233. /package/dist/{EvidenceGraphBridge-BIfgB7HP.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
  234. /package/dist/{HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
  235. /package/dist/{InstrumentationSession-DxXs0sCp.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
  236. /package/dist/{StealthVerifier-Dhbj4B4P.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
  237. /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
  238. /package/dist/{authorization-schema-B40obG1A.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
  239. /package/dist/{bind-helpers-BlAOQrFQ.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
  240. /package/dist/{capabilities-DbYCv-HF.mjs → capabilities-L1ax5EHS.mjs} +0 -0
  241. /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
  242. /package/dist/{concurrency-CcK46d0h.mjs → concurrency-Dehnw4JC.mjs} +0 -0
  243. /package/dist/{evidence-graph-bridge-B0yhGPcs.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
  244. /package/dist/{formatAddress-C7j2fDlM.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
  245. /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
  246. /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
  247. /package/dist/{ssrf-policy-T96MR3r6.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
  248. /package/dist/{tool-builder-CI9914Tf.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
  249. /package/dist/{types-CuyefmGT.mjs → types-BzPBzmVB.mjs} +0 -0
@@ -1,5 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{d as t,f as n,u as r}from"./constants-Cp6hBrrx.mjs";import{a as i,n as a,r as o,t as s}from"./response-C7rKQst4.mjs";import{a as c,i as l,n as u,r as d,s as f,t as p}from"./parse-args-Cuk7-xUt.mjs";import{s as m}from"./PageController-D9jVkH0i.mjs";import"./definitions-CuJRsJ6N.mjs";import{n as h,t as g}from"./webcrack-CsLLJIs9.mjs";import*as _ from"@babel/parser";import v from"@babel/traverse";import*as y from"@babel/types";import b from"@babel/generator";const x=new Set([`=`,`(`,`[`,`,`,`;`,`{`,`!`,`&`,`|`,`?`,`:`,`~`,`^`,`+`,`-`,`*`,`%`,`<`,`>`,`
2
- `]);function S(e){return new RegExp(e.source,e.flags)}function ee(e){if(e.length===0)return[];let t=[],n=e.toSorted((e,t)=>e.start-t.start||e.end-t.end);for(let e of n){let n=t[t.length-1];if(!n||e.start>n.end){t.push({...e});continue}n.end=Math.max(n.end,e.end)}return t}function C(e){try{let t=_.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),n=[],r=(e,t)=>{typeof e==`number`&&typeof t==`number`&&t>e&&n.push({start:e,end:t})},i=Array.isArray(t.comments)?t.comments:[];for(let e of i)r(e.start,e.end);return v(t,{StringLiteral(e){r(e.node.start,e.node.end),e.skip()},TemplateElement(e){r(e.node.start,e.node.end),e.skip()},RegExpLiteral(e){r(e.node.start,e.node.end),e.skip()}}),ee(n)}catch{return null}}function w(e){let t=e[e.length-2];if(typeof t==`number`)return t;let n=e[e.length-3];return typeof n==`number`?n:null}function T(e,t){let n=t-1;for(;n>=0&&(e[n]===` `||e[n]===` `||e[n]===`\r`);)n--;if(n<0)return!0;let r=e[n];if(x.has(r))return!0;if(r!==`)`)return!1;let i=1,a=n-1;for(;a>=0&&i>0;)e[a]===`)`&&i++,e[a]===`(`&&i--,a--;for(a--;a>=0&&(e[a]===` `||e[a]===` `);)a--;let o=``;for(;a>=0&&/[a-z]/.test(e[a]);)o=e[a]+o,a--;return[`if`,`while`,`for`,`switch`,`return`,`typeof`,`void`,`in`,`of`,`case`].includes(o)}function E(e,t){let n=null,r=!1,i=!1,a=!1;for(let o=0;o<t;o++){let s=e[o];if(r){s===`*`&&e[o+1]===`/`&&(r=!1,o++);continue}if(i){s===`
3
- `&&(i=!1);continue}if(a){if(s===`\\`){o++;continue}if(s===`/`){for(a=!1,o++;o<t&&/[gimsuy]/.test(e[o]);)o++;continue}if(s===`[`){for(o++;o<t&&e[o]!==`]`;)e[o]===`\\`&&o++,o++;continue}continue}if(n){if(s===`\\`){o++;continue}s===n&&(n=null);continue}if(s===`/`&&e[o+1]===`/`){i=!0,o++;continue}if(s===`/`&&e[o+1]===`*`){r=!0,o++;continue}if(s===`/`&&T(e,o)){a=!0;continue}(s===`'`||s===`"`||s==="`")&&(n=s)}return n!==null||r||i||a}function D(e,t,n){let r=e=>e.replace(S(t),n),i=C(e);if(i===null)return e.replace(S(t),(...t)=>{let r=typeof t[0]==`string`?t[0]:``,i=w(t);return i!==null&&E(e,i)?r:typeof n==`string`?n:n(r,...t.slice(1))});if(i.length===0)return r(e);let a=``,o=0;for(let t of i)o<t.start&&(a+=r(e.slice(o,t.start))),a+=e.slice(t.start,t.end),o=t.end;return o<e.length&&(a+=r(e.slice(o))),a}const te=/\b(-?\d+(?:\.\d+)?)\s*([+\-%*/])\s*(-?\d+(?:\.\d+)?)\b/g,ne=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*/g,O=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*else\s*\{([^}]*)\}/g,k=/if\s*\(\s*true\s*\)\s*\{([^}]*)\}\s*(?:else\s*\{[^}]*\}\s*)?/g,A=/var\s+([A-Za-z_$]\w*)\s*=\s*['"]([^'"]+)['"]\.split\(['"]\|['"]\)\s*;\s*var\s+(\w+)\s*=\s*0\s*;\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\s*\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,j=/var\s+([A-Za-z_$]\w*)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\];\s*var\s+(\w+)\s*=\s*(\d+);\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,M=/['"]([^'"]*)['"]\s*\+\s*['"]([^'"]*)['"]/g;function N(e,t,n){for(let r=t;r>=0&&r<e.length;r+=n){let t=e[r];if(t&&!/\s/.test(t))return t}return``}function P(e,t){let n=t.toSorted((e,t)=>t.start-e.start||t.end-e.end),r=e;for(let e of n)r=`${r.slice(0,e.start)}${e.text}${r.slice(e.end)}`;return r}function F(e,t){let n=t.get(e.node.name);if(!n)return null;let r=e.scope.getBinding(e.node.name);if(!r||!y.isVariableDeclarator(r.path.node)||!y.isIdentifier(r.path.node.id)||!t.has(r.path.node.id.name))return null;let i=r.identifier===e.node,a=e.isReferencedIdentifier(),o=e.key===`left`&&e.parentPath.isAssignmentExpression(),s=e.key===`left`&&(e.parentPath.isForInStatement()||e.parentPath.isForOfStatement()),c=e.key===`argument`&&e.parentPath.isUpdateExpression();return!i&&!a&&!o&&!s&&!c?null:n}function I(e,t){try{let n=_.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),r=new Map;return v(n,{ObjectProperty(e){if(!e.node.shorthand||!y.isIdentifier(e.node.key)||!y.isIdentifier(e.node.value))return;let n=e.get(`value`);if(!n.isIdentifier())return;let i=F(n,t),{start:a,end:o}=e.node;!i||a==null||o!=null&&(r.set(`${a}:${o}`,{start:a,end:o,text:`${e.node.key.name}: ${i}`}),e.skip())},Identifier(e){let n=F(e,t),{start:i,end:a}=e.node;!n||i==null||a!=null&&r.set(`${i}:${a}`,{start:i,end:a,text:n})}}),r.size===0?e:P(e,[...r.values()])}catch{return null}}function L(e){let t=e;return t=D(t,te,(e,t,n,r)=>{let i=Number(t),a=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a))return e;let o=null;return n===`+`?o=i+a:n===`-`?o=i-a:n===`*`?o=i*a:n===`/`&&a!==0?o=i/a:n===`%`&&a!==0&&(o=i%a),o===null||!Number.isFinite(o)?e:String(Number.isInteger(o)?o:Number(o.toFixed(12)))}),t=D(t,M,(e,t,n)=>JSON.stringify(`${t}${n}`)),t=D(t,/--(\d)/g,(e,t)=>t),t=D(t,/\+\s*(\d+(?:\.\d+)?)/g,(e,t)=>t),t=D(t,/\b0x([0-9a-fA-F]{2,8})\b/g,(e,t)=>{let n=Number.parseInt(t,16);return Number.isFinite(n)?String(n):e}),t}function R(e){let t=e;return t=D(t,O,(e,t)=>t),t=D(t,ne,``),t=D(t,k,(e,t)=>t),t=D(t,/\btrue\s*\?\s*([^:]+)\s*:\s*([^,;)\]}]+)/g,(e,t)=>t),t=D(t,/\bfalse\s*\?\s*[^:]+\s*:\s*([^,;)}\]]+)/g,(e,t)=>t),t=D(t,/if\s*\([^)]*\)\s*\{\s*\}\s*/g,``),t}function z(e){let t=e;return t=D(t,A,(e,t,n,r,i)=>{let a=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,o=new Map,s;for(;(s=a.exec(i))!==null;){let e=s[1],t=(s[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&o.set(e,t)}let c=n.split(`|`).map(e=>e.trim()).map(e=>o.get(e)).filter(e=>!!e).join(`
4
- `);return c.length>0?c:e}),t=D(t,j,(e,t,n,r,i,a)=>{let o=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,s=new Map,c;for(;(c=o.exec(a))!==null;){let e=c[1],t=(c[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&s.set(e,t)}let l=n.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``).trim()).map(e=>s.get(e)).filter(e=>!!e).join(`
5
- `);return l.length>0?l:e}),t}function B(e){let t=new Set,n=/\b(?:var|let|const)\s+([A-Za-z_$]\w{0,3})\b/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];e&&(e.length<=2||e.startsWith(`_0x`)||e.startsWith(`_`))&&t.add(e)}if(t.size===0)return{code:e,count:0};let i=new Map,a=1;for(let e of t)i.set(e,`var_${a}`),a++;let o=I(e,i);if(o!==null)return{code:o,count:o===e?0:i.size};let s=e.replace(RegExp(`\\b(${[...t].map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})\\b`,`g`),(e,t,n,r)=>{let a=i.get(t);if(!a)return e;let o=n>0?r[n-1]:``,s=N(r,n-1,-1),c=N(r,n+e.length,1);return o===`.`||o===`'`||o===`"`||o==="`"||o===`$`||(s===`{`||s===`,`)&&(c===`:`||c===`(`)?e:a});return{code:s,count:s===e?0:i.size}}const V={"<":(e,t)=>e<t,">":(e,t)=>e>t,"<=":(e,t)=>e<=t,"<==":(e,t)=>e<=t,">=":(e,t)=>e>=t,">==":(e,t)=>e>=t,"==":(e,t)=>e===t,"===":(e,t)=>e===t,"!=":(e,t)=>e!==t,"!==":(e,t)=>e!==t},H=[{pattern:`jsfuck`,regex:/\[!\[\]\]\[\(['"]\)constructor['"]\)\]\(!!\[\]\+\[\]\)\(\)/g,replacement:`"function Boolean() { [native code] }"`},{pattern:`jsfuck`,regex:/!!\[\]\+\[\]/g,replacement:`"true"`},{pattern:`jsfuck`,regex:/!\[\]\+\[\]/g,replacement:`"false"`},{pattern:`jsfuck`,regex:/\+!!\[\]/g,replacement:`1`},{pattern:`jsfuck`,regex:/\[\]\+\[\]/g,replacement:`""`},{pattern:`jsfuck`,regex:/\+\[\]/g,replacement:`0`}],U=[{pattern:`boolean-literal`,regex:/!!\[\]/g,replacement:`true`},{pattern:`boolean-literal`,regex:/!\[\]/g,replacement:`false`},{pattern:`undefined-literal`,regex:/void\s+0/g,replacement:`undefined`}],W={pattern:`opaque-truthy`,regex:/!0x0\b|!\b0(?![.\d])/g,replacement:`true`},G=[{pattern:`type-coercion`,regex:/typeof\s+undefined\s*===?\s*["']undefined["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/typeof\s+null\s*===?\s*["']object["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/typeof\s+NaN\s*===?\s*["']number["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/null\s*==\s*undefined/g,replacement:`true`},{pattern:`type-coercion`,regex:/null\s*===\s*undefined/g,replacement:`false`},{pattern:`type-coercion`,regex:/NaN\s*===?\s*NaN/g,replacement:`false`}],K=/if\s*\(\s*(-?\d+(?:\.\d+)?)\s*([<>!=]+)\s*(-?\d+(?:\.\d+)?)\s*\)/g,q=/!\s*(-?\d+(?:\.\d+)?)(?![.\d\s\w])/g,re=/(?:var|let|const)\s+(\w+)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\]/g;function J(e,t,n,r){return e.solved.push({pattern:t,original:n,result:r}),r}function Y(e,t){for(let n of t)e.output=D(e.output,n.regex,t=>J(e,n.pattern,t,n.replacement))}function X(e){e.output=D(e.output,K,(t,n,r,i)=>{if(e.iterations>=e.maxIterations)return t;let a=V[r];if(!a)return t;e.iterations+=1;let o=a(Number(n),Number(i));return J(e,`constant-comparison`,t,String(o)),e.replaceInPlace?`/* ${t} => ${o} */ if (${o})`:`if (${o})`})}function ie(e){e.output=D(e.output,q,(t,n)=>{let r=Number(n);return r===0||!Number.isFinite(r)?t:J(e,`opaque-falsy`,t,`false`)})}function ae(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function oe(e){let t=new Map;return D(e,re,(e,n,r)=>{let i=r.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``));return t.set(n,i),e}),t}function se(e){let t=oe(e.output);if(t.size!==0)for(let[n,r]of t){let t=RegExp(`${ae(n)}\\(['"]?(0x[0-9a-fA-F]+|\\d+)['"]?\\)`,`g`);e.output=D(e.output,t,(t,n)=>{if(e.iterations>=e.maxIterations)return t;let i=n.startsWith(`0x`)?Number.parseInt(n,16):Number(n);return i<0||i>=r.length?t:(e.iterations+=1,J(e,`string-array-access`,t,JSON.stringify(r[i])))})}}function ce(e){let t={output:e.code,solved:[],replaceInPlace:e.replaceInPlace,maxIterations:e.maxIterations,iterations:0};return X(t),Y(t,H),Y(t,U),Y(t,[W]),ie(t),se(t),Y(t,G),{success:!0,solvedCount:t.solved.length,solved:t.solved,transformedCode:e.replaceInPlace?t.output:void 0}}const le=[{type:`for-switch`,test:/for.*switch/s},{type:`while-switch`,test:/while.*switch/s},{type:`if-else-chain`,test:/if\s*\(\s*\w+\s*===?\s*\w+/}];function ue(e){for(let t of le)if(t.test.test(e))return t.type;return`switch`}function de(e){let t=new Map;for(let n of e){let e=n.type||`unknown`;t.set(e,(t.get(e)||0)+1)}return Object.fromEntries(t)}function fe(e){let{code:t,extractBytecode:n,mapOpcodes:r,vmResult:i}=e;if(!i.isJSVMP)return{success:!0,isVM:!1,message:`No VM/JSVMP patterns detected.`};let a={isVM:!0,vmType:i.vmType,dispatchType:ue(t),complexity:i.vmFeatures?.complexity,instructionCount:i.vmFeatures?.instructionCount,interpreterLocation:i.vmFeatures?.interpreterLocation};return n&&i.instructions&&(a.bytecode=i.instructions),r&&i.instructions&&(a.opcodeDistribution=de(i.instructions),a.suggestedStrategy=i.vmFeatures?.complexity===`high`?`Use symbolic execution (js_deobfuscate_jsvmp with aggressive=true) for high-complexity VMs`:`Use standard deobfuscation pipeline (js_deobfuscate_pipeline)`),{success:!0,analysis:a}}async function pe(t,n){let r=c(n,`searchKeyword`,``),i=p(n,`forceRequireAll`,!!r),o=Math.min(d(n,`maxResults`,20),100);try{let n=await m(await t.getActivePage(),async e=>{let t=window,n=null;typeof t.__webpack_require__==`function`&&(n=t.__webpack_require__);let r=Object.keys(t).filter(e=>e.startsWith(`webpackChunk`)||e.startsWith(`webpackJsonp`)),i=new Set;for(let e of r){let n=t[e];if(!Array.isArray(n))continue;let r=n;if(r.m&&typeof r.m==`object`)for(let e of Object.keys(r.m))i.add(e);for(let e of n)if(Array.isArray(e)&&e[1]&&typeof e[1]==`object`)for(let t of Object.keys(e[1]))i.add(t)}if(typeof t.__webpack_modules__==`object`&&t.__webpack_modules__)for(let e of Object.keys(t.__webpack_modules__))i.add(e);if(!n)for(let e of r){let r=t[e];if(r?.m&&typeof r.m==`object`){let e=r.m;n=t=>{try{let n=e[t];return typeof n==`function`?n():n}catch{return}};break}}let a=Array.from(i);if(!e.forceRequireAll||!n)return{total:a.length,requireFound:!!n,chunkKeys:r,moduleIds:a.slice(0,200),matches:[]};let o=n,s=[];for(let t of a){if(s.length>=e.maxResults)break;try{let n=o(t);if(n==null)continue;let r;try{r=JSON.stringify(n)}catch{r=String(n)}(!e.searchKeyword||r.toLowerCase().includes(e.searchKeyword.toLowerCase()))&&s.push({id:t,preview:r.slice(0,600)})}catch{}}return{total:a.length,requireFound:!0,chunkKeys:r,moduleIds:a.slice(0,200),matches:s}},{searchKeyword:r,forceRequireAll:i,maxResults:o});return e.info(`webpack_enumerate: found ${n.total} modules, ${n.matches.length} matches`),a(n)}catch(e){return s(e)}}function me(t){e.info(`Derotating string array...`);try{let n=_.parse(t,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=0;return v(n,{CallExpression(t){if(!y.isFunctionExpression(t.node.callee)&&!y.isArrowFunctionExpression(t.node.callee))return;let n=t.node.callee;if(!y.isFunctionExpression(n)||!y.isBlockStatement(n.body))return;let i=n.body.body.some(e=>y.isWhileStatement(e)),a=JSON.stringify(n.body).includes(`push`)&&JSON.stringify(n.body).includes(`shift`);i&&a&&(e.debug(`Found string array rotation IIFE`),t.remove(),r++)}}),r>0?(e.info(`Removed ${r} string array rotation functions`),b(n,{comments:!0,compact:!1}).code):t}catch(n){return e.error(`Failed to derotate string array:`,n),t}}const Z=v.default??v,Q=b.default??b,he=new Set([`summary`,`priority`,`incremental`,`full`]),ge=new Set([`structure`,`business`,`security`,`all`]),$=new Set([`function`,`xhr`,`fetch`,`websocket`,`localstorage`,`cookie`]),_e=new Set([`log`,`block`,`modify`]),ve=new Set([`call`,`apply`]);var ye=class{collector;scriptManager;deobfuscator;advancedDeobfuscator;obfuscationDetector;analyzer;cryptoDetector;hookManager;jsvmpDeobfuscator;constructor(e){this.collector=e.collector,this.scriptManager=e.scriptManager,this.deobfuscator=e.deobfuscator,this.advancedDeobfuscator=e.advancedDeobfuscator,this.obfuscationDetector=e.obfuscationDetector,this.analyzer=e.analyzer,this.cryptoDetector=e.cryptoDetector,this.hookManager=e.hookManager,this.jsvmpDeobfuscator=new h}requireCodeArg(t,n){let r=t.code;return typeof r!=`string`||r.trim().length===0?(e.warn(`${n} called without valid code argument`),null):r}extractWebcrackArgs(e){let t={},n=p(e,`unpack`),r=p(e,`unminify`),i=p(e,`jsx`),a=p(e,`mangle`),o=p(e,`forceOutput`),s=p(e,`includeModuleCode`),l=c(e,`outputDir`),u=d(e,`maxBundleModules`);return n!==void 0&&(t.unpack=n),r!==void 0&&(t.unminify=r),i!==void 0&&(t.jsx=i),a!==void 0&&(t.mangle=a),o!==void 0&&(t.forceOutput=o),s!==void 0&&(t.includeModuleCode=s),l?.trim()&&(t.outputDir=l),u!==void 0&&(t.maxBundleModules=u),Array.isArray(e.mappings)&&(t.mappings=e.mappings.filter(e=>typeof e==`object`&&!!e&&typeof e.path==`string`&&typeof e.pattern==`string`)),t}async handleCollectCode(i){let o=p(i,`returnSummaryOnly`,!1),s=u(i,`smartMode`,he),c=n,l=e=>e.slice(0,c).map(e=>({url:e.url,type:e.type,size:e.size,sizeKB:(e.size/1024).toFixed(2),truncated:e.metadata?.truncated||!1,preview:`${e.content.substring(0,200)}...`})),m=e=>{let t=(Array.isArray(e.summaries)&&e.summaries.length>0?e.summaries:l(e.files)).slice(0,c),n=Array.isArray(e.summaries)?e.summaries.length:e.files.length,r=e.totalSize>0?e.totalSize:Array.isArray(e.summaries)?e.summaries.reduce((e,t)=>e+(typeof t.size==`number`?t.size:0),0):e.files.reduce((e,t)=>e+t.size,0);return{totalSize:r,totalSizeKB:(r/1024).toFixed(2),filesCount:n,summarizedFiles:t.length,omittedFiles:Math.max(0,n-t.length),collectTime:e.collectTime,summary:t}};s||=`summary`;let h=await this.collector.collect({url:f(i,`url`),includeInline:p(i,`includeInline`),includeExternal:p(i,`includeExternal`),includeDynamic:p(i,`includeDynamic`),smartMode:s,compress:p(i,`compress`),maxTotalSize:d(i,`maxTotalSize`),maxFileSize:i.maxFileSize?d(i,`maxFileSize`,0)*1024:void 0,priorities:i.priorities});if(o)return a({mode:`summary`,...m(h),hint:`Use get_script_source for specific files.`});let g=r,_=t,v=Buffer.byteLength(JSON.stringify(h),`utf8`);return h.totalSize>g||v>_?(e.warn(`Collected code is too large (collected=${(h.totalSize/1024).toFixed(2)}KB, response=${(v/1024).toFixed(2)}KB), returning summary mode.`),a({warning:`Code size exceeds safe response threshold; summary returned.`,...m(h),estimatedResponseSize:v,estimatedResponseSizeKB:(v/1024).toFixed(2),recommendations:[`Use get_script_source for targeted files.`,`Use more specific priority filters.`,`Use smartMode=summary for initial reconnaissance.`]})):a(h)}async handleSearchInScripts(e){await this.scriptManager.init();let t=c(e,`keyword`);if(!t)return a({success:!1,error:`keyword is required`});let n=d(e,`maxMatches`,100),r=p(e,`returnSummary`,!1),i=d(e,`maxContextSize`,5e4),o=await this.scriptManager.searchInScripts(t,{isRegex:p(e,`isRegex`),caseSensitive:p(e,`caseSensitive`),contextLines:d(e,`contextLines`),maxMatches:n}),s=JSON.stringify(o).length;if(r||s>i){let t=o.matches??[];return a({success:!0,keyword:e.keyword,totalMatches:t.length,resultSize:s,resultSizeKB:(s/1024).toFixed(2),truncated:s>i,reason:s>i?`Result too large (${(s/1024).toFixed(2)}KB > ${(i/1024).toFixed(2)}KB)`:`Summary mode enabled`,matchesSummary:t.slice(0,10).map(e=>({scriptId:e.scriptId,url:e.url,line:e.line,preview:`${(e.context??``).substring(0,100)}...`})),recommendations:[`Use more specific keywords.`,`Reduce maxMatches (current: ${n}).`,`Use get_script_source for targeted file retrieval.`]})}return a(o)}async handleExtractFunctionTree(e){let t=c(e,`scriptId`),n=c(e,`functionName`);if(!t)return a({success:!1,error:`scriptId is required`,hint:`Use get_all_scripts() to list available scripts and their scriptIds`});if(!n)return a({success:!1,error:`functionName is required`,hint:`Specify the name of the function to extract`});await this.scriptManager.init();let r=await this.scriptManager.getAllScripts();if(!r.some(e=>String(e.scriptId)===String(t))){let e=r.slice(0,10).map(e=>({scriptId:e.scriptId,url:e.url?.substring(0,80)}));return a({success:!1,error:`Script not found: ${t}`,hint:`The specified scriptId does not exist. Use get_all_scripts() to list available scripts.`,availableScripts:e.length>0?e:`No scripts loaded. Navigate to a page first.`,totalScripts:r.length})}try{return a({success:!0,...await this.scriptManager.extractFunctionTree(t,n,{maxDepth:d(e,`maxDepth`),maxSize:d(e,`maxSize`),includeComments:p(e,`includeComments`)})})}catch(e){return a({success:!1,error:e instanceof Error?e.message:String(e),hint:`Make sure the function name exists in the specified script`})}}async handleDeobfuscate(e){let t=this.requireCodeArg(e,`deobfuscate`);if(!t)return a({success:!1,error:`code is required and must be a non-empty string`});if(u(e,`engine`,new Set([`auto`,`webcrack`]),`auto`)===`webcrack`)return a(await this.advancedDeobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e),...typeof e.detectOnly==`boolean`?{detectOnly:e.detectOnly}:{}}));let n=await this.deobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e)});return n&&typeof n==`object`&&`success`in n&&n.success===!1&&!(`error`in n)?a({...n,error:n.reason||`deobfuscation failed`}):a(n)}async handleUnderstandCode(e){let t=this.requireCodeArg(e,`understand_code`);return a(t?await this.analyzer.understand({code:t,context:l(e,`context`),focus:u(e,`focus`,ge,`all`)}):{success:!1,error:`code is required and must be a non-empty string`})}async handleDetectCrypto(e){let t=this.requireCodeArg(e,`detect_crypto`);return a(t?await this.cryptoDetector.detect({code:t}):{success:!1,error:`code is required and must be a non-empty string`})}async handleManageHooks(e){let t=f(e,`action`);switch(t){case`create`:return a(await this.hookManager.createHook({target:f(e,`target`),type:u(e,`type`,$)??`function`,action:u(e,`hookAction`,_e,`log`),customCode:c(e,`customCode`)}));case`list`:return a({hooks:this.hookManager.getAllHooks()});case`records`:return a({records:this.hookManager.getHookRecords(f(e,`hookId`))});case`clear`:return this.hookManager.clearHookRecords(c(e,`hookId`)),a({success:!0,message:`Hook records cleared`});default:return a({success:!1,message:`Unknown hook action: ${t}. Valid actions: create, list, records, clear`})}}async handleDetectObfuscation(e){let t=this.requireCodeArg(e,`detect_obfuscation`);if(!t)return a({success:!1,error:`code is required and must be a non-empty string`});let n=p(e,`generateReport`,!0),r=this.obfuscationDetector.detect(t);if(!n)return a(r);let i=this.obfuscationDetector.generateReport(r);return o(`${JSON.stringify(r,null,2)}\n\n${i}`)}async handleWebcrackUnpack(e){let t=this.requireCodeArg(e,`webcrack_unpack`);if(!t)return a({success:!1,error:`code is required and must be a non-empty string`});let n=await g(t,{unpack:p(e,`unpack`,!0),unminify:p(e,`unminify`,!0),jsx:p(e,`jsx`,!0),mangle:p(e,`mangle`,!1),...this.extractWebcrackArgs(e)});return n.applied?a({success:!0,code:n.code,bundle:n.bundle,savedTo:n.savedTo,savedArtifacts:n.savedArtifacts,optionsUsed:n.optionsUsed,engine:`webcrack`}):a({success:!1,error:n.reason||`webcrack execution failed`,optionsUsed:n.optionsUsed,engine:`webcrack`})}async handleWebpackEnumerate(e){return pe(this.collector,e)}async handleClearCollectedData(){try{return await this.collector.clearAllData(),this.scriptManager.clear(),a({success:!0,message:`All collected data cleared.`,cleared:{fileCache:!0,compressionCache:!0,collectedUrls:!0,scriptManager:!0}})}catch(t){return e.error(`Failed to clear collected data:`,t),a(i(t))}}async handleGetCollectionStats(){try{let e=await this.collector.getAllStats();return a({success:!0,stats:e,summary:{totalCachedFiles:e.cache.memoryEntries+e.cache.diskEntries,totalCacheSize:`${(e.cache.totalSize/1024).toFixed(2)} KB`,compressionRatio:`${e.compression.averageRatio.toFixed(1)}%`,cacheHitRate:e.compression.cacheHits>0?`${(e.compression.cacheHits/(e.compression.cacheHits+e.compression.cacheMisses)*100).toFixed(1)}%`:`0%`,collectedUrls:e.collector.collectedUrls}})}catch(t){return e.error(`Failed to get collection stats:`,t),a(i(t))}}async handleJsDeobfuscateJsvmp(e){let t=this.requireCodeArg(e,`js_deobfuscate_jsvmp`);if(!t)return a({success:!1,error:`code is required and must be a non-empty string`});let n=p(e,`detectOnly`,!1),r=await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:p(e,`aggressive`,!1),extractInstructions:p(e,`extractInstructions`,!0),timeout:d(e,`timeout`,3e4)});return a(n?{success:!0,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,confidence:r.confidence,instructionCount:r.instructions?.length}:{success:r.isJSVMP,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,instructions:r.instructions,deobfuscatedCode:r.deobfuscatedCode,confidence:r.confidence,warnings:r.warnings,unresolvedParts:r.unresolvedParts,stats:r.stats})}async handleJsDeobfuscatePipeline(e){let t=this.requireCodeArg(e,`js_deobfuscate_pipeline`);if(!t)return a({success:!1,error:`code is required`});let n=p(e,`useWebcrack`,!0),r=p(e,`aggressive`,!1),i=p(e,`humanize`,!0),o=p(e,`returnStageDetails`,!1),s=Date.now(),c=t,l=[],u=L(c);u!==c&&(c=u,l.push(`constant_fold`));let d=R(c);d!==c&&(c=d,l.push(`dead_code_remove`));let f=c,m=!1,h,_;if(n)try{let e=await g(c,{unminify:!0,unpack:!0});e.applied?(f=e.code,m=!0):h=e.reason?`webcrack stage did not apply: ${e.reason}`:`webcrack stage did not apply any transformation.`}catch(e){_=e instanceof Error?e.message:String(e)}if(r){let e=z(f);e!==f&&(f=e)}let v=f,y=0;if(i){let e=B(v);e.code!==v&&(v=e.code,y=e.count)}let b=Date.now()-s,x=t.length>0?1-v.length/t.length:0,S={success:!h&&!_,deobfuscatedCode:v,...h?{warning:h}:{},..._?{error:`webcrack stage failed: ${_}`}:{},stats:{originalSize:t.length,finalSize:v.length,reductionRate:Math.round(x*1e3)/10,processingTimeMs:b,stages:{preprocessor:{transforms:l,sizeAfter:c.length},deobfuscator:{webcrackApplied:m,sizeAfter:f.length,...h?{warning:h}:{},..._?{error:_}:{}},humanizer:{renameCount:y,sizeAfter:v.length}}}};return o&&(S.stageDetails={preprocessed:c.substring(0,5e3),deobfuscated:f.substring(0,5e3)}),a(S)}async handleJsAnalyzeVm(e){let t=this.requireCodeArg(e,`js_analyze_vm`);if(!t)return a({success:!1,error:`code is required`});let n=p(e,`extractBytecode`,!0);return a(fe({code:t,extractBytecode:n,mapOpcodes:p(e,`mapOpcodes`,!0),vmResult:await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:!1,extractInstructions:n,timeout:15e3})}))}async handleJsSolveConstraints(e){let t=this.requireCodeArg(e,`js_solve_constraints`);return a(t?ce({code:t,replaceInPlace:p(e,`replaceInPlace`,!0),maxIterations:d(e,`maxIterations`,100)}):{success:!1,error:`code is required`})}async handleAnalysisAstMatch(e){let t=c(e,`code`);if(!t)return a({success:!1,error:`code is required`});let n=c(e,`nodeType`);if(!n)return a({success:!1,error:`nodeType is required`});let r=d(e,`maxResults`,50),i=c(e,`filter`),o;if(i)try{o=JSON.parse(i)}catch{return a({success:!1,error:`filter must be valid JSON`})}let s;try{s=_.parse(t,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){return a({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let l=[],u=n;function f(e){if(!o)return!0;for(let[t,n]of Object.entries(o)){let r=t.split(`.`),i=e;for(let e of r){if(typeof i!=`object`||!i)return!1;i=i[e]}if(String(i)!==String(n))return!1}return!0}function p(e){let t={};for(let n of Object.keys(e)){if(n===`type`||n===`start`||n===`end`||n===`loc`||n===`range`)continue;let r=e[n];r==null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`?t[n]=r:Array.isArray(r)&&r.length<=5?t[n]=r.map(e=>typeof e==`object`&&e&&`type`in e?{type:e.type}:e):typeof r==`object`&&r&&`type`in r&&(t[n]={type:r.type})}return t}return Z(s,{enter(e){let n=e.node;n.type===u&&f(n)&&(l.push({type:n.type,start:n.start??-1,end:n.end??-1,code:t.slice(n.start??0,n.end??0),properties:p(n)}),l.length>=r&&e.stop())}}),a({success:!0,matches:l,total:l.length,nodeType:n})}async handleAnalysisDeflatControlFlow(e){let t=c(e,`code`);if(!t)return a({success:!1,error:`code is required`});let n;try{n=_.parse(t,{sourceType:`unambiguous`})}catch(e){return a({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let r=p(e,`removeDispatcher`,!0),i=this.preprocessDeflatCode(t);if(i.code!==t)try{n=_.parse(i.code,{sourceType:`unambiguous`})}catch(e){return a({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let o=0,s=new Set,l=this.resolveDispatcherArray.bind(this);Z(n,{WhileStatement:e=>{let t=e.node.test;if(t.type!==`BooleanLiteral`||t.value!==!0)return;let n=e.node.body;if(n.type!==`BlockStatement`)return;let r=n.body.find(e=>e.type===`SwitchStatement`);if(!r)return;let i=r.discriminant;if(i.type!==`MemberExpression`||!i.computed)return;let a=i.object;if(a.type!==`Identifier`)return;let c=a.name,u,d=i.property;if(d.type===`Identifier`?u=d.name:d.type===`UpdateExpression`&&d.argument.type===`Identifier`&&(u=d.argument.name),!u)return;let f=r.cases;if(f.length===0)return;let p=new Map;for(let e of f)!e.test||e.test.type!==`StringLiteral`||p.set(e.test.value,e.consequent);let m=e.scope.getBinding(c),h=e.scope.getBinding(u);if(!m||!h)return;let g=l(e,c);if(!g)return;let _=[];if(g.type===`ArrayExpression`)for(let e of g.elements)e&&e.type===`StringLiteral`&&_.push(e.value);else if(g.type===`CallExpression`&&g.callee.type===`MemberExpression`&&g.callee.property.type===`Identifier`&&g.callee.property.name===`split`&&g.arguments[0]?.type===`StringLiteral`){let e=g.arguments[0].value,t=g.callee.object;t.type===`StringLiteral`&&_.push(...t.value.split(e))}if(_.length===0)return;let v=[];for(let e of _){let t=p.get(e);if(t)for(let e of t)e.type!==`BreakStatement`&&e.type!==`ContinueStatement`&&v.push(e)}e.replaceWith(y.blockStatement(v)),s.add(m.identifier),s.add(h.identifier),o++}}),r&&s.size>0&&Z(n,{VariableDeclarator(e){if(e.node.id.type===`Identifier`&&s.has(e.node.id)){let t=e.parent;t.type===`VariableDeclaration`&&t.declarations.length===1?e.parentPath.remove():e.remove()}}});let u=Q(n,{retainLines:!0}).code;return a({success:!0,code:u,flattenedCount:o,dispatchersRemoved:r?s.size:0,helperTransforms:i.transforms})}async handleAnalysisDecodeStringArray(e){let t=c(e,`code`);if(!t)return a({success:!1,error:`code is required`});let n=d(e,`maxReplacements`,200),r=p(e,`removeRotation`,!0),i=r?me(t):t,o=new Map,s;try{s=_.parse(i,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){return a({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}Z(s,{VariableDeclarator(e){if(!y.isIdentifier(e.node.id)||!y.isArrayExpression(e.node.init))return;let t=[];for(let n of e.node.init.elements){if(!y.isStringLiteral(n))return;t.push(n.value)}o.set(e.node.id.name,t)}});let l=[],u=0;return Z(s,{CallExpression(e){if(u>=n){e.stop();return}if(!y.isIdentifier(e.node.callee))return;let t=e.node.callee.name,r=o.get(t);if(!r||e.node.arguments.length!==1)return;let i=e.node.arguments[0];if(!y.isNumericLiteral(i)&&!y.isStringLiteral(i))return;let a=y.isNumericLiteral(i)?i.value:i.value.startsWith(`0x`)?Number.parseInt(i.value,16):Number(i.value);if(!Number.isInteger(a)||a<0||a>=r.length)return;let s=r[a];typeof s==`string`&&(l.push({arrayName:t,index:a,value:s,original:Q(e.node,{compact:!0}).code}),e.replaceWith(y.stringLiteral(s)),u+=1)}}),a({success:!0,code:Q(s,{retainLines:!0}).code,replacedCount:u,arraysFound:o.size,rotationRemoved:r&&i!==t,replacements:l})}preprocessDeflatCode(e){let t=e,n=[];return t=t.replace(/(\b[a-zA-Z_$][\w$]*)\[['"]([a-zA-Z_$][\w$]*)['"]\]\(([^)]*)\)/g,(e,t,r,i)=>ve.has(r)?(n.push(`helper-member-call`),`${t}.${r}(${i})`):e),{code:t,transforms:n}}resolveDispatcherArray(e,t){let n=e.scope.getBinding(t);if(!n?.path.isVariableDeclarator())return null;let r=n.path.node.init;if(r)return r;let i=n.path.parentPath;if(!i.isVariableDeclaration())return null;let a=i.getAllNextSiblings();for(let e of a){if(!e.isExpressionStatement())continue;let n=e.node.expression;if(!(!y.isAssignmentExpression(n)||n.operator!==`=`||!y.isIdentifier(n.left,{name:t})))return n.right}return null}};export{ye as CoreAnalysisHandlers};
@@ -1 +0,0 @@
1
- import{createRequire as e}from"node:module";const t=e(import.meta.url),n=`pnpm add -O better-sqlite3@12.6.2`,r=`npm rebuild better-sqlite3 --foreground-scripts`;function i(e){return e instanceof Error?e.message:String(e)}function a(e){return/better-sqlite3|better_sqlite3\.node|NODE_MODULE_VERSION|compiled against a different Node\.js version/i.test(i(e))}function o(e){let t=i(e);return/Cannot find module 'better-sqlite3'|Cannot find package 'better-sqlite3'|better-sqlite3 is not installed/i.test(t)?`missing`:/better_sqlite3\.node|NODE_MODULE_VERSION|compiled against a different Node\.js version|module was compiled against/i.test(t)?`abi-mismatch`:`load-failed`}function s(e){let t=o(e),a=i(e);return t===`missing`?`GRACEFUL: better-sqlite3 is not installed. Install the optional trace backend with \`${n}\`.`:t===`abi-mismatch`?`GRACEFUL: better-sqlite3 is installed but its native binary is incompatible with the current Node.js runtime (${process.version}, ABI ${process.versions.modules}). Rebuild it with \`${r}\` or reinstall dependencies under the active Node version. Original error: ${a}`:`GRACEFUL: better-sqlite3 failed to initialize. Try \`${r}\` or reinstall dependencies under the active Node version. Original error: ${a}`}function c(){try{return t(t.resolve(`better-sqlite3/package.json`)).version??null}catch{return null}}function l(){let e=c();if(!e)return{status:`missing`,detail:`GRACEFUL: Optional SQLite backend for trace tools is not installed. Install it with: ${n}`,version:null,issue:`missing`};try{let n=new(t(`better-sqlite3`))(`:memory:`);try{n.prepare(`SELECT 1 AS ok`).get()}finally{n.close()}return{status:`ok`,detail:`installed (${e}) — native trace backend healthy`,version:e}}catch(t){let r=o(t);return r===`missing`?{status:`missing`,detail:`GRACEFUL: Optional SQLite backend for trace tools is not installed. Install it with: ${n}`,version:e,issue:r}:{status:`warn`,detail:`installed (${e}) but ${s(t)}`,version:e,issue:r}}}export{a as n,l as r,s as t};
@@ -1,7 +0,0 @@
1
- import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import{Q as n,et as r,jr as i}from"./constants-Cp6hBrrx.mjs";import{t as a}from"./ToolError-DWU_z7gp.mjs";import{t as o}from"./ToolProbe-xsfALmN3.mjs";import{t as s}from"./PrerequisiteError-Bl3dK8XA.mjs";import{tmpdir as c}from"node:os";import{randomUUID as l}from"node:crypto";import{basename as u,dirname as d,join as f}from"node:path";import{access as p,mkdtemp as m,readFile as h,rm as g,writeFile as _}from"node:fs/promises";import{execFile as v}from"node:child_process";var y=class{sessions=new Map;activeSessionId;fridaProbe;probePromise;async attach(e){let t=await this.getAvailability();if(!t.available)throw new s(t.reason??`Frida CLI is not available`);let n=await this.runFridaCommand(e,`console.log("__frida_attach_ok__");`);if(n.error)throw new a(`CONNECTION`,n.error);let r=l(),i={id:r,target:e,pid:this.resolvePid(e),status:`attached`,attachedAt:new Date().toISOString()};return this.sessions.set(r,i),this.activeSessionId=r,r}async detach(){let e=this.getActiveSessionRecord();e&&(e.status=`detached`,this.activeSessionId=void 0)}async executeScript(e){let t=this.requireActiveSession(),n=await this.runFridaCommand(t.target,e);return n.error&&(t.status=`error`,t.lastError=n.error),n}async enumerateModules(){let e=this.requireActiveSession(),t=await this.runFridaCommand(e.target,`console.log(JSON.stringify(Process.enumerateModules()));`),n=this.parseModuleList(t.output);return n.length>0?n:(t.error&&(e.status=`error`,e.lastError=t.error),[])}async enumerateFunctions(e){let t=this.requireActiveSession(),n=JSON.stringify(e),r=await this.runFridaCommand(t.target,[`const entries = Process.getModuleByName(${n}).enumerateExports()`,`.filter(function (entry) { return entry.type === "function"; })`,`.map(function (entry) {`,` return { name: entry.name, address: String(entry.address), size: 0 };`,`});`,`console.log(JSON.stringify(entries));`].join(``)),i=this.parseFunctionList(r.output);return i.length>0?i:(r.error&&(t.status=`error`,t.lastError=r.error),[])}async findSymbols(e){let t=this.requireActiveSession(),n=e.trim(),r=n.includes(`:`)?n:n.includes(`!`)?`exports:${n}`:`exports:*!${n}*`,i=JSON.stringify(r),a=await this.runFridaCommand(t.target,[`const resolver = new ApiResolver("module");`,`const matches = resolver.enumerateMatches(${i});`,`const mapped = matches.map(function (entry) {`,` const resolvedName = typeof entry.name === "string" ? entry.name : "unknown";`,` const resolvedAddress = entry.address ? String(entry.address) : "0x0";`,` return { name: resolvedName, address: resolvedAddress, demangled: resolvedName };`,`});`,`console.log(JSON.stringify(mapped));`].join(``)),o=this.parseSymbolList(a.output);return o.length>0?o:(a.error&&(t.status=`error`,t.lastError=a.error),[])}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,target:e.target,pid:e.pid,status:e.status}))}async isAvailable(){return(await this.getAvailability()).available}async getAvailability(){if(this.fridaProbe)return this.fridaProbe;this.probePromise||=o(`frida`);let e=await this.probePromise;return this.fridaProbe=e,this.probePromise=void 0,e}useSession(e){return this.sessions.has(e)?(this.activeSessionId=e,!0):!1}hasSession(e){return this.sessions.has(e)}getSessionDiagnostics(e){let t=this.sessions.get(e);if(t)return{status:t.status,lastError:t.lastError}}getActiveSessionRecord(){if(this.activeSessionId)return this.sessions.get(this.activeSessionId)}requireActiveSession(){let e=this.getActiveSessionRecord();if(!e)throw new s(`No active Frida session. Call attach() first.`);return e}resolvePid(e){if(!/^\d+$/.test(e))return null;let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}async runFridaCommand(e,r){let i=await this.getAvailability();if(!i.available)return{output:``,error:i.reason??`Frida CLI is not available`};let a=i.path??`frida`,o=[...this.buildTargetArgs(e),`--runtime=v8`,`-q`,`-e`,r];try{let e=await this.execFileUtf8(a,o,n),t=e.stdout.trim(),r=e.stderr.trim();return r?{output:t,error:r}:{output:t}}catch(n){let r=n instanceof Error?n.message:String(n);return t.warn(`[binary-instrument] Frida command failed`,{target:e,message:r}),{output:``,error:r}}}buildTargetArgs(e){return/^\d+$/.test(e)?[`-p`,e]:e.includes(`/`)||e.includes(`\\`)?[`-f`,e]:[`-n`,e]}parseModuleList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.readStringField(e,`path`),i=this.normalizeHex(e.base),a=this.readNumberField(e,`size`);!t||!r||!i||a===void 0||n.push({name:t,base:i,size:a,path:r})}return n}parseFunctionList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.normalizeHex(e.address),i=this.readNumberField(e,`size`)??0;!t||!r||n.push({name:t,address:r,size:i})}return n}parseSymbolList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.normalizeHex(e.address),i=this.readStringField(e,`demangled`);!t||!r||(i?n.push({name:t,address:r,demangled:i}):n.push({name:t,address:r}))}return n}extractJsonPayload(e){let t=e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.startsWith(`{`)||e.startsWith(`[`)).toReversed();for(let e of t)try{return JSON.parse(e)}catch{continue}}readStringField(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}readNumberField(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}normalizeHex(e){if(typeof e==`number`&&Number.isFinite(e))return`0x${e.toString(16)}`;if(typeof e==`string`&&e.length>0)return e.startsWith(`0x`)?e:`0x${e}`}isRecord(e){return typeof e==`object`&&!!e}execFileUtf8(e,t,n){return new Promise((r,i)=>{v(e,t,{timeout:n,windowsHide:!0,maxBuffer:5242880,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}},b=class{ghidraProbe;probePromise;async analyze(e,n){await p(e);let i=await h(e),a=this.extractPrintableStrings(i),o=this.deriveImports(a),s=this.deriveExports(a);if(!(await this.getAvailability()).available)return{functions:[],imports:o,exports:s,strings:a};let l=typeof n?.timeout==`number`&&Number.isFinite(n.timeout)?n.timeout:r,u=await m(f(c(),`jshook-ghidra-script-`)),d=f(u,`BinaryInstrumentDump.py`);try{await _(d,this.buildDefaultScript(),`utf8`);let t=await this.headlessAnalyze(d,e,l);return{functions:this.parseDecompiledOutput(t),imports:o,exports:s,strings:a}}catch(n){let r=n instanceof Error?n.message:String(n);return t.warn(`[binary-instrument] Ghidra analyze fallback`,{binaryPath:e,message:r}),{functions:[],imports:o,exports:s,strings:a}}finally{await g(u,{recursive:!0,force:!0})}}async headlessAnalyze(e,t,n=r){let i=await this.getAvailability();if(!i.available)throw new s(i.reason??`Ghidra analyzeHeadless is not available`);await p(t),await p(e);let a=i.path??`analyzeHeadless`,o=await m(f(c(),`jshook-ghidra-project-`));try{let r=await this.execFileUtf8(a,[o,`binary-instrument`,`-import`,t,`-scriptPath`,d(e),`-postScript`,u(e)],n);return[r.stdout.trim(),r.stderr.trim()].filter(e=>e.length>0).join(`
2
- `)}finally{await g(o,{recursive:!0,force:!0})}}parseDecompiledOutput(e){let t=[],n=/FUNCTION_START\s*[\r\n]+NAME:(.+?)\s*[\r\n]+ADDRESS:(.+?)\s*[\r\n]+SIGNATURE:(.+?)\s*[\r\n]+DECOMPILED_START\s*[\r\n]+([\s\S]*?)\s*[\r\n]+DECOMPILED_END\s*[\r\n]+FUNCTION_END/g,r=n.exec(e);for(;r;){let i=r[1]??``,a=r[2]??``,o=r[3]??``,s=r[4]??``,c=i.trim(),l=this.normalizeHex(a.trim()),u=o.trim(),d=s.trim();c.length>0&&l.length>0&&u.length>0&&t.push({name:c,address:l,signature:u,decompiled:d}),r=n.exec(e)}return t}async isAvailable(){return(await this.getAvailability()).available}async getAvailability(){if(this.ghidraProbe)return this.ghidraProbe;this.probePromise||=o(`analyzeHeadless`,[`-help`]);let e=await this.probePromise;return this.ghidraProbe=e,this.probePromise=void 0,e}buildDefaultScript(){return[`# @category BinaryInstrument`,`from ghidra.app.decompiler import DecompInterface`,``,`program = currentProgram`,`interface = DecompInterface()`,`interface.openProgram(program)`,`function_manager = program.getFunctionManager()`,`functions = function_manager.getFunctions(True)`,``,`for function in functions:`,` print("FUNCTION_START")`,` print("NAME:" + str(function.getName()))`,` print("ADDRESS:" + str(function.getEntryPoint()))`,` try:`,` signature = str(function.getSignature())`,` except:`,` signature = str(function.getName()) + "()"`,` print("SIGNATURE:" + signature)`,` print("DECOMPILED_START")`,` try:`,` decompiled = interface.decompileFunction(function, 30, monitor).getDecompiledFunction()`,` if decompiled:`,` print(str(decompiled.getC()))`,` else:`,` print("// no decompiled output")`,` except:`,` print("// decompile failed")`,` print("DECOMPILED_END")`,` print("FUNCTION_END")`].join(`
3
- `)}extractPrintableStrings(e){let t=[],n=``;for(let r of e.values()){if(r>=32&&r<=126){n+=String.fromCharCode(r);continue}n.length>=4&&t.push(n),n=``}return n.length>=4&&t.push(n),Array.from(new Set(t)).slice(0,1e3)}deriveImports(e){return e.filter(e=>/(?:\.dll|\.so|\.dylib|kernel32|user32|libc|printf|malloc|LoadLibrary)/i.test(e)).slice(0,100)}deriveExports(e){return e.filter(e=>/^[A-Za-z_][A-Za-z0-9_@?$]{2,}$/.test(e)).slice(0,100)}normalizeHex(e){return e.startsWith(`0x`)?e:`0x${e}`}execFileUtf8(e,t,n){return new Promise((r,i)=>{v(e,t,{timeout:n,windowsHide:!0,maxBuffer:16777216,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}},x=class{generateHooks(e){let t=[];for(let n of e.functions){let r=this.classifyFunction(n,e);r!==`unknown`&&t.push({functionName:n.name,description:this.describeCategory(r,e),hookCode:this.buildHookCode(n,r),parameters:this.buildParameters(n)})}return t}exportScript(e,t){if(t!==`frida`)throw new a(`VALIDATION`,`Unsupported export format: "${t}". Only "frida" is supported.`);let n=[`// Frida hook script`,`// auto-generated by HookCodeGenerator`,`// Hook count: ${e.length}`,``];for(let t of e)n.push(`// ${t.functionName}: ${t.description}`),n.push(t.hookCode),n.push(``);return n.join(`
4
- `)}classifyFunction(e,t){let n=e.name.toLowerCase(),r=t.imports.map(e=>e.toLowerCase()),i=t.strings.map(e=>e.toLowerCase());return e.name.startsWith(`Java_`)?`jni`:n.includes(`aes`)?`aes`:n.includes(`md5`)?`md5`:n.includes(`sha`)?`sha`:n.includes(`rsa`)?`rsa`:n.includes(`base64`)?`base64`:n.includes(`send`)||n.includes(`recv`)||n.includes(`socket`)||n.includes(`http`)?`network`:n.includes(`open`)||n.includes(`read`)||n.includes(`write`)||n.includes(`fopen`)?`file-io`:(n.includes(`decrypt`)||n.includes(`encrypt`))&&i.some(e=>e.includes(`obfuscation`)||e.includes(`encryption`))?`obfuscation`:n.includes(`memcpy`)||n.includes(`strcpy`)||n.includes(`memmove`)||n.includes(`string`)?`string`:r.some(e=>e.includes(`aes`))?`aes`:`unknown`}describeCategory(e,t){switch(e){case`jni`:return`JNI bridge hook for Java/native boundary inspection`;case`aes`:return`AES crypto hook for key/plaintext capture`;case`md5`:return`MD5 crypto hook for digest inspection`;case`sha`:return`SHA crypto hook for digest inspection`;case`rsa`:return`RSA crypto hook for key operation tracing`;case`base64`:return`Base64 transform hook for encoded payload tracing`;case`network`:return`Network hook for request and payload tracing`;case`file-io`:return`File I/O hook for filesystem access tracing`;case`string`:return`String operation hook for buffer tracing`;case`obfuscation`:return t.strings.some(e=>e.toLowerCase().includes(`obfuscation`))?`Potential obfuscation hook for runtime string decryption tracing`:`Potential obfuscation hook`;case`unknown`:return`Unknown hook`}}buildHookCode(e,t){if(t===`jni`)return[`Java.perform(function () {`,` const target = ptr("${e.address}");`,` Interceptor.attach(target, {`,` onEnter(args) {`,` console.log("[jni] ${e.name}");`,` },`,` });`,`});`].join(`
5
- `);let n=t===`aes`||t===`md5`||t===`sha`||t===`rsa`||t===`base64`?` console.log(hexdump(args[0]));`:` console.log("[trace] entering");`,r=e.name.replace(/[^A-Za-z0-9_]/g,`_`);return[`const target_${r} = ptr("${e.address}");`,`Interceptor.attach(target_${r}, {`,` onEnter(args) {`,` console.log("[hook] ${e.name}");`,n,` },`,`});`].join(`
6
- `)}buildParameters(e){return e.parameters.length>0?e.parameters.map((e,t)=>({name:e.name||`arg${t}`,type:e.type||`pointer`,description:`Captured parameter ${t}`})):[{name:`arg0`,type:`pointer`,description:`Captured parameter 0`}]}};async function S(e,t){let n=C(e),r=w(t.pluginId),i=T(r,n);if(!i)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin ${r} is not installed`};let a=E(e,i);if(!a?.lifecycleContext)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin ${i} is installed but has no runtime`};try{let e=(await a.lifecycleContext.invokeTool(t.toolName,t.args)).content?.find(e=>e.type===`text`)?.text;if(!e)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin returned no text content`};try{let n=JSON.parse(e);if(O(n))return{tool:`binary-instrument`,action:t.toolName,success:k(n,`success`)??!0,data:n.data,error:A(n,`error`)}}catch{return{success:!0,tool:`binary-instrument`,action:t.toolName,data:e}}return{success:!0,tool:`binary-instrument`,action:t.toolName,data:e}}catch(e){return{success:!1,tool:`binary-instrument`,action:t.toolName,error:e instanceof Error?e.message:String(e)}}}function C(e){return Array.from(e.extensionPluginsById.keys()).map(w)}function w(e){return e.replaceAll(`_`,`-`)}function T(e,t){let n=e.replace(/^plugin-/,``);for(let r of t){let t=r.replace(/^plugin-/,``);if(r===e||t===n)return r}}function E(e,t){for(let[n,r]of e.extensionPluginRuntimeById.entries())if(w(n)===t)return D(r)?r:void 0}function D(e){return typeof e==`object`&&!!e}function O(e){return typeof e==`object`&&!!e}function k(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}function A(e,t){let n=e[t];return typeof n==`string`?n:void 0}var j=class{generateFridaHookScript(e,t){let n=t?.includeArgs??!0,r=t?.includeRetAddr??!1,i=[`'use strict';`,``,`function resolveTarget(name) {`,` try {`,` const exported = Module.findExportByName(null, name);`,` if (exported) {`,` return exported;`,` }`,` } catch (error) {}`,` try {`,` const symbol = DebugSymbol.fromName(name);`,` if (symbol && symbol.address) {`,` return symbol.address;`,` }`,` } catch (error) {}`,` return null;`,`}`,``,`const installedHooks = [];`];for(let t=0;t<e.length;t+=1){let a=this.toDescriptor(e[t]),o=`target_${t}`,s=a.demangled??a.name,c=a.address?`const ${o} = ptr("${this.escapeForDoubleQuotes(a.address)}");`:`const ${o} = resolveTarget("${this.escapeForDoubleQuotes(a.name)}");`;i.push(c),i.push(`if (${o}) {`),i.push(` Interceptor.attach(${o}, {`),i.push(` onEnter(args) {`),r?i.push(` console.log("[binary-instrument] enter ${this.escapeForDoubleQuotes(s)} ret=" + this.returnAddress);`):i.push(` console.log("[binary-instrument] enter ${this.escapeForDoubleQuotes(s)}");`),n&&(i.push(` const renderedArgs = [];`),i.push(` for (let i = 0; i < 6; i += 1) {`),i.push(` try {`),i.push(` renderedArgs.push(String(args[i]));`),i.push(` } catch (error) {`),i.push(` renderedArgs.push("<unreadable>");`),i.push(` }`),i.push(` }`),i.push(` console.log("[binary-instrument] args " + JSON.stringify(renderedArgs));`)),i.push(` },`),i.push(` onLeave(retval) {`),i.push(` console.log("[binary-instrument] leave ${this.escapeForDoubleQuotes(s)} retval=" + retval);`),i.push(` },`),i.push(` });`),i.push(` installedHooks.push({ name: "${this.escapeForDoubleQuotes(s)}", address: String(${o}) });`),i.push(`} else {`),i.push(` console.log("[binary-instrument] unresolved ${this.escapeForDoubleQuotes(s)}");`),i.push(`}`),i.push(``)}return i.push(`console.log("[binary-instrument] hooks=" + JSON.stringify(installedHooks));`),i.join(`
7
- `)}generateInterceptorScript(e){return this.generateFridaHookScript(e,{includeArgs:!0,includeRetAddr:!1})}toDescriptor(e){return typeof e==`string`?{name:e}:e}escapeForDoubleQuotes(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}},M=class{sessions=new Map;close(){for(let e of this.sessions.values())if(e.childProcess)try{process.kill(e.childProcess.pid,`SIGTERM`)}catch{}this.sessions.clear()}async launch(e,n=`arm`,r){let o=r??process.env.UNIDBG_JAR;if(!o)throw new s(`UNIDBG_JAR is not configured. Set the UNIDBG_JAR env var or pass jarPath.`);try{await p(o)}catch{throw new a(`NOT_FOUND`,`Unidbg JAR not found: ${o}`)}try{await p(e)}catch{throw new a(`NOT_FOUND`,`Shared library not found: ${e}`)}let c=l(),u=this.getJavaCommand(),d=[`-jar`,o,`--so`,e,`--arch`,n,`--server`];try{let t=await this.execFileUtf8(u,d,i),r=this.parseLaunchOutput(t.stdout,c),a={id:r.id,soPath:e,arch:n,startedAt:new Date().toISOString(),childProcess:r.pid?{pid:r.pid}:void 0};return this.sessions.set(c,a),{sessionId:c,soPath:e,arch:n}}catch(r){let i=r instanceof Error?r.message:String(r);t.warn(`[binary-instrument] Unidbg launch failed, registering stub session`,{soPath:e,message:i});let a={id:c,soPath:e,arch:n,startedAt:new Date().toISOString()};return this.sessions.set(c,a),{sessionId:c,soPath:e,arch:n}}}async callFunction(e,t,n={}){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let r=process.env.UNIDBG_JAR;if(!r)return{sessionId:e,functionName:t,args:n,returnValue:`0x0`,stdout:``,stderr:``,trace:[`mock-unidbg-unavailable`],_note:`Unidbg emulation requires UNIDBG_JAR to be configured`};let o=this.getJavaCommand(),s=[`-jar`,r,`--session`,e,`--call`,t,`--args`,JSON.stringify(n)];try{let r=await this.execFileUtf8(o,s,i);return{sessionId:e,functionName:t,args:n,returnValue:this.extractReturnValue(r.stdout),stdout:r.stdout.trim(),stderr:r.stderr.trim(),trace:[]}}catch(r){return{sessionId:e,functionName:t,args:n,returnValue:`0x0`,stdout:``,stderr:r instanceof Error?r.message:String(r),trace:[`error`]}}}async trace(e){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let t=process.env.UNIDBG_JAR;if(!t)return{sessionId:e,trace:[`mock-unidbg-unavailable`],_note:`Unidbg tracing requires UNIDBG_JAR to be configured`};let n=this.getJavaCommand(),r=[`-jar`,t,`--session`,e,`--trace`];try{let t=await this.execFileUtf8(n,r,i);return{sessionId:e,trace:this.parseTraceOutput(t.stdout),instructionCount:this.countInstructions(t.stdout)}}catch(t){return{sessionId:e,trace:[`error`],error:t instanceof Error?t.message:String(t)}}}getSessionInfo(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,soPath:e.soPath,arch:e.arch,startedAt:e.startedAt}))}getJavaCommand(){return process.env.JAVA_HOME?`${process.env.JAVA_HOME}/bin/java`:`java`}parseLaunchOutput(e,t){let n=e.split(/\r?\n/).filter(e=>e.trim().length>0);for(let e of n.toReversed())try{let t=JSON.parse(e);if(typeof t.id==`string`)return{id:t.id,pid:typeof t.pid==`number`?t.pid:null}}catch{}return{id:t,pid:null}}extractReturnValue(e){let t=/return[=:\s]+(0x[0-9a-fA-F]+|-?\d+)/.exec(e);return t?.[1]?t[1]:`0x0`}parseTraceOutput(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`{`)).slice(0,1e4)}countInstructions(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`{`)&&/\b(ldr|str|mov|bl|b|add|sub)\b/i.test(e)).length}async execFileUtf8(e,t,n){return new Promise((r,i)=>{v(e,t,{timeout:n,windowsHide:!0,maxBuffer:8388608,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``,exitCode:0})})})}},N=e({GhidraAnalyzer:()=>b,HookGenerator:()=>j});export{S as a,y as c,C as i,M as n,x as o,j as r,b as s,N as t};
@@ -1,11 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{C as t,D as n,E as r,Nn as i,O as a,S as o,T as s,k as c,w as l,x as u}from"./constants-Cp6hBrrx.mjs";import{t as d}from"./DetailedDataManager-BniBJlVv.mjs";import{t as f}from"./response-C7rKQst4.mjs";import{t as p}from"./ToolError-DWU_z7gp.mjs";import{a as m,n as h,o as g}from"./modules-p-PUNv9r.mjs";import{c as _,l as v,o as y,s as b,u as x}from"./outputPaths-BonGThuc.mjs";import{t as ee}from"./PrerequisiteError-Bl3dK8XA.mjs";import{n as te,t as ne}from"./betterSqlite3-CGaxz4AX.mjs";import{t as re}from"./concurrency-CcK46d0h.mjs";import{a as S,i as C,n as w,o as T,r as E,s as D,t as O}from"./parse-args-Cuk7-xUt.mjs";import{c as ie}from"./PageController-D9jVkH0i.mjs";import{n as ae}from"./capabilities-DbYCv-HF.mjs";import"./definitions-CoQFbggH.mjs";import{t as k}from"./ResponseBuilder-B2lu4KEl.mjs";import{join as oe}from"path";import{randomUUID as se}from"node:crypto";import{readFile as ce,writeFile as le}from"fs/promises";const A=oe(x,`.env`),ue=new Set([`stable`,`beta`,`dev`,`canary`]);var de=class{deps;constructor(e){this.deps=e}markMonitoringContextChanged(t){try{this.deps.consoleMonitor.markContextChanged()}catch(n){e.warn(`[${t}] Failed to mark monitoring context as stale: ${n instanceof Error?n.message:String(n)}`)}}async syncTabRegistryWithCollectorPages(t){try{let e=await this.deps.collector.listPages();this.deps.getTabRegistry().reconcilePages(e.map(()=>null),e)}catch(n){e.warn(`[${t}] Failed to sync attached tabs into TabRegistry: ${n instanceof Error?n.message:String(n)}`)}}parseHeadlessArg(e){if(typeof e==`boolean`)return e;if(typeof e==`number`)return e===1?!0:e===0?!1:void 0;if(typeof e==`string`){let t=e.trim().toLowerCase();if([`true`,`1`,`yes`,`on`].includes(t))return!0;if([`false`,`0`,`no`,`off`].includes(t))return!1}}parseChromeConnectRequest(e){let t=S(e,`channel`);if(t&&!ue.has(t))throw Error(`Invalid channel "${t}". Expected one of: stable, beta, dev, canary.`);return{browserURL:S(e,`browserURL`),wsEndpoint:S(e,`wsEndpoint`),autoConnect:O(e,`autoConnect`),userDataDir:S(e,`userDataDir`),channel:t}}parseChromeLaunchRequest(e){return{headless:this.parseHeadlessArg(e.headless),args:T(e,`args`),enableV8NativesSyntax:O(e,`enableV8NativesSyntax`)}}hasChromeConnectRequest(e){return!!(e.browserURL||e.wsEndpoint||e.autoConnect||e.userDataDir||e.channel)}describeChromeConnectRequest(e){return e.wsEndpoint?e.wsEndpoint:e.browserURL?e.browserURL:e.userDataDir?`autoConnect:${e.userDataDir}`:`autoConnect:${e.channel??`stable`}`}isAutoConnectRequest(e){return!!(e.autoConnect||e.userDataDir||e.channel)}getAutoConnectApprovalHint(e){return this.isAutoConnectRequest(e)?`Chrome 144+ autoConnect may prompt for manual approval. Switch to Chrome and click Allow for this client if prompted.`:null}shouldAttemptLinuxHeadfulFallback(e,t){let n=e===!1||e===void 0&&process.env.PUPPETEER_HEADLESS===`false`,r=process.platform===`linux`||process.env.JSHOOK_FORCE_LINUX_FALLBACK===`true`;if(!n||!r)return!1;let i=t instanceof Error?t.message:String(t);return/Missing X server|cannot open display|Failed to launch the browser process|ozone|No protocol specified|X11|Wayland|DevToolsActivePort/i.test(i)}async persistHeadlessEnv(t){try{let e=``;try{e=await ce(A,`utf-8`)}catch(e){if(e?.code!==`ENOENT`)throw e}let n=`PUPPETEER_HEADLESS=${t}`;await le(A,/^PUPPETEER_HEADLESS=.*$/m.test(e)?e.replace(/^PUPPETEER_HEADLESS=.*$/m,n):`${e.trimEnd()}\n${n}\n`,`utf-8`)}catch(n){e.warn(`Failed to persist PUPPETEER_HEADLESS=${t} to .env: ${String(n)}`)}}async handleBrowserLaunch(t){try{if(S(t,`driver`,`chrome`)===`camoufox`){if(S(t,`mode`,`launch`)===`connect`){let e=S(t,`wsEndpoint`);return e?k.ok().merge({driver:`camoufox`,mode:`connect`,wsEndpoint:e,message:`Connected to Camoufox server. Use page_navigate to begin.`}).json():k.fail(`wsEndpoint is required for connect mode. Use camoufox_server({ action: "launch" }) first to get a wsEndpoint.`).json()}return k.ok().merge({driver:`camoufox`,mode:`launch`,message:`Camoufox (Firefox) browser launched`,note:`Use page_navigate to begin. CDP debugger is limited in Firefox; network_enable and console_monitor({ action: "enable" }) use Playwright events and are fully supported.`}).json()}if(S(t,`mode`,`launch`)===`connect`){let e=this.parseChromeConnectRequest(t);if(!this.hasChromeConnectRequest(e))return k.fail(`browserURL, wsEndpoint, autoConnect, userDataDir, or channel is required for chrome connect mode.`).json();await this.deps.collector.connect(e);let n=await this.deps.collector.getStatus();return k.ok().merge({driver:`chrome`,mode:`connect`,endpoint:this.describeChromeConnectRequest(e),autoConnect:this.isAutoConnectRequest(e),channel:e.channel??null,userDataDir:e.userDataDir??null,manualApprovalMayBeRequired:this.isAutoConnectRequest(e),approvalHint:this.getAutoConnectApprovalHint(e),message:`Connected to existing Chrome browser successfully`,status:n}).json()}let n=this.parseChromeLaunchRequest(t);try{let e=await this.deps.collector.launch(n);e.action===`relaunched`&&this.markMonitoringContextChanged(`browser_launch_relaunch`);let t=await this.deps.collector.listPages(),r=this.deps.getTabRegistry();t.length>0&&(await this.deps.collector.selectPage(0),r.setCurrentByIndex(0));let i=t[0],a=await this.deps.collector.getStatus();return k.ok().merge({driver:`chrome`,message:e.action===`relaunched`?`Browser relaunched successfully`:`Browser launched successfully`,launchAction:e.action,relaunchReason:e.reason??null,v8NativeSyntaxEnabled:e.launchOptions.v8NativeSyntaxEnabled,launchArgs:e.launchOptions.args,selectedIndex:t.length>0?0:null,currentUrl:i?.url??null,currentTitle:i?.title??null,totalPages:t.length,status:a}).json()}catch(t){if(!this.shouldAttemptLinuxHeadfulFallback(n.headless,t))throw t;let r=t instanceof Error?t.message:String(t);e.warn(`Headful launch failed on Linux, fallback to headless=true: ${r}`),process.env.PUPPETEER_HEADLESS=`true`,await this.persistHeadlessEnv(`true`);let i=await this.deps.collector.launch({...n,headless:!0}),a=await this.deps.collector.getStatus();return k.ok().merge({driver:`chrome`,message:`Browser launched with Linux fallback (headless=true)`,launchAction:i.action,relaunchReason:i.reason??null,v8NativeSyntaxEnabled:i.launchOptions.v8NativeSyntaxEnabled,launchArgs:i.launchOptions.args,status:a,fallback:{applied:!0,reason:`Headful browser is unavailable in current Linux runtime; switched to headless and updated .env`,newEnv:`PUPPETEER_HEADLESS=true`}}).json()}}catch(e){return k.fail(e).json()}}async handleBrowserClose(e){try{return await this.deps.collector.close(),k.ok().set(`message`,`Browser closed successfully`).json()}catch(e){return k.fail(e).json()}}async handleBrowserStatus(e){try{let e=await this.deps.collector.getStatus();return k.ok().merge({driver:`chrome`,...e}).json()}catch(e){return k.fail(e).json()}}async handleBrowserListTabs(e){let t=this.parseChromeConnectRequest(e);try{this.hasChromeConnectRequest(t)&&await this.deps.collector.connect(t);let e=await this.deps.collector.listPages(),n=this.deps.getTabRegistry();await this.syncTabRegistryWithCollectorPages(`browser_list_tabs`);let r=e.map(e=>{let t=n.getTabByIndex(e.index);return{...e,pageId:t?.pageId??null,aliases:t?.aliases??[]}}),i=n.getContextMeta();return k.ok().merge({count:e.length,pages:r,currentPageId:i.pageId,currentIndex:i.tabIndex,autoConnect:this.isAutoConnectRequest(t),manualApprovalMayBeRequired:this.isAutoConnectRequest(t),approvalHint:this.getAutoConnectApprovalHint(t),hint:`Use browser_select_tab(index=N) to switch to a specific tab`}).json()}catch(e){return k.fail(e).set(`hint`,`Make sure browser is attached via browser_attach first, or provide browserURL/autoConnect. Chrome 144+ autoConnect may require manual approval in the Chrome window.`).set(`approvalHint`,this.getAutoConnectApprovalHint(t)).json()}}async handleBrowserSelectTab(e){try{let t=E(e,`index`),n=S(e,`urlPattern`),r=S(e,`titlePattern`),i=this.deps.getTabRegistry();if(t!==void 0){let e=await this.deps.clearAttachedTargetContext(`browser_select_tab`);await this.deps.collector.selectPage(t);let n=await this.deps.collector.listPages();await this.syncTabRegistryWithCollectorPages(`browser_select_tab`);let r=n[t],a=i.setCurrentByIndex(t);return(a?.pageId||e.detached)&&this.markMonitoringContextChanged(`browser_select_tab`),k.ok().merge({selectedIndex:t,selectedPageId:a?.pageId??null,url:r?.url,title:r?.title,contextSwitched:!0,detachedCdpTarget:e.detached,detachedCdpTargetId:e.targetId,monitoringBindingDeferred:!!a?.pageId,networkMonitoringEnabled:!1,consoleMonitoringEnabled:!1}).json()}let a=await this.deps.collector.listPages(),o=-1;for(let e of a){if(n&&e.url.includes(n)){o=e.index;break}if(r&&e.title.includes(r)){o=e.index;break}}if(o===-1)return k.fail(`No matching tab found`).set(`availablePages`,a).json();let s=await this.deps.clearAttachedTargetContext(`browser_select_tab`);await this.deps.collector.selectPage(o),await this.syncTabRegistryWithCollectorPages(`browser_select_tab`);let c=a[o],l=i.setCurrentByIndex(o);return(l?.pageId||s.detached)&&this.markMonitoringContextChanged(`browser_select_tab`),k.ok().merge({selectedIndex:o,selectedPageId:l?.pageId??null,url:c?.url,title:c?.title,contextSwitched:!0,detachedCdpTarget:s.detached,detachedCdpTargetId:s.targetId,monitoringBindingDeferred:!!l?.pageId,networkMonitoringEnabled:!1,consoleMonitoringEnabled:!1}).json()}catch(e){return k.fail(e).json()}}async handleBrowserAttach(t){let n=null;try{if(n=this.parseChromeConnectRequest(t),!this.hasChromeConnectRequest(n))return k.fail(`browserURL, wsEndpoint, autoConnect, userDataDir, or channel is required`).json();let r=await this.deps.clearAttachedTargetContext(`browser_attach`);await this.deps.collector.connect(n);let i=t.pageIndex,a=typeof i==`number`?i:typeof i==`string`&&i.trim()!==``?Number(i):0,o=Number.isFinite(a)?a:0,s=await this.deps.collector.listPages();s.length>0&&o<s.length?await this.deps.collector.selectPage(o):s.length>0&&(await this.deps.collector.selectPage(0),e.warn(`[browser_attach] pageIndex ${o} out of range (0-${s.length-1}), fell back to 0`));let c=this.deps.getTabRegistry();await this.syncTabRegistryWithCollectorPages(`browser_attach`);let l=s.length>0?Math.min(o,s.length-1):0,u=s.length>0?c.setCurrentByIndex(l):null,d=s[l],f=!!u?.pageId;f&&this.markMonitoringContextChanged(`browser_attach`);let p=await this.deps.collector.getStatus();return k.ok().merge({message:`Attached to existing browser successfully`,endpoint:this.describeChromeConnectRequest(n),autoConnect:this.isAutoConnectRequest(n),channel:n.channel??null,userDataDir:n.userDataDir??null,manualApprovalMayBeRequired:this.isAutoConnectRequest(n),approvalHint:this.getAutoConnectApprovalHint(n),selectedIndex:l,selectedPageId:u?.pageId??null,currentUrl:d?.url??null,currentTitle:d?.title??null,totalPages:s.length,contextSwitched:s.length>0,detachedCdpTarget:r.detached,detachedCdpTargetId:r.targetId,monitoringBindingDeferred:f,networkMonitoringEnabled:!1,consoleMonitoringEnabled:!1,takeoverReady:f,note:f?`Monitoring will auto-rebind on the next console/network operation for the selected tab.`:`Connected to existing Chrome, but the selected tab does not currently expose a stable Puppeteer Page handle. Tab discovery still works; try selecting a different tab or navigate the tab and retry.`,status:p}).json()}catch(e){return k.fail(e).set(`approvalHint`,this.getAutoConnectApprovalHint(n??{})).json()}}};function fe(e){let t=T(e,`addons`),n=T(e,`excludeAddons`),r=T(e,`fonts`);return{headless:O(e,`headless`,!0),os:S(e,`os`,`windows`),geoip:O(e,`geoip`,!1),humanize:O(e,`humanize`,!1),proxy:S(e,`proxy`)||void 0,blockImages:O(e,`blockImages`,!1),blockWebrtc:O(e,`blockWebrtc`,!1),blockWebgl:O(e,`blockWebgl`,!1),locale:S(e,`locale`)||void 0,addons:t.length>0?t:void 0,fonts:r.length>0?r:void 0,excludeAddons:n.length>0?n:void 0,customFontsOnly:O(e,`customFontsOnly`,!1),screen:e.screen,window:e.window,fingerprint:C(e,`fingerprint`),webglConfig:C(e,`webglConfig`),firefoxUserPrefs:C(e,`firefoxUserPrefs`),mainWorldEval:O(e,`mainWorldEval`,!0),enableCache:O(e,`enableCache`,!1)}}async function pe(){try{return await import(`camoufox-js`),null}catch(e){let t=e instanceof Error?e.message:String(e);return te(e)?`Camoufox requires the same native SQLite backend used by trace tooling. ${ne(e)}`:t.includes(`Cannot find package 'camoufox-js'`)?`camoufox-js package is not installed. Run: pnpm add camoufox-js && npx camoufox-js fetch`:`Camoufox dependencies check failed: ${t}`}}var me=class{deps;constructor(e){this.deps=e}async handleCamoufoxServerLaunch(t){try{let n=await pe();if(n)return e.warn(`Camoufox dependencies not available: ${n}`),k.fail(n).set(`hint`,`Camoufox is optional. Use browser_launch with Chrome driver instead, or install dependencies.`).json();let r=E(t,`port`),i=S(t,`ws_path`),a=fe(t),o=this.deps.getCamoufoxManager();o||(o=new g(a),this.deps.setCamoufoxManager(o));let s=await o.launchAsServer(r,i);return k.ok().merge({wsEndpoint:s,config:{os:a.os,headless:a.headless,geoip:a.geoip,locale:a.locale,blockWebgl:a.blockWebgl},message:`Camoufox server launched. Connect with: browser_launch(driver="camoufox", mode="connect", wsEndpoint=<wsEndpoint>)`}).json()}catch(e){return k.fail(e).set(`hint`,`Try running: npx camoufox-js fetch to download browser binaries`).json()}}async handleCamoufoxServerClose(e){try{let e=this.deps.getCamoufoxManager();return e?(await e.closeBrowserServer(),k.ok().set(`message`,`Camoufox server closed.`).json()):k.fail(`No camoufox server is running.`).json()}catch(e){return k.fail(e).json()}}async handleCamoufoxServerStatus(e){try{let e=this.deps.getCamoufoxManager()?.getBrowserServerEndpoint()??null;return k.ok().merge({running:e!==null,wsEndpoint:e}).json()}catch(e){return k.fail(e).json()}}};const he=new Set(ie);function j(e){return w(e,`waitUntil`,he,`networkidle`)}var ge=class{deps;constructor(e){this.deps=e}syncCurrentTabMeta(e,t){let n=this.deps.getTabRegistry?.();if(!n||!e||!t.url||t.title===void 0)return;let r=t.url,i=t.title,a=n.upsertPage(e,{url:r,title:i});n.setCurrentPageId(a)}async getChromePageIfAvailable(){let e=this.deps.pageController.getPage;return typeof e==`function`?await Reflect.apply(e,this.deps.pageController,[]):null}async getCamoufoxTitleIfAvailable(e){let t=e.title;if(typeof t!=`function`)return;let n=await Reflect.apply(t,e,[]);return typeof n==`string`?n:void 0}getCamoufoxUrlIfAvailable(e){let t=e.url;if(typeof t!=`function`)return;let n=Reflect.apply(t,e,[]);return typeof n==`string`?n:void 0}async handlePageNavigate(e){try{let t=S(e,`url`,``),n=j(e),r=E(e,`timeout`),i=O(e,`enableNetworkMonitoring`);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.goto(t,{waitUntil:n,timeout:r}),this.deps.consoleMonitor.setPlaywrightPage(e),i&&await this.deps.consoleMonitor.enable({enableNetwork:!0,enableExceptions:!0});let a=this.getCamoufoxUrlIfAvailable(e)??``,o=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:a,title:o}),this.deps.eventBus?.emit(`browser:navigated`,{url:a,timestamp:new Date().toISOString()}),k.ok().build({driver:`camoufox`,url:a,title:o??``,network_monitoring:{enabled:this.deps.consoleMonitor.isNetworkEnabled()}})}i&&await this.deps.consoleMonitor.enable({enableNetwork:!0,enableExceptions:!0}),await this.deps.pageController.navigate(t,{waitUntil:n,timeout:r});let a=await this.getChromePageIfAvailable(),o=await this.deps.pageController.getURL(),s=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(a,{url:o,title:s}),this.deps.eventBus?.emit(`browser:navigated`,{url:o,timestamp:new Date().toISOString()}),k.ok().build({url:o,title:s,network_monitoring:{enabled:this.deps.consoleMonitor.isNetworkEnabled()}})}catch(e){return k.fail(e).build()}}async handlePageReload(e){try{if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();return await e.reload(),this.syncCurrentTabMeta(e,{url:this.getCamoufoxUrlIfAvailable(e),title:await this.getCamoufoxTitleIfAvailable(e)}),k.ok().build({message:`Page reloaded`,driver:`camoufox`})}await this.deps.pageController.reload();let e=await this.getChromePageIfAvailable();return this.syncCurrentTabMeta(e,{url:await this.deps.pageController.getURL(),title:await this.deps.pageController.getTitle()}),k.ok().build({message:`Page reloaded`})}catch(e){return k.fail(e).build()}}async handlePageBack(e){try{let t=E(e,`timeout`,1e4);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();return await e.goBack(),this.syncCurrentTabMeta(e,{url:this.getCamoufoxUrlIfAvailable(e),title:await this.getCamoufoxTitleIfAvailable(e)}),k.ok().build({url:this.getCamoufoxUrlIfAvailable(e),driver:`camoufox`})}await this.deps.pageController.goBack(t);let n=await this.getChromePageIfAvailable(),r=await this.deps.pageController.getURL();return this.syncCurrentTabMeta(n,{url:r,title:await this.deps.pageController.getTitle()}),k.ok().build({url:r})}catch(e){return k.fail(e).build()}}async handlePageForward(e){try{let t=E(e,`timeout`,1e4);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();return await e.goForward(),this.syncCurrentTabMeta(e,{url:this.getCamoufoxUrlIfAvailable(e),title:await this.getCamoufoxTitleIfAvailable(e)}),k.ok().build({url:this.getCamoufoxUrlIfAvailable(e),driver:`camoufox`})}await this.deps.pageController.goForward(t);let n=await this.getChromePageIfAvailable(),r=await this.deps.pageController.getURL();return this.syncCurrentTabMeta(n,{url:r,title:await this.deps.pageController.getTitle()}),k.ok().build({url:r})}catch(e){return k.fail(e).build()}}},_e=class{deps;constructor(e){this.deps=e}toErrorMessage(e){return e instanceof Error?e.message:typeof e==`string`?e:``}parseNumberArg(e,t={}){let n;if(typeof e==`number`&&Number.isFinite(e))n=e;else if(typeof e==`string`){let t=e.trim();if(t.length>0){let e=Number(t);Number.isFinite(e)&&(n=e)}}if(n===void 0&&(n=t.defaultValue),n!==void 0)return t.integer&&(n=Math.trunc(n)),typeof t.min==`number`&&(n=Math.max(t.min,n)),typeof t.max==`number`&&(n=Math.min(t.max,n)),n}parseMouseButton(e){if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`left`||t===`right`||t===`middle`)return t}return`left`}async getCamoufoxInteractionContext(e){let t=await this.deps.getCamoufoxPage();return!e?.frameUrl&&!e?.frameSelector?t:await this.deps.pageController.resolveFrame(t,e)}async handlePageClick(e){try{let t=S(e,`selector`,``),n=this.parseMouseButton(e.button),r=this.parseNumberArg(e.clickCount,{defaultValue:1,min:1,max:10,integer:!0}),i=this.parseNumberArg(e.delay,{min:0,max:6e4,integer:!0}),a=this.parseNumberArg(e.timeout,{defaultValue:1e4,min:1e3,max:12e4,integer:!0}),o=S(e,`frameUrl`),s=S(e,`frameSelector`),c=o||s?{frameUrl:o||void 0,frameSelector:s||void 0}:void 0;if(!t||typeof t!=`string`||t.trim().length===0)return k.fail(`selector parameter is required`).build();if(this.deps.getActiveDriver()===`camoufox`)return await(await this.getCamoufoxInteractionContext(c)).click(t,{button:n,clickCount:r,delay:i}),k.ok().build({driver:`camoufox`,message:`Clicked: ${t}`,...c?{frame:c}:{}});try{c?await this.deps.pageController.click(t,{button:n,clickCount:r,delay:i,timeout:a},c):await this.deps.pageController.click(t,{button:n,clickCount:r,delay:i,timeout:a})}catch(e){let n=this.toErrorMessage(e);if(n.includes(`detached`)||n.includes(`timed out`)||n.includes(`Execution context was destroyed`)||n.includes(`callFunctionOn`)||n.includes(`Target closed`))return k.ok().build({message:`Clicked ${t} - navigation triggered`,navigated:!0,...c?{frame:c}:{}});throw e}return k.ok().build({message:`Clicked: ${t}`,...c?{frame:c}:{}})}catch(e){return k.fail(e).build()}}async handlePageType(e){try{let t=S(e,`selector`,``),n=S(e,`text`,``),r=E(e,`delay`),i=S(e,`frameUrl`),a=S(e,`frameSelector`),o=i||a?{frameUrl:i||void 0,frameSelector:a||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(o)).fill(t,n),k.ok().build({driver:`camoufox`,message:`Typed into ${t}`,...o?{frame:o}:{}})):(o?await this.deps.pageController.type(t,n,{delay:r},o):await this.deps.pageController.type(t,n,{delay:r}),k.ok().build({message:`Typed into ${t}`,...o?{frame:o}:{}}))}catch(e){return k.fail(e).build()}}async handlePageUploadFiles(e){try{let t=S(e,`selector`,``),n=T(e,`paths`).map(e=>e.trim()).filter(Boolean),r=S(e,`frameUrl`),i=S(e,`frameSelector`),a=r||i?{frameUrl:r||void 0,frameSelector:i||void 0}:void 0;if(!t||t.trim().length===0)return k.fail(`selector parameter is required`).build();if(n.length===0)return k.fail(`paths parameter must contain at least one relative file path`).build();let o=n.map(e=>b(e));if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage(),r=await(a?await this.deps.pageController.resolveFrame(e,a):e).$(t);return!r||typeof r.setInputFiles!=`function`?k.fail(`File input not found: ${t}`).build({driver:`camoufox`}):(await r.setInputFiles(o),k.ok().build({driver:`camoufox`,selector:t,count:o.length,paths:n,message:`Uploaded ${o.length} file(s) into ${t}`,...a?{frame:a}:{}}))}return await this.deps.pageController.uploadFile(t,o,a),k.ok().build({selector:t,count:o.length,paths:n,message:`Uploaded ${o.length} file(s) into ${t}`,...a?{frame:a}:{}})}catch(e){return k.fail(e).build()}}async handlePageSelect(e){try{let t=S(e,`selector`,``),n=T(e,`values`),r=S(e,`frameUrl`),i=S(e,`frameSelector`),a=r||i?{frameUrl:r||void 0,frameSelector:i||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(a)).selectOption(t,n),k.ok().build({driver:`camoufox`,message:`Selected in ${t}: ${n.join(`, `)}`,...a?{frame:a}:{}})):(a?await this.deps.pageController.select(t,n,a):await this.deps.pageController.select(t,n),k.ok().build({message:`Selected in ${t}: ${n.join(`, `)}`,...a?{frame:a}:{}}))}catch(e){return k.fail(e).build()}}async handlePageHover(e){try{let t=S(e,`selector`,``),n=S(e,`frameUrl`),r=S(e,`frameSelector`),i=n||r?{frameUrl:n||void 0,frameSelector:r||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(i)).hover(t),k.ok().build({driver:`camoufox`,message:`Hovered: ${t}`,...i?{frame:i}:{}})):(i?await this.deps.pageController.hover(t,i):await this.deps.pageController.hover(t),k.ok().build({message:`Hovered: ${t}`,...i?{frame:i}:{}}))}catch(e){return k.fail(e).build()}}async handlePageScroll(e){try{let t=E(e,`x`,0),n=E(e,`y`,0);return this.deps.getActiveDriver()===`camoufox`?(await(await this.deps.getCamoufoxPage()).evaluate(e=>{window.scrollTo(e.x||0,e.y||0)},{x:t,y:n}),k.ok().build({driver:`camoufox`,message:`Scrolled to: x=${t||0}, y=${n||0}`})):(await this.deps.pageController.scroll({x:t,y:n}),k.ok().build({message:`Scrolled to: x=${t||0}, y=${n||0}`}))}catch(e){return k.fail(e).build()}}async handlePagePressKey(e){try{let t=S(e,`key`,``);return this.deps.getActiveDriver()===`camoufox`?(await(await this.deps.getCamoufoxPage()).keyboard.press(t),k.ok().build({driver:`camoufox`,key:t})):(await this.deps.pageController.pressKey(t),k.ok().build({key:t}))}catch(e){return k.fail(e).build()}}};function M(e,t){if(Array.isArray(e))return e.map(e=>M(e,t));if(typeof e==`object`&&e){let n=e,r={};for(let[e,i]of Object.entries(n))t.has(e)||(r[e]=M(i,t));return r}return e}function N(e){if(typeof e==`string`)return/^data:[a-z+-]+\/[a-z+-]+;base64,/i.test(e)?`[base64 ~${Math.round(e.length/1024)}KB stripped]`:e.length>500&&/^[A-Za-z0-9+/=\r\n]+$/.test(e.replace(/\s/g,``))?`[base64 ~${e.length}chars stripped]`:e;if(Array.isArray(e))return e.map(e=>N(e));if(typeof e==`object`&&e){let t=e,n={};for(let[e,r]of Object.entries(t))n[e]=N(r);return n}return e}function P(e,t,n){let r=n.autoSummarize?t.smartHandle(e,n.maxSize):e;return n.fieldFilter&&n.fieldFilter.length>0&&(r=M(r,new Set(n.fieldFilter))),n.stripBase64&&(r=N(r)),r}var ve=class{deps;constructor(e){this.deps=e}resolveEvaluationSource(e){let t=S(e,`script`,``)||S(e,`code`,``)||S(e,`expression`,``);return t.trim()?t:null}async getCamoufoxEvaluationContext(e){let t=await this.deps.getCamoufoxPage();return!e?.frameUrl&&!e?.frameSelector?t:await this.deps.pageController.resolveFrame(t,e)}async handlePageEvaluate(e){try{let t=this.resolveEvaluationSource(e),n=O(e,`autoSummarize`,!0),r=E(e,`maxSize`,51200),i=T(e,`fieldFilter`),a=O(e,`stripBase64`,!1),o=S(e,`frameUrl`),s=S(e,`frameSelector`);if(!t)return k.fail(`code, script, or expression is required`).build();let c=o||s?{frameUrl:o||void 0,frameSelector:s||void 0}:void 0;if(this.deps.getActiveDriver()===`camoufox`){let e=await this.getCamoufoxEvaluationContext(c),o=Function(`return (${t})`),s=P(await e.evaluate(o),this.deps.detailedDataManager,{autoSummarize:n,maxSize:r,fieldFilter:i??void 0,stripBase64:a});return k.ok().build({driver:`camoufox`,...c?{frame:c}:{},result:s})}let l=P(c?await this.deps.pageController.evaluate(t,c):await this.deps.pageController.evaluate(t),this.deps.detailedDataManager,{autoSummarize:n,maxSize:r,fieldFilter:i??void 0,stripBase64:a});return k.ok().build({...c?{frame:c}:{},result:l})}catch(e){return k.fail(e).build()}}async handlePageScreenshot(e){try{let t=S(e,`path`),n=S(e,`type`,`png`),r=E(e,`quality`),i=O(e,`fullPage`,!1),a=C(e,`clip`),o=e.selector,s=[];if(Array.isArray(o))for(let e of o){let t=typeof e==`string`?e.trim():``;t.length>0&&t.toLowerCase()!==`all`&&s.push(t)}else if(typeof o==`string`){let e=o.trim();e.length>0&&e.toLowerCase()!==`all`&&s.push(e)}if(s.length>1)return this.screenshotBatch(s,t,n,r);let c=s[0]??``,{absolutePath:l,displayPath:u,pathRewritten:d}=await _({requestedPath:t,type:n,fallbackName:c?`element`:a?`region`:`page`,fallbackDir:`screenshots/manual`});if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage(),t;if(c){let i=await e.$(c);if(!i)return k.fail(`Element not found: ${c}`).build();t=await i.screenshot({path:l,type:n,quality:r})}else t=await e.screenshot({path:l,type:n,quality:r,fullPage:a?!1:i});return k.ok().build({driver:`camoufox`,selector:c||void 0,clip:a||void 0,message:`Screenshot taken: ${u}`,path:u,pathRewritten:d,size:t?.length??0})}let f;if(c){let e=await(await this.deps.pageController.getPage()).$(c);if(!e)return k.fail(`Element not found: ${c}`).build();f=await e.screenshot({path:l,type:n,quality:r})}else f=await this.deps.pageController.screenshot({path:l,type:n,quality:r,fullPage:a?!1:i,clip:a});return k.ok().build({selector:c||void 0,clip:a||void 0,message:`Screenshot taken: ${u}`,path:u,pathRewritten:d,size:f.length})}catch(e){return k.fail(e).build()}}async screenshotBatch(e,t,n,r){let i=this.deps.getActiveDriver()===`camoufox`,a=[];for(let o of e){let{absolutePath:e,displayPath:s}=await _({requestedPath:t?t.replace(/(\.\w+)$/,`-${o.replace(/[^a-zA-Z0-9]/g,`_`)}$1`):void 0,type:n,fallbackName:`element-${o.replace(/[^a-zA-Z0-9]/g,`_`)}`,fallbackDir:`screenshots/manual`});try{let t=0;if(i){let i=await(await this.deps.getCamoufoxPage()).$(o);if(!i){a.push({selector:o,success:!1,error:`Element not found: ${o}`});continue}t=(await i.screenshot({path:e,type:n,quality:r}))?.length??0}else{let i=await(await this.deps.pageController.getPage()).$(o);if(!i){a.push({selector:o,success:!1,error:`Element not found: ${o}`});continue}t=(await i.screenshot({path:e,type:n,quality:r})).length}a.push({selector:o,success:!0,path:s,size:t})}catch(e){a.push({selector:o,success:!1,error:String(e)})}}return k.ok().build({mode:`batch`,total:e.length,succeeded:a.filter(e=>e.success).length,results:a})}async handlePageInjectScript(e){try{let t=S(e,`script`,``);return await this.deps.pageController.injectScript(t),k.ok().build({message:`Script injected`})}catch(e){return k.fail(e).build()}}async handlePageWaitForSelector(e){try{let t=S(e,`selector`,``),n=E(e,`timeout`);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();try{await e.waitForSelector(t,{timeout:n||3e4});let r=await e.evaluate(e=>{let t=document.querySelector(e);return t?{tagName:t.tagName.toLowerCase(),id:t.id||void 0,className:t.className||void 0,textContent:t.textContent?.trim().substring(0,100)||void 0,attributes:Array.from(t.attributes).reduce((e,t)=>(e[t.name]=t.value,e),{})}:null},t);return k.ok().build({driver:`camoufox`,element:r,message:`Selector appeared: ${t}`})}catch{return k.fail(`Timeout waiting for selector: ${t}`).build({driver:`camoufox`})}}let r=await this.deps.pageController.waitForSelector(t,n);return k.ok().merge(r).build()}catch(e){return k.fail(e).build()}}},ye=class{deps;constructor(e){this.deps=e}safeOrigin(e){try{return new URL(e).origin}catch{return null}}async listCamoufoxFrames(){let e=this.deps.getCamoufoxPage;if(!e)throw Error(`Camoufox page is not available`);let t=await e(),n=t.frames(),r=t.mainFrame(),i=this.safeOrigin(r.url());return n.map((e,t)=>{let a=e.parentFrame(),o=this.safeOrigin(e.url()),s=a?n.findIndex(e=>e===a):-1;return{frameId:`frame-${t}`,url:e.url(),name:e.name()||``,parentFrameId:s>=0?`frame-${s}`:null,parentUrl:a?.url()||null,isMainFrame:e===r,crossOrigin:!!(e!==r&&o&&i&&o!==i)}})}async handlePageListFrames(e){try{let e=this.deps.getActiveDriver()===`camoufox`?await this.listCamoufoxFrames():await this.deps.pageController.listFrames();return k.ok().build({count:e.length,frames:e})}catch(e){return k.fail(e).build()}}async handleGetContent(e){try{let e=await this.deps.pageController.getContent();return k.ok().build({html:e})}catch(e){return k.fail(e).build()}}async handleGetTitle(e){try{let e=await this.deps.pageController.getTitle();return k.ok().build({title:e})}catch(e){return k.fail(e).build()}}async handleGetUrl(e){try{let e=await this.deps.pageController.getURL();return k.ok().build({url:e})}catch(e){return k.fail(e).build()}}async handleGetText(e){try{let t=S(e,`selector`,``),n=await this.deps.pageController.evaluate(`document.querySelector(${JSON.stringify(t)})?.textContent || ""`);return k.ok().build({selector:t,text:n})}catch(e){return k.fail(e).build()}}async handleGetOuterHtml(e){try{let t=S(e,`selector`,``),n=await this.deps.pageController.evaluate(`document.querySelector(${JSON.stringify(t)})?.outerHTML || ""`);return k.ok().build({selector:t,html:n})}catch(e){return k.fail(e).build()}}async handleGetScrollPosition(e){try{let e=await this.deps.pageController.evaluate(`({
2
- scrollX: window.scrollX,
3
- scrollY: window.scrollY,
4
- maxScrollX: document.documentElement.scrollWidth - window.innerWidth,
5
- maxScrollY: document.documentElement.scrollHeight - window.innerHeight
6
- })`);return k.ok().build(e)}catch(e){return k.fail(e).build()}}async handlePageSetCookies(e){try{let t=e.cookies;return await this.deps.pageController.setCookies(t),k.ok().build({message:`Set ${t.length} cookies`})}catch(e){return k.fail(e).build()}}async handlePageGetCookies(e){try{let e=await this.deps.pageController.getCookies();return k.ok().build({count:e.length,cookies:e})}catch(e){return k.fail(e).build()}}async getPageCookieCount(){return(await this.deps.pageController.getCookies()).length}async handlePageClearCookies(e){try{return await this.deps.pageController.clearCookies(),k.ok().build({message:`Cookies cleared`})}catch(e){return k.fail(e).build()}}async handlePageSetViewport(e){try{let t=E(e,`width`,0),n=E(e,`height`,0);return await this.deps.pageController.setViewport(t,n),k.ok().build({viewport:{width:t,height:n}})}catch(e){return k.fail(e).build()}}async handlePageEmulateDevice(e){try{let t=S(e,`device`,``);return await this.deps.pageController.emulateDevice(t),k.ok().build({device:t})}catch(e){return k.fail(e).build()}}async handlePageGetLocalStorage(e){try{let e=await this.deps.pageController.getLocalStorage();return k.ok().build({count:Object.keys(e).length,storage:e})}catch(e){return k.fail(e).build()}}async handlePageSetLocalStorage(e){try{let t=S(e,`key`,``),n=S(e,`value`,``);return await this.deps.pageController.setLocalStorage(t,n),k.ok().build({key:t})}catch(e){return k.fail(e).build()}}},be=class{deps;constructor(e){this.deps=e}async handleConsoleMonitor(e){try{return S(e,`action`)===`enable`?(await this.deps.consoleMonitor.enable(),k.ok().build({message:`Console monitoring enabled`})):(await this.deps.consoleMonitor.disable(),k.ok().build({message:`Console monitoring disabled`}))}catch(e){return k.fail(e).build()}}async handleConsoleGetLogs(e){try{let t=S(e,`type`),n=E(e,`limit`),r=E(e,`since`),i=this.deps.consoleMonitor.getLogs({type:t,limit:n,since:r}),a={count:i.length,logs:i},o=this.deps.detailedDataManager.smartHandle(a,51200);return k.ok().merge(o).build()}catch(e){return k.fail(e).build()}}async handleConsoleExecute(e){try{let t=S(e,`expression`,``),n=E(e,`maxSize`,10485760),r=O(e,`stripBase64`,!1);if(!t.trim())return k.fail(`expression is required`).build();let i=P(await this.deps.consoleMonitor.execute(t),this.deps.detailedDataManager,{autoSummarize:!0,maxSize:n,stripBase64:r});return k.ok().build({result:i})}catch(e){return k.fail(e).build()}}},xe=class{deps;constructor(e){this.deps=e}async handleGetAllScripts(e){try{let t=O(e,`includeSource`,!1),n=i,r=Math.min(E(e,`maxScripts`,t?200:1e3),n),a=await this.deps.scriptManager.getAllScripts(t,r),o={count:a.length,scripts:a},s=this.deps.detailedDataManager.smartHandle(o);return k.ok().merge(s).build()}catch(e){return k.fail(e).build()}}async handleGetScriptSource(e){try{let t=S(e,`scriptId`),n=S(e,`url`),r=O(e,`preview`,!0),i=E(e,`maxLines`,100),a=E(e,`startLine`),o=E(e,`endLine`),s=await this.deps.scriptManager.getScriptSource(t,n);if(!s)return k.fail(`Script not found`).build();if(r||a!==void 0||o!==void 0){let e=s.source||``,t=e.split(`
7
- `),n=t.length,r=e.length,c,l,u;a!==void 0&&o!==void 0?(l=Math.max(1,a),u=Math.min(n,o),c=t.slice(l-1,u).join(`
8
- `)):(l=1,u=Math.min(i,n),c=t.slice(0,i).join(`
9
- `));let d={scriptId:s.scriptId,url:s.url,preview:!0,totalLines:n,size:r,sizeKB:(r/1024).toFixed(1)+`KB`,showingLines:`${l}-${u}`,content:c,hint:r>51200?`Script is large (${(r/1024).toFixed(1)}KB). Use startLine/endLine to get specific sections, or set preview=false to get full source (will return detailId).`:`Set preview=false to get full source`};return k.ok().build(d)}let c=this.deps.detailedDataManager.smartHandle(s,51200);return k.ok().merge(c).build()}catch(e){return k.fail(e).build()}}},Se=class{deps;constructor(e){this.deps=e}async handleCaptchaDetect(e){try{let e=await this.deps.pageController.getPage(),t=await this.deps.captchaDetector.detect(e);return k.ok().build({captcha_detected:t.detected,captcha_info:t})}catch(e){return k.fail(e).build()}}async handleCaptchaWait(t){try{let n=E(t,`timeout`,this.deps.captchaTimeout),r=await this.deps.pageController.getPage();return e.info(`Waiting for CAPTCHA to be solved...`),await this.deps.captchaDetector.waitForCompletion(r,n)?k.ok().build({message:`CAPTCHA solved`}):k.fail(`CAPTCHA wait timed out`).build()}catch(e){return k.fail(e).build()}}async handleCaptchaConfig(e){try{return e.autoDetectCaptcha!==void 0&&this.deps.setAutoDetectCaptcha(O(e,`autoDetectCaptcha`,!1)),e.autoSwitchHeadless!==void 0&&this.deps.setAutoSwitchHeadless(O(e,`autoSwitchHeadless`,!1)),e.captchaTimeout!==void 0&&this.deps.setCaptchaTimeout(E(e,`captchaTimeout`,0)),k.ok().build({config:{autoDetectCaptcha:this.deps.autoDetectCaptcha,autoSwitchHeadless:this.deps.autoSwitchHeadless,captchaTimeout:this.deps.captchaTimeout}})}catch(e){return k.fail(e).build()}}};const Ce={enabled:!0,minDelayMs:20,maxDelayMs:80,burstMode:!1};var we=class t{static instance=null;cachedProfile=null;static DEFAULT_TTL_SEC=1800;static getInstance(){return t.instance||=new t,t.instance}async exportFromPage(n,r={}){let i=await n.cookies(),a=await n.evaluate(()=>{let e=navigator,t=e.userAgentData,n={secChUa:Array.isArray(t?.brands)?t.brands.map(e=>`"${e.brand}";v="${e.version}"`).join(`, `):void 0,secChUaMobile:typeof t?.mobile==`boolean`?t.mobile?`?1`:`?0`:void 0,secChUaPlatform:t?.platform?`"${t.platform}"`:void 0};return{userAgent:e.userAgent,platform:e.platform,acceptLanguage:e.language,referer:document.referrer||void 0,clientHints:n}}),o=r.origin??this.safeOrigin(n.url()),s=r.ttlSec??t.DEFAULT_TTL_SEC,c={cookies:i.map(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path,expires:e.expires,size:e.size,httpOnly:e.httpOnly,secure:e.secure,session:e.session,sameSite:e.sameSite,sourceScheme:e.sourceScheme})),userAgent:a.userAgent,acceptLanguage:a.acceptLanguage,referer:r.referer??a.referer,clientHints:a.clientHints,platform:a.platform,origin:o,collectedAt:Date.now(),ttlSec:s};return this.cachedProfile=c,e.info(`Session profile exported: cookies=${c.cookies.length}, origin=${c.origin??`unknown`}, ttlSec=${c.ttlSec}`),c}serialize(e){return JSON.stringify(e)}deserialize(e){let n=JSON.parse(e);return{cookies:Array.isArray(n.cookies)?n.cookies:[],userAgent:n.userAgent,acceptLanguage:n.acceptLanguage,referer:n.referer,clientHints:n.clientHints,platform:n.platform,origin:n.origin,collectedAt:typeof n.collectedAt==`number`?n.collectedAt:Date.now(),ttlSec:typeof n.ttlSec==`number`&&n.ttlSec>0?n.ttlSec:t.DEFAULT_TTL_SEC}}setProfile(e){this.cachedProfile=e}getProfile(){return this.cachedProfile}getValidProfile(e=Date.now()){return!this.cachedProfile||this.isExpired(this.cachedProfile,e)?null:this.cachedProfile}isExpired(e,t=Date.now()){return e.collectedAt+e.ttlSec*1e3<=t}clearProfile(){this.cachedProfile=null}static resetInstance(){t.instance=null}safeOrigin(e){if(!(!e||e===`about:blank`))try{return new URL(e).origin}catch{return}}};const Te=[{api:`navigator.webdriver`,method:`property override (configurable:false)`},{api:`window.chrome`,method:`object injection (runtime, loadTimes, csi)`},{api:`navigator.plugins`,method:`PluginArray override (spoofed length/names)`},{api:`Permissions.query`,method:`result filter (returns granted/prompt)`},{api:`HTMLCanvasElement.toDataURL/toBlob`,method:`pixel noise injection`},{api:`WebGLRenderingContext.getParameter`,method:`vendor/renderer override`},{api:`navigator.languages`,method:`array override (locale-specific)`},{api:`navigator.getBattery`,method:`fake BatteryManager`},{api:`MediaDevices.enumerateDevices`,method:`device list filter`},{api:`Notification.permission`,method:`permission override`},{api:`performance.now / Date.now`,method:`timing offset compensation`},{api:`CDP request timing`,method:`jitter compensation proxy`}],F={...Ce};let I=null;const L=we.getInstance();async function R(){if(I)return I;try{return I=(await import(`./FingerprintManager-N7BZqjxP.mjs`)).FingerprintManager.getInstance(),I}catch{return null}}var Ee=class{deps;constructor(e){this.deps=e}async handleStealthInject(t){try{if(this.deps.getActiveDriver()===`camoufox`)return k.ok().build({driver:`camoufox`,message:`Camoufox uses C++ engine-level fingerprint spoofing — JS-layer stealth scripts are not needed and have been skipped.`});let t=await this.deps.pageController.getPage(),n=await R(),r=!1;if(n?.isAvailable())try{let e=n.getActiveProfile();e||=await n.generateFingerprint(),e&&(await n.injectFingerprint(t,e),r=!0)}catch(t){e.warn(`Fingerprint injection failed, falling back to StealthScripts:`,t)}if(await h.injectAll(t),r&&n){let e=n.getActiveProfile(),t=L.getValidProfile(),r={cookies:t?.cookies??[],userAgent:e?.headers?.[`User-Agent`]??t?.userAgent,acceptLanguage:e?.headers?.[`Accept-Language`]??t?.acceptLanguage,referer:t?.referer,clientHints:t?.clientHints,platform:e?.os??t?.platform,origin:t?.origin,collectedAt:t?.collectedAt??Date.now(),ttlSec:t?.ttlSec??1800};L.setProfile(r)}return k.ok().build({message:`Stealth scripts injected successfully`,fingerprintApplied:r,patchManifest:Te,_nextStepHint:`Stealth patches are now active. Next: navigate to your target URL with page_navigate. Do NOT call stealth_inject again — it only needs to run once per page.`})}catch(e){return k.fail(e).build()}}async handleStealthSetUserAgent(e){try{let t=S(e,`platform`,`windows`),n=await this.deps.pageController.getPage();return await h.setRealisticUserAgent(n,t),k.ok().build({platform:t,message:`User-Agent set for ${t}`,_nextStepHint:`User-Agent is now configured. Next: call stealth_inject to apply all anti-detection patches, then page_navigate to your target URL.`})}catch(e){return k.fail(e).build()}}async handleStealthConfigureJitter(e){try{return e.enabled!==void 0&&(F.enabled=!!e.enabled),typeof e.minDelayMs==`number`&&(F.minDelayMs=e.minDelayMs),typeof e.maxDelayMs==`number`&&(F.maxDelayMs=e.maxDelayMs),e.burstMode!==void 0&&(F.burstMode=!!e.burstMode),k.ok().build({jitterOptions:F,message:`CDP timing jitter ${F.enabled?`enabled`:`disabled`}: ${F.minDelayMs}-${F.maxDelayMs}ms${F.burstMode?` (burst mode)`:``}`})}catch(e){return k.fail(e).build()}}async handleStealthGenerateFingerprint(e){try{if(this.deps.getActiveDriver()===`camoufox`)try{let t=await import(`camoufox-js/fingerprints`),n=S(e,`os`,`windows`),r=await t.generateFingerprint(n);return k.ok().build({fingerprint:r,driver:`camoufox`,message:`Fingerprint generated using camoufox native engine. Apply via browser_launch(fingerprint=...) before launching.`})}catch(e){return k.fail(`Camoufox fingerprint generation failed: ${e instanceof Error?e.message:String(e)}`).build()}let t=await R();if(!t?.isAvailable())return k.fail(`fingerprint-generator/fingerprint-injector packages are not installed. Install them with: pnpm add fingerprint-generator fingerprint-injector`).merge({available:!1,capability:`fingerprint_generator`,status:`unavailable`,fix:`Install fingerprint-generator and fingerprint-injector: pnpm add fingerprint-generator fingerprint-injector`}).build();let n=await t.generateFingerprint({os:e.os,browser:e.browser??`chrome`,locale:e.locale??`en-US`});return k.ok().build({profile:n,message:`Fingerprint generated and cached. It will be auto-applied on next stealth_inject.`})}catch(e){return k.fail(e).build()}}async handleStealthVerify(e){try{let e=await this.deps.pageController.getPage(),t=await new(await(import(`./StealthVerifier-Dhbj4B4P.mjs`))).StealthVerifier().verify(e);return k.ok().merge(t).build()}catch(e){return k.fail(`Stealth verification failed: ${e instanceof Error?e.message:String(e)}`).build()}}async handleCamoufoxGeolocation(e){try{let t=S(e,`locale`);if(!t)return k.fail(`locale is required (e.g. "en-US", "zh-CN")`).build();let n;try{n=await(await import(`camoufox-js/locale`)).getGeolocation(t)}catch(e){return k.fail(`Camoufox locale module unavailable: ${e instanceof Error?e.message:String(e)}. Ensure camoufox-js is installed.`).merge({available:!1,capability:`camoufox_locale`,status:`unavailable`,fix:`Install camoufox-js and fetch its browser assets: pnpm add camoufox-js && npx camoufox-js fetch`}).build()}let r=null,i=S(e,`proxy`);if(i)try{r=await(await import(`camoufox-js/ip`)).publicIP(i)}catch{}return k.ok().build({locale:t,geolocation:n,publicIp:r})}catch(e){return k.fail(e).build()}}},De=class{deps;constructor(e){this.deps=e}async handleFrameworkStateExtract(e){let t=S(e,`framework`,`auto`),n=S(e,`selector`,``),r=E(e,`maxDepth`,5);try{let e=await this.deps.getActivePage();try{let t=await e.createCDPSession();await Promise.race([t.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_unreachable`)),3e3))])}catch{throw new ee(`CDP session unresponsive — the debugger may be blocking page evaluation. Call debugger_lifecycle({ action: 'disable' })() before framework_state_extract, or run it before debugger_lifecycle({ action: 'enable' }).`)}let i=e.evaluate(e=>{let t=window;function n(e,t=0){if(t>4)return`[deep]`;if(e==null)return e;if(typeof e==`function`)return`[Function]`;if(typeof e!=`object`)return e;if(Array.isArray(e))return e.slice(0,20).map(e=>n(e,t+1));try{let r={},i=0;for(let a of Object.keys(e)){if(i++>30){r.__truncated__=!0;break}r[a]=n(e[a],t+1)}return r}catch{return`[unserializable]`}}let r=()=>e.selector?document.querySelector(e.selector)??document.body:document.getElementById(`root`)??document.getElementById(`app`)??document.querySelector(`[data-reactroot]`)??document.body,i=()=>{let t=r(),i=Object.keys(t).find(e=>e.startsWith(`__reactFiber`)||e.startsWith(`__reactInternalInstance`)||e.startsWith(`__reactFiberContainer`));if(!i)return null;let a=[],o=new WeakSet,s=(t,r)=>{if(!(!t||r>e.maxDepth||o.has(t))){if(o.add(t),t.memoizedState){let e=[],r=t.memoizedState,i=0;for(;r&&i++<20;){let t=r.queue,i=r.memoizedState===void 0?t?.lastRenderedState:r.memoizedState;i!==void 0&&e.push(n(i)),r=r.next??null}if(e.length>0){let n=t.type,r=typeof n==`object`&&n?String(n.name??`anonymous`):typeof n==`string`?n:`anonymous`;a.push({component:r,state:e})}}s(t.child??null,r+1),s(t.sibling??null,r+1)}};return s(t[i]??null,0),a},a=()=>{let t=r(),i=Object.keys(t).find(e=>e===`__vueParentComponent`||e===`__vue_app__`||e.startsWith(`__vue`));if(!i)return null;let a=t[i];if(!a)return null;let o=[],s=new WeakSet,c=(t,r)=>{if(!t||r>e.maxDepth||s.has(t))return;s.add(t);let i=n(t.setupState??t.ctx),a=n(t.$data??t.data);if(i||a){let e=t.type;o.push({component:e?.__name??`unknown`,setupState:i,data:a})}let l=t.subTree?.children;if(Array.isArray(l))for(let e of l)e?.component&&c(e.component,r+1)};return c(a,0),o},o=()=>{let t=r(),i=Object.keys(t).find(e=>e===`__vue__`);if(!i)return null;let a=t[i];if(!a)return null;let o=[],s=new WeakSet,c=(t,r)=>{if(!t||r>e.maxDepth||s.has(t))return;s.add(t);let i=t.$options;o.push({component:i?.name??`unknown`,data:n(t.$data)});let a=t.$children;if(Array.isArray(a))for(let e of a)c(e,r+1)};return c(a,0),o},s=()=>{let e=[],t=new WeakSet,i=document.querySelectorAll(`[class]`),a=[r(),...Array.from(i)],o=!1;for(let r of a){let i=r;if(!Object.keys(i).some(e=>e===`$$`||e===`__svelte_meta`||e.startsWith(`__s`)))continue;o=!0;let a=i.$$;if(!a||t.has(a))continue;t.add(a);let s=i.__svelte_meta?.loc?.file,c=a.ctx,l={};if(Array.isArray(c)){let e=0;for(let t of c.slice(0,20))t!==void 0&&typeof t!=`function`&&(l[`$${e}`]=n(t)),e++}let u=a.fragment;if((Object.keys(l).length>0||u)&&e.push({component:s??r.tagName?.toLowerCase()??`svelte-component`,state:[l],...s?{file:s}:{}}),e.length>=50)break}return o?e:null},c=()=>{let r=[],i=t._$DX,a=t._$HY;if(!i&&!a)return document.querySelector(`[data-hk]`)?(r.push({component:`SolidRoot`,state:[{_note:`Solid detected via hydration markers; install solid-devtools for full state extraction`}]}),r):null;if(i){let t=i.roots;if(t&&typeof t==`object`){let i=t instanceof Map?Array.from(t.values()):Object.values(t),a=0;for(let t of i){if(a++>=e.maxDepth*10)break;let i=t.name??`SolidComponent`,o=t.value??t.state;r.push({component:i,state:o?[n(o)]:[]})}}}return a&&r.length===0&&r.push({component:`SolidHydration`,state:[n(a)]}),r.length>0?r:null},l=()=>{let t=r(),i=Object.keys(t);if(i.some(e=>e.startsWith(`__reactFiber`)||e.startsWith(`__reactInternalInstance`))||!i.some(e=>e===`__k`||e===`__e`||e===`_dom`))return null;let a=[],o=new WeakSet,s=(t,r)=>{if(!t||r>e.maxDepth||o.has(t))return;o.add(t);let i=t.__c;if(i){let e=i.state,r=i.props,o=i.__H,s=[];if(o){let e=o.__;if(Array.isArray(e))for(let t of e.slice(0,20)){let e=t.__??t._value;e!==void 0&&s.push(n(e))}}let c=t.type,l=typeof c==`function`?c.displayName??c.name??`PreactComponent`:typeof c==`string`?c:`PreactComponent`;(e||s.length>0)&&a.push({component:String(l),state:s.length>0?s:e?[n(e)]:[],...r?{props:n(r)}:{}})}let c=t.__k;if(Array.isArray(c))for(let e of c)e&&s(e,r+1)},c=t.__k;if(Array.isArray(c))for(let e of c)e&&s(e,0);else if(t._children){let e=t._children;if(Array.isArray(e))for(let t of e)t&&s(t,0)}return a.length>0?a:null},u=()=>{let e=t.__NEXT_DATA__;if(e)return{framework:`nextjs`,route:e.page,buildId:e.buildId,runtimeConfig:n(e.runtimeConfig),props:n(e.props)};let r=t.__NUXT__;return r?r.config!==void 0||r._errors!==void 0?{framework:`nuxt3`,state:n(r.state),config:n(r.config),payload:n(r.data)}:{framework:`nuxt2`,state:n(r.state),serverRendered:r.serverRendered}:null},d=r(),f=Object.keys(d),p=f.some(e=>e.startsWith(`__reactFiber`)||e.startsWith(`__reactInternalInstance`)||e.startsWith(`__reactFiberContainer`)),m=f.some(e=>e===`__vueParentComponent`||e===`__vue_app__`),h=f.some(e=>e===`__vue__`),g=f.some(e=>e===`$$`||e===`__svelte_meta`||e.startsWith(`__s`)),_=t._$DX!==void 0||t._$HY!==void 0||!!document.querySelector(`[data-hk]`),v=f.some(e=>e===`__k`||e===`__e`||e===`_dom`||e===`_children`),y=e.framework;y===`preact`&&p&&(y=`react`),y===`auto`&&(p?y=`react`:m?y=`vue3`:h?y=`vue2`:g?y=`svelte`:_?y=`solid`:v&&(y=`preact`));let b=null;(y===`react`||y===`auto`)&&(b=i()),!b&&(y===`vue3`||y===`auto`)&&(b=a()),!b&&(y===`vue2`||y===`auto`)&&(b=o()),!b&&(y===`svelte`||y===`auto`)&&(b=s()),!b&&(y===`solid`||y===`auto`)&&(b=c()),!b&&(y===`preact`||y===`auto`)&&(b=l());let x=u();return{detected:y,states:b??[],found:b!==null&&b.length>0,...x?{meta:x}:{}}},{framework:t,selector:n,maxDepth:r}),a=await Promise.race([i,new Promise((e,t)=>setTimeout(()=>t(Error(`page.evaluate timed out after 30000ms`)),3e4))]);return k.ok().build(a)}catch(e){return k.fail(e).build()}}},Oe=class{deps;constructor(e){this.deps=e}async handleIndexedDBDump(e){let t=S(e,`database`,``),n=S(e,`store`,``),r=E(e,`maxRecords`,100);try{let e=await(await this.deps.getActivePage()).evaluate(async e=>{let t=await indexedDB.databases(),n={};for(let r of t){if(!r.name||e.database&&r.name!==e.database)continue;let t=r.name,i;try{i=await new Promise((e,n)=>{let i=r.version?indexedDB.open(t,r.version):indexedDB.open(t);i.addEventListener(`success`,()=>e(i.result),{once:!0}),i.addEventListener(`error`,()=>n(i.error),{once:!0})})}catch{n[t]={__error__:[`failed to open`]};continue}let a=Array.from(i.objectStoreNames),o={};for(let t of a)if(!(e.store&&t!==e.store))try{o[t]=await new Promise((n,r)=>{try{let a=i.transaction(t,`readonly`).objectStore(t).getAll();a.addEventListener(`success`,()=>n(a.result.slice(0,e.maxRecords)),{once:!0}),a.addEventListener(`error`,()=>r(a.error),{once:!0})}catch(e){r(e)}})}catch{o[t]=[`__error reading store__`]}i.close(),n[t]=o}return n},{database:t,store:n,maxRecords:r});return k.ok().build(e)}catch(e){return k.fail(e).build()}}},ke=class{deps;constructor(e){this.deps=e}async handleGetDetailedData(e){try{let t=S(e,`detailId`,``),n=S(e,`path`),r=this.deps.detailedDataManager.retrieve(t,n);return k.ok().build({detailId:t,path:n||`full`,data:r})}catch(e){return k.fail(e).set(`hint`,`DetailId may have expired (TTL: 10 minutes) or is invalid`).build()}}},Ae=class{deps;constructor(e){this.deps=e}async handleBrowserEvaluateCdpTarget(t){try{let e=S(t,`script`,``)||S(t,`code`,``)||S(t,`expression`,``),n=O(t,`autoSummarize`,!0),r=E(t,`maxSize`,51200),i=T(t,`fieldFilter`),a=O(t,`stripBase64`,!1),o=O(t,`returnByValue`,!0),s=O(t,`awaitPromise`,!0);if(!e.trim())return k.fail(`code, script, or expression is required`).build();let c=this.deps.pageController.getAttachedTargetInfo();if(!c)return k.fail(`No CDP target is currently attached. Call browser_attach_cdp_target(targetId="...") first.`).build();let l=P(await this.deps.pageController.evaluateAttachedTarget(e,{returnByValue:o,awaitPromise:s}),this.deps.detailedDataManager,{autoSummarize:n,maxSize:r,fieldFilter:i??void 0,stripBase64:a});return k.ok().build({target:c,result:l})}catch(t){return e.error(`Failed to evaluate in CDP target:`,t),k.fail(t instanceof Error?t.message:String(t)).build()}}},je=class{deps;constructor(e){this.deps=e}markMonitoringContextChanged(t){try{this.deps.consoleMonitor.markContextChanged()}catch(n){e.warn(`[${t}] Failed to mark monitoring context as stale: ${n instanceof Error?n.message:String(n)}`)}}safeOrigin(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}async syncAttachedPageContext(e){if(e.type!==`page`||!e.targetId)return{contextSwitched:!1,selectedIndex:null,selectedPageId:null,currentUrl:e.url??null,currentTitle:e.title??null};let t=await this.deps.collector.selectResolvedPageByTargetId(e.targetId);if(!t)return{contextSwitched:!1,selectedIndex:null,selectedPageId:null,currentUrl:e.url??null,currentTitle:e.title??null};let n=this.deps.getTabRegistry(),r=n.upsertPage(t.page,{index:t.index,url:t.url,title:t.title});return n.setCurrentPageId(r),{contextSwitched:!0,selectedIndex:t.index,selectedPageId:r,currentUrl:t.url,currentTitle:t.title}}async clearAttachedTargetContext(t){let n=this.deps.collector.getAttachedTargetInfo();if(!n)return{detached:!1,targetId:null,type:null};let r=await this.deps.collector.detachCdpTarget();return r&&e.info(`[${t}] Detached active CDP target ${n.targetId} before switching page context`),{detached:r,targetId:n.targetId,type:n.type??null}}async handleBrowserListCdpTargets(t){try{let e=S(t,`type`),n=T(t,`types`),r=S(t,`targetId`),i=S(t,`urlPattern`),a=S(t,`titlePattern`),o=O(t,`attachedOnly`,!1),s=O(t,`discoverOOPIF`,!0),c=await this.deps.collector.listCdpTargets({type:e??void 0,types:n??void 0,targetId:r??void 0,urlPattern:i??void 0,titlePattern:a??void 0,attachedOnly:o,discoverOOPIF:s}),l=this.deps.collector.getAttachedTargetInfo(),u=this.deps.getTabRegistry().getContextMeta(),d=await this.deps.collector.listPages(),f=typeof u.tabIndex==`number`?d[u.tabIndex]:void 0,p=f?.url??null,m=this.safeOrigin(p),h=c.map(e=>{let t=e.url,n=this.safeOrigin(t),r=p!==null&&t===p,i=m!==null&&n!==null&&m===n,a=l?.targetId===e.targetId,o=[];return a&&o.push(`active_target`),r&&o.push(`matches_current_tab_url`),!r&&i&&o.push(`same_origin_as_current_tab`),e.openerId&&l?.targetId===e.openerId&&o.push(`opened_by_active_target`),e.openerId&&!o.includes(`opened_by_active_target`)&&o.push(`has_opener_target`),e.openerFrameId&&o.push(`has_opener_frame`),{...e,isActiveTarget:a,matchesCurrentTabUrl:r,sameOriginAsCurrentTab:i,relationHints:o}});return k.ok().build({count:h.length,activeTarget:l,currentTab:f?{index:f.index,url:f.url,title:f.title}:null,filters:{type:e??null,types:n??null,targetId:r??null,urlPattern:i??null,titlePattern:a??null,attachedOnly:o},targets:h})}catch(t){return e.error(`Failed to list CDP targets:`,t),k.fail(t instanceof Error?t.message:String(t)).build()}}async handleBrowserAttachCdpTarget(t){try{let e=S(t,`targetId`);if(!e)throw Error(`targetId is required`);let n=await this.deps.collector.attachCdpTarget(e),r=await this.syncAttachedPageContext(n);return this.markMonitoringContextChanged(`browser_attach_cdp_target`),k.ok().build({attached:!0,target:n,...r})}catch(t){return e.error(`Failed to attach CDP target:`,t),k.fail(t instanceof Error?t.message:String(t)).build()}}async handleBrowserDetachCdpTarget(t){try{let e=this.deps.collector.getAttachedTargetInfo(),t=await this.deps.collector.detachCdpTarget();return t&&this.markMonitoringContextChanged(`browser_detach_cdp_target`),k.ok().build({detached:t,targetId:e?.targetId??null})}catch(t){return e.error(`Failed to detach CDP target:`,t),k.fail(t instanceof Error?t.message:String(t)).build()}}};const Me=[`hidden`,`array`,`string`,`object`,`code`,`closure`,`regexp`,`number`,`native`,`synthetic`,`concatenated string`,`sliced string`,`symbol`,`bigint`];function z(e){return typeof e==`object`&&!!e}function Ne(e){return z(e)&&typeof e.createCDPSession==`function`}function Pe(e){return z(e)&&typeof e.chunk==`string`}var Fe=class{deps;detailedDataManager;constructor(e){this.deps=e,this.detailedDataManager=d.getInstance()}async handleJSHeapSearch(t){let n=S(t,`pattern`,``)||S(t,`query`,``),r=E(t,`maxResults`,50),i=O(t,`caseSensitive`,!1);return n?re(async()=>{let t=null,a=!1;try{let o=await this.deps.getActivePage();if(!Ne(o))throw Error(`Active page does not support CDP session creation`);t=await o.createCDPSession(),a=!0,e.info(`[js_heap_search] Taking heap snapshot`,{patternLength:n.length,caseSensitive:i,maxResults:r}),await t.send(`HeapProfiler.enable`);let s=[],c=0;t.on(`HeapProfiler.addHeapSnapshotChunk`,e=>{Pe(e)&&(s.push(e.chunk),c+=e.chunk.length)}),await t.send(`HeapProfiler.takeHeapSnapshot`,{reportProgress:!1,treatGlobalObjectsAsRoots:!0,captureNumericValue:!1}),await t.send(`HeapProfiler.disable`),e.info(`[js_heap_search] Snapshot size: ${(c/1024).toFixed(1)} KB`);let l=s.join(``);s.length=0;let u=await this.searchSnapshot(l,n,r,i),d={success:!0,pattern:n,caseSensitive:i,snapshotSizeKB:Math.round(c/1024),matchCount:u.length,truncated:u.length>=r,matches:u,tip:u.length>0?`Use page_evaluate to inspect the objects at the paths found. E.g., eval the objectPath as a JS expression.`:`No matches found. The value may be encrypted, compressed, or stored in a non-string form.`};return k.ok().build(this.detailedDataManager.smartHandle(d,51200))}catch(t){return e.error(`[js_heap_search] Error:`,t),k.fail(t).build()}finally{if(a&&t)try{await t.detach()}catch{}}}):k.fail(`pattern is required`).build()}async searchSnapshot(t,n,r,i){try{let e;try{e=JSON.parse(t)}catch{return[]}if(typeof e!=`object`||!e||Array.isArray(e))return[];let a=e,o=a.strings,s=a.nodes,c=typeof a.snapshot==`object`&&a.snapshot!==null?a.snapshot:null,l=c&&typeof c.meta==`object`&&c.meta!==null?c.meta:null,u=l?.node_fields,d=l?.node_types;if(!Array.isArray(u)||!Array.isArray(o)||!Array.isArray(s))return[];let f=u.length;if(f===0)return[];let p=u.indexOf(`type`),m=u.indexOf(`name`),h=u.indexOf(`id`);if(p<0||m<0)return[];let g=Array.isArray(d)&&Array.isArray(d[0])?d[0]:[],_=i?n:n.toLowerCase(),v=[],y=Math.floor(s.length/f),b=o;for(let e=0;e<y&&v.length<r;e++){e>0&&e%1e3==0&&await new Promise(e=>setImmediate(e));let t=e*f,n=s[t+p],r=s[t+m];if(typeof r!=`number`||r<0||r>=b.length)continue;let a=g[n],o=(typeof a==`string`?a:void 0)??Me[n]??`type_${n}`;if(o!==`string`&&o!==`concatenated string`&&o!==`sliced string`)continue;let c=b[r];if(typeof c!=`string`||!(i?c:c.toLowerCase()).includes(_))continue;let l=h>=0?s[t+h]:void 0,u=l===void 0?e:l;v.push({nodeId:u,nodeType:o,value:c.length>200?`${c.slice(0,200)}…`:c,objectPath:`[HeapNode #${u}]`,nameHint:c.slice(0,80)})}return v}catch(t){return e.warn(`[js_heap_search] Snapshot parse error:`,t),[]}}};const Ie=new Set([`alias_bind`,`alias_open`,`navigate`,`wait_for`,`context_set`,`context_get`,`transfer`,`list`,`clear`]);function B(e){return typeof e==`object`&&!!e}function Le(e){return typeof e==`string`&&Ie.has(e)}function V(e){return B(e)&&typeof e.goto==`function`&&typeof e.waitForSelector==`function`&&typeof e.evaluate==`function`&&typeof e.url==`function`&&typeof e.title==`function`}function H(e){return!V(e)||!B(e)?!1:typeof e.context==`function`}function Re(e){return B(e)&&typeof e.newPage==`function`&&typeof e.pages==`function`}function U(e){return typeof e==`string`&&e.length>0?e:null}function ze(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null}function Be(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:t}var Ve=class{deps;constructor(e){this.deps=e}get registry(){return this.deps.getTabRegistry()}async handleTabWorkflow(t){let n=t.action;try{if(!Le(n))return k.fail(`Unknown action: "${String(n)}". Valid: list, alias_bind, alias_open, navigate, wait_for, context_set, context_get, transfer, clear`).build();switch(n){case`list`:return this.listAliases();case`clear`:return this.clearState();case`alias_bind`:return await this.aliasBind(t);case`alias_open`:return await this.aliasOpen(t);case`navigate`:return await this.navigateAlias(t);case`wait_for`:return await this.waitFor(t);case`context_set`:return this.contextSet(t);case`context_get`:return this.contextGet(t);case`transfer`:return await this.transfer(t)}}catch(r){let i=r instanceof Error?r.message:String(r);return e.error(`[tab_workflow] Action failed`,{action:typeof n==`string`?n:String(n),alias:typeof t.alias==`string`?t.alias:void 0,fromAlias:typeof t.fromAlias==`string`?t.fromAlias:void 0,error:i}),k.fail(i).build()}}listAliases(){let e=this.registry.getCurrentTabInfo(this.deps.getActiveDriver()),t=this.registry.getSharedContextMap();return k.ok().build({aliases:e.aliases,staleAliases:e.staleAliases,currentPageId:e.currentPageId,currentIndex:e.currentIndex,currentUrl:e.url,context:t})}clearState(){return this.registry.clear(),k.ok().build({cleared:!0})}async aliasBind(e){let t=U(e.alias),n=ze(e.index);if(!t)return k.fail(`alias is required`).build();if(n===null)return k.fail(`index is required`).build();await this.reconcilePages();let r=this.registry.bindAliasByIndex(t,n);return r?k.ok().build({bound:{alias:t,index:n,pageId:r}}):k.fail(`No active page at index ${n}. Use browser_list_tabs to check available pages.`).build()}async aliasOpen(e){let t=U(e.alias),n=U(e.url);if(!t)return k.fail(`alias is required`).build();if(!n)return k.fail(`url is required`).build();if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();if(!H(e))return k.fail(`Cannot open new tab: camoufox page context not accessible`).build();let r=e.context(),i=await r.newPage();await i.goto(n,{waitUntil:`domcontentloaded`});let a=r.pages().indexOf(i),o=await i.title(),s=this.registry.registerPage(i,{index:a,url:i.url(),title:o});return this.registry.bindAlias(t,s),k.ok().build({alias:t,index:a,pageId:s,url:i.url(),title:o})}let r=await this.getBrowserFromController();if(!r)return k.fail(`Cannot open new tab: browser instance not accessible via PageController`).build();let i=await r.newPage();await i.goto(n,{waitUntil:`domcontentloaded`});let a=(await r.pages()).indexOf(i),o=await i.title(),s=this.registry.registerPage(i,{index:a,url:i.url(),title:o});return this.registry.bindAlias(t,s),k.ok().build({alias:t,index:a,pageId:s,url:i.url(),title:o})}async navigateAlias(e){let t=U(e.alias),n=U(e.url);if(!t)return k.fail(`alias is required`).build();if(!n)return k.fail(`url is required`).build();let r=await this.getPageByAlias(t);return r?(await r.goto(n,{waitUntil:`domcontentloaded`}),k.ok().build({alias:t,navigated:n,currentUrl:r.url()})):k.fail(`No tab found for alias "${t}". Use alias_bind or alias_open first.`).build()}async waitFor(e){let t=U(e.alias),n=U(e.selector),r=U(e.waitForText),i=Be(e.timeoutMs,1e4);if(!t)return k.fail(`alias is required`).build();if(!n&&!r)return k.fail(`selector or waitForText is required`).build();let a=await this.getPageByAlias(t);if(!a)return k.fail(`No tab found for alias "${t}"`).build();if(n)return await a.waitForSelector(n,{timeout:i}),k.ok().build({alias:t,waitedFor:n,found:!0});let o=r,s=Date.now();for(;Date.now()-s<i;){let e=await a.evaluate(()=>document.body.innerText);if((typeof e==`string`?e:String(e??``)).includes(o))return k.ok().build({alias:t,waitedForText:o,found:!0});await new Promise(e=>setTimeout(e,500))}return k.fail(`Timeout waiting for text "${o}" in tab "${t}"`).build()}contextSet(e){let t=U(e.key),n=e.value;return t?(this.registry.setSharedContext(t,n),k.ok().build({set:{key:t,value:n}})):k.fail(`key is required`).build()}contextGet(e){let t=U(e.key);if(!t)return k.fail(`key is required`).build();let{value:n,found:r}=this.registry.getSharedContext(t);return k.ok().build({key:t,value:n,found:r})}async transfer(e){let t=U(e.fromAlias),n=U(e.key),r=U(e.expression);if(!t)return k.fail(`fromAlias is required`).build();if(!n)return k.fail(`key is required`).build();if(!r)return k.fail(`expression is required`).build();let i=await this.getPageByAlias(t);if(!i)return k.fail(`No tab found for alias "${t}"`).build();let a=await i.evaluate(r);return this.registry.setSharedContext(n,a),k.ok().build({transferred:{fromAlias:t,key:n,value:a}})}async getPageByAlias(e){let t=this.registry.resolveAlias(e);if(!t)return null;let n=this.registry.getPageById(t);if(n&&V(n))return n;await this.reconcilePages();let r=this.registry.getPageById(t);return r&&V(r)?r:null}async reconcilePages(){if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();if(H(e)){let t=e.context().pages(),n=await Promise.all(t.map(async(e,t)=>({index:t,url:e.url(),title:await e.title()})));this.registry.reconcilePages(t,n)}return}let e=await this.getBrowserFromController();if(!e)return;let t=await e.pages(),n=await Promise.all(t.map(async(e,t)=>({index:t,url:e.url(),title:await e.title()})));this.registry.reconcilePages(t,n)}async getBrowserFromController(){let e=this.deps.getPageController();if(!B(e)||typeof e.getBrowser!=`function`)return null;let t=await e.getBrowser();return Re(t)?t:null}};const He=new Set([`none`,`outside-only`,`dangerously`]),Ue=new Set([`get`,`set`,`clear`]),W=10*1024*1024,G=600*1e3;var We=class{sessions=new Map;createSessionId(){return se()}scheduleExpiry(t){let n=setTimeout(()=>{e.debug(`JSDOM session ${t} expired after ${G}ms`),this.closeSession(t)},G);return n.unref?.(),n}refreshSessionExpiry(e,t){clearTimeout(t.timer),t.timer=this.scheduleExpiry(e)}getSession(e){let t=this.sessions.get(e);if(!t)throw Error(`JSDOM session not found or expired: ${e}`);return this.refreshSessionExpiry(e,t),t}closeSession(t){let n=this.sessions.get(t);if(n){clearTimeout(n.timer);try{n.dom.window.close()}catch(t){e.debug(`JSDOM window close error: ${String(t)}`)}this.sessions.delete(t)}}closeAll(){for(let e of Array.from(this.sessions.keys()))this.closeSession(e)}async handleJsdomParse(e){try{let t=D(e,`html`);if(Buffer.byteLength(t,`utf8`)>W)return k.fail(`HTML input exceeds ${W/1024/1024}MB limit. Provide smaller HTML or use a URL.`).build();let n=S(e,`url`,`about:blank`),r=S(e,`contentType`,`text/html`),i=w(e,`runScripts`,He,`none`),a=O(e,`includeNodeLocations`,!1),o=O(e,`pretendToBeVisual`,!1),s=S(e,`referrer`,``),c=E(e,`storageQuotaBytes`,1e6);if(this.sessions.size>=5)return k.fail(`JSDOM session limit reached (5). Close existing sessions first with browser_jsdom_serialize + drop.`).build();let l={url:n,contentType:r,includeNodeLocations:a,pretendToBeVisual:o,storageQuota:c};i!==`none`&&(l.runScripts=i),s&&(l.referrer=s);let{JSDOM:u}=await import(`jsdom`),d=new u(t,l),f=this.createSessionId(),p={dom:d,url:n,runScripts:i,includeNodeLocations:a,createdAt:Date.now(),timer:this.scheduleExpiry(f)};this.sessions.set(f,p);let m=d.window.document;return k.ok().set(`sessionId`,f).set(`title`,m.title||``).set(`url`,n).set(`contentType`,r).set(`runScripts`,i).set(`ttlMs`,G).set(`activeSessions`,this.sessions.size).set(`stats`,{elements:m.getElementsByTagName(`*`).length,scripts:m.getElementsByTagName(`script`).length,links:m.getElementsByTagName(`a`).length,images:m.getElementsByTagName(`img`).length,stylesheets:m.querySelectorAll(`link[rel="stylesheet"], style`).length}).build()}catch(e){return k.fail(e).build()}}async handleJsdomQuery(e){try{let t=D(e,`sessionId`),n=D(e,`selector`),r=E(e,`maxResults`,50),i=O(e,`includeHtml`,!1),a=O(e,`includeText`,!0),o=O(e,`includeLocation`,!1),s=T(e,`attributes`),c=this.getSession(t),l=c.dom.window.document,u=Array.from(l.querySelectorAll(n)),d=u.slice(0,r).map(e=>{let t={tag:e.tagName.toLowerCase()};if(s.length>0){let n={};for(let t of s)n[t]=e.getAttribute(t);t.attributes=n}else{let n={};for(let t of Array.from(e.attributes))n[t.name]=t.value;t.attributes=n}if(a&&(t.text=(e.textContent??``).trim()),i&&(t.html=e.outerHTML),o&&c.includeNodeLocations)try{t.location=c.dom.nodeLocation(e)??null}catch{t.location=null}return t});return k.ok().set(`sessionId`,t).set(`selector`,n).set(`matched`,u.length).set(`returned`,d.length).set(`results`,d).build()}catch(e){return k.fail(e).build()}}async handleJsdomExecute(e){try{let t=D(e,`sessionId`),n=D(e,`code`),r=E(e,`timeoutMs`,5e3),i=this.getSession(t);if(i.runScripts===`none`)return k.fail(`JSDOM session was created with runScripts="none". Re-parse with runScripts="outside-only" or "dangerously" to execute code.`).build();let a=[],o=i.dom.window,s=o.console;o.console=qe(s,a);let c,l=null;try{c=o.eval(n)}catch(e){l=e instanceof Error?e.message:String(e)}finally{o.console=s}return l===null?k.ok().set(`sessionId`,t).set(`result`,K(c)).set(`consoleLogs`,a).set(`timeoutHintMs`,r).build():k.fail(l).set(`consoleLogs`,a).build()}catch(e){return k.fail(e).build()}}async handleJsdomSerialize(e){try{let t=D(e,`sessionId`),n=O(e,`pretty`,!1),r=S(e,`selector`,``),i=this.getSession(t),a;if(r){let e=i.dom.window.document.querySelector(r);if(!e)return k.fail(`No element matches selector: ${r}`).build();a=e.outerHTML}else a=i.dom.serialize();return n&&(a=Je(a)),k.ok().set(`sessionId`,t).set(`bytes`,Buffer.byteLength(a,`utf8`)).set(`pretty`,n).set(`html`,a).build()}catch(e){return k.fail(e).build()}}async handleJsdomCookies(e){try{let t=D(e,`sessionId`),n=w(e,`action`,Ue,`get`),r=this.getSession(t),i=r.dom.cookieJar,a=S(e,`url`,r.url);if(n===`get`){let e=await i.getCookies(a);return k.ok().set(`sessionId`,t).set(`url`,a).set(`cookies`,e.map(Ge)).build()}if(n===`set`){let n=C(e,`cookie`);if(!n)return k.fail(`cookie object required for action="set"`).build();let r=typeof n.raw==`string`?n.raw:Ke(n);return await i.setCookie(r,a),k.ok().set(`sessionId`,t).set(`action`,`set`).set(`cookie`,r).build()}let o=i.store;return o&&typeof o.removeAllCookies==`function`&&await new Promise((e,t)=>o.removeAllCookies(n=>n?t(n):e())),k.ok().set(`sessionId`,t).set(`action`,`clear`).build()}catch(e){return k.fail(e).build()}}};function Ge(e){return{key:e.key??``,value:e.value??``,domain:e.domain??null,path:e.path??null,expires:e.expires instanceof Date?e.expires.toISOString():e.expires??null,httpOnly:e.httpOnly===!0,secure:e.secure===!0,sameSite:e.sameSite??null}}function Ke(e){let t=String(e.name??e.key??``),n=String(e.value??``);if(!t)throw Error(`cookie.name (or cookie.key) is required`);let r=[`${t}=${n}`];return typeof e.domain==`string`&&r.push(`Domain=${e.domain}`),typeof e.path==`string`&&r.push(`Path=${e.path}`),typeof e.expires==`string`&&r.push(`Expires=${e.expires}`),typeof e.maxAge==`number`&&r.push(`Max-Age=${e.maxAge}`),e.secure===!0&&r.push(`Secure`),e.httpOnly===!0&&r.push(`HttpOnly`),typeof e.sameSite==`string`&&r.push(`SameSite=${e.sameSite}`),r.join(`; `)}function qe(e,t){let n=[`log`,`info`,`warn`,`error`,`debug`,`trace`],r={};for(let i of n)r[i]=(...n)=>{t.push({level:i,args:n.map(e=>K(e))});let r=e?.[i];if(typeof r==`function`)try{r.apply(e,n)}catch{}};return r}function K(e){if(e==null)return e;let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return e;if(t===`bigint`)return`${e.toString()}n`;if(t===`function`)return`[Function: ${e.name||`anonymous`}]`;if(t===`symbol`)return String(e);try{return JSON.parse(JSON.stringify(e))}catch{return String(e)}}function Je(e){return e.replace(/>(?=<)/g,`>
10
- `)}let q=0;var Ye=class{pageIdByHandle=new WeakMap;tabsById=new Map;aliasToPageId=new Map;currentPageId=null;sharedContext=new Map;upsertPage(e,t){let n=this.pageIdByHandle.get(e),r=n?this.tabsById.get(n)?.meta:null,i=typeof t.index==`number`&&Number.isFinite(t.index)?t.index:r?.index??0;return this.registerPage(e,{index:i,url:t.url,title:t.title})}registerPage(t,n){let r=t,i=this.pageIdByHandle.get(r);if(i){let e=this.tabsById.get(i);return e?(e.meta=n,e.stale=!1):this.tabsById.set(i,{page:t,meta:n,stale:!1}),i}q+=1;let a=`tab-${q}`;return this.pageIdByHandle.set(r,a),this.tabsById.set(a,{page:t,meta:n,stale:!1}),e.debug(`[TabRegistry] Registered page ${a} (index=${n.index}, url=${n.url})`),a}reconcilePages(t,n){let r=new Set;for(let e=0;e<t.length;e++){let i=t[e],a=n[e]??{index:e,url:``,title:``},o=this.registerPage(i,{...a,index:e});r.add(o)}let i=[];for(let[t,n]of this.tabsById)r.has(t)||(n.stale?i.push(t):(n.stale=!0,e.debug(`[TabRegistry] Page ${t} marked stale`)));for(let t of i)this.tabsById.delete(t),e.debug(`[TabRegistry] Page ${t} pruned (was already stale)`);return this.currentPageId&&!r.has(this.currentPageId)&&(e.debug(`[TabRegistry] Current page ${this.currentPageId} is stale, clearing`),this.currentPageId=null),this.listTabs()}bindAlias(e,t){return this.tabsById.has(t)?(this.aliasToPageId.set(e,t),!0):!1}bindAliasByIndex(e,t){for(let[n,r]of this.tabsById)if(r.meta.index===t&&!r.stale)return this.aliasToPageId.set(e,n),n;return null}unbindAlias(e){return this.aliasToPageId.delete(e)}resolveAlias(e){let t=this.aliasToPageId.get(e);if(!t)return null;let n=this.tabsById.get(t);return!n||n.stale?null:t}getPageById(e){let t=this.tabsById.get(e);return!t||t.stale?null:t.page}getTabById(e){let t=this.tabsById.get(e);if(!t)return null;let n=this.getAliasesForPageId(e);return{pageId:e,index:t.meta.index,url:t.meta.url,title:t.meta.title,page:t.page,aliases:n,stale:t.stale}}getTabByIndex(e){for(let[t,n]of this.tabsById)if(n.meta.index===e&&!n.stale)return this.getTabById(t);return null}findTab(e){for(let[t]of this.tabsById){let n=this.getTabById(t);if(n&&e(n))return n}return null}setCurrentPageId(e){let t=this.tabsById.get(e);return!t||t.stale?!1:(this.currentPageId=e,!0)}setCurrentByIndex(e){let t=this.getTabByIndex(e);return t&&(this.currentPageId=t.pageId),t}getCurrentPageId(){return this.currentPageId}getCurrentPage(){return this.currentPageId?this.getPageById(this.currentPageId):null}getCurrentTabInfo(e){let t=[],n=[];for(let[e,r]of this.aliasToPageId){let i=this.tabsById.get(r),a=!i||i.stale;t.push({alias:e,pageId:r,index:i?.meta.index??null,stale:a}),a&&n.push(e)}let r=this.currentPageId?this.tabsById.get(this.currentPageId):null,i=r&&!r.stale?r:null;return{driver:e,currentPageId:i?this.currentPageId:null,currentIndex:i?.meta.index??null,url:i?.meta.url??null,title:i?.meta.title??null,aliases:t,staleAliases:n}}getContextMeta(){let e=this.currentPageId?this.tabsById.get(this.currentPageId):null,t=e&&!e.stale?e:null;return{url:t?.meta.url??null,title:t?.meta.title??null,tabIndex:t?.meta.index??null,pageId:t?this.currentPageId:null}}listTabs(){let e=[];for(let[t,n]of this.tabsById)if(!n.stale){let r=this.getAliasesForPageId(t);e.push({pageId:t,index:n.meta.index,url:n.meta.url,title:n.meta.title,page:n.page,aliases:r,stale:!1})}return e.toSorted((e,t)=>e.index-t.index)}listAllTabs(){let e=[];for(let[t,n]of this.tabsById){let r=this.getAliasesForPageId(t);e.push({pageId:t,index:n.meta.index,url:n.meta.url,title:n.meta.title,page:n.page,aliases:r,stale:n.stale})}return e.toSorted((e,t)=>e.index-t.index)}setSharedContext(e,t){this.sharedContext.set(e,t)}getSharedContext(e){return{value:this.sharedContext.get(e)??null,found:this.sharedContext.has(e)}}getSharedContextMap(){let e={};return this.sharedContext.forEach((t,n)=>{e[n]=t}),e}clear(){this.tabsById.clear(),this.aliasToPageId.clear(),this.sharedContext.clear(),this.currentPageId=null}getAliasesForPageId(e){let t=[];for(let[n,r]of this.aliasToPageId)r===e&&t.push(n);return t}};function Xe(e){let t={getActiveDriver:e.getActiveDriver,getCamoufoxPage:e.getCamoufoxPage},n=new Ye,r=new je({collector:e.collector,consoleMonitor:e.consoleMonitor,getTabRegistry:()=>n});return{tabRegistry:n,targetControl:r,browserControl:new de({collector:e.collector,pageController:e.pageController,consoleMonitor:e.consoleMonitor,getActiveDriver:e.getActiveDriver,getCamoufoxManager:e.getCamoufoxManager,getCamoufoxPage:e.getCamoufoxPage,getTabRegistry:()=>n,clearAttachedTargetContext:e=>r.clearAttachedTargetContext(e)}),camoufoxBrowser:new me({getCamoufoxManager:e.getCamoufoxManager,setCamoufoxManager:e.setCamoufoxManager,closeCamoufox:e.closeCamoufox}),pageNavigation:new ge({pageController:e.pageController,consoleMonitor:e.consoleMonitor,getTabRegistry:()=>n,eventBus:e.eventBus,...t}),pageInteraction:new _e({pageController:e.pageController,...t}),pageEvaluation:new ve({pageController:e.pageController,detailedDataManager:e.detailedDataManager,...t}),targetEvaluation:new Ae({pageController:e.pageController,detailedDataManager:e.detailedDataManager}),pageData:new ye({pageController:e.pageController,...t}),consoleHandlers:new be({consoleMonitor:e.consoleMonitor,detailedDataManager:e.detailedDataManager}),scriptManagement:new xe({scriptManager:e.scriptManager,detailedDataManager:e.detailedDataManager}),captchaHandlers:new Se({pageController:e.pageController,captchaDetector:e.captchaDetector,autoDetectCaptcha:e.getAutoDetectCaptcha(),autoSwitchHeadless:e.getAutoSwitchHeadless(),captchaTimeout:e.getCaptchaTimeout(),setAutoDetectCaptcha:e.setAutoDetectCaptcha,setAutoSwitchHeadless:e.setAutoSwitchHeadless,setCaptchaTimeout:e.setCaptchaTimeout}),stealthInjection:new Ee({pageController:e.pageController,...t}),frameworkState:new De({getActivePage:()=>e.collector.getActivePage()}),indexedDBDump:new Oe({getActivePage:()=>e.collector.getActivePage()}),jsHeapSearch:new Fe({getActivePage:()=>e.collector.getActivePage(),getActiveDriver:e.getActiveDriver}),tabWorkflow:new Ve({getActiveDriver:e.getActiveDriver,getCamoufoxPage:e.getCamoufoxPage,getPageController:()=>e.pageController,getTabRegistry:()=>n}),detailedData:new ke({detailedDataManager:e.detailedDataManager}),jsdomHandlers:new We}}function Ze(e,t,n,r,i){let a=1-i,o=a*a,s=o*a,c=i*i,l=c*i;return{x:s*e.x+3*o*i*t.x+3*a*c*n.x+l*r.x,y:s*e.y+3*o*i*t.y+3*a*c*n.y+l*r.y}}function Qe(e,t){let n=t.x-e.x,r=t.y-e.y,i=-r,a=n,o=Math.sqrt(i*i+a*a)||1,s=(Math.random()-.5)*.4,c=(Math.random()-.5)*.4;return[{x:e.x+n*.3+i/o*Math.abs(n+r)*s,y:e.y+r*.3+a/o*Math.abs(n+r)*s},{x:e.x+n*.7+i/o*Math.abs(n+r)*c,y:e.y+r*.7+a/o*Math.abs(n+r)*c}]}function $e(e,t){switch(t){case`linear`:return e;case`ease-in`:return e*e;case`ease-out`:return 1-(1-e)*(1-e);default:return e<.5?2*e*e:1-(-2*e+2)**2/2}}function J(e){return new Promise(t=>setTimeout(t,e))}function Y(e){let t=S(e,`frameUrl`),n=S(e,`frameSelector`);if(!(!t&&!n))return{frameUrl:t||void 0,frameSelector:n||void 0}}async function X(e,t,n){let r=await e.getActivePage();if(!r)return null;if(!n?.frameUrl&&!n?.frameSelector)return{page:r,context:r};if(!t)throw Error(`frameUrl/frameSelector requires PageController`);return{page:r,context:await t.resolveFrame(r,n)}}async function et(e,t,n){if(t===e||typeof t.frameElement!=`function`)return n;let r=await t.frameElement(),i=r&&typeof r.boundingBox==`function`?await r.boundingBox():null;return i?{x:i.x+n.x,y:i.y+n.y}:n}async function tt(e,t,n){try{let r=Y(e),i=await X(t,n,r);if(!i)return k.fail(`No active page. Use browser_launch or browser_attach first.`).build();let{page:a,context:o}=i,s=E(e,`toX`),c=E(e,`toY`),l=S(e,`selector`);if(l){let e=await o.evaluate(e=>{let t=document.querySelector(e);if(!t)return null;let n=t.getBoundingClientRect();return{x:n.x+n.width/2,y:n.y+n.height/2}},l);if(!e)return k.fail(`Selector not found: ${l}`).build();let t=await et(a,o,e);s=t.x,c=t.y}if(s===void 0||c===void 0)return k.fail(`Either selector or toX/toY coordinates are required`).build();let u=E(e,`fromX`,0),d=E(e,`fromY`,0),f=Math.max(1,Math.min(E(e,`steps`,24),500)),p=Math.max(10,Math.min(E(e,`durationMs`,600),3e4)),m=Math.max(0,Math.min(E(e,`jitterPx`,1.5),20)),h=S(e,`curve`,`ease`),g=O(e,`click`,!1),_={x:u,y:d},v={x:s,y:c},[y,b]=Qe(_,v),x=p/f;for(let e=0;e<=f;e++){let t=Ze(_,y,b,v,$e(e/f,h));e>0&&e<f&&(t.x+=(Math.random()-.5)*2*m,t.y+=(Math.random()-.5)*2*m),t.x=Math.max(0,t.x),t.y=Math.max(0,t.y),await a.mouse.move(t.x,t.y),await J(x*(.8+Math.random()*.4))}return g&&await a.mouse.click(s,c),k.ok().build({from:{x:u,y:d},to:{x:s,y:c},steps:f,durationMs:p,clicked:g,...r?{frame:r}:{}})}catch(e){return k.fail(e).build()}}async function nt(e,t){try{let n=await t.getActivePage();if(!n)return k.fail(`No active page.`).build();let r=Math.max(1,Math.min(E(e,`distance`,500),1e4)),i=S(e,`direction`,`down`),a=Math.max(10,Math.min(E(e,`durationMs`,1500),3e4)),o=Math.max(1,Math.min(E(e,`segments`,8),200)),s=typeof e.pauseMs==`number`&&Number.isFinite(e.pauseMs)?Math.max(0,Math.min(E(e,`pauseMs`,80),5e3)):Math.max(0,Math.min(Math.round(a/o),5e3)),c=Math.max(0,Math.min(E(e,`jitter`,.3),1)),l=S(e,`selector`),u=i===`up`||i===`down`,d=i===`down`||i===`right`?1:-1,f=0;for(let e=0;e<o;e++){let t=1-e/o*.4,i=r/o*t*(1+(Math.random()-.5)*c*2),a=Math.min(i,r-f);if(a<=0)break;let p=u?0:a*d,m=u?a*d:0;l?await n.evaluate((e,t,n)=>{let r=document.querySelector(e);r&&r.scrollBy({left:t,top:n,behavior:`auto`})},l,p,m):await n.evaluate((e,t)=>window.scrollBy({left:e,top:t,behavior:`auto`}),p,m),f+=a,await J(s*(.5+Math.random()))}return k.ok().build({direction:i,requestedDistance:r,actualScrolled:Math.round(f),durationMs:a,pauseMs:s,segments:o})}catch(e){return k.fail(e).build()}}async function rt(e,t,n){try{let r=Y(e),i=await X(t,n,r);if(!i)return k.fail(`No active page.`).build();let{page:a,context:o}=i,s=S(e,`selector`,``),c=S(e,`text`,``),l=Math.max(10,Math.min(E(e,`wpm`,90),300)),u=Math.max(0,Math.min(E(e,`errorRate`,.02),.3)),d=Math.max(50,Math.min(E(e,`correctDelayMs`,200),2e3)),f=O(e,`clearFirst`,!1);if(!s||!c)return k.fail(`selector and text are required`).build();let p=6e4/(l*5);await o.click(s),f&&await o.evaluate(e=>{let t=document.querySelector(e);t&&(t.value=``)},s);let m=0;for(let e of c){if(Math.random()<u&&e!==` `){let t=String.fromCharCode(e.charCodeAt(0)+(Math.random()>.5?1:-1));await a.keyboard.type(t,{delay:0}),await J(d*(.5+Math.random())),await a.keyboard.press(`Backspace`),await J(50+Math.random()*50),m++}await a.keyboard.type(e,{delay:0});let t=p*(.5+Math.random());(e===` `||`.,:;!?`.includes(e))&&(t*=1.5+Math.random()*.5),await J(t)}return k.ok().build({selector:s,length:c.length,wpm:l,typosSimulated:m,errorRate:u,...r?{frame:r}:{}})}catch(e){return k.fail(e).build()}}function it(e){return new Promise(t=>setTimeout(t,e))}function Z(e){let t=typeof e==`string`?e.toLowerCase():``;return t===`hook`?`hook`:t===`external_service`||t===`2captcha`||t===`anticaptcha`||t===`capsolver`?`external_service`:`manual`}function at(e){let t=typeof e==`string`?e.toLowerCase():``;return t===`image`?`image`:t===`widget`||t===`recaptcha_v2`||t===`recaptcha_v3`||t===`hcaptcha`||t===`funcaptcha`||t===`turnstile`?`widget`:t===`browser_check`||t===`managed_widget`?`browser_check`:`auto`}function ot(e){if(!(typeof e!=`string`||!e.trim()))return e.trim().toLowerCase()}function Q(e){let t=ot(e.provider),n=(process.env.CAPTCHA_PROVIDER||``).trim().toLowerCase();return t||n||`2captcha`}async function $(e,t,i){let o=Date.now(),s=a;if(!s)throw Error(`CAPTCHA_SOLVER_BASE_URL must be configured before using external_service mode.`);let l={key:e,json:1};t.taskKind===`turnstile`||t.taskKind===`recaptcha_v2`||t.taskKind===`hcaptcha`?(l.method=t.taskKind===`turnstile`?`turnstile`:t.taskKind===`hcaptcha`?`hcaptcha`:`userrecaptcha`,l.sitekey=t.siteKey,l.pageurl=t.pageUrl):(l.method=`base64`,l.body=t.imageBase64);let u=await(await fetch(`${s}/in.php`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(l),signal:AbortSignal.timeout(c)})).json();if(u.status!==1)throw Error(`2captcha submit failed: ${JSON.stringify(u)}`);let d=u.request,f=r;for(;;){let r=i-(Date.now()-o);if(r<=0||(await it(Math.min(f,r)),Date.now()-o>=i))break;let a=new URL(`${s}/res.php`);a.searchParams.set(`key`,e),a.searchParams.set(`action`,`get`),a.searchParams.set(`id`,d),a.searchParams.set(`json`,`1`);let c=await(await fetch(a.toString(),{signal:AbortSignal.timeout(n)})).json();if(c.status===1)return{token:c.request,challengeType:t.taskKind===`image`?`image`:`widget`,mode:`external_service`,durationMs:Date.now()-o};if(c.request!==`CAPCHA_NOT_READY`)throw Error(`2captcha solve failed: ${JSON.stringify(c)}`)}throw Error(`2captcha solve timeout after ${i}ms`)}async function st(n,r){let i=await r.getActivePage();if(!i)return k.fail(`No active page.`).build();let a=Z(n.mode??n.provider??process.env.CAPTCHA_PROVIDER),c=Q(n),d=S(n,`apiKey`,``)||process.env.CAPTCHA_API_KEY||``,f=at(n.challengeType??n.typeHint),p=Math.min(Math.max(E(n,`timeoutMs`,o),s),l),m=Math.min(Math.max(E(n,`maxRetries`,u),0),t),h=f,g=f===`image`?`image`:`recaptcha_v2`,_=S(n,`siteKey`),v=S(n,`pageUrl`,``)||i.url();if(h===`auto`){let e=await i.evaluate(()=>{if(document.querySelector(`[data-sitekey]`)){let e=document.querySelector(`[data-sitekey]`)?.getAttribute(`data-sitekey`)||``;return document.querySelector(`.cf-turnstile`)?{challengeType:`widget`,taskKind:`turnstile`,siteKey:e}:document.querySelector(`.h-captcha`)?{challengeType:`widget`,taskKind:`hcaptcha`,siteKey:e}:{challengeType:`widget`,taskKind:`recaptcha_v2`,siteKey:e}}return document.querySelector(`iframe[src*="recaptcha"]`)?{challengeType:`widget`,taskKind:`recaptcha_v2`,siteKey:``}:document.querySelector(`iframe[src*="hcaptcha"]`)?{challengeType:`widget`,taskKind:`hcaptcha`,siteKey:``}:document.querySelector(`.cf-turnstile`)?{challengeType:`widget`,taskKind:`turnstile`,siteKey:``}:{challengeType:`image`,taskKind:`image`,siteKey:``}});h=e.challengeType,g=e.taskKind,!_&&e.siteKey&&(_=e.siteKey)}else g=h===`image`?`image`:`recaptcha_v2`;if(a===`manual`)return k.ok().build({mode:`manual`,challengeType:h,siteKey:_??null,instruction:`Please solve the CAPTCHA manually in the browser, then continue.`,hint:`Configure an external solver service and CAPTCHA_API_KEY to automate this flow.`});if(!d)return k.fail(`External solver credentials are required. Set CAPTCHA_API_KEY.`).build();let y=null;for(let t=0;t<=m;t++)try{let e;if(c===`2captcha`)e=await $(d,{taskKind:g,siteKey:_,pageUrl:v},p);else if(c===`anticaptcha`||c===`capsolver`)throw Error(`The selected external solver service is not yet implemented. Currently only the configured primary service and manual mode are supported.`);else throw Error(`Unsupported external solver service.`);return k.ok().build({token:e.token,challengeType:e.challengeType,mode:e.mode,durationMs:e.durationMs,attempt:t+1})}catch(n){y=n instanceof Error?n:Error(String(n)),e.warn(`[captcha] Attempt ${t+1} failed: ${y.message}`)}return k.fail(y??Error(`All attempts failed`)).merge({challengeType:h,mode:a,maxRetries:m,suggestion:`Try manual mode or adjust the external solver configuration.`}).build()}async function ct(e,t){let n=await t.getActivePage();if(!n)return k.fail(`No active page.`).build();let r=Z(e.mode??e.provider??process.env.CAPTCHA_PROVIDER),i=Q(e),a=S(e,`apiKey`,``)||process.env.CAPTCHA_API_KEY||``,o=Math.min(Math.max(E(e,`timeoutMs`,12e4),5e3),6e5),s=O(e,`injectToken`,!0),c=S(e,`siteKey`),l=S(e,`pageUrl`,``)||n.url();if(c||=await n.evaluate(()=>document.querySelector(`.cf-turnstile[data-sitekey], [data-sitekey]`)?.getAttribute(`data-sitekey`)??``)||void 0,!c)return k.fail(`Could not detect the widget siteKey. Provide it manually or ensure the page exposes a site key.`).build();if(r===`hook`){let e=Math.min(o,3e4),t=await n.evaluate(e=>new Promise((t,n)=>{let r=setTimeout(()=>n(Error(`Hook timeout`)),e),i=window.__turnstile_callbacks;if(i)for(let[e,n]of Object.entries(i))i[e]=e=>{clearTimeout(r),t(e),n(e)};else clearTimeout(r),n(Error(`No widget callbacks found. Try external_service mode instead.`))}),e).catch(()=>null);if(t)return k.ok().build({token:t,method:`hook`,challengeType:`widget`,siteKey:c})}if(r===`manual`)return k.ok().build({mode:`manual`,challengeType:`widget`,siteKey:c,pageUrl:l,instruction:`Please complete the widget challenge manually.`});if(i!==`2captcha`)return k.fail(`The selected external solver service is not implemented for this widget flow. Currently only the configured primary service, manual mode, and hook mode are supported.`).build();if(!a)return k.fail(`External solver credentials are required.`).build();try{let e=await $(a,{taskKind:`turnstile`,siteKey:c,pageUrl:l},o);return s&&e.token&&await n.evaluate(e=>{document.querySelectorAll(`input[name*="turnstile"], input[name*="cf-turnstile"]`).forEach(t=>{t.value=e}),window.turnstile?.getResponse},e.token),k.ok().build({token:e.token,challengeType:e.challengeType,siteKey:c,mode:e.mode,durationMs:e.durationMs,injected:s})}catch(e){return k.fail(e).merge({siteKey:c,mode:r,suggestion:`Try manual mode or hook mode.`}).build()}}function lt(){return(process.env.CAPTCHA_PROVIDER||``).trim().toLowerCase()||`manual`}function ut(){return process.env.CAPTCHA_SOLVER_BASE_URL?.trim()||process.env.CAPTCHA_2CAPTCHA_BASE_URL?.trim()||``}function dt(){let e=lt(),t=ut(),n=!!process.env.CAPTCHA_API_KEY?.trim(),r=t.length>0,i=n&&r;return{capability:`captcha_external_service_2captcha`,status:i?`available`:`unavailable`,reason:i?void 0:`The 2captcha-compatible external path needs both CAPTCHA_API_KEY and CAPTCHA_SOLVER_BASE_URL.`,fix:i?void 0:`Set CAPTCHA_API_KEY and CAPTCHA_SOLVER_BASE_URL to enable external_service mode.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:e,defaultExternalProviderSupported:e===`2captcha`,apiKeyConfigured:n,baseUrlConfigured:r,...r?{baseUrl:t}:{}}}}async function ft(e){let t;try{t=await e.getActivePage()}catch(e){return{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Attach or launch a browser page before using hook mode.`,details:{tools:[`widget_challenge_solve`],pageAttached:!1}}}if(!t)return{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`No active page is attached.`,fix:`Attach or launch a browser page before using hook mode.`,details:{tools:[`widget_challenge_solve`],pageAttached:!1}};try{let e=await t.evaluate(()=>{let e=window.__turnstile_callbacks,t=e&&typeof e==`object`&&!Array.isArray(e)?Object.keys(e).length:0;return{url:location.href,callbackCount:t}});return{capability:`captcha_widget_hook_current_page`,status:e.callbackCount>0?`available`:`unavailable`,reason:e.callbackCount>0?void 0:`The current page does not expose window.__turnstile_callbacks for hook mode.`,fix:e.callbackCount>0?void 0:`Use manual mode, or configure the external 2captcha-compatible service for widget solving.`,details:{tools:[`widget_challenge_solve`],pageAttached:!0,...e}}}catch(e){return{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Ensure the attached page is reachable before using hook mode.`,details:{tools:[`widget_challenge_solve`],pageAttached:!0}}}}async function pt(e){let t=lt(),n=await ft(e);return k.raw(ae(`captcha_solver_capabilities`,[{capability:`captcha_manual`,status:`available`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`]}},dt(),{capability:`captcha_external_service_anticaptcha`,status:`unavailable`,reason:`AntiCaptcha integration is not implemented in this build.`,fix:`Use manual mode or the configured 2captcha-compatible service instead.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:t}},{capability:`captcha_external_service_capsolver`,status:`unavailable`,reason:`CapSolver integration is not implemented in this build.`,fix:`Use manual mode or the configured 2captcha-compatible service instead.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:t}},n],{configuredProvider:t}))}function mt(e){let t=T(e,`addons`),n=T(e,`excludeAddons`),r=T(e,`fonts`);return{headless:O(e,`headless`,!0),os:S(e,`os`,`windows`),geoip:O(e,`geoip`,!1),humanize:O(e,`humanize`,!1),proxy:S(e,`proxy`)||void 0,blockImages:O(e,`blockImages`,!1),blockWebrtc:O(e,`blockWebrtc`,!1),blockWebgl:O(e,`blockWebgl`,!1),locale:S(e,`locale`)||void 0,addons:t.length>0?t:void 0,fonts:r.length>0?r:void 0,excludeAddons:n.length>0?n:void 0,customFontsOnly:O(e,`customFontsOnly`,!1),screen:e.screen,window:e.window,fingerprint:C(e,`fingerprint`),webglConfig:C(e,`webglConfig`),firefoxUserPrefs:C(e,`firefoxUserPrefs`),mainWorldEval:O(e,`mainWorldEval`,!0),enableCache:O(e,`enableCache`,!1)}}async function ht(e,t){try{let n=mt(t);if(S(t,`mode`,`launch`)===`connect`){let r=S(t,`wsEndpoint`);if(!r)return k.fail(`wsEndpoint is required for connect mode.`).build();let i=new g(n);return await i.connectToServer(r),e.setCamoufoxManager(i),e.setActiveDriver(`camoufox`),e.clearCamoufoxPage(),k.ok().build({driver:`camoufox`,mode:`connect`,wsEndpoint:r,message:`Connected to Camoufox server.`})}let r=new g(n);return await r.launch(),e.setCamoufoxManager(r),e.setActiveDriver(`camoufox`),e.clearCamoufoxPage(),k.ok().build({driver:`camoufox`,mode:`launch`,config:{os:n.os,headless:n.headless,geoip:n.geoip,humanize:n.humanize,locale:n.locale,blockWebgl:n.blockWebgl,blockImages:n.blockImages,blockWebrtc:n.blockWebrtc},message:`Camoufox (Firefox) browser launched`})}catch(e){return k.fail(e).build()}}async function gt(e,t){try{let n=S(t,`url`,``),r=j(t),i=E(t,`timeout`),a=await e.getCamoufoxPage();return await a.goto(n,{waitUntil:r,timeout:i}),e.setConsoleMonitorPage(a),k.ok().build({driver:`camoufox`,url:a.url(),title:await a.title()})}catch(e){return k.fail(e).build()}}const _t=new Set([`page_navigate`,`page_click`,`page_type`,`page_hover`,`page_scroll`,`page_press_key`,`page_select`,`page_upload_files`,`page_wait_for_selector`]);var vt=class{collector;pageController;scriptManager;consoleMonitor;captchaDetector;detailedDataManager;camoufoxManager=null;activeDriver=`chrome`;camoufoxPage=null;autoDetectCaptcha=!0;autoSwitchHeadless=!0;captchaTimeout=3e5;browserControl;targetControl;camoufoxBrowser;pageNavigation;pageInteraction;pageEvaluation;targetEvaluation;pageData;consoleHandlers;scriptManagement;captchaHandlers;stealthInjection;frameworkState;indexedDBDump;jsHeapSearch;tabWorkflow;detailedData;jsdomHandlers;tabRegistry;eventBus;codegenStopListening;codegenSteps=[];constructor(e,t,n,r,i){this.collector=e,this.pageController=t,this.scriptManager=n,this.consoleMonitor=r,this.eventBus=i;let a=y(v().paths.captchaScreenshotDir,`screenshots/captcha`);this.captchaDetector=new m(a),this.detailedDataManager=d.getInstance();let o=Xe({collector:this.collector,pageController:this.pageController,scriptManager:this.scriptManager,consoleMonitor:this.consoleMonitor,eventBus:i,captchaDetector:this.captchaDetector,detailedDataManager:this.detailedDataManager,getActiveDriver:()=>this.activeDriver,getCamoufoxPage:()=>this.getCamoufoxPage(),getCamoufoxManager:()=>this.camoufoxManager,setCamoufoxManager:e=>{this.camoufoxManager=e},closeCamoufox:()=>this.closeCamoufox(),getAutoDetectCaptcha:()=>this.autoDetectCaptcha,getAutoSwitchHeadless:()=>this.autoSwitchHeadless,getCaptchaTimeout:()=>this.captchaTimeout,setAutoDetectCaptcha:e=>{this.autoDetectCaptcha=e},setAutoSwitchHeadless:e=>{this.autoSwitchHeadless=e},setCaptchaTimeout:e=>{this.captchaTimeout=e}});this.browserControl=o.browserControl,this.targetControl=o.targetControl,this.camoufoxBrowser=o.camoufoxBrowser,this.pageNavigation=o.pageNavigation,this.pageInteraction=o.pageInteraction,this.pageEvaluation=o.pageEvaluation,this.targetEvaluation=o.targetEvaluation,this.pageData=o.pageData,this.consoleHandlers=o.consoleHandlers,this.scriptManagement=o.scriptManagement,this.captchaHandlers=o.captchaHandlers,this.stealthInjection=o.stealthInjection,this.frameworkState=o.frameworkState,this.indexedDBDump=o.indexedDBDump,this.jsHeapSearch=o.jsHeapSearch,this.tabWorkflow=o.tabWorkflow,this.detailedData=o.detailedData,this.jsdomHandlers=o.jsdomHandlers,this.tabRegistry=o.tabRegistry}makeJsonResponse(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}sanitizeCodegenArgs(e){let t={...e};for(let e of[`delay`,`timeout`])t[e]===void 0&&delete t[e];return t}isSameFrameArgs(e,t){return(e.frameUrl??null)===(t.frameUrl??null)&&(e.frameSelector??null)===(t.frameSelector??null)}compactCodegenSteps(e){let t=[];for(let n of e){let e={tool:n.tool,args:this.sanitizeCodegenArgs(n.args),timestamp:n.timestamp},r=t.at(-1);if(!r){t.push(e);continue}if(e.tool===`page_wait_for_selector`&&r.tool===`page_wait_for_selector`&&e.args.selector===r.args.selector&&this.isSameFrameArgs(e.args,r.args)){r.timestamp=e.timestamp;continue}if(!(e.tool===`page_wait_for_selector`&&(r.tool===`page_click`||r.tool===`page_type`)&&e.args.selector===r.args.selector&&this.isSameFrameArgs(e.args,r.args))){if(e.tool===r.tool&&JSON.stringify(e.args)===JSON.stringify(r.args)){r.timestamp=e.timestamp;continue}t.push(e)}}return t}formatCodegenScript(e){return[`const steps = [`,...e.map(e=>` ${JSON.stringify({tool:e.tool,args:e.args},null,0)},`),`];`,``,`for (const step of steps) {`,` await callTool(step.tool, step.args);`,`}`].join(`
11
- `)}getTabRegistry(){return this.tabRegistry}async getCamoufoxPage(){if(!this.camoufoxManager)throw Error(`Camoufox browser not launched. Call browser_launch(driver="camoufox") first.`);return this.camoufoxPage||=await this.camoufoxManager.newPage(),this.camoufoxPage}async closeCamoufox(){try{await this.consoleMonitor.disable()}catch(t){e.warn(`Failed to reset console monitor before closing Camoufox: ${String(t)}`)}this.consoleMonitor.clearPlaywrightPage(),this.camoufoxManager&&(await this.camoufoxManager.close(),this.camoufoxManager=null,this.camoufoxPage=null)}async handleBrowserLaunch(e){return S(e,`driver`,`chrome`)===`camoufox`?this.handleCamoufoxLaunch(e):(this.activeDriver===`camoufox`&&this.camoufoxManager&&await this.closeCamoufox(),this.activeDriver=`chrome`,this.browserControl.handleBrowserLaunch(e))}async handleBrowserClose(e){return this.activeDriver===`camoufox`&&this.camoufoxManager?(await this.closeCamoufox(),await this.browserControl.handleBrowserClose(e),this.activeDriver=`chrome`,{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Camoufox browser closed`},null,2)}]}):this.browserControl.handleBrowserClose(e)}async handleBrowserStatus(e){if(this.activeDriver===`camoufox`){let e=!!this.camoufoxManager?.getBrowser();return{content:[{type:`text`,text:JSON.stringify({success:!0,driver:`camoufox`,running:e,hasActivePage:!!this.camoufoxPage},null,2)}]}}return this.browserControl.handleBrowserStatus(e)}async handleBrowserListTabs(e){return this.browserControl.handleBrowserListTabs(e)}async handleBrowserListCdpTargets(e){return this.targetControl.handleBrowserListCdpTargets(e)}async handleBrowserSelectTab(e){return this.browserControl.handleBrowserSelectTab(e)}async handleBrowserAttachCdpTarget(e){return this.targetControl.handleBrowserAttachCdpTarget(e)}async handleBrowserDetachCdpTarget(e){return this.targetControl.handleBrowserDetachCdpTarget(e)}async handleBrowserEvaluateCdpTarget(e){return this.targetEvaluation.handleBrowserEvaluateCdpTarget(e)}async handleBrowserAttach(e){return this.activeDriver===`camoufox`&&this.camoufoxManager&&await this.closeCamoufox(),this.activeDriver=`chrome`,this.browserControl.handleBrowserAttach(e)}async handleCamoufoxServerDispatch(e){switch(String(e.action??``)){case`close`:return this.camoufoxBrowser.handleCamoufoxServerClose(e);case`status`:return this.camoufoxBrowser.handleCamoufoxServerStatus(e);default:return this.camoufoxBrowser.handleCamoufoxServerLaunch(e)}}async handleCamoufoxServerLaunch(e){return this.camoufoxBrowser.handleCamoufoxServerLaunch(e)}async handleCamoufoxServerClose(e){return this.camoufoxBrowser.handleCamoufoxServerClose(e)}async handleCamoufoxServerStatus(e){return this.camoufoxBrowser.handleCamoufoxServerStatus(e)}async handlePageNavigate(e){return this.activeDriver===`camoufox`?this.handleCamoufoxNavigate(e):this.pageNavigation.handlePageNavigate(e)}async handlePageReload(e){return this.pageNavigation.handlePageReload(e)}async handlePageBack(e){return this.pageNavigation.handlePageBack(e)}async handlePageForward(e){return this.pageNavigation.handlePageForward(e)}async handlePageListFrames(e){return this.pageData.handlePageListFrames(e)}async handlePageClick(e){return this.pageInteraction.handlePageClick(e)}async handlePageType(e){return this.pageInteraction.handlePageType(e)}async handlePageUploadFiles(e){return this.pageInteraction.handlePageUploadFiles(e)}async handlePageSelect(e){return this.pageInteraction.handlePageSelect(e)}async handlePageHover(e){return this.pageInteraction.handlePageHover(e)}async handlePageScroll(e){return this.pageInteraction.handlePageScroll(e)}async handlePagePressKey(e){return this.pageInteraction.handlePagePressKey(e)}async handlePageEvaluate(e){return this.pageEvaluation.handlePageEvaluate(e)}async handlePageScreenshot(e){return this.pageEvaluation.handlePageScreenshot(e)}async handlePageInjectScript(e){return this.pageEvaluation.handlePageInjectScript(e)}async handlePageWaitForSelector(e){return this.pageEvaluation.handlePageWaitForSelector(e)}async handlePageCookiesDispatch(e){let t=String(e.action??``);switch(t){case`get`:return this.pageData.handlePageGetCookies(e);case`set`:return this.pageData.handlePageSetCookies(e);case`clear`:{let t=e.expectedCount;if(typeof t!=`number`||t<0)return f(new p(`VALIDATION`,`action=clear requires expectedCount (number). Call action=get first to obtain the current cookie count.`,{toolName:`page_cookies`}));let n=await this.pageData.getPageCookieCount();return n===t?this.pageData.handlePageClearCookies(e):f(new p(`VALIDATION`,`Cookie count mismatch: expected ${t} but found ${n}. Call action=get to refresh, then retry with the correct count.`,{toolName:`page_cookies`,details:{expected:t,actual:n}}))}default:return f(new p(`VALIDATION`,`Invalid action: "${t}". Expected one of: get, set, clear`,{toolName:`page_cookies`}))}}async handlePageSetViewport(e){return this.pageData.handlePageSetViewport(e)}async handlePageEmulateDevice(e){return this.pageData.handlePageEmulateDevice(e)}async handlePageLocalStorageDispatch(e){let t=String(e.action??``);switch(t){case`get`:return this.pageData.handlePageGetLocalStorage(e);case`set`:return this.pageData.handlePageSetLocalStorage(e);default:return f(new p(`VALIDATION`,`Invalid action: "${t}". Expected one of: get, set`,{toolName:`page_local_storage`}))}}async handleConsoleMonitor(e){return this.consoleHandlers.handleConsoleMonitor(e)}async handleConsoleGetLogs(e){return this.consoleHandlers.handleConsoleGetLogs(e)}async handleConsoleExecute(e){return this.consoleHandlers.handleConsoleExecute(e)}async handleGetAllScripts(e){return this.scriptManagement.handleGetAllScripts(e)}async handleGetScriptSource(e){return this.scriptManagement.handleGetScriptSource(e)}async handleCaptchaDetect(e){return this.captchaHandlers.handleCaptchaDetect(e)}async handleCaptchaWait(e){return this.captchaHandlers.handleCaptchaWait(e)}async handleCaptchaConfig(e){return this.captchaHandlers.handleCaptchaConfig(e)}async handleStealthInject(e){return this.stealthInjection.handleStealthInject(e)}async handleStealthSetUserAgent(e){return this.stealthInjection.handleStealthSetUserAgent(e)}async handleStealthConfigureJitter(e){return this.stealthInjection.handleStealthConfigureJitter(e)}async handleStealthGenerateFingerprint(e){return this.stealthInjection.handleStealthGenerateFingerprint(e)}async handleStealthVerify(e){return this.stealthInjection.handleStealthVerify(e)}async handleCamoufoxGeolocation(e){return this.stealthInjection.handleCamoufoxGeolocation(e)}async handleFrameworkStateExtract(e){return this.frameworkState.handleFrameworkStateExtract(e)}async handleIndexedDBDump(e){return this.indexedDBDump.handleIndexedDBDump(e)}async handleJSHeapSearch(e){return this.jsHeapSearch.handleJSHeapSearch(e)}async handleTabWorkflow(e){return this.tabWorkflow.handleTabWorkflow(e)}async handleBrowserCodegenStart(){return this.eventBus?(this.codegenStopListening?.(),this.codegenSteps=[],this.codegenStopListening=this.eventBus.on(`tool:called`,e=>{e.domain!==`browser`||!e.success||e.result?.success===!1||_t.has(e.toolName)&&this.codegenSteps.push({tool:e.toolName,args:{...e.args},timestamp:e.timestamp})}),this.makeJsonResponse({success:!0,recording:!0,message:`Browser action recording started.`})):this.makeJsonResponse({success:!1,message:`Event bus unavailable for browser codegen recording.`})}async handleBrowserCodegenStop(){this.codegenStopListening?.(),this.codegenStopListening=void 0;let e=[...this.codegenSteps],t=this.compactCodegenSteps(e);return this.codegenSteps=[],this.makeJsonResponse({success:!0,recording:!1,stepCount:t.length,rawStepCount:e.length,steps:t,script:this.formatCodegenScript(t)})}async handleGetDetailedData(e){return this.detailedData.handleGetDetailedData(e)}async handleCamoufoxLaunch(e){return ht({setCamoufoxManager:e=>{this.camoufoxManager=e},setActiveDriver:e=>{this.activeDriver=e},clearCamoufoxPage:()=>{this.camoufoxPage=null}},e)}async handleCamoufoxNavigate(e){return gt({getCamoufoxPage:()=>this.getCamoufoxPage(),setConsoleMonitorPage:e=>{this.consoleMonitor.setPlaywrightPage(e)}},e)}async handleHumanMouse(e){return tt(e,this.collector,this.pageController)}async handleHumanScroll(e){return nt(e,this.collector)}async handleHumanTyping(e){return rt(e,this.collector,this.pageController)}async handleCaptchaVisionSolve(e){return st(e,this.collector)}async handleWidgetChallengeSolve(e){return ct(e,this.collector)}async handleCaptchaSolverCapabilities(){return pt(this.collector)}async handleJsdomParse(e){return this.jsdomHandlers.handleJsdomParse(e)}async handleJsdomQuery(e){return this.jsdomHandlers.handleJsdomQuery(e)}async handleJsdomExecute(e){return this.jsdomHandlers.handleJsdomExecute(e)}async handleJsdomSerialize(e){return this.jsdomHandlers.handleJsdomSerialize(e)}async handleJsdomCookies(e){return this.jsdomHandlers.handleJsdomCookies(e)}};export{vt as BrowserToolHandlers};
@@ -1 +0,0 @@
1
- import{ConsoleMonitor as e}from"./ConsoleMonitor-Dkqc0HNi.mjs";import"./PageController-D9jVkH0i.mjs";import{n as t}from"./DOMInspector-BYY_EJ0C.mjs";export{t as CodeCollector,e as ConsoleMonitor};
@@ -1 +0,0 @@
1
- import{cpus as e}from"node:os";const t=(e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=parseInt(n,10);return Number.isFinite(r)?r:t},n=(e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=Number.parseFloat(n);return Number.isFinite(r)?r:t},r=(e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=n.trim().toLowerCase();return r===`true`||r===`1`?!0:r===`false`||r===`0`?!1:t},i=(e,t)=>process.env[e]||t,ee=(e,t)=>{let n=process.env[e];return n?n.split(`,`).map(Number).filter(Number.isFinite):t},te=(e,t)=>{let n=process.env[e];if(!n)return t;let r=n.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);return r.length>0?r:t},a=(e,n,r)=>{let i=process.env[e];if(i!==void 0&&i.trim().toLowerCase()===`auto`){let e=r();return Number.isFinite(e)&&e>0?Math.floor(e):n}return t(e,n)},o=()=>{try{return e().length}catch{return 4}},s=t(`SHUTDOWN_TIMEOUT_MS`,2e4),c=t(`RUNTIME_ERROR_WINDOW_MS`,6e4),l=t(`RUNTIME_ERROR_THRESHOLD`,8),u=ee(`DEBUG_PORT_CANDIDATES`,[9222,9229,9333,2039]),d=t(`DEFAULT_DEBUG_PORT`,9222),f=i(`GHIDRA_BRIDGE_URL`,`http://127.0.0.1:18080`),p=i(`IDA_BRIDGE_URL`,`http://127.0.0.1:18081`),m=process.env.CAPTCHA_SOLVER_BASE_URL?.trim()||process.env.CAPTCHA_2CAPTCHA_BASE_URL?.trim()||``;process.env.EXTENSION_REGISTRY_BASE_URL?.trim();const h=t(`MCP_HTTP_REQUEST_TIMEOUT_MS`,3e4),g=t(`MCP_HTTP_HEADERS_TIMEOUT_MS`,1e4),_=t(`MCP_HTTP_KEEPALIVE_TIMEOUT_MS`,864e5),v=t(`MCP_HTTP_FORCE_CLOSE_TIMEOUT_MS`,5e3),y=t(`EXTERNAL_TOOL_TIMEOUT_MS`,3e4),b=t(`EXTERNAL_TOOL_PROBE_TIMEOUT_MS`,5e3),x=t(`EXTERNAL_TOOL_PROBE_CACHE_TTL_MS`,6e4),S=t(`EXTERNAL_TOOL_FORCE_KILL_GRACE_MS`,2e3),C=t(`SANDBOX_EXEC_TIMEOUT_MS`,5e3),w=t(`SANDBOX_MEMORY_LIMIT_MB`,128),T=t(`SANDBOX_STACK_SIZE_MB`,4),E=t(`SANDBOX_TERMINATE_GRACE_MS`,2e3);t(`SYMBOLIC_EXEC_MAX_PATHS`,100),t(`SYMBOLIC_EXEC_MAX_DEPTH`,50),t(`SYMBOLIC_EXEC_TIMEOUT_MS`,3e4);const D=t(`JSVMP_DEOBFUSCATE_TIMEOUT_MS`,3e4),O=t(`JSVMP_MAX_ITERATIONS`,100);t(`JSVMP_SYMBOLIC_MAX_STEPS`,1e3),t(`JSVMP_SYMBOLIC_TIMEOUT_MS`,3e4);const k=t(`DEBUGGER_WAIT_FOR_PAUSED_TIMEOUT_MS`,3e4),A=t(`WATCH_EVAL_TIMEOUT_MS`,5e3),j=t(`TRANSFORM_WORKER_TIMEOUT_MS`,15e3);t(`TRANSFORM_VM_SCRIPT_TIMEOUT_MS`,5e3);const M=t(`TRANSFORM_CRYPTO_POOL_MAX_WORKERS`,4),N=t(`TRANSFORM_CRYPTO_POOL_IDLE_TIMEOUT_MS`,3e4),P=t(`TRANSFORM_CRYPTO_POOL_MAX_OLD_GEN_MB`,64),F=t(`TRANSFORM_CRYPTO_POOL_MAX_YOUNG_GEN_MB`,16);t(`EMULATOR_FETCH_GOTO_TIMEOUT_MS`,3e4);const I=t(`WASM_TOOL_TIMEOUT_MS`,6e4);t(`WASM_OFFLINE_RUN_TIMEOUT_MS`,1e4);const L=t(`WASM_OPTIMIZE_TIMEOUT_MS`,12e4);t(`MINIAPP_UNPACK_TIMEOUT_MS`,18e4);const R=t(`CAPTCHA_SUBMIT_TIMEOUT_MS`,15e3);t(`FETCH_ABORT_TIMEOUT_MS`,1e4);const z=t(`CAPTCHA_POLL_INTERVAL_MS`,5e3),B=t(`CAPTCHA_RESULT_TIMEOUT_MS`,1e4),V=t(`CAPTCHA_DEFAULT_TIMEOUT_MS`,18e4),H=t(`CAPTCHA_MIN_TIMEOUT_MS`,5e3),U=t(`CAPTCHA_MAX_TIMEOUT_MS`,6e5),W=t(`CAPTCHA_MAX_RETRIES`,5),G=t(`CAPTCHA_DEFAULT_RETRIES`,2);t(`NETWORK_REPLAY_TIMEOUT_MS`,3e4),t(`NETWORK_REPLAY_MAX_BODY_BYTES`,512e3);const K=t(`NETWORK_REPLAY_MAX_REDIRECTS`,5),q=t(`NETWORK_HAR_BODY_CONCURRENCY`,4);t(`WORKFLOW_BATCH_MAX_ACCOUNTS`,50),t(`WORKFLOW_BATCH_MAX_CONCURRENCY`,1),t(`WORKFLOW_REGISTER_ACCOUNT_TIMEOUT_MS`,6e4),t(`WORKFLOW_ACTION_DELAY_MS`,1e3),t(`WORKFLOW_SETTLE_DELAY_MS`,2e3),t(`WORKFLOW_INPUT_DELAY_MS`,1500),t(`WORKFLOW_BATCH_MAX_RETRIES`,3),t(`WORKFLOW_BATCH_MAX_BACKOFF_MS`,3e4),t(`WORKFLOW_BATCH_MAX_TIMEOUT_MS`,3e5),t(`WORKFLOW_BATCH_RETRY_BACKOFF_MS`,2e3),t(`WORKFLOW_BATCH_TIMEOUT_PER_ACCOUNT_MS`,9e4);const J=t(`WORKFLOW_JS_BUNDLE_MAX_SIZE_BYTES`,20*1024*1024),Y=t(`WORKFLOW_JS_BUNDLE_MAX_REDIRECTS`,5),X=t(`WORKFLOW_JS_BUNDLE_FETCH_TIMEOUT_MS`,3e4),Z=t(`WORKFLOW_BUNDLE_CACHE_TTL_MS`,300*1e3),Q=t(`WORKFLOW_BUNDLE_CACHE_MAX_BYTES`,100*1024*1024);new Set(te(`SEARCH_WORKFLOW_BOOST_TIERS`,[`workflow`,`full`]));const ne=n(`SEARCH_WORKFLOW_DOMAIN_BOOST_MULTIPLIER`,2.4),re=t(`ACTIVATION_TTL_MINUTES`,30);r(`SEARCH_AUTO_ACTIVATE_DOMAINS`,!0);const ie=t(`AUTOPRUNE_AUTO_INACTIVITY_MS`,15*6e4),ae=t(`AUTOPRUNE_MANUAL_INACTIVITY_MS`,30*6e4),oe=t(`AUTOPRUNE_CHECK_INTERVAL_MS`,6e4),se=t(`PREDICTIVE_MAX_HISTORY`,100),ce=n(`PREDICTIVE_CONFIDENCE_THRESHOLD`,.25),le=n(`PREDICTIVE_DECAY_FACTOR`,.95),ue=t(`ACTIVATION_COOLDOWN_MS`,3e4),de=t(`ACTIVATION_COMPOUND_EVAL_EVERY`,5),fe=t(`ACTIVATION_EVENT_HISTORY_MAX`,200),pe=t(`ACTIVATION_BOOST_WINDOW_MS`,6e4),me=t(`COMPOUND_EVENT_WINDOW_MS`,12e4),he=t(`COMPOUND_LONG_WINDOW_MS`,3e5),ge=n(`SEARCH_AFFINITY_BOOST_FACTOR`,.38),_e=t(`SEARCH_AFFINITY_TOP_N`,9),ve=t(`SEARCH_DOMAIN_HUB_THRESHOLD`,5),ye=t(`SEARCH_QUERY_CACHE_CAPACITY`,500),be=n(`SEARCH_CACHE_VECTOR_WEIGHT_TOLERANCE`,.05),xe=n(`SEARCH_TRIGRAM_WEIGHT`,.02),Se=n(`SEARCH_TRIGRAM_THRESHOLD`,.47),Ce=t(`SEARCH_RRF_K`,18),we=n(`SEARCH_RRF_RESCALE_FACTOR`,2100),Te=n(`SEARCH_RRF_BM25_BLEND`,.39),Ee=t(`SEARCH_SYNONYM_EXPANSION_LIMIT`,2),De=n(`SEARCH_PARAM_TOKEN_WEIGHT`,1.1),Oe=n(`SEARCH_SCENE_KEYWORD_WEIGHT`,.8),ke=n(`SEARCH_BM25_K1`,1),Ae=n(`SEARCH_BM25_B`,.75),je=r(`SEARCH_VECTOR_ENABLED`,!0),Me=i(`SEARCH_VECTOR_MODEL_ID`,`Xenova/bge-micro-v2`),Ne=n(`SEARCH_VECTOR_COSINE_WEIGHT`,.53),Pe=r(`SEARCH_VECTOR_DYNAMIC_WEIGHT`,!0),Fe=n(`SEARCH_VECTOR_LEARN_UP`,.13),Ie=n(`SEARCH_VECTOR_LEARN_DOWN`,.02),Le=t(`SEARCH_VECTOR_LEARN_TOP_N`,3),Re=n(`SEARCH_VECTOR_BM25_SKIP_THRESHOLD`,8),ze=n(`SEARCH_TIER_PENALTY`,.35),Be=n(`SEARCH_TIER_PENALTY_SEARCH`,.4),Ve=n(`SEARCH_TIER_PENALTY_WORKFLOW`,.6),He=n(`SEARCH_TIER_PENALTY_FULL`,.6),Ue=t(`SEARCH_RECENCY_WINDOW_MS`,30*6e4),We=n(`SEARCH_RECENCY_MAX_BOOST`,.1),Ge=t(`SEARCH_RECENCY_TRACKER_MAX`,200),Ke=n(`SEARCH_EXACT_NAME_MATCH_MULTIPLIER`,3.2),qe=n(`SEARCH_DOMAIN_HUB_BOOST_MULTIPLIER`,1.04),Je=n(`SEARCH_AFFINITY_BASE_WEIGHT`,.5),Ye=n(`SEARCH_COVERAGE_PRECISION_FACTOR`,.94),Xe=n(`SEARCH_PREFIX_MATCH_MULTIPLIER`,.84),Ze=n(`RERANK_MAINTENANCE_PENALTY`,.43),Qe=n(`RERANK_STATELESS_INTERACTIVE_PENALTY`,.65),$e=n(`RERANK_STATELESS_CORE_PENALTY`,.15),et=n(`RERANK_STATELESS_COMPUTE_BOOST`,2.2),tt=n(`RERANK_STATELESS_SPECIFIC_TOOL_BOOST`,2.25),nt=n(`RERANK_BROWSER_LAUNCH_BOOST`,1.35),rt=n(`RERANK_BROWSER_ATTACH_BOOST`,1.55),it=n(`RERANK_NETWORK_MONITOR_BOOST`,1.6),at=n(`RERANK_NETWORK_GET_REQUESTS_BOOST`,1.55),ot=t(`PREDICTIVE_MAX_SECOND_ORDER_KEYS`,1e3),st=t(`EXTENSION_GIT_CLONE_TIMEOUT_MS`,6e4),ct=t(`EXTENSION_GIT_CHECKOUT_TIMEOUT_MS`,3e4),lt=t(`PROCESS_LIST_MAX_BUFFER_BYTES`,1024*1024*10),ut=t(`EXTERNAL_TOOL_MAX_STDOUT_BYTES`,10*1024*1024),dt=t(`EXTERNAL_TOOL_MAX_STDERR_BYTES`,1*1024*1024),ft=t(`GRAPHQL_MAX_PREVIEW_CHARS`,4e3),pt=t(`GRAPHQL_MAX_SCHEMA_CHARS`,12e4),mt=t(`GRAPHQL_MAX_QUERY_CHARS`,12e3),ht=t(`GRAPHQL_MAX_GRAPH_NODES`,2e3),gt=t(`GRAPHQL_MAX_GRAPH_EDGES`,5e3),$=t(`ANALYSIS_MAX_SUMMARY_FILES`,40),_t=t(`ANALYSIS_MAX_SAFE_COLLECTED_BYTES`,256*1024),vt=t(`ANALYSIS_MAX_SAFE_RESPONSE_BYTES`,220*1024),yt=t(`WS_PAYLOAD_PREVIEW_LIMIT`,200),bt=t(`WS_PAYLOAD_SAMPLE_LIMIT`,2e3),xt=t(`SCRIPTS_MAX_CAP`,500),St=t(`WORKER_POOL_MIN_WORKERS`,2),Ct=a(`WORKER_POOL_MAX_WORKERS`,4,()=>{let e=Math.floor(o()/2),n=t(`WORKER_POOL_MIN_WORKERS`,2);return Math.max(n,Math.min(8,e))}),wt=t(`WORKER_POOL_IDLE_TIMEOUT_MS`,3e4),Tt=t(`WORKER_POOL_JOB_TIMEOUT_MS`,15e3);t(`PARALLEL_DEFAULT_CONCURRENCY`,3),t(`PARALLEL_DEFAULT_TIMEOUT_MS`,6e4),t(`PARALLEL_DEFAULT_MAX_RETRIES`,2),t(`PARALLEL_RETRY_BACKOFF_BASE_MS`,1e3);const Et=t(`CACHE_GLOBAL_MAX_SIZE_BYTES`,500*1024*1024),Dt=n(`CACHE_LOW_HIT_RATE_THRESHOLD`,.3),Ot=t(`TOKEN_BUDGET_MAX_TOKENS`,2e5),kt=t(`DETAILED_DATA_DEFAULT_TTL_MS`,1800*1e3),At=t(`DETAILED_DATA_MAX_TTL_MS`,3600*1e3),jt=t(`DETAILED_DATA_SMART_THRESHOLD_BYTES`,50*1024);t(`ADV_DEOBF_LLM_MAX_TOKENS`,3e3),t(`VM_DEOBF_LLM_MAX_TOKENS`,4e3),t(`DEOBF_LLM_MAX_TOKENS`,2e3),t(`CRYPTO_DETECT_LLM_MAX_TOKENS`,2e3);const Mt=t(`MEMORY_READ_TIMEOUT_MS`,1e4),Nt=t(`MEMORY_MAX_READ_BYTES`,16*1024*1024),Pt=t(`MEMORY_WRITE_TIMEOUT_MS`,1e4),Ft=t(`MEMORY_MAX_WRITE_BYTES`,16*1024),It=t(`MEMORY_DUMP_TIMEOUT_MS`,6e4),Lt=t(`MEMORY_SCAN_TIMEOUT_MS`,12e4),Rt=t(`MEMORY_SCAN_MAX_BUFFER_BYTES`,1024*1024*50),zt=t(`MEMORY_SCAN_MAX_RESULTS`,1e4);t(`MEMORY_SCAN_MAX_REGIONS`,5e4),t(`MEMORY_SCAN_REGION_MAX_BYTES`,16777216);const Bt=t(`MEMORY_INJECT_TIMEOUT_MS`,3e4),Vt=r(`ENABLE_INJECTION_TOOLS`,!0);t(`MEMORY_MONITOR_INTERVAL_MS`,1e3);const Ht=t(`MEMORY_VMMAP_TIMEOUT_MS`,15e3),Ut=t(`MEMORY_PROTECTION_QUERY_TIMEOUT_MS`,15e3),Wt=t(`MEMORY_PROTECTION_PWSH_TIMEOUT_MS`,3e4),Gt=t(`NATIVE_ADMIN_CHECK_TIMEOUT_MS`,5e3);t(`NATIVE_SCAN_MAX_RESULTS`,1e4);const Kt=t(`PROCESS_LAUNCH_WAIT_MS`,2e3),qt=t(`WIN_DEBUG_PORT_POLL_ATTEMPTS`,20),Jt=t(`WIN_DEBUG_PORT_POLL_INTERVAL_MS`,500);t(`PACKER_SANDBOX_TIMEOUT_MS`,3e3);const Yt=t(`CODE_CAVE_MIN_SIZE`,16),Xt=t(`BREAKPOINT_HIT_TIMEOUT_MS`,1e4),Zt=t(`BREAKPOINT_TRACE_MAX_HITS`,100),Qt=t(`HEAP_ENUMERATE_MAX_BLOCKS`,1e4),$t=t(`HEAP_SPRAY_THRESHOLD`,50),en=t(`HEAP_SPRAY_SIZE_TOLERANCE`,64),tn=t(`HEAP_SUSPICIOUS_BLOCK_SIZE`,10485760),nn=t(`FREEZE_DEFAULT_INTERVAL_MS`,100),rn=t(`WRITE_HISTORY_MAX`,200),an=t(`SCAN_MAX_RESULTS_PER_SCAN`,1e5),on=t(`SCAN_DISPLAY_RESULTS_LIMIT`,200),sn=t(`SCAN_UNKNOWN_INITIAL_MAX_ADDRESSES`,5e5),cn=t(`SCAN_POINTER_MAX_RESULTS`,5e3),ln=t(`SCAN_GROUP_MAX_PATTERN_SIZE`,256),un=t(`SCAN_SESSION_MAX_COUNT`,20),dn=t(`SCAN_SESSION_TTL_MS`,18e5),fn=t(`POINTER_CHAIN_MAX_DEPTH`,6),pn=t(`POINTER_CHAIN_MAX_OFFSET`,4096),mn=t(`POINTER_CHAIN_MAX_RESULTS`,500),hn=t(`POINTER_CHAIN_SCAN_CHUNK_SIZE`,16777216),gn=t(`STRUCT_ANALYZE_DEFAULT_SIZE`,256),_n=t(`STRUCT_VTABLE_MAX_FUNCTIONS`,64),vn=t(`STRUCT_RTTI_MAX_STRING_LEN`,256);t(`STRUCT_CSTRING_MAX_LEN`,256);const yn=t(`FRIDA_TIMEOUT_MS`,15e3),bn=t(`GHIDRA_TIMEOUT_MS`,12e4),xn=t(`UNIDBG_TIMEOUT_MS`,6e4),Sn=t(`ADB_DEFAULT_TIMEOUT_MS`,3e4),Cn=t(`ADB_SHELL_TIMEOUT_MS`,6e4),wn=t(`ADB_WEBVIEW_HTTP_TIMEOUT_MS`,5e3),Tn=t(`ADB_WEBVIEW_WS_TIMEOUT_MS`,1e4),En=t(`MOJO_MONITOR_TIMEOUT_MS`,1e4),Dn=t(`MEMORY_AVAILABILITY_CACHE_TTL_MS`,45e3),On=t(`HTTP_RATE_LIMIT_MAX_IPS`,1e4),kn=t(`HTTP_CLEANUP_INTERVAL_MS`,5*6e4);t(`SSE_HEARTBEAT_MS`,3e4);const An=r(`MCP_COMPACT_SCHEMA`,!0),jn=t(`SANDBOX_MAX_TIMEOUT_MS`,3e4);t(`NATIVE_BRIDGE_TIMEOUT_MS`,15e3),t(`SOURCEMAP_EXT_TIMEOUT_MS`,15e3);const Mn=t(`V8_BYTECODE_SUBPROC_TIMEOUT_MS`,6e4),Nn=t(`SYSCALL_TRACE_DURATION_DEFAULT_SEC`,10),Pn=t(`SYSCALL_TRACE_DURATION_MIN_SEC`,1),Fn=t(`SYSCALL_TRACE_DURATION_MAX_SEC`,300),In=t(`SOURCEMAP_V4_RAW_FIELD_MAX_LEN`,200),Ln=t(`SOURCEMAP_V4_RETRY_DELAY_MS`,250),Rn=t(`WASM_DEAD_CODE_MIN_MATCHES`,10),zn=t(`WASM_BITWISE_OPS_THRESHOLD`,20),Bn=t(`WASM_VM_DISPATCH_MIN_LOOPS`,3),Vn=t(`PROTO_TLS_MIN_RECORD_LEN`,4),Hn=n(`PROTO_TLS_CONFIDENCE`,.95),Un=n(`PROTO_WS_CONFIDENCE`,.85),Wn=n(`PROTO_HTTP_CONFIDENCE`,.95),Gn=n(`PROTO_SSH_CONFIDENCE`,.95),Kn=t(`BOT_DETECT_LIMIT_DEFAULT`,50);t(`BOT_DETECT_LIMIT_MIN`,1),t(`BOT_DETECT_LIMIT_MAX`,500);const qn=t(`WEBHOOK_PROCESS_TIMEOUT_MS`,1e4);t(`ORCHESTRATOR_STEP_TIMEOUT_MS`,1e4);const Jn=t(`MACRO_DEFAULT_TIMEOUT_MS`,12e4),Yn=t(`MACRO_BUILTIN_TIMEOUT_MS`,6e4),Xn=t(`PAGE_FRAME_SELECTOR_TIMEOUT_MS`,1e4),Zn=t(`PAGE_NETWORK_IDLE_TIMEOUT_MS`,3e4),Qn=t(`DOM_QUERY_DEFAULT_LIMIT`,50),$n=t(`DOM_WAIT_ELEMENT_TIMEOUT_MS`,3e4);t(`BROWSER_POOL_IDLE_TIMEOUT_MS`,3e5),t(`BROWSER_POOL_MAX_TABS`,10);const er=t(`ICMP_PROBE_TIMEOUT_MS`,5e3),tr=t(`ICMP_TRACEROUTE_MAX_HOPS`,30),nr=t(`ICMP_DEFAULT_PACKET_SIZE`,32);t(`ADB_VERSION_CHECK_TIMEOUT_MS`,5e3);const rr=t(`COORDINATION_GOTO_TIMEOUT_MS`,3e4),ir=t(`MEMORY_AUDIT_TRAIL_CAPACITY`,5e3),ar=t(`MEMORY_PROCESS_SIGNAL_TIMEOUT_MS`,2e3),or=t(`MEMORY_PROBE_CMD_TIMEOUT_MS`,5e3),sr=t(`MEMORY_VMMAP_ENUM_TIMEOUT_MS`,15e3),cr=t(`MEMORY_MODULES_TIMEOUT_MS`,3e4);export{f as $,Oe as $n,bt as $r,ce as $t,Yt as A,un as An,j as Ar,Ft as At,Qn as B,Ye as Bn,qt as Br,sr as Bt,W as C,w as Cn,Fn as Cr,_ as Ct,B as D,ln as Dn,P as Dr,It as Dt,z as E,on as En,N as Er,Dn as Et,u as F,ge as Fn,L as Fr,Ut as Ft,S as G,Xe as Gn,St as Gr,q as Gt,Vt as H,ve as Hn,wt as Hr,Pt as Ht,d as I,_e as In,I as Ir,Mt as It,x as J,Ge as Jn,X as Jr,Zn as Jt,dt as K,ye as Kn,Q as Kr,K as Kt,kt as L,Ae as Ln,Bn as Lr,Rt as Lt,he as M,sn as Mn,Mn as Mr,or as Mt,rr as N,xt as Nn,zn as Nr,ar as Nt,m as O,an as On,M as Or,Bt as Ot,k as P,Je as Pn,Rn as Pr,Wt as Pt,yn as Q,we as Qn,yt as Qr,hn as Qt,At as R,ke as Rn,A as Rr,zt as Rt,V as S,jn as Sn,Nn as Sr,g as St,H as T,E as Tn,Ot as Tr,ir as Tt,ct as U,Ke as Un,Tt as Ur,En as Ut,$n as V,qe as Vn,Jt as Vr,Ht as Vt,st as W,De as Wn,Ct as Wr,Gt as Wt,y as X,Te as Xn,J as Xr,pn as Xt,b as Y,Ue as Yn,Y as Yr,fn as Yt,nn as Z,Ce as Zn,rn as Zr,mn as Zt,Xt as _,Qe as _n,In as _r,O as _t,re as a,Wn as an,Se as ar,pt as at,Dt as b,c as bn,vn as br,An as bt,wn as c,Vn as cn,Ne as cr,$t as ct,vt as d,nt as dn,Ie as dr,On as dt,le as en,Ee as er,bn as et,$ as f,Ze as fn,Le as fr,nr as ft,Kn as g,$e as gn,s as gr,D as gt,ae as h,et as hn,ne as hr,p as ht,fe as i,lt as in,Ve as ir,mt as it,me as j,dn as jn,xn as jr,cr as jt,R as k,cn as kn,F as kr,Nt as kt,Tn as l,Un as ln,Pe as lr,tn as lt,oe as m,it as mn,Me as mr,tr as mt,de as n,ot as nn,He as nr,ht as nt,Sn as o,Gn as on,xe as or,Qt as ot,ie as p,at as pn,Fe as pr,er as pt,ut as q,We as qn,Z as qr,Xn as qt,ue as r,Kt as rn,Be as rr,ft as rt,Cn as s,Hn as sn,Re as sr,en as st,pe as t,se as tn,ze as tr,gt as tt,_t as u,rt as un,je as ur,kn as ut,Zt as v,tt as vn,Ln as vr,Yn as vt,U as w,T as wn,Pn as wr,h as wt,G as x,C as xn,_n as xr,v as xt,Et as y,l as yn,gn as yr,Jn as yt,jt as z,be as zn,qn as zr,Lt as zt};
@@ -1 +0,0 @@
1
- import{N as e}from"./constants-Cp6hBrrx.mjs";import"./definitions-jXPaVy4P.mjs";import{randomUUID as t}from"node:crypto";var n=class{handoffs=new Map;insights=[];ctx;constructor(e){this.ctx=e}async handleCreateTaskHandoff(e){let n=e.description,r=e.constraints,i=e.targetDomain,a=e.decision,o=e.risks,s=e.nextSteps,c;try{let e=this.ctx.pageController;if(e){let t=await e.getPage?.();t&&typeof t.url==`function`&&(c=t.url())}}catch{}let l={id:t().slice(0,8),status:`pending`,description:n,constraints:r,targetDomain:i,decision:a,risks:o,nextSteps:s,pageUrl:c,createdAt:Date.now()};return this.handoffs.set(l.id,l),{taskId:l.id,status:l.status,description:l.description,constraints:l.constraints,targetDomain:l.targetDomain,decision:l.decision,risks:l.risks,nextSteps:l.nextSteps,pageUrl:l.pageUrl,createdAt:new Date(l.createdAt).toISOString(),totalActiveHandoffs:this.handoffs.size}}async handleCompleteTaskHandoff(e){let t=e.taskId,n=e.summary,r=e.keyFindings,i=e.artifacts,a=this.handoffs.get(t);if(!a)throw Error(`Task handoff "${t}" not found. Active IDs: ${[...this.handoffs.keys()].join(`, `)||`(none)`}`);if(a.status===`completed`)throw Error(`Task handoff "${t}" is already completed`);return a.status=`completed`,a.completedAt=Date.now(),a.summary=n,a.keyFindings=r,a.artifacts=i,{taskId:a.id,status:`completed`,summary:a.summary,keyFindings:a.keyFindings,artifacts:a.artifacts,durationMs:a.completedAt-a.createdAt}}async handleGetTaskContext(e){let t=e.taskId;if(t){let e=this.handoffs.get(t);if(!e)throw Error(`Task handoff "${t}" not found`);return{handoff:this.serializeHandoff(e)}}let n=[...this.handoffs.values()].map(e=>this.serializeHandoff(e)),r=n.filter(e=>e.status!==`completed`),i=n.filter(e=>e.status===`completed`);return{active:r,completed:i,sessionInsights:this.insights.map(e=>({id:e.id,category:e.category,content:e.content,confidence:e.confidence,timestamp:new Date(e.timestamp).toISOString(),sourceTaskId:e.sourceTaskId})),summary:{totalActive:r.length,totalCompleted:i.length,totalInsights:this.insights.length}}}async handleAppendSessionInsight(e){let n=e.category,r=e.content,i=e.confidence??1,a=[...this.handoffs.values()].find(e=>e.status===`in_progress`||e.status===`pending`),o={id:t().slice(0,8),category:n,content:r,confidence:i,timestamp:Date.now(),sourceTaskId:a?.id};return this.insights.push(o),{insightId:o.id,category:o.category,totalInsights:this.insights.length,totalByCategory:this.getInsightCountByCategory()}}serializeHandoff(e){return{taskId:e.id,status:e.status,description:e.description,constraints:e.constraints,targetDomain:e.targetDomain,decision:e.decision,risks:e.risks,nextSteps:e.nextSteps,pageUrl:e.pageUrl,createdAt:new Date(e.createdAt).toISOString(),completedAt:e.completedAt?new Date(e.completedAt).toISOString():void 0,summary:e.summary,keyFindings:e.keyFindings,artifacts:e.artifacts}}getInsightCountByCategory(){let e={};for(let t of this.insights)e[t.category]=(e[t.category]??0)+1;return e}snapshots=new Map;async handleSavePageSnapshot(e){let n=e.label,r=this.ctx.pageController;if(!r)throw Error(`No page controller available`);let i=await r.getPage();if(!i)throw Error(`No active page to snapshot`);let a=i.url(),o=[];try{let e=await i.createCDPSession();o=(await e.send(`Network.getAllCookies`)).cookies.map(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path})),await e.detach()}catch{}let s={},c={};try{s=await i.evaluate(()=>{let e={};for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n&&(e[n]=window.localStorage.getItem(n)??``)}return e}),c=await i.evaluate(()=>{let e={};for(let t=0;t<window.sessionStorage.length;t++){let n=window.sessionStorage.key(t);n&&(e[n]=window.sessionStorage.getItem(n)??``)}return e})}catch{}let l={id:t().slice(0,8),url:a,cookies:o,localStorage:s,sessionStorage:c,timestamp:Date.now(),label:n};return this.snapshots.set(l.id,l),{snapshotId:l.id,url:l.url,cookieCount:l.cookies.length,localStorageKeys:Object.keys(l.localStorage).length,sessionStorageKeys:Object.keys(l.sessionStorage).length,label:l.label}}async handleRestorePageSnapshot(t){let n=t.snapshotId;if(!n)throw Error(`snapshotId is required`);let r=this.snapshots.get(n);if(!r)throw Error(`Snapshot "${n}" not found`);let i=this.ctx.pageController;if(!i)throw Error(`No page controller available`);let a=await i.getPage();if(!a)throw Error(`No active page for restoration`);if(await a.goto(r.url,{waitUntil:`domcontentloaded`,timeout:e}),r.cookies.length>0)try{let e=await a.createCDPSession();await e.send(`Network.setCookies`,{cookies:r.cookies.map(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path}))}),await e.detach()}catch{}try{await a.evaluate((e,t)=>{window.localStorage.clear();for(let[t,n]of Object.entries(e))window.localStorage.setItem(t,n);window.sessionStorage.clear();for(let[e,n]of Object.entries(t))window.sessionStorage.setItem(e,n)},r.localStorage,r.sessionStorage)}catch{}return{restored:!0,snapshotId:r.id,url:r.url,cookiesRestored:r.cookies.length,localStorageKeysRestored:Object.keys(r.localStorage).length,sessionStorageKeysRestored:Object.keys(r.sessionStorage).length}}async handleListPageSnapshots(){let e=[...this.snapshots.values()].map(e=>({id:e.id,url:e.url,label:e.label,cookieCount:e.cookies.length,localStorageKeys:Object.keys(e.localStorage).length,sessionStorageKeys:Object.keys(e.sessionStorage).length,createdAt:new Date(e.timestamp).toISOString()}));return{snapshots:e,total:e.length}}};export{n as CoordinationHandlers};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{t}from"./ToolError-DWU_z7gp.mjs";import{a as n,i as r,r as i,t as a}from"./parse-args-Cuk7-xUt.mjs";import"./definitions-LaYTuwQd.mjs";var o=class{deps;constructor(e){this.deps=e}async handleDebuggerLifecycle(e){return e.action===`enable`?(await this.deps.debuggerManager.init(),await this.deps.runtimeInspector.init(),await this.deps.debuggerManager.initAdvancedFeatures(this.deps.runtimeInspector),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Debugger enabled`,enabled:this.deps.debuggerManager.isEnabled()},null,2)}]}):(await this.deps.debuggerManager.disable(),await this.deps.runtimeInspector.disable(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Debugger disabled`},null,2)}]})}async handleDebuggerPause(e){await this.deps.debuggerManager.pause();try{let e=await this.deps.debuggerManager.waitForPaused(500);return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!0,message:`Execution paused`,reason:e.reason,location:e.callFrames[0]?.location},null,2)}]}}catch{return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!1,message:`Pause requested; no paused event observed yet`},null,2)}]}}}async handleDebuggerResume(e){let t=this.deps.debuggerManager.getPausedState()!==null;return await this.deps.debuggerManager.resume(),{content:[{type:`text`,text:JSON.stringify({success:!0,resumed:t,message:t?`Execution resumed`:`Resume requested; debugger was not paused`},null,2)}]}}},s=class{deps;constructor(e){this.deps=e}async handleDebuggerStepInto(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step while not paused`,hint:`The debugger must be paused at a breakpoint to perform step operations. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepInto(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped into`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step into failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}async handleDebuggerStepOver(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step while not paused`,hint:`The debugger must be paused at a breakpoint to perform step operations. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepOver(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped over`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step over failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}async handleDebuggerStepOut(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step out while not paused`,hint:`The debugger must be paused at a breakpoint to perform step out. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepOut(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped out`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step out failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}},c=class{deps;constructor(e){this.deps=e}async handleDebuggerEvaluate(e){let t=n(e,`expression`,``),r=n(e,`callFrameId`),i=await this.deps.runtimeInspector.evaluate(t,r);return{content:[{type:`text`,text:JSON.stringify({success:!0,expression:t,result:i},null,2)}]}}async handleDebuggerEvaluateGlobal(e){let t=n(e,`expression`,``),r=await this.deps.runtimeInspector.evaluateGlobal(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,expression:t,result:r},null,2)}]}}},l=class{deps;constructor(e){this.deps=e}async handleDebuggerWaitForPaused(e){let n=i(e,`timeout`,3e4);try{let e=await this.deps.debuggerManager.waitForPaused(n);return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!0,reason:e.reason,location:e.callFrames[0]?.location,hitBreakpoints:e.hitBreakpoints},null,2)}]}}catch(e){if(e instanceof t)throw e;return{content:[{type:`text`,text:JSON.stringify({success:!1,paused:!1,message:e instanceof Error?e.message:`Timeout waiting for paused event`},null,2)}]}}}async handleDebuggerGetPausedState(e){let t=this.deps.debuggerManager.getPausedState();return t?{content:[{type:`text`,text:JSON.stringify({paused:!0,reason:t.reason,frameCount:t.callFrames.length,topFrame:{functionName:t.callFrames[0]?.functionName,location:t.callFrames[0]?.location},hitBreakpoints:t.hitBreakpoints,timestamp:t.timestamp},null,2)}]}:{content:[{type:`text`,text:JSON.stringify({paused:!1,message:`Debugger is not paused`},null,2)}]}}async handleGetCallStack(e){let t=await this.deps.runtimeInspector.getCallStack();return t?{content:[{type:`text`,text:JSON.stringify({success:!0,callStack:{frameCount:t.callFrames.length,reason:t.reason,frames:t.callFrames.map((e,t)=>({index:t,callFrameId:e.callFrameId,functionName:e.functionName,location:`${e.location.url}:${e.location.lineNumber}:${e.location.columnNumber}`,scopeCount:e.scopeChain.length}))}},null,2)}]}:{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Not in paused state. Set a breakpoint and trigger it first.`},null,2)}]}}};function u(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var d=class{deps;constructor(e){this.deps=e}async handleSaveSession(e){let t=n(e,`filePath`),i=r(e,`metadata`);try{let e=await this.deps.debuggerManager.saveSession(t,i);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session saved successfully`,filePath:e,breakpointCount:this.deps.debuggerManager.listBreakpoints().length},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to save session`,error:u(e)},null,2)}]}}}async handleLoadSession(e){let t=n(e,`filePath`),r=n(e,`sessionData`);try{if(t)await this.deps.debuggerManager.loadSessionFromFile(t);else if(r)await this.deps.debuggerManager.importSession(r);else throw Error(`Either filePath or sessionData must be provided`);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session loaded successfully`,breakpointCount:this.deps.debuggerManager.listBreakpoints().length,pauseOnExceptions:this.deps.debuggerManager.getPauseOnExceptionsState()},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to load session`,error:u(e)},null,2)}]}}}async handleExportSession(e){let t=r(e,`metadata`);try{let e=this.deps.debuggerManager.exportSession(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session exported successfully`,session:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to export session`,error:u(e)},null,2)}]}}}async handleListSessions(e){try{let e=await this.deps.debuggerManager.listSavedSessions();return{content:[{type:`text`,text:JSON.stringify({success:!0,count:e.length,sessions:e.map(e=>({path:e.path,timestamp:e.timestamp,date:new Date(e.timestamp).toISOString(),metadata:e.metadata}))},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list sessions`,error:u(e)},null,2)}]}}}},f=class{deps;constructor(e){this.deps=e}async handleBreakpointSet(e){let t=n(e,`url`),r=n(e,`scriptId`),a=i(e,`lineNumber`,0),o=i(e,`columnNumber`),s=n(e,`condition`),c;if(t)c=await this.deps.debuggerManager.setBreakpointByUrl({url:t,lineNumber:a,columnNumber:o,condition:s});else if(r)c=await this.deps.debuggerManager.setBreakpoint({scriptId:r,lineNumber:a,columnNumber:o,condition:s});else throw Error(`Either url or scriptId must be provided`);return this.deps.eventBus?.emit(`debugger:breakpoint_hit`,{scriptId:c.location?.scriptId??r??``,lineNumber:c.location?.lineNumber??a,timestamp:new Date().toISOString()}),{content:[{type:`text`,text:JSON.stringify({success:!0,breakpoint:{breakpointId:c.breakpointId,location:c.location,condition:c.condition,enabled:c.enabled}},null,2)}]}}async handleBreakpointRemove(e){let t=n(e,`breakpointId`,``);return await this.deps.debuggerManager.removeBreakpoint(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Breakpoint ${t} removed`},null,2)}]}}async handleBreakpointList(e){let t=this.deps.debuggerManager.listBreakpoints();return{content:[{type:`text`,text:JSON.stringify({count:t.length,breakpoints:t.map(e=>({breakpointId:e.breakpointId,location:e.location,condition:e.condition,enabled:e.enabled,hitCount:e.hitCount}))},null,2)}]}}},p=class{deps;constructor(e){this.deps=e}async handleBreakpointSetOnException(e){let t=n(e,`state`,`none`);return await this.deps.debuggerManager.setPauseOnExceptions(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Pause on exceptions set to: ${t}`,state:t},null,2)}]}}};function m(e){return typeof e.ensureAdvancedFeatures==`function`}function h(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var g=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){m(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async handleXHRBreakpointSet(e){try{let t=n(e,`urlPattern`,``);await this.ensureAdvancedFeaturesIfSupported();let r=await this.deps.debuggerManager.getXHRManager().setXHRBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`XHR breakpoint set`,breakpointId:r,urlPattern:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set XHR breakpoint`,error:h(e)},null,2)}]}}}async handleXHRBreakpointRemove(e){try{let t=n(e,`breakpointId`,``);await this.ensureAdvancedFeaturesIfSupported();let r=await this.deps.debuggerManager.getXHRManager().removeXHRBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:r,message:r?`XHR breakpoint removed`:`XHR breakpoint not found`,breakpointId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove XHR breakpoint`,error:h(e)},null,2)}]}}}async handleXHRBreakpointList(e){try{await this.ensureAdvancedFeaturesIfSupported();let e=this.deps.debuggerManager.getXHRManager().getAllXHRBreakpoints();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} XHR breakpoint(s)`,breakpoints:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list XHR breakpoints`,error:h(e)},null,2)}]}}}};function _(e){return typeof e.ensureAdvancedFeatures==`function`}function v(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var y=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){_(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async handleEventBreakpointSet(e){try{let t=n(e,`eventName`,``),r=n(e,`targetName`);await this.ensureAdvancedFeaturesIfSupported();let i=await this.deps.debuggerManager.getEventManager().setEventListenerBreakpoint(t,r);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Event breakpoint set`,breakpointId:i,eventName:t,targetName:r},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set event breakpoint`,error:v(e)},null,2)}]}}}async handleEventBreakpointSetCategory(e){try{let t=n(e,`category`,``);await this.ensureAdvancedFeaturesIfSupported();let r=this.deps.debuggerManager.getEventManager(),i;switch(t){case`mouse`:i=await r.setMouseEventBreakpoints();break;case`keyboard`:i=await r.setKeyboardEventBreakpoints();break;case`timer`:i=await r.setTimerEventBreakpoints();break;case`websocket`:i=await r.setWebSocketEventBreakpoints();break;default:throw Error(`Unknown category: ${t}`)}return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Set ${i.length} ${t} event breakpoint(s)`,category:t,breakpointIds:i},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set event breakpoints`,error:v(e)},null,2)}]}}}async handleEventBreakpointRemove(e){try{let t=n(e,`breakpointId`,``);await this.ensureAdvancedFeaturesIfSupported();let r=await this.deps.debuggerManager.getEventManager().removeEventListenerBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:r,message:r?`Event breakpoint removed`:`Event breakpoint not found`,breakpointId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove event breakpoint`,error:v(e)},null,2)}]}}}async handleEventBreakpointList(e){try{await this.ensureAdvancedFeaturesIfSupported();let e=this.deps.debuggerManager.getEventManager().getAllEventBreakpoints();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} event breakpoint(s)`,breakpoints:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list event breakpoints`,error:v(e)},null,2)}]}}}};function b(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var x=class{deps;constructor(e){this.deps=e}async handleWatchAdd(e){try{let t=n(e,`expression`,``),r=n(e,`name`),i=this.deps.debuggerManager.getWatchManager().addWatch(t,r);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Watch expression added`,watchId:i,expression:t,name:r||t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add watch expression`,error:b(e)},null,2)}]}}}async handleWatchRemove(e){try{let t=n(e,`watchId`,``),r=this.deps.debuggerManager.getWatchManager().removeWatch(t);return{content:[{type:`text`,text:JSON.stringify({success:r,message:r?`Watch expression removed`:`Watch expression not found`,watchId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove watch expression`,error:b(e)},null,2)}]}}}async handleWatchList(e){try{let e=this.deps.debuggerManager.getWatchManager().getAllWatches();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} watch expression(s)`,watches:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list watch expressions`,error:b(e)},null,2)}]}}}async handleWatchEvaluateAll(e){try{let t=n(e,`callFrameId`),r=await this.deps.debuggerManager.getWatchManager().evaluateAll(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Evaluated ${r.length} watch expression(s)`,results:r},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to evaluate watch expressions`,error:b(e)},null,2)}]}}}async handleWatchClearAll(e){try{return this.deps.debuggerManager.getWatchManager().clearAll(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`All watch expressions cleared`},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to clear watch expressions`,error:b(e)},null,2)}]}}}};const S=(e,t)=>{if(e instanceof Error)return e.message;if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`)return t}return t};var C=class{deps;constructor(e){this.deps=e}async handleGetScopeVariablesEnhanced(e){let t=n(e,`callFrameId`),r=a(e,`includeObjectProperties`),o=i(e,`maxDepth`),s=a(e,`skipErrors`,!0);try{let e=await this.deps.debuggerManager.getScopeVariables({callFrameId:t,includeObjectProperties:r,maxDepth:o,skipErrors:s});return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:S(e,`Failed to get scope variables`),error:String(e)},null,2)}]}}}async handleGetObjectProperties(e){let t=n(e,`objectId`,``);if(!t)return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`objectId parameter is required`},null,2)}]};try{let e=await this.deps.debuggerManager.getObjectPropertiesById(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,propertyCount:e.length,properties:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:S(e,`Failed to get object properties`),error:String(e)},null,2)}]}}}};function w(e){return typeof e.ensureAdvancedFeatures==`function`}function T(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var E=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){w(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async getBlackboxManager(){return await this.ensureAdvancedFeaturesIfSupported(),this.deps.debuggerManager.getBlackboxManager()}async handleBlackboxAdd(e){try{let t=n(e,`urlPattern`,``);return await(await this.getBlackboxManager()).blackboxByPattern(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Script pattern blackboxed`,urlPattern:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add blackbox pattern`,error:T(e)},null,2)}]}}}async handleBlackboxAddCommon(e){try{return await(await this.getBlackboxManager()).blackboxCommonLibraries(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Blackboxed common library patterns`},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add common blackbox patterns`,error:T(e)},null,2)}]}}}async handleBlackboxList(e){try{let e=(await this.getBlackboxManager()).getAllBlackboxedPatterns();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} blackboxed pattern(s)`,patterns:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list blackbox patterns`,error:T(e)},null,2)}]}}}},D=class{debuggerManager;runtimeInspector;debuggerControl;debuggerStepping;debuggerEvaluate;debuggerState;sessionManagement;breakpointBasic;breakpointException;xhrBreakpoint;eventBreakpoint;watchExpressions;scopeInspection;blackbox;constructor(e,t,n){this.debuggerManager=e,this.runtimeInspector=t;let r={debuggerManager:this.debuggerManager,runtimeInspector:this.runtimeInspector};this.debuggerControl=new o(r),this.debuggerStepping=new s({debuggerManager:this.debuggerManager}),this.debuggerEvaluate=new c({runtimeInspector:this.runtimeInspector}),this.debuggerState=new l(r),this.sessionManagement=new d({debuggerManager:this.debuggerManager}),this.breakpointBasic=new f({debuggerManager:this.debuggerManager,eventBus:n}),this.breakpointException=new p({debuggerManager:this.debuggerManager}),this.xhrBreakpoint=new g({debuggerManager:this.debuggerManager}),this.eventBreakpoint=new y({debuggerManager:this.debuggerManager}),this.watchExpressions=new x({debuggerManager:this.debuggerManager}),this.scopeInspection=new C(r),this.blackbox=new E({debuggerManager:this.debuggerManager})}async handleDebuggerLifecycle(e){return this.debuggerControl.handleDebuggerLifecycle(e)}async handleDebuggerPause(e){return this.debuggerControl.handleDebuggerPause(e)}async handleDebuggerResume(e){return this.debuggerControl.handleDebuggerResume(e)}async handleDebuggerStepInto(e){return this.debuggerStepping.handleDebuggerStepInto(e)}async handleDebuggerStepOver(e){return this.debuggerStepping.handleDebuggerStepOver(e)}async handleDebuggerStepOut(e){return this.debuggerStepping.handleDebuggerStepOut(e)}async handleDebuggerEvaluate(e){return this.debuggerEvaluate.handleDebuggerEvaluate(e)}async handleDebuggerEvaluateGlobal(e){return this.debuggerEvaluate.handleDebuggerEvaluateGlobal(e)}async handleDebuggerWaitForPaused(e){return this.debuggerState.handleDebuggerWaitForPaused(e)}async handleDebuggerGetPausedState(e){return this.debuggerState.handleDebuggerGetPausedState(e)}async handleGetCallStack(e){return this.debuggerState.handleGetCallStack(e)}async handleSaveSession(e){return this.sessionManagement.handleSaveSession(e)}async handleLoadSession(e){return this.sessionManagement.handleLoadSession(e)}async handleExportSession(e){return this.sessionManagement.handleExportSession(e)}async handleListSessions(e){return this.sessionManagement.handleListSessions(e)}async handleBreakpointSet(e){return this.breakpointBasic.handleBreakpointSet(e)}async handleBreakpointRemove(e){return this.breakpointBasic.handleBreakpointRemove(e)}async handleBreakpointList(e){return this.breakpointBasic.handleBreakpointList(e)}async handleBreakpointSetOnException(e){return this.breakpointException.handleBreakpointSetOnException(e)}async handleXHRBreakpointSet(e){return this.xhrBreakpoint.handleXHRBreakpointSet(e)}async handleXHRBreakpointRemove(e){return this.xhrBreakpoint.handleXHRBreakpointRemove(e)}async handleXHRBreakpointList(e){return this.xhrBreakpoint.handleXHRBreakpointList(e)}async handleEventBreakpointSet(e){return this.eventBreakpoint.handleEventBreakpointSet(e)}async handleEventBreakpointSetCategory(e){return this.eventBreakpoint.handleEventBreakpointSetCategory(e)}async handleEventBreakpointRemove(e){return this.eventBreakpoint.handleEventBreakpointRemove(e)}async handleEventBreakpointList(e){return this.eventBreakpoint.handleEventBreakpointList(e)}async handleWatchAdd(e){return this.watchExpressions.handleWatchAdd(e)}async handleWatchRemove(e){return this.watchExpressions.handleWatchRemove(e)}async handleWatchList(e){return this.watchExpressions.handleWatchList(e)}async handleWatchEvaluateAll(e){return this.watchExpressions.handleWatchEvaluateAll(e)}async handleWatchClearAll(e){return this.watchExpressions.handleWatchClearAll(e)}async handleGetScopeVariablesEnhanced(e){return this.scopeInspection.handleGetScopeVariablesEnhanced(e)}async handleGetObjectProperties(e){return this.scopeInspection.handleGetObjectProperties(e)}async handleBlackboxAdd(e){return this.blackbox.handleBlackboxAdd(e)}async handleBlackboxAddCommon(e){return this.blackbox.handleBlackboxAddCommon(e)}async handleBlackboxList(e){return this.blackbox.handleBlackboxList(e)}async handleBreakpoint(e){let t=String(e.action??``),n=String(e.type??`code`);switch(n){case`code`:switch(t){case`set`:return this.breakpointBasic.handleBreakpointSet(e);case`remove`:return this.breakpointBasic.handleBreakpointRemove(e);case`list`:return this.breakpointBasic.handleBreakpointList(e)}break;case`xhr`:switch(t){case`set`:return this.xhrBreakpoint.handleXHRBreakpointSet(e);case`remove`:return this.xhrBreakpoint.handleXHRBreakpointRemove(e);case`list`:return this.xhrBreakpoint.handleXHRBreakpointList(e)}break;case`event`:switch(t){case`set`:return this.eventBreakpoint.handleEventBreakpointSet(e);case`remove`:return this.eventBreakpoint.handleEventBreakpointRemove(e);case`list`:return this.eventBreakpoint.handleEventBreakpointList(e)}break;case`event_category`:if(t===`set`)return this.eventBreakpoint.handleEventBreakpointSetCategory(e);break;case`exception`:if(t===`set`)return this.breakpointException.handleBreakpointSetOnException(e);break}return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Invalid breakpoint action/type: ${t}/${n}. Valid types: code, xhr, event, event_category, exception. Valid actions: set, remove, list.`})}]}}async handleWatch(e){let t=String(e.action??``);switch(t){case`add`:return this.watchExpressions.handleWatchAdd(e);case`remove`:return this.watchExpressions.handleWatchRemove(e);case`list`:return this.watchExpressions.handleWatchList(e);case`evaluate_all`:return this.watchExpressions.handleWatchEvaluateAll(e);case`clear_all`:return this.watchExpressions.handleWatchClearAll(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown watch action: ${t}. Valid: add, remove, list, evaluate_all, clear_all`})}]}}}async handleDebuggerStep(e){let t=String(e.direction??`over`);switch(t){case`into`:return this.debuggerStepping.handleDebuggerStepInto(e);case`over`:return this.debuggerStepping.handleDebuggerStepOver(e);case`out`:return this.debuggerStepping.handleDebuggerStepOut(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown direction: ${t}. Valid: into, over, out`})}]}}}async handleDebuggerEvaluateDispatch(e){return String(e.context??`frame`)===`global`?this.debuggerEvaluate.handleDebuggerEvaluateGlobal(e):this.debuggerEvaluate.handleDebuggerEvaluate(e)}async handleDebuggerSession(e){let t=String(e.action??``);switch(t){case`save`:return this.sessionManagement.handleSaveSession(e);case`load`:return this.sessionManagement.handleLoadSession(e);case`export`:return this.sessionManagement.handleExportSession(e);case`list`:return this.sessionManagement.handleListSessions(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown action: ${t}. Valid actions: save, load, export, list`})}]}}}};export{D as DebuggerToolHandlers};
@@ -1 +0,0 @@
1
- import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`state_board`,e=>e.desc(`CRUD operations on the cross-tool shared state board.`).enum(`action`,[`set`,`get`,`delete`,`list`,`history`,`clear`],`Operation to perform`).string(`key`,`Key name (required for set/get/delete/history)`).prop(`value`,{type:`object`,description:`Value to store`}).string(`namespace`,`Namespace for key isolation`).number(`ttlSeconds`,`TTL in seconds`).boolean(`includeValues`,`Include current values in list results`,{default:!1}).number(`limit`,`Maximum history entries to return`,{default:50}).string(`keyPattern`,`Key pattern filter`).required(`action`)),e(`state_board_watch`,e=>e.desc(`Watch state board keys for changes with configurable polling.`).enum(`action`,[`start`,`poll`,`stop`],`Watch operation: start watching, poll for changes, or stop watching`).string(`key`,`Key or pattern to watch`).string(`namespace`,`Namespace`).number(`pollIntervalMs`,`Polling interval in milliseconds`).string(`watchId`,`Watch ID`).required(`action`)),e(`state_board_io`,e=>e.desc(`Serialize state board to JSON or restore from a previous export.`).enum(`action`,[`export`,`import`],`IO operation`).string(`namespace`,`Namespace filter or target namespace`).string(`keyPattern`,`Key pattern filter`).prop(`data`,{type:`object`,description:`Entries to import`}).boolean(`overwrite`,`Overwrite existing keys on import`).required(`action`))];export{t};
@@ -1 +0,0 @@
1
- import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`get_token_budget_stats`,e=>e.desc(`Get token budget usage stats, warnings, and optimization suggestions.`).query()),e(`manual_token_cleanup`,e=>e.desc(`Clear stale entries and reset counters to free 10-30% of token budget.`)),e(`reset_token_budget`,e=>e.desc(`Hard-reset all token budget counters. Destructive — prefer manual_token_cleanup.`).destructive())],n=[e(`list_extensions`,e=>e.desc(`List all loaded plugins, workflows, and extension tools.`).query()),e(`reload_extensions`,e=>e.desc(`Reload plugins and workflows from configured directories.`).openWorld()),e(`browse_extension_registry`,e=>e.desc(`Browse the online extension registry for installable plugins and workflows.`).enum(`kind`,[`plugin`,`workflow`,`all`],`Filter by extension kind`,{default:`all`}).query()),e(`install_extension`,e=>e.desc(`Install an extension from the remote registry.`).string(`slug`,`Extension slug from the registry`).string(`targetDir`,`Target directory override`).requiredOpenWorld(`slug`))],r=[e(`get_cache_stats`,e=>e.desc(`Get cache statistics: entries, sizes, hit rates, and cleanup recommendations.`).query()),e(`smart_cache_cleanup`,e=>e.desc(`Evict LRU and stale entries while preserving hot data.`).number(`targetSize`,`Target size in bytes`)),e(`clear_all_caches`,e=>e.desc(`Clear all internal caches. Destructive — prefer smart_cache_cleanup.`).destructive())],i=[e(`cleanup_artifacts`,e=>e.desc(`Clean generated artifacts by age and size.`).number(`retentionDays`,`Override retention window in days`).number(`maxTotalBytes`,`Override maximum retained bytes`).boolean(`dryRun`,`Preview removals without deleting`).destructive()),e(`doctor_environment`,e=>e.desc(`Run environment doctor: dependencies, bridges, platform limits.`).boolean(`includeBridgeHealth`,`Probe native-bridge / Burp endpoints`).readOnly())];export{t as i,r as n,n as r,i as t};
@@ -1 +0,0 @@
1
- import{c as e}from"./PageController-D9jVkH0i.mjs";import{t}from"./tool-builder-CI9914Tf.mjs";const n=[t(`js_heap_search`,e=>e.desc(`Search JS heap for strings matching a pattern.`).string(`pattern`,`Pattern to search`).number(`maxResults`,`Max matches`,{default:50}).boolean(`caseSensitive`,`Case sensitive`,{default:!1}).required(`pattern`).query()),t(`tab_workflow`,e=>e.desc(`Cross-tab coordination.`).enum(`action`,[`list`,`alias_bind`,`alias_open`,`navigate`,`wait_for`,`context_set`,`context_get`,`transfer`,`clear`],`Action`).string(`alias`,`Tab alias`).string(`fromAlias`,`Source tab alias`).number(`index`,`Tab index (0-based)`).string(`url`,`URL`).string(`selector`,`CSS selector to wait for`).string(`waitForText`,`Text to wait for`).string(`key`,`Context key`).string(`value`,`Context value`).string(`expression`,`JS expression for transfer`).number(`timeoutMs`,`Timeout ms`,{default:1e4}).requiredOpenWorld(`action`))],r=[t(`page_navigate`,t=>t.desc(`Navigate the page to a URL with wait and network options.`).string(`url`,`Target URL`).enum(`waitUntil`,e,`When to consider navigation succeeded`,{default:`networkidle`}).number(`timeout`,`Navigation timeout in ms`,{default:3e4,minimum:1e3,maximum:12e4}).boolean(`enableNetworkMonitoring`,`Enable network monitoring before navigation`,{default:!1}).required(`url`).idempotent().openWorld()),t(`page_reload`,e=>e.desc(`Reload the page with optional cache bypass.`).idempotent().openWorld()),t(`page_back`,e=>e.desc(`Navigate back in browser history.`).openWorld()),t(`page_forward`,e=>e.desc(`Navigate forward in browser history.`).openWorld()),t(`page_list_frames`,e=>e.desc(`List page frames for frame targeting.`).query()),t(`page_click`,e=>e.desc(`Click a page element by CSS selector.`).string(`selector`,`CSS selector`).enum(`button`,[`left`,`right`,`middle`],`Mouse button`,{default:`left`}).number(`clickCount`,`Number of clicks`,{default:1,minimum:1,maximum:10}).number(`delay`,`Delay between mousedown and mouseup in ms`,{minimum:0,maximum:1e4}).number(`timeout`,`Click timeout in ms`,{default:1e4,minimum:1e3,maximum:12e4}).string(`frameUrl`,`iframe URL substring`).string(`frameSelector`,`iframe CSS selector`).requiredOpenWorld(`selector`)),t(`page_type`,e=>e.desc(`Type text into an element.`).string(`selector`,`CSS selector`).string(`text`,`Text to type`).number(`delay`,`Delay between key presses in ms`,{minimum:0,maximum:1e3}).string(`frameUrl`,`iframe URL substring`).string(`frameSelector`,`iframe CSS selector`).requiredOpenWorld(`selector`,`text`)),t(`page_upload_files`,e=>e.desc(`Upload one or more local files into an <input type="file"> element.`).string(`selector`,`CSS selector for the file input`).array(`paths`,{type:`string`},`Project-relative file paths to upload`).string(`frameUrl`,`iframe URL substring`).string(`frameSelector`,`iframe CSS selector`).required(`selector`,`paths`).openWorld()),t(`page_select`,e=>e.desc(`Select option(s) in a <select> element.`).string(`selector`,`CSS selector`).array(`values`,{type:`string`},`Values to select`).string(`frameUrl`,`iframe URL substring`).string(`frameSelector`,`iframe CSS selector`).required(`selector`,`values`).idempotent().openWorld()),t(`page_hover`,e=>e.desc(`Hover over an element by CSS selector.`).string(`selector`,`CSS selector`).string(`frameUrl`,`iframe URL substring`).string(`frameSelector`,`iframe CSS selector`).required(`selector`).idempotent().openWorld()),t(`page_scroll`,e=>e.desc(`Scroll to absolute or relative coordinates.`).number(`x`,`Horizontal position`,{default:0}).number(`y`,`Vertical position`,{default:0}).idempotent()),t(`page_wait_for_selector`,e=>e.desc(`Wait for an element to appear.`).string(`selector`,`CSS selector`).number(`timeout`,`Timeout in ms`,{default:3e4,minimum:1e3,maximum:12e4}).required(`selector`).query()),t(`page_evaluate`,e=>e.desc(`Execute JavaScript in page context.`).string(`code`,`JavaScript code`).string(`script`,`Alias of code`).string(`expression`,`Alias of code`).boolean(`autoSummarize`,`Auto-summarize large results`,{default:!0}).number(`maxSize`,`Max result size in bytes before summarizing`,{default:51200,minimum:1024,maximum:10485760}).array(`fieldFilter`,{type:`string`},`Field names to strip from result (recursive)`).boolean(`stripBase64`,`Strip base64 strings from result`,{default:!1}).string(`frameUrl`,`iframe URL substring`).string(`frameSelector`,`iframe CSS selector`).openWorld()),t(`page_screenshot`,e=>e.desc(`Capture a page or element screenshot.`).prop(`selector`,{oneOf:[{type:`string`,description:`CSS selector`},{type:`array`,items:{type:`string`},description:`Multiple CSS selectors`}],description:`Element selector(s). Omit for full page viewport.`}).object(`clip`,{x:{type:`number`,description:`Left offset`},y:{type:`number`,description:`Top offset`},width:{type:`number`,description:`Width`},height:{type:`number`,description:`Height`}},`Pixel region to capture`,{required:[`x`,`y`,`width`,`height`]}).string(`path`,`File path to save screenshot`).enum(`type`,[`png`,`jpeg`],`Image format`,{default:`png`}).number(`quality`,`Image quality 0-100 (jpeg only)`,{minimum:1,maximum:100}).boolean(`fullPage`,`Capture full scrollable page`,{default:!1}).query()),t(`get_all_scripts`,e=>e.desc(`List all scripts loaded by the page with optional source.`).boolean(`includeSource`,`Include source code`,{default:!1}).query()),t(`get_script_source`,e=>e.desc(`Retrieve source code of a script by ID or URL pattern.`).string(`scriptId`,`Script ID`).string(`url`,`Script URL (supports wildcards)`).boolean(`preview`,`Preview only (first N lines + metadata)`,{default:!1}).number(`maxLines`,`Max lines in preview`,{default:100,minimum:1,maximum:1e4}).number(`startLine`,`Start line (1-based)`,{minimum:1}).number(`endLine`,`End line (1-based)`,{minimum:1}).query())],i=[t(`console_monitor`,e=>e.desc(`Toggle console log capture (log, warn, error, info, debug).`).enum(`action`,[`enable`,`disable`],`Action`).required(`action`).idempotent()),t(`console_get_logs`,e=>e.desc(`Retrieve captured console logs with type and time filters.`).enum(`type`,[`log`,`warn`,`error`,`info`,`debug`],`Log type filter`).number(`limit`,`Max logs`).number(`since`,`Timestamp filter`).query()),t(`console_execute`,e=>e.desc(`Evaluate a JS expression in the browser console context.`).string(`expression`,`JavaScript expression`).number(`maxSize`,`Max result size in bytes before offloading (default 50KB → detailId ref)`,{default:51200,minimum:1024,maximum:104857600}).boolean(`stripBase64`,`Strip base64 strings from result`,{default:!1}).requiredOpenWorld(`expression`)),t(`page_inject_script`,e=>e.desc(`Inject JavaScript to run on every page load.`).string(`script`,`JavaScript code`).requiredOpenWorld(`script`)),t(`page_cookies`,e=>e.desc(`Manage page cookies; clear requires matching expectedCount.`).enum(`action`,[`get`,`set`,`clear`],`Action`).number(`expectedCount`,`Required for clear: must match current count`).array(`cookies`,{type:`object`,properties:{name:{type:`string`},value:{type:`string`},domain:{type:`string`},path:{type:`string`},expires:{type:`number`},httpOnly:{type:`boolean`},secure:{type:`boolean`},sameSite:{type:`string`,enum:[`Strict`,`Lax`,`None`]}},required:[`name`,`value`]},`Cookies (action=set)`).destructive().required(`action`)),t(`page_set_viewport`,e=>e.desc(`Set the browser viewport dimensions.`).number(`width`,`Width`).number(`height`,`Height`).required(`width`,`height`).idempotent()),t(`page_emulate_device`,e=>e.desc(`Emulate a mobile device profile.`).string(`device`,`Device name`).required(`device`).idempotent()),t(`page_local_storage`,e=>e.desc(`Read or write localStorage entries for the current origin.`).enum(`action`,[`get`,`set`],`Action`).string(`key`,`Key`).string(`value`,`Value`).required(`action`)),t(`page_press_key`,e=>e.desc(`Simulate a key press by name.`).string(`key`,`Key name`).requiredOpenWorld(`key`))],a=[t(`get_detailed_data`,e=>e.desc(`Retrieve large data by detailId.`).string(`detailId`,`Detail ID from previous response`).string(`path`,`Path to specific nested data`).required(`detailId`).query()),t(`browser_launch`,e=>e.desc(`Launch Chromium/Camoufox or connect to a running browser.`).enum(`driver`,[`chrome`,`camoufox`],`Browser driver`,{default:`chrome`}).boolean(`headless`,`Run headless`,{default:!1}).enum(`os`,[`windows`,`macos`,`linux`],`OS fingerprint (camoufox)`,{default:`windows`}).enum(`mode`,[`launch`,`connect`],`Launch or connect`,{default:`launch`}).string(`browserURL`,`Browser debug endpoint URL`).string(`wsEndpoint`,`WebSocket endpoint`).boolean(`autoConnect`,`Auto-detect local Chrome debug WebSocket`,{default:!1}).enum(`channel`,[`stable`,`beta`,`dev`,`canary`],`Chrome channel`,{default:`stable`}).string(`userDataDir`,`Chrome profile directory`).array(`args`,{type:`string`},`Extra Chrome launch args`).boolean(`enableV8NativesSyntax`,`Enable V8 native syntax for launched Chrome`,{default:!0}).boolean(`geoip`,`Auto-resolve GeoIP (camoufox)`,{default:!1}).boolean(`humanize`,`Humanize cursor (camoufox)`,{default:!1}).string(`proxy`,`Proxy URL (camoufox)`).boolean(`blockImages`,`Block images (camoufox)`,{default:!1}).boolean(`blockWebrtc`,`Block WebRTC (camoufox)`,{default:!1}).boolean(`blockWebgl`,`Block WebGL (camoufox)`,{default:!1}).string(`locale`,`Firefox locale (camoufox)`).array(`addons`,{type:`string`},`Firefox addons (camoufox)`).array(`fonts`,{type:`string`},`Custom fonts (camoufox)`).array(`excludeAddons`,{type:`string`},`Addons to exclude (camoufox)`).boolean(`customFontsOnly`,`Only use custom fonts (camoufox)`,{default:!1}).object(`screen`,{width:{type:`number`},height:{type:`number`}},`Screen resolution (camoufox)`).object(`window`,{width:{type:`number`},height:{type:`number`}},`Window size (camoufox)`).prop(`fingerprint`,{type:`object`,description:`Pre-generated fingerprint (camoufox)`,additionalProperties:!0}).prop(`webglConfig`,{type:`object`,description:`WebGL config (camoufox)`,additionalProperties:!0}).prop(`firefoxUserPrefs`,{type:`object`,description:`Firefox about:config overrides (camoufox)`,additionalProperties:!0}).boolean(`mainWorldEval`,`Main world eval (camoufox)`,{default:!0}).openWorld()),t(`camoufox_server`,e=>e.desc(`Start, close, or check status of a Camoufox anti-detect server.`).enum(`action`,[`launch`,`close`,`status`],`Action`).number(`port`,`Listen port (launch)`).string(`ws_path`,`WebSocket path (launch)`).enum(`os`,[`windows`,`macos`,`linux`],`OS fingerprint (launch)`,{default:`windows`}).boolean(`headless`,`Headless (launch)`,{default:!0}).boolean(`geoip`,`GeoIP (launch)`,{default:!1}).boolean(`humanize`,`Humanize cursor (launch)`,{default:!1}).string(`proxy`,`Proxy URL (launch)`).boolean(`blockImages`,`Block images (launch)`,{default:!1}).boolean(`blockWebrtc`,`Block WebRTC (launch)`,{default:!1}).boolean(`blockWebgl`,`Block WebGL (launch)`,{default:!1}).string(`locale`,`Firefox locale (launch)`).array(`addons`,{type:`string`},`Addons (launch)`).array(`fonts`,{type:`string`},`Fonts (launch)`).array(`excludeAddons`,{type:`string`},`Excluded addons (launch)`).boolean(`customFontsOnly`,`Only custom fonts (launch)`,{default:!1}).object(`screen`,{width:{type:`number`},height:{type:`number`}},`Screen resolution (launch)`).object(`window`,{width:{type:`number`},height:{type:`number`}},`Window size (launch)`).prop(`fingerprint`,{type:`object`,description:`Pre-generated fingerprint (launch)`,additionalProperties:!0}).prop(`webglConfig`,{type:`object`,description:`WebGL config (launch)`,additionalProperties:!0}).prop(`firefoxUserPrefs`,{type:`object`,description:`Firefox about:config overrides (launch)`,additionalProperties:!0}).boolean(`mainWorldEval`,`Main world eval (launch)`,{default:!0}).boolean(`enableCache`,`Enable cache (launch)`,{default:!1}).required(`action`).destructive()),t(`browser_attach`,e=>e.desc(`Connect to a running browser.`).string(`browserURL`,`Debug endpoint URL`).string(`wsEndpoint`,`WebSocket URL`).boolean(`autoConnect`,`Auto-detect local Chrome debug WebSocket`,{default:!1}).enum(`channel`,[`stable`,`beta`,`dev`,`canary`],`Chrome channel`,{default:`stable`}).string(`userDataDir`,`Chrome profile directory`).number(`pageIndex`,`Tab index to activate`,{default:0}).openWorld()),t(`browser_list_cdp_targets`,e=>e.desc(`List CDP targets with optional type/URL/title filters.`).string(`browserURL`,`Browser URL`).string(`wsEndpoint`,`WebSocket endpoint`).boolean(`autoConnect`,`Auto-detect local Chrome debug WebSocket`,{default:!1}).enum(`channel`,[`stable`,`beta`,`dev`,`canary`],`Chrome channel`,{default:`stable`}).string(`userDataDir`,`Chrome profile directory`).string(`type`,`Target type filter`).array(`types`,{type:`string`},`Target types to include`).string(`targetId`,`Exact targetId filter`).string(`urlPattern`,`URL substring filter`).string(`titlePattern`,`Title substring filter`).boolean(`attachedOnly`,`Only attached targets`,{default:!1}).boolean(`discoverOOPIF`,`Auto-discover cross-origin iframes`,{default:!0}).query().openWorld()),t(`browser_attach_cdp_target`,e=>e.desc(`Attach to a CDP target by targetId.`).string(`targetId`,`Target ID`).required(`targetId`)),t(`browser_detach_cdp_target`,e=>e.desc(`Detach the current CDP target session.`).destructive()),t(`browser_evaluate_cdp_target`,e=>e.desc(`Evaluate JS in the attached CDP target.`).string(`code`,`JavaScript code`).string(`script`,`Alias of code`).string(`expression`,`Alias of code`).boolean(`returnByValue`,`Return by value`,{default:!0}).boolean(`awaitPromise`,`Await promises`,{default:!0}).boolean(`autoSummarize`,`Summarize large results`,{default:!0}).number(`maxSize`,`Max size before summarizing`,{default:51200}).array(`fieldFilter`,{type:`string`},`Field names to strip`).boolean(`stripBase64`,`Strip base64 payloads`,{default:!1}).openWorld()),t(`browser_close`,e=>e.desc(`Close the browser and release all resources.`).destructive()),t(`browser_status`,e=>e.desc(`Report browser status: running, tab count, version.`).query())],o=[t(`captcha_detect`,e=>e.desc(`Detect CAPTCHAs on the current page.`).query()),t(`captcha_wait`,e=>e.desc(`Block until the user manually solves the CAPTCHA.`).number(`timeout`,`Timeout in ms`,{default:3e5}).query().openWorld()),t(`captcha_config`,e=>e.desc(`Configure CAPTCHA detection sensitivity and solver backend.`).boolean(`autoDetectCaptcha`,`Auto-detect after navigation`).boolean(`autoSwitchHeadless`,`Switch to headed on detection`).number(`captchaTimeout`,`Wait timeout in ms`).idempotent()),t(`stealth_inject`,e=>e.desc(`Inject anti-detection scripts to reduce bot fingerprint exposure.`).idempotent()),t(`stealth_set_user_agent`,e=>e.desc(`Set User-Agent and fingerprint.`).enum(`platform`,[`windows`,`mac`,`linux`],`Platform`,{default:`windows`}).idempotent()),t(`stealth_configure_jitter`,e=>e.desc(`Configure CDP timing jitter.`).boolean(`enabled`,`Enable`,{default:!0}).number(`minDelayMs`,`Min delay ms`,{default:20}).number(`maxDelayMs`,`Max delay ms`,{default:80}).boolean(`burstMode`,`Skip jitter for time-critical ops`,{default:!1}).idempotent()),t(`stealth_generate_fingerprint`,e=>e.desc(`Generate a browser fingerprint.`).enum(`os`,[`windows`,`macos`,`linux`],`Target OS`).enum(`browser`,[`chrome`,`firefox`],`Target browser`,{default:`chrome`}).string(`locale`,`Locale`,{default:`en-US`})),t(`stealth_verify`,e=>e.desc(`Run anti-detection checks.`).query()),t(`browser_list_tabs`,e=>e.desc(`List open browser tabs with URLs and titles.`).string(`browserURL`,`Browser URL`).string(`wsEndpoint`,`WebSocket endpoint`).boolean(`autoConnect`,`Auto-detect Chrome debug WebSocket`,{default:!1}).enum(`channel`,[`stable`,`beta`,`dev`,`canary`],`Chrome channel`,{default:`stable`}).string(`userDataDir`,`Chrome profile directory`).query().openWorld()),t(`browser_select_tab`,e=>e.desc(`Switch active tab by index, URL pattern, or title pattern.`).number(`index`,`Tab index`).string(`urlPattern`,`URL substring match`).string(`titlePattern`,`Title substring match`).idempotent()),t(`framework_state_extract`,e=>e.desc(`Extract React/Vue/Svelte/Solid component state and meta-framework info.`).enum(`framework`,[`auto`,`react`,`vue2`,`vue3`,`svelte`,`solid`,`preact`],`Framework`,{default:`auto`}).string(`selector`,`Root element CSS selector`).number(`maxDepth`,`Max traversal depth`,{default:5}).query().openWorld()),t(`indexeddb_dump`,e=>e.desc(`Export all IndexedDB databases and records for offline analysis.`).string(`database`,`Database name`).string(`store`,`Object store name`).number(`maxRecords`,`Max records per store`,{default:100}).query()),t(`camoufox_geolocation`,e=>e.desc(`Get geolocation for a locale.`).string(`locale`,`Locale string`).string(`proxy`,`Proxy URL for IP lookup`).required(`locale`).query())],s=[t(`browser_codegen_start`,e=>e.desc(`Start recording browser actions as replayable steps.`).idempotent()),t(`browser_codegen_stop`,e=>e.desc(`Stop recording browser actions and return cleaned replay steps.`).query()),t(`captcha_solver_capabilities`,e=>e.desc(`Report CAPTCHA solving mode availability.`).query()),t(`human_mouse`,e=>e.desc(`Move mouse along a Bezier curve with jitter.`).number(`fromX`,`Start X`).number(`fromY`,`Start Y`).number(`toX`,`Target X`).number(`toY`,`Target Y`).string(`selector`,`CSS selector (alternative to toX/toY)`).string(`frameUrl`,`iframe URL substring`).string(`frameSelector`,`iframe CSS selector`).number(`durationMs`,`Duration ms`,{default:600}).number(`steps`,`Intermediate points`,{default:24}).number(`jitterPx`,`Max jitter px`,{default:1.5}).enum(`curve`,[`ease`,`linear`,`ease-in`,`ease-out`],`Speed curve`,{default:`ease`}).boolean(`click`,`Click at destination`,{default:!1}).openWorld()),t(`human_scroll`,e=>e.desc(`Scroll with randomized speed and pauses to mimic human behavior.`).number(`distance`,`Distance px`,{default:500}).enum(`direction`,[`up`,`down`,`left`,`right`],`Direction`,{default:`down`}).number(`durationMs`,`Duration ms`,{default:1500}).number(`segments`,`Segments`,{default:8}).number(`pauseMs`,`Pause between segments ms`,{default:80}).number(`jitter`,`Variation factor 0-1`,{default:.3}).string(`selector`,`Scrollable container selector`).openWorld()),t(`human_typing`,e=>e.desc(`Type text with human-like speed and occasional typos.`).string(`selector`,`CSS selector`).string(`text`,`Text to type`).string(`frameUrl`,`iframe URL substring`).string(`frameSelector`,`iframe CSS selector`).number(`wpm`,`Words per minute`,{default:90}).number(`errorRate`,`Typo probability per char`,{default:.02}).number(`correctDelayMs`,`Delay before correcting typo ms`,{default:200}).boolean(`clearFirst`,`Clear existing value first`,{default:!1}).requiredOpenWorld(`selector`,`text`)),t(`captcha_vision_solve`,e=>e.desc(`Solve a CAPTCHA with manual flow or a configured external service.`).enum(`mode`,[`external_service`,`manual`],`Solver mode`).string(`provider`,`External solver provider`).string(`apiKey`,`API key`).enum(`challengeType`,[`image`,`widget`,`browser_check`,`auto`],`Challenge type`,{default:`auto`}).string(`typeHint`,`Legacy alias for challengeType`).string(`siteKey`,`Widget site key`).string(`pageUrl`,`Page URL`).number(`timeoutMs`,`Timeout ms`,{default:18e4}).number(`maxRetries`,`Max retries`,{default:2}).openWorld()),t(`widget_challenge_solve`,e=>e.desc(`Solve a widget challenge with hook, manual, or configured external service.`).string(`siteKey`,`Widget site key`).string(`pageUrl`,`Page URL`).enum(`mode`,[`external_service`,`hook`,`manual`],`Solving mode`).string(`provider`,`External solver provider`).string(`apiKey`,`API key`).number(`timeoutMs`,`Timeout ms`,{default:12e4}).boolean(`injectToken`,`Auto-inject token`,{default:!0}).openWorld())],c=[t(`browser_jsdom_parse`,e=>e.desc(`Parse HTML into an in-memory JSDOM session. No browser needed.`).string(`html`,`HTML source`).string(`url`,`Document URL`).string(`contentType`,`Content-Type`).enum(`runScripts`,[`none`,`outside-only`,`dangerously`],`Script execution mode`,{default:`none`}).boolean(`includeNodeLocations`,`Track source offsets`,{default:!1}).boolean(`pretendToBeVisual`,`Expose rAF/matchMedia shims`,{default:!1}).string(`referrer`,`Referrer URL`).number(`storageQuotaBytes`,`Storage quota bytes`,{default:5e6}).required(`html`).query()),t(`browser_jsdom_query`,e=>e.desc(`Query a JSDOM session with a CSS selector.`).string(`sessionId`,`Session ID`).string(`selector`,`CSS selector`).number(`maxResults`,`Max matches`,{default:50}).array(`attributes`,{type:`string`},`Attribute whitelist`).boolean(`includeText`,`Include textContent`,{default:!0}).boolean(`includeHtml`,`Include outerHTML`,{default:!1}).boolean(`includeLocation`,`Include source offsets`,{default:!1}).required(`sessionId`,`selector`).query()),t(`browser_jsdom_execute`,e=>e.desc(`Evaluate JS inside a JSDOM session.`).string(`sessionId`,`Session ID`).string(`code`,`JavaScript code`).number(`timeoutMs`,`Timeout hint ms`,{default:5e3}).required(`sessionId`,`code`)),t(`browser_jsdom_serialize`,e=>e.desc(`Serialize a JSDOM session to HTML.`).string(`sessionId`,`Session ID`).string(`selector`,`CSS selector for a fragment`).boolean(`pretty`,`Pretty-print`,{default:!1}).required(`sessionId`).query()),t(`browser_jsdom_cookies`,e=>e.desc(`Manage cookies on a JSDOM session. Isolated from the attached browser.`).string(`sessionId`,`Session ID`).enum(`action`,[`get`,`set`,`clear`],`Action`,{default:`get`}).string(`url`,`URL scope`).object(`cookie`,{name:{type:`string`,description:`Name`},value:{type:`string`,description:`Value`},domain:{type:`string`,description:`Domain`},path:{type:`string`,description:`Path`},expires:{type:`string`,description:`Expiration`},httpOnly:{type:`boolean`,description:`HttpOnly`},secure:{type:`boolean`,description:`Secure`},sameSite:{type:`string`,description:`SameSite`},raw:{type:`string`,description:`Raw Set-Cookie string`}},`Cookie (action=set)`).destructive().requiredOpenWorld(`sessionId`))],l=[...a,...r,...i,...o,...s,...c];export{n,l as t};