@enclave-vm/core 2.15.3 → 2.17.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.
@@ -9,6 +9,7 @@
9
9
  import { z } from 'zod';
10
10
  import { type NormalizedToolNamespace } from '@enclave-vm/ast';
11
11
  import type { ResourceUsage } from './config';
12
+ import type { SpecialResultValue } from './result-encoding';
12
13
  /**
13
14
  * Serialized error format for cross-thread communication
14
15
  * Errors are serialized to prevent prototype pollution
@@ -159,8 +160,10 @@ export interface ExecutionResultMessage {
159
160
  requestId: string;
160
161
  /** Whether execution succeeded */
161
162
  success: boolean;
162
- /** Return value (if successful) */
163
+ /** Return value (if successful), as JSON data */
163
164
  value?: unknown;
165
+ /** Values in `value` JSON cannot carry (Date, NaN, Infinity, undefined), restored by the pool */
166
+ specialValues?: SpecialResultValue[];
164
167
  /** Error (if failed) */
165
168
  error?: SerializedError;
166
169
  /** Execution statistics */
@@ -208,6 +211,17 @@ export declare const executionResultMessageSchema: z.ZodObject<{
208
211
  requestId: z.ZodString;
209
212
  success: z.ZodBoolean;
210
213
  value: z.ZodOptional<z.ZodUnknown>;
214
+ specialValues: z.ZodOptional<z.ZodArray<z.ZodObject<{
215
+ path: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
216
+ kind: z.ZodEnum<{
217
+ undefined: "undefined";
218
+ date: "date";
219
+ nan: "nan";
220
+ infinity: "infinity";
221
+ "-infinity": "-infinity";
222
+ }>;
223
+ time: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
224
+ }, z.core.$strict>>>;
211
225
  error: z.ZodOptional<z.ZodObject<{
212
226
  name: z.ZodString;
213
227
  message: z.ZodString;
@@ -271,6 +285,17 @@ export declare const workerToMainMessageSchema: z.ZodDiscriminatedUnion<[z.ZodOb
271
285
  requestId: z.ZodString;
272
286
  success: z.ZodBoolean;
273
287
  value: z.ZodOptional<z.ZodUnknown>;
288
+ specialValues: z.ZodOptional<z.ZodArray<z.ZodObject<{
289
+ path: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
290
+ kind: z.ZodEnum<{
291
+ undefined: "undefined";
292
+ date: "date";
293
+ nan: "nan";
294
+ infinity: "infinity";
295
+ "-infinity": "-infinity";
296
+ }>;
297
+ time: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
298
+ }, z.core.$strict>>>;
274
299
  error: z.ZodOptional<z.ZodObject<{
275
300
  name: z.ZodString;
276
301
  message: z.ZodString;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Worker Result Encoding
3
+ *
4
+ * Worker messages are JSON (see safe-deserialize), which has no Date, NaN, Infinity or
5
+ * undefined. The worker sends the sanitized script result as JSON plus the list of values JSON
6
+ * would lose, each with its path; the pool puts them back, so a worker result matches what the
7
+ * in-process adapters return.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ /** Keys and indices from the result's root to a value. */
12
+ export type ResultPath = Array<string | number>;
13
+ /** A value JSON cannot carry, sent next to the result and restored on the main thread. */
14
+ export interface SpecialResultValue {
15
+ path: ResultPath;
16
+ kind: 'date' | 'nan' | 'infinity' | '-infinity' | 'undefined';
17
+ /** Milliseconds since the epoch for a Date; null for an invalid Date. */
18
+ time?: number | null;
19
+ }
20
+ /**
21
+ * Split a sanitized result (plain data, no cycles) into JSON data, with `null` in place of each
22
+ * special value, and the list of special values. Keys the transport strips are left out.
23
+ */
24
+ export declare function encodeResult(value: unknown): {
25
+ value: unknown;
26
+ specialValues: SpecialResultValue[];
27
+ };
28
+ /**
29
+ * Put the special values back into a deserialized result. Every entry must point at a `null`
30
+ * placeholder inside the result's arrays and plain objects; anything else means the message was
31
+ * not produced by `encodeResult`, and the result is refused.
32
+ */
33
+ export declare function decodeResult(value: unknown, specialValues: unknown): unknown;
@@ -60,10 +60,9 @@ export declare class WorkerPoolAdapter implements SandboxAdapter {
60
60
  /**
61
61
  * Build result from worker message.
62
62
  *
63
- * Note: The `msg.value as T` assertion is inherent to cross-thread
64
- * serialization boundaries. The worker sanitizes output via sanitizeObject()
65
- * before sending, but full runtime type validation would require schema
66
- * definitions which are not available at this layer.
63
+ * Note: The `as T` assertion is inherent to cross-thread serialization boundaries. The
64
+ * worker sanitizes the result with sanitizeValue() and sends the values JSON cannot carry
65
+ * (Dates, NaN, ...) separately; decodeResult() puts them back and refuses a malformed list.
67
66
  */
68
67
  private buildResult;
69
68
  /**
package/enclave.d.ts CHANGED
@@ -50,6 +50,7 @@ export declare class Enclave {
50
50
  private readonly doubleVmConfig;
51
51
  private readonly customGlobalNames;
52
52
  private readonly toolNamespaces;
53
+ private readonly sandboxAdapter?;
53
54
  private adapter?;
54
55
  constructor(options?: CreateEnclaveOptions);
55
56
  /**
@@ -109,7 +110,8 @@ export declare class Enclave {
109
110
  /**
110
111
  * Get or create the sandbox adapter
111
112
  *
112
- * When double VM is enabled (default), the base adapter is wrapped
113
+ * A host-supplied `sandboxAdapter` is used as is. Otherwise, when double VM is enabled
114
+ * (default), the base adapter is wrapped
113
115
  * with a double VM layer that provides:
114
116
  * - Nested VM isolation (Parent VM + Inner VM)
115
117
  * - Enhanced tool call validation
package/esm/index.mjs CHANGED
@@ -470,6 +470,15 @@ function isSecureProxy(obj) {
470
470
  }
471
471
  return proxySet.has(obj);
472
472
  }
473
+ function unwrapSecureProxy(value) {
474
+ let current = value;
475
+ while (current !== null && (typeof current === "object" || typeof current === "function")) {
476
+ const target = proxyToTarget.get(current);
477
+ if (target === void 0) break;
478
+ current = target;
479
+ }
480
+ return current;
481
+ }
473
482
  var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor2, ReflectOwnKeys2, ReflectApply2, ReflectConstruct, ReflectObject, PINNED_REFLECT_VALUES, FunctionCtor, AsyncFunctionCtor, GeneratorFunctionCtor, AsyncGeneratorFunctionCtor, MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, gatedProxyCaches, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
474
483
  var init_secure_proxy = __esm({
475
484
  "libs/core/src/secure-proxy.ts"() {
@@ -1013,6 +1022,26 @@ var init_reference_resolver = __esm({
1013
1022
  });
1014
1023
 
1015
1024
  // libs/core/src/value-sanitizer.ts
1025
+ function hasBrand(builtin, value) {
1026
+ if (!builtin) return false;
1027
+ try {
1028
+ ReflectApply3(builtin, value, []);
1029
+ return true;
1030
+ } catch {
1031
+ return false;
1032
+ }
1033
+ }
1034
+ function regExpToString(value) {
1035
+ let flags = "";
1036
+ for (const [flag, getter] of RegExpFlagGetters) {
1037
+ if (getter && ReflectApply3(getter, value, [])) flags += flag;
1038
+ }
1039
+ return `/${ReflectApply3(RegExpProtoSourceGetter, value, [])}/${flags}`;
1040
+ }
1041
+ function isPlainObject(value) {
1042
+ const prototype = ObjectGetPrototypeOf2(value);
1043
+ return prototype === null || ObjectGetPrototypeOf2(prototype) === null;
1044
+ }
1016
1045
  function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
1017
1046
  const maxDepth = options.maxDepth ?? 20;
1018
1047
  const maxProperties = options.maxProperties ?? 1e4;
@@ -1073,12 +1102,14 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1073
1102
  }
1074
1103
  return result;
1075
1104
  }
1076
- if (value instanceof Date) {
1077
- const time = ReflectApply3(DateProtoGetTime, value, []);
1105
+ const inspected = options.unwrap ? options.unwrap(value) : value;
1106
+ const isPlain = isPlainObject(inspected);
1107
+ if (!isPlain && hasBrand(DateProtoGetTime, inspected)) {
1108
+ const time = ReflectApply3(DateProtoGetTime, inspected, []);
1078
1109
  if (allowDates) {
1079
1110
  return new Date(time);
1080
1111
  }
1081
- return ReflectApply3(DateProtoToISOString, value, []);
1112
+ return ReflectApply3(DateProtoToISOString, inspected, []);
1082
1113
  }
1083
1114
  if (value instanceof Error) {
1084
1115
  const rawName = ReflectGet3(value, "name");
@@ -1094,12 +1125,12 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1094
1125
  }
1095
1126
  return { error: message };
1096
1127
  }
1097
- if (value instanceof RegExp) {
1098
- return ReflectApply3(RegExpProtoToString, value, []);
1128
+ if (!isPlain && hasBrand(RegExpProtoSourceGetter, inspected)) {
1129
+ return regExpToString(inspected);
1099
1130
  }
1100
- if (value instanceof Map) {
1131
+ if (!isPlain && hasBrand(MapProtoSizeGetter, inspected)) {
1101
1132
  const sanitizedMap = ObjectCreate(null);
1102
- const entries = ReflectApply3(MapProtoEntries, value, []);
1133
+ const entries = ReflectApply3(MapProtoEntries, inspected, []);
1103
1134
  for (const [key, val] of entries) {
1104
1135
  if (typeof key !== "string") continue;
1105
1136
  if (DANGEROUS_KEYS.has(key)) continue;
@@ -1108,8 +1139,8 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1108
1139
  }
1109
1140
  return sanitizedMap;
1110
1141
  }
1111
- if (value instanceof Set) {
1112
- const iter = ReflectApply3(SetProtoValues, value, []);
1142
+ if (!isPlain && hasBrand(SetProtoSizeGetter, inspected)) {
1143
+ const iter = ReflectApply3(SetProtoValues, inspected, []);
1113
1144
  const result = [];
1114
1145
  for (const item of iter) {
1115
1146
  context.propCount.count++;
@@ -1268,7 +1299,7 @@ function checkSerializedSize(value, maxBytes) {
1268
1299
  return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
1269
1300
  }
1270
1301
  }
1271
- var DANGEROUS_KEYS, ReflectApply3, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1302
+ var DANGEROUS_KEYS, ReflectApply3, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, ObjectGetPrototypeOf2, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoSourceGetter, RegExpFlagGetters, MapProtoSizeGetter, SetProtoSizeGetter;
1272
1303
  var init_value_sanitizer = __esm({
1273
1304
  "libs/core/src/value-sanitizer.ts"() {
1274
1305
  "use strict";
@@ -1278,13 +1309,26 @@ var init_value_sanitizer = __esm({
1278
1309
  ArrayIsArray = Array.isArray;
1279
1310
  ObjectKeys = Object.keys;
1280
1311
  ObjectCreate = Object.create;
1312
+ ObjectGetPrototypeOf2 = Object.getPrototypeOf;
1281
1313
  NumberIsFinite2 = Number.isFinite;
1282
1314
  MathFloor2 = Math.floor;
1283
1315
  MapProtoEntries = Map.prototype.entries;
1284
1316
  SetProtoValues = Set.prototype.values;
1285
1317
  DateProtoGetTime = Date.prototype.getTime;
1286
1318
  DateProtoToISOString = Date.prototype.toISOString;
1287
- RegExpProtoToString = RegExp.prototype.toString;
1319
+ RegExpProtoSourceGetter = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get;
1320
+ RegExpFlagGetters = [
1321
+ ["d", "hasIndices"],
1322
+ ["g", "global"],
1323
+ ["i", "ignoreCase"],
1324
+ ["m", "multiline"],
1325
+ ["s", "dotAll"],
1326
+ ["u", "unicode"],
1327
+ ["v", "unicodeSets"],
1328
+ ["y", "sticky"]
1329
+ ].map(([flag, property]) => [flag, Object.getOwnPropertyDescriptor(RegExp.prototype, property)?.get]);
1330
+ MapProtoSizeGetter = Object.getOwnPropertyDescriptor(Map.prototype, "size")?.get;
1331
+ SetProtoSizeGetter = Object.getOwnPropertyDescriptor(Set.prototype, "size")?.get;
1288
1332
  }
1289
1333
  });
1290
1334
 
@@ -1433,7 +1477,7 @@ function createGlobalFunctionGate(context, realm) {
1433
1477
  }
1434
1478
  };
1435
1479
  }
1436
- var ReflectApply4, ReflectOwnKeys3, ObjectGetOwnPropertyDescriptor2, ObjectGetPrototypeOf2, ArrayIsArray2, JsonStringify, BUILTIN_METHODS, DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL, DEFAULT_MAX_PAYLOAD_BYTES, MAX_ERROR_MESSAGE_LENGTH, MAX_ERROR_NAME_LENGTH, UNSAFE_RESULT_MESSAGE;
1480
+ var ReflectApply4, ReflectOwnKeys3, ObjectGetOwnPropertyDescriptor2, ObjectGetPrototypeOf3, ArrayIsArray2, JsonStringify, BUILTIN_METHODS, DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL, DEFAULT_MAX_PAYLOAD_BYTES, MAX_ERROR_MESSAGE_LENGTH, MAX_ERROR_NAME_LENGTH, UNSAFE_RESULT_MESSAGE;
1437
1481
  var init_global_function_gate = __esm({
1438
1482
  "libs/core/src/global-function-gate.ts"() {
1439
1483
  "use strict";
@@ -1442,7 +1486,7 @@ var init_global_function_gate = __esm({
1442
1486
  ReflectApply4 = Reflect.apply;
1443
1487
  ReflectOwnKeys3 = Reflect.ownKeys;
1444
1488
  ObjectGetOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
1445
- ObjectGetPrototypeOf2 = Object.getPrototypeOf;
1489
+ ObjectGetPrototypeOf3 = Object.getPrototypeOf;
1446
1490
  ArrayIsArray2 = Array.isArray;
1447
1491
  JsonStringify = JSON.stringify;
1448
1492
  BUILTIN_METHODS = (() => {
@@ -1460,7 +1504,7 @@ var init_global_function_gate = __esm({
1460
1504
  BigInt64Array,
1461
1505
  BigUint64Array
1462
1506
  ];
1463
- const arrayIteratorPrototype = ObjectGetPrototypeOf2([][Symbol.iterator]());
1507
+ const arrayIteratorPrototype = ObjectGetPrototypeOf3([][Symbol.iterator]());
1464
1508
  const prototypes = [
1465
1509
  Object.prototype,
1466
1510
  Array.prototype,
@@ -1485,15 +1529,15 @@ var init_global_function_gate = __esm({
1485
1529
  Promise.prototype,
1486
1530
  ArrayBuffer.prototype,
1487
1531
  DataView.prototype,
1488
- ObjectGetPrototypeOf2(Uint8Array.prototype),
1532
+ ObjectGetPrototypeOf3(Uint8Array.prototype),
1489
1533
  // %TypedArray%.prototype
1490
1534
  ...typedArrays.map((TypedArray) => TypedArray.prototype),
1491
1535
  arrayIteratorPrototype,
1492
- ObjectGetPrototypeOf2(arrayIteratorPrototype),
1536
+ ObjectGetPrototypeOf3(arrayIteratorPrototype),
1493
1537
  // %IteratorPrototype%
1494
- ObjectGetPrototypeOf2((/* @__PURE__ */ new Map())[Symbol.iterator]()),
1495
- ObjectGetPrototypeOf2((/* @__PURE__ */ new Set())[Symbol.iterator]()),
1496
- ObjectGetPrototypeOf2(""[Symbol.iterator]())
1538
+ ObjectGetPrototypeOf3((/* @__PURE__ */ new Map())[Symbol.iterator]()),
1539
+ ObjectGetPrototypeOf3((/* @__PURE__ */ new Set())[Symbol.iterator]()),
1540
+ ObjectGetPrototypeOf3(""[Symbol.iterator]())
1497
1541
  ];
1498
1542
  for (const prototype of prototypes) {
1499
1543
  if (prototype === null || typeof prototype !== "object") continue;
@@ -4637,7 +4681,7 @@ var init_suspicious_patterns = __esm({
4637
4681
  });
4638
4682
 
4639
4683
  // libs/core/src/double-vm/double-vm-wrapper.ts
4640
- import * as vm2 from "vm";
4684
+ import * as vm3 from "vm";
4641
4685
  var DoubleVmWrapper;
4642
4686
  var init_double_vm_wrapper = __esm({
4643
4687
  "libs/core/src/double-vm/double-vm-wrapper.ts"() {
@@ -4679,7 +4723,7 @@ var init_double_vm_wrapper = __esm({
4679
4723
  });
4680
4724
  this.parentContext = parentContext;
4681
4725
  const parentScript = this.buildParentScript(code, executionContext);
4682
- const script = new vm2.Script(parentScript, {
4726
+ const script = new vm3.Script(parentScript, {
4683
4727
  filename: "parent-vm.js"
4684
4728
  });
4685
4729
  const parentTimeout = config.timeout + this.config.parentTimeoutBuffer;
@@ -4791,15 +4835,15 @@ var init_double_vm_wrapper = __esm({
4791
4835
  */
4792
4836
  createParentContext(executionContext, memoryTracker, reportViolation) {
4793
4837
  const { stats, config } = executionContext;
4794
- const parentContext = vm2.createContext(
4838
+ const parentContext = vm3.createContext(
4795
4839
  {},
4796
4840
  {
4797
4841
  codeGeneration: { strings: false, wasm: false }
4798
4842
  }
4799
4843
  );
4800
4844
  const safeVm = {
4801
- createContext: vm2.createContext.bind(vm2),
4802
- Script: vm2.Script
4845
+ createContext: vm3.createContext.bind(vm3),
4846
+ Script: vm3.Script
4803
4847
  };
4804
4848
  Object.defineProperty(parentContext, "__host_vm_module__", {
4805
4849
  value: safeVm,
@@ -5721,7 +5765,7 @@ var vm_adapter_exports = {};
5721
5765
  __export(vm_adapter_exports, {
5722
5766
  VmAdapter: () => VmAdapter
5723
5767
  });
5724
- import * as vm3 from "vm";
5768
+ import * as vm4 from "vm";
5725
5769
  function createSafeConsole(config, stats) {
5726
5770
  const wrap = (method) => (...args) => {
5727
5771
  stats.callCount++;
@@ -5997,7 +6041,7 @@ var init_vm_adapter = __esm({
5997
6041
  } catch (e) {}
5998
6042
  })();
5999
6043
  `.trim();
6000
- STACK_TRACE_HARDENING_SCRIPT = new vm3.Script(STACK_TRACE_HARDENING_CODE);
6044
+ STACK_TRACE_HARDENING_SCRIPT = new vm4.Script(STACK_TRACE_HARDENING_CODE);
6001
6045
  CODE_GENERATION_VIOLATION_DETECTOR_CODE = `
6002
6046
  (function() {
6003
6047
  var __ag_report = (typeof __ag_reportViolation__ === 'function') ? __ag_reportViolation__ : null;
@@ -6046,7 +6090,7 @@ var init_vm_adapter = __esm({
6046
6090
  try { __ag_wrapCtor((async function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
6047
6091
  })();
6048
6092
  `.trim();
6049
- CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new vm3.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
6093
+ CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new vm4.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
6050
6094
  INTRINSIC_OBJECT_NEUTRALIZATION_CODE = `
6051
6095
  (function() {
6052
6096
  var RealObject = Object.getPrototypeOf({}).constructor;
@@ -6062,8 +6106,8 @@ var init_vm_adapter = __esm({
6062
6106
  }
6063
6107
  })();
6064
6108
  `;
6065
- INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm3.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
6066
- SANDBOX_REALM_BRIDGE_SCRIPT = new vm3.Script(`
6109
+ INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm4.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
6110
+ SANDBOX_REALM_BRIDGE_SCRIPT = new vm4.Script(`
6067
6111
  (function () {
6068
6112
  'use strict';
6069
6113
  var parse = JSON.parse;
@@ -6076,7 +6120,7 @@ var init_vm_adapter = __esm({
6076
6120
  });
6077
6121
  })()
6078
6122
  `);
6079
- TOOL_NAMESPACE_FACTORY_SCRIPT = new vm3.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
6123
+ TOOL_NAMESPACE_FACTORY_SCRIPT = new vm4.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
6080
6124
  PROTECTED_PREFIXES = ["__safe_", "__ag_"];
6081
6125
  DANGEROUS_OBJECT_STATIC_METHODS = [
6082
6126
  "defineProperty",
@@ -6192,7 +6236,7 @@ var init_vm_adapter = __esm({
6192
6236
  }) : void 0;
6193
6237
  memoryTracker?.start();
6194
6238
  try {
6195
- const baseSandbox = vm3.createContext(
6239
+ const baseSandbox = vm4.createContext(
6196
6240
  {},
6197
6241
  {
6198
6242
  codeGeneration: { strings: false, wasm: false }
@@ -6218,7 +6262,7 @@ var init_vm_adapter = __esm({
6218
6262
  configurable: true,
6219
6263
  enumerable: false
6220
6264
  });
6221
- const patchScript = new vm3.Script(`
6265
+ const patchScript = new vm4.Script(`
6222
6266
  (function() {
6223
6267
  var memoryLimit = ${config.memoryLimit};
6224
6268
  var trackMemory = __host_memory_track__;
@@ -6361,7 +6405,7 @@ var init_vm_adapter = __esm({
6361
6405
  // allow deletion after capture
6362
6406
  enumerable: false
6363
6407
  });
6364
- const bridgeInitScript = new vm3.Script(`
6408
+ const bridgeInitScript = new vm4.Script(`
6365
6409
  (function() {
6366
6410
  var bridge = __host_callToolBridge__;
6367
6411
  var stringify = JSON.stringify;
@@ -6573,7 +6617,7 @@ var init_vm_adapter = __esm({
6573
6617
  const _protectedSandbox = createProtectedSandbox(baseSandbox);
6574
6618
  this.context = baseSandbox;
6575
6619
  const wrappedCode = "(async () => {\n" + code + '\nreturn typeof __ag_main === "function" ? await __ag_main() : undefined;\n})();';
6576
- const script = new vm3.Script(wrappedCode, {
6620
+ const script = new vm4.Script(wrappedCode, {
6577
6621
  filename: "agentscript.js"
6578
6622
  });
6579
6623
  const resultPromise = script.runInContext(this.context, {
@@ -6622,7 +6666,9 @@ var init_vm_adapter = __esm({
6622
6666
  maxDepth: clampedDepth,
6623
6667
  maxProperties: clampedProperties,
6624
6668
  allowDates: true,
6625
- allowErrors: true
6669
+ allowErrors: true,
6670
+ // The membrane wraps the script's Dates; read them through their targets.
6671
+ unwrap: unwrapSecureProxy
6626
6672
  });
6627
6673
  return {
6628
6674
  success: true,
@@ -6830,6 +6876,13 @@ var init_protocol = __esm({
6830
6876
  requestId: z.string().min(1).max(100).regex(ID_PATTERN),
6831
6877
  success: z.boolean(),
6832
6878
  value: z.unknown().optional(),
6879
+ specialValues: z.array(
6880
+ z.object({
6881
+ path: z.array(z.union([z.string(), z.number().int().nonnegative()])).max(64),
6882
+ kind: z.enum(["date", "nan", "infinity", "-infinity", "undefined"]),
6883
+ time: z.number().nullable().optional()
6884
+ }).strict()
6885
+ ).optional(),
6833
6886
  error: z.object({
6834
6887
  name: z.string().max(100),
6835
6888
  message: z.string().max(1e4),
@@ -7067,6 +7120,9 @@ function safeSerialize(value) {
7067
7120
  return val;
7068
7121
  });
7069
7122
  }
7123
+ function isDangerousKey(key) {
7124
+ return DANGEROUS_KEYS2.has(key);
7125
+ }
7070
7126
  function sanitizeObject(value, depth = 0) {
7071
7127
  if (depth > MAX_DEPTH) {
7072
7128
  return void 0;
@@ -7793,6 +7849,75 @@ var init_rate_limiter = __esm({
7793
7849
  }
7794
7850
  });
7795
7851
 
7852
+ // libs/core/src/adapters/worker-pool/result-encoding.ts
7853
+ function decodeResult(value, specialValues) {
7854
+ if (specialValues === void 0) {
7855
+ return value;
7856
+ }
7857
+ if (!Array.isArray(specialValues)) {
7858
+ throw new MessageValidationError("Worker result special values must be an array");
7859
+ }
7860
+ let decoded = value;
7861
+ for (const special of specialValues) {
7862
+ assertSpecialValue(special);
7863
+ const restored = restoreSpecialValue(special);
7864
+ if (special.path.length === 0) {
7865
+ decoded = restored;
7866
+ continue;
7867
+ }
7868
+ const container = resolveContainer(decoded, special.path.slice(0, -1));
7869
+ const key = special.path[special.path.length - 1];
7870
+ if (!container || !Object.hasOwn(container, key) || container[key] !== null) {
7871
+ throw new MessageValidationError("Worker result refers to a value it does not contain");
7872
+ }
7873
+ container[key] = restored;
7874
+ }
7875
+ return decoded;
7876
+ }
7877
+ function assertSpecialValue(special) {
7878
+ const candidate = special;
7879
+ const validPath = Array.isArray(candidate?.path) && candidate.path.every((key) => typeof key === "string" || Number.isInteger(key) && key >= 0);
7880
+ if (!validPath || !SPECIAL_KINDS.has(candidate?.kind)) {
7881
+ throw new MessageValidationError("Worker result has an invalid special value");
7882
+ }
7883
+ }
7884
+ function resolveContainer(root, path2) {
7885
+ let current = root;
7886
+ for (const key of path2) {
7887
+ if (!isDataContainer(current) || isDangerousKey(String(key)) || !Object.hasOwn(current, key)) {
7888
+ return void 0;
7889
+ }
7890
+ current = current[key];
7891
+ }
7892
+ return isDataContainer(current) ? current : void 0;
7893
+ }
7894
+ function isDataContainer(value) {
7895
+ return Array.isArray(value) || typeof value === "object" && value !== null && Object.getPrototypeOf(value) === null;
7896
+ }
7897
+ function restoreSpecialValue(special) {
7898
+ switch (special.kind) {
7899
+ case "date":
7900
+ return new Date(typeof special.time === "number" ? special.time : NaN);
7901
+ case "nan":
7902
+ return NaN;
7903
+ case "infinity":
7904
+ return Infinity;
7905
+ case "-infinity":
7906
+ return -Infinity;
7907
+ case "undefined":
7908
+ return void 0;
7909
+ }
7910
+ }
7911
+ var SPECIAL_KINDS;
7912
+ var init_result_encoding = __esm({
7913
+ "libs/core/src/adapters/worker-pool/result-encoding.ts"() {
7914
+ "use strict";
7915
+ init_errors();
7916
+ init_safe_deserialize();
7917
+ SPECIAL_KINDS = /* @__PURE__ */ new Set(["date", "nan", "infinity", "-infinity", "undefined"]);
7918
+ }
7919
+ });
7920
+
7796
7921
  // libs/core/src/adapters/worker-pool/worker-pool-adapter.ts
7797
7922
  import crypto from "crypto";
7798
7923
  var WorkerPoolAdapter;
@@ -7806,6 +7931,7 @@ var init_worker_pool_adapter = __esm({
7806
7931
  init_memory_monitor();
7807
7932
  init_rate_limiter();
7808
7933
  init_safe_deserialize();
7934
+ init_result_encoding();
7809
7935
  init_errors();
7810
7936
  init_stack_trace();
7811
7937
  WorkerPoolAdapter = class {
@@ -8151,16 +8277,15 @@ var init_worker_pool_adapter = __esm({
8151
8277
  /**
8152
8278
  * Build result from worker message.
8153
8279
  *
8154
- * Note: The `msg.value as T` assertion is inherent to cross-thread
8155
- * serialization boundaries. The worker sanitizes output via sanitizeObject()
8156
- * before sending, but full runtime type validation would require schema
8157
- * definitions which are not available at this layer.
8280
+ * Note: The `as T` assertion is inherent to cross-thread serialization boundaries. The
8281
+ * worker sanitizes the result with sanitizeValue() and sends the values JSON cannot carry
8282
+ * (Dates, NaN, ...) separately; decodeResult() puts them back and refuses a malformed list.
8158
8283
  */
8159
8284
  buildResult(msg, duration, sanitizeStacks) {
8160
8285
  if (msg.success) {
8161
8286
  return {
8162
8287
  success: true,
8163
- value: msg.value,
8288
+ value: decodeResult(msg.value, msg.specialValues),
8164
8289
  stats: {
8165
8290
  duration,
8166
8291
  toolCallCount: msg.stats.toolCallCount,
@@ -11102,6 +11227,19 @@ function createScoringGate(config) {
11102
11227
  // libs/core/src/enclave.ts
11103
11228
  init_global_function_gate();
11104
11229
  init_stack_trace();
11230
+
11231
+ // libs/core/src/node-vm.ts
11232
+ import * as vm2 from "vm";
11233
+ function assertNodeVmAvailable() {
11234
+ if (typeof vm2.createContext === "function" && typeof vm2.Script === "function") {
11235
+ return;
11236
+ }
11237
+ throw new Error(
11238
+ "@enclave-vm/core needs node:vm, which this runtime does not provide. In a browser, use @enclave-vm/browser; elsewhere, pass a sandboxAdapter (for example new InterpreterAdapter())."
11239
+ );
11240
+ }
11241
+
11242
+ // libs/core/src/enclave.ts
11105
11243
  var DEFAULT_SECURITY_LEVEL = "STANDARD";
11106
11244
  var DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
11107
11245
  function getConfigFromSecurityLevel(securityLevel, options) {
@@ -11157,6 +11295,7 @@ var Enclave = class {
11157
11295
  doubleVmConfig;
11158
11296
  customGlobalNames;
11159
11297
  toolNamespaces;
11298
+ sandboxAdapter;
11160
11299
  adapter;
11161
11300
  constructor(options = {}) {
11162
11301
  this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
@@ -11248,6 +11387,10 @@ var Enclave = class {
11248
11387
  this.scoringGate = new ScoringGate(options.scoringGate);
11249
11388
  }
11250
11389
  this.doubleVmConfig = this.buildDoubleVmConfig(options.doubleVm);
11390
+ if (options.sandboxAdapter !== void 0 && !isSandboxAdapter(options.sandboxAdapter)) {
11391
+ throw new TypeError("sandboxAdapter must have execute(code, context) and dispose() methods");
11392
+ }
11393
+ this.sandboxAdapter = options.sandboxAdapter;
11251
11394
  }
11252
11395
  /**
11253
11396
  * Build double VM configuration from user options
@@ -11508,7 +11651,8 @@ ${errorMessages}`,
11508
11651
  /**
11509
11652
  * Get or create the sandbox adapter
11510
11653
  *
11511
- * When double VM is enabled (default), the base adapter is wrapped
11654
+ * A host-supplied `sandboxAdapter` is used as is. Otherwise, when double VM is enabled
11655
+ * (default), the base adapter is wrapped
11512
11656
  * with a double VM layer that provides:
11513
11657
  * - Nested VM isolation (Parent VM + Inner VM)
11514
11658
  * - Enhanced tool call validation
@@ -11516,9 +11660,15 @@ ${errorMessages}`,
11516
11660
  * - Defense-in-depth against VM escape attacks
11517
11661
  */
11518
11662
  async getAdapter() {
11663
+ if (this.sandboxAdapter) {
11664
+ return this.sandboxAdapter;
11665
+ }
11519
11666
  if (this.adapter) {
11520
11667
  return this.adapter;
11521
11668
  }
11669
+ if (this.doubleVmConfig.enabled || this.config.adapter === "vm") {
11670
+ assertNodeVmAvailable();
11671
+ }
11522
11672
  if (this.doubleVmConfig.enabled) {
11523
11673
  const { wrapWithDoubleVm: wrapWithDoubleVm3 } = await Promise.resolve().then(() => (init_double_vm(), double_vm_exports));
11524
11674
  this.adapter = wrapWithDoubleVm3(void 0, this.doubleVmConfig, this.securityLevel);
@@ -11661,6 +11811,10 @@ ${errorMessages}`,
11661
11811
  return uniqueErrors.join("\n");
11662
11812
  }
11663
11813
  };
11814
+ function isSandboxAdapter(value) {
11815
+ const candidate = value;
11816
+ return typeof candidate === "object" && candidate !== null && typeof candidate.execute === "function" && typeof candidate.dispose === "function";
11817
+ }
11664
11818
  async function runAgentScript(code, options = {}) {
11665
11819
  const enclave = new Enclave(options);
11666
11820
  try {