@inkeep/agents-run-api 0.39.5 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase1/system-prompt.js +5 -0
  2. package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase1/thinking-preparation.js +5 -0
  3. package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase1/tool.js +5 -0
  4. package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase2/data-component.js +5 -0
  5. package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase2/data-components.js +5 -0
  6. package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase2/system-prompt.js +5 -0
  7. package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/shared/artifact-retrieval-guidance.js +5 -0
  8. package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/shared/artifact.js +5 -0
  9. package/dist/a2a/client.d.ts +184 -0
  10. package/dist/a2a/client.js +510 -0
  11. package/dist/a2a/handlers.d.ts +7 -0
  12. package/dist/a2a/handlers.js +576 -0
  13. package/dist/a2a/transfer.d.ts +22 -0
  14. package/dist/a2a/transfer.js +46 -0
  15. package/dist/a2a/types.d.ts +79 -0
  16. package/dist/a2a/types.js +22 -0
  17. package/dist/agents/Agent.d.ts +268 -0
  18. package/dist/agents/Agent.js +1932 -0
  19. package/dist/agents/ModelFactory.d.ts +63 -0
  20. package/dist/agents/ModelFactory.js +194 -0
  21. package/dist/agents/SystemPromptBuilder.d.ts +21 -0
  22. package/dist/agents/SystemPromptBuilder.js +48 -0
  23. package/dist/agents/ToolSessionManager.d.ts +63 -0
  24. package/dist/agents/ToolSessionManager.js +146 -0
  25. package/dist/agents/generateTaskHandler.d.ts +49 -0
  26. package/dist/agents/generateTaskHandler.js +523 -0
  27. package/dist/agents/relationTools.d.ts +57 -0
  28. package/dist/agents/relationTools.js +262 -0
  29. package/dist/agents/types.d.ts +28 -0
  30. package/dist/agents/types.js +1 -0
  31. package/dist/agents/versions/v1/Phase1Config.d.ts +27 -0
  32. package/dist/agents/versions/v1/Phase1Config.js +424 -0
  33. package/dist/agents/versions/v1/Phase2Config.d.ts +31 -0
  34. package/dist/agents/versions/v1/Phase2Config.js +330 -0
  35. package/dist/constants/execution-limits/defaults.d.ts +51 -0
  36. package/dist/constants/execution-limits/defaults.js +52 -0
  37. package/dist/constants/execution-limits/index.d.ts +6 -0
  38. package/dist/constants/execution-limits/index.js +21 -0
  39. package/dist/create-app.d.ts +9 -0
  40. package/dist/create-app.js +195 -0
  41. package/dist/data/agent.d.ts +7 -0
  42. package/dist/data/agent.js +72 -0
  43. package/dist/data/agents.d.ts +34 -0
  44. package/dist/data/agents.js +139 -0
  45. package/dist/data/conversations.d.ts +128 -0
  46. package/dist/data/conversations.js +522 -0
  47. package/dist/data/db/dbClient.d.ts +6 -0
  48. package/dist/data/db/dbClient.js +17 -0
  49. package/dist/env.d.ts +57 -0
  50. package/dist/env.js +1 -2
  51. package/dist/handlers/executionHandler.d.ts +41 -0
  52. package/dist/handlers/executionHandler.js +457 -0
  53. package/dist/index.d.ts +8 -29
  54. package/dist/index.js +5 -11386
  55. package/dist/instrumentation.d.ts +1 -2
  56. package/dist/instrumentation.js +66 -3
  57. package/dist/{logger2.js → logger.d.ts} +1 -2
  58. package/dist/logger.js +1 -1
  59. package/dist/middleware/api-key-auth.d.ts +26 -0
  60. package/dist/middleware/api-key-auth.js +240 -0
  61. package/dist/middleware/index.d.ts +2 -0
  62. package/dist/middleware/index.js +3 -0
  63. package/dist/openapi.d.ts +4 -0
  64. package/dist/openapi.js +54 -0
  65. package/dist/routes/agents.d.ts +12 -0
  66. package/dist/routes/agents.js +147 -0
  67. package/dist/routes/chat.d.ts +13 -0
  68. package/dist/routes/chat.js +305 -0
  69. package/dist/routes/chatDataStream.d.ts +13 -0
  70. package/dist/routes/chatDataStream.js +365 -0
  71. package/dist/routes/mcp.d.ts +13 -0
  72. package/dist/routes/mcp.js +495 -0
  73. package/dist/services/AgentSession.d.ts +356 -0
  74. package/dist/services/AgentSession.js +1208 -0
  75. package/dist/services/ArtifactParser.d.ts +105 -0
  76. package/dist/services/ArtifactParser.js +338 -0
  77. package/dist/services/ArtifactService.d.ts +123 -0
  78. package/dist/services/ArtifactService.js +612 -0
  79. package/dist/services/BaseCompressor.d.ts +183 -0
  80. package/dist/services/BaseCompressor.js +500 -0
  81. package/dist/services/ConversationCompressor.d.ts +32 -0
  82. package/dist/services/ConversationCompressor.js +91 -0
  83. package/dist/services/IncrementalStreamParser.d.ts +98 -0
  84. package/dist/services/IncrementalStreamParser.js +327 -0
  85. package/dist/services/MidGenerationCompressor.d.ts +63 -0
  86. package/dist/services/MidGenerationCompressor.js +104 -0
  87. package/dist/services/PendingToolApprovalManager.d.ts +62 -0
  88. package/dist/services/PendingToolApprovalManager.js +133 -0
  89. package/dist/services/ResponseFormatter.d.ts +39 -0
  90. package/dist/services/ResponseFormatter.js +152 -0
  91. package/dist/tools/NativeSandboxExecutor.d.ts +38 -0
  92. package/dist/tools/NativeSandboxExecutor.js +432 -0
  93. package/dist/tools/SandboxExecutorFactory.d.ts +36 -0
  94. package/dist/tools/SandboxExecutorFactory.js +80 -0
  95. package/dist/tools/VercelSandboxExecutor.d.ts +71 -0
  96. package/dist/tools/VercelSandboxExecutor.js +340 -0
  97. package/dist/tools/distill-conversation-history-tool.d.ts +62 -0
  98. package/dist/tools/distill-conversation-history-tool.js +206 -0
  99. package/dist/tools/distill-conversation-tool.d.ts +41 -0
  100. package/dist/tools/distill-conversation-tool.js +141 -0
  101. package/dist/tools/sandbox-utils.d.ts +18 -0
  102. package/dist/tools/sandbox-utils.js +53 -0
  103. package/dist/types/chat.d.ts +27 -0
  104. package/dist/types/chat.js +1 -0
  105. package/dist/types/execution-context.d.ts +46 -0
  106. package/dist/types/execution-context.js +27 -0
  107. package/dist/types/xml.d.ts +5 -0
  108. package/dist/utils/SchemaProcessor.d.ts +52 -0
  109. package/dist/utils/SchemaProcessor.js +182 -0
  110. package/dist/utils/agent-operations.d.ts +62 -0
  111. package/dist/utils/agent-operations.js +53 -0
  112. package/dist/utils/artifact-component-schema.d.ts +42 -0
  113. package/dist/utils/artifact-component-schema.js +186 -0
  114. package/dist/utils/cleanup.d.ts +21 -0
  115. package/dist/utils/cleanup.js +59 -0
  116. package/dist/utils/data-component-schema.d.ts +2 -0
  117. package/dist/utils/data-component-schema.js +3 -0
  118. package/dist/utils/default-status-schemas.d.ts +20 -0
  119. package/dist/utils/default-status-schemas.js +24 -0
  120. package/dist/utils/json-postprocessor.d.ts +13 -0
  121. package/dist/{json-postprocessor.cjs → utils/json-postprocessor.js} +2 -3
  122. package/dist/utils/model-context-utils.d.ts +39 -0
  123. package/dist/utils/model-context-utils.js +181 -0
  124. package/dist/utils/model-resolver.d.ts +6 -0
  125. package/dist/utils/model-resolver.js +34 -0
  126. package/dist/utils/schema-validation.d.ts +44 -0
  127. package/dist/utils/schema-validation.js +97 -0
  128. package/dist/utils/stream-helpers.d.ts +197 -0
  129. package/dist/utils/stream-helpers.js +518 -0
  130. package/dist/utils/stream-registry.d.ts +22 -0
  131. package/dist/utils/stream-registry.js +34 -0
  132. package/dist/utils/token-estimator.d.ts +69 -0
  133. package/dist/utils/token-estimator.js +53 -0
  134. package/dist/utils/tracer.d.ts +7 -0
  135. package/dist/utils/tracer.js +7 -0
  136. package/package.json +10 -26
  137. package/dist/SandboxExecutorFactory.cjs +0 -895
  138. package/dist/SandboxExecutorFactory.js +0 -893
  139. package/dist/SandboxExecutorFactory.js.map +0 -1
  140. package/dist/chunk-VBDAOXYI.cjs +0 -927
  141. package/dist/chunk-VBDAOXYI.js +0 -832
  142. package/dist/chunk-VBDAOXYI.js.map +0 -1
  143. package/dist/chunk.cjs +0 -34
  144. package/dist/conversations.cjs +0 -7
  145. package/dist/conversations.js +0 -7
  146. package/dist/conversations2.cjs +0 -209
  147. package/dist/conversations2.js +0 -180
  148. package/dist/conversations2.js.map +0 -1
  149. package/dist/dbClient.cjs +0 -9676
  150. package/dist/dbClient.js +0 -9670
  151. package/dist/dbClient.js.map +0 -1
  152. package/dist/dbClient2.cjs +0 -5
  153. package/dist/dbClient2.js +0 -5
  154. package/dist/env.cjs +0 -59
  155. package/dist/env.js.map +0 -1
  156. package/dist/execution-limits.cjs +0 -260
  157. package/dist/execution-limits.js +0 -63
  158. package/dist/execution-limits.js.map +0 -1
  159. package/dist/index.cjs +0 -11411
  160. package/dist/index.d.cts +0 -36
  161. package/dist/index.d.cts.map +0 -1
  162. package/dist/index.d.ts.map +0 -1
  163. package/dist/index.js.map +0 -1
  164. package/dist/instrumentation.cjs +0 -12
  165. package/dist/instrumentation.d.cts +0 -18
  166. package/dist/instrumentation.d.cts.map +0 -1
  167. package/dist/instrumentation.d.ts.map +0 -1
  168. package/dist/instrumentation2.cjs +0 -116
  169. package/dist/instrumentation2.js +0 -69
  170. package/dist/instrumentation2.js.map +0 -1
  171. package/dist/json-postprocessor.js +0 -20
  172. package/dist/json-postprocessor.js.map +0 -1
  173. package/dist/logger.cjs +0 -5
  174. package/dist/logger2.cjs +0 -1
  175. package/dist/nodefs.cjs +0 -29
  176. package/dist/nodefs.js +0 -27
  177. package/dist/nodefs.js.map +0 -1
  178. package/dist/opfs-ahp.cjs +0 -367
  179. package/dist/opfs-ahp.js +0 -368
  180. package/dist/opfs-ahp.js.map +0 -1
