@jshookmcp/jshook 0.2.8 → 0.3.0

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 (162) hide show
  1. package/README.md +36 -5
  2. package/README.zh.md +36 -5
  3. package/dist/{AntiCheatDetector-S8VRj-dD.mjs → AntiCheatDetector-CqGDXmfc.mjs} +160 -54
  4. package/dist/{CodeInjector-4Z3ngPoX.mjs → CodeInjector-BdjRfNx7.mjs} +5 -5
  5. package/dist/ConsoleMonitor-DykL3IAw.mjs +2269 -0
  6. package/dist/{DarwinAPI-B8hg_yhz.mjs → DarwinAPI-ETyy0xyo.mjs} +1 -1
  7. package/dist/DetailedDataManager-HT49OrvF.mjs +217 -0
  8. package/dist/EventBus-DFKvADm3.mjs +141 -0
  9. package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +153 -0
  10. package/dist/{ExtensionManager-D5-bO9D8.mjs → ExtensionManager-BDMsY2Dz.mjs} +27 -13
  11. package/dist/{FingerprintManager-BVxFJL2-.mjs → FingerprintManager-BN4UQWnX.mjs} +1 -1
  12. package/dist/{HardwareBreakpoint-DK1yjWkV.mjs → HardwareBreakpoint-Cc2AFq1Y.mjs} +3 -3
  13. package/dist/{HeapAnalyzer-CEbo10xU.mjs → HeapAnalyzer-DruMgsgj.mjs} +21 -21
  14. package/dist/HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs +566 -0
  15. package/dist/InstrumentationSession-DLH0vd-z.mjs +244 -0
  16. package/dist/{MemoryController-DdtnBdD4.mjs → MemoryController-CMtviNW_.mjs} +3 -3
  17. package/dist/{MemoryScanSession-RMixN3bX.mjs → MemoryScanSession-ITgb_NMi.mjs} +81 -78
  18. package/dist/{MemoryScanner-QjK4ld0B.mjs → MemoryScanner-CiL7Z3ey.mjs} +50 -21
  19. package/dist/{NativeMemoryManager.impl-CB6gJ0NM.mjs → NativeMemoryManager.impl-D9Lkovvn.mjs} +20 -56
  20. package/dist/{NativeMemoryManager.utils-BML4q1ry.mjs → NativeMemoryManager.utils-BBlAixF5.mjs} +1 -1
  21. package/dist/{PEAnalyzer-CK0xe0Fs.mjs → PEAnalyzer-DMQ44gen.mjs} +16 -16
  22. package/dist/PageController-BPJNqqBN.mjs +431 -0
  23. package/dist/{PointerChainEngine-Cd73qu5b.mjs → PointerChainEngine-K7wN8Z-w.mjs} +10 -7
  24. package/dist/PrerequisiteError-TuyZIs6n.mjs +20 -0
  25. package/dist/ProcessRegistry-zGg12QbE.mjs +74 -0
  26. package/dist/ResponseBuilder-CJXWmWNw.mjs +143 -0
  27. package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +269 -0
  28. package/dist/ScriptManager-ZuWD-0Jg.mjs +3003 -0
  29. package/dist/{Speedhack-CeF0XmEz.mjs → Speedhack-D-z0umeT.mjs} +2 -2
  30. package/dist/{StructureAnalyzer-D4GkMduU.mjs → StructureAnalyzer-Cav5AVSL.mjs} +9 -6
  31. package/dist/ToolCatalog-5OJdMiF0.mjs +582 -0
  32. package/dist/ToolError-jh9whhMd.mjs +15 -0
  33. package/dist/ToolProbe-DbCFGyrg.mjs +45 -0
  34. package/dist/ToolRegistry-B9krbTtI.mjs +180 -0
  35. package/dist/ToolRouter.policy-BGDAGyeH.mjs +344 -0
  36. package/dist/TraceRecorder-B41Z5XBj.mjs +1286 -0
  37. package/dist/{Win32API-Bc0QnQsN.mjs → Win32API-C2kjj0ze.mjs} +19 -13
  38. package/dist/{Win32Debug-DUHt9XUn.mjs → Win32Debug-CKrGOTpo.mjs} +3 -3
  39. package/dist/WorkflowEngine-DJ6M4opp.mjs +569 -0
  40. package/dist/analysis-BHeJW2Nb.mjs +1234 -0
  41. package/dist/antidebug-BRKeyt27.mjs +1081 -0
  42. package/dist/artifactRetention-CPXkUJXp.mjs +598 -0
  43. package/dist/artifacts-DkfosXH3.mjs +59 -0
  44. package/dist/authorization-schema-DRqyJMSk.mjs +31 -0
  45. package/dist/betterSqlite3-DLSBZodi.mjs +74 -0
  46. package/dist/binary-instrument--V3MAhJ4.mjs +971 -0
  47. package/dist/bind-helpers-ClV34xdn.mjs +42 -0
  48. package/dist/boringssl-inspector-Bo_LOLaS.mjs +180 -0
  49. package/dist/browser-Dx3_S2cG.mjs +4369 -0
  50. package/dist/capabilities-CcHlvWgK.mjs +33 -0
  51. package/dist/concurrency-Drev_Vz9.mjs +41 -0
  52. package/dist/{constants-CCvsN80K.mjs → constants-CDZLOoVv.mjs} +105 -48
  53. package/dist/coordination-DgItD9DL.mjs +259 -0
  54. package/dist/debugger-RS3RSAqs.mjs +1288 -0
  55. package/dist/definitions-BEoYofW5.mjs +47 -0
  56. package/dist/definitions-BRaefg3u.mjs +365 -0
  57. package/dist/definitions-BbkvZkiv.mjs +96 -0
  58. package/dist/definitions-BtWSHJ3o.mjs +17 -0
  59. package/dist/definitions-C1gCHO0i.mjs +43 -0
  60. package/dist/definitions-CDOg_b-l.mjs +138 -0
  61. package/dist/definitions-CVPD9hzZ.mjs +54 -0
  62. package/dist/definitions-Cea8Lgl7.mjs +94 -0
  63. package/dist/definitions-DAgIyjxM.mjs +10 -0
  64. package/dist/definitions-DJA27nsL.mjs +66 -0
  65. package/dist/definitions-DKPFU3LW.mjs +25 -0
  66. package/dist/definitions-DPRpZQ96.mjs +47 -0
  67. package/dist/definitions-DUE5gmdn.mjs +18 -0
  68. package/dist/definitions-DYVjOtxa.mjs +26 -0
  69. package/dist/definitions-DcYLVLCo.mjs +37 -0
  70. package/dist/definitions-Pp5LI2H4.mjs +27 -0
  71. package/dist/definitions-j9KdHVNR.mjs +14 -0
  72. package/dist/definitions-uzkjBwa7.mjs +258 -0
  73. package/dist/definitions-va-AnLuQ.mjs +28 -0
  74. package/dist/encoding-DJeqHmpd.mjs +1079 -0
  75. package/dist/evidence-graph-bridge-DcYizFk2.mjs +136 -0
  76. package/dist/{factory-CibqTNC8.mjs → factory-C90tBff6.mjs} +41 -56
  77. package/dist/flat-target-session-Dgax2Cy3.mjs +29 -0
  78. package/dist/graphql-CoHrhweh.mjs +1197 -0
  79. package/dist/handlers-4jmR0nMs.mjs +898 -0
  80. package/dist/handlers-BAHPxcch.mjs +789 -0
  81. package/dist/handlers-BOs9b907.mjs +2600 -0
  82. package/dist/handlers-BWXEy6ef.mjs +917 -0
  83. package/dist/handlers-Bndn6QvE.mjs +111 -0
  84. package/dist/handlers-BqC4bD4s.mjs +681 -0
  85. package/dist/handlers-BtYq60bM2.mjs +276 -0
  86. package/dist/handlers-BzgcB4iv.mjs +799 -0
  87. package/dist/handlers-CRyRWj2b.mjs +859 -0
  88. package/dist/handlers-CVv2H1uq.mjs +592 -0
  89. package/dist/handlers-Dl5a7JS4.mjs +572 -0
  90. package/dist/handlers-Dx2d7jt7.mjs +2537 -0
  91. package/dist/handlers-Dz9PYsCa.mjs +2805 -0
  92. package/dist/handlers-HujRKC3b.mjs +661 -0
  93. package/dist/handlers.impl-XWXkQfyi.mjs +807 -0
  94. package/dist/hooks-B1B8NRHL.mjs +898 -0
  95. package/dist/index.mjs +491 -259
  96. package/dist/{logger-BmWzC2lM.mjs → logger-Dh_xb7_2.mjs} +14 -6
  97. package/dist/maintenance-PRMkLVRW.mjs +835 -0
  98. package/dist/manifest-67Bok-Si.mjs +58 -0
  99. package/dist/manifest-6lNTMZAB2.mjs +87 -0
  100. package/dist/manifest-B2duEHiH.mjs +90 -0
  101. package/dist/manifest-B6EY9Vm8.mjs +57 -0
  102. package/dist/manifest-B6nKSbyY.mjs +95 -0
  103. package/dist/manifest-BL8AQNPF.mjs +106 -0
  104. package/dist/manifest-BSZvJJmV.mjs +47 -0
  105. package/dist/manifest-BU7qzUyX.mjs +418 -0
  106. package/dist/manifest-Bl62e8WK.mjs +49 -0
  107. package/dist/manifest-Bo5cXjdt.mjs +82 -0
  108. package/dist/manifest-BpS4gtUK.mjs +1347 -0
  109. package/dist/manifest-Bv65_e2W.mjs +101 -0
  110. package/dist/manifest-BytNIF4Z.mjs +117 -0
  111. package/dist/manifest-C-xtsjS3.mjs +81 -0
  112. package/dist/manifest-CDYl7OhA.mjs +66 -0
  113. package/dist/manifest-CRZ3xmkD.mjs +61 -0
  114. package/dist/manifest-CoW6u4Tp.mjs +132 -0
  115. package/dist/manifest-Cq5zN_8A.mjs +50 -0
  116. package/dist/manifest-D7YZM_2e.mjs +194 -0
  117. package/dist/manifest-DE_VrAeQ.mjs +314 -0
  118. package/dist/manifest-DGsXSCpT.mjs +39 -0
  119. package/dist/manifest-DJ2vfEuW.mjs +156 -0
  120. package/dist/manifest-DPXDYhEu.mjs +80 -0
  121. package/dist/manifest-Dd4fQb0a.mjs +322 -0
  122. package/dist/manifest-Deq6opGg.mjs +223 -0
  123. package/dist/manifest-DfJTafJK.mjs +37 -0
  124. package/dist/manifest-DgOdgN_j.mjs +50 -0
  125. package/dist/manifest-DlbMW4v4.mjs +47 -0
  126. package/dist/manifest-DmVfbH0w.mjs +374 -0
  127. package/dist/manifest-Dog6Ddjr.mjs +109 -0
  128. package/dist/manifest-DvgU5FWb.mjs +58 -0
  129. package/dist/manifest-HsfDBs7j.mjs +50 -0
  130. package/dist/manifest-I8oQHvCG.mjs +186 -0
  131. package/dist/manifest-NvH_a-av.mjs +786 -0
  132. package/dist/manifest-cEJU1v0Z.mjs +129 -0
  133. package/dist/manifest-wOl5XLB12.mjs +112 -0
  134. package/dist/modules-tZozf0LQ.mjs +10635 -0
  135. package/dist/mojo-ipc-DXNEXEqb.mjs +640 -0
  136. package/dist/network-CPVvwvFg.mjs +3852 -0
  137. package/dist/{artifacts-BbdOMET5.mjs → outputPaths-um7lCRY3.mjs} +219 -216
  138. package/dist/parse-args-B4cY5Vx5.mjs +39 -0
  139. package/dist/platform-CYeFoTWp.mjs +2161 -0
  140. package/dist/process-BTbgcVc6.mjs +1306 -0
  141. package/dist/proxy-r8YN6nP1.mjs +192 -0
  142. package/dist/registry-Bl8ZQW61.mjs +34 -0
  143. package/dist/response-CWhh2aLo.mjs +34 -0
  144. package/dist/server/plugin-api.mjs +2 -2
  145. package/dist/shared-state-board-BoZnSoj-.mjs +586 -0
  146. package/dist/sourcemap-BIDHUVXy.mjs +934 -0
  147. package/dist/ssrf-policy-Dsqd-DTX.mjs +166 -0
  148. package/dist/streaming-Dal6utPp.mjs +725 -0
  149. package/dist/tool-builder-BHJp32mV.mjs +186 -0
  150. package/dist/transform-DRVgGG90.mjs +1011 -0
  151. package/dist/types-Bx92KJfT.mjs +4 -0
  152. package/dist/wasm-BYx5UOeG.mjs +1044 -0
  153. package/dist/webcrack-Be0_FccV.mjs +747 -0
  154. package/dist/workflow-BpuKEtvn.mjs +725 -0
  155. package/package.json +82 -49
  156. package/dist/ExtensionManager-CPTJhHFg.mjs +0 -2
  157. package/dist/ToolCatalog-Bq4V2sbJ.mjs +0 -67201
  158. package/dist/{CacheAdapters-CzFNpD9a.mjs → CacheAdapters-jJFy20G-.mjs} +0 -0
  159. package/dist/{StealthVerifier-BzBCFiwx.mjs → StealthVerifier-BWmPgQsv.mjs} +0 -0
  160. package/dist/{VersionDetector-CNXcvD46.mjs → VersionDetector-K3V4vGsw.mjs} +0 -0
  161. package/dist/{formatAddress-ChCSIRWT.mjs → formatAddress-nnMvEohD.mjs} +0 -0
  162. package/dist/{types-BBjOqye-.mjs → types-DDBWs9UP.mjs} +1 -1
