@inkeep/agents-run-api 0.39.5 → 0.40.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 +560 -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 +266 -0
  18. package/dist/agents/Agent.js +1927 -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 +521 -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 +39 -0
  52. package/dist/handlers/executionHandler.js +456 -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 +293 -0
  69. package/dist/routes/chatDataStream.d.ts +13 -0
  70. package/dist/routes/chatDataStream.js +352 -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 +504 -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} +1 -2
  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 +4 -20
  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,104 @@
1
+ import { getLogger } from "../logger.js";
2
+ import { BaseCompressor, getModelAwareCompressionConfig } from "./BaseCompressor.js";
3
+
4
+ //#region src/services/MidGenerationCompressor.ts
5
+ const logger = getLogger("MidGenerationCompressor");
6
+ /**
7
+ * Mid-generation compressor
8
+ * Compresses context when generate() steps get too large with manual compression support
9
+ */
10
+ var MidGenerationCompressor = class extends BaseCompressor {
11
+ shouldCompress = false;
12
+ lastProcessedMessageIndex = 0;
13
+ constructor(sessionId, conversationId, tenantId, projectId, config, summarizerModel, baseModel) {
14
+ const compressionConfig = config || getModelAwareCompressionConfig(summarizerModel);
15
+ super(sessionId, conversationId, tenantId, projectId, compressionConfig, summarizerModel, baseModel);
16
+ }
17
+ /**
18
+ * Get compression type for this compressor
19
+ */
20
+ getCompressionType() {
21
+ return "mid_generation";
22
+ }
23
+ /**
24
+ * Manual compression request from LLM tool
25
+ */
26
+ requestManualCompression(reason) {
27
+ this.shouldCompress = true;
28
+ logger.info({
29
+ sessionId: this.sessionId,
30
+ reason: reason || "Manual request from LLM"
31
+ }, "Manual compression requested");
32
+ }
33
+ /**
34
+ * Check if compression is needed (either automatic or manual)
35
+ * Supports manual compression requests unique to mid-generation
36
+ */
37
+ isCompressionNeeded(messages) {
38
+ if (this.shouldCompress) return true;
39
+ const contextSize = this.calculateContextSize(messages);
40
+ const remaining = this.config.hardLimit - contextSize;
41
+ const needsCompression = remaining <= this.config.safetyBuffer;
42
+ logger.debug({
43
+ sessionId: this.sessionId,
44
+ contextSize,
45
+ hardLimit: this.config.hardLimit,
46
+ safetyBuffer: this.config.safetyBuffer,
47
+ remaining,
48
+ needsCompression,
49
+ manualRequest: this.shouldCompress
50
+ }, "Checking mid-generation compression criteria");
51
+ return needsCompression;
52
+ }
53
+ /**
54
+ * Perform mid-generation compression with incremental processing
55
+ * Uses base class functionality with mid-generation specific logic
56
+ */
57
+ async compress(messages) {
58
+ const contextSizeBefore = this.calculateContextSize(messages);
59
+ logger.info({
60
+ sessionId: this.sessionId,
61
+ messageCount: messages.length,
62
+ contextSize: contextSizeBefore
63
+ }, "MID-GENERATION COMPRESSION: Starting compression");
64
+ const toolCallToArtifactMap = await this.saveToolResultsAsArtifacts(messages, this.lastProcessedMessageIndex);
65
+ const summary = await this.createConversationSummary(messages, toolCallToArtifactMap);
66
+ const contextSizeAfter = this.estimateTokens(JSON.stringify(summary));
67
+ this.recordCompressionEvent({
68
+ reason: this.shouldCompress ? "manual" : "automatic",
69
+ messageCount: messages.length,
70
+ artifactCount: Object.keys(toolCallToArtifactMap).length,
71
+ contextSizeBefore,
72
+ contextSizeAfter,
73
+ compressionType: this.getCompressionType()
74
+ });
75
+ this.shouldCompress = false;
76
+ this.lastProcessedMessageIndex = messages.length;
77
+ logger.info({
78
+ sessionId: this.sessionId,
79
+ artifactsCreated: Object.keys(toolCallToArtifactMap).length,
80
+ messageCount: messages.length,
81
+ contextSizeBefore,
82
+ contextSizeAfter,
83
+ compressionRatio: contextSizeAfter / contextSizeBefore,
84
+ artifactIds: Object.values(toolCallToArtifactMap)
85
+ }, "MID-GENERATION COMPRESSION: Compression completed successfully");
86
+ return {
87
+ artifactIds: Object.values(toolCallToArtifactMap),
88
+ summary
89
+ };
90
+ }
91
+ /**
92
+ * Get current state for debugging
93
+ */
94
+ getState() {
95
+ return {
96
+ ...super.getState(),
97
+ shouldCompress: this.shouldCompress,
98
+ lastProcessedMessageIndex: this.lastProcessedMessageIndex
99
+ };
100
+ }
101
+ };
102
+
103
+ //#endregion
104
+ export { MidGenerationCompressor };
@@ -0,0 +1,62 @@
1
+ //#region src/services/PendingToolApprovalManager.d.ts
2
+ interface PendingToolApproval {
3
+ toolCallId: string;
4
+ toolName: string;
5
+ args: any;
6
+ conversationId: string;
7
+ subAgentId: string;
8
+ createdAt: number;
9
+ resolve: (result: {
10
+ approved: boolean;
11
+ reason?: string;
12
+ }) => void;
13
+ reject: (error: Error) => void;
14
+ timeoutId: ReturnType<typeof setTimeout>;
15
+ }
16
+ /**
17
+ * Manages pending tool approval requests during agent execution.
18
+ * Similar to ToolSessionManager but for approval workflows.
19
+ * Uses in-memory Map storage with automatic cleanup like OAuth PKCE store.
20
+ */
21
+ declare class PendingToolApprovalManager {
22
+ private static instance;
23
+ private pendingApprovals;
24
+ private constructor();
25
+ static getInstance(): PendingToolApprovalManager;
26
+ /**
27
+ * Create a new pending approval and return a promise that resolves with approval status
28
+ */
29
+ waitForApproval(toolCallId: string, toolName: string, args: any, conversationId: string, subAgentId: string): Promise<{
30
+ approved: boolean;
31
+ reason?: string;
32
+ }>;
33
+ /**
34
+ * Approve a pending tool call
35
+ */
36
+ approveToolCall(toolCallId: string): boolean;
37
+ /**
38
+ * Deny a pending tool call
39
+ */
40
+ denyToolCall(toolCallId: string, reason?: string): boolean;
41
+ /**
42
+ * Clean up expired approvals (called by interval timer)
43
+ */
44
+ private cleanupExpiredApprovals;
45
+ /**
46
+ * Get current status for monitoring
47
+ */
48
+ getStatus(): {
49
+ pendingApprovals: number;
50
+ approvals: {
51
+ toolCallId: string;
52
+ toolName: string;
53
+ conversationId: string;
54
+ subAgentId: string;
55
+ createdAt: number;
56
+ age: number;
57
+ }[];
58
+ };
59
+ }
60
+ declare const pendingToolApprovalManager: PendingToolApprovalManager;
61
+ //#endregion
62
+ export { PendingToolApproval, PendingToolApprovalManager, pendingToolApprovalManager };
@@ -0,0 +1,133 @@
1
+ import { getLogger } from "../logger.js";
2
+
3
+ //#region src/services/PendingToolApprovalManager.ts
4
+ const logger = getLogger("PendingToolApprovalManager");
5
+ const APPROVAL_CLEANUP_INTERVAL_MS = 120 * 1e3;
6
+ const APPROVAL_TIMEOUT_MS = 600 * 1e3;
7
+ /**
8
+ * Manages pending tool approval requests during agent execution.
9
+ * Similar to ToolSessionManager but for approval workflows.
10
+ * Uses in-memory Map storage with automatic cleanup like OAuth PKCE store.
11
+ */
12
+ var PendingToolApprovalManager = class PendingToolApprovalManager {
13
+ static instance;
14
+ pendingApprovals = /* @__PURE__ */ new Map();
15
+ constructor() {
16
+ setInterval(() => this.cleanupExpiredApprovals(), APPROVAL_CLEANUP_INTERVAL_MS);
17
+ }
18
+ static getInstance() {
19
+ if (!PendingToolApprovalManager.instance) PendingToolApprovalManager.instance = new PendingToolApprovalManager();
20
+ return PendingToolApprovalManager.instance;
21
+ }
22
+ /**
23
+ * Create a new pending approval and return a promise that resolves with approval status
24
+ */
25
+ async waitForApproval(toolCallId, toolName, args, conversationId, subAgentId) {
26
+ return new Promise((resolve, reject) => {
27
+ const timeoutId = setTimeout(() => {
28
+ this.pendingApprovals.delete(toolCallId);
29
+ resolve({
30
+ approved: false,
31
+ reason: `Tool approval timeout for ${toolName} (${toolCallId})`
32
+ });
33
+ }, APPROVAL_TIMEOUT_MS);
34
+ const approval = {
35
+ toolCallId,
36
+ toolName,
37
+ args,
38
+ conversationId,
39
+ subAgentId,
40
+ createdAt: Date.now(),
41
+ resolve,
42
+ reject,
43
+ timeoutId
44
+ };
45
+ this.pendingApprovals.set(toolCallId, approval);
46
+ logger.info({
47
+ toolCallId,
48
+ toolName,
49
+ conversationId,
50
+ subAgentId
51
+ }, "Tool approval request created, waiting for user response");
52
+ });
53
+ }
54
+ /**
55
+ * Approve a pending tool call
56
+ */
57
+ approveToolCall(toolCallId) {
58
+ const approval = this.pendingApprovals.get(toolCallId);
59
+ if (!approval) {
60
+ logger.warn({ toolCallId }, "Tool approval not found or already processed");
61
+ return false;
62
+ }
63
+ logger.info({
64
+ toolCallId,
65
+ toolName: approval.toolName,
66
+ conversationId: approval.conversationId
67
+ }, "Tool approved by user, resuming execution");
68
+ clearTimeout(approval.timeoutId);
69
+ this.pendingApprovals.delete(toolCallId);
70
+ approval.resolve({ approved: true });
71
+ return true;
72
+ }
73
+ /**
74
+ * Deny a pending tool call
75
+ */
76
+ denyToolCall(toolCallId, reason) {
77
+ const approval = this.pendingApprovals.get(toolCallId);
78
+ if (!approval) {
79
+ logger.warn({ toolCallId }, "Tool approval not found or already processed");
80
+ return false;
81
+ }
82
+ logger.info({
83
+ toolCallId,
84
+ toolName: approval.toolName,
85
+ conversationId: approval.conversationId,
86
+ reason
87
+ }, "Tool execution denied by user");
88
+ clearTimeout(approval.timeoutId);
89
+ this.pendingApprovals.delete(toolCallId);
90
+ approval.resolve({
91
+ approved: false,
92
+ reason: reason || "User denied approval"
93
+ });
94
+ return true;
95
+ }
96
+ /**
97
+ * Clean up expired approvals (called by interval timer)
98
+ */
99
+ cleanupExpiredApprovals() {
100
+ const now = Date.now();
101
+ let cleanedUp = 0;
102
+ for (const [toolCallId, approval] of this.pendingApprovals) if (now - approval.createdAt > APPROVAL_TIMEOUT_MS) {
103
+ clearTimeout(approval.timeoutId);
104
+ this.pendingApprovals.delete(toolCallId);
105
+ approval.resolve({
106
+ approved: false,
107
+ reason: "Tool approval expired"
108
+ });
109
+ cleanedUp++;
110
+ }
111
+ if (cleanedUp > 0) logger.info({ cleanedUp }, "Cleaned up expired tool approvals");
112
+ }
113
+ /**
114
+ * Get current status for monitoring
115
+ */
116
+ getStatus() {
117
+ return {
118
+ pendingApprovals: this.pendingApprovals.size,
119
+ approvals: Array.from(this.pendingApprovals.values()).map((approval) => ({
120
+ toolCallId: approval.toolCallId,
121
+ toolName: approval.toolName,
122
+ conversationId: approval.conversationId,
123
+ subAgentId: approval.subAgentId,
124
+ createdAt: approval.createdAt,
125
+ age: Date.now() - approval.createdAt
126
+ }))
127
+ };
128
+ }
129
+ };
130
+ const pendingToolApprovalManager = PendingToolApprovalManager.getInstance();
131
+
132
+ //#endregion
133
+ export { PendingToolApprovalManager, pendingToolApprovalManager };
@@ -0,0 +1,39 @@
1
+ import { MessageContent } from "@inkeep/agents-core";
2
+
3
+ //#region src/services/ResponseFormatter.d.ts
4
+
5
+ /**
6
+ * Response formatter that uses the unified ArtifactParser to convert artifact markers
7
+ * into data parts for consistent artifact handling across all agent responses
8
+ */
9
+ declare class ResponseFormatter {
10
+ private artifactParser;
11
+ private subAgentId?;
12
+ constructor(tenantId: string, artifactParserOptions?: {
13
+ sessionId?: string;
14
+ taskId?: string;
15
+ projectId?: string;
16
+ contextId?: string;
17
+ artifactComponents?: any[];
18
+ streamRequestId?: string;
19
+ subAgentId?: string;
20
+ });
21
+ /**
22
+ * Process structured object response and replace artifact markers with actual artifacts
23
+ */
24
+ formatObjectResponse(responseObject: any, contextId: string): Promise<MessageContent>;
25
+ /**
26
+ * Process agent response and convert artifact markers to data parts
27
+ */
28
+ formatResponse(responseText: string, contextId: string): Promise<MessageContent>;
29
+ /**
30
+ * Count unique artifacts in parts array
31
+ */
32
+ private countUniqueArtifacts;
33
+ /**
34
+ * Log artifacts found in parts to span
35
+ */
36
+ private logArtifacts;
37
+ }
38
+ //#endregion
39
+ export { ResponseFormatter };
@@ -0,0 +1,152 @@
1
+ import { getLogger } from "../logger.js";
2
+ import { setSpanWithError, tracer } from "../utils/tracer.js";
3
+ import { ArtifactParser } from "./ArtifactParser.js";
4
+ import { agentSessionManager } from "./AgentSession.js";
5
+
6
+ //#region src/services/ResponseFormatter.ts
7
+ const logger = getLogger("ResponseFormatter");
8
+ /**
9
+ * Response formatter that uses the unified ArtifactParser to convert artifact markers
10
+ * into data parts for consistent artifact handling across all agent responses
11
+ */
12
+ var ResponseFormatter = class {
13
+ artifactParser;
14
+ subAgentId;
15
+ constructor(tenantId, artifactParserOptions) {
16
+ this.subAgentId = artifactParserOptions?.subAgentId;
17
+ if (artifactParserOptions?.streamRequestId) {
18
+ const sessionParser = agentSessionManager.getArtifactParser(artifactParserOptions.streamRequestId);
19
+ if (sessionParser) {
20
+ this.artifactParser = sessionParser;
21
+ return;
22
+ }
23
+ }
24
+ let sharedArtifactService = null;
25
+ if (artifactParserOptions?.streamRequestId && typeof agentSessionManager.getArtifactService === "function") try {
26
+ sharedArtifactService = agentSessionManager.getArtifactService(artifactParserOptions.streamRequestId);
27
+ } catch (_error) {}
28
+ this.artifactParser = new ArtifactParser(tenantId, {
29
+ ...artifactParserOptions,
30
+ artifactService: sharedArtifactService
31
+ });
32
+ }
33
+ /**
34
+ * Process structured object response and replace artifact markers with actual artifacts
35
+ */
36
+ async formatObjectResponse(responseObject, contextId) {
37
+ return tracer.startActiveSpan("response.format_object_response", async (span) => {
38
+ try {
39
+ const artifactMap = await this.artifactParser.getContextArtifacts(contextId);
40
+ span.setAttributes({
41
+ "response.type": "object",
42
+ "response.availableArtifacts": artifactMap.size
43
+ });
44
+ const parts = await this.artifactParser.parseObject(responseObject, artifactMap, this.subAgentId);
45
+ const uniqueArtifacts = this.countUniqueArtifacts(parts);
46
+ span.setAttributes({
47
+ "response.dataPartsCount": parts.length,
48
+ "response.artifactsCount": uniqueArtifacts,
49
+ "response.totalPartsCount": parts.length
50
+ });
51
+ this.logArtifacts(span, parts);
52
+ span.addEvent("response.parts.final_output", { final_parts_array: JSON.stringify(parts, null, 2) });
53
+ return { parts };
54
+ } catch (error) {
55
+ setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
56
+ logger.error({
57
+ error,
58
+ responseObject
59
+ }, "Error formatting object response");
60
+ return { parts: [{
61
+ kind: "data",
62
+ data: responseObject
63
+ }] };
64
+ } finally {
65
+ span.end();
66
+ }
67
+ });
68
+ }
69
+ /**
70
+ * Process agent response and convert artifact markers to data parts
71
+ */
72
+ async formatResponse(responseText, contextId) {
73
+ return tracer.startActiveSpan("response.format_response", async (span) => {
74
+ try {
75
+ const hasMarkers = this.artifactParser.hasArtifactMarkers(responseText);
76
+ span.setAttributes({
77
+ "response.hasArtifactMarkers": hasMarkers,
78
+ "response.contextId": contextId,
79
+ "response.textLength": responseText.length
80
+ });
81
+ if (!this.artifactParser.hasArtifactMarkers(responseText)) {
82
+ span.setAttributes({ "response.result": "no_markers_found" });
83
+ return { parts: [{
84
+ kind: "text",
85
+ text: responseText
86
+ }] };
87
+ }
88
+ const artifactMap = await this.artifactParser.getContextArtifacts(contextId);
89
+ span.setAttributes({
90
+ "response.type": "text",
91
+ "response.availableArtifacts": artifactMap.size
92
+ });
93
+ const parts = await this.artifactParser.parseText(responseText, artifactMap, this.subAgentId);
94
+ if (parts.length === 1 && parts[0].kind === "text") return { text: parts[0].text };
95
+ const textParts = parts.filter((p) => p.kind === "text").length;
96
+ const dataParts = parts.filter((p) => p.kind === "data").length;
97
+ const uniqueArtifacts = this.countUniqueArtifacts(parts);
98
+ span.setAttributes({
99
+ "response.textPartsCount": textParts,
100
+ "response.dataPartsCount": dataParts,
101
+ "response.artifactsCount": uniqueArtifacts,
102
+ "response.totalPartsCount": parts.length
103
+ });
104
+ this.logArtifacts(span, parts);
105
+ span.addEvent("response.parts.final_output", { final_parts_array: JSON.stringify(parts, null, 2) });
106
+ return { parts };
107
+ } catch (error) {
108
+ setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
109
+ logger.error({
110
+ error,
111
+ responseText
112
+ }, "Error formatting response");
113
+ return { text: responseText };
114
+ } finally {
115
+ span.end();
116
+ }
117
+ });
118
+ }
119
+ /**
120
+ * Count unique artifacts in parts array
121
+ */
122
+ countUniqueArtifacts(parts) {
123
+ return new Set(parts.filter((p) => p.kind === "data").map((p) => {
124
+ const data = p.data;
125
+ if (data?.artifactId && data?.taskId) return `${data.artifactId}:${data.taskId}`;
126
+ return null;
127
+ }).filter((key) => key !== null)).size;
128
+ }
129
+ /**
130
+ * Log artifacts found in parts to span
131
+ */
132
+ logArtifacts(span, parts) {
133
+ const artifacts = parts.filter((p) => p.kind === "data").map((p) => {
134
+ const data = p.data;
135
+ return {
136
+ artifactId: data?.artifactId,
137
+ name: data?.name,
138
+ taskId: data?.taskId
139
+ };
140
+ }).filter((art) => art.artifactId && art.taskId);
141
+ if (artifacts.length > 0) {
142
+ const uniqueArtifactsList = Array.from(new Map(artifacts.map((art) => [`${art.artifactId}:${art.taskId}`, art])).values());
143
+ span.addEvent("artifacts.found", {
144
+ "artifacts.count": uniqueArtifactsList.length,
145
+ "artifacts.list": JSON.stringify(uniqueArtifactsList)
146
+ });
147
+ }
148
+ }
149
+ };
150
+
151
+ //#endregion
152
+ export { ResponseFormatter };
@@ -0,0 +1,38 @@
1
+ import { SandboxConfig } from "../types/execution-context.js";
2
+
3
+ //#region src/tools/NativeSandboxExecutor.d.ts
4
+
5
+ interface FunctionToolConfig {
6
+ name?: string;
7
+ description: string;
8
+ inputSchema: Record<string, unknown>;
9
+ executeCode: string;
10
+ dependencies: Record<string, string>;
11
+ sandboxConfig?: SandboxConfig;
12
+ }
13
+ declare class NativeSandboxExecutor {
14
+ private tempDir;
15
+ private sandboxPool;
16
+ private static instance;
17
+ private executionSemaphores;
18
+ constructor();
19
+ static getInstance(): NativeSandboxExecutor;
20
+ private getSemaphore;
21
+ getExecutionStats(): Record<string, {
22
+ availablePermits: number;
23
+ queueLength: number;
24
+ }>;
25
+ private ensureTempDir;
26
+ private generateDependencyHash;
27
+ private getCachedSandbox;
28
+ private addToPool;
29
+ private cleanupSandbox;
30
+ private startPoolCleanup;
31
+ private detectModuleType;
32
+ executeFunctionTool(toolId: string, args: any, config: FunctionToolConfig): Promise<any>;
33
+ private executeInSandbox_Internal;
34
+ private installDependencies;
35
+ private executeInSandbox;
36
+ }
37
+ //#endregion
38
+ export { FunctionToolConfig, NativeSandboxExecutor };