@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/worker.js CHANGED
@@ -30,9 +30,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // libs/core/src/worker.ts
31
31
  var worker_exports = {};
32
32
  __export(worker_exports, {
33
+ AgentScriptRunner: () => AgentScriptRunner,
33
34
  Interpreter: () => Interpreter,
34
35
  InterpreterAdapter: () => InterpreterAdapter,
35
36
  InterpreterError: () => InterpreterError,
37
+ PortableEnclave: () => PortableEnclave,
36
38
  StepLimitError: () => StepLimitError
37
39
  });
38
40
  module.exports = __toCommonJS(worker_exports);
@@ -84,15 +86,73 @@ var CONSOLE_FACTORY_SOURCE = `
84
86
  var toText = ''.constructor;
85
87
  var freeze = Object.freeze;
86
88
  var RealmError = Error;
89
+ var apply = Reflect.apply;
90
+ var isArray = Array.isArray;
91
+ var stringValueOf = ''.constructor.prototype.valueOf;
92
+ var numberValueOf = (0).constructor.prototype.valueOf;
87
93
 
88
- function formatArgument(value) {
94
+ // Whether a value has the internal slot that a built-in's valueOf reads.
95
+ function hasSlot(valueOf, value) {
96
+ try {
97
+ apply(valueOf, value, []);
98
+ return true;
99
+ } catch (e) {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // The JSON text of a value, given up as soon as it would be longer than limit characters. A
105
+ // value referenced many times is written as many times, so the text can be far longer than the
106
+ // value is large. What each member adds is counted as JSON.stringify writes it, and the count
107
+ // is a lower bound of its length (an escape only adds), so a text within the limit is never
108
+ // given up. The members JSON.stringify visits are counted as well, also those it leaves out (a
109
+ // function, undefined): at most as many as the limit has characters.
110
+ var TOO_LARGE = {};
111
+ function stringifyWithin(value, limit) {
112
+ var length = 0;
113
+ var visits = 0;
114
+ var root = true;
115
+ return stringify(value, function (key, member) {
116
+ if (++visits > limit) throw TOO_LARGE;
117
+ // A String or Number object is written as what it converts to; converted here, the way
118
+ // JSON.stringify converts it and once, so the count is of what is written.
119
+ if (member !== null && typeof member === 'object') {
120
+ if (hasSlot(stringValueOf, member)) member = toText(member);
121
+ else if (hasSlot(numberValueOf, member)) member = +member;
122
+ }
123
+ var added;
124
+ var kind = typeof member;
125
+ if (kind === 'string') added = member.length + 2;
126
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
127
+ else if (kind === 'boolean') added = member ? 4 : 5;
128
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
129
+ else added = 0;
130
+ if (!root) {
131
+ // An element of an array is written, as null if nothing else; a member of an object
132
+ // that is written has its key in front of it.
133
+ if (isArray(this)) added = added || 4;
134
+ else if (added > 0) added += key.length + 3;
135
+ }
136
+ root = false;
137
+ length += added;
138
+ if (length > limit) throw TOO_LARGE;
139
+ return member;
140
+ });
141
+ }
142
+
143
+ // An argument as it is written in the line, in at most room characters for an object: an
144
+ // object is written only when the line has room left, and its text within that room. TOO_LARGE
145
+ // when it does not fit.
146
+ function formatArgument(value, room) {
89
147
  if (value === undefined) return 'undefined';
90
148
  if (value === null) return 'null';
91
149
  if (typeof value === 'object') {
150
+ if (room <= 0) throw TOO_LARGE;
92
151
  try {
93
- var json = stringify(value);
152
+ var json = stringifyWithin(value, room);
94
153
  return json === undefined ? '' : json;
95
154
  } catch (e) {
155
+ if (e === TOO_LARGE) throw e;
96
156
  return toText(value);
97
157
  }
98
158
  }
@@ -103,19 +163,38 @@ var CONSOLE_FACTORY_SOURCE = `
103
163
  var callCount = 0;
104
164
  var totalBytes = 0;
105
165
 
