@enclave-vm/core 2.15.2 → 2.15.3
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 +12 -0
- package/double-vm/parent-vm-bootstrap.d.ts +8 -0
- package/enclave.d.ts +13 -0
- package/esm/index.mjs +1129 -327
- 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 +1148 -347
- package/package.json +3 -3
- package/safe-error.d.ts +5 -1
- package/safe-runtime.d.ts +13 -2
- package/secure-proxy.d.ts +12 -0
- package/src/adapters/worker-pool/package.json +3 -3
- package/src/adapters/worker-pool/worker-script.js +96 -3
- package/stack-trace.d.ts +38 -0
- package/tool-namespaces.d.ts +38 -0
- package/types.d.ts +117 -2
- package/worker.js +158 -4
package/index.js
CHANGED
|
@@ -31,9 +31,17 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
31
31
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
32
|
|
|
33
33
|
// libs/core/src/safe-error.ts
|
|
34
|
-
function createSafeError(message, name = "Error") {
|
|
34
|
+
function createSafeError(message, name = "Error", code) {
|
|
35
35
|
const error = new Error(message);
|
|
36
36
|
error.name = name;
|
|
37
|
+
if (typeof code === "string") {
|
|
38
|
+
Object.defineProperty(error, "code", {
|
|
39
|
+
value: code,
|
|
40
|
+
writable: false,
|
|
41
|
+
enumerable: false,
|
|
42
|
+
configurable: false
|
|
43
|
+
});
|
|
44
|
+
}
|
|
37
45
|
const SafeConstructor = /* @__PURE__ */ Object.create(null);
|
|
38
46
|
Object.defineProperties(SafeConstructor, {
|
|
39
47
|
constructor: {
|
|
@@ -176,6 +184,14 @@ function createSafeReflect(securityLevel) {
|
|
|
176
184
|
}
|
|
177
185
|
});
|
|
178
186
|
}
|
|
187
|
+
function gatedProxyCache(gate) {
|
|
188
|
+
let cache = gatedProxyCaches.get(gate);
|
|
189
|
+
if (!cache) {
|
|
190
|
+
cache = /* @__PURE__ */ new WeakMap();
|
|
191
|
+
gatedProxyCaches.set(gate, cache);
|
|
192
|
+
}
|
|
193
|
+
return cache;
|
|
194
|
+
}
|
|
179
195
|
function getFullCacheKey(options) {
|
|
180
196
|
const parts = [];
|
|
181
197
|
if (options.levelConfig) {
|
|
@@ -201,7 +217,7 @@ function getFullCacheKey(options) {
|
|
|
201
217
|
function isProxyable(value) {
|
|
202
218
|
if (value === null) return false;
|
|
203
219
|
if (typeof value !== "object" && typeof value !== "function") return false;
|
|
204
|
-
const tag =
|
|
220
|
+
const tag = ReflectApply2(ObjectToString, value, []);
|
|
205
221
|
if (NON_PROXYABLE_TYPES.has(tag)) {
|
|
206
222
|
return false;
|
|
207
223
|
}
|
|
@@ -212,12 +228,11 @@ function createSecureProxy(target, options = {}) {
|
|
|
212
228
|
return target;
|
|
213
229
|
}
|
|
214
230
|
const cacheKey = getFullCacheKey(options);
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
}
|
|
231
|
+
const gateCache = options.callGate ? gatedProxyCache(options.callGate) : void 0;
|
|
232
|
+
const lookupCached = (obj) => gateCache ? gateCache.get(obj) : proxyCache.get(obj)?.get(cacheKey);
|
|
233
|
+
const cached = lookupCached(target);
|
|
234
|
+
if (cached) {
|
|
235
|
+
return cached;
|
|
221
236
|
}
|
|
222
237
|
const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
|
|
223
238
|
const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
|
|
@@ -228,12 +243,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
228
243
|
if (!isProxyable(obj)) {
|
|
229
244
|
return obj;
|
|
230
245
|
}
|
|
231
|
-
const
|
|
232
|
-
if (
|
|
233
|
-
|
|
234
|
-
if (cachedProxy) {
|
|
235
|
-
return cachedProxy;
|
|
236
|
-
}
|
|
246
|
+
const cachedProxy = lookupCached(obj);
|
|
247
|
+
if (cachedProxy) {
|
|
248
|
+
return cachedProxy;
|
|
237
249
|
}
|
|
238
250
|
if (depth > maxDepth) {
|
|
239
251
|
throw createSafeError(
|
|
@@ -281,9 +293,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
281
293
|
}
|
|
282
294
|
const value = ReflectGet(target2, property, receiver);
|
|
283
295
|
if (typeof value === "function") {
|
|
284
|
-
const tag =
|
|
296
|
+
const tag = ReflectApply2(ObjectToString, target2, []);
|
|
285
297
|
if (INTERNAL_SLOT_TYPES.has(tag)) {
|
|
286
|
-
const boundMethod =
|
|
298
|
+
const boundMethod = ReflectApply2(FunctionBind, value, [target2]);
|
|
287
299
|
return proxyWithDepth(boundMethod, depth + 1);
|
|
288
300
|
}
|
|
289
301
|
}
|
|
@@ -329,7 +341,7 @@ function createSecureProxy(target, options = {}) {
|
|
|
329
341
|
// Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
|
|
330
342
|
// Must respect proxy invariants: non-configurable own properties cannot be hidden
|
|
331
343
|
ownKeys(target2) {
|
|
332
|
-
const keys =
|
|
344
|
+
const keys = ReflectOwnKeys2(target2);
|
|
333
345
|
return keys.filter((key) => {
|
|
334
346
|
const keyStr = typeof key === "symbol" ? key.toString() : key;
|
|
335
347
|
if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
|
|
@@ -346,7 +358,7 @@ function createSecureProxy(target, options = {}) {
|
|
|
346
358
|
// Must respect proxy invariants: non-configurable properties must return actual descriptor
|
|
347
359
|
getOwnPropertyDescriptor(target2, property) {
|
|
348
360
|
const propName = typeof property === "symbol" ? property.toString() : property;
|
|
349
|
-
const descriptor =
|
|
361
|
+
const descriptor = ReflectGetOwnPropertyDescriptor2(target2, property);
|
|
350
362
|
if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
|
|
351
363
|
const exactValue = descriptor.value;
|
|
352
364
|
if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
|
|
@@ -405,7 +417,10 @@ function createSecureProxy(target, options = {}) {
|
|
|
405
417
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
|
|
406
418
|
apply(target2, thisArg, argArray) {
|
|
407
419
|
const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
|
|
408
|
-
|
|
420
|
+
if (options.callGate && options.callGate.gates(target2)) {
|
|
421
|
+
return options.callGate.call(target2, unwrappedThis, argArray);
|
|
422
|
+
}
|
|
423
|
+
const result = ReflectApply2(target2, unwrappedThis, argArray);
|
|
409
424
|
if (isProxyable(result)) {
|
|
410
425
|
return proxyWithDepth(result, depth + 1);
|
|
411
426
|
}
|
|
@@ -416,6 +431,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
416
431
|
// host Function constructor — the same escape class the apply trap closes for calls.
|
|
417
432
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
|
|
418
433
|
construct(target2, argArray, newTarget) {
|
|
434
|
+
if (options.callGate && options.callGate.gates(target2)) {
|
|
435
|
+
throw createSafeError("Host functions cannot be called with new", "TypeError");
|
|
436
|
+
}
|
|
419
437
|
const instance = ReflectConstruct(target2, argArray, newTarget === proxy ? target2 : newTarget);
|
|
420
438
|
if (isProxyable(instance)) {
|
|
421
439
|
return proxyWithDepth(instance, depth + 1);
|
|
@@ -423,12 +441,16 @@ function createSecureProxy(target, options = {}) {
|
|
|
423
441
|
return instance;
|
|
424
442
|
}
|
|
425
443
|
});
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
proxyCache.
|
|
444
|
+
if (gateCache) {
|
|
445
|
+
gateCache.set(obj, proxy);
|
|
446
|
+
} else {
|
|
447
|
+
let objCacheMap = proxyCache.get(obj);
|
|
448
|
+
if (!objCacheMap) {
|
|
449
|
+
objCacheMap = /* @__PURE__ */ new Map();
|
|
450
|
+
proxyCache.set(obj, objCacheMap);
|
|
451
|
+
}
|
|
452
|
+
objCacheMap.set(cacheKey, proxy);
|
|
430
453
|
}
|
|
431
|
-
objCacheMap.set(cacheKey, proxy);
|
|
432
454
|
proxySet.add(proxy);
|
|
433
455
|
proxyToTarget.set(proxy, obj);
|
|
434
456
|
return proxy;
|
|
@@ -470,7 +492,7 @@ function isSecureProxy(obj) {
|
|
|
470
492
|
}
|
|
471
493
|
return proxySet.has(obj);
|
|
472
494
|
}
|
|
473
|
-
var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty,
|
|
495
|
+
var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor2, ReflectOwnKeys2, ReflectApply2, ReflectConstruct, ReflectObject, PINNED_REFLECT_VALUES, FunctionCtor, AsyncFunctionCtor, GeneratorFunctionCtor, AsyncGeneratorFunctionCtor, MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, gatedProxyCaches, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
|
|
474
496
|
var init_secure_proxy = __esm({
|
|
475
497
|
"libs/core/src/secure-proxy.ts"() {
|
|
476
498
|
"use strict";
|
|
@@ -481,13 +503,13 @@ var init_secure_proxy = __esm({
|
|
|
481
503
|
ReflectGet = Reflect.get;
|
|
482
504
|
ReflectSet = Reflect.set;
|
|
483
505
|
ReflectDefineProperty = Reflect.defineProperty;
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
506
|
+
ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
|
|
507
|
+
ReflectOwnKeys2 = Reflect.ownKeys;
|
|
508
|
+
ReflectApply2 = Reflect.apply;
|
|
487
509
|
ReflectConstruct = Reflect.construct;
|
|
488
510
|
ReflectObject = Reflect;
|
|
489
511
|
PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
|
|
490
|
-
for (const key of
|
|
512
|
+
for (const key of ReflectOwnKeys2(ReflectObject)) {
|
|
491
513
|
PINNED_REFLECT_VALUES.set(key, ReflectGet(ReflectObject, key));
|
|
492
514
|
}
|
|
493
515
|
FunctionCtor = Function;
|
|
@@ -596,6 +618,7 @@ var init_secure_proxy = __esm({
|
|
|
596
618
|
// 'call',
|
|
597
619
|
// 'apply',
|
|
598
620
|
]);
|
|
621
|
+
gatedProxyCaches = /* @__PURE__ */ new WeakMap();
|
|
599
622
|
proxyCache = /* @__PURE__ */ new WeakMap();
|
|
600
623
|
proxySet = /* @__PURE__ */ new WeakSet();
|
|
601
624
|
proxyToTarget = /* @__PURE__ */ new WeakMap();
|
|
@@ -1073,11 +1096,11 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1073
1096
|
return result;
|
|
1074
1097
|
}
|
|
1075
1098
|
if (value instanceof Date) {
|
|
1076
|
-
const time =
|
|
1099
|
+
const time = ReflectApply3(DateProtoGetTime, value, []);
|
|
1077
1100
|
if (allowDates) {
|
|
1078
1101
|
return new Date(time);
|
|
1079
1102
|
}
|
|
1080
|
-
return
|
|
1103
|
+
return ReflectApply3(DateProtoToISOString, value, []);
|
|
1081
1104
|
}
|
|
1082
1105
|
if (value instanceof Error) {
|
|
1083
1106
|
const rawName = ReflectGet3(value, "name");
|
|
@@ -1094,11 +1117,11 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1094
1117
|
return { error: message };
|
|
1095
1118
|
}
|
|
1096
1119
|
if (value instanceof RegExp) {
|
|
1097
|
-
return
|
|
1120
|
+
return ReflectApply3(RegExpProtoToString, value, []);
|
|
1098
1121
|
}
|
|
1099
1122
|
if (value instanceof Map) {
|
|
1100
1123
|
const sanitizedMap = ObjectCreate(null);
|
|
1101
|
-
const entries =
|
|
1124
|
+
const entries = ReflectApply3(MapProtoEntries, value, []);
|
|
1102
1125
|
for (const [key, val] of entries) {
|
|
1103
1126
|
if (typeof key !== "string") continue;
|
|
1104
1127
|
if (DANGEROUS_KEYS.has(key)) continue;
|
|
@@ -1108,7 +1131,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1108
1131
|
return sanitizedMap;
|
|
1109
1132
|
}
|
|
1110
1133
|
if (value instanceof Set) {
|
|
1111
|
-
const iter =
|
|
1134
|
+
const iter = ReflectApply3(SetProtoValues, value, []);
|
|
1112
1135
|
const result = [];
|
|
1113
1136
|
for (const item of iter) {
|
|
1114
1137
|
context.propCount.count++;
|
|
@@ -1267,12 +1290,12 @@ function checkSerializedSize(value, maxBytes) {
|
|
|
1267
1290
|
return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
|
|
1268
1291
|
}
|
|
1269
1292
|
}
|
|
1270
|
-
var DANGEROUS_KEYS,
|
|
1293
|
+
var DANGEROUS_KEYS, ReflectApply3, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
|
|
1271
1294
|
var init_value_sanitizer = __esm({
|
|
1272
1295
|
"libs/core/src/value-sanitizer.ts"() {
|
|
1273
1296
|
"use strict";
|
|
1274
1297
|
DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
|
|
1275
|
-
|
|
1298
|
+
ReflectApply3 = Reflect.apply;
|
|
1276
1299
|
ReflectGet3 = Reflect.get;
|
|
1277
1300
|
ArrayIsArray = Array.isArray;
|
|
1278
1301
|
ObjectKeys = Object.keys;
|
|
@@ -1287,6 +1310,390 @@ var init_value_sanitizer = __esm({
|
|
|
1287
1310
|
}
|
|
1288
1311
|
});
|
|
1289
1312
|
|
|
1313
|
+
// libs/core/src/global-function-gate.ts
|
|
1314
|
+
function isBuiltinMethod(fn) {
|
|
1315
|
+
return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHODS.has(fn);
|
|
1316
|
+
}
|
|
1317
|
+
function resolveMaxGlobalFunctionCalls(config) {
|
|
1318
|
+
const explicit = config.maxGlobalFunctionCalls;
|
|
1319
|
+
if (typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 0) {
|
|
1320
|
+
return Math.floor(explicit);
|
|
1321
|
+
}
|
|
1322
|
+
const maxToolCalls = typeof config.maxToolCalls === "number" && Number.isFinite(config.maxToolCalls) ? config.maxToolCalls : 100;
|
|
1323
|
+
return Math.max(0, Math.floor(maxToolCalls)) * DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL;
|
|
1324
|
+
}
|
|
1325
|
+
function globalFunctionLimitMessage(max) {
|
|
1326
|
+
return `Maximum global function call limit exceeded (${max}). This limit prevents runaway calls into host functions.`;
|
|
1327
|
+
}
|
|
1328
|
+
function resultLimits(context) {
|
|
1329
|
+
const { config } = context;
|
|
1330
|
+
return {
|
|
1331
|
+
maxDepth: config.maxSanitizeDepth,
|
|
1332
|
+
maxProperties: config.maxSanitizeProperties,
|
|
1333
|
+
maxPayloadBytes: config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES
|
|
1334
|
+
};
|
|
1335
|
+
}
|
|
1336
|
+
function truncate(value, max) {
|
|
1337
|
+
return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
|
|
1338
|
+
}
|
|
1339
|
+
function failure(error) {
|
|
1340
|
+
let name = "Error";
|
|
1341
|
+
let message = "Global function call failed";
|
|
1342
|
+
try {
|
|
1343
|
+
if (error && typeof error === "object") {
|
|
1344
|
+
const rawName = error.name;
|
|
1345
|
+
const rawMessage = error.message;
|
|
1346
|
+
if (typeof rawName === "string" && rawName) name = rawName;
|
|
1347
|
+
if (typeof rawMessage === "string" && rawMessage) message = rawMessage;
|
|
1348
|
+
} else if (typeof error === "string" && error) {
|
|
1349
|
+
message = error;
|
|
1350
|
+
}
|
|
1351
|
+
} catch {
|
|
1352
|
+
}
|
|
1353
|
+
return {
|
|
1354
|
+
ok: false,
|
|
1355
|
+
name: truncate(name, MAX_ERROR_NAME_LENGTH),
|
|
1356
|
+
message: truncate(message, MAX_ERROR_MESSAGE_LENGTH)
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
1359
|
+
function jsonReplacer(_key, value) {
|
|
1360
|
+
if (typeof value === "bigint") return value.toString();
|
|
1361
|
+
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
1362
|
+
return value;
|
|
1363
|
+
}
|
|
1364
|
+
function utf8ByteLength(value) {
|
|
1365
|
+
return Buffer.byteLength(value, "utf8");
|
|
1366
|
+
}
|
|
1367
|
+
function encodeResult(value, limits) {
|
|
1368
|
+
if (value === void 0) return { ok: true };
|
|
1369
|
+
let json;
|
|
1370
|
+
try {
|
|
1371
|
+
const sanitized = sanitizeValue(value, {
|
|
1372
|
+
maxDepth: limits.maxDepth,
|
|
1373
|
+
maxProperties: limits.maxProperties,
|
|
1374
|
+
allowDates: false,
|
|
1375
|
+
allowErrors: true
|
|
1376
|
+
});
|
|
1377
|
+
json = JsonStringify(sanitized, jsonReplacer);
|
|
1378
|
+
} catch {
|
|
1379
|
+
return { ok: false, name: "GlobalFunctionError", message: UNSAFE_RESULT_MESSAGE };
|
|
1380
|
+
}
|
|
1381
|
+
if (json === void 0) return { ok: true };
|
|
1382
|
+
if (utf8ByteLength(json) > limits.maxPayloadBytes) {
|
|
1383
|
+
return {
|
|
1384
|
+
ok: false,
|
|
1385
|
+
name: "GlobalFunctionError",
|
|
1386
|
+
message: `Global function result exceeds maximum size (${limits.maxPayloadBytes} bytes)`
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
return { ok: true, json };
|
|
1390
|
+
}
|
|
1391
|
+
function isThenable(value) {
|
|
1392
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return false;
|
|
1393
|
+
try {
|
|
1394
|
+
return typeof value.then === "function";
|
|
1395
|
+
} catch {
|
|
1396
|
+
return false;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
function invokeGlobalFunction(fn, thisArg, args, limits) {
|
|
1400
|
+
if (typeof fn !== "function") {
|
|
1401
|
+
return { ok: false, name: "TypeError", message: "Global is not a function" };
|
|
1402
|
+
}
|
|
1403
|
+
let result;
|
|
1404
|
+
try {
|
|
1405
|
+
result = ReflectApply4(fn, thisArg, ArrayIsArray2(args) ? args : []);
|
|
1406
|
+
} catch (error) {
|
|
1407
|
+
return failure(error);
|
|
1408
|
+
}
|
|
1409
|
+
if (isThenable(result)) {
|
|
1410
|
+
return Promise.resolve(result).then(
|
|
1411
|
+
(value) => encodeResult(value, limits),
|
|
1412
|
+
(error) => failure(error)
|
|
1413
|
+
);
|
|
1414
|
+
}
|
|
1415
|
+
return encodeResult(result, limits);
|
|
1416
|
+
}
|
|
1417
|
+
function toEnvelope(outcome) {
|
|
1418
|
+
if (outcome.ok) {
|
|
1419
|
+
return outcome.json === void 0 ? '{"v":1,"ok":true}' : `{"v":1,"ok":true,"value":${outcome.json}}`;
|
|
1420
|
+
}
|
|
1421
|
+
return JsonStringify({ v: 1, ok: false, error: { name: outcome.name, message: outcome.message } });
|
|
1422
|
+
}
|
|
1423
|
+
function createHostGlobalFunctionInvoker(context) {
|
|
1424
|
+
const limits = resultLimits(context);
|
|
1425
|
+
return (fn, thisArg, args) => {
|
|
1426
|
+
const outcome = invokeGlobalFunction(fn, thisArg, args, limits);
|
|
1427
|
+
return outcome instanceof Promise ? outcome.then(toEnvelope) : toEnvelope(outcome);
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
function createGlobalFunctionGate(context, realm) {
|
|
1431
|
+
const limits = resultLimits(context);
|
|
1432
|
+
const max = resolveMaxGlobalFunctionCalls(context.config);
|
|
1433
|
+
let calls = 0;
|
|
1434
|
+
const settle = (outcome) => {
|
|
1435
|
+
if (!outcome.ok) {
|
|
1436
|
+
throw createSafeError(outcome.message, outcome.name);
|
|
1437
|
+
}
|
|
1438
|
+
return outcome.json === void 0 ? void 0 : realm.parseJson(outcome.json);
|
|
1439
|
+
};
|
|
1440
|
+
return {
|
|
1441
|
+
gates: (target) => !isBuiltinMethod(target),
|
|
1442
|
+
call: (target, thisArg, args) => {
|
|
1443
|
+
if (context.aborted) {
|
|
1444
|
+
throw createSafeError("Execution aborted");
|
|
1445
|
+
}
|
|
1446
|
+
calls++;
|
|
1447
|
+
if (calls > max) {
|
|
1448
|
+
throw createSafeError(globalFunctionLimitMessage(max));
|
|
1449
|
+
}
|
|
1450
|
+
const outcome = invokeGlobalFunction(target, thisArg, args, limits);
|
|
1451
|
+
if (outcome instanceof Promise) {
|
|
1452
|
+
return realm.adoptPromise(outcome.then(settle));
|
|
1453
|
+
}
|
|
1454
|
+
return settle(outcome);
|
|
1455
|
+
}
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1458
|
+
var ReflectApply4, ReflectOwnKeys3, ObjectGetOwnPropertyDescriptor2, ObjectGetPrototypeOf2, ArrayIsArray2, JsonStringify, BUILTIN_METHODS, DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL, DEFAULT_MAX_PAYLOAD_BYTES, MAX_ERROR_MESSAGE_LENGTH, MAX_ERROR_NAME_LENGTH, UNSAFE_RESULT_MESSAGE;
|
|
1459
|
+
var init_global_function_gate = __esm({
|
|
1460
|
+
"libs/core/src/global-function-gate.ts"() {
|
|
1461
|
+
"use strict";
|
|
1462
|
+
init_value_sanitizer();
|
|
1463
|
+
init_safe_error();
|
|
1464
|
+
ReflectApply4 = Reflect.apply;
|
|
1465
|
+
ReflectOwnKeys3 = Reflect.ownKeys;
|
|
1466
|
+
ObjectGetOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
|
|
1467
|
+
ObjectGetPrototypeOf2 = Object.getPrototypeOf;
|
|
1468
|
+
ArrayIsArray2 = Array.isArray;
|
|
1469
|
+
JsonStringify = JSON.stringify;
|
|
1470
|
+
BUILTIN_METHODS = (() => {
|
|
1471
|
+
const methods = /* @__PURE__ */ new WeakSet();
|
|
1472
|
+
const typedArrays = [
|
|
1473
|
+
Int8Array,
|
|
1474
|
+
Uint8Array,
|
|
1475
|
+
Uint8ClampedArray,
|
|
1476
|
+
Int16Array,
|
|
1477
|
+
Uint16Array,
|
|
1478
|
+
Int32Array,
|
|
1479
|
+
Uint32Array,
|
|
1480
|
+
Float32Array,
|
|
1481
|
+
Float64Array,
|
|
1482
|
+
BigInt64Array,
|
|
1483
|
+
BigUint64Array
|
|
1484
|
+
];
|
|
1485
|
+
const arrayIteratorPrototype = ObjectGetPrototypeOf2([][Symbol.iterator]());
|
|
1486
|
+
const prototypes = [
|
|
1487
|
+
Object.prototype,
|
|
1488
|
+
Array.prototype,
|
|
1489
|
+
String.prototype,
|
|
1490
|
+
Number.prototype,
|
|
1491
|
+
Boolean.prototype,
|
|
1492
|
+
Symbol.prototype,
|
|
1493
|
+
BigInt.prototype,
|
|
1494
|
+
Date.prototype,
|
|
1495
|
+
RegExp.prototype,
|
|
1496
|
+
Error.prototype,
|
|
1497
|
+
EvalError.prototype,
|
|
1498
|
+
RangeError.prototype,
|
|
1499
|
+
ReferenceError.prototype,
|
|
1500
|
+
SyntaxError.prototype,
|
|
1501
|
+
TypeError.prototype,
|
|
1502
|
+
URIError.prototype,
|
|
1503
|
+
Map.prototype,
|
|
1504
|
+
Set.prototype,
|
|
1505
|
+
WeakMap.prototype,
|
|
1506
|
+
WeakSet.prototype,
|
|
1507
|
+
Promise.prototype,
|
|
1508
|
+
ArrayBuffer.prototype,
|
|
1509
|
+
DataView.prototype,
|
|
1510
|
+
ObjectGetPrototypeOf2(Uint8Array.prototype),
|
|
1511
|
+
// %TypedArray%.prototype
|
|
1512
|
+
...typedArrays.map((TypedArray) => TypedArray.prototype),
|
|
1513
|
+
arrayIteratorPrototype,
|
|
1514
|
+
ObjectGetPrototypeOf2(arrayIteratorPrototype),
|
|
1515
|
+
// %IteratorPrototype%
|
|
1516
|
+
ObjectGetPrototypeOf2((/* @__PURE__ */ new Map())[Symbol.iterator]()),
|
|
1517
|
+
ObjectGetPrototypeOf2((/* @__PURE__ */ new Set())[Symbol.iterator]()),
|
|
1518
|
+
ObjectGetPrototypeOf2(""[Symbol.iterator]())
|
|
1519
|
+
];
|
|
1520
|
+
for (const prototype of prototypes) {
|
|
1521
|
+
if (prototype === null || typeof prototype !== "object") continue;
|
|
1522
|
+
for (const key of ReflectOwnKeys3(prototype)) {
|
|
1523
|
+
if (key === "constructor") continue;
|
|
1524
|
+
const descriptor = ObjectGetOwnPropertyDescriptor2(prototype, key);
|
|
1525
|
+
if (descriptor && typeof descriptor.value === "function") {
|
|
1526
|
+
methods.add(descriptor.value);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
return methods;
|
|
1531
|
+
})();
|
|
1532
|
+
DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
|
|
1533
|
+
DEFAULT_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
1534
|
+
MAX_ERROR_MESSAGE_LENGTH = 4096;
|
|
1535
|
+
MAX_ERROR_NAME_LENGTH = 128;
|
|
1536
|
+
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)";
|
|
1537
|
+
}
|
|
1538
|
+
});
|
|
1539
|
+
|
|
1540
|
+
// libs/core/src/stack-trace.ts
|
|
1541
|
+
function redactLine(line) {
|
|
1542
|
+
let out = line.length > MAX_LINE_LENGTH ? `${line.slice(0, MAX_LINE_LENGTH)}\u2026` : line;
|
|
1543
|
+
for (const pattern of SENSITIVE_STACK_PATTERNS) {
|
|
1544
|
+
pattern.lastIndex = 0;
|
|
1545
|
+
out = out.replace(pattern, "[REDACTED]");
|
|
1546
|
+
}
|
|
1547
|
+
return out;
|
|
1548
|
+
}
|
|
1549
|
+
function sanitizeStackTrace(stack, sanitize = true) {
|
|
1550
|
+
if (typeof stack !== "string" || !stack || !sanitize) return stack;
|
|
1551
|
+
const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
|
|
1552
|
+
return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
|
|
1553
|
+
}
|
|
1554
|
+
var SENSITIVE_STACK_PATTERNS, FRAME_LINE, MAX_STACK_LENGTH, MAX_LINE_LENGTH, REDACTED_FRAME;
|
|
1555
|
+
var init_stack_trace = __esm({
|
|
1556
|
+
"libs/core/src/stack-trace.ts"() {
|
|
1557
|
+
"use strict";
|
|
1558
|
+
SENSITIVE_STACK_PATTERNS = [
|
|
1559
|
+
// Unix file system paths
|
|
1560
|
+
/\/Users\/[^/]+\/[^\s):]*/gi,
|
|
1561
|
+
// macOS home directories
|
|
1562
|
+
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
1563
|
+
// Linux home directories
|
|
1564
|
+
/\/var\/[^\s):]*/gi,
|
|
1565
|
+
// System var directories
|
|
1566
|
+
/\/opt\/[^\s):]*/gi,
|
|
1567
|
+
// Optional software
|
|
1568
|
+
/\/tmp\/[^\s):]*/gi,
|
|
1569
|
+
// Temporary files
|
|
1570
|
+
/\/etc\/[^\s):]*/gi,
|
|
1571
|
+
// System configuration
|
|
1572
|
+
/\/root\/[^\s):]*/gi,
|
|
1573
|
+
// Root home directory
|
|
1574
|
+
/\/mnt\/[^\s):]*/gi,
|
|
1575
|
+
// Mount points
|
|
1576
|
+
/\/srv\/[^\s):]*/gi,
|
|
1577
|
+
// Service data
|
|
1578
|
+
/\/data\/[^\s):]*/gi,
|
|
1579
|
+
// Data directories
|
|
1580
|
+
/\/app\/[^\s):]*/gi,
|
|
1581
|
+
// Application directories
|
|
1582
|
+
/\/proc\/[^\s):]*/gi,
|
|
1583
|
+
// Process information
|
|
1584
|
+
/\/sys\/[^\s):]*/gi,
|
|
1585
|
+
// System files
|
|
1586
|
+
// Windows paths
|
|
1587
|
+
/\\\\[^\s):]*/g,
|
|
1588
|
+
// UNC paths
|
|
1589
|
+
/[A-Z]:\\[^\s):]+/gi,
|
|
1590
|
+
// Windows drive paths
|
|
1591
|
+
// URL-based paths
|
|
1592
|
+
/file:\/\/[^\s):]+/gi,
|
|
1593
|
+
// File URLs
|
|
1594
|
+
/webpack:\/\/[^\s):]+/gi,
|
|
1595
|
+
// Webpack paths
|
|
1596
|
+
/%2F[^\s):]+/gi,
|
|
1597
|
+
// URL-encoded paths
|
|
1598
|
+
// Package managers and node
|
|
1599
|
+
/node_modules\/[^\s):]+/gi,
|
|
1600
|
+
// Node modules paths
|
|
1601
|
+
/\/nix\/store\/[^\s):]*/gi,
|
|
1602
|
+
// Nix store paths
|
|
1603
|
+
/\.npm\/[^\s):]*/gi,
|
|
1604
|
+
// NPM cache
|
|
1605
|
+
/\.yarn\/[^\s):]*/gi,
|
|
1606
|
+
// Yarn cache
|
|
1607
|
+
/\.pnpm\/[^\s):]*/gi,
|
|
1608
|
+
// PNPM cache
|
|
1609
|
+
// Container and orchestration
|
|
1610
|
+
/\/run\/secrets\/[^\s):]*/gi,
|
|
1611
|
+
// Docker/K8s secrets
|
|
1612
|
+
/\/var\/run\/[^\s):]*/gi,
|
|
1613
|
+
// Runtime directories
|
|
1614
|
+
/\/docker\/[^\s):]*/gi,
|
|
1615
|
+
// Docker paths
|
|
1616
|
+
/\/containers\/[^\s):]*/gi,
|
|
1617
|
+
// Container paths
|
|
1618
|
+
/\/kubelet\/[^\s):]*/gi,
|
|
1619
|
+
// Kubernetes kubelet
|
|
1620
|
+
// CI/CD systems
|
|
1621
|
+
/\/github\/workspace\/[^\s):]*/gi,
|
|
1622
|
+
// GitHub Actions
|
|
1623
|
+
/\/runner\/[^\s):]*/gi,
|
|
1624
|
+
// GitHub/GitLab runner
|
|
1625
|
+
/\/builds\/[^\s):]*/gi,
|
|
1626
|
+
// CI builds
|
|
1627
|
+
/\/workspace\/[^\s):]*/gi,
|
|
1628
|
+
// Generic workspace
|
|
1629
|
+
/\/pipeline\/[^\s):]*/gi,
|
|
1630
|
+
// CI pipelines
|
|
1631
|
+
/\/jenkins\/[^\s):]*/gi,
|
|
1632
|
+
// Jenkins
|
|
1633
|
+
/\/bamboo\/[^\s):]*/gi,
|
|
1634
|
+
// Bamboo
|
|
1635
|
+
/\/teamcity\/[^\s):]*/gi,
|
|
1636
|
+
// TeamCity
|
|
1637
|
+
/\/circleci\/[^\s):]*/gi,
|
|
1638
|
+
// CircleCI
|
|
1639
|
+
// Cloud providers
|
|
1640
|
+
/\/aws\/[^\s):]*/gi,
|
|
1641
|
+
// AWS paths
|
|
1642
|
+
/\/gcloud\/[^\s):]*/gi,
|
|
1643
|
+
// Google Cloud
|
|
1644
|
+
/\/azure\/[^\s):]*/gi,
|
|
1645
|
+
// Azure paths
|
|
1646
|
+
/s3:\/\/[^\s):]+/gi,
|
|
1647
|
+
// S3 URIs
|
|
1648
|
+
/gs:\/\/[^\s):]+/gi,
|
|
1649
|
+
// GCS URIs
|
|
1650
|
+
// Secrets and credentials (patterns that might appear in paths or errors)
|
|
1651
|
+
/[A-Z0-9]{20,}/g,
|
|
1652
|
+
// AWS-style access keys (20+ uppercase chars)
|
|
1653
|
+
/sk-[a-zA-Z0-9]{32,}/g,
|
|
1654
|
+
// OpenAI/Stripe-style secret keys
|
|
1655
|
+
/ghp_[a-zA-Z0-9]{36,}/g,
|
|
1656
|
+
// GitHub personal access tokens
|
|
1657
|
+
/gho_[a-zA-Z0-9]{36,}/g,
|
|
1658
|
+
// GitHub OAuth tokens
|
|
1659
|
+
/github_pat_[a-zA-Z0-9_]{22,}/g,
|
|
1660
|
+
// GitHub fine-grained tokens
|
|
1661
|
+
/xox[baprs]-[a-zA-Z0-9-]+/g,
|
|
1662
|
+
// Slack tokens
|
|
1663
|
+
/Bearer\s+[a-zA-Z0-9._-]+/gi,
|
|
1664
|
+
// Bearer tokens
|
|
1665
|
+
/Basic\s+[a-zA-Z0-9+/=]+/gi,
|
|
1666
|
+
// Basic auth
|
|
1667
|
+
// Internal network info
|
|
1668
|
+
/(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
|
|
1669
|
+
// Private IPs
|
|
1670
|
+
/[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
|
|
1671
|
+
// Internal hostnames
|
|
1672
|
+
/localhost:\d+/gi,
|
|
1673
|
+
// Localhost with port
|
|
1674
|
+
/127\.0\.0\.1:\d+/gi,
|
|
1675
|
+
// Loopback with port
|
|
1676
|
+
// User information
|
|
1677
|
+
/\/u\/[^/]+\//gi,
|
|
1678
|
+
// User subdirectories
|
|
1679
|
+
/~[a-z_][a-z0-9_-]*/gi,
|
|
1680
|
+
// Unix user home shorthand
|
|
1681
|
+
// Anything else that is still shaped like a location: an absolute path of two or more
|
|
1682
|
+
// segments, a URL, or a script location such as `agentscript.js:3` / `index.mjs:10:5`.
|
|
1683
|
+
/[a-z][a-z0-9+.-]*:\/\/[^\s)]+/gi,
|
|
1684
|
+
// Other URLs (http://host/bundle.js:1:2)
|
|
1685
|
+
/(?:\/[\w.@%+-]+){2,}\/?/g,
|
|
1686
|
+
// Remaining absolute paths
|
|
1687
|
+
/[\w.@-]+\.(?:[cm]?[jt]sx?|json|node|wasm)(?::\d+){1,2}/gi
|
|
1688
|
+
// file.ext:line[:column]
|
|
1689
|
+
];
|
|
1690
|
+
FRAME_LINE = /^\s*at\s/;
|
|
1691
|
+
MAX_STACK_LENGTH = 16 * 1024;
|
|
1692
|
+
MAX_LINE_LENGTH = 1e3;
|
|
1693
|
+
REDACTED_FRAME = " at [REDACTED]";
|
|
1694
|
+
}
|
|
1695
|
+
});
|
|
1696
|
+
|
|
1290
1697
|
// libs/core/src/memory-tracker.ts
|
|
1291
1698
|
function estimateStringSize2(str) {
|
|
1292
1699
|
return str.length * 2 + 40;
|
|
@@ -1442,16 +1849,16 @@ var init_memory_tracker = __esm({
|
|
|
1442
1849
|
});
|
|
1443
1850
|
|
|
1444
1851
|
// libs/core/src/tool-bridge.ts
|
|
1445
|
-
function
|
|
1852
|
+
function utf8ByteLength2(value) {
|
|
1446
1853
|
return Buffer.byteLength(value, "utf8");
|
|
1447
1854
|
}
|
|
1448
|
-
function
|
|
1855
|
+
function jsonReplacer2(_key, value) {
|
|
1449
1856
|
if (typeof value === "bigint") return value.toString();
|
|
1450
1857
|
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
1451
1858
|
return value;
|
|
1452
1859
|
}
|
|
1453
1860
|
function safeJsonStringify(value) {
|
|
1454
|
-
return JSON.stringify(value,
|
|
1861
|
+
return JSON.stringify(value, jsonReplacer2);
|
|
1455
1862
|
}
|
|
1456
1863
|
function truncateForErrorMessage(value, maxChars) {
|
|
1457
1864
|
if (value.length <= maxChars) return value;
|
|
@@ -1492,7 +1899,7 @@ function serializeResponse(response, maxPayloadBytes) {
|
|
|
1492
1899
|
}
|
|
1493
1900
|
});
|
|
1494
1901
|
}
|
|
1495
|
-
if (
|
|
1902
|
+
if (utf8ByteLength2(json) <= maxPayloadBytes) return json;
|
|
1496
1903
|
const minimal = {
|
|
1497
1904
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1498
1905
|
ok: false,
|
|
@@ -1548,7 +1955,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1548
1955
|
maxPayloadBytes
|
|
1549
1956
|
);
|
|
1550
1957
|
}
|
|
1551
|
-
if (
|
|
1958
|
+
if (utf8ByteLength2(requestJson) > maxPayloadBytes) {
|
|
1552
1959
|
return serializeResponse(
|
|
1553
1960
|
{
|
|
1554
1961
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -1689,7 +2096,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1689
2096
|
{
|
|
1690
2097
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1691
2098
|
ok: false,
|
|
1692
|
-
error: safeError
|
|
2099
|
+
error: { ...safeError, toolError: true }
|
|
1693
2100
|
},
|
|
1694
2101
|
maxPayloadBytes
|
|
1695
2102
|
);
|
|
@@ -1713,13 +2120,13 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1713
2120
|
{
|
|
1714
2121
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1715
2122
|
ok: false,
|
|
1716
|
-
error: safeError
|
|
2123
|
+
error: { ...safeError, toolError: true }
|
|
1717
2124
|
},
|
|
1718
2125
|
maxPayloadBytes
|
|
1719
2126
|
);
|
|
1720
2127
|
}
|
|
1721
2128
|
if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
|
|
1722
|
-
const size =
|
|
2129
|
+
const size = utf8ByteLength2(sanitizedResult);
|
|
1723
2130
|
if (size >= referenceConfig.extractionThreshold) {
|
|
1724
2131
|
try {
|
|
1725
2132
|
const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
|
|
@@ -1743,12 +2150,12 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1743
2150
|
{
|
|
1744
2151
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1745
2152
|
ok: false,
|
|
1746
|
-
error: safeError
|
|
2153
|
+
error: { ...safeError, toolError: true }
|
|
1747
2154
|
},
|
|
1748
2155
|
maxPayloadBytes
|
|
1749
2156
|
);
|
|
1750
2157
|
}
|
|
1751
|
-
if (
|
|
2158
|
+
if (utf8ByteLength2(okJson) > maxPayloadBytes) {
|
|
1752
2159
|
return serializeResponse(
|
|
1753
2160
|
{
|
|
1754
2161
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -1756,7 +2163,8 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1756
2163
|
error: {
|
|
1757
2164
|
name: "ToolBridgeError",
|
|
1758
2165
|
message: `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
1759
|
-
code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
|
|
2166
|
+
code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
|
|
2167
|
+
toolError: true
|
|
1760
2168
|
}
|
|
1761
2169
|
},
|
|
1762
2170
|
maxPayloadBytes
|
|
@@ -1786,6 +2194,64 @@ var init_tool_bridge = __esm({
|
|
|
1786
2194
|
}
|
|
1787
2195
|
});
|
|
1788
2196
|
|
|
2197
|
+
// libs/core/src/tool-namespaces.ts
|
|
2198
|
+
function buildToolNamespaceBindings(install, callTool, namespaces) {
|
|
2199
|
+
if (namespaces.length === 0) return [];
|
|
2200
|
+
if (typeof install !== "function") {
|
|
2201
|
+
throw new Error("Tool namespace factory is not available in the sandbox");
|
|
2202
|
+
}
|
|
2203
|
+
const built = install(
|
|
2204
|
+
callTool,
|
|
2205
|
+
JSON.stringify(namespaces)
|
|
2206
|
+
);
|
|
2207
|
+
return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
|
|
2208
|
+
}
|
|
2209
|
+
var TOOL_NAMESPACE_FACTORY_SOURCE;
|
|
2210
|
+
var init_tool_namespaces = __esm({
|
|
2211
|
+
"libs/core/src/tool-namespaces.ts"() {
|
|
2212
|
+
"use strict";
|
|
2213
|
+
TOOL_NAMESPACE_FACTORY_SOURCE = `
|
|
2214
|
+
(function () {
|
|
2215
|
+
'use strict';
|
|
2216
|
+
var parse = JSON.parse;
|
|
2217
|
+
var freeze = Object.freeze;
|
|
2218
|
+
var isArray = Array.isArray;
|
|
2219
|
+
|
|
2220
|
+
function isSafeKey(key) {
|
|
2221
|
+
return typeof key === 'string' && key.length > 0 &&
|
|
2222
|
+
!(key.charAt(0) === '_' && key.charAt(1) === '_') &&
|
|
2223
|
+
key !== 'constructor' && key !== 'prototype';
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
function bind(callTool, toolName) {
|
|
2227
|
+
return (args, options) => callTool(toolName, args === undefined ? {} : args, options);
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
return function install(callTool, namespacesJson) {
|
|
2231
|
+
var spec = parse(namespacesJson);
|
|
2232
|
+
var namespaces = { __proto__: null };
|
|
2233
|
+
if (isArray(spec)) {
|
|
2234
|
+
for (var i = 0; i < spec.length; i++) {
|
|
2235
|
+
var ns = spec[i];
|
|
2236
|
+
if (!ns || !isSafeKey(ns.name) || !isArray(ns.methods)) continue;
|
|
2237
|
+
var target = { __proto__: null };
|
|
2238
|
+
for (var j = 0; j < ns.methods.length; j++) {
|
|
2239
|
+
var method = ns.methods[j];
|
|
2240
|
+
if (!method || !isSafeKey(method.name) || typeof method.toolName !== 'string') continue;
|
|
2241
|
+
target[method.name] = bind(callTool, method.toolName);
|
|
2242
|
+
}
|
|
2243
|
+
freeze(target);
|
|
2244
|
+
namespaces[ns.name] = target;
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
freeze(namespaces);
|
|
2248
|
+
return namespaces;
|
|
2249
|
+
};
|
|
2250
|
+
})()
|
|
2251
|
+
`.trim();
|
|
2252
|
+
}
|
|
2253
|
+
});
|
|
2254
|
+
|
|
1789
2255
|
// libs/core/src/double-vm/parent-vm-bootstrap.ts
|
|
1790
2256
|
function generateSanitizeContextCode(securityLevel) {
|
|
1791
2257
|
const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];
|
|
@@ -1827,7 +2293,9 @@ function generateParentVmBootstrap(options) {
|
|
|
1827
2293
|
blockedProperties,
|
|
1828
2294
|
allowComposites = false,
|
|
1829
2295
|
memoryLimit = 0,
|
|
1830
|
-
throwOnBlocked = true
|
|
2296
|
+
throwOnBlocked = true,
|
|
2297
|
+
maxGlobalFunctionCalls = 1e3,
|
|
2298
|
+
toolNamespaces = []
|
|
1831
2299
|
} = options;
|
|
1832
2300
|
const sanitizeContextCode = generateSanitizeContextCode(securityLevel);
|
|
1833
2301
|
const patternDetectorsCode = generatePatternDetectorsCode(suspiciousPatterns);
|
|
@@ -2263,6 +2731,8 @@ ${stackTraceHardeningCode}
|
|
|
2263
2731
|
const hostReportViolation = __host_reportViolation__;
|
|
2264
2732
|
const hostConfig = __host_config__;
|
|
2265
2733
|
const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
|
|
2734
|
+
const hostInvokeGlobal = typeof __host_invokeGlobal__ === 'function' ? __host_invokeGlobal__ : null;
|
|
2735
|
+
const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
|
|
2266
2736
|
const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
|
|
2267
2737
|
const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
|
|
2268
2738
|
|
|
@@ -2275,6 +2745,8 @@ ${stackTraceHardeningCode}
|
|
|
2275
2745
|
try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }
|
|
2276
2746
|
try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }
|
|
2277
2747
|
try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
|
|
2748
|
+
try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
|
|
2749
|
+
try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
|
|
2278
2750
|
|
|
2279
2751
|
// Policy violation reporter (best-effort; host decides how to handle based on security level)
|
|
2280
2752
|
function __ag_reportViolation(kind) {
|
|
@@ -2444,6 +2916,22 @@ ${stackTraceHardeningCode}
|
|
|
2444
2916
|
// Tool call stats for rate limiting
|
|
2445
2917
|
let toolCallCount = 0;
|
|
2446
2918
|
|
|
2919
|
+
// Calls into host functions passed in globals: counted against their own cap, and their
|
|
2920
|
+
// timestamps share the operation rate limit with tool calls. They are not recorded in
|
|
2921
|
+
// operationHistory, so the tool-call suspicious-sequence detectors only see tool calls.
|
|
2922
|
+
let globalFunctionCallCount = 0;
|
|
2923
|
+
const globalFunctionCallTimes = [];
|
|
2924
|
+
|
|
2925
|
+
// Fail-closed: every call into a host function goes through the gate, except the built-in
|
|
2926
|
+
// prototype methods of host data (Array.prototype.map, iterators, Date methods, ...), which
|
|
2927
|
+
// the get trap binds and records here so data globals keep working as before.
|
|
2928
|
+
const ungatedHostFunctions = new WeakSet();
|
|
2929
|
+
|
|
2930
|
+
// Errors that report a failure of the tool itself (the handler threw, or its result could not
|
|
2931
|
+
// be delivered), as opposed to a refusal by the enclave. callTool(..., { throwOnError: false })
|
|
2932
|
+
// turns only these into { success: false, error } results. Keyed by the safe error thrown.
|
|
2933
|
+
const toolFailures = new WeakMap();
|
|
2934
|
+
|
|
2447
2935
|
// Blocked properties for secure proxy (from security level)
|
|
2448
2936
|
const blockedPropertiesSet = new Set(${JSON.stringify(blockedProperties)});
|
|
2449
2937
|
|
|
@@ -2549,6 +3037,9 @@ ${stackTraceHardeningCode}
|
|
|
2549
3037
|
// Then recursively proxy the bound function to block constructor access
|
|
2550
3038
|
if (typeof value === 'function') {
|
|
2551
3039
|
var boundMethod = __ag_functionBind.call(value, target);
|
|
3040
|
+
if (host && hostIsBuiltinMethod(value)) {
|
|
3041
|
+
ungatedHostFunctions.add(boundMethod);
|
|
3042
|
+
}
|
|
2552
3043
|
return createSecureProxy(boundMethod, depth + 1, host);
|
|
2553
3044
|
}
|
|
2554
3045
|
|
|
@@ -2685,18 +3176,29 @@ ${stackTraceHardeningCode}
|
|
|
2685
3176
|
// (Promise.prototype up to Function) to reach the host Function constructor for RCE.
|
|
2686
3177
|
// Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
|
|
2687
3178
|
// then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
|
|
3179
|
+
//
|
|
3180
|
+
// SECURITY: a call into a HOST function (a custom global, a method read off one, or
|
|
3181
|
+
// call/apply/bind on one) goes through the global-function gate instead: abort check,
|
|
3182
|
+
// maxGlobalFunctionCalls, the shared operation rate limit, and a sanitized, parent-realm
|
|
3183
|
+
// copy of the result. Without it those calls skipped every limit that guards callTool, and
|
|
3184
|
+
// their results arrived unsanitized. Only built-in methods of host data are exempt.
|
|
2688
3185
|
apply: function(target, thisArg, args) {
|
|
3186
|
+
if (host && !ungatedHostFunctions.has(target)) {
|
|
3187
|
+
return callHostFunction(target, thisArg, args);
|
|
3188
|
+
}
|
|
2689
3189
|
return createSecureProxy(__ag_ReflectApply(target, thisArg, args), 0, host);
|
|
2690
|
-
}
|
|
2691
|
-
//
|
|
2692
|
-
//
|
|
3190
|
+
},
|
|
3191
|
+
// Constructing a HOST function would hand back a raw host instance without passing the
|
|
3192
|
+
// gate, so it is refused. Realm-owned values keep NO construct trap (undefined here means
|
|
3193
|
+
// the default behavior): every constructor reachable from sandbox code resolves to an
|
|
2693
3194
|
// inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
|
|
2694
3195
|
// from strings disabled, so a 'new X()' result cannot reach a usable Function
|
|
2695
|
-
// constructor.
|
|
2696
|
-
//
|
|
2697
|
-
//
|
|
2698
|
-
|
|
2699
|
-
|
|
3196
|
+
// constructor. Wrapping construct results would additionally break the proxy invariant
|
|
3197
|
+
// for the frozen (non-extensible) Error objects the harness throws (getPrototypeOf must
|
|
3198
|
+
// not report null for a non-extensible target), masking legitimate errors.
|
|
3199
|
+
construct: host ? function() {
|
|
3200
|
+
throw createSafeError('Host functions cannot be called with new', 'TypeError');
|
|
3201
|
+
} : undefined
|
|
2700
3202
|
});
|
|
2701
3203
|
|
|
2702
3204
|
cache.set(obj, proxy);
|
|
@@ -2708,19 +3210,91 @@ ${stackTraceHardeningCode}
|
|
|
2708
3210
|
}
|
|
2709
3211
|
|
|
2710
3212
|
/**
|
|
2711
|
-
*
|
|
3213
|
+
* Operation rate limit, shared by tool calls and calls into host functions.
|
|
3214
|
+
* Sliding one-second window; entries older than two seconds are dropped.
|
|
2712
3215
|
*/
|
|
2713
|
-
function
|
|
2714
|
-
// Rate limiting check with sliding window cleanup
|
|
2715
|
-
const now = Date.now();
|
|
2716
|
-
// Clean up old entries to prevent unbounded growth (keep only last 2 seconds)
|
|
3216
|
+
function enforceRateLimit(now) {
|
|
2717
3217
|
while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
|
|
2718
3218
|
operationHistory.shift();
|
|
2719
3219
|
}
|
|
2720
|
-
|
|
2721
|
-
|
|
3220
|
+
while (globalFunctionCallTimes.length > 0 && now - globalFunctionCallTimes[0] > 2000) {
|
|
3221
|
+
globalFunctionCallTimes.shift();
|
|
3222
|
+
}
|
|
3223
|
+
var recent = 0;
|
|
3224
|
+
for (var r = 0; r < operationHistory.length; r++) {
|
|
3225
|
+
if (now - operationHistory[r].timestamp < 1000) recent++;
|
|
3226
|
+
}
|
|
3227
|
+
for (var g = 0; g < globalFunctionCallTimes.length; g++) {
|
|
3228
|
+
if (now - globalFunctionCallTimes[g] < 1000) recent++;
|
|
3229
|
+
}
|
|
3230
|
+
if (recent >= validationConfig.maxOperationsPerSecond) {
|
|
2722
3231
|
throw createSafeError('Operation rate limit exceeded (' + validationConfig.maxOperationsPerSecond + ' operations/second)');
|
|
2723
3232
|
}
|
|
3233
|
+
}
|
|
3234
|
+
|
|
3235
|
+
/**
|
|
3236
|
+
* Parse the host invoker's JSON envelope into a parent-realm value, or throw its error.
|
|
3237
|
+
*/
|
|
3238
|
+
function decodeGlobalFunctionResult(envelopeJson) {
|
|
3239
|
+
if (typeof envelopeJson !== 'string') {
|
|
3240
|
+
throw createSafeError('Global function bridge returned an invalid response');
|
|
3241
|
+
}
|
|
3242
|
+
var envelope;
|
|
3243
|
+
try {
|
|
3244
|
+
envelope = JSON.parse(envelopeJson);
|
|
3245
|
+
} catch (e) {
|
|
3246
|
+
throw createSafeError('Global function bridge returned invalid JSON');
|
|
3247
|
+
}
|
|
3248
|
+
if (!envelope || typeof envelope !== 'object' || envelope.v !== 1) {
|
|
3249
|
+
throw createSafeError('Global function bridge returned an invalid response');
|
|
3250
|
+
}
|
|
3251
|
+
if (envelope.ok === true) {
|
|
3252
|
+
return __ag_hasOwnProperty.call(envelope, 'value') ? envelope.value : undefined;
|
|
3253
|
+
}
|
|
3254
|
+
var failure = envelope.error;
|
|
3255
|
+
var message = (failure && typeof failure.message === 'string') ? failure.message : 'Global function call failed';
|
|
3256
|
+
var name = (failure && typeof failure.name === 'string') ? failure.name : 'Error';
|
|
3257
|
+
throw createSafeError(message, name);
|
|
3258
|
+
}
|
|
3259
|
+
|
|
3260
|
+
/**
|
|
3261
|
+
* The global-function gate: every call from the sandbox into a host function passed in
|
|
3262
|
+
* globals (including functions nested in objects) comes through here.
|
|
3263
|
+
*/
|
|
3264
|
+
function callHostFunction(target, thisArg, args) {
|
|
3265
|
+
if (hostAbortCheck()) {
|
|
3266
|
+
throw createSafeError('Execution aborted');
|
|
3267
|
+
}
|
|
3268
|
+
if (typeof hostInvokeGlobal !== 'function') {
|
|
3269
|
+
throw createSafeError('Global function bridge is not available');
|
|
3270
|
+
}
|
|
3271
|
+
|
|
3272
|
+
globalFunctionCallCount++;
|
|
3273
|
+
if (globalFunctionCallCount > ${maxGlobalFunctionCalls}) {
|
|
3274
|
+
throw createSafeError(${JSON.stringify(globalFunctionLimitMessage(maxGlobalFunctionCalls))});
|
|
3275
|
+
}
|
|
3276
|
+
|
|
3277
|
+
var now = Date.now();
|
|
3278
|
+
enforceRateLimit(now);
|
|
3279
|
+
globalFunctionCallTimes.push(now);
|
|
3280
|
+
|
|
3281
|
+
var outcome = hostInvokeGlobal(target, thisArg, args);
|
|
3282
|
+
if (typeof outcome === 'string') {
|
|
3283
|
+
return createSecureProxy(decodeGlobalFunctionResult(outcome));
|
|
3284
|
+
}
|
|
3285
|
+
|
|
3286
|
+
// A host function that returned a thenable: settle to a sanitized parent-realm value.
|
|
3287
|
+
return createSecureProxy(outcome.then(decodeGlobalFunctionResult).then(function(value) {
|
|
3288
|
+
return createSecureProxy(value);
|
|
3289
|
+
}));
|
|
3290
|
+
}
|
|
3291
|
+
|
|
3292
|
+
/**
|
|
3293
|
+
* Validate an operation before forwarding to host
|
|
3294
|
+
*/
|
|
3295
|
+
function validateOperation(operationName, args) {
|
|
3296
|
+
// Rate limiting check with sliding window cleanup
|
|
3297
|
+
enforceRateLimit(Date.now());
|
|
2724
3298
|
|
|
2725
3299
|
// Operation name format validation
|
|
2726
3300
|
if (typeof operationName !== 'string' || !operationName) {
|
|
@@ -2762,11 +3336,64 @@ ${stackTraceHardeningCode}
|
|
|
2762
3336
|
}
|
|
2763
3337
|
}
|
|
2764
3338
|
|
|
3339
|
+
/**
|
|
3340
|
+
* Read a script's callTool options. Only { throwOnError: false } changes behavior.
|
|
3341
|
+
*/
|
|
3342
|
+
function readThrowOnError(options) {
|
|
3343
|
+
if (options === undefined || options === null) return true;
|
|
3344
|
+
if (typeof options !== 'object') {
|
|
3345
|
+
throw createSafeError('callTool options must be an object', 'TypeError');
|
|
3346
|
+
}
|
|
3347
|
+
return options.throwOnError !== false;
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
/**
|
|
3351
|
+
* Remember that a safe error reports a failure of the tool itself (see toolFailures).
|
|
3352
|
+
*/
|
|
3353
|
+
function markToolFailure(error, toolName, name, message, code) {
|
|
3354
|
+
var info = { name: name, message: message, toolName: toolName };
|
|
3355
|
+
if (typeof code === 'string') info.code = code;
|
|
3356
|
+
toolFailures.set(error, info);
|
|
3357
|
+
return error;
|
|
3358
|
+
}
|
|
3359
|
+
|
|
3360
|
+
/**
|
|
3361
|
+
* Whether a tool bridge payload is larger than the limit in UTF-8 bytes, as the host counts it.
|
|
3362
|
+
* A code unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
|
|
3363
|
+
*/
|
|
3364
|
+
function exceedsPayloadLimit(str, maxBytes) {
|
|
3365
|
+
if (str.length > maxBytes) return true;
|
|
3366
|
+
if (str.length * 3 <= maxBytes) return false;
|
|
3367
|
+
var bytes = 0;
|
|
3368
|
+
for (var i = 0; i < str.length; i++) {
|
|
3369
|
+
var c = str.charCodeAt(i);
|
|
3370
|
+
if (c < 0x80) bytes += 1;
|
|
3371
|
+
else if (c < 0x800) bytes += 2;
|
|
3372
|
+
else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
|
|
3373
|
+
var d = str.charCodeAt(i + 1);
|
|
3374
|
+
if (d >= 0xdc00 && d <= 0xdfff) {
|
|
3375
|
+
bytes += 4;
|
|
3376
|
+
i++;
|
|
3377
|
+
} else {
|
|
3378
|
+
bytes += 3;
|
|
3379
|
+
}
|
|
3380
|
+
} else bytes += 3;
|
|
3381
|
+
if (bytes > maxBytes) return true;
|
|
3382
|
+
}
|
|
3383
|
+
return false;
|
|
3384
|
+
}
|
|
3385
|
+
|
|
2765
3386
|
/**
|
|
2766
3387
|
* Inner VM's callTool function
|
|
2767
3388
|
* Proxies through parent VM with validation
|
|
3389
|
+
*
|
|
3390
|
+
* options.throwOnError === false: a failing tool resolves to { success: false, error } and a
|
|
3391
|
+
* working one to { success: true, data }. Refusals by the enclave (abort, tool-call cap, rate
|
|
3392
|
+
* limit, operation-name and suspicious-sequence checks, invalid arguments) still throw.
|
|
2768
3393
|
*/
|
|
2769
|
-
function innerCallTool(toolName, args) {
|
|
3394
|
+
function innerCallTool(toolName, args, options) {
|
|
3395
|
+
var throwOnError = readThrowOnError(options);
|
|
3396
|
+
|
|
2770
3397
|
// Check if aborted
|
|
2771
3398
|
if (hostAbortCheck()) {
|
|
2772
3399
|
throw createSafeError('Execution aborted');
|
|
@@ -2815,8 +3442,8 @@ ${stackTraceHardeningCode}
|
|
|
2815
3442
|
throw createSafeError('Tool request must be JSON-serializable');
|
|
2816
3443
|
}
|
|
2817
3444
|
|
|
2818
|
-
//
|
|
2819
|
-
if (requestJson && (requestJson
|
|
3445
|
+
// Counted in UTF-8 bytes, as the host counts it, so both sides agree on the limit.
|
|
3446
|
+
if (requestJson && exceedsPayloadLimit(requestJson, toolBridgeMaxPayloadBytes)) {
|
|
2820
3447
|
throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
|
|
2821
3448
|
}
|
|
2822
3449
|
|
|
@@ -2825,8 +3452,17 @@ ${stackTraceHardeningCode}
|
|
|
2825
3452
|
throw createSafeError('Tool bridge returned non-string response');
|
|
2826
3453
|
}
|
|
2827
3454
|
|
|
2828
|
-
|
|
2829
|
-
|
|
3455
|
+
// The host refuses an oversized response as a tool failure; this check only backs it up,
|
|
3456
|
+
// and reports the same way so { throwOnError: false } resolves it to a result.
|
|
3457
|
+
if (exceedsPayloadLimit(responseJson, toolBridgeMaxPayloadBytes)) {
|
|
3458
|
+
var tooLarge = 'Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)';
|
|
3459
|
+
throw markToolFailure(
|
|
3460
|
+
createSafeError(tooLarge, 'RangeError'),
|
|
3461
|
+
toolName,
|
|
3462
|
+
'RangeError',
|
|
3463
|
+
tooLarge,
|
|
3464
|
+
'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
|
|
3465
|
+
);
|
|
2830
3466
|
}
|
|
2831
3467
|
|
|
2832
3468
|
var response;
|
|
@@ -2855,13 +3491,36 @@ ${stackTraceHardeningCode}
|
|
|
2855
3491
|
var err = response.error;
|
|
2856
3492
|
var msg = (err && typeof err.message === 'string') ? err.message : 'Tool call failed';
|
|
2857
3493
|
var name = (err && typeof err.name === 'string') ? err.name : 'Error';
|
|
2858
|
-
|
|
3494
|
+
var failure = createSafeError(msg, name);
|
|
3495
|
+
if (err && err.toolError === true) {
|
|
3496
|
+
markToolFailure(failure, toolName, name, msg, err.code);
|
|
3497
|
+
}
|
|
3498
|
+
throw failure;
|
|
2859
3499
|
}
|
|
2860
3500
|
|
|
2861
3501
|
throw createSafeError('Tool bridge returned invalid response');
|
|
2862
3502
|
});
|
|
2863
3503
|
} else {
|
|
2864
|
-
promise = hostCallTool(toolName, sanitizedArgs)
|
|
3504
|
+
promise = hostCallTool(toolName, sanitizedArgs).then(undefined, function(error) {
|
|
3505
|
+
// Direct mode: the host marks failures of the tool itself with this code.
|
|
3506
|
+
if (error && error.code === 'TOOL_CALL_FAILED') {
|
|
3507
|
+
var message = typeof error.message === 'string' ? error.message : 'Tool call failed';
|
|
3508
|
+
throw markToolFailure(createSafeError(message), toolName, 'Error', message, 'TOOL_CALL_FAILED');
|
|
3509
|
+
}
|
|
3510
|
+
throw error;
|
|
3511
|
+
});
|
|
3512
|
+
}
|
|
3513
|
+
|
|
3514
|
+
if (!throwOnError) {
|
|
3515
|
+
promise = promise.then(function(result) {
|
|
3516
|
+
return { success: true, data: result };
|
|
3517
|
+
}, function(error) {
|
|
3518
|
+
var info = toolFailures.get(error);
|
|
3519
|
+
if (info) {
|
|
3520
|
+
return { success: false, error: info };
|
|
3521
|
+
}
|
|
3522
|
+
throw error;
|
|
3523
|
+
});
|
|
2865
3524
|
}
|
|
2866
3525
|
|
|
2867
3526
|
// Create a secure promise that wraps both the promise object and its result
|
|
@@ -3514,6 +4173,36 @@ ${stackTraceHardeningCode}
|
|
|
3514
4173
|
innerRuntimeScript.runInContext(innerContext);
|
|
3515
4174
|
} catch (e) { /* ignore */ }
|
|
3516
4175
|
|
|
4176
|
+
// Tool namespaces (mail.list(args)): built INSIDE the inner realm by a factory evaluated there
|
|
4177
|
+
// (before Object/JSON are replaced by the safe globals below), so each namespace is a frozen,
|
|
4178
|
+
// null-prototype inner-realm object whose methods call the gated callTool. A namespace call is
|
|
4179
|
+
// therefore an ordinary tool call: counted, rate-limited, pattern-checked and sanitized.
|
|
4180
|
+
var toolNamespaceNames = ${JSON.stringify(toolNamespaces.map((ns) => ns.name))};
|
|
4181
|
+
if (toolNamespaceNames.length > 0) {
|
|
4182
|
+
var installToolNamespaces = new vm.Script(${JSON.stringify(TOOL_NAMESPACE_FACTORY_SOURCE)}, {
|
|
4183
|
+
filename: 'inner-tool-namespaces.js'
|
|
4184
|
+
}).runInContext(innerContext);
|
|
4185
|
+
var builtToolNamespaces = installToolNamespaces(safeRuntime.__safe_callTool, ${JSON.stringify(
|
|
4186
|
+
JSON.stringify(toolNamespaces)
|
|
4187
|
+
)});
|
|
4188
|
+
for (var tn = 0; tn < toolNamespaceNames.length; tn++) {
|
|
4189
|
+
var toolNamespaceName = toolNamespaceNames[tn];
|
|
4190
|
+
var toolNamespace = builtToolNamespaces[toolNamespaceName];
|
|
4191
|
+
__ag_defineProperty(innerContext, toolNamespaceName, {
|
|
4192
|
+
value: toolNamespace,
|
|
4193
|
+
writable: false,
|
|
4194
|
+
configurable: false,
|
|
4195
|
+
enumerable: false
|
|
4196
|
+
});
|
|
4197
|
+
__ag_defineProperty(innerContext, '__safe_' + toolNamespaceName, {
|
|
4198
|
+
value: toolNamespace,
|
|
4199
|
+
writable: false,
|
|
4200
|
+
configurable: false,
|
|
4201
|
+
enumerable: false
|
|
4202
|
+
});
|
|
4203
|
+
}
|
|
4204
|
+
}
|
|
4205
|
+
|
|
3517
4206
|
// Defense-in-depth: Remove host callback from inner sandbox after all scripts have captured it
|
|
3518
4207
|
try { delete innerContext['__host_memory_track__']; } catch (e) { /* ignore */ }
|
|
3519
4208
|
|
|
@@ -3757,6 +4446,8 @@ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
|
|
|
3757
4446
|
var init_parent_vm_bootstrap = __esm({
|
|
3758
4447
|
"libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
|
|
3759
4448
|
"use strict";
|
|
4449
|
+
init_global_function_gate();
|
|
4450
|
+
init_tool_namespaces();
|
|
3760
4451
|
MEMBRANE_MAX_RECURSION_DEPTH = 256;
|
|
3761
4452
|
NODEJS_24_DANGEROUS_GLOBALS = {
|
|
3762
4453
|
STRICT: [
|
|
@@ -3968,36 +4659,7 @@ var init_suspicious_patterns = __esm({
|
|
|
3968
4659
|
});
|
|
3969
4660
|
|
|
3970
4661
|
// libs/core/src/double-vm/double-vm-wrapper.ts
|
|
3971
|
-
|
|
3972
|
-
if (!stack || !sanitize) return stack;
|
|
3973
|
-
let sanitized = stack;
|
|
3974
|
-
for (const pattern of SENSITIVE_STACK_PATTERNS) {
|
|
3975
|
-
pattern.lastIndex = 0;
|
|
3976
|
-
sanitized = sanitized.replace(pattern, "[REDACTED]");
|
|
3977
|
-
}
|
|
3978
|
-
const lines = sanitized.split("\n");
|
|
3979
|
-
for (let i = 0; i < lines.length; i++) {
|
|
3980
|
-
const line = lines[i];
|
|
3981
|
-
if (line.length > 1e3) continue;
|
|
3982
|
-
if (/:\d+:\d+\)/.test(line)) {
|
|
3983
|
-
const atIdx = line.indexOf("at ");
|
|
3984
|
-
if (atIdx !== -1) {
|
|
3985
|
-
const afterAt = line.substring(atIdx + 3).trimStart();
|
|
3986
|
-
const spaceIdx = afterAt.indexOf(" ");
|
|
3987
|
-
if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
|
|
3988
|
-
const funcName = afterAt.substring(0, spaceIdx);
|
|
3989
|
-
lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
|
|
3990
|
-
continue;
|
|
3991
|
-
}
|
|
3992
|
-
}
|
|
3993
|
-
}
|
|
3994
|
-
if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
|
|
3995
|
-
lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
|
|
3996
|
-
}
|
|
3997
|
-
}
|
|
3998
|
-
return lines.join("\n");
|
|
3999
|
-
}
|
|
4000
|
-
var vm2, SENSITIVE_STACK_PATTERNS, DoubleVmWrapper;
|
|
4662
|
+
var vm2, DoubleVmWrapper;
|
|
4001
4663
|
var init_double_vm_wrapper = __esm({
|
|
4002
4664
|
"libs/core/src/double-vm/double-vm-wrapper.ts"() {
|
|
4003
4665
|
"use strict";
|
|
@@ -4008,14 +4670,10 @@ var init_double_vm_wrapper = __esm({
|
|
|
4008
4670
|
init_reference_resolver();
|
|
4009
4671
|
init_memory_tracker();
|
|
4010
4672
|
init_tool_bridge();
|
|
4673
|
+
init_stack_trace();
|
|
4674
|
+
init_global_function_gate();
|
|
4011
4675
|
init_parent_vm_bootstrap();
|
|
4012
4676
|
init_suspicious_patterns();
|
|
4013
|
-
SENSITIVE_STACK_PATTERNS = [
|
|
4014
|
-
/\/Users\/[^/]+\/[^\s):]*/gi,
|
|
4015
|
-
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
4016
|
-
/\/var\/[^\s):]*/gi,
|
|
4017
|
-
/node_modules\/[^\s):]+/gi
|
|
4018
|
-
];
|
|
4019
4677
|
DoubleVmWrapper = class {
|
|
4020
4678
|
constructor(config, securityLevel) {
|
|
4021
4679
|
this.config = config;
|
|
@@ -4179,6 +4837,18 @@ var init_double_vm_wrapper = __esm({
|
|
|
4179
4837
|
configurable: true
|
|
4180
4838
|
// Allow deletion after capture for defense-in-depth
|
|
4181
4839
|
});
|
|
4840
|
+
Object.defineProperty(parentContext, "__host_invokeGlobal__", {
|
|
4841
|
+
value: createHostGlobalFunctionInvoker(executionContext),
|
|
4842
|
+
writable: false,
|
|
4843
|
+
configurable: true
|
|
4844
|
+
// Allow deletion after capture for defense-in-depth
|
|
4845
|
+
});
|
|
4846
|
+
Object.defineProperty(parentContext, "__host_isBuiltinMethod__", {
|
|
4847
|
+
value: (fn) => isBuiltinMethod(fn),
|
|
4848
|
+
writable: false,
|
|
4849
|
+
configurable: true
|
|
4850
|
+
// Allow deletion after capture for defense-in-depth
|
|
4851
|
+
});
|
|
4182
4852
|
Object.defineProperty(parentContext, "__host_stats__", {
|
|
4183
4853
|
value: stats,
|
|
4184
4854
|
writable: false,
|
|
@@ -4314,7 +4984,11 @@ var init_double_vm_wrapper = __esm({
|
|
|
4314
4984
|
return sanitized;
|
|
4315
4985
|
} catch (error) {
|
|
4316
4986
|
const err = error;
|
|
4317
|
-
throw createSafeError(
|
|
4987
|
+
throw createSafeError(
|
|
4988
|
+
`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
|
|
4989
|
+
"Error",
|
|
4990
|
+
"TOOL_CALL_FAILED"
|
|
4991
|
+
);
|
|
4318
4992
|
}
|
|
4319
4993
|
};
|
|
4320
4994
|
}
|
|
@@ -4359,7 +5033,9 @@ var init_double_vm_wrapper = __esm({
|
|
|
4359
5033
|
memoryLimit: config.memoryLimit,
|
|
4360
5034
|
throwOnBlocked,
|
|
4361
5035
|
toolBridgeMode,
|
|
4362
|
-
toolBridgeMaxPayloadBytes
|
|
5036
|
+
toolBridgeMaxPayloadBytes,
|
|
5037
|
+
maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls(config),
|
|
5038
|
+
toolNamespaces: executionContext.toolNamespaces ?? []
|
|
4363
5039
|
});
|
|
4364
5040
|
}
|
|
4365
5041
|
/**
|
|
@@ -4540,6 +5216,16 @@ var init_memory_proxy = __esm({
|
|
|
4540
5216
|
});
|
|
4541
5217
|
|
|
4542
5218
|
// libs/core/src/safe-runtime.ts
|
|
5219
|
+
function readThrowOnError(options) {
|
|
5220
|
+
if (options === void 0 || options === null) return true;
|
|
5221
|
+
if (typeof options !== "object") {
|
|
5222
|
+
throw createSafeTypeError("callTool options must be an object");
|
|
5223
|
+
}
|
|
5224
|
+
return options.throwOnError !== false;
|
|
5225
|
+
}
|
|
5226
|
+
function plainResult(fields) {
|
|
5227
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), fields);
|
|
5228
|
+
}
|
|
4543
5229
|
function createSafeRuntime(context, options) {
|
|
4544
5230
|
const { config, stats } = context;
|
|
4545
5231
|
const sidecar = options?.sidecar;
|
|
@@ -4548,7 +5234,8 @@ function createSafeRuntime(context, options) {
|
|
|
4548
5234
|
const memoryTracker = options?.memoryTracker;
|
|
4549
5235
|
const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
|
|
4550
5236
|
const proxyOptions = secureProxyConfig ? { levelConfig: secureProxyConfig } : {};
|
|
4551
|
-
async function __safe_callTool(toolName, args) {
|
|
5237
|
+
async function __safe_callTool(toolName, args, options2) {
|
|
5238
|
+
const throwOnError = readThrowOnError(options2);
|
|
4552
5239
|
if (context.aborted) {
|
|
4553
5240
|
throw createSafeError("Execution aborted");
|
|
4554
5241
|
}
|
|
@@ -4592,21 +5279,34 @@ function createSafeRuntime(context, options) {
|
|
|
4592
5279
|
allowDates: true,
|
|
4593
5280
|
allowErrors: true
|
|
4594
5281
|
});
|
|
5282
|
+
let value = sanitized;
|
|
4595
5283
|
if (sidecar && referenceConfig && typeof sanitized === "string") {
|
|
4596
5284
|
const size = Buffer.byteLength(sanitized, "utf-8");
|
|
4597
5285
|
if (size >= referenceConfig.extractionThreshold) {
|
|
4598
5286
|
try {
|
|
4599
|
-
|
|
4600
|
-
return refId;
|
|
5287
|
+
value = sidecar.store(sanitized, "tool-result", { origin: toolName });
|
|
4601
5288
|
} catch {
|
|
4602
|
-
|
|
5289
|
+
value = sanitized;
|
|
4603
5290
|
}
|
|
4604
5291
|
}
|
|
4605
5292
|
}
|
|
4606
|
-
return
|
|
5293
|
+
return throwOnError ? value : plainResult({ success: true, data: value });
|
|
4607
5294
|
} catch (error) {
|
|
4608
5295
|
const err = error;
|
|
4609
|
-
|
|
5296
|
+
const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
|
|
5297
|
+
if (!throwOnError) {
|
|
5298
|
+
const code = error?.code;
|
|
5299
|
+
return plainResult({
|
|
5300
|
+
success: false,
|
|
5301
|
+
error: plainResult({
|
|
5302
|
+
name: "Error",
|
|
5303
|
+
message,
|
|
5304
|
+
...typeof code === "string" ? { code } : {},
|
|
5305
|
+
toolName
|
|
5306
|
+
})
|
|
5307
|
+
});
|
|
5308
|
+
}
|
|
5309
|
+
throw createSafeError(message);
|
|
4610
5310
|
}
|
|
4611
5311
|
}
|
|
4612
5312
|
function* __safe_forOf(iterable) {
|
|
@@ -4803,7 +5503,8 @@ ${errorMessages}`);
|
|
|
4803
5503
|
}
|
|
4804
5504
|
const customGlobalsWithPrefix = {};
|
|
4805
5505
|
if (config.globals) {
|
|
4806
|
-
const
|
|
5506
|
+
const customGlobalProxyOptions = options?.globalFunctionGate ? { ...proxyOptions, callGate: options.globalFunctionGate } : proxyOptions;
|
|
5507
|
+
const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, customGlobalProxyOptions);
|
|
4807
5508
|
for (const [key, value] of Object.entries(wrappedCustomGlobals)) {
|
|
4808
5509
|
customGlobalsWithPrefix[`__safe_${key}`] = value;
|
|
4809
5510
|
}
|
|
@@ -4858,18 +5559,22 @@ ${errorMessages}`);
|
|
|
4858
5559
|
}
|
|
4859
5560
|
function serializeSafeRuntime() {
|
|
4860
5561
|
return `
|
|
4861
|
-
// Safe callTool implementation
|
|
4862
|
-
|
|
5562
|
+
// Safe callTool implementation. The options ({ throwOnError: false }) are passed on:
|
|
5563
|
+
// only the adapter's __internal_callTool can tell a failure of the tool from a refusal.
|
|
5564
|
+
async function __safe_callTool(toolName, args, options) {
|
|
4863
5565
|
if (typeof toolName !== 'string' || !toolName) {
|
|
4864
5566
|
throw new TypeError('Tool name must be a non-empty string');
|
|
4865
5567
|
}
|
|
4866
5568
|
if (typeof args !== 'object' || args === null || Array.isArray(args)) {
|
|
4867
5569
|
throw new TypeError('Tool arguments must be an object');
|
|
4868
5570
|
}
|
|
5571
|
+
if (options !== undefined && options !== null && typeof options !== 'object') {
|
|
5572
|
+
throw new TypeError('callTool options must be an object');
|
|
5573
|
+
}
|
|
4869
5574
|
|
|
4870
5575
|
// This will be replaced by the sandbox adapter with actual implementation
|
|
4871
5576
|
if (typeof __internal_callTool === 'function') {
|
|
4872
|
-
return await __internal_callTool(toolName, args);
|
|
5577
|
+
return await __internal_callTool(toolName, args, options);
|
|
4873
5578
|
}
|
|
4874
5579
|
throw new Error('Tool handler not available');
|
|
4875
5580
|
}
|
|
@@ -5038,36 +5743,6 @@ var vm_adapter_exports = {};
|
|
|
5038
5743
|
__export(vm_adapter_exports, {
|
|
5039
5744
|
VmAdapter: () => VmAdapter
|
|
5040
5745
|
});
|
|
5041
|
-
function sanitizeStackTrace2(stack, sanitize = true) {
|
|
5042
|
-
if (!stack) return stack;
|
|
5043
|
-
if (!sanitize) return stack;
|
|
5044
|
-
let sanitized = stack;
|
|
5045
|
-
for (const pattern of SENSITIVE_STACK_PATTERNS2) {
|
|
5046
|
-
pattern.lastIndex = 0;
|
|
5047
|
-
sanitized = sanitized.replace(pattern, "[REDACTED]");
|
|
5048
|
-
}
|
|
5049
|
-
const lines = sanitized.split("\n");
|
|
5050
|
-
for (let i = 0; i < lines.length; i++) {
|
|
5051
|
-
const line = lines[i];
|
|
5052
|
-
if (line.length > 1e3) continue;
|
|
5053
|
-
if (/:\d+:\d+\)/.test(line)) {
|
|
5054
|
-
const atIdx = line.indexOf("at ");
|
|
5055
|
-
if (atIdx !== -1) {
|
|
5056
|
-
const afterAt = line.substring(atIdx + 3).trimStart();
|
|
5057
|
-
const spaceIdx = afterAt.indexOf(" ");
|
|
5058
|
-
if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
|
|
5059
|
-
const funcName = afterAt.substring(0, spaceIdx);
|
|
5060
|
-
lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
|
|
5061
|
-
continue;
|
|
5062
|
-
}
|
|
5063
|
-
}
|
|
5064
|
-
}
|
|
5065
|
-
if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
|
|
5066
|
-
lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
|
|
5067
|
-
}
|
|
5068
|
-
}
|
|
5069
|
-
return lines.join("\n");
|
|
5070
|
-
}
|
|
5071
5746
|
function createSafeConsole(config, stats) {
|
|
5072
5747
|
const wrap = (method) => (...args) => {
|
|
5073
5748
|
stats.callCount++;
|
|
@@ -5231,7 +5906,7 @@ function sanitizeVmContext(context, securityLevel) {
|
|
|
5231
5906
|
enumerable: true
|
|
5232
5907
|
});
|
|
5233
5908
|
}
|
|
5234
|
-
var vm3,
|
|
5909
|
+
var vm3, 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;
|
|
5235
5910
|
var init_vm_adapter = __esm({
|
|
5236
5911
|
"libs/core/src/adapters/vm-adapter.ts"() {
|
|
5237
5912
|
"use strict";
|
|
@@ -5242,130 +5917,9 @@ var init_vm_adapter = __esm({
|
|
|
5242
5917
|
init_memory_tracker();
|
|
5243
5918
|
init_tool_bridge();
|
|
5244
5919
|
init_value_sanitizer();
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
// macOS home directories
|
|
5249
|
-
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
5250
|
-
// Linux home directories
|
|
5251
|
-
/\/var\/[^\s):]*/gi,
|
|
5252
|
-
// System var directories
|
|
5253
|
-
/\/opt\/[^\s):]*/gi,
|
|
5254
|
-
// Optional software
|
|
5255
|
-
/\/tmp\/[^\s):]*/gi,
|
|
5256
|
-
// Temporary files
|
|
5257
|
-
/\/etc\/[^\s):]*/gi,
|
|
5258
|
-
// System configuration
|
|
5259
|
-
/\/root\/[^\s):]*/gi,
|
|
5260
|
-
// Root home directory
|
|
5261
|
-
/\/mnt\/[^\s):]*/gi,
|
|
5262
|
-
// Mount points
|
|
5263
|
-
/\/srv\/[^\s):]*/gi,
|
|
5264
|
-
// Service data
|
|
5265
|
-
/\/data\/[^\s):]*/gi,
|
|
5266
|
-
// Data directories
|
|
5267
|
-
/\/app\/[^\s):]*/gi,
|
|
5268
|
-
// Application directories
|
|
5269
|
-
/\/proc\/[^\s):]*/gi,
|
|
5270
|
-
// Process information
|
|
5271
|
-
/\/sys\/[^\s):]*/gi,
|
|
5272
|
-
// System files
|
|
5273
|
-
// Windows paths
|
|
5274
|
-
/\\\\[^\s):]*/g,
|
|
5275
|
-
// UNC paths
|
|
5276
|
-
/[A-Z]:\\[^\s):]+/gi,
|
|
5277
|
-
// Windows drive paths
|
|
5278
|
-
// URL-based paths
|
|
5279
|
-
/file:\/\/[^\s):]+/gi,
|
|
5280
|
-
// File URLs
|
|
5281
|
-
/webpack:\/\/[^\s):]+/gi,
|
|
5282
|
-
// Webpack paths
|
|
5283
|
-
/%2F[^\s):]+/gi,
|
|
5284
|
-
// URL-encoded paths
|
|
5285
|
-
// Package managers and node
|
|
5286
|
-
/node_modules\/[^\s):]+/gi,
|
|
5287
|
-
// Node modules paths
|
|
5288
|
-
/\/nix\/store\/[^\s):]*/gi,
|
|
5289
|
-
// Nix store paths
|
|
5290
|
-
/\.npm\/[^\s):]*/gi,
|
|
5291
|
-
// NPM cache
|
|
5292
|
-
/\.yarn\/[^\s):]*/gi,
|
|
5293
|
-
// Yarn cache
|
|
5294
|
-
/\.pnpm\/[^\s):]*/gi,
|
|
5295
|
-
// PNPM cache
|
|
5296
|
-
// Container and orchestration
|
|
5297
|
-
/\/run\/secrets\/[^\s):]*/gi,
|
|
5298
|
-
// Docker/K8s secrets
|
|
5299
|
-
/\/var\/run\/[^\s):]*/gi,
|
|
5300
|
-
// Runtime directories
|
|
5301
|
-
/\/docker\/[^\s):]*/gi,
|
|
5302
|
-
// Docker paths
|
|
5303
|
-
/\/containers\/[^\s):]*/gi,
|
|
5304
|
-
// Container paths
|
|
5305
|
-
/\/kubelet\/[^\s):]*/gi,
|
|
5306
|
-
// Kubernetes kubelet
|
|
5307
|
-
// CI/CD systems
|
|
5308
|
-
/\/github\/workspace\/[^\s):]*/gi,
|
|
5309
|
-
// GitHub Actions
|
|
5310
|
-
/\/runner\/[^\s):]*/gi,
|
|
5311
|
-
// GitHub/GitLab runner
|
|
5312
|
-
/\/builds\/[^\s):]*/gi,
|
|
5313
|
-
// CI builds
|
|
5314
|
-
/\/workspace\/[^\s):]*/gi,
|
|
5315
|
-
// Generic workspace
|
|
5316
|
-
/\/pipeline\/[^\s):]*/gi,
|
|
5317
|
-
// CI pipelines
|
|
5318
|
-
/\/jenkins\/[^\s):]*/gi,
|
|
5319
|
-
// Jenkins
|
|
5320
|
-
/\/bamboo\/[^\s):]*/gi,
|
|
5321
|
-
// Bamboo
|
|
5322
|
-
/\/teamcity\/[^\s):]*/gi,
|
|
5323
|
-
// TeamCity
|
|
5324
|
-
/\/circleci\/[^\s):]*/gi,
|
|
5325
|
-
// CircleCI
|
|
5326
|
-
// Cloud providers
|
|
5327
|
-
/\/aws\/[^\s):]*/gi,
|
|
5328
|
-
// AWS paths
|
|
5329
|
-
/\/gcloud\/[^\s):]*/gi,
|
|
5330
|
-
// Google Cloud
|
|
5331
|
-
/\/azure\/[^\s):]*/gi,
|
|
5332
|
-
// Azure paths
|
|
5333
|
-
/s3:\/\/[^\s):]+/gi,
|
|
5334
|
-
// S3 URIs
|
|
5335
|
-
/gs:\/\/[^\s):]+/gi,
|
|
5336
|
-
// GCS URIs
|
|
5337
|
-
// Secrets and credentials (patterns that might appear in paths or errors)
|
|
5338
|
-
/[A-Z0-9]{20,}/g,
|
|
5339
|
-
// AWS-style access keys (20+ uppercase chars)
|
|
5340
|
-
/sk-[a-zA-Z0-9]{32,}/g,
|
|
5341
|
-
// OpenAI/Stripe-style secret keys
|
|
5342
|
-
/ghp_[a-zA-Z0-9]{36,}/g,
|
|
5343
|
-
// GitHub personal access tokens
|
|
5344
|
-
/gho_[a-zA-Z0-9]{36,}/g,
|
|
5345
|
-
// GitHub OAuth tokens
|
|
5346
|
-
/github_pat_[a-zA-Z0-9_]{22,}/g,
|
|
5347
|
-
// GitHub fine-grained tokens
|
|
5348
|
-
/xox[baprs]-[a-zA-Z0-9-]+/g,
|
|
5349
|
-
// Slack tokens
|
|
5350
|
-
/Bearer\s+[a-zA-Z0-9._-]+/gi,
|
|
5351
|
-
// Bearer tokens
|
|
5352
|
-
/Basic\s+[a-zA-Z0-9+/=]+/gi,
|
|
5353
|
-
// Basic auth
|
|
5354
|
-
// Internal network info
|
|
5355
|
-
/(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
|
|
5356
|
-
// Private IPs
|
|
5357
|
-
/[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
|
|
5358
|
-
// Internal hostnames
|
|
5359
|
-
/localhost:\d+/gi,
|
|
5360
|
-
// Localhost with port
|
|
5361
|
-
/127\.0\.0\.1:\d+/gi,
|
|
5362
|
-
// Loopback with port
|
|
5363
|
-
// User information
|
|
5364
|
-
/\/u\/[^/]+\//gi,
|
|
5365
|
-
// User subdirectories
|
|
5366
|
-
/~[a-z_][a-z0-9_-]*/gi
|
|
5367
|
-
// Unix user home shorthand
|
|
5368
|
-
];
|
|
5920
|
+
init_stack_trace();
|
|
5921
|
+
init_global_function_gate();
|
|
5922
|
+
init_tool_namespaces();
|
|
5369
5923
|
STACK_TRACE_HARDENING_CODE = `
|
|
5370
5924
|
(function() {
|
|
5371
5925
|
function __ag_redactStackString(stackStr) {
|
|
@@ -5531,6 +6085,20 @@ var init_vm_adapter = __esm({
|
|
|
5531
6085
|
})();
|
|
5532
6086
|
`;
|
|
5533
6087
|
INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm3.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
|
|
6088
|
+
SANDBOX_REALM_BRIDGE_SCRIPT = new vm3.Script(`
|
|
6089
|
+
(function () {
|
|
6090
|
+
'use strict';
|
|
6091
|
+
var parse = JSON.parse;
|
|
6092
|
+
var SandboxPromise = Promise;
|
|
6093
|
+
return Object.freeze({
|
|
6094
|
+
parseJson: function (json) { return parse(json); },
|
|
6095
|
+
adoptPromise: function (hostPromise) {
|
|
6096
|
+
return new SandboxPromise(function (resolve, reject) { hostPromise.then(resolve, reject); });
|
|
6097
|
+
}
|
|
6098
|
+
});
|
|
6099
|
+
})()
|
|
6100
|
+
`);
|
|
6101
|
+
TOOL_NAMESPACE_FACTORY_SCRIPT = new vm3.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
|
|
5534
6102
|
PROTECTED_PREFIXES = ["__safe_", "__ag_"];
|
|
5535
6103
|
DANGEROUS_OBJECT_STATIC_METHODS = [
|
|
5536
6104
|
"defineProperty",
|
|
@@ -5646,19 +6214,23 @@ var init_vm_adapter = __esm({
|
|
|
5646
6214
|
}) : void 0;
|
|
5647
6215
|
memoryTracker?.start();
|
|
5648
6216
|
try {
|
|
5649
|
-
const safeRuntime = createSafeRuntime(executionContext, {
|
|
5650
|
-
sidecar: executionContext.sidecar,
|
|
5651
|
-
referenceConfig: executionContext.referenceConfig,
|
|
5652
|
-
secureProxyConfig: executionContext.secureProxyConfig,
|
|
5653
|
-
memoryTracker
|
|
5654
|
-
// Pass tracker for allocation monitoring
|
|
5655
|
-
});
|
|
5656
6217
|
const baseSandbox = vm3.createContext(
|
|
5657
6218
|
{},
|
|
5658
6219
|
{
|
|
5659
6220
|
codeGeneration: { strings: false, wasm: false }
|
|
5660
6221
|
}
|
|
5661
6222
|
);
|
|
6223
|
+
const realmBridge = SANDBOX_REALM_BRIDGE_SCRIPT.runInContext(baseSandbox);
|
|
6224
|
+
const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
|
|
6225
|
+
const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge);
|
|
6226
|
+
const safeRuntime = createSafeRuntime(executionContext, {
|
|
6227
|
+
sidecar: executionContext.sidecar,
|
|
6228
|
+
referenceConfig: executionContext.referenceConfig,
|
|
6229
|
+
secureProxyConfig: executionContext.secureProxyConfig,
|
|
6230
|
+
memoryTracker,
|
|
6231
|
+
// Pass tracker for allocation monitoring
|
|
6232
|
+
globalFunctionGate
|
|
6233
|
+
});
|
|
5662
6234
|
if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
|
|
5663
6235
|
Object.defineProperty(baseSandbox, "__host_memory_track__", {
|
|
5664
6236
|
value: (bytes) => {
|
|
@@ -5822,9 +6394,28 @@ var init_vm_adapter = __esm({
|
|
|
5822
6394
|
// Remove global handle after capture (defense-in-depth)
|
|
5823
6395
|
try { delete globalThis.__host_callToolBridge__; } catch (e) { /* ignore */ }
|
|
5824
6396
|
|
|
5825
|
-
|
|
5826
|
-
|
|
5827
|
-
|
|
6397
|
+
// Whether a payload is larger than the limit in UTF-8 bytes, as the host counts it. A code
|
|
6398
|
+
// unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
|
|
6399
|
+
function exceedsPayloadLimit(str) {
|
|
6400
|
+
if (str.length > maxBytes) return true;
|
|
6401
|
+
if (str.length * 3 <= maxBytes) return false;
|
|
6402
|
+
var bytes = 0;
|
|
6403
|
+
for (var i = 0; i < str.length; i++) {
|
|
6404
|
+
var c = str.charCodeAt(i);
|
|
6405
|
+
if (c < 0x80) bytes += 1;
|
|
6406
|
+
else if (c < 0x800) bytes += 2;
|
|
6407
|
+
else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
|
|
6408
|
+
var d = str.charCodeAt(i + 1);
|
|
6409
|
+
if (d >= 0xdc00 && d <= 0xdfff) {
|
|
6410
|
+
bytes += 4;
|
|
6411
|
+
i++;
|
|
6412
|
+
} else {
|
|
6413
|
+
bytes += 3;
|
|
6414
|
+
}
|
|
6415
|
+
} else bytes += 3;
|
|
6416
|
+
if (bytes > maxBytes) return true;
|
|
6417
|
+
}
|
|
6418
|
+
return false;
|
|
5828
6419
|
}
|
|
5829
6420
|
|
|
5830
6421
|
function makeError(message, name) {
|
|
@@ -5833,7 +6424,16 @@ var init_vm_adapter = __esm({
|
|
|
5833
6424
|
return err;
|
|
5834
6425
|
}
|
|
5835
6426
|
|
|
5836
|
-
return async function __safe_callTool(toolName, args) {
|
|
6427
|
+
return async function __safe_callTool(toolName, args, options) {
|
|
6428
|
+
// callTool options: only { throwOnError: false } changes behavior. Tool failures
|
|
6429
|
+
// then resolve to { success: false, error }; the enclave's own refusals still throw.
|
|
6430
|
+
var throwOnError = true;
|
|
6431
|
+
if (options !== undefined && options !== null) {
|
|
6432
|
+
if (typeof options !== 'object') {
|
|
6433
|
+
throw makeError('callTool options must be an object', 'TypeError');
|
|
6434
|
+
}
|
|
6435
|
+
throwOnError = options.throwOnError !== false;
|
|
6436
|
+
}
|
|
5837
6437
|
if (typeof toolName !== 'string' || !toolName) {
|
|
5838
6438
|
throw makeError('Tool name must be a non-empty string', 'TypeError');
|
|
5839
6439
|
}
|
|
@@ -5859,7 +6459,7 @@ var init_vm_adapter = __esm({
|
|
|
5859
6459
|
throw makeError('Tool request must be JSON-serializable', 'TypeError');
|
|
5860
6460
|
}
|
|
5861
6461
|
|
|
5862
|
-
if (
|
|
6462
|
+
if (exceedsPayloadLimit(requestJson)) {
|
|
5863
6463
|
throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
|
|
5864
6464
|
}
|
|
5865
6465
|
|
|
@@ -5867,8 +6467,24 @@ var init_vm_adapter = __esm({
|
|
|
5867
6467
|
if (typeof responseJson !== 'string') {
|
|
5868
6468
|
throw makeError('Tool bridge returned invalid response', 'Error');
|
|
5869
6469
|
}
|
|
5870
|
-
|
|
5871
|
-
|
|
6470
|
+
// The host refuses an oversized response as a tool failure; this check only backs it
|
|
6471
|
+
// up, and reports the same way so { throwOnError: false } resolves it to a result.
|
|
6472
|
+
if (exceedsPayloadLimit(responseJson)) {
|
|
6473
|
+
var tooLarge = 'Tool response exceeds maximum size (' + maxBytes + ' bytes)';
|
|
6474
|
+
if (!throwOnError) {
|
|
6475
|
+
return {
|
|
6476
|
+
__proto__: null,
|
|
6477
|
+
success: false,
|
|
6478
|
+
error: {
|
|
6479
|
+
__proto__: null,
|
|
6480
|
+
name: 'RangeError',
|
|
6481
|
+
message: tooLarge,
|
|
6482
|
+
toolName: toolName,
|
|
6483
|
+
code: 'TOOL_BRIDGE_RESPONSE_TOO_LARGE',
|
|
6484
|
+
},
|
|
6485
|
+
};
|
|
6486
|
+
}
|
|
6487
|
+
throw makeError(tooLarge, 'RangeError');
|
|
5872
6488
|
}
|
|
5873
6489
|
|
|
5874
6490
|
var response;
|
|
@@ -5883,13 +6499,18 @@ var init_vm_adapter = __esm({
|
|
|
5883
6499
|
}
|
|
5884
6500
|
|
|
5885
6501
|
if (response.ok === true) {
|
|
5886
|
-
|
|
5887
|
-
return
|
|
6502
|
+
var value = hasOwn.call(response, 'value') ? response.value : undefined;
|
|
6503
|
+
return throwOnError ? value : { __proto__: null, success: true, data: value };
|
|
5888
6504
|
}
|
|
5889
6505
|
|
|
5890
6506
|
if (response.ok === false && response.error) {
|
|
5891
6507
|
var msg = (typeof response.error.message === 'string') ? response.error.message : 'Tool call failed';
|
|
5892
6508
|
var name = (typeof response.error.name === 'string') ? response.error.name : 'Error';
|
|
6509
|
+
if (!throwOnError && response.error.toolError === true) {
|
|
6510
|
+
var info = { __proto__: null, name: name, message: msg, toolName: toolName };
|
|
6511
|
+
if (typeof response.error.code === 'string') info.code = response.error.code;
|
|
6512
|
+
return { __proto__: null, success: false, error: info };
|
|
6513
|
+
}
|
|
5893
6514
|
throw makeError(msg, name);
|
|
5894
6515
|
}
|
|
5895
6516
|
|
|
@@ -5923,8 +6544,9 @@ var init_vm_adapter = __esm({
|
|
|
5923
6544
|
}
|
|
5924
6545
|
if (config.globals) {
|
|
5925
6546
|
for (const [key, value2] of Object.entries(config.globals)) {
|
|
5926
|
-
const wrappedValue = value2 !== null && typeof value2 === "object" ? createSecureProxy(value2, {
|
|
5927
|
-
levelConfig: executionContext.secureProxyConfig
|
|
6547
|
+
const wrappedValue = value2 !== null && (typeof value2 === "object" || typeof value2 === "function") ? createSecureProxy(value2, {
|
|
6548
|
+
levelConfig: executionContext.secureProxyConfig,
|
|
6549
|
+
callGate: globalFunctionGate
|
|
5928
6550
|
}) : value2;
|
|
5929
6551
|
Object.defineProperty(baseSandbox, key, {
|
|
5930
6552
|
value: wrappedValue,
|
|
@@ -5934,6 +6556,23 @@ var init_vm_adapter = __esm({
|
|
|
5934
6556
|
});
|
|
5935
6557
|
}
|
|
5936
6558
|
}
|
|
6559
|
+
if (executionContext.toolNamespaces?.length) {
|
|
6560
|
+
const callTool = baseSandbox["__safe_callTool"];
|
|
6561
|
+
for (const binding of buildToolNamespaceBindings(
|
|
6562
|
+
installToolNamespaces,
|
|
6563
|
+
callTool,
|
|
6564
|
+
executionContext.toolNamespaces
|
|
6565
|
+
)) {
|
|
6566
|
+
for (const name of [binding.name, `__safe_${binding.name}`]) {
|
|
6567
|
+
Object.defineProperty(baseSandbox, name, {
|
|
6568
|
+
value: binding.value,
|
|
6569
|
+
writable: false,
|
|
6570
|
+
configurable: false,
|
|
6571
|
+
enumerable: false
|
|
6572
|
+
});
|
|
6573
|
+
}
|
|
6574
|
+
}
|
|
6575
|
+
}
|
|
5937
6576
|
if (!("__safe_console" in safeRuntime)) {
|
|
5938
6577
|
const consoleStats = { totalBytes: 0, callCount: 0 };
|
|
5939
6578
|
Object.defineProperty(baseSandbox, "__safe_console", {
|
|
@@ -6041,7 +6680,7 @@ var init_vm_adapter = __esm({
|
|
|
6041
6680
|
error: {
|
|
6042
6681
|
name: err.name || "VMExecutionError",
|
|
6043
6682
|
message: err.message || "Unknown VM execution error",
|
|
6044
|
-
stack:
|
|
6683
|
+
stack: sanitizeStackTrace(err.stack, shouldSanitize),
|
|
6045
6684
|
code: "VM_EXECUTION_ERROR"
|
|
6046
6685
|
},
|
|
6047
6686
|
stats
|
|
@@ -6193,12 +6832,13 @@ function isExecutionResultMessage(msg) {
|
|
|
6193
6832
|
function isConsoleMessage(msg) {
|
|
6194
6833
|
return msg.type === "console";
|
|
6195
6834
|
}
|
|
6196
|
-
var import_zod, TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessageSchema, memoryReportResultMessageSchema, consoleMessageSchema, workerReadyMessageSchema, workerToMainMessageSchema;
|
|
6835
|
+
var import_zod, import_ast3, TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessageSchema, memoryReportResultMessageSchema, consoleMessageSchema, workerReadyMessageSchema, workerToMainMessageSchema;
|
|
6197
6836
|
var init_protocol = __esm({
|
|
6198
6837
|
"libs/core/src/adapters/worker-pool/protocol.ts"() {
|
|
6199
6838
|
"use strict";
|
|
6200
6839
|
import_zod = require("zod");
|
|
6201
|
-
|
|
6840
|
+
import_ast3 = require("@enclave-vm/ast");
|
|
6841
|
+
TOOL_NAME_PATTERN = import_ast3.TOOL_NAMESPACE_TOOL_NAME_PATTERN;
|
|
6202
6842
|
ID_PATTERN = /^[a-zA-Z0-9-]+$/;
|
|
6203
6843
|
toolCallMessageSchema = import_zod.z.object({
|
|
6204
6844
|
type: import_zod.z.literal("tool-call"),
|
|
@@ -6430,7 +7070,7 @@ function sanitizeObjectWithDepthCheck(value, depth) {
|
|
|
6430
7070
|
if (typeof value !== "object") {
|
|
6431
7071
|
return value;
|
|
6432
7072
|
}
|
|
6433
|
-
if (
|
|
7073
|
+
if (ArrayIsArray3(value)) {
|
|
6434
7074
|
return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
|
|
6435
7075
|
}
|
|
6436
7076
|
const result = /* @__PURE__ */ Object.create(null);
|
|
@@ -6459,7 +7099,7 @@ function sanitizeObject(value, depth = 0) {
|
|
|
6459
7099
|
if (typeof value !== "object") {
|
|
6460
7100
|
return value;
|
|
6461
7101
|
}
|
|
6462
|
-
if (
|
|
7102
|
+
if (ArrayIsArray3(value)) {
|
|
6463
7103
|
return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
|
|
6464
7104
|
}
|
|
6465
7105
|
const result = /* @__PURE__ */ Object.create(null);
|
|
@@ -6470,13 +7110,13 @@ function sanitizeObject(value, depth = 0) {
|
|
|
6470
7110
|
}
|
|
6471
7111
|
return result;
|
|
6472
7112
|
}
|
|
6473
|
-
var ReflectGet4,
|
|
7113
|
+
var ReflectGet4, ArrayIsArray3, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
|
|
6474
7114
|
var init_safe_deserialize = __esm({
|
|
6475
7115
|
"libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
|
|
6476
7116
|
"use strict";
|
|
6477
7117
|
init_errors();
|
|
6478
7118
|
ReflectGet4 = Reflect.get;
|
|
6479
|
-
|
|
7119
|
+
ArrayIsArray3 = Array.isArray;
|
|
6480
7120
|
NumberIsFinite3 = Number.isFinite;
|
|
6481
7121
|
MathFloor3 = Math.floor;
|
|
6482
7122
|
MAX_ARRAY_LENGTH = 1e6;
|
|
@@ -7189,6 +7829,7 @@ var init_worker_pool_adapter = __esm({
|
|
|
7189
7829
|
init_rate_limiter();
|
|
7190
7830
|
init_safe_deserialize();
|
|
7191
7831
|
init_errors();
|
|
7832
|
+
init_stack_trace();
|
|
7192
7833
|
WorkerPoolAdapter = class {
|
|
7193
7834
|
config;
|
|
7194
7835
|
securityLevel;
|
|
@@ -7427,7 +8068,8 @@ var init_worker_pool_adapter = __esm({
|
|
|
7427
8068
|
globals: context.config.globals,
|
|
7428
8069
|
// Security level determines which globals are available in sandbox
|
|
7429
8070
|
// This mirrors AST guard's allowed globals for defense-in-depth
|
|
7430
|
-
securityLevel: this.securityLevel
|
|
8071
|
+
securityLevel: this.securityLevel,
|
|
8072
|
+
toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0
|
|
7431
8073
|
};
|
|
7432
8074
|
return new Promise((resolve, reject) => {
|
|
7433
8075
|
const pendingToolCalls = /* @__PURE__ */ new Map();
|
|
@@ -7444,7 +8086,7 @@ var init_worker_pool_adapter = __esm({
|
|
|
7444
8086
|
} else if (isExecutionResultMessage(msg) && msg.requestId === requestId) {
|
|
7445
8087
|
cleanup();
|
|
7446
8088
|
const duration = Date.now() - startTime;
|
|
7447
|
-
const result = this.buildResult(msg, duration);
|
|
8089
|
+
const result = this.buildResult(msg, duration, context.config.sanitizeStackTraces);
|
|
7448
8090
|
resolve(result);
|
|
7449
8091
|
} else if (isConsoleMessage(msg) && msg.requestId === requestId) {
|
|
7450
8092
|
this.handleConsoleMessage(msg);
|
|
@@ -7485,17 +8127,30 @@ var init_worker_pool_adapter = __esm({
|
|
|
7485
8127
|
pendingToolCalls.set(msg.callId, true);
|
|
7486
8128
|
let result;
|
|
7487
8129
|
let error;
|
|
8130
|
+
let toolError = false;
|
|
7488
8131
|
try {
|
|
7489
8132
|
if (!context.toolHandler) {
|
|
7490
8133
|
throw new Error("No tool handler configured");
|
|
7491
8134
|
}
|
|
7492
8135
|
const sanitizedArgs = sanitizeObject(msg.args);
|
|
7493
|
-
|
|
8136
|
+
toolError = true;
|
|
8137
|
+
const handlerResult = await context.toolHandler(msg.toolName, sanitizedArgs);
|
|
8138
|
+
try {
|
|
8139
|
+
result = sanitizeObject(handlerResult);
|
|
8140
|
+
} catch {
|
|
8141
|
+
throw Object.assign(new Error("Tool returned an unsupported value"), {
|
|
8142
|
+
name: "ToolBridgeError",
|
|
8143
|
+
code: "TOOL_RESULT_NOT_SAFE"
|
|
8144
|
+
});
|
|
8145
|
+
}
|
|
8146
|
+
toolError = false;
|
|
7494
8147
|
} catch (e) {
|
|
7495
8148
|
const err = e;
|
|
8149
|
+
const code = e?.code;
|
|
7496
8150
|
error = {
|
|
7497
8151
|
name: err.name || "Error",
|
|
7498
|
-
message: err.message || "Unknown error"
|
|
8152
|
+
message: err.message || "Unknown error",
|
|
8153
|
+
...toolError && typeof code === "string" ? { code } : {}
|
|
7499
8154
|
};
|
|
7500
8155
|
} finally {
|
|
7501
8156
|
pendingToolCalls.delete(msg.callId);
|
|
@@ -7504,8 +8159,9 @@ var init_worker_pool_adapter = __esm({
|
|
|
7504
8159
|
type: "tool-response",
|
|
7505
8160
|
requestId: msg.requestId,
|
|
7506
8161
|
callId: msg.callId,
|
|
7507
|
-
result
|
|
7508
|
-
error
|
|
8162
|
+
result,
|
|
8163
|
+
error,
|
|
8164
|
+
...error && toolError ? { toolError: true } : {}
|
|
7509
8165
|
});
|
|
7510
8166
|
}
|
|
7511
8167
|
handleConsoleMessage(msg) {
|
|
@@ -7522,7 +8178,7 @@ var init_worker_pool_adapter = __esm({
|
|
|
7522
8178
|
* before sending, but full runtime type validation would require schema
|
|
7523
8179
|
* definitions which are not available at this layer.
|
|
7524
8180
|
*/
|
|
7525
|
-
buildResult(msg, duration) {
|
|
8181
|
+
buildResult(msg, duration, sanitizeStacks) {
|
|
7526
8182
|
if (msg.success) {
|
|
7527
8183
|
return {
|
|
7528
8184
|
success: true,
|
|
@@ -7543,7 +8199,8 @@ var init_worker_pool_adapter = __esm({
|
|
|
7543
8199
|
name: error.name,
|
|
7544
8200
|
message: error.message,
|
|
7545
8201
|
code: error.code,
|
|
7546
|
-
stack
|
|
8202
|
+
// The worker trims its stack; sanitize it here too so the result obeys the option.
|
|
8203
|
+
stack: sanitizeStackTrace(error.stack, sanitizeStacks)
|
|
7547
8204
|
},
|
|
7548
8205
|
stats: {
|
|
7549
8206
|
duration,
|
|
@@ -7745,7 +8402,7 @@ __export(index_exports, {
|
|
|
7745
8402
|
module.exports = __toCommonJS(index_exports);
|
|
7746
8403
|
|
|
7747
8404
|
// libs/core/src/enclave.ts
|
|
7748
|
-
var
|
|
8405
|
+
var import_ast4 = require("@enclave-vm/ast");
|
|
7749
8406
|
|
|
7750
8407
|
// libs/core/src/babel/babel-wrapper.ts
|
|
7751
8408
|
var vm = __toESM(require("vm"));
|
|
@@ -8248,8 +8905,8 @@ function transformMultiple(files, options, limits, singleFileTransform) {
|
|
|
8248
8905
|
}
|
|
8249
8906
|
|
|
8250
8907
|
// libs/core/src/enclave.ts
|
|
8251
|
-
var import_ast4 = require("@enclave-vm/ast");
|
|
8252
8908
|
var import_ast5 = require("@enclave-vm/ast");
|
|
8909
|
+
var import_ast6 = require("@enclave-vm/ast");
|
|
8253
8910
|
var acorn2 = __toESM(require("acorn"));
|
|
8254
8911
|
var import_astring = require("astring");
|
|
8255
8912
|
|
|
@@ -8431,6 +9088,7 @@ var DEFAULT_DOUBLE_VM_CONFIG = {
|
|
|
8431
9088
|
};
|
|
8432
9089
|
|
|
8433
9090
|
// libs/core/src/globals-validator.ts
|
|
9091
|
+
var import_util = require("util");
|
|
8434
9092
|
var DANGEROUS_FUNCTION_PATTERNS = [
|
|
8435
9093
|
/\beval\b/,
|
|
8436
9094
|
// eval() calls
|
|
@@ -8458,7 +9116,55 @@ var DANGEROUS_FUNCTION_PATTERNS = [
|
|
|
8458
9116
|
// Synchronous spawn
|
|
8459
9117
|
];
|
|
8460
9118
|
var DANGEROUS_GLOBAL_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
8461
|
-
|
|
9119
|
+
var MapEntries = Map.prototype.entries;
|
|
9120
|
+
var SetValues = Set.prototype.values;
|
|
9121
|
+
var ReflectApply = Reflect.apply;
|
|
9122
|
+
var ReflectOwnKeys = Reflect.ownKeys;
|
|
9123
|
+
var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
|
|
9124
|
+
var ObjectGetPrototypeOf = Object.getPrototypeOf;
|
|
9125
|
+
var ArrayPrototype = Array.prototype;
|
|
9126
|
+
var MapPrototype = Map.prototype;
|
|
9127
|
+
var SetPrototype = Set.prototype;
|
|
9128
|
+
var IteratorPrototype = ObjectGetPrototypeOf(ObjectGetPrototypeOf([][Symbol.iterator]()));
|
|
9129
|
+
var AsyncIteratorPrototype = ObjectGetPrototypeOf(
|
|
9130
|
+
ObjectGetPrototypeOf(
|
|
9131
|
+
async function* () {
|
|
9132
|
+
}.prototype
|
|
9133
|
+
)
|
|
9134
|
+
);
|
|
9135
|
+
function describeOpaqueContainer(obj) {
|
|
9136
|
+
if (import_util.types.isPromise(obj)) return "a Promise";
|
|
9137
|
+
if (import_util.types.isWeakMap(obj)) return "a WeakMap";
|
|
9138
|
+
if (import_util.types.isGeneratorObject(obj)) return "a generator";
|
|
9139
|
+
if (import_util.types.isMapIterator(obj) || import_util.types.isSetIterator(obj) || Object.prototype.isPrototypeOf.call(IteratorPrototype, obj) || Object.prototype.isPrototypeOf.call(AsyncIteratorPrototype, obj)) {
|
|
9140
|
+
return "an iterator";
|
|
9141
|
+
}
|
|
9142
|
+
return void 0;
|
|
9143
|
+
}
|
|
9144
|
+
function isPlainDataObject(obj) {
|
|
9145
|
+
const proto = ObjectGetPrototypeOf(obj);
|
|
9146
|
+
return proto === null || proto === Object.prototype || import_util.types.isDate(obj) || import_util.types.isRegExp(obj) || import_util.types.isArrayBufferView(obj) || import_util.types.isAnyArrayBuffer(obj);
|
|
9147
|
+
}
|
|
9148
|
+
function describeInstance(obj) {
|
|
9149
|
+
try {
|
|
9150
|
+
const name = ObjectGetPrototypeOf(obj)?.constructor?.name;
|
|
9151
|
+
if (typeof name === "string" && name) return `a ${name} instance`;
|
|
9152
|
+
} catch {
|
|
9153
|
+
}
|
|
9154
|
+
return "a non-plain object";
|
|
9155
|
+
}
|
|
9156
|
+
function collectionError(key, what, path2) {
|
|
9157
|
+
return new Error(
|
|
9158
|
+
`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.`
|
|
9159
|
+
);
|
|
9160
|
+
}
|
|
9161
|
+
function mapValueSegment(mapKey, index) {
|
|
9162
|
+
if (typeof mapKey === "string" || typeof mapKey === "number" || typeof mapKey === "boolean") {
|
|
9163
|
+
return `get(${JSON.stringify(mapKey)})`;
|
|
9164
|
+
}
|
|
9165
|
+
return `values()[${index}]`;
|
|
9166
|
+
}
|
|
9167
|
+
function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet(), collectionVisited = /* @__PURE__ */ new WeakSet(), inCollection = false) {
|
|
8462
9168
|
const maxDepth = options.maxDepth ?? 10;
|
|
8463
9169
|
const allowFunctions = options.allowFunctions ?? false;
|
|
8464
9170
|
const allowGettersSetters = options.allowGettersSetters ?? false;
|
|
@@ -8482,6 +9188,9 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
|
|
|
8482
9188
|
}
|
|
8483
9189
|
if (type === "function") {
|
|
8484
9190
|
const funcName = value.name || "anonymous";
|
|
9191
|
+
if (inCollection && (allowFunctions || allowedFunctionNames.includes(funcName))) {
|
|
9192
|
+
throw collectionError(key, "a function", path2);
|
|
9193
|
+
}
|
|
8485
9194
|
if (allowedFunctionNames.includes(funcName)) {
|
|
8486
9195
|
return;
|
|
8487
9196
|
}
|
|
@@ -8508,35 +9217,89 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
|
|
|
8508
9217
|
}
|
|
8509
9218
|
if (type === "object") {
|
|
8510
9219
|
const obj = value;
|
|
8511
|
-
|
|
9220
|
+
const seen = inCollection ? collectionVisited : visited;
|
|
9221
|
+
if (seen.has(obj)) {
|
|
8512
9222
|
return;
|
|
8513
9223
|
}
|
|
8514
|
-
|
|
9224
|
+
seen.add(obj);
|
|
9225
|
+
const opaque = describeOpaqueContainer(obj);
|
|
9226
|
+
if (opaque) {
|
|
9227
|
+
throw new Error(
|
|
9228
|
+
`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.`
|
|
9229
|
+
);
|
|
9230
|
+
}
|
|
9231
|
+
const isArray = Array.isArray(obj);
|
|
9232
|
+
const isMap = import_util.types.isMap(obj);
|
|
9233
|
+
const isSet = import_util.types.isSet(obj);
|
|
9234
|
+
if (isArray) {
|
|
9235
|
+
const hidden = import_util.types.isProxy(obj) ? "a Proxy array" : ObjectGetPrototypeOf(obj) !== ArrayPrototype ? "an array with a custom prototype" : void 0;
|
|
9236
|
+
if (hidden) {
|
|
9237
|
+
throw new Error(
|
|
9238
|
+
`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.`
|
|
9239
|
+
);
|
|
9240
|
+
}
|
|
9241
|
+
}
|
|
9242
|
+
if (inCollection) {
|
|
9243
|
+
if (import_util.types.isProxy(obj)) {
|
|
9244
|
+
throw collectionError(key, "a Proxy", path2);
|
|
9245
|
+
}
|
|
9246
|
+
if (!isArray && !isMap && !isSet && !isPlainDataObject(obj)) {
|
|
9247
|
+
throw collectionError(key, describeInstance(obj), path2);
|
|
9248
|
+
}
|
|
9249
|
+
if ((isMap || isSet) && ObjectGetPrototypeOf(obj) !== (isMap ? MapPrototype : SetPrototype)) {
|
|
9250
|
+
throw collectionError(key, describeInstance(obj), path2);
|
|
9251
|
+
}
|
|
9252
|
+
}
|
|
8515
9253
|
if (!allowGettersSetters) {
|
|
8516
|
-
const
|
|
8517
|
-
|
|
8518
|
-
if (desc.get || desc.set) {
|
|
9254
|
+
for (const prop of ReflectOwnKeys(obj)) {
|
|
9255
|
+
const desc = ReflectGetOwnPropertyDescriptor(obj, prop);
|
|
9256
|
+
if (desc && (desc.get || desc.set)) {
|
|
9257
|
+
const at = [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`].join(".");
|
|
8519
9258
|
throw new Error(
|
|
8520
|
-
`Custom global "${key}" has a getter/setter at ${
|
|
9259
|
+
`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.`
|
|
8521
9260
|
);
|
|
8522
9261
|
}
|
|
8523
9262
|
}
|
|
8524
9263
|
}
|
|
8525
|
-
if (
|
|
8526
|
-
|
|
8527
|
-
|
|
9264
|
+
if (isMap) {
|
|
9265
|
+
let index = 0;
|
|
9266
|
+
for (const [mapKey, mapValue] of ReflectApply(MapEntries, obj, [])) {
|
|
9267
|
+
validateGlobalValue(key, mapKey, options, [...path2, `keys()[${index}]`], visited, collectionVisited, true);
|
|
9268
|
+
validateGlobalValue(
|
|
9269
|
+
key,
|
|
9270
|
+
mapValue,
|
|
9271
|
+
options,
|
|
9272
|
+
[...path2, mapValueSegment(mapKey, index)],
|
|
9273
|
+
visited,
|
|
9274
|
+
collectionVisited,
|
|
9275
|
+
true
|
|
9276
|
+
);
|
|
9277
|
+
index++;
|
|
9278
|
+
}
|
|
9279
|
+
} else if (isSet) {
|
|
9280
|
+
let index = 0;
|
|
9281
|
+
for (const element of ReflectApply(SetValues, obj, [])) {
|
|
9282
|
+
validateGlobalValue(key, element, options, [...path2, `values()[${index}]`], visited, collectionVisited, true);
|
|
9283
|
+
index++;
|
|
8528
9284
|
}
|
|
8529
|
-
return;
|
|
8530
9285
|
}
|
|
8531
|
-
const keys = Object.keys(obj);
|
|
9286
|
+
const keys = isArray || inCollection ? ReflectOwnKeys(obj) : Object.keys(obj);
|
|
8532
9287
|
for (const prop of keys) {
|
|
8533
|
-
if (DANGEROUS_GLOBAL_KEYS.has(prop)) {
|
|
9288
|
+
if (typeof prop === "string" && DANGEROUS_GLOBAL_KEYS.has(prop)) {
|
|
8534
9289
|
throw new Error(
|
|
8535
9290
|
`Custom global "${key}" contains dangerous key "${prop}" at ${path2.join(".") || "root"}. Keys like "__proto__", "constructor", and "prototype" are not allowed.`
|
|
8536
9291
|
);
|
|
8537
9292
|
}
|
|
8538
9293
|
const propValue = obj[prop];
|
|
8539
|
-
validateGlobalValue(
|
|
9294
|
+
validateGlobalValue(
|
|
9295
|
+
key,
|
|
9296
|
+
propValue,
|
|
9297
|
+
options,
|
|
9298
|
+
[...path2, typeof prop === "string" ? prop : `[${String(prop)}]`],
|
|
9299
|
+
visited,
|
|
9300
|
+
collectionVisited,
|
|
9301
|
+
inCollection || isArray
|
|
9302
|
+
);
|
|
8540
9303
|
}
|
|
8541
9304
|
return;
|
|
8542
9305
|
}
|
|
@@ -10430,6 +11193,8 @@ function createScoringGate(config) {
|
|
|
10430
11193
|
}
|
|
10431
11194
|
|
|
10432
11195
|
// libs/core/src/enclave.ts
|
|
11196
|
+
init_global_function_gate();
|
|
11197
|
+
init_stack_trace();
|
|
10433
11198
|
var DEFAULT_SECURITY_LEVEL = "STANDARD";
|
|
10434
11199
|
var DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
10435
11200
|
function getConfigFromSecurityLevel(securityLevel, options) {
|
|
@@ -10484,6 +11249,7 @@ var Enclave = class {
|
|
|
10484
11249
|
scoringGate;
|
|
10485
11250
|
doubleVmConfig;
|
|
10486
11251
|
customGlobalNames;
|
|
11252
|
+
toolNamespaces;
|
|
10487
11253
|
adapter;
|
|
10488
11254
|
constructor(options = {}) {
|
|
10489
11255
|
this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
|
|
@@ -10517,7 +11283,7 @@ var Enclave = class {
|
|
|
10517
11283
|
};
|
|
10518
11284
|
const presetName = options.preset ?? "agentscript";
|
|
10519
11285
|
if (presetName === "babel") {
|
|
10520
|
-
const babelConfig = (0,
|
|
11286
|
+
const babelConfig = (0, import_ast4.getBabelConfig)(this.securityLevel);
|
|
10521
11287
|
const restrictedBabel = createRestrictedBabel({
|
|
10522
11288
|
maxInputSize: babelConfig.maxInputSize,
|
|
10523
11289
|
maxOutputSize: babelConfig.maxOutputSize,
|
|
@@ -10539,6 +11305,12 @@ var Enclave = class {
|
|
|
10539
11305
|
}
|
|
10540
11306
|
};
|
|
10541
11307
|
}
|
|
11308
|
+
this.toolNamespaces = (0, import_ast6.normalizeToolNamespaces)(options.toolNamespaces, {
|
|
11309
|
+
reservedNames: Object.keys(initialGlobals)
|
|
11310
|
+
});
|
|
11311
|
+
if (options.maxGlobalFunctionCalls !== void 0 && !(Number.isInteger(options.maxGlobalFunctionCalls) && options.maxGlobalFunctionCalls >= 0)) {
|
|
11312
|
+
throw new TypeError("maxGlobalFunctionCalls must be a non-negative integer");
|
|
11313
|
+
}
|
|
10542
11314
|
this.config = {
|
|
10543
11315
|
...BASE_CONFIG,
|
|
10544
11316
|
timeout: securityConfig.timeout,
|
|
@@ -10553,9 +11325,13 @@ var Enclave = class {
|
|
|
10553
11325
|
toolBridge: normalizedToolBridge,
|
|
10554
11326
|
// secureProxyConfig must come AFTER options spread to use the merged config
|
|
10555
11327
|
secureProxyConfig: securityConfig.secureProxyConfig,
|
|
10556
|
-
globals: initialGlobals
|
|
11328
|
+
globals: initialGlobals,
|
|
11329
|
+
maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls({
|
|
11330
|
+
maxToolCalls: securityConfig.maxToolCalls,
|
|
11331
|
+
maxGlobalFunctionCalls: options.maxGlobalFunctionCalls
|
|
11332
|
+
})
|
|
10557
11333
|
};
|
|
10558
|
-
this.customGlobalNames = Object.keys(initialGlobals);
|
|
11334
|
+
this.customGlobalNames = [...Object.keys(initialGlobals), ...this.toolNamespaces.map((ns) => ns.name)];
|
|
10559
11335
|
const customAllowedGlobals = this.customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
|
|
10560
11336
|
this.validator = this.createValidator(presetName, customAllowedGlobals);
|
|
10561
11337
|
this.validateCode = options.validate !== false;
|
|
@@ -10599,11 +11375,31 @@ var Enclave = class {
|
|
|
10599
11375
|
/**
|
|
10600
11376
|
* Execute AgentScript code
|
|
10601
11377
|
*
|
|
11378
|
+
* Every error returned obeys `sanitizeStackTraces`, whichever stage raised it.
|
|
11379
|
+
*
|
|
10602
11380
|
* @param code AgentScript code to execute
|
|
10603
11381
|
* @param toolHandler Optional tool handler (overrides constructor config)
|
|
10604
11382
|
* @returns Execution result
|
|
10605
11383
|
*/
|
|
10606
11384
|
async run(code, toolHandler) {
|
|
11385
|
+
const result = await this.execute(code, toolHandler);
|
|
11386
|
+
return this.applyStackTracePolicy(result);
|
|
11387
|
+
}
|
|
11388
|
+
/**
|
|
11389
|
+
* Single exit for returned errors: with `sanitizeStackTraces` on, strip host paths, file
|
|
11390
|
+
* locations and frames from the stack, whichever stage (validation, transform, compile,
|
|
11391
|
+
* execution, tool call) and adapter produced the error.
|
|
11392
|
+
*/
|
|
11393
|
+
applyStackTracePolicy(result) {
|
|
11394
|
+
if (result.success || !result.error?.stack || !this.config.sanitizeStackTraces) {
|
|
11395
|
+
return result;
|
|
11396
|
+
}
|
|
11397
|
+
return { ...result, error: { ...result.error, stack: sanitizeStackTrace(result.error.stack, true) } };
|
|
11398
|
+
}
|
|
11399
|
+
/**
|
|
11400
|
+
* Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
|
|
11401
|
+
*/
|
|
11402
|
+
async execute(code, toolHandler) {
|
|
10607
11403
|
const startTime = Date.now();
|
|
10608
11404
|
const stats = {
|
|
10609
11405
|
duration: 0,
|
|
@@ -10616,8 +11412,8 @@ var Enclave = class {
|
|
|
10616
11412
|
try {
|
|
10617
11413
|
let transformedCode = code;
|
|
10618
11414
|
if (this.transformCode) {
|
|
10619
|
-
const needsWrapping = !(0,
|
|
10620
|
-
transformedCode = (0,
|
|
11415
|
+
const needsWrapping = !(0, import_ast5.isWrappedInMain)(code);
|
|
11416
|
+
transformedCode = (0, import_ast5.transformAgentScript)(code, {
|
|
10621
11417
|
wrapInMain: needsWrapping,
|
|
10622
11418
|
transformCallTool: true,
|
|
10623
11419
|
transformLoops: true,
|
|
@@ -10688,7 +11484,8 @@ ${errorMessages}`,
|
|
|
10688
11484
|
toolHandler: toolHandler || this.config.toolHandler,
|
|
10689
11485
|
sidecar,
|
|
10690
11486
|
referenceConfig: this.referenceConfig,
|
|
10691
|
-
secureProxyConfig: this.config.secureProxyConfig
|
|
11487
|
+
secureProxyConfig: this.config.secureProxyConfig,
|
|
11488
|
+
toolNamespaces: this.toolNamespaces
|
|
10692
11489
|
};
|
|
10693
11490
|
const timeoutId = setTimeout(() => {
|
|
10694
11491
|
context.aborted = true;
|
|
@@ -10760,7 +11557,7 @@ ${errorMessages}`,
|
|
|
10760
11557
|
const throwOnBlocked = proxyConfig.throwOnBlocked ?? true;
|
|
10761
11558
|
const parseModule = (source) => acorn2.parse(source, { ecmaVersion: "latest", sourceType: "module" });
|
|
10762
11559
|
const ast = parseModule(code);
|
|
10763
|
-
const { guardedCount } = (0,
|
|
11560
|
+
const { guardedCount } = (0, import_ast6.guardComputedMemberKeys)(ast, parseModule, { blockedKeys, throwOnBlocked });
|
|
10764
11561
|
if (guardedCount === 0) {
|
|
10765
11562
|
return code;
|
|
10766
11563
|
}
|
|
@@ -10771,8 +11568,8 @@ ${errorMessages}`,
|
|
|
10771
11568
|
ecmaVersion: "latest",
|
|
10772
11569
|
sourceType: "module"
|
|
10773
11570
|
});
|
|
10774
|
-
(0,
|
|
10775
|
-
(0,
|
|
11571
|
+
(0, import_ast6.transformConcatenation)(ast);
|
|
11572
|
+
(0, import_ast6.transformTemplateLiterals)(ast);
|
|
10776
11573
|
return (0, import_astring.generate)(ast);
|
|
10777
11574
|
}
|
|
10778
11575
|
/**
|
|
@@ -10790,15 +11587,15 @@ ${errorMessages}`,
|
|
|
10790
11587
|
sourceType: "module"
|
|
10791
11588
|
});
|
|
10792
11589
|
if (this.referenceConfig?.extractionThreshold) {
|
|
10793
|
-
(0,
|
|
11590
|
+
(0, import_ast6.extractLargeStrings)(ast, {
|
|
10794
11591
|
threshold: this.referenceConfig.extractionThreshold,
|
|
10795
11592
|
onExtract: (value) => {
|
|
10796
11593
|
return sidecar.store(value, "extraction");
|
|
10797
11594
|
}
|
|
10798
11595
|
});
|
|
10799
11596
|
}
|
|
10800
|
-
(0,
|
|
10801
|
-
(0,
|
|
11597
|
+
(0, import_ast6.transformConcatenation)(ast);
|
|
11598
|
+
(0, import_ast6.transformTemplateLiterals)(ast);
|
|
10802
11599
|
return (0, import_astring.generate)(ast);
|
|
10803
11600
|
}
|
|
10804
11601
|
/**
|
|
@@ -10877,7 +11674,7 @@ ${errorMessages}`,
|
|
|
10877
11674
|
* @returns A configured JSAstValidator
|
|
10878
11675
|
*/
|
|
10879
11676
|
createValidator(presetName, customAllowedGlobals) {
|
|
10880
|
-
const securityLevelGlobals = (0,
|
|
11677
|
+
const securityLevelGlobals = (0, import_ast4.getAgentScriptGlobals)(this.securityLevel);
|
|
10881
11678
|
const enclaveSpecificGlobals = [
|
|
10882
11679
|
"parallel",
|
|
10883
11680
|
// Parallel execution API
|
|
@@ -10891,24 +11688,24 @@ ${errorMessages}`,
|
|
|
10891
11688
|
const allAllowedGlobals = [...securityLevelGlobals, ...enclaveSpecificGlobals, ...customAllowedGlobals];
|
|
10892
11689
|
switch (presetName) {
|
|
10893
11690
|
case "agentscript":
|
|
10894
|
-
return new
|
|
10895
|
-
(0,
|
|
11691
|
+
return new import_ast4.JSAstValidator(
|
|
11692
|
+
(0, import_ast4.createAgentScriptPreset)({
|
|
10896
11693
|
securityLevel: this.securityLevel,
|
|
10897
11694
|
allowedGlobals: allAllowedGlobals,
|
|
10898
11695
|
allowDynamicArrayFill: this.config.memoryLimit > 0
|
|
10899
11696
|
})
|
|
10900
11697
|
);
|
|
10901
11698
|
case "strict":
|
|
10902
|
-
return new
|
|
11699
|
+
return new import_ast4.JSAstValidator((0, import_ast4.createStrictPreset)());
|
|
10903
11700
|
case "secure":
|
|
10904
|
-
return new
|
|
11701
|
+
return new import_ast4.JSAstValidator((0, import_ast4.createSecurePreset)());
|
|
10905
11702
|
case "standard":
|
|
10906
|
-
return new
|
|
11703
|
+
return new import_ast4.JSAstValidator((0, import_ast4.createStandardPreset)());
|
|
10907
11704
|
case "permissive":
|
|
10908
|
-
return new
|
|
11705
|
+
return new import_ast4.JSAstValidator((0, import_ast4.createPermissivePreset)());
|
|
10909
11706
|
case "babel":
|
|
10910
|
-
return new
|
|
10911
|
-
(0,
|
|
11707
|
+
return new import_ast4.JSAstValidator(
|
|
11708
|
+
(0, import_ast4.createBabelPreset)({
|
|
10912
11709
|
securityLevel: this.securityLevel,
|
|
10913
11710
|
allowedGlobals: allAllowedGlobals,
|
|
10914
11711
|
allowDynamicArrayFill: this.config.memoryLimit > 0
|
|
@@ -11566,6 +12363,7 @@ function applyBinary(op, l, r) {
|
|
|
11566
12363
|
}
|
|
11567
12364
|
|
|
11568
12365
|
// libs/core/src/adapters/interpreter-adapter.ts
|
|
12366
|
+
init_stack_trace();
|
|
11569
12367
|
var SAFE_GLOBALS = Object.freeze({ Math, JSON });
|
|
11570
12368
|
var DEFAULT_MAX_STEPS = 5e6;
|
|
11571
12369
|
var DEFAULT_MAX_CALL_DEPTH = 256;
|
|
@@ -11576,6 +12374,7 @@ var InterpreterAdapter = class {
|
|
|
11576
12374
|
async execute(code, context) {
|
|
11577
12375
|
const startTime = Date.now();
|
|
11578
12376
|
let toolCallCount = 0;
|
|
12377
|
+
const sanitizeStacks = context.config.sanitizeStackTraces === true;
|
|
11579
12378
|
const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
|
|
11580
12379
|
const toolHandler = context.toolHandler ?? context.config.toolHandler;
|
|
11581
12380
|
const __safe_callTool = async (name, args) => {
|
|
@@ -11592,7 +12391,7 @@ var InterpreterAdapter = class {
|
|
|
11592
12391
|
try {
|
|
11593
12392
|
program = acorn3.parse(code, { ecmaVersion: "latest", sourceType: "script" });
|
|
11594
12393
|
} catch (error) {
|
|
11595
|
-
return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
|
|
12394
|
+
return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
|
|
11596
12395
|
}
|
|
11597
12396
|
const timeout = context.config.timeout;
|
|
11598
12397
|
const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
|
|
@@ -11617,6 +12416,7 @@ var InterpreterAdapter = class {
|
|
|
11617
12416
|
startTime,
|
|
11618
12417
|
toolCallCount,
|
|
11619
12418
|
interpreter.stepCount,
|
|
12419
|
+
sanitizeStacks,
|
|
11620
12420
|
"TimeoutError",
|
|
11621
12421
|
"EXECUTION_TIMEOUT"
|
|
11622
12422
|
);
|
|
@@ -11628,7 +12428,7 @@ var InterpreterAdapter = class {
|
|
|
11628
12428
|
};
|
|
11629
12429
|
} catch (error) {
|
|
11630
12430
|
const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
|
|
11631
|
-
return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
|
|
12431
|
+
return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
|
|
11632
12432
|
} finally {
|
|
11633
12433
|
if (timer) clearTimeout(timer);
|
|
11634
12434
|
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
@@ -11640,12 +12440,13 @@ var InterpreterAdapter = class {
|
|
|
11640
12440
|
const endTime = Date.now();
|
|
11641
12441
|
return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
|
|
11642
12442
|
}
|
|
11643
|
-
fail(error, startTime, toolCallCount, iterationCount, name, code) {
|
|
12443
|
+
fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
|
|
11644
12444
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
12445
|
+
const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
|
|
11645
12446
|
const execError = {
|
|
11646
12447
|
message: err.message,
|
|
11647
12448
|
name: name ?? err.name,
|
|
11648
|
-
...
|
|
12449
|
+
...stack ? { stack } : {},
|
|
11649
12450
|
...code ? { code } : {}
|
|
11650
12451
|
};
|
|
11651
12452
|
return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
|