@enclave-vm/core 2.15.2 → 2.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -0
- package/adapters/worker-pool/protocol.d.ts +38 -1
- package/adapters/worker-pool/result-encoding.d.ts +33 -0
- package/adapters/worker-pool/worker-pool-adapter.d.ts +3 -4
- package/double-vm/parent-vm-bootstrap.d.ts +8 -0
- package/enclave.d.ts +16 -1
- package/esm/index.mjs +1308 -352
- package/esm/worker.mjs +158 -4
- package/global-function-gate.d.ts +74 -0
- package/globals-validator.d.ts +8 -1
- package/index.d.ts +1 -1
- package/index.js +1326 -371
- package/node-vm.d.ts +13 -0
- package/package.json +3 -3
- package/safe-error.d.ts +5 -1
- package/safe-runtime.d.ts +13 -2
- package/secure-proxy.d.ts +19 -0
- package/src/adapters/worker-pool/package.json +3 -3
- package/src/adapters/worker-pool/worker-script.js +318 -4
- package/stack-trace.d.ts +38 -0
- package/tool-namespaces.d.ts +38 -0
- package/types.d.ts +142 -4
- package/value-sanitizer.d.ts +6 -0
- package/worker.js +158 -4
package/esm/index.mjs
CHANGED
|
@@ -9,9 +9,17 @@ var __export = (target, all) => {
|
|
|
9
9
|
};
|
|
10
10
|
|
|
11
11
|
// libs/core/src/safe-error.ts
|
|
12
|
-
function createSafeError(message, name = "Error") {
|
|
12
|
+
function createSafeError(message, name = "Error", code) {
|
|
13
13
|
const error = new Error(message);
|
|
14
14
|
error.name = name;
|
|
15
|
+
if (typeof code === "string") {
|
|
16
|
+
Object.defineProperty(error, "code", {
|
|
17
|
+
value: code,
|
|
18
|
+
writable: false,
|
|
19
|
+
enumerable: false,
|
|
20
|
+
configurable: false
|
|
21
|
+
});
|
|
22
|
+
}
|
|
15
23
|
const SafeConstructor = /* @__PURE__ */ Object.create(null);
|
|
16
24
|
Object.defineProperties(SafeConstructor, {
|
|
17
25
|
constructor: {
|
|
@@ -154,6 +162,14 @@ function createSafeReflect(securityLevel) {
|
|
|
154
162
|
}
|
|
155
163
|
});
|
|
156
164
|
}
|
|
165
|
+
function gatedProxyCache(gate) {
|
|
166
|
+
let cache = gatedProxyCaches.get(gate);
|
|
167
|
+
if (!cache) {
|
|
168
|
+
cache = /* @__PURE__ */ new WeakMap();
|
|
169
|
+
gatedProxyCaches.set(gate, cache);
|
|
170
|
+
}
|
|
171
|
+
return cache;
|
|
172
|
+
}
|
|
157
173
|
function getFullCacheKey(options) {
|
|
158
174
|
const parts = [];
|
|
159
175
|
if (options.levelConfig) {
|
|
@@ -179,7 +195,7 @@ function getFullCacheKey(options) {
|
|
|
179
195
|
function isProxyable(value) {
|
|
180
196
|
if (value === null) return false;
|
|
181
197
|
if (typeof value !== "object" && typeof value !== "function") return false;
|
|
182
|
-
const tag =
|
|
198
|
+
const tag = ReflectApply2(ObjectToString, value, []);
|
|
183
199
|
if (NON_PROXYABLE_TYPES.has(tag)) {
|
|
184
200
|
return false;
|
|
185
201
|
}
|
|
@@ -190,12 +206,11 @@ function createSecureProxy(target, options = {}) {
|
|
|
190
206
|
return target;
|
|
191
207
|
}
|
|
192
208
|
const cacheKey = getFullCacheKey(options);
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
}
|
|
209
|
+
const gateCache = options.callGate ? gatedProxyCache(options.callGate) : void 0;
|
|
210
|
+
const lookupCached = (obj) => gateCache ? gateCache.get(obj) : proxyCache.get(obj)?.get(cacheKey);
|
|
211
|
+
const cached = lookupCached(target);
|
|
212
|
+
if (cached) {
|
|
213
|
+
return cached;
|
|
199
214
|
}
|
|
200
215
|
const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
|
|
201
216
|
const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
|
|
@@ -206,12 +221,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
206
221
|
if (!isProxyable(obj)) {
|
|
207
222
|
return obj;
|
|
208
223
|
}
|
|
209
|
-
const
|
|
210
|
-
if (
|
|
211
|
-
|
|
212
|
-
if (cachedProxy) {
|
|
213
|
-
return cachedProxy;
|
|
214
|
-
}
|
|
224
|
+
const cachedProxy = lookupCached(obj);
|
|
225
|
+
if (cachedProxy) {
|
|
226
|
+
return cachedProxy;
|
|
215
227
|
}
|
|
216
228
|
if (depth > maxDepth) {
|
|
217
229
|
throw createSafeError(
|
|
@@ -259,9 +271,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
259
271
|
}
|
|
260
272
|
const value = ReflectGet(target2, property, receiver);
|
|
261
273
|
if (typeof value === "function") {
|
|
262
|
-
const tag =
|
|
274
|
+
const tag = ReflectApply2(ObjectToString, target2, []);
|
|
263
275
|
if (INTERNAL_SLOT_TYPES.has(tag)) {
|
|
264
|
-
const boundMethod =
|
|
276
|
+
const boundMethod = ReflectApply2(FunctionBind, value, [target2]);
|
|
265
277
|
return proxyWithDepth(boundMethod, depth + 1);
|
|
266
278
|
}
|
|
267
279
|
}
|
|
@@ -307,7 +319,7 @@ function createSecureProxy(target, options = {}) {
|
|
|
307
319
|
// Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
|
|
308
320
|
// Must respect proxy invariants: non-configurable own properties cannot be hidden
|
|
309
321
|
ownKeys(target2) {
|
|
310
|
-
const keys =
|
|
322
|
+
const keys = ReflectOwnKeys2(target2);
|
|
311
323
|
return keys.filter((key) => {
|
|
312
324
|
const keyStr = typeof key === "symbol" ? key.toString() : key;
|
|
313
325
|
if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
|
|
@@ -324,7 +336,7 @@ function createSecureProxy(target, options = {}) {
|
|
|
324
336
|
// Must respect proxy invariants: non-configurable properties must return actual descriptor
|
|
325
337
|
getOwnPropertyDescriptor(target2, property) {
|
|
326
338
|
const propName = typeof property === "symbol" ? property.toString() : property;
|
|
327
|
-
const descriptor =
|
|
339
|
+
const descriptor = ReflectGetOwnPropertyDescriptor2(target2, property);
|
|
328
340
|
if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
|
|
329
341
|
const exactValue = descriptor.value;
|
|
330
342
|
if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
|
|
@@ -383,7 +395,10 @@ function createSecureProxy(target, options = {}) {
|
|
|
383
395
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
|
|
384
396
|
apply(target2, thisArg, argArray) {
|
|
385
397
|
const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
|
|
386
|
-
|
|
398
|
+
if (options.callGate && options.callGate.gates(target2)) {
|
|
399
|
+
return options.callGate.call(target2, unwrappedThis, argArray);
|
|
400
|
+
}
|
|
401
|
+
const result = ReflectApply2(target2, unwrappedThis, argArray);
|
|
387
402
|
if (isProxyable(result)) {
|
|
388
403
|
return proxyWithDepth(result, depth + 1);
|
|
389
404
|
}
|
|
@@ -394,6 +409,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
394
409
|
// host Function constructor — the same escape class the apply trap closes for calls.
|
|
395
410
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
|
|
396
411
|
construct(target2, argArray, newTarget) {
|
|
412
|
+
if (options.callGate && options.callGate.gates(target2)) {
|
|
413
|
+
throw createSafeError("Host functions cannot be called with new", "TypeError");
|
|
414
|
+
}
|
|
397
415
|
const instance = ReflectConstruct(target2, argArray, newTarget === proxy ? target2 : newTarget);
|
|
398
416
|
if (isProxyable(instance)) {
|
|
399
417
|
return proxyWithDepth(instance, depth + 1);
|
|
@@ -401,12 +419,16 @@ function createSecureProxy(target, options = {}) {
|
|
|
401
419
|
return instance;
|
|
402
420
|
}
|
|
403
421
|
});
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
proxyCache.
|
|
422
|
+
if (gateCache) {
|
|
423
|
+
gateCache.set(obj, proxy);
|
|
424
|
+
} else {
|
|
425
|
+
let objCacheMap = proxyCache.get(obj);
|
|
426
|
+
if (!objCacheMap) {
|
|
427
|
+
objCacheMap = /* @__PURE__ */ new Map();
|
|
428
|
+
proxyCache.set(obj, objCacheMap);
|
|
429
|
+
}
|
|
430
|
+
objCacheMap.set(cacheKey, proxy);
|
|
408
431
|
}
|
|
409
|
-
objCacheMap.set(cacheKey, proxy);
|
|
410
432
|
proxySet.add(proxy);
|
|
411
433
|
proxyToTarget.set(proxy, obj);
|
|
412
434
|
return proxy;
|
|
@@ -448,7 +470,16 @@ function isSecureProxy(obj) {
|
|
|
448
470
|
}
|
|
449
471
|
return proxySet.has(obj);
|
|
450
472
|
}
|
|
451
|
-
|
|
473
|
+
function unwrapSecureProxy(value) {
|
|
474
|
+
let current = value;
|
|
475
|
+
while (current !== null && (typeof current === "object" || typeof current === "function")) {
|
|
476
|
+
const target = proxyToTarget.get(current);
|
|
477
|
+
if (target === void 0) break;
|
|
478
|
+
current = target;
|
|
479
|
+
}
|
|
480
|
+
return current;
|
|
481
|
+
}
|
|
482
|
+
var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor2, ReflectOwnKeys2, ReflectApply2, ReflectConstruct, ReflectObject, PINNED_REFLECT_VALUES, FunctionCtor, AsyncFunctionCtor, GeneratorFunctionCtor, AsyncGeneratorFunctionCtor, MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, gatedProxyCaches, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
|
|
452
483
|
var init_secure_proxy = __esm({
|
|
453
484
|
"libs/core/src/secure-proxy.ts"() {
|
|
454
485
|
"use strict";
|
|
@@ -459,13 +490,13 @@ var init_secure_proxy = __esm({
|
|
|
459
490
|
ReflectGet = Reflect.get;
|
|
460
491
|
ReflectSet = Reflect.set;
|
|
461
492
|
ReflectDefineProperty = Reflect.defineProperty;
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
493
|
+
ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
|
|
494
|
+
ReflectOwnKeys2 = Reflect.ownKeys;
|
|
495
|
+
ReflectApply2 = Reflect.apply;
|
|
465
496
|
ReflectConstruct = Reflect.construct;
|
|
466
497
|
ReflectObject = Reflect;
|
|
467
498
|
PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
|
|
468
|
-
for (const key of
|
|
499
|
+
for (const key of ReflectOwnKeys2(ReflectObject)) {
|
|
469
500
|
PINNED_REFLECT_VALUES.set(key, ReflectGet(ReflectObject, key));
|
|
470
501
|
}
|
|
471
502
|
FunctionCtor = Function;
|
|
@@ -574,6 +605,7 @@ var init_secure_proxy = __esm({
|
|
|
574
605
|
// 'call',
|
|
575
606
|
// 'apply',
|
|
576
607
|
]);
|
|
608
|
+
gatedProxyCaches = /* @__PURE__ */ new WeakMap();
|
|
577
609
|
proxyCache = /* @__PURE__ */ new WeakMap();
|
|
578
610
|
proxySet = /* @__PURE__ */ new WeakSet();
|
|
579
611
|
proxyToTarget = /* @__PURE__ */ new WeakMap();
|
|
@@ -990,6 +1022,26 @@ var init_reference_resolver = __esm({
|
|
|
990
1022
|
});
|
|
991
1023
|
|
|
992
1024
|
// libs/core/src/value-sanitizer.ts
|
|
1025
|
+
function hasBrand(builtin, value) {
|
|
1026
|
+
if (!builtin) return false;
|
|
1027
|
+
try {
|
|
1028
|
+
ReflectApply3(builtin, value, []);
|
|
1029
|
+
return true;
|
|
1030
|
+
} catch {
|
|
1031
|
+
return false;
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
function regExpToString(value) {
|
|
1035
|
+
let flags = "";
|
|
1036
|
+
for (const [flag, getter] of RegExpFlagGetters) {
|
|
1037
|
+
if (getter && ReflectApply3(getter, value, [])) flags += flag;
|
|
1038
|
+
}
|
|
1039
|
+
return `/${ReflectApply3(RegExpProtoSourceGetter, value, [])}/${flags}`;
|
|
1040
|
+
}
|
|
1041
|
+
function isPlainObject(value) {
|
|
1042
|
+
const prototype = ObjectGetPrototypeOf2(value);
|
|
1043
|
+
return prototype === null || ObjectGetPrototypeOf2(prototype) === null;
|
|
1044
|
+
}
|
|
993
1045
|
function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
|
|
994
1046
|
const maxDepth = options.maxDepth ?? 20;
|
|
995
1047
|
const maxProperties = options.maxProperties ?? 1e4;
|
|
@@ -1050,12 +1102,14 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1050
1102
|
}
|
|
1051
1103
|
return result;
|
|
1052
1104
|
}
|
|
1053
|
-
|
|
1054
|
-
|
|
1105
|
+
const inspected = options.unwrap ? options.unwrap(value) : value;
|
|
1106
|
+
const isPlain = isPlainObject(inspected);
|
|
1107
|
+
if (!isPlain && hasBrand(DateProtoGetTime, inspected)) {
|
|
1108
|
+
const time = ReflectApply3(DateProtoGetTime, inspected, []);
|
|
1055
1109
|
if (allowDates) {
|
|
1056
1110
|
return new Date(time);
|
|
1057
1111
|
}
|
|
1058
|
-
return
|
|
1112
|
+
return ReflectApply3(DateProtoToISOString, inspected, []);
|
|
1059
1113
|
}
|
|
1060
1114
|
if (value instanceof Error) {
|
|
1061
1115
|
const rawName = ReflectGet3(value, "name");
|
|
@@ -1071,12 +1125,12 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1071
1125
|
}
|
|
1072
1126
|
return { error: message };
|
|
1073
1127
|
}
|
|
1074
|
-
if (
|
|
1075
|
-
return
|
|
1128
|
+
if (!isPlain && hasBrand(RegExpProtoSourceGetter, inspected)) {
|
|
1129
|
+
return regExpToString(inspected);
|
|
1076
1130
|
}
|
|
1077
|
-
if (
|
|
1131
|
+
if (!isPlain && hasBrand(MapProtoSizeGetter, inspected)) {
|
|
1078
1132
|
const sanitizedMap = ObjectCreate(null);
|
|
1079
|
-
const entries =
|
|
1133
|
+
const entries = ReflectApply3(MapProtoEntries, inspected, []);
|
|
1080
1134
|
for (const [key, val] of entries) {
|
|
1081
1135
|
if (typeof key !== "string") continue;
|
|
1082
1136
|
if (DANGEROUS_KEYS.has(key)) continue;
|
|
@@ -1085,8 +1139,8 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1085
1139
|
}
|
|
1086
1140
|
return sanitizedMap;
|
|
1087
1141
|
}
|
|
1088
|
-
if (
|
|
1089
|
-
const iter =
|
|
1142
|
+
if (!isPlain && hasBrand(SetProtoSizeGetter, inspected)) {
|
|
1143
|
+
const iter = ReflectApply3(SetProtoValues, inspected, []);
|
|
1090
1144
|
const result = [];
|
|
1091
1145
|
for (const item of iter) {
|
|
1092
1146
|
context.propCount.count++;
|
|
@@ -1245,23 +1299,420 @@ function checkSerializedSize(value, maxBytes) {
|
|
|
1245
1299
|
return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
|
|
1246
1300
|
}
|
|
1247
1301
|
}
|
|
1248
|
-
var DANGEROUS_KEYS,
|
|
1302
|
+
var DANGEROUS_KEYS, ReflectApply3, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, ObjectGetPrototypeOf2, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoSourceGetter, RegExpFlagGetters, MapProtoSizeGetter, SetProtoSizeGetter;
|
|
1249
1303
|
var init_value_sanitizer = __esm({
|
|
1250
1304
|
"libs/core/src/value-sanitizer.ts"() {
|
|
1251
1305
|
"use strict";
|
|
1252
1306
|
DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
|
|
1253
|
-
|
|
1307
|
+
ReflectApply3 = Reflect.apply;
|
|
1254
1308
|
ReflectGet3 = Reflect.get;
|
|
1255
1309
|
ArrayIsArray = Array.isArray;
|
|
1256
1310
|
ObjectKeys = Object.keys;
|
|
1257
1311
|
ObjectCreate = Object.create;
|
|
1312
|
+
ObjectGetPrototypeOf2 = Object.getPrototypeOf;
|
|
1258
1313
|
NumberIsFinite2 = Number.isFinite;
|
|
1259
1314
|
MathFloor2 = Math.floor;
|
|
1260
1315
|
MapProtoEntries = Map.prototype.entries;
|
|
1261
1316
|
SetProtoValues = Set.prototype.values;
|
|
1262
1317
|
DateProtoGetTime = Date.prototype.getTime;
|
|
1263
1318
|
DateProtoToISOString = Date.prototype.toISOString;
|
|
1264
|
-
|
|
1319
|
+
RegExpProtoSourceGetter = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get;
|
|
1320
|
+
RegExpFlagGetters = [
|
|
1321
|
+
["d", "hasIndices"],
|
|
1322
|
+
["g", "global"],
|
|
1323
|
+
["i", "ignoreCase"],
|
|
1324
|
+
["m", "multiline"],
|
|
1325
|
+
["s", "dotAll"],
|
|
1326
|
+
["u", "unicode"],
|
|
1327
|
+
["v", "unicodeSets"],
|
|
1328
|
+
["y", "sticky"]
|
|
1329
|
+
].map(([flag, property]) => [flag, Object.getOwnPropertyDescriptor(RegExp.prototype, property)?.get]);
|
|
1330
|
+
MapProtoSizeGetter = Object.getOwnPropertyDescriptor(Map.prototype, "size")?.get;
|
|
1331
|
+
SetProtoSizeGetter = Object.getOwnPropertyDescriptor(Set.prototype, "size")?.get;
|
|
1332
|
+
}
|
|
1333
|
+
});
|
|
1334
|
+
|
|
1335
|
+
// libs/core/src/global-function-gate.ts
|
|
1336
|
+
function isBuiltinMethod(fn) {
|
|
1337
|
+
return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHODS.has(fn);
|
|
1338
|
+
}
|
|
1339
|
+
function resolveMaxGlobalFunctionCalls(config) {
|
|
1340
|
+
const explicit = config.maxGlobalFunctionCalls;
|
|
1341
|
+
if (typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 0) {
|
|
1342
|
+
return Math.floor(explicit);
|
|
1343
|
+
}
|
|
1344
|
+
const maxToolCalls = typeof config.maxToolCalls === "number" && Number.isFinite(config.maxToolCalls) ? config.maxToolCalls : 100;
|
|
1345
|
+
return Math.max(0, Math.floor(maxToolCalls)) * DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL;
|
|
1346
|
+
}
|
|
1347
|
+
function globalFunctionLimitMessage(max) {
|
|
1348
|
+
return `Maximum global function call limit exceeded (${max}). This limit prevents runaway calls into host functions.`;
|
|
1349
|
+
}
|
|
1350
|
+
function resultLimits(context) {
|
|
1351
|
+
const { config } = context;
|
|
1352
|
+
return {
|
|
1353
|
+
maxDepth: config.maxSanitizeDepth,
|
|
1354
|
+
maxProperties: config.maxSanitizeProperties,
|
|
1355
|
+
maxPayloadBytes: config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
function truncate(value, max) {
|
|
1359
|
+
return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
|
|
1360
|
+
}
|
|
1361
|
+
function failure(error) {
|
|
1362
|
+
let name = "Error";
|
|
1363
|
+
let message = "Global function call failed";
|
|
1364
|
+
try {
|
|
1365
|
+
if (error && typeof error === "object") {
|
|
1366
|
+
const rawName = error.name;
|
|
1367
|
+
const rawMessage = error.message;
|
|
1368
|
+
if (typeof rawName === "string" && rawName) name = rawName;
|
|
1369
|
+
if (typeof rawMessage === "string" && rawMessage) message = rawMessage;
|
|
1370
|
+
} else if (typeof error === "string" && error) {
|
|
1371
|
+
message = error;
|
|
1372
|
+
}
|
|
1373
|
+
} catch {
|
|
1374
|
+
}
|
|
1375
|
+
return {
|
|
1376
|
+
ok: false,
|
|
1377
|
+
name: truncate(name, MAX_ERROR_NAME_LENGTH),
|
|
1378
|
+
message: truncate(message, MAX_ERROR_MESSAGE_LENGTH)
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
function jsonReplacer(_key, value) {
|
|
1382
|
+
if (typeof value === "bigint") return value.toString();
|
|
1383
|
+
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
1384
|
+
return value;
|
|
1385
|
+
}
|
|
1386
|
+
function utf8ByteLength(value) {
|
|
1387
|
+
return Buffer.byteLength(value, "utf8");
|
|
1388
|
+
}
|
|
1389
|
+
function encodeResult(value, limits) {
|
|
1390
|
+
if (value === void 0) return { ok: true };
|
|
1391
|
+
let json;
|
|
1392
|
+
try {
|
|
1393
|
+
const sanitized = sanitizeValue(value, {
|
|
1394
|
+
maxDepth: limits.maxDepth,
|
|
1395
|
+
maxProperties: limits.maxProperties,
|
|
1396
|
+
allowDates: false,
|
|
1397
|
+
allowErrors: true
|
|
1398
|
+
});
|
|
1399
|
+
json = JsonStringify(sanitized, jsonReplacer);
|
|
1400
|
+
} catch {
|
|
1401
|
+
return { ok: false, name: "GlobalFunctionError", message: UNSAFE_RESULT_MESSAGE };
|
|
1402
|
+
}
|
|
1403
|
+
if (json === void 0) return { ok: true };
|
|
1404
|
+
if (utf8ByteLength(json) > limits.maxPayloadBytes) {
|
|
1405
|
+
return {
|
|
1406
|
+
ok: false,
|
|
1407
|
+
name: "GlobalFunctionError",
|
|
1408
|
+
message: `Global function result exceeds maximum size (${limits.maxPayloadBytes} bytes)`
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
return { ok: true, json };
|
|
1412
|
+
}
|
|
1413
|
+
function isThenable(value) {
|
|
1414
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return false;
|
|
1415
|
+
try {
|
|
1416
|
+
return typeof value.then === "function";
|
|
1417
|
+
} catch {
|
|
1418
|
+
return false;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
function invokeGlobalFunction(fn, thisArg, args, limits) {
|
|
1422
|
+
if (typeof fn !== "function") {
|
|
1423
|
+
return { ok: false, name: "TypeError", message: "Global is not a function" };
|
|
1424
|
+
}
|
|
1425
|
+
let result;
|
|
1426
|
+
try {
|
|
1427
|
+
result = ReflectApply4(fn, thisArg, ArrayIsArray2(args) ? args : []);
|
|
1428
|
+
} catch (error) {
|
|
1429
|
+
return failure(error);
|
|
1430
|
+
}
|
|
1431
|
+
if (isThenable(result)) {
|
|
1432
|
+
return Promise.resolve(result).then(
|
|
1433
|
+
(value) => encodeResult(value, limits),
|
|
1434
|
+
(error) => failure(error)
|
|
1435
|
+
);
|
|
1436
|
+
}
|
|
1437
|
+
return encodeResult(result, limits);
|
|
1438
|
+
}
|
|
1439
|
+
function toEnvelope(outcome) {
|
|
1440
|
+
if (outcome.ok) {
|
|
1441
|
+
return outcome.json === void 0 ? '{"v":1,"ok":true}' : `{"v":1,"ok":true,"value":${outcome.json}}`;
|
|
1442
|
+
}
|
|
1443
|
+
return JsonStringify({ v: 1, ok: false, error: { name: outcome.name, message: outcome.message } });
|
|
1444
|
+
}
|
|
1445
|
+
function createHostGlobalFunctionInvoker(context) {
|
|
1446
|
+
const limits = resultLimits(context);
|
|
1447
|
+
return (fn, thisArg, args) => {
|
|
1448
|
+
const outcome = invokeGlobalFunction(fn, thisArg, args, limits);
|
|
1449
|
+
return outcome instanceof Promise ? outcome.then(toEnvelope) : toEnvelope(outcome);
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
function createGlobalFunctionGate(context, realm) {
|
|
1453
|
+
const limits = resultLimits(context);
|
|
1454
|
+
const max = resolveMaxGlobalFunctionCalls(context.config);
|
|
1455
|
+
let calls = 0;
|
|
1456
|
+
const settle = (outcome) => {
|
|
1457
|
+
if (!outcome.ok) {
|
|
1458
|
+
throw createSafeError(outcome.message, outcome.name);
|
|
1459
|
+
}
|
|
1460
|
+
return outcome.json === void 0 ? void 0 : realm.parseJson(outcome.json);
|
|
1461
|
+
};
|
|
1462
|
+
return {
|
|
1463
|
+
gates: (target) => !isBuiltinMethod(target),
|
|
1464
|
+
call: (target, thisArg, args) => {
|
|
1465
|
+
if (context.aborted) {
|
|
1466
|
+
throw createSafeError("Execution aborted");
|
|
1467
|
+
}
|
|
1468
|
+
calls++;
|
|
1469
|
+
if (calls > max) {
|
|
1470
|
+
throw createSafeError(globalFunctionLimitMessage(max));
|
|
1471
|
+
}
|
|
1472
|
+
const outcome = invokeGlobalFunction(target, thisArg, args, limits);
|
|
1473
|
+
if (outcome instanceof Promise) {
|
|
1474
|
+
return realm.adoptPromise(outcome.then(settle));
|
|
1475
|
+
}
|
|
1476
|
+
return settle(outcome);
|
|
1477
|
+
}
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
var ReflectApply4, ReflectOwnKeys3, ObjectGetOwnPropertyDescriptor2, ObjectGetPrototypeOf3, ArrayIsArray2, JsonStringify, BUILTIN_METHODS, DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL, DEFAULT_MAX_PAYLOAD_BYTES, MAX_ERROR_MESSAGE_LENGTH, MAX_ERROR_NAME_LENGTH, UNSAFE_RESULT_MESSAGE;
|
|
1481
|
+
var init_global_function_gate = __esm({
|
|
1482
|
+
"libs/core/src/global-function-gate.ts"() {
|
|
1483
|
+
"use strict";
|
|
1484
|
+
init_value_sanitizer();
|
|
1485
|
+
init_safe_error();
|
|
1486
|
+
ReflectApply4 = Reflect.apply;
|
|
1487
|
+
ReflectOwnKeys3 = Reflect.ownKeys;
|
|
1488
|
+
ObjectGetOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
|
|
1489
|
+
ObjectGetPrototypeOf3 = Object.getPrototypeOf;
|
|
1490
|
+
ArrayIsArray2 = Array.isArray;
|
|
1491
|
+
JsonStringify = JSON.stringify;
|
|
1492
|
+
BUILTIN_METHODS = (() => {
|
|
1493
|
+
const methods = /* @__PURE__ */ new WeakSet();
|
|
1494
|
+
const typedArrays = [
|
|
1495
|
+
Int8Array,
|
|
1496
|
+
Uint8Array,
|
|
1497
|
+
Uint8ClampedArray,
|
|
1498
|
+
Int16Array,
|
|
1499
|
+
Uint16Array,
|
|
1500
|
+
Int32Array,
|
|
1501
|
+
Uint32Array,
|
|
1502
|
+
Float32Array,
|
|
1503
|
+
Float64Array,
|
|
1504
|
+
BigInt64Array,
|
|
1505
|
+
BigUint64Array
|
|
1506
|
+
];
|
|
1507
|
+
const arrayIteratorPrototype = ObjectGetPrototypeOf3([][Symbol.iterator]());
|
|
1508
|
+
const prototypes = [
|
|
1509
|
+
Object.prototype,
|
|
1510
|
+
Array.prototype,
|
|
1511
|
+
String.prototype,
|
|
1512
|
+
Number.prototype,
|
|
1513
|
+
Boolean.prototype,
|
|
1514
|
+
Symbol.prototype,
|
|
1515
|
+
BigInt.prototype,
|
|
1516
|
+
Date.prototype,
|
|
1517
|
+
RegExp.prototype,
|
|
1518
|
+
Error.prototype,
|
|
1519
|
+
EvalError.prototype,
|
|
1520
|
+
RangeError.prototype,
|
|
1521
|
+
ReferenceError.prototype,
|
|
1522
|
+
SyntaxError.prototype,
|
|
1523
|
+
TypeError.prototype,
|
|
1524
|
+
URIError.prototype,
|
|
1525
|
+
Map.prototype,
|
|
1526
|
+
Set.prototype,
|
|
1527
|
+
WeakMap.prototype,
|
|
1528
|
+
WeakSet.prototype,
|
|
1529
|
+
Promise.prototype,
|
|
1530
|
+
ArrayBuffer.prototype,
|
|
1531
|
+
DataView.prototype,
|
|
1532
|
+
ObjectGetPrototypeOf3(Uint8Array.prototype),
|
|
1533
|
+
// %TypedArray%.prototype
|
|
1534
|
+
...typedArrays.map((TypedArray) => TypedArray.prototype),
|
|
1535
|
+
arrayIteratorPrototype,
|
|
1536
|
+
ObjectGetPrototypeOf3(arrayIteratorPrototype),
|
|
1537
|
+
// %IteratorPrototype%
|
|
1538
|
+
ObjectGetPrototypeOf3((/* @__PURE__ */ new Map())[Symbol.iterator]()),
|
|
1539
|
+
ObjectGetPrototypeOf3((/* @__PURE__ */ new Set())[Symbol.iterator]()),
|
|
1540
|
+
ObjectGetPrototypeOf3(""[Symbol.iterator]())
|
|
1541
|
+
];
|
|
1542
|
+
for (const prototype of prototypes) {
|
|
1543
|
+
if (prototype === null || typeof prototype !== "object") continue;
|
|
1544
|
+
for (const key of ReflectOwnKeys3(prototype)) {
|
|
1545
|
+
if (key === "constructor") continue;
|
|
1546
|
+
const descriptor = ObjectGetOwnPropertyDescriptor2(prototype, key);
|
|
1547
|
+
if (descriptor && typeof descriptor.value === "function") {
|
|
1548
|
+
methods.add(descriptor.value);
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
return methods;
|
|
1553
|
+
})();
|
|
1554
|
+
DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
|
|
1555
|
+
DEFAULT_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
1556
|
+
MAX_ERROR_MESSAGE_LENGTH = 4096;
|
|
1557
|
+
MAX_ERROR_NAME_LENGTH = 128;
|
|
1558
|
+
UNSAFE_RESULT_MESSAGE = "Global function returned a value that cannot be passed into the sandbox (functions, symbols, and values beyond the sanitization depth or size limits are not allowed)";
|
|
1559
|
+
}
|
|
1560
|
+
});
|
|
1561
|
+
|
|
1562
|
+
// libs/core/src/stack-trace.ts
|
|
1563
|
+
function redactLine(line) {
|
|
1564
|
+
let out = line.length > MAX_LINE_LENGTH ? `${line.slice(0, MAX_LINE_LENGTH)}\u2026` : line;
|
|
1565
|
+
for (const pattern of SENSITIVE_STACK_PATTERNS) {
|
|
1566
|
+
pattern.lastIndex = 0;
|
|
1567
|
+
out = out.replace(pattern, "[REDACTED]");
|
|
1568
|
+
}
|
|
1569
|
+
return out;
|
|
1570
|
+
}
|
|
1571
|
+
function sanitizeStackTrace(stack, sanitize = true) {
|
|
1572
|
+
if (typeof stack !== "string" || !stack || !sanitize) return stack;
|
|
1573
|
+
const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
|
|
1574
|
+
return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
|
|
1575
|
+
}
|
|
1576
|
+
var SENSITIVE_STACK_PATTERNS, FRAME_LINE, MAX_STACK_LENGTH, MAX_LINE_LENGTH, REDACTED_FRAME;
|
|
1577
|
+
var init_stack_trace = __esm({
|
|
1578
|
+
"libs/core/src/stack-trace.ts"() {
|
|
1579
|
+
"use strict";
|
|
1580
|
+
SENSITIVE_STACK_PATTERNS = [
|
|
1581
|
+
// Unix file system paths
|
|
1582
|
+
/\/Users\/[^/]+\/[^\s):]*/gi,
|
|
1583
|
+
// macOS home directories
|
|
1584
|
+
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
1585
|
+
// Linux home directories
|
|
1586
|
+
/\/var\/[^\s):]*/gi,
|
|
1587
|
+
// System var directories
|
|
1588
|
+
/\/opt\/[^\s):]*/gi,
|
|
1589
|
+
// Optional software
|
|
1590
|
+
/\/tmp\/[^\s):]*/gi,
|
|
1591
|
+
// Temporary files
|
|
1592
|
+
/\/etc\/[^\s):]*/gi,
|
|
1593
|
+
// System configuration
|
|
1594
|
+
/\/root\/[^\s):]*/gi,
|
|
1595
|
+
// Root home directory
|
|
1596
|
+
/\/mnt\/[^\s):]*/gi,
|
|
1597
|
+
// Mount points
|
|
1598
|
+
/\/srv\/[^\s):]*/gi,
|
|
1599
|
+
// Service data
|
|
1600
|
+
/\/data\/[^\s):]*/gi,
|
|
1601
|
+
// Data directories
|
|
1602
|
+
/\/app\/[^\s):]*/gi,
|
|
1603
|
+
// Application directories
|
|
1604
|
+
/\/proc\/[^\s):]*/gi,
|
|
1605
|
+
// Process information
|
|
1606
|
+
/\/sys\/[^\s):]*/gi,
|
|
1607
|
+
// System files
|
|
1608
|
+
// Windows paths
|
|
1609
|
+
/\\\\[^\s):]*/g,
|
|
1610
|
+
// UNC paths
|
|
1611
|
+
/[A-Z]:\\[^\s):]+/gi,
|
|
1612
|
+
// Windows drive paths
|
|
1613
|
+
// URL-based paths
|
|
1614
|
+
/file:\/\/[^\s):]+/gi,
|
|
1615
|
+
// File URLs
|
|
1616
|
+
/webpack:\/\/[^\s):]+/gi,
|
|
1617
|
+
// Webpack paths
|
|
1618
|
+
/%2F[^\s):]+/gi,
|
|
1619
|
+
// URL-encoded paths
|
|
1620
|
+
// Package managers and node
|
|
1621
|
+
/node_modules\/[^\s):]+/gi,
|
|
1622
|
+
// Node modules paths
|
|
1623
|
+
/\/nix\/store\/[^\s):]*/gi,
|
|
1624
|
+
// Nix store paths
|
|
1625
|
+
/\.npm\/[^\s):]*/gi,
|
|
1626
|
+
// NPM cache
|
|
1627
|
+
/\.yarn\/[^\s):]*/gi,
|
|
1628
|
+
// Yarn cache
|
|
1629
|
+
/\.pnpm\/[^\s):]*/gi,
|
|
1630
|
+
// PNPM cache
|
|
1631
|
+
// Container and orchestration
|
|
1632
|
+
/\/run\/secrets\/[^\s):]*/gi,
|
|
1633
|
+
// Docker/K8s secrets
|
|
1634
|
+
/\/var\/run\/[^\s):]*/gi,
|
|
1635
|
+
// Runtime directories
|
|
1636
|
+
/\/docker\/[^\s):]*/gi,
|
|
1637
|
+
// Docker paths
|
|
1638
|
+
/\/containers\/[^\s):]*/gi,
|
|
1639
|
+
// Container paths
|
|
1640
|
+
/\/kubelet\/[^\s):]*/gi,
|
|
1641
|
+
// Kubernetes kubelet
|
|
1642
|
+
// CI/CD systems
|
|
1643
|
+
/\/github\/workspace\/[^\s):]*/gi,
|
|
1644
|
+
// GitHub Actions
|
|
1645
|
+
/\/runner\/[^\s):]*/gi,
|
|
1646
|
+
// GitHub/GitLab runner
|
|
1647
|
+
/\/builds\/[^\s):]*/gi,
|
|
1648
|
+
// CI builds
|
|
1649
|
+
/\/workspace\/[^\s):]*/gi,
|
|
1650
|
+
// Generic workspace
|
|
1651
|
+
/\/pipeline\/[^\s):]*/gi,
|
|
1652
|
+
// CI pipelines
|
|
1653
|
+
/\/jenkins\/[^\s):]*/gi,
|
|
1654
|
+
// Jenkins
|
|
1655
|
+
/\/bamboo\/[^\s):]*/gi,
|
|
1656
|
+
// Bamboo
|
|
1657
|
+
/\/teamcity\/[^\s):]*/gi,
|
|
1658
|
+
// TeamCity
|
|
1659
|
+
/\/circleci\/[^\s):]*/gi,
|
|
1660
|
+
// CircleCI
|
|
1661
|
+
// Cloud providers
|
|
1662
|
+
/\/aws\/[^\s):]*/gi,
|
|
1663
|
+
// AWS paths
|
|
1664
|
+
/\/gcloud\/[^\s):]*/gi,
|
|
1665
|
+
// Google Cloud
|
|
1666
|
+
/\/azure\/[^\s):]*/gi,
|
|
1667
|
+
// Azure paths
|
|
1668
|
+
/s3:\/\/[^\s):]+/gi,
|
|
1669
|
+
// S3 URIs
|
|
1670
|
+
/gs:\/\/[^\s):]+/gi,
|
|
1671
|
+
// GCS URIs
|
|
1672
|
+
// Secrets and credentials (patterns that might appear in paths or errors)
|
|
1673
|
+
/[A-Z0-9]{20,}/g,
|
|
1674
|
+
// AWS-style access keys (20+ uppercase chars)
|
|
1675
|
+
/sk-[a-zA-Z0-9]{32,}/g,
|
|
1676
|
+
// OpenAI/Stripe-style secret keys
|
|
1677
|
+
/ghp_[a-zA-Z0-9]{36,}/g,
|
|
1678
|
+
// GitHub personal access tokens
|
|
1679
|
+
/gho_[a-zA-Z0-9]{36,}/g,
|
|
1680
|
+
// GitHub OAuth tokens
|
|
1681
|
+
/github_pat_[a-zA-Z0-9_]{22,}/g,
|
|
1682
|
+
// GitHub fine-grained tokens
|
|
1683
|
+
/xox[baprs]-[a-zA-Z0-9-]+/g,
|
|
1684
|
+
// Slack tokens
|
|
1685
|
+
/Bearer\s+[a-zA-Z0-9._-]+/gi,
|
|
1686
|
+
// Bearer tokens
|
|
1687
|
+
/Basic\s+[a-zA-Z0-9+/=]+/gi,
|
|
1688
|
+
// Basic auth
|
|
1689
|
+
// Internal network info
|
|
1690
|
+
/(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
|
|
1691
|
+
// Private IPs
|
|
1692
|
+
/[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
|
|
1693
|
+
// Internal hostnames
|
|
1694
|
+
/localhost:\d+/gi,
|
|
1695
|
+
// Localhost with port
|
|
1696
|
+
/127\.0\.0\.1:\d+/gi,
|
|
1697
|
+
// Loopback with port
|
|
1698
|
+
// User information
|
|
1699
|
+
/\/u\/[^/]+\//gi,
|
|
1700
|
+
// User subdirectories
|
|
1701
|
+
/~[a-z_][a-z0-9_-]*/gi,
|
|
1702
|
+
// Unix user home shorthand
|
|
1703
|
+
// Anything else that is still shaped like a location: an absolute path of two or more
|
|
1704
|
+
// segments, a URL, or a script location such as `agentscript.js:3` / `index.mjs:10:5`.
|
|
1705
|
+
/[a-z][a-z0-9+.-]*:\/\/[^\s)]+/gi,
|
|
1706
|
+
// Other URLs (http://host/bundle.js:1:2)
|
|
1707
|
+
/(?:\/[\w.@%+-]+){2,}\/?/g,
|
|
1708
|
+
// Remaining absolute paths
|
|
1709
|
+
/[\w.@-]+\.(?:[cm]?[jt]sx?|json|node|wasm)(?::\d+){1,2}/gi
|
|
1710
|
+
// file.ext:line[:column]
|
|
1711
|
+
];
|
|
1712
|
+
FRAME_LINE = /^\s*at\s/;
|
|
1713
|
+
MAX_STACK_LENGTH = 16 * 1024;
|
|
1714
|
+
MAX_LINE_LENGTH = 1e3;
|
|
1715
|
+
REDACTED_FRAME = " at [REDACTED]";
|
|
1265
1716
|
}
|
|
1266
1717
|
});
|
|
1267
1718
|
|
|
@@ -1420,16 +1871,16 @@ var init_memory_tracker = __esm({
|
|
|
1420
1871
|
});
|
|
1421
1872
|
|
|
1422
1873
|
// libs/core/src/tool-bridge.ts
|
|
1423
|
-
function
|
|
1874
|
+
function utf8ByteLength2(value) {
|
|
1424
1875
|
return Buffer.byteLength(value, "utf8");
|
|
1425
1876
|
}
|
|
1426
|
-
function
|
|
1877
|
+
function jsonReplacer2(_key, value) {
|
|
1427
1878
|
if (typeof value === "bigint") return value.toString();
|
|
1428
1879
|
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
1429
1880
|
return value;
|
|
1430
1881
|
}
|
|
1431
1882
|
function safeJsonStringify(value) {
|
|
1432
|
-
return JSON.stringify(value,
|
|
1883
|
+
return JSON.stringify(value, jsonReplacer2);
|
|
1433
1884
|
}
|
|
1434
1885
|
function truncateForErrorMessage(value, maxChars) {
|
|
1435
1886
|
if (value.length <= maxChars) return value;
|
|
@@ -1470,7 +1921,7 @@ function serializeResponse(response, maxPayloadBytes) {
|
|
|
1470
1921
|
}
|
|
1471
1922
|
});
|
|
1472
1923
|
}
|
|
1473
|
-
if (
|
|
1924
|
+
if (utf8ByteLength2(json) <= maxPayloadBytes) return json;
|
|
1474
1925
|
const minimal = {
|
|
1475
1926
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1476
1927
|
ok: false,
|
|
@@ -1526,7 +1977,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1526
1977
|
maxPayloadBytes
|
|
1527
1978
|
);
|
|
1528
1979
|
}
|
|
1529
|
-
if (
|
|
1980
|
+
if (utf8ByteLength2(requestJson) > maxPayloadBytes) {
|
|
1530
1981
|
return serializeResponse(
|
|
1531
1982
|
{
|
|
1532
1983
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -1667,7 +2118,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1667
2118
|
{
|
|
1668
2119
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1669
2120
|
ok: false,
|
|
1670
|
-
error: safeError
|
|
2121
|
+
error: { ...safeError, toolError: true }
|
|
1671
2122
|
},
|
|
1672
2123
|
maxPayloadBytes
|
|
1673
2124
|
);
|
|
@@ -1691,13 +2142,13 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1691
2142
|
{
|
|
1692
2143
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1693
2144
|
ok: false,
|
|
1694
|
-
error: safeError
|
|
2145
|
+
error: { ...safeError, toolError: true }
|
|
1695
2146
|
},
|
|
1696
2147
|
maxPayloadBytes
|
|
1697
2148
|
);
|
|
1698
2149
|
}
|
|
1699
2150
|
if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
|
|
1700
|
-
const size =
|
|
2151
|
+
const size = utf8ByteLength2(sanitizedResult);
|
|
1701
2152
|
if (size >= referenceConfig.extractionThreshold) {
|
|
1702
2153
|
try {
|
|
1703
2154
|
const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
|
|
@@ -1721,12 +2172,12 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1721
2172
|
{
|
|
1722
2173
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1723
2174
|
ok: false,
|
|
1724
|
-
error: safeError
|
|
2175
|
+
error: { ...safeError, toolError: true }
|
|
1725
2176
|
},
|
|
1726
2177
|
maxPayloadBytes
|
|
1727
2178
|
);
|
|
1728
2179
|
}
|
|
1729
|
-
if (
|
|
2180
|
+
if (utf8ByteLength2(okJson) > maxPayloadBytes) {
|
|
1730
2181
|
return serializeResponse(
|
|
1731
2182
|
{
|
|
1732
2183
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -1734,7 +2185,8 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1734
2185
|
error: {
|
|
1735
2186
|
name: "ToolBridgeError",
|
|
1736
2187
|
message: `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
1737
|
-
code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
|
|
2188
|
+
code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
|
|
2189
|
+
toolError: true
|
|
1738
2190
|
}
|
|
1739
2191
|
},
|
|
1740
2192
|
maxPayloadBytes
|
|
@@ -1764,6 +2216,64 @@ var init_tool_bridge = __esm({
|
|
|
1764
2216
|
}
|
|
1765
2217
|
});
|
|
1766
2218
|
|
|
2219
|
+
// libs/core/src/tool-namespaces.ts
|
|
2220
|
+
function buildToolNamespaceBindings(install, callTool, namespaces) {
|
|
2221
|
+
if (namespaces.length === 0) return [];
|
|
2222
|
+
if (typeof install !== "function") {
|
|
2223
|
+
throw new Error("Tool namespace factory is not available in the sandbox");
|
|
2224
|
+
}
|
|
2225
|
+
const built = install(
|
|
2226
|
+
callTool,
|
|
2227
|
+
JSON.stringify(namespaces)
|
|
2228
|
+
);
|
|
2229
|
+
return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
|
|
2230
|
+
}
|
|
2231
|
+
var TOOL_NAMESPACE_FACTORY_SOURCE;
|
|
2232
|
+
var init_tool_namespaces = __esm({
|
|
2233
|
+
"libs/core/src/tool-namespaces.ts"() {
|
|
2234
|
+
"use strict";
|
|
2235
|
+
TOOL_NAMESPACE_FACTORY_SOURCE = `
|
|
2236
|
+
(function () {
|
|
2237
|
+
'use strict';
|
|
2238
|
+
var parse = JSON.parse;
|
|
2239
|
+
var freeze = Object.freeze;
|
|
2240
|
+
var isArray = Array.isArray;
|
|
2241
|
+
|
|
2242
|
+
function isSafeKey(key) {
|
|
2243
|
+
return typeof key === 'string' && key.length > 0 &&
|
|
2244
|
+
!(key.charAt(0) === '_' && key.charAt(1) === '_') &&
|
|
2245
|
+
key !== 'constructor' && key !== 'prototype';
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
function bind(callTool, toolName) {
|
|
2249
|
+
return (args, options) => callTool(toolName, args === undefined ? {} : args, options);
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
return function install(callTool, namespacesJson) {
|
|
2253
|
+
var spec = parse(namespacesJson);
|
|
2254
|
+
var namespaces = { __proto__: null };
|
|
2255
|
+
if (isArray(spec)) {
|
|
2256
|
+
for (var i = 0; i < spec.length; i++) {
|
|
2257
|
+
var ns = spec[i];
|
|
2258
|
+
if (!ns || !isSafeKey(ns.name) || !isArray(ns.methods)) continue;
|
|
2259
|
+
var target = { __proto__: null };
|
|
2260
|
+
for (var j = 0; j < ns.methods.length; j++) {
|
|
2261
|
+
var method = ns.methods[j];
|
|
2262
|
+
if (!method || !isSafeKey(method.name) || typeof method.toolName !== 'string') continue;
|
|
2263
|
+
target[method.name] = bind(callTool, method.toolName);
|
|
2264
|
+
}
|
|
2265
|
+
freeze(target);
|
|
2266
|
+
namespaces[ns.name] = target;
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
freeze(namespaces);
|
|
2270
|
+
return namespaces;
|
|
2271
|
+
};
|
|
2272
|
+
})()
|
|
2273
|
+
`.trim();
|
|
2274
|
+
}
|
|
2275
|
+
});
|
|
2276
|
+
|
|
1767
2277
|
// libs/core/src/double-vm/parent-vm-bootstrap.ts
|
|
1768
2278
|
function generateSanitizeContextCode(securityLevel) {
|
|
1769
2279
|
const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];
|
|
@@ -1805,7 +2315,9 @@ function generateParentVmBootstrap(options) {
|
|
|
1805
2315
|
blockedProperties,
|
|
1806
2316
|
allowComposites = false,
|
|
1807
2317
|
memoryLimit = 0,
|
|
1808
|
-
throwOnBlocked = true
|
|
2318
|
+
throwOnBlocked = true,
|
|
2319
|
+
maxGlobalFunctionCalls = 1e3,
|
|
2320
|
+
toolNamespaces = []
|
|
1809
2321
|
} = options;
|
|
1810
2322
|
const sanitizeContextCode = generateSanitizeContextCode(securityLevel);
|
|
1811
2323
|
const patternDetectorsCode = generatePatternDetectorsCode(suspiciousPatterns);
|
|
@@ -2241,6 +2753,8 @@ ${stackTraceHardeningCode}
|
|
|
2241
2753
|
const hostReportViolation = __host_reportViolation__;
|
|
2242
2754
|
const hostConfig = __host_config__;
|
|
2243
2755
|
const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
|
|
2756
|
+
const hostInvokeGlobal = typeof __host_invokeGlobal__ === 'function' ? __host_invokeGlobal__ : null;
|
|
2757
|
+
const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
|
|
2244
2758
|
const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
|
|
2245
2759
|
const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
|
|
2246
2760
|
|
|
@@ -2253,6 +2767,8 @@ ${stackTraceHardeningCode}
|
|
|
2253
2767
|
try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }
|
|
2254
2768
|
try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }
|
|
2255
2769
|
try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
|
|
2770
|
+
try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
|
|
2771
|
+
try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
|
|
2256
2772
|
|
|
2257
2773
|
// Policy violation reporter (best-effort; host decides how to handle based on security level)
|
|
2258
2774
|
function __ag_reportViolation(kind) {
|
|
@@ -2422,6 +2938,22 @@ ${stackTraceHardeningCode}
|
|
|
2422
2938
|
// Tool call stats for rate limiting
|
|
2423
2939
|
let toolCallCount = 0;
|
|
2424
2940
|
|
|
2941
|
+
// Calls into host functions passed in globals: counted against their own cap, and their
|
|
2942
|
+
// timestamps share the operation rate limit with tool calls. They are not recorded in
|
|
2943
|
+
// operationHistory, so the tool-call suspicious-sequence detectors only see tool calls.
|
|
2944
|
+
let globalFunctionCallCount = 0;
|
|
2945
|
+
const globalFunctionCallTimes = [];
|
|
2946
|
+
|
|
2947
|
+
// Fail-closed: every call into a host function goes through the gate, except the built-in
|
|
2948
|
+
// prototype methods of host data (Array.prototype.map, iterators, Date methods, ...), which
|
|
2949
|
+
// the get trap binds and records here so data globals keep working as before.
|
|
2950
|
+
const ungatedHostFunctions = new WeakSet();
|
|
2951
|
+
|
|
2952
|
+
// Errors that report a failure of the tool itself (the handler threw, or its result could not
|
|
2953
|
+
// be delivered), as opposed to a refusal by the enclave. callTool(..., { throwOnError: false })
|
|
2954
|
+
// turns only these into { success: false, error } results. Keyed by the safe error thrown.
|
|
2955
|
+
const toolFailures = new WeakMap();
|
|
2956
|
+
|
|
2425
2957
|
// Blocked properties for secure proxy (from security level)
|
|
2426
2958
|
const blockedPropertiesSet = new Set(${JSON.stringify(blockedProperties)});
|
|
2427
2959
|
|
|
@@ -2527,6 +3059,9 @@ ${stackTraceHardeningCode}
|
|
|
2527
3059
|
// Then recursively proxy the bound function to block constructor access
|
|
2528
3060
|
if (typeof value === 'function') {
|
|
2529
3061
|
var boundMethod = __ag_functionBind.call(value, target);
|
|
3062
|
+
if (host && hostIsBuiltinMethod(value)) {
|
|
3063
|
+
ungatedHostFunctions.add(boundMethod);
|
|
3064
|
+
}
|
|
2530
3065
|
return createSecureProxy(boundMethod, depth + 1, host);
|
|
2531
3066
|
}
|
|
2532
3067
|
|
|
@@ -2663,18 +3198,29 @@ ${stackTraceHardeningCode}
|
|
|
2663
3198
|
// (Promise.prototype up to Function) to reach the host Function constructor for RCE.
|
|
2664
3199
|
// Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
|
|
2665
3200
|
// then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
|
|
3201
|
+
//
|
|
3202
|
+
// SECURITY: a call into a HOST function (a custom global, a method read off one, or
|
|
3203
|
+
// call/apply/bind on one) goes through the global-function gate instead: abort check,
|
|
3204
|
+
// maxGlobalFunctionCalls, the shared operation rate limit, and a sanitized, parent-realm
|
|
3205
|
+
// copy of the result. Without it those calls skipped every limit that guards callTool, and
|
|
3206
|
+
// their results arrived unsanitized. Only built-in methods of host data are exempt.
|
|
2666
3207
|
apply: function(target, thisArg, args) {
|
|
3208
|
+
if (host && !ungatedHostFunctions.has(target)) {
|
|
3209
|
+
return callHostFunction(target, thisArg, args);
|
|
3210
|
+
}
|
|
2667
3211
|
return createSecureProxy(__ag_ReflectApply(target, thisArg, args), 0, host);
|
|
2668
|
-
}
|
|
2669
|
-
//
|
|
2670
|
-
//
|
|
3212
|
+
},
|
|
3213
|
+
// Constructing a HOST function would hand back a raw host instance without passing the
|
|
3214
|
+
// gate, so it is refused. Realm-owned values keep NO construct trap (undefined here means
|
|
3215
|
+
// the default behavior): every constructor reachable from sandbox code resolves to an
|
|
2671
3216
|
// inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
|
|
2672
3217
|
// from strings disabled, so a 'new X()' result cannot reach a usable Function
|
|
2673
|
-
// constructor.
|
|
2674
|
-
//
|
|
2675
|
-
//
|
|
2676
|
-
|
|
2677
|
-
|
|
3218
|
+
// constructor. Wrapping construct results would additionally break the proxy invariant
|
|
3219
|
+
// for the frozen (non-extensible) Error objects the harness throws (getPrototypeOf must
|
|
3220
|
+
// not report null for a non-extensible target), masking legitimate errors.
|
|
3221
|
+
construct: host ? function() {
|
|
3222
|
+
throw createSafeError('Host functions cannot be called with new', 'TypeError');
|
|
3223
|
+
} : undefined
|
|
2678
3224
|
});
|
|
2679
3225
|
|
|
2680
3226
|
cache.set(obj, proxy);
|
|
@@ -2686,19 +3232,91 @@ ${stackTraceHardeningCode}
|
|
|
2686
3232
|
}
|
|
2687
3233
|
|
|
2688
3234
|
/**
|
|
2689
|
-
*
|
|
3235
|
+
* Operation rate limit, shared by tool calls and calls into host functions.
|
|
3236
|
+
* Sliding one-second window; entries older than two seconds are dropped.
|
|
2690
3237
|
*/
|
|
2691
|
-
function
|
|
2692
|
-
// Rate limiting check with sliding window cleanup
|
|
2693
|
-
const now = Date.now();
|
|
2694
|
-
// Clean up old entries to prevent unbounded growth (keep only last 2 seconds)
|
|
3238
|
+
function enforceRateLimit(now) {
|
|
2695
3239
|
while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
|
|
2696
3240
|
operationHistory.shift();
|
|
2697
3241
|
}
|
|
2698
|
-
|
|
2699
|
-
|
|
3242
|
+
while (globalFunctionCallTimes.length > 0 && now - globalFunctionCallTimes[0] > 2000) {
|
|
3243
|
+
globalFunctionCallTimes.shift();
|
|
3244
|
+
}
|
|
3245
|
+
var recent = 0;
|
|
3246
|
+
for (var r = 0; r < operationHistory.length; r++) {
|
|
3247
|
+
if (now - operationHistory[r].timestamp < 1000) recent++;
|
|
3248
|
+
}
|
|
3249
|
+
for (var g = 0; g < globalFunctionCallTimes.length; g++) {
|
|
3250
|
+
if (now - globalFunctionCallTimes[g] < 1000) recent++;
|
|
3251
|
+
}
|
|
3252
|
+
if (recent >= validationConfig.maxOperationsPerSecond) {
|
|
2700
3253
|
throw createSafeError('Operation rate limit exceeded (' + validationConfig.maxOperationsPerSecond + ' operations/second)');
|
|
2701
3254
|
}
|
|
3255
|
+
}
|
|
3256
|
+
|
|
3257
|
+
/**
|
|
3258
|
+
* Parse the host invoker's JSON envelope into a parent-realm value, or throw its error.
|
|
3259
|
+
*/
|
|
3260
|
+
function decodeGlobalFunctionResult(envelopeJson) {
|
|
3261
|
+
if (typeof envelopeJson !== 'string') {
|
|
3262
|
+
throw createSafeError('Global function bridge returned an invalid response');
|
|
3263
|
+
}
|
|
3264
|
+
var envelope;
|
|
3265
|
+
try {
|
|
3266
|
+
envelope = JSON.parse(envelopeJson);
|
|
3267
|
+
} catch (e) {
|
|
3268
|
+
throw createSafeError('Global function bridge returned invalid JSON');
|
|
3269
|
+
}
|
|
3270
|
+
if (!envelope || typeof envelope !== 'object' || envelope.v !== 1) {
|
|
3271
|
+
throw createSafeError('Global function bridge returned an invalid response');
|
|
3272
|
+
}
|
|
3273
|
+
if (envelope.ok === true) {
|
|
3274
|
+
return __ag_hasOwnProperty.call(envelope, 'value') ? envelope.value : undefined;
|
|
3275
|
+
}
|
|
3276
|
+
var failure = envelope.error;
|
|
3277
|
+
var message = (failure && typeof failure.message === 'string') ? failure.message : 'Global function call failed';
|
|
3278
|
+
var name = (failure && typeof failure.name === 'string') ? failure.name : 'Error';
|
|
3279
|
+
throw createSafeError(message, name);
|
|
3280
|
+
}
|
|
3281
|
+
|
|
3282
|
+
/**
|
|
3283
|
+
* The global-function gate: every call from the sandbox into a host function passed in
|
|
3284
|
+
* globals (including functions nested in objects) comes through here.
|
|
3285
|
+
*/
|
|
3286
|
+
function callHostFunction(target, thisArg, args) {
|
|
3287
|
+
if (hostAbortCheck()) {
|
|
3288
|
+
throw createSafeError('Execution aborted');
|
|
3289
|
+
}
|
|
3290
|
+
if (typeof hostInvokeGlobal !== 'function') {
|
|
3291
|
+
throw createSafeError('Global function bridge is not available');
|
|
3292
|
+
}
|
|
3293
|
+
|
|
3294
|
+
globalFunctionCallCount++;
|
|
3295
|
+
if (globalFunctionCallCount > ${maxGlobalFunctionCalls}) {
|
|
3296
|
+
throw createSafeError(${JSON.stringify(globalFunctionLimitMessage(maxGlobalFunctionCalls))});
|
|
3297
|
+
}
|
|
3298
|
+
|
|
3299
|
+
var now = Date.now();
|
|
3300
|
+
enforceRateLimit(now);
|
|
3301
|
+
globalFunctionCallTimes.push(now);
|
|
3302
|
+
|
|
3303
|
+
var outcome = hostInvokeGlobal(target, thisArg, args);
|
|
3304
|
+
if (typeof outcome === 'string') {
|
|
3305
|
+
return createSecureProxy(decodeGlobalFunctionResult(outcome));
|
|
3306
|
+
}
|
|
3307
|
+
|
|
3308
|
+
// A host function that returned a thenable: settle to a sanitized parent-realm value.
|
|
3309
|
+
return createSecureProxy(outcome.then(decodeGlobalFunctionResult).then(function(value) {
|
|
3310
|
+
return createSecureProxy(value);
|
|
3311
|
+
}));
|
|
3312
|
+
}
|
|
3313
|
+
|
|
3314
|
+
/**
|
|
3315
|
+
* Validate an operation before forwarding to host
|
|
3316
|
+
*/
|
|
3317
|
+
function validateOperation(operationName, args) {
|
|
3318
|
+
// Rate limiting check with sliding window cleanup
|
|
3319
|
+
enforceRateLimit(Date.now());
|
|
2702
3320
|
|
|
2703
3321
|
// Operation name format validation
|
|
2704
3322
|
if (typeof operationName !== 'string' || !operationName) {
|
|
@@ -2740,11 +3358,64 @@ ${stackTraceHardeningCode}
|
|
|
2740
3358
|
}
|
|
2741
3359
|
}
|
|
2742
3360
|
|
|
3361
|
+
/**
|
|
3362
|
+
* Read a script's callTool options. Only { throwOnError: false } changes behavior.
|
|
3363
|
+
*/
|
|
3364
|
+
function readThrowOnError(options) {
|
|
3365
|
+
if (options === undefined || options === null) return true;
|
|
3366
|
+
if (typeof options !== 'object') {
|
|
3367
|
+
throw createSafeError('callTool options must be an object', 'TypeError');
|
|
3368
|
+
}
|
|
3369
|
+
return options.throwOnError !== false;
|
|
3370
|
+
}
|
|
3371
|
+
|
|
3372
|
+
/**
|
|
3373
|
+
* Remember that a safe error reports a failure of the tool itself (see toolFailures).
|
|
3374
|
+
*/
|
|
3375
|
+
function markToolFailure(error, toolName, name, message, code) {
|
|
3376
|
+
var info = { name: name, message: message, toolName: toolName };
|
|
3377
|
+
if (typeof code === 'string') info.code = code;
|
|
3378
|
+
toolFailures.set(error, info);
|
|
3379
|
+
return error;
|
|
3380
|
+
}
|
|
3381
|
+
|
|
3382
|
+
/**
|
|
3383
|
+
* Whether a tool bridge payload is larger than the limit in UTF-8 bytes, as the host counts it.
|
|
3384
|
+
* A code unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
|
|
3385
|
+
*/
|
|
3386
|
+
function exceedsPayloadLimit(str, maxBytes) {
|
|
3387
|
+
if (str.length > maxBytes) return true;
|
|
3388
|
+
if (str.length * 3 <= maxBytes) return false;
|
|
3389
|
+
var bytes = 0;
|
|
3390
|
+
for (var i = 0; i < str.length; i++) {
|
|
3391
|
+
var c = str.charCodeAt(i);
|
|
3392
|
+
if (c < 0x80) bytes += 1;
|
|
3393
|
+
else if (c < 0x800) bytes += 2;
|
|
3394
|
+
else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
|
|
3395
|
+
var d = str.charCodeAt(i + 1);
|
|
3396
|
+
if (d >= 0xdc00 && d <= 0xdfff) {
|
|
3397
|
+
bytes += 4;
|
|
3398
|
+
i++;
|
|
3399
|
+
} else {
|
|
3400
|
+
bytes += 3;
|
|
3401
|
+
}
|
|
3402
|
+
} else bytes += 3;
|
|
3403
|
+
if (bytes > maxBytes) return true;
|
|
3404
|
+
}
|
|
3405
|
+
return false;
|
|
3406
|
+
}
|
|
3407
|
+
|
|
2743
3408
|
/**
|
|
2744
3409
|
* Inner VM's callTool function
|
|
2745
3410
|
* Proxies through parent VM with validation
|
|
3411
|
+
*
|
|
3412
|
+
* options.throwOnError === false: a failing tool resolves to { success: false, error } and a
|
|
3413
|
+
* working one to { success: true, data }. Refusals by the enclave (abort, tool-call cap, rate
|
|
3414
|
+
* limit, operation-name and suspicious-sequence checks, invalid arguments) still throw.
|
|
2746
3415
|
*/
|
|
2747
|
-
function innerCallTool(toolName, args) {
|
|
3416
|
+
function innerCallTool(toolName, args, options) {
|
|
3417
|
+
var throwOnError = readThrowOnError(options);
|
|
3418
|
+
|
|
2748
3419
|
// Check if aborted
|
|
2749
3420
|
if (hostAbortCheck()) {
|
|
2750
3421
|
throw createSafeError('Execution aborted');
|
|
@@ -2793,8 +3464,8 @@ ${stackTraceHardeningCode}
|
|
|
2793
3464
|
throw createSafeError('Tool request must be JSON-serializable');
|
|
2794
3465
|
}
|
|
2795
3466
|
|
|
2796
|
-
//
|
|
2797
|
-
if (requestJson && (requestJson
|
|
3467
|
+
// Counted in UTF-8 bytes, as the host counts it, so both sides agree on the limit.
|
|
3468
|
+
if (requestJson && exceedsPayloadLimit(requestJson, toolBridgeMaxPayloadBytes)) {
|
|
2798
3469
|
throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
|
|
2799
3470
|
}
|
|
2800
3471
|
|
|
@@ -2803,8 +3474,17 @@ ${stackTraceHardeningCode}
|
|
|
2803
3474
|
throw createSafeError('Tool bridge returned non-string response');
|
|
2804
3475
|
}
|
|
2805
3476
|
|
|
2806
|
-
|
|
2807
|
-
|
|
3477
|
+
// The host refuses an oversized response as a tool failure; this check only backs it up,
|
|
3478
|
+
// and reports the same way so { throwOnError: false } resolves it to a result.
|
|
3479
|
+
if (exceedsPayloadLimit(responseJson, toolBridgeMaxPayloadBytes)) {
|
|
3480
|
+
var tooLarge = 'Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)';
|
|
3481
|
+
throw markToolFailure(
|
|
3482
|
+
createSafeError(tooLarge, 'RangeError'),
|
|
3483
|
+
toolName,
|
|
3484
|
+
'RangeError',
|
|
3485
|
+
tooLarge,
|
|
3486
|
+
'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
|
|
3487
|
+
);
|
|
2808
3488
|
}
|
|
2809
3489
|
|
|
2810
3490
|
var response;
|
|
@@ -2833,13 +3513,36 @@ ${stackTraceHardeningCode}
|
|
|
2833
3513
|
var err = response.error;
|
|
2834
3514
|
var msg = (err && typeof err.message === 'string') ? err.message : 'Tool call failed';
|
|
2835
3515
|
var name = (err && typeof err.name === 'string') ? err.name : 'Error';
|
|
2836
|
-
|
|
3516
|
+
var failure = createSafeError(msg, name);
|
|
3517
|
+
if (err && err.toolError === true) {
|
|
3518
|
+
markToolFailure(failure, toolName, name, msg, err.code);
|
|
3519
|
+
}
|
|
3520
|
+
throw failure;
|
|
2837
3521
|
}
|
|
2838
3522
|
|
|
2839
3523
|
throw createSafeError('Tool bridge returned invalid response');
|
|
2840
3524
|
});
|
|
2841
3525
|
} else {
|
|
2842
|
-
promise = hostCallTool(toolName, sanitizedArgs)
|
|
3526
|
+
promise = hostCallTool(toolName, sanitizedArgs).then(undefined, function(error) {
|
|
3527
|
+
// Direct mode: the host marks failures of the tool itself with this code.
|
|
3528
|
+
if (error && error.code === 'TOOL_CALL_FAILED') {
|
|
3529
|
+
var message = typeof error.message === 'string' ? error.message : 'Tool call failed';
|
|
3530
|
+
throw markToolFailure(createSafeError(message), toolName, 'Error', message, 'TOOL_CALL_FAILED');
|
|
3531
|
+
}
|
|
3532
|
+
throw error;
|
|
3533
|
+
});
|
|
3534
|
+
}
|
|
3535
|
+
|
|
3536
|
+
if (!throwOnError) {
|
|
3537
|
+
promise = promise.then(function(result) {
|
|
3538
|
+
return { success: true, data: result };
|
|
3539
|
+
}, function(error) {
|
|
3540
|
+
var info = toolFailures.get(error);
|
|
3541
|
+
if (info) {
|
|
3542
|
+
return { success: false, error: info };
|
|
3543
|
+
}
|
|
3544
|
+
throw error;
|
|
3545
|
+
});
|
|
2843
3546
|
}
|
|
2844
3547
|
|
|
2845
3548
|
// Create a secure promise that wraps both the promise object and its result
|
|
@@ -3492,6 +4195,36 @@ ${stackTraceHardeningCode}
|
|
|
3492
4195
|
innerRuntimeScript.runInContext(innerContext);
|
|
3493
4196
|
} catch (e) { /* ignore */ }
|
|
3494
4197
|
|
|
4198
|
+
// Tool namespaces (mail.list(args)): built INSIDE the inner realm by a factory evaluated there
|
|
4199
|
+
// (before Object/JSON are replaced by the safe globals below), so each namespace is a frozen,
|
|
4200
|
+
// null-prototype inner-realm object whose methods call the gated callTool. A namespace call is
|
|
4201
|
+
// therefore an ordinary tool call: counted, rate-limited, pattern-checked and sanitized.
|
|
4202
|
+
var toolNamespaceNames = ${JSON.stringify(toolNamespaces.map((ns) => ns.name))};
|
|
4203
|
+
if (toolNamespaceNames.length > 0) {
|
|
4204
|
+
var installToolNamespaces = new vm.Script(${JSON.stringify(TOOL_NAMESPACE_FACTORY_SOURCE)}, {
|
|
4205
|
+
filename: 'inner-tool-namespaces.js'
|
|
4206
|
+
}).runInContext(innerContext);
|
|
4207
|
+
var builtToolNamespaces = installToolNamespaces(safeRuntime.__safe_callTool, ${JSON.stringify(
|
|
4208
|
+
JSON.stringify(toolNamespaces)
|
|
4209
|
+
)});
|
|
4210
|
+
for (var tn = 0; tn < toolNamespaceNames.length; tn++) {
|
|
4211
|
+
var toolNamespaceName = toolNamespaceNames[tn];
|
|
4212
|
+
var toolNamespace = builtToolNamespaces[toolNamespaceName];
|
|
4213
|
+
__ag_defineProperty(innerContext, toolNamespaceName, {
|
|
4214
|
+
value: toolNamespace,
|
|
4215
|
+
writable: false,
|
|
4216
|
+
configurable: false,
|
|
4217
|
+
enumerable: false
|
|
4218
|
+
});
|
|
4219
|
+
__ag_defineProperty(innerContext, '__safe_' + toolNamespaceName, {
|
|
4220
|
+
value: toolNamespace,
|
|
4221
|
+
writable: false,
|
|
4222
|
+
configurable: false,
|
|
4223
|
+
enumerable: false
|
|
4224
|
+
});
|
|
4225
|
+
}
|
|
4226
|
+
}
|
|
4227
|
+
|
|
3495
4228
|
// Defense-in-depth: Remove host callback from inner sandbox after all scripts have captured it
|
|
3496
4229
|
try { delete innerContext['__host_memory_track__']; } catch (e) { /* ignore */ }
|
|
3497
4230
|
|
|
@@ -3735,6 +4468,8 @@ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
|
|
|
3735
4468
|
var init_parent_vm_bootstrap = __esm({
|
|
3736
4469
|
"libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
|
|
3737
4470
|
"use strict";
|
|
4471
|
+
init_global_function_gate();
|
|
4472
|
+
init_tool_namespaces();
|
|
3738
4473
|
MEMBRANE_MAX_RECURSION_DEPTH = 256;
|
|
3739
4474
|
NODEJS_24_DANGEROUS_GLOBALS = {
|
|
3740
4475
|
STRICT: [
|
|
@@ -3946,37 +4681,8 @@ var init_suspicious_patterns = __esm({
|
|
|
3946
4681
|
});
|
|
3947
4682
|
|
|
3948
4683
|
// libs/core/src/double-vm/double-vm-wrapper.ts
|
|
3949
|
-
import * as
|
|
3950
|
-
|
|
3951
|
-
if (!stack || !sanitize) return stack;
|
|
3952
|
-
let sanitized = stack;
|
|
3953
|
-
for (const pattern of SENSITIVE_STACK_PATTERNS) {
|
|
3954
|
-
pattern.lastIndex = 0;
|
|
3955
|
-
sanitized = sanitized.replace(pattern, "[REDACTED]");
|
|
3956
|
-
}
|
|
3957
|
-
const lines = sanitized.split("\n");
|
|
3958
|
-
for (let i = 0; i < lines.length; i++) {
|
|
3959
|
-
const line = lines[i];
|
|
3960
|
-
if (line.length > 1e3) continue;
|
|
3961
|
-
if (/:\d+:\d+\)/.test(line)) {
|
|
3962
|
-
const atIdx = line.indexOf("at ");
|
|
3963
|
-
if (atIdx !== -1) {
|
|
3964
|
-
const afterAt = line.substring(atIdx + 3).trimStart();
|
|
3965
|
-
const spaceIdx = afterAt.indexOf(" ");
|
|
3966
|
-
if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
|
|
3967
|
-
const funcName = afterAt.substring(0, spaceIdx);
|
|
3968
|
-
lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
|
|
3969
|
-
continue;
|
|
3970
|
-
}
|
|
3971
|
-
}
|
|
3972
|
-
}
|
|
3973
|
-
if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
|
|
3974
|
-
lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
|
|
3975
|
-
}
|
|
3976
|
-
}
|
|
3977
|
-
return lines.join("\n");
|
|
3978
|
-
}
|
|
3979
|
-
var SENSITIVE_STACK_PATTERNS, DoubleVmWrapper;
|
|
4684
|
+
import * as vm3 from "vm";
|
|
4685
|
+
var DoubleVmWrapper;
|
|
3980
4686
|
var init_double_vm_wrapper = __esm({
|
|
3981
4687
|
"libs/core/src/double-vm/double-vm-wrapper.ts"() {
|
|
3982
4688
|
"use strict";
|
|
@@ -3986,14 +4692,10 @@ var init_double_vm_wrapper = __esm({
|
|
|
3986
4692
|
init_reference_resolver();
|
|
3987
4693
|
init_memory_tracker();
|
|
3988
4694
|
init_tool_bridge();
|
|
4695
|
+
init_stack_trace();
|
|
4696
|
+
init_global_function_gate();
|
|
3989
4697
|
init_parent_vm_bootstrap();
|
|
3990
|
-
init_suspicious_patterns();
|
|
3991
|
-
SENSITIVE_STACK_PATTERNS = [
|
|
3992
|
-
/\/Users\/[^/]+\/[^\s):]*/gi,
|
|
3993
|
-
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
3994
|
-
/\/var\/[^\s):]*/gi,
|
|
3995
|
-
/node_modules\/[^\s):]+/gi
|
|
3996
|
-
];
|
|
4698
|
+
init_suspicious_patterns();
|
|
3997
4699
|
DoubleVmWrapper = class {
|
|
3998
4700
|
constructor(config, securityLevel) {
|
|
3999
4701
|
this.config = config;
|
|
@@ -4021,7 +4723,7 @@ var init_double_vm_wrapper = __esm({
|
|
|
4021
4723
|
});
|
|
4022
4724
|
this.parentContext = parentContext;
|
|
4023
4725
|
const parentScript = this.buildParentScript(code, executionContext);
|
|
4024
|
-
const script = new
|
|
4726
|
+
const script = new vm3.Script(parentScript, {
|
|
4025
4727
|
filename: "parent-vm.js"
|
|
4026
4728
|
});
|
|
4027
4729
|
const parentTimeout = config.timeout + this.config.parentTimeoutBuffer;
|
|
@@ -4133,15 +4835,15 @@ var init_double_vm_wrapper = __esm({
|
|
|
4133
4835
|
*/
|
|
4134
4836
|
createParentContext(executionContext, memoryTracker, reportViolation) {
|
|
4135
4837
|
const { stats, config } = executionContext;
|
|
4136
|
-
const parentContext =
|
|
4838
|
+
const parentContext = vm3.createContext(
|
|
4137
4839
|
{},
|
|
4138
4840
|
{
|
|
4139
4841
|
codeGeneration: { strings: false, wasm: false }
|
|
4140
4842
|
}
|
|
4141
4843
|
);
|
|
4142
4844
|
const safeVm = {
|
|
4143
|
-
createContext:
|
|
4144
|
-
Script:
|
|
4845
|
+
createContext: vm3.createContext.bind(vm3),
|
|
4846
|
+
Script: vm3.Script
|
|
4145
4847
|
};
|
|
4146
4848
|
Object.defineProperty(parentContext, "__host_vm_module__", {
|
|
4147
4849
|
value: safeVm,
|
|
@@ -4157,6 +4859,18 @@ var init_double_vm_wrapper = __esm({
|
|
|
4157
4859
|
configurable: true
|
|
4158
4860
|
// Allow deletion after capture for defense-in-depth
|
|
4159
4861
|
});
|
|
4862
|
+
Object.defineProperty(parentContext, "__host_invokeGlobal__", {
|
|
4863
|
+
value: createHostGlobalFunctionInvoker(executionContext),
|
|
4864
|
+
writable: false,
|
|
4865
|
+
configurable: true
|
|
4866
|
+
// Allow deletion after capture for defense-in-depth
|
|
4867
|
+
});
|
|
4868
|
+
Object.defineProperty(parentContext, "__host_isBuiltinMethod__", {
|
|
4869
|
+
value: (fn) => isBuiltinMethod(fn),
|
|
4870
|
+
writable: false,
|
|
4871
|
+
configurable: true
|
|
4872
|
+
// Allow deletion after capture for defense-in-depth
|
|
4873
|
+
});
|
|
4160
4874
|
Object.defineProperty(parentContext, "__host_stats__", {
|
|
4161
4875
|
value: stats,
|
|
4162
4876
|
writable: false,
|
|
@@ -4292,7 +5006,11 @@ var init_double_vm_wrapper = __esm({
|
|
|
4292
5006
|
return sanitized;
|
|
4293
5007
|
} catch (error) {
|
|
4294
5008
|
const err = error;
|
|
4295
|
-
throw createSafeError(
|
|
5009
|
+
throw createSafeError(
|
|
5010
|
+
`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
|
|
5011
|
+
"Error",
|
|
5012
|
+
"TOOL_CALL_FAILED"
|
|
5013
|
+
);
|
|
4296
5014
|
}
|
|
4297
5015
|
};
|
|
4298
5016
|
}
|
|
@@ -4337,7 +5055,9 @@ var init_double_vm_wrapper = __esm({
|
|
|
4337
5055
|
memoryLimit: config.memoryLimit,
|
|
4338
5056
|
throwOnBlocked,
|
|
4339
5057
|
toolBridgeMode,
|
|
4340
|
-
toolBridgeMaxPayloadBytes
|
|
5058
|
+
toolBridgeMaxPayloadBytes,
|
|
5059
|
+
maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls(config),
|
|
5060
|
+
toolNamespaces: executionContext.toolNamespaces ?? []
|
|
4341
5061
|
});
|
|
4342
5062
|
}
|
|
4343
5063
|
/**
|
|
@@ -4518,6 +5238,16 @@ var init_memory_proxy = __esm({
|
|
|
4518
5238
|
});
|
|
4519
5239
|
|
|
4520
5240
|
// libs/core/src/safe-runtime.ts
|
|
5241
|
+
function readThrowOnError(options) {
|
|
5242
|
+
if (options === void 0 || options === null) return true;
|
|
5243
|
+
if (typeof options !== "object") {
|
|
5244
|
+
throw createSafeTypeError("callTool options must be an object");
|
|
5245
|
+
}
|
|
5246
|
+
return options.throwOnError !== false;
|
|
5247
|
+
}
|
|
5248
|
+
function plainResult(fields) {
|
|
5249
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), fields);
|
|
5250
|
+
}
|
|
4521
5251
|
function createSafeRuntime(context, options) {
|
|
4522
5252
|
const { config, stats } = context;
|
|
4523
5253
|
const sidecar = options?.sidecar;
|
|
@@ -4526,7 +5256,8 @@ function createSafeRuntime(context, options) {
|
|
|
4526
5256
|
const memoryTracker = options?.memoryTracker;
|
|
4527
5257
|
const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
|
|
4528
5258
|
const proxyOptions = secureProxyConfig ? { levelConfig: secureProxyConfig } : {};
|
|
4529
|
-
async function __safe_callTool(toolName, args) {
|
|
5259
|
+
async function __safe_callTool(toolName, args, options2) {
|
|
5260
|
+
const throwOnError = readThrowOnError(options2);
|
|
4530
5261
|
if (context.aborted) {
|
|
4531
5262
|
throw createSafeError("Execution aborted");
|
|
4532
5263
|
}
|
|
@@ -4570,21 +5301,34 @@ function createSafeRuntime(context, options) {
|
|
|
4570
5301
|
allowDates: true,
|
|
4571
5302
|
allowErrors: true
|
|
4572
5303
|
});
|
|
5304
|
+
let value = sanitized;
|
|
4573
5305
|
if (sidecar && referenceConfig && typeof sanitized === "string") {
|
|
4574
5306
|
const size = Buffer.byteLength(sanitized, "utf-8");
|
|
4575
5307
|
if (size >= referenceConfig.extractionThreshold) {
|
|
4576
5308
|
try {
|
|
4577
|
-
|
|
4578
|
-
return refId;
|
|
5309
|
+
value = sidecar.store(sanitized, "tool-result", { origin: toolName });
|
|
4579
5310
|
} catch {
|
|
4580
|
-
|
|
5311
|
+
value = sanitized;
|
|
4581
5312
|
}
|
|
4582
5313
|
}
|
|
4583
5314
|
}
|
|
4584
|
-
return
|
|
5315
|
+
return throwOnError ? value : plainResult({ success: true, data: value });
|
|
4585
5316
|
} catch (error) {
|
|
4586
5317
|
const err = error;
|
|
4587
|
-
|
|
5318
|
+
const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
|
|
5319
|
+
if (!throwOnError) {
|
|
5320
|
+
const code = error?.code;
|
|
5321
|
+
return plainResult({
|
|
5322
|
+
success: false,
|
|
5323
|
+
error: plainResult({
|
|
5324
|
+
name: "Error",
|
|
5325
|
+
message,
|
|
5326
|
+
...typeof code === "string" ? { code } : {},
|
|
5327
|
+
toolName
|
|
5328
|
+
})
|
|
5329
|
+
});
|
|
5330
|
+
}
|
|
5331
|
+
throw createSafeError(message);
|
|
4588
5332
|
}
|
|
4589
5333
|
}
|
|
4590
5334
|
function* __safe_forOf(iterable) {
|
|
@@ -4781,7 +5525,8 @@ ${errorMessages}`);
|
|
|
4781
5525
|
}
|
|
4782
5526
|
const customGlobalsWithPrefix = {};
|
|
4783
5527
|
if (config.globals) {
|
|
4784
|
-
const
|
|
5528
|
+
const customGlobalProxyOptions = options?.globalFunctionGate ? { ...proxyOptions, callGate: options.globalFunctionGate } : proxyOptions;
|
|
5529
|
+
const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, customGlobalProxyOptions);
|
|
4785
5530
|
for (const [key, value] of Object.entries(wrappedCustomGlobals)) {
|
|
4786
5531
|
customGlobalsWithPrefix[`__safe_${key}`] = value;
|
|
4787
5532
|
}
|
|
@@ -4836,18 +5581,22 @@ ${errorMessages}`);
|
|
|
4836
5581
|
}
|
|
4837
5582
|
function serializeSafeRuntime() {
|
|
4838
5583
|
return `
|
|
4839
|
-
// Safe callTool implementation
|
|
4840
|
-
|
|
5584
|
+
// Safe callTool implementation. The options ({ throwOnError: false }) are passed on:
|
|
5585
|
+
// only the adapter's __internal_callTool can tell a failure of the tool from a refusal.
|
|
5586
|
+
async function __safe_callTool(toolName, args, options) {
|
|
4841
5587
|
if (typeof toolName !== 'string' || !toolName) {
|
|
4842
5588
|
throw new TypeError('Tool name must be a non-empty string');
|
|
4843
5589
|
}
|
|
4844
5590
|
if (typeof args !== 'object' || args === null || Array.isArray(args)) {
|
|
4845
5591
|
throw new TypeError('Tool arguments must be an object');
|
|
4846
5592
|
}
|
|
5593
|
+
if (options !== undefined && options !== null && typeof options !== 'object') {
|
|
5594
|
+
throw new TypeError('callTool options must be an object');
|
|
5595
|
+
}
|
|
4847
5596
|
|
|
4848
5597
|
// This will be replaced by the sandbox adapter with actual implementation
|
|
4849
5598
|
if (typeof __internal_callTool === 'function') {
|
|
4850
|
-
return await __internal_callTool(toolName, args);
|
|
5599
|
+
return await __internal_callTool(toolName, args, options);
|
|
4851
5600
|
}
|
|
4852
5601
|
throw new Error('Tool handler not available');
|
|
4853
5602
|
}
|
|
@@ -5016,37 +5765,7 @@ var vm_adapter_exports = {};
|
|
|
5016
5765
|
__export(vm_adapter_exports, {
|
|
5017
5766
|
VmAdapter: () => VmAdapter
|
|
5018
5767
|
});
|
|
5019
|
-
import * as
|
|
5020
|
-
function sanitizeStackTrace2(stack, sanitize = true) {
|
|
5021
|
-
if (!stack) return stack;
|
|
5022
|
-
if (!sanitize) return stack;
|
|
5023
|
-
let sanitized = stack;
|
|
5024
|
-
for (const pattern of SENSITIVE_STACK_PATTERNS2) {
|
|
5025
|
-
pattern.lastIndex = 0;
|
|
5026
|
-
sanitized = sanitized.replace(pattern, "[REDACTED]");
|
|
5027
|
-
}
|
|
5028
|
-
const lines = sanitized.split("\n");
|
|
5029
|
-
for (let i = 0; i < lines.length; i++) {
|
|
5030
|
-
const line = lines[i];
|
|
5031
|
-
if (line.length > 1e3) continue;
|
|
5032
|
-
if (/:\d+:\d+\)/.test(line)) {
|
|
5033
|
-
const atIdx = line.indexOf("at ");
|
|
5034
|
-
if (atIdx !== -1) {
|
|
5035
|
-
const afterAt = line.substring(atIdx + 3).trimStart();
|
|
5036
|
-
const spaceIdx = afterAt.indexOf(" ");
|
|
5037
|
-
if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
|
|
5038
|
-
const funcName = afterAt.substring(0, spaceIdx);
|
|
5039
|
-
lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
|
|
5040
|
-
continue;
|
|
5041
|
-
}
|
|
5042
|
-
}
|
|
5043
|
-
}
|
|
5044
|
-
if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
|
|
5045
|
-
lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
|
|
5046
|
-
}
|
|
5047
|
-
}
|
|
5048
|
-
return lines.join("\n");
|
|
5049
|
-
}
|
|
5768
|
+
import * as vm4 from "vm";
|
|
5050
5769
|
function createSafeConsole(config, stats) {
|
|
5051
5770
|
const wrap = (method) => (...args) => {
|
|
5052
5771
|
stats.callCount++;
|
|
@@ -5210,7 +5929,7 @@ function sanitizeVmContext(context, securityLevel) {
|
|
|
5210
5929
|
enumerable: true
|
|
5211
5930
|
});
|
|
5212
5931
|
}
|
|
5213
|
-
var
|
|
5932
|
+
var STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, SANDBOX_REALM_BRIDGE_SCRIPT, TOOL_NAMESPACE_FACTORY_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
|
|
5214
5933
|
var init_vm_adapter = __esm({
|
|
5215
5934
|
"libs/core/src/adapters/vm-adapter.ts"() {
|
|
5216
5935
|
"use strict";
|
|
@@ -5220,130 +5939,9 @@ var init_vm_adapter = __esm({
|
|
|
5220
5939
|
init_memory_tracker();
|
|
5221
5940
|
init_tool_bridge();
|
|
5222
5941
|
init_value_sanitizer();
|
|
5223
|
-
|
|
5224
|
-
|
|
5225
|
-
|
|
5226
|
-
// macOS home directories
|
|
5227
|
-
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
5228
|
-
// Linux home directories
|
|
5229
|
-
/\/var\/[^\s):]*/gi,
|
|
5230
|
-
// System var directories
|
|
5231
|
-
/\/opt\/[^\s):]*/gi,
|
|
5232
|
-
// Optional software
|
|
5233
|
-
/\/tmp\/[^\s):]*/gi,
|
|
5234
|
-
// Temporary files
|
|
5235
|
-
/\/etc\/[^\s):]*/gi,
|
|
5236
|
-
// System configuration
|
|
5237
|
-
/\/root\/[^\s):]*/gi,
|
|
5238
|
-
// Root home directory
|
|
5239
|
-
/\/mnt\/[^\s):]*/gi,
|
|
5240
|
-
// Mount points
|
|
5241
|
-
/\/srv\/[^\s):]*/gi,
|
|
5242
|
-
// Service data
|
|
5243
|
-
/\/data\/[^\s):]*/gi,
|
|
5244
|
-
// Data directories
|
|
5245
|
-
/\/app\/[^\s):]*/gi,
|
|
5246
|
-
// Application directories
|
|
5247
|
-
/\/proc\/[^\s):]*/gi,
|
|
5248
|
-
// Process information
|
|
5249
|
-
/\/sys\/[^\s):]*/gi,
|
|
5250
|
-
// System files
|
|
5251
|
-
// Windows paths
|
|
5252
|
-
/\\\\[^\s):]*/g,
|
|
5253
|
-
// UNC paths
|
|
5254
|
-
/[A-Z]:\\[^\s):]+/gi,
|
|
5255
|
-
// Windows drive paths
|
|
5256
|
-
// URL-based paths
|
|
5257
|
-
/file:\/\/[^\s):]+/gi,
|
|
5258
|
-
// File URLs
|
|
5259
|
-
/webpack:\/\/[^\s):]+/gi,
|
|
5260
|
-
// Webpack paths
|
|
5261
|
-
/%2F[^\s):]+/gi,
|
|
5262
|
-
// URL-encoded paths
|
|
5263
|
-
// Package managers and node
|
|
5264
|
-
/node_modules\/[^\s):]+/gi,
|
|
5265
|
-
// Node modules paths
|
|
5266
|
-
/\/nix\/store\/[^\s):]*/gi,
|
|
5267
|
-
// Nix store paths
|
|
5268
|
-
/\.npm\/[^\s):]*/gi,
|
|
5269
|
-
// NPM cache
|
|
5270
|
-
/\.yarn\/[^\s):]*/gi,
|
|
5271
|
-
// Yarn cache
|
|
5272
|
-
/\.pnpm\/[^\s):]*/gi,
|
|
5273
|
-
// PNPM cache
|
|
5274
|
-
// Container and orchestration
|
|
5275
|
-
/\/run\/secrets\/[^\s):]*/gi,
|
|
5276
|
-
// Docker/K8s secrets
|
|
5277
|
-
/\/var\/run\/[^\s):]*/gi,
|
|
5278
|
-
// Runtime directories
|
|
5279
|
-
/\/docker\/[^\s):]*/gi,
|
|
5280
|
-
// Docker paths
|
|
5281
|
-
/\/containers\/[^\s):]*/gi,
|
|
5282
|
-
// Container paths
|
|
5283
|
-
/\/kubelet\/[^\s):]*/gi,
|
|
5284
|
-
// Kubernetes kubelet
|
|
5285
|
-
// CI/CD systems
|
|
5286
|
-
/\/github\/workspace\/[^\s):]*/gi,
|
|
5287
|
-
// GitHub Actions
|
|
5288
|
-
/\/runner\/[^\s):]*/gi,
|
|
5289
|
-
// GitHub/GitLab runner
|
|
5290
|
-
/\/builds\/[^\s):]*/gi,
|
|
5291
|
-
// CI builds
|
|
5292
|
-
/\/workspace\/[^\s):]*/gi,
|
|
5293
|
-
// Generic workspace
|
|
5294
|
-
/\/pipeline\/[^\s):]*/gi,
|
|
5295
|
-
// CI pipelines
|
|
5296
|
-
/\/jenkins\/[^\s):]*/gi,
|
|
5297
|
-
// Jenkins
|
|
5298
|
-
/\/bamboo\/[^\s):]*/gi,
|
|
5299
|
-
// Bamboo
|
|
5300
|
-
/\/teamcity\/[^\s):]*/gi,
|
|
5301
|
-
// TeamCity
|
|
5302
|
-
/\/circleci\/[^\s):]*/gi,
|
|
5303
|
-
// CircleCI
|
|
5304
|
-
// Cloud providers
|
|
5305
|
-
/\/aws\/[^\s):]*/gi,
|
|
5306
|
-
// AWS paths
|
|
5307
|
-
/\/gcloud\/[^\s):]*/gi,
|
|
5308
|
-
// Google Cloud
|
|
5309
|
-
/\/azure\/[^\s):]*/gi,
|
|
5310
|
-
// Azure paths
|
|
5311
|
-
/s3:\/\/[^\s):]+/gi,
|
|
5312
|
-
// S3 URIs
|
|
5313
|
-
/gs:\/\/[^\s):]+/gi,
|
|
5314
|
-
// GCS URIs
|
|
5315
|
-
// Secrets and credentials (patterns that might appear in paths or errors)
|
|
5316
|
-
/[A-Z0-9]{20,}/g,
|
|
5317
|
-
// AWS-style access keys (20+ uppercase chars)
|
|
5318
|
-
/sk-[a-zA-Z0-9]{32,}/g,
|
|
5319
|
-
// OpenAI/Stripe-style secret keys
|
|
5320
|
-
/ghp_[a-zA-Z0-9]{36,}/g,
|
|
5321
|
-
// GitHub personal access tokens
|
|
5322
|
-
/gho_[a-zA-Z0-9]{36,}/g,
|
|
5323
|
-
// GitHub OAuth tokens
|
|
5324
|
-
/github_pat_[a-zA-Z0-9_]{22,}/g,
|
|
5325
|
-
// GitHub fine-grained tokens
|
|
5326
|
-
/xox[baprs]-[a-zA-Z0-9-]+/g,
|
|
5327
|
-
// Slack tokens
|
|
5328
|
-
/Bearer\s+[a-zA-Z0-9._-]+/gi,
|
|
5329
|
-
// Bearer tokens
|
|
5330
|
-
/Basic\s+[a-zA-Z0-9+/=]+/gi,
|
|
5331
|
-
// Basic auth
|
|
5332
|
-
// Internal network info
|
|
5333
|
-
/(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
|
|
5334
|
-
// Private IPs
|
|
5335
|
-
/[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
|
|
5336
|
-
// Internal hostnames
|
|
5337
|
-
/localhost:\d+/gi,
|
|
5338
|
-
// Localhost with port
|
|
5339
|
-
/127\.0\.0\.1:\d+/gi,
|
|
5340
|
-
// Loopback with port
|
|
5341
|
-
// User information
|
|
5342
|
-
/\/u\/[^/]+\//gi,
|
|
5343
|
-
// User subdirectories
|
|
5344
|
-
/~[a-z_][a-z0-9_-]*/gi
|
|
5345
|
-
// Unix user home shorthand
|
|
5346
|
-
];
|
|
5942
|
+
init_stack_trace();
|
|
5943
|
+
init_global_function_gate();
|
|
5944
|
+
init_tool_namespaces();
|
|
5347
5945
|
STACK_TRACE_HARDENING_CODE = `
|
|
5348
5946
|
(function() {
|
|
5349
5947
|
function __ag_redactStackString(stackStr) {
|
|
@@ -5443,7 +6041,7 @@ var init_vm_adapter = __esm({
|
|
|
5443
6041
|
} catch (e) {}
|
|
5444
6042
|
})();
|
|
5445
6043
|
`.trim();
|
|
5446
|
-
STACK_TRACE_HARDENING_SCRIPT = new
|
|
6044
|
+
STACK_TRACE_HARDENING_SCRIPT = new vm4.Script(STACK_TRACE_HARDENING_CODE);
|
|
5447
6045
|
CODE_GENERATION_VIOLATION_DETECTOR_CODE = `
|
|
5448
6046
|
(function() {
|
|
5449
6047
|
var __ag_report = (typeof __ag_reportViolation__ === 'function') ? __ag_reportViolation__ : null;
|
|
@@ -5492,7 +6090,7 @@ var init_vm_adapter = __esm({
|
|
|
5492
6090
|
try { __ag_wrapCtor((async function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
|
|
5493
6091
|
})();
|
|
5494
6092
|
`.trim();
|
|
5495
|
-
CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new
|
|
6093
|
+
CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new vm4.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
|
|
5496
6094
|
INTRINSIC_OBJECT_NEUTRALIZATION_CODE = `
|
|
5497
6095
|
(function() {
|
|
5498
6096
|
var RealObject = Object.getPrototypeOf({}).constructor;
|
|
@@ -5508,7 +6106,21 @@ var init_vm_adapter = __esm({
|
|
|
5508
6106
|
}
|
|
5509
6107
|
})();
|
|
5510
6108
|
`;
|
|
5511
|
-
INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new
|
|
6109
|
+
INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm4.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
|
|
6110
|
+
SANDBOX_REALM_BRIDGE_SCRIPT = new vm4.Script(`
|
|
6111
|
+
(function () {
|
|
6112
|
+
'use strict';
|
|
6113
|
+
var parse = JSON.parse;
|
|
6114
|
+
var SandboxPromise = Promise;
|
|
6115
|
+
return Object.freeze({
|
|
6116
|
+
parseJson: function (json) { return parse(json); },
|
|
6117
|
+
adoptPromise: function (hostPromise) {
|
|
6118
|
+
return new SandboxPromise(function (resolve, reject) { hostPromise.then(resolve, reject); });
|
|
6119
|
+
}
|
|
6120
|
+
});
|
|
6121
|
+
})()
|
|
6122
|
+
`);
|
|
6123
|
+
TOOL_NAMESPACE_FACTORY_SCRIPT = new vm4.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
|
|
5512
6124
|
PROTECTED_PREFIXES = ["__safe_", "__ag_"];
|
|
5513
6125
|
DANGEROUS_OBJECT_STATIC_METHODS = [
|
|
5514
6126
|
"defineProperty",
|
|
@@ -5624,19 +6236,23 @@ var init_vm_adapter = __esm({
|
|
|
5624
6236
|
}) : void 0;
|
|
5625
6237
|
memoryTracker?.start();
|
|
5626
6238
|
try {
|
|
6239
|
+
const baseSandbox = vm4.createContext(
|
|
6240
|
+
{},
|
|
6241
|
+
{
|
|
6242
|
+
codeGeneration: { strings: false, wasm: false }
|
|
6243
|
+
}
|
|
6244
|
+
);
|
|
6245
|
+
const realmBridge = SANDBOX_REALM_BRIDGE_SCRIPT.runInContext(baseSandbox);
|
|
6246
|
+
const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
|
|
6247
|
+
const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge);
|
|
5627
6248
|
const safeRuntime = createSafeRuntime(executionContext, {
|
|
5628
6249
|
sidecar: executionContext.sidecar,
|
|
5629
6250
|
referenceConfig: executionContext.referenceConfig,
|
|
5630
6251
|
secureProxyConfig: executionContext.secureProxyConfig,
|
|
5631
|
-
memoryTracker
|
|
6252
|
+
memoryTracker,
|
|
5632
6253
|
// Pass tracker for allocation monitoring
|
|
6254
|
+
globalFunctionGate
|
|
5633
6255
|
});
|
|
5634
|
-
const baseSandbox = vm3.createContext(
|
|
5635
|
-
{},
|
|
5636
|
-
{
|
|
5637
|
-
codeGeneration: { strings: false, wasm: false }
|
|
5638
|
-
}
|
|
5639
|
-
);
|
|
5640
6256
|
if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
|
|
5641
6257
|
Object.defineProperty(baseSandbox, "__host_memory_track__", {
|
|
5642
6258
|
value: (bytes) => {
|
|
@@ -5646,7 +6262,7 @@ var init_vm_adapter = __esm({
|
|
|
5646
6262
|
configurable: true,
|
|
5647
6263
|
enumerable: false
|
|
5648
6264
|
});
|
|
5649
|
-
const patchScript = new
|
|
6265
|
+
const patchScript = new vm4.Script(`
|
|
5650
6266
|
(function() {
|
|
5651
6267
|
var memoryLimit = ${config.memoryLimit};
|
|
5652
6268
|
var trackMemory = __host_memory_track__;
|
|
@@ -5789,7 +6405,7 @@ var init_vm_adapter = __esm({
|
|
|
5789
6405
|
// allow deletion after capture
|
|
5790
6406
|
enumerable: false
|
|
5791
6407
|
});
|
|
5792
|
-
const bridgeInitScript = new
|
|
6408
|
+
const bridgeInitScript = new vm4.Script(`
|
|
5793
6409
|
(function() {
|
|
5794
6410
|
var bridge = __host_callToolBridge__;
|
|
5795
6411
|
var stringify = JSON.stringify;
|
|
@@ -5800,9 +6416,28 @@ var init_vm_adapter = __esm({
|
|
|
5800
6416
|
// Remove global handle after capture (defense-in-depth)
|
|
5801
6417
|
try { delete globalThis.__host_callToolBridge__; } catch (e) { /* ignore */ }
|
|
5802
6418
|
|
|
5803
|
-
|
|
5804
|
-
|
|
5805
|
-
|
|
6419
|
+
// Whether a payload is larger than the limit in UTF-8 bytes, as the host counts it. A code
|
|
6420
|
+
// unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
|
|
6421
|
+
function exceedsPayloadLimit(str) {
|
|
6422
|
+
if (str.length > maxBytes) return true;
|
|
6423
|
+
if (str.length * 3 <= maxBytes) return false;
|
|
6424
|
+
var bytes = 0;
|
|
6425
|
+
for (var i = 0; i < str.length; i++) {
|
|
6426
|
+
var c = str.charCodeAt(i);
|
|
6427
|
+
if (c < 0x80) bytes += 1;
|
|
6428
|
+
else if (c < 0x800) bytes += 2;
|
|
6429
|
+
else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
|
|
6430
|
+
var d = str.charCodeAt(i + 1);
|
|
6431
|
+
if (d >= 0xdc00 && d <= 0xdfff) {
|
|
6432
|
+
bytes += 4;
|
|
6433
|
+
i++;
|
|
6434
|
+
} else {
|
|
6435
|
+
bytes += 3;
|
|
6436
|
+
}
|
|
6437
|
+
} else bytes += 3;
|
|
6438
|
+
if (bytes > maxBytes) return true;
|
|
6439
|
+
}
|
|
6440
|
+
return false;
|
|
5806
6441
|
}
|
|
5807
6442
|
|
|
5808
6443
|
function makeError(message, name) {
|
|
@@ -5811,7 +6446,16 @@ var init_vm_adapter = __esm({
|
|
|
5811
6446
|
return err;
|
|
5812
6447
|
}
|
|
5813
6448
|
|
|
5814
|
-
return async function __safe_callTool(toolName, args) {
|
|
6449
|
+
return async function __safe_callTool(toolName, args, options) {
|
|
6450
|
+
// callTool options: only { throwOnError: false } changes behavior. Tool failures
|
|
6451
|
+
// then resolve to { success: false, error }; the enclave's own refusals still throw.
|
|
6452
|
+
var throwOnError = true;
|
|
6453
|
+
if (options !== undefined && options !== null) {
|
|
6454
|
+
if (typeof options !== 'object') {
|
|
6455
|
+
throw makeError('callTool options must be an object', 'TypeError');
|
|
6456
|
+
}
|
|
6457
|
+
throwOnError = options.throwOnError !== false;
|
|
6458
|
+
}
|
|
5815
6459
|
if (typeof toolName !== 'string' || !toolName) {
|
|
5816
6460
|
throw makeError('Tool name must be a non-empty string', 'TypeError');
|
|
5817
6461
|
}
|
|
@@ -5837,7 +6481,7 @@ var init_vm_adapter = __esm({
|
|
|
5837
6481
|
throw makeError('Tool request must be JSON-serializable', 'TypeError');
|
|
5838
6482
|
}
|
|
5839
6483
|
|
|
5840
|
-
if (
|
|
6484
|
+
if (exceedsPayloadLimit(requestJson)) {
|
|
5841
6485
|
throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
|
|
5842
6486
|
}
|
|
5843
6487
|
|
|
@@ -5845,8 +6489,24 @@ var init_vm_adapter = __esm({
|
|
|
5845
6489
|
if (typeof responseJson !== 'string') {
|
|
5846
6490
|
throw makeError('Tool bridge returned invalid response', 'Error');
|
|
5847
6491
|
}
|
|
5848
|
-
|
|
5849
|
-
|
|
6492
|
+
// The host refuses an oversized response as a tool failure; this check only backs it
|
|
6493
|
+
// up, and reports the same way so { throwOnError: false } resolves it to a result.
|
|
6494
|
+
if (exceedsPayloadLimit(responseJson)) {
|
|
6495
|
+
var tooLarge = 'Tool response exceeds maximum size (' + maxBytes + ' bytes)';
|
|
6496
|
+
if (!throwOnError) {
|
|
6497
|
+
return {
|
|
6498
|
+
__proto__: null,
|
|
6499
|
+
success: false,
|
|
6500
|
+
error: {
|
|
6501
|
+
__proto__: null,
|
|
6502
|
+
name: 'RangeError',
|
|
6503
|
+
message: tooLarge,
|
|
6504
|
+
toolName: toolName,
|
|
6505
|
+
code: 'TOOL_BRIDGE_RESPONSE_TOO_LARGE',
|
|
6506
|
+
},
|
|
6507
|
+
};
|
|
6508
|
+
}
|
|
6509
|
+
throw makeError(tooLarge, 'RangeError');
|
|
5850
6510
|
}
|
|
5851
6511
|
|
|
5852
6512
|
var response;
|
|
@@ -5861,13 +6521,18 @@ var init_vm_adapter = __esm({
|
|
|
5861
6521
|
}
|
|
5862
6522
|
|
|
5863
6523
|
if (response.ok === true) {
|
|
5864
|
-
|
|
5865
|
-
return
|
|
6524
|
+
var value = hasOwn.call(response, 'value') ? response.value : undefined;
|
|
6525
|
+
return throwOnError ? value : { __proto__: null, success: true, data: value };
|
|
5866
6526
|
}
|
|
5867
6527
|
|
|
5868
6528
|
if (response.ok === false && response.error) {
|
|
5869
6529
|
var msg = (typeof response.error.message === 'string') ? response.error.message : 'Tool call failed';
|
|
5870
6530
|
var name = (typeof response.error.name === 'string') ? response.error.name : 'Error';
|
|
6531
|
+
if (!throwOnError && response.error.toolError === true) {
|
|
6532
|
+
var info = { __proto__: null, name: name, message: msg, toolName: toolName };
|
|
6533
|
+
if (typeof response.error.code === 'string') info.code = response.error.code;
|
|
6534
|
+
return { __proto__: null, success: false, error: info };
|
|
6535
|
+
}
|
|
5871
6536
|
throw makeError(msg, name);
|
|
5872
6537
|
}
|
|
5873
6538
|
|
|
@@ -5901,8 +6566,9 @@ var init_vm_adapter = __esm({
|
|
|
5901
6566
|
}
|
|
5902
6567
|
if (config.globals) {
|
|
5903
6568
|
for (const [key, value2] of Object.entries(config.globals)) {
|
|
5904
|
-
const wrappedValue = value2 !== null && typeof value2 === "object" ? createSecureProxy(value2, {
|
|
5905
|
-
levelConfig: executionContext.secureProxyConfig
|
|
6569
|
+
const wrappedValue = value2 !== null && (typeof value2 === "object" || typeof value2 === "function") ? createSecureProxy(value2, {
|
|
6570
|
+
levelConfig: executionContext.secureProxyConfig,
|
|
6571
|
+
callGate: globalFunctionGate
|
|
5906
6572
|
}) : value2;
|
|
5907
6573
|
Object.defineProperty(baseSandbox, key, {
|
|
5908
6574
|
value: wrappedValue,
|
|
@@ -5912,6 +6578,23 @@ var init_vm_adapter = __esm({
|
|
|
5912
6578
|
});
|
|
5913
6579
|
}
|
|
5914
6580
|
}
|
|
6581
|
+
if (executionContext.toolNamespaces?.length) {
|
|
6582
|
+
const callTool = baseSandbox["__safe_callTool"];
|
|
6583
|
+
for (const binding of buildToolNamespaceBindings(
|
|
6584
|
+
installToolNamespaces,
|
|
6585
|
+
callTool,
|
|
6586
|
+
executionContext.toolNamespaces
|
|
6587
|
+
)) {
|
|
6588
|
+
for (const name of [binding.name, `__safe_${binding.name}`]) {
|
|
6589
|
+
Object.defineProperty(baseSandbox, name, {
|
|
6590
|
+
value: binding.value,
|
|
6591
|
+
writable: false,
|
|
6592
|
+
configurable: false,
|
|
6593
|
+
enumerable: false
|
|
6594
|
+
});
|
|
6595
|
+
}
|
|
6596
|
+
}
|
|
6597
|
+
}
|
|
5915
6598
|
if (!("__safe_console" in safeRuntime)) {
|
|
5916
6599
|
const consoleStats = { totalBytes: 0, callCount: 0 };
|
|
5917
6600
|
Object.defineProperty(baseSandbox, "__safe_console", {
|
|
@@ -5934,7 +6617,7 @@ var init_vm_adapter = __esm({
|
|
|
5934
6617
|
const _protectedSandbox = createProtectedSandbox(baseSandbox);
|
|
5935
6618
|
this.context = baseSandbox;
|
|
5936
6619
|
const wrappedCode = "(async () => {\n" + code + '\nreturn typeof __ag_main === "function" ? await __ag_main() : undefined;\n})();';
|
|
5937
|
-
const script = new
|
|
6620
|
+
const script = new vm4.Script(wrappedCode, {
|
|
5938
6621
|
filename: "agentscript.js"
|
|
5939
6622
|
});
|
|
5940
6623
|
const resultPromise = script.runInContext(this.context, {
|
|
@@ -5983,7 +6666,9 @@ var init_vm_adapter = __esm({
|
|
|
5983
6666
|
maxDepth: clampedDepth,
|
|
5984
6667
|
maxProperties: clampedProperties,
|
|
5985
6668
|
allowDates: true,
|
|
5986
|
-
allowErrors: true
|
|
6669
|
+
allowErrors: true,
|
|
6670
|
+
// The membrane wraps the script's Dates; read them through their targets.
|
|
6671
|
+
unwrap: unwrapSecureProxy
|
|
5987
6672
|
});
|
|
5988
6673
|
return {
|
|
5989
6674
|
success: true,
|
|
@@ -6019,7 +6704,7 @@ var init_vm_adapter = __esm({
|
|
|
6019
6704
|
error: {
|
|
6020
6705
|
name: err.name || "VMExecutionError",
|
|
6021
6706
|
message: err.message || "Unknown VM execution error",
|
|
6022
|
-
stack:
|
|
6707
|
+
stack: sanitizeStackTrace(err.stack, shouldSanitize),
|
|
6023
6708
|
code: "VM_EXECUTION_ERROR"
|
|
6024
6709
|
},
|
|
6025
6710
|
stats
|
|
@@ -6163,6 +6848,7 @@ var init_config = __esm({
|
|
|
6163
6848
|
|
|
6164
6849
|
// libs/core/src/adapters/worker-pool/protocol.ts
|
|
6165
6850
|
import { z } from "zod";
|
|
6851
|
+
import { TOOL_NAMESPACE_TOOL_NAME_PATTERN } from "@enclave-vm/ast";
|
|
6166
6852
|
function isToolCallMessage(msg) {
|
|
6167
6853
|
return msg.type === "tool-call";
|
|
6168
6854
|
}
|
|
@@ -6176,7 +6862,7 @@ var TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessage
|
|
|
6176
6862
|
var init_protocol = __esm({
|
|
6177
6863
|
"libs/core/src/adapters/worker-pool/protocol.ts"() {
|
|
6178
6864
|
"use strict";
|
|
6179
|
-
TOOL_NAME_PATTERN =
|
|
6865
|
+
TOOL_NAME_PATTERN = TOOL_NAMESPACE_TOOL_NAME_PATTERN;
|
|
6180
6866
|
ID_PATTERN = /^[a-zA-Z0-9-]+$/;
|
|
6181
6867
|
toolCallMessageSchema = z.object({
|
|
6182
6868
|
type: z.literal("tool-call"),
|
|
@@ -6190,6 +6876,13 @@ var init_protocol = __esm({
|
|
|
6190
6876
|
requestId: z.string().min(1).max(100).regex(ID_PATTERN),
|
|
6191
6877
|
success: z.boolean(),
|
|
6192
6878
|
value: z.unknown().optional(),
|
|
6879
|
+
specialValues: z.array(
|
|
6880
|
+
z.object({
|
|
6881
|
+
path: z.array(z.union([z.string(), z.number().int().nonnegative()])).max(64),
|
|
6882
|
+
kind: z.enum(["date", "nan", "infinity", "-infinity", "undefined"]),
|
|
6883
|
+
time: z.number().nullable().optional()
|
|
6884
|
+
}).strict()
|
|
6885
|
+
).optional(),
|
|
6193
6886
|
error: z.object({
|
|
6194
6887
|
name: z.string().max(100),
|
|
6195
6888
|
message: z.string().max(1e4),
|
|
@@ -6408,7 +7101,7 @@ function sanitizeObjectWithDepthCheck(value, depth) {
|
|
|
6408
7101
|
if (typeof value !== "object") {
|
|
6409
7102
|
return value;
|
|
6410
7103
|
}
|
|
6411
|
-
if (
|
|
7104
|
+
if (ArrayIsArray3(value)) {
|
|
6412
7105
|
return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
|
|
6413
7106
|
}
|
|
6414
7107
|
const result = /* @__PURE__ */ Object.create(null);
|
|
@@ -6427,6 +7120,9 @@ function safeSerialize(value) {
|
|
|
6427
7120
|
return val;
|
|
6428
7121
|
});
|
|
6429
7122
|
}
|
|
7123
|
+
function isDangerousKey(key) {
|
|
7124
|
+
return DANGEROUS_KEYS2.has(key);
|
|
7125
|
+
}
|
|
6430
7126
|
function sanitizeObject(value, depth = 0) {
|
|
6431
7127
|
if (depth > MAX_DEPTH) {
|
|
6432
7128
|
return void 0;
|
|
@@ -6437,7 +7133,7 @@ function sanitizeObject(value, depth = 0) {
|
|
|
6437
7133
|
if (typeof value !== "object") {
|
|
6438
7134
|
return value;
|
|
6439
7135
|
}
|
|
6440
|
-
if (
|
|
7136
|
+
if (ArrayIsArray3(value)) {
|
|
6441
7137
|
return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
|
|
6442
7138
|
}
|
|
6443
7139
|
const result = /* @__PURE__ */ Object.create(null);
|
|
@@ -6448,13 +7144,13 @@ function sanitizeObject(value, depth = 0) {
|
|
|
6448
7144
|
}
|
|
6449
7145
|
return result;
|
|
6450
7146
|
}
|
|
6451
|
-
var ReflectGet4,
|
|
7147
|
+
var ReflectGet4, ArrayIsArray3, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
|
|
6452
7148
|
var init_safe_deserialize = __esm({
|
|
6453
7149
|
"libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
|
|
6454
7150
|
"use strict";
|
|
6455
7151
|
init_errors();
|
|
6456
7152
|
ReflectGet4 = Reflect.get;
|
|
6457
|
-
|
|
7153
|
+
ArrayIsArray3 = Array.isArray;
|
|
6458
7154
|
NumberIsFinite3 = Number.isFinite;
|
|
6459
7155
|
MathFloor3 = Math.floor;
|
|
6460
7156
|
MAX_ARRAY_LENGTH = 1e6;
|
|
@@ -7153,6 +7849,75 @@ var init_rate_limiter = __esm({
|
|
|
7153
7849
|
}
|
|
7154
7850
|
});
|
|
7155
7851
|
|
|
7852
|
+
// libs/core/src/adapters/worker-pool/result-encoding.ts
|
|
7853
|
+
function decodeResult(value, specialValues) {
|
|
7854
|
+
if (specialValues === void 0) {
|
|
7855
|
+
return value;
|
|
7856
|
+
}
|
|
7857
|
+
if (!Array.isArray(specialValues)) {
|
|
7858
|
+
throw new MessageValidationError("Worker result special values must be an array");
|
|
7859
|
+
}
|
|
7860
|
+
let decoded = value;
|
|
7861
|
+
for (const special of specialValues) {
|
|
7862
|
+
assertSpecialValue(special);
|
|
7863
|
+
const restored = restoreSpecialValue(special);
|
|
7864
|
+
if (special.path.length === 0) {
|
|
7865
|
+
decoded = restored;
|
|
7866
|
+
continue;
|
|
7867
|
+
}
|
|
7868
|
+
const container = resolveContainer(decoded, special.path.slice(0, -1));
|
|
7869
|
+
const key = special.path[special.path.length - 1];
|
|
7870
|
+
if (!container || !Object.hasOwn(container, key) || container[key] !== null) {
|
|
7871
|
+
throw new MessageValidationError("Worker result refers to a value it does not contain");
|
|
7872
|
+
}
|
|
7873
|
+
container[key] = restored;
|
|
7874
|
+
}
|
|
7875
|
+
return decoded;
|
|
7876
|
+
}
|
|
7877
|
+
function assertSpecialValue(special) {
|
|
7878
|
+
const candidate = special;
|
|
7879
|
+
const validPath = Array.isArray(candidate?.path) && candidate.path.every((key) => typeof key === "string" || Number.isInteger(key) && key >= 0);
|
|
7880
|
+
if (!validPath || !SPECIAL_KINDS.has(candidate?.kind)) {
|
|
7881
|
+
throw new MessageValidationError("Worker result has an invalid special value");
|
|
7882
|
+
}
|
|
7883
|
+
}
|
|
7884
|
+
function resolveContainer(root, path2) {
|
|
7885
|
+
let current = root;
|
|
7886
|
+
for (const key of path2) {
|
|
7887
|
+
if (!isDataContainer(current) || isDangerousKey(String(key)) || !Object.hasOwn(current, key)) {
|
|
7888
|
+
return void 0;
|
|
7889
|
+
}
|
|
7890
|
+
current = current[key];
|
|
7891
|
+
}
|
|
7892
|
+
return isDataContainer(current) ? current : void 0;
|
|
7893
|
+
}
|
|
7894
|
+
function isDataContainer(value) {
|
|
7895
|
+
return Array.isArray(value) || typeof value === "object" && value !== null && Object.getPrototypeOf(value) === null;
|
|
7896
|
+
}
|
|
7897
|
+
function restoreSpecialValue(special) {
|
|
7898
|
+
switch (special.kind) {
|
|
7899
|
+
case "date":
|
|
7900
|
+
return new Date(typeof special.time === "number" ? special.time : NaN);
|
|
7901
|
+
case "nan":
|
|
7902
|
+
return NaN;
|
|
7903
|
+
case "infinity":
|
|
7904
|
+
return Infinity;
|
|
7905
|
+
case "-infinity":
|
|
7906
|
+
return -Infinity;
|
|
7907
|
+
case "undefined":
|
|
7908
|
+
return void 0;
|
|
7909
|
+
}
|
|
7910
|
+
}
|
|
7911
|
+
var SPECIAL_KINDS;
|
|
7912
|
+
var init_result_encoding = __esm({
|
|
7913
|
+
"libs/core/src/adapters/worker-pool/result-encoding.ts"() {
|
|
7914
|
+
"use strict";
|
|
7915
|
+
init_errors();
|
|
7916
|
+
init_safe_deserialize();
|
|
7917
|
+
SPECIAL_KINDS = /* @__PURE__ */ new Set(["date", "nan", "infinity", "-infinity", "undefined"]);
|
|
7918
|
+
}
|
|
7919
|
+
});
|
|
7920
|
+
|
|
7156
7921
|
// libs/core/src/adapters/worker-pool/worker-pool-adapter.ts
|
|
7157
7922
|
import crypto from "crypto";
|
|
7158
7923
|
var WorkerPoolAdapter;
|
|
@@ -7166,7 +7931,9 @@ var init_worker_pool_adapter = __esm({
|
|
|
7166
7931
|
init_memory_monitor();
|
|
7167
7932
|
init_rate_limiter();
|
|
7168
7933
|
init_safe_deserialize();
|
|
7934
|
+
init_result_encoding();
|
|
7169
7935
|
init_errors();
|
|
7936
|
+
init_stack_trace();
|
|
7170
7937
|
WorkerPoolAdapter = class {
|
|
7171
7938
|
config;
|
|
7172
7939
|
securityLevel;
|
|
@@ -7405,7 +8172,8 @@ var init_worker_pool_adapter = __esm({
|
|
|
7405
8172
|
globals: context.config.globals,
|
|
7406
8173
|
// Security level determines which globals are available in sandbox
|
|
7407
8174
|
// This mirrors AST guard's allowed globals for defense-in-depth
|
|
7408
|
-
securityLevel: this.securityLevel
|
|
8175
|
+
securityLevel: this.securityLevel,
|
|
8176
|
+
toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0
|
|
7409
8177
|
};
|
|
7410
8178
|
return new Promise((resolve, reject) => {
|
|
7411
8179
|
const pendingToolCalls = /* @__PURE__ */ new Map();
|
|
@@ -7422,7 +8190,7 @@ var init_worker_pool_adapter = __esm({
|
|
|
7422
8190
|
} else if (isExecutionResultMessage(msg) && msg.requestId === requestId) {
|
|
7423
8191
|
cleanup();
|
|
7424
8192
|
const duration = Date.now() - startTime;
|
|
7425
|
-
const result = this.buildResult(msg, duration);
|
|
8193
|
+
const result = this.buildResult(msg, duration, context.config.sanitizeStackTraces);
|
|
7426
8194
|
resolve(result);
|
|
7427
8195
|
} else if (isConsoleMessage(msg) && msg.requestId === requestId) {
|
|
7428
8196
|
this.handleConsoleMessage(msg);
|
|
@@ -7463,17 +8231,30 @@ var init_worker_pool_adapter = __esm({
|
|
|
7463
8231
|
pendingToolCalls.set(msg.callId, true);
|
|
7464
8232
|
let result;
|
|
7465
8233
|
let error;
|
|
8234
|
+
let toolError = false;
|
|
7466
8235
|
try {
|
|
7467
8236
|
if (!context.toolHandler) {
|
|
7468
8237
|
throw new Error("No tool handler configured");
|
|
7469
8238
|
}
|
|
7470
8239
|
const sanitizedArgs = sanitizeObject(msg.args);
|
|
7471
|
-
|
|
8240
|
+
toolError = true;
|
|
8241
|
+
const handlerResult = await context.toolHandler(msg.toolName, sanitizedArgs);
|
|
8242
|
+
try {
|
|
8243
|
+
result = sanitizeObject(handlerResult);
|
|
8244
|
+
} catch {
|
|
8245
|
+
throw Object.assign(new Error("Tool returned an unsupported value"), {
|
|
8246
|
+
name: "ToolBridgeError",
|
|
8247
|
+
code: "TOOL_RESULT_NOT_SAFE"
|
|
8248
|
+
});
|
|
8249
|
+
}
|
|
8250
|
+
toolError = false;
|
|
7472
8251
|
} catch (e) {
|
|
7473
8252
|
const err = e;
|
|
8253
|
+
const code = e?.code;
|
|
7474
8254
|
error = {
|
|
7475
8255
|
name: err.name || "Error",
|
|
7476
|
-
message: err.message || "Unknown error"
|
|
8256
|
+
message: err.message || "Unknown error",
|
|
8257
|
+
...toolError && typeof code === "string" ? { code } : {}
|
|
7477
8258
|
};
|
|
7478
8259
|
} finally {
|
|
7479
8260
|
pendingToolCalls.delete(msg.callId);
|
|
@@ -7482,8 +8263,9 @@ var init_worker_pool_adapter = __esm({
|
|
|
7482
8263
|
type: "tool-response",
|
|
7483
8264
|
requestId: msg.requestId,
|
|
7484
8265
|
callId: msg.callId,
|
|
7485
|
-
result
|
|
7486
|
-
error
|
|
8266
|
+
result,
|
|
8267
|
+
error,
|
|
8268
|
+
...error && toolError ? { toolError: true } : {}
|
|
7487
8269
|
});
|
|
7488
8270
|
}
|
|
7489
8271
|
handleConsoleMessage(msg) {
|
|
@@ -7495,16 +8277,15 @@ var init_worker_pool_adapter = __esm({
|
|
|
7495
8277
|
/**
|
|
7496
8278
|
* Build result from worker message.
|
|
7497
8279
|
*
|
|
7498
|
-
* Note: The `
|
|
7499
|
-
*
|
|
7500
|
-
*
|
|
7501
|
-
* definitions which are not available at this layer.
|
|
8280
|
+
* Note: The `as T` assertion is inherent to cross-thread serialization boundaries. The
|
|
8281
|
+
* worker sanitizes the result with sanitizeValue() and sends the values JSON cannot carry
|
|
8282
|
+
* (Dates, NaN, ...) separately; decodeResult() puts them back and refuses a malformed list.
|
|
7502
8283
|
*/
|
|
7503
|
-
buildResult(msg, duration) {
|
|
8284
|
+
buildResult(msg, duration, sanitizeStacks) {
|
|
7504
8285
|
if (msg.success) {
|
|
7505
8286
|
return {
|
|
7506
8287
|
success: true,
|
|
7507
|
-
value: msg.value,
|
|
8288
|
+
value: decodeResult(msg.value, msg.specialValues),
|
|
7508
8289
|
stats: {
|
|
7509
8290
|
duration,
|
|
7510
8291
|
toolCallCount: msg.stats.toolCallCount,
|
|
@@ -7521,7 +8302,8 @@ var init_worker_pool_adapter = __esm({
|
|
|
7521
8302
|
name: error.name,
|
|
7522
8303
|
message: error.message,
|
|
7523
8304
|
code: error.code,
|
|
7524
|
-
stack
|
|
8305
|
+
// The worker trims its stack; sanitize it here too so the result obeys the option.
|
|
8306
|
+
stack: sanitizeStackTrace(error.stack, sanitizeStacks)
|
|
7525
8307
|
},
|
|
7526
8308
|
stats: {
|
|
7527
8309
|
duration,
|
|
@@ -8154,7 +8936,8 @@ import {
|
|
|
8154
8936
|
extractLargeStrings,
|
|
8155
8937
|
transformConcatenation,
|
|
8156
8938
|
transformTemplateLiterals,
|
|
8157
|
-
guardComputedMemberKeys
|
|
8939
|
+
guardComputedMemberKeys,
|
|
8940
|
+
normalizeToolNamespaces
|
|
8158
8941
|
} from "@enclave-vm/ast";
|
|
8159
8942
|
import * as acorn2 from "acorn";
|
|
8160
8943
|
import { generate } from "astring";
|
|
@@ -8337,6 +9120,7 @@ var DEFAULT_DOUBLE_VM_CONFIG = {
|
|
|
8337
9120
|
};
|
|
8338
9121
|
|
|
8339
9122
|
// libs/core/src/globals-validator.ts
|
|
9123
|
+
import { types } from "util";
|
|
8340
9124
|
var DANGEROUS_FUNCTION_PATTERNS = [
|
|
8341
9125
|
/\beval\b/,
|
|
8342
9126
|
// eval() calls
|
|
@@ -8364,7 +9148,55 @@ var DANGEROUS_FUNCTION_PATTERNS = [
|
|
|
8364
9148
|
// Synchronous spawn
|
|
8365
9149
|
];
|
|
8366
9150
|
var DANGEROUS_GLOBAL_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
8367
|
-
|
|
9151
|
+
var MapEntries = Map.prototype.entries;
|
|
9152
|
+
var SetValues = Set.prototype.values;
|
|
9153
|
+
var ReflectApply = Reflect.apply;
|
|
9154
|
+
var ReflectOwnKeys = Reflect.ownKeys;
|
|
9155
|
+
var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
|
|
9156
|
+
var ObjectGetPrototypeOf = Object.getPrototypeOf;
|
|
9157
|
+
var ArrayPrototype = Array.prototype;
|
|
9158
|
+
var MapPrototype = Map.prototype;
|
|
9159
|
+
var SetPrototype = Set.prototype;
|
|
9160
|
+
var IteratorPrototype = ObjectGetPrototypeOf(ObjectGetPrototypeOf([][Symbol.iterator]()));
|
|
9161
|
+
var AsyncIteratorPrototype = ObjectGetPrototypeOf(
|
|
9162
|
+
ObjectGetPrototypeOf(
|
|
9163
|
+
async function* () {
|
|
9164
|
+
}.prototype
|
|
9165
|
+
)
|
|
9166
|
+
);
|
|
9167
|
+
function describeOpaqueContainer(obj) {
|
|
9168
|
+
if (types.isPromise(obj)) return "a Promise";
|
|
9169
|
+
if (types.isWeakMap(obj)) return "a WeakMap";
|
|
9170
|
+
if (types.isGeneratorObject(obj)) return "a generator";
|
|
9171
|
+
if (types.isMapIterator(obj) || types.isSetIterator(obj) || Object.prototype.isPrototypeOf.call(IteratorPrototype, obj) || Object.prototype.isPrototypeOf.call(AsyncIteratorPrototype, obj)) {
|
|
9172
|
+
return "an iterator";
|
|
9173
|
+
}
|
|
9174
|
+
return void 0;
|
|
9175
|
+
}
|
|
9176
|
+
function isPlainDataObject(obj) {
|
|
9177
|
+
const proto = ObjectGetPrototypeOf(obj);
|
|
9178
|
+
return proto === null || proto === Object.prototype || types.isDate(obj) || types.isRegExp(obj) || types.isArrayBufferView(obj) || types.isAnyArrayBuffer(obj);
|
|
9179
|
+
}
|
|
9180
|
+
function describeInstance(obj) {
|
|
9181
|
+
try {
|
|
9182
|
+
const name = ObjectGetPrototypeOf(obj)?.constructor?.name;
|
|
9183
|
+
if (typeof name === "string" && name) return `a ${name} instance`;
|
|
9184
|
+
} catch {
|
|
9185
|
+
}
|
|
9186
|
+
return "a non-plain object";
|
|
9187
|
+
}
|
|
9188
|
+
function collectionError(key, what, path2) {
|
|
9189
|
+
return new Error(
|
|
9190
|
+
`Custom global "${key}" contains ${what} inside a collection at ${path2.join(".") || "root"}. Only plain data (primitives, plain objects, arrays, Maps, Sets, Dates, RegExps, typed arrays) is allowed inside arrays, Maps and Sets: their built-in methods (forEach, iteration, get) hand elements to the script directly, so a function there would be called without the enclave's global-function gate. Expose functions as properties of a plain object, or as tools.`
|
|
9191
|
+
);
|
|
9192
|
+
}
|
|
9193
|
+
function mapValueSegment(mapKey, index) {
|
|
9194
|
+
if (typeof mapKey === "string" || typeof mapKey === "number" || typeof mapKey === "boolean") {
|
|
9195
|
+
return `get(${JSON.stringify(mapKey)})`;
|
|
9196
|
+
}
|
|
9197
|
+
return `values()[${index}]`;
|
|
9198
|
+
}
|
|
9199
|
+
function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet(), collectionVisited = /* @__PURE__ */ new WeakSet(), inCollection = false) {
|
|
8368
9200
|
const maxDepth = options.maxDepth ?? 10;
|
|
8369
9201
|
const allowFunctions = options.allowFunctions ?? false;
|
|
8370
9202
|
const allowGettersSetters = options.allowGettersSetters ?? false;
|
|
@@ -8388,6 +9220,9 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
|
|
|
8388
9220
|
}
|
|
8389
9221
|
if (type === "function") {
|
|
8390
9222
|
const funcName = value.name || "anonymous";
|
|
9223
|
+
if (inCollection && (allowFunctions || allowedFunctionNames.includes(funcName))) {
|
|
9224
|
+
throw collectionError(key, "a function", path2);
|
|
9225
|
+
}
|
|
8391
9226
|
if (allowedFunctionNames.includes(funcName)) {
|
|
8392
9227
|
return;
|
|
8393
9228
|
}
|
|
@@ -8414,35 +9249,89 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
|
|
|
8414
9249
|
}
|
|
8415
9250
|
if (type === "object") {
|
|
8416
9251
|
const obj = value;
|
|
8417
|
-
|
|
9252
|
+
const seen = inCollection ? collectionVisited : visited;
|
|
9253
|
+
if (seen.has(obj)) {
|
|
8418
9254
|
return;
|
|
8419
9255
|
}
|
|
8420
|
-
|
|
9256
|
+
seen.add(obj);
|
|
9257
|
+
const opaque = describeOpaqueContainer(obj);
|
|
9258
|
+
if (opaque) {
|
|
9259
|
+
throw new Error(
|
|
9260
|
+
`Custom global "${key}" contains ${opaque} at ${path2.join(".") || "root"}. Promises, WeakMaps, iterators and generators are not allowed in custom globals: their contents cannot be validated, and their built-in methods hand those contents to the script directly.`
|
|
9261
|
+
);
|
|
9262
|
+
}
|
|
9263
|
+
const isArray = Array.isArray(obj);
|
|
9264
|
+
const isMap = types.isMap(obj);
|
|
9265
|
+
const isSet = types.isSet(obj);
|
|
9266
|
+
if (isArray) {
|
|
9267
|
+
const hidden = types.isProxy(obj) ? "a Proxy array" : ObjectGetPrototypeOf(obj) !== ArrayPrototype ? "an array with a custom prototype" : void 0;
|
|
9268
|
+
if (hidden) {
|
|
9269
|
+
throw new Error(
|
|
9270
|
+
`Custom global "${key}" contains ${hidden} at ${path2.join(".") || "root"}. Only plain arrays are allowed in custom globals: their built-in methods (forEach, iteration) read entries that a Proxy or a prototype can hide from validation, and hand them to the script directly.`
|
|
9271
|
+
);
|
|
9272
|
+
}
|
|
9273
|
+
}
|
|
9274
|
+
if (inCollection) {
|
|
9275
|
+
if (types.isProxy(obj)) {
|
|
9276
|
+
throw collectionError(key, "a Proxy", path2);
|
|
9277
|
+
}
|
|
9278
|
+
if (!isArray && !isMap && !isSet && !isPlainDataObject(obj)) {
|
|
9279
|
+
throw collectionError(key, describeInstance(obj), path2);
|
|
9280
|
+
}
|
|
9281
|
+
if ((isMap || isSet) && ObjectGetPrototypeOf(obj) !== (isMap ? MapPrototype : SetPrototype)) {
|
|
9282
|
+
throw collectionError(key, describeInstance(obj), path2);
|
|
9283
|
+
}
|
|
9284
|
+
}
|
|
8421
9285
|
if (!allowGettersSetters) {
|
|
8422
|
-
const
|
|
8423
|
-
|
|
8424
|
-
if (desc.get || desc.set) {
|
|
9286
|
+
for (const prop of ReflectOwnKeys(obj)) {
|
|
9287
|
+
const desc = ReflectGetOwnPropertyDescriptor(obj, prop);
|
|
9288
|
+
if (desc && (desc.get || desc.set)) {
|
|
9289
|
+
const at = [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`].join(".");
|
|
8425
9290
|
throw new Error(
|
|
8426
|
-
`Custom global "${key}" has a getter/setter at ${
|
|
9291
|
+
`Custom global "${key}" has a getter/setter at ${at}. Getters and setters are not allowed because they can execute arbitrary code on property access. Use allowGettersSetters: true if you understand the security implications.`
|
|
8427
9292
|
);
|
|
8428
9293
|
}
|
|
8429
9294
|
}
|
|
8430
9295
|
}
|
|
8431
|
-
if (
|
|
8432
|
-
|
|
8433
|
-
|
|
9296
|
+
if (isMap) {
|
|
9297
|
+
let index = 0;
|
|
9298
|
+
for (const [mapKey, mapValue] of ReflectApply(MapEntries, obj, [])) {
|
|
9299
|
+
validateGlobalValue(key, mapKey, options, [...path2, `keys()[${index}]`], visited, collectionVisited, true);
|
|
9300
|
+
validateGlobalValue(
|
|
9301
|
+
key,
|
|
9302
|
+
mapValue,
|
|
9303
|
+
options,
|
|
9304
|
+
[...path2, mapValueSegment(mapKey, index)],
|
|
9305
|
+
visited,
|
|
9306
|
+
collectionVisited,
|
|
9307
|
+
true
|
|
9308
|
+
);
|
|
9309
|
+
index++;
|
|
9310
|
+
}
|
|
9311
|
+
} else if (isSet) {
|
|
9312
|
+
let index = 0;
|
|
9313
|
+
for (const element of ReflectApply(SetValues, obj, [])) {
|
|
9314
|
+
validateGlobalValue(key, element, options, [...path2, `values()[${index}]`], visited, collectionVisited, true);
|
|
9315
|
+
index++;
|
|
8434
9316
|
}
|
|
8435
|
-
return;
|
|
8436
9317
|
}
|
|
8437
|
-
const keys = Object.keys(obj);
|
|
9318
|
+
const keys = isArray || inCollection ? ReflectOwnKeys(obj) : Object.keys(obj);
|
|
8438
9319
|
for (const prop of keys) {
|
|
8439
|
-
if (DANGEROUS_GLOBAL_KEYS.has(prop)) {
|
|
9320
|
+
if (typeof prop === "string" && DANGEROUS_GLOBAL_KEYS.has(prop)) {
|
|
8440
9321
|
throw new Error(
|
|
8441
9322
|
`Custom global "${key}" contains dangerous key "${prop}" at ${path2.join(".") || "root"}. Keys like "__proto__", "constructor", and "prototype" are not allowed.`
|
|
8442
9323
|
);
|
|
8443
9324
|
}
|
|
8444
9325
|
const propValue = obj[prop];
|
|
8445
|
-
validateGlobalValue(
|
|
9326
|
+
validateGlobalValue(
|
|
9327
|
+
key,
|
|
9328
|
+
propValue,
|
|
9329
|
+
options,
|
|
9330
|
+
[...path2, typeof prop === "string" ? prop : `[${String(prop)}]`],
|
|
9331
|
+
visited,
|
|
9332
|
+
collectionVisited,
|
|
9333
|
+
inCollection || isArray
|
|
9334
|
+
);
|
|
8446
9335
|
}
|
|
8447
9336
|
return;
|
|
8448
9337
|
}
|
|
@@ -10335,6 +11224,21 @@ function createScoringGate(config) {
|
|
|
10335
11224
|
return new ScoringGate(config);
|
|
10336
11225
|
}
|
|
10337
11226
|
|
|
11227
|
+
// libs/core/src/enclave.ts
|
|
11228
|
+
init_global_function_gate();
|
|
11229
|
+
init_stack_trace();
|
|
11230
|
+
|
|
11231
|
+
// libs/core/src/node-vm.ts
|
|
11232
|
+
import * as vm2 from "vm";
|
|
11233
|
+
function assertNodeVmAvailable() {
|
|
11234
|
+
if (typeof vm2.createContext === "function" && typeof vm2.Script === "function") {
|
|
11235
|
+
return;
|
|
11236
|
+
}
|
|
11237
|
+
throw new Error(
|
|
11238
|
+
"@enclave-vm/core needs node:vm, which this runtime does not provide. In a browser, use @enclave-vm/browser; elsewhere, pass a sandboxAdapter (for example new InterpreterAdapter())."
|
|
11239
|
+
);
|
|
11240
|
+
}
|
|
11241
|
+
|
|
10338
11242
|
// libs/core/src/enclave.ts
|
|
10339
11243
|
var DEFAULT_SECURITY_LEVEL = "STANDARD";
|
|
10340
11244
|
var DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
@@ -10390,6 +11294,8 @@ var Enclave = class {
|
|
|
10390
11294
|
scoringGate;
|
|
10391
11295
|
doubleVmConfig;
|
|
10392
11296
|
customGlobalNames;
|
|
11297
|
+
toolNamespaces;
|
|
11298
|
+
sandboxAdapter;
|
|
10393
11299
|
adapter;
|
|
10394
11300
|
constructor(options = {}) {
|
|
10395
11301
|
this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
|
|
@@ -10445,6 +11351,12 @@ var Enclave = class {
|
|
|
10445
11351
|
}
|
|
10446
11352
|
};
|
|
10447
11353
|
}
|
|
11354
|
+
this.toolNamespaces = normalizeToolNamespaces(options.toolNamespaces, {
|
|
11355
|
+
reservedNames: Object.keys(initialGlobals)
|
|
11356
|
+
});
|
|
11357
|
+
if (options.maxGlobalFunctionCalls !== void 0 && !(Number.isInteger(options.maxGlobalFunctionCalls) && options.maxGlobalFunctionCalls >= 0)) {
|
|
11358
|
+
throw new TypeError("maxGlobalFunctionCalls must be a non-negative integer");
|
|
11359
|
+
}
|
|
10448
11360
|
this.config = {
|
|
10449
11361
|
...BASE_CONFIG,
|
|
10450
11362
|
timeout: securityConfig.timeout,
|
|
@@ -10459,9 +11371,13 @@ var Enclave = class {
|
|
|
10459
11371
|
toolBridge: normalizedToolBridge,
|
|
10460
11372
|
// secureProxyConfig must come AFTER options spread to use the merged config
|
|
10461
11373
|
secureProxyConfig: securityConfig.secureProxyConfig,
|
|
10462
|
-
globals: initialGlobals
|
|
11374
|
+
globals: initialGlobals,
|
|
11375
|
+
maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls({
|
|
11376
|
+
maxToolCalls: securityConfig.maxToolCalls,
|
|
11377
|
+
maxGlobalFunctionCalls: options.maxGlobalFunctionCalls
|
|
11378
|
+
})
|
|
10463
11379
|
};
|
|
10464
|
-
this.customGlobalNames = Object.keys(initialGlobals);
|
|
11380
|
+
this.customGlobalNames = [...Object.keys(initialGlobals), ...this.toolNamespaces.map((ns) => ns.name)];
|
|
10465
11381
|
const customAllowedGlobals = this.customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
|
|
10466
11382
|
this.validator = this.createValidator(presetName, customAllowedGlobals);
|
|
10467
11383
|
this.validateCode = options.validate !== false;
|
|
@@ -10471,6 +11387,10 @@ var Enclave = class {
|
|
|
10471
11387
|
this.scoringGate = new ScoringGate(options.scoringGate);
|
|
10472
11388
|
}
|
|
10473
11389
|
this.doubleVmConfig = this.buildDoubleVmConfig(options.doubleVm);
|
|
11390
|
+
if (options.sandboxAdapter !== void 0 && !isSandboxAdapter(options.sandboxAdapter)) {
|
|
11391
|
+
throw new TypeError("sandboxAdapter must have execute(code, context) and dispose() methods");
|
|
11392
|
+
}
|
|
11393
|
+
this.sandboxAdapter = options.sandboxAdapter;
|
|
10474
11394
|
}
|
|
10475
11395
|
/**
|
|
10476
11396
|
* Build double VM configuration from user options
|
|
@@ -10505,11 +11425,31 @@ var Enclave = class {
|
|
|
10505
11425
|
/**
|
|
10506
11426
|
* Execute AgentScript code
|
|
10507
11427
|
*
|
|
11428
|
+
* Every error returned obeys `sanitizeStackTraces`, whichever stage raised it.
|
|
11429
|
+
*
|
|
10508
11430
|
* @param code AgentScript code to execute
|
|
10509
11431
|
* @param toolHandler Optional tool handler (overrides constructor config)
|
|
10510
11432
|
* @returns Execution result
|
|
10511
11433
|
*/
|
|
10512
11434
|
async run(code, toolHandler) {
|
|
11435
|
+
const result = await this.execute(code, toolHandler);
|
|
11436
|
+
return this.applyStackTracePolicy(result);
|
|
11437
|
+
}
|
|
11438
|
+
/**
|
|
11439
|
+
* Single exit for returned errors: with `sanitizeStackTraces` on, strip host paths, file
|
|
11440
|
+
* locations and frames from the stack, whichever stage (validation, transform, compile,
|
|
11441
|
+
* execution, tool call) and adapter produced the error.
|
|
11442
|
+
*/
|
|
11443
|
+
applyStackTracePolicy(result) {
|
|
11444
|
+
if (result.success || !result.error?.stack || !this.config.sanitizeStackTraces) {
|
|
11445
|
+
return result;
|
|
11446
|
+
}
|
|
11447
|
+
return { ...result, error: { ...result.error, stack: sanitizeStackTrace(result.error.stack, true) } };
|
|
11448
|
+
}
|
|
11449
|
+
/**
|
|
11450
|
+
* Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
|
|
11451
|
+
*/
|
|
11452
|
+
async execute(code, toolHandler) {
|
|
10513
11453
|
const startTime = Date.now();
|
|
10514
11454
|
const stats = {
|
|
10515
11455
|
duration: 0,
|
|
@@ -10594,7 +11534,8 @@ ${errorMessages}`,
|
|
|
10594
11534
|
toolHandler: toolHandler || this.config.toolHandler,
|
|
10595
11535
|
sidecar,
|
|
10596
11536
|
referenceConfig: this.referenceConfig,
|
|
10597
|
-
secureProxyConfig: this.config.secureProxyConfig
|
|
11537
|
+
secureProxyConfig: this.config.secureProxyConfig,
|
|
11538
|
+
toolNamespaces: this.toolNamespaces
|
|
10598
11539
|
};
|
|
10599
11540
|
const timeoutId = setTimeout(() => {
|
|
10600
11541
|
context.aborted = true;
|
|
@@ -10710,7 +11651,8 @@ ${errorMessages}`,
|
|
|
10710
11651
|
/**
|
|
10711
11652
|
* Get or create the sandbox adapter
|
|
10712
11653
|
*
|
|
10713
|
-
*
|
|
11654
|
+
* A host-supplied `sandboxAdapter` is used as is. Otherwise, when double VM is enabled
|
|
11655
|
+
* (default), the base adapter is wrapped
|
|
10714
11656
|
* with a double VM layer that provides:
|
|
10715
11657
|
* - Nested VM isolation (Parent VM + Inner VM)
|
|
10716
11658
|
* - Enhanced tool call validation
|
|
@@ -10718,9 +11660,15 @@ ${errorMessages}`,
|
|
|
10718
11660
|
* - Defense-in-depth against VM escape attacks
|
|
10719
11661
|
*/
|
|
10720
11662
|
async getAdapter() {
|
|
11663
|
+
if (this.sandboxAdapter) {
|
|
11664
|
+
return this.sandboxAdapter;
|
|
11665
|
+
}
|
|
10721
11666
|
if (this.adapter) {
|
|
10722
11667
|
return this.adapter;
|
|
10723
11668
|
}
|
|
11669
|
+
if (this.doubleVmConfig.enabled || this.config.adapter === "vm") {
|
|
11670
|
+
assertNodeVmAvailable();
|
|
11671
|
+
}
|
|
10724
11672
|
if (this.doubleVmConfig.enabled) {
|
|
10725
11673
|
const { wrapWithDoubleVm: wrapWithDoubleVm3 } = await Promise.resolve().then(() => (init_double_vm(), double_vm_exports));
|
|
10726
11674
|
this.adapter = wrapWithDoubleVm3(void 0, this.doubleVmConfig, this.securityLevel);
|
|
@@ -10863,6 +11811,10 @@ ${errorMessages}`,
|
|
|
10863
11811
|
return uniqueErrors.join("\n");
|
|
10864
11812
|
}
|
|
10865
11813
|
};
|
|
11814
|
+
function isSandboxAdapter(value) {
|
|
11815
|
+
const candidate = value;
|
|
11816
|
+
return typeof candidate === "object" && candidate !== null && typeof candidate.execute === "function" && typeof candidate.dispose === "function";
|
|
11817
|
+
}
|
|
10866
11818
|
async function runAgentScript(code, options = {}) {
|
|
10867
11819
|
const enclave = new Enclave(options);
|
|
10868
11820
|
try {
|
|
@@ -11472,6 +12424,7 @@ function applyBinary(op, l, r) {
|
|
|
11472
12424
|
}
|
|
11473
12425
|
|
|
11474
12426
|
// libs/core/src/adapters/interpreter-adapter.ts
|
|
12427
|
+
init_stack_trace();
|
|
11475
12428
|
var SAFE_GLOBALS = Object.freeze({ Math, JSON });
|
|
11476
12429
|
var DEFAULT_MAX_STEPS = 5e6;
|
|
11477
12430
|
var DEFAULT_MAX_CALL_DEPTH = 256;
|
|
@@ -11482,6 +12435,7 @@ var InterpreterAdapter = class {
|
|
|
11482
12435
|
async execute(code, context) {
|
|
11483
12436
|
const startTime = Date.now();
|
|
11484
12437
|
let toolCallCount = 0;
|
|
12438
|
+
const sanitizeStacks = context.config.sanitizeStackTraces === true;
|
|
11485
12439
|
const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
|
|
11486
12440
|
const toolHandler = context.toolHandler ?? context.config.toolHandler;
|
|
11487
12441
|
const __safe_callTool = async (name, args) => {
|
|
@@ -11498,7 +12452,7 @@ var InterpreterAdapter = class {
|
|
|
11498
12452
|
try {
|
|
11499
12453
|
program = acorn3.parse(code, { ecmaVersion: "latest", sourceType: "script" });
|
|
11500
12454
|
} catch (error) {
|
|
11501
|
-
return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
|
|
12455
|
+
return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
|
|
11502
12456
|
}
|
|
11503
12457
|
const timeout = context.config.timeout;
|
|
11504
12458
|
const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
|
|
@@ -11523,6 +12477,7 @@ var InterpreterAdapter = class {
|
|
|
11523
12477
|
startTime,
|
|
11524
12478
|
toolCallCount,
|
|
11525
12479
|
interpreter.stepCount,
|
|
12480
|
+
sanitizeStacks,
|
|
11526
12481
|
"TimeoutError",
|
|
11527
12482
|
"EXECUTION_TIMEOUT"
|
|
11528
12483
|
);
|
|
@@ -11534,7 +12489,7 @@ var InterpreterAdapter = class {
|
|
|
11534
12489
|
};
|
|
11535
12490
|
} catch (error) {
|
|
11536
12491
|
const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
|
|
11537
|
-
return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
|
|
12492
|
+
return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
|
|
11538
12493
|
} finally {
|
|
11539
12494
|
if (timer) clearTimeout(timer);
|
|
11540
12495
|
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
@@ -11546,12 +12501,13 @@ var InterpreterAdapter = class {
|
|
|
11546
12501
|
const endTime = Date.now();
|
|
11547
12502
|
return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
|
|
11548
12503
|
}
|
|
11549
|
-
fail(error, startTime, toolCallCount, iterationCount, name, code) {
|
|
12504
|
+
fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
|
|
11550
12505
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
12506
|
+
const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
|
|
11551
12507
|
const execError = {
|
|
11552
12508
|
message: err.message,
|
|
11553
12509
|
name: name ?? err.name,
|
|
11554
|
-
...
|
|
12510
|
+
...stack ? { stack } : {},
|
|
11555
12511
|
...code ? { code } : {}
|
|
11556
12512
|
};
|
|
11557
12513
|
return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
|