@enclave-vm/core 2.19.2 → 2.20.0-rc.1

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/esm/worker.mjs CHANGED
@@ -45,15 +45,73 @@ var CONSOLE_FACTORY_SOURCE = `
45
45
  var toText = ''.constructor;
46
46
  var freeze = Object.freeze;
47
47
  var RealmError = Error;
48
+ var apply = Reflect.apply;
49
+ var isArray = Array.isArray;
50
+ var stringValueOf = ''.constructor.prototype.valueOf;
51
+ var numberValueOf = (0).constructor.prototype.valueOf;
48
52
 
49
- function formatArgument(value) {
53
+ // Whether a value has the internal slot that a built-in's valueOf reads.
54
+ function hasSlot(valueOf, value) {
55
+ try {
56
+ apply(valueOf, value, []);
57
+ return true;
58
+ } catch (e) {
59
+ return false;
60
+ }
61
+ }
62
+
63
+ // The JSON text of a value, given up as soon as it would be longer than limit characters. A
64
+ // value referenced many times is written as many times, so the text can be far longer than the
65
+ // value is large. What each member adds is counted as JSON.stringify writes it, and the count
66
+ // is a lower bound of its length (an escape only adds), so a text within the limit is never
67
+ // given up. The members JSON.stringify visits are counted as well, also those it leaves out (a
68
+ // function, undefined): at most as many as the limit has characters.
69
+ var TOO_LARGE = {};
70
+ function stringifyWithin(value, limit) {
71
+ var length = 0;
72
+ var visits = 0;
73
+ var root = true;
74
+ return stringify(value, function (key, member) {
75
+ if (++visits > limit) throw TOO_LARGE;
76
+ // A String or Number object is written as what it converts to; converted here, the way
77
+ // JSON.stringify converts it and once, so the count is of what is written.
78
+ if (member !== null && typeof member === 'object') {
79
+ if (hasSlot(stringValueOf, member)) member = toText(member);
80
+ else if (hasSlot(numberValueOf, member)) member = +member;
81
+ }
82
+ var added;
83
+ var kind = typeof member;
84
+ if (kind === 'string') added = member.length + 2;
85
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
86
+ else if (kind === 'boolean') added = member ? 4 : 5;
87
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
88
+ else added = 0;
89
+ if (!root) {
90
+ // An element of an array is written, as null if nothing else; a member of an object
91
+ // that is written has its key in front of it.
92
+ if (isArray(this)) added = added || 4;
93
+ else if (added > 0) added += key.length + 3;
94
+ }
95
+ root = false;
96
+ length += added;
97
+ if (length > limit) throw TOO_LARGE;
98
+ return member;
99
+ });
100
+ }
101
+
102
+ // An argument as it is written in the line, in at most room characters for an object: an
103
+ // object is written only when the line has room left, and its text within that room. TOO_LARGE
104
+ // when it does not fit.
105
+ function formatArgument(value, room) {
50
106
  if (value === undefined) return 'undefined';
51
107
  if (value === null) return 'null';
52
108
  if (typeof value === 'object') {
109
+ if (room <= 0) throw TOO_LARGE;
53
110
  try {
54
- var json = stringify(value);
111
+ var json = stringifyWithin(value, room);
55
112
  return json === undefined ? '' : json;
56
113
  } catch (e) {
114
+ if (e === TOO_LARGE) throw e;
57
115
  return toText(value);
58
116
  }
59
117
  }
@@ -64,19 +122,38 @@ var CONSOLE_FACTORY_SOURCE = `
64
122
  var callCount = 0;
65
123
  var totalBytes = 0;
66
124
 
