@enclave-vm/core 2.17.0 → 2.18.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.
package/README.md CHANGED
@@ -93,6 +93,11 @@ interface CreateEnclaveOptions {
93
93
  toolHandler?: ToolHandler; // Function to execute tool calls
94
94
  toolNamespaces?: ToolNamespaces; // Expose tools as `ns.method(args)` (see "Tool Namespaces")
95
95
 
96
+ // Console
97
+ consoleHandler?: ConsoleHandler; // Receive console calls as (level, message) instead of the host console (see "Console Handler")
98
+ maxConsoleCalls?: number; // Maximum console calls (default: by security level)
99
+ maxConsoleOutputBytes?: number; // Maximum total console output (default: by security level)
100
+
96
101
  // Custom globals
97
102
  globals?: Record<string, unknown>; // Additional globals for the VM
98
103
  allowFunctionsInGlobals?: boolean; // Allow functions in globals (default: false)
@@ -161,6 +166,8 @@ Both AST validation and runtime sandbox enforce the same allowed globals for def
161
166
  | **Debugging** | | | | |
162
167
  | `console` | ❌ | ❌ | ❌ | ✅ |
163
168
 
169
+ With a `consoleHandler`, `console` is allowed at every level (see [Console Handler](#console-handler)).
170
+
164
171
  ### Blocked Globals (All Security Levels)
165
172
 
166
173
  These dangerous globals are **always blocked** regardless of security level:
@@ -180,6 +187,26 @@ These dangerous globals are **always blocked** regardless of security level:
180
187
  | **Error Types** | `Error`, `TypeError`, `ReferenceError`, `SyntaxError`, `RangeError` |
181
188
  | **Symbols/Regex** | `Symbol`, `RegExp` |
182
189
 
190
+ ### Console Handler
191
+
192
+ Without a `consoleHandler`, `console` is allowed only at `PERMISSIVE` and writes to the host process console. With one, scripts may use `console` at every security level and each call goes to the handler instead:
193
+
194
+ ```typescript
195
+ import { Enclave, type ConsoleHandler } from '@enclave-vm/core';
196
+
197
+ const consoleHandler: ConsoleHandler = (level, message) => logger[level](message);
198
+ const enclave = new Enclave({ securityLevel: 'STRICT', consoleHandler });
199
+
200
+ await enclave.run(`console.info('users', { count: 2 }); return 1;`); // logger.info('users {"count":2}')
201
+ ```
202
+
203
+ - `level` is a `ConsoleLevel` (`'log' | 'info' | 'warn' | 'error' | 'debug'`); `message` is the formatted line (arguments joined by spaces, objects JSON-serialized).
204
+ - `maxConsoleCalls` and `maxConsoleOutputBytes` are checked before the handler runs; past a limit the script's call throws and the handler is not called.
205
+ - The handler's return value is ignored and anything it throws or rejects with is swallowed.
206
+ - The script's `console` is a frozen, null-prototype object built inside the sandbox; it leads to neither the handler nor any host object.
207
+ - Supported by the double VM (default), the `vm` adapter and the `worker_threads` adapter. A custom `sandboxAdapter` receives the handler as `context.consoleHandler`; the built-in `InterpreterAdapter` has no `console`, so a script that uses it fails there.
208
+ - Combining a `consoleHandler` with a `console` entry in `globals` throws a `TypeError`.
209
+
183
210
  ### AST Presets
184
211
 
185
212
  The `preset` option controls **AST-level validation** - what JavaScript constructs are allowed before code transformation. This is separate from `securityLevel` which controls runtime security.
@@ -10,6 +10,7 @@ import { z } from 'zod';
10
10
  import { type NormalizedToolNamespace } from '@enclave-vm/ast';
11
11
  import type { ResourceUsage } from './config';
12
12
  import type { SpecialResultValue } from './result-encoding';
13
+ import type { ConsoleLevel } from '../../console-handler';
13
14
  /**
14
15
  * Serialized error format for cross-thread communication
15
16
  * Errors are serialized to prevent prototype pollution
@@ -72,6 +73,11 @@ export interface SerializedConfig {
72
73
  * `mail.list` through the worker's callTool)
73
74
  */
74
75
  toolNamespaces?: NormalizedToolNamespace[];
76
+ /**
77
+ * Whether the host has a consoleHandler: the sandbox then gets the handler console at every
78
+ * security level, and each console message carries one formatted line as its only argument
79
+ */
80
+ hasConsoleHandler?: boolean;
75
81
  }
76
82
  /**
77
83
  * Execute code in the worker
@@ -185,7 +191,7 @@ export interface ConsoleMessage {
185
191
  /** Execution request identifier */
186
192
  requestId: string;
187
193
  /** Console level */
188
- level: 'log' | 'warn' | 'error' | 'info';
194
+ level: ConsoleLevel;
189
195
  /** Console arguments */
190
196
  args: unknown[];
191
197
  }
@@ -257,9 +263,10 @@ export declare const consoleMessageSchema: z.ZodObject<{
257
263
  requestId: z.ZodString;
258
264
  level: z.ZodEnum<{
259
265
  log: "log";
266
+ info: "info";
260
267
  warn: "warn";
261
268
  error: "error";
262
- info: "info";
269
+ debug: "debug";
263
270
  }>;
264
271
  args: z.ZodArray<z.ZodUnknown>;
265
272
  }, z.core.$strict>;
@@ -323,9 +330,10 @@ export declare const workerToMainMessageSchema: z.ZodDiscriminatedUnion<[z.ZodOb
323
330
  requestId: z.ZodString;
324
331
  level: z.ZodEnum<{
325
332
  log: "log";
333
+ info: "info";
326
334
  warn: "warn";
327
335
  error: "error";
328
- info: "info";
336
+ debug: "debug";
329
337
  }>;
330
338
  args: z.ZodArray<z.ZodUnknown>;
331
339
  }, z.core.$strict>], "type">;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Routes a script's console calls to a host `consoleHandler` instead of the host console.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ /** A console method a script can call. */