166
+ function tooLarge() {
167
+ return new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
168
+ }
169
+
106
170
  function method(level) {
107
171
  return (...args) => {
108
172
  callCount++;
109
173
  if (callCount > maxCalls) {
110
174
  throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
111
175
  }
176
+ // The line is measured as it is built: what an argument may add is the room the limit
177
+ // leaves, so the work done on a line that does not fit is in proportion to the limit.
112
178
  var line = '';
113
179
  for (var i = 0; i < args.length; i++) {
114
- line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
180
+ var separator = i === 0 ? '' : ' ';
181
+ var text;
182
+ try {
183
+ text = formatArgument(args[i], maxBytes - totalBytes - line.length - separator.length);
184
+ } catch (e) {
185
+ if (e !== TOO_LARGE) throw e;
186
+ totalBytes = maxBytes + 1;
187
+ throw tooLarge();
188
+ }
189
+ line += separator + text;
190
+ if (totalBytes + line.length > maxBytes) {
191
+ totalBytes = maxBytes + 1;
192
+ throw tooLarge();
193
+ }
115
194
  }
116
195
  totalBytes += line.length;
117
196
  if (totalBytes > maxBytes) {
118
- throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
197
+ throw tooLarge();
119
198
  }
120
199
  try {
121
200
  write(level, line);
@@ -417,6 +496,11 @@ var ReturnSignal = class {
417
496
  this.value = value;
418
497
  }
419
498
  };
499
+ var ScriptThrown = class {
500
+ constructor(value) {
501
+ this.value = value;
502
+ }
503
+ };
420
504
  var BreakSignal = class {
421
505
  };
422
506
  var ContinueSignal = class {
@@ -580,33 +664,44 @@ var Interpreter = class {
580
664
  * For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
581
665
  * of the script, or a built-in or host function the script passed along.
582
666
  */
583
- call(fn, args) {
584
- if (this.fatal !== void 0) throw this.fatal;
585
- if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
586
- if (this.interpretedFunctions.has(fn)) return fn(...args);
587
- return this.callFunction(fn, void 0, args, this.callerDepth);
667
+ async call(fn, args) {
668
+ try {
669
+ if (this.fatal !== void 0) throw this.fatal;
670
+ if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
671
+ if (this.interpretedFunctions.has(fn)) return await fn(...args);
672
+ return await this.callFunction(fn, void 0, args, this.callerDepth);
673
+ } catch (thrown) {
674
+ if (thrown instanceof ScriptThrown) throw thrown.value;
675
+ if (!(thrown instanceof Error)) throw new InterpreterError("Host operation failed");
676
+ throw thrown;
677
+ }
588
678
  }
589
679
  /** Number of AST nodes evaluated so far (for execution stats). */
590
680
  get stepCount() {
591
681
  return this.steps;
592
682
  }
593
683
  async run(program) {
594
- const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
595
- for (const stmt of program.body) {
596
- if (stmt.type === "FunctionDeclaration" && stmt.id) {
597
- root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
684
+ try {
685
+ const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
686
+ for (const stmt of program.body) {
687
+ if (stmt.type === "FunctionDeclaration" && stmt.id) {
688
+ root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
689
+ }
598
690
  }
691
+ let last;
692
+ for (const stmt of program.body) {
693
+ if (stmt.type === "FunctionDeclaration") continue;
694
+ last = await this.execStatement(stmt, root);
695
+ }
696
+ if (root.has("__ag_main")) {
697
+ const main = root.get("__ag_main");
698
+ if (typeof main === "function") return await main();
699
+ }
700
+ return last;
701
+ } catch (thrown) {
702
+ if (thrown instanceof ScriptThrown) throw thrown.value;
703
+ throw thrown;
599
704
  }
600
- let last;
601
- for (const stmt of program.body) {
602
- if (stmt.type === "FunctionDeclaration") continue;
603
- last = await this.execStatement(stmt, root);
604
- }
605
- if (root.has("__ag_main")) {
606
- const main = root.get("__ag_main");
607
- if (typeof main === "function") return main();
608
- }
609
- return last;
610
705
  }
611
706
  /**
612
707
  * End the run from outside: whatever of the script is still going (a callback waiting for a
@@ -780,7 +875,7 @@ var Interpreter = class {
780
875
  case "TryStatement":
781
876
  return this.execTry(node, scope);
782
877
  case "ThrowStatement":
783
- throw await this.evalExpr(node.argument, scope);
878
+ throw new ScriptThrown(await this.evalExpr(node.argument, scope));
784
879
  case "ReturnStatement":
785
880
  throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
786
881
  case "BreakStatement":
@@ -902,12 +997,12 @@ var Interpreter = class {
902
997
  }
903
998
  }
904
999
  /**
905
- * What a `catch` clause receives. A value the script threw is its own. A host Error (a refusal
906
- * by the interpreter, a failed tool call, a TypeError of a built-in) is replaced by a plain
907
- * copy with its name, message and code.
1000
+ * What a `catch` clause receives. A value the script threw is its own. A host Error is copied
1001
+ * with its name, message and code; every other host rejection reason becomes a generic error.
908
1002
  */
909
1003
  toScriptValue(thrown) {
910
- if (!(thrown instanceof Error)) return thrown;
1004
+ if (thrown instanceof ScriptThrown) return thrown.value;
1005
+ if (!(thrown instanceof Error)) return createScriptError("Error", "Host operation failed");
911
1006
  const known = this.errorCopies.get(thrown);
912
1007
  if (known) return known;
913
1008
  const code = thrown.code;
@@ -2298,27 +2393,28 @@ function expandReplacement(template, text, at, matched) {
2298
2393
  function convertedOnce(value, convert) {
2299
2394
  return typeof value === "object" && value !== null ? convert(value) : value;
2300
2395
  }
2301
- function checkArrayWrite(array, key, value) {
2396
+ function checkArrayWrite(array, key, value, currentLength = array.length) {
2302
2397
  if (key === "length") value = convertedOnce(value, Number);
2303
- const length = arrayLengthAfterWrite(array, key, value);
2398
+ const length = arrayLengthAfterWrite(currentLength, key, value);
2304
2399
  if (length > MAX_ARRAY_LENGTH) {
2305
2400
  throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
2306
2401
  }
2307
2402
  return { value, length };
2308
2403
  }
2309
- function arrayLengthAfterWrite(array, key, value) {
2404
+ function arrayLengthAfterWrite(currentLength, key, value) {
2310
2405
  if (key === "length") {
2311
2406
  const length = Number(value);
2312
2407
  if (!Number.isInteger(length) || length < 0) throw new InterpreterError("Invalid array length");
2313
2408
  return length;
2314
2409
  }
2315
2410
  const index = Number(key);
2316
- if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(array.length, index + 1);
2317
- return array.length;
2411
+ if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(currentLength, index + 1);
2412
+ return currentLength;
2318
2413
  }
2319
2414
 
2320
2415
  // libs/core/src/value-sanitizer.ts
2321
2416
  var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
2417
+ var CIRCULAR_MARKER_BYTES = 12;
2322
2418
  var ReflectApply2 = Reflect.apply;
2323
2419
  var ReflectGet = Reflect.get;
2324
2420
  var ArrayIsArray = Array.isArray;
@@ -2464,9 +2560,12 @@ function sanitizeObjectValue(value, options, depth, context) {
2464
2560
  const sanitizedMap = ObjectCreate(null);
2465
2561
  const entries = ReflectApply2(MapProtoEntries, inspected, []);
2466
2562
  for (const [key, val] of entries) {
2563
+ context.propCount.count++;
2564
+ if (context.propCount.count > maxProperties) {
2565
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
2566
+ }
2467
2567
  if (typeof key !== "string") continue;
2468
2568
  if (DANGEROUS_KEYS.has(key)) continue;
2469
- context.propCount.count++;
2470
2569
  sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
2471
2570
  }
2472
2571
  return sanitizedMap;
@@ -2476,6 +2575,9 @@ function sanitizeObjectValue(value, options, depth, context) {
2476
2575
  const result = [];
2477
2576
  for (const item of iter) {
2478
2577
  context.propCount.count++;
2578
+ if (context.propCount.count > maxProperties) {
2579
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
2580
+ }
2479
2581
  result.push(sanitizeValue(item, options, depth + 1, context));
2480
2582
  }
2481
2583
  return result;
@@ -2563,7 +2665,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
2563
2665
  }
2564
2666
  if (ArrayIsArray(value)) {
2565
2667
  if (currentPath.has(value)) {
2566
- return 4;
2668
+ return CIRCULAR_MARKER_BYTES;
2567
2669
  }
2568
2670
  currentPath.add(value);
2569
2671
  try {
@@ -2589,7 +2691,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
2589
2691
  if (type === "object") {
2590
2692
  const object = value;
2591
2693
  if (currentPath.has(object)) {
2592
- return 4;
2694
+ return CIRCULAR_MARKER_BYTES;
2593
2695
  }
2594
2696
  if (!isPlainObject(object)) {
2595
2697
  if (hasBrand(DateProtoGetTime, object)) {
@@ -2813,13 +2915,26 @@ var SafeObject = frozenRecord({
2813
2915
  if (!isScriptData(target) || Object.isFrozen(target)) {
2814
2916
  throw new TypeError("Object.assign needs an object or array the script created as its target");
2815
2917
  }
2918
+ const targetIsArray = Array.isArray(target);
2919
+ const lengths = [];
2920
+ let length = targetIsArray ? target.length : 0;
2816
2921
  for (const source of sources) {
2817
2922
  if (source === null || source === void 0) continue;
2818
2923
  for (const key of dataKeys(source)) {
2819
- let value = source[key];
2924
+ const value = source[key];
2820
2925
  assertStorable(target, key, value);
2821
- if (Array.isArray(target)) value = checkArrayWrite(target, key, value).value;
2822
- target[key] = value;
2926
+ if (targetIsArray) {
2927
+ const checked = checkArrayWrite(target, key, value, length);
2928
+ length = checked.length;
2929
+ if (key === "length") lengths.push(checked.value);
2930
+ }
2931
+ }
2932
+ }
2933
+ let nextLength = 0;
2934
+ for (const source of sources) {
2935
+ if (source === null || source === void 0) continue;
2936
+ for (const key of dataKeys(source)) {
2937
+ target[key] = targetIsArray && key === "length" ? lengths[nextLength++] : source[key];
2823
2938
  }
2824
2939
  }
2825
2940
  return target;
@@ -3295,10 +3410,19 @@ var REFERENCE_CONFIGS = {
3295
3410
  // Very deep resolution
3296
3411
  }
3297
3412
  };
3413
+ var REF_ID_PREFIX = "__REF_";
3414
+ var REF_ID_SUFFIX = "__";
3298
3415
  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;
3299
3416
  function isReferenceId(value) {
3300
3417
  return typeof value === "string" && REF_ID_PATTERN.test(value);
3301
3418
  }
3419
+ function getMaxTotalResolvedSize(config) {
3420
+ const configured = config.maxTotalResolvedSize;
3421
+ if (typeof configured === "number" && configured >= 0) {
3422
+ return configured;
3423
+ }
3424
+ return 2 * config.maxTotalSize;
3425
+ }
3302
3426
 
3303
3427
  // libs/core/src/sidecar/reference-sidecar.ts
3304
3428
  var SidecarLimitError = class _SidecarLimitError extends Error {
@@ -3311,6 +3435,245 @@ var SidecarLimitError = class _SidecarLimitError extends Error {
3311
3435
  Object.setPrototypeOf(this, _SidecarLimitError.prototype);
3312
3436
  }
3313
3437
  };
3438
+ var ReferenceSidecar = class {
3439
+ constructor(config) {
3440
+ this.config = config;
3441
+ this.maxTotalResolvedSize = getMaxTotalResolvedSize(config);
3442
+ }
3443
+ storage = /* @__PURE__ */ new Map();
3444
+ metadata = /* @__PURE__ */ new Map();
3445
+ /** The stored values that were resolved for a tool call, as the string they were resolved to */
3446
+ resolved = /* @__PURE__ */ new Map();
3447
+ totalSize = 0;
3448
+ /** Bytes of resolved data built for the tool calls of this execution so far */
3449
+ resolvedSize = 0;
3450
+ maxTotalResolvedSize;
3451
+ disposed = false;
3452
+ /**
3453
+ * Store data and return a reference ID
3454
+ *
3455
+ * @param data - The data to store (string or Buffer)
3456
+ * @param source - Where this data came from
3457
+ * @param options - Optional metadata
3458
+ * @returns The reference ID (format: __REF_uuid__)
3459
+ * @throws SidecarLimitError if limits are exceeded
3460
+ */
3461
+ store(data, source, options) {
3462
+ if (this.disposed) {
3463
+ throw new Error("Cannot store: sidecar has been disposed");
3464
+ }
3465
+ const buffer = typeof data === "string" ? Buffer.from(data, "utf-8") : data;
3466
+ const size = buffer.length;
3467
+ if (this.storage.size >= this.config.maxReferenceCount) {
3468
+ throw new SidecarLimitError(
3469
+ `Maximum reference count exceeded (${this.config.maxReferenceCount})`,
3470
+ "MAX_REFERENCE_COUNT",
3471
+ this.config.maxReferenceCount,
3472
+ this.storage.size
3473
+ );
3474
+ }
3475
+ if (size > this.config.maxReferenceSize) {
3476
+ throw new SidecarLimitError(
3477
+ `Reference size ${size} bytes exceeds maximum ${this.config.maxReferenceSize} bytes`,
3478
+ "MAX_REFERENCE_SIZE",
3479
+ this.config.maxReferenceSize,
3480
+ size
3481
+ );
3482
+ }
3483
+ if (this.totalSize + size > this.config.maxTotalSize) {
3484
+ throw new SidecarLimitError(
3485
+ `Total sidecar size would exceed maximum: ${this.totalSize + size} > ${this.config.maxTotalSize}`,
3486
+ "MAX_TOTAL_SIZE",
3487
+ this.config.maxTotalSize,
3488
+ this.totalSize + size
3489
+ );
3490
+ }
3491
+ const randomUUID = globalThis.crypto?.randomUUID?.bind(globalThis.crypto);
3492
+ if (!randomUUID) throw new Error("Secure random UUID generation is unavailable");
3493
+ const refId = `${REF_ID_PREFIX}${randomUUID()}${REF_ID_SUFFIX}`;
3494
+ this.storage.set(refId, Buffer.from(buffer));
3495
+ this.totalSize += size;
3496
+ this.metadata.set(refId, {
3497
+ createdAt: Date.now(),
3498
+ size,
3499
+ source,
3500
+ mimeType: options?.mimeType,
3501
+ origin: options?.origin
3502
+ });
3503
+ return refId;
3504
+ }
3505
+ /**
3506
+ * Retrieve data by reference ID
3507
+ *
3508
+ * @param refId - The reference ID to look up
3509
+ * @returns The stored data or undefined if not found
3510
+ */
3511
+ retrieve(refId) {
3512
+ if (this.disposed) {
3513
+ return void 0;
3514
+ }
3515
+ const data = this.storage.get(refId);
3516
+ return data ? Buffer.from(data) : void 0;
3517
+ }
3518
+ /**
3519
+ * Retrieve data as a string
3520
+ *
3521
+ * @param refId - The reference ID to look up
3522
+ * @param encoding - String encoding (default: utf-8)
3523
+ * @returns The stored data as a string or undefined
3524
+ */
3525
+ retrieveString(refId, encoding = "utf-8") {
3526
+ const data = this.retrieve(refId);
3527
+ return data?.toString(encoding);
3528
+ }
3529
+ /**
3530
+ * Resolve a reference for a tool call: the stored data as a string
3531
+ *
3532
+ * A stored value is decoded once in the life of the sidecar (one execution) and counted
3533
+ * against `maxTotalResolvedSize` then. Every later resolution, in the same call or in another,
3534
+ * returns the same string and counts nothing: a string cannot be changed, so handing it out
3535
+ * again takes no memory.
3536
+ *
3537
+ * @param refId - The reference ID to resolve
3538
+ * @returns The stored data as a string, or undefined if the reference is not known
3539
+ * @throws SidecarLimitError if the execution's total of resolved data would be exceeded
3540
+ */
3541
+ resolveString(refId) {
3542
+ if (this.disposed) {
3543
+ return void 0;
3544
+ }
3545
+ const known = this.resolved.get(refId);
3546
+ if (known !== void 0) {
3547
+ return known;
3548
+ }
3549
+ const data = this.storage.get(refId);
3550
+ if (data === void 0) {
3551
+ return void 0;
3552
+ }
3553
+ this.countResolved(data.length);
3554
+ const text = data.toString("utf-8");
3555
+ this.resolved.set(refId, text);
3556
+ return text;
3557
+ }
3558
+ /**
3559
+ * Whether a reference was resolved before, so that resolving it again counts nothing
3560
+ */
3561
+ isResolved(refId) {
3562
+ return !this.disposed && this.resolved.has(refId);
3563
+ }
3564
+ /**
3565
+ * Count resolved data that is about to be built for a tool call of this execution
3566
+ *
3567
+ * @param bytes - Size of the data in bytes
3568
+ * @throws SidecarLimitError if the total would exceed `maxTotalResolvedSize`; nothing is counted then
3569
+ */
3570
+ countResolved(bytes) {
3571
+ if (!this.canResolve(bytes)) {
3572
+ throw new SidecarLimitError(
3573
+ `Total resolved size would exceed maximum: ${this.resolvedSize + bytes} > ${this.maxTotalResolvedSize}`,
3574
+ "MAX_TOTAL_RESOLVED_SIZE",
3575
+ this.maxTotalResolvedSize,
3576
+ this.resolvedSize + bytes
3577
+ );
3578
+ }
3579
+ this.resolvedSize += bytes;
3580
+ }
3581
+ /**
3582
+ * Whether `bytes` more of resolved data fit in what this execution may resolve in total
3583
+ */
3584
+ canResolve(bytes) {
3585
+ return bytes >= 0 && this.resolvedSize + bytes <= this.maxTotalResolvedSize;
3586
+ }
3587
+ /**
3588
+ * Bytes of resolved data built for the tool calls of this execution so far
3589
+ */
3590
+ getResolvedSize() {
3591
+ return this.resolvedSize;
3592
+ }
3593
+ /**
3594
+ * Check if a reference ID exists
3595
+ */
3596
+ has(refId) {
3597
+ return !this.disposed && this.storage.has(refId);
3598
+ }
3599
+ /**
3600
+ * Get metadata for a reference
3601
+ */
3602
+ getMetadata(refId) {
3603
+ if (this.disposed) {
3604
+ return void 0;
3605
+ }
3606
+ return this.metadata.get(refId);
3607
+ }
3608
+ /**
3609
+ * Get the size of a reference without retrieving data
3610
+ */
3611
+ getSize(refId) {
3612
+ return this.getMetadata(refId)?.size;
3613
+ }
3614
+ /**
3615
+ * Get total size of all stored references
3616
+ */
3617
+ getTotalSize() {
3618
+ return this.totalSize;
3619
+ }
3620
+ /**
3621
+ * Get number of stored references
3622
+ */
3623
+ getCount() {
3624
+ return this.storage.size;
3625
+ }
3626
+ /**
3627
+ * Get the configuration
3628
+ */
3629
+ getConfig() {
3630
+ return { ...this.config };
3631
+ }
3632
+ /**
3633
+ * Check if a value is a reference ID
3634
+ */
3635
+ isReference(value) {
3636
+ return isReferenceId(value);
3637
+ }
3638
+ /**
3639
+ * Get all reference IDs (for debugging/auditing)
3640
+ */
3641
+ getAllReferenceIds() {
3642
+ return Array.from(this.storage.keys());
3643
+ }
3644
+ /**
3645
+ * Get audit log of all stored references
3646
+ */
3647
+ getAuditLog() {
3648
+ const log = [];
3649
+ for (const [refId, metadata] of this.metadata) {
3650
+ log.push({ refId, metadata });
3651
+ }
3652
+ return log;
3653
+ }
3654
+ /**
3655
+ * Check if the sidecar has been disposed
3656
+ */
3657
+ isDisposed() {
3658
+ return this.disposed;
3659
+ }
3660
+ /**
3661
+ * Dispose the sidecar and release all memory
3662
+ *
3663
+ * MUST be called after each execution to prevent memory leaks.
3664
+ * After disposal, the sidecar cannot be used.
3665
+ */
3666
+ dispose() {
3667
+ if (this.disposed) {
3668
+ return;
3669
+ }
3670
+ this.storage.clear();
3671
+ this.metadata.clear();
3672
+ this.resolved.clear();
3673
+ this.totalSize = 0;
3674
+ this.disposed = true;
3675
+ }
3676
+ };
3314
3677
 
3315
3678
  // libs/core/src/sidecar/reference-resolver.ts
3316
3679
  var ReflectGet2 = Reflect.get;
@@ -3581,28 +3944,38 @@ var ReferenceResolver = class {
3581
3944
  /**
3582
3945
  * Check if a value contains any reference IDs
3583
3946
  *
3947
+ * Every value is looked at, at any depth: a reference or composite past `maxResolutionDepth`
3948
+ * cannot be resolved, and it must still be found, so that `resolve()` refuses the call rather
3949
+ * than the handler receiving it unresolved. The value is walked with a list instead of by
3950
+ * recursion, so a deep value cannot exhaust the stack, and an object is looked at once.
3951
+ *
3584
3952
  * @param value - The value to check
3585
- * @param depth - Current recursion depth (internal)
3953
+ * @param _depth - Unused; kept for callers that pass a depth
3586
3954
  * @returns true if the value or any nested value is a reference
3587
3955
  */
3588
- containsReferences(value, depth = 0) {
3589
- if (depth > this.config.maxResolutionDepth) {
3590
- return false;
3591
- }
3592
- if (isReferenceId(value) || isCompositeHandle(value)) {
3593
- return true;
3594
- }
3595
- if (Array.isArray(value)) {
3596
- const len = untrustedLength(value);
3597
- for (let i = 0; i < len; i++) {
3598
- if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
3599
- return true;
3956
+ containsReferences(value, _depth = 0) {
3957
+ const pending = [value];
3958
+ const seen = /* @__PURE__ */ new Set();
3959
+ while (pending.length > 0) {
3960
+ const current = pending.pop();
3961
+ if (isReferenceId(current) || isCompositeHandle(current)) {
3962
+ return true;
3963
+ }
3964
+ if (current === null || typeof current !== "object" || seen.has(current)) {
3965
+ continue;
3966
+ }
3967
+ seen.add(current);
3968
+ if (Array.isArray(current)) {
3969
+ const len = untrustedLength(current);
3970
+ for (let i = 0; i < len; i++) {
3971
+ pending.push(untrustedAt(current, i));
3600
3972
  }
3973
+ continue;
3974
+ }
3975
+ const members = Object.values(current);
3976
+ for (let i = 0; i < members.length; i++) {
3977
+ pending.push(members[i]);
3601
3978
  }
3602
- return false;
3603
- }
3604
- if (value !== null && typeof value === "object") {
3605
- return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
3606
3979
  }
3607
3980
  return false;
3608
3981
  }
@@ -3799,6 +4172,79 @@ function sanitizeStackTrace(stack, sanitize = true) {
3799
4172
  return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
3800
4173
  }
3801
4174
 
4175
+ // libs/core/src/thrown-value.ts
4176
+ var MAX_THROWN_MESSAGE_LENGTH = 16 * 1024;
4177
+ var MAX_THROWN_STACK_LENGTH = 64 * 1024;
4178
+
4179
+ // libs/core/src/bounded-json.ts
4180
+ var JSONStringify = JSON.stringify;
4181
+ var ReflectApply3 = Reflect.apply;
4182
+ var ArrayIsArray2 = Array.isArray;
4183
+ var StringValueOf = String.prototype.valueOf;
4184
+ var NumberValueOf = Number.prototype.valueOf;
4185
+ var JsonTooLargeError = class extends Error {
4186
+ constructor(limit) {
4187
+ super(`JSON text exceeds ${limit} bytes`);
4188
+ this.name = "JsonTooLargeError";
4189
+ }
4190
+ };
4191
+ var JsonTraversalLimitError = class extends Error {
4192
+ constructor(limit) {
4193
+ super(`JSON traversal exceeds ${limit} members`);
4194
+ this.name = "JsonTraversalLimitError";
4195
+ }
4196
+ };
4197
+ function hasSlot(valueOf, value) {
4198
+ try {
4199
+ ReflectApply3(valueOf, value, []);
4200
+ return true;
4201
+ } catch {
4202
+ return false;
4203
+ }
4204
+ }
4205
+ function stringifyWithin(value, limit) {
4206
+ let bytes = 0;
4207
+ let visits = 0;
4208
+ const maxVisits = Math.max(1e4, Math.min(1e6, limit * 10));
4209
+ let root = true;
4210
+ return JSONStringify(value, function(key, member) {
4211
+ if (++visits > maxVisits) throw new JsonTraversalLimitError(maxVisits);
4212
+ if (member !== null && typeof member === "object") {
4213
+ if (hasSlot(StringValueOf, member)) member = String(member);
4214
+ else if (hasSlot(NumberValueOf, member)) member = Number(member);
4215
+ }
4216
+ let added;
4217
+ switch (typeof member) {
4218
+ case "string":
4219
+ added = member.length + 2;
4220
+ break;
4221
+ case "number":
4222
+ added = Number.isFinite(member) ? String(member).length : 4;
4223
+ break;
4224
+ case "boolean":
4225
+ added = member ? 4 : 5;
4226
+ break;
4227
+ case "object":
4228
+ case "bigint":
4229
+ added = member === null ? 4 : 2;
4230
+ break;
4231
+ default:
4232
+ added = 0;
4233
+ }
4234
+ if (!root) {
4235
+ if (ArrayIsArray2(this)) added = added || 4;
4236
+ else if (added > 0) added += key.length + 3;
4237
+ }
4238
+ root = false;
4239
+ bytes += added;
4240
+ if (bytes > limit) throw new JsonTooLargeError(limit);
4241
+ return member;
4242
+ });
4243
+ }
4244
+ function utf8Length2(value) {
4245
+ return Buffer.byteLength(value, "utf8");
4246
+ }
4247
+
3802
4248
  // libs/core/src/tool-bridge.ts
3803
4249
  var TOOL_BRIDGE_PROTOCOL_VERSION = 1;
3804
4250
  function utf8ByteLength(value) {
@@ -3954,9 +4400,9 @@ function createHostToolBridge(executionContext, options) {
3954
4400
  if (typeof executionContext.hostToolBridge === "function") {
3955
4401
  return createRelayedToolBridge(executionContext, options, executionContext.hostToolBridge);
3956
4402
  }
3957
- const { config, stats, toolHandler, sidecar, referenceConfig } = executionContext;
4403
+ const { config, stats, toolHandler, sidecar, referenceConfig: referenceConfig2 } = executionContext;
3958
4404
  const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
3959
- const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
4405
+ const resolver = sidecar && referenceConfig2 ? new ReferenceResolver(sidecar, referenceConfig2) : void 0;
3960
4406
  return async (requestJson) => {
3961
4407
  try {
3962
4408
  if (typeof requestJson !== "string") {
@@ -4134,6 +4580,7 @@ function createHostToolBridge(executionContext, options) {
4134
4580
  "Tool returned an unsupported value",
4135
4581
  "TOOL_RESULT_NOT_SAFE"
4136
4582
  );
4583
+ executionContext.onToolBridgeFailure?.();
4137
4584
  return serializeResponse(
4138
4585
  {
4139
4586
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -4143,13 +4590,55 @@ function createHostToolBridge(executionContext, options) {
4143
4590
  maxPayloadBytes
4144
4591
  );
4145
4592
  }
4146
- if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
4593
+ const resultLimit = executionContext.maxToolResultBytes;
4594
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
4595
+ let tooLarge = false;
4596
+ let tooComplex = false;
4597
+ try {
4598
+ const resultJson = stringifyWithin(sanitizedResult, resultLimit);
4599
+ tooLarge = resultJson !== void 0 && utf8ByteLength(resultJson) > resultLimit;
4600
+ } catch (error) {
4601
+ tooLarge = error instanceof JsonTooLargeError;
4602
+ tooComplex = error instanceof JsonTraversalLimitError;
4603
+ }
4604
+ if (tooLarge || tooComplex) {
4605
+ executionContext.onToolBridgeFailure?.();
4606
+ return serializeResponse(
4607
+ {
4608
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
4609
+ ok: false,
4610
+ error: {
4611
+ name: "ToolBridgeError",
4612
+ message: tooComplex ? "Tool result exceeds the traversal limit" : `Tool result exceeds the limit of ${resultLimit} bytes`,
4613
+ code: tooComplex ? "TOOL_RESULT_TOO_COMPLEX" : "TOOL_RESULT_TOO_LARGE",
4614
+ toolError: true
4615
+ }
4616
+ },
4617
+ maxPayloadBytes
4618
+ );
4619
+ }
4620
+ }
4621
+ if (sidecar && referenceConfig2 && typeof sanitizedResult === "string") {
4147
4622
  const size = utf8ByteLength(sanitizedResult);
4148
- if (size >= referenceConfig.extractionThreshold) {
4623
+ if (size >= referenceConfig2.extractionThreshold) {
4149
4624
  try {
4150
4625
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
4151
4626
  sanitizedResult = refId;
4152
4627
  } catch {
4628
+ executionContext.onToolBridgeFailure?.();
4629
+ return serializeResponse(
4630
+ {
4631
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
4632
+ ok: false,
4633
+ error: {
4634
+ name: "ToolBridgeError",
4635
+ message: "Tool result could not be stored in the reference sidecar",
4636
+ code: "TOOL_RESULT_NOT_STORED",
4637
+ toolError: true
4638
+ }
4639
+ },
4640
+ maxPayloadBytes
4641
+ );
4153
4642
  }
4154
4643
  }
4155
4644
  }
@@ -4164,6 +4653,7 @@ function createHostToolBridge(executionContext, options) {
4164
4653
  "Tool result must be JSON-serializable",
4165
4654
  "TOOL_RESULT_NOT_JSON"
4166
4655
  );
4656
+ executionContext.onToolBridgeFailure?.();
4167
4657
  return serializeResponse(
4168
4658
  {
4169
4659
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -4174,6 +4664,7 @@ function createHostToolBridge(executionContext, options) {
4174
4664
  );
4175
4665
  }
4176
4666
  if (utf8ByteLength(okJson) > maxPayloadBytes) {
4667
+ executionContext.onToolBridgeFailure?.();
4177
4668
  return serializeResponse(
4178
4669
  {
4179
4670
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -4384,7 +4875,7 @@ var InterpreterAdapter = class {
4384
4875
  */
4385
4876
  runtimeGlobals(context, charge, callbacks) {
4386
4877
  const { config } = context;
4387
- const callTool = observed(this.createCallTool(context, callbacks));
4878
+ const callTool = observed(this.createCallTool(context, callbacks, charge));
4388
4879
  const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
4389
4880
  const joinReferences = (parts) => {
4390
4881
  if (!resolver) {
@@ -4466,9 +4957,21 @@ var InterpreterAdapter = class {
4466
4957
  const settled = await Promise.allSettled(tasks.map(async (task) => task()));
4467
4958
  const failures = settled.filter((result) => result.status === "rejected");
4468
4959
  if (failures.length > 0) {
4469
- const messages = failures.map((failure) => this.describe(failure.reason).message).join("\n");
4470
- throw sandboxError(`${failures.length} of ${tasks.length} parallel operations failed:
4471
- ${messages}`);
4960
+ let messages = "";
4961
+ let listed = 0;
4962
+ for (const failure of failures) {
4963
+ const room = MAX_THROWN_MESSAGE_LENGTH - messages.length - (listed === 0 ? 0 : 1);
4964
+ if (room <= 0) break;
4965
+ const message = this.describe(failure.reason).message;
4966
+ messages += (listed === 0 ? "" : "\n") + (message.length > room ? message.slice(0, room) : message);
4967
+ listed++;
4968
+ }
4969
+ const unlisted = failures.length - listed;
4970
+ throw sandboxError(
4971
+ `${failures.length} of ${tasks.length} parallel operations failed:
4972
+ ${messages}` + (unlisted > 0 ? `
4973
+ (${unlisted} more not shown)` : "")
4974
+ );
4472
4975
  }
4473
4976
  return settled.map((result) => result.value);
4474
4977
  });
@@ -4525,9 +5028,81 @@ ${messages}`);
4525
5028
  }
4526
5029
  const custom = config.globals;
4527
5030
  if (custom && typeof custom === "object") {
5031
+ const maxGlobalCalls = config.maxGlobalFunctionCalls ?? Math.max(10, config.maxToolCalls * 10);
5032
+ const payloadLimit = config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
5033
+ let globalCalls = 0;
5034
+ const serialize = (value) => {
5035
+ const sanitized = sanitizeValue(value, {
5036
+ maxDepth: config.maxSanitizeDepth,
5037
+ maxProperties: config.maxSanitizeProperties,
5038
+ allowDates: false,
5039
+ allowErrors: true
5040
+ });
5041
+ const json = stringifyWithin(sanitized, payloadLimit);
5042
+ if (json === void 0) return void 0;
5043
+ if (utf8Length2(json) > payloadLimit) throw sandboxError("Global function value exceeds bridge limit");
5044
+ return json;
5045
+ };
5046
+ const copy = (value) => {
5047
+ const json = serialize(value);
5048
+ return json === void 0 ? void 0 : JSON.parse(json);
5049
+ };
5050
+ const safeHostCall = (name, fn) => (...args) => {
5051
+ if (callbacks.over || context.aborted) throw executionOver();
5052
+ if (++globalCalls > maxGlobalCalls)
5053
+ throw sandboxError(`Global function call limit exceeded (${maxGlobalCalls})`);
5054
+ if (context.beforeGlobalCall && context.beforeGlobalCall() !== true) {
5055
+ throw sandboxError("Global function policy refused the call");
5056
+ }
5057
+ let safeArgs;
5058
+ try {
5059
+ safeArgs = copy(args);
5060
+ } catch {
5061
+ throw sandboxError(`Global function ${name} received unsupported arguments`, "TypeError");
5062
+ }
5063
+ let outcome;
5064
+ try {
5065
+ outcome = fn(...safeArgs);
5066
+ } catch {
5067
+ throw sandboxError("Global function failed");
5068
+ }
5069
+ const settle = (value) => {
5070
+ if (callbacks.over || context.aborted) throw executionOver();
5071
+ let json;
5072
+ try {
5073
+ json = serialize(value);
5074
+ } catch {
5075
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
5076
+ }
5077
+ if (json === void 0) return void 0;
5078
+ if (value !== null && typeof value === "object") charge(Math.max(json.length * 2, utf8Length2(json)));
5079
+ return JSON.parse(json);
5080
+ };
5081
+ if (outcome !== null && (typeof outcome === "object" || typeof outcome === "function")) {
5082
+ let then;
5083
+ try {
5084
+ then = outcome.then;
5085
+ } catch {
5086
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
5087
+ }
5088
+ if (typeof then === "function") {
5089
+ return observed(async () => {
5090
+ let value;
5091
+ try {
5092
+ value = await Promise.resolve(outcome);
5093
+ } catch {
5094
+ throw sandboxError("Global function failed");
5095
+ }
5096
+ return settle(value);
5097
+ })();
5098
+ }
5099
+ }
5100
+ return settle(outcome);
5101
+ };
4528
5102
  for (const name of Object.keys(custom)) {
4529
5103
  if (name.startsWith("__") || Object.prototype.hasOwnProperty.call(globals, name)) continue;
4530
- globals[name] = frozenDataCopy(name, custom[name]);
5104
+ const value = custom[name];
5105
+ globals[name] = typeof value === "function" ? safeHostCall(name, value) : frozenDataCopy(name, value);
4531
5106
  }
4532
5107
  }
4533
5108
  return globals;
@@ -4537,7 +5112,7 @@ ${messages}`);
4537
5112
  * and the response cross as JSON, so the handler never receives a value of the script and the
4538
5113
  * script never receives an object of the handler.
4539
5114
  */
4540
- createCallTool(context, execution) {
5115
+ createCallTool(context, execution, charge) {
4541
5116
  const configured = context.config.toolHandler;
4542
5117
  const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
4543
5118
  const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
@@ -4568,9 +5143,20 @@ ${messages}`);
4568
5143
  } catch {
4569
5144
  throw sandboxError("Tool arguments must be JSON-serializable", "TypeError");
4570
5145
  }
5146
+ if (utf8Length2(requestJson) > maxPayloadBytes) {
5147
+ throw sandboxError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "ToolBridgeError");
5148
+ }
5149
+ if (context.beforeToolCall) {
5150
+ const request = JSON.parse(requestJson);
5151
+ if (context.beforeToolCall(toolName, request.args) !== true) {
5152
+ throw sandboxError("Tool policy refused the call");
5153
+ }
5154
+ }
4571
5155
  let response;
5156
+ let responseJson;
4572
5157
  try {
4573
- response = JSON.parse(await bridge(requestJson));
5158
+ responseJson = await bridge(requestJson);
5159
+ response = JSON.parse(responseJson);
4574
5160
  } catch {
4575
5161
  throw sandboxError("Tool bridge returned invalid JSON");
4576
5162
  }
@@ -4579,6 +5165,15 @@ ${messages}`);
4579
5165
  }
4580
5166
  const reply = response;
4581
5167
  if (reply.ok === true) {
5168
+ try {
5169
+ charge(Math.max(responseJson.length * 2, utf8Length2(responseJson)));
5170
+ } catch (error) {
5171
+ try {
5172
+ context.onToolBridgeFailure?.();
5173
+ } catch {
5174
+ }
5175
+ throw error;
5176
+ }
4582
5177
  return throwOnError ? reply.value : { success: true, data: reply.value };
4583
5178
  }
4584
5179
  if (reply.ok === false && reply.error && typeof reply.error === "object") {
@@ -4665,10 +5260,985 @@ ${messages}`);
4665
5260
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
4666
5261
  }
4667
5262
  };
5263
+
5264
+ // libs/core/src/portable-enclave.ts
5265
+ var import_ast = require("@enclave-vm/ast");
5266
+ var acorn3 = __toESM(require("acorn"));
5267
+ var import_astring = require("astring");
5268
+
5269
+ // libs/core/src/types.ts
5270
+ var SECURITY_LEVEL_CONFIGS = {
5271
+ /**
5272
+ * STRICT: Maximum security for untrusted code
5273
+ *
5274
+ * Use for:
5275
+ * - AI-generated code from external sources
5276
+ * - User-submitted scripts
5277
+ * - Untrusted third-party integrations
5278
+ *
5279
+ * Characteristics:
5280
+ * - Short timeout (5s)
5281
+ * - Low iteration limits (1000)
5282
+ * - Limited tool calls (10)
5283
+ * - Deep value sanitization
5284
+ * - Full stack trace sanitization
5285
+ */
5286
+ STRICT: {
5287
+ timeout: 5e3,
5288
+ maxIterations: 1e3,
5289
+ maxToolCalls: 10,
5290
+ maxSanitizeDepth: 5,
5291
+ maxSanitizeProperties: 50,
5292
+ sanitizeStackTraces: true,
5293
+ blockTimingAPIs: true,
5294
+ allowUnboundedLoops: false,
5295
+ unicodeSecurityCheck: true,
5296
+ allowFunctionsInGlobals: false,
5297
+ maxConsoleOutputBytes: 64 * 1024,
5298
+ // 64KB - prevent I/O flood attacks
5299
+ maxConsoleCalls: 100,
5300
+ secureProxy: {
5301
+ blockConstructor: true,
5302
+ blockPrototype: true,
5303
+ blockLegacyAccessors: true,
5304
+ proxyMaxDepth: 5,
5305
+ throwOnBlocked: true
5306
+ }
5307
+ },
5308
+ /**
5309
+ * SECURE: High security with more headroom
5310
+ *
5311
+ * Use for:
5312
+ * - AI-generated code from trusted models
5313
+ * - Internal automation scripts
5314
+ * - Controlled multi-tenant environments
5315
+ *
5316
+ * Characteristics:
5317
+ * - Moderate timeout (15s)
5318
+ * - Moderate iteration limits (5000)
5319
+ * - Moderate tool calls (50)
5320
+ * - Standard value sanitization
5321
+ * - Stack trace sanitization
5322
+ */
5323
+ SECURE: {
5324
+ timeout: 15e3,
5325
+ maxIterations: 5e3,
5326
+ maxToolCalls: 50,
5327
+ maxSanitizeDepth: 10,
5328
+ maxSanitizeProperties: 100,
5329
+ sanitizeStackTraces: true,
5330
+ blockTimingAPIs: false,
5331
+ allowUnboundedLoops: false,
5332
+ unicodeSecurityCheck: true,
5333
+ allowFunctionsInGlobals: false,
5334
+ maxConsoleOutputBytes: 256 * 1024,
5335
+ // 256KB
5336
+ maxConsoleCalls: 500,
5337
+ secureProxy: {
5338
+ blockConstructor: true,
5339
+ blockPrototype: true,
5340
+ blockLegacyAccessors: true,
5341
+ proxyMaxDepth: 10,
5342
+ throwOnBlocked: true
5343
+ }
5344
+ },
5345
+ /**
5346
+ * STANDARD: Balanced security and functionality (DEFAULT)
5347
+ *
5348
+ * Use for:
5349
+ * - Internal tools and scripts
5350
+ * - Development and testing
5351
+ * - Trusted environments
5352
+ *
5353
+ * Characteristics:
5354
+ * - Standard timeout (30s)
5355
+ * - Standard iteration limits (10000)
5356
+ * - Standard tool calls (100)
5357
+ * - Basic value sanitization
5358
+ * - Minimal stack trace sanitization
5359
+ */
5360
+ STANDARD: {
5361
+ timeout: 3e4,
5362
+ maxIterations: 1e4,
5363
+ maxToolCalls: 100,
5364
+ maxSanitizeDepth: 20,
5365
+ maxSanitizeProperties: 500,
5366
+ sanitizeStackTraces: false,
5367
+ blockTimingAPIs: false,
5368
+ allowUnboundedLoops: true,
5369
+ unicodeSecurityCheck: false,
5370
+ allowFunctionsInGlobals: false,
5371
+ maxConsoleOutputBytes: 1024 * 1024,
5372
+ // 1MB
5373
+ maxConsoleCalls: 1e3,
5374
+ secureProxy: {
5375
+ blockConstructor: true,
5376
+ blockPrototype: true,
5377
+ blockLegacyAccessors: true,
5378
+ proxyMaxDepth: 15,
5379
+ throwOnBlocked: true
5380
+ }
5381
+ },
5382
+ /**
5383
+ * PERMISSIVE: Minimal restrictions
5384
+ *
5385
+ * Use for:
5386
+ * - Local development only
5387
+ * - Debugging
5388
+ * - Performance testing
5389
+ *
5390
+ * WARNING: Not recommended for production use with untrusted code
5391
+ *
5392
+ * Characteristics:
5393
+ * - Long timeout (60s)
5394
+ * - High iteration limits (100000)
5395
+ * - High tool calls (1000)
5396
+ * - Minimal sanitization
5397
+ * - No stack trace sanitization
5398
+ * - All features enabled
5399
+ */
5400
+ PERMISSIVE: {
5401
+ timeout: 6e4,
5402
+ maxIterations: 1e5,
5403
+ maxToolCalls: 1e3,
5404
+ maxSanitizeDepth: 50,
5405
+ maxSanitizeProperties: 1e3,
5406
+ sanitizeStackTraces: false,
5407
+ blockTimingAPIs: false,
5408
+ allowUnboundedLoops: true,
5409
+ unicodeSecurityCheck: false,
5410
+ allowFunctionsInGlobals: true,
5411
+ maxConsoleOutputBytes: 10 * 1024 * 1024,
5412
+ // 10MB
5413
+ maxConsoleCalls: 1e4,
5414
+ secureProxy: {
5415
+ blockConstructor: false,
5416
+ // Allow constructor access for development/debugging
5417
+ blockPrototype: true,
5418
+ // Still block prototype for safety
5419
+ blockLegacyAccessors: true,
5420
+ proxyMaxDepth: 20,
5421
+ throwOnBlocked: false
5422
+ // Return undefined instead of throwing for development
5423
+ }
5424
+ }
5425
+ };
5426
+ var DEFAULT_DOUBLE_VM_CONFIG = {
5427
+ enabled: true,
5428
+ parentTimeoutBuffer: 1e3,
5429
+ parentValidation: {
5430
+ validateOperationNames: true,
5431
+ maxOperationsPerSecond: 100,
5432
+ blockSuspiciousSequences: true,
5433
+ rapidEnumerationThreshold: 30,
5434
+ rapidEnumerationOverrides: {},
5435
+ suspiciousPatterns: []
5436
+ // Default patterns added at runtime
5437
+ }
5438
+ };
5439
+
5440
+ // libs/core/src/enclave-options.ts
5441
+ var MAX_TIMEOUT_MS = 2147483647;
5442
+ function withoutUndefined(value) {
5443
+ const result = {};
5444
+ for (const key of Object.keys(value)) {
5445
+ const member = value[key];
5446
+ if (member !== void 0) result[key] = member;
5447
+ }
5448
+ return result;
5449
+ }
5450
+ function describe(value) {
5451
+ if (value === null) return "null";
5452
+ if (typeof value === "number") return String(value);
5453
+ if (Array.isArray(value)) return "an array";
5454
+ if (typeof value === "string") return "a string";
5455
+ return `a value of type ${typeof value}`;
5456
+ }
5457
+ function assertIntegerOption(name, value, min, max = Number.MAX_SAFE_INTEGER) {
5458
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
5459
+ const range = max === Number.MAX_SAFE_INTEGER ? `an integer of at least ${min}` : `an integer from ${min} to ${max}`;
5460
+ throw new TypeError(`${name} must be ${range}, got ${describe(value)}`);
5461
+ }
5462
+ }
5463
+ function assertFiniteNumberOption(name, value, min) {
5464
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min) {
5465
+ throw new TypeError(`${name} must be a finite number of at least ${min}, got ${describe(value)}`);
5466
+ }
5467
+ }
5468
+ function assertBooleanOption(name, value) {
5469
+ if (typeof value !== "boolean") {
5470
+ throw new TypeError(`${name} must be true or false, got ${describe(value)}`);
5471
+ }
5472
+ }
5473
+ function assertSecurityLevel(value) {
5474
+ if (typeof value !== "string" || !Object.hasOwn(SECURITY_LEVEL_CONFIGS, value)) {
5475
+ throw new TypeError(
5476
+ `securityLevel must be one of ${Object.keys(SECURITY_LEVEL_CONFIGS).join(", ")}, got ${typeof value === "string" ? JSON.stringify(value.slice(0, 40)) : describe(value)}`
5477
+ );
5478
+ }
5479
+ }
5480
+ function isPlainRecord(value) {
5481
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5482
+ }
5483
+ function assertRecordOption(name, value) {
5484
+ if (!isPlainRecord(value)) {
5485
+ throw new TypeError(`${name} must be an object, got ${describe(value)}`);
5486
+ }
5487
+ }
5488
+ function assertKnownKeys(name, value, known) {
5489
+ for (const key of Object.keys(value)) {
5490
+ if (!known.includes(key)) {
5491
+ throw new TypeError(`${name} has no option ${JSON.stringify(key.slice(0, 40))}`);
5492
+ }
5493
+ }
5494
+ }
5495
+ function isOneOf(values, value) {
5496
+ return typeof value === "string" && values.includes(value);
5497
+ }
5498
+ var PRE_SCAN_PRESETS = ["agentscript", "strict", "secure", "standard", "permissive"];
5499
+ var PRE_SCAN_INTEGERS = [
5500
+ "maxInputSize",
5501
+ "maxLineLength",
5502
+ "maxLines",
5503
+ "maxNestingDepth",
5504
+ "maxConsecutiveOperators",
5505
+ "maxRegexLength",
5506
+ "maxRegexCount",
5507
+ "maxStringLength",
5508
+ "maxTotalStringContent"
5509
+ ];
5510
+ var PRE_SCAN_BOOLEANS = ["unicodePreCheck", "blockBidiPatterns", "blockInvisibleChars"];
5511
+ var PRE_SCAN_REGEX_MODES = ["allow", "analyze", "block"];
5512
+ var PRE_SCAN_REGEX_ANALYSIS_LEVELS = ["catastrophic", "polynomial"];
5513
+ var INTEGER_OPTIONS = [
5514
+ // What a timer can hold (see MAX_TIMEOUT_MS)
5515
+ ["timeout", 1, MAX_TIMEOUT_MS],
5516
+ ["maxIterations", 1],
5517
+ ["maxToolCalls", 0],
5518
+ // 0: no memory limit
5519
+ ["memoryLimit", 0],
5520
+ ["maxSanitizeDepth", 1],
5521
+ ["maxSanitizeProperties", 1],
5522
+ ["maxConsoleOutputBytes", 0],
5523
+ ["maxConsoleCalls", 0]
5524
+ ];
5525
+ var BOOLEAN_OPTIONS = [
5526
+ "validate",
5527
+ "transform",
5528
+ "sanitizeStackTraces",
5529
+ "allowFunctionsInGlobals",
5530
+ "allowBuiltins"
5531
+ ];
5532
+ var SECURE_PROXY_BOOLEANS = ["blockConstructor", "blockPrototype", "blockLegacyAccessors", "throwOnBlocked"];
5533
+ var PARENT_VALIDATION_BOOLEANS = ["validateOperationNames", "blockSuspiciousSequences"];
5534
+ function normalizeEnclaveOptions(options) {
5535
+ if (!isPlainRecord(options)) {
5536
+ throw new TypeError(`Enclave options must be an object, got ${describe(options)}`);
5537
+ }
5538
+ const result = withoutUndefined(options);
5539
+ if (result.securityLevel !== void 0) assertSecurityLevel(result.securityLevel);
5540
+ for (const [name, min, max] of INTEGER_OPTIONS) {
5541
+ if (result[name] !== void 0) assertIntegerOption(name, result[name], min, max);
5542
+ }
5543
+ for (const name of BOOLEAN_OPTIONS) {
5544
+ if (result[name] !== void 0) assertBooleanOption(name, result[name]);
5545
+ }
5546
+ if (result.secureProxyConfig !== void 0) {
5547
+ assertRecordOption("secureProxyConfig", result.secureProxyConfig);
5548
+ const proxy = withoutUndefined(result.secureProxyConfig);
5549
+ for (const name of SECURE_PROXY_BOOLEANS) {
5550
+ if (proxy[name] !== void 0) assertBooleanOption(`secureProxyConfig.${name}`, proxy[name]);
5551
+ }
5552
+ if (proxy["proxyMaxDepth"] !== void 0) {
5553
+ assertIntegerOption("secureProxyConfig.proxyMaxDepth", proxy["proxyMaxDepth"], 1);
5554
+ }
5555
+ result.secureProxyConfig = proxy;
5556
+ }
5557
+ if (result.toolBridge !== void 0) {
5558
+ assertRecordOption("toolBridge", result.toolBridge);
5559
+ const bridge = withoutUndefined(result.toolBridge);
5560
+ if (bridge["acknowledgeInsecureDirect"] !== void 0) {
5561
+ assertBooleanOption("toolBridge.acknowledgeInsecureDirect", bridge["acknowledgeInsecureDirect"]);
5562
+ }
5563
+ result.toolBridge = bridge;
5564
+ }
5565
+ if (result.preScan !== void 0) {
5566
+ assertRecordOption("preScan", result.preScan);
5567
+ const preScan = withoutUndefined(result.preScan);
5568
+ assertKnownKeys("preScan", preScan, ["preset", "config"]);
5569
+ if (preScan["preset"] !== void 0 && !isOneOf(PRE_SCAN_PRESETS, preScan["preset"])) {
5570
+ throw new TypeError(
5571
+ `preScan.preset must be one of ${PRE_SCAN_PRESETS.join(", ")}, got ${describe(preScan["preset"])}`
5572
+ );
5573
+ }
5574
+ if (preScan["config"] !== void 0) {
5575
+ assertRecordOption("preScan.config", preScan["config"]);
5576
+ const config = withoutUndefined(preScan["config"]);
5577
+ assertKnownKeys("preScan.config", config, [
5578
+ ...PRE_SCAN_INTEGERS,
5579
+ ...PRE_SCAN_BOOLEANS,
5580
+ "regexMode",
5581
+ "regexAnalysisLevel"
5582
+ ]);
5583
+ for (const name of PRE_SCAN_INTEGERS) {
5584
+ if (config[name] !== void 0) assertIntegerOption(`preScan.config.${name}`, config[name], 0);
5585
+ }
5586
+ for (const name of PRE_SCAN_BOOLEANS) {
5587
+ if (config[name] !== void 0) assertBooleanOption(`preScan.config.${name}`, config[name]);
5588
+ }
5589
+ if (config["regexMode"] !== void 0 && !isOneOf(PRE_SCAN_REGEX_MODES, config["regexMode"])) {
5590
+ throw new TypeError(
5591
+ `preScan.config.regexMode must be one of ${PRE_SCAN_REGEX_MODES.join(", ")}, got ${describe(config["regexMode"])}`
5592
+ );
5593
+ }
5594
+ if (config["regexAnalysisLevel"] !== void 0 && !isOneOf(PRE_SCAN_REGEX_ANALYSIS_LEVELS, config["regexAnalysisLevel"])) {
5595
+ throw new TypeError(
5596
+ `preScan.config.regexAnalysisLevel must be one of ${PRE_SCAN_REGEX_ANALYSIS_LEVELS.join(", ")}, got ${describe(config["regexAnalysisLevel"])}`
5597
+ );
5598
+ }
5599
+ preScan["config"] = config;
5600
+ }
5601
+ result.preScan = preScan;
5602
+ }
5603
+ if (result.doubleVm !== void 0) {
5604
+ assertRecordOption("doubleVm", result.doubleVm);
5605
+ const doubleVm = withoutUndefined(result.doubleVm);
5606
+ if (doubleVm["enabled"] !== void 0) assertBooleanOption("doubleVm.enabled", doubleVm["enabled"]);
5607
+ if (doubleVm["parentTimeoutBuffer"] !== void 0) {
5608
+ assertIntegerOption("doubleVm.parentTimeoutBuffer", doubleVm["parentTimeoutBuffer"], 0, MAX_TIMEOUT_MS);
5609
+ }
5610
+ if (doubleVm["parentValidation"] !== void 0) {
5611
+ assertRecordOption("doubleVm.parentValidation", doubleVm["parentValidation"]);
5612
+ const validation = withoutUndefined(doubleVm["parentValidation"]);
5613
+ for (const name of PARENT_VALIDATION_BOOLEANS) {
5614
+ if (validation[name] !== void 0) {
5615
+ assertBooleanOption(`doubleVm.parentValidation.${name}`, validation[name]);
5616
+ }
5617
+ }
5618
+ if (validation["maxOperationsPerSecond"] !== void 0) {
5619
+ assertFiniteNumberOption(
5620
+ "doubleVm.parentValidation.maxOperationsPerSecond",
5621
+ validation["maxOperationsPerSecond"],
5622
+ 1
5623
+ );
5624
+ }
5625
+ if (validation["rapidEnumerationThreshold"] !== void 0) {
5626
+ assertIntegerOption(
5627
+ "doubleVm.parentValidation.rapidEnumerationThreshold",
5628
+ validation["rapidEnumerationThreshold"],
5629
+ 1
5630
+ );
5631
+ }
5632
+ if (validation["rapidEnumerationOverrides"] !== void 0) {
5633
+ assertRecordOption(
5634
+ "doubleVm.parentValidation.rapidEnumerationOverrides",
5635
+ validation["rapidEnumerationOverrides"]
5636
+ );
5637
+ for (const [operation, threshold] of Object.entries(validation["rapidEnumerationOverrides"])) {
5638
+ assertIntegerOption(
5639
+ `doubleVm.parentValidation.rapidEnumerationOverrides[${JSON.stringify(operation.slice(0, 40))}]`,
5640
+ threshold,
5641
+ 1
5642
+ );
5643
+ }
5644
+ }
5645
+ doubleVm["parentValidation"] = validation;
5646
+ }
5647
+ result.doubleVm = doubleVm;
5648
+ }
5649
+ return result;
5650
+ }
5651
+
5652
+ // libs/core/src/portable-globals.ts
5653
+ var MAX_GLOBAL_DEPTH = 10;
5654
+ var MAX_GLOBAL_PROPERTIES = 1e4;
5655
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
5656
+ var BLOCKED_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
5657
+ function copyPortableGlobals(globals, allowFunctions, maxBytes) {
5658
+ const result = /* @__PURE__ */ Object.create(null);
5659
+ if (globals === void 0) return result;
5660
+ if (globals === null || typeof globals !== "object" || Array.isArray(globals)) {
5661
+ throw new TypeError("globals must be a record");
5662
+ }
5663
+ let properties = 0;
5664
+ let bytes = 0;
5665
+ const active = /* @__PURE__ */ new Set();
5666
+ const charge = (value) => {
5667
+ bytes += value.length * 6 + 8;
5668
+ if (bytes > maxBytes) throw new TypeError("globals exceed the portable bridge size limit");
5669
+ };
5670
+ const copy = (value, depth) => {
5671
+ if (depth > MAX_GLOBAL_DEPTH) throw new TypeError("globals exceed the portable depth limit");
5672
+ if (value === null || typeof value === "boolean") return value;
5673
+ if (typeof value === "string") {
5674
+ charge(value);
5675
+ return value;
5676
+ }
5677
+ if (typeof value === "number" && Number.isFinite(value)) return value;
5678
+ if (typeof value !== "object") throw new TypeError("portable globals must contain JSON data only");
5679
+ if (active.has(value)) throw new TypeError("portable globals cannot contain cycles");
5680
+ const array = Array.isArray(value);
5681
+ if (array && value.length > MAX_GLOBAL_PROPERTIES) {
5682
+ throw new TypeError("portable globals exceed the array length limit");
5683
+ }
5684
+ const prototype = Object.getPrototypeOf(value);
5685
+ if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
5686
+ throw new TypeError("portable globals must contain plain records or arrays");
5687
+ }
5688
+ active.add(value);
5689
+ try {
5690
+ const destination = array ? [] : /* @__PURE__ */ Object.create(null);
5691
+ const keys = Reflect.ownKeys(value);
5692
+ if (array && keys.length - 1 !== value.length) {
5693
+ throw new TypeError("portable globals cannot contain sparse arrays");
5694
+ }
5695
+ for (const key of keys) {
5696
+ if (typeof key !== "string") throw new TypeError("portable globals cannot contain symbol properties");
5697
+ if (array && key === "length") continue;
5698
+ if (BLOCKED_KEYS2.has(key)) throw new TypeError("portable globals contain a blocked property");
5699
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
5700
+ if (!descriptor || !Object.hasOwn(descriptor, "value")) {
5701
+ throw new TypeError("portable globals cannot contain accessors");
5702
+ }
5703
+ if (++properties > MAX_GLOBAL_PROPERTIES) throw new TypeError("globals exceed the portable property limit");
5704
+ charge(key);
5705
+ if (array) {
5706
+ const index = Number(key);
5707
+ if (!Number.isSafeInteger(index) || index < 0 || index >= value.length || String(index) !== key) {
5708
+ throw new TypeError("portable global arrays cannot contain named properties");
5709
+ }
5710
+ destination[index] = copy(descriptor.value, depth + 1);
5711
+ } else {
5712
+ destination[key] = copy(descriptor.value, depth + 1);
5713
+ }
5714
+ }
5715
+ return destination;
5716
+ } finally {
5717
+ active.delete(value);
5718
+ }
5719
+ };
5720
+ for (const key of Reflect.ownKeys(globals)) {
5721
+ if (typeof key !== "string" || !IDENTIFIER.test(key) || BLOCKED_KEYS2.has(key) || key.startsWith("__")) {
5722
+ throw new TypeError("portable globals contain an invalid name");
5723
+ }
5724
+ const descriptor = Object.getOwnPropertyDescriptor(globals, key);
5725
+ if (!descriptor || !Object.hasOwn(descriptor, "value")) {
5726
+ throw new TypeError("portable globals cannot contain accessors");
5727
+ }
5728
+ if (++properties > MAX_GLOBAL_PROPERTIES) throw new TypeError("globals exceed the portable property limit");
5729
+ charge(key);
5730
+ if (typeof descriptor.value === "function") {
5731
+ if (!allowFunctions) throw new TypeError("portable host functions require allowFunctionsInGlobals");
5732
+ result[key] = descriptor.value;
5733
+ } else {
5734
+ result[key] = copy(descriptor.value, 0);
5735
+ }
5736
+ }
5737
+ return result;
5738
+ }
5739
+
5740
+ // libs/core/src/double-vm/suspicious-patterns.ts
5741
+ var EXFIL_LIST_SEND = {
5742
+ id: "EXFIL_LIST_SEND",
5743
+ description: "List/query followed by send/export (potential exfiltration)",
5744
+ detect: (operationName, _args, history) => {
5745
+ const recentQueries = history.filter(
5746
+ (h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 5e3
5747
+ );
5748
+ const isSendOperation = /send|export|post|write|upload|publish|emit|transmit|forward/i.test(operationName);
5749
+ return recentQueries.length > 0 && isSendOperation;
5750
+ }
5751
+ };
5752
+ var RAPID_ENUMERATION = {
5753
+ id: "RAPID_ENUMERATION",
5754
+ description: "Rapid enumeration of resources (same operation called too many times in 5s)",
5755
+ detect: (operationName, _args, history) => {
5756
+ const now = Date.now();
5757
+ const recentSameOperation = history.filter((h) => h.operationName === operationName && now - h.timestamp < 5e3);
5758
+ let threshold = 30;
5759
+ try {
5760
+ const localConfig = typeof validationConfig !== "undefined" ? validationConfig : null;
5761
+ if (localConfig) {
5762
+ const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
5763
+ const overrides = localConfig.rapidEnumerationOverrides ?? {};
5764
+ const override = Object.prototype.hasOwnProperty.call(overrides, operationName) ? overrides[operationName] : void 0;
5765
+ threshold = typeof override === "number" ? override : defaultThreshold;
5766
+ }
5767
+ } catch {
5768
+ threshold = 30;
5769
+ }
5770
+ return recentSameOperation.length > threshold;
5771
+ }
5772
+ };
5773
+ var CREDENTIAL_EXFIL = {
5774
+ id: "CREDENTIAL_EXFIL",
5775
+ description: "Credential access followed by external operation",
5776
+ detect: (operationName, _args, history) => {
5777
+ const recentCredentialAccess = history.filter(
5778
+ (h) => /secret|credential|password|token|key|auth|api[_-]?key/i.test(h.operationName) && Date.now() - h.timestamp < 1e4
5779
+ );
5780
+ const isExternalOperation = /http|api|external|webhook|slack|email|sms|notification/i.test(operationName);
5781
+ return recentCredentialAccess.length > 0 && isExternalOperation;
5782
+ }
5783
+ };
5784
+ var BULK_OPERATION = {
5785
+ id: "BULK_OPERATION",
5786
+ description: "Bulk/batch operation detected",
5787
+ detect: (operationName, args, _history) => {
5788
+ const isBulkOperation = /\b(bulk|batch|mass|dump)\b|export[_-]all\b/i.test(operationName);
5789
+ if (typeof args === "object" && args !== null) {
5790
+ try {
5791
+ const argStr = JSON.stringify(args).toLowerCase();
5792
+ const firstLimit = argStr.indexOf("limit");
5793
+ 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;
5794
+ if (hasBulkArgs) return true;
5795
+ } catch {
5796
+ }
5797
+ }
5798
+ return isBulkOperation;
5799
+ }
5800
+ };
5801
+ var DELETE_AFTER_ACCESS = {
5802
+ id: "DELETE_AFTER_ACCESS",
5803
+ description: "Delete operation after data access (potential cover-up)",
5804
+ detect: (operationName, _args, history) => {
5805
+ const isDeleteOperation = /delete|remove|destroy|purge|clear|wipe|erase/i.test(operationName);
5806
+ if (!isDeleteOperation) return false;
5807
+ const recentDataAccess = history.filter(
5808
+ (h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 3e4
5809
+ );
5810
+ return recentDataAccess.length > 0;
5811
+ }
5812
+ };
5813
+ var DEFAULT_SUSPICIOUS_PATTERNS = [
5814
+ EXFIL_LIST_SEND,
5815
+ RAPID_ENUMERATION,
5816
+ CREDENTIAL_EXFIL,
5817
+ BULK_OPERATION,
5818
+ DELETE_AFTER_ACCESS
5819
+ ];
5820
+
5821
+ // libs/core/src/dynamic-import.ts
5822
+ var acorn2 = __toESM(require("acorn"));
5823
+ var walk = __toESM(require("acorn-walk"));
5824
+ var DYNAMIC_IMPORT_MESSAGE = "Dynamic import() is not available in the sandbox";
5825
+ function refuseDynamicImport(code) {
5826
+ if (typeof code !== "string" || !code.includes("import")) {
5827
+ return void 0;
5828
+ }
5829
+ let ast;
5830
+ try {
5831
+ ast = acorn2.parse(code, {
5832
+ ecmaVersion: "latest",
5833
+ sourceType: "script",
5834
+ allowHashBang: true,
5835
+ allowReturnOutsideFunction: true,
5836
+ allowAwaitOutsideFunction: true
5837
+ });
5838
+ } catch {
5839
+ return `${DYNAMIC_IMPORT_MESSAGE} (the script contains the word "import" and could not be parsed to rule it out)`;
5840
+ }
5841
+ let found = false;
5842
+ try {
5843
+ walk.full(ast, (node) => {
5844
+ if (node.type === "ImportExpression") found = true;
5845
+ if (node.type === "MetaProperty" && node.meta?.name === "import") {
5846
+ found = true;
5847
+ }
5848
+ });
5849
+ } catch {
5850
+ return DYNAMIC_IMPORT_MESSAGE;
5851
+ }
5852
+ return found ? DYNAMIC_IMPORT_MESSAGE : void 0;
5853
+ }
5854
+
5855
+ // libs/core/src/portable-enclave.ts
5856
+ var MAX_SCRIPT_LENGTH = 5 * 1024 * 1024;
5857
+ var MAX_PORTABLE_ALLOCATION_BYTES = 64 * 1024 * 1024;
5858
+ var MAX_PORTABLE_STEPS = 2e7;
5859
+ var MAX_PORTABLE_PENDING_CALLS = 4096;
5860
+ var MAX_PORTABLE_CALL_DEPTH = 1024;
5861
+ var DEFAULT_BRIDGE_BYTES = 5 * 1024 * 1024;
5862
+ function boundedInteger(name, value, max) {
5863
+ if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max)) {
5864
+ throw new TypeError(`${name} must be an integer from 1 to ${max}`);
5865
+ }
5866
+ }
5867
+ function referenceConfig(level, sidecar) {
5868
+ if (!sidecar?.enabled) return void 0;
5869
+ const base = REFERENCE_CONFIGS[level];
5870
+ return {
5871
+ maxTotalSize: sidecar.maxTotalSize ?? base.maxTotalSize,
5872
+ maxReferenceSize: sidecar.maxReferenceSize ?? base.maxReferenceSize,
5873
+ extractionThreshold: sidecar.extractionThreshold ?? base.extractionThreshold,
5874
+ maxResolvedSize: sidecar.maxResolvedSize ?? base.maxResolvedSize,
5875
+ maxTotalResolvedSize: sidecar.maxTotalResolvedSize ?? base.maxTotalResolvedSize,
5876
+ allowComposites: sidecar.allowComposites ?? base.allowComposites,
5877
+ maxReferenceCount: sidecar.maxReferenceCount ?? base.maxReferenceCount,
5878
+ maxResolutionDepth: base.maxResolutionDepth
5879
+ };
5880
+ }
5881
+ function validateReferenceConfig(config) {
5882
+ if (!config) return;
5883
+ for (const key of [
5884
+ "maxTotalSize",
5885
+ "maxReferenceSize",
5886
+ "extractionThreshold",
5887
+ "maxResolvedSize",
5888
+ "maxTotalResolvedSize",
5889
+ "maxReferenceCount",
5890
+ "maxResolutionDepth"
5891
+ ]) {
5892
+ const value = config[key];
5893
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0)) {
5894
+ throw new TypeError(`sidecar.${key} must be a positive finite integer`);
5895
+ }
5896
+ }
5897
+ if (config.maxReferenceSize > config.maxTotalSize || config.extractionThreshold > config.maxReferenceSize) {
5898
+ throw new TypeError("sidecar size limits must be ordered: threshold <= reference <= total");
5899
+ }
5900
+ }
5901
+ var PortableOperationPolicy = class {
5902
+ constructor(config) {
5903
+ this.config = config;
5904
+ }
5905
+ history = [];
5906
+ globalCallTimes = [];
5907
+ rate(now) {
5908
+ while (this.history.length && now - this.history[0].timestamp > 6e4) this.history.shift();
5909
+ while (this.globalCallTimes.length && now - this.globalCallTimes[0] > 2e3) this.globalCallTimes.shift();
5910
+ const recentTools = this.history.filter((entry) => now - entry.timestamp < 1e3).length;
5911
+ const recentGlobals = this.globalCallTimes.filter((at) => now - at < 1e3).length;
5912
+ if (recentTools + recentGlobals >= this.config.maxOperationsPerSecond) {
5913
+ throw new Error(`Operation rate limit exceeded (${this.config.maxOperationsPerSecond} operations/second)`);
5914
+ }
5915
+ }
5916
+ globalCall() {
5917
+ const now = Date.now();
5918
+ this.rate(now);
5919
+ this.globalCallTimes.push(now);
5920
+ }
5921
+ toolCall(name, args) {
5922
+ const now = Date.now();
5923
+ this.rate(now);
5924
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("Operation name must be a non-empty string");
5925
+ if (this.config.validateOperationNames) {
5926
+ const allowed = this.config.allowedOperationPattern;
5927
+ if (allowed) {
5928
+ allowed.lastIndex = 0;
5929
+ if (!allowed.test(name)) throw new Error(`Operation "${name}" does not match allowed pattern`);
5930
+ }
5931
+ for (const blocked of this.config.blockedOperationPatterns ?? []) {
5932
+ blocked.lastIndex = 0;
5933
+ if (blocked.test(name)) throw new Error(`Operation "${name}" matches blocked pattern`);
5934
+ }
5935
+ }
5936
+ if (this.config.blockSuspiciousSequences) {
5937
+ const override = Object.hasOwn(this.config.rapidEnumerationOverrides, name) ? this.config.rapidEnumerationOverrides[name] : void 0;
5938
+ const threshold = override ?? this.config.rapidEnumerationThreshold;
5939
+ const recentSame = this.history.filter((entry) => entry.operationName === name && now - entry.timestamp < 5e3);
5940
+ if (recentSame.length >= threshold) {
5941
+ throw new Error("Suspicious pattern detected: Rapid enumeration of resources [RAPID_ENUMERATION]");
5942
+ }
5943
+ for (const pattern of DEFAULT_SUSPICIOUS_PATTERNS) {
5944
+ if (pattern.id === "RAPID_ENUMERATION") continue;
5945
+ let detected = false;
5946
+ try {
5947
+ detected = pattern.detect(name, args, this.history);
5948
+ } catch {
5949
+ }
5950
+ if (detected) throw new Error(`Suspicious pattern detected: ${pattern.description} [${pattern.id}]`);
5951
+ }
5952
+ }
5953
+ this.history.push({ operationName: name, timestamp: now, argKeys: Object.keys(args) });
5954
+ }
5955
+ };
5956
+ var PortableEnclave = class {
5957
+ options;
5958
+ config;
5959
+ preScanner;
5960
+ validator;
5961
+ adapter;
5962
+ namespaces;
5963
+ references;
5964
+ policyConfig;
5965
+ customNames;
5966
+ disposed = false;
5967
+ constructor(rawOptions = {}) {
5968
+ const { interpreter, ...rawEnclaveOptions } = rawOptions;
5969
+ const options = normalizeEnclaveOptions(rawEnclaveOptions);
5970
+ const level = options.securityLevel ?? "STANDARD";
5971
+ if (level === "PERMISSIVE") throw new TypeError("Portable AgentScript requires STANDARD, SECURE or STRICT");
5972
+ if (options.preset !== void 0 && options.preset !== "agentscript") {
5973
+ throw new TypeError("PortableEnclave supports the AgentScript preset only");
5974
+ }
5975
+ if (options.validate === false || options.transform === false) {
5976
+ throw new TypeError("PortableEnclave requires validation, transformation and pre-scan");
5977
+ }
5978
+ if (options.preScan?.preset !== void 0 && options.preScan.preset !== "agentscript") {
5979
+ throw new TypeError("PortableEnclave requires the AgentScript pre-scan preset");
5980
+ }
5981
+ if (options.preScan?.config !== void 0) {
5982
+ throw new TypeError("PortableEnclave does not allow pre-scan overrides");
5983
+ }
5984
+ if (options.toolBridge?.mode === "direct") throw new TypeError("PortableEnclave requires the string tool bridge");
5985
+ if (options.toolBridge?.acknowledgeInsecureDirect === true) {
5986
+ throw new TypeError("PortableEnclave does not support direct bridge acknowledgement");
5987
+ }
5988
+ if (options.adapter || options.sandboxAdapter || options.workerPoolConfig || options.scoringGate) {
5989
+ throw new TypeError("PortableEnclave does not support VM adapters or scoring gates");
5990
+ }
5991
+ if (options.allowBuiltins === true || options.toolCallGraceMs !== void 0) {
5992
+ throw new TypeError("PortableEnclave does not support VM builtin or tool grace overrides");
5993
+ }
5994
+ if (options.secureProxyConfig || options.realmGlobals === "security-level") {
5995
+ throw new TypeError("PortableEnclave does not support VM realm proxy overrides");
5996
+ }
5997
+ if (options.doubleVm?.enabled === false || options.doubleVm?.parentTimeoutBuffer !== void 0 || options.doubleVm?.parentValidation?.suspiciousPatterns?.length) {
5998
+ throw new TypeError("PortableEnclave cannot disable or replace its tool policy");
5999
+ }
6000
+ boundedInteger("interpreter.maxSteps", interpreter?.maxSteps, MAX_PORTABLE_STEPS);
6001
+ boundedInteger("interpreter.maxCallDepth", interpreter?.maxCallDepth, MAX_PORTABLE_CALL_DEPTH);
6002
+ boundedInteger("interpreter.maxPendingCalls", interpreter?.maxPendingCalls, MAX_PORTABLE_PENDING_CALLS);
6003
+ boundedInteger("interpreter.maxAllocationBytes", interpreter?.maxAllocationBytes, MAX_PORTABLE_ALLOCATION_BYTES);
6004
+ const memoryLimit = options.memoryLimit ?? 1024 * 1024;
6005
+ boundedInteger("memoryLimit", memoryLimit, MAX_PORTABLE_ALLOCATION_BYTES);
6006
+ const maxPayloadBytes = options.toolBridge?.maxPayloadBytes ?? DEFAULT_BRIDGE_BYTES;
6007
+ boundedInteger("toolBridge.maxPayloadBytes", maxPayloadBytes, MAX_PORTABLE_ALLOCATION_BYTES);
6008
+ const security = SECURITY_LEVEL_CONFIGS[level];
6009
+ const maxToolCalls = options.maxToolCalls ?? security.maxToolCalls;
6010
+ if (maxToolCalls > 1e5) throw new TypeError("maxToolCalls cannot exceed 100000 in PortableEnclave");
6011
+ if ((options.maxIterations ?? security.maxIterations) > MAX_PORTABLE_STEPS) {
6012
+ throw new TypeError(`maxIterations cannot exceed ${MAX_PORTABLE_STEPS} in PortableEnclave`);
6013
+ }
6014
+ if ((options.maxSanitizeDepth ?? security.maxSanitizeDepth) > 100) {
6015
+ throw new TypeError("maxSanitizeDepth cannot exceed 100 in PortableEnclave");
6016
+ }
6017
+ if ((options.maxSanitizeProperties ?? security.maxSanitizeProperties) > 2e4) {
6018
+ throw new TypeError("maxSanitizeProperties cannot exceed 20000 in PortableEnclave");
6019
+ }
6020
+ const maxGlobalFunctionCalls = options.maxGlobalFunctionCalls ?? Math.max(10, maxToolCalls * 10);
6021
+ boundedInteger("maxGlobalFunctionCalls", maxGlobalFunctionCalls, 1e6);
6022
+ options.globals = copyPortableGlobals(options.globals, options.allowFunctionsInGlobals === true, maxPayloadBytes);
6023
+ const standardNames = /* @__PURE__ */ new Set([...Object.keys(createSafeGlobals().globals), "callTool", "parallel", "console"]);
6024
+ for (const name of Object.keys(options.globals)) {
6025
+ if (standardNames.has(name)) throw new TypeError(`PortableEnclave cannot replace standard global ${name}`);
6026
+ }
6027
+ this.namespaces = (0, import_ast.normalizeToolNamespaces)(options.toolNamespaces, {
6028
+ reservedNames: Object.keys(options.globals ?? {})
6029
+ });
6030
+ this.customNames = [...Object.keys(options.globals ?? {}), ...this.namespaces.map((entry) => entry.name)];
6031
+ const allowed = [
6032
+ ...(0, import_ast.getAgentScriptGlobals)(level),
6033
+ "parallel",
6034
+ "__safe_parallel",
6035
+ "__safe_concat",
6036
+ "__safe_template",
6037
+ ...options.consoleHandler ? ["console", "__safe_console"] : [],
6038
+ ...this.customNames.flatMap((name) => [name, `__safe_${name}`])
6039
+ ];
6040
+ const hostObjects = [
6041
+ ...Object.keys(options.globals ?? {}).filter((name) => typeof options.globals?.[name] !== "string"),
6042
+ ...this.namespaces.map((entry) => entry.name)
6043
+ ];
6044
+ this.preScanner = new import_ast.PreScanner({
6045
+ preset: options.preScan?.preset ?? "agentscript",
6046
+ config: options.preScan?.config
6047
+ });
6048
+ this.validator = new import_ast.JSAstValidator(
6049
+ (0, import_ast.createAgentScriptPreset)({
6050
+ securityLevel: level,
6051
+ allowedGlobals: allowed,
6052
+ hostObjectGlobals: hostObjects,
6053
+ allowDynamicArrayFill: true
6054
+ })
6055
+ );
6056
+ this.references = referenceConfig(level, options.sidecar);
6057
+ validateReferenceConfig(this.references);
6058
+ this.policyConfig = {
6059
+ ...DEFAULT_DOUBLE_VM_CONFIG.parentValidation,
6060
+ ...options.doubleVm?.parentValidation,
6061
+ rapidEnumerationOverrides: { ...options.doubleVm?.parentValidation?.rapidEnumerationOverrides },
6062
+ blockedOperationPatterns: [...options.doubleVm?.parentValidation?.blockedOperationPatterns ?? []],
6063
+ suspiciousPatterns: []
6064
+ };
6065
+ this.config = {
6066
+ timeout: options.timeout ?? security.timeout,
6067
+ maxIterations: options.maxIterations ?? security.maxIterations,
6068
+ maxToolCalls,
6069
+ memoryLimit,
6070
+ maxSanitizeDepth: options.maxSanitizeDepth ?? security.maxSanitizeDepth,
6071
+ maxSanitizeProperties: options.maxSanitizeProperties ?? security.maxSanitizeProperties,
6072
+ maxConsoleCalls: options.maxConsoleCalls ?? security.maxConsoleCalls,
6073
+ maxConsoleOutputBytes: options.maxConsoleOutputBytes ?? security.maxConsoleOutputBytes,
6074
+ sanitizeStackTraces: options.sanitizeStackTraces ?? true,
6075
+ maxGlobalFunctionCalls,
6076
+ toolBridge: { mode: "string", maxPayloadBytes },
6077
+ globals: options.globals ?? {},
6078
+ toolHandler: options.toolHandler
6079
+ };
6080
+ this.adapter = new InterpreterAdapter({
6081
+ maxSteps: interpreter?.maxSteps,
6082
+ maxCallDepth: interpreter?.maxCallDepth,
6083
+ maxPendingCalls: interpreter?.maxPendingCalls,
6084
+ maxAllocationBytes: interpreter?.maxAllocationBytes
6085
+ });
6086
+ this.options = options;
6087
+ }
6088
+ async run(code, toolHandler, runOptions = {}) {
6089
+ if (this.disposed) throw new Error("PortableEnclave has been disposed");
6090
+ boundedInteger("maxToolResultBytes", runOptions.maxToolResultBytes, MAX_PORTABLE_ALLOCATION_BYTES);
6091
+ const startTime = Date.now();
6092
+ const stats = { duration: 0, startTime, endTime: startTime, toolCallCount: 0, iterationCount: 0 };
6093
+ const failure = (name, message, code2, issues) => ({
6094
+ success: false,
6095
+ error: { name, message, code: code2, ...issues ? { data: { issues } } : {} },
6096
+ stats: { ...stats, duration: Date.now() - startTime, endTime: Date.now() }
6097
+ });
6098
+ if (typeof code !== "string" || code.length > MAX_SCRIPT_LENGTH) {
6099
+ return failure("ValidationError", "The script must be a string of at most 5 MiB", "VALIDATION_ERROR");
6100
+ }
6101
+ if (code.length > 0) {
6102
+ const scanned = this.preScanner.scan(code);
6103
+ if (!scanned.success) {
6104
+ const issues = scanned.issues.map((issue) => ({
6105
+ code: issue.code,
6106
+ severity: issue.severity === "error" ? import_ast.ValidationSeverity.ERROR : issue.severity === "warning" ? import_ast.ValidationSeverity.WARNING : import_ast.ValidationSeverity.INFO,
6107
+ message: issue.message,
6108
+ location: issue.line === void 0 ? void 0 : { line: issue.line, column: issue.column ?? 0 },
6109
+ data: issue.data
6110
+ }));
6111
+ return failure("ValidationError", "AgentScript pre-scan failed", "VALIDATION_ERROR", issues);
6112
+ }
6113
+ }
6114
+ let transformed;
6115
+ try {
6116
+ transformed = (0, import_ast.transformAgentScript)(code, {
6117
+ wrapInMain: !(0, import_ast.isWrappedInMain)(code),
6118
+ transformCallTool: true,
6119
+ transformLoops: true,
6120
+ maxIterations: this.config.maxIterations,
6121
+ additionalIdentifiers: this.customNames
6122
+ });
6123
+ } catch (error) {
6124
+ const message = error?.message;
6125
+ return failure(
6126
+ "ValidationError",
6127
+ typeof message === "string" ? message.slice(0, 2048) : "AgentScript parse failed",
6128
+ "VALIDATION_ERROR"
6129
+ );
6130
+ }
6131
+ const validation = await this.validator.validate(transformed, { preScan: { enabled: false } });
6132
+ if (!validation.valid) {
6133
+ return failure("ValidationError", "AgentScript validation failed", "VALIDATION_ERROR", validation.issues);
6134
+ }
6135
+ if (refuseDynamicImport(transformed)) {
6136
+ return failure("SecurityError", "Dynamic imports are unavailable", "SECURITY_VIOLATION");
6137
+ }
6138
+ const sidecar = this.references ? new ReferenceSidecar(this.references) : void 0;
6139
+ try {
6140
+ if (sidecar && this.references) {
6141
+ const ast = acorn3.parse(transformed, { ecmaVersion: "latest", sourceType: "script" });
6142
+ (0, import_ast.extractLargeStrings)(ast, {
6143
+ threshold: this.references.extractionThreshold,
6144
+ onExtract: (value) => sidecar.store(value, "extraction")
6145
+ });
6146
+ (0, import_ast.transformConcatenation)(ast, { arraySpread: false });
6147
+ (0, import_ast.transformTemplateLiterals)(ast);
6148
+ transformed = (0, import_astring.generate)(ast);
6149
+ }
6150
+ const policy = new PortableOperationPolicy(this.policyConfig);
6151
+ let closed = false;
6152
+ const deadline = Date.now() + this.config.timeout;
6153
+ const abortController = new AbortController();
6154
+ const context = {
6155
+ config: this.config,
6156
+ stats,
6157
+ abortController,
6158
+ get aborted() {
6159
+ return closed || abortController.signal.aborted || Date.now() >= deadline;
6160
+ },
6161
+ set aborted(value) {
6162
+ if (value) abortController.abort();
6163
+ },
6164
+ toolHandler: toolHandler ?? this.options.toolHandler,
6165
+ toolNamespaces: this.namespaces,
6166
+ beforeToolCall: (name, args) => {
6167
+ policy.toolCall(name, args);
6168
+ return true;
6169
+ },
6170
+ beforeGlobalCall: () => {
6171
+ policy.globalCall();
6172
+ return true;
6173
+ },
6174
+ maxToolResultBytes: runOptions.maxToolResultBytes,
6175
+ onToolBridgeFailure: runOptions.onToolBridgeFailure,
6176
+ sidecar,
6177
+ referenceConfig: this.references,
6178
+ consoleHandler: this.options.consoleHandler
6179
+ };
6180
+ try {
6181
+ return await this.adapter.execute(transformed, context);
6182
+ } finally {
6183
+ closed = true;
6184
+ abortController.abort();
6185
+ }
6186
+ } catch (error) {
6187
+ const message = error?.message;
6188
+ return failure(
6189
+ "ExecutionError",
6190
+ typeof message === "string" ? message.slice(0, 2048) : "Portable execution failed",
6191
+ "EXECUTION_ERROR"
6192
+ );
6193
+ } finally {
6194
+ sidecar?.dispose();
6195
+ }
6196
+ }
6197
+ dispose() {
6198
+ this.disposed = true;
6199
+ this.adapter.dispose();
6200
+ }
6201
+ };
6202
+ var AgentScriptRunner = class extends PortableEnclave {
6203
+ static capabilities = Object.freeze([
6204
+ "validated-agentscript",
6205
+ "host-functions",
6206
+ "tool-namespaces",
6207
+ "sidecar",
6208
+ "console",
6209
+ "rapid-enumeration"
6210
+ ]);
6211
+ constructor(options) {
6212
+ const {
6213
+ hostFunctions,
6214
+ maxHostFunctionCalls,
6215
+ maxSteps,
6216
+ maxCallDepth,
6217
+ maxPendingCalls,
6218
+ rapidEnumeration,
6219
+ ...enclaveOptions
6220
+ } = options;
6221
+ super({
6222
+ ...enclaveOptions,
6223
+ allowFunctionsInGlobals: true,
6224
+ globals: { ...hostFunctions },
6225
+ maxGlobalFunctionCalls: maxHostFunctionCalls,
6226
+ doubleVm: {
6227
+ parentValidation: {
6228
+ ...rapidEnumeration?.threshold !== void 0 && { rapidEnumerationThreshold: rapidEnumeration.threshold },
6229
+ ...rapidEnumeration?.overrides !== void 0 && { rapidEnumerationOverrides: rapidEnumeration.overrides }
6230
+ }
6231
+ },
6232
+ interpreter: { maxSteps, maxCallDepth, maxPendingCalls }
6233
+ });
6234
+ }
6235
+ };
4668
6236
  // Annotate the CommonJS export names for ESM import in node:
4669
6237
  0 && (module.exports = {
6238
+ AgentScriptRunner,
4670
6239
  Interpreter,
4671
6240
  InterpreterAdapter,
4672
6241
  InterpreterError,
6242
+ PortableEnclave,
4673
6243
  StepLimitError
4674
6244
  });