@enclave-vm/core 0.0.1 → 2.9.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 (169) hide show
  1. package/esm/index.mjs +11172 -0
  2. package/esm/package.json +6 -0
  3. package/index.js +11268 -0
  4. package/package.json +11 -10
  5. package/src/adapters/vm-adapter.js +0 -1140
  6. package/src/adapters/vm-adapter.js.map +0 -1
  7. package/src/adapters/worker-pool/config.js +0 -129
  8. package/src/adapters/worker-pool/config.js.map +0 -1
  9. package/src/adapters/worker-pool/errors.js +0 -181
  10. package/src/adapters/worker-pool/errors.js.map +0 -1
  11. package/src/adapters/worker-pool/execution-queue.js +0 -179
  12. package/src/adapters/worker-pool/execution-queue.js.map +0 -1
  13. package/src/adapters/worker-pool/index.js +0 -73
  14. package/src/adapters/worker-pool/index.js.map +0 -1
  15. package/src/adapters/worker-pool/memory-monitor.js +0 -184
  16. package/src/adapters/worker-pool/memory-monitor.js.map +0 -1
  17. package/src/adapters/worker-pool/protocol.js +0 -143
  18. package/src/adapters/worker-pool/protocol.js.map +0 -1
  19. package/src/adapters/worker-pool/rate-limiter.js +0 -101
  20. package/src/adapters/worker-pool/rate-limiter.js.map +0 -1
  21. package/src/adapters/worker-pool/safe-deserialize.js +0 -141
  22. package/src/adapters/worker-pool/safe-deserialize.js.map +0 -1
  23. package/src/adapters/worker-pool/worker-pool-adapter.js +0 -506
  24. package/src/adapters/worker-pool/worker-pool-adapter.js.map +0 -1
  25. package/src/adapters/worker-pool/worker-script.js +0 -770
  26. package/src/adapters/worker-pool/worker-script.js.map +0 -1
  27. package/src/adapters/worker-pool/worker-slot.js +0 -301
  28. package/src/adapters/worker-pool/worker-slot.js.map +0 -1
  29. package/src/babel/babel-wrapper.js +0 -395
  30. package/src/babel/babel-wrapper.js.map +0 -1
  31. package/src/babel/index.js +0 -17
  32. package/src/babel/index.js.map +0 -1
  33. package/src/babel/multi-file-transform.js +0 -344
  34. package/src/babel/multi-file-transform.js.map +0 -1
  35. package/src/double-vm/double-vm-wrapper.js +0 -523
  36. package/src/double-vm/double-vm-wrapper.js.map +0 -1
  37. package/src/double-vm/index.js +0 -34
  38. package/src/double-vm/index.js.map +0 -1
  39. package/src/double-vm/parent-vm-bootstrap.js +0 -1695
  40. package/src/double-vm/parent-vm-bootstrap.js.map +0 -1
  41. package/src/double-vm/suspicious-patterns.js +0 -304
  42. package/src/double-vm/suspicious-patterns.js.map +0 -1
  43. package/src/double-vm/types.js +0 -11
  44. package/src/double-vm/types.js.map +0 -1
  45. package/src/double-vm/wrap-adapter.js +0 -59
  46. package/src/double-vm/wrap-adapter.js.map +0 -1
  47. package/src/enclave.js +0 -671
  48. package/src/enclave.js.map +0 -1
  49. package/src/globals-validator.js +0 -206
  50. package/src/globals-validator.js.map +0 -1
  51. package/src/index.js +0 -130
  52. package/src/index.js.map +0 -1
  53. package/src/memory-proxy.js +0 -310
  54. package/src/memory-proxy.js.map +0 -1
  55. package/src/memory-tracker.js +0 -230
  56. package/src/memory-tracker.js.map +0 -1
  57. package/src/safe-error.js +0 -76
  58. package/src/safe-error.js.map +0 -1
  59. package/src/safe-runtime.js +0 -656
  60. package/src/safe-runtime.js.map +0 -1
  61. package/src/scoring/cache.js +0 -158
  62. package/src/scoring/cache.js.map +0 -1
  63. package/src/scoring/feature-extractor.js +0 -366
  64. package/src/scoring/feature-extractor.js.map +0 -1
  65. package/src/scoring/index.js +0 -53
  66. package/src/scoring/index.js.map +0 -1
  67. package/src/scoring/scorer.interface.js +0 -49
  68. package/src/scoring/scorer.interface.js.map +0 -1
  69. package/src/scoring/scorers/disabled.scorer.js +0 -34
  70. package/src/scoring/scorers/disabled.scorer.js.map +0 -1
  71. package/src/scoring/scorers/external-api.scorer.js +0 -141
  72. package/src/scoring/scorers/external-api.scorer.js.map +0 -1
  73. package/src/scoring/scorers/index.js +0 -22
  74. package/src/scoring/scorers/index.js.map +0 -1
  75. package/src/scoring/scorers/local-llm.scorer.js +0 -474
  76. package/src/scoring/scorers/local-llm.scorer.js.map +0 -1
  77. package/src/scoring/scorers/progressive.scorer.js +0 -199
  78. package/src/scoring/scorers/progressive.scorer.js.map +0 -1
  79. package/src/scoring/scorers/rule-based.scorer.js +0 -316
  80. package/src/scoring/scorers/rule-based.scorer.js.map +0 -1
  81. package/src/scoring/scoring-gate.js +0 -246
  82. package/src/scoring/scoring-gate.js.map +0 -1
  83. package/src/scoring/types.js +0 -107
  84. package/src/scoring/types.js.map +0 -1
  85. package/src/secure-proxy.js +0 -609
  86. package/src/secure-proxy.js.map +0 -1
  87. package/src/session/channels/embedded-channel.js +0 -130
  88. package/src/session/channels/embedded-channel.js.map +0 -1
  89. package/src/session/channels/index.js +0 -14
  90. package/src/session/channels/index.js.map +0 -1
  91. package/src/session/index.js +0 -27
  92. package/src/session/index.js.map +0 -1
  93. package/src/session/session-emitter.js +0 -253
  94. package/src/session/session-emitter.js.map +0 -1
  95. package/src/session/session-state-machine.js +0 -182
  96. package/src/session/session-state-machine.js.map +0 -1
  97. package/src/session/session.js +0 -398
  98. package/src/session/session.js.map +0 -1
  99. package/src/session-types.js +0 -39
  100. package/src/session-types.js.map +0 -1
  101. package/src/sidecar/index.js +0 -31
  102. package/src/sidecar/index.js.map +0 -1
  103. package/src/sidecar/reference-config.js +0 -118
  104. package/src/sidecar/reference-config.js.map +0 -1
  105. package/src/sidecar/reference-resolver.js +0 -262
  106. package/src/sidecar/reference-resolver.js.map +0 -1
  107. package/src/sidecar/reference-sidecar.js +0 -226
  108. package/src/sidecar/reference-sidecar.js.map +0 -1
  109. package/src/tool-bridge.js +0 -306
  110. package/src/tool-bridge.js.map +0 -1
  111. package/src/types.js +0 -187
  112. package/src/types.js.map +0 -1
  113. package/src/value-sanitizer.js +0 -421
  114. package/src/value-sanitizer.js.map +0 -1
  115. /package/{src/adapters → adapters}/vm-adapter.d.ts +0 -0
  116. /package/{src/adapters → adapters}/worker-pool/config.d.ts +0 -0
  117. /package/{src/adapters → adapters}/worker-pool/errors.d.ts +0 -0
  118. /package/{src/adapters → adapters}/worker-pool/execution-queue.d.ts +0 -0
  119. /package/{src/adapters → adapters}/worker-pool/index.d.ts +0 -0
  120. /package/{src/adapters → adapters}/worker-pool/memory-monitor.d.ts +0 -0
  121. /package/{src/adapters → adapters}/worker-pool/protocol.d.ts +0 -0
  122. /package/{src/adapters → adapters}/worker-pool/rate-limiter.d.ts +0 -0
  123. /package/{src/adapters → adapters}/worker-pool/safe-deserialize.d.ts +0 -0
  124. /package/{src/adapters → adapters}/worker-pool/worker-pool-adapter.d.ts +0 -0
  125. /package/{src/adapters → adapters}/worker-pool/worker-script.d.ts +0 -0
  126. /package/{src/adapters → adapters}/worker-pool/worker-slot.d.ts +0 -0
  127. /package/{src/babel → babel}/babel-wrapper.d.ts +0 -0
  128. /package/{src/babel → babel}/index.d.ts +0 -0
  129. /package/{src/babel → babel}/multi-file-transform.d.ts +0 -0
  130. /package/{src/double-vm → double-vm}/double-vm-wrapper.d.ts +0 -0
  131. /package/{src/double-vm → double-vm}/index.d.ts +0 -0
  132. /package/{src/double-vm → double-vm}/parent-vm-bootstrap.d.ts +0 -0
  133. /package/{src/double-vm → double-vm}/suspicious-patterns.d.ts +0 -0
  134. /package/{src/double-vm → double-vm}/types.d.ts +0 -0
  135. /package/{src/double-vm → double-vm}/wrap-adapter.d.ts +0 -0
  136. /package/{src/enclave.d.ts → enclave.d.ts} +0 -0
  137. /package/{src/globals-validator.d.ts → globals-validator.d.ts} +0 -0
  138. /package/{src/index.d.ts → index.d.ts} +0 -0
  139. /package/{src/memory-proxy.d.ts → memory-proxy.d.ts} +0 -0
  140. /package/{src/memory-tracker.d.ts → memory-tracker.d.ts} +0 -0
  141. /package/{src/safe-error.d.ts → safe-error.d.ts} +0 -0
  142. /package/{src/safe-runtime.d.ts → safe-runtime.d.ts} +0 -0
  143. /package/{src/scoring → scoring}/cache.d.ts +0 -0
  144. /package/{src/scoring → scoring}/feature-extractor.d.ts +0 -0
  145. /package/{src/scoring → scoring}/index.d.ts +0 -0
  146. /package/{src/scoring → scoring}/scorer.interface.d.ts +0 -0
  147. /package/{src/scoring → scoring}/scorers/disabled.scorer.d.ts +0 -0
  148. /package/{src/scoring → scoring}/scorers/external-api.scorer.d.ts +0 -0
  149. /package/{src/scoring → scoring}/scorers/index.d.ts +0 -0
  150. /package/{src/scoring → scoring}/scorers/local-llm.scorer.d.ts +0 -0
  151. /package/{src/scoring → scoring}/scorers/progressive.scorer.d.ts +0 -0
  152. /package/{src/scoring → scoring}/scorers/rule-based.scorer.d.ts +0 -0
  153. /package/{src/scoring → scoring}/scoring-gate.d.ts +0 -0
  154. /package/{src/scoring → scoring}/types.d.ts +0 -0
  155. /package/{src/secure-proxy.d.ts → secure-proxy.d.ts} +0 -0
  156. /package/{src/session → session}/channels/embedded-channel.d.ts +0 -0
  157. /package/{src/session → session}/channels/index.d.ts +0 -0
  158. /package/{src/session → session}/index.d.ts +0 -0
  159. /package/{src/session → session}/session-emitter.d.ts +0 -0
  160. /package/{src/session → session}/session-state-machine.d.ts +0 -0
  161. /package/{src/session → session}/session.d.ts +0 -0
  162. /package/{src/session-types.d.ts → session-types.d.ts} +0 -0
  163. /package/{src/sidecar → sidecar}/index.d.ts +0 -0
  164. /package/{src/sidecar → sidecar}/reference-config.d.ts +0 -0
  165. /package/{src/sidecar → sidecar}/reference-resolver.d.ts +0 -0
  166. /package/{src/sidecar → sidecar}/reference-sidecar.d.ts +0 -0
  167. /package/{src/tool-bridge.d.ts → tool-bridge.d.ts} +0 -0
  168. /package/{src/types.d.ts → types.d.ts} +0 -0
  169. /package/{src/value-sanitizer.d.ts → value-sanitizer.d.ts} +0 -0