7
+ export type ConsoleLevel = 'log' | 'info' | 'warn' | 'error' | 'debug';
8
+ /**
9
+ * Receives each console call of a script as its level and formatted line. Its return value is
10
+ * ignored and anything it throws or rejects with is swallowed.
11
+ */
12
+ export type ConsoleHandler = (level: ConsoleLevel, message: string) => void;
13
+ export interface ConsoleLimits {
14
+ maxConsoleCalls: number;
15
+ maxConsoleOutputBytes: number;
16
+ }
17
+ /**
18
+ * Host end of the sandbox console for one execution: accepts only a known level and a string,
19
+ * re-applies the limits, and never returns a value or throws.
20
+ */
21
+ export declare function createConsoleSink(handler: ConsoleHandler, limits: ConsoleLimits): (level: unknown, message: unknown) => void;
22
+ /**
23
+ * Evaluated in a sandbox realm, returns `install(write, maxCalls, maxBytes)`, which builds the
24
+ * script's console there: a frozen, null-prototype object whose realm-local methods format their
25
+ * arguments, enforce the limits with realm errors, then call `write(level, line)` and discard its
26
+ * result and errors.
27
+ */
28
+ export declare const CONSOLE_FACTORY_SOURCE: string;
package/enclave.d.ts CHANGED
@@ -51,6 +51,7 @@ export declare class Enclave {
51
51
  private readonly customGlobalNames;
52
52
  private readonly toolNamespaces;
53
53
  private readonly sandboxAdapter?;
54
+ private readonly consoleHandler?;
54
55
  private adapter?;
55
56
  constructor(options?: CreateEnclaveOptions);
56
57
  /**
package/esm/index.mjs CHANGED
@@ -2216,6 +2216,88 @@ var init_tool_bridge = __esm({
2216
2216
  }
2217
2217
  });
2218
2218
 
2219
+ // libs/core/src/console-handler.ts
2220
+ function createConsoleSink(handler, limits) {
2221
+ let callCount = 0;
2222
+ let totalLength = 0;
2223
+ return (level, message) => {
2224
+ if (!CONSOLE_LEVELS.has(level) || typeof message !== "string") return;
2225
+ callCount++;
2226
+ totalLength += message.length;
2227
+ if (callCount > limits.maxConsoleCalls || totalLength > limits.maxConsoleOutputBytes) return;
2228
+ try {
2229
+ Promise.resolve(handler(level, message)).catch(ignoreRejection);
2230
+ } catch {
2231
+ }
2232
+ };
2233
+ }
2234
+ var CONSOLE_LEVELS, ignoreRejection, CONSOLE_FACTORY_SOURCE;
2235
+ var init_console_handler = __esm({
2236
+ "libs/core/src/console-handler.ts"() {
2237
+ "use strict";
2238
+ CONSOLE_LEVELS = /* @__PURE__ */ new Set(["log", "info", "warn", "error", "debug"]);
2239
+ ignoreRejection = () => void 0;
2240
+ CONSOLE_FACTORY_SOURCE = `
2241
+ (function () {
2242
+ 'use strict';
2243
+ var stringify = JSON.stringify;
2244
+ // The realm's own String, even where a sandbox global shadows it.
2245
+ var toText = ''.constructor;
2246
+ var freeze = Object.freeze;
2247
+ var RealmError = Error;
2248
+
2249
+ function formatArgument(value) {
2250
+ if (value === undefined) return 'undefined';
2251
+ if (value === null) return 'null';
2252
+ if (typeof value === 'object') {
2253
+ try {
2254
+ var json = stringify(value);
2255
+ return json === undefined ? '' : json;
2256
+ } catch (e) {
2257
+ return toText(value);
2258
+ }
2259
+ }
2260
+ return toText(value);
2261
+ }
2262
+
2263
+ return function install(write, maxCalls, maxBytes) {
2264
+ var callCount = 0;
2265
+ var totalBytes = 0;
2266
+
2267
+ function method(level) {
2268
+ return (...args) => {
2269
+ callCount++;
2270
+ if (callCount > maxCalls) {
2271
+ throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
2272
+ }
2273
+ var line = '';
2274
+ for (var i = 0; i < args.length; i++) {
2275
+ line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
2276
+ }
2277
+ totalBytes += line.length;
2278
+ if (totalBytes > maxBytes) {
2279
+ throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
2280
+ }
2281
+ try {
2282
+ write(level, line);
2283
+ } catch (e) {}
2284
+ };
2285
+ }
2286
+
2287
+ return freeze({
2288
+ __proto__: null,
2289
+ log: method('log'),
2290
+ info: method('info'),
2291
+ warn: method('warn'),
2292
+ error: method('error'),
2293
+ debug: method('debug')
2294
+ });
2295
+ };
2296
+ })()
2297
+ `.trim();
2298
+ }
2299
+ });
2300
+
2219
2301
  // libs/core/src/tool-namespaces.ts
