@jshookmcp/jshook 0.2.7 → 0.2.9

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 (157) hide show
  1. package/README.md +36 -5
  2. package/README.zh.md +36 -5
  3. package/dist/{AntiCheatDetector-S8VRj-dD.mjs → AntiCheatDetector-BNk-EoBt.mjs} +3 -3
  4. package/dist/{CodeInjector-4Z3ngPoX.mjs → CodeInjector-Cq8q01kp.mjs} +5 -5
  5. package/dist/ConsoleMonitor-CPVQW1Y-.mjs +2201 -0
  6. package/dist/{DarwinAPI-B8hg_yhz.mjs → DarwinAPI-BNPxu0RH.mjs} +1 -1
  7. package/dist/DetailedDataManager-BQQcxh64.mjs +217 -0
  8. package/dist/EventBus-DgPmwpeu.mjs +141 -0
  9. package/dist/EvidenceGraphBridge-SFesNera.mjs +153 -0
  10. package/dist/{ExtensionManager-CZ6IveoV.mjs → ExtensionManager-CWYgw0YW.mjs} +13 -6
  11. package/dist/{FingerprintManager-BVxFJL2-.mjs → FingerprintManager-gzWtkKuf.mjs} +1 -1
  12. package/dist/{HardwareBreakpoint-DK1yjWkV.mjs → HardwareBreakpoint-B9gZCdFP.mjs} +3 -3
  13. package/dist/{HeapAnalyzer-CEbo10xU.mjs → HeapAnalyzer-BLDH0dCv.mjs} +4 -4
  14. package/dist/HookGeneratorBuilders.core.generators.storage-CtcdK78Q.mjs +639 -0
  15. package/dist/InstrumentationSession-CvPC7Jwy.mjs +244 -0
  16. package/dist/{MemoryController-DdtnBdD4.mjs → MemoryController-CbVdCIJF.mjs} +3 -3
  17. package/dist/{MemoryScanSession-RMixN3bX.mjs → MemoryScanSession-BsDZbLYm.mjs} +81 -78
  18. package/dist/{MemoryScanner-QjK4ld0B.mjs → MemoryScanner-Bcpml6II.mjs} +44 -18
  19. package/dist/{NativeMemoryManager.impl-CB6gJ0NM.mjs → NativeMemoryManager.impl-dZtA1ZGn.mjs} +14 -53
  20. package/dist/{NativeMemoryManager.utils-BML4q1ry.mjs → NativeMemoryManager.utils-B-FjA2mJ.mjs} +1 -1
  21. package/dist/{PEAnalyzer-CK0xe0Fs.mjs → PEAnalyzer-D1lzJ_VG.mjs} +2 -2
  22. package/dist/PageController-Bqm2kZ_X.mjs +417 -0
  23. package/dist/{PointerChainEngine-Cd73qu5b.mjs → PointerChainEngine-BOhyVsjx.mjs} +4 -4
  24. package/dist/PrerequisiteError-Dl33Svkz.mjs +20 -0
  25. package/dist/ResponseBuilder-D3iFYx2N.mjs +143 -0
  26. package/dist/ReverseEvidenceGraph-Dlsk94LC.mjs +269 -0
  27. package/dist/ScriptManager-aHHq0X7U.mjs +3000 -0
  28. package/dist/{Speedhack-CeF0XmEz.mjs → Speedhack-CqdIFlQl.mjs} +2 -2
  29. package/dist/{StructureAnalyzer-D4GkMduU.mjs → StructureAnalyzer-DhFaPvRO.mjs} +3 -3
  30. package/dist/ToolCatalog-C0JGZoOm.mjs +582 -0
  31. package/dist/ToolError-jh9whhMd.mjs +15 -0
  32. package/dist/ToolProbe-oC7aPrkv.mjs +45 -0
  33. package/dist/ToolRegistry-BjaF4oNz.mjs +131 -0
  34. package/dist/ToolRouter.policy-BWV67ZK-.mjs +304 -0
  35. package/dist/TraceRecorder-DgxyVbdQ.mjs +519 -0
  36. package/dist/{Win32API-Bc0QnQsN.mjs → Win32API-CePkipZY.mjs} +1 -1
  37. package/dist/{Win32Debug-DUHt9XUn.mjs → Win32Debug-BvKs-gxc.mjs} +2 -2
  38. package/dist/WorkflowEngine-CuvkZtWu.mjs +598 -0
  39. package/dist/analysis-CL9uACt9.mjs +463 -0
  40. package/dist/antidebug-CqDTB_uk.mjs +1081 -0
  41. package/dist/artifactRetention-CFEprwPw.mjs +591 -0
  42. package/dist/artifacts-Bk2-_uPq.mjs +59 -0
  43. package/dist/betterSqlite3-0pqusHHH.mjs +74 -0
  44. package/dist/binary-instrument-CXfpx6fT.mjs +979 -0
  45. package/dist/bind-helpers-xFfRF-qm.mjs +22 -0
  46. package/dist/boringssl-inspector-BH2D3VKc.mjs +180 -0
  47. package/dist/browser-BpOr5PEx.mjs +4082 -0
  48. package/dist/concurrency-Bt0yv1kJ.mjs +41 -0
  49. package/dist/{constants-CCvsN80K.mjs → constants-B0OANIBL.mjs} +88 -46
  50. package/dist/coordination-qUbyF8KU.mjs +259 -0
  51. package/dist/debugger-gnKxRSN0.mjs +1271 -0
  52. package/dist/definitions-6M-eejaT.mjs +53 -0
  53. package/dist/definitions-B18eyf0B.mjs +18 -0
  54. package/dist/definitions-B3QdlrHv.mjs +34 -0
  55. package/dist/definitions-B4rAvHNZ.mjs +63 -0
  56. package/dist/definitions-BB_4jnmy.mjs +37 -0
  57. package/dist/definitions-BMfYXoNC.mjs +43 -0
  58. package/dist/definitions-Beid2EB3.mjs +27 -0
  59. package/dist/definitions-C1UvM5Iy.mjs +126 -0
  60. package/dist/definitions-CXEI7QC72.mjs +216 -0
  61. package/dist/definitions-C_4r7Fo-2.mjs +14 -0
  62. package/dist/definitions-CkFDALoa.mjs +26 -0
  63. package/dist/definitions-Cke7zEb8.mjs +94 -0
  64. package/dist/definitions-ClJLzsJQ.mjs +25 -0
  65. package/dist/definitions-Cq-zroAU.mjs +28 -0
  66. package/dist/definitions-Cy3Sl6gV.mjs +34 -0
  67. package/dist/definitions-D3VsGcvz.mjs +47 -0
  68. package/dist/definitions-DVGfrn7y.mjs +96 -0
  69. package/dist/definitions-LKpC3-nL.mjs +9 -0
  70. package/dist/definitions-bAhHQJq9.mjs +359 -0
  71. package/dist/encoding-Bvz5jLRv.mjs +1065 -0
  72. package/dist/evidence-graph-bridge-C_fv9PuC.mjs +135 -0
  73. package/dist/{factory-CibqTNC8.mjs → factory-DxlGh9Xf.mjs} +37 -52
  74. package/dist/graphql-DYWzJ29s.mjs +1026 -0
  75. package/dist/handlers-9sAbfIg-.mjs +2552 -0
  76. package/dist/handlers-Bl8zkwz1.mjs +2716 -0
  77. package/dist/handlers-C67ktuRN.mjs +710 -0
  78. package/dist/handlers-C87g8oCe.mjs +276 -0
  79. package/dist/handlers-CTsDAO6p.mjs +681 -0
  80. package/dist/handlers-Cgyg6c0U.mjs +645 -0
  81. package/dist/handlers-D6j6yka7.mjs +2124 -0
  82. package/dist/handlers-DdFzXLvF.mjs +446 -0
  83. package/dist/handlers-DeLOCd5m.mjs +799 -0
  84. package/dist/handlers-DlCJN4Td.mjs +757 -0
  85. package/dist/handlers-DxGIq15_2.mjs +917 -0
  86. package/dist/handlers-U6L4xhuF.mjs +585 -0
  87. package/dist/handlers-tB9Mp9ZK.mjs +84 -0
  88. package/dist/handlers-tiy7EIBp.mjs +572 -0
  89. package/dist/handlers.impl-DS0d9fUw.mjs +761 -0
  90. package/dist/hooks-CzCWByww.mjs +898 -0
  91. package/dist/index.mjs +384 -155
  92. package/dist/{logger-BmWzC2lM.mjs → logger-Dh_xb7_2.mjs} +14 -6
  93. package/dist/maintenance-P7ePRXQC.mjs +830 -0
  94. package/dist/manifest-2ToTpjv8.mjs +106 -0
  95. package/dist/manifest-3g71z6Bg.mjs +79 -0
  96. package/dist/manifest-82baTv4U.mjs +45 -0
  97. package/dist/manifest-B3QVVeBS.mjs +82 -0
  98. package/dist/manifest-BB2J8IMJ.mjs +149 -0
  99. package/dist/manifest-BKbgbSiY.mjs +60 -0
  100. package/dist/manifest-Bcf-TJzH.mjs +848 -0
  101. package/dist/manifest-BmtZzQiQ2.mjs +45 -0
  102. package/dist/manifest-Bnd7kqEY.mjs +55 -0
  103. package/dist/manifest-BqQX6OQC2.mjs +65 -0
  104. package/dist/manifest-BqrQ4Tpj.mjs +81 -0
  105. package/dist/manifest-Br4RPFt5.mjs +370 -0
  106. package/dist/manifest-C5qDjysN.mjs +107 -0
  107. package/dist/manifest-C9RT5nk32.mjs +34 -0
  108. package/dist/manifest-CAhOuvSl.mjs +204 -0
  109. package/dist/manifest-CBYWCUBJ.mjs +51 -0
  110. package/dist/manifest-CFADCRa1.mjs +37 -0
  111. package/dist/manifest-CQVhavRF.mjs +114 -0
  112. package/dist/manifest-CT7zZBV1.mjs +48 -0
  113. package/dist/manifest-CV12bcrF.mjs +121 -0
  114. package/dist/manifest-CXsRWjjI.mjs +224 -0
  115. package/dist/manifest-CZLUCfG02.mjs +95 -0
  116. package/dist/manifest-D6phHKFd.mjs +131 -0
  117. package/dist/manifest-DCyjf4n2.mjs +294 -0
  118. package/dist/manifest-DHsnKgP6.mjs +60 -0
  119. package/dist/manifest-Df_dliIe.mjs +55 -0
  120. package/dist/manifest-Dh8WBmEW.mjs +129 -0
  121. package/dist/manifest-DhKRAT8_.mjs +92 -0
  122. package/dist/manifest-DlpTj4ic2.mjs +193 -0
  123. package/dist/manifest-DrbmZcFl2.mjs +253 -0
  124. package/dist/manifest-DuwHjUa5.mjs +70 -0
  125. package/dist/manifest-DzwvxPJX.mjs +38 -0
  126. package/dist/manifest-NXctwWQq.mjs +68 -0
  127. package/dist/manifest-Sc_0JQ13.mjs +418 -0
  128. package/dist/manifest-gZ4s_UtG.mjs +96 -0
  129. package/dist/manifest-qSleDqdO.mjs +1023 -0
  130. package/dist/modules-C184v-S9.mjs +11365 -0
  131. package/dist/mojo-ipc-B_H61Afw.mjs +525 -0
  132. package/dist/network-671Cw6hV.mjs +3346 -0
  133. package/dist/{artifacts-BbdOMET5.mjs → outputPaths-B1uGmrWZ.mjs} +219 -212
  134. package/dist/parse-args-BlRjqlkL.mjs +39 -0
  135. package/dist/platform-WmNn8Sxb.mjs +2070 -0
  136. package/dist/process-QcbIy5Zq.mjs +1401 -0
  137. package/dist/proxy-DqNs0bAd.mjs +170 -0
  138. package/dist/registry-D-6e18lB.mjs +34 -0
  139. package/dist/response-BQVP-xUn.mjs +28 -0
  140. package/dist/server/plugin-api.mjs +2 -2
  141. package/dist/shared-state-board-DV-dpHFJ.mjs +586 -0
  142. package/dist/sourcemap-Dq8ez8vS.mjs +650 -0
  143. package/dist/ssrf-policy-ZaUfvhq7.mjs +166 -0
  144. package/dist/streaming-BUQ0VJsg.mjs +725 -0
  145. package/dist/tool-builder-DCbIC5Eo.mjs +186 -0
  146. package/dist/transform-CiYJfNX0.mjs +1007 -0
  147. package/dist/types-Bx92KJfT.mjs +4 -0
  148. package/dist/wasm-DQTnHDs4.mjs +531 -0
  149. package/dist/workflow-f3xJOcjx.mjs +725 -0
  150. package/package.json +48 -78
  151. package/dist/ExtensionManager-DqUSOamB.mjs +0 -2
  152. package/dist/ToolCatalog-CnwmMIw3.mjs +0 -61483
  153. package/dist/{CacheAdapters-CzFNpD9a.mjs → CacheAdapters-CDe5WPSV.mjs} +0 -0
  154. package/dist/{StealthVerifier-BzBCFiwx.mjs → StealthVerifier-Bo4T3bz8.mjs} +0 -0
  155. package/dist/{VersionDetector-CNXcvD46.mjs → VersionDetector-CwVLVdDM.mjs} +0 -0
  156. package/dist/{formatAddress-ChCSIRWT.mjs → formatAddress-DVkj9kpI.mjs} +0 -0
  157. package/dist/{types-BBjOqye-.mjs → types-CPhOReNX.mjs} +1 -1
