@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.
- package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase1/system-prompt.js +5 -0
- package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase1/thinking-preparation.js +5 -0
- package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase1/tool.js +5 -0
- package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase2/data-component.js +5 -0
- package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase2/data-components.js +5 -0
- package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/phase2/system-prompt.js +5 -0
- package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/shared/artifact-retrieval-guidance.js +5 -0
- package/dist/_virtual/_raw_/home/runner/work/agents/agents/agents-run-api/templates/v1/shared/artifact.js +5 -0
- package/dist/a2a/client.d.ts +184 -0
- package/dist/a2a/client.js +510 -0
- package/dist/a2a/handlers.d.ts +7 -0
- package/dist/a2a/handlers.js +576 -0
- package/dist/a2a/transfer.d.ts +22 -0
- package/dist/a2a/transfer.js +46 -0
- package/dist/a2a/types.d.ts +79 -0
- package/dist/a2a/types.js +22 -0
- package/dist/agents/Agent.d.ts +268 -0
- package/dist/agents/Agent.js +1932 -0
- package/dist/agents/ModelFactory.d.ts +63 -0
- package/dist/agents/ModelFactory.js +194 -0
- package/dist/agents/SystemPromptBuilder.d.ts +21 -0
- package/dist/agents/SystemPromptBuilder.js +48 -0
- package/dist/agents/ToolSessionManager.d.ts +63 -0
- package/dist/agents/ToolSessionManager.js +146 -0
- package/dist/agents/generateTaskHandler.d.ts +49 -0
- package/dist/agents/generateTaskHandler.js +523 -0
- package/dist/agents/relationTools.d.ts +57 -0
- package/dist/agents/relationTools.js +262 -0
- package/dist/agents/types.d.ts +28 -0
- package/dist/agents/types.js +1 -0
- package/dist/agents/versions/v1/Phase1Config.d.ts +27 -0
- package/dist/agents/versions/v1/Phase1Config.js +424 -0
- package/dist/agents/versions/v1/Phase2Config.d.ts +31 -0
- package/dist/agents/versions/v1/Phase2Config.js +330 -0
- package/dist/constants/execution-limits/defaults.d.ts +51 -0
- package/dist/constants/execution-limits/defaults.js +52 -0
- package/dist/constants/execution-limits/index.d.ts +6 -0
- package/dist/constants/execution-limits/index.js +21 -0
- package/dist/create-app.d.ts +9 -0
- package/dist/create-app.js +195 -0
- package/dist/data/agent.d.ts +7 -0
- package/dist/data/agent.js +72 -0
- package/dist/data/agents.d.ts +34 -0
- package/dist/data/agents.js +139 -0
- package/dist/data/conversations.d.ts +128 -0
- package/dist/data/conversations.js +522 -0
- package/dist/data/db/dbClient.d.ts +6 -0
- package/dist/data/db/dbClient.js +17 -0
- package/dist/env.d.ts +57 -0
- package/dist/env.js +1 -2
- package/dist/handlers/executionHandler.d.ts +41 -0
- package/dist/handlers/executionHandler.js +457 -0
- package/dist/index.d.ts +8 -29
- package/dist/index.js +5 -11386
- package/dist/instrumentation.d.ts +1 -2
- package/dist/instrumentation.js +66 -3
- package/dist/{logger2.js → logger.d.ts} +1 -2
- package/dist/logger.js +1 -1
- package/dist/middleware/api-key-auth.d.ts +26 -0
- package/dist/middleware/api-key-auth.js +240 -0
- package/dist/middleware/index.d.ts +2 -0
- package/dist/middleware/index.js +3 -0
- package/dist/openapi.d.ts +4 -0
- package/dist/openapi.js +54 -0
- package/dist/routes/agents.d.ts +12 -0
- package/dist/routes/agents.js +147 -0
- package/dist/routes/chat.d.ts +13 -0
- package/dist/routes/chat.js +305 -0
- package/dist/routes/chatDataStream.d.ts +13 -0
- package/dist/routes/chatDataStream.js +365 -0
- package/dist/routes/mcp.d.ts +13 -0
- package/dist/routes/mcp.js +495 -0
- package/dist/services/AgentSession.d.ts +356 -0
- package/dist/services/AgentSession.js +1208 -0
- package/dist/services/ArtifactParser.d.ts +105 -0
- package/dist/services/ArtifactParser.js +338 -0
- package/dist/services/ArtifactService.d.ts +123 -0
- package/dist/services/ArtifactService.js +612 -0
- package/dist/services/BaseCompressor.d.ts +183 -0
- package/dist/services/BaseCompressor.js +500 -0
- package/dist/services/ConversationCompressor.d.ts +32 -0
- package/dist/services/ConversationCompressor.js +91 -0
- package/dist/services/IncrementalStreamParser.d.ts +98 -0
- package/dist/services/IncrementalStreamParser.js +327 -0
- package/dist/services/MidGenerationCompressor.d.ts +63 -0
- package/dist/services/MidGenerationCompressor.js +104 -0
- package/dist/services/PendingToolApprovalManager.d.ts +62 -0
- package/dist/services/PendingToolApprovalManager.js +133 -0
- package/dist/services/ResponseFormatter.d.ts +39 -0
- package/dist/services/ResponseFormatter.js +152 -0
- package/dist/tools/NativeSandboxExecutor.d.ts +38 -0
- package/dist/tools/NativeSandboxExecutor.js +432 -0
- package/dist/tools/SandboxExecutorFactory.d.ts +36 -0
- package/dist/tools/SandboxExecutorFactory.js +80 -0
- package/dist/tools/VercelSandboxExecutor.d.ts +71 -0
- package/dist/tools/VercelSandboxExecutor.js +340 -0
- package/dist/tools/distill-conversation-history-tool.d.ts +62 -0
- package/dist/tools/distill-conversation-history-tool.js +206 -0
- package/dist/tools/distill-conversation-tool.d.ts +41 -0
- package/dist/tools/distill-conversation-tool.js +141 -0
- package/dist/tools/sandbox-utils.d.ts +18 -0
- package/dist/tools/sandbox-utils.js +53 -0
- package/dist/types/chat.d.ts +27 -0
- package/dist/types/chat.js +1 -0
- package/dist/types/execution-context.d.ts +46 -0
- package/dist/types/execution-context.js +27 -0
- package/dist/types/xml.d.ts +5 -0
- package/dist/utils/SchemaProcessor.d.ts +52 -0
- package/dist/utils/SchemaProcessor.js +182 -0
- package/dist/utils/agent-operations.d.ts +62 -0
- package/dist/utils/agent-operations.js +53 -0
- package/dist/utils/artifact-component-schema.d.ts +42 -0
- package/dist/utils/artifact-component-schema.js +186 -0
- package/dist/utils/cleanup.d.ts +21 -0
- package/dist/utils/cleanup.js +59 -0
- package/dist/utils/data-component-schema.d.ts +2 -0
- package/dist/utils/data-component-schema.js +3 -0
- package/dist/utils/default-status-schemas.d.ts +20 -0
- package/dist/utils/default-status-schemas.js +24 -0
- package/dist/utils/json-postprocessor.d.ts +13 -0
- package/dist/{json-postprocessor.cjs → utils/json-postprocessor.js} +2 -3
- package/dist/utils/model-context-utils.d.ts +39 -0
- package/dist/utils/model-context-utils.js +181 -0
- package/dist/utils/model-resolver.d.ts +6 -0
- package/dist/utils/model-resolver.js +34 -0
- package/dist/utils/schema-validation.d.ts +44 -0
- package/dist/utils/schema-validation.js +97 -0
- package/dist/utils/stream-helpers.d.ts +197 -0
- package/dist/utils/stream-helpers.js +518 -0
- package/dist/utils/stream-registry.d.ts +22 -0
- package/dist/utils/stream-registry.js +34 -0
- package/dist/utils/token-estimator.d.ts +69 -0
- package/dist/utils/token-estimator.js +53 -0
- package/dist/utils/tracer.d.ts +7 -0
- package/dist/utils/tracer.js +7 -0
- package/package.json +10 -26
- package/dist/SandboxExecutorFactory.cjs +0 -895
- package/dist/SandboxExecutorFactory.js +0 -893
- package/dist/SandboxExecutorFactory.js.map +0 -1
- package/dist/chunk-VBDAOXYI.cjs +0 -927
- package/dist/chunk-VBDAOXYI.js +0 -832
- package/dist/chunk-VBDAOXYI.js.map +0 -1
- package/dist/chunk.cjs +0 -34
- package/dist/conversations.cjs +0 -7
- package/dist/conversations.js +0 -7
- package/dist/conversations2.cjs +0 -209
- package/dist/conversations2.js +0 -180
- package/dist/conversations2.js.map +0 -1
- package/dist/dbClient.cjs +0 -9676
- package/dist/dbClient.js +0 -9670
- package/dist/dbClient.js.map +0 -1
- package/dist/dbClient2.cjs +0 -5
- package/dist/dbClient2.js +0 -5
- package/dist/env.cjs +0 -59
- package/dist/env.js.map +0 -1
- package/dist/execution-limits.cjs +0 -260
- package/dist/execution-limits.js +0 -63
- package/dist/execution-limits.js.map +0 -1
- package/dist/index.cjs +0 -11411
- package/dist/index.d.cts +0 -36
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/instrumentation.cjs +0 -12
- package/dist/instrumentation.d.cts +0 -18
- package/dist/instrumentation.d.cts.map +0 -1
- package/dist/instrumentation.d.ts.map +0 -1
- package/dist/instrumentation2.cjs +0 -116
- package/dist/instrumentation2.js +0 -69
- package/dist/instrumentation2.js.map +0 -1
- package/dist/json-postprocessor.js +0 -20
- package/dist/json-postprocessor.js.map +0 -1
- package/dist/logger.cjs +0 -5
- package/dist/logger2.cjs +0 -1
- package/dist/nodefs.cjs +0 -29
- package/dist/nodefs.js +0 -27
- package/dist/nodefs.js.map +0 -1
- package/dist/opfs-ahp.cjs +0 -367
- package/dist/opfs-ahp.js +0 -368
- package/dist/opfs-ahp.js.map +0 -1
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import { getLogger } from "../logger.js";
|
|
2
|
+
import { flushBatchProcessor } from "../instrumentation.js";
|
|
3
|
+
import dbClient_default from "../data/db/dbClient.js";
|
|
4
|
+
import { AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS } from "../constants/execution-limits/index.js";
|
|
5
|
+
import { tracer } from "../utils/tracer.js";
|
|
6
|
+
import { registerStreamHelper, unregisterStreamHelper } from "../utils/stream-registry.js";
|
|
7
|
+
import { agentSessionManager } from "../services/AgentSession.js";
|
|
8
|
+
import { resolveModelConfig } from "../utils/model-resolver.js";
|
|
9
|
+
import { agentInitializingOp, completionOp, errorOp } from "../utils/agent-operations.js";
|
|
10
|
+
import { A2AClient } from "../a2a/client.js";
|
|
11
|
+
import { extractTransferData, isTransferTask } from "../a2a/types.js";
|
|
12
|
+
import { executeTransfer } from "../a2a/transfer.js";
|
|
13
|
+
import { BufferingStreamHelper } from "../utils/stream-helpers.js";
|
|
14
|
+
import { AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT, createMessage, createTask, generateId, getActiveAgentForConversation, getAgentWithDefaultSubAgent, getFullAgent, getTask, setSpanWithError, updateTask } from "@inkeep/agents-core";
|
|
15
|
+
|
|
16
|
+
//#region src/handlers/executionHandler.ts
|
|
17
|
+
const logger = getLogger("ExecutionHandler");
|
|
18
|
+
var ExecutionHandler = class {
|
|
19
|
+
MAX_ERRORS = AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS;
|
|
20
|
+
/**
|
|
21
|
+
* performs exeuction loop
|
|
22
|
+
*
|
|
23
|
+
* Do up to limit of MAX_ITERATIONS
|
|
24
|
+
*
|
|
25
|
+
* 1. lookup active agent for thread
|
|
26
|
+
* 2. Send A2A message to selected agent
|
|
27
|
+
* 3. Parse A2A message response
|
|
28
|
+
* 4. Handle transfer messages (if any)
|
|
29
|
+
* 5. Handle completion messages (if any)
|
|
30
|
+
* 6. If no valid response or transfer, return error
|
|
31
|
+
* @param params
|
|
32
|
+
* @returns
|
|
33
|
+
*/
|
|
34
|
+
async execute(params) {
|
|
35
|
+
const { executionContext, conversationId, userMessage, initialAgentId, requestId, sseHelper, emitOperations, forwardedHeaders } = params;
|
|
36
|
+
const { tenantId, projectId, agentId, apiKey, baseUrl } = executionContext;
|
|
37
|
+
registerStreamHelper(requestId, sseHelper);
|
|
38
|
+
agentSessionManager.createSession(requestId, agentId, tenantId, projectId, conversationId);
|
|
39
|
+
if (emitOperations) agentSessionManager.enableEmitOperations(requestId);
|
|
40
|
+
logger.info({
|
|
41
|
+
sessionId: requestId,
|
|
42
|
+
agentId,
|
|
43
|
+
conversationId,
|
|
44
|
+
emitOperations
|
|
45
|
+
}, "Created AgentSession for message execution");
|
|
46
|
+
let agentConfig = null;
|
|
47
|
+
try {
|
|
48
|
+
agentConfig = await getFullAgent(dbClient_default)({ scopes: {
|
|
49
|
+
tenantId,
|
|
50
|
+
projectId,
|
|
51
|
+
agentId
|
|
52
|
+
} });
|
|
53
|
+
if (agentConfig?.statusUpdates && agentConfig.statusUpdates.enabled !== false) try {
|
|
54
|
+
const agentWithDefault = await getAgentWithDefaultSubAgent(dbClient_default)({ scopes: {
|
|
55
|
+
tenantId,
|
|
56
|
+
projectId,
|
|
57
|
+
agentId
|
|
58
|
+
} });
|
|
59
|
+
if (agentWithDefault?.defaultSubAgent) {
|
|
60
|
+
const resolvedModels = await resolveModelConfig(agentId, agentWithDefault.defaultSubAgent);
|
|
61
|
+
agentSessionManager.initializeStatusUpdates(requestId, agentConfig.statusUpdates, resolvedModels.summarizer, resolvedModels.base);
|
|
62
|
+
} else agentSessionManager.initializeStatusUpdates(requestId, agentConfig.statusUpdates, agentConfig.models?.summarizer);
|
|
63
|
+
} catch (modelError) {
|
|
64
|
+
logger.warn({
|
|
65
|
+
error: modelError instanceof Error ? modelError.message : "Unknown error",
|
|
66
|
+
agentId
|
|
67
|
+
}, "Failed to resolve models for status updates, using agent-level config");
|
|
68
|
+
agentSessionManager.initializeStatusUpdates(requestId, agentConfig.statusUpdates, agentConfig.models?.summarizer);
|
|
69
|
+
}
|
|
70
|
+
} catch (error) {
|
|
71
|
+
logger.error({
|
|
72
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
73
|
+
stack: error instanceof Error ? error.stack : void 0
|
|
74
|
+
}, "❌ Failed to initialize status updates, continuing without them");
|
|
75
|
+
}
|
|
76
|
+
let currentAgentId = initialAgentId;
|
|
77
|
+
let iterations = 0;
|
|
78
|
+
let errorCount = 0;
|
|
79
|
+
let task = null;
|
|
80
|
+
let fromSubAgentId;
|
|
81
|
+
try {
|
|
82
|
+
await sseHelper.writeOperation(agentInitializingOp(requestId, agentId));
|
|
83
|
+
const taskId = `task_${conversationId}-${requestId}`;
|
|
84
|
+
logger.info({
|
|
85
|
+
taskId,
|
|
86
|
+
currentAgentId,
|
|
87
|
+
conversationId,
|
|
88
|
+
requestId
|
|
89
|
+
}, "Attempting to create or reuse existing task");
|
|
90
|
+
try {
|
|
91
|
+
task = await createTask(dbClient_default)({
|
|
92
|
+
id: taskId,
|
|
93
|
+
tenantId,
|
|
94
|
+
projectId,
|
|
95
|
+
agentId,
|
|
96
|
+
subAgentId: currentAgentId,
|
|
97
|
+
contextId: conversationId,
|
|
98
|
+
status: "pending",
|
|
99
|
+
metadata: {
|
|
100
|
+
conversation_id: conversationId,
|
|
101
|
+
message_id: requestId,
|
|
102
|
+
stream_request_id: requestId,
|
|
103
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
104
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
105
|
+
root_sub_agent_id: initialAgentId,
|
|
106
|
+
sub_agent_id: currentAgentId
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
logger.info({
|
|
110
|
+
taskId,
|
|
111
|
+
createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
|
|
112
|
+
}, "Task created with metadata");
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (error?.cause?.code === "23505") {
|
|
115
|
+
logger.info({
|
|
116
|
+
taskId,
|
|
117
|
+
error: error.message
|
|
118
|
+
}, "Task already exists, fetching existing task");
|
|
119
|
+
const existingTask = await getTask(dbClient_default)({ id: taskId });
|
|
120
|
+
if (existingTask) {
|
|
121
|
+
task = existingTask;
|
|
122
|
+
logger.info({
|
|
123
|
+
taskId,
|
|
124
|
+
existingTask
|
|
125
|
+
}, "Successfully reused existing task from race condition");
|
|
126
|
+
} else {
|
|
127
|
+
logger.error({
|
|
128
|
+
taskId,
|
|
129
|
+
error
|
|
130
|
+
}, "Task constraint failed but task not found");
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
} else {
|
|
134
|
+
logger.error({
|
|
135
|
+
taskId,
|
|
136
|
+
error
|
|
137
|
+
}, "Failed to create task due to non-constraint error");
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
logger.debug({
|
|
142
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
143
|
+
executionType: "create_initial_task",
|
|
144
|
+
conversationId,
|
|
145
|
+
agentId,
|
|
146
|
+
requestId,
|
|
147
|
+
currentAgentId,
|
|
148
|
+
taskId: Array.isArray(task) ? task[0]?.id : task?.id,
|
|
149
|
+
userMessage: userMessage.substring(0, 100)
|
|
150
|
+
}, "ExecutionHandler: Initial task created");
|
|
151
|
+
if (Array.isArray(task)) task = task[0];
|
|
152
|
+
let currentMessage = userMessage;
|
|
153
|
+
const maxTransfers = agentConfig?.stopWhen?.transferCountIs ?? AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT;
|
|
154
|
+
while (iterations < maxTransfers) {
|
|
155
|
+
iterations++;
|
|
156
|
+
logger.info({
|
|
157
|
+
iterations,
|
|
158
|
+
currentAgentId,
|
|
159
|
+
agentId,
|
|
160
|
+
conversationId,
|
|
161
|
+
fromSubAgentId
|
|
162
|
+
}, `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromSubAgentId || "none"}`);
|
|
163
|
+
const activeAgent = await getActiveAgentForConversation(dbClient_default)({
|
|
164
|
+
scopes: {
|
|
165
|
+
tenantId,
|
|
166
|
+
projectId
|
|
167
|
+
},
|
|
168
|
+
conversationId
|
|
169
|
+
});
|
|
170
|
+
logger.info({ activeAgent }, "activeAgent");
|
|
171
|
+
if (activeAgent && activeAgent.activeSubAgentId !== currentAgentId) {
|
|
172
|
+
currentAgentId = activeAgent.activeSubAgentId;
|
|
173
|
+
logger.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
|
|
174
|
+
}
|
|
175
|
+
const a2aClient = new A2AClient(`${baseUrl}/agents`, { headers: {
|
|
176
|
+
Authorization: `Bearer ${apiKey}`,
|
|
177
|
+
"x-inkeep-tenant-id": tenantId,
|
|
178
|
+
"x-inkeep-project-id": projectId,
|
|
179
|
+
"x-inkeep-agent-id": agentId,
|
|
180
|
+
"x-inkeep-sub-agent-id": currentAgentId,
|
|
181
|
+
...forwardedHeaders || {}
|
|
182
|
+
} });
|
|
183
|
+
let messageResponse = null;
|
|
184
|
+
const messageMetadata = { stream_request_id: requestId };
|
|
185
|
+
if (fromSubAgentId) messageMetadata.fromSubAgentId = fromSubAgentId;
|
|
186
|
+
messageResponse = await a2aClient.sendMessage({
|
|
187
|
+
message: {
|
|
188
|
+
role: "user",
|
|
189
|
+
parts: [{
|
|
190
|
+
kind: "text",
|
|
191
|
+
text: currentMessage
|
|
192
|
+
}],
|
|
193
|
+
messageId: `${requestId}-iter-${iterations}`,
|
|
194
|
+
kind: "message",
|
|
195
|
+
contextId: conversationId,
|
|
196
|
+
metadata: messageMetadata
|
|
197
|
+
},
|
|
198
|
+
configuration: {
|
|
199
|
+
acceptedOutputModes: ["text", "text/plain"],
|
|
200
|
+
blocking: false
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
if (!messageResponse?.result) {
|
|
204
|
+
errorCount++;
|
|
205
|
+
logger.error({
|
|
206
|
+
currentAgentId,
|
|
207
|
+
iterations,
|
|
208
|
+
errorCount
|
|
209
|
+
}, `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`);
|
|
210
|
+
if (errorCount >= this.MAX_ERRORS) {
|
|
211
|
+
const errorMessage$1 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
|
|
212
|
+
logger.error({
|
|
213
|
+
maxErrors: this.MAX_ERRORS,
|
|
214
|
+
errorCount
|
|
215
|
+
}, errorMessage$1);
|
|
216
|
+
await sseHelper.writeOperation(errorOp(errorMessage$1, currentAgentId || "system"));
|
|
217
|
+
if (task) await updateTask(dbClient_default)({
|
|
218
|
+
taskId: task.id,
|
|
219
|
+
data: {
|
|
220
|
+
status: "failed",
|
|
221
|
+
metadata: {
|
|
222
|
+
...task.metadata,
|
|
223
|
+
failed_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
224
|
+
error: errorMessage$1
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
await agentSessionManager.endSession(requestId);
|
|
229
|
+
unregisterStreamHelper(requestId);
|
|
230
|
+
return {
|
|
231
|
+
success: false,
|
|
232
|
+
error: errorMessage$1,
|
|
233
|
+
iterations
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
if (isTransferTask(messageResponse.result)) {
|
|
239
|
+
const transferData = extractTransferData(messageResponse.result);
|
|
240
|
+
if (!transferData) {
|
|
241
|
+
logger.error({ result: messageResponse.result }, "Transfer detected but no transfer data found");
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
const { targetSubAgentId, fromSubAgentId: transferFromAgent } = transferData;
|
|
245
|
+
const firstArtifact = messageResponse.result.artifacts[0];
|
|
246
|
+
const transferReason = firstArtifact?.parts[1]?.kind === "text" ? firstArtifact.parts[1].text : "Transfer initiated";
|
|
247
|
+
logger.info({
|
|
248
|
+
targetSubAgentId,
|
|
249
|
+
transferReason,
|
|
250
|
+
transferFromAgent
|
|
251
|
+
}, "Transfer response");
|
|
252
|
+
await createMessage(dbClient_default)({
|
|
253
|
+
id: generateId(),
|
|
254
|
+
tenantId,
|
|
255
|
+
projectId,
|
|
256
|
+
conversationId,
|
|
257
|
+
role: "agent",
|
|
258
|
+
content: {
|
|
259
|
+
text: transferReason,
|
|
260
|
+
parts: [{
|
|
261
|
+
kind: "text",
|
|
262
|
+
text: transferReason
|
|
263
|
+
}]
|
|
264
|
+
},
|
|
265
|
+
visibility: "user-facing",
|
|
266
|
+
messageType: "chat",
|
|
267
|
+
fromSubAgentId: currentAgentId,
|
|
268
|
+
taskId: task.id
|
|
269
|
+
});
|
|
270
|
+
currentMessage = currentMessage + "\n\nPlease continue this conversation seamlessly. The previous response in conversation history was from another internal agent, but you must continue as if YOU made that response. All responses must appear as one unified agent - do not repeat what was already communicated.";
|
|
271
|
+
const { success, targetSubAgentId: newAgentId } = await executeTransfer({
|
|
272
|
+
projectId,
|
|
273
|
+
tenantId,
|
|
274
|
+
threadId: conversationId,
|
|
275
|
+
targetSubAgentId
|
|
276
|
+
});
|
|
277
|
+
if (success) {
|
|
278
|
+
fromSubAgentId = currentAgentId;
|
|
279
|
+
currentAgentId = newAgentId;
|
|
280
|
+
logger.info({
|
|
281
|
+
transferFrom: fromSubAgentId,
|
|
282
|
+
transferTo: currentAgentId,
|
|
283
|
+
reason: transferReason
|
|
284
|
+
}, "Transfer executed, tracking fromSubAgentId for next iteration");
|
|
285
|
+
}
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
let responseParts = [];
|
|
289
|
+
if (messageResponse.result.streamedContent?.parts) {
|
|
290
|
+
responseParts = messageResponse.result.streamedContent.parts;
|
|
291
|
+
logger.info({ partsCount: responseParts.length }, "Using streamed content for conversation history");
|
|
292
|
+
} else {
|
|
293
|
+
responseParts = messageResponse.result.artifacts?.flatMap((artifact) => artifact.parts || []) || [];
|
|
294
|
+
logger.info({ partsCount: responseParts.length }, "Using artifacts for conversation history (fallback)");
|
|
295
|
+
}
|
|
296
|
+
if (responseParts && responseParts.length > 0) {
|
|
297
|
+
const agentSessionData = agentSessionManager.getSession(requestId);
|
|
298
|
+
if (agentSessionData) {
|
|
299
|
+
const sessionSummary = agentSessionData.getSummary();
|
|
300
|
+
logger.info(sessionSummary, "AgentSession data after completion");
|
|
301
|
+
}
|
|
302
|
+
let textContent = "";
|
|
303
|
+
for (const part of responseParts) if ((part.kind === "text" || part.type === "text") && part.text) textContent += part.text;
|
|
304
|
+
return tracer.startActiveSpan("execution_handler.execute", {}, async (span) => {
|
|
305
|
+
try {
|
|
306
|
+
span.setAttributes({
|
|
307
|
+
"ai.response.content": textContent || "No response content",
|
|
308
|
+
"ai.response.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
|
|
309
|
+
"subAgent.name": agentConfig?.subAgents[currentAgentId]?.name,
|
|
310
|
+
"subAgent.id": currentAgentId
|
|
311
|
+
});
|
|
312
|
+
await createMessage(dbClient_default)({
|
|
313
|
+
id: generateId(),
|
|
314
|
+
tenantId,
|
|
315
|
+
projectId,
|
|
316
|
+
conversationId,
|
|
317
|
+
role: "agent",
|
|
318
|
+
content: {
|
|
319
|
+
text: textContent || void 0,
|
|
320
|
+
parts: responseParts.map((part) => ({
|
|
321
|
+
type: part.kind === "text" ? "text" : "data",
|
|
322
|
+
text: part.kind === "text" ? part.text : void 0,
|
|
323
|
+
data: part.kind === "data" ? JSON.stringify(part.data) : void 0
|
|
324
|
+
}))
|
|
325
|
+
},
|
|
326
|
+
visibility: "user-facing",
|
|
327
|
+
messageType: "chat",
|
|
328
|
+
fromSubAgentId: currentAgentId,
|
|
329
|
+
taskId: task.id
|
|
330
|
+
});
|
|
331
|
+
const updateTaskStart = Date.now();
|
|
332
|
+
await updateTask(dbClient_default)({
|
|
333
|
+
taskId: task.id,
|
|
334
|
+
data: {
|
|
335
|
+
status: "completed",
|
|
336
|
+
metadata: {
|
|
337
|
+
...task.metadata,
|
|
338
|
+
completed_at: /* @__PURE__ */ new Date(),
|
|
339
|
+
response: {
|
|
340
|
+
text: textContent,
|
|
341
|
+
parts: responseParts,
|
|
342
|
+
hasText: !!textContent,
|
|
343
|
+
hasData: responseParts.some((p) => p.kind === "data")
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
const updateTaskEnd = Date.now();
|
|
349
|
+
logger.info({ duration: updateTaskEnd - updateTaskStart }, "Completed updateTask operation");
|
|
350
|
+
await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
|
|
351
|
+
await sseHelper.complete();
|
|
352
|
+
logger.info({}, "Ending AgentSession and cleaning up");
|
|
353
|
+
await agentSessionManager.endSession(requestId);
|
|
354
|
+
logger.info({}, "Cleaning up streamHelper");
|
|
355
|
+
unregisterStreamHelper(requestId);
|
|
356
|
+
let response;
|
|
357
|
+
if (sseHelper instanceof BufferingStreamHelper) response = sseHelper.getCapturedResponse().text || "No response content";
|
|
358
|
+
logger.info({}, "ExecutionHandler returning success");
|
|
359
|
+
return {
|
|
360
|
+
success: true,
|
|
361
|
+
iterations,
|
|
362
|
+
response
|
|
363
|
+
};
|
|
364
|
+
} catch (error) {
|
|
365
|
+
setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
|
|
366
|
+
throw error;
|
|
367
|
+
} finally {
|
|
368
|
+
span.end();
|
|
369
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
370
|
+
await flushBatchProcessor();
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
errorCount++;
|
|
375
|
+
logger.warn({
|
|
376
|
+
iterations,
|
|
377
|
+
errorCount
|
|
378
|
+
}, `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`);
|
|
379
|
+
if (errorCount >= this.MAX_ERRORS) {
|
|
380
|
+
const errorMessage$1 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
|
|
381
|
+
logger.error({
|
|
382
|
+
maxErrors: this.MAX_ERRORS,
|
|
383
|
+
errorCount
|
|
384
|
+
}, errorMessage$1);
|
|
385
|
+
await sseHelper.writeOperation(errorOp(errorMessage$1, currentAgentId || "system"));
|
|
386
|
+
if (task) await updateTask(dbClient_default)({
|
|
387
|
+
taskId: task.id,
|
|
388
|
+
data: {
|
|
389
|
+
status: "failed",
|
|
390
|
+
metadata: {
|
|
391
|
+
...task.metadata,
|
|
392
|
+
failed_at: /* @__PURE__ */ new Date(),
|
|
393
|
+
error: errorMessage$1
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
await agentSessionManager.endSession(requestId);
|
|
398
|
+
unregisterStreamHelper(requestId);
|
|
399
|
+
return {
|
|
400
|
+
success: false,
|
|
401
|
+
error: errorMessage$1,
|
|
402
|
+
iterations
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
|
|
407
|
+
logger.error({
|
|
408
|
+
maxTransfers,
|
|
409
|
+
iterations
|
|
410
|
+
}, errorMessage);
|
|
411
|
+
await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
|
|
412
|
+
if (task) await updateTask(dbClient_default)({
|
|
413
|
+
taskId: task.id,
|
|
414
|
+
data: {
|
|
415
|
+
status: "failed",
|
|
416
|
+
metadata: {
|
|
417
|
+
...task.metadata,
|
|
418
|
+
failed_at: /* @__PURE__ */ new Date(),
|
|
419
|
+
error: errorMessage
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
await agentSessionManager.endSession(requestId);
|
|
424
|
+
unregisterStreamHelper(requestId);
|
|
425
|
+
return {
|
|
426
|
+
success: false,
|
|
427
|
+
error: errorMessage,
|
|
428
|
+
iterations
|
|
429
|
+
};
|
|
430
|
+
} catch (error) {
|
|
431
|
+
logger.error({ error }, "Error in execution handler");
|
|
432
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
|
|
433
|
+
await sseHelper.writeOperation(errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system"));
|
|
434
|
+
if (task) await updateTask(dbClient_default)({
|
|
435
|
+
taskId: task.id,
|
|
436
|
+
data: {
|
|
437
|
+
status: "failed",
|
|
438
|
+
metadata: {
|
|
439
|
+
...task.metadata,
|
|
440
|
+
failed_at: /* @__PURE__ */ new Date(),
|
|
441
|
+
error: errorMessage
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
});
|
|
445
|
+
await agentSessionManager.endSession(requestId);
|
|
446
|
+
unregisterStreamHelper(requestId);
|
|
447
|
+
return {
|
|
448
|
+
success: false,
|
|
449
|
+
error: errorMessage,
|
|
450
|
+
iterations
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
//#endregion
|
|
457
|
+
export { ExecutionHandler };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,37 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
1
|
+
import { NativeSandboxConfig, SandboxConfig, VercelSandboxConfig } from "./types/execution-context.js";
|
|
2
|
+
import { createExecutionHono } from "./create-app.js";
|
|
3
|
+
import "./env.js";
|
|
4
|
+
import { CredentialStore, ServerConfig } from "@inkeep/agents-core";
|
|
4
5
|
import { Hono } from "hono";
|
|
5
|
-
import * as
|
|
6
|
+
import * as hono_types1 from "hono/types";
|
|
6
7
|
|
|
7
|
-
//#region src/types/execution-context.d.ts
|
|
8
|
-
|
|
9
|
-
interface CommonSandboxConfig {
|
|
10
|
-
runtime: 'node22' | 'typescript';
|
|
11
|
-
timeout?: number;
|
|
12
|
-
vcpus?: number;
|
|
13
|
-
}
|
|
14
|
-
interface NativeSandboxConfig extends CommonSandboxConfig {
|
|
15
|
-
provider: 'native';
|
|
16
|
-
}
|
|
17
|
-
interface VercelSandboxConfig extends CommonSandboxConfig {
|
|
18
|
-
provider: 'vercel';
|
|
19
|
-
teamId: string;
|
|
20
|
-
projectId: string;
|
|
21
|
-
token: string;
|
|
22
|
-
}
|
|
23
|
-
type SandboxConfig = NativeSandboxConfig | VercelSandboxConfig;
|
|
24
|
-
//#endregion
|
|
25
|
-
//#region src/app.d.ts
|
|
26
|
-
declare function createExecutionHono(serverConfig: ServerConfig, credentialStores: CredentialStoreRegistry, sandboxConfig?: SandboxConfig): Hono<hono_types3.BlankEnv, hono_types3.BlankSchema, "/">;
|
|
27
|
-
//#endregion
|
|
28
8
|
//#region src/index.d.ts
|
|
29
|
-
declare const app:
|
|
9
|
+
declare const app: Hono<hono_types1.BlankEnv, hono_types1.BlankSchema, "/">;
|
|
30
10
|
declare function createExecutionApp(config?: {
|
|
31
11
|
serverConfig?: ServerConfig;
|
|
32
12
|
credentialStores?: CredentialStore[];
|
|
33
13
|
sandboxConfig?: SandboxConfig;
|
|
34
|
-
}):
|
|
14
|
+
}): Hono<hono_types1.BlankEnv, hono_types1.BlankSchema, "/">;
|
|
35
15
|
//#endregion
|
|
36
|
-
export { type NativeSandboxConfig, type SandboxConfig, type VercelSandboxConfig, createExecutionApp, createExecutionHono, app as default };
|
|
37
|
-
//# sourceMappingURL=index.d.ts.map
|
|
16
|
+
export { Hono, type NativeSandboxConfig, type SandboxConfig, type VercelSandboxConfig, createExecutionApp, createExecutionHono, app as default };
|