125
+ function tooLarge() {
126
+ return new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
127
+ }
128
+
67
129
  function method(level) {
68
130
  return (...args) => {
69
131
  callCount++;
70
132
  if (callCount > maxCalls) {
71
133
  throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
72
134
  }
135
+ // The line is measured as it is built: what an argument may add is the room the limit
136
+ // leaves, so the work done on a line that does not fit is in proportion to the limit.
73
137
  var line = '';
74
138
  for (var i = 0; i < args.length; i++) {
75
- line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
139
+ var separator = i === 0 ? '' : ' ';
140
+ var text;
141
+ try {
142
+ text = formatArgument(args[i], maxBytes - totalBytes - line.length - separator.length);
143
+ } catch (e) {
144
+ if (e !== TOO_LARGE) throw e;
145
+ totalBytes = maxBytes + 1;
146
+ throw tooLarge();
147
+ }
148
+ line += separator + text;
149
+ if (totalBytes + line.length > maxBytes) {
150
+ totalBytes = maxBytes + 1;
151
+ throw tooLarge();
152
+ }
76
153
  }
77
154
  totalBytes += line.length;
78
155
  if (totalBytes > maxBytes) {
79
- throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
156
+ throw tooLarge();
80
157
  }
81
158
  try {
82
159
  write(level, line);
@@ -378,6 +455,11 @@ var ReturnSignal = class {
378
455
  this.value = value;
379
456
  }
380
457
  };
458
+ var ScriptThrown = class {
459
+ constructor(value) {
460
+ this.value = value;
461
+ }
462
+ };
381
463
  var BreakSignal = class {
382
464
  };
383
465
  var ContinueSignal = class {
@@ -541,33 +623,44 @@ var Interpreter = class {
541
623
  * For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
542
624
  * of the script, or a built-in or host function the script passed along.
543
625
  */
544
- call(fn, args) {
545
- if (this.fatal !== void 0) throw this.fatal;
546
- if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
547
- if (this.interpretedFunctions.has(fn)) return fn(...args);
548
- return this.callFunction(fn, void 0, args, this.callerDepth);
626
+ async call(fn, args) {
627
+ try {
628
+ if (this.fatal !== void 0) throw this.fatal;
629
+ if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
630
+ if (this.interpretedFunctions.has(fn)) return await fn(...args);
631
+ return await this.callFunction(fn, void 0, args, this.callerDepth);
632
+ } catch (thrown) {
633
+ if (thrown instanceof ScriptThrown) throw thrown.value;
634
+ if (!(thrown instanceof Error)) throw new InterpreterError("Host operation failed");
635
+ throw thrown;
636
+ }
549
637
  }
550
638
  /** Number of AST nodes evaluated so far (for execution stats). */
551
639
  get stepCount() {
552
640
  return this.steps;
553
641
  }
554
642
  async run(program) {
555
- const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
556
- for (const stmt of program.body) {
557
- if (stmt.type === "FunctionDeclaration" && stmt.id) {
558
- root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
643
+ try {
644
+ const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
645
+ for (const stmt of program.body) {
646
+ if (stmt.type === "FunctionDeclaration" && stmt.id) {
647
+ root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
648
+ }
559
649
  }
650
+ let last;
651
+ for (const stmt of program.body) {
652
+ if (stmt.type === "FunctionDeclaration") continue;
653
+ last = await this.execStatement(stmt, root);
654
+ }
655
+ if (root.has("__ag_main")) {
656
+ const main = root.get("__ag_main");
657
+ if (typeof main === "function") return await main();
658
+ }
659
+ return last;
660
+ } catch (thrown) {
661
+ if (thrown instanceof ScriptThrown) throw thrown.value;
662
+ throw thrown;
560
663
  }
561
- let last;
562
- for (const stmt of program.body) {
563
- if (stmt.type === "FunctionDeclaration") continue;
564
- last = await this.execStatement(stmt, root);
565
- }
566
- if (root.has("__ag_main")) {
567
- const main = root.get("__ag_main");
568
- if (typeof main === "function") return main();
569
- }
570
- return last;
571
664
  }
572
665
  /**
573
666
  * End the run from outside: whatever of the script is still going (a callback waiting for a
@@ -741,7 +834,7 @@ var Interpreter = class {
741
834
  case "TryStatement":
742
835
  return this.execTry(node, scope);
743
836
  case "ThrowStatement":
744
- throw await this.evalExpr(node.argument, scope);
837
+ throw new ScriptThrown(await this.evalExpr(node.argument, scope));
745
838
  case "ReturnStatement":
746
839
  throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
747
840
  case "BreakStatement":
@@ -863,12 +956,12 @@ var Interpreter = class {
863
956
  }
864
957
  }
865
958
  /**
866
- * What a `catch` clause receives. A value the script threw is its own. A host Error (a refusal
867
- * by the interpreter, a failed tool call, a TypeError of a built-in) is replaced by a plain
868
- * copy with its name, message and code.
959
+ * What a `catch` clause receives. A value the script threw is its own. A host Error is copied
960
+ * with its name, message and code; every other host rejection reason becomes a generic error.
869
961
  */
870
962
  toScriptValue(thrown) {
871
- if (!(thrown instanceof Error)) return thrown;
963
+ if (thrown instanceof ScriptThrown) return thrown.value;
964
+ if (!(thrown instanceof Error)) return createScriptError("Error", "Host operation failed");
872
965
  const known = this.errorCopies.get(thrown);
873
966
  if (known) return known;
874
967
  const code = thrown.code;
@@ -2259,27 +2352,28 @@ function expandReplacement(template, text, at, matched) {
2259
2352
  function convertedOnce(value, convert) {
2260
2353
  return typeof value === "object" && value !== null ? convert(value) : value;
2261
2354
  }
2262
- function checkArrayWrite(array, key, value) {
2355
+ function checkArrayWrite(array, key, value, currentLength = array.length) {
2263
2356
  if (key === "length") value = convertedOnce(value, Number);
2264
- const length = arrayLengthAfterWrite(array, key, value);
2357
+ const length = arrayLengthAfterWrite(currentLength, key, value);
2265
2358
  if (length > MAX_ARRAY_LENGTH) {
2266
2359
  throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
2267
2360
  }
2268
2361
  return { value, length };
2269
2362
  }
2270
- function arrayLengthAfterWrite(array, key, value) {
2363
+ function arrayLengthAfterWrite(currentLength, key, value) {
2271
2364
  if (key === "length") {
2272
2365
  const length = Number(value);
2273
2366
  if (!Number.isInteger(length) || length < 0) throw new InterpreterError("Invalid array length");
2274
2367
  return length;
2275
2368
  }
2276
2369
  const index = Number(key);
2277
- if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(array.length, index + 1);
2278
- return array.length;
2370
+ if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(currentLength, index + 1);
2371
+ return currentLength;
2279
2372
  }
2280
2373
 
2281
2374
  // libs/core/src/value-sanitizer.ts
2282
2375
  var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
2376
+ var CIRCULAR_MARKER_BYTES = 12;
2283
2377
  var ReflectApply2 = Reflect.apply;
2284
2378
  var ReflectGet = Reflect.get;
2285
2379
  var ArrayIsArray = Array.isArray;
@@ -2425,9 +2519,12 @@ function sanitizeObjectValue(value, options, depth, context) {
2425
2519
  const sanitizedMap = ObjectCreate(null);
2426
2520
  const entries = ReflectApply2(MapProtoEntries, inspected, []);
2427
2521
  for (const [key, val] of entries) {
2522
+ context.propCount.count++;
2523
+ if (context.propCount.count > maxProperties) {
2524
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
2525
+ }
2428
2526
  if (typeof key !== "string") continue;
2429
2527
  if (DANGEROUS_KEYS.has(key)) continue;
2430
- context.propCount.count++;
2431
2528
  sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
2432
2529
  }
2433
2530
  return sanitizedMap;
@@ -2437,6 +2534,9 @@ function sanitizeObjectValue(value, options, depth, context) {
2437
2534
  const result = [];
2438
2535
  for (const item of iter) {
2439
2536
  context.propCount.count++;
2537
+ if (context.propCount.count > maxProperties) {
2538
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
2539
+ }
2440
2540
  result.push(sanitizeValue(item, options, depth + 1, context));
2441
2541
  }
2442
2542
  return result;
@@ -2524,7 +2624,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
2524
2624
  }
2525
2625
  if (ArrayIsArray(value)) {
2526
2626
  if (currentPath.has(value)) {
2527
- return 4;
2627
+ return CIRCULAR_MARKER_BYTES;
2528
2628
  }
2529
2629
  currentPath.add(value);
2530
2630
  try {
@@ -2550,7 +2650,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
2550
2650
  if (type === "object") {
2551
2651
  const object = value;
2552
2652
  if (currentPath.has(object)) {
2553
- return 4;
2653
+ return CIRCULAR_MARKER_BYTES;
2554
2654
  }
2555
2655
  if (!isPlainObject(object)) {
2556
2656
  if (hasBrand(DateProtoGetTime, object)) {
@@ -2774,13 +2874,26 @@ var SafeObject = frozenRecord({
2774
2874
  if (!isScriptData(target) || Object.isFrozen(target)) {
2775
2875
  throw new TypeError("Object.assign needs an object or array the script created as its target");
2776
2876
  }
2877
+ const targetIsArray = Array.isArray(target);
2878
+ const lengths = [];
2879
+ let length = targetIsArray ? target.length : 0;
2777
2880
  for (const source of sources) {
2778
2881
  if (source === null || source === void 0) continue;
2779
2882
  for (const key of dataKeys(source)) {
2780
- let value = source[key];
2883
+ const value = source[key];
2781
2884
  assertStorable(target, key, value);
2782
- if (Array.isArray(target)) value = checkArrayWrite(target, key, value).value;
2783
- target[key] = value;
2885
+ if (targetIsArray) {
2886
+ const checked = checkArrayWrite(target, key, value, length);
2887
+ length = checked.length;
2888
+ if (key === "length") lengths.push(checked.value);
2889
+ }
2890
+ }
2891
+ }
2892
+ let nextLength = 0;
2893
+ for (const source of sources) {
2894
+ if (source === null || source === void 0) continue;
2895
+ for (const key of dataKeys(source)) {
2896
+ target[key] = targetIsArray && key === "length" ? lengths[nextLength++] : source[key];
2784
2897
  }
2785
2898
  }
2786
2899
  return target;
@@ -3256,10 +3369,19 @@ var REFERENCE_CONFIGS = {
3256
3369
  // Very deep resolution
3257
3370
  }
3258
3371
  };
3372
+ var REF_ID_PREFIX = "__REF_";
3373
+ var REF_ID_SUFFIX = "__";
3259
3374
  var REF_ID_PATTERN = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
3260
3375
  function isReferenceId(value) {
3261
3376
  return typeof value === "string" && REF_ID_PATTERN.test(value);
3262
3377
  }
3378
+ function getMaxTotalResolvedSize(config) {
3379
+ const configured = config.maxTotalResolvedSize;
3380
+ if (typeof configured === "number" && configured >= 0) {
3381
+ return configured;
3382
+ }
3383
+ return 2 * config.maxTotalSize;
3384
+ }
3263
3385
 
3264
3386
  // libs/core/src/sidecar/reference-sidecar.ts
3265
3387
  var SidecarLimitError = class _SidecarLimitError extends Error {
@@ -3272,6 +3394,245 @@ var SidecarLimitError = class _SidecarLimitError extends Error {
3272
3394
  Object.setPrototypeOf(this, _SidecarLimitError.prototype);
3273
3395
  }
3274
3396
  };
3397
+ var ReferenceSidecar = class {
3398
+ constructor(config) {
3399
+ this.config = config;
3400
+ this.maxTotalResolvedSize = getMaxTotalResolvedSize(config);
3401
+ }
3402
+ storage = /* @__PURE__ */ new Map();
3403
+ metadata = /* @__PURE__ */ new Map();
3404
+ /** The stored values that were resolved for a tool call, as the string they were resolved to */
3405
+ resolved = /* @__PURE__ */ new Map();
3406
+ totalSize = 0;
3407
+ /** Bytes of resolved data built for the tool calls of this execution so far */
3408
+ resolvedSize = 0;
3409
+ maxTotalResolvedSize;
3410
+ disposed = false;
3411
+ /**
3412
+ * Store data and return a reference ID
3413
+ *
3414
+ * @param data - The data to store (string or Buffer)
3415
+ * @param source - Where this data came from
3416
+ * @param options - Optional metadata
3417
+ * @returns The reference ID (format: __REF_uuid__)
3418
+ * @throws SidecarLimitError if limits are exceeded
3419
+ */
3420
+ store(data, source, options) {
3421
+ if (this.disposed) {
3422
+ throw new Error("Cannot store: sidecar has been disposed");
3423
+ }
3424
+ const buffer = typeof data === "string" ? Buffer.from(data, "utf-8") : data;
3425
+ const size = buffer.length;
3426
+ if (this.storage.size >= this.config.maxReferenceCount) {
3427
+ throw new SidecarLimitError(
3428
+ `Maximum reference count exceeded (${this.config.maxReferenceCount})`,
3429
+ "MAX_REFERENCE_COUNT",
3430
+ this.config.maxReferenceCount,
3431
+ this.storage.size
3432
+ );
3433
+ }
3434
+ if (size > this.config.maxReferenceSize) {
3435
+ throw new SidecarLimitError(
3436
+ `Reference size ${size} bytes exceeds maximum ${this.config.maxReferenceSize} bytes`,
3437
+ "MAX_REFERENCE_SIZE",
3438
+ this.config.maxReferenceSize,
3439
+ size
3440
+ );
3441
+ }
3442
+ if (this.totalSize + size > this.config.maxTotalSize) {
3443
+ throw new SidecarLimitError(
3444
+ `Total sidecar size would exceed maximum: ${this.totalSize + size} > ${this.config.maxTotalSize}`,
3445
+ "MAX_TOTAL_SIZE",
3446
+ this.config.maxTotalSize,
3447
+ this.totalSize + size
3448
+ );
3449
+ }
3450
+ const randomUUID = globalThis.crypto?.randomUUID?.bind(globalThis.crypto);
3451
+ if (!randomUUID) throw new Error("Secure random UUID generation is unavailable");
3452
+ const refId = `${REF_ID_PREFIX}${randomUUID()}${REF_ID_SUFFIX}`;
3453
+ this.storage.set(refId, Buffer.from(buffer));
3454
+ this.totalSize += size;
3455
+ this.metadata.set(refId, {
3456
+ createdAt: Date.now(),
3457
+ size,
3458
+ source,
3459
+ mimeType: options?.mimeType,
3460
+ origin: options?.origin
3461
+ });
3462
+ return refId;
3463
+ }
3464
+ /**
3465
+ * Retrieve data by reference ID
3466
+ *
3467
+ * @param refId - The reference ID to look up
3468
+ * @returns The stored data or undefined if not found
3469
+ */
3470
+ retrieve(refId) {
3471
+ if (this.disposed) {
3472
+ return void 0;
3473
+ }
3474
+ const data = this.storage.get(refId);
3475
+ return data ? Buffer.from(data) : void 0;
3476
+ }
3477
+ /**
3478
+ * Retrieve data as a string
3479
+ *
3480
+ * @param refId - The reference ID to look up
3481
+ * @param encoding - String encoding (default: utf-8)
3482
+ * @returns The stored data as a string or undefined
3483
+ */
3484
+ retrieveString(refId, encoding = "utf-8") {
3485
+ const data = this.retrieve(refId);
3486
+ return data?.toString(encoding);
3487
+ }
3488
+ /**
3489
+ * Resolve a reference for a tool call: the stored data as a string
3490
+ *
3491
+ * A stored value is decoded once in the life of the sidecar (one execution) and counted
3492
+ * against `maxTotalResolvedSize` then. Every later resolution, in the same call or in another,
3493
+ * returns the same string and counts nothing: a string cannot be changed, so handing it out
3494
+ * again takes no memory.
3495
+ *
3496
+ * @param refId - The reference ID to resolve
3497
+ * @returns The stored data as a string, or undefined if the reference is not known
3498
+ * @throws SidecarLimitError if the execution's total of resolved data would be exceeded
3499
+ */
3500
+ resolveString(refId) {
3501
+ if (this.disposed) {
3502
+ return void 0;
3503
+ }
3504
+ const known = this.resolved.get(refId);
3505
+ if (known !== void 0) {
3506
+ return known;
3507
+ }
3508
+ const data = this.storage.get(refId);
3509
+ if (data === void 0) {
3510
+ return void 0;
3511
+ }
3512
+ this.countResolved(data.length);
3513
+ const text = data.toString("utf-8");
3514
+ this.resolved.set(refId, text);
3515
+ return text;
3516
+ }
3517
+ /**
3518
+ * Whether a reference was resolved before, so that resolving it again counts nothing
3519
+ */
3520
+ isResolved(refId) {
3521
+ return !this.disposed && this.resolved.has(refId);
3522
+ }
3523
+ /**
3524
+ * Count resolved data that is about to be built for a tool call of this execution
3525
+ *
3526
+ * @param bytes - Size of the data in bytes
3527
+ * @throws SidecarLimitError if the total would exceed `maxTotalResolvedSize`; nothing is counted then
3528
+ */
3529
+ countResolved(bytes) {
3530
+ if (!this.canResolve(bytes)) {
3531
+ throw new SidecarLimitError(
3532
+ `Total resolved size would exceed maximum: ${this.resolvedSize + bytes} > ${this.maxTotalResolvedSize}`,
3533
+ "MAX_TOTAL_RESOLVED_SIZE",
3534
+ this.maxTotalResolvedSize,
3535
+ this.resolvedSize + bytes
3536
+ );
3537
+ }
3538
+ this.resolvedSize += bytes;
3539
+ }
3540
+ /**
3541
+ * Whether `bytes` more of resolved data fit in what this execution may resolve in total
3542
+ */
3543
+ canResolve(bytes) {
3544
+ return bytes >= 0 && this.resolvedSize + bytes <= this.maxTotalResolvedSize;
3545
+ }
3546
+ /**
3547
+ * Bytes of resolved data built for the tool calls of this execution so far
3548
+ */
3549
+ getResolvedSize() {
3550
+ return this.resolvedSize;
3551
+ }
3552
+ /**
3553
+ * Check if a reference ID exists
3554
+ */
3555
+ has(refId) {
3556
+ return !this.disposed && this.storage.has(refId);
3557
+ }
3558
+ /**
3559
+ * Get metadata for a reference
3560
+ */
3561
+ getMetadata(refId) {
3562
+ if (this.disposed) {
3563
+ return void 0;
3564
+ }
3565
+ return this.metadata.get(refId);
3566
+ }
3567
+ /**
3568
+ * Get the size of a reference without retrieving data
3569
+ */
3570
+ getSize(refId) {
3571
+ return this.getMetadata(refId)?.size;
3572
+ }
3573
+ /**
3574
+ * Get total size of all stored references
3575
+ */
3576
+ getTotalSize() {
3577
+ return this.totalSize;
3578
+ }
3579
+ /**
3580
+ * Get number of stored references
3581
+ */
3582
+ getCount() {
3583
+ return this.storage.size;
3584
+ }
3585
+ /**
3586
+ * Get the configuration
3587
+ */
3588
+ getConfig() {
3589
+ return { ...this.config };
3590
+ }
3591
+ /**
3592
+ * Check if a value is a reference ID
3593
+ */
3594
+ isReference(value) {
3595
+ return isReferenceId(value);
3596
+ }
3597
+ /**
3598
+ * Get all reference IDs (for debugging/auditing)
3599
+ */
3600
+ getAllReferenceIds() {
3601
+ return Array.from(this.storage.keys());
3602
+ }
3603
+ /**
3604
+ * Get audit log of all stored references
3605
+ */
3606
+ getAuditLog() {
3607
+ const log = [];
3608
+ for (const [refId, metadata] of this.metadata) {
3609
+ log.push({ refId, metadata });
3610
+ }
3611
+ return log;
3612
+ }
3613
+ /**
3614
+ * Check if the sidecar has been disposed
3615
+ */
3616
+ isDisposed() {
3617
+ return this.disposed;
3618
+ }
3619
+ /**
3620
+ * Dispose the sidecar and release all memory
3621
+ *
3622
+ * MUST be called after each execution to prevent memory leaks.
3623
+ * After disposal, the sidecar cannot be used.
3624
+ */
3625
+ dispose() {
3626
+ if (this.disposed) {
3627
+ return;
3628
+ }
3629
+ this.storage.clear();
3630
+ this.metadata.clear();
3631
+ this.resolved.clear();
3632
+ this.totalSize = 0;
3633
+ this.disposed = true;
3634
+ }
3635
+ };
3275
3636
 
3276
3637
  // libs/core/src/sidecar/reference-resolver.ts
3277
3638
  var ReflectGet2 = Reflect.get;
@@ -3542,28 +3903,38 @@ var ReferenceResolver = class {
3542
3903
  /**
3543
3904
  * Check if a value contains any reference IDs
3544
3905
  *
3906
+ * Every value is looked at, at any depth: a reference or composite past `maxResolutionDepth`
3907
+ * cannot be resolved, and it must still be found, so that `resolve()` refuses the call rather
3908
+ * than the handler receiving it unresolved. The value is walked with a list instead of by
3909
+ * recursion, so a deep value cannot exhaust the stack, and an object is looked at once.
3910
+ *
3545
3911
  * @param value - The value to check
3546
- * @param depth - Current recursion depth (internal)
3912
+ * @param _depth - Unused; kept for callers that pass a depth
3547
3913
  * @returns true if the value or any nested value is a reference
3548
3914
  */
3549
- containsReferences(value, depth = 0) {
3550
- if (depth > this.config.maxResolutionDepth) {
3551
- return false;
3552
- }
3553
- if (isReferenceId(value) || isCompositeHandle(value)) {
3554
- return true;
3555
- }
3556
- if (Array.isArray(value)) {
3557
- const len = untrustedLength(value);
3558
- for (let i = 0; i < len; i++) {
3559
- if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
3560
- return true;
3915
+ containsReferences(value, _depth = 0) {
3916
+ const pending = [value];
3917
+ const seen = /* @__PURE__ */ new Set();
3918
+ while (pending.length > 0) {
3919
+ const current = pending.pop();
3920
+ if (isReferenceId(current) || isCompositeHandle(current)) {
3921
+ return true;
3922
+ }
3923
+ if (current === null || typeof current !== "object" || seen.has(current)) {
3924
+ continue;
3925
+ }
3926
+ seen.add(current);
3927
+ if (Array.isArray(current)) {
3928
+ const len = untrustedLength(current);
3929
+ for (let i = 0; i < len; i++) {
3930
+ pending.push(untrustedAt(current, i));
3561
3931
  }
3932
+ continue;
3933
+ }
3934
+ const members = Object.values(current);
3935
+ for (let i = 0; i < members.length; i++) {
3936
+ pending.push(members[i]);
3562
3937
  }
3563
- return false;
3564
- }
3565
- if (value !== null && typeof value === "object") {
3566
- return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
3567
3938
  }
3568
3939
  return false;
3569
3940
  }
@@ -3760,6 +4131,79 @@ function sanitizeStackTrace(stack, sanitize = true) {
3760
4131
  return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
3761
4132
  }
3762
4133
 
4134
+ // libs/core/src/thrown-value.ts
4135
+ var MAX_THROWN_MESSAGE_LENGTH = 16 * 1024;
4136
+ var MAX_THROWN_STACK_LENGTH = 64 * 1024;
4137
+
4138
+ // libs/core/src/bounded-json.ts
4139
+ var JSONStringify = JSON.stringify;
4140
+ var ReflectApply3 = Reflect.apply;
4141
+ var ArrayIsArray2 = Array.isArray;
4142
+ var StringValueOf = String.prototype.valueOf;
4143
+ var NumberValueOf = Number.prototype.valueOf;
4144
+ var JsonTooLargeError = class extends Error {
4145
+ constructor(limit) {
4146
+ super(`JSON text exceeds ${limit} bytes`);
4147
+ this.name = "JsonTooLargeError";
4148
+ }
4149
+ };
4150
+ var JsonTraversalLimitError = class extends Error {
4151
+ constructor(limit) {
4152
+ super(`JSON traversal exceeds ${limit} members`);
4153
+ this.name = "JsonTraversalLimitError";
4154
+ }
4155
+ };
4156
+ function hasSlot(valueOf, value) {
4157
+ try {
4158
+ ReflectApply3(valueOf, value, []);
4159
+ return true;
4160
+ } catch {
4161
+ return false;
4162
+ }
4163
+ }
4164
+ function stringifyWithin(value, limit) {
4165
+ let bytes = 0;
4166
+ let visits = 0;
4167
+ const maxVisits = Math.max(1e4, Math.min(1e6, limit * 10));
4168
+ let root = true;
4169
+ return JSONStringify(value, function(key, member) {
4170
+ if (++visits > maxVisits) throw new JsonTraversalLimitError(maxVisits);
4171
+ if (member !== null && typeof member === "object") {
4172
+ if (hasSlot(StringValueOf, member)) member = String(member);
4173
+ else if (hasSlot(NumberValueOf, member)) member = Number(member);
4174
+ }
4175
+ let added;
4176
+ switch (typeof member) {
4177
+ case "string":
4178
+ added = member.length + 2;
4179
+ break;
4180
+ case "number":
4181
+ added = Number.isFinite(member) ? String(member).length : 4;
4182
+ break;
4183
+ case "boolean":
4184
+ added = member ? 4 : 5;
4185
+ break;
4186
+ case "object":
4187
+ case "bigint":
4188
+ added = member === null ? 4 : 2;
4189
+ break;
4190
+ default:
4191
+ added = 0;
4192
+ }
4193
+ if (!root) {
4194
+ if (ArrayIsArray2(this)) added = added || 4;
4195
+ else if (added > 0) added += key.length + 3;
4196
+ }
4197
+ root = false;
4198
+ bytes += added;
4199
+ if (bytes > limit) throw new JsonTooLargeError(limit);
4200
+ return member;
4201
+ });
4202
+ }
4203
+ function utf8Length2(value) {
4204
+ return Buffer.byteLength(value, "utf8");
4205
+ }
4206
+
3763
4207
  // libs/core/src/tool-bridge.ts
3764
4208
  var TOOL_BRIDGE_PROTOCOL_VERSION = 1;
3765
4209
  function utf8ByteLength(value) {
@@ -3915,9 +4359,9 @@ function createHostToolBridge(executionContext, options) {
3915
4359
  if (typeof executionContext.hostToolBridge === "function") {
3916
4360
  return createRelayedToolBridge(executionContext, options, executionContext.hostToolBridge);
3917
4361
  }
3918
- const { config, stats, toolHandler, sidecar, referenceConfig } = executionContext;
4362
+ const { config, stats, toolHandler, sidecar, referenceConfig: referenceConfig2 } = executionContext;
3919
4363
  const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
3920
- const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
4364
+ const resolver = sidecar && referenceConfig2 ? new ReferenceResolver(sidecar, referenceConfig2) : void 0;
3921
4365
  return async (requestJson) => {
3922
4366
  try {
3923
4367
  if (typeof requestJson !== "string") {
@@ -4095,6 +4539,7 @@ function createHostToolBridge(executionContext, options) {
4095
4539
  "Tool returned an unsupported value",
4096
4540
  "TOOL_RESULT_NOT_SAFE"
4097
4541
  );
4542
+ executionContext.onToolBridgeFailure?.();
4098
4543
  return serializeResponse(
4099
4544
  {
4100
4545
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -4104,13 +4549,55 @@ function createHostToolBridge(executionContext, options) {
4104
4549
  maxPayloadBytes
4105
4550
  );
4106
4551
  }
4107
- if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
4552
+ const resultLimit = executionContext.maxToolResultBytes;
4553
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
4554
+ let tooLarge = false;
4555
+ let tooComplex = false;
4556
+ try {
4557
+ const resultJson = stringifyWithin(sanitizedResult, resultLimit);
4558
+ tooLarge = resultJson !== void 0 && utf8ByteLength(resultJson) > resultLimit;
4559
+ } catch (error) {
4560
+ tooLarge = error instanceof JsonTooLargeError;
4561
+ tooComplex = error instanceof JsonTraversalLimitError;
4562
+ }
4563
+ if (tooLarge || tooComplex) {
4564
+ executionContext.onToolBridgeFailure?.();
4565
+ return serializeResponse(
4566
+ {
4567
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
4568
+ ok: false,
4569
+ error: {
4570
+ name: "ToolBridgeError",
4571
+ message: tooComplex ? "Tool result exceeds the traversal limit" : `Tool result exceeds the limit of ${resultLimit} bytes`,
4572
+ code: tooComplex ? "TOOL_RESULT_TOO_COMPLEX" : "TOOL_RESULT_TOO_LARGE",
4573
+ toolError: true
4574
+ }
4575
+ },
4576
+ maxPayloadBytes
4577
+ );
4578
+ }
4579
+ }
4580
+ if (sidecar && referenceConfig2 && typeof sanitizedResult === "string") {
4108
4581
  const size = utf8ByteLength(sanitizedResult);
4109
- if (size >= referenceConfig.extractionThreshold) {
4582
+ if (size >= referenceConfig2.extractionThreshold) {
4110
4583
  try {
4111
4584
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
4112
4585
  sanitizedResult = refId;
4113
4586
  } catch {
4587
+ executionContext.onToolBridgeFailure?.();
4588
+ return serializeResponse(
4589
+ {
4590
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
4591
+ ok: false,
4592
+ error: {
4593
+ name: "ToolBridgeError",
4594
+ message: "Tool result could not be stored in the reference sidecar",
4595
+ code: "TOOL_RESULT_NOT_STORED",
4596
+ toolError: true
4597
+ }
4598
+ },
4599
+ maxPayloadBytes
4600
+ );
4114
4601
  }
4115
4602
  }
4116
4603
  }
@@ -4125,6 +4612,7 @@ function createHostToolBridge(executionContext, options) {
4125
4612
  "Tool result must be JSON-serializable",
4126
4613
  "TOOL_RESULT_NOT_JSON"
4127
4614
  );
4615
+ executionContext.onToolBridgeFailure?.();
4128
4616
  return serializeResponse(
4129
4617
  {
4130
4618
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -4135,6 +4623,7 @@ function createHostToolBridge(executionContext, options) {
4135
4623
  );
4136
4624
  }
4137
4625
  if (utf8ByteLength(okJson) > maxPayloadBytes) {
4626
+ executionContext.onToolBridgeFailure?.();
4138
4627
  return serializeResponse(
4139
4628
  {
4140
4629
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -4345,7 +4834,7 @@ var InterpreterAdapter = class {
4345
4834
  */
4346
4835
  runtimeGlobals(context, charge, callbacks) {
4347
4836
  const { config } = context;
4348
- const callTool = observed(this.createCallTool(context, callbacks));
4837
+ const callTool = observed(this.createCallTool(context, callbacks, charge));
4349
4838
  const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
4350
4839
  const joinReferences = (parts) => {
4351
4840
  if (!resolver) {
@@ -4427,9 +4916,21 @@ var InterpreterAdapter = class {
4427
4916
  const settled = await Promise.allSettled(tasks.map(async (task) => task()));
4428
4917
  const failures = settled.filter((result) => result.status === "rejected");
4429
4918
  if (failures.length > 0) {
4430
- const messages = failures.map((failure) => this.describe(failure.reason).message).join("\n");
4431
- throw sandboxError(`${failures.length} of ${tasks.length} parallel operations failed:
4432
- ${messages}`);
4919
+ let messages = "";
4920
+ let listed = 0;
4921
+ for (const failure of failures) {
4922
+ const room = MAX_THROWN_MESSAGE_LENGTH - messages.length - (listed === 0 ? 0 : 1);
4923
+ if (room <= 0) break;
4924
+ const message = this.describe(failure.reason).message;
4925
+ messages += (listed === 0 ? "" : "\n") + (message.length > room ? message.slice(0, room) : message);
4926
+ listed++;
4927
+ }
4928
+ const unlisted = failures.length - listed;
4929
+ throw sandboxError(
4930
+ `${failures.length} of ${tasks.length} parallel operations failed:
4931
+ ${messages}` + (unlisted > 0 ? `
4932
+ (${unlisted} more not shown)` : "")
4933
+ );
4433
4934
  }
4434
4935
  return settled.map((result) => result.value);
4435
4936
  });
@@ -4486,9 +4987,81 @@ ${messages}`);
4486
4987
  }
4487
4988
  const custom = config.globals;
4488
4989
  if (custom && typeof custom === "object") {
4990
+ const maxGlobalCalls = config.maxGlobalFunctionCalls ?? Math.max(10, config.maxToolCalls * 10);
4991
+ const payloadLimit = config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
4992
+ let globalCalls = 0;
4993
+ const serialize = (value) => {
4994
+ const sanitized = sanitizeValue(value, {
4995
+ maxDepth: config.maxSanitizeDepth,
4996
+ maxProperties: config.maxSanitizeProperties,
4997
+ allowDates: false,
4998
+ allowErrors: true
4999
+ });
5000
+ const json = stringifyWithin(sanitized, payloadLimit);
5001
+ if (json === void 0) return void 0;
5002
+ if (utf8Length2(json) > payloadLimit) throw sandboxError("Global function value exceeds bridge limit");
5003
+ return json;
5004
+ };
5005
+ const copy = (value) => {
5006
+ const json = serialize(value);
5007
+ return json === void 0 ? void 0 : JSON.parse(json);
5008
+ };
5009
+ const safeHostCall = (name, fn) => (...args) => {
5010
+ if (callbacks.over || context.aborted) throw executionOver();
5011
+ if (++globalCalls > maxGlobalCalls)
5012
+ throw sandboxError(`Global function call limit exceeded (${maxGlobalCalls})`);
5013
+ if (context.beforeGlobalCall && context.beforeGlobalCall() !== true) {
5014
+ throw sandboxError("Global function policy refused the call");
5015
+ }
5016
+ let safeArgs;
5017
+ try {
5018
+ safeArgs = copy(args);
5019
+ } catch {
5020
+ throw sandboxError(`Global function ${name} received unsupported arguments`, "TypeError");
5021
+ }
5022
+ let outcome;
5023
+ try {
5024
+ outcome = fn(...safeArgs);
5025
+ } catch {
5026
+ throw sandboxError("Global function failed");
5027
+ }
5028
+ const settle = (value) => {
5029
+ if (callbacks.over || context.aborted) throw executionOver();
5030
+ let json;
5031
+ try {
5032
+ json = serialize(value);
5033
+ } catch {
5034
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
5035
+ }
5036
+ if (json === void 0) return void 0;
5037
+ if (value !== null && typeof value === "object") charge(Math.max(json.length * 2, utf8Length2(json)));
5038
+ return JSON.parse(json);
5039
+ };
5040
+ if (outcome !== null && (typeof outcome === "object" || typeof outcome === "function")) {
5041
+ let then;
5042
+ try {
5043
+ then = outcome.then;
5044
+ } catch {
5045
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
5046
+ }
5047
+ if (typeof then === "function") {
5048
+ return observed(async () => {
5049
+ let value;
5050
+ try {
5051
+ value = await Promise.resolve(outcome);
5052
+ } catch {
5053
+ throw sandboxError("Global function failed");
5054
+ }
5055
+ return settle(value);
5056
+ })();
5057
+ }
5058
+ }
5059
+ return settle(outcome);
5060
+ };
4489
5061
  for (const name of Object.keys(custom)) {
4490
5062
  if (name.startsWith("__") || Object.prototype.hasOwnProperty.call(globals, name)) continue;
4491
- globals[name] = frozenDataCopy(name, custom[name]);
5063
+ const value = custom[name];
5064
+ globals[name] = typeof value === "function" ? safeHostCall(name, value) : frozenDataCopy(name, value);
4492
5065
  }
4493
5066
  }
4494
5067
  return globals;
@@ -4498,7 +5071,7 @@ ${messages}`);
4498
5071
  * and the response cross as JSON, so the handler never receives a value of the script and the
4499
5072
  * script never receives an object of the handler.
4500
5073
  */
4501
- createCallTool(context, execution) {
5074
+ createCallTool(context, execution, charge) {
4502
5075
  const configured = context.config.toolHandler;
4503
5076
  const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
4504
5077
  const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
@@ -4529,9 +5102,20 @@ ${messages}`);
4529
5102
  } catch {
4530
5103
  throw sandboxError("Tool arguments must be JSON-serializable", "TypeError");
4531
5104
  }
5105
+ if (utf8Length2(requestJson) > maxPayloadBytes) {
5106
+ throw sandboxError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "ToolBridgeError");
5107
+ }
5108
+ if (context.beforeToolCall) {
5109
+ const request = JSON.parse(requestJson);
5110
+ if (context.beforeToolCall(toolName, request.args) !== true) {
5111
+ throw sandboxError("Tool policy refused the call");
5112
+ }
5113
+ }
4532
5114
  let response;
5115
+ let responseJson;
4533
5116
  try {
4534
- response = JSON.parse(await bridge(requestJson));
5117
+ responseJson = await bridge(requestJson);
5118
+ response = JSON.parse(responseJson);
4535
5119
  } catch {
4536
5120
  throw sandboxError("Tool bridge returned invalid JSON");
4537
5121
  }
@@ -4540,6 +5124,15 @@ ${messages}`);
4540
5124
  }
4541
5125
  const reply = response;
4542
5126
  if (reply.ok === true) {
5127
+ try {
5128
+ charge(Math.max(responseJson.length * 2, utf8Length2(responseJson)));
5129
+ } catch (error) {
5130
+ try {
5131
+ context.onToolBridgeFailure?.();
5132
+ } catch {
5133
+ }
5134
+ throw error;
5135
+ }
4543
5136
  return throwOnError ? reply.value : { success: true, data: reply.value };
4544
5137
  }
4545
5138
  if (reply.ok === false && reply.error && typeof reply.error === "object") {
@@ -4626,9 +5219,996 @@ ${messages}`);
4626
5219
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
4627
5220
  }
4628
5221
  };
5222
+
5223
+ // libs/core/src/portable-enclave.ts
5224
+ import {
5225
+ JSAstValidator,
5226
+ PreScanner,
5227
+ ValidationSeverity,
5228
+ createAgentScriptPreset,
5229
+ extractLargeStrings,
5230
+ getAgentScriptGlobals,
5231
+ isWrappedInMain,
5232
+ normalizeToolNamespaces,
5233
+ transformAgentScript,
5234
+ transformConcatenation,
5235
+ transformTemplateLiterals
5236
+ } from "@enclave-vm/ast";
5237
+ import * as acorn3 from "acorn";
5238
+ import { generate } from "astring";
5239
+
5240
+ // libs/core/src/types.ts
5241
+ var SECURITY_LEVEL_CONFIGS = {
5242
+ /**
5243
+ * STRICT: Maximum security for untrusted code
5244
+ *
5245
+ * Use for:
5246
+ * - AI-generated code from external sources
5247
+ * - User-submitted scripts
5248
+ * - Untrusted third-party integrations
5249
+ *
5250
+ * Characteristics:
5251
+ * - Short timeout (5s)
5252
+ * - Low iteration limits (1000)
5253
+ * - Limited tool calls (10)
5254
+ * - Deep value sanitization
5255
+ * - Full stack trace sanitization
5256
+ */
5257
+ STRICT: {
5258
+ timeout: 5e3,
5259
+ maxIterations: 1e3,
5260
+ maxToolCalls: 10,
5261
+ maxSanitizeDepth: 5,
5262
+ maxSanitizeProperties: 50,
5263
+ sanitizeStackTraces: true,
5264
+ blockTimingAPIs: true,
5265
+ allowUnboundedLoops: false,
5266
+ unicodeSecurityCheck: true,
5267
+ allowFunctionsInGlobals: false,
5268
+ maxConsoleOutputBytes: 64 * 1024,
5269
+ // 64KB - prevent I/O flood attacks
5270
+ maxConsoleCalls: 100,
5271
+ secureProxy: {
5272
+ blockConstructor: true,
5273
+ blockPrototype: true,
5274
+ blockLegacyAccessors: true,
5275
+ proxyMaxDepth: 5,
5276
+ throwOnBlocked: true
5277
+ }
5278
+ },
5279
+ /**
5280
+ * SECURE: High security with more headroom
5281
+ *
5282
+ * Use for:
5283
+ * - AI-generated code from trusted models
5284
+ * - Internal automation scripts
5285
+ * - Controlled multi-tenant environments
5286
+ *
5287
+ * Characteristics:
5288
+ * - Moderate timeout (15s)
5289
+ * - Moderate iteration limits (5000)
5290
+ * - Moderate tool calls (50)
5291
+ * - Standard value sanitization
5292
+ * - Stack trace sanitization
5293
+ */
5294
+ SECURE: {
5295
+ timeout: 15e3,
5296
+ maxIterations: 5e3,
5297
+ maxToolCalls: 50,
5298
+ maxSanitizeDepth: 10,
5299
+ maxSanitizeProperties: 100,
5300
+ sanitizeStackTraces: true,
5301
+ blockTimingAPIs: false,
5302
+ allowUnboundedLoops: false,
5303
+ unicodeSecurityCheck: true,
5304
+ allowFunctionsInGlobals: false,
5305
+ maxConsoleOutputBytes: 256 * 1024,
5306
+ // 256KB
5307
+ maxConsoleCalls: 500,
5308
+ secureProxy: {
5309
+ blockConstructor: true,
5310
+ blockPrototype: true,
5311
+ blockLegacyAccessors: true,
5312
+ proxyMaxDepth: 10,
5313
+ throwOnBlocked: true
5314
+ }
5315
+ },
5316
+ /**
5317
+ * STANDARD: Balanced security and functionality (DEFAULT)
5318
+ *
5319
+ * Use for:
5320
+ * - Internal tools and scripts
5321
+ * - Development and testing
5322
+ * - Trusted environments
5323
+ *
5324
+ * Characteristics:
5325
+ * - Standard timeout (30s)
5326
+ * - Standard iteration limits (10000)
5327
+ * - Standard tool calls (100)
5328
+ * - Basic value sanitization
5329
+ * - Minimal stack trace sanitization
5330
+ */
5331
+ STANDARD: {
5332
+ timeout: 3e4,
5333
+ maxIterations: 1e4,
5334
+ maxToolCalls: 100,
5335
+ maxSanitizeDepth: 20,
5336
+ maxSanitizeProperties: 500,
5337
+ sanitizeStackTraces: false,
5338
+ blockTimingAPIs: false,
5339
+ allowUnboundedLoops: true,
5340
+ unicodeSecurityCheck: false,
5341
+ allowFunctionsInGlobals: false,
5342
+ maxConsoleOutputBytes: 1024 * 1024,
5343
+ // 1MB
5344
+ maxConsoleCalls: 1e3,
5345
+ secureProxy: {
5346
+ blockConstructor: true,
5347
+ blockPrototype: true,
5348
+ blockLegacyAccessors: true,
5349
+ proxyMaxDepth: 15,
5350
+ throwOnBlocked: true
5351
+ }
5352
+ },
5353
+ /**
5354
+ * PERMISSIVE: Minimal restrictions
5355
+ *
5356
+ * Use for:
5357
+ * - Local development only
5358
+ * - Debugging
5359
+ * - Performance testing
5360
+ *
5361
+ * WARNING: Not recommended for production use with untrusted code
5362
+ *
5363
+ * Characteristics:
5364
+ * - Long timeout (60s)
5365
+ * - High iteration limits (100000)
5366
+ * - High tool calls (1000)
5367
+ * - Minimal sanitization
5368
+ * - No stack trace sanitization
5369
+ * - All features enabled
5370
+ */
5371
+ PERMISSIVE: {
5372
+ timeout: 6e4,
5373
+ maxIterations: 1e5,
5374
+ maxToolCalls: 1e3,
5375
+ maxSanitizeDepth: 50,
5376
+ maxSanitizeProperties: 1e3,
5377
+ sanitizeStackTraces: false,
5378
+ blockTimingAPIs: false,
5379
+ allowUnboundedLoops: true,
5380
+ unicodeSecurityCheck: false,
5381
+ allowFunctionsInGlobals: true,
5382
+ maxConsoleOutputBytes: 10 * 1024 * 1024,
5383
+ // 10MB
5384
+ maxConsoleCalls: 1e4,
5385
+ secureProxy: {
5386
+ blockConstructor: false,
5387
+ // Allow constructor access for development/debugging
5388
+ blockPrototype: true,
5389
+ // Still block prototype for safety
5390
+ blockLegacyAccessors: true,
5391
+ proxyMaxDepth: 20,
5392
+ throwOnBlocked: false
5393
+ // Return undefined instead of throwing for development
5394
+ }
5395
+ }
5396
+ };
5397
+ var DEFAULT_DOUBLE_VM_CONFIG = {
5398
+ enabled: true,
5399
+ parentTimeoutBuffer: 1e3,
5400
+ parentValidation: {
5401
+ validateOperationNames: true,
5402
+ maxOperationsPerSecond: 100,
5403
+ blockSuspiciousSequences: true,
5404
+ rapidEnumerationThreshold: 30,
5405
+ rapidEnumerationOverrides: {},
5406
+ suspiciousPatterns: []
5407
+ // Default patterns added at runtime
5408
+ }
5409
+ };
5410
+
5411
+ // libs/core/src/enclave-options.ts
5412
+ var MAX_TIMEOUT_MS = 2147483647;
5413
+ function withoutUndefined(value) {
5414
+ const result = {};
5415
+ for (const key of Object.keys(value)) {
5416
+ const member = value[key];
5417
+ if (member !== void 0) result[key] = member;
5418
+ }
5419
+ return result;
5420
+ }
5421
+ function describe(value) {
5422
+ if (value === null) return "null";
5423
+ if (typeof value === "number") return String(value);
5424
+ if (Array.isArray(value)) return "an array";
5425
+ if (typeof value === "string") return "a string";
5426
+ return `a value of type ${typeof value}`;
5427
+ }
5428
+ function assertIntegerOption(name, value, min, max = Number.MAX_SAFE_INTEGER) {
5429
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
5430
+ const range = max === Number.MAX_SAFE_INTEGER ? `an integer of at least ${min}` : `an integer from ${min} to ${max}`;
5431
+ throw new TypeError(`${name} must be ${range}, got ${describe(value)}`);
5432
+ }
5433
+ }
5434
+ function assertFiniteNumberOption(name, value, min) {
5435
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min) {
5436
+ throw new TypeError(`${name} must be a finite number of at least ${min}, got ${describe(value)}`);
5437
+ }
5438
+ }
5439
+ function assertBooleanOption(name, value) {
5440
+ if (typeof value !== "boolean") {
5441
+ throw new TypeError(`${name} must be true or false, got ${describe(value)}`);
5442
+ }
5443
+ }
5444
+ function assertSecurityLevel(value) {
5445
+ if (typeof value !== "string" || !Object.hasOwn(SECURITY_LEVEL_CONFIGS, value)) {
5446
+ throw new TypeError(
5447
+ `securityLevel must be one of ${Object.keys(SECURITY_LEVEL_CONFIGS).join(", ")}, got ${typeof value === "string" ? JSON.stringify(value.slice(0, 40)) : describe(value)}`
5448
+ );
5449
+ }
5450
+ }
5451
+ function isPlainRecord(value) {
5452
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5453
+ }
5454
+ function assertRecordOption(name, value) {
5455
+ if (!isPlainRecord(value)) {
5456
+ throw new TypeError(`${name} must be an object, got ${describe(value)}`);
5457
+ }
5458
+ }
5459
+ function assertKnownKeys(name, value, known) {
5460
+ for (const key of Object.keys(value)) {
5461
+ if (!known.includes(key)) {
5462
+ throw new TypeError(`${name} has no option ${JSON.stringify(key.slice(0, 40))}`);
5463
+ }
5464
+ }
5465
+ }
5466
+ function isOneOf(values, value) {
5467
+ return typeof value === "string" && values.includes(value);
5468
+ }
5469
+ var PRE_SCAN_PRESETS = ["agentscript", "strict", "secure", "standard", "permissive"];
5470
+ var PRE_SCAN_INTEGERS = [
5471
+ "maxInputSize",
5472
+ "maxLineLength",
5473
+ "maxLines",
5474
+ "maxNestingDepth",
5475
+ "maxConsecutiveOperators",
5476
+ "maxRegexLength",
5477
+ "maxRegexCount",
5478
+ "maxStringLength",
5479
+ "maxTotalStringContent"
5480
+ ];
5481
+ var PRE_SCAN_BOOLEANS = ["unicodePreCheck", "blockBidiPatterns", "blockInvisibleChars"];
5482
+ var PRE_SCAN_REGEX_MODES = ["allow", "analyze", "block"];
5483
+ var PRE_SCAN_REGEX_ANALYSIS_LEVELS = ["catastrophic", "polynomial"];
5484
+ var INTEGER_OPTIONS = [
5485
+ // What a timer can hold (see MAX_TIMEOUT_MS)
5486
+ ["timeout", 1, MAX_TIMEOUT_MS],
5487
+ ["maxIterations", 1],
5488
+ ["maxToolCalls", 0],
5489
+ // 0: no memory limit
5490
+ ["memoryLimit", 0],
5491
+ ["maxSanitizeDepth", 1],
5492
+ ["maxSanitizeProperties", 1],
5493
+ ["maxConsoleOutputBytes", 0],
5494
+ ["maxConsoleCalls", 0]
5495
+ ];
5496
+ var BOOLEAN_OPTIONS = [
5497
+ "validate",
5498
+ "transform",
5499
+ "sanitizeStackTraces",
5500
+ "allowFunctionsInGlobals",
5501
+ "allowBuiltins"
5502
+ ];
5503
+ var SECURE_PROXY_BOOLEANS = ["blockConstructor", "blockPrototype", "blockLegacyAccessors", "throwOnBlocked"];
5504
+ var PARENT_VALIDATION_BOOLEANS = ["validateOperationNames", "blockSuspiciousSequences"];
5505
+ function normalizeEnclaveOptions(options) {
5506
+ if (!isPlainRecord(options)) {
5507
+ throw new TypeError(`Enclave options must be an object, got ${describe(options)}`);
5508
+ }
5509
+ const result = withoutUndefined(options);
5510
+ if (result.securityLevel !== void 0) assertSecurityLevel(result.securityLevel);
5511
+ for (const [name, min, max] of INTEGER_OPTIONS) {
5512
+ if (result[name] !== void 0) assertIntegerOption(name, result[name], min, max);
5513
+ }
5514
+ for (const name of BOOLEAN_OPTIONS) {
5515
+ if (result[name] !== void 0) assertBooleanOption(name, result[name]);
5516
+ }
5517
+ if (result.secureProxyConfig !== void 0) {
5518
+ assertRecordOption("secureProxyConfig", result.secureProxyConfig);
5519
+ const proxy = withoutUndefined(result.secureProxyConfig);
5520
+ for (const name of SECURE_PROXY_BOOLEANS) {
5521
+ if (proxy[name] !== void 0) assertBooleanOption(`secureProxyConfig.${name}`, proxy[name]);
5522
+ }
5523
+ if (proxy["proxyMaxDepth"] !== void 0) {
5524
+ assertIntegerOption("secureProxyConfig.proxyMaxDepth", proxy["proxyMaxDepth"], 1);
5525
+ }
5526
+ result.secureProxyConfig = proxy;
5527
+ }
5528
+ if (result.toolBridge !== void 0) {
5529
+ assertRecordOption("toolBridge", result.toolBridge);
5530
+ const bridge = withoutUndefined(result.toolBridge);
5531
+ if (bridge["acknowledgeInsecureDirect"] !== void 0) {
5532
+ assertBooleanOption("toolBridge.acknowledgeInsecureDirect", bridge["acknowledgeInsecureDirect"]);
5533
+ }
5534
+ result.toolBridge = bridge;
5535
+ }
5536
+ if (result.preScan !== void 0) {
5537
+ assertRecordOption("preScan", result.preScan);
5538
+ const preScan = withoutUndefined(result.preScan);
5539
+ assertKnownKeys("preScan", preScan, ["preset", "config"]);
5540
+ if (preScan["preset"] !== void 0 && !isOneOf(PRE_SCAN_PRESETS, preScan["preset"])) {
5541
+ throw new TypeError(
5542
+ `preScan.preset must be one of ${PRE_SCAN_PRESETS.join(", ")}, got ${describe(preScan["preset"])}`
5543
+ );
5544
+ }
5545
+ if (preScan["config"] !== void 0) {
5546
+ assertRecordOption("preScan.config", preScan["config"]);
5547
+ const config = withoutUndefined(preScan["config"]);
5548
+ assertKnownKeys("preScan.config", config, [
5549
+ ...PRE_SCAN_INTEGERS,
5550
+ ...PRE_SCAN_BOOLEANS,
5551
+ "regexMode",
5552
+ "regexAnalysisLevel"
5553
+ ]);
5554
+ for (const name of PRE_SCAN_INTEGERS) {
5555
+ if (config[name] !== void 0) assertIntegerOption(`preScan.config.${name}`, config[name], 0);
5556
+ }
5557
+ for (const name of PRE_SCAN_BOOLEANS) {
5558
+ if (config[name] !== void 0) assertBooleanOption(`preScan.config.${name}`, config[name]);
5559
+ }
5560
+ if (config["regexMode"] !== void 0 && !isOneOf(PRE_SCAN_REGEX_MODES, config["regexMode"])) {
5561
+ throw new TypeError(
5562
+ `preScan.config.regexMode must be one of ${PRE_SCAN_REGEX_MODES.join(", ")}, got ${describe(config["regexMode"])}`
5563
+ );
5564
+ }
5565
+ if (config["regexAnalysisLevel"] !== void 0 && !isOneOf(PRE_SCAN_REGEX_ANALYSIS_LEVELS, config["regexAnalysisLevel"])) {
5566
+ throw new TypeError(
5567
+ `preScan.config.regexAnalysisLevel must be one of ${PRE_SCAN_REGEX_ANALYSIS_LEVELS.join(", ")}, got ${describe(config["regexAnalysisLevel"])}`
5568
+ );
5569
+ }
5570
+ preScan["config"] = config;
5571
+ }
5572
+ result.preScan = preScan;
5573
+ }
5574
+ if (result.doubleVm !== void 0) {
5575
+ assertRecordOption("doubleVm", result.doubleVm);
5576
+ const doubleVm = withoutUndefined(result.doubleVm);
5577
+ if (doubleVm["enabled"] !== void 0) assertBooleanOption("doubleVm.enabled", doubleVm["enabled"]);
5578
+ if (doubleVm["parentTimeoutBuffer"] !== void 0) {
5579
+ assertIntegerOption("doubleVm.parentTimeoutBuffer", doubleVm["parentTimeoutBuffer"], 0, MAX_TIMEOUT_MS);
5580
+ }
5581
+ if (doubleVm["parentValidation"] !== void 0) {
5582
+ assertRecordOption("doubleVm.parentValidation", doubleVm["parentValidation"]);
5583
+ const validation = withoutUndefined(doubleVm["parentValidation"]);
5584
+ for (const name of PARENT_VALIDATION_BOOLEANS) {
5585
+ if (validation[name] !== void 0) {
5586
+ assertBooleanOption(`doubleVm.parentValidation.${name}`, validation[name]);
5587
+ }
5588
+ }
5589
+ if (validation["maxOperationsPerSecond"] !== void 0) {
5590
+ assertFiniteNumberOption(
5591
+ "doubleVm.parentValidation.maxOperationsPerSecond",
5592
+ validation["maxOperationsPerSecond"],
5593
+ 1
5594
+ );
5595
+ }
5596
+ if (validation["rapidEnumerationThreshold"] !== void 0) {
5597
+ assertIntegerOption(
5598
+ "doubleVm.parentValidation.rapidEnumerationThreshold",
5599
+ validation["rapidEnumerationThreshold"],
5600
+ 1
5601
+ );
5602
+ }
5603
+ if (validation["rapidEnumerationOverrides"] !== void 0) {
5604
+ assertRecordOption(
5605
+ "doubleVm.parentValidation.rapidEnumerationOverrides",
5606
+ validation["rapidEnumerationOverrides"]
5607
+ );
5608
+ for (const [operation, threshold] of Object.entries(validation["rapidEnumerationOverrides"])) {
5609
+ assertIntegerOption(
5610
+ `doubleVm.parentValidation.rapidEnumerationOverrides[${JSON.stringify(operation.slice(0, 40))}]`,
5611
+ threshold,
5612
+ 1
5613
+ );
5614
+ }
5615
+ }
5616
+ doubleVm["parentValidation"] = validation;
5617
+ }
5618
+ result.doubleVm = doubleVm;
5619
+ }
5620
+ return result;
5621
+ }
5622
+
5623
+ // libs/core/src/portable-globals.ts
5624
+ var MAX_GLOBAL_DEPTH = 10;
5625
+ var MAX_GLOBAL_PROPERTIES = 1e4;
5626
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
5627
+ var BLOCKED_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
5628
+ function copyPortableGlobals(globals, allowFunctions, maxBytes) {
5629
+ const result = /* @__PURE__ */ Object.create(null);
5630
+ if (globals === void 0) return result;
5631
+ if (globals === null || typeof globals !== "object" || Array.isArray(globals)) {
5632
+ throw new TypeError("globals must be a record");
5633
+ }
5634
+ let properties = 0;
5635
+ let bytes = 0;
5636
+ const active = /* @__PURE__ */ new Set();
5637
+ const charge = (value) => {
5638
+ bytes += value.length * 6 + 8;
5639
+ if (bytes > maxBytes) throw new TypeError("globals exceed the portable bridge size limit");
5640
+ };
5641
+ const copy = (value, depth) => {
5642
+ if (depth > MAX_GLOBAL_DEPTH) throw new TypeError("globals exceed the portable depth limit");
5643
+ if (value === null || typeof value === "boolean") return value;
5644
+ if (typeof value === "string") {
5645
+ charge(value);
5646
+ return value;
5647
+ }
5648
+ if (typeof value === "number" && Number.isFinite(value)) return value;
5649
+ if (typeof value !== "object") throw new TypeError("portable globals must contain JSON data only");
5650
+ if (active.has(value)) throw new TypeError("portable globals cannot contain cycles");
5651
+ const array = Array.isArray(value);
5652
+ if (array && value.length > MAX_GLOBAL_PROPERTIES) {
5653
+ throw new TypeError("portable globals exceed the array length limit");
5654
+ }
5655
+ const prototype = Object.getPrototypeOf(value);
5656
+ if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
5657
+ throw new TypeError("portable globals must contain plain records or arrays");
5658
+ }
5659
+ active.add(value);
5660
+ try {
5661
+ const destination = array ? [] : /* @__PURE__ */ Object.create(null);
5662
+ const keys = Reflect.ownKeys(value);
5663
+ if (array && keys.length - 1 !== value.length) {
5664
+ throw new TypeError("portable globals cannot contain sparse arrays");
5665
+ }
5666
+ for (const key of keys) {
5667
+ if (typeof key !== "string") throw new TypeError("portable globals cannot contain symbol properties");
5668
+ if (array && key === "length") continue;
5669
+ if (BLOCKED_KEYS2.has(key)) throw new TypeError("portable globals contain a blocked property");
5670
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
5671
+ if (!descriptor || !Object.hasOwn(descriptor, "value")) {
5672
+ throw new TypeError("portable globals cannot contain accessors");
5673
+ }
5674
+ if (++properties > MAX_GLOBAL_PROPERTIES) throw new TypeError("globals exceed the portable property limit");
5675
+ charge(key);
5676
+ if (array) {
5677
+ const index = Number(key);
5678
+ if (!Number.isSafeInteger(index) || index < 0 || index >= value.length || String(index) !== key) {
5679
+ throw new TypeError("portable global arrays cannot contain named properties");
5680
+ }
5681
+ destination[index] = copy(descriptor.value, depth + 1);
5682
+ } else {
5683
+ destination[key] = copy(descriptor.value, depth + 1);
5684
+ }
5685
+ }
5686
+ return destination;
5687
+ } finally {
5688
+ active.delete(value);
5689
+ }
5690
+ };
5691
+ for (const key of Reflect.ownKeys(globals)) {
5692
+ if (typeof key !== "string" || !IDENTIFIER.test(key) || BLOCKED_KEYS2.has(key) || key.startsWith("__")) {
5693
+ throw new TypeError("portable globals contain an invalid name");
5694
+ }
5695
+ const descriptor = Object.getOwnPropertyDescriptor(globals, key);
5696
+ if (!descriptor || !Object.hasOwn(descriptor, "value")) {
5697
+ throw new TypeError("portable globals cannot contain accessors");
5698
+ }
5699
+ if (++properties > MAX_GLOBAL_PROPERTIES) throw new TypeError("globals exceed the portable property limit");
5700
+ charge(key);
5701
+ if (typeof descriptor.value === "function") {
5702
+ if (!allowFunctions) throw new TypeError("portable host functions require allowFunctionsInGlobals");
5703
+ result[key] = descriptor.value;
5704
+ } else {
5705
+ result[key] = copy(descriptor.value, 0);
5706
+ }
5707
+ }
5708
+ return result;
5709
+ }
5710
+
5711
+ // libs/core/src/double-vm/suspicious-patterns.ts
5712
+ var EXFIL_LIST_SEND = {
5713
+ id: "EXFIL_LIST_SEND",
5714
+ description: "List/query followed by send/export (potential exfiltration)",
5715
+ detect: (operationName, _args, history) => {
5716
+ const recentQueries = history.filter(
5717
+ (h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 5e3
5718
+ );
5719
+ const isSendOperation = /send|export|post|write|upload|publish|emit|transmit|forward/i.test(operationName);
5720
+ return recentQueries.length > 0 && isSendOperation;
5721
+ }
5722
+ };
5723
+ var RAPID_ENUMERATION = {
5724
+ id: "RAPID_ENUMERATION",
5725
+ description: "Rapid enumeration of resources (same operation called too many times in 5s)",
5726
+ detect: (operationName, _args, history) => {
5727
+ const now = Date.now();
5728
+ const recentSameOperation = history.filter((h) => h.operationName === operationName && now - h.timestamp < 5e3);
5729
+ let threshold = 30;
5730
+ try {
5731
+ const localConfig = typeof validationConfig !== "undefined" ? validationConfig : null;
5732
+ if (localConfig) {
5733
+ const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
5734
+ const overrides = localConfig.rapidEnumerationOverrides ?? {};
5735
+ const override = Object.prototype.hasOwnProperty.call(overrides, operationName) ? overrides[operationName] : void 0;
5736
+ threshold = typeof override === "number" ? override : defaultThreshold;
5737
+ }
5738
+ } catch {
5739
+ threshold = 30;
5740
+ }
5741
+ return recentSameOperation.length > threshold;
5742
+ }
5743
+ };
5744
+ var CREDENTIAL_EXFIL = {
5745
+ id: "CREDENTIAL_EXFIL",
5746
+ description: "Credential access followed by external operation",
5747
+ detect: (operationName, _args, history) => {
5748
+ const recentCredentialAccess = history.filter(
5749
+ (h) => /secret|credential|password|token|key|auth|api[_-]?key/i.test(h.operationName) && Date.now() - h.timestamp < 1e4
5750
+ );
5751
+ const isExternalOperation = /http|api|external|webhook|slack|email|sms|notification/i.test(operationName);
5752
+ return recentCredentialAccess.length > 0 && isExternalOperation;
5753
+ }
5754
+ };
5755
+ var BULK_OPERATION = {
5756
+ id: "BULK_OPERATION",
5757
+ description: "Bulk/batch operation detected",
5758
+ detect: (operationName, args, _history) => {
5759
+ const isBulkOperation = /\b(bulk|batch|mass|dump)\b|export[_-]all\b/i.test(operationName);
5760
+ if (typeof args === "object" && args !== null) {
5761
+ try {
5762
+ const argStr = JSON.stringify(args).toLowerCase();
5763
+ const firstLimit = argStr.indexOf("limit");
5764
+ const hasBulkArgs = firstLimit >= 0 && /[0-9]{4}/.test(argStr.slice(firstLimit + 5)) || argStr.indexOf('"*"') >= 0 || argStr.indexOf("nolimit") >= 0 || argStr.indexOf("no_limit") >= 0 || argStr.indexOf("no-limit") >= 0;
5765
+ if (hasBulkArgs) return true;
5766
+ } catch {
5767
+ }
5768
+ }
5769
+ return isBulkOperation;
5770
+ }
5771
+ };
5772
+ var DELETE_AFTER_ACCESS = {
5773
+ id: "DELETE_AFTER_ACCESS",
5774
+ description: "Delete operation after data access (potential cover-up)",
5775
+ detect: (operationName, _args, history) => {
5776
+ const isDeleteOperation = /delete|remove|destroy|purge|clear|wipe|erase/i.test(operationName);
5777
+ if (!isDeleteOperation) return false;
5778
+ const recentDataAccess = history.filter(
5779
+ (h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 3e4
5780
+ );
5781
+ return recentDataAccess.length > 0;
5782
+ }
5783
+ };
5784
+ var DEFAULT_SUSPICIOUS_PATTERNS = [
5785
+ EXFIL_LIST_SEND,
5786
+ RAPID_ENUMERATION,
5787
+ CREDENTIAL_EXFIL,
5788
+ BULK_OPERATION,
5789
+ DELETE_AFTER_ACCESS
5790
+ ];
5791
+
5792
+ // libs/core/src/dynamic-import.ts
5793
+ import * as acorn2 from "acorn";
5794
+ import * as walk from "acorn-walk";
5795
+ var DYNAMIC_IMPORT_MESSAGE = "Dynamic import() is not available in the sandbox";
5796
+ function refuseDynamicImport(code) {
5797
+ if (typeof code !== "string" || !code.includes("import")) {
5798
+ return void 0;
5799
+ }
5800
+ let ast;
5801
+ try {
5802
+ ast = acorn2.parse(code, {
5803
+ ecmaVersion: "latest",
5804
+ sourceType: "script",
5805
+ allowHashBang: true,
5806
+ allowReturnOutsideFunction: true,
5807
+ allowAwaitOutsideFunction: true
5808
+ });
5809
+ } catch {
5810
+ return `${DYNAMIC_IMPORT_MESSAGE} (the script contains the word "import" and could not be parsed to rule it out)`;
5811
+ }
5812
+ let found = false;
5813
+ try {
5814
+ walk.full(ast, (node) => {
5815
+ if (node.type === "ImportExpression") found = true;
5816
+ if (node.type === "MetaProperty" && node.meta?.name === "import") {
5817
+ found = true;
5818
+ }
5819
+ });
5820
+ } catch {
5821
+ return DYNAMIC_IMPORT_MESSAGE;
5822
+ }
5823
+ return found ? DYNAMIC_IMPORT_MESSAGE : void 0;
5824
+ }
5825
+
5826
+ // libs/core/src/portable-enclave.ts
5827
+ var MAX_SCRIPT_LENGTH = 5 * 1024 * 1024;
5828
+ var MAX_PORTABLE_ALLOCATION_BYTES = 64 * 1024 * 1024;
5829
+ var MAX_PORTABLE_STEPS = 2e7;
5830
+ var MAX_PORTABLE_PENDING_CALLS = 4096;
5831
+ var MAX_PORTABLE_CALL_DEPTH = 1024;
5832
+ var DEFAULT_BRIDGE_BYTES = 5 * 1024 * 1024;
5833
+ function boundedInteger(name, value, max) {
5834
+ if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max)) {
5835
+ throw new TypeError(`${name} must be an integer from 1 to ${max}`);
5836
+ }
5837
+ }
5838
+ function referenceConfig(level, sidecar) {
5839
+ if (!sidecar?.enabled) return void 0;
5840
+ const base = REFERENCE_CONFIGS[level];
5841
+ return {
5842
+ maxTotalSize: sidecar.maxTotalSize ?? base.maxTotalSize,
5843
+ maxReferenceSize: sidecar.maxReferenceSize ?? base.maxReferenceSize,
5844
+ extractionThreshold: sidecar.extractionThreshold ?? base.extractionThreshold,
5845
+ maxResolvedSize: sidecar.maxResolvedSize ?? base.maxResolvedSize,
5846
+ maxTotalResolvedSize: sidecar.maxTotalResolvedSize ?? base.maxTotalResolvedSize,
5847
+ allowComposites: sidecar.allowComposites ?? base.allowComposites,
5848
+ maxReferenceCount: sidecar.maxReferenceCount ?? base.maxReferenceCount,
5849
+ maxResolutionDepth: base.maxResolutionDepth
5850
+ };
5851
+ }
5852
+ function validateReferenceConfig(config) {
5853
+ if (!config) return;
5854
+ for (const key of [
5855
+ "maxTotalSize",
5856
+ "maxReferenceSize",
5857
+ "extractionThreshold",
5858
+ "maxResolvedSize",
5859
+ "maxTotalResolvedSize",
5860
+ "maxReferenceCount",
5861
+ "maxResolutionDepth"
5862
+ ]) {
5863
+ const value = config[key];
5864
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0)) {
5865
+ throw new TypeError(`sidecar.${key} must be a positive finite integer`);
5866
+ }
5867
+ }
5868
+ if (config.maxReferenceSize > config.maxTotalSize || config.extractionThreshold > config.maxReferenceSize) {
5869
+ throw new TypeError("sidecar size limits must be ordered: threshold <= reference <= total");
5870
+ }
5871
+ }
5872
+ var PortableOperationPolicy = class {
5873
+ constructor(config) {
5874
+ this.config = config;
5875
+ }
5876
+ history = [];
5877
+ globalCallTimes = [];
5878
+ rate(now) {
5879
+ while (this.history.length && now - this.history[0].timestamp > 6e4) this.history.shift();
5880
+ while (this.globalCallTimes.length && now - this.globalCallTimes[0] > 2e3) this.globalCallTimes.shift();
5881
+ const recentTools = this.history.filter((entry) => now - entry.timestamp < 1e3).length;
5882
+ const recentGlobals = this.globalCallTimes.filter((at) => now - at < 1e3).length;
5883
+ if (recentTools + recentGlobals >= this.config.maxOperationsPerSecond) {
5884
+ throw new Error(`Operation rate limit exceeded (${this.config.maxOperationsPerSecond} operations/second)`);
5885
+ }
5886
+ }
5887
+ globalCall() {
5888
+ const now = Date.now();
5889
+ this.rate(now);
5890
+ this.globalCallTimes.push(now);
5891
+ }
5892
+ toolCall(name, args) {
5893
+ const now = Date.now();
5894
+ this.rate(now);
5895
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("Operation name must be a non-empty string");
5896
+ if (this.config.validateOperationNames) {
5897
+ const allowed = this.config.allowedOperationPattern;
5898
+ if (allowed) {
5899
+ allowed.lastIndex = 0;
5900
+ if (!allowed.test(name)) throw new Error(`Operation "${name}" does not match allowed pattern`);
5901
+ }
5902
+ for (const blocked of this.config.blockedOperationPatterns ?? []) {
5903
+ blocked.lastIndex = 0;
5904
+ if (blocked.test(name)) throw new Error(`Operation "${name}" matches blocked pattern`);
5905
+ }
5906
+ }
5907
+ if (this.config.blockSuspiciousSequences) {
5908
+ const override = Object.hasOwn(this.config.rapidEnumerationOverrides, name) ? this.config.rapidEnumerationOverrides[name] : void 0;
5909
+ const threshold = override ?? this.config.rapidEnumerationThreshold;
5910
+ const recentSame = this.history.filter((entry) => entry.operationName === name && now - entry.timestamp < 5e3);
5911
+ if (recentSame.length >= threshold) {
5912
+ throw new Error("Suspicious pattern detected: Rapid enumeration of resources [RAPID_ENUMERATION]");
5913
+ }
5914
+ for (const pattern of DEFAULT_SUSPICIOUS_PATTERNS) {
5915
+ if (pattern.id === "RAPID_ENUMERATION") continue;
5916
+ let detected = false;
5917
+ try {
5918
+ detected = pattern.detect(name, args, this.history);
5919
+ } catch {
5920
+ }
5921
+ if (detected) throw new Error(`Suspicious pattern detected: ${pattern.description} [${pattern.id}]`);
5922
+ }
5923
+ }
5924
+ this.history.push({ operationName: name, timestamp: now, argKeys: Object.keys(args) });
5925
+ }
5926
+ };
5927
+ var PortableEnclave = class {
5928
+ options;
5929
+ config;
5930
+ preScanner;
5931
+ validator;
5932
+ adapter;
5933
+ namespaces;
5934
+ references;
5935
+ policyConfig;
5936
+ customNames;
5937
+ disposed = false;
5938
+ constructor(rawOptions = {}) {
5939
+ const { interpreter, ...rawEnclaveOptions } = rawOptions;
5940
+ const options = normalizeEnclaveOptions(rawEnclaveOptions);
5941
+ const level = options.securityLevel ?? "STANDARD";
5942
+ if (level === "PERMISSIVE") throw new TypeError("Portable AgentScript requires STANDARD, SECURE or STRICT");
5943
+ if (options.preset !== void 0 && options.preset !== "agentscript") {
5944
+ throw new TypeError("PortableEnclave supports the AgentScript preset only");
5945
+ }
5946
+ if (options.validate === false || options.transform === false) {
5947
+ throw new TypeError("PortableEnclave requires validation, transformation and pre-scan");
5948
+ }
5949
+ if (options.preScan?.preset !== void 0 && options.preScan.preset !== "agentscript") {
5950
+ throw new TypeError("PortableEnclave requires the AgentScript pre-scan preset");
5951
+ }
5952
+ if (options.preScan?.config !== void 0) {
5953
+ throw new TypeError("PortableEnclave does not allow pre-scan overrides");
5954
+ }
5955
+ if (options.toolBridge?.mode === "direct") throw new TypeError("PortableEnclave requires the string tool bridge");
5956
+ if (options.toolBridge?.acknowledgeInsecureDirect === true) {
5957
+ throw new TypeError("PortableEnclave does not support direct bridge acknowledgement");
5958
+ }
5959
+ if (options.adapter || options.sandboxAdapter || options.workerPoolConfig || options.scoringGate) {
5960
+ throw new TypeError("PortableEnclave does not support VM adapters or scoring gates");
5961
+ }
5962
+ if (options.allowBuiltins === true || options.toolCallGraceMs !== void 0) {
5963
+ throw new TypeError("PortableEnclave does not support VM builtin or tool grace overrides");
5964
+ }
5965
+ if (options.secureProxyConfig || options.realmGlobals === "security-level") {
5966
+ throw new TypeError("PortableEnclave does not support VM realm proxy overrides");
5967
+ }
5968
+ if (options.doubleVm?.enabled === false || options.doubleVm?.parentTimeoutBuffer !== void 0 || options.doubleVm?.parentValidation?.suspiciousPatterns?.length) {
5969
+ throw new TypeError("PortableEnclave cannot disable or replace its tool policy");
5970
+ }
5971
+ boundedInteger("interpreter.maxSteps", interpreter?.maxSteps, MAX_PORTABLE_STEPS);
5972
+ boundedInteger("interpreter.maxCallDepth", interpreter?.maxCallDepth, MAX_PORTABLE_CALL_DEPTH);
5973
+ boundedInteger("interpreter.maxPendingCalls", interpreter?.maxPendingCalls, MAX_PORTABLE_PENDING_CALLS);
5974
+ boundedInteger("interpreter.maxAllocationBytes", interpreter?.maxAllocationBytes, MAX_PORTABLE_ALLOCATION_BYTES);
5975
+ const memoryLimit = options.memoryLimit ?? 1024 * 1024;
5976
+ boundedInteger("memoryLimit", memoryLimit, MAX_PORTABLE_ALLOCATION_BYTES);
5977
+ const maxPayloadBytes = options.toolBridge?.maxPayloadBytes ?? DEFAULT_BRIDGE_BYTES;
5978
+ boundedInteger("toolBridge.maxPayloadBytes", maxPayloadBytes, MAX_PORTABLE_ALLOCATION_BYTES);
5979
+ const security = SECURITY_LEVEL_CONFIGS[level];
5980
+ const maxToolCalls = options.maxToolCalls ?? security.maxToolCalls;
5981
+ if (maxToolCalls > 1e5) throw new TypeError("maxToolCalls cannot exceed 100000 in PortableEnclave");
5982
+ if ((options.maxIterations ?? security.maxIterations) > MAX_PORTABLE_STEPS) {
5983
+ throw new TypeError(`maxIterations cannot exceed ${MAX_PORTABLE_STEPS} in PortableEnclave`);
5984
+ }
5985
+ if ((options.maxSanitizeDepth ?? security.maxSanitizeDepth) > 100) {
5986
+ throw new TypeError("maxSanitizeDepth cannot exceed 100 in PortableEnclave");
5987
+ }
5988
+ if ((options.maxSanitizeProperties ?? security.maxSanitizeProperties) > 2e4) {
5989
+ throw new TypeError("maxSanitizeProperties cannot exceed 20000 in PortableEnclave");
5990
+ }
5991
+ const maxGlobalFunctionCalls = options.maxGlobalFunctionCalls ?? Math.max(10, maxToolCalls * 10);
5992
+ boundedInteger("maxGlobalFunctionCalls", maxGlobalFunctionCalls, 1e6);
5993
+ options.globals = copyPortableGlobals(options.globals, options.allowFunctionsInGlobals === true, maxPayloadBytes);
5994
+ const standardNames = /* @__PURE__ */ new Set([...Object.keys(createSafeGlobals().globals), "callTool", "parallel", "console"]);
5995
+ for (const name of Object.keys(options.globals)) {
5996
+ if (standardNames.has(name)) throw new TypeError(`PortableEnclave cannot replace standard global ${name}`);
5997
+ }
5998
+ this.namespaces = normalizeToolNamespaces(options.toolNamespaces, {
5999
+ reservedNames: Object.keys(options.globals ?? {})
6000
+ });
6001
+ this.customNames = [...Object.keys(options.globals ?? {}), ...this.namespaces.map((entry) => entry.name)];
6002
+ const allowed = [
6003
+ ...getAgentScriptGlobals(level),
6004
+ "parallel",
6005
+ "__safe_parallel",
6006
+ "__safe_concat",
6007
+ "__safe_template",
6008
+ ...options.consoleHandler ? ["console", "__safe_console"] : [],
6009
+ ...this.customNames.flatMap((name) => [name, `__safe_${name}`])
6010
+ ];
6011
+ const hostObjects = [
6012
+ ...Object.keys(options.globals ?? {}).filter((name) => typeof options.globals?.[name] !== "string"),
6013
+ ...this.namespaces.map((entry) => entry.name)
6014
+ ];
6015
+ this.preScanner = new PreScanner({
6016
+ preset: options.preScan?.preset ?? "agentscript",
6017
+ config: options.preScan?.config
6018
+ });
6019
+ this.validator = new JSAstValidator(
6020
+ createAgentScriptPreset({
6021
+ securityLevel: level,
6022
+ allowedGlobals: allowed,
6023
+ hostObjectGlobals: hostObjects,
6024
+ allowDynamicArrayFill: true
6025
+ })
6026
+ );
6027
+ this.references = referenceConfig(level, options.sidecar);
6028
+ validateReferenceConfig(this.references);
6029
+ this.policyConfig = {
6030
+ ...DEFAULT_DOUBLE_VM_CONFIG.parentValidation,
6031
+ ...options.doubleVm?.parentValidation,
6032
+ rapidEnumerationOverrides: { ...options.doubleVm?.parentValidation?.rapidEnumerationOverrides },
6033
+ blockedOperationPatterns: [...options.doubleVm?.parentValidation?.blockedOperationPatterns ?? []],
6034
+ suspiciousPatterns: []
6035
+ };
6036
+ this.config = {
6037
+ timeout: options.timeout ?? security.timeout,
6038
+ maxIterations: options.maxIterations ?? security.maxIterations,
6039
+ maxToolCalls,
6040
+ memoryLimit,
6041
+ maxSanitizeDepth: options.maxSanitizeDepth ?? security.maxSanitizeDepth,
6042
+ maxSanitizeProperties: options.maxSanitizeProperties ?? security.maxSanitizeProperties,
6043
+ maxConsoleCalls: options.maxConsoleCalls ?? security.maxConsoleCalls,
6044
+ maxConsoleOutputBytes: options.maxConsoleOutputBytes ?? security.maxConsoleOutputBytes,
6045
+ sanitizeStackTraces: options.sanitizeStackTraces ?? true,
6046
+ maxGlobalFunctionCalls,
6047
+ toolBridge: { mode: "string", maxPayloadBytes },
6048
+ globals: options.globals ?? {},
6049
+ toolHandler: options.toolHandler
6050
+ };
6051
+ this.adapter = new InterpreterAdapter({
6052
+ maxSteps: interpreter?.maxSteps,
6053
+ maxCallDepth: interpreter?.maxCallDepth,
6054
+ maxPendingCalls: interpreter?.maxPendingCalls,
6055
+ maxAllocationBytes: interpreter?.maxAllocationBytes
6056
+ });
6057
+ this.options = options;
6058
+ }
6059
+ async run(code, toolHandler, runOptions = {}) {
6060
+ if (this.disposed) throw new Error("PortableEnclave has been disposed");
6061
+ boundedInteger("maxToolResultBytes", runOptions.maxToolResultBytes, MAX_PORTABLE_ALLOCATION_BYTES);
6062
+ const startTime = Date.now();
6063
+ const stats = { duration: 0, startTime, endTime: startTime, toolCallCount: 0, iterationCount: 0 };
6064
+ const failure = (name, message, code2, issues) => ({
6065
+ success: false,
6066
+ error: { name, message, code: code2, ...issues ? { data: { issues } } : {} },
6067
+ stats: { ...stats, duration: Date.now() - startTime, endTime: Date.now() }
6068
+ });
6069
+ if (typeof code !== "string" || code.length > MAX_SCRIPT_LENGTH) {
6070
+ return failure("ValidationError", "The script must be a string of at most 5 MiB", "VALIDATION_ERROR");
6071
+ }
6072
+ if (code.length > 0) {
6073
+ const scanned = this.preScanner.scan(code);
6074
+ if (!scanned.success) {
6075
+ const issues = scanned.issues.map((issue) => ({
6076
+ code: issue.code,
6077
+ severity: issue.severity === "error" ? ValidationSeverity.ERROR : issue.severity === "warning" ? ValidationSeverity.WARNING : ValidationSeverity.INFO,
6078
+ message: issue.message,
6079
+ location: issue.line === void 0 ? void 0 : { line: issue.line, column: issue.column ?? 0 },
6080
+ data: issue.data
6081
+ }));
6082
+ return failure("ValidationError", "AgentScript pre-scan failed", "VALIDATION_ERROR", issues);
6083
+ }
6084
+ }
6085
+ let transformed;
6086
+ try {
6087
+ transformed = transformAgentScript(code, {
6088
+ wrapInMain: !isWrappedInMain(code),
6089
+ transformCallTool: true,
6090
+ transformLoops: true,
6091
+ maxIterations: this.config.maxIterations,
6092
+ additionalIdentifiers: this.customNames
6093
+ });
6094
+ } catch (error) {
6095
+ const message = error?.message;
6096
+ return failure(
6097
+ "ValidationError",
6098
+ typeof message === "string" ? message.slice(0, 2048) : "AgentScript parse failed",
6099
+ "VALIDATION_ERROR"
6100
+ );
6101
+ }
6102
+ const validation = await this.validator.validate(transformed, { preScan: { enabled: false } });
6103
+ if (!validation.valid) {
6104
+ return failure("ValidationError", "AgentScript validation failed", "VALIDATION_ERROR", validation.issues);
6105
+ }
6106
+ if (refuseDynamicImport(transformed)) {
6107
+ return failure("SecurityError", "Dynamic imports are unavailable", "SECURITY_VIOLATION");
6108
+ }
6109
+ const sidecar = this.references ? new ReferenceSidecar(this.references) : void 0;
6110
+ try {
6111
+ if (sidecar && this.references) {
6112
+ const ast = acorn3.parse(transformed, { ecmaVersion: "latest", sourceType: "script" });
6113
+ extractLargeStrings(ast, {
6114
+ threshold: this.references.extractionThreshold,
6115
+ onExtract: (value) => sidecar.store(value, "extraction")
6116
+ });
6117
+ transformConcatenation(ast, { arraySpread: false });
6118
+ transformTemplateLiterals(ast);
6119
+ transformed = generate(ast);
6120
+ }
6121
+ const policy = new PortableOperationPolicy(this.policyConfig);
6122
+ let closed = false;
6123
+ const deadline = Date.now() + this.config.timeout;
6124
+ const abortController = new AbortController();
6125
+ const context = {
6126
+ config: this.config,
6127
+ stats,
6128
+ abortController,
6129
+ get aborted() {
6130
+ return closed || abortController.signal.aborted || Date.now() >= deadline;
6131
+ },
6132
+ set aborted(value) {
6133
+ if (value) abortController.abort();
6134
+ },
6135
+ toolHandler: toolHandler ?? this.options.toolHandler,
6136
+ toolNamespaces: this.namespaces,
6137
+ beforeToolCall: (name, args) => {
6138
+ policy.toolCall(name, args);
6139
+ return true;
6140
+ },
6141
+ beforeGlobalCall: () => {
6142
+ policy.globalCall();
6143
+ return true;
6144
+ },
6145
+ maxToolResultBytes: runOptions.maxToolResultBytes,
6146
+ onToolBridgeFailure: runOptions.onToolBridgeFailure,
6147
+ sidecar,
6148
+ referenceConfig: this.references,
6149
+ consoleHandler: this.options.consoleHandler
6150
+ };
6151
+ try {
6152
+ return await this.adapter.execute(transformed, context);
6153
+ } finally {
6154
+ closed = true;
6155
+ abortController.abort();
6156
+ }
6157
+ } catch (error) {
6158
+ const message = error?.message;
6159
+ return failure(
6160
+ "ExecutionError",
6161
+ typeof message === "string" ? message.slice(0, 2048) : "Portable execution failed",
6162
+ "EXECUTION_ERROR"
6163
+ );
6164
+ } finally {
6165
+ sidecar?.dispose();
6166
+ }
6167
+ }
6168
+ dispose() {
6169
+ this.disposed = true;
6170
+ this.adapter.dispose();
6171
+ }
6172
+ };
6173
+ var AgentScriptRunner = class extends PortableEnclave {
6174
+ static capabilities = Object.freeze([
6175
+ "validated-agentscript",
6176
+ "host-functions",
6177
+ "tool-namespaces",
6178
+ "sidecar",
6179
+ "console",
6180
+ "rapid-enumeration"
6181
+ ]);
6182
+ constructor(options) {
6183
+ const {
6184
+ hostFunctions,
6185
+ maxHostFunctionCalls,
6186
+ maxSteps,
6187
+ maxCallDepth,
6188
+ maxPendingCalls,
6189
+ rapidEnumeration,
6190
+ ...enclaveOptions
6191
+ } = options;
6192
+ super({
6193
+ ...enclaveOptions,
6194
+ allowFunctionsInGlobals: true,
6195
+ globals: { ...hostFunctions },
6196
+ maxGlobalFunctionCalls: maxHostFunctionCalls,
6197
+ doubleVm: {
6198
+ parentValidation: {
6199
+ ...rapidEnumeration?.threshold !== void 0 && { rapidEnumerationThreshold: rapidEnumeration.threshold },
6200
+ ...rapidEnumeration?.overrides !== void 0 && { rapidEnumerationOverrides: rapidEnumeration.overrides }
6201
+ }
6202
+ },
6203
+ interpreter: { maxSteps, maxCallDepth, maxPendingCalls }
6204
+ });
6205
+ }
6206
+ };
4629
6207
  export {
6208
+ AgentScriptRunner,
4630
6209
  Interpreter,
4631
6210
  InterpreterAdapter,
4632
6211
  InterpreterError,
6212
+ PortableEnclave,
4633
6213
  StepLimitError
4634
6214
  };