@inkeep/agents-run-api 0.22.0 → 0.22.2

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/dist/index.cjs CHANGED
@@ -10,6 +10,7 @@ var crypto = require('crypto');
10
10
  var fs = require('fs');
11
11
  var os = require('os');
12
12
  var path = require('path');
13
+ var sandbox = require('@vercel/sandbox');
13
14
  var otel = require('@hono/otel');
14
15
  var zodOpenapi = require('@hono/zod-openapi');
15
16
  var api = require('@opentelemetry/api');
@@ -356,8 +357,8 @@ async function getConversationScopedArtifacts(params) {
356
357
  });
357
358
  referenceArtifacts.push(...artifacts);
358
359
  }
359
- const logger27 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
360
- logger27.debug(
360
+ const logger28 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
361
+ logger28.debug(
361
362
  {
362
363
  conversationId,
363
364
  visibleMessages: visibleMessages.length,
@@ -369,8 +370,8 @@ async function getConversationScopedArtifacts(params) {
369
370
  );
370
371
  return referenceArtifacts;
371
372
  } catch (error) {
372
- const logger27 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
373
- logger27.error(
373
+ const logger28 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
374
+ logger28.error(
374
375
  {
375
376
  error: error instanceof Error ? error.message : "Unknown error",
376
377
  conversationId
@@ -386,15 +387,59 @@ var init_conversations = __esm({
386
387
  }
387
388
  });
388
389
 
389
- // src/tools/LocalSandboxExecutor.ts
390
- var LocalSandboxExecutor_exports = {};
391
- __export(LocalSandboxExecutor_exports, {
392
- LocalSandboxExecutor: () => LocalSandboxExecutor
390
+ // src/tools/sandbox-utils.ts
391
+ function createExecutionWrapper(executeCode, args) {
392
+ return `
393
+ // Function tool execution wrapper
394
+ const args = ${JSON.stringify(args, null, 2)};
395
+
396
+ // User's function code
397
+ const execute = ${executeCode}
398
+
399
+ // Execute the function and output the result
400
+ (async () => {
401
+ try {
402
+ const result = await execute(args);
403
+ // Output result as JSON on the last line
404
+ console.log(JSON.stringify({ success: true, result }));
405
+ } catch (error) {
406
+ console.error(JSON.stringify({
407
+ success: false,
408
+ error: error instanceof Error ? error.message : String(error)
409
+ }));
410
+ process.exit(1);
411
+ }
412
+ })();
413
+ `;
414
+ }
415
+ function parseExecutionResult(stdout, functionId, logger28) {
416
+ try {
417
+ const outputLines = stdout.split("\n").filter((line) => line.trim());
418
+ const resultLine = outputLines[outputLines.length - 1];
419
+ return JSON.parse(resultLine);
420
+ } catch (parseError) {
421
+ if (logger28) {
422
+ logger28.warn(
423
+ {
424
+ functionId,
425
+ stdout,
426
+ parseError
427
+ },
428
+ "Failed to parse execution result"
429
+ );
430
+ }
431
+ return stdout;
432
+ }
433
+ }
434
+ var init_sandbox_utils = __esm({
435
+ "src/tools/sandbox-utils.ts"() {
436
+ }
393
437
  });
394
- var logger17, ExecutionSemaphore, _LocalSandboxExecutor, LocalSandboxExecutor;
395
- var init_LocalSandboxExecutor = __esm({
396
- "src/tools/LocalSandboxExecutor.ts"() {
397
- logger17 = agentsCore.getLogger("local-sandbox-executor");
438
+ var logger16, ExecutionSemaphore, _NativeSandboxExecutor, NativeSandboxExecutor;
439
+ var init_NativeSandboxExecutor = __esm({
440
+ "src/tools/NativeSandboxExecutor.ts"() {
441
+ init_sandbox_utils();
442
+ logger16 = agentsCore.getLogger("native-sandbox-executor");
398
443
  ExecutionSemaphore = class {
399
444
  constructor(permits, maxWaitTimeMs = 3e4) {
400
445
  __publicField(this, "permits");
@@ -447,7 +492,7 @@ var init_LocalSandboxExecutor = __esm({
447
492
  return this.waitQueue.length;
448
493
  }
449
494
  };
450
- _LocalSandboxExecutor = class _LocalSandboxExecutor {
495
+ _NativeSandboxExecutor = class _NativeSandboxExecutor {
451
496
  constructor() {
452
497
  __publicField(this, "tempDir");
453
498
  __publicField(this, "sandboxPool", {});
@@ -460,15 +505,15 @@ var init_LocalSandboxExecutor = __esm({
460
505
  this.startPoolCleanup();
461
506
  }
462
507
  static getInstance() {
463
- if (!_LocalSandboxExecutor.instance) {
464
- _LocalSandboxExecutor.instance = new _LocalSandboxExecutor();
508
+ if (!_NativeSandboxExecutor.instance) {
509
+ _NativeSandboxExecutor.instance = new _NativeSandboxExecutor();
465
510
  }
466
- return _LocalSandboxExecutor.instance;
511
+ return _NativeSandboxExecutor.instance;
467
512
  }
468
513
  getSemaphore(vcpus) {
469
514
  const effectiveVcpus = Math.max(1, vcpus || 1);
470
515
  if (!this.executionSemaphores.has(effectiveVcpus)) {
471
- logger17.debug({ vcpus: effectiveVcpus }, "Creating new execution semaphore");
516
+ logger16.debug({ vcpus: effectiveVcpus }, "Creating new execution semaphore");
472
517
  this.executionSemaphores.set(effectiveVcpus, new ExecutionSemaphore(effectiveVcpus));
473
518
  }
474
519
  const semaphore = this.executionSemaphores.get(effectiveVcpus);
@@ -505,7 +550,7 @@ var init_LocalSandboxExecutor = __esm({
505
550
  if (now - sandbox.lastUsed < this.POOL_TTL && sandbox.useCount < this.MAX_USE_COUNT) {
506
551
  sandbox.lastUsed = now;
507
552
  sandbox.useCount++;
508
- logger17.debug(
553
+ logger16.debug(
509
554
  {
510
555
  poolKey,
511
556
  useCount: sandbox.useCount,
@@ -533,14 +578,14 @@ var init_LocalSandboxExecutor = __esm({
533
578
  useCount: 1,
534
579
  dependencies
535
580
  };
536
- logger17.debug({ poolKey, sandboxDir }, "Added sandbox to pool");
581
+ logger16.debug({ poolKey, sandboxDir }, "Added sandbox to pool");
537
582
  }
538
583
  cleanupSandbox(sandboxDir) {
539
584
  try {
540
585
  fs.rmSync(sandboxDir, { recursive: true, force: true });
541
- logger17.debug({ sandboxDir }, "Cleaned up sandbox");
586
+ logger16.debug({ sandboxDir }, "Cleaned up sandbox");
542
587
  } catch (error) {
543
- logger17.warn({ sandboxDir, error }, "Failed to clean up sandbox");
588
+ logger16.warn({ sandboxDir, error }, "Failed to clean up sandbox");
544
589
  }
545
590
  }
546
591
  startPoolCleanup() {
@@ -557,7 +602,7 @@ var init_LocalSandboxExecutor = __esm({
557
602
  delete this.sandboxPool[key];
558
603
  });
559
604
  if (keysToDelete.length > 0) {
560
- logger17.debug({ cleanedCount: keysToDelete.length }, "Cleaned up expired sandboxes");
605
+ logger16.debug({ cleanedCount: keysToDelete.length }, "Cleaned up expired sandboxes");
561
606
  }
562
607
  }, 6e4);
563
608
  }
@@ -586,7 +631,7 @@ var init_LocalSandboxExecutor = __esm({
586
631
  return hasCjsSyntax ? "cjs" : "esm";
587
632
  }
588
633
  if (hasEsmSyntax && hasCjsSyntax) {
589
- logger17.warn(
634
+ logger16.warn(
590
635
  { executeCode: `${executeCode.substring(0, 100)}...` },
591
636
  "Both ESM and CommonJS syntax detected, defaulting to ESM"
592
637
  );
@@ -603,7 +648,7 @@ var init_LocalSandboxExecutor = __esm({
603
648
  async executeFunctionTool(toolId, args, config) {
604
649
  const vcpus = config.sandboxConfig?.vcpus || 1;
605
650
  const semaphore = this.getSemaphore(vcpus);
606
- logger17.debug(
651
+ logger16.debug(
607
652
  {
608
653
  toolId,
609
654
  vcpus,
@@ -621,7 +666,7 @@ var init_LocalSandboxExecutor = __esm({
621
666
  async executeInSandbox_Internal(toolId, args, config) {
622
667
  const dependencies = config.dependencies || {};
623
668
  const dependencyHash = this.generateDependencyHash(dependencies);
624
- logger17.debug(
669
+ logger16.debug(
625
670
  {
626
671
  toolId,
627
672
  dependencies,
@@ -637,7 +682,7 @@ var init_LocalSandboxExecutor = __esm({
637
682
  sandboxDir = path.join(this.tempDir, `sandbox-${dependencyHash}-${Date.now()}`);
638
683
  fs.mkdirSync(sandboxDir, { recursive: true });
639
684
  isNewSandbox = true;
640
- logger17.debug(
685
+ logger16.debug(
641
686
  {
642
687
  toolId,
643
688
  dependencyHash,
@@ -664,7 +709,7 @@ var init_LocalSandboxExecutor = __esm({
664
709
  }
665
710
  try {
666
711
  const moduleType = this.detectModuleType(config.executeCode, config.sandboxConfig?.runtime);
667
- const executionCode = this.wrapFunctionCode(config.executeCode, args);
712
+ const executionCode = createExecutionWrapper(config.executeCode, args);
668
713
  const fileExtension = moduleType === "esm" ? "mjs" : "js";
669
714
  fs.writeFileSync(path.join(sandboxDir, `index.${fileExtension}`), executionCode, "utf8");
670
715
  const result = await this.executeInSandbox(
@@ -708,15 +753,15 @@ var init_LocalSandboxExecutor = __esm({
708
753
  });
709
754
  npm.on("close", (code) => {
710
755
  if (code === 0) {
711
- logger17.debug({ sandboxDir }, "Dependencies installed successfully");
756
+ logger16.debug({ sandboxDir }, "Dependencies installed successfully");
712
757
  resolve();
713
758
  } else {
714
- logger17.error({ sandboxDir, code, stderr }, "Failed to install dependencies");
759
+ logger16.error({ sandboxDir, code, stderr }, "Failed to install dependencies");
715
760
  reject(new Error(`npm install failed with code ${code}: ${stderr}`));
716
761
  }
717
762
  });
718
763
  npm.on("error", (err) => {
719
- logger17.error({ sandboxDir, error: err }, "Failed to spawn npm install");
764
+ logger16.error({ sandboxDir, error: err }, "Failed to spawn npm install");
720
765
  reject(err);
721
766
  });
722
767
  });
@@ -756,7 +801,7 @@ var init_LocalSandboxExecutor = __esm({
756
801
  stderr += dataStr;
757
802
  });
758
803
  const timeoutId = setTimeout(() => {
759
- logger17.warn({ sandboxDir, timeout }, "Function execution timed out, killing process");
804
+ logger16.warn({ sandboxDir, timeout }, "Function execution timed out, killing process");
760
805
  node.kill("SIGTERM");
761
806
  const forceKillTimeout = Math.min(Math.max(timeout / 10, 2e3), 5e3);
762
807
  setTimeout(() => {
@@ -771,60 +816,324 @@ var init_LocalSandboxExecutor = __esm({
771
816
  clearTimeout(timeoutId);
772
817
  if (code === 0) {
773
818
  try {
774
- const result = JSON.parse(stdout);
775
- if (result.success) {
776
- resolve(result.result);
819
+ const result = parseExecutionResult(stdout, "function", logger16);
820
+ if (typeof result === "object" && result !== null && "success" in result) {
821
+ const parsed = result;
822
+ if (parsed.success) {
823
+ resolve(parsed.result);
824
+ } else {
825
+ reject(new Error(parsed.error || "Function execution failed"));
826
+ }
777
827
  } else {
778
- reject(new Error(result.error || "Function execution failed"));
828
+ resolve(result);
779
829
  }
780
830
  } catch (parseError) {
781
- logger17.error({ stdout, stderr, parseError }, "Failed to parse function result");
831
+ logger16.error({ stdout, stderr, parseError }, "Failed to parse function result");
782
832
  reject(new Error(`Invalid function result: ${stdout}`));
783
833
  }
784
834
  } else {
785
835
  const errorMsg = signal ? `Function execution killed by signal ${signal}: ${stderr}` : `Function execution failed with code ${code}: ${stderr}`;
786
- logger17.error({ code, signal, stderr }, "Function execution failed");
836
+ logger16.error({ code, signal, stderr }, "Function execution failed");
787
837
  reject(new Error(errorMsg));
788
838
  }
789
839
  });
790
840
  node.on("error", (error) => {
791
841
  clearTimeout(timeoutId);
792
- logger17.error({ sandboxDir, error }, "Failed to spawn node process");
842
+ logger16.error({ sandboxDir, error }, "Failed to spawn node process");
793
843
  reject(error);
794
844
  });
795
845
  });
796
846
  }
797
- wrapFunctionCode(executeCode, args) {
798
- return `
799
- // Wrapped function execution (ESM)
800
- const execute = ${executeCode};
801
- const args = ${JSON.stringify(args)};
802
-
803
- try {
804
- const result = execute(args);
805
-
806
- // Handle both sync and async functions
807
- if (result && typeof result.then === 'function') {
808
- // Async function - result is a Promise
809
- result
810
- .then(result => {
811
- console.log(JSON.stringify({ success: true, result }));
812
- })
813
- .catch(error => {
814
- console.log(JSON.stringify({ success: false, error: error.message }));
815
- });
816
- } else {
817
- // Sync function - result is immediate
818
- console.log(JSON.stringify({ success: true, result }));
847
+ };
848
+ __publicField(_NativeSandboxExecutor, "instance", null);
849
+ NativeSandboxExecutor = _NativeSandboxExecutor;
819
850
  }
820
- } catch (error) {
821
- console.log(JSON.stringify({ success: false, error: error.message }));
822
- }
823
- `;
851
+ });
852
+ var logger17, _VercelSandboxExecutor, VercelSandboxExecutor;
853
+ var init_VercelSandboxExecutor = __esm({
854
+ "src/tools/VercelSandboxExecutor.ts"() {
855
+ init_logger();
856
+ init_sandbox_utils();
857
+ logger17 = agentsCore.getLogger("VercelSandboxExecutor");
858
+ _VercelSandboxExecutor = class _VercelSandboxExecutor {
859
+ constructor(config) {
860
+ __publicField(this, "config");
861
+ this.config = config;
862
+ logger17.info(
863
+ {
864
+ teamId: config.teamId,
865
+ projectId: config.projectId,
866
+ runtime: config.runtime,
867
+ timeout: config.timeout,
868
+ vcpus: config.vcpus
869
+ },
870
+ "VercelSandboxExecutor initialized"
871
+ );
872
+ }
873
+ /**
874
+ * Get singleton instance of VercelSandboxExecutor
875
+ */
876
+ static getInstance(config) {
877
+ if (!_VercelSandboxExecutor.instance) {
878
+ _VercelSandboxExecutor.instance = new _VercelSandboxExecutor(config);
879
+ }
880
+ return _VercelSandboxExecutor.instance;
881
+ }
882
+ /**
883
+ * Execute a function tool in Vercel Sandbox
884
+ */
885
+ async executeFunctionTool(functionId, args, toolConfig) {
886
+ const startTime = Date.now();
887
+ const logs = [];
888
+ try {
889
+ logger17.info(
890
+ {
891
+ functionId,
892
+ functionName: toolConfig.name
893
+ },
894
+ "Executing function in Vercel Sandbox"
895
+ );
896
+ const sandbox$1 = await sandbox.Sandbox.create({
897
+ token: this.config.token,
898
+ teamId: this.config.teamId,
899
+ projectId: this.config.projectId,
900
+ timeout: this.config.timeout,
901
+ resources: {
902
+ vcpus: this.config.vcpus || 1
903
+ },
904
+ runtime: this.config.runtime
905
+ });
906
+ logger17.info(
907
+ {
908
+ functionId,
909
+ sandboxId: sandbox$1.sandboxId
910
+ },
911
+ `Sandbox created for function ${functionId}`
912
+ );
913
+ try {
914
+ if (toolConfig.dependencies && Object.keys(toolConfig.dependencies).length > 0) {
915
+ logger17.debug(
916
+ {
917
+ functionId,
918
+ functionName: toolConfig.name,
919
+ dependencies: toolConfig.dependencies
920
+ },
921
+ "Installing dependencies"
922
+ );
923
+ const packageJson = {
924
+ dependencies: toolConfig.dependencies
925
+ };
926
+ const packageJsonContent = JSON.stringify(packageJson, null, 2);
927
+ await sandbox$1.writeFiles([
928
+ {
929
+ path: "package.json",
930
+ content: Buffer.from(packageJsonContent, "utf-8")
931
+ }
932
+ ]);
933
+ const installCmd = await sandbox$1.runCommand({
934
+ cmd: "npm",
935
+ args: ["install", "--omit=dev"]
936
+ });
937
+ const installStdout = await installCmd.stdout();
938
+ const installStderr = await installCmd.stderr();
939
+ if (installStdout) {
940
+ logs.push(installStdout);
941
+ }
942
+ if (installStderr) {
943
+ logs.push(installStderr);
944
+ }
945
+ if (installCmd.exitCode !== 0) {
946
+ throw new Error(`Failed to install dependencies: ${installStderr}`);
947
+ }
948
+ }
949
+ const executionCode = createExecutionWrapper(toolConfig.executeCode, args);
950
+ const filename = this.config.runtime === "typescript" ? "execute.ts" : "execute.js";
951
+ await sandbox$1.writeFiles([
952
+ {
953
+ path: filename,
954
+ content: Buffer.from(executionCode, "utf-8")
955
+ }
956
+ ]);
957
+ logger17.info(
958
+ {
959
+ functionId,
960
+ runtime: this.config.runtime === "typescript" ? "tsx" : "node"
961
+ },
962
+ `Execution code written to file for runtime ${this.config.runtime}`
963
+ );
964
+ const runtime = this.config.runtime === "typescript" ? "tsx" : "node";
965
+ const executeCmd = await sandbox$1.runCommand({
966
+ cmd: runtime,
967
+ args: [filename]
968
+ });
969
+ const executeStdout = await executeCmd.stdout();
970
+ const executeStderr = await executeCmd.stderr();
971
+ if (executeStdout) {
972
+ logs.push(executeStdout);
973
+ }
974
+ if (executeStderr) {
975
+ logs.push(executeStderr);
976
+ }
977
+ const executionTime = Date.now() - startTime;
978
+ if (executeCmd.exitCode !== 0) {
979
+ logger17.error(
980
+ {
981
+ functionId,
982
+ exitCode: executeCmd.exitCode,
983
+ stderr: executeStderr
984
+ },
985
+ "Function execution failed"
986
+ );
987
+ return {
988
+ success: false,
989
+ error: executeStderr || "Function execution failed with non-zero exit code",
990
+ logs,
991
+ executionTime
992
+ };
993
+ }
994
+ const result = parseExecutionResult(executeStdout, functionId, logger17);
995
+ logger17.info(
996
+ {
997
+ functionId,
998
+ executionTime
999
+ },
1000
+ "Function executed successfully in Vercel Sandbox"
1001
+ );
1002
+ return {
1003
+ success: true,
1004
+ result,
1005
+ logs,
1006
+ executionTime
1007
+ };
1008
+ } finally {
1009
+ await sandbox$1.stop();
1010
+ }
1011
+ } catch (error) {
1012
+ const executionTime = Date.now() - startTime;
1013
+ const errorMessage = error instanceof Error ? error.message : String(error);
1014
+ logger17.error(
1015
+ {
1016
+ functionId,
1017
+ error: errorMessage,
1018
+ executionTime
1019
+ },
1020
+ "Vercel Sandbox execution error"
1021
+ );
1022
+ return {
1023
+ success: false,
1024
+ error: errorMessage,
1025
+ logs,
1026
+ executionTime
1027
+ };
1028
+ }
1029
+ }
1030
+ /**
1031
+ * Clean up resources
1032
+ */
1033
+ async cleanup() {
1034
+ logger17.info({}, "VercelSandboxExecutor cleanup completed");
1035
+ }
1036
+ };
1037
+ __publicField(_VercelSandboxExecutor, "instance");
1038
+ VercelSandboxExecutor = _VercelSandboxExecutor;
1039
+ }
1040
+ });
1041
+
1042
+ // src/tools/SandboxExecutorFactory.ts
1043
+ var SandboxExecutorFactory_exports = {};
1044
+ __export(SandboxExecutorFactory_exports, {
1045
+ SandboxExecutorFactory: () => SandboxExecutorFactory
1046
+ });
1047
+ var logger18, _SandboxExecutorFactory, SandboxExecutorFactory;
1048
+ var init_SandboxExecutorFactory = __esm({
1049
+ "src/tools/SandboxExecutorFactory.ts"() {
1050
+ init_logger();
1051
+ init_NativeSandboxExecutor();
1052
+ init_VercelSandboxExecutor();
1053
+ logger18 = agentsCore.getLogger("SandboxExecutorFactory");
1054
+ _SandboxExecutorFactory = class _SandboxExecutorFactory {
1055
+ constructor() {
1056
+ __publicField(this, "nativeExecutor", null);
1057
+ __publicField(this, "vercelExecutors", /* @__PURE__ */ new Map());
1058
+ logger18.info({}, "SandboxExecutorFactory initialized");
1059
+ }
1060
+ /**
1061
+ * Get singleton instance of SandboxExecutorFactory
1062
+ */
1063
+ static getInstance() {
1064
+ if (!_SandboxExecutorFactory.instance) {
1065
+ _SandboxExecutorFactory.instance = new _SandboxExecutorFactory();
1066
+ }
1067
+ return _SandboxExecutorFactory.instance;
1068
+ }
1069
+ /**
1070
+ * Execute a function tool using the appropriate sandbox provider
1071
+ */
1072
+ async executeFunctionTool(functionId, args, config) {
1073
+ const sandboxConfig = config.sandboxConfig;
1074
+ if (!sandboxConfig) {
1075
+ throw new Error("Sandbox configuration is required for function tool execution");
1076
+ }
1077
+ if (sandboxConfig.provider === "native") {
1078
+ return this.executeInNativeSandbox(functionId, args, config);
1079
+ }
1080
+ if (sandboxConfig.provider === "vercel") {
1081
+ return this.executeInVercelSandbox(functionId, args, config);
1082
+ }
1083
+ throw new Error(`Unknown sandbox provider: ${sandboxConfig.provider}`);
1084
+ }
1085
+ /**
1086
+ * Execute in native sandbox
1087
+ */
1088
+ async executeInNativeSandbox(functionId, args, config) {
1089
+ if (!this.nativeExecutor) {
1090
+ this.nativeExecutor = NativeSandboxExecutor.getInstance();
1091
+ logger18.info({}, "Native sandbox executor created");
1092
+ }
1093
+ return this.nativeExecutor.executeFunctionTool(functionId, args, config);
1094
+ }
1095
+ /**
1096
+ * Execute in Vercel sandbox
1097
+ */
1098
+ async executeInVercelSandbox(functionId, args, config) {
1099
+ const vercelConfig = config.sandboxConfig;
1100
+ const configKey = `${vercelConfig.teamId}:${vercelConfig.projectId}`;
1101
+ if (!this.vercelExecutors.has(configKey)) {
1102
+ const executor2 = VercelSandboxExecutor.getInstance(vercelConfig);
1103
+ this.vercelExecutors.set(configKey, executor2);
1104
+ logger18.info(
1105
+ {
1106
+ teamId: vercelConfig.teamId,
1107
+ projectId: vercelConfig.projectId
1108
+ },
1109
+ "Vercel sandbox executor created"
1110
+ );
1111
+ }
1112
+ const executor = this.vercelExecutors.get(configKey);
1113
+ if (!executor) {
1114
+ throw new Error(`Failed to get Vercel executor for config: ${configKey}`);
1115
+ }
1116
+ const result = await executor.executeFunctionTool(functionId, args, config);
1117
+ if (!result.success) {
1118
+ throw new Error(result.error || "Vercel sandbox execution failed");
1119
+ }
1120
+ return result.result;
1121
+ }
1122
+ /**
1123
+ * Clean up all sandbox executors
1124
+ */
1125
+ async cleanup() {
1126
+ logger18.info({}, "Cleaning up sandbox executors");
1127
+ this.nativeExecutor = null;
1128
+ for (const [key, executor] of this.vercelExecutors.entries()) {
1129
+ await executor.cleanup();
1130
+ this.vercelExecutors.delete(key);
1131
+ }
1132
+ logger18.info({}, "Sandbox executor cleanup completed");
824
1133
  }
825
1134
  };
826
- __publicField(_LocalSandboxExecutor, "instance", null);
827
- LocalSandboxExecutor = _LocalSandboxExecutor;
1135
+ __publicField(_SandboxExecutorFactory, "instance");
1136
+ SandboxExecutorFactory = _SandboxExecutorFactory;
828
1137
  }
829
1138
  });
830
1139
 
@@ -2603,31 +2912,6 @@ var _ArtifactService = class _ArtifactService {
2603
2912
  }
2604
2913
  return value;
2605
2914
  }
2606
- /**
2607
- * Extract properties from data using prop selectors
2608
- */
2609
- extractProps(item, propSelectors) {
2610
- const extracted = {};
2611
- for (const [propName, selector] of Object.entries(propSelectors)) {
2612
- try {
2613
- const sanitizedSelector = this.sanitizeJMESPathSelector(selector);
2614
- const rawValue = sanitizedSelector ? jmespath__default.default.search(item, sanitizedSelector) : item[propName];
2615
- if (rawValue !== null && rawValue !== void 0) {
2616
- extracted[propName] = this.cleanEscapedContent(rawValue);
2617
- }
2618
- } catch (error) {
2619
- logger7.warn(
2620
- { propName, selector, error: error instanceof Error ? error.message : "Unknown error" },
2621
- "Failed to extract property"
2622
- );
2623
- const fallbackValue = item[propName];
2624
- if (fallbackValue !== null && fallbackValue !== void 0) {
2625
- extracted[propName] = this.cleanEscapedContent(fallbackValue);
2626
- }
2627
- }
2628
- }
2629
- return extracted;
2630
- }
2631
2915
  /**
2632
2916
  * Extract properties from data using schema-defined fields and custom selectors
2633
2917
  */
@@ -2758,7 +3042,7 @@ var _ArtifactParser = class _ArtifactParser {
2758
3042
  while ((match = _ArtifactParser.ATTR_REGEX.exec(attrString)) !== null) {
2759
3043
  const key = match[1] || match[3] || match[5];
2760
3044
  let value = match[2] || match[4] || match[6];
2761
- if (value && value.startsWith("{")) {
3045
+ if (value?.startsWith("{")) {
2762
3046
  try {
2763
3047
  value = JSON.parse(value);
2764
3048
  } catch {
@@ -3025,9 +3309,7 @@ var _ArtifactParser = class _ArtifactParser {
3025
3309
  return await this.artifactService.getArtifactSummary(artifactId, toolCallId, artifactMap);
3026
3310
  }
3027
3311
  };
3028
- __publicField(_ArtifactParser, "ARTIFACT_REGEX", /<artifact:ref\s+id=(['"])([^'"]*?)\1\s+tool=(['"])([^'"]*?)\3\s*\/>/gs);
3029
3312
  __publicField(_ArtifactParser, "ARTIFACT_CHECK_REGEX", /<artifact:ref\s+(?=.*id=['"][^'"]+['"])(?=.*tool=['"][^'"]+['"])[^>]*\/>/);
3030
- __publicField(_ArtifactParser, "ARTIFACT_CREATE_REGEX", /<artifact:create\s+([^>]+?)(?:\s*\/)?>(?:(.*?)<\/artifact:create>)?/gs);
3031
3313
  __publicField(_ArtifactParser, "ATTR_REGEX", /(\w+)="([^"]*)"|(\w+)='([^']*)'|(\w+)=({[^}]+})/g);
3032
3314
  __publicField(_ArtifactParser, "ARTIFACT_PATTERNS", [
3033
3315
  "<a",
@@ -4507,7 +4789,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4507
4789
  sharedArtifactService = agentSessionManager.getArtifactService(
4508
4790
  artifactParserOptions.streamRequestId
4509
4791
  );
4510
- } catch (error) {
4792
+ } catch (_error) {
4511
4793
  }
4512
4794
  }
4513
4795
  this.artifactParser = new ArtifactParser(tenantId, {
@@ -4547,7 +4829,9 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4547
4829
  */
4548
4830
  async processTextChunk(chunk) {
4549
4831
  if (this.lastChunkWasToolResult && this.buffer === "" && chunk) {
4550
- chunk = "\n\n" + chunk;
4832
+ chunk = `
4833
+
4834
+ ${chunk}`;
4551
4835
  this.lastChunkWasToolResult = false;
4552
4836
  }
4553
4837
  this.buffer += chunk;
@@ -4578,7 +4862,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4578
4862
  if (this.isComponentComplete(component)) {
4579
4863
  await this.streamComponent(component);
4580
4864
  }
4581
- } catch (e) {
4865
+ } catch (_e) {
4582
4866
  }
4583
4867
  }
4584
4868
  }
@@ -4892,7 +5176,7 @@ var ResponseFormatter = class {
4892
5176
  sharedArtifactService = agentSessionManager.getArtifactService(
4893
5177
  artifactParserOptions.streamRequestId
4894
5178
  );
4895
- } catch (error) {
5179
+ } catch (_error) {
4896
5180
  }
4897
5181
  }
4898
5182
  this.artifactParser = new ArtifactParser(tenantId, {
@@ -5111,7 +5395,7 @@ function jsonSchemaToZod(jsonSchema) {
5111
5395
 
5112
5396
  // src/utils/SchemaProcessor.ts
5113
5397
  init_logger();
5114
- var SchemaProcessor = class {
5398
+ var _SchemaProcessor = class _SchemaProcessor {
5115
5399
  /**
5116
5400
  * Transform complex schema types to strings for JMESPath compatibility
5117
5401
  */
@@ -5142,13 +5426,13 @@ var SchemaProcessor = class {
5142
5426
  * Validate if a selector looks like a valid JMESPath expression
5143
5427
  */
5144
5428
  static validateJMESPathSelector(selector) {
5145
- if (this.isLiteralValue(selector)) {
5429
+ if (_SchemaProcessor.isLiteralValue(selector)) {
5146
5430
  return {
5147
5431
  isLiteral: true,
5148
5432
  isValidSelector: false
5149
5433
  };
5150
5434
  }
5151
- if (this.looksLikeJMESPath(selector)) {
5435
+ if (_SchemaProcessor.looksLikeJMESPath(selector)) {
5152
5436
  return {
5153
5437
  isLiteral: false,
5154
5438
  isValidSelector: true
@@ -5184,7 +5468,7 @@ var SchemaProcessor = class {
5184
5468
  * Check if a selector appears to be a literal value rather than a JMESPath expression
5185
5469
  */
5186
5470
  static isLiteralValue(selector) {
5187
- if (this.looksLikeJMESPath(selector)) {
5471
+ if (_SchemaProcessor.looksLikeJMESPath(selector)) {
5188
5472
  return false;
5189
5473
  }
5190
5474
  if (/^https?:\/\//.test(selector)) {
@@ -5206,18 +5490,21 @@ var SchemaProcessor = class {
5206
5490
  */
5207
5491
  static safeJMESPathSearch(data, selector, fallback = null) {
5208
5492
  try {
5209
- const validation = this.validateJMESPathSelector(selector);
5493
+ const validation = _SchemaProcessor.validateJMESPathSelector(selector);
5210
5494
  if (validation.isLiteral) {
5211
- this.logger.debug({ selector }, "Selector appears to be literal value, returning as-is");
5495
+ _SchemaProcessor.logger.debug(
5496
+ { selector },
5497
+ "Selector appears to be literal value, returning as-is"
5498
+ );
5212
5499
  return selector;
5213
5500
  }
5214
5501
  if (!validation.isValidSelector) {
5215
- this.logger.warn({ selector }, "Selector does not appear to be valid JMESPath");
5502
+ _SchemaProcessor.logger.warn({ selector }, "Selector does not appear to be valid JMESPath");
5216
5503
  return fallback;
5217
5504
  }
5218
5505
  return jmespath__default.default.search(data, selector) || fallback;
5219
5506
  } catch (error) {
5220
- this.logger.warn(
5507
+ _SchemaProcessor.logger.warn(
5221
5508
  { selector, error: error instanceof Error ? error.message : String(error) },
5222
5509
  "JMESPath search failed"
5223
5510
  );
@@ -5239,7 +5526,7 @@ var SchemaProcessor = class {
5239
5526
  if (!schema.properties || typeof schema.properties !== "object") {
5240
5527
  errors.push("Schema must have properties object");
5241
5528
  }
5242
- const transformedSchema = this.transformSchemaForJMESPath(schema);
5529
+ const transformedSchema = _SchemaProcessor.transformSchemaForJMESPath(schema);
5243
5530
  return {
5244
5531
  isValid: errors.length === 0,
5245
5532
  errors,
@@ -5249,8 +5536,8 @@ var SchemaProcessor = class {
5249
5536
  /**
5250
5537
  * Extract property value with proper type conversion and validation
5251
5538
  */
5252
- static extractPropertyValue(data, propName, selector, expectedType) {
5253
- const value = this.safeJMESPathSearch(data, selector);
5539
+ static extractPropertyValue(data, _propName, selector, expectedType) {
5540
+ const value = _SchemaProcessor.safeJMESPathSearch(data, selector);
5254
5541
  if (value === null || value === void 0) {
5255
5542
  return null;
5256
5543
  }
@@ -5258,9 +5545,10 @@ var SchemaProcessor = class {
5258
5545
  switch (expectedType) {
5259
5546
  case "string":
5260
5547
  return String(value);
5261
- case "number":
5548
+ case "number": {
5262
5549
  const num = Number(value);
5263
- return isNaN(num) ? null : num;
5550
+ return Number.isNaN(num) ? null : num;
5551
+ }
5264
5552
  case "boolean":
5265
5553
  return Boolean(value);
5266
5554
  case "array":
@@ -5324,7 +5612,8 @@ var SchemaProcessor = class {
5324
5612
  return transformToSelectorSchema(schema);
5325
5613
  }
5326
5614
  };
5327
- __publicField(SchemaProcessor, "logger", agentsCore.getLogger("SchemaProcessor"));
5615
+ __publicField(_SchemaProcessor, "logger", agentsCore.getLogger("SchemaProcessor"));
5616
+ var SchemaProcessor = _SchemaProcessor;
5328
5617
 
5329
5618
  // src/utils/artifact-component-schema.ts
5330
5619
  agentsCore.getLogger("ArtifactComponentSchema");
@@ -7419,7 +7708,7 @@ function hasToolCallWithPrefix(prefix) {
7419
7708
  return false;
7420
7709
  };
7421
7710
  }
7422
- var logger18 = agentsCore.getLogger("Agent");
7711
+ var logger19 = agentsCore.getLogger("Agent");
7423
7712
  var CONSTANTS = {
7424
7713
  MAX_GENERATION_STEPS: 12,
7425
7714
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -7725,14 +8014,14 @@ var Agent = class {
7725
8014
  for (const toolSet of tools) {
7726
8015
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
7727
8016
  if (!isValidTool(originalTool)) {
7728
- logger18.error({ toolName }, "Invalid MCP tool structure - missing required properties");
8017
+ logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7729
8018
  continue;
7730
8019
  }
7731
8020
  const sessionWrappedTool = ai.tool({
7732
8021
  description: originalTool.description,
7733
8022
  inputSchema: originalTool.inputSchema,
7734
8023
  execute: async (args, { toolCallId }) => {
7735
- logger18.debug({ toolName, toolCallId }, "MCP Tool Called");
8024
+ logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
7736
8025
  try {
7737
8026
  const rawResult = await originalTool.execute(args, { toolCallId });
7738
8027
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -7746,7 +8035,7 @@ var Agent = class {
7746
8035
  });
7747
8036
  return { result: enhancedResult, toolCallId };
7748
8037
  } catch (error) {
7749
- logger18.error({ toolName, toolCallId, error }, "MCP tool execution failed");
8038
+ logger19.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7750
8039
  throw error;
7751
8040
  }
7752
8041
  }
@@ -7847,7 +8136,7 @@ var Agent = class {
7847
8136
  headers: agentToolRelationHeaders
7848
8137
  };
7849
8138
  }
7850
- logger18.info(
8139
+ logger19.info(
7851
8140
  {
7852
8141
  toolName: tool3.name,
7853
8142
  credentialReferenceId,
@@ -7872,7 +8161,7 @@ var Agent = class {
7872
8161
  this.mcpClientCache.set(cacheKey, client);
7873
8162
  } catch (error) {
7874
8163
  this.mcpConnectionLocks.delete(cacheKey);
7875
- logger18.error(
8164
+ logger19.error(
7876
8165
  {
7877
8166
  toolName: tool3.name,
7878
8167
  subAgentId: this.config.id,
@@ -7936,7 +8225,7 @@ var Agent = class {
7936
8225
  await client.connect();
7937
8226
  return client;
7938
8227
  } catch (error) {
7939
- logger18.error(
8228
+ logger19.error(
7940
8229
  {
7941
8230
  toolName: tool3.name,
7942
8231
  subAgentId: this.config.id,
@@ -7973,12 +8262,12 @@ var Agent = class {
7973
8262
  if (functionToolsData.length === 0) {
7974
8263
  return functionTools;
7975
8264
  }
7976
- const { LocalSandboxExecutor: LocalSandboxExecutor2 } = await Promise.resolve().then(() => (init_LocalSandboxExecutor(), LocalSandboxExecutor_exports));
7977
- const sandboxExecutor = LocalSandboxExecutor2.getInstance();
8265
+ const { SandboxExecutorFactory: SandboxExecutorFactory2 } = await Promise.resolve().then(() => (init_SandboxExecutorFactory(), SandboxExecutorFactory_exports));
8266
+ const sandboxExecutor = SandboxExecutorFactory2.getInstance();
7978
8267
  for (const functionToolDef of functionToolsData) {
7979
8268
  const functionId = functionToolDef.functionId;
7980
8269
  if (!functionId) {
7981
- logger18.warn(
8270
+ logger19.warn(
7982
8271
  { functionToolId: functionToolDef.id },
7983
8272
  "Function tool missing functionId reference"
7984
8273
  );
@@ -7992,7 +8281,7 @@ var Agent = class {
7992
8281
  }
7993
8282
  });
7994
8283
  if (!functionData) {
7995
- logger18.warn(
8284
+ logger19.warn(
7996
8285
  { functionId, functionToolId: functionToolDef.id },
7997
8286
  "Function not found in functions table"
7998
8287
  );
@@ -8003,16 +8292,13 @@ var Agent = class {
8003
8292
  description: functionToolDef.description || functionToolDef.name,
8004
8293
  inputSchema: zodSchema,
8005
8294
  execute: async (args, { toolCallId }) => {
8006
- logger18.debug(
8295
+ logger19.debug(
8007
8296
  { toolName: functionToolDef.name, toolCallId, args },
8008
8297
  "Function Tool Called"
8009
8298
  );
8010
8299
  try {
8011
- const project = await agentsCore.getProject(dbClient_default)({
8012
- scopes: { tenantId: this.config.tenantId, projectId: this.config.projectId }
8013
- });
8014
8300
  const defaultSandboxConfig = {
8015
- provider: "local",
8301
+ provider: "native",
8016
8302
  runtime: "node22",
8017
8303
  timeout: 3e4,
8018
8304
  vcpus: 1
@@ -8022,7 +8308,7 @@ var Agent = class {
8022
8308
  inputSchema: functionData.inputSchema || {},
8023
8309
  executeCode: functionData.executeCode,
8024
8310
  dependencies: functionData.dependencies || {},
8025
- sandboxConfig: project?.sandboxConfig || defaultSandboxConfig
8311
+ sandboxConfig: this.config.sandboxConfig || defaultSandboxConfig
8026
8312
  });
8027
8313
  toolSessionManager.recordToolResult(sessionId || "", {
8028
8314
  toolCallId,
@@ -8033,8 +8319,12 @@ var Agent = class {
8033
8319
  });
8034
8320
  return { result, toolCallId };
8035
8321
  } catch (error) {
8036
- logger18.error(
8037
- { toolName: functionToolDef.name, toolCallId, error },
8322
+ logger19.error(
8323
+ {
8324
+ toolName: functionToolDef.name,
8325
+ toolCallId,
8326
+ error: error instanceof Error ? error.message : String(error)
8327
+ },
8038
8328
  "Function tool execution failed"
8039
8329
  );
8040
8330
  throw error;
@@ -8049,7 +8339,7 @@ var Agent = class {
8049
8339
  );
8050
8340
  }
8051
8341
  } catch (error) {
8052
- logger18.error({ error }, "Failed to load function tools from database");
8342
+ logger19.error({ error }, "Failed to load function tools from database");
8053
8343
  }
8054
8344
  return functionTools;
8055
8345
  }
@@ -8059,7 +8349,7 @@ var Agent = class {
8059
8349
  async getResolvedContext(conversationId, headers) {
8060
8350
  try {
8061
8351
  if (!this.config.contextConfigId) {
8062
- logger18.debug({ agentId: this.config.agentId }, "No context config found for agent");
8352
+ logger19.debug({ agentId: this.config.agentId }, "No context config found for agent");
8063
8353
  return null;
8064
8354
  }
8065
8355
  const contextConfig = await agentsCore.getContextConfigById(dbClient_default)({
@@ -8071,7 +8361,7 @@ var Agent = class {
8071
8361
  id: this.config.contextConfigId
8072
8362
  });
8073
8363
  if (!contextConfig) {
8074
- logger18.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
8364
+ logger19.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
8075
8365
  return null;
8076
8366
  }
8077
8367
  if (!this.contextResolver) {
@@ -8088,7 +8378,7 @@ var Agent = class {
8088
8378
  $now: (/* @__PURE__ */ new Date()).toISOString(),
8089
8379
  $env: process.env
8090
8380
  };
8091
- logger18.debug(
8381
+ logger19.debug(
8092
8382
  {
8093
8383
  conversationId,
8094
8384
  contextConfigId: contextConfig.id,
@@ -8102,7 +8392,7 @@ var Agent = class {
8102
8392
  );
8103
8393
  return contextWithBuiltins;
8104
8394
  } catch (error) {
8105
- logger18.error(
8395
+ logger19.error(
8106
8396
  {
8107
8397
  conversationId,
8108
8398
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8126,7 +8416,7 @@ var Agent = class {
8126
8416
  });
8127
8417
  return agentDefinition?.prompt || void 0;
8128
8418
  } catch (error) {
8129
- logger18.warn(
8419
+ logger19.warn(
8130
8420
  {
8131
8421
  agentId: this.config.agentId,
8132
8422
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8155,7 +8445,7 @@ var Agent = class {
8155
8445
  (subAgent) => "artifactComponents" in subAgent && subAgent.artifactComponents && subAgent.artifactComponents.length > 0
8156
8446
  );
8157
8447
  } catch (error) {
8158
- logger18.warn(
8448
+ logger19.warn(
8159
8449
  {
8160
8450
  agentId: this.config.agentId,
8161
8451
  tenantId: this.config.tenantId,
@@ -8184,7 +8474,7 @@ var Agent = class {
8184
8474
  preserveUnresolved: false
8185
8475
  });
8186
8476
  } catch (error) {
8187
- logger18.error(
8477
+ logger19.error(
8188
8478
  {
8189
8479
  conversationId,
8190
8480
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8231,7 +8521,7 @@ var Agent = class {
8231
8521
  preserveUnresolved: false
8232
8522
  });
8233
8523
  } catch (error) {
8234
- logger18.error(
8524
+ logger19.error(
8235
8525
  {
8236
8526
  conversationId,
8237
8527
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8246,7 +8536,7 @@ var Agent = class {
8246
8536
  const functionTools = await this.getFunctionTools(streamRequestId || "");
8247
8537
  const relationTools = this.getRelationTools(runtimeContext);
8248
8538
  const allTools = { ...mcpTools, ...functionTools, ...relationTools };
8249
- logger18.info(
8539
+ logger19.info(
8250
8540
  {
8251
8541
  mcpTools: Object.keys(mcpTools),
8252
8542
  functionTools: Object.keys(functionTools),
@@ -8285,7 +8575,7 @@ var Agent = class {
8285
8575
  preserveUnresolved: false
8286
8576
  });
8287
8577
  } catch (error) {
8288
- logger18.error(
8578
+ logger19.error(
8289
8579
  {
8290
8580
  conversationId,
8291
8581
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8318,7 +8608,7 @@ var Agent = class {
8318
8608
  toolCallId: z6.z.string().describe("The tool call ID associated with this artifact.")
8319
8609
  }),
8320
8610
  execute: async ({ artifactId, toolCallId }) => {
8321
- logger18.info({ artifactId, toolCallId }, "get_artifact_full executed");
8611
+ logger19.info({ artifactId, toolCallId }, "get_artifact_full executed");
8322
8612
  const streamRequestId = this.getStreamRequestId();
8323
8613
  const artifactService = agentSessionManager.getArtifactService(streamRequestId);
8324
8614
  if (!artifactService) {
@@ -8389,7 +8679,7 @@ var Agent = class {
8389
8679
  if (typeof result === "string") {
8390
8680
  try {
8391
8681
  parsedForAnalysis = parseEmbeddedJson(result);
8392
- } catch (error) {
8682
+ } catch (_error) {
8393
8683
  parsedForAnalysis = result;
8394
8684
  }
8395
8685
  }
@@ -8578,7 +8868,7 @@ var Agent = class {
8578
8868
  };
8579
8869
  return enhanced;
8580
8870
  } catch (error) {
8581
- logger18.warn({ error }, "Failed to enhance tool result with structure hints");
8871
+ logger19.warn({ error }, "Failed to enhance tool result with structure hints");
8582
8872
  return result;
8583
8873
  }
8584
8874
  }
@@ -8593,7 +8883,7 @@ var Agent = class {
8593
8883
  }
8594
8884
  });
8595
8885
  } catch (error) {
8596
- logger18.error(
8886
+ logger19.error(
8597
8887
  { error, agentId: this.config.agentId },
8598
8888
  "Failed to check agent artifact components"
8599
8889
  );
@@ -8694,7 +8984,7 @@ var Agent = class {
8694
8984
  const configuredTimeout = modelSettings.maxDuration ? Math.min(modelSettings.maxDuration * 1e3, MAX_ALLOWED_TIMEOUT_MS) : shouldStreamPhase1 ? CONSTANTS.PHASE_1_TIMEOUT_MS : CONSTANTS.NON_STREAMING_PHASE_1_TIMEOUT_MS;
8695
8985
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
8696
8986
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
8697
- logger18.warn(
8987
+ logger19.warn(
8698
8988
  {
8699
8989
  requestedTimeout: modelSettings.maxDuration * 1e3,
8700
8990
  appliedTimeout: timeoutMs,
@@ -8736,7 +9026,7 @@ var Agent = class {
8736
9026
  }
8737
9027
  );
8738
9028
  } catch (error) {
8739
- logger18.debug({ error }, "Failed to track agent reasoning");
9029
+ logger19.debug({ error }, "Failed to track agent reasoning");
8740
9030
  }
8741
9031
  }
8742
9032
  if (steps.length >= 2) {
@@ -8858,7 +9148,7 @@ var Agent = class {
8858
9148
  }
8859
9149
  );
8860
9150
  } catch (error) {
8861
- logger18.debug({ error }, "Failed to track agent reasoning");
9151
+ logger19.debug({ error }, "Failed to track agent reasoning");
8862
9152
  }
8863
9153
  }
8864
9154
  if (steps.length >= 2) {
@@ -9156,7 +9446,7 @@ ${output}${structureHintsFormatted}`;
9156
9446
  };
9157
9447
 
9158
9448
  // src/agents/generateTaskHandler.ts
9159
- var logger19 = agentsCore.getLogger("generateTaskHandler");
9449
+ var logger20 = agentsCore.getLogger("generateTaskHandler");
9160
9450
  var createTaskHandler = (config, credentialStoreRegistry) => {
9161
9451
  return async (task) => {
9162
9452
  try {
@@ -9209,7 +9499,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9209
9499
  }
9210
9500
  })
9211
9501
  ]);
9212
- logger19.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9502
+ logger20.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9213
9503
  const enhancedInternalRelations = await Promise.all(
9214
9504
  internalRelations.map(async (relation) => {
9215
9505
  try {
@@ -9238,7 +9528,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9238
9528
  return { ...relation, description: enhancedDescription };
9239
9529
  }
9240
9530
  } catch (error) {
9241
- logger19.warn({ subAgentId: relation.id, error }, "Failed to enhance agent description");
9531
+ logger20.warn({ subAgentId: relation.id, error }, "Failed to enhance agent description");
9242
9532
  }
9243
9533
  return relation;
9244
9534
  })
@@ -9327,7 +9617,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9327
9617
  dataComponents,
9328
9618
  artifactComponents,
9329
9619
  contextConfigId: config.contextConfigId || void 0,
9330
- conversationHistoryConfig: config.conversationHistoryConfig
9620
+ conversationHistoryConfig: config.conversationHistoryConfig,
9621
+ sandboxConfig: config.sandboxConfig
9331
9622
  },
9332
9623
  credentialStoreRegistry
9333
9624
  );
@@ -9340,7 +9631,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9340
9631
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
9341
9632
  if (taskIdMatch) {
9342
9633
  contextId = taskIdMatch[1];
9343
- logger19.info(
9634
+ logger20.info(
9344
9635
  {
9345
9636
  taskId: task.id,
9346
9637
  extractedContextId: contextId,
@@ -9356,7 +9647,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9356
9647
  const isDelegation = task.context?.metadata?.isDelegation === true;
9357
9648
  agent.setDelegationStatus(isDelegation);
9358
9649
  if (isDelegation) {
9359
- logger19.info(
9650
+ logger20.info(
9360
9651
  { subAgentId: config.subAgentId, taskId: task.id },
9361
9652
  "Delegated agent - streaming disabled"
9362
9653
  );
@@ -9393,7 +9684,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9393
9684
  const toolResult = allToolResults.find(
9394
9685
  (result) => result.toolCallId === toolCall.toolCallId
9395
9686
  );
9396
- logger19.info(
9687
+ logger20.info(
9397
9688
  {
9398
9689
  toolCallName: toolCall.toolName,
9399
9690
  toolCallId: toolCall.toolCallId,
@@ -9410,7 +9701,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9410
9701
  const transferReason = responseText || allThoughts[allThoughts.length - 1]?.text || "Agent requested transfer. No reason provided.";
9411
9702
  if (toolResult?.output && isValidTransferResult(toolResult.output)) {
9412
9703
  const transferResult = toolResult.output;
9413
- logger19.info(
9704
+ logger20.info(
9414
9705
  {
9415
9706
  validationPassed: true,
9416
9707
  transferResult,
@@ -9427,7 +9718,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9427
9718
  reason: transferReason,
9428
9719
  original_message: userMessage
9429
9720
  };
9430
- logger19.info(
9721
+ logger20.info(
9431
9722
  {
9432
9723
  artifactData,
9433
9724
  artifactDataKeys: Object.keys(artifactData)
@@ -9452,7 +9743,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9452
9743
  ]
9453
9744
  };
9454
9745
  } else {
9455
- logger19.warn(
9746
+ logger20.warn(
9456
9747
  {
9457
9748
  hasToolResult: !!toolResult,
9458
9749
  hasOutput: !!toolResult?.output,
@@ -9533,7 +9824,8 @@ var createTaskHandlerConfig = async (params) => {
9533
9824
  name: subAgent.name,
9534
9825
  description: subAgent.description,
9535
9826
  conversationHistoryConfig: effectiveConversationHistoryConfig,
9536
- contextConfigId: agent?.contextConfigId || void 0
9827
+ contextConfigId: agent?.contextConfigId || void 0,
9828
+ sandboxConfig: params.sandboxConfig
9537
9829
  };
9538
9830
  };
9539
9831
 
@@ -9609,7 +9901,8 @@ async function hydrateAgent({
9609
9901
  agentId,
9610
9902
  baseUrl,
9611
9903
  apiKey,
9612
- credentialStoreRegistry
9904
+ credentialStoreRegistry,
9905
+ sandboxConfig
9613
9906
  }) {
9614
9907
  try {
9615
9908
  const taskHandlerConfig = await createTaskHandlerConfig({
@@ -9618,7 +9911,8 @@ async function hydrateAgent({
9618
9911
  agentId,
9619
9912
  subAgentId: dbAgent.id,
9620
9913
  baseUrl,
9621
- apiKey
9914
+ apiKey,
9915
+ sandboxConfig
9622
9916
  });
9623
9917
  const taskHandler = createTaskHandler(taskHandlerConfig, credentialStoreRegistry);
9624
9918
  const agentCard = createAgentCard({
@@ -9638,7 +9932,8 @@ async function hydrateAgent({
9638
9932
  throw error;
9639
9933
  }
9640
9934
  }
9641
- async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
9935
+ async function getRegisteredAgent(params) {
9936
+ const { executionContext, credentialStoreRegistry, sandboxConfig } = params;
9642
9937
  const { tenantId, projectId, agentId, subAgentId, baseUrl, apiKey } = executionContext;
9643
9938
  if (!subAgentId) {
9644
9939
  throw new Error("Agent ID is required");
@@ -9656,7 +9951,8 @@ async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
9656
9951
  agentId,
9657
9952
  baseUrl: agentFrameworkBaseUrl,
9658
9953
  credentialStoreRegistry,
9659
- apiKey
9954
+ apiKey,
9955
+ sandboxConfig
9660
9956
  });
9661
9957
  }
9662
9958
 
@@ -9664,7 +9960,7 @@ async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
9664
9960
  init_dbClient();
9665
9961
  init_logger();
9666
9962
  var app = new zodOpenapi.OpenAPIHono();
9667
- var logger20 = agentsCore.getLogger("agents");
9963
+ var logger21 = agentsCore.getLogger("agents");
9668
9964
  app.openapi(
9669
9965
  zodOpenapi.createRoute({
9670
9966
  method: "get",
@@ -9702,7 +9998,7 @@ app.openapi(
9702
9998
  tracestate: c.req.header("tracestate"),
9703
9999
  baggage: c.req.header("baggage")
9704
10000
  };
9705
- logger20.info(
10001
+ logger21.info(
9706
10002
  {
9707
10003
  otelHeaders,
9708
10004
  path: c.req.path,
@@ -9714,7 +10010,7 @@ app.openapi(
9714
10010
  const { tenantId, projectId, agentId, subAgentId } = executionContext;
9715
10011
  console.dir("executionContext", executionContext);
9716
10012
  if (subAgentId) {
9717
- logger20.info(
10013
+ logger21.info(
9718
10014
  {
9719
10015
  message: "getRegisteredAgent (agent-level)",
9720
10016
  tenantId,
@@ -9725,8 +10021,13 @@ app.openapi(
9725
10021
  "agent-level well-known agent.json"
9726
10022
  );
9727
10023
  const credentialStores = c.get("credentialStores");
9728
- const agent = await getRegisteredAgent(executionContext, credentialStores);
9729
- logger20.info({ agent }, "agent registered: well-known agent.json");
10024
+ const sandboxConfig = c.get("sandboxConfig");
10025
+ const agent = await getRegisteredAgent({
10026
+ executionContext,
10027
+ credentialStoreRegistry: credentialStores,
10028
+ sandboxConfig
10029
+ });
10030
+ logger21.info({ agent }, "agent registered: well-known agent.json");
9730
10031
  if (!agent) {
9731
10032
  throw agentsCore.createApiError({
9732
10033
  code: "not_found",
@@ -9735,7 +10036,7 @@ app.openapi(
9735
10036
  }
9736
10037
  return c.json(agent.agentCard);
9737
10038
  } else {
9738
- logger20.info(
10039
+ logger21.info(
9739
10040
  {
9740
10041
  message: "getRegisteredAgent (agent-level)",
9741
10042
  tenantId,
@@ -9744,7 +10045,11 @@ app.openapi(
9744
10045
  },
9745
10046
  "agent-level well-known agent.json"
9746
10047
  );
9747
- const agent = await getRegisteredAgent(executionContext);
10048
+ const sandboxConfig = c.get("sandboxConfig");
10049
+ const agent = await getRegisteredAgent({
10050
+ executionContext,
10051
+ sandboxConfig
10052
+ });
9748
10053
  if (!agent) {
9749
10054
  throw agentsCore.createApiError({
9750
10055
  code: "not_found",
@@ -9761,7 +10066,7 @@ app.post("/a2a", async (c) => {
9761
10066
  tracestate: c.req.header("tracestate"),
9762
10067
  baggage: c.req.header("baggage")
9763
10068
  };
9764
- logger20.info(
10069
+ logger21.info(
9765
10070
  {
9766
10071
  otelHeaders,
9767
10072
  path: c.req.path,
@@ -9772,7 +10077,7 @@ app.post("/a2a", async (c) => {
9772
10077
  const executionContext = agentsCore.getRequestExecutionContext(c);
9773
10078
  const { tenantId, projectId, agentId, subAgentId } = executionContext;
9774
10079
  if (subAgentId) {
9775
- logger20.info(
10080
+ logger21.info(
9776
10081
  {
9777
10082
  message: "a2a (agent-level)",
9778
10083
  tenantId,
@@ -9783,7 +10088,12 @@ app.post("/a2a", async (c) => {
9783
10088
  "agent-level a2a endpoint"
9784
10089
  );
9785
10090
  const credentialStores = c.get("credentialStores");
9786
- const agent = await getRegisteredAgent(executionContext, credentialStores);
10091
+ const sandboxConfig = c.get("sandboxConfig");
10092
+ const agent = await getRegisteredAgent({
10093
+ executionContext,
10094
+ credentialStoreRegistry: credentialStores,
10095
+ sandboxConfig
10096
+ });
9787
10097
  if (!agent) {
9788
10098
  return c.json(
9789
10099
  {
@@ -9796,7 +10106,7 @@ app.post("/a2a", async (c) => {
9796
10106
  }
9797
10107
  return a2aHandler(c, agent);
9798
10108
  } else {
9799
- logger20.info(
10109
+ logger21.info(
9800
10110
  {
9801
10111
  message: "a2a (agent-level)",
9802
10112
  tenantId,
@@ -9830,7 +10140,12 @@ app.post("/a2a", async (c) => {
9830
10140
  }
9831
10141
  executionContext.subAgentId = agent.defaultSubAgentId;
9832
10142
  const credentialStores = c.get("credentialStores");
9833
- const defaultSubAgent = await getRegisteredAgent(executionContext, credentialStores);
10143
+ const sandboxConfig = c.get("sandboxConfig");
10144
+ const defaultSubAgent = await getRegisteredAgent({
10145
+ executionContext,
10146
+ credentialStoreRegistry: credentialStores,
10147
+ sandboxConfig
10148
+ });
9834
10149
  if (!defaultSubAgent) {
9835
10150
  return c.json(
9836
10151
  {
@@ -9901,28 +10216,37 @@ function extractTransferData(task) {
9901
10216
  }
9902
10217
 
9903
10218
  // src/a2a/transfer.ts
9904
- var logger21 = agentsCore.getLogger("Transfer");
10219
+ var logger22 = agentsCore.getLogger("Transfer");
9905
10220
  async function executeTransfer({
9906
10221
  tenantId,
9907
10222
  threadId,
9908
10223
  projectId,
9909
10224
  targetSubAgentId
9910
10225
  }) {
9911
- logger21.info({
9912
- targetAgent: targetSubAgentId,
9913
- threadId,
9914
- tenantId,
9915
- projectId
9916
- }, "Executing transfer - calling setActiveAgentForThread");
10226
+ logger22.info(
10227
+ {
10228
+ targetAgent: targetSubAgentId,
10229
+ threadId,
10230
+ tenantId,
10231
+ projectId
10232
+ },
10233
+ "Executing transfer - calling setActiveAgentForThread"
10234
+ );
9917
10235
  try {
9918
10236
  await agentsCore.setActiveAgentForThread(dbClient_default)({
9919
10237
  scopes: { tenantId, projectId },
9920
10238
  threadId,
9921
10239
  subAgentId: targetSubAgentId
9922
10240
  });
9923
- logger21.info({ targetAgent: targetSubAgentId, threadId }, "Successfully updated active_sub_agent_id in database");
10241
+ logger22.info(
10242
+ { targetAgent: targetSubAgentId, threadId },
10243
+ "Successfully updated active_sub_agent_id in database"
10244
+ );
9924
10245
  } catch (error) {
9925
- logger21.error({ error, targetAgent: targetSubAgentId, threadId }, "Failed to update active_sub_agent_id");
10246
+ logger22.error(
10247
+ { error, targetAgent: targetSubAgentId, threadId },
10248
+ "Failed to update active_sub_agent_id"
10249
+ );
9926
10250
  throw error;
9927
10251
  }
9928
10252
  return { success: true, targetSubAgentId };
@@ -10338,7 +10662,7 @@ var _VercelDataStreamHelper = class _VercelDataStreamHelper {
10338
10662
  timestamp: Date.now()
10339
10663
  });
10340
10664
  }
10341
- } catch (e) {
10665
+ } catch (_e) {
10342
10666
  }
10343
10667
  }
10344
10668
  /**
@@ -10494,7 +10818,7 @@ function createMCPStreamHelper() {
10494
10818
  }
10495
10819
 
10496
10820
  // src/handlers/executionHandler.ts
10497
- var logger22 = agentsCore.getLogger("ExecutionHandler");
10821
+ var logger23 = agentsCore.getLogger("ExecutionHandler");
10498
10822
  var ExecutionHandler = class {
10499
10823
  constructor() {
10500
10824
  __publicField(this, "MAX_ERRORS", 3);
@@ -10529,7 +10853,7 @@ var ExecutionHandler = class {
10529
10853
  if (emitOperations) {
10530
10854
  agentSessionManager.enableEmitOperations(requestId2);
10531
10855
  }
10532
- logger22.info(
10856
+ logger23.info(
10533
10857
  { sessionId: requestId2, agentId, conversationId, emitOperations },
10534
10858
  "Created AgentSession for message execution"
10535
10859
  );
@@ -10546,7 +10870,7 @@ var ExecutionHandler = class {
10546
10870
  );
10547
10871
  }
10548
10872
  } catch (error) {
10549
- logger22.error(
10873
+ logger23.error(
10550
10874
  {
10551
10875
  error: error instanceof Error ? error.message : "Unknown error",
10552
10876
  stack: error instanceof Error ? error.stack : void 0
@@ -10562,7 +10886,7 @@ var ExecutionHandler = class {
10562
10886
  try {
10563
10887
  await sseHelper.writeOperation(agentInitializingOp(requestId2, agentId));
10564
10888
  const taskId = `task_${conversationId}-${requestId2}`;
10565
- logger22.info(
10889
+ logger23.info(
10566
10890
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
10567
10891
  "Attempting to create or reuse existing task"
10568
10892
  );
@@ -10586,7 +10910,7 @@ var ExecutionHandler = class {
10586
10910
  sub_agent_id: currentAgentId
10587
10911
  }
10588
10912
  });
10589
- logger22.info(
10913
+ logger23.info(
10590
10914
  {
10591
10915
  taskId,
10592
10916
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -10595,27 +10919,27 @@ var ExecutionHandler = class {
10595
10919
  );
10596
10920
  } catch (error) {
10597
10921
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
10598
- logger22.info(
10922
+ logger23.info(
10599
10923
  { taskId, error: error.message },
10600
10924
  "Task already exists, fetching existing task"
10601
10925
  );
10602
10926
  const existingTask = await agentsCore.getTask(dbClient_default)({ id: taskId });
10603
10927
  if (existingTask) {
10604
10928
  task = existingTask;
10605
- logger22.info(
10929
+ logger23.info(
10606
10930
  { taskId, existingTask },
10607
10931
  "Successfully reused existing task from race condition"
10608
10932
  );
10609
10933
  } else {
10610
- logger22.error({ taskId, error }, "Task constraint failed but task not found");
10934
+ logger23.error({ taskId, error }, "Task constraint failed but task not found");
10611
10935
  throw error;
10612
10936
  }
10613
10937
  } else {
10614
- logger22.error({ taskId, error }, "Failed to create task due to non-constraint error");
10938
+ logger23.error({ taskId, error }, "Failed to create task due to non-constraint error");
10615
10939
  throw error;
10616
10940
  }
10617
10941
  }
10618
- logger22.debug(
10942
+ logger23.debug(
10619
10943
  {
10620
10944
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
10621
10945
  executionType: "create_initial_task",
@@ -10634,7 +10958,7 @@ var ExecutionHandler = class {
10634
10958
  const maxTransfers = agentConfig?.stopWhen?.transferCountIs ?? 10;
10635
10959
  while (iterations < maxTransfers) {
10636
10960
  iterations++;
10637
- logger22.info(
10961
+ logger23.info(
10638
10962
  { iterations, currentAgentId, agentId, conversationId, fromSubAgentId },
10639
10963
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromSubAgentId || "none"}`
10640
10964
  );
@@ -10642,10 +10966,10 @@ var ExecutionHandler = class {
10642
10966
  scopes: { tenantId, projectId },
10643
10967
  conversationId
10644
10968
  });
10645
- logger22.info({ activeAgent }, "activeAgent");
10969
+ logger23.info({ activeAgent }, "activeAgent");
10646
10970
  if (activeAgent && activeAgent.activeSubAgentId !== currentAgentId) {
10647
10971
  currentAgentId = activeAgent.activeSubAgentId;
10648
- logger22.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10972
+ logger23.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10649
10973
  }
10650
10974
  const agentBaseUrl = `${baseUrl}/agents`;
10651
10975
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -10686,13 +11010,13 @@ var ExecutionHandler = class {
10686
11010
  });
10687
11011
  if (!messageResponse?.result) {
10688
11012
  errorCount++;
10689
- logger22.error(
11013
+ logger23.error(
10690
11014
  { currentAgentId, iterations, errorCount },
10691
11015
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
10692
11016
  );
10693
11017
  if (errorCount >= this.MAX_ERRORS) {
10694
11018
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
10695
- logger22.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
11019
+ logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10696
11020
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
10697
11021
  if (task) {
10698
11022
  await agentsCore.updateTask(dbClient_default)({
@@ -10716,7 +11040,7 @@ var ExecutionHandler = class {
10716
11040
  if (isTransferTask(messageResponse.result)) {
10717
11041
  const transferData = extractTransferData(messageResponse.result);
10718
11042
  if (!transferData) {
10719
- logger22.error(
11043
+ logger23.error(
10720
11044
  { result: messageResponse.result },
10721
11045
  "Transfer detected but no transfer data found"
10722
11046
  );
@@ -10725,10 +11049,7 @@ var ExecutionHandler = class {
10725
11049
  const { targetSubAgentId, fromSubAgentId: transferFromAgent } = transferData;
10726
11050
  const firstArtifact = messageResponse.result.artifacts[0];
10727
11051
  const transferReason = firstArtifact?.parts[1]?.kind === "text" ? firstArtifact.parts[1].text : "Transfer initiated";
10728
- logger22.info(
10729
- { targetSubAgentId, transferReason, transferFromAgent },
10730
- "Transfer response"
10731
- );
11052
+ logger23.info({ targetSubAgentId, transferReason, transferFromAgent }, "Transfer response");
10732
11053
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
10733
11054
  const { success, targetSubAgentId: newAgentId } = await executeTransfer({
10734
11055
  projectId,
@@ -10739,7 +11060,7 @@ var ExecutionHandler = class {
10739
11060
  if (success) {
10740
11061
  fromSubAgentId = currentAgentId;
10741
11062
  currentAgentId = newAgentId;
10742
- logger22.info(
11063
+ logger23.info(
10743
11064
  {
10744
11065
  transferFrom: fromSubAgentId,
10745
11066
  transferTo: currentAgentId,
@@ -10753,7 +11074,7 @@ var ExecutionHandler = class {
10753
11074
  let responseParts = [];
10754
11075
  if (messageResponse.result.streamedContent?.parts) {
10755
11076
  responseParts = messageResponse.result.streamedContent.parts;
10756
- logger22.info(
11077
+ logger23.info(
10757
11078
  { partsCount: responseParts.length },
10758
11079
  "Using streamed content for conversation history"
10759
11080
  );
@@ -10761,7 +11082,7 @@ var ExecutionHandler = class {
10761
11082
  responseParts = messageResponse.result.artifacts?.flatMap(
10762
11083
  (artifact) => artifact.parts || []
10763
11084
  ) || [];
10764
- logger22.info(
11085
+ logger23.info(
10765
11086
  { partsCount: responseParts.length },
10766
11087
  "Using artifacts for conversation history (fallback)"
10767
11088
  );
@@ -10770,7 +11091,7 @@ var ExecutionHandler = class {
10770
11091
  const agentSessionData = agentSessionManager.getSession(requestId2);
10771
11092
  if (agentSessionData) {
10772
11093
  const sessionSummary = agentSessionData.getSummary();
10773
- logger22.info(sessionSummary, "AgentSession data after completion");
11094
+ logger23.info(sessionSummary, "AgentSession data after completion");
10774
11095
  }
10775
11096
  let textContent = "";
10776
11097
  for (const part of responseParts) {
@@ -10823,22 +11144,22 @@ var ExecutionHandler = class {
10823
11144
  }
10824
11145
  });
10825
11146
  const updateTaskEnd = Date.now();
10826
- logger22.info(
11147
+ logger23.info(
10827
11148
  { duration: updateTaskEnd - updateTaskStart },
10828
11149
  "Completed updateTask operation"
10829
11150
  );
10830
11151
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
10831
11152
  await sseHelper.complete();
10832
- logger22.info({}, "Ending AgentSession and cleaning up");
11153
+ logger23.info({}, "Ending AgentSession and cleaning up");
10833
11154
  agentSessionManager.endSession(requestId2);
10834
- logger22.info({}, "Cleaning up streamHelper");
11155
+ logger23.info({}, "Cleaning up streamHelper");
10835
11156
  unregisterStreamHelper(requestId2);
10836
11157
  let response;
10837
11158
  if (sseHelper instanceof MCPStreamHelper) {
10838
11159
  const captured = sseHelper.getCapturedResponse();
10839
11160
  response = captured.text || "No response content";
10840
11161
  }
10841
- logger22.info({}, "ExecutionHandler returning success");
11162
+ logger23.info({}, "ExecutionHandler returning success");
10842
11163
  return { success: true, iterations, response };
10843
11164
  } catch (error) {
10844
11165
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -10849,13 +11170,13 @@ var ExecutionHandler = class {
10849
11170
  });
10850
11171
  }
10851
11172
  errorCount++;
10852
- logger22.warn(
11173
+ logger23.warn(
10853
11174
  { iterations, errorCount },
10854
11175
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
10855
11176
  );
10856
11177
  if (errorCount >= this.MAX_ERRORS) {
10857
11178
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
10858
- logger22.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
11179
+ logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10859
11180
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
10860
11181
  if (task) {
10861
11182
  await agentsCore.updateTask(dbClient_default)({
@@ -10876,7 +11197,7 @@ var ExecutionHandler = class {
10876
11197
  }
10877
11198
  }
10878
11199
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
10879
- logger22.error({ maxTransfers, iterations }, errorMessage);
11200
+ logger23.error({ maxTransfers, iterations }, errorMessage);
10880
11201
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
10881
11202
  if (task) {
10882
11203
  await agentsCore.updateTask(dbClient_default)({
@@ -10895,7 +11216,7 @@ var ExecutionHandler = class {
10895
11216
  unregisterStreamHelper(requestId2);
10896
11217
  return { success: false, error: errorMessage, iterations };
10897
11218
  } catch (error) {
10898
- logger22.error({ error }, "Error in execution handler");
11219
+ logger23.error({ error }, "Error in execution handler");
10899
11220
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
10900
11221
  await sseHelper.writeOperation(
10901
11222
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -10923,7 +11244,7 @@ var ExecutionHandler = class {
10923
11244
  // src/routes/chat.ts
10924
11245
  init_logger();
10925
11246
  var app2 = new zodOpenapi.OpenAPIHono();
10926
- var logger23 = agentsCore.getLogger("completionsHandler");
11247
+ var logger24 = agentsCore.getLogger("completionsHandler");
10927
11248
  var chatCompletionsRoute = zodOpenapi.createRoute({
10928
11249
  method: "post",
10929
11250
  path: "/completions",
@@ -11041,7 +11362,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11041
11362
  tracestate: c.req.header("tracestate"),
11042
11363
  baggage: c.req.header("baggage")
11043
11364
  };
11044
- logger23.info(
11365
+ logger24.info(
11045
11366
  {
11046
11367
  otelHeaders,
11047
11368
  path: c.req.path,
@@ -11150,7 +11471,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11150
11471
  dbClient: dbClient_default,
11151
11472
  credentialStores
11152
11473
  });
11153
- logger23.info(
11474
+ logger24.info(
11154
11475
  {
11155
11476
  tenantId,
11156
11477
  projectId,
@@ -11198,7 +11519,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11198
11519
  try {
11199
11520
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
11200
11521
  await sseHelper.writeRole();
11201
- logger23.info({ subAgentId }, "Starting execution");
11522
+ logger24.info({ subAgentId }, "Starting execution");
11202
11523
  const emitOperationsHeader = c.req.header("x-emit-operations");
11203
11524
  const emitOperations = emitOperationsHeader === "true";
11204
11525
  const executionHandler = new ExecutionHandler();
@@ -11211,7 +11532,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11211
11532
  sseHelper,
11212
11533
  emitOperations
11213
11534
  });
11214
- logger23.info(
11535
+ logger24.info(
11215
11536
  { result },
11216
11537
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11217
11538
  );
@@ -11225,7 +11546,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11225
11546
  }
11226
11547
  await sseHelper.complete();
11227
11548
  } catch (error) {
11228
- logger23.error(
11549
+ logger24.error(
11229
11550
  {
11230
11551
  error: error instanceof Error ? error.message : error,
11231
11552
  stack: error instanceof Error ? error.stack : void 0
@@ -11242,13 +11563,13 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11242
11563
  );
11243
11564
  await sseHelper.complete();
11244
11565
  } catch (streamError) {
11245
- logger23.error({ streamError }, "Failed to write error to stream");
11566
+ logger24.error({ streamError }, "Failed to write error to stream");
11246
11567
  }
11247
11568
  }
11248
11569
  });
11249
11570
  });
11250
11571
  } catch (error) {
11251
- logger23.error(
11572
+ logger24.error(
11252
11573
  {
11253
11574
  error: error instanceof Error ? error.message : error,
11254
11575
  stack: error instanceof Error ? error.stack : void 0
@@ -11276,7 +11597,7 @@ var chat_default = app2;
11276
11597
  init_dbClient();
11277
11598
  init_logger();
11278
11599
  var app3 = new zodOpenapi.OpenAPIHono();
11279
- var logger24 = agentsCore.getLogger("chatDataStream");
11600
+ var logger25 = agentsCore.getLogger("chatDataStream");
11280
11601
  var chatDataStreamRoute = zodOpenapi.createRoute({
11281
11602
  method: "post",
11282
11603
  path: "/chat",
@@ -11400,7 +11721,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11400
11721
  });
11401
11722
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
11402
11723
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
11403
- logger24.info({ userText, lastUserMessage }, "userText");
11724
+ logger25.info({ userText, lastUserMessage }, "userText");
11404
11725
  const messageSpan = api.trace.getActiveSpan();
11405
11726
  if (messageSpan) {
11406
11727
  messageSpan.setAttributes({
@@ -11445,7 +11766,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11445
11766
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
11446
11767
  }
11447
11768
  } catch (err) {
11448
- logger24.error({ err }, "Streaming error");
11769
+ logger25.error({ err }, "Streaming error");
11449
11770
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
11450
11771
  } finally {
11451
11772
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -11467,7 +11788,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11467
11788
  );
11468
11789
  });
11469
11790
  } catch (error) {
11470
- logger24.error({ error }, "chatDataStream error");
11791
+ logger25.error({ error }, "chatDataStream error");
11471
11792
  throw agentsCore.createApiError({
11472
11793
  code: "internal_server_error",
11473
11794
  message: "Failed to process chat completion"
@@ -11482,7 +11803,7 @@ init_logger();
11482
11803
  function createMCPSchema(schema) {
11483
11804
  return schema;
11484
11805
  }
11485
- var logger25 = agentsCore.getLogger("mcp");
11806
+ var logger26 = agentsCore.getLogger("mcp");
11486
11807
  var _MockResponseSingleton = class _MockResponseSingleton {
11487
11808
  constructor() {
11488
11809
  __publicField(this, "mockRes");
@@ -11537,21 +11858,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
11537
11858
  id: 0
11538
11859
  });
11539
11860
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
11540
- logger25.info({ sessionId }, "Spoofing initialization message to set transport state");
11861
+ logger26.info({ sessionId }, "Spoofing initialization message to set transport state");
11541
11862
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
11542
11863
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
11543
11864
  try {
11544
11865
  await transport.handleRequest(req, mockRes, spoofInitMessage);
11545
- logger25.info({ sessionId }, "Successfully spoofed initialization");
11866
+ logger26.info({ sessionId }, "Successfully spoofed initialization");
11546
11867
  } catch (spoofError) {
11547
- logger25.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11868
+ logger26.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11548
11869
  }
11549
11870
  };
11550
11871
  var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
11551
11872
  const sessionId = req.headers["mcp-session-id"];
11552
- logger25.info({ sessionId }, "Received MCP session ID");
11873
+ logger26.info({ sessionId }, "Received MCP session ID");
11553
11874
  if (!sessionId) {
11554
- logger25.info({ body }, "Missing session ID");
11875
+ logger26.info({ body }, "Missing session ID");
11555
11876
  res.writeHead(400).end(
11556
11877
  JSON.stringify({
11557
11878
  jsonrpc: "2.0",
@@ -11577,7 +11898,7 @@ var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
11577
11898
  scopes: { tenantId, projectId },
11578
11899
  conversationId: sessionId
11579
11900
  });
11580
- logger25.info(
11901
+ logger26.info(
11581
11902
  {
11582
11903
  sessionId,
11583
11904
  conversationFound: !!conversation,
@@ -11588,7 +11909,7 @@ var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
11588
11909
  "Conversation lookup result"
11589
11910
  );
11590
11911
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.agentId !== agentId) {
11591
- logger25.info(
11912
+ logger26.info(
11592
11913
  { sessionId, conversationId: conversation?.id },
11593
11914
  "MCP session not found or invalid"
11594
11915
  );
@@ -11649,7 +11970,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultS
11649
11970
  requestId: requestId2,
11650
11971
  sseHelper: mcpStreamHelper
11651
11972
  });
11652
- logger25.info(
11973
+ logger26.info(
11653
11974
  { result },
11654
11975
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11655
11976
  );
@@ -11733,7 +12054,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11733
12054
  dbClient: dbClient_default,
11734
12055
  credentialStores
11735
12056
  });
11736
- logger25.info(
12057
+ logger26.info(
11737
12058
  {
11738
12059
  tenantId,
11739
12060
  projectId,
@@ -11795,7 +12116,7 @@ var validateRequestParameters = (c) => {
11795
12116
  };
11796
12117
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
11797
12118
  const { tenantId, projectId, agentId } = executionContext;
11798
- logger25.info({ body }, "Received initialization request");
12119
+ logger26.info({ body }, "Received initialization request");
11799
12120
  const sessionId = agentsCore.getConversationId();
11800
12121
  const activeSpan = api.trace.getActiveSpan();
11801
12122
  if (activeSpan) {
@@ -11851,7 +12172,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11851
12172
  }
11852
12173
  }
11853
12174
  });
11854
- logger25.info(
12175
+ logger26.info(
11855
12176
  { sessionId, conversationId: conversation.id },
11856
12177
  "Created MCP session as conversation"
11857
12178
  );
@@ -11860,9 +12181,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11860
12181
  });
11861
12182
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
11862
12183
  await server.connect(transport);
11863
- logger25.info({ sessionId }, "Server connected for initialization");
12184
+ logger26.info({ sessionId }, "Server connected for initialization");
11864
12185
  res.setHeader("Mcp-Session-Id", sessionId);
11865
- logger25.info(
12186
+ logger26.info(
11866
12187
  {
11867
12188
  sessionId,
11868
12189
  bodyMethod: body?.method,
@@ -11871,7 +12192,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11871
12192
  "About to handle initialization request"
11872
12193
  );
11873
12194
  await transport.handleRequest(req, res, body);
11874
- logger25.info({ sessionId }, "Successfully handled initialization request");
12195
+ logger26.info({ sessionId }, "Successfully handled initialization request");
11875
12196
  return fetchToNode.toFetchResponse(res);
11876
12197
  });
11877
12198
  };
@@ -11898,8 +12219,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
11898
12219
  sessionId,
11899
12220
  conversation.metadata?.session_data?.mcpProtocolVersion
11900
12221
  );
11901
- logger25.info({ sessionId }, "Server connected and transport initialized");
11902
- logger25.info(
12222
+ logger26.info({ sessionId }, "Server connected and transport initialized");
12223
+ logger26.info(
11903
12224
  {
11904
12225
  sessionId,
11905
12226
  bodyKeys: Object.keys(body || {}),
@@ -11913,9 +12234,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
11913
12234
  );
11914
12235
  try {
11915
12236
  await transport.handleRequest(req, res, body);
11916
- logger25.info({ sessionId }, "Successfully handled MCP request");
12237
+ logger26.info({ sessionId }, "Successfully handled MCP request");
11917
12238
  } catch (transportError) {
11918
- logger25.error(
12239
+ logger26.error(
11919
12240
  {
11920
12241
  sessionId,
11921
12242
  error: transportError,
@@ -11966,13 +12287,13 @@ app4.openapi(
11966
12287
  }
11967
12288
  const { executionContext } = paramValidation;
11968
12289
  const body = c.get("requestBody") || {};
11969
- logger25.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
12290
+ logger26.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
11970
12291
  const isInitRequest = body.method === "initialize";
11971
12292
  const { req, res } = fetchToNode.toReqRes(c.req.raw);
11972
12293
  const validatedContext = c.get("validatedContext") || {};
11973
12294
  const credentialStores = c.get("credentialStores");
11974
- logger25.info({ validatedContext }, "Validated context");
11975
- logger25.info({ req }, "request");
12295
+ logger26.info({ validatedContext }, "Validated context");
12296
+ logger26.info({ req }, "request");
11976
12297
  if (isInitRequest) {
11977
12298
  return await handleInitializationRequest(
11978
12299
  body,
@@ -11994,7 +12315,7 @@ app4.openapi(
11994
12315
  );
11995
12316
  }
11996
12317
  } catch (e) {
11997
- logger25.error(
12318
+ logger26.error(
11998
12319
  {
11999
12320
  error: e instanceof Error ? e.message : e,
12000
12321
  stack: e instanceof Error ? e.stack : void 0
@@ -12006,7 +12327,7 @@ app4.openapi(
12006
12327
  }
12007
12328
  );
12008
12329
  app4.get("/", async (c) => {
12009
- logger25.info({}, "Received GET MCP request");
12330
+ logger26.info({}, "Received GET MCP request");
12010
12331
  return c.json(
12011
12332
  {
12012
12333
  jsonrpc: "2.0",
@@ -12020,7 +12341,7 @@ app4.get("/", async (c) => {
12020
12341
  );
12021
12342
  });
12022
12343
  app4.delete("/", async (c) => {
12023
- logger25.info({}, "Received DELETE MCP request");
12344
+ logger26.info({}, "Received DELETE MCP request");
12024
12345
  return c.json(
12025
12346
  {
12026
12347
  jsonrpc: "2.0",
@@ -12033,14 +12354,17 @@ app4.delete("/", async (c) => {
12033
12354
  var mcp_default = app4;
12034
12355
 
12035
12356
  // src/app.ts
12036
- var logger26 = agentsCore.getLogger("agents-run-api");
12037
- function createExecutionHono(serverConfig, credentialStores) {
12357
+ var logger27 = agentsCore.getLogger("agents-run-api");
12358
+ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12038
12359
  const app6 = new zodOpenapi.OpenAPIHono();
12039
12360
  app6.use("*", otel.otel());
12040
12361
  app6.use("*", requestId.requestId());
12041
12362
  app6.use("*", async (c, next) => {
12042
12363
  c.set("serverConfig", serverConfig);
12043
12364
  c.set("credentialStores", credentialStores);
12365
+ if (sandboxConfig) {
12366
+ c.set("sandboxConfig", sandboxConfig);
12367
+ }
12044
12368
  return next();
12045
12369
  });
12046
12370
  app6.use("*", async (c, next) => {
@@ -12049,7 +12373,7 @@ function createExecutionHono(serverConfig, credentialStores) {
12049
12373
  const body = await c.req.json();
12050
12374
  c.set("requestBody", body);
12051
12375
  } catch (error) {
12052
- logger26.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
12376
+ logger27.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
12053
12377
  }
12054
12378
  }
12055
12379
  return next();
@@ -12100,8 +12424,8 @@ function createExecutionHono(serverConfig, credentialStores) {
12100
12424
  if (!isExpectedError) {
12101
12425
  const errorMessage = err instanceof Error ? err.message : String(err);
12102
12426
  const errorStack = err instanceof Error ? err.stack : void 0;
12103
- if (logger26) {
12104
- logger26.error(
12427
+ if (logger27) {
12428
+ logger27.error(
12105
12429
  {
12106
12430
  error: err,
12107
12431
  message: errorMessage,
@@ -12113,8 +12437,8 @@ function createExecutionHono(serverConfig, credentialStores) {
12113
12437
  );
12114
12438
  }
12115
12439
  } else {
12116
- if (logger26) {
12117
- logger26.error(
12440
+ if (logger27) {
12441
+ logger27.error(
12118
12442
  {
12119
12443
  error: err,
12120
12444
  path: c.req.path,
@@ -12131,8 +12455,8 @@ function createExecutionHono(serverConfig, credentialStores) {
12131
12455
  const response = err.getResponse();
12132
12456
  return response;
12133
12457
  } catch (responseError) {
12134
- if (logger26) {
12135
- logger26.error({ error: responseError }, "Error while handling HTTPException response");
12458
+ if (logger27) {
12459
+ logger27.error({ error: responseError }, "Error while handling HTTPException response");
12136
12460
  }
12137
12461
  }
12138
12462
  }
@@ -12166,7 +12490,7 @@ function createExecutionHono(serverConfig, credentialStores) {
12166
12490
  app6.use("*", async (c, next) => {
12167
12491
  const executionContext = c.get("executionContext");
12168
12492
  if (!executionContext) {
12169
- logger26.debug({}, "Empty execution context");
12493
+ logger27.debug({}, "Empty execution context");
12170
12494
  return next();
12171
12495
  }
12172
12496
  const { tenantId, projectId, agentId } = executionContext;
@@ -12175,7 +12499,7 @@ function createExecutionHono(serverConfig, credentialStores) {
12175
12499
  if (requestBody) {
12176
12500
  conversationId = requestBody.conversationId;
12177
12501
  if (!conversationId) {
12178
- logger26.debug({ requestBody }, "No conversation ID found in request body");
12502
+ logger27.debug({ requestBody }, "No conversation ID found in request body");
12179
12503
  }
12180
12504
  }
12181
12505
  const entries = Object.fromEntries(
@@ -12190,7 +12514,7 @@ function createExecutionHono(serverConfig, credentialStores) {
12190
12514
  })
12191
12515
  );
12192
12516
  if (!Object.keys(entries).length) {
12193
- logger26.debug({}, "Empty entries for baggage");
12517
+ logger27.debug({}, "Empty entries for baggage");
12194
12518
  return next();
12195
12519
  }
12196
12520
  const bag = Object.entries(entries).reduce(
@@ -12261,7 +12585,7 @@ function createExecutionApp(config) {
12261
12585
  const serverConfig = config?.serverConfig ?? defaultConfig;
12262
12586
  const stores = config?.credentialStores ?? defaultStores;
12263
12587
  const registry = new agentsCore.CredentialStoreRegistry(stores);
12264
- return createExecutionHono(serverConfig, registry);
12588
+ return createExecutionHono(serverConfig, registry, config?.sandboxConfig);
12265
12589
  }
12266
12590
 
12267
12591
  exports.createExecutionApp = createExecutionApp;