@inkeep/agents-run-api 0.0.0-chat-to-edit-20251119071712

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.
@@ -0,0 +1,948 @@
1
+ import { getLogger } from './chunk-A2S7GSHL.js';
2
+ import { FUNCTION_TOOL_SANDBOX_POOL_TTL_MS, FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT, FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS, FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT, FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES, FUNCTION_TOOL_SANDBOX_QUEUE_WAIT_TIMEOUT_MS } from './chunk-IVALDC72.js';
3
+ import { __publicField } from './chunk-PKBMQBKP.js';
4
+ import { spawn } from 'child_process';
5
+ import crypto, { createHash } from 'crypto';
6
+ import { mkdirSync, existsSync, rmSync, writeFileSync } from 'fs';
7
+ import { tmpdir } from 'os';
8
+ import { join } from 'path';
9
+ import { Sandbox } from '@vercel/sandbox';
10
+
11
+ // src/tools/sandbox-utils.ts
12
+ function createExecutionWrapper(executeCode, args) {
13
+ return `
14
+ // Function tool execution wrapper
15
+ const args = ${JSON.stringify(args, null, 2)};
16
+
17
+ // User's function code
18
+ const execute = ${executeCode}
19
+
20
+ // Execute the function and output the result
21
+ (async () => {
22
+ try {
23
+ const result = await execute(args);
24
+ // Output result as JSON on the last line
25
+ console.log(JSON.stringify({ success: true, result }));
26
+ } catch (error) {
27
+ console.error(JSON.stringify({
28
+ success: false,
29
+ error: error instanceof Error ? error.message : String(error)
30
+ }));
31
+ process.exit(1);
32
+ }
33
+ })();
34
+ `;
35
+ }
36
+ function parseExecutionResult(stdout, functionId, logger4) {
37
+ try {
38
+ const outputLines = stdout.split("\n").filter((line) => line.trim());
39
+ const resultLine = outputLines[outputLines.length - 1];
40
+ return JSON.parse(resultLine);
41
+ } catch (parseError) {
42
+ if (logger4) {
43
+ logger4.warn(
44
+ {
45
+ functionId,
46
+ stdout,
47
+ parseError
48
+ },
49
+ "Failed to parse execution result"
50
+ );
51
+ }
52
+ return stdout;
53
+ }
54
+ }
55
+
56
+ // src/tools/NativeSandboxExecutor.ts
57
+ var logger = getLogger("native-sandbox-executor");
58
+ var ExecutionSemaphore = class {
59
+ constructor(permits, maxWaitTimeMs = FUNCTION_TOOL_SANDBOX_QUEUE_WAIT_TIMEOUT_MS) {
60
+ __publicField(this, "permits");
61
+ __publicField(this, "waitQueue", []);
62
+ __publicField(this, "maxWaitTime");
63
+ this.permits = Math.max(1, permits);
64
+ this.maxWaitTime = maxWaitTimeMs;
65
+ }
66
+ async acquire(fn) {
67
+ await new Promise((resolve, reject) => {
68
+ if (this.permits > 0) {
69
+ this.permits--;
70
+ resolve();
71
+ return;
72
+ }
73
+ const timeoutId = setTimeout(() => {
74
+ const index = this.waitQueue.findIndex((item) => item.resolve === resolve);
75
+ if (index !== -1) {
76
+ this.waitQueue.splice(index, 1);
77
+ reject(
78
+ new Error(
79
+ `Function execution queue timeout after ${this.maxWaitTime}ms. Too many concurrent executions.`
80
+ )
81
+ );
82
+ }
83
+ }, this.maxWaitTime);
84
+ this.waitQueue.push({
85
+ resolve: () => {
86
+ clearTimeout(timeoutId);
87
+ this.permits--;
88
+ resolve();
89
+ },
90
+ reject
91
+ });
92
+ });
93
+ try {
94
+ return await fn();
95
+ } finally {
96
+ this.permits++;
97
+ const next = this.waitQueue.shift();
98
+ if (next) {
99
+ next.resolve();
100
+ }
101
+ }
102
+ }
103
+ getAvailablePermits() {
104
+ return this.permits;
105
+ }
106
+ getQueueLength() {
107
+ return this.waitQueue.length;
108
+ }
109
+ };
110
+ var _NativeSandboxExecutor = class _NativeSandboxExecutor {
111
+ constructor() {
112
+ __publicField(this, "tempDir");
113
+ __publicField(this, "sandboxPool", {});
114
+ __publicField(this, "executionSemaphores", /* @__PURE__ */ new Map());
115
+ this.tempDir = join(tmpdir(), "inkeep-sandboxes");
116
+ this.ensureTempDir();
117
+ this.startPoolCleanup();
118
+ }
119
+ static getInstance() {
120
+ if (!_NativeSandboxExecutor.instance) {
121
+ _NativeSandboxExecutor.instance = new _NativeSandboxExecutor();
122
+ }
123
+ return _NativeSandboxExecutor.instance;
124
+ }
125
+ getSemaphore(vcpus) {
126
+ const effectiveVcpus = Math.max(1, vcpus || 1);
127
+ if (!this.executionSemaphores.has(effectiveVcpus)) {
128
+ logger.debug({ vcpus: effectiveVcpus }, "Creating new execution semaphore");
129
+ this.executionSemaphores.set(effectiveVcpus, new ExecutionSemaphore(effectiveVcpus));
130
+ }
131
+ const semaphore = this.executionSemaphores.get(effectiveVcpus);
132
+ if (!semaphore) {
133
+ throw new Error(`Failed to create semaphore for ${effectiveVcpus} vCPUs`);
134
+ }
135
+ return semaphore;
136
+ }
137
+ getExecutionStats() {
138
+ const stats = {};
139
+ for (const [vcpus, semaphore] of this.executionSemaphores.entries()) {
140
+ stats[`vcpu_${vcpus}`] = {
141
+ availablePermits: semaphore.getAvailablePermits(),
142
+ queueLength: semaphore.getQueueLength()
143
+ };
144
+ }
145
+ return stats;
146
+ }
147
+ ensureTempDir() {
148
+ try {
149
+ mkdirSync(this.tempDir, { recursive: true });
150
+ } catch {
151
+ }
152
+ }
153
+ generateDependencyHash(dependencies) {
154
+ const sortedDeps = Object.keys(dependencies).sort().map((key) => `${key}@${dependencies[key]}`).join(",");
155
+ return createHash("sha256").update(sortedDeps).digest("hex").substring(0, 16);
156
+ }
157
+ getCachedSandbox(dependencyHash) {
158
+ const poolKey = dependencyHash;
159
+ const sandbox = this.sandboxPool[poolKey];
160
+ if (sandbox && existsSync(sandbox.sandboxDir)) {
161
+ const now = Date.now();
162
+ if (now - sandbox.lastUsed < FUNCTION_TOOL_SANDBOX_POOL_TTL_MS && sandbox.useCount < FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
163
+ sandbox.lastUsed = now;
164
+ sandbox.useCount++;
165
+ logger.debug(
166
+ {
167
+ poolKey,
168
+ useCount: sandbox.useCount,
169
+ sandboxDir: sandbox.sandboxDir,
170
+ lastUsed: new Date(sandbox.lastUsed)
171
+ },
172
+ "Reusing cached sandbox"
173
+ );
174
+ return sandbox.sandboxDir;
175
+ } else {
176
+ this.cleanupSandbox(sandbox.sandboxDir);
177
+ delete this.sandboxPool[poolKey];
178
+ }
179
+ }
180
+ return null;
181
+ }
182
+ addToPool(dependencyHash, sandboxDir, dependencies) {
183
+ const poolKey = dependencyHash;
184
+ if (this.sandboxPool[poolKey]) {
185
+ this.cleanupSandbox(this.sandboxPool[poolKey].sandboxDir);
186
+ }
187
+ this.sandboxPool[poolKey] = {
188
+ sandboxDir,
189
+ lastUsed: Date.now(),
190
+ useCount: 1,
191
+ dependencies
192
+ };
193
+ logger.debug({ poolKey, sandboxDir }, "Added sandbox to pool");
194
+ }
195
+ cleanupSandbox(sandboxDir) {
196
+ try {
197
+ rmSync(sandboxDir, { recursive: true, force: true });
198
+ logger.debug({ sandboxDir }, "Cleaned up sandbox");
199
+ } catch (error) {
200
+ logger.warn({ sandboxDir, error }, "Failed to clean up sandbox");
201
+ }
202
+ }
203
+ startPoolCleanup() {
204
+ setInterval(() => {
205
+ const now = Date.now();
206
+ const keysToDelete = [];
207
+ for (const [key, sandbox] of Object.entries(this.sandboxPool)) {
208
+ if (now - sandbox.lastUsed > FUNCTION_TOOL_SANDBOX_POOL_TTL_MS || sandbox.useCount >= FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
209
+ this.cleanupSandbox(sandbox.sandboxDir);
210
+ keysToDelete.push(key);
211
+ }
212
+ }
213
+ keysToDelete.forEach((key) => {
214
+ delete this.sandboxPool[key];
215
+ });
216
+ if (keysToDelete.length > 0) {
217
+ logger.debug({ cleanedCount: keysToDelete.length }, "Cleaned up expired sandboxes");
218
+ }
219
+ }, FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS);
220
+ }
221
+ detectModuleType(executeCode, configuredRuntime) {
222
+ const esmPatterns = [
223
+ /import\s+.*\s+from\s+['"]/g,
224
+ // import ... from '...'
225
+ /import\s*\(/g,
226
+ // import(...)
227
+ /export\s+(default|const|let|var|function|class)/g,
228
+ // export statements
229
+ /export\s*\{/g
230
+ // export { ... }
231
+ ];
232
+ const cjsPatterns = [
233
+ /require\s*\(/g,
234
+ // require(...)
235
+ /module\.exports/g,
236
+ // module.exports
237
+ /exports\./g
238
+ // exports.something
239
+ ];
240
+ const hasEsmSyntax = esmPatterns.some((pattern) => pattern.test(executeCode));
241
+ const hasCjsSyntax = cjsPatterns.some((pattern) => pattern.test(executeCode));
242
+ if (configuredRuntime === "typescript") {
243
+ return hasCjsSyntax ? "cjs" : "esm";
244
+ }
245
+ if (hasEsmSyntax && hasCjsSyntax) {
246
+ logger.warn(
247
+ { executeCode: `${executeCode.substring(0, 100)}...` },
248
+ "Both ESM and CommonJS syntax detected, defaulting to ESM"
249
+ );
250
+ return "esm";
251
+ }
252
+ if (hasEsmSyntax) {
253
+ return "esm";
254
+ }
255
+ if (hasCjsSyntax) {
256
+ return "cjs";
257
+ }
258
+ return "cjs";
259
+ }
260
+ async executeFunctionTool(toolId, args, config) {
261
+ const vcpus = config.sandboxConfig?.vcpus || 1;
262
+ const semaphore = this.getSemaphore(vcpus);
263
+ logger.debug(
264
+ {
265
+ toolId,
266
+ vcpus,
267
+ availablePermits: semaphore.getAvailablePermits(),
268
+ queueLength: semaphore.getQueueLength(),
269
+ sandboxConfig: config.sandboxConfig,
270
+ poolSize: Object.keys(this.sandboxPool).length
271
+ },
272
+ "Acquiring execution slot for function tool"
273
+ );
274
+ return semaphore.acquire(async () => {
275
+ return this.executeInSandbox_Internal(toolId, args, config);
276
+ });
277
+ }
278
+ async executeInSandbox_Internal(toolId, args, config) {
279
+ const dependencies = config.dependencies || {};
280
+ const dependencyHash = this.generateDependencyHash(dependencies);
281
+ logger.debug(
282
+ {
283
+ toolId,
284
+ dependencies,
285
+ dependencyHash,
286
+ sandboxConfig: config.sandboxConfig,
287
+ poolSize: Object.keys(this.sandboxPool).length
288
+ },
289
+ "Executing function tool"
290
+ );
291
+ let sandboxDir = this.getCachedSandbox(dependencyHash);
292
+ let isNewSandbox = false;
293
+ if (!sandboxDir) {
294
+ sandboxDir = join(this.tempDir, `sandbox-${dependencyHash}-${Date.now()}`);
295
+ mkdirSync(sandboxDir, { recursive: true });
296
+ isNewSandbox = true;
297
+ logger.debug(
298
+ {
299
+ toolId,
300
+ dependencyHash,
301
+ sandboxDir,
302
+ dependencies
303
+ },
304
+ "Creating new sandbox"
305
+ );
306
+ const moduleType = this.detectModuleType(config.executeCode, config.sandboxConfig?.runtime);
307
+ const packageJson = {
308
+ name: `function-tool-${toolId}`,
309
+ version: "1.0.0",
310
+ ...moduleType === "esm" && { type: "module" },
311
+ dependencies,
312
+ scripts: {
313
+ start: moduleType === "esm" ? "node index.mjs" : "node index.js"
314
+ }
315
+ };
316
+ writeFileSync(join(sandboxDir, "package.json"), JSON.stringify(packageJson, null, 2), "utf8");
317
+ if (Object.keys(dependencies).length > 0) {
318
+ await this.installDependencies(sandboxDir);
319
+ }
320
+ this.addToPool(dependencyHash, sandboxDir, dependencies);
321
+ }
322
+ try {
323
+ const moduleType = this.detectModuleType(config.executeCode, config.sandboxConfig?.runtime);
324
+ const executionCode = createExecutionWrapper(config.executeCode, args);
325
+ const fileExtension = moduleType === "esm" ? "mjs" : "js";
326
+ writeFileSync(join(sandboxDir, `index.${fileExtension}`), executionCode, "utf8");
327
+ const result = await this.executeInSandbox(
328
+ sandboxDir,
329
+ config.sandboxConfig?.timeout || FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT,
330
+ moduleType,
331
+ config.sandboxConfig
332
+ );
333
+ return result;
334
+ } catch (error) {
335
+ if (isNewSandbox) {
336
+ this.cleanupSandbox(sandboxDir);
337
+ const poolKey = dependencyHash;
338
+ delete this.sandboxPool[poolKey];
339
+ }
340
+ throw error;
341
+ }
342
+ }
343
+ async installDependencies(sandboxDir) {
344
+ return new Promise((resolve, reject) => {
345
+ const npmEnv = {
346
+ ...process.env,
347
+ npm_config_cache: join(sandboxDir, ".npm-cache"),
348
+ npm_config_logs_dir: join(sandboxDir, ".npm-logs"),
349
+ npm_config_tmp: join(sandboxDir, ".npm-tmp"),
350
+ HOME: sandboxDir,
351
+ npm_config_update_notifier: "false",
352
+ npm_config_progress: "false",
353
+ npm_config_loglevel: "error"
354
+ };
355
+ const npm = spawn("npm", ["install", "--no-audit", "--no-fund"], {
356
+ cwd: sandboxDir,
357
+ stdio: "pipe",
358
+ env: npmEnv
359
+ });
360
+ let stderr = "";
361
+ npm.stdout?.on("data", () => {
362
+ });
363
+ npm.stderr?.on("data", (data) => {
364
+ stderr += data.toString();
365
+ });
366
+ npm.on("close", (code) => {
367
+ if (code === 0) {
368
+ logger.debug({ sandboxDir }, "Dependencies installed successfully");
369
+ resolve();
370
+ } else {
371
+ logger.error({ sandboxDir, code, stderr }, "Failed to install dependencies");
372
+ reject(new Error(`npm install failed with code ${code}: ${stderr}`));
373
+ }
374
+ });
375
+ npm.on("error", (err) => {
376
+ logger.error({ sandboxDir, error: err }, "Failed to spawn npm install");
377
+ reject(err);
378
+ });
379
+ });
380
+ }
381
+ async executeInSandbox(sandboxDir, timeout, moduleType, _sandboxConfig) {
382
+ return new Promise((resolve, reject) => {
383
+ const fileExtension = moduleType === "esm" ? "mjs" : "js";
384
+ const spawnOptions = {
385
+ cwd: sandboxDir,
386
+ stdio: "pipe",
387
+ uid: process.getuid ? process.getuid() : void 0,
388
+ gid: process.getgid ? process.getgid() : void 0
389
+ };
390
+ const node = spawn("node", [`index.${fileExtension}`], spawnOptions);
391
+ let stdout = "";
392
+ let stderr = "";
393
+ let outputSize = 0;
394
+ node.stdout?.on("data", (data) => {
395
+ const dataStr = data.toString();
396
+ outputSize += dataStr.length;
397
+ if (outputSize > FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES) {
398
+ node.kill("SIGTERM");
399
+ reject(
400
+ new Error(
401
+ `Output size exceeded limit of ${FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES} bytes`
402
+ )
403
+ );
404
+ return;
405
+ }
406
+ stdout += dataStr;
407
+ });
408
+ node.stderr?.on("data", (data) => {
409
+ const dataStr = data.toString();
410
+ outputSize += dataStr.length;
411
+ if (outputSize > FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES) {
412
+ node.kill("SIGTERM");
413
+ reject(
414
+ new Error(
415
+ `Output size exceeded limit of ${FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES} bytes`
416
+ )
417
+ );
418
+ return;
419
+ }
420
+ stderr += dataStr;
421
+ });
422
+ const timeoutId = setTimeout(() => {
423
+ logger.warn({ sandboxDir, timeout }, "Function execution timed out, killing process");
424
+ node.kill("SIGTERM");
425
+ const forceKillTimeout = Math.min(Math.max(timeout / 10, 2e3), 5e3);
426
+ setTimeout(() => {
427
+ try {
428
+ node.kill("SIGKILL");
429
+ } catch {
430
+ }
431
+ }, forceKillTimeout);
432
+ reject(new Error(`Function execution timed out after ${timeout}ms`));
433
+ }, timeout);
434
+ node.on("close", (code, signal) => {
435
+ clearTimeout(timeoutId);
436
+ if (code === 0) {
437
+ try {
438
+ const result = parseExecutionResult(stdout, "function", logger);
439
+ if (typeof result === "object" && result !== null && "success" in result) {
440
+ const parsed = result;
441
+ if (parsed.success) {
442
+ resolve(parsed.result);
443
+ } else {
444
+ reject(new Error(parsed.error || "Function execution failed"));
445
+ }
446
+ } else {
447
+ resolve(result);
448
+ }
449
+ } catch (parseError) {
450
+ logger.error({ stdout, stderr, parseError }, "Failed to parse function result");
451
+ reject(new Error(`Invalid function result: ${stdout}`));
452
+ }
453
+ } else {
454
+ const errorMsg = signal ? `Function execution killed by signal ${signal}: ${stderr}` : `Function execution failed with code ${code}: ${stderr}`;
455
+ logger.error({ code, signal, stderr }, "Function execution failed");
456
+ reject(new Error(errorMsg));
457
+ }
458
+ });
459
+ node.on("error", (error) => {
460
+ clearTimeout(timeoutId);
461
+ logger.error({ sandboxDir, error }, "Failed to spawn node process");
462
+ reject(error);
463
+ });
464
+ });
465
+ }
466
+ };
467
+ __publicField(_NativeSandboxExecutor, "instance", null);
468
+ var NativeSandboxExecutor = _NativeSandboxExecutor;
469
+ var logger2 = getLogger("VercelSandboxExecutor");
470
+ var _VercelSandboxExecutor = class _VercelSandboxExecutor {
471
+ constructor(config) {
472
+ __publicField(this, "config");
473
+ __publicField(this, "sandboxPool", /* @__PURE__ */ new Map());
474
+ __publicField(this, "cleanupInterval", null);
475
+ this.config = config;
476
+ logger2.info(
477
+ {
478
+ teamId: config.teamId,
479
+ projectId: config.projectId,
480
+ runtime: config.runtime,
481
+ timeout: config.timeout,
482
+ vcpus: config.vcpus
483
+ },
484
+ "VercelSandboxExecutor initialized with pooling"
485
+ );
486
+ this.startPoolCleanup();
487
+ }
488
+ /**
489
+ * Get singleton instance of VercelSandboxExecutor
490
+ */
491
+ static getInstance(config) {
492
+ if (!_VercelSandboxExecutor.instance) {
493
+ _VercelSandboxExecutor.instance = new _VercelSandboxExecutor(config);
494
+ }
495
+ return _VercelSandboxExecutor.instance;
496
+ }
497
+ /**
498
+ * Generate a hash for dependencies to use as cache key
499
+ */
500
+ generateDependencyHash(dependencies) {
501
+ const sorted = Object.keys(dependencies).sort().map((key) => `${key}@${dependencies[key]}`).join(",");
502
+ return crypto.createHash("md5").update(sorted).digest("hex").substring(0, 8);
503
+ }
504
+ /**
505
+ * Get a cached sandbox if available and still valid
506
+ */
507
+ getCachedSandbox(dependencyHash) {
508
+ const cached = this.sandboxPool.get(dependencyHash);
509
+ if (!cached) return null;
510
+ const now = Date.now();
511
+ const age = now - cached.createdAt;
512
+ if (age > FUNCTION_TOOL_SANDBOX_POOL_TTL_MS || cached.useCount >= FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
513
+ logger2.debug(
514
+ {
515
+ dependencyHash,
516
+ age,
517
+ useCount: cached.useCount,
518
+ ttl: FUNCTION_TOOL_SANDBOX_POOL_TTL_MS,
519
+ maxUseCount: FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT
520
+ },
521
+ "Sandbox expired, will create new one"
522
+ );
523
+ this.removeSandbox(dependencyHash);
524
+ return null;
525
+ }
526
+ logger2.debug(
527
+ {
528
+ dependencyHash,
529
+ useCount: cached.useCount,
530
+ age
531
+ },
532
+ "Reusing cached sandbox"
533
+ );
534
+ return cached.sandbox;
535
+ }
536
+ /**
537
+ * Add sandbox to pool
538
+ */
539
+ addToPool(dependencyHash, sandbox, dependencies) {
540
+ this.sandboxPool.set(dependencyHash, {
541
+ sandbox,
542
+ createdAt: Date.now(),
543
+ useCount: 0,
544
+ dependencies
545
+ });
546
+ logger2.debug(
547
+ {
548
+ dependencyHash,
549
+ poolSize: this.sandboxPool.size
550
+ },
551
+ "Sandbox added to pool"
552
+ );
553
+ }
554
+ /**
555
+ * Increment use count for a sandbox
556
+ */
557
+ incrementUseCount(dependencyHash) {
558
+ const cached = this.sandboxPool.get(dependencyHash);
559
+ if (cached) {
560
+ cached.useCount++;
561
+ }
562
+ }
563
+ /**
564
+ * Remove and clean up a sandbox
565
+ */
566
+ async removeSandbox(dependencyHash) {
567
+ const cached = this.sandboxPool.get(dependencyHash);
568
+ if (cached) {
569
+ try {
570
+ await cached.sandbox.stop();
571
+ logger2.debug({ dependencyHash }, "Sandbox stopped");
572
+ } catch (error) {
573
+ logger2.warn({ error, dependencyHash }, "Error stopping sandbox");
574
+ }
575
+ this.sandboxPool.delete(dependencyHash);
576
+ }
577
+ }
578
+ /**
579
+ * Start periodic cleanup of expired sandboxes
580
+ */
581
+ startPoolCleanup() {
582
+ this.cleanupInterval = setInterval(() => {
583
+ const now = Date.now();
584
+ const toRemove = [];
585
+ for (const [hash, cached] of this.sandboxPool.entries()) {
586
+ const age = now - cached.createdAt;
587
+ if (age > FUNCTION_TOOL_SANDBOX_POOL_TTL_MS || cached.useCount >= FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
588
+ toRemove.push(hash);
589
+ }
590
+ }
591
+ if (toRemove.length > 0) {
592
+ logger2.info(
593
+ {
594
+ count: toRemove.length,
595
+ poolSize: this.sandboxPool.size
596
+ },
597
+ "Cleaning up expired sandboxes"
598
+ );
599
+ for (const hash of toRemove) {
600
+ this.removeSandbox(hash);
601
+ }
602
+ }
603
+ }, FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS);
604
+ }
605
+ /**
606
+ * Cleanup all sandboxes and stop cleanup interval
607
+ */
608
+ async cleanup() {
609
+ if (this.cleanupInterval) {
610
+ clearInterval(this.cleanupInterval);
611
+ this.cleanupInterval = null;
612
+ }
613
+ logger2.info(
614
+ {
615
+ poolSize: this.sandboxPool.size
616
+ },
617
+ "Cleaning up all sandboxes"
618
+ );
619
+ const promises = Array.from(this.sandboxPool.keys()).map((hash) => this.removeSandbox(hash));
620
+ await Promise.all(promises);
621
+ }
622
+ /**
623
+ * Extract environment variable names from code
624
+ * Matches patterns like process.env.VAR_NAME or process.env['VAR_NAME']
625
+ */
626
+ extractEnvVars(code) {
627
+ const envVars = /* @__PURE__ */ new Set();
628
+ const dotNotationRegex = /process\.env\.([A-Z_][A-Z0-9_]*)/g;
629
+ let match = dotNotationRegex.exec(code);
630
+ while (match !== null) {
631
+ envVars.add(match[1]);
632
+ match = dotNotationRegex.exec(code);
633
+ }
634
+ const bracketNotationRegex = /process\.env\[['"]([A-Z_][A-Z0-9_]*)['"]\]/g;
635
+ match = bracketNotationRegex.exec(code);
636
+ while (match !== null) {
637
+ envVars.add(match[1]);
638
+ match = bracketNotationRegex.exec(code);
639
+ }
640
+ return envVars;
641
+ }
642
+ /**
643
+ * Create .env file content from environment variables
644
+ * Note: Currently creates empty placeholders. Values will be populated in the future.
645
+ */
646
+ createEnvFileContent(envVarNames) {
647
+ const envLines = [];
648
+ for (const varName of envVarNames) {
649
+ envLines.push(`${varName}=""`);
650
+ logger2.debug({ varName }, "Adding environment variable placeholder to sandbox");
651
+ }
652
+ return envLines.join("\n");
653
+ }
654
+ /**
655
+ * Execute a function tool in Vercel Sandbox with pooling
656
+ */
657
+ async executeFunctionTool(functionId, args, toolConfig) {
658
+ const startTime = Date.now();
659
+ const logs = [];
660
+ const dependencies = toolConfig.dependencies || {};
661
+ const dependencyHash = this.generateDependencyHash(dependencies);
662
+ try {
663
+ logger2.info(
664
+ {
665
+ functionId,
666
+ functionName: toolConfig.name,
667
+ dependencyHash,
668
+ poolSize: this.sandboxPool.size
669
+ },
670
+ "Executing function in Vercel Sandbox"
671
+ );
672
+ let sandbox = this.getCachedSandbox(dependencyHash);
673
+ let isNewSandbox = false;
674
+ if (!sandbox) {
675
+ isNewSandbox = true;
676
+ sandbox = await Sandbox.create({
677
+ token: this.config.token,
678
+ teamId: this.config.teamId,
679
+ projectId: this.config.projectId,
680
+ timeout: this.config.timeout,
681
+ resources: {
682
+ vcpus: this.config.vcpus || 1
683
+ },
684
+ runtime: this.config.runtime
685
+ });
686
+ logger2.info(
687
+ {
688
+ functionId,
689
+ sandboxId: sandbox.sandboxId,
690
+ dependencyHash
691
+ },
692
+ `New sandbox created for function ${functionId}`
693
+ );
694
+ this.addToPool(dependencyHash, sandbox, dependencies);
695
+ } else {
696
+ logger2.info(
697
+ {
698
+ functionId,
699
+ sandboxId: sandbox.sandboxId,
700
+ dependencyHash
701
+ },
702
+ `Reusing cached sandbox for function ${functionId}`
703
+ );
704
+ }
705
+ this.incrementUseCount(dependencyHash);
706
+ try {
707
+ if (isNewSandbox && toolConfig.dependencies && Object.keys(toolConfig.dependencies).length > 0) {
708
+ logger2.debug(
709
+ {
710
+ functionId,
711
+ functionName: toolConfig.name,
712
+ dependencies: toolConfig.dependencies
713
+ },
714
+ "Installing dependencies in new sandbox"
715
+ );
716
+ const packageJson = {
717
+ dependencies: toolConfig.dependencies
718
+ };
719
+ const packageJsonContent = JSON.stringify(packageJson, null, 2);
720
+ await sandbox.writeFiles([
721
+ {
722
+ path: "package.json",
723
+ content: Buffer.from(packageJsonContent, "utf-8")
724
+ }
725
+ ]);
726
+ const installCmd = await sandbox.runCommand({
727
+ cmd: "npm",
728
+ args: ["install", "--omit=dev"]
729
+ });
730
+ const installStdout = await installCmd.stdout();
731
+ const installStderr = await installCmd.stderr();
732
+ if (installStdout) {
733
+ logs.push(installStdout);
734
+ }
735
+ if (installStderr) {
736
+ logs.push(installStderr);
737
+ }
738
+ if (installCmd.exitCode !== 0) {
739
+ throw new Error(`Failed to install dependencies: ${installStderr}`);
740
+ }
741
+ logger2.info(
742
+ {
743
+ functionId,
744
+ dependencyHash
745
+ },
746
+ "Dependencies installed successfully"
747
+ );
748
+ }
749
+ const executionCode = createExecutionWrapper(toolConfig.executeCode, args);
750
+ const envVars = this.extractEnvVars(toolConfig.executeCode);
751
+ const filesToWrite = [];
752
+ const filename = this.config.runtime === "typescript" ? "execute.ts" : "execute.js";
753
+ filesToWrite.push({
754
+ path: filename,
755
+ content: Buffer.from(executionCode, "utf-8")
756
+ });
757
+ if (envVars.size > 0) {
758
+ const envFileContent = this.createEnvFileContent(envVars);
759
+ if (envFileContent) {
760
+ filesToWrite.push({
761
+ path: ".env",
762
+ content: Buffer.from(envFileContent, "utf-8")
763
+ });
764
+ logger2.info(
765
+ {
766
+ functionId,
767
+ envVarCount: envVars.size,
768
+ envVars: Array.from(envVars)
769
+ },
770
+ "Creating environment variable placeholders in sandbox"
771
+ );
772
+ }
773
+ }
774
+ await sandbox.writeFiles(filesToWrite);
775
+ logger2.info(
776
+ {
777
+ functionId,
778
+ runtime: this.config.runtime === "typescript" ? "tsx" : "node",
779
+ hasEnvVars: envVars.size > 0
780
+ },
781
+ `Execution code written to file for runtime ${this.config.runtime}`
782
+ );
783
+ const executeCmd = await (async () => {
784
+ if (envVars.size > 0) {
785
+ return sandbox.runCommand({
786
+ cmd: "npx",
787
+ args: this.config.runtime === "typescript" ? ["--yes", "dotenv-cli", "--", "npx", "tsx", filename] : ["--yes", "dotenv-cli", "--", "node", filename]
788
+ });
789
+ }
790
+ const runtime = this.config.runtime === "typescript" ? "tsx" : "node";
791
+ return sandbox.runCommand({
792
+ cmd: runtime,
793
+ args: [filename]
794
+ });
795
+ })();
796
+ const executeStdout = await executeCmd.stdout();
797
+ const executeStderr = await executeCmd.stderr();
798
+ if (executeStdout) {
799
+ logs.push(executeStdout);
800
+ }
801
+ if (executeStderr) {
802
+ logs.push(executeStderr);
803
+ }
804
+ const executionTime = Date.now() - startTime;
805
+ if (executeCmd.exitCode !== 0) {
806
+ logger2.error(
807
+ {
808
+ functionId,
809
+ exitCode: executeCmd.exitCode,
810
+ stderr: executeStderr
811
+ },
812
+ "Function execution failed"
813
+ );
814
+ return {
815
+ success: false,
816
+ error: executeStderr || "Function execution failed with non-zero exit code",
817
+ logs,
818
+ executionTime
819
+ };
820
+ }
821
+ const result = parseExecutionResult(executeStdout, functionId, logger2);
822
+ logger2.info(
823
+ {
824
+ functionId,
825
+ executionTime
826
+ },
827
+ "Function executed successfully in Vercel Sandbox"
828
+ );
829
+ return {
830
+ success: true,
831
+ result,
832
+ logs,
833
+ executionTime
834
+ };
835
+ } catch (innerError) {
836
+ await this.removeSandbox(dependencyHash);
837
+ throw innerError;
838
+ }
839
+ } catch (error) {
840
+ const executionTime = Date.now() - startTime;
841
+ const errorMessage = error instanceof Error ? error.message : String(error);
842
+ logger2.error(
843
+ {
844
+ functionId,
845
+ error: errorMessage,
846
+ executionTime
847
+ },
848
+ "Vercel Sandbox execution error"
849
+ );
850
+ return {
851
+ success: false,
852
+ error: errorMessage,
853
+ logs,
854
+ executionTime
855
+ };
856
+ }
857
+ }
858
+ };
859
+ __publicField(_VercelSandboxExecutor, "instance");
860
+ var VercelSandboxExecutor = _VercelSandboxExecutor;
861
+
862
+ // src/tools/SandboxExecutorFactory.ts
863
+ var logger3 = getLogger("SandboxExecutorFactory");
864
+ var _SandboxExecutorFactory = class _SandboxExecutorFactory {
865
+ constructor() {
866
+ __publicField(this, "nativeExecutor", null);
867
+ __publicField(this, "vercelExecutors", /* @__PURE__ */ new Map());
868
+ logger3.info({}, "SandboxExecutorFactory initialized");
869
+ }
870
+ /**
871
+ * Get singleton instance of SandboxExecutorFactory
872
+ */
873
+ static getInstance() {
874
+ if (!_SandboxExecutorFactory.instance) {
875
+ _SandboxExecutorFactory.instance = new _SandboxExecutorFactory();
876
+ }
877
+ return _SandboxExecutorFactory.instance;
878
+ }
879
+ /**
880
+ * Execute a function tool using the appropriate sandbox provider
881
+ */
882
+ async executeFunctionTool(functionId, args, config) {
883
+ const sandboxConfig = config.sandboxConfig;
884
+ if (!sandboxConfig) {
885
+ throw new Error("Sandbox configuration is required for function tool execution");
886
+ }
887
+ if (sandboxConfig.provider === "native") {
888
+ return this.executeInNativeSandbox(functionId, args, config);
889
+ }
890
+ if (sandboxConfig.provider === "vercel") {
891
+ return this.executeInVercelSandbox(functionId, args, config);
892
+ }
893
+ throw new Error(`Unknown sandbox provider: ${sandboxConfig.provider}`);
894
+ }
895
+ /**
896
+ * Execute in native sandbox
897
+ */
898
+ async executeInNativeSandbox(functionId, args, config) {
899
+ if (!this.nativeExecutor) {
900
+ this.nativeExecutor = NativeSandboxExecutor.getInstance();
901
+ logger3.info({}, "Native sandbox executor created");
902
+ }
903
+ return this.nativeExecutor.executeFunctionTool(functionId, args, config);
904
+ }
905
+ /**
906
+ * Execute in Vercel sandbox
907
+ */
908
+ async executeInVercelSandbox(functionId, args, config) {
909
+ const vercelConfig = config.sandboxConfig;
910
+ const configKey = `${vercelConfig.teamId}:${vercelConfig.projectId}`;
911
+ if (!this.vercelExecutors.has(configKey)) {
912
+ const executor2 = VercelSandboxExecutor.getInstance(vercelConfig);
913
+ this.vercelExecutors.set(configKey, executor2);
914
+ logger3.info(
915
+ {
916
+ teamId: vercelConfig.teamId,
917
+ projectId: vercelConfig.projectId
918
+ },
919
+ "Vercel sandbox executor created"
920
+ );
921
+ }
922
+ const executor = this.vercelExecutors.get(configKey);
923
+ if (!executor) {
924
+ throw new Error(`Failed to get Vercel executor for config: ${configKey}`);
925
+ }
926
+ const result = await executor.executeFunctionTool(functionId, args, config);
927
+ if (!result.success) {
928
+ throw new Error(result.error || "Vercel sandbox execution failed");
929
+ }
930
+ return result.result;
931
+ }
932
+ /**
933
+ * Clean up all sandbox executors
934
+ */
935
+ async cleanup() {
936
+ logger3.info({}, "Cleaning up sandbox executors");
937
+ this.nativeExecutor = null;
938
+ for (const [key, executor] of this.vercelExecutors.entries()) {
939
+ await executor.cleanup();
940
+ this.vercelExecutors.delete(key);
941
+ }
942
+ logger3.info({}, "Sandbox executor cleanup completed");
943
+ }
944
+ };
945
+ __publicField(_SandboxExecutorFactory, "instance");
946
+ var SandboxExecutorFactory = _SandboxExecutorFactory;
947
+
948
+ export { SandboxExecutorFactory };