@jshookmcp/jshook 0.3.1 → 0.3.2

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 (226) hide show
  1. package/LICENSE +661 -661
  2. package/README.md +11 -3
  3. package/README.zh.md +11 -3
  4. package/dist/{AntiCheatDetector-CGVGNfy5.mjs → AntiCheatDetector-B6d4Qe9D.mjs} +1 -1
  5. package/dist/BrowserSessionCoordinator-BJ-HOxo0.mjs +1 -0
  6. package/dist/{CodeInjector-BlgyqTOk.mjs → CodeInjector-Cll_7bLJ.mjs} +1 -1
  7. package/dist/ConsoleMonitor-CxDJV15E.mjs +306 -0
  8. package/dist/DOMInspector-C19J4zeq.mjs +95 -0
  9. package/dist/DetailedDataManager-DmQ1LT-W.mjs +1 -0
  10. package/dist/ExtensionManager-BD724zkO.mjs +1 -0
  11. package/dist/ExtensionManager.tools-oVMJgPcN.mjs +1 -0
  12. package/dist/{HardwareBreakpoint-OcJqNFVc.mjs → HardwareBreakpoint-BUfPdp0f.mjs} +1 -1
  13. package/dist/{HeapAnalyzer-CqAxZzeS.mjs → HeapAnalyzer-B_aqY8oj.mjs} +1 -1
  14. package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +1 -0
  15. package/dist/MemoryController-X1XNSn1n.mjs +2 -0
  16. package/dist/{MemoryScanSession-CaxAjZJf.mjs → MemoryScanSession-DG_F-PjE.mjs} +1 -1
  17. package/dist/{MemoryScanner-BLYnMJy6.mjs → MemoryScanner-g1_L1ub5.mjs} +1 -1
  18. package/dist/{NativeMemoryManager.impl-CI554XbY.mjs → NativeMemoryManager.impl-DniBe2wf.mjs} +1 -1
  19. package/dist/{NativeMemoryManager.utils-DM4NC3FE.mjs → NativeMemoryManager.utils-BHy1P_jM.mjs} +1 -1
  20. package/dist/NetworkMonitor-B_-au6aV.mjs +185 -0
  21. package/dist/{PEAnalyzer-DJyaJTQJ.mjs → PEAnalyzer-yWQaGrcx.mjs} +1 -1
  22. package/dist/PageController-Dfsm1_o7.mjs +1 -0
  23. package/dist/{PointerChainEngine-5nF9eNlu.mjs → PointerChainEngine-BhCUkmxY.mjs} +1 -1
  24. package/dist/ProcessRegistry-C-bN48oR.mjs +1 -0
  25. package/dist/{ResponseBuilder-B2lu4KEl.mjs → ResponseBuilder-BfWP-uaT.mjs} +1 -1
  26. package/dist/RingBuffer-Dm54ELKT.mjs +1 -0
  27. package/dist/{ScriptManager-fgqiALgj.mjs → ScriptManager-LWGPTdvD.mjs} +1 -1
  28. package/dist/ServerRuntimeState-D2bWHqEE.mjs +1 -0
  29. package/dist/{Speedhack-l6s8L2Qw.mjs → Speedhack-yseDPSZ9.mjs} +1 -1
  30. package/dist/{StructureAnalyzer-A-WamfYE.mjs → StructureAnalyzer-C5lpuZkg.mjs} +1 -1
  31. package/dist/ToolCatalog-CYdD9F5f.mjs +1 -0
  32. package/dist/ToolProbe-C7ZU2x7M.mjs +1 -0
  33. package/dist/ToolRegistry-C5oB8KP8.mjs +1 -0
  34. package/dist/{ToolRouter.policy-CFHoN_Lw.mjs → ToolRouter.policy-CfhJczkt.mjs} +2 -2
  35. package/dist/{TraceRecorder-Dd8jLXpi.mjs → TraceRecorder-BiJWBXHX.mjs} +1 -1
  36. package/dist/{Win32Debug-CQteFL4F.mjs → Win32Debug-CYrIQBvr.mjs} +1 -1
  37. package/dist/{WorkflowEngine-CxEp2WXH.mjs → WorkflowEngine-D876meOO.mjs} +1 -1
  38. package/dist/analysis-D4swdMvq.mjs +6 -0
  39. package/dist/{antidebug-BOTZH6-0.mjs → antidebug-7L3ygj_9.mjs} +4 -4
  40. package/dist/apk-packer-BqXcInnX.mjs +1 -0
  41. package/dist/{artifactRetention-NBdncOEW.mjs → artifactRetention-BCPQASm7.mjs} +1 -1
  42. package/dist/{artifacts-B5xQuEa_.mjs → artifacts-CkodUM4j.mjs} +1 -1
  43. package/dist/betterSqlite3-Brtq-SIQ.mjs +1 -0
  44. package/dist/{binary-instrument-Cf9qqLlM.mjs → binary-instrument-DU7V6TUM.mjs} +1 -1
  45. package/dist/binary-secrets-PdMVoyt0.mjs +1 -0
  46. package/dist/{boringssl-inspector-BST5vtKx.mjs → boringssl-inspector-BBaJwwkU.mjs} +1 -1
  47. package/dist/browser-Qqco2rOT.mjs +11 -0
  48. package/dist/collector-Bpl6qy2L.mjs +1 -0
  49. package/dist/constants-BYj8Xek8.mjs +1 -0
  50. package/dist/{coordination-BbijHEHH.mjs → coordination-CWXW1o8K.mjs} +1 -1
  51. package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
  52. package/dist/{debugger-CRJq_krh.mjs → debugger-DyALjYMk.mjs} +1 -1
  53. package/dist/{definitions-DZ8uKusP.mjs → definitions-BWxBke3r.mjs} +1 -1
  54. package/dist/{definitions-CYFbewnd.mjs → definitions-BYwATKc-.mjs} +1 -1
  55. package/dist/{definitions-DJklW2sS.mjs → definitions-B_83XfNQ.mjs} +1 -1
  56. package/dist/definitions-Bf3H1EwV.mjs +1 -0
  57. package/dist/{definitions-BGobEDQa.mjs → definitions-BftdXgXI.mjs} +1 -1
  58. package/dist/definitions-Bio5XJYy.mjs +1 -0
  59. package/dist/definitions-C3qNgSn1.mjs +1 -0
  60. package/dist/{definitions-NoVp_9Pm.mjs → definitions-CB6vmOer.mjs} +1 -1
  61. package/dist/{definitions-CoQFbggH.mjs → definitions-CMZRSy3k.mjs} +1 -1
  62. package/dist/{definitions-DI9YXsJk.mjs → definitions-CQd7yCQH.mjs} +1 -1
  63. package/dist/{definitions-CIO9O-Sw.mjs → definitions-CT8ln6GQ.mjs} +1 -1
  64. package/dist/{definitions-BGwNSkVm.mjs → definitions-Cenu6mxo.mjs} +1 -1
  65. package/dist/definitions-D4g-MS10.mjs +1 -0
  66. package/dist/{definitions-CuJRsJ6N.mjs → definitions-D5wl_8HN.mjs} +1 -1
  67. package/dist/{definitions-jXPaVy4P.mjs → definitions-DAQm1Xar.mjs} +1 -1
  68. package/dist/definitions-DP1vgxEY.mjs +1 -0
  69. package/dist/{definitions-Dds_zrWx.mjs → definitions-DxFNRQNK2.mjs} +1 -1
  70. package/dist/{definitions-DtE0XLrT.mjs → definitions-Ibci7e_L.mjs} +1 -1
  71. package/dist/{definitions-CCP9gphV.mjs → definitions-OeLvmlQy.mjs} +1 -1
  72. package/dist/{definitions-BbxOUiP-.mjs → definitions-RZYGD_Ey.mjs} +1 -1
  73. package/dist/definitions-Tls8c0A0.mjs +1 -0
  74. package/dist/{definitions-LaYTuwQd.mjs → definitions-bybDvnG0.mjs} +1 -1
  75. package/dist/{definitions-Dgrg7f3D.mjs → definitions-l7TjdE6V.mjs} +1 -1
  76. package/dist/{encoding-DGcr6Aj_.mjs → encoding-ycOaz8Vr.mjs} +1 -1
  77. package/dist/{ensure-browser-core-Buls24LQ.mjs → ensure-browser-core-DxWC-NTp.mjs} +1 -1
  78. package/dist/{factory-Cx_1LorX.mjs → factory-CKr4fAE1.mjs} +1 -1
  79. package/dist/{graphql-HLf3MS8H.mjs → graphql-B2TiPEow.mjs} +4 -4
  80. package/dist/{handlers-D49r1-1P.mjs → handlers-8zN_vBIz.mjs} +1 -1
  81. package/dist/handlers-B62K4FTc.mjs +1 -0
  82. package/dist/{handlers-BZoPla6E.mjs → handlers-BpDlVVVU.mjs} +1 -1
  83. package/dist/{handlers-DmQzIc44.mjs → handlers-CMJK7m1c.mjs} +1 -1
  84. package/dist/{handlers-BLMa4X7l.mjs → handlers-D2ZOul9p.mjs} +2 -2
  85. package/dist/{handlers-DW5AbYs5.mjs → handlers-D5E40ssn.mjs} +3 -3
  86. package/dist/{handlers-BP12ZsWc.mjs → handlers-DGbdQAgD.mjs} +2 -2
  87. package/dist/handlers-DHO3rjsW.mjs +1 -0
  88. package/dist/{handlers-DCE45Ww8.mjs → handlers-FJ80VzUI.mjs} +1 -1
  89. package/dist/handlers-VHWrxbM_.mjs +1 -0
  90. package/dist/{handlers-BggKiVx9.mjs → handlers-l8QIKqBj.mjs} +1 -1
  91. package/dist/{handlers-DnJRGp7t.mjs → handlers-mPFiNPe8.mjs} +1 -1
  92. package/dist/{handlers-pVNpaw4A.mjs → handlers-yo_xYzT8.mjs} +1 -1
  93. package/dist/handlers.impl-D9Hh8Bgl.mjs +1 -0
  94. package/dist/{hooks-DDKppogd.mjs → hooks-D4XLfgtV.mjs} +1 -1
  95. package/dist/index.mjs +11 -15
  96. package/dist/jadx-search-B_Yse0Zh.mjs +5 -0
  97. package/dist/maintenance-BUpIukhg.mjs +1 -0
  98. package/dist/{manifest-yu2xiQqe.mjs → manifest-0Jpt_AQa.mjs} +1 -1
  99. package/dist/{manifest-DMJlcsTR.mjs → manifest-B3fZbSWR.mjs} +1 -1
  100. package/dist/{manifest-De-6Wf2R.mjs → manifest-B7NB2rh2.mjs} +1 -1
  101. package/dist/manifest-BDi4nbH1.mjs +1 -0
  102. package/dist/{manifest-ais9Afrw.mjs → manifest-BLDfkE7n.mjs} +1 -1
  103. package/dist/manifest-BcXbB4gf.mjs +1 -0
  104. package/dist/{manifest-DsVh7Y4U.mjs → manifest-Bdnc_vrc.mjs} +1 -1
  105. package/dist/manifest-BuYKgCnp.mjs +1 -0
  106. package/dist/{manifest-Cx2IVMUY.mjs → manifest-CBfNnGPV.mjs} +1 -1
  107. package/dist/{manifest-DC-SMF6b.mjs → manifest-CPS1Xv69.mjs} +1 -1
  108. package/dist/{manifest-CGq4NpqH2.mjs → manifest-CQH9FhwI.mjs} +1 -1
  109. package/dist/{manifest-CRIJq4Hs.mjs → manifest-CRryuZF4.mjs} +1 -1
  110. package/dist/manifest-CctIumog.mjs +1 -0
  111. package/dist/manifest-CvTe5ZGV2.mjs +1 -0
  112. package/dist/{manifest-H-EpAyZQ.mjs → manifest-D-5GH0DV.mjs} +1 -1
  113. package/dist/{manifest-CtPmHAdn.mjs → manifest-D3Ssf3IC.mjs} +1 -1
  114. package/dist/{manifest-BeP_zJGb2.mjs → manifest-D5ck3NvC.mjs} +1 -1
  115. package/dist/{manifest-CeQmtQOY.mjs → manifest-D9jUUJAu.mjs} +1 -1
  116. package/dist/{manifest-C7qV1z7F.mjs → manifest-DCx6w2XV.mjs} +1 -1
  117. package/dist/{manifest-CFn0359q2.mjs → manifest-DG19q-Ld.mjs} +1 -1
  118. package/dist/{manifest-CJMGt7Qy.mjs → manifest-DLMlD0Zc.mjs} +1 -1
  119. package/dist/{manifest-CDeUZGUZ.mjs → manifest-DYpn8w_h.mjs} +1 -1
  120. package/dist/manifest-DYzWI8Xs.mjs +1 -0
  121. package/dist/{manifest-DKUorv5M.mjs → manifest-D_obs5F4.mjs} +1 -1
  122. package/dist/{manifest-D610kxZr.mjs → manifest-DujQqEQR.mjs} +2 -2
  123. package/dist/manifest-DwL2ik8P.mjs +1 -0
  124. package/dist/manifest-ItF5P8A12.mjs +1 -0
  125. package/dist/{manifest-tmb54wmA.mjs → manifest-KZphqIyX.mjs} +1 -1
  126. package/dist/{manifest-BPuE6oH2.mjs → manifest-LG42zPLY2.mjs} +1 -1
  127. package/dist/{manifest-D44TaRJU.mjs → manifest-LLdI5m4T.mjs} +1 -1
  128. package/dist/{manifest-Dgh0uDW-.mjs → manifest-QYbQXJn0.mjs} +1 -1
  129. package/dist/{manifest-BFGxlDRh.mjs → manifest-RcpX_MyZ.mjs} +2 -2
  130. package/dist/{manifest-CDiCtaQT.mjs → manifest-YgVd8Sgz.mjs} +1 -1
  131. package/dist/{manifest-D16xPXro.mjs → manifest-Zy7Odg5J.mjs} +1 -1
  132. package/dist/manifest-ff1H7Pdp.mjs +1 -0
  133. package/dist/{manifest-C_hEIjSx.mjs → manifest-iuhF6pTL2.mjs} +1 -1
  134. package/dist/{manifest-DWUUWBz0.mjs → manifest-nXHmtMSp2.mjs} +1 -1
  135. package/dist/{manifest-C1nZkTkO.mjs → manifest-xWfu6iLo.mjs} +1 -1
  136. package/dist/{manifest-C0g67k6U.mjs → manifest-yC16OhL2.mjs} +1 -1
  137. package/dist/manifest-ztWJoXy4.mjs +1 -0
  138. package/dist/modules-BPBcSaM-.mjs +333 -0
  139. package/dist/{mojo-ipc-VGlv3Qyp.mjs → mojo-ipc-BhwsdVUW.mjs} +1 -1
  140. package/dist/native/scripts/linux/enum-windows.sh +12 -12
  141. package/dist/native/scripts/macos/enum-windows.applescript +22 -22
  142. package/dist/native-j8l473zn.mjs +961 -0
  143. package/dist/network-T0VRwNPd.mjs +7 -0
  144. package/dist/{outputPaths-BonGThuc.mjs → outputPaths-B4Ic4RZh.mjs} +2 -2
  145. package/dist/platform-CzaQtISh.mjs +93 -0
  146. package/dist/process-CWhsCWrf.mjs +2 -0
  147. package/dist/proxy-DZFlDsG3.mjs +2 -0
  148. package/dist/{registry-DUHIPE-v.mjs → registry-DH4sc1dt.mjs} +1 -1
  149. package/dist/renderer-pid-9tJnZ_9N.mjs +1 -0
  150. package/dist/{search-defaults-D2bY-rzH.mjs → search-defaults-lYBVn_3L.mjs} +1 -1
  151. package/dist/server/plugin-api.d.mts +19 -36
  152. package/dist/server/plugin-api.mjs +1 -1
  153. package/dist/{shared-state-board-Cyg-xh_k.mjs → shared-state-board-BSjXLUV1.mjs} +1 -1
  154. package/dist/{sourcemap-D6Q1UuAp.mjs → sourcemap-Dh3Ai_ur.mjs} +1 -1
  155. package/dist/streaming-BcJ0B6ao.mjs +1 -0
  156. package/dist/transform-DOxzeWPB.mjs +103 -0
  157. package/dist/wasm-CZ_HTfKR.mjs +174 -0
  158. package/dist/{webcrack-CsLLJIs9.mjs → webcrack-C1iYG_EX.mjs} +3 -3
  159. package/dist/{workflow-CYIXtrWD.mjs → workflow-BdwQmARn.mjs} +4 -4
  160. package/package.json +16 -15
  161. package/src/native/scripts/linux/enum-windows.sh +12 -12
  162. package/src/native/scripts/macos/enum-windows.applescript +22 -22
  163. package/dist/ConsoleMonitor-Dkqc0HNi.mjs +0 -490
  164. package/dist/DOMInspector-BYY_EJ0C.mjs +0 -95
  165. package/dist/DetailedDataManager-BniBJlVv.mjs +0 -1
  166. package/dist/ExtensionManager-erMpqcLk.mjs +0 -1
  167. package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +0 -1
  168. package/dist/MemoryController-BaqstM5w.mjs +0 -2
  169. package/dist/PageController-D9jVkH0i.mjs +0 -1
  170. package/dist/ProcessRegistry-Hf12LlR9.mjs +0 -1
  171. package/dist/ToolCatalog-D_IKl1Hu.mjs +0 -1
  172. package/dist/ToolProbe-xsfALmN3.mjs +0 -1
  173. package/dist/ToolRegistry-B0Zs-phN.mjs +0 -1
  174. package/dist/analysis-BuR-NgX8.mjs +0 -5
  175. package/dist/betterSqlite3-CGaxz4AX.mjs +0 -1
  176. package/dist/browser-C4Le3xqA.mjs +0 -11
  177. package/dist/collector-CKO8RPK8.mjs +0 -1
  178. package/dist/constants-Cp6hBrrx.mjs +0 -1
  179. package/dist/definitions-CdWEuIkI.mjs +0 -1
  180. package/dist/definitions-OvGsfxdt.mjs +0 -1
  181. package/dist/handlers-D3iev8g1.mjs +0 -1
  182. package/dist/handlers-De5u62Ga2.mjs +0 -1
  183. package/dist/handlers-S9Ws0IGy.mjs +0 -2
  184. package/dist/handlers.impl-CD2_kOcC.mjs +0 -1
  185. package/dist/maintenance-CutEO84j.mjs +0 -1
  186. package/dist/manifest-BXry5N09.mjs +0 -1
  187. package/dist/manifest-Cq0j7GZt.mjs +0 -1
  188. package/dist/manifest-DD3rtxvV.mjs +0 -1
  189. package/dist/manifest-Dm0o3i2U.mjs +0 -1
  190. package/dist/manifest-DtEFSRaq.mjs +0 -1
  191. package/dist/manifest-zrbrpKCC.mjs +0 -1
  192. package/dist/modules-p-PUNv9r.mjs +0 -332
  193. package/dist/network-BjZ1Y-GB.mjs +0 -7
  194. package/dist/platform-C446Lf97.mjs +0 -93
  195. package/dist/process-C9f2A5zk.mjs +0 -962
  196. package/dist/proxy-CvRepxgV.mjs +0 -1
  197. package/dist/streaming-CTX58tbb.mjs +0 -1
  198. package/dist/transform-Cv9P2vVD.mjs +0 -103
  199. package/dist/wasm-DaJa8J0V.mjs +0 -174
  200. /package/dist/{CacheAdapters-CdAxBmVW.mjs → CacheAdapters-CsNtQIR8.mjs} +0 -0
  201. /package/dist/{DarwinAPI-DC4HGGLl.mjs → DarwinAPI-ZfQdpLNI.mjs} +0 -0
  202. /package/dist/{EventBus-DgciURGg.mjs → EventBus-DL8iLA09.mjs} +0 -0
  203. /package/dist/{EvidenceGraphBridge-BIfgB7HP.mjs → EvidenceGraphBridge-BtbwXsLC.mjs} +0 -0
  204. /package/dist/{FingerprintManager-N7BZqjxP.mjs → FingerprintManager-DT0EAUEo.mjs} +0 -0
  205. /package/dist/{HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs → HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs} +0 -0
  206. /package/dist/{InstrumentationSession-DxXs0sCp.mjs → InstrumentationSession-D_G1ZPyd.mjs} +0 -0
  207. /package/dist/{PrerequisiteError-Bl3dK8XA.mjs → PrerequisiteError-BjCQA-gK.mjs} +0 -0
  208. /package/dist/{ReverseEvidenceGraph-B931HeoW.mjs → ReverseEvidenceGraph-BhSYYdiI.mjs} +0 -0
  209. /package/dist/{StealthVerifier-Dhbj4B4P.mjs → StealthVerifier-BmcxfwSF.mjs} +0 -0
  210. /package/dist/{VersionDetector-DMoUWyNm.mjs → VersionDetector-CHT36Az0.mjs} +0 -0
  211. /package/dist/{Win32API-Bhi5xFBe.mjs → Win32API-eUCF57l_.mjs} +0 -0
  212. /package/dist/{authorization-schema-B40obG1A.mjs → authorization-schema-BOFwSXUN.mjs} +0 -0
  213. /package/dist/{bind-helpers-BlAOQrFQ.mjs → bind-helpers-m2U8glkF.mjs} +0 -0
  214. /package/dist/{capabilities-DbYCv-HF.mjs → capabilities-CyXuKUl1.mjs} +0 -0
  215. /package/dist/{concurrency-CcK46d0h.mjs → concurrency-DCr8WQ2M.mjs} +0 -0
  216. /package/dist/{evidence-graph-bridge-B0yhGPcs.mjs → evidence-graph-bridge-CV_UdYqj.mjs} +0 -0
  217. /package/dist/{flat-target-session-CO5g78k3.mjs → flat-target-session-DvcQX7J5.mjs} +0 -0
  218. /package/dist/{formatAddress-C7j2fDlM.mjs → formatAddress-vLA_hOJt.mjs} +0 -0
  219. /package/dist/{handlers-Dv_runVv.mjs → handlers-0yKLRIfo.mjs} +0 -0
  220. /package/dist/{matchesWildcardPattern-BGqLSmEs.mjs → matchesWildcardPattern-BAG6LvX5.mjs} +0 -0
  221. /package/dist/{parse-args-Cuk7-xUt.mjs → parse-args-Bw413PlW.mjs} +0 -0
  222. /package/dist/{playwright-cdp-fallback-BwVR-_T3.mjs → playwright-cdp-fallback-DqFdx9-s.mjs} +0 -0
  223. /package/dist/{ssrf-policy-T96MR3r6.mjs → ssrf-policy-CsIJGkpd.mjs} +0 -0
  224. /package/dist/{tool-builder-CI9914Tf.mjs → tool-builder-qif8M9-K.mjs} +0 -0
  225. /package/dist/{types-DtThH00r.mjs → types-D9EiE5o9.mjs} +0 -0
  226. /package/dist/{types-CuyefmGT.mjs → types-Fz69RzbZ.mjs} +0 -0