@@ -0,0 +1,598 @@
1
+ import { t as logger } from "./logger-Dh_xb7_2.mjs";
2
+ import { b as CACHE_LOW_HIT_RATE_THRESHOLD, hr as TOKEN_BUDGET_MAX_TOKENS, y as CACHE_GLOBAL_MAX_SIZE_BYTES } from "./constants-CDZLOoVv.mjs";
3
+ import { c as getConfig, i as getProjectRoot, n as getDebuggerSessionsDir } from "./outputPaths-um7lCRY3.mjs";
4
+ import { n as getArtifactDir, r as getArtifactsRoot } from "./artifacts-DkfosXH3.mjs";
5
+ import { join, resolve } from "node:path";
6
+ import { readdir, rm, stat } from "node:fs/promises";
7
+ //#region src/utils/TokenBudgetManager.ts
8
+ var TokenBudgetManager = class TokenBudgetManager {
9
+ static instance;
10
+ MAX_TOKENS = TOKEN_BUDGET_MAX_TOKENS;
11
+ WARNING_THRESHOLDS = [
12
+ .8,
13
+ .9,
14
+ .95
15
+ ];
16
+ BYTES_PER_TOKEN = 4;
17
+ AUTO_CLEANUP_THRESHOLD = .9;
18
+ HISTORY_RETENTION = 300 * 1e3;
19
+ currentUsage = 0;
20
+ toolCallHistory = [];
21
+ warnings = /* @__PURE__ */ new Set();
22
+ sessionStartTime = Date.now();
23
+ trackingEnabled = true;
24
+ MAX_ESTIMATION_DEPTH = 4;
25
+ MAX_ESTIMATION_ARRAY_ITEMS = 50;
26
+ MAX_ESTIMATION_OBJECT_KEYS = 50;
27
+ MAX_ESTIMATION_STRING_LENGTH = 2e3;
28
+ MAX_ESTIMATION_BYTES = 256 * 1024;
29
+ externalCleanupFn = null;
30
+ constructor() {
31
+ logger.info("TokenBudgetManager initialized");
32
+ }
33
+ /** @deprecated Use constructor injection. Kept for backward compatibility. */
34
+ static getInstance() {
35
+ if (!this.instance) this.instance = new TokenBudgetManager();
36
+ return this.instance;
37
+ }
38
+ /**
39
+ * Register a callback invoked during auto-cleanup to clear external caches.
40
+ * This replaces the previous hard dependency on DetailedDataManager.getInstance().
41
+ */
42
+ setExternalCleanup(fn) {
43
+ this.externalCleanupFn = fn;
44
+ }
45
+ recordToolCall(toolName, request, response) {
46
+ if (!this.trackingEnabled) return;
47
+ try {
48
+ const requestSize = this.calculateSize(request);
49
+ const responseSize = this.calculateSize(response);
50
+ const totalSize = requestSize + responseSize;
51
+ const estimatedTokens = this.estimateTokens(totalSize);
52
+ this.currentUsage += estimatedTokens;
53
+ const record = {
54
+ toolName,
55
+ timestamp: Date.now(),
56
+ requestSize,
57
+ responseSize,
58
+ estimatedTokens,
59
+ cumulativeTokens: this.currentUsage
60
+ };
61
+ this.toolCallHistory.push(record);
62
+ logger.debug(`Token usage: ${this.currentUsage}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%) | Tool: ${toolName} | Size: ${(totalSize / 1024).toFixed(1)}KB | Tokens: ${estimatedTokens}`);
63
+ this.checkWarnings();
64
+ if (this.shouldAutoCleanup()) this.autoCleanup();
65
+ } catch (error) {
66
+ logger.error("Failed to record tool call:", error);
67
+ }
68
+ }
69
+ isRecord(value) {
70
+ return value !== null && typeof value === "object";
71
+ }
72
+ hasDetailedSummarySize(value) {
73
+ if (!this.isRecord(value) || !("detailId" in value)) return false;
74
+ const summary = value.summary;
75
+ if (!this.isRecord(summary)) return false;
76
+ const { size } = summary;
77
+ return typeof size === "number" && Number.isFinite(size) && size > 0;
78
+ }
79
+ /**
80
+ * Fast path for common MCP tool response envelopes:
81
+ * { content: [{ type: 'text', text: string }], isError?: boolean }
82
+ *
83
+ * Avoids full recursive normalization by estimating size directly from
84
+ * the text payload with the same truncation semantics.
85
+ */
86
+ tryEstimateMcpEnvelope(data) {
87
+ if (!this.isRecord(data)) return null;
88
+ const content = data["content"];
89
+ if (!Array.isArray(content) || content.length === 0) return null;
90
+ const first = content[0];
91
+ if (!this.isRecord(first)) return null;
92
+ if (first["type"] !== "text" || typeof first["text"] !== "string") return null;
93
+ const text = first["text"];
94
+ const truncated = text.length > this.MAX_ESTIMATION_STRING_LENGTH ? `${text.slice(0, this.MAX_ESTIMATION_STRING_LENGTH)}...[truncated:${text.length}]` : text;
95
+ const overhead = 42 + (data["isError"] === true ? 14 : 0);
96
+ const textBytes = Buffer.byteLength(truncated, "utf8");
97
+ return Math.min(overhead + textBytes, this.MAX_ESTIMATION_BYTES);
98
+ }
99
+ calculateSize(data) {
100
+ try {
101
+ if (this.hasDetailedSummarySize(data)) return Math.min(data.summary.size, this.MAX_ESTIMATION_BYTES);
102
+ const mcpSize = this.tryEstimateMcpEnvelope(data);
103
+ if (mcpSize !== null) return mcpSize;
104
+ const normalized = this.normalizeForSizeEstimate(data, 0, /* @__PURE__ */ new WeakSet());
105
+ const serialized = JSON.stringify(normalized);
106
+ if (!serialized) return 0;
107
+ return Math.min(Buffer.byteLength(serialized, "utf8"), this.MAX_ESTIMATION_BYTES);
108
+ } catch (error) {
109
+ logger.warn("Failed to calculate data size:", error);
110
+ return 0;
111
+ }
112
+ }
113
+ normalizeForSizeEstimate(value, depth, seen) {
114
+ if (value === null || value === void 0) return value;
115
+ const valueType = typeof value;
116
+ if (valueType === "boolean" || valueType === "number") return value;
117
+ if (valueType === "string") {
118
+ const stringValue = value;
119
+ if (stringValue.length <= this.MAX_ESTIMATION_STRING_LENGTH) return stringValue;
120
+ const marker = `...[truncated:${stringValue.length}]`;
121
+ const maxPrefixLength = Math.max(this.MAX_ESTIMATION_STRING_LENGTH - marker.length, 0);
122
+ return `${stringValue.slice(0, maxPrefixLength)}${marker}`;
123
+ }
124
+ if (valueType === "bigint") return value.toString();
125
+ if (valueType === "symbol") return value.toString();
126
+ if (valueType === "function") return "[Function]";
127
+ if (value instanceof Error) return {
128
+ name: value.name,
129
+ message: value.message,
130
+ stack: value.stack?.slice(0, this.MAX_ESTIMATION_STRING_LENGTH)
131
+ };
132
+ if (Buffer.isBuffer(value)) return `[Buffer:${value.byteLength}]`;
133
+ if (depth >= this.MAX_ESTIMATION_DEPTH) {
134
+ if (Array.isArray(value)) return `[Array:${value.length}]`;
135
+ return "[Object]";
136
+ }
137
+ if (Array.isArray(value)) {
138
+ const limited = value.slice(0, this.MAX_ESTIMATION_ARRAY_ITEMS).map((item) => this.normalizeForSizeEstimate(item, depth + 1, seen));
139
+ if (value.length > this.MAX_ESTIMATION_ARRAY_ITEMS) limited.push(`[truncated:${value.length - this.MAX_ESTIMATION_ARRAY_ITEMS}]`);
140
+ return limited;
141
+ }
142
+ if (valueType === "object") {
143
+ /* v8 ignore next 3 */
144
+ if (!this.isRecord(value)) return "[Object]";
145
+ if (seen.has(value)) return "[Circular]";
146
+ seen.add(value);
147
+ const entries = Object.entries(value);
148
+ const limitedEntries = entries.slice(0, this.MAX_ESTIMATION_OBJECT_KEYS);
149
+ const out = {};
150
+ for (const [key, nestedValue] of limitedEntries) out[key] = this.normalizeForSizeEstimate(nestedValue, depth + 1, seen);
151
+ if (entries.length > this.MAX_ESTIMATION_OBJECT_KEYS) out.__truncatedKeys = entries.length - this.MAX_ESTIMATION_OBJECT_KEYS;
152
+ return out;
153
+ }
154
+ /* v8 ignore next */
155
+ return String(value);
156
+ }
157
+ estimateTokens(bytes) {
158
+ return Math.ceil(bytes / this.BYTES_PER_TOKEN);
159
+ }
160
+ getUsagePercentage() {
161
+ return Math.round(this.currentUsage / this.MAX_TOKENS * 100);
162
+ }
163
+ checkWarnings() {
164
+ const ratio = this.currentUsage / this.MAX_TOKENS;
165
+ for (const threshold of this.WARNING_THRESHOLDS) if (ratio >= threshold && !this.warnings.has(threshold)) {
166
+ this.emitWarning(threshold);
167
+ this.warnings.add(threshold);
168
+ }
169
+ }
170
+ emitWarning(threshold) {
171
+ const percentage = Math.round(threshold * 100);
172
+ const remaining = this.MAX_TOKENS - this.currentUsage;
173
+ logger.warn(`Token Budget Warning: ${percentage}% used! (${this.currentUsage}/${this.MAX_TOKENS}, ${remaining} tokens remaining)`);
174
+ if (threshold >= .95) logger.warn("CRITICAL: Consider clearing caches or starting a new session.");
175
+ else if (threshold >= .9) logger.warn("HIGH: Auto-cleanup will trigger soon. Consider using summary modes.");
176
+ else if (threshold >= .8) logger.warn("MODERATE: Monitor usage. Use get_token_budget_stats for details.");
177
+ }
178
+ shouldAutoCleanup() {
179
+ return this.currentUsage / this.MAX_TOKENS >= this.AUTO_CLEANUP_THRESHOLD;
180
+ }
181
+ autoCleanup() {
182
+ logger.info("Auto-cleanup triggered at 90% usage.");
183
+ const beforeUsage = this.currentUsage;
184
+ if (this.externalCleanupFn) try {
185
+ this.externalCleanupFn();
186
+ logger.info("External cleanup callback invoked");
187
+ } catch (e) {
188
+ logger.warn("External cleanup callback failed:", e);
189
+ }
190
+ const cutoff = Date.now() - this.HISTORY_RETENTION;
191
+ const beforeCount = this.toolCallHistory.length;
192
+ this.toolCallHistory = this.toolCallHistory.filter((call) => call.timestamp > cutoff);
193
+ const removedCount = beforeCount - this.toolCallHistory.length;
194
+ logger.info(`Removed ${removedCount} old tool call records`);
195
+ this.recalculateUsage();
196
+ const afterUsage = this.currentUsage;
197
+ const freed = beforeUsage - afterUsage;
198
+ const freedPercentage = Math.round(freed / this.MAX_TOKENS * 100);
199
+ logger.info(`Cleanup complete. Freed ${freed} tokens (${freedPercentage}%). Usage: ${afterUsage}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%)`);
200
+ const newRatio = afterUsage / this.MAX_TOKENS;
201
+ this.warnings = new Set(Array.from(this.warnings).filter((threshold) => newRatio >= threshold));
202
+ }
203
+ recalculateUsage() {
204
+ this.currentUsage = this.toolCallHistory.reduce((sum, call) => sum + call.estimatedTokens, 0);
205
+ }
206
+ getStats() {
207
+ const toolUsage = /* @__PURE__ */ new Map();
208
+ for (const call of this.toolCallHistory) {
209
+ const current = toolUsage.get(call.toolName) || 0;
210
+ toolUsage.set(call.toolName, current + call.estimatedTokens);
211
+ }
212
+ const topTools = Array.from(toolUsage.entries()).map(([tool, tokens]) => ({
213
+ tool,
214
+ tokens,
215
+ percentage: Math.round(tokens / this.currentUsage * 100)
216
+ })).toSorted((a, b) => b.tokens - a.tokens).slice(0, 10);
217
+ const suggestions = this.generateSuggestions(topTools);
218
+ const recentCalls = this.toolCallHistory.slice(-20);
219
+ return {
220
+ currentUsage: this.currentUsage,
221
+ maxTokens: this.MAX_TOKENS,
222
+ usagePercentage: this.getUsagePercentage(),
223
+ toolCallCount: this.toolCallHistory.length,
224
+ topTools,
225
+ warnings: Array.from(this.warnings).map((t) => Math.round(t * 100)),
226
+ recentCalls,
227
+ suggestions,
228
+ sessionStartTime: this.sessionStartTime
229
+ };
230
+ }
231
+ generateSuggestions(topTools) {
232
+ const suggestions = [];
233
+ const ratio = this.currentUsage / this.MAX_TOKENS;
234
+ if (ratio >= .95) suggestions.push(" CRITICAL: Clear all caches immediately or start a new session");
235
+ else if (ratio >= .9) suggestions.push("HIGH: Auto-cleanup triggered. Consider manual cleanup for better control");
236
+ else if (ratio >= .8) suggestions.push("MODERATE: Monitor usage closely. Use summary modes for large data");
237
+ for (const { tool, percentage } of topTools) if (percentage > 30) {
238
+ if (tool.includes("collect_code")) suggestions.push(` ${tool} uses ${percentage}% tokens. Try smartMode="summary" or "priority"`);
239
+ else if (tool.includes("get_script_source")) suggestions.push(` ${tool} uses ${percentage}% tokens. Try preview=true first`);
240
+ else if (tool.includes("network_get_requests")) suggestions.push(` ${tool} uses ${percentage}% tokens. Reduce limit or use filters`);
241
+ else if (tool.includes("page_evaluate")) suggestions.push(` ${tool} uses ${percentage}% tokens. Query specific properties instead of full objects`);
242
+ }
243
+ if (suggestions.length === 0) suggestions.push(" Token usage is healthy. Continue monitoring.");
244
+ return suggestions;
245
+ }
246
+ manualCleanup() {
247
+ logger.info("Manual cleanup requested.");
248
+ this.autoCleanup();
249
+ }
250
+ setTrackingEnabled(enabled) {
251
+ if (this.trackingEnabled === enabled) return;
252
+ this.trackingEnabled = enabled;
253
+ logger.warn(`Token budget tracking ${enabled ? "enabled" : "disabled"}`);
254
+ }
255
+ isTrackingEnabled() {
256
+ return this.trackingEnabled;
257
+ }
258
+ reset() {
259
+ logger.info("Resetting token budget...");
260
+ this.currentUsage = 0;
261
+ this.toolCallHistory = [];
262
+ this.warnings.clear();
263
+ this.sessionStartTime = Date.now();
264
+ logger.info("Token budget reset complete");
265
+ }
266
+ };
267
+ //#endregion
268
+ //#region src/utils/UnifiedCacheManager.ts
269
+ var UnifiedCacheManager = class UnifiedCacheManager {
270
+ static instance;
271
+ GLOBAL_MAX_SIZE = CACHE_GLOBAL_MAX_SIZE_BYTES;
272
+ LOW_HIT_RATE_THRESHOLD = CACHE_LOW_HIT_RATE_THRESHOLD;
273
+ caches = /* @__PURE__ */ new Map();
274
+ constructor() {
275
+ logger.info("UnifiedCacheManager initialized");
276
+ }
277
+ /** @deprecated Use constructor injection. Kept for backward compatibility. */
278
+ static getInstance() {
279
+ if (!this.instance) this.instance = new UnifiedCacheManager();
280
+ return this.instance;
281
+ }
282
+ registerCache(cache) {
283
+ this.caches.set(cache.name, cache);
284
+ logger.info(`Registered cache: ${cache.name}`);
285
+ }
286
+ unregisterCache(name) {
287
+ this.caches.delete(name);
288
+ logger.info(`Unregistered cache: ${name}`);
289
+ }
290
+ async getGlobalStats() {
291
+ let totalEntries = 0;
292
+ let totalSize = 0;
293
+ let totalHits = 0;
294
+ let totalMisses = 0;
295
+ const cacheStats = [];
296
+ for (const [name, cache] of this.caches) try {
297
+ const stats = await cache.getStats();
298
+ totalEntries += stats.entries;
299
+ totalSize += stats.size;
300
+ totalHits += stats.hits || 0;
301
+ totalMisses += stats.misses || 0;
302
+ cacheStats.push({
303
+ name,
304
+ entries: stats.entries,
305
+ size: stats.size,
306
+ sizeMB: (stats.size / 1024 / 1024).toFixed(2),
307
+ hitRate: stats.hitRate,
308
+ ttl: stats.ttl
309
+ });
310
+ } catch (error) {
311
+ logger.error(`Failed to get stats for cache ${name}:`, error);
312
+ }
313
+ const hitRate = totalHits + totalMisses > 0 ? totalHits / (totalHits + totalMisses) : 0;
314
+ const recommendations = this.generateRecommendations(totalSize, hitRate, cacheStats);
315
+ return {
316
+ totalEntries,
317
+ totalSize,
318
+ totalSizeMB: (totalSize / 1024 / 1024).toFixed(2),
319
+ hitRate,
320
+ caches: cacheStats,
321
+ recommendations
322
+ };
323
+ }
324
+ async smartCleanup(targetSize) {
325
+ const target = targetSize || this.GLOBAL_MAX_SIZE * .7;
326
+ const beforeStats = await this.getGlobalStats();
327
+ const beforeSize = beforeStats.totalSize;
328
+ if (beforeSize <= target) {
329
+ logger.info("No cleanup needed");
330
+ return {
331
+ before: beforeSize,
332
+ after: beforeSize,
333
+ freed: 0,
334
+ freedPercentage: 0
335
+ };
336
+ }
337
+ logger.info(`Smart cleanup: current ${beforeStats.totalSizeMB}MB, target ${(target / 1024 / 1024).toFixed(2)}MB`);
338
+ await this.cleanupExpired();
339
+ let currentStats = await this.getGlobalStats();
340
+ if (currentStats.totalSize <= target) return this.calculateCleanupResult(beforeSize, currentStats.totalSize);
341
+ await this.cleanupLowHitRate();
342
+ currentStats = await this.getGlobalStats();
343
+ if (currentStats.totalSize <= target) return this.calculateCleanupResult(beforeSize, currentStats.totalSize);
344
+ await this.cleanupLargeItems();
345
+ const afterStats = await this.getGlobalStats();
346
+ return this.calculateCleanupResult(beforeSize, afterStats.totalSize);
347
+ }
348
+ async cleanupExpired() {
349
+ logger.info("Cleaning up expired data...");
350
+ for (const [name, cache] of this.caches) if (cache.cleanup) try {
351
+ await cache.cleanup();
352
+ logger.debug(`Cleaned up expired data in ${name}`);
353
+ } catch (error) {
354
+ logger.error(`Failed to cleanup ${name}:`, error);
355
+ }
356
+ }
357
+ async cleanupLowHitRate() {
358
+ logger.info("Cleaning up low hit rate caches...");
359
+ const stats = await this.getGlobalStats();
360
+ const avgHitRate = stats.hitRate;
361
+ for (const cacheStats of stats.caches) if (cacheStats.hitRate !== void 0 && cacheStats.hitRate < avgHitRate * this.LOW_HIT_RATE_THRESHOLD) {
362
+ const cache = this.caches.get(cacheStats.name);
363
+ /* v8 ignore next */
364
+ if (cache?.clear) try {
365
+ await cache.clear();
366
+ logger.info(`Cleared low hit rate cache: ${cacheStats.name} (${(cacheStats.hitRate * 100).toFixed(1)}%)`);
367
+ } catch (error) {
368
+ logger.error(`Failed to clear ${cacheStats.name}:`, error);
369
+ }
370
+ }
371
+ }
372
+ async cleanupLargeItems() {
373
+ logger.info("Cleaning up large caches...");
374
+ const sortedCaches = (await this.getGlobalStats()).caches.toSorted((a, b) => b.size - a.size);
375
+ for (const cacheStats of sortedCaches.slice(0, 2)) {
376
+ const cache = this.caches.get(cacheStats.name);
377
+ /* v8 ignore next */
378
+ if (cache?.clear) try {
379
+ await cache.clear();
380
+ logger.info(`Cleared large cache: ${cacheStats.name} (${cacheStats.sizeMB}MB)`);
381
+ } catch (error) {
382
+ logger.error(`Failed to clear ${cacheStats.name}:`, error);
383
+ }
384
+ }
385
+ }
386
+ calculateCleanupResult(before, after) {
387
+ const freed = before - after;
388
+ const freedPercentage = Math.round(freed / this.GLOBAL_MAX_SIZE * 100);
389
+ logger.info(`Cleanup complete! Freed ${(freed / 1024 / 1024).toFixed(2)}MB (${freedPercentage}%). Usage: ${(after / 1024 / 1024).toFixed(2)}MB/${(this.GLOBAL_MAX_SIZE / 1024 / 1024).toFixed(0)}MB`);
390
+ return {
391
+ before,
392
+ after,
393
+ freed,
394
+ freedPercentage
395
+ };
396
+ }
397
+ async clearAll() {
398
+ logger.info("Clearing all caches...");
399
+ for (const [name, cache] of this.caches)
400
+ /* v8 ignore next */
401
+ if (cache.clear) try {
402
+ await cache.clear();
403
+ logger.info(`Cleared cache: ${name}`);
404
+ } catch (error) {
405
+ logger.error(`Failed to clear ${name}:`, error);
406
+ }
407
+ logger.success("All caches cleared");
408
+ }
409
+ async preheat(urls) {
410
+ logger.info(`Preheating cache for ${urls.length} URLs...`);
411
+ logger.info("Cache preheat completed");
412
+ }
413
+ generateRecommendations(totalSize, hitRate, cacheStats) {
414
+ const recommendations = [];
415
+ const sizeRatio = totalSize / this.GLOBAL_MAX_SIZE;
416
+ if (sizeRatio >= .9) recommendations.push(" CRITICAL: Cache size at 90%. Run smart_cache_cleanup immediately!");
417
+ else if (sizeRatio >= .7) recommendations.push("WARNING: Cache size at 70%. Consider cleanup soon.");
418
+ else if (sizeRatio >= .5) recommendations.push("INFO: Cache size at 50%. Monitor usage.");
419
+ if (hitRate < .3) recommendations.push(" Low cache hit rate (<30%). Consider adjusting TTL or cache strategy.");
420
+ else if (hitRate > .7) recommendations.push(" Good cache hit rate (>70%). Cache is working well.");
421
+ for (const cache of cacheStats) {
422
+ const cacheRatio = cache.size / totalSize;
423
+ if (cacheRatio > .5) recommendations.push(` ${cache.name} uses ${Math.round(cacheRatio * 100)}% of total cache. Consider cleanup.`);
424
+ if (cache.hitRate !== void 0 && cache.hitRate < .2) recommendations.push(` ${cache.name} has low hit rate (${(cache.hitRate * 100).toFixed(1)}%). Consider disabling or adjusting.`);
425
+ }
426
+ if (recommendations.length === 0) recommendations.push(" Cache health is good. No action needed.");
427
+ return recommendations;
428
+ }
429
+ };
430
+ //#endregion
431
+ //#region src/utils/artifactRetention.ts
432
+ const DAY_MS = 1440 * 60 * 1e3;
433
+ function getArtifactRetentionConfig(env = process.env) {
434
+ const retentionDays = Math.max(0, parseInt(env.MCP_ARTIFACT_RETENTION_DAYS ?? "0", 10) || 0);
435
+ const maxTotalMb = Math.max(0, parseInt(env.MCP_ARTIFACT_MAX_TOTAL_MB ?? "0", 10) || 0);
436
+ const cleanupIntervalMinutes = Math.max(0, parseInt(env.MCP_ARTIFACT_CLEANUP_INTERVAL_MINUTES ?? "0", 10) || 0);
437
+ const cleanupOnStart = ["1", "true"].includes((env.MCP_ARTIFACT_CLEANUP_ON_START ?? "").toLowerCase());
438
+ return {
439
+ enabled: retentionDays > 0 || maxTotalMb > 0,
440
+ retentionDays,
441
+ maxTotalBytes: maxTotalMb * 1024 * 1024,
442
+ cleanupOnStart,
443
+ cleanupIntervalMinutes
444
+ };
445
+ }
446
+ async function cleanupArtifacts(options) {
447
+ const envConfig = getArtifactRetentionConfig();
448
+ const config = {
449
+ ...envConfig,
450
+ retentionDays: options?.retentionDays ?? envConfig.retentionDays,
451
+ maxTotalBytes: options?.maxTotalBytes ?? envConfig.maxTotalBytes
452
+ };
453
+ const now = options?.now ?? Date.now();
454
+ const dryRun = options?.dryRun ?? false;
455
+ const directories = options?.directories ?? getManagedArtifactDirectories();
456
+ const cutoff = config.retentionDays > 0 ? now - config.retentionDays * DAY_MS : 0;
457
+ let scannedFiles = 0;
458
+ let removedFiles = 0;
459
+ let removedBytes = 0;
460
+ let removedByAge = 0;
461
+ let removedBySize = 0;
462
+ const remaining = [];
463
+ const removedSample = [];
464
+ const root = getProjectRoot();
465
+ const pendingRemovals = [];
466
+ function scheduleRemoval(path) {
467
+ pendingRemovals.push(rm(path, { force: true }).then(() => void 0).catch(() => void 0));
468
+ }
469
+ for (const directory of directories) await walkAndProcess(directory, root, cutoff, dryRun, (entry) => {
470
+ scannedFiles++;
471
+ if (cutoff > 0 && entry.mtimeMs < cutoff) {
472
+ removedFiles++;
473
+ removedBytes += entry.size;
474
+ removedByAge += entry.size;
475
+ if (removedSample.length < 20) removedSample.push(entry.relativePath);
476
+ if (!dryRun) scheduleRemoval(entry.path);
477
+ } else remaining.push(entry);
478
+ });
479
+ if (config.maxTotalBytes > 0) {
480
+ let totalBytes = remaining.reduce((sum, entry) => sum + entry.size, 0);
481
+ if (totalBytes > config.maxTotalBytes) {
482
+ remaining.sort((a, b) => a.mtimeMs - b.mtimeMs);
483
+ let i = 0;
484
+ while (i < remaining.length && totalBytes > config.maxTotalBytes) {
485
+ const entry = remaining[i];
486
+ totalBytes -= entry.size;
487
+ removedFiles++;
488
+ removedBytes += entry.size;
489
+ removedBySize += entry.size;
490
+ if (removedSample.length < 20) removedSample.push(entry.relativePath);
491
+ if (!dryRun) scheduleRemoval(entry.path);
492
+ i++;
493
+ }
494
+ remaining.splice(0, i);
495
+ }
496
+ }
497
+ if (!dryRun) {
498
+ await Promise.all(pendingRemovals);
499
+ await Promise.all(directories.map((dir) => pruneEmptyDirectories(dir)));
500
+ }
501
+ return {
502
+ success: true,
503
+ scannedFiles,
504
+ removedFiles,
505
+ removedBytes,
506
+ removedByAge,
507
+ removedBySize,
508
+ remainingFiles: remaining.length,
509
+ remainingBytes: remaining.reduce((sum, entry) => sum + entry.size, 0),
510
+ dryRun,
511
+ directories,
512
+ removedSample,
513
+ config
514
+ };
515
+ }
516
+ function startArtifactRetentionScheduler() {
517
+ const config = getArtifactRetentionConfig();
518
+ if (!config.enabled || config.cleanupIntervalMinutes <= 0) return null;
519
+ const handle = setInterval(() => {
520
+ /* v8 ignore next */
521
+ cleanupArtifacts().then((result) => {
522
+ if (result.removedFiles > 0) logger.info(`[artifacts] retention cleanup removed ${result.removedFiles} files (${result.removedBytes} bytes)`);
523
+ }).catch((error) => {
524
+ logger.warn("[artifacts] retention cleanup failed", error);
525
+ });
526
+ }, config.cleanupIntervalMinutes * 60 * 1e3);
527
+ handle.unref();
528
+ return () => clearInterval(handle);
529
+ }
530
+ function getManagedArtifactDirectories() {
531
+ const projectRoot = getProjectRoot();
532
+ const cwdDebuggerSessionsDir = resolve(process.cwd(), "debugger-sessions");
533
+ const projectDebuggerSessionsDir = resolve(projectRoot, "debugger-sessions");
534
+ const directories = new Set([
535
+ getArtifactsRoot(),
536
+ getConfig().paths.screenshotDir,
537
+ getDebuggerSessionsDir(),
538
+ cwdDebuggerSessionsDir,
539
+ projectDebuggerSessionsDir
540
+ ]);
541
+ for (const category of [
542
+ "wasm",
543
+ "traces",
544
+ "profiles",
545
+ "dumps",
546
+ "reports",
547
+ "har",
548
+ "sessions",
549
+ "tmp"
550
+ ]) directories.add(getArtifactDir(category));
551
+ return [...directories];
552
+ }
553
+ async function walkAndProcess(directory, root, cutoff, dryRun, onFile) {
554
+ let entries;
555
+ try {
556
+ entries = await readdir(directory, { withFileTypes: true });
557
+ } catch {
558
+ return;
559
+ }
560
+ for (const entry of entries) {
561
+ const entryPath = join(directory, entry.name);
562
+ if (entry.isDirectory()) await walkAndProcess(entryPath, root, cutoff, dryRun, onFile);
563
+ else if (entry.isFile()) {
564
+ let info;
565
+ try {
566
+ info = await stat(entryPath);
567
+ } catch {
568
+ continue;
569
+ }
570
+ onFile({
571
+ path: entryPath,
572
+ relativePath: relativePathFromRoot(root, entryPath),
573
+ size: info.size,
574
+ mtimeMs: info.mtimeMs
575
+ });
576
+ }
577
+ }
578
+ }
579
+ async function pruneEmptyDirectories(directory) {
580
+ let entries;
581
+ try {
582
+ entries = await readdir(directory, { withFileTypes: true });
583
+ } catch {
584
+ return;
585
+ }
586
+ await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => pruneEmptyDirectories(join(directory, entry.name))));
587
+ try {
588
+ if ((await readdir(directory)).length === 0) await rm(directory, {
589
+ recursive: true,
590
+ force: true
591
+ });
592
+ } catch {}
593
+ }
594
+ function relativePathFromRoot(root, path) {
595
+ return path.startsWith(root) ? path.slice(root.length).replace(/^[\\/]/, "").replace(/\\/g, "/") : path.replace(/\\/g, "/");
596
+ }
597
+ //#endregion
598
+ export { TokenBudgetManager as a, UnifiedCacheManager as i, getArtifactRetentionConfig as n, startArtifactRetentionScheduler as r, cleanupArtifacts as t };
@@ -0,0 +1,59 @@
1
+ import { t as __exportAll } from "./chunk-CjcI7cDX.mjs";
2
+ import { i as getProjectRoot } from "./outputPaths-um7lCRY3.mjs";
3
+ import { isAbsolute, normalize, relative, resolve, sep } from "node:path";
4
+ import { mkdir } from "node:fs/promises";
5
+ //#region src/utils/artifacts.ts
6
+ /**
7
+ * Unified artifact output management.
8
+ * Ensures all tool outputs go to well-structured directories with consistent naming.
9
+ */
10
+ var artifacts_exports = /* @__PURE__ */ __exportAll({
11
+ getArtifactDir: () => getArtifactDir,
12
+ getArtifactsRoot: () => getArtifactsRoot,
13
+ resolveArtifactPath: () => resolveArtifactPath
14
+ });
15
+ const ARTIFACT_BASE = "artifacts";
16
+ /**
17
+ * Generate a timestamped artifact path.
18
+ *
19
+ * @param category - Artifact subdirectory (wasm, traces, etc.)
20
+ * @param toolName - Tool that produces this artifact
21
+ * @param target - Target identifier (e.g., module name, URL hash)
22
+ * @param ext - File extension (without dot)
23
+ * @returns { absolutePath, displayPath }
24
+ */
25
+ async function resolveArtifactPath(options) {
26
+ const { category, toolName, target, ext, customDir } = options;
27
+ const root = getProjectRoot();
28
+ const dir = customDir ? resolve(root, customDir) : resolve(root, ARTIFACT_BASE, category);
29
+ const relativeDir = relative(normalize(root), normalize(dir));
30
+ if (relativeDir === ".." || relativeDir.startsWith(`..${sep}`) || isAbsolute(relativeDir)) throw new Error(`Path traversal blocked: artifact directory "${customDir}" escapes project root`);
31
+ await mkdir(dir, { recursive: true });
32
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
33
+ const shortId = Math.random().toString(36).substring(2, 8);
34
+ const absolutePath = resolve(dir, `${sanitizeFilename(toolName)}${target ? `-${sanitizeFilename(target)}` : ""}-${ts}-${shortId}.${ext.replace(/^\./, "")}`);
35
+ return {
36
+ absolutePath,
37
+ displayPath: relative(root, absolutePath).replace(/\\/g, "/")
38
+ };
39
+ }
40
+ /**
41
+ * Get the artifacts root directory.
42
+ */
43
+ function getArtifactsRoot() {
44
+ return resolve(getProjectRoot(), ARTIFACT_BASE);
45
+ }
46
+ /**
47
+ * Get a specific artifact category directory.
48
+ */
49
+ function getArtifactDir(category) {
50
+ return resolve(getProjectRoot(), ARTIFACT_BASE, category);
51
+ }
52
+ /**
53
+ * Sanitize a string for use as a filename component.
54
+ */
55
+ function sanitizeFilename(name) {
56
+ return name.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "").substring(0, 60);
57
+ }
58
+ //#endregion
59
+ export { resolveArtifactPath as i, getArtifactDir as n, getArtifactsRoot as r, artifacts_exports as t };
@@ -0,0 +1,31 @@
1
+ //#region src/server/domains/network/authorization-schema.ts
2
+ const networkAuthorizationSchema = {
3
+ allowedHosts: {
4
+ type: "array",
5
+ items: { type: "string" },
6
+ description: "Exact hostnames or IP literals allowed for this request."
7
+ },
8
+ allowedCidrs: {
9
+ type: "array",
10
+ items: { type: "string" },
11
+ description: "Explicit CIDR ranges allowed for this request."
12
+ },
13
+ allowPrivateNetwork: {
14
+ type: "boolean",
15
+ description: "Allow access to private or reserved network targets, but only when the resolved host matches allowedHosts or allowedCidrs."
16
+ },
17
+ allowInsecureHttp: {
18
+ type: "boolean",
19
+ description: "Allow plain HTTP access to explicitly authorized targets in allowedHosts or allowedCidrs."
20
+ },
21
+ expiresAt: {
22
+ type: "string",
23
+ description: "Optional ISO-8601 expiry time for this authorization."
24
+ },
25
+ reason: {
26
+ type: "string",
27
+ description: "Short audit note describing why this authorization is needed."
28
+ }
29
+ };
30
+ //#endregion
31
+ export { networkAuthorizationSchema as t };