@jshookmcp/jshook 0.3.2 → 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 (241) hide show
  1. package/README.md +3 -3
  2. package/README.zh.md +3 -3
  3. package/dist/{AntiCheatDetector-B6d4Qe9D.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
  4. package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-QIt3tetp.mjs} +1 -1
  5. package/dist/CodeInjector-Btj9upnf.mjs +1 -0
  6. package/dist/{ConsoleMonitor-CxDJV15E.mjs → ConsoleMonitor-DIjN5Afa.mjs} +5 -5
  7. package/dist/{DarwinAPI-ZfQdpLNI.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
  8. package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
  9. package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
  10. package/dist/{FingerprintManager-DT0EAUEo.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
  11. package/dist/{HardwareBreakpoint-BUfPdp0f.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
  12. package/dist/{HeapAnalyzer-B_aqY8oj.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
  13. package/dist/{ExtensionManager.tools-oVMJgPcN.mjs → MCPServer.activation.ttl-CEGNBycZ.mjs} +1 -1
  14. package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
  15. package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
  16. package/dist/{MemoryController-X1XNSn1n.mjs → MemoryController-DjtgiING.mjs} +1 -1
  17. package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
  18. package/dist/MemoryScanner-Dxd657li.mjs +1 -0
  19. package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
  20. package/dist/{PEAnalyzer-yWQaGrcx.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
  21. package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
  22. package/dist/{ProcessRegistry-C-bN48oR.mjs → ProcessRegistry-D5y1yuP2.mjs} +1 -1
  23. package/dist/{ReverseEvidenceGraph-BhSYYdiI.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
  24. package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
  25. package/dist/{Speedhack-yseDPSZ9.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
  26. package/dist/{StructureAnalyzer-C5lpuZkg.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
  27. package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
  28. package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
  29. package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-DQiREmNp.mjs} +1 -1
  30. package/dist/{ToolRegistry-C5oB8KP8.mjs → ToolRegistry-eMZEBiR1.mjs} +1 -1
  31. package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
  32. package/dist/{TraceRecorder-BiJWBXHX.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
  33. package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
  34. package/dist/{Win32API-eUCF57l_.mjs → Win32API-DoP3MMHS.mjs} +1 -1
  35. package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
  36. package/dist/{WorkflowEngine-D876meOO.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
  37. package/dist/{analysis-D4swdMvq.mjs → analysis-C-ln0Brh.mjs} +3 -3
  38. package/dist/antidebug-CsnpOR9z.mjs +1 -0
  39. package/dist/{artifactRetention-BCPQASm7.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
  40. package/dist/{artifacts-CkodUM4j.mjs → artifacts-D-4pSS_N.mjs} +1 -1
  41. package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
  42. package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
  43. package/dist/{boringssl-inspector-BBaJwwkU.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
  44. package/dist/browser-BUaB25bk.mjs +11 -0
  45. package/dist/{handlers-yo_xYzT8.mjs → canvas-396ieNv5.mjs} +22 -22
  46. package/dist/collector-CB2syQEg.mjs +1 -0
  47. package/dist/constants-DMv3svps.mjs +2 -0
  48. package/dist/coordination-Dbohmj6D.mjs +1 -0
  49. package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
  50. package/dist/debugger-CLzkObIO.mjs +1 -0
  51. package/dist/{definitions-OeLvmlQy.mjs → definitions-0hxnrDU72.mjs} +1 -1
  52. package/dist/definitions-B3a9QC2t.mjs +1 -0
  53. package/dist/{definitions-Ibci7e_L.mjs → definitions-BOvju5t2.mjs} +1 -1
  54. package/dist/{definitions-D4g-MS10.mjs → definitions-CXj_cEVt.mjs} +1 -1
  55. package/dist/{definitions-C3qNgSn1.mjs → definitions-Co6AvTjH.mjs} +1 -1
  56. package/dist/{definitions-DxFNRQNK2.mjs → definitions-Cv5r8xwq.mjs} +1 -1
  57. package/dist/definitions-DBYSxChX.mjs +1 -0
  58. package/dist/{definitions-CQd7yCQH.mjs → definitions-D_dTDX9B.mjs} +1 -1
  59. package/dist/{definitions-l7TjdE6V.mjs → definitions-Db9t2ddh.mjs} +1 -1
  60. package/dist/{definitions-BWxBke3r.mjs → definitions-DbN2CjI2.mjs} +1 -1
  61. package/dist/{definitions-DAQm1Xar.mjs → definitions-DlmmHmZc.mjs} +1 -1
  62. package/dist/{definitions-Bf3H1EwV.mjs → definitions-DnYpoGig.mjs} +1 -1
  63. package/dist/{definitions-BYwATKc-.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
  64. package/dist/{definitions-D5wl_8HN.mjs → definitions-DuIPS8gq.mjs} +1 -1
  65. package/dist/{definitions-RZYGD_Ey.mjs → definitions-DywfwPMb.mjs} +1 -1
  66. package/dist/definitions-EGmqr85H.mjs +1 -0
  67. package/dist/{definitions-bybDvnG0.mjs → definitions-Fetw_Cge.mjs} +3 -3
  68. package/dist/{definitions-CB6vmOer.mjs → definitions-LdkeuOeA.mjs} +1 -1
  69. package/dist/{definitions-B_83XfNQ.mjs → definitions-Ym8niHDb.mjs} +1 -1
  70. package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
  71. package/dist/{definitions-CT8ln6GQ.mjs → definitions-cnG6tj17.mjs} +1 -1
  72. package/dist/{encoding-ycOaz8Vr.mjs → encoding-B4xZWErf.mjs} +2 -2
  73. package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
  74. package/dist/{factory-CKr4fAE1.mjs → factory-BxNdBiZa.mjs} +1 -1
  75. package/dist/{graphql-B2TiPEow.mjs → graphql-GBWsZ9xC.mjs} +4 -4
  76. package/dist/{handlers-D5E40ssn.mjs → handlers-5nzR8B0a.mjs} +2 -2
  77. package/dist/handlers-6iNsXOVT.mjs +7 -0
  78. package/dist/{handlers-BpDlVVVU.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
  79. package/dist/{handlers-0yKLRIfo.mjs → handlers-BbLxNbbT.mjs} +1 -1
  80. package/dist/{handlers-DGbdQAgD.mjs → handlers-BbS4hssc.mjs} +2 -2
  81. package/dist/{handlers-l8QIKqBj.mjs → handlers-CIKOP4aI.mjs} +2 -2
  82. package/dist/handlers-CWKBBjai.mjs +1 -0
  83. package/dist/{handlers-B62K4FTc.mjs → handlers-Cmb6SoRC.mjs} +1 -1
  84. package/dist/handlers-CrJsKnEI.mjs +1 -0
  85. package/dist/{antidebug-7L3ygj_9.mjs → handlers-DB6xVVWq.mjs} +2 -2
  86. package/dist/{handlers-CMJK7m1c.mjs → handlers-DOOCWUNR.mjs} +3 -3
  87. package/dist/{handlers-D2ZOul9p.mjs → handlers-Z_B5aVaU.mjs} +2 -2
  88. package/dist/handlers-gVscChvl.mjs +1 -0
  89. package/dist/handlers-xFvI9P_y.mjs +1 -0
  90. package/dist/{handlers.impl-D9Hh8Bgl.mjs → handlers.impl-BsFTW6SD.mjs} +1 -1
  91. package/dist/{hooks-D4XLfgtV.mjs → hooks-DPouiS7I.mjs} +9 -9
  92. package/dist/index.mjs +11 -11
  93. package/dist/macro-p8kuJVcm.mjs +2 -0
  94. package/dist/maintenance-DAqADb6Z.mjs +302 -0
  95. package/dist/manifest-4lmM6MZR.mjs +1 -0
  96. package/dist/{manifest-DujQqEQR.mjs → manifest-AxaxRSt6.mjs} +2 -2
  97. package/dist/{manifest-DYpn8w_h.mjs → manifest-BIqRE1Qz.mjs} +1 -1
  98. package/dist/manifest-Box-jWfr.mjs +1 -0
  99. package/dist/manifest-Bp33di0Q.mjs +1 -0
  100. package/dist/{manifest-CQH9FhwI.mjs → manifest-BvRX4nRP.mjs} +1 -1
  101. package/dist/{manifest-0Jpt_AQa.mjs → manifest-C6KoB1XE.mjs} +1 -1
  102. package/dist/manifest-C7TdXCWY.mjs +1 -0
  103. package/dist/manifest-CM-n64K0.mjs +1 -0
  104. package/dist/{manifest-nXHmtMSp2.mjs → manifest-CUokxCUN.mjs} +1 -1
  105. package/dist/manifest-CWJS45iO.mjs +1 -0
  106. package/dist/{manifest-LLdI5m4T.mjs → manifest-Cdxdgo-D.mjs} +1 -1
  107. package/dist/{manifest-D_obs5F4.mjs → manifest-Cf6SmamD.mjs} +1 -1
  108. package/dist/manifest-Cgxu2qdv.mjs +1 -0
  109. package/dist/{manifest-ztWJoXy4.mjs → manifest-CowGSURa2.mjs} +1 -1
  110. package/dist/{manifest-DYzWI8Xs.mjs → manifest-CsGIrh34.mjs} +1 -1
  111. package/dist/manifest-CvDpVToN.mjs +1 -0
  112. package/dist/manifest-D8TL9RLE.mjs +1 -0
  113. package/dist/{manifest-DCx6w2XV.mjs → manifest-DIhtCBe6.mjs} +1 -1
  114. package/dist/{manifest-D9jUUJAu.mjs → manifest-DJbruNOg.mjs} +1 -1
  115. package/dist/manifest-DLGtZH-0.mjs +1 -0
  116. package/dist/manifest-DXHdPt2T.mjs +1 -0
  117. package/dist/{manifest-B3fZbSWR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
  118. package/dist/{manifest-xWfu6iLo.mjs → manifest-DzGoTS0R.mjs} +1 -1
  119. package/dist/manifest-G2H52LKz.mjs +131 -0
  120. package/dist/{manifest-CctIumog.mjs → manifest-P0Futrgb.mjs} +1 -1
  121. package/dist/{manifest-YgVd8Sgz.mjs → manifest-Qw7xgvjv.mjs} +1 -1
  122. package/dist/{manifest-QYbQXJn0.mjs → manifest-W3qvVrP2.mjs} +1 -1
  123. package/dist/manifest-dG6MuR1U.mjs +1 -0
  124. package/dist/manifest-nWXtgq5Y2.mjs +1 -0
  125. package/dist/{manifest-LG42zPLY2.mjs → manifest-vp1upSSq.mjs} +1 -1
  126. package/dist/{modules-BPBcSaM-.mjs → modules-DO3jXCgj.mjs} +10 -10
  127. package/dist/{mojo-ipc-BhwsdVUW.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
  128. package/dist/native-g095qhpK.mjs +961 -0
  129. package/dist/network-Dvxm7eEI.mjs +7 -0
  130. package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
  131. package/dist/{parse-args-Bw413PlW.mjs → parse-args-ngRrvF9e.mjs} +1 -1
  132. package/dist/platform-DjWbuiF8.mjs +93 -0
  133. package/dist/process-Dq5I-KZW.mjs +2 -0
  134. package/dist/proxy-DPNgM7TE.mjs +2 -0
  135. package/dist/{registry-DH4sc1dt.mjs → registry-xB8Wgmyj.mjs} +1 -1
  136. package/dist/{renderer-pid-9tJnZ_9N.mjs → renderer-pid-7jbTR8f5.mjs} +1 -1
  137. package/dist/search-defaults-CJik67or.mjs +1 -0
  138. package/dist/server/plugin-api.mjs +1 -1
  139. package/dist/sourcemap-DqEW15Ao.mjs +1 -0
  140. package/dist/streaming-Dbk4eStJ.mjs +1 -0
  141. package/dist/{transform-DOxzeWPB.mjs → transform-D-peM3aO.mjs} +2 -2
  142. package/dist/{wasm-CZ_HTfKR.mjs → wasm-CZajRaad.mjs} +6 -6
  143. package/dist/{webcrack-C1iYG_EX.mjs → webcrack-phEfVt5y.mjs} +3 -3
  144. package/dist/{workflow-BdwQmARn.mjs → workflow-wkXb3x-U.mjs} +3 -3
  145. package/package.json +2 -2
  146. package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
  147. package/dist/DOMInspector-C19J4zeq.mjs +0 -95
  148. package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
  149. package/dist/ExtensionManager-BD724zkO.mjs +0 -1
  150. package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
  151. package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
  152. package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
  153. package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
  154. package/dist/PageController-Dfsm1_o7.mjs +0 -1
  155. package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
  156. package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
  157. package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
  158. package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
  159. package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
  160. package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
  161. package/dist/VersionDetector-CHT36Az0.mjs +0 -9
  162. package/dist/apk-packer-BqXcInnX.mjs +0 -1
  163. package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
  164. package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
  165. package/dist/browser-Qqco2rOT.mjs +0 -11
  166. package/dist/collector-Bpl6qy2L.mjs +0 -1
  167. package/dist/constants-BYj8Xek8.mjs +0 -1
  168. package/dist/coordination-CWXW1o8K.mjs +0 -1
  169. package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
  170. package/dist/debugger-DyALjYMk.mjs +0 -1
  171. package/dist/definitions-BftdXgXI.mjs +0 -1
  172. package/dist/definitions-Bio5XJYy.mjs +0 -1
  173. package/dist/definitions-CMZRSy3k.mjs +0 -1
  174. package/dist/definitions-DP1vgxEY.mjs +0 -1
  175. package/dist/definitions-Tls8c0A0.mjs +0 -1
  176. package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
  177. package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
  178. package/dist/handlers-8zN_vBIz.mjs +0 -1
  179. package/dist/handlers-DHO3rjsW.mjs +0 -1
  180. package/dist/handlers-FJ80VzUI.mjs +0 -2
  181. package/dist/handlers-VHWrxbM_.mjs +0 -1
  182. package/dist/handlers-mPFiNPe8.mjs +0 -302
  183. package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
  184. package/dist/maintenance-BUpIukhg.mjs +0 -1
  185. package/dist/manifest-B7NB2rh2.mjs +0 -1
  186. package/dist/manifest-BDi4nbH1.mjs +0 -1
  187. package/dist/manifest-BLDfkE7n.mjs +0 -1
  188. package/dist/manifest-BcXbB4gf.mjs +0 -1
  189. package/dist/manifest-Bdnc_vrc.mjs +0 -1
  190. package/dist/manifest-BuYKgCnp.mjs +0 -1
  191. package/dist/manifest-CBfNnGPV.mjs +0 -1
  192. package/dist/manifest-CPS1Xv69.mjs +0 -1
  193. package/dist/manifest-CRryuZF4.mjs +0 -1
  194. package/dist/manifest-CvTe5ZGV2.mjs +0 -1
  195. package/dist/manifest-D-5GH0DV.mjs +0 -1
  196. package/dist/manifest-D3Ssf3IC.mjs +0 -1
  197. package/dist/manifest-D5ck3NvC.mjs +0 -1
  198. package/dist/manifest-DG19q-Ld.mjs +0 -1
  199. package/dist/manifest-DLMlD0Zc.mjs +0 -1
  200. package/dist/manifest-DwL2ik8P.mjs +0 -1
  201. package/dist/manifest-ItF5P8A12.mjs +0 -1
  202. package/dist/manifest-KZphqIyX.mjs +0 -1
  203. package/dist/manifest-RcpX_MyZ.mjs +0 -123
  204. package/dist/manifest-Zy7Odg5J.mjs +0 -1
  205. package/dist/manifest-ff1H7Pdp.mjs +0 -1
  206. package/dist/manifest-iuhF6pTL2.mjs +0 -1
  207. package/dist/manifest-yC16OhL2.mjs +0 -1
  208. package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
  209. package/dist/native-j8l473zn.mjs +0 -961
  210. package/dist/network-T0VRwNPd.mjs +0 -7
  211. package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
  212. package/dist/platform-CzaQtISh.mjs +0 -93
  213. package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
  214. package/dist/process-CWhsCWrf.mjs +0 -2
  215. package/dist/proxy-DZFlDsG3.mjs +0 -2
  216. package/dist/search-defaults-lYBVn_3L.mjs +0 -1
  217. package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
  218. package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
  219. package/dist/streaming-BcJ0B6ao.mjs +0 -1
  220. package/dist/types-D9EiE5o9.mjs +0 -1
  221. /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
  222. /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
  223. /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
  224. /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
  225. /package/dist/{InstrumentationSession-D_G1ZPyd.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
  226. /package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-nPXl_khE.mjs} +0 -0
  227. /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
  228. /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
  229. /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
  230. /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
  231. /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
  232. /package/dist/{capabilities-CyXuKUl1.mjs → capabilities-L1ax5EHS.mjs} +0 -0
  233. /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
  234. /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
  235. /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
  236. /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
  237. /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
  238. /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
  239. /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
  240. /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
  241. /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
@@ -1,11 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{C as t,S as n,T as r,_ as i,b as a,er as o,v as s,w as c,x as l,y as u}from"./constants-BYj8Xek8.mjs";import{t as d}from"./DetailedDataManager-DmQ1LT-W.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-BPBcSaM-.mjs";import{r as _}from"./BrowserSessionCoordinator-BJ-HOxo0.mjs";import{c as v,l as y,o as b,s as x,u as ee}from"./outputPaths-B4Ic4RZh.mjs";import{t as te}from"./PrerequisiteError-BjCQA-gK.mjs";import{n as ne,t as re}from"./betterSqlite3-Brtq-SIQ.mjs";import{t as ie}from"./concurrency-DCr8WQ2M.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-Bw413PlW.mjs";import{c as ae}from"./PageController-Dfsm1_o7.mjs";import{n as k,t as A}from"./ResponseBuilder-BfWP-uaT.mjs";import{n as oe}from"./capabilities-CyXuKUl1.mjs";import"./definitions-CMZRSy3k.mjs";import{join as se}from"path";import{randomUUID as ce}from"node:crypto";import{readFile as le,writeFile as ue}from"fs/promises";const de=se(ee,`.env`),fe=new Set([`stable`,`beta`,`dev`,`canary`]);var pe=class{deps;constructor(e){this.deps=e}pickPreferredAttachPage(e,t){if(e.length===0)return{selectedIndex:0,selected:null};if(t!==null&&t>=0&&t<e.length)return{selectedIndex:t,selected:e[t]??null};let n=e.findIndex(e=>e.url.trim().length>0&&e.url!==`about:blank`);return n>=0?{selectedIndex:n,selected:e[n]??null}:{selectedIndex:0,selected:e[0]??null}}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&&!fe.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 le(de,`utf-8`)}catch(e){if(e?.code!==`ENOENT`)throw e}let n=`PUPPETEER_HEADLESS=${t}`;await ue(de,/^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?A.ok().merge({driver:`camoufox`,mode:`connect`,wsEndpoint:e,message:`Connected to Camoufox server. Use page_navigate to begin.`}).json():A.fail(`wsEndpoint is required for connect mode. Use camoufox_server({ action: "launch" }) first to get a wsEndpoint.`).json()}return A.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 A.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 A.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];this.deps.onBrowserAttachStateChanged?.({endpoint:null,selectedIndex:t.length>0?0:null,selectedUrl:i?.url??null,selectedTitle:i?.title??null,selectedTargetId:null,browserPid:this.deps.collector.getChromePid(),rendererPid:null,attachedAt:new Date().toISOString()});let a=await this.deps.collector.getStatus();return A.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.listPages(),o=this.deps.getTabRegistry();a.length>0&&(await this.deps.collector.selectPage(0),o.setCurrentByIndex(0));let s=a[0];this.deps.onBrowserAttachStateChanged?.({endpoint:null,selectedIndex:a.length>0?0:null,selectedUrl:s?.url??null,selectedTitle:s?.title??null,selectedTargetId:null,browserPid:this.deps.collector.getChromePid(),rendererPid:null,attachedAt:new Date().toISOString()});let c=await this.deps.collector.getStatus();return A.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,selectedIndex:a.length>0?0:null,currentUrl:s?.url??null,currentTitle:s?.title??null,totalPages:a.length,status:c,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 A.fail(e).json()}}async handleBrowserClose(e){try{return await this.deps.collector.close(),A.ok().set(`message`,`Browser closed successfully`).json()}catch(e){return A.fail(e).json()}}async handleBrowserStatus(e){try{let e=await this.deps.collector.getStatus();return A.ok().merge({driver:`chrome`,...e}).json()}catch(e){return A.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 A.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 A.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`),A.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 A.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`),A.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 A.fail(e).json()}}async handleBrowserAttach(t){let n=null;try{if(n=this.parseChromeConnectRequest(t),!this.hasChromeConnectRequest(n))return A.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=i!=null&&!(typeof i==`string`&&i.trim()===``),o=typeof i==`number`?i:typeof i==`string`&&i.trim()!==``?Number(i):0,s=Number.isFinite(o)?o:0,c=await this.deps.collector.listPages(),l=this.pickPreferredAttachPage(c,a?s:null).selectedIndex;c.length>0&&(await this.deps.collector.selectPage(l),s!==l&&e.warn(`[browser_attach] requested pageIndex ${s} resolved to ${l}; preferred non-blank target when available`));let u=this.deps.getTabRegistry();await this.syncTabRegistryWithCollectorPages(`browser_attach`);let d=c.length>0?Math.min(l,c.length-1):0,f=c.length>0?u.setCurrentByIndex(d):null,p=c[d],m=!!f?.pageId,h=this.deps.collector.getChromePid(),g={pageControllerReady:m,v8InspectorReady:m,memoryRendererPidReady:h!==null};m&&this.markMonitoringContextChanged(`browser_attach`);let _=await this.deps.collector.getStatus(),v=this.deps.collector.getAttachedTargetInfo();return this.deps.onBrowserAttachStateChanged?.({endpoint:this.describeChromeConnectRequest(n),selectedIndex:d,selectedUrl:p?.url??null,selectedTitle:p?.title??null,selectedTargetId:v?.targetId??null,browserPid:h,attachedAt:new Date().toISOString()}),A.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:d,selectedPageId:f?.pageId??null,currentUrl:p?.url??null,currentTitle:p?.title??null,totalPages:c.length,contextSwitched:c.length>0,detachedCdpTarget:r.detached,detachedCdpTargetId:r.targetId,monitoringBindingDeferred:m,networkMonitoringEnabled:!1,consoleMonitoringEnabled:!1,takeoverReady:m,capabilities:g,note:m?`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. V8/page-bound tools will degrade until a stable Page handle is available.`,status:_}).json()}catch(e){return this.deps.onBrowserAttachStateChanged?.({endpoint:n?this.describeChromeConnectRequest(n):null}),A.fail(e).set(`approvalHint`,this.getAutoConnectApprovalHint(n??{})).json()}}};function me(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 he(){try{return await import(`camoufox-js`),null}catch(e){let t=e instanceof Error?e.message:String(e);return ne(e)?`Camoufox requires the same native SQLite backend used by trace tooling. ${re(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 ge=class{deps;constructor(e){this.deps=e}async handleCamoufoxServerLaunch(t){try{let n=await he();if(n)return e.warn(`Camoufox dependencies not available: ${n}`),A.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=me(t),o=this.deps.getCamoufoxManager();o||(o=new g(a),this.deps.setCamoufoxManager(o));let s=await o.launchAsServer(r,i);return A.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 A.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(),A.ok().set(`message`,`Camoufox server closed.`).json()):A.fail(`No camoufox server is running.`).json()}catch(e){return A.fail(e).json()}}async handleCamoufoxServerStatus(e){try{let e=this.deps.getCamoufoxManager()?.getBrowserServerEndpoint()??null;return A.ok().merge({running:e!==null,wsEndpoint:e}).json()}catch(e){return A.fail(e).json()}}};const _e=new Set(ae);function j(e){return w(e,`waitUntil`,_e,`networkidle`)}var ve=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)}syncRuntimeAttachMeta(e){this.deps.onBrowserAttachStateChanged&&(!e.url||e.title===void 0||this.deps.onBrowserAttachStateChanged({selectedUrl:e.url,selectedTitle:e.title,rendererPid:null}))}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){return k(async()=>{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.syncRuntimeAttachMeta({url:a,title:o}),this.deps.eventBus?.emit(`browser:navigated`,{url:a,timestamp:new Date().toISOString()}),{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.syncRuntimeAttachMeta({url:o,title:s}),this.deps.eventBus?.emit(`browser:navigated`,{url:o,timestamp:new Date().toISOString()}),{url:o,title:s,network_monitoring:{enabled:this.deps.consoleMonitor.isNetworkEnabled()}}})}async handlePageReload(e){return k(async()=>{if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.reload();let t=this.getCamoufoxUrlIfAvailable(e),n=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:t,title:n}),this.syncRuntimeAttachMeta({url:t,title:n}),{message:`Page reloaded`,driver:`camoufox`}}await this.deps.pageController.reload();let e=await this.getChromePageIfAvailable(),t=await this.deps.pageController.getURL(),n=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(e,{url:t,title:n}),this.syncRuntimeAttachMeta({url:t,title:n}),{message:`Page reloaded`}})}async handlePageBack(e){return k(async()=>{let t=E(e,`timeout`,1e4);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.goBack();let t=this.getCamoufoxUrlIfAvailable(e),n=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:t,title:n}),this.syncRuntimeAttachMeta({url:t,title:n}),{url:t,driver:`camoufox`}}await this.deps.pageController.goBack(t);let n=await this.getChromePageIfAvailable(),r=await this.deps.pageController.getURL(),i=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(n,{url:r,title:i}),this.syncRuntimeAttachMeta({url:r,title:i}),{url:r}})}async handlePageForward(e){return k(async()=>{let t=E(e,`timeout`,1e4);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.goForward();let t=this.getCamoufoxUrlIfAvailable(e),n=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:t,title:n}),this.syncRuntimeAttachMeta({url:t,title:n}),{url:t,driver:`camoufox`}}await this.deps.pageController.goForward(t);let n=await this.getChromePageIfAvailable(),r=await this.deps.pageController.getURL(),i=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(n,{url:r,title:i}),this.syncRuntimeAttachMeta({url:r,title:i}),{url:r}})}},ye=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 A.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}),A.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 A.ok().build({message:`Clicked ${t} - navigation triggered`,navigated:!0,...c?{frame:c}:{}});throw e}return A.ok().build({message:`Clicked: ${t}`,...c?{frame:c}:{}})}catch(e){return A.fail(e).build()}}async handlePageType(e){return k(async()=>{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),{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}),{message:`Typed into ${t}`,...o?{frame:o}:{}})})}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 A.fail(`selector parameter is required`).build();if(n.length===0)return A.fail(`paths parameter must contain at least one relative file path`).build();let o=n.map(e=>x(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`?A.fail(`File input not found: ${t}`).build({driver:`camoufox`}):(await r.setInputFiles(o),A.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),A.ok().build({selector:t,count:o.length,paths:n,message:`Uploaded ${o.length} file(s) into ${t}`,...a?{frame:a}:{}})}catch(e){return A.fail(e).build()}}async handlePageSelect(e){return k(async()=>{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),{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),{message:`Selected in ${t}: ${n.join(`, `)}`,...a?{frame:a}:{}})})}async handlePageHover(e){return k(async()=>{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),{driver:`camoufox`,message:`Hovered: ${t}`,...i?{frame:i}:{}}):(i?await this.deps.pageController.hover(t,i):await this.deps.pageController.hover(t),{message:`Hovered: ${t}`,...i?{frame:i}:{}})})}async handlePageScroll(e){return k(async()=>{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}),{driver:`camoufox`,message:`Scrolled to: x=${t||0}, y=${n||0}`}):(await this.deps.pageController.scroll({x:t,y:n}),{message:`Scrolled to: x=${t||0}, y=${n||0}`})})}async handlePagePressKey(e){return k(async()=>{let t=S(e,`key`,``);return this.deps.getActiveDriver()===`camoufox`?(await(await this.deps.getCamoufoxPage()).keyboard.press(t),{driver:`camoufox`,key:t}):(await this.deps.pageController.pressKey(t),{key:t})})}};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 be=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 A.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 A.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 A.ok().build({...c?{frame:c}:{},result:l})}catch(e){return A.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 v({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 A.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 A.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 A.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 A.ok().build({selector:c||void 0,clip:a||void 0,message:`Screenshot taken: ${u}`,path:u,pathRewritten:d,size:f.length})}catch(e){return A.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 v({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 A.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),A.ok().build({message:`Script injected`})}catch(e){return A.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 A.ok().build({driver:`camoufox`,element:r,message:`Selector appeared: ${t}`})}catch{return A.fail(`Timeout waiting for selector: ${t}`).build({driver:`camoufox`})}}let r=await this.deps.pageController.waitForSelector(t,n);return A.ok().merge(r).build()}catch(e){return A.fail(e).build()}}},xe=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){return k(async()=>{let e=this.deps.getActiveDriver()===`camoufox`?await this.listCamoufoxFrames():await this.deps.pageController.listFrames();return{count:e.length,frames:e}})}async handleGetContent(e){return k(async()=>({html:await this.deps.pageController.getContent()}))}async handleGetTitle(e){return k(async()=>({title:await this.deps.pageController.getTitle()}))}async handleGetUrl(e){return k(async()=>({url:await this.deps.pageController.getURL()}))}async handleGetText(e){return k(async()=>{let t=S(e,`selector`,``);return{selector:t,text:await this.deps.pageController.evaluate(`document.querySelector(${JSON.stringify(t)})?.textContent || ""`)}})}async handleGetOuterHtml(e){return k(async()=>{let t=S(e,`selector`,``);return{selector:t,html:await this.deps.pageController.evaluate(`document.querySelector(${JSON.stringify(t)})?.outerHTML || ""`)}})}async handleGetScrollPosition(e){return k(async()=>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
- })`))}async handlePageSetCookies(e){return k(async()=>{let t=e.cookies;return await this.deps.pageController.setCookies(t),{message:`Set ${t.length} cookies`}})}async handlePageGetCookies(e){return k(async()=>{let e=await this.deps.pageController.getCookies();return{count:e.length,cookies:e}})}async getPageCookieCount(){return(await this.deps.pageController.getCookies()).length}async handlePageClearCookies(e){return k(async()=>(await this.deps.pageController.clearCookies(),{message:`Cookies cleared`}))}async handlePageSetViewport(e){return k(async()=>{let t=E(e,`width`,0),n=E(e,`height`,0);return await this.deps.pageController.setViewport(t,n),{viewport:{width:t,height:n}}})}async handlePageEmulateDevice(e){return k(async()=>{let t=S(e,`device`,``);return await this.deps.pageController.emulateDevice(t),{device:t}})}async handlePageGetLocalStorage(e){return k(async()=>{let e=await this.deps.pageController.getLocalStorage();return{count:Object.keys(e).length,storage:e}})}async handlePageSetLocalStorage(e){return k(async()=>{let t=S(e,`key`,``),n=S(e,`value`,``);return await this.deps.pageController.setLocalStorage(t,n),{key:t}})}},Se=class{deps;constructor(e){this.deps=e}async handleConsoleMonitor(e){return k(async()=>S(e,`action`)===`enable`?(await this.deps.consoleMonitor.enable(),{message:`Console monitoring enabled`}):(await this.deps.consoleMonitor.disable(),{message:`Console monitoring disabled`}))}async handleConsoleGetLogs(e){return k(async()=>{let t=S(e,`type`),n=E(e,`limit`),r=E(e,`since`),i=this.deps.consoleMonitor.getLogs({type:t,limit:n,since:r});return this.deps.detailedDataManager.smartHandle({count:i.length,logs:i},51200)})}async handleConsoleExecute(e){return k(async()=>{let t=S(e,`expression`,``),n=E(e,`maxSize`,10485760),r=O(e,`stripBase64`,!1);if(!t.trim())throw Error(`expression is required`);return{result:P(await this.deps.consoleMonitor.execute(t),this.deps.detailedDataManager,{autoSummarize:!0,maxSize:n,stripBase64:r})}})}},Ce=class{deps;constructor(e){this.deps=e}async handleGetAllScripts(e){return k(async()=>{let t=O(e,`includeSource`,!1),n=Math.min(E(e,`maxScripts`,t?200:1e3),o),r=await this.deps.scriptManager.getAllScripts(t,n);return this.deps.detailedDataManager.smartHandle({count:r.length,scripts:r})})}async handleGetScriptSource(e){return k(async()=>{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)throw Error(`Script not found`);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;return 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
- `)),{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 this.deps.detailedDataManager.smartHandle(s,51200)})}},we=class{deps;constructor(e){this.deps=e}async handleCaptchaDetect(e){return k(async()=>{let e=await this.deps.pageController.getPage(),t=await this.deps.captchaDetector.detect(e);return{captcha_detected:t.detected,captcha_info:t}})}async handleCaptchaWait(t){return k(async()=>{let n=E(t,`timeout`,this.deps.captchaTimeout),r=await this.deps.pageController.getPage();if(e.info(`Waiting for CAPTCHA to be solved...`),!await this.deps.captchaDetector.waitForCompletion(r,n))throw Error(`CAPTCHA wait timed out`);return{message:`CAPTCHA solved`}})}async handleCaptchaConfig(e){return k(async()=>(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)),{config:{autoDetectCaptcha:this.deps.autoDetectCaptcha,autoSwitchHeadless:this.deps.autoSwitchHeadless,captchaTimeout:this.deps.captchaTimeout}}))}};const Te={enabled:!0,minDelayMs:20,maxDelayMs:80,burstMode:!1};var Ee=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 De=[{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={...Te};let I=null;const L=Ee.getInstance();async function R(){if(I)return I;try{return I=(await import(`./FingerprintManager-DT0EAUEo.mjs`)).FingerprintManager.getInstance(),I}catch{return null}}var Oe=class{deps;constructor(e){this.deps=e}async handleStealthInject(t){try{if(this.deps.getActiveDriver()===`camoufox`)return A.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 A.ok().build({message:`Stealth scripts injected successfully`,fingerprintApplied:r,patchManifest:De,_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 A.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),A.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 A.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),A.ok().build({jitterOptions:F,message:`CDP timing jitter ${F.enabled?`enabled`:`disabled`}: ${F.minDelayMs}-${F.maxDelayMs}ms${F.burstMode?` (burst mode)`:``}`})}catch(e){return A.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 A.ok().build({fingerprint:r,driver:`camoufox`,message:`Fingerprint generated using camoufox native engine. Apply via browser_launch(fingerprint=...) before launching.`})}catch(e){return A.fail(`Camoufox fingerprint generation failed: ${e instanceof Error?e.message:String(e)}`).build()}let t=await R();if(!t?.isAvailable())return A.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 A.ok().build({profile:n,message:`Fingerprint generated and cached. It will be auto-applied on next stealth_inject.`})}catch(e){return A.fail(e).build()}}async handleStealthVerify(e){try{let e=await this.deps.pageController.getPage(),t=await new(await(import(`./StealthVerifier-BmcxfwSF.mjs`))).StealthVerifier().verify(e);return A.ok().merge(t).build()}catch(e){return A.fail(`Stealth verification failed: ${e instanceof Error?e.message:String(e)}`).build()}}async handleCamoufoxGeolocation(e){try{let t=S(e,`locale`);if(!t)return A.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 A.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 A.ok().build({locale:t,geolocation:n,publicIp:r})}catch(e){return A.fail(e).build()}}},ke=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 te(`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 A.ok().build(a)}catch(e){return A.fail(e).build()}}},Ae=class{deps;constructor(e){this.deps=e}async handleIndexedDBDump(e){let t=S(e,`database`,``),n=S(e,`store`,``),r=E(e,`maxRecords`,100);return k(async()=>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}))}},je=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 A.ok().build({detailId:t,path:n||`full`,data:r})}catch(e){return A.fail(e).set(`hint`,`DetailId may have expired (TTL: 10 minutes) or is invalid`).build()}}},Me=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 A.fail(`code, script, or expression is required`).build();let c=this.deps.pageController.getAttachedTargetInfo();if(!c)return A.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 A.ok().build({target:c,result:l})}catch(t){return e.error(`Failed to evaluate in CDP target:`,t),A.fail(t instanceof Error?t.message:String(t)).build()}}},Ne=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 A.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),A.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`),A.ok().build({attached:!0,target:n,...r})}catch(t){return e.error(`Failed to attach CDP target:`,t),A.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`),A.ok().build({detached:t,targetId:e?.targetId??null})}catch(t){return e.error(`Failed to detach CDP target:`,t),A.fail(t instanceof Error?t.message:String(t)).build()}}};const Pe=[`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 Fe(e){return z(e)&&typeof e.createCDPSession==`function`}function Ie(e){return z(e)&&typeof e.chunk==`string`}var Le=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?ie(async()=>{let t=null,a=!1;try{let o=await this.deps.getActivePage();if(!Fe(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=>{Ie(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 A.ok().build(this.detailedDataManager.smartHandle(d,51200))}catch(t){return e.error(`[js_heap_search] Error:`,t),A.fail(t).build()}finally{if(a&&t)try{await t.detach()}catch{}}}):A.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)??Pe[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 Re=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 ze(e){return typeof e==`string`&&Re.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 Be(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 Ve(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 He(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:t}var Ue=class{deps;constructor(e){this.deps=e}get registry(){return this.deps.getTabRegistry()}async handleTabWorkflow(t){let n=t.action;try{if(!ze(n))return A.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}),A.fail(i).build()}}listAliases(){let e=this.registry.getCurrentTabInfo(this.deps.getActiveDriver()),t=this.registry.getSharedContextMap();return A.ok().build({aliases:e.aliases,staleAliases:e.staleAliases,currentPageId:e.currentPageId,currentIndex:e.currentIndex,currentUrl:e.url,context:t})}clearState(){return this.registry.clear(),A.ok().build({cleared:!0})}async aliasBind(e){let t=U(e.alias),n=Ve(e.index);if(!t)return A.fail(`alias is required`).build();if(n===null)return A.fail(`index is required`).build();await this.reconcilePages();let r=this.registry.bindAliasByIndex(t,n);return r?A.ok().build({bound:{alias:t,index:n,pageId:r}}):A.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 A.fail(`alias is required`).build();if(!n)return A.fail(`url is required`).build();if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();if(!H(e))return A.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),A.ok().build({alias:t,index:a,pageId:s,url:i.url(),title:o})}let r=await this.getBrowserFromController();if(!r)return A.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),A.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 A.fail(`alias is required`).build();if(!n)return A.fail(`url is required`).build();let r=await this.getPageByAlias(t);return r?(await r.goto(n,{waitUntil:`domcontentloaded`}),A.ok().build({alias:t,navigated:n,currentUrl:r.url()})):A.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=He(e.timeoutMs,1e4);if(!t)return A.fail(`alias is required`).build();if(!n&&!r)return A.fail(`selector or waitForText is required`).build();let a=await this.getPageByAlias(t);if(!a)return A.fail(`No tab found for alias "${t}"`).build();if(n)return await a.waitForSelector(n,{timeout:i}),A.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 A.ok().build({alias:t,waitedForText:o,found:!0});await new Promise(e=>setTimeout(e,500))}return A.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),A.ok().build({set:{key:t,value:n}})):A.fail(`key is required`).build()}contextGet(e){let t=U(e.key);if(!t)return A.fail(`key is required`).build();let{value:n,found:r}=this.registry.getSharedContext(t);return A.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 A.fail(`fromAlias is required`).build();if(!n)return A.fail(`key is required`).build();if(!r)return A.fail(`expression is required`).build();let i=await this.getPageByAlias(t);if(!i)return A.fail(`No tab found for alias "${t}"`).build();let a=await i.evaluate(r);return this.registry.setSharedContext(n,a),A.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 Be(t)?t:null}};const We=new Set([`none`,`outside-only`,`dangerously`]),Ge=new Set([`get`,`set`,`clear`]),W=10*1024*1024,G=600*1e3;var Ke=class{sessions=new Map;createSessionId(){return ce()}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 A.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`,We,`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 A.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 A.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 A.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 A.ok().set(`sessionId`,t).set(`selector`,n).set(`matched`,u.length).set(`returned`,d.length).set(`results`,d).build()}catch(e){return A.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 A.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=Ye(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?A.ok().set(`sessionId`,t).set(`result`,K(c)).set(`consoleLogs`,a).set(`timeoutHintMs`,r).build():A.fail(l).set(`consoleLogs`,a).build()}catch(e){return A.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 A.fail(`No element matches selector: ${r}`).build();a=e.outerHTML}else a=i.dom.serialize();return n&&(a=Xe(a)),A.ok().set(`sessionId`,t).set(`bytes`,Buffer.byteLength(a,`utf8`)).set(`pretty`,n).set(`html`,a).build()}catch(e){return A.fail(e).build()}}async handleJsdomCookies(e){try{let t=D(e,`sessionId`),n=w(e,`action`,Ge,`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 A.ok().set(`sessionId`,t).set(`url`,a).set(`cookies`,e.map(qe)).build()}if(n===`set`){let n=C(e,`cookie`);if(!n)return A.fail(`cookie object required for action="set"`).build();let r=typeof n.raw==`string`?n.raw:Je(n);return await i.setCookie(r,a),A.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())),A.ok().set(`sessionId`,t).set(`action`,`clear`).build()}catch(e){return A.fail(e).build()}}};function qe(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 Je(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 Ye(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 Xe(e){return e.replace(/>(?=<)/g,`>
10
- `)}function Ze(e){let t={getActiveDriver:e.getActiveDriver,getCamoufoxPage:e.getCamoufoxPage},n=new _,r=e.getTabRegistry??(()=>n),i=new Ne({collector:e.collector,consoleMonitor:e.consoleMonitor,getTabRegistry:r});return{tabRegistry:n,targetControl:i,browserControl:new pe({collector:e.collector,pageController:e.pageController,consoleMonitor:e.consoleMonitor,getActiveDriver:e.getActiveDriver,getCamoufoxManager:e.getCamoufoxManager,getCamoufoxPage:e.getCamoufoxPage,getTabRegistry:r,clearAttachedTargetContext:e=>i.clearAttachedTargetContext(e),onBrowserAttachStateChanged:e.onBrowserAttachStateChanged}),camoufoxBrowser:new ge({getCamoufoxManager:e.getCamoufoxManager,setCamoufoxManager:e.setCamoufoxManager,closeCamoufox:e.closeCamoufox}),pageNavigation:new ve({pageController:e.pageController,consoleMonitor:e.consoleMonitor,getTabRegistry:r,eventBus:e.eventBus,onBrowserAttachStateChanged:e.onBrowserAttachStateChanged,...t}),pageInteraction:new ye({pageController:e.pageController,...t}),pageEvaluation:new be({pageController:e.pageController,detailedDataManager:e.detailedDataManager,...t}),targetEvaluation:new Me({pageController:e.pageController,detailedDataManager:e.detailedDataManager}),pageData:new xe({pageController:e.pageController,...t}),consoleHandlers:new Se({consoleMonitor:e.consoleMonitor,detailedDataManager:e.detailedDataManager}),scriptManagement:new Ce({scriptManager:e.scriptManager,detailedDataManager:e.detailedDataManager}),captchaHandlers:new we({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 Oe({pageController:e.pageController,...t}),frameworkState:new ke({getActivePage:()=>e.collector.getActivePage()}),indexedDBDump:new Ae({getActivePage:()=>e.collector.getActivePage()}),jsHeapSearch:new Le({getActivePage:()=>e.collector.getActivePage(),getActiveDriver:e.getActiveDriver}),tabWorkflow:new Ue({getActiveDriver:e.getActiveDriver,getCamoufoxPage:e.getCamoufoxPage,getPageController:()=>e.pageController,getTabRegistry:r}),detailedData:new je({detailedDataManager:e.detailedDataManager}),jsdomHandlers:new Ke}}function Qe(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 $e(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 et(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 q(e){return new Promise(t=>setTimeout(t,e))}function J(e){let t=S(e,`frameUrl`),n=S(e,`frameSelector`);if(!(!t&&!n))return{frameUrl:t||void 0,frameSelector:n||void 0}}async function Y(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 tt(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 nt(e,t,n){return k(async()=>{let r=J(e),i=await Y(t,n,r);if(!i)throw Error(`No active page. Use browser_launch or browser_attach first.`);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)throw Error(`Selector not found: ${l}`);let t=await tt(a,o,e);s=t.x,c=t.y}if(s===void 0||c===void 0)throw Error(`Either selector or toX/toY coordinates are required`);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]=$e(_,v),x=p/f;for(let e=0;e<=f;e++){let t=Qe(_,y,b,v,et(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 q(x*(.8+Math.random()*.4))}return g&&await a.mouse.click(s,c),{from:{x:u,y:d},to:{x:s,y:c},steps:f,durationMs:p,clicked:g,...r?{frame:r}:{}}})}async function rt(e,t){return k(async()=>{let n=await t.getActivePage();if(!n)throw Error(`No active page.`);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 q(s*(.5+Math.random()))}return{direction:i,requestedDistance:r,actualScrolled:Math.round(f),durationMs:a,pauseMs:s,segments:o}})}async function it(e,t,n){return k(async()=>{let r=J(e),i=await Y(t,n,r);if(!i)throw Error(`No active page.`);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)throw Error(`selector and text are required`);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 q(d*(.5+Math.random())),await a.keyboard.press(`Backspace`),await q(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 q(t)}return{selector:s,length:c.length,wpm:l,typosSimulated:m,errorRate:u,...r?{frame:r}:{}}})}function X(e){return new Promise(t=>setTimeout(t,e))}function at(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 ot(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`:`image`}function st(e){let t=typeof e==`string`?e.toLowerCase():``;if(t===`image`||t===`recaptcha_v2`||t===`recaptcha_v3`||t===`hcaptcha`||t===`funcaptcha`||t===`turnstile`)return t}function ct(e,t){return st(e)||(t===`image`?`image`:`recaptcha_v2`)}function lt(e){return e!==`image`}function ut(e){if(!(typeof e!=`string`||!e.trim()))return e.trim().toLowerCase()}function dt(e){let t=ut(e.provider),n=(process.env.CAPTCHA_PROVIDER||``).trim().toLowerCase();return t||n||`2captcha`}function ft(e){return e===`2captcha`?process.env.CAPTCHA_SOLVER_BASE_URL?.trim()||process.env.CAPTCHA_2CAPTCHA_BASE_URL?.trim()||c:e===`anticaptcha`?process.env.CAPTCHA_ANTICAPTCHA_BASE_URL?.trim()||``:e===`capsolver`&&process.env.CAPTCHA_CAPSOLVER_BASE_URL?.trim()||``}function pt(e,t){return e===`anticaptcha`?t===`recaptcha_v2`?`RecaptchaV2TaskProxyless`:t===`hcaptcha`?`HCaptchaTaskProxyless`:t===`turnstile`?`TurnstileTaskProxyless`:`ImageToTextTask`:e===`capsolver`?t===`recaptcha_v2`?`ReCaptchaV2TaskProxyLess`:t===`hcaptcha`?`HCaptchaTaskProxyLess`:t===`turnstile`?`AntiTurnstileTaskProxyLess`:`ImageToTextTask`:``}async function Z(e,i,a,o){let s=Date.now(),c=ft(e);if(!c)throw Error(`${e} base URL is not configured.`);let l=pt(e,a.taskKind),u=a.taskKind===`image`?{type:l,body:a.imageBase64}:{type:l,websiteURL:a.pageUrl,websiteKey:a.siteKey},d=await(await fetch(`${c}/createTask`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({clientKey:i,task:u}),signal:AbortSignal.timeout(r)})).json();if(d.errorId&&d.errorId!==0)throw Error(`${e} createTask failed: ${String(d.errorCode??d.errorDescription??JSON.stringify(d))}`);let f=d.taskId;if(typeof f!=`number`&&typeof f!=`string`)throw Error(`${e} createTask did not return a taskId.`);for(;;){let r=o-(Date.now()-s);if(r<=0||(await X(Math.min(n,r)),Date.now()-s>=o))break;let l=await(await fetch(`${c}/getTaskResult`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({clientKey:i,taskId:f}),signal:AbortSignal.timeout(t)})).json();if(l.errorId&&l.errorId!==0)throw Error(`${e} getTaskResult failed: ${String(l.errorCode??l.errorDescription??JSON.stringify(l))}`);if(l.status===`processing`||l.status===`idle`)continue;if(l.status!==`ready`)throw Error(`${e} returned unexpected status: ${String(l.status)}`);let u=typeof l.solution==`object`&&l.solution!==null?l.solution:null,d=typeof u?.gRecaptchaResponse==`string`?u.gRecaptchaResponse:typeof u?.token==`string`?u.token:typeof u?.text==`string`?u.text:``;if(!d)throw Error(`${e} returned ready without a usable solution token.`);return{token:d,challengeType:a.taskKind===`image`?`image`:`widget`,mode:`external_service`,durationMs:Date.now()-s}}throw Error(`${e} solve timeout after ${o}ms`)}async function mt(e){if(typeof e.screenshot==`function`)return(await e.screenshot({type:`png`})).toString(`base64`);throw Error(`Could not capture image CAPTCHA payload from the current page.`)}function ht(e){if(typeof e!=`string`)return;let t=e.trim();if(t){if(t.startsWith(`data:`)){let e=t.indexOf(`,`);return e>=0?t.slice(e+1):void 0}return t}}function gt(e){return{enabled:O(e,`injectToken`,!0),responseSelector:S(e,`responseSelector`,``).trim()||void 0,callbackName:S(e,`callbackName`,``).trim()||void 0}}async function _t(e,t,n){await e.evaluate((e,t)=>{let{responseSelector:n,callbackName:r}=t;if(n){let t=document.querySelector(n);t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement?(t.value=e,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0}))):t instanceof HTMLElement&&(t.setAttribute(`data-captcha-token`,e),t.dispatchEvent(new CustomEvent(`captcha-token`,{detail:e})))}if(r){let t=window[r];typeof t==`function`&&t(e)}},t,n)}async function vt(e,i,a){let o=Date.now(),s=ft(`2captcha`);if(!s)throw Error(`CAPTCHA_SOLVER_BASE_URL must be configured before using external_service mode.`);let c={key:e,json:1};i.taskKind===`turnstile`||i.taskKind===`recaptcha_v2`||i.taskKind===`hcaptcha`?(c.method=i.taskKind===`turnstile`?`turnstile`:i.taskKind===`hcaptcha`?`hcaptcha`:`userrecaptcha`,c.sitekey=i.siteKey,c.pageurl=i.pageUrl):(c.method=`base64`,c.body=i.imageBase64);let l=await(await fetch(`${s}/in.php`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(c),signal:AbortSignal.timeout(r)})).json();if(l.status!==1)throw Error(`2captcha submit failed: ${JSON.stringify(l)}`);let u=l.request,d=n;for(;;){let n=a-(Date.now()-o);if(n<=0||(await X(Math.min(d,n)),Date.now()-o>=a))break;let r=new URL(`${s}/res.php`);r.searchParams.set(`key`,e),r.searchParams.set(`action`,`get`),r.searchParams.set(`id`,u),r.searchParams.set(`json`,`1`);let c=await(await fetch(r.toString(),{signal:AbortSignal.timeout(t)})).json();if(c.status===1)return{token:c.request,challengeType:i.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 ${a}ms`)}async function yt(t,n){let r=await n.getActivePage();if(!r)return A.fail(`No active page.`).build();let o=at(t.mode??t.provider??process.env.CAPTCHA_PROVIDER),c=dt(t),d=S(t,`apiKey`,``)||process.env.CAPTCHA_API_KEY||``,f=ot(t.challengeType??t.typeHint),p=ct(t.taskKind,f),m=Math.min(Math.max(E(t,`timeoutMs`,s),l),a),h=Math.min(Math.max(E(t,`maxRetries`,i),0),u),g=f,_=S(t,`siteKey`),v=S(t,`pageUrl`,``)||r.url();if(lt(p)&&!_)return A.fail(`Widget solving requires an explicit siteKey.`).build();if(o===`manual`)return A.ok().build({mode:`manual`,challengeType:g,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 A.fail(`External solver credentials are required. Set CAPTCHA_API_KEY.`).build();if(![`2captcha`,`anticaptcha`,`capsolver`].includes(c))return A.fail(`Unsupported external solver service.`).build();let y=null;for(let n=0;n<=h;n++)try{let e=p===`image`?ht(t.imageBase64)??await mt(r):void 0,i=c===`2captcha`?await vt(d,{taskKind:p,siteKey:_,pageUrl:v,imageBase64:e},m):await Z(c,d,{taskKind:p,siteKey:_,pageUrl:v,imageBase64:e},m);return A.ok().build({token:i.token,challengeType:i.challengeType,mode:i.mode,durationMs:i.durationMs,attempt:n+1})}catch(t){y=t instanceof Error?t:Error(String(t)),e.warn(`[captcha] Attempt ${n+1} failed: ${y.message}`)}return A.fail(y??Error(`All attempts failed`)).merge({challengeType:g,mode:o,maxRetries:h,suggestion:`Try manual mode or adjust the external solver configuration.`}).build()}async function bt(e,t){let n=await t.getActivePage();if(!n)return A.fail(`No active page.`).build();let r=at(e.mode??e.provider??process.env.CAPTCHA_PROVIDER),i=dt(e),a=S(e,`apiKey`,``)||process.env.CAPTCHA_API_KEY||``,o=Math.min(Math.max(E(e,`timeoutMs`,12e4),5e3),6e5),s=gt(e),c=ct(e.taskKind,`widget`),l=S(e,`siteKey`),u=S(e,`pageUrl`,``)||n.url();if(r===`hook`){if(!l)return A.fail(`Widget solving requires an explicit siteKey.`).build();let t=Math.min(o,3e4),r=S(e,`callbackName`,``).trim();if(!r)return A.fail(`Hook mode requires an explicit callbackName.`).build();let i=await n.evaluate((e,t)=>new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`Hook timeout`)),e),a=window[t];if(typeof a==`function`){let e=a;window[t]=t=>(clearTimeout(i),n(t),e(t))}else clearTimeout(i),r(Error(`The requested callbackName is not a callable function.`))}),t,r).catch(()=>null);if(i)return A.ok().build({token:i,method:`hook`,challengeType:`widget`,siteKey:l,callbackName:r})}if(r===`manual`)return A.ok().build({mode:`manual`,challengeType:`widget`,siteKey:l||null,pageUrl:u,instruction:`Please complete the widget challenge manually.`});if(!l)return A.fail(`Widget solving requires an explicit siteKey.`).build();if(!a)return A.fail(`External solver credentials are required.`).build();try{let e=i===`2captcha`?await vt(a,{taskKind:c,siteKey:l,pageUrl:u},o):i===`anticaptcha`||i===`capsolver`?await Z(i,a,{taskKind:c,siteKey:l,pageUrl:u},o):(()=>{throw Error(`Unsupported external solver service.`)})();return s.enabled&&e.token&&await _t(n,e.token,{responseSelector:s.responseSelector,callbackName:s.callbackName}),A.ok().build({token:e.token,challengeType:e.challengeType,siteKey:l,mode:e.mode,durationMs:e.durationMs,taskKind:c,injected:s.enabled,responseSelector:s.responseSelector??null,callbackName:s.callbackName??null})}catch(e){return A.fail(e).merge({siteKey:l,mode:r,suggestion:`Try manual mode or hook mode.`}).build()}}function Q(){return(process.env.CAPTCHA_PROVIDER||``).trim().toLowerCase()||`manual`}function xt(){return process.env.CAPTCHA_SOLVER_BASE_URL?.trim()||process.env.CAPTCHA_2CAPTCHA_BASE_URL?.trim()||``}function St(e){return e===`2captcha`?xt():e===`anticaptcha`?process.env.CAPTCHA_ANTICAPTCHA_BASE_URL?.trim()||``:process.env.CAPTCHA_CAPSOLVER_BASE_URL?.trim()||``}function Ct(){let e=Q(),t=St(`2captcha`),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}:{}}}}function $(e){let t=Q(),n=St(e),r=!!process.env.CAPTCHA_API_KEY?.trim(),i=r&&n.length>0;return{capability:`captcha_external_service_${e}`,status:i?`available`:`unavailable`,reason:i?void 0:`${e} requires CAPTCHA_API_KEY and a reachable API base URL.`,fix:i?void 0:`Set CAPTCHA_API_KEY and ${e===`anticaptcha`?`CAPTCHA_ANTICAPTCHA_BASE_URL`:`CAPTCHA_CAPSOLVER_BASE_URL`}.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:t,defaultExternalProviderSupported:t===e,apiKeyConfigured:r,baseUrlConfigured:n.length>0,baseUrl:n}}}async function wt(e){let t;try{t=await e.getActivePage()}catch(e){return{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`Current page availability check 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}}}return t?{capability:`captcha_widget_hook_current_page`,status:`available`,reason:`Hook mode is available when the caller provides an explicit callbackName.`,details:{tools:[`widget_challenge_solve`],pageAttached:!0,requiresExplicitCallbackName:!0,requiresExplicitSiteKey:!0}}:{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}}}async function Tt(e){let t=Q(),n=await wt(e);return A.raw(oe(`captcha_solver_capabilities`,[{capability:`captcha_manual`,status:`available`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`]}},Ct(),$(`anticaptcha`),$(`capsolver`),n],{configuredProvider:t}))}function Et(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 Dt(e,t){return k(async()=>{let n=Et(t);if(S(t,`mode`,`launch`)===`connect`){let r=S(t,`wsEndpoint`);if(!r)throw Error(`wsEndpoint is required for connect mode.`);let i=new g(n);return await i.connectToServer(r),e.setCamoufoxManager(i),e.setActiveDriver(`camoufox`),e.clearCamoufoxPage(),{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(),{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`}})}async function Ot(e,t){return k(async()=>{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),{driver:`camoufox`,url:a.url(),title:await a.title()}})}const kt=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 At=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;getCurrentSessionId;sessionCoordinator;onBrowserAttachStateChanged;codegenStopListening;codegenSteps=[];constructor(e,t,n,r,i,a,o,s){this.collector=e,this.pageController=t,this.scriptManager=n,this.consoleMonitor=r,this.eventBus=i,this.getCurrentSessionId=a,this.sessionCoordinator=o,this.onBrowserAttachStateChanged=s;let c=b(y().paths.captchaScreenshotDir,`screenshots/captcha`);this.captchaDetector=new m(c),this.detailedDataManager=d.getInstance();let l=Ze({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},getTabRegistry:()=>this.getCurrentTabRegistry(),onBrowserAttachStateChanged:this.onBrowserAttachStateChanged});this.browserControl=l.browserControl,this.targetControl=l.targetControl,this.camoufoxBrowser=l.camoufoxBrowser,this.pageNavigation=l.pageNavigation,this.pageInteraction=l.pageInteraction,this.pageEvaluation=l.pageEvaluation,this.targetEvaluation=l.targetEvaluation,this.pageData=l.pageData,this.consoleHandlers=l.consoleHandlers,this.scriptManagement=l.scriptManagement,this.captchaHandlers=l.captchaHandlers,this.stealthInjection=l.stealthInjection,this.frameworkState=l.frameworkState,this.indexedDBDump=l.indexedDBDump,this.jsHeapSearch=l.jsHeapSearch,this.tabWorkflow=l.tabWorkflow,this.detailedData=l.detailedData,this.jsdomHandlers=l.jsdomHandlers,this.tabRegistry=l.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}getCurrentTabRegistry(){let e=this.getCurrentSessionId?.()??null;return this.sessionCoordinator?.getTabRegistry(e)??this.tabRegistry}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.getCurrentTabRegistry()}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||kt.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 Dt({setCamoufoxManager:e=>{this.camoufoxManager=e},setActiveDriver:e=>{this.activeDriver=e},clearCamoufoxPage:()=>{this.camoufoxPage=null}},e)}async handleCamoufoxNavigate(e){return Ot({getCamoufoxPage:()=>this.getCamoufoxPage(),setConsoleMonitorPage:e=>{this.consoleMonitor.setPlaywrightPage(e)}},e)}async handleHumanMouse(e){return nt(e,this.collector,this.pageController)}async handleHumanScroll(e){return rt(e,this.collector)}async handleHumanTyping(e){return it(e,this.collector,this.pageController)}async handleCaptchaVisionSolve(e){return yt(e,this.collector)}async handleWidgetChallengeSolve(e){return bt(e,this.collector)}async handleCaptchaSolverCapabilities(){return Tt(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{At as BrowserToolHandlers};
@@ -1 +0,0 @@
1
- import{ConsoleMonitor as e}from"./ConsoleMonitor-CxDJV15E.mjs";import"./PageController-Dfsm1_o7.mjs";import{n as t}from"./DOMInspector-C19J4zeq.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),D=t(`SYMBOLIC_EXEC_MAX_PATHS`,100),O=t(`SYMBOLIC_EXEC_MAX_DEPTH`,50),k=t(`SYMBOLIC_EXEC_TIMEOUT_MS`,3e4),A=t(`JSVMP_DEOBFUSCATE_TIMEOUT_MS`,3e4),j=t(`JSVMP_MAX_ITERATIONS`,100),M=t(`JSVMP_SYMBOLIC_MAX_STEPS`,1e3),N=t(`JSVMP_SYMBOLIC_TIMEOUT_MS`,3e4),P=t(`DEBUGGER_WAIT_FOR_PAUSED_TIMEOUT_MS`,3e4),F=t(`WATCH_EVAL_TIMEOUT_MS`,5e3),I=t(`TRANSFORM_WORKER_TIMEOUT_MS`,15e3);t(`TRANSFORM_VM_SCRIPT_TIMEOUT_MS`,5e3);const L=t(`TRANSFORM_CRYPTO_POOL_MAX_WORKERS`,4),R=t(`TRANSFORM_CRYPTO_POOL_IDLE_TIMEOUT_MS`,3e4),z=t(`TRANSFORM_CRYPTO_POOL_MAX_OLD_GEN_MB`,64),B=t(`TRANSFORM_CRYPTO_POOL_MAX_YOUNG_GEN_MB`,16);t(`EMULATOR_FETCH_GOTO_TIMEOUT_MS`,3e4);const V=t(`WASM_TOOL_TIMEOUT_MS`,6e4);t(`WASM_OFFLINE_RUN_TIMEOUT_MS`,1e4);const H=t(`WASM_OPTIMIZE_TIMEOUT_MS`,12e4);t(`MINIAPP_UNPACK_TIMEOUT_MS`,18e4);const U=t(`CAPTCHA_SUBMIT_TIMEOUT_MS`,15e3);t(`FETCH_ABORT_TIMEOUT_MS`,1e4);const W=t(`CAPTCHA_POLL_INTERVAL_MS`,5e3),G=t(`CAPTCHA_RESULT_TIMEOUT_MS`,1e4),K=t(`CAPTCHA_DEFAULT_TIMEOUT_MS`,18e4),q=t(`CAPTCHA_MIN_TIMEOUT_MS`,5e3),J=t(`CAPTCHA_MAX_TIMEOUT_MS`,6e5),Y=t(`CAPTCHA_MAX_RETRIES`,5),X=t(`CAPTCHA_DEFAULT_RETRIES`,2);t(`NETWORK_REPLAY_TIMEOUT_MS`,3e4),t(`NETWORK_REPLAY_MAX_BODY_BYTES`,512e3);const Z=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 ne=t(`WORKFLOW_JS_BUNDLE_MAX_SIZE_BYTES`,20*1024*1024),re=t(`WORKFLOW_JS_BUNDLE_MAX_REDIRECTS`,5),ie=t(`WORKFLOW_JS_BUNDLE_FETCH_TIMEOUT_MS`,3e4),ae=t(`WORKFLOW_BUNDLE_CACHE_TTL_MS`,300*1e3),oe=t(`WORKFLOW_BUNDLE_CACHE_MAX_BYTES`,100*1024*1024);new Set(te(`SEARCH_WORKFLOW_BOOST_TIERS`,[`workflow`,`full`]));const se=n(`SEARCH_WORKFLOW_DOMAIN_BOOST_MULTIPLIER`,2.4),ce=t(`ACTIVATION_TTL_MINUTES`,30);r(`SEARCH_AUTO_ACTIVATE_DOMAINS`,!0);const le=t(`AUTOPRUNE_AUTO_INACTIVITY_MS`,15*6e4),ue=t(`AUTOPRUNE_MANUAL_INACTIVITY_MS`,30*6e4),de=t(`AUTOPRUNE_CHECK_INTERVAL_MS`,6e4),fe=t(`PREDICTIVE_MAX_HISTORY`,100),pe=n(`PREDICTIVE_CONFIDENCE_THRESHOLD`,.25),me=n(`PREDICTIVE_DECAY_FACTOR`,.95),he=t(`ACTIVATION_COOLDOWN_MS`,3e4),ge=t(`ACTIVATION_COMPOUND_EVAL_EVERY`,5),_e=t(`ACTIVATION_EVENT_HISTORY_MAX`,200),ve=t(`ACTIVATION_BOOST_WINDOW_MS`,6e4),ye=t(`COMPOUND_EVENT_WINDOW_MS`,12e4),be=t(`COMPOUND_LONG_WINDOW_MS`,3e5),xe=n(`SEARCH_AFFINITY_BOOST_FACTOR`,.38),Se=t(`SEARCH_AFFINITY_TOP_N`,9),Ce=t(`SEARCH_DOMAIN_HUB_THRESHOLD`,5),we=t(`SEARCH_QUERY_CACHE_CAPACITY`,500),Te=n(`SEARCH_CACHE_VECTOR_WEIGHT_TOLERANCE`,.05),Ee=n(`SEARCH_TRIGRAM_WEIGHT`,.02),De=n(`SEARCH_TRIGRAM_THRESHOLD`,.47),Oe=t(`SEARCH_RRF_K`,18),ke=n(`SEARCH_RRF_RESCALE_FACTOR`,2100),Ae=n(`SEARCH_RRF_BM25_BLEND`,.39),je=t(`SEARCH_SYNONYM_EXPANSION_LIMIT`,2),Me=n(`SEARCH_PARAM_TOKEN_WEIGHT`,1.1),Ne=n(`SEARCH_SCENE_KEYWORD_WEIGHT`,.8),Pe=n(`SEARCH_BM25_K1`,1),Fe=n(`SEARCH_BM25_B`,.75),Ie=r(`SEARCH_VECTOR_ENABLED`,!0),Le=i(`SEARCH_VECTOR_MODEL_ID`,`Xenova/bge-micro-v2`),Re=n(`SEARCH_VECTOR_COSINE_WEIGHT`,.53),ze=r(`SEARCH_VECTOR_DYNAMIC_WEIGHT`,!0),Be=n(`SEARCH_VECTOR_LEARN_UP`,.13),Ve=n(`SEARCH_VECTOR_LEARN_DOWN`,.02),He=t(`SEARCH_VECTOR_LEARN_TOP_N`,3),Ue=n(`SEARCH_VECTOR_BM25_SKIP_THRESHOLD`,8),We=n(`SEARCH_TIER_PENALTY`,.35),Ge=n(`SEARCH_TIER_PENALTY_SEARCH`,.4),Ke=n(`SEARCH_TIER_PENALTY_WORKFLOW`,.6),qe=n(`SEARCH_TIER_PENALTY_FULL`,.6),Je=t(`SEARCH_RECENCY_WINDOW_MS`,30*6e4),Ye=n(`SEARCH_RECENCY_MAX_BOOST`,.1),Xe=t(`SEARCH_RECENCY_TRACKER_MAX`,200),Ze=n(`SEARCH_EXACT_NAME_MATCH_MULTIPLIER`,3.2),Qe=n(`SEARCH_DOMAIN_HUB_BOOST_MULTIPLIER`,1.04),$e=n(`SEARCH_AFFINITY_BASE_WEIGHT`,.5),et=n(`SEARCH_COVERAGE_PRECISION_FACTOR`,.94),tt=n(`SEARCH_PREFIX_MATCH_MULTIPLIER`,.84),nt=r(`SEARCH_SELF_RAG_ENABLED`,!0),rt=n(`RERANK_MAINTENANCE_PENALTY`,.43),it=n(`RERANK_STATELESS_INTERACTIVE_PENALTY`,.65),at=n(`RERANK_STATELESS_CORE_PENALTY`,.15),ot=n(`RERANK_STATELESS_COMPUTE_BOOST`,2.2),st=n(`RERANK_STATELESS_SPECIFIC_TOOL_BOOST`,2.25),ct=n(`RERANK_BROWSER_LAUNCH_BOOST`,1.35),lt=n(`RERANK_BROWSER_ATTACH_BOOST`,1.55),ut=n(`RERANK_NETWORK_MONITOR_BOOST`,1.6),dt=n(`RERANK_NETWORK_GET_REQUESTS_BOOST`,1.55),ft=t(`PREDICTIVE_MAX_SECOND_ORDER_KEYS`,1e3),pt=t(`EXTENSION_GIT_CLONE_TIMEOUT_MS`,6e4),mt=t(`EXTENSION_GIT_CHECKOUT_TIMEOUT_MS`,3e4),ht=t(`PROCESS_LIST_MAX_BUFFER_BYTES`,1024*1024*10),gt=t(`EXTERNAL_TOOL_MAX_STDOUT_BYTES`,10*1024*1024),_t=t(`EXTERNAL_TOOL_MAX_STDERR_BYTES`,1*1024*1024),vt=t(`GRAPHQL_MAX_PREVIEW_CHARS`,4e3),yt=t(`GRAPHQL_MAX_SCHEMA_CHARS`,12e4),bt=t(`GRAPHQL_MAX_QUERY_CHARS`,12e3),xt=t(`GRAPHQL_MAX_GRAPH_NODES`,2e3),St=t(`GRAPHQL_MAX_GRAPH_EDGES`,5e3),Ct=t(`ANALYSIS_MAX_SUMMARY_FILES`,40),wt=t(`ANALYSIS_MAX_SAFE_COLLECTED_BYTES`,256*1024),Tt=t(`ANALYSIS_MAX_SAFE_RESPONSE_BYTES`,220*1024),Et=t(`WS_PAYLOAD_PREVIEW_LIMIT`,200),Dt=t(`WS_PAYLOAD_SAMPLE_LIMIT`,2e3),Ot=t(`SCRIPTS_MAX_CAP`,500),$=t(`WORKER_POOL_MIN_WORKERS`,2),kt=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))}),At=t(`WORKER_POOL_IDLE_TIMEOUT_MS`,3e4),jt=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 Mt=t(`CACHE_GLOBAL_MAX_SIZE_BYTES`,500*1024*1024),Nt=n(`CACHE_LOW_HIT_RATE_THRESHOLD`,.3),Pt=t(`TOKEN_BUDGET_MAX_TOKENS`,2e5),Ft=t(`DETAILED_DATA_DEFAULT_TTL_MS`,1800*1e3),It=t(`DETAILED_DATA_MAX_TTL_MS`,3600*1e3),Lt=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 Rt=t(`MEMORY_READ_TIMEOUT_MS`,1e4),zt=t(`MEMORY_MAX_READ_BYTES`,16*1024*1024),Bt=t(`MEMORY_WRITE_TIMEOUT_MS`,1e4),Vt=t(`MEMORY_MAX_WRITE_BYTES`,16*1024),Ht=t(`MEMORY_DUMP_TIMEOUT_MS`,6e4),Ut=t(`MEMORY_SCAN_TIMEOUT_MS`,12e4),Wt=t(`MEMORY_SCAN_MAX_BUFFER_BYTES`,1024*1024*50),Gt=t(`MEMORY_SCAN_MAX_RESULTS`,1e4);t(`MEMORY_SCAN_MAX_REGIONS`,5e4),t(`MEMORY_SCAN_REGION_MAX_BYTES`,16777216);const Kt=t(`MEMORY_INJECT_TIMEOUT_MS`,3e4),qt=r(`ENABLE_INJECTION_TOOLS`,!0);t(`MEMORY_MONITOR_INTERVAL_MS`,1e3);const Jt=t(`MEMORY_VMMAP_TIMEOUT_MS`,15e3),Yt=t(`MEMORY_PROTECTION_QUERY_TIMEOUT_MS`,15e3),Xt=t(`MEMORY_PROTECTION_PWSH_TIMEOUT_MS`,3e4),Zt=t(`NATIVE_ADMIN_CHECK_TIMEOUT_MS`,5e3);t(`NATIVE_SCAN_MAX_RESULTS`,1e4);const Qt=t(`PROCESS_LAUNCH_WAIT_MS`,2e3),$t=t(`WIN_DEBUG_PORT_POLL_ATTEMPTS`,20),en=t(`WIN_DEBUG_PORT_POLL_INTERVAL_MS`,500);t(`PACKER_SANDBOX_TIMEOUT_MS`,3e3);const tn=t(`CODE_CAVE_MIN_SIZE`,16),nn=t(`BREAKPOINT_HIT_TIMEOUT_MS`,1e4),rn=t(`BREAKPOINT_TRACE_MAX_HITS`,100),an=t(`HEAP_ENUMERATE_MAX_BLOCKS`,1e4),on=t(`HEAP_SPRAY_THRESHOLD`,50),sn=t(`HEAP_SPRAY_SIZE_TOLERANCE`,64),cn=t(`HEAP_SUSPICIOUS_BLOCK_SIZE`,10485760),ln=t(`FREEZE_DEFAULT_INTERVAL_MS`,100),un=t(`WRITE_HISTORY_MAX`,200),dn=t(`SCAN_MAX_RESULTS_PER_SCAN`,1e5),fn=t(`SCAN_DISPLAY_RESULTS_LIMIT`,200),pn=t(`SCAN_UNKNOWN_INITIAL_MAX_ADDRESSES`,5e5),mn=t(`SCAN_POINTER_MAX_RESULTS`,5e3),hn=t(`SCAN_GROUP_MAX_PATTERN_SIZE`,256),gn=t(`SCAN_SESSION_MAX_COUNT`,20),_n=t(`SCAN_SESSION_TTL_MS`,18e5),vn=t(`POINTER_CHAIN_MAX_DEPTH`,6),yn=t(`POINTER_CHAIN_MAX_OFFSET`,4096),bn=t(`POINTER_CHAIN_MAX_RESULTS`,500),xn=t(`POINTER_CHAIN_SCAN_CHUNK_SIZE`,16777216),Sn=t(`STRUCT_ANALYZE_DEFAULT_SIZE`,256),Cn=t(`STRUCT_VTABLE_MAX_FUNCTIONS`,64),wn=t(`STRUCT_RTTI_MAX_STRING_LEN`,256);t(`STRUCT_CSTRING_MAX_LEN`,256);const Tn=t(`FRIDA_TIMEOUT_MS`,15e3),En=t(`GHIDRA_TIMEOUT_MS`,12e4),Dn=t(`UNIDBG_TIMEOUT_MS`,6e4);t(`ADB_DEFAULT_TIMEOUT_MS`,3e4),t(`ADB_SHELL_TIMEOUT_MS`,6e4),t(`ADB_WEBVIEW_HTTP_TIMEOUT_MS`,5e3),t(`ADB_WEBVIEW_WS_TIMEOUT_MS`,1e4);const On=t(`MOJO_MONITOR_TIMEOUT_MS`,1e4),kn=t(`MEMORY_AVAILABILITY_CACHE_TTL_MS`,45e3),An=t(`HTTP_RATE_LIMIT_MAX_IPS`,1e4),jn=t(`HTTP_CLEANUP_INTERVAL_MS`,5*6e4);t(`SSE_HEARTBEAT_MS`,3e4);const Mn=r(`MCP_COMPACT_SCHEMA`,!0),Nn=t(`SANDBOX_MAX_TIMEOUT_MS`,3e4);t(`NATIVE_BRIDGE_TIMEOUT_MS`,15e3),t(`SOURCEMAP_EXT_TIMEOUT_MS`,15e3);const Pn=t(`V8_BYTECODE_SUBPROC_TIMEOUT_MS`,6e4),Fn=t(`SYSCALL_TRACE_DURATION_DEFAULT_SEC`,10),In=t(`SYSCALL_TRACE_DURATION_MIN_SEC`,1),Ln=t(`SYSCALL_TRACE_DURATION_MAX_SEC`,300),Rn=t(`SOURCEMAP_V4_RAW_FIELD_MAX_LEN`,200),zn=t(`SOURCEMAP_V4_RETRY_DELAY_MS`,250),Bn=t(`WASM_DEAD_CODE_MIN_MATCHES`,10),Vn=t(`WASM_BITWISE_OPS_THRESHOLD`,20),Hn=t(`WASM_VM_DISPATCH_MIN_LOOPS`,3),Un=t(`PROTO_TLS_MIN_RECORD_LEN`,4),Wn=n(`PROTO_TLS_CONFIDENCE`,.95),Gn=n(`PROTO_WS_CONFIDENCE`,.85),Kn=n(`PROTO_HTTP_CONFIDENCE`,.95),qn=n(`PROTO_SSH_CONFIDENCE`,.95),Jn=t(`BOT_DETECT_LIMIT_DEFAULT`,50);t(`BOT_DETECT_LIMIT_MIN`,1),t(`BOT_DETECT_LIMIT_MAX`,500);const Yn=t(`WEBHOOK_PROCESS_TIMEOUT_MS`,1e4);t(`ORCHESTRATOR_STEP_TIMEOUT_MS`,1e4);const Xn=t(`MACRO_DEFAULT_TIMEOUT_MS`,12e4),Zn=t(`MACRO_BUILTIN_TIMEOUT_MS`,6e4),Qn=t(`PAGE_FRAME_SELECTOR_TIMEOUT_MS`,1e4),$n=t(`PAGE_NETWORK_IDLE_TIMEOUT_MS`,3e4),er=t(`DOM_QUERY_DEFAULT_LIMIT`,50),tr=t(`DOM_WAIT_ELEMENT_TIMEOUT_MS`,3e4);t(`BROWSER_POOL_IDLE_TIMEOUT_MS`,3e5),t(`BROWSER_POOL_MAX_TABS`,10);const nr=t(`ICMP_PROBE_TIMEOUT_MS`,5e3),rr=t(`ICMP_TRACEROUTE_MAX_HOPS`,30),ir=t(`ICMP_DEFAULT_PACKET_SIZE`,32);t(`ADB_VERSION_CHECK_TIMEOUT_MS`,5e3);const ar=t(`COORDINATION_GOTO_TIMEOUT_MS`,3e4),or=t(`MEMORY_AUDIT_TRAIL_CAPACITY`,5e3),sr=t(`MEMORY_PROCESS_SIGNAL_TIMEOUT_MS`,2e3),cr=t(`MEMORY_PROBE_CMD_TIMEOUT_MS`,5e3),lr=t(`MEMORY_VMMAP_ENUM_TIMEOUT_MS`,15e3),ur=t(`MEMORY_MODULES_TIMEOUT_MS`,3e4),dr=r(`MCP_LOG_ENABLED`,!1),fr=i(`MCP_LOG_LEVEL`,`info`),pr=i(`MCP_LOG_FILE_DIR`,``),mr=t(`DART_MIN_LENGTH`,4);t(`DART_MIN_LENGTH_FLOOR`,2),t(`DART_MIN_LENGTH_CEILING`,64);const hr=t(`DART_MAX_CHUNK_BYTES`,16*1024*1024),gr=t(`DART_CHUNK_OVERLAP_BYTES`,128),_r=t(`DART_PRINTABLE_ASCII_MIN`,32),vr=t(`DART_PRINTABLE_ASCII_MAX`,126),yr=i(`DART_DEFAULT_ENCODING`,`both`),br=t(`DART_MAX_OFFSETS_PER_STRING`,1e3),xr=t(`DART_MAX_REGEX_PATTERN_LENGTH`,256),Sr=t(`DART_REGEX_TIMEOUT_MS`,50),Cr=i(`DART_ALLOWED_REGEX_FLAGS`,`iu`);t(`DART_MAX_EXTRACT_DURATION_MS`,3e4),t(`DART_MAX_RESULT_BYTES`,16*1024*1024);const wr=t(`DART_MAX_SMI_VALUE`,1e6),Tr=t(`DART_MAX_MAP_BYTES`,16*1024*1024),Er=t(`DART_MAX_PACKAGES_PER_RESULT`,1e3),Dr=t(`DART_MAX_FILES_PER_PACKAGE`,50),Or=t(`DART_SNAPSHOT_MAX_FILE_BYTES`,1024*1024*1024),kr=t(`DART_SNAPSHOT_HEADER_SCAN_MAX_BYTES`,32*1024*1024),Ar=i(`DART_SNAPSHOT_TABLE_PATH`,``),jr=t(`DART_PP_MAX_SLOTS`,4096),Mr=t(`DART_PP_PREVIEW_BYTES`,64),Nr=t(`DART_PP_MAX_DUMP_DURATION_MS`,1e4);export{Ft as $,pn as $n,L as $r,cr as $t,Cr as A,Gn as An,Re as Ar,rr as At,mr as B,l as Bn,zn as Br,g as Bt,G as C,Et as Ci,ft as Cn,We as Cr,sn as Ct,ye as D,qn as Dn,De as Dr,An as Dt,tn as E,Kn as En,Ke as Er,jn as Et,Tr as F,ut as Fn,Be as Fr,N as Ft,_r as G,T as Gn,D as Gr,fr as Gt,jr as H,C as Hn,wn as Hr,h as Ht,br as I,ot as In,Le as Ir,Zn as It,Or as J,hn as Jn,Ln as Jr,Ht as Jt,Sr as K,E as Kn,k as Kr,or as Kt,Er as L,at as Ln,se as Lr,Xn as Lt,yr as M,ct as Mn,Ie as Mr,A as Mt,hr as N,rt as Nn,Ve as Nr,j as Nt,be as O,Wn as On,Ee as Or,ir as Ot,Dr as P,dt as Pn,He as Pr,M as Pt,d as Q,_n as Qn,z as Qr,ur as Qt,xr as R,it as Rn,s as Rr,Mn as Rt,W as S,un as Si,fe as Sn,je as Sr,an as St,U as T,ht as Tn,Ge as Tr,cn as Tt,Mr as U,Nn as Un,Cn as Ur,dr as Ut,Nr as V,c as Vn,Sn as Vr,_ as Vt,vr as W,w as Wn,O as Wr,pr as Wt,P as X,mn as Xn,Pt as Xr,zt as Xt,Ar as Y,dn as Yn,In as Yr,Kt as Yt,u as Z,gn as Zn,R as Zr,Vt as Zt,X as _,oe as _i,yn as _n,Ae as _r,St as _t,ce as a,Bn as ai,Gt as an,Pe as ar,mt as at,J as b,re as bi,pe as bn,Ne as br,bt,Ct as c,Hn as ci,Jt as cn,Qe as cr,_t as ct,ue as d,$t as di,Zt as dn,Me as dr,b as dt,B as ei,sr as en,Ot as er,It as et,Jn as f,en as fi,Q as fn,tt as fr,y as ft,Nt as g,$ as gi,vn as gn,Je as gr,En as gt,Mt as h,kt as hi,$n as hn,Xe as hr,f as ht,_e as i,Vn as ii,Wt as in,Fe as ir,qt as it,gr as j,lt as jn,ze as jr,p as jt,ar as k,Un as kn,Ue as kr,nr as kt,le as l,F as li,Bt as ln,Ce as lr,gt as lt,rn as m,jt as mi,Qn as mn,Ye as mr,Tn as mt,ge as n,Dn as ni,Yt as nn,xe as nr,er as nt,wt as o,H as oi,Ut as on,Te as or,pt as ot,nn as p,At as pi,Z as pn,we as pr,ln as pt,kr as q,fn as qn,Fn as qr,kn as qt,he as r,Pn as ri,Rt as rn,Se as rr,tr as rt,Tt as s,V as si,lr as sn,et as sr,S as st,ve as t,I as ti,Xt as tn,$e as tr,Lt as tt,de as u,Yn as ui,On as un,Ze as ur,x as ut,K as v,ae as vi,bn as vn,Oe as vr,xt as vt,m as w,Dt as wi,Qt as wn,qe as wr,on as wt,q as x,ne as xi,me as xn,nt as xr,yt as xt,Y as y,ie as yi,xn as yn,ke as yr,vt as yt,wr as z,st as zn,Rn as zr,v as zt};
@@ -1 +0,0 @@
1
- import{k as e}from"./constants-BYj8Xek8.mjs";import"./definitions-DAQm1Xar.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};
Binary file
@@ -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-Bw413PlW.mjs";import"./definitions-bybDvnG0.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-qif8M9-K.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-qif8M9-K.mjs";const t=[e(`binary_key_extract`,e=>e.desc(`Scan a binary for hardcoded key candidates (raw high-entropy, Base64, hex). Read-only — no decryption.`).string(`filePath`,`Absolute path to the binary file to scan`).array(`keyLengths`,{type:`integer`,minimum:1,maximum:4096},`Decoded byte lengths to accept (default: [16, 24, 32, 64])`).number(`minEntropy`,`Inclusive minimum Shannon entropy for raw windows (0..8)`,{minimum:0,maximum:8}).array(`formats`,{type:`string`,enum:[`raw`,`base64`,`hex`]},`Which candidate formats to emit (default: all three)`).boolean(`includeContext`,`Attach a hex+ASCII context window to each candidate`,{default:!0}).integer(`contextBytes`,`Context window size on each side, in bytes (0..1024)`,{minimum:0,maximum:1024,default:16}).integer(`maxResults`,"Cap on returned candidates; excess sets `truncated:true`",{minimum:1}).integer(`maxChunkBytes`,`Streaming chunk size in bytes`).object(`scanWindow`,{start:{type:`integer`,minimum:0,description:`Inclusive start byte offset`},end:{type:`integer`,minimum:1,description:`Exclusive end byte offset`}},`Restrict scanning to a byte range (skip ELF headers, focus on a section, etc.)`).required(`filePath`).query())];export{t};
@@ -1 +0,0 @@
1
- import{c as e}from"./PageController-Dfsm1_o7.mjs";import{t}from"./tool-builder-qif8M9-K.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`],`Challenge type`,{default:`image`}).string(`typeHint`,`Legacy alias for challengeType`).enum(`taskKind`,[`image`,`recaptcha_v2`,`recaptcha_v3`,`hcaptcha`,`funcaptcha`,`turnstile`],`Explicit solver task kind`).string(`siteKey`,`Widget site key`).string(`pageUrl`,`Page URL`).string(`imageBase64`,`Explicit base64 image payload`).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}).string(`responseSelector`,`Explicit selector to receive the solved token`).string(`callbackName`,`Explicit global callback name for hook or injection flows`).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};
@@ -1 +0,0 @@
1
- import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`jadx_search_code`,e=>e.desc(`Read-only ripgrep-backed search over an existing jadx decompile directory. ReDoS-guarded; Node fallback.`).string(`decompileDir`,`Absolute path to an existing jadx decompile output directory. The tool does not decompile — run jadx via the binary-instrument domain first.`).string(`query`,"Search query (regex unless `literal:true`)").boolean(`literal`,"Treat `query` as a literal string, not a regex",{default:!1}).boolean(`caseInsensitive`,`Case-insensitive matching`,{default:!1}).integer(`contextLines`,`Lines of context around each match`,{default:2,minimum:0,maximum:20}).integer(`maxMatchesPerFile`,`Cap on matches recorded per file`,{minimum:1}).integer(`maxResults`,`Hard ceiling on total matches across all files`,{minimum:1}).array(`globs`,{type:`string`,description:`Glob pattern (negative globs may start with !)`},"File globs applied during enumeration. Defaults to `**/*.java`, `**/*.kt`.").required(`decompileDir`,`query`).query())];export{t};
@@ -1 +0,0 @@
1
- import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`apk_packer_detect`,e=>e.desc("Detect Android APK packers by matching `lib/<abi>/lib*.so` filenames against user-supplied customSignatures (ReDoS-guarded regex compilation). The framework ships no built-in signature table — callers provide their own. **Does not unpack, execute, or otherwise interact with the packed payload.**").string(`apkPath`,`Absolute path to the .apk (or .aab) file to inspect`).string(`dirPath`,`Optional path to a directory containing an already-unpacked APK tree`).enum(`ruleMode`,[`append`,`prepend`,`replace`],`How customSignatures interact with the default (empty) signature table`,{default:`append`}).array(`customSignatures`,{type:`object`,properties:{name:{type:`string`,description:`Display name of the fingerprint entry`},category:{type:`string`,description:`Optional free-form category label supplied by the caller`},libPatterns:{type:`array`,items:{type:`string`},description:`lib basenames or anchored regex sources (case-insensitive; ReDoS-guarded)`},confidence:{type:`string`,enum:[`high`,`medium`,`low`],description:`Optional single-hit confidence hint (default: medium)`},notes:{type:`string`,description:`Free-form notes surfaced in list-signatures`}},required:[`name`,`libPatterns`]},`Fingerprints supplied by the caller. Compile-time and runtime ReDoS guards apply.`).query()),e(`apk_packer_list_signatures`,e=>e.desc("List the in-process signature table used by `apk_packer_detect`. Empty by default; reflects caller-managed state at request time. Optionally filter by case-insensitive category substring.").string(`category`,`Optional case-insensitive category substring filter`).query()),e(`apk_signing_block_parse`,e=>e.desc(`Read-only parser for the APK Signing Block (schemes v2/v3/v3.1/v4) plus key-rotation lineage detection and residue-block / dex-prefix / magic-offset anomaly flags. Never mutates the APK.`).string(`apkPath`,`Absolute path to the .apk file to parse`).required(`apkPath`).query())];export{t};
@@ -1 +0,0 @@
1
- import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./PageController-Dfsm1_o7.mjs";import{n,t as r}from"./DOMInspector-C19J4zeq.mjs";import{t as i}from"./ScriptManager-LWGPTdvD.mjs";var a=e({ensureBrowserCore:()=>c});let o=null;async function s(){return o||=(await import(`./ConsoleMonitor-CxDJV15E.mjs`)).ConsoleMonitor,o}async function c(e){e.collector||(e.collector=new n(e.config.puppeteer),e.registerCaches()),e.pageController||=new t(e.collector),e.domInspector||=new r(e.collector),e.scriptManager||=new i(e.collector),e.consoleMonitor||=new(await(s()))(e.collector)}export{a as n,c as t};
@@ -1 +0,0 @@
1
- function e(e){if(typeof e!=`object`||!e)return null;let t=e.sessionId;return typeof t==`string`&&t.length>0?t:null}function t(e){let t=e.id?.();return typeof t==`string`&&t.length>0?t:null}async function n(t,n){let r=e(await t.send(`Target.attachToTarget`,{targetId:n,flatten:!0}));if(!r)throw Error(`Target.attachToTarget did not return sessionId for ${n}`);let i=t.connection?.();if(!i||typeof i.session!=`function`)throw Error(`CDP connection lookup unavailable for attached target ${n}`);let a=i.session(r);if(!a)throw Error(`CDP attached target session ${r} was not registered for ${n}`);return a}async function r(e,n){let r=t(n);if(!r)throw Error(`CDP attached target session id unavailable for detach`);await e.send(`Target.detachFromTarget`,{sessionId:r})}export{r as n,n as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./ToolError-DWU_z7gp.mjs";import{a as t,o as n,t as r}from"./parse-args-Bw413PlW.mjs";function i(e){return typeof e!=`object`||!e||!(`evaluate`in e)?!1:typeof e.evaluate==`function`}function a(e){return typeof e!=`object`||!e||!(`getExtension`in e)||!(`getParameter`in e)||!(`RENDERER`in e)||!(`VERSION`in e)?!1:typeof e.getExtension==`function`&&typeof e.getParameter==`function`}function o(e){let t=(e??``).toLowerCase();return t.includes(`vulkan`)?`vulkan`:t.includes(`metal`)?`metal`:t.includes(`d3d`)||t.includes(`direct3d`)?`direct3d`:t.includes(`angle`)||t.includes(`opengl`)||t.includes(`mesa`)||t.includes(`gl`)?`opengl`:t.includes(`swiftshader`)||t.includes(`software`)||t.includes(`cpu`)?`cpu`:t.length>0?`gpu`:`cpu`}function s(e){let t=0;for(let n of e)t+=1,t+=s(n.children);return t}function c(e){let t=e.getAttribute(`aria-label`);if(t)return t;if(e.id)return e.id;let n=typeof e.className==`string`?e.className.trim():``;return n.length>0?n:e.tagName.toLowerCase()}function l(e){if(typeof e.getBoundingClientRect!=`function`)return;let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function u(e){if(!(e instanceof HTMLElement)||typeof window>`u`)return;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`}function d(e,t){let n=Array.from(e.children).slice(0,12).map((e,n)=>d(e,`${t}-${n}`));return{id:e.id||t,type:e.tagName.toLowerCase(),label:c(e),children:n,visible:u(e),bounds:l(e)}}function f(){let e=[{id:`mock-root`,type:`canvas`,label:`mock-skia-surface`,visible:!0,bounds:{x:0,y:0,width:640,height:480},children:[{id:`mock-layer`,type:`layer`,label:`mock-layer`,visible:!0,bounds:{x:16,y:16,width:320,height:160},children:[]}]}];return{rootNodes:e,totalNodes:s(e),extractedAt:new Date().toISOString()}}function p(e){let t=`software`,n=`Raster`;return e.backend===`vulkan`?(t=`vulkan`,n=`Vulkan`):e.backend===`metal`?(t=`metal`,n=`Metal`):(e.backend===`opengl`||e.backend===`direct3d`||e.backend===`gpu`)&&(t=`gl`,n=`OpenGL`),{isSkiaBacked:e.backend!==`cpu`,version:e.version??null,gpuBackend:t,shaderPipeline:n,rendererStrings:e.gpu?[e.gpu]:[],features:e.backend===`cpu`?[]:[`backend:${e.backend}`],confidence:e.backend===`cpu`?.2:.8,evidence:e.gpu?[`Renderer string: ${e.gpu}`]:[`No renderer information available`]}}function m(e,t){return e.x>=t.x&&e.y>=t.y&&e.x+e.width<=t.x+t.width&&e.y+e.height<=t.y+t.height}function h(e){let t=(e??``).toLowerCase();return t.includes(`rrect`)||t.includes(`round`)?`drawRRect`:t.includes(`rect`)?`drawRect`:t.includes(`text`)?`drawText`:t.includes(`image`)||t.includes(`sprite`)?`drawImage`:t.includes(`path`)?`drawPath`:t.includes(`circle`)||t.includes(`arc`)?`drawCircle`:t.includes(`line`)?`drawLine`:`unknown`}function g(e){let t=e.layers.map((e,t)=>({id:e.id??`layer-${t}`,name:e.name??`layer-${t}`,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:e.transform??[1,0,0,0,1,0,0,0,1],opacity:e.opacity??1,visible:e.visible??!0,children:[],customData:e.customData})),n=t[0]??null;if(n)for(let e=1;e<t.length;e+=1){let r=t[e];r&&m(r.bounds,n.bounds)&&n.children.push(r)}let r=e.drawCommands.map(e=>({type:h(e.type),bounds:e.bounds??{x:0,y:0,width:0,height:0},paintInfo:e.paintInfo??{},layerId:e.layerId}));return{rootLayer:n,layers:t,drawCommands:r,totalLayers:t.length,totalDrawCommands:r.length,canvas:{id:e.canvas.id,width:e.canvas.width??0,height:e.canvas.height??0,dpr:e.canvas.dpr??1,contextType:e.canvas.contextType??`unknown`}}}function _(e){return{id:e.id,name:e.label,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:[1,0,0,0,1,0,0,0,1],opacity:1,visible:e.visible??!0,children:e.children.map(e=>_(e))}}function v(e){let t=e.rootNodes.map(e=>_(e));return{rootLayer:t[0]??null,layers:t,drawCommands:[],totalLayers:t.length,totalDrawCommands:0,canvas:{width:t[0]?.bounds.width??0,height:t[0]?.bounds.height??0,dpr:1,contextType:`mock`}}}function y(e){for(let t of e){let e=t.match(/(\d+\.\d+(?:\.\d+)?)/);if(e&&e[1])return e[1]}return null}function b(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`metal`:t.includes(`vulkan`)?`vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`software`:t.length>0?`gl`:`software`}function x(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`Metal`:t.includes(`vulkan`)?`Vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`Raster`:t.length>0?`OpenGL`:`Raster`}function S(e,t,n){let r=e.flatMap(e=>{let t=[];return e.unmaskedRenderer&&t.push(e.unmaskedRenderer),e.renderer&&t.push(e.renderer),t}),i=[],a=[];t.hasSkiaFontSignatures&&(i.push(`fontBoundingBoxAscent/Descent available`),a.push(`Canvas text metrics expose font bounding boxes`));for(let e of n.engines)i.push(`engine:${e}`),a.push(`Detected known Skia-adjacent engine: ${e}`);for(let t of e)t.hasSkiaBackend&&t.unmaskedRenderer&&a.push(`Renderer probe: ${t.unmaskedRenderer}`);let o=e.some(e=>e.hasSkiaBackend)||n.isSkiaEngine||t.hasSkiaFontSignatures,s=.1;e.some(e=>e.hasSkiaBackend)&&(s+=.5),n.isSkiaEngine&&(s+=.3),t.hasSkiaFontSignatures&&(s+=.1);let c=o?b(r):`software`,l=o?x(r):`Raster`;return{isSkiaBacked:o,version:y(r),gpuBackend:c,shaderPipeline:l,rendererStrings:r,features:i,confidence:Math.min(s,1),evidence:a}}var C=class{detectSkiaRenderer(){if(typeof document>`u`)return{backend:`cpu`,version:`mock`,gpu:`browser-context-unavailable`};let e=document.querySelector(`canvas`);if(!(e instanceof HTMLCanvasElement))return{backend:`cpu`,version:`mock`,gpu:`no-canvas-detected`};let t=e.getContext(`webgl2`)||e.getContext(`webgl`)||e.getContext(`experimental-webgl`);if(!a(t))return{backend:`cpu`,version:`mock`,gpu:`canvas-without-webgl`};let n,r=t.getExtension(`WEBGL_debug_renderer_info`);if(r){let e=t.getParameter(r.UNMASKED_RENDERER_WEBGL);typeof e==`string`&&e.trim().length>0&&(n=e)}if(!n){let e=t.getParameter(t.RENDERER);typeof e==`string`&&e.trim().length>0&&(n=e)}let i,s=t.getParameter(t.VERSION);return typeof s==`string`&&s.trim().length>0&&(i=s),{backend:o(n),version:i,gpu:n}}extractSceneTree(e){if(typeof document>`u`)return f();let t=e?document.querySelector(e):document.querySelector(`canvas`);if(!(t instanceof HTMLCanvasElement))return f();let n=d(t,`skia-root`);if(t.parentElement){let e=Array.from(t.parentElement.children).filter(e=>e!==t).slice(0,8).map((e,t)=>d(e,`skia-sibling-${t}`));n.children.push(...e)}let r=[n];return{rootNodes:r,totalNodes:s(r),extractedAt:new Date().toISOString()}}};async function w(e,t){return i(e)?S(await e.evaluate(`(() => { /* UNMASKED_RENDERER_WEBGL ${t??``} */ return []; })()`),await e.evaluate(`(() => { /* fontBoundingBoxAscent */ return { hasSkiaFontSignatures: false, textMetrics: null }; })()`),await e.evaluate(`(() => { /* window.cc window.legacyCC */ return { engines: [], isSkiaEngine: false }; })()`)):p(new C().detectSkiaRenderer())}async function T(e,t,n=!0){return i(e)?g(await e.evaluate(`(() => { /* drawCommands canvasMeta ${t??``} */ return { canvas: {}, layers: [], drawCommands: [] }; })()`)):v(new C().extractSceneTree(t))}function E(e,t){let n=[],r=new Set,i=new Set,a=O(e);for(let e of a){let a=null;for(let n of t){let t=D(e,n);t&&(!a||t.confidence>a.confidence)&&(a=t)}a&&a.confidence>=.3&&(n.push(a),r.add(a.skiaObjectId),i.add(a.jsObjectId))}let o=[...new Set(a.map(e=>e.id))].filter(e=>!r.has(e)),s=t.filter(e=>!i.has(e.objectId)).map(e=>e.objectId),c=n.reduce((e,t)=>e+t.confidence,0),l=n.length>0?c/n.length:0;return{correlations:n,unmatchedJSObjects:s,unmatchedSkiaObjects:o,summary:{totalSkiaObjects:a.length,totalJSObjects:t.length,matchedCount:n.length,averageConfidence:Math.round(l*100)/100}}}function D(e,t){if(e.text){for(let n of t.stringProps)if(n===e.text||n.includes(e.text)&&e.text.length>3)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.85,matchType:`text`,explanation:`Draw text "${e.text.slice(0,50)}" matches JS string property`}}let n=j(e.bounds,t.numericProps);if(n)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:n.confidence,matchType:`dimension`,explanation:n.explanation};if(e.color){for(let n of t.colorProps)if(P(n,e.color))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.7,matchType:`color`,explanation:`Color ${e.color} matches JS color property "${n}"`}}if(e.type===`drawImage`){let n=e.color;if(n){for(let r of t.urlProps)if(r===n||r.includes(n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.8,matchType:`url`,explanation:`Image URL matches JS property`}}}if(e.name){if(t.name&&N(e.name,t.name))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name,confidence:.75,matchType:`name`,explanation:`Object name "${e.name}" matches JS object "${t.name}"`};for(let n of t.stringProps)if(N(e.name,n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.6,matchType:`name`,explanation:`Skia layer name matches JS string property`}}let r=M(e.bounds,t.numericProps);return r?{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:r.confidence,matchType:`geometry`,explanation:r.explanation}:null}function O(e){let t=[];for(let n of e.layers)t.push({id:n.id,type:`layer`,name:n.name,bounds:n.bounds,color:n.customData?.color});for(let n of e.drawCommands){let e=k(n.paintInfo),r=A(n.paintInfo);t.push({id:`cmd_${n.type}_${n.bounds.x}_${n.bounds.y}`,type:n.type,name:`${n.type} at (${n.bounds.x}, ${n.bounds.y})`,text:e,bounds:n.bounds,color:r})}return t}function k(e){if(typeof e.text==`string`)return e.text;if(typeof e.content==`string`)return e.content}function A(e){if(typeof e.color==`string`)return e.color;if(typeof e.fillColor==`string`)return e.fillColor;if(typeof e.strokeColor==`string`)return e.strokeColor;if(typeof e.url==`string`)return e.url;if(typeof e.src==`string`)return e.src}function j(e,t){let n=[`width`,`height`,`w`,`h`,`sizeX`,`sizeY`,`sw`,`sh`],r=!1,i=!1;for(let a of n){let n=t[a];n!==void 0&&((a===`width`||a===`w`||a===`sizeX`||a===`sw`)&&Math.abs(n-e.width)<=2&&(r=!0),(a===`height`||a===`h`||a===`sizeY`||a===`sh`)&&Math.abs(n-e.height)<=2&&(i=!0))}return r&&i?{confidence:.75,explanation:`Dimensions ${e.width}x${e.height} match JS numeric properties`}:r||i?{confidence:.45,explanation:`Partial dimension match for ${e.width}x${e.height}`}:null}function M(e,t){let n=!1,r=!1;for(let[i,a]of Object.entries(t))(i===`x`||i===`posX`||i===`left`)&&Math.abs(a-e.x)<=5&&(n=!0),(i===`y`||i===`posY`||i===`top`)&&Math.abs(a-e.y)<=5&&(r=!0);return n&&r?{confidence:.5,explanation:`Position (${e.x}, ${e.y}) matches JS numeric properties`}:null}function N(e,t){return e.toLowerCase()===t.toLowerCase()||e.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(e.toLowerCase())}function P(e,t){return e.toLowerCase().replace(/\s/g,``)===t.toLowerCase().replace(/\s/g,``)}async function F(e,n){let r=t(n,`canvasId`);return{rendererInfo:await w(e,r||void 0),canvasId:r||`auto`,detectionComplete:!0}}async function I(e,n){let i=t(n,`canvasId`),a=r(n,`includeDrawCommands`,!0);return{sceneTree:await T(e,i||void 0,a),canvasId:i||`auto`,extractionComplete:!0}}async function L(r,i,a){let o=t(i,`canvasId`),s=n(i,`skiaNodeIds`),c=await T(r,o||void 0,!0);if(c.layers.length===0&&c.drawCommands.length===0)throw new e(`PREREQUISITE`,`No Skia scene data available for correlation`);let l=[];if(a)try{l=await a()}catch{l=[]}let u=c;if(s.length>0){let e=new Set(s);u={...c,layers:c.layers.filter(t=>e.has(t.id)),drawCommands:c.drawCommands.filter(t=>{let n=t.layerId;return n===void 0||e.has(n)})}}return{correlations:E(u,l),canvasId:o||`auto`,skiaNodeIds:s.length>0?s:void 0,correlationComplete:!0}}var R=class{deps;constructor(e){this.deps=e}async handleSkiaDetectRenderer(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return F(this.deps.pageController,t)}async handleSkiaExtractScene(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);let n=await I(this.deps.pageController,t),r=n?.sceneTree;return r&&this.deps.eventBus?.emit(`skia:scene_captured`,{canvasId:t.canvasId??`auto`,nodeCount:(r.layers?.length??0)+(r.drawCommands?.length??0),timestamp:new Date().toISOString()}),n}async handleSkiaCorrelateObjects(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return L(this.deps.pageController,t,this.deps.getJSObjects)}};export{R as SkiaCaptureHandlers};
@@ -1 +0,0 @@
1
- import{n as e}from"./response-C7rKQst4.mjs";import{t}from"./ToolError-DWU_z7gp.mjs";import{t as n}from"./ToolProbe-C7ZU2x7M.mjs";import{a as r,r as i,s as a,t as o}from"./parse-args-Bw413PlW.mjs";import{join as s}from"node:path";import{mkdir as c}from"node:fs/promises";import{execFile as l}from"node:child_process";function u(e){return e instanceof Error?e.message:String(e)}function d(e){return e?[`-s`,e]:[]}async function f(e,t){return new Promise((n,r)=>{l(e,t,{encoding:`utf8`,windowsHide:!0},(e,t,i)=>{e?r(e):n({stdout:t??``,stderr:i??``})})})}async function p(e,t){let{stdout:n}=await f(e,[...d(t),`shell`,`cat /proc/net/unix`]),r=[];for(let e of n.split(/\r?\n/)){let t=e.trim();if(t.includes(`@webview_devtools_remote`)){let e=t.match(/@webview_devtools_remote\S+/);e&&r.push(e[0])}}return r}function m(e){return e.trim().replace(/\/+$/,``)}function h(e,t,n){let r=new Set;for(let i of[/nativeLibraryDir=([^\s]+)/g,/legacyNativeLibraryDir=([^\s]+)/g,/secondaryNativeLibraryDir=([^\s]+)/g]){let a;for(;(a=i.exec(e))!==null;){let e=m(a[1]??``);e&&(!n&&!e.includes(t)||r.add(e))}}return[...r]}var g=class{cachedAdb;async resolveAdb(){if(this.cachedAdb)return this.cachedAdb;let e=await n(`adb`);if(!e.available)throw new t(`PREREQUISITE`,e.reason??`adb not found in PATH. Install Android Platform Tools.`,{toolName:`adb-bridge`});return this.cachedAdb=e.path??`adb`,this.cachedAdb}async run(n,r){try{return e(await r())}catch(e){throw e instanceof t?e:new t(`RUNTIME`,u(e),{toolName:n})}}async handleDeviceList(e){return this.run(`adb_device_list`,async()=>{let{stdout:e}=await f(await this.resolveAdb(),[`devices`,`-l`]),t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`List of devices`))continue;let r=e.split(/\s+/),i=r[0];if(!i)continue;let a={};for(let e=2;e<r.length;e++){let t=r[e];if(!t)continue;let n=t.indexOf(`:`);if(n>0){let e=t.slice(0,n),r=t.slice(n+1);e&&r&&(a[e]=r)}}t.push({serial:i,state:r[1]??``,model:a.model??``,product:a.product??``})}return{success:!0,count:t.length,devices:t}})}async handleShell(e){return this.run(`adb_shell`,async()=>{let t=a(e,`serial`),n=a(e,`command`),{stdout:r,stderr:i}=await f(await this.resolveAdb(),[...d(t),`shell`,n]);return{success:!0,serial:t,command:n,stdout:r,stderr:i||``}})}async handleApkPull(e){return this.run(`adb_apk_pull`,async()=>{let t=a(e,`serial`),n=r(e,`packageName`),i=r(e,`outputPath`)??`.`;if(!n)return{success:!1,error:`packageName is required`};let o=await this.resolveAdb(),{stdout:c}=await f(o,[...d(t),`shell`,`pm path ${n}`]),l=c.match(/package:([\w./]+)/)?.[1];if(!l)return{success:!1,error:`APK not found for ${n}`,raw:c};let u=s(i,`${n}.apk`).replace(/\\/g,`/`);return await f(o,[...d(t),`pull`,l,u]),{success:!0,serial:t,packageName:n,remotePath:l,localPath:u}})}async handleAnalyzeApk(e){return this.run(`adb_apk_analyze`,async()=>{let t=a(e,`serial`),n=a(e,`packageName`),{stdout:r}=await f(await this.resolveAdb(),[...d(t),`shell`,`dumpsys package ${n}`]),i={packageName:n},o=r.match(/versionName=([^\s]+)/);o?.[1]&&(i.versionName=o[1]);let s=r.match(/versionCode=(\d+)/);s?.[1]&&(i.versionCode=s[1]);let c=r.match(/minSdk=(\d+)/);c?.[1]&&(i.minSdk=c[1]);let l=r.match(/targetSdk=(\d+)/);l?.[1]&&(i.targetSdk=l[1]);let u=[],p=[],m=[],h=[],g=``;for(let e of r.split(/\r?\n/)){if(e.includes(`requested permissions:`)||e.includes(`install permissions:`)){g=`permissions`;continue}if(e.includes(`Activity Resolver Table`)||e.includes(`activities:`)){g=`activities`;continue}if(e.includes(`Service Resolver Table`)||e.includes(`services:`)){g=`services`;continue}if(e.includes(`Receiver Resolver Table`)||e.includes(`receivers:`)){g=`receivers`;continue}let t=e.trim(),r=t.split(` `)[0];g===`permissions`?r&&t.startsWith(`android.permission.`)&&u.push(r):g===`activities`&&t.includes(n)?r&&p.push(r):g===`services`&&t.includes(n)?r&&m.push(r):g===`receivers`&&t.includes(n)&&r&&h.push(r)}return i.permissions=[...new Set(u)],i.activities=[...new Set(p)],i.services=[...new Set(m)],i.receivers=[...new Set(h)],{success:!0,serial:t,...i}})}async handlePullNativeLibs(e){return this.run(`adb_pull_native_libs`,async()=>{let t=a(e,`serial`),n=a(e,`packageName`),i=r(e,`outputPath`)??`.`,l=o(e,`includeSystemLibs`)??!1,u=await this.resolveAdb(),{stdout:p}=await f(u,[...d(t),`shell`,`dumpsys package ${n}`]),m=h(p,n,l);if(m.length===0)return{success:!1,serial:t,packageName:n,error:`No native library directories found for ${n}`};let g=s(i,`${n}-native-libs`).replace(/\\/g,`/`);await c(g,{recursive:!0});let _=[];for(let e of m){let n=s(g,e.split(`/`).filter(Boolean).pop()??`lib`).replace(/\\/g,`/`);await c(n,{recursive:!0}),await f(u,[...d(t),`pull`,e,n]),_.push({remoteDir:e,localPath:n})}return{success:!0,serial:t,packageName:n,includeSystemLibs:l,count:_.length,outputPath:g,libraries:_}})}async handleWebViewList(e){return this.run(`adb_webview_list`,async()=>{let t=a(e,`serial`),n=i(e,`hostPort`)??9222,r=await this.resolveAdb(),o=await p(r,t);if(o.length===0)return{success:!0,serial:t,hostPort:n,webviews:[],count:0};let s=o[0];await f(r,[...d(t),`forward`,`tcp:${n}`,`localabstract:${s}`]);let c=await import(`node:http`),l=await new Promise(e=>{c.get(`http://localhost:${n}/json/list`,t=>{let n=``;t.on(`data`,e=>{n+=e}),t.on(`end`,()=>{try{e(JSON.parse(n))}catch{e([])}})}).on(`error`,()=>e([]))});return{success:!0,serial:t,hostPort:n,webviews:l.map(e=>({id:e.id,url:e.url,title:e.title,webSocketDebuggerUrl:e.webSocketDebuggerUrl})),count:l.length}})}async handleWebViewAttach(e){return this.run(`adb_webview_attach`,async()=>{let t=a(e,`serial`),n=a(e,`targetId`),r=i(e,`hostPort`)??9222,o=await this.resolveAdb(),s=await p(o,t);if(s.length===0)return{success:!1,error:`No WebView devtools sockets found on device`};let c=s[0];await f(o,[...d(t),`forward`,`tcp:${r}`,`localabstract:${c}`]);let l=await import(`node:http`),u=await new Promise(e=>{l.get(`http://localhost:${r}/json`,t=>{let r=``;t.on(`data`,e=>{r+=e}),t.on(`end`,()=>{try{e(JSON.parse(r).find(e=>e.id===n)?.webSocketDebuggerUrl)}catch{e(void 0)}})}).on(`error`,()=>e(void 0))});return u?{success:!0,serial:t,targetId:n,hostPort:r,webSocketDebuggerUrl:u,attached:!0}:{success:!1,error:`Target ${n} not found`}})}};export{g as ADBBridgeHandlers};
@@ -1,2 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{It as t,Lt as n}from"./constants-BYj8Xek8.mjs";import{i as r}from"./outputPaths-B4Ic4RZh.mjs";import{n as i}from"./WorkflowEngine-D876meOO.mjs";import{extname as a,resolve as o}from"node:path";import{readFile as s,readdir as c}from"node:fs/promises";function l(e){return`kind`in e?e:e.build()}function u(e,t){return t?.(e),e}function d(e,t){let n={},r,i,a,o;return n.input=e=>(r=e,n),n.inputFrom=e=>(i=e,n),n.retry=e=>(a=e,n),n.timeout=e=>(o=e,n),n.build=()=>({kind:`tool`,id:e,toolName:t,input:r,inputFrom:i,retry:a,timeoutMs:o}),n}function f(e,t){return t?typeof t==`function`?(t(e),e):(t.input&&e.input(t.input),t.inputFrom&&e.inputFrom(t.inputFrom),t.retry&&e.retry(t.retry),t.timeoutMs!==void 0&&e.timeout(t.timeoutMs),e):e}function p(e,t){return e.step=n=>(t.push(n),e),e.tool=(n,r,i)=>(t.push(f(d(n,r),i)),e),e.sequence=(n,r)=>(t.push(u(m(n),r)),e),e.parallel=(n,r)=>(t.push(u(h(n),r)),e),e.branch=(n,r,i)=>(t.push(u(g(n,r),i)),e),e.fallback=(n,r)=>(t.push(u(_(n),r)),e),e}function m(e){let t=[],n=p({},t);return n.build=()=>({kind:`sequence`,id:e,steps:t.map(l)}),n}function h(e){let t=[],n=p({},t),r=4,i=!1;return n.maxConcurrency=e=>(r=e,n),n.failFast=e=>(i=e,n),n.build=()=>({kind:`parallel`,id:e,steps:t.map(l),maxConcurrency:r,failFast:i}),n}function g(e,t){let n={},r,i,a;return n.predicateFn=e=>(r=e,n),n.whenTrue=e=>(i=e,n),n.whenFalse=e=>(a=e,n),n.build=()=>{if(!i)throw Error(`BranchNode '${e}' requires a whenTrue step`);return{kind:`branch`,id:e,predicateId:t,predicateFn:r,whenTrue:l(i),whenFalse:a?l(a):void 0}},n}function _(e){let t={},n,r;return t.primary=e=>(n=e,t),t.fallback=e=>(r=e,t),t.build=()=>{if(!n)throw Error(`FallbackNode '${e}' requires a primary step`);if(!r)throw Error(`FallbackNode '${e}' requires a fallback step`);return{kind:`fallback`,id:e,primary:l(n),fallback:l(r)}},t}function v(e,t){let n={},r,i,a,o,s,c,l,u,d;return n.description=e=>(r=e,n),n.tags=e=>(i=e,n),n.timeoutMs=e=>(a=e,n),n.defaultMaxConcurrency=e=>(o=e,n),n.route=e=>(s=e,n),n.buildGraph=e=>(c=e,n),n.onStart=e=>(l=e,n),n.onFinish=e=>(u=e,n),n.onError=e=>(d=e,n),n.build=()=>{if(!c)throw Error(`Workflow '${e}' needs a buildGraph() function.`);return{kind:`workflow-contract`,version:1,id:e,displayName:t,description:r,tags:i,timeoutMs:a,defaultMaxConcurrency:o,route:s,build:c,onStart:l,onFinish:u,onError:d}},n}function y(e,t,n){let r=v(e,t);return n(r),r.build()}function b(e,t,n){return f(d(e,t),n).build()}function x(e,t){return u(m(e),t).build()}var S=class{ctx;constructor(e){this.ctx=e}buildWorkflowFromDefinition(e){return y(e.id,e.displayName,t=>t.description(e.description).tags(e.tags).timeoutMs(e.timeoutMs??n).buildGraph(()=>x(`${e.id}-root`,t=>{for(let n of e.steps)t.step(b(n.id,n.toolName,e=>{e.input(n.input??{}).timeout(n.timeoutMs??0),n.inputFrom&&e.inputFrom(n.inputFrom)}))})).onStart(t=>{t.emitSpan(`macro.start`,{macroId:e.id,totalSteps:e.steps.length})}).onError((t,n)=>{t.emitSpan(`macro.error`,{macroId:e.id,error:n.message})}))}async execute(e,t){let n=this.buildWorkflowFromDefinition(e),r=Date.now();try{let r=await i(this.ctx,n,{nodeInputOverrides:t}),a=this.buildProgress(e,r.spans,r.stepResults);return{macroId:e.id,displayName:e.displayName,ok:!0,durationMs:r.durationMs,stepsCompleted:e.steps.length,totalSteps:e.steps.length,stepResults:r.stepResults,progress:a}}catch(t){let n=Date.now()-r,i=t instanceof Error?t.message:String(t),a=this.buildPartialProgress(e,i);return{macroId:e.id,displayName:e.displayName,ok:!1,durationMs:n,stepsCompleted:a.filter(e=>e.status===`complete`).length,totalSteps:e.steps.length,stepResults:{},progress:a,error:i}}}formatProgressReport(e){let t=[];t.push(`**Macro:** ${e.displayName} (\`${e.macroId}\`)`),t.push(``);for(let n of e.progress){let e=n.durationMs===void 0?``:` (${n.durationMs}ms)`,r=n.error?`: ${n.error}`:``,i=n.status===`complete`?`✓`:n.status===`failed`?`✗`:`○`;t.push(`[stage ${n.step}/${n.totalSteps}] ${i} ${n.stepName} — ${n.status}${e}${r}`)}return t.push(``),e.ok?t.push(`✓ Macro complete (${e.stepsCompleted}/${e.totalSteps} steps, ${e.durationMs}ms)`):t.push(`✗ Macro failed at step ${e.stepsCompleted+1}/${e.totalSteps}: ${e.error??`unknown error`}`),t.join(`
2
- `)}buildProgress(e,t,n){return e.steps.map((r,i)=>{let a=t.find(e=>e.name===`workflow.node.start`&&e.attrs?.nodeId===r.id),o=t.find(e=>e.name===`workflow.node.finish`&&e.attrs?.nodeId===r.id),s;a&&o&&(s=new Date(o.at).getTime()-new Date(a.at).getTime());let c=r.id in n;return{step:i+1,totalSteps:e.steps.length,stepName:r.id,status:c?`complete`:`skipped`,durationMs:s}})}buildPartialProgress(e,t){return e.steps.map((n,r)=>({step:r+1,totalSteps:e.steps.length,stepName:n.id,status:`failed`,error:r===0?t:void 0}))}};async function C(t){let n;try{n=await c(t)}catch{return[]}let r=n.filter(e=>a(e)===`.json`),i=[];for(let n of r){let r=o(t,n);try{let t=JSON.parse(await s(r,`utf-8`));w(t)?(i.push(T(t)),e.info(`[macros] Loaded user macro "${t.id}" from ${n}`)):e.warn(`[macros] Skipping ${n}: invalid macro schema`)}catch(t){e.warn(`[macros] Skipping ${n}: ${t instanceof Error?t.message:String(t)}`)}}return i}function w(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.id!=`string`||!t.id||typeof t.displayName!=`string`||!t.displayName||!Array.isArray(t.steps)||t.steps.length===0)return!1;for(let e of t.steps){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.id!=`string`||!t.id||typeof t.toolName!=`string`||!t.toolName)return!1}return!0}function T(e){return{id:e.id,displayName:e.displayName,description:e.description??``,tags:e.tags??[],timeoutMs:e.timeoutMs,steps:e.steps.map(e=>({id:e.id,toolName:e.toolName,input:e.input,inputFrom:e.inputFrom,timeoutMs:e.timeoutMs,optional:e.optional}))}}const E={loadFromDirectory:C,validate:w},D=[{id:`deobfuscate_ast_flow`,displayName:`Deobfuscate AST Flow`,description:`Chain: deobfuscate → optional webcrack unpack → semantic analysis`,tags:[`analysis`,`deobfuscation`,`ast`],timeoutMs:t,steps:[{id:`deobfuscate`,toolName:`deobfuscate`,input:{}},{id:`advanced_deobfuscate`,toolName:`webcrack_unpack`,input:{unpack:!0,unminify:!0},inputFrom:{code:`deobfuscate.code`},optional:!0},{id:`analyze_deobfuscated`,toolName:`understand_code`,inputFrom:{code:`deobfuscate.code`}}]},{id:`unpacker_flow`,displayName:`Unpacker Flow`,description:`Detect packer type → extract inner code → optional deep unpack → normalize output`,tags:[`analysis`,`unpacking`,`deobfuscation`],timeoutMs:9e4,steps:[{id:`detect_and_unpack`,toolName:`deobfuscate`,input:{unpack:!0}},{id:`deep_deobfuscate`,toolName:`webcrack_unpack`,input:{unpack:!0,unminify:!0},inputFrom:{code:`detect_and_unpack.code`},optional:!0},{id:`normalize_output`,toolName:`ast_transform_apply`,input:{transforms:[`dead_code_remove`,`rename_vars`]},inputFrom:{code:`detect_and_unpack.code`}}]}];var O=class{runner;macros=null;constructor(e){this.runner=new S(e)}async ensureMacrosLoaded(){if(this.macros)return this.macros;this.macros=new Map;for(let e of D)this.macros.set(e.id,e);try{let e=await E.loadFromDirectory(o(r(),`macros`));for(let t of e)this.macros.set(t.id,t)}catch{}return this.macros}async handleRunMacro(e){let t=e.macroId,n=e.inputOverrides;if(!t||typeof t!=`string`)return{content:[{type:`text`,text:JSON.stringify({ok:!1,error:`macroId parameter is required`})}]};let r=await this.ensureMacrosLoaded(),i=r.get(t);if(!i)return{content:[{type:`text`,text:JSON.stringify({ok:!1,error:`Macro "${t}" not found`,available:Array.from(r.keys())})}]};let a=await this.runner.execute(i,n);return{content:[{type:`text`,text:this.runner.formatProgressReport(a)}]}}async handleListMacros(){let e=await this.ensureMacrosLoaded(),t=Array.from(e.values()).map(e=>({id:e.id,displayName:e.displayName,description:e.description,tags:e.tags,stepCount:e.steps.length}));return{content:[{type:`text`,text:JSON.stringify({macros:t,count:t.length})}]}}};export{O as MacroToolHandlers};