@inkeep/agents-run-api 0.37.0 → 0.37.2

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/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import { flushBatchProcessor } from './chunk-2LBNQ773.js';
2
- import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-OAAX46OE.js';
3
- import { dbClient_default } from './chunk-D3AB2AZW.js';
4
- import { env } from './chunk-HUZGFAUJ.js';
1
+ import { flushBatchProcessor } from './chunk-QOUOKHYQ.js';
2
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-BQB27EXW.js';
3
+ import { dbClient_default } from './chunk-W6UIBREL.js';
4
+ import { env } from './chunk-CDYXP4BN.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-IVALDC72.js';
7
- import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, generateId, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, createTask, getTask, updateTask, setSpanWithError, AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT, updateConversation, handleApiError, TaskState, getAgentById, getProject, setActiveAgentForThread, getConversation, getRelatedAgentsForAgent, getExternalAgentsForSubAgent, getTeamAgentsForSubAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, CONVERSATION_HISTORY_DEFAULT_LIMIT, 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-SUUSOBLI.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, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, 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 as z$1 } from '@hono/zod-openapi';
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,15 +14,8 @@ 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
- import { createAnthropic, anthropic } from '@ai-sdk/anthropic';
21
- import { createGateway, gateway } from '@ai-sdk/gateway';
22
- import { createGoogleGenerativeAI, google } from '@ai-sdk/google';
23
- import { createOpenAI, openai } from '@ai-sdk/openai';
24
- import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
25
- import { createOpenRouter, openrouter } from '@openrouter/ai-sdk-provider';
26
19
  import jmespath from 'jmespath';
27
20
  import Ajv from 'ajv';
28
21
  import destr from 'destr';
@@ -634,6 +627,21 @@ async function handleMessageSend(c, agent, request) {
634
627
  });
635
628
  }
636
629
  }
630
+ if (result.status.state === TaskState.Failed) {
631
+ const isConnectionRefused = result.status.type === "connection_refused";
632
+ if (isConnectionRefused) {
633
+ return c.json({
634
+ jsonrpc: "2.0",
635
+ error: {
636
+ code: -32603,
637
+ message: result.status.message || "Agent execution failed",
638
+ data: {
639
+ type: "connection_refused"
640
+ }
641
+ }
642
+ });
643
+ }
644
+ }
637
645
  const taskStatus = {
638
646
  state: result.status.state,
639
647
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -981,269 +989,7 @@ async function handleTasksResubscribe(c, agent, request) {
981
989
  });
982
990
  }
983
991
  }
