@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.
Files changed (311) hide show
  1. package/README.md +19 -4
  2. package/README.zh.md +19 -4
  3. package/dist/AntiCheatDetector-B-mz4DK_.mjs +1 -0
  4. package/dist/{BrowserSessionCoordinator-QIt3tetp.mjs → BrowserSessionCoordinator-Cdic8FsH.mjs} +1 -1
  5. package/dist/CodeAnalyzerDataFlow-a-NkwcaG.mjs +2 -0
  6. package/dist/CodeInjector-B099WO6x.mjs +1 -0
  7. package/dist/ConsoleMonitor-BZRqrBH-.mjs +306 -0
  8. package/dist/CpuEngine-BC8jayy9.mjs +1 -0
  9. package/dist/DartAotExecutor-B7WVTKsd.mjs +1 -0
  10. package/dist/DartAotLoader-BxdhW-K2.mjs +2 -0
  11. package/dist/DarwinAPI-DzojdfjF.mjs +1 -0
  12. package/dist/{DetailedDataManager-Z77fDl9Z.mjs → DetailedDataManager-Dgh402Gp.mjs} +2 -2
  13. package/dist/ExecutionSandbox-QbWQmzuC.mjs +45 -0
  14. package/dist/ExtensionManager.tools-D3h818Xs.mjs +1 -0
  15. package/dist/FingerprintManager-D9Zlr6be.mjs +1 -0
  16. package/dist/HardwareBreakpoint-C_lJ22bj.mjs +1 -0
  17. package/dist/HeapAnalyzer-bJbLvzp6.mjs +1 -0
  18. package/dist/HookPatternScanner-yx4vJ9sd.mjs +1 -0
  19. package/dist/InstrumentationSession-Cv1wikLA.mjs +1 -0
  20. package/dist/IntegrityScanner-BB7sw-SA.mjs +1 -0
  21. package/dist/JScramblerDeobfuscator-NVR5VatT.mjs +1 -0
  22. package/dist/MCPServer.activation.ttl-C2wOCMLV.mjs +1 -0
  23. package/dist/MCPServer.search.helpers-DlassAew.mjs +2 -0
  24. package/dist/MemoryController-CCsGuGJS.mjs +2 -0
  25. package/dist/{MemoryScanSession-zfoVZJB0.mjs → MemoryScanSession-BZ2A9Ph1.mjs} +1 -1
  26. package/dist/MemoryScanner-DAxsq7Sx.mjs +1 -0
  27. package/dist/NativeMemoryManager.impl-BIJzXMqH.mjs +1 -0
  28. package/dist/{NativeMemoryManager.utils-Bu8srMEF.mjs → NativeMemoryManager.utils-CMoul2an.mjs} +1 -1
  29. package/dist/PEAnalyzer-CB_kaTis.mjs +1 -0
  30. package/dist/PackerDeobfuscator-BpwGjxDL.mjs +7 -0
  31. package/dist/PointerChainEngine-B6SYv6ZM.mjs +1 -0
  32. package/dist/ProcessRegistry-C5W1Tkn9.mjs +1 -0
  33. package/dist/QuickJSSandbox-CIde-jzG.mjs +299 -0
  34. package/dist/{ResponseBuilder-nPXl_khE.mjs → ResponseBuilder-BLicSCjn.mjs} +1 -1
  35. package/dist/ReverseEvidenceGraph-DJzk0GQz.mjs +2 -0
  36. package/dist/ServerRuntimeState-DGXNv8Ji.mjs +1 -0
  37. package/dist/Speedhack-MGoeq1ZS.mjs +1 -0
  38. package/dist/StructureAnalyzer-CCTWAXR3.mjs +2 -0
  39. package/dist/ToolHandlerMap-C40EmuLT.mjs +1 -0
  40. package/dist/{ToolProbe-DQiREmNp.mjs → ToolProbe-B02GC3ZY.mjs} +1 -1
  41. package/dist/ToolRegistry-CzqQxFqf.mjs +1 -0
  42. package/dist/{ToolRouter.policy-UKBlFlbh.mjs → ToolRouter.policy-Bgb3S8jc.mjs} +2 -2
  43. package/dist/TraceRecorder-BfeCTQUj.mjs +407 -0
  44. package/dist/VMDeobfuscator-BHtkV850.mjs +1 -0
  45. package/dist/Win32API-G7QPyckq.mjs +1 -0
  46. package/dist/{Win32Debug-DwF8mQGm.mjs → Win32Debug-6yzmtv5b.mjs} +1 -1
  47. package/dist/allocation-track-CiI-CnaI.mjs +1 -0
  48. package/dist/analysis-CojUzwX-.mjs +27 -0
  49. package/dist/{antidebug-CsnpOR9z.mjs → antidebug-CgU84TE1.mjs} +1 -1
  50. package/dist/apk-DrPBsOq8.mjs +1 -0
  51. package/dist/artifactRetention-Bk6fW2uF.mjs +1 -0
  52. package/dist/artifacts-Bx9GLx4J.mjs +1 -0
  53. package/dist/ast-bridge-BlOrmVAv.mjs +1 -0
  54. package/dist/ast-utils-B9E5k_v1.mjs +1 -0
  55. package/dist/binary-instrument-DiE1BP0x.mjs +12 -0
  56. package/dist/boringssl-inspector-C6M3sOga.mjs +2 -0
  57. package/dist/browser-QDUu5ML9.mjs +29 -0
  58. package/dist/{canvas-396ieNv5.mjs → canvas-g5kmLdY-.mjs} +1098 -24
  59. package/dist/{capabilities-L1ax5EHS.mjs → capabilities-DwzyxL2w.mjs} +1 -1
  60. package/dist/cdp-session-Dy4OwMOP.mjs +1 -0
  61. package/dist/collector-Cld4i-E4.mjs +1 -0
  62. package/dist/config-5ODJ3Aj0.mjs +3 -0
  63. package/dist/constants-nvsLpSri.mjs +1 -0
  64. package/dist/coordination-C6y2gM9O.mjs +98 -0
  65. package/dist/coverage-and-block--cWjjEe5.mjs +1 -0
  66. package/dist/dart-inspector-D4IKxZ6u.mjs +0 -0
  67. package/dist/debugger-C2SpiXoO.mjs +1 -0
  68. package/dist/definitions-0mtilYzG.mjs +1 -0
  69. package/dist/definitions-9csunmeX.mjs +1 -0
  70. package/dist/definitions-B11MudW_.mjs +1 -0
  71. package/dist/definitions-BKpRDjcI.mjs +1 -0
  72. package/dist/definitions-BXE3H4re.mjs +1 -0
  73. package/dist/definitions-BlPHe5DX.mjs +1 -0
  74. package/dist/definitions-Bob4XMxI.mjs +27 -0
  75. package/dist/definitions-BpIQN2nm.mjs +1 -0
  76. package/dist/{definitions-Ym8niHDb.mjs → definitions-BvolWeSu.mjs} +1 -1
  77. package/dist/definitions-C-6j3Ejl.mjs +1 -0
  78. package/dist/definitions-C-AdFfFu.mjs +1 -0
  79. package/dist/definitions-CArdw_9T.mjs +1 -0
  80. package/dist/definitions-CCvIcRrT.mjs +1 -0
  81. package/dist/definitions-CJPE5PIl.mjs +1 -0
  82. package/dist/definitions-CbqeW06u.mjs +1 -0
  83. package/dist/definitions-Cexmkypg.mjs +1 -0
  84. package/dist/definitions-D1dxl8qt.mjs +1 -0
  85. package/dist/definitions-D3uT-ZbU.mjs +1 -0
  86. package/dist/definitions-DtOY5iUc.mjs +1 -0
  87. package/dist/{definitions-Cv5r8xwq.mjs → definitions-DvrYdDCJ2.mjs} +1 -1
  88. package/dist/definitions-ihxOqOC4.mjs +1 -0
  89. package/dist/deopt-trace-qnAcC931.mjs +17 -0
  90. package/dist/disasm-DoxSucGp.mjs +1 -0
  91. package/dist/dumpsys-parser-Du-5ruEe.mjs +2 -0
  92. package/dist/encoding-UMtwgy4M.mjs +2 -0
  93. package/dist/ensure-browser-core-BP70x0TB.mjs +285 -0
  94. package/dist/factory-BeND77hf.mjs +2 -0
  95. package/dist/graphql-CF7QKJME.mjs +68 -0
  96. package/dist/grpc-raw-Dp7ps2sv.mjs +1 -0
  97. package/dist/handlers--qCl9vNv.mjs +1 -0
  98. package/dist/handlers-BHIu1LqA.mjs +1 -0
  99. package/dist/{handlers-DB6xVVWq.mjs → handlers-BQ4K8Jbr.mjs} +1 -1
  100. package/dist/handlers-BxQv-wtf.mjs +8 -0
  101. package/dist/handlers-ByYG27-5.mjs +1 -0
  102. package/dist/handlers-C0I9-BtX.mjs +5 -0
  103. package/dist/{handlers-CWKBBjai.mjs → handlers-CL0Iokmw.mjs} +1 -1
  104. package/dist/handlers-CNbhIdSK.mjs +4 -0
  105. package/dist/handlers-CnTTSJFs.mjs +109 -0
  106. package/dist/handlers-CoDx6akJ2.mjs +49 -0
  107. package/dist/{handlers-BbLxNbbT.mjs → handlers-DASJI0Pn.mjs} +1 -1
  108. package/dist/handlers-DRKMaA-_.mjs +74 -0
  109. package/dist/handlers-Dalu0olz.mjs +2 -0
  110. package/dist/handlers-KY0g31ny.mjs +9 -0
  111. package/dist/handlers-oGo60aVv.mjs +1 -0
  112. package/dist/handlers.impl-BTXLw6Qc.mjs +1 -0
  113. package/dist/heap-sampling-BqdiU-5j.mjs +1 -0
  114. package/dist/{hooks-DPouiS7I.mjs → hooks-COK3t5rT.mjs} +51 -32
  115. package/dist/index.mjs +11 -11
  116. package/dist/logger-BGCcd-jJ.mjs +1 -0
  117. package/dist/macro-nUYUjKNZ.mjs +2 -0
  118. package/dist/maintenance-CfnE7ZKU.mjs +4 -0
  119. package/dist/manifest-7EOTUc0D.mjs +1 -0
  120. package/dist/manifest-B5ujuQmf.mjs +1 -0
  121. package/dist/manifest-BErXl3zn.mjs +1 -0
  122. package/dist/manifest-BKA-mD3J.mjs +1 -0
  123. package/dist/manifest-BUXj23bX.mjs +1 -0
  124. package/dist/manifest-BfXt9cau.mjs +1 -0
  125. package/dist/manifest-Bx-tpURK.mjs +1 -0
  126. package/dist/manifest-C0owVAdq.mjs +1 -0
  127. package/dist/manifest-C5XqYc9o.mjs +1 -0
  128. package/dist/manifest-CVKzLjsA.mjs +1 -0
  129. package/dist/manifest-CaeFjdhj.mjs +1 -0
  130. package/dist/manifest-CegBgip0.mjs +1 -0
  131. package/dist/manifest-CoJHqlgS.mjs +1 -0
  132. package/dist/manifest-D0dbtDqd.mjs +1 -0
  133. package/dist/manifest-D5Gr8ujd.mjs +12 -0
  134. package/dist/manifest-D82z-5og.mjs +1 -0
  135. package/dist/manifest-DA2afIwh.mjs +1 -0
  136. package/dist/manifest-DAbiFP5o.mjs +1 -0
  137. package/dist/manifest-DEY0s1O72.mjs +1 -0
  138. package/dist/manifest-DTOqNqiA.mjs +1 -0
  139. package/dist/manifest-DZ6ELNgX.mjs +1 -0
  140. package/dist/manifest-DjHkjddT.mjs +1 -0
  141. package/dist/manifest-DocA_itf2.mjs +1 -0
  142. package/dist/manifest-Dpnhvfq0.mjs +1 -0
  143. package/dist/manifest-DucPMG_a.mjs +1 -0
  144. package/dist/manifest-Dw5yYEac.mjs +1 -0
  145. package/dist/manifest-Ic_Cg66S.mjs +1 -0
  146. package/dist/manifest-JHaG6GMN.mjs +1 -0
  147. package/dist/manifest-QdkIzmYM.mjs +1 -0
  148. package/dist/manifest-YZqaCe25.mjs +1 -0
  149. package/dist/manifest-f0lUeXwq.mjs +1 -0
  150. package/dist/manifest-h-Ebisf8.mjs +1 -0
  151. package/dist/manifest-oOfTymBS.mjs +1 -0
  152. package/dist/manifest-qXqrO6KC.mjs +2 -0
  153. package/dist/mapsParser-DrJoeC0c.mjs +1 -0
  154. package/dist/modules-CC_ADmwi.mjs +333 -0
  155. package/dist/mojo-ipc-kVztXYw-.mjs +140 -0
  156. package/dist/native-D9ouskXO.mjs +961 -0
  157. package/dist/native-bridge-Dzd7hYoq.mjs +1 -0
  158. package/dist/network-C5Y-S87J.mjs +7 -0
  159. package/dist/one-gadget-CiWFE17F.mjs +1 -0
  160. package/dist/outputPaths-CHtELDyi.mjs +1 -0
  161. package/dist/parse-args-B6dwWc9k.mjs +1 -0
  162. package/dist/platform-BIXgJaM3.mjs +94 -0
  163. package/dist/process-aDIfLC0v.mjs +6 -0
  164. package/dist/proxy-DsHsQ1I4.mjs +2 -0
  165. package/dist/registry-7h8jJ9y9.mjs +1 -0
  166. package/dist/{registry-xB8Wgmyj.mjs → registry-DJDnkQW2.mjs} +1 -1
  167. package/dist/response-R8ghbZSb.mjs +1 -0
  168. package/dist/retry-policy-DtYv0kDi.mjs +1 -0
  169. package/dist/reverseEngineeringConfig-BhZLOa3C.mjs +1 -0
  170. package/dist/safeOutput-Dt4mfjXA.mjs +1 -0
  171. package/dist/{search-defaults-CJik67or.mjs → search-defaults-BBRJNAzC.mjs} +1 -1
  172. package/dist/server/search/EmbeddingWorker.d.mts +1 -0
  173. package/dist/server/search/EmbeddingWorker.mjs +1 -0
  174. package/dist/shared-BKtWZDGN.mjs +1 -0
  175. package/dist/sourcemap-2VIeVeKw.mjs +3 -0
  176. package/dist/streaming-DkpE3GGU.mjs +15 -0
  177. package/dist/syscall-DGZoYM_U.mjs +1 -0
  178. package/dist/transform-BJqsBC_-.mjs +105 -0
  179. package/dist/turbofan-graph-CbGHNVtl.mjs +1 -0
  180. package/dist/turbofan-inspect--NdCuYXi.mjs +23 -0
  181. package/dist/types-CWSvzmIh.mjs +1 -0
  182. package/dist/v8-inspector-CTJo08-K.mjs +297 -0
  183. package/dist/wasm-DX4Qm2Vs.mjs +235 -0
  184. package/dist/weakrefs-inspect-CnhaF-rN.mjs +57 -0
  185. package/dist/webgpu-D4-DxbxZ.mjs +6 -0
  186. package/dist/workflow-DHktRNF2.mjs +108 -0
  187. package/package.json +33 -27
  188. package/dist/AntiCheatDetector-CUpZBh5O.mjs +0 -1
  189. package/dist/CodeInjector-Btj9upnf.mjs +0 -1
  190. package/dist/ConsoleMonitor-DIjN5Afa.mjs +0 -306
  191. package/dist/DarwinAPI-BuMPGzHm.mjs +0 -1
  192. package/dist/ExtensionManager.tools-CIGOWViz.mjs +0 -1
  193. package/dist/FingerprintManager-BkDSsjjP.mjs +0 -1
  194. package/dist/HardwareBreakpoint-DMAMcPyB.mjs +0 -1
  195. package/dist/HeapAnalyzer-Yj348FYt.mjs +0 -1
  196. package/dist/InstrumentationSession-c5qZyp7d.mjs +0 -1
  197. package/dist/MCPServer.activation.ttl-CEGNBycZ.mjs +0 -1
  198. package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +0 -1
  199. package/dist/MemoryController-DjtgiING.mjs +0 -2
  200. package/dist/MemoryScanner-Dxd657li.mjs +0 -1
  201. package/dist/PEAnalyzer-CMu9Ua9T.mjs +0 -1
  202. package/dist/PointerChainEngine-CaSC1Mry.mjs +0 -1
  203. package/dist/ProcessRegistry-D5y1yuP2.mjs +0 -1
  204. package/dist/ReverseEvidenceGraph-BksOpsPs.mjs +0 -2
  205. package/dist/ServerRuntimeState-CgqBBwfd.mjs +0 -1
  206. package/dist/Speedhack-pwXTHxOY.mjs +0 -1
  207. package/dist/StructureAnalyzer-BseGzsSl.mjs +0 -2
  208. package/dist/ToolCatalog-DgmQXdsm.mjs +0 -1
  209. package/dist/ToolHandlerMap-7HWoIgQO.mjs +0 -1
  210. package/dist/ToolRegistry-eMZEBiR1.mjs +0 -1
  211. package/dist/TraceRecorder-B5ktv3nP.mjs +0 -272
  212. package/dist/VersionDetector-CmPJmaJg.mjs +0 -1
  213. package/dist/Win32API-DoP3MMHS.mjs +0 -1
  214. package/dist/WorkflowEngine-CldHG5b4.mjs +0 -1
  215. package/dist/analysis-C-ln0Brh.mjs +0 -6
  216. package/dist/artifactRetention-DkYKLOvi.mjs +0 -1
  217. package/dist/artifacts-D-4pSS_N.mjs +0 -1
  218. package/dist/binary-instrument-BeZ224mZ.mjs +0 -9
  219. package/dist/boringssl-inspector-ZOCkaipa.mjs +0 -2
  220. package/dist/browser-BUaB25bk.mjs +0 -11
  221. package/dist/collector-CB2syQEg.mjs +0 -1
  222. package/dist/constants-DMv3svps.mjs +0 -2
  223. package/dist/coordination-Dbohmj6D.mjs +0 -1
  224. package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
  225. package/dist/debugger-CLzkObIO.mjs +0 -1
  226. package/dist/definitions-0hxnrDU72.mjs +0 -1
  227. package/dist/definitions-B3a9QC2t.mjs +0 -1
  228. package/dist/definitions-BOvju5t2.mjs +0 -1
  229. package/dist/definitions-CXj_cEVt.mjs +0 -1
  230. package/dist/definitions-Co6AvTjH.mjs +0 -1
  231. package/dist/definitions-DBYSxChX.mjs +0 -1
  232. package/dist/definitions-D_dTDX9B.mjs +0 -1
  233. package/dist/definitions-Db9t2ddh.mjs +0 -1
  234. package/dist/definitions-DbN2CjI2.mjs +0 -1
  235. package/dist/definitions-DlmmHmZc.mjs +0 -1
  236. package/dist/definitions-DnYpoGig.mjs +0 -1
  237. package/dist/definitions-DtZ6Ktx2.mjs +0 -1
  238. package/dist/definitions-DuIPS8gq.mjs +0 -1
  239. package/dist/definitions-DywfwPMb.mjs +0 -1
  240. package/dist/definitions-EGmqr85H.mjs +0 -1
  241. package/dist/definitions-Fetw_Cge.mjs +0 -26
  242. package/dist/definitions-LdkeuOeA.mjs +0 -1
  243. package/dist/definitions-cnG6tj17.mjs +0 -1
  244. package/dist/encoding-B4xZWErf.mjs +0 -2
  245. package/dist/ensure-browser-core-JHwDo5ql.mjs +0 -285
  246. package/dist/factory-BxNdBiZa.mjs +0 -1
  247. package/dist/graphql-GBWsZ9xC.mjs +0 -62
  248. package/dist/handlers-5nzR8B0a.mjs +0 -5
  249. package/dist/handlers-6iNsXOVT.mjs +0 -7
  250. package/dist/handlers-BZ8n6Hvf.mjs +0 -1
  251. package/dist/handlers-BbS4hssc.mjs +0 -4
  252. package/dist/handlers-CIKOP4aI.mjs +0 -2
  253. package/dist/handlers-Cmb6SoRC.mjs +0 -1
  254. package/dist/handlers-CrJsKnEI.mjs +0 -1
  255. package/dist/handlers-DOOCWUNR.mjs +0 -31
  256. package/dist/handlers-Z_B5aVaU.mjs +0 -54
  257. package/dist/handlers-gVscChvl.mjs +0 -1
  258. package/dist/handlers-xFvI9P_y.mjs +0 -1
  259. package/dist/handlers.impl-BsFTW6SD.mjs +0 -1
  260. package/dist/logger-CCikqqvj.mjs +0 -1
  261. package/dist/macro-p8kuJVcm.mjs +0 -2
  262. package/dist/maintenance-DAqADb6Z.mjs +0 -302
  263. package/dist/manifest-4lmM6MZR.mjs +0 -1
  264. package/dist/manifest-AxaxRSt6.mjs +0 -2
  265. package/dist/manifest-BIqRE1Qz.mjs +0 -1
  266. package/dist/manifest-Box-jWfr.mjs +0 -1
  267. package/dist/manifest-Bp33di0Q.mjs +0 -1
  268. package/dist/manifest-BvRX4nRP.mjs +0 -1
  269. package/dist/manifest-C6KoB1XE.mjs +0 -1
  270. package/dist/manifest-C7TdXCWY.mjs +0 -1
  271. package/dist/manifest-CM-n64K0.mjs +0 -1
  272. package/dist/manifest-CUokxCUN.mjs +0 -1
  273. package/dist/manifest-CWJS45iO.mjs +0 -1
  274. package/dist/manifest-Cdxdgo-D.mjs +0 -1
  275. package/dist/manifest-Cf6SmamD.mjs +0 -1
  276. package/dist/manifest-Cgxu2qdv.mjs +0 -1
  277. package/dist/manifest-CowGSURa2.mjs +0 -1
  278. package/dist/manifest-CsGIrh34.mjs +0 -1
  279. package/dist/manifest-CvDpVToN.mjs +0 -1
  280. package/dist/manifest-D8TL9RLE.mjs +0 -1
  281. package/dist/manifest-DIhtCBe6.mjs +0 -1
  282. package/dist/manifest-DJbruNOg.mjs +0 -1
  283. package/dist/manifest-DLGtZH-0.mjs +0 -1
  284. package/dist/manifest-DXHdPt2T.mjs +0 -1
  285. package/dist/manifest-Dg5ScOyW.mjs +0 -1
  286. package/dist/manifest-DzGoTS0R.mjs +0 -1
  287. package/dist/manifest-G2H52LKz.mjs +0 -131
  288. package/dist/manifest-P0Futrgb.mjs +0 -1
  289. package/dist/manifest-Qw7xgvjv.mjs +0 -1
  290. package/dist/manifest-W3qvVrP2.mjs +0 -1
  291. package/dist/manifest-dG6MuR1U.mjs +0 -1
  292. package/dist/manifest-nWXtgq5Y2.mjs +0 -1
  293. package/dist/manifest-vp1upSSq.mjs +0 -1
  294. package/dist/modules-DO3jXCgj.mjs +0 -333
  295. package/dist/mojo-ipc-Be-ccWrc.mjs +0 -9
  296. package/dist/native-g095qhpK.mjs +0 -961
  297. package/dist/network-Dvxm7eEI.mjs +0 -7
  298. package/dist/outputPaths-D2ddHrOJ.mjs +0 -2
  299. package/dist/parse-args-ngRrvF9e.mjs +0 -1
  300. package/dist/platform-DjWbuiF8.mjs +0 -93
  301. package/dist/process-Dq5I-KZW.mjs +0 -2
  302. package/dist/proxy-DPNgM7TE.mjs +0 -2
  303. package/dist/renderer-pid-7jbTR8f5.mjs +0 -1
  304. package/dist/response-B1RuVVfD.mjs +0 -1
  305. package/dist/sourcemap-DqEW15Ao.mjs +0 -1
  306. package/dist/streaming-Dbk4eStJ.mjs +0 -1
  307. package/dist/transform-D-peM3aO.mjs +0 -103
  308. package/dist/wasm-CZajRaad.mjs +0 -174
  309. package/dist/webcrack-phEfVt5y.mjs +0 -46
  310. package/dist/workflow-wkXb3x-U.mjs +0 -101
  311. /package/dist/{chunk-88NL7fhV.mjs → rolldown-runtime-88NL7fhV.mjs} +0 -0
