@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,141 @@
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-tool.ts
7
+ const logger = getLogger("distill-conversation-tool");
8
+ /**
9
+ * Conversation Summary Schema - structured object for maintaining conversation context
10
+ */
11
+ const ConversationSummarySchema = z.object({
12
+ type: z.literal("conversation_summary_v1"),
13
+ session_id: z.string().nullable().optional(),
14
+ high_level: z.string().describe("1-3 sentences capturing what was discovered and learned"),
15
+ user_intent: z.string().describe("Current main goal or what the user wants to accomplish"),
16
+ decisions: z.array(z.string()).describe("Concrete decisions made about approach or implementation (≤5 items)"),
17
+ open_questions: z.array(z.string()).describe("Unresolved questions about the subject matter (≤5 items)"),
18
+ next_steps: z.object({
19
+ for_agent: z.array(z.string()).describe("Content-focused actions: what to discover, analyze, or present. Don't get trapped in an infinite loop of tool calls. You have already done a lot of work that is why you are being compressed. Don't encourage too much more work."),
20
+ for_user: z.array(z.string()).describe("Actions for user based on discovered content")
21
+ }),
22
+ related_artifacts: z.array(z.object({
23
+ id: z.string().describe("Artifact ID"),
24
+ name: z.string().describe("Human-readable name describing the content"),
25
+ tool_name: z.string().describe("Tool that generated this artifact (e.g. search-inkeep-docs)"),
26
+ tool_call_id: z.string().describe("Specific tool call ID for precise referencing"),
27
+ content_type: z.string().describe("Type of content (e.g. search_results, api_response, documentation)"),
28
+ key_findings: z.array(z.string()).describe("2-3 most important findings from this specific artifact")
29
+ })).optional().describe("Artifacts containing detailed findings with citation info")
30
+ });
31
+ /**
32
+ * Core conversation distillation - takes messages and creates structured summary
33
+ */
34
+ async function distillConversation(params) {
35
+ const { messages, conversationId, currentSummary, summarizerModel, toolCallToArtifactMap } = params;
36
+ try {
37
+ const modelToUse = summarizerModel;
38
+ if (!modelToUse?.model?.trim()) throw new Error("Summarizer model is required");
39
+ const { output: summary } = await generateText({
40
+ model: ModelFactory.createModel(modelToUse),
41
+ prompt: `You are a conversation summarization assistant. Your job is to create or update a compact, structured summary that captures VALUABLE CONTENT and FINDINGS, not just operational details.
42
+
43
+ ${currentSummary ? `**Current summary:**\n\n\`\`\`json\n${JSON.stringify(currentSummary, null, 2)}\n\`\`\`` : "**Current summary:** None (first distillation)"}
44
+
45
+ **Messages to summarize:**
46
+
47
+ \`\`\`text
48
+ ${messages.map((msg) => {
49
+ const parts = [];
50
+ if (typeof msg.content === "string") parts.push(msg.content);
51
+ else if (Array.isArray(msg.content)) {
52
+ for (const block of msg.content) if (block.type === "text") parts.push(block.text);
53
+ else if (block.type === "tool-call") parts.push(`[TOOL CALL] ${block.toolName}(${JSON.stringify(block.input)}) [ID: ${block.toolCallId}]`);
54
+ else if (block.type === "tool-result") {
55
+ const artifactId = toolCallToArtifactMap?.[block.toolCallId];
56
+ const artifactInfo = artifactId ? `\n[ARTIFACT CREATED: ${artifactId}]` : "";
57
+ parts.push(`[TOOL RESULT] ${block.toolName} [ID: ${block.toolCallId}]${artifactInfo}\nResult: ${JSON.stringify(block.output)}`);
58
+ }
59
+ } else if (msg.content?.text) parts.push(msg.content.text);
60
+ return parts.length > 0 ? `${msg.role || "system"}: ${parts.join("\n")}` : "";
61
+ }).filter((line) => line.trim().length > 0).join("\n\n")}
62
+ \`\`\`
63
+
64
+ Create/update a summary using this exact JSON schema:
65
+
66
+ \`\`\`json
67
+ {
68
+ "type": "conversation_summary_v1",
69
+ "session_id": "<conversationId>",
70
+ "high_level": "<1–3 sentences capturing what was discovered and learned>",
71
+ "user_intent": "<current main goal>",
72
+ "decisions": ["<concrete decisions made>"],
73
+ "open_questions": ["<unresolved issues>"],
74
+ "next_steps": {
75
+ "for_agent": ["<what agent should do>"],
76
+ "for_user": ["<what user should do>"]
77
+ },
78
+ "related_artifacts": [
79
+ {
80
+ "id": "<artifact_id>",
81
+ "name": "<descriptive name>",
82
+ "tool_name": "<tool_name>",
83
+ "tool_call_id": "<tool_call_id>",
84
+ "content_type": "<search_results|api_response|documentation>",
85
+ "key_findings": ["<important finding 1>", "<important finding 2>"]
86
+ }
87
+ ]
88
+ }
89
+ \`\`\`
90
+
91
+ **CRITICAL RULES - FOCUS ON CONTENT NOT OPERATIONS:**
92
+ 🎯 **EXTRACT VALUABLE FINDINGS**: Capture the actual information discovered, data retrieved, insights gained
93
+ 🎯 **IGNORE OPERATIONAL DETAILS**: Don't mention "tool was used", "artifact was created", "messages were compressed"
94
+ 🎯 **PRESERVE SUBSTANCE**: Include specific facts, features, capabilities, configurations, results found
95
+ 🎯 **BUILD KNOWLEDGE**: When updating existing summary, ADD new discoveries to existing knowledge
96
+ 🎯 **BE CONCRETE**: Use specific details from tool results, not generic descriptions
97
+ 🎯 **BE CONCISE**: Keep ALL fields brief - you are compressing to save context, not writing a report
98
+ 🎯 **LIMIT NEXT STEPS**: Agent has already done substantial work - suggest minimal follow-up actions only
99
+ 🎯 **HANDLE TRANSFERS SIMPLY**: Agent transfers/delegations are just routing - don't look for reasons or justifications. Simply note "conversation transferred to [specialist]" if relevant.
100
+
101
+ **Examples:**
102
+ ❌ BAD: "Assistant used search tool and created artifacts"
103
+ ✅ GOOD: "Inkeep supports streaming structured objects, OpenAI-compatible APIs, analytics logging, and Zendesk integration"
104
+
105
+ ❌ BAD: "Tool calls were made to gather information"
106
+ ✅ GOOD: "Platform includes 10 feature categories: chat widgets, knowledge base, analytics, integrations, theming options"
107
+
108
+ ❌ BAD: "Assistant needed to transfer to QA because user required specialized testing help"
109
+ ✅ GOOD: "Conversation transferred to QA specialist"
110
+
111
+ **Focus on WHAT WAS LEARNED, not HOW IT WAS LEARNED**
112
+
113
+ Return **only** valid JSON.`,
114
+ output: Output.object({ schema: ConversationSummarySchema })
115
+ });
116
+ summary.session_id = conversationId;
117
+ return summary;
118
+ } catch (error) {
119
+ logger.error({
120
+ conversationId,
121
+ messageCount: messages.length,
122
+ error: error instanceof Error ? error.message : "Unknown error"
123
+ }, "Failed to distill conversation");
124
+ return {
125
+ type: "conversation_summary_v1",
126
+ session_id: conversationId,
127
+ high_level: "Ongoing conversation session",
128
+ user_intent: "Continue working on current task",
129
+ related_artifacts: [],
130
+ decisions: [],
131
+ open_questions: ["Review recent work and determine next steps"],
132
+ next_steps: {
133
+ for_agent: ["Continue with current task"],
134
+ for_user: ["Provide additional guidance if needed"]
135
+ }
136
+ };
137
+ }
138
+ }
139
+
140
+ //#endregion
141
+ export { ConversationSummarySchema, distillConversation };
@@ -0,0 +1,18 @@
1
+ //#region src/tools/sandbox-utils.d.ts
2
+ /**
3
+ * Shared utilities for sandbox executors
4
+ */
5
+ /**
6
+ * Create an execution wrapper that handles input/output for function tools
7
+ * This is used by both Native and Vercel sandbox executors
8
+ */
9
+ declare function createExecutionWrapper(executeCode: string, args: Record<string, unknown>): string;
10
+ /**
11
+ * Parse execution result from stdout
12
+ * Returns the parsed result or the raw stdout if parsing fails
13
+ */
14
+ declare function parseExecutionResult(stdout: string, functionId: string, logger?: {
15
+ warn: (obj: unknown, msg: string) => void;
16
+ }): unknown;
17
+ //#endregion
18
+ export { createExecutionWrapper, parseExecutionResult };
@@ -0,0 +1,53 @@
1
+ //#region src/tools/sandbox-utils.ts
2
+ /**
3
+ * Shared utilities for sandbox executors
4
+ */
5
+ /**
6
+ * Create an execution wrapper that handles input/output for function tools
7
+ * This is used by both Native and Vercel sandbox executors
8
+ */
9
+ function createExecutionWrapper(executeCode, args) {
10
+ return `
11
+ // Function tool execution wrapper
12
+ const args = ${JSON.stringify(args, null, 2)};
13
+
14
+ // User's function code
15
+ const execute = ${executeCode}
16
+
17
+ // Execute the function and output the result
18
+ (async () => {
19
+ try {
20
+ const result = await execute(args);
21
+ // Output result as JSON on the last line
22
+ console.log(JSON.stringify({ success: true, result }));
23
+ } catch (error) {
24
+ console.error(JSON.stringify({
25
+ success: false,
26
+ error: error instanceof Error ? error.message : String(error)
27
+ }));
28
+ process.exit(1);
29
+ }
30
+ })();
31
+ `;
32
+ }
33
+ /**
34
+ * Parse execution result from stdout
35
+ * Returns the parsed result or the raw stdout if parsing fails
36
+ */
37
+ function parseExecutionResult(stdout, functionId, logger) {
38
+ try {
39
+ const outputLines = stdout.split("\n").filter((line) => line.trim());
40
+ const resultLine = outputLines[outputLines.length - 1];
41
+ return JSON.parse(resultLine);
42
+ } catch (parseError) {
43
+ if (logger) logger.warn({
44
+ functionId,
45
+ stdout,
46
+ parseError
47
+ }, "Failed to parse execution result");
48
+ return stdout;
49
+ }
50
+ }
51
+
52
+ //#endregion
53
+ export { createExecutionWrapper, parseExecutionResult };
@@ -0,0 +1,27 @@
1
+ //#region src/types/chat.d.ts
2
+ type ContentItem = {
3
+ type: string;
4
+ text?: string;
5
+ };
6
+ type Message = {
7
+ role: 'system' | 'user' | 'assistant' | 'function' | 'tool';
8
+ content: string | ContentItem[];
9
+ name?: string;
10
+ };
11
+ type ChatCompletionRequest = {
12
+ model: string;
13
+ messages: Message[];
14
+ temperature?: number;
15
+ top_p?: number;
16
+ n?: number;
17
+ stream?: boolean;
18
+ max_tokens?: number;
19
+ presence_penalty?: number;
20
+ frequency_penalty?: number;
21
+ logit_bias?: Record<string, number>;
22
+ user?: string;
23
+ tools?: Record<string, unknown>;
24
+ runConfig?: Record<string, unknown>;
25
+ };
26
+ //#endregion
27
+ export { ChatCompletionRequest, ContentItem, Message };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,46 @@
1
+ import { ExecutionContext } from "@inkeep/agents-core";
2
+
3
+ //#region src/types/execution-context.d.ts
4
+
5
+ /**
6
+ * Extract userId from execution context metadata (when available)
7
+ * Only available when request originates from an authenticated user session (e.g., playground)
8
+ */
9
+ declare function getUserIdFromContext(ctx: ExecutionContext): string | undefined;
10
+ /**
11
+ * Create execution context from middleware values
12
+ */
13
+ declare function createExecutionContext(params: {
14
+ apiKey: string;
15
+ tenantId: string;
16
+ projectId: string;
17
+ agentId: string;
18
+ apiKeyId: string;
19
+ subAgentId?: string;
20
+ baseUrl?: string;
21
+ metadata?: {
22
+ teamDelegation?: boolean;
23
+ originAgentId?: string;
24
+ initiatedBy?: {
25
+ type: 'user' | 'api_key';
26
+ id: string;
27
+ };
28
+ };
29
+ }): ExecutionContext;
30
+ interface CommonSandboxConfig {
31
+ runtime: 'node22' | 'typescript';
32
+ timeout?: number;
33
+ vcpus?: number;
34
+ }
35
+ interface NativeSandboxConfig extends CommonSandboxConfig {
36
+ provider: 'native';
37
+ }
38
+ interface VercelSandboxConfig extends CommonSandboxConfig {
39
+ provider: 'vercel';
40
+ teamId: string;
41
+ projectId: string;
42
+ token: string;
43
+ }
44
+ type SandboxConfig = NativeSandboxConfig | VercelSandboxConfig;
45
+ //#endregion
46
+ export { NativeSandboxConfig, SandboxConfig, VercelSandboxConfig, createExecutionContext, getUserIdFromContext };
@@ -0,0 +1,27 @@
1
+ //#region src/types/execution-context.ts
2
+ /**
3
+ * Extract userId from execution context metadata (when available)
4
+ * Only available when request originates from an authenticated user session (e.g., playground)
5
+ */
6
+ function getUserIdFromContext(ctx) {
7
+ const metadata = ctx.metadata;
8
+ return metadata?.initiatedBy?.type === "user" ? metadata.initiatedBy.id : void 0;
9
+ }
10
+ /**
11
+ * Create execution context from middleware values
12
+ */
13
+ function createExecutionContext(params) {
14
+ return {
15
+ apiKey: params.apiKey,
16
+ tenantId: params.tenantId,
17
+ projectId: params.projectId,
18
+ agentId: params.agentId,
19
+ baseUrl: params.baseUrl || process.env.API_URL || "http://localhost:3003",
20
+ apiKeyId: params.apiKeyId,
21
+ subAgentId: params.subAgentId,
22
+ metadata: params.metadata || {}
23
+ };
24
+ }
25
+
26
+ //#endregion
27
+ export { createExecutionContext, getUserIdFromContext };
@@ -0,0 +1,5 @@
1
+ //#region src/types/xml.d.ts
2
+ declare module '*.xml?raw' {
3
+ const content: string;
4
+ export default content;
5
+ }
@@ -0,0 +1,52 @@
1
+ //#region src/utils/SchemaProcessor.d.ts
2
+ interface SchemaValidationResult {
3
+ isValid: boolean;
4
+ errors: string[];
5
+ transformedSchema?: any;
6
+ }
7
+ interface JMESPathValidationResult {
8
+ isLiteral: boolean;
9
+ isValidSelector: boolean;
10
+ suggestions?: string[];
11
+ }
12
+ /**
13
+ * Centralized schema processing and validation utilities
14
+ */
15
+ declare class SchemaProcessor {
16
+ private static logger;
17
+ /**
18
+ * Transform complex schema types to strings for JMESPath compatibility
19
+ */
20
+ static transformSchemaForJMESPath(schema: any): any;
21
+ /**
22
+ * Validate if a selector looks like a valid JMESPath expression
23
+ */
24
+ static validateJMESPathSelector(selector: string): JMESPathValidationResult;
25
+ /**
26
+ * Check if a selector looks like a JMESPath expression
27
+ */
28
+ private static looksLikeJMESPath;
29
+ /**
30
+ * Check if a selector appears to be a literal value rather than a JMESPath expression
31
+ */
32
+ private static isLiteralValue;
33
+ /**
34
+ * Safely extract data using JMESPath with validation
35
+ */
36
+ static safeJMESPathSearch(data: any, selector: string, fallback?: any): any;
37
+ /**
38
+ * Validate schema structure for artifact components
39
+ */
40
+ static validateArtifactSchema(schema: any): SchemaValidationResult;
41
+ /**
42
+ * Extract property value with proper type conversion and validation
43
+ */
44
+ static extractPropertyValue(data: any, _propName: string, selector: string, expectedType?: string): any;
45
+ /**
46
+ * Enhance schema with JMESPath guidance for artifact component schemas
47
+ * Transforms all schema types to string selectors with helpful descriptions
48
+ */
49
+ static enhanceSchemaWithJMESPathGuidance(schema: Record<string, unknown> | null | undefined): Record<string, unknown>;
50
+ }
51
+ //#endregion
52
+ export { JMESPathValidationResult, SchemaProcessor, SchemaValidationResult };
@@ -0,0 +1,182 @@
1
+ import { getLogger } from "../logger.js";
2
+ import jmespath from "jmespath";
3
+
4
+ //#region src/utils/SchemaProcessor.ts
5
+ /**
6
+ * Centralized schema processing and validation utilities
7
+ */
8
+ var SchemaProcessor = class SchemaProcessor {
9
+ static logger = getLogger("SchemaProcessor");
10
+ /**
11
+ * Transform complex schema types to strings for JMESPath compatibility
12
+ */
13
+ static transformSchemaForJMESPath(schema) {
14
+ if (!schema || typeof schema !== "object") return schema;
15
+ const transform = (obj) => {
16
+ if (Array.isArray(obj)) return obj.map(transform);
17
+ if (obj && typeof obj === "object") {
18
+ const result = {};
19
+ for (const [key, value] of Object.entries(obj)) if (key === "type" && typeof value === "string") result[key] = value === "string" ? "string" : "string";
20
+ else result[key] = transform(value);
21
+ return result;
22
+ }
23
+ return obj;
24
+ };
25
+ return transform(schema);
26
+ }
27
+ /**
28
+ * Validate if a selector looks like a valid JMESPath expression
29
+ */
30
+ static validateJMESPathSelector(selector) {
31
+ if (SchemaProcessor.isLiteralValue(selector)) return {
32
+ isLiteral: true,
33
+ isValidSelector: false
34
+ };
35
+ if (SchemaProcessor.looksLikeJMESPath(selector)) return {
36
+ isLiteral: false,
37
+ isValidSelector: true
38
+ };
39
+ return {
40
+ isLiteral: false,
41
+ isValidSelector: false
42
+ };
43
+ }
44
+ /**
45
+ * Check if a selector looks like a JMESPath expression
46
+ */
47
+ static looksLikeJMESPath(selector) {
48
+ if (/^[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*$/.test(selector)) return true;
49
+ if (/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)+$/.test(selector)) return true;
50
+ if (/\[\d+\]/.test(selector) || /\[\*\]/.test(selector)) return true;
51
+ if (/\[.*?\]/.test(selector) && /[=<>!]/.test(selector)) return true;
52
+ if (selector.includes("|")) return true;
53
+ return false;
54
+ }
55
+ /**
56
+ * Check if a selector appears to be a literal value rather than a JMESPath expression
57
+ */
58
+ static isLiteralValue(selector) {
59
+ if (SchemaProcessor.looksLikeJMESPath(selector)) return false;
60
+ if (/^https?:\/\//.test(selector)) return true;
61
+ if (/^[0-9]+$/.test(selector)) return true;
62
+ if (selector.includes(" ") && !selector.includes("[")) return true;
63
+ if (/^[a-zA-Z0-9\s\-_,;:!?.'"+()]+$/.test(selector) && selector.length > 20) return true;
64
+ return false;
65
+ }
66
+ /**
67
+ * Safely extract data using JMESPath with validation
68
+ */
69
+ static safeJMESPathSearch(data, selector, fallback = null) {
70
+ try {
71
+ const validation = SchemaProcessor.validateJMESPathSelector(selector);
72
+ if (validation.isLiteral) {
73
+ SchemaProcessor.logger.debug({ selector }, "Selector appears to be literal value, returning as-is");
74
+ return selector;
75
+ }
76
+ if (!validation.isValidSelector) {
77
+ SchemaProcessor.logger.warn({ selector }, "Selector does not appear to be valid JMESPath");
78
+ return fallback;
79
+ }
80
+ return jmespath.search(data, selector) || fallback;
81
+ } catch (error) {
82
+ SchemaProcessor.logger.warn({
83
+ selector,
84
+ error: error instanceof Error ? error.message : String(error)
85
+ }, "JMESPath search failed");
86
+ return fallback;
87
+ }
88
+ }
89
+ /**
90
+ * Validate schema structure for artifact components
91
+ */
92
+ static validateArtifactSchema(schema) {
93
+ const errors = [];
94
+ if (!schema || typeof schema !== "object") {
95
+ errors.push("Schema must be an object");
96
+ return {
97
+ isValid: false,
98
+ errors
99
+ };
100
+ }
101
+ if (!schema.type || schema.type !== "object") errors.push("Schema must have type \"object\"");
102
+ if (!schema.properties || typeof schema.properties !== "object") errors.push("Schema must have properties object");
103
+ const transformedSchema = SchemaProcessor.transformSchemaForJMESPath(schema);
104
+ return {
105
+ isValid: errors.length === 0,
106
+ errors,
107
+ transformedSchema
108
+ };
109
+ }
110
+ /**
111
+ * Extract property value with proper type conversion and validation
112
+ */
113
+ static extractPropertyValue(data, _propName, selector, expectedType) {
114
+ const value = SchemaProcessor.safeJMESPathSearch(data, selector);
115
+ if (value === null || value === void 0) return null;
116
+ if (expectedType) switch (expectedType) {
117
+ case "string": return String(value);
118
+ case "number": {
119
+ const num = Number(value);
120
+ return Number.isNaN(num) ? null : num;
121
+ }
122
+ case "boolean": return Boolean(value);
123
+ case "array": return Array.isArray(value) ? value : [value];
124
+ default: return value;
125
+ }
126
+ return value;
127
+ }
128
+ /**
129
+ * Enhance schema with JMESPath guidance for artifact component schemas
130
+ * Transforms all schema types to string selectors with helpful descriptions
131
+ */
132
+ static enhanceSchemaWithJMESPathGuidance(schema) {
133
+ if (!schema || typeof schema !== "object") return schema || {};
134
+ const transformToSelectorSchema = (obj, path = "") => {
135
+ if (!obj || typeof obj !== "object") return obj;
136
+ if (obj.type === "array") {
137
+ obj.items?.description;
138
+ const arrayDescription = obj.description || "array data";
139
+ path.includes("content");
140
+ return {
141
+ type: "string",
142
+ description: `🎯 ARRAY SELECTOR: Provide JMESPath selector for ${arrayDescription}. RELATIVE to base selector - this will be applied to the item selected by base_selector. Example: "content.blocks" or "items" (NOT absolute paths like "result.content.blocks")`
143
+ };
144
+ }
145
+ if (obj.type === "object" && !obj.properties) return {
146
+ type: "string",
147
+ description: `🎯 OBJECT SELECTOR: Provide JMESPath selector for ${obj.description || "object data"}. RELATIVE to base selector - this will be applied to the item selected by base_selector. Example: "metadata" or "spec.details" (NOT absolute paths)`
148
+ };
149
+ if (obj.type === "object" && obj.properties) {
150
+ const transformedProperties = {};
151
+ Object.entries(obj.properties).forEach(([propertyName, property]) => {
152
+ transformedProperties[propertyName] = transformToSelectorSchema(property, path ? `${path}.${propertyName}` : propertyName);
153
+ });
154
+ return {
155
+ type: "object",
156
+ properties: transformedProperties,
157
+ required: obj.required || [],
158
+ description: `${obj.description || "Object containing JMESPath selectors"} - Each property should be a selector RELATIVE to the base_selector`
159
+ };
160
+ }
161
+ if ([
162
+ "string",
163
+ "number",
164
+ "boolean"
165
+ ].includes(obj.type)) {
166
+ const originalDescription = obj.description || `${obj.type} value`;
167
+ return {
168
+ type: "string",
169
+ description: `🎯 FIELD SELECTOR: Provide JMESPath selector for ${originalDescription}. RELATIVE to base selector (e.g., "title", "metadata.category", "properties.value"). For nested data: use field paths like "content.details", "attributes.data", "specifications.info". NOT absolute paths and NOT literal values like "${originalDescription}". The base_selector finds the item, this selector extracts the field FROM that item.`
170
+ };
171
+ }
172
+ return {
173
+ type: "string",
174
+ description: `🎯 SELECTOR: Provide JMESPath selector RELATIVE to base selector. Example: "fieldName" or "nested.path" (NOT absolute paths)`
175
+ };
176
+ };
177
+ return transformToSelectorSchema(schema);
178
+ }
179
+ };
180
+
181
+ //#endregion
182
+ export { SchemaProcessor };
@@ -0,0 +1,62 @@
1
+ import { DataOperationEvent } from "@inkeep/agents-core";
2
+
3
+ //#region src/utils/agent-operations.d.ts
4
+
5
+ /**
6
+ * Agent initialization operation event
7
+ */
8
+ interface AgentInitializingEvent {
9
+ type: 'agent_initializing';
10
+ details: {
11
+ sessionId: string;
12
+ agentId: string;
13
+ };
14
+ }
15
+ /**
16
+ * Completion operation event
17
+ */
18
+ interface CompletionEvent {
19
+ type: 'completion';
20
+ details: {
21
+ agent: string;
22
+ iteration: number;
23
+ };
24
+ }
25
+ /**
26
+ * Unified error event structure
27
+ * Can be used for both operational errors (with agent context) and general stream errors
28
+ */
29
+ interface ErrorEvent {
30
+ type: 'error';
31
+ message: string;
32
+ agent?: string;
33
+ severity?: 'error' | 'warning' | 'info';
34
+ code?: string;
35
+ timestamp?: number;
36
+ }
37
+ /**
38
+ * Discriminated union of all operation events
39
+ */
40
+ type OperationEvent = AgentInitializingEvent | CompletionEvent | ErrorEvent | DataOperationEvent;
41
+ /**
42
+ * Creates an agent initializing operation
43
+ */
44
+ declare function agentInitializingOp(sessionId: string, agentId: string): AgentInitializingEvent;
45
+ /**
46
+ * Creates a completion operation
47
+ */
48
+ declare function completionOp(subAgentId: string, iterations: number): CompletionEvent;
49
+ /**
50
+ * Creates a unified error event
51
+ * @param message - Error message
52
+ * @param subAgentId - Optional agent ID for context
53
+ * @param severity - Error severity level
54
+ * @param code - Optional error code
55
+ */
56
+ declare function errorOp(message: string, subAgentId?: string, severity?: 'error' | 'warning' | 'info', code?: string): ErrorEvent;
57
+ /**
58
+ * Generate a unique tool execution ID for lifecycle tracking
59
+ */
60
+ declare function generateToolId(): string;
61
+ //#endregion
62
+ export { AgentInitializingEvent, CompletionEvent, ErrorEvent, OperationEvent, agentInitializingOp, completionOp, errorOp, generateToolId };
@@ -0,0 +1,53 @@
1
+ import { generateId } from "@inkeep/agents-core";
2
+
3
+ //#region src/utils/agent-operations.ts
4
+ /**
5
+ * Creates an agent initializing operation
6
+ */
7
+ function agentInitializingOp(sessionId, agentId) {
8
+ return {
9
+ type: "agent_initializing",
10
+ details: {
11
+ sessionId,
12
+ agentId
13
+ }
14
+ };
15
+ }
16
+ /**
17
+ * Creates a completion operation
18
+ */
19
+ function completionOp(subAgentId, iterations) {
20
+ return {
21
+ type: "completion",
22
+ details: {
23
+ agent: subAgentId,
24
+ iteration: iterations
25
+ }
26
+ };
27
+ }
28
+ /**
29
+ * Creates a unified error event
30
+ * @param message - Error message
31
+ * @param subAgentId - Optional agent ID for context
32
+ * @param severity - Error severity level
33
+ * @param code - Optional error code
34
+ */
35
+ function errorOp(message, subAgentId, severity = "error", code) {
36
+ return {
37
+ type: "error",
38
+ message,
39
+ agent: subAgentId,
40
+ severity,
41
+ code,
42
+ timestamp: Date.now()
43
+ };
44
+ }
45
+ /**
46
+ * Generate a unique tool execution ID for lifecycle tracking
47
+ */
48
+ function generateToolId() {
49
+ return `tool_${generateId(8)}`;
50
+ }
51
+
52
+ //#endregion
53
+ export { agentInitializingOp, completionOp, errorOp, generateToolId };