984
- var logger3 = getLogger("ModelFactory");
985
- var nimDefault = createOpenAICompatible({
986
- name: "nim",
987
- baseURL: "https://integrate.api.nvidia.com/v1",
988
- headers: {
989
- Authorization: `Bearer ${process.env.NIM_API_KEY}`
990
- }
991
- });
992
- var ModelFactory = class _ModelFactory {
993
- /**
994
- * Create a provider instance with custom configuration
995
- */
996
- static createProvider(provider, config) {
997
- switch (provider) {
998
- case "anthropic":
999
- return createAnthropic(config);
1000
- case "openai":
1001
- return createOpenAI(config);
1002
- case "google":
1003
- return createGoogleGenerativeAI(config);
1004
- case "openrouter":
1005
- return {
1006
- ...createOpenRouter(config),
1007
- textEmbeddingModel: () => {
1008
- throw new Error("OpenRouter does not support text embeddings");
1009
- },
1010
- imageModel: () => {
1011
- throw new Error("OpenRouter does not support image generation");
1012
- }
1013
- };
1014
- case "gateway":
1015
- return createGateway(config);
1016
- case "nim": {
1017
- const nimConfig = {
1018
- name: "nim",
1019
- baseURL: "https://integrate.api.nvidia.com/v1",
1020
- headers: {
1021
- Authorization: `Bearer ${process.env.NIM_API_KEY}`
1022
- },
1023
- ...config
1024
- };
1025
- return createOpenAICompatible(nimConfig);
1026
- }
1027
- case "custom": {
1028
- if (!config.baseURL && !config.baseUrl) {
1029
- throw new Error(
1030
- "Custom provider requires baseURL. Please provide it in providerOptions.baseURL or providerOptions.baseUrl"
1031
- );
1032
- }
1033
- const customConfig = {
1034
- name: "custom",
1035
- baseURL: config.baseURL || config.baseUrl,
1036
- headers: {
1037
- ...process.env.CUSTOM_LLM_API_KEY && {
1038
- Authorization: `Bearer ${process.env.CUSTOM_LLM_API_KEY}`
1039
- },
1040
- ...config.headers || {}
1041
- },
1042
- ...config
1043
- };
1044
- logger3.info(
1045
- {
1046
- config: {
1047
- baseURL: customConfig.baseURL,
1048
- hasApiKey: !!process.env.CUSTOM_LLM_API_KEY,
1049
- apiKeyPrefix: process.env.CUSTOM_LLM_API_KEY?.substring(0, 10) + "...",
1050
- headers: Object.keys(customConfig.headers || {})
1051
- }
1052
- },
1053
- "Creating custom OpenAI-compatible provider"
1054
- );
1055
- return createOpenAICompatible(customConfig);
1056
- }
1057
- default:
1058
- throw new Error(`Unsupported provider: ${provider}`);
1059
- }
1060
- }
1061
- /**
1062
- * Extract provider configuration from providerOptions
1063
- * Only includes settings that go to the provider constructor (baseURL, apiKey, etc.)
1064
- */
1065
- static extractProviderConfig(providerOptions) {
1066
- if (!providerOptions) {
1067
- return {};
1068
- }
1069
- const providerConfig = {};
1070
- if (providerOptions.baseUrl || providerOptions.baseURL) {
1071
- providerConfig.baseURL = providerOptions.baseUrl || providerOptions.baseURL;
1072
- }
1073
- if (providerOptions.headers) {
1074
- providerConfig.headers = providerOptions.headers;
1075
- }
1076
- if (providerOptions.gateway) {
1077
- Object.assign(providerConfig, providerOptions.gateway);
1078
- }
1079
- if (providerOptions.nim) {
1080
- Object.assign(providerConfig, providerOptions.nim);
1081
- }
1082
- if (providerOptions.custom) {
1083
- Object.assign(providerConfig, providerOptions.custom);
1084
- }
1085
- return providerConfig;
1086
- }
1087
- /**
1088
- * Create a language model instance from configuration
1089
- * Throws error if no config provided - models must be configured at project level
1090
- */
1091
- static createModel(config) {
1092
- if (!config?.model?.trim()) {
1093
- throw new Error(
1094
- "Model configuration is required. Please configure models at the project level."
1095
- );
1096
- }
1097
- const modelSettings = config;
1098
- if (!modelSettings.model) {
1099
- throw new Error("Model configuration is required");
1100
- }
1101
- const modelString = modelSettings.model.trim();
1102
- const { provider, modelName } = _ModelFactory.parseModelString(modelString);
1103
- logger3.debug(
1104
- {
1105
- provider,
1106
- model: modelName,
1107
- fullModelString: modelSettings.model,
1108
- hasProviderOptions: !!modelSettings.providerOptions
1109
- },
1110
- "Creating language model from config"
1111
- );
1112
- const providerConfig = _ModelFactory.extractProviderConfig(modelSettings.providerOptions);
1113
- if (Object.keys(providerConfig).length > 0) {
1114
- logger3.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
1115
- const customProvider = _ModelFactory.createProvider(provider, providerConfig);
1116
- return customProvider.languageModel(modelName);
1117
- }
1118
- switch (provider) {
1119
- case "anthropic":
1120
- return anthropic(modelName);
1121
- case "openai":
1122
- return openai(modelName);
1123
- case "google":
1124
- return google(modelName);
1125
- case "openrouter":
1126
- return openrouter(modelName);
1127
- case "gateway":
1128
- return gateway(modelName);
1129
- case "nim":
1130
- return nimDefault(modelName);
1131
- case "custom":
1132
- throw new Error(
1133
- "Custom provider requires configuration. Please provide baseURL in providerOptions.custom.baseURL or providerOptions.baseURL"
1134
- );
1135
- default:
1136
- throw new Error(
1137
- `Unsupported provider: ${provider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`
1138
- );
1139
- }
1140
- }
1141
- /**
1142
- * Built-in providers that have special handling
1143
- */
1144
- static BUILT_IN_PROVIDERS = [
1145
- "anthropic",
1146
- "openai",
1147
- "google",
1148
- "openrouter",
1149
- "gateway",
1150
- "nim",
1151
- "custom"
1152
- ];
1153
- /**
1154
- * Parse model string to extract provider and model name
1155
- * Examples: "anthropic/claude-sonnet-4" -> { provider: "anthropic", modelName: "claude-sonnet-4" }
1156
- * "openrouter/anthropic/claude-sonnet-4" -> { provider: "openrouter", modelName: "anthropic/claude-sonnet-4" }
1157
- * "claude-sonnet-4" -> { provider: "anthropic", modelName: "claude-sonnet-4" } (default to anthropic)
1158
- */
1159
- static parseModelString(modelString) {
1160
- if (modelString.includes("/")) {
1161
- const [provider, ...modelParts] = modelString.split("/");
1162
- const normalizedProvider = provider.toLowerCase();
1163
- if (!_ModelFactory.BUILT_IN_PROVIDERS.includes(normalizedProvider)) {
1164
- throw new Error(
1165
- `Unsupported provider: ${normalizedProvider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`
1166
- );
1167
- }
1168
- return {
1169
- provider: normalizedProvider,
1170
- modelName: modelParts.join("/")
1171
- // In case model name has slashes
1172
- };
1173
- }
1174
- throw new Error(`No provider specified in model string: ${modelString}`);
1175
- }
1176
- /**
1177
- * Get generation parameters from provider options
1178
- * These are parameters that get passed to generateText/streamText calls
1179
- */
1180
- static getGenerationParams(providerOptions) {
1181
- if (!providerOptions) {
1182
- return {};
1183
- }
1184
- const excludedKeys = [
1185
- "apiKey",
1186
- "baseURL",
1187
- "baseUrl",
1188
- "maxDuration",
1189
- "headers",
1190
- "gateway",
1191
- "nim",
1192
- "custom"
1193
- ];
1194
- const params = {};
1195
- for (const [key, value] of Object.entries(providerOptions)) {
1196
- if (!excludedKeys.includes(key) && value !== void 0) {
1197
- params[key] = value;
1198
- }
1199
- }
1200
- return params;
1201
- }
1202
- /**
1203
- * Prepare complete generation configuration from model settings
1204
- * Returns model instance and generation parameters ready to spread into generateText/streamText
1205
- * Includes maxDuration if specified in provider options (in seconds, following Vercel standard)
1206
- */
1207
- static prepareGenerationConfig(modelSettings) {
1208
- const modelString = modelSettings?.model?.trim();
1209
- const model = _ModelFactory.createModel({
1210
- model: modelString,
1211
- providerOptions: modelSettings?.providerOptions
1212
- });
1213
- const generationParams = _ModelFactory.getGenerationParams(modelSettings?.providerOptions);
1214
- const maxDuration = modelSettings?.providerOptions?.maxDuration;
1215
- return {
1216
- model,
1217
- ...generationParams,
1218
- ...maxDuration !== void 0 && { maxDuration }
1219
- };
1220
- }
1221
- /**
1222
- * Validate model settingsuration
1223
- * Basic validation only - let AI SDK handle parameter-specific validation
1224
- */
1225
- static validateConfig(config) {
1226
- const errors = [];
1227
- if (!config.model) {
1228
- errors.push("Model name is required");
1229
- }
1230
- if (config.providerOptions) {
1231
- if (config.providerOptions.apiKey) {
1232
- errors.push(
1233
- "API keys should not be stored in provider options. Use environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY) or credential store instead."
1234
- );
1235
- }
1236
- if (config.providerOptions.maxDuration !== void 0) {
1237
- const maxDuration = config.providerOptions.maxDuration;
1238
- if (typeof maxDuration !== "number" || maxDuration <= 0) {
1239
- errors.push("maxDuration must be a positive number (in seconds)");
1240
- }
1241
- }
1242
- }
1243
- return errors;
1244
- }
1245
- };
1246
- var logger4 = getLogger("ToolSessionManager");
992
+ var logger3 = getLogger("ToolSessionManager");
1247
993
  var ToolSessionManager = class _ToolSessionManager {
1248
994
  static instance;
1249
995
  sessions = /* @__PURE__ */ new Map();
@@ -1277,7 +1023,7 @@ var ToolSessionManager = class _ToolSessionManager {
1277
1023
  createdAt: Date.now()
1278
1024
  };
1279
1025
  this.sessions.set(sessionId, session);
1280
- logger4.debug(
1026
+ logger3.debug(
1281
1027
  {
1282
1028
  sessionId,
1283
1029
  tenantId,
@@ -1295,10 +1041,10 @@ var ToolSessionManager = class _ToolSessionManager {
1295
1041
  */
1296
1042
  ensureAgentSession(sessionId, tenantId, projectId, contextId, taskId) {
1297
1043
  if (this.sessions.has(sessionId)) {
1298
- logger4.debug({ sessionId }, "Agent session already exists, reusing");
1044
+ logger3.debug({ sessionId }, "Agent session already exists, reusing");
1299
1045
  return sessionId;
1300
1046
  }
1301
- logger4.debug(
1047
+ logger3.debug(
1302
1048
  { sessionId, tenantId, contextId, taskId },
1303
1049
  "Creating new agent-scoped tool session"
1304
1050
  );
@@ -1310,7 +1056,7 @@ var ToolSessionManager = class _ToolSessionManager {
1310
1056
  recordToolResult(sessionId, toolResult) {
1311
1057
  const session = this.sessions.get(sessionId);
1312
1058
  if (!session) {
1313
- logger4.warn(
1059
+ logger3.warn(
1314
1060
  {
1315
1061
  sessionId,
1316
1062
  toolCallId: toolResult.toolCallId,
@@ -1322,7 +1068,7 @@ var ToolSessionManager = class _ToolSessionManager {
1322
1068
  return;
1323
1069
  }
1324
1070
  session.toolResults.set(toolResult.toolCallId, toolResult);
1325
- logger4.debug(
1071
+ logger3.debug(
1326
1072
  {
1327
1073
  sessionId,
1328
1074
  toolCallId: toolResult.toolCallId,
@@ -1337,7 +1083,7 @@ var ToolSessionManager = class _ToolSessionManager {
1337
1083
  getToolResult(sessionId, toolCallId) {
1338
1084
  const session = this.sessions.get(sessionId);
1339
1085
  if (!session) {
1340
- logger4.warn(
1086
+ logger3.warn(
1341
1087
  {
1342
1088
  sessionId,
1343
1089
  toolCallId,
@@ -1350,7 +1096,7 @@ var ToolSessionManager = class _ToolSessionManager {
1350
1096
  }
1351
1097
  const result = session.toolResults.get(toolCallId);
1352
1098
  if (!result) {
1353
- logger4.warn(
1099
+ logger3.warn(
1354
1100
  {
1355
1101
  sessionId,
1356
1102
  toolCallId,
@@ -1360,7 +1106,7 @@ var ToolSessionManager = class _ToolSessionManager {
1360
1106
  "Tool result not found"
1361
1107
  );
1362
1108
  } else {
1363
- logger4.debug(
1109
+ logger3.debug(
1364
1110
  {
1365
1111
  sessionId,
1366
1112
  toolCallId,
@@ -1399,10 +1145,10 @@ var ToolSessionManager = class _ToolSessionManager {
1399
1145
  }
1400
1146
  for (const sessionId of expiredSessions) {
1401
1147
  this.sessions.delete(sessionId);
1402
- logger4.debug({ sessionId }, "Cleaned up expired tool session");
1148
+ logger3.debug({ sessionId }, "Cleaned up expired tool session");
1403
1149
  }
1404
1150
  if (expiredSessions.length > 0) {
1405
- logger4.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
1151
+ logger3.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
1406
1152
  }
1407
1153
  }
1408
1154
  };
@@ -1470,7 +1216,7 @@ function extractFullFields(schema) {
1470
1216
  }
1471
1217
 
1472
1218
  // src/services/ArtifactService.ts
1473
- var logger6 = getLogger("ArtifactService");
1219
+ var logger5 = getLogger("ArtifactService");
1474
1220
  var ArtifactService = class _ArtifactService {
1475
1221
  constructor(context) {
1476
1222
  this.context = context;
@@ -1503,7 +1249,7 @@ var ArtifactService = class _ArtifactService {
1503
1249
  id: taskId
1504
1250
  });
1505
1251
  if (!task) {
1506
- logger6.warn({ taskId }, "Task not found when fetching artifacts");
1252
+ logger5.warn({ taskId }, "Task not found when fetching artifacts");
1507
1253
  continue;
1508
1254
  }
1509
1255
  const taskArtifacts = await getLedgerArtifacts(dbClient_default)({
@@ -1521,7 +1267,7 @@ var ArtifactService = class _ArtifactService {
1521
1267
  }
1522
1268
  }
1523
1269
  } catch (error) {
1524
- logger6.error({ error, contextId }, "Error loading context artifacts");
1270
+ logger5.error({ error, contextId }, "Error loading context artifacts");
1525
1271
  }
1526
1272
  return artifacts;
1527
1273
  }
@@ -1530,12 +1276,12 @@ var ArtifactService = class _ArtifactService {
1530
1276
  */
1531
1277
  async createArtifact(request, subAgentId) {
1532
1278
  if (!this.context.sessionId) {
1533
- logger6.warn({ request }, "No session ID available for artifact creation");
1279
+ logger5.warn({ request }, "No session ID available for artifact creation");
1534
1280
  return null;
1535
1281
  }
1536
1282
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
1537
1283
  if (!toolResult) {
1538
- logger6.warn(
1284
+ logger5.warn(
1539
1285
  { request, sessionId: this.context.sessionId },
1540
1286
  "Tool result not found for artifact"
1541
1287
  );
@@ -1551,7 +1297,7 @@ var ArtifactService = class _ArtifactService {
1551
1297
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
1552
1298
  }
1553
1299
  if (!selectedData) {
1554
- logger6.warn(
1300
+ logger5.warn(
1555
1301
  {
1556
1302
  request,
1557
1303
  baseSelector: request.baseSelector
@@ -1622,7 +1368,7 @@ var ArtifactService = class _ArtifactService {
1622
1368
  );
1623
1369
  return artifactData;
1624
1370
  } catch (error) {
1625
- logger6.error({ error, request }, "Failed to create artifact");
1371
+ logger5.error({ error, request }, "Failed to create artifact");
1626
1372
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
1627
1373
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
1628
1374
  }
@@ -1651,7 +1397,7 @@ var ArtifactService = class _ArtifactService {
1651
1397
  }
1652
1398
  try {
1653
1399
  if (!this.context.projectId || !this.context.taskId) {
1654
- logger6.warn(
1400
+ logger5.warn(
1655
1401
  { artifactId, toolCallId },
1656
1402
  "No projectId or taskId available for artifact lookup"
1657
1403
  );
@@ -1675,7 +1421,7 @@ var ArtifactService = class _ArtifactService {
1675
1421
  return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
1676
1422
  }
1677
1423
  } catch (error) {
1678
- logger6.warn(
1424
+ logger5.warn(
1679
1425
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1680
1426
  "Failed to fetch artifact"
1681
1427
  );
@@ -1706,7 +1452,7 @@ var ArtifactService = class _ArtifactService {
1706
1452
  }
1707
1453
  try {
1708
1454
  if (!this.context.projectId || !this.context.taskId) {
1709
- logger6.warn(
1455
+ logger5.warn(
1710
1456
  { artifactId, toolCallId },
1711
1457
  "No projectId or taskId available for artifact lookup"
1712
1458
  );
@@ -1730,7 +1476,7 @@ var ArtifactService = class _ArtifactService {
1730
1476
  return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
1731
1477
  }
1732
1478
  } catch (error) {
1733
- logger6.warn(
1479
+ logger5.warn(
1734
1480
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1735
1481
  "Failed to fetch artifact"
1736
1482
  );
@@ -1747,7 +1493,7 @@ var ArtifactService = class _ArtifactService {
1747
1493
  data = artifact.parts?.[0]?.data;
1748
1494
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1749
1495
  dataSource = "parts[0].data (fallback)";
1750
- logger6.debug(
1496
+ logger5.debug(
1751
1497
  { artifactId, toolCallId, dataSource },
1752
1498
  "Using fallback data source for artifact summary"
1753
1499
  );
@@ -1755,14 +1501,14 @@ var ArtifactService = class _ArtifactService {
1755
1501
  data = artifact.data;
1756
1502
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1757
1503
  dataSource = "artifact.data (fallback)";
1758
- logger6.debug(
1504
+ logger5.debug(
1759
1505
  { artifactId, toolCallId, dataSource },
1760
1506
  "Using fallback data source for artifact summary"
1761
1507
  );
1762
1508
  } else {
1763
1509
  data = {};
1764
1510
  dataSource = "empty (no data found)";
1765
- logger6.warn(
1511
+ logger5.warn(
1766
1512
  {
1767
1513
  artifactId,
1768
1514
  toolCallId,
@@ -1799,7 +1545,7 @@ var ArtifactService = class _ArtifactService {
1799
1545
  data = artifact.parts?.[0]?.data;
1800
1546
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1801
1547
  dataSource = "parts[0].data (fallback)";
1802
- logger6.debug(
1548
+ logger5.debug(
1803
1549
  { artifactId, toolCallId, dataSource },
1804
1550
  "Using fallback data source for artifact full data"
1805
1551
  );
@@ -1807,14 +1553,14 @@ var ArtifactService = class _ArtifactService {
1807
1553
  data = artifact.data;
1808
1554
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1809
1555
  dataSource = "artifact.data (fallback)";
1810
- logger6.debug(
1556
+ logger5.debug(
1811
1557
  { artifactId, toolCallId, dataSource },
1812
1558
  "Using fallback data source for artifact full data"
1813
1559
  );
1814
1560
  } else {
1815
1561
  data = {};
1816
1562
  dataSource = "empty (no data found)";
1817
- logger6.warn(
1563
+ logger5.warn(
1818
1564
  {
1819
1565
  artifactId,
1820
1566
  toolCallId,
@@ -1868,7 +1614,7 @@ var ArtifactService = class _ArtifactService {
1868
1614
  const error = new Error(
1869
1615
  `Cannot save artifact: Missing required fields [${summaryValidation.missingRequired.join(", ")}] for '${artifactType}' schema. Required: [${summaryValidation.missingRequired.join(", ")}]. Found: [${summaryValidation.actualFields.join(", ")}]. Consider using a different artifact component type that matches your data structure.`
1870
1616
  );
1871
- logger6.error(
1617
+ logger5.error(
1872
1618
  {
1873
1619
  artifactId,
1874
1620
  artifactType,
@@ -1881,7 +1627,7 @@ var ArtifactService = class _ArtifactService {
1881
1627
  throw error;
1882
1628
  }
1883
1629
  if (!summaryValidation.hasExpectedFields || summaryValidation.extraFields.length > 0) {
1884
- logger6.warn(
1630
+ logger5.warn(
1885
1631
  {
1886
1632
  artifactId,
1887
1633
  artifactType,
@@ -1895,7 +1641,7 @@ var ArtifactService = class _ArtifactService {
1895
1641
  );
1896
1642
  }
1897
1643
  if (!fullValidation.hasExpectedFields || fullValidation.extraFields.length > 0) {
1898
- logger6.warn(
1644
+ logger5.warn(
1899
1645
  {
1900
1646
  artifactId,
1901
1647
  artifactType,
@@ -1967,7 +1713,7 @@ var ArtifactService = class _ArtifactService {
1967
1713
  }
1968
1714
  );
1969
1715
  } else {
1970
- logger6.warn(
1716
+ logger5.warn(
1971
1717
  {
1972
1718
  artifactId: request.artifactId,
1973
1719
  hasStreamRequestId: !!this.context.streamRequestId,
@@ -2042,7 +1788,7 @@ var ArtifactService = class _ArtifactService {
2042
1788
  summaryData = this.filterBySchema(artifact.data, previewSchema);
2043
1789
  fullData = this.filterBySchema(artifact.data, fullSchema);
2044
1790
  } catch (error) {
2045
- logger6.warn(
1791
+ logger5.warn(
2046
1792
  {
2047
1793
  artifactType: artifact.type,
2048
1794
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2080,7 +1826,7 @@ var ArtifactService = class _ArtifactService {
2080
1826
  artifact: artifactToSave
2081
1827
  });
2082
1828
  if (!result.created && result.existing) {
2083
- logger6.debug(
1829
+ logger5.debug(
2084
1830
  {
2085
1831
  artifactId: artifact.artifactId,
2086
1832
  taskId: this.context.taskId
@@ -2140,7 +1886,7 @@ var ArtifactService = class _ArtifactService {
2140
1886
  extracted[fieldName] = this.cleanEscapedContent(rawValue);
2141
1887
  }
2142
1888
  } catch (error) {
2143
- logger6.warn(
1889
+ logger5.warn(
2144
1890
  { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
2145
1891
  "Failed to extract schema field"
2146
1892
  );
@@ -2169,7 +1915,7 @@ var ArtifactService = class _ArtifactService {
2169
1915
  };
2170
1916
 
2171
1917
  // src/services/ArtifactParser.ts
2172
- var logger7 = getLogger("ArtifactParser");
1918
+ var logger6 = getLogger("ArtifactParser");
2173
1919
  var ArtifactParser = class _ArtifactParser {
2174
1920
  static ARTIFACT_CHECK_REGEX = /<artifact:ref\s+(?=.*id=['"][^'"]+['"])(?=.*tool=['"][^'"]+['"])[^>]*\/>/;
2175
1921
  static ATTR_REGEX = /(\w+)="([^"]*)"|(\w+)='([^']*)'|(\w+)=({[^}]+})/g;
@@ -2280,7 +2026,7 @@ var ArtifactParser = class _ArtifactParser {
2280
2026
  attrs[key] = value;
2281
2027
  }
2282
2028
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
2283
- logger7.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2029
+ logger6.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2284
2030
  return null;
2285
2031
  }
2286
2032
  return {
@@ -2341,7 +2087,7 @@ var ArtifactParser = class _ArtifactParser {
2341
2087
  `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
2342
2088
  );
2343
2089
  processedText = processedText.replace(annotation.raw, "");
2344
- logger7.warn(
2090
+ logger6.warn(
2345
2091
  { annotation, artifactData },
2346
2092
  "Removed failed artifact:create annotation from output"
2347
2093
  );
@@ -2352,11 +2098,11 @@ var ArtifactParser = class _ArtifactParser {
2352
2098
  if (annotation.raw) {
2353
2099
  processedText = processedText.replace(annotation.raw, "");
2354
2100
  }
2355
- logger7.error({ annotation, error }, "Failed to extract artifact from create annotation");
2101
+ logger6.error({ annotation, error }, "Failed to extract artifact from create annotation");
2356
2102
  }
2357
2103
  }
2358
2104
  if (failedAnnotations.length > 0) {
2359
- logger7.warn(
2105
+ logger6.warn(
2360
2106
  {
2361
2107
  failedCount: failedAnnotations.length,
2362
2108
  failures: failedAnnotations
@@ -2540,7 +2286,7 @@ var ArtifactParser = class _ArtifactParser {
2540
2286
  };
2541
2287
 
2542
2288
  // src/services/AgentSession.ts
2543
- var logger8 = getLogger("AgentSession");
2289
+ var logger7 = getLogger("AgentSession");
2544
2290
  var AgentSession = class {
2545
2291
  // Whether to send data operations
2546
2292
  constructor(sessionId, messageId, agentId, tenantId, projectId, contextId) {
@@ -2550,7 +2296,7 @@ var AgentSession = class {
2550
2296
  this.tenantId = tenantId;
2551
2297
  this.projectId = projectId;
2552
2298
  this.contextId = contextId;
2553
- logger8.debug({ sessionId, messageId, agentId }, "AgentSession created");
2299
+ logger7.debug({ sessionId, messageId, agentId }, "AgentSession created");
2554
2300
  if (tenantId && projectId) {
2555
2301
  toolSessionManager.createSessionWithId(
2556
2302
  sessionId,
@@ -2607,7 +2353,7 @@ var AgentSession = class {
2607
2353
  */
2608
2354
  enableEmitOperations() {
2609
2355
  this.isEmitOperations = true;
2610
- logger8.info(
2356
+ logger7.info(
2611
2357
  { sessionId: this.sessionId },
2612
2358
  "\u{1F50D} DEBUG: Emit operations enabled for AgentSession"
2613
2359
  );
@@ -2616,6 +2362,7 @@ var AgentSession = class {
2616
2362
  * Send data operation to stream when emit operations is enabled
2617
2363
  */
2618
2364
  async sendDataOperation(event) {
2365
+ console.log("sendDataOperation called with event", Date.now());
2619
2366
  try {
2620
2367
  const streamHelper = getStreamHelper(this.sessionId);
2621
2368
  if (streamHelper) {
@@ -2631,7 +2378,7 @@ var AgentSession = class {
2631
2378
  await streamHelper.writeOperation(formattedOperation);
2632
2379
  }
2633
2380
  } catch (error) {
2634
- logger8.error(
2381
+ logger7.error(
2635
2382
  {
2636
2383
  sessionId: this.sessionId,
2637
2384
  eventType: event.eventType,
@@ -2690,7 +2437,7 @@ var AgentSession = class {
2690
2437
  if (this.statusUpdateState.config.timeInSeconds) {
2691
2438
  this.statusUpdateTimer = setInterval(async () => {
2692
2439
  if (!this.statusUpdateState || this.isEnded) {
2693
- logger8.debug(
2440
+ logger7.debug(
2694
2441
  { sessionId: this.sessionId },
2695
2442
  "Timer triggered but session already cleaned up or ended"
2696
2443
  );
@@ -2702,7 +2449,7 @@ var AgentSession = class {
2702
2449
  }
2703
2450
  await this.checkAndSendTimeBasedUpdate();
2704
2451
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
2705
- logger8.info(
2452
+ logger7.info(
2706
2453
  {
2707
2454
  sessionId: this.sessionId,
2708
2455
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -2726,7 +2473,7 @@ var AgentSession = class {
2726
2473
  this.sendDataOperation(dataOpEvent);
2727
2474
  }
2728
2475
  if (this.isEnded) {
2729
- logger8.debug(
2476
+ logger7.debug(
2730
2477
  {
2731
2478
  sessionId: this.sessionId,
2732
2479
  eventType,
@@ -2748,7 +2495,7 @@ var AgentSession = class {
2748
2495
  if (artifactData.pendingGeneration) {
2749
2496
  const artifactId = artifactData.artifactId;
2750
2497
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2751
- logger8.warn(
2498
+ logger7.warn(
2752
2499
  {
2753
2500
  sessionId: this.sessionId,
2754
2501
  artifactId,
@@ -2770,7 +2517,7 @@ var AgentSession = class {
2770
2517
  this.artifactProcessingErrors.set(artifactId, errorCount);
2771
2518
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2772
2519
  this.pendingArtifacts.delete(artifactId);
2773
- logger8.error(
2520
+ logger7.error(
2774
2521
  {
2775
2522
  sessionId: this.sessionId,
2776
2523
  artifactId,
@@ -2782,7 +2529,7 @@ var AgentSession = class {
2782
2529
  "Artifact processing failed after max retries, giving up"
2783
2530
  );
2784
2531
  } else {
2785
- logger8.warn(
2532
+ logger7.warn(
2786
2533
  {
2787
2534
  sessionId: this.sessionId,
2788
2535
  artifactId,
@@ -2805,14 +2552,14 @@ var AgentSession = class {
2805
2552
  */
2806
2553
  checkStatusUpdates() {
2807
2554
  if (this.isEnded) {
2808
- logger8.debug(
2555
+ logger7.debug(
2809
2556
  { sessionId: this.sessionId },
2810
2557
  "Session has ended - skipping status update check"
2811
2558
  );
2812
2559
  return;
2813
2560
  }
2814
2561
  if (!this.statusUpdateState) {
2815
- logger8.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2562
+ logger7.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2816
2563
  return;
2817
2564
  }
2818
2565
  const statusUpdateState = this.statusUpdateState;
@@ -2823,11 +2570,11 @@ var AgentSession = class {
2823
2570
  */
2824
2571
  async checkAndSendTimeBasedUpdate() {
2825
2572
  if (this.isEnded) {
2826
- logger8.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2573
+ logger7.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2827
2574
  return;
2828
2575
  }
2829
2576
  if (!this.statusUpdateState) {
2830
- logger8.debug(
2577
+ logger7.debug(
2831
2578
  { sessionId: this.sessionId },
2832
2579
  "No status updates configured for time-based check"
2833
2580
  );
@@ -2840,7 +2587,7 @@ var AgentSession = class {
2840
2587
  try {
2841
2588
  await this.generateAndSendUpdate();
2842
2589
  } catch (error) {
2843
- logger8.error(
2590
+ logger7.error(
2844
2591
  {
2845
2592
  sessionId: this.sessionId,
2846
2593
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2943,29 +2690,29 @@ var AgentSession = class {
2943
2690
  */
2944
2691
  async generateAndSendUpdate() {
2945
2692
  if (this.isEnded) {
2946
- logger8.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2693
+ logger7.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2947
2694
  return;
2948
2695
  }
2949
2696
  if (this.isTextStreaming) {
2950
- logger8.debug(
2697
+ logger7.debug(
2951
2698
  { sessionId: this.sessionId },
2952
2699
  "Text is currently streaming - skipping status update"
2953
2700
  );
2954
2701
  return;
2955
2702
  }
2956
2703
  if (this.isGeneratingUpdate) {
2957
- logger8.debug(
2704
+ logger7.debug(
2958
2705
  { sessionId: this.sessionId },
2959
2706
  "Update already in progress - skipping duplicate generation"
2960
2707
  );
2961
2708
  return;
2962
2709
  }
2963
2710
  if (!this.statusUpdateState) {
2964
- logger8.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2711
+ logger7.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2965
2712
  return;
2966
2713
  }
2967
2714
  if (!this.agentId) {
2968
- logger8.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
2715
+ logger7.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
2969
2716
  return;
2970
2717
  }
2971
2718
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -2977,7 +2724,7 @@ var AgentSession = class {
2977
2724
  try {
2978
2725
  const streamHelper = getStreamHelper(this.sessionId);
2979
2726
  if (!streamHelper) {
2980
- logger8.warn(
2727
+ logger7.warn(
2981
2728
  { sessionId: this.sessionId },
2982
2729
  "No stream helper found - cannot send status update"
2983
2730
  );
@@ -2997,7 +2744,7 @@ var AgentSession = class {
2997
2744
  if (result.summaries && result.summaries.length > 0) {
2998
2745
  for (const summary of result.summaries) {
2999
2746
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
3000
- logger8.warn(
2747
+ logger7.warn(
3001
2748
  {
3002
2749
  sessionId: this.sessionId,
3003
2750
  summary
@@ -3034,7 +2781,7 @@ var AgentSession = class {
3034
2781
  this.statusUpdateState.lastEventCount = this.events.length;
3035
2782
  }
3036
2783
  } catch (error) {
3037
- logger8.error(
2784
+ logger7.error(
3038
2785
  {
3039
2786
  sessionId: this.sessionId,
3040
2787
  error: error instanceof Error ? error.message : "Unknown error",
@@ -3072,7 +2819,7 @@ var AgentSession = class {
3072
2819
  this.releaseUpdateLock();
3073
2820
  }
3074
2821
  } catch (error) {
3075
- logger8.error(
2822
+ logger7.error(
3076
2823
  {
3077
2824
  sessionId: this.sessionId,
3078
2825
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3151,7 +2898,7 @@ User's Question/Context:
3151
2898
  ${conversationHistory}
3152
2899
  ` : "";
3153
2900
  } catch (error) {
3154
- logger8.warn(
2901
+ logger7.warn(
3155
2902
  { sessionId: this.sessionId, error },
3156
2903
  "Failed to fetch conversation history for structured status update"
3157
2904
  );
@@ -3262,10 +3009,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3262
3009
  }
3263
3010
  });
3264
3011
  const result = object;
3265
- logger8.info({ result: JSON.stringify(result) }, "DEBUG: Result");
3012
+ logger7.info({ result: JSON.stringify(result) }, "DEBUG: Result");
3266
3013
  const summaries = [];
3267
3014
  for (const [componentId, data] of Object.entries(result)) {
3268
- logger8.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
3015
+ logger7.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
3269
3016
  if (componentId === "no_relevant_updates") {
3270
3017
  continue;
3271
3018
  }
@@ -3285,7 +3032,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3285
3032
  return { summaries };
3286
3033
  } catch (error) {
3287
3034
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3288
- logger8.error({ error }, "Failed to generate structured update, using fallback");
3035
+ logger7.error({ error }, "Failed to generate structured update, using fallback");
3289
3036
  return { summaries: [] };
3290
3037
  } finally {
3291
3038
  span.end();
@@ -3557,7 +3304,7 @@ Make it specific and relevant.`;
3557
3304
  });
3558
3305
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
3559
3306
  modelToUse = agentData.models.base;
3560
- logger8.info(
3307
+ logger7.info(
3561
3308
  {
3562
3309
  sessionId: this.sessionId,
3563
3310
  artifactId: artifactData.artifactId,
@@ -3568,7 +3315,7 @@ Make it specific and relevant.`;
3568
3315
  );
3569
3316
  }
3570
3317
  } catch (error) {
3571
- logger8.warn(
3318
+ logger7.warn(
3572
3319
  {
3573
3320
  sessionId: this.sessionId,
3574
3321
  artifactId: artifactData.artifactId,
@@ -3580,7 +3327,7 @@ Make it specific and relevant.`;
3580
3327
  }
3581
3328
  }
3582
3329
  if (!modelToUse?.model?.trim()) {
3583
- logger8.warn(
3330
+ logger7.warn(
3584
3331
  {
3585
3332
  sessionId: this.sessionId,
3586
3333
  artifactId: artifactData.artifactId
@@ -3662,7 +3409,7 @@ Make it specific and relevant.`;
3662
3409
  return result2;
3663
3410
  } catch (error) {
3664
3411
  lastError = error instanceof Error ? error : new Error(String(error));
3665
- logger8.warn(
3412
+ logger7.warn(
3666
3413
  {
3667
3414
  sessionId: this.sessionId,
3668
3415
  artifactId: artifactData.artifactId,
@@ -3710,7 +3457,7 @@ Make it specific and relevant.`;
3710
3457
  });
3711
3458
  span.setStatus({ code: SpanStatusCode.OK });
3712
3459
  } catch (saveError) {
3713
- logger8.error(
3460
+ logger7.error(
3714
3461
  {
3715
3462
  sessionId: this.sessionId,
3716
3463
  artifactId: artifactData.artifactId,
@@ -3738,7 +3485,7 @@ Make it specific and relevant.`;
3738
3485
  metadata: artifactData.metadata || {},
3739
3486
  toolCallId: artifactData.toolCallId
3740
3487
  });
3741
- logger8.info(
3488
+ logger7.info(
3742
3489
  {
3743
3490
  sessionId: this.sessionId,
3744
3491
  artifactId: artifactData.artifactId
@@ -3749,7 +3496,7 @@ Make it specific and relevant.`;
3749
3496
  } catch (fallbackError) {
3750
3497
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
3751
3498
  if (isDuplicateError) ; else {
3752
- logger8.error(
3499
+ logger7.error(
3753
3500
  {
3754
3501
  sessionId: this.sessionId,
3755
3502
  artifactId: artifactData.artifactId,
@@ -3762,7 +3509,7 @@ Make it specific and relevant.`;
3762
3509
  }
3763
3510
  } catch (error) {
3764
3511
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3765
- logger8.error(
3512
+ logger7.error(
3766
3513
  {
3767
3514
  sessionId: this.sessionId,
3768
3515
  artifactId: artifactData.artifactId,
@@ -3781,7 +3528,7 @@ Make it specific and relevant.`;
3781
3528
  */
3782
3529
  setArtifactCache(key, artifact) {
3783
3530
  this.artifactCache.set(key, artifact);
3784
- logger8.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3531
+ logger7.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3785
3532
  }
3786
3533
  /**
3787
3534
  * Get session-scoped ArtifactService instance
@@ -3800,7 +3547,7 @@ Make it specific and relevant.`;
3800
3547
  */
3801
3548
  getArtifactCache(key) {
3802
3549
  const artifact = this.artifactCache.get(key);
3803
- logger8.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3550
+ logger7.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3804
3551
  return artifact || null;
3805
3552
  }
3806
3553
  /**
@@ -3821,7 +3568,7 @@ var AgentSessionManager = class {
3821
3568
  const sessionId = messageId;
3822
3569
  const session = new AgentSession(sessionId, messageId, agentId, tenantId, projectId, contextId);
3823
3570
  this.sessions.set(sessionId, session);
3824
- logger8.info(
3571
+ logger7.info(
3825
3572
  { sessionId, messageId, agentId, tenantId, projectId, contextId },
3826
3573
  "AgentSession created"
3827
3574
  );
@@ -3835,7 +3582,7 @@ var AgentSessionManager = class {
3835
3582
  if (session) {
3836
3583
  session.initializeStatusUpdates(config, summarizerModel, baseModel);
3837
3584
  } else {
3838
- logger8.error(
3585
+ logger7.error(
3839
3586
  {
3840
3587
  sessionId,
3841
3588
  availableSessions: Array.from(this.sessions.keys())
@@ -3852,7 +3599,7 @@ var AgentSessionManager = class {
3852
3599
  if (session) {
3853
3600
  session.enableEmitOperations();
3854
3601
  } else {
3855
- logger8.error(
3602
+ logger7.error(
3856
3603
  {
3857
3604
  sessionId,
3858
3605
  availableSessions: Array.from(this.sessions.keys())
@@ -3874,7 +3621,7 @@ var AgentSessionManager = class {
3874
3621
  recordEvent(sessionId, eventType, subAgentId, data) {
3875
3622
  const session = this.sessions.get(sessionId);
3876
3623
  if (!session) {
3877
- logger8.warn({ sessionId }, "Attempted to record event in non-existent session");
3624
+ logger7.warn({ sessionId }, "Attempted to record event in non-existent session");
3878
3625
  return;
3879
3626
  }
3880
3627
  session.recordEvent(eventType, subAgentId, data);
@@ -3885,12 +3632,12 @@ var AgentSessionManager = class {
3885
3632
  endSession(sessionId) {
3886
3633
  const session = this.sessions.get(sessionId);
3887
3634
  if (!session) {
3888
- logger8.warn({ sessionId }, "Attempted to end non-existent session");
3635
+ logger7.warn({ sessionId }, "Attempted to end non-existent session");
3889
3636
  return [];
3890
3637
  }
3891
3638
  const events = session.getEvents();
3892
3639
  const summary = session.getSummary();
3893
- logger8.info({ sessionId, summary }, "AgentSession ended");
3640
+ logger7.info({ sessionId, summary }, "AgentSession ended");
3894
3641
  session.cleanup();
3895
3642
  this.sessions.delete(sessionId);
3896
3643
  return events;
@@ -3989,7 +3736,7 @@ async function resolveModelConfig(agentId, subAgent) {
3989
3736
  }
3990
3737
 
3991
3738
  // src/services/IncrementalStreamParser.ts
3992
- var logger9 = getLogger("IncrementalStreamParser");
3739
+ var logger8 = getLogger("IncrementalStreamParser");
3993
3740
  var IncrementalStreamParser = class _IncrementalStreamParser {
3994
3741
  buffer = "";
3995
3742
  pendingTextBuffer = "";
@@ -4047,7 +3794,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
4047
3794
  async initializeArtifactMap() {
4048
3795
  try {
4049
3796
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
4050
- logger9.debug(
3797
+ logger8.debug(
4051
3798
  {
4052
3799
  contextId: this.contextId,
4053
3800
  artifactMapSize: this.artifactMap.size
@@ -4055,7 +3802,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
4055
3802
  "Initialized artifact map for streaming"
4056
3803
  );
4057
3804
  } catch (error) {
4058
- logger9.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3805
+ logger8.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
4059
3806
  this.artifactMap = /* @__PURE__ */ new Map();
4060
3807
  }
4061
3808
  }
@@ -4388,6 +4135,142 @@ ${chunk}`;
4388
4135
  }
4389
4136
  };
4390
4137
 
4138
+ // src/services/PendingToolApprovalManager.ts
4139
+ var logger9 = getLogger("PendingToolApprovalManager");
4140
+ var APPROVAL_CLEANUP_INTERVAL_MS = 2 * 60 * 1e3;
4141
+ var APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
4142
+ var PendingToolApprovalManager = class _PendingToolApprovalManager {
4143
+ static instance;
4144
+ pendingApprovals = /* @__PURE__ */ new Map();
4145
+ constructor() {
4146
+ setInterval(() => this.cleanupExpiredApprovals(), APPROVAL_CLEANUP_INTERVAL_MS);
4147
+ }
4148
+ static getInstance() {
4149
+ if (!_PendingToolApprovalManager.instance) {
4150
+ _PendingToolApprovalManager.instance = new _PendingToolApprovalManager();
4151
+ }
4152
+ return _PendingToolApprovalManager.instance;
4153
+ }
4154
+ /**
4155
+ * Create a new pending approval and return a promise that resolves with approval status
4156
+ */
4157
+ async waitForApproval(toolCallId, toolName, args, conversationId, subAgentId) {
4158
+ return new Promise((resolve, reject) => {
4159
+ const timeoutId = setTimeout(() => {
4160
+ this.pendingApprovals.delete(toolCallId);
4161
+ resolve({
4162
+ approved: false,
4163
+ reason: `Tool approval timeout for ${toolName} (${toolCallId})`
4164
+ });
4165
+ }, APPROVAL_TIMEOUT_MS);
4166
+ const approval = {
4167
+ toolCallId,
4168
+ toolName,
4169
+ args,
4170
+ conversationId,
4171
+ subAgentId,
4172
+ createdAt: Date.now(),
4173
+ resolve,
4174
+ reject,
4175
+ timeoutId
4176
+ };
4177
+ this.pendingApprovals.set(toolCallId, approval);
4178
+ logger9.info(
4179
+ {
4180
+ toolCallId,
4181
+ toolName,
4182
+ conversationId,
4183
+ subAgentId
4184
+ },
4185
+ "Tool approval request created, waiting for user response"
4186
+ );
4187
+ });
4188
+ }
4189
+ /**
4190
+ * Approve a pending tool call
4191
+ */
4192
+ approveToolCall(toolCallId) {
4193
+ const approval = this.pendingApprovals.get(toolCallId);
4194
+ if (!approval) {
4195
+ logger9.warn({ toolCallId }, "Tool approval not found or already processed");
4196
+ return false;
4197
+ }
4198
+ logger9.info(
4199
+ {
4200
+ toolCallId,
4201
+ toolName: approval.toolName,
4202
+ conversationId: approval.conversationId
4203
+ },
4204
+ "Tool approved by user, resuming execution"
4205
+ );
4206
+ clearTimeout(approval.timeoutId);
4207
+ this.pendingApprovals.delete(toolCallId);
4208
+ approval.resolve({ approved: true });
4209
+ return true;
4210
+ }
4211
+ /**
4212
+ * Deny a pending tool call
4213
+ */
4214
+ denyToolCall(toolCallId, reason) {
4215
+ const approval = this.pendingApprovals.get(toolCallId);
4216
+ if (!approval) {
4217
+ logger9.warn({ toolCallId }, "Tool approval not found or already processed");
4218
+ return false;
4219
+ }
4220
+ logger9.info(
4221
+ {
4222
+ toolCallId,
4223
+ toolName: approval.toolName,
4224
+ conversationId: approval.conversationId,
4225
+ reason
4226
+ },
4227
+ "Tool execution denied by user"
4228
+ );
4229
+ clearTimeout(approval.timeoutId);
4230
+ this.pendingApprovals.delete(toolCallId);
4231
+ approval.resolve({
4232
+ approved: false,
4233
+ reason: reason || "User denied approval"
4234
+ });
4235
+ return true;
4236
+ }
4237
+ /**
4238
+ * Clean up expired approvals (called by interval timer)
4239
+ */
4240
+ cleanupExpiredApprovals() {
4241
+ const now = Date.now();
4242
+ let cleanedUp = 0;
4243
+ for (const [toolCallId, approval] of this.pendingApprovals) {
4244
+ if (now - approval.createdAt > APPROVAL_TIMEOUT_MS) {
4245
+ clearTimeout(approval.timeoutId);
4246
+ this.pendingApprovals.delete(toolCallId);
4247
+ approval.resolve({ approved: false, reason: "Tool approval expired" });
4248
+ cleanedUp++;
4249
+ }
4250
+ }
4251
+ if (cleanedUp > 0) {
4252
+ logger9.info({ cleanedUp }, "Cleaned up expired tool approvals");
4253
+ }
4254
+ }
4255
+ /**
4256
+ * Get current status for monitoring
4257
+ */
4258
+ getStatus() {
4259
+ return {
4260
+ pendingApprovals: this.pendingApprovals.size,
4261
+ approvals: Array.from(this.pendingApprovals.values()).map((approval) => ({
4262
+ toolCallId: approval.toolCallId,
4263
+ toolName: approval.toolName,
4264
+ conversationId: approval.conversationId,
4265
+ subAgentId: approval.subAgentId,
4266
+ createdAt: approval.createdAt,
4267
+ age: Date.now() - approval.createdAt
4268
+ }))
4269
+ };
4270
+ }
4271
+ };
4272
+ var pendingToolApprovalManager = PendingToolApprovalManager.getInstance();
4273
+
4391
4274
  // src/services/ResponseFormatter.ts
4392
4275
  var logger10 = getLogger("ResponseFormatter");
4393
4276
  var ResponseFormatter = class {
@@ -4987,13 +4870,14 @@ var DEFAULT_BACKOFF = {
4987
4870
  var DEFAULT_RETRY_STATUS_CODES = ["429", "500", "502", "503", "504"];
4988
4871
  var PermanentError = class _PermanentError extends Error {
4989
4872
  cause;
4873
+ type;
4990
4874
  constructor(message, options) {
4991
4875
  let msg = message;
4992
4876
  if (options?.cause) {
4993
4877
  msg += `: ${options.cause}`;
4994
4878
  }
4995
4879
  super(msg, options);
4996
- this.name = "PermanentError";
4880
+ this.name = options?.type || "PermanentError";
4997
4881
  if (typeof this.cause === "undefined") {
4998
4882
  this.cause = options?.cause;
4999
4883
  }
@@ -5302,6 +5186,12 @@ var A2AClient = class {
5302
5186
  }
5303
5187
  }
5304
5188
  const rpcResponse = await httpResponse.json();
5189
+ if (rpcResponse.error?.data?.type === "connection_refused") {
5190
+ throw new PermanentError(rpcResponse.error.message, {
5191
+ cause: new Error(rpcResponse.error.message),
5192
+ type: "connection_refused"
5193
+ });
5194
+ }
5305
5195
  if (rpcResponse.id !== requestId2) {
5306
5196
  logger12.warn(
5307
5197
  {
@@ -5689,7 +5579,7 @@ var createTransferToAgentTool = ({
5689
5579
  const toolDescription = generateTransferToolDescription(transferConfig);
5690
5580
  return tool({
5691
5581
  description: toolDescription,
5692
- inputSchema: z5.object({}),
5582
+ inputSchema: z.object({}),
5693
5583
  execute: async () => {
5694
5584
  const activeSpan = trace.getActiveSpan();
5695
5585
  if (activeSpan) {
@@ -5744,7 +5634,7 @@ function createDelegateToAgentTool({
5744
5634
  }) {
5745
5635
  return tool({
5746
5636
  description: generateDelegateToolDescription(delegateConfig),
5747
- inputSchema: z5.object({ message: z5.string() }),
5637
+ inputSchema: z.object({ message: z.string() }),
5748
5638
  execute: async (input, context) => {
5749
5639
  const delegationId = `del_${generateId()}`;
5750
5640
  const activeSpan = trace.getActiveSpan();
@@ -7192,7 +7082,7 @@ var Agent = class {
7192
7082
  /**
7193
7083
  * Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
7194
7084
  */
7195
- wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId) {
7085
+ wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId, options) {
7196
7086
  if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
7197
7087
  return toolDefinition;
7198
7088
  }
@@ -7214,13 +7104,24 @@ var Agent = class {
7214
7104
  });
7215
7105
  }
7216
7106
  const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_");
7107
+ const needsApproval = options?.needsApproval || false;
7217
7108
  if (streamRequestId && !isInternalTool) {
7218
- agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, {
7109
+ const toolCallData = {
7219
7110
  toolName,
7220
7111
  input: args,
7221
7112
  toolCallId,
7222
7113
  relationshipId
7223
- });
7114
+ };
7115
+ if (needsApproval) {
7116
+ toolCallData.needsApproval = true;
7117
+ toolCallData.conversationId = this.conversationId;
7118
+ }
7119
+ await agentSessionManager.recordEvent(
7120
+ streamRequestId,
7121
+ "tool_call",
7122
+ this.config.id,
7123
+ toolCallData
7124
+ );
7224
7125
  }
7225
7126
  try {
7226
7127
  const result = await originalExecute(args, context);
@@ -7265,7 +7166,8 @@ var Agent = class {
7265
7166
  output: result,
7266
7167
  toolCallId,
7267
7168
  duration,
7268
- relationshipId
7169
+ relationshipId,
7170
+ needsApproval
7269
7171
  });
7270
7172
  }
7271
7173
  return result;
@@ -7279,7 +7181,8 @@ var Agent = class {
7279
7181
  toolCallId,
7280
7182
  duration,
7281
7183
  error: errorMessage,
7282
- relationshipId
7184
+ relationshipId,
7185
+ needsApproval
7283
7186
  });
7284
7187
  }
7285
7188
  throw error;
@@ -7348,30 +7251,120 @@ var Agent = class {
7348
7251
  const wrappedTools2 = {};
7349
7252
  for (const [index, toolSet] of tools.entries()) {
7350
7253
  const relationshipId = mcpTools[index]?.relationshipId;
7351
- for (const [toolName, toolDef] of Object.entries(toolSet)) {
7254
+ for (const [toolName, toolDef] of Object.entries(toolSet.tools)) {
7255
+ const needsApproval = toolSet.toolPolicies?.[toolName]?.needsApproval || false;
7256
+ const enhancedTool = {
7257
+ ...toolDef,
7258
+ needsApproval
7259
+ };
7352
7260
  wrappedTools2[toolName] = this.wrapToolWithStreaming(
7353
7261
  toolName,
7354
- toolDef,
7262
+ enhancedTool,
7355
7263
  streamRequestId,
7356
7264
  "mcp",
7357
- relationshipId
7265
+ relationshipId,
7266
+ { needsApproval }
7358
7267
  );
7359
7268
  }
7360
7269
  }
7361
7270
  return wrappedTools2;
7362
7271
  }
7363
7272
  const wrappedTools = {};
7364
- for (const [index, toolSet] of tools.entries()) {
7273
+ for (const [index, toolResult] of tools.entries()) {
7365
7274
  const relationshipId = mcpTools[index]?.relationshipId;
7366
- for (const [toolName, originalTool] of Object.entries(toolSet)) {
7275
+ for (const [toolName, originalTool] of Object.entries(toolResult.tools)) {
7367
7276
  if (!isValidTool(originalTool)) {
7368
7277
  logger15.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7369
7278
  continue;
7370
7279
  }
7280
+ const needsApproval = toolResult.toolPolicies?.[toolName]?.needsApproval || false;
7281
+ logger15.debug(
7282
+ {
7283
+ toolName,
7284
+ toolPolicies: toolResult.toolPolicies,
7285
+ needsApproval,
7286
+ policyForThisTool: toolResult.toolPolicies?.[toolName]
7287
+ },
7288
+ "Tool approval check"
7289
+ );
7371
7290
  const sessionWrappedTool = tool({
7372
7291
  description: originalTool.description,
7373
7292
  inputSchema: originalTool.inputSchema,
7374
7293
  execute: async (args, { toolCallId }) => {
7294
+ if (needsApproval) {
7295
+ logger15.info(
7296
+ { toolName, toolCallId, args },
7297
+ "Tool requires approval - waiting for user response"
7298
+ );
7299
+ const currentSpan = trace.getActiveSpan();
7300
+ if (currentSpan) {
7301
+ currentSpan.addEvent("tool.approval.requested", {
7302
+ "tool.name": toolName,
7303
+ "tool.callId": toolCallId,
7304
+ "subAgent.id": this.config.id
7305
+ });
7306
+ }
7307
+ tracer.startActiveSpan(
7308
+ "tool.approval_requested",
7309
+ {
7310
+ attributes: {
7311
+ "tool.name": toolName,
7312
+ "tool.callId": toolCallId,
7313
+ "subAgent.id": this.config.id,
7314
+ "subAgent.name": this.config.name
7315
+ }
7316
+ },
7317
+ (requestSpan) => {
7318
+ requestSpan.setStatus({ code: SpanStatusCode.OK });
7319
+ requestSpan.end();
7320
+ }
7321
+ );
7322
+ const approvalResult = await pendingToolApprovalManager.waitForApproval(
7323
+ toolCallId,
7324
+ toolName,
7325
+ args,
7326
+ this.conversationId || "unknown",
7327
+ this.config.id
7328
+ );
7329
+ if (!approvalResult.approved) {
7330
+ return tracer.startActiveSpan(
7331
+ "tool.approval_denied",
7332
+ {
7333
+ attributes: {
7334
+ "tool.name": toolName,
7335
+ "tool.callId": toolCallId,
7336
+ "subAgent.id": this.config.id,
7337
+ "subAgent.name": this.config.name
7338
+ }
7339
+ },
7340
+ (denialSpan) => {
7341
+ logger15.info(
7342
+ { toolName, toolCallId, reason: approvalResult.reason },
7343
+ "Tool execution denied by user"
7344
+ );
7345
+ denialSpan.setStatus({ code: SpanStatusCode.OK });
7346
+ denialSpan.end();
7347
+ return `User denied approval to run this tool: ${approvalResult.reason}`;
7348
+ }
7349
+ );
7350
+ }
7351
+ tracer.startActiveSpan(
7352
+ "tool.approval_approved",
7353
+ {
7354
+ attributes: {
7355
+ "tool.name": toolName,
7356
+ "tool.callId": toolCallId,
7357
+ "subAgent.id": this.config.id,
7358
+ "subAgent.name": this.config.name
7359
+ }
7360
+ },
7361
+ (approvedSpan) => {
7362
+ logger15.info({ toolName, toolCallId }, "Tool approved, continuing with execution");
7363
+ approvedSpan.setStatus({ code: SpanStatusCode.OK });
7364
+ approvedSpan.end();
7365
+ }
7366
+ );
7367
+ }
7375
7368
  logger15.debug({ toolName, toolCallId }, "MCP Tool Called");
7376
7369
  try {
7377
7370
  const rawResult = await originalTool.execute(args, { toolCallId });
@@ -7437,7 +7430,8 @@ var Agent = class {
7437
7430
  sessionWrappedTool,
7438
7431
  streamRequestId,
7439
7432
  "mcp",
7440
- relationshipId
7433
+ relationshipId,
7434
+ { needsApproval }
7441
7435
  );
7442
7436
  }
7443
7437
  }
@@ -7476,8 +7470,10 @@ var Agent = class {
7476
7470
  subAgentId: this.config.id
7477
7471
  }
7478
7472
  });
7479
- const agentToolRelationHeaders = toolsForAgent.data.find((t) => t.toolId === tool3.id)?.headers || void 0;
7480
- const selectedTools = toolsForAgent.data.find((t) => t.toolId === tool3.id)?.selectedTools || void 0;
7473
+ const toolRelation = toolsForAgent.data.find((t) => t.toolId === tool3.id);
7474
+ const agentToolRelationHeaders = toolRelation?.headers || void 0;
7475
+ const selectedTools = toolRelation?.selectedTools || void 0;
7476
+ const toolPolicies = toolRelation?.toolPolicies || {};
7481
7477
  let serverConfig;
7482
7478
  if (credentialReferenceId && this.credentialStuffer) {
7483
7479
  const credentialReference = await getCredentialReference(dbClient_default)({
@@ -7608,7 +7604,7 @@ var Agent = class {
7608
7604
  );
7609
7605
  }
7610
7606
  }
7611
- return tools;
7607
+ return { tools, toolPolicies };
7612
7608
  }
7613
7609
  async createMcpConnection(tool3, serverConfig) {
7614
7610
  const client = new McpClient({
@@ -7631,12 +7627,12 @@ var Agent = class {
7631
7627
  if (error?.cause && JSON.stringify(error.cause).includes("ECONNREFUSED")) {
7632
7628
  const errorMessage = "Connection refused. Please check if the MCP server is running.";
7633
7629
  throw new Error(errorMessage);
7634
- } else if (error.message.includes("404")) {
7630
+ }
7631
+ if (error.message.includes("404")) {
7635
7632
  const errorMessage = "Error accessing endpoint (HTTP 404)";
7636
7633
  throw new Error(errorMessage);
7637
- } else {
7638
- throw new Error(`MCP server connection failed: ${error.message}`);
7639
7634
  }
7635
+ throw new Error(`MCP server connection failed: ${error.message}`);
7640
7636
  }
7641
7637
  throw error;
7642
7638
  }
@@ -7656,7 +7652,7 @@ var Agent = class {
7656
7652
  if (functionToolsData.length === 0) {
7657
7653
  return functionTools;
7658
7654
  }
7659
- const { SandboxExecutorFactory } = await import('./SandboxExecutorFactory-NUNGK35F.js');
7655
+ const { SandboxExecutorFactory } = await import('./SandboxExecutorFactory-A2LTPE2X.js');
7660
7656
  const sandboxExecutor = SandboxExecutorFactory.getInstance();
7661
7657
  for (const functionToolDef of functionToolsData) {
7662
7658
  const functionId = functionToolDef.functionId;
@@ -7950,7 +7946,7 @@ var Agent = class {
7950
7946
  inputSchema: tool3.inputSchema || tool3.parameters || {},
7951
7947
  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."
7952
7948
  }));
7953
- const { getConversationScopedArtifacts } = await import('./conversations-YFQ52RQB.js');
7949
+ const { getConversationScopedArtifacts } = await import('./conversations-33GSAG2C.js');
7954
7950
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
7955
7951
  const referenceArtifacts = await getConversationScopedArtifacts({
7956
7952
  tenantId: this.config.tenantId,
@@ -8474,6 +8470,15 @@ ${output}`;
8474
8470
  logger15.debug({ error }, "Failed to track agent reasoning");
8475
8471
  }
8476
8472
  }
8473
+ if (last && last["content"] && last["content"].length > 0) {
8474
+ const lastContent = last["content"][last["content"].length - 1];
8475
+ if (lastContent["type"] === "tool-error") {
8476
+ const error = lastContent["error"];
8477
+ if (error && typeof error === "object" && "name" in error && error.name === "connection_refused") {
8478
+ return true;
8479
+ }
8480
+ }
8481
+ }
8477
8482
  if (steps.length >= 2) {
8478
8483
  const previousStep = steps[steps.length - 2];
8479
8484
  if (previousStep && "toolCalls" in previousStep && previousStep.toolCalls) {
@@ -8534,13 +8539,13 @@ ${output}`;
8534
8539
  parser.markToolResult();
8535
8540
  }
8536
8541
  break;
8537
- case "error":
8542
+ case "error": {
8538
8543
  if (event.error instanceof Error) {
8539
8544
  throw event.error;
8540
- } else {
8541
- const errorMessage = event.error?.error?.message;
8542
- throw new Error(errorMessage);
8543
8545
  }
8546
+ const errorMessage = event.error?.error?.message;
8547
+ throw new Error(errorMessage);
8548
+ }
8544
8549
  }
8545
8550
  }
8546
8551
  await parser.finalize();
@@ -9435,17 +9440,16 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9435
9440
  }
9436
9441
  ]
9437
9442
  };
9438
- } else {
9439
- logger16.warn(
9440
- {
9441
- hasToolResult: !!toolResult,
9442
- hasOutput: !!toolResult?.output,
9443
- validationPassed: false,
9444
- output: toolResult?.output
9445
- },
9446
- "[DEBUG] Transfer validation FAILED"
9447
- );
9448
9443
  }
9444
+ logger16.warn(
9445
+ {
9446
+ hasToolResult: !!toolResult,
9447
+ hasOutput: !!toolResult?.output,
9448
+ validationPassed: false,
9449
+ output: toolResult?.output
9450
+ },
9451
+ "[DEBUG] Transfer validation FAILED"
9452
+ );
9449
9453
  }
9450
9454
  }
9451
9455
  }
@@ -9465,10 +9469,13 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9465
9469
  };
9466
9470
  } catch (error) {
9467
9471
  console.error("Task handler error:", error);
9472
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
9473
+ const isConnectionRefused = errorMessage.includes("Connection refused. Please check if the MCP server is running.");
9468
9474
  return {
9469
9475
  status: {
9470
9476
  state: TaskState.Failed,
9471
- message: error instanceof Error ? error.message : "Unknown error occurred"
9477
+ message: errorMessage,
9478
+ type: isConnectionRefused ? "connection_refused" : "unknown"
9472
9479
  },
9473
9480
  artifacts: []
9474
9481
  };
@@ -10345,7 +10352,7 @@ var VercelDataStreamHelper = class _VercelDataStreamHelper {
10345
10352
  }
10346
10353
  const now = Date.now();
10347
10354
  const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
10348
- if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
10355
+ if (operation.type !== "tool_call" && operation.type !== "tool_result" && (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS)) {
10349
10356
  this.queuedEvents.push({ type: "data-operation", event: operation });
10350
10357
  return;
10351
10358
  }
@@ -11289,29 +11296,29 @@ var chatDataStreamRoute = createRoute({
11289
11296
  body: {
11290
11297
  content: {
11291
11298
  "application/json": {
11292
- schema: z$1.object({
11293
- model: z$1.string().optional(),
11294
- messages: z$1.array(
11295
- z$1.object({
11296
- role: z$1.enum(["system", "user", "assistant", "function", "tool"]),
11297
- content: z$1.any(),
11298
- parts: z$1.array(
11299
- z$1.object({
11300
- type: z$1.union([
11301
- z$1.enum(["text", "image", "audio", "video", "file"]),
11302
- z$1.string().regex(/^data-/, 'Type must start with "data-"')
11299
+ schema: z.object({
11300
+ model: z.string().optional(),
11301
+ messages: z.array(
11302
+ z.object({
11303
+ role: z.enum(["system", "user", "assistant", "function", "tool"]),
11304
+ content: z.any(),
11305
+ parts: z.array(
11306
+ z.object({
11307
+ type: z.union([
11308
+ z.enum(["text", "image", "audio", "video", "file"]),
11309
+ z.string().regex(/^data-/, 'Type must start with "data-"')
11303
11310
  ]),
11304
- text: z$1.string().optional()
11311
+ text: z.string().optional()
11305
11312
  })
11306
11313
  ).optional()
11307
11314
  })
11308
11315
  ),
11309
- id: z$1.string().optional(),
11310
- conversationId: z$1.string().optional(),
11311
- stream: z$1.boolean().optional().describe("Whether to stream the response").default(true),
11312
- max_tokens: z$1.number().optional().describe("Maximum tokens to generate"),
11313
- headers: z$1.record(z$1.string(), z$1.unknown()).optional().describe("Headers data for template processing"),
11314
- runConfig: z$1.record(z$1.string(), z$1.unknown()).optional().describe("Run configuration")
11316
+ id: z.string().optional(),
11317
+ conversationId: z.string().optional(),
11318
+ stream: z.boolean().optional().describe("Whether to stream the response").default(true),
11319
+ max_tokens: z.number().optional().describe("Maximum tokens to generate"),
11320
+ headers: z.record(z.string(), z.unknown()).optional().describe("Headers data for template processing"),
11321
+ runConfig: z.record(z.string(), z.unknown()).optional().describe("Run configuration")
11315
11322
  })
11316
11323
  }
11317
11324
  }
@@ -11320,9 +11327,9 @@ var chatDataStreamRoute = createRoute({
11320
11327
  responses: {
11321
11328
  200: {
11322
11329
  description: "Streamed chat completion",
11323
- headers: z$1.object({
11324
- "Content-Type": z$1.string().default("text/plain; charset=utf-8"),
11325
- "x-vercel-ai-data-stream": z$1.string().default("v1")
11330
+ headers: z.object({
11331
+ "Content-Type": z.string().default("text/plain; charset=utf-8"),
11332
+ "x-vercel-ai-data-stream": z.string().default("v1")
11326
11333
  })
11327
11334
  },
11328
11335
  ...commonGetErrorResponses
@@ -11524,6 +11531,137 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11524
11531
  });
11525
11532
  }
11526
11533
  });
11534
+ var toolApprovalRoute = createRoute({
11535
+ method: "post",
11536
+ path: "/tool-approvals",
11537
+ tags: ["chat"],
11538
+ summary: "Approve or deny tool execution",
11539
+ description: "Handle user approval/denial of tool execution requests during conversations",
11540
+ security: [{ bearerAuth: [] }],
11541
+ request: {
11542
+ body: {
11543
+ content: {
11544
+ "application/json": {
11545
+ schema: z.object({
11546
+ conversationId: z.string().describe("The conversation ID"),
11547
+ toolCallId: z.string().describe("The tool call ID to respond to"),
11548
+ approved: z.boolean().describe("Whether the tool execution is approved"),
11549
+ reason: z.string().optional().describe("Optional reason for the decision")
11550
+ })
11551
+ }
11552
+ }
11553
+ }
11554
+ },
11555
+ responses: {
11556
+ 200: {
11557
+ description: "Tool approval response processed successfully",
11558
+ content: {
11559
+ "application/json": {
11560
+ schema: z.object({
11561
+ success: z.boolean(),
11562
+ message: z.string().optional()
11563
+ })
11564
+ }
11565
+ }
11566
+ },
11567
+ 400: {
11568
+ description: "Bad request - invalid tool call ID or conversation ID",
11569
+ content: {
11570
+ "application/json": {
11571
+ schema: z.object({
11572
+ error: z.string()
11573
+ })
11574
+ }
11575
+ }
11576
+ },
11577
+ 404: {
11578
+ description: "Tool call not found or already processed",
11579
+ content: {
11580
+ "application/json": {
11581
+ schema: z.object({
11582
+ error: z.string()
11583
+ })
11584
+ }
11585
+ }
11586
+ },
11587
+ 500: {
11588
+ description: "Internal server error",
11589
+ content: {
11590
+ "application/json": {
11591
+ schema: z.object({
11592
+ error: z.string(),
11593
+ message: z.string()
11594
+ })
11595
+ }
11596
+ }
11597
+ }
11598
+ }
11599
+ });
11600
+ app3.openapi(toolApprovalRoute, async (c) => {
11601
+ const tracer2 = trace.getTracer("tool-approval-handler");
11602
+ return tracer2.startActiveSpan("tool_approval_request", async (span) => {
11603
+ try {
11604
+ const executionContext = getRequestExecutionContext(c);
11605
+ const { tenantId, projectId } = executionContext;
11606
+ const requestBody = await c.req.json();
11607
+ const { conversationId, toolCallId, approved, reason } = requestBody;
11608
+ logger22.info(
11609
+ {
11610
+ conversationId,
11611
+ toolCallId,
11612
+ approved,
11613
+ reason,
11614
+ tenantId,
11615
+ projectId
11616
+ },
11617
+ "Processing tool approval request"
11618
+ );
11619
+ const conversation = await getConversation(dbClient_default)({
11620
+ scopes: { tenantId, projectId },
11621
+ conversationId
11622
+ });
11623
+ if (!conversation) {
11624
+ span.setStatus({ code: 1, message: "Conversation not found" });
11625
+ return c.json({ error: "Conversation not found" }, 404);
11626
+ }
11627
+ let success = false;
11628
+ if (approved) {
11629
+ success = pendingToolApprovalManager.approveToolCall(toolCallId);
11630
+ } else {
11631
+ success = pendingToolApprovalManager.denyToolCall(toolCallId, reason);
11632
+ }
11633
+ if (!success) {
11634
+ span.setStatus({ code: 1, message: "Tool call not found" });
11635
+ return c.json({ error: "Tool call not found or already processed" }, 404);
11636
+ }
11637
+ logger22.info({ conversationId, toolCallId, approved }, "Tool approval processed successfully");
11638
+ span.setStatus({ code: 1, message: "Success" });
11639
+ return c.json({
11640
+ success: true,
11641
+ message: approved ? "Tool execution approved" : "Tool execution denied"
11642
+ });
11643
+ } catch (error) {
11644
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
11645
+ logger22.error(
11646
+ {
11647
+ error: errorMessage,
11648
+ stack: error instanceof Error ? error.stack : void 0
11649
+ },
11650
+ "Failed to process tool approval"
11651
+ );
11652
+ span.setStatus({ code: 2, message: errorMessage });
11653
+ return c.json(
11654
+ {
11655
+ error: "Internal server error",
11656
+ message: errorMessage
11657
+ },
11658
+ 500
11659
+ );
11660
+ } finally {
11661
+ span.end();
11662
+ }
11663
+ });
11664
+ });
11527
11665
  var chatDataStream_default = app3;
11528
11666
  var logger23 = getLogger("mcp");
11529
11667
  var MockResponseSingleton = class _MockResponseSingleton {
@@ -11602,7 +11740,8 @@ var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
11602
11740
  })
11603
11741
  );
11604
11742
  return false;
11605
- } else if (Array.isArray(sessionId)) {
11743
+ }
11744
+ if (Array.isArray(sessionId)) {
11606
11745
  res.writeHead(400).end(
11607
11746
  JSON.stringify({
11608
11747
  jsonrpc: "2.0",
@@ -12025,16 +12164,15 @@ app4.openapi(
12025
12164
  c,
12026
12165
  credentialStores
12027
12166
  );
12028
- } else {
12029
- return await handleExistingSessionRequest(
12030
- body,
12031
- executionContext,
12032
- validatedContext,
12033
- req,
12034
- res,
12035
- credentialStores
12036
- );
12037
12167
  }
12168
+ return await handleExistingSessionRequest(
12169
+ body,
12170
+ executionContext,
12171
+ validatedContext,
12172
+ req,
12173
+ res,
12174
+ credentialStores
12175
+ );
12038
12176
  } catch (e) {
12039
12177
  logger23.error(
12040
12178
  {