package/src/types.js DELETED
@@ -1,187 +0,0 @@
1
- "use strict";
2
- /**
3
- * Enclave Types and Interfaces
4
- *
5
- * Core types for the AgentScript execution environment.
6
- *
7
- * @packageDocumentation
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.DEFAULT_DOUBLE_VM_CONFIG = exports.SECURITY_LEVEL_CONFIGS = void 0;
11
- /**
12
- * Pre-defined security level configurations
13
- */
14
- exports.SECURITY_LEVEL_CONFIGS = {
15
- /**
16
- * STRICT: Maximum security for untrusted code
17
- *
18
- * Use for:
19
- * - AI-generated code from external sources
20
- * - User-submitted scripts
21
- * - Untrusted third-party integrations
22
- *
23
- * Characteristics:
24
- * - Short timeout (5s)
25
- * - Low iteration limits (1000)
26
- * - Limited tool calls (10)
27
- * - Deep value sanitization
28
- * - Full stack trace sanitization
29
- * - Timing API blocking
30
- * - No unbounded loops
31
- * - Unicode security checks
32
- */
33
- STRICT: {
34
- timeout: 5000,
35
- maxIterations: 1000,
36
- maxToolCalls: 10,
37
- maxSanitizeDepth: 5,
38
- maxSanitizeProperties: 50,
39
- sanitizeStackTraces: true,
40
- blockTimingAPIs: true,
41
- allowUnboundedLoops: false,
42
- unicodeSecurityCheck: true,
43
- allowFunctionsInGlobals: false,
44
- maxConsoleOutputBytes: 64 * 1024, // 64KB - prevent I/O flood attacks
45
- maxConsoleCalls: 100,
46
- secureProxy: {
47
- blockConstructor: true,
48
- blockPrototype: true,
49
- blockLegacyAccessors: true,
50
- proxyMaxDepth: 5,
51
- throwOnBlocked: true,
52
- },
53
- },
54
- /**
55
- * SECURE: High security with more headroom
56
- *
57
- * Use for:
58
- * - AI-generated code from trusted models
59
- * - Internal automation scripts
60
- * - Controlled multi-tenant environments
61
- *
62
- * Characteristics:
63
- * - Moderate timeout (15s)
64
- * - Moderate iteration limits (5000)
65
- * - Moderate tool calls (50)
66
- * - Standard value sanitization
67
- * - Stack trace sanitization
68
- * - No timing API blocking
69
- * - No unbounded loops
70
- */
71
- SECURE: {
72
- timeout: 15000,
73
- maxIterations: 5000,
74
- maxToolCalls: 50,
75
- maxSanitizeDepth: 10,
76
- maxSanitizeProperties: 100,
77
- sanitizeStackTraces: true,
78
- blockTimingAPIs: false,
79
- allowUnboundedLoops: false,
80
- unicodeSecurityCheck: true,
81
- allowFunctionsInGlobals: false,
82
- maxConsoleOutputBytes: 256 * 1024, // 256KB
83
- maxConsoleCalls: 500,
84
- secureProxy: {
85
- blockConstructor: true,
86
- blockPrototype: true,
87
- blockLegacyAccessors: true,
88
- proxyMaxDepth: 10,
89
- throwOnBlocked: true,
90
- },
91
- },
92
- /**
93
- * STANDARD: Balanced security and functionality (DEFAULT)
94
- *
95
- * Use for:
96
- * - Internal tools and scripts
97
- * - Development and testing
98
- * - Trusted environments
99
- *
100
- * Characteristics:
101
- * - Standard timeout (30s)
102
- * - Standard iteration limits (10000)
103
- * - Standard tool calls (100)
104
- * - Basic value sanitization
105
- * - Minimal stack trace sanitization
106
- * - Unbounded loops allowed
107
- */
108
- STANDARD: {
109
- timeout: 30000,
110
- maxIterations: 10000,
111
- maxToolCalls: 100,
112
- maxSanitizeDepth: 20,
113
- maxSanitizeProperties: 500,
114
- sanitizeStackTraces: false,
115
- blockTimingAPIs: false,
116
- allowUnboundedLoops: true,
117
- unicodeSecurityCheck: false,
118
- allowFunctionsInGlobals: false,
119
- maxConsoleOutputBytes: 1024 * 1024, // 1MB
120
- maxConsoleCalls: 1000,
121
- secureProxy: {
122
- blockConstructor: true,
123
- blockPrototype: true,
124
- blockLegacyAccessors: true,
125
- proxyMaxDepth: 15,
126
- throwOnBlocked: true,
127
- },
128
- },
129
- /**
130
- * PERMISSIVE: Minimal restrictions
131
- *
132
- * Use for:
133
- * - Local development only
134
- * - Debugging
135
- * - Performance testing
136
- *
137
- * WARNING: Not recommended for production use with untrusted code
138
- *
139
- * Characteristics:
140
- * - Long timeout (60s)
141
- * - High iteration limits (100000)
142
- * - High tool calls (1000)
143
- * - Minimal sanitization
144
- * - No stack trace sanitization
145
- * - All features enabled
146
- */
147
- PERMISSIVE: {
148
- timeout: 60000,
149
- maxIterations: 100000,
150
- maxToolCalls: 1000,
151
- maxSanitizeDepth: 50,
152
- maxSanitizeProperties: 1000,
153
- sanitizeStackTraces: false,
154
- blockTimingAPIs: false,
155
- allowUnboundedLoops: true,
156
- unicodeSecurityCheck: false,
157
- allowFunctionsInGlobals: true,
158
- maxConsoleOutputBytes: 10 * 1024 * 1024, // 10MB
159
- maxConsoleCalls: 10000,
160
- secureProxy: {
161
- blockConstructor: false, // Allow constructor access for development/debugging
162
- blockPrototype: true, // Still block prototype for safety
163
- blockLegacyAccessors: true,
164
- proxyMaxDepth: 20,
165
- throwOnBlocked: false, // Return undefined instead of throwing for development
166
- },
167
- },
168
- };
169
- /**
170
- * Default double VM configuration
171
- *
172
- * Double VM is enabled by default for all adapters.
173
- * This provides defense-in-depth security through nested VM isolation.
174
- */
175
- exports.DEFAULT_DOUBLE_VM_CONFIG = {
176
- enabled: true,
177
- parentTimeoutBuffer: 1000,
178
- parentValidation: {
179
- validateOperationNames: true,
180
- maxOperationsPerSecond: 100,
181
- blockSuspiciousSequences: true,
182
- rapidEnumerationThreshold: 30,
183
- rapidEnumerationOverrides: {},
184
- suspiciousPatterns: [], // Default patterns added at runtime
185
- },
186
- };
187
- //# sourceMappingURL=types.js.map
package/src/types.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AA+KH;;GAEG;AACU,QAAA,sBAAsB,GAA+C;IAChF;;;;;;;;;;;;;;;;;OAiBG;IACH,MAAM,EAAE;QACN,OAAO,EAAE,IAAI;QACb,aAAa,EAAE,IAAI;QACnB,YAAY,EAAE,EAAE;QAChB,gBAAgB,EAAE,CAAC;QACnB,qBAAqB,EAAE,EAAE;QACzB,mBAAmB,EAAE,IAAI;QACzB,eAAe,EAAE,IAAI;QACrB,mBAAmB,EAAE,KAAK;QAC1B,oBAAoB,EAAE,IAAI;QAC1B,uBAAuB,EAAE,KAAK;QAC9B,qBAAqB,EAAE,EAAE,GAAG,IAAI,EAAE,mCAAmC;QACrE,eAAe,EAAE,GAAG;QACpB,WAAW,EAAE;YACX,gBAAgB,EAAE,IAAI;YACtB,cAAc,EAAE,IAAI;YACpB,oBAAoB,EAAE,IAAI;YAC1B,aAAa,EAAE,CAAC;YAChB,cAAc,EAAE,IAAI;SACrB;KACF;IAED;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,EAAE;QACN,OAAO,EAAE,KAAK;QACd,aAAa,EAAE,IAAI;QACnB,YAAY,EAAE,EAAE;QAChB,gBAAgB,EAAE,EAAE;QACpB,qBAAqB,EAAE,GAAG;QAC1B,mBAAmB,EAAE,IAAI;QACzB,eAAe,EAAE,KAAK;QACtB,mBAAmB,EAAE,KAAK;QAC1B,oBAAoB,EAAE,IAAI;QAC1B,uBAAuB,EAAE,KAAK;QAC9B,qBAAqB,EAAE,GAAG,GAAG,IAAI,EAAE,QAAQ;QAC3C,eAAe,EAAE,GAAG;QACpB,WAAW,EAAE;YACX,gBAAgB,EAAE,IAAI;YACtB,cAAc,EAAE,IAAI;YACpB,oBAAoB,EAAE,IAAI;YAC1B,aAAa,EAAE,EAAE;YACjB,cAAc,EAAE,IAAI;SACrB;KACF;IAED;;;;;;;;;;;;;;;OAeG;IACH,QAAQ,EAAE;QACR,OAAO,EAAE,KAAK;QACd,aAAa,EAAE,KAAK;QACpB,YAAY,EAAE,GAAG;QACjB,gBAAgB,EAAE,EAAE;QACpB,qBAAqB,EAAE,GAAG;QAC1B,mBAAmB,EAAE,KAAK;QAC1B,eAAe,EAAE,KAAK;QACtB,mBAAmB,EAAE,IAAI;QACzB,oBAAoB,EAAE,KAAK;QAC3B,uBAAuB,EAAE,KAAK;QAC9B,qBAAqB,EAAE,IAAI,GAAG,IAAI,EAAE,MAAM;QAC1C,eAAe,EAAE,IAAI;QACrB,WAAW,EAAE;YACX,gBAAgB,EAAE,IAAI;YACtB,cAAc,EAAE,IAAI;YACpB,oBAAoB,EAAE,IAAI;YAC1B,aAAa,EAAE,EAAE;YACjB,cAAc,EAAE,IAAI;SACrB;KACF;IAED;;;;;;;;;;;;;;;;;OAiBG;IACH,UAAU,EAAE;QACV,OAAO,EAAE,KAAK;QACd,aAAa,EAAE,MAAM;QACrB,YAAY,EAAE,IAAI;QAClB,gBAAgB,EAAE,EAAE;QACpB,qBAAqB,EAAE,IAAI;QAC3B,mBAAmB,EAAE,KAAK;QAC1B,eAAe,EAAE,KAAK;QACtB,mBAAmB,EAAE,IAAI;QACzB,oBAAoB,EAAE,KAAK;QAC3B,uBAAuB,EAAE,IAAI;QAC7B,qBAAqB,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI,EAAE,OAAO;QAChD,eAAe,EAAE,KAAK;QACtB,WAAW,EAAE;YACX,gBAAgB,EAAE,KAAK,EAAE,qDAAqD;YAC9E,cAAc,EAAE,IAAI,EAAE,mCAAmC;YACzD,oBAAoB,EAAE,IAAI;YAC1B,aAAa,EAAE,EAAE;YACjB,cAAc,EAAE,KAAK,EAAE,uDAAuD;SAC/E;KACF;CACF,CAAC;AAyqBF;;;;;GAKG;AACU,QAAA,wBAAwB,GAAmB;IACtD,OAAO,EAAE,IAAI;IACb,mBAAmB,EAAE,IAAI;IACzB,gBAAgB,EAAE;QAChB,sBAAsB,EAAE,IAAI;QAC5B,sBAAsB,EAAE,GAAG;QAC3B,wBAAwB,EAAE,IAAI;QAC9B,yBAAyB,EAAE,EAAE;QAC7B,yBAAyB,EAAE,EAAE;QAC7B,kBAAkB,EAAE,EAAE,EAAE,oCAAoC;KAC7D;CACF,CAAC","sourcesContent":["/**\n * Enclave Types and Interfaces\n *\n * Core types for the AgentScript execution environment.\n *\n * @packageDocumentation\n */\n\n/**\n * Security levels for Enclave configuration\n *\n * These levels provide pre-configured security profiles that balance\n * functionality against security risk. Higher levels are more restrictive.\n *\n * @example\n * ```typescript\n * // Use STRICT for untrusted AI-generated code\n * const enclave = new Enclave({ securityLevel: 'STRICT' });\n *\n * // Use STANDARD for trusted internal tools\n * const enclave = new Enclave({ securityLevel: 'STANDARD' });\n * ```\n */\nexport type SecurityLevel = 'STRICT' | 'SECURE' | 'STANDARD' | 'PERMISSIVE';\n\n/**\n * AST validation preset for code validation\n *\n * Controls which validation rules are applied to code before execution.\n * Each preset is designed for different security/functionality trade-offs.\n *\n * @example\n * ```typescript\n * // Use agentscript preset for AI-generated tool orchestration (default)\n * const enclave = new Enclave({ preset: 'agentscript' });\n *\n * // Use strict preset for maximum security\n * const enclave = new Enclave({ preset: 'strict' });\n *\n * // Use babel preset for TSX/JSX transformation support\n * const enclave = new Enclave({ preset: 'babel' });\n * ```\n */\nexport type AstPreset = 'agentscript' | 'strict' | 'secure' | 'standard' | 'permissive' | 'babel';\n\n/**\n * Secure proxy configuration per security level\n *\n * Controls which dangerous properties are blocked at runtime via JavaScript Proxies.\n * This provides defense-in-depth against computed property access attacks that\n * bypass static AST analysis.\n */\nexport interface SecureProxyLevelConfig {\n /**\n * Whether to block 'constructor' property access\n * Prevents: obj['const' + 'ructor'] attacks for code execution\n * @default true (blocks constructor for security)\n *\n * Set to false in PERMISSIVE mode for development/debugging\n */\n blockConstructor: boolean;\n\n /**\n * Whether to block prototype access (__proto__, prototype)\n * Prevents: prototype chain manipulation attacks\n * @default true (always recommended to keep true)\n */\n blockPrototype: boolean;\n\n /**\n * Whether to block legacy getter/setter methods\n * Blocks: __defineGetter__, __defineSetter__, __lookupGetter__, __lookupSetter__\n * @default true\n */\n blockLegacyAccessors: boolean;\n\n /**\n * Maximum depth for recursive proxying\n * Limits how deep nested objects are wrapped in secure proxies\n * @default 10\n */\n proxyMaxDepth: number;\n\n /**\n * Whether to throw an error when blocked properties are accessed.\n *\n * Security level defaults:\n * - STRICT/SECURE/STANDARD: `true` (throws error)\n * - PERMISSIVE: `false` (returns undefined)\n *\n * When true, accessing blocked properties like 'constructor', '__proto__',\n * 'prototype' will throw a SecurityError instead of returning undefined.\n * This makes security violations explicit and easier to detect.\n *\n * **Breaking change note**: Prior versions returned undefined for all security levels.\n * Set to `false` for backward compatibility (returns undefined for blocked properties).\n */\n throwOnBlocked: boolean;\n}\n\n/**\n * Security level configuration presets\n *\n * Each level adjusts:\n * - Resource limits (timeout, iterations, tool calls)\n * - Validation strictness\n * - Stack trace sanitization\n * - Value sanitization depth\n */\nexport interface SecurityLevelConfig {\n /**\n * Maximum execution time in milliseconds\n */\n timeout: number;\n\n /**\n * Maximum number of loop iterations\n */\n maxIterations: number;\n\n /**\n * Maximum number of tool calls\n */\n maxToolCalls: number;\n\n /**\n * Maximum depth for value sanitization\n */\n maxSanitizeDepth: number;\n\n /**\n * Maximum properties per object in sanitized values\n */\n maxSanitizeProperties: number;\n\n /**\n * Whether to sanitize stack traces (remove file paths, line numbers)\n */\n sanitizeStackTraces: boolean;\n\n /**\n * Whether to block Date.now() and performance timing APIs\n * (prevents timing attacks)\n */\n blockTimingAPIs: boolean;\n\n /**\n * Whether to allow while/do-while loops\n * (false = only bounded for/for-of loops allowed)\n */\n allowUnboundedLoops: boolean;\n\n /**\n * Whether to check for Unicode security attacks in code\n */\n unicodeSecurityCheck: boolean;\n\n /**\n * Whether to allow functions in custom globals\n */\n allowFunctionsInGlobals: boolean;\n\n /**\n * Maximum total console output in bytes\n * Prevents I/O flood attacks via console.log spam\n */\n maxConsoleOutputBytes: number;\n\n /**\n * Maximum number of console calls (log, warn, error, info)\n * Prevents I/O flood attacks via excessive console calls\n */\n maxConsoleCalls: number;\n\n /**\n * Secure proxy configuration for runtime property access protection\n * Controls which dangerous properties are blocked via JavaScript Proxies\n */\n secureProxy: SecureProxyLevelConfig;\n}\n\n/**\n * Pre-defined security level configurations\n */\nexport const SECURITY_LEVEL_CONFIGS: Record<SecurityLevel, SecurityLevelConfig> = {\n /**\n * STRICT: Maximum security for untrusted code\n *\n * Use for:\n * - AI-generated code from external sources\n * - User-submitted scripts\n * - Untrusted third-party integrations\n *\n * Characteristics:\n * - Short timeout (5s)\n * - Low iteration limits (1000)\n * - Limited tool calls (10)\n * - Deep value sanitization\n * - Full stack trace sanitization\n * - Timing API blocking\n * - No unbounded loops\n * - Unicode security checks\n */\n STRICT: {\n timeout: 5000,\n maxIterations: 1000,\n maxToolCalls: 10,\n maxSanitizeDepth: 5,\n maxSanitizeProperties: 50,\n sanitizeStackTraces: true,\n blockTimingAPIs: true,\n allowUnboundedLoops: false,\n unicodeSecurityCheck: true,\n allowFunctionsInGlobals: false,\n maxConsoleOutputBytes: 64 * 1024, // 64KB - prevent I/O flood attacks\n maxConsoleCalls: 100,\n secureProxy: {\n blockConstructor: true,\n blockPrototype: true,\n blockLegacyAccessors: true,\n proxyMaxDepth: 5,\n throwOnBlocked: true,\n },\n },\n\n /**\n * SECURE: High security with more headroom\n *\n * Use for:\n * - AI-generated code from trusted models\n * - Internal automation scripts\n * - Controlled multi-tenant environments\n *\n * Characteristics:\n * - Moderate timeout (15s)\n * - Moderate iteration limits (5000)\n * - Moderate tool calls (50)\n * - Standard value sanitization\n * - Stack trace sanitization\n * - No timing API blocking\n * - No unbounded loops\n */\n SECURE: {\n timeout: 15000,\n maxIterations: 5000,\n maxToolCalls: 50,\n maxSanitizeDepth: 10,\n maxSanitizeProperties: 100,\n sanitizeStackTraces: true,\n blockTimingAPIs: false,\n allowUnboundedLoops: false,\n unicodeSecurityCheck: true,\n allowFunctionsInGlobals: false,\n maxConsoleOutputBytes: 256 * 1024, // 256KB\n maxConsoleCalls: 500,\n secureProxy: {\n blockConstructor: true,\n blockPrototype: true,\n blockLegacyAccessors: true,\n proxyMaxDepth: 10,\n throwOnBlocked: true,\n },\n },\n\n /**\n * STANDARD: Balanced security and functionality (DEFAULT)\n *\n * Use for:\n * - Internal tools and scripts\n * - Development and testing\n * - Trusted environments\n *\n * Characteristics:\n * - Standard timeout (30s)\n * - Standard iteration limits (10000)\n * - Standard tool calls (100)\n * - Basic value sanitization\n * - Minimal stack trace sanitization\n * - Unbounded loops allowed\n */\n STANDARD: {\n timeout: 30000,\n maxIterations: 10000,\n maxToolCalls: 100,\n maxSanitizeDepth: 20,\n maxSanitizeProperties: 500,\n sanitizeStackTraces: false,\n blockTimingAPIs: false,\n allowUnboundedLoops: true,\n unicodeSecurityCheck: false,\n allowFunctionsInGlobals: false,\n maxConsoleOutputBytes: 1024 * 1024, // 1MB\n maxConsoleCalls: 1000,\n secureProxy: {\n blockConstructor: true,\n blockPrototype: true,\n blockLegacyAccessors: true,\n proxyMaxDepth: 15,\n throwOnBlocked: true,\n },\n },\n\n /**\n * PERMISSIVE: Minimal restrictions\n *\n * Use for:\n * - Local development only\n * - Debugging\n * - Performance testing\n *\n * WARNING: Not recommended for production use with untrusted code\n *\n * Characteristics:\n * - Long timeout (60s)\n * - High iteration limits (100000)\n * - High tool calls (1000)\n * - Minimal sanitization\n * - No stack trace sanitization\n * - All features enabled\n */\n PERMISSIVE: {\n timeout: 60000,\n maxIterations: 100000,\n maxToolCalls: 1000,\n maxSanitizeDepth: 50,\n maxSanitizeProperties: 1000,\n sanitizeStackTraces: false,\n blockTimingAPIs: false,\n allowUnboundedLoops: true,\n unicodeSecurityCheck: false,\n allowFunctionsInGlobals: true,\n maxConsoleOutputBytes: 10 * 1024 * 1024, // 10MB\n maxConsoleCalls: 10000,\n secureProxy: {\n blockConstructor: false, // Allow constructor access for development/debugging\n blockPrototype: true, // Still block prototype for safety\n blockLegacyAccessors: true,\n proxyMaxDepth: 20,\n throwOnBlocked: false, // Return undefined instead of throwing for development\n },\n },\n};\n\n/**\n * Result of executing AgentScript code\n */\nexport interface ExecutionResult<T = unknown> {\n /**\n * Whether execution was successful\n */\n success: boolean;\n\n /**\n * Return value from the script (if successful)\n */\n value?: T;\n\n /**\n * Error that occurred during execution (if failed)\n */\n error?: ExecutionError;\n\n /**\n * Execution statistics\n */\n stats: ExecutionStats;\n\n /**\n * AI scoring result (if scoring gate is enabled)\n */\n scoringResult?: ScoringGateResult;\n}\n\n/**\n * Execution error details\n */\nexport interface ExecutionError {\n /**\n * Error message\n */\n message: string;\n\n /**\n * Error name/type\n */\n name: string;\n\n /**\n * Stack trace (if available)\n */\n stack?: string;\n\n /**\n * Error code (for structured errors)\n */\n code?: string;\n\n /**\n * Additional error data\n */\n data?: Record<string, unknown>;\n}\n\n/**\n * Execution statistics\n */\nexport interface ExecutionStats {\n /**\n * Execution duration in milliseconds\n */\n duration: number;\n\n /**\n * Peak tracked memory usage in bytes\n *\n * When `memoryLimit` is configured, this reports the peak memory usage\n * tracked during execution. Tracking monitors String and Array allocations.\n *\n * Note: This is an estimate based on allocation tracking, not actual V8 heap usage.\n * For precise memory isolation, use the worker_threads adapter with `--max-old-space-size`.\n */\n memoryUsage?: number;\n\n /**\n * Number of tool calls made\n */\n toolCallCount: number;\n\n /**\n * Number of loop iterations executed\n */\n iterationCount: number;\n\n /**\n * Timestamp when execution started\n */\n startTime: number;\n\n /**\n * Timestamp when execution ended\n */\n endTime: number;\n}\n\n/**\n * Configuration for Enclave execution\n */\nexport type ToolBridgeMode = 'string' | 'direct';\n\n/**\n * Tool bridge configuration between the sandbox and host runtime.\n *\n * By default, tool calls use a JSON string request/response envelope to avoid\n * leaking host-realm objects (Errors, Promises, Functions) into the sandbox.\n *\n * SECURITY WARNING: `mode: 'direct'` disables the string bridge and passes\n * objects directly across realms. This is riskier and requires an explicit\n * acknowledgement.\n */\nexport interface ToolBridgeConfig {\n /**\n * Bridge mode.\n * @default 'string'\n */\n mode?: ToolBridgeMode;\n\n /**\n * Maximum size (in bytes) of a tool request or response payload.\n * @default 5 * 1024 * 1024 (5MB)\n */\n maxPayloadBytes?: number;\n\n /**\n * Required acknowledgement to enable insecure direct bridging.\n *\n * When `mode` is set to `'direct'`, enclave construction throws unless this\n * field is explicitly set to `true`.\n */\n acknowledgeInsecureDirect?: boolean;\n}\n\nexport interface EnclaveConfig {\n /**\n * Maximum execution time in milliseconds\n * Default: 30000 (30 seconds)\n */\n timeout?: number;\n\n /**\n * Maximum memory usage in bytes\n *\n * When set, the VM adapter tracks String and Array allocations and throws\n * a MemoryLimitError if the limit is exceeded. Tracking adds ~5-10% overhead.\n *\n * Note: This is enforced via allocation tracking, not V8 heap limits.\n * For precise memory isolation, use the worker_threads adapter.\n *\n * Default: 128 * 1024 * 1024 (128MB)\n */\n memoryLimit?: number;\n\n /**\n * Maximum number of tool calls allowed\n * Default: 100\n */\n maxToolCalls?: number;\n\n /**\n * Maximum number of loop iterations (per loop)\n * Default: 10000\n */\n maxIterations?: number;\n\n /**\n * Sandbox adapter to use\n * Default: 'vm'\n */\n adapter?: 'vm' | 'isolated-vm' | 'worker_threads';\n\n /**\n * Whether to allow access to Node.js built-ins\n * Default: false\n */\n allowBuiltins?: boolean;\n\n /**\n * Custom globals to inject into the sandbox\n */\n globals?: Record<string, unknown>;\n\n /**\n * Tool call handler\n * This function is called when the script calls __safe_callTool\n */\n toolHandler?: ToolHandler;\n\n /**\n * Tool bridge configuration between the sandbox and host.\n *\n * Default: `{ mode: 'string', maxPayloadBytes: 5MB }`\n */\n toolBridge?: ToolBridgeConfig;\n\n /**\n * Maximum total console output in bytes\n * Default: Determined by securityLevel (1MB for STANDARD)\n * Prevents I/O flood attacks via console.log spam\n */\n maxConsoleOutputBytes?: number;\n\n /**\n * Maximum number of console calls (log, warn, error, info)\n * Default: Determined by securityLevel (1000 for STANDARD)\n * Prevents I/O flood attacks via excessive console calls\n */\n maxConsoleCalls?: number;\n}\n\n/**\n * Tool call handler function\n */\nexport type ToolHandler = (toolName: string, args: Record<string, unknown>) => Promise<unknown>;\n\n/**\n * Safe runtime context provided to AgentScript code\n */\nexport interface SafeRuntimeContext {\n /**\n * Safe tool call function\n * Tracks calls, enforces limits, and delegates to the tool handler\n */\n __safe_callTool: (toolName: string, args: Record<string, unknown>) => Promise<unknown>;\n\n /**\n * Safe for-of loop iterator\n * Enforces iteration limits\n */\n __safe_forOf: <T>(iterable: Iterable<T>) => Iterable<T>;\n\n /**\n * Safe for loop wrapper\n * Enforces iteration limits\n */\n __safe_for: (init: () => void, test: () => boolean, update: () => void, body: () => void) => void;\n\n /**\n * Safe while loop wrapper\n * Enforces iteration limits\n */\n __safe_while: (test: () => boolean, body: () => void) => void;\n\n /**\n * Safe do-while loop wrapper\n * Enforces iteration limits\n */\n __safe_doWhile: (body: () => void, test: () => boolean) => void;\n\n /**\n * Safe string concatenation\n * Detects reference IDs and handles them appropriately\n */\n __safe_concat: (left: unknown, right: unknown) => unknown;\n\n /**\n * Safe template literal interpolation\n * Detects reference IDs in interpolated values\n */\n __safe_template: (quasis: string[], ...values: unknown[]) => unknown;\n\n /**\n * Whitelisted safe globals\n */\n Math: typeof Math;\n JSON: typeof JSON;\n Array: typeof Array;\n Object: typeof Object;\n String: typeof String;\n Number: typeof Number;\n Date: typeof Date;\n NaN: typeof NaN;\n Infinity: typeof Infinity;\n undefined: typeof undefined;\n isNaN: typeof isNaN;\n isFinite: typeof isFinite;\n parseInt: typeof parseInt;\n parseFloat: typeof parseFloat;\n}\n\n// Forward reference - imported at runtime to avoid circular dependency\nimport type { ReferenceSidecar } from './sidecar/reference-sidecar';\nimport type { ReferenceConfig } from './sidecar/reference-config';\nimport type { ScoringGateConfig, ScoringGateResult } from './scoring/types';\nimport type { WorkerPoolConfig } from './adapters/worker-pool/config';\nimport type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig } from './double-vm/types';\n\n/**\n * Internal execution context (tracks state during execution)\n */\nexport interface ExecutionContext {\n /**\n * Configuration\n */\n config: Omit<Required<EnclaveConfig>, 'toolHandler'> & {\n toolHandler?: ToolHandler;\n sanitizeStackTraces: boolean;\n maxSanitizeDepth: number;\n maxSanitizeProperties: number;\n };\n\n /**\n * Statistics tracker\n */\n stats: ExecutionStats;\n\n /**\n * Abort controller for cancellation\n */\n abortController: AbortController;\n\n /**\n * Whether execution has been aborted\n */\n aborted: boolean;\n\n /**\n * Tool handler\n */\n toolHandler?: ToolHandler;\n\n /**\n * Reference sidecar for pass-by-reference support (per-execution)\n * Created and disposed by the Enclave for each run\n */\n sidecar?: ReferenceSidecar;\n\n /**\n * Reference configuration for sidecar\n */\n referenceConfig?: ReferenceConfig;\n\n /**\n * Secure proxy configuration for runtime property blocking\n */\n secureProxyConfig?: SecureProxyLevelConfig;\n}\n\n/**\n * Sandbox adapter interface\n * Different sandboxing strategies (isolated-vm, vm2, worker_threads) implement this\n */\nexport interface SandboxAdapter {\n /**\n * Execute code in the sandbox\n *\n * @param code Transformed AgentScript code to execute\n * @param context Execution context\n * @returns Execution result\n */\n execute<T = unknown>(code: string, context: ExecutionContext): Promise<ExecutionResult<T>>;\n\n /**\n * Cleanup the sandbox\n */\n dispose(): void;\n}\n\n/**\n * Options for reference sidecar (pass-by-reference) support\n */\nexport interface ReferenceSidecarOptions {\n /**\n * Enable pass-by-reference support\n * When enabled, large strings are automatically lifted to a sidecar\n * and replaced with reference IDs.\n * @default false\n */\n enabled: boolean;\n\n /**\n * Maximum total size of all stored references in bytes\n * Prevents memory exhaustion from excessive data storage\n * @default Determined by securityLevel\n */\n maxTotalSize?: number;\n\n /**\n * Maximum size of a single reference in bytes\n * @default Determined by securityLevel\n */\n maxReferenceSize?: number;\n\n /**\n * Threshold in bytes to trigger extraction from source code\n * Strings larger than this are lifted to the sidecar\n * @default Determined by securityLevel\n */\n extractionThreshold?: number;\n\n /**\n * Maximum expanded size when resolving references for tool calls\n * @default Determined by securityLevel\n */\n maxResolvedSize?: number;\n\n /**\n * Whether to allow composite handles from string concatenation\n * If false, concatenating references throws an error\n * @default Determined by securityLevel (false for STRICT/SECURE)\n */\n allowComposites?: boolean;\n\n /**\n * Maximum number of references in a single execution\n * @default Determined by securityLevel\n */\n maxReferenceCount?: number;\n}\n\n/**\n * Options for creating an Enclave instance\n */\nexport interface CreateEnclaveOptions extends EnclaveConfig {\n /**\n * Security level preset\n *\n * Pre-configured security profiles that balance functionality against risk.\n * Individual options (timeout, maxIterations, etc.) override the preset values.\n *\n * Levels:\n * - STRICT: Maximum security for untrusted AI-generated code\n * - SECURE: High security with more headroom for trusted AI code\n * - STANDARD: Balanced security and functionality (DEFAULT)\n * - PERMISSIVE: Minimal restrictions (development only)\n *\n * @default 'STANDARD'\n *\n * @example\n * ```typescript\n * // Use STRICT for untrusted code\n * const enclave = new Enclave({ securityLevel: 'STRICT' });\n *\n * // Override specific values from the preset\n * const enclave = new Enclave({\n * securityLevel: 'SECURE',\n * timeout: 20000, // Override SECURE's 15s default\n * });\n * ```\n */\n securityLevel?: SecurityLevel;\n\n /**\n * AST validation preset to use for code validation\n *\n * Controls which validation rules are applied to code before execution.\n * All presets support custom globals via the `globals` option.\n *\n * Presets:\n * - agentscript: Specialized for AI agent tool orchestration (DEFAULT)\n * - strict: Bank-grade security, blocks almost everything\n * - secure: High security with reasonable flexibility\n * - standard: Balanced security for most use cases\n * - permissive: Minimal restrictions for trusted code\n *\n * @default 'agentscript'\n *\n * @example\n * ```typescript\n * // Use agentscript preset (default)\n * const enclave = new Enclave({ preset: 'agentscript' });\n *\n * // Use strict preset for maximum security\n * const enclave = new Enclave({ preset: 'strict' });\n * ```\n */\n preset?: AstPreset;\n\n /**\n * Whether to validate AgentScript code before execution\n * Default: true\n */\n validate?: boolean;\n\n /**\n * Whether to transform AgentScript code before execution\n * Default: true\n */\n transform?: boolean;\n\n /**\n * Whether to allow functions in custom globals\n * Default: Determined by securityLevel (false for STRICT/SECURE/STANDARD)\n *\n * Security Warning: Functions can leak host scope via closures.\n * Only enable if you understand the security implications.\n */\n allowFunctionsInGlobals?: boolean;\n\n /**\n * Whether to sanitize stack traces in error messages\n * Default: Determined by securityLevel (true for STRICT/SECURE)\n *\n * When enabled, file paths and line numbers are removed from stack traces\n * to prevent information leakage about the host system.\n */\n sanitizeStackTraces?: boolean;\n\n /**\n * Maximum depth for value sanitization in tool responses\n * Default: Determined by securityLevel\n */\n maxSanitizeDepth?: number;\n\n /**\n * Maximum properties per object in sanitized values\n * Default: Determined by securityLevel\n */\n maxSanitizeProperties?: number;\n\n /**\n * Reference sidecar (pass-by-reference) configuration\n *\n * When enabled, the enclave:\n * - Extracts large strings from code and stores them in a sidecar\n * - Transforms concatenation to detect reference IDs\n * - Resolves references at the callTool boundary\n * - Lifts large tool results back to the sidecar\n *\n * This enables scripts to manipulate large data (videos, PDFs, images)\n * without loading them into the JavaScript sandbox.\n *\n * @example\n * ```typescript\n * const enclave = new Enclave({\n * securityLevel: 'STRICT',\n * sidecar: {\n * enabled: true,\n * extractionThreshold: 64 * 1024, // 64KB\n * },\n * });\n * ```\n */\n sidecar?: ReferenceSidecarOptions;\n\n /**\n * AI Scoring Gate configuration\n *\n * Adds semantic security analysis that detects attack patterns\n * beyond what static AST validation can catch:\n * - Data exfiltration patterns (list→send)\n * - Excessive access (high limits, wildcards)\n * - Fan-out attacks (tool calls in loops)\n * - Sensitive data access (passwords, tokens)\n *\n * Runs AFTER AST validation but BEFORE code execution.\n *\n * @example\n * ```typescript\n * // Rule-based scorer (~1ms, zero dependencies)\n * const enclave = new Enclave({\n * scoringGate: {\n * scorer: 'rule-based',\n * blockThreshold: 70,\n * },\n * });\n *\n * // External API scorer (best detection)\n * const enclave = new Enclave({\n * scoringGate: {\n * scorer: 'external-api',\n * externalApi: {\n * endpoint: 'https://api.example.com/score',\n * apiKey: process.env.SCORING_API_KEY,\n * },\n * },\n * });\n * ```\n */\n scoringGate?: ScoringGateConfig;\n\n /**\n * Worker Pool Adapter configuration\n *\n * Only used when adapter is set to 'worker_threads'.\n * Provides OS-level memory isolation via worker threads with:\n * - Pool management (min/max workers, scaling)\n * - Memory monitoring and enforcement\n * - Hard halt capability via worker.terminate()\n * - Rate limiting for message flood protection\n * - Dual-layer sandbox (worker thread + VM context)\n *\n * @example\n * ```typescript\n * const enclave = new Enclave({\n * adapter: 'worker_threads',\n * workerPoolConfig: {\n * minWorkers: 2,\n * maxWorkers: 8,\n * memoryLimitPerWorker: 256 * 1024 * 1024, // 256MB\n * },\n * });\n * ```\n */\n workerPoolConfig?: Partial<WorkerPoolConfig>;\n\n /**\n * Secure proxy configuration override\n *\n * Override individual secure proxy settings from the security level preset.\n * If not provided, uses the security level defaults.\n *\n * @example\n * ```typescript\n * // Use STRICT but allow constructor access for debugging\n * const enclave = new Enclave({\n * securityLevel: 'STRICT',\n * secureProxyConfig: { blockConstructor: false },\n * });\n * ```\n */\n secureProxyConfig?: Partial<SecureProxyLevelConfig>;\n\n /**\n * Double VM configuration for enhanced security isolation\n *\n * When enabled (default), user code runs inside a nested VM structure:\n * - Parent VM: Security barrier with enhanced validation\n * - Inner VM: Where user code actually executes\n *\n * This provides defense-in-depth: even if malicious code exploits a VM\n * vulnerability, it only escapes to another sandboxed VM rather than\n * the host process.\n *\n * The parent VM provides additional security:\n * - Operation name validation (whitelist/blacklist patterns)\n * - Rate limiting (max operations per second)\n * - Suspicious pattern detection (exfiltration, enumeration)\n * - Double sanitization of operation arguments\n *\n * @default { enabled: true }\n *\n * @example\n * ```typescript\n * // Use with custom validation (default is enabled)\n * const enclave = new Enclave({\n * doubleVm: {\n * parentValidation: {\n * allowedOperationPattern: /^[a-z]+:[a-z]+$/i,\n * maxOperationsPerSecond: 50,\n * },\n * },\n * });\n *\n * // SECURITY WARNING: Disable (not recommended for production)\n * const enclave = new Enclave({\n * doubleVm: { enabled: false },\n * });\n * ```\n */\n doubleVm?: PartialDoubleVmConfig;\n}\n\n/**\n * Re-exported scoring types for convenience\n * @see {@link ScoringGateConfig} Configuration for the AI scoring gate\n * @see {@link ScoringGateResult} Result from scoring gate evaluation\n */\nexport type { ScoringGateConfig, ScoringGateResult };\n\n/**\n * Re-exported worker pool configuration type\n * @see {@link WorkerPoolConfig} Configuration for worker pool adapter\n */\nexport type { WorkerPoolConfig };\n\n/**\n * Re-exported double VM types for convenience\n * @see {@link DoubleVmConfig} Full configuration for double VM layer\n * @see {@link PartialDoubleVmConfig} Partial configuration with defaults\n * @see {@link ParentValidationConfig} Parent VM validation settings\n */\nexport type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig };\n\n/**\n * Default double VM configuration\n *\n * Double VM is enabled by default for all adapters.\n * This provides defense-in-depth security through nested VM isolation.\n */\nexport const DEFAULT_DOUBLE_VM_CONFIG: DoubleVmConfig = {\n enabled: true,\n parentTimeoutBuffer: 1000,\n parentValidation: {\n validateOperationNames: true,\n maxOperationsPerSecond: 100,\n blockSuspiciousSequences: true,\n rapidEnumerationThreshold: 30,\n rapidEnumerationOverrides: {},\n suspiciousPatterns: [], // Default patterns added at runtime\n },\n};\n"]}
@@ -1,421 +0,0 @@
1
- "use strict";
2
- /**
3
- * Value Sanitizer - Tool Handler Return Value Security
4
- *
5
- * Sanitizes values returned from tool handlers to prevent:
6
- * - Function injection (return values containing executable functions)
7
- * - Symbol injection (symbols can be used for prototype manipulation)
8
- * - Prototype pollution (__proto__, constructor keys)
9
- * - Deeply nested objects (DoS via recursion)
10
- * - Large object graphs (DoS via memory exhaustion)
11
- *
12
- * @packageDocumentation
13
- */
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.sanitizeValue = sanitizeValue;
16
- exports.canSanitize = canSanitize;
17
- exports.sanitizeValueOrFallback = sanitizeValueOrFallback;
18
- exports.estimateSerializedSize = estimateSerializedSize;
19
- exports.checkSerializedSize = checkSerializedSize;
20
- /**
21
- * Keys that are stripped from sanitized objects for security
22
- * - __proto__: Prototype pollution vector
23
- * - constructor: Constructor chain escape vector
24
- */
25
- const DANGEROUS_KEYS = new Set(['__proto__', 'constructor']);
26
- /**
27
- * Sanitize a value returned from a tool handler
28
- *
29
- * Security features:
30
- * - Strips functions (prevent code injection)
31
- * - Strips symbols (prevent prototype manipulation)
32
- * - Removes __proto__ and constructor keys (prevent prototype pollution)
33
- * - Creates null-prototype objects (prevent prototype chain attacks)
34
- * - Enforces max depth (prevent DoS via deep recursion)
35
- * - Enforces max properties (prevent DoS via memory exhaustion)
36
- *
37
- * @param value The value to sanitize
38
- * @param options Sanitization options
39
- * @param depth Current recursion depth (internal)
40
- * @param propCount Property counter (internal)
41
- * @returns Sanitized value safe for sandbox use
42
- * @throws Error if value contains functions, symbols, or exceeds limits
43
- *
44
- * @example
45
- * ```typescript
46
- * const toolResult = await toolHandler('getData', {});
47
- * const safeResult = sanitizeValue(toolResult);
48
- * ```
49
- */
50
- function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: new WeakSet() }) {
51
- const maxDepth = options.maxDepth ?? 20;
52
- const maxProperties = options.maxProperties ?? 10000;
53
- const allowDates = options.allowDates ?? true;
54
- const allowErrors = options.allowErrors ?? true;
55
- // Check depth limit
56
- if (depth > maxDepth) {
57
- throw new Error(`Tool handler return value exceeds maximum depth (${maxDepth}). ` +
58
- `This limit prevents deeply nested objects that could cause stack overflow.`);
59
- }
60
- // Check property count limit
61
- if (context.propCount.count > maxProperties) {
62
- throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}). ` +
63
- `This limit prevents memory exhaustion from large object graphs.`);
64
- }
65
- // Handle null/undefined
66
- if (value === null || value === undefined) {
67
- return value;
68
- }
69
- const type = typeof value;
70
- // Primitives are safe
71
- if (type === 'string' || type === 'number' || type === 'boolean') {
72
- return value;
73
- }
74
- // BigInt: Convert to string for JSON-safety (JSON.stringify throws on raw BigInt)
75
- if (type === 'bigint') {
76
- return String(value);
77
- }
78
- // Functions are NOT safe - prevent code injection
79
- if (type === 'function') {
80
- throw new Error('Tool handler returned a function. Functions cannot be returned to sandbox code ' +
81
- 'as they could be used for code injection or host scope access.');
82
- }
83
- // Symbols are NOT safe - prevent prototype manipulation
84
- if (type === 'symbol') {
85
- throw new Error('Tool handler returned a symbol. Symbols cannot be returned to sandbox code ' +
86
- 'as they could be used for prototype manipulation.');
87
- }
88
- // Check for circular references (only for objects)
89
- if (type === 'object' && value !== null) {
90
- if (context.visited.has(value)) {
91
- // Return a marker for circular references instead of infinite recursion
92
- return '[Circular]';
93
- }
94
- context.visited.add(value);
95
- }
96
- // Handle arrays
97
- if (Array.isArray(value)) {
98
- context.propCount.count += value.length;
99
- if (context.propCount.count > maxProperties) {
100
- throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
101
- }
102
- return value.map((item) => sanitizeValue(item, options, depth + 1, context));
103
- }
104
- // Handle Date objects
105
- if (value instanceof Date) {
106
- if (allowDates) {
107
- // Return a new Date to prevent reference sharing
108
- return new Date(value.getTime());
109
- }
110
- // Convert to ISO string if dates not allowed
111
- return value.toISOString();
112
- }
113
- // Handle Error objects
114
- if (value instanceof Error) {
115
- if (allowErrors) {
116
- // Convert to plain object with safe properties only
117
- return {
118
- name: value.name,
119
- message: value.message,
120
- // Do NOT include stack trace - could leak host information
121
- };
122
- }
123
- return { error: value.message };
124
- }
125
- // Handle RegExp objects (convert to string)
126
- if (value instanceof RegExp) {
127
- return value.toString();
128
- }
129
- // Handle Map objects
130
- if (value instanceof Map) {
131
- const sanitizedMap = Object.create(null);
132
- for (const [key, val] of value.entries()) {
133
- if (typeof key !== 'string')
134
- continue; // Only string keys
135
- if (DANGEROUS_KEYS.has(key))
136
- continue; // Skip dangerous keys
137
- context.propCount.count++;
138
- sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
139
- }
140
- return sanitizedMap;
141
- }
142
- // Handle Set objects (convert to array)
143
- if (value instanceof Set) {
144
- const arr = Array.from(value);
145
- context.propCount.count += arr.length;
146
- return arr.map((item) => sanitizeValue(item, options, depth + 1, context));
147
- }
148
- // Handle plain objects
149
- if (type === 'object') {
150
- // Create null-prototype object to prevent prototype chain attacks
151
- const sanitized = Object.create(null);
152
- // Get own enumerable string keys only
153
- const keys = Object.keys(value);
154
- context.propCount.count += keys.length;
155
- if (context.propCount.count > maxProperties) {
156
- throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
157
- }
158
- for (const key of keys) {
159
- // Skip dangerous keys
160
- if (DANGEROUS_KEYS.has(key)) {
161
- continue;
162
- }
163
- // Try to access the property (may throw if getter trap)
164
- let propValue;
165
- try {
166
- propValue = value[key];
167
- }
168
- catch {
169
- // Skip properties that throw on access (likely getter traps)
170
- continue;
171
- }
172
- // Recursively sanitize - DO NOT catch these errors, let them propagate
173
- sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
174
- }
175
- return sanitized;
176
- }
177
- // Unknown type - convert to string
178
- return String(value);
179
- }
180
- /**
181
- * Check if a value can be safely sanitized without throwing
182
- *
183
- * @param value Value to check
184
- * @param options Sanitization options
185
- * @returns true if sanitization will succeed, false otherwise
186
- */
187
- function canSanitize(value, options = {}) {
188
- try {
189
- sanitizeValue(value, options);
190
- return true;
191
- }
192
- catch {
193
- return false;
194
- }
195
- }
196
- /**
197
- * Sanitize value with fallback on error
198
- *
199
- * @param value Value to sanitize
200
- * @param fallback Fallback value if sanitization fails
201
- * @param options Sanitization options
202
- * @returns Sanitized value or fallback
203
- */
204
- function sanitizeValueOrFallback(value, fallback, options = {}) {
205
- try {
206
- return sanitizeValue(value, options);
207
- }
208
- catch {
209
- return fallback;
210
- }
211
- }
212
- /**
213
- * Estimate the serialized (JSON) size of a string in bytes.
214
- * Accounts for quotes and proper JSON escaping.
215
- *
216
- * @param str The string to estimate
217
- * @returns Size in bytes when serialized as JSON string
218
- */
219
- function estimateStringSize(str) {
220
- let bytes = 2; // quotes
221
- for (let i = 0; i < str.length; i++) {
222
- const code = str.charCodeAt(i);
223
- if (code < 128) {
224
- // ASCII: check if needs escaping
225
- if (code === 34 || code === 92) {
226
- // Quote and backslash: 2-byte escape (\" or \\)
227
- bytes += 2;
228
- }
229
- else if (code < 32) {
230
- // Control characters: 6-byte \uXXXX escape
231
- bytes += 6;
232
- }
233
- else {
234
- bytes += 1;
235
- }
236
- }
237
- else if (code < 2048) {
238
- bytes += 2; // 2-byte UTF-8
239
- }
240
- else if (code >= 0xd800 && code <= 0xdbff && i + 1 < str.length) {
241
- // High surrogate - check for low surrogate pair (emoji, supplementary chars)
242
- const nextCode = str.charCodeAt(i + 1);
243
- if (nextCode >= 0xdc00 && nextCode <= 0xdfff) {
244
- bytes += 4; // 4-byte UTF-8 for surrogate pair
245
- i++; // Skip the low surrogate
246
- }
247
- else {
248
- bytes += 3; // Unpaired high surrogate (3-byte UTF-8)
249
- }
250
- }
251
- else {
252
- bytes += 3; // 3-byte UTF-8 (BMP characters U+0800 to U+FFFF)
253
- }
254
- }
255
- return bytes;
256
- }
257
- /**
258
- * Estimates the serialized (JSON) size of a value in bytes.
259
- *
260
- * Security feature: Prevents memory exhaustion attacks (Vector 340) where:
261
- * - Attacker creates a structure with many references to the same large string
262
- * - In-VM memory is small (strings are shared by reference)
263
- * - But JSON serialization expands each reference to full string copy
264
- * - Example: 500 refs × 5 copies × 10KB string = 25MB serialized from ~20KB in-memory
265
- *
266
- * This function counts EVERY string occurrence, not unique strings,
267
- * to accurately estimate the serialized output size.
268
- *
269
- * IMPORTANT: Circular reference handling:
270
- * - Uses a "current path" Set to detect circular references (ancestor chain)
271
- * - Repeated (non-circular) references to the same object are counted fully each time
272
- * - This matches JSON.stringify behavior where repeated refs are serialized multiple times
273
- *
274
- * @param value The value to estimate
275
- * @param maxBytes Maximum allowed serialized bytes (0 = no limit)
276
- * @param depth Current recursion depth (internal)
277
- * @param maxDepth Maximum recursion depth (default 2000 to handle deep structures)
278
- * @param currentPath Set tracking the current ancestor path (for circular detection only)
279
- * @returns Estimated serialized size in bytes
280
- * @throws Error if estimated size exceeds maxBytes or depth limit
281
- */
282
- function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2000, currentPath = new Set()) {
283
- // Depth limit to prevent stack overflow - reject deeply nested structures
284
- if (depth > maxDepth) {
285
- throw new Error(`Structure exceeds maximum nesting depth (${maxDepth}). ` +
286
- `Deeply nested structures are rejected to prevent stack overflow attacks.`);
287
- }
288
- // Handle null/undefined
289
- if (value === null)
290
- return 4; // "null"
291
- if (value === undefined)
292
- return 0; // undefined is omitted in JSON
293
- const type = typeof value;
294
- // String: count actual bytes (each occurrence, not unique!)
295
- if (type === 'string') {
296
- const bytes = estimateStringSize(value);
297
- if (maxBytes > 0 && bytes > maxBytes) {
298
- throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
299
- }
300
- return bytes;
301
- }
302
- // Number: estimate digit count
303
- if (type === 'number') {
304
- const num = value;
305
- if (!Number.isFinite(num))
306
- return 4; // "null" for Infinity/NaN
307
- return String(num).length;
308
- }
309
- // Boolean
310
- if (type === 'boolean') {
311
- return value ? 4 : 5; // "true" or "false"
312
- }
313
- // BigInt: Cannot be JSON.stringify'd directly, but estimate as string for size purposes
314
- // (caller is responsible for actual serialization, e.g., converting to string first)
315
- if (type === 'bigint') {
316
- return String(value).length + 2; // Estimate as quoted string
317
- }
318
- // Function/Symbol: shouldn't be serialized
319
- if (type === 'function' || type === 'symbol') {
320
- return 0; // omitted in JSON
321
- }
322
- // Arrays
323
- if (Array.isArray(value)) {
324
- // Check for circular reference (is this object an ancestor of itself?)
325
- if (currentPath.has(value)) {
326
- // Circular reference detected - JSON.stringify would throw, but we estimate small
327
- return 4;
328
- }
329
- // Add to current path for descendant checks
330
- currentPath.add(value);
331
- let size = 2; // brackets []
332
- for (let i = 0; i < value.length; i++) {
333
- if (i > 0)
334
- size += 1; // comma
335
- let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
336
- // JSON.stringify turns undefined/function/symbol array elements into null (4 bytes)
337
- if (elementSize === 0)
338
- elementSize = 4;
339
- size += elementSize;
340
- // Check limit incrementally to fail fast
341
- if (maxBytes > 0 && size > maxBytes) {
342
- currentPath.delete(value); // Clean up before throwing
343
- throw new Error(`Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. ` +
344
- `This often indicates repeated references to large strings that expand during JSON serialization.`);
345
- }
346
- }
347
- // Remove from current path (we're done with this branch)
348
- currentPath.delete(value);
349
- return size;
350
- }
351
- // Objects
352
- if (type === 'object' && value !== null) {
353
- // Check for circular reference (is this object an ancestor of itself?)
354
- if (currentPath.has(value)) {
355
- // Circular reference detected
356
- return 4;
357
- }
358
- // Add to current path for descendant checks
359
- currentPath.add(value);
360
- // Handle special objects
361
- if (value instanceof Date) {
362
- currentPath.delete(value);
363
- return 26; // ISO date string with quotes: "2024-01-01T00:00:00.000Z"
364
- }
365
- if (value instanceof RegExp) {
366
- // RegExp serializes to "{}" in JSON.stringify
367
- currentPath.delete(value);
368
- return 2; // "{}"
369
- }
370
- let size = 2; // braces {}
371
- const keys = Object.keys(value);
372
- let first = true;
373
- for (const key of keys) {
374
- // Skip dangerous keys (they're stripped)
375
- if (key === '__proto__' || key === 'constructor')
376
- continue;
377
- if (!first)
378
- size += 1; // comma
379
- first = false;
380
- // Key: quoted string + colon (accounting for JSON escaping)
381
- size += estimateStringSize(key) + 1; // "key":
382
- // Value
383
- let propValue;
384
- try {
385
- propValue = value[key];
386
- }
387
- catch {
388
- continue; // Skip throwing properties
389
- }
390
- const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
391
- size += valueSize;
392
- // Check limit incrementally to fail fast
393
- if (maxBytes > 0 && size > maxBytes) {
394
- currentPath.delete(value); // Clean up before throwing
395
- throw new Error(`Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. ` +
396
- `This often indicates repeated references to large strings that expand during JSON serialization.`);
397
- }
398
- }
399
- // Remove from current path (we're done with this branch)
400
- currentPath.delete(value);
401
- return size;
402
- }
403
- return 0;
404
- }
405
- /**
406
- * Check if a value's serialized size is within limits
407
- *
408
- * @param value Value to check
409
- * @param maxBytes Maximum allowed serialized bytes
410
- * @returns Object with ok status and estimated size or error message
411
- */
412
- function checkSerializedSize(value, maxBytes) {
413
- try {
414
- const estimatedBytes = estimateSerializedSize(value, maxBytes);
415
- return { ok: true, estimatedBytes };
416
- }
417
- catch (err) {
418
- return { ok: false, error: err instanceof Error ? err.message : 'Unknown error' };
419
- }
420
- }
421
- //# sourceMappingURL=value-sanitizer.js.map