@@ -0,0 +1,340 @@
1
+ import { getLogger } from "../logger.js";
2
+ import { FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS, FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT, FUNCTION_TOOL_SANDBOX_POOL_TTL_MS } from "../constants/execution-limits/index.js";
3
+ import { createExecutionWrapper, parseExecutionResult } from "./sandbox-utils.js";
4
+ import crypto from "node:crypto";
5
+ import { Sandbox } from "@vercel/sandbox";
6
+
7
+ //#region src/tools/VercelSandboxExecutor.ts
8
+ const logger = getLogger("VercelSandboxExecutor");
9
+ /**
10
+ * Vercel Sandbox Executor with pooling/reuse
11
+ * Executes function tools in isolated Vercel Sandbox MicroVMs
12
+ * Caches and reuses sandboxes based on dependencies to improve performance
13
+ */
14
+ var VercelSandboxExecutor = class VercelSandboxExecutor {
15
+ static instance;
16
+ config;
17
+ sandboxPool = /* @__PURE__ */ new Map();
18
+ cleanupInterval = null;
19
+ constructor(config) {
20
+ this.config = config;
21
+ logger.info({
22
+ teamId: config.teamId,
23
+ projectId: config.projectId,
24
+ runtime: config.runtime,
25
+ timeout: config.timeout,
26
+ vcpus: config.vcpus
27
+ }, "VercelSandboxExecutor initialized with pooling");
28
+ this.startPoolCleanup();
29
+ }
30
+ /**
31
+ * Get singleton instance of VercelSandboxExecutor
32
+ */
33
+ static getInstance(config) {
34
+ if (!VercelSandboxExecutor.instance) VercelSandboxExecutor.instance = new VercelSandboxExecutor(config);
35
+ return VercelSandboxExecutor.instance;
36
+ }
37
+ /**
38
+ * Generate a hash for dependencies to use as cache key
39
+ */
40
+ generateDependencyHash(dependencies) {
41
+ const sorted = Object.keys(dependencies).sort().map((key) => `${key}@${dependencies[key]}`).join(",");
42
+ return crypto.createHash("md5").update(sorted).digest("hex").substring(0, 8);
43
+ }
44
+ /**
45
+ * Get a cached sandbox if available and still valid
46
+ */
47
+ getCachedSandbox(dependencyHash) {
48
+ const cached = this.sandboxPool.get(dependencyHash);
49
+ if (!cached) return null;
50
+ const age = Date.now() - cached.createdAt;
51
+ if (age > FUNCTION_TOOL_SANDBOX_POOL_TTL_MS || cached.useCount >= FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
52
+ logger.debug({
53
+ dependencyHash,
54
+ age,
55
+ useCount: cached.useCount,
56
+ ttl: FUNCTION_TOOL_SANDBOX_POOL_TTL_MS,
57
+ maxUseCount: FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT
58
+ }, "Sandbox expired, will create new one");
59
+ this.removeSandbox(dependencyHash);
60
+ return null;
61
+ }
62
+ logger.debug({
63
+ dependencyHash,
64
+ useCount: cached.useCount,
65
+ age
66
+ }, "Reusing cached sandbox");
67
+ return cached.sandbox;
68
+ }
69
+ /**
70
+ * Add sandbox to pool
71
+ */
72
+ addToPool(dependencyHash, sandbox, dependencies) {
73
+ this.sandboxPool.set(dependencyHash, {
74
+ sandbox,
75
+ createdAt: Date.now(),
76
+ useCount: 0,
77
+ dependencies
78
+ });
79
+ logger.debug({
80
+ dependencyHash,
81
+ poolSize: this.sandboxPool.size
82
+ }, "Sandbox added to pool");
83
+ }
84
+ /**
85
+ * Increment use count for a sandbox
86
+ */
87
+ incrementUseCount(dependencyHash) {
88
+ const cached = this.sandboxPool.get(dependencyHash);
89
+ if (cached) cached.useCount++;
90
+ }
91
+ /**
92
+ * Remove and clean up a sandbox
93
+ */
94
+ async removeSandbox(dependencyHash) {
95
+ const cached = this.sandboxPool.get(dependencyHash);
96
+ if (cached) {
97
+ try {
98
+ await cached.sandbox.stop();
99
+ logger.debug({ dependencyHash }, "Sandbox stopped");
100
+ } catch (error) {
101
+ logger.warn({
102
+ error,
103
+ dependencyHash
104
+ }, "Error stopping sandbox");
105
+ }
106
+ this.sandboxPool.delete(dependencyHash);
107
+ }
108
+ }
109
+ /**
110
+ * Start periodic cleanup of expired sandboxes
111
+ */
112
+ startPoolCleanup() {
113
+ this.cleanupInterval = setInterval(() => {
114
+ const now = Date.now();
115
+ const toRemove = [];
116
+ for (const [hash, cached] of this.sandboxPool.entries()) if (now - cached.createdAt > FUNCTION_TOOL_SANDBOX_POOL_TTL_MS || cached.useCount >= FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) toRemove.push(hash);
117
+ if (toRemove.length > 0) {
118
+ logger.info({
119
+ count: toRemove.length,
120
+ poolSize: this.sandboxPool.size
121
+ }, "Cleaning up expired sandboxes");
122
+ for (const hash of toRemove) this.removeSandbox(hash);
123
+ }
124
+ }, FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS);
125
+ }
126
+ /**
127
+ * Cleanup all sandboxes and stop cleanup interval
128
+ */
129
+ async cleanup() {
130
+ if (this.cleanupInterval) {
131
+ clearInterval(this.cleanupInterval);
132
+ this.cleanupInterval = null;
133
+ }
134
+ logger.info({ poolSize: this.sandboxPool.size }, "Cleaning up all sandboxes");
135
+ const promises = Array.from(this.sandboxPool.keys()).map((hash) => this.removeSandbox(hash));
136
+ await Promise.all(promises);
137
+ }
138
+ /**
139
+ * Extract environment variable names from code
140
+ * Matches patterns like process.env.VAR_NAME or process.env['VAR_NAME']
141
+ */
142
+ extractEnvVars(code) {
143
+ const envVars = /* @__PURE__ */ new Set();
144
+ const dotNotationRegex = /process\.env\.([A-Z_][A-Z0-9_]*)/g;
145
+ let match = dotNotationRegex.exec(code);
146
+ while (match !== null) {
147
+ envVars.add(match[1]);
148
+ match = dotNotationRegex.exec(code);
149
+ }
150
+ const bracketNotationRegex = /process\.env\[['"]([A-Z_][A-Z0-9_]*)['"]\]/g;
151
+ match = bracketNotationRegex.exec(code);
152
+ while (match !== null) {
153
+ envVars.add(match[1]);
154
+ match = bracketNotationRegex.exec(code);
155
+ }
156
+ return envVars;
157
+ }
158
+ /**
159
+ * Create .env file content from environment variables
160
+ * Note: Currently creates empty placeholders. Values will be populated in the future.
161
+ */
162
+ createEnvFileContent(envVarNames) {
163
+ const envLines = [];
164
+ for (const varName of envVarNames) {
165
+ envLines.push(`${varName}=""`);
166
+ logger.debug({ varName }, "Adding environment variable placeholder to sandbox");
167
+ }
168
+ return envLines.join("\n");
169
+ }
170
+ /**
171
+ * Execute a function tool in Vercel Sandbox with pooling
172
+ */
173
+ async executeFunctionTool(functionId, args, toolConfig) {
174
+ const startTime = Date.now();
175
+ const logs = [];
176
+ const dependencies = toolConfig.dependencies || {};
177
+ const dependencyHash = this.generateDependencyHash(dependencies);
178
+ try {
179
+ logger.info({
180
+ functionId,
181
+ functionName: toolConfig.name,
182
+ dependencyHash,
183
+ poolSize: this.sandboxPool.size
184
+ }, "Executing function in Vercel Sandbox");
185
+ let sandbox = this.getCachedSandbox(dependencyHash);
186
+ let isNewSandbox = false;
187
+ if (!sandbox) {
188
+ isNewSandbox = true;
189
+ sandbox = await Sandbox.create({
190
+ token: this.config.token,
191
+ teamId: this.config.teamId,
192
+ projectId: this.config.projectId,
193
+ timeout: this.config.timeout,
194
+ resources: { vcpus: this.config.vcpus || 1 },
195
+ runtime: this.config.runtime
196
+ });
197
+ logger.info({
198
+ functionId,
199
+ sandboxId: sandbox.sandboxId,
200
+ dependencyHash
201
+ }, `New sandbox created for function ${functionId}`);
202
+ this.addToPool(dependencyHash, sandbox, dependencies);
203
+ } else logger.info({
204
+ functionId,
205
+ sandboxId: sandbox.sandboxId,
206
+ dependencyHash
207
+ }, `Reusing cached sandbox for function ${functionId}`);
208
+ this.incrementUseCount(dependencyHash);
209
+ try {
210
+ if (isNewSandbox && toolConfig.dependencies && Object.keys(toolConfig.dependencies).length > 0) {
211
+ logger.debug({
212
+ functionId,
213
+ functionName: toolConfig.name,
214
+ dependencies: toolConfig.dependencies
215
+ }, "Installing dependencies in new sandbox");
216
+ const packageJson = { dependencies: toolConfig.dependencies };
217
+ const packageJsonContent = JSON.stringify(packageJson, null, 2);
218
+ await sandbox.writeFiles([{
219
+ path: "package.json",
220
+ content: Buffer.from(packageJsonContent, "utf-8")
221
+ }]);
222
+ const installCmd = await sandbox.runCommand({
223
+ cmd: "npm",
224
+ args: ["install", "--omit=dev"]
225
+ });
226
+ const installStdout = await installCmd.stdout();
227
+ const installStderr = await installCmd.stderr();
228
+ if (installStdout) logs.push(installStdout);
229
+ if (installStderr) logs.push(installStderr);
230
+ if (installCmd.exitCode !== 0) throw new Error(`Failed to install dependencies: ${installStderr}`);
231
+ logger.info({
232
+ functionId,
233
+ dependencyHash
234
+ }, "Dependencies installed successfully");
235
+ }
236
+ const executionCode = createExecutionWrapper(toolConfig.executeCode, args);
237
+ const envVars = this.extractEnvVars(toolConfig.executeCode);
238
+ const filesToWrite = [];
239
+ const filename = this.config.runtime === "typescript" ? "execute.ts" : "execute.js";
240
+ filesToWrite.push({
241
+ path: filename,
242
+ content: Buffer.from(executionCode, "utf-8")
243
+ });
244
+ if (envVars.size > 0) {
245
+ const envFileContent = this.createEnvFileContent(envVars);
246
+ if (envFileContent) {
247
+ filesToWrite.push({
248
+ path: ".env",
249
+ content: Buffer.from(envFileContent, "utf-8")
250
+ });
251
+ logger.info({
252
+ functionId,
253
+ envVarCount: envVars.size,
254
+ envVars: Array.from(envVars)
255
+ }, "Creating environment variable placeholders in sandbox");
256
+ }
257
+ }
258
+ await sandbox.writeFiles(filesToWrite);
259
+ logger.info({
260
+ functionId,
261
+ runtime: this.config.runtime === "typescript" ? "tsx" : "node",
262
+ hasEnvVars: envVars.size > 0
263
+ }, `Execution code written to file for runtime ${this.config.runtime}`);
264
+ const executeCmd = await (async () => {
265
+ if (envVars.size > 0) return sandbox.runCommand({
266
+ cmd: "npx",
267
+ args: this.config.runtime === "typescript" ? [
268
+ "--yes",
269
+ "dotenv-cli",
270
+ "--",
271
+ "npx",
272
+ "tsx",
273
+ filename
274
+ ] : [
275
+ "--yes",
276
+ "dotenv-cli",
277
+ "--",
278
+ "node",
279
+ filename
280
+ ]
281
+ });
282
+ const runtime = this.config.runtime === "typescript" ? "tsx" : "node";
283
+ return sandbox.runCommand({
284
+ cmd: runtime,
285
+ args: [filename]
286
+ });
287
+ })();
288
+ const executeStdout = await executeCmd.stdout();
289
+ const executeStderr = await executeCmd.stderr();
290
+ if (executeStdout) logs.push(executeStdout);
291
+ if (executeStderr) logs.push(executeStderr);
292
+ const executionTime = Date.now() - startTime;
293
+ if (executeCmd.exitCode !== 0) {
294
+ logger.error({
295
+ functionId,
296
+ exitCode: executeCmd.exitCode,
297
+ stderr: executeStderr
298
+ }, "Function execution failed");
299
+ return {
300
+ success: false,
301
+ error: executeStderr || "Function execution failed with non-zero exit code",
302
+ logs,
303
+ executionTime
304
+ };
305
+ }
306
+ const result = parseExecutionResult(executeStdout, functionId, logger);
307
+ logger.info({
308
+ functionId,
309
+ executionTime
310
+ }, "Function executed successfully in Vercel Sandbox");
311
+ return {
312
+ success: true,
313
+ result,
314
+ logs,
315
+ executionTime
316
+ };
317
+ } catch (innerError) {
318
+ await this.removeSandbox(dependencyHash);
319
+ throw innerError;
320
+ }
321
+ } catch (error) {
322
+ const executionTime = Date.now() - startTime;
323
+ const errorMessage = error instanceof Error ? error.message : String(error);
324
+ logger.error({
325
+ functionId,
326
+ error: errorMessage,
327
+ executionTime
328
+ }, "Vercel Sandbox execution error");
329
+ return {
330
+ success: false,
331
+ error: errorMessage,
332
+ logs,
333
+ executionTime
334
+ };
335
+ }
336
+ }
337
+ };
338
+
339
+ //#endregion
340
+ export { VercelSandboxExecutor };
@@ -0,0 +1,62 @@
1
+ import { ModelSettings } from "@inkeep/agents-core";
2
+ import { z } from "zod";
3
+
4
+ //#region src/tools/distill-conversation-history-tool.d.ts
5
+
6
+ /**
7
+ * Conversation History Summary Schema - structured object for replacing entire conversation histories
8
+ */
9
+ declare const ConversationHistorySummarySchema: z.ZodObject<{
10
+ type: z.ZodLiteral<"conversation_history_summary_v1">;
11
+ session_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
+ conversation_overview: z.ZodString;
13
+ user_goals: z.ZodObject<{
14
+ primary: z.ZodString;
15
+ secondary: z.ZodArray<z.ZodString>;
16
+ }, z.core.$strip>;
17
+ key_outcomes: z.ZodObject<{
18
+ completed: z.ZodArray<z.ZodString>;
19
+ partial: z.ZodArray<z.ZodString>;
20
+ discoveries: z.ZodArray<z.ZodString>;
21
+ }, z.core.$strip>;
22
+ technical_context: z.ZodObject<{
23
+ technologies: z.ZodArray<z.ZodString>;
24
+ configurations: z.ZodArray<z.ZodString>;
25
+ issues_encountered: z.ZodArray<z.ZodString>;
26
+ solutions_applied: z.ZodArray<z.ZodString>;
27
+ }, z.core.$strip>;
28
+ conversation_artifacts: z.ZodOptional<z.ZodArray<z.ZodObject<{
29
+ id: z.ZodString;
30
+ name: z.ZodString;
31
+ tool_name: z.ZodString;
32
+ tool_call_id: z.ZodString;
33
+ content_summary: z.ZodString;
34
+ relevance: z.ZodEnum<{
35
+ high: "high";
36
+ medium: "medium";
37
+ low: "low";
38
+ }>;
39
+ }, z.core.$strip>>>;
40
+ conversation_flow: z.ZodObject<{
41
+ major_phases: z.ZodArray<z.ZodString>;
42
+ decision_points: z.ZodArray<z.ZodString>;
43
+ topic_shifts: z.ZodArray<z.ZodString>;
44
+ }, z.core.$strip>;
45
+ context_for_continuation: z.ZodObject<{
46
+ current_state: z.ZodString;
47
+ next_logical_steps: z.ZodArray<z.ZodString>;
48
+ important_context: z.ZodArray<z.ZodString>;
49
+ }, z.core.$strip>;
50
+ }, z.core.$strip>;
51
+ type ConversationHistorySummary = z.infer<typeof ConversationHistorySummarySchema>;
52
+ /**
53
+ * Distill entire conversation history into a comprehensive summary that can replace the full message history
54
+ */
55
+ declare function distillConversationHistory(params: {
56
+ messages: any[];
57
+ conversationId: string;
58
+ summarizerModel: ModelSettings;
59
+ toolCallToArtifactMap?: Record<string, string>;
60
+ }): Promise<ConversationHistorySummary>;
61
+ //#endregion
62
+ export { ConversationHistorySummary, ConversationHistorySummarySchema, distillConversationHistory };
@@ -0,0 +1,206 @@
1
+ import { getLogger } from "../logger.js";
2
+ import { ModelFactory } from "@inkeep/agents-core";
3
+ import { Output, generateText } from "ai";
4
+ import { z } from "zod";
5
+
6
+ //#region src/tools/distill-conversation-history-tool.ts
7
+ const logger = getLogger("distill-conversation-history-tool");
8
+ /**
9
+ * Conversation History Summary Schema - structured object for replacing entire conversation histories
10
+ */
11
+ const ConversationHistorySummarySchema = z.object({
12
+ type: z.literal("conversation_history_summary_v1"),
13
+ session_id: z.string().nullable().optional(),
14
+ conversation_overview: z.string().describe("2-4 sentences capturing the full conversation context and what was accomplished"),
15
+ user_goals: z.object({
16
+ primary: z.string().describe("Main objective the user was trying to achieve"),
17
+ secondary: z.array(z.string()).describe("Additional goals or tasks that emerged during conversation")
18
+ }),
19
+ key_outcomes: z.object({
20
+ completed: z.array(z.string()).describe("Tasks, questions, or problems that were fully resolved"),
21
+ partial: z.array(z.string()).describe("Work that was started but not completed"),
22
+ discoveries: z.array(z.string()).describe("Important information, insights, or findings uncovered")
23
+ }),
24
+ technical_context: z.object({
25
+ technologies: z.array(z.string()).describe("Relevant technologies, frameworks, tools mentioned"),
26
+ configurations: z.array(z.string()).describe("Settings, parameters, or configurations discussed"),
27
+ issues_encountered: z.array(z.string()).describe("Problems, errors, or challenges that came up"),
28
+ solutions_applied: z.array(z.string()).describe("Fixes, workarounds, or solutions that were implemented")
29
+ }),
30
+ conversation_artifacts: z.array(z.object({
31
+ id: z.string().describe("Artifact ID"),
32
+ name: z.string().describe("Human-readable name describing the content"),
33
+ tool_name: z.string().describe("Tool that generated this artifact"),
34
+ tool_call_id: z.string().describe("Specific tool call ID for precise referencing"),
35
+ content_summary: z.string().describe("Brief summary of what this artifact contains"),
36
+ relevance: z.enum([
37
+ "high",
38
+ "medium",
39
+ "low"
40
+ ]).describe("Importance of this artifact to the overall conversation")
41
+ })).optional().describe("All artifacts referenced in this conversation with their significance"),
42
+ conversation_flow: z.object({
43
+ major_phases: z.array(z.string()).describe("Main phases or stages the conversation went through"),
44
+ decision_points: z.array(z.string()).describe("Key decisions made during the conversation"),
45
+ topic_shifts: z.array(z.string()).describe("When and why the conversation changed direction")
46
+ }),
47
+ context_for_continuation: z.object({
48
+ current_state: z.string().describe("Where things stand now - current status or position"),
49
+ next_logical_steps: z.array(z.string()).describe("What should naturally happen next based on conversation"),
50
+ important_context: z.array(z.string()).describe("Critical background info needed for future interactions")
51
+ })
52
+ });
53
+ /**
54
+ * Distill entire conversation history into a comprehensive summary that can replace the full message history
55
+ */
56
+ async function distillConversationHistory(params) {
57
+ const { messages, conversationId, summarizerModel, toolCallToArtifactMap } = params;
58
+ try {
59
+ if (!summarizerModel?.model?.trim()) throw new Error("Summarizer model is required");
60
+ const { output: summary } = await generateText({
61
+ model: ModelFactory.createModel(summarizerModel),
62
+ prompt: `You are a conversation history summarization assistant. Your job is to create a comprehensive summary that can COMPLETELY REPLACE the original conversation history while preserving all essential context.
63
+
64
+ **Complete Conversation to Summarize:**
65
+
66
+ \`\`\`text
67
+ ${messages.map((msg) => {
68
+ const parts = [];
69
+ if (typeof msg.content === "string") parts.push(msg.content);
70
+ else if (Array.isArray(msg.content)) {
71
+ for (const block of msg.content) if (block.type === "text") parts.push(block.text);
72
+ else if (block.type === "tool-call") parts.push(`[TOOL CALL] ${block.toolName}(${JSON.stringify(block.input)}) [ID: ${block.toolCallId}]`);
73
+ else if (block.type === "tool-result") {
74
+ const artifactId = toolCallToArtifactMap?.[block.toolCallId];
75
+ const artifactInfo = artifactId ? `\n[ARTIFACT CREATED: ${artifactId}]` : "";
76
+ parts.push(`[TOOL RESULT] ${block.toolName} [ID: ${block.toolCallId}]${artifactInfo}\nResult: ${JSON.stringify(block.result)}`);
77
+ }
78
+ } else if (msg.content?.text) parts.push(msg.content.text);
79
+ return parts.length > 0 ? `${msg.role || "system"}: ${parts.join("\n")}` : "";
80
+ }).filter((line) => line.trim().length > 0).join("\n\n")}
81
+ \`\`\`
82
+
83
+ Create a comprehensive summary using this exact JSON schema:
84
+
85
+ \`\`\`json
86
+ {
87
+ "type": "conversation_history_summary_v1",
88
+ "session_id": "<conversationId>",
89
+ "conversation_overview": "<2-4 sentences capturing full context and accomplishments>",
90
+ "user_goals": {
91
+ "primary": "<main objective user was trying to achieve>",
92
+ "secondary": ["<additional goals that emerged>"]
93
+ },
94
+ "key_outcomes": {
95
+ "completed": ["<tasks/questions fully resolved>"],
96
+ "partial": ["<work started but not completed>"],
97
+ "discoveries": ["<important findings uncovered>"]
98
+ },
99
+ "technical_context": {
100
+ "technologies": ["<relevant tech/frameworks/tools>"],
101
+ "configurations": ["<settings/parameters discussed>"],
102
+ "issues_encountered": ["<problems/errors that came up>"],
103
+ "solutions_applied": ["<fixes/workarounds implemented>"]
104
+ },
105
+ "conversation_artifacts": [
106
+ {
107
+ "id": "<artifact_id>",
108
+ "name": "<descriptive name>",
109
+ "tool_name": "<tool_name>",
110
+ "tool_call_id": "<tool_call_id>",
111
+ "content_summary": "<what this artifact contains>",
112
+ "relevance": "<high|medium|low>"
113
+ }
114
+ ],
115
+ "conversation_flow": {
116
+ "major_phases": ["<main stages conversation went through>"],
117
+ "decision_points": ["<key decisions made>"],
118
+ "topic_shifts": ["<when/why conversation changed direction>"]
119
+ },
120
+ "context_for_continuation": {
121
+ "current_state": "<where things stand now>",
122
+ "next_logical_steps": ["<what should happen next>"],
123
+ "important_context": ["<critical background for future interactions>"]
124
+ }
125
+ }
126
+ \`\`\`
127
+
128
+ **CRITICAL RULES - COMPREHENSIVE HISTORICAL PRESERVATION:**
129
+
130
+ 🎯 **COMPLETE CONTEXT CAPTURE**: This summary must contain ALL information needed to continue the conversation as if the full history was available
131
+
132
+ 🎯 **PRESERVE OUTCOMES**: Document everything that was accomplished, learned, discovered, or decided
133
+
134
+ 🎯 **TECHNICAL PRECISION**: Include specific technologies, configurations, error messages, solutions - technical details matter
135
+
136
+ 🎯 **ARTIFACT COMPLETENESS**: Reference ALL artifacts with clear descriptions of their contents and importance
137
+
138
+ 🎯 **CONVERSATION NARRATIVE**: Capture the logical flow - how did we get from start to current state?
139
+
140
+ 🎯 **CONTINUATION CONTEXT**: Provide everything needed for smooth conversation continuation
141
+
142
+ 🎯 **NO OPERATIONAL DETAILS**: Focus on WHAT was accomplished, not HOW (tools used, compression, etc.)
143
+
144
+ 🎯 **HANDLE TRANSFERS SIMPLY**: Agent transfers/delegations are just routing - don't look for reasons or justifications. Simply note "conversation transferred to [specialist]" if relevant to context.
145
+
146
+ **Examples of GOOD content:**
147
+ ✅ "User was implementing OAuth2 authentication in React app using Auth0, encountered CORS errors on localhost:3000, resolved by adding domain to Auth0 dashboard allowed origins"
148
+ ✅ "Discovered that the API supports both REST and GraphQL endpoints, with GraphQL providing better performance for complex queries"
149
+ ✅ "Configured webpack dev server with proxy settings to handle API calls during development"
150
+ ✅ "Conversation transferred to QA specialist to handle testing questions"
151
+
152
+ **Examples of BAD content:**
153
+ ❌ "Assistant used search tool to find information"
154
+ ❌ "Multiple tool calls were made"
155
+ ❌ "Artifacts were created for reference"
156
+ ❌ "Assistant needed to transfer because user required specialized help" (don't invent reasons for transfers)
157
+
158
+ **REMEMBER**: This summary is REPLACING the entire conversation history. Include everything essential for context continuation.
159
+
160
+ Return **only** valid JSON.`,
161
+ output: Output.object({ schema: ConversationHistorySummarySchema })
162
+ });
163
+ summary.session_id = conversationId;
164
+ return summary;
165
+ } catch (error) {
166
+ logger.error({
167
+ conversationId,
168
+ messageCount: messages.length,
169
+ error: error instanceof Error ? error.message : "Unknown error"
170
+ }, "Failed to distill conversation history");
171
+ return {
172
+ type: "conversation_history_summary_v1",
173
+ session_id: conversationId,
174
+ conversation_overview: "Conversation session with technical discussion and problem-solving",
175
+ user_goals: {
176
+ primary: "Technical assistance and problem-solving",
177
+ secondary: []
178
+ },
179
+ key_outcomes: {
180
+ completed: [],
181
+ partial: ["Ongoing technical work"],
182
+ discoveries: []
183
+ },
184
+ technical_context: {
185
+ technologies: [],
186
+ configurations: [],
187
+ issues_encountered: [],
188
+ solutions_applied: []
189
+ },
190
+ conversation_artifacts: [],
191
+ conversation_flow: {
192
+ major_phases: ["Initial discussion", "Technical exploration"],
193
+ decision_points: [],
194
+ topic_shifts: []
195
+ },
196
+ context_for_continuation: {
197
+ current_state: "In progress - technical work ongoing",
198
+ next_logical_steps: ["Continue with current technical objectives"],
199
+ important_context: ["Review previous discussion for technical context"]
200
+ }
201
+ };
202
+ }
203
+ }
204
+
205
+ //#endregion
206
+ export { ConversationHistorySummarySchema, distillConversationHistory };
@@ -0,0 +1,41 @@
1
+ import { ModelSettings } from "@inkeep/agents-core";
2
+ import { z } from "zod";
3
+
4
+ //#region src/tools/distill-conversation-tool.d.ts
5
+
6
+ /**
7
+ * Conversation Summary Schema - structured object for maintaining conversation context
8
+ */
9
+ declare const ConversationSummarySchema: z.ZodObject<{
10
+ type: z.ZodLiteral<"conversation_summary_v1">;
11
+ session_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
+ high_level: z.ZodString;
13
+ user_intent: z.ZodString;
14
+ decisions: z.ZodArray<z.ZodString>;
15
+ open_questions: z.ZodArray<z.ZodString>;
16
+ next_steps: z.ZodObject<{
17
+ for_agent: z.ZodArray<z.ZodString>;
18
+ for_user: z.ZodArray<z.ZodString>;
19
+ }, z.core.$strip>;
20
+ related_artifacts: z.ZodOptional<z.ZodArray<z.ZodObject<{
21
+ id: z.ZodString;
22
+ name: z.ZodString;
23
+ tool_name: z.ZodString;
24
+ tool_call_id: z.ZodString;
25
+ content_type: z.ZodString;
26
+ key_findings: z.ZodArray<z.ZodString>;
27
+ }, z.core.$strip>>>;
28
+ }, z.core.$strip>;
29
+ type ConversationSummary = z.infer<typeof ConversationSummarySchema>;
30
+ /**
31
+ * Core conversation distillation - takes messages and creates structured summary
32
+ */
33
+ declare function distillConversation(params: {
34
+ messages: any[];
35
+ conversationId: string;
36
+ currentSummary?: ConversationSummary | null;
37
+ summarizerModel?: ModelSettings;
38
+ toolCallToArtifactMap?: Record<string, string>;
39
+ }): Promise<ConversationSummary>;
40
+ //#endregion
41
+ export { ConversationSummary, ConversationSummarySchema, distillConversation };