@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.
- package/LICENSE +661 -661
- package/README.md +11 -3
- package/README.zh.md +11 -3
- package/dist/{AntiCheatDetector-CGVGNfy5.mjs → AntiCheatDetector-B6d4Qe9D.mjs} +1 -1
- package/dist/BrowserSessionCoordinator-BJ-HOxo0.mjs +1 -0
- package/dist/{CodeInjector-BlgyqTOk.mjs → CodeInjector-Cll_7bLJ.mjs} +1 -1
- package/dist/ConsoleMonitor-CxDJV15E.mjs +306 -0
- package/dist/DOMInspector-C19J4zeq.mjs +95 -0
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +1 -0
- package/dist/ExtensionManager-BD724zkO.mjs +1 -0
- package/dist/ExtensionManager.tools-oVMJgPcN.mjs +1 -0
- package/dist/{HardwareBreakpoint-OcJqNFVc.mjs → HardwareBreakpoint-BUfPdp0f.mjs} +1 -1
- package/dist/{HeapAnalyzer-CqAxZzeS.mjs → HeapAnalyzer-B_aqY8oj.mjs} +1 -1
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +1 -0
- package/dist/MemoryController-X1XNSn1n.mjs +2 -0
- package/dist/{MemoryScanSession-CaxAjZJf.mjs → MemoryScanSession-DG_F-PjE.mjs} +1 -1
- package/dist/{MemoryScanner-BLYnMJy6.mjs → MemoryScanner-g1_L1ub5.mjs} +1 -1
- package/dist/{NativeMemoryManager.impl-CI554XbY.mjs → NativeMemoryManager.impl-DniBe2wf.mjs} +1 -1
- package/dist/{NativeMemoryManager.utils-DM4NC3FE.mjs → NativeMemoryManager.utils-BHy1P_jM.mjs} +1 -1
- package/dist/NetworkMonitor-B_-au6aV.mjs +185 -0
- package/dist/{PEAnalyzer-DJyaJTQJ.mjs → PEAnalyzer-yWQaGrcx.mjs} +1 -1
- package/dist/PageController-Dfsm1_o7.mjs +1 -0
- package/dist/{PointerChainEngine-5nF9eNlu.mjs → PointerChainEngine-BhCUkmxY.mjs} +1 -1
- package/dist/ProcessRegistry-C-bN48oR.mjs +1 -0
- package/dist/{ResponseBuilder-B2lu4KEl.mjs → ResponseBuilder-BfWP-uaT.mjs} +1 -1
- package/dist/RingBuffer-Dm54ELKT.mjs +1 -0
- package/dist/{ScriptManager-fgqiALgj.mjs → ScriptManager-LWGPTdvD.mjs} +1 -1
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +1 -0
- package/dist/{Speedhack-l6s8L2Qw.mjs → Speedhack-yseDPSZ9.mjs} +1 -1
- package/dist/{StructureAnalyzer-A-WamfYE.mjs → StructureAnalyzer-C5lpuZkg.mjs} +1 -1
- package/dist/ToolCatalog-CYdD9F5f.mjs +1 -0
- package/dist/ToolProbe-C7ZU2x7M.mjs +1 -0
- package/dist/ToolRegistry-C5oB8KP8.mjs +1 -0
- package/dist/{ToolRouter.policy-CFHoN_Lw.mjs → ToolRouter.policy-CfhJczkt.mjs} +2 -2
- package/dist/{TraceRecorder-Dd8jLXpi.mjs → TraceRecorder-BiJWBXHX.mjs} +1 -1
- package/dist/{Win32Debug-CQteFL4F.mjs → Win32Debug-CYrIQBvr.mjs} +1 -1
- package/dist/{WorkflowEngine-CxEp2WXH.mjs → WorkflowEngine-D876meOO.mjs} +1 -1
- package/dist/analysis-D4swdMvq.mjs +6 -0
- package/dist/{antidebug-BOTZH6-0.mjs → antidebug-7L3ygj_9.mjs} +4 -4
- package/dist/apk-packer-BqXcInnX.mjs +1 -0
- package/dist/{artifactRetention-NBdncOEW.mjs → artifactRetention-BCPQASm7.mjs} +1 -1
- package/dist/{artifacts-B5xQuEa_.mjs → artifacts-CkodUM4j.mjs} +1 -1
- package/dist/betterSqlite3-Brtq-SIQ.mjs +1 -0
- package/dist/{binary-instrument-Cf9qqLlM.mjs → binary-instrument-DU7V6TUM.mjs} +1 -1
- package/dist/binary-secrets-PdMVoyt0.mjs +1 -0
- package/dist/{boringssl-inspector-BST5vtKx.mjs → boringssl-inspector-BBaJwwkU.mjs} +1 -1
- package/dist/browser-Qqco2rOT.mjs +11 -0
- package/dist/collector-Bpl6qy2L.mjs +1 -0
- package/dist/constants-BYj8Xek8.mjs +1 -0
- package/dist/{coordination-BbijHEHH.mjs → coordination-CWXW1o8K.mjs} +1 -1
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/{debugger-CRJq_krh.mjs → debugger-DyALjYMk.mjs} +1 -1
- package/dist/{definitions-DZ8uKusP.mjs → definitions-BWxBke3r.mjs} +1 -1
- package/dist/{definitions-CYFbewnd.mjs → definitions-BYwATKc-.mjs} +1 -1
- package/dist/{definitions-DJklW2sS.mjs → definitions-B_83XfNQ.mjs} +1 -1
- package/dist/definitions-Bf3H1EwV.mjs +1 -0
- package/dist/{definitions-BGobEDQa.mjs → definitions-BftdXgXI.mjs} +1 -1
- package/dist/definitions-Bio5XJYy.mjs +1 -0
- package/dist/definitions-C3qNgSn1.mjs +1 -0
- package/dist/{definitions-NoVp_9Pm.mjs → definitions-CB6vmOer.mjs} +1 -1
- package/dist/{definitions-CoQFbggH.mjs → definitions-CMZRSy3k.mjs} +1 -1
- package/dist/{definitions-DI9YXsJk.mjs → definitions-CQd7yCQH.mjs} +1 -1
- package/dist/{definitions-CIO9O-Sw.mjs → definitions-CT8ln6GQ.mjs} +1 -1
- package/dist/{definitions-BGwNSkVm.mjs → definitions-Cenu6mxo.mjs} +1 -1
- package/dist/definitions-D4g-MS10.mjs +1 -0
- package/dist/{definitions-CuJRsJ6N.mjs → definitions-D5wl_8HN.mjs} +1 -1
- package/dist/{definitions-jXPaVy4P.mjs → definitions-DAQm1Xar.mjs} +1 -1
- package/dist/definitions-DP1vgxEY.mjs +1 -0
- package/dist/{definitions-Dds_zrWx.mjs → definitions-DxFNRQNK2.mjs} +1 -1
- package/dist/{definitions-DtE0XLrT.mjs → definitions-Ibci7e_L.mjs} +1 -1
- package/dist/{definitions-CCP9gphV.mjs → definitions-OeLvmlQy.mjs} +1 -1
- package/dist/{definitions-BbxOUiP-.mjs → definitions-RZYGD_Ey.mjs} +1 -1
- package/dist/definitions-Tls8c0A0.mjs +1 -0
- package/dist/{definitions-LaYTuwQd.mjs → definitions-bybDvnG0.mjs} +1 -1
- package/dist/{definitions-Dgrg7f3D.mjs → definitions-l7TjdE6V.mjs} +1 -1
- package/dist/{encoding-DGcr6Aj_.mjs → encoding-ycOaz8Vr.mjs} +1 -1
- package/dist/{ensure-browser-core-Buls24LQ.mjs → ensure-browser-core-DxWC-NTp.mjs} +1 -1
- package/dist/{factory-Cx_1LorX.mjs → factory-CKr4fAE1.mjs} +1 -1
- package/dist/{graphql-HLf3MS8H.mjs → graphql-B2TiPEow.mjs} +4 -4
- package/dist/{handlers-D49r1-1P.mjs → handlers-8zN_vBIz.mjs} +1 -1
- package/dist/handlers-B62K4FTc.mjs +1 -0
- package/dist/{handlers-BZoPla6E.mjs → handlers-BpDlVVVU.mjs} +1 -1
- package/dist/{handlers-DmQzIc44.mjs → handlers-CMJK7m1c.mjs} +1 -1
- package/dist/{handlers-BLMa4X7l.mjs → handlers-D2ZOul9p.mjs} +2 -2
- package/dist/{handlers-DW5AbYs5.mjs → handlers-D5E40ssn.mjs} +3 -3
- package/dist/{handlers-BP12ZsWc.mjs → handlers-DGbdQAgD.mjs} +2 -2
- package/dist/handlers-DHO3rjsW.mjs +1 -0
- package/dist/{handlers-DCE45Ww8.mjs → handlers-FJ80VzUI.mjs} +1 -1
- package/dist/handlers-VHWrxbM_.mjs +1 -0
- package/dist/{handlers-BggKiVx9.mjs → handlers-l8QIKqBj.mjs} +1 -1
- package/dist/{handlers-DnJRGp7t.mjs → handlers-mPFiNPe8.mjs} +1 -1
- package/dist/{handlers-pVNpaw4A.mjs → handlers-yo_xYzT8.mjs} +1 -1
- package/dist/handlers.impl-D9Hh8Bgl.mjs +1 -0
- package/dist/{hooks-DDKppogd.mjs → hooks-D4XLfgtV.mjs} +1 -1
- package/dist/index.mjs +11 -15
- package/dist/jadx-search-B_Yse0Zh.mjs +5 -0
- package/dist/maintenance-BUpIukhg.mjs +1 -0
- package/dist/{manifest-yu2xiQqe.mjs → manifest-0Jpt_AQa.mjs} +1 -1
- package/dist/{manifest-DMJlcsTR.mjs → manifest-B3fZbSWR.mjs} +1 -1
- package/dist/{manifest-De-6Wf2R.mjs → manifest-B7NB2rh2.mjs} +1 -1
- package/dist/manifest-BDi4nbH1.mjs +1 -0
- package/dist/{manifest-ais9Afrw.mjs → manifest-BLDfkE7n.mjs} +1 -1
- package/dist/manifest-BcXbB4gf.mjs +1 -0
- package/dist/{manifest-DsVh7Y4U.mjs → manifest-Bdnc_vrc.mjs} +1 -1
- package/dist/manifest-BuYKgCnp.mjs +1 -0
- package/dist/{manifest-Cx2IVMUY.mjs → manifest-CBfNnGPV.mjs} +1 -1
- package/dist/{manifest-DC-SMF6b.mjs → manifest-CPS1Xv69.mjs} +1 -1
- package/dist/{manifest-CGq4NpqH2.mjs → manifest-CQH9FhwI.mjs} +1 -1
- package/dist/{manifest-CRIJq4Hs.mjs → manifest-CRryuZF4.mjs} +1 -1
- package/dist/manifest-CctIumog.mjs +1 -0
- package/dist/manifest-CvTe5ZGV2.mjs +1 -0
- package/dist/{manifest-H-EpAyZQ.mjs → manifest-D-5GH0DV.mjs} +1 -1
- package/dist/{manifest-CtPmHAdn.mjs → manifest-D3Ssf3IC.mjs} +1 -1
- package/dist/{manifest-BeP_zJGb2.mjs → manifest-D5ck3NvC.mjs} +1 -1
- package/dist/{manifest-CeQmtQOY.mjs → manifest-D9jUUJAu.mjs} +1 -1
- package/dist/{manifest-C7qV1z7F.mjs → manifest-DCx6w2XV.mjs} +1 -1
- package/dist/{manifest-CFn0359q2.mjs → manifest-DG19q-Ld.mjs} +1 -1
- package/dist/{manifest-CJMGt7Qy.mjs → manifest-DLMlD0Zc.mjs} +1 -1
- package/dist/{manifest-CDeUZGUZ.mjs → manifest-DYpn8w_h.mjs} +1 -1
- package/dist/manifest-DYzWI8Xs.mjs +1 -0
- package/dist/{manifest-DKUorv5M.mjs → manifest-D_obs5F4.mjs} +1 -1
- package/dist/{manifest-D610kxZr.mjs → manifest-DujQqEQR.mjs} +2 -2
- package/dist/manifest-DwL2ik8P.mjs +1 -0
- package/dist/manifest-ItF5P8A12.mjs +1 -0
- package/dist/{manifest-tmb54wmA.mjs → manifest-KZphqIyX.mjs} +1 -1
- package/dist/{manifest-BPuE6oH2.mjs → manifest-LG42zPLY2.mjs} +1 -1
- package/dist/{manifest-D44TaRJU.mjs → manifest-LLdI5m4T.mjs} +1 -1
- package/dist/{manifest-Dgh0uDW-.mjs → manifest-QYbQXJn0.mjs} +1 -1
- package/dist/{manifest-BFGxlDRh.mjs → manifest-RcpX_MyZ.mjs} +2 -2
- package/dist/{manifest-CDiCtaQT.mjs → manifest-YgVd8Sgz.mjs} +1 -1
- package/dist/{manifest-D16xPXro.mjs → manifest-Zy7Odg5J.mjs} +1 -1
- package/dist/manifest-ff1H7Pdp.mjs +1 -0
- package/dist/{manifest-C_hEIjSx.mjs → manifest-iuhF6pTL2.mjs} +1 -1
- package/dist/{manifest-DWUUWBz0.mjs → manifest-nXHmtMSp2.mjs} +1 -1
- package/dist/{manifest-C1nZkTkO.mjs → manifest-xWfu6iLo.mjs} +1 -1
- package/dist/{manifest-C0g67k6U.mjs → manifest-yC16OhL2.mjs} +1 -1
- package/dist/manifest-ztWJoXy4.mjs +1 -0
- package/dist/modules-BPBcSaM-.mjs +333 -0
- package/dist/{mojo-ipc-VGlv3Qyp.mjs → mojo-ipc-BhwsdVUW.mjs} +1 -1
- package/dist/native/scripts/linux/enum-windows.sh +12 -12
- package/dist/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/native-j8l473zn.mjs +961 -0
- package/dist/network-T0VRwNPd.mjs +7 -0
- package/dist/{outputPaths-BonGThuc.mjs → outputPaths-B4Ic4RZh.mjs} +2 -2
- package/dist/platform-CzaQtISh.mjs +93 -0
- package/dist/process-CWhsCWrf.mjs +2 -0
- package/dist/proxy-DZFlDsG3.mjs +2 -0
- package/dist/{registry-DUHIPE-v.mjs → registry-DH4sc1dt.mjs} +1 -1
- package/dist/renderer-pid-9tJnZ_9N.mjs +1 -0
- package/dist/{search-defaults-D2bY-rzH.mjs → search-defaults-lYBVn_3L.mjs} +1 -1
- package/dist/server/plugin-api.d.mts +19 -36
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/{shared-state-board-Cyg-xh_k.mjs → shared-state-board-BSjXLUV1.mjs} +1 -1
- package/dist/{sourcemap-D6Q1UuAp.mjs → sourcemap-Dh3Ai_ur.mjs} +1 -1
- package/dist/streaming-BcJ0B6ao.mjs +1 -0
- package/dist/transform-DOxzeWPB.mjs +103 -0
- package/dist/wasm-CZ_HTfKR.mjs +174 -0
- package/dist/{webcrack-CsLLJIs9.mjs → webcrack-C1iYG_EX.mjs} +3 -3
- package/dist/{workflow-CYIXtrWD.mjs → workflow-BdwQmARn.mjs} +4 -4
- package/package.json +16 -15
- package/src/native/scripts/linux/enum-windows.sh +12 -12
- package/src/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/ConsoleMonitor-Dkqc0HNi.mjs +0 -490
- package/dist/DOMInspector-BYY_EJ0C.mjs +0 -95
- package/dist/DetailedDataManager-BniBJlVv.mjs +0 -1
- package/dist/ExtensionManager-erMpqcLk.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +0 -1
- package/dist/MemoryController-BaqstM5w.mjs +0 -2
- package/dist/PageController-D9jVkH0i.mjs +0 -1
- package/dist/ProcessRegistry-Hf12LlR9.mjs +0 -1
- package/dist/ToolCatalog-D_IKl1Hu.mjs +0 -1
- package/dist/ToolProbe-xsfALmN3.mjs +0 -1
- package/dist/ToolRegistry-B0Zs-phN.mjs +0 -1
- package/dist/analysis-BuR-NgX8.mjs +0 -5
- package/dist/betterSqlite3-CGaxz4AX.mjs +0 -1
- package/dist/browser-C4Le3xqA.mjs +0 -11
- package/dist/collector-CKO8RPK8.mjs +0 -1
- package/dist/constants-Cp6hBrrx.mjs +0 -1
- package/dist/definitions-CdWEuIkI.mjs +0 -1
- package/dist/definitions-OvGsfxdt.mjs +0 -1
- package/dist/handlers-D3iev8g1.mjs +0 -1
- package/dist/handlers-De5u62Ga2.mjs +0 -1
- package/dist/handlers-S9Ws0IGy.mjs +0 -2
- package/dist/handlers.impl-CD2_kOcC.mjs +0 -1
- package/dist/maintenance-CutEO84j.mjs +0 -1
- package/dist/manifest-BXry5N09.mjs +0 -1
- package/dist/manifest-Cq0j7GZt.mjs +0 -1
- package/dist/manifest-DD3rtxvV.mjs +0 -1
- package/dist/manifest-Dm0o3i2U.mjs +0 -1
- package/dist/manifest-DtEFSRaq.mjs +0 -1
- package/dist/manifest-zrbrpKCC.mjs +0 -1
- package/dist/modules-p-PUNv9r.mjs +0 -332
- package/dist/network-BjZ1Y-GB.mjs +0 -7
- package/dist/platform-C446Lf97.mjs +0 -93
- package/dist/process-C9f2A5zk.mjs +0 -962
- package/dist/proxy-CvRepxgV.mjs +0 -1
- package/dist/streaming-CTX58tbb.mjs +0 -1
- package/dist/transform-Cv9P2vVD.mjs +0 -103
- package/dist/wasm-DaJa8J0V.mjs +0 -174
- /package/dist/{CacheAdapters-CdAxBmVW.mjs → CacheAdapters-CsNtQIR8.mjs} +0 -0
- /package/dist/{DarwinAPI-DC4HGGLl.mjs → DarwinAPI-ZfQdpLNI.mjs} +0 -0
- /package/dist/{EventBus-DgciURGg.mjs → EventBus-DL8iLA09.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BIfgB7HP.mjs → EvidenceGraphBridge-BtbwXsLC.mjs} +0 -0
- /package/dist/{FingerprintManager-N7BZqjxP.mjs → FingerprintManager-DT0EAUEo.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs → HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs} +0 -0
- /package/dist/{InstrumentationSession-DxXs0sCp.mjs → InstrumentationSession-D_G1ZPyd.mjs} +0 -0
- /package/dist/{PrerequisiteError-Bl3dK8XA.mjs → PrerequisiteError-BjCQA-gK.mjs} +0 -0
- /package/dist/{ReverseEvidenceGraph-B931HeoW.mjs → ReverseEvidenceGraph-BhSYYdiI.mjs} +0 -0
- /package/dist/{StealthVerifier-Dhbj4B4P.mjs → StealthVerifier-BmcxfwSF.mjs} +0 -0
- /package/dist/{VersionDetector-DMoUWyNm.mjs → VersionDetector-CHT36Az0.mjs} +0 -0
- /package/dist/{Win32API-Bhi5xFBe.mjs → Win32API-eUCF57l_.mjs} +0 -0
- /package/dist/{authorization-schema-B40obG1A.mjs → authorization-schema-BOFwSXUN.mjs} +0 -0
- /package/dist/{bind-helpers-BlAOQrFQ.mjs → bind-helpers-m2U8glkF.mjs} +0 -0
- /package/dist/{capabilities-DbYCv-HF.mjs → capabilities-CyXuKUl1.mjs} +0 -0
- /package/dist/{concurrency-CcK46d0h.mjs → concurrency-DCr8WQ2M.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-B0yhGPcs.mjs → evidence-graph-bridge-CV_UdYqj.mjs} +0 -0
- /package/dist/{flat-target-session-CO5g78k3.mjs → flat-target-session-DvcQX7J5.mjs} +0 -0
- /package/dist/{formatAddress-C7j2fDlM.mjs → formatAddress-vLA_hOJt.mjs} +0 -0
- /package/dist/{handlers-Dv_runVv.mjs → handlers-0yKLRIfo.mjs} +0 -0
- /package/dist/{matchesWildcardPattern-BGqLSmEs.mjs → matchesWildcardPattern-BAG6LvX5.mjs} +0 -0
- /package/dist/{parse-args-Cuk7-xUt.mjs → parse-args-Bw413PlW.mjs} +0 -0
- /package/dist/{playwright-cdp-fallback-BwVR-_T3.mjs → playwright-cdp-fallback-DqFdx9-s.mjs} +0 -0
- /package/dist/{ssrf-policy-T96MR3r6.mjs → ssrf-policy-CsIJGkpd.mjs} +0 -0
- /package/dist/{tool-builder-CI9914Tf.mjs → tool-builder-qif8M9-K.mjs} +0 -0
- /package/dist/{types-DtThH00r.mjs → types-D9EiE5o9.mjs} +0 -0
- /package/dist/{types-CuyefmGT.mjs → types-Fz69RzbZ.mjs} +0 -0
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./logger-sBC6IdRT.mjs";import{C as t,D as n,E as r,Nn as i,O as a,S as o,T as s,k as c,w as l,x as u}from"./constants-Cp6hBrrx.mjs";import{t as d}from"./DetailedDataManager-BniBJlVv.mjs";import{t as f}from"./response-C7rKQst4.mjs";import{t as p}from"./ToolError-DWU_z7gp.mjs";import{a as m,n as h,o as g}from"./modules-p-PUNv9r.mjs";import{c as _,l as v,o as y,s as b,u as x}from"./outputPaths-BonGThuc.mjs";import{t as ee}from"./PrerequisiteError-Bl3dK8XA.mjs";import{n as te,t as ne}from"./betterSqlite3-CGaxz4AX.mjs";import{t as re}from"./concurrency-CcK46d0h.mjs";import{a as S,i as C,n as w,o as T,r as E,s as D,t as O}from"./parse-args-Cuk7-xUt.mjs";import{c as ie}from"./PageController-D9jVkH0i.mjs";import{n as ae}from"./capabilities-DbYCv-HF.mjs";import"./definitions-CoQFbggH.mjs";import{t as k}from"./ResponseBuilder-B2lu4KEl.mjs";import{join as oe}from"path";import{randomUUID as se}from"node:crypto";import{readFile as ce,writeFile as le}from"fs/promises";const A=oe(x,`.env`),ue=new Set([`stable`,`beta`,`dev`,`canary`]);var de=class{deps;constructor(e){this.deps=e}markMonitoringContextChanged(t){try{this.deps.consoleMonitor.markContextChanged()}catch(n){e.warn(`[${t}] Failed to mark monitoring context as stale: ${n instanceof Error?n.message:String(n)}`)}}async syncTabRegistryWithCollectorPages(t){try{let e=await this.deps.collector.listPages();this.deps.getTabRegistry().reconcilePages(e.map(()=>null),e)}catch(n){e.warn(`[${t}] Failed to sync attached tabs into TabRegistry: ${n instanceof Error?n.message:String(n)}`)}}parseHeadlessArg(e){if(typeof e==`boolean`)return e;if(typeof e==`number`)return e===1?!0:e===0?!1:void 0;if(typeof e==`string`){let t=e.trim().toLowerCase();if([`true`,`1`,`yes`,`on`].includes(t))return!0;if([`false`,`0`,`no`,`off`].includes(t))return!1}}parseChromeConnectRequest(e){let t=S(e,`channel`);if(t&&!ue.has(t))throw Error(`Invalid channel "${t}". Expected one of: stable, beta, dev, canary.`);return{browserURL:S(e,`browserURL`),wsEndpoint:S(e,`wsEndpoint`),autoConnect:O(e,`autoConnect`),userDataDir:S(e,`userDataDir`),channel:t}}parseChromeLaunchRequest(e){return{headless:this.parseHeadlessArg(e.headless),args:T(e,`args`),enableV8NativesSyntax:O(e,`enableV8NativesSyntax`)}}hasChromeConnectRequest(e){return!!(e.browserURL||e.wsEndpoint||e.autoConnect||e.userDataDir||e.channel)}describeChromeConnectRequest(e){return e.wsEndpoint?e.wsEndpoint:e.browserURL?e.browserURL:e.userDataDir?`autoConnect:${e.userDataDir}`:`autoConnect:${e.channel??`stable`}`}isAutoConnectRequest(e){return!!(e.autoConnect||e.userDataDir||e.channel)}getAutoConnectApprovalHint(e){return this.isAutoConnectRequest(e)?`Chrome 144+ autoConnect may prompt for manual approval. Switch to Chrome and click Allow for this client if prompted.`:null}shouldAttemptLinuxHeadfulFallback(e,t){let n=e===!1||e===void 0&&process.env.PUPPETEER_HEADLESS===`false`,r=process.platform===`linux`||process.env.JSHOOK_FORCE_LINUX_FALLBACK===`true`;if(!n||!r)return!1;let i=t instanceof Error?t.message:String(t);return/Missing X server|cannot open display|Failed to launch the browser process|ozone|No protocol specified|X11|Wayland|DevToolsActivePort/i.test(i)}async persistHeadlessEnv(t){try{let e=``;try{e=await ce(A,`utf-8`)}catch(e){if(e?.code!==`ENOENT`)throw e}let n=`PUPPETEER_HEADLESS=${t}`;await le(A,/^PUPPETEER_HEADLESS=.*$/m.test(e)?e.replace(/^PUPPETEER_HEADLESS=.*$/m,n):`${e.trimEnd()}\n${n}\n`,`utf-8`)}catch(n){e.warn(`Failed to persist PUPPETEER_HEADLESS=${t} to .env: ${String(n)}`)}}async handleBrowserLaunch(t){try{if(S(t,`driver`,`chrome`)===`camoufox`){if(S(t,`mode`,`launch`)===`connect`){let e=S(t,`wsEndpoint`);return e?k.ok().merge({driver:`camoufox`,mode:`connect`,wsEndpoint:e,message:`Connected to Camoufox server. Use page_navigate to begin.`}).json():k.fail(`wsEndpoint is required for connect mode. Use camoufox_server({ action: "launch" }) first to get a wsEndpoint.`).json()}return k.ok().merge({driver:`camoufox`,mode:`launch`,message:`Camoufox (Firefox) browser launched`,note:`Use page_navigate to begin. CDP debugger is limited in Firefox; network_enable and console_monitor({ action: "enable" }) use Playwright events and are fully supported.`}).json()}if(S(t,`mode`,`launch`)===`connect`){let e=this.parseChromeConnectRequest(t);if(!this.hasChromeConnectRequest(e))return k.fail(`browserURL, wsEndpoint, autoConnect, userDataDir, or channel is required for chrome connect mode.`).json();await this.deps.collector.connect(e);let n=await this.deps.collector.getStatus();return k.ok().merge({driver:`chrome`,mode:`connect`,endpoint:this.describeChromeConnectRequest(e),autoConnect:this.isAutoConnectRequest(e),channel:e.channel??null,userDataDir:e.userDataDir??null,manualApprovalMayBeRequired:this.isAutoConnectRequest(e),approvalHint:this.getAutoConnectApprovalHint(e),message:`Connected to existing Chrome browser successfully`,status:n}).json()}let n=this.parseChromeLaunchRequest(t);try{let e=await this.deps.collector.launch(n);e.action===`relaunched`&&this.markMonitoringContextChanged(`browser_launch_relaunch`);let t=await this.deps.collector.listPages(),r=this.deps.getTabRegistry();t.length>0&&(await this.deps.collector.selectPage(0),r.setCurrentByIndex(0));let i=t[0],a=await this.deps.collector.getStatus();return k.ok().merge({driver:`chrome`,message:e.action===`relaunched`?`Browser relaunched successfully`:`Browser launched successfully`,launchAction:e.action,relaunchReason:e.reason??null,v8NativeSyntaxEnabled:e.launchOptions.v8NativeSyntaxEnabled,launchArgs:e.launchOptions.args,selectedIndex:t.length>0?0:null,currentUrl:i?.url??null,currentTitle:i?.title??null,totalPages:t.length,status:a}).json()}catch(t){if(!this.shouldAttemptLinuxHeadfulFallback(n.headless,t))throw t;let r=t instanceof Error?t.message:String(t);e.warn(`Headful launch failed on Linux, fallback to headless=true: ${r}`),process.env.PUPPETEER_HEADLESS=`true`,await this.persistHeadlessEnv(`true`);let i=await this.deps.collector.launch({...n,headless:!0}),a=await this.deps.collector.getStatus();return k.ok().merge({driver:`chrome`,message:`Browser launched with Linux fallback (headless=true)`,launchAction:i.action,relaunchReason:i.reason??null,v8NativeSyntaxEnabled:i.launchOptions.v8NativeSyntaxEnabled,launchArgs:i.launchOptions.args,status:a,fallback:{applied:!0,reason:`Headful browser is unavailable in current Linux runtime; switched to headless and updated .env`,newEnv:`PUPPETEER_HEADLESS=true`}}).json()}}catch(e){return k.fail(e).json()}}async handleBrowserClose(e){try{return await this.deps.collector.close(),k.ok().set(`message`,`Browser closed successfully`).json()}catch(e){return k.fail(e).json()}}async handleBrowserStatus(e){try{let e=await this.deps.collector.getStatus();return k.ok().merge({driver:`chrome`,...e}).json()}catch(e){return k.fail(e).json()}}async handleBrowserListTabs(e){let t=this.parseChromeConnectRequest(e);try{this.hasChromeConnectRequest(t)&&await this.deps.collector.connect(t);let e=await this.deps.collector.listPages(),n=this.deps.getTabRegistry();await this.syncTabRegistryWithCollectorPages(`browser_list_tabs`);let r=e.map(e=>{let t=n.getTabByIndex(e.index);return{...e,pageId:t?.pageId??null,aliases:t?.aliases??[]}}),i=n.getContextMeta();return k.ok().merge({count:e.length,pages:r,currentPageId:i.pageId,currentIndex:i.tabIndex,autoConnect:this.isAutoConnectRequest(t),manualApprovalMayBeRequired:this.isAutoConnectRequest(t),approvalHint:this.getAutoConnectApprovalHint(t),hint:`Use browser_select_tab(index=N) to switch to a specific tab`}).json()}catch(e){return k.fail(e).set(`hint`,`Make sure browser is attached via browser_attach first, or provide browserURL/autoConnect. Chrome 144+ autoConnect may require manual approval in the Chrome window.`).set(`approvalHint`,this.getAutoConnectApprovalHint(t)).json()}}async handleBrowserSelectTab(e){try{let t=E(e,`index`),n=S(e,`urlPattern`),r=S(e,`titlePattern`),i=this.deps.getTabRegistry();if(t!==void 0){let e=await this.deps.clearAttachedTargetContext(`browser_select_tab`);await this.deps.collector.selectPage(t);let n=await this.deps.collector.listPages();await this.syncTabRegistryWithCollectorPages(`browser_select_tab`);let r=n[t],a=i.setCurrentByIndex(t);return(a?.pageId||e.detached)&&this.markMonitoringContextChanged(`browser_select_tab`),k.ok().merge({selectedIndex:t,selectedPageId:a?.pageId??null,url:r?.url,title:r?.title,contextSwitched:!0,detachedCdpTarget:e.detached,detachedCdpTargetId:e.targetId,monitoringBindingDeferred:!!a?.pageId,networkMonitoringEnabled:!1,consoleMonitoringEnabled:!1}).json()}let a=await this.deps.collector.listPages(),o=-1;for(let e of a){if(n&&e.url.includes(n)){o=e.index;break}if(r&&e.title.includes(r)){o=e.index;break}}if(o===-1)return k.fail(`No matching tab found`).set(`availablePages`,a).json();let s=await this.deps.clearAttachedTargetContext(`browser_select_tab`);await this.deps.collector.selectPage(o),await this.syncTabRegistryWithCollectorPages(`browser_select_tab`);let c=a[o],l=i.setCurrentByIndex(o);return(l?.pageId||s.detached)&&this.markMonitoringContextChanged(`browser_select_tab`),k.ok().merge({selectedIndex:o,selectedPageId:l?.pageId??null,url:c?.url,title:c?.title,contextSwitched:!0,detachedCdpTarget:s.detached,detachedCdpTargetId:s.targetId,monitoringBindingDeferred:!!l?.pageId,networkMonitoringEnabled:!1,consoleMonitoringEnabled:!1}).json()}catch(e){return k.fail(e).json()}}async handleBrowserAttach(t){let n=null;try{if(n=this.parseChromeConnectRequest(t),!this.hasChromeConnectRequest(n))return k.fail(`browserURL, wsEndpoint, autoConnect, userDataDir, or channel is required`).json();let r=await this.deps.clearAttachedTargetContext(`browser_attach`);await this.deps.collector.connect(n);let i=t.pageIndex,a=typeof i==`number`?i:typeof i==`string`&&i.trim()!==``?Number(i):0,o=Number.isFinite(a)?a:0,s=await this.deps.collector.listPages();s.length>0&&o<s.length?await this.deps.collector.selectPage(o):s.length>0&&(await this.deps.collector.selectPage(0),e.warn(`[browser_attach] pageIndex ${o} out of range (0-${s.length-1}), fell back to 0`));let c=this.deps.getTabRegistry();await this.syncTabRegistryWithCollectorPages(`browser_attach`);let l=s.length>0?Math.min(o,s.length-1):0,u=s.length>0?c.setCurrentByIndex(l):null,d=s[l],f=!!u?.pageId;f&&this.markMonitoringContextChanged(`browser_attach`);let p=await this.deps.collector.getStatus();return k.ok().merge({message:`Attached to existing browser successfully`,endpoint:this.describeChromeConnectRequest(n),autoConnect:this.isAutoConnectRequest(n),channel:n.channel??null,userDataDir:n.userDataDir??null,manualApprovalMayBeRequired:this.isAutoConnectRequest(n),approvalHint:this.getAutoConnectApprovalHint(n),selectedIndex:l,selectedPageId:u?.pageId??null,currentUrl:d?.url??null,currentTitle:d?.title??null,totalPages:s.length,contextSwitched:s.length>0,detachedCdpTarget:r.detached,detachedCdpTargetId:r.targetId,monitoringBindingDeferred:f,networkMonitoringEnabled:!1,consoleMonitoringEnabled:!1,takeoverReady:f,note:f?`Monitoring will auto-rebind on the next console/network operation for the selected tab.`:`Connected to existing Chrome, but the selected tab does not currently expose a stable Puppeteer Page handle. Tab discovery still works; try selecting a different tab or navigate the tab and retry.`,status:p}).json()}catch(e){return k.fail(e).set(`approvalHint`,this.getAutoConnectApprovalHint(n??{})).json()}}};function fe(e){let t=T(e,`addons`),n=T(e,`excludeAddons`),r=T(e,`fonts`);return{headless:O(e,`headless`,!0),os:S(e,`os`,`windows`),geoip:O(e,`geoip`,!1),humanize:O(e,`humanize`,!1),proxy:S(e,`proxy`)||void 0,blockImages:O(e,`blockImages`,!1),blockWebrtc:O(e,`blockWebrtc`,!1),blockWebgl:O(e,`blockWebgl`,!1),locale:S(e,`locale`)||void 0,addons:t.length>0?t:void 0,fonts:r.length>0?r:void 0,excludeAddons:n.length>0?n:void 0,customFontsOnly:O(e,`customFontsOnly`,!1),screen:e.screen,window:e.window,fingerprint:C(e,`fingerprint`),webglConfig:C(e,`webglConfig`),firefoxUserPrefs:C(e,`firefoxUserPrefs`),mainWorldEval:O(e,`mainWorldEval`,!0),enableCache:O(e,`enableCache`,!1)}}async function pe(){try{return await import(`camoufox-js`),null}catch(e){let t=e instanceof Error?e.message:String(e);return te(e)?`Camoufox requires the same native SQLite backend used by trace tooling. ${ne(e)}`:t.includes(`Cannot find package 'camoufox-js'`)?`camoufox-js package is not installed. Run: pnpm add camoufox-js && npx camoufox-js fetch`:`Camoufox dependencies check failed: ${t}`}}var me=class{deps;constructor(e){this.deps=e}async handleCamoufoxServerLaunch(t){try{let n=await pe();if(n)return e.warn(`Camoufox dependencies not available: ${n}`),k.fail(n).set(`hint`,`Camoufox is optional. Use browser_launch with Chrome driver instead, or install dependencies.`).json();let r=E(t,`port`),i=S(t,`ws_path`),a=fe(t),o=this.deps.getCamoufoxManager();o||(o=new g(a),this.deps.setCamoufoxManager(o));let s=await o.launchAsServer(r,i);return k.ok().merge({wsEndpoint:s,config:{os:a.os,headless:a.headless,geoip:a.geoip,locale:a.locale,blockWebgl:a.blockWebgl},message:`Camoufox server launched. Connect with: browser_launch(driver="camoufox", mode="connect", wsEndpoint=<wsEndpoint>)`}).json()}catch(e){return k.fail(e).set(`hint`,`Try running: npx camoufox-js fetch to download browser binaries`).json()}}async handleCamoufoxServerClose(e){try{let e=this.deps.getCamoufoxManager();return e?(await e.closeBrowserServer(),k.ok().set(`message`,`Camoufox server closed.`).json()):k.fail(`No camoufox server is running.`).json()}catch(e){return k.fail(e).json()}}async handleCamoufoxServerStatus(e){try{let e=this.deps.getCamoufoxManager()?.getBrowserServerEndpoint()??null;return k.ok().merge({running:e!==null,wsEndpoint:e}).json()}catch(e){return k.fail(e).json()}}};const he=new Set(ie);function j(e){return w(e,`waitUntil`,he,`networkidle`)}var ge=class{deps;constructor(e){this.deps=e}syncCurrentTabMeta(e,t){let n=this.deps.getTabRegistry?.();if(!n||!e||!t.url||t.title===void 0)return;let r=t.url,i=t.title,a=n.upsertPage(e,{url:r,title:i});n.setCurrentPageId(a)}async getChromePageIfAvailable(){let e=this.deps.pageController.getPage;return typeof e==`function`?await Reflect.apply(e,this.deps.pageController,[]):null}async getCamoufoxTitleIfAvailable(e){let t=e.title;if(typeof t!=`function`)return;let n=await Reflect.apply(t,e,[]);return typeof n==`string`?n:void 0}getCamoufoxUrlIfAvailable(e){let t=e.url;if(typeof t!=`function`)return;let n=Reflect.apply(t,e,[]);return typeof n==`string`?n:void 0}async handlePageNavigate(e){try{let t=S(e,`url`,``),n=j(e),r=E(e,`timeout`),i=O(e,`enableNetworkMonitoring`);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.goto(t,{waitUntil:n,timeout:r}),this.deps.consoleMonitor.setPlaywrightPage(e),i&&await this.deps.consoleMonitor.enable({enableNetwork:!0,enableExceptions:!0});let a=this.getCamoufoxUrlIfAvailable(e)??``,o=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:a,title:o}),this.deps.eventBus?.emit(`browser:navigated`,{url:a,timestamp:new Date().toISOString()}),k.ok().build({driver:`camoufox`,url:a,title:o??``,network_monitoring:{enabled:this.deps.consoleMonitor.isNetworkEnabled()}})}i&&await this.deps.consoleMonitor.enable({enableNetwork:!0,enableExceptions:!0}),await this.deps.pageController.navigate(t,{waitUntil:n,timeout:r});let a=await this.getChromePageIfAvailable(),o=await this.deps.pageController.getURL(),s=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(a,{url:o,title:s}),this.deps.eventBus?.emit(`browser:navigated`,{url:o,timestamp:new Date().toISOString()}),k.ok().build({url:o,title:s,network_monitoring:{enabled:this.deps.consoleMonitor.isNetworkEnabled()}})}catch(e){return k.fail(e).build()}}async handlePageReload(e){try{if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();return await e.reload(),this.syncCurrentTabMeta(e,{url:this.getCamoufoxUrlIfAvailable(e),title:await this.getCamoufoxTitleIfAvailable(e)}),k.ok().build({message:`Page reloaded`,driver:`camoufox`})}await this.deps.pageController.reload();let e=await this.getChromePageIfAvailable();return this.syncCurrentTabMeta(e,{url:await this.deps.pageController.getURL(),title:await this.deps.pageController.getTitle()}),k.ok().build({message:`Page reloaded`})}catch(e){return k.fail(e).build()}}async handlePageBack(e){try{let t=E(e,`timeout`,1e4);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();return await e.goBack(),this.syncCurrentTabMeta(e,{url:this.getCamoufoxUrlIfAvailable(e),title:await this.getCamoufoxTitleIfAvailable(e)}),k.ok().build({url:this.getCamoufoxUrlIfAvailable(e),driver:`camoufox`})}await this.deps.pageController.goBack(t);let n=await this.getChromePageIfAvailable(),r=await this.deps.pageController.getURL();return this.syncCurrentTabMeta(n,{url:r,title:await this.deps.pageController.getTitle()}),k.ok().build({url:r})}catch(e){return k.fail(e).build()}}async handlePageForward(e){try{let t=E(e,`timeout`,1e4);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();return await e.goForward(),this.syncCurrentTabMeta(e,{url:this.getCamoufoxUrlIfAvailable(e),title:await this.getCamoufoxTitleIfAvailable(e)}),k.ok().build({url:this.getCamoufoxUrlIfAvailable(e),driver:`camoufox`})}await this.deps.pageController.goForward(t);let n=await this.getChromePageIfAvailable(),r=await this.deps.pageController.getURL();return this.syncCurrentTabMeta(n,{url:r,title:await this.deps.pageController.getTitle()}),k.ok().build({url:r})}catch(e){return k.fail(e).build()}}},_e=class{deps;constructor(e){this.deps=e}toErrorMessage(e){return e instanceof Error?e.message:typeof e==`string`?e:``}parseNumberArg(e,t={}){let n;if(typeof e==`number`&&Number.isFinite(e))n=e;else if(typeof e==`string`){let t=e.trim();if(t.length>0){let e=Number(t);Number.isFinite(e)&&(n=e)}}if(n===void 0&&(n=t.defaultValue),n!==void 0)return t.integer&&(n=Math.trunc(n)),typeof t.min==`number`&&(n=Math.max(t.min,n)),typeof t.max==`number`&&(n=Math.min(t.max,n)),n}parseMouseButton(e){if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`left`||t===`right`||t===`middle`)return t}return`left`}async getCamoufoxInteractionContext(e){let t=await this.deps.getCamoufoxPage();return!e?.frameUrl&&!e?.frameSelector?t:await this.deps.pageController.resolveFrame(t,e)}async handlePageClick(e){try{let t=S(e,`selector`,``),n=this.parseMouseButton(e.button),r=this.parseNumberArg(e.clickCount,{defaultValue:1,min:1,max:10,integer:!0}),i=this.parseNumberArg(e.delay,{min:0,max:6e4,integer:!0}),a=this.parseNumberArg(e.timeout,{defaultValue:1e4,min:1e3,max:12e4,integer:!0}),o=S(e,`frameUrl`),s=S(e,`frameSelector`),c=o||s?{frameUrl:o||void 0,frameSelector:s||void 0}:void 0;if(!t||typeof t!=`string`||t.trim().length===0)return k.fail(`selector parameter is required`).build();if(this.deps.getActiveDriver()===`camoufox`)return await(await this.getCamoufoxInteractionContext(c)).click(t,{button:n,clickCount:r,delay:i}),k.ok().build({driver:`camoufox`,message:`Clicked: ${t}`,...c?{frame:c}:{}});try{c?await this.deps.pageController.click(t,{button:n,clickCount:r,delay:i,timeout:a},c):await this.deps.pageController.click(t,{button:n,clickCount:r,delay:i,timeout:a})}catch(e){let n=this.toErrorMessage(e);if(n.includes(`detached`)||n.includes(`timed out`)||n.includes(`Execution context was destroyed`)||n.includes(`callFunctionOn`)||n.includes(`Target closed`))return k.ok().build({message:`Clicked ${t} - navigation triggered`,navigated:!0,...c?{frame:c}:{}});throw e}return k.ok().build({message:`Clicked: ${t}`,...c?{frame:c}:{}})}catch(e){return k.fail(e).build()}}async handlePageType(e){try{let t=S(e,`selector`,``),n=S(e,`text`,``),r=E(e,`delay`),i=S(e,`frameUrl`),a=S(e,`frameSelector`),o=i||a?{frameUrl:i||void 0,frameSelector:a||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(o)).fill(t,n),k.ok().build({driver:`camoufox`,message:`Typed into ${t}`,...o?{frame:o}:{}})):(o?await this.deps.pageController.type(t,n,{delay:r},o):await this.deps.pageController.type(t,n,{delay:r}),k.ok().build({message:`Typed into ${t}`,...o?{frame:o}:{}}))}catch(e){return k.fail(e).build()}}async handlePageUploadFiles(e){try{let t=S(e,`selector`,``),n=T(e,`paths`).map(e=>e.trim()).filter(Boolean),r=S(e,`frameUrl`),i=S(e,`frameSelector`),a=r||i?{frameUrl:r||void 0,frameSelector:i||void 0}:void 0;if(!t||t.trim().length===0)return k.fail(`selector parameter is required`).build();if(n.length===0)return k.fail(`paths parameter must contain at least one relative file path`).build();let o=n.map(e=>b(e));if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage(),r=await(a?await this.deps.pageController.resolveFrame(e,a):e).$(t);return!r||typeof r.setInputFiles!=`function`?k.fail(`File input not found: ${t}`).build({driver:`camoufox`}):(await r.setInputFiles(o),k.ok().build({driver:`camoufox`,selector:t,count:o.length,paths:n,message:`Uploaded ${o.length} file(s) into ${t}`,...a?{frame:a}:{}}))}return await this.deps.pageController.uploadFile(t,o,a),k.ok().build({selector:t,count:o.length,paths:n,message:`Uploaded ${o.length} file(s) into ${t}`,...a?{frame:a}:{}})}catch(e){return k.fail(e).build()}}async handlePageSelect(e){try{let t=S(e,`selector`,``),n=T(e,`values`),r=S(e,`frameUrl`),i=S(e,`frameSelector`),a=r||i?{frameUrl:r||void 0,frameSelector:i||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(a)).selectOption(t,n),k.ok().build({driver:`camoufox`,message:`Selected in ${t}: ${n.join(`, `)}`,...a?{frame:a}:{}})):(a?await this.deps.pageController.select(t,n,a):await this.deps.pageController.select(t,n),k.ok().build({message:`Selected in ${t}: ${n.join(`, `)}`,...a?{frame:a}:{}}))}catch(e){return k.fail(e).build()}}async handlePageHover(e){try{let t=S(e,`selector`,``),n=S(e,`frameUrl`),r=S(e,`frameSelector`),i=n||r?{frameUrl:n||void 0,frameSelector:r||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(i)).hover(t),k.ok().build({driver:`camoufox`,message:`Hovered: ${t}`,...i?{frame:i}:{}})):(i?await this.deps.pageController.hover(t,i):await this.deps.pageController.hover(t),k.ok().build({message:`Hovered: ${t}`,...i?{frame:i}:{}}))}catch(e){return k.fail(e).build()}}async handlePageScroll(e){try{let t=E(e,`x`,0),n=E(e,`y`,0);return this.deps.getActiveDriver()===`camoufox`?(await(await this.deps.getCamoufoxPage()).evaluate(e=>{window.scrollTo(e.x||0,e.y||0)},{x:t,y:n}),k.ok().build({driver:`camoufox`,message:`Scrolled to: x=${t||0}, y=${n||0}`})):(await this.deps.pageController.scroll({x:t,y:n}),k.ok().build({message:`Scrolled to: x=${t||0}, y=${n||0}`}))}catch(e){return k.fail(e).build()}}async handlePagePressKey(e){try{let t=S(e,`key`,``);return this.deps.getActiveDriver()===`camoufox`?(await(await this.deps.getCamoufoxPage()).keyboard.press(t),k.ok().build({driver:`camoufox`,key:t})):(await this.deps.pageController.pressKey(t),k.ok().build({key:t}))}catch(e){return k.fail(e).build()}}};function M(e,t){if(Array.isArray(e))return e.map(e=>M(e,t));if(typeof e==`object`&&e){let n=e,r={};for(let[e,i]of Object.entries(n))t.has(e)||(r[e]=M(i,t));return r}return e}function N(e){if(typeof e==`string`)return/^data:[a-z+-]+\/[a-z+-]+;base64,/i.test(e)?`[base64 ~${Math.round(e.length/1024)}KB stripped]`:e.length>500&&/^[A-Za-z0-9+/=\r\n]+$/.test(e.replace(/\s/g,``))?`[base64 ~${e.length}chars stripped]`:e;if(Array.isArray(e))return e.map(e=>N(e));if(typeof e==`object`&&e){let t=e,n={};for(let[e,r]of Object.entries(t))n[e]=N(r);return n}return e}function P(e,t,n){let r=n.autoSummarize?t.smartHandle(e,n.maxSize):e;return n.fieldFilter&&n.fieldFilter.length>0&&(r=M(r,new Set(n.fieldFilter))),n.stripBase64&&(r=N(r)),r}var ve=class{deps;constructor(e){this.deps=e}resolveEvaluationSource(e){let t=S(e,`script`,``)||S(e,`code`,``)||S(e,`expression`,``);return t.trim()?t:null}async getCamoufoxEvaluationContext(e){let t=await this.deps.getCamoufoxPage();return!e?.frameUrl&&!e?.frameSelector?t:await this.deps.pageController.resolveFrame(t,e)}async handlePageEvaluate(e){try{let t=this.resolveEvaluationSource(e),n=O(e,`autoSummarize`,!0),r=E(e,`maxSize`,51200),i=T(e,`fieldFilter`),a=O(e,`stripBase64`,!1),o=S(e,`frameUrl`),s=S(e,`frameSelector`);if(!t)return k.fail(`code, script, or expression is required`).build();let c=o||s?{frameUrl:o||void 0,frameSelector:s||void 0}:void 0;if(this.deps.getActiveDriver()===`camoufox`){let e=await this.getCamoufoxEvaluationContext(c),o=Function(`return (${t})`),s=P(await e.evaluate(o),this.deps.detailedDataManager,{autoSummarize:n,maxSize:r,fieldFilter:i??void 0,stripBase64:a});return k.ok().build({driver:`camoufox`,...c?{frame:c}:{},result:s})}let l=P(c?await this.deps.pageController.evaluate(t,c):await this.deps.pageController.evaluate(t),this.deps.detailedDataManager,{autoSummarize:n,maxSize:r,fieldFilter:i??void 0,stripBase64:a});return k.ok().build({...c?{frame:c}:{},result:l})}catch(e){return k.fail(e).build()}}async handlePageScreenshot(e){try{let t=S(e,`path`),n=S(e,`type`,`png`),r=E(e,`quality`),i=O(e,`fullPage`,!1),a=C(e,`clip`),o=e.selector,s=[];if(Array.isArray(o))for(let e of o){let t=typeof e==`string`?e.trim():``;t.length>0&&t.toLowerCase()!==`all`&&s.push(t)}else if(typeof o==`string`){let e=o.trim();e.length>0&&e.toLowerCase()!==`all`&&s.push(e)}if(s.length>1)return this.screenshotBatch(s,t,n,r);let c=s[0]??``,{absolutePath:l,displayPath:u,pathRewritten:d}=await _({requestedPath:t,type:n,fallbackName:c?`element`:a?`region`:`page`,fallbackDir:`screenshots/manual`});if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage(),t;if(c){let i=await e.$(c);if(!i)return k.fail(`Element not found: ${c}`).build();t=await i.screenshot({path:l,type:n,quality:r})}else t=await e.screenshot({path:l,type:n,quality:r,fullPage:a?!1:i});return k.ok().build({driver:`camoufox`,selector:c||void 0,clip:a||void 0,message:`Screenshot taken: ${u}`,path:u,pathRewritten:d,size:t?.length??0})}let f;if(c){let e=await(await this.deps.pageController.getPage()).$(c);if(!e)return k.fail(`Element not found: ${c}`).build();f=await e.screenshot({path:l,type:n,quality:r})}else f=await this.deps.pageController.screenshot({path:l,type:n,quality:r,fullPage:a?!1:i,clip:a});return k.ok().build({selector:c||void 0,clip:a||void 0,message:`Screenshot taken: ${u}`,path:u,pathRewritten:d,size:f.length})}catch(e){return k.fail(e).build()}}async screenshotBatch(e,t,n,r){let i=this.deps.getActiveDriver()===`camoufox`,a=[];for(let o of e){let{absolutePath:e,displayPath:s}=await _({requestedPath:t?t.replace(/(\.\w+)$/,`-${o.replace(/[^a-zA-Z0-9]/g,`_`)}$1`):void 0,type:n,fallbackName:`element-${o.replace(/[^a-zA-Z0-9]/g,`_`)}`,fallbackDir:`screenshots/manual`});try{let t=0;if(i){let i=await(await this.deps.getCamoufoxPage()).$(o);if(!i){a.push({selector:o,success:!1,error:`Element not found: ${o}`});continue}t=(await i.screenshot({path:e,type:n,quality:r}))?.length??0}else{let i=await(await this.deps.pageController.getPage()).$(o);if(!i){a.push({selector:o,success:!1,error:`Element not found: ${o}`});continue}t=(await i.screenshot({path:e,type:n,quality:r})).length}a.push({selector:o,success:!0,path:s,size:t})}catch(e){a.push({selector:o,success:!1,error:String(e)})}}return k.ok().build({mode:`batch`,total:e.length,succeeded:a.filter(e=>e.success).length,results:a})}async handlePageInjectScript(e){try{let t=S(e,`script`,``);return await this.deps.pageController.injectScript(t),k.ok().build({message:`Script injected`})}catch(e){return k.fail(e).build()}}async handlePageWaitForSelector(e){try{let t=S(e,`selector`,``),n=E(e,`timeout`);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();try{await e.waitForSelector(t,{timeout:n||3e4});let r=await e.evaluate(e=>{let t=document.querySelector(e);return t?{tagName:t.tagName.toLowerCase(),id:t.id||void 0,className:t.className||void 0,textContent:t.textContent?.trim().substring(0,100)||void 0,attributes:Array.from(t.attributes).reduce((e,t)=>(e[t.name]=t.value,e),{})}:null},t);return k.ok().build({driver:`camoufox`,element:r,message:`Selector appeared: ${t}`})}catch{return k.fail(`Timeout waiting for selector: ${t}`).build({driver:`camoufox`})}}let r=await this.deps.pageController.waitForSelector(t,n);return k.ok().merge(r).build()}catch(e){return k.fail(e).build()}}},ye=class{deps;constructor(e){this.deps=e}safeOrigin(e){try{return new URL(e).origin}catch{return null}}async listCamoufoxFrames(){let e=this.deps.getCamoufoxPage;if(!e)throw Error(`Camoufox page is not available`);let t=await e(),n=t.frames(),r=t.mainFrame(),i=this.safeOrigin(r.url());return n.map((e,t)=>{let a=e.parentFrame(),o=this.safeOrigin(e.url()),s=a?n.findIndex(e=>e===a):-1;return{frameId:`frame-${t}`,url:e.url(),name:e.name()||``,parentFrameId:s>=0?`frame-${s}`:null,parentUrl:a?.url()||null,isMainFrame:e===r,crossOrigin:!!(e!==r&&o&&i&&o!==i)}})}async handlePageListFrames(e){try{let e=this.deps.getActiveDriver()===`camoufox`?await this.listCamoufoxFrames():await this.deps.pageController.listFrames();return k.ok().build({count:e.length,frames:e})}catch(e){return k.fail(e).build()}}async handleGetContent(e){try{let e=await this.deps.pageController.getContent();return k.ok().build({html:e})}catch(e){return k.fail(e).build()}}async handleGetTitle(e){try{let e=await this.deps.pageController.getTitle();return k.ok().build({title:e})}catch(e){return k.fail(e).build()}}async handleGetUrl(e){try{let e=await this.deps.pageController.getURL();return k.ok().build({url:e})}catch(e){return k.fail(e).build()}}async handleGetText(e){try{let t=S(e,`selector`,``),n=await this.deps.pageController.evaluate(`document.querySelector(${JSON.stringify(t)})?.textContent || ""`);return k.ok().build({selector:t,text:n})}catch(e){return k.fail(e).build()}}async handleGetOuterHtml(e){try{let t=S(e,`selector`,``),n=await this.deps.pageController.evaluate(`document.querySelector(${JSON.stringify(t)})?.outerHTML || ""`);return k.ok().build({selector:t,html:n})}catch(e){return k.fail(e).build()}}async handleGetScrollPosition(e){try{let e=await this.deps.pageController.evaluate(`({
|
|
2
|
-
scrollX: window.scrollX,
|
|
3
|
-
scrollY: window.scrollY,
|
|
4
|
-
maxScrollX: document.documentElement.scrollWidth - window.innerWidth,
|
|
5
|
-
maxScrollY: document.documentElement.scrollHeight - window.innerHeight
|
|
6
|
-
})`);return k.ok().build(e)}catch(e){return k.fail(e).build()}}async handlePageSetCookies(e){try{let t=e.cookies;return await this.deps.pageController.setCookies(t),k.ok().build({message:`Set ${t.length} cookies`})}catch(e){return k.fail(e).build()}}async handlePageGetCookies(e){try{let e=await this.deps.pageController.getCookies();return k.ok().build({count:e.length,cookies:e})}catch(e){return k.fail(e).build()}}async getPageCookieCount(){return(await this.deps.pageController.getCookies()).length}async handlePageClearCookies(e){try{return await this.deps.pageController.clearCookies(),k.ok().build({message:`Cookies cleared`})}catch(e){return k.fail(e).build()}}async handlePageSetViewport(e){try{let t=E(e,`width`,0),n=E(e,`height`,0);return await this.deps.pageController.setViewport(t,n),k.ok().build({viewport:{width:t,height:n}})}catch(e){return k.fail(e).build()}}async handlePageEmulateDevice(e){try{let t=S(e,`device`,``);return await this.deps.pageController.emulateDevice(t),k.ok().build({device:t})}catch(e){return k.fail(e).build()}}async handlePageGetLocalStorage(e){try{let e=await this.deps.pageController.getLocalStorage();return k.ok().build({count:Object.keys(e).length,storage:e})}catch(e){return k.fail(e).build()}}async handlePageSetLocalStorage(e){try{let t=S(e,`key`,``),n=S(e,`value`,``);return await this.deps.pageController.setLocalStorage(t,n),k.ok().build({key:t})}catch(e){return k.fail(e).build()}}},be=class{deps;constructor(e){this.deps=e}async handleConsoleMonitor(e){try{return S(e,`action`)===`enable`?(await this.deps.consoleMonitor.enable(),k.ok().build({message:`Console monitoring enabled`})):(await this.deps.consoleMonitor.disable(),k.ok().build({message:`Console monitoring disabled`}))}catch(e){return k.fail(e).build()}}async handleConsoleGetLogs(e){try{let t=S(e,`type`),n=E(e,`limit`),r=E(e,`since`),i=this.deps.consoleMonitor.getLogs({type:t,limit:n,since:r}),a={count:i.length,logs:i},o=this.deps.detailedDataManager.smartHandle(a,51200);return k.ok().merge(o).build()}catch(e){return k.fail(e).build()}}async handleConsoleExecute(e){try{let t=S(e,`expression`,``),n=E(e,`maxSize`,10485760),r=O(e,`stripBase64`,!1);if(!t.trim())return k.fail(`expression is required`).build();let i=P(await this.deps.consoleMonitor.execute(t),this.deps.detailedDataManager,{autoSummarize:!0,maxSize:n,stripBase64:r});return k.ok().build({result:i})}catch(e){return k.fail(e).build()}}},xe=class{deps;constructor(e){this.deps=e}async handleGetAllScripts(e){try{let t=O(e,`includeSource`,!1),n=i,r=Math.min(E(e,`maxScripts`,t?200:1e3),n),a=await this.deps.scriptManager.getAllScripts(t,r),o={count:a.length,scripts:a},s=this.deps.detailedDataManager.smartHandle(o);return k.ok().merge(s).build()}catch(e){return k.fail(e).build()}}async handleGetScriptSource(e){try{let t=S(e,`scriptId`),n=S(e,`url`),r=O(e,`preview`,!0),i=E(e,`maxLines`,100),a=E(e,`startLine`),o=E(e,`endLine`),s=await this.deps.scriptManager.getScriptSource(t,n);if(!s)return k.fail(`Script not found`).build();if(r||a!==void 0||o!==void 0){let e=s.source||``,t=e.split(`
|
|
7
|
-
`),n=t.length,r=e.length,c,l,u;a!==void 0&&o!==void 0?(l=Math.max(1,a),u=Math.min(n,o),c=t.slice(l-1,u).join(`
|
|
8
|
-
`)):(l=1,u=Math.min(i,n),c=t.slice(0,i).join(`
|
|
9
|
-
`));let d={scriptId:s.scriptId,url:s.url,preview:!0,totalLines:n,size:r,sizeKB:(r/1024).toFixed(1)+`KB`,showingLines:`${l}-${u}`,content:c,hint:r>51200?`Script is large (${(r/1024).toFixed(1)}KB). Use startLine/endLine to get specific sections, or set preview=false to get full source (will return detailId).`:`Set preview=false to get full source`};return k.ok().build(d)}let c=this.deps.detailedDataManager.smartHandle(s,51200);return k.ok().merge(c).build()}catch(e){return k.fail(e).build()}}},Se=class{deps;constructor(e){this.deps=e}async handleCaptchaDetect(e){try{let e=await this.deps.pageController.getPage(),t=await this.deps.captchaDetector.detect(e);return k.ok().build({captcha_detected:t.detected,captcha_info:t})}catch(e){return k.fail(e).build()}}async handleCaptchaWait(t){try{let n=E(t,`timeout`,this.deps.captchaTimeout),r=await this.deps.pageController.getPage();return e.info(`Waiting for CAPTCHA to be solved...`),await this.deps.captchaDetector.waitForCompletion(r,n)?k.ok().build({message:`CAPTCHA solved`}):k.fail(`CAPTCHA wait timed out`).build()}catch(e){return k.fail(e).build()}}async handleCaptchaConfig(e){try{return e.autoDetectCaptcha!==void 0&&this.deps.setAutoDetectCaptcha(O(e,`autoDetectCaptcha`,!1)),e.autoSwitchHeadless!==void 0&&this.deps.setAutoSwitchHeadless(O(e,`autoSwitchHeadless`,!1)),e.captchaTimeout!==void 0&&this.deps.setCaptchaTimeout(E(e,`captchaTimeout`,0)),k.ok().build({config:{autoDetectCaptcha:this.deps.autoDetectCaptcha,autoSwitchHeadless:this.deps.autoSwitchHeadless,captchaTimeout:this.deps.captchaTimeout}})}catch(e){return k.fail(e).build()}}};const Ce={enabled:!0,minDelayMs:20,maxDelayMs:80,burstMode:!1};var we=class t{static instance=null;cachedProfile=null;static DEFAULT_TTL_SEC=1800;static getInstance(){return t.instance||=new t,t.instance}async exportFromPage(n,r={}){let i=await n.cookies(),a=await n.evaluate(()=>{let e=navigator,t=e.userAgentData,n={secChUa:Array.isArray(t?.brands)?t.brands.map(e=>`"${e.brand}";v="${e.version}"`).join(`, `):void 0,secChUaMobile:typeof t?.mobile==`boolean`?t.mobile?`?1`:`?0`:void 0,secChUaPlatform:t?.platform?`"${t.platform}"`:void 0};return{userAgent:e.userAgent,platform:e.platform,acceptLanguage:e.language,referer:document.referrer||void 0,clientHints:n}}),o=r.origin??this.safeOrigin(n.url()),s=r.ttlSec??t.DEFAULT_TTL_SEC,c={cookies:i.map(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path,expires:e.expires,size:e.size,httpOnly:e.httpOnly,secure:e.secure,session:e.session,sameSite:e.sameSite,sourceScheme:e.sourceScheme})),userAgent:a.userAgent,acceptLanguage:a.acceptLanguage,referer:r.referer??a.referer,clientHints:a.clientHints,platform:a.platform,origin:o,collectedAt:Date.now(),ttlSec:s};return this.cachedProfile=c,e.info(`Session profile exported: cookies=${c.cookies.length}, origin=${c.origin??`unknown`}, ttlSec=${c.ttlSec}`),c}serialize(e){return JSON.stringify(e)}deserialize(e){let n=JSON.parse(e);return{cookies:Array.isArray(n.cookies)?n.cookies:[],userAgent:n.userAgent,acceptLanguage:n.acceptLanguage,referer:n.referer,clientHints:n.clientHints,platform:n.platform,origin:n.origin,collectedAt:typeof n.collectedAt==`number`?n.collectedAt:Date.now(),ttlSec:typeof n.ttlSec==`number`&&n.ttlSec>0?n.ttlSec:t.DEFAULT_TTL_SEC}}setProfile(e){this.cachedProfile=e}getProfile(){return this.cachedProfile}getValidProfile(e=Date.now()){return!this.cachedProfile||this.isExpired(this.cachedProfile,e)?null:this.cachedProfile}isExpired(e,t=Date.now()){return e.collectedAt+e.ttlSec*1e3<=t}clearProfile(){this.cachedProfile=null}static resetInstance(){t.instance=null}safeOrigin(e){if(!(!e||e===`about:blank`))try{return new URL(e).origin}catch{return}}};const Te=[{api:`navigator.webdriver`,method:`property override (configurable:false)`},{api:`window.chrome`,method:`object injection (runtime, loadTimes, csi)`},{api:`navigator.plugins`,method:`PluginArray override (spoofed length/names)`},{api:`Permissions.query`,method:`result filter (returns granted/prompt)`},{api:`HTMLCanvasElement.toDataURL/toBlob`,method:`pixel noise injection`},{api:`WebGLRenderingContext.getParameter`,method:`vendor/renderer override`},{api:`navigator.languages`,method:`array override (locale-specific)`},{api:`navigator.getBattery`,method:`fake BatteryManager`},{api:`MediaDevices.enumerateDevices`,method:`device list filter`},{api:`Notification.permission`,method:`permission override`},{api:`performance.now / Date.now`,method:`timing offset compensation`},{api:`CDP request timing`,method:`jitter compensation proxy`}],F={...Ce};let I=null;const L=we.getInstance();async function R(){if(I)return I;try{return I=(await import(`./FingerprintManager-N7BZqjxP.mjs`)).FingerprintManager.getInstance(),I}catch{return null}}var Ee=class{deps;constructor(e){this.deps=e}async handleStealthInject(t){try{if(this.deps.getActiveDriver()===`camoufox`)return k.ok().build({driver:`camoufox`,message:`Camoufox uses C++ engine-level fingerprint spoofing — JS-layer stealth scripts are not needed and have been skipped.`});let t=await this.deps.pageController.getPage(),n=await R(),r=!1;if(n?.isAvailable())try{let e=n.getActiveProfile();e||=await n.generateFingerprint(),e&&(await n.injectFingerprint(t,e),r=!0)}catch(t){e.warn(`Fingerprint injection failed, falling back to StealthScripts:`,t)}if(await h.injectAll(t),r&&n){let e=n.getActiveProfile(),t=L.getValidProfile(),r={cookies:t?.cookies??[],userAgent:e?.headers?.[`User-Agent`]??t?.userAgent,acceptLanguage:e?.headers?.[`Accept-Language`]??t?.acceptLanguage,referer:t?.referer,clientHints:t?.clientHints,platform:e?.os??t?.platform,origin:t?.origin,collectedAt:t?.collectedAt??Date.now(),ttlSec:t?.ttlSec??1800};L.setProfile(r)}return k.ok().build({message:`Stealth scripts injected successfully`,fingerprintApplied:r,patchManifest:Te,_nextStepHint:`Stealth patches are now active. Next: navigate to your target URL with page_navigate. Do NOT call stealth_inject again — it only needs to run once per page.`})}catch(e){return k.fail(e).build()}}async handleStealthSetUserAgent(e){try{let t=S(e,`platform`,`windows`),n=await this.deps.pageController.getPage();return await h.setRealisticUserAgent(n,t),k.ok().build({platform:t,message:`User-Agent set for ${t}`,_nextStepHint:`User-Agent is now configured. Next: call stealth_inject to apply all anti-detection patches, then page_navigate to your target URL.`})}catch(e){return k.fail(e).build()}}async handleStealthConfigureJitter(e){try{return e.enabled!==void 0&&(F.enabled=!!e.enabled),typeof e.minDelayMs==`number`&&(F.minDelayMs=e.minDelayMs),typeof e.maxDelayMs==`number`&&(F.maxDelayMs=e.maxDelayMs),e.burstMode!==void 0&&(F.burstMode=!!e.burstMode),k.ok().build({jitterOptions:F,message:`CDP timing jitter ${F.enabled?`enabled`:`disabled`}: ${F.minDelayMs}-${F.maxDelayMs}ms${F.burstMode?` (burst mode)`:``}`})}catch(e){return k.fail(e).build()}}async handleStealthGenerateFingerprint(e){try{if(this.deps.getActiveDriver()===`camoufox`)try{let t=await import(`camoufox-js/fingerprints`),n=S(e,`os`,`windows`),r=await t.generateFingerprint(n);return k.ok().build({fingerprint:r,driver:`camoufox`,message:`Fingerprint generated using camoufox native engine. Apply via browser_launch(fingerprint=...) before launching.`})}catch(e){return k.fail(`Camoufox fingerprint generation failed: ${e instanceof Error?e.message:String(e)}`).build()}let t=await R();if(!t?.isAvailable())return k.fail(`fingerprint-generator/fingerprint-injector packages are not installed. Install them with: pnpm add fingerprint-generator fingerprint-injector`).merge({available:!1,capability:`fingerprint_generator`,status:`unavailable`,fix:`Install fingerprint-generator and fingerprint-injector: pnpm add fingerprint-generator fingerprint-injector`}).build();let n=await t.generateFingerprint({os:e.os,browser:e.browser??`chrome`,locale:e.locale??`en-US`});return k.ok().build({profile:n,message:`Fingerprint generated and cached. It will be auto-applied on next stealth_inject.`})}catch(e){return k.fail(e).build()}}async handleStealthVerify(e){try{let e=await this.deps.pageController.getPage(),t=await new(await(import(`./StealthVerifier-Dhbj4B4P.mjs`))).StealthVerifier().verify(e);return k.ok().merge(t).build()}catch(e){return k.fail(`Stealth verification failed: ${e instanceof Error?e.message:String(e)}`).build()}}async handleCamoufoxGeolocation(e){try{let t=S(e,`locale`);if(!t)return k.fail(`locale is required (e.g. "en-US", "zh-CN")`).build();let n;try{n=await(await import(`camoufox-js/locale`)).getGeolocation(t)}catch(e){return k.fail(`Camoufox locale module unavailable: ${e instanceof Error?e.message:String(e)}. Ensure camoufox-js is installed.`).merge({available:!1,capability:`camoufox_locale`,status:`unavailable`,fix:`Install camoufox-js and fetch its browser assets: pnpm add camoufox-js && npx camoufox-js fetch`}).build()}let r=null,i=S(e,`proxy`);if(i)try{r=await(await import(`camoufox-js/ip`)).publicIP(i)}catch{}return k.ok().build({locale:t,geolocation:n,publicIp:r})}catch(e){return k.fail(e).build()}}},De=class{deps;constructor(e){this.deps=e}async handleFrameworkStateExtract(e){let t=S(e,`framework`,`auto`),n=S(e,`selector`,``),r=E(e,`maxDepth`,5);try{let e=await this.deps.getActivePage();try{let t=await e.createCDPSession();await Promise.race([t.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_unreachable`)),3e3))])}catch{throw new ee(`CDP session unresponsive — the debugger may be blocking page evaluation. Call debugger_lifecycle({ action: 'disable' })() before framework_state_extract, or run it before debugger_lifecycle({ action: 'enable' }).`)}let i=e.evaluate(e=>{let t=window;function n(e,t=0){if(t>4)return`[deep]`;if(e==null)return e;if(typeof e==`function`)return`[Function]`;if(typeof e!=`object`)return e;if(Array.isArray(e))return e.slice(0,20).map(e=>n(e,t+1));try{let r={},i=0;for(let a of Object.keys(e)){if(i++>30){r.__truncated__=!0;break}r[a]=n(e[a],t+1)}return r}catch{return`[unserializable]`}}let r=()=>e.selector?document.querySelector(e.selector)??document.body:document.getElementById(`root`)??document.getElementById(`app`)??document.querySelector(`[data-reactroot]`)??document.body,i=()=>{let t=r(),i=Object.keys(t).find(e=>e.startsWith(`__reactFiber`)||e.startsWith(`__reactInternalInstance`)||e.startsWith(`__reactFiberContainer`));if(!i)return null;let a=[],o=new WeakSet,s=(t,r)=>{if(!(!t||r>e.maxDepth||o.has(t))){if(o.add(t),t.memoizedState){let e=[],r=t.memoizedState,i=0;for(;r&&i++<20;){let t=r.queue,i=r.memoizedState===void 0?t?.lastRenderedState:r.memoizedState;i!==void 0&&e.push(n(i)),r=r.next??null}if(e.length>0){let n=t.type,r=typeof n==`object`&&n?String(n.name??`anonymous`):typeof n==`string`?n:`anonymous`;a.push({component:r,state:e})}}s(t.child??null,r+1),s(t.sibling??null,r+1)}};return s(t[i]??null,0),a},a=()=>{let t=r(),i=Object.keys(t).find(e=>e===`__vueParentComponent`||e===`__vue_app__`||e.startsWith(`__vue`));if(!i)return null;let a=t[i];if(!a)return null;let o=[],s=new WeakSet,c=(t,r)=>{if(!t||r>e.maxDepth||s.has(t))return;s.add(t);let i=n(t.setupState??t.ctx),a=n(t.$data??t.data);if(i||a){let e=t.type;o.push({component:e?.__name??`unknown`,setupState:i,data:a})}let l=t.subTree?.children;if(Array.isArray(l))for(let e of l)e?.component&&c(e.component,r+1)};return c(a,0),o},o=()=>{let t=r(),i=Object.keys(t).find(e=>e===`__vue__`);if(!i)return null;let a=t[i];if(!a)return null;let o=[],s=new WeakSet,c=(t,r)=>{if(!t||r>e.maxDepth||s.has(t))return;s.add(t);let i=t.$options;o.push({component:i?.name??`unknown`,data:n(t.$data)});let a=t.$children;if(Array.isArray(a))for(let e of a)c(e,r+1)};return c(a,0),o},s=()=>{let e=[],t=new WeakSet,i=document.querySelectorAll(`[class]`),a=[r(),...Array.from(i)],o=!1;for(let r of a){let i=r;if(!Object.keys(i).some(e=>e===`$$`||e===`__svelte_meta`||e.startsWith(`__s`)))continue;o=!0;let a=i.$$;if(!a||t.has(a))continue;t.add(a);let s=i.__svelte_meta?.loc?.file,c=a.ctx,l={};if(Array.isArray(c)){let e=0;for(let t of c.slice(0,20))t!==void 0&&typeof t!=`function`&&(l[`$${e}`]=n(t)),e++}let u=a.fragment;if((Object.keys(l).length>0||u)&&e.push({component:s??r.tagName?.toLowerCase()??`svelte-component`,state:[l],...s?{file:s}:{}}),e.length>=50)break}return o?e:null},c=()=>{let r=[],i=t._$DX,a=t._$HY;if(!i&&!a)return document.querySelector(`[data-hk]`)?(r.push({component:`SolidRoot`,state:[{_note:`Solid detected via hydration markers; install solid-devtools for full state extraction`}]}),r):null;if(i){let t=i.roots;if(t&&typeof t==`object`){let i=t instanceof Map?Array.from(t.values()):Object.values(t),a=0;for(let t of i){if(a++>=e.maxDepth*10)break;let i=t.name??`SolidComponent`,o=t.value??t.state;r.push({component:i,state:o?[n(o)]:[]})}}}return a&&r.length===0&&r.push({component:`SolidHydration`,state:[n(a)]}),r.length>0?r:null},l=()=>{let t=r(),i=Object.keys(t);if(i.some(e=>e.startsWith(`__reactFiber`)||e.startsWith(`__reactInternalInstance`))||!i.some(e=>e===`__k`||e===`__e`||e===`_dom`))return null;let a=[],o=new WeakSet,s=(t,r)=>{if(!t||r>e.maxDepth||o.has(t))return;o.add(t);let i=t.__c;if(i){let e=i.state,r=i.props,o=i.__H,s=[];if(o){let e=o.__;if(Array.isArray(e))for(let t of e.slice(0,20)){let e=t.__??t._value;e!==void 0&&s.push(n(e))}}let c=t.type,l=typeof c==`function`?c.displayName??c.name??`PreactComponent`:typeof c==`string`?c:`PreactComponent`;(e||s.length>0)&&a.push({component:String(l),state:s.length>0?s:e?[n(e)]:[],...r?{props:n(r)}:{}})}let c=t.__k;if(Array.isArray(c))for(let e of c)e&&s(e,r+1)},c=t.__k;if(Array.isArray(c))for(let e of c)e&&s(e,0);else if(t._children){let e=t._children;if(Array.isArray(e))for(let t of e)t&&s(t,0)}return a.length>0?a:null},u=()=>{let e=t.__NEXT_DATA__;if(e)return{framework:`nextjs`,route:e.page,buildId:e.buildId,runtimeConfig:n(e.runtimeConfig),props:n(e.props)};let r=t.__NUXT__;return r?r.config!==void 0||r._errors!==void 0?{framework:`nuxt3`,state:n(r.state),config:n(r.config),payload:n(r.data)}:{framework:`nuxt2`,state:n(r.state),serverRendered:r.serverRendered}:null},d=r(),f=Object.keys(d),p=f.some(e=>e.startsWith(`__reactFiber`)||e.startsWith(`__reactInternalInstance`)||e.startsWith(`__reactFiberContainer`)),m=f.some(e=>e===`__vueParentComponent`||e===`__vue_app__`),h=f.some(e=>e===`__vue__`),g=f.some(e=>e===`$$`||e===`__svelte_meta`||e.startsWith(`__s`)),_=t._$DX!==void 0||t._$HY!==void 0||!!document.querySelector(`[data-hk]`),v=f.some(e=>e===`__k`||e===`__e`||e===`_dom`||e===`_children`),y=e.framework;y===`preact`&&p&&(y=`react`),y===`auto`&&(p?y=`react`:m?y=`vue3`:h?y=`vue2`:g?y=`svelte`:_?y=`solid`:v&&(y=`preact`));let b=null;(y===`react`||y===`auto`)&&(b=i()),!b&&(y===`vue3`||y===`auto`)&&(b=a()),!b&&(y===`vue2`||y===`auto`)&&(b=o()),!b&&(y===`svelte`||y===`auto`)&&(b=s()),!b&&(y===`solid`||y===`auto`)&&(b=c()),!b&&(y===`preact`||y===`auto`)&&(b=l());let x=u();return{detected:y,states:b??[],found:b!==null&&b.length>0,...x?{meta:x}:{}}},{framework:t,selector:n,maxDepth:r}),a=await Promise.race([i,new Promise((e,t)=>setTimeout(()=>t(Error(`page.evaluate timed out after 30000ms`)),3e4))]);return k.ok().build(a)}catch(e){return k.fail(e).build()}}},Oe=class{deps;constructor(e){this.deps=e}async handleIndexedDBDump(e){let t=S(e,`database`,``),n=S(e,`store`,``),r=E(e,`maxRecords`,100);try{let e=await(await this.deps.getActivePage()).evaluate(async e=>{let t=await indexedDB.databases(),n={};for(let r of t){if(!r.name||e.database&&r.name!==e.database)continue;let t=r.name,i;try{i=await new Promise((e,n)=>{let i=r.version?indexedDB.open(t,r.version):indexedDB.open(t);i.addEventListener(`success`,()=>e(i.result),{once:!0}),i.addEventListener(`error`,()=>n(i.error),{once:!0})})}catch{n[t]={__error__:[`failed to open`]};continue}let a=Array.from(i.objectStoreNames),o={};for(let t of a)if(!(e.store&&t!==e.store))try{o[t]=await new Promise((n,r)=>{try{let a=i.transaction(t,`readonly`).objectStore(t).getAll();a.addEventListener(`success`,()=>n(a.result.slice(0,e.maxRecords)),{once:!0}),a.addEventListener(`error`,()=>r(a.error),{once:!0})}catch(e){r(e)}})}catch{o[t]=[`__error reading store__`]}i.close(),n[t]=o}return n},{database:t,store:n,maxRecords:r});return k.ok().build(e)}catch(e){return k.fail(e).build()}}},ke=class{deps;constructor(e){this.deps=e}async handleGetDetailedData(e){try{let t=S(e,`detailId`,``),n=S(e,`path`),r=this.deps.detailedDataManager.retrieve(t,n);return k.ok().build({detailId:t,path:n||`full`,data:r})}catch(e){return k.fail(e).set(`hint`,`DetailId may have expired (TTL: 10 minutes) or is invalid`).build()}}},Ae=class{deps;constructor(e){this.deps=e}async handleBrowserEvaluateCdpTarget(t){try{let e=S(t,`script`,``)||S(t,`code`,``)||S(t,`expression`,``),n=O(t,`autoSummarize`,!0),r=E(t,`maxSize`,51200),i=T(t,`fieldFilter`),a=O(t,`stripBase64`,!1),o=O(t,`returnByValue`,!0),s=O(t,`awaitPromise`,!0);if(!e.trim())return k.fail(`code, script, or expression is required`).build();let c=this.deps.pageController.getAttachedTargetInfo();if(!c)return k.fail(`No CDP target is currently attached. Call browser_attach_cdp_target(targetId="...") first.`).build();let l=P(await this.deps.pageController.evaluateAttachedTarget(e,{returnByValue:o,awaitPromise:s}),this.deps.detailedDataManager,{autoSummarize:n,maxSize:r,fieldFilter:i??void 0,stripBase64:a});return k.ok().build({target:c,result:l})}catch(t){return e.error(`Failed to evaluate in CDP target:`,t),k.fail(t instanceof Error?t.message:String(t)).build()}}},je=class{deps;constructor(e){this.deps=e}markMonitoringContextChanged(t){try{this.deps.consoleMonitor.markContextChanged()}catch(n){e.warn(`[${t}] Failed to mark monitoring context as stale: ${n instanceof Error?n.message:String(n)}`)}}safeOrigin(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}async syncAttachedPageContext(e){if(e.type!==`page`||!e.targetId)return{contextSwitched:!1,selectedIndex:null,selectedPageId:null,currentUrl:e.url??null,currentTitle:e.title??null};let t=await this.deps.collector.selectResolvedPageByTargetId(e.targetId);if(!t)return{contextSwitched:!1,selectedIndex:null,selectedPageId:null,currentUrl:e.url??null,currentTitle:e.title??null};let n=this.deps.getTabRegistry(),r=n.upsertPage(t.page,{index:t.index,url:t.url,title:t.title});return n.setCurrentPageId(r),{contextSwitched:!0,selectedIndex:t.index,selectedPageId:r,currentUrl:t.url,currentTitle:t.title}}async clearAttachedTargetContext(t){let n=this.deps.collector.getAttachedTargetInfo();if(!n)return{detached:!1,targetId:null,type:null};let r=await this.deps.collector.detachCdpTarget();return r&&e.info(`[${t}] Detached active CDP target ${n.targetId} before switching page context`),{detached:r,targetId:n.targetId,type:n.type??null}}async handleBrowserListCdpTargets(t){try{let e=S(t,`type`),n=T(t,`types`),r=S(t,`targetId`),i=S(t,`urlPattern`),a=S(t,`titlePattern`),o=O(t,`attachedOnly`,!1),s=O(t,`discoverOOPIF`,!0),c=await this.deps.collector.listCdpTargets({type:e??void 0,types:n??void 0,targetId:r??void 0,urlPattern:i??void 0,titlePattern:a??void 0,attachedOnly:o,discoverOOPIF:s}),l=this.deps.collector.getAttachedTargetInfo(),u=this.deps.getTabRegistry().getContextMeta(),d=await this.deps.collector.listPages(),f=typeof u.tabIndex==`number`?d[u.tabIndex]:void 0,p=f?.url??null,m=this.safeOrigin(p),h=c.map(e=>{let t=e.url,n=this.safeOrigin(t),r=p!==null&&t===p,i=m!==null&&n!==null&&m===n,a=l?.targetId===e.targetId,o=[];return a&&o.push(`active_target`),r&&o.push(`matches_current_tab_url`),!r&&i&&o.push(`same_origin_as_current_tab`),e.openerId&&l?.targetId===e.openerId&&o.push(`opened_by_active_target`),e.openerId&&!o.includes(`opened_by_active_target`)&&o.push(`has_opener_target`),e.openerFrameId&&o.push(`has_opener_frame`),{...e,isActiveTarget:a,matchesCurrentTabUrl:r,sameOriginAsCurrentTab:i,relationHints:o}});return k.ok().build({count:h.length,activeTarget:l,currentTab:f?{index:f.index,url:f.url,title:f.title}:null,filters:{type:e??null,types:n??null,targetId:r??null,urlPattern:i??null,titlePattern:a??null,attachedOnly:o},targets:h})}catch(t){return e.error(`Failed to list CDP targets:`,t),k.fail(t instanceof Error?t.message:String(t)).build()}}async handleBrowserAttachCdpTarget(t){try{let e=S(t,`targetId`);if(!e)throw Error(`targetId is required`);let n=await this.deps.collector.attachCdpTarget(e),r=await this.syncAttachedPageContext(n);return this.markMonitoringContextChanged(`browser_attach_cdp_target`),k.ok().build({attached:!0,target:n,...r})}catch(t){return e.error(`Failed to attach CDP target:`,t),k.fail(t instanceof Error?t.message:String(t)).build()}}async handleBrowserDetachCdpTarget(t){try{let e=this.deps.collector.getAttachedTargetInfo(),t=await this.deps.collector.detachCdpTarget();return t&&this.markMonitoringContextChanged(`browser_detach_cdp_target`),k.ok().build({detached:t,targetId:e?.targetId??null})}catch(t){return e.error(`Failed to detach CDP target:`,t),k.fail(t instanceof Error?t.message:String(t)).build()}}};const Me=[`hidden`,`array`,`string`,`object`,`code`,`closure`,`regexp`,`number`,`native`,`synthetic`,`concatenated string`,`sliced string`,`symbol`,`bigint`];function z(e){return typeof e==`object`&&!!e}function Ne(e){return z(e)&&typeof e.createCDPSession==`function`}function Pe(e){return z(e)&&typeof e.chunk==`string`}var Fe=class{deps;detailedDataManager;constructor(e){this.deps=e,this.detailedDataManager=d.getInstance()}async handleJSHeapSearch(t){let n=S(t,`pattern`,``)||S(t,`query`,``),r=E(t,`maxResults`,50),i=O(t,`caseSensitive`,!1);return n?re(async()=>{let t=null,a=!1;try{let o=await this.deps.getActivePage();if(!Ne(o))throw Error(`Active page does not support CDP session creation`);t=await o.createCDPSession(),a=!0,e.info(`[js_heap_search] Taking heap snapshot`,{patternLength:n.length,caseSensitive:i,maxResults:r}),await t.send(`HeapProfiler.enable`);let s=[],c=0;t.on(`HeapProfiler.addHeapSnapshotChunk`,e=>{Pe(e)&&(s.push(e.chunk),c+=e.chunk.length)}),await t.send(`HeapProfiler.takeHeapSnapshot`,{reportProgress:!1,treatGlobalObjectsAsRoots:!0,captureNumericValue:!1}),await t.send(`HeapProfiler.disable`),e.info(`[js_heap_search] Snapshot size: ${(c/1024).toFixed(1)} KB`);let l=s.join(``);s.length=0;let u=await this.searchSnapshot(l,n,r,i),d={success:!0,pattern:n,caseSensitive:i,snapshotSizeKB:Math.round(c/1024),matchCount:u.length,truncated:u.length>=r,matches:u,tip:u.length>0?`Use page_evaluate to inspect the objects at the paths found. E.g., eval the objectPath as a JS expression.`:`No matches found. The value may be encrypted, compressed, or stored in a non-string form.`};return k.ok().build(this.detailedDataManager.smartHandle(d,51200))}catch(t){return e.error(`[js_heap_search] Error:`,t),k.fail(t).build()}finally{if(a&&t)try{await t.detach()}catch{}}}):k.fail(`pattern is required`).build()}async searchSnapshot(t,n,r,i){try{let e;try{e=JSON.parse(t)}catch{return[]}if(typeof e!=`object`||!e||Array.isArray(e))return[];let a=e,o=a.strings,s=a.nodes,c=typeof a.snapshot==`object`&&a.snapshot!==null?a.snapshot:null,l=c&&typeof c.meta==`object`&&c.meta!==null?c.meta:null,u=l?.node_fields,d=l?.node_types;if(!Array.isArray(u)||!Array.isArray(o)||!Array.isArray(s))return[];let f=u.length;if(f===0)return[];let p=u.indexOf(`type`),m=u.indexOf(`name`),h=u.indexOf(`id`);if(p<0||m<0)return[];let g=Array.isArray(d)&&Array.isArray(d[0])?d[0]:[],_=i?n:n.toLowerCase(),v=[],y=Math.floor(s.length/f),b=o;for(let e=0;e<y&&v.length<r;e++){e>0&&e%1e3==0&&await new Promise(e=>setImmediate(e));let t=e*f,n=s[t+p],r=s[t+m];if(typeof r!=`number`||r<0||r>=b.length)continue;let a=g[n],o=(typeof a==`string`?a:void 0)??Me[n]??`type_${n}`;if(o!==`string`&&o!==`concatenated string`&&o!==`sliced string`)continue;let c=b[r];if(typeof c!=`string`||!(i?c:c.toLowerCase()).includes(_))continue;let l=h>=0?s[t+h]:void 0,u=l===void 0?e:l;v.push({nodeId:u,nodeType:o,value:c.length>200?`${c.slice(0,200)}…`:c,objectPath:`[HeapNode #${u}]`,nameHint:c.slice(0,80)})}return v}catch(t){return e.warn(`[js_heap_search] Snapshot parse error:`,t),[]}}};const Ie=new Set([`alias_bind`,`alias_open`,`navigate`,`wait_for`,`context_set`,`context_get`,`transfer`,`list`,`clear`]);function B(e){return typeof e==`object`&&!!e}function Le(e){return typeof e==`string`&&Ie.has(e)}function V(e){return B(e)&&typeof e.goto==`function`&&typeof e.waitForSelector==`function`&&typeof e.evaluate==`function`&&typeof e.url==`function`&&typeof e.title==`function`}function H(e){return!V(e)||!B(e)?!1:typeof e.context==`function`}function Re(e){return B(e)&&typeof e.newPage==`function`&&typeof e.pages==`function`}function U(e){return typeof e==`string`&&e.length>0?e:null}function ze(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null}function Be(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:t}var Ve=class{deps;constructor(e){this.deps=e}get registry(){return this.deps.getTabRegistry()}async handleTabWorkflow(t){let n=t.action;try{if(!Le(n))return k.fail(`Unknown action: "${String(n)}". Valid: list, alias_bind, alias_open, navigate, wait_for, context_set, context_get, transfer, clear`).build();switch(n){case`list`:return this.listAliases();case`clear`:return this.clearState();case`alias_bind`:return await this.aliasBind(t);case`alias_open`:return await this.aliasOpen(t);case`navigate`:return await this.navigateAlias(t);case`wait_for`:return await this.waitFor(t);case`context_set`:return this.contextSet(t);case`context_get`:return this.contextGet(t);case`transfer`:return await this.transfer(t)}}catch(r){let i=r instanceof Error?r.message:String(r);return e.error(`[tab_workflow] Action failed`,{action:typeof n==`string`?n:String(n),alias:typeof t.alias==`string`?t.alias:void 0,fromAlias:typeof t.fromAlias==`string`?t.fromAlias:void 0,error:i}),k.fail(i).build()}}listAliases(){let e=this.registry.getCurrentTabInfo(this.deps.getActiveDriver()),t=this.registry.getSharedContextMap();return k.ok().build({aliases:e.aliases,staleAliases:e.staleAliases,currentPageId:e.currentPageId,currentIndex:e.currentIndex,currentUrl:e.url,context:t})}clearState(){return this.registry.clear(),k.ok().build({cleared:!0})}async aliasBind(e){let t=U(e.alias),n=ze(e.index);if(!t)return k.fail(`alias is required`).build();if(n===null)return k.fail(`index is required`).build();await this.reconcilePages();let r=this.registry.bindAliasByIndex(t,n);return r?k.ok().build({bound:{alias:t,index:n,pageId:r}}):k.fail(`No active page at index ${n}. Use browser_list_tabs to check available pages.`).build()}async aliasOpen(e){let t=U(e.alias),n=U(e.url);if(!t)return k.fail(`alias is required`).build();if(!n)return k.fail(`url is required`).build();if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();if(!H(e))return k.fail(`Cannot open new tab: camoufox page context not accessible`).build();let r=e.context(),i=await r.newPage();await i.goto(n,{waitUntil:`domcontentloaded`});let a=r.pages().indexOf(i),o=await i.title(),s=this.registry.registerPage(i,{index:a,url:i.url(),title:o});return this.registry.bindAlias(t,s),k.ok().build({alias:t,index:a,pageId:s,url:i.url(),title:o})}let r=await this.getBrowserFromController();if(!r)return k.fail(`Cannot open new tab: browser instance not accessible via PageController`).build();let i=await r.newPage();await i.goto(n,{waitUntil:`domcontentloaded`});let a=(await r.pages()).indexOf(i),o=await i.title(),s=this.registry.registerPage(i,{index:a,url:i.url(),title:o});return this.registry.bindAlias(t,s),k.ok().build({alias:t,index:a,pageId:s,url:i.url(),title:o})}async navigateAlias(e){let t=U(e.alias),n=U(e.url);if(!t)return k.fail(`alias is required`).build();if(!n)return k.fail(`url is required`).build();let r=await this.getPageByAlias(t);return r?(await r.goto(n,{waitUntil:`domcontentloaded`}),k.ok().build({alias:t,navigated:n,currentUrl:r.url()})):k.fail(`No tab found for alias "${t}". Use alias_bind or alias_open first.`).build()}async waitFor(e){let t=U(e.alias),n=U(e.selector),r=U(e.waitForText),i=Be(e.timeoutMs,1e4);if(!t)return k.fail(`alias is required`).build();if(!n&&!r)return k.fail(`selector or waitForText is required`).build();let a=await this.getPageByAlias(t);if(!a)return k.fail(`No tab found for alias "${t}"`).build();if(n)return await a.waitForSelector(n,{timeout:i}),k.ok().build({alias:t,waitedFor:n,found:!0});let o=r,s=Date.now();for(;Date.now()-s<i;){let e=await a.evaluate(()=>document.body.innerText);if((typeof e==`string`?e:String(e??``)).includes(o))return k.ok().build({alias:t,waitedForText:o,found:!0});await new Promise(e=>setTimeout(e,500))}return k.fail(`Timeout waiting for text "${o}" in tab "${t}"`).build()}contextSet(e){let t=U(e.key),n=e.value;return t?(this.registry.setSharedContext(t,n),k.ok().build({set:{key:t,value:n}})):k.fail(`key is required`).build()}contextGet(e){let t=U(e.key);if(!t)return k.fail(`key is required`).build();let{value:n,found:r}=this.registry.getSharedContext(t);return k.ok().build({key:t,value:n,found:r})}async transfer(e){let t=U(e.fromAlias),n=U(e.key),r=U(e.expression);if(!t)return k.fail(`fromAlias is required`).build();if(!n)return k.fail(`key is required`).build();if(!r)return k.fail(`expression is required`).build();let i=await this.getPageByAlias(t);if(!i)return k.fail(`No tab found for alias "${t}"`).build();let a=await i.evaluate(r);return this.registry.setSharedContext(n,a),k.ok().build({transferred:{fromAlias:t,key:n,value:a}})}async getPageByAlias(e){let t=this.registry.resolveAlias(e);if(!t)return null;let n=this.registry.getPageById(t);if(n&&V(n))return n;await this.reconcilePages();let r=this.registry.getPageById(t);return r&&V(r)?r:null}async reconcilePages(){if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();if(H(e)){let t=e.context().pages(),n=await Promise.all(t.map(async(e,t)=>({index:t,url:e.url(),title:await e.title()})));this.registry.reconcilePages(t,n)}return}let e=await this.getBrowserFromController();if(!e)return;let t=await e.pages(),n=await Promise.all(t.map(async(e,t)=>({index:t,url:e.url(),title:await e.title()})));this.registry.reconcilePages(t,n)}async getBrowserFromController(){let e=this.deps.getPageController();if(!B(e)||typeof e.getBrowser!=`function`)return null;let t=await e.getBrowser();return Re(t)?t:null}};const He=new Set([`none`,`outside-only`,`dangerously`]),Ue=new Set([`get`,`set`,`clear`]),W=10*1024*1024,G=600*1e3;var We=class{sessions=new Map;createSessionId(){return se()}scheduleExpiry(t){let n=setTimeout(()=>{e.debug(`JSDOM session ${t} expired after ${G}ms`),this.closeSession(t)},G);return n.unref?.(),n}refreshSessionExpiry(e,t){clearTimeout(t.timer),t.timer=this.scheduleExpiry(e)}getSession(e){let t=this.sessions.get(e);if(!t)throw Error(`JSDOM session not found or expired: ${e}`);return this.refreshSessionExpiry(e,t),t}closeSession(t){let n=this.sessions.get(t);if(n){clearTimeout(n.timer);try{n.dom.window.close()}catch(t){e.debug(`JSDOM window close error: ${String(t)}`)}this.sessions.delete(t)}}closeAll(){for(let e of Array.from(this.sessions.keys()))this.closeSession(e)}async handleJsdomParse(e){try{let t=D(e,`html`);if(Buffer.byteLength(t,`utf8`)>W)return k.fail(`HTML input exceeds ${W/1024/1024}MB limit. Provide smaller HTML or use a URL.`).build();let n=S(e,`url`,`about:blank`),r=S(e,`contentType`,`text/html`),i=w(e,`runScripts`,He,`none`),a=O(e,`includeNodeLocations`,!1),o=O(e,`pretendToBeVisual`,!1),s=S(e,`referrer`,``),c=E(e,`storageQuotaBytes`,1e6);if(this.sessions.size>=5)return k.fail(`JSDOM session limit reached (5). Close existing sessions first with browser_jsdom_serialize + drop.`).build();let l={url:n,contentType:r,includeNodeLocations:a,pretendToBeVisual:o,storageQuota:c};i!==`none`&&(l.runScripts=i),s&&(l.referrer=s);let{JSDOM:u}=await import(`jsdom`),d=new u(t,l),f=this.createSessionId(),p={dom:d,url:n,runScripts:i,includeNodeLocations:a,createdAt:Date.now(),timer:this.scheduleExpiry(f)};this.sessions.set(f,p);let m=d.window.document;return k.ok().set(`sessionId`,f).set(`title`,m.title||``).set(`url`,n).set(`contentType`,r).set(`runScripts`,i).set(`ttlMs`,G).set(`activeSessions`,this.sessions.size).set(`stats`,{elements:m.getElementsByTagName(`*`).length,scripts:m.getElementsByTagName(`script`).length,links:m.getElementsByTagName(`a`).length,images:m.getElementsByTagName(`img`).length,stylesheets:m.querySelectorAll(`link[rel="stylesheet"], style`).length}).build()}catch(e){return k.fail(e).build()}}async handleJsdomQuery(e){try{let t=D(e,`sessionId`),n=D(e,`selector`),r=E(e,`maxResults`,50),i=O(e,`includeHtml`,!1),a=O(e,`includeText`,!0),o=O(e,`includeLocation`,!1),s=T(e,`attributes`),c=this.getSession(t),l=c.dom.window.document,u=Array.from(l.querySelectorAll(n)),d=u.slice(0,r).map(e=>{let t={tag:e.tagName.toLowerCase()};if(s.length>0){let n={};for(let t of s)n[t]=e.getAttribute(t);t.attributes=n}else{let n={};for(let t of Array.from(e.attributes))n[t.name]=t.value;t.attributes=n}if(a&&(t.text=(e.textContent??``).trim()),i&&(t.html=e.outerHTML),o&&c.includeNodeLocations)try{t.location=c.dom.nodeLocation(e)??null}catch{t.location=null}return t});return k.ok().set(`sessionId`,t).set(`selector`,n).set(`matched`,u.length).set(`returned`,d.length).set(`results`,d).build()}catch(e){return k.fail(e).build()}}async handleJsdomExecute(e){try{let t=D(e,`sessionId`),n=D(e,`code`),r=E(e,`timeoutMs`,5e3),i=this.getSession(t);if(i.runScripts===`none`)return k.fail(`JSDOM session was created with runScripts="none". Re-parse with runScripts="outside-only" or "dangerously" to execute code.`).build();let a=[],o=i.dom.window,s=o.console;o.console=qe(s,a);let c,l=null;try{c=o.eval(n)}catch(e){l=e instanceof Error?e.message:String(e)}finally{o.console=s}return l===null?k.ok().set(`sessionId`,t).set(`result`,K(c)).set(`consoleLogs`,a).set(`timeoutHintMs`,r).build():k.fail(l).set(`consoleLogs`,a).build()}catch(e){return k.fail(e).build()}}async handleJsdomSerialize(e){try{let t=D(e,`sessionId`),n=O(e,`pretty`,!1),r=S(e,`selector`,``),i=this.getSession(t),a;if(r){let e=i.dom.window.document.querySelector(r);if(!e)return k.fail(`No element matches selector: ${r}`).build();a=e.outerHTML}else a=i.dom.serialize();return n&&(a=Je(a)),k.ok().set(`sessionId`,t).set(`bytes`,Buffer.byteLength(a,`utf8`)).set(`pretty`,n).set(`html`,a).build()}catch(e){return k.fail(e).build()}}async handleJsdomCookies(e){try{let t=D(e,`sessionId`),n=w(e,`action`,Ue,`get`),r=this.getSession(t),i=r.dom.cookieJar,a=S(e,`url`,r.url);if(n===`get`){let e=await i.getCookies(a);return k.ok().set(`sessionId`,t).set(`url`,a).set(`cookies`,e.map(Ge)).build()}if(n===`set`){let n=C(e,`cookie`);if(!n)return k.fail(`cookie object required for action="set"`).build();let r=typeof n.raw==`string`?n.raw:Ke(n);return await i.setCookie(r,a),k.ok().set(`sessionId`,t).set(`action`,`set`).set(`cookie`,r).build()}let o=i.store;return o&&typeof o.removeAllCookies==`function`&&await new Promise((e,t)=>o.removeAllCookies(n=>n?t(n):e())),k.ok().set(`sessionId`,t).set(`action`,`clear`).build()}catch(e){return k.fail(e).build()}}};function Ge(e){return{key:e.key??``,value:e.value??``,domain:e.domain??null,path:e.path??null,expires:e.expires instanceof Date?e.expires.toISOString():e.expires??null,httpOnly:e.httpOnly===!0,secure:e.secure===!0,sameSite:e.sameSite??null}}function Ke(e){let t=String(e.name??e.key??``),n=String(e.value??``);if(!t)throw Error(`cookie.name (or cookie.key) is required`);let r=[`${t}=${n}`];return typeof e.domain==`string`&&r.push(`Domain=${e.domain}`),typeof e.path==`string`&&r.push(`Path=${e.path}`),typeof e.expires==`string`&&r.push(`Expires=${e.expires}`),typeof e.maxAge==`number`&&r.push(`Max-Age=${e.maxAge}`),e.secure===!0&&r.push(`Secure`),e.httpOnly===!0&&r.push(`HttpOnly`),typeof e.sameSite==`string`&&r.push(`SameSite=${e.sameSite}`),r.join(`; `)}function qe(e,t){let n=[`log`,`info`,`warn`,`error`,`debug`,`trace`],r={};for(let i of n)r[i]=(...n)=>{t.push({level:i,args:n.map(e=>K(e))});let r=e?.[i];if(typeof r==`function`)try{r.apply(e,n)}catch{}};return r}function K(e){if(e==null)return e;let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return e;if(t===`bigint`)return`${e.toString()}n`;if(t===`function`)return`[Function: ${e.name||`anonymous`}]`;if(t===`symbol`)return String(e);try{return JSON.parse(JSON.stringify(e))}catch{return String(e)}}function Je(e){return e.replace(/>(?=<)/g,`>
|
|
10
|
-
`)}let q=0;var Ye=class{pageIdByHandle=new WeakMap;tabsById=new Map;aliasToPageId=new Map;currentPageId=null;sharedContext=new Map;upsertPage(e,t){let n=this.pageIdByHandle.get(e),r=n?this.tabsById.get(n)?.meta:null,i=typeof t.index==`number`&&Number.isFinite(t.index)?t.index:r?.index??0;return this.registerPage(e,{index:i,url:t.url,title:t.title})}registerPage(t,n){let r=t,i=this.pageIdByHandle.get(r);if(i){let e=this.tabsById.get(i);return e?(e.meta=n,e.stale=!1):this.tabsById.set(i,{page:t,meta:n,stale:!1}),i}q+=1;let a=`tab-${q}`;return this.pageIdByHandle.set(r,a),this.tabsById.set(a,{page:t,meta:n,stale:!1}),e.debug(`[TabRegistry] Registered page ${a} (index=${n.index}, url=${n.url})`),a}reconcilePages(t,n){let r=new Set;for(let e=0;e<t.length;e++){let i=t[e],a=n[e]??{index:e,url:``,title:``},o=this.registerPage(i,{...a,index:e});r.add(o)}let i=[];for(let[t,n]of this.tabsById)r.has(t)||(n.stale?i.push(t):(n.stale=!0,e.debug(`[TabRegistry] Page ${t} marked stale`)));for(let t of i)this.tabsById.delete(t),e.debug(`[TabRegistry] Page ${t} pruned (was already stale)`);return this.currentPageId&&!r.has(this.currentPageId)&&(e.debug(`[TabRegistry] Current page ${this.currentPageId} is stale, clearing`),this.currentPageId=null),this.listTabs()}bindAlias(e,t){return this.tabsById.has(t)?(this.aliasToPageId.set(e,t),!0):!1}bindAliasByIndex(e,t){for(let[n,r]of this.tabsById)if(r.meta.index===t&&!r.stale)return this.aliasToPageId.set(e,n),n;return null}unbindAlias(e){return this.aliasToPageId.delete(e)}resolveAlias(e){let t=this.aliasToPageId.get(e);if(!t)return null;let n=this.tabsById.get(t);return!n||n.stale?null:t}getPageById(e){let t=this.tabsById.get(e);return!t||t.stale?null:t.page}getTabById(e){let t=this.tabsById.get(e);if(!t)return null;let n=this.getAliasesForPageId(e);return{pageId:e,index:t.meta.index,url:t.meta.url,title:t.meta.title,page:t.page,aliases:n,stale:t.stale}}getTabByIndex(e){for(let[t,n]of this.tabsById)if(n.meta.index===e&&!n.stale)return this.getTabById(t);return null}findTab(e){for(let[t]of this.tabsById){let n=this.getTabById(t);if(n&&e(n))return n}return null}setCurrentPageId(e){let t=this.tabsById.get(e);return!t||t.stale?!1:(this.currentPageId=e,!0)}setCurrentByIndex(e){let t=this.getTabByIndex(e);return t&&(this.currentPageId=t.pageId),t}getCurrentPageId(){return this.currentPageId}getCurrentPage(){return this.currentPageId?this.getPageById(this.currentPageId):null}getCurrentTabInfo(e){let t=[],n=[];for(let[e,r]of this.aliasToPageId){let i=this.tabsById.get(r),a=!i||i.stale;t.push({alias:e,pageId:r,index:i?.meta.index??null,stale:a}),a&&n.push(e)}let r=this.currentPageId?this.tabsById.get(this.currentPageId):null,i=r&&!r.stale?r:null;return{driver:e,currentPageId:i?this.currentPageId:null,currentIndex:i?.meta.index??null,url:i?.meta.url??null,title:i?.meta.title??null,aliases:t,staleAliases:n}}getContextMeta(){let e=this.currentPageId?this.tabsById.get(this.currentPageId):null,t=e&&!e.stale?e:null;return{url:t?.meta.url??null,title:t?.meta.title??null,tabIndex:t?.meta.index??null,pageId:t?this.currentPageId:null}}listTabs(){let e=[];for(let[t,n]of this.tabsById)if(!n.stale){let r=this.getAliasesForPageId(t);e.push({pageId:t,index:n.meta.index,url:n.meta.url,title:n.meta.title,page:n.page,aliases:r,stale:!1})}return e.toSorted((e,t)=>e.index-t.index)}listAllTabs(){let e=[];for(let[t,n]of this.tabsById){let r=this.getAliasesForPageId(t);e.push({pageId:t,index:n.meta.index,url:n.meta.url,title:n.meta.title,page:n.page,aliases:r,stale:n.stale})}return e.toSorted((e,t)=>e.index-t.index)}setSharedContext(e,t){this.sharedContext.set(e,t)}getSharedContext(e){return{value:this.sharedContext.get(e)??null,found:this.sharedContext.has(e)}}getSharedContextMap(){let e={};return this.sharedContext.forEach((t,n)=>{e[n]=t}),e}clear(){this.tabsById.clear(),this.aliasToPageId.clear(),this.sharedContext.clear(),this.currentPageId=null}getAliasesForPageId(e){let t=[];for(let[n,r]of this.aliasToPageId)r===e&&t.push(n);return t}};function Xe(e){let t={getActiveDriver:e.getActiveDriver,getCamoufoxPage:e.getCamoufoxPage},n=new Ye,r=new je({collector:e.collector,consoleMonitor:e.consoleMonitor,getTabRegistry:()=>n});return{tabRegistry:n,targetControl:r,browserControl:new de({collector:e.collector,pageController:e.pageController,consoleMonitor:e.consoleMonitor,getActiveDriver:e.getActiveDriver,getCamoufoxManager:e.getCamoufoxManager,getCamoufoxPage:e.getCamoufoxPage,getTabRegistry:()=>n,clearAttachedTargetContext:e=>r.clearAttachedTargetContext(e)}),camoufoxBrowser:new me({getCamoufoxManager:e.getCamoufoxManager,setCamoufoxManager:e.setCamoufoxManager,closeCamoufox:e.closeCamoufox}),pageNavigation:new ge({pageController:e.pageController,consoleMonitor:e.consoleMonitor,getTabRegistry:()=>n,eventBus:e.eventBus,...t}),pageInteraction:new _e({pageController:e.pageController,...t}),pageEvaluation:new ve({pageController:e.pageController,detailedDataManager:e.detailedDataManager,...t}),targetEvaluation:new Ae({pageController:e.pageController,detailedDataManager:e.detailedDataManager}),pageData:new ye({pageController:e.pageController,...t}),consoleHandlers:new be({consoleMonitor:e.consoleMonitor,detailedDataManager:e.detailedDataManager}),scriptManagement:new xe({scriptManager:e.scriptManager,detailedDataManager:e.detailedDataManager}),captchaHandlers:new Se({pageController:e.pageController,captchaDetector:e.captchaDetector,autoDetectCaptcha:e.getAutoDetectCaptcha(),autoSwitchHeadless:e.getAutoSwitchHeadless(),captchaTimeout:e.getCaptchaTimeout(),setAutoDetectCaptcha:e.setAutoDetectCaptcha,setAutoSwitchHeadless:e.setAutoSwitchHeadless,setCaptchaTimeout:e.setCaptchaTimeout}),stealthInjection:new Ee({pageController:e.pageController,...t}),frameworkState:new De({getActivePage:()=>e.collector.getActivePage()}),indexedDBDump:new Oe({getActivePage:()=>e.collector.getActivePage()}),jsHeapSearch:new Fe({getActivePage:()=>e.collector.getActivePage(),getActiveDriver:e.getActiveDriver}),tabWorkflow:new Ve({getActiveDriver:e.getActiveDriver,getCamoufoxPage:e.getCamoufoxPage,getPageController:()=>e.pageController,getTabRegistry:()=>n}),detailedData:new ke({detailedDataManager:e.detailedDataManager}),jsdomHandlers:new We}}function Ze(e,t,n,r,i){let a=1-i,o=a*a,s=o*a,c=i*i,l=c*i;return{x:s*e.x+3*o*i*t.x+3*a*c*n.x+l*r.x,y:s*e.y+3*o*i*t.y+3*a*c*n.y+l*r.y}}function Qe(e,t){let n=t.x-e.x,r=t.y-e.y,i=-r,a=n,o=Math.sqrt(i*i+a*a)||1,s=(Math.random()-.5)*.4,c=(Math.random()-.5)*.4;return[{x:e.x+n*.3+i/o*Math.abs(n+r)*s,y:e.y+r*.3+a/o*Math.abs(n+r)*s},{x:e.x+n*.7+i/o*Math.abs(n+r)*c,y:e.y+r*.7+a/o*Math.abs(n+r)*c}]}function $e(e,t){switch(t){case`linear`:return e;case`ease-in`:return e*e;case`ease-out`:return 1-(1-e)*(1-e);default:return e<.5?2*e*e:1-(-2*e+2)**2/2}}function J(e){return new Promise(t=>setTimeout(t,e))}function Y(e){let t=S(e,`frameUrl`),n=S(e,`frameSelector`);if(!(!t&&!n))return{frameUrl:t||void 0,frameSelector:n||void 0}}async function X(e,t,n){let r=await e.getActivePage();if(!r)return null;if(!n?.frameUrl&&!n?.frameSelector)return{page:r,context:r};if(!t)throw Error(`frameUrl/frameSelector requires PageController`);return{page:r,context:await t.resolveFrame(r,n)}}async function et(e,t,n){if(t===e||typeof t.frameElement!=`function`)return n;let r=await t.frameElement(),i=r&&typeof r.boundingBox==`function`?await r.boundingBox():null;return i?{x:i.x+n.x,y:i.y+n.y}:n}async function tt(e,t,n){try{let r=Y(e),i=await X(t,n,r);if(!i)return k.fail(`No active page. Use browser_launch or browser_attach first.`).build();let{page:a,context:o}=i,s=E(e,`toX`),c=E(e,`toY`),l=S(e,`selector`);if(l){let e=await o.evaluate(e=>{let t=document.querySelector(e);if(!t)return null;let n=t.getBoundingClientRect();return{x:n.x+n.width/2,y:n.y+n.height/2}},l);if(!e)return k.fail(`Selector not found: ${l}`).build();let t=await et(a,o,e);s=t.x,c=t.y}if(s===void 0||c===void 0)return k.fail(`Either selector or toX/toY coordinates are required`).build();let u=E(e,`fromX`,0),d=E(e,`fromY`,0),f=Math.max(1,Math.min(E(e,`steps`,24),500)),p=Math.max(10,Math.min(E(e,`durationMs`,600),3e4)),m=Math.max(0,Math.min(E(e,`jitterPx`,1.5),20)),h=S(e,`curve`,`ease`),g=O(e,`click`,!1),_={x:u,y:d},v={x:s,y:c},[y,b]=Qe(_,v),x=p/f;for(let e=0;e<=f;e++){let t=Ze(_,y,b,v,$e(e/f,h));e>0&&e<f&&(t.x+=(Math.random()-.5)*2*m,t.y+=(Math.random()-.5)*2*m),t.x=Math.max(0,t.x),t.y=Math.max(0,t.y),await a.mouse.move(t.x,t.y),await J(x*(.8+Math.random()*.4))}return g&&await a.mouse.click(s,c),k.ok().build({from:{x:u,y:d},to:{x:s,y:c},steps:f,durationMs:p,clicked:g,...r?{frame:r}:{}})}catch(e){return k.fail(e).build()}}async function nt(e,t){try{let n=await t.getActivePage();if(!n)return k.fail(`No active page.`).build();let r=Math.max(1,Math.min(E(e,`distance`,500),1e4)),i=S(e,`direction`,`down`),a=Math.max(10,Math.min(E(e,`durationMs`,1500),3e4)),o=Math.max(1,Math.min(E(e,`segments`,8),200)),s=typeof e.pauseMs==`number`&&Number.isFinite(e.pauseMs)?Math.max(0,Math.min(E(e,`pauseMs`,80),5e3)):Math.max(0,Math.min(Math.round(a/o),5e3)),c=Math.max(0,Math.min(E(e,`jitter`,.3),1)),l=S(e,`selector`),u=i===`up`||i===`down`,d=i===`down`||i===`right`?1:-1,f=0;for(let e=0;e<o;e++){let t=1-e/o*.4,i=r/o*t*(1+(Math.random()-.5)*c*2),a=Math.min(i,r-f);if(a<=0)break;let p=u?0:a*d,m=u?a*d:0;l?await n.evaluate((e,t,n)=>{let r=document.querySelector(e);r&&r.scrollBy({left:t,top:n,behavior:`auto`})},l,p,m):await n.evaluate((e,t)=>window.scrollBy({left:e,top:t,behavior:`auto`}),p,m),f+=a,await J(s*(.5+Math.random()))}return k.ok().build({direction:i,requestedDistance:r,actualScrolled:Math.round(f),durationMs:a,pauseMs:s,segments:o})}catch(e){return k.fail(e).build()}}async function rt(e,t,n){try{let r=Y(e),i=await X(t,n,r);if(!i)return k.fail(`No active page.`).build();let{page:a,context:o}=i,s=S(e,`selector`,``),c=S(e,`text`,``),l=Math.max(10,Math.min(E(e,`wpm`,90),300)),u=Math.max(0,Math.min(E(e,`errorRate`,.02),.3)),d=Math.max(50,Math.min(E(e,`correctDelayMs`,200),2e3)),f=O(e,`clearFirst`,!1);if(!s||!c)return k.fail(`selector and text are required`).build();let p=6e4/(l*5);await o.click(s),f&&await o.evaluate(e=>{let t=document.querySelector(e);t&&(t.value=``)},s);let m=0;for(let e of c){if(Math.random()<u&&e!==` `){let t=String.fromCharCode(e.charCodeAt(0)+(Math.random()>.5?1:-1));await a.keyboard.type(t,{delay:0}),await J(d*(.5+Math.random())),await a.keyboard.press(`Backspace`),await J(50+Math.random()*50),m++}await a.keyboard.type(e,{delay:0});let t=p*(.5+Math.random());(e===` `||`.,:;!?`.includes(e))&&(t*=1.5+Math.random()*.5),await J(t)}return k.ok().build({selector:s,length:c.length,wpm:l,typosSimulated:m,errorRate:u,...r?{frame:r}:{}})}catch(e){return k.fail(e).build()}}function it(e){return new Promise(t=>setTimeout(t,e))}function Z(e){let t=typeof e==`string`?e.toLowerCase():``;return t===`hook`?`hook`:t===`external_service`||t===`2captcha`||t===`anticaptcha`||t===`capsolver`?`external_service`:`manual`}function at(e){let t=typeof e==`string`?e.toLowerCase():``;return t===`image`?`image`:t===`widget`||t===`recaptcha_v2`||t===`recaptcha_v3`||t===`hcaptcha`||t===`funcaptcha`||t===`turnstile`?`widget`:t===`browser_check`||t===`managed_widget`?`browser_check`:`auto`}function ot(e){if(!(typeof e!=`string`||!e.trim()))return e.trim().toLowerCase()}function Q(e){let t=ot(e.provider),n=(process.env.CAPTCHA_PROVIDER||``).trim().toLowerCase();return t||n||`2captcha`}async function $(e,t,i){let o=Date.now(),s=a;if(!s)throw Error(`CAPTCHA_SOLVER_BASE_URL must be configured before using external_service mode.`);let l={key:e,json:1};t.taskKind===`turnstile`||t.taskKind===`recaptcha_v2`||t.taskKind===`hcaptcha`?(l.method=t.taskKind===`turnstile`?`turnstile`:t.taskKind===`hcaptcha`?`hcaptcha`:`userrecaptcha`,l.sitekey=t.siteKey,l.pageurl=t.pageUrl):(l.method=`base64`,l.body=t.imageBase64);let u=await(await fetch(`${s}/in.php`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(l),signal:AbortSignal.timeout(c)})).json();if(u.status!==1)throw Error(`2captcha submit failed: ${JSON.stringify(u)}`);let d=u.request,f=r;for(;;){let r=i-(Date.now()-o);if(r<=0||(await it(Math.min(f,r)),Date.now()-o>=i))break;let a=new URL(`${s}/res.php`);a.searchParams.set(`key`,e),a.searchParams.set(`action`,`get`),a.searchParams.set(`id`,d),a.searchParams.set(`json`,`1`);let c=await(await fetch(a.toString(),{signal:AbortSignal.timeout(n)})).json();if(c.status===1)return{token:c.request,challengeType:t.taskKind===`image`?`image`:`widget`,mode:`external_service`,durationMs:Date.now()-o};if(c.request!==`CAPCHA_NOT_READY`)throw Error(`2captcha solve failed: ${JSON.stringify(c)}`)}throw Error(`2captcha solve timeout after ${i}ms`)}async function st(n,r){let i=await r.getActivePage();if(!i)return k.fail(`No active page.`).build();let a=Z(n.mode??n.provider??process.env.CAPTCHA_PROVIDER),c=Q(n),d=S(n,`apiKey`,``)||process.env.CAPTCHA_API_KEY||``,f=at(n.challengeType??n.typeHint),p=Math.min(Math.max(E(n,`timeoutMs`,o),s),l),m=Math.min(Math.max(E(n,`maxRetries`,u),0),t),h=f,g=f===`image`?`image`:`recaptcha_v2`,_=S(n,`siteKey`),v=S(n,`pageUrl`,``)||i.url();if(h===`auto`){let e=await i.evaluate(()=>{if(document.querySelector(`[data-sitekey]`)){let e=document.querySelector(`[data-sitekey]`)?.getAttribute(`data-sitekey`)||``;return document.querySelector(`.cf-turnstile`)?{challengeType:`widget`,taskKind:`turnstile`,siteKey:e}:document.querySelector(`.h-captcha`)?{challengeType:`widget`,taskKind:`hcaptcha`,siteKey:e}:{challengeType:`widget`,taskKind:`recaptcha_v2`,siteKey:e}}return document.querySelector(`iframe[src*="recaptcha"]`)?{challengeType:`widget`,taskKind:`recaptcha_v2`,siteKey:``}:document.querySelector(`iframe[src*="hcaptcha"]`)?{challengeType:`widget`,taskKind:`hcaptcha`,siteKey:``}:document.querySelector(`.cf-turnstile`)?{challengeType:`widget`,taskKind:`turnstile`,siteKey:``}:{challengeType:`image`,taskKind:`image`,siteKey:``}});h=e.challengeType,g=e.taskKind,!_&&e.siteKey&&(_=e.siteKey)}else g=h===`image`?`image`:`recaptcha_v2`;if(a===`manual`)return k.ok().build({mode:`manual`,challengeType:h,siteKey:_??null,instruction:`Please solve the CAPTCHA manually in the browser, then continue.`,hint:`Configure an external solver service and CAPTCHA_API_KEY to automate this flow.`});if(!d)return k.fail(`External solver credentials are required. Set CAPTCHA_API_KEY.`).build();let y=null;for(let t=0;t<=m;t++)try{let e;if(c===`2captcha`)e=await $(d,{taskKind:g,siteKey:_,pageUrl:v},p);else if(c===`anticaptcha`||c===`capsolver`)throw Error(`The selected external solver service is not yet implemented. Currently only the configured primary service and manual mode are supported.`);else throw Error(`Unsupported external solver service.`);return k.ok().build({token:e.token,challengeType:e.challengeType,mode:e.mode,durationMs:e.durationMs,attempt:t+1})}catch(n){y=n instanceof Error?n:Error(String(n)),e.warn(`[captcha] Attempt ${t+1} failed: ${y.message}`)}return k.fail(y??Error(`All attempts failed`)).merge({challengeType:h,mode:a,maxRetries:m,suggestion:`Try manual mode or adjust the external solver configuration.`}).build()}async function ct(e,t){let n=await t.getActivePage();if(!n)return k.fail(`No active page.`).build();let r=Z(e.mode??e.provider??process.env.CAPTCHA_PROVIDER),i=Q(e),a=S(e,`apiKey`,``)||process.env.CAPTCHA_API_KEY||``,o=Math.min(Math.max(E(e,`timeoutMs`,12e4),5e3),6e5),s=O(e,`injectToken`,!0),c=S(e,`siteKey`),l=S(e,`pageUrl`,``)||n.url();if(c||=await n.evaluate(()=>document.querySelector(`.cf-turnstile[data-sitekey], [data-sitekey]`)?.getAttribute(`data-sitekey`)??``)||void 0,!c)return k.fail(`Could not detect the widget siteKey. Provide it manually or ensure the page exposes a site key.`).build();if(r===`hook`){let e=Math.min(o,3e4),t=await n.evaluate(e=>new Promise((t,n)=>{let r=setTimeout(()=>n(Error(`Hook timeout`)),e),i=window.__turnstile_callbacks;if(i)for(let[e,n]of Object.entries(i))i[e]=e=>{clearTimeout(r),t(e),n(e)};else clearTimeout(r),n(Error(`No widget callbacks found. Try external_service mode instead.`))}),e).catch(()=>null);if(t)return k.ok().build({token:t,method:`hook`,challengeType:`widget`,siteKey:c})}if(r===`manual`)return k.ok().build({mode:`manual`,challengeType:`widget`,siteKey:c,pageUrl:l,instruction:`Please complete the widget challenge manually.`});if(i!==`2captcha`)return k.fail(`The selected external solver service is not implemented for this widget flow. Currently only the configured primary service, manual mode, and hook mode are supported.`).build();if(!a)return k.fail(`External solver credentials are required.`).build();try{let e=await $(a,{taskKind:`turnstile`,siteKey:c,pageUrl:l},o);return s&&e.token&&await n.evaluate(e=>{document.querySelectorAll(`input[name*="turnstile"], input[name*="cf-turnstile"]`).forEach(t=>{t.value=e}),window.turnstile?.getResponse},e.token),k.ok().build({token:e.token,challengeType:e.challengeType,siteKey:c,mode:e.mode,durationMs:e.durationMs,injected:s})}catch(e){return k.fail(e).merge({siteKey:c,mode:r,suggestion:`Try manual mode or hook mode.`}).build()}}function lt(){return(process.env.CAPTCHA_PROVIDER||``).trim().toLowerCase()||`manual`}function ut(){return process.env.CAPTCHA_SOLVER_BASE_URL?.trim()||process.env.CAPTCHA_2CAPTCHA_BASE_URL?.trim()||``}function dt(){let e=lt(),t=ut(),n=!!process.env.CAPTCHA_API_KEY?.trim(),r=t.length>0,i=n&&r;return{capability:`captcha_external_service_2captcha`,status:i?`available`:`unavailable`,reason:i?void 0:`The 2captcha-compatible external path needs both CAPTCHA_API_KEY and CAPTCHA_SOLVER_BASE_URL.`,fix:i?void 0:`Set CAPTCHA_API_KEY and CAPTCHA_SOLVER_BASE_URL to enable external_service mode.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:e,defaultExternalProviderSupported:e===`2captcha`,apiKeyConfigured:n,baseUrlConfigured:r,...r?{baseUrl:t}:{}}}}async function ft(e){let t;try{t=await e.getActivePage()}catch(e){return{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Attach or launch a browser page before using hook mode.`,details:{tools:[`widget_challenge_solve`],pageAttached:!1}}}if(!t)return{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`No active page is attached.`,fix:`Attach or launch a browser page before using hook mode.`,details:{tools:[`widget_challenge_solve`],pageAttached:!1}};try{let e=await t.evaluate(()=>{let e=window.__turnstile_callbacks,t=e&&typeof e==`object`&&!Array.isArray(e)?Object.keys(e).length:0;return{url:location.href,callbackCount:t}});return{capability:`captcha_widget_hook_current_page`,status:e.callbackCount>0?`available`:`unavailable`,reason:e.callbackCount>0?void 0:`The current page does not expose window.__turnstile_callbacks for hook mode.`,fix:e.callbackCount>0?void 0:`Use manual mode, or configure the external 2captcha-compatible service for widget solving.`,details:{tools:[`widget_challenge_solve`],pageAttached:!0,...e}}}catch(e){return{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`Current page probe failed: ${e instanceof Error?e.message:String(e)}`,fix:`Ensure the attached page is reachable before using hook mode.`,details:{tools:[`widget_challenge_solve`],pageAttached:!0}}}}async function pt(e){let t=lt(),n=await ft(e);return k.raw(ae(`captcha_solver_capabilities`,[{capability:`captcha_manual`,status:`available`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`]}},dt(),{capability:`captcha_external_service_anticaptcha`,status:`unavailable`,reason:`AntiCaptcha integration is not implemented in this build.`,fix:`Use manual mode or the configured 2captcha-compatible service instead.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:t}},{capability:`captcha_external_service_capsolver`,status:`unavailable`,reason:`CapSolver integration is not implemented in this build.`,fix:`Use manual mode or the configured 2captcha-compatible service instead.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:t}},n],{configuredProvider:t}))}function mt(e){let t=T(e,`addons`),n=T(e,`excludeAddons`),r=T(e,`fonts`);return{headless:O(e,`headless`,!0),os:S(e,`os`,`windows`),geoip:O(e,`geoip`,!1),humanize:O(e,`humanize`,!1),proxy:S(e,`proxy`)||void 0,blockImages:O(e,`blockImages`,!1),blockWebrtc:O(e,`blockWebrtc`,!1),blockWebgl:O(e,`blockWebgl`,!1),locale:S(e,`locale`)||void 0,addons:t.length>0?t:void 0,fonts:r.length>0?r:void 0,excludeAddons:n.length>0?n:void 0,customFontsOnly:O(e,`customFontsOnly`,!1),screen:e.screen,window:e.window,fingerprint:C(e,`fingerprint`),webglConfig:C(e,`webglConfig`),firefoxUserPrefs:C(e,`firefoxUserPrefs`),mainWorldEval:O(e,`mainWorldEval`,!0),enableCache:O(e,`enableCache`,!1)}}async function ht(e,t){try{let n=mt(t);if(S(t,`mode`,`launch`)===`connect`){let r=S(t,`wsEndpoint`);if(!r)return k.fail(`wsEndpoint is required for connect mode.`).build();let i=new g(n);return await i.connectToServer(r),e.setCamoufoxManager(i),e.setActiveDriver(`camoufox`),e.clearCamoufoxPage(),k.ok().build({driver:`camoufox`,mode:`connect`,wsEndpoint:r,message:`Connected to Camoufox server.`})}let r=new g(n);return await r.launch(),e.setCamoufoxManager(r),e.setActiveDriver(`camoufox`),e.clearCamoufoxPage(),k.ok().build({driver:`camoufox`,mode:`launch`,config:{os:n.os,headless:n.headless,geoip:n.geoip,humanize:n.humanize,locale:n.locale,blockWebgl:n.blockWebgl,blockImages:n.blockImages,blockWebrtc:n.blockWebrtc},message:`Camoufox (Firefox) browser launched`})}catch(e){return k.fail(e).build()}}async function gt(e,t){try{let n=S(t,`url`,``),r=j(t),i=E(t,`timeout`),a=await e.getCamoufoxPage();return await a.goto(n,{waitUntil:r,timeout:i}),e.setConsoleMonitorPage(a),k.ok().build({driver:`camoufox`,url:a.url(),title:await a.title()})}catch(e){return k.fail(e).build()}}const _t=new Set([`page_navigate`,`page_click`,`page_type`,`page_hover`,`page_scroll`,`page_press_key`,`page_select`,`page_upload_files`,`page_wait_for_selector`]);var vt=class{collector;pageController;scriptManager;consoleMonitor;captchaDetector;detailedDataManager;camoufoxManager=null;activeDriver=`chrome`;camoufoxPage=null;autoDetectCaptcha=!0;autoSwitchHeadless=!0;captchaTimeout=3e5;browserControl;targetControl;camoufoxBrowser;pageNavigation;pageInteraction;pageEvaluation;targetEvaluation;pageData;consoleHandlers;scriptManagement;captchaHandlers;stealthInjection;frameworkState;indexedDBDump;jsHeapSearch;tabWorkflow;detailedData;jsdomHandlers;tabRegistry;eventBus;codegenStopListening;codegenSteps=[];constructor(e,t,n,r,i){this.collector=e,this.pageController=t,this.scriptManager=n,this.consoleMonitor=r,this.eventBus=i;let a=y(v().paths.captchaScreenshotDir,`screenshots/captcha`);this.captchaDetector=new m(a),this.detailedDataManager=d.getInstance();let o=Xe({collector:this.collector,pageController:this.pageController,scriptManager:this.scriptManager,consoleMonitor:this.consoleMonitor,eventBus:i,captchaDetector:this.captchaDetector,detailedDataManager:this.detailedDataManager,getActiveDriver:()=>this.activeDriver,getCamoufoxPage:()=>this.getCamoufoxPage(),getCamoufoxManager:()=>this.camoufoxManager,setCamoufoxManager:e=>{this.camoufoxManager=e},closeCamoufox:()=>this.closeCamoufox(),getAutoDetectCaptcha:()=>this.autoDetectCaptcha,getAutoSwitchHeadless:()=>this.autoSwitchHeadless,getCaptchaTimeout:()=>this.captchaTimeout,setAutoDetectCaptcha:e=>{this.autoDetectCaptcha=e},setAutoSwitchHeadless:e=>{this.autoSwitchHeadless=e},setCaptchaTimeout:e=>{this.captchaTimeout=e}});this.browserControl=o.browserControl,this.targetControl=o.targetControl,this.camoufoxBrowser=o.camoufoxBrowser,this.pageNavigation=o.pageNavigation,this.pageInteraction=o.pageInteraction,this.pageEvaluation=o.pageEvaluation,this.targetEvaluation=o.targetEvaluation,this.pageData=o.pageData,this.consoleHandlers=o.consoleHandlers,this.scriptManagement=o.scriptManagement,this.captchaHandlers=o.captchaHandlers,this.stealthInjection=o.stealthInjection,this.frameworkState=o.frameworkState,this.indexedDBDump=o.indexedDBDump,this.jsHeapSearch=o.jsHeapSearch,this.tabWorkflow=o.tabWorkflow,this.detailedData=o.detailedData,this.jsdomHandlers=o.jsdomHandlers,this.tabRegistry=o.tabRegistry}makeJsonResponse(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}sanitizeCodegenArgs(e){let t={...e};for(let e of[`delay`,`timeout`])t[e]===void 0&&delete t[e];return t}isSameFrameArgs(e,t){return(e.frameUrl??null)===(t.frameUrl??null)&&(e.frameSelector??null)===(t.frameSelector??null)}compactCodegenSteps(e){let t=[];for(let n of e){let e={tool:n.tool,args:this.sanitizeCodegenArgs(n.args),timestamp:n.timestamp},r=t.at(-1);if(!r){t.push(e);continue}if(e.tool===`page_wait_for_selector`&&r.tool===`page_wait_for_selector`&&e.args.selector===r.args.selector&&this.isSameFrameArgs(e.args,r.args)){r.timestamp=e.timestamp;continue}if(!(e.tool===`page_wait_for_selector`&&(r.tool===`page_click`||r.tool===`page_type`)&&e.args.selector===r.args.selector&&this.isSameFrameArgs(e.args,r.args))){if(e.tool===r.tool&&JSON.stringify(e.args)===JSON.stringify(r.args)){r.timestamp=e.timestamp;continue}t.push(e)}}return t}formatCodegenScript(e){return[`const steps = [`,...e.map(e=>` ${JSON.stringify({tool:e.tool,args:e.args},null,0)},`),`];`,``,`for (const step of steps) {`,` await callTool(step.tool, step.args);`,`}`].join(`
|
|
11
|
-
`)}getTabRegistry(){return this.tabRegistry}async getCamoufoxPage(){if(!this.camoufoxManager)throw Error(`Camoufox browser not launched. Call browser_launch(driver="camoufox") first.`);return this.camoufoxPage||=await this.camoufoxManager.newPage(),this.camoufoxPage}async closeCamoufox(){try{await this.consoleMonitor.disable()}catch(t){e.warn(`Failed to reset console monitor before closing Camoufox: ${String(t)}`)}this.consoleMonitor.clearPlaywrightPage(),this.camoufoxManager&&(await this.camoufoxManager.close(),this.camoufoxManager=null,this.camoufoxPage=null)}async handleBrowserLaunch(e){return S(e,`driver`,`chrome`)===`camoufox`?this.handleCamoufoxLaunch(e):(this.activeDriver===`camoufox`&&this.camoufoxManager&&await this.closeCamoufox(),this.activeDriver=`chrome`,this.browserControl.handleBrowserLaunch(e))}async handleBrowserClose(e){return this.activeDriver===`camoufox`&&this.camoufoxManager?(await this.closeCamoufox(),await this.browserControl.handleBrowserClose(e),this.activeDriver=`chrome`,{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Camoufox browser closed`},null,2)}]}):this.browserControl.handleBrowserClose(e)}async handleBrowserStatus(e){if(this.activeDriver===`camoufox`){let e=!!this.camoufoxManager?.getBrowser();return{content:[{type:`text`,text:JSON.stringify({success:!0,driver:`camoufox`,running:e,hasActivePage:!!this.camoufoxPage},null,2)}]}}return this.browserControl.handleBrowserStatus(e)}async handleBrowserListTabs(e){return this.browserControl.handleBrowserListTabs(e)}async handleBrowserListCdpTargets(e){return this.targetControl.handleBrowserListCdpTargets(e)}async handleBrowserSelectTab(e){return this.browserControl.handleBrowserSelectTab(e)}async handleBrowserAttachCdpTarget(e){return this.targetControl.handleBrowserAttachCdpTarget(e)}async handleBrowserDetachCdpTarget(e){return this.targetControl.handleBrowserDetachCdpTarget(e)}async handleBrowserEvaluateCdpTarget(e){return this.targetEvaluation.handleBrowserEvaluateCdpTarget(e)}async handleBrowserAttach(e){return this.activeDriver===`camoufox`&&this.camoufoxManager&&await this.closeCamoufox(),this.activeDriver=`chrome`,this.browserControl.handleBrowserAttach(e)}async handleCamoufoxServerDispatch(e){switch(String(e.action??``)){case`close`:return this.camoufoxBrowser.handleCamoufoxServerClose(e);case`status`:return this.camoufoxBrowser.handleCamoufoxServerStatus(e);default:return this.camoufoxBrowser.handleCamoufoxServerLaunch(e)}}async handleCamoufoxServerLaunch(e){return this.camoufoxBrowser.handleCamoufoxServerLaunch(e)}async handleCamoufoxServerClose(e){return this.camoufoxBrowser.handleCamoufoxServerClose(e)}async handleCamoufoxServerStatus(e){return this.camoufoxBrowser.handleCamoufoxServerStatus(e)}async handlePageNavigate(e){return this.activeDriver===`camoufox`?this.handleCamoufoxNavigate(e):this.pageNavigation.handlePageNavigate(e)}async handlePageReload(e){return this.pageNavigation.handlePageReload(e)}async handlePageBack(e){return this.pageNavigation.handlePageBack(e)}async handlePageForward(e){return this.pageNavigation.handlePageForward(e)}async handlePageListFrames(e){return this.pageData.handlePageListFrames(e)}async handlePageClick(e){return this.pageInteraction.handlePageClick(e)}async handlePageType(e){return this.pageInteraction.handlePageType(e)}async handlePageUploadFiles(e){return this.pageInteraction.handlePageUploadFiles(e)}async handlePageSelect(e){return this.pageInteraction.handlePageSelect(e)}async handlePageHover(e){return this.pageInteraction.handlePageHover(e)}async handlePageScroll(e){return this.pageInteraction.handlePageScroll(e)}async handlePagePressKey(e){return this.pageInteraction.handlePagePressKey(e)}async handlePageEvaluate(e){return this.pageEvaluation.handlePageEvaluate(e)}async handlePageScreenshot(e){return this.pageEvaluation.handlePageScreenshot(e)}async handlePageInjectScript(e){return this.pageEvaluation.handlePageInjectScript(e)}async handlePageWaitForSelector(e){return this.pageEvaluation.handlePageWaitForSelector(e)}async handlePageCookiesDispatch(e){let t=String(e.action??``);switch(t){case`get`:return this.pageData.handlePageGetCookies(e);case`set`:return this.pageData.handlePageSetCookies(e);case`clear`:{let t=e.expectedCount;if(typeof t!=`number`||t<0)return f(new p(`VALIDATION`,`action=clear requires expectedCount (number). Call action=get first to obtain the current cookie count.`,{toolName:`page_cookies`}));let n=await this.pageData.getPageCookieCount();return n===t?this.pageData.handlePageClearCookies(e):f(new p(`VALIDATION`,`Cookie count mismatch: expected ${t} but found ${n}. Call action=get to refresh, then retry with the correct count.`,{toolName:`page_cookies`,details:{expected:t,actual:n}}))}default:return f(new p(`VALIDATION`,`Invalid action: "${t}". Expected one of: get, set, clear`,{toolName:`page_cookies`}))}}async handlePageSetViewport(e){return this.pageData.handlePageSetViewport(e)}async handlePageEmulateDevice(e){return this.pageData.handlePageEmulateDevice(e)}async handlePageLocalStorageDispatch(e){let t=String(e.action??``);switch(t){case`get`:return this.pageData.handlePageGetLocalStorage(e);case`set`:return this.pageData.handlePageSetLocalStorage(e);default:return f(new p(`VALIDATION`,`Invalid action: "${t}". Expected one of: get, set`,{toolName:`page_local_storage`}))}}async handleConsoleMonitor(e){return this.consoleHandlers.handleConsoleMonitor(e)}async handleConsoleGetLogs(e){return this.consoleHandlers.handleConsoleGetLogs(e)}async handleConsoleExecute(e){return this.consoleHandlers.handleConsoleExecute(e)}async handleGetAllScripts(e){return this.scriptManagement.handleGetAllScripts(e)}async handleGetScriptSource(e){return this.scriptManagement.handleGetScriptSource(e)}async handleCaptchaDetect(e){return this.captchaHandlers.handleCaptchaDetect(e)}async handleCaptchaWait(e){return this.captchaHandlers.handleCaptchaWait(e)}async handleCaptchaConfig(e){return this.captchaHandlers.handleCaptchaConfig(e)}async handleStealthInject(e){return this.stealthInjection.handleStealthInject(e)}async handleStealthSetUserAgent(e){return this.stealthInjection.handleStealthSetUserAgent(e)}async handleStealthConfigureJitter(e){return this.stealthInjection.handleStealthConfigureJitter(e)}async handleStealthGenerateFingerprint(e){return this.stealthInjection.handleStealthGenerateFingerprint(e)}async handleStealthVerify(e){return this.stealthInjection.handleStealthVerify(e)}async handleCamoufoxGeolocation(e){return this.stealthInjection.handleCamoufoxGeolocation(e)}async handleFrameworkStateExtract(e){return this.frameworkState.handleFrameworkStateExtract(e)}async handleIndexedDBDump(e){return this.indexedDBDump.handleIndexedDBDump(e)}async handleJSHeapSearch(e){return this.jsHeapSearch.handleJSHeapSearch(e)}async handleTabWorkflow(e){return this.tabWorkflow.handleTabWorkflow(e)}async handleBrowserCodegenStart(){return this.eventBus?(this.codegenStopListening?.(),this.codegenSteps=[],this.codegenStopListening=this.eventBus.on(`tool:called`,e=>{e.domain!==`browser`||!e.success||e.result?.success===!1||_t.has(e.toolName)&&this.codegenSteps.push({tool:e.toolName,args:{...e.args},timestamp:e.timestamp})}),this.makeJsonResponse({success:!0,recording:!0,message:`Browser action recording started.`})):this.makeJsonResponse({success:!1,message:`Event bus unavailable for browser codegen recording.`})}async handleBrowserCodegenStop(){this.codegenStopListening?.(),this.codegenStopListening=void 0;let e=[...this.codegenSteps],t=this.compactCodegenSteps(e);return this.codegenSteps=[],this.makeJsonResponse({success:!0,recording:!1,stepCount:t.length,rawStepCount:e.length,steps:t,script:this.formatCodegenScript(t)})}async handleGetDetailedData(e){return this.detailedData.handleGetDetailedData(e)}async handleCamoufoxLaunch(e){return ht({setCamoufoxManager:e=>{this.camoufoxManager=e},setActiveDriver:e=>{this.activeDriver=e},clearCamoufoxPage:()=>{this.camoufoxPage=null}},e)}async handleCamoufoxNavigate(e){return gt({getCamoufoxPage:()=>this.getCamoufoxPage(),setConsoleMonitorPage:e=>{this.consoleMonitor.setPlaywrightPage(e)}},e)}async handleHumanMouse(e){return tt(e,this.collector,this.pageController)}async handleHumanScroll(e){return nt(e,this.collector)}async handleHumanTyping(e){return rt(e,this.collector,this.pageController)}async handleCaptchaVisionSolve(e){return st(e,this.collector)}async handleWidgetChallengeSolve(e){return ct(e,this.collector)}async handleCaptchaSolverCapabilities(){return pt(this.collector)}async handleJsdomParse(e){return this.jsdomHandlers.handleJsdomParse(e)}async handleJsdomQuery(e){return this.jsdomHandlers.handleJsdomQuery(e)}async handleJsdomExecute(e){return this.jsdomHandlers.handleJsdomExecute(e)}async handleJsdomSerialize(e){return this.jsdomHandlers.handleJsdomSerialize(e)}async handleJsdomCookies(e){return this.jsdomHandlers.handleJsdomCookies(e)}};export{vt as BrowserToolHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ConsoleMonitor as e}from"./ConsoleMonitor-Dkqc0HNi.mjs";import"./PageController-D9jVkH0i.mjs";import{n as t}from"./DOMInspector-BYY_EJ0C.mjs";export{t as CodeCollector,e as ConsoleMonitor};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{cpus as e}from"node:os";const t=(e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=parseInt(n,10);return Number.isFinite(r)?r:t},n=(e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=Number.parseFloat(n);return Number.isFinite(r)?r:t},r=(e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=n.trim().toLowerCase();return r===`true`||r===`1`?!0:r===`false`||r===`0`?!1:t},i=(e,t)=>process.env[e]||t,ee=(e,t)=>{let n=process.env[e];return n?n.split(`,`).map(Number).filter(Number.isFinite):t},te=(e,t)=>{let n=process.env[e];if(!n)return t;let r=n.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);return r.length>0?r:t},a=(e,n,r)=>{let i=process.env[e];if(i!==void 0&&i.trim().toLowerCase()===`auto`){let e=r();return Number.isFinite(e)&&e>0?Math.floor(e):n}return t(e,n)},o=()=>{try{return e().length}catch{return 4}},s=t(`SHUTDOWN_TIMEOUT_MS`,2e4),c=t(`RUNTIME_ERROR_WINDOW_MS`,6e4),l=t(`RUNTIME_ERROR_THRESHOLD`,8),u=ee(`DEBUG_PORT_CANDIDATES`,[9222,9229,9333,2039]),d=t(`DEFAULT_DEBUG_PORT`,9222),f=i(`GHIDRA_BRIDGE_URL`,`http://127.0.0.1:18080`),p=i(`IDA_BRIDGE_URL`,`http://127.0.0.1:18081`),m=process.env.CAPTCHA_SOLVER_BASE_URL?.trim()||process.env.CAPTCHA_2CAPTCHA_BASE_URL?.trim()||``;process.env.EXTENSION_REGISTRY_BASE_URL?.trim();const h=t(`MCP_HTTP_REQUEST_TIMEOUT_MS`,3e4),g=t(`MCP_HTTP_HEADERS_TIMEOUT_MS`,1e4),_=t(`MCP_HTTP_KEEPALIVE_TIMEOUT_MS`,864e5),v=t(`MCP_HTTP_FORCE_CLOSE_TIMEOUT_MS`,5e3),y=t(`EXTERNAL_TOOL_TIMEOUT_MS`,3e4),b=t(`EXTERNAL_TOOL_PROBE_TIMEOUT_MS`,5e3),x=t(`EXTERNAL_TOOL_PROBE_CACHE_TTL_MS`,6e4),S=t(`EXTERNAL_TOOL_FORCE_KILL_GRACE_MS`,2e3),C=t(`SANDBOX_EXEC_TIMEOUT_MS`,5e3),w=t(`SANDBOX_MEMORY_LIMIT_MB`,128),T=t(`SANDBOX_STACK_SIZE_MB`,4),E=t(`SANDBOX_TERMINATE_GRACE_MS`,2e3);t(`SYMBOLIC_EXEC_MAX_PATHS`,100),t(`SYMBOLIC_EXEC_MAX_DEPTH`,50),t(`SYMBOLIC_EXEC_TIMEOUT_MS`,3e4);const D=t(`JSVMP_DEOBFUSCATE_TIMEOUT_MS`,3e4),O=t(`JSVMP_MAX_ITERATIONS`,100);t(`JSVMP_SYMBOLIC_MAX_STEPS`,1e3),t(`JSVMP_SYMBOLIC_TIMEOUT_MS`,3e4);const k=t(`DEBUGGER_WAIT_FOR_PAUSED_TIMEOUT_MS`,3e4),A=t(`WATCH_EVAL_TIMEOUT_MS`,5e3),j=t(`TRANSFORM_WORKER_TIMEOUT_MS`,15e3);t(`TRANSFORM_VM_SCRIPT_TIMEOUT_MS`,5e3);const M=t(`TRANSFORM_CRYPTO_POOL_MAX_WORKERS`,4),N=t(`TRANSFORM_CRYPTO_POOL_IDLE_TIMEOUT_MS`,3e4),P=t(`TRANSFORM_CRYPTO_POOL_MAX_OLD_GEN_MB`,64),F=t(`TRANSFORM_CRYPTO_POOL_MAX_YOUNG_GEN_MB`,16);t(`EMULATOR_FETCH_GOTO_TIMEOUT_MS`,3e4);const I=t(`WASM_TOOL_TIMEOUT_MS`,6e4);t(`WASM_OFFLINE_RUN_TIMEOUT_MS`,1e4);const L=t(`WASM_OPTIMIZE_TIMEOUT_MS`,12e4);t(`MINIAPP_UNPACK_TIMEOUT_MS`,18e4);const R=t(`CAPTCHA_SUBMIT_TIMEOUT_MS`,15e3);t(`FETCH_ABORT_TIMEOUT_MS`,1e4);const z=t(`CAPTCHA_POLL_INTERVAL_MS`,5e3),B=t(`CAPTCHA_RESULT_TIMEOUT_MS`,1e4),V=t(`CAPTCHA_DEFAULT_TIMEOUT_MS`,18e4),H=t(`CAPTCHA_MIN_TIMEOUT_MS`,5e3),U=t(`CAPTCHA_MAX_TIMEOUT_MS`,6e5),W=t(`CAPTCHA_MAX_RETRIES`,5),G=t(`CAPTCHA_DEFAULT_RETRIES`,2);t(`NETWORK_REPLAY_TIMEOUT_MS`,3e4),t(`NETWORK_REPLAY_MAX_BODY_BYTES`,512e3);const K=t(`NETWORK_REPLAY_MAX_REDIRECTS`,5),q=t(`NETWORK_HAR_BODY_CONCURRENCY`,4);t(`WORKFLOW_BATCH_MAX_ACCOUNTS`,50),t(`WORKFLOW_BATCH_MAX_CONCURRENCY`,1),t(`WORKFLOW_REGISTER_ACCOUNT_TIMEOUT_MS`,6e4),t(`WORKFLOW_ACTION_DELAY_MS`,1e3),t(`WORKFLOW_SETTLE_DELAY_MS`,2e3),t(`WORKFLOW_INPUT_DELAY_MS`,1500),t(`WORKFLOW_BATCH_MAX_RETRIES`,3),t(`WORKFLOW_BATCH_MAX_BACKOFF_MS`,3e4),t(`WORKFLOW_BATCH_MAX_TIMEOUT_MS`,3e5),t(`WORKFLOW_BATCH_RETRY_BACKOFF_MS`,2e3),t(`WORKFLOW_BATCH_TIMEOUT_PER_ACCOUNT_MS`,9e4);const J=t(`WORKFLOW_JS_BUNDLE_MAX_SIZE_BYTES`,20*1024*1024),Y=t(`WORKFLOW_JS_BUNDLE_MAX_REDIRECTS`,5),X=t(`WORKFLOW_JS_BUNDLE_FETCH_TIMEOUT_MS`,3e4),Z=t(`WORKFLOW_BUNDLE_CACHE_TTL_MS`,300*1e3),Q=t(`WORKFLOW_BUNDLE_CACHE_MAX_BYTES`,100*1024*1024);new Set(te(`SEARCH_WORKFLOW_BOOST_TIERS`,[`workflow`,`full`]));const ne=n(`SEARCH_WORKFLOW_DOMAIN_BOOST_MULTIPLIER`,2.4),re=t(`ACTIVATION_TTL_MINUTES`,30);r(`SEARCH_AUTO_ACTIVATE_DOMAINS`,!0);const ie=t(`AUTOPRUNE_AUTO_INACTIVITY_MS`,15*6e4),ae=t(`AUTOPRUNE_MANUAL_INACTIVITY_MS`,30*6e4),oe=t(`AUTOPRUNE_CHECK_INTERVAL_MS`,6e4),se=t(`PREDICTIVE_MAX_HISTORY`,100),ce=n(`PREDICTIVE_CONFIDENCE_THRESHOLD`,.25),le=n(`PREDICTIVE_DECAY_FACTOR`,.95),ue=t(`ACTIVATION_COOLDOWN_MS`,3e4),de=t(`ACTIVATION_COMPOUND_EVAL_EVERY`,5),fe=t(`ACTIVATION_EVENT_HISTORY_MAX`,200),pe=t(`ACTIVATION_BOOST_WINDOW_MS`,6e4),me=t(`COMPOUND_EVENT_WINDOW_MS`,12e4),he=t(`COMPOUND_LONG_WINDOW_MS`,3e5),ge=n(`SEARCH_AFFINITY_BOOST_FACTOR`,.38),_e=t(`SEARCH_AFFINITY_TOP_N`,9),ve=t(`SEARCH_DOMAIN_HUB_THRESHOLD`,5),ye=t(`SEARCH_QUERY_CACHE_CAPACITY`,500),be=n(`SEARCH_CACHE_VECTOR_WEIGHT_TOLERANCE`,.05),xe=n(`SEARCH_TRIGRAM_WEIGHT`,.02),Se=n(`SEARCH_TRIGRAM_THRESHOLD`,.47),Ce=t(`SEARCH_RRF_K`,18),we=n(`SEARCH_RRF_RESCALE_FACTOR`,2100),Te=n(`SEARCH_RRF_BM25_BLEND`,.39),Ee=t(`SEARCH_SYNONYM_EXPANSION_LIMIT`,2),De=n(`SEARCH_PARAM_TOKEN_WEIGHT`,1.1),Oe=n(`SEARCH_SCENE_KEYWORD_WEIGHT`,.8),ke=n(`SEARCH_BM25_K1`,1),Ae=n(`SEARCH_BM25_B`,.75),je=r(`SEARCH_VECTOR_ENABLED`,!0),Me=i(`SEARCH_VECTOR_MODEL_ID`,`Xenova/bge-micro-v2`),Ne=n(`SEARCH_VECTOR_COSINE_WEIGHT`,.53),Pe=r(`SEARCH_VECTOR_DYNAMIC_WEIGHT`,!0),Fe=n(`SEARCH_VECTOR_LEARN_UP`,.13),Ie=n(`SEARCH_VECTOR_LEARN_DOWN`,.02),Le=t(`SEARCH_VECTOR_LEARN_TOP_N`,3),Re=n(`SEARCH_VECTOR_BM25_SKIP_THRESHOLD`,8),ze=n(`SEARCH_TIER_PENALTY`,.35),Be=n(`SEARCH_TIER_PENALTY_SEARCH`,.4),Ve=n(`SEARCH_TIER_PENALTY_WORKFLOW`,.6),He=n(`SEARCH_TIER_PENALTY_FULL`,.6),Ue=t(`SEARCH_RECENCY_WINDOW_MS`,30*6e4),We=n(`SEARCH_RECENCY_MAX_BOOST`,.1),Ge=t(`SEARCH_RECENCY_TRACKER_MAX`,200),Ke=n(`SEARCH_EXACT_NAME_MATCH_MULTIPLIER`,3.2),qe=n(`SEARCH_DOMAIN_HUB_BOOST_MULTIPLIER`,1.04),Je=n(`SEARCH_AFFINITY_BASE_WEIGHT`,.5),Ye=n(`SEARCH_COVERAGE_PRECISION_FACTOR`,.94),Xe=n(`SEARCH_PREFIX_MATCH_MULTIPLIER`,.84),Ze=n(`RERANK_MAINTENANCE_PENALTY`,.43),Qe=n(`RERANK_STATELESS_INTERACTIVE_PENALTY`,.65),$e=n(`RERANK_STATELESS_CORE_PENALTY`,.15),et=n(`RERANK_STATELESS_COMPUTE_BOOST`,2.2),tt=n(`RERANK_STATELESS_SPECIFIC_TOOL_BOOST`,2.25),nt=n(`RERANK_BROWSER_LAUNCH_BOOST`,1.35),rt=n(`RERANK_BROWSER_ATTACH_BOOST`,1.55),it=n(`RERANK_NETWORK_MONITOR_BOOST`,1.6),at=n(`RERANK_NETWORK_GET_REQUESTS_BOOST`,1.55),ot=t(`PREDICTIVE_MAX_SECOND_ORDER_KEYS`,1e3),st=t(`EXTENSION_GIT_CLONE_TIMEOUT_MS`,6e4),ct=t(`EXTENSION_GIT_CHECKOUT_TIMEOUT_MS`,3e4),lt=t(`PROCESS_LIST_MAX_BUFFER_BYTES`,1024*1024*10),ut=t(`EXTERNAL_TOOL_MAX_STDOUT_BYTES`,10*1024*1024),dt=t(`EXTERNAL_TOOL_MAX_STDERR_BYTES`,1*1024*1024),ft=t(`GRAPHQL_MAX_PREVIEW_CHARS`,4e3),pt=t(`GRAPHQL_MAX_SCHEMA_CHARS`,12e4),mt=t(`GRAPHQL_MAX_QUERY_CHARS`,12e3),ht=t(`GRAPHQL_MAX_GRAPH_NODES`,2e3),gt=t(`GRAPHQL_MAX_GRAPH_EDGES`,5e3),$=t(`ANALYSIS_MAX_SUMMARY_FILES`,40),_t=t(`ANALYSIS_MAX_SAFE_COLLECTED_BYTES`,256*1024),vt=t(`ANALYSIS_MAX_SAFE_RESPONSE_BYTES`,220*1024),yt=t(`WS_PAYLOAD_PREVIEW_LIMIT`,200),bt=t(`WS_PAYLOAD_SAMPLE_LIMIT`,2e3),xt=t(`SCRIPTS_MAX_CAP`,500),St=t(`WORKER_POOL_MIN_WORKERS`,2),Ct=a(`WORKER_POOL_MAX_WORKERS`,4,()=>{let e=Math.floor(o()/2),n=t(`WORKER_POOL_MIN_WORKERS`,2);return Math.max(n,Math.min(8,e))}),wt=t(`WORKER_POOL_IDLE_TIMEOUT_MS`,3e4),Tt=t(`WORKER_POOL_JOB_TIMEOUT_MS`,15e3);t(`PARALLEL_DEFAULT_CONCURRENCY`,3),t(`PARALLEL_DEFAULT_TIMEOUT_MS`,6e4),t(`PARALLEL_DEFAULT_MAX_RETRIES`,2),t(`PARALLEL_RETRY_BACKOFF_BASE_MS`,1e3);const Et=t(`CACHE_GLOBAL_MAX_SIZE_BYTES`,500*1024*1024),Dt=n(`CACHE_LOW_HIT_RATE_THRESHOLD`,.3),Ot=t(`TOKEN_BUDGET_MAX_TOKENS`,2e5),kt=t(`DETAILED_DATA_DEFAULT_TTL_MS`,1800*1e3),At=t(`DETAILED_DATA_MAX_TTL_MS`,3600*1e3),jt=t(`DETAILED_DATA_SMART_THRESHOLD_BYTES`,50*1024);t(`ADV_DEOBF_LLM_MAX_TOKENS`,3e3),t(`VM_DEOBF_LLM_MAX_TOKENS`,4e3),t(`DEOBF_LLM_MAX_TOKENS`,2e3),t(`CRYPTO_DETECT_LLM_MAX_TOKENS`,2e3);const Mt=t(`MEMORY_READ_TIMEOUT_MS`,1e4),Nt=t(`MEMORY_MAX_READ_BYTES`,16*1024*1024),Pt=t(`MEMORY_WRITE_TIMEOUT_MS`,1e4),Ft=t(`MEMORY_MAX_WRITE_BYTES`,16*1024),It=t(`MEMORY_DUMP_TIMEOUT_MS`,6e4),Lt=t(`MEMORY_SCAN_TIMEOUT_MS`,12e4),Rt=t(`MEMORY_SCAN_MAX_BUFFER_BYTES`,1024*1024*50),zt=t(`MEMORY_SCAN_MAX_RESULTS`,1e4);t(`MEMORY_SCAN_MAX_REGIONS`,5e4),t(`MEMORY_SCAN_REGION_MAX_BYTES`,16777216);const Bt=t(`MEMORY_INJECT_TIMEOUT_MS`,3e4),Vt=r(`ENABLE_INJECTION_TOOLS`,!0);t(`MEMORY_MONITOR_INTERVAL_MS`,1e3);const Ht=t(`MEMORY_VMMAP_TIMEOUT_MS`,15e3),Ut=t(`MEMORY_PROTECTION_QUERY_TIMEOUT_MS`,15e3),Wt=t(`MEMORY_PROTECTION_PWSH_TIMEOUT_MS`,3e4),Gt=t(`NATIVE_ADMIN_CHECK_TIMEOUT_MS`,5e3);t(`NATIVE_SCAN_MAX_RESULTS`,1e4);const Kt=t(`PROCESS_LAUNCH_WAIT_MS`,2e3),qt=t(`WIN_DEBUG_PORT_POLL_ATTEMPTS`,20),Jt=t(`WIN_DEBUG_PORT_POLL_INTERVAL_MS`,500);t(`PACKER_SANDBOX_TIMEOUT_MS`,3e3);const Yt=t(`CODE_CAVE_MIN_SIZE`,16),Xt=t(`BREAKPOINT_HIT_TIMEOUT_MS`,1e4),Zt=t(`BREAKPOINT_TRACE_MAX_HITS`,100),Qt=t(`HEAP_ENUMERATE_MAX_BLOCKS`,1e4),$t=t(`HEAP_SPRAY_THRESHOLD`,50),en=t(`HEAP_SPRAY_SIZE_TOLERANCE`,64),tn=t(`HEAP_SUSPICIOUS_BLOCK_SIZE`,10485760),nn=t(`FREEZE_DEFAULT_INTERVAL_MS`,100),rn=t(`WRITE_HISTORY_MAX`,200),an=t(`SCAN_MAX_RESULTS_PER_SCAN`,1e5),on=t(`SCAN_DISPLAY_RESULTS_LIMIT`,200),sn=t(`SCAN_UNKNOWN_INITIAL_MAX_ADDRESSES`,5e5),cn=t(`SCAN_POINTER_MAX_RESULTS`,5e3),ln=t(`SCAN_GROUP_MAX_PATTERN_SIZE`,256),un=t(`SCAN_SESSION_MAX_COUNT`,20),dn=t(`SCAN_SESSION_TTL_MS`,18e5),fn=t(`POINTER_CHAIN_MAX_DEPTH`,6),pn=t(`POINTER_CHAIN_MAX_OFFSET`,4096),mn=t(`POINTER_CHAIN_MAX_RESULTS`,500),hn=t(`POINTER_CHAIN_SCAN_CHUNK_SIZE`,16777216),gn=t(`STRUCT_ANALYZE_DEFAULT_SIZE`,256),_n=t(`STRUCT_VTABLE_MAX_FUNCTIONS`,64),vn=t(`STRUCT_RTTI_MAX_STRING_LEN`,256);t(`STRUCT_CSTRING_MAX_LEN`,256);const yn=t(`FRIDA_TIMEOUT_MS`,15e3),bn=t(`GHIDRA_TIMEOUT_MS`,12e4),xn=t(`UNIDBG_TIMEOUT_MS`,6e4),Sn=t(`ADB_DEFAULT_TIMEOUT_MS`,3e4),Cn=t(`ADB_SHELL_TIMEOUT_MS`,6e4),wn=t(`ADB_WEBVIEW_HTTP_TIMEOUT_MS`,5e3),Tn=t(`ADB_WEBVIEW_WS_TIMEOUT_MS`,1e4),En=t(`MOJO_MONITOR_TIMEOUT_MS`,1e4),Dn=t(`MEMORY_AVAILABILITY_CACHE_TTL_MS`,45e3),On=t(`HTTP_RATE_LIMIT_MAX_IPS`,1e4),kn=t(`HTTP_CLEANUP_INTERVAL_MS`,5*6e4);t(`SSE_HEARTBEAT_MS`,3e4);const An=r(`MCP_COMPACT_SCHEMA`,!0),jn=t(`SANDBOX_MAX_TIMEOUT_MS`,3e4);t(`NATIVE_BRIDGE_TIMEOUT_MS`,15e3),t(`SOURCEMAP_EXT_TIMEOUT_MS`,15e3);const Mn=t(`V8_BYTECODE_SUBPROC_TIMEOUT_MS`,6e4),Nn=t(`SYSCALL_TRACE_DURATION_DEFAULT_SEC`,10),Pn=t(`SYSCALL_TRACE_DURATION_MIN_SEC`,1),Fn=t(`SYSCALL_TRACE_DURATION_MAX_SEC`,300),In=t(`SOURCEMAP_V4_RAW_FIELD_MAX_LEN`,200),Ln=t(`SOURCEMAP_V4_RETRY_DELAY_MS`,250),Rn=t(`WASM_DEAD_CODE_MIN_MATCHES`,10),zn=t(`WASM_BITWISE_OPS_THRESHOLD`,20),Bn=t(`WASM_VM_DISPATCH_MIN_LOOPS`,3),Vn=t(`PROTO_TLS_MIN_RECORD_LEN`,4),Hn=n(`PROTO_TLS_CONFIDENCE`,.95),Un=n(`PROTO_WS_CONFIDENCE`,.85),Wn=n(`PROTO_HTTP_CONFIDENCE`,.95),Gn=n(`PROTO_SSH_CONFIDENCE`,.95),Kn=t(`BOT_DETECT_LIMIT_DEFAULT`,50);t(`BOT_DETECT_LIMIT_MIN`,1),t(`BOT_DETECT_LIMIT_MAX`,500);const qn=t(`WEBHOOK_PROCESS_TIMEOUT_MS`,1e4);t(`ORCHESTRATOR_STEP_TIMEOUT_MS`,1e4);const Jn=t(`MACRO_DEFAULT_TIMEOUT_MS`,12e4),Yn=t(`MACRO_BUILTIN_TIMEOUT_MS`,6e4),Xn=t(`PAGE_FRAME_SELECTOR_TIMEOUT_MS`,1e4),Zn=t(`PAGE_NETWORK_IDLE_TIMEOUT_MS`,3e4),Qn=t(`DOM_QUERY_DEFAULT_LIMIT`,50),$n=t(`DOM_WAIT_ELEMENT_TIMEOUT_MS`,3e4);t(`BROWSER_POOL_IDLE_TIMEOUT_MS`,3e5),t(`BROWSER_POOL_MAX_TABS`,10);const er=t(`ICMP_PROBE_TIMEOUT_MS`,5e3),tr=t(`ICMP_TRACEROUTE_MAX_HOPS`,30),nr=t(`ICMP_DEFAULT_PACKET_SIZE`,32);t(`ADB_VERSION_CHECK_TIMEOUT_MS`,5e3);const rr=t(`COORDINATION_GOTO_TIMEOUT_MS`,3e4),ir=t(`MEMORY_AUDIT_TRAIL_CAPACITY`,5e3),ar=t(`MEMORY_PROCESS_SIGNAL_TIMEOUT_MS`,2e3),or=t(`MEMORY_PROBE_CMD_TIMEOUT_MS`,5e3),sr=t(`MEMORY_VMMAP_ENUM_TIMEOUT_MS`,15e3),cr=t(`MEMORY_MODULES_TIMEOUT_MS`,3e4);export{f as $,Oe as $n,bt as $r,ce as $t,Yt as A,un as An,j as Ar,Ft as At,Qn as B,Ye as Bn,qt as Br,sr as Bt,W as C,w as Cn,Fn as Cr,_ as Ct,B as D,ln as Dn,P as Dr,It as Dt,z as E,on as En,N as Er,Dn as Et,u as F,ge as Fn,L as Fr,Ut as Ft,S as G,Xe as Gn,St as Gr,q as Gt,Vt as H,ve as Hn,wt as Hr,Pt as Ht,d as I,_e as In,I as Ir,Mt as It,x as J,Ge as Jn,X as Jr,Zn as Jt,dt as K,ye as Kn,Q as Kr,K as Kt,kt as L,Ae as Ln,Bn as Lr,Rt as Lt,he as M,sn as Mn,Mn as Mr,or as Mt,rr as N,xt as Nn,zn as Nr,ar as Nt,m as O,an as On,M as Or,Bt as Ot,k as P,Je as Pn,Rn as Pr,Wt as Pt,yn as Q,we as Qn,yt as Qr,hn as Qt,At as R,ke as Rn,A as Rr,zt as Rt,V as S,jn as Sn,Nn as Sr,g as St,H as T,E as Tn,Ot as Tr,ir as Tt,ct as U,Ke as Un,Tt as Ur,En as Ut,$n as V,qe as Vn,Jt as Vr,Ht as Vt,st as W,De as Wn,Ct as Wr,Gt as Wt,y as X,Te as Xn,J as Xr,pn as Xt,b as Y,Ue as Yn,Y as Yr,fn as Yt,nn as Z,Ce as Zn,rn as Zr,mn as Zt,Xt as _,Qe as _n,In as _r,O as _t,re as a,Wn as an,Se as ar,pt as at,Dt as b,c as bn,vn as br,An as bt,wn as c,Vn as cn,Ne as cr,$t as ct,vt as d,nt as dn,Ie as dr,On as dt,le as en,Ee as er,bn as et,$ as f,Ze as fn,Le as fr,nr as ft,Kn as g,$e as gn,s as gr,D as gt,ae as h,et as hn,ne as hr,p as ht,fe as i,lt as in,Ve as ir,mt as it,me as j,dn as jn,xn as jr,cr as jt,R as k,cn as kn,F as kr,Nt as kt,Tn as l,Un as ln,Pe as lr,tn as lt,oe as m,it as mn,Me as mr,tr as mt,de as n,ot as nn,He as nr,ht as nt,Sn as o,Gn as on,xe as or,Qt as ot,ie as p,at as pn,Fe as pr,er as pt,ut as q,We as qn,Z as qr,Xn as qt,ue as r,Kt as rn,Be as rr,ft as rt,Cn as s,Hn as sn,Re as sr,en as st,pe as t,se as tn,ze as tr,gt as tt,_t as u,rt as un,je as ur,kn as ut,Zt as v,tt as vn,Ln as vr,Yn as vt,U as w,T as wn,Pn as wr,h as wt,G as x,C as xn,_n as xr,v as xt,Et as y,l as yn,gn as yr,Jn as yt,jt as z,be as zn,qn as zr,Lt as zt};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`get_token_budget_stats`,e=>e.desc(`Get token budget usage stats, warnings, and optimization suggestions.`).query()),e(`manual_token_cleanup`,e=>e.desc(`Clear stale entries and reset counters to free 10-30% of token budget.`)),e(`reset_token_budget`,e=>e.desc(`Hard-reset all token budget counters. Destructive — prefer manual_token_cleanup.`).destructive())],n=[e(`list_extensions`,e=>e.desc(`List all loaded plugins, workflows, and extension tools.`).query()),e(`reload_extensions`,e=>e.desc(`Reload plugins and workflows from configured directories.`).openWorld()),e(`browse_extension_registry`,e=>e.desc(`Browse the online extension registry for installable plugins and workflows.`).enum(`kind`,[`plugin`,`workflow`,`all`],`Filter by extension kind`,{default:`all`}).query()),e(`install_extension`,e=>e.desc(`Install an extension from the remote registry.`).string(`slug`,`Extension slug from the registry`).string(`targetDir`,`Target directory override`).requiredOpenWorld(`slug`))],r=[e(`get_cache_stats`,e=>e.desc(`Get cache statistics: entries, sizes, hit rates, and cleanup recommendations.`).query()),e(`smart_cache_cleanup`,e=>e.desc(`Evict LRU and stale entries while preserving hot data.`).number(`targetSize`,`Target size in bytes`)),e(`clear_all_caches`,e=>e.desc(`Clear all internal caches. Destructive — prefer smart_cache_cleanup.`).destructive())],i=[e(`cleanup_artifacts`,e=>e.desc(`Clean generated artifacts by age and size.`).number(`retentionDays`,`Override retention window in days`).number(`maxTotalBytes`,`Override maximum retained bytes`).boolean(`dryRun`,`Preview removals without deleting`).destructive()),e(`doctor_environment`,e=>e.desc(`Run environment doctor: dependencies, bridges, platform limits.`).boolean(`includeBridgeHealth`,`Probe native-bridge / Burp endpoints`).readOnly())];export{t as i,r as n,n as r,i as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`process_windows`,e=>e.desc(`Get all window handles for a process.`).number(`pid`,`Process ID to get windows for`).required(`pid`)),e(`process_check_debug_port`,e=>e.desc(`Check if a process has a debug port enabled for CDP attachment.`).number(`pid`,`Process ID to check`).required(`pid`)),e(`process_launch_debug`,e=>e.desc(`Launch an executable with remote debugging port enabled.`).string(`executablePath`,`Full path to the executable to launch`).number(`debugPort`,`Debug port to use`,{default:9222,minimum:1,maximum:65535}).array(`args`,{type:`string`},`Additional command line arguments`).required(`executablePath`)),e(`memory_read`,e=>e.desc(`Read memory from a process at a specific address. Requires elevated privileges.`).number(`pid`,`Target process ID`).string(`address`,`Memory address to read (hex string like "0x12345678")`).number(`size`,`Number of bytes to read`).required(`pid`,`address`,`size`)),e(`memory_write`,e=>e.desc(`Write data to process memory at a given address.`).number(`pid`,`Target process ID`).string(`address`,`Memory address to write to (hex string like "0x12345678")`).string(`data`,`Data to write (hex string or base64)`).enum(`encoding`,[`hex`,`base64`],`Encoding of the data parameter`,{default:`hex`}).required(`pid`,`address`,`data`)),e(`memory_scan`,e=>e.desc(`Scan process memory for a pattern or value. Requires elevated privileges.`).number(`pid`,`Target process ID`).string(`pattern`,`Pattern to search for (hex bytes like "48 8B 05" or value)`).enum(`patternType`,[`hex`,`int32`,`int64`,`float`,`double`,`string`],`Type of pattern to search`,{default:`hex`}).boolean(`suspendTarget`,`Suspend the target process during scan for a consistent memory snapshot (default: false)`,{default:!1}).required(`pid`,`pattern`)),e(`memory_check_protection`,e=>e.desc(`Check memory protection flags at a specific address.`).number(`pid`,`Target process ID`).string(`address`,`Memory address to check (hex string like "0x12345678")`).required(`pid`,`address`)),e(`memory_scan_filtered`,e=>e.desc(`Refine a previous memory scan with filtered addresses.`).number(`pid`,`Target process ID`).string(`pattern`,`Pattern to search for`).array(`addresses`,{type:`string`},`List of addresses to scan within (from previous scan)`).enum(`patternType`,[`hex`,`int32`,`int64`,`float`,`double`,`string`],`Type of pattern to search`,{default:`hex`}).required(`pid`,`pattern`,`addresses`)),e(`memory_batch_write`,e=>e.desc(`Write multiple memory patches at once.`).number(`pid`,`Target process ID`).array(`patches`,{type:`object`,properties:{address:{type:`string`,description:`Memory address (hex)`},data:{type:`string`,description:`Data to write`},encoding:{type:`string`,enum:[`hex`,`base64`],default:`hex`}},required:[`address`,`data`]},`Array of patches to apply`).required(`pid`,`patches`)),e(`memory_dump_region`,e=>e.desc(`Dump a process memory region to a binary file for offline analysis.`).number(`pid`,`Target process ID`).string(`address`,`Start address (hex)`).number(`size`,`Number of bytes to dump`).string(`outputPath`,`Output file path`).required(`pid`,`address`,`size`,`outputPath`)),e(`memory_list_regions`,e=>e.desc(`List all memory regions in a process with protection flags.`).number(`pid`,`Target process ID`).required(`pid`)),e(`memory_audit_export`,e=>e.desc(`Export the in-memory audit trail for memory operations as JSON.`)),e(`inject_dll`,e=>e.desc(`Inject a DLL into a target process.`).number(`pid`,`Target process ID`).string(`dllPath`,`Full path to the DLL file to inject`).required(`pid`,`dllPath`)),e(`inject_shellcode`,e=>e.desc(`Allocate and execute raw shellcode in a target process.`).number(`pid`,`Target process ID`).string(`shellcode`,`Shellcode bytes (hex string or base64)`).enum(`encoding`,[`hex`,`base64`],`Encoding of shellcode`,{default:`hex`}).required(`pid`,`shellcode`)),e(`check_debug_port`,e=>e.desc(`Check if a process is being debugged using NtQueryInformationProcess (ProcessDebugPort).`).number(`pid`,`Target process ID`).required(`pid`)),e(`enumerate_modules`,e=>e.desc(`List all loaded modules (DLLs) in a process with their base addresses.`).number(`pid`,`Target process ID`).required(`pid`)),e(`electron_attach`,e=>e.desc(`Attach to an Electron CDP port and optionally evaluate in a matching page.`).number(`port`,`CDP port to connect to`,{minimum:1,maximum:65535}).string(`pageUrl`,`Optional URL substring used to pick the target page`).string(`evaluate`,`Optional JavaScript expression to evaluate in the selected page`).string(`wsEndpoint`,`Optional browser WebSocket endpoint override`))];export{t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{jr as e}from"./constants-Cp6hBrrx.mjs";import{a as t,c as n,i as r,n as i,o as a,r as o,s}from"./binary-instrument-Cf9qqLlM.mjs";import{n as c,t as l}from"./capabilities-DbYCv-HF.mjs";import{access as u}from"node:fs/promises";import{execFile as d}from"node:child_process";const f={plugin_frida_bridge:`Install @jshookmcpextension/plugin-frida-bridge and reload extensions.`,plugin_ghidra_bridge:`Install @jshookmcpextension/plugin-ghidra-bridge and reload extensions.`,plugin_ida_bridge:`Install @jshookmcpextension/plugin-ida-bridge and reload extensions.`,plugin_jadx_bridge:`Install @jshookmcpextension/plugin-jadx-bridge and reload extensions.`};function p(e){return{content:[{type:`text`,text:e}]}}function m(e){return p(JSON.stringify(e))}function h(e,t){let n=e[t];if(typeof n!=`string`||n.trim().length===0)throw Error(`${t} is required`);return n.trim()}function g(e,t){let n=e[t];return typeof n==`string`&&n.trim().length>0?n.trim():void 0}function _(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function v(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e.length>0):[]}function y(e){return typeof e==`object`&&!!e}function b(e){return y(e)&&e.extensionPluginsById instanceof Map&&e.extensionPluginRuntimeById instanceof Map}function x(e,t){if(!e)return;let n=e.extensionPluginsById;if(n instanceof Map)return n.has(t)}function S(e){return f[e]}function C(e,t){let n=x(e,t);return n===!0?{status:`available`,fix:S(t)}:n===!1?{status:`unavailable`,reason:`Plugin ${t.replaceAll(`_`,`-`)} is not installed`,fix:S(t)}:{status:`unknown`,reason:`Extension plugin registry is not available in the current server context`,fix:`Run inside the full MCP server with extension support enabled.`}}async function w(e,n,r,i){let a=C(e,n);if(!e||a.status!==`available`)return m({...l(r,n,a.reason??`Plugin ${n.replaceAll(`_`,`-`)} is not available`,a.fix),status:a.status});let o=await t(e,{pluginId:n,toolName:r,args:i});return o.success?m(o):m({...l(r,n,o.error??`Plugin invocation failed`,a.fix)})}function T(e,t){let n=e[t];if(!y(n))return;let r={},i=n.includeArgs,a=n.includeRetAddr;return typeof i==`boolean`&&(r.includeArgs=i),typeof a==`boolean`&&(r.includeRetAddr=a),r}function E(e){if(!/^\d+$/.test(e))return null;let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function D(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,24)}async function O(){let e=process.env.UNIDBG_JAR??``;if(e.length===0)return{available:!1,reason:`UNIDBG_JAR is not configured`,command:`java`,jarPath:``};try{await u(e)}catch{return{available:!1,reason:`UNIDBG_JAR not found: ${e}`,command:`java`,jarPath:e}}return{available:!0,reason:``,command:`java`,jarPath:e}}function k(e,t,n){return new Promise((r,i)=>{d(e,t,{timeout:n,windowsHide:!0,maxBuffer:8388608,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}function A(e){return y(e)&&Array.isArray(e.functions)&&Array.isArray(e.imports)}function j(e){let t=[];for(let n of e){if(!y(n))continue;let e=M(n,`functionName`),r=M(n,`hookCode`),i=M(n,`description`),a=N(n.parameters);!e||!r||!i||t.push({functionName:e,hookCode:r,description:i,parameters:a})}return t}function M(e,t){let n=e[t];return typeof n==`string`?n:void 0}function N(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!y(n))continue;let e=M(n,`name`),r=M(n,`type`),i=M(n,`description`);e&&r&&i&&t.push({name:e,type:r,description:i})}return t}var P=class{state;constructor(e){this.state=e}async handleFridaAttach(e){let t=g(e,`pid`);if(!g(e,`target`)&&t)return w(this.state.context,`plugin_frida_bridge`,`frida_attach`,e);let n=h(e,`target`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available){let e=`mock-frida-${D(n)}`;return m({success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,target:n,sessionId:e,reason:i.reason??`Frida CLI is not available`,sessions:[{id:e,target:n,pid:E(n),status:`unavailable`}]})}let a;try{a=await r.attach(n)}catch(e){return m({success:!1,available:!0,capability:`frida_attach`,fix:`Run the server elevated or choose a target process that allows Frida injection.`,target:n,reason:e instanceof Error?e.message:String(e),sessions:r.listSessions()})}return this.state.context?.eventBus.emit(`frida:attached`,{target:n,sessionId:a,timestamp:new Date().toISOString()}),m({success:!0,available:!0,target:n,sessionId:a,sessions:r.listSessions()})}async handleFridaEnumerateModules(e){let t=h(e,`sessionId`),n=this.getFridaSession(),r=await n.getAvailability();if(!r.available)return m({available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,reason:r.reason??`Frida CLI is not available`,modules:[{name:`mock-module`,base:`0x0`,size:0,path:`<unavailable>`}]});if(!n.useSession(t))return m({available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,modules:[]});let i=await n.enumerateModules(),a=n.getSessionDiagnostics(t);return a?.status===`error`&&a.lastError?m({success:!1,available:!0,sessionId:t,reason:a.lastError,modules:i}):m({success:!0,available:!0,sessionId:t,modules:i})}async handleFridaRunScript(e){let t=g(e,`sessionId`);if(!t)return p(`Missing required string argument: sessionId`);let n=h(e,`script`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,reason:i.reason??`Frida CLI is not available`,execution:{output:``,error:`Frida unavailable`}};if(!r.useSession(t))return{available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,execution:{output:``,error:`Unknown session`}};let a=await r.executeScript(n);return a.error?m({success:!1,available:!0,sessionId:t,reason:a.error,execution:a}):m({success:!0,available:!0,sessionId:t,execution:a})}async handleFridaDetach(e){let t=g(e,`sessionId`);if(!t)return p(`Missing required string argument: sessionId`);let n=this.getFridaSession();return(await n.getAvailability()).available&&n.hasSession(t)?(n.useSession(t),await n.detach(),m({success:!0,sessionId:t,detached:!0})):w(this.state.context,`plugin_frida_bridge`,`frida_detach`,e)}async handleFridaListSessions(e){let t=this.getFridaSession(),n=await t.getAvailability(),r=t.listSessions();if(n.available)return m({success:!0,available:!0,sessions:r,count:r.length});let i=C(this.state.context,`plugin_frida_bridge`);return r.length>0||i.status===`unavailable`?m({success:!0,available:!1,capability:`frida_cli`,reason:n.reason??`Frida CLI is not available`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessions:r,count:r.length}):w(this.state.context,`plugin_frida_bridge`,`frida_list_sessions`,e)}async handleFridaGenerateScript(e){let t=g(e,`target`)??`unknown`,n=g(e,`template`)??`trace`,r=g(e,`functionName`)??`target_function`,i=[{functionName:r,hookCode:`console.log('[${n}] ${r} called');`,description:`${n} hook for ${r}`,parameters:[]}];return m({success:!0,target:t,template:n,functionName:r,script:this.state.hookCodeGenerator.exportScript(i,`frida`)})}async handleFridaEnumerateFunctions(e){let t=h(e,`sessionId`),n=h(e,`moduleName`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,moduleName:n,reason:i.reason??`Frida CLI is not available`,functions:[]};if(!r.useSession(t))return{available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,functions:[]};let a=await r.enumerateFunctions(n),o=r.getSessionDiagnostics(t);return o?.status===`error`&&o.lastError?m({success:!1,available:!0,sessionId:t,moduleName:n,reason:o.lastError,functions:a,count:a.length}):m({success:!0,available:!0,sessionId:t,moduleName:n,functions:a,count:a.length})}async handleFridaFindSymbols(e){let t=h(e,`sessionId`),n=h(e,`pattern`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,pattern:n,reason:i.reason??`Frida CLI is not available`,symbols:[]};if(!r.useSession(t))return{available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,symbols:[]};let a=await r.findSymbols(n),o=r.getSessionDiagnostics(t);return o?.status===`error`&&o.lastError?m({success:!1,available:!0,sessionId:t,pattern:n,reason:o.lastError,symbols:a,count:a.length}):m({success:!0,available:!0,sessionId:t,pattern:n,symbols:a,count:a.length})}getFridaSession(){return this.state.fridaSession||(this.state.fridaSession=new n),this.state.fridaSession}},F=class{state;constructor(e){this.state=e}async handleGhidraAnalyze(e){let t=g(e,`targetPath`);if(!g(e,`binaryPath`)&&t)return w(this.state.context,`plugin_ghidra_bridge`,`ghidra_analyze`,e);let n=h(e,`binaryPath`),r=_(e,`timeout`),i=this.getGhidraAnalyzer(),a=await i.getAvailability(),o=await i.analyze(n,r===void 0?void 0:{timeout:r});return a.available?{available:!0,binaryPath:n,analysis:o}:{available:!1,capability:`ghidra_headless`,fix:`Install Ghidra and ensure analyzeHeadless is on PATH.`,binaryPath:n,reason:a.reason??`Ghidra analyzeHeadless is not available`,analysis:o}}async handleGhidraDecompile(e){return w(this.state.context,`plugin_ghidra_bridge`,`ghidra_decompile`,e)}async handleIdaDecompile(e){return w(this.state.context,`plugin_ida_bridge`,`ida_decompile`,e)}async handleJadxDecompile(e){return w(this.state.context,`plugin_jadx_bridge`,`jadx_decompile`,e)}async handleGenerateHooks(e){let t=g(e,`ghidraOutput`);if(t)return this.handleLegacyGenerateHooks(t);let n=e.ghidraOutput;if(y(n))return this.handleLegacyGenerateHooks(JSON.stringify(n));let r=v(e,`symbols`);if(r.length===0)return p(`symbols or ghidraOutput is required`);let i=T(e,`options`),a=this.getHookGenerator().generateFridaHookScript(r,i);return m({available:!0,symbolCount:r.length,script:a})}async handleExportHookScript(e){let t=g(e,`hookTemplates`);if(!t){let e=this.state.hookCodeGenerator.exportScript([],`frida`);return m({format:`frida`,hookCount:0,script:e.includes(`Java.perform`)?e:`Java.perform(function() {\n${e}\n});`})}try{let e=JSON.parse(t);if(!Array.isArray(e))return p(`Invalid JSON`);let n=j(e),r=this.state.hookCodeGenerator.exportScript(n,`frida`);return m({format:`frida`,hookCount:n.length,script:r})}catch{return p(`Invalid JSON`)}}async handleUnidbgEmulate(t){let n=h(t,`binaryPath`),r=h(t,`functionName`),i=v(t,`args`),a=await O();if(!a.available)return{available:!1,capability:`unidbg_jar`,fix:`Set UNIDBG_JAR to a reachable Unidbg JAR path.`,binaryPath:n,functionName:r,args:i,reason:a.reason,result:{returnValue:`0x0`,stdout:``,stderr:``,trace:[`mock-unidbg-unavailable`]}};let o=await k(a.command,[`-jar`,a.jarPath,n,r,...i],e);return{available:!0,binaryPath:n,functionName:r,args:i,result:{returnValue:`0x0`,stdout:o.stdout.trim(),stderr:o.stderr.trim(),trace:[]}}}async handleUnidbgLaunch(e){let t=g(e,`soPath`);if(!t)return p(`Missing required string argument: soPath`);let n=g(e,`arch`)??`arm`;try{let e=await this.state.unidbgRunner.launch(t,n);return{available:!0,sessionId:e.sessionId,soPath:e.soPath,arch:e.arch,sessions:this.state.unidbgRunner.listSessions()}}catch(e){return{available:!1,capability:`unidbg_jar`,fix:`Set UNIDBG_JAR to a reachable Unidbg JAR path and retry.`,soPath:t,arch:n,reason:e instanceof Error?e.message:String(e),sessions:this.state.unidbgRunner.listSessions()}}}async handleUnidbgCall(e){let t=g(e,`sessionId`);if(!t)return p(`Missing required string argument: sessionId`);let n=g(e,`functionName`);if(!n)return p(`Missing required string argument: functionName`);let r=y(e.args)?e.args:{};try{return m(await this.state.unidbgRunner.callFunction(t,n,r))}catch(e){let t=e instanceof Error?e.message:String(e);return p(t.startsWith(`No unidbg session found`)?`${t} (not found)`:t)}}async handleUnidbgTrace(e){let t=g(e,`sessionId`);if(!t)return p(`Missing required string argument: sessionId`);try{return m(await this.state.unidbgRunner.trace(t))}catch(e){let t=e instanceof Error?e.message:String(e);return p(t.startsWith(`No unidbg session found`)?`${t} (not found)`:t)}}async handleGetAvailablePlugins(e){let t=this.state.context?r(this.state.context):[];return m({plugins:t,count:t.length})}getGhidraAnalyzer(){return this.state.ghidra||(this.state.ghidra=new s),this.state.ghidra}getHookGenerator(){return this.state.hookGen||(this.state.hookGen=new o),this.state.hookGen}handleLegacyGenerateHooks(e){let t;try{t=JSON.parse(e)}catch{return p(`Invalid JSON`)}if(!A(t))return p(`ghidraOutput is required`);let n=this.state.hookCodeGenerator.generateHooks(t);return m({count:n.length,hooks:n})}},I=class{state;constructor(e){this.state=e}async handleBinaryInstrumentCapabilities(){let e=await this.getFridaSession().getAvailability(),t=await this.getGhidraAnalyzer().getAvailability(),n=await O();return m(c(`binary_instrument_capabilities`,[{capability:`frida_cli`,status:e.available?`available`:`unavailable`,reason:e.reason,fix:e.available?void 0:`Install frida-tools and ensure the frida CLI is on PATH.`,details:{tools:[`frida_attach`,`frida_enumerate_modules`,`frida_run_script`,`frida_enumerate_functions`,`frida_find_symbols`],...e.path?{path:e.path}:{},...e.version?{version:e.version}:{}}},{capability:`plugin_frida_bridge`,...C(this.state.context,`plugin_frida_bridge`),details:{tools:[`frida_attach`,`frida_detach`,`frida_list_sessions`]}},{capability:`ghidra_headless`,status:t.available?`available`:`unavailable`,reason:t.reason,fix:t.available?void 0:`Install Ghidra and ensure analyzeHeadless is on PATH.`,details:{tools:[`ghidra_analyze`],...t.path?{path:t.path}:{},...t.version?{version:t.version}:{}}},{capability:`plugin_ghidra_bridge`,...C(this.state.context,`plugin_ghidra_bridge`),details:{tools:[`ghidra_decompile`]}},{capability:`plugin_ida_bridge`,...C(this.state.context,`plugin_ida_bridge`),details:{tools:[`ida_decompile`]}},{capability:`plugin_jadx_bridge`,...C(this.state.context,`plugin_jadx_bridge`),details:{tools:[`jadx_decompile`]}},{capability:`unidbg_jar`,status:n.available?`available`:`unavailable`,reason:n.reason||void 0,fix:n.available?void 0:`Set UNIDBG_JAR to a reachable Unidbg JAR path.`,details:{tools:[`unidbg_emulate`,`unidbg_launch`,`unidbg_call`,`unidbg_trace`],command:n.command,jarPath:n.jarPath}}]))}getFridaSession(){return this.state.fridaSession||(this.state.fridaSession=new n),this.state.fridaSession}getGhidraAnalyzer(){return this.state.ghidra||(this.state.ghidra=new s),this.state.ghidra}},L=class{state;frida;analysis;capabilities;constructor(e,t,r){this.state={hookCodeGenerator:new a,unidbgRunner:new i},e instanceof n?this.state.fridaSession=e:b(e)&&(this.state.context=e),t&&(this.state.ghidra=t),r&&(this.state.hookGen=r),this.frida=new P(this.state),this.analysis=new F(this.state),this.capabilities=new I(this.state)}handleBinaryInstrumentCapabilities(){return this.capabilities.handleBinaryInstrumentCapabilities()}handleFridaAttach(e){return this.frida.handleFridaAttach(e)}handleFridaEnumerateModules(e){return this.frida.handleFridaEnumerateModules(e)}handleFridaRunScript(e){return this.frida.handleFridaRunScript(e)}handleFridaDetach(e){return this.frida.handleFridaDetach(e)}handleFridaListSessions(e){return this.frida.handleFridaListSessions(e)}handleFridaGenerateScript(e){return this.frida.handleFridaGenerateScript(e)}handleFridaEnumerateFunctions(e){return this.frida.handleFridaEnumerateFunctions(e)}handleFridaFindSymbols(e){return this.frida.handleFridaFindSymbols(e)}handleGhidraAnalyze(e){return this.analysis.handleGhidraAnalyze(e)}handleGhidraDecompile(e){return this.analysis.handleGhidraDecompile(e)}handleIdaDecompile(e){return this.analysis.handleIdaDecompile(e)}handleJadxDecompile(e){return this.analysis.handleJadxDecompile(e)}handleGenerateHooks(e){return this.analysis.handleGenerateHooks(e)}handleExportHookScript(e){return this.analysis.handleExportHookScript(e)}handleUnidbgEmulate(e){return this.analysis.handleUnidbgEmulate(e)}handleUnidbgLaunch(e){return this.analysis.handleUnidbgLaunch(e)}handleUnidbgCall(e){return this.analysis.handleUnidbgCall(e)}handleUnidbgTrace(e){return this.analysis.handleUnidbgTrace(e)}handleGetAvailablePlugins(e){return this.analysis.handleGetAvailablePlugins(e)}};export{L as BinaryInstrumentHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as e}from"./parse-args-Cuk7-xUt.mjs";function t(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}var n=class{sessionManager;deps;constructor(e,t={}){this.sessionManager=e,this.deps=t}async handleSessionDispatch(n){let r=e(n,`action`);switch(r){case`create`:return this.handleSessionCreate(n);case`list`:return this.handleSessionList(n);case`destroy`:return this.handleSessionDestroy(n);case`status`:return this.handleSessionStatus(n);default:return t({success:!1,error:`Unknown action: ${r}. Valid: create, list, destroy, status`})}}async handleOperationDispatch(n){let r=e(n,`action`);switch(r){case`register`:return this.handleOperationRegister(n);case`list`:return this.handleOperationList(n);default:return t({success:!1,error:`Unknown action: ${r}. Valid: register, list`})}}async handleArtifactDispatch(n){let r=e(n,`action`);switch(r){case`record`:return this.handleArtifactRecord(n);case`query`:return this.handleArtifactQuery(n);default:return t({success:!1,error:`Unknown action: ${r}. Valid: record, query`})}}async handleSessionCreate(n){try{let r=e(n,`name`);return t({success:!0,session:this.sessionManager.createSession(r||void 0)})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleSessionList(e){try{let e=this.sessionManager.listSessions();return t({success:!0,totalSessions:e.length,sessions:e})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleSessionDestroy(n){try{let r=e(n,`sessionId`,``);return r?(this.sessionManager.destroySession(r),t({success:!0,sessionId:r,message:`Session destroyed`})):t({success:!1,error:`sessionId is required`})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleSessionStatus(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});let i=this.sessionManager.getSession(r);return t(i?{success:!0,session:i,stats:this.sessionManager.getSessionStats(r)}:{success:!1,error:`Session "${r}" not found`})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleOperationList(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});let i=this.sessionManager.getSessionOperations(r),a=e(n,`type`);return a&&(i=i.filter(e=>e.type===a)),t({success:!0,totalOperations:i.length,operations:i})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleOperationRegister(n){try{let r=e(n,`sessionId`,``),i=e(n,`type`,``),a=e(n,`target`,``),o=n.config&&typeof n.config==`object`&&!Array.isArray(n.config)?n.config:{};return t(r?i?a?{success:!0,operation:this.sessionManager.registerOperation(r,i,a,o)}:{success:!1,error:`target is required`}:{success:!1,error:`type is required`}:{success:!1,error:`sessionId is required`})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleArtifactQuery(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});let i=e(n,`type`)||void 0,a=typeof n.limit==`number`?n.limit:50,o=this.sessionManager.getArtifacts(r,i);return a>0&&(o=o.slice(0,a)),t({success:!0,totalArtifacts:o.length,artifacts:o})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleArtifactRecord(n){try{let r=e(n,`operationId`,``),i=n.data&&typeof n.data==`object`&&!Array.isArray(n.data)?n.data:void 0;return t(r?i?{success:!0,artifact:this.sessionManager.recordArtifact(r,i)}:{success:!1,error:`data is required`}:{success:!1,error:`operationId is required`})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleHookPreset(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});if(!this.deps.hookPresetHandlers)return t({success:!1,error:`hookPresetHandlers is not available`});let i={...n};delete i.sessionId;let a=await this.sessionManager.applyHookPreset(r,this.deps.hookPresetHandlers,i);return t({success:a.payload.success!==!1&&a.operation.status===`completed`,operation:a.operation,artifacts:a.artifacts,result:a.payload})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleNetworkReplay(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});if(!this.deps.advancedHandlers)return t({success:!1,error:`advancedHandlers is not available`});let i={...n};delete i.sessionId;let a=await this.sessionManager.replayNetworkRequest(r,this.deps.advancedHandlers,i);return t({success:a.payload.success!==!1&&a.operation.status===`completed`,operation:a.operation,artifacts:a.artifacts,result:a.payload})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}};export{n as InstrumentationHandlers};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{c as e,l as t,o as n,s as r}from"./constants-Cp6hBrrx.mjs";import{n as i}from"./response-C7rKQst4.mjs";import{t as a}from"./ToolError-DWU_z7gp.mjs";import{r as o,s}from"./parse-args-Cuk7-xUt.mjs";import{access as c}from"node:fs/promises";import{execFile as l}from"node:child_process";import{promisify as u}from"node:util";import{createServer as d}from"node:net";const f=u(l),p=n,m={encoding:`utf8`,maxBuffer:16*1024*1024,windowsHide:!0};function h(e){return typeof e==`object`&&!!e}function g(e){return typeof e==`string`?e:null}function _(e){return e instanceof Error?e.message:String(e)}function v(e){if(!h(e))return``;let t=g(e.stdout);return[g(e.stderr),t].filter(e=>typeof e==`string`&&e.length>0).join(`
|
|
2
|
-
`)}function y(e){return h(e)?g(e.code):null}function b(e,t){if(!e)return null;let n=e[t];return typeof n==`string`&&n.length>0?n:null}function x(e){let t=b(e.match(/Current WebView package.*\(([^()]+)\)/i),1)??b(e.match(/versionName=([^\s]+)/i),1);return t?t.trim():null}var S=class{connectedTarget=null;async ensureLocalFileExists(e){try{await c(e)}catch(t){throw new a(`NOT_FOUND`,`Local file not found: ${e}`,{toolName:`adb-bridge`,details:{filePath:e,reason:_(t)}})}}normalizeError(e,t){if(t instanceof a)return t;if(y(t)===`ENOENT`)return new a(`PREREQUISITE`,"ADB binary not found in PATH. Install Android Platform Tools and ensure `adb` is available.",{toolName:`adb-bridge`});let n=v(t).trim(),r=n.length>0?n:_(t),i=r.toLowerCase();return i.includes(`device not found`)||i.includes(`no devices/emulators found`)||i.includes(`device offline`)||i.includes(`device unauthorized`)?new a(`NOT_FOUND`,r,{toolName:`adb-bridge`,details:{command:[`adb`,...e].join(` `)}}):i.includes(`failed to connect`)||i.includes(`unable to connect`)?new a(`CONNECTION`,r,{toolName:`adb-bridge`,details:{command:[`adb`,...e].join(` `)}}):new a(`RUNTIME`,r,{toolName:`adb-bridge`,details:{command:[`adb`,...e].join(` `)}})}async runAdb(e,t=p){try{let{stdout:n}=await f(process.env.ADB_PATH??`adb`,e,{...m,timeout:t});return n}catch(t){throw this.normalizeError(e,t)}}async connect(e,t){if(typeof e==`string`&&e.trim().length>0){let n=`${e.trim()}:${t??5555}`,r=await this.runAdb([`connect`,n]);if(/(failed|unable)/i.test(r))throw new a(`CONNECTION`,r.trim(),{toolName:`adb-bridge`,details:{target:n}});this.connectedTarget=n;return}await this.runAdb([`start-server`]),this.connectedTarget=null}async disconnect(){if(this.connectedTarget){await this.runAdb([`disconnect`,this.connectedTarget]),this.connectedTarget=null;return}await this.runAdb([`disconnect`])}async listDevices(){let e=await this.runAdb([`devices`,`-l`]),t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(e.length===0||e.startsWith(`List of devices attached`)||e.startsWith(`*`))continue;let r=e.split(/\s+/),i=r[0],a=r[1];if(typeof i!=`string`||typeof a!=`string`||a!==`device`)continue;let o=``,s=``,c=``;for(let e of r.slice(2)){let[t,n]=e.split(`:`,2);typeof t!=`string`||typeof n!=`string`||(t===`product`?o=n:t===`model`?s=n:(t===`transport_id`||t===`transport`||t===`usb`)&&(c=n))}t.push({id:i,type:i.startsWith(`emulator-`)?`emulator`:`device`,product:o,model:s,transport:c})}return t}async shell(e,t){return(await this.runAdb([`-s`,e,`shell`,t],r)).replace(/\r?\n$/,``)}async reverse(e,t,n){await this.runAdb([`-s`,e,`reverse`,t,n])}async install(e,t){await this.ensureLocalFileExists(t),await this.runAdb([`-s`,e,`install`,`-r`,t],18e4)}async pull(e,t,n){await this.runAdb([`-s`,e,`pull`,t,n],18e4)}async push(e,t,n){await this.ensureLocalFileExists(t),await this.runAdb([`-s`,e,`push`,t,n],18e4)}async forward(e,t,n){await this.runAdb([`-s`,e,`forward`,t,n])}async getWebViewVersion(e){for(let t of[`cmd webviewupdate getCurrentWebViewPackage`,`dumpsys webviewupdate`,`dumpsys package com.google.android.webview`,`dumpsys package com.android.webview`,`dumpsys package com.android.chrome`])try{let n=x(await this.shell(e,t));if(n)return n}catch{continue}return null}};function C(e){return typeof e==`object`&&!!e}function w(e){return typeof e==`string`?e:null}function T(e,t){if(!e)return null;let n=e[t];return typeof n==`string`&&n.length>0?n:null}function E(e){return C(e)?typeof e.id==`string`&&typeof e.title==`string`&&typeof e.url==`string`:!1}function D(e){return e.startsWith(`@`)?e.slice(1):e}var O=class{adbClient;forwardedPorts=new Map;constructor(e=new S){this.adbClient=e}getPortKey(e,t){return`${e}:${t}`}async getFreePort(){return new Promise((e,t)=>{let n=d();n.once(`error`,t),n.listen(0,`127.0.0.1`,()=>{let r=n.address();if(!r||typeof r==`string`){n.close(),t(new a(`RUNTIME`,`Failed to allocate a local TCP port for WebView debugging.`));return}let{port:i}=r;n.close(n=>{if(n){t(n);return}e(i)})})})}async discoverSockets(e){let t=await this.adbClient.shell(e,`cat /proc/net/unix`),n=new Set;for(let e of t.split(/\r?\n/)){let t=T(e.match(/(@[^\s]*devtools_remote[^\s]*)$/),1);if(!t)continue;let r=D(t);r!==`chrome_devtools_remote`&&n.add(r)}return[...n]}async ensureForward(e,t){let n=this.getPortKey(e,t),r=this.forwardedPorts.get(n);if(typeof r==`number`)return r;let i=await this.getFreePort();return await this.adbClient.forward(e,`tcp:${i}`,`localabstract:${t}`),this.forwardedPorts.set(n,i),i}async fetchTargets(t){let n=await fetch(`http://127.0.0.1:${t}/json/list`,{signal:AbortSignal.timeout(e)});if(!n.ok)throw new a(`CONNECTION`,`Failed to fetch WebView target list on forwarded port ${t}.`,{toolName:`adb_webview`,details:{status:n.status}});let r=await n.json();if(!Array.isArray(r))throw new a(`RUNTIME`,`Unexpected WebView target payload. Expected an array response.`,{toolName:`adb_webview`});return r.filter(E)}async resolveProcessId(e,t){let n=T(t.match(/(?:webview_)?devtools_remote_(\d+)/),1);if(n){let e=Number.parseInt(n,10);if(!Number.isNaN(e))return e}let r=T(t.match(/^(.*)_devtools_remote$/),1);if(!r)return 0;try{let t=(await this.adbClient.shell(e,`pidof -s ${r}`)).split(/\s+/)[0];if(typeof t!=`string`)return 0;let n=Number.parseInt(t,10);return Number.isNaN(n)?0:n}catch{return 0}}async getPrimaryTarget(e,t){let n=await this.ensureForward(e,t),r=await this.fetchTargets(n),i=r.find(e=>e.type===`page`)??r[0];if(!i)throw new a(`NOT_FOUND`,`No debuggable targets found for WebView ${t}.`,{toolName:`adb_webview`,details:{deviceId:e,webviewId:t}});return i}async evaluateViaCdp(e,n){let r=globalThis.WebSocket;if(!r)throw new a(`PREREQUISITE`,`WebSocket API is not available in this Node runtime. Use Node.js 22+ to debug Android WebViews.`,{toolName:`adb_webview`});return new Promise((i,o)=>{let s=new r(e),c=setTimeout(()=>{s.close(),o(new a(`TIMEOUT`,`Timed out while evaluating script inside the Android WebView.`,{toolName:`adb_webview`}))},t),l=e=>{clearTimeout(c),e(),s.close()};s.addEventListener(`open`,()=>{s.send(JSON.stringify({id:1,method:`Runtime.evaluate`,params:{expression:n,returnByValue:!0,awaitPromise:!0}}))}),s.addEventListener(`message`,e=>{let t;try{t=JSON.parse(String(e.data))}catch(e){l(()=>{o(new a(`RUNTIME`,`Failed to parse WebView CDP response: ${String(e)}`,{toolName:`adb_webview`}))});return}if(!C(t)||t.id!==1)return;if(C(t.error)){let e=w(t.error.message)??`Unknown CDP error`;l(()=>{o(new a(`RUNTIME`,e,{toolName:`adb_webview`}))});return}if(!C(t.result)){l(()=>{i(null)});return}if(C(t.result.exceptionDetails)){let e=w(t.result.exceptionDetails.text)??w(t.result.exceptionDetails.description)??`Script execution failed inside the Android WebView.`;l(()=>{o(new a(`RUNTIME`,e,{toolName:`adb_webview`}))});return}if(!C(t.result.result)){l(()=>{i(null)});return}let n=t.result.result;if(`value`in n){l(()=>{i(n.value)});return}let r=w(n.description);l(()=>{i(r)})}),s.addEventListener(`error`,()=>{l(()=>{o(new a(`CONNECTION`,`WebView DevTools socket reported an error while executing script.`,{toolName:`adb_webview`}))})})})}async listWebViews(e){let t=await this.discoverSockets(e),n=[];for(let r of t)try{let t=await this.getPrimaryTarget(e,r);n.push({id:r,url:t.url,title:t.title,processId:await this.resolveProcessId(e,r)})}catch{n.push({id:r,url:``,title:``,processId:await this.resolveProcessId(e,r)})}return n}async attachWebView(e,t){if(!(await this.discoverSockets(e)).includes(t))throw new a(`NOT_FOUND`,`WebView ${t} was not found on device ${e}.`,{toolName:`adb_webview`});await this.getPrimaryTarget(e,t)}async executeScript(e,t,n){await this.attachWebView(e,t);let r=await this.getPrimaryTarget(e,t);if(typeof r.webSocketDebuggerUrl!=`string`||r.webSocketDebuggerUrl.length===0)throw new a(`CONNECTION`,`WebView ${t} does not expose a WebSocket debugger endpoint.`,{toolName:`adb_webview`});return this.evaluateViaCdp(r.webSocketDebuggerUrl,n)}};function k(e){return e instanceof Error?e.message:String(e)}var A=class{adbClient;webviewDbg;constructor(e,t){this.adbClient=e,this.webviewDbg=t}getADBClient(){return this.adbClient||=new S,this.adbClient}getWebViewDebugger(){return this.webviewDbg||=new O(this.getADBClient()),this.webviewDbg}async run(e,t){try{return i(await t())}catch(t){throw t instanceof a?t:new a(`RUNTIME`,k(t),{toolName:e})}}async handleAnalyzeApk(e){return this.run(`adb_apk_analyze`,async()=>{let t=s(e,`serial`),n=s(e,`packageName`),r=await this.getADBClient().shell(t,`dumpsys package ${n}`),i={packageName:n},a=r.match(/versionName=([^\s]+)/);a&&(i.versionName=a[1]);let o=r.match(/versionCode=(\d+)/);o&&(i.versionCode=o[1]);let c=r.match(/minSdk=(\d+)/);c&&(i.minSdk=c[1]);let l=r.match(/targetSdk=(\d+)/);l&&(i.targetSdk=l[1]);let u=[],d=[],f=[],p=[],m=``;for(let e of r.split(/\r?\n/)){if(e.includes(`requested permissions:`)||e.includes(`install permissions:`)){m=`permissions`;continue}if(e.includes(`Activity Resolver Table`)||e.includes(`activities:`)){m=`activities`;continue}if(e.includes(`Service Resolver Table`)||e.includes(`services:`)){m=`services`;continue}if(e.includes(`Receiver Resolver Table`)||e.includes(`receivers:`)){m=`receivers`;continue}let t=e.trim();if(t.startsWith(`android.permission.`)||t.startsWith(`com.`)){let e=t.split(` `)[0];e&&(m===`permissions`?u.push(e):m||u.push(e))}if(m===`activities`&&t.includes(n)){let e=t.match(/(\S+)/);e&&d.push(e[1])}if(m===`services`&&t.includes(n)){let e=t.match(/(\S+)/);e&&f.push(e[1])}if(m===`receivers`&&t.includes(n)){let e=t.match(/(\S+)/);e&&p.push(e[1])}}return i.permissions=[...new Set(u)],i.activities=[...new Set(d)],i.services=[...new Set(f)],i.receivers=[...new Set(p)],{success:!0,serial:t,...i}})}async handleWebViewList(e){return this.run(`adb_webview_list`,async()=>{let t=s(e,`serial`),n=o(e,`hostPort`)??9222;return{success:!0,serial:t,webViewVersion:await this.getADBClient().getWebViewVersion(t),hostPort:n,webviews:(await this.getWebViewDebugger().listWebViews(t)).map(e=>({id:e.id,url:e.url,title:e.title,processId:e.processId}))}})}async handleWebViewAttach(e){return this.run(`adb_webview_attach`,async()=>{let t=s(e,`serial`),n=s(e,`targetId`),r=o(e,`hostPort`)??9222;return await this.getWebViewDebugger().attachWebView(t,n),{success:!0,serial:t,targetId:n,hostPort:r,attached:!0,snapshot:await this.getWebViewDebugger().executeScript(t,n,`(() => ({ title: document.title, url: location.href, readyState: document.readyState }))()`)}})}};export{A as ADBBridgeHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Rt as e}from"./constants-Cp6hBrrx.mjs";function t(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function n(e,n){return t({success:!1,tool:e,error:n instanceof Error?n.message:String(n)})}var r=class{sessionManager;constructor(e){this.sessionManager=e}async handleScanList(e){try{let e=this.sessionManager.listSessions();return t({success:!0,sessions:e,count:e.length})}catch(e){return n(`memory_scan_session`,e)}}async handleScanDelete(e){try{return t({success:!0,deleted:this.sessionManager.deleteSession(e.sessionId)})}catch(e){return n(`memory_scan_session`,e)}}async handleScanExport(e){try{return t({success:!0,exportedData:this.sessionManager.exportSession(e.sessionId)})}catch(e){return n(`memory_scan_session`,e)}}};function i(t){return t===void 0||!Number.isFinite(t)||t<=0?e:Math.min(t,e)}function a(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function o(e,t){return a({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}var s=class{scanner;eventBus;constructor(e,t){this.scanner=e,this.eventBus=t}async handleFirstScan(e){try{let t={valueType:e.valueType,alignment:e.alignment,maxResults:i(e.maxResults),regionFilter:e.regionFilter,onProgress:e.onProgress},n=await this.scanner.firstScan(e.pid,e.value,t);return this.eventBus?.emit(`memory:scan_completed`,{scanType:`first`,resultCount:n.totalMatches??0,timestamp:new Date().toISOString()}),a({success:!0,...n,hint:n.totalMatches>0?`Found ${n.totalMatches} matches. Use memory_next_scan with sessionId "${n.sessionId}" to narrow down.`:`No matches found. Try a different value or type.`})}catch(e){return o(`memory_first_scan`,e)}}async handleNextScan(e){try{let t=await this.scanner.nextScan(e.sessionId,e.mode,e.value,e.value2);return a({success:!0,...t,hint:t.totalMatches<=10?`Few matches remaining — inspect these addresses.`:`${t.totalMatches} matches remain. Continue narrowing with memory_next_scan.`})}catch(e){return o(`memory_next_scan`,e)}}async handleUnknownScan(e){try{let t={valueType:e.valueType,alignment:e.alignment,maxResults:i(e.maxResults),regionFilter:e.regionFilter,onProgress:e.onProgress},n=await this.scanner.unknownInitialScan(e.pid,t);return a({success:!0,...n,hint:`Captured ${n.totalMatches} addresses. Use memory_next_scan with changed/unchanged/increased/decreased to narrow.`})}catch(e){return o(`memory_unknown_scan`,e)}}async handlePointerScan(e){try{return a({success:!0,...await this.scanner.pointerScan(e.pid,e.targetAddress,{maxResults:i(e.maxResults),moduleOnly:e.moduleOnly})})}catch(e){return o(`memory_pointer_scan`,e)}}async handleGroupScan(e){try{return a({success:!0,...await this.scanner.groupScan(e.pid,e.pattern,{alignment:e.alignment,maxResults:i(e.maxResults)})})}catch(e){return o(`memory_group_scan`,e)}}};function c(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function l(e,t){return c({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}var u=class{ptrEngine;constructor(e){this.ptrEngine=e}async handlePointerChainScan(e){try{let t=await this.ptrEngine.scan(e.pid,e.targetAddress,{maxDepth:e.maxDepth,maxOffset:e.maxOffset,staticOnly:e.staticOnly,modules:e.modules,maxResults:e.maxResults});return c({success:!0,...t,hint:t.totalFound>0?`Found ${t.totalFound} pointer chains. Static chains survive process restarts.`:`No pointer chains found. Try increasing maxDepth or maxOffset.`})}catch(e){return l(`memory_pointer_chain_scan`,e)}}async handlePointerChainValidate(e){try{let t=JSON.parse(e.chains),n=await this.ptrEngine.validateChains(e.pid,t);return c({success:!0,results:n,validCount:n.filter(e=>e.isValid).length,totalChecked:t.length})}catch(e){return l(`memory_pointer_chain_validate`,e)}}async handlePointerChainResolve(e){try{let t=JSON.parse(e.chain),n=await this.ptrEngine.resolveChain(e.pid,t);return c({success:!0,chainId:t.id,resolvedAddress:n,isResolvable:n!==null})}catch(e){return l(`memory_pointer_chain_resolve`,e)}}async handlePointerChainExport(e){try{let t=JSON.parse(e.chains);return c({success:!0,exportedData:this.ptrEngine.exportChains(t),chainCount:t.length})}catch(e){return l(`memory_pointer_chain_export`,e)}}};function d(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function f(e,t){return d({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}const p={int8_t:`int8`,uint8_t:`uint8`,int16_t:`int16`,uint16_t:`uint16`,int32_t:`int32`,uint32_t:`uint32`,int64_t:`int64`,uint64_t:`uint64`,void_ptr:`pointer`,char_ptr:`string_ptr`};function m(e){if(typeof e!=`string`||e.length===0)return`unknown`;let t=e.toLowerCase().replace(/\s+/g,`_`).replace(/\*/g,`_ptr`);return p[t]??t}function h(e){if(!e||typeof e!=`object`)throw Error(`structure must be a JSON object`);let t=e,n=(Array.isArray(t.fields)?t.fields:[]).map((e,t)=>{let n=e;return{offset:typeof n.offset==`number`?n.offset:0,size:typeof n.size==`number`?n.size:1,type:m(n.type),name:typeof n.name==`string`&&n.name.length>0?n.name:`field_${t}`,value:typeof n.value==`string`?n.value:``,confidence:typeof n.confidence==`number`?n.confidence:1,notes:typeof n.notes==`string`?n.notes:void 0}}),r=n.reduce((e,t)=>Math.max(e,t.offset+t.size),0),i=typeof t.totalSize==`number`?t.totalSize:typeof t.size==`number`?t.size:r;return{baseAddress:typeof t.baseAddress==`string`?t.baseAddress:`0x0`,totalSize:i,fields:n,vtableAddress:typeof t.vtableAddress==`string`?t.vtableAddress:void 0,className:typeof t.className==`string`?t.className:void 0,baseClasses:Array.isArray(t.baseClasses)?t.baseClasses.filter(e=>typeof e==`string`):void 0,timestamp:typeof t.timestamp==`number`?t.timestamp:Date.now()}}var g=class{structAnalyzer;constructor(e){this.structAnalyzer=e}async handleStructureAnalyze(e){try{let t=await this.structAnalyzer.analyzeStructure(e.pid,e.address,{size:e.size,otherInstances:e.otherInstances,parseRtti:e.parseRtti});return d({success:!0,...t,hint:t.className?`Detected class: ${t.className}${t.baseClasses?.length?` (inherits: ${t.baseClasses.join(` → `)})`:``}`:`Inferred ${t.fields.length} fields. Use memory_structure_export_c to export as C struct.`})}catch(e){return f(`memory_structure_analyze`,e)}}async handleVtableParse(e){try{return d({success:!0,...await this.structAnalyzer.parseVtable(e.pid,e.vtableAddress)})}catch(e){return f(`memory_vtable_parse`,e)}}async handleStructureExportC(e){try{let t=h(JSON.parse(e.structure));return d({success:!0,...this.structAnalyzer.exportToCStruct(t,e.name)})}catch(e){return f(`memory_structure_export_c`,e)}}async handleStructureCompare(e){try{let t=await this.structAnalyzer.compareInstances(e.pid,e.address1,e.address2,e.size);return d({success:!0,matchingFieldCount:t.matching.length,differingFieldCount:t.differing.length,...t})}catch(e){return f(`memory_structure_compare`,e)}}};function _(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function v(e,t){return _({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}var y=class{bpEngine;injector;constructor(e,t){this.bpEngine=e,this.injector=t}async handleBreakpointSet(e){try{return _({success:!0,...await this.bpEngine.setBreakpoint(e.pid,e.address,e.access,e.size??4),hint:`Hardware breakpoint set on DR register. Use memory_breakpoint with action='trace' to collect hits.`})}catch(e){return v(`memory_breakpoint`,e)}}async handleBreakpointRemove(e){try{return _({success:!0,removed:await this.bpEngine.removeBreakpoint(e.breakpointId)})}catch(e){return v(`memory_breakpoint`,e)}}async handleBreakpointList(e){try{let e=this.bpEngine.listBreakpoints();return _({success:!0,breakpoints:e,count:e.length})}catch(e){return v(`memory_breakpoint`,e)}}async handleBreakpointTrace(e){try{let t=await this.bpEngine.traceAccess(e.pid,e.address,e.access,e.maxHits,e.timeoutMs);return _({success:!0,hits:t,hitCount:t.length,hint:t.length>0?`${t.length} accesses captured. Check instructionAddress to find the code accessing this address.`:`No hits captured within timeout.`})}catch(e){return v(`memory_breakpoint`,e)}}async handlePatchBytes(e){try{let t=await this.injector.patchBytes(e.pid,e.address,e.bytes);return _({success:!0,...t,hint:`Patch applied. Use memory_patch_undo with patchId "${t.id}" to restore.`})}catch(e){return v(`memory_patch_bytes`,e)}}async handlePatchNop(e){try{return _({success:!0,...await this.injector.nopBytes(e.pid,e.address,e.count),hint:`${e.count} bytes NOP'd. Use memory_patch_undo to restore.`})}catch(e){return v(`memory_patch_nop`,e)}}async handlePatchUndo(e){try{return _({success:!0,restored:await this.injector.unpatch(e.patchId)})}catch(e){return v(`memory_patch_undo`,e)}}async handleCodeCaves(e){try{let t=await this.injector.findCodeCaves(e.pid,e.minSize);return _({success:!0,caves:t,count:t.length})}catch(e){return v(`memory_code_caves`,e)}}};function b(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function x(e,t){return b({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}var S=class{memCtrl;constructor(e){this.memCtrl=e}async handleWriteValue(e){try{return b({success:!0,...await this.memCtrl.writeValue(e.pid,e.address,e.value,e.valueType),hint:`Use memory_write_history with action='undo' to revert.`})}catch(e){return x(`memory_write_value`,e)}}async handleFreeze(e){try{let t=await this.memCtrl.freeze(e.pid,e.address,e.value,e.valueType,e.intervalMs);return b({success:!0,...t,hint:`Frozen. Use memory_freeze with action="unfreeze" and freezeId "${t.id}" to stop.`})}catch(e){return x(`memory_freeze`,e)}}async handleUnfreeze(e){try{return b({success:!0,unfrozen:await this.memCtrl.unfreeze(e.freezeId)})}catch(e){return x(`memory_freeze`,e)}}async handleDump(e){try{return b({success:!0,dump:await this.memCtrl.dumpMemoryHex(e.pid,e.address,e.size??256)})}catch(e){return x(`memory_dump`,e)}}async handleWriteUndo(e){try{let e=await this.memCtrl.undo();return b({success:!0,undone:e!==null,entry:e})}catch(e){return x(`memory_write_history`,e)}}async handleWriteRedo(e){try{let e=await this.memCtrl.redo();return b({success:!0,redone:e!==null,entry:e})}catch(e){return x(`memory_write_history`,e)}}};function C(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function w(e,t){return C({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}var T=class{speedhackEngine;heapAnalyzer;peAnalyzer;antiCheatDetector;constructor(e,t,n,r){this.speedhackEngine=e,this.heapAnalyzer=t,this.peAnalyzer=n,this.antiCheatDetector=r}async handleSpeedhackApply(e){try{return C({...await this.speedhackEngine.apply(e.pid,e.speed),success:!0,hint:`Speedhack active (${e.speed}x). Use memory_speedhack({ action: 'set' }) to adjust.`})}catch(e){return w(`memory_speedhack`,e)}}async handleSpeedhackSet(e){try{return C({success:!0,updated:await this.speedhackEngine.setSpeed(e.pid,e.speed),newSpeed:e.speed})}catch(e){return w(`memory_speedhack`,e)}}async handleHeapEnumerate(e){try{let t=await this.heapAnalyzer.enumerateHeaps(e.pid);return C({success:!0,...t,hint:`Enumerated ${t.heaps.length} heaps. Use memory_heap_stats for statistics or memory_heap_anomalies to check for issues.`})}catch(e){return w(`memory_heap_enumerate`,e)}}async handleHeapStats(e){try{return C({success:!0,...await this.heapAnalyzer.getStats(e.pid)})}catch(e){return w(`memory_heap_stats`,e)}}async handleHeapAnomalies(e){try{let t=await this.heapAnalyzer.detectAnomalies(e.pid);return C({success:!0,anomalies:t,count:t.length,hint:t.length>0?`Found ${t.length} anomalies — inspect types for spray, UAF, or suspicious patterns.`:`No heap anomalies detected.`})}catch(e){return w(`memory_heap_anomalies`,e)}}async handlePEHeaders(e){try{return C({success:!0,...await this.peAnalyzer.parseHeaders(e.pid,e.moduleBase)})}catch(e){return w(`memory_pe_headers`,e)}}async handlePEImportsExports(e){try{let t=e.table||`both`,n=e.moduleBase,r=e.pid,i={success:!0};return(t===`imports`||t===`both`)&&(i.imports=await this.peAnalyzer.parseImports(r,n)),(t===`exports`||t===`both`)&&(i.exports=await this.peAnalyzer.parseExports(r,n)),C(i)}catch(e){return w(`memory_pe_imports_exports`,e)}}async handleInlineHookDetect(e){try{let t=await this.peAnalyzer.detectInlineHooks(e.pid,e.moduleName);return C({success:!0,hooks:t,count:t.length,hint:t.length>0?`Detected ${t.length} inline hooks — check hookType and jumpTarget for each.`:`No inline hooks detected — exports match disk bytes.`})}catch(e){return w(`memory_inline_hook_detect`,e)}}async handleAntiCheatDetect(e){try{let t=await this.antiCheatDetector.detect(e.pid);return C({success:!0,detections:t,count:t.length,hint:t.length>0?`Found ${t.length} anti-debug mechanisms. Each includes a bypassSuggestion.`:`No anti-debug mechanisms detected in imports.`})}catch(e){return w(`memory_anticheat_detect`,e)}}async handleGuardPages(e){try{let{guardPages:t,stats:n}=await this.antiCheatDetector.scanGuardPages(e.pid);return C({success:!0,guardPages:t,count:t.length,scan:n,hint:n.truncated?`Scan stopped after ${n.scannedRegions} regions in ${n.durationMs}ms to avoid hanging. Results may be partial.`:t.length>0?`Found ${t.length} guard page regions — these may indicate anti-tampering.`:`No guard pages found.`})}catch(e){return w(`memory_guard_pages`,e)}}async handleIntegrityCheck(e){try{let{sections:t,stats:n}=await this.antiCheatDetector.scanIntegrity(e.pid,e.moduleName),r=t.filter(e=>e.isModified);return C({success:!0,sections:t,totalChecked:t.length,modifiedCount:r.length,scan:n,hint:n.truncated?`Checked ${n.scannedSections} executable section(s) across ${n.scannedModules} module(s) before hitting safety limits. Results may be partial.`:r.length>0?`${r.length} section(s) modified — code may have been patched or hooked.`:`All checked sections match disk — no runtime modifications detected.`})}catch(e){return w(`memory_integrity_check`,e)}}},E=class{sessions;scans;ptrChains;structures;hooks;readwrite;integrity;constructor(e,t,n,i,a,o,c,l,d,f,p,m){this.sessions=new r(t),this.scans=new s(e,m),this.ptrChains=new u(n),this.structures=new g(i),this.hooks=new y(a,o),this.readwrite=new S(c),this.integrity=new T(l,d,f,p)}handleScanSessionDispatch(e){switch(String(e.action??``)){case`delete`:return this.sessions.handleScanDelete(e);case`export`:return this.sessions.handleScanExport(e);default:return this.sessions.handleScanList(e)}}handleScanList=e=>this.sessions.handleScanList(e);handleScanDelete=e=>this.sessions.handleScanDelete(e);handleScanExport=e=>this.sessions.handleScanExport(e);handleFirstScan=e=>this.scans.handleFirstScan(e);handleNextScan=e=>this.scans.handleNextScan(e);handleUnknownScan=e=>this.scans.handleUnknownScan(e);handlePointerScan=e=>this.scans.handlePointerScan(e);handleGroupScan=e=>this.scans.handleGroupScan(e);handlePointerChainDispatch(e){switch(String(e.action??``)){case`validate`:return this.ptrChains.handlePointerChainValidate(e);case`resolve`:return this.ptrChains.handlePointerChainResolve(e);case`export`:return this.ptrChains.handlePointerChainExport(e);default:return this.ptrChains.handlePointerChainScan(e)}}handlePointerChainScan=e=>this.ptrChains.handlePointerChainScan(e);handlePointerChainValidate=e=>this.ptrChains.handlePointerChainValidate(e);handlePointerChainResolve=e=>this.ptrChains.handlePointerChainResolve(e);handlePointerChainExport=e=>this.ptrChains.handlePointerChainExport(e);handleStructureAnalyze=e=>this.structures.handleStructureAnalyze(e);handleVtableParse=e=>this.structures.handleVtableParse(e);handleStructureExportC=e=>this.structures.handleStructureExportC(e);handleStructureCompare=e=>this.structures.handleStructureCompare(e);handleBreakpointDispatch(e){switch(String(e.action??``)){case`remove`:return this.hooks.handleBreakpointRemove(e);case`list`:return this.hooks.handleBreakpointList(e);case`trace`:return this.hooks.handleBreakpointTrace(e);default:return this.hooks.handleBreakpointSet(e)}}handleBreakpointSet=e=>this.hooks.handleBreakpointSet(e);handleBreakpointRemove=e=>this.hooks.handleBreakpointRemove(e);handleBreakpointList=e=>this.hooks.handleBreakpointList(e);handleBreakpointTrace=e=>this.hooks.handleBreakpointTrace(e);handlePatchBytes=e=>this.hooks.handlePatchBytes(e);handlePatchNop=e=>this.hooks.handlePatchNop(e);handlePatchUndo=e=>this.hooks.handlePatchUndo(e);handleCodeCaves=e=>this.hooks.handleCodeCaves(e);handleFreezeDispatch(e){return String(e.action??``)===`unfreeze`?this.readwrite.handleUnfreeze(e):this.readwrite.handleFreeze(e)}handleWriteHistoryDispatch(e){return String(e.action??``)===`redo`?this.readwrite.handleWriteRedo(e):this.readwrite.handleWriteUndo(e)}handleWriteValue=e=>this.readwrite.handleWriteValue(e);handleFreeze=e=>this.readwrite.handleFreeze(e);handleUnfreeze=e=>this.readwrite.handleUnfreeze(e);handleDump=e=>this.readwrite.handleDump(e);handleWriteUndo=e=>this.readwrite.handleWriteUndo(e);handleWriteRedo=e=>this.readwrite.handleWriteRedo(e);handleSpeedhackDispatch(e){return String(e.action??``)===`set`?this.integrity.handleSpeedhackSet(e):this.integrity.handleSpeedhackApply(e)}handleSpeedhackApply=e=>this.integrity.handleSpeedhackApply(e);handleSpeedhackSet=e=>this.integrity.handleSpeedhackSet(e);handleHeapEnumerate=e=>this.integrity.handleHeapEnumerate(e);handleHeapStats=e=>this.integrity.handleHeapStats(e);handleHeapAnomalies=e=>this.integrity.handleHeapAnomalies(e);handlePEHeaders=e=>this.integrity.handlePEHeaders(e);handlePEImportsExports=e=>this.integrity.handlePEImportsExports(e);handleInlineHookDetect=e=>this.integrity.handleInlineHookDetect(e);handleAntiCheatDetect=e=>this.integrity.handleAntiCheatDetect(e);handleGuardPages=e=>this.integrity.handleGuardPages(e);handleIntegrityCheck=e=>this.integrity.handleIntegrityCheck(e)};export{E as MemoryScanHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./logger-sBC6IdRT.mjs";import{$ as t,U as n,W as r,ht as i}from"./constants-Cp6hBrrx.mjs";import{n as a,t as o}from"./artifactRetention-NBdncOEW.mjs";import{a as s,n as c}from"./response-C7rKQst4.mjs";import{t as l}from"./types-CuyefmGT.mjs";import{i as u,l as d}from"./outputPaths-BonGThuc.mjs";import{r as f}from"./betterSqlite3-CGaxz4AX.mjs";import{r as p}from"./concurrency-CcK46d0h.mjs";import{t as m}from"./ToolRegistry-B0Zs-phN.mjs";import"./definitions-CdWEuIkI.mjs";import{createRequire as h}from"node:module";import{existsSync as g}from"node:fs";import{dirname as _,isAbsolute as v,relative as y,resolve as b}from"node:path";import{fileURLToPath as x}from"node:url";import{mkdir as S,readFile as C,writeFile as w}from"node:fs/promises";import{execFile as T}from"node:child_process";import{promisify as E}from"node:util";const D=E(T),O=h(import.meta.url);let k=null,A=0;function j(){let e=Date.now();return(!k||e-A>12e4)&&(k=new m,A=e),k}async function M(e){let n=e?.includeBridgeHealth??!0,r=j().probeAll(!0),o=p(()=>L(`git`,[`--version`])),s=p(()=>L(`python`,[`--version`])),c=p(()=>ee()),l=p(()=>L(`corepack`,[`--version`])),d=n?Promise.all([p(()=>z(`ghidra-bridge`,`${t.replace(/\/$/,``)}/health`)),p(()=>z(`ida-bridge`,`${i.replace(/\/$/,``)}/health`)),p(()=>z(`burp-mcp-sse`,process.env.BURP_MCP_SSE_URL?.trim()||`http://127.0.0.1:9876`))]):Promise.resolve([]),[f,m,h,g,_,v]=await Promise.all([r,o,s,c,l,d]),y=te(_,g),b=[N(`@modelcontextprotocol/sdk`),N(`rebrowser-puppeteer-core`),P(),N(`camoufox-js`,`Optional Firefox anti-detect driver`),N(`playwright-core`,`Optional browser automation dependency`),I()],x=[m,h,g,y,...Object.entries(f).map(([e,t])=>({name:e,status:t.available?`ok`:`missing`,detail:t.available?`${t.path??`PATH`}${t.version?` (${t.version})`:``}`:t.reason??`Unavailable`}))],S=ne(),C=re(b,x,v,S);return{success:[...b,...x,...v].every(e=>e.status!==`error`),generatedAt:new Date().toISOString(),runtime:{platform:process.platform,arch:process.arch,node:process.version,cwd:process.cwd(),projectRoot:u()},packages:b,commands:x,bridges:v,config:{transport:(process.env.MCP_TRANSPORT??`stdio`).toLowerCase(),toolProfile:(process.env.MCP_TOOL_PROFILE??`search`).toLowerCase(),pluginRoots:process.env.MCP_PLUGIN_ROOTS??`<jshook-install>/plugins`,workflowRoots:process.env.MCP_WORKFLOW_ROOTS??`<jshook-install>/workflows`,pluginSignatureRequired:process.env.MCP_PLUGIN_SIGNATURE_REQUIRED??(process.env.NODE_ENV===`production`?`true (production default)`:`false`),pluginStrictLoad:process.env.MCP_PLUGIN_STRICT_LOAD??(process.env.NODE_ENV===`production`?`true (production default)`:`false`),artifactRetention:a()},limitations:S,recommendations:C}}function N(e,t){try{let t=O(O.resolve(`${e}/package.json`));return{name:e,status:`ok`,detail:t.version?`installed (${t.version})`:`installed`}}catch{return{name:e,status:`missing`,detail:t??`Not installed`}}}function P(){let e=f();return{name:`better-sqlite3`,status:e.status,detail:e.detail}}function F(e){return e.status===`ok`||e.detail.includes(`npx fallback works`)}async function ee(){let e=await L(`pnpm`,[`--version`]);if(e.status===`ok`)return e;let t=await L(`npx`,[`pnpm`,`--version`],1e4);return t.status===`ok`?{name:`pnpm`,status:`warn`,detail:`direct pnpm command unavailable; npx fallback works (${t.detail})`}:e}function te(e,t){return e.status!==`missing`||!F(t)?e:{name:e.name,status:`warn`,detail:process.platform===`win32`?t.detail.includes(`npx fallback works`)?"corepack not found; use `npx pnpm` directly (common with nvm4w-managed Node on Windows)":`corepack not found; standalone pnpm is available (common with nvm4w-managed Node on Windows)`:t.detail.includes(`npx fallback works`)?"corepack not found; use `npx pnpm` directly":`corepack not found; standalone pnpm is available`}}function I(){try{let e=O(O.resolve(`koffi/package.json`)).version??`unknown`;if(process.platform===`win32`)return{name:`native-memory`,status:`ok`,detail:`koffi ${e} — Win32 kernel32.dll available`};if(process.platform===`darwin`)try{return O(`koffi`).load(`/usr/lib/libSystem.B.dylib`).unload(),delete O.cache[O.resolve(`koffi`)],{name:`native-memory`,status:`ok`,detail:`koffi ${e} — macOS libSystem.B.dylib available (Mach APIs need root + SIP config)`}}catch{return{name:`native-memory`,status:`warn`,detail:`koffi ${e} installed but cannot load libSystem.B.dylib`}}return{name:`native-memory`,status:`warn`,detail:`koffi ${e} — no native FFI memory provider for ${process.platform} (proc-based ops available on Linux)`}}catch{return{name:`native-memory`,status:`missing`,detail:`koffi not installed — native memory tools unavailable. Install with: pnpm add koffi`}}}async function L(e,t,n=4e3){try{let{stdout:r,stderr:i}=await D(e,t,{timeout:n,windowsHide:!0});return{name:e,status:`ok`,detail:`${r||i}`.trim().split(/\r?\n/)[0]||`available`}}catch(r){if(process.platform===`win32`)try{let{stdout:r,stderr:i}=await D(`cmd`,[`/c`,e,...t],{timeout:n,windowsHide:!0});return{name:e,status:`ok`,detail:`${`${r||i}`.trim().split(/\r?\n/)[0]||`available`} (via cmd)`}}catch(t){return R(e,t)}return R(e,r)}}function R(e,t){let n=t instanceof Error?t.message:String(t);return{name:e,status:/ENOENT|not recognized|not found/i.test(n)?`missing`:`warn`,detail:n}}async function z(e,t){try{let n=await fetch(t,{method:`GET`,signal:AbortSignal.timeout(3e3)});return{name:e,status:n.ok?`ok`:`warn`,detail:`${t} -> HTTP ${n.status}`}}catch(n){return{name:e,status:`warn`,detail:`${t} -> ${n instanceof Error?n.message:String(n)}`}}}function ne(){let e=[];return process.platform===`darwin`?(e.push(`26 cross-platform memory tools available (scan, pointer-chain, structure-analysis, heap). 15 Windows-only tools unavailable (PE analysis, anti-cheat, code injection, speedhack, hardware breakpoints).`),e.push(`Native memory operations (mach_vm_read/write) require root privileges and may require SIP configuration on ARM64.`)):process.platform===`linux`?(e.push(`Process management available via /proc. Native FFI memory provider not implemented — memory read/write uses /proc/pid/mem (requires root or CAP_SYS_PTRACE).`),e.push(`Camoufox runs on Linux, but some Chrome/CDP-heavy workflows are better served by the Chrome driver.`)):process.platform!==`win32`&&e.push(`Platform ${process.platform} is not supported for native memory operations. Use Windows or macOS.`),e}function re(e,t,n,r){let i=[],a=t.find(e=>e.name===`pnpm`),o=t.find(e=>e.name===`corepack`);return e.some(e=>e.name===`better-sqlite3`&&e.status!==`ok`)&&i.push("Install or rebuild the optional SQLite trace backend with `pnpm add -O better-sqlite3@12.6.2` or `npm rebuild better-sqlite3 --foreground-scripts` under the active Node version if you need trace tooling."),e.some(e=>e.name===`camoufox-js`&&e.status!==`ok`)&&i.push("Install optional browser dependencies with `pnpm run install:full` if you need Camoufox support."),t.some(e=>e.name.startsWith(`wabt.`)&&e.status!==`ok`)&&i.push(`Install wabt if you need full WASM disassembly/decompilation; otherwise the server will stay in basic mode.`),a&&!F(a)?i.push("Install pnpm or enable Corepack (`corepack enable`) before running package-management workflows."):a?.detail.includes(`npx fallback works`)?i.push("Use `npx pnpm` directly on this machine or repair the local pnpm/Corepack shim if scripts expect bare `pnpm`."):o?.status===`warn`&&o.detail.includes(`standalone pnpm`)&&i.push("Use `pnpm` or `npx pnpm` directly on this machine; `corepack` is optional and may be absent on nvm4w-managed Windows installs."),n.some(e=>e.status!==`ok`)&&i.push(`Check local bridge endpoints (Ghidra / IDA / Burp) before relying on native-bridge workflows.`),r.length>0&&i.push(`Review platform limitations before using process/memory tooling on non-Windows hosts.`),i}var ie=class{tokenBudget;unifiedCache;artifactCleanup;environmentDoctor;constructor(e){this.tokenBudget=e.tokenBudget,this.unifiedCache=e.unifiedCache,this.artifactCleanup=e.artifactCleanup??o,this.environmentDoctor=e.environmentDoctor??M}async handleGetTokenBudgetStats(){try{let e=this.tokenBudget.getStats();return c({success:!0,...e,sessionDuration:`${Math.round((Date.now()-e.sessionStartTime)/1e3)}s`})}catch(t){return e.error(`Failed to read token budget stats:`,t),c(s(t))}}async handleManualTokenCleanup(){try{let e=this.tokenBudget.getStats();this.tokenBudget.manualCleanup();let t=this.tokenBudget.getStats(),n=e.currentUsage-t.currentUsage;return c({success:!0,message:`Manual cleanup completed`,before:{usage:e.currentUsage,percentage:e.usagePercentage},after:{usage:t.currentUsage,percentage:t.usagePercentage},freed:{tokens:n,percentage:Math.round(n/e.maxTokens*100)}})}catch(t){return e.error(`Failed to perform manual cleanup:`,t),c(s(t))}}async handleResetTokenBudget(){try{return this.tokenBudget.reset(),c({success:!0,message:`Token budget reset successfully`,currentUsage:0,maxTokens:2e5,usagePercentage:0})}catch(t){return e.error(`Failed to reset token budget:`,t),c(s(t))}}async handleGetCacheStats(){try{return c({success:!0,...await this.unifiedCache.getGlobalStats()})}catch(t){return e.error(`Failed to get cache stats:`,t),c(s(t))}}async handleSmartCacheCleanup(t){try{return c({success:!0,...await this.unifiedCache.smartCleanup(t)})}catch(t){return e.error(`Failed to perform cache cleanup:`,t),c(s(t))}}async handleClearAllCaches(){try{return await this.unifiedCache.clearAll(),c({success:!0,message:`All caches cleared`})}catch(t){return e.error(`Failed to clear caches:`,t),c(s(t))}}async handleCleanupArtifacts(t){try{return c(await this.artifactCleanup({retentionDays:t.retentionDays,maxTotalBytes:t.maxTotalBytes,dryRun:t.dryRun}))}catch(t){return e.error(`Failed to cleanup artifacts:`,t),c(s(t))}}async handleEnvironmentDoctor(t){try{return c(await this.environmentDoctor({includeBridgeHealth:t.includeBridgeHealth}))}catch(t){return e.error(`Failed to run environment doctor:`,t),c(s(t))}}};const B=E(T);function V(){return x(new URL(`../../../../`,import.meta.url))}function ae(e){let t=e?.trim();if(t)return t.split(`,`).map(e=>e.trim()).find(e=>e.length>0)}function H(e){let t=e===`workflow`?`MCP_WORKFLOW_ROOTS`:`MCP_PLUGIN_ROOTS`,n=ae(process.env[t]);return n?b(n):b(V(),e===`workflow`?`workflows`:`plugins`)}function U(){let e=(process.env.EXTENSION_REGISTRY_BASE_URL??``).trim().replace(/\/+$/,``);if(!e)throw Error(`EXTENSION_REGISTRY_BASE_URL is not configured. Set it in .env or environment before browsing or installing extensions.`);return e}function W(e,t){let n=e?.trim();if(!n){if(t===`subpath`)return`.`;throw Error(`Registry source.${t} must be a non-empty string`)}return n}function G(e,t,n){let r=y(e,t).replace(/\\/g,`/`);if(r===`..`||r.startsWith(`../`)||v(r))throw Error(`Registry source.${n} must stay within ${e}: ${t}`)}function K(e,t){let n=b(e,W(t,`subpath`));return G(e,n,`subpath`),n}function q(e,t){let n=b(e,W(t,`entry`));return G(e,n,`entry`),n}function oe(e){let t=W(e,`entry`).replace(/\\/g,`/`),n=[t];if(!t.endsWith(`.ts`))return n;let r=`${t.slice(0,-3)}.js`;return n.unshift(r),t.startsWith(`dist/`)||n.unshift(`dist/${r}`),[...new Set(n)]}function se(e,t){let n=oe(t);for(let t of n)if(g(q(e,t)))return t;return W(t,`entry`)}async function ce(e,t,n,r){let i={version:1,kind:e,slug:t.slug,id:t.id,source:{type:t.source.type,repo:t.source.repo,ref:t.source.ref,commit:t.source.commit,subpath:W(t.source.subpath,`subpath`),entry:W(r,`entry`)}},a=b(n,l);return await w(a,`${JSON.stringify(i,null,2)}\n`,`utf8`),a}const J=`@jshookmcp/extension-sdk`,le=b(V(),`packages`,`extension-sdk`);function ue(){return d().paths.registryCacheDir}var Y=class extends Error{code;url;cachePath;status;constructor(e,t,n,r,i){super(n),this.code=e,this.url=t,this.cachePath=r,this.status=i,this.name=`RegistryFetchError`}};function de(e,t){return process.platform===`win32`?{command:`powershell.exe`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,`${e} ${t.join(` `)}`]}:{command:e,args:t}}async function X(e,t,n){let r=de(e,t);return B(r.command,r.args,{...n,env:{...process.env,...n?.env,CI:`true`}})}async function fe(e){let t=b(e,`package.json`),n=b(e,`pnpm-lock.yaml`),r=b(e,`package-lock.json`);if(g(t))try{let e=await C(t,`utf8`),n=JSON.parse(e).packageManager?.trim().toLowerCase().split(`@`)[0];if(n===`pnpm`)return`pnpm`;if(n===`npm`)return`npm`}catch{}return g(n)?`pnpm`:g(r)?`npm`:`pnpm`}function Z(e){return b(ue(),`registry-${e}.json`)}async function pe(e){let t=Z(e);try{let e=await C(t,`utf8`);return JSON.parse(e)}catch{return null}}async function me(e,t){let n=Z(e);await S(_(n),{recursive:!0}),await w(n,JSON.stringify(t,null,2),`utf8`)}function Q(e,t,n){if(t instanceof Y)return t;if(t instanceof DOMException&&t.name===`AbortError`)return new Y(`timeout`,e,`Registry fetch timed out after 10000ms: ${e}`,n);let r=t instanceof Error?t.message:String(t);if(r.includes(`ENOTFOUND`)||r.includes(`getaddrinfo`))return new Y(`dns_failure`,e,`DNS resolution failed for registry URL: ${e}`,n);if(r.includes(`ECONNREFUSED`))return new Y(`connection_refused`,e,`Connection refused by registry server: ${e}`,n);if(r.includes(`CERT_`)||r.includes(`certificate`)||r.includes(`SSL`))return new Y(`tls_error`,e,`TLS/certificate error when connecting to registry: ${e}`,n);let i=r.match(/HTTP\s+(\d+)/i);return i?new Y(`http_error`,e,r,n,Number(i[1])):new Y(`fetch_failed`,e,r,n)}function he(e){return{success:!1,error:e.code,message:e.message,url:e.url,...typeof e.status==`number`?{status:e.status}:{}}}async function $(t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),1e4),a=n?.cacheKey?Z(n.cacheKey):void 0;try{let i=await fetch(t,{signal:r.signal});if(!i.ok)throw new Y(`http_error`,t,`HTTP ${i.status} ${i.statusText} from ${t}`,a,i.status);let o=await i.json();if(n?.cacheKey)try{await me(n.cacheKey,o)}catch(r){e.warn(`[extensions] Failed to persist ${n.cacheKey} registry cache for ${t}:`,r)}return{data:o,stale:!1,source:`network`,cachePath:a}}catch(r){let i=Q(t,r,a);if(n?.cacheKey){let r=await pe(n.cacheKey);if(r)return e.warn(`[extensions] Using stale ${n.cacheKey} registry cache after ${i.code}: ${t}`),{data:r,stale:!0,source:`cache`,cachePath:a}}throw i}finally{clearTimeout(i)}}async function ge(t){let n=b(t,`package.json`);try{let r=await C(n,`utf8`),i=JSON.parse(r),a=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`],o=`file:${y(t,le).replace(/\\/g,`/`)||`.`}`,s=!1;for(let e of a){let t=i[e];if(!t||typeof t!=`object`)continue;let n=t,r=n[J];typeof r==`string`&&r.startsWith(`workspace:`)&&(n[J]=o,s=!0)}return s?(await w(n,`${JSON.stringify(i,null,2)}\n`,`utf8`),e.info(`[extensions] Rewrote ${J} dependency to local file path for ${t}`),!0):!1}catch(n){return e.warn(`[extensions] Failed to rewrite ${J} dependency for ${t}:`,n),!1}}async function _e(e,t){let[n,r]=await Promise.allSettled([$(`${e}/workflows.index.json`,{cacheKey:`workflows`}),$(`${e}/plugins.index.json`,{cacheKey:`plugins`})]);if(n.status===`fulfilled`){let e=(Array.isArray(n.value.data.workflows)?n.value.data.workflows:[]).find(e=>e.slug===t);if(e)return{entry:e,kind:`workflow`}}if(r.status===`fulfilled`){let e=(Array.isArray(r.value.data.plugins)?r.value.data.plugins:[]).find(e=>e.slug===t);if(e)return{entry:e,kind:`plugin`}}let i=n.status===`rejected`?n.reason instanceof Error?n.reason:Error(String(n.reason)):void 0,a=r.status===`rejected`?r.reason instanceof Error?r.reason:Error(String(r.reason)):void 0;throw Error(i&&a?`Failed to resolve extension slug "${t}": workflow registry error: ${i.message}; plugin registry error: ${a.message}`:a?`Extension "${t}" was not found in workflow registry, and plugin registry lookup failed: ${a.message}`:i?`Extension "${t}" was not found in plugin registry, and workflow registry lookup failed: ${i.message}`:`Extension "${t}" not found in workflow or plugin registry`)}var ve=class{ctx;constructor(e){this.ctx=e}async handleListExtensions(){try{return c({success:!0,...this.ctx.listExtensions()})}catch(t){return e.error(`Failed to list extensions:`,t),c(s(t))}}async handleReloadExtensions(){try{return c({success:!0,...await this.ctx.reloadExtensions()})}catch(t){return e.error(`Failed to reload extensions:`,t),c(s(t))}}async handleBrowseExtensionRegistry(t){try{let e=U(),n=t===`all`||t===`plugin`,r=t===`all`||t===`workflow`,i={success:!0},a=!1,o=n?$(`${e}/plugins.index.json`,{cacheKey:`plugins`}):void 0,s=r?$(`${e}/workflows.index.json`,{cacheKey:`workflows`}):void 0,[l,u]=await Promise.all([o??Promise.resolve(void 0),s??Promise.resolve(void 0)]);if(l){let e=Array.isArray(l.data.plugins)?l.data.plugins:[];i.plugins=e.map(e=>({slug:e.slug,id:e.id,name:e.meta.name,description:e.meta.description,author:e.meta.author,repo:e.source.repo,commit:e.source.commit,entry:e.source.entry})),i.pluginCount=e.length,i.pluginSource=l.source,a||=l.stale}if(u){let e=Array.isArray(u.data.workflows)?u.data.workflows:[];i.workflows=e.map(e=>({slug:e.slug,id:e.id,name:e.meta.name,description:e.meta.description,author:e.meta.author,repo:e.source.repo,commit:e.source.commit,entry:e.source.entry})),i.workflowCount=e.length,i.workflowSource=u.source,a||=u.stale}return a&&(i.stale=!0),c(i)}catch(t){return e.error(`Failed to browse extension registry:`,t),t instanceof Y?c(he(t)):c(s(t))}}async handleInstallExtension(t,i){try{let{entry:e,kind:a}=await _e(U(),t),o=a===`workflow`,s=H(o?`workflow`:`plugin`),l=i?b(i):b(s,t),u=K(l,e.source.subpath);if(q(u,e.source.entry),g(l))return c({success:!1,error:`Target directory already exists: ${l}`,hint:`Remove the existing directory first, or specify a different targetDir`});if(await S(_(l),{recursive:!0}),await B(`git`,[`clone`,e.source.repo,l],{timeout:r}),await B(`git`,[`-C`,l,`checkout`,e.source.commit],{timeout:n}),g(b(u,`package.json`))){await ge(u);let e=await fe(u);await X(e,e===`pnpm`?[`--ignore-workspace`,`install`,`--no-frozen-lockfile`,`--ignore-scripts`]:[`install`,`--ignore-scripts`],{cwd:u,timeout:Math.max(r,12e4)}),await X(e,e===`pnpm`?[`--ignore-workspace`,`run`,`--if-present`,`build`]:[`run`,`build`,`--if-present`],{cwd:u,timeout:Math.max(r,12e4)})}let d=se(u,e.source.entry),f=q(u,d);if(!g(f))return c({success:!1,error:`Installed extension entry not found: ${d}`,installDir:l,projectDir:u,expectedEntryFile:f,hint:`The registry source.entry or its compiled JS output must exist after clone/build before reloadExtensions can load it.`});let p=await ce(o?`workflow`:`plugin`,e,u,d),m=await this.ctx.reloadExtensions();return c({success:!0,installed:{slug:e.slug,id:e.id,name:e.meta.name,repo:e.source.repo,commit:e.source.commit,installDir:l,projectDir:u,entry:d,entryFile:f,metadataPath:p},reload:{addedTools:m.addedTools,pluginCount:m.pluginCount,workflowCount:m.workflowCount,errors:m.errors,warnings:m.warnings}})}catch(t){return e.error(`Failed to install extension:`,t),c(s(t))}}};export{ie as CoreMaintenanceHandlers,ve as ExtensionManagementHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./registry-DUHIPE-v.mjs";import{n as t}from"./bind-helpers-BlAOQrFQ.mjs";import{t as n}from"./tool-builder-CI9914Tf.mjs";const r=[n(`adb_apk_analyze`,e=>e.desc(`Analyze an installed APK: package, permissions, activities, and security info.`).string(`serial`,`Required. Android device serial or emulator id.`).string(`packageName`,`Required. Android package name, for example com.example.app.`).requiredOpenWorld(`serial`,`packageName`)),n(`adb_webview_list`,e=>e.desc(`List debuggable WebView targets connected via ADB.`).string(`serial`,`Required. Android device serial or emulator id.`).number(`hostPort`,`Optional. Local port to use for forwarding.`,{default:9222}).requiredOpenWorld(`serial`)),n(`adb_webview_attach`,e=>e.desc(`Attach to a WebView via ADB; returns WebSocket debugger URL for CDP.`).string(`serial`,`Required. Android device serial or emulator id.`).string(`targetId`,`Required. WebView target id returned by adb_webview_list.`).number(`hostPort`,`Optional. Local port to use for forwarding.`,{default:9222}).requiredOpenWorld(`serial`,`targetId`))],i=`adb-bridge`,a=`adbBridgeHandlers`,o=t({domain:i,depKey:a,lookup:e(r),entries:[{tool:`adb_apk_analyze`,method:`handleAnalyzeApk`},{tool:`adb_webview_list`,method:`handleWebViewList`},{tool:`adb_webview_attach`,method:`handleWebViewAttach`}]});async function s(e){let{ADBBridgeHandlers:t}=await import(`./handlers-S9Ws0IGy.mjs`),n=e.getDomainInstance(a);if(n)return n;let r=new t;return e.setDomainInstance(a,r),r}const c={kind:`domain-manifest`,version:1,domain:i,depKey:a,profiles:[`full`],registrations:o,ensure:s,workflowRule:{patterns:[/(android|adb|mobile|apk|device).*(list|shell|pull|analyze|dump)/i,/(adb|android).*(webview|chrome|debug|cdp|inspect)/i],priority:75,tools:[`adb_apk_analyze`,`adb_webview_list`,`adb_webview_attach`],hint:`Android/ADB: list devices → run shell commands → pull/analyze APK → debug WebViews via CDP`},prerequisites:{"*":[{condition:`ADB server binary must be in PATH`,fix:`Install Android Platform Tools: https://developer.android.com/studio/command-line/adb`}],adb_webview_list:[{condition:`App must have android:debuggable="true"`,fix:`Use a debug build of the Android app`}],adb_webview_attach:[{condition:`App must have android:debuggable="true"`,fix:`Use a debug build of the Android app`}]},toolDependencies:[{from:`browser`,to:`adb-bridge`,relation:`uses`,weight:.7}]};export{c as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./registry-DUHIPE-v.mjs";import{n as t}from"./bind-helpers-BlAOQrFQ.mjs";import{t as n}from"./definitions-OvGsfxdt.mjs";const r=`process`,i=`processHandlers`,a=e(n),o=process.env.JSHOOK_REGISTRY_PLATFORM===`win32`||process.env.JSHOOK_REGISTRY_PLATFORM===`linux`||process.env.JSHOOK_REGISTRY_PLATFORM===`darwin`?process.env.JSHOOK_REGISTRY_PLATFORM:process.platform;async function s(e){let{ProcessToolHandlers:t}=await import(`./process-C9f2A5zk.mjs`);return e.processHandlers||=new t,e.processHandlers}const c=o===`win32`,l=new Set([`check_debug_port`]),u=t({domain:r,depKey:i,lookup:a,entries:[{tool:`electron_attach`,method:`handleElectronAttach`},{tool:`process_windows`,method:`handleProcessWindows`},{tool:`process_check_debug_port`,method:`handleProcessCheckDebugPort`},{tool:`process_launch_debug`,method:`handleProcessLaunchDebug`},{tool:`memory_read`,method:`handleMemoryRead`},{tool:`memory_write`,method:`handleMemoryWrite`},{tool:`memory_scan`,method:`handleMemoryScan`},{tool:`memory_check_protection`,method:`handleMemoryCheckProtection`},{tool:`memory_scan_filtered`,method:`handleMemoryScanFiltered`},{tool:`memory_batch_write`,method:`handleMemoryBatchWrite`},{tool:`memory_dump_region`,method:`handleMemoryDumpRegion`},{tool:`memory_list_regions`,method:`handleMemoryListRegions`},{tool:`memory_audit_export`,method:`handleMemoryAuditExport`},{tool:`inject_dll`,method:`handleInjectDll`},{tool:`inject_shellcode`,method:`handleInjectShellcode`},{tool:`check_debug_port`,method:`handleCheckDebugPort`},{tool:`enumerate_modules`,method:`handleEnumerateModules`}]}),d={kind:`domain-manifest`,version:1,domain:r,depKey:i,profiles:[`full`],ensure:s,registrations:c?u:u.filter(e=>!l.has(e.tool.name))};export{d as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./registry-DUHIPE-v.mjs";import{n as t}from"./bind-helpers-BlAOQrFQ.mjs";import{t as n}from"./tool-builder-CI9914Tf.mjs";const r=[n(`binary_instrument_capabilities`,e=>e.desc(`Report binary instrumentation backend availability.`).query()),n(`frida_attach`,e=>e.desc(`Attach Frida to a local target and open a session.`).string(`target`,`Process name, PID, or binary path to attach to`).required(`target`)),n(`frida_enumerate_modules`,e=>e.desc(`List loaded modules in an attached Frida session.`).string(`sessionId`,`Session id returned by frida_attach`).required(`sessionId`).query()),n(`ghidra_analyze`,e=>e.desc(`Analyze a binary and return metadata.`).string(`binaryPath`,`Path to the binary file`).number(`timeout`,`Optional timeout in milliseconds for headless analysis`).required(`binaryPath`)),n(`generate_hooks`,e=>e.desc(`Generate a Frida interceptor script for a list of symbols.`).array(`symbols`,{type:`string`},`Symbol names to hook`).object(`options`,{includeArgs:{type:`boolean`,description:`Emit argument logging on function entry`},includeRetAddr:{type:`boolean`,description:`Emit return-address logging on function entry`}},`Optional Frida hook generation flags`).required(`symbols`)),n(`unidbg_emulate`,e=>e.desc(`Emulate a native function with Unidbg when available.`).string(`binaryPath`,`Path to the binary file`).string(`functionName`,`Function name to emulate`).array(`args`,{type:`string`},`Optional string arguments forwarded to emulation`).required(`binaryPath`,`functionName`)),n(`frida_run_script`,e=>e.desc(`Execute a Frida JavaScript snippet inside an attached Frida session.`).string(`sessionId`,`Session id returned by frida_attach`).string(`script`,`Frida JavaScript to execute`).required(`sessionId`,`script`)),n(`frida_detach`,e=>e.desc(`Detach from a Frida session and clean up resources.`).string(`sessionId`,`Session id returned by frida_attach`).required(`sessionId`)),n(`frida_list_sessions`,e=>e.desc(`List all active Frida attach sessions with target info.`).query()),n(`frida_generate_script`,e=>e.desc(`Generate a Frida interceptor or hook script from built-in templates.`).string(`target`,`Target binary or module name`).string(`template`,`Hook template type: trace, intercept, replace, log`).string(`functionName`,`Function name to generate hook for`).required(`target`,`template`)),n(`get_available_plugins`,e=>e.desc(`List installed binary analysis plugins.`).query()),n(`ghidra_decompile`,e=>e.desc(`Decompile a function using Ghidra.`).string(`binaryPath`,`Path to the binary file`).string(`functionName`,`Function name to decompile`).required(`binaryPath`,`functionName`)),n(`ida_decompile`,e=>e.desc(`Decompile a function using IDA Pro.`).string(`binaryPath`,`Path to the binary file`).string(`functionName`,`Function name to decompile`).required(`binaryPath`,`functionName`)),n(`jadx_decompile`,e=>e.desc(`Decompile an APK class or method using JADX.`).string(`apkPath`,`Path to the APK file`).string(`className`,`Fully qualified class name`).string(`methodName`,`Method name to decompile`).required(`apkPath`,`className`)),n(`unidbg_launch`,e=>e.desc(`Emulate a native shared library in Unidbg.`).string(`soPath`,`Path to the .so library file`).string(`arch`,`Architecture: arm or arm64`).required(`soPath`)),n(`unidbg_call`,e=>e.desc(`Call a JNI function in a running Unidbg emulator session.`).string(`sessionId`,`Session id from unidbg_launch`).string(`functionName`,`JNI function name to call`).required(`sessionId`,`functionName`)),n(`unidbg_trace`,e=>e.desc(`Get execution trace from Unidbg session with configurable detail.`).string(`sessionId`,`Session id from unidbg_launch`).required(`sessionId`)),n(`export_hook_script`,e=>e.desc(`Export generated hook templates as a complete, runnable Frida script.`).string(`hookTemplates`,`JSON array of hook template objects`)),n(`frida_enumerate_functions`,e=>e.desc(`Enumerate exported functions for a specific module in a Frida session.`).string(`sessionId`,`Session id returned by frida_attach`).string(`moduleName`,`Module name to enumerate exports from`).required(`sessionId`,`moduleName`).query()),n(`frida_find_symbols`,e=>e.desc(`Search for symbols matching a pattern in a Frida session.`).string(`sessionId`,`Session id returned by frida_attach`).string(`pattern`,`Symbol search pattern (e.g. "exports:*libssl*SSL*")`).required(`sessionId`,`pattern`).query())],i=`binary-instrument`,a=`binaryInstrumentHandlers`,o=t({domain:i,depKey:a,lookup:e(r),entries:[{tool:`binary_instrument_capabilities`,method:`handleBinaryInstrumentCapabilities`},{tool:`frida_attach`,method:`handleFridaAttach`},{tool:`frida_enumerate_modules`,method:`handleFridaEnumerateModules`},{tool:`ghidra_analyze`,method:`handleGhidraAnalyze`},{tool:`generate_hooks`,method:`handleGenerateHooks`},{tool:`unidbg_emulate`,method:`handleUnidbgEmulate`},{tool:`frida_run_script`,method:`handleFridaRunScript`},{tool:`frida_detach`,method:`handleFridaDetach`},{tool:`frida_list_sessions`,method:`handleFridaListSessions`},{tool:`frida_generate_script`,method:`handleFridaGenerateScript`},{tool:`get_available_plugins`,method:`handleGetAvailablePlugins`},{tool:`ghidra_decompile`,method:`handleGhidraDecompile`},{tool:`ida_decompile`,method:`handleIdaDecompile`},{tool:`jadx_decompile`,method:`handleJadxDecompile`},{tool:`unidbg_launch`,method:`handleUnidbgLaunch`},{tool:`unidbg_call`,method:`handleUnidbgCall`},{tool:`unidbg_trace`,method:`handleUnidbgTrace`},{tool:`export_hook_script`,method:`handleExportHookScript`},{tool:`frida_enumerate_functions`,method:`handleFridaEnumerateFunctions`},{tool:`frida_find_symbols`,method:`handleFridaFindSymbols`}]});async function s(e){let{BinaryInstrumentHandlers:t}=await import(`./handlers-D3iev8g1.mjs`),{GhidraAnalyzer:n,HookGenerator:r}=await import(`./binary-instrument-Cf9qqLlM.mjs`).then(e=>e.t),i=e.getDomainInstance(a);return i||(i=new t(e,new n,new r),e.setDomainInstance(a,i)),i}const c={kind:`domain-manifest`,version:1,domain:i,depKey:a,profiles:[`full`],ensure:s,registrations:o,workflowRule:{patterns:[/\b(frida|ghidra|ida|unidbg|jadx|binary|disassemb|decompil|dump\s?so)\b/i,/(binary|native|so|dll|elf|apk).*(analyze|hook|instrument|decompile)/i],priority:88,tools:[`frida_attach`,`ghidra_analyze`,`generate_hooks`,`unidbg_launch`],hint:`Binary analysis pipeline: attach Frida → decompile (Ghidra/IDA/JADX) → generate hook scripts → emulatewith Unidbg.`},prerequisites:{frida_attach:[{condition:`plugin_frida_bridge must be installed and frida-server reachable`,fix:`Install @jshookmcpextension/plugin-frida-bridge; launch frida-server on the target`}],frida_run_script:[{condition:`A Frida session must be active`,fix:`Call frida_attach before running a script`}],ghidra_analyze:[{condition:`plugin_ghidra_bridge must be installed with Ghidra headless available`,fix:`Install @jshookmcpextension/plugin-ghidra-bridge and configure Ghidra path`}],ida_decompile:[{condition:`plugin_ida_bridge must be installed`,fix:`Install @jshookmcpextension/plugin-ida-bridge and provide IDA Pro license`}],jadx_decompile:[{condition:`plugin_jadx_bridge must be installed`,fix:`Install @jshookmcpextension/plugin-jadx-bridge`}],unidbg_launch:[{condition:`Java 17+ and unidbg JAR must be reachable`,fix:`Install JDK 17+ and download unidbg from its official release`}],generate_hooks:[{condition:`Ghidra analysis output required`,fix:`Run ghidra_analyze first and pass the output to generate_hooks`}]},toolDependencies:[{from:`process`,to:`binary-instrument`,relation:`uses`,weight:.6}]};export{c as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./registry-DUHIPE-v.mjs";import{n as t}from"./bind-helpers-BlAOQrFQ.mjs";import{t as n}from"./definitions-Dds_zrWx.mjs";const r=`transform`,i=`transformHandlers`,a=t({domain:r,depKey:i,lookup:e(n),entries:[{tool:`ast_transform_preview`,method:`handleAstTransformPreview`},{tool:`ast_transform_chain`,method:`handleAstTransformChain`},{tool:`ast_transform_apply`,method:`handleAstTransformApply`},{tool:`crypto_extract_standalone`,method:`handleCryptoExtractStandalone`},{tool:`crypto_test_harness`,method:`handleCryptoTestHarness`},{tool:`crypto_compare`,method:`handleCryptoCompare`}]});async function o(e){let{CodeCollector:t}=await import(`./collector-CKO8RPK8.mjs`),{TransformToolHandlers:n}=await import(`./transform-Cv9P2vVD.mjs`);return e.collector||(e.collector=new t(e.config.puppeteer),e.registerCaches()),e.transformHandlers||=new n(e.collector),e.transformHandlers}const s={kind:`domain-manifest`,version:1,domain:r,depKey:i,profiles:[`full`],ensure:o,registrations:a};export{s as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./EventBus-DgciURGg.mjs";import{t}from"./tool-builder-CI9914Tf.mjs";const n=[`byte`,`int8`,`int16`,`uint16`,`int32`,`uint32`,`int64`,`uint64`,`float`,`double`,`string`,`hex`,`pointer`],r=[`exact`,`unknown_initial`,`changed`,`unchanged`,`increased`,`decreased`,`greater_than`,`less_than`,`between`,`not_equal`],i=[t(`memory_first_scan`,e=>e.desc(`Start a new memory scan session.`).number(`pid`,`Target process ID`).string(`value`,`Value to search for (as string, e.g. "100", "3.14", "48 65 6C 6C 6F")`).enum(`valueType`,[...n],`Data type of the value`).number(`alignment`,`Alignment in bytes (0=unaligned, 4=4-byte aligned). Default: natural alignment for the type.`).number(`maxResults`,`Maximum results to return (default: 1,000,000)`).prop(`regionFilter`,{type:`object`,properties:{writable:{type:`boolean`,description:`Only scan writable regions`},executable:{type:`boolean`,description:`Only scan executable regions`},moduleOnly:{type:`boolean`,description:`Only scan module-backed regions`}},description:`Filter which memory regions to scan`}).requiredOpenWorld(`pid`,`value`,`valueType`)),t(`memory_next_scan`,e=>e.desc(`Narrow an existing scan session.`).string(`sessionId`,`Scan session ID`).enum(`mode`,[...r],`Comparison mode`).string(`value`,`Target value for exact/greater_than/less_than/between/not_equal modes`).string(`value2`,`Upper bound value for "between" mode`).requiredOpenWorld(`sessionId`,`mode`)),t(`memory_unknown_scan`,e=>e.desc(`Start an unknown initial value scan.`).number(`pid`,`Target process ID`).enum(`valueType`,[...n],`Data type to capture`).number(`alignment`,`Alignment in bytes (default: natural for type)`).number(`maxResults`,`Maximum addresses to capture (default: 5,000,000)`).prop(`regionFilter`,{type:`object`,properties:{writable:{type:`boolean`},executable:{type:`boolean`},moduleOnly:{type:`boolean`}}}).requiredOpenWorld(`pid`,`valueType`)),t(`memory_pointer_scan`,e=>e.desc(`Find pointers to a target address.`).number(`pid`,`Target process ID`).string(`targetAddress`,`Target address to find pointers to (hex, e.g. "0x7FF612340000")`).number(`maxResults`,`Maximum results (default: 10,000)`).boolean(`moduleOnly`,`Only scan module-backed regions`).required(`pid`,`targetAddress`).query().openWorld()),t(`memory_group_scan`,e=>e.desc(`Search for multiple values at known offsets simultaneously.`).number(`pid`,`Target process ID`).array(`pattern`,{type:`object`,properties:{offset:{type:`number`,description:`Byte offset from base`},value:{type:`string`,description:`Expected value at offset`},type:{type:`string`,enum:[...n],description:`Value type at offset`}},required:[`offset`,`value`,`type`]},`Array of {offset, value, type} patterns`).number(`alignment`,`Alignment for base address (default: 4)`).number(`maxResults`,`Maximum results (default: 1,000,000)`).required(`pid`,`pattern`).query()),t(`memory_scan_session`,e=>e.desc(`Manage scan sessions. Actions: list (all sessions), delete (by sessionId), export (as JSON).`).enum(`action`,[`list`,`delete`,`export`],`Session management action`).string(`sessionId`,`Scan session ID (required for delete/export)`).required(`action`)),t(`memory_pointer_chain`,e=>e.desc(`Pointer chain operations: scan (find chains to target), validate, resolve, or export as JSON.`).enum(`action`,[`scan`,`validate`,`resolve`,`export`],`Chain operation`).number(`pid`,`Target process ID`).string(`targetAddress`,`Target address hex (action=scan)`).number(`maxDepth`,`Max chain depth 1-6 (action=scan, default: 4)`).number(`maxOffset`,`Max offset per level in bytes (action=scan, default: 4096)`).boolean(`staticOnly`,`Only module-relative chains (action=scan, default: false)`).array(`modules`,{type:`string`},`Only scan specific modules (action=scan)`).number(`maxResults`,`Max chains to return (action=scan, default: 1000)`).string(`chains`,`JSON PointerChain[] (action=validate/export)`).string(`chain`,`JSON single PointerChain (action=resolve)`).required(`action`)),t(`memory_structure_analyze`,e=>e.desc(`Analyze memory at an address to infer data structure layout.`).number(`pid`,`Target process ID`).string(`address`,`Base address of the structure (hex)`).number(`size`,`Size to analyze in bytes (default: 256)`).array(`otherInstances`,{type:`string`},`Additional instance addresses for cross-comparison`).boolean(`parseRtti`,`Whether to attempt RTTI parsing (default: true)`).required(`pid`,`address`).query()),t(`memory_vtable_parse`,e=>e.desc(`Parse a vtable to enumerate virtual function pointers and resolve them to module+offset. Also attempts RTTI parsing for class name and inheritance hierarchy.`).number(`pid`,`Target process ID`).string(`vtableAddress`,`Address of the vtable (hex)`).required(`pid`,`vtableAddress`).query()),t(`memory_structure_export_c`,e=>e.desc(`Export an inferred structure as a C-style struct definition with offset comments and type annotations.`).string(`structure`,`JSON string of InferredStruct to export`).string(`name`,`Struct name (defaults to RTTI class name or "UnknownStruct")`).required(`structure`).query()),t(`memory_structure_compare`,e=>e.desc(`Compare two structure instances to identify which fields differ (dynamic values like health/position) vs which are constant (vtable, type flags). Useful for finding important fields.`).number(`pid`,`Target process ID`).string(`address1`,`First instance address (hex)`).string(`address2`,`Second instance address (hex)`).number(`size`,`Size to compare in bytes (default: 256)`).required(`pid`,`address1`,`address2`).query()),t(`memory_breakpoint`,e=>e.desc(`Hardware breakpoint via x64 debug registers (DR0-DR3). Actions: set, remove, list, trace.`).enum(`action`,[`set`,`remove`,`list`,`trace`],`Breakpoint operation`).number(`pid`,`Target process ID (action=set/trace)`).string(`address`,`Address hex (action=set/trace)`).enum(`access`,[`read`,`write`,`readwrite`,`execute`],`Access type (action=set/trace)`).number(`size`,`Watch size in bytes (action=set, default: 4)`).string(`breakpointId`,`Breakpoint ID (action=remove)`).number(`maxHits`,`Max hits to collect (action=trace, default: 50)`).number(`timeoutMs`,`Timeout ms (action=trace, default: 10000)`).required(`action`).destructive()),t(`memory_patch_bytes`,e=>e.desc(`Write bytes to target process at address. Saves original bytes for undo. Use for runtime code patching.`).number(`pid`,`Target process ID`).string(`address`,`Address to patch (hex)`).array(`bytes`,{type:`number`},`Byte values to write (e.g. [0x90, 0x90])`).required(`pid`,`address`,`bytes`).destructive().openWorld()),t(`memory_patch_nop`,e=>e.desc(`NOP out instructions at address (replace with 0x90). Useful for disabling checks or jumps.`).number(`pid`,`Target process ID`).string(`address`,`Address to NOP (hex)`).number(`count`,`Number of bytes to NOP`).required(`pid`,`address`,`count`).destructive()),t(`memory_patch_undo`,e=>e.desc(`Undo a previous patch by restoring the original bytes.`).string(`patchId`,`Patch ID to undo`).required(`patchId`).destructive()),t(`memory_code_caves`,e=>e.desc(`Find code caves (runs of 0x00 or 0xCC) in executable sections of loaded modules. Returns largest caves first.`).number(`pid`,`Target process ID`).number(`minSize`,`Minimum cave size in bytes (default: 16)`).required(`pid`).query()),t(`memory_write_value`,e=>e.desc(`Write a typed value to a memory address. Supports undo/redo via memory_write_history(action=undo|redo).`).number(`pid`,`Target process ID`).string(`address`,`Address to write to (hex)`).string(`value`,`Value to write (as string)`).enum(`valueType`,[...n],`Data type of the value`).required(`pid`,`address`,`value`,`valueType`).destructive()),t(`memory_freeze`,e=>e.desc(`Freeze or unfreeze a memory address. Freeze continuously writes a value to prevent changes; unfreeze stops it.`).enum(`action`,[`freeze`,`unfreeze`],`Freeze operation`).number(`pid`,`Target process ID (action=freeze)`).string(`address`,`Address to freeze hex (action=freeze)`).string(`value`,`Value to maintain (action=freeze)`).enum(`valueType`,[...n],`Data type (action=freeze)`).number(`intervalMs`,`Write interval ms (action=freeze, default: 100)`).string(`freezeId`,`Freeze ID to remove (action=unfreeze)`).required(`action`).destructive()),t(`memory_dump`,e=>e.desc(`Dump memory region as hex with ASCII column. Outputs a formatted hex dump similar to xxd.`).number(`pid`,`Target process ID`).string(`address`,`Start address (hex)`).number(`size`,`Size to dump in bytes (default: 256)`).required(`pid`,`address`).query()),t(`memory_speedhack`,e=>e.desc(`Hook time APIs to scale process time. Actions: apply (hook + set speed), set (adjust speed).`).enum(`action`,[`apply`,`set`],`Speedhack action`).number(`pid`,`Target process ID`).number(`speed`,`Speed multiplier`).required(`action`,`pid`,`speed`).destructive()),t(`memory_write_history`,e=>e.desc(`Undo or redo the last memory write operation.`).enum(`action`,[`undo`,`redo`],`History action`).required(`action`).destructive().openWorld()),t(`memory_heap_enumerate`,e=>e.desc(`Enumerate all heaps and heap blocks in a process via Toolhelp32 snapshot. Returns heap list with block counts, sizes, and overall statistics.`).number(`pid`,`Target process ID`).number(`maxBlocks`,`Maximum blocks to enumerate per heap (default: 10000)`).required(`pid`).query()),t(`memory_heap_stats`,e=>e.desc(`Get detailed heap statistics with size distribution buckets (0-64B, 64B-1KB, 1-64KB, 64KB-1MB, >1MB), fragmentation ratio, and aggregate metrics.`).number(`pid`,`Target process ID`).required(`pid`).query()),t(`memory_heap_anomalies`,e=>e.desc(`Detect heap anomalies: heap spray patterns (many same-size blocks), possible use-after-free (non-zero free blocks), and suspicious block sizes (0 or >100MB).`).number(`pid`,`Target process ID`).required(`pid`).query()),t(`memory_pe_headers`,e=>e.desc(`Parse PE headers (DOS, NT, File, Optional) from a module base address in process memory. Returns machine type, entry point, image base, section count, and data directory info.`).number(`pid`,`Target process ID`).string(`moduleBase`,`Module base address (hex, e.g. "0x7ff612340000")`).required(`pid`,`moduleBase`).query()),t(`memory_pe_imports_exports`,e=>e.desc(`Parse import and/or export tables from a PE module in process memory. Returns DLL names, function names, ordinals, hints, and forwarded exports.`).number(`pid`,`Target process ID`).string(`moduleBase`,`Module base address (hex)`).enum(`table`,[`imports`,`exports`,`both`],`Which table to parse`,{default:`both`}).required(`pid`,`moduleBase`).query()),t(`memory_inline_hook_detect`,e=>e.desc(`Detect inline hooks by comparing the first 16 bytes of each exported function on disk vs in memory. Identifies JMP rel32, JMP abs64, PUSH+RET hooks and decodes jump targets.`).number(`pid`,`Target process ID`).string(`moduleName`,`Module name filter (optional — scans all modules if omitted)`).required(`pid`).query()),t(`memory_anticheat_detect`,e=>e.desc(`Scan process imports for anti-debug/anti-cheat mechanisms: IsDebuggerPresent, NtQueryInformationProcess, timing checks (QPC, GetTickCount), thread hiding, heap flag checks, and DR register inspection. Each detection includes a bypass suggestion.`).number(`pid`,`Target process ID`).required(`pid`).query()),t(`memory_guard_pages`,e=>e.desc(`Find all memory regions with PAGE_GUARD protection in a process. Guard pages are often used as anti-tampering mechanisms or stack overflow detection.`).number(`pid`,`Target process ID`).required(`pid`).query()),t(`memory_integrity_check`,e=>e.desc(`Check executable memory regions against their corresponding on-disk PE files (.text sections) to detect modifications like inline hooks or code patches.`).number(`pid`,`Target process ID`).required(`pid`).query())],a=`memory`,o=`memoryScanHandlers`,s=(process.env.JSHOOK_REGISTRY_PLATFORM===`win32`||process.env.JSHOOK_REGISTRY_PLATFORM===`linux`||process.env.JSHOOK_REGISTRY_PLATFORM===`darwin`?process.env.JSHOOK_REGISTRY_PLATFORM:process.platform)===`win32`;let c=null;async function l(e){let{MemoryScanHandlers:t}=await import(`./handlers.impl-CD2_kOcC.mjs`);c=e;let n=e;if(n[o])return n[o];let[r,i,a,l,u,d]=await Promise.all([import(`./MemoryScanner-BLYnMJy6.mjs`),import(`./MemoryScanSession-CaxAjZJf.mjs`),import(`./PointerChainEngine-5nF9eNlu.mjs`),import(`./StructureAnalyzer-A-WamfYE.mjs`),import(`./CodeInjector-BlgyqTOk.mjs`),import(`./MemoryController-BaqstM5w.mjs`)]);if(s){let[s,c,f,p,m]=await Promise.all([import(`./HardwareBreakpoint-OcJqNFVc.mjs`),import(`./Speedhack-l6s8L2Qw.mjs`),import(`./HeapAnalyzer-CqAxZzeS.mjs`),import(`./PEAnalyzer-DJyaJTQJ.mjs`),import(`./AntiCheatDetector-CGVGNfy5.mjs`)]);n[o]=new t(r.memoryScanner,i.scanSessionManager,a.pointerChainEngine,l.structureAnalyzer,s.hardwareBreakpointEngine,u.codeInjector,d.memoryController,c.speedhack,f.heapAnalyzer,p.peAnalyzer,m.antiCheatDetector,e.eventBus)}else n[o]=new t(r.memoryScanner,i.scanSessionManager,a.pointerChainEngine,l.structureAnalyzer,null,u.codeInjector,d.memoryController,null,null,null,null,e.eventBus);return n[o]}function u(t){return n=>{let r=n[o];return n=>{let i=n._meta,a;return i?.progressToken!==void 0&&c&&(a=e(c.eventBus,i.progressToken)),t(r,{...n,onProgress:a})}}}function d(e){let t=i.find(t=>t.name===e);if(!t)throw Error(`Memory tool not found: ${e}`);return t}const f=new Set([`memory_heap_enumerate`,`memory_heap_stats`,`memory_heap_anomalies`,`memory_pe_headers`,`memory_pe_imports_exports`,`memory_inline_hook_detect`,`memory_anticheat_detect`,`memory_guard_pages`,`memory_integrity_check`,`memory_breakpoint`,`memory_speedhack`]),p=[{tool:d(`memory_first_scan`),domain:a,bind:u((e,t)=>e.handleFirstScan(t))},{tool:d(`memory_next_scan`),domain:a,bind:u((e,t)=>e.handleNextScan(t))},{tool:d(`memory_unknown_scan`),domain:a,bind:u((e,t)=>e.handleUnknownScan(t))},{tool:d(`memory_pointer_scan`),domain:a,bind:u((e,t)=>e.handlePointerScan(t))},{tool:d(`memory_group_scan`),domain:a,bind:u((e,t)=>e.handleGroupScan(t))},{tool:d(`memory_scan_session`),domain:a,bind:u((e,t)=>e.handleScanSessionDispatch(t))},{tool:d(`memory_pointer_chain`),domain:a,bind:u((e,t)=>e.handlePointerChainDispatch(t))},{tool:d(`memory_structure_analyze`),domain:a,bind:u((e,t)=>e.handleStructureAnalyze(t))},{tool:d(`memory_vtable_parse`),domain:a,bind:u((e,t)=>e.handleVtableParse(t))},{tool:d(`memory_structure_export_c`),domain:a,bind:u((e,t)=>e.handleStructureExportC(t))},{tool:d(`memory_structure_compare`),domain:a,bind:u((e,t)=>e.handleStructureCompare(t))},{tool:d(`memory_breakpoint`),domain:a,bind:u((e,t)=>e.handleBreakpointDispatch(t))},{tool:d(`memory_patch_bytes`),domain:a,bind:u((e,t)=>e.handlePatchBytes(t))},{tool:d(`memory_patch_nop`),domain:a,bind:u((e,t)=>e.handlePatchNop(t))},{tool:d(`memory_patch_undo`),domain:a,bind:u((e,t)=>e.handlePatchUndo(t))},{tool:d(`memory_code_caves`),domain:a,bind:u((e,t)=>e.handleCodeCaves(t))},{tool:d(`memory_write_value`),domain:a,bind:u((e,t)=>e.handleWriteValue(t))},{tool:d(`memory_freeze`),domain:a,bind:u((e,t)=>e.handleFreezeDispatch(t))},{tool:d(`memory_dump`),domain:a,bind:u((e,t)=>e.handleDump(t))},{tool:d(`memory_speedhack`),domain:a,bind:u((e,t)=>e.handleSpeedhackDispatch(t))},{tool:d(`memory_write_history`),domain:a,bind:u((e,t)=>e.handleWriteHistoryDispatch(t))},{tool:d(`memory_heap_enumerate`),domain:a,bind:u((e,t)=>e.handleHeapEnumerate(t))},{tool:d(`memory_heap_stats`),domain:a,bind:u((e,t)=>e.handleHeapStats(t))},{tool:d(`memory_heap_anomalies`),domain:a,bind:u((e,t)=>e.handleHeapAnomalies(t))},{tool:d(`memory_pe_headers`),domain:a,bind:u((e,t)=>e.handlePEHeaders(t))},{tool:d(`memory_pe_imports_exports`),domain:a,bind:u((e,t)=>e.handlePEImportsExports(t))},{tool:d(`memory_inline_hook_detect`),domain:a,bind:u((e,t)=>e.handleInlineHookDetect(t))},{tool:d(`memory_anticheat_detect`),domain:a,bind:u((e,t)=>e.handleAntiCheatDetect(t))},{tool:d(`memory_guard_pages`),domain:a,bind:u((e,t)=>e.handleGuardPages(t))},{tool:d(`memory_integrity_check`),domain:a,bind:u((e,t)=>e.handleIntegrityCheck(t))}],m={kind:`domain-manifest`,version:1,domain:a,depKey:o,profiles:[`full`],ensure:l,registrations:s?p:p.filter(e=>!f.has(e.tool.name)),workflowRule:{patterns:[/memory\s*scan/i,/cheat\s*engine/i,/find\s*(value|address|variable|struct)/i,/scan\s*(for|memory)/i,/pointer\s*(chain|scan)/i,/struct(ure)?\s*(analy|infer|dissect)/i,/vtable|rtti/i,/breakpoint|watchpoint|hardware\s*bp/i,/patch\s*(byte|nop|code)/i,/code\s*cave/i,/freeze|unfreeze/i,/speedhack|time\s*(hack|scale)/i,/memory\s*(dump|hex)/i,/undo|redo/i,/heap|堆\s*(分析|枚举|异常)/i,/PE\s*(header|import|export)|inline.*hook/i,/anti.?cheat|anti.?debug|反作弊|反调试/i,/guard\s*page|integrity\s*check|代码完整性/i,/内存\s*(扫描|搜索|分析|结构|断点|注入|冻结|加速|堆|模块|反作弊)/i],priority:90,tools:[`memory_first_scan`,`memory_next_scan`,`memory_unknown_scan`,`memory_pointer_chain`,`memory_structure_analyze`,`memory_vtable_parse`,`memory_scan_session`,...s?[`memory_breakpoint`,`memory_speedhack`]:[],`memory_patch_bytes`,`memory_freeze`,`memory_dump`,...s?[`memory_speedhack`,`memory_heap_enumerate`,`memory_pe_headers`,`memory_anticheat_detect`]:[],`memory_write_history`],hint:s?`Memory domain: scan → narrow → pointer chain → structure | breakpoint trace → patch/NOP → freeze speedhack | heap analysis | PE introspection | anti-cheat detection`:`Memory domain: scan → narrow → pointer chain → structure | patch/NOP → freeze | dump`}};export{m as default};
|