@@ -0,0 +1,799 @@
1
+ import { gr as WEBHOOK_PROCESS_TIMEOUT_MS } from "./constants-B0OANIBL.mjs";
2
+ import { n as asJsonResponse } from "./response-BQVP-xUn.mjs";
3
+ import { i as getProjectRoot, r as getExtensionRegistryDir } from "./outputPaths-B1uGmrWZ.mjs";
4
+ import { a as argString, i as argObject, s as argStringRequired } from "./parse-args-BlRjqlkL.mjs";
5
+ import http from "node:http";
6
+ import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { mkdir, writeFile } from "node:fs/promises";
10
+ import { EventEmitter } from "node:events";
11
+ //#region src/modules/extension-registry/PluginRegistry.ts
12
+ function isRecord$2(value) {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+ function sanitizeId(value) {
16
+ const normalized = value.trim().toLowerCase().replace(/\//g, "-").replace(/(?!^@)[^a-z0-9@_-]+/g, "-");
17
+ return normalized.length > 0 ? normalized : `plugin-${Date.now()}`;
18
+ }
19
+ function toStoredPluginManifest(value) {
20
+ if (!isRecord$2(value)) return null;
21
+ const { id, name, version, entry, permissions, status } = value;
22
+ if (typeof id !== "string" || typeof name !== "string" || typeof version !== "string" || typeof entry !== "string" || status !== "loaded" && status !== "unloaded") return null;
23
+ return {
24
+ id,
25
+ name,
26
+ version,
27
+ entry,
28
+ permissions: Array.isArray(permissions) ? permissions.filter((permission) => typeof permission === "string") : [],
29
+ status
30
+ };
31
+ }
32
+ var PluginRegistry = class {
33
+ rootDir;
34
+ legacyPluginRoots;
35
+ useLegacyScanApi;
36
+ registryFile;
37
+ moduleCacheDir;
38
+ installedPlugins = /* @__PURE__ */ new Map();
39
+ loadedPlugins = /* @__PURE__ */ new Map();
40
+ constructor(rootDirOrContext = getExtensionRegistryDir(), pluginRoots = []) {
41
+ const resolvedRootDir = typeof rootDirOrContext === "string" ? rootDirOrContext : getExtensionRegistryDir();
42
+ this.useLegacyScanApi = typeof rootDirOrContext !== "string";
43
+ this.rootDir = resolvedRootDir;
44
+ this.registryFile = path.join(resolvedRootDir, "plugins.json");
45
+ this.moduleCacheDir = path.join(resolvedRootDir, "modules");
46
+ this.legacyPluginRoots = pluginRoots.length > 0 ? pluginRoots : process.env["JSHOOKMCP_PLUGIN_ROOT"] ? [process.env["JSHOOKMCP_PLUGIN_ROOT"]] : [];
47
+ if (this.useLegacyScanApi) return;
48
+ this.initializeFromDisk();
49
+ }
50
+ async register(plugin) {
51
+ const pluginId = sanitizeId(plugin.id || plugin.name);
52
+ const manifest = {
53
+ id: pluginId,
54
+ name: plugin.name,
55
+ version: plugin.version,
56
+ entry: plugin.entry,
57
+ permissions: plugin.permissions ? [...plugin.permissions] : [],
58
+ status: this.loadedPlugins.has(pluginId) ? "loaded" : "unloaded"
59
+ };
60
+ this.installedPlugins.set(pluginId, manifest);
61
+ await this.persist();
62
+ return pluginId;
63
+ }
64
+ async unregister(pluginId) {
65
+ await this.unloadPlugin(pluginId);
66
+ this.installedPlugins.delete(pluginId);
67
+ await this.persist();
68
+ }
69
+ listInstalled() {
70
+ return [...this.installedPlugins.values()].map((plugin) => ({
71
+ id: plugin.id,
72
+ name: plugin.name,
73
+ version: plugin.version,
74
+ status: plugin.status,
75
+ permissions: [...plugin.permissions]
76
+ })).toSorted((left, right) => left.name.localeCompare(right.name));
77
+ }
78
+ async loadPlugin(pluginId) {
79
+ const manifest = this.installedPlugins.get(pluginId);
80
+ if (!manifest) throw new Error(`Plugin not found: ${pluginId}`);
81
+ const existing = this.loadedPlugins.get(pluginId);
82
+ if (existing) return {
83
+ manifest: this.toPublicManifest(existing.manifest),
84
+ exports: existing.exports
85
+ };
86
+ const importUrl = pathToFileURL(await this.resolveEntryPath(manifest));
87
+ importUrl.searchParams.set("ts", String(Date.now()));
88
+ const moduleExports = await import(importUrl.href);
89
+ const exportsRecord = isRecord$2(moduleExports) ? moduleExports : {};
90
+ manifest.status = "loaded";
91
+ this.loadedPlugins.set(pluginId, {
92
+ manifest,
93
+ exports: exportsRecord
94
+ });
95
+ await this.persist();
96
+ return {
97
+ manifest: this.toPublicManifest(manifest),
98
+ exports: exportsRecord
99
+ };
100
+ }
101
+ async unloadPlugin(pluginId) {
102
+ const manifest = this.installedPlugins.get(pluginId);
103
+ if (!manifest) return;
104
+ this.loadedPlugins.delete(pluginId);
105
+ manifest.status = "unloaded";
106
+ await this.persist();
107
+ }
108
+ initializeFromDisk() {
109
+ if (!existsSync(this.rootDir)) mkdirSync(this.rootDir, { recursive: true });
110
+ if (!existsSync(this.moduleCacheDir)) mkdirSync(this.moduleCacheDir, { recursive: true });
111
+ if (!existsSync(this.registryFile)) return;
112
+ const content = readFileSync(this.registryFile, "utf8");
113
+ if (!content.trim()) return;
114
+ const parsed = JSON.parse(content);
115
+ if (!Array.isArray(parsed)) return;
116
+ for (const item of parsed) {
117
+ const manifest = toStoredPluginManifest(item);
118
+ if (manifest) this.installedPlugins.set(manifest.id, manifest);
119
+ }
120
+ }
121
+ async persist() {
122
+ await mkdir(this.rootDir, { recursive: true });
123
+ await mkdir(this.moduleCacheDir, { recursive: true });
124
+ await writeFile(this.registryFile, JSON.stringify([...this.installedPlugins.values()], null, 2), "utf8");
125
+ }
126
+ async resolveEntryPath(manifest) {
127
+ if (manifest.entry.startsWith("http://") || manifest.entry.startsWith("https://")) return this.downloadRemoteModule(manifest.id, manifest.entry);
128
+ if (manifest.entry.startsWith("file://")) return fileURLToPath(new URL(manifest.entry));
129
+ return path.isAbsolute(manifest.entry) ? manifest.entry : path.resolve(getProjectRoot(), manifest.entry);
130
+ }
131
+ async downloadRemoteModule(pluginId, url) {
132
+ const response = await fetch(url);
133
+ if (!response.ok) throw new Error(`Failed to download plugin module: ${response.status} ${response.statusText}`);
134
+ const source = await response.text();
135
+ const outputPath = path.join(this.moduleCacheDir, `${sanitizeId(pluginId)}.mjs`);
136
+ await mkdir(this.moduleCacheDir, { recursive: true });
137
+ await writeFile(outputPath, source, "utf8");
138
+ return outputPath;
139
+ }
140
+ toPublicManifest(manifest) {
141
+ return {
142
+ id: manifest.id,
143
+ name: manifest.name,
144
+ version: manifest.version,
145
+ entry: manifest.entry,
146
+ permissions: [...manifest.permissions]
147
+ };
148
+ }
149
+ listPlugins() {
150
+ const plugins = [];
151
+ for (const root of this.legacyPluginRoots) {
152
+ if (!existsSync(root)) continue;
153
+ const entries = readdirSync(root, { withFileTypes: true });
154
+ for (const entry of entries) {
155
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
156
+ const packageJsonPath = path.join(root, entry.name, "package.json");
157
+ if (!existsSync(packageJsonPath)) continue;
158
+ try {
159
+ const manifest = JSON.parse(readFileSync(packageJsonPath, "utf8"));
160
+ const plugin = this.toLegacyPluginInfo(manifest);
161
+ if (plugin) plugins.push(plugin);
162
+ } catch {
163
+ continue;
164
+ }
165
+ }
166
+ }
167
+ return plugins;
168
+ }
169
+ searchPlugins(query) {
170
+ const normalized = query.trim().toLowerCase();
171
+ if (!normalized) return this.listPlugins();
172
+ return this.listPlugins().filter((plugin) => {
173
+ return plugin.name.toLowerCase().includes(normalized) || (plugin.description ?? "").toLowerCase().includes(normalized) || (plugin.capabilities ?? []).some((capability) => capability.toLowerCase().includes(normalized)) || (plugin.dependencies ?? []).some((dependency) => dependency.toLowerCase().includes(normalized));
174
+ });
175
+ }
176
+ async installPlugin(source) {
177
+ if (/^https:\/\/github\.com\/.+\.git$/u.test(source) || /^git@github\.com:.+\.git$/u.test(source)) return {
178
+ id: "git-plugin",
179
+ name: source.split("/").pop()?.replace(/\.git$/u, "") ?? "plugin",
180
+ version: "0.0.0"
181
+ };
182
+ if (source.includes("://") || source.startsWith("git@") || source === "invalid-url") throw new Error("Invalid git URL");
183
+ if (source.startsWith("/") || source.includes("\\")) {
184
+ const packageJsonPath = path.join(source, "package.json");
185
+ if (!existsSync(packageJsonPath)) throw new Error("No package.json");
186
+ const manifest = JSON.parse(readFileSync(packageJsonPath, "utf8"));
187
+ const plugin = this.toLegacyPluginInfo(manifest);
188
+ if (!plugin) throw new Error("No package.json");
189
+ return plugin;
190
+ }
191
+ for (const root of this.legacyPluginRoots) {
192
+ const packageJsonPath = path.join(root, source, "package.json");
193
+ if (!existsSync(packageJsonPath)) continue;
194
+ const manifest = JSON.parse(readFileSync(packageJsonPath, "utf8"));
195
+ const plugin = this.toLegacyPluginInfo(manifest);
196
+ if (plugin) return plugin;
197
+ }
198
+ throw new Error("Plugin not found");
199
+ }
200
+ getPluginInfo(pluginId) {
201
+ return this.listPlugins().find((plugin) => plugin.id === pluginId || plugin.name === pluginId);
202
+ }
203
+ getPluginDependencies(pluginId) {
204
+ return this.getPluginInfo(pluginId)?.dependencies ?? [];
205
+ }
206
+ async uninstallPlugin(_pluginId) {}
207
+ toLegacyPluginInfo(manifest) {
208
+ if (typeof manifest["name"] !== "string") return null;
209
+ const dependencies = isRecord$2(manifest["dependencies"]) ? Object.keys(manifest["dependencies"]) : [];
210
+ return {
211
+ id: sanitizeId(manifest["name"]),
212
+ name: manifest["name"],
213
+ version: typeof manifest["version"] === "string" ? manifest["version"] : "0.0.0",
214
+ description: typeof manifest["description"] === "string" ? manifest["description"] : void 0,
215
+ capabilities: Array.isArray(manifest["capabilities"]) ? manifest["capabilities"].filter((value) => typeof value === "string") : void 0,
216
+ dependencies
217
+ };
218
+ }
219
+ };
220
+ //#endregion
221
+ //#region src/modules/extension-registry/WebhookBridge.ts
222
+ function isRecord$1(value) {
223
+ return value !== null && typeof value === "object" && !Array.isArray(value);
224
+ }
225
+ function toWebhookRecord(value) {
226
+ if (!isRecord$1(value)) return null;
227
+ const { id, url, events, active } = value;
228
+ if (typeof id !== "string" || typeof url !== "string" || !Array.isArray(events) || typeof active !== "boolean") return null;
229
+ return {
230
+ id,
231
+ url,
232
+ events: events.filter((event) => typeof event === "string"),
233
+ active
234
+ };
235
+ }
236
+ var WebhookBridge = class {
237
+ rootDir;
238
+ storageFile;
239
+ webhooks = /* @__PURE__ */ new Map();
240
+ constructor(rootDir = getExtensionRegistryDir()) {
241
+ this.rootDir = rootDir;
242
+ this.storageFile = path.join(rootDir, "webhooks.json");
243
+ this.initializeFromDisk();
244
+ }
245
+ async registerWebhook(url, events) {
246
+ new URL(url);
247
+ const record = {
248
+ id: `webhook-${Date.now()}-${this.webhooks.size + 1}`,
249
+ url,
250
+ events: [...new Set(events.filter((event) => event.trim().length > 0))],
251
+ active: true
252
+ };
253
+ this.webhooks.set(record.id, record);
254
+ await this.persist();
255
+ return record.id;
256
+ }
257
+ async sendEvent(event, payload) {
258
+ const deliveries = [...this.webhooks.values()].filter((record) => record.active && (record.events.includes(event) || record.events.includes("*")));
259
+ for (const record of deliveries) {
260
+ const response = await fetch(record.url, {
261
+ method: "POST",
262
+ headers: { "content-type": "application/json" },
263
+ body: JSON.stringify({
264
+ event,
265
+ payload,
266
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
267
+ })
268
+ });
269
+ if (!response.ok) throw new Error(`Webhook delivery failed for ${record.url}: ${response.status} ${response.statusText}`);
270
+ }
271
+ }
272
+ listWebhooks() {
273
+ return [...this.webhooks.values()].map((record) => ({
274
+ id: record.id,
275
+ url: record.url,
276
+ events: [...record.events],
277
+ active: record.active
278
+ }));
279
+ }
280
+ /**
281
+ * Register an external callback URL for a webhook endpoint.
282
+ * Used when webhook_create registers an endpoint — the URL is stored
283
+ * here so emitEvent() can forward events to external callbacks.
284
+ */
285
+ registerExternalCallback(endpointId, url) {
286
+ const existing = this.webhooks.get(endpointId);
287
+ if (existing) {
288
+ existing.url = url;
289
+ return;
290
+ }
291
+ this.webhooks.set(endpointId, {
292
+ id: endpointId,
293
+ url,
294
+ events: ["*"],
295
+ active: true
296
+ });
297
+ }
298
+ initializeFromDisk() {
299
+ if (!existsSync(this.rootDir)) mkdirSync(this.rootDir, { recursive: true });
300
+ if (!existsSync(this.storageFile)) return;
301
+ const content = readFileSync(this.storageFile, "utf8");
302
+ if (!content.trim()) return;
303
+ const parsed = JSON.parse(content);
304
+ if (!Array.isArray(parsed)) return;
305
+ for (const item of parsed) {
306
+ const record = toWebhookRecord(item);
307
+ if (record) this.webhooks.set(record.id, record);
308
+ }
309
+ }
310
+ async persist() {
311
+ await mkdir(this.rootDir, { recursive: true });
312
+ await writeFile(this.storageFile, JSON.stringify([...this.webhooks.values()], null, 2), "utf8");
313
+ }
314
+ };
315
+ //#endregion
316
+ //#region src/server/webhook/CommandQueue.impl.ts
317
+ function cloneCommand(command) {
318
+ return { ...command };
319
+ }
320
+ function normalizeTimestamp() {
321
+ return (/* @__PURE__ */ new Date()).toISOString();
322
+ }
323
+ var CommandQueueImpl = class extends EventEmitter {
324
+ maxQueueSize;
325
+ commands = /* @__PURE__ */ new Map();
326
+ order = [];
327
+ maxRetries;
328
+ retryDelay;
329
+ processTimeout;
330
+ nextId = 1;
331
+ constructor(options = {}) {
332
+ super();
333
+ this.maxQueueSize = typeof options.maxQueueSize === "number" ? options.maxQueueSize : 1e3;
334
+ this.maxRetries = typeof options.maxRetries === "number" ? options.maxRetries : 3;
335
+ this.retryDelay = typeof options.retryDelay === "number" ? options.retryDelay : 0;
336
+ this.processTimeout = typeof options.processTimeout === "number" ? options.processTimeout : WEBHOOK_PROCESS_TIMEOUT_MS;
337
+ }
338
+ enqueue(command) {
339
+ if (this.order.length >= this.maxQueueSize) throw new Error(`Command queue is full (${this.maxQueueSize})`);
340
+ const id = `cmd-${this.nextId}`;
341
+ this.nextId += 1;
342
+ const createdAt = normalizeTimestamp();
343
+ const entry = {
344
+ id,
345
+ endpointId: command.endpointId,
346
+ event: command.event,
347
+ payload: command.payload,
348
+ status: "pending",
349
+ retries: 0,
350
+ createdAt,
351
+ updatedAt: createdAt
352
+ };
353
+ this.commands.set(id, entry);
354
+ this.order.push(id);
355
+ this.emit("enqueued", cloneCommand(entry));
356
+ return id;
357
+ }
358
+ dequeue(filter) {
359
+ if (!filter) {
360
+ const firstPending = this.getCommandsByFilter({ status: "pending" })[0];
361
+ return firstPending ? cloneCommand(firstPending) : void 0;
362
+ }
363
+ return this.getCommandsByFilter(filter).map(cloneCommand);
364
+ }
365
+ getStatus(id) {
366
+ const command = this.commands.get(id);
367
+ if (!command) return "failed";
368
+ if (command.status === "processed") return "completed";
369
+ return command.status;
370
+ }
371
+ retry(id) {
372
+ const command = this.commands.get(id);
373
+ if (!command) throw new Error(`Command ${id} not found`);
374
+ if (command.status !== "failed") throw new Error(`Command ${id} is not in failed state`);
375
+ command.status = "pending";
376
+ command.retries = 0;
377
+ command.lastError = void 0;
378
+ command.updatedAt = normalizeTimestamp();
379
+ }
380
+ getCommand(id) {
381
+ return this.commands.get(id);
382
+ }
383
+ getCommandsByFilter(filter) {
384
+ const normalizedStatus = filter.status === "completed" ? "processed" : filter.status;
385
+ const results = [];
386
+ for (const id of this.order) {
387
+ const command = this.commands.get(id);
388
+ if (!command) continue;
389
+ if (normalizedStatus && command.status !== normalizedStatus) continue;
390
+ if (filter.endpointId && command.endpointId !== filter.endpointId) continue;
391
+ results.push(command);
392
+ }
393
+ return results;
394
+ }
395
+ updateStatus(id, status, lastError) {
396
+ const command = this.commands.get(id);
397
+ if (!command) throw new Error(`Command ${id} not found`);
398
+ command.status = status;
399
+ command.updatedAt = normalizeTimestamp();
400
+ command.lastError = lastError;
401
+ return command;
402
+ }
403
+ };
404
+ var CommandQueue = class extends CommandQueueImpl {
405
+ async process(id, handler) {
406
+ const command = this.getCommand(id);
407
+ if (!command) throw new Error(`Command ${id} not found`);
408
+ if (command.status === "processed") throw new Error(`Command ${id} already processed`);
409
+ if (command.status === "failed") throw new Error(`Command ${id} already processed with failure`);
410
+ if (command.status === "processing") throw new Error(`Command ${id} is already processing`);
411
+ this.updateStatus(id, "processing");
412
+ let finalStatus = "processed";
413
+ let lastError;
414
+ try {
415
+ await Promise.race([Promise.resolve(handler(cloneCommand(command))), new Promise((_, reject) => {
416
+ setTimeout(() => {
417
+ reject(/* @__PURE__ */ new Error("Process timeout"));
418
+ }, this.processTimeout);
419
+ })]);
420
+ } catch (error) {
421
+ lastError = error instanceof Error ? error.message : String(error);
422
+ if (command.retries + 1 >= this.maxRetries) finalStatus = "failed";
423
+ else finalStatus = "pending";
424
+ }
425
+ if (lastError !== void 0 && this.retryDelay > 0) setTimeout(() => {}, this.retryDelay);
426
+ if (finalStatus === "processed") {
427
+ const processed = this.updateStatus(id, "processed");
428
+ this.emit("processed", cloneCommand(processed));
429
+ } else if (finalStatus === "pending") {
430
+ command.retries += 1;
431
+ const retried = this.updateStatus(id, "pending", lastError);
432
+ this.emit("retried", cloneCommand(retried));
433
+ throw lastError !== void 0 ? new Error(lastError) : /* @__PURE__ */ new Error("retry");
434
+ } else {
435
+ const failed = this.updateStatus(id, "failed", lastError);
436
+ this.emit("failed", cloneCommand(failed));
437
+ throw lastError !== void 0 ? new Error(lastError) : /* @__PURE__ */ new Error("failed");
438
+ }
439
+ }
440
+ async retry(id) {
441
+ super.retry(id);
442
+ }
443
+ exportState() {
444
+ const results = [];
445
+ for (const id of this.order) {
446
+ const command = this.commands.get(id);
447
+ if (command) results.push(cloneCommand(command));
448
+ }
449
+ return results;
450
+ }
451
+ importState(commands) {
452
+ this.commands.clear();
453
+ this.order.length = 0;
454
+ let maxId = 0;
455
+ for (const command of commands) {
456
+ const entry = cloneCommand(command);
457
+ this.commands.set(entry.id, entry);
458
+ this.order.push(entry.id);
459
+ const match = /^cmd-(\d+)$/.exec(entry.id);
460
+ if (match && match[1]) {
461
+ const num = parseInt(match[1], 10);
462
+ if (num > maxId) maxId = num;
463
+ }
464
+ }
465
+ if (maxId > 0) this.nextId = maxId + 1;
466
+ }
467
+ };
468
+ //#endregion
469
+ //#region src/server/webhook/WebhookServer.impl.ts
470
+ function isWebhookEvent(value) {
471
+ return value === "tool_called" || value === "domain_activated" || value === "evidence_added" || value === "workflow_completed";
472
+ }
473
+ function parseJsonBody(rawBody) {
474
+ if (rawBody.length === 0) return {};
475
+ try {
476
+ return JSON.parse(rawBody);
477
+ } catch {
478
+ return { rawBody };
479
+ }
480
+ }
481
+ var WebhookServerImpl = class extends EventEmitter {
482
+ endpoints = /* @__PURE__ */ new Map();
483
+ eventHandlers = /* @__PURE__ */ new Map();
484
+ port;
485
+ commandQueue;
486
+ stats = {
487
+ eventsRegistered: 0,
488
+ webhooksSent: 0
489
+ };
490
+ server;
491
+ nextEndpointId = 1;
492
+ constructor(options = {}) {
493
+ super();
494
+ this.port = typeof options.port === "number" ? options.port : 18789;
495
+ this.commandQueue = options.commandQueue;
496
+ }
497
+ registerEndpoint(config) {
498
+ const id = `ep-${this.nextEndpointId}`;
499
+ this.nextEndpointId += 1;
500
+ this.endpoints.set(id, {
501
+ id,
502
+ path: config.path,
503
+ method: config.method ?? "POST",
504
+ secret: config.secret
505
+ });
506
+ this.emit("endpointRegistered", id);
507
+ return id;
508
+ }
509
+ removeEndpoint(id) {
510
+ if (!this.endpoints.delete(id)) throw new Error(`Endpoint ${id} not found`);
511
+ this.emit("endpointRemoved", id);
512
+ }
513
+ listEndpoints() {
514
+ return [...this.endpoints.values()].map((endpoint) => ({ ...endpoint }));
515
+ }
516
+ getPort() {
517
+ return this.port;
518
+ }
519
+ isRunning() {
520
+ return this.server !== void 0;
521
+ }
522
+ registerEvent(event, handler) {
523
+ const handlers = this.eventHandlers.get(event) ?? [];
524
+ handlers.push(handler);
525
+ this.eventHandlers.set(event, handlers);
526
+ this.stats.eventsRegistered += 1;
527
+ }
528
+ start() {
529
+ if (this.server) throw new Error("Webhook server already started");
530
+ this.server = http.createServer((request, response) => {
531
+ this.handleRequest(request, response);
532
+ });
533
+ this.server.listen(this.port);
534
+ this.emit("started", this.port);
535
+ }
536
+ async stop() {
537
+ if (!this.server) return;
538
+ const server = this.server;
539
+ this.server = void 0;
540
+ await new Promise((resolve, reject) => {
541
+ server.close((error) => {
542
+ if (error) {
543
+ reject(error);
544
+ return;
545
+ }
546
+ resolve();
547
+ });
548
+ });
549
+ this.emit("stopped");
550
+ }
551
+ async sendWebhook(url, event, payload) {
552
+ await fetch(url, {
553
+ method: "POST",
554
+ headers: { "content-type": "application/json" },
555
+ body: JSON.stringify({
556
+ event,
557
+ payload
558
+ })
559
+ });
560
+ this.stats.webhooksSent += 1;
561
+ this.stats.lastSentAt = (/* @__PURE__ */ new Date()).toISOString();
562
+ }
563
+ getStats() {
564
+ return { ...this.stats };
565
+ }
566
+ async handleRequest(request, response) {
567
+ const method = request.method ?? "GET";
568
+ const url = request.url ?? "/";
569
+ const endpoint = [...this.endpoints.values()].find((item) => item.path === url && item.method === method);
570
+ if (!endpoint) {
571
+ response.statusCode = 404;
572
+ response.end("not found");
573
+ return;
574
+ }
575
+ if (endpoint.secret) {
576
+ if (request.headers["x-webhook-secret"] !== endpoint.secret) {
577
+ response.statusCode = 401;
578
+ response.end("unauthorized");
579
+ return;
580
+ }
581
+ }
582
+ const chunks = [];
583
+ await new Promise((resolve, reject) => {
584
+ request.setEncoding("utf8");
585
+ request.on("data", (chunk) => {
586
+ chunks.push(chunk);
587
+ });
588
+ request.on("end", () => {
589
+ resolve();
590
+ });
591
+ request.on("error", (error) => {
592
+ reject(error);
593
+ });
594
+ });
595
+ const payload = parseJsonBody(chunks.join(""));
596
+ if (this.commandQueue) this.commandQueue.enqueue({
597
+ endpointId: endpoint.id,
598
+ payload
599
+ });
600
+ if (payload && typeof payload === "object" && "event" in payload && typeof payload.event === "string") await this.invokeEventHandlers(payload.event, payload);
601
+ response.setHeader("content-type", "application/json");
602
+ response.end(JSON.stringify({
603
+ ok: true,
604
+ endpointId: endpoint.id
605
+ }));
606
+ }
607
+ async invokeEventHandlers(eventName, payload) {
608
+ if (!isWebhookEvent(eventName)) return;
609
+ const handlers = this.eventHandlers.get(eventName) ?? [];
610
+ for (const handler of handlers) await Promise.resolve(handler(payload));
611
+ }
612
+ };
613
+ var WebhookServer = class extends WebhookServerImpl {};
614
+ //#endregion
615
+ //#region src/server/domains/extension-registry/handlers.impl.ts
616
+ function isRecord(value) {
617
+ return value !== null && typeof value === "object" && !Array.isArray(value);
618
+ }
619
+ function isCallable(value) {
620
+ return typeof value === "function";
621
+ }
622
+ var ExtensionRegistryHandlers = class {
623
+ _webhookServer;
624
+ _commandQueue;
625
+ constructor(registry, webhook) {
626
+ this.registry = registry;
627
+ this.webhook = webhook;
628
+ }
629
+ async handleListInstalled() {
630
+ return asJsonResponse({
631
+ success: true,
632
+ plugins: this.getRegistry().listInstalled()
633
+ });
634
+ }
635
+ async handleExecuteInContext(args) {
636
+ const pluginId = argStringRequired(args, "pluginId");
637
+ const contextName = argStringRequired(args, "contextName");
638
+ const contextArgs = argObject(args, "args") ?? {};
639
+ const { manifest, exports } = await this.getRegistry().loadPlugin(pluginId);
640
+ const context = this.resolveContext(exports, contextName);
641
+ if (!context) throw new Error(`Context "${contextName}" was not found in plugin "${pluginId}"`);
642
+ const result = await Promise.resolve(context(contextArgs));
643
+ this.emitEvent("extension.executed", {
644
+ pluginId,
645
+ contextName
646
+ });
647
+ return asJsonResponse({
648
+ success: true,
649
+ manifest,
650
+ contextName,
651
+ result
652
+ });
653
+ }
654
+ async handleReload(args) {
655
+ const pluginId = argStringRequired(args, "pluginId");
656
+ await this.getRegistry().unloadPlugin(pluginId);
657
+ const loaded = await this.getRegistry().loadPlugin(pluginId);
658
+ this.emitEvent("extension.reloaded", { pluginId });
659
+ return asJsonResponse({
660
+ success: true,
661
+ pluginId,
662
+ manifest: loaded.manifest,
663
+ exportedKeys: Object.keys(loaded.exports).toSorted()
664
+ });
665
+ }
666
+ async handleUninstall(args) {
667
+ const pluginId = argStringRequired(args, "pluginId");
668
+ await this.getRegistry().unregister(pluginId);
669
+ this.emitEvent("extension.uninstalled", { pluginId });
670
+ return asJsonResponse({
671
+ success: true,
672
+ pluginId
673
+ });
674
+ }
675
+ async handleWebhookCreate(args) {
676
+ const name = argStringRequired(args, "name");
677
+ const webhookPath = argStringRequired(args, "path");
678
+ const secret = argString(args, "secret");
679
+ const events = Array.isArray(args.events) ? args.events.filter((e) => typeof e === "string") : [];
680
+ const server = this.getWebhookServer();
681
+ if (!server.isRunning()) server.start();
682
+ const endpointId = server.registerEndpoint({
683
+ path: webhookPath,
684
+ method: "POST",
685
+ secret: secret ?? void 0
686
+ });
687
+ const bridge = this.getWebhook();
688
+ const baseUrl = `http://localhost:${server.getPort()}${webhookPath}`;
689
+ bridge.registerExternalCallback(endpointId, baseUrl);
690
+ return asJsonResponse({
691
+ success: true,
692
+ endpointId,
693
+ url: baseUrl,
694
+ name,
695
+ events
696
+ });
697
+ }
698
+ async handleWebhookList() {
699
+ const server = this.getWebhookServer();
700
+ return asJsonResponse({
701
+ success: true,
702
+ endpoints: server.listEndpoints(),
703
+ port: server.getPort(),
704
+ running: server.isRunning()
705
+ });
706
+ }
707
+ async handleWebhookDelete(args) {
708
+ const endpointId = argStringRequired(args, "endpointId");
709
+ const server = this.getWebhookServer();
710
+ try {
711
+ server.removeEndpoint(endpointId);
712
+ } catch (err) {
713
+ throw new Error(`GRACEFUL: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
714
+ }
715
+ return asJsonResponse({
716
+ success: true,
717
+ endpointId
718
+ });
719
+ }
720
+ async handleWebhookCommands(args) {
721
+ const endpointId = argStringRequired(args, "endpointId");
722
+ const status = argString(args, "status");
723
+ const command = argObject(args, "command");
724
+ if (command) return asJsonResponse({
725
+ success: true,
726
+ commandId: this.getCommandQueue().enqueue({
727
+ endpointId,
728
+ payload: command
729
+ }),
730
+ status: "pending"
731
+ });
732
+ const queue = this.getCommandQueue();
733
+ const filter = { endpointId };
734
+ if (status) filter.status = status;
735
+ const commands = queue.dequeue(filter);
736
+ return asJsonResponse({
737
+ success: true,
738
+ endpointId,
739
+ commands,
740
+ count: Array.isArray(commands) ? commands.length : commands ? 1 : 0
741
+ });
742
+ }
743
+ getWebhookServer() {
744
+ if (!this._webhookServer) {
745
+ this._commandQueue = new CommandQueue();
746
+ this._webhookServer = new WebhookServer({ commandQueue: this._commandQueue });
747
+ }
748
+ return this._webhookServer;
749
+ }
750
+ async startWebhookServer() {
751
+ const server = this.getWebhookServer();
752
+ if (!server.isRunning()) server.start();
753
+ }
754
+ async stopWebhookServer() {
755
+ if (this._webhookServer) {
756
+ await this._webhookServer.stop();
757
+ this._webhookServer = void 0;
758
+ this._commandQueue = void 0;
759
+ }
760
+ }
761
+ getRegistry() {
762
+ if (!this.registry) this.registry = new PluginRegistry();
763
+ return this.registry;
764
+ }
765
+ getWebhook() {
766
+ if (!this.webhook) this.webhook = new WebhookBridge();
767
+ return this.webhook;
768
+ }
769
+ getCommandQueue() {
770
+ if (!this._commandQueue) this._commandQueue = new CommandQueue();
771
+ return this._commandQueue;
772
+ }
773
+ emitEvent(event, payload) {
774
+ this.getWebhook().sendEvent(event, payload).catch(() => void 0);
775
+ }
776
+ resolveContext(exportsRecord, contextName) {
777
+ const directContext = exportsRecord[contextName];
778
+ if (isCallable(directContext)) return directContext;
779
+ const defaultExport = exportsRecord.default;
780
+ if (contextName === "default" && isCallable(defaultExport)) return defaultExport;
781
+ if (isRecord(defaultExport)) {
782
+ const nestedContext = defaultExport[contextName];
783
+ if (isCallable(nestedContext)) return nestedContext;
784
+ }
785
+ return null;
786
+ }
787
+ async handleWebhookDispatch(args) {
788
+ const action = argString(args, "action");
789
+ switch (action) {
790
+ case "create": return this.handleWebhookCreate(args);
791
+ case "list": return this.handleWebhookList();
792
+ case "delete": return this.handleWebhookDelete(args);
793
+ case "commands": return this.handleWebhookCommands(args);
794
+ default: return asJsonResponse({ error: `Invalid action: "${action}". Expected one of: create, list, delete, commands` });
795
+ }
796
+ }
797
+ };
798
+ //#endregion
799
+ export { ExtensionRegistryHandlers };