@inkeep/agents-run-api 0.37.1 → 0.38.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/{SandboxExecutorFactory-FVKDJKKZ.js → SandboxExecutorFactory-2N27SE3B.js} +1 -1
- package/dist/{chunk-V4RNZ6BX.js → chunk-EVOISBFH.js} +9 -9
- package/dist/{chunk-SBJLXGYG.js → chunk-JCVMVG3J.js} +2 -2
- package/dist/{chunk-IYG4HUQ6.js → chunk-KBZIYCPJ.js} +1 -1
- package/dist/{chunk-M46DFVYB.js → chunk-KCJWSIDZ.js} +3 -3
- package/dist/{chunk-IVALDC72.js → chunk-THWNUGWP.js} +1 -1
- package/dist/{chunk-AZFBQY6E.js → chunk-UC2EPLSW.js} +1 -1
- package/dist/{conversations-NZLQK64L.js → conversations-XPSTWUMK.js} +1 -1
- package/dist/dbClient-MAHUR4TO.js +1 -0
- package/dist/index.cjs +559 -448
- package/dist/index.js +399 -282
- package/dist/instrumentation.cjs +19 -19
- package/dist/instrumentation.js +1 -1
- package/dist/{nodefs-ZHXQGWPG.js → nodefs-RPE52Q4Z.js} +1 -1
- package/dist/{opfs-ahp-CJXSQU3E.js → opfs-ahp-QL4REJJW.js} +2 -2
- package/package.json +13 -11
- package/dist/dbClient-BXOIYVCJ.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { flushBatchProcessor } from './chunk-
|
|
2
|
-
import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-
|
|
3
|
-
import { dbClient_default } from './chunk-
|
|
4
|
-
import { env } from './chunk-
|
|
1
|
+
import { defaultSDK, flushBatchProcessor } from './chunk-UC2EPLSW.js';
|
|
2
|
+
import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-KCJWSIDZ.js';
|
|
3
|
+
import { dbClient_default } from './chunk-EVOISBFH.js';
|
|
4
|
+
import { env } from './chunk-KBZIYCPJ.js';
|
|
5
5
|
import { getLogger } from './chunk-A2S7GSHL.js';
|
|
6
|
-
import { SESSION_CLEANUP_INTERVAL_MS, AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS, SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS, STREAM_MAX_LIFETIME_MS, STREAM_BUFFER_MAX_SIZE_BYTES, STREAM_TEXT_GAP_THRESHOLD_MS, ARTIFACT_GENERATION_MAX_RETRIES, ARTIFACT_SESSION_MAX_PENDING, STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS, STATUS_UPDATE_DEFAULT_NUM_EVENTS, ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES, AGENT_EXECUTION_MAX_GENERATION_STEPS, FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT, FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS, ARTIFACT_GENERATION_BACKOFF_INITIAL_MS, ARTIFACT_GENERATION_BACKOFF_MAX_MS, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING, LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS, DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS, DELEGATION_TOOL_BACKOFF_EXPONENT, DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS, DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS, STREAM_PARSER_MAX_SNAPSHOT_SIZE, STREAM_PARSER_MAX_STREAMED_SIZE, STREAM_PARSER_MAX_COLLECTED_PARTS } from './chunk-
|
|
7
|
-
import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, generateId, commonGetErrorResponses, loggerFactory, getConversation, createDefaultCredentialStores, CredentialStoreRegistry, createTask, getTask, updateTask, setSpanWithError, AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT, updateConversation, handleApiError, TaskState, getAgentById, getProject, setActiveAgentForThread, getRelatedAgentsForAgent, getExternalAgentsForSubAgent, getTeamAgentsForSubAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, CONVERSATION_HISTORY_DEFAULT_LIMIT, ModelFactory, verifyTempToken, validateAndGetApiKey, verifyServiceToken, validateTargetAgent, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, getContextConfigById, getFullAgentDefinition, TemplateEngine, listTaskIdsByContextId, getLedgerArtifacts, agentHasArtifactComponents, upsertLedgerArtifact, MCPTransportType, SPAN_KEYS, headers, generateServiceToken } from '@inkeep/agents-core';
|
|
6
|
+
import { SESSION_CLEANUP_INTERVAL_MS, AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS, SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS, STREAM_MAX_LIFETIME_MS, STREAM_BUFFER_MAX_SIZE_BYTES, STREAM_TEXT_GAP_THRESHOLD_MS, ARTIFACT_GENERATION_MAX_RETRIES, ARTIFACT_SESSION_MAX_PENDING, STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS, STATUS_UPDATE_DEFAULT_NUM_EVENTS, ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES, AGENT_EXECUTION_MAX_GENERATION_STEPS, FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT, FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS, ARTIFACT_GENERATION_BACKOFF_INITIAL_MS, ARTIFACT_GENERATION_BACKOFF_MAX_MS, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING, LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS, DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS, DELEGATION_TOOL_BACKOFF_EXPONENT, DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS, DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS, STREAM_PARSER_MAX_SNAPSHOT_SIZE, STREAM_PARSER_MAX_STREAMED_SIZE, STREAM_PARSER_MAX_COLLECTED_PARTS } from './chunk-THWNUGWP.js';
|
|
7
|
+
import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, generateId, commonGetErrorResponses, loggerFactory, getConversation, createDefaultCredentialStores, CredentialStoreRegistry, createTask, getTask, updateTask, setSpanWithError, AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT, updateConversation, handleApiError, TaskState, getAgentById, getProject, setActiveAgentForThread, getRelatedAgentsForAgent, getExternalAgentsForSubAgent, getTeamAgentsForSubAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, CONVERSATION_HISTORY_DEFAULT_LIMIT, ModelFactory, verifyTempToken, validateAndGetApiKey, verifyServiceToken, validateTargetAgent, ContextResolver, CredentialStuffer, MCPServerType, getUserScopedCredentialReference, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, jsonSchemaToZod, getContextConfigById, getFullAgentDefinition, TemplateEngine, listTaskIdsByContextId, getLedgerArtifacts, agentHasArtifactComponents, upsertLedgerArtifact, MCPTransportType, SPAN_KEYS, headers, generateServiceToken } from '@inkeep/agents-core';
|
|
8
8
|
import { otel } from '@hono/otel';
|
|
9
|
-
import { OpenAPIHono, createRoute, z
|
|
9
|
+
import { OpenAPIHono, createRoute, z } from '@hono/zod-openapi';
|
|
10
10
|
import { trace, propagation, context, SpanStatusCode } from '@opentelemetry/api';
|
|
11
11
|
import { Hono } from 'hono';
|
|
12
12
|
import { cors } from 'hono/cors';
|
|
@@ -14,7 +14,6 @@ import { HTTPException } from 'hono/http-exception';
|
|
|
14
14
|
import { requestId } from 'hono/request-id';
|
|
15
15
|
import { createMiddleware } from 'hono/factory';
|
|
16
16
|
import { swaggerUI } from '@hono/swagger-ui';
|
|
17
|
-
import z5, { z } from 'zod';
|
|
18
17
|
import { streamSSE, stream } from 'hono/streaming';
|
|
19
18
|
import { createUIMessageStream, JsonToSseTransformStream, parsePartialJson, generateObject, tool, streamText, generateText, streamObject } from 'ai';
|
|
20
19
|
import jmespath from 'jmespath';
|
|
@@ -26,6 +25,10 @@ import { StreamableHTTPServerTransport } from '@alcyone-labs/modelcontextprotoco
|
|
|
26
25
|
import { toReqRes, toFetchResponse } from 'fetch-to-node';
|
|
27
26
|
|
|
28
27
|
// src/types/execution-context.ts
|
|
28
|
+
function getUserIdFromContext(ctx) {
|
|
29
|
+
const metadata = ctx.metadata;
|
|
30
|
+
return metadata?.initiatedBy?.type === "user" ? metadata.initiatedBy.id : void 0;
|
|
31
|
+
}
|
|
29
32
|
function createExecutionContext(params) {
|
|
30
33
|
return {
|
|
31
34
|
apiKey: params.apiKey,
|
|
@@ -628,6 +631,21 @@ async function handleMessageSend(c, agent, request) {
|
|
|
628
631
|
});
|
|
629
632
|
}
|
|
630
633
|
}
|
|
634
|
+
if (result.status.state === TaskState.Failed) {
|
|
635
|
+
const isConnectionRefused = result.status.type === "connection_refused";
|
|
636
|
+
if (isConnectionRefused) {
|
|
637
|
+
return c.json({
|
|
638
|
+
jsonrpc: "2.0",
|
|
639
|
+
error: {
|
|
640
|
+
code: -32603,
|
|
641
|
+
message: result.status.message || "Agent execution failed",
|
|
642
|
+
data: {
|
|
643
|
+
type: "connection_refused"
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
}
|
|
631
649
|
const taskStatus = {
|
|
632
650
|
state: result.status.state,
|
|
633
651
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -2645,13 +2663,30 @@ var AgentSession = class {
|
|
|
2645
2663
|
/**
|
|
2646
2664
|
* Clean up status update resources when session ends
|
|
2647
2665
|
*/
|
|
2648
|
-
cleanup() {
|
|
2666
|
+
async cleanup() {
|
|
2649
2667
|
this.isEnded = true;
|
|
2650
2668
|
if (this.statusUpdateTimer) {
|
|
2651
2669
|
clearInterval(this.statusUpdateTimer);
|
|
2652
2670
|
this.statusUpdateTimer = void 0;
|
|
2653
2671
|
}
|
|
2654
2672
|
this.statusUpdateState = void 0;
|
|
2673
|
+
if (this.pendingArtifacts.size > 0) {
|
|
2674
|
+
const maxWaitTime = 1e4;
|
|
2675
|
+
const startTime = Date.now();
|
|
2676
|
+
while (this.pendingArtifacts.size > 0 && Date.now() - startTime < maxWaitTime) {
|
|
2677
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
2678
|
+
}
|
|
2679
|
+
if (this.pendingArtifacts.size > 0) {
|
|
2680
|
+
logger7.warn(
|
|
2681
|
+
{
|
|
2682
|
+
sessionId: this.sessionId,
|
|
2683
|
+
pendingCount: this.pendingArtifacts.size,
|
|
2684
|
+
pendingIds: Array.from(this.pendingArtifacts)
|
|
2685
|
+
},
|
|
2686
|
+
"Cleanup proceeding with pending artifacts still processing"
|
|
2687
|
+
);
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2655
2690
|
this.pendingArtifacts.clear();
|
|
2656
2691
|
this.artifactProcessingErrors.clear();
|
|
2657
2692
|
this.artifactCache.clear();
|
|
@@ -3426,6 +3461,9 @@ Make it specific and relevant.`;
|
|
|
3426
3461
|
result = object;
|
|
3427
3462
|
}
|
|
3428
3463
|
try {
|
|
3464
|
+
if (!this.artifactService) {
|
|
3465
|
+
throw new Error("ArtifactService is not initialized");
|
|
3466
|
+
}
|
|
3429
3467
|
await this.artifactService.saveArtifact({
|
|
3430
3468
|
artifactId: artifactData.artifactId,
|
|
3431
3469
|
name: result.name,
|
|
@@ -3615,7 +3653,7 @@ var AgentSessionManager = class {
|
|
|
3615
3653
|
/**
|
|
3616
3654
|
* End a session and return the final event data
|
|
3617
3655
|
*/
|
|
3618
|
-
endSession(sessionId) {
|
|
3656
|
+
async endSession(sessionId) {
|
|
3619
3657
|
const session = this.sessions.get(sessionId);
|
|
3620
3658
|
if (!session) {
|
|
3621
3659
|
logger7.warn({ sessionId }, "Attempted to end non-existent session");
|
|
@@ -3624,7 +3662,7 @@ var AgentSessionManager = class {
|
|
|
3624
3662
|
const events = session.getEvents();
|
|
3625
3663
|
const summary = session.getSummary();
|
|
3626
3664
|
logger7.info({ sessionId, summary }, "AgentSession ended");
|
|
3627
|
-
session.cleanup();
|
|
3665
|
+
await session.cleanup();
|
|
3628
3666
|
this.sessions.delete(sessionId);
|
|
3629
3667
|
return events;
|
|
3630
3668
|
}
|
|
@@ -4449,46 +4487,6 @@ function errorOp(message, subAgentId, severity = "error", code) {
|
|
|
4449
4487
|
function generateToolId() {
|
|
4450
4488
|
return `tool_${generateId(8)}`;
|
|
4451
4489
|
}
|
|
4452
|
-
var logger11 = getLogger("DataComponentSchema");
|
|
4453
|
-
function jsonSchemaToZod(jsonSchema) {
|
|
4454
|
-
if (!jsonSchema || typeof jsonSchema !== "object") {
|
|
4455
|
-
logger11.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
|
|
4456
|
-
return z.string();
|
|
4457
|
-
}
|
|
4458
|
-
switch (jsonSchema.type) {
|
|
4459
|
-
case "object":
|
|
4460
|
-
if (jsonSchema.properties) {
|
|
4461
|
-
const shape = {};
|
|
4462
|
-
for (const [key, prop] of Object.entries(jsonSchema.properties)) {
|
|
4463
|
-
shape[key] = jsonSchemaToZod(prop);
|
|
4464
|
-
}
|
|
4465
|
-
return z.object(shape);
|
|
4466
|
-
}
|
|
4467
|
-
return z.record(z.string(), z.unknown());
|
|
4468
|
-
case "array": {
|
|
4469
|
-
const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z.unknown();
|
|
4470
|
-
return z.array(itemSchema);
|
|
4471
|
-
}
|
|
4472
|
-
case "string":
|
|
4473
|
-
return z.string();
|
|
4474
|
-
case "number":
|
|
4475
|
-
case "integer":
|
|
4476
|
-
return z.number();
|
|
4477
|
-
case "boolean":
|
|
4478
|
-
return z.boolean();
|
|
4479
|
-
case "null":
|
|
4480
|
-
return z.null();
|
|
4481
|
-
default:
|
|
4482
|
-
logger11.warn(
|
|
4483
|
-
{
|
|
4484
|
-
unsupportedType: jsonSchema.type,
|
|
4485
|
-
schema: jsonSchema
|
|
4486
|
-
},
|
|
4487
|
-
"Unsupported JSON schema type, using unknown validation"
|
|
4488
|
-
);
|
|
4489
|
-
return z.unknown();
|
|
4490
|
-
}
|
|
4491
|
-
}
|
|
4492
4490
|
var SchemaProcessor = class _SchemaProcessor {
|
|
4493
4491
|
static logger = getLogger("SchemaProcessor");
|
|
4494
4492
|
/**
|
|
@@ -4845,7 +4843,7 @@ function parseEmbeddedJson(data) {
|
|
|
4845
4843
|
}
|
|
4846
4844
|
|
|
4847
4845
|
// src/a2a/client.ts
|
|
4848
|
-
var
|
|
4846
|
+
var logger11 = getLogger("a2aClient");
|
|
4849
4847
|
var DEFAULT_BACKOFF = {
|
|
4850
4848
|
initialInterval: 500,
|
|
4851
4849
|
maxInterval: 6e4,
|
|
@@ -4856,13 +4854,14 @@ var DEFAULT_BACKOFF = {
|
|
|
4856
4854
|
var DEFAULT_RETRY_STATUS_CODES = ["429", "500", "502", "503", "504"];
|
|
4857
4855
|
var PermanentError = class _PermanentError extends Error {
|
|
4858
4856
|
cause;
|
|
4857
|
+
type;
|
|
4859
4858
|
constructor(message, options) {
|
|
4860
4859
|
let msg = message;
|
|
4861
4860
|
if (options?.cause) {
|
|
4862
4861
|
msg += `: ${options.cause}`;
|
|
4863
4862
|
}
|
|
4864
4863
|
super(msg, options);
|
|
4865
|
-
this.name = "PermanentError";
|
|
4864
|
+
this.name = options?.type || "PermanentError";
|
|
4866
4865
|
if (typeof this.cause === "undefined") {
|
|
4867
4866
|
this.cause = options?.cause;
|
|
4868
4867
|
}
|
|
@@ -5051,7 +5050,7 @@ var A2AClient = class {
|
|
|
5051
5050
|
try {
|
|
5052
5051
|
const res = await fn();
|
|
5053
5052
|
if (attempt > 0) {
|
|
5054
|
-
|
|
5053
|
+
logger11.info(
|
|
5055
5054
|
{
|
|
5056
5055
|
attempts: attempt + 1,
|
|
5057
5056
|
elapsedTime: Date.now() - start
|
|
@@ -5066,7 +5065,7 @@ var A2AClient = class {
|
|
|
5066
5065
|
}
|
|
5067
5066
|
const elapsed = Date.now() - start;
|
|
5068
5067
|
if (elapsed > maxElapsedTime) {
|
|
5069
|
-
|
|
5068
|
+
logger11.warn(
|
|
5070
5069
|
{
|
|
5071
5070
|
attempts: attempt + 1,
|
|
5072
5071
|
elapsedTime: elapsed,
|
|
@@ -5087,7 +5086,7 @@ var A2AClient = class {
|
|
|
5087
5086
|
retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
|
|
5088
5087
|
}
|
|
5089
5088
|
const delayMs = Math.min(retryInterval, maxInterval);
|
|
5090
|
-
|
|
5089
|
+
logger11.info(
|
|
5091
5090
|
{
|
|
5092
5091
|
attempt: attempt + 1,
|
|
5093
5092
|
delayMs,
|
|
@@ -5171,8 +5170,14 @@ var A2AClient = class {
|
|
|
5171
5170
|
}
|
|
5172
5171
|
}
|
|
5173
5172
|
const rpcResponse = await httpResponse.json();
|
|
5173
|
+
if (rpcResponse.error?.data?.type === "connection_refused") {
|
|
5174
|
+
throw new PermanentError(rpcResponse.error.message, {
|
|
5175
|
+
cause: new Error(rpcResponse.error.message),
|
|
5176
|
+
type: "connection_refused"
|
|
5177
|
+
});
|
|
5178
|
+
}
|
|
5174
5179
|
if (rpcResponse.id !== requestId2) {
|
|
5175
|
-
|
|
5180
|
+
logger11.warn(
|
|
5176
5181
|
{
|
|
5177
5182
|
method,
|
|
5178
5183
|
expectedId: requestId2,
|
|
@@ -5369,7 +5374,7 @@ var A2AClient = class {
|
|
|
5369
5374
|
try {
|
|
5370
5375
|
while (true) {
|
|
5371
5376
|
const { done, value } = await reader.read();
|
|
5372
|
-
|
|
5377
|
+
logger11.info({ done, value }, "parseA2ASseStream");
|
|
5373
5378
|
if (done) {
|
|
5374
5379
|
if (eventDataBuffer.trim()) {
|
|
5375
5380
|
const result = this._processSseEventData(
|
|
@@ -5456,7 +5461,7 @@ var A2AClient = class {
|
|
|
5456
5461
|
};
|
|
5457
5462
|
|
|
5458
5463
|
// src/agents/relationTools.ts
|
|
5459
|
-
var
|
|
5464
|
+
var logger12 = getLogger("relationships Tools");
|
|
5460
5465
|
var A2A_RETRY_STATUS_CODES = ["429", "500", "502", "503", "504"];
|
|
5461
5466
|
var generateTransferToolDescription = (config) => {
|
|
5462
5467
|
let toolsSection = "";
|
|
@@ -5558,7 +5563,7 @@ var createTransferToAgentTool = ({
|
|
|
5558
5563
|
const toolDescription = generateTransferToolDescription(transferConfig);
|
|
5559
5564
|
return tool({
|
|
5560
5565
|
description: toolDescription,
|
|
5561
|
-
inputSchema:
|
|
5566
|
+
inputSchema: z.object({}),
|
|
5562
5567
|
execute: async () => {
|
|
5563
5568
|
const activeSpan = trace.getActiveSpan();
|
|
5564
5569
|
if (activeSpan) {
|
|
@@ -5567,7 +5572,7 @@ var createTransferToAgentTool = ({
|
|
|
5567
5572
|
[SPAN_KEYS.TRANSFER_TO_SUB_AGENT_ID]: transferConfig.id ?? "unknown"
|
|
5568
5573
|
});
|
|
5569
5574
|
}
|
|
5570
|
-
|
|
5575
|
+
logger12.info(
|
|
5571
5576
|
{
|
|
5572
5577
|
transferTo: transferConfig.id ?? "unknown",
|
|
5573
5578
|
fromSubAgent: callingAgentId
|
|
@@ -5588,7 +5593,7 @@ var createTransferToAgentTool = ({
|
|
|
5588
5593
|
fromSubAgentId: callingAgentId
|
|
5589
5594
|
// Include the calling agent ID for tracking
|
|
5590
5595
|
};
|
|
5591
|
-
|
|
5596
|
+
logger12.info(
|
|
5592
5597
|
{
|
|
5593
5598
|
transferResult,
|
|
5594
5599
|
transferResultKeys: Object.keys(transferResult)
|
|
@@ -5613,7 +5618,7 @@ function createDelegateToAgentTool({
|
|
|
5613
5618
|
}) {
|
|
5614
5619
|
return tool({
|
|
5615
5620
|
description: generateDelegateToolDescription(delegateConfig),
|
|
5616
|
-
inputSchema:
|
|
5621
|
+
inputSchema: z.object({ message: z.string() }),
|
|
5617
5622
|
execute: async (input, context) => {
|
|
5618
5623
|
const delegationId = `del_${generateId()}`;
|
|
5619
5624
|
const activeSpan = trace.getActiveSpan();
|
|
@@ -5735,7 +5740,7 @@ function createDelegateToAgentTool({
|
|
|
5735
5740
|
...isInternal ? { fromSubAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
|
|
5736
5741
|
}
|
|
5737
5742
|
};
|
|
5738
|
-
|
|
5743
|
+
logger12.info({ messageToSend }, "messageToSend");
|
|
5739
5744
|
await createMessage(dbClient_default)({
|
|
5740
5745
|
id: generateId(),
|
|
5741
5746
|
tenantId,
|
|
@@ -5797,7 +5802,7 @@ function createDelegateToAgentTool({
|
|
|
5797
5802
|
}
|
|
5798
5803
|
|
|
5799
5804
|
// src/agents/SystemPromptBuilder.ts
|
|
5800
|
-
var
|
|
5805
|
+
var logger13 = getLogger("SystemPromptBuilder");
|
|
5801
5806
|
var SystemPromptBuilder = class {
|
|
5802
5807
|
constructor(version, versionConfig) {
|
|
5803
5808
|
this.version = version;
|
|
@@ -5813,12 +5818,12 @@ var SystemPromptBuilder = class {
|
|
|
5813
5818
|
this.templates.set(name, content);
|
|
5814
5819
|
}
|
|
5815
5820
|
this.loaded = true;
|
|
5816
|
-
|
|
5821
|
+
logger13.debug(
|
|
5817
5822
|
{ templateCount: this.templates.size, version: this.version },
|
|
5818
5823
|
`Loaded ${this.templates.size} templates for version ${this.version}`
|
|
5819
5824
|
);
|
|
5820
5825
|
} catch (error) {
|
|
5821
|
-
|
|
5826
|
+
logger13.error({ error }, `Failed to load templates for version ${this.version}`);
|
|
5822
5827
|
throw new Error(`Template loading failed: ${error}`);
|
|
5823
5828
|
}
|
|
5824
5829
|
}
|
|
@@ -6058,7 +6063,14 @@ var Phase1Config = class _Phase1Config {
|
|
|
6058
6063
|
throw new Error("System prompt template not loaded");
|
|
6059
6064
|
}
|
|
6060
6065
|
let systemPrompt = systemPromptTemplate;
|
|
6061
|
-
|
|
6066
|
+
if (config.corePrompt && config.corePrompt.trim()) {
|
|
6067
|
+
systemPrompt = systemPrompt.replace("{{CORE_INSTRUCTIONS}}", config.corePrompt);
|
|
6068
|
+
} else {
|
|
6069
|
+
systemPrompt = systemPrompt.replace(
|
|
6070
|
+
/<core_instructions>\s*\{\{CORE_INSTRUCTIONS\}\}\s*<\/core_instructions>/g,
|
|
6071
|
+
""
|
|
6072
|
+
);
|
|
6073
|
+
}
|
|
6062
6074
|
const agentContextSection = this.generateAgentContextSection(config.prompt);
|
|
6063
6075
|
systemPrompt = systemPrompt.replace("{{AGENT_CONTEXT_SECTION}}", agentContextSection);
|
|
6064
6076
|
const toolData = this.isToolDataArray(config.tools) ? config.tools : _Phase1Config.convertMcpToolsToToolData(config.tools);
|
|
@@ -6088,7 +6100,7 @@ var Phase1Config = class _Phase1Config {
|
|
|
6088
6100
|
return systemPrompt;
|
|
6089
6101
|
}
|
|
6090
6102
|
generateAgentContextSection(prompt) {
|
|
6091
|
-
if (!prompt) {
|
|
6103
|
+
if (!prompt || prompt.trim() === "") {
|
|
6092
6104
|
return "";
|
|
6093
6105
|
}
|
|
6094
6106
|
return `
|
|
@@ -6225,6 +6237,8 @@ THE details PROPERTY MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE
|
|
|
6225
6237
|
\u274C NEVER: [?text ~ contains(@, 'word')] (~ with @ operator)
|
|
6226
6238
|
\u274C NEVER: contains(@, 'text') (@ operator usage)
|
|
6227
6239
|
\u274C NEVER: [?field=="value"] (double quotes in filters)
|
|
6240
|
+
\u274C NEVER: [?field=='value'] (escaped quotes in filters)
|
|
6241
|
+
\u274C NEVER: [?field=='"'"'value'"'"'] (nightmare quote mixing)
|
|
6228
6242
|
\u274C NEVER: result.items[?type=='doc'][?status=='active'] (chained filters)
|
|
6229
6243
|
|
|
6230
6244
|
\u2705 CORRECT JMESPATH SYNTAX:
|
|
@@ -6236,6 +6250,11 @@ THE details PROPERTY MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE
|
|
|
6236
6250
|
\u2705 [?contains(text, 'Founder')] (contains haystack, needle format)
|
|
6237
6251
|
\u2705 source.content[?contains(text, 'Founder')].text (correct filter usage)
|
|
6238
6252
|
|
|
6253
|
+
\u{1F6A8} MANDATORY QUOTE PATTERN - FOLLOW EXACTLY:
|
|
6254
|
+
- ALWAYS: base="path[?field=='value']" (double quotes outside, single inside)
|
|
6255
|
+
- This is the ONLY allowed pattern - any other pattern WILL FAIL
|
|
6256
|
+
- NEVER escape quotes, NEVER mix quote types, NEVER use complex quoting
|
|
6257
|
+
|
|
6239
6258
|
\u{1F6A8} CRITICAL: EXAMINE TOOL RESULTS BEFORE CREATING SELECTORS! \u{1F6A8}
|
|
6240
6259
|
|
|
6241
6260
|
STEP 1: INSPECT THE ACTUAL DATA FIRST
|
|
@@ -6274,7 +6293,7 @@ Only use artifact:ref when you need to cite the SAME artifact again for a differ
|
|
|
6274
6293
|
Format: <artifact:ref id="artifact-id" tool="tool_call_id" />
|
|
6275
6294
|
|
|
6276
6295
|
EXAMPLE TEXT RESPONSE:
|
|
6277
|
-
"I found the authentication documentation. <artifact:create id='auth-doc-1' tool='call_xyz789' type='APIDoc' base=
|
|
6296
|
+
"I found the authentication documentation. <artifact:create id='auth-doc-1' tool='call_xyz789' type='APIDoc' base="result.documents[?type=='auth']" details='{"title":"metadata.title","endpoint":"api.endpoint","description":"content.description","parameters":"spec.parameters","examples":"examples.sample_code"}' /> The documentation explains OAuth 2.0 implementation in detail.
|
|
6278
6297
|
|
|
6279
6298
|
The process involves three main steps: registration, token exchange, and API calls. As mentioned in the authentication documentation <artifact:ref id='auth-doc-1' tool='call_xyz789' />, you'll need to register your application first."
|
|
6280
6299
|
|
|
@@ -6772,7 +6791,7 @@ ${componentDescriptions}`;
|
|
|
6772
6791
|
dataComponentXml = dataComponentXml.replace("{{COMPONENT_NAME}}", dataComponent.name);
|
|
6773
6792
|
dataComponentXml = dataComponentXml.replace(
|
|
6774
6793
|
"{{COMPONENT_DESCRIPTION}}",
|
|
6775
|
-
dataComponent.description
|
|
6794
|
+
dataComponent.description || ""
|
|
6776
6795
|
);
|
|
6777
6796
|
dataComponentXml = dataComponentXml.replace(
|
|
6778
6797
|
"{{COMPONENT_PROPS_SCHEMA}}",
|
|
@@ -6868,7 +6887,14 @@ ${artifact_retrieval_guidance_default}
|
|
|
6868
6887
|
artifactComponents
|
|
6869
6888
|
);
|
|
6870
6889
|
let phase2Prompt = system_prompt_default2;
|
|
6871
|
-
|
|
6890
|
+
if (corePrompt && corePrompt.trim()) {
|
|
6891
|
+
phase2Prompt = phase2Prompt.replace("{{CORE_INSTRUCTIONS}}", corePrompt);
|
|
6892
|
+
} else {
|
|
6893
|
+
phase2Prompt = phase2Prompt.replace(
|
|
6894
|
+
/<core_instructions>\s*\{\{CORE_INSTRUCTIONS\}\}\s*<\/core_instructions>/g,
|
|
6895
|
+
""
|
|
6896
|
+
);
|
|
6897
|
+
}
|
|
6872
6898
|
phase2Prompt = phase2Prompt.replace("{{DATA_COMPONENTS_SECTION}}", dataComponentsSection);
|
|
6873
6899
|
phase2Prompt = phase2Prompt.replace("{{ARTIFACTS_SECTION}}", artifactsSection);
|
|
6874
6900
|
phase2Prompt = phase2Prompt.replace("{{ARTIFACT_GUIDANCE_SECTION}}", artifactGuidance);
|
|
@@ -6887,7 +6913,7 @@ function hasToolCallWithPrefix(prefix) {
|
|
|
6887
6913
|
return false;
|
|
6888
6914
|
};
|
|
6889
6915
|
}
|
|
6890
|
-
var
|
|
6916
|
+
var logger14 = getLogger("Agent");
|
|
6891
6917
|
function validateModel(modelString, modelType) {
|
|
6892
6918
|
if (!modelString?.trim()) {
|
|
6893
6919
|
throw new Error(
|
|
@@ -6993,6 +7019,32 @@ var Agent = class {
|
|
|
6993
7019
|
}
|
|
6994
7020
|
return sanitizedTools;
|
|
6995
7021
|
}
|
|
7022
|
+
#createRelationToolName(prefix, targetId) {
|
|
7023
|
+
return `${prefix}_to_${targetId.toLowerCase().replace(/\s+/g, "_")}`;
|
|
7024
|
+
}
|
|
7025
|
+
#getRelationshipIdForTool(toolName, toolType) {
|
|
7026
|
+
if (toolType === "mcp") {
|
|
7027
|
+
const matchingTool = this.config.tools?.find((tool3) => {
|
|
7028
|
+
if (tool3.config?.type !== "mcp") {
|
|
7029
|
+
return false;
|
|
7030
|
+
}
|
|
7031
|
+
if (tool3.availableTools?.some((available) => available.name === toolName)) {
|
|
7032
|
+
return true;
|
|
7033
|
+
}
|
|
7034
|
+
if (tool3.config.mcp.activeTools?.includes(toolName)) {
|
|
7035
|
+
return true;
|
|
7036
|
+
}
|
|
7037
|
+
return tool3.name === toolName;
|
|
7038
|
+
});
|
|
7039
|
+
return matchingTool?.relationshipId;
|
|
7040
|
+
}
|
|
7041
|
+
if (toolType === "delegation") {
|
|
7042
|
+
const relation = this.config.delegateRelations.find(
|
|
7043
|
+
(relation2) => this.#createRelationToolName("delegate", relation2.config.id) === toolName
|
|
7044
|
+
);
|
|
7045
|
+
return relation?.config.relationId;
|
|
7046
|
+
}
|
|
7047
|
+
}
|
|
6996
7048
|
/**
|
|
6997
7049
|
* Get the primary model settings for text generation and thinking
|
|
6998
7050
|
* Requires model to be configured at project level
|
|
@@ -7061,10 +7113,11 @@ var Agent = class {
|
|
|
7061
7113
|
/**
|
|
7062
7114
|
* Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
|
|
7063
7115
|
*/
|
|
7064
|
-
wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType,
|
|
7116
|
+
wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, options) {
|
|
7065
7117
|
if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
|
|
7066
7118
|
return toolDefinition;
|
|
7067
7119
|
}
|
|
7120
|
+
const relationshipId = this.#getRelationshipIdForTool(toolName, toolType);
|
|
7068
7121
|
const originalExecute = toolDefinition.execute;
|
|
7069
7122
|
return {
|
|
7070
7123
|
...toolDefinition,
|
|
@@ -7133,7 +7186,7 @@ var Agent = class {
|
|
|
7133
7186
|
};
|
|
7134
7187
|
await createMessage(dbClient_default)(messagePayload);
|
|
7135
7188
|
} catch (error) {
|
|
7136
|
-
|
|
7189
|
+
logger14.warn(
|
|
7137
7190
|
{ error, toolName, toolCallId, conversationId: toolResultConversationId },
|
|
7138
7191
|
"Failed to store tool result in conversation history"
|
|
7139
7192
|
);
|
|
@@ -7171,10 +7224,9 @@ var Agent = class {
|
|
|
7171
7224
|
}
|
|
7172
7225
|
getRelationTools(runtimeContext, sessionId) {
|
|
7173
7226
|
const { transferRelations = [], delegateRelations = [] } = this.config;
|
|
7174
|
-
const createToolName = (prefix, subAgentId) => `${prefix}_to_${subAgentId.toLowerCase().replace(/\s+/g, "_")}`;
|
|
7175
7227
|
return Object.fromEntries([
|
|
7176
7228
|
...transferRelations.map((agentConfig) => {
|
|
7177
|
-
const toolName =
|
|
7229
|
+
const toolName = this.#createRelationToolName("transfer", agentConfig.id);
|
|
7178
7230
|
return [
|
|
7179
7231
|
toolName,
|
|
7180
7232
|
this.wrapToolWithStreaming(
|
|
@@ -7191,7 +7243,7 @@ var Agent = class {
|
|
|
7191
7243
|
];
|
|
7192
7244
|
}),
|
|
7193
7245
|
...delegateRelations.map((relation) => {
|
|
7194
|
-
const toolName =
|
|
7246
|
+
const toolName = this.#createRelationToolName("delegate", relation.config.id);
|
|
7195
7247
|
return [
|
|
7196
7248
|
toolName,
|
|
7197
7249
|
this.wrapToolWithStreaming(
|
|
@@ -7228,8 +7280,7 @@ var Agent = class {
|
|
|
7228
7280
|
const tools = await Promise.all(mcpTools.map((tool3) => this.getMcpTool(tool3)) || []) || [];
|
|
7229
7281
|
if (!sessionId) {
|
|
7230
7282
|
const wrappedTools2 = {};
|
|
7231
|
-
for (const
|
|
7232
|
-
const relationshipId = mcpTools[index]?.relationshipId;
|
|
7283
|
+
for (const toolSet of tools) {
|
|
7233
7284
|
for (const [toolName, toolDef] of Object.entries(toolSet.tools)) {
|
|
7234
7285
|
const needsApproval = toolSet.toolPolicies?.[toolName]?.needsApproval || false;
|
|
7235
7286
|
const enhancedTool = {
|
|
@@ -7241,7 +7292,6 @@ var Agent = class {
|
|
|
7241
7292
|
enhancedTool,
|
|
7242
7293
|
streamRequestId,
|
|
7243
7294
|
"mcp",
|
|
7244
|
-
relationshipId,
|
|
7245
7295
|
{ needsApproval }
|
|
7246
7296
|
);
|
|
7247
7297
|
}
|
|
@@ -7249,15 +7299,14 @@ var Agent = class {
|
|
|
7249
7299
|
return wrappedTools2;
|
|
7250
7300
|
}
|
|
7251
7301
|
const wrappedTools = {};
|
|
7252
|
-
for (const
|
|
7253
|
-
const relationshipId = mcpTools[index]?.relationshipId;
|
|
7302
|
+
for (const toolResult of tools) {
|
|
7254
7303
|
for (const [toolName, originalTool] of Object.entries(toolResult.tools)) {
|
|
7255
7304
|
if (!isValidTool(originalTool)) {
|
|
7256
|
-
|
|
7305
|
+
logger14.error({ toolName }, "Invalid MCP tool structure - missing required properties");
|
|
7257
7306
|
continue;
|
|
7258
7307
|
}
|
|
7259
7308
|
const needsApproval = toolResult.toolPolicies?.[toolName]?.needsApproval || false;
|
|
7260
|
-
|
|
7309
|
+
logger14.debug(
|
|
7261
7310
|
{
|
|
7262
7311
|
toolName,
|
|
7263
7312
|
toolPolicies: toolResult.toolPolicies,
|
|
@@ -7271,7 +7320,7 @@ var Agent = class {
|
|
|
7271
7320
|
inputSchema: originalTool.inputSchema,
|
|
7272
7321
|
execute: async (args, { toolCallId }) => {
|
|
7273
7322
|
if (needsApproval) {
|
|
7274
|
-
|
|
7323
|
+
logger14.info(
|
|
7275
7324
|
{ toolName, toolCallId, args },
|
|
7276
7325
|
"Tool requires approval - waiting for user response"
|
|
7277
7326
|
);
|
|
@@ -7317,7 +7366,7 @@ var Agent = class {
|
|
|
7317
7366
|
}
|
|
7318
7367
|
},
|
|
7319
7368
|
(denialSpan) => {
|
|
7320
|
-
|
|
7369
|
+
logger14.info(
|
|
7321
7370
|
{ toolName, toolCallId, reason: approvalResult.reason },
|
|
7322
7371
|
"Tool execution denied by user"
|
|
7323
7372
|
);
|
|
@@ -7338,18 +7387,18 @@ var Agent = class {
|
|
|
7338
7387
|
}
|
|
7339
7388
|
},
|
|
7340
7389
|
(approvedSpan) => {
|
|
7341
|
-
|
|
7390
|
+
logger14.info({ toolName, toolCallId }, "Tool approved, continuing with execution");
|
|
7342
7391
|
approvedSpan.setStatus({ code: SpanStatusCode.OK });
|
|
7343
7392
|
approvedSpan.end();
|
|
7344
7393
|
}
|
|
7345
7394
|
);
|
|
7346
7395
|
}
|
|
7347
|
-
|
|
7396
|
+
logger14.debug({ toolName, toolCallId }, "MCP Tool Called");
|
|
7348
7397
|
try {
|
|
7349
7398
|
const rawResult = await originalTool.execute(args, { toolCallId });
|
|
7350
7399
|
if (rawResult && typeof rawResult === "object" && rawResult.isError) {
|
|
7351
7400
|
const errorMessage = rawResult.content?.[0]?.text || "MCP tool returned an error";
|
|
7352
|
-
|
|
7401
|
+
logger14.error(
|
|
7353
7402
|
{ toolName, toolCallId, errorMessage, rawResult },
|
|
7354
7403
|
"MCP tool returned error status"
|
|
7355
7404
|
);
|
|
@@ -7361,6 +7410,7 @@ var Agent = class {
|
|
|
7361
7410
|
timestamp: Date.now()
|
|
7362
7411
|
});
|
|
7363
7412
|
if (streamRequestId) {
|
|
7413
|
+
const relationshipId = this.#getRelationshipIdForTool(toolName, "mcp");
|
|
7364
7414
|
agentSessionManager.recordEvent(streamRequestId, "error", this.config.id, {
|
|
7365
7415
|
message: `MCP tool "${toolName}" failed: ${errorMessage}`,
|
|
7366
7416
|
code: "mcp_tool_error",
|
|
@@ -7399,7 +7449,7 @@ var Agent = class {
|
|
|
7399
7449
|
});
|
|
7400
7450
|
return { result: enhancedResult, toolCallId };
|
|
7401
7451
|
} catch (error) {
|
|
7402
|
-
|
|
7452
|
+
logger14.error({ toolName, toolCallId, error }, "MCP tool execution failed");
|
|
7403
7453
|
throw error;
|
|
7404
7454
|
}
|
|
7405
7455
|
}
|
|
@@ -7409,7 +7459,6 @@ var Agent = class {
|
|
|
7409
7459
|
sessionWrappedTool,
|
|
7410
7460
|
streamRequestId,
|
|
7411
7461
|
"mcp",
|
|
7412
|
-
relationshipId,
|
|
7413
7462
|
{ needsApproval }
|
|
7414
7463
|
);
|
|
7415
7464
|
}
|
|
@@ -7454,7 +7503,51 @@ var Agent = class {
|
|
|
7454
7503
|
const selectedTools = toolRelation?.selectedTools || void 0;
|
|
7455
7504
|
const toolPolicies = toolRelation?.toolPolicies || {};
|
|
7456
7505
|
let serverConfig;
|
|
7457
|
-
|
|
7506
|
+
const isUserScoped = tool3.credentialScope === "user";
|
|
7507
|
+
const userId = this.config.userId;
|
|
7508
|
+
if (isUserScoped && userId && this.credentialStuffer) {
|
|
7509
|
+
const userCredentialReference = await getUserScopedCredentialReference(dbClient_default)({
|
|
7510
|
+
scopes: {
|
|
7511
|
+
tenantId: this.config.tenantId,
|
|
7512
|
+
projectId: this.config.projectId
|
|
7513
|
+
},
|
|
7514
|
+
toolId: tool3.id,
|
|
7515
|
+
userId
|
|
7516
|
+
});
|
|
7517
|
+
if (userCredentialReference) {
|
|
7518
|
+
const storeReference = {
|
|
7519
|
+
credentialStoreId: userCredentialReference.credentialStoreId,
|
|
7520
|
+
retrievalParams: userCredentialReference.retrievalParams || {}
|
|
7521
|
+
};
|
|
7522
|
+
serverConfig = await this.credentialStuffer.buildMcpServerConfig(
|
|
7523
|
+
{
|
|
7524
|
+
tenantId: this.config.tenantId,
|
|
7525
|
+
projectId: this.config.projectId,
|
|
7526
|
+
contextConfigId: this.config.contextConfigId || void 0,
|
|
7527
|
+
conversationId: this.conversationId || void 0
|
|
7528
|
+
},
|
|
7529
|
+
this.convertToMCPToolConfig(tool3, agentToolRelationHeaders),
|
|
7530
|
+
storeReference,
|
|
7531
|
+
selectedTools
|
|
7532
|
+
);
|
|
7533
|
+
} else {
|
|
7534
|
+
logger14.warn(
|
|
7535
|
+
{ toolId: tool3.id, userId },
|
|
7536
|
+
"User-scoped tool has no credential connected for this user"
|
|
7537
|
+
);
|
|
7538
|
+
serverConfig = await this.credentialStuffer.buildMcpServerConfig(
|
|
7539
|
+
{
|
|
7540
|
+
tenantId: this.config.tenantId,
|
|
7541
|
+
projectId: this.config.projectId,
|
|
7542
|
+
contextConfigId: this.config.contextConfigId || void 0,
|
|
7543
|
+
conversationId: this.conversationId || void 0
|
|
7544
|
+
},
|
|
7545
|
+
this.convertToMCPToolConfig(tool3, agentToolRelationHeaders),
|
|
7546
|
+
void 0,
|
|
7547
|
+
selectedTools
|
|
7548
|
+
);
|
|
7549
|
+
}
|
|
7550
|
+
} else if (credentialReferenceId && this.credentialStuffer) {
|
|
7458
7551
|
const credentialReference = await getCredentialReference(dbClient_default)({
|
|
7459
7552
|
scopes: {
|
|
7460
7553
|
tenantId: this.config.tenantId,
|
|
@@ -7504,7 +7597,7 @@ var Agent = class {
|
|
|
7504
7597
|
headers: agentToolRelationHeaders
|
|
7505
7598
|
};
|
|
7506
7599
|
}
|
|
7507
|
-
|
|
7600
|
+
logger14.info(
|
|
7508
7601
|
{
|
|
7509
7602
|
toolName: tool3.name,
|
|
7510
7603
|
credentialReferenceId,
|
|
@@ -7529,7 +7622,7 @@ var Agent = class {
|
|
|
7529
7622
|
this.mcpClientCache.set(cacheKey, client);
|
|
7530
7623
|
} catch (error) {
|
|
7531
7624
|
this.mcpConnectionLocks.delete(cacheKey);
|
|
7532
|
-
|
|
7625
|
+
logger14.error(
|
|
7533
7626
|
{
|
|
7534
7627
|
toolName: tool3.name,
|
|
7535
7628
|
subAgentId: this.config.id,
|
|
@@ -7594,7 +7687,7 @@ var Agent = class {
|
|
|
7594
7687
|
await client.connect();
|
|
7595
7688
|
return client;
|
|
7596
7689
|
} catch (error) {
|
|
7597
|
-
|
|
7690
|
+
logger14.error(
|
|
7598
7691
|
{
|
|
7599
7692
|
toolName: tool3.name,
|
|
7600
7693
|
subAgentId: this.config.id,
|
|
@@ -7631,12 +7724,12 @@ var Agent = class {
|
|
|
7631
7724
|
if (functionToolsData.length === 0) {
|
|
7632
7725
|
return functionTools;
|
|
7633
7726
|
}
|
|
7634
|
-
const { SandboxExecutorFactory } = await import('./SandboxExecutorFactory-
|
|
7727
|
+
const { SandboxExecutorFactory } = await import('./SandboxExecutorFactory-2N27SE3B.js');
|
|
7635
7728
|
const sandboxExecutor = SandboxExecutorFactory.getInstance();
|
|
7636
7729
|
for (const functionToolDef of functionToolsData) {
|
|
7637
7730
|
const functionId = functionToolDef.functionId;
|
|
7638
7731
|
if (!functionId) {
|
|
7639
|
-
|
|
7732
|
+
logger14.warn(
|
|
7640
7733
|
{ functionToolId: functionToolDef.id },
|
|
7641
7734
|
"Function tool missing functionId reference"
|
|
7642
7735
|
);
|
|
@@ -7650,7 +7743,7 @@ var Agent = class {
|
|
|
7650
7743
|
}
|
|
7651
7744
|
});
|
|
7652
7745
|
if (!functionData) {
|
|
7653
|
-
|
|
7746
|
+
logger14.warn(
|
|
7654
7747
|
{ functionId, functionToolId: functionToolDef.id },
|
|
7655
7748
|
"Function not found in functions table"
|
|
7656
7749
|
);
|
|
@@ -7661,7 +7754,7 @@ var Agent = class {
|
|
|
7661
7754
|
description: functionToolDef.description || functionToolDef.name,
|
|
7662
7755
|
inputSchema: zodSchema,
|
|
7663
7756
|
execute: async (args, { toolCallId }) => {
|
|
7664
|
-
|
|
7757
|
+
logger14.debug(
|
|
7665
7758
|
{ toolName: functionToolDef.name, toolCallId, args },
|
|
7666
7759
|
"Function Tool Called"
|
|
7667
7760
|
);
|
|
@@ -7688,7 +7781,7 @@ var Agent = class {
|
|
|
7688
7781
|
});
|
|
7689
7782
|
return { result, toolCallId };
|
|
7690
7783
|
} catch (error) {
|
|
7691
|
-
|
|
7784
|
+
logger14.error(
|
|
7692
7785
|
{
|
|
7693
7786
|
toolName: functionToolDef.name,
|
|
7694
7787
|
toolCallId,
|
|
@@ -7708,7 +7801,7 @@ var Agent = class {
|
|
|
7708
7801
|
);
|
|
7709
7802
|
}
|
|
7710
7803
|
} catch (error) {
|
|
7711
|
-
|
|
7804
|
+
logger14.error({ error }, "Failed to load function tools from database");
|
|
7712
7805
|
}
|
|
7713
7806
|
return functionTools;
|
|
7714
7807
|
}
|
|
@@ -7718,7 +7811,7 @@ var Agent = class {
|
|
|
7718
7811
|
async getResolvedContext(conversationId, headers2) {
|
|
7719
7812
|
try {
|
|
7720
7813
|
if (!this.config.contextConfigId) {
|
|
7721
|
-
|
|
7814
|
+
logger14.debug({ agentId: this.config.agentId }, "No context config found for agent");
|
|
7722
7815
|
return null;
|
|
7723
7816
|
}
|
|
7724
7817
|
const contextConfig = await getContextConfigById(dbClient_default)({
|
|
@@ -7730,7 +7823,7 @@ var Agent = class {
|
|
|
7730
7823
|
id: this.config.contextConfigId
|
|
7731
7824
|
});
|
|
7732
7825
|
if (!contextConfig) {
|
|
7733
|
-
|
|
7826
|
+
logger14.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
|
|
7734
7827
|
return null;
|
|
7735
7828
|
}
|
|
7736
7829
|
if (!this.contextResolver) {
|
|
@@ -7746,7 +7839,7 @@ var Agent = class {
|
|
|
7746
7839
|
...result.resolvedContext,
|
|
7747
7840
|
$env: process.env
|
|
7748
7841
|
};
|
|
7749
|
-
|
|
7842
|
+
logger14.debug(
|
|
7750
7843
|
{
|
|
7751
7844
|
conversationId,
|
|
7752
7845
|
contextConfigId: contextConfig.id,
|
|
@@ -7760,7 +7853,7 @@ var Agent = class {
|
|
|
7760
7853
|
);
|
|
7761
7854
|
return contextWithBuiltins;
|
|
7762
7855
|
} catch (error) {
|
|
7763
|
-
|
|
7856
|
+
logger14.error(
|
|
7764
7857
|
{
|
|
7765
7858
|
conversationId,
|
|
7766
7859
|
error: error instanceof Error ? error.message : "Unknown error"
|
|
@@ -7784,7 +7877,7 @@ var Agent = class {
|
|
|
7784
7877
|
});
|
|
7785
7878
|
return agentDefinition?.prompt || void 0;
|
|
7786
7879
|
} catch (error) {
|
|
7787
|
-
|
|
7880
|
+
logger14.warn(
|
|
7788
7881
|
{
|
|
7789
7882
|
agentId: this.config.agentId,
|
|
7790
7883
|
error: error instanceof Error ? error.message : "Unknown error"
|
|
@@ -7813,7 +7906,7 @@ var Agent = class {
|
|
|
7813
7906
|
(subAgent) => "artifactComponents" in subAgent && subAgent.artifactComponents && subAgent.artifactComponents.length > 0
|
|
7814
7907
|
);
|
|
7815
7908
|
} catch (error) {
|
|
7816
|
-
|
|
7909
|
+
logger14.warn(
|
|
7817
7910
|
{
|
|
7818
7911
|
agentId: this.config.agentId,
|
|
7819
7912
|
tenantId: this.config.tenantId,
|
|
@@ -7834,15 +7927,15 @@ var Agent = class {
|
|
|
7834
7927
|
const hasAgentArtifactComponents = await this.hasAgentArtifactComponents();
|
|
7835
7928
|
const conversationId = runtimeContext?.metadata?.conversationId || runtimeContext?.contextId;
|
|
7836
7929
|
const resolvedContext = conversationId ? await this.getResolvedContext(conversationId) : null;
|
|
7837
|
-
let processedPrompt = this.config.prompt;
|
|
7838
|
-
if (resolvedContext) {
|
|
7930
|
+
let processedPrompt = this.config.prompt || "";
|
|
7931
|
+
if (resolvedContext && this.config.prompt) {
|
|
7839
7932
|
try {
|
|
7840
7933
|
processedPrompt = TemplateEngine.render(this.config.prompt, resolvedContext, {
|
|
7841
7934
|
strict: false,
|
|
7842
7935
|
preserveUnresolved: false
|
|
7843
7936
|
});
|
|
7844
7937
|
} catch (error) {
|
|
7845
|
-
|
|
7938
|
+
logger14.error(
|
|
7846
7939
|
{
|
|
7847
7940
|
conversationId,
|
|
7848
7941
|
error: error instanceof Error ? error.message : "Unknown error"
|
|
@@ -7881,15 +7974,15 @@ var Agent = class {
|
|
|
7881
7974
|
this.setConversationId(conversationId);
|
|
7882
7975
|
}
|
|
7883
7976
|
const resolvedContext = conversationId ? await this.getResolvedContext(conversationId) : null;
|
|
7884
|
-
let processedPrompt = this.config.prompt;
|
|
7885
|
-
if (resolvedContext) {
|
|
7977
|
+
let processedPrompt = this.config.prompt || "";
|
|
7978
|
+
if (resolvedContext && this.config.prompt) {
|
|
7886
7979
|
try {
|
|
7887
7980
|
processedPrompt = TemplateEngine.render(this.config.prompt, resolvedContext, {
|
|
7888
7981
|
strict: false,
|
|
7889
7982
|
preserveUnresolved: false
|
|
7890
7983
|
});
|
|
7891
7984
|
} catch (error) {
|
|
7892
|
-
|
|
7985
|
+
logger14.error(
|
|
7893
7986
|
{
|
|
7894
7987
|
conversationId,
|
|
7895
7988
|
error: error instanceof Error ? error.message : "Unknown error"
|
|
@@ -7904,7 +7997,7 @@ var Agent = class {
|
|
|
7904
7997
|
const functionTools = await this.getFunctionTools(streamRequestId || "");
|
|
7905
7998
|
const relationTools = this.getRelationTools(runtimeContext);
|
|
7906
7999
|
const allTools = { ...mcpTools, ...functionTools, ...relationTools };
|
|
7907
|
-
|
|
8000
|
+
logger14.info(
|
|
7908
8001
|
{
|
|
7909
8002
|
mcpTools: Object.keys(mcpTools),
|
|
7910
8003
|
functionTools: Object.keys(functionTools),
|
|
@@ -7925,7 +8018,7 @@ var Agent = class {
|
|
|
7925
8018
|
inputSchema: tool3.inputSchema || tool3.parameters || {},
|
|
7926
8019
|
usageGuidelines: name.startsWith("transfer_to_") || name.startsWith("delegate_to_") ? `Use this tool to ${name.startsWith("transfer_to_") ? "transfer" : "delegate"} to another agent when appropriate.` : "Use this tool when appropriate for the task at hand."
|
|
7927
8020
|
}));
|
|
7928
|
-
const { getConversationScopedArtifacts } = await import('./conversations-
|
|
8021
|
+
const { getConversationScopedArtifacts } = await import('./conversations-XPSTWUMK.js');
|
|
7929
8022
|
const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
|
|
7930
8023
|
const referenceArtifacts = await getConversationScopedArtifacts({
|
|
7931
8024
|
tenantId: this.config.tenantId,
|
|
@@ -7943,7 +8036,7 @@ var Agent = class {
|
|
|
7943
8036
|
preserveUnresolved: false
|
|
7944
8037
|
});
|
|
7945
8038
|
} catch (error) {
|
|
7946
|
-
|
|
8039
|
+
logger14.error(
|
|
7947
8040
|
{
|
|
7948
8041
|
conversationId,
|
|
7949
8042
|
error: error instanceof Error ? error.message : "Unknown error"
|
|
@@ -7976,7 +8069,7 @@ var Agent = class {
|
|
|
7976
8069
|
toolCallId: z.string().describe("The tool call ID associated with this artifact.")
|
|
7977
8070
|
}),
|
|
7978
8071
|
execute: async ({ artifactId, toolCallId }) => {
|
|
7979
|
-
|
|
8072
|
+
logger14.info({ artifactId, toolCallId }, "get_artifact_full executed");
|
|
7980
8073
|
const streamRequestId = this.getStreamRequestId();
|
|
7981
8074
|
const artifactService = agentSessionManager.getArtifactService(streamRequestId);
|
|
7982
8075
|
if (!artifactService) {
|
|
@@ -8272,7 +8365,7 @@ ${output}`;
|
|
|
8272
8365
|
};
|
|
8273
8366
|
return enhanced;
|
|
8274
8367
|
} catch (error) {
|
|
8275
|
-
|
|
8368
|
+
logger14.warn({ error }, "Failed to enhance tool result with structure hints");
|
|
8276
8369
|
return result;
|
|
8277
8370
|
}
|
|
8278
8371
|
}
|
|
@@ -8287,7 +8380,7 @@ ${output}`;
|
|
|
8287
8380
|
}
|
|
8288
8381
|
});
|
|
8289
8382
|
} catch (error) {
|
|
8290
|
-
|
|
8383
|
+
logger14.error(
|
|
8291
8384
|
{ error, agentId: this.config.agentId },
|
|
8292
8385
|
"Failed to check agent artifact components"
|
|
8293
8386
|
);
|
|
@@ -8404,7 +8497,7 @@ ${output}`;
|
|
|
8404
8497
|
const configuredTimeout = modelSettings.maxDuration ? Math.min(modelSettings.maxDuration * 1e3, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) : shouldStreamPhase1 ? LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING : LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING;
|
|
8405
8498
|
const timeoutMs = Math.min(configuredTimeout, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS);
|
|
8406
8499
|
if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) {
|
|
8407
|
-
|
|
8500
|
+
logger14.warn(
|
|
8408
8501
|
{
|
|
8409
8502
|
requestedTimeout: modelSettings.maxDuration * 1e3,
|
|
8410
8503
|
appliedTimeout: timeoutMs,
|
|
@@ -8446,7 +8539,16 @@ ${output}`;
|
|
|
8446
8539
|
}
|
|
8447
8540
|
);
|
|
8448
8541
|
} catch (error) {
|
|
8449
|
-
|
|
8542
|
+
logger14.debug({ error }, "Failed to track agent reasoning");
|
|
8543
|
+
}
|
|
8544
|
+
}
|
|
8545
|
+
if (last && last["content"] && last["content"].length > 0) {
|
|
8546
|
+
const lastContent = last["content"][last["content"].length - 1];
|
|
8547
|
+
if (lastContent["type"] === "tool-error") {
|
|
8548
|
+
const error = lastContent["error"];
|
|
8549
|
+
if (error && typeof error === "object" && "name" in error && error.name === "connection_refused") {
|
|
8550
|
+
return true;
|
|
8551
|
+
}
|
|
8450
8552
|
}
|
|
8451
8553
|
}
|
|
8452
8554
|
if (steps.length >= 2) {
|
|
@@ -8572,7 +8674,7 @@ ${output}`;
|
|
|
8572
8674
|
}
|
|
8573
8675
|
);
|
|
8574
8676
|
} catch (error) {
|
|
8575
|
-
|
|
8677
|
+
logger14.debug({ error }, "Failed to track agent reasoning");
|
|
8576
8678
|
}
|
|
8577
8679
|
}
|
|
8578
8680
|
if (steps.length >= 2) {
|
|
@@ -8719,7 +8821,7 @@ ${output}${structureHintsFormatted}`;
|
|
|
8719
8821
|
LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS
|
|
8720
8822
|
);
|
|
8721
8823
|
if (structuredModelSettings.maxDuration && structuredModelSettings.maxDuration * 1e3 > LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) {
|
|
8722
|
-
|
|
8824
|
+
logger14.warn(
|
|
8723
8825
|
{
|
|
8724
8826
|
requestedTimeout: structuredModelSettings.maxDuration * 1e3,
|
|
8725
8827
|
appliedTimeout: phase2TimeoutMs,
|
|
@@ -8895,7 +8997,7 @@ ${output}${structureHintsFormatted}`;
|
|
|
8895
8997
|
};
|
|
8896
8998
|
|
|
8897
8999
|
// src/agents/generateTaskHandler.ts
|
|
8898
|
-
var
|
|
9000
|
+
var logger15 = getLogger("generateTaskHandler");
|
|
8899
9001
|
var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
8900
9002
|
return async (task) => {
|
|
8901
9003
|
try {
|
|
@@ -9013,7 +9115,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9013
9115
|
return { ...relation, description: enhancedDescription };
|
|
9014
9116
|
}
|
|
9015
9117
|
} catch (error) {
|
|
9016
|
-
|
|
9118
|
+
logger15.warn({ subAgentId: relation.id, error }, "Failed to enhance agent description");
|
|
9017
9119
|
}
|
|
9018
9120
|
return relation;
|
|
9019
9121
|
})
|
|
@@ -9071,7 +9173,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9071
9173
|
};
|
|
9072
9174
|
}
|
|
9073
9175
|
} catch (error) {
|
|
9074
|
-
|
|
9176
|
+
logger15.warn(
|
|
9075
9177
|
{ targetAgentId: relation.targetAgentId, error },
|
|
9076
9178
|
"Failed to enhance team agent description"
|
|
9077
9179
|
);
|
|
@@ -9079,7 +9181,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9079
9181
|
return relation;
|
|
9080
9182
|
})
|
|
9081
9183
|
);
|
|
9082
|
-
const prompt = "prompt" in config.agentSchema ? config.agentSchema.prompt : "";
|
|
9184
|
+
const prompt = "prompt" in config.agentSchema ? config.agentSchema.prompt || void 0 : "";
|
|
9083
9185
|
const models = "models" in config.agentSchema ? config.agentSchema.models : void 0;
|
|
9084
9186
|
const stopWhen = "stopWhen" in config.agentSchema ? config.agentSchema.stopWhen : void 0;
|
|
9085
9187
|
const toolsForAgentResult = await Promise.all(
|
|
@@ -9088,7 +9190,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9088
9190
|
item.tool,
|
|
9089
9191
|
dbClient_default,
|
|
9090
9192
|
credentialStoreRegistry,
|
|
9091
|
-
item.id
|
|
9193
|
+
item.id,
|
|
9194
|
+
config.userId
|
|
9092
9195
|
);
|
|
9093
9196
|
if (item.selectedTools && item.selectedTools.length > 0) {
|
|
9094
9197
|
const selectedToolsSet = new Set(item.selectedTools);
|
|
@@ -9105,6 +9208,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9105
9208
|
agentId: config.agentId,
|
|
9106
9209
|
baseUrl: config.baseUrl,
|
|
9107
9210
|
apiKey: config.apiKey,
|
|
9211
|
+
userId: config.userId,
|
|
9108
9212
|
name: config.name,
|
|
9109
9213
|
description: config.description || "",
|
|
9110
9214
|
prompt,
|
|
@@ -9118,7 +9222,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9118
9222
|
baseUrl: config.baseUrl,
|
|
9119
9223
|
apiKey: config.apiKey,
|
|
9120
9224
|
name: relation.name,
|
|
9121
|
-
description: relation.description,
|
|
9225
|
+
description: relation.description || void 0,
|
|
9122
9226
|
prompt: "",
|
|
9123
9227
|
delegateRelations: [],
|
|
9124
9228
|
subAgentRelations: [],
|
|
@@ -9158,7 +9262,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9158
9262
|
targetTransferRelations = transferRel;
|
|
9159
9263
|
targetDelegateRelations = delegateRel;
|
|
9160
9264
|
} catch (err) {
|
|
9161
|
-
|
|
9265
|
+
logger15.info(
|
|
9162
9266
|
{
|
|
9163
9267
|
agentId: relation.id,
|
|
9164
9268
|
error: err?.message || "Unknown error"
|
|
@@ -9172,7 +9276,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9172
9276
|
item.tool,
|
|
9173
9277
|
dbClient_default,
|
|
9174
9278
|
credentialStoreRegistry,
|
|
9175
|
-
item.id
|
|
9279
|
+
item.id,
|
|
9280
|
+
config.userId
|
|
9176
9281
|
);
|
|
9177
9282
|
if (item.selectedTools && item.selectedTools.length > 0) {
|
|
9178
9283
|
const selectedToolsSet = new Set(item.selectedTools);
|
|
@@ -9221,7 +9326,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9221
9326
|
projectId: config.projectId,
|
|
9222
9327
|
agentId: config.agentId,
|
|
9223
9328
|
name: relation.name,
|
|
9224
|
-
description: relation.description,
|
|
9329
|
+
description: relation.description || void 0,
|
|
9225
9330
|
prompt: "",
|
|
9226
9331
|
delegateRelations: targetDelegateRelationsConfig,
|
|
9227
9332
|
subAgentRelations: [],
|
|
@@ -9236,13 +9341,14 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9236
9341
|
type: "internal",
|
|
9237
9342
|
config: {
|
|
9238
9343
|
id: relation.id,
|
|
9344
|
+
relationId: relation.relationId,
|
|
9239
9345
|
tenantId: config.tenantId,
|
|
9240
9346
|
projectId: config.projectId,
|
|
9241
9347
|
agentId: config.agentId,
|
|
9242
9348
|
baseUrl: config.baseUrl,
|
|
9243
9349
|
apiKey: config.apiKey,
|
|
9244
9350
|
name: relation.name,
|
|
9245
|
-
description: relation.description,
|
|
9351
|
+
description: relation.description || void 0,
|
|
9246
9352
|
prompt: "",
|
|
9247
9353
|
delegateRelations: [],
|
|
9248
9354
|
// Simplified - no nested relations
|
|
@@ -9297,7 +9403,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9297
9403
|
const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
|
|
9298
9404
|
if (taskIdMatch) {
|
|
9299
9405
|
contextId = taskIdMatch[1];
|
|
9300
|
-
|
|
9406
|
+
logger15.info(
|
|
9301
9407
|
{
|
|
9302
9408
|
taskId: task.id,
|
|
9303
9409
|
extractedContextId: contextId,
|
|
@@ -9315,7 +9421,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9315
9421
|
agent.setDelegationStatus(isDelegation);
|
|
9316
9422
|
agent.setDelegationId(delegationId);
|
|
9317
9423
|
if (isDelegation) {
|
|
9318
|
-
|
|
9424
|
+
logger15.info(
|
|
9319
9425
|
{ subAgentId: config.subAgentId, taskId: task.id, delegationId },
|
|
9320
9426
|
"Delegated agent - streaming disabled"
|
|
9321
9427
|
);
|
|
@@ -9352,7 +9458,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9352
9458
|
const toolResult = allToolResults.find(
|
|
9353
9459
|
(result) => result.toolCallId === toolCall.toolCallId
|
|
9354
9460
|
);
|
|
9355
|
-
|
|
9461
|
+
logger15.info(
|
|
9356
9462
|
{
|
|
9357
9463
|
toolCallName: toolCall.toolName,
|
|
9358
9464
|
toolCallId: toolCall.toolCallId,
|
|
@@ -9369,7 +9475,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9369
9475
|
const transferReason = responseText || allThoughts[allThoughts.length - 1]?.text || "Agent requested transfer. No reason provided.";
|
|
9370
9476
|
if (toolResult?.output && isValidTransferResult(toolResult.output)) {
|
|
9371
9477
|
const transferResult = toolResult.output;
|
|
9372
|
-
|
|
9478
|
+
logger15.info(
|
|
9373
9479
|
{
|
|
9374
9480
|
validationPassed: true,
|
|
9375
9481
|
transferResult,
|
|
@@ -9386,7 +9492,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9386
9492
|
reason: transferReason,
|
|
9387
9493
|
original_message: userMessage
|
|
9388
9494
|
};
|
|
9389
|
-
|
|
9495
|
+
logger15.info(
|
|
9390
9496
|
{
|
|
9391
9497
|
artifactData,
|
|
9392
9498
|
artifactDataKeys: Object.keys(artifactData)
|
|
@@ -9411,7 +9517,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9411
9517
|
]
|
|
9412
9518
|
};
|
|
9413
9519
|
}
|
|
9414
|
-
|
|
9520
|
+
logger15.warn(
|
|
9415
9521
|
{
|
|
9416
9522
|
hasToolResult: !!toolResult,
|
|
9417
9523
|
hasOutput: !!toolResult?.output,
|
|
@@ -9439,10 +9545,15 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
|
|
|
9439
9545
|
};
|
|
9440
9546
|
} catch (error) {
|
|
9441
9547
|
console.error("Task handler error:", error);
|
|
9548
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
9549
|
+
const isConnectionRefused = errorMessage.includes(
|
|
9550
|
+
"Connection refused. Please check if the MCP server is running."
|
|
9551
|
+
);
|
|
9442
9552
|
return {
|
|
9443
9553
|
status: {
|
|
9444
9554
|
state: TaskState.Failed,
|
|
9445
|
-
message:
|
|
9555
|
+
message: errorMessage,
|
|
9556
|
+
type: isConnectionRefused ? "connection_refused" : "unknown"
|
|
9446
9557
|
},
|
|
9447
9558
|
artifacts: []
|
|
9448
9559
|
};
|
|
@@ -9489,15 +9600,16 @@ var createTaskHandlerConfig = async (params) => {
|
|
|
9489
9600
|
baseUrl: params.baseUrl,
|
|
9490
9601
|
apiKey: params.apiKey,
|
|
9491
9602
|
name: subAgent.name,
|
|
9492
|
-
description: subAgent.description,
|
|
9603
|
+
description: subAgent.description || void 0,
|
|
9493
9604
|
conversationHistoryConfig: effectiveConversationHistoryConfig,
|
|
9494
9605
|
contextConfigId: agent?.contextConfigId || void 0,
|
|
9495
|
-
sandboxConfig: params.sandboxConfig
|
|
9606
|
+
sandboxConfig: params.sandboxConfig,
|
|
9607
|
+
userId: params.userId
|
|
9496
9608
|
};
|
|
9497
9609
|
};
|
|
9498
9610
|
|
|
9499
9611
|
// src/data/agents.ts
|
|
9500
|
-
var
|
|
9612
|
+
var logger16 = getLogger("agents");
|
|
9501
9613
|
function createAgentCard({
|
|
9502
9614
|
dbAgent,
|
|
9503
9615
|
baseUrl
|
|
@@ -9567,7 +9679,8 @@ async function hydrateAgent({
|
|
|
9567
9679
|
baseUrl,
|
|
9568
9680
|
apiKey,
|
|
9569
9681
|
credentialStoreRegistry,
|
|
9570
|
-
sandboxConfig
|
|
9682
|
+
sandboxConfig,
|
|
9683
|
+
userId
|
|
9571
9684
|
}) {
|
|
9572
9685
|
try {
|
|
9573
9686
|
const taskHandlerConfig = await createTaskHandlerConfig({
|
|
@@ -9577,7 +9690,8 @@ async function hydrateAgent({
|
|
|
9577
9690
|
subAgentId: dbAgent.id,
|
|
9578
9691
|
baseUrl,
|
|
9579
9692
|
apiKey,
|
|
9580
|
-
sandboxConfig
|
|
9693
|
+
sandboxConfig,
|
|
9694
|
+
userId
|
|
9581
9695
|
});
|
|
9582
9696
|
const taskHandler = createTaskHandler(taskHandlerConfig, credentialStoreRegistry);
|
|
9583
9697
|
const agentCard = createAgentCard({
|
|
@@ -9600,12 +9714,13 @@ async function hydrateAgent({
|
|
|
9600
9714
|
async function getRegisteredAgent(params) {
|
|
9601
9715
|
const { executionContext, credentialStoreRegistry, sandboxConfig } = params;
|
|
9602
9716
|
const { tenantId, projectId, agentId, subAgentId, baseUrl, apiKey } = executionContext;
|
|
9717
|
+
const userId = getUserIdFromContext(executionContext);
|
|
9603
9718
|
let dbAgent;
|
|
9604
9719
|
if (!subAgentId) {
|
|
9605
9720
|
const agent = await getAgentWithDefaultSubAgent(dbClient_default)({
|
|
9606
9721
|
scopes: { tenantId, projectId, agentId }
|
|
9607
9722
|
});
|
|
9608
|
-
|
|
9723
|
+
logger16.info({ agent }, "agent with default sub agent");
|
|
9609
9724
|
if (!agent || !agent.defaultSubAgent) {
|
|
9610
9725
|
return null;
|
|
9611
9726
|
}
|
|
@@ -9630,13 +9745,14 @@ async function getRegisteredAgent(params) {
|
|
|
9630
9745
|
baseUrl: agentFrameworkBaseUrl,
|
|
9631
9746
|
credentialStoreRegistry,
|
|
9632
9747
|
apiKey,
|
|
9633
|
-
sandboxConfig
|
|
9748
|
+
sandboxConfig,
|
|
9749
|
+
userId
|
|
9634
9750
|
});
|
|
9635
9751
|
}
|
|
9636
9752
|
|
|
9637
9753
|
// src/routes/agents.ts
|
|
9638
9754
|
var app = new OpenAPIHono();
|
|
9639
|
-
var
|
|
9755
|
+
var logger17 = getLogger("agents");
|
|
9640
9756
|
app.openapi(
|
|
9641
9757
|
createRoute({
|
|
9642
9758
|
method: "get",
|
|
@@ -9674,7 +9790,7 @@ app.openapi(
|
|
|
9674
9790
|
tracestate: c.req.header("tracestate"),
|
|
9675
9791
|
baggage: c.req.header("baggage")
|
|
9676
9792
|
};
|
|
9677
|
-
|
|
9793
|
+
logger17.info(
|
|
9678
9794
|
{
|
|
9679
9795
|
otelHeaders,
|
|
9680
9796
|
path: c.req.path,
|
|
@@ -9684,8 +9800,8 @@ app.openapi(
|
|
|
9684
9800
|
);
|
|
9685
9801
|
const executionContext = getRequestExecutionContext(c);
|
|
9686
9802
|
const { tenantId, projectId, agentId, subAgentId } = executionContext;
|
|
9687
|
-
|
|
9688
|
-
|
|
9803
|
+
logger17.info({ executionContext }, "executionContext");
|
|
9804
|
+
logger17.info(
|
|
9689
9805
|
{
|
|
9690
9806
|
message: "getRegisteredAgent (agent-level)",
|
|
9691
9807
|
tenantId,
|
|
@@ -9702,7 +9818,7 @@ app.openapi(
|
|
|
9702
9818
|
credentialStoreRegistry: credentialStores,
|
|
9703
9819
|
sandboxConfig
|
|
9704
9820
|
});
|
|
9705
|
-
|
|
9821
|
+
logger17.info({ agent }, "agent registered: well-known agent.json");
|
|
9706
9822
|
if (!agent) {
|
|
9707
9823
|
throw createApiError({
|
|
9708
9824
|
code: "not_found",
|
|
@@ -9718,7 +9834,7 @@ app.post("/a2a", async (c) => {
|
|
|
9718
9834
|
tracestate: c.req.header("tracestate"),
|
|
9719
9835
|
baggage: c.req.header("baggage")
|
|
9720
9836
|
};
|
|
9721
|
-
|
|
9837
|
+
logger17.info(
|
|
9722
9838
|
{
|
|
9723
9839
|
otelHeaders,
|
|
9724
9840
|
path: c.req.path,
|
|
@@ -9729,7 +9845,7 @@ app.post("/a2a", async (c) => {
|
|
|
9729
9845
|
const executionContext = getRequestExecutionContext(c);
|
|
9730
9846
|
const { tenantId, projectId, agentId, subAgentId } = executionContext;
|
|
9731
9847
|
if (subAgentId) {
|
|
9732
|
-
|
|
9848
|
+
logger17.info(
|
|
9733
9849
|
{
|
|
9734
9850
|
message: "a2a (agent-level)",
|
|
9735
9851
|
tenantId,
|
|
@@ -9758,7 +9874,7 @@ app.post("/a2a", async (c) => {
|
|
|
9758
9874
|
}
|
|
9759
9875
|
return a2aHandler(c, agent2);
|
|
9760
9876
|
}
|
|
9761
|
-
|
|
9877
|
+
logger17.info(
|
|
9762
9878
|
{
|
|
9763
9879
|
message: "a2a (agent-level)",
|
|
9764
9880
|
tenantId,
|
|
@@ -9836,14 +9952,14 @@ function extractTransferData(task) {
|
|
|
9836
9952
|
}
|
|
9837
9953
|
|
|
9838
9954
|
// src/a2a/transfer.ts
|
|
9839
|
-
var
|
|
9955
|
+
var logger18 = getLogger("Transfer");
|
|
9840
9956
|
async function executeTransfer({
|
|
9841
9957
|
tenantId,
|
|
9842
9958
|
threadId,
|
|
9843
9959
|
projectId,
|
|
9844
9960
|
targetSubAgentId
|
|
9845
9961
|
}) {
|
|
9846
|
-
|
|
9962
|
+
logger18.info(
|
|
9847
9963
|
{
|
|
9848
9964
|
targetAgent: targetSubAgentId,
|
|
9849
9965
|
threadId,
|
|
@@ -9858,12 +9974,12 @@ async function executeTransfer({
|
|
|
9858
9974
|
threadId,
|
|
9859
9975
|
subAgentId: targetSubAgentId
|
|
9860
9976
|
});
|
|
9861
|
-
|
|
9977
|
+
logger18.info(
|
|
9862
9978
|
{ targetAgent: targetSubAgentId, threadId },
|
|
9863
9979
|
"Successfully updated active_sub_agent_id in database"
|
|
9864
9980
|
);
|
|
9865
9981
|
} catch (error) {
|
|
9866
|
-
|
|
9982
|
+
logger18.error(
|
|
9867
9983
|
{ error, targetAgent: targetSubAgentId, threadId },
|
|
9868
9984
|
"Failed to update active_sub_agent_id"
|
|
9869
9985
|
);
|
|
@@ -10427,7 +10543,7 @@ function createBufferingStreamHelper() {
|
|
|
10427
10543
|
var createMCPStreamHelper = createBufferingStreamHelper;
|
|
10428
10544
|
|
|
10429
10545
|
// src/handlers/executionHandler.ts
|
|
10430
|
-
var
|
|
10546
|
+
var logger19 = getLogger("ExecutionHandler");
|
|
10431
10547
|
var ExecutionHandler = class {
|
|
10432
10548
|
MAX_ERRORS = AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS;
|
|
10433
10549
|
/**
|
|
@@ -10460,7 +10576,7 @@ var ExecutionHandler = class {
|
|
|
10460
10576
|
if (emitOperations) {
|
|
10461
10577
|
agentSessionManager.enableEmitOperations(requestId2);
|
|
10462
10578
|
}
|
|
10463
|
-
|
|
10579
|
+
logger19.info(
|
|
10464
10580
|
{ sessionId: requestId2, agentId, conversationId, emitOperations },
|
|
10465
10581
|
"Created AgentSession for message execution"
|
|
10466
10582
|
);
|
|
@@ -10493,7 +10609,7 @@ var ExecutionHandler = class {
|
|
|
10493
10609
|
);
|
|
10494
10610
|
}
|
|
10495
10611
|
} catch (modelError) {
|
|
10496
|
-
|
|
10612
|
+
logger19.warn(
|
|
10497
10613
|
{
|
|
10498
10614
|
error: modelError instanceof Error ? modelError.message : "Unknown error",
|
|
10499
10615
|
agentId
|
|
@@ -10508,7 +10624,7 @@ var ExecutionHandler = class {
|
|
|
10508
10624
|
}
|
|
10509
10625
|
}
|
|
10510
10626
|
} catch (error) {
|
|
10511
|
-
|
|
10627
|
+
logger19.error(
|
|
10512
10628
|
{
|
|
10513
10629
|
error: error instanceof Error ? error.message : "Unknown error",
|
|
10514
10630
|
stack: error instanceof Error ? error.stack : void 0
|
|
@@ -10524,7 +10640,7 @@ var ExecutionHandler = class {
|
|
|
10524
10640
|
try {
|
|
10525
10641
|
await sseHelper.writeOperation(agentInitializingOp(requestId2, agentId));
|
|
10526
10642
|
const taskId = `task_${conversationId}-${requestId2}`;
|
|
10527
|
-
|
|
10643
|
+
logger19.info(
|
|
10528
10644
|
{ taskId, currentAgentId, conversationId, requestId: requestId2 },
|
|
10529
10645
|
"Attempting to create or reuse existing task"
|
|
10530
10646
|
);
|
|
@@ -10548,7 +10664,7 @@ var ExecutionHandler = class {
|
|
|
10548
10664
|
sub_agent_id: currentAgentId
|
|
10549
10665
|
}
|
|
10550
10666
|
});
|
|
10551
|
-
|
|
10667
|
+
logger19.info(
|
|
10552
10668
|
{
|
|
10553
10669
|
taskId,
|
|
10554
10670
|
createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
|
|
@@ -10557,27 +10673,27 @@ var ExecutionHandler = class {
|
|
|
10557
10673
|
);
|
|
10558
10674
|
} catch (error) {
|
|
10559
10675
|
if (error?.cause?.code === "23505") {
|
|
10560
|
-
|
|
10676
|
+
logger19.info(
|
|
10561
10677
|
{ taskId, error: error.message },
|
|
10562
10678
|
"Task already exists, fetching existing task"
|
|
10563
10679
|
);
|
|
10564
10680
|
const existingTask = await getTask(dbClient_default)({ id: taskId });
|
|
10565
10681
|
if (existingTask) {
|
|
10566
10682
|
task = existingTask;
|
|
10567
|
-
|
|
10683
|
+
logger19.info(
|
|
10568
10684
|
{ taskId, existingTask },
|
|
10569
10685
|
"Successfully reused existing task from race condition"
|
|
10570
10686
|
);
|
|
10571
10687
|
} else {
|
|
10572
|
-
|
|
10688
|
+
logger19.error({ taskId, error }, "Task constraint failed but task not found");
|
|
10573
10689
|
throw error;
|
|
10574
10690
|
}
|
|
10575
10691
|
} else {
|
|
10576
|
-
|
|
10692
|
+
logger19.error({ taskId, error }, "Failed to create task due to non-constraint error");
|
|
10577
10693
|
throw error;
|
|
10578
10694
|
}
|
|
10579
10695
|
}
|
|
10580
|
-
|
|
10696
|
+
logger19.debug(
|
|
10581
10697
|
{
|
|
10582
10698
|
timestamp: /* @__PURE__ */ new Date(),
|
|
10583
10699
|
executionType: "create_initial_task",
|
|
@@ -10596,7 +10712,7 @@ var ExecutionHandler = class {
|
|
|
10596
10712
|
const maxTransfers = agentConfig?.stopWhen?.transferCountIs ?? AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT;
|
|
10597
10713
|
while (iterations < maxTransfers) {
|
|
10598
10714
|
iterations++;
|
|
10599
|
-
|
|
10715
|
+
logger19.info(
|
|
10600
10716
|
{ iterations, currentAgentId, agentId, conversationId, fromSubAgentId },
|
|
10601
10717
|
`Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromSubAgentId || "none"}`
|
|
10602
10718
|
);
|
|
@@ -10604,10 +10720,10 @@ var ExecutionHandler = class {
|
|
|
10604
10720
|
scopes: { tenantId, projectId },
|
|
10605
10721
|
conversationId
|
|
10606
10722
|
});
|
|
10607
|
-
|
|
10723
|
+
logger19.info({ activeAgent }, "activeAgent");
|
|
10608
10724
|
if (activeAgent && activeAgent.activeSubAgentId !== currentAgentId) {
|
|
10609
10725
|
currentAgentId = activeAgent.activeSubAgentId;
|
|
10610
|
-
|
|
10726
|
+
logger19.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
|
|
10611
10727
|
}
|
|
10612
10728
|
const agentBaseUrl = `${baseUrl}/agents`;
|
|
10613
10729
|
const a2aClient = new A2AClient(agentBaseUrl, {
|
|
@@ -10648,13 +10764,13 @@ var ExecutionHandler = class {
|
|
|
10648
10764
|
});
|
|
10649
10765
|
if (!messageResponse?.result) {
|
|
10650
10766
|
errorCount++;
|
|
10651
|
-
|
|
10767
|
+
logger19.error(
|
|
10652
10768
|
{ currentAgentId, iterations, errorCount },
|
|
10653
10769
|
`No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
|
|
10654
10770
|
);
|
|
10655
10771
|
if (errorCount >= this.MAX_ERRORS) {
|
|
10656
10772
|
const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
|
|
10657
|
-
|
|
10773
|
+
logger19.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
|
|
10658
10774
|
await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
|
|
10659
10775
|
if (task) {
|
|
10660
10776
|
await updateTask(dbClient_default)({
|
|
@@ -10669,7 +10785,7 @@ var ExecutionHandler = class {
|
|
|
10669
10785
|
}
|
|
10670
10786
|
});
|
|
10671
10787
|
}
|
|
10672
|
-
agentSessionManager.endSession(requestId2);
|
|
10788
|
+
await agentSessionManager.endSession(requestId2);
|
|
10673
10789
|
unregisterStreamHelper(requestId2);
|
|
10674
10790
|
return { success: false, error: errorMessage2, iterations };
|
|
10675
10791
|
}
|
|
@@ -10678,7 +10794,7 @@ var ExecutionHandler = class {
|
|
|
10678
10794
|
if (isTransferTask(messageResponse.result)) {
|
|
10679
10795
|
const transferData = extractTransferData(messageResponse.result);
|
|
10680
10796
|
if (!transferData) {
|
|
10681
|
-
|
|
10797
|
+
logger19.error(
|
|
10682
10798
|
{ result: messageResponse.result },
|
|
10683
10799
|
"Transfer detected but no transfer data found"
|
|
10684
10800
|
);
|
|
@@ -10687,7 +10803,7 @@ var ExecutionHandler = class {
|
|
|
10687
10803
|
const { targetSubAgentId, fromSubAgentId: transferFromAgent } = transferData;
|
|
10688
10804
|
const firstArtifact = messageResponse.result.artifacts[0];
|
|
10689
10805
|
const transferReason = firstArtifact?.parts[1]?.kind === "text" ? firstArtifact.parts[1].text : "Transfer initiated";
|
|
10690
|
-
|
|
10806
|
+
logger19.info({ targetSubAgentId, transferReason, transferFromAgent }, "Transfer response");
|
|
10691
10807
|
await createMessage(dbClient_default)({
|
|
10692
10808
|
id: generateId(),
|
|
10693
10809
|
tenantId,
|
|
@@ -10718,7 +10834,7 @@ var ExecutionHandler = class {
|
|
|
10718
10834
|
if (success) {
|
|
10719
10835
|
fromSubAgentId = currentAgentId;
|
|
10720
10836
|
currentAgentId = newAgentId;
|
|
10721
|
-
|
|
10837
|
+
logger19.info(
|
|
10722
10838
|
{
|
|
10723
10839
|
transferFrom: fromSubAgentId,
|
|
10724
10840
|
transferTo: currentAgentId,
|
|
@@ -10732,7 +10848,7 @@ var ExecutionHandler = class {
|
|
|
10732
10848
|
let responseParts = [];
|
|
10733
10849
|
if (messageResponse.result.streamedContent?.parts) {
|
|
10734
10850
|
responseParts = messageResponse.result.streamedContent.parts;
|
|
10735
|
-
|
|
10851
|
+
logger19.info(
|
|
10736
10852
|
{ partsCount: responseParts.length },
|
|
10737
10853
|
"Using streamed content for conversation history"
|
|
10738
10854
|
);
|
|
@@ -10740,7 +10856,7 @@ var ExecutionHandler = class {
|
|
|
10740
10856
|
responseParts = messageResponse.result.artifacts?.flatMap(
|
|
10741
10857
|
(artifact) => artifact.parts || []
|
|
10742
10858
|
) || [];
|
|
10743
|
-
|
|
10859
|
+
logger19.info(
|
|
10744
10860
|
{ partsCount: responseParts.length },
|
|
10745
10861
|
"Using artifacts for conversation history (fallback)"
|
|
10746
10862
|
);
|
|
@@ -10749,7 +10865,7 @@ var ExecutionHandler = class {
|
|
|
10749
10865
|
const agentSessionData = agentSessionManager.getSession(requestId2);
|
|
10750
10866
|
if (agentSessionData) {
|
|
10751
10867
|
const sessionSummary = agentSessionData.getSummary();
|
|
10752
|
-
|
|
10868
|
+
logger19.info(sessionSummary, "AgentSession data after completion");
|
|
10753
10869
|
}
|
|
10754
10870
|
let textContent = "";
|
|
10755
10871
|
for (const part of responseParts) {
|
|
@@ -10803,22 +10919,22 @@ var ExecutionHandler = class {
|
|
|
10803
10919
|
}
|
|
10804
10920
|
});
|
|
10805
10921
|
const updateTaskEnd = Date.now();
|
|
10806
|
-
|
|
10922
|
+
logger19.info(
|
|
10807
10923
|
{ duration: updateTaskEnd - updateTaskStart },
|
|
10808
10924
|
"Completed updateTask operation"
|
|
10809
10925
|
);
|
|
10810
10926
|
await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
|
|
10811
10927
|
await sseHelper.complete();
|
|
10812
|
-
|
|
10813
|
-
agentSessionManager.endSession(requestId2);
|
|
10814
|
-
|
|
10928
|
+
logger19.info({}, "Ending AgentSession and cleaning up");
|
|
10929
|
+
await agentSessionManager.endSession(requestId2);
|
|
10930
|
+
logger19.info({}, "Cleaning up streamHelper");
|
|
10815
10931
|
unregisterStreamHelper(requestId2);
|
|
10816
10932
|
let response;
|
|
10817
10933
|
if (sseHelper instanceof BufferingStreamHelper) {
|
|
10818
10934
|
const captured = sseHelper.getCapturedResponse();
|
|
10819
10935
|
response = captured.text || "No response content";
|
|
10820
10936
|
}
|
|
10821
|
-
|
|
10937
|
+
logger19.info({}, "ExecutionHandler returning success");
|
|
10822
10938
|
return { success: true, iterations, response };
|
|
10823
10939
|
} catch (error) {
|
|
10824
10940
|
setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
|
|
@@ -10829,13 +10945,13 @@ var ExecutionHandler = class {
|
|
|
10829
10945
|
});
|
|
10830
10946
|
}
|
|
10831
10947
|
errorCount++;
|
|
10832
|
-
|
|
10948
|
+
logger19.warn(
|
|
10833
10949
|
{ iterations, errorCount },
|
|
10834
10950
|
`No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
|
|
10835
10951
|
);
|
|
10836
10952
|
if (errorCount >= this.MAX_ERRORS) {
|
|
10837
10953
|
const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
|
|
10838
|
-
|
|
10954
|
+
logger19.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
|
|
10839
10955
|
await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
|
|
10840
10956
|
if (task) {
|
|
10841
10957
|
await updateTask(dbClient_default)({
|
|
@@ -10850,13 +10966,13 @@ var ExecutionHandler = class {
|
|
|
10850
10966
|
}
|
|
10851
10967
|
});
|
|
10852
10968
|
}
|
|
10853
|
-
agentSessionManager.endSession(requestId2);
|
|
10969
|
+
await agentSessionManager.endSession(requestId2);
|
|
10854
10970
|
unregisterStreamHelper(requestId2);
|
|
10855
10971
|
return { success: false, error: errorMessage2, iterations };
|
|
10856
10972
|
}
|
|
10857
10973
|
}
|
|
10858
10974
|
const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
|
|
10859
|
-
|
|
10975
|
+
logger19.error({ maxTransfers, iterations }, errorMessage);
|
|
10860
10976
|
await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
|
|
10861
10977
|
if (task) {
|
|
10862
10978
|
await updateTask(dbClient_default)({
|
|
@@ -10871,11 +10987,11 @@ var ExecutionHandler = class {
|
|
|
10871
10987
|
}
|
|
10872
10988
|
});
|
|
10873
10989
|
}
|
|
10874
|
-
agentSessionManager.endSession(requestId2);
|
|
10990
|
+
await agentSessionManager.endSession(requestId2);
|
|
10875
10991
|
unregisterStreamHelper(requestId2);
|
|
10876
10992
|
return { success: false, error: errorMessage, iterations };
|
|
10877
10993
|
} catch (error) {
|
|
10878
|
-
|
|
10994
|
+
logger19.error({ error }, "Error in execution handler");
|
|
10879
10995
|
const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
|
|
10880
10996
|
await sseHelper.writeOperation(
|
|
10881
10997
|
errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
|
|
@@ -10893,7 +11009,7 @@ var ExecutionHandler = class {
|
|
|
10893
11009
|
}
|
|
10894
11010
|
});
|
|
10895
11011
|
}
|
|
10896
|
-
agentSessionManager.endSession(requestId2);
|
|
11012
|
+
await agentSessionManager.endSession(requestId2);
|
|
10897
11013
|
unregisterStreamHelper(requestId2);
|
|
10898
11014
|
return { success: false, error: errorMessage, iterations };
|
|
10899
11015
|
}
|
|
@@ -10902,7 +11018,7 @@ var ExecutionHandler = class {
|
|
|
10902
11018
|
|
|
10903
11019
|
// src/routes/chat.ts
|
|
10904
11020
|
var app2 = new OpenAPIHono();
|
|
10905
|
-
var
|
|
11021
|
+
var logger20 = getLogger("completionsHandler");
|
|
10906
11022
|
var chatCompletionsRoute = createRoute({
|
|
10907
11023
|
method: "post",
|
|
10908
11024
|
path: "/completions",
|
|
@@ -11020,7 +11136,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
|
|
|
11020
11136
|
tracestate: c.req.header("tracestate"),
|
|
11021
11137
|
baggage: c.req.header("baggage")
|
|
11022
11138
|
};
|
|
11023
|
-
|
|
11139
|
+
logger20.info(
|
|
11024
11140
|
{
|
|
11025
11141
|
otelHeaders,
|
|
11026
11142
|
path: c.req.path,
|
|
@@ -11129,7 +11245,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
|
|
|
11129
11245
|
dbClient: dbClient_default,
|
|
11130
11246
|
credentialStores
|
|
11131
11247
|
});
|
|
11132
|
-
|
|
11248
|
+
logger20.info(
|
|
11133
11249
|
{
|
|
11134
11250
|
tenantId,
|
|
11135
11251
|
projectId,
|
|
@@ -11177,7 +11293,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
|
|
|
11177
11293
|
try {
|
|
11178
11294
|
const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
|
|
11179
11295
|
await sseHelper.writeRole();
|
|
11180
|
-
|
|
11296
|
+
logger20.info({ subAgentId }, "Starting execution");
|
|
11181
11297
|
const emitOperationsHeader = c.req.header("x-emit-operations");
|
|
11182
11298
|
const emitOperations = emitOperationsHeader === "true";
|
|
11183
11299
|
const executionHandler = new ExecutionHandler();
|
|
@@ -11190,7 +11306,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
|
|
|
11190
11306
|
sseHelper,
|
|
11191
11307
|
emitOperations
|
|
11192
11308
|
});
|
|
11193
|
-
|
|
11309
|
+
logger20.info(
|
|
11194
11310
|
{ result },
|
|
11195
11311
|
`Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
|
|
11196
11312
|
);
|
|
@@ -11204,7 +11320,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
|
|
|
11204
11320
|
}
|
|
11205
11321
|
await sseHelper.complete();
|
|
11206
11322
|
} catch (error) {
|
|
11207
|
-
|
|
11323
|
+
logger20.error(
|
|
11208
11324
|
{
|
|
11209
11325
|
error: error instanceof Error ? error.message : error,
|
|
11210
11326
|
stack: error instanceof Error ? error.stack : void 0
|
|
@@ -11221,13 +11337,13 @@ app2.openapi(chatCompletionsRoute, async (c) => {
|
|
|
11221
11337
|
);
|
|
11222
11338
|
await sseHelper.complete();
|
|
11223
11339
|
} catch (streamError) {
|
|
11224
|
-
|
|
11340
|
+
logger20.error({ streamError }, "Failed to write error to stream");
|
|
11225
11341
|
}
|
|
11226
11342
|
}
|
|
11227
11343
|
});
|
|
11228
11344
|
});
|
|
11229
11345
|
} catch (error) {
|
|
11230
|
-
|
|
11346
|
+
logger20.error(
|
|
11231
11347
|
{
|
|
11232
11348
|
error: error instanceof Error ? error.message : error,
|
|
11233
11349
|
stack: error instanceof Error ? error.stack : void 0
|
|
@@ -11251,7 +11367,7 @@ var getMessageText = (content) => {
|
|
|
11251
11367
|
};
|
|
11252
11368
|
var chat_default = app2;
|
|
11253
11369
|
var app3 = new OpenAPIHono();
|
|
11254
|
-
var
|
|
11370
|
+
var logger21 = getLogger("chatDataStream");
|
|
11255
11371
|
var chatDataStreamRoute = createRoute({
|
|
11256
11372
|
method: "post",
|
|
11257
11373
|
path: "/chat",
|
|
@@ -11263,29 +11379,29 @@ var chatDataStreamRoute = createRoute({
|
|
|
11263
11379
|
body: {
|
|
11264
11380
|
content: {
|
|
11265
11381
|
"application/json": {
|
|
11266
|
-
schema: z
|
|
11267
|
-
model: z
|
|
11268
|
-
messages: z
|
|
11269
|
-
z
|
|
11270
|
-
role: z
|
|
11271
|
-
content: z
|
|
11272
|
-
parts: z
|
|
11273
|
-
z
|
|
11274
|
-
type: z
|
|
11275
|
-
z
|
|
11276
|
-
z
|
|
11382
|
+
schema: z.object({
|
|
11383
|
+
model: z.string().optional(),
|
|
11384
|
+
messages: z.array(
|
|
11385
|
+
z.object({
|
|
11386
|
+
role: z.enum(["system", "user", "assistant", "function", "tool"]),
|
|
11387
|
+
content: z.any(),
|
|
11388
|
+
parts: z.array(
|
|
11389
|
+
z.object({
|
|
11390
|
+
type: z.union([
|
|
11391
|
+
z.enum(["text", "image", "audio", "video", "file"]),
|
|
11392
|
+
z.string().regex(/^data-/, 'Type must start with "data-"')
|
|
11277
11393
|
]),
|
|
11278
|
-
text: z
|
|
11394
|
+
text: z.string().optional()
|
|
11279
11395
|
})
|
|
11280
11396
|
).optional()
|
|
11281
11397
|
})
|
|
11282
11398
|
),
|
|
11283
|
-
id: z
|
|
11284
|
-
conversationId: z
|
|
11285
|
-
stream: z
|
|
11286
|
-
max_tokens: z
|
|
11287
|
-
headers: z
|
|
11288
|
-
runConfig: z
|
|
11399
|
+
id: z.string().optional(),
|
|
11400
|
+
conversationId: z.string().optional(),
|
|
11401
|
+
stream: z.boolean().optional().describe("Whether to stream the response").default(true),
|
|
11402
|
+
max_tokens: z.number().optional().describe("Maximum tokens to generate"),
|
|
11403
|
+
headers: z.record(z.string(), z.unknown()).optional().describe("Headers data for template processing"),
|
|
11404
|
+
runConfig: z.record(z.string(), z.unknown()).optional().describe("Run configuration")
|
|
11289
11405
|
})
|
|
11290
11406
|
}
|
|
11291
11407
|
}
|
|
@@ -11294,9 +11410,9 @@ var chatDataStreamRoute = createRoute({
|
|
|
11294
11410
|
responses: {
|
|
11295
11411
|
200: {
|
|
11296
11412
|
description: "Streamed chat completion",
|
|
11297
|
-
headers: z
|
|
11298
|
-
"Content-Type": z
|
|
11299
|
-
"x-vercel-ai-data-stream": z
|
|
11413
|
+
headers: z.object({
|
|
11414
|
+
"Content-Type": z.string().default("text/plain; charset=utf-8"),
|
|
11415
|
+
"x-vercel-ai-data-stream": z.string().default("v1")
|
|
11300
11416
|
})
|
|
11301
11417
|
},
|
|
11302
11418
|
...commonGetErrorResponses
|
|
@@ -11378,7 +11494,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
|
|
|
11378
11494
|
});
|
|
11379
11495
|
const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
|
|
11380
11496
|
const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
|
|
11381
|
-
|
|
11497
|
+
logger21.info({ userText, lastUserMessage }, "userText");
|
|
11382
11498
|
const messageSpan = trace.getActiveSpan();
|
|
11383
11499
|
if (messageSpan) {
|
|
11384
11500
|
messageSpan.setAttributes({
|
|
@@ -11461,7 +11577,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
|
|
|
11461
11577
|
await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
|
|
11462
11578
|
}
|
|
11463
11579
|
} catch (err) {
|
|
11464
|
-
|
|
11580
|
+
logger21.error({ err }, "Streaming error");
|
|
11465
11581
|
await streamHelper.writeOperation(errorOp("Internal server error", "system"));
|
|
11466
11582
|
} finally {
|
|
11467
11583
|
if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
|
|
@@ -11483,7 +11599,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
|
|
|
11483
11599
|
);
|
|
11484
11600
|
});
|
|
11485
11601
|
} catch (error) {
|
|
11486
|
-
|
|
11602
|
+
logger21.error(
|
|
11487
11603
|
{
|
|
11488
11604
|
error,
|
|
11489
11605
|
errorMessage: error instanceof Error ? error.message : String(error),
|
|
@@ -11509,11 +11625,11 @@ var toolApprovalRoute = createRoute({
|
|
|
11509
11625
|
body: {
|
|
11510
11626
|
content: {
|
|
11511
11627
|
"application/json": {
|
|
11512
|
-
schema: z
|
|
11513
|
-
conversationId: z
|
|
11514
|
-
toolCallId: z
|
|
11515
|
-
approved: z
|
|
11516
|
-
reason: z
|
|
11628
|
+
schema: z.object({
|
|
11629
|
+
conversationId: z.string().describe("The conversation ID"),
|
|
11630
|
+
toolCallId: z.string().describe("The tool call ID to respond to"),
|
|
11631
|
+
approved: z.boolean().describe("Whether the tool execution is approved"),
|
|
11632
|
+
reason: z.string().optional().describe("Optional reason for the decision")
|
|
11517
11633
|
})
|
|
11518
11634
|
}
|
|
11519
11635
|
}
|
|
@@ -11524,9 +11640,9 @@ var toolApprovalRoute = createRoute({
|
|
|
11524
11640
|
description: "Tool approval response processed successfully",
|
|
11525
11641
|
content: {
|
|
11526
11642
|
"application/json": {
|
|
11527
|
-
schema: z
|
|
11528
|
-
success: z
|
|
11529
|
-
message: z
|
|
11643
|
+
schema: z.object({
|
|
11644
|
+
success: z.boolean(),
|
|
11645
|
+
message: z.string().optional()
|
|
11530
11646
|
})
|
|
11531
11647
|
}
|
|
11532
11648
|
}
|
|
@@ -11535,8 +11651,8 @@ var toolApprovalRoute = createRoute({
|
|
|
11535
11651
|
description: "Bad request - invalid tool call ID or conversation ID",
|
|
11536
11652
|
content: {
|
|
11537
11653
|
"application/json": {
|
|
11538
|
-
schema: z
|
|
11539
|
-
error: z
|
|
11654
|
+
schema: z.object({
|
|
11655
|
+
error: z.string()
|
|
11540
11656
|
})
|
|
11541
11657
|
}
|
|
11542
11658
|
}
|
|
@@ -11545,8 +11661,8 @@ var toolApprovalRoute = createRoute({
|
|
|
11545
11661
|
description: "Tool call not found or already processed",
|
|
11546
11662
|
content: {
|
|
11547
11663
|
"application/json": {
|
|
11548
|
-
schema: z
|
|
11549
|
-
error: z
|
|
11664
|
+
schema: z.object({
|
|
11665
|
+
error: z.string()
|
|
11550
11666
|
})
|
|
11551
11667
|
}
|
|
11552
11668
|
}
|
|
@@ -11555,9 +11671,9 @@ var toolApprovalRoute = createRoute({
|
|
|
11555
11671
|
description: "Internal server error",
|
|
11556
11672
|
content: {
|
|
11557
11673
|
"application/json": {
|
|
11558
|
-
schema: z
|
|
11559
|
-
error: z
|
|
11560
|
-
message: z
|
|
11674
|
+
schema: z.object({
|
|
11675
|
+
error: z.string(),
|
|
11676
|
+
message: z.string()
|
|
11561
11677
|
})
|
|
11562
11678
|
}
|
|
11563
11679
|
}
|
|
@@ -11572,7 +11688,7 @@ app3.openapi(toolApprovalRoute, async (c) => {
|
|
|
11572
11688
|
const { tenantId, projectId } = executionContext;
|
|
11573
11689
|
const requestBody = await c.req.json();
|
|
11574
11690
|
const { conversationId, toolCallId, approved, reason } = requestBody;
|
|
11575
|
-
|
|
11691
|
+
logger21.info(
|
|
11576
11692
|
{
|
|
11577
11693
|
conversationId,
|
|
11578
11694
|
toolCallId,
|
|
@@ -11601,7 +11717,7 @@ app3.openapi(toolApprovalRoute, async (c) => {
|
|
|
11601
11717
|
span.setStatus({ code: 1, message: "Tool call not found" });
|
|
11602
11718
|
return c.json({ error: "Tool call not found or already processed" }, 404);
|
|
11603
11719
|
}
|
|
11604
|
-
|
|
11720
|
+
logger21.info({ conversationId, toolCallId, approved }, "Tool approval processed successfully");
|
|
11605
11721
|
span.setStatus({ code: 1, message: "Success" });
|
|
11606
11722
|
return c.json({
|
|
11607
11723
|
success: true,
|
|
@@ -11609,7 +11725,7 @@ app3.openapi(toolApprovalRoute, async (c) => {
|
|
|
11609
11725
|
});
|
|
11610
11726
|
} catch (error) {
|
|
11611
11727
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
11612
|
-
|
|
11728
|
+
logger21.error(
|
|
11613
11729
|
{
|
|
11614
11730
|
error: errorMessage,
|
|
11615
11731
|
stack: error instanceof Error ? error.stack : void 0
|
|
@@ -11630,7 +11746,7 @@ app3.openapi(toolApprovalRoute, async (c) => {
|
|
|
11630
11746
|
});
|
|
11631
11747
|
});
|
|
11632
11748
|
var chatDataStream_default = app3;
|
|
11633
|
-
var
|
|
11749
|
+
var logger22 = getLogger("mcp");
|
|
11634
11750
|
var MockResponseSingleton = class _MockResponseSingleton {
|
|
11635
11751
|
static instance;
|
|
11636
11752
|
mockRes;
|
|
@@ -11684,21 +11800,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
|
|
|
11684
11800
|
id: 0
|
|
11685
11801
|
});
|
|
11686
11802
|
var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
|
|
11687
|
-
|
|
11803
|
+
logger22.info({ sessionId }, "Spoofing initialization message to set transport state");
|
|
11688
11804
|
const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
|
|
11689
11805
|
const mockRes = MockResponseSingleton.getInstance().getMockResponse();
|
|
11690
11806
|
try {
|
|
11691
11807
|
await transport.handleRequest(req, mockRes, spoofInitMessage);
|
|
11692
|
-
|
|
11808
|
+
logger22.info({ sessionId }, "Successfully spoofed initialization");
|
|
11693
11809
|
} catch (spoofError) {
|
|
11694
|
-
|
|
11810
|
+
logger22.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
|
|
11695
11811
|
}
|
|
11696
11812
|
};
|
|
11697
11813
|
var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
|
|
11698
11814
|
const sessionId = req.headers["mcp-session-id"];
|
|
11699
|
-
|
|
11815
|
+
logger22.info({ sessionId }, "Received MCP session ID");
|
|
11700
11816
|
if (!sessionId) {
|
|
11701
|
-
|
|
11817
|
+
logger22.info({ body }, "Missing session ID");
|
|
11702
11818
|
res.writeHead(400).end(
|
|
11703
11819
|
JSON.stringify({
|
|
11704
11820
|
jsonrpc: "2.0",
|
|
@@ -11725,7 +11841,7 @@ var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
|
|
|
11725
11841
|
scopes: { tenantId, projectId },
|
|
11726
11842
|
conversationId: sessionId
|
|
11727
11843
|
});
|
|
11728
|
-
|
|
11844
|
+
logger22.info(
|
|
11729
11845
|
{
|
|
11730
11846
|
sessionId,
|
|
11731
11847
|
conversationFound: !!conversation,
|
|
@@ -11736,7 +11852,7 @@ var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
|
|
|
11736
11852
|
"Conversation lookup result"
|
|
11737
11853
|
);
|
|
11738
11854
|
if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.agentId !== agentId) {
|
|
11739
|
-
|
|
11855
|
+
logger22.info(
|
|
11740
11856
|
{ sessionId, conversationId: conversation?.id },
|
|
11741
11857
|
"MCP session not found or invalid"
|
|
11742
11858
|
);
|
|
@@ -11797,7 +11913,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultS
|
|
|
11797
11913
|
requestId: requestId2,
|
|
11798
11914
|
sseHelper: mcpStreamHelper
|
|
11799
11915
|
});
|
|
11800
|
-
|
|
11916
|
+
logger22.info(
|
|
11801
11917
|
{ result },
|
|
11802
11918
|
`Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
|
|
11803
11919
|
);
|
|
@@ -11881,7 +11997,7 @@ var getServer = async (headers2, executionContext, conversationId, credentialSto
|
|
|
11881
11997
|
dbClient: dbClient_default,
|
|
11882
11998
|
credentialStores
|
|
11883
11999
|
});
|
|
11884
|
-
|
|
12000
|
+
logger22.info(
|
|
11885
12001
|
{
|
|
11886
12002
|
tenantId,
|
|
11887
12003
|
projectId,
|
|
@@ -11943,7 +12059,7 @@ var validateRequestParameters = (c) => {
|
|
|
11943
12059
|
};
|
|
11944
12060
|
var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
|
|
11945
12061
|
const { tenantId, projectId, agentId } = executionContext;
|
|
11946
|
-
|
|
12062
|
+
logger22.info({ body }, "Received initialization request");
|
|
11947
12063
|
const sessionId = getConversationId();
|
|
11948
12064
|
const activeSpan = trace.getActiveSpan();
|
|
11949
12065
|
if (activeSpan) {
|
|
@@ -11999,7 +12115,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
|
|
|
11999
12115
|
}
|
|
12000
12116
|
}
|
|
12001
12117
|
});
|
|
12002
|
-
|
|
12118
|
+
logger22.info(
|
|
12003
12119
|
{ sessionId, conversationId: conversation.id },
|
|
12004
12120
|
"Created MCP session as conversation"
|
|
12005
12121
|
);
|
|
@@ -12008,9 +12124,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
|
|
|
12008
12124
|
});
|
|
12009
12125
|
const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
|
|
12010
12126
|
await server.connect(transport);
|
|
12011
|
-
|
|
12127
|
+
logger22.info({ sessionId }, "Server connected for initialization");
|
|
12012
12128
|
res.setHeader("Mcp-Session-Id", sessionId);
|
|
12013
|
-
|
|
12129
|
+
logger22.info(
|
|
12014
12130
|
{
|
|
12015
12131
|
sessionId,
|
|
12016
12132
|
bodyMethod: body?.method,
|
|
@@ -12019,7 +12135,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
|
|
|
12019
12135
|
"About to handle initialization request"
|
|
12020
12136
|
);
|
|
12021
12137
|
await transport.handleRequest(req, res, body);
|
|
12022
|
-
|
|
12138
|
+
logger22.info({ sessionId }, "Successfully handled initialization request");
|
|
12023
12139
|
return toFetchResponse(res);
|
|
12024
12140
|
});
|
|
12025
12141
|
};
|
|
@@ -12046,8 +12162,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
|
|
|
12046
12162
|
sessionId,
|
|
12047
12163
|
conversation.metadata?.session_data?.mcpProtocolVersion
|
|
12048
12164
|
);
|
|
12049
|
-
|
|
12050
|
-
|
|
12165
|
+
logger22.info({ sessionId }, "Server connected and transport initialized");
|
|
12166
|
+
logger22.info(
|
|
12051
12167
|
{
|
|
12052
12168
|
sessionId,
|
|
12053
12169
|
bodyKeys: Object.keys(body || {}),
|
|
@@ -12061,9 +12177,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
|
|
|
12061
12177
|
);
|
|
12062
12178
|
try {
|
|
12063
12179
|
await transport.handleRequest(req, res, body);
|
|
12064
|
-
|
|
12180
|
+
logger22.info({ sessionId }, "Successfully handled MCP request");
|
|
12065
12181
|
} catch (transportError) {
|
|
12066
|
-
|
|
12182
|
+
logger22.error(
|
|
12067
12183
|
{
|
|
12068
12184
|
sessionId,
|
|
12069
12185
|
error: transportError,
|
|
@@ -12114,13 +12230,13 @@ app4.openapi(
|
|
|
12114
12230
|
}
|
|
12115
12231
|
const { executionContext } = paramValidation;
|
|
12116
12232
|
const body = c.get("requestBody") || {};
|
|
12117
|
-
|
|
12233
|
+
logger22.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
|
|
12118
12234
|
const isInitRequest = body.method === "initialize";
|
|
12119
12235
|
const { req, res } = toReqRes(c.req.raw);
|
|
12120
12236
|
const validatedContext = c.get("validatedContext") || {};
|
|
12121
12237
|
const credentialStores = c.get("credentialStores");
|
|
12122
|
-
|
|
12123
|
-
|
|
12238
|
+
logger22.info({ validatedContext }, "Validated context");
|
|
12239
|
+
logger22.info({ req }, "request");
|
|
12124
12240
|
if (isInitRequest) {
|
|
12125
12241
|
return await handleInitializationRequest(
|
|
12126
12242
|
body,
|
|
@@ -12141,7 +12257,7 @@ app4.openapi(
|
|
|
12141
12257
|
credentialStores
|
|
12142
12258
|
);
|
|
12143
12259
|
} catch (e) {
|
|
12144
|
-
|
|
12260
|
+
logger22.error(
|
|
12145
12261
|
{
|
|
12146
12262
|
error: e instanceof Error ? e.message : e,
|
|
12147
12263
|
stack: e instanceof Error ? e.stack : void 0
|
|
@@ -12153,7 +12269,7 @@ app4.openapi(
|
|
|
12153
12269
|
}
|
|
12154
12270
|
);
|
|
12155
12271
|
app4.get("/", async (c) => {
|
|
12156
|
-
|
|
12272
|
+
logger22.info({}, "Received GET MCP request");
|
|
12157
12273
|
return c.json(
|
|
12158
12274
|
{
|
|
12159
12275
|
jsonrpc: "2.0",
|
|
@@ -12167,7 +12283,7 @@ app4.get("/", async (c) => {
|
|
|
12167
12283
|
);
|
|
12168
12284
|
});
|
|
12169
12285
|
app4.delete("/", async (c) => {
|
|
12170
|
-
|
|
12286
|
+
logger22.info({}, "Received DELETE MCP request");
|
|
12171
12287
|
return c.json(
|
|
12172
12288
|
{
|
|
12173
12289
|
jsonrpc: "2.0",
|
|
@@ -12180,7 +12296,7 @@ app4.delete("/", async (c) => {
|
|
|
12180
12296
|
var mcp_default = app4;
|
|
12181
12297
|
|
|
12182
12298
|
// src/app.ts
|
|
12183
|
-
var
|
|
12299
|
+
var logger23 = getLogger("agents-run-api");
|
|
12184
12300
|
function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
12185
12301
|
const app6 = new OpenAPIHono();
|
|
12186
12302
|
app6.use("*", otel());
|
|
@@ -12199,7 +12315,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
12199
12315
|
const body = await c.req.json();
|
|
12200
12316
|
c.set("requestBody", body);
|
|
12201
12317
|
} catch (error) {
|
|
12202
|
-
|
|
12318
|
+
logger23.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
|
|
12203
12319
|
}
|
|
12204
12320
|
}
|
|
12205
12321
|
return next();
|
|
@@ -12250,8 +12366,8 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
12250
12366
|
if (!isExpectedError) {
|
|
12251
12367
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
12252
12368
|
const errorStack = err instanceof Error ? err.stack : void 0;
|
|
12253
|
-
if (
|
|
12254
|
-
|
|
12369
|
+
if (logger23) {
|
|
12370
|
+
logger23.error(
|
|
12255
12371
|
{
|
|
12256
12372
|
error: err,
|
|
12257
12373
|
message: errorMessage,
|
|
@@ -12263,8 +12379,8 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
12263
12379
|
);
|
|
12264
12380
|
}
|
|
12265
12381
|
} else {
|
|
12266
|
-
if (
|
|
12267
|
-
|
|
12382
|
+
if (logger23) {
|
|
12383
|
+
logger23.error(
|
|
12268
12384
|
{
|
|
12269
12385
|
error: err,
|
|
12270
12386
|
path: c.req.path,
|
|
@@ -12281,8 +12397,8 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
12281
12397
|
const response = err.getResponse();
|
|
12282
12398
|
return response;
|
|
12283
12399
|
} catch (responseError) {
|
|
12284
|
-
if (
|
|
12285
|
-
|
|
12400
|
+
if (logger23) {
|
|
12401
|
+
logger23.error({ error: responseError }, "Error while handling HTTPException response");
|
|
12286
12402
|
}
|
|
12287
12403
|
}
|
|
12288
12404
|
}
|
|
@@ -12316,7 +12432,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
12316
12432
|
app6.use("*", async (c, next) => {
|
|
12317
12433
|
const executionContext = c.get("executionContext");
|
|
12318
12434
|
if (!executionContext) {
|
|
12319
|
-
|
|
12435
|
+
logger23.debug({}, "Empty execution context");
|
|
12320
12436
|
return next();
|
|
12321
12437
|
}
|
|
12322
12438
|
const { tenantId, projectId, agentId } = executionContext;
|
|
@@ -12325,7 +12441,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
12325
12441
|
if (requestBody) {
|
|
12326
12442
|
conversationId = requestBody.conversationId;
|
|
12327
12443
|
if (!conversationId) {
|
|
12328
|
-
|
|
12444
|
+
logger23.debug({ requestBody }, "No conversation ID found in request body");
|
|
12329
12445
|
}
|
|
12330
12446
|
}
|
|
12331
12447
|
const entries = Object.fromEntries(
|
|
@@ -12340,7 +12456,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
12340
12456
|
})
|
|
12341
12457
|
);
|
|
12342
12458
|
if (!Object.keys(entries).length) {
|
|
12343
|
-
|
|
12459
|
+
logger23.debug({}, "Empty entries for baggage");
|
|
12344
12460
|
return next();
|
|
12345
12461
|
}
|
|
12346
12462
|
const bag = Object.entries(entries).reduce(
|
|
@@ -12394,6 +12510,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
12394
12510
|
}
|
|
12395
12511
|
|
|
12396
12512
|
// src/index.ts
|
|
12513
|
+
defaultSDK.start();
|
|
12397
12514
|
var defaultConfig = {
|
|
12398
12515
|
port: 3003,
|
|
12399
12516
|
serverOptions: {
|