@@ -1,306 +0,0 @@
1
- import{t as e}from"./logger-CCikqqvj.mjs";import{_ as t,v as n}from"./ensure-browser-core-JHwDo5ql.mjs";import{randomUUID as r}from"node:crypto";var i=class{page;networkEnabled=!1;requests=new Map;responses=new Map;MAX_NETWORK_RECORDS=500;MAX_INJECTED_RECORDS=500;requestCounter=0;responseBodyCache=new Map;MAX_BODY_CACHE_ENTRIES=200;requestIdMap=new WeakMap;boundOnRequest=null;boundOnResponse=null;constructor(e){this.page=e}setPage(e){if(this.page===e)return;let t=this.page,n=this.networkEnabled,r=this.boundOnRequest,i=this.boundOnResponse;if(n&&t&&r)try{t.off(`request`,r)}catch{}if(n&&t&&i)try{t.off(`response`,i)}catch{}if(this.page=e,!n||!this.page){this.page||(this.networkEnabled=!1);return}r&&this.page.on(`request`,r),i&&this.page.on(`response`,i)}getPageOrThrow(){if(!this.page)throw Error(`Playwright page not initialized`);return this.page}async evaluateInPage(e){let t=this.getPageOrThrow();if(!t.evaluate)throw Error(`Playwright page.evaluate is not available`);return t.evaluate(e)}async evaluateOnNewDocumentInPage(e){let t=this.getPageOrThrow();if(!t.evaluateOnNewDocument)throw Error(`Playwright page.evaluateOnNewDocument is not available`);return t.evaluateOnNewDocument(e)}isUnknownArray(e){return Array.isArray(e)}isClearedBuffersResult(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.xhrCleared==`number`&&typeof t.fetchCleared==`number`}isResetInterceptorsResult(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.xhrReset==`boolean`&&typeof t.fetchReset==`boolean`}isPlaywrightLikeRequest(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.url==`function`&&typeof t.method==`function`&&typeof t.headers==`function`&&typeof t.postData==`function`&&typeof t.resourceType==`function`}isPlaywrightLikeResponse(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.request==`function`&&typeof t.url==`function`&&typeof t.status==`function`&&typeof t.statusText==`function`&&typeof t.headers==`function`}normalizeHttpVersion(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`http/1.0`||t===`1.0`)return`1.0`;if(t===`http/1.1`||t===`1.1`)return`1.1`;if(t===`http/2`||t===`2`||t===`2.0`||t===`h2`)return`h2`;if(t===`http/3`||t===`3`||t===`3.0`||t===`h3`)return`h3`}detectHttpVersion(e){let t=typeof e.httpVersion==`function`?e.httpVersion():void 0,n=this.normalizeHttpVersion(t);if(n)return n;let r=typeof e.protocol==`function`?e.protocol():void 0;return this.normalizeHttpVersion(r)}async enable(){if(this.networkEnabled){e.warn(`PlaywrightNetworkMonitor already enabled`);return}this.boundOnRequest=e=>{if(!this.isPlaywrightLikeRequest(e))return;let t=`pw-${++this.requestCounter}`;this.requestIdMap.set(e,t);let n={requestId:t,url:e.url(),method:e.method(),headers:e.headers(),postData:e.postData()??void 0,timestamp:Date.now(),type:e.resourceType()};if(this.requests.set(t,n),this.requests.size>this.MAX_NETWORK_RECORDS){let e=this.requests.keys().next().value;e&&this.requests.delete(e)}},this.boundOnResponse=t=>{if(!this.isPlaywrightLikeResponse(t))return;let n=t.request(),r=`pw-res-${Date.now()}-${Math.random()}`,i=this.isPlaywrightLikeRequest(n)?this.requestIdMap.get(n)??r:r,a=this.detectHttpVersion(t),o=this.requests.get(i);o&&a&&(o.httpVersion=a);let s={requestId:i,url:t.url(),status:t.status(),statusText:t.statusText(),headers:t.headers(),mimeType:t.headers()[`content-type`]??`unknown`,timestamp:Date.now()};if(this.responses.set(i,s),this.responses.size>this.MAX_NETWORK_RECORDS){let e=this.responses.keys().next().value;e&&this.responses.delete(e)}if(typeof t.body==`function`){let n=i;t.body().then(t=>{if(t.length>1048576){e.debug(`[PW-BodyCache] Skipping oversized body for ${n} (${t.length} bytes)`);return}if(this.responseBodyCache.size>=this.MAX_BODY_CACHE_ENTRIES){let e=this.responseBodyCache.keys().next().value;e&&this.responseBodyCache.delete(e)}/^(text\/|application\/(json|javascript|xml|x-www-form-urlencoded))/i.test(s.mimeType)?this.responseBodyCache.set(n,{body:t.toString(`utf-8`),base64Encoded:!1}):this.responseBodyCache.set(n,{body:t.toString(`base64`),base64Encoded:!0}),e.debug(`[PW-BodyCache] Cached body for ${n} (${t.length} bytes)`)}).catch(t=>{e.debug(`[PW-BodyCache] Could not capture body for ${n}: ${t instanceof Error?t.message:String(t)}`)})}};let t=this.getPageOrThrow();t.on(`request`,this.boundOnRequest),t.on(`response`,this.boundOnResponse),this.networkEnabled=!0,e.info(`PlaywrightNetworkMonitor enabled`)}async disable(){let t=this.getPageOrThrow();if(this.boundOnRequest){try{t.off(`request`,this.boundOnRequest)}catch{}this.boundOnRequest=null}if(this.boundOnResponse){try{t.off(`response`,this.boundOnResponse)}catch{}this.boundOnResponse=null}this.networkEnabled=!1,e.info(`PlaywrightNetworkMonitor disabled`)}isEnabled(){return this.networkEnabled}getRequests(e){let t=Array.from(this.requests.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.method&&(t=t.filter(t=>t.method.toUpperCase()===e.method.toUpperCase())),e?.limit&&(t=t.slice(-e.limit)),t}getResponses(e){let t=Array.from(this.responses.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.status&&(t=t.filter(t=>t.status===e.status)),e?.limit&&(t=t.slice(-e.limit)),t}getStatus(){return{enabled:this.networkEnabled,requestCount:this.requests.size,responseCount:this.responses.size,listenerCount:this.networkEnabled?2:0,cdpSessionActive:!1}}getActivity(e){return{request:this.requests.get(e),response:this.responses.get(e)}}clearRecords(){this.requests.clear(),this.responses.clear(),this.responseBodyCache.clear()}getStats(){let e=Array.from(this.requests.values()),t=Array.from(this.responses.values()),n={};e.forEach(e=>{n[e.method]=(n[e.method]||0)+1});let r={};t.forEach(e=>{r[e.status]=(r[e.status]||0)+1});let i={};return e.forEach(e=>{let t=e.type||`unknown`;i[t]=(i[t]||0)+1}),{totalRequests:e.length,totalResponses:t.length,byMethod:n,byStatus:r,byType:i}}async getResponseBody(t){let n=this.responseBodyCache.get(t);return n?(this.responseBodyCache.delete(t),this.responseBodyCache.set(t,n),e.debug(`[PW-BodyCache] Cache hit for ${t}`),n):(e.warn(`getResponseBody: no cached body for ${t} in Playwright mode`),null)}async injectScript(e){await this.evaluateInPage(e)}async injectXHRInterceptor(e){let t=`
2
- (function() {
3
- if (window.__xhrInterceptorInjected) return;
4
- window.__xhrInterceptorInjected = true;
5
- const maxRecords = ${this.MAX_INJECTED_RECORDS};
6
- const OrigXHR = window.__pwOriginalXMLHttpRequest || window.XMLHttpRequest;
7
- window.__pwOriginalXMLHttpRequest = OrigXHR;
8
- if (!window.__xhrRequests) window.__xhrRequests = [];
9
- window.XMLHttpRequest = function() {
10
- const xhr = new OrigXHR();
11
- const origOpen = xhr.open.bind(xhr);
12
- const origSend = xhr.send.bind(xhr);
13
- xhr.open = function(method, url, ...rest) {
14
- xhr.__hookMeta = { method, url, timestamp: Date.now() };
15
- return origOpen(method, url, ...rest);
16
- };
17
- xhr.send = function(body) {
18
- xhr.addEventListener('load', function() {
19
- window.__xhrRequests.push({
20
- ...xhr.__hookMeta, body: body ? String(body).slice(0, 2048) : null,
21
- status: xhr.status, response: xhr.responseText.slice(0, 2048),
22
- });
23
- if (window.__xhrRequests.length > maxRecords) {
24
- window.__xhrRequests.splice(0, window.__xhrRequests.length - maxRecords);
25
- }
26
- });
27
- return origSend(body);
28
- };
29
- return xhr;
30
- };
31
- console.log('[PlaywrightXHR] XHR interceptor injected');
32
- })();
33
- `;e?.persistent?await this.evaluateOnNewDocumentInPage(t):await this.evaluateInPage(t)}async injectFetchInterceptor(e){let t=`
34
- (function() {
35
- if (window.__fetchInterceptorInjected) return;
36
- window.__fetchInterceptorInjected = true;
37
- const maxRecords = ${this.MAX_INJECTED_RECORDS};
38
- const origFetch = window.__pwOriginalFetch || window.fetch;
39
- window.__pwOriginalFetch = origFetch;
40
- if (!window.__fetchRequests) window.__fetchRequests = [];
41
- const normalizeHeaders = (value) => {
42
- if (!value) return {};
43
- try {
44
- if (typeof Headers !== 'undefined' && value instanceof Headers) {
45
- return Object.fromEntries(value.entries());
46
- }
47
- } catch {}
48
- if (Array.isArray(value)) {
49
- try {
50
- return Object.fromEntries(value);
51
- } catch {
52
- return {};
53
- }
54
- }
55
- return typeof value === 'object' ? value : {};
56
- };
57
- window.fetch = function(...args) {
58
- const [resource, opts = {}] = args;
59
- const requestLike = resource && typeof resource === 'object' ? resource : null;
60
- const url =
61
- typeof resource === 'string'
62
- ? resource
63
- : typeof resource?.url === 'string'
64
- ? resource.url
65
- : String(resource);
66
- const method = opts?.method || requestLike?.method || 'GET';
67
- const headers = normalizeHeaders(opts?.headers || requestLike?.headers);
68
- const bodySource = opts?.body;
69
- const body =
70
- bodySource === undefined || bodySource === null
71
- ? null
72
- : String(bodySource).slice(0, 2048);
73
- const entry = {
74
- url,
75
- method,
76
- headers,
77
- body,
78
- timestamp: Date.now(),
79
- response: null,
80
- status: 0,
81
- };
82
- return origFetch.apply(this, args).then(res => {
83
- entry.status = res.status;
84
- return res.clone().text().then(
85
- (text) => {
86
- entry.response = text.slice(0, 2048);
87
- return res;
88
- },
89
- () => {
90
- entry.response = '[Unable to read response]';
91
- return res;
92
- },
93
- ).then((response) => {
94
- window.__fetchRequests.push(entry);
95
- if (window.__fetchRequests.length > maxRecords) {
96
- window.__fetchRequests.splice(0, window.__fetchRequests.length - maxRecords);
97
- }
98
- // Auto-persist compact summary so data survives context compression
99
- try {
100
- const s = { url: entry.url, method: entry.method, status: entry.status, ts: entry.timestamp };
101
- const prev = JSON.parse(localStorage.getItem('__capturedAPIs') || '[]');
102
- prev.push(s);
103
- if (prev.length > 500) prev.splice(0, prev.length - 500);
104
- localStorage.setItem('__capturedAPIs', JSON.stringify(prev));
105
- } catch(e) {}
106
- return response;
107
- });
108
- });
109
- };
110
- console.log('[PlaywrightFetch] Fetch interceptor injected');
111
- })();
112
- `;e?.persistent?await this.evaluateOnNewDocumentInPage(t):await this.evaluateInPage(t)}async getXHRRequests(){try{let e=await this.evaluateInPage(()=>window.__xhrRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get XHR requests: ${t instanceof Error?t.message:String(t)}`),[]}}async getFetchRequests(){try{let e=await this.evaluateInPage(()=>window.__fetchRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get fetch requests: ${t instanceof Error?t.message:String(t)}`),[]}}async clearInjectedBuffers(){try{let e=await this.evaluateInPage(()=>{let e=window,t=e.__xhrRequests,n=e.__fetchRequests,r=Array.isArray(t)?t.length:0,i=Array.isArray(n)?n.length:0;return Array.isArray(t)&&(t.length=0),Array.isArray(n)&&(n.length=0),{xhrCleared:r,fetchCleared:i}});return this.isClearedBuffersResult(e)?e:{xhrCleared:0,fetchCleared:0}}catch(t){return e.warn(`[PW] Failed to clear injected buffers: ${t instanceof Error?t.message:String(t)}`),{xhrCleared:0,fetchCleared:0}}}async resetInjectedInterceptors(){try{let e=await this.evaluateInPage(()=>{let e=window,t=!1,n=!1;return e.__pwOriginalXMLHttpRequest&&(e.XMLHttpRequest=e.__pwOriginalXMLHttpRequest,t=!0),e.__pwOriginalFetch&&(e.fetch=e.__pwOriginalFetch,n=!0),Array.isArray(e.__xhrRequests)&&(e.__xhrRequests.length=0),Array.isArray(e.__fetchRequests)&&(e.__fetchRequests.length=0),e.__xhrInterceptorInjected=!1,e.__fetchInterceptorInjected=!1,{xhrReset:t,fetchReset:n}});return this.isResetInterceptorsResult(e)?e:{xhrReset:!1,fetchReset:!1}}catch(t){return e.warn(`[PW] Failed to reset interceptors: ${t instanceof Error?t.message:String(t)}`),{xhrReset:!1,fetchReset:!1}}}async getAllJavaScriptResponses(){return Array.from(this.responses.values()).filter(e=>e.mimeType.includes(`javascript`))}},a=class{cdpSession;rules=new Map;enabled=!1;eventHandler=null;compiledPatterns=new Map;constructor(e){this.cdpSession=e}async enable(t){let n=[];for(let e of t){let t=this.createRule(e);this.rules.set(t.id,t),this.compiledPatterns.set(t.id,this.compilePattern(t)),n.push(t)}return await this.applyRules(),this.eventHandler||(this.eventHandler=e=>{this.handleRequestPaused(e)},this.cdpSession.on(`Fetch.requestPaused`,this.eventHandler)),this.enabled=!0,e.info(`FetchInterceptor enabled with ${this.rules.size} rule(s)`),n}async disable(){let t=this.rules.size;if(this.eventHandler){try{this.cdpSession.off(`Fetch.requestPaused`,this.eventHandler)}catch{}this.eventHandler=null}try{await this.cdpSession.send(`Fetch.disable`)}catch(t){e.warn(`Fetch.disable failed:`,t)}return this.rules.clear(),this.compiledPatterns.clear(),this.enabled=!1,e.info(`FetchInterceptor disabled, removed ${t} rule(s)`),{removedRules:t}}async removeRule(e){let t=this.rules.delete(e);return this.compiledPatterns.delete(e),t&&(this.rules.size===0?await this.disable():await this.applyRules()),t}listRules(){let e=Array.from(this.rules.values());return{enabled:this.enabled,rules:e,totalHits:e.reduce((e,t)=>e+t.hitCount,0)}}isEnabled(){return this.enabled}createRule(e){let t=[];if(e.responseHeaders)for(let[n,r]of Object.entries(e.responseHeaders))t.push({name:n,value:r});return{id:r().slice(0,8),urlPattern:e.urlPattern,urlPatternType:e.urlPatternType??`glob`,stage:e.stage??`Response`,interceptAction:e.interceptAction??`fulfill`,responseCode:e.responseCode??200,responseHeaders:t,responseBody:e.responseBody??``,hitCount:0,createdAt:Date.now()}}compilePattern(e){if(e.urlPatternType===`regex`)try{return new RegExp(e.urlPattern,`i`)}catch{return new RegExp(e.urlPattern.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`i`)}let t=e.urlPattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`⟨GLOBSTAR⟩`).replace(/\*/g,`[^/]*`).replace(/⟨GLOBSTAR⟩/g,`.*`);return new RegExp(t,`i`)}async applyRules(){let t=[];for(let e of this.rules.values())t.push({urlPattern:e.urlPatternType===`glob`?e.urlPattern:`*`,requestStage:e.stage});if(t.length!==0)try{try{await this.cdpSession.send(`Fetch.disable`)}catch{}await this.cdpSession.send(`Fetch.enable`,{patterns:t.length>0?t:[{urlPattern:`*`,requestStage:`Response`}],handleAuthRequests:!1})}catch(t){throw e.error(`Failed to apply Fetch interception rules:`,t),t}}async handleRequestPaused(t){let n=t.request.url;for(let[r,i]of this.rules){let a=this.compiledPatterns.get(r);if(a&&a.test(n)&&(i.hitCount++,e.info(`[FetchInterceptor] Rule "${i.urlPattern}" matched: ${n}`),await this.applyMatchedRule(i,t,n)))return}await this.continueOriginalRequest(t,n)}async applyMatchedRule(t,n,r){try{switch(t.interceptAction){case`continue`:return await this.continuePausedRequest(n),!0;case`abort`:return await this.cdpSession.send(`Fetch.failRequest`,{requestId:n.requestId,errorReason:`Failed`}),!0;case`fulfill`:return await this.cdpSession.send(`Fetch.fulfillRequest`,{requestId:n.requestId,responseCode:t.responseCode,responseHeaders:this.buildFulfillHeaders(t),body:Buffer.from(t.responseBody,`utf-8`).toString(`base64`)}),!0}}catch(n){return e.error(`[FetchInterceptor] ${t.interceptAction} failed for ${r}:`,n),!1}}buildFulfillHeaders(e){let t=[...e.responseHeaders];return t.some(e=>e.name.toLowerCase()===`content-type`)||(e.responseBody.startsWith(`{`)||e.responseBody.startsWith(`[`)?t.push({name:`Content-Type`,value:`application/json`}):t.push({name:`Content-Type`,value:`text/plain`})),t.some(e=>e.name.toLowerCase()===`access-control-allow-origin`)||t.push({name:`Access-Control-Allow-Origin`,value:`*`}),t}async continuePausedRequest(e){if(e.responseStatusCode!==void 0){await this.cdpSession.send(`Fetch.continueResponse`,{requestId:e.requestId});return}await this.cdpSession.send(`Fetch.continueRequest`,{requestId:e.requestId})}async continueOriginalRequest(t,n){try{await this.continuePausedRequest(t)}catch(t){e.warn(`[FetchInterceptor] continue failed for ${n}:`,t)}}};function o(e){return e}function s(t,n){let r=o(t);if(r.contextSwitchPending)return[];let i=r.messages;n?.type&&(i=i.filter(e=>e.type===n.type));let a=n?.since;return a!==void 0&&(i=i.filter(e=>e.timestamp>=a)),n?.limit&&(i=i.slice(-n.limit)),e.debug(`getLogs: ${i.length} messages`),i}function c(t){let n=o(t);n.messages=[],e.info(`Console logs cleared`)}function l(e){let t=o(e);if(t.contextSwitchPending)return{totalMessages:0,byType:{}};let n={};for(let e of t.messages)n[e.type]=(n[e.type]||0)+1;return{totalMessages:t.messages.length,byType:n}}function u(e,t){let n=o(e);if(n.contextSwitchPending)return[];let r=n.exceptions;t?.url&&(r=r.filter(e=>e.url?.includes(t.url)));let i=t?.since;return i!==void 0&&(r=r.filter(e=>e.timestamp>=i)),t?.limit&&(r=r.slice(-t.limit)),r}function d(t){let n=o(t);n.exceptions=[],e.info(`Exceptions cleared`)}function f(e){return e}function p(e){return e.contextSwitchPending===!0}function m(e){let t=f(e);return p(t)?!1:(t.networkMonitor?.isEnabled()??!1)||(t.playwrightNetworkMonitor?.isEnabled()??!1)}function h(e){let t=f(e);return p(t)?{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:!1}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStatus():t.networkMonitor?t.networkMonitor.getStatus():{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:t.cdpSession!==null}}function g(e,t){let n=f(e);return p(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getRequests(t):n.networkMonitor?.getRequests(t)??[]}function _(e,t){let n=f(e);return p(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getResponses(t):n.networkMonitor?.getResponses(t)??[]}function v(e,t){let n=f(e);return p(n)?{}:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getActivity(t):n.networkMonitor?.getActivity(t)??{}}async function y(t,n){let r=f(t);return p(r)?null:r.playwrightNetworkMonitor?r.playwrightNetworkMonitor.getResponseBody(n):r.networkMonitor?r.networkMonitor.getResponseBody(n):(e.error(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`),null)}async function b(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getAllJavaScriptResponses():t.networkMonitor?t.networkMonitor.getAllJavaScriptResponses():[]}function x(e){let t=f(e);t.networkMonitor?.clearRecords(),t.playwrightNetworkMonitor?.clearRecords()}async function S(e){let t=f(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.clearInjectedBuffers(),dynamicScriptsCleared:0};let n=t.networkMonitor?await t.networkMonitor.clearInjectedBuffers():{xhrCleared:0,fetchCleared:0},r=await t.clearDynamicScriptBuffer();return{...n,...r}}async function C(e){let t=f(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.resetInjectedInterceptors(),scriptMonitorReset:!1};let n=t.networkMonitor?await t.networkMonitor.resetInjectedInterceptors():{xhrReset:!1,fetchReset:!1},r=await t.resetDynamicScriptMonitoring();return{...n,...r}}function w(e){let t=f(e);return p(t)?{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStats():t.networkMonitor?.getStats()??{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}}async function T(e,t){let r=f(e);if(p(r))throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectXHRInterceptor(t);if(!r.networkMonitor)throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectXHRInterceptor(t)}async function E(e,t){let r=f(e);if(p(r))throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectFetchInterceptor(t);if(!r.networkMonitor)throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectFetchInterceptor(t)}async function D(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getXHRRequests():t.networkMonitor?t.networkMonitor.getXHRRequests():[]}async function O(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getFetchRequests():t.networkMonitor?t.networkMonitor.getFetchRequests():[]}async function k(t,n){let r=t;if(await r.ensureSession(),!r.cdpSession)throw Error(`CDP session not available after reconnect attempt`);if(r.objectCache.has(n)){let e=r.objectCache.get(n);if(e!==void 0)return e}try{let t=await r.cdpSession.send(`Runtime.getProperties`,{objectId:n,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),i={};for(let e of t.result){if(!e.value)continue;let t=e.value;i[e.name]={value:r.extractValue(t),type:t.type,objectId:t.objectId,description:t.description}}if(!r.objectCache.has(n))for(;r.objectCache.size>=r.MAX_OBJECT_CACHE_SIZE;){let e=r.objectCache.keys().next().value;if(e===void 0)break;r.objectCache.delete(e)}return r.objectCache.set(n,i),e.info(`Object inspected: ${n}`,{propertyCount:Object.keys(i).length}),i}catch(t){throw e.error(`Failed to inspect object:`,t),t}}function A(t){t.objectCache.clear(),e.info(`Object cache cleared`)}function j(e){return e}async function M(t,r){let i=j(t);if(await i.ensureSession(),!i.cdpSession)throw new n(`CDP session not available after reconnect attempt`);let a=`
113
- (function() {
114
- if (window.__dynamicScriptMonitorInstalled) {
115
- console.log('[ScriptMonitor] Already installed');
116
- return;
117
- }
118
- window.__dynamicScriptMonitorInstalled = true;
119
-
120
- const maxRecords = ${i.MAX_INJECTED_DYNAMIC_SCRIPTS};
121
- if (!window.__dynamicScripts) {
122
- window.__dynamicScripts = [];
123
- }
124
- const dynamicScripts = window.__dynamicScripts;
125
- const state = window.__dynamicScriptMonitorState || {};
126
- if (!state.originalCreateElement) state.originalCreateElement = document.createElement;
127
- if (!state.originalEval) state.originalEval = window.eval;
128
- if (!state.originalFunction) state.originalFunction = window.Function;
129
- window.__dynamicScriptMonitorState = state;
130
-
131
- const observer = new MutationObserver((mutations) => {
132
- mutations.forEach((mutation) => {
133
- mutation.addedNodes.forEach((node) => {
134
- if (node.nodeName === 'SCRIPT') {
135
- const script = node;
136
- const info = {
137
- type: 'dynamic',
138
- src: script.src || '(inline)',
139
- content: script.src ? null : script.textContent,
140
- timestamp: Date.now(),
141
- async: script.async,
142
- defer: script.defer,
143
- };
144
-
145
- dynamicScripts.push(info);
146
- if (dynamicScripts.length > maxRecords) {
147
- dynamicScripts.splice(0, dynamicScripts.length - maxRecords);
148
- }
149
- console.log('[ScriptMonitor] Dynamic script added:', info);
150
- }
151
- });
152
- });
153
- });
154
-
155
- observer.observe(document.documentElement, {
156
- childList: true,
157
- subtree: true,
158
- });
159
- state.observer = observer;
160
-
161
- const originalCreateElement = state.originalCreateElement;
162
- document.createElement = function(tagName) {
163
- const element = originalCreateElement.call(document, tagName);
164
-
165
- if (tagName.toLowerCase() === 'script') {
166
- console.log('[ScriptMonitor] Script element created via createElement');
167
-
168
- const originalSetAttribute = element.setAttribute;
169
- element.setAttribute = function(name, value) {
170
- if (name === 'src') {
171
- console.log('[ScriptMonitor] Script src set to:', value);
172
- }
173
- return originalSetAttribute.call(element, name, value);
174
- };
175
- }
176
-
177
- return element;
178
- };
179
-
180
- const originalEval = state.originalEval;
181
- window.eval = function(code) {
182
- console.log('[ScriptMonitor] eval() called with code:',
183
- typeof code === 'string' ? code.substring(0, 100) + '...' : code);
184
- return originalEval.call(window, code);
185
- };
186
-
187
- const originalFunction = state.originalFunction;
188
- window.Function = function(...args) {
189
- console.log('[ScriptMonitor] Function() constructor called with args:', args);
190
- return originalFunction.apply(this, args);
191
- };
192
-
193
- window.__getDynamicScripts = function() {
194
- return dynamicScripts;
195
- };
196
-
197
- console.log('[ScriptMonitor] Dynamic script monitoring enabled');
198
- })();
199
- `;r?.persistent?(await i.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:a}),e.info(`Dynamic script monitoring enabled (persistent)`)):(await i.cdpSession.send(`Runtime.evaluate`,{expression:a}),e.info(`Dynamic script monitoring enabled`))}async function N(t){let n=j(t);if(!n.cdpSession)return{dynamicScriptsCleared:0};try{let e=(await n.cdpSession.send(`Runtime.evaluate`,{expression:`
200
- (() => {
201
- const store = Array.isArray(window.__dynamicScripts)
202
- ? window.__dynamicScripts
203
- : (typeof window.__getDynamicScripts === 'function'
204
- ? window.__getDynamicScripts()
205
- : null);
206
- const dynamicScriptsCleared = Array.isArray(store) ? store.length : 0;
207
- if (Array.isArray(store)) {
208
- store.length = 0;
209
- }
210
- return { dynamicScriptsCleared };
211
- })()
212
- `,returnByValue:!0})).result?.value;return typeof e==`object`&&e&&`dynamicScriptsCleared`in e&&typeof e.dynamicScriptsCleared==`number`?e:{dynamicScriptsCleared:0}}catch(t){return e.error(`Failed to clear dynamic script buffer:`,t),{dynamicScriptsCleared:0}}}async function P(t){let n=j(t);if(!n.cdpSession)return{scriptMonitorReset:!1};try{let e=(await n.cdpSession.send(`Runtime.evaluate`,{expression:`
213
- (() => {
214
- const state = window.__dynamicScriptMonitorState;
215
- let scriptMonitorReset = false;
216
-
217
- try {
218
- if (state && state.observer && typeof state.observer.disconnect === 'function') {
219
- state.observer.disconnect();
220
- state.observer = null;
221
- scriptMonitorReset = true;
222
- }
223
- } catch (_) {}
224
-
225
- try {
226
- if (state && state.originalCreateElement) {
227
- document.createElement = state.originalCreateElement;
228
- scriptMonitorReset = true;
229
- }
230
- } catch (_) {}
231
-
232
- try {
233
- if (state && state.originalEval) {
234
- window.eval = state.originalEval;
235
- scriptMonitorReset = true;
236
- }
237
- } catch (_) {}
238
-
239
- try {
240
- if (state && state.originalFunction) {
241
- window.Function = state.originalFunction;
242
- scriptMonitorReset = true;
243
- }
244
- } catch (_) {}
245
-
246
- if (Array.isArray(window.__dynamicScripts)) {
247
- window.__dynamicScripts.length = 0;
248
- }
249
- delete window.__getDynamicScripts;
250
- window.__dynamicScriptMonitorInstalled = false;
251
-
252
- return { scriptMonitorReset };
253
- })()
254
- `,returnByValue:!0})).result?.value;return typeof e==`object`&&e&&`scriptMonitorReset`in e&&typeof e.scriptMonitorReset==`boolean`?e:{scriptMonitorReset:!1}}catch(t){return e.error(`Failed to reset dynamic script monitoring:`,t),{scriptMonitorReset:!1}}}async function F(t){let r=j(t);if(!r.cdpSession)throw new n(`CDP session not initialized`);try{let e=(await r.cdpSession.send(`Runtime.evaluate`,{expression:`window.__getDynamicScripts ? window.__getDynamicScripts() : []`,returnByValue:!0})).result?.value;return Array.isArray(e)?e:[]}catch(t){return e.error(`Failed to get dynamic scripts:`,t),[]}}async function I(t,r,i){let a=j(t);if(!a.cdpSession)throw new n(`CDP session not initialized`);let o=`
255
- (function() {
256
- const originalFunc = window.${r};
257
- if (typeof originalFunc !== 'function') {
258
- console.error('[Tracer] ${r} is not a function');
259
- return;
260
- }
261
-
262
- window.${r} = new Proxy(originalFunc, {
263
- apply: function(target, thisArg, args) {
264
- console.log('[Tracer] ${r} called with args:', args);
265
- const startTime = performance.now();
266
-
267
- try {
268
- const result = target.apply(thisArg, args);
269
- const endTime = performance.now();
270
- console.log('[Tracer] ${r} returned:', result, 'Time:', (endTime - startTime).toFixed(2), 'ms');
271
- return result;
272
- } catch (error) {
273
- console.error('[Tracer] ${r} threw error:', error);
274
- throw error;
275
- }
276
- }
277
- });
278
-
279
- console.log('[Tracer] ${r} is now being traced');
280
- })();
281
- `;i?.persistent?(await a.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:o}),e.info(`Function tracer injected for: ${r} (persistent)`)):(await a.cdpSession.send(`Runtime.evaluate`,{expression:o}),e.info(`Function tracer injected for: ${r}`))}async function L(t,r,i,a){let o=j(t);if(!o.cdpSession)throw new n(`CDP session not initialized`);let s=`
282
- (function() {
283
- const obj = ${r};
284
- if (!obj) {
285
- console.error('[Watcher] Object not found: ${r}');
286
- return;
287
- }
288
-
289
- let value = obj.${i};
290
-
291
- Object.defineProperty(obj, '${i}', {
292
- get: function() {
293
- console.log('[Watcher] ${r}.${i} accessed, value:', value);
294
- return value;
295
- },
296
- set: function(newValue) {
297
- console.log('[Watcher] ${r}.${i} changed from', value, 'to', newValue);
298
- value = newValue;
299
- },
300
- enumerable: true,
301
- configurable: true
302
- });
303
-
304
- console.log('[Watcher] Property watcher installed for ${r}.${i}');
305
- })();
306
- `;a?.persistent?(await o.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:s}),e.info(`Property watcher injected for: ${r}.${i} (persistent)`)):(await o.cdpSession.send(`Runtime.evaluate`,{expression:s}),e.info(`Property watcher injected for: ${r}.${i}`))}function R(e){return e}async function z(n,r,i,a){let o=R(n);o.cdpSession=r,o.usingManagedTargetSession=i,o.lastEnableOptions={...a},o.cdpSession.on(`disconnected`,()=>{e.warn(`ConsoleMonitor CDP session disconnected`),o.cdpSession=null,o.networkMonitor=null,o.usingManagedTargetSession=!1}),await H(o.cdpSession,`Runtime.enable`,{},5e3),await H(o.cdpSession,`Console.enable`,{},5e3),o.cdpSession.on(`Runtime.consoleAPICalled`,t=>{let n=t.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],r={type:t.type,text:t.args.map(e=>o.formatRemoteObject(e)).join(` `),args:t.args.map(e=>o.extractValue(e)),timestamp:t.timestamp,stackTrace:n,url:n[0]?.url,lineNumber:n[0]?.lineNumber,columnNumber:n[0]?.columnNumber};o.messages.push(r),o.messages.length>o.MAX_MESSAGES&&(o.messages=o.messages.slice(-Math.floor(o.MAX_MESSAGES/2))),e.debug(`Console ${t.type}: ${r.text}`)}),o.cdpSession.on(`Console.messageAdded`,e=>{let t=e.message,n={type:t.level||`log`,text:t.text,timestamp:Date.now(),url:t.url,lineNumber:t.line,columnNumber:t.column};o.messages.push(n),o.messages.length>o.MAX_MESSAGES&&(o.messages=o.messages.slice(-Math.floor(o.MAX_MESSAGES/2)))}),a?.enableExceptions!==!1&&o.cdpSession.on(`Runtime.exceptionThrown`,t=>{let n=t.exceptionDetails,r=n.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],i={text:n.exception?.description||n.text,exceptionId:n.exceptionId,timestamp:Date.now(),stackTrace:r,url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber,scriptId:n.scriptId};o.exceptions.push(i),o.exceptions.length>o.MAX_EXCEPTIONS&&(o.exceptions=o.exceptions.slice(-Math.floor(o.MAX_EXCEPTIONS/2))),e.error(`Exception thrown: ${i.text}`,{url:i.url,line:i.lineNumber})}),a?.enableNetwork&&(o.networkMonitor=o.getManagedTargetNetworkMonitor?.()??new t(o.cdpSession),await o.networkMonitor.enable()),e.info(`ConsoleMonitor enabled`,{network:a?.enableNetwork||!1,exceptions:a?.enableExceptions!==!1})}async function B(t,n){let r=R(t);if(r.playwrightConsoleHandler){n?.enableNetwork&&!r.playwrightNetworkMonitor&&(r.playwrightNetworkMonitor=new i(r.playwrightPage),await r.playwrightNetworkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor Playwright session`));return}let a=r.playwrightPage;r.playwrightConsoleHandler=e=>{let t={type:e.type()||`log`,text:e.text(),timestamp:Date.now()};r.messages.push(t),r.messages.length>r.MAX_MESSAGES&&(r.messages=r.messages.slice(-Math.floor(r.MAX_MESSAGES/2)))},a.on(`console`,r.playwrightConsoleHandler),n?.enableExceptions!==!1&&(r.playwrightErrorHandler=e=>{let t={text:e.message,exceptionId:Date.now(),timestamp:Date.now()};r.exceptions.push(t),r.exceptions.length>r.MAX_EXCEPTIONS&&(r.exceptions=r.exceptions.slice(-Math.floor(r.MAX_EXCEPTIONS/2)))},a.on(`pageerror`,r.playwrightErrorHandler)),n?.enableNetwork&&(r.playwrightNetworkMonitor=new i(r.playwrightPage),await r.playwrightNetworkMonitor.enable()),e.info(`ConsoleMonitor enabled (Playwright/camoufox mode)`,{network:n?.enableNetwork||!1})}async function V(t){let n=R(t);if(n.playwrightPage){let e=n.playwrightPage;if(n.playwrightConsoleHandler){try{e.off(`console`,n.playwrightConsoleHandler)}catch{}n.playwrightConsoleHandler=null}if(n.playwrightErrorHandler){try{e.off(`pageerror`,n.playwrightErrorHandler)}catch{}n.playwrightErrorHandler=null}}if(n.playwrightNetworkMonitor&&=(await n.playwrightNetworkMonitor.disable(),null),n.cdpSession){n.networkMonitor&&=(await n.networkMonitor.disable(),null);try{await n.cdpSession.send(`Console.disable`)}catch(t){e.warn(`Failed to disable Console domain:`,t)}try{await n.cdpSession.send(`Runtime.disable`)}catch(t){e.warn(`Failed to disable Runtime domain:`,t)}if(n.usingManagedTargetSession)e.debug(`ConsoleMonitor released managed target session without detaching target`);else try{await n.cdpSession.detach()}catch(t){e.warn(`Failed to detach ConsoleMonitor CDP session:`,t)}n.cdpSession=null,n.usingManagedTargetSession=!1,e.info(`ConsoleMonitor disabled`)}}async function H(e,t,n,r=3e4){return Promise.race([e.send(t,n),new Promise((e,n)=>setTimeout(()=>n(Error(`CDP ${t} timed out after ${r}ms`)),r))])}var U=class{collector;cdpSession=null;networkMonitor=null;fetchInterceptor=null;playwrightNetworkMonitor=null;playwrightPage=null;usingManagedTargetSession=!1;contextSwitchPending=!1;playwrightConsoleHandler=null;playwrightErrorHandler=null;messages=[];MAX_MESSAGES=1e3;exceptions=[];MAX_EXCEPTIONS=500;MAX_INJECTED_DYNAMIC_SCRIPTS=500;MAX_OBJECT_CACHE_SIZE=1e3;objectCache=new Map;initPromise;lastEnableOptions={};constructor(e){this.collector=e,this.touchSplitMembersForTypeCheck()}touchSplitMembersForTypeCheck(){this.MAX_INJECTED_DYNAMIC_SCRIPTS,this.MAX_OBJECT_CACHE_SIZE,this.clearDynamicScriptBuffer,this.resetDynamicScriptMonitoring,this.usingManagedTargetSession,this.playwrightErrorHandler,this.messages,this.MAX_MESSAGES,this.exceptions,this.MAX_EXCEPTIONS,this.formatRemoteObject,this.extractValue}setPlaywrightPage(e){this.playwrightPage=e,this.playwrightNetworkMonitor?.setPage(e)}clearPlaywrightPage(){this.playwrightPage=null,this.contextSwitchPending=!1,this.playwrightConsoleHandler=null,this.playwrightErrorHandler=null,this.playwrightNetworkMonitor?.setPage(null),this.playwrightNetworkMonitor=null}getManagedTargetSession(){return this.collector.getAttachedTargetSession?.()??null}getManagedTargetNetworkMonitor(){return this.collector.getBrowserTargetSessionManager?.()??null}async createCdpSession(){let e=this.getManagedTargetSession();if(e)return{session:e,managed:!0};let t=await this.collector.getActivePage();return{session:await Promise.race([t.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),managed:!1}}markContextChanged(){!this.cdpSession&&!this.playwrightPage&&!this.networkMonitor&&!this.playwrightNetworkMonitor&&!this.fetchInterceptor||(this.contextSwitchPending=!0,this.clearLogs(),this.clearExceptions(),this.networkMonitor?.persistsAcrossContextSwitches?.()||this.clearNetworkRecords(),this.clearObjectCache(),e.info(`ConsoleMonitor marked stale after active context switch`))}async enable(e){if(this.contextSwitchPending&&await this.disable(),this.initPromise){await this.initPromise,await this.applyPostEnableOptions(e);return}this.initPromise=this.doEnable(e);try{await this.initPromise}finally{this.initPromise=void 0}}async doEnable(n){if(this.playwrightPage)return this.lastEnableOptions={...n},B(this,n);if(this.cdpSession){n?.enableNetwork&&!this.networkMonitor&&(this.networkMonitor=this.getManagedTargetNetworkMonitor()??new t(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`));return}let{session:r,managed:i}=await this.createCdpSession();await z(this,r,i,n)}async applyPostEnableOptions(n){if(n?.enableNetwork){if(this.lastEnableOptions={...this.lastEnableOptions,...n},this.playwrightPage&&this.playwrightConsoleHandler&&!this.playwrightNetworkMonitor){await B(this,n);return}this.cdpSession&&!this.networkMonitor&&(this.networkMonitor=this.getManagedTargetNetworkMonitor()??new t(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`))}}async disable(){try{this.cdpSession&&this.fetchInterceptor&&(await this.fetchInterceptor.disable(),this.fetchInterceptor=null),await V(this)}finally{this.fetchInterceptor=null,this.initPromise=void 0,this.contextSwitchPending=!1,this.objectCache.clear()}}async ensureSession(){if(this.contextSwitchPending){e.info(`ConsoleMonitor context switched, rebinding on demand...`);let t={...this.lastEnableOptions};await this.disable(),await this.enable(t);return}if(!this.cdpSession&&!this.playwrightPage){e.info(`ConsoleMonitor CDP session lost, reinitializing...`),await this.enable(this.lastEnableOptions);return}if(this.cdpSession)try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]);return}catch{e.warn(`ConsoleMonitor CDP session unresponsive (zombie), reinitializing...`),this.cdpSession=null,this.networkMonitor=null,this.fetchInterceptor=null,this.usingManagedTargetSession=!1,await this.enable(this.lastEnableOptions)}}isSessionActive(){return!this.contextSwitchPending&&(this.cdpSession!==null||this.playwrightPage!==null)}getLogs(e){return s(this,e)}async execute(t){await this.ensureSession();try{let n=await H(this.cdpSession,`Runtime.evaluate`,{expression:t,returnByValue:!0});if(n.exceptionDetails)throw e.error(`Console execute error:`,n.exceptionDetails),Error(n.exceptionDetails.text);return e.info(`Console expression executed`),n.result.value}catch(t){throw e.error(`Console execute failed:`,t),t}}clearLogs(){c(this)}getStats(){return l(this)}async close(){try{await this.disable()}finally{this.initPromise=void 0,this.objectCache.clear()}}isNetworkEnabled(){return m(this)}getNetworkStatus(){return h(this)}getNetworkRequests(e){return g(this,e)}getNetworkResponses(e){return _(this,e)}getNetworkActivity(e){return v(this,e)}async getResponseBody(e){return y(this,e)}async getAllJavaScriptResponses(){return b(this)}clearNetworkRecords(){x(this)}async clearInjectedBuffers(){return S(this)}async resetInjectedInterceptors(){return C(this)}getNetworkStats(){return w(this)}async injectXHRInterceptor(e){return T(this,e)}async injectFetchInterceptor(e){return E(this,e)}async getXHRRequests(){return D(this)}async getFetchRequests(){return O(this)}getExceptions(e){return u(this,e)}clearExceptions(){d(this)}async inspectObject(e){return k(this,e)}clearObjectCache(){A(this)}async enableDynamicScriptMonitoring(e){return M(this,e)}async clearDynamicScriptBuffer(){return N(this)}async resetDynamicScriptMonitoring(){return P(this)}async getDynamicScripts(){return F(this)}async injectFunctionTracer(e,t){return I(this,e,t)}async injectPropertyWatcher(e,t,n){return L(this,e,t,n)}async enableFetchIntercept(e){if(await this.ensureSession(),!this.cdpSession)throw Error(`No CDP session available for Fetch interception`);return this.fetchInterceptor||=new a(this.cdpSession),this.fetchInterceptor.enable(e)}async disableFetchIntercept(){if(!this.fetchInterceptor)return{removedRules:0};let e=await this.fetchInterceptor.disable();return this.fetchInterceptor=null,e}async removeFetchInterceptRule(e){if(!this.fetchInterceptor)return!1;let t=await this.fetchInterceptor.removeRule(e);return this.fetchInterceptor.isEnabled()||(this.fetchInterceptor=null),t}getFetchInterceptStatus(){return this.fetchInterceptor?this.fetchInterceptor.listRules():{enabled:!1,rules:[],totalHits:0}}formatRemoteObject(e){return e.value===void 0?e.description?e.description:e.type===`undefined`?`undefined`:e.type===`object`&&e.subtype===`null`?`null`:`[${e.type}]`:String(e.value)}extractValue(e){if(e.value!==void 0)return e.value;if(e.type!==`undefined`)return e.type===`object`&&e.subtype===`null`?null:e.objectId?{__objectId:e.objectId,__type:e.type,__description:e.description}:e.description||`[${e.type}]`}};export{U as ConsoleMonitor};
@@ -1 +0,0 @@
1
- import{t as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";import n from"koffi";var r=e({KERN:()=>i,SM:()=>l,VM_FLAGS:()=>c,VM_PROT:()=>s,VM_REGION_BASIC_INFO_64:()=>9,VM_REGION_BASIC_INFO_COUNT_64:()=>9,dyldGetImageHeader:()=>O,dyldGetImageName:()=>D,dyldImageCount:()=>E,isDarwin:()=>f,isKoffiAvailableOnDarwin:()=>p,kernReturnName:()=>o,machPortDeallocate:()=>_,machTaskSelf:()=>h,machVmAllocate:()=>S,machVmDeallocate:()=>C,machVmProtect:()=>x,machVmReadOverwrite:()=>v,machVmRegion:()=>b,machVmWrite:()=>y,taskForPid:()=>g,taskResume:()=>T,taskSuspend:()=>w});const i={SUCCESS:0,INVALID_ADDRESS:1,PROTECTION_FAILURE:2,NO_SPACE:3,INVALID_ARGUMENT:4,FAILURE:5,RESOURCE_SHORTAGE:6,NOT_RECEIVER:7,NO_ACCESS:8,MEMORY_FAILURE:9,MEMORY_ERROR:10,ALREADY_IN_SET:11,NOT_IN_SET:12,NAME_EXISTS:13,ABORTED:14,INVALID_NAME:15,INVALID_TASK:16,INVALID_RIGHT:17,INVALID_VALUE:18,UREFS_OVERFLOW:19,INVALID_CAPABILITY:20,RIGHT_EXISTS:21,INVALID_HOST:22,MEMORY_PRESENT:23,MEMORY_DATA_MOVED:24,MEMORY_RESTART_COPY:25,INVALID_PROCESSOR_SET:26,POLICY_LIMIT:27,INVALID_POLICY:28,INVALID_OBJECT:29,ALREADY_WAITING:30,DEFAULT_SET:31,EXCEPTION_PROTECTED:32,INVALID_LEDGER:33,INVALID_MEMORY_CONTROL:34,INVALID_SECURITY:35,NOT_DEPRESSED:36,TERMINATED:37,LOCK_SET_DESTROYED:38,LOCK_UNSTABLE:39,LOCK_OWNED:40,LOCK_OWNED_SELF:41,SEMAPHORE_DESTROYED:42,RPC_SERVER_TERMINATED:43,RPC_TERMINATE_ORPHAN:44,RPC_CONTINUE_ORPHAN:45,NOT_SUPPORTED:46,NODE_DOWN:47,NOT_WAITING:48,OPERATION_TIMED_OUT:49,CODESIGN_ERROR:50,POLICY_STATIC:51},a={[i.SUCCESS]:`KERN_SUCCESS`,[i.INVALID_ADDRESS]:`KERN_INVALID_ADDRESS`,[i.PROTECTION_FAILURE]:`KERN_PROTECTION_FAILURE`,[i.NO_SPACE]:`KERN_NO_SPACE`,[i.INVALID_ARGUMENT]:`KERN_INVALID_ARGUMENT`,[i.FAILURE]:`KERN_FAILURE`,[i.NO_ACCESS]:`KERN_NO_ACCESS`,[i.INVALID_TASK]:`KERN_INVALID_TASK`,[i.INVALID_RIGHT]:`KERN_INVALID_RIGHT`,[i.CODESIGN_ERROR]:`KERN_CODESIGN_ERROR`};function o(e){return a[e]??`KERN_UNKNOWN(${e})`}const s={NONE:0,READ:1,WRITE:2,EXECUTE:4,ALL:7},c={FIXED:0,ANYWHERE:1,PURGABLE:2,RANDOM_ADDR:8,OVERWRITE:16384},l={COW:1,PRIVATE:2,EMPTY:3,SHARED:4,TRUESHARED:5,PRIVATE_ALIASED:6,SHARED_ALIASED:7,LARGE_PAGE:8};let u=null,d=null;function f(){return process.platform===`darwin`}function p(){if(d!==null)return d;try{return n.load(`/usr/lib/libSystem.B.dylib`).unload(),d=!0,!0}catch{return d=!1,!1}}function m(){return u||(u=n.load(`/usr/lib/libSystem.B.dylib`),t.debug(`Loaded libSystem.B.dylib via koffi`)),u}function h(){return m().func(`uint32 mach_task_self()`)()}function g(e,t){let n=m().func(`int32 task_for_pid(uint32, int32, _Out_ uint32 *)`),r=Buffer.alloc(4);return{kr:n(e,t,r),task:r.readUInt32LE(0)}}function _(e,t){return m().func(`int32 mach_port_deallocate(uint32, uint32)`)(e,t)}function v(e,t,n){let r=m().func(`int32 mach_vm_read_overwrite(uint32, uint64, uint64, _Out_ uint8_t *, uint64, _Out_ uint64 *)`),i=Buffer.alloc(n),a=Buffer.alloc(8);return{kr:r(e,t,BigInt(n),i,BigInt(n),a),data:i,outsize:a.readBigUInt64LE(0)}}function y(e,t,n){return m().func(`int32 mach_vm_write(uint32, uint64, uint8_t *, uint32)`)(e,t,n,n.length)}function b(e,t){let n=m().func(`int32 mach_vm_region(uint32, _Inout_ uint64 *, _Out_ uint64 *, int32, _Out_ uint8_t *, _Inout_ uint32 *, _Out_ uint32 *)`),r=Buffer.alloc(8);r.writeBigUInt64LE(t);let i=Buffer.alloc(8),a=Buffer.alloc(36),o=Buffer.alloc(4);o.writeUInt32LE(9);let s=n(e,r,i,9,a,o,Buffer.alloc(4)),c={protection:a.readUInt32LE(0),max_protection:a.readUInt32LE(4),inheritance:a.readUInt32LE(8),shared:a.readUInt32LE(12)!==0,reserved:a.readUInt32LE(16)!==0,offset:a.readBigUInt64LE(20),behavior:a.readUInt32LE(28),user_wired_count:a.readUInt32LE(32)};return{kr:s,address:r.readBigUInt64LE(0),size:i.readBigUInt64LE(0),info:c}}function x(e,t,n,r,i){return m().func(`int32 mach_vm_protect(uint32, uint64, uint64, int32, int32)`)(e,t,n,+!!r,i)}function S(e,t,n){let r=m().func(`int32 mach_vm_allocate(uint32, _Inout_ uint64 *, uint64, int32)`),i=Buffer.alloc(8);return i.writeBigUInt64LE(0n),{kr:r(e,i,t,n),address:i.readBigUInt64LE(0)}}function C(e,t,n){return m().func(`int32 mach_vm_deallocate(uint32, uint64, uint64)`)(e,t,n)}function w(e){return m().func(`int32 task_suspend(uint32)`)(e)}function T(e){return m().func(`int32 task_resume(uint32)`)(e)}function E(){return m().func(`uint32 _dyld_image_count()`)()}function D(e){let t=m().func(`const char * _dyld_get_image_name(uint32)`)(e);return t?String(t):``}function O(e){let t=m().func(`void * _dyld_get_image_header(uint32)`);return BigInt(t(e))}export{v as _,s as a,g as b,E as c,o as d,_ as f,x as g,C as h,c as i,f as l,S as m,i as n,O as o,h as p,l as r,D as s,r as t,p as u,b as v,y};
@@ -1 +0,0 @@
1
- import{i as e}from"./ToolCatalog-DgmQXdsm.mjs";const t=[`search`,`workflow`,`full`];function n(e){return e.profiles&&e.profiles.length>0?e.profiles:t}function r(t,n){for(let r of t.selectedTools)if(e(r.name)===n)return!0;for(let r of t.activatedToolNames){let i=t.extensionToolsByName.get(r);if(i){if(i.domain===n)return!0;continue}if(e(r)===n)return!0}return!1}function i(e,t){if(r(e,t)){e.enabledDomains.add(t);return}e.enabledDomains.delete(t)}function a(e,t){return n(t).includes(e)}function o(e,t,n=`activate_tools`){if(e.activatedToolNames.has(t.name))return e.enabledDomains.add(t.domain),t.activationSource??=n,t.activatedAt??=new Date().toISOString(),!1;let r=e.registerSingleTool(t.tool);return e.activatedToolNames.add(t.name),e.activatedRegisteredTools.set(t.name,r),t.registeredTool=r,t.activationSource=n,t.activatedAt=new Date().toISOString(),e.enabledDomains.add(t.domain),t.handler&&e.router.addHandlers({[t.name]:t.handler}),!0}function s(e,t,n={}){let r=t.registeredTool??e.activatedRegisteredTools.get(t.name),a=!!r||e.activatedToolNames.has(t.name)||e.activatedRegisteredTools.has(t.name);if(r&&!n.skipRegisteredToolRemoval)try{r.remove()}catch(e){n.onRemoveError?.(e)}return e.router.removeHandler(t.name),e.activatedToolNames.delete(t.name),e.activatedRegisteredTools.delete(t.name),t.registeredTool=void 0,t.activationSource=void 0,t.activatedAt=void 0,n.removeDefinition&&e.extensionToolsByName.delete(t.name),i(e,t.domain),a}export{a as n,s as r,o as t};
@@ -1 +0,0 @@
1
- import{n as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";var n=class n{static instance=null;activeProfile=null;available=null;constructor(){}static getInstance(){return n.instance||=new n,n.instance}isAvailable(){if(this.available!==null)return this.available;try{e.resolve(`fingerprint-generator`),e.resolve(`fingerprint-injector`),this.available=!0}catch{this.available=!1}return this.available}async generateFingerprint(e){if(!this.isAvailable())return t.warn(`fingerprint-generator not installed. Run: pnpm add fingerprint-generator fingerprint-injector`),null;try{let{FingerprintGenerator:n}=await import(`fingerprint-generator`),r=new n,i={};e?.os&&(i.operatingSystems=[{windows:`windows`,macos:`macos`,linux:`linux`}[e.os]??`windows`]),e?.browser&&(i.browsers=[e.browser]),e?.locale&&(i.locales=[e.locale]),e?.screen&&(i.screen=e.screen);let a=r.getFingerprint(i);return this.activeProfile={fingerprint:a.fingerprint,headers:a.headers??{},generatedAt:Date.now(),os:e?.os??`windows`,browser:e?.browser??`chrome`},t.info(`Fingerprint generated for ${this.activeProfile.os}/${this.activeProfile.browser}`),this.activeProfile}catch(e){return t.error(`Failed to generate fingerprint:`,e),null}}async injectFingerprint(e,n){if(!this.isAvailable())throw Error(`fingerprint-injector not installed`);try{let{newInjectedPage:r}=await import(`fingerprint-injector`);await r(e,{fingerprint:`fingerprint`in n?n.fingerprint:n}),t.info(`Fingerprint injected into page`)}catch(e){throw t.error(`Failed to inject fingerprint:`,e),e}}getActiveProfile(){return this.activeProfile}clearProfile(){this.activeProfile=null}static resetInstance(){n.instance=null}};export{n as FingerprintManager};
@@ -1 +0,0 @@
1
- import{U as e,W as t}from"./constants-DMv3svps.mjs";import{t as n}from"./ToolError-g3rjWzhx.mjs";import{t as r}from"./Win32API-DoP3MMHS.mjs";import{_ as i,a,c as o,d as s,f as c,g as l,h as u,i as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v,v as y,y as b}from"./Win32Debug-DwF8mQGm.mjs";import{randomUUID as x}from"node:crypto";const S=e=>`0x${e.toString(16).toUpperCase()}`;var C=class{breakpoints=new Map;attachedPids=new Set;drAllocation=[!1,!1,!1,!1];async attach(e){if(!this.attachedPids.has(e)){d(e),p(!1),this.attachedPids.add(e);for(let e=0;e<100;e++){let e=u(100);if(!e)break;f(e.processId,e.threadId,h.CONTINUE)}}}async detach(e){for(let[t,n]of this.breakpoints)n.pid===e&&(this.clearDR(e,n.drIndex),this.drAllocation[n.drIndex]=!1,this.breakpoints.delete(t));if(this.attachedPids.has(e)){try{a(e)}catch{}this.attachedPids.delete(e)}}async setBreakpoint(e,t,n,r=4){this.attachedPids.has(e)||await this.attach(e);let i=this.allocateDR(),a=BigInt(t.startsWith(`0x`)?t:`0x${t}`);this.applyDRToAllThreads(e,i,a,n,r,!0);let o={id:x(),pid:e,address:`0x${a.toString(16).toUpperCase()}`,access:n,size:r,enabled:!0,drIndex:i,hitCount:0};return this.breakpoints.set(o.id,o),o}async removeBreakpoint(e){let t=this.breakpoints.get(e);return t?(this.clearDR(t.pid,t.drIndex),this.drAllocation[t.drIndex]=!1,this.breakpoints.delete(e),!0):!1}listBreakpoints(){return Array.from(this.breakpoints.values()).map(e=>({id:e.id,address:e.address,access:e.access,size:e.size,enabled:e.enabled,hitCount:e.hitCount,lastHit:e.lastHit}))}async waitForHit(t){let n=t??e,r=Date.now()+n;for(;Date.now()<r;){let e=Math.max(100,r-Date.now()),t=u(Math.min(e,500));if(t)if(t.exceptionCode===g.SINGLE_STEP){let e=this.processHit(t.threadId,t.processId,t.exceptionAddress);if(f(t.processId,t.threadId,h.CONTINUE),e)return e}else f(t.processId,t.threadId,h.CONTINUE)}return null}async traceAccess(n,r,i,a,o){let s=a??t,c=o??e,l=await this.setBreakpoint(n,r,i),u=[],d=Date.now()+c;for(;u.length<s&&Date.now()<d;){let e=await this.waitForHit(Math.min(1e3,d-Date.now()));e?.breakpointId===l.id&&u.push(e)}return await this.removeBreakpoint(l.id),u}allocateDR(){for(let e=0;e<4;e++)if(!this.drAllocation[e])return this.drAllocation[e]=!0,e;throw new n(`PREREQUISITE`,`All 4 hardware breakpoint registers (DR0-DR3) are in use`)}applyDRToAllThreads(e,t,n,a,u,d){let f=o(e),p={execute:`execute`,write:`write`,readwrite:`readwrite`,read:`read`};for(let e of f){let o;try{o=i(e)}catch{continue}try{m(o);let e=v(o,_.ALL),r=[72,80,88,96];d?e.writeBigUInt64LE(n,r[t]):e.writeBigUInt64LE(0n,r[t]);let i=Array.from(this.breakpoints.values()).filter(e=>e.enabled).map(e=>({drIndex:e.drIndex,enabled:!0,access:p[e.access],size:e.size}));d&&i.push({drIndex:t,enabled:!0,access:p[a],size:u});let f=l(i);e.writeBigUInt64LE(f,112),b(e,{contextFlags:_.ALL}),c(o,e),s(o)}catch{try{s(o)}catch{}}finally{r(o)}}}clearDR(e,t){this.applyDRToAllThreads(e,t,0n,`write`,1,!1)}processHit(e,t,n){let a;try{a=i(e)}catch{return null}try{let n=v(a,_.ALL),r=y(n);for(let[i,o]of this.breakpoints){if(o.pid!==t)continue;let s=1n<<BigInt(o.drIndex);if(r.dr6&s)return o.hitCount++,o.lastHit=Date.now(),n.writeBigUInt64LE(0n,104),c(a,n),{breakpointId:i,address:o.address,accessAddress:o.address,instructionAddress:S(r.rip),threadId:e,accessType:o.access,timestamp:Date.now(),registers:{rax:S(r.rax),rbx:S(r.rbx),rcx:S(r.rcx),rdx:S(r.rdx),rsi:S(r.rsi),rdi:S(r.rdi),rsp:S(r.rsp),rbp:S(r.rbp),r8:S(r.r8),r9:S(r.r9),r10:S(r.r10),r11:S(r.r11),r12:S(r.r12),r13:S(r.r13),r14:S(r.r14),r15:S(r.r15),rip:S(r.rip),rflags:`0x${r.eflags.toString(16).toUpperCase()}`}}}return null}finally{r(a)}}};const w=new C;export{C as HardwareBreakpointEngine,w as hardwareBreakpointEngine};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-CCikqqvj.mjs";import{cn as t,ln as n,on as r,sn as i}from"./constants-DMv3svps.mjs";import{t as a}from"./ToolError-g3rjWzhx.mjs";import{b as o,d as s,t as c}from"./Win32API-DoP3MMHS.mjs";import{m as l}from"./Win32Debug-DwF8mQGm.mjs";import u from"koffi";const d={FIXED:1,FREE:2,MOVEABLE:4},f={DEFAULT:1,SHARED:2};let p=null;function m(){let e=u.load(`kernel32.dll`);return{CreateToolhelp32Snapshot:e.func(`CreateToolhelp32Snapshot`,`intptr`,[`uint32`,`uint32`]),Heap32ListFirst:e.func(`Heap32ListFirst`,`bool`,[`intptr`,`_Inout_ uint8_t *`]),Heap32ListNext:e.func(`Heap32ListNext`,`bool`,[`intptr`,`_Inout_ uint8_t *`]),Heap32First:e.func(`Heap32First`,`bool`,[`_Inout_ uint8_t *`,`uint32`,`uintptr_t`]),Heap32Next:e.func(`Heap32Next`,`bool`,[`_Inout_ uint8_t *`]),CloseHandle:e.func(`int CloseHandle(intptr)`),HEAPLIST32_SIZE:36,HEAPENTRY32_SIZE:56}}function h(){return p||=m(),p}const g=[[`0-64B`,0,64],[`64-256B`,64,256],[`256B-1KB`,256,1024],[`1-4KB`,1024,4096],[`4-16KB`,4096,16384],[`16-64KB`,16384,65536],[`64KB-1MB`,65536,1048576],[`>1MB`,1048576,2**53-1]];function _(e){for(let t=0;t<g.length;t++){let n=g[t];if(e>=n[1]&&e<n[2])return t}return g.length-1}var v=class{async enumerateHeaps(e){let t=h(),n=t.CreateToolhelp32Snapshot(l.SNAPHEAPLIST,e);if(n===-1n&&typeof n==`bigint`)throw new a(`RUNTIME`,`Failed to create heap snapshot for PID ${e}`);let i=[];try{let a=Buffer.alloc(t.HEAPLIST32_SIZE);a.writeBigUInt64LE(BigInt(t.HEAPLIST32_SIZE),0);let o=t.Heap32ListFirst(n,a);for(;o;){let s=a.readUInt32LE(8),c=a.readBigUInt64LE(12),l=a.readUInt32LE(20),u=await this.enumerateBlocksInternal(e,c,r);i.push({heapId:`0x${c.toString(16)}`,processId:s,flags:l,isDefault:(l&f.DEFAULT)!==0,blockCount:u.length,totalSize:u.reduce((e,t)=>e+t.size,0)}),a.writeBigUInt64LE(BigInt(t.HEAPLIST32_SIZE),0),o=t.Heap32ListNext(n,a)}}finally{t.CloseHandle(n)}return{heaps:i,stats:this.computeStats(i,[])}}async enumerateBlocks(e,t,n){let i=BigInt(t),a=n?.maxBlocks??r;return this.enumerateBlocksInternal(e,i,a)}async getStats(e){let{heaps:t}=await this.enumerateHeaps(e),n=[];for(let i of t){let t=await this.enumerateBlocksInternal(e,BigInt(i.heapId),r);n.push(...t)}return this.computeStats(t,n)}async detectAnomalies(e){let t=[],{heaps:n}=await this.enumerateHeaps(e);for(let i of n){let n=await this.enumerateBlocksInternal(e,BigInt(i.heapId),r);this.detectSpray(n,i.heapId,t),this.detectSuspiciousSizes(n,i.heapId,t),await this.detectPossibleUaf(e,n,i.heapId,t)}return t}async enumerateBlocksInternal(e,t,n){let r=h(),i=[],a=Buffer.alloc(r.HEAPENTRY32_SIZE);a.writeBigUInt64LE(BigInt(r.HEAPENTRY32_SIZE),0);let o=r.Heap32First(a,e,t);for(;o&&i.length<n;){let e=a.readBigUInt64LE(16),n=Number(a.readBigUInt64LE(24)),s=a.readUInt32LE(32);i.push({address:`0x${e.toString(16)}`,size:n,flags:s,heapId:`0x${t.toString(16)}`,isFree:(s&d.FREE)!==0}),a.writeBigUInt64LE(BigInt(r.HEAPENTRY32_SIZE),0),o=r.Heap32Next(a)}return i}computeStats(e,t){let n=g.map(([e])=>({range:e,count:0,totalBytes:0})),r=0,i=0,a=0,o=2**53-1;for(let e of t){r+=e.size,e.isFree&&(i+=e.size),e.size>a&&(a=e.size),!e.isFree&&e.size<o&&(o=e.size);let t=_(e.size);n[t].count++,n[t].totalBytes+=e.size}return o===2**53-1&&(o=0),r===0&&e.length>0&&(r=e.reduce((e,t)=>e+t.totalSize,0)),{totalHeaps:e.length,totalBlocks:t.length||e.reduce((e,t)=>e+t.blockCount,0),totalSize:r,freeSize:i,usedSize:r-i,largestBlock:a,smallestBlock:o,averageBlockSize:t.length>0?Math.round(r/t.length):0,sizeDistribution:n,fragmentationRatio:r>0?i/r:0}}detectSpray(e,n,r){let a=new Map;for(let t of e){if(t.isFree)continue;let e=Math.round(t.size/i)*i,n=a.get(e)??[];n.push(t),a.set(e,n)}for(let[e,i]of a)i.length>=t&&r.push({type:`heap_spray_pattern`,severity:`high`,address:i[0].address,details:`${i.length} blocks of ~${e} bytes detected — possible heap spray`,heapId:n})}detectSuspiciousSizes(e,t,r){for(let i of e)i.size===0?r.push({type:`suspicious_size`,severity:`medium`,address:i.address,details:`Block with zero size`,heapId:t}):i.size>n&&r.push({type:`suspicious_size`,severity:`medium`,address:i.address,details:`Unusually large block: ${(i.size/(1024*1024)).toFixed(1)} MB`,heapId:t})}async detectPossibleUaf(t,n,r,i){let a=n.filter(e=>e.isFree&&e.size>=8).slice(0,100),l=null;try{l=o(t);for(let e of a){let t=BigInt(e.address),n=s(l,t,8);n&&n.readBigUInt64LE(0)!==0n&&i.push({type:`possible_uaf`,severity:`low`,address:e.address,details:`Free block has non-zero data: 0x${n.readBigUInt64LE(0).toString(16)}`,heapId:r})}}catch(n){e.debug(`UAF check failed for PID ${t}: ${n}`)}finally{l&&c(l)}}};const y=new v;export{v as HeapAnalyzer,y as heapAnalyzer};
@@ -1 +0,0 @@
1
- let e=0;function t(t){return`${t}-${Date.now().toString(36)}-${(++e).toString(36)}`}function n(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function r(e){let t=e.content.find(e=>e.type===`text`&&typeof e.text==`string`);if(!t)throw Error(`Expected JSON text payload from wrapped tool response`);let r;try{r=JSON.parse(t.text)}catch(e){throw Error(`Wrapped tool returned non-JSON text payload: ${e instanceof Error?e.message:String(e)}`,{cause:e})}if(!n(r))throw Error(`Wrapped tool returned JSON that is not an object`);return r}function i(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}var a=class{sessions=new Map;operations=new Map;artifacts=new Map;operationIndex=new Map;evidenceBridge;setEvidenceBridge(e){this.evidenceBridge=e}createSession(e){let n=t(`sess`),r={id:n,name:e,createdAt:Date.now(),operationCount:0,artifactCount:0,status:`active`};return this.sessions.set(n,r),this.operations.set(n,[]),this.artifacts.set(n,[]),r}destroySession(e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);t.status=`destroyed`;let n=this.operations.get(e)??[];for(let e of n)e.status===`active`&&(e.status=`completed`)}listSessions(){return[...this.sessions.values()].filter(e=>e.status===`active`)}getSession(e){return this.sessions.get(e)}registerOperation(e,n,r,i){let a=this.sessions.get(e);if(!a)throw Error(`Session "${e}" not found`);if(a.status===`destroyed`)throw Error(`Session "${e}" is destroyed — cannot register new operations`);let o=t(`op`),s={id:o,sessionId:e,type:n,target:r,config:i,createdAt:Date.now(),status:`active`},c=this.operations.get(e);return c.push(s),this.operationIndex.set(o,e),a.operationCount=c.length,this.evidenceBridge?.onOperation(s),s}getSessionOperations(e){return this.operations.get(e)??[]}recordArtifact(e,t){let n=this.operationIndex.get(e);if(!n)throw Error(`Operation "${e}" not found`);let r=(this.operations.get(n)??[]).find(t=>t.id===e);if(!r)throw Error(`Operation "${e}" metadata missing`);let i={operationId:e,sessionId:n,type:r.type,timestamp:Date.now(),data:t},a=this.artifacts.get(n);a.push(i);let o=this.sessions.get(n);return o.artifactCount=a.length,this.evidenceBridge?.onArtifact(i),i}getArtifacts(e,t){let n=this.artifacts.get(e)??[];return t?n.filter(e=>e.type===t):n}getSessionSnapshot(e){let t=this.sessions.get(e);if(t)return{session:t,stats:this.getSessionStats(e),operations:[...this.getSessionOperations(e)],artifacts:[...this.getArtifacts(e)]}}listSessionSnapshots(){return this.listSessions().map(e=>({session:e,stats:this.getSessionStats(e.id),operations:[...this.getSessionOperations(e.id)],artifacts:[...this.getArtifacts(e.id)]}))}async applyHookPreset(e,t,r){let a=i(r.presets),o=(typeof r.preset==`string`?r.preset:void 0)??(a.length>0?a.join(`, `):`hook_preset`);return this.executeTrackedTool({sessionId:e,type:`runtime-hook`,target:o,config:{...r},invoke:()=>t.handleHookPreset(r),isSuccessful:e=>i(e.injected).length>0,buildArtifacts:e=>{let t=i(e.injected);return[{presetIds:t,failedPresets:Array.isArray(e.failed)?e.failed.filter(e=>n(e)&&typeof e.preset==`string`&&typeof e.error==`string`):[],injectionPoint:e.method===`evaluateOnNewDocument`?`before-load`:`runtime`,scriptContent:t.join(`, `),body:e}]}})}async replayNetworkRequest(e,t,r){let i=typeof r.requestId==`string`?r.requestId:`network_replay`,a=typeof r.urlOverride==`string`?r.urlOverride:void 0;return this.executeTrackedTool({sessionId:e,type:`network-intercept`,target:i,config:{...r},invoke:()=>t.handleNetworkReplayRequest(r),buildArtifacts:e=>e.dryRun===!0&&n(e.preview)?[{requestId:i,url:typeof e.preview.url==`string`?e.preview.url:a,method:typeof e.preview.method==`string`?e.preview.method:void 0,headers:n(e.preview.headers)?e.preview.headers:void 0,body:e.preview.body,replayMode:`dry-run`}]:[{requestId:typeof e.requestId==`string`?e.requestId:i,url:a,method:typeof r.methodOverride==`string`?r.methodOverride:void 0,headers:n(e.headers)?e.headers:void 0,body:e.body,statusCode:typeof e.status==`number`?e.status:void 0,statusText:typeof e.statusText==`string`?e.statusText:void 0,bodyTruncated:typeof e.bodyTruncated==`boolean`?e.bodyTruncated:void 0,replayMode:`live`}]})}getSessionStats(e){let t=this.sessions.get(e);return t?{operationCount:t.operationCount,artifactCount:t.artifactCount}:{operationCount:0,artifactCount:0}}findOperation(e){let t=this.operationIndex.get(e);if(t)return(this.operations.get(t)??[]).find(t=>t.id===e)}setOperationStatus(e,t){let n=this.findOperation(e);n&&(n.status=t)}async executeTrackedTool(e){let t=this.registerOperation(e.sessionId,e.type,e.target,e.config);try{let n=r(await e.invoke());if(!(e.isSuccessful?e.isSuccessful(n):n.success!==!1))return this.setOperationStatus(t.id,`failed`),{operation:t,artifacts:[],payload:n};let i=(e.buildArtifacts?.(n)??[]).map(e=>this.recordArtifact(t.id,e));return this.setOperationStatus(t.id,`completed`),{operation:t,artifacts:i,payload:n}}catch(e){throw this.setOperationStatus(t.id,`failed`),e}}};export{a as InstrumentationSessionManager};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-CCikqqvj.mjs";import{i as t}from"./ToolCatalog-DgmQXdsm.mjs";import{n}from"./ServerRuntimeState-CgqBBwfd.mjs";function r(t,n,r,i){if(o(t,n),r<=0)return;let a=r*60*1e3,c=new Set(i),l=setTimeout(()=>{e.info(`Domain "${n}" TTL expired (${r}min) — auto-deactivating ${c.size} tools`),s(t,n).catch(t=>{e.error(`Failed to deactivate domain "${n}" on TTL expiry:`,t)})},a);t.domainTtlEntries.set(n,{timer:l,ttlMs:a,toolNames:c})}function i(t,n){let r=t.domainTtlEntries.get(n);if(!r)return;clearTimeout(r.timer);let i=r.ttlMs/6e4;r.timer=setTimeout(()=>{e.info(`Domain "${n}" TTL expired (${i}min) — auto-deactivating`),s(t,n).catch(t=>{e.error(`Failed to deactivate domain "${n}" on TTL expiry:`,t)})},r.ttlMs)}function a(e,n){let r=t(n);if(!r){let t=e.extensionToolsByName.get(n);t&&(r=t.domain)}r&&e.domainTtlEntries.has(r)&&i(e,r)}function o(e,t){let r=e.domainTtlEntries.get(t);r&&(clearTimeout(r.timer),e.domainTtlEntries.delete(t)),n(e)?.clearPendingDomainActivation(t)}async function s(r,i){let a=r.domainTtlEntries.get(i);if(!a)return;let o=a.toolNames;r.domainTtlEntries.delete(i),n(r)?.clearPendingDomainActivation(i);let s=0;for(let t of o){if(!r.activatedToolNames.has(t))continue;let n=r.activatedRegisteredTools.get(t);if(n)try{n.remove()}catch(n){e.warn(`Failed to remove tool "${t}" on domain TTL expiry:`,n)}r.router.removeHandler(t),r.activatedToolNames.delete(t),r.activatedRegisteredTools.delete(t);let i=r.extensionToolsByName.get(t);i&&(i.registeredTool=void 0),s++}if(s>0){r.enabledDomains.delete(i);for(let e of r.activatedToolNames)if(t(e)===i){r.enabledDomains.add(i);break}for(let e of r.selectedTools)if(t(e.name)===i){r.enabledDomains.add(i);break}try{await r.server.sendToolListChanged()}catch(t){e.warn(`sendToolListChanged failed after domain TTL expiry:`,t)}e.info(`Domain "${i}" deactivated: removed ${s} tools`)}}export{a as n,r,o as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./chunk-88NL7fhV.mjs";import{$r as t,Ai as n,Ci as r,Di as i,Ei as a,Jr as o,Oi as s,Qr as c,Si as l,Ti as u,Yr as d,Zr as f,_i as p,ai as m,bi as h,ci as g,di as _,ei as v,fi as y,gi as b,hi as x,ii as ee,li as te,mi as ne,ni as S,oi as re,pi as ie,qr as ae,ri as C,si as w,ti as oe,ui as se,vi as ce,xi as T,yi as le}from"./constants-DMv3svps.mjs";import{t as E}from"./search-defaults-CJik67or.mjs";import{i as D,l as O,m as k,n as A,p as ue,r as de}from"./ToolCatalog-DgmQXdsm.mjs";import{t as fe}from"./ProcessRegistry-D5y1yuP2.mjs";import{t as pe}from"./RingBuffer-B6RTHmij.mjs";import{Worker as me}from"worker_threads";const he=[[`navigate`,`go`,`open`,`visit`,`browse`,`load`],[`intercept`,`capture`,`monitor`,`sniff`,`collect`,`record`,`track`],[`request`,`fetch`,`xhr`,`ajax`,`http`,`api`],[`authenticate`,`auth`,`login`,`credential`,`token`,`jwt`,`session`],[`breakpoint`,`pause`,`halt`,`stop`,`break`],[`step`,`next`,`continue`,`resume`],[`deobfuscate`,`beautify`,`unminify`,`decode`,`transform`,`decompile`],[`screenshot`,`snapshot`,`image`,`picture`,`photo`],[`evaluate`,`execute`,`run`,`eval`,`invoke`,`call`],[`element`,`node`,`selector`,`dom`,`component`],[`click`,`tap`,`press`,`interact`,`trigger`],[`type`,`input`,`enter`,`fill`,`write`],[`cookie`,`localstorage`,`storage`,`cache`,`indexeddb`],[`websocket`,`ws`,`socket`,`realtime`],[`scroll`,`swipe`,`drag`],[`search`,`find`,`query`,`lookup`,`discover`,`locate`],[`hook`,`patch`,`override`,`replace`,`wrap`,`proxy`],[`script`,`code`,`source`,`javascript`,`js`],[`bundle`,`webpack`,`module`,`pack`,`chunk`],[`block`,`filter`,`deny`,`reject`,`prevent`],[`allow`,`permit`,`whitelist`,`accept`,`enable`],[`remove`,`delete`,`clear`,`clean`,`purge`,`erase`],[`list`,`show`,`display`,`enumerate`,`get`],[`set`,`configure`,`config`,`setup`,`assign`],[`stealth`,`antidetect`,`fingerprint`,`evasion`,`undetected`],[`mobile`,`device`,`emulate`,`responsive`,`phone`],[`performance`,`profile`,`benchmark`,`metric`,`vitals`],[`register`,`signup`,`account`,`enroll`,`join`],[`captcha`,`challenge`,`verification`,`verify`,`solve`],[`tab`,`window`,`page`],[`inspect`,`examine`,`analyze`,`analyse`,`debug`,`investigate`],[`wait`,`delay`,`sleep`,`timeout`,`poll`],[`close`,`disconnect`,`quit`,`exit`,`shutdown`,`terminate`],[`traffic`,`network`,`request`,`response`,`connection`],[`heap`,`memory`,`allocation`,`gc`,`garbage`],[`export`,`save`,`dump`,`download`,`extract`],[`replay`,`resend`,`repeat`,`redo`,`retry`],[`variable`,`scope`,`local`,`closure`,`context`],[`watch`,`observe`,`monitor`,`trace`,`track`],[`protobuf`,`proto`,`binary`,`msgpack`,`grpc`],[`wasm`,`webassembly`,`assembly`],[`sse`,`eventsource`,`stream`,`streaming`],[`graphql`,`gql`,`introspect`,`mutation`,`subscription`],[`v8`,`heap`,`snapshot`,`bytecode`,`jit`,`turbofan`,`ignition`,`hiddenclass`],[`tls`,`ssl`,`boringssl`,`cert`,`certificate`,`pinning`,`handshake`,`keylog`],[`skia`,`gpu`,`render`,`scenegraph`,`scene`,`draw`,`paint`,`raster`,`layer`],[`frida`,`ghidra`,`ida`,`unidbg`,`jadx`,`binary`,`disassemble`,`decompile`,`instrument`],[`mojo`,`ipc`,`chromium`,`interface`,`broker`,`message`],[`syscall`,`etw`,`strace`,`dtrace`,`kernel`,`systemcall`,`tracefs`],[`adb`,`android`,`webview`,`apk`,`dalvik`,`art`,`emulator`],[`extension`,`plugin`,`addon`,`webhook`,`c2`,`bluetooth`,`ble`,`hid`,`serial`,`registry`]];var ge=class e{reverseMap;constructor(){this.reverseMap=e.buildReverseMap(he)}expand(e){let t=this.reverseMap.get(e.toLowerCase());return t?[...t]:[]}expandQuery(e){let t=new Set(e.map(e=>e.toLowerCase())),n=[],r=x;for(let i of e){let e=this.reverseMap.get(i.toLowerCase());if(!e)continue;let a=0;for(let i of e){if(a>=r)break;t.has(i)||(n.push(i),t.add(i),a++)}}return n}static buildReverseMap(e){let t=new Map;for(let n of e)for(let e of n){let r=e.toLowerCase(),i=t.get(r);i||(i=new Set,t.set(r,i));for(let e of n){let t=e.toLowerCase();t!==r&&i.add(t)}}return t}};const _e=c,ve=f;var ye=class e{queryCategoryProfiles;cjkQueryAliases;synonymExpander;constructor(t){this.queryCategoryProfiles=t?.queryCategoryProfiles===void 0?e.compileQueryCategoryProfiles(E.queryCategoryProfiles):e.compileQueryCategoryProfiles(t.queryCategoryProfiles),this.cjkQueryAliases=t?.cjkQueryAliases===void 0?e.compileCjkQueryAliasRules(E.cjkQueryAliases):e.compileCjkQueryAliasRules(t.cjkQueryAliases),this.synonymExpander=new ge}static compileQueryCategoryProfiles(e){return e.flatMap(e=>{if(!e||typeof e.pattern!=`string`||!Array.isArray(e.domainBoosts))return[];let t;try{t=new RegExp(e.pattern,e.flags)}catch{return[]}let n=new Map(e.domainBoosts.flatMap(e=>!e||typeof e.domain!=`string`||e.domain.length===0||typeof e.weight!=`number`||!Number.isFinite(e.weight)?[]:[[e.domain,e.weight]]));return[{pattern:t,domainBoosts:n}]})}static compileCjkQueryAliasRules(e){return e.flatMap(e=>{if(!e||typeof e.pattern!=`string`||!Array.isArray(e.tokens))return[];let t;try{t=new RegExp(e.pattern,e.flags)}catch{return[]}let n=e.tokens.filter(e=>typeof e==`string`&&e.length>0);return[{pattern:t,tokens:n}]})}detectQueryCategoryBoosts(e){let t=new Map;for(let n of this.queryCategoryProfiles)if(n.pattern.test(e))for(let[e,r]of n.domainBoosts){let n=t.get(e)??1;t.set(e,Math.max(n,r))}return t}expandCjkAliasTokens(e){let t=e.toLowerCase(),n=new Set;for(let e of this.cjkQueryAliases)if(e.pattern.test(t))for(let t of e.tokens)n.add(t);return[...n]}tokenise(e,t){let n=e.replace(/[_-]/g,` `);n=n.replace(/([\u4e00-\u9fff])/g,` $1 `);let r=n.split(/[^a-zA-Z0-9\u4e00-\u9fff]+/).filter(Boolean),i=[];for(let e of r){let t=e.toLowerCase(),n=e.replace(/([a-z])([A-Z])/g,`$1 $2`).split(/\s+/);if(n.length>1){for(let e of n)i.push(e.toLowerCase());i.push(t)}else i.push(t)}return i.push(...this.expandCjkAliasTokens(e)),t?.expandSynonyms&&i.push(...this.synonymExpander.expandQuery(i)),i}getK1(){return _e}getB(){return ve}},be=class{worker=null;ready=!1;nextId=0;pending=new Map;isReady(){return this.ready}async embed(e){this.ensureWorker();let t=this.nextId++;return new Promise((n,r)=>{this.pending.set(t,{resolve:n,reject:r}),this.worker.postMessage({type:`embed`,id:t,text:e})})}async embedBatch(e){if(e.length===0)return[];this.ensureWorker();let t=this.nextId++;return new Promise((n,r)=>{this.pending.set(t,{resolve:n,reject:r}),this.worker.postMessage({type:`embed_batch`,id:t,texts:e})})}async terminate(){if(this.worker){for(let[,e]of this.pending)e.reject(Error(`EmbeddingEngine terminated`));this.pending.clear(),await this.worker.terminate(),this.worker=null,this.ready=!1}}ensureWorker(){if(this.worker)return;let e=new URL(`./EmbeddingWorker.js`,import.meta.url);this.worker=new me(e),typeof this.worker.unref==`function`&&this.worker.unref(),fe.register(this.worker),this.worker.on(`message`,e=>{let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.type===`result`?(this.ready=!0,t.resolve(e.embedding)):e.type===`error`&&t.reject(Error(e.message??`Unknown worker error`)))}),this.worker.on(`error`,e=>{for(let[,t]of this.pending)t.reject(e);this.pending.clear(),this.worker=null,this.ready=!1}),this.worker.on(`exit`,e=>{if(e!==0){let t=Error(`Embedding worker exited with code ${e}`);for(let[,e]of this.pending)e.reject(t);this.pending.clear()}this.worker=null,this.ready=!1})}},j=class e{compiledRules;constructor(t){this.compiledRules=t===void 0?e.compileIntentToolBoostRules(E.intentToolBoostRules):e.compileIntentToolBoostRules(t)}static compileIntentToolBoostRules(e){let t=[];for(let n of e){if(!n||typeof n.pattern!=`string`||!Array.isArray(n.boosts)||n.boosts.length===0)continue;let e;try{e=new RegExp(n.pattern,n.flags??`i`)}catch{continue}let r=n.boosts.filter(e=>e&&typeof e.tool==`string`&&e.tool.length>0).map(e=>({tool:e.tool,bonus:Number.isFinite(e.bonus)?e.bonus:0})).filter(e=>e.bonus>0);r.length!==0&&t.push({pattern:e,boosts:r})}return t}resolveIntentToolBonuses(e){let t=e.toLowerCase(),n=new Map;for(let e of this.compiledRules)if(e.pattern.test(t))for(let{tool:t,bonus:r}of e.boosts){let e=n.get(t)??0;n.set(t,Math.max(e,r))}return n}getCompiledRules(){return this.compiledRules}},M=class e{trigramSets;constructor(t){this.trigramSets=t.map(t=>e.extractTrigrams(t))}search(t,n=h){let r=e.extractTrigrams(t);if(r.size===0)return new Map;let i=new Map;for(let t=0;t<this.trigramSets.length;t++){let a=this.trigramSets[t];if(a.size===0)continue;let o=e.jaccardSimilarity(r,a);o>=n&&i.set(t,o)}return i}static extractTrigrams(e){let t=e.toLowerCase().replace(/[_\-\s]+/g,``),n=new Set;for(let e=0;e<=t.length-3;e++)n.add(t.slice(e,e+3));return n}static jaccardSimilarity(e,t){let n=0,[r,i]=e.size<=t.size?[e,t]:[t,e];for(let e of r)i.has(e)&&n++;let a=e.size+t.size-n;return a===0?0:n/a}};const N=.1,P=.8;var xe=class{vectorWeight;lastVectorRanking=null;topN;learnUp;learnDown;constructor(e){this.vectorWeight=e?.vectorCosineWeight??r,this.topN=Math.max(1,i),this.learnUp=Math.max(0,s),this.learnDown=Math.max(0,a)}getVectorWeight(){return this.vectorWeight}recordVectorRanking(e){this.lastVectorRanking=e}recordToolCallFeedback(e,t){if(!this.lastVectorRanking||!t)return!1;let n=this.lastVectorRanking.get(e),r=this.vectorWeight;return n===void 0?this.vectorWeight=Math.max(N,this.vectorWeight-this.learnDown):n<this.topN?this.vectorWeight=Math.min(P,this.vectorWeight+this.learnUp):n<this.topN*2?this.vectorWeight=Math.min(P,this.vectorWeight+this.learnUp*.3):this.vectorWeight=Math.max(N,this.vectorWeight-this.learnDown),this.vectorWeight!==r}};const Se=new Set(`the.a.an.is.are.was.were.be.been.to.of.in.for.on.with.at.by.from.or.and.not.this.that.it.its.if.as.will.can.may.must.should.would.could.e.g.default.optional.required.when.set`.split(`.`)),F={extractParamTokens(e){let t=[];if(!e||typeof e!=`object`)return t;let n=e.properties;if(!n||typeof n!=`object`)return t;for(let[e,r]of Object.entries(n)){let n=e.replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[\s_-]+/);for(let e of n){let n=e.toLowerCase();n.length>1&&t.push(n)}if(r&&typeof r==`object`){let e=r.description;if(typeof e==`string`){let n=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);for(let e of n)e.length>2&&!Se.has(e)&&t.push(e)}}}return t},extractShortDescription(e){if(!e)return``;let t=e.match(/^[^.!?\n]+[.!?]?/);if(t){let e=t[0].trim();return e.length>120?e.slice(0,117)+`...`:e}return e.length>120?e.slice(0,117)+`...`:e},containsCJK(e){return/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(e)},normalizeToolName(e){return e.toLowerCase().replace(/[\s-]+/g,`_`)}},I={queryToolNameMatch:.35,descriptionKeywordOverlap:.25,domainRelevance:.2,intentAlignment:.2};function L(e){return e.toLowerCase().replace(/[\s-]+/g,`_`).replace(/[^a-z0-9_]/g,``)}function R(e){return e.toLowerCase().replace(/[_-]/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Ce(e,t){if(e===t)return 1;if(e.length===0||t.length===0)return 0;let n=e.length<=t.length?e:t,r=e.length<=t.length?t:e,i=new Float64Array(n.length+1),a=new Float64Array(n.length+1);for(let e=1;e<=r.length;e++){let t=r[e-1];for(let e=1;e<=n.length;e++){let r=i[e-1]??0;t===n[e-1]?a[e]=r+1:a[e]=Math.max(i[e]??0,a[e-1]??0)}let o=i;i=a,a=o,a.fill(0)}return(i[n.length]??0)/Math.max(e.length,t.length)}function we(e,t){if(e.size===0)return 0;let n=R(t),r=0;for(let t of n)e.has(t)&&r++;return r/e.size}var Te=class{weights;domainKeywords;constructor(e){this.weights=e?{...I,...e}:I,this.domainKeywords=new Map}buildFromTools(e){let t=new Map;for(let n of e){if(!n.domain)continue;let e=t.get(n.domain);e||(e=new Map,t.set(n.domain,e));let r=R(n.name);for(let t of r)e.set(t,(e.get(t)??0)+1);let i=R(n.description);for(let t of i)t.length>=3&&e.set(t,(e.get(t)??0)+1)}for(let[e,n]of t){let t=[...n.entries()].toSorted((e,t)=>t[1]-e[1]).slice(0,15);this.domainKeywords.set(e,new Set(t.map(([e])=>e)))}}reRank(e,t,n){if(t.length===0)return[];let r=n??t.length,i=L(e),a=R(e),o=new Set(a),s=this.inferTargetDomain(a),c=[];for(let e=0;e<t.length;e++){let n=t[e],r=Ce(i,L(n.toolName)),l=we(o,n.description),u=0;s.size>0&&n.domain&&(u=+!!s.has(n.domain));let d=this.computeIntentAlignment(a,n.description),f=this.weights.queryToolNameMatch*r+this.weights.descriptionKeywordOverlap*l+this.weights.domainRelevance*u+this.weights.intentAlignment*d,p=n.score*.3+f*.7;c.push({result:n,originalRank:e,reRankScore:p})}return c.toSorted((e,t)=>t.reRankScore-e.reRankScore).slice(0,r).map(e=>({toolName:e.result.toolName,originalRank:e.originalRank,reRankedScore:Math.round(e.reRankScore*1e4)/1e4}))}inferTargetDomain(e){let t=new Set,n=new Set(e);for(let[e,r]of this.domainKeywords)for(let i of r)if(n.has(i)){t.add(e);break}return t}computeIntentAlignment(e,t){if(e.length===0||this.domainKeywords.size===0)return 0;let n=t.toLowerCase(),r=[];for(let e of this.domainKeywords.values())for(let t of e)r.push(t);let i=e.filter(e=>r.includes(e));if(i.length===0)return 0;let a=0;for(let e of i)n.includes(e)&&a++;return a/i.length}};let Ee=0;function De(){return`sq-${Date.now()}-${++Ee}`}function z(e,t){if(e.length===0)return 0;let n=Math.ceil(t/100*e.length)-1;return e[Math.max(0,n)]??0}var B=class{MAX_HISTORY=1e3;records=new pe(this.MAX_HISTORY);lastRecordId;recordSearch(e,t,n,r){let i=De(),a={id:i,query:e,timestamp:Date.now(),returnedTools:t,returnedScores:n,latencyMs:r};return this.records.push(a),this.lastRecordId=i,i}recordToolUsed(e,t){let n=this.records.toArray();for(let r=n.length-1;r>=0;r--){let i=n[r];if(i.id===e){i.usedTool=t;let e=i.returnedTools.indexOf(t);i.usedToolRank=e>=0?e+1:void 0;return}}}associateLastSearch(e){if(!this.lastRecordId)return;let t=this.records.toArray();for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.id===this.lastRecordId){let t=r.returnedTools.indexOf(e);t>=0&&(r.usedTool=e,r.usedToolRank=t+1);return}}}computeMetrics(){let e=this.records.toArray(),t=e.length;if(t===0)return{totalQueries:0,avgLatencyMs:0,p50LatencyMs:0,p99LatencyMs:0,toolUsedRate:0,avgUsedRank:0,mrr:0,topKDistribution:{}};let n=e.map(e=>e.latencyMs).toSorted((e,t)=>e-t),r=n.reduce((e,t)=>e+t,0),i=e.filter(e=>e.usedTool!==void 0),a=i.length/t,o=0,s=0,c={};if(i.length>0){let e=0,t=0;for(let n of i){let r=n.usedToolRank;if(r!==void 0&&r>0){e+=r,t+=1/r;let n=String(r);c[n]=(c[n]??0)+1}}o=e/i.length,s=t/i.length}return{totalQueries:t,avgLatencyMs:r/t,p50LatencyMs:z(n,50),p99LatencyMs:z(n,99),toolUsedRate:a,avgUsedRank:o,mrr:s,topKDistribution:c}}getRecentRecords(e=10){return this.records.toArray().slice(-e)}getStats(){return this.computeMetrics()}getEnhancementSuggestions(e,t,n){if(t>=5&&n>=.5)return null;let r=[];return t===0?r.push(`No tools found for "${e}". Try broader terms or use search_tools with a different query.`):t<3&&r.push(`Only ${t} tools found. Consider using synonyms or breaking down the query.`),n<.3&&t>0&&r.push(`Low relevance scores. Try more specific tool names or domain prefixes (e.g., "page_", "hook_", "network_").`),r.length>0?r:null}};function V(e,t,n){if(!t)return-1;let r=e.indexOf(t);for(;r>=0;){let i=r>0?e[r-1]:null,a=r+t.length<e.length?e[r+t.length]:null,o=i===null||!n.test(i),s=a===null||!n.test(a);if(o&&s)return r;r=e.indexOf(t,r+1)}return-1}function Oe(e){let t=new Map,n=new Map;for(let t=0;t<e.length;t++){let r=e[t].name,i=r.indexOf(`_`);if(i<=0)continue;let a=r.slice(0,i),o=n.get(a)??[];o.push(t),n.set(a,o)}for(let[,e]of n){if(e.length<2||e.length>15)continue;let n=ae/Math.sqrt(e.length);for(let r of e){let i=t.get(r)??[];for(let t of e)t!==r&&i.push({docIndex:t,weight:n});t.set(r,i)}}return t}function ke(e){let t=[];for(let n=0;n<e.length;n++)e[n]>0&&t.push({idx:n,score:e[n]});t.sort((e,t)=>t.score-e.score);let n=new Map;for(let e=0;e<t.length;e++)n.set(t[e].idx,e);return n}function H(e){let t=[...e.entries()].toSorted((e,t)=>t[1]-e[1]),n=new Map;for(let e=0;e<t.length;e++)n.set(t[e][0],e);return n}function Ae(e,t){for(let n=0;n<e.length;n++){let r=t[n];r<=0||(e[n]=e[n]+r*y*se)}}function je(e){let{scores:t,docs:n,affinityGraph:r}=e,i=[];for(let e=0;e<t.length;e++)t[e]>0&&i.push({idx:e,score:t[e]});if(i.length!==0){if(i.sort((e,t)=>t.score-e.score),r.size>0){let e=Math.min(d,i.length);for(let n=0;n<e;n++){let{idx:e,score:a}=i[n],s=r.get(e);if(!s)continue;let c=1/(1+n);for(let{docIndex:e,weight:n}of s)t[e]>0&&(t[e]+=a*n*c*o)}}if(S>0&&i.length>=S){let e=i.slice(0,10),r=new Map;for(let{idx:t}of e){let e=n[t].domain;e&&r.set(e,(r.get(e)??0)+1)}for(let[e,i]of r)if(!(i<S))for(let r=0;r<n.length;r++)t[r]>0&&n[r].domain===e&&(t[r]*=oe)}}}function Me(e,t,n,r){return`${`${e}\0${t}`}${!n||n.size===0?``:`\0${[...n].toSorted().join(`|`)}`}${r?`\0${r}`:``}`}var U=class{capacity;map=new Map;constructor(e){this.capacity=Math.max(1,e)}get(e){let t=this.map.get(e);return t!==void 0&&(this.map.delete(e),this.map.set(e,t)),t}set(e,t){if(this.map.delete(e),this.map.set(e,t),this.map.size>this.capacity){let e=this.map.keys().next().value;this.map.delete(e)}}clear(){this.map.clear()}},Ne=class{docs=[];invertedIndex=new Map;sortedKeys;avgDocLength;docCount;domainOverrides;domainScoreMultipliers;toolScoreMultipliers;extensionEtag=``;docNameIndex=new Map;affinityGraph;queryCache;trigramIndex;embeddingEngine;toolEmbeddings=null;feedbackTracker;recencyTracker=new Map;bm25Scorer;intentBoost;reRanker;qualityTracker=new B;constructor(e,t,n,r,i,a){let o=e??A;this.domainOverrides=t,this.domainScoreMultipliers=n,this.toolScoreMultipliers=r,this.docCount=o.length,this.bm25Scorer=new ye(i);let s=i?.vectorEnabled??u;this.embeddingEngine=s?new be:null,this.feedbackTracker=new xe(i),this.intentBoost=new j(i?.intentToolBoostRules);let c=0;for(let e=0;e<o.length;e++){let t=o[e],n=this.domainOverrides?.get(t.name)??D(t.name),r=t.description??``,i=F.extractShortDescription(r),s=this.bm25Scorer.tokenise(t.name),l=new Set(s),u=n?this.bm25Scorer.tokenise(n):[],d=this.bm25Scorer.tokenise(r),f=F.extractParamTokens(t.inputSchema),p=[...s,...u,...d,...f],m={name:t.name,domain:n,description:r,shortDescription:i,tokens:p,length:p.length,nameTokens:s,nameTokenSet:l,nameTokenCount:l.size};this.docs.push(m),this.docNameIndex.set(t.name,e),c+=m.length;let h=new Map;for(let e of s){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,3),h.set(e,t)}for(let e of u){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,2),h.set(e,t)}for(let e of d){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,1),h.set(e,t)}for(let e of f){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,ee),h.set(e,t)}let g=a?.get(t.name);if(g)for(let e of g){let t=h.get(e)??{tf:0,weight:0};t.tf++,t.weight=Math.max(t.weight,ie),h.set(e,t)}for(let[t,{tf:n,weight:r}]of h){let i=this.invertedIndex.get(t);i||(i=[],this.invertedIndex.set(t,i)),i.push({docIndex:e,tf:n,weight:r})}}this.avgDocLength=this.docCount>0?c/this.docCount:1,this.sortedKeys=[...this.invertedIndex.keys()].toSorted(),this.reRanker=new Te,this.reRanker.buildFromTools(this.docs.map(e=>({name:e.name,domain:e.domain??``,description:e.description}))),this.affinityGraph=Oe(this.docs),this.trigramIndex=new M(this.docs.map(e=>e.name)),this.queryCache=new U(re)}async search(e,t=10,n,r,i){let a=performance.now(),o=this.bm25Scorer.tokenise(e);if(o.length===0)return[];if(ne&&this.isSimpleQuery(e,o))return this.quickPathSearch(e,o,t,n);if(o.length>6){let e=o.filter(e=>this.invertedIndex.has(e));if(e.length>=3){let t=e.map(e=>{let t=this.invertedIndex.get(e).length;return{token:e,idf:Math.log((this.docCount-t+.5)/(t+.5)+1)}});t.sort((e,t)=>t.idf-e.idf);let n=new Set(t.slice(0,6).map(e=>e.token));o=o.filter(e=>n.has(e))}}let s=this.bm25Scorer.tokenise(o.join(` `),{expandSynonyms:!0}).filter(e=>!o.includes(e));o.push(...s);let c=(()=>{let t=e.toLowerCase();if(!/(?:\b(?:call|use|run|invoke|execute)\b|调用|执行|使用|运行)/i.test(t))return null;let n=/[a-z0-9_]/,r=/[a-z0-9]/,i=null,a=1/0;for(let e of this.docNameIndex.keys()){let o=V(t,e,n);o<0&&e.includes(`_`)&&(o=V(t,e.replace(/_/g,`-`),r),o<0&&(o=V(t,e.replace(/_/g,` `),r))),!(o<0)&&(o<a||o===a&&e.length>(i?.length??0))&&(i=e,a=o)}return i})(),l=Me(e,t,r,this.extensionEtag),u=this.queryCache.get(l);if(u&&this.isCachedEntryFresh(u)){let e=n??new Set;return u.results.map(t=>({...t,isActive:e.has(t.name)}))}let d=this.intentBoost.resolveIntentToolBonuses(e),f=new Float64Array(this.docCount);for(let e of o)if(this.scoreToken(e,f),e.length>=3){let t=this.findPrefixMatches(e);for(let n of t)if(n!==e){let e=this.invertedIndex.get(n);e&&this.scorePostings(e,this.docCount,f,m)}}await this.applyRRFFusion(o,e,f);let p=this.bm25Scorer.detectQueryCategoryBoosts(e),h=e.toLowerCase().replace(/[\s-]+/g,`_`),g=new Set(o);for(let e=0;e<this.docCount;e++){let t=this.docs[e],n=d.get(t.name)??0;if(f[e]<=0&&n<=0)continue;if(t.name===h){f[e]*=C;continue}let r=0;for(let e of o)t.nameTokenSet.has(e)&&r++;if(r>0&&t.nameTokenCount>0&&g.size>0){let n=r/t.nameTokenCount,i=r/g.size;f[e]*=1+v*n*i}let i=t.domain?this.domainScoreMultipliers?.get(t.domain)??1:1;if(i!==1&&(f[e]*=i),t.domain&&p.size>0){let n=p.get(t.domain);n!==void 0&&n>1&&(f[e]*=n)}let a=this.toolScoreMultipliers?.get(t.name)??1;a!==1&&(f[e]*=a)}if(this.applyIntentBonusBand(f,d),this.applyGraphExpansion(f),this.applyRecencyBoost(f),this.applyTierPenalty(f,r,i),c){let e=this.docNameIndex.get(c);if(e!==void 0){let t=0;for(let e=0;e<this.docCount;e++){let n=f[e];n>t&&(t=n)}let n=Math.max(1,t+1);f[e]+=n}}let _=n??new Set,y=[];for(let e=0;e<this.docCount;e++)if(f[e]>0){let t=this.docs[e];y.push({name:t.name,domain:t.domain,shortDescription:t.shortDescription,score:Math.round(f[e]*1e3)/1e3,isActive:_.has(t.name)})}y.sort((e,t)=>t.score-e.score);let b=y.slice(0,t);if(b.length>1){let n=b.map(e=>({toolName:e.name,score:e.score,domain:e.domain??``,description:this.docs[this.docNameIndex.get(e.name)??0]?.description??``})),r=this.reRanker.reRank(e,n,t),i=new Map(r.map((e,t)=>[e.toolName,t]));b=b.slice().toSorted((e,t)=>(i.get(e.name)??0)-(i.get(t.name)??0))}this.queryCache.set(l,{results:b,vectorWeightAtCache:this.feedbackTracker.getVectorWeight(),cachedAtMs:Date.now()});let x=performance.now()-a;return this.qualityTracker.recordSearch(e,b.map(e=>e.name),b.map(e=>e.score),x),b}isCachedEntryFresh(e){let n=this.feedbackTracker.getVectorWeight();return Math.abs(n-e.vectorWeightAtCache)<=t}isSimpleQuery(e,t){let n=e.toLowerCase().replace(/[\s-]+/g,`_`);return!!(this.docNameIndex.has(n)||t.length===1)}quickPathSearch(e,t,n,r){let i=new Float64Array(this.docCount);for(let e of t)if(this.scoreToken(e,i),e.length>=3){let t=this.findPrefixMatches(e);for(let n of t)if(n!==e){let e=this.invertedIndex.get(n);e&&this.scorePostings(e,this.docCount,i,m)}}let a=this.trigramIndex.search(e,h),o=T;if(o>0)for(let[e,t]of a)t>0&&(i[e]+=t*o);let s=e.toLowerCase().replace(/[\s-]+/g,`_`);if(this.docNameIndex.has(s)){let e=this.docNameIndex.get(s);i[e]*=C}let c=r??new Set,l=[];for(let e=0;e<this.docCount;e++)if(i[e]>0){let t=this.docs[e];l.push({name:t.name,domain:t.domain,shortDescription:t.shortDescription,score:Math.round(i[e]*1e3)/1e3,isActive:c.has(t.name)})}return l.sort((e,t)=>t.score-e.score),l.slice(0,n)}applyRecencyBoost(e){if(w<=0||this.recencyTracker.size===0)return;let t=te;if(t<=0)return;let n=Date.now(),r=w;for(let[i,a]of this.recencyTracker){let o=n-a;if(o<0||o>t)continue;let s=this.docNameIndex.get(i);if(s===void 0||e[s]<=0)continue;let c=1+r*(1-o/t);e[s]*=c}}applyTierPenalty(e,t,n){let r=n?n===`full`?p:n===`workflow`?le:ce:b;if(r>=1||r<=0)return;let i=t&&t.size>0;for(let n=0;n<this.docCount;n++){if(e[n]<=0)continue;let a=this.docs[n].domain;a&&(!i||!t.has(a))&&(e[n]*=r,e[n]<=0&&r>0&&(e[n]=1e-6))}}getDomainSummary(){let e=new Map;for(let t of this.docs){let n=e.get(t.domain)??[];n.push(t.name),e.set(t.domain,n)}return Array.from(e.entries()).map(([e,t])=>({domain:e,count:t.length,tools:t})).toSorted((e,t)=>t.count-e.count)}scoreToken(e,t){let n=this.invertedIndex.get(e);n&&this.scorePostings(n,this.docCount,t,1)}findPrefixMatches(e){let t=this.sortedKeys,n=0,r=t.length;for(;n<r;){let i=n+r>>>1;t[i]<e?n=i+1:r=i}let i=[];for(;n<t.length&&t[n].startsWith(e);)i.push(t[n]),n++;return i}scorePostings(e,t,n,r){let i=e.length,a=Math.log((this.docCount-i+.5)/(i+.5)+1),o=f,s=c;for(let{docIndex:t,tf:i,weight:c}of e){let e=this.docs[t],l=1-o+o*(e.length/this.avgDocLength),u=i*(s+1)/(i+s*l);n[t]+=a*u*c*r}}async applyRRFFusion(e,t,n){let r=_,i=T,a=ke(n),o=H(this.trigramIndex.search(t,h)),s,c;if(l>0&&a.size>0){let e=[...a.entries()].find(([,e])=>e===0)?.[0];(e===void 0?0:n[e])>=l?(s=new Map,c=new Map):(s=await this.computeVectorCosineScores(t),c=H(s))}else s=await this.computeVectorCosineScores(t),c=H(s);let u=new Map;for(let[e,t]of c)u.set(this.docs[e].name,t);this.feedbackTracker.recordVectorRanking(u);let d=new Float64Array(this.docCount);for(let e=0;e<this.docCount;e++){let t=0,n=a.get(e);n!==void 0&&(t+=1/(r+n));let s=o.get(e);s!==void 0&&i>0&&(t+=i*(1/(r+s)));let l=c.get(e);l!==void 0&&this.feedbackTracker.getVectorWeight()>0&&(t+=this.feedbackTracker.getVectorWeight()*(1/(r+l))),d[e]=t}Ae(n,d)}async ensureToolEmbeddings(){if(this.toolEmbeddings||!this.embeddingEngine)return;let e=this.docs.map(e=>`${e.name.replace(/_/g,` `)}: ${e.description}`);this.toolEmbeddings=await this.embeddingEngine.embedBatch(e)}async computeVectorCosineScores(e){if(!this.embeddingEngine)return new Map;try{await this.ensureToolEmbeddings()}catch{return new Map}if(!this.toolEmbeddings)return new Map;let t;try{t=await this.embeddingEngine.embed(e)}catch{return new Map}let n=new Map;for(let e=0;e<this.toolEmbeddings.length;e++){let r=this.toolEmbeddings[e],i=0;for(let e=0;e<t.length;e++)i+=t[e]*r[e];i>0&&n.set(e,i)}return n}recordToolCallFeedback(e,t){for(this.feedbackTracker.recordToolCallFeedback(e,!!this.embeddingEngine),this.recencyTracker.delete(e),this.recencyTracker.set(e,Date.now());this.recencyTracker.size>g;){let e=this.recencyTracker.keys().next().value;if(e===void 0)break;this.recencyTracker.delete(e)}}associateLastSearch(e){this.qualityTracker.associateLastSearch(e)}getSearchQualityMetrics(){return this.qualityTracker.computeMetrics()}getSearchQualityTracker(){return this.qualityTracker}applyIntentBonusBand(e,t){if(t.size===0)return;let n=0;for(let t=0;t<this.docCount;t++)n=Math.max(n,e[t]);let r=0;for(let e of t.values())r=Math.max(r,e);if(r<=0)return;let i=Math.max(1,n+1),a=[...new Set([...t.values()].filter(e=>e>0))].toSorted((e,t)=>e-t),o=new Map;for(let e=0;e<a.length;e++)o.set(a[e],e+1);for(let[n,r]of t){if(r<=0)continue;let t=this.docNameIndex.get(n);if(t===void 0)continue;let a=o.get(r);a!==void 0&&(e[t]+=i*a)}}applyGraphExpansion(e){je({scores:e,docs:this.docs,affinityGraph:this.affinityGraph})}},Pe=e({buildDomainDescription:()=>$,buildSearchSignature:()=>Z,getActiveToolNames:()=>W,getBaseTier:()=>K,getCombinedTools:()=>J,getExtensionDomainMap:()=>q,getSearchEngine:()=>Q,getToolByName:()=>Y,getVisibleDomainsForTier:()=>G});function W(e){let t=new Set(e.selectedTools.map(e=>e.name));for(let n of e.activatedToolNames)t.add(n);return t}function G(e){let t=new Set(de(e.baseTier));for(let n of e.enabledDomains)t.add(n);for(let n of e.extensionToolsByName.values())t.add(n.domain);for(let n of W(e)){let r=e.extensionToolsByName.get(n)?.domain;if(r){t.add(r);continue}let i=D(n);i&&t.add(i)}return t}function K(e){return e.baseTier}function q(e){let t=new Map;for(let n of e.extensionToolsByName.values())t.set(n.name,n.domain);return t}async function J(e){await O();let t=new Map(A.map(e=>[e.name,e]));for(let n of e.extensionToolsByName.values())t.set(n.name,n.tool);return[...t.values()]}async function Y(e){return new Map((await J(e)).map(e=>[e.name,e]))}const X=new WeakMap;function Fe(){let e=new Map;for(let t of ue())if(t.sceneKeywords)for(let[n,r]of Object.entries(t.sceneKeywords))r.length>0&&e.set(n,r);return e}function Z(e){let t=[];for(let[n,r]of e.extensionToolsByName)t.push(`${n}:${r.domain}`);return t.sort(),[e.extensionWorkflowRuntimeById.size,t.join(`|`)].join(`::`)}async function Q(e){await O();let t=Z(e),r=X.get(e);if(r?.signature===t)return r.engine;let i=await J(e),a=q(e),o=new Map,s=new Map;for(let t of e.extensionToolsByName.values())s.set(t.name,1.12);e.extensionWorkflowRuntimeById.size>0&&(o.set(`workflow`,n),s.set(`run_extension_workflow`,1.35),s.set(`list_extension_workflows`,1.25));let c=new Ne(i,a,o,s,e.config.search,Fe());return c.extensionEtag=t,X.set(e,{signature:t,engine:c}),c}function $(e){let t={};for(let e of k())t[e.domain]=(t[e.domain]??0)+1;for(let n of e.extensionToolsByName.values())t[n.domain]=(t[n.domain]??0)+1;let n=k().length,r=e.extensionToolsByName.size;return`Search ${n+r} tools across ${Object.keys(t).length} capability domains. This includes built-in tools plus any loaded plugin/workflow tools (${r} currently loaded). In search-tier sessions, call this before assuming a capability is unavailable. Use activate_tools for exact matches, activate_domain for an entire domain. Domains: ${Object.entries(t).toSorted((e,t)=>t[1]-e[1]).map(([e,t])=>`${e} (${t})`).join(` | `)}. Query tip: before searching, distill your intent into key concepts (action verb + target + domain). Pass distilled keywords, not full sentences — the search engine works on token matching, not semantic understanding.`}export{Q as a,B as c,K as i,$ as n,Y as o,W as r,G as s,Pe as t};
@@ -1,2 +0,0 @@
1
- import{Jt as e,ga as t}from"./constants-DMv3svps.mjs";import{_ as n,b as r,d as i,m as a,t as o,u as s}from"./Win32API-DoP3MMHS.mjs";import{i as c}from"./NativeMemoryManager.utils-Bu8srMEF.mjs";import{randomUUID as l}from"node:crypto";var u=class{freezes=new Map;writeHistory=[];undoneStack=[];async writeValue(e,u,d,f){let p=BigInt(u.startsWith(`0x`)?u:`0x${u}`),{patternBytes:m}=c(d,f),h=Buffer.from(m),g=r(e,!0);try{let r=i(g,p,h.length),{oldProtect:o}=a(g,p,h.length,s.READWRITE);n(g,p,h),a(g,p,h.length,o);let c={id:l(),pid:e,address:`0x${p.toString(16).toUpperCase()}`,oldValue:Array.from(r),newValue:Array.from(h),timestamp:Date.now(),undone:!1};return this.writeHistory.push(c),this.undoneStack=[],this.writeHistory.length>t&&(this.writeHistory=this.writeHistory.slice(-t)),c}finally{o(g)}}async undo(){for(let e=this.writeHistory.length-1;e>=0;e--){let t=this.writeHistory[e];if(!t.undone){let e=BigInt(t.address),i=Buffer.from(t.oldValue),c=r(t.pid,!0);try{let{oldProtect:t}=a(c,e,i.length,s.READWRITE);n(c,e,i),a(c,e,i.length,t)}finally{o(c)}return t.undone=!0,this.undoneStack.push(t),t}}return null}async redo(){let e=this.undoneStack.pop();if(!e)return null;let t=BigInt(e.address),i=Buffer.from(e.newValue),c=r(e.pid,!0);try{let{oldProtect:e}=a(c,t,i.length,s.READWRITE);n(c,t,i),a(c,t,i.length,e)}finally{o(c)}return e.undone=!1,e}async freeze(t,i,u,d,f){let p=BigInt(i.startsWith(`0x`)?i:`0x${i}`),{patternBytes:m}=c(u,d),h=Buffer.from(m),g=f??e,_={id:l(),pid:t,address:`0x${p.toString(16).toUpperCase()}`,value:Array.from(h),valueType:d,intervalMs:g,isActive:!0};return _.timer=setInterval(()=>{try{let e=r(t,!0);try{let{oldProtect:t}=a(e,p,h.length,s.READWRITE);n(e,p,h),a(e,p,h.length,t)}finally{o(e)}}catch{_.isActive=!1,_.timer&&clearInterval(_.timer),this.freezes.delete(_.id)}},g),typeof _.timer.unref==`function`&&_.timer.unref(),this.freezes.set(_.id,_),_}async unfreeze(e){let t=this.freezes.get(e);return t?(t.timer&&clearInterval(t.timer),t.isActive=!1,this.freezes.delete(e),!0):!1}async unfreezeAll(){let e=0;for(let[t]of this.freezes)await this.unfreeze(t),e++;return e}listFreezes(){return Array.from(this.freezes.values()).map(({timer:e,...t})=>t)}async dumpMemory(e,t,n){let a=BigInt(t.startsWith(`0x`)?t:`0x${t}`),s=r(e,!1);try{return i(s,a,n)}finally{o(s)}}async dumpMemoryHex(e,t,n){let r=await this.dumpMemory(e,t,n),i=[],a=BigInt(t.startsWith(`0x`)?t:`0x${t}`);for(let e=0;e<r.length;e+=16){let t=a+BigInt(e),n=Array.from(r.subarray(e,Math.min(e+16,r.length))).map(e=>e.toString(16).padStart(2,`0`)).join(` `),o=Array.from(r.subarray(e,Math.min(e+16,r.length))).map(e=>e>=32&&e<=126?String.fromCharCode(e):`.`).join(``);i.push(`${t.toString(16).padStart(12,`0`)} ${n.padEnd(47)} |${o}|`)}return i.join(`
2
- `)}getWriteHistory(){return[...this.writeHistory]}};const d=new u;export{u as MemoryController,d as memoryController};
@@ -1 +0,0 @@
1
- import{Br as e,Gr as t,Hr as n,Vr as r,Xi as i,zr as a}from"./constants-DMv3svps.mjs";import{t as o}from"./ToolError-g3rjWzhx.mjs";import{r as s}from"./native-g095qhpK.mjs";import{t as c}from"./factory-BxNdBiZa.mjs";import{i as l}from"./NativeMemoryManager.utils-Bu8srMEF.mjs";import{n as u,t as d}from"./formatAddress-DAcw4Ckg.mjs";import{n as f,r as p,scanSessionManager as m,t as h}from"./MemoryScanSession-zfoVZJB0.mjs";var g=class{nmm;providerCache=null;get provider(){return this.providerCache||=c(),this.providerCache}set provider(e){this.providerCache=e}constructor(e){this.nmm=e}async firstScan(e,t,n){let i=performance.now(),s=n.valueType,c=p(s),u=n.alignment??f(s),h=n.maxResults??r;if(c===0)return this.patternFirstScan(e,t,s,n);let{patternBytes:g}=l(t,s===`pointer`?`uint64`:s);if(g.length===0)throw new o(`VALIDATION`,`Invalid pattern for type ${s}: "${t}"`);let _=Buffer.from(g),v=m.createSession(e,n),y=[],b=new Map,x=this.provider.openProcess(e,!1);try{let e=this.getFilteredRegions(x,n),t=e.length,r=0;for(let i of e){if(n.onProgress&&n.onProgress(r,t),r++,y.length>=h)break;let e=i.baseAddress,a=i.size,o=16*1024*1024;for(let t=0;t<a&&y.length<h;t+=o){let n=Math.min(o,a-t),r=e+BigInt(t),i;try{i=this.provider.readMemory(x,r,n).data}catch{break}if(u===c&&c>0){let e=this.getAlignStep(u),t=this.getAlignedChunkStart(r,e);for(;t<=i.length-c&&y.length<h;){let n=i.indexOf(_,t);if(n===-1)break;if(!this.isAlignedAddress(r+BigInt(n),e)){t=n+1;continue}let a=r+BigInt(n);y.push(a),b.set(a,Buffer.from(i.subarray(n,n+c))),t=n+e}}else{let e=this.getAlignStep(u),t=this.getAlignedChunkStart(r,e);for(let n=t;n<=i.length-c;n+=e)if(Buffer.compare(i.subarray(n,n+c),_)===0){let e=r+BigInt(n);if(y.push(e),b.set(e,Buffer.from(i.subarray(n,n+c))),y.length>=h)break}}}}}finally{this.provider.closeProcess(x)}m.updateSession(v,y,b);let S=`${(performance.now()-i).toFixed(1)}ms`,C=y.slice(0,a).map(d);return{sessionId:v,matchCount:y.length,scanNumber:1,addresses:C,totalMatches:y.length,truncated:y.length>a,elapsed:S}}async nextScan(e,t,n,r){let i=performance.now(),s=m.getSession(e),{pid:c,valueType:u,addresses:f,previousValues:g}=s,_=p(u);if(_===0)throw new o(`VALIDATION`,`Next-scan is not supported for variable-length types (hex/string)`);let v=null,y=null;if(n!==void 0){let{patternBytes:e}=l(n,u===`pointer`?`uint64`:u);v=Buffer.from(e)}if(r!==void 0){let{patternBytes:e}=l(r,u===`pointer`?`uint64`:u);y=Buffer.from(e)}let b=[],x=new Map,S=this.provider.openProcess(c,!1);try{for(let e of f){let n;try{n=this.provider.readMemory(S,e,_).data}catch{continue}let r=g.get(e)??null;h(n,r,v,y,t,u)&&(b.push(e),x.set(e,Buffer.from(n)))}}finally{this.provider.closeProcess(S)}m.updateSession(e,b,x);let C=`${(performance.now()-i).toFixed(1)}ms`,w=b.slice(0,a).map(d);return{sessionId:e,matchCount:b.length,scanNumber:s.scanCount,addresses:w,totalMatches:b.length,truncated:b.length>a,elapsed:C}}async unknownInitialScan(e,n){let r=performance.now(),i=n.valueType,s=p(i),c=n.alignment??f(i),l=n.maxResults??t;if(s===0)throw new o(`VALIDATION`,`Unknown initial scan is not supported for variable-length types`);let u=m.createSession(e,n),h=[],g=new Map,_=this.provider.openProcess(e,!1);try{let e=this.getFilteredRegions(_,n),t=e.length,r=0;for(let i of e){if(n.onProgress&&n.onProgress(r,t),r++,h.length>=l)break;let e=i.baseAddress,a=i.size,o=16*1024*1024;for(let t=0;t<a&&h.length<l;t+=o){let n=Math.min(o,a-t),r=e+BigInt(t),i;try{i=this.provider.readMemory(_,r,n).data}catch{break}let u=this.getAlignStep(c),d=this.getAlignedChunkStart(r,u);for(let e=d;e<=i.length-s;e+=u){let t=r+BigInt(e);if(h.push(t),g.set(t,Buffer.from(i.subarray(e,e+s))),h.length>=l)break}}}}finally{this.provider.closeProcess(_)}m.updateSession(u,h,g);let v=`${(performance.now()-r).toFixed(1)}ms`;return{sessionId:u,matchCount:h.length,scanNumber:1,addresses:h.slice(0,a).map(d),totalMatches:h.length,truncated:h.length>a,elapsed:v}}async pointerScan(e,t,r={}){let i=performance.now(),o=r.maxResults??n,s=u(t),c={valueType:`pointer`,alignment:8,regionFilter:{moduleOnly:r.moduleOnly}},l=m.createSession(e,c),f=[],p=this.provider.openProcess(e,!1);try{let e=this.getFilteredRegions(p,c);for(let t of e){if(f.length>=o)break;let e=t.baseAddress,n=t.size,r=16*1024*1024;for(let t=0;t<n&&f.length<o;t+=r){let i=Math.min(r,n-t),a=e+BigInt(t),c;try{c=this.provider.readMemory(p,a,i).data}catch{break}for(let e=0;e<=c.length-8;e+=8){let t=c.readBigUInt64LE(e);if(Number(t>s?t-s:s-t)<=4096){let n=a+BigInt(e),r=t>=s?Number(t-s):-Number(s-t);if(f.push({address:d(n),value:d(t),offsetFromTarget:r}),f.length>=o)break}}}}}finally{this.provider.closeProcess(p)}let h=f.map(e=>u(e.address));m.updateSession(l,h,new Map);let g=`${(performance.now()-i).toFixed(1)}ms`;return{sessionId:l,pointers:f.slice(0,a),totalFound:f.length,elapsed:g}}async groupScan(t,n,i){let s=performance.now();if(n.length===0)throw new o(`VALIDATION`,`Group scan requires at least one value pattern`);let c=Math.max(...n.map(e=>e.offset+p(e.type)));if(c>e)throw new o(`VALIDATION`,`Group pattern too large: ${c} bytes (max ${e})`);let u=Array.from({length:c},()=>0),f=Array.from({length:c},()=>0);for(let e of n){let t=e.type===`pointer`?`uint64`:e.type,{patternBytes:n,mask:r}=l(e.value,t);for(let t=0;t<n.length;t++)u[e.offset+t]=n[t],f[e.offset+t]=r[t]}let h=i?.alignment??4,g=i?.maxResults??r,_={valueType:`int32`,alignment:h},v=m.createSession(t,_),y=[],b=this.provider.openProcess(t,!1);try{let e=this.getFilteredRegions(b,_);for(let t of e){if(y.length>=g)break;let e=t.baseAddress,n=t.size,r=16*1024*1024,i=c-1;for(let t=0;t<n&&y.length<g;t+=r){let a=Math.min(r+i,n-t),o=e+BigInt(t),s;try{s=this.provider.readMemory(b,o,a).data}catch{break}let l=this.getAlignStep(h),d=this.getAlignedChunkStart(o,l);for(let e=d;e<=s.length-c;e+=l){let t=!0;for(let n=0;n<c;n++)if(f[n]===1&&s[e+n]!==u[n]){t=!1;break}if(t){let t=o+BigInt(e);if(y.push(t),y.length>=g)break}}}}}finally{this.provider.closeProcess(b)}m.updateSession(v,y,new Map);let x=`${(performance.now()-s).toFixed(1)}ms`;return{sessionId:v,matchCount:y.length,scanNumber:1,addresses:y.slice(0,a).map(d),totalMatches:y.length,truncated:y.length>a,elapsed:x}}getAlignStep(e){return e>0?e:1}getAlignedChunkStart(e,t){let n=BigInt(t),r=e%n;return r===0n?0:Number(n-r)}isAlignedAddress(e,t){return e%BigInt(t)===0n}async patternFirstScan(e,t,n,i){let s=performance.now(),c=n===`hex`?`hex`:`string`,l=await this.nmm.scanMemory(e,t,c);if(!l.success)throw new o(`RUNTIME`,l.error??`Scan failed`);let f=m.createSession(e,i),p=i.maxResults??r,h=l.addresses.slice(0,p).map(u);m.updateSession(f,h,new Map);let g=`${(performance.now()-s).toFixed(1)}ms`;return{sessionId:f,matchCount:h.length,scanNumber:1,addresses:h.slice(0,a).map(d),totalMatches:l.addresses.length,truncated:h.length>a,elapsed:g}}getFilteredRegions(e,t){let n=[],r=0n,a=i,o=t.regionFilter;for(;r<a;){let t=this.provider.queryRegion(e,r);if(!t)break;let i=t.size;if(t.isReadable&&i>0&&i<=2**53-1){let e=!0;o?.writable&&!t.isWritable&&(e=!1),o?.executable&&!t.isExecutable&&(e=!1),o?.moduleOnly&&t.type!==`image`&&(e=!1),e&&n.push({baseAddress:t.baseAddress,size:i})}r=t.baseAddress+BigInt(t.size)}return n}};const _=new g(s);export{g as MemoryScanner,_ as memoryScanner};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-CCikqqvj.mjs";import{a as t,b as n,d as r,i,n as a,s as o,t as s}from"./Win32API-DoP3MMHS.mjs";import{promises as c}from"node:fs";const l={CNT_CODE:32,CNT_INITIALIZED_DATA:64,CNT_UNINITIALIZED_DATA:128,MEM_EXECUTE:536870912,MEM_READ:1073741824,MEM_WRITE:2147483648},u={EXPORT:0,IMPORT:1,RESOURCE:2,EXCEPTION:3,IAT:12,DELAY_IMPORT:13};var d=class{async parseHeaders(e,t){let i=BigInt(t),a=n(e);try{let e=r(a,i,64),t=e.readUInt16LE(0);if(t!==23117)throw Error(`Invalid DOS header: expected 0x5A4D, got 0x${t.toString(16)}`);let n=e.readUInt32LE(60),o=r(a,i+BigInt(n),264),s=o.readUInt32LE(0);if(s!==17744)throw Error(`Invalid PE signature: expected 0x4550, got 0x${s.toString(16)}`);let c=o.readUInt16LE(4),l=o.readUInt16LE(6),u=o.readUInt32LE(8),d=o.readUInt16LE(22),f=o.readUInt16LE(24),p=f===523,m,h,g,_;return p?(h=o.readUInt32LE(40),m=o.readBigUInt64LE(48),g=o.readUInt32LE(80),_=o.readUInt32LE(132)):(h=o.readUInt32LE(40),m=BigInt(o.readUInt32LE(52)),g=o.readUInt32LE(80),_=o.readUInt32LE(116)),{dosHeader:{e_magic:t,e_lfanew:n},ntSignature:s,fileHeader:{machine:c,numberOfSections:l,timeDateStamp:u,characteristics:d},optionalHeader:{magic:f,imageBase:`0x${m.toString(16)}`,entryPoint:`0x${h.toString(16)}`,sizeOfImage:g,numberOfRvaAndSizes:_}}}finally{s(a)}}async listSections(e,t){let i=BigInt(t),a=n(e);try{let e=await this.readCoreHeaders(a,i),t=[];for(let n=0;n<e.numSections;n++){let o=e.firstSectionOffset+n*40,s=r(a,i+BigInt(o),40),c=s.indexOf(0),u=s.subarray(0,c>0&&c<=8?c:8).toString(`ascii`),d=s.readUInt32LE(8),f=s.readUInt32LE(12),p=s.readUInt32LE(16),m=s.readUInt32LE(36);t.push({name:u,virtualAddress:`0x${f.toString(16)}`,virtualSize:d,rawSize:p,characteristics:m,isExecutable:(m&l.MEM_EXECUTE)!==0,isWritable:(m&l.MEM_WRITE)!==0,isReadable:(m&l.MEM_READ)!==0})}return t}finally{s(a)}}async parseImports(e,t){let i=BigInt(t),a=n(e);try{let e=await this.readCoreHeaders(a,i),t=e.dataDirectories[u.IMPORT];if(!t||t.rva===0)return[];let n=[],o=t.rva;for(let t=0;t<500;t++){let t=r(a,i+BigInt(o),20),s=t.readUInt32LE(12);if(s===0)break;let c=r(a,i+BigInt(s),256),l=c.indexOf(0),u=c.subarray(0,l>0?l:256).toString(`ascii`),d=t.readUInt32LE(0)||t.readUInt32LE(16),f=this.readThunkArray(a,i,d,e.isPE32Plus);n.push({dllName:u,functions:f}),o+=20}return n}finally{s(a)}}async parseExports(e,t){let i=BigInt(t),a=n(e);try{let e=(await this.readCoreHeaders(a,i)).dataDirectories[u.EXPORT];if(!e||e.rva===0)return[];let t=r(a,i+BigInt(e.rva),40),n=t.readUInt32LE(24),o=t.readUInt32LE(28),s=t.readUInt32LE(32),c=t.readUInt32LE(36),l=t.readUInt32LE(16),d=[],f=r(a,i+BigInt(s),n*4),p=r(a,i+BigInt(c),n*2);for(let t=0;t<Math.min(n,2e3);t++){let n=f.readUInt32LE(t*4),s=p.readUInt16LE(t*2),c=r(a,i+BigInt(n),256),u=c.indexOf(0),m=c.subarray(0,u>0?u:256).toString(`ascii`),h=r(a,i+BigInt(o+s*4),4).readUInt32LE(0),g=null;if(h>=e.rva&&h<e.rva+e.size){let e=r(a,i+BigInt(h),256),t=e.indexOf(0);g=e.subarray(0,t>0?t:256).toString(`ascii`)}d.push({name:m,ordinal:l+s,rva:`0x${h.toString(16)}`,forwardedTo:g})}return d}finally{s(a)}}async detectInlineHooks(t,i){let a=n(t),o=[];try{let n=this.enumerateModulesInternal(a),s=i?n.filter(e=>e.name.toLowerCase().includes(i.toLowerCase())):n;for(let n of s)try{let e=await c.readFile(n.path),i=await this.parseExports(t,n.base);for(let t of i){let i=parseInt(t.rva,16);if(i===0||t.forwardedTo)continue;let s=r(a,BigInt(n.base)+BigInt(i),16),c=this.rvaToFileOffset(e,i);if(c<0||c+16>e.length)continue;let l=e.subarray(c,c+16);if(!s.equals(l)){let e=this.classifyHook(s),r=this.decodeJumpTarget(s,BigInt(n.base)+BigInt(i));o.push({address:`0x${(BigInt(n.base)+BigInt(i)).toString(16)}`,moduleName:n.name,functionName:t.name,originalBytes:Array.from(l),currentBytes:Array.from(s),hookType:e,jumpTarget:r})}}}catch(t){e.debug(`Hook check skipped for ${n.name}: ${t}`)}}finally{s(a)}return o}async analyzeSections(e,t){let n=await this.listSections(e,t),r=[];for(let e of n)e.isReadable&&e.isWritable&&e.isExecutable?r.push({sectionName:e.name,anomalyType:`rwx`,severity:`high`,details:`Section ${e.name} has Read+Write+Execute permissions — unusual and potentially malicious`}):e.isWritable&&e.isExecutable?r.push({sectionName:e.name,anomalyType:`writable_code`,severity:`high`,details:`Section ${e.name} is writable and executable — code may be self-modifying or packed`}):e.isExecutable&&!e.name.startsWith(`.text`)&&!e.name.startsWith(`.code`)&&(e.characteristics&l.CNT_INITIALIZED_DATA)!==0&&r.push({sectionName:e.name,anomalyType:`executable_data`,severity:`medium`,details:`Data section ${e.name} has execute permission`});return r}async readCoreHeaders(e,t){let n=r(e,t,64).readUInt32LE(60),i=r(e,t+BigInt(n),264),a=i.readUInt16LE(6),o=i.readUInt16LE(20),s=i.readUInt16LE(24)===523,c=s?i.readUInt32LE(132):i.readUInt32LE(116),l=s?136:120,u=[];for(let e=0;e<Math.min(c,16);e++){let t=l+e*8;t+8<=i.length&&u.push({rva:i.readUInt32LE(t),size:i.readUInt32LE(t+4)})}return{numSections:a,isPE32Plus:s,firstSectionOffset:n+4+20+o,dataDirectories:u}}readThunkArray(e,t,n,i){let a=i?8:4,o=[],s=i?9223372036854775808n:2147483648n;for(let c=0;c<2e3;c++){let l=r(e,t+BigInt(n+c*a),a),u=i?l.readBigUInt64LE(0):BigInt(l.readUInt32LE(0));if(u===0n)break;if((u&s)!==0n)o.push({name:`Ordinal#${Number(u&65535n)}`,ordinal:Number(u&65535n),hint:0,thunkRva:`0x${(n+c*a).toString(16)}`});else{let i=Number(u),s=r(e,t+BigInt(i),258),l=s.readUInt16LE(0),d=s.indexOf(0,2),f=s.subarray(2,d>2?d:258).toString(`ascii`);o.push({name:f,ordinal:0,hint:l,thunkRva:`0x${(n+c*a).toString(16)}`})}}return o}enumerateModulesInternal(n){let r=[];try{let{modules:e,count:s}=a(n);for(let a=0;a<s;a++){let s=e[a],c=i(n,s),l=o(n,s),u=t(n,s)??c;l.success&&r.push({name:c,base:`0x${l.info.lpBaseOfDll.toString(16)}`,path:u,size:l.info.SizeOfImage})}}catch(t){e.debug(`Module enumeration failed: ${t}`)}return r}rvaToFileOffset(e,t){let n=e.readUInt32LE(60),r=e.readUInt16LE(n+6),i=e.readUInt16LE(n+20),a=n+24+i;for(let n=0;n<r;n++){let r=a+n*40;if(r+40>e.length)break;let i=e.readUInt32LE(r+12),o=e.readUInt32LE(r+8),s=e.readUInt32LE(r+20);if(t>=i&&t<i+o)return s+(t-i)}return-1}classifyHook(e){return e[0]===233?`jmp_rel32`:e[0]===255&&e[1]===37?`jmp_abs64`:e[0]===104&&e[5]===195?`push_ret`:`unknown`}decodeJumpTarget(e,t){if(e[0]===233){let n=e.readInt32LE(1);return`0x${(t+5n+BigInt(n)).toString(16)}`}return e[0]===255&&e[1]===37&&e.length>=14?`0x${e.readBigUInt64LE(6).toString(16)}`:e[0]===104?`0x${e.readUInt32LE(1).toString(16)}`:`0x0`}};const f=new d;export{d as PEAnalyzer,f as peAnalyzer};
@@ -1 +0,0 @@
1
- import{Xi as e,ar as t,ir as n,or as r,sr as i}from"./constants-DMv3svps.mjs";import{r as a}from"./native-g095qhpK.mjs";import{t as o}from"./factory-BxNdBiZa.mjs";import{n as s,t as c}from"./formatAddress-DAcw4Ckg.mjs";import{randomUUID as l}from"node:crypto";var u=class{providerCache=null;get provider(){return this.providerCache||=o(),this.providerCache}set provider(e){this.providerCache=e}async scan(e,i,a){let o=performance.now(),l=Math.min(a?.maxDepth??4,n),u=a?.maxOffset??t,d=a?.maxResults??r,f=a?.alignment??8,p=a?.staticOnly??!1,m=s(i),h=this.provider.openProcess(e,!1);try{let t=await this.getModuleMap(e),n=[],r=new Set([m]);for(let e=0;e<l&&r.size!==0;e++){let e=this.scanLevel(h,r,u,f,a?.modules?{modules:a.modules}:void 0);if(e.length===0)break;n.push(e),r=new Set;for(let t of e)if(r.add(t.pointerAddress),r.size>5e4)break}let i=this.buildChains(n,m,t,d,p),s=`${(performance.now()-o).toFixed(1)}ms`;return{pid:e,targetAddress:c(m),chains:i,totalFound:i.length,maxDepth:l,elapsed:s}}finally{this.provider.closeProcess(h)}}async validateChain(e,t){let n=this.provider.openProcess(e,!1);try{let e=s(t.baseAddress);for(let r=0;r<t.links.length;r++){let i=t.links[r],a;try{a=this.provider.readMemory(n,e,8).data.readBigUInt64LE(0)}catch{return{chainId:t.id,isValid:!1,resolvedAddress:null,expectedAddress:t.targetAddress,brokenAt:r}}e=a+BigInt(i.offset)}let r=c(e),i=s(t.targetAddress),a=e===i;return{chainId:t.id,isValid:a,resolvedAddress:r,expectedAddress:t.targetAddress,brokenAt:a?void 0:t.links.length-1}}finally{this.provider.closeProcess(n)}}async validateChains(e,t){let n=[];for(let r of t)n.push(await this.validateChain(e,r));return n}async resolveChain(e,t){let n=this.provider.openProcess(e,!1);try{let e=s(t.baseAddress);for(let r of t.links){let t;try{t=this.provider.readMemory(n,e,8).data.readBigUInt64LE(0)}catch{return null}e=t+BigInt(r.offset)}return c(e)}finally{this.provider.closeProcess(n)}}exportChains(e){return JSON.stringify(e,null,2)}importChains(e){let t=JSON.parse(e);if(!Array.isArray(t))throw Error(`Invalid chain data: expected array`);return t}async getModuleMap(e){let t=new Map;try{let n=await a.enumerateModules(e);if(n.success&&n.modules)for(let e of n.modules){let n=s(e.baseAddress);t.set(e.name.toLowerCase(),{name:e.name,base:n,size:e.size})}}catch{}return t}resolveToModule(e,t){for(let n of t.values())if(e>=n.base&&e<n.base+BigInt(n.size))return{module:n.name,offset:Number(e-n.base)};return null}scanLevel(t,n,r,a,o){let s=[],c=i,l=Array.from(n).toSorted((e,t)=>e<t?-1:+(e>t));if(l.length===0)return s;let u=BigInt(r),d=l[0]-u,f=l[l.length-1]+u,p=0n,m=e;for(;p<m;){let e=this.provider.queryRegion(t,p);if(!e)break;let n=e.size;if(e.isReadable&&n>0&&n<=2**53-1){let i=e.baseAddress;for(let e=0;e<n&&s.length<1e5;e+=c){let o=Math.min(c,n-e),p=i+BigInt(e),m;try{m=this.provider.readMemory(t,p,o).data}catch{break}for(let e=0;e<=m.length-8;e+=a){let t=m.readBigUInt64LE(e);if(t<d||t>f)continue;let n=t-u,i=t+u,a=0,o=l.length;for(;a<o;){let e=a+o>>>1;l[e]<n?a=e+1:o=e}for(let n=a;n<l.length&&l[n]<=i;n++){let i=l[n];if(Number(t>i?t-i:i-t)<=r){let n=p+BigInt(e),r=Number(i-t);s.push({pointerAddress:n,pointsTo:t,offset:r});break}}}}}p=e.baseAddress+BigInt(e.size)}return s}buildChains(e,n,r,i,a){if(e.length===0)return[];let o=[],s=c(n);for(let n=0;n<e.length&&o.length<i;n++){let u=e[n];if(n===0)for(let e of u){if(o.length>=i)break;let t=c(e.pointerAddress),n=this.resolveToModule(e.pointerAddress,r),u=n!==null;if(a&&!u)continue;let d={address:t,module:n?.module,moduleOffset:n?.offset,offset:e.offset};o.push({id:l(),links:[d],targetAddress:s,baseAddress:t,isStatic:u,depth:1,lastValidated:Date.now(),isValid:!0})}else{let d=e[n-1],f=new Map;for(let e of d)f.set(e.pointerAddress,e);let p=BigInt(t);for(let e of u){if(o.length>=i)break;let t;if(t=f.get(e.pointsTo),!t){for(let n of d)if((e.pointsTo>n.pointerAddress?e.pointsTo-n.pointerAddress:n.pointerAddress-e.pointsTo)<=p){t=n;break}}if(!t)continue;let n=c(e.pointerAddress),u=this.resolveToModule(e.pointerAddress,r),m=u!==null;if(a&&!m)continue;let h=[{address:n,module:u?.module,moduleOffset:u?.offset,offset:Number(t.pointerAddress-e.pointsTo)},{address:c(t.pointerAddress),offset:t.offset}];o.push({id:l(),links:h,targetAddress:s,baseAddress:n,isStatic:m,depth:h.length,lastValidated:Date.now(),isValid:!0})}}}return o.sort((e,t)=>e.isStatic===t.isStatic?e.depth-t.depth:e.isStatic?-1:1),o.slice(0,i)}};const d=new u;export{u as PointerChainEngine,d as pointerChainEngine};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-CCikqqvj.mjs";import{Ht as t}from"./constants-DMv3svps.mjs";const n=new class{processes=new Set;register(e){e&&(this.processes.add(e),`kill`in e?e.once(`close`,()=>this.unregister(e)):`terminate`in e&&(typeof e.once==`function`?e.once(`exit`,()=>this.unregister(e)):typeof e.on==`function`&&e.on(`exit`,()=>this.unregister(e))))}unregister(e){e&&this.processes.delete(e)}async terminateAll(){if(this.processes.size===0)return;e.debug(`[ProcessRegistry] Attempting to terminate ${this.processes.size} active processes/workers...`);let n=[];for(let r of this.processes)`terminate`in r?n.push(r.terminate().then(()=>{this.processes.delete(r)}).catch(t=>{e.warn(`[ProcessRegistry] Error terminating worker: ${t.message}`)})):`kill`in r&&n.push(new Promise(n=>{if(r.killed||r.exitCode!==null||r.signalCode!==null)return this.processes.delete(r),n();r.kill(`SIGTERM`);let i=!1,a=()=>{i||(i=!0,this.processes.delete(r),n())};r.once(`exit`,a),r.once(`close`,a),setTimeout(()=>{if(!i&&!r.killed&&r.exitCode===null){e.debug(`[ProcessRegistry] Force killing child process PID ${r.pid}`);try{r.kill(`SIGKILL`)}catch{}a()}},t).unref()}));await Promise.race([Promise.all(n),new Promise(e=>setTimeout(e,t+1e3).unref())]),this.processes.clear(),e.debug(`[ProcessRegistry] Termination sweep complete.`)}};export{n as t};
@@ -1,2 +0,0 @@
1
- import{t as e}from"./chunk-88NL7fhV.mjs";var t=e({ReverseEvidenceGraph:()=>i});let n=1;function r(e){return`${e}-${n++}`}var i=class{nodes=new Map;edges=new Map;eventBus;isDirty=!1;mutationSeq=0;lastPersistedSeq=0;persistNotifier;setEventBus(e){this.eventBus=e}setPersistNotifier(e){this.persistNotifier=e}markDirty(){this.isDirty=!0,this.mutationSeq++,this.persistNotifier?.()}commit(){this.isDirty&&this.eventBus&&(this.isDirty=!1,this.eventBus.emit(`evidence:updated`,{timestamp:new Date().toISOString(),reason:`Tool execution committed changes`}))}addNode(e,t,n={}){let i={id:r(e),type:e,label:t,metadata:n,createdAt:Date.now()};return this.nodes.set(i.id,i),this.markDirty(),i}addEdge(e,t,n,i){if(!this.nodes.has(e))throw Error(`Source node "${e}" not found`);if(!this.nodes.has(t))throw Error(`Target node "${t}" not found`);let a={id:r(`edge`),source:e,target:t,type:n,metadata:i};return this.edges.set(a.id,a),this.markDirty(),a}getNode(e){return this.nodes.get(e)}removeNode(e){if(!this.nodes.has(e))return!1;this.nodes.delete(e);for(let[t,n]of this.edges)(n.source===e||n.target===e)&&this.edges.delete(t);return this.markDirty(),!0}getEdgesFrom(e){return[...this.edges.values()].filter(t=>t.source===e)}getEdgesTo(e){return[...this.edges.values()].filter(t=>t.target===e)}get nodeCount(){return this.nodes.size}get edgeCount(){return this.edges.size}getEvidenceChain(e,t=`forward`){if(!this.nodes.get(e))return[];let n=new Set,r=[e],i=[];for(;r.length>0;){let e=r.shift();if(n.has(e))continue;n.add(e);let a=this.nodes.get(e);a&&i.push(a);let o=t===`forward`?this.getEdgesFrom(e):this.getEdgesTo(e);for(let e of o){let i=t===`forward`?e.target:e.source;n.has(i)||r.push(i)}}return i}queryByUrl(e){let t=[...this.nodes.values()].filter(t=>t.type===`request`&&typeof t.metadata.url==`string`||typeof t.metadata.url==`string`?t.metadata.url.includes(e):!1),n=new Set;for(let e of t){for(let t of this.getEvidenceChain(e.id,`forward`))n.add(t.id);for(let t of this.getEvidenceChain(e.id,`backward`))n.add(t.id)}return[...n].map(e=>this.nodes.get(e)).filter(Boolean)}queryByFunction(e){let t=[...this.nodes.values()].filter(t=>t.type===`function`&&typeof t.metadata.functionName==`string`?t.metadata.functionName.includes(e):!!(t.label.includes(e)&&(t.type===`function`||t.type===`breakpoint-hook`))),n=new Set;for(let e of t){for(let t of this.getEvidenceChain(e.id,`forward`))n.add(t.id);for(let t of this.getEvidenceChain(e.id,`backward`))n.add(t.id)}return[...n].map(e=>this.nodes.get(e)).filter(Boolean)}queryByScriptId(e){let t=[...this.nodes.values()].filter(t=>t.type===`script`&&t.metadata.scriptId===e),n=new Set;for(let e of t){for(let t of this.getEvidenceChain(e.id,`forward`))n.add(t.id);for(let t of this.getEvidenceChain(e.id,`backward`))n.add(t.id)}return[...n].map(e=>this.nodes.get(e)).filter(Boolean)}exportJson(){return{version:1,nodes:[...this.nodes.values()],edges:[...this.edges.values()],exportedAt:new Date().toISOString()}}exportMarkdown(){let e=[];e.push(`# Reverse Evidence Graph Report`),e.push(``),e.push(`**Exported:** ${new Date().toISOString()}`),e.push(`**Nodes:** ${this.nodes.size} | **Edges:** ${this.edges.size}`),e.push(``);let t=new Map;for(let e of this.nodes.values()){let n=t.get(e.type)??[];n.push(e),t.set(e.type,n)}for(let n of[`request`,`initiator-stack`,`script`,`function`,`breakpoint-hook`,`captured-data`,`replay-artifact`,`v8-heap-object`,`v8-hidden-class`,`network-request`,`network-response`,`canvas-scene-node`,`canvas-render-node`,`skia-draw-call`,`syscall-event`,`mojo-message`,`mojo-interface`,`binary-symbol`,`binary-function`,`binary-module`,`proto-message`,`proto-state`]){let r=t.get(n);if(!(!r||r.length===0)){e.push(`## ${n} (${r.length})`),e.push(``);for(let t of r){e.push(`### ${t.label}`),e.push(`- **ID:** \`${t.id}\``),e.push(`- **Created:** ${new Date(t.createdAt).toISOString()}`);let n=Object.keys(t.metadata);if(n.length>0)for(let r of n){let n=t.metadata[r],i=typeof n==`string`?n:JSON.stringify(n);e.push(`- **${r}:** ${i}`)}let r=this.getEdgesFrom(t.id),i=this.getEdgesTo(t.id);r.length>0&&e.push(`- **→ Out:** ${r.map(e=>`${e.type} → \`${e.target}\``).join(`, `)}`),i.length>0&&e.push(`- **← In:** ${i.map(e=>`\`${e.source}\` ${e.type} →`).join(`, `)}`),e.push(``)}}}return e.join(`
2
- `)}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(),graph:this.exportJson()}}restoreSnapshot(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion!==1||!t.graph)return;let{nodes:n,edges:r}=t.graph;this.nodes.clear(),this.edges.clear();for(let e of n)this.nodes.set(e.id,e);for(let e of r)this.edges.set(e.id,e);this.mutationSeq=n.length+r.length,this.lastPersistedSeq=this.mutationSeq,this.isDirty=!1}};export{t};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-CCikqqvj.mjs";import{n as t}from"./ToolCatalog-DgmQXdsm.mjs";const n={endpoint:null,selectedIndex:null,selectedUrl:null,selectedTitle:null,selectedTargetId:null,browserPid:null,rendererPid:null,attachedAt:null};var r=class{dirty=!1;persistedRevision=0;revision=0;pendingActivatedDomains=new Set;pendingDomainTtls=new Map;browserAttach={...n};toolCoverage=new Map;markPersisted(){this.persistedRevision=this.revision,this.dirty=!1}isPersistDirty(){return this.dirty||this.revision!==this.persistedRevision}exportSnapshot(){return{schemaVersion:1,savedAt:new Date().toISOString(),activatedDomains:[...this.pendingActivatedDomains].toSorted(),domainTtls:Object.fromEntries([...this.pendingDomainTtls.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,{ttlMinutes:t.ttlMinutes,toolNames:[...t.toolNames]}])),browserAttach:{...this.browserAttach},toolCoverage:Object.fromEntries([...this.toolCoverage.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,{...t,lastArgsKeys:[...t.lastArgsKeys]}]))}}restoreSnapshot(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion!==1)return;if(this.pendingActivatedDomains=new Set(Array.isArray(t.activatedDomains)?t.activatedDomains.filter(e=>typeof e==`string`):[]),this.pendingDomainTtls=new Map,t.domainTtls&&typeof t.domainTtls==`object`)for(let[e,n]of Object.entries(t.domainTtls)){if(!n||typeof n!=`object`)continue;let t=n,r=Number(t.ttlMinutes),i=Array.isArray(t.toolNames)?t.toolNames.filter(e=>typeof e==`string`):[];Number.isFinite(r)&&this.pendingDomainTtls.set(e,{ttlMinutes:r,toolNames:i})}let r=t.browserAttach;if(this.browserAttach=r&&typeof r==`object`?{endpoint:typeof r.endpoint==`string`?r.endpoint:null,selectedIndex:typeof r.selectedIndex==`number`&&Number.isInteger(r.selectedIndex)?r.selectedIndex:null,selectedUrl:typeof r.selectedUrl==`string`?r.selectedUrl:null,selectedTitle:typeof r.selectedTitle==`string`?r.selectedTitle:null,selectedTargetId:typeof r.selectedTargetId==`string`?r.selectedTargetId:null,browserPid:typeof r.browserPid==`number`&&Number.isInteger(r.browserPid)?r.browserPid:null,rendererPid:typeof r.rendererPid==`number`&&Number.isInteger(r.rendererPid)?r.rendererPid:null,attachedAt:typeof r.attachedAt==`string`?r.attachedAt:null}:{...n},this.toolCoverage.clear(),t.toolCoverage&&typeof t.toolCoverage==`object`)for(let[e,n]of Object.entries(t.toolCoverage)){if(!n||typeof n!=`object`)continue;let t=n;this.toolCoverage.set(e,{count:typeof t.count==`number`&&Number.isFinite(t.count)&&t.count>=0?Math.trunc(t.count):0,lastCalledAt:typeof t.lastCalledAt==`string`?t.lastCalledAt:null,lastArgsKeys:Array.isArray(t.lastArgsKeys)?t.lastArgsKeys.filter(e=>typeof e==`string`):[]})}this.revision+=1,this.persistedRevision=this.revision,this.dirty=!1}noteDirty(){this.revision+=1,this.dirty=!0}setPendingDomainActivation(e,t,n){this.pendingActivatedDomains.add(e),this.pendingDomainTtls.set(e,{ttlMinutes:t,toolNames:[...n]}),this.noteDirty()}clearPendingDomainActivation(e){let t=this.pendingActivatedDomains.delete(e),n=this.pendingDomainTtls.delete(e);(t||n)&&this.noteDirty()}getPendingActivatedDomains(){return[...this.pendingActivatedDomains]}getPendingDomainTtl(e){return this.pendingDomainTtls.get(e)??null}setBrowserAttach(e){this.browserAttach={...this.browserAttach,...e},this.noteDirty()}clearBrowserAttach(){this.browserAttach={...n},this.noteDirty()}getBrowserAttach(){return{...this.browserAttach}}recordToolCall(e,t){let n={count:(this.toolCoverage.get(e)?.count??0)+1,lastCalledAt:new Date().toISOString(),lastArgsKeys:Object.keys(t).filter(e=>e!==`_meta`).toSorted()};this.toolCoverage.set(e,n),this.noteDirty()}getCoverageSummary(e){let n=Object.fromEntries([...this.toolCoverage.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,{...t,lastArgsKeys:[...t.lastArgsKeys]}])),r=new Set([...t.map(e=>e.name),...e.selectedTools.map(e=>e.name),...e.activatedToolNames,...e.extensionToolsByName.keys(),...e.metaToolsByName.keys()]),i=[...this.toolCoverage.keys()].filter(e=>!r.has(e)).toSorted((e,t)=>e.localeCompare(t)),a=[...r].filter(e=>!this.toolCoverage.has(e)).toSorted((e,t)=>e.localeCompare(t));return{called:n,calledCount:this.toolCoverage.size,uncataloguedCalls:i,uncataloguedCallCount:i.length,totalKnownTools:r.size,uncalled:a,uncalledCount:a.length}}};function i(e){return!e||typeof e.getDomainInstance!=`function`?null:e.getDomainInstance(`serverRuntimeState`)??null}async function a(t){let n=i(t);if(!n)return;let r=n.getPendingActivatedDomains();if(r.length!==0){for(let i of r)if(!(t.enabledDomains.has(i)&&t.domainTtlEntries.has(i)))try{let{handleActivateDomain:e}=await import(`./index.mjs`).then(e=>e.n),r=n.getPendingDomainTtl(i);await e(t,{domain:i,...r?{ttlMinutes:r.ttlMinutes}:{}})}catch(t){e.warn(`Failed to restore activated domain "${i}":`,t)}}}export{i as n,a as r,r as t};
@@ -1 +0,0 @@
1
- import{_ as e,b as t,c as n,d as r,f as i,l as a,m as o,o as s,p as c,t as l,u}from"./Win32API-DoP3MMHS.mjs";import{l as d}from"./Win32Debug-DwF8mQGm.mjs";var f=class{states=new Map;async apply(r,o){this.states.has(r)&&await this.remove(r);let c=t(r,!0),d=[],f=[];try{let t=s(`kernel32.dll`);if(t===0n)throw Error(`Cannot find kernel32.dll`);let l=i(c,0n,4096,a.COMMIT|a.RESERVE,u.EXECUTE_READWRITE);if(l===0n)throw Error(`VirtualAllocEx failed for speedhack shared memory`);let p=Buffer.alloc(8);p.writeDoubleLE(o,0),e(c,l,p);let m=Buffer.alloc(8,0);e(c,l+8n,m),e(c,l+16n,m);let h=n(t,`GetTickCount64`);h!==0n&&await this.hookTimeFunction(c,h,l,256n,`gettick64`)&&(d.push(`GetTickCount64`),f.push(`gettick64`));let g=n(t,`QueryPerformanceCounter`);return g!==0n&&await this.hookTimeFunction(c,g,l,512n,`qpc`)&&(d.push(`QueryPerformanceCounter`),f.push(`qpc`)),this.states.set(r,{pid:r,speed:o,hookedApis:d,isActive:!0,allocatedMemory:`0x${l.toString(16).toUpperCase()}`,patchIds:f}),{success:d.length>0,hookedApis:d}}catch(e){throw l(c),e}finally{l(c)}}async setSpeed(n,r){let i=this.states.get(n);if(!i||!i.isActive||!i.allocatedMemory)return!1;let a=BigInt(i.allocatedMemory),o=t(n,!0);try{let t=Buffer.alloc(8);return t.writeDoubleLE(r,0),e(o,a,t),i.speed=r,!0}finally{l(o)}}getSpeed(e){let t=this.states.get(e);return t?.isActive?t.speed:null}async remove(n){let i=this.states.get(n);if(!i)return!1;let s=t(n,!0);try{if(i.allocatedMemory){let t=BigInt(i.allocatedMemory);for(let n=0;n<i.patchIds.length;n++)try{let i=r(s,t+(3072n+BigInt(n*32)),32),a=i.readBigUInt64LE(0),c=i.readUInt32LE(8);if(a!==0n&&c>0&&c<=16){let t=i.subarray(12,12+c),{oldProtect:n}=o(s,a,c,u.EXECUTE_READWRITE);e(s,a,t),d(s,a,c),o(s,a,c,n)}}catch{}c(s,t,0,a.RELEASE)}}finally{l(s)}return i.isActive=!1,this.states.delete(n),!0}isActive(e){return this.states.get(e)?.isActive??!1}listActive(){return Array.from(this.states.values()).filter(e=>e.isActive)}async hookTimeFunction(t,n,i,a,s){try{let s=r(t,n,14),c=i+a;e(t,c,s);let l=n+14n,f=this.buildAbsoluteJump(l);e(t,c+14n,Buffer.from(f));let p=this.buildAbsoluteJump(c),{oldProtect:m}=o(t,n,14,u.EXECUTE_READWRITE);e(t,n,Buffer.from(p)),d(t,n,14),o(t,n,14,m);let h=this.states.size,g=3072n+BigInt(h*32),_=Buffer.alloc(32);return _.writeBigUInt64LE(n,0),_.writeUInt32LE(14,8),s.copy(_,12),e(t,i+g,_),d(t,c,32),!0}catch{return!1}}buildAbsoluteJump(e){let t=Buffer.alloc(14);return t[0]=255,t[1]=37,t.writeUInt32LE(0,2),t.writeBigUInt64LE(e,6),Array.from(t)}};const p=new f;export{f as Speedhack,p as speedhack};