@jshookmcp/jshook 0.3.3 → 0.3.4
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/README.md +19 -4
- package/README.zh.md +19 -4
- package/dist/AntiCheatDetector-B-mz4DK_.mjs +1 -0
- package/dist/{BrowserSessionCoordinator-QIt3tetp.mjs → BrowserSessionCoordinator-Cdic8FsH.mjs} +1 -1
- package/dist/CodeAnalyzerDataFlow-a-NkwcaG.mjs +2 -0
- package/dist/CodeInjector-B099WO6x.mjs +1 -0
- package/dist/ConsoleMonitor-BZRqrBH-.mjs +306 -0
- package/dist/CpuEngine-BC8jayy9.mjs +1 -0
- package/dist/DartAotExecutor-B7WVTKsd.mjs +1 -0
- package/dist/DartAotLoader-BxdhW-K2.mjs +2 -0
- package/dist/DarwinAPI-DzojdfjF.mjs +1 -0
- package/dist/{DetailedDataManager-Z77fDl9Z.mjs → DetailedDataManager-Dgh402Gp.mjs} +2 -2
- package/dist/ExecutionSandbox-QbWQmzuC.mjs +45 -0
- package/dist/ExtensionManager.tools-D3h818Xs.mjs +1 -0
- package/dist/FingerprintManager-D9Zlr6be.mjs +1 -0
- package/dist/HardwareBreakpoint-C_lJ22bj.mjs +1 -0
- package/dist/HeapAnalyzer-bJbLvzp6.mjs +1 -0
- package/dist/HookPatternScanner-yx4vJ9sd.mjs +1 -0
- package/dist/InstrumentationSession-Cv1wikLA.mjs +1 -0
- package/dist/IntegrityScanner-BB7sw-SA.mjs +1 -0
- package/dist/JScramblerDeobfuscator-NVR5VatT.mjs +1 -0
- package/dist/MCPServer.activation.ttl-C2wOCMLV.mjs +1 -0
- package/dist/MCPServer.search.helpers-DlassAew.mjs +2 -0
- package/dist/MemoryController-CCsGuGJS.mjs +2 -0
- package/dist/{MemoryScanSession-zfoVZJB0.mjs → MemoryScanSession-BZ2A9Ph1.mjs} +1 -1
- package/dist/MemoryScanner-DAxsq7Sx.mjs +1 -0
- package/dist/NativeMemoryManager.impl-BIJzXMqH.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-Bu8srMEF.mjs → NativeMemoryManager.utils-CMoul2an.mjs} +1 -1
- package/dist/PEAnalyzer-CB_kaTis.mjs +1 -0
- package/dist/PackerDeobfuscator-BpwGjxDL.mjs +7 -0
- package/dist/PointerChainEngine-B6SYv6ZM.mjs +1 -0
- package/dist/ProcessRegistry-C5W1Tkn9.mjs +1 -0
- package/dist/QuickJSSandbox-CIde-jzG.mjs +299 -0
- package/dist/{ResponseBuilder-nPXl_khE.mjs → ResponseBuilder-BLicSCjn.mjs} +1 -1
- package/dist/ReverseEvidenceGraph-DJzk0GQz.mjs +2 -0
- package/dist/ServerRuntimeState-DGXNv8Ji.mjs +1 -0
- package/dist/Speedhack-MGoeq1ZS.mjs +1 -0
- package/dist/StructureAnalyzer-CCTWAXR3.mjs +2 -0
- package/dist/ToolHandlerMap-C40EmuLT.mjs +1 -0
- package/dist/{ToolProbe-DQiREmNp.mjs → ToolProbe-B02GC3ZY.mjs} +1 -1
- package/dist/ToolRegistry-CzqQxFqf.mjs +1 -0
- package/dist/{ToolRouter.policy-UKBlFlbh.mjs → ToolRouter.policy-Bgb3S8jc.mjs} +2 -2
- package/dist/TraceRecorder-BfeCTQUj.mjs +407 -0
- package/dist/VMDeobfuscator-BHtkV850.mjs +1 -0
- package/dist/Win32API-G7QPyckq.mjs +1 -0
- package/dist/{Win32Debug-DwF8mQGm.mjs → Win32Debug-6yzmtv5b.mjs} +1 -1
- package/dist/allocation-track-CiI-CnaI.mjs +1 -0
- package/dist/analysis-CojUzwX-.mjs +27 -0
- package/dist/{antidebug-CsnpOR9z.mjs → antidebug-CgU84TE1.mjs} +1 -1
- package/dist/apk-DrPBsOq8.mjs +1 -0
- package/dist/artifactRetention-Bk6fW2uF.mjs +1 -0
- package/dist/artifacts-Bx9GLx4J.mjs +1 -0
- package/dist/ast-bridge-BlOrmVAv.mjs +1 -0
- package/dist/ast-utils-B9E5k_v1.mjs +1 -0
- package/dist/binary-instrument-DiE1BP0x.mjs +12 -0
- package/dist/boringssl-inspector-C6M3sOga.mjs +2 -0
- package/dist/browser-QDUu5ML9.mjs +29 -0
- package/dist/{canvas-396ieNv5.mjs → canvas-g5kmLdY-.mjs} +1098 -24
- package/dist/{capabilities-L1ax5EHS.mjs → capabilities-DwzyxL2w.mjs} +1 -1
- package/dist/cdp-session-Dy4OwMOP.mjs +1 -0
- package/dist/collector-Cld4i-E4.mjs +1 -0
- package/dist/config-5ODJ3Aj0.mjs +3 -0
- package/dist/constants-nvsLpSri.mjs +1 -0
- package/dist/coordination-C6y2gM9O.mjs +98 -0
- package/dist/coverage-and-block--cWjjEe5.mjs +1 -0
- package/dist/dart-inspector-D4IKxZ6u.mjs +0 -0
- package/dist/debugger-C2SpiXoO.mjs +1 -0
- package/dist/definitions-0mtilYzG.mjs +1 -0
- package/dist/definitions-9csunmeX.mjs +1 -0
- package/dist/definitions-B11MudW_.mjs +1 -0
- package/dist/definitions-BKpRDjcI.mjs +1 -0
- package/dist/definitions-BXE3H4re.mjs +1 -0
- package/dist/definitions-BlPHe5DX.mjs +1 -0
- package/dist/definitions-Bob4XMxI.mjs +27 -0
- package/dist/definitions-BpIQN2nm.mjs +1 -0
- package/dist/{definitions-Ym8niHDb.mjs → definitions-BvolWeSu.mjs} +1 -1
- package/dist/definitions-C-6j3Ejl.mjs +1 -0
- package/dist/definitions-C-AdFfFu.mjs +1 -0
- package/dist/definitions-CArdw_9T.mjs +1 -0
- package/dist/definitions-CCvIcRrT.mjs +1 -0
- package/dist/definitions-CJPE5PIl.mjs +1 -0
- package/dist/definitions-CbqeW06u.mjs +1 -0
- package/dist/definitions-Cexmkypg.mjs +1 -0
- package/dist/definitions-D1dxl8qt.mjs +1 -0
- package/dist/definitions-D3uT-ZbU.mjs +1 -0
- package/dist/definitions-DtOY5iUc.mjs +1 -0
- package/dist/{definitions-Cv5r8xwq.mjs → definitions-DvrYdDCJ2.mjs} +1 -1
- package/dist/definitions-ihxOqOC4.mjs +1 -0
- package/dist/deopt-trace-qnAcC931.mjs +17 -0
- package/dist/disasm-DoxSucGp.mjs +1 -0
- package/dist/dumpsys-parser-Du-5ruEe.mjs +2 -0
- package/dist/encoding-UMtwgy4M.mjs +2 -0
- package/dist/ensure-browser-core-BP70x0TB.mjs +285 -0
- package/dist/factory-BeND77hf.mjs +2 -0
- package/dist/graphql-CF7QKJME.mjs +68 -0
- package/dist/grpc-raw-Dp7ps2sv.mjs +1 -0
- package/dist/handlers--qCl9vNv.mjs +1 -0
- package/dist/handlers-BHIu1LqA.mjs +1 -0
- package/dist/{handlers-DB6xVVWq.mjs → handlers-BQ4K8Jbr.mjs} +1 -1
- package/dist/handlers-BxQv-wtf.mjs +8 -0
- package/dist/handlers-ByYG27-5.mjs +1 -0
- package/dist/handlers-C0I9-BtX.mjs +5 -0
- package/dist/{handlers-CWKBBjai.mjs → handlers-CL0Iokmw.mjs} +1 -1
- package/dist/handlers-CNbhIdSK.mjs +4 -0
- package/dist/handlers-CnTTSJFs.mjs +109 -0
- package/dist/handlers-CoDx6akJ2.mjs +49 -0
- package/dist/{handlers-BbLxNbbT.mjs → handlers-DASJI0Pn.mjs} +1 -1
- package/dist/handlers-DRKMaA-_.mjs +74 -0
- package/dist/handlers-Dalu0olz.mjs +2 -0
- package/dist/handlers-KY0g31ny.mjs +9 -0
- package/dist/handlers-oGo60aVv.mjs +1 -0
- package/dist/handlers.impl-BTXLw6Qc.mjs +1 -0
- package/dist/heap-sampling-BqdiU-5j.mjs +1 -0
- package/dist/{hooks-DPouiS7I.mjs → hooks-COK3t5rT.mjs} +51 -32
- package/dist/index.mjs +11 -11
- package/dist/logger-BGCcd-jJ.mjs +1 -0
- package/dist/macro-nUYUjKNZ.mjs +2 -0
- package/dist/maintenance-CfnE7ZKU.mjs +4 -0
- package/dist/manifest-7EOTUc0D.mjs +1 -0
- package/dist/manifest-B5ujuQmf.mjs +1 -0
- package/dist/manifest-BErXl3zn.mjs +1 -0
- package/dist/manifest-BKA-mD3J.mjs +1 -0
- package/dist/manifest-BUXj23bX.mjs +1 -0
- package/dist/manifest-BfXt9cau.mjs +1 -0
- package/dist/manifest-Bx-tpURK.mjs +1 -0
- package/dist/manifest-C0owVAdq.mjs +1 -0
- package/dist/manifest-C5XqYc9o.mjs +1 -0
- package/dist/manifest-CVKzLjsA.mjs +1 -0
- package/dist/manifest-CaeFjdhj.mjs +1 -0
- package/dist/manifest-CegBgip0.mjs +1 -0
- package/dist/manifest-CoJHqlgS.mjs +1 -0
- package/dist/manifest-D0dbtDqd.mjs +1 -0
- package/dist/manifest-D5Gr8ujd.mjs +12 -0
- package/dist/manifest-D82z-5og.mjs +1 -0
- package/dist/manifest-DA2afIwh.mjs +1 -0
- package/dist/manifest-DAbiFP5o.mjs +1 -0
- package/dist/manifest-DEY0s1O72.mjs +1 -0
- package/dist/manifest-DTOqNqiA.mjs +1 -0
- package/dist/manifest-DZ6ELNgX.mjs +1 -0
- package/dist/manifest-DjHkjddT.mjs +1 -0
- package/dist/manifest-DocA_itf2.mjs +1 -0
- package/dist/manifest-Dpnhvfq0.mjs +1 -0
- package/dist/manifest-DucPMG_a.mjs +1 -0
- package/dist/manifest-Dw5yYEac.mjs +1 -0
- package/dist/manifest-Ic_Cg66S.mjs +1 -0
- package/dist/manifest-JHaG6GMN.mjs +1 -0
- package/dist/manifest-QdkIzmYM.mjs +1 -0
- package/dist/manifest-YZqaCe25.mjs +1 -0
- package/dist/manifest-f0lUeXwq.mjs +1 -0
- package/dist/manifest-h-Ebisf8.mjs +1 -0
- package/dist/manifest-oOfTymBS.mjs +1 -0
- package/dist/manifest-qXqrO6KC.mjs +2 -0
- package/dist/mapsParser-DrJoeC0c.mjs +1 -0
- package/dist/modules-CC_ADmwi.mjs +333 -0
- package/dist/mojo-ipc-kVztXYw-.mjs +140 -0
- package/dist/native-D9ouskXO.mjs +961 -0
- package/dist/native-bridge-Dzd7hYoq.mjs +1 -0
- package/dist/network-C5Y-S87J.mjs +7 -0
- package/dist/one-gadget-CiWFE17F.mjs +1 -0
- package/dist/outputPaths-CHtELDyi.mjs +1 -0
- package/dist/parse-args-B6dwWc9k.mjs +1 -0
- package/dist/platform-BIXgJaM3.mjs +94 -0
- package/dist/process-aDIfLC0v.mjs +6 -0
- package/dist/proxy-DsHsQ1I4.mjs +2 -0
- package/dist/registry-7h8jJ9y9.mjs +1 -0
- package/dist/{registry-xB8Wgmyj.mjs → registry-DJDnkQW2.mjs} +1 -1
- package/dist/response-R8ghbZSb.mjs +1 -0
- package/dist/retry-policy-DtYv0kDi.mjs +1 -0
- package/dist/reverseEngineeringConfig-BhZLOa3C.mjs +1 -0
- package/dist/safeOutput-Dt4mfjXA.mjs +1 -0
- package/dist/{search-defaults-CJik67or.mjs → search-defaults-BBRJNAzC.mjs} +1 -1
- package/dist/server/search/EmbeddingWorker.d.mts +1 -0
- package/dist/server/search/EmbeddingWorker.mjs +1 -0
- package/dist/shared-BKtWZDGN.mjs +1 -0
- package/dist/sourcemap-2VIeVeKw.mjs +3 -0
- package/dist/streaming-DkpE3GGU.mjs +15 -0
- package/dist/syscall-DGZoYM_U.mjs +1 -0
- package/dist/transform-BJqsBC_-.mjs +105 -0
- package/dist/turbofan-graph-CbGHNVtl.mjs +1 -0
- package/dist/turbofan-inspect--NdCuYXi.mjs +23 -0
- package/dist/types-CWSvzmIh.mjs +1 -0
- package/dist/v8-inspector-CTJo08-K.mjs +297 -0
- package/dist/wasm-DX4Qm2Vs.mjs +235 -0
- package/dist/weakrefs-inspect-CnhaF-rN.mjs +57 -0
- package/dist/webgpu-D4-DxbxZ.mjs +6 -0
- package/dist/workflow-DHktRNF2.mjs +108 -0
- package/package.json +33 -27
- package/dist/AntiCheatDetector-CUpZBh5O.mjs +0 -1
- package/dist/CodeInjector-Btj9upnf.mjs +0 -1
- package/dist/ConsoleMonitor-DIjN5Afa.mjs +0 -306
- package/dist/DarwinAPI-BuMPGzHm.mjs +0 -1
- package/dist/ExtensionManager.tools-CIGOWViz.mjs +0 -1
- package/dist/FingerprintManager-BkDSsjjP.mjs +0 -1
- package/dist/HardwareBreakpoint-DMAMcPyB.mjs +0 -1
- package/dist/HeapAnalyzer-Yj348FYt.mjs +0 -1
- package/dist/InstrumentationSession-c5qZyp7d.mjs +0 -1
- package/dist/MCPServer.activation.ttl-CEGNBycZ.mjs +0 -1
- package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +0 -1
- package/dist/MemoryController-DjtgiING.mjs +0 -2
- package/dist/MemoryScanner-Dxd657li.mjs +0 -1
- package/dist/PEAnalyzer-CMu9Ua9T.mjs +0 -1
- package/dist/PointerChainEngine-CaSC1Mry.mjs +0 -1
- package/dist/ProcessRegistry-D5y1yuP2.mjs +0 -1
- package/dist/ReverseEvidenceGraph-BksOpsPs.mjs +0 -2
- package/dist/ServerRuntimeState-CgqBBwfd.mjs +0 -1
- package/dist/Speedhack-pwXTHxOY.mjs +0 -1
- package/dist/StructureAnalyzer-BseGzsSl.mjs +0 -2
- package/dist/ToolCatalog-DgmQXdsm.mjs +0 -1
- package/dist/ToolHandlerMap-7HWoIgQO.mjs +0 -1
- package/dist/ToolRegistry-eMZEBiR1.mjs +0 -1
- package/dist/TraceRecorder-B5ktv3nP.mjs +0 -272
- package/dist/VersionDetector-CmPJmaJg.mjs +0 -1
- package/dist/Win32API-DoP3MMHS.mjs +0 -1
- package/dist/WorkflowEngine-CldHG5b4.mjs +0 -1
- package/dist/analysis-C-ln0Brh.mjs +0 -6
- package/dist/artifactRetention-DkYKLOvi.mjs +0 -1
- package/dist/artifacts-D-4pSS_N.mjs +0 -1
- package/dist/binary-instrument-BeZ224mZ.mjs +0 -9
- package/dist/boringssl-inspector-ZOCkaipa.mjs +0 -2
- package/dist/browser-BUaB25bk.mjs +0 -11
- package/dist/collector-CB2syQEg.mjs +0 -1
- package/dist/constants-DMv3svps.mjs +0 -2
- package/dist/coordination-Dbohmj6D.mjs +0 -1
- package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
- package/dist/debugger-CLzkObIO.mjs +0 -1
- package/dist/definitions-0hxnrDU72.mjs +0 -1
- package/dist/definitions-B3a9QC2t.mjs +0 -1
- package/dist/definitions-BOvju5t2.mjs +0 -1
- package/dist/definitions-CXj_cEVt.mjs +0 -1
- package/dist/definitions-Co6AvTjH.mjs +0 -1
- package/dist/definitions-DBYSxChX.mjs +0 -1
- package/dist/definitions-D_dTDX9B.mjs +0 -1
- package/dist/definitions-Db9t2ddh.mjs +0 -1
- package/dist/definitions-DbN2CjI2.mjs +0 -1
- package/dist/definitions-DlmmHmZc.mjs +0 -1
- package/dist/definitions-DnYpoGig.mjs +0 -1
- package/dist/definitions-DtZ6Ktx2.mjs +0 -1
- package/dist/definitions-DuIPS8gq.mjs +0 -1
- package/dist/definitions-DywfwPMb.mjs +0 -1
- package/dist/definitions-EGmqr85H.mjs +0 -1
- package/dist/definitions-Fetw_Cge.mjs +0 -26
- package/dist/definitions-LdkeuOeA.mjs +0 -1
- package/dist/definitions-cnG6tj17.mjs +0 -1
- package/dist/encoding-B4xZWErf.mjs +0 -2
- package/dist/ensure-browser-core-JHwDo5ql.mjs +0 -285
- package/dist/factory-BxNdBiZa.mjs +0 -1
- package/dist/graphql-GBWsZ9xC.mjs +0 -62
- package/dist/handlers-5nzR8B0a.mjs +0 -5
- package/dist/handlers-6iNsXOVT.mjs +0 -7
- package/dist/handlers-BZ8n6Hvf.mjs +0 -1
- package/dist/handlers-BbS4hssc.mjs +0 -4
- package/dist/handlers-CIKOP4aI.mjs +0 -2
- package/dist/handlers-Cmb6SoRC.mjs +0 -1
- package/dist/handlers-CrJsKnEI.mjs +0 -1
- package/dist/handlers-DOOCWUNR.mjs +0 -31
- package/dist/handlers-Z_B5aVaU.mjs +0 -54
- package/dist/handlers-gVscChvl.mjs +0 -1
- package/dist/handlers-xFvI9P_y.mjs +0 -1
- package/dist/handlers.impl-BsFTW6SD.mjs +0 -1
- package/dist/logger-CCikqqvj.mjs +0 -1
- package/dist/macro-p8kuJVcm.mjs +0 -2
- package/dist/maintenance-DAqADb6Z.mjs +0 -302
- package/dist/manifest-4lmM6MZR.mjs +0 -1
- package/dist/manifest-AxaxRSt6.mjs +0 -2
- package/dist/manifest-BIqRE1Qz.mjs +0 -1
- package/dist/manifest-Box-jWfr.mjs +0 -1
- package/dist/manifest-Bp33di0Q.mjs +0 -1
- package/dist/manifest-BvRX4nRP.mjs +0 -1
- package/dist/manifest-C6KoB1XE.mjs +0 -1
- package/dist/manifest-C7TdXCWY.mjs +0 -1
- package/dist/manifest-CM-n64K0.mjs +0 -1
- package/dist/manifest-CUokxCUN.mjs +0 -1
- package/dist/manifest-CWJS45iO.mjs +0 -1
- package/dist/manifest-Cdxdgo-D.mjs +0 -1
- package/dist/manifest-Cf6SmamD.mjs +0 -1
- package/dist/manifest-Cgxu2qdv.mjs +0 -1
- package/dist/manifest-CowGSURa2.mjs +0 -1
- package/dist/manifest-CsGIrh34.mjs +0 -1
- package/dist/manifest-CvDpVToN.mjs +0 -1
- package/dist/manifest-D8TL9RLE.mjs +0 -1
- package/dist/manifest-DIhtCBe6.mjs +0 -1
- package/dist/manifest-DJbruNOg.mjs +0 -1
- package/dist/manifest-DLGtZH-0.mjs +0 -1
- package/dist/manifest-DXHdPt2T.mjs +0 -1
- package/dist/manifest-Dg5ScOyW.mjs +0 -1
- package/dist/manifest-DzGoTS0R.mjs +0 -1
- package/dist/manifest-G2H52LKz.mjs +0 -131
- package/dist/manifest-P0Futrgb.mjs +0 -1
- package/dist/manifest-Qw7xgvjv.mjs +0 -1
- package/dist/manifest-W3qvVrP2.mjs +0 -1
- package/dist/manifest-dG6MuR1U.mjs +0 -1
- package/dist/manifest-nWXtgq5Y2.mjs +0 -1
- package/dist/manifest-vp1upSSq.mjs +0 -1
- package/dist/modules-DO3jXCgj.mjs +0 -333
- package/dist/mojo-ipc-Be-ccWrc.mjs +0 -9
- package/dist/native-g095qhpK.mjs +0 -961
- package/dist/network-Dvxm7eEI.mjs +0 -7
- package/dist/outputPaths-D2ddHrOJ.mjs +0 -2
- package/dist/parse-args-ngRrvF9e.mjs +0 -1
- package/dist/platform-DjWbuiF8.mjs +0 -93
- package/dist/process-Dq5I-KZW.mjs +0 -2
- package/dist/proxy-DPNgM7TE.mjs +0 -2
- package/dist/renderer-pid-7jbTR8f5.mjs +0 -1
- package/dist/response-B1RuVVfD.mjs +0 -1
- package/dist/sourcemap-DqEW15Ao.mjs +0 -1
- package/dist/streaming-Dbk4eStJ.mjs +0 -1
- package/dist/transform-D-peM3aO.mjs +0 -103
- package/dist/wasm-CZajRaad.mjs +0 -174
- package/dist/webcrack-phEfVt5y.mjs +0 -46
- package/dist/workflow-wkXb3x-U.mjs +0 -101
- /package/dist/{chunk-88NL7fhV.mjs → rolldown-runtime-88NL7fhV.mjs} +0 -0
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";import{Qt as n,Yi as r,en as i}from"./constants-DMv3svps.mjs";import{t as a}from"./ToolError-g3rjWzhx.mjs";import{t as o}from"./ToolProbe-DQiREmNp.mjs";import{v as s}from"./ensure-browser-core-JHwDo5ql.mjs";import{tmpdir as c}from"node:os";import{constants as l}from"node:fs";import{basename as u,dirname as d,isAbsolute as f,join as p,normalize as m,resolve as h}from"node:path";import{access as g,mkdtemp as _,readFile as v,readdir as y,rm as b,stat as x,writeFile as S}from"node:fs/promises";import{createHash as C,randomUUID as w}from"node:crypto";import{execFile as T}from"node:child_process";var E=class{sessions=new Map;activeSessionId;fridaProbe;probePromise;async attach(e){let t=await this.getAvailability();if(!t.available)throw new s(t.reason??`Frida CLI is not available`);let n=await this.runFridaCommand(e,`console.log("__frida_attach_ok__");`);if(n.error)throw new a(`CONNECTION`,n.error);let r=w(),i={id:r,target:e,pid:this.resolvePid(e),status:`attached`,attachedAt:new Date().toISOString()};return this.sessions.set(r,i),this.activeSessionId=r,r}async detach(){let e=this.getActiveSessionRecord();e&&(e.status=`detached`,this.activeSessionId=void 0)}async executeScript(e){let t=this.requireActiveSession(),n=await this.runFridaCommand(t.target,e);return n.error&&(t.status=`error`,t.lastError=n.error),n}async enumerateModules(){let e=this.requireActiveSession(),t=await this.runFridaCommand(e.target,`console.log(JSON.stringify(Process.enumerateModules()));`),n=this.parseModuleList(t.output);return n.length>0?n:(t.error&&(e.status=`error`,e.lastError=t.error),[])}async enumerateFunctions(e){let t=this.requireActiveSession(),n=JSON.stringify(e),r=await this.runFridaCommand(t.target,[`const entries = Process.getModuleByName(${n}).enumerateExports()`,`.filter(function (entry) { return entry.type === "function"; })`,`.map(function (entry) {`,` return { name: entry.name, address: String(entry.address), size: 0 };`,`});`,`console.log(JSON.stringify(entries));`].join(``)),i=this.parseFunctionList(r.output);return i.length>0?i:(r.error&&(t.status=`error`,t.lastError=r.error),[])}async findSymbols(e){let t=this.requireActiveSession(),n=e.trim(),r=n.includes(`:`)?n:n.includes(`!`)?`exports:${n}`:`exports:*!${n}*`,i=JSON.stringify(r),a=await this.runFridaCommand(t.target,[`const resolver = new ApiResolver("module");`,`const matches = resolver.enumerateMatches(${i});`,`const mapped = matches.map(function (entry) {`,` const resolvedName = typeof entry.name === "string" ? entry.name : "unknown";`,` const resolvedAddress = entry.address ? String(entry.address) : "0x0";`,` return { name: resolvedName, address: resolvedAddress, demangled: resolvedName };`,`});`,`console.log(JSON.stringify(mapped));`].join(``)),o=this.parseSymbolList(a.output);return o.length>0?o:(a.error&&(t.status=`error`,t.lastError=a.error),[])}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,target:e.target,pid:e.pid,status:e.status}))}async isAvailable(){return(await this.getAvailability()).available}async getAvailability(){if(this.fridaProbe)return this.fridaProbe;this.probePromise||=o(`frida`);let e=await this.probePromise;return this.fridaProbe=e,this.probePromise=void 0,e}useSession(e){return this.sessions.has(e)?(this.activeSessionId=e,!0):!1}hasSession(e){return this.sessions.has(e)}getSessionDiagnostics(e){let t=this.sessions.get(e);if(t)return{status:t.status,lastError:t.lastError}}getActiveSessionRecord(){if(this.activeSessionId)return this.sessions.get(this.activeSessionId)}requireActiveSession(){let e=this.getActiveSessionRecord();if(!e)throw new s(`No active Frida session. Call attach() first.`);return e}resolvePid(e){if(!/^\d+$/.test(e))return null;let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}async runFridaCommand(e,r){let i=await this.getAvailability();if(!i.available)return{output:``,error:i.reason??`Frida CLI is not available`};let a=i.path??`frida`,o=[...this.buildTargetArgs(e),`--runtime=v8`,`-q`,`-e`,r];try{let e=await this.execFileUtf8(a,o,n),t=e.stdout.trim(),r=e.stderr.trim();return r?{output:t,error:r}:{output:t}}catch(n){let r=n instanceof Error?n.message:String(n);return t.warn(`[binary-instrument] Frida command failed`,{target:e,message:r}),{output:``,error:r}}}buildTargetArgs(e){return/^\d+$/.test(e)?[`-p`,e]:e.includes(`/`)||e.includes(`\\`)?[`-f`,e]:[`-n`,e]}parseModuleList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.readStringField(e,`path`),i=this.normalizeHex(e.base),a=this.readNumberField(e,`size`);!t||!r||!i||a===void 0||n.push({name:t,base:i,size:a,path:r})}return n}parseFunctionList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.normalizeHex(e.address),i=this.readNumberField(e,`size`)??0;!t||!r||n.push({name:t,address:r,size:i})}return n}parseSymbolList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.normalizeHex(e.address),i=this.readStringField(e,`demangled`);!t||!r||(i?n.push({name:t,address:r,demangled:i}):n.push({name:t,address:r}))}return n}extractJsonPayload(e){let t=e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.startsWith(`{`)||e.startsWith(`[`)).toReversed();for(let e of t)try{return JSON.parse(e)}catch{continue}}readStringField(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}readNumberField(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}normalizeHex(e){if(typeof e==`number`&&Number.isFinite(e))return`0x${e.toString(16)}`;if(typeof e==`string`&&e.length>0)return e.startsWith(`0x`)?e:`0x${e}`}isRecord(e){return typeof e==`object`&&!!e}execFileUtf8(e,t,n){return new Promise((r,i)=>{T(e,t,{timeout:n,windowsHide:!0,maxBuffer:5242880,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}};const D=[`GHIDRA_HEADLESS_PATH`,`GHIDRA_ANALYZE_HEADLESS`],O=[`GHIDRA_HOME`,`GHIDRA_INSTALL_DIR`],k=process.platform===`win32`?[`analyzeHeadless.bat`,`analyzeHeadless.cmd`]:[`analyzeHeadless`];var A=class e{ghidraProbe;probePromise;analysisCache=new Map;static CACHE_TTL_MS=1800*1e3;discoveryPaths;constructor(e={}){this.discoveryPaths=e.discoveryPaths??N()}async analyze(e,n){await g(e);let r=await v(e),a=this.extractPrintableStrings(r),o=this.deriveImports(a),l=this.deriveExports(a),u=await this.getAvailability();if(!u.available)throw new s([`Ghidra analyzeHeadless is not available: ${u.reason||`not found on PATH`}`,`Install Ghidra and add analyzeHeadless to your PATH.`,`Windows: add <ghidra>/support to PATH. Linux/macOS: add <ghidra_install_dir>/support to PATH.`].join(` `));if(!n?.forceRefresh){let n=this.getCachedResult(e,r);if(n)return t.info(`[binary-instrument] Returning cached Ghidra analysis for ${e}`),{...n,strings:a,imports:o,exports:l}}let d=typeof n?.timeout==`number`&&Number.isFinite(n.timeout)?n.timeout:i,f=await _(p(c(),`jshook-ghidra-script-`)),m=p(f,`BinaryInstrumentDump.java`);try{await S(m,this.buildDefaultScript(),`utf8`);let t=await this.headlessAnalyze(m,e,d),n={functions:this.parseDecompiledOutput(t),imports:o,exports:l,strings:a};return this.cacheResult(e,r,n),n}catch(n){let r=n instanceof Error?n.message:String(n);return t.warn(`[binary-instrument] Ghidra analyze fallback`,{binaryPath:e,message:r}),{functions:[],imports:o,exports:l,strings:a}}finally{await b(f,{recursive:!0,force:!0})}}async analyzeBatch(e,n){let r=new Map;for(let i of e)try{let e=await this.analyze(i,n);r.set(i,e)}catch(e){let n=e instanceof Error?e.message:String(e);t.warn(`[binary-instrument] Batch analysis failed for ${i}`,{message:n}),r.set(i,{functions:[],imports:[],exports:[],strings:[]})}return r}async runCustomScript(e,t,n){let r=await this.getAvailability();if(!r.available)throw new s([`Ghidra analyzeHeadless is not available: ${r.reason||`not found on PATH`}`,`Install Ghidra and add analyzeHeadless to your PATH.`].join(` `));await g(e);let a=await _(p(c(),`jshook-ghidra-custom-`)),o=p(a,L(t,n?.language??I(t)));try{return await S(o,t,`utf8`),await this.headlessAnalyze(o,e,n?.timeout??i)}finally{await b(a,{recursive:!0,force:!0})}}async headlessAnalyze(e,t,n=i){let r=await this.getAvailability();if(!r.available)throw new s(r.reason??`Ghidra analyzeHeadless is not available`);await g(t),await g(e);let a=r.path??`analyzeHeadless`,o=await _(p(c(),`jshook-ghidra-project-`));try{let r=await this.execFileUtf8(a,[o,`binary-instrument`,`-import`,t,`-scriptPath`,d(e),`-postScript`,u(e)],n);return[r.stdout.trim(),r.stderr.trim()].filter(e=>e.length>0).join(`
|
|
2
|
-
`)}finally{await b(o,{recursive:!0,force:!0})}}parseDecompiledOutput(e){let t=[],n=F(e),r=/FUNCTION_START\s*[\r\n]+NAME:(.+?)\s*[\r\n]+ADDRESS:(.+?)\s*[\r\n]+SIGNATURE:(.+?)\s*[\r\n]+DECOMPILED_START\s*[\r\n]+([\s\S]*?)\s*[\r\n]+DECOMPILED_END\s*[\r\n]+FUNCTION_END/g,i=r.exec(n);for(;i;){let e=i[1]??``,a=i[2]??``,o=i[3]??``,s=i[4]??``,c=e.trim(),l=this.normalizeHex(a.trim()),u=o.trim(),d=s.trim();c.length>0&&l.length>0&&u.length>0&&t.push({name:c,address:l,signature:u,decompiled:d}),i=r.exec(n)}return t}async isAvailable(){return(await this.getAvailability()).available}async getAvailability(){if(this.ghidraProbe)return this.ghidraProbe;this.probePromise||=this.probeAnalyzeHeadless();let e=await this.probePromise;return this.ghidraProbe=e,this.probePromise=void 0,e}async probeAnalyzeHeadless(){return await this.resolveFromEnvironment()||await this.resolveFromDiscoveryPaths()||o(`analyzeHeadless`,[`-help`])}async resolveFromEnvironment(){for(let e of D){let t=process.env[e]?.trim();if(!t)continue;let n=await this.probeCandidate(t,e);if(n)return n}for(let e of O){let t=process.env[e]?.trim();if(!t)continue;let n=await this.probeHomeDirectory(t,e);if(n)return n}return null}async resolveFromDiscoveryPaths(){for(let e of this.discoveryPaths){let t=await this.probeHomeDirectory(e,`auto-discovery`);if(t)return t;for(let t of await M(e)){let e=await this.probeHomeDirectory(t,`auto-discovery`);if(e)return e}}return null}async probeHomeDirectory(e,t){let n=j(e);for(let e of n){let n=await this.probeCandidate(e,t);if(n)return n}return null}async probeCandidate(e,t){let n=m(e);if(!(await x(n).catch(()=>null))?.isFile())return null;try{await g(n,l.X_OK)}catch{try{await g(n,l.R_OK)}catch{return null}}return{available:!0,path:n,version:`analyzeHeadless (${t})`}}buildDefaultScript(){return[`// @category BinaryInstrument`,`import ghidra.app.decompiler.DecompInterface;`,`import ghidra.app.decompiler.DecompileResults;`,`import ghidra.app.script.GhidraScript;`,`import ghidra.program.model.listing.Function;`,`import ghidra.program.model.listing.FunctionIterator;`,``,`public class BinaryInstrumentDump extends GhidraScript {`,` @Override`,` public void run() throws Exception {`,` DecompInterface decompiler = new DecompInterface();`,` decompiler.openProgram(currentProgram);`,``,` try {`,` FunctionIterator functions = currentProgram.getFunctionManager().getFunctions(true);`,` while (functions.hasNext()) {`,` Function function = functions.next();`,` emit("FUNCTION_START");`,` emit("NAME:" + function.getName());`,` emit("ADDRESS:" + function.getEntryPoint().toString());`,` emit("SIGNATURE:" + getSignature(function));`,` emit("DECOMPILED_START");`,` emit(decompileFunction(decompiler, function));`,` emit("DECOMPILED_END");`,` emit("FUNCTION_END");`,` }`,` } finally {`,` decompiler.dispose();`,` }`,` }`,``,` private void emit(String value) {`,` System.out.println(value);`,` }`,``,` private String getSignature(Function function) {`,` try {`,` return function.getSignature().toString();`,` } catch (Exception ignored) {`,` return function.getName() + "()";`,` }`,` }`,``,` private String decompileFunction(DecompInterface decompiler, Function function) {`,` try {`,` DecompileResults results = decompiler.decompileFunction(function, 30, monitor);`,` if (results != null && results.decompileCompleted() && results.getDecompiledFunction() != null) {`,` return results.getDecompiledFunction().getC();`,` }`,` return "// no decompiled output";`,` } catch (Exception error) {`,` return "// decompile failed: " + error.getMessage();`,` }`,` }`,`}`].join(`
|
|
3
|
-
`)}extractPrintableStrings(e){let t=[],n=``;for(let r of e.values()){if(r>=32&&r<=126){n+=String.fromCharCode(r);continue}n.length>=4&&t.push(n),n=``}return n.length>=4&&t.push(n),Array.from(new Set(t)).slice(0,1e3)}deriveImports(e){return e.filter(e=>/(?:\.dll|\.so|\.dylib|kernel32|user32|libc|printf|malloc|LoadLibrary)/i.test(e)).slice(0,100)}deriveExports(e){return e.filter(e=>/^[A-Za-z_][A-Za-z0-9_@?$]{2,}$/.test(e)).slice(0,100)}normalizeHex(e){return e.startsWith(`0x`)?e:`0x${e}`}getCachedResult(t,n){let r=this.analysisCache.get(t);return r?Date.now()-r.analyzedAt>e.CACHE_TTL_MS||this.computeHash(n)!==r.hash?(this.analysisCache.delete(t),null):{...r.result}:null}cacheResult(e,t,n){if(this.analysisCache.set(e,{hash:this.computeHash(t),fileSize:t.length,analyzedAt:Date.now(),result:n}),this.analysisCache.size>20){let e=``,t=1/0;for(let[n,r]of this.analysisCache.entries())r.analyzedAt<t&&(t=r.analyzedAt,e=n);e&&this.analysisCache.delete(e)}}computeHash(e){return C(`sha256`).update(e).digest(`hex`).substring(0,32)}execFileUtf8(e,t,n){return new Promise((r,i)=>{T(e,t,{timeout:n,windowsHide:!0,maxBuffer:16777216,encoding:`utf8`,shell:P(e)},(e,t,n)=>{if(e){let r=[typeof t==`string`&&t.trim()?`stdout:\n${t.trim()}`:``,typeof n==`string`&&n.trim()?`stderr:\n${n.trim()}`:``].filter(e=>e.length>0).join(`
|
|
4
|
-
`);r&&e instanceof Error&&(e.message=`${e.message}\n${r}`),i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}};function j(e){let t=m(e),n=f(t)?t:h(t),r=[n];for(let e of k)r.push(p(n,e)),r.push(p(n,`support`,e));return Array.from(new Set(r))}async function M(e){try{return(await y(e,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/ghidra/i.test(e.name)).slice(0,20).map(t=>p(e,t.name))}catch{return[]}}function N(){let e=new Set,t=t=>{t&&t.trim().length>0&&e.add(t.trim())};return t(process.cwd()),t(process.env.USERPROFILE),t(process.env.HOME),process.platform===`win32`?(t(process.env.ProgramFiles),t(process.env[`ProgramFiles(x86)`]),t(`D:\\coding\\security`),t(`D:\\tools`),t(`C:\\tools`)):(t(`/opt`),t(`/usr/local`),t(`/Applications`)),Array.from(e)}function P(e){return process.platform===`win32`&&/\.(?:bat|cmd)$/i.test(e)}function F(e){return e.split(/\r?\n/).map(e=>{let t=/^(?:INFO|WARN|ERROR)\s+[^>]+>\s*(.*)$/.exec(e);return t?(t[1]??``).replace(/\s+\(GhidraScript\)\s*$/,``):e}).join(`
|
|
5
|
-
`)}function I(e){return/\bextends\s+GhidraScript\b/.test(e)||/\bimport\s+ghidra\./.test(e)||/\bpublic\s+class\s+\w+\b/.test(e)?`java`:`python`}function L(e,t){return t===`python`?`custom_script.py`:`${/\bpublic\s+class\s+([A-Za-z_$][\w$]*)\b/.exec(e)?.[1]??`CustomScript`}.java`}var R=class{generateHooks(e){let t=[];for(let n of e.functions){let r=this.classifyFunction(n,e);r!==`unknown`&&t.push({functionName:n.name,description:this.describeCategory(r,e),hookCode:this.buildHookCode(n,r),parameters:this.buildParameters(n)})}return t}exportScript(e,t){if(t!==`frida`)throw new a(`VALIDATION`,`Unsupported export format: "${t}". Only "frida" is supported.`);let n=[`// Frida hook script`,`// auto-generated by HookCodeGenerator`,`// Hook count: ${e.length}`,``];for(let t of e)n.push(`// ${t.functionName}: ${t.description}`),n.push(t.hookCode),n.push(``);return n.join(`
|
|
6
|
-
`)}classifyFunction(e,t){let n=e.name.toLowerCase(),r=t.imports.map(e=>e.toLowerCase()),i=t.strings.map(e=>e.toLowerCase());return e.name.startsWith(`Java_`)?`jni`:n.includes(`aes`)?`aes`:n.includes(`md5`)?`md5`:n.includes(`sha`)?`sha`:n.includes(`rsa`)?`rsa`:n.includes(`base64`)?`base64`:n.includes(`send`)||n.includes(`recv`)||n.includes(`socket`)||n.includes(`http`)?`network`:n.includes(`open`)||n.includes(`read`)||n.includes(`write`)||n.includes(`fopen`)?`file-io`:(n.includes(`decrypt`)||n.includes(`encrypt`))&&i.some(e=>e.includes(`obfuscation`)||e.includes(`encryption`))?`obfuscation`:n.includes(`memcpy`)||n.includes(`strcpy`)||n.includes(`memmove`)||n.includes(`string`)?`string`:r.some(e=>e.includes(`aes`))?`aes`:`unknown`}describeCategory(e,t){switch(e){case`jni`:return`JNI bridge hook for Java/native boundary inspection`;case`aes`:return`AES crypto hook for key/plaintext capture`;case`md5`:return`MD5 crypto hook for digest inspection`;case`sha`:return`SHA crypto hook for digest inspection`;case`rsa`:return`RSA crypto hook for key operation tracing`;case`base64`:return`Base64 transform hook for encoded payload tracing`;case`network`:return`Network hook for request and payload tracing`;case`file-io`:return`File I/O hook for filesystem access tracing`;case`string`:return`String operation hook for buffer tracing`;case`obfuscation`:return t.strings.some(e=>e.toLowerCase().includes(`obfuscation`))?`Potential obfuscation hook for runtime string decryption tracing`:`Potential obfuscation hook`;case`unknown`:return`Unknown hook`}}buildHookCode(e,t){if(t===`jni`)return[`Java.perform(function () {`,` const target = ptr("${e.address}");`,` Interceptor.attach(target, {`,` onEnter(args) {`,` console.log("[jni] ${e.name}");`,` },`,` });`,`});`].join(`
|
|
7
|
-
`);let n=t===`aes`||t===`md5`||t===`sha`||t===`rsa`||t===`base64`?` console.log(hexdump(args[0]));`:` console.log("[trace] entering");`,r=e.name.replace(/[^A-Za-z0-9_]/g,`_`);return[`const target_${r} = ptr("${e.address}");`,`Interceptor.attach(target_${r}, {`,` onEnter(args) {`,` console.log("[hook] ${e.name}");`,n,` },`,`});`].join(`
|
|
8
|
-
`)}buildParameters(e){return e.parameters.length>0?e.parameters.map((e,t)=>({name:e.name||`arg${t}`,type:e.type||`pointer`,description:`Captured parameter ${t}`})):[{name:`arg0`,type:`pointer`,description:`Captured parameter 0`}]}};async function z(e,t){let n=B(e),r=V(t.pluginId),i=H(r,n);if(!i)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin ${r} is not installed`};let a=U(e,i);if(!a?.lifecycleContext)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin ${i} is installed but has no runtime`};try{let e=(await a.lifecycleContext.invokeTool(t.toolName,t.args)).content?.find(e=>e.type===`text`)?.text;if(!e)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin returned no text content`};try{let n=JSON.parse(e);if(G(n))return{tool:`binary-instrument`,action:t.toolName,success:K(n,`success`)??!0,data:n.data,error:q(n,`error`)}}catch{return{success:!0,tool:`binary-instrument`,action:t.toolName,data:e}}return{success:!0,tool:`binary-instrument`,action:t.toolName,data:e}}catch(e){return{success:!1,tool:`binary-instrument`,action:t.toolName,error:e instanceof Error?e.message:String(e)}}}function B(e){return Array.from(e.extensionPluginsById.keys()).map(V)}function V(e){return e.replaceAll(`_`,`-`)}function H(e,t){let n=e.replace(/^plugin-/,``);for(let r of t){let t=r.replace(/^plugin-/,``);if(r===e||t===n)return r}}function U(e,t){for(let[n,r]of e.extensionPluginRuntimeById.entries())if(V(n)===t)return W(r)?r:void 0}function W(e){return typeof e==`object`&&!!e}function G(e){return typeof e==`object`&&!!e}function K(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}function q(e,t){let n=e[t];return typeof n==`string`?n:void 0}var J=class{generateFridaHookScript(e,t){let n=t?.includeArgs??!0,r=t?.includeRetAddr??!1,i=[`'use strict';`,``,`function resolveTarget(name) {`,` try {`,` const exported = Module.findExportByName(null, name);`,` if (exported) {`,` return exported;`,` }`,` } catch (error) {}`,` try {`,` const symbol = DebugSymbol.fromName(name);`,` if (symbol && symbol.address) {`,` return symbol.address;`,` }`,` } catch (error) {}`,` return null;`,`}`,``,`const installedHooks = [];`];for(let t=0;t<e.length;t+=1){let a=this.toDescriptor(e[t]),o=`target_${t}`,s=a.demangled??a.name,c=a.address?`const ${o} = ptr("${this.escapeForDoubleQuotes(a.address)}");`:`const ${o} = resolveTarget("${this.escapeForDoubleQuotes(a.name)}");`;i.push(c),i.push(`if (${o}) {`),i.push(` Interceptor.attach(${o}, {`),i.push(` onEnter(args) {`),r?i.push(` console.log("[binary-instrument] enter ${this.escapeForDoubleQuotes(s)} ret=" + this.returnAddress);`):i.push(` console.log("[binary-instrument] enter ${this.escapeForDoubleQuotes(s)}");`),n&&(i.push(` const renderedArgs = [];`),i.push(` for (let i = 0; i < 6; i += 1) {`),i.push(` try {`),i.push(` renderedArgs.push(String(args[i]));`),i.push(` } catch (error) {`),i.push(` renderedArgs.push("<unreadable>");`),i.push(` }`),i.push(` }`),i.push(` console.log("[binary-instrument] args " + JSON.stringify(renderedArgs));`)),i.push(` },`),i.push(` onLeave(retval) {`),i.push(` console.log("[binary-instrument] leave ${this.escapeForDoubleQuotes(s)} retval=" + retval);`),i.push(` },`),i.push(` });`),i.push(` installedHooks.push({ name: "${this.escapeForDoubleQuotes(s)}", address: String(${o}) });`),i.push(`} else {`),i.push(` console.log("[binary-instrument] unresolved ${this.escapeForDoubleQuotes(s)}");`),i.push(`}`),i.push(``)}return i.push(`console.log("[binary-instrument] hooks=" + JSON.stringify(installedHooks));`),i.join(`
|
|
9
|
-
`)}generateInterceptorScript(e){return this.generateFridaHookScript(e,{includeArgs:!0,includeRetAddr:!1})}toDescriptor(e){return typeof e==`string`?{name:e}:e}escapeForDoubleQuotes(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}},Y=class{sessions=new Map;close(){for(let e of this.sessions.values())if(e.childProcess)try{process.kill(e.childProcess.pid,`SIGTERM`)}catch{}this.sessions.clear()}async launch(e,n=`arm`,i){let o=i??process.env.UNIDBG_JAR;if(!o)throw new s(`UNIDBG_JAR is not configured. Set the UNIDBG_JAR env var or pass jarPath.`);try{await g(o)}catch{throw new a(`NOT_FOUND`,`Unidbg JAR not found: ${o}`)}try{await g(e)}catch{throw new a(`NOT_FOUND`,`Shared library not found: ${e}`)}let c=w(),l=this.getJavaCommand(),u=[`-jar`,o,`--so`,e,`--arch`,n,`--server`];try{let t=await this.execFileUtf8(l,u,r),i=this.parseLaunchOutput(t.stdout,c),a={id:i.id,soPath:e,arch:n,startedAt:new Date().toISOString(),childProcess:i.pid?{pid:i.pid}:void 0};return this.sessions.set(c,a),{sessionId:c,soPath:e,arch:n}}catch(r){let i=r instanceof Error?r.message:String(r);t.warn(`[binary-instrument] Unidbg launch failed, registering stub session`,{soPath:e,message:i});let a={id:c,soPath:e,arch:n,startedAt:new Date().toISOString()};return this.sessions.set(c,a),{sessionId:c,soPath:e,arch:n}}}async callFunction(e,t,n={}){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let i=process.env.UNIDBG_JAR;if(!i)return{sessionId:e,functionName:t,args:n,returnValue:`0x0`,stdout:``,stderr:``,trace:[`mock-unidbg-unavailable`],_note:`Unidbg emulation requires UNIDBG_JAR to be configured`};let o=this.getJavaCommand(),s=[`-jar`,i,`--session`,e,`--call`,t,`--args`,JSON.stringify(n)];try{let i=await this.execFileUtf8(o,s,r);return{sessionId:e,functionName:t,args:n,returnValue:this.extractReturnValue(i.stdout),stdout:i.stdout.trim(),stderr:i.stderr.trim(),trace:[]}}catch(r){return{sessionId:e,functionName:t,args:n,returnValue:`0x0`,stdout:``,stderr:r instanceof Error?r.message:String(r),trace:[`error`]}}}async trace(e){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let t=process.env.UNIDBG_JAR;if(!t)return{sessionId:e,trace:[`mock-unidbg-unavailable`],_note:`Unidbg tracing requires UNIDBG_JAR to be configured`};let n=this.getJavaCommand(),i=[`-jar`,t,`--session`,e,`--trace`];try{let t=await this.execFileUtf8(n,i,r);return{sessionId:e,trace:this.parseTraceOutput(t.stdout),instructionCount:this.countInstructions(t.stdout)}}catch(t){return{sessionId:e,trace:[`error`],error:t instanceof Error?t.message:String(t)}}}getSessionInfo(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,soPath:e.soPath,arch:e.arch,startedAt:e.startedAt}))}getJavaCommand(){return process.env.JAVA_HOME?`${process.env.JAVA_HOME}/bin/java`:`java`}parseLaunchOutput(e,t){let n=e.split(/\r?\n/).filter(e=>e.trim().length>0);for(let e of n.toReversed())try{let t=JSON.parse(e);if(typeof t.id==`string`)return{id:t.id,pid:typeof t.pid==`number`?t.pid:null}}catch{}return{id:t,pid:null}}extractReturnValue(e){let t=/return[=:\s]+(0x[0-9a-fA-F]+|-?\d+)/.exec(e);return t?.[1]?t[1]:`0x0`}parseTraceOutput(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`{`)).slice(0,1e4)}countInstructions(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`{`)&&/\b(ldr|str|mov|bl|b|add|sub)\b/i.test(e)).length}async execFileUtf8(e,t,n){return new Promise((r,i)=>{T(e,t,{timeout:n,windowsHide:!0,maxBuffer:8388608,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``,exitCode:0})})})}},X=e({GhidraAnalyzer:()=>A,HookGenerator:()=>J});export{z as a,E as c,B as i,Y as n,R as o,J as r,A as s,X as t};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./chunk-88NL7fhV.mjs";import{a as t}from"./outputPaths-D2ddHrOJ.mjs";import{existsSync as n,readFileSync as r}from"node:fs";import{dirname as i,resolve as a}from"node:path";import{mkdir as o,writeFile as s}from"node:fs/promises";import{createDecipheriv as c,randomUUID as l}from"node:crypto";function u(e){return e.replace(/\s+/g,``).toUpperCase()}function d(e){return e.length>0&&e.length%2==0&&/^[0-9A-F]+$/i.test(e)}function f(e){if(!e)return;let t=new Date(e);if(!Number.isNaN(t.valueOf()))return t.toISOString()}function p(){return a(t(),`jshook-boringssl-${l()}.log`)}function m(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(e.length===0||e.startsWith(`#`))continue;let r=e.split(/\s+/),i=r[0],a=r[1],o=r[2],s=f(r[3]);if(!i||!a||!o)continue;let c=u(a),l=u(o);if(!d(c)||!d(l))continue;let p={label:i,clientRandom:c,secret:l};s&&(p.timestamp=s),t.push(p)}return t}var h=class{keyLogPath;cachedEntries=[];secretByClientRandom=new Map;constructor(e){this.keyLogPath=a(e??p())}async enableKeyLog(){return await o(i(this.keyLogPath),{recursive:!0}),await s(this.keyLogPath,``,{flag:`a`}),process.env.SSLKEYLOGFILE=this.keyLogPath,this.keyLogPath}async disableKeyLog(){if(process.env.SSLKEYLOGFILE===this.keyLogPath){delete process.env.SSLKEYLOGFILE;return}delete process.env.SSLKEYLOGFILE}getKeyLogFilePath(){return this.keyLogPath}parseKeyLog(e){let t=a(e??this.keyLogPath);if(!n(t))return this.cachedEntries=[],this.secretByClientRandom.clear(),[];let i=m(r(t,`utf8`));this.cachedEntries=i,this.secretByClientRandom.clear();for(let e of i)this.secretByClientRandom.set(e.clientRandom,e.secret);return i}decryptPayload(e,t){let n=u(e);if(!d(n)||t.length===0||!t.some(e=>e.secret.length>0))return null;try{return Buffer.from(n,`hex`)}catch{return null}}summarizeKeyLog(e){let t=this.parseKeyLog(e),n={},r=[];for(let e of t)n[e.label]=(n[e.label]??0)+1,e.timestamp&&r.push(e.timestamp);r.sort((e,t)=>e.localeCompare(t));let i={totalEntries:t.length,entriesByLabel:n};if(r.length>0){let e=r[0],t=r[r.length-1];e&&(i.firstSeen=e),t&&(i.lastSeen=t)}return i}lookupSecret(e){let t=u(e),n=this.secretByClientRandom.get(t);if(n)return n;for(let e of this.cachedEntries.length>0?this.cachedEntries:this.parseKeyLog())if(e.clientRandom===t)return e.secret;return null}};function g(e=`/tmp/sslkeylog.log`){return process.env.SSLKEYLOGFILE=e,e}function _(){delete process.env.SSLKEYLOGFILE}function v(){let e=process.env.SSLKEYLOGFILE;return!e||e.trim().length===0?null:e}function y(e){return e.length===0?[]:e.includes(`
|
|
2
|
-
`)||e.includes(`\r`)||e.includes(`CLIENT_`)||e.trim().startsWith(`#`)?m(e):new h(e).parseKeyLog()}function b(e){let t=[...new Set(e.map(e=>e.label))],n=new Set(e.map(e=>e.clientRandom)).size,r=e.some(e=>e.label.includes(`TRAFFIC_SECRET`));return{totalEntries:e.length,uniqueClients:n,hasClientRandom:t.includes(`CLIENT_RANDOM`),hasTrafficSecrets:r,labels:t}}function x(e,t,n){let r=u(t),i=n?.trim();for(let t of e)if(t.clientRandom===r&&!(i&&t.label!==i))return t.secret;return null}function S(e,t,n,r=`aes-256-gcm`,i){try{let a=Buffer.from(u(e),`hex`),o=c(r,Buffer.from(u(t),`hex`),Buffer.from(u(n),`hex`));if(i){let e=Reflect.get(o,`setAuthTag`);typeof e==`function`&&e.call(o,Buffer.from(u(i),`hex`))}return Buffer.concat([o.update(a),o.final()]).toString(`utf8`)}catch{return`DECRYPTION_FAILED:${r}`}}var C=e({TLSKeyLogExtractor:()=>h});export{g as a,y as c,_ as i,b as l,h as n,v as o,S as r,x as s,C as t};
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./logger-CCikqqvj.mjs";import{$ as t,J as n,Kr as r,Q as i,X as a,Y as o,Z as s,et as c,q as l,tt as u}from"./constants-DMv3svps.mjs";import{c as d,l as f,o as p,s as m,u as h}from"./outputPaths-D2ddHrOJ.mjs";import{i as g,t as _}from"./DetailedDataManager-Z77fDl9Z.mjs";import{t as v}from"./response-B1RuVVfD.mjs";import{t as y}from"./ToolError-g3rjWzhx.mjs";import{a as b,n as x,o as S}from"./modules-DO3jXCgj.mjs";import{r as ee}from"./BrowserSessionCoordinator-QIt3tetp.mjs";import{g as te,v as ne}from"./ensure-browser-core-JHwDo5ql.mjs";import{n as re,t as ie}from"./betterSqlite3-Bdo_ifuJ.mjs";import{t as ae}from"./concurrency-Dehnw4JC.mjs";import{a as C,c as w,n as T,o as E,r as D,s as O,t as k}from"./parse-args-ngRrvF9e.mjs";import{n as A,t as j}from"./ResponseBuilder-nPXl_khE.mjs";import{n as oe}from"./capabilities-L1ax5EHS.mjs";import"./definitions-DBYSxChX.mjs";import{join as se}from"path";import{readFileSync as ce}from"node:fs";import{isAbsolute as le,relative as ue,sep as de}from"node:path";import{randomUUID as fe}from"node:crypto";import{readFile as pe,writeFile as me}from"fs/promises";const M=se(h,`.env`),he=new Set([`stable`,`beta`,`dev`,`canary`]);var ge=class{deps;constructor(e){this.deps=e}pickPreferredAttachPage(e,t){if(e.length===0)return{selectedIndex:0,selected:null};if(t!==null&&t>=0&&t<e.length)return{selectedIndex:t,selected:e[t]??null};let n=e.findIndex(e=>e.url.trim().length>0&&e.url!==`about:blank`);return n>=0?{selectedIndex:n,selected:e[n]??null}:{selectedIndex:0,selected:e[0]??null}}markMonitoringContextChanged(t){try{this.deps.consoleMonitor.markContextChanged()}catch(n){e.warn(`[${t}] Failed to mark monitoring context as stale: ${n instanceof Error?n.message:String(n)}`)}}async syncTabRegistryWithCollectorPages(t){try{let e=await this.deps.collector.listPages();this.deps.getTabRegistry().reconcilePages(e.map(()=>null),e)}catch(n){e.warn(`[${t}] Failed to sync attached tabs into TabRegistry: ${n instanceof Error?n.message:String(n)}`)}}parseHeadlessArg(e){if(typeof e==`boolean`)return e;if(typeof e==`number`)return e===1?!0:e===0?!1:void 0;if(typeof e==`string`){let t=e.trim().toLowerCase();if([`true`,`1`,`yes`,`on`].includes(t))return!0;if([`false`,`0`,`no`,`off`].includes(t))return!1}}parseChromeConnectRequest(e){let t=E(e,`channel`);if(t&&!he.has(t))throw Error(`Invalid channel "${t}". Expected one of: stable, beta, dev, canary.`);return{browserURL:E(e,`browserURL`),wsEndpoint:E(e,`wsEndpoint`),autoConnect:k(e,`autoConnect`),userDataDir:E(e,`userDataDir`),channel:t}}parseChromeLaunchRequest(e){return{headless:this.parseHeadlessArg(e.headless),args:O(e,`args`),enableV8NativesSyntax:k(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 pe(M,`utf-8`)}catch(e){if(e?.code!==`ENOENT`)throw e}let n=`PUPPETEER_HEADLESS=${t}`;await me(M,/^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(E(t,`driver`,`chrome`)===`camoufox`){if(E(t,`mode`,`launch`)===`connect`){let e=E(t,`wsEndpoint`);return e?j.ok().merge({driver:`camoufox`,mode:`connect`,wsEndpoint:e,message:`Connected to Camoufox server. Use page_navigate to begin.`}).json():j.fail(`wsEndpoint is required for connect mode. Use camoufox_server({ action: "launch" }) first to get a wsEndpoint.`).json()}return j.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(E(t,`mode`,`launch`)===`connect`){let e=this.parseChromeConnectRequest(t);if(!this.hasChromeConnectRequest(e))return j.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 j.ok().merge({driver:`chrome`,mode:`connect`,endpoint:this.describeChromeConnectRequest(e),autoConnect:this.isAutoConnectRequest(e),channel:e.channel??null,userDataDir:e.userDataDir??null,manualApprovalMayBeRequired:this.isAutoConnectRequest(e),approvalHint:this.getAutoConnectApprovalHint(e),message:`Connected to existing Chrome browser successfully`,status:n}).json()}let n=this.parseChromeLaunchRequest(t);try{let e=await this.deps.collector.launch(n);e.action===`relaunched`&&this.markMonitoringContextChanged(`browser_launch_relaunch`);let t=await this.deps.collector.listPages(),r=this.deps.getTabRegistry();t.length>0&&(await this.deps.collector.selectPage(0),r.setCurrentByIndex(0));let i=t[0];this.deps.onBrowserAttachStateChanged?.({endpoint:null,selectedIndex:t.length>0?0:null,selectedUrl:i?.url??null,selectedTitle:i?.title??null,selectedTargetId:null,browserPid:this.deps.collector.getChromePid(),rendererPid:null,attachedAt:new Date().toISOString()});let a=await this.deps.collector.getStatus();return j.ok().merge({driver:`chrome`,message:e.action===`relaunched`?`Browser relaunched successfully`:`Browser launched successfully`,launchAction:e.action,relaunchReason:e.reason??null,v8NativeSyntaxEnabled:e.launchOptions.v8NativeSyntaxEnabled,launchArgs:e.launchOptions.args,selectedIndex:t.length>0?0:null,currentUrl:i?.url??null,currentTitle:i?.title??null,totalPages:t.length,status:a}).json()}catch(t){if(!this.shouldAttemptLinuxHeadfulFallback(n.headless,t))throw t;let r=t instanceof Error?t.message:String(t);e.warn(`Headful launch failed on Linux, fallback to headless=true: ${r}`),process.env.PUPPETEER_HEADLESS=`true`,await this.persistHeadlessEnv(`true`);let i=await this.deps.collector.launch({...n,headless:!0}),a=await this.deps.collector.listPages(),o=this.deps.getTabRegistry();a.length>0&&(await this.deps.collector.selectPage(0),o.setCurrentByIndex(0));let s=a[0];this.deps.onBrowserAttachStateChanged?.({endpoint:null,selectedIndex:a.length>0?0:null,selectedUrl:s?.url??null,selectedTitle:s?.title??null,selectedTargetId:null,browserPid:this.deps.collector.getChromePid(),rendererPid:null,attachedAt:new Date().toISOString()});let c=await this.deps.collector.getStatus();return j.ok().merge({driver:`chrome`,message:`Browser launched with Linux fallback (headless=true)`,launchAction:i.action,relaunchReason:i.reason??null,v8NativeSyntaxEnabled:i.launchOptions.v8NativeSyntaxEnabled,launchArgs:i.launchOptions.args,selectedIndex:a.length>0?0:null,currentUrl:s?.url??null,currentTitle:s?.title??null,totalPages:a.length,status:c,fallback:{applied:!0,reason:`Headful browser is unavailable in current Linux runtime; switched to headless and updated .env`,newEnv:`PUPPETEER_HEADLESS=true`}}).json()}}catch(e){return j.fail(e).json()}}async handleBrowserClose(e){try{return await this.deps.collector.close(),j.ok().set(`message`,`Browser closed successfully`).json()}catch(e){return j.fail(e).json()}}async handleBrowserStatus(e){try{let e=await this.deps.collector.getStatus();return j.ok().merge({driver:`chrome`,...e}).json()}catch(e){return j.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 j.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 j.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=D(e,`index`),n=E(e,`urlPattern`),r=E(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`),j.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 j.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`),j.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 j.fail(e).json()}}async handleBrowserAttach(t){let n=null;try{if(n=this.parseChromeConnectRequest(t),!this.hasChromeConnectRequest(n))return j.fail(`browserURL, wsEndpoint, autoConnect, userDataDir, or channel is required`).json();let r=await this.deps.clearAttachedTargetContext(`browser_attach`);await this.deps.collector.connect(n);let i=t.pageIndex,a=i!=null&&!(typeof i==`string`&&i.trim()===``),o=typeof i==`number`?i:typeof i==`string`&&i.trim()!==``?Number(i):0,s=Number.isFinite(o)?o:0,c=await this.deps.collector.listPages(),l=this.pickPreferredAttachPage(c,a?s:null).selectedIndex;c.length>0&&(await this.deps.collector.selectPage(l),s!==l&&e.warn(`[browser_attach] requested pageIndex ${s} resolved to ${l}; preferred non-blank target when available`));let u=this.deps.getTabRegistry();await this.syncTabRegistryWithCollectorPages(`browser_attach`);let d=c.length>0?Math.min(l,c.length-1):0,f=c.length>0?u.setCurrentByIndex(d):null,p=c[d],m=!!f?.pageId,h=this.deps.collector.getChromePid(),g={pageControllerReady:m,v8InspectorReady:m,memoryRendererPidReady:h!==null};m&&this.markMonitoringContextChanged(`browser_attach`);let _=await this.deps.collector.getStatus(),v=this.deps.collector.getAttachedTargetInfo();return this.deps.onBrowserAttachStateChanged?.({endpoint:this.describeChromeConnectRequest(n),selectedIndex:d,selectedUrl:p?.url??null,selectedTitle:p?.title??null,selectedTargetId:v?.targetId??null,browserPid:h,attachedAt:new Date().toISOString()}),j.ok().merge({message:`Attached to existing browser successfully`,endpoint:this.describeChromeConnectRequest(n),autoConnect:this.isAutoConnectRequest(n),channel:n.channel??null,userDataDir:n.userDataDir??null,manualApprovalMayBeRequired:this.isAutoConnectRequest(n),approvalHint:this.getAutoConnectApprovalHint(n),selectedIndex:d,selectedPageId:f?.pageId??null,currentUrl:p?.url??null,currentTitle:p?.title??null,totalPages:c.length,contextSwitched:c.length>0,detachedCdpTarget:r.detached,detachedCdpTargetId:r.targetId,monitoringBindingDeferred:m,networkMonitoringEnabled:!1,consoleMonitoringEnabled:!1,takeoverReady:m,capabilities:g,note:m?`Monitoring will auto-rebind on the next console/network operation for the selected tab.`:`Connected to existing Chrome, but the selected tab does not currently expose a stable Puppeteer Page handle. Tab discovery still works; try selecting a different tab or navigate the tab and retry. V8/page-bound tools will degrade until a stable Page handle is available.`,status:_}).json()}catch(e){return this.deps.onBrowserAttachStateChanged?.({endpoint:n?this.describeChromeConnectRequest(n):null}),j.fail(e).set(`approvalHint`,this.getAutoConnectApprovalHint(n??{})).json()}}};function _e(e){let t=O(e,`addons`),n=O(e,`excludeAddons`),r=O(e,`fonts`);return{headless:k(e,`headless`,!0),os:E(e,`os`,`windows`),geoip:k(e,`geoip`,!1),humanize:k(e,`humanize`,!1),proxy:E(e,`proxy`)||void 0,blockImages:k(e,`blockImages`,!1),blockWebrtc:k(e,`blockWebrtc`,!1),blockWebgl:k(e,`blockWebgl`,!1),locale:E(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:k(e,`customFontsOnly`,!1),screen:e.screen,window:e.window,fingerprint:C(e,`fingerprint`),webglConfig:C(e,`webglConfig`),firefoxUserPrefs:C(e,`firefoxUserPrefs`),mainWorldEval:k(e,`mainWorldEval`,!0),enableCache:k(e,`enableCache`,!1)}}async function ve(){try{return await import(`camoufox-js`),null}catch(e){let t=e instanceof Error?e.message:String(e);return re(e)?`Camoufox requires the same native SQLite backend used by trace tooling. ${ie(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 ye=class{deps;constructor(e){this.deps=e}async handleCamoufoxServerLaunch(t){try{let n=await ve();if(n)return e.warn(`Camoufox dependencies not available: ${n}`),j.fail(n).set(`hint`,`Camoufox is optional. Use browser_launch with Chrome driver instead, or install dependencies.`).json();let r=D(t,`port`),i=E(t,`ws_path`),a=_e(t),o=this.deps.getCamoufoxManager();o||(o=new S(a),this.deps.setCamoufoxManager(o));let s=await o.launchAsServer(r,i);return j.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 j.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(),j.ok().set(`message`,`Camoufox server closed.`).json()):j.fail(`No camoufox server is running.`).json()}catch(e){return j.fail(e).json()}}async handleCamoufoxServerStatus(e){try{let e=this.deps.getCamoufoxManager()?.getBrowserServerEndpoint()??null;return j.ok().merge({running:e!==null,wsEndpoint:e}).json()}catch(e){return j.fail(e).json()}}};const be=new Set(te);function N(e){return T(e,`waitUntil`,be,`networkidle`)}var xe=class{deps;constructor(e){this.deps=e}syncCurrentTabMeta(e,t){let n=this.deps.getTabRegistry?.();if(!n||!e||!t.url||t.title===void 0)return;let r=t.url,i=t.title,a=n.upsertPage(e,{url:r,title:i});n.setCurrentPageId(a)}syncRuntimeAttachMeta(e){this.deps.onBrowserAttachStateChanged&&(!e.url||e.title===void 0||this.deps.onBrowserAttachStateChanged({selectedUrl:e.url,selectedTitle:e.title,rendererPid:null}))}async getChromePageIfAvailable(){let e=this.deps.pageController.getPage;return typeof e==`function`?await Reflect.apply(e,this.deps.pageController,[]):null}async getCamoufoxTitleIfAvailable(e){let t=e.title;if(typeof t!=`function`)return;let n=await Reflect.apply(t,e,[]);return typeof n==`string`?n:void 0}getCamoufoxUrlIfAvailable(e){let t=e.url;if(typeof t!=`function`)return;let n=Reflect.apply(t,e,[]);return typeof n==`string`?n:void 0}async handlePageNavigate(e){return A(async()=>{let t=E(e,`url`,``),n=N(e),r=D(e,`timeout`),i=k(e,`enableNetworkMonitoring`);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.goto(t,{waitUntil:n,timeout:r}),this.deps.consoleMonitor.setPlaywrightPage(e),i&&await this.deps.consoleMonitor.enable({enableNetwork:!0,enableExceptions:!0});let a=this.getCamoufoxUrlIfAvailable(e)??``,o=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:a,title:o}),this.syncRuntimeAttachMeta({url:a,title:o}),this.deps.eventBus?.emit(`browser:navigated`,{url:a,timestamp:new Date().toISOString()}),{driver:`camoufox`,url:a,title:o??``,network_monitoring:{enabled:this.deps.consoleMonitor.isNetworkEnabled()}}}i&&await this.deps.consoleMonitor.enable({enableNetwork:!0,enableExceptions:!0}),await this.deps.pageController.navigate(t,{waitUntil:n,timeout:r});let a=await this.getChromePageIfAvailable(),o=await this.deps.pageController.getURL(),s=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(a,{url:o,title:s}),this.syncRuntimeAttachMeta({url:o,title:s}),this.deps.eventBus?.emit(`browser:navigated`,{url:o,timestamp:new Date().toISOString()}),{url:o,title:s,network_monitoring:{enabled:this.deps.consoleMonitor.isNetworkEnabled()}}})}async handlePageReload(e){return A(async()=>{if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.reload();let t=this.getCamoufoxUrlIfAvailable(e),n=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:t,title:n}),this.syncRuntimeAttachMeta({url:t,title:n}),{message:`Page reloaded`,driver:`camoufox`}}await this.deps.pageController.reload();let e=await this.getChromePageIfAvailable(),t=await this.deps.pageController.getURL(),n=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(e,{url:t,title:n}),this.syncRuntimeAttachMeta({url:t,title:n}),{message:`Page reloaded`}})}async handlePageBack(e){return A(async()=>{let t=D(e,`timeout`,1e4);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.goBack();let t=this.getCamoufoxUrlIfAvailable(e),n=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:t,title:n}),this.syncRuntimeAttachMeta({url:t,title:n}),{url:t,driver:`camoufox`}}await this.deps.pageController.goBack(t);let n=await this.getChromePageIfAvailable(),r=await this.deps.pageController.getURL(),i=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(n,{url:r,title:i}),this.syncRuntimeAttachMeta({url:r,title:i}),{url:r}})}async handlePageForward(e){return A(async()=>{let t=D(e,`timeout`,1e4);if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();await e.goForward();let t=this.getCamoufoxUrlIfAvailable(e),n=await this.getCamoufoxTitleIfAvailable(e);return this.syncCurrentTabMeta(e,{url:t,title:n}),this.syncRuntimeAttachMeta({url:t,title:n}),{url:t,driver:`camoufox`}}await this.deps.pageController.goForward(t);let n=await this.getChromePageIfAvailable(),r=await this.deps.pageController.getURL(),i=await this.deps.pageController.getTitle();return this.syncCurrentTabMeta(n,{url:r,title:i}),this.syncRuntimeAttachMeta({url:r,title:i}),{url:r}})}},Se=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=E(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=E(e,`frameUrl`),s=E(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 j.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}),j.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 j.ok().build({message:`Clicked ${t} - navigation triggered`,navigated:!0,...c?{frame:c}:{}});throw e}return j.ok().build({message:`Clicked: ${t}`,...c?{frame:c}:{}})}catch(e){return j.fail(e).build()}}async handlePageType(e){return A(async()=>{let t=E(e,`selector`,``),n=E(e,`text`,``),r=D(e,`delay`),i=E(e,`frameUrl`),a=E(e,`frameSelector`),o=i||a?{frameUrl:i||void 0,frameSelector:a||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(o)).fill(t,n),{driver:`camoufox`,message:`Typed into ${t}`,...o?{frame:o}:{}}):(o?await this.deps.pageController.type(t,n,{delay:r},o):await this.deps.pageController.type(t,n,{delay:r}),{message:`Typed into ${t}`,...o?{frame:o}:{}})})}async handlePageUploadFiles(e){try{let t=E(e,`selector`,``),n=O(e,`paths`).map(e=>e.trim()).filter(Boolean),r=E(e,`frameUrl`),i=E(e,`frameSelector`),a=r||i?{frameUrl:r||void 0,frameSelector:i||void 0}:void 0;if(!t||t.trim().length===0)return j.fail(`selector parameter is required`).build();if(n.length===0)return j.fail(`paths parameter must contain at least one relative file path`).build();let o=n.map(e=>m(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`?j.fail(`File input not found: ${t}`).build({driver:`camoufox`}):(await r.setInputFiles(o),j.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),j.ok().build({selector:t,count:o.length,paths:n,message:`Uploaded ${o.length} file(s) into ${t}`,...a?{frame:a}:{}})}catch(e){return j.fail(e).build()}}async handlePageSelect(e){return A(async()=>{let t=E(e,`selector`,``),n=O(e,`values`),r=E(e,`frameUrl`),i=E(e,`frameSelector`),a=r||i?{frameUrl:r||void 0,frameSelector:i||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(a)).selectOption(t,n),{driver:`camoufox`,message:`Selected in ${t}: ${n.join(`, `)}`,...a?{frame:a}:{}}):(a?await this.deps.pageController.select(t,n,a):await this.deps.pageController.select(t,n),{message:`Selected in ${t}: ${n.join(`, `)}`,...a?{frame:a}:{}})})}async handlePageHover(e){return A(async()=>{let t=E(e,`selector`,``),n=E(e,`frameUrl`),r=E(e,`frameSelector`),i=n||r?{frameUrl:n||void 0,frameSelector:r||void 0}:void 0;return this.deps.getActiveDriver()===`camoufox`?(await(await this.getCamoufoxInteractionContext(i)).hover(t),{driver:`camoufox`,message:`Hovered: ${t}`,...i?{frame:i}:{}}):(i?await this.deps.pageController.hover(t,i):await this.deps.pageController.hover(t),{message:`Hovered: ${t}`,...i?{frame:i}:{}})})}async handlePageScroll(e){return A(async()=>{let t=D(e,`x`,0),n=D(e,`y`,0);return this.deps.getActiveDriver()===`camoufox`?(await(await this.deps.getCamoufoxPage()).evaluate(e=>{window.scrollTo(e.x||0,e.y||0)},{x:t,y:n}),{driver:`camoufox`,message:`Scrolled to: x=${t||0}, y=${n||0}`}):(await this.deps.pageController.scroll({x:t,y:n}),{message:`Scrolled to: x=${t||0}, y=${n||0}`})})}async handlePagePressKey(e){return A(async()=>{let t=E(e,`key`,``);return this.deps.getActiveDriver()===`camoufox`?(await(await this.deps.getCamoufoxPage()).keyboard.press(t),{driver:`camoufox`,key:t}):(await this.deps.pageController.pressKey(t),{key:t})})}};function P(e,t){if(Array.isArray(e))return e.map(e=>P(e,t));if(typeof e==`object`&&e){let n=e,r={};for(let[e,i]of Object.entries(n))t.has(e)||(r[e]=P(i,t));return r}return e}function F(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=>F(e));if(typeof e==`object`&&e){let t=e,n={};for(let[e,r]of Object.entries(t))n[e]=F(r);return n}return e}function I(e,t,n){let r=n.autoSummarize?t.smartHandle(e,n.maxSize):e;return n.fieldFilter&&n.fieldFilter.length>0&&(r=P(r,new Set(n.fieldFilter))),n.stripBase64&&(r=F(r)),r}var Ce=class{deps;constructor(e){this.deps=e}resolveEvaluationSource(e){let t=E(e,`script`,``)||E(e,`code`,``)||E(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=k(e,`autoSummarize`,!0),r=D(e,`maxSize`,51200),i=O(e,`fieldFilter`),a=k(e,`stripBase64`,!1),o=E(e,`frameUrl`),s=E(e,`frameSelector`);if(!t)return j.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=I(await e.evaluate(o),this.deps.detailedDataManager,{autoSummarize:n,maxSize:r,fieldFilter:i??void 0,stripBase64:a});return j.ok().build({driver:`camoufox`,...c?{frame:c}:{},result:s})}let l=I(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 j.ok().build({...c?{frame:c}:{},result:l})}catch(e){return j.fail(e).build()}}async handlePageScreenshot(e){try{let t=E(e,`path`),n=E(e,`type`,`png`),r=D(e,`quality`),i=k(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:f}=await d({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 j.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 j.ok().build({driver:`camoufox`,selector:c||void 0,clip:a||void 0,message:`Screenshot taken: ${u}`,path:u,pathRewritten:f,size:t?.length??0})}let p;if(c){let e=await(await this.deps.pageController.getPage()).$(c);if(!e)return j.fail(`Element not found: ${c}`).build();p=await e.screenshot({path:l,type:n,quality:r})}else p=await this.deps.pageController.screenshot({path:l,type:n,quality:r,fullPage:a?!1:i,clip:a});return j.ok().build({selector:c||void 0,clip:a||void 0,message:`Screenshot taken: ${u}`,path:u,pathRewritten:f,size:p.length})}catch(e){return j.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 d({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 j.ok().build({mode:`batch`,total:e.length,succeeded:a.filter(e=>e.success).length,results:a})}async handlePageInjectScript(e){try{let t=E(e,`script`,``);return await this.deps.pageController.injectScript(t),j.ok().build({message:`Script injected`})}catch(e){return j.fail(e).build()}}async handlePageWaitForSelector(e){try{let t=E(e,`selector`,``),n=D(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 j.ok().build({driver:`camoufox`,element:r,message:`Selector appeared: ${t}`})}catch{return j.fail(`Timeout waiting for selector: ${t}`).build({driver:`camoufox`})}}let r=await this.deps.pageController.waitForSelector(t,n);return j.ok().merge(r).build()}catch(e){return j.fail(e).build()}}},we=class{deps;constructor(e){this.deps=e}safeOrigin(e){try{return new URL(e).origin}catch{return null}}async listCamoufoxFrames(){let e=this.deps.getCamoufoxPage;if(!e)throw Error(`Camoufox page is not available`);let t=await e(),n=t.frames(),r=t.mainFrame(),i=this.safeOrigin(r.url());return n.map((e,t)=>{let a=e.parentFrame(),o=this.safeOrigin(e.url()),s=a?n.findIndex(e=>e===a):-1;return{frameId:`frame-${t}`,url:e.url(),name:e.name()||``,parentFrameId:s>=0?`frame-${s}`:null,parentUrl:a?.url()||null,isMainFrame:e===r,crossOrigin:!!(e!==r&&o&&i&&o!==i)}})}async handlePageListFrames(e){return A(async()=>{let e=this.deps.getActiveDriver()===`camoufox`?await this.listCamoufoxFrames():await this.deps.pageController.listFrames();return{count:e.length,frames:e}})}async handleGetContent(e){return A(async()=>({html:await this.deps.pageController.getContent()}))}async handleGetTitle(e){return A(async()=>({title:await this.deps.pageController.getTitle()}))}async handleGetUrl(e){return A(async()=>({url:await this.deps.pageController.getURL()}))}async handleGetText(e){return A(async()=>{let t=E(e,`selector`,``);return{selector:t,text:await this.deps.pageController.evaluate(`document.querySelector(${JSON.stringify(t)})?.textContent || ""`)}})}async handleGetOuterHtml(e){return A(async()=>{let t=E(e,`selector`,``);return{selector:t,html:await this.deps.pageController.evaluate(`document.querySelector(${JSON.stringify(t)})?.outerHTML || ""`)}})}async handleGetScrollPosition(e){return A(async()=>await this.deps.pageController.evaluate(`({
|
|
2
|
-
scrollX: window.scrollX,
|
|
3
|
-
scrollY: window.scrollY,
|
|
4
|
-
maxScrollX: document.documentElement.scrollWidth - window.innerWidth,
|
|
5
|
-
maxScrollY: document.documentElement.scrollHeight - window.innerHeight
|
|
6
|
-
})`))}async handlePageSetCookies(e){return A(async()=>{let t=e.cookies;return await this.deps.pageController.setCookies(t),{message:`Set ${t.length} cookies`}})}async handlePageGetCookies(e){return A(async()=>{let e=await this.deps.pageController.getCookies();return{count:e.length,cookies:e}})}async getPageCookieCount(){return(await this.deps.pageController.getCookies()).length}async handlePageClearCookies(e){return A(async()=>(await this.deps.pageController.clearCookies(),{message:`Cookies cleared`}))}async handlePageSetViewport(e){return A(async()=>{let t=D(e,`width`,0),n=D(e,`height`,0);return await this.deps.pageController.setViewport(t,n),{viewport:{width:t,height:n}}})}async handlePageEmulateDevice(e){return A(async()=>{let t=E(e,`device`,``);return await this.deps.pageController.emulateDevice(t),{device:t}})}async handlePageGetLocalStorage(e){return A(async()=>{let e=await this.deps.pageController.getLocalStorage();return{count:Object.keys(e).length,storage:e}})}async handlePageSetLocalStorage(e){return A(async()=>{let t=E(e,`key`,``),n=E(e,`value`,``);return await this.deps.pageController.setLocalStorage(t,n),{key:t}})}},Te=class{deps;constructor(e){this.deps=e}async handleConsoleMonitor(e){return A(async()=>E(e,`action`)===`enable`?(await this.deps.consoleMonitor.enable(),{message:`Console monitoring enabled`}):(await this.deps.consoleMonitor.disable(),{message:`Console monitoring disabled`}))}async handleConsoleGetLogs(e){return A(async()=>{let t=E(e,`type`),n=D(e,`limit`),r=D(e,`since`),i=this.deps.consoleMonitor.getLogs({type:t,limit:n,since:r});return this.deps.detailedDataManager.smartHandle({count:i.length,logs:i},51200)})}async handleConsoleExecute(e){return A(async()=>{let t=E(e,`expression`,``),n=D(e,`maxSize`,10485760),r=k(e,`stripBase64`,!1);if(!t.trim())throw Error(`expression is required`);return{result:I(await this.deps.consoleMonitor.execute(t),this.deps.detailedDataManager,{autoSummarize:!0,maxSize:n,stripBase64:r})}})}},Ee=class{deps;constructor(e){this.deps=e}async handleGetAllScripts(e){return A(async()=>{let t=k(e,`includeSource`,!1),n=Math.min(D(e,`maxScripts`,t?200:1e3),r),i=await this.deps.scriptManager.getAllScripts(t,n);return this.deps.detailedDataManager.smartHandle({count:i.length,scripts:i})})}async handleGetScriptSource(e){return A(async()=>{let t=E(e,`scriptId`),n=E(e,`url`),r=k(e,`preview`,!0),i=D(e,`maxLines`,100),a=D(e,`startLine`),o=D(e,`endLine`),s=await this.deps.scriptManager.getScriptSource(t,n);if(!s)throw Error(`Script not found`);if(r||a!==void 0||o!==void 0){let e=s.source||``,t=e.split(`
|
|
7
|
-
`),n=t.length,r=e.length,c,l,u;return a!==void 0&&o!==void 0?(l=Math.max(1,a),u=Math.min(n,o),c=t.slice(l-1,u).join(`
|
|
8
|
-
`)):(l=1,u=Math.min(i,n),c=t.slice(0,i).join(`
|
|
9
|
-
`)),{scriptId:s.scriptId,url:s.url,preview:!0,totalLines:n,size:r,sizeKB:(r/1024).toFixed(1)+`KB`,showingLines:`${l}-${u}`,content:c,hint:r>51200?`Script is large (${(r/1024).toFixed(1)}KB). Use startLine/endLine to get specific sections, or set preview=false to get full source (will return detailId).`:`Set preview=false to get full source`}}return this.deps.detailedDataManager.smartHandle(s,51200)})}},De=class{deps;constructor(e){this.deps=e}async handleCaptchaDetect(e){return A(async()=>{let e=await this.deps.pageController.getPage(),t=await this.deps.captchaDetector.detect(e);return{captcha_detected:t.detected,captcha_info:t}})}async handleCaptchaWait(t){return A(async()=>{let n=D(t,`timeout`,this.deps.captchaTimeout),r=await this.deps.pageController.getPage();if(e.info(`Waiting for CAPTCHA to be solved...`),!await this.deps.captchaDetector.waitForCompletion(r,n))throw Error(`CAPTCHA wait timed out`);return{message:`CAPTCHA solved`}})}async handleCaptchaConfig(e){return A(async()=>(e.autoDetectCaptcha!==void 0&&this.deps.setAutoDetectCaptcha(k(e,`autoDetectCaptcha`,!1)),e.autoSwitchHeadless!==void 0&&this.deps.setAutoSwitchHeadless(k(e,`autoSwitchHeadless`,!1)),e.captchaTimeout!==void 0&&this.deps.setCaptchaTimeout(D(e,`captchaTimeout`,0)),{config:{autoDetectCaptcha:this.deps.autoDetectCaptcha,autoSwitchHeadless:this.deps.autoSwitchHeadless,captchaTimeout:this.deps.captchaTimeout}}))}};const Oe={enabled:!0,minDelayMs:20,maxDelayMs:80,burstMode:!1};var ke=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 Ae=[{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`}],L={...Oe};let R=null;const z=ke.getInstance();async function B(){if(R)return R;try{return R=(await import(`./FingerprintManager-BkDSsjjP.mjs`)).FingerprintManager.getInstance(),R}catch{return null}}var je=class{deps;constructor(e){this.deps=e}async handleStealthInject(t){try{if(this.deps.getActiveDriver()===`camoufox`)return j.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 B(),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 x.injectAll(t),r&&n){let e=n.getActiveProfile(),t=z.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};z.setProfile(r)}return j.ok().build({message:`Stealth scripts injected successfully`,fingerprintApplied:r,patchManifest:Ae,_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 j.fail(e).build()}}async handleStealthSetUserAgent(e){try{let t=E(e,`platform`,`windows`),n=await this.deps.pageController.getPage();return await x.setRealisticUserAgent(n,t),j.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 j.fail(e).build()}}async handleStealthConfigureJitter(e){try{return e.enabled!==void 0&&(L.enabled=!!e.enabled),typeof e.minDelayMs==`number`&&(L.minDelayMs=e.minDelayMs),typeof e.maxDelayMs==`number`&&(L.maxDelayMs=e.maxDelayMs),e.burstMode!==void 0&&(L.burstMode=!!e.burstMode),j.ok().build({jitterOptions:L,message:`CDP timing jitter ${L.enabled?`enabled`:`disabled`}: ${L.minDelayMs}-${L.maxDelayMs}ms${L.burstMode?` (burst mode)`:``}`})}catch(e){return j.fail(e).build()}}async handleStealthGenerateFingerprint(e){try{if(this.deps.getActiveDriver()===`camoufox`)try{let t=await import(`camoufox-js/fingerprints`),n=E(e,`os`,`windows`),r=await t.generateFingerprint(n);return j.ok().build({fingerprint:r,driver:`camoufox`,message:`Fingerprint generated using camoufox native engine. Apply via browser_launch(fingerprint=...) before launching.`})}catch(e){return j.fail(`Camoufox fingerprint generation failed: ${e instanceof Error?e.message:String(e)}`).build()}let t=await B();if(!t?.isAvailable())return j.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 j.ok().build({profile:n,message:`Fingerprint generated and cached. It will be auto-applied on next stealth_inject.`})}catch(e){return j.fail(e).build()}}async handleStealthVerify(e){try{let e=await this.deps.pageController.getPage(),t=await new(await(import(`./StealthVerifier-DMBrtkhN.mjs`))).StealthVerifier().verify(e);return j.ok().merge(t).build()}catch(e){return j.fail(`Stealth verification failed: ${e instanceof Error?e.message:String(e)}`).build()}}async handleCamoufoxGeolocation(e){try{let t=E(e,`locale`);if(!t)return j.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 j.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=E(e,`proxy`);if(i)try{r=await(await import(`camoufox-js/ip`)).publicIP(i)}catch{}return j.ok().build({locale:t,geolocation:n,publicIp:r})}catch(e){return j.fail(e).build()}}},Me=class{deps;constructor(e){this.deps=e}async handleFrameworkStateExtract(e){let t=E(e,`framework`,`auto`),n=E(e,`selector`,``),r=D(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 ne(`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 j.ok().build(a)}catch(e){return j.fail(e).build()}}},Ne=class{deps;constructor(e){this.deps=e}async handleIndexedDBDump(e){let t=E(e,`database`,``),n=E(e,`store`,``),r=D(e,`maxRecords`,100);return A(async()=>await(await this.deps.getActivePage()).evaluate(async e=>{let t=await indexedDB.databases(),n={};for(let r of t){if(!r.name||e.database&&r.name!==e.database)continue;let t=r.name,i;try{i=await new Promise((e,n)=>{let i=r.version?indexedDB.open(t,r.version):indexedDB.open(t);i.addEventListener(`success`,()=>e(i.result),{once:!0}),i.addEventListener(`error`,()=>n(i.error),{once:!0})})}catch{n[t]={__error__:[`failed to open`]};continue}let a=Array.from(i.objectStoreNames),o={};for(let t of a)if(!(e.store&&t!==e.store))try{o[t]=await new Promise((n,r)=>{try{let a=i.transaction(t,`readonly`).objectStore(t).getAll();a.addEventListener(`success`,()=>n(a.result.slice(0,e.maxRecords)),{once:!0}),a.addEventListener(`error`,()=>r(a.error),{once:!0})}catch(e){r(e)}})}catch{o[t]=[`__error reading store__`]}i.close(),n[t]=o}return n},{database:t,store:n,maxRecords:r}))}},Pe=class{deps;constructor(e){this.deps=e}async handleGetDetailedData(e){try{let t=E(e,`detailId`,``),n=E(e,`path`),r=this.deps.detailedDataManager.retrieve(t,n);return j.ok().build({detailId:t,path:n||`full`,data:r})}catch(e){return j.fail(e).set(`hint`,`DetailId may have expired (TTL: 10 minutes) or is invalid`).build()}}async handleGetOffloadedData(e){try{let t=E(e,`path`,``),n=T(e,`encoding`,new Set([`base64`,`utf8`]),`base64`);if(!t)return j.fail(`path is required`).build();let r=m(t),i=ue(g(),r);if(i===``||i===`..`||i.startsWith(`..${de}`)||le(i))return j.fail(`path must point inside the offloaded artifacts directory (artifacts/offloaded/)`).build();let a=ce(r);return j.ok().build({path:t,encoding:n,size:a.length,data:a.toString(n)})}catch(e){return j.fail(e).set(`hint`,`Offloaded file may have been cleaned up by artifact retention, or the path is invalid`).build()}}},Fe=class{deps;constructor(e){this.deps=e}async handleBrowserEvaluateCdpTarget(t){try{let e=E(t,`script`,``)||E(t,`code`,``)||E(t,`expression`,``),n=k(t,`autoSummarize`,!0),r=D(t,`maxSize`,51200),i=O(t,`fieldFilter`),a=k(t,`stripBase64`,!1),o=k(t,`returnByValue`,!0),s=k(t,`awaitPromise`,!0);if(!e.trim())return j.fail(`code, script, or expression is required`).build();let c=this.deps.pageController.getAttachedTargetInfo();if(!c)return j.fail(`No CDP target is currently attached. Call browser_attach_cdp_target(targetId="...") first.`).build();let l=I(await this.deps.pageController.evaluateAttachedTarget(e,{returnByValue:o,awaitPromise:s}),this.deps.detailedDataManager,{autoSummarize:n,maxSize:r,fieldFilter:i??void 0,stripBase64:a});return j.ok().build({target:c,result:l})}catch(t){return e.error(`Failed to evaluate in CDP target:`,t),j.fail(t instanceof Error?t.message:String(t)).build()}}},Ie=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=E(t,`type`),n=O(t,`types`),r=E(t,`targetId`),i=E(t,`urlPattern`),a=E(t,`titlePattern`),o=k(t,`attachedOnly`,!1),s=k(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 j.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),j.fail(t instanceof Error?t.message:String(t)).build()}}async handleBrowserAttachCdpTarget(t){try{let e=E(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`),j.ok().build({attached:!0,target:n,...r})}catch(t){return e.error(`Failed to attach CDP target:`,t),j.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`),j.ok().build({detached:t,targetId:e?.targetId??null})}catch(t){return e.error(`Failed to detach CDP target:`,t),j.fail(t instanceof Error?t.message:String(t)).build()}}};const Le=[`hidden`,`array`,`string`,`object`,`code`,`closure`,`regexp`,`number`,`native`,`synthetic`,`concatenated string`,`sliced string`,`symbol`,`bigint`];function V(e){return typeof e==`object`&&!!e}function Re(e){return V(e)&&typeof e.createCDPSession==`function`}function ze(e){return V(e)&&typeof e.chunk==`string`}var Be=class{deps;detailedDataManager;constructor(e){this.deps=e,this.detailedDataManager=_.getInstance()}async handleJSHeapSearch(t){let n=E(t,`pattern`,``)||E(t,`query`,``),r=D(t,`maxResults`,50),i=k(t,`caseSensitive`,!1);return n?ae(async()=>{let t=null,a=!1;try{let o=await this.deps.getActivePage();if(!Re(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=>{ze(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 j.ok().build(this.detailedDataManager.smartHandle(d,51200))}catch(t){return e.error(`[js_heap_search] Error:`,t),j.fail(t).build()}finally{if(a&&t)try{await t.detach()}catch{}}}):j.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)??Le[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 Ve=new Set([`alias_bind`,`alias_open`,`navigate`,`wait_for`,`context_set`,`context_get`,`transfer`,`list`,`clear`]);function H(e){return typeof e==`object`&&!!e}function He(e){return typeof e==`string`&&Ve.has(e)}function U(e){return H(e)&&typeof e.goto==`function`&&typeof e.waitForSelector==`function`&&typeof e.evaluate==`function`&&typeof e.url==`function`&&typeof e.title==`function`}function W(e){return!U(e)||!H(e)?!1:typeof e.context==`function`}function Ue(e){return H(e)&&typeof e.newPage==`function`&&typeof e.pages==`function`}function G(e){return typeof e==`string`&&e.length>0?e:null}function We(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 Ge(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:t}var Ke=class{deps;constructor(e){this.deps=e}get registry(){return this.deps.getTabRegistry()}async handleTabWorkflow(t){let n=t.action;try{if(!He(n))return j.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}),j.fail(i).build()}}listAliases(){let e=this.registry.getCurrentTabInfo(this.deps.getActiveDriver()),t=this.registry.getSharedContextMap();return j.ok().build({aliases:e.aliases,staleAliases:e.staleAliases,currentPageId:e.currentPageId,currentIndex:e.currentIndex,currentUrl:e.url,context:t})}clearState(){return this.registry.clear(),j.ok().build({cleared:!0})}async aliasBind(e){let t=G(e.alias),n=We(e.index);if(!t)return j.fail(`alias is required`).build();if(n===null)return j.fail(`index is required`).build();await this.reconcilePages();let r=this.registry.bindAliasByIndex(t,n);return r?j.ok().build({bound:{alias:t,index:n,pageId:r}}):j.fail(`No active page at index ${n}. Use browser_list_tabs to check available pages.`).build()}async aliasOpen(e){let t=G(e.alias),n=G(e.url);if(!t)return j.fail(`alias is required`).build();if(!n)return j.fail(`url is required`).build();if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();if(!W(e))return j.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),j.ok().build({alias:t,index:a,pageId:s,url:i.url(),title:o})}let r=await this.getBrowserFromController();if(!r)return j.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),j.ok().build({alias:t,index:a,pageId:s,url:i.url(),title:o})}async navigateAlias(e){let t=G(e.alias),n=G(e.url);if(!t)return j.fail(`alias is required`).build();if(!n)return j.fail(`url is required`).build();let r=await this.getPageByAlias(t);return r?(await r.goto(n,{waitUntil:`domcontentloaded`}),j.ok().build({alias:t,navigated:n,currentUrl:r.url()})):j.fail(`No tab found for alias "${t}". Use alias_bind or alias_open first.`).build()}async waitFor(e){let t=G(e.alias),n=G(e.selector),r=G(e.waitForText),i=Ge(e.timeoutMs,1e4);if(!t)return j.fail(`alias is required`).build();if(!n&&!r)return j.fail(`selector or waitForText is required`).build();let a=await this.getPageByAlias(t);if(!a)return j.fail(`No tab found for alias "${t}"`).build();if(n)return await a.waitForSelector(n,{timeout:i}),j.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 j.ok().build({alias:t,waitedForText:o,found:!0});await new Promise(e=>setTimeout(e,500))}return j.fail(`Timeout waiting for text "${o}" in tab "${t}"`).build()}contextSet(e){let t=G(e.key),n=e.value;return t?(this.registry.setSharedContext(t,n),j.ok().build({set:{key:t,value:n}})):j.fail(`key is required`).build()}contextGet(e){let t=G(e.key);if(!t)return j.fail(`key is required`).build();let{value:n,found:r}=this.registry.getSharedContext(t);return j.ok().build({key:t,value:n,found:r})}async transfer(e){let t=G(e.fromAlias),n=G(e.key),r=G(e.expression);if(!t)return j.fail(`fromAlias is required`).build();if(!n)return j.fail(`key is required`).build();if(!r)return j.fail(`expression is required`).build();let i=await this.getPageByAlias(t);if(!i)return j.fail(`No tab found for alias "${t}"`).build();let a=await i.evaluate(r);return this.registry.setSharedContext(n,a),j.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&&U(n))return n;await this.reconcilePages();let r=this.registry.getPageById(t);return r&&U(r)?r:null}async reconcilePages(){if(this.deps.getActiveDriver()===`camoufox`){let e=await this.deps.getCamoufoxPage();if(W(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(!H(e)||typeof e.getBrowser!=`function`)return null;let t=await e.getBrowser();return Ue(t)?t:null}};const qe=new Set([`none`,`outside-only`,`dangerously`]),Je=new Set([`get`,`set`,`clear`]),K=10*1024*1024,q=600*1e3;var Ye=class{sessions=new Map;createSessionId(){return fe()}scheduleExpiry(t){let n=setTimeout(()=>{e.debug(`JSDOM session ${t} expired after ${q}ms`),this.closeSession(t)},q);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=w(e,`html`);if(Buffer.byteLength(t,`utf8`)>K)return j.fail(`HTML input exceeds ${K/1024/1024}MB limit. Provide smaller HTML or use a URL.`).build();let n=E(e,`url`,`about:blank`),r=E(e,`contentType`,`text/html`),i=T(e,`runScripts`,qe,`none`),a=k(e,`includeNodeLocations`,!1),o=k(e,`pretendToBeVisual`,!1),s=E(e,`referrer`,``),c=D(e,`storageQuotaBytes`,1e6);if(this.sessions.size>=5)return j.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 j.ok().set(`sessionId`,f).set(`title`,m.title||``).set(`url`,n).set(`contentType`,r).set(`runScripts`,i).set(`ttlMs`,q).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 j.fail(e).build()}}async handleJsdomQuery(e){try{let t=w(e,`sessionId`),n=w(e,`selector`),r=D(e,`maxResults`,50),i=k(e,`includeHtml`,!1),a=k(e,`includeText`,!0),o=k(e,`includeLocation`,!1),s=O(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 j.ok().set(`sessionId`,t).set(`selector`,n).set(`matched`,u.length).set(`returned`,d.length).set(`results`,d).build()}catch(e){return j.fail(e).build()}}async handleJsdomExecute(e){try{let t=w(e,`sessionId`),n=w(e,`code`),r=D(e,`timeoutMs`,5e3),i=this.getSession(t);if(i.runScripts===`none`)return j.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?j.ok().set(`sessionId`,t).set(`result`,J(c)).set(`consoleLogs`,a).set(`timeoutHintMs`,r).build():j.fail(l).set(`consoleLogs`,a).build()}catch(e){return j.fail(e).build()}}async handleJsdomSerialize(e){try{let t=w(e,`sessionId`),n=k(e,`pretty`,!1),r=E(e,`selector`,``),i=this.getSession(t),a;if(r){let e=i.dom.window.document.querySelector(r);if(!e)return j.fail(`No element matches selector: ${r}`).build();a=e.outerHTML}else a=i.dom.serialize();return n&&(a=$e(a)),j.ok().set(`sessionId`,t).set(`bytes`,Buffer.byteLength(a,`utf8`)).set(`pretty`,n).set(`html`,a).build()}catch(e){return j.fail(e).build()}}async handleJsdomCookies(e){try{let t=w(e,`sessionId`),n=T(e,`action`,Je,`get`),r=this.getSession(t),i=r.dom.cookieJar,a=E(e,`url`,r.url);if(n===`get`){let e=await i.getCookies(a);return j.ok().set(`sessionId`,t).set(`url`,a).set(`cookies`,e.map(Xe)).build()}if(n===`set`){let n=C(e,`cookie`);if(!n)return j.fail(`cookie object required for action="set"`).build();let r=typeof n.raw==`string`?n.raw:Ze(n);return await i.setCookie(r,a),j.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())),j.ok().set(`sessionId`,t).set(`action`,`clear`).build()}catch(e){return j.fail(e).build()}}};function Xe(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 Ze(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=>J(e))});let r=e?.[i];if(typeof r==`function`)try{r.apply(e,n)}catch{}};return r}function J(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 $e(e){return e.replace(/>(?=<)/g,`>
|
|
10
|
-
`)}function et(e){let t={getActiveDriver:e.getActiveDriver,getCamoufoxPage:e.getCamoufoxPage},n=new ee,r=e.getTabRegistry??(()=>n),i=new Ie({collector:e.collector,consoleMonitor:e.consoleMonitor,getTabRegistry:r});return{tabRegistry:n,targetControl:i,browserControl:new ge({collector:e.collector,pageController:e.pageController,consoleMonitor:e.consoleMonitor,getActiveDriver:e.getActiveDriver,getCamoufoxManager:e.getCamoufoxManager,getCamoufoxPage:e.getCamoufoxPage,getTabRegistry:r,clearAttachedTargetContext:e=>i.clearAttachedTargetContext(e),onBrowserAttachStateChanged:e.onBrowserAttachStateChanged}),camoufoxBrowser:new ye({getCamoufoxManager:e.getCamoufoxManager,setCamoufoxManager:e.setCamoufoxManager,closeCamoufox:e.closeCamoufox}),pageNavigation:new xe({pageController:e.pageController,consoleMonitor:e.consoleMonitor,getTabRegistry:r,eventBus:e.eventBus,onBrowserAttachStateChanged:e.onBrowserAttachStateChanged,...t}),pageInteraction:new Se({pageController:e.pageController,...t}),pageEvaluation:new Ce({pageController:e.pageController,detailedDataManager:e.detailedDataManager,...t}),targetEvaluation:new Fe({pageController:e.pageController,detailedDataManager:e.detailedDataManager}),pageData:new we({pageController:e.pageController,...t}),consoleHandlers:new Te({consoleMonitor:e.consoleMonitor,detailedDataManager:e.detailedDataManager}),scriptManagement:new Ee({scriptManager:e.scriptManager,detailedDataManager:e.detailedDataManager}),captchaHandlers:new De({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 je({pageController:e.pageController,...t}),frameworkState:new Me({getActivePage:()=>e.collector.getActivePage()}),indexedDBDump:new Ne({getActivePage:()=>e.collector.getActivePage()}),jsHeapSearch:new Be({getActivePage:()=>e.collector.getActivePage(),getActiveDriver:e.getActiveDriver}),tabWorkflow:new Ke({getActiveDriver:e.getActiveDriver,getCamoufoxPage:e.getCamoufoxPage,getPageController:()=>e.pageController,getTabRegistry:r}),detailedData:new Pe({detailedDataManager:e.detailedDataManager}),jsdomHandlers:new Ye}}function tt(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 nt(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 rt(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 Y(e){return new Promise(t=>setTimeout(t,e))}function X(e){let t=E(e,`frameUrl`),n=E(e,`frameSelector`);if(!(!t&&!n))return{frameUrl:t||void 0,frameSelector:n||void 0}}async function Z(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 it(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 at(e,t,n){return A(async()=>{let r=X(e),i=await Z(t,n,r);if(!i)throw Error(`No active page. Use browser_launch or browser_attach first.`);let{page:a,context:o}=i,s=D(e,`toX`),c=D(e,`toY`),l=E(e,`selector`);if(l){let e=await o.evaluate(e=>{let t=document.querySelector(e);if(!t)return null;let n=t.getBoundingClientRect();return{x:n.x+n.width/2,y:n.y+n.height/2}},l);if(!e)throw Error(`Selector not found: ${l}`);let t=await it(a,o,e);s=t.x,c=t.y}if(s===void 0||c===void 0)throw Error(`Either selector or toX/toY coordinates are required`);let u=D(e,`fromX`,0),d=D(e,`fromY`,0),f=Math.max(1,Math.min(D(e,`steps`,24),500)),p=Math.max(10,Math.min(D(e,`durationMs`,600),3e4)),m=Math.max(0,Math.min(D(e,`jitterPx`,1.5),20)),h=E(e,`curve`,`ease`),g=k(e,`click`,!1),_={x:u,y:d},v={x:s,y:c},[y,b]=nt(_,v),x=p/f;for(let e=0;e<=f;e++){let t=tt(_,y,b,v,rt(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 Y(x*(.8+Math.random()*.4))}return g&&await a.mouse.click(s,c),{from:{x:u,y:d},to:{x:s,y:c},steps:f,durationMs:p,clicked:g,...r?{frame:r}:{}}})}async function ot(e,t){return A(async()=>{let n=await t.getActivePage();if(!n)throw Error(`No active page.`);let r=Math.max(1,Math.min(D(e,`distance`,500),1e4)),i=E(e,`direction`,`down`),a=Math.max(10,Math.min(D(e,`durationMs`,1500),3e4)),o=Math.max(1,Math.min(D(e,`segments`,8),200)),s=typeof e.pauseMs==`number`&&Number.isFinite(e.pauseMs)?Math.max(0,Math.min(D(e,`pauseMs`,80),5e3)):Math.max(0,Math.min(Math.round(a/o),5e3)),c=Math.max(0,Math.min(D(e,`jitter`,.3),1)),l=E(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 Y(s*(.5+Math.random()))}return{direction:i,requestedDistance:r,actualScrolled:Math.round(f),durationMs:a,pauseMs:s,segments:o}})}async function st(e,t,n){return A(async()=>{let r=X(e),i=await Z(t,n,r);if(!i)throw Error(`No active page.`);let{page:a,context:o}=i,s=E(e,`selector`,``),c=E(e,`text`,``),l=Math.max(10,Math.min(D(e,`wpm`,90),300)),u=Math.max(0,Math.min(D(e,`errorRate`,.02),.3)),d=Math.max(50,Math.min(D(e,`correctDelayMs`,200),2e3)),f=k(e,`clearFirst`,!1);if(!s||!c)throw Error(`selector and text are required`);let p=6e4/(l*5);await o.click(s),f&&await o.evaluate(e=>{let t=document.querySelector(e);t&&(t.value=``)},s);let m=0;for(let e of c){if(Math.random()<u&&e!==` `){let t=String.fromCharCode(e.charCodeAt(0)+(Math.random()>.5?1:-1));await a.keyboard.type(t,{delay:0}),await Y(d*(.5+Math.random())),await a.keyboard.press(`Backspace`),await Y(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 Y(t)}return{selector:s,length:c.length,wpm:l,typosSimulated:m,errorRate:u,...r?{frame:r}:{}}})}function Q(e){return new Promise(t=>setTimeout(t,e))}function ct(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 lt(e){let t=typeof e==`string`?e.toLowerCase():``;return t===`image`?`image`:t===`widget`||t===`recaptcha_v2`||t===`recaptcha_v3`||t===`hcaptcha`||t===`funcaptcha`||t===`turnstile`?`widget`:t===`browser_check`||t===`managed_widget`?`browser_check`:`image`}function ut(e){let t=typeof e==`string`?e.toLowerCase():``;if(t===`image`||t===`recaptcha_v2`||t===`recaptcha_v3`||t===`hcaptcha`||t===`funcaptcha`||t===`turnstile`)return t}function dt(e,t){return ut(e)||(t===`image`?`image`:`recaptcha_v2`)}function ft(e){return e!==`image`}function pt(e){if(!(typeof e!=`string`||!e.trim()))return e.trim().toLowerCase()}function mt(e){let t=pt(e.provider),n=(process.env.CAPTCHA_PROVIDER||``).trim().toLowerCase();return t||n||`2captcha`}function ht(e){return e===`2captcha`?process.env.CAPTCHA_SOLVER_BASE_URL?.trim()||process.env.CAPTCHA_2CAPTCHA_BASE_URL?.trim()||c:e===`anticaptcha`?process.env.CAPTCHA_ANTICAPTCHA_BASE_URL?.trim()||``:e===`capsolver`&&process.env.CAPTCHA_CAPSOLVER_BASE_URL?.trim()||``}function gt(e,t){return e===`anticaptcha`?t===`recaptcha_v2`?`RecaptchaV2TaskProxyless`:t===`hcaptcha`?`HCaptchaTaskProxyless`:t===`turnstile`?`TurnstileTaskProxyless`:`ImageToTextTask`:e===`capsolver`?t===`recaptcha_v2`?`ReCaptchaV2TaskProxyLess`:t===`hcaptcha`?`HCaptchaTaskProxyLess`:t===`turnstile`?`AntiTurnstileTaskProxyLess`:`ImageToTextTask`:``}async function _t(e,n,r,a){let o=Date.now(),s=ht(e);if(!s)throw Error(`${e} base URL is not configured.`);let c=gt(e,r.taskKind),l=r.taskKind===`image`?{type:c,body:r.imageBase64}:{type:c,websiteURL:r.pageUrl,websiteKey:r.siteKey},d=await(await fetch(`${s}/createTask`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({clientKey:n,task:l}),signal:AbortSignal.timeout(u)})).json();if(d.errorId&&d.errorId!==0)throw Error(`${e} createTask failed: ${String(d.errorCode??d.errorDescription??JSON.stringify(d))}`);let f=d.taskId;if(typeof f!=`number`&&typeof f!=`string`)throw Error(`${e} createTask did not return a taskId.`);for(;;){let c=a-(Date.now()-o);if(c<=0||(await Q(Math.min(i,c)),Date.now()-o>=a))break;let l=await(await fetch(`${s}/getTaskResult`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({clientKey:n,taskId:f}),signal:AbortSignal.timeout(t)})).json();if(l.errorId&&l.errorId!==0)throw Error(`${e} getTaskResult failed: ${String(l.errorCode??l.errorDescription??JSON.stringify(l))}`);if(l.status===`processing`||l.status===`idle`)continue;if(l.status!==`ready`)throw Error(`${e} returned unexpected status: ${String(l.status)}`);let u=typeof l.solution==`object`&&l.solution!==null?l.solution:null,d=typeof u?.gRecaptchaResponse==`string`?u.gRecaptchaResponse:typeof u?.token==`string`?u.token:typeof u?.text==`string`?u.text:``;if(!d)throw Error(`${e} returned ready without a usable solution token.`);return{token:d,challengeType:r.taskKind===`image`?`image`:`widget`,mode:`external_service`,durationMs:Date.now()-o}}throw Error(`${e} solve timeout after ${a}ms`)}async function vt(e){if(typeof e.screenshot==`function`)return(await e.screenshot({type:`png`})).toString(`base64`);throw Error(`Could not capture image CAPTCHA payload from the current page.`)}function yt(e){if(typeof e!=`string`)return;let t=e.trim();if(t){if(t.startsWith(`data:`)){let e=t.indexOf(`,`);return e>=0?t.slice(e+1):void 0}return t}}function bt(e){return{enabled:k(e,`injectToken`,!0),responseSelector:E(e,`responseSelector`,``).trim()||void 0,callbackName:E(e,`callbackName`,``).trim()||void 0}}async function xt(e,t,n){await e.evaluate((e,t)=>{let{responseSelector:n,callbackName:r}=t;if(n){let t=document.querySelector(n);t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement?(t.value=e,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0}))):t instanceof HTMLElement&&(t.setAttribute(`data-captcha-token`,e),t.dispatchEvent(new CustomEvent(`captcha-token`,{detail:e})))}if(r){let t=window[r];typeof t==`function`&&t(e)}},t,n)}async function St(e,n,r){let a=Date.now(),o=ht(`2captcha`);if(!o)throw Error(`CAPTCHA_SOLVER_BASE_URL must be configured before using external_service mode.`);let s={key:e,json:1};n.taskKind===`turnstile`||n.taskKind===`recaptcha_v2`||n.taskKind===`hcaptcha`?(s.method=n.taskKind===`turnstile`?`turnstile`:n.taskKind===`hcaptcha`?`hcaptcha`:`userrecaptcha`,s.sitekey=n.siteKey,s.pageurl=n.pageUrl):(s.method=`base64`,s.body=n.imageBase64);let c=await(await fetch(`${o}/in.php`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s),signal:AbortSignal.timeout(u)})).json();if(c.status!==1)throw Error(`2captcha submit failed: ${JSON.stringify(c)}`);let l=c.request,d=i;for(;;){let i=r-(Date.now()-a);if(i<=0||(await Q(Math.min(d,i)),Date.now()-a>=r))break;let s=new URL(`${o}/res.php`);s.searchParams.set(`key`,e),s.searchParams.set(`action`,`get`),s.searchParams.set(`id`,l),s.searchParams.set(`json`,`1`);let c=await(await fetch(s.toString(),{signal:AbortSignal.timeout(t)})).json();if(c.status===1)return{token:c.request,challengeType:n.taskKind===`image`?`image`:`widget`,mode:`external_service`,durationMs:Date.now()-a};if(c.request!==`CAPCHA_NOT_READY`)throw Error(`2captcha solve failed: ${JSON.stringify(c)}`)}throw Error(`2captcha solve timeout after ${r}ms`)}async function Ct(t,r){let i=await r.getActivePage();if(!i)return j.fail(`No active page.`).build();let c=ct(t.mode??t.provider??process.env.CAPTCHA_PROVIDER),u=mt(t),d=E(t,`apiKey`,``)||process.env.CAPTCHA_API_KEY||``,f=lt(t.challengeType??t.typeHint),p=dt(t.taskKind,f),m=Math.min(Math.max(D(t,`timeoutMs`,n),s),a),h=Math.min(Math.max(D(t,`maxRetries`,l),0),o),g=f,_=E(t,`siteKey`),v=E(t,`pageUrl`,``)||i.url();if(ft(p)&&!_)return j.fail(`Widget solving requires an explicit siteKey.`).build();if(c===`manual`)return j.ok().build({mode:`manual`,challengeType:g,siteKey:_??null,instruction:`Please solve the CAPTCHA manually in the browser, then continue.`,hint:`Configure an external solver service and CAPTCHA_API_KEY to automate this flow.`});if(!d)return j.fail(`External solver credentials are required. Set CAPTCHA_API_KEY.`).build();if(![`2captcha`,`anticaptcha`,`capsolver`].includes(u))return j.fail(`Unsupported external solver service.`).build();let y=null;for(let n=0;n<=h;n++)try{let e=p===`image`?yt(t.imageBase64)??await vt(i):void 0,r=u===`2captcha`?await St(d,{taskKind:p,siteKey:_,pageUrl:v,imageBase64:e},m):await _t(u,d,{taskKind:p,siteKey:_,pageUrl:v,imageBase64:e},m);return j.ok().build({token:r.token,challengeType:r.challengeType,mode:r.mode,durationMs:r.durationMs,attempt:n+1})}catch(t){y=t instanceof Error?t:Error(String(t)),e.warn(`[captcha] Attempt ${n+1} failed: ${y.message}`)}return j.fail(y??Error(`All attempts failed`)).merge({challengeType:g,mode:c,maxRetries:h,suggestion:`Try manual mode or adjust the external solver configuration.`}).build()}async function wt(e,t){let n=await t.getActivePage();if(!n)return j.fail(`No active page.`).build();let r=ct(e.mode??e.provider??process.env.CAPTCHA_PROVIDER),i=mt(e),a=E(e,`apiKey`,``)||process.env.CAPTCHA_API_KEY||``,o=Math.min(Math.max(D(e,`timeoutMs`,12e4),5e3),6e5),s=bt(e),c=dt(e.taskKind,`widget`),l=E(e,`siteKey`),u=E(e,`pageUrl`,``)||n.url();if(r===`hook`){if(!l)return j.fail(`Widget solving requires an explicit siteKey.`).build();let t=Math.min(o,3e4),r=E(e,`callbackName`,``).trim();if(!r)return j.fail(`Hook mode requires an explicit callbackName.`).build();let i=await n.evaluate((e,t)=>new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`Hook timeout`)),e),a=window[t];if(typeof a==`function`){let e=a;window[t]=t=>(clearTimeout(i),n(t),e(t))}else clearTimeout(i),r(Error(`The requested callbackName is not a callable function.`))}),t,r).catch(()=>null);if(i)return j.ok().build({token:i,method:`hook`,challengeType:`widget`,siteKey:l,callbackName:r})}if(r===`manual`)return j.ok().build({mode:`manual`,challengeType:`widget`,siteKey:l||null,pageUrl:u,instruction:`Please complete the widget challenge manually.`});if(!l)return j.fail(`Widget solving requires an explicit siteKey.`).build();if(!a)return j.fail(`External solver credentials are required.`).build();try{let e=i===`2captcha`?await St(a,{taskKind:c,siteKey:l,pageUrl:u},o):i===`anticaptcha`||i===`capsolver`?await _t(i,a,{taskKind:c,siteKey:l,pageUrl:u},o):(()=>{throw Error(`Unsupported external solver service.`)})();return s.enabled&&e.token&&await xt(n,e.token,{responseSelector:s.responseSelector,callbackName:s.callbackName}),j.ok().build({token:e.token,challengeType:e.challengeType,siteKey:l,mode:e.mode,durationMs:e.durationMs,taskKind:c,injected:s.enabled,responseSelector:s.responseSelector??null,callbackName:s.callbackName??null})}catch(e){return j.fail(e).merge({siteKey:l,mode:r,suggestion:`Try manual mode or hook mode.`}).build()}}function $(){return(process.env.CAPTCHA_PROVIDER||``).trim().toLowerCase()||`manual`}function Tt(){return process.env.CAPTCHA_SOLVER_BASE_URL?.trim()||process.env.CAPTCHA_2CAPTCHA_BASE_URL?.trim()||``}function Et(e){return e===`2captcha`?Tt():e===`anticaptcha`?process.env.CAPTCHA_ANTICAPTCHA_BASE_URL?.trim()||``:process.env.CAPTCHA_CAPSOLVER_BASE_URL?.trim()||``}function Dt(){let e=$(),t=Et(`2captcha`),n=!!process.env.CAPTCHA_API_KEY?.trim(),r=t.length>0,i=n&&r;return{capability:`captcha_external_service_2captcha`,status:i?`available`:`unavailable`,reason:i?void 0:`The 2captcha-compatible external path needs both CAPTCHA_API_KEY and CAPTCHA_SOLVER_BASE_URL.`,fix:i?void 0:`Set CAPTCHA_API_KEY and CAPTCHA_SOLVER_BASE_URL to enable external_service mode.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:e,defaultExternalProviderSupported:e===`2captcha`,apiKeyConfigured:n,baseUrlConfigured:r,...r?{baseUrl:t}:{}}}}function Ot(e){let t=$(),n=Et(e),r=!!process.env.CAPTCHA_API_KEY?.trim(),i=r&&n.length>0;return{capability:`captcha_external_service_${e}`,status:i?`available`:`unavailable`,reason:i?void 0:`${e} requires CAPTCHA_API_KEY and a reachable API base URL.`,fix:i?void 0:`Set CAPTCHA_API_KEY and ${e===`anticaptcha`?`CAPTCHA_ANTICAPTCHA_BASE_URL`:`CAPTCHA_CAPSOLVER_BASE_URL`}.`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`],configuredProvider:t,defaultExternalProviderSupported:t===e,apiKeyConfigured:r,baseUrlConfigured:n.length>0,baseUrl:n}}}async function kt(e){let t;try{t=await e.getActivePage()}catch(e){return{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`Current page availability check failed: ${e instanceof Error?e.message:String(e)}`,fix:`Attach or launch a browser page before using hook mode.`,details:{tools:[`widget_challenge_solve`],pageAttached:!1}}}return t?{capability:`captcha_widget_hook_current_page`,status:`available`,reason:`Hook mode is available when the caller provides an explicit callbackName.`,details:{tools:[`widget_challenge_solve`],pageAttached:!0,requiresExplicitCallbackName:!0,requiresExplicitSiteKey:!0}}:{capability:`captcha_widget_hook_current_page`,status:`unknown`,reason:`No active page is attached.`,fix:`Attach or launch a browser page before using hook mode.`,details:{tools:[`widget_challenge_solve`],pageAttached:!1}}}async function At(e){let t=$(),n=await kt(e);return j.raw(oe(`captcha_solver_capabilities`,[{capability:`captcha_manual`,status:`available`,details:{tools:[`captcha_vision_solve`,`widget_challenge_solve`]}},Dt(),Ot(`anticaptcha`),Ot(`capsolver`),n],{configuredProvider:t}))}function jt(e){let t=O(e,`addons`),n=O(e,`excludeAddons`),r=O(e,`fonts`);return{headless:k(e,`headless`,!0),os:E(e,`os`,`windows`),geoip:k(e,`geoip`,!1),humanize:k(e,`humanize`,!1),proxy:E(e,`proxy`)||void 0,blockImages:k(e,`blockImages`,!1),blockWebrtc:k(e,`blockWebrtc`,!1),blockWebgl:k(e,`blockWebgl`,!1),locale:E(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:k(e,`customFontsOnly`,!1),screen:e.screen,window:e.window,fingerprint:C(e,`fingerprint`),webglConfig:C(e,`webglConfig`),firefoxUserPrefs:C(e,`firefoxUserPrefs`),mainWorldEval:k(e,`mainWorldEval`,!0),enableCache:k(e,`enableCache`,!1)}}async function Mt(e,t){return A(async()=>{let n=jt(t);if(E(t,`mode`,`launch`)===`connect`){let r=E(t,`wsEndpoint`);if(!r)throw Error(`wsEndpoint is required for connect mode.`);let i=new S(n);return await i.connectToServer(r),e.setCamoufoxManager(i),e.setActiveDriver(`camoufox`),e.clearCamoufoxPage(),{driver:`camoufox`,mode:`connect`,wsEndpoint:r,message:`Connected to Camoufox server.`}}let r=new S(n);return await r.launch(),e.setCamoufoxManager(r),e.setActiveDriver(`camoufox`),e.clearCamoufoxPage(),{driver:`camoufox`,mode:`launch`,config:{os:n.os,headless:n.headless,geoip:n.geoip,humanize:n.humanize,locale:n.locale,blockWebgl:n.blockWebgl,blockImages:n.blockImages,blockWebrtc:n.blockWebrtc},message:`Camoufox (Firefox) browser launched`}})}async function Nt(e,t){return A(async()=>{let n=E(t,`url`,``),r=N(t),i=D(t,`timeout`),a=await e.getCamoufoxPage();return await a.goto(n,{waitUntil:r,timeout:i}),e.setConsoleMonitorPage(a),{driver:`camoufox`,url:a.url(),title:await a.title()}})}const Pt=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 Ft=class{collector;pageController;scriptManager;consoleMonitor;captchaDetector;detailedDataManager;camoufoxManager=null;activeDriver=`chrome`;camoufoxPage=null;autoDetectCaptcha=!0;autoSwitchHeadless=!0;captchaTimeout=3e5;browserControl;targetControl;camoufoxBrowser;pageNavigation;pageInteraction;pageEvaluation;targetEvaluation;pageData;consoleHandlers;scriptManagement;captchaHandlers;stealthInjection;frameworkState;indexedDBDump;jsHeapSearch;tabWorkflow;detailedData;jsdomHandlers;tabRegistry;eventBus;getCurrentSessionId;sessionCoordinator;onBrowserAttachStateChanged;codegenStopListening;codegenSteps=[];constructor(e,t,n,r,i,a,o,s){this.collector=e,this.pageController=t,this.scriptManager=n,this.consoleMonitor=r,this.eventBus=i,this.getCurrentSessionId=a,this.sessionCoordinator=o,this.onBrowserAttachStateChanged=s;let c=p(f().paths.captchaScreenshotDir,`screenshots/captcha`);this.captchaDetector=new b(c),this.detailedDataManager=_.getInstance();let l=et({collector:this.collector,pageController:this.pageController,scriptManager:this.scriptManager,consoleMonitor:this.consoleMonitor,eventBus:i,captchaDetector:this.captchaDetector,detailedDataManager:this.detailedDataManager,getActiveDriver:()=>this.activeDriver,getCamoufoxPage:()=>this.getCamoufoxPage(),getCamoufoxManager:()=>this.camoufoxManager,setCamoufoxManager:e=>{this.camoufoxManager=e},closeCamoufox:()=>this.closeCamoufox(),getAutoDetectCaptcha:()=>this.autoDetectCaptcha,getAutoSwitchHeadless:()=>this.autoSwitchHeadless,getCaptchaTimeout:()=>this.captchaTimeout,setAutoDetectCaptcha:e=>{this.autoDetectCaptcha=e},setAutoSwitchHeadless:e=>{this.autoSwitchHeadless=e},setCaptchaTimeout:e=>{this.captchaTimeout=e},getTabRegistry:()=>this.getCurrentTabRegistry(),onBrowserAttachStateChanged:this.onBrowserAttachStateChanged});this.browserControl=l.browserControl,this.targetControl=l.targetControl,this.camoufoxBrowser=l.camoufoxBrowser,this.pageNavigation=l.pageNavigation,this.pageInteraction=l.pageInteraction,this.pageEvaluation=l.pageEvaluation,this.targetEvaluation=l.targetEvaluation,this.pageData=l.pageData,this.consoleHandlers=l.consoleHandlers,this.scriptManagement=l.scriptManagement,this.captchaHandlers=l.captchaHandlers,this.stealthInjection=l.stealthInjection,this.frameworkState=l.frameworkState,this.indexedDBDump=l.indexedDBDump,this.jsHeapSearch=l.jsHeapSearch,this.tabWorkflow=l.tabWorkflow,this.detailedData=l.detailedData,this.jsdomHandlers=l.jsdomHandlers,this.tabRegistry=l.tabRegistry}makeJsonResponse(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}sanitizeCodegenArgs(e){let t={...e};for(let e of[`delay`,`timeout`])t[e]===void 0&&delete t[e];return t}getCurrentTabRegistry(){let e=this.getCurrentSessionId?.()??null;return this.sessionCoordinator?.getTabRegistry(e)??this.tabRegistry}isSameFrameArgs(e,t){return(e.frameUrl??null)===(t.frameUrl??null)&&(e.frameSelector??null)===(t.frameSelector??null)}compactCodegenSteps(e){let t=[];for(let n of e){let e={tool:n.tool,args:this.sanitizeCodegenArgs(n.args),timestamp:n.timestamp},r=t.at(-1);if(!r){t.push(e);continue}if(e.tool===`page_wait_for_selector`&&r.tool===`page_wait_for_selector`&&e.args.selector===r.args.selector&&this.isSameFrameArgs(e.args,r.args)){r.timestamp=e.timestamp;continue}if(!(e.tool===`page_wait_for_selector`&&(r.tool===`page_click`||r.tool===`page_type`)&&e.args.selector===r.args.selector&&this.isSameFrameArgs(e.args,r.args))){if(e.tool===r.tool&&JSON.stringify(e.args)===JSON.stringify(r.args)){r.timestamp=e.timestamp;continue}t.push(e)}}return t}formatCodegenScript(e){return[`const steps = [`,...e.map(e=>` ${JSON.stringify({tool:e.tool,args:e.args},null,0)},`),`];`,``,`for (const step of steps) {`,` await callTool(step.tool, step.args);`,`}`].join(`
|
|
11
|
-
`)}getTabRegistry(){return this.getCurrentTabRegistry()}async getCamoufoxPage(){if(!this.camoufoxManager)throw Error(`Camoufox browser not launched. Call browser_launch(driver="camoufox") first.`);return this.camoufoxPage||=await this.camoufoxManager.newPage(),this.camoufoxPage}async closeCamoufox(){try{await this.consoleMonitor.disable()}catch(t){e.warn(`Failed to reset console monitor before closing Camoufox: ${String(t)}`)}this.consoleMonitor.clearPlaywrightPage(),this.camoufoxManager&&(await this.camoufoxManager.close(),this.camoufoxManager=null,this.camoufoxPage=null)}async handleBrowserLaunch(e){return E(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 v(new y(`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):v(new y(`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 v(new y(`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 v(new y(`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||Pt.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 handleGetOffloadedData(e){return this.detailedData.handleGetOffloadedData(e)}async handleCamoufoxLaunch(e){return Mt({setCamoufoxManager:e=>{this.camoufoxManager=e},setActiveDriver:e=>{this.activeDriver=e},clearCamoufoxPage:()=>{this.camoufoxPage=null}},e)}async handleCamoufoxNavigate(e){return Nt({getCamoufoxPage:()=>this.getCamoufoxPage(),setConsoleMonitorPage:e=>{this.consoleMonitor.setPlaywrightPage(e)}},e)}async handleHumanMouse(e){return at(e,this.collector,this.pageController)}async handleHumanScroll(e){return ot(e,this.collector)}async handleHumanTyping(e){return st(e,this.collector,this.pageController)}async handleCaptchaVisionSolve(e){return Ct(e,this.collector)}async handleWidgetChallengeSolve(e){return wt(e,this.collector)}async handleCaptchaSolverCapabilities(){return At(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{Ft as BrowserToolHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as e}from"./ensure-browser-core-JHwDo5ql.mjs";import{ConsoleMonitor as t}from"./ConsoleMonitor-DIjN5Afa.mjs";export{e as CodeCollector,t as ConsoleMonitor};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./chunk-88NL7fhV.mjs";import{cpus as t}from"node:os";var n=e({ACTIVATION_BOOST_WINDOW_MS:()=>Se,ACTIVATION_COMPOUND_EVAL_EVERY:()=>be,ACTIVATION_COOLDOWN_MS:()=>ye,ACTIVATION_EVENT_HISTORY_MAX:()=>xe,ACTIVATION_TTL_MINUTES:()=>de,ADB_COLD_START_LOGCAT_TAIL_DEFAULT:()=>Xn,ADB_COLD_START_LOGCAT_TAIL_MAX:()=>Qn,ADB_COLD_START_LOGCAT_TAIL_MIN:()=>Zn,ADB_COLD_START_TIMELINE_LIMIT:()=>$n,ADB_COLD_START_WAIT_MS_DEFAULT:()=>Jn,ADB_COLD_START_WAIT_MS_MAX:()=>Yn,ADB_DEFAULT_TIMEOUT_MS:()=>Ln,ADB_FILE_TRANSFER_TIMEOUT_MS:()=>Vn,ADB_LARGE_OUTPUT_MAX_BUFFER_BYTES:()=>Bn,ADB_LOGCAT_MAX_LINES_DEFAULT:()=>Kn,ADB_LOGCAT_MAX_LINES_MAX:()=>qn,ADB_LOGCAT_TAIL_DEFAULT:()=>Wn,ADB_LOGCAT_TAIL_MAX:()=>Gn,ADB_MAX_BUFFER_BYTES:()=>zn,ADB_PACKAGE_COMPONENT_LIMIT:()=>Hn,ADB_SHELL_TIMEOUT_MS:()=>Rn,ADB_WEBVIEW_HOST_PORT_DEFAULT:()=>er,ANALYSIS_MAX_SAFE_COLLECTED_BYTES:()=>Ot,ANALYSIS_MAX_SAFE_RESPONSE_BYTES:()=>kt,ANALYSIS_MAX_SUMMARY_FILES:()=>Dt,APK_STATIC_TRIAGE_ASSET_HINT_LIMIT:()=>cr,APK_STATIC_TRIAGE_DEFAULT_ENTRIES:()=>or,APK_STATIC_TRIAGE_MAX_ENTRIES:()=>sr,APK_STATIC_TRIAGE_MIN_ENTRIES:()=>ar,APK_STATIC_TRIAGE_NATIVE_LIB_LIMIT:()=>lr,APK_ZIP_MAGIC_HEX_HEADERS:()=>Un,AUTOPRUNE_AUTO_INACTIVITY_MS:()=>pe,AUTOPRUNE_CHECK_INTERVAL_MS:()=>he,AUTOPRUNE_MANUAL_INACTIVITY_MS:()=>me,BINARY_STRINGS_MAX_RESULTS_DEFAULT:()=>vr,BINARY_STRINGS_MAX_RESULTS_LIMIT:()=>yr,BINARY_STRINGS_MIN_LENGTH_CEILING:()=>_r,BINARY_STRINGS_MIN_LENGTH_DEFAULT:()=>hr,BINARY_STRINGS_MIN_LENGTH_FLOOR:()=>gr,BINARY_STRINGS_PRINTABLE_ASCII_MAX:()=>xr,BINARY_STRINGS_PRINTABLE_ASCII_MIN:()=>br,BOT_DETECT_LIMIT_DEFAULT:()=>Gr,BREAKPOINT_HIT_TIMEOUT_MS:()=>cn,BREAKPOINT_TRACE_MAX_HITS:()=>ln,CACHE_GLOBAL_MAX_SIZE_BYTES:()=>Lt,CACHE_LOW_HIT_RATE_THRESHOLD:()=>Rt,CAPTCHA_DEFAULT_RETRIES:()=>X,CAPTCHA_DEFAULT_TIMEOUT_MS:()=>K,CAPTCHA_MAX_RETRIES:()=>Y,CAPTCHA_MAX_TIMEOUT_MS:()=>J,CAPTCHA_MIN_TIMEOUT_MS:()=>q,CAPTCHA_POLL_INTERVAL_MS:()=>W,CAPTCHA_RESULT_TIMEOUT_MS:()=>G,CAPTCHA_SCREENSHOT_FALLBACK_DIR:()=>CAPTCHA_SCREENSHOT_FALLBACK_DIR,CAPTCHA_SOLVER_BASE_URL:()=>m,CAPTCHA_SUBMIT_TIMEOUT_MS:()=>U,CDEX_MAGIC_ASCII:()=>mr,CDP_JSON_LIST_PATH:()=>CDP_JSON_LIST_PATH,CDP_JSON_VERSION_PATH:()=>CDP_JSON_VERSION_PATH,CDP_LOOPBACK_HOST:()=>CDP_LOOPBACK_HOST,CODE_CAVE_MIN_SIZE:()=>sn,COMPOUND_EVENT_WINDOW_MS:()=>Ce,COMPOUND_LONG_WINDOW_MS:()=>we,COORDINATION_GOTO_TIMEOUT_MS:()=>ni,DART_ALLOWED_REGEX_FLAGS:()=>bi,DART_CHUNK_OVERLAP_BYTES:()=>pi,DART_DEFAULT_ENCODING:()=>gi,DART_MAX_CHUNK_BYTES:()=>fi,DART_MAX_FILES_PER_PACKAGE:()=>wi,DART_MAX_MAP_BYTES:()=>Si,DART_MAX_OFFSETS_PER_STRING:()=>_i,DART_MAX_PACKAGES_PER_RESULT:()=>Ci,DART_MAX_REGEX_PATTERN_LENGTH:()=>vi,DART_MAX_SMI_VALUE:()=>xi,DART_MIN_LENGTH:()=>di,DART_PP_MAX_DUMP_DURATION_MS:()=>$,DART_PP_MAX_SLOTS:()=>Oi,DART_PP_PREVIEW_BYTES:()=>ki,DART_PRINTABLE_ASCII_MAX:()=>hi,DART_PRINTABLE_ASCII_MIN:()=>mi,DART_REGEX_TIMEOUT_MS:()=>yi,DART_SNAPSHOT_HEADER_SCAN_MAX_BYTES:()=>Ei,DART_SNAPSHOT_MAX_FILE_BYTES:()=>Ti,DART_SNAPSHOT_TABLE_PATH:()=>Di,DEBUGGER_WAIT_FOR_PAUSED_TIMEOUT_MS:()=>P,DEBUG_PORT_CANDIDATES:()=>u,DEFAULT_DEBUG_PORT:()=>d,DETAILED_DATA_DEFAULT_TTL_MS:()=>Bt,DETAILED_DATA_MAX_TTL_MS:()=>Vt,DETAILED_DATA_SMART_THRESHOLD_BYTES:()=>Ht,DEX_MAGIC_ASCII:()=>pr,DEX_SCAN_DEFAULT_MAX_HITS:()=>ur,DEX_SCAN_MAX_EXTRACT_BYTES:()=>fr,DEX_SCAN_MAX_HITS:()=>dr,DOM_QUERY_DEFAULT_LIMIT:()=>Zr,DOM_WAIT_ELEMENT_TIMEOUT_MS:()=>Qr,ENABLE_INJECTION_TOOLS:()=>$t,EXTENSION_GIT_CHECKOUT_TIMEOUT_MS:()=>vt,EXTENSION_GIT_CLONE_TIMEOUT_MS:()=>_t,EXTERNAL_TOOL_FORCE_KILL_GRACE_MS:()=>S,EXTERNAL_TOOL_MAX_STDERR_BYTES:()=>xt,EXTERNAL_TOOL_MAX_STDOUT_BYTES:()=>bt,EXTERNAL_TOOL_PROBE_CACHE_TTL_MS:()=>x,EXTERNAL_TOOL_PROBE_TIMEOUT_MS:()=>b,EXTERNAL_TOOL_TIMEOUT_MS:()=>y,FREEZE_DEFAULT_INTERVAL_MS:()=>mn,FRIDA_DEX_DUMP_FILE_LIMIT:()=>wr,FRIDA_DEX_DUMP_MAX_BUFFER_BYTES:()=>Cr,FRIDA_DEX_DUMP_TIMEOUT_MS:()=>Sr,FRIDA_TIMEOUT_MS:()=>jn,GHIDRA_BRIDGE_ENDPOINT:()=>f,GHIDRA_TIMEOUT_MS:()=>Mn,GRAPHQL_MAX_GRAPH_EDGES:()=>Et,GRAPHQL_MAX_GRAPH_NODES:()=>Tt,GRAPHQL_MAX_PREVIEW_CHARS:()=>St,GRAPHQL_MAX_QUERY_CHARS:()=>wt,GRAPHQL_MAX_SCHEMA_CHARS:()=>Ct,HEAP_ENUMERATE_MAX_BLOCKS:()=>un,HEAP_SPRAY_SIZE_TOLERANCE:()=>fn,HEAP_SPRAY_THRESHOLD:()=>dn,HEAP_SUSPICIOUS_BLOCK_SIZE:()=>pn,HTTP_CLEANUP_INTERVAL_MS:()=>Or,HTTP_RATE_LIMIT_MAX_IPS:()=>Dr,ICMP_DEFAULT_PACKET_SIZE:()=>ti,ICMP_PROBE_TIMEOUT_MS:()=>$r,ICMP_TRACEROUTE_MAX_HOPS:()=>ei,IDA_BRIDGE_ENDPOINT:()=>p,JSVMP_DEOBFUSCATE_TIMEOUT_MS:()=>A,JSVMP_MAX_ITERATIONS:()=>j,JSVMP_SYMBOLIC_MAX_STEPS:()=>M,JSVMP_SYMBOLIC_TIMEOUT_MS:()=>N,MACRO_BUILTIN_TIMEOUT_MS:()=>Jr,MACRO_DEFAULT_TIMEOUT_MS:()=>qr,MCP_ARTIFACTS_HAR_DIR:()=>MCP_ARTIFACTS_HAR_DIR,MCP_ARTIFACTS_REPORTS_DIR:()=>MCP_ARTIFACTS_REPORTS_DIR,MCP_COMPACT_SCHEMA:()=>kr,MCP_HTTP_FORCE_CLOSE_TIMEOUT_MS:()=>v,MCP_HTTP_HEADERS_TIMEOUT_MS:()=>g,MCP_HTTP_KEEPALIVE_TIMEOUT_MS:()=>_,MCP_HTTP_REQUEST_TIMEOUT_MS:()=>h,MCP_LOG_ENABLED:()=>ci,MCP_LOG_FILE_DIR:()=>ui,MCP_LOG_LEVEL:()=>li,MEMORY_AUDIT_TRAIL_CAPACITY:()=>ri,MEMORY_AVAILABILITY_CACHE_TTL_MS:()=>Er,MEMORY_DUMP_TIMEOUT_MS:()=>Jt,MEMORY_INJECT_TIMEOUT_MS:()=>Qt,MEMORY_MAX_READ_BYTES:()=>Gt,MEMORY_MAX_WRITE_BYTES:()=>qt,MEMORY_MODULES_TIMEOUT_MS:()=>si,MEMORY_PROBE_CMD_TIMEOUT_MS:()=>ai,MEMORY_PROCESS_SIGNAL_TIMEOUT_MS:()=>ii,MEMORY_PROTECTION_PWSH_TIMEOUT_MS:()=>nn,MEMORY_PROTECTION_QUERY_TIMEOUT_MS:()=>tn,MEMORY_READ_TIMEOUT_MS:()=>Wt,MEMORY_SCAN_MAX_BUFFER_BYTES:()=>Xt,MEMORY_SCAN_MAX_RESULTS:()=>Zt,MEMORY_SCAN_TIMEOUT_MS:()=>Yt,MEMORY_VMMAP_ENUM_TIMEOUT_MS:()=>oi,MEMORY_VMMAP_TIMEOUT_MS:()=>en,MEMORY_WRITE_TIMEOUT_MS:()=>Kt,MOJO_MONITOR_TIMEOUT_MS:()=>Tr,NATIVE_ADMIN_CHECK_TIMEOUT_MS:()=>rn,NEMU_MAX_SESSIONS:()=>In,NEMU_SESSION_IDLE_TTL_MS:()=>Pn,NEMU_SESSION_SWEEP_MS:()=>Fn,NETWORK_HAR_BODY_CONCURRENCY:()=>ie,NETWORK_REPLAY_MAX_REDIRECTS:()=>Z,OFFLOAD_FIELD_SANITIZE_THRESHOLD_BYTES:()=>Ut,PAGE_FRAME_SELECTOR_TIMEOUT_MS:()=>Yr,PAGE_NETWORK_IDLE_TIMEOUT_MS:()=>Xr,POINTER_CHAIN_MAX_DEPTH:()=>wn,POINTER_CHAIN_MAX_OFFSET:()=>Tn,POINTER_CHAIN_MAX_RESULTS:()=>En,POINTER_CHAIN_SCAN_CHUNK_SIZE:()=>Dn,PREDICTIVE_CONFIDENCE_THRESHOLD:()=>_e,PREDICTIVE_DECAY_FACTOR:()=>ve,PREDICTIVE_MAX_HISTORY:()=>ge,PREDICTIVE_MAX_SECOND_ORDER_KEYS:()=>gt,PROCESS_LAUNCH_WAIT_MS:()=>Q,PROCESS_LIST_MAX_BUFFER_BYTES:()=>yt,PROTO_HTTP_CONFIDENCE:()=>Ur,PROTO_SSH_CONFIDENCE:()=>Wr,PROTO_TLS_CONFIDENCE:()=>Vr,PROTO_TLS_MIN_RECORD_LEN:()=>Br,PROTO_WS_CONFIDENCE:()=>Hr,PROXY_ADB_MAX_BUFFER_BYTES:()=>ir,PROXY_ADB_TIMEOUT_MS:()=>rr,PROXY_CAPTURE_BUFFER_MAX:()=>tr,PROXY_CAPTURE_RETURN_LIMIT:()=>nr,RERANK_BROWSER_ATTACH_BOOST:()=>pt,RERANK_BROWSER_LAUNCH_BOOST:()=>ft,RERANK_MAINTENANCE_PENALTY:()=>st,RERANK_NETWORK_GET_REQUESTS_BOOST:()=>ht,RERANK_NETWORK_MONITOR_BOOST:()=>mt,RERANK_STATELESS_COMPUTE_BOOST:()=>ut,RERANK_STATELESS_CORE_PENALTY:()=>lt,RERANK_STATELESS_INTERACTIVE_PENALTY:()=>ct,RERANK_STATELESS_SPECIFIC_TOOL_BOOST:()=>dt,RUNTIME_ERROR_THRESHOLD:()=>l,RUNTIME_ERROR_WINDOW_MS:()=>c,SANDBOX_EXEC_TIMEOUT_MS:()=>C,SANDBOX_MAX_TIMEOUT_MS:()=>Ar,SANDBOX_MEMORY_LIMIT_MB:()=>w,SANDBOX_STACK_SIZE_MB:()=>T,SANDBOX_TERMINATE_GRACE_MS:()=>E,SCAN_DISPLAY_RESULTS_LIMIT:()=>_n,SCAN_GROUP_MAX_PATTERN_SIZE:()=>bn,SCAN_MAX_RESULTS_PER_SCAN:()=>gn,SCAN_POINTER_MAX_RESULTS:()=>yn,SCAN_SESSION_MAX_COUNT:()=>xn,SCAN_SESSION_TTL_MS:()=>Sn,SCAN_UNKNOWN_INITIAL_MAX_ADDRESSES:()=>vn,SCRIPTS_MAX_CAP:()=>Mt,SEARCH_AFFINITY_BASE_WEIGHT:()=>rt,SEARCH_AFFINITY_BOOST_FACTOR:()=>Te,SEARCH_AFFINITY_TOP_N:()=>Ee,SEARCH_AUTO_ACTIVATE_DOMAINS:()=>fe,SEARCH_BM25_B:()=>ze,SEARCH_BM25_K1:()=>Re,SEARCH_CACHE_VECTOR_WEIGHT_TOLERANCE:()=>ke,SEARCH_COVERAGE_PRECISION_FACTOR:()=>it,SEARCH_DOMAIN_HUB_BOOST_MULTIPLIER:()=>nt,SEARCH_DOMAIN_HUB_THRESHOLD:()=>De,SEARCH_EXACT_NAME_MATCH_MULTIPLIER:()=>tt,SEARCH_PARAM_TOKEN_WEIGHT:()=>Ie,SEARCH_PREFIX_MATCH_MULTIPLIER:()=>at,SEARCH_QUERY_CACHE_CAPACITY:()=>Oe,SEARCH_RECENCY_MAX_BOOST:()=>$e,SEARCH_RECENCY_TRACKER_MAX:()=>et,SEARCH_RECENCY_WINDOW_MS:()=>Qe,SEARCH_RRF_BM25_BLEND:()=>Pe,SEARCH_RRF_K:()=>Me,SEARCH_RRF_RESCALE_FACTOR:()=>Ne,SEARCH_SCENE_KEYWORD_WEIGHT:()=>Le,SEARCH_SELF_RAG_ENABLED:()=>ot,SEARCH_SYNONYM_EXPANSION_LIMIT:()=>Fe,SEARCH_TIER_PENALTY:()=>Je,SEARCH_TIER_PENALTY_FULL:()=>Ze,SEARCH_TIER_PENALTY_SEARCH:()=>Ye,SEARCH_TIER_PENALTY_WORKFLOW:()=>Xe,SEARCH_TRIGRAM_THRESHOLD:()=>je,SEARCH_TRIGRAM_WEIGHT:()=>Ae,SEARCH_VECTOR_BM25_SKIP_THRESHOLD:()=>qe,SEARCH_VECTOR_COSINE_WEIGHT:()=>He,SEARCH_VECTOR_DYNAMIC_WEIGHT:()=>Ue,SEARCH_VECTOR_ENABLED:()=>Be,SEARCH_VECTOR_LEARN_DOWN:()=>Ge,SEARCH_VECTOR_LEARN_TOP_N:()=>Ke,SEARCH_VECTOR_LEARN_UP:()=>We,SEARCH_VECTOR_MODEL_ID:()=>Ve,SEARCH_WORKFLOW_DOMAIN_BOOST_MULTIPLIER:()=>ue,SHUTDOWN_TIMEOUT_MS:()=>s,SOURCEMAP_V4_RAW_FIELD_MAX_LEN:()=>Fr,SOURCEMAP_V4_RETRY_DELAY_MS:()=>Ir,STRUCT_ANALYZE_DEFAULT_SIZE:()=>On,STRUCT_RTTI_MAX_STRING_LEN:()=>An,STRUCT_VTABLE_MAX_FUNCTIONS:()=>kn,SYMBOLIC_EXEC_MAX_DEPTH:()=>O,SYMBOLIC_EXEC_MAX_PATHS:()=>D,SYMBOLIC_EXEC_TIMEOUT_MS:()=>k,SYSCALL_TRACE_DURATION_DEFAULT_SEC:()=>Mr,SYSCALL_TRACE_DURATION_MAX_SEC:()=>Pr,SYSCALL_TRACE_DURATION_MIN_SEC:()=>Nr,TOKEN_BUDGET_MAX_TOKENS:()=>zt,TRANSFORM_CRYPTO_POOL_IDLE_TIMEOUT_MS:()=>R,TRANSFORM_CRYPTO_POOL_MAX_OLD_GEN_MB:()=>z,TRANSFORM_CRYPTO_POOL_MAX_WORKERS:()=>L,TRANSFORM_CRYPTO_POOL_MAX_YOUNG_GEN_MB:()=>B,TRANSFORM_WORKER_TIMEOUT_MS:()=>I,UNIDBG_TIMEOUT_MS:()=>Nn,USERSPACE_MAX_ADDRESS:()=>Cn,V8_BYTECODE_SUBPROC_TIMEOUT_MS:()=>jr,WASM_BITWISE_OPS_THRESHOLD:()=>Rr,WASM_DEAD_CODE_MIN_MATCHES:()=>Lr,WASM_OPTIMIZE_TIMEOUT_MS:()=>H,WASM_TOOL_TIMEOUT_MS:()=>V,WASM_VM_DISPATCH_MIN_LOOPS:()=>zr,WATCH_EVAL_TIMEOUT_MS:()=>F,WEBHOOK_PROCESS_TIMEOUT_MS:()=>Kr,WIN_DEBUG_PORT_POLL_ATTEMPTS:()=>an,WIN_DEBUG_PORT_POLL_INTERVAL_MS:()=>on,WORKER_POOL_IDLE_TIMEOUT_MS:()=>Ft,WORKER_POOL_JOB_TIMEOUT_MS:()=>It,WORKER_POOL_MAX_WORKERS:()=>Pt,WORKER_POOL_MIN_WORKERS:()=>Nt,WORKFLOW_BUNDLE_CACHE_MAX_BYTES:()=>le,WORKFLOW_BUNDLE_CACHE_TTL_MS:()=>ce,WORKFLOW_JS_BUNDLE_FETCH_TIMEOUT_MS:()=>se,WORKFLOW_JS_BUNDLE_MAX_REDIRECTS:()=>oe,WORKFLOW_JS_BUNDLE_MAX_SIZE_BYTES:()=>ae,WRITE_HISTORY_MAX:()=>hn,WS_PAYLOAD_PREVIEW_LIMIT:()=>At,WS_PAYLOAD_SAMPLE_LIMIT:()=>jt});const r=(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},i=(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},a=(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},o=(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},ne=(e,t,n)=>{let i=process.env[e];if(i!==void 0&&i.trim().toLowerCase()===`auto`){let e=n();return Number.isFinite(e)&&e>0?Math.floor(e):t}return r(e,t)},re=()=>{try{return t().length}catch{return 4}},s=r(`SHUTDOWN_TIMEOUT_MS`,2e4),c=r(`RUNTIME_ERROR_WINDOW_MS`,6e4),l=r(`RUNTIME_ERROR_THRESHOLD`,8),u=ee(`DEBUG_PORT_CANDIDATES`,[9222,9229,9333,2039]),d=r(`DEFAULT_DEBUG_PORT`,9222),f=o(`GHIDRA_BRIDGE_URL`,`http://127.0.0.1:18080`),p=o(`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=r(`MCP_HTTP_REQUEST_TIMEOUT_MS`,3e4),g=r(`MCP_HTTP_HEADERS_TIMEOUT_MS`,1e4),_=r(`MCP_HTTP_KEEPALIVE_TIMEOUT_MS`,864e5),v=r(`MCP_HTTP_FORCE_CLOSE_TIMEOUT_MS`,5e3),y=r(`EXTERNAL_TOOL_TIMEOUT_MS`,3e4),b=r(`EXTERNAL_TOOL_PROBE_TIMEOUT_MS`,5e3),x=r(`EXTERNAL_TOOL_PROBE_CACHE_TTL_MS`,6e4),S=r(`EXTERNAL_TOOL_FORCE_KILL_GRACE_MS`,2e3),C=r(`SANDBOX_EXEC_TIMEOUT_MS`,5e3),w=r(`SANDBOX_MEMORY_LIMIT_MB`,128),T=r(`SANDBOX_STACK_SIZE_MB`,4),E=r(`SANDBOX_TERMINATE_GRACE_MS`,2e3),D=r(`SYMBOLIC_EXEC_MAX_PATHS`,100),O=r(`SYMBOLIC_EXEC_MAX_DEPTH`,50),k=r(`SYMBOLIC_EXEC_TIMEOUT_MS`,3e4),A=r(`JSVMP_DEOBFUSCATE_TIMEOUT_MS`,3e4),j=r(`JSVMP_MAX_ITERATIONS`,100),M=r(`JSVMP_SYMBOLIC_MAX_STEPS`,1e3),N=r(`JSVMP_SYMBOLIC_TIMEOUT_MS`,3e4),P=r(`DEBUGGER_WAIT_FOR_PAUSED_TIMEOUT_MS`,3e4),F=r(`WATCH_EVAL_TIMEOUT_MS`,5e3),I=r(`TRANSFORM_WORKER_TIMEOUT_MS`,15e3);r(`TRANSFORM_VM_SCRIPT_TIMEOUT_MS`,5e3);const L=r(`TRANSFORM_CRYPTO_POOL_MAX_WORKERS`,4),R=r(`TRANSFORM_CRYPTO_POOL_IDLE_TIMEOUT_MS`,3e4),z=r(`TRANSFORM_CRYPTO_POOL_MAX_OLD_GEN_MB`,64),B=r(`TRANSFORM_CRYPTO_POOL_MAX_YOUNG_GEN_MB`,16);r(`EMULATOR_FETCH_GOTO_TIMEOUT_MS`,3e4);const V=r(`WASM_TOOL_TIMEOUT_MS`,6e4);r(`WASM_OFFLINE_RUN_TIMEOUT_MS`,1e4);const H=r(`WASM_OPTIMIZE_TIMEOUT_MS`,12e4);r(`MINIAPP_UNPACK_TIMEOUT_MS`,18e4);const U=r(`CAPTCHA_SUBMIT_TIMEOUT_MS`,15e3);r(`FETCH_ABORT_TIMEOUT_MS`,1e4);const W=r(`CAPTCHA_POLL_INTERVAL_MS`,5e3),G=r(`CAPTCHA_RESULT_TIMEOUT_MS`,1e4),K=r(`CAPTCHA_DEFAULT_TIMEOUT_MS`,18e4),q=r(`CAPTCHA_MIN_TIMEOUT_MS`,5e3),J=r(`CAPTCHA_MAX_TIMEOUT_MS`,6e5),Y=r(`CAPTCHA_MAX_RETRIES`,5),X=r(`CAPTCHA_DEFAULT_RETRIES`,2);r(`NETWORK_REPLAY_TIMEOUT_MS`,3e4),r(`NETWORK_REPLAY_MAX_BODY_BYTES`,512e3);const Z=r(`NETWORK_REPLAY_MAX_REDIRECTS`,5),ie=r(`NETWORK_HAR_BODY_CONCURRENCY`,4);r(`WORKFLOW_BATCH_MAX_ACCOUNTS`,50),r(`WORKFLOW_BATCH_MAX_CONCURRENCY`,1),r(`WORKFLOW_REGISTER_ACCOUNT_TIMEOUT_MS`,6e4),r(`WORKFLOW_ACTION_DELAY_MS`,1e3),r(`WORKFLOW_SETTLE_DELAY_MS`,2e3),r(`WORKFLOW_INPUT_DELAY_MS`,1500),r(`WORKFLOW_BATCH_MAX_RETRIES`,3),r(`WORKFLOW_BATCH_MAX_BACKOFF_MS`,3e4),r(`WORKFLOW_BATCH_MAX_TIMEOUT_MS`,3e5),r(`WORKFLOW_BATCH_RETRY_BACKOFF_MS`,2e3),r(`WORKFLOW_BATCH_TIMEOUT_PER_ACCOUNT_MS`,9e4);const ae=r(`WORKFLOW_JS_BUNDLE_MAX_SIZE_BYTES`,20*1024*1024),oe=r(`WORKFLOW_JS_BUNDLE_MAX_REDIRECTS`,5),se=r(`WORKFLOW_JS_BUNDLE_FETCH_TIMEOUT_MS`,3e4),ce=r(`WORKFLOW_BUNDLE_CACHE_TTL_MS`,300*1e3),le=r(`WORKFLOW_BUNDLE_CACHE_MAX_BYTES`,100*1024*1024);new Set(te(`SEARCH_WORKFLOW_BOOST_TIERS`,[`workflow`,`full`]));const ue=i(`SEARCH_WORKFLOW_DOMAIN_BOOST_MULTIPLIER`,2.4),de=r(`ACTIVATION_TTL_MINUTES`,30),fe=a(`SEARCH_AUTO_ACTIVATE_DOMAINS`,!0),pe=r(`AUTOPRUNE_AUTO_INACTIVITY_MS`,15*6e4),me=r(`AUTOPRUNE_MANUAL_INACTIVITY_MS`,30*6e4),he=r(`AUTOPRUNE_CHECK_INTERVAL_MS`,6e4),ge=r(`PREDICTIVE_MAX_HISTORY`,100),_e=i(`PREDICTIVE_CONFIDENCE_THRESHOLD`,.25),ve=i(`PREDICTIVE_DECAY_FACTOR`,.95),ye=r(`ACTIVATION_COOLDOWN_MS`,3e4),be=r(`ACTIVATION_COMPOUND_EVAL_EVERY`,5),xe=r(`ACTIVATION_EVENT_HISTORY_MAX`,200),Se=r(`ACTIVATION_BOOST_WINDOW_MS`,6e4),Ce=r(`COMPOUND_EVENT_WINDOW_MS`,12e4),we=r(`COMPOUND_LONG_WINDOW_MS`,3e5),Te=i(`SEARCH_AFFINITY_BOOST_FACTOR`,.38),Ee=r(`SEARCH_AFFINITY_TOP_N`,9),De=r(`SEARCH_DOMAIN_HUB_THRESHOLD`,5),Oe=r(`SEARCH_QUERY_CACHE_CAPACITY`,500),ke=i(`SEARCH_CACHE_VECTOR_WEIGHT_TOLERANCE`,.05),Ae=i(`SEARCH_TRIGRAM_WEIGHT`,.02),je=i(`SEARCH_TRIGRAM_THRESHOLD`,.47),Me=r(`SEARCH_RRF_K`,18),Ne=i(`SEARCH_RRF_RESCALE_FACTOR`,2100),Pe=i(`SEARCH_RRF_BM25_BLEND`,.39),Fe=r(`SEARCH_SYNONYM_EXPANSION_LIMIT`,2),Ie=i(`SEARCH_PARAM_TOKEN_WEIGHT`,1.1),Le=i(`SEARCH_SCENE_KEYWORD_WEIGHT`,.8),Re=i(`SEARCH_BM25_K1`,1),ze=i(`SEARCH_BM25_B`,.75),Be=a(`SEARCH_VECTOR_ENABLED`,!0),Ve=o(`SEARCH_VECTOR_MODEL_ID`,`Xenova/bge-micro-v2`),He=i(`SEARCH_VECTOR_COSINE_WEIGHT`,.53),Ue=a(`SEARCH_VECTOR_DYNAMIC_WEIGHT`,!0),We=i(`SEARCH_VECTOR_LEARN_UP`,.13),Ge=i(`SEARCH_VECTOR_LEARN_DOWN`,.02),Ke=r(`SEARCH_VECTOR_LEARN_TOP_N`,3),qe=i(`SEARCH_VECTOR_BM25_SKIP_THRESHOLD`,8),Je=i(`SEARCH_TIER_PENALTY`,.35),Ye=i(`SEARCH_TIER_PENALTY_SEARCH`,.4),Xe=i(`SEARCH_TIER_PENALTY_WORKFLOW`,.6),Ze=i(`SEARCH_TIER_PENALTY_FULL`,.6),Qe=r(`SEARCH_RECENCY_WINDOW_MS`,30*6e4),$e=i(`SEARCH_RECENCY_MAX_BOOST`,.1),et=r(`SEARCH_RECENCY_TRACKER_MAX`,200),tt=i(`SEARCH_EXACT_NAME_MATCH_MULTIPLIER`,3.2),nt=i(`SEARCH_DOMAIN_HUB_BOOST_MULTIPLIER`,1.04),rt=i(`SEARCH_AFFINITY_BASE_WEIGHT`,.5),it=i(`SEARCH_COVERAGE_PRECISION_FACTOR`,.94),at=i(`SEARCH_PREFIX_MATCH_MULTIPLIER`,.84),ot=a(`SEARCH_SELF_RAG_ENABLED`,!0),st=i(`RERANK_MAINTENANCE_PENALTY`,.43),ct=i(`RERANK_STATELESS_INTERACTIVE_PENALTY`,.65),lt=i(`RERANK_STATELESS_CORE_PENALTY`,.15),ut=i(`RERANK_STATELESS_COMPUTE_BOOST`,2.2),dt=i(`RERANK_STATELESS_SPECIFIC_TOOL_BOOST`,2.25),ft=i(`RERANK_BROWSER_LAUNCH_BOOST`,1.35),pt=i(`RERANK_BROWSER_ATTACH_BOOST`,1.55),mt=i(`RERANK_NETWORK_MONITOR_BOOST`,1.6),ht=i(`RERANK_NETWORK_GET_REQUESTS_BOOST`,1.55),gt=r(`PREDICTIVE_MAX_SECOND_ORDER_KEYS`,1e3),_t=r(`EXTENSION_GIT_CLONE_TIMEOUT_MS`,6e4),vt=r(`EXTENSION_GIT_CHECKOUT_TIMEOUT_MS`,3e4),yt=r(`PROCESS_LIST_MAX_BUFFER_BYTES`,1024*1024*10),bt=r(`EXTERNAL_TOOL_MAX_STDOUT_BYTES`,10*1024*1024),xt=r(`EXTERNAL_TOOL_MAX_STDERR_BYTES`,1*1024*1024),St=r(`GRAPHQL_MAX_PREVIEW_CHARS`,4e3),Ct=r(`GRAPHQL_MAX_SCHEMA_CHARS`,12e4),wt=r(`GRAPHQL_MAX_QUERY_CHARS`,12e3),Tt=r(`GRAPHQL_MAX_GRAPH_NODES`,2e3),Et=r(`GRAPHQL_MAX_GRAPH_EDGES`,5e3),Dt=r(`ANALYSIS_MAX_SUMMARY_FILES`,40),Ot=r(`ANALYSIS_MAX_SAFE_COLLECTED_BYTES`,256*1024),kt=r(`ANALYSIS_MAX_SAFE_RESPONSE_BYTES`,220*1024),At=r(`WS_PAYLOAD_PREVIEW_LIMIT`,200),jt=r(`WS_PAYLOAD_SAMPLE_LIMIT`,2e3),Mt=r(`SCRIPTS_MAX_CAP`,500),Nt=r(`WORKER_POOL_MIN_WORKERS`,2),Pt=ne(`WORKER_POOL_MAX_WORKERS`,4,()=>{let e=Math.floor(re()/2),t=r(`WORKER_POOL_MIN_WORKERS`,2);return Math.max(t,Math.min(8,e))}),Ft=r(`WORKER_POOL_IDLE_TIMEOUT_MS`,3e4),It=r(`WORKER_POOL_JOB_TIMEOUT_MS`,15e3);r(`PARALLEL_DEFAULT_CONCURRENCY`,3),r(`PARALLEL_DEFAULT_TIMEOUT_MS`,6e4),r(`PARALLEL_DEFAULT_MAX_RETRIES`,2),r(`PARALLEL_RETRY_BACKOFF_BASE_MS`,1e3);const Lt=r(`CACHE_GLOBAL_MAX_SIZE_BYTES`,500*1024*1024),Rt=i(`CACHE_LOW_HIT_RATE_THRESHOLD`,.3),zt=r(`TOKEN_BUDGET_MAX_TOKENS`,2e5),Bt=r(`DETAILED_DATA_DEFAULT_TTL_MS`,1800*1e3),Vt=r(`DETAILED_DATA_MAX_TTL_MS`,3600*1e3),Ht=r(`DETAILED_DATA_SMART_THRESHOLD_BYTES`,50*1024),Ut=r(`OFFLOAD_FIELD_SANITIZE_THRESHOLD_BYTES`,64*1024);r(`ADV_DEOBF_LLM_MAX_TOKENS`,3e3),r(`VM_DEOBF_LLM_MAX_TOKENS`,4e3),r(`DEOBF_LLM_MAX_TOKENS`,2e3),r(`CRYPTO_DETECT_LLM_MAX_TOKENS`,2e3);const Wt=r(`MEMORY_READ_TIMEOUT_MS`,1e4),Gt=r(`MEMORY_MAX_READ_BYTES`,16*1024*1024),Kt=r(`MEMORY_WRITE_TIMEOUT_MS`,1e4),qt=r(`MEMORY_MAX_WRITE_BYTES`,16*1024),Jt=r(`MEMORY_DUMP_TIMEOUT_MS`,6e4),Yt=r(`MEMORY_SCAN_TIMEOUT_MS`,12e4),Xt=r(`MEMORY_SCAN_MAX_BUFFER_BYTES`,1024*1024*50),Zt=r(`MEMORY_SCAN_MAX_RESULTS`,1e4);r(`MEMORY_SCAN_MAX_REGIONS`,5e4),r(`MEMORY_SCAN_REGION_MAX_BYTES`,16777216);const Qt=r(`MEMORY_INJECT_TIMEOUT_MS`,3e4),$t=a(`ENABLE_INJECTION_TOOLS`,!0);r(`MEMORY_MONITOR_INTERVAL_MS`,1e3);const en=r(`MEMORY_VMMAP_TIMEOUT_MS`,15e3),tn=r(`MEMORY_PROTECTION_QUERY_TIMEOUT_MS`,15e3),nn=r(`MEMORY_PROTECTION_PWSH_TIMEOUT_MS`,3e4),rn=r(`NATIVE_ADMIN_CHECK_TIMEOUT_MS`,5e3);r(`NATIVE_SCAN_MAX_RESULTS`,1e4);const Q=r(`PROCESS_LAUNCH_WAIT_MS`,2e3),an=r(`WIN_DEBUG_PORT_POLL_ATTEMPTS`,20),on=r(`WIN_DEBUG_PORT_POLL_INTERVAL_MS`,500);r(`PACKER_SANDBOX_TIMEOUT_MS`,3e3);const sn=r(`CODE_CAVE_MIN_SIZE`,16),cn=r(`BREAKPOINT_HIT_TIMEOUT_MS`,1e4),ln=r(`BREAKPOINT_TRACE_MAX_HITS`,100),un=r(`HEAP_ENUMERATE_MAX_BLOCKS`,1e4),dn=r(`HEAP_SPRAY_THRESHOLD`,50),fn=r(`HEAP_SPRAY_SIZE_TOLERANCE`,64),pn=r(`HEAP_SUSPICIOUS_BLOCK_SIZE`,10485760),mn=r(`FREEZE_DEFAULT_INTERVAL_MS`,100),hn=r(`WRITE_HISTORY_MAX`,200),gn=r(`SCAN_MAX_RESULTS_PER_SCAN`,1e5),_n=r(`SCAN_DISPLAY_RESULTS_LIMIT`,200),vn=r(`SCAN_UNKNOWN_INITIAL_MAX_ADDRESSES`,5e5),yn=r(`SCAN_POINTER_MAX_RESULTS`,5e3),bn=r(`SCAN_GROUP_MAX_PATTERN_SIZE`,256),xn=r(`SCAN_SESSION_MAX_COUNT`,20),Sn=r(`SCAN_SESSION_TTL_MS`,18e5),Cn=140737488289792n,wn=r(`POINTER_CHAIN_MAX_DEPTH`,6),Tn=r(`POINTER_CHAIN_MAX_OFFSET`,4096),En=r(`POINTER_CHAIN_MAX_RESULTS`,500),Dn=r(`POINTER_CHAIN_SCAN_CHUNK_SIZE`,16777216),On=r(`STRUCT_ANALYZE_DEFAULT_SIZE`,256),kn=r(`STRUCT_VTABLE_MAX_FUNCTIONS`,64),An=r(`STRUCT_RTTI_MAX_STRING_LEN`,256);r(`STRUCT_CSTRING_MAX_LEN`,256);const jn=r(`FRIDA_TIMEOUT_MS`,15e3),Mn=r(`GHIDRA_TIMEOUT_MS`,12e4),Nn=r(`UNIDBG_TIMEOUT_MS`,6e4),Pn=r(`NEMU_SESSION_IDLE_TTL_MS`,3e5),Fn=r(`NEMU_SESSION_SWEEP_MS`,6e4),In=r(`NEMU_MAX_SESSIONS`,64),Ln=r(`ADB_DEFAULT_TIMEOUT_MS`,3e4),Rn=r(`ADB_SHELL_TIMEOUT_MS`,6e4),zn=r(`ADB_MAX_BUFFER_BYTES`,16*1024*1024),Bn=r(`ADB_LARGE_OUTPUT_MAX_BUFFER_BYTES`,32*1024*1024),Vn=r(`ADB_FILE_TRANSFER_TIMEOUT_MS`,18e4),Hn=r(`ADB_PACKAGE_COMPONENT_LIMIT`,500),Un=te(`APK_ZIP_MAGIC_HEX_HEADERS`,[`504b0304`,`504b0506`,`504b0708`]),Wn=r(`ADB_LOGCAT_TAIL_DEFAULT`,500),Gn=r(`ADB_LOGCAT_TAIL_MAX`,2e4),Kn=r(`ADB_LOGCAT_MAX_LINES_DEFAULT`,100),qn=r(`ADB_LOGCAT_MAX_LINES_MAX`,5e3),Jn=r(`ADB_COLD_START_WAIT_MS_DEFAULT`,5e3),Yn=r(`ADB_COLD_START_WAIT_MS_MAX`,3e4),Xn=r(`ADB_COLD_START_LOGCAT_TAIL_DEFAULT`,800),Zn=r(`ADB_COLD_START_LOGCAT_TAIL_MIN`,100),Qn=r(`ADB_COLD_START_LOGCAT_TAIL_MAX`,2e4),$n=r(`ADB_COLD_START_TIMELINE_LIMIT`,300);r(`ADB_WEBVIEW_HTTP_TIMEOUT_MS`,5e3),r(`ADB_WEBVIEW_WS_TIMEOUT_MS`,1e4);const er=r(`ADB_WEBVIEW_HOST_PORT_DEFAULT`,9222),tr=r(`PROXY_CAPTURE_BUFFER_MAX`,5e3),nr=r(`PROXY_CAPTURE_RETURN_LIMIT`,100),rr=r(`PROXY_ADB_TIMEOUT_MS`,6e4),ir=r(`PROXY_ADB_MAX_BUFFER_BYTES`,8*1024*1024),ar=r(`APK_STATIC_TRIAGE_MIN_ENTRIES`,100),or=r(`APK_STATIC_TRIAGE_DEFAULT_ENTRIES`,2e3),sr=r(`APK_STATIC_TRIAGE_MAX_ENTRIES`,2e4),cr=r(`APK_STATIC_TRIAGE_ASSET_HINT_LIMIT`,200),lr=r(`APK_STATIC_TRIAGE_NATIVE_LIB_LIMIT`,300),ur=r(`DEX_SCAN_DEFAULT_MAX_HITS`,50),dr=r(`DEX_SCAN_MAX_HITS`,500),fr=r(`DEX_SCAN_MAX_EXTRACT_BYTES`,512*1024*1024),pr=o(`DEX_MAGIC_ASCII`,`dex
|
|
2
|
-
`),mr=o(`CDEX_MAGIC_ASCII`,`cdex`),hr=r(`BINARY_STRINGS_MIN_LENGTH_DEFAULT`,4),gr=r(`BINARY_STRINGS_MIN_LENGTH_FLOOR`,2),_r=r(`BINARY_STRINGS_MIN_LENGTH_CEILING`,256),vr=r(`BINARY_STRINGS_MAX_RESULTS_DEFAULT`,1e3),yr=r(`BINARY_STRINGS_MAX_RESULTS_LIMIT`,5e4),br=r(`BINARY_STRINGS_PRINTABLE_ASCII_MIN`,32),xr=r(`BINARY_STRINGS_PRINTABLE_ASCII_MAX`,126),Sr=r(`FRIDA_DEX_DUMP_TIMEOUT_MS`,18e4),Cr=r(`FRIDA_DEX_DUMP_MAX_BUFFER_BYTES`,16*1024*1024),wr=r(`FRIDA_DEX_DUMP_FILE_LIMIT`,500),Tr=r(`MOJO_MONITOR_TIMEOUT_MS`,1e4),Er=r(`MEMORY_AVAILABILITY_CACHE_TTL_MS`,45e3),Dr=r(`HTTP_RATE_LIMIT_MAX_IPS`,1e4),Or=r(`HTTP_CLEANUP_INTERVAL_MS`,5*6e4);r(`SSE_HEARTBEAT_MS`,3e4);const kr=a(`MCP_COMPACT_SCHEMA`,!0),Ar=r(`SANDBOX_MAX_TIMEOUT_MS`,3e4);r(`NATIVE_BRIDGE_TIMEOUT_MS`,15e3),r(`SOURCEMAP_EXT_TIMEOUT_MS`,15e3);const jr=r(`V8_BYTECODE_SUBPROC_TIMEOUT_MS`,6e4),Mr=r(`SYSCALL_TRACE_DURATION_DEFAULT_SEC`,10),Nr=r(`SYSCALL_TRACE_DURATION_MIN_SEC`,1),Pr=r(`SYSCALL_TRACE_DURATION_MAX_SEC`,300),Fr=r(`SOURCEMAP_V4_RAW_FIELD_MAX_LEN`,200),Ir=r(`SOURCEMAP_V4_RETRY_DELAY_MS`,250),Lr=r(`WASM_DEAD_CODE_MIN_MATCHES`,10),Rr=r(`WASM_BITWISE_OPS_THRESHOLD`,20),zr=r(`WASM_VM_DISPATCH_MIN_LOOPS`,3),Br=r(`PROTO_TLS_MIN_RECORD_LEN`,4),Vr=i(`PROTO_TLS_CONFIDENCE`,.95),Hr=i(`PROTO_WS_CONFIDENCE`,.85),Ur=i(`PROTO_HTTP_CONFIDENCE`,.95),Wr=i(`PROTO_SSH_CONFIDENCE`,.95),Gr=r(`BOT_DETECT_LIMIT_DEFAULT`,50);r(`BOT_DETECT_LIMIT_MIN`,1),r(`BOT_DETECT_LIMIT_MAX`,500);const Kr=r(`WEBHOOK_PROCESS_TIMEOUT_MS`,1e4);r(`ORCHESTRATOR_STEP_TIMEOUT_MS`,1e4);const qr=r(`MACRO_DEFAULT_TIMEOUT_MS`,12e4),Jr=r(`MACRO_BUILTIN_TIMEOUT_MS`,6e4),Yr=r(`PAGE_FRAME_SELECTOR_TIMEOUT_MS`,1e4),Xr=r(`PAGE_NETWORK_IDLE_TIMEOUT_MS`,3e4),Zr=r(`DOM_QUERY_DEFAULT_LIMIT`,50),Qr=r(`DOM_WAIT_ELEMENT_TIMEOUT_MS`,3e4);r(`BROWSER_POOL_IDLE_TIMEOUT_MS`,3e5),r(`BROWSER_POOL_MAX_TABS`,10);const $r=r(`ICMP_PROBE_TIMEOUT_MS`,5e3),ei=r(`ICMP_TRACEROUTE_MAX_HOPS`,30),ti=r(`ICMP_DEFAULT_PACKET_SIZE`,32);r(`ADB_VERSION_CHECK_TIMEOUT_MS`,5e3);const ni=r(`COORDINATION_GOTO_TIMEOUT_MS`,3e4),ri=r(`MEMORY_AUDIT_TRAIL_CAPACITY`,5e3),ii=r(`MEMORY_PROCESS_SIGNAL_TIMEOUT_MS`,2e3),ai=r(`MEMORY_PROBE_CMD_TIMEOUT_MS`,5e3),oi=r(`MEMORY_VMMAP_ENUM_TIMEOUT_MS`,15e3),si=r(`MEMORY_MODULES_TIMEOUT_MS`,3e4),ci=a(`MCP_LOG_ENABLED`,!1),li=o(`MCP_LOG_LEVEL`,`info`),ui=o(`MCP_LOG_FILE_DIR`,``),di=r(`DART_MIN_LENGTH`,4);r(`DART_MIN_LENGTH_FLOOR`,2),r(`DART_MIN_LENGTH_CEILING`,64);const fi=r(`DART_MAX_CHUNK_BYTES`,16*1024*1024),pi=r(`DART_CHUNK_OVERLAP_BYTES`,128),mi=r(`DART_PRINTABLE_ASCII_MIN`,32),hi=r(`DART_PRINTABLE_ASCII_MAX`,126),gi=o(`DART_DEFAULT_ENCODING`,`both`),_i=r(`DART_MAX_OFFSETS_PER_STRING`,1e3),vi=r(`DART_MAX_REGEX_PATTERN_LENGTH`,256),yi=r(`DART_REGEX_TIMEOUT_MS`,50),bi=o(`DART_ALLOWED_REGEX_FLAGS`,`iu`);r(`DART_MAX_EXTRACT_DURATION_MS`,3e4),r(`DART_MAX_RESULT_BYTES`,16*1024*1024);const xi=r(`DART_MAX_SMI_VALUE`,1e6),Si=r(`DART_MAX_MAP_BYTES`,16*1024*1024),Ci=r(`DART_MAX_PACKAGES_PER_RESULT`,1e3),wi=r(`DART_MAX_FILES_PER_PACKAGE`,50),Ti=r(`DART_SNAPSHOT_MAX_FILE_BYTES`,1024*1024*1024),Ei=r(`DART_SNAPSHOT_HEADER_SCAN_MAX_BYTES`,32*1024*1024),Di=o(`DART_SNAPSHOT_TABLE_PATH`,``),Oi=r(`DART_PP_MAX_SLOTS`,4096),ki=r(`DART_PP_PREVIEW_BYTES`,64),$=r(`DART_PP_MAX_DUMP_DURATION_MS`,1e4);export{G as $,Lr as $i,ie as $n,ke as $r,f as $t,lr as A,ue as Ai,ri as An,ct as Ar,Bt as At,xr as B,Mr as Bi,tn as Bn,bn as Br,vt as Bt,Ot as C,He as Ci,v as Cn,pt as Cr,yi as Ct,or as D,Ke as Di,ci as Dn,mt as Dr,P as Dt,cr as E,Ge as Ei,h as En,ht as Er,Di as Et,vr as F,An as Fi,qt as Fn,Ar as Fr,fr as Ft,Lt as G,z as Gi,oi as Gn,vn as Gr,x as Gt,Gr as H,Nr as Hi,Xt as Hn,yn as Hr,S as Ht,yr as I,kn as Ii,si as In,w as Ir,dr as It,K as J,I as Ji,Tr as Jn,Te as Jr,mn as Jt,Rt as K,L as Ki,en as Kn,Mt as Kr,b as Kt,_r as L,O as Li,ai as Ln,T as Lr,Zr as Lt,pe as M,Fr as Mi,Jt as Mn,l as Mr,Ht as Mt,he as N,Ir as Ni,Qt as Nn,c as Nr,pr as Nt,sr as O,We as Oi,ui as On,ut as Or,u as Ot,me as P,On as Pi,Gt as Pn,C as Pr,ur as Pt,W as Q,Rr as Qi,Fn as Qn,Re as Qr,jn as Qt,hr as R,D as Ri,ii as Rn,E as Rr,Qr as Rt,er as S,qe as Si,kr as Sn,nr as Sr,mi as St,Dt as T,Be as Ti,_ as Tn,st as Tr,Ti as Tt,cn as U,zt as Ui,Zt as Un,xn as Ur,xt as Ut,br as V,Pr as Vi,Wt as Vn,gn as Vr,_t as Vt,ln as W,R as Wi,Yt as Wn,Sn as Wr,bt as Wt,J as X,Cn as Xi,In as Xn,fe as Xr,Cr as Xt,Y,Nn as Yi,rn as Yn,Ee as Yr,wr as Yt,q as Z,jr as Zi,Pn as Zn,ze as Zr,Sr as Zt,Wn as _,At as _a,Ze as _i,j as _n,Br as _r,di as _t,de as a,an as aa,at as ai,Ct as an,Tn as ar,we as at,Hn as b,je as bi,Jr as bn,rr as br,ki as bt,Zn as c,It as ca,et as ci,dn as cn,_e as cr,pi as ct,Yn as d,le as da,Me as di,Dr as dn,gt as dr,wi as dt,H as ea,it as ei,Mn as en,Z as er,m as et,Ln as f,ce as fa,Ne as fi,ti as fn,Q as fr,Si as ft,qn as g,hn as ga,Je as gi,A as gn,Vr as gr,xi as gt,Kn as h,ae as ha,Fe as hi,p as hn,Wr as hr,vi as ht,xe as i,Kr as ia,Ie as ii,wt as in,wn as ir,Ce as it,Un as j,s as ji,Er as jn,dt as jr,Vt as jt,ar as k,Ve as ki,li as kn,lt as kr,d as kt,$n as l,Pt as la,Qe as li,pn as ln,ve as lr,gi as lt,Bn as m,oe as ma,ot as mi,ei as mn,Ur as mr,Ci as mt,be as n,zr as na,De as ni,Tt as nn,Yr as nr,mr as nt,Xn as o,on as oa,Oe as oi,un as on,En as or,ni as ot,Vn as p,se as pa,Le as pi,$r as pn,yt as pr,_i as pt,X as q,B as qi,Kt as qn,rt as qr,y as qt,ye as r,F as ra,tt as ri,St as rn,Xr as rr,sn as rt,Qn as s,Ft as sa,$e as si,fn as sn,Dn as sr,bi as st,Se as t,V as ta,nt as ti,Et as tn,Ut as tr,U as tt,Jn as u,Nt as ua,Pe as ui,Or as un,ge as ur,fi as ut,Gn as v,jt as va,Ye as vi,M as vn,Hr as vr,$ as vt,kt as w,Ue as wi,g as wn,ft as wr,Ei as wt,Rn as x,Ae as xi,qr as xn,tr as xr,hi as xt,zn as y,n as ya,Xe as yi,N as yn,ir as yr,Oi as yt,gr as z,k as zi,nn as zn,_n as zr,$t as zt};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ot as e}from"./constants-DMv3svps.mjs";import{t}from"./response-B1RuVVfD.mjs";import{t as n}from"./ToolError-g3rjWzhx.mjs";import{a as r,c as i,o as a,r as o,t as s}from"./parse-args-ngRrvF9e.mjs";import"./definitions-DlmmHmZc.mjs";import{randomUUID as c}from"node:crypto";function l(e){return e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`)}function u(e,t){return t?RegExp(`^${t.split(`*`).map(e=>l(e)).join(`.*`)}$`).test(e):!0}var d=class{state=new Map;history=new Map;watches=new Map;maxHistoryPerKey=100;maxWatches=200;watchIdleTtlMs=30*6e4;mutationSeq=0;lastPersistedSeq=0;persistNotifier;pruneExpiredWatches(){let e=Date.now(),t=0;for(let[n,r]of this.watches)r.expiresAt<e&&(this.watches.delete(n),t++);if(this.watches.size>this.maxWatches){let e=[...this.watches.entries()].toSorted((e,t)=>e[1].lastChecked-t[1].lastChecked),n=this.watches.size-this.maxWatches;for(let r=0;r<n;r++){let n=e[r];n&&(this.watches.delete(n[0]),t++)}}return t}setPersistNotifier(e){this.persistNotifier=e}markDirty(){this.mutationSeq++,this.persistNotifier?.()}recordChange(e,t){this.markDirty();let n=this.history.get(e);n||(n=[],this.history.set(e,n)),n.push(t),n.length>this.maxHistoryPerKey&&n.splice(0,n.length-this.maxHistoryPerKey)}deleteEntry(e){let t=this.state.get(e);t&&(this.state.delete(e),this.recordChange(e,{id:c().slice(0,8),key:t.key,namespace:t.namespace,action:`delete`,oldValue:t.value,timestamp:Date.now()}))}isExpired(e){return!!(e.expiresAt&&Date.now()>e.expiresAt)}cleanupExpired(){let e=Date.now(),t=0;for(let[n,r]of this.state.entries())r.expiresAt&&e>r.expiresAt&&(this.state.delete(n),this.recordChange(n,{id:c().slice(0,8),key:r.key,namespace:r.namespace,action:`expire`,oldValue:r.value,timestamp:e}),t++);return t}getSnapshotSeq(){return this.mutationSeq}getLastPersistedSeq(){return this.lastPersistedSeq}markPersisted(){this.lastPersistedSeq=this.mutationSeq}isPersistDirty(){return this.mutationSeq!==this.lastPersistedSeq}exportSnapshot(){return{schemaVersion:1,savedAt:new Date().toISOString(),entries:[...this.state.entries()],history:[...this.history.entries()]}}restoreSnapshot(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion!==1)return;let n=Date.now();if(this.state.clear(),this.history.clear(),t.entries)for(let[e,r]of t.entries)r.expiresAt&&n>r.expiresAt||this.state.set(e,r);if(t.history)for(let[e,n]of t.history)this.history.set(e,n);this.mutationSeq=this.state.size,this.lastPersistedSeq=this.mutationSeq}},f=class{store;constructor(e){this.store=e}async handleSet(e){let t=i(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let n=e.value,r=a(e,`namespace`,`default`),s=o(e,`ttlSeconds`),l=`${r}:${t}`,u=Date.now(),d=this.store.state.get(l),f=d?.version??0,p=d?.value,m={key:t,value:n,namespace:r,createdAt:d?.createdAt??u,updatedAt:u,ttlSeconds:s,expiresAt:s?u+s*1e3:void 0,version:f+1};return this.store.state.set(l,m),this.store.recordChange(l,{id:c().slice(0,8),key:t,namespace:r,action:`set`,oldValue:p,newValue:n,timestamp:u}),{success:!0,key:t,namespace:r,version:m.version,expiresAt:m.expiresAt?new Date(m.expiresAt).toISOString():void 0}}async handleGet(e){let t=i(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let n=a(e,`namespace`,`default`),r=`${n}:${t}`,o=this.store.state.get(r);return o?this.store.isExpired(o)?(this.store.deleteEntry(r),{found:!1,key:t,namespace:n,expired:!0}):{found:!0,key:t,namespace:n,value:o.value,version:o.version,createdAt:new Date(o.createdAt).toISOString(),updatedAt:new Date(o.updatedAt).toISOString(),ttlSeconds:o.ttlSeconds,expiresAt:o.expiresAt?new Date(o.expiresAt).toISOString():void 0}:{found:!1,key:t,namespace:n}}async handleDelete(e){let t=i(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let n=a(e,`namespace`,`default`),r=`${n}:${t}`;return this.store.state.get(r)?(this.store.deleteEntry(r),{deleted:!0,key:t,namespace:n}):{deleted:!1,key:t,namespace:n,reason:`not_found`}}async handleList(e){let t=a(e,`namespace`),n=s(e,`includeValues`,!1),r=[],i=[];for(let e of this.store.state.values())if(!(t&&e.namespace!==t)){if(this.store.isExpired(e)){i.push(`${e.namespace}:${e.key}`);continue}r.push({key:e.key,namespace:e.namespace,version:e.version,updatedAt:new Date(e.updatedAt).toISOString(),...n?{value:e.value}:{}})}for(let e of i)this.store.deleteEntry(e);return r.sort((e,t)=>e.namespace===t.namespace?e.key.localeCompare(t.key):e.namespace.localeCompare(t.namespace)),{entries:r,total:r.length,namespaces:[...new Set(r.map(e=>e.namespace))]}}async handleClear(e){let t=a(e,`namespace`),n=a(e,`keyPattern`),r=[];for(let[e,i]of this.store.state.entries())t&&i.namespace!==t||u(i.key,n)&&r.push(e);for(let e of r)this.store.deleteEntry(e);return{cleared:r.length,namespace:t??`all`,pattern:n}}async handleStats(){let e=Date.now(),t={},n=0;for(let[,r]of this.store.state.entries()){if(r.expiresAt&&e>r.expiresAt){n++;continue}t[r.namespace]=(t[r.namespace]??0)+1}let r=0;for(let e of this.store.history.values())r+=e.length;return{totalEntries:Object.values(t).reduce((e,t)=>e+t,0),entriesByNamespace:t,expiredEntries:n,totalWatches:this.store.watches.size,historySize:r}}},p=class{store;constructor(e){this.store=e}async handleWatch(e){let t=i(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let n=a(e,`namespace`,`default`),r=o(e,`pollIntervalMs`,1e3);this.store.pruneExpiredWatches();let s=`watch_${c().slice(0,8)}`,l=t.includes(`*`),d=Date.now(),f={id:s,key:t,namespace:n,pattern:l,pollIntervalMs:r,lastChecked:d,lastVersion:{},createdAt:d,expiresAt:d+this.store.watchIdleTtlMs},p=`${n}:`;for(let[e,n]of this.store.state.entries())e.startsWith(p)&&(l?u(n.key,t)&&(f.lastVersion[n.key]=n.version):n.key===t&&(f.lastVersion[n.key]=n.version));return this.store.watches.set(s,f),{watchId:s,key:t,namespace:n,pattern:l,pollIntervalMs:r,initialKeys:Object.keys(f.lastVersion)}}async handleUnwatch(e){let t=i(e,`watchId`),n=this.store.watches.get(t);return n?(this.store.watches.delete(t),{removed:!0,watchId:t,wasWatching:n.key}):{removed:!1,watchId:t,reason:`not_found`}}async handlePoll(e){let t=i(e,`watchId`),n=this.store.watches.get(t);if(!n)throw Error(`Watch "${t}" not found`);let r=Date.now(),a=[],o=`${n.namespace}:`;if(n.pattern){for(let[e,t]of this.store.state.entries())if(e.startsWith(o)&&u(t.key,n.key)){let e=n.lastVersion[t.key];e===void 0?a.push({key:t.key,namespace:t.namespace,action:`created`}):t.version>e&&a.push({key:t.key,namespace:t.namespace,action:`changed`}),n.lastVersion[t.key]=t.version}for(let e of Object.keys(n.lastVersion))!this.store.state.has(`${n.namespace}:${e}`)&&u(e,n.key)&&(a.push({key:e,namespace:n.namespace,action:`deleted`}),delete n.lastVersion[e])}else{let e=`${n.namespace}:${n.key}`,t=this.store.state.get(e),r=n.lastVersion[n.key];!t&&r!==void 0?(a.push({key:n.key,namespace:n.namespace,action:`deleted`}),delete n.lastVersion[n.key]):t&&(r===void 0?a.push({key:t.key,namespace:t.namespace,action:`created`}):t.version>r&&a.push({key:t.key,namespace:t.namespace,action:`changed`}),n.lastVersion[n.key]=t.version)}return n.lastChecked=r,n.expiresAt=r+this.store.watchIdleTtlMs,{watchId:t,changes:a,hasChanges:a.length>0,checkedAt:new Date(r).toISOString()}}},m=class{store;constructor(e){this.store=e}async handleHistory(e){let t=i(e,`key`),n=a(e,`namespace`,`default`),r=o(e,`limit`,50),s=`${n}:${t}`,c=this.store.history.get(s)??[],l=[...c].toSorted((e,t)=>t.timestamp-e.timestamp).slice(0,r);return{key:t,namespace:n,history:l.map(e=>({...e,timestamp:new Date(e.timestamp).toISOString()})),total:c.length,returned:l.length}}async handleExport(e){let t=a(e,`namespace`),n=a(e,`keyPattern`),r=Date.now(),i={};for(let[e,a]of this.store.state.entries())t&&a.namespace!==t||u(a.key,n)&&(a.expiresAt&&r>a.expiresAt||(i[a.key]=a.value));return{data:i,count:Object.keys(i).length,namespace:t??`all`,exportedAt:new Date(r).toISOString()}}async handleImport(e){let t=r(e,`data`),n=a(e,`namespace`,`default`),i=s(e,`overwrite`,!1);if(!t)throw Error(`data must be an object`);let o=[],l=[],u=[];for(let[e,r]of Object.entries(t)){let t=`${n}:${e}`,a=this.store.state.get(t);if(a&&!i){l.push(e);continue}a&&i&&u.push(e);let s=Date.now(),d={key:e,value:r,namespace:n,createdAt:a?.createdAt??s,updatedAt:s,version:(a?.version??0)+1};this.store.state.set(t,d),this.store.recordChange(t,{id:c().slice(0,8),key:e,namespace:n,action:`set`,oldValue:a?.value,newValue:r,timestamp:s,source:`import`}),o.push(e)}return{imported:o.length,skipped:l.length,overwritten:u.length,total:Object.keys(t).length,keys:o}}},h=class{store;storeHandlers;watchHandlers;ioHandlers;constructor(){this.store=new d,this.storeHandlers=new f(this.store),this.watchHandlers=new p(this.store),this.ioHandlers=new m(this.store)}setPersistNotifier(e){this.store.setPersistNotifier(e)}handleSet(e){return this.storeHandlers.handleSet(e)}handleGet(e){return this.storeHandlers.handleGet(e)}handleDelete(e){return this.storeHandlers.handleDelete(e)}handleList(e){return this.storeHandlers.handleList(e)}handleWatchDispatch(e){let t=String(e.action??``);return t===`stop`?this.watchHandlers.handleUnwatch(e):t===`poll`?this.watchHandlers.handlePoll(e):this.watchHandlers.handleWatch(e)}handleIODispatch(e){return String(e.action??``)===`import`?this.ioHandlers.handleImport(e):this.ioHandlers.handleExport(e)}handleWatch(e){return this.watchHandlers.handleWatch(e)}handleUnwatch(e){return this.watchHandlers.handleUnwatch(e)}handlePoll(e){return this.watchHandlers.handlePoll(e)}handleHistory(e){return this.ioHandlers.handleHistory(e)}handleExport(e){return this.ioHandlers.handleExport(e)}handleImport(e){return this.ioHandlers.handleImport(e)}handleClear(e){return this.storeHandlers.handleClear(e)}handleDispatch(e){let r=String(e.action??``);switch(r){case`set`:return this.storeHandlers.handleSet(e);case`get`:return this.storeHandlers.handleGet(e);case`delete`:return this.storeHandlers.handleDelete(e);case`list`:return this.storeHandlers.handleList(e);case`history`:return this.ioHandlers.handleHistory(e);case`clear`:return this.storeHandlers.handleClear(e);default:return Promise.resolve(t(new n(`VALIDATION`,`Invalid action: "${r}". Expected one of: set, get, delete, list, history, clear`,{toolName:`state_board`})))}}handleStats(){return this.storeHandlers.handleStats()}cleanupExpired(){return this.store.cleanupExpired()}getStore(){return this.store}},g=class{handoffs=new Map;insights=[];ctx;constructor(e){this.ctx=e}async handleCreateTaskHandoff(e){let t=e.description,n=e.constraints,r=e.targetDomain,i=e.decision,a=e.risks,o=e.nextSteps,s;try{let e=this.ctx.pageController;if(e){let t=await e.getPage?.();t&&typeof t.url==`function`&&(s=t.url())}}catch{}let l={id:c().slice(0,8),status:`pending`,description:t,constraints:n,targetDomain:r,decision:i,risks:a,nextSteps:o,pageUrl:s,createdAt:Date.now()};return this.handoffs.set(l.id,l),{taskId:l.id,status:l.status,description:l.description,constraints:l.constraints,targetDomain:l.targetDomain,decision:l.decision,risks:l.risks,nextSteps:l.nextSteps,pageUrl:l.pageUrl,createdAt:new Date(l.createdAt).toISOString(),totalActiveHandoffs:this.handoffs.size}}async handleCompleteTaskHandoff(e){let t=e.taskId,n=e.summary,r=e.keyFindings,i=e.artifacts,a=this.handoffs.get(t);if(!a)throw Error(`Task handoff "${t}" not found. Active IDs: ${[...this.handoffs.keys()].join(`, `)||`(none)`}`);if(a.status===`completed`)throw Error(`Task handoff "${t}" is already completed`);return a.status=`completed`,a.completedAt=Date.now(),a.summary=n,a.keyFindings=r,a.artifacts=i,{taskId:a.id,status:`completed`,summary:a.summary,keyFindings:a.keyFindings,artifacts:a.artifacts,durationMs:a.completedAt-a.createdAt}}async handleGetTaskContext(e){let t=e.taskId;if(t){let e=this.handoffs.get(t);if(!e)throw Error(`Task handoff "${t}" not found`);return{handoff:this.serializeHandoff(e)}}let n=[...this.handoffs.values()].map(e=>this.serializeHandoff(e)),r=n.filter(e=>e.status!==`completed`),i=n.filter(e=>e.status===`completed`);return{active:r,completed:i,sessionInsights:this.insights.map(e=>({id:e.id,category:e.category,content:e.content,confidence:e.confidence,timestamp:new Date(e.timestamp).toISOString(),sourceTaskId:e.sourceTaskId})),summary:{totalActive:r.length,totalCompleted:i.length,totalInsights:this.insights.length}}}async handleAppendSessionInsight(e){let t=e.category,n=e.content,r=e.confidence??1,i=[...this.handoffs.values()].find(e=>e.status===`in_progress`||e.status===`pending`),a={id:c().slice(0,8),category:t,content:n,confidence:r,timestamp:Date.now(),sourceTaskId:i?.id};return this.insights.push(a),{insightId:a.id,category:a.category,totalInsights:this.insights.length,totalByCategory:this.getInsightCountByCategory()}}serializeHandoff(e){return{taskId:e.id,status:e.status,description:e.description,constraints:e.constraints,targetDomain:e.targetDomain,decision:e.decision,risks:e.risks,nextSteps:e.nextSteps,pageUrl:e.pageUrl,createdAt:new Date(e.createdAt).toISOString(),completedAt:e.completedAt?new Date(e.completedAt).toISOString():void 0,summary:e.summary,keyFindings:e.keyFindings,artifacts:e.artifacts}}getInsightCountByCategory(){let e={};for(let t of this.insights)e[t.category]=(e[t.category]??0)+1;return e}snapshots=new Map;async handleSavePageSnapshot(e){let t=e.label,n=this.ctx.pageController;if(!n)throw Error(`No page controller available`);let r=await n.getPage();if(!r)throw Error(`No active page to snapshot`);let i=r.url(),a=[];try{let e=await r.createCDPSession();a=(await e.send(`Network.getAllCookies`)).cookies.map(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path})),await e.detach()}catch{}let o={},s={};try{o=await r.evaluate(()=>{let e={};for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n&&(e[n]=window.localStorage.getItem(n)??``)}return e}),s=await r.evaluate(()=>{let e={};for(let t=0;t<window.sessionStorage.length;t++){let n=window.sessionStorage.key(t);n&&(e[n]=window.sessionStorage.getItem(n)??``)}return e})}catch{}let l={id:c().slice(0,8),url:i,cookies:a,localStorage:o,sessionStorage:s,timestamp:Date.now(),label:t};return this.snapshots.set(l.id,l),{snapshotId:l.id,url:l.url,cookieCount:l.cookies.length,localStorageKeys:Object.keys(l.localStorage).length,sessionStorageKeys:Object.keys(l.sessionStorage).length,label:l.label}}async handleRestorePageSnapshot(t){let n=t.snapshotId;if(!n)throw Error(`snapshotId is required`);let r=this.snapshots.get(n);if(!r)throw Error(`Snapshot "${n}" not found`);let i=this.ctx.pageController;if(!i)throw Error(`No page controller available`);let a=await i.getPage();if(!a)throw Error(`No active page for restoration`);if(await a.goto(r.url,{waitUntil:`domcontentloaded`,timeout:e}),r.cookies.length>0)try{let e=await a.createCDPSession();await e.send(`Network.setCookies`,{cookies:r.cookies.map(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path}))}),await e.detach()}catch{}try{await a.evaluate((e,t)=>{window.localStorage.clear();for(let[t,n]of Object.entries(e))window.localStorage.setItem(t,n);window.sessionStorage.clear();for(let[e,n]of Object.entries(t))window.sessionStorage.setItem(e,n)},r.localStorage,r.sessionStorage)}catch{}return{restored:!0,snapshotId:r.id,url:r.url,cookiesRestored:r.cookies.length,localStorageKeysRestored:Object.keys(r.localStorage).length,sessionStorageKeysRestored:Object.keys(r.sessionStorage).length}}async handleListPageSnapshots(){let e=[...this.snapshots.values()].map(e=>({id:e.id,url:e.url,label:e.label,cookieCount:e.cookies.length,localStorageKeys:Object.keys(e.localStorage).length,sessionStorageKeys:Object.keys(e.sessionStorage).length,createdAt:new Date(e.timestamp).toISOString()}));return{snapshots:e,total:e.length}}};export{g as CoordinationHandlers,h as SharedStateBoardHandlers};
|
|
Binary file
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./logger-CCikqqvj.mjs";import{t}from"./ToolError-g3rjWzhx.mjs";import{a as n,o as r,r as i,t as a}from"./parse-args-ngRrvF9e.mjs";import"./definitions-aeRd5DAR.mjs";import"./handlers-DB6xVVWq.mjs";import"./definitions-Fetw_Cge.mjs";var o=class{deps;constructor(e){this.deps=e}async handleDebuggerLifecycle(e){return e.action===`enable`?(await this.deps.debuggerManager.init(),await this.deps.runtimeInspector.init(),await this.deps.debuggerManager.initAdvancedFeatures(this.deps.runtimeInspector),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Debugger enabled`,enabled:this.deps.debuggerManager.isEnabled()},null,2)}]}):(await this.deps.debuggerManager.disable(),await this.deps.runtimeInspector.disable(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Debugger disabled`},null,2)}]})}async handleDebuggerPause(e){await this.deps.debuggerManager.pause();try{let e=await this.deps.debuggerManager.waitForPaused(500);return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!0,message:`Execution paused`,reason:e.reason,location:e.callFrames[0]?.location},null,2)}]}}catch{return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!1,message:`Pause requested; no paused event observed yet`},null,2)}]}}}async handleDebuggerResume(e){let t=this.deps.debuggerManager.getPausedState()!==null;return await this.deps.debuggerManager.resume(),{content:[{type:`text`,text:JSON.stringify({success:!0,resumed:t,message:t?`Execution resumed`:`Resume requested; debugger was not paused`},null,2)}]}}},s=class{deps;constructor(e){this.deps=e}async handleDebuggerStepInto(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step while not paused`,hint:`The debugger must be paused at a breakpoint to perform step operations. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepInto(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped into`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step into failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}async handleDebuggerStepOver(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step while not paused`,hint:`The debugger must be paused at a breakpoint to perform step operations. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepOver(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped over`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step over failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}async handleDebuggerStepOut(t){let n=this.deps.debuggerManager;if(!n.isEnabled())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Debugger not enabled`,hint:`Call debugger_lifecycle({ action: 'enable' })() first to enable the debugger`},null,2)}]};if(!n.isPaused())return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Cannot step out while not paused`,hint:`The debugger must be paused at a breakpoint to perform step out. Set one with breakpoint({ action: 'set', type: 'code', ... }) or pause with debugger_pause().`,currentState:`running`},null,2)}]};try{return await n.stepOut(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Stepped out`},null,2)}]}}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(`Step out failed: ${n}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:n},null,2)}]}}}},c=class{deps;constructor(e){this.deps=e}async handleDebuggerEvaluate(e){let t=r(e,`expression`,``),n=r(e,`callFrameId`),i=await this.deps.runtimeInspector.evaluate(t,n);return{content:[{type:`text`,text:JSON.stringify({success:!0,expression:t,result:i},null,2)}]}}async handleDebuggerEvaluateGlobal(e){let t=r(e,`expression`,``),n=await this.deps.runtimeInspector.evaluateGlobal(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,expression:t,result:n},null,2)}]}}},l=class{deps;constructor(e){this.deps=e}async handleDebuggerWaitForPaused(e){let n=i(e,`timeout`,3e4);try{let e=await this.deps.debuggerManager.waitForPaused(n);return{content:[{type:`text`,text:JSON.stringify({success:!0,paused:!0,reason:e.reason,location:e.callFrames[0]?.location,hitBreakpoints:e.hitBreakpoints},null,2)}]}}catch(e){if(e instanceof t)throw e;return{content:[{type:`text`,text:JSON.stringify({success:!1,paused:!1,message:e instanceof Error?e.message:`Timeout waiting for paused event`},null,2)}]}}}async handleDebuggerGetPausedState(e){let t=this.deps.debuggerManager.getPausedState();return t?{content:[{type:`text`,text:JSON.stringify({paused:!0,reason:t.reason,frameCount:t.callFrames.length,topFrame:{functionName:t.callFrames[0]?.functionName,location:t.callFrames[0]?.location},hitBreakpoints:t.hitBreakpoints,timestamp:t.timestamp},null,2)}]}:{content:[{type:`text`,text:JSON.stringify({paused:!1,message:`Debugger is not paused`},null,2)}]}}async handleGetCallStack(e){let t=await this.deps.runtimeInspector.getCallStack();return t?{content:[{type:`text`,text:JSON.stringify({success:!0,callStack:{frameCount:t.callFrames.length,reason:t.reason,frames:t.callFrames.map((e,t)=>({index:t,callFrameId:e.callFrameId,functionName:e.functionName,location:`${e.location.url}:${e.location.lineNumber}:${e.location.columnNumber}`,scopeCount:e.scopeChain.length}))}},null,2)}]}:{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Not in paused state. Set a breakpoint and trigger it first.`},null,2)}]}}};function u(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var d=class{deps;constructor(e){this.deps=e}async handleSaveSession(e){let t=r(e,`filePath`),i=n(e,`metadata`);try{let e=await this.deps.debuggerManager.saveSession(t,i);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session saved successfully`,filePath:e,breakpointCount:this.deps.debuggerManager.listBreakpoints().length},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to save session`,error:u(e)},null,2)}]}}}async handleLoadSession(e){let t=r(e,`filePath`),n=r(e,`sessionData`);try{if(t)await this.deps.debuggerManager.loadSessionFromFile(t);else if(n)await this.deps.debuggerManager.importSession(n);else throw Error(`Either filePath or sessionData must be provided`);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session loaded successfully`,breakpointCount:this.deps.debuggerManager.listBreakpoints().length,pauseOnExceptions:this.deps.debuggerManager.getPauseOnExceptionsState()},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to load session`,error:u(e)},null,2)}]}}}async handleExportSession(e){let t=n(e,`metadata`);try{let e=this.deps.debuggerManager.exportSession(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Session exported successfully`,session:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to export session`,error:u(e)},null,2)}]}}}async handleListSessions(e){try{let e=await this.deps.debuggerManager.listSavedSessions();return{content:[{type:`text`,text:JSON.stringify({success:!0,count:e.length,sessions:e.map(e=>({path:e.path,timestamp:e.timestamp,date:new Date(e.timestamp).toISOString(),metadata:e.metadata}))},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list sessions`,error:u(e)},null,2)}]}}}},f=class{deps;constructor(e){this.deps=e}async handleBreakpointSet(e){let t=r(e,`url`),n=r(e,`scriptId`),a=i(e,`lineNumber`,0),o=i(e,`columnNumber`),s=r(e,`condition`),c;if(t)c=await this.deps.debuggerManager.setBreakpointByUrl({url:t,lineNumber:a,columnNumber:o,condition:s});else if(n)c=await this.deps.debuggerManager.setBreakpoint({scriptId:n,lineNumber:a,columnNumber:o,condition:s});else throw Error(`Either url or scriptId must be provided`);return this.deps.eventBus?.emit(`debugger:breakpoint_hit`,{scriptId:c.location?.scriptId??n??``,lineNumber:c.location?.lineNumber??a,timestamp:new Date().toISOString()}),{content:[{type:`text`,text:JSON.stringify({success:!0,breakpoint:{breakpointId:c.breakpointId,location:c.location,condition:c.condition,enabled:c.enabled}},null,2)}]}}async handleBreakpointRemove(e){let t=r(e,`breakpointId`,``);return await this.deps.debuggerManager.removeBreakpoint(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Breakpoint ${t} removed`},null,2)}]}}async handleBreakpointList(e){let t=this.deps.debuggerManager.listBreakpoints();return{content:[{type:`text`,text:JSON.stringify({count:t.length,breakpoints:t.map(e=>({breakpointId:e.breakpointId,location:e.location,condition:e.condition,enabled:e.enabled,hitCount:e.hitCount}))},null,2)}]}}},p=class{deps;constructor(e){this.deps=e}async handleBreakpointSetOnException(e){let t=r(e,`state`,`none`);return await this.deps.debuggerManager.setPauseOnExceptions(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Pause on exceptions set to: ${t}`,state:t},null,2)}]}}};function m(e){return typeof e.ensureAdvancedFeatures==`function`}function h(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var g=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){m(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async handleXHRBreakpointSet(e){try{let t=r(e,`urlPattern`,``);await this.ensureAdvancedFeaturesIfSupported();let n=await this.deps.debuggerManager.getXHRManager().setXHRBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`XHR breakpoint set`,breakpointId:n,urlPattern:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set XHR breakpoint`,error:h(e)},null,2)}]}}}async handleXHRBreakpointRemove(e){try{let t=r(e,`breakpointId`,``);await this.ensureAdvancedFeaturesIfSupported();let n=await this.deps.debuggerManager.getXHRManager().removeXHRBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:n,message:n?`XHR breakpoint removed`:`XHR breakpoint not found`,breakpointId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove XHR breakpoint`,error:h(e)},null,2)}]}}}async handleXHRBreakpointList(e){try{await this.ensureAdvancedFeaturesIfSupported();let e=this.deps.debuggerManager.getXHRManager().getAllXHRBreakpoints();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} XHR breakpoint(s)`,breakpoints:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list XHR breakpoints`,error:h(e)},null,2)}]}}}};function _(e){return typeof e.ensureAdvancedFeatures==`function`}function v(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var y=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){_(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async handleEventBreakpointSet(e){try{let t=r(e,`eventName`,``),n=r(e,`targetName`);await this.ensureAdvancedFeaturesIfSupported();let i=await this.deps.debuggerManager.getEventManager().setEventListenerBreakpoint(t,n);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Event breakpoint set`,breakpointId:i,eventName:t,targetName:n},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set event breakpoint`,error:v(e)},null,2)}]}}}async handleEventBreakpointSetCategory(e){try{let t=r(e,`category`,``);await this.ensureAdvancedFeaturesIfSupported();let n=this.deps.debuggerManager.getEventManager(),i;switch(t){case`mouse`:i=await n.setMouseEventBreakpoints();break;case`keyboard`:i=await n.setKeyboardEventBreakpoints();break;case`timer`:i=await n.setTimerEventBreakpoints();break;case`websocket`:i=await n.setWebSocketEventBreakpoints();break;default:throw Error(`Unknown category: ${t}`)}return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Set ${i.length} ${t} event breakpoint(s)`,category:t,breakpointIds:i},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to set event breakpoints`,error:v(e)},null,2)}]}}}async handleEventBreakpointRemove(e){try{let t=r(e,`breakpointId`,``);await this.ensureAdvancedFeaturesIfSupported();let n=await this.deps.debuggerManager.getEventManager().removeEventListenerBreakpoint(t);return{content:[{type:`text`,text:JSON.stringify({success:n,message:n?`Event breakpoint removed`:`Event breakpoint not found`,breakpointId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove event breakpoint`,error:v(e)},null,2)}]}}}async handleEventBreakpointList(e){try{await this.ensureAdvancedFeaturesIfSupported();let e=this.deps.debuggerManager.getEventManager().getAllEventBreakpoints();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} event breakpoint(s)`,breakpoints:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list event breakpoints`,error:v(e)},null,2)}]}}}};function b(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var x=class{deps;constructor(e){this.deps=e}async handleWatchAdd(e){try{let t=r(e,`expression`,``),n=r(e,`name`),i=this.deps.debuggerManager.getWatchManager().addWatch(t,n);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Watch expression added`,watchId:i,expression:t,name:n||t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add watch expression`,error:b(e)},null,2)}]}}}async handleWatchRemove(e){try{let t=r(e,`watchId`,``),n=this.deps.debuggerManager.getWatchManager().removeWatch(t);return{content:[{type:`text`,text:JSON.stringify({success:n,message:n?`Watch expression removed`:`Watch expression not found`,watchId:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to remove watch expression`,error:b(e)},null,2)}]}}}async handleWatchList(e){try{let e=this.deps.debuggerManager.getWatchManager().getAllWatches();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} watch expression(s)`,watches:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list watch expressions`,error:b(e)},null,2)}]}}}async handleWatchEvaluateAll(e){try{let t=r(e,`callFrameId`),n=await this.deps.debuggerManager.getWatchManager().evaluateAll(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Evaluated ${n.length} watch expression(s)`,results:n},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to evaluate watch expressions`,error:b(e)},null,2)}]}}}async handleWatchClearAll(e){try{return this.deps.debuggerManager.getWatchManager().clearAll(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`All watch expressions cleared`},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to clear watch expressions`,error:b(e)},null,2)}]}}}};const S=(e,t)=>{if(e instanceof Error)return e.message;if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`)return t}return t};var C=class{deps;constructor(e){this.deps=e}async handleGetScopeVariablesEnhanced(e){let t=r(e,`callFrameId`),n=a(e,`includeObjectProperties`),o=i(e,`maxDepth`),s=a(e,`skipErrors`,!0);try{let e=await this.deps.debuggerManager.getScopeVariables({callFrameId:t,includeObjectProperties:n,maxDepth:o,skipErrors:s});return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:S(e,`Failed to get scope variables`),error:String(e)},null,2)}]}}}async handleGetObjectProperties(e){let t=r(e,`objectId`,``);if(!t)return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`objectId parameter is required`},null,2)}]};try{let e=await this.deps.debuggerManager.getObjectPropertiesById(t);return{content:[{type:`text`,text:JSON.stringify({success:!0,propertyCount:e.length,properties:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:S(e,`Failed to get object properties`),error:String(e)},null,2)}]}}}};function w(e){return typeof e.ensureAdvancedFeatures==`function`}function T(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return t}return String(e)}var E=class{deps;constructor(e){this.deps=e}async ensureAdvancedFeaturesIfSupported(){w(this.deps.debuggerManager)&&await this.deps.debuggerManager.ensureAdvancedFeatures()}async getBlackboxManager(){return await this.ensureAdvancedFeaturesIfSupported(),this.deps.debuggerManager.getBlackboxManager()}async handleBlackboxAdd(e){try{let t=r(e,`urlPattern`,``);return await(await this.getBlackboxManager()).blackboxByPattern(t),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Script pattern blackboxed`,urlPattern:t},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add blackbox pattern`,error:T(e)},null,2)}]}}}async handleBlackboxAddCommon(e){try{return await(await this.getBlackboxManager()).blackboxCommonLibraries(),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Blackboxed common library patterns`},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to add common blackbox patterns`,error:T(e)},null,2)}]}}}async handleBlackboxList(e){try{let e=(await this.getBlackboxManager()).getAllBlackboxedPatterns();return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Found ${e.length} blackboxed pattern(s)`,patterns:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to list blackbox patterns`,error:T(e)},null,2)}]}}}},D=class{debuggerManager;runtimeInspector;debuggerControl;debuggerStepping;debuggerEvaluate;debuggerState;sessionManagement;breakpointBasic;breakpointException;xhrBreakpoint;eventBreakpoint;watchExpressions;scopeInspection;blackbox;constructor(e,t,n){this.debuggerManager=e,this.runtimeInspector=t;let r={debuggerManager:this.debuggerManager,runtimeInspector:this.runtimeInspector};this.debuggerControl=new o(r),this.debuggerStepping=new s({debuggerManager:this.debuggerManager}),this.debuggerEvaluate=new c({runtimeInspector:this.runtimeInspector}),this.debuggerState=new l(r),this.sessionManagement=new d({debuggerManager:this.debuggerManager}),this.breakpointBasic=new f({debuggerManager:this.debuggerManager,eventBus:n}),this.breakpointException=new p({debuggerManager:this.debuggerManager}),this.xhrBreakpoint=new g({debuggerManager:this.debuggerManager}),this.eventBreakpoint=new y({debuggerManager:this.debuggerManager}),this.watchExpressions=new x({debuggerManager:this.debuggerManager}),this.scopeInspection=new C(r),this.blackbox=new E({debuggerManager:this.debuggerManager})}async handleDebuggerLifecycle(e){return this.debuggerControl.handleDebuggerLifecycle(e)}async handleDebuggerPause(e){return this.debuggerControl.handleDebuggerPause(e)}async handleDebuggerResume(e){return this.debuggerControl.handleDebuggerResume(e)}async handleDebuggerStepInto(e){return this.debuggerStepping.handleDebuggerStepInto(e)}async handleDebuggerStepOver(e){return this.debuggerStepping.handleDebuggerStepOver(e)}async handleDebuggerStepOut(e){return this.debuggerStepping.handleDebuggerStepOut(e)}async handleDebuggerEvaluate(e){return this.debuggerEvaluate.handleDebuggerEvaluate(e)}async handleDebuggerEvaluateGlobal(e){return this.debuggerEvaluate.handleDebuggerEvaluateGlobal(e)}async handleDebuggerWaitForPaused(e){return this.debuggerState.handleDebuggerWaitForPaused(e)}async handleDebuggerGetPausedState(e){return this.debuggerState.handleDebuggerGetPausedState(e)}async handleGetCallStack(e){return this.debuggerState.handleGetCallStack(e)}async handleSaveSession(e){return this.sessionManagement.handleSaveSession(e)}async handleLoadSession(e){return this.sessionManagement.handleLoadSession(e)}async handleExportSession(e){return this.sessionManagement.handleExportSession(e)}async handleListSessions(e){return this.sessionManagement.handleListSessions(e)}async handleBreakpointSet(e){return this.breakpointBasic.handleBreakpointSet(e)}async handleBreakpointRemove(e){return this.breakpointBasic.handleBreakpointRemove(e)}async handleBreakpointList(e){return this.breakpointBasic.handleBreakpointList(e)}async handleBreakpointSetOnException(e){return this.breakpointException.handleBreakpointSetOnException(e)}async handleXHRBreakpointSet(e){return this.xhrBreakpoint.handleXHRBreakpointSet(e)}async handleXHRBreakpointRemove(e){return this.xhrBreakpoint.handleXHRBreakpointRemove(e)}async handleXHRBreakpointList(e){return this.xhrBreakpoint.handleXHRBreakpointList(e)}async handleEventBreakpointSet(e){return this.eventBreakpoint.handleEventBreakpointSet(e)}async handleEventBreakpointSetCategory(e){return this.eventBreakpoint.handleEventBreakpointSetCategory(e)}async handleEventBreakpointRemove(e){return this.eventBreakpoint.handleEventBreakpointRemove(e)}async handleEventBreakpointList(e){return this.eventBreakpoint.handleEventBreakpointList(e)}async handleWatchAdd(e){return this.watchExpressions.handleWatchAdd(e)}async handleWatchRemove(e){return this.watchExpressions.handleWatchRemove(e)}async handleWatchList(e){return this.watchExpressions.handleWatchList(e)}async handleWatchEvaluateAll(e){return this.watchExpressions.handleWatchEvaluateAll(e)}async handleWatchClearAll(e){return this.watchExpressions.handleWatchClearAll(e)}async handleGetScopeVariablesEnhanced(e){return this.scopeInspection.handleGetScopeVariablesEnhanced(e)}async handleGetObjectProperties(e){return this.scopeInspection.handleGetObjectProperties(e)}async handleBlackboxAdd(e){return this.blackbox.handleBlackboxAdd(e)}async handleBlackboxAddCommon(e){return this.blackbox.handleBlackboxAddCommon(e)}async handleBlackboxList(e){return this.blackbox.handleBlackboxList(e)}async handleBreakpoint(e){let t=String(e.action??``),n=String(e.type??`code`);switch(n){case`code`:switch(t){case`set`:return this.breakpointBasic.handleBreakpointSet(e);case`remove`:return this.breakpointBasic.handleBreakpointRemove(e);case`list`:return this.breakpointBasic.handleBreakpointList(e)}break;case`xhr`:switch(t){case`set`:return this.xhrBreakpoint.handleXHRBreakpointSet(e);case`remove`:return this.xhrBreakpoint.handleXHRBreakpointRemove(e);case`list`:return this.xhrBreakpoint.handleXHRBreakpointList(e)}break;case`event`:switch(t){case`set`:return this.eventBreakpoint.handleEventBreakpointSet(e);case`remove`:return this.eventBreakpoint.handleEventBreakpointRemove(e);case`list`:return this.eventBreakpoint.handleEventBreakpointList(e)}break;case`event_category`:if(t===`set`)return this.eventBreakpoint.handleEventBreakpointSetCategory(e);break;case`exception`:if(t===`set`)return this.breakpointException.handleBreakpointSetOnException(e);break}return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Invalid breakpoint action/type: ${t}/${n}. Valid types: code, xhr, event, event_category, exception. Valid actions: set, remove, list.`})}]}}async handleWatch(e){let t=String(e.action??``);switch(t){case`add`:return this.watchExpressions.handleWatchAdd(e);case`remove`:return this.watchExpressions.handleWatchRemove(e);case`list`:return this.watchExpressions.handleWatchList(e);case`evaluate_all`:return this.watchExpressions.handleWatchEvaluateAll(e);case`clear_all`:return this.watchExpressions.handleWatchClearAll(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown watch action: ${t}. Valid: add, remove, list, evaluate_all, clear_all`})}]}}}async handleDebuggerStep(e){let t=String(e.direction??`over`);switch(t){case`into`:return this.debuggerStepping.handleDebuggerStepInto(e);case`over`:return this.debuggerStepping.handleDebuggerStepOver(e);case`out`:return this.debuggerStepping.handleDebuggerStepOut(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown direction: ${t}. Valid: into, over, out`})}]}}}async handleDebuggerEvaluateDispatch(e){return String(e.context??`frame`)===`global`?this.debuggerEvaluate.handleDebuggerEvaluateGlobal(e):this.debuggerEvaluate.handleDebuggerEvaluate(e)}async handleDebuggerSession(e){let t=String(e.action??``);switch(t){case`save`:return this.sessionManagement.handleSaveSession(e);case`load`:return this.sessionManagement.handleLoadSession(e);case`export`:return this.sessionManagement.handleExportSession(e);case`list`:return this.sessionManagement.handleListSessions(e);default:return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Unknown action: ${t}. Valid actions: save, load, export, list`})}]}}}};export{D as DebuggerToolHandlers};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./tool-builder-CpLh-UQd.mjs";const t=[e(`ai_hook`,e=>e.desc(`Manage AI hooks. Actions: inject (inject code into page), get_data (retrieve captured hook data), list (all active hooks), clear (remove hook data by id or all), toggle (enable/disable a hook), export (export data as JSON/CSV).`).enum(`action`,[`inject`,`get_data`,`list`,`clear`,`toggle`,`export`],`Operation to perform`).string(`hookId`,`Hook identifier (required for inject/get_data/toggle; optional for clear/export)`).string(`code`,`Hook code to inject (required for action=inject)`).enum(`method`,[`evaluateOnNewDocument`,`evaluate`],`Injection method (for action=inject)`,{default:`evaluate`}).boolean(`enabled`,`Enable or disable hook (required for action=toggle)`).enum(`format`,[`json`,`csv`],`Export format (for action=export)`,{default:`json`}).required(`action`))],n=[e(`hook_preset`,e=>e.desc(`Install a pre-built JavaScript hook from 20+ built-in presets (eval, atob/btoa, Proxy, Reflect, Object.defineProperty, etc.), or provide customTemplate/customTemplates to install your own reusable hook bodies. Use listPresets=true to see all available preset descriptions.`).string(`preset`,`Single preset name to install. Accepts built-in preset ids or ids provided by customTemplate/customTemplates.`).array(`presets`,{type:`string`},`List of preset names to install simultaneously. Accepts built-in ids and custom template ids.`).prop(`customTemplate`,{type:`object`,properties:{id:{type:`string`,description:`Stable preset id, for example deobfuscation-sinks`},description:{type:`string`,description:`Human-readable description for listPresets output.`},body:{type:`string`,description:`Hook body snippet inserted into the preset wrapper.`}},required:[`id`,`body`],description:`Inline custom template. body should contain the hook body inserted into the standard buildHookCode wrapper. Use {{STACK_CODE}} and {{LOG_FN}} placeholders when needed.`}).prop(`customTemplates`,{type:`array`,items:{type:`object`,properties:{id:{type:`string`},description:{type:`string`},body:{type:`string`}},required:[`id`,`body`]},description:`List of inline custom templates to register for this invocation.`}).boolean(`captureStack`,`Include call stack in captured data (has performance impact)`,{default:!1}).boolean(`logToConsole`,`Log hook events to browser console`,{default:!0}).enum(`method`,[`evaluate`,`evaluateOnNewDocument`],`Injection method: evaluate=current page, evaluateOnNewDocument=before page scripts`,{default:`evaluate`}).boolean(`listPresets`,`Set to true to list all available presets with descriptions instead of installing.`,{default:!1}))];export{n,t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./tool-builder-CpLh-UQd.mjs";const t=[e(`canvas_engine_fingerprint`,e=>e.desc(`Detect Canvas/WebGL game engines in the page.`).query()),e(`canvas_scene_dump`,e=>e.desc(`Extract the full scene tree / display list from a detected canvas engine.`).string(`canvasId`,`Canvas element ID or index to target`).number(`maxDepth`,`Maximum tree traversal depth`,{default:20}).boolean(`onlyInteractive`,`Only include interactive (mouseEnabled) nodes`,{default:!1}).boolean(`onlyVisible`,`Only include visible nodes`,{default:!1}).query()),e(`canvas_pick_object_at_point`,e=>e.desc(`Pick / hit-test the topmost object at a given screen coordinate using the engine's hit-test system`).number(`x`,`Screen X coordinate`).number(`y`,`Screen Y coordinate`).string(`canvasId`,`Canvas element ID or index to target`).boolean(`highlight`,`Draw a highlight rectangle on the picked object`,{default:!1}).required(`x`,`y`).readOnly()),e(`canvas_trace_click_handler`,e=>e.desc(`Trace a click event from DOM to JS call stack.`).number(`x`,`Screen X coordinate to click`).number(`y`,`Screen Y coordinate to click`).string(`canvasId`,`Canvas element ID or index to target`).enum(`breakpointType`,[`click`,`mousedown`,`pointerdown`],`Event breakpoint type`,{default:`click`}).number(`maxFrames`,`Maximum call stack frames to capture`,{default:50}).requiredOpenWorld(`x`,`y`))],n=[{name:`skia_detect_renderer`,description:`Detect the active Skia renderer backend from the current page context.`,inputSchema:{type:`object`,properties:{},required:[]}},{name:`skia_extract_scene`,description:`Extract a lightweight Skia scene tree from the selected canvas.`,inputSchema:{type:`object`,properties:{canvasId:{type:`string`}},required:[]}},{name:`skia_correlate_objects`,description:`Correlate requested Skia node identifiers with the extracted scene tree.`,inputSchema:{type:`object`,properties:{canvasId:{type:`string`,description:`Optional canvas element ID to target for correlation.`},skiaNodeIds:{type:`array`,items:{type:`string`},description:`Optional list of Skia node identifiers to correlate.`}},required:[]}}];export{t as n,n as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./tool-builder-CpLh-UQd.mjs";const t={type:`object`,additionalProperties:!1,properties:{allowPrivateNetwork:{type:`boolean`,description:`Allow access to private/reserved targets only when the request also matches allowedHosts or allowedCidrs.`},allowInsecureHttp:{type:`boolean`,description:`Allow non-loopback HTTP targets only when the request also matches allowedHosts or allowedCidrs.`},allowedHosts:{type:`array`,items:{type:`string`},description:`Exact hostname or host:port allowlist for the primary target (for example ["labs.example.com", "localhost:8080"]).`},allowedCidrs:{type:`array`,items:{type:`string`},description:`CIDR allowlist applied after DNS resolution (for example ["10.10.0.0/16", "192.168.1.10/32"]).`},allowedRedirectHosts:{type:`array`,items:{type:`string`},description:`Optional hostname or host:port allowlist for redirect hops. When omitted, redirects inherit allowedHosts/allowedCidrs.`}},description:`Request-level network authorization policy. Use this instead of process-wide bypasses when you need to reach a real lab target, private address, or plain HTTP service.`},n=[e(`js_bundle_search`,e=>e.desc(`Fetch a remote JS bundle and search it with named regex patterns, with caching and noise filtering.`).string(`url`,`Remote URL of the JavaScript bundle to analyze`).array(`patterns`,{type:`object`,properties:{name:{type:`string`,description:`Human-readable label for this pattern`},regex:{type:`string`,description:`JavaScript regex string`},contextBefore:{type:`number`,description:`Characters of context before match (default: 80)`},contextAfter:{type:`number`,description:`Characters of context after match (default: 80)`}},required:[`name`,`regex`]},`Named regex patterns to search for`).boolean(`cacheBundle`,`Cache the bundle for 5 minutes to avoid re-downloads`,{default:!0}).boolean(`stripNoise`,`Skip matches inside SVG path data or base64 blobs`,{default:!0}).number(`maxMatches`,`Maximum matches to return per pattern`,{default:10,minimum:1,maximum:1e3}).prop(`networkPolicy`,t).requiredOpenWorld(`url`,`patterns`)),e(`page_script_register`,e=>e.desc(`Register a named reusable JS snippet in the Script Library. Execute with page_script_run.`).string(`name`,`Unique script name (e.g. "my_extractor")`).string(`code`,'JavaScript expression/IIFE to register. Use `typeof __params__ !== "undefined" ? __params__ : {}` to safely access runtime parameters.').string(`description`,`Optional human-readable description of the script`).required(`name`,`code`)),e(`page_script_run`,e=>e.desc(`Execute a named script from the Script Library with optional runtime params (__params__).`).string(`name`,`Script name to run (built-in or registered)`).prop(`params`,{type:`object`,additionalProperties:!0,description:`Optional parameters injected as __params__ (must be JSON-serializable)`}).requiredOpenWorld(`name`)),e(`api_probe_batch`,e=>e.desc(`Batch-probe API endpoints in browser context with auto token injection and HTML skip.`).string(`baseUrl`,`Base URL prefix (e.g. "https://chat.qwen.ai") — trailing slash will be stripped`).array(`paths`,{type:`string`},`Paths to probe (e.g. ["/api/v1/users", "/api/v1/chats"])`).enum(`method`,[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`],`HTTP method for all probes`,{default:`GET`}).object(`headers`,{additionalProperties:{type:`string`}},`Additional HTTP headers to include in all requests`).string(`bodyTemplate`,`JSON body string to send for POST/PUT/PATCH requests (optional)`).array(`includeBodyStatuses`,{type:`number`},`Status codes for which to include response body snippet (default: [200, 201, 204])`).number(`maxBodySnippetLength`,`Max characters per response body snippet`,{default:500,minimum:0,maximum:1e4}).boolean(`autoInjectAuth`,`Auto-inject Bearer token from localStorage (token / active_token / access_token).`,{default:!0}).prop(`networkPolicy`,t).requiredOpenWorld(`baseUrl`,`paths`)),e(`list_extension_workflows`,e=>e.desc(`List runtime-loaded extension workflows from plugins/ or workflows/ directories.`).query()),e(`run_extension_workflow`,e=>e.desc(`Execute an extension workflow by workflowId with optional config and timeout overrides.`).string(`workflowId`,`Registered extension workflow id to execute`).string(`profile`,`Optional profile label exposed to the workflow execution context`).prop(`config`,{type:`object`,additionalProperties:!0,description:`Optional config overrides read through ctx.getConfig(path, fallback)`}).prop(`nodeInputOverrides`,{type:`object`,additionalProperties:{type:`object`,additionalProperties:!0},description:`Optional shallow input overrides keyed by workflow node id`}).number(`timeoutMs`,`Optional override for total workflow timeout in milliseconds`).requiredOpenWorld(`workflowId`))];export{n as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./tool-builder-CpLh-UQd.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. If pid is omitted, the active browser renderer PID is auto-discovered from the current browser session.`).number(`pid`,`Target process ID (optional when a browser session is attached)`).string(`address`,`Memory address to read (hex string like "0x12345678")`).number(`size`,`Number of bytes to read`).required(`address`,`size`)),e(`memory_write`,e=>e.desc(`Write data to process memory at a given address. If pid is omitted, the active browser renderer PID is auto-discovered from the current browser session.`).number(`pid`,`Target process ID (optional when a browser session is attached)`).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(`address`,`data`)),e(`memory_scan`,e=>e.desc(`Scan process memory for a pattern or value. Requires elevated privileges. If pid is omitted, the active browser renderer PID is auto-discovered from the current browser session.`).number(`pid`,`Target process ID (optional when a browser session is attached)`).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(`pattern`)),e(`memory_check_protection`,e=>e.desc(`Check memory protection flags at a specific address. If pid is omitted, the active browser renderer PID is auto-discovered from the current browser session.`).number(`pid`,`Target process ID (optional when a browser session is attached)`).string(`address`,`Memory address to check (hex string like "0x12345678")`).required(`address`)),e(`memory_scan_filtered`,e=>e.desc(`Refine a previous memory scan with filtered addresses. If pid is omitted, the active browser renderer PID is auto-discovered from the current browser session.`).number(`pid`,`Target process ID (optional when a browser session is attached)`).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(`pattern`,`addresses`)),e(`memory_batch_write`,e=>e.desc(`Write multiple memory patches at once. If pid is omitted, the active browser renderer PID is auto-discovered from the current browser session.`).number(`pid`,`Target process ID (optional when a browser session is attached)`).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(`patches`)),e(`memory_dump_region`,e=>e.desc(`Dump a process memory region to a binary file for offline analysis. If pid is omitted, the active browser renderer PID is auto-discovered from the current browser session.`).number(`pid`,`Target process ID (optional when a browser session is attached)`).string(`address`,`Start address (hex)`).number(`size`,`Number of bytes to dump`).string(`outputPath`,`Output file path`).required(`address`,`size`,`outputPath`)),e(`memory_list_regions`,e=>e.desc(`List all memory regions in a process with protection flags. If pid is omitted, the active browser renderer PID is auto-discovered from the current browser session.`).number(`pid`,`Target process ID (optional when a browser session is attached)`)),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{t as e}from"./tool-builder-CpLh-UQd.mjs";const t=[e(`dart_strings_extract`,e=>e.desc(`Stream-extract ASCII/UTF-16LE strings from a Dart AOT libapp.so and classify them (urls, paths, classNames, packageRefs, cryptoKeywords, plus customRules). ReDoS-guarded.`).string(`filePath`,`Absolute path to the libapp.so (or arbitrary binary) to extract from`).number(`minLength`,`Minimum string length to emit`,{default:4,minimum:2,maximum:64}).boolean(`includeRaw`,"Include unclassified strings under the `raw` bucket",{default:!1}).boolean(`includeOffsets`,`Include byte offsets[] for each extracted string`,{default:!0}).enum(`encoding`,[`ascii`,`utf16le`,`both`],`Which encodings to scan`,{default:`both`}).number(`maxChunkBytes`,`Streaming chunk size in bytes`).number(`maxOffsetsPerString`,`Cap on offsets recorded per string (excess sets truncated)`,{default:1e3}).enum(`ruleMode`,[`append`,`prepend`,`replace`],`How customRules interact with DEFAULT_RULES`,{default:`append`}).number(`regexTimeoutMs`,`Per-rule .test() wall-clock budget for the ReDoS guard`).number(`scanStride`,`Only emit hits whose offset is divisible by stride (e.g. 4 for pointer-aligned scans)`).object(`scanWindow`,{start:{type:`number`,description:`Inclusive start byte offset`},end:{type:`number`,description:`Exclusive end byte offset`}},`Restrict scanning to a byte range (skip ELF headers, focus on a section, etc.)`).array(`customRules`,{type:`object`,properties:{category:{type:`string`,description:`Category bucket name for matched strings`},pattern:{type:`string`,description:`Regex source (anchored as needed)`},flags:{type:`string`,description:`Regex flags (must be in DART_ALLOWED_REGEX_FLAGS)`},exclude:{type:`string`,description:`Optional exclude regex applied before category match`},excludeFlags:{type:`string`,description:`Flags for the exclude regex`},confidence:{type:`number`,description:`Confidence weight in [0,1] carried onto each matching hit`},enableWhenFileNameMatches:{type:`string`,description:`Rule only fires when source basename matches this regex`},enableWhenFileNameFlags:{type:`string`,description:`Flags for enableWhenFileNameMatches`}},required:[`category`,`pattern`]},`Custom classification rules with safe regex compilation (ReDoS-guarded)`).required(`filePath`).query()),e(`dart_smi_scan`,e=>e.desc(`Recover Dart Small Integer (Smi) constants from a libapp.so by reading aligned little-endian words and stripping the heap-pointer tag bit.`).string(`filePath`,`Absolute path to the libapp.so (or arbitrary binary) to scan`).enum(`width`,[`4`,`8`],`Word width in bytes (4 for ARM32, 8 for ARM64)`,{default:`8`}).number(`stride`,"Bytes between consecutive scan positions; defaults to `width`").number(`minValue`,`Inclusive minimum decoded Smi value`,{default:1}).number(`maxValue`,`Inclusive maximum decoded Smi value`,{default:1e6}).boolean(`includeZero`,`Include decoded-to-zero hits`,{default:!1}).boolean(`includeNegative`,`Include decoded-to-negative hits`,{default:!1}).number(`maxResults`,`Cap on returned hits (truncates with truncated=true)`).number(`maxChunkBytes`,`Streaming chunk size in bytes`).object(`scanWindow`,{start:{type:`number`,description:`Inclusive start byte offset`},end:{type:`number`,description:`Exclusive end byte offset`}},`Restrict scanning to a byte range`).required(`filePath`).query()),e(`dart_symbolize`,e=>e.desc(`Resolve obfuscated Dart identifiers using a developer-supplied Flutter --save-obfuscation-map JSON (flat, pairs, or object shape).`).string(`obfuscationMapFile`,"Absolute path to the obfuscation-map.json emitted by `flutter build ... --extra-gen-snapshot-options=--save-obfuscation-map=FILE`").array(`obfuscatedNames`,{type:`string`,description:`An obfuscated (or original, in reverse mode) identifier`},`List of identifiers to resolve against the map`).enum(`format`,[`auto`,`flat`,`pairs`,`object`],`Force a specific parser; auto sniffs the JSON shape`,{default:`auto`}).enum(`mode`,[`forward`,`reverse`],`Lookup direction (forward: obfuscated→original, reverse: original→obfuscated)`,{default:`forward`}).number(`maxMapBytes`,`Cap on map file size in bytes`,{default:16*1024*1024}).number(`maxLookups`,`Cap on number of lookups attempted (extras go to unresolved)`).required(`obfuscationMapFile`,`obfuscatedNames`).query()),e(`flutter_packages_detect`,e=>e.desc("Detect third-party Dart `package:` refs in a Flutter libapp.so, aggregated and SDK-stdlib-filtered.").string(`filePath`,`Absolute path to the libapp.so (or arbitrary binary) to scan`).boolean(`includeFlutterStdlib`,`Keep Flutter SDK packages in the result`,{default:!1}).boolean(`includeFiles`,"Emit the list of `package:foo/...` files per package",{default:!0}).boolean(`includeOffsets`,`Emit aggregated byte offsets per package`,{default:!1}).integer(`maxFilesPerPackage`,`Per-package file cap (excess marks filesTruncated)`,{minimum:1}).integer(`maxPackages`,`Global package cap (excess marks truncated:true)`,{minimum:1}).array(`extraStdlibPackages`,{type:`string`,minLength:1,maxLength:128},`Additional package names to treat as stdlib (filtered when includeFlutterStdlib=false)`).required(`filePath`).query()),e(`dart_snapshot_header_parse`,e=>e.desc(`Parse the Dart isolate snapshot header in a libapp.so: magic, kind, 32-byte hash, features, target arch. Read-only.`).string(`filePath`,`Absolute path to the libapp.so to parse`).number(`maxScanBytes`,`Upper bound on the byte-scan fallback (defaults to env)`,{minimum:0}).required(`filePath`).query()),e(`dart_version_fingerprint`,e=>e.desc(`Identify Flutter/Dart SDK release from a libapp.so by combining header parse with a built-in (and optionally user-supplied) hash table.`).string(`filePath`,`Absolute path to the libapp.so to fingerprint`).boolean(`includeFeatures`,`Include the raw features array in the response`,{default:!0}).string(`customTablePath`,`Optional path to a JSON file extending the built-in hash table (user wins on collision)`).required(`filePath`).query()),e(`dart_object_pool_dump`,e=>e.desc(`Read-only static dump of the Dart isolate ObjectPool in a libapp.so: classify each slot as smi/mint/double/string/classRef/functionRef/pool/null/unknown.`).string(`filePath`,`Absolute path to the libapp.so to dump`).number(`maxSlots`,`Upper bound on emitted slots (defaults to env)`,{minimum:1}).number(`previewBytes`,`String slot preview byte cap (defaults to env)`,{minimum:0}).string(`grammar`,`Force a cluster grammar by sdkFamily (e.g. "2.10", "2.17", "3.0+"); overrides auto-pick`).object(`fingerprint`,{flutterVersion:{type:`string`},dartSdkRev:{type:`string`},targetArch:{type:`string`}},`Optional pre-supplied snapshot fingerprint to skip internal lookup`).required(`filePath`).query())];export{t};
|