@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/esm/index.mjs
CHANGED
|
@@ -9,9 +9,17 @@ var __export = (target, all) => {
|
|
|
9
9
|
};
|
|
10
10
|
|
|
11
11
|
// libs/core/src/safe-error.ts
|
|
12
|
-
function createSafeError(message, name = "Error") {
|
|
12
|
+
function createSafeError(message, name = "Error", code) {
|
|
13
13
|
const error = new Error(message);
|
|
14
14
|
error.name = name;
|
|
15
|
+
if (typeof code === "string") {
|
|
16
|
+
Object.defineProperty(error, "code", {
|
|
17
|
+
value: code,
|
|
18
|
+
writable: false,
|
|
19
|
+
enumerable: false,
|
|
20
|
+
configurable: false
|
|
21
|
+
});
|
|
22
|
+
}
|
|
15
23
|
const SafeConstructor = /* @__PURE__ */ Object.create(null);
|
|
16
24
|
Object.defineProperties(SafeConstructor, {
|
|
17
25
|
constructor: {
|
|
@@ -154,6 +162,14 @@ function createSafeReflect(securityLevel) {
|
|
|
154
162
|
}
|
|
155
163
|
});
|
|
156
164
|
}
|
|
165
|
+
function gatedProxyCache(gate) {
|
|
166
|
+
let cache = gatedProxyCaches.get(gate);
|
|
167
|
+
if (!cache) {
|
|
168
|
+
cache = /* @__PURE__ */ new WeakMap();
|
|
169
|
+
gatedProxyCaches.set(gate, cache);
|
|
170
|
+
}
|
|
171
|
+
return cache;
|
|
172
|
+
}
|
|
157
173
|
function getFullCacheKey(options) {
|
|
158
174
|
const parts = [];
|
|
159
175
|
if (options.levelConfig) {
|
|
@@ -179,7 +195,7 @@ function getFullCacheKey(options) {
|
|
|
179
195
|
function isProxyable(value) {
|
|
180
196
|
if (value === null) return false;
|
|
181
197
|
if (typeof value !== "object" && typeof value !== "function") return false;
|
|
182
|
-
const tag =
|
|
198
|
+
const tag = ReflectApply2(ObjectToString, value, []);
|
|
183
199
|
if (NON_PROXYABLE_TYPES.has(tag)) {
|
|
184
200
|
return false;
|
|
185
201
|
}
|
|
@@ -190,12 +206,11 @@ function createSecureProxy(target, options = {}) {
|
|
|
190
206
|
return target;
|
|
191
207
|
}
|
|
192
208
|
const cacheKey = getFullCacheKey(options);
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
}
|
|
209
|
+
const gateCache = options.callGate ? gatedProxyCache(options.callGate) : void 0;
|
|
210
|
+
const lookupCached = (obj) => gateCache ? gateCache.get(obj) : proxyCache.get(obj)?.get(cacheKey);
|
|
211
|
+
const cached = lookupCached(target);
|
|
212
|
+
if (cached) {
|
|
213
|
+
return cached;
|
|
199
214
|
}
|
|
200
215
|
const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
|
|
201
216
|
const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
|
|
@@ -206,12 +221,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
206
221
|
if (!isProxyable(obj)) {
|
|
207
222
|
return obj;
|
|
208
223
|
}
|
|
209
|
-
const
|
|
210
|
-
if (
|
|
211
|
-
|
|
212
|
-
if (cachedProxy) {
|
|
213
|
-
return cachedProxy;
|
|
214
|
-
}
|
|
224
|
+
const cachedProxy = lookupCached(obj);
|
|
225
|
+
if (cachedProxy) {
|
|
226
|
+
return cachedProxy;
|
|
215
227
|
}
|
|
216
228
|
if (depth > maxDepth) {
|
|
217
229
|
throw createSafeError(
|
|
@@ -259,9 +271,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
259
271
|
}
|
|
260
272
|
const value = ReflectGet(target2, property, receiver);
|
|
261
273
|
if (typeof value === "function") {
|
|
262
|
-
const tag =
|
|
274
|
+
const tag = ReflectApply2(ObjectToString, target2, []);
|
|
263
275
|
if (INTERNAL_SLOT_TYPES.has(tag)) {
|
|
264
|
-
const boundMethod =
|
|
276
|
+
const boundMethod = ReflectApply2(FunctionBind, value, [target2]);
|
|
265
277
|
return proxyWithDepth(boundMethod, depth + 1);
|
|
266
278
|
}
|
|
267
279
|
}
|
|
@@ -307,7 +319,7 @@ function createSecureProxy(target, options = {}) {
|
|
|
307
319
|
// Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
|
|
308
320
|
// Must respect proxy invariants: non-configurable own properties cannot be hidden
|
|
309
321
|
ownKeys(target2) {
|
|
310
|
-
const keys =
|
|
322
|
+
const keys = ReflectOwnKeys2(target2);
|
|
311
323
|
return keys.filter((key) => {
|
|
312
324
|
const keyStr = typeof key === "symbol" ? key.toString() : key;
|
|
313
325
|
if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
|
|
@@ -324,7 +336,7 @@ function createSecureProxy(target, options = {}) {
|
|
|
324
336
|
// Must respect proxy invariants: non-configurable properties must return actual descriptor
|
|
325
337
|
getOwnPropertyDescriptor(target2, property) {
|
|
326
338
|
const propName = typeof property === "symbol" ? property.toString() : property;
|
|
327
|
-
const descriptor =
|
|
339
|
+
const descriptor = ReflectGetOwnPropertyDescriptor2(target2, property);
|
|
328
340
|
if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
|
|
329
341
|
const exactValue = descriptor.value;
|
|
330
342
|
if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
|
|
@@ -383,7 +395,10 @@ function createSecureProxy(target, options = {}) {
|
|
|
383
395
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
|
|
384
396
|
apply(target2, thisArg, argArray) {
|
|
385
397
|
const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
|
|
386
|
-
|
|
398
|
+
if (options.callGate && options.callGate.gates(target2)) {
|
|
399
|
+
return options.callGate.call(target2, unwrappedThis, argArray);
|
|
400
|
+
}
|
|
401
|
+
const result = ReflectApply2(target2, unwrappedThis, argArray);
|
|
387
402
|
if (isProxyable(result)) {
|
|
388
403
|
return proxyWithDepth(result, depth + 1);
|
|
389
404
|
}
|
|
@@ -394,6 +409,9 @@ function createSecureProxy(target, options = {}) {
|
|
|
394
409
|
// host Function constructor — the same escape class the apply trap closes for calls.
|
|
395
410
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
|
|
396
411
|
construct(target2, argArray, newTarget) {
|
|
412
|
+
if (options.callGate && options.callGate.gates(target2)) {
|
|
413
|
+
throw createSafeError("Host functions cannot be called with new", "TypeError");
|
|
414
|
+
}
|
|
397
415
|
const instance = ReflectConstruct(target2, argArray, newTarget === proxy ? target2 : newTarget);
|
|
398
416
|
if (isProxyable(instance)) {
|
|
399
417
|
return proxyWithDepth(instance, depth + 1);
|
|
@@ -401,12 +419,16 @@ function createSecureProxy(target, options = {}) {
|
|
|
401
419
|
return instance;
|
|
402
420
|
}
|
|
403
421
|
});
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
proxyCache.
|
|
422
|
+
if (gateCache) {
|
|
423
|
+
gateCache.set(obj, proxy);
|
|
424
|
+
} else {
|
|
425
|
+
let objCacheMap = proxyCache.get(obj);
|
|
426
|
+
if (!objCacheMap) {
|
|
427
|
+
objCacheMap = /* @__PURE__ */ new Map();
|
|
428
|
+
proxyCache.set(obj, objCacheMap);
|
|
429
|
+
}
|
|
430
|
+
objCacheMap.set(cacheKey, proxy);
|
|
408
431
|
}
|
|
409
|
-
objCacheMap.set(cacheKey, proxy);
|
|
410
432
|
proxySet.add(proxy);
|
|
411
433
|
proxyToTarget.set(proxy, obj);
|
|
412
434
|
return proxy;
|
|
@@ -448,7 +470,7 @@ function isSecureProxy(obj) {
|
|
|
448
470
|
}
|
|
449
471
|
return proxySet.has(obj);
|
|
450
472
|
}
|
|
451
|
-
var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty,
|
|
473
|
+
var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor2, ReflectOwnKeys2, ReflectApply2, ReflectConstruct, ReflectObject, PINNED_REFLECT_VALUES, FunctionCtor, AsyncFunctionCtor, GeneratorFunctionCtor, AsyncGeneratorFunctionCtor, MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, gatedProxyCaches, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
|
|
452
474
|
var init_secure_proxy = __esm({
|
|
453
475
|
"libs/core/src/secure-proxy.ts"() {
|
|
454
476
|
"use strict";
|
|
@@ -459,13 +481,13 @@ var init_secure_proxy = __esm({
|
|
|
459
481
|
ReflectGet = Reflect.get;
|
|
460
482
|
ReflectSet = Reflect.set;
|
|
461
483
|
ReflectDefineProperty = Reflect.defineProperty;
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
484
|
+
ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
|
|
485
|
+
ReflectOwnKeys2 = Reflect.ownKeys;
|
|
486
|
+
ReflectApply2 = Reflect.apply;
|
|
465
487
|
ReflectConstruct = Reflect.construct;
|
|
466
488
|
ReflectObject = Reflect;
|
|
467
489
|
PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
|
|
468
|
-
for (const key of
|
|
490
|
+
for (const key of ReflectOwnKeys2(ReflectObject)) {
|
|
469
491
|
PINNED_REFLECT_VALUES.set(key, ReflectGet(ReflectObject, key));
|
|
470
492
|
}
|
|
471
493
|
FunctionCtor = Function;
|
|
@@ -574,6 +596,7 @@ var init_secure_proxy = __esm({
|
|
|
574
596
|
// 'call',
|
|
575
597
|
// 'apply',
|
|
576
598
|
]);
|
|
599
|
+
gatedProxyCaches = /* @__PURE__ */ new WeakMap();
|
|
577
600
|
proxyCache = /* @__PURE__ */ new WeakMap();
|
|
578
601
|
proxySet = /* @__PURE__ */ new WeakSet();
|
|
579
602
|
proxyToTarget = /* @__PURE__ */ new WeakMap();
|
|
@@ -1051,11 +1074,11 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1051
1074
|
return result;
|
|
1052
1075
|
}
|
|
1053
1076
|
if (value instanceof Date) {
|
|
1054
|
-
const time =
|
|
1077
|
+
const time = ReflectApply3(DateProtoGetTime, value, []);
|
|
1055
1078
|
if (allowDates) {
|
|
1056
1079
|
return new Date(time);
|
|
1057
1080
|
}
|
|
1058
|
-
return
|
|
1081
|
+
return ReflectApply3(DateProtoToISOString, value, []);
|
|
1059
1082
|
}
|
|
1060
1083
|
if (value instanceof Error) {
|
|
1061
1084
|
const rawName = ReflectGet3(value, "name");
|
|
@@ -1072,11 +1095,11 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1072
1095
|
return { error: message };
|
|
1073
1096
|
}
|
|
1074
1097
|
if (value instanceof RegExp) {
|
|
1075
|
-
return
|
|
1098
|
+
return ReflectApply3(RegExpProtoToString, value, []);
|
|
1076
1099
|
}
|
|
1077
1100
|
if (value instanceof Map) {
|
|
1078
1101
|
const sanitizedMap = ObjectCreate(null);
|
|
1079
|
-
const entries =
|
|
1102
|
+
const entries = ReflectApply3(MapProtoEntries, value, []);
|
|
1080
1103
|
for (const [key, val] of entries) {
|
|
1081
1104
|
if (typeof key !== "string") continue;
|
|
1082
1105
|
if (DANGEROUS_KEYS.has(key)) continue;
|
|
@@ -1086,7 +1109,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1086
1109
|
return sanitizedMap;
|
|
1087
1110
|
}
|
|
1088
1111
|
if (value instanceof Set) {
|
|
1089
|
-
const iter =
|
|
1112
|
+
const iter = ReflectApply3(SetProtoValues, value, []);
|
|
1090
1113
|
const result = [];
|
|
1091
1114
|
for (const item of iter) {
|
|
1092
1115
|
context.propCount.count++;
|
|
@@ -1245,12 +1268,12 @@ function checkSerializedSize(value, maxBytes) {
|
|
|
1245
1268
|
return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
|
|
1246
1269
|
}
|
|
1247
1270
|
}
|
|
1248
|
-
var DANGEROUS_KEYS,
|
|
1271
|
+
var DANGEROUS_KEYS, ReflectApply3, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
|
|
1249
1272
|
var init_value_sanitizer = __esm({
|
|
1250
1273
|
"libs/core/src/value-sanitizer.ts"() {
|
|
1251
1274
|
"use strict";
|
|
1252
1275
|
DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
|
|
1253
|
-
|
|
1276
|
+
ReflectApply3 = Reflect.apply;
|
|
1254
1277
|
ReflectGet3 = Reflect.get;
|
|
1255
1278
|
ArrayIsArray = Array.isArray;
|
|
1256
1279
|
ObjectKeys = Object.keys;
|
|
@@ -1265,6 +1288,390 @@ var init_value_sanitizer = __esm({
|
|
|
1265
1288
|
}
|
|
1266
1289
|
});
|
|
1267
1290
|
|
|
1291
|
+
// libs/core/src/global-function-gate.ts
|
|
1292
|
+
function isBuiltinMethod(fn) {
|
|
1293
|
+
return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHODS.has(fn);
|
|
1294
|
+
}
|
|
1295
|
+
function resolveMaxGlobalFunctionCalls(config) {
|
|
1296
|
+
const explicit = config.maxGlobalFunctionCalls;
|
|
1297
|
+
if (typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 0) {
|
|
1298
|
+
return Math.floor(explicit);
|
|
1299
|
+
}
|
|
1300
|
+
const maxToolCalls = typeof config.maxToolCalls === "number" && Number.isFinite(config.maxToolCalls) ? config.maxToolCalls : 100;
|
|
1301
|
+
return Math.max(0, Math.floor(maxToolCalls)) * DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL;
|
|
1302
|
+
}
|
|
1303
|
+
function globalFunctionLimitMessage(max) {
|
|
1304
|
+
return `Maximum global function call limit exceeded (${max}). This limit prevents runaway calls into host functions.`;
|
|
1305
|
+
}
|
|
1306
|
+
function resultLimits(context) {
|
|
1307
|
+
const { config } = context;
|
|
1308
|
+
return {
|
|
1309
|
+
maxDepth: config.maxSanitizeDepth,
|
|
1310
|
+
maxProperties: config.maxSanitizeProperties,
|
|
1311
|
+
maxPayloadBytes: config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES
|
|
1312
|
+
};
|
|
1313
|
+
}
|
|
1314
|
+
function truncate(value, max) {
|
|
1315
|
+
return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
|
|
1316
|
+
}
|
|
1317
|
+
function failure(error) {
|
|
1318
|
+
let name = "Error";
|
|
1319
|
+
let message = "Global function call failed";
|
|
1320
|
+
try {
|
|
1321
|
+
if (error && typeof error === "object") {
|
|
1322
|
+
const rawName = error.name;
|
|
1323
|
+
const rawMessage = error.message;
|
|
1324
|
+
if (typeof rawName === "string" && rawName) name = rawName;
|
|
1325
|
+
if (typeof rawMessage === "string" && rawMessage) message = rawMessage;
|
|
1326
|
+
} else if (typeof error === "string" && error) {
|
|
1327
|
+
message = error;
|
|
1328
|
+
}
|
|
1329
|
+
} catch {
|
|
1330
|
+
}
|
|
1331
|
+
return {
|
|
1332
|
+
ok: false,
|
|
1333
|
+
name: truncate(name, MAX_ERROR_NAME_LENGTH),
|
|
1334
|
+
message: truncate(message, MAX_ERROR_MESSAGE_LENGTH)
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
function jsonReplacer(_key, value) {
|
|
1338
|
+
if (typeof value === "bigint") return value.toString();
|
|
1339
|
+
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
1340
|
+
return value;
|
|
1341
|
+
}
|
|
1342
|
+
function utf8ByteLength(value) {
|
|
1343
|
+
return Buffer.byteLength(value, "utf8");
|
|
1344
|
+
}
|
|
1345
|
+
function encodeResult(value, limits) {
|
|
1346
|
+
if (value === void 0) return { ok: true };
|
|
1347
|
+
let json;
|
|
1348
|
+
try {
|
|
1349
|
+
const sanitized = sanitizeValue(value, {
|
|
1350
|
+
maxDepth: limits.maxDepth,
|
|
1351
|
+
maxProperties: limits.maxProperties,
|
|
1352
|
+
allowDates: false,
|
|
1353
|
+
allowErrors: true
|
|
1354
|
+
});
|
|
1355
|
+
json = JsonStringify(sanitized, jsonReplacer);
|
|
1356
|
+
} catch {
|
|
1357
|
+
return { ok: false, name: "GlobalFunctionError", message: UNSAFE_RESULT_MESSAGE };
|
|
1358
|
+
}
|
|
1359
|
+
if (json === void 0) return { ok: true };
|
|
1360
|
+
if (utf8ByteLength(json) > limits.maxPayloadBytes) {
|
|
1361
|
+
return {
|
|
1362
|
+
ok: false,
|
|
1363
|
+
name: "GlobalFunctionError",
|
|
1364
|
+
message: `Global function result exceeds maximum size (${limits.maxPayloadBytes} bytes)`
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
return { ok: true, json };
|
|
1368
|
+
}
|
|
1369
|
+
function isThenable(value) {
|
|
1370
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return false;
|
|
1371
|
+
try {
|
|
1372
|
+
return typeof value.then === "function";
|
|
1373
|
+
} catch {
|
|
1374
|
+
return false;
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
function invokeGlobalFunction(fn, thisArg, args, limits) {
|
|
1378
|
+
if (typeof fn !== "function") {
|
|
1379
|
+
return { ok: false, name: "TypeError", message: "Global is not a function" };
|
|
1380
|
+
}
|
|
1381
|
+
let result;
|
|
1382
|
+
try {
|
|
1383
|
+
result = ReflectApply4(fn, thisArg, ArrayIsArray2(args) ? args : []);
|
|
1384
|
+
} catch (error) {
|
|
1385
|
+
return failure(error);
|
|
1386
|
+
}
|
|
1387
|
+
if (isThenable(result)) {
|
|
1388
|
+
return Promise.resolve(result).then(
|
|
1389
|
+
(value) => encodeResult(value, limits),
|
|
1390
|
+
(error) => failure(error)
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1393
|
+
return encodeResult(result, limits);
|
|
1394
|
+
}
|
|
1395
|
+
function toEnvelope(outcome) {
|
|
1396
|
+
if (outcome.ok) {
|
|
1397
|
+
return outcome.json === void 0 ? '{"v":1,"ok":true}' : `{"v":1,"ok":true,"value":${outcome.json}}`;
|
|
1398
|
+
}
|
|
1399
|
+
return JsonStringify({ v: 1, ok: false, error: { name: outcome.name, message: outcome.message } });
|
|
1400
|
+
}
|
|
1401
|
+
function createHostGlobalFunctionInvoker(context) {
|
|
1402
|
+
const limits = resultLimits(context);
|
|
1403
|
+
return (fn, thisArg, args) => {
|
|
1404
|
+
const outcome = invokeGlobalFunction(fn, thisArg, args, limits);
|
|
1405
|
+
return outcome instanceof Promise ? outcome.then(toEnvelope) : toEnvelope(outcome);
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
function createGlobalFunctionGate(context, realm) {
|
|
1409
|
+
const limits = resultLimits(context);
|
|
1410
|
+
const max = resolveMaxGlobalFunctionCalls(context.config);
|
|
1411
|
+
let calls = 0;
|
|
1412
|
+
const settle = (outcome) => {
|
|
1413
|
+
if (!outcome.ok) {
|
|
1414
|
+
throw createSafeError(outcome.message, outcome.name);
|
|
1415
|
+
}
|
|
1416
|
+
return outcome.json === void 0 ? void 0 : realm.parseJson(outcome.json);
|
|
1417
|
+
};
|
|
1418
|
+
return {
|
|
1419
|
+
gates: (target) => !isBuiltinMethod(target),
|
|
1420
|
+
call: (target, thisArg, args) => {
|
|
1421
|
+
if (context.aborted) {
|
|
1422
|
+
throw createSafeError("Execution aborted");
|
|
1423
|
+
}
|
|
1424
|
+
calls++;
|
|
1425
|
+
if (calls > max) {
|
|
1426
|
+
throw createSafeError(globalFunctionLimitMessage(max));
|
|
1427
|
+
}
|
|
1428
|
+
const outcome = invokeGlobalFunction(target, thisArg, args, limits);
|
|
1429
|
+
if (outcome instanceof Promise) {
|
|
1430
|
+
return realm.adoptPromise(outcome.then(settle));
|
|
1431
|
+
}
|
|
1432
|
+
return settle(outcome);
|
|
1433
|
+
}
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
var ReflectApply4, ReflectOwnKeys3, ObjectGetOwnPropertyDescriptor2, ObjectGetPrototypeOf2, ArrayIsArray2, JsonStringify, BUILTIN_METHODS, DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL, DEFAULT_MAX_PAYLOAD_BYTES, MAX_ERROR_MESSAGE_LENGTH, MAX_ERROR_NAME_LENGTH, UNSAFE_RESULT_MESSAGE;
|
|
1437
|
+
var init_global_function_gate = __esm({
|
|
1438
|
+
"libs/core/src/global-function-gate.ts"() {
|
|
1439
|
+
"use strict";
|
|
1440
|
+
init_value_sanitizer();
|
|
1441
|
+
init_safe_error();
|
|
1442
|
+
ReflectApply4 = Reflect.apply;
|
|
1443
|
+
ReflectOwnKeys3 = Reflect.ownKeys;
|
|
1444
|
+
ObjectGetOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
|
|
1445
|
+
ObjectGetPrototypeOf2 = Object.getPrototypeOf;
|
|
1446
|
+
ArrayIsArray2 = Array.isArray;
|
|
1447
|
+
JsonStringify = JSON.stringify;
|
|
1448
|
+
BUILTIN_METHODS = (() => {
|
|
1449
|
+
const methods = /* @__PURE__ */ new WeakSet();
|
|
1450
|
+
const typedArrays = [
|
|
1451
|
+
Int8Array,
|
|
1452
|
+
Uint8Array,
|
|
1453
|
+
Uint8ClampedArray,
|
|
1454
|
+
Int16Array,
|
|
1455
|
+
Uint16Array,
|
|
1456
|
+
Int32Array,
|
|
1457
|
+
Uint32Array,
|
|
1458
|
+
Float32Array,
|
|
1459
|
+
Float64Array,
|
|
1460
|
+
BigInt64Array,
|
|
1461
|
+
BigUint64Array
|
|
1462
|
+
];
|
|
1463
|
+
const arrayIteratorPrototype = ObjectGetPrototypeOf2([][Symbol.iterator]());
|
|
1464
|
+
const prototypes = [
|
|
1465
|
+
Object.prototype,
|
|
1466
|
+
Array.prototype,
|
|
1467
|
+
String.prototype,
|
|
1468
|
+
Number.prototype,
|
|
1469
|
+
Boolean.prototype,
|
|
1470
|
+
Symbol.prototype,
|
|
1471
|
+
BigInt.prototype,
|
|
1472
|
+
Date.prototype,
|
|
1473
|
+
RegExp.prototype,
|
|
1474
|
+
Error.prototype,
|
|
1475
|
+
EvalError.prototype,
|
|
1476
|
+
RangeError.prototype,
|
|
1477
|
+
ReferenceError.prototype,
|
|
1478
|
+
SyntaxError.prototype,
|
|
1479
|
+
TypeError.prototype,
|
|
1480
|
+
URIError.prototype,
|
|
1481
|
+
Map.prototype,
|
|
1482
|
+
Set.prototype,
|
|
1483
|
+
WeakMap.prototype,
|
|
1484
|
+
WeakSet.prototype,
|
|
1485
|
+
Promise.prototype,
|
|
1486
|
+
ArrayBuffer.prototype,
|
|
1487
|
+
DataView.prototype,
|
|
1488
|
+
ObjectGetPrototypeOf2(Uint8Array.prototype),
|
|
1489
|
+
// %TypedArray%.prototype
|
|
1490
|
+
...typedArrays.map((TypedArray) => TypedArray.prototype),
|
|
1491
|
+
arrayIteratorPrototype,
|
|
1492
|
+
ObjectGetPrototypeOf2(arrayIteratorPrototype),
|
|
1493
|
+
// %IteratorPrototype%
|
|
1494
|
+
ObjectGetPrototypeOf2((/* @__PURE__ */ new Map())[Symbol.iterator]()),
|
|
1495
|
+
ObjectGetPrototypeOf2((/* @__PURE__ */ new Set())[Symbol.iterator]()),
|
|
1496
|
+
ObjectGetPrototypeOf2(""[Symbol.iterator]())
|
|
1497
|
+
];
|
|
1498
|
+
for (const prototype of prototypes) {
|
|
1499
|
+
if (prototype === null || typeof prototype !== "object") continue;
|
|
1500
|
+
for (const key of ReflectOwnKeys3(prototype)) {
|
|
1501
|
+
if (key === "constructor") continue;
|
|
1502
|
+
const descriptor = ObjectGetOwnPropertyDescriptor2(prototype, key);
|
|
1503
|
+
if (descriptor && typeof descriptor.value === "function") {
|
|
1504
|
+
methods.add(descriptor.value);
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
return methods;
|
|
1509
|
+
})();
|
|
1510
|
+
DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
|
|
1511
|
+
DEFAULT_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
1512
|
+
MAX_ERROR_MESSAGE_LENGTH = 4096;
|
|
1513
|
+
MAX_ERROR_NAME_LENGTH = 128;
|
|
1514
|
+
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)";
|
|
1515
|
+
}
|
|
1516
|
+
});
|
|
1517
|
+
|
|
1518
|
+
// libs/core/src/stack-trace.ts
|
|
1519
|
+
function redactLine(line) {
|
|
1520
|
+
let out = line.length > MAX_LINE_LENGTH ? `${line.slice(0, MAX_LINE_LENGTH)}\u2026` : line;
|
|
1521
|
+
for (const pattern of SENSITIVE_STACK_PATTERNS) {
|
|
1522
|
+
pattern.lastIndex = 0;
|
|
1523
|
+
out = out.replace(pattern, "[REDACTED]");
|
|
1524
|
+
}
|
|
1525
|
+
return out;
|
|
1526
|
+
}
|
|
1527
|
+
function sanitizeStackTrace(stack, sanitize = true) {
|
|
1528
|
+
if (typeof stack !== "string" || !stack || !sanitize) return stack;
|
|
1529
|
+
const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
|
|
1530
|
+
return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
|
|
1531
|
+
}
|
|
1532
|
+
var SENSITIVE_STACK_PATTERNS, FRAME_LINE, MAX_STACK_LENGTH, MAX_LINE_LENGTH, REDACTED_FRAME;
|
|
1533
|
+
var init_stack_trace = __esm({
|
|
1534
|
+
"libs/core/src/stack-trace.ts"() {
|
|
1535
|
+
"use strict";
|
|
1536
|
+
SENSITIVE_STACK_PATTERNS = [
|
|
1537
|
+
// Unix file system paths
|
|
1538
|
+
/\/Users\/[^/]+\/[^\s):]*/gi,
|
|
1539
|
+
// macOS home directories
|
|
1540
|
+
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
1541
|
+
// Linux home directories
|
|
1542
|
+
/\/var\/[^\s):]*/gi,
|
|
1543
|
+
// System var directories
|
|
1544
|
+
/\/opt\/[^\s):]*/gi,
|
|
1545
|
+
// Optional software
|
|
1546
|
+
/\/tmp\/[^\s):]*/gi,
|
|
1547
|
+
// Temporary files
|
|
1548
|
+
/\/etc\/[^\s):]*/gi,
|
|
1549
|
+
// System configuration
|
|
1550
|
+
/\/root\/[^\s):]*/gi,
|
|
1551
|
+
// Root home directory
|
|
1552
|
+
/\/mnt\/[^\s):]*/gi,
|
|
1553
|
+
// Mount points
|
|
1554
|
+
/\/srv\/[^\s):]*/gi,
|
|
1555
|
+
// Service data
|
|
1556
|
+
/\/data\/[^\s):]*/gi,
|
|
1557
|
+
// Data directories
|
|
1558
|
+
/\/app\/[^\s):]*/gi,
|
|
1559
|
+
// Application directories
|
|
1560
|
+
/\/proc\/[^\s):]*/gi,
|
|
1561
|
+
// Process information
|
|
1562
|
+
/\/sys\/[^\s):]*/gi,
|
|
1563
|
+
// System files
|
|
1564
|
+
// Windows paths
|
|
1565
|
+
/\\\\[^\s):]*/g,
|
|
1566
|
+
// UNC paths
|
|
1567
|
+
/[A-Z]:\\[^\s):]+/gi,
|
|
1568
|
+
// Windows drive paths
|
|
1569
|
+
// URL-based paths
|
|
1570
|
+
/file:\/\/[^\s):]+/gi,
|
|
1571
|
+
// File URLs
|
|
1572
|
+
/webpack:\/\/[^\s):]+/gi,
|
|
1573
|
+
// Webpack paths
|
|
1574
|
+
/%2F[^\s):]+/gi,
|
|
1575
|
+
// URL-encoded paths
|
|
1576
|
+
// Package managers and node
|
|
1577
|
+
/node_modules\/[^\s):]+/gi,
|
|
1578
|
+
// Node modules paths
|
|
1579
|
+
/\/nix\/store\/[^\s):]*/gi,
|
|
1580
|
+
// Nix store paths
|
|
1581
|
+
/\.npm\/[^\s):]*/gi,
|
|
1582
|
+
// NPM cache
|
|
1583
|
+
/\.yarn\/[^\s):]*/gi,
|
|
1584
|
+
// Yarn cache
|
|
1585
|
+
/\.pnpm\/[^\s):]*/gi,
|
|
1586
|
+
// PNPM cache
|
|
1587
|
+
// Container and orchestration
|
|
1588
|
+
/\/run\/secrets\/[^\s):]*/gi,
|
|
1589
|
+
// Docker/K8s secrets
|
|
1590
|
+
/\/var\/run\/[^\s):]*/gi,
|
|
1591
|
+
// Runtime directories
|
|
1592
|
+
/\/docker\/[^\s):]*/gi,
|
|
1593
|
+
// Docker paths
|
|
1594
|
+
/\/containers\/[^\s):]*/gi,
|
|
1595
|
+
// Container paths
|
|
1596
|
+
/\/kubelet\/[^\s):]*/gi,
|
|
1597
|
+
// Kubernetes kubelet
|
|
1598
|
+
// CI/CD systems
|
|
1599
|
+
/\/github\/workspace\/[^\s):]*/gi,
|
|
1600
|
+
// GitHub Actions
|
|
1601
|
+
/\/runner\/[^\s):]*/gi,
|
|
1602
|
+
// GitHub/GitLab runner
|
|
1603
|
+
/\/builds\/[^\s):]*/gi,
|
|
1604
|
+
// CI builds
|
|
1605
|
+
/\/workspace\/[^\s):]*/gi,
|
|
1606
|
+
// Generic workspace
|
|
1607
|
+
/\/pipeline\/[^\s):]*/gi,
|
|
1608
|
+
// CI pipelines
|
|
1609
|
+
/\/jenkins\/[^\s):]*/gi,
|
|
1610
|
+
// Jenkins
|
|
1611
|
+
/\/bamboo\/[^\s):]*/gi,
|
|
1612
|
+
// Bamboo
|
|
1613
|
+
/\/teamcity\/[^\s):]*/gi,
|
|
1614
|
+
// TeamCity
|
|
1615
|
+
/\/circleci\/[^\s):]*/gi,
|
|
1616
|
+
// CircleCI
|
|
1617
|
+
// Cloud providers
|
|
1618
|
+
/\/aws\/[^\s):]*/gi,
|
|
1619
|
+
// AWS paths
|
|
1620
|
+
/\/gcloud\/[^\s):]*/gi,
|
|
1621
|
+
// Google Cloud
|
|
1622
|
+
/\/azure\/[^\s):]*/gi,
|
|
1623
|
+
// Azure paths
|
|
1624
|
+
/s3:\/\/[^\s):]+/gi,
|
|
1625
|
+
// S3 URIs
|
|
1626
|
+
/gs:\/\/[^\s):]+/gi,
|
|
1627
|
+
// GCS URIs
|
|
1628
|
+
// Secrets and credentials (patterns that might appear in paths or errors)
|
|
1629
|
+
/[A-Z0-9]{20,}/g,
|
|
1630
|
+
// AWS-style access keys (20+ uppercase chars)
|
|
1631
|
+
/sk-[a-zA-Z0-9]{32,}/g,
|
|
1632
|
+
// OpenAI/Stripe-style secret keys
|
|
1633
|
+
/ghp_[a-zA-Z0-9]{36,}/g,
|
|
1634
|
+
// GitHub personal access tokens
|
|
1635
|
+
/gho_[a-zA-Z0-9]{36,}/g,
|
|
1636
|
+
// GitHub OAuth tokens
|
|
1637
|
+
/github_pat_[a-zA-Z0-9_]{22,}/g,
|
|
1638
|
+
// GitHub fine-grained tokens
|
|
1639
|
+
/xox[baprs]-[a-zA-Z0-9-]+/g,
|
|
1640
|
+
// Slack tokens
|
|
1641
|
+
/Bearer\s+[a-zA-Z0-9._-]+/gi,
|
|
1642
|
+
// Bearer tokens
|
|
1643
|
+
/Basic\s+[a-zA-Z0-9+/=]+/gi,
|
|
1644
|
+
// Basic auth
|
|
1645
|
+
// Internal network info
|
|
1646
|
+
/(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
|
|
1647
|
+
// Private IPs
|
|
1648
|
+
/[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
|
|
1649
|
+
// Internal hostnames
|
|
1650
|
+
/localhost:\d+/gi,
|
|
1651
|
+
// Localhost with port
|
|
1652
|
+
/127\.0\.0\.1:\d+/gi,
|
|
1653
|
+
// Loopback with port
|
|
1654
|
+
// User information
|
|
1655
|
+
/\/u\/[^/]+\//gi,
|
|
1656
|
+
// User subdirectories
|
|
1657
|
+
/~[a-z_][a-z0-9_-]*/gi,
|
|
1658
|
+
// Unix user home shorthand
|
|
1659
|
+
// Anything else that is still shaped like a location: an absolute path of two or more
|
|
1660
|
+
// segments, a URL, or a script location such as `agentscript.js:3` / `index.mjs:10:5`.
|
|
1661
|
+
/[a-z][a-z0-9+.-]*:\/\/[^\s)]+/gi,
|
|
1662
|
+
// Other URLs (http://host/bundle.js:1:2)
|
|
1663
|
+
/(?:\/[\w.@%+-]+){2,}\/?/g,
|
|
1664
|
+
// Remaining absolute paths
|
|
1665
|
+
/[\w.@-]+\.(?:[cm]?[jt]sx?|json|node|wasm)(?::\d+){1,2}/gi
|
|
1666
|
+
// file.ext:line[:column]
|
|
1667
|
+
];
|
|
1668
|
+
FRAME_LINE = /^\s*at\s/;
|
|
1669
|
+
MAX_STACK_LENGTH = 16 * 1024;
|
|
1670
|
+
MAX_LINE_LENGTH = 1e3;
|
|
1671
|
+
REDACTED_FRAME = " at [REDACTED]";
|
|
1672
|
+
}
|
|
1673
|
+
});
|
|
1674
|
+
|
|
1268
1675
|
// libs/core/src/memory-tracker.ts
|
|
1269
1676
|
function estimateStringSize2(str) {
|
|
1270
1677
|
return str.length * 2 + 40;
|
|
@@ -1420,16 +1827,16 @@ var init_memory_tracker = __esm({
|
|
|
1420
1827
|
});
|
|
1421
1828
|
|
|
1422
1829
|
// libs/core/src/tool-bridge.ts
|
|
1423
|
-
function
|
|
1830
|
+
function utf8ByteLength2(value) {
|
|
1424
1831
|
return Buffer.byteLength(value, "utf8");
|
|
1425
1832
|
}
|
|
1426
|
-
function
|
|
1833
|
+
function jsonReplacer2(_key, value) {
|
|
1427
1834
|
if (typeof value === "bigint") return value.toString();
|
|
1428
1835
|
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
1429
1836
|
return value;
|
|
1430
1837
|
}
|
|
1431
1838
|
function safeJsonStringify(value) {
|
|
1432
|
-
return JSON.stringify(value,
|
|
1839
|
+
return JSON.stringify(value, jsonReplacer2);
|
|
1433
1840
|
}
|
|
1434
1841
|
function truncateForErrorMessage(value, maxChars) {
|
|
1435
1842
|
if (value.length <= maxChars) return value;
|
|
@@ -1470,7 +1877,7 @@ function serializeResponse(response, maxPayloadBytes) {
|
|
|
1470
1877
|
}
|
|
1471
1878
|
});
|
|
1472
1879
|
}
|
|
1473
|
-
if (
|
|
1880
|
+
if (utf8ByteLength2(json) <= maxPayloadBytes) return json;
|
|
1474
1881
|
const minimal = {
|
|
1475
1882
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1476
1883
|
ok: false,
|
|
@@ -1526,7 +1933,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1526
1933
|
maxPayloadBytes
|
|
1527
1934
|
);
|
|
1528
1935
|
}
|
|
1529
|
-
if (
|
|
1936
|
+
if (utf8ByteLength2(requestJson) > maxPayloadBytes) {
|
|
1530
1937
|
return serializeResponse(
|
|
1531
1938
|
{
|
|
1532
1939
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -1667,7 +2074,7 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1667
2074
|
{
|
|
1668
2075
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1669
2076
|
ok: false,
|
|
1670
|
-
error: safeError
|
|
2077
|
+
error: { ...safeError, toolError: true }
|
|
1671
2078
|
},
|
|
1672
2079
|
maxPayloadBytes
|
|
1673
2080
|
);
|
|
@@ -1691,13 +2098,13 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1691
2098
|
{
|
|
1692
2099
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1693
2100
|
ok: false,
|
|
1694
|
-
error: safeError
|
|
2101
|
+
error: { ...safeError, toolError: true }
|
|
1695
2102
|
},
|
|
1696
2103
|
maxPayloadBytes
|
|
1697
2104
|
);
|
|
1698
2105
|
}
|
|
1699
2106
|
if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
|
|
1700
|
-
const size =
|
|
2107
|
+
const size = utf8ByteLength2(sanitizedResult);
|
|
1701
2108
|
if (size >= referenceConfig.extractionThreshold) {
|
|
1702
2109
|
try {
|
|
1703
2110
|
const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
|
|
@@ -1721,12 +2128,12 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1721
2128
|
{
|
|
1722
2129
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
1723
2130
|
ok: false,
|
|
1724
|
-
error: safeError
|
|
2131
|
+
error: { ...safeError, toolError: true }
|
|
1725
2132
|
},
|
|
1726
2133
|
maxPayloadBytes
|
|
1727
2134
|
);
|
|
1728
2135
|
}
|
|
1729
|
-
if (
|
|
2136
|
+
if (utf8ByteLength2(okJson) > maxPayloadBytes) {
|
|
1730
2137
|
return serializeResponse(
|
|
1731
2138
|
{
|
|
1732
2139
|
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
@@ -1734,7 +2141,8 @@ function createHostToolBridge(executionContext, options) {
|
|
|
1734
2141
|
error: {
|
|
1735
2142
|
name: "ToolBridgeError",
|
|
1736
2143
|
message: `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
1737
|
-
code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
|
|
2144
|
+
code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
|
|
2145
|
+
toolError: true
|
|
1738
2146
|
}
|
|
1739
2147
|
},
|
|
1740
2148
|
maxPayloadBytes
|
|
@@ -1764,6 +2172,64 @@ var init_tool_bridge = __esm({
|
|
|
1764
2172
|
}
|
|
1765
2173
|
});
|
|
1766
2174
|
|
|
2175
|
+
// libs/core/src/tool-namespaces.ts
|
|
2176
|
+
function buildToolNamespaceBindings(install, callTool, namespaces) {
|
|
2177
|
+
if (namespaces.length === 0) return [];
|
|
2178
|
+
if (typeof install !== "function") {
|
|
2179
|
+
throw new Error("Tool namespace factory is not available in the sandbox");
|
|
2180
|
+
}
|
|
2181
|
+
const built = install(
|
|
2182
|
+
callTool,
|
|
2183
|
+
JSON.stringify(namespaces)
|
|
2184
|
+
);
|
|
2185
|
+
return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
|
|
2186
|
+
}
|
|
2187
|
+
var TOOL_NAMESPACE_FACTORY_SOURCE;
|
|
2188
|
+
var init_tool_namespaces = __esm({
|
|
2189
|
+
"libs/core/src/tool-namespaces.ts"() {
|
|
2190
|
+
"use strict";
|
|
2191
|
+
TOOL_NAMESPACE_FACTORY_SOURCE = `
|
|
2192
|
+
(function () {
|
|
2193
|
+
'use strict';
|
|
2194
|
+
var parse = JSON.parse;
|
|
2195
|
+
var freeze = Object.freeze;
|
|
2196
|
+
var isArray = Array.isArray;
|
|
2197
|
+
|
|
2198
|
+
function isSafeKey(key) {
|
|
2199
|
+
return typeof key === 'string' && key.length > 0 &&
|
|
2200
|
+
!(key.charAt(0) === '_' && key.charAt(1) === '_') &&
|
|
2201
|
+
key !== 'constructor' && key !== 'prototype';
|
|
2202
|
+
}
|
|
2203
|
+
|
|
2204
|
+
function bind(callTool, toolName) {
|
|
2205
|
+
return (args, options) => callTool(toolName, args === undefined ? {} : args, options);
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
return function install(callTool, namespacesJson) {
|
|
2209
|
+
var spec = parse(namespacesJson);
|
|
2210
|
+
var namespaces = { __proto__: null };
|
|
2211
|
+
if (isArray(spec)) {
|
|
2212
|
+
for (var i = 0; i < spec.length; i++) {
|
|
2213
|
+
var ns = spec[i];
|
|
2214
|
+
if (!ns || !isSafeKey(ns.name) || !isArray(ns.methods)) continue;
|
|
2215
|
+
var target = { __proto__: null };
|
|
2216
|
+
for (var j = 0; j < ns.methods.length; j++) {
|
|
2217
|
+
var method = ns.methods[j];
|
|
2218
|
+
if (!method || !isSafeKey(method.name) || typeof method.toolName !== 'string') continue;
|
|
2219
|
+
target[method.name] = bind(callTool, method.toolName);
|
|
2220
|
+
}
|
|
2221
|
+
freeze(target);
|
|
2222
|
+
namespaces[ns.name] = target;
|
|
2223
|
+
}
|
|
2224
|
+
}
|
|
2225
|
+
freeze(namespaces);
|
|
2226
|
+
return namespaces;
|
|
2227
|
+
};
|
|
2228
|
+
})()
|
|
2229
|
+
`.trim();
|
|
2230
|
+
}
|
|
2231
|
+
});
|
|
2232
|
+
|
|
1767
2233
|
// libs/core/src/double-vm/parent-vm-bootstrap.ts
|
|
1768
2234
|
function generateSanitizeContextCode(securityLevel) {
|
|
1769
2235
|
const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];
|
|
@@ -1805,7 +2271,9 @@ function generateParentVmBootstrap(options) {
|
|
|
1805
2271
|
blockedProperties,
|
|
1806
2272
|
allowComposites = false,
|
|
1807
2273
|
memoryLimit = 0,
|
|
1808
|
-
throwOnBlocked = true
|
|
2274
|
+
throwOnBlocked = true,
|
|
2275
|
+
maxGlobalFunctionCalls = 1e3,
|
|
2276
|
+
toolNamespaces = []
|
|
1809
2277
|
} = options;
|
|
1810
2278
|
const sanitizeContextCode = generateSanitizeContextCode(securityLevel);
|
|
1811
2279
|
const patternDetectorsCode = generatePatternDetectorsCode(suspiciousPatterns);
|
|
@@ -2241,6 +2709,8 @@ ${stackTraceHardeningCode}
|
|
|
2241
2709
|
const hostReportViolation = __host_reportViolation__;
|
|
2242
2710
|
const hostConfig = __host_config__;
|
|
2243
2711
|
const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
|
|
2712
|
+
const hostInvokeGlobal = typeof __host_invokeGlobal__ === 'function' ? __host_invokeGlobal__ : null;
|
|
2713
|
+
const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
|
|
2244
2714
|
const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
|
|
2245
2715
|
const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
|
|
2246
2716
|
|
|
@@ -2253,6 +2723,8 @@ ${stackTraceHardeningCode}
|
|
|
2253
2723
|
try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }
|
|
2254
2724
|
try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }
|
|
2255
2725
|
try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
|
|
2726
|
+
try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
|
|
2727
|
+
try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
|
|
2256
2728
|
|
|
2257
2729
|
// Policy violation reporter (best-effort; host decides how to handle based on security level)
|
|
2258
2730
|
function __ag_reportViolation(kind) {
|
|
@@ -2422,6 +2894,22 @@ ${stackTraceHardeningCode}
|
|
|
2422
2894
|
// Tool call stats for rate limiting
|
|
2423
2895
|
let toolCallCount = 0;
|
|
2424
2896
|
|
|
2897
|
+
// Calls into host functions passed in globals: counted against their own cap, and their
|
|
2898
|
+
// timestamps share the operation rate limit with tool calls. They are not recorded in
|
|
2899
|
+
// operationHistory, so the tool-call suspicious-sequence detectors only see tool calls.
|
|
2900
|
+
let globalFunctionCallCount = 0;
|
|
2901
|
+
const globalFunctionCallTimes = [];
|
|
2902
|
+
|
|
2903
|
+
// Fail-closed: every call into a host function goes through the gate, except the built-in
|
|
2904
|
+
// prototype methods of host data (Array.prototype.map, iterators, Date methods, ...), which
|
|
2905
|
+
// the get trap binds and records here so data globals keep working as before.
|
|
2906
|
+
const ungatedHostFunctions = new WeakSet();
|
|
2907
|
+
|
|
2908
|
+
// Errors that report a failure of the tool itself (the handler threw, or its result could not
|
|
2909
|
+
// be delivered), as opposed to a refusal by the enclave. callTool(..., { throwOnError: false })
|
|
2910
|
+
// turns only these into { success: false, error } results. Keyed by the safe error thrown.
|
|
2911
|
+
const toolFailures = new WeakMap();
|
|
2912
|
+
|
|
2425
2913
|
// Blocked properties for secure proxy (from security level)
|
|
2426
2914
|
const blockedPropertiesSet = new Set(${JSON.stringify(blockedProperties)});
|
|
2427
2915
|
|
|
@@ -2527,6 +3015,9 @@ ${stackTraceHardeningCode}
|
|
|
2527
3015
|
// Then recursively proxy the bound function to block constructor access
|
|
2528
3016
|
if (typeof value === 'function') {
|
|
2529
3017
|
var boundMethod = __ag_functionBind.call(value, target);
|
|
3018
|
+
if (host && hostIsBuiltinMethod(value)) {
|
|
3019
|
+
ungatedHostFunctions.add(boundMethod);
|
|
3020
|
+
}
|
|
2530
3021
|
return createSecureProxy(boundMethod, depth + 1, host);
|
|
2531
3022
|
}
|
|
2532
3023
|
|
|
@@ -2663,18 +3154,29 @@ ${stackTraceHardeningCode}
|
|
|
2663
3154
|
// (Promise.prototype up to Function) to reach the host Function constructor for RCE.
|
|
2664
3155
|
// Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
|
|
2665
3156
|
// then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
|
|
3157
|
+
//
|
|
3158
|
+
// SECURITY: a call into a HOST function (a custom global, a method read off one, or
|
|
3159
|
+
// call/apply/bind on one) goes through the global-function gate instead: abort check,
|
|
3160
|
+
// maxGlobalFunctionCalls, the shared operation rate limit, and a sanitized, parent-realm
|
|
3161
|
+
// copy of the result. Without it those calls skipped every limit that guards callTool, and
|
|
3162
|
+
// their results arrived unsanitized. Only built-in methods of host data are exempt.
|
|
2666
3163
|
apply: function(target, thisArg, args) {
|
|
3164
|
+
if (host && !ungatedHostFunctions.has(target)) {
|
|
3165
|
+
return callHostFunction(target, thisArg, args);
|
|
3166
|
+
}
|
|
2667
3167
|
return createSecureProxy(__ag_ReflectApply(target, thisArg, args), 0, host);
|
|
2668
|
-
}
|
|
2669
|
-
//
|
|
2670
|
-
//
|
|
3168
|
+
},
|
|
3169
|
+
// Constructing a HOST function would hand back a raw host instance without passing the
|
|
3170
|
+
// gate, so it is refused. Realm-owned values keep NO construct trap (undefined here means
|
|
3171
|
+
// the default behavior): every constructor reachable from sandbox code resolves to an
|
|
2671
3172
|
// inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
|
|
2672
3173
|
// from strings disabled, so a 'new X()' result cannot reach a usable Function
|
|
2673
|
-
// constructor.
|
|
2674
|
-
//
|
|
2675
|
-
//
|
|
2676
|
-
|
|
2677
|
-
|
|
3174
|
+
// constructor. Wrapping construct results would additionally break the proxy invariant
|
|
3175
|
+
// for the frozen (non-extensible) Error objects the harness throws (getPrototypeOf must
|
|
3176
|
+
// not report null for a non-extensible target), masking legitimate errors.
|
|
3177
|
+
construct: host ? function() {
|
|
3178
|
+
throw createSafeError('Host functions cannot be called with new', 'TypeError');
|
|
3179
|
+
} : undefined
|
|
2678
3180
|
});
|
|
2679
3181
|
|
|
2680
3182
|
cache.set(obj, proxy);
|
|
@@ -2686,19 +3188,91 @@ ${stackTraceHardeningCode}
|
|
|
2686
3188
|
}
|
|
2687
3189
|
|
|
2688
3190
|
/**
|
|
2689
|
-
*
|
|
3191
|
+
* Operation rate limit, shared by tool calls and calls into host functions.
|
|
3192
|
+
* Sliding one-second window; entries older than two seconds are dropped.
|
|
2690
3193
|
*/
|
|
2691
|
-
function
|
|
2692
|
-
// Rate limiting check with sliding window cleanup
|
|
2693
|
-
const now = Date.now();
|
|
2694
|
-
// Clean up old entries to prevent unbounded growth (keep only last 2 seconds)
|
|
3194
|
+
function enforceRateLimit(now) {
|
|
2695
3195
|
while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
|
|
2696
3196
|
operationHistory.shift();
|
|
2697
3197
|
}
|
|
2698
|
-
|
|
2699
|
-
|
|
3198
|
+
while (globalFunctionCallTimes.length > 0 && now - globalFunctionCallTimes[0] > 2000) {
|
|
3199
|
+
globalFunctionCallTimes.shift();
|
|
3200
|
+
}
|
|
3201
|
+
var recent = 0;
|
|
3202
|
+
for (var r = 0; r < operationHistory.length; r++) {
|
|
3203
|
+
if (now - operationHistory[r].timestamp < 1000) recent++;
|
|
3204
|
+
}
|
|
3205
|
+
for (var g = 0; g < globalFunctionCallTimes.length; g++) {
|
|
3206
|
+
if (now - globalFunctionCallTimes[g] < 1000) recent++;
|
|
3207
|
+
}
|
|
3208
|
+
if (recent >= validationConfig.maxOperationsPerSecond) {
|
|
2700
3209
|
throw createSafeError('Operation rate limit exceeded (' + validationConfig.maxOperationsPerSecond + ' operations/second)');
|
|
2701
3210
|
}
|
|
3211
|
+
}
|
|
3212
|
+
|
|
3213
|
+
/**
|
|
3214
|
+
* Parse the host invoker's JSON envelope into a parent-realm value, or throw its error.
|
|
3215
|
+
*/
|
|
3216
|
+
function decodeGlobalFunctionResult(envelopeJson) {
|
|
3217
|
+
if (typeof envelopeJson !== 'string') {
|
|
3218
|
+
throw createSafeError('Global function bridge returned an invalid response');
|
|
3219
|
+
}
|
|
3220
|
+
var envelope;
|
|
3221
|
+
try {
|
|
3222
|
+
envelope = JSON.parse(envelopeJson);
|
|
3223
|
+
} catch (e) {
|
|
3224
|
+
throw createSafeError('Global function bridge returned invalid JSON');
|
|
3225
|
+
}
|
|
3226
|
+
if (!envelope || typeof envelope !== 'object' || envelope.v !== 1) {
|
|
3227
|
+
throw createSafeError('Global function bridge returned an invalid response');
|
|
3228
|
+
}
|
|
3229
|
+
if (envelope.ok === true) {
|
|
3230
|
+
return __ag_hasOwnProperty.call(envelope, 'value') ? envelope.value : undefined;
|
|
3231
|
+
}
|
|
3232
|
+
var failure = envelope.error;
|
|
3233
|
+
var message = (failure && typeof failure.message === 'string') ? failure.message : 'Global function call failed';
|
|
3234
|
+
var name = (failure && typeof failure.name === 'string') ? failure.name : 'Error';
|
|
3235
|
+
throw createSafeError(message, name);
|
|
3236
|
+
}
|
|
3237
|
+
|
|
3238
|
+
/**
|
|
3239
|
+
* The global-function gate: every call from the sandbox into a host function passed in
|
|
3240
|
+
* globals (including functions nested in objects) comes through here.
|
|
3241
|
+
*/
|
|
3242
|
+
function callHostFunction(target, thisArg, args) {
|
|
3243
|
+
if (hostAbortCheck()) {
|
|
3244
|
+
throw createSafeError('Execution aborted');
|
|
3245
|
+
}
|
|
3246
|
+
if (typeof hostInvokeGlobal !== 'function') {
|
|
3247
|
+
throw createSafeError('Global function bridge is not available');
|
|
3248
|
+
}
|
|
3249
|
+
|
|
3250
|
+
globalFunctionCallCount++;
|
|
3251
|
+
if (globalFunctionCallCount > ${maxGlobalFunctionCalls}) {
|
|
3252
|
+
throw createSafeError(${JSON.stringify(globalFunctionLimitMessage(maxGlobalFunctionCalls))});
|
|
3253
|
+
}
|
|
3254
|
+
|
|
3255
|
+
var now = Date.now();
|
|
3256
|
+
enforceRateLimit(now);
|
|
3257
|
+
globalFunctionCallTimes.push(now);
|
|
3258
|
+
|
|
3259
|
+
var outcome = hostInvokeGlobal(target, thisArg, args);
|
|
3260
|
+
if (typeof outcome === 'string') {
|
|
3261
|
+
return createSecureProxy(decodeGlobalFunctionResult(outcome));
|
|
3262
|
+
}
|
|
3263
|
+
|
|
3264
|
+
// A host function that returned a thenable: settle to a sanitized parent-realm value.
|
|
3265
|
+
return createSecureProxy(outcome.then(decodeGlobalFunctionResult).then(function(value) {
|
|
3266
|
+
return createSecureProxy(value);
|
|
3267
|
+
}));
|
|
3268
|
+
}
|
|
3269
|
+
|
|
3270
|
+
/**
|
|
3271
|
+
* Validate an operation before forwarding to host
|
|
3272
|
+
*/
|
|
3273
|
+
function validateOperation(operationName, args) {
|
|
3274
|
+
// Rate limiting check with sliding window cleanup
|
|
3275
|
+
enforceRateLimit(Date.now());
|
|
2702
3276
|
|
|
2703
3277
|
// Operation name format validation
|
|
2704
3278
|
if (typeof operationName !== 'string' || !operationName) {
|
|
@@ -2740,11 +3314,64 @@ ${stackTraceHardeningCode}
|
|
|
2740
3314
|
}
|
|
2741
3315
|
}
|
|
2742
3316
|
|
|
3317
|
+
/**
|
|
3318
|
+
* Read a script's callTool options. Only { throwOnError: false } changes behavior.
|
|
3319
|
+
*/
|
|
3320
|
+
function readThrowOnError(options) {
|
|
3321
|
+
if (options === undefined || options === null) return true;
|
|
3322
|
+
if (typeof options !== 'object') {
|
|
3323
|
+
throw createSafeError('callTool options must be an object', 'TypeError');
|
|
3324
|
+
}
|
|
3325
|
+
return options.throwOnError !== false;
|
|
3326
|
+
}
|
|
3327
|
+
|
|
3328
|
+
/**
|
|
3329
|
+
* Remember that a safe error reports a failure of the tool itself (see toolFailures).
|
|
3330
|
+
*/
|
|
3331
|
+
function markToolFailure(error, toolName, name, message, code) {
|
|
3332
|
+
var info = { name: name, message: message, toolName: toolName };
|
|
3333
|
+
if (typeof code === 'string') info.code = code;
|
|
3334
|
+
toolFailures.set(error, info);
|
|
3335
|
+
return error;
|
|
3336
|
+
}
|
|
3337
|
+
|
|
3338
|
+
/**
|
|
3339
|
+
* Whether a tool bridge payload is larger than the limit in UTF-8 bytes, as the host counts it.
|
|
3340
|
+
* A code unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
|
|
3341
|
+
*/
|
|
3342
|
+
function exceedsPayloadLimit(str, maxBytes) {
|
|
3343
|
+
if (str.length > maxBytes) return true;
|
|
3344
|
+
if (str.length * 3 <= maxBytes) return false;
|
|
3345
|
+
var bytes = 0;
|
|
3346
|
+
for (var i = 0; i < str.length; i++) {
|
|
3347
|
+
var c = str.charCodeAt(i);
|
|
3348
|
+
if (c < 0x80) bytes += 1;
|
|
3349
|
+
else if (c < 0x800) bytes += 2;
|
|
3350
|
+
else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
|
|
3351
|
+
var d = str.charCodeAt(i + 1);
|
|
3352
|
+
if (d >= 0xdc00 && d <= 0xdfff) {
|
|
3353
|
+
bytes += 4;
|
|
3354
|
+
i++;
|
|
3355
|
+
} else {
|
|
3356
|
+
bytes += 3;
|
|
3357
|
+
}
|
|
3358
|
+
} else bytes += 3;
|
|
3359
|
+
if (bytes > maxBytes) return true;
|
|
3360
|
+
}
|
|
3361
|
+
return false;
|
|
3362
|
+
}
|
|
3363
|
+
|
|
2743
3364
|
/**
|
|
2744
3365
|
* Inner VM's callTool function
|
|
2745
3366
|
* Proxies through parent VM with validation
|
|
3367
|
+
*
|
|
3368
|
+
* options.throwOnError === false: a failing tool resolves to { success: false, error } and a
|
|
3369
|
+
* working one to { success: true, data }. Refusals by the enclave (abort, tool-call cap, rate
|
|
3370
|
+
* limit, operation-name and suspicious-sequence checks, invalid arguments) still throw.
|
|
2746
3371
|
*/
|
|
2747
|
-
function innerCallTool(toolName, args) {
|
|
3372
|
+
function innerCallTool(toolName, args, options) {
|
|
3373
|
+
var throwOnError = readThrowOnError(options);
|
|
3374
|
+
|
|
2748
3375
|
// Check if aborted
|
|
2749
3376
|
if (hostAbortCheck()) {
|
|
2750
3377
|
throw createSafeError('Execution aborted');
|
|
@@ -2793,8 +3420,8 @@ ${stackTraceHardeningCode}
|
|
|
2793
3420
|
throw createSafeError('Tool request must be JSON-serializable');
|
|
2794
3421
|
}
|
|
2795
3422
|
|
|
2796
|
-
//
|
|
2797
|
-
if (requestJson && (requestJson
|
|
3423
|
+
// Counted in UTF-8 bytes, as the host counts it, so both sides agree on the limit.
|
|
3424
|
+
if (requestJson && exceedsPayloadLimit(requestJson, toolBridgeMaxPayloadBytes)) {
|
|
2798
3425
|
throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
|
|
2799
3426
|
}
|
|
2800
3427
|
|
|
@@ -2803,8 +3430,17 @@ ${stackTraceHardeningCode}
|
|
|
2803
3430
|
throw createSafeError('Tool bridge returned non-string response');
|
|
2804
3431
|
}
|
|
2805
3432
|
|
|
2806
|
-
|
|
2807
|
-
|
|
3433
|
+
// The host refuses an oversized response as a tool failure; this check only backs it up,
|
|
3434
|
+
// and reports the same way so { throwOnError: false } resolves it to a result.
|
|
3435
|
+
if (exceedsPayloadLimit(responseJson, toolBridgeMaxPayloadBytes)) {
|
|
3436
|
+
var tooLarge = 'Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)';
|
|
3437
|
+
throw markToolFailure(
|
|
3438
|
+
createSafeError(tooLarge, 'RangeError'),
|
|
3439
|
+
toolName,
|
|
3440
|
+
'RangeError',
|
|
3441
|
+
tooLarge,
|
|
3442
|
+
'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
|
|
3443
|
+
);
|
|
2808
3444
|
}
|
|
2809
3445
|
|
|
2810
3446
|
var response;
|
|
@@ -2833,13 +3469,36 @@ ${stackTraceHardeningCode}
|
|
|
2833
3469
|
var err = response.error;
|
|
2834
3470
|
var msg = (err && typeof err.message === 'string') ? err.message : 'Tool call failed';
|
|
2835
3471
|
var name = (err && typeof err.name === 'string') ? err.name : 'Error';
|
|
2836
|
-
|
|
3472
|
+
var failure = createSafeError(msg, name);
|
|
3473
|
+
if (err && err.toolError === true) {
|
|
3474
|
+
markToolFailure(failure, toolName, name, msg, err.code);
|
|
3475
|
+
}
|
|
3476
|
+
throw failure;
|
|
2837
3477
|
}
|
|
2838
3478
|
|
|
2839
3479
|
throw createSafeError('Tool bridge returned invalid response');
|
|
2840
3480
|
});
|
|
2841
3481
|
} else {
|
|
2842
|
-
promise = hostCallTool(toolName, sanitizedArgs)
|
|
3482
|
+
promise = hostCallTool(toolName, sanitizedArgs).then(undefined, function(error) {
|
|
3483
|
+
// Direct mode: the host marks failures of the tool itself with this code.
|
|
3484
|
+
if (error && error.code === 'TOOL_CALL_FAILED') {
|
|
3485
|
+
var message = typeof error.message === 'string' ? error.message : 'Tool call failed';
|
|
3486
|
+
throw markToolFailure(createSafeError(message), toolName, 'Error', message, 'TOOL_CALL_FAILED');
|
|
3487
|
+
}
|
|
3488
|
+
throw error;
|
|
3489
|
+
});
|
|
3490
|
+
}
|
|
3491
|
+
|
|
3492
|
+
if (!throwOnError) {
|
|
3493
|
+
promise = promise.then(function(result) {
|
|
3494
|
+
return { success: true, data: result };
|
|
3495
|
+
}, function(error) {
|
|
3496
|
+
var info = toolFailures.get(error);
|
|
3497
|
+
if (info) {
|
|
3498
|
+
return { success: false, error: info };
|
|
3499
|
+
}
|
|
3500
|
+
throw error;
|
|
3501
|
+
});
|
|
2843
3502
|
}
|
|
2844
3503
|
|
|
2845
3504
|
// Create a secure promise that wraps both the promise object and its result
|
|
@@ -3492,6 +4151,36 @@ ${stackTraceHardeningCode}
|
|
|
3492
4151
|
innerRuntimeScript.runInContext(innerContext);
|
|
3493
4152
|
} catch (e) { /* ignore */ }
|
|
3494
4153
|
|
|
4154
|
+
// Tool namespaces (mail.list(args)): built INSIDE the inner realm by a factory evaluated there
|
|
4155
|
+
// (before Object/JSON are replaced by the safe globals below), so each namespace is a frozen,
|
|
4156
|
+
// null-prototype inner-realm object whose methods call the gated callTool. A namespace call is
|
|
4157
|
+
// therefore an ordinary tool call: counted, rate-limited, pattern-checked and sanitized.
|
|
4158
|
+
var toolNamespaceNames = ${JSON.stringify(toolNamespaces.map((ns) => ns.name))};
|
|
4159
|
+
if (toolNamespaceNames.length > 0) {
|
|
4160
|
+
var installToolNamespaces = new vm.Script(${JSON.stringify(TOOL_NAMESPACE_FACTORY_SOURCE)}, {
|
|
4161
|
+
filename: 'inner-tool-namespaces.js'
|
|
4162
|
+
}).runInContext(innerContext);
|
|
4163
|
+
var builtToolNamespaces = installToolNamespaces(safeRuntime.__safe_callTool, ${JSON.stringify(
|
|
4164
|
+
JSON.stringify(toolNamespaces)
|
|
4165
|
+
)});
|
|
4166
|
+
for (var tn = 0; tn < toolNamespaceNames.length; tn++) {
|
|
4167
|
+
var toolNamespaceName = toolNamespaceNames[tn];
|
|
4168
|
+
var toolNamespace = builtToolNamespaces[toolNamespaceName];
|
|
4169
|
+
__ag_defineProperty(innerContext, toolNamespaceName, {
|
|
4170
|
+
value: toolNamespace,
|
|
4171
|
+
writable: false,
|
|
4172
|
+
configurable: false,
|
|
4173
|
+
enumerable: false
|
|
4174
|
+
});
|
|
4175
|
+
__ag_defineProperty(innerContext, '__safe_' + toolNamespaceName, {
|
|
4176
|
+
value: toolNamespace,
|
|
4177
|
+
writable: false,
|
|
4178
|
+
configurable: false,
|
|
4179
|
+
enumerable: false
|
|
4180
|
+
});
|
|
4181
|
+
}
|
|
4182
|
+
}
|
|
4183
|
+
|
|
3495
4184
|
// Defense-in-depth: Remove host callback from inner sandbox after all scripts have captured it
|
|
3496
4185
|
try { delete innerContext['__host_memory_track__']; } catch (e) { /* ignore */ }
|
|
3497
4186
|
|
|
@@ -3735,6 +4424,8 @@ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
|
|
|
3735
4424
|
var init_parent_vm_bootstrap = __esm({
|
|
3736
4425
|
"libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
|
|
3737
4426
|
"use strict";
|
|
4427
|
+
init_global_function_gate();
|
|
4428
|
+
init_tool_namespaces();
|
|
3738
4429
|
MEMBRANE_MAX_RECURSION_DEPTH = 256;
|
|
3739
4430
|
NODEJS_24_DANGEROUS_GLOBALS = {
|
|
3740
4431
|
STRICT: [
|
|
@@ -3947,36 +4638,7 @@ var init_suspicious_patterns = __esm({
|
|
|
3947
4638
|
|
|
3948
4639
|
// libs/core/src/double-vm/double-vm-wrapper.ts
|
|
3949
4640
|
import * as vm2 from "vm";
|
|
3950
|
-
|
|
3951
|
-
if (!stack || !sanitize) return stack;
|
|
3952
|
-
let sanitized = stack;
|
|
3953
|
-
for (const pattern of SENSITIVE_STACK_PATTERNS) {
|
|
3954
|
-
pattern.lastIndex = 0;
|
|
3955
|
-
sanitized = sanitized.replace(pattern, "[REDACTED]");
|
|
3956
|
-
}
|
|
3957
|
-
const lines = sanitized.split("\n");
|
|
3958
|
-
for (let i = 0; i < lines.length; i++) {
|
|
3959
|
-
const line = lines[i];
|
|
3960
|
-
if (line.length > 1e3) continue;
|
|
3961
|
-
if (/:\d+:\d+\)/.test(line)) {
|
|
3962
|
-
const atIdx = line.indexOf("at ");
|
|
3963
|
-
if (atIdx !== -1) {
|
|
3964
|
-
const afterAt = line.substring(atIdx + 3).trimStart();
|
|
3965
|
-
const spaceIdx = afterAt.indexOf(" ");
|
|
3966
|
-
if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
|
|
3967
|
-
const funcName = afterAt.substring(0, spaceIdx);
|
|
3968
|
-
lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
|
|
3969
|
-
continue;
|
|
3970
|
-
}
|
|
3971
|
-
}
|
|
3972
|
-
}
|
|
3973
|
-
if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
|
|
3974
|
-
lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
|
|
3975
|
-
}
|
|
3976
|
-
}
|
|
3977
|
-
return lines.join("\n");
|
|
3978
|
-
}
|
|
3979
|
-
var SENSITIVE_STACK_PATTERNS, DoubleVmWrapper;
|
|
4641
|
+
var DoubleVmWrapper;
|
|
3980
4642
|
var init_double_vm_wrapper = __esm({
|
|
3981
4643
|
"libs/core/src/double-vm/double-vm-wrapper.ts"() {
|
|
3982
4644
|
"use strict";
|
|
@@ -3986,14 +4648,10 @@ var init_double_vm_wrapper = __esm({
|
|
|
3986
4648
|
init_reference_resolver();
|
|
3987
4649
|
init_memory_tracker();
|
|
3988
4650
|
init_tool_bridge();
|
|
4651
|
+
init_stack_trace();
|
|
4652
|
+
init_global_function_gate();
|
|
3989
4653
|
init_parent_vm_bootstrap();
|
|
3990
4654
|
init_suspicious_patterns();
|
|
3991
|
-
SENSITIVE_STACK_PATTERNS = [
|
|
3992
|
-
/\/Users\/[^/]+\/[^\s):]*/gi,
|
|
3993
|
-
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
3994
|
-
/\/var\/[^\s):]*/gi,
|
|
3995
|
-
/node_modules\/[^\s):]+/gi
|
|
3996
|
-
];
|
|
3997
4655
|
DoubleVmWrapper = class {
|
|
3998
4656
|
constructor(config, securityLevel) {
|
|
3999
4657
|
this.config = config;
|
|
@@ -4157,6 +4815,18 @@ var init_double_vm_wrapper = __esm({
|
|
|
4157
4815
|
configurable: true
|
|
4158
4816
|
// Allow deletion after capture for defense-in-depth
|
|
4159
4817
|
});
|
|
4818
|
+
Object.defineProperty(parentContext, "__host_invokeGlobal__", {
|
|
4819
|
+
value: createHostGlobalFunctionInvoker(executionContext),
|
|
4820
|
+
writable: false,
|
|
4821
|
+
configurable: true
|
|
4822
|
+
// Allow deletion after capture for defense-in-depth
|
|
4823
|
+
});
|
|
4824
|
+
Object.defineProperty(parentContext, "__host_isBuiltinMethod__", {
|
|
4825
|
+
value: (fn) => isBuiltinMethod(fn),
|
|
4826
|
+
writable: false,
|
|
4827
|
+
configurable: true
|
|
4828
|
+
// Allow deletion after capture for defense-in-depth
|
|
4829
|
+
});
|
|
4160
4830
|
Object.defineProperty(parentContext, "__host_stats__", {
|
|
4161
4831
|
value: stats,
|
|
4162
4832
|
writable: false,
|
|
@@ -4292,7 +4962,11 @@ var init_double_vm_wrapper = __esm({
|
|
|
4292
4962
|
return sanitized;
|
|
4293
4963
|
} catch (error) {
|
|
4294
4964
|
const err = error;
|
|
4295
|
-
throw createSafeError(
|
|
4965
|
+
throw createSafeError(
|
|
4966
|
+
`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
|
|
4967
|
+
"Error",
|
|
4968
|
+
"TOOL_CALL_FAILED"
|
|
4969
|
+
);
|
|
4296
4970
|
}
|
|
4297
4971
|
};
|
|
4298
4972
|
}
|
|
@@ -4337,7 +5011,9 @@ var init_double_vm_wrapper = __esm({
|
|
|
4337
5011
|
memoryLimit: config.memoryLimit,
|
|
4338
5012
|
throwOnBlocked,
|
|
4339
5013
|
toolBridgeMode,
|
|
4340
|
-
toolBridgeMaxPayloadBytes
|
|
5014
|
+
toolBridgeMaxPayloadBytes,
|
|
5015
|
+
maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls(config),
|
|
5016
|
+
toolNamespaces: executionContext.toolNamespaces ?? []
|
|
4341
5017
|
});
|
|
4342
5018
|
}
|
|
4343
5019
|
/**
|
|
@@ -4518,6 +5194,16 @@ var init_memory_proxy = __esm({
|
|
|
4518
5194
|
});
|
|
4519
5195
|
|
|
4520
5196
|
// libs/core/src/safe-runtime.ts
|
|
5197
|
+
function readThrowOnError(options) {
|
|
5198
|
+
if (options === void 0 || options === null) return true;
|
|
5199
|
+
if (typeof options !== "object") {
|
|
5200
|
+
throw createSafeTypeError("callTool options must be an object");
|
|
5201
|
+
}
|
|
5202
|
+
return options.throwOnError !== false;
|
|
5203
|
+
}
|
|
5204
|
+
function plainResult(fields) {
|
|
5205
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), fields);
|
|
5206
|
+
}
|
|
4521
5207
|
function createSafeRuntime(context, options) {
|
|
4522
5208
|
const { config, stats } = context;
|
|
4523
5209
|
const sidecar = options?.sidecar;
|
|
@@ -4526,7 +5212,8 @@ function createSafeRuntime(context, options) {
|
|
|
4526
5212
|
const memoryTracker = options?.memoryTracker;
|
|
4527
5213
|
const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
|
|
4528
5214
|
const proxyOptions = secureProxyConfig ? { levelConfig: secureProxyConfig } : {};
|
|
4529
|
-
async function __safe_callTool(toolName, args) {
|
|
5215
|
+
async function __safe_callTool(toolName, args, options2) {
|
|
5216
|
+
const throwOnError = readThrowOnError(options2);
|
|
4530
5217
|
if (context.aborted) {
|
|
4531
5218
|
throw createSafeError("Execution aborted");
|
|
4532
5219
|
}
|
|
@@ -4570,21 +5257,34 @@ function createSafeRuntime(context, options) {
|
|
|
4570
5257
|
allowDates: true,
|
|
4571
5258
|
allowErrors: true
|
|
4572
5259
|
});
|
|
5260
|
+
let value = sanitized;
|
|
4573
5261
|
if (sidecar && referenceConfig && typeof sanitized === "string") {
|
|
4574
5262
|
const size = Buffer.byteLength(sanitized, "utf-8");
|
|
4575
5263
|
if (size >= referenceConfig.extractionThreshold) {
|
|
4576
5264
|
try {
|
|
4577
|
-
|
|
4578
|
-
return refId;
|
|
5265
|
+
value = sidecar.store(sanitized, "tool-result", { origin: toolName });
|
|
4579
5266
|
} catch {
|
|
4580
|
-
|
|
5267
|
+
value = sanitized;
|
|
4581
5268
|
}
|
|
4582
5269
|
}
|
|
4583
5270
|
}
|
|
4584
|
-
return
|
|
5271
|
+
return throwOnError ? value : plainResult({ success: true, data: value });
|
|
4585
5272
|
} catch (error) {
|
|
4586
5273
|
const err = error;
|
|
4587
|
-
|
|
5274
|
+
const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
|
|
5275
|
+
if (!throwOnError) {
|
|
5276
|
+
const code = error?.code;
|
|
5277
|
+
return plainResult({
|
|
5278
|
+
success: false,
|
|
5279
|
+
error: plainResult({
|
|
5280
|
+
name: "Error",
|
|
5281
|
+
message,
|
|
5282
|
+
...typeof code === "string" ? { code } : {},
|
|
5283
|
+
toolName
|
|
5284
|
+
})
|
|
5285
|
+
});
|
|
5286
|
+
}
|
|
5287
|
+
throw createSafeError(message);
|
|
4588
5288
|
}
|
|
4589
5289
|
}
|
|
4590
5290
|
function* __safe_forOf(iterable) {
|
|
@@ -4781,7 +5481,8 @@ ${errorMessages}`);
|
|
|
4781
5481
|
}
|
|
4782
5482
|
const customGlobalsWithPrefix = {};
|
|
4783
5483
|
if (config.globals) {
|
|
4784
|
-
const
|
|
5484
|
+
const customGlobalProxyOptions = options?.globalFunctionGate ? { ...proxyOptions, callGate: options.globalFunctionGate } : proxyOptions;
|
|
5485
|
+
const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, customGlobalProxyOptions);
|
|
4785
5486
|
for (const [key, value] of Object.entries(wrappedCustomGlobals)) {
|
|
4786
5487
|
customGlobalsWithPrefix[`__safe_${key}`] = value;
|
|
4787
5488
|
}
|
|
@@ -4836,18 +5537,22 @@ ${errorMessages}`);
|
|
|
4836
5537
|
}
|
|
4837
5538
|
function serializeSafeRuntime() {
|
|
4838
5539
|
return `
|
|
4839
|
-
// Safe callTool implementation
|
|
4840
|
-
|
|
5540
|
+
// Safe callTool implementation. The options ({ throwOnError: false }) are passed on:
|
|
5541
|
+
// only the adapter's __internal_callTool can tell a failure of the tool from a refusal.
|
|
5542
|
+
async function __safe_callTool(toolName, args, options) {
|
|
4841
5543
|
if (typeof toolName !== 'string' || !toolName) {
|
|
4842
5544
|
throw new TypeError('Tool name must be a non-empty string');
|
|
4843
5545
|
}
|
|
4844
5546
|
if (typeof args !== 'object' || args === null || Array.isArray(args)) {
|
|
4845
5547
|
throw new TypeError('Tool arguments must be an object');
|
|
4846
5548
|
}
|
|
5549
|
+
if (options !== undefined && options !== null && typeof options !== 'object') {
|
|
5550
|
+
throw new TypeError('callTool options must be an object');
|
|
5551
|
+
}
|
|
4847
5552
|
|
|
4848
5553
|
// This will be replaced by the sandbox adapter with actual implementation
|
|
4849
5554
|
if (typeof __internal_callTool === 'function') {
|
|
4850
|
-
return await __internal_callTool(toolName, args);
|
|
5555
|
+
return await __internal_callTool(toolName, args, options);
|
|
4851
5556
|
}
|
|
4852
5557
|
throw new Error('Tool handler not available');
|
|
4853
5558
|
}
|
|
@@ -5017,36 +5722,6 @@ __export(vm_adapter_exports, {
|
|
|
5017
5722
|
VmAdapter: () => VmAdapter
|
|
5018
5723
|
});
|
|
5019
5724
|
import * as vm3 from "vm";
|
|
5020
|
-
function sanitizeStackTrace2(stack, sanitize = true) {
|
|
5021
|
-
if (!stack) return stack;
|
|
5022
|
-
if (!sanitize) return stack;
|
|
5023
|
-
let sanitized = stack;
|
|
5024
|
-
for (const pattern of SENSITIVE_STACK_PATTERNS2) {
|
|
5025
|
-
pattern.lastIndex = 0;
|
|
5026
|
-
sanitized = sanitized.replace(pattern, "[REDACTED]");
|
|
5027
|
-
}
|
|
5028
|
-
const lines = sanitized.split("\n");
|
|
5029
|
-
for (let i = 0; i < lines.length; i++) {
|
|
5030
|
-
const line = lines[i];
|
|
5031
|
-
if (line.length > 1e3) continue;
|
|
5032
|
-
if (/:\d+:\d+\)/.test(line)) {
|
|
5033
|
-
const atIdx = line.indexOf("at ");
|
|
5034
|
-
if (atIdx !== -1) {
|
|
5035
|
-
const afterAt = line.substring(atIdx + 3).trimStart();
|
|
5036
|
-
const spaceIdx = afterAt.indexOf(" ");
|
|
5037
|
-
if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
|
|
5038
|
-
const funcName = afterAt.substring(0, spaceIdx);
|
|
5039
|
-
lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
|
|
5040
|
-
continue;
|
|
5041
|
-
}
|
|
5042
|
-
}
|
|
5043
|
-
}
|
|
5044
|
-
if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
|
|
5045
|
-
lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
|
|
5046
|
-
}
|
|
5047
|
-
}
|
|
5048
|
-
return lines.join("\n");
|
|
5049
|
-
}
|
|
5050
5725
|
function createSafeConsole(config, stats) {
|
|
5051
5726
|
const wrap = (method) => (...args) => {
|
|
5052
5727
|
stats.callCount++;
|
|
@@ -5210,7 +5885,7 @@ function sanitizeVmContext(context, securityLevel) {
|
|
|
5210
5885
|
enumerable: true
|
|
5211
5886
|
});
|
|
5212
5887
|
}
|
|
5213
|
-
var
|
|
5888
|
+
var STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, SANDBOX_REALM_BRIDGE_SCRIPT, TOOL_NAMESPACE_FACTORY_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
|
|
5214
5889
|
var init_vm_adapter = __esm({
|
|
5215
5890
|
"libs/core/src/adapters/vm-adapter.ts"() {
|
|
5216
5891
|
"use strict";
|
|
@@ -5220,130 +5895,9 @@ var init_vm_adapter = __esm({
|
|
|
5220
5895
|
init_memory_tracker();
|
|
5221
5896
|
init_tool_bridge();
|
|
5222
5897
|
init_value_sanitizer();
|
|
5223
|
-
|
|
5224
|
-
|
|
5225
|
-
|
|
5226
|
-
// macOS home directories
|
|
5227
|
-
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
5228
|
-
// Linux home directories
|
|
5229
|
-
/\/var\/[^\s):]*/gi,
|
|
5230
|
-
// System var directories
|
|
5231
|
-
/\/opt\/[^\s):]*/gi,
|
|
5232
|
-
// Optional software
|
|
5233
|
-
/\/tmp\/[^\s):]*/gi,
|
|
5234
|
-
// Temporary files
|
|
5235
|
-
/\/etc\/[^\s):]*/gi,
|
|
5236
|
-
// System configuration
|
|
5237
|
-
/\/root\/[^\s):]*/gi,
|
|
5238
|
-
// Root home directory
|
|
5239
|
-
/\/mnt\/[^\s):]*/gi,
|
|
5240
|
-
// Mount points
|
|
5241
|
-
/\/srv\/[^\s):]*/gi,
|
|
5242
|
-
// Service data
|
|
5243
|
-
/\/data\/[^\s):]*/gi,
|
|
5244
|
-
// Data directories
|
|
5245
|
-
/\/app\/[^\s):]*/gi,
|
|
5246
|
-
// Application directories
|
|
5247
|
-
/\/proc\/[^\s):]*/gi,
|
|
5248
|
-
// Process information
|
|
5249
|
-
/\/sys\/[^\s):]*/gi,
|
|
5250
|
-
// System files
|
|
5251
|
-
// Windows paths
|
|
5252
|
-
/\\\\[^\s):]*/g,
|
|
5253
|
-
// UNC paths
|
|
5254
|
-
/[A-Z]:\\[^\s):]+/gi,
|
|
5255
|
-
// Windows drive paths
|
|
5256
|
-
// URL-based paths
|
|
5257
|
-
/file:\/\/[^\s):]+/gi,
|
|
5258
|
-
// File URLs
|
|
5259
|
-
/webpack:\/\/[^\s):]+/gi,
|
|
5260
|
-
// Webpack paths
|
|
5261
|
-
/%2F[^\s):]+/gi,
|
|
5262
|
-
// URL-encoded paths
|
|
5263
|
-
// Package managers and node
|
|
5264
|
-
/node_modules\/[^\s):]+/gi,
|
|
5265
|
-
// Node modules paths
|
|
5266
|
-
/\/nix\/store\/[^\s):]*/gi,
|
|
5267
|
-
// Nix store paths
|
|
5268
|
-
/\.npm\/[^\s):]*/gi,
|
|
5269
|
-
// NPM cache
|
|
5270
|
-
/\.yarn\/[^\s):]*/gi,
|
|
5271
|
-
// Yarn cache
|
|
5272
|
-
/\.pnpm\/[^\s):]*/gi,
|
|
5273
|
-
// PNPM cache
|
|
5274
|
-
// Container and orchestration
|
|
5275
|
-
/\/run\/secrets\/[^\s):]*/gi,
|
|
5276
|
-
// Docker/K8s secrets
|
|
5277
|
-
/\/var\/run\/[^\s):]*/gi,
|
|
5278
|
-
// Runtime directories
|
|
5279
|
-
/\/docker\/[^\s):]*/gi,
|
|
5280
|
-
// Docker paths
|
|
5281
|
-
/\/containers\/[^\s):]*/gi,
|
|
5282
|
-
// Container paths
|
|
5283
|
-
/\/kubelet\/[^\s):]*/gi,
|
|
5284
|
-
// Kubernetes kubelet
|
|
5285
|
-
// CI/CD systems
|
|
5286
|
-
/\/github\/workspace\/[^\s):]*/gi,
|
|
5287
|
-
// GitHub Actions
|
|
5288
|
-
/\/runner\/[^\s):]*/gi,
|
|
5289
|
-
// GitHub/GitLab runner
|
|
5290
|
-
/\/builds\/[^\s):]*/gi,
|
|
5291
|
-
// CI builds
|
|
5292
|
-
/\/workspace\/[^\s):]*/gi,
|
|
5293
|
-
// Generic workspace
|
|
5294
|
-
/\/pipeline\/[^\s):]*/gi,
|
|
5295
|
-
// CI pipelines
|
|
5296
|
-
/\/jenkins\/[^\s):]*/gi,
|
|
5297
|
-
// Jenkins
|
|
5298
|
-
/\/bamboo\/[^\s):]*/gi,
|
|
5299
|
-
// Bamboo
|
|
5300
|
-
/\/teamcity\/[^\s):]*/gi,
|
|
5301
|
-
// TeamCity
|
|
5302
|
-
/\/circleci\/[^\s):]*/gi,
|
|
5303
|
-
// CircleCI
|
|
5304
|
-
// Cloud providers
|
|
5305
|
-
/\/aws\/[^\s):]*/gi,
|
|
5306
|
-
// AWS paths
|
|
5307
|
-
/\/gcloud\/[^\s):]*/gi,
|
|
5308
|
-
// Google Cloud
|
|
5309
|
-
/\/azure\/[^\s):]*/gi,
|
|
5310
|
-
// Azure paths
|
|
5311
|
-
/s3:\/\/[^\s):]+/gi,
|
|
5312
|
-
// S3 URIs
|
|
5313
|
-
/gs:\/\/[^\s):]+/gi,
|
|
5314
|
-
// GCS URIs
|
|
5315
|
-
// Secrets and credentials (patterns that might appear in paths or errors)
|
|
5316
|
-
/[A-Z0-9]{20,}/g,
|
|
5317
|
-
// AWS-style access keys (20+ uppercase chars)
|
|
5318
|
-
/sk-[a-zA-Z0-9]{32,}/g,
|
|
5319
|
-
// OpenAI/Stripe-style secret keys
|
|
5320
|
-
/ghp_[a-zA-Z0-9]{36,}/g,
|
|
5321
|
-
// GitHub personal access tokens
|
|
5322
|
-
/gho_[a-zA-Z0-9]{36,}/g,
|
|
5323
|
-
// GitHub OAuth tokens
|
|
5324
|
-
/github_pat_[a-zA-Z0-9_]{22,}/g,
|
|
5325
|
-
// GitHub fine-grained tokens
|
|
5326
|
-
/xox[baprs]-[a-zA-Z0-9-]+/g,
|
|
5327
|
-
// Slack tokens
|
|
5328
|
-
/Bearer\s+[a-zA-Z0-9._-]+/gi,
|
|
5329
|
-
// Bearer tokens
|
|
5330
|
-
/Basic\s+[a-zA-Z0-9+/=]+/gi,
|
|
5331
|
-
// Basic auth
|
|
5332
|
-
// Internal network info
|
|
5333
|
-
/(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
|
|
5334
|
-
// Private IPs
|
|
5335
|
-
/[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
|
|
5336
|
-
// Internal hostnames
|
|
5337
|
-
/localhost:\d+/gi,
|
|
5338
|
-
// Localhost with port
|
|
5339
|
-
/127\.0\.0\.1:\d+/gi,
|
|
5340
|
-
// Loopback with port
|
|
5341
|
-
// User information
|
|
5342
|
-
/\/u\/[^/]+\//gi,
|
|
5343
|
-
// User subdirectories
|
|
5344
|
-
/~[a-z_][a-z0-9_-]*/gi
|
|
5345
|
-
// Unix user home shorthand
|
|
5346
|
-
];
|
|
5898
|
+
init_stack_trace();
|
|
5899
|
+
init_global_function_gate();
|
|
5900
|
+
init_tool_namespaces();
|
|
5347
5901
|
STACK_TRACE_HARDENING_CODE = `
|
|
5348
5902
|
(function() {
|
|
5349
5903
|
function __ag_redactStackString(stackStr) {
|
|
@@ -5509,6 +6063,20 @@ var init_vm_adapter = __esm({
|
|
|
5509
6063
|
})();
|
|
5510
6064
|
`;
|
|
5511
6065
|
INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm3.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
|
|
6066
|
+
SANDBOX_REALM_BRIDGE_SCRIPT = new vm3.Script(`
|
|
6067
|
+
(function () {
|
|
6068
|
+
'use strict';
|
|
6069
|
+
var parse = JSON.parse;
|
|
6070
|
+
var SandboxPromise = Promise;
|
|
6071
|
+
return Object.freeze({
|
|
6072
|
+
parseJson: function (json) { return parse(json); },
|
|
6073
|
+
adoptPromise: function (hostPromise) {
|
|
6074
|
+
return new SandboxPromise(function (resolve, reject) { hostPromise.then(resolve, reject); });
|
|
6075
|
+
}
|
|
6076
|
+
});
|
|
6077
|
+
})()
|
|
6078
|
+
`);
|
|
6079
|
+
TOOL_NAMESPACE_FACTORY_SCRIPT = new vm3.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
|
|
5512
6080
|
PROTECTED_PREFIXES = ["__safe_", "__ag_"];
|
|
5513
6081
|
DANGEROUS_OBJECT_STATIC_METHODS = [
|
|
5514
6082
|
"defineProperty",
|
|
@@ -5624,19 +6192,23 @@ var init_vm_adapter = __esm({
|
|
|
5624
6192
|
}) : void 0;
|
|
5625
6193
|
memoryTracker?.start();
|
|
5626
6194
|
try {
|
|
5627
|
-
const safeRuntime = createSafeRuntime(executionContext, {
|
|
5628
|
-
sidecar: executionContext.sidecar,
|
|
5629
|
-
referenceConfig: executionContext.referenceConfig,
|
|
5630
|
-
secureProxyConfig: executionContext.secureProxyConfig,
|
|
5631
|
-
memoryTracker
|
|
5632
|
-
// Pass tracker for allocation monitoring
|
|
5633
|
-
});
|
|
5634
6195
|
const baseSandbox = vm3.createContext(
|
|
5635
6196
|
{},
|
|
5636
6197
|
{
|
|
5637
6198
|
codeGeneration: { strings: false, wasm: false }
|
|
5638
6199
|
}
|
|
5639
6200
|
);
|
|
6201
|
+
const realmBridge = SANDBOX_REALM_BRIDGE_SCRIPT.runInContext(baseSandbox);
|
|
6202
|
+
const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
|
|
6203
|
+
const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge);
|
|
6204
|
+
const safeRuntime = createSafeRuntime(executionContext, {
|
|
6205
|
+
sidecar: executionContext.sidecar,
|
|
6206
|
+
referenceConfig: executionContext.referenceConfig,
|
|
6207
|
+
secureProxyConfig: executionContext.secureProxyConfig,
|
|
6208
|
+
memoryTracker,
|
|
6209
|
+
// Pass tracker for allocation monitoring
|
|
6210
|
+
globalFunctionGate
|
|
6211
|
+
});
|
|
5640
6212
|
if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
|
|
5641
6213
|
Object.defineProperty(baseSandbox, "__host_memory_track__", {
|
|
5642
6214
|
value: (bytes) => {
|
|
@@ -5800,9 +6372,28 @@ var init_vm_adapter = __esm({
|
|
|
5800
6372
|
// Remove global handle after capture (defense-in-depth)
|
|
5801
6373
|
try { delete globalThis.__host_callToolBridge__; } catch (e) { /* ignore */ }
|
|
5802
6374
|
|
|
5803
|
-
|
|
5804
|
-
|
|
5805
|
-
|
|
6375
|
+
// Whether a payload is larger than the limit in UTF-8 bytes, as the host counts it. A code
|
|
6376
|
+
// unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
|
|
6377
|
+
function exceedsPayloadLimit(str) {
|
|
6378
|
+
if (str.length > maxBytes) return true;
|
|
6379
|
+
if (str.length * 3 <= maxBytes) return false;
|
|
6380
|
+
var bytes = 0;
|
|
6381
|
+
for (var i = 0; i < str.length; i++) {
|
|
6382
|
+
var c = str.charCodeAt(i);
|
|
6383
|
+
if (c < 0x80) bytes += 1;
|
|
6384
|
+
else if (c < 0x800) bytes += 2;
|
|
6385
|
+
else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
|
|
6386
|
+
var d = str.charCodeAt(i + 1);
|
|
6387
|
+
if (d >= 0xdc00 && d <= 0xdfff) {
|
|
6388
|
+
bytes += 4;
|
|
6389
|
+
i++;
|
|
6390
|
+
} else {
|
|
6391
|
+
bytes += 3;
|
|
6392
|
+
}
|
|
6393
|
+
} else bytes += 3;
|
|
6394
|
+
if (bytes > maxBytes) return true;
|
|
6395
|
+
}
|
|
6396
|
+
return false;
|
|
5806
6397
|
}
|
|
5807
6398
|
|
|
5808
6399
|
function makeError(message, name) {
|
|
@@ -5811,7 +6402,16 @@ var init_vm_adapter = __esm({
|
|
|
5811
6402
|
return err;
|
|
5812
6403
|
}
|
|
5813
6404
|
|
|
5814
|
-
return async function __safe_callTool(toolName, args) {
|
|
6405
|
+
return async function __safe_callTool(toolName, args, options) {
|
|
6406
|
+
// callTool options: only { throwOnError: false } changes behavior. Tool failures
|
|
6407
|
+
// then resolve to { success: false, error }; the enclave's own refusals still throw.
|
|
6408
|
+
var throwOnError = true;
|
|
6409
|
+
if (options !== undefined && options !== null) {
|
|
6410
|
+
if (typeof options !== 'object') {
|
|
6411
|
+
throw makeError('callTool options must be an object', 'TypeError');
|
|
6412
|
+
}
|
|
6413
|
+
throwOnError = options.throwOnError !== false;
|
|
6414
|
+
}
|
|
5815
6415
|
if (typeof toolName !== 'string' || !toolName) {
|
|
5816
6416
|
throw makeError('Tool name must be a non-empty string', 'TypeError');
|
|
5817
6417
|
}
|
|
@@ -5837,7 +6437,7 @@ var init_vm_adapter = __esm({
|
|
|
5837
6437
|
throw makeError('Tool request must be JSON-serializable', 'TypeError');
|
|
5838
6438
|
}
|
|
5839
6439
|
|
|
5840
|
-
if (
|
|
6440
|
+
if (exceedsPayloadLimit(requestJson)) {
|
|
5841
6441
|
throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
|
|
5842
6442
|
}
|
|
5843
6443
|
|
|
@@ -5845,8 +6445,24 @@ var init_vm_adapter = __esm({
|
|
|
5845
6445
|
if (typeof responseJson !== 'string') {
|
|
5846
6446
|
throw makeError('Tool bridge returned invalid response', 'Error');
|
|
5847
6447
|
}
|
|
5848
|
-
|
|
5849
|
-
|
|
6448
|
+
// The host refuses an oversized response as a tool failure; this check only backs it
|
|
6449
|
+
// up, and reports the same way so { throwOnError: false } resolves it to a result.
|
|
6450
|
+
if (exceedsPayloadLimit(responseJson)) {
|
|
6451
|
+
var tooLarge = 'Tool response exceeds maximum size (' + maxBytes + ' bytes)';
|
|
6452
|
+
if (!throwOnError) {
|
|
6453
|
+
return {
|
|
6454
|
+
__proto__: null,
|
|
6455
|
+
success: false,
|
|
6456
|
+
error: {
|
|
6457
|
+
__proto__: null,
|
|
6458
|
+
name: 'RangeError',
|
|
6459
|
+
message: tooLarge,
|
|
6460
|
+
toolName: toolName,
|
|
6461
|
+
code: 'TOOL_BRIDGE_RESPONSE_TOO_LARGE',
|
|
6462
|
+
},
|
|
6463
|
+
};
|
|
6464
|
+
}
|
|
6465
|
+
throw makeError(tooLarge, 'RangeError');
|
|
5850
6466
|
}
|
|
5851
6467
|
|
|
5852
6468
|
var response;
|
|
@@ -5861,13 +6477,18 @@ var init_vm_adapter = __esm({
|
|
|
5861
6477
|
}
|
|
5862
6478
|
|
|
5863
6479
|
if (response.ok === true) {
|
|
5864
|
-
|
|
5865
|
-
return
|
|
6480
|
+
var value = hasOwn.call(response, 'value') ? response.value : undefined;
|
|
6481
|
+
return throwOnError ? value : { __proto__: null, success: true, data: value };
|
|
5866
6482
|
}
|
|
5867
6483
|
|
|
5868
6484
|
if (response.ok === false && response.error) {
|
|
5869
6485
|
var msg = (typeof response.error.message === 'string') ? response.error.message : 'Tool call failed';
|
|
5870
6486
|
var name = (typeof response.error.name === 'string') ? response.error.name : 'Error';
|
|
6487
|
+
if (!throwOnError && response.error.toolError === true) {
|
|
6488
|
+
var info = { __proto__: null, name: name, message: msg, toolName: toolName };
|
|
6489
|
+
if (typeof response.error.code === 'string') info.code = response.error.code;
|
|
6490
|
+
return { __proto__: null, success: false, error: info };
|
|
6491
|
+
}
|
|
5871
6492
|
throw makeError(msg, name);
|
|
5872
6493
|
}
|
|
5873
6494
|
|
|
@@ -5901,8 +6522,9 @@ var init_vm_adapter = __esm({
|
|
|
5901
6522
|
}
|
|
5902
6523
|
if (config.globals) {
|
|
5903
6524
|
for (const [key, value2] of Object.entries(config.globals)) {
|
|
5904
|
-
const wrappedValue = value2 !== null && typeof value2 === "object" ? createSecureProxy(value2, {
|
|
5905
|
-
levelConfig: executionContext.secureProxyConfig
|
|
6525
|
+
const wrappedValue = value2 !== null && (typeof value2 === "object" || typeof value2 === "function") ? createSecureProxy(value2, {
|
|
6526
|
+
levelConfig: executionContext.secureProxyConfig,
|
|
6527
|
+
callGate: globalFunctionGate
|
|
5906
6528
|
}) : value2;
|
|
5907
6529
|
Object.defineProperty(baseSandbox, key, {
|
|
5908
6530
|
value: wrappedValue,
|
|
@@ -5912,6 +6534,23 @@ var init_vm_adapter = __esm({
|
|
|
5912
6534
|
});
|
|
5913
6535
|
}
|
|
5914
6536
|
}
|
|
6537
|
+
if (executionContext.toolNamespaces?.length) {
|
|
6538
|
+
const callTool = baseSandbox["__safe_callTool"];
|
|
6539
|
+
for (const binding of buildToolNamespaceBindings(
|
|
6540
|
+
installToolNamespaces,
|
|
6541
|
+
callTool,
|
|
6542
|
+
executionContext.toolNamespaces
|
|
6543
|
+
)) {
|
|
6544
|
+
for (const name of [binding.name, `__safe_${binding.name}`]) {
|
|
6545
|
+
Object.defineProperty(baseSandbox, name, {
|
|
6546
|
+
value: binding.value,
|
|
6547
|
+
writable: false,
|
|
6548
|
+
configurable: false,
|
|
6549
|
+
enumerable: false
|
|
6550
|
+
});
|
|
6551
|
+
}
|
|
6552
|
+
}
|
|
6553
|
+
}
|
|
5915
6554
|
if (!("__safe_console" in safeRuntime)) {
|
|
5916
6555
|
const consoleStats = { totalBytes: 0, callCount: 0 };
|
|
5917
6556
|
Object.defineProperty(baseSandbox, "__safe_console", {
|
|
@@ -6019,7 +6658,7 @@ var init_vm_adapter = __esm({
|
|
|
6019
6658
|
error: {
|
|
6020
6659
|
name: err.name || "VMExecutionError",
|
|
6021
6660
|
message: err.message || "Unknown VM execution error",
|
|
6022
|
-
stack:
|
|
6661
|
+
stack: sanitizeStackTrace(err.stack, shouldSanitize),
|
|
6023
6662
|
code: "VM_EXECUTION_ERROR"
|
|
6024
6663
|
},
|
|
6025
6664
|
stats
|
|
@@ -6163,6 +6802,7 @@ var init_config = __esm({
|
|
|
6163
6802
|
|
|
6164
6803
|
// libs/core/src/adapters/worker-pool/protocol.ts
|
|
6165
6804
|
import { z } from "zod";
|
|
6805
|
+
import { TOOL_NAMESPACE_TOOL_NAME_PATTERN } from "@enclave-vm/ast";
|
|
6166
6806
|
function isToolCallMessage(msg) {
|
|
6167
6807
|
return msg.type === "tool-call";
|
|
6168
6808
|
}
|
|
@@ -6176,7 +6816,7 @@ var TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessage
|
|
|
6176
6816
|
var init_protocol = __esm({
|
|
6177
6817
|
"libs/core/src/adapters/worker-pool/protocol.ts"() {
|
|
6178
6818
|
"use strict";
|
|
6179
|
-
TOOL_NAME_PATTERN =
|
|
6819
|
+
TOOL_NAME_PATTERN = TOOL_NAMESPACE_TOOL_NAME_PATTERN;
|
|
6180
6820
|
ID_PATTERN = /^[a-zA-Z0-9-]+$/;
|
|
6181
6821
|
toolCallMessageSchema = z.object({
|
|
6182
6822
|
type: z.literal("tool-call"),
|
|
@@ -6408,7 +7048,7 @@ function sanitizeObjectWithDepthCheck(value, depth) {
|
|
|
6408
7048
|
if (typeof value !== "object") {
|
|
6409
7049
|
return value;
|
|
6410
7050
|
}
|
|
6411
|
-
if (
|
|
7051
|
+
if (ArrayIsArray3(value)) {
|
|
6412
7052
|
return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
|
|
6413
7053
|
}
|
|
6414
7054
|
const result = /* @__PURE__ */ Object.create(null);
|
|
@@ -6437,7 +7077,7 @@ function sanitizeObject(value, depth = 0) {
|
|
|
6437
7077
|
if (typeof value !== "object") {
|
|
6438
7078
|
return value;
|
|
6439
7079
|
}
|
|
6440
|
-
if (
|
|
7080
|
+
if (ArrayIsArray3(value)) {
|
|
6441
7081
|
return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
|
|
6442
7082
|
}
|
|
6443
7083
|
const result = /* @__PURE__ */ Object.create(null);
|
|
@@ -6448,13 +7088,13 @@ function sanitizeObject(value, depth = 0) {
|
|
|
6448
7088
|
}
|
|
6449
7089
|
return result;
|
|
6450
7090
|
}
|
|
6451
|
-
var ReflectGet4,
|
|
7091
|
+
var ReflectGet4, ArrayIsArray3, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
|
|
6452
7092
|
var init_safe_deserialize = __esm({
|
|
6453
7093
|
"libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
|
|
6454
7094
|
"use strict";
|
|
6455
7095
|
init_errors();
|
|
6456
7096
|
ReflectGet4 = Reflect.get;
|
|
6457
|
-
|
|
7097
|
+
ArrayIsArray3 = Array.isArray;
|
|
6458
7098
|
NumberIsFinite3 = Number.isFinite;
|
|
6459
7099
|
MathFloor3 = Math.floor;
|
|
6460
7100
|
MAX_ARRAY_LENGTH = 1e6;
|
|
@@ -7167,6 +7807,7 @@ var init_worker_pool_adapter = __esm({
|
|
|
7167
7807
|
init_rate_limiter();
|
|
7168
7808
|
init_safe_deserialize();
|
|
7169
7809
|
init_errors();
|
|
7810
|
+
init_stack_trace();
|
|
7170
7811
|
WorkerPoolAdapter = class {
|
|
7171
7812
|
config;
|
|
7172
7813
|
securityLevel;
|
|
@@ -7405,7 +8046,8 @@ var init_worker_pool_adapter = __esm({
|
|
|
7405
8046
|
globals: context.config.globals,
|
|
7406
8047
|
// Security level determines which globals are available in sandbox
|
|
7407
8048
|
// This mirrors AST guard's allowed globals for defense-in-depth
|
|
7408
|
-
securityLevel: this.securityLevel
|
|
8049
|
+
securityLevel: this.securityLevel,
|
|
8050
|
+
toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0
|
|
7409
8051
|
};
|
|
7410
8052
|
return new Promise((resolve, reject) => {
|
|
7411
8053
|
const pendingToolCalls = /* @__PURE__ */ new Map();
|
|
@@ -7422,7 +8064,7 @@ var init_worker_pool_adapter = __esm({
|
|
|
7422
8064
|
} else if (isExecutionResultMessage(msg) && msg.requestId === requestId) {
|
|
7423
8065
|
cleanup();
|
|
7424
8066
|
const duration = Date.now() - startTime;
|
|
7425
|
-
const result = this.buildResult(msg, duration);
|
|
8067
|
+
const result = this.buildResult(msg, duration, context.config.sanitizeStackTraces);
|
|
7426
8068
|
resolve(result);
|
|
7427
8069
|
} else if (isConsoleMessage(msg) && msg.requestId === requestId) {
|
|
7428
8070
|
this.handleConsoleMessage(msg);
|
|
@@ -7463,17 +8105,30 @@ var init_worker_pool_adapter = __esm({
|
|
|
7463
8105
|
pendingToolCalls.set(msg.callId, true);
|
|
7464
8106
|
let result;
|
|
7465
8107
|
let error;
|
|
8108
|
+
let toolError = false;
|
|
7466
8109
|
try {
|
|
7467
8110
|
if (!context.toolHandler) {
|
|
7468
8111
|
throw new Error("No tool handler configured");
|
|
7469
8112
|
}
|
|
7470
8113
|
const sanitizedArgs = sanitizeObject(msg.args);
|
|
7471
|
-
|
|
8114
|
+
toolError = true;
|
|
8115
|
+
const handlerResult = await context.toolHandler(msg.toolName, sanitizedArgs);
|
|
8116
|
+
try {
|
|
8117
|
+
result = sanitizeObject(handlerResult);
|
|
8118
|
+
} catch {
|
|
8119
|
+
throw Object.assign(new Error("Tool returned an unsupported value"), {
|
|
8120
|
+
name: "ToolBridgeError",
|
|
8121
|
+
code: "TOOL_RESULT_NOT_SAFE"
|
|
8122
|
+
});
|
|
8123
|
+
}
|
|
8124
|
+
toolError = false;
|
|
7472
8125
|
} catch (e) {
|
|
7473
8126
|
const err = e;
|
|
8127
|
+
const code = e?.code;
|
|
7474
8128
|
error = {
|
|
7475
8129
|
name: err.name || "Error",
|
|
7476
|
-
message: err.message || "Unknown error"
|
|
8130
|
+
message: err.message || "Unknown error",
|
|
8131
|
+
...toolError && typeof code === "string" ? { code } : {}
|
|
7477
8132
|
};
|
|
7478
8133
|
} finally {
|
|
7479
8134
|
pendingToolCalls.delete(msg.callId);
|
|
@@ -7482,8 +8137,9 @@ var init_worker_pool_adapter = __esm({
|
|
|
7482
8137
|
type: "tool-response",
|
|
7483
8138
|
requestId: msg.requestId,
|
|
7484
8139
|
callId: msg.callId,
|
|
7485
|
-
result
|
|
7486
|
-
error
|
|
8140
|
+
result,
|
|
8141
|
+
error,
|
|
8142
|
+
...error && toolError ? { toolError: true } : {}
|
|
7487
8143
|
});
|
|
7488
8144
|
}
|
|
7489
8145
|
handleConsoleMessage(msg) {
|
|
@@ -7500,7 +8156,7 @@ var init_worker_pool_adapter = __esm({
|
|
|
7500
8156
|
* before sending, but full runtime type validation would require schema
|
|
7501
8157
|
* definitions which are not available at this layer.
|
|
7502
8158
|
*/
|
|
7503
|
-
buildResult(msg, duration) {
|
|
8159
|
+
buildResult(msg, duration, sanitizeStacks) {
|
|
7504
8160
|
if (msg.success) {
|
|
7505
8161
|
return {
|
|
7506
8162
|
success: true,
|
|
@@ -7521,7 +8177,8 @@ var init_worker_pool_adapter = __esm({
|
|
|
7521
8177
|
name: error.name,
|
|
7522
8178
|
message: error.message,
|
|
7523
8179
|
code: error.code,
|
|
7524
|
-
stack
|
|
8180
|
+
// The worker trims its stack; sanitize it here too so the result obeys the option.
|
|
8181
|
+
stack: sanitizeStackTrace(error.stack, sanitizeStacks)
|
|
7525
8182
|
},
|
|
7526
8183
|
stats: {
|
|
7527
8184
|
duration,
|
|
@@ -8154,7 +8811,8 @@ import {
|
|
|
8154
8811
|
extractLargeStrings,
|
|
8155
8812
|
transformConcatenation,
|
|
8156
8813
|
transformTemplateLiterals,
|
|
8157
|
-
guardComputedMemberKeys
|
|
8814
|
+
guardComputedMemberKeys,
|
|
8815
|
+
normalizeToolNamespaces
|
|
8158
8816
|
} from "@enclave-vm/ast";
|
|
8159
8817
|
import * as acorn2 from "acorn";
|
|
8160
8818
|
import { generate } from "astring";
|
|
@@ -8337,6 +8995,7 @@ var DEFAULT_DOUBLE_VM_CONFIG = {
|
|
|
8337
8995
|
};
|
|
8338
8996
|
|
|
8339
8997
|
// libs/core/src/globals-validator.ts
|
|
8998
|
+
import { types } from "util";
|
|
8340
8999
|
var DANGEROUS_FUNCTION_PATTERNS = [
|
|
8341
9000
|
/\beval\b/,
|
|
8342
9001
|
// eval() calls
|
|
@@ -8364,7 +9023,55 @@ var DANGEROUS_FUNCTION_PATTERNS = [
|
|
|
8364
9023
|
// Synchronous spawn
|
|
8365
9024
|
];
|
|
8366
9025
|
var DANGEROUS_GLOBAL_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
8367
|
-
|
|
9026
|
+
var MapEntries = Map.prototype.entries;
|
|
9027
|
+
var SetValues = Set.prototype.values;
|
|
9028
|
+
var ReflectApply = Reflect.apply;
|
|
9029
|
+
var ReflectOwnKeys = Reflect.ownKeys;
|
|
9030
|
+
var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
|
|
9031
|
+
var ObjectGetPrototypeOf = Object.getPrototypeOf;
|
|
9032
|
+
var ArrayPrototype = Array.prototype;
|
|
9033
|
+
var MapPrototype = Map.prototype;
|
|
9034
|
+
var SetPrototype = Set.prototype;
|
|
9035
|
+
var IteratorPrototype = ObjectGetPrototypeOf(ObjectGetPrototypeOf([][Symbol.iterator]()));
|
|
9036
|
+
var AsyncIteratorPrototype = ObjectGetPrototypeOf(
|
|
9037
|
+
ObjectGetPrototypeOf(
|
|
9038
|
+
async function* () {
|
|
9039
|
+
}.prototype
|
|
9040
|
+
)
|
|
9041
|
+
);
|
|
9042
|
+
function describeOpaqueContainer(obj) {
|
|
9043
|
+
if (types.isPromise(obj)) return "a Promise";
|
|
9044
|
+
if (types.isWeakMap(obj)) return "a WeakMap";
|
|
9045
|
+
if (types.isGeneratorObject(obj)) return "a generator";
|
|
9046
|
+
if (types.isMapIterator(obj) || types.isSetIterator(obj) || Object.prototype.isPrototypeOf.call(IteratorPrototype, obj) || Object.prototype.isPrototypeOf.call(AsyncIteratorPrototype, obj)) {
|
|
9047
|
+
return "an iterator";
|
|
9048
|
+
}
|
|
9049
|
+
return void 0;
|
|
9050
|
+
}
|
|
9051
|
+
function isPlainDataObject(obj) {
|
|
9052
|
+
const proto = ObjectGetPrototypeOf(obj);
|
|
9053
|
+
return proto === null || proto === Object.prototype || types.isDate(obj) || types.isRegExp(obj) || types.isArrayBufferView(obj) || types.isAnyArrayBuffer(obj);
|
|
9054
|
+
}
|
|
9055
|
+
function describeInstance(obj) {
|
|
9056
|
+
try {
|
|
9057
|
+
const name = ObjectGetPrototypeOf(obj)?.constructor?.name;
|
|
9058
|
+
if (typeof name === "string" && name) return `a ${name} instance`;
|
|
9059
|
+
} catch {
|
|
9060
|
+
}
|
|
9061
|
+
return "a non-plain object";
|
|
9062
|
+
}
|
|
9063
|
+
function collectionError(key, what, path2) {
|
|
9064
|
+
return new Error(
|
|
9065
|
+
`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.`
|
|
9066
|
+
);
|
|
9067
|
+
}
|
|
9068
|
+
function mapValueSegment(mapKey, index) {
|
|
9069
|
+
if (typeof mapKey === "string" || typeof mapKey === "number" || typeof mapKey === "boolean") {
|
|
9070
|
+
return `get(${JSON.stringify(mapKey)})`;
|
|
9071
|
+
}
|
|
9072
|
+
return `values()[${index}]`;
|
|
9073
|
+
}
|
|
9074
|
+
function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet(), collectionVisited = /* @__PURE__ */ new WeakSet(), inCollection = false) {
|
|
8368
9075
|
const maxDepth = options.maxDepth ?? 10;
|
|
8369
9076
|
const allowFunctions = options.allowFunctions ?? false;
|
|
8370
9077
|
const allowGettersSetters = options.allowGettersSetters ?? false;
|
|
@@ -8388,6 +9095,9 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
|
|
|
8388
9095
|
}
|
|
8389
9096
|
if (type === "function") {
|
|
8390
9097
|
const funcName = value.name || "anonymous";
|
|
9098
|
+
if (inCollection && (allowFunctions || allowedFunctionNames.includes(funcName))) {
|
|
9099
|
+
throw collectionError(key, "a function", path2);
|
|
9100
|
+
}
|
|
8391
9101
|
if (allowedFunctionNames.includes(funcName)) {
|
|
8392
9102
|
return;
|
|
8393
9103
|
}
|
|
@@ -8414,35 +9124,89 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
|
|
|
8414
9124
|
}
|
|
8415
9125
|
if (type === "object") {
|
|
8416
9126
|
const obj = value;
|
|
8417
|
-
|
|
9127
|
+
const seen = inCollection ? collectionVisited : visited;
|
|
9128
|
+
if (seen.has(obj)) {
|
|
8418
9129
|
return;
|
|
8419
9130
|
}
|
|
8420
|
-
|
|
9131
|
+
seen.add(obj);
|
|
9132
|
+
const opaque = describeOpaqueContainer(obj);
|
|
9133
|
+
if (opaque) {
|
|
9134
|
+
throw new Error(
|
|
9135
|
+
`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.`
|
|
9136
|
+
);
|
|
9137
|
+
}
|
|
9138
|
+
const isArray = Array.isArray(obj);
|
|
9139
|
+
const isMap = types.isMap(obj);
|
|
9140
|
+
const isSet = types.isSet(obj);
|
|
9141
|
+
if (isArray) {
|
|
9142
|
+
const hidden = types.isProxy(obj) ? "a Proxy array" : ObjectGetPrototypeOf(obj) !== ArrayPrototype ? "an array with a custom prototype" : void 0;
|
|
9143
|
+
if (hidden) {
|
|
9144
|
+
throw new Error(
|
|
9145
|
+
`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.`
|
|
9146
|
+
);
|
|
9147
|
+
}
|
|
9148
|
+
}
|
|
9149
|
+
if (inCollection) {
|
|
9150
|
+
if (types.isProxy(obj)) {
|
|
9151
|
+
throw collectionError(key, "a Proxy", path2);
|
|
9152
|
+
}
|
|
9153
|
+
if (!isArray && !isMap && !isSet && !isPlainDataObject(obj)) {
|
|
9154
|
+
throw collectionError(key, describeInstance(obj), path2);
|
|
9155
|
+
}
|
|
9156
|
+
if ((isMap || isSet) && ObjectGetPrototypeOf(obj) !== (isMap ? MapPrototype : SetPrototype)) {
|
|
9157
|
+
throw collectionError(key, describeInstance(obj), path2);
|
|
9158
|
+
}
|
|
9159
|
+
}
|
|
8421
9160
|
if (!allowGettersSetters) {
|
|
8422
|
-
const
|
|
8423
|
-
|
|
8424
|
-
if (desc.get || desc.set) {
|
|
9161
|
+
for (const prop of ReflectOwnKeys(obj)) {
|
|
9162
|
+
const desc = ReflectGetOwnPropertyDescriptor(obj, prop);
|
|
9163
|
+
if (desc && (desc.get || desc.set)) {
|
|
9164
|
+
const at = [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`].join(".");
|
|
8425
9165
|
throw new Error(
|
|
8426
|
-
`Custom global "${key}" has a getter/setter at ${
|
|
9166
|
+
`Custom global "${key}" has a getter/setter at ${at}. Getters and setters are not allowed because they can execute arbitrary code on property access. Use allowGettersSetters: true if you understand the security implications.`
|
|
8427
9167
|
);
|
|
8428
9168
|
}
|
|
8429
9169
|
}
|
|
8430
9170
|
}
|
|
8431
|
-
if (
|
|
8432
|
-
|
|
8433
|
-
|
|
9171
|
+
if (isMap) {
|
|
9172
|
+
let index = 0;
|
|
9173
|
+
for (const [mapKey, mapValue] of ReflectApply(MapEntries, obj, [])) {
|
|
9174
|
+
validateGlobalValue(key, mapKey, options, [...path2, `keys()[${index}]`], visited, collectionVisited, true);
|
|
9175
|
+
validateGlobalValue(
|
|
9176
|
+
key,
|
|
9177
|
+
mapValue,
|
|
9178
|
+
options,
|
|
9179
|
+
[...path2, mapValueSegment(mapKey, index)],
|
|
9180
|
+
visited,
|
|
9181
|
+
collectionVisited,
|
|
9182
|
+
true
|
|
9183
|
+
);
|
|
9184
|
+
index++;
|
|
9185
|
+
}
|
|
9186
|
+
} else if (isSet) {
|
|
9187
|
+
let index = 0;
|
|
9188
|
+
for (const element of ReflectApply(SetValues, obj, [])) {
|
|
9189
|
+
validateGlobalValue(key, element, options, [...path2, `values()[${index}]`], visited, collectionVisited, true);
|
|
9190
|
+
index++;
|
|
8434
9191
|
}
|
|
8435
|
-
return;
|
|
8436
9192
|
}
|
|
8437
|
-
const keys = Object.keys(obj);
|
|
9193
|
+
const keys = isArray || inCollection ? ReflectOwnKeys(obj) : Object.keys(obj);
|
|
8438
9194
|
for (const prop of keys) {
|
|
8439
|
-
if (DANGEROUS_GLOBAL_KEYS.has(prop)) {
|
|
9195
|
+
if (typeof prop === "string" && DANGEROUS_GLOBAL_KEYS.has(prop)) {
|
|
8440
9196
|
throw new Error(
|
|
8441
9197
|
`Custom global "${key}" contains dangerous key "${prop}" at ${path2.join(".") || "root"}. Keys like "__proto__", "constructor", and "prototype" are not allowed.`
|
|
8442
9198
|
);
|
|
8443
9199
|
}
|
|
8444
9200
|
const propValue = obj[prop];
|
|
8445
|
-
validateGlobalValue(
|
|
9201
|
+
validateGlobalValue(
|
|
9202
|
+
key,
|
|
9203
|
+
propValue,
|
|
9204
|
+
options,
|
|
9205
|
+
[...path2, typeof prop === "string" ? prop : `[${String(prop)}]`],
|
|
9206
|
+
visited,
|
|
9207
|
+
collectionVisited,
|
|
9208
|
+
inCollection || isArray
|
|
9209
|
+
);
|
|
8446
9210
|
}
|
|
8447
9211
|
return;
|
|
8448
9212
|
}
|
|
@@ -10336,6 +11100,8 @@ function createScoringGate(config) {
|
|
|
10336
11100
|
}
|
|
10337
11101
|
|
|
10338
11102
|
// libs/core/src/enclave.ts
|
|
11103
|
+
init_global_function_gate();
|
|
11104
|
+
init_stack_trace();
|
|
10339
11105
|
var DEFAULT_SECURITY_LEVEL = "STANDARD";
|
|
10340
11106
|
var DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
10341
11107
|
function getConfigFromSecurityLevel(securityLevel, options) {
|
|
@@ -10390,6 +11156,7 @@ var Enclave = class {
|
|
|
10390
11156
|
scoringGate;
|
|
10391
11157
|
doubleVmConfig;
|
|
10392
11158
|
customGlobalNames;
|
|
11159
|
+
toolNamespaces;
|
|
10393
11160
|
adapter;
|
|
10394
11161
|
constructor(options = {}) {
|
|
10395
11162
|
this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
|
|
@@ -10445,6 +11212,12 @@ var Enclave = class {
|
|
|
10445
11212
|
}
|
|
10446
11213
|
};
|
|
10447
11214
|
}
|
|
11215
|
+
this.toolNamespaces = normalizeToolNamespaces(options.toolNamespaces, {
|
|
11216
|
+
reservedNames: Object.keys(initialGlobals)
|
|
11217
|
+
});
|
|
11218
|
+
if (options.maxGlobalFunctionCalls !== void 0 && !(Number.isInteger(options.maxGlobalFunctionCalls) && options.maxGlobalFunctionCalls >= 0)) {
|
|
11219
|
+
throw new TypeError("maxGlobalFunctionCalls must be a non-negative integer");
|
|
11220
|
+
}
|
|
10448
11221
|
this.config = {
|
|
10449
11222
|
...BASE_CONFIG,
|
|
10450
11223
|
timeout: securityConfig.timeout,
|
|
@@ -10459,9 +11232,13 @@ var Enclave = class {
|
|
|
10459
11232
|
toolBridge: normalizedToolBridge,
|
|
10460
11233
|
// secureProxyConfig must come AFTER options spread to use the merged config
|
|
10461
11234
|
secureProxyConfig: securityConfig.secureProxyConfig,
|
|
10462
|
-
globals: initialGlobals
|
|
11235
|
+
globals: initialGlobals,
|
|
11236
|
+
maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls({
|
|
11237
|
+
maxToolCalls: securityConfig.maxToolCalls,
|
|
11238
|
+
maxGlobalFunctionCalls: options.maxGlobalFunctionCalls
|
|
11239
|
+
})
|
|
10463
11240
|
};
|
|
10464
|
-
this.customGlobalNames = Object.keys(initialGlobals);
|
|
11241
|
+
this.customGlobalNames = [...Object.keys(initialGlobals), ...this.toolNamespaces.map((ns) => ns.name)];
|
|
10465
11242
|
const customAllowedGlobals = this.customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
|
|
10466
11243
|
this.validator = this.createValidator(presetName, customAllowedGlobals);
|
|
10467
11244
|
this.validateCode = options.validate !== false;
|
|
@@ -10505,11 +11282,31 @@ var Enclave = class {
|
|
|
10505
11282
|
/**
|
|
10506
11283
|
* Execute AgentScript code
|
|
10507
11284
|
*
|
|
11285
|
+
* Every error returned obeys `sanitizeStackTraces`, whichever stage raised it.
|
|
11286
|
+
*
|
|
10508
11287
|
* @param code AgentScript code to execute
|
|
10509
11288
|
* @param toolHandler Optional tool handler (overrides constructor config)
|
|
10510
11289
|
* @returns Execution result
|
|
10511
11290
|
*/
|
|
10512
11291
|
async run(code, toolHandler) {
|
|
11292
|
+
const result = await this.execute(code, toolHandler);
|
|
11293
|
+
return this.applyStackTracePolicy(result);
|
|
11294
|
+
}
|
|
11295
|
+
/**
|
|
11296
|
+
* Single exit for returned errors: with `sanitizeStackTraces` on, strip host paths, file
|
|
11297
|
+
* locations and frames from the stack, whichever stage (validation, transform, compile,
|
|
11298
|
+
* execution, tool call) and adapter produced the error.
|
|
11299
|
+
*/
|
|
11300
|
+
applyStackTracePolicy(result) {
|
|
11301
|
+
if (result.success || !result.error?.stack || !this.config.sanitizeStackTraces) {
|
|
11302
|
+
return result;
|
|
11303
|
+
}
|
|
11304
|
+
return { ...result, error: { ...result.error, stack: sanitizeStackTrace(result.error.stack, true) } };
|
|
11305
|
+
}
|
|
11306
|
+
/**
|
|
11307
|
+
* Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
|
|
11308
|
+
*/
|
|
11309
|
+
async execute(code, toolHandler) {
|
|
10513
11310
|
const startTime = Date.now();
|
|
10514
11311
|
const stats = {
|
|
10515
11312
|
duration: 0,
|
|
@@ -10594,7 +11391,8 @@ ${errorMessages}`,
|
|
|
10594
11391
|
toolHandler: toolHandler || this.config.toolHandler,
|
|
10595
11392
|
sidecar,
|
|
10596
11393
|
referenceConfig: this.referenceConfig,
|
|
10597
|
-
secureProxyConfig: this.config.secureProxyConfig
|
|
11394
|
+
secureProxyConfig: this.config.secureProxyConfig,
|
|
11395
|
+
toolNamespaces: this.toolNamespaces
|
|
10598
11396
|
};
|
|
10599
11397
|
const timeoutId = setTimeout(() => {
|
|
10600
11398
|
context.aborted = true;
|
|
@@ -11472,6 +12270,7 @@ function applyBinary(op, l, r) {
|
|
|
11472
12270
|
}
|
|
11473
12271
|
|
|
11474
12272
|
// libs/core/src/adapters/interpreter-adapter.ts
|
|
12273
|
+
init_stack_trace();
|
|
11475
12274
|
var SAFE_GLOBALS = Object.freeze({ Math, JSON });
|
|
11476
12275
|
var DEFAULT_MAX_STEPS = 5e6;
|
|
11477
12276
|
var DEFAULT_MAX_CALL_DEPTH = 256;
|
|
@@ -11482,6 +12281,7 @@ var InterpreterAdapter = class {
|
|
|
11482
12281
|
async execute(code, context) {
|
|
11483
12282
|
const startTime = Date.now();
|
|
11484
12283
|
let toolCallCount = 0;
|
|
12284
|
+
const sanitizeStacks = context.config.sanitizeStackTraces === true;
|
|
11485
12285
|
const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
|
|
11486
12286
|
const toolHandler = context.toolHandler ?? context.config.toolHandler;
|
|
11487
12287
|
const __safe_callTool = async (name, args) => {
|
|
@@ -11498,7 +12298,7 @@ var InterpreterAdapter = class {
|
|
|
11498
12298
|
try {
|
|
11499
12299
|
program = acorn3.parse(code, { ecmaVersion: "latest", sourceType: "script" });
|
|
11500
12300
|
} catch (error) {
|
|
11501
|
-
return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
|
|
12301
|
+
return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
|
|
11502
12302
|
}
|
|
11503
12303
|
const timeout = context.config.timeout;
|
|
11504
12304
|
const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
|
|
@@ -11523,6 +12323,7 @@ var InterpreterAdapter = class {
|
|
|
11523
12323
|
startTime,
|
|
11524
12324
|
toolCallCount,
|
|
11525
12325
|
interpreter.stepCount,
|
|
12326
|
+
sanitizeStacks,
|
|
11526
12327
|
"TimeoutError",
|
|
11527
12328
|
"EXECUTION_TIMEOUT"
|
|
11528
12329
|
);
|
|
@@ -11534,7 +12335,7 @@ var InterpreterAdapter = class {
|
|
|
11534
12335
|
};
|
|
11535
12336
|
} catch (error) {
|
|
11536
12337
|
const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
|
|
11537
|
-
return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
|
|
12338
|
+
return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
|
|
11538
12339
|
} finally {
|
|
11539
12340
|
if (timer) clearTimeout(timer);
|
|
11540
12341
|
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
@@ -11546,12 +12347,13 @@ var InterpreterAdapter = class {
|
|
|
11546
12347
|
const endTime = Date.now();
|
|
11547
12348
|
return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
|
|
11548
12349
|
}
|
|
11549
|
-
fail(error, startTime, toolCallCount, iterationCount, name, code) {
|
|
12350
|
+
fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
|
|
11550
12351
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
12352
|
+
const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
|
|
11551
12353
|
const execError = {
|
|
11552
12354
|
message: err.message,
|
|
11553
12355
|
name: name ?? err.name,
|
|
11554
|
-
...
|
|
12356
|
+
...stack ? { stack } : {},
|
|
11555
12357
|
...code ? { code } : {}
|
|
11556
12358
|
};
|
|
11557
12359
|
return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
|