@@ -0,0 +1,11 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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 +1 @@
1
- import{N as e}from"./constants-Cp6hBrrx.mjs";import"./definitions-jXPaVy4P.mjs";import{randomUUID as t}from"node:crypto";var n=class{handoffs=new Map;insights=[];ctx;constructor(e){this.ctx=e}async handleCreateTaskHandoff(e){let n=e.description,r=e.constraints,i=e.targetDomain,a=e.decision,o=e.risks,s=e.nextSteps,c;try{let e=this.ctx.pageController;if(e){let t=await e.getPage?.();t&&typeof t.url==`function`&&(c=t.url())}}catch{}let l={id:t().slice(0,8),status:`pending`,description:n,constraints:r,targetDomain:i,decision:a,risks:o,nextSteps:s,pageUrl:c,createdAt:Date.now()};return this.handoffs.set(l.id,l),{taskId:l.id,status:l.status,description:l.description,constraints:l.constraints,targetDomain:l.targetDomain,decision:l.decision,risks:l.risks,nextSteps:l.nextSteps,pageUrl:l.pageUrl,createdAt:new Date(l.createdAt).toISOString(),totalActiveHandoffs:this.handoffs.size}}async handleCompleteTaskHandoff(e){let t=e.taskId,n=e.summary,r=e.keyFindings,i=e.artifacts,a=this.handoffs.get(t);if(!a)throw Error(`Task handoff "${t}" not found. Active IDs: ${[...this.handoffs.keys()].join(`, `)||`(none)`}`);if(a.status===`completed`)throw Error(`Task handoff "${t}" is already completed`);return a.status=`completed`,a.completedAt=Date.now(),a.summary=n,a.keyFindings=r,a.artifacts=i,{taskId:a.id,status:`completed`,summary:a.summary,keyFindings:a.keyFindings,artifacts:a.artifacts,durationMs:a.completedAt-a.createdAt}}async handleGetTaskContext(e){let t=e.taskId;if(t){let e=this.handoffs.get(t);if(!e)throw Error(`Task handoff "${t}" not found`);return{handoff:this.serializeHandoff(e)}}let n=[...this.handoffs.values()].map(e=>this.serializeHandoff(e)),r=n.filter(e=>e.status!==`completed`),i=n.filter(e=>e.status===`completed`);return{active:r,completed:i,sessionInsights:this.insights.map(e=>({id:e.id,category:e.category,content:e.content,confidence:e.confidence,timestamp:new Date(e.timestamp).toISOString(),sourceTaskId:e.sourceTaskId})),summary:{totalActive:r.length,totalCompleted:i.length,totalInsights:this.insights.length}}}async handleAppendSessionInsight(e){let n=e.category,r=e.content,i=e.confidence??1,a=[...this.handoffs.values()].find(e=>e.status===`in_progress`||e.status===`pending`),o={id:t().slice(0,8),category:n,content:r,confidence:i,timestamp:Date.now(),sourceTaskId:a?.id};return this.insights.push(o),{insightId:o.id,category:o.category,totalInsights:this.insights.length,totalByCategory:this.getInsightCountByCategory()}}serializeHandoff(e){return{taskId:e.id,status:e.status,description:e.description,constraints:e.constraints,targetDomain:e.targetDomain,decision:e.decision,risks:e.risks,nextSteps:e.nextSteps,pageUrl:e.pageUrl,createdAt:new Date(e.createdAt).toISOString(),completedAt:e.completedAt?new Date(e.completedAt).toISOString():void 0,summary:e.summary,keyFindings:e.keyFindings,artifacts:e.artifacts}}getInsightCountByCategory(){let e={};for(let t of this.insights)e[t.category]=(e[t.category]??0)+1;return e}snapshots=new Map;async handleSavePageSnapshot(e){let n=e.label,r=this.ctx.pageController;if(!r)throw Error(`No page controller available`);let i=await r.getPage();if(!i)throw Error(`No active page to snapshot`);let a=i.url(),o=[];try{let e=await i.createCDPSession();o=(await e.send(`Network.getAllCookies`)).cookies.map(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path})),await e.detach()}catch{}let s={},c={};try{s=await i.evaluate(()=>{let e={};for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n&&(e[n]=window.localStorage.getItem(n)??``)}return e}),c=await i.evaluate(()=>{let e={};for(let t=0;t<window.sessionStorage.length;t++){let n=window.sessionStorage.key(t);n&&(e[n]=window.sessionStorage.getItem(n)??``)}return e})}catch{}let l={id:t().slice(0,8),url:a,cookies:o,localStorage:s,sessionStorage:c,timestamp:Date.now(),label:n};return this.snapshots.set(l.id,l),{snapshotId:l.id,url:l.url,cookieCount:l.cookies.length,localStorageKeys:Object.keys(l.localStorage).length,sessionStorageKeys:Object.keys(l.sessionStorage).length,label:l.label}}async handleRestorePageSnapshot(t){let n=t.snapshotId;if(!n)throw Error(`snapshotId is required`);let r=this.snapshots.get(n);if(!r)throw Error(`Snapshot "${n}" not found`);let i=this.ctx.pageController;if(!i)throw Error(`No page controller available`);let a=await i.getPage();if(!a)throw Error(`No active page for restoration`);if(await a.goto(r.url,{waitUntil:`domcontentloaded`,timeout:e}),r.cookies.length>0)try{let e=await a.createCDPSession();await e.send(`Network.setCookies`,{cookies:r.cookies.map(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path}))}),await e.detach()}catch{}try{await a.evaluate((e,t)=>{window.localStorage.clear();for(let[t,n]of Object.entries(e))window.localStorage.setItem(t,n);window.sessionStorage.clear();for(let[e,n]of Object.entries(t))window.sessionStorage.setItem(e,n)},r.localStorage,r.sessionStorage)}catch{}return{restored:!0,snapshotId:r.id,url:r.url,cookiesRestored:r.cookies.length,localStorageKeysRestored:Object.keys(r.localStorage).length,sessionStorageKeysRestored:Object.keys(r.sessionStorage).length}}async handleListPageSnapshots(){let e=[...this.snapshots.values()].map(e=>({id:e.id,url:e.url,label:e.label,cookieCount:e.cookies.length,localStorageKeys:Object.keys(e.localStorage).length,sessionStorageKeys:Object.keys(e.sessionStorage).length,createdAt:new Date(e.timestamp).toISOString()}));return{snapshots:e,total:e.length}}};export{n as CoordinationHandlers};
1
+ 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 +1 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{t}from"./ToolError-DWU_z7gp.mjs";import{a as n,i as r,r as i,t as a}from"./parse-args-Cuk7-xUt.mjs";import"./definitions-LaYTuwQd.mjs";var o=class{deps;constructor(e){this.deps=e}async handleDebuggerLifecycle(e){return e.action===`enable`?(await this.deps.debuggerManager.init(),await this.deps.runtimeInspector.init(),await this.deps.debuggerManager.initAdvancedFeatures(this.deps.runtimeInspector),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Debugger enabled`,enabled:this.deps.debuggerManager.isEnabled()},null,2)}]}):(await this.deps.debuggerManager.disable(),await this.deps.runtimeInspector.disable(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Debugger disabled`},null,2)}]})}async handleDebuggerPause(e){await this.deps.debuggerManager.pause();try{let e=await this.deps.debuggerManager.waitForPaused(500);return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!0,message:`Execution paused`,reason:e.reason,location:e.callFrames[0]?.location},null,2)}]}}catch{return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!1,message:`Pause requested; no paused event observed yet`},null,2)}]}}}async handleDebuggerResume(e){let t=this.deps.debuggerManager.getPausedState()!==null;return await this.deps.debuggerManager.resume(),{content:[{type:`text`,text:JSON.stringify({success:!0,resumed:t,message:t?`Execution resumed`:`Resume requested; debugger was not paused`},null,2)}]}}},s=class{deps;constructor(e){this.deps=e}async handleDebuggerStepInto(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step while not paused`,hint:`The debugger must be paused at a breakpoint to perform step operations. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepInto(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped into`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step into failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}async handleDebuggerStepOver(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step while not paused`,hint:`The debugger must be paused at a breakpoint to perform step operations. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepOver(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped over`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step over failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}async handleDebuggerStepOut(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step out while not paused`,hint:`The debugger must be paused at a breakpoint to perform step out. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepOut(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped out`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step out failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}},c=class{deps;constructor(e){this.deps=e}async handleDebuggerEvaluate(e){let t=n(e,`expression`,``),r=n(e,`callFrameId`),i=await this.deps.runtimeInspector.evaluate(t,r);return{content:[{type:`text`,text:JSON.stringify({success:!0,expression:t,result:i},null,2)}]}}async handleDebuggerEvaluateGlobal(e){let t=n(e,`expression`,``),r=await this.deps.runtimeInspector.evaluateGlobal(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,expression:t,result:r},null,2)}]}}},l=class{deps;constructor(e){this.deps=e}async handleDebuggerWaitForPaused(e){let n=i(e,`timeout`,3e4);try{let e=await this.deps.debuggerManager.waitForPaused(n);return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!0,reason:e.reason,location:e.callFrames[0]?.location,hitBreakpoints:e.hitBreakpoints},null,2)}]}}catch(e){if(e instanceof t)throw e;return{content:[{type:`text`,text:JSON.stringify({success:!1,paused:!1,message:e instanceof Error?e.message:`Timeout waiting for paused event`},null,2)}]}}}async handleDebuggerGetPausedState(e){let t=this.deps.debuggerManager.getPausedState();return t?{content:[{type:`text`,text:JSON.stringify({paused:!0,reason:t.reason,frameCount:t.callFrames.length,topFrame:{functionName:t.callFrames[0]?.functionName,location:t.callFrames[0]?.location},hitBreakpoints:t.hitBreakpoints,timestamp:t.timestamp},null,2)}]}:{content:[{type:`text`,text:JSON.stringify({paused:!1,message:`Debugger is not paused`},null,2)}]}}async handleGetCallStack(e){let t=await this.deps.runtimeInspector.getCallStack();return t?{content:[{type:`text`,text:JSON.stringify({success:!0,callStack:{frameCount:t.callFrames.length,reason:t.reason,frames:t.callFrames.map((e,t)=>({index:t,callFrameId:e.callFrameId,functionName:e.functionName,location:`${e.location.url}:${e.location.lineNumber}:${e.location.columnNumber}`,scopeCount:e.scopeChain.length}))}},null,2)}]}:{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Not in paused state. Set a breakpoint and trigger it first.`},null,2)}]}}};function u(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var d=class{deps;constructor(e){this.deps=e}async handleSaveSession(e){let t=n(e,`filePath`),i=r(e,`metadata`);try{let e=await this.deps.debuggerManager.saveSession(t,i);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session saved successfully`,filePath:e,breakpointCount:this.deps.debuggerManager.listBreakpoints().length},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to save session`,error:u(e)},null,2)}]}}}async handleLoadSession(e){let t=n(e,`filePath`),r=n(e,`sessionData`);try{if(t)await this.deps.debuggerManager.loadSessionFromFile(t);else if(r)await this.deps.debuggerManager.importSession(r);else throw Error(`Either filePath or sessionData must be provided`);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session loaded successfully`,breakpointCount:this.deps.debuggerManager.listBreakpoints().length,pauseOnExceptions:this.deps.debuggerManager.getPauseOnExceptionsState()},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to load session`,error:u(e)},null,2)}]}}}async handleExportSession(e){let t=r(e,`metadata`);try{let e=this.deps.debuggerManager.exportSession(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session exported successfully`,session:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to export session`,error:u(e)},null,2)}]}}}async handleListSessions(e){try{let e=await this.deps.debuggerManager.listSavedSessions();return{content:[{type:`text`,text:JSON.stringify({success:!0,count:e.length,sessions:e.map(e=>({path:e.path,timestamp:e.timestamp,date:new Date(e.timestamp).toISOString(),metadata:e.metadata}))},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list sessions`,error:u(e)},null,2)}]}}}},f=class{deps;constructor(e){this.deps=e}async handleBreakpointSet(e){let t=n(e,`url`),r=n(e,`scriptId`),a=i(e,`lineNumber`,0),o=i(e,`columnNumber`),s=n(e,`condition`),c;if(t)c=await this.deps.debuggerManager.setBreakpointByUrl({url:t,lineNumber:a,columnNumber:o,condition:s});else if(r)c=await this.deps.debuggerManager.setBreakpoint({scriptId:r,lineNumber:a,columnNumber:o,condition:s});else throw Error(`Either url or scriptId must be provided`);return this.deps.eventBus?.emit(`debugger:breakpoint_hit`,{scriptId:c.location?.scriptId??r??``,lineNumber:c.location?.lineNumber??a,timestamp:new Date().toISOString()}),{content:[{type:`text`,text:JSON.stringify({success:!0,breakpoint:{breakpointId:c.breakpointId,location:c.location,condition:c.condition,enabled:c.enabled}},null,2)}]}}async handleBreakpointRemove(e){let t=n(e,`breakpointId`,``);return await this.deps.debuggerManager.removeBreakpoint(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Breakpoint ${t} removed`},null,2)}]}}async handleBreakpointList(e){let t=this.deps.debuggerManager.listBreakpoints();return{content:[{type:`text`,text:JSON.stringify({count:t.length,breakpoints:t.map(e=>({breakpointId:e.breakpointId,location:e.location,condition:e.condition,enabled:e.enabled,hitCount:e.hitCount}))},null,2)}]}}},p=class{deps;constructor(e){this.deps=e}async handleBreakpointSetOnException(e){let t=n(e,`state`,`none`);return await this.deps.debuggerManager.setPauseOnExceptions(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Pause on exceptions set to: ${t}`,state:t},null,2)}]}}};function m(e){return typeof e.ensureAdvancedFeatures==`function`}function h(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var g=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){m(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async handleXHRBreakpointSet(e){try{let t=n(e,`urlPattern`,``);await this.ensureAdvancedFeaturesIfSupported();let r=await this.deps.debuggerManager.getXHRManager().setXHRBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`XHR breakpoint set`,breakpointId:r,urlPattern:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set XHR breakpoint`,error:h(e)},null,2)}]}}}async handleXHRBreakpointRemove(e){try{let t=n(e,`breakpointId`,``);await this.ensureAdvancedFeaturesIfSupported();let r=await this.deps.debuggerManager.getXHRManager().removeXHRBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:r,message:r?`XHR breakpoint removed`:`XHR breakpoint not found`,breakpointId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove XHR breakpoint`,error:h(e)},null,2)}]}}}async handleXHRBreakpointList(e){try{await this.ensureAdvancedFeaturesIfSupported();let e=this.deps.debuggerManager.getXHRManager().getAllXHRBreakpoints();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} XHR breakpoint(s)`,breakpoints:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list XHR breakpoints`,error:h(e)},null,2)}]}}}};function _(e){return typeof e.ensureAdvancedFeatures==`function`}function v(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var y=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){_(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async handleEventBreakpointSet(e){try{let t=n(e,`eventName`,``),r=n(e,`targetName`);await this.ensureAdvancedFeaturesIfSupported();let i=await this.deps.debuggerManager.getEventManager().setEventListenerBreakpoint(t,r);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Event breakpoint set`,breakpointId:i,eventName:t,targetName:r},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set event breakpoint`,error:v(e)},null,2)}]}}}async handleEventBreakpointSetCategory(e){try{let t=n(e,`category`,``);await this.ensureAdvancedFeaturesIfSupported();let r=this.deps.debuggerManager.getEventManager(),i;switch(t){case`mouse`:i=await r.setMouseEventBreakpoints();break;case`keyboard`:i=await r.setKeyboardEventBreakpoints();break;case`timer`:i=await r.setTimerEventBreakpoints();break;case`websocket`:i=await r.setWebSocketEventBreakpoints();break;default:throw Error(`Unknown category: ${t}`)}return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Set ${i.length} ${t} event breakpoint(s)`,category:t,breakpointIds:i},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set event breakpoints`,error:v(e)},null,2)}]}}}async handleEventBreakpointRemove(e){try{let t=n(e,`breakpointId`,``);await this.ensureAdvancedFeaturesIfSupported();let r=await this.deps.debuggerManager.getEventManager().removeEventListenerBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:r,message:r?`Event breakpoint removed`:`Event breakpoint not found`,breakpointId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove event breakpoint`,error:v(e)},null,2)}]}}}async handleEventBreakpointList(e){try{await this.ensureAdvancedFeaturesIfSupported();let e=this.deps.debuggerManager.getEventManager().getAllEventBreakpoints();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} event breakpoint(s)`,breakpoints:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list event breakpoints`,error:v(e)},null,2)}]}}}};function b(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var x=class{deps;constructor(e){this.deps=e}async handleWatchAdd(e){try{let t=n(e,`expression`,``),r=n(e,`name`),i=this.deps.debuggerManager.getWatchManager().addWatch(t,r);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Watch expression added`,watchId:i,expression:t,name:r||t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add watch expression`,error:b(e)},null,2)}]}}}async handleWatchRemove(e){try{let t=n(e,`watchId`,``),r=this.deps.debuggerManager.getWatchManager().removeWatch(t);return{content:[{type:`text`,text:JSON.stringify({success:r,message:r?`Watch expression removed`:`Watch expression not found`,watchId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove watch expression`,error:b(e)},null,2)}]}}}async handleWatchList(e){try{let e=this.deps.debuggerManager.getWatchManager().getAllWatches();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} watch expression(s)`,watches:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list watch expressions`,error:b(e)},null,2)}]}}}async handleWatchEvaluateAll(e){try{let t=n(e,`callFrameId`),r=await this.deps.debuggerManager.getWatchManager().evaluateAll(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Evaluated ${r.length} watch expression(s)`,results:r},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to evaluate watch expressions`,error:b(e)},null,2)}]}}}async handleWatchClearAll(e){try{return this.deps.debuggerManager.getWatchManager().clearAll(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`All watch expressions cleared`},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to clear watch expressions`,error:b(e)},null,2)}]}}}};const S=(e,t)=>{if(e instanceof Error)return e.message;if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`)return t}return t};var C=class{deps;constructor(e){this.deps=e}async handleGetScopeVariablesEnhanced(e){let t=n(e,`callFrameId`),r=a(e,`includeObjectProperties`),o=i(e,`maxDepth`),s=a(e,`skipErrors`,!0);try{let e=await this.deps.debuggerManager.getScopeVariables({callFrameId:t,includeObjectProperties:r,maxDepth:o,skipErrors:s});return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:S(e,`Failed to get scope variables`),error:String(e)},null,2)}]}}}async handleGetObjectProperties(e){let t=n(e,`objectId`,``);if(!t)return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`objectId parameter is required`},null,2)}]};try{let e=await this.deps.debuggerManager.getObjectPropertiesById(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,propertyCount:e.length,properties:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:S(e,`Failed to get object properties`),error:String(e)},null,2)}]}}}};function w(e){return typeof e.ensureAdvancedFeatures==`function`}function T(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var E=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){w(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async getBlackboxManager(){return await this.ensureAdvancedFeaturesIfSupported(),this.deps.debuggerManager.getBlackboxManager()}async handleBlackboxAdd(e){try{let t=n(e,`urlPattern`,``);return await(await this.getBlackboxManager()).blackboxByPattern(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Script pattern blackboxed`,urlPattern:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add blackbox pattern`,error:T(e)},null,2)}]}}}async handleBlackboxAddCommon(e){try{return await(await this.getBlackboxManager()).blackboxCommonLibraries(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Blackboxed common library patterns`},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add common blackbox patterns`,error:T(e)},null,2)}]}}}async handleBlackboxList(e){try{let e=(await this.getBlackboxManager()).getAllBlackboxedPatterns();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} blackboxed pattern(s)`,patterns:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list blackbox patterns`,error:T(e)},null,2)}]}}}},D=class{debuggerManager;runtimeInspector;debuggerControl;debuggerStepping;debuggerEvaluate;debuggerState;sessionManagement;breakpointBasic;breakpointException;xhrBreakpoint;eventBreakpoint;watchExpressions;scopeInspection;blackbox;constructor(e,t,n){this.debuggerManager=e,this.runtimeInspector=t;let r={debuggerManager:this.debuggerManager,runtimeInspector:this.runtimeInspector};this.debuggerControl=new o(r),this.debuggerStepping=new s({debuggerManager:this.debuggerManager}),this.debuggerEvaluate=new c({runtimeInspector:this.runtimeInspector}),this.debuggerState=new l(r),this.sessionManagement=new d({debuggerManager:this.debuggerManager}),this.breakpointBasic=new f({debuggerManager:this.debuggerManager,eventBus:n}),this.breakpointException=new p({debuggerManager:this.debuggerManager}),this.xhrBreakpoint=new g({debuggerManager:this.debuggerManager}),this.eventBreakpoint=new y({debuggerManager:this.debuggerManager}),this.watchExpressions=new x({debuggerManager:this.debuggerManager}),this.scopeInspection=new C(r),this.blackbox=new E({debuggerManager:this.debuggerManager})}async handleDebuggerLifecycle(e){return this.debuggerControl.handleDebuggerLifecycle(e)}async handleDebuggerPause(e){return this.debuggerControl.handleDebuggerPause(e)}async handleDebuggerResume(e){return this.debuggerControl.handleDebuggerResume(e)}async handleDebuggerStepInto(e){return this.debuggerStepping.handleDebuggerStepInto(e)}async handleDebuggerStepOver(e){return this.debuggerStepping.handleDebuggerStepOver(e)}async handleDebuggerStepOut(e){return this.debuggerStepping.handleDebuggerStepOut(e)}async handleDebuggerEvaluate(e){return this.debuggerEvaluate.handleDebuggerEvaluate(e)}async handleDebuggerEvaluateGlobal(e){return this.debuggerEvaluate.handleDebuggerEvaluateGlobal(e)}async handleDebuggerWaitForPaused(e){return this.debuggerState.handleDebuggerWaitForPaused(e)}async handleDebuggerGetPausedState(e){return this.debuggerState.handleDebuggerGetPausedState(e)}async handleGetCallStack(e){return this.debuggerState.handleGetCallStack(e)}async handleSaveSession(e){return this.sessionManagement.handleSaveSession(e)}async handleLoadSession(e){return this.sessionManagement.handleLoadSession(e)}async handleExportSession(e){return this.sessionManagement.handleExportSession(e)}async handleListSessions(e){return this.sessionManagement.handleListSessions(e)}async handleBreakpointSet(e){return this.breakpointBasic.handleBreakpointSet(e)}async handleBreakpointRemove(e){return this.breakpointBasic.handleBreakpointRemove(e)}async handleBreakpointList(e){return this.breakpointBasic.handleBreakpointList(e)}async handleBreakpointSetOnException(e){return this.breakpointException.handleBreakpointSetOnException(e)}async handleXHRBreakpointSet(e){return this.xhrBreakpoint.handleXHRBreakpointSet(e)}async handleXHRBreakpointRemove(e){return this.xhrBreakpoint.handleXHRBreakpointRemove(e)}async handleXHRBreakpointList(e){return this.xhrBreakpoint.handleXHRBreakpointList(e)}async handleEventBreakpointSet(e){return this.eventBreakpoint.handleEventBreakpointSet(e)}async handleEventBreakpointSetCategory(e){return this.eventBreakpoint.handleEventBreakpointSetCategory(e)}async handleEventBreakpointRemove(e){return this.eventBreakpoint.handleEventBreakpointRemove(e)}async handleEventBreakpointList(e){return this.eventBreakpoint.handleEventBreakpointList(e)}async handleWatchAdd(e){return this.watchExpressions.handleWatchAdd(e)}async handleWatchRemove(e){return this.watchExpressions.handleWatchRemove(e)}async handleWatchList(e){return this.watchExpressions.handleWatchList(e)}async handleWatchEvaluateAll(e){return this.watchExpressions.handleWatchEvaluateAll(e)}async handleWatchClearAll(e){return this.watchExpressions.handleWatchClearAll(e)}async handleGetScopeVariablesEnhanced(e){return this.scopeInspection.handleGetScopeVariablesEnhanced(e)}async handleGetObjectProperties(e){return this.scopeInspection.handleGetObjectProperties(e)}async handleBlackboxAdd(e){return this.blackbox.handleBlackboxAdd(e)}async handleBlackboxAddCommon(e){return this.blackbox.handleBlackboxAddCommon(e)}async handleBlackboxList(e){return this.blackbox.handleBlackboxList(e)}async handleBreakpoint(e){let t=String(e.action??``),n=String(e.type??`code`);switch(n){case`code`:switch(t){case`set`:return this.breakpointBasic.handleBreakpointSet(e);case`remove`:return this.breakpointBasic.handleBreakpointRemove(e);case`list`:return this.breakpointBasic.handleBreakpointList(e)}break;case`xhr`:switch(t){case`set`:return this.xhrBreakpoint.handleXHRBreakpointSet(e);case`remove`:return this.xhrBreakpoint.handleXHRBreakpointRemove(e);case`list`:return this.xhrBreakpoint.handleXHRBreakpointList(e)}break;case`event`:switch(t){case`set`:return this.eventBreakpoint.handleEventBreakpointSet(e);case`remove`:return this.eventBreakpoint.handleEventBreakpointRemove(e);case`list`:return this.eventBreakpoint.handleEventBreakpointList(e)}break;case`event_category`:if(t===`set`)return this.eventBreakpoint.handleEventBreakpointSetCategory(e);break;case`exception`:if(t===`set`)return this.breakpointException.handleBreakpointSetOnException(e);break}return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Invalid breakpoint action/type: ${t}/${n}. Valid types: code, xhr, event, event_category, exception. Valid actions: set, remove, list.`})}]}}async handleWatch(e){let t=String(e.action??``);switch(t){case`add`:return this.watchExpressions.handleWatchAdd(e);case`remove`:return this.watchExpressions.handleWatchRemove(e);case`list`:return this.watchExpressions.handleWatchList(e);case`evaluate_all`:return this.watchExpressions.handleWatchEvaluateAll(e);case`clear_all`:return this.watchExpressions.handleWatchClearAll(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown watch action: ${t}. Valid: add, remove, list, evaluate_all, clear_all`})}]}}}async handleDebuggerStep(e){let t=String(e.direction??`over`);switch(t){case`into`:return this.debuggerStepping.handleDebuggerStepInto(e);case`over`:return this.debuggerStepping.handleDebuggerStepOver(e);case`out`:return this.debuggerStepping.handleDebuggerStepOut(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown direction: ${t}. Valid: into, over, out`})}]}}}async handleDebuggerEvaluateDispatch(e){return String(e.context??`frame`)===`global`?this.debuggerEvaluate.handleDebuggerEvaluateGlobal(e):this.debuggerEvaluate.handleDebuggerEvaluate(e)}async handleDebuggerSession(e){let t=String(e.action??``);switch(t){case`save`:return this.sessionManagement.handleSaveSession(e);case`load`:return this.sessionManagement.handleLoadSession(e);case`export`:return this.sessionManagement.handleExportSession(e);case`list`:return this.sessionManagement.handleListSessions(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown action: ${t}. Valid actions: save, load, export, list`})}]}}}};export{D as DebuggerToolHandlers};
1
+ 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 +1 @@
1
- import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`proxy_start`,e=>e.desc(`Start the local HTTP/HTTPS interception proxy with optional TLS.`).number(`port`,`Listen port.`,{default:8080}).boolean(`useHttps`,`Enable HTTPS interception.`,{default:!0})),e(`proxy_stop`,e=>e.desc(`Stop the proxy and release all active rules.`).destructive()),e(`proxy_status`,e=>e.desc(`Report proxy status, listen port, and CA certificate path.`).query()),e(`proxy_export_ca`,e=>e.desc(`Read the proxy CA certificate.`).query()),e(`proxy_add_rule`,e=>e.desc(`Add an interception rule: forward, mock response, or block.`).string(`action`,`Rule action: forward, mock_response, or block.`).string(`method`,`HTTP method to match.`,{default:`GET`}).string(`urlPattern`,`URL matcher string or regex literal.`).number(`mockStatus`,`Response status for mock_response.`,{default:200}).string(`mockBody`,`Response body for mock_response.`).required(`action`)),e(`proxy_get_requests`,e=>e.desc(`Read captured proxy requests.`).string(`urlFilter`,`Optional URL filter.`).query()),e(`proxy_clear_logs`,e=>e.desc(`Clear all captured proxy request/response logs.`).resettable()),e(`proxy_setup_adb_device`,e=>e.desc(`Configure an Android device to use the proxy.`).string(`deviceSerial`,`ADB device serial.`))];export{t};
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`proxy_start`,e=>e.desc(`Start the local HTTP/HTTPS interception proxy with optional TLS.`).number(`port`,`Listen port.`,{default:8080}).boolean(`useHttps`,`Enable HTTPS interception.`,{default:!0})),e(`proxy_stop`,e=>e.desc(`Stop the proxy and release all active rules.`).destructive()),e(`proxy_status`,e=>e.desc(`Report proxy status, listen port, and CA certificate path.`).query()),e(`proxy_export_ca`,e=>e.desc(`Read the proxy CA certificate.`).query()),e(`proxy_add_rule`,e=>e.desc(`Add an interception rule: forward, mock response, or block.`).string(`action`,`Rule action: forward, mock_response, or block.`).string(`method`,`HTTP method to match.`,{default:`GET`}).string(`urlPattern`,`URL matcher string or regex literal.`).number(`mockStatus`,`Response status for mock_response.`,{default:200}).string(`mockBody`,`Response body for mock_response.`).required(`action`)),e(`proxy_get_requests`,e=>e.desc(`Read captured proxy requests.`).string(`urlFilter`,`Optional URL filter.`).query()),e(`proxy_clear_logs`,e=>e.desc(`Clear all captured proxy request/response logs.`).resettable()),e(`proxy_setup_adb_device`,e=>e.desc(`Configure an Android device to use the proxy.`).string(`deviceSerial`,`ADB device serial.`))];export{t};
@@ -1 +1 @@
1
- import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`sourcemap_discover`,e=>e.desc(`Discover source maps on the current page.`).boolean(`includeInline`,`Include inline data: source maps.`,{default:!0})),e(`sourcemap_fetch_and_parse`,e=>e.desc(`Fetch a source map from URL and parse to original sources.`).string(`sourceMapUrl`,`Source map URL.`).string(`scriptUrl`,`Script URL for relative map resolution.`).required(`sourceMapUrl`)),e(`sourcemap_coverage`,e=>e.desc(`Summarize mapped and unmapped source coverage.`).string(`sourceMapUrl`,`Source map URL.`).string(`scriptUrl`,`Script URL for relative map resolution.`).required(`sourceMapUrl`)),e(`sourcemap_lookup`,e=>e.desc(`Resolve generated code position to original source.`).string(`sourceMapUrl`,`Source map URL.`).string(`scriptUrl`,`Script URL for relative map resolution.`).number(`line`,`Generated line number.`,{minimum:1}).number(`column`,`Generated column number.`,{minimum:0}).required(`sourceMapUrl`,`line`,`column`)),e(`sourcemap_reconstruct_tree`,e=>e.desc(`Reconstruct source files from a source map.`).string(`sourceMapUrl`,`Source map URL.`).string(`outputDir`,`Output directory under the project root.`).required(`sourceMapUrl`)),e(`sourcemap_parse_v4`,e=>e.desc(`Parse source map with ECMA-426 v4 scope/debug-id support; falls back to v3.`).string(`sourceMapUrl`,`Source map URL to parse.`).boolean(`extractScopes`,`Extract and decode scope information from v4 x_scopes field`,{default:!0}).boolean(`extractDebugIds`,`Extract debug-id mappings for source correlation`,{default:!0}).boolean(`compareV3`,`Compare v4 fields against v3 baseline and report differences`,{default:!1}).required(`sourceMapUrl`))];export{t};
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`sourcemap_discover`,e=>e.desc(`Discover source maps on the current page.`).boolean(`includeInline`,`Include inline data: source maps.`,{default:!0})),e(`sourcemap_fetch_and_parse`,e=>e.desc(`Fetch a source map from URL and parse to original sources.`).string(`sourceMapUrl`,`Source map URL.`).string(`scriptUrl`,`Script URL for relative map resolution.`).required(`sourceMapUrl`)),e(`sourcemap_coverage`,e=>e.desc(`Summarize mapped and unmapped source coverage.`).string(`sourceMapUrl`,`Source map URL.`).string(`scriptUrl`,`Script URL for relative map resolution.`).required(`sourceMapUrl`)),e(`sourcemap_lookup`,e=>e.desc(`Resolve generated code position to original source.`).string(`sourceMapUrl`,`Source map URL.`).string(`scriptUrl`,`Script URL for relative map resolution.`).number(`line`,`Generated line number.`,{minimum:1}).number(`column`,`Generated column number.`,{minimum:0}).required(`sourceMapUrl`,`line`,`column`)),e(`sourcemap_reconstruct_tree`,e=>e.desc(`Reconstruct source files from a source map.`).string(`sourceMapUrl`,`Source map URL.`).string(`outputDir`,`Output directory under the project root.`).required(`sourceMapUrl`)),e(`sourcemap_parse_v4`,e=>e.desc(`Parse source map with ECMA-426 v4 scope/debug-id support; falls back to v3.`).string(`sourceMapUrl`,`Source map URL to parse.`).boolean(`extractScopes`,`Extract and decode scope information from v4 x_scopes field`,{default:!0}).boolean(`extractDebugIds`,`Extract debug-id mappings for source correlation`,{default:!0}).boolean(`compareV3`,`Compare v4 fields against v3 baseline and report differences`,{default:!1}).required(`sourceMapUrl`))];export{t};
@@ -1 +1 @@
1
- import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`platform_capabilities`,e=>e.desc(`Report platform tool backend availability.`).query()),e(`miniapp_pkg_scan`,e=>e.desc(`Scan local directories for miniapp package files.`).string(`searchPath`,`可选。指定扫描根目录;不提供时使用默认路径(MiniApp/Cache 与 MiniApp/Plugin)。`)),e(`miniapp_pkg_unpack`,e=>e.desc(`Unpack a miniapp package.`).string(`inputPath`,`必填。小程序包文件路径。`).string(`outputDir`,`可选。输出目录;不提供时自动生成 artifacts 临时目录。`).required(`inputPath`)),e(`miniapp_pkg_analyze`,e=>e.desc(`Analyze an unpacked miniapp package.`).string(`unpackedDir`,`必填。已解包目录路径。`).required(`unpackedDir`)),e(`asar_extract`,e=>e.desc(`Extract and list files from an Electron ASAR package.`).string(`inputPath`,`必填。asar 文件路径。`).string(`outputDir`,`可选。提取目录;不提供时自动生成 artifacts 临时目录。`).boolean(`listOnly`,`可选。默认 false;true 时仅列出文件清单,不执行提取。`,{default:!1}).required(`inputPath`)),e(`electron_inspect_app`,e=>e.desc(`Analyze Electron app structure: main/renderer entry, preload, IPC.`).string(`appPath`,`Path to Electron app (.exe or app directory)`).required(`appPath`)),e(`electron_scan_userdata`,e=>e.desc(`Scan a directory for Electron JSON userdata files.`).string(`dirPath`,`Directory path to scan for JSON files`).number(`maxFiles`,`可选。最多读取的 JSON 文件数量。默认 20。`,{default:20,minimum:1,maximum:1e4}).number(`maxFileSizeKB`,`可选。单个文件大小上限(KB)。超限文件跳过。默认 1024。`,{default:1024,minimum:1,maximum:102400}).required(`dirPath`).query()),e(`asar_search`,e=>e.desc(`Grep text patterns inside ASAR archive contents without extraction.`).string(`inputPath`,`必填。ASAR 文件路径。`).string(`pattern`,`必填。正则表达式字符串。`).string(`fileGlob`,`可选。文件扩展名过滤。默认 *.js。`,{default:`*.js`}).number(`maxResults`,`可选。最大返回匹配数。默认 100。`,{default:100,minimum:1,maximum:1e4}).required(`inputPath`,`pattern`).query()),e(`electron_check_fuses`,e=>e.desc(`Read Electron fuse states.`).string(`exePath`,`必填。Electron .exe 文件路径。`).required(`exePath`).query()),e(`electron_patch_fuses`,e=>e.desc(`Patch Electron fuse states.`).string(`exePath`,`Electron .exe file path`).enum(`profile`,[`debug`,`custom`],`Patch profile. "debug" enables debug-related fuses. "custom" requires a fuses object.`,{default:`debug`}).object(`fuses`,{},`For profile="custom". Map of fuse names to ENABLE/DISABLE. E.g. {"RunAsNode": "ENABLE"}.`).boolean(`createBackup`,`Create a .exe.bak backup before patching.`,{default:!0}).required(`exePath`).destructive()),e(`v8_bytecode_decompile`,e=>e.desc(`Decompile or extract strings from V8 bytecode files.`).string(`filePath`,`Path to .jsc bytecode file`).required(`filePath`).query()),e(`electron_launch_debug`,e=>e.desc(`Launch Electron with main and renderer CDP ports.`).string(`exePath`,`Electron .exe file path`).number(`mainPort`,`Main process inspect port.`,{default:9229,minimum:1,maximum:65535}).number(`rendererPort`,`Renderer remote debugging port.`,{default:9222,minimum:1,maximum:65535}).array(`args`,{type:`string`},`Extra command-line arguments.`).boolean(`skipFuseCheck`,`Skip fuse status check.`,{default:!1}).number(`waitMs`,`Milliseconds to wait for CDP ports.`,{default:8e3,minimum:1e3,maximum:12e4}).requiredOpenWorld(`exePath`)),e(`electron_debug_status`,e=>e.desc(`Check status of dual-CDP debug sessions launched by electron_launch_debug.`).string(`sessionId`,`Optional. Check specific session. Omit to list all.`).query()),e(`electron_ipc_sniff`,e=>e.desc(`Monitor Electron IPC messages.`).enum(`action`,[`start`,`dump`,`stop`,`list`,`guide`],`Action to perform.`,{default:`guide`}).number(`port`,`Renderer CDP port (--remote-debugging-port).`,{default:9222,minimum:1,maximum:65535}).string(`sessionId`,`Session ID for dump/stop.`).boolean(`clear`,`Clear captured messages after dump.`,{default:!0}).openWorld())];export{t};
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`platform_capabilities`,e=>e.desc(`Report platform tool backend availability.`).query()),e(`miniapp_pkg_scan`,e=>e.desc(`Scan local directories for miniapp package files.`).string(`searchPath`,`可选。指定扫描根目录;不提供时使用默认路径(MiniApp/Cache 与 MiniApp/Plugin)。`)),e(`miniapp_pkg_unpack`,e=>e.desc(`Unpack a miniapp package.`).string(`inputPath`,`必填。小程序包文件路径。`).string(`outputDir`,`可选。输出目录;不提供时自动生成 artifacts 临时目录。`).required(`inputPath`)),e(`miniapp_pkg_analyze`,e=>e.desc(`Analyze an unpacked miniapp package.`).string(`unpackedDir`,`必填。已解包目录路径。`).required(`unpackedDir`)),e(`asar_extract`,e=>e.desc(`Extract and list files from an Electron ASAR package.`).string(`inputPath`,`必填。asar 文件路径。`).string(`outputDir`,`可选。提取目录;不提供时自动生成 artifacts 临时目录。`).boolean(`listOnly`,`可选。默认 false;true 时仅列出文件清单,不执行提取。`,{default:!1}).required(`inputPath`)),e(`electron_inspect_app`,e=>e.desc(`Analyze Electron app structure: main/renderer entry, preload, IPC.`).string(`appPath`,`Path to Electron app (.exe or app directory)`).required(`appPath`)),e(`electron_scan_userdata`,e=>e.desc(`Scan a directory for Electron JSON userdata files.`).string(`dirPath`,`Directory path to scan for JSON files`).number(`maxFiles`,`可选。最多读取的 JSON 文件数量。默认 20。`,{default:20,minimum:1,maximum:1e4}).number(`maxFileSizeKB`,`可选。单个文件大小上限(KB)。超限文件跳过。默认 1024。`,{default:1024,minimum:1,maximum:102400}).required(`dirPath`).query()),e(`asar_search`,e=>e.desc(`Grep text patterns inside ASAR archive contents without extraction.`).string(`inputPath`,`必填。ASAR 文件路径。`).string(`pattern`,`必填。正则表达式字符串。`).string(`fileGlob`,`可选。文件扩展名过滤。默认 *.js。`,{default:`*.js`}).number(`maxResults`,`可选。最大返回匹配数。默认 100。`,{default:100,minimum:1,maximum:1e4}).required(`inputPath`,`pattern`).query()),e(`electron_check_fuses`,e=>e.desc(`Read Electron fuse states.`).string(`exePath`,`必填。Electron .exe 文件路径。`).required(`exePath`).query()),e(`electron_patch_fuses`,e=>e.desc(`Patch Electron fuse states.`).string(`exePath`,`Electron .exe file path`).enum(`profile`,[`debug`,`custom`],`Patch profile. "debug" enables debug-related fuses. "custom" requires a fuses object.`,{default:`debug`}).object(`fuses`,{},`For profile="custom". Map of fuse names to ENABLE/DISABLE. E.g. {"RunAsNode": "ENABLE"}.`).boolean(`createBackup`,`Create a .exe.bak backup before patching.`,{default:!0}).required(`exePath`).destructive()),e(`v8_bytecode_decompile`,e=>e.desc(`Decompile or extract strings from V8 bytecode files.`).string(`filePath`,`Path to .jsc bytecode file`).required(`filePath`).query()),e(`electron_launch_debug`,e=>e.desc(`Launch Electron with main and renderer CDP ports.`).string(`exePath`,`Electron .exe file path`).number(`mainPort`,`Main process inspect port.`,{default:9229,minimum:1,maximum:65535}).number(`rendererPort`,`Renderer remote debugging port.`,{default:9222,minimum:1,maximum:65535}).array(`args`,{type:`string`},`Extra command-line arguments.`).boolean(`skipFuseCheck`,`Skip fuse status check.`,{default:!1}).number(`waitMs`,`Milliseconds to wait for CDP ports.`,{default:8e3,minimum:1e3,maximum:12e4}).requiredOpenWorld(`exePath`)),e(`electron_debug_status`,e=>e.desc(`Check status of dual-CDP debug sessions launched by electron_launch_debug.`).string(`sessionId`,`Optional. Check specific session. Omit to list all.`).query()),e(`electron_ipc_sniff`,e=>e.desc(`Monitor Electron IPC messages.`).enum(`action`,[`start`,`dump`,`stop`,`list`,`guide`],`Action to perform.`,{default:`guide`}).number(`port`,`Renderer CDP port (--remote-debugging-port).`,{default:9222,minimum:1,maximum:65535}).string(`sessionId`,`Session ID for dump/stop.`).boolean(`clear`,`Clear captured messages after dump.`,{default:!0}).openWorld())];export{t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`get_token_budget_stats`,e=>e.desc(`Get token budget usage stats, warnings, and optimization suggestions.`).query()),e(`manual_token_cleanup`,e=>e.desc(`Clear stale entries and reset counters to free 10-30% of token budget.`)),e(`reset_token_budget`,e=>e.desc(`Hard-reset all token budget counters. Destructive — prefer manual_token_cleanup.`).destructive())],n=[e(`list_extensions`,e=>e.desc(`List all loaded plugins, workflows, and extension tools.`).query()),e(`reload_extensions`,e=>e.desc(`Reload plugins and workflows from configured directories, and directly register extension tools visible in the current profile.`).openWorld()),e(`browse_extension_registry`,e=>e.desc(`Browse the online extension registry for installable plugins and workflows.`).enum(`kind`,[`plugin`,`workflow`,`all`],`Filter by extension kind`,{default:`all`}).query()),e(`install_extension`,e=>e.desc(`Install an extension from the remote registry.`).string(`slug`,`Extension slug from the registry`).string(`targetDir`,`Target directory override`).requiredOpenWorld(`slug`))],r=[e(`get_cache_stats`,e=>e.desc(`Get cache statistics: entries, sizes, hit rates, and cleanup recommendations.`).query()),e(`smart_cache_cleanup`,e=>e.desc(`Evict LRU and stale entries while preserving hot data.`).number(`targetSize`,`Target size in bytes`)),e(`clear_all_caches`,e=>e.desc(`Clear all internal caches. Destructive — prefer smart_cache_cleanup.`).destructive())],i=[e(`cleanup_artifacts`,e=>e.desc(`Clean generated artifacts by age and size.`).number(`retentionDays`,`Override retention window in days`).number(`maxTotalBytes`,`Override maximum retained bytes`).boolean(`dryRun`,`Preview removals without deleting`).destructive()),e(`doctor_environment`,e=>e.desc(`Run environment doctor: dependencies, bridges, platform limits.`).boolean(`includeBridgeHealth`,`Probe native-bridge / Burp endpoints`).readOnly())];export{t as i,r as n,n as r,i as t};
@@ -1 +1 @@
1
- import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`state_board`,e=>e.desc(`CRUD operations on the cross-tool shared state board.`).enum(`action`,[`set`,`get`,`delete`,`list`,`history`,`clear`],`Operation to perform`).string(`key`,`Key name (required for set/get/delete/history)`).prop(`value`,{type:`object`,description:`Value to store`}).string(`namespace`,`Namespace for key isolation`).number(`ttlSeconds`,`TTL in seconds`).boolean(`includeValues`,`Include current values in list results`,{default:!1}).number(`limit`,`Maximum history entries to return`,{default:50}).string(`keyPattern`,`Key pattern filter`).required(`action`)),e(`state_board_watch`,e=>e.desc(`Watch state board keys for changes with configurable polling.`).enum(`action`,[`start`,`poll`,`stop`],`Watch operation: start watching, poll for changes, or stop watching`).string(`key`,`Key or pattern to watch`).string(`namespace`,`Namespace`).number(`pollIntervalMs`,`Polling interval in milliseconds`).string(`watchId`,`Watch ID`).required(`action`)),e(`state_board_io`,e=>e.desc(`Serialize state board to JSON or restore from a previous export.`).enum(`action`,[`export`,`import`],`IO operation`).string(`namespace`,`Namespace filter or target namespace`).string(`keyPattern`,`Key pattern filter`).prop(`data`,{type:`object`,description:`Entries to import`}).boolean(`overwrite`,`Overwrite existing keys on import`).required(`action`))];export{t};
1
+ 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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`dart_strings_extract`,e=>e.desc(`Stream-extract ASCII/UTF-16LE strings from a Dart AOT libapp.so and classify them (urls, paths, classNames, packageRefs, cryptoKeywords, plus customRules). ReDoS-guarded.`).string(`filePath`,`Absolute path to the libapp.so (or arbitrary binary) to extract from`).number(`minLength`,`Minimum string length to emit`,{default:4,minimum:2,maximum:64}).boolean(`includeRaw`,"Include unclassified strings under the `raw` bucket",{default:!1}).boolean(`includeOffsets`,`Include byte offsets[] for each extracted string`,{default:!0}).enum(`encoding`,[`ascii`,`utf16le`,`both`],`Which encodings to scan`,{default:`both`}).number(`maxChunkBytes`,`Streaming chunk size in bytes`).number(`maxOffsetsPerString`,`Cap on offsets recorded per string (excess sets truncated)`,{default:1e3}).enum(`ruleMode`,[`append`,`prepend`,`replace`],`How customRules interact with DEFAULT_RULES`,{default:`append`}).number(`regexTimeoutMs`,`Per-rule .test() wall-clock budget for the ReDoS guard`).number(`scanStride`,`Only emit hits whose offset is divisible by stride (e.g. 4 for pointer-aligned scans)`).object(`scanWindow`,{start:{type:`number`,description:`Inclusive start byte offset`},end:{type:`number`,description:`Exclusive end byte offset`}},`Restrict scanning to a byte range (skip ELF headers, focus on a section, etc.)`).array(`customRules`,{type:`object`,properties:{category:{type:`string`,description:`Category bucket name for matched strings`},pattern:{type:`string`,description:`Regex source (anchored as needed)`},flags:{type:`string`,description:`Regex flags (must be in DART_ALLOWED_REGEX_FLAGS)`},exclude:{type:`string`,description:`Optional exclude regex applied before category match`},excludeFlags:{type:`string`,description:`Flags for the exclude regex`},confidence:{type:`number`,description:`Confidence weight in [0,1] carried onto each matching hit`},enableWhenFileNameMatches:{type:`string`,description:`Rule only fires when source basename matches this regex`},enableWhenFileNameFlags:{type:`string`,description:`Flags for enableWhenFileNameMatches`}},required:[`category`,`pattern`]},`Custom classification rules with safe regex compilation (ReDoS-guarded)`).required(`filePath`).query()),e(`dart_smi_scan`,e=>e.desc(`Recover Dart Small Integer (Smi) constants from a libapp.so by reading aligned little-endian words and stripping the heap-pointer tag bit.`).string(`filePath`,`Absolute path to the libapp.so (or arbitrary binary) to scan`).enum(`width`,[`4`,`8`],`Word width in bytes (4 for ARM32, 8 for ARM64)`,{default:`8`}).number(`stride`,"Bytes between consecutive scan positions; defaults to `width`").number(`minValue`,`Inclusive minimum decoded Smi value`,{default:1}).number(`maxValue`,`Inclusive maximum decoded Smi value`,{default:1e6}).boolean(`includeZero`,`Include decoded-to-zero hits`,{default:!1}).boolean(`includeNegative`,`Include decoded-to-negative hits`,{default:!1}).number(`maxResults`,`Cap on returned hits (truncates with truncated=true)`).number(`maxChunkBytes`,`Streaming chunk size in bytes`).object(`scanWindow`,{start:{type:`number`,description:`Inclusive start byte offset`},end:{type:`number`,description:`Exclusive end byte offset`}},`Restrict scanning to a byte range`).required(`filePath`).query()),e(`dart_symbolize`,e=>e.desc(`Resolve obfuscated Dart identifiers using a developer-supplied Flutter --save-obfuscation-map JSON (flat, pairs, or object shape).`).string(`obfuscationMapFile`,"Absolute path to the obfuscation-map.json emitted by `flutter build ... --extra-gen-snapshot-options=--save-obfuscation-map=FILE`").array(`obfuscatedNames`,{type:`string`,description:`An obfuscated (or original, in reverse mode) identifier`},`List of identifiers to resolve against the map`).enum(`format`,[`auto`,`flat`,`pairs`,`object`],`Force a specific parser; auto sniffs the JSON shape`,{default:`auto`}).enum(`mode`,[`forward`,`reverse`],`Lookup direction (forward: obfuscated→original, reverse: original→obfuscated)`,{default:`forward`}).number(`maxMapBytes`,`Cap on map file size in bytes`,{default:16*1024*1024}).number(`maxLookups`,`Cap on number of lookups attempted (extras go to unresolved)`).required(`obfuscationMapFile`,`obfuscatedNames`).query()),e(`flutter_packages_detect`,e=>e.desc("Detect third-party Dart `package:` refs in a Flutter libapp.so, aggregated and SDK-stdlib-filtered.").string(`filePath`,`Absolute path to the libapp.so (or arbitrary binary) to scan`).boolean(`includeFlutterStdlib`,`Keep Flutter SDK packages in the result`,{default:!1}).boolean(`includeFiles`,"Emit the list of `package:foo/...` files per package",{default:!0}).boolean(`includeOffsets`,`Emit aggregated byte offsets per package`,{default:!1}).integer(`maxFilesPerPackage`,`Per-package file cap (excess marks filesTruncated)`,{minimum:1}).integer(`maxPackages`,`Global package cap (excess marks truncated:true)`,{minimum:1}).array(`extraStdlibPackages`,{type:`string`,minLength:1,maxLength:128},`Additional package names to treat as stdlib (filtered when includeFlutterStdlib=false)`).required(`filePath`).query()),e(`dart_snapshot_header_parse`,e=>e.desc(`Parse the Dart isolate snapshot header in a libapp.so: magic, kind, 32-byte hash, features, target arch. Read-only.`).string(`filePath`,`Absolute path to the libapp.so to parse`).number(`maxScanBytes`,`Upper bound on the byte-scan fallback (defaults to env)`,{minimum:0}).required(`filePath`).query()),e(`dart_version_fingerprint`,e=>e.desc(`Identify Flutter/Dart SDK release from a libapp.so by combining header parse with a built-in (and optionally user-supplied) hash table.`).string(`filePath`,`Absolute path to the libapp.so to fingerprint`).boolean(`includeFeatures`,`Include the raw features array in the response`,{default:!0}).string(`customTablePath`,`Optional path to a JSON file extending the built-in hash table (user wins on collision)`).required(`filePath`).query()),e(`dart_object_pool_dump`,e=>e.desc(`Read-only static dump of the Dart isolate ObjectPool in a libapp.so: classify each slot as smi/mint/double/string/classRef/functionRef/pool/null/unknown.`).string(`filePath`,`Absolute path to the libapp.so to dump`).number(`maxSlots`,`Upper bound on emitted slots (defaults to env)`,{minimum:1}).number(`previewBytes`,`String slot preview byte cap (defaults to env)`,{minimum:0}).string(`grammar`,`Force a cluster grammar by sdkFamily (e.g. "2.10", "2.17", "3.0+"); overrides auto-pick`).object(`fingerprint`,{flutterVersion:{type:`string`},dartSdkRev:{type:`string`},targetArch:{type:`string`}},`Optional pre-supplied snapshot fingerprint to skip internal lookup`).required(`filePath`).query())];export{t};
@@ -1 +1 @@
1
- import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`binary_detect_format`,e=>e.desc(`Detect binary payload format and encoding signals.`).enum(`source`,[`base64`,`hex`,`file`,`raw`],`How to interpret input payload`).string(`data`,`Input payload for base64/hex/raw sources`).string(`filePath`,`File path when source=file`).string(`requestId`,`Captured requestId when a response body is available`).required(`source`).query()),e(`binary_decode`,e=>e.desc(`Decode binary payloads into hex, utf8, or json output.`).string(`data`,`Input encoded payload`).enum(`encoding`,[`base64`,`hex`,`url`,`protobuf`,`msgpack`],`Declared input encoding`).enum(`outputFormat`,[`hex`,`utf8`,`json`],`Target output format`,{default:`hex`}).required(`data`,`encoding`).query()),e(`binary_encode`,e=>e.desc(`Encode utf8/hex/json input into base64/hex/url output.`).string(`data`,`Input payload`).enum(`inputFormat`,[`utf8`,`hex`,`json`],`How to parse input`).enum(`outputEncoding`,[`base64`,`hex`,`url`],`Desired output encoding`).required(`data`,`inputFormat`,`outputEncoding`).query()),e(`binary_entropy_analysis`,e=>e.desc(`Compute entropy and byte frequency for a payload.`).enum(`source`,[`base64`,`hex`,`raw`,`file`],`How to interpret input payload`).string(`data`,`Input payload for base64/hex/raw sources`).string(`filePath`,`File path when source=file`).number(`blockSize`,`Block size for per-block entropy`,{default:256,minimum:16,maximum:8192}).required(`source`).query()),e(`protobuf_decode_raw`,e=>e.desc(`Decode protobuf bytes without a schema.`).string(`data`,`Base64-encoded protobuf payload`).number(`maxDepth`,`Maximum recursive decode depth`,{default:5,minimum:1,maximum:20}).required(`data`).query())];export{t};
1
+ import{t as e}from"./tool-builder-qif8M9-K.mjs";const t=[e(`binary_detect_format`,e=>e.desc(`Detect binary payload format and encoding signals.`).enum(`source`,[`base64`,`hex`,`file`,`raw`],`How to interpret input payload`).string(`data`,`Input payload for base64/hex/raw sources`).string(`filePath`,`File path when source=file`).string(`requestId`,`Captured requestId when a response body is available`).required(`source`).query()),e(`binary_decode`,e=>e.desc(`Decode binary payloads into hex, utf8, or json output.`).string(`data`,`Input encoded payload`).enum(`encoding`,[`base64`,`hex`,`url`,`protobuf`,`msgpack`],`Declared input encoding`).enum(`outputFormat`,[`hex`,`utf8`,`json`],`Target output format`,{default:`hex`}).required(`data`,`encoding`).query()),e(`binary_encode`,e=>e.desc(`Encode utf8/hex/json input into base64/hex/url output.`).string(`data`,`Input payload`).enum(`inputFormat`,[`utf8`,`hex`,`json`],`How to parse input`).enum(`outputEncoding`,[`base64`,`hex`,`url`],`Desired output encoding`).required(`data`,`inputFormat`,`outputEncoding`).query()),e(`binary_entropy_analysis`,e=>e.desc(`Compute entropy and byte frequency for a payload.`).enum(`source`,[`base64`,`hex`,`raw`,`file`],`How to interpret input payload`).string(`data`,`Input payload for base64/hex/raw sources`).string(`filePath`,`File path when source=file`).number(`blockSize`,`Block size for per-block entropy`,{default:256,minimum:16,maximum:8192}).required(`source`).query()),e(`protobuf_decode_raw`,e=>e.desc(`Decode protobuf bytes without a schema.`).string(`data`,`Base64-encoded protobuf payload`).number(`maxDepth`,`Maximum recursive decode depth`,{default:5,minimum:1,maximum:20}).required(`data`).query())];export{t};