2220
2302
  function buildToolNamespaceBindings(install, callTool, namespaces) {
2221
2303
  if (namespaces.length === 0) return [];
@@ -2755,6 +2837,7 @@ ${stackTraceHardeningCode}
2755
2837
  const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
2756
2838
  const hostInvokeGlobal = typeof __host_invokeGlobal__ === 'function' ? __host_invokeGlobal__ : null;
2757
2839
  const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
2840
+ const hostConsoleSink = typeof __host_consoleSink__ === 'function' ? __host_consoleSink__ : null;
2758
2841
  const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
2759
2842
  const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
2760
2843
 
@@ -2769,6 +2852,7 @@ ${stackTraceHardeningCode}
2769
2852
  try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
2770
2853
  try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
2771
2854
  try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
2855
+ try { delete globalThis.__host_consoleSink__; } catch (e) { /* ignore */ }
2772
2856
 
2773
2857
  // Policy violation reporter (best-effort; host decides how to handle based on security level)
2774
2858
  function __ag_reportViolation(kind) {
@@ -3814,6 +3898,16 @@ ${stackTraceHardeningCode}
3814
3898
  info: createSafeConsoleMethod(console.info.bind(console))
3815
3899
  };
3816
3900
 
3901
+ // With a consoleHandler, the script's console is built inside the inner realm and writes
3902
+ // (level, line) strings to the host sink instead of the host console.
3903
+ function createHandlerConsole() {
3904
+ var installConsole = new vm.Script(${JSON.stringify(CONSOLE_FACTORY_SOURCE)}, {
3905
+ filename: 'inner-console.js'
3906
+ }).runInContext(innerContext);
3907
+ var writeToSink = createSecureProxy(function(level, line) { hostConsoleSink(level, line); });
3908
+ return installConsole(writeToSink, maxConsoleCalls, maxConsoleBytes);
3909
+ }
3910
+
3817
3911
  // ============================================================
3818
3912
  // Create Inner VM
3819
3913
  // ============================================================
@@ -4166,7 +4260,7 @@ ${stackTraceHardeningCode}
4166
4260
  __safe_while: createSecureProxy(innerWhile),
4167
4261
  __safe_doWhile: createSecureProxy(innerDoWhile),
4168
4262
  __safe_parallel: createSecureProxy(innerParallel),
4169
- __safe_console: createSecureProxy(innerConsole),
4263
+ __safe_console: hostConsoleSink ? createHandlerConsole() : createSecureProxy(innerConsole),
4170
4264
  callTool: createSecureProxy(innerCallTool),
4171
4265
  parallel: createSecureProxy(innerParallel),
4172
4266
  // Loop transformation runtime support
@@ -4470,6 +4564,7 @@ var init_parent_vm_bootstrap = __esm({
4470
4564
  "use strict";
4471
4565
  init_global_function_gate();
4472
4566
  init_tool_namespaces();
4567
+ init_console_handler();
4473
4568
  MEMBRANE_MAX_RECURSION_DEPTH = 256;
4474
4569
  NODEJS_24_DANGEROUS_GLOBALS = {
4475
4570
  STRICT: [
@@ -4693,6 +4788,7 @@ var init_double_vm_wrapper = __esm({
4693
4788
  init_memory_tracker();
4694
4789
  init_tool_bridge();
4695
4790
  init_stack_trace();
4791
+ init_console_handler();
4696
4792
  init_global_function_gate();
4697
4793
  init_parent_vm_bootstrap();
4698
4794
  init_suspicious_patterns();
@@ -4901,6 +4997,14 @@ var init_double_vm_wrapper = __esm({
4901
4997
  configurable: true
4902
4998
  // Allow deletion after capture for defense-in-depth
4903
4999
  });
5000
+ if (executionContext.consoleHandler) {
5001
+ Object.defineProperty(parentContext, "__host_consoleSink__", {
5002
+ value: createConsoleSink(executionContext.consoleHandler, config),
5003
+ writable: false,
5004
+ configurable: true
5005
+ // Allow deletion after capture for defense-in-depth
5006
+ });
5007
+ }
4904
5008
  if (memoryTracker) {
4905
5009
  Object.defineProperty(parentContext, "__host_memory_track__", {
4906
5010
  value: (bytes) => {
@@ -5760,12 +5864,71 @@ var init_safe_runtime = __esm({
5760
5864
  }
5761
5865
  });
5762
5866
 
5867
+ // libs/core/src/sandbox-console.ts
5868
+ function createHostConsoleWriter(methods) {
5869
+ return (level, ...args) => {
5870
+ try {
5871
+ methods[level](...args);
5872
+ return void 0;
5873
+ } catch (error) {
5874
+ if (error instanceof Error) return `${error.name}
5875
+ ${error.message}`;
5876
+ throw error;
5877
+ }
5878
+ };
5879
+ }
5880
+ var SANDBOX_CONSOLE_FACTORY_SOURCE;
5881
+ var init_sandbox_console = __esm({
5882
+ "libs/core/src/sandbox-console.ts"() {
5883
+ "use strict";
5884
+ SANDBOX_CONSOLE_FACTORY_SOURCE = `
5885
+ (function () {
5886
+ 'use strict';
5887
+ var RealmObject = ({}).constructor;
5888
+ var getPrototypeOf = RealmObject.getPrototypeOf;
5889
+ var freeze = RealmObject.freeze;
5890
+ var RealmError = (function () {
5891
+ try {
5892
+ null.f;
5893
+ } catch (e) {
5894
+ return getPrototypeOf(getPrototypeOf(e)).constructor;
5895
+ }
5896
+ })();
5897
+
5898
+ function method(write, level) {
5899
+ return (...args) => {
5900
+ var failure = write(level, ...args);
5901
+ if (typeof failure === 'string') {
5902
+ var separator = failure.indexOf('\\n');
5903
+ var error = new RealmError(failure.slice(separator + 1));
5904
+ error.name = failure.slice(0, separator);
5905
+ throw error;
5906
+ }
5907
+ };
5908
+ }
5909
+
5910
+ return function install(write, levels) {
5911
+ var methods = { __proto__: null };
5912
+ for (var i = 0; i < levels.length; i++) {
5913
+ methods[levels[i]] = method(write, levels[i]);
5914
+ }
5915
+ return freeze(methods);
5916
+ };
5917
+ })()
5918
+ `.trim();
5919
+ }
5920
+ });
5921
+
5763
5922
  // libs/core/src/adapters/vm-adapter.ts
5764
5923
  var vm_adapter_exports = {};
5765
5924
  __export(vm_adapter_exports, {
5766
5925
  VmAdapter: () => VmAdapter
5767
5926
  });
5768
5927
  import * as vm4 from "vm";
5928
+ function createHandlerConsole(sandbox, handler, limits) {
5929
+ const install = CONSOLE_FACTORY_SCRIPT.runInContext(sandbox);
5930
+ return install(createConsoleSink(handler, limits), limits.maxConsoleCalls, limits.maxConsoleOutputBytes);
5931
+ }
5769
5932
  function createSafeConsole(config, stats) {
5770
5933
  const wrap = (method) => (...args) => {
5771
5934
  stats.callCount++;
@@ -5929,7 +6092,7 @@ function sanitizeVmContext(context, securityLevel) {
5929
6092
  enumerable: true
5930
6093
  });
5931
6094
  }
5932
- var STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, SANDBOX_REALM_BRIDGE_SCRIPT, TOOL_NAMESPACE_FACTORY_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
6095
+ var STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, SANDBOX_REALM_BRIDGE_SCRIPT, TOOL_NAMESPACE_FACTORY_SCRIPT, SANDBOX_CONSOLE_FACTORY_SCRIPT, CONSOLE_FACTORY_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
5933
6096
  var init_vm_adapter = __esm({
5934
6097
  "libs/core/src/adapters/vm-adapter.ts"() {
5935
6098
  "use strict";
@@ -5942,6 +6105,8 @@ var init_vm_adapter = __esm({
5942
6105
  init_stack_trace();
5943
6106
  init_global_function_gate();
5944
6107
  init_tool_namespaces();
6108
+ init_console_handler();
6109
+ init_sandbox_console();
5945
6110
  STACK_TRACE_HARDENING_CODE = `
5946
6111
  (function() {
5947
6112
  function __ag_redactStackString(stackStr) {
@@ -6121,6 +6286,8 @@ var init_vm_adapter = __esm({
6121
6286
  })()
6122
6287
  `);
6123
6288
  TOOL_NAMESPACE_FACTORY_SCRIPT = new vm4.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
6289
+ SANDBOX_CONSOLE_FACTORY_SCRIPT = new vm4.Script(SANDBOX_CONSOLE_FACTORY_SOURCE, { filename: "console.js" });
6290
+ CONSOLE_FACTORY_SCRIPT = new vm4.Script(CONSOLE_FACTORY_SOURCE, { filename: "handler-console.js" });
6124
6291
  PROTECTED_PREFIXES = ["__safe_", "__ag_"];
6125
6292
  DANGEROUS_OBJECT_STATIC_METHODS = [
6126
6293
  "defineProperty",
@@ -6244,6 +6411,8 @@ var init_vm_adapter = __esm({
6244
6411
  );
6245
6412
  const realmBridge = SANDBOX_REALM_BRIDGE_SCRIPT.runInContext(baseSandbox);
6246
6413
  const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
6414
+ const handlerConsole = executionContext.consoleHandler ? createHandlerConsole(baseSandbox, executionContext.consoleHandler, config) : void 0;
6415
+ const installConsole = handlerConsole ? void 0 : SANDBOX_CONSOLE_FACTORY_SCRIPT.runInContext(baseSandbox);
6247
6416
  const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge);
6248
6417
  const safeRuntime = createSafeRuntime(executionContext, {
6249
6418
  sidecar: executionContext.sidecar,
@@ -6598,12 +6767,17 @@ var init_vm_adapter = __esm({
6598
6767
  if (!("__safe_console" in safeRuntime)) {
6599
6768
  const consoleStats = { totalBytes: 0, callCount: 0 };
6600
6769
  Object.defineProperty(baseSandbox, "__safe_console", {
6601
- value: createSafeConsole(
6602
- {
6603
- maxConsoleOutputBytes: config.maxConsoleOutputBytes,
6604
- maxConsoleCalls: config.maxConsoleCalls
6605
- },
6606
- consoleStats
6770
+ value: handlerConsole ?? installConsole?.(
6771
+ createHostConsoleWriter(
6772
+ createSafeConsole(
6773
+ {
6774
+ maxConsoleOutputBytes: config.maxConsoleOutputBytes,
6775
+ maxConsoleCalls: config.maxConsoleCalls
6776
+ },
6777
+ consoleStats
6778
+ )
6779
+ ),
6780
+ ["log", "error", "warn", "info"]
6607
6781
  ),
6608
6782
  writable: false,
6609
6783
  configurable: false,
@@ -6910,7 +7084,7 @@ var init_protocol = __esm({
6910
7084
  consoleMessageSchema = z.object({
6911
7085
  type: z.literal("console"),
6912
7086
  requestId: z.string().min(1).max(100).regex(ID_PATTERN),
6913
- level: z.enum(["log", "warn", "error", "info"]),
7087
+ level: z.enum(["log", "warn", "error", "info", "debug"]),
6914
7088
  args: z.array(z.unknown()).max(100)
6915
7089
  }).strict();
6916
7090
  workerReadyMessageSchema = z.object({
@@ -7934,6 +8108,7 @@ var init_worker_pool_adapter = __esm({
7934
8108
  init_result_encoding();
7935
8109
  init_errors();
7936
8110
  init_stack_trace();
8111
+ init_console_handler();
7937
8112
  WorkerPoolAdapter = class {
7938
8113
  config;
7939
8114
  securityLevel;
@@ -8160,6 +8335,7 @@ var init_worker_pool_adapter = __esm({
8160
8335
  async executeInSlot(slot, code, context) {
8161
8336
  const requestId = `exec-${Date.now()}-${crypto.randomUUID()}`;
8162
8337
  const startTime = Date.now();
8338
+ const consoleSink = context.consoleHandler ? createConsoleSink(context.consoleHandler, context.config) : void 0;
8163
8339
  const serializedConfig = {
8164
8340
  timeout: context.config.timeout,
8165
8341
  maxIterations: context.config.maxIterations,
@@ -8173,7 +8349,8 @@ var init_worker_pool_adapter = __esm({
8173
8349
  // Security level determines which globals are available in sandbox
8174
8350
  // This mirrors AST guard's allowed globals for defense-in-depth
8175
8351
  securityLevel: this.securityLevel,
8176
- toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0
8352
+ toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0,
8353
+ hasConsoleHandler: consoleSink !== void 0
8177
8354
  };
8178
8355
  return new Promise((resolve, reject) => {
8179
8356
  const pendingToolCalls = /* @__PURE__ */ new Map();
@@ -8193,7 +8370,11 @@ var init_worker_pool_adapter = __esm({
8193
8370
  const result = this.buildResult(msg, duration, context.config.sanitizeStackTraces);
8194
8371
  resolve(result);
8195
8372
  } else if (isConsoleMessage(msg) && msg.requestId === requestId) {
8196
- this.handleConsoleMessage(msg);
8373
+ if (consoleSink) {
8374
+ consoleSink(msg.level, msg.args[0]);
8375
+ } else {
8376
+ this.handleConsoleMessage(msg);
8377
+ }
8197
8378
  }
8198
8379
  } catch (error) {
8199
8380
  cleanup();
@@ -11296,6 +11477,7 @@ var Enclave = class {
11296
11477
  customGlobalNames;
11297
11478
  toolNamespaces;
11298
11479
  sandboxAdapter;
11480
+ consoleHandler;
11299
11481
  adapter;
11300
11482
  constructor(options = {}) {
11301
11483
  this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
@@ -11307,6 +11489,15 @@ var Enclave = class {
11307
11489
  allowGettersSetters: false
11308
11490
  });
11309
11491
  }
11492
+ if (options.consoleHandler !== void 0) {
11493
+ if (typeof options.consoleHandler !== "function") {
11494
+ throw new TypeError("consoleHandler must be a function");
11495
+ }
11496
+ if (options.globals && Object.hasOwn(options.globals, "console")) {
11497
+ throw new TypeError("consoleHandler cannot be combined with a custom `console` global");
11498
+ }
11499
+ }
11500
+ this.consoleHandler = options.consoleHandler;
11310
11501
  const normalizedToolBridge = {
11311
11502
  mode: options.toolBridge?.mode ?? "string",
11312
11503
  maxPayloadBytes: options.toolBridge?.maxPayloadBytes ?? DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES,
@@ -11532,6 +11723,7 @@ ${errorMessages}`,
11532
11723
  abortController: new AbortController(),
11533
11724
  aborted: false,
11534
11725
  toolHandler: toolHandler || this.config.toolHandler,
11726
+ consoleHandler: this.consoleHandler,
11535
11727
  sidecar,
11536
11728
  referenceConfig: this.referenceConfig,
11537
11729
  secureProxyConfig: this.config.secureProxyConfig,
@@ -11742,7 +11934,13 @@ ${errorMessages}`,
11742
11934
  "__safe_template"
11743
11935
  // Memory-safe template literals
11744
11936
  ];
11745
- const allAllowedGlobals = [...securityLevelGlobals, ...enclaveSpecificGlobals, ...customAllowedGlobals];
11937
+ const consoleGlobals = this.consoleHandler ? ["console", "__safe_console"] : [];
11938
+ const allAllowedGlobals = [
11939
+ ...securityLevelGlobals,
11940
+ ...enclaveSpecificGlobals,
11941
+ ...consoleGlobals,
11942
+ ...customAllowedGlobals
11943
+ ];
11746
11944
  switch (presetName) {
11747
11945
  case "agentscript":
11748
11946
  return new JSAstValidator(
package/index.d.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  * @packageDocumentation
12
12
  */
13
13
  export { Enclave, runAgentScript } from './enclave';
14
- export type { ExecutionResult, ExecutionError, ExecutionStats, EnclaveConfig, CreateEnclaveOptions, ToolHandler, SafeRuntimeContext, ExecutionContext, SandboxAdapter, SecurityLevel, AstPreset, SecurityLevelConfig, SecureProxyLevelConfig, ReferenceSidecarOptions, WorkerPoolConfig, PartialDoubleVmConfig, CallToolOptions, ToolCallResult, ToolCallErrorInfo, ToolNamespaces, NormalizedToolNamespace, } from './types';
14
+ export type { ExecutionResult, ExecutionError, ExecutionStats, EnclaveConfig, CreateEnclaveOptions, ToolHandler, SafeRuntimeContext, ExecutionContext, SandboxAdapter, SecurityLevel, AstPreset, SecurityLevelConfig, SecureProxyLevelConfig, ReferenceSidecarOptions, WorkerPoolConfig, PartialDoubleVmConfig, CallToolOptions, ToolCallResult, ToolCallErrorInfo, ToolNamespaces, NormalizedToolNamespace, ConsoleHandler, ConsoleLevel, } from './types';
15
15
  export { SECURITY_LEVEL_CONFIGS } from './types';
16
16
  export { ScoringGate, ScoringGateError, createScoringGate, FeatureExtractor, ScoringCache, BaseScorer, DisabledScorer, RuleBasedScorer, ExternalApiScorer, ExternalApiScorerError, DEFAULT_SCORING_CONFIG, RULE_THRESHOLDS, } from './scoring';
17
17
  export type { Scorer, ScorerType, RiskLevel, SensitiveCategory, RuleId, ExtractedFeatures, ExtractedToolCall, PatternSignals, NumericSignals, SensitiveAccess, ExtractionMeta, RiskSignal, ScoringResult, ScoringGateResult, ScoringGateConfig, ScoringCacheConfig, LocalLlmConfig, ExternalApiConfig, } from './scoring';
package/index.js CHANGED
@@ -2238,6 +2238,88 @@ var init_tool_bridge = __esm({
2238
2238
  }
2239
2239
  });
2240
2240
 
2241
+ // libs/core/src/console-handler.ts
2242
+ function createConsoleSink(handler, limits) {
2243
+ let callCount = 0;
2244
+ let totalLength = 0;
2245
+ return (level, message) => {
2246
+ if (!CONSOLE_LEVELS.has(level) || typeof message !== "string") return;
2247
+ callCount++;
2248
+ totalLength += message.length;
2249
+ if (callCount > limits.maxConsoleCalls || totalLength > limits.maxConsoleOutputBytes) return;
2250
+ try {
2251
+ Promise.resolve(handler(level, message)).catch(ignoreRejection);
2252
+ } catch {
2253
+ }
2254
+ };
2255
+ }
2256
+ var CONSOLE_LEVELS, ignoreRejection, CONSOLE_FACTORY_SOURCE;
2257
+ var init_console_handler = __esm({
2258
+ "libs/core/src/console-handler.ts"() {
2259
+ "use strict";
2260
+ CONSOLE_LEVELS = /* @__PURE__ */ new Set(["log", "info", "warn", "error", "debug"]);
2261
+ ignoreRejection = () => void 0;
2262
+ CONSOLE_FACTORY_SOURCE = `
2263
+ (function () {
2264
+ 'use strict';
2265
+ var stringify = JSON.stringify;
2266
+ // The realm's own String, even where a sandbox global shadows it.
2267
+ var toText = ''.constructor;
2268
+ var freeze = Object.freeze;
2269
+ var RealmError = Error;
2270
+
2271
+ function formatArgument(value) {
2272
+ if (value === undefined) return 'undefined';
2273
+ if (value === null) return 'null';
2274
+ if (typeof value === 'object') {
2275
+ try {
2276
+ var json = stringify(value);
2277
+ return json === undefined ? '' : json;
2278
+ } catch (e) {
2279
+ return toText(value);
2280
+ }
2281
+ }
2282
+ return toText(value);
2283
+ }
2284
+
2285
+ return function install(write, maxCalls, maxBytes) {
2286
+ var callCount = 0;
2287
+ var totalBytes = 0;
2288
+
2289
+ function method(level) {
2290
+ return (...args) => {
2291
+ callCount++;
2292
+ if (callCount > maxCalls) {
2293
+ throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
2294
+ }
2295
+ var line = '';
2296
+ for (var i = 0; i < args.length; i++) {
2297
+ line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
2298
+ }
2299
+ totalBytes += line.length;
2300
+ if (totalBytes > maxBytes) {
2301
+ throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
2302
+ }
2303
+ try {
2304
+ write(level, line);
2305
+ } catch (e) {}
2306
+ };
2307
+ }
2308
+
2309
+ return freeze({
2310
+ __proto__: null,
2311
+ log: method('log'),
2312
+ info: method('info'),
2313
+ warn: method('warn'),
2314
+ error: method('error'),
2315
+ debug: method('debug')
2316
+ });
2317
+ };
2318
+ })()
2319
+ `.trim();
2320
+ }
2321
+ });
2322
+
2241
2323
  // libs/core/src/tool-namespaces.ts
2242
2324
  function buildToolNamespaceBindings(install, callTool, namespaces) {
2243
2325
  if (namespaces.length === 0) return [];
@@ -2777,6 +2859,7 @@ ${stackTraceHardeningCode}
2777
2859
  const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
2778
2860
  const hostInvokeGlobal = typeof __host_invokeGlobal__ === 'function' ? __host_invokeGlobal__ : null;
2779
2861
  const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
2862
+ const hostConsoleSink = typeof __host_consoleSink__ === 'function' ? __host_consoleSink__ : null;
2780
2863
  const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
2781
2864
  const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
2782
2865
 
@@ -2791,6 +2874,7 @@ ${stackTraceHardeningCode}
2791
2874
  try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
2792
2875
  try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
2793
2876
  try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
2877
+ try { delete globalThis.__host_consoleSink__; } catch (e) { /* ignore */ }
2794
2878
 
2795
2879
  // Policy violation reporter (best-effort; host decides how to handle based on security level)
2796
2880
  function __ag_reportViolation(kind) {
@@ -3836,6 +3920,16 @@ ${stackTraceHardeningCode}
3836
3920
  info: createSafeConsoleMethod(console.info.bind(console))
3837
3921
  };
3838
3922
 
3923
+ // With a consoleHandler, the script's console is built inside the inner realm and writes
3924
+ // (level, line) strings to the host sink instead of the host console.
3925
+ function createHandlerConsole() {
3926
+ var installConsole = new vm.Script(${JSON.stringify(CONSOLE_FACTORY_SOURCE)}, {
3927
+ filename: 'inner-console.js'
3928
+ }).runInContext(innerContext);
3929
+ var writeToSink = createSecureProxy(function(level, line) { hostConsoleSink(level, line); });
3930
+ return installConsole(writeToSink, maxConsoleCalls, maxConsoleBytes);
3931
+ }
3932
+
3839
3933
  // ============================================================
3840
3934
  // Create Inner VM
3841
3935
  // ============================================================
@@ -4188,7 +4282,7 @@ ${stackTraceHardeningCode}
4188
4282
  __safe_while: createSecureProxy(innerWhile),
4189
4283
  __safe_doWhile: createSecureProxy(innerDoWhile),
4190
4284
  __safe_parallel: createSecureProxy(innerParallel),
4191
- __safe_console: createSecureProxy(innerConsole),
4285
+ __safe_console: hostConsoleSink ? createHandlerConsole() : createSecureProxy(innerConsole),
4192
4286
  callTool: createSecureProxy(innerCallTool),
4193
4287
  parallel: createSecureProxy(innerParallel),
4194
4288
  // Loop transformation runtime support
@@ -4492,6 +4586,7 @@ var init_parent_vm_bootstrap = __esm({
4492
4586
  "use strict";
4493
4587
  init_global_function_gate();
4494
4588
  init_tool_namespaces();
4589
+ init_console_handler();
4495
4590
  MEMBRANE_MAX_RECURSION_DEPTH = 256;
4496
4591
  NODEJS_24_DANGEROUS_GLOBALS = {
4497
4592
  STRICT: [
@@ -4715,6 +4810,7 @@ var init_double_vm_wrapper = __esm({
4715
4810
  init_memory_tracker();
4716
4811
  init_tool_bridge();
4717
4812
  init_stack_trace();
4813
+ init_console_handler();
4718
4814
  init_global_function_gate();
4719
4815
  init_parent_vm_bootstrap();
4720
4816
  init_suspicious_patterns();
@@ -4923,6 +5019,14 @@ var init_double_vm_wrapper = __esm({
4923
5019
  configurable: true
4924
5020
  // Allow deletion after capture for defense-in-depth
4925
5021
  });
5022
+ if (executionContext.consoleHandler) {
5023
+ Object.defineProperty(parentContext, "__host_consoleSink__", {
5024
+ value: createConsoleSink(executionContext.consoleHandler, config),
5025
+ writable: false,
5026
+ configurable: true
5027
+ // Allow deletion after capture for defense-in-depth
5028
+ });
5029
+ }
4926
5030
  if (memoryTracker) {
4927
5031
  Object.defineProperty(parentContext, "__host_memory_track__", {
4928
5032
  value: (bytes) => {
@@ -5782,11 +5886,70 @@ var init_safe_runtime = __esm({
5782
5886
  }
5783
5887
  });
5784
5888
 
5889
+ // libs/core/src/sandbox-console.ts
5890
+ function createHostConsoleWriter(methods) {
5891
+ return (level, ...args) => {
5892
+ try {
5893
+ methods[level](...args);
5894
+ return void 0;
5895
+ } catch (error) {
5896
+ if (error instanceof Error) return `${error.name}
5897
+ ${error.message}`;
5898
+ throw error;
5899
+ }
5900
+ };
5901
+ }
5902
+ var SANDBOX_CONSOLE_FACTORY_SOURCE;
5903
+ var init_sandbox_console = __esm({
5904
+ "libs/core/src/sandbox-console.ts"() {
5905
+ "use strict";
5906
+ SANDBOX_CONSOLE_FACTORY_SOURCE = `
5907
+ (function () {
5908
+ 'use strict';
5909
+ var RealmObject = ({}).constructor;
5910
+ var getPrototypeOf = RealmObject.getPrototypeOf;
5911
+ var freeze = RealmObject.freeze;
5912
+ var RealmError = (function () {
5913
+ try {
5914
+ null.f;
5915
+ } catch (e) {
5916
+ return getPrototypeOf(getPrototypeOf(e)).constructor;
5917
+ }
5918
+ })();
5919
+
5920
+ function method(write, level) {
5921
+ return (...args) => {
5922
+ var failure = write(level, ...args);
5923
+ if (typeof failure === 'string') {
5924
+ var separator = failure.indexOf('\\n');
5925
+ var error = new RealmError(failure.slice(separator + 1));
5926
+ error.name = failure.slice(0, separator);
5927
+ throw error;
5928
+ }
5929
+ };
5930
+ }
5931
+
5932
+ return function install(write, levels) {
5933
+ var methods = { __proto__: null };
5934
+ for (var i = 0; i < levels.length; i++) {
5935
+ methods[levels[i]] = method(write, levels[i]);
5936
+ }
5937
+ return freeze(methods);
5938
+ };
5939
+ })()
5940
+ `.trim();
5941
+ }
5942
+ });
5943
+
5785
5944
  // libs/core/src/adapters/vm-adapter.ts
5786
5945
  var vm_adapter_exports = {};
5787
5946
  __export(vm_adapter_exports, {
5788
5947
  VmAdapter: () => VmAdapter
5789
5948
  });
5949
+ function createHandlerConsole(sandbox, handler, limits) {
5950
+ const install = CONSOLE_FACTORY_SCRIPT.runInContext(sandbox);
5951
+ return install(createConsoleSink(handler, limits), limits.maxConsoleCalls, limits.maxConsoleOutputBytes);
5952
+ }
5790
5953
  function createSafeConsole(config, stats) {
5791
5954
  const wrap = (method) => (...args) => {
5792
5955
  stats.callCount++;
@@ -5950,7 +6113,7 @@ function sanitizeVmContext(context, securityLevel) {
5950
6113
  enumerable: true
5951
6114
  });
5952
6115
  }
5953
- var vm4, STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, SANDBOX_REALM_BRIDGE_SCRIPT, TOOL_NAMESPACE_FACTORY_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
6116
+ var vm4, STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, SANDBOX_REALM_BRIDGE_SCRIPT, TOOL_NAMESPACE_FACTORY_SCRIPT, SANDBOX_CONSOLE_FACTORY_SCRIPT, CONSOLE_FACTORY_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
5954
6117
  var init_vm_adapter = __esm({
5955
6118
  "libs/core/src/adapters/vm-adapter.ts"() {
5956
6119
  "use strict";
@@ -5964,6 +6127,8 @@ var init_vm_adapter = __esm({
5964
6127
  init_stack_trace();
5965
6128
  init_global_function_gate();
5966
6129
  init_tool_namespaces();
6130
+ init_console_handler();
6131
+ init_sandbox_console();
5967
6132
  STACK_TRACE_HARDENING_CODE = `
5968
6133
  (function() {
5969
6134
  function __ag_redactStackString(stackStr) {
@@ -6143,6 +6308,8 @@ var init_vm_adapter = __esm({
6143
6308
  })()
6144
6309
  `);
6145
6310
  TOOL_NAMESPACE_FACTORY_SCRIPT = new vm4.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
6311
+ SANDBOX_CONSOLE_FACTORY_SCRIPT = new vm4.Script(SANDBOX_CONSOLE_FACTORY_SOURCE, { filename: "console.js" });
6312
+ CONSOLE_FACTORY_SCRIPT = new vm4.Script(CONSOLE_FACTORY_SOURCE, { filename: "handler-console.js" });
6146
6313
  PROTECTED_PREFIXES = ["__safe_", "__ag_"];
6147
6314
  DANGEROUS_OBJECT_STATIC_METHODS = [
6148
6315
  "defineProperty",
@@ -6266,6 +6433,8 @@ var init_vm_adapter = __esm({
6266
6433
  );
6267
6434
  const realmBridge = SANDBOX_REALM_BRIDGE_SCRIPT.runInContext(baseSandbox);
6268
6435
  const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
6436
+ const handlerConsole = executionContext.consoleHandler ? createHandlerConsole(baseSandbox, executionContext.consoleHandler, config) : void 0;
6437
+ const installConsole = handlerConsole ? void 0 : SANDBOX_CONSOLE_FACTORY_SCRIPT.runInContext(baseSandbox);
6269
6438
  const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge);
6270
6439
  const safeRuntime = createSafeRuntime(executionContext, {
6271
6440
  sidecar: executionContext.sidecar,
@@ -6620,12 +6789,17 @@ var init_vm_adapter = __esm({
6620
6789
  if (!("__safe_console" in safeRuntime)) {
6621
6790
  const consoleStats = { totalBytes: 0, callCount: 0 };
6622
6791
  Object.defineProperty(baseSandbox, "__safe_console", {
6623
- value: createSafeConsole(
6624
- {
6625
- maxConsoleOutputBytes: config.maxConsoleOutputBytes,
6626
- maxConsoleCalls: config.maxConsoleCalls
6627
- },
6628
- consoleStats
6792
+ value: handlerConsole ?? installConsole?.(
6793
+ createHostConsoleWriter(
6794
+ createSafeConsole(
6795
+ {
6796
+ maxConsoleOutputBytes: config.maxConsoleOutputBytes,
6797
+ maxConsoleCalls: config.maxConsoleCalls
6798
+ },
6799
+ consoleStats
6800
+ )
6801
+ ),
6802
+ ["log", "error", "warn", "info"]
6629
6803
  ),
6630
6804
  writable: false,
6631
6805
  configurable: false,
@@ -6932,7 +7106,7 @@ var init_protocol = __esm({
6932
7106
  consoleMessageSchema = import_zod.z.object({
6933
7107
  type: import_zod.z.literal("console"),
6934
7108
  requestId: import_zod.z.string().min(1).max(100).regex(ID_PATTERN),
6935
- level: import_zod.z.enum(["log", "warn", "error", "info"]),
7109
+ level: import_zod.z.enum(["log", "warn", "error", "info", "debug"]),
6936
7110
  args: import_zod.z.array(import_zod.z.unknown()).max(100)
6937
7111
  }).strict();
6938
7112
  workerReadyMessageSchema = import_zod.z.object({
@@ -7956,6 +8130,7 @@ var init_worker_pool_adapter = __esm({
7956
8130
  init_result_encoding();
7957
8131
  init_errors();
7958
8132
  init_stack_trace();
8133
+ init_console_handler();
7959
8134
  WorkerPoolAdapter = class {
7960
8135
  config;
7961
8136
  securityLevel;
@@ -8182,6 +8357,7 @@ var init_worker_pool_adapter = __esm({
8182
8357
  async executeInSlot(slot, code, context) {
8183
8358
  const requestId = `exec-${Date.now()}-${import_crypto3.default.randomUUID()}`;
8184
8359
  const startTime = Date.now();
8360
+ const consoleSink = context.consoleHandler ? createConsoleSink(context.consoleHandler, context.config) : void 0;
8185
8361
  const serializedConfig = {
8186
8362
  timeout: context.config.timeout,
8187
8363
  maxIterations: context.config.maxIterations,
@@ -8195,7 +8371,8 @@ var init_worker_pool_adapter = __esm({
8195
8371
  // Security level determines which globals are available in sandbox
8196
8372
  // This mirrors AST guard's allowed globals for defense-in-depth
8197
8373
  securityLevel: this.securityLevel,
8198
- toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0
8374
+ toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0,
8375
+ hasConsoleHandler: consoleSink !== void 0
8199
8376
  };
8200
8377
  return new Promise((resolve, reject) => {
8201
8378
  const pendingToolCalls = /* @__PURE__ */ new Map();
@@ -8215,7 +8392,11 @@ var init_worker_pool_adapter = __esm({
8215
8392
  const result = this.buildResult(msg, duration, context.config.sanitizeStackTraces);
8216
8393
  resolve(result);
8217
8394
  } else if (isConsoleMessage(msg) && msg.requestId === requestId) {
8218
- this.handleConsoleMessage(msg);
8395
+ if (consoleSink) {
8396
+ consoleSink(msg.level, msg.args[0]);
8397
+ } else {
8398
+ this.handleConsoleMessage(msg);
8399
+ }
8219
8400
  }
8220
8401
  } catch (error) {
8221
8402
  cleanup();
@@ -11389,6 +11570,7 @@ var Enclave = class {
11389
11570
  customGlobalNames;
11390
11571
  toolNamespaces;
11391
11572
  sandboxAdapter;
11573
+ consoleHandler;
11392
11574
  adapter;
11393
11575
  constructor(options = {}) {
11394
11576
  this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
@@ -11400,6 +11582,15 @@ var Enclave = class {
11400
11582
  allowGettersSetters: false
11401
11583
  });
11402
11584
  }
11585
+ if (options.consoleHandler !== void 0) {
11586
+ if (typeof options.consoleHandler !== "function") {
11587
+ throw new TypeError("consoleHandler must be a function");
11588
+ }
11589
+ if (options.globals && Object.hasOwn(options.globals, "console")) {
11590
+ throw new TypeError("consoleHandler cannot be combined with a custom `console` global");
11591
+ }
11592
+ }
11593
+ this.consoleHandler = options.consoleHandler;
11403
11594
  const normalizedToolBridge = {
11404
11595
  mode: options.toolBridge?.mode ?? "string",
11405
11596
  maxPayloadBytes: options.toolBridge?.maxPayloadBytes ?? DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES,
@@ -11625,6 +11816,7 @@ ${errorMessages}`,
11625
11816
  abortController: new AbortController(),
11626
11817
  aborted: false,
11627
11818
  toolHandler: toolHandler || this.config.toolHandler,
11819
+ consoleHandler: this.consoleHandler,
11628
11820
  sidecar,
11629
11821
  referenceConfig: this.referenceConfig,
11630
11822
  secureProxyConfig: this.config.secureProxyConfig,
@@ -11835,7 +12027,13 @@ ${errorMessages}`,
11835
12027
  "__safe_template"
11836
12028
  // Memory-safe template literals
11837
12029
  ];
11838
- const allAllowedGlobals = [...securityLevelGlobals, ...enclaveSpecificGlobals, ...customAllowedGlobals];
12030
+ const consoleGlobals = this.consoleHandler ? ["console", "__safe_console"] : [];
12031
+ const allAllowedGlobals = [
12032
+ ...securityLevelGlobals,
12033
+ ...enclaveSpecificGlobals,
12034
+ ...consoleGlobals,
12035
+ ...customAllowedGlobals
12036
+ ];
11839
12037
  switch (presetName) {
11840
12038
  case "agentscript":
11841
12039
  return new import_ast4.JSAstValidator(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.17.0",
3
+ "version": "2.18.0",
4
4
  "description": "Sandbox runtime for secure JavaScript code execution",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -44,8 +44,8 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@babel/standalone": "^7.29.0",
47
- "@enclave-vm/ast": "2.17.0",
48
- "@enclave-vm/types": "2.17.0",
47
+ "@enclave-vm/ast": "2.18.0",
48
+ "@enclave-vm/types": "2.18.0",
49
49
  "@types/estree": "1.0.8",
50
50
  "acorn": "8.15.0",
51
51
  "acorn-walk": "8.3.4",
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Sandbox Console
3
+ *
4
+ * Builds the script's `console` INSIDE the sandbox realm on the single-VM and worker_threads paths, the way
5
+ * `toolNamespaces` objects are built: a frozen, null-prototype object whose methods are realm-local functions. Each
6
+ * method passes its arguments to the host's console writer, held in a closure, and turns an error the writer reports
7
+ * into a realm error with the same name and message. Formatting, limits and output stay the host's.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ /** The host's console methods behind a sandbox console, by level. */
12
+ export type HostConsoleMethods = Readonly<Record<string, (...args: unknown[]) => void>>;
13
+ /** The host end of a sandbox console: `undefined`, or `name\nmessage` of the error the host method threw. */
14
+ export type HostConsoleWriter = (level: string, ...args: unknown[]) => string | undefined;
15
+ /** `install(write, levels)`, evaluated in the sandbox realm by {@link SANDBOX_CONSOLE_FACTORY_SOURCE}. */
16
+ export type InstallSandboxConsole = (write: HostConsoleWriter, levels: readonly string[]) => object;
17
+ /**
18
+ * Source of an expression that, evaluated in a sandbox realm, captures that realm's own `Object` and `Error` (from
19
+ * literals, so globals the realm shadows don't matter) and returns `install(write, levels)`.
20
+ */
21
+ export declare const SANDBOX_CONSOLE_FACTORY_SOURCE: string;
22
+ /**
23
+ * The host end of a sandbox console over `methods`: runs the method for a level and reports an error the host throws
24
+ * as `name\nmessage`. A value the script threw while its arguments were formatted is rethrown as it is.
25
+ */
26
+ export declare function createHostConsoleWriter(methods: HostConsoleMethods): HostConsoleWriter;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.17.0",
3
+ "version": "2.18.0",
4
4
  "description": "Sandbox runtime for secure JavaScript code execution",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -46,8 +46,8 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@babel/standalone": "^7.29.0",
49
- "@enclave-vm/ast": "2.17.0",
50
- "@enclave-vm/types": "2.17.0",
49
+ "@enclave-vm/ast": "2.18.0",
50
+ "@enclave-vm/types": "2.18.0",
51
51
  "@types/estree": "1.0.8",
52
52
  "acorn": "8.15.0",
53
53
  "acorn-walk": "8.3.4",
@@ -416,6 +416,115 @@ function buildToolNamespaceBindings(install, callTool, namespaces) {
416
416
  return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
417
417
  }
418
418
 
419
+ // libs/core/src/console-handler.ts
420
+ var CONSOLE_FACTORY_SOURCE = `
421
+ (function () {
422
+ 'use strict';
423
+ var stringify = JSON.stringify;
424
+ // The realm's own String, even where a sandbox global shadows it.
425
+ var toText = ''.constructor;
426
+ var freeze = Object.freeze;
427
+ var RealmError = Error;
428
+
429
+ function formatArgument(value) {
430
+ if (value === undefined) return 'undefined';
431
+ if (value === null) return 'null';
432
+ if (typeof value === 'object') {
433
+ try {
434
+ var json = stringify(value);
435
+ return json === undefined ? '' : json;
436
+ } catch (e) {
437
+ return toText(value);
438
+ }
439
+ }
440
+ return toText(value);
441
+ }
442
+
443
+ return function install(write, maxCalls, maxBytes) {
444
+ var callCount = 0;
445
+ var totalBytes = 0;
446
+
447
+ function method(level) {
448
+ return (...args) => {
449
+ callCount++;
450
+ if (callCount > maxCalls) {
451
+ throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
452
+ }
453
+ var line = '';
454
+ for (var i = 0; i < args.length; i++) {
455
+ line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
456
+ }
457
+ totalBytes += line.length;
458
+ if (totalBytes > maxBytes) {
459
+ throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
460
+ }
461
+ try {
462
+ write(level, line);
463
+ } catch (e) {}
464
+ };
465
+ }
466
+
467
+ return freeze({
468
+ __proto__: null,
469
+ log: method('log'),
470
+ info: method('info'),
471
+ warn: method('warn'),
472
+ error: method('error'),
473
+ debug: method('debug')
474
+ });
475
+ };
476
+ })()
477
+ `.trim();
478
+
479
+ // libs/core/src/sandbox-console.ts
480
+ var SANDBOX_CONSOLE_FACTORY_SOURCE = `
481
+ (function () {
482
+ 'use strict';
483
+ var RealmObject = ({}).constructor;
484
+ var getPrototypeOf = RealmObject.getPrototypeOf;
485
+ var freeze = RealmObject.freeze;
486
+ var RealmError = (function () {
487
+ try {
488
+ null.f;
489
+ } catch (e) {
490
+ return getPrototypeOf(getPrototypeOf(e)).constructor;
491
+ }
492
+ })();
493
+
494
+ function method(write, level) {
495
+ return (...args) => {
496
+ var failure = write(level, ...args);
497
+ if (typeof failure === 'string') {
498
+ var separator = failure.indexOf('\\n');
499
+ var error = new RealmError(failure.slice(separator + 1));
500
+ error.name = failure.slice(0, separator);
501
+ throw error;
502
+ }
503
+ };
504
+ }
505
+
506
+ return function install(write, levels) {
507
+ var methods = { __proto__: null };
508
+ for (var i = 0; i < levels.length; i++) {
509
+ methods[levels[i]] = method(write, levels[i]);
510
+ }
511
+ return freeze(methods);
512
+ };
513
+ })()
514
+ `.trim();
515
+ function createHostConsoleWriter(methods) {
516
+ return (level, ...args) => {
517
+ try {
518
+ methods[level](...args);
519
+ return void 0;
520
+ } catch (error) {
521
+ if (error instanceof Error) return `${error.name}
522
+ ${error.message}`;
523
+ throw error;
524
+ }
525
+ };
526
+ }
527
+
419
528
  // libs/core/src/adapters/worker-pool/worker-script.ts
420
529
  var STACK_TRACE_HARDENING_CODE = `
421
530
  (function() {
@@ -566,6 +675,8 @@ var CODE_GENERATION_VIOLATION_DETECTOR_CODE = `
566
675
  `.trim();
567
676
  var CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new import_vm.default.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
568
677
  var TOOL_NAMESPACE_FACTORY_SCRIPT = new import_vm.default.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
678
+ var SANDBOX_CONSOLE_FACTORY_SCRIPT = new import_vm.default.Script(SANDBOX_CONSOLE_FACTORY_SOURCE, { filename: "console.js" });
679
+ var CONSOLE_FACTORY_SCRIPT = new import_vm.default.Script(CONSOLE_FACTORY_SOURCE, { filename: "handler-console.js" });
569
680
  var port = import_worker_threads.parentPort;
570
681
  if (!port) {
571
682
  throw new Error("worker-script.ts must run inside a worker thread");
@@ -642,6 +753,11 @@ async function handleExecute(msg) {
642
753
  const context = import_vm.default.createContext(sandbox, {
643
754
  codeGeneration: { strings: false, wasm: false }
644
755
  });
756
+ if (msg.config.hasConsoleHandler) {
757
+ installHandlerConsole(context, msg.requestId, msg.config);
758
+ } else {
759
+ installSandboxConsoles(context);
760
+ }
645
761
  const isStrictOrSecure = msg.config.securityLevel === "STRICT" || msg.config.securityLevel === "SECURE";
646
762
  const policyViolation = {};
647
763
  const toolNamespaces = msg.config.toolNamespaces ?? [];
@@ -1034,6 +1150,37 @@ function createSafeWhile() {
1034
1150
  }
1035
1151
  };
1036
1152
  }
1153
+ var builtInConsoles = /* @__PURE__ */ new WeakSet();
1154
+ function installSandboxConsoles(context) {
1155
+ const globals = context;
1156
+ const consoles = ["console", "__safe_console"].filter((name) => builtInConsoles.has(globals[name]));
1157
+ if (consoles.length === 0) return;
1158
+ const install = SANDBOX_CONSOLE_FACTORY_SCRIPT.runInContext(context);
1159
+ for (const name of consoles) {
1160
+ globals[name] = install(createHostConsoleWriter(globals[name]), [
1161
+ "log",
1162
+ "warn",
1163
+ "error",
1164
+ "info"
1165
+ ]);
1166
+ }
1167
+ }
1168
+ function installHandlerConsole(context, requestId, config) {
1169
+ const install = CONSOLE_FACTORY_SCRIPT.runInContext(context);
1170
+ const handlerConsole = install(
1171
+ (level, line) => sendMessage({ type: "console", requestId, level, args: [line] }),
1172
+ config.maxConsoleCalls,
1173
+ config.maxConsoleOutputBytes
1174
+ );
1175
+ for (const name of ["console", "__safe_console"]) {
1176
+ Object.defineProperty(context, name, {
1177
+ value: handlerConsole,
1178
+ writable: false,
1179
+ configurable: false,
1180
+ enumerable: false
1181
+ });
1182
+ }
1183
+ }
1037
1184
  function createSafeConsole(requestId, config) {
1038
1185
  let totalBytes = 0;
1039
1186
  let callCount = 0;
@@ -1061,12 +1208,14 @@ function createSafeConsole(requestId, config) {
1061
1208
  args: serialized
1062
1209
  });
1063
1210
  }
1064
- return {
1211
+ const methods = {
1065
1212
  log: (...args) => safeLog("log", args),
1066
1213
  warn: (...args) => safeLog("warn", args),
1067
1214
  error: (...args) => safeLog("error", args),
1068
1215
  info: (...args) => safeLog("info", args)
1069
1216
  };
1217
+ builtInConsoles.add(methods);
1218
+ return methods;
1070
1219
  }
1071
1220
  function sendMessage(msg) {
1072
1221
  if (!port) {
package/types.d.ts CHANGED
@@ -461,6 +461,7 @@ import type { ScoringGateConfig, ScoringGateResult } from './scoring/types';
461
461
  import type { WorkerPoolConfig } from './adapters/worker-pool/config';
462
462
  import type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig } from './double-vm/types';
463
463
  import type { NormalizedToolNamespace, ToolNamespaces } from '@enclave-vm/ast';
464
+ import type { ConsoleHandler, ConsoleLevel } from './console-handler';
464
465
  /**
465
466
  * Internal execution context (tracks state during execution)
466
467
  */
@@ -499,6 +500,10 @@ export interface ExecutionContext {
499
500
  * Tool handler
500
501
  */
501
502
  toolHandler?: ToolHandler;
503
+ /**
504
+ * Receives the script's console calls (see `CreateEnclaveOptions.consoleHandler`)
505
+ */
506
+ consoleHandler?: ConsoleHandler;
502
507
  /**
503
508
  * Reference sidecar for pass-by-reference support (per-execution)
504
509
  * Created and disposed by the Enclave for each run
@@ -703,6 +708,32 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
703
708
  * ```
704
709
  */
705
710
  toolNamespaces?: ToolNamespaces;
711
+ /**
712
+ * Receives the script's `console.log/info/warn/error/debug` calls instead of the host console.
713
+ *
714
+ * With a handler, scripts may use `console` at every security level. Each call is formatted as
715
+ * the built-in console formats it (arguments joined by spaces, objects JSON-serialized) and
716
+ * handed over as `(level, message)` strings, once `maxConsoleCalls` and `maxConsoleOutputBytes`
717
+ * have allowed it; past a limit the script's call throws and the handler is not called. The
718
+ * handler's return value is ignored and anything it throws or rejects with is swallowed. The
719
+ * script's `console` is a frozen, null-prototype object built inside the sandbox, so it leads
720
+ * to neither the handler nor any host object.
721
+ *
722
+ * Without a handler nothing changes: `console` is allowed only at PERMISSIVE and writes to the
723
+ * host process console.
724
+ *
725
+ * Supported by the double VM (default), the `vm` adapter and the `worker_threads` adapter. A
726
+ * `sandboxAdapter` receives the handler as `ExecutionContext.consoleHandler`; the built-in
727
+ * `InterpreterAdapter` has no `console`, so a script that uses it fails there.
728
+ *
729
+ * @example
730
+ * ```typescript
731
+ * const enclave = new Enclave({
732
+ * consoleHandler: (level, message) => logger[level](message),
733
+ * });
734
+ * ```
735
+ */
736
+ consoleHandler?: ConsoleHandler;
706
737
  /**
707
738
  * Whether to sanitize stack traces in error messages
708
739
  * Default: Determined by securityLevel (true for STRICT/SECURE)
@@ -904,6 +935,12 @@ export type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig };
904
935
  * @see {@link NormalizedToolNamespace} A validated namespace
905
936
  */
906
937
  export type { ToolNamespaces, NormalizedToolNamespace };
938
+ /**
939
+ * Re-exported console handler types
940
+ * @see {@link ConsoleHandler} The `consoleHandler` option
941
+ * @see {@link ConsoleLevel} A console method a script can call
942
+ */
943
+ export type { ConsoleHandler, ConsoleLevel };
907
944
  /**
908
945
  * Default double VM configuration
909
946
  *