@inkeep/agents-run-api 0.37.0 → 0.37.1

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,10 +1,10 @@
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-AZFBQY6E.js';
2
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-M46DFVYB.js';
3
+ import { dbClient_default } from './chunk-V4RNZ6BX.js';
4
+ import { env } from './chunk-IYG4HUQ6.js';
5
5
  import { getLogger } from './chunk-A2S7GSHL.js';
6
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';
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
9
  import { OpenAPIHono, createRoute, z as z$1 } from '@hono/zod-openapi';
10
10
  import { trace, propagation, context, SpanStatusCode } from '@opentelemetry/api';
@@ -17,12 +17,6 @@ import { swaggerUI } from '@hono/swagger-ui';
17
17
  import z5, { z } from 'zod';
18
18
  import { streamSSE, stream } from 'hono/streaming';
19
19
  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
20
  import jmespath from 'jmespath';
27
21
  import Ajv from 'ajv';
28
22
  import destr from 'destr';
@@ -981,269 +975,7 @@ async function handleTasksResubscribe(c, agent, request) {
981
975
  });
982
976
  }
983
977
  }
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");
978
+ var logger3 = getLogger("ToolSessionManager");
1247
979
  var ToolSessionManager = class _ToolSessionManager {
1248
980
  static instance;
1249
981
  sessions = /* @__PURE__ */ new Map();
@@ -1277,7 +1009,7 @@ var ToolSessionManager = class _ToolSessionManager {
1277
1009
  createdAt: Date.now()
1278
1010
  };
1279
1011
  this.sessions.set(sessionId, session);
1280
- logger4.debug(
1012
+ logger3.debug(
1281
1013
  {
1282
1014
  sessionId,
1283
1015
  tenantId,
@@ -1295,10 +1027,10 @@ var ToolSessionManager = class _ToolSessionManager {
1295
1027
  */
1296
1028
  ensureAgentSession(sessionId, tenantId, projectId, contextId, taskId) {
1297
1029
  if (this.sessions.has(sessionId)) {
1298
- logger4.debug({ sessionId }, "Agent session already exists, reusing");
1030
+ logger3.debug({ sessionId }, "Agent session already exists, reusing");
1299
1031
  return sessionId;
1300
1032
  }
1301
- logger4.debug(
1033
+ logger3.debug(
1302
1034
  { sessionId, tenantId, contextId, taskId },
1303
1035
  "Creating new agent-scoped tool session"
1304
1036
  );
@@ -1310,7 +1042,7 @@ var ToolSessionManager = class _ToolSessionManager {
1310
1042
  recordToolResult(sessionId, toolResult) {
1311
1043
  const session = this.sessions.get(sessionId);
1312
1044
  if (!session) {
1313
- logger4.warn(
1045
+ logger3.warn(
1314
1046
  {
1315
1047
  sessionId,
1316
1048
  toolCallId: toolResult.toolCallId,
@@ -1322,7 +1054,7 @@ var ToolSessionManager = class _ToolSessionManager {
1322
1054
  return;
1323
1055
  }
1324
1056
  session.toolResults.set(toolResult.toolCallId, toolResult);
1325
- logger4.debug(
1057
+ logger3.debug(
1326
1058
  {
1327
1059
  sessionId,
1328
1060
  toolCallId: toolResult.toolCallId,
@@ -1337,7 +1069,7 @@ var ToolSessionManager = class _ToolSessionManager {
1337
1069
  getToolResult(sessionId, toolCallId) {
1338
1070
  const session = this.sessions.get(sessionId);
1339
1071
  if (!session) {
1340
- logger4.warn(
1072
+ logger3.warn(
1341
1073
  {
1342
1074
  sessionId,
1343
1075
  toolCallId,
@@ -1350,7 +1082,7 @@ var ToolSessionManager = class _ToolSessionManager {
1350
1082
  }
1351
1083
  const result = session.toolResults.get(toolCallId);
1352
1084
  if (!result) {
1353
- logger4.warn(
1085
+ logger3.warn(
1354
1086
  {
1355
1087
  sessionId,
1356
1088
  toolCallId,
@@ -1360,7 +1092,7 @@ var ToolSessionManager = class _ToolSessionManager {
1360
1092
  "Tool result not found"
1361
1093
  );
1362
1094
  } else {
1363
- logger4.debug(
1095
+ logger3.debug(
1364
1096
  {
1365
1097
  sessionId,
1366
1098
  toolCallId,
@@ -1399,10 +1131,10 @@ var ToolSessionManager = class _ToolSessionManager {
1399
1131
  }
1400
1132
  for (const sessionId of expiredSessions) {
1401
1133
  this.sessions.delete(sessionId);
1402
- logger4.debug({ sessionId }, "Cleaned up expired tool session");
1134
+ logger3.debug({ sessionId }, "Cleaned up expired tool session");
1403
1135
  }
1404
1136
  if (expiredSessions.length > 0) {
1405
- logger4.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
1137
+ logger3.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
1406
1138
  }
1407
1139
  }
1408
1140
  };
@@ -1470,7 +1202,7 @@ function extractFullFields(schema) {
1470
1202
  }
1471
1203
 
1472
1204
  // src/services/ArtifactService.ts
1473
- var logger6 = getLogger("ArtifactService");
1205
+ var logger5 = getLogger("ArtifactService");
1474
1206
  var ArtifactService = class _ArtifactService {
1475
1207
  constructor(context) {
1476
1208
  this.context = context;
@@ -1503,7 +1235,7 @@ var ArtifactService = class _ArtifactService {
1503
1235
  id: taskId
1504
1236
  });
1505
1237
  if (!task) {
1506
- logger6.warn({ taskId }, "Task not found when fetching artifacts");
1238
+ logger5.warn({ taskId }, "Task not found when fetching artifacts");
1507
1239
  continue;
1508
1240
  }
1509
1241
  const taskArtifacts = await getLedgerArtifacts(dbClient_default)({
@@ -1521,7 +1253,7 @@ var ArtifactService = class _ArtifactService {
1521
1253
  }
1522
1254
  }
1523
1255
  } catch (error) {
1524
- logger6.error({ error, contextId }, "Error loading context artifacts");
1256
+ logger5.error({ error, contextId }, "Error loading context artifacts");
1525
1257
  }
1526
1258
  return artifacts;
1527
1259
  }
@@ -1530,12 +1262,12 @@ var ArtifactService = class _ArtifactService {
1530
1262
  */
1531
1263
  async createArtifact(request, subAgentId) {
1532
1264
  if (!this.context.sessionId) {
1533
- logger6.warn({ request }, "No session ID available for artifact creation");
1265
+ logger5.warn({ request }, "No session ID available for artifact creation");
1534
1266
  return null;
1535
1267
  }
1536
1268
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
1537
1269
  if (!toolResult) {
1538
- logger6.warn(
1270
+ logger5.warn(
1539
1271
  { request, sessionId: this.context.sessionId },
1540
1272
  "Tool result not found for artifact"
1541
1273
  );
@@ -1551,7 +1283,7 @@ var ArtifactService = class _ArtifactService {
1551
1283
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
1552
1284
  }
1553
1285
  if (!selectedData) {
1554
- logger6.warn(
1286
+ logger5.warn(
1555
1287
  {
1556
1288
  request,
1557
1289
  baseSelector: request.baseSelector
@@ -1622,7 +1354,7 @@ var ArtifactService = class _ArtifactService {
1622
1354
  );
1623
1355
  return artifactData;
1624
1356
  } catch (error) {
1625
- logger6.error({ error, request }, "Failed to create artifact");
1357
+ logger5.error({ error, request }, "Failed to create artifact");
1626
1358
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
1627
1359
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
1628
1360
  }
@@ -1651,7 +1383,7 @@ var ArtifactService = class _ArtifactService {
1651
1383
  }
1652
1384
  try {
1653
1385
  if (!this.context.projectId || !this.context.taskId) {
1654
- logger6.warn(
1386
+ logger5.warn(
1655
1387
  { artifactId, toolCallId },
1656
1388
  "No projectId or taskId available for artifact lookup"
1657
1389
  );
@@ -1675,7 +1407,7 @@ var ArtifactService = class _ArtifactService {
1675
1407
  return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
1676
1408
  }
1677
1409
  } catch (error) {
1678
- logger6.warn(
1410
+ logger5.warn(
1679
1411
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1680
1412
  "Failed to fetch artifact"
1681
1413
  );
@@ -1706,7 +1438,7 @@ var ArtifactService = class _ArtifactService {
1706
1438
  }
1707
1439
  try {
1708
1440
  if (!this.context.projectId || !this.context.taskId) {
1709
- logger6.warn(
1441
+ logger5.warn(
1710
1442
  { artifactId, toolCallId },
1711
1443
  "No projectId or taskId available for artifact lookup"
1712
1444
  );
@@ -1730,7 +1462,7 @@ var ArtifactService = class _ArtifactService {
1730
1462
  return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
1731
1463
  }
1732
1464
  } catch (error) {
1733
- logger6.warn(
1465
+ logger5.warn(
1734
1466
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1735
1467
  "Failed to fetch artifact"
1736
1468
  );
@@ -1747,7 +1479,7 @@ var ArtifactService = class _ArtifactService {
1747
1479
  data = artifact.parts?.[0]?.data;
1748
1480
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1749
1481
  dataSource = "parts[0].data (fallback)";
1750
- logger6.debug(
1482
+ logger5.debug(
1751
1483
  { artifactId, toolCallId, dataSource },
1752
1484
  "Using fallback data source for artifact summary"
1753
1485
  );
@@ -1755,14 +1487,14 @@ var ArtifactService = class _ArtifactService {
1755
1487
  data = artifact.data;
1756
1488
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1757
1489
  dataSource = "artifact.data (fallback)";
1758
- logger6.debug(
1490
+ logger5.debug(
1759
1491
  { artifactId, toolCallId, dataSource },
1760
1492
  "Using fallback data source for artifact summary"
1761
1493
  );
1762
1494
  } else {
1763
1495
  data = {};
1764
1496
  dataSource = "empty (no data found)";
1765
- logger6.warn(
1497
+ logger5.warn(
1766
1498
  {
1767
1499
  artifactId,
1768
1500
  toolCallId,
@@ -1799,7 +1531,7 @@ var ArtifactService = class _ArtifactService {
1799
1531
  data = artifact.parts?.[0]?.data;
1800
1532
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1801
1533
  dataSource = "parts[0].data (fallback)";
1802
- logger6.debug(
1534
+ logger5.debug(
1803
1535
  { artifactId, toolCallId, dataSource },
1804
1536
  "Using fallback data source for artifact full data"
1805
1537
  );
@@ -1807,14 +1539,14 @@ var ArtifactService = class _ArtifactService {
1807
1539
  data = artifact.data;
1808
1540
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1809
1541
  dataSource = "artifact.data (fallback)";
1810
- logger6.debug(
1542
+ logger5.debug(
1811
1543
  { artifactId, toolCallId, dataSource },
1812
1544
  "Using fallback data source for artifact full data"
1813
1545
  );
1814
1546
  } else {
1815
1547
  data = {};
1816
1548
  dataSource = "empty (no data found)";
1817
- logger6.warn(
1549
+ logger5.warn(
1818
1550
  {
1819
1551
  artifactId,
1820
1552
  toolCallId,
@@ -1868,7 +1600,7 @@ var ArtifactService = class _ArtifactService {
1868
1600
  const error = new Error(
1869
1601
  `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
1602
  );
1871
- logger6.error(
1603
+ logger5.error(
1872
1604
  {
1873
1605
  artifactId,
1874
1606
  artifactType,
@@ -1881,7 +1613,7 @@ var ArtifactService = class _ArtifactService {
1881
1613
  throw error;
1882
1614
  }
1883
1615
  if (!summaryValidation.hasExpectedFields || summaryValidation.extraFields.length > 0) {
1884
- logger6.warn(
1616
+ logger5.warn(
1885
1617
  {
1886
1618
  artifactId,
1887
1619
  artifactType,
@@ -1895,7 +1627,7 @@ var ArtifactService = class _ArtifactService {
1895
1627
  );
1896
1628
  }
1897
1629
  if (!fullValidation.hasExpectedFields || fullValidation.extraFields.length > 0) {
1898
- logger6.warn(
1630
+ logger5.warn(
1899
1631
  {
1900
1632
  artifactId,
1901
1633
  artifactType,
@@ -1967,7 +1699,7 @@ var ArtifactService = class _ArtifactService {
1967
1699
  }
1968
1700
  );
1969
1701
  } else {
1970
- logger6.warn(
1702
+ logger5.warn(
1971
1703
  {
1972
1704
  artifactId: request.artifactId,
1973
1705
  hasStreamRequestId: !!this.context.streamRequestId,
@@ -2042,7 +1774,7 @@ var ArtifactService = class _ArtifactService {
2042
1774
  summaryData = this.filterBySchema(artifact.data, previewSchema);
2043
1775
  fullData = this.filterBySchema(artifact.data, fullSchema);
2044
1776
  } catch (error) {
2045
- logger6.warn(
1777
+ logger5.warn(
2046
1778
  {
2047
1779
  artifactType: artifact.type,
2048
1780
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2080,7 +1812,7 @@ var ArtifactService = class _ArtifactService {
2080
1812
  artifact: artifactToSave
2081
1813
  });
2082
1814
  if (!result.created && result.existing) {
2083
- logger6.debug(
1815
+ logger5.debug(
2084
1816
  {
2085
1817
  artifactId: artifact.artifactId,
2086
1818
  taskId: this.context.taskId
@@ -2140,7 +1872,7 @@ var ArtifactService = class _ArtifactService {
2140
1872
  extracted[fieldName] = this.cleanEscapedContent(rawValue);
2141
1873
  }
2142
1874
  } catch (error) {
2143
- logger6.warn(
1875
+ logger5.warn(
2144
1876
  { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
2145
1877
  "Failed to extract schema field"
2146
1878
  );
@@ -2169,7 +1901,7 @@ var ArtifactService = class _ArtifactService {
2169
1901
  };
2170
1902
 
2171
1903
  // src/services/ArtifactParser.ts
2172
- var logger7 = getLogger("ArtifactParser");
1904
+ var logger6 = getLogger("ArtifactParser");
2173
1905
  var ArtifactParser = class _ArtifactParser {
2174
1906
  static ARTIFACT_CHECK_REGEX = /<artifact:ref\s+(?=.*id=['"][^'"]+['"])(?=.*tool=['"][^'"]+['"])[^>]*\/>/;
2175
1907
  static ATTR_REGEX = /(\w+)="([^"]*)"|(\w+)='([^']*)'|(\w+)=({[^}]+})/g;
@@ -2280,7 +2012,7 @@ var ArtifactParser = class _ArtifactParser {
2280
2012
  attrs[key] = value;
2281
2013
  }
2282
2014
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
2283
- logger7.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2015
+ logger6.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2284
2016
  return null;
2285
2017
  }
2286
2018
  return {
@@ -2341,7 +2073,7 @@ var ArtifactParser = class _ArtifactParser {
2341
2073
  `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
2342
2074
  );
2343
2075
  processedText = processedText.replace(annotation.raw, "");
2344
- logger7.warn(
2076
+ logger6.warn(
2345
2077
  { annotation, artifactData },
2346
2078
  "Removed failed artifact:create annotation from output"
2347
2079
  );
@@ -2352,11 +2084,11 @@ var ArtifactParser = class _ArtifactParser {
2352
2084
  if (annotation.raw) {
2353
2085
  processedText = processedText.replace(annotation.raw, "");
2354
2086
  }
2355
- logger7.error({ annotation, error }, "Failed to extract artifact from create annotation");
2087
+ logger6.error({ annotation, error }, "Failed to extract artifact from create annotation");
2356
2088
  }
2357
2089
  }
2358
2090
  if (failedAnnotations.length > 0) {
2359
- logger7.warn(
2091
+ logger6.warn(
2360
2092
  {
2361
2093
  failedCount: failedAnnotations.length,
2362
2094
  failures: failedAnnotations
@@ -2540,7 +2272,7 @@ var ArtifactParser = class _ArtifactParser {
2540
2272
  };
2541
2273
 
2542
2274
  // src/services/AgentSession.ts
2543
- var logger8 = getLogger("AgentSession");
2275
+ var logger7 = getLogger("AgentSession");
2544
2276
  var AgentSession = class {
2545
2277
  // Whether to send data operations
2546
2278
  constructor(sessionId, messageId, agentId, tenantId, projectId, contextId) {
@@ -2550,7 +2282,7 @@ var AgentSession = class {
2550
2282
  this.tenantId = tenantId;
2551
2283
  this.projectId = projectId;
2552
2284
  this.contextId = contextId;
2553
- logger8.debug({ sessionId, messageId, agentId }, "AgentSession created");
2285
+ logger7.debug({ sessionId, messageId, agentId }, "AgentSession created");
2554
2286
  if (tenantId && projectId) {
2555
2287
  toolSessionManager.createSessionWithId(
2556
2288
  sessionId,
@@ -2607,7 +2339,7 @@ var AgentSession = class {
2607
2339
  */
2608
2340
  enableEmitOperations() {
2609
2341
  this.isEmitOperations = true;
2610
- logger8.info(
2342
+ logger7.info(
2611
2343
  { sessionId: this.sessionId },
2612
2344
  "\u{1F50D} DEBUG: Emit operations enabled for AgentSession"
2613
2345
  );
@@ -2616,6 +2348,7 @@ var AgentSession = class {
2616
2348
  * Send data operation to stream when emit operations is enabled
2617
2349
  */
2618
2350
  async sendDataOperation(event) {
2351
+ console.log("sendDataOperation called with event", Date.now());
2619
2352
  try {
2620
2353
  const streamHelper = getStreamHelper(this.sessionId);
2621
2354
  if (streamHelper) {
@@ -2631,7 +2364,7 @@ var AgentSession = class {
2631
2364
  await streamHelper.writeOperation(formattedOperation);
2632
2365
  }
2633
2366
  } catch (error) {
2634
- logger8.error(
2367
+ logger7.error(
2635
2368
  {
2636
2369
  sessionId: this.sessionId,
2637
2370
  eventType: event.eventType,
@@ -2690,7 +2423,7 @@ var AgentSession = class {
2690
2423
  if (this.statusUpdateState.config.timeInSeconds) {
2691
2424
  this.statusUpdateTimer = setInterval(async () => {
2692
2425
  if (!this.statusUpdateState || this.isEnded) {
2693
- logger8.debug(
2426
+ logger7.debug(
2694
2427
  { sessionId: this.sessionId },
2695
2428
  "Timer triggered but session already cleaned up or ended"
2696
2429
  );
@@ -2702,7 +2435,7 @@ var AgentSession = class {
2702
2435
  }
2703
2436
  await this.checkAndSendTimeBasedUpdate();
2704
2437
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
2705
- logger8.info(
2438
+ logger7.info(
2706
2439
  {
2707
2440
  sessionId: this.sessionId,
2708
2441
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -2726,7 +2459,7 @@ var AgentSession = class {
2726
2459
  this.sendDataOperation(dataOpEvent);
2727
2460
  }
2728
2461
  if (this.isEnded) {
2729
- logger8.debug(
2462
+ logger7.debug(
2730
2463
  {
2731
2464
  sessionId: this.sessionId,
2732
2465
  eventType,
@@ -2748,7 +2481,7 @@ var AgentSession = class {
2748
2481
  if (artifactData.pendingGeneration) {
2749
2482
  const artifactId = artifactData.artifactId;
2750
2483
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2751
- logger8.warn(
2484
+ logger7.warn(
2752
2485
  {
2753
2486
  sessionId: this.sessionId,
2754
2487
  artifactId,
@@ -2770,7 +2503,7 @@ var AgentSession = class {
2770
2503
  this.artifactProcessingErrors.set(artifactId, errorCount);
2771
2504
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2772
2505
  this.pendingArtifacts.delete(artifactId);
2773
- logger8.error(
2506
+ logger7.error(
2774
2507
  {
2775
2508
  sessionId: this.sessionId,
2776
2509
  artifactId,
@@ -2782,7 +2515,7 @@ var AgentSession = class {
2782
2515
  "Artifact processing failed after max retries, giving up"
2783
2516
  );
2784
2517
  } else {
2785
- logger8.warn(
2518
+ logger7.warn(
2786
2519
  {
2787
2520
  sessionId: this.sessionId,
2788
2521
  artifactId,
@@ -2805,14 +2538,14 @@ var AgentSession = class {
2805
2538
  */
2806
2539
  checkStatusUpdates() {
2807
2540
  if (this.isEnded) {
2808
- logger8.debug(
2541
+ logger7.debug(
2809
2542
  { sessionId: this.sessionId },
2810
2543
  "Session has ended - skipping status update check"
2811
2544
  );
2812
2545
  return;
2813
2546
  }
2814
2547
  if (!this.statusUpdateState) {
2815
- logger8.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2548
+ logger7.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2816
2549
  return;
2817
2550
  }
2818
2551
  const statusUpdateState = this.statusUpdateState;
@@ -2823,11 +2556,11 @@ var AgentSession = class {
2823
2556
  */
2824
2557
  async checkAndSendTimeBasedUpdate() {
2825
2558
  if (this.isEnded) {
2826
- logger8.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2559
+ logger7.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2827
2560
  return;
2828
2561
  }
2829
2562
  if (!this.statusUpdateState) {
2830
- logger8.debug(
2563
+ logger7.debug(
2831
2564
  { sessionId: this.sessionId },
2832
2565
  "No status updates configured for time-based check"
2833
2566
  );
@@ -2840,7 +2573,7 @@ var AgentSession = class {
2840
2573
  try {
2841
2574
  await this.generateAndSendUpdate();
2842
2575
  } catch (error) {
2843
- logger8.error(
2576
+ logger7.error(
2844
2577
  {
2845
2578
  sessionId: this.sessionId,
2846
2579
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2943,29 +2676,29 @@ var AgentSession = class {
2943
2676
  */
2944
2677
  async generateAndSendUpdate() {
2945
2678
  if (this.isEnded) {
2946
- logger8.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2679
+ logger7.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2947
2680
  return;
2948
2681
  }
2949
2682
  if (this.isTextStreaming) {
2950
- logger8.debug(
2683
+ logger7.debug(
2951
2684
  { sessionId: this.sessionId },
2952
2685
  "Text is currently streaming - skipping status update"
2953
2686
  );
2954
2687
  return;
2955
2688
  }
2956
2689
  if (this.isGeneratingUpdate) {
2957
- logger8.debug(
2690
+ logger7.debug(
2958
2691
  { sessionId: this.sessionId },
2959
2692
  "Update already in progress - skipping duplicate generation"
2960
2693
  );
2961
2694
  return;
2962
2695
  }
2963
2696
  if (!this.statusUpdateState) {
2964
- logger8.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2697
+ logger7.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2965
2698
  return;
2966
2699
  }
2967
2700
  if (!this.agentId) {
2968
- logger8.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
2701
+ logger7.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
2969
2702
  return;
2970
2703
  }
2971
2704
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -2977,7 +2710,7 @@ var AgentSession = class {
2977
2710
  try {
2978
2711
  const streamHelper = getStreamHelper(this.sessionId);
2979
2712
  if (!streamHelper) {
2980
- logger8.warn(
2713
+ logger7.warn(
2981
2714
  { sessionId: this.sessionId },
2982
2715
  "No stream helper found - cannot send status update"
2983
2716
  );
@@ -2997,7 +2730,7 @@ var AgentSession = class {
2997
2730
  if (result.summaries && result.summaries.length > 0) {
2998
2731
  for (const summary of result.summaries) {
2999
2732
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
3000
- logger8.warn(
2733
+ logger7.warn(
3001
2734
  {
3002
2735
  sessionId: this.sessionId,
3003
2736
  summary
@@ -3034,7 +2767,7 @@ var AgentSession = class {
3034
2767
  this.statusUpdateState.lastEventCount = this.events.length;
3035
2768
  }
3036
2769
  } catch (error) {
3037
- logger8.error(
2770
+ logger7.error(
3038
2771
  {
3039
2772
  sessionId: this.sessionId,
3040
2773
  error: error instanceof Error ? error.message : "Unknown error",
@@ -3072,7 +2805,7 @@ var AgentSession = class {
3072
2805
  this.releaseUpdateLock();
3073
2806
  }
3074
2807
  } catch (error) {
3075
- logger8.error(
2808
+ logger7.error(
3076
2809
  {
3077
2810
  sessionId: this.sessionId,
3078
2811
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3151,7 +2884,7 @@ User's Question/Context:
3151
2884
  ${conversationHistory}
3152
2885
  ` : "";
3153
2886
  } catch (error) {
3154
- logger8.warn(
2887
+ logger7.warn(
3155
2888
  { sessionId: this.sessionId, error },
3156
2889
  "Failed to fetch conversation history for structured status update"
3157
2890
  );
@@ -3262,10 +2995,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3262
2995
  }
3263
2996
  });
3264
2997
  const result = object;
3265
- logger8.info({ result: JSON.stringify(result) }, "DEBUG: Result");
2998
+ logger7.info({ result: JSON.stringify(result) }, "DEBUG: Result");
3266
2999
  const summaries = [];
3267
3000
  for (const [componentId, data] of Object.entries(result)) {
3268
- logger8.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
3001
+ logger7.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
3269
3002
  if (componentId === "no_relevant_updates") {
3270
3003
  continue;
3271
3004
  }
@@ -3285,7 +3018,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3285
3018
  return { summaries };
3286
3019
  } catch (error) {
3287
3020
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3288
- logger8.error({ error }, "Failed to generate structured update, using fallback");
3021
+ logger7.error({ error }, "Failed to generate structured update, using fallback");
3289
3022
  return { summaries: [] };
3290
3023
  } finally {
3291
3024
  span.end();
@@ -3557,7 +3290,7 @@ Make it specific and relevant.`;
3557
3290
  });
3558
3291
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
3559
3292
  modelToUse = agentData.models.base;
3560
- logger8.info(
3293
+ logger7.info(
3561
3294
  {
3562
3295
  sessionId: this.sessionId,
3563
3296
  artifactId: artifactData.artifactId,
@@ -3568,7 +3301,7 @@ Make it specific and relevant.`;
3568
3301
  );
3569
3302
  }
3570
3303
  } catch (error) {
3571
- logger8.warn(
3304
+ logger7.warn(
3572
3305
  {
3573
3306
  sessionId: this.sessionId,
3574
3307
  artifactId: artifactData.artifactId,
@@ -3580,7 +3313,7 @@ Make it specific and relevant.`;
3580
3313
  }
3581
3314
  }
3582
3315
  if (!modelToUse?.model?.trim()) {
3583
- logger8.warn(
3316
+ logger7.warn(
3584
3317
  {
3585
3318
  sessionId: this.sessionId,
3586
3319
  artifactId: artifactData.artifactId
@@ -3662,7 +3395,7 @@ Make it specific and relevant.`;
3662
3395
  return result2;
3663
3396
  } catch (error) {
3664
3397
  lastError = error instanceof Error ? error : new Error(String(error));
3665
- logger8.warn(
3398
+ logger7.warn(
3666
3399
  {
3667
3400
  sessionId: this.sessionId,
3668
3401
  artifactId: artifactData.artifactId,
@@ -3710,7 +3443,7 @@ Make it specific and relevant.`;
3710
3443
  });
3711
3444
  span.setStatus({ code: SpanStatusCode.OK });
3712
3445
  } catch (saveError) {
3713
- logger8.error(
3446
+ logger7.error(
3714
3447
  {
3715
3448
  sessionId: this.sessionId,
3716
3449
  artifactId: artifactData.artifactId,
@@ -3738,7 +3471,7 @@ Make it specific and relevant.`;
3738
3471
  metadata: artifactData.metadata || {},
3739
3472
  toolCallId: artifactData.toolCallId
3740
3473
  });
3741
- logger8.info(
3474
+ logger7.info(
3742
3475
  {
3743
3476
  sessionId: this.sessionId,
3744
3477
  artifactId: artifactData.artifactId
@@ -3749,7 +3482,7 @@ Make it specific and relevant.`;
3749
3482
  } catch (fallbackError) {
3750
3483
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
3751
3484
  if (isDuplicateError) ; else {
3752
- logger8.error(
3485
+ logger7.error(
3753
3486
  {
3754
3487
  sessionId: this.sessionId,
3755
3488
  artifactId: artifactData.artifactId,
@@ -3762,7 +3495,7 @@ Make it specific and relevant.`;
3762
3495
  }
3763
3496
  } catch (error) {
3764
3497
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3765
- logger8.error(
3498
+ logger7.error(
3766
3499
  {
3767
3500
  sessionId: this.sessionId,
3768
3501
  artifactId: artifactData.artifactId,
@@ -3781,7 +3514,7 @@ Make it specific and relevant.`;
3781
3514
  */
3782
3515
  setArtifactCache(key, artifact) {
3783
3516
  this.artifactCache.set(key, artifact);
3784
- logger8.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3517
+ logger7.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3785
3518
  }
3786
3519
  /**
3787
3520
  * Get session-scoped ArtifactService instance
@@ -3800,7 +3533,7 @@ Make it specific and relevant.`;
3800
3533
  */
3801
3534
  getArtifactCache(key) {
3802
3535
  const artifact = this.artifactCache.get(key);
3803
- logger8.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3536
+ logger7.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3804
3537
  return artifact || null;
3805
3538
  }
3806
3539
  /**
@@ -3821,7 +3554,7 @@ var AgentSessionManager = class {
3821
3554
  const sessionId = messageId;
3822
3555
  const session = new AgentSession(sessionId, messageId, agentId, tenantId, projectId, contextId);
3823
3556
  this.sessions.set(sessionId, session);
3824
- logger8.info(
3557
+ logger7.info(
3825
3558
  { sessionId, messageId, agentId, tenantId, projectId, contextId },
3826
3559
  "AgentSession created"
3827
3560
  );
@@ -3835,7 +3568,7 @@ var AgentSessionManager = class {
3835
3568
  if (session) {
3836
3569
  session.initializeStatusUpdates(config, summarizerModel, baseModel);
3837
3570
  } else {
3838
- logger8.error(
3571
+ logger7.error(
3839
3572
  {
3840
3573
  sessionId,
3841
3574
  availableSessions: Array.from(this.sessions.keys())
@@ -3852,7 +3585,7 @@ var AgentSessionManager = class {
3852
3585
  if (session) {
3853
3586
  session.enableEmitOperations();
3854
3587
  } else {
3855
- logger8.error(
3588
+ logger7.error(
3856
3589
  {
3857
3590
  sessionId,
3858
3591
  availableSessions: Array.from(this.sessions.keys())
@@ -3874,7 +3607,7 @@ var AgentSessionManager = class {
3874
3607
  recordEvent(sessionId, eventType, subAgentId, data) {
3875
3608
  const session = this.sessions.get(sessionId);
3876
3609
  if (!session) {
3877
- logger8.warn({ sessionId }, "Attempted to record event in non-existent session");
3610
+ logger7.warn({ sessionId }, "Attempted to record event in non-existent session");
3878
3611
  return;
3879
3612
  }
3880
3613
  session.recordEvent(eventType, subAgentId, data);
@@ -3885,12 +3618,12 @@ var AgentSessionManager = class {
3885
3618
  endSession(sessionId) {
3886
3619
  const session = this.sessions.get(sessionId);
3887
3620
  if (!session) {
3888
- logger8.warn({ sessionId }, "Attempted to end non-existent session");
3621
+ logger7.warn({ sessionId }, "Attempted to end non-existent session");
3889
3622
  return [];
3890
3623
  }
3891
3624
  const events = session.getEvents();
3892
3625
  const summary = session.getSummary();
3893
- logger8.info({ sessionId, summary }, "AgentSession ended");
3626
+ logger7.info({ sessionId, summary }, "AgentSession ended");
3894
3627
  session.cleanup();
3895
3628
  this.sessions.delete(sessionId);
3896
3629
  return events;
@@ -3989,7 +3722,7 @@ async function resolveModelConfig(agentId, subAgent) {
3989
3722
  }
3990
3723
 
3991
3724
  // src/services/IncrementalStreamParser.ts
3992
- var logger9 = getLogger("IncrementalStreamParser");
3725
+ var logger8 = getLogger("IncrementalStreamParser");
3993
3726
  var IncrementalStreamParser = class _IncrementalStreamParser {
3994
3727
  buffer = "";
3995
3728
  pendingTextBuffer = "";
@@ -4047,7 +3780,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
4047
3780
  async initializeArtifactMap() {
4048
3781
  try {
4049
3782
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
4050
- logger9.debug(
3783
+ logger8.debug(
4051
3784
  {
4052
3785
  contextId: this.contextId,
4053
3786
  artifactMapSize: this.artifactMap.size
@@ -4055,7 +3788,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
4055
3788
  "Initialized artifact map for streaming"
4056
3789
  );
4057
3790
  } catch (error) {
4058
- logger9.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3791
+ logger8.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
4059
3792
  this.artifactMap = /* @__PURE__ */ new Map();
4060
3793
  }
4061
3794
  }
@@ -4388,6 +4121,142 @@ ${chunk}`;
4388
4121
  }
4389
4122
  };
4390
4123
 
4124
+ // src/services/PendingToolApprovalManager.ts
4125
+ var logger9 = getLogger("PendingToolApprovalManager");
4126
+ var APPROVAL_CLEANUP_INTERVAL_MS = 2 * 60 * 1e3;
4127
+ var APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
4128
+ var PendingToolApprovalManager = class _PendingToolApprovalManager {
4129
+ static instance;
4130
+ pendingApprovals = /* @__PURE__ */ new Map();
4131
+ constructor() {
4132
+ setInterval(() => this.cleanupExpiredApprovals(), APPROVAL_CLEANUP_INTERVAL_MS);
4133
+ }
4134
+ static getInstance() {
4135
+ if (!_PendingToolApprovalManager.instance) {
4136
+ _PendingToolApprovalManager.instance = new _PendingToolApprovalManager();
4137
+ }
4138
+ return _PendingToolApprovalManager.instance;
4139
+ }
4140
+ /**
4141
+ * Create a new pending approval and return a promise that resolves with approval status
4142
+ */
4143
+ async waitForApproval(toolCallId, toolName, args, conversationId, subAgentId) {
4144
+ return new Promise((resolve, reject) => {
4145
+ const timeoutId = setTimeout(() => {
4146
+ this.pendingApprovals.delete(toolCallId);
4147
+ resolve({
4148
+ approved: false,
4149
+ reason: `Tool approval timeout for ${toolName} (${toolCallId})`
4150
+ });
4151
+ }, APPROVAL_TIMEOUT_MS);
4152
+ const approval = {
4153
+ toolCallId,
4154
+ toolName,
4155
+ args,
4156
+ conversationId,
4157
+ subAgentId,
4158
+ createdAt: Date.now(),
4159
+ resolve,
4160
+ reject,
4161
+ timeoutId
4162
+ };
4163
+ this.pendingApprovals.set(toolCallId, approval);
4164
+ logger9.info(
4165
+ {
4166
+ toolCallId,
4167
+ toolName,
4168
+ conversationId,
4169
+ subAgentId
4170
+ },
4171
+ "Tool approval request created, waiting for user response"
4172
+ );
4173
+ });
4174
+ }
4175
+ /**
4176
+ * Approve a pending tool call
4177
+ */
4178
+ approveToolCall(toolCallId) {
4179
+ const approval = this.pendingApprovals.get(toolCallId);
4180
+ if (!approval) {
4181
+ logger9.warn({ toolCallId }, "Tool approval not found or already processed");
4182
+ return false;
4183
+ }
4184
+ logger9.info(
4185
+ {
4186
+ toolCallId,
4187
+ toolName: approval.toolName,
4188
+ conversationId: approval.conversationId
4189
+ },
4190
+ "Tool approved by user, resuming execution"
4191
+ );
4192
+ clearTimeout(approval.timeoutId);
4193
+ this.pendingApprovals.delete(toolCallId);
4194
+ approval.resolve({ approved: true });
4195
+ return true;
4196
+ }
4197
+ /**
4198
+ * Deny a pending tool call
4199
+ */
4200
+ denyToolCall(toolCallId, reason) {
4201
+ const approval = this.pendingApprovals.get(toolCallId);
4202
+ if (!approval) {
4203
+ logger9.warn({ toolCallId }, "Tool approval not found or already processed");
4204
+ return false;
4205
+ }
4206
+ logger9.info(
4207
+ {
4208
+ toolCallId,
4209
+ toolName: approval.toolName,
4210
+ conversationId: approval.conversationId,
4211
+ reason
4212
+ },
4213
+ "Tool execution denied by user"
4214
+ );
4215
+ clearTimeout(approval.timeoutId);
4216
+ this.pendingApprovals.delete(toolCallId);
4217
+ approval.resolve({
4218
+ approved: false,
4219
+ reason: reason || "User denied approval"
4220
+ });
4221
+ return true;
4222
+ }
4223
+ /**
4224
+ * Clean up expired approvals (called by interval timer)
4225
+ */
4226
+ cleanupExpiredApprovals() {
4227
+ const now = Date.now();
4228
+ let cleanedUp = 0;
4229
+ for (const [toolCallId, approval] of this.pendingApprovals) {
4230
+ if (now - approval.createdAt > APPROVAL_TIMEOUT_MS) {
4231
+ clearTimeout(approval.timeoutId);
4232
+ this.pendingApprovals.delete(toolCallId);
4233
+ approval.resolve({ approved: false, reason: "Tool approval expired" });
4234
+ cleanedUp++;
4235
+ }
4236
+ }
4237
+ if (cleanedUp > 0) {
4238
+ logger9.info({ cleanedUp }, "Cleaned up expired tool approvals");
4239
+ }
4240
+ }
4241
+ /**
4242
+ * Get current status for monitoring
4243
+ */
4244
+ getStatus() {
4245
+ return {
4246
+ pendingApprovals: this.pendingApprovals.size,
4247
+ approvals: Array.from(this.pendingApprovals.values()).map((approval) => ({
4248
+ toolCallId: approval.toolCallId,
4249
+ toolName: approval.toolName,
4250
+ conversationId: approval.conversationId,
4251
+ subAgentId: approval.subAgentId,
4252
+ createdAt: approval.createdAt,
4253
+ age: Date.now() - approval.createdAt
4254
+ }))
4255
+ };
4256
+ }
4257
+ };
4258
+ var pendingToolApprovalManager = PendingToolApprovalManager.getInstance();
4259
+
4391
4260
  // src/services/ResponseFormatter.ts
4392
4261
  var logger10 = getLogger("ResponseFormatter");
4393
4262
  var ResponseFormatter = class {
@@ -7192,7 +7061,7 @@ var Agent = class {
7192
7061
  /**
7193
7062
  * Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
7194
7063
  */
7195
- wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId) {
7064
+ wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId, options) {
7196
7065
  if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
7197
7066
  return toolDefinition;
7198
7067
  }
@@ -7214,13 +7083,24 @@ var Agent = class {
7214
7083
  });
7215
7084
  }
7216
7085
  const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_");
7086
+ const needsApproval = options?.needsApproval || false;
7217
7087
  if (streamRequestId && !isInternalTool) {
7218
- agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, {
7088
+ const toolCallData = {
7219
7089
  toolName,
7220
7090
  input: args,
7221
7091
  toolCallId,
7222
7092
  relationshipId
7223
- });
7093
+ };
7094
+ if (needsApproval) {
7095
+ toolCallData.needsApproval = true;
7096
+ toolCallData.conversationId = this.conversationId;
7097
+ }
7098
+ await agentSessionManager.recordEvent(
7099
+ streamRequestId,
7100
+ "tool_call",
7101
+ this.config.id,
7102
+ toolCallData
7103
+ );
7224
7104
  }
7225
7105
  try {
7226
7106
  const result = await originalExecute(args, context);
@@ -7265,7 +7145,8 @@ var Agent = class {
7265
7145
  output: result,
7266
7146
  toolCallId,
7267
7147
  duration,
7268
- relationshipId
7148
+ relationshipId,
7149
+ needsApproval
7269
7150
  });
7270
7151
  }
7271
7152
  return result;
@@ -7279,7 +7160,8 @@ var Agent = class {
7279
7160
  toolCallId,
7280
7161
  duration,
7281
7162
  error: errorMessage,
7282
- relationshipId
7163
+ relationshipId,
7164
+ needsApproval
7283
7165
  });
7284
7166
  }
7285
7167
  throw error;
@@ -7348,30 +7230,120 @@ var Agent = class {
7348
7230
  const wrappedTools2 = {};
7349
7231
  for (const [index, toolSet] of tools.entries()) {
7350
7232
  const relationshipId = mcpTools[index]?.relationshipId;
7351
- for (const [toolName, toolDef] of Object.entries(toolSet)) {
7233
+ for (const [toolName, toolDef] of Object.entries(toolSet.tools)) {
7234
+ const needsApproval = toolSet.toolPolicies?.[toolName]?.needsApproval || false;
7235
+ const enhancedTool = {
7236
+ ...toolDef,
7237
+ needsApproval
7238
+ };
7352
7239
  wrappedTools2[toolName] = this.wrapToolWithStreaming(
7353
7240
  toolName,
7354
- toolDef,
7241
+ enhancedTool,
7355
7242
  streamRequestId,
7356
7243
  "mcp",
7357
- relationshipId
7244
+ relationshipId,
7245
+ { needsApproval }
7358
7246
  );
7359
7247
  }
7360
7248
  }
7361
7249
  return wrappedTools2;
7362
7250
  }
7363
7251
  const wrappedTools = {};
7364
- for (const [index, toolSet] of tools.entries()) {
7252
+ for (const [index, toolResult] of tools.entries()) {
7365
7253
  const relationshipId = mcpTools[index]?.relationshipId;
7366
- for (const [toolName, originalTool] of Object.entries(toolSet)) {
7254
+ for (const [toolName, originalTool] of Object.entries(toolResult.tools)) {
7367
7255
  if (!isValidTool(originalTool)) {
7368
7256
  logger15.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7369
7257
  continue;
7370
7258
  }
7259
+ const needsApproval = toolResult.toolPolicies?.[toolName]?.needsApproval || false;
7260
+ logger15.debug(
7261
+ {
7262
+ toolName,
7263
+ toolPolicies: toolResult.toolPolicies,
7264
+ needsApproval,
7265
+ policyForThisTool: toolResult.toolPolicies?.[toolName]
7266
+ },
7267
+ "Tool approval check"
7268
+ );
7371
7269
  const sessionWrappedTool = tool({
7372
7270
  description: originalTool.description,
7373
7271
  inputSchema: originalTool.inputSchema,
7374
7272
  execute: async (args, { toolCallId }) => {
7273
+ if (needsApproval) {
7274
+ logger15.info(
7275
+ { toolName, toolCallId, args },
7276
+ "Tool requires approval - waiting for user response"
7277
+ );
7278
+ const currentSpan = trace.getActiveSpan();
7279
+ if (currentSpan) {
7280
+ currentSpan.addEvent("tool.approval.requested", {
7281
+ "tool.name": toolName,
7282
+ "tool.callId": toolCallId,
7283
+ "subAgent.id": this.config.id
7284
+ });
7285
+ }
7286
+ tracer.startActiveSpan(
7287
+ "tool.approval_requested",
7288
+ {
7289
+ attributes: {
7290
+ "tool.name": toolName,
7291
+ "tool.callId": toolCallId,
7292
+ "subAgent.id": this.config.id,
7293
+ "subAgent.name": this.config.name
7294
+ }
7295
+ },
7296
+ (requestSpan) => {
7297
+ requestSpan.setStatus({ code: SpanStatusCode.OK });
7298
+ requestSpan.end();
7299
+ }
7300
+ );
7301
+ const approvalResult = await pendingToolApprovalManager.waitForApproval(
7302
+ toolCallId,
7303
+ toolName,
7304
+ args,
7305
+ this.conversationId || "unknown",
7306
+ this.config.id
7307
+ );
7308
+ if (!approvalResult.approved) {
7309
+ return tracer.startActiveSpan(
7310
+ "tool.approval_denied",
7311
+ {
7312
+ attributes: {
7313
+ "tool.name": toolName,
7314
+ "tool.callId": toolCallId,
7315
+ "subAgent.id": this.config.id,
7316
+ "subAgent.name": this.config.name
7317
+ }
7318
+ },
7319
+ (denialSpan) => {
7320
+ logger15.info(
7321
+ { toolName, toolCallId, reason: approvalResult.reason },
7322
+ "Tool execution denied by user"
7323
+ );
7324
+ denialSpan.setStatus({ code: SpanStatusCode.OK });
7325
+ denialSpan.end();
7326
+ return `User denied approval to run this tool: ${approvalResult.reason}`;
7327
+ }
7328
+ );
7329
+ }
7330
+ tracer.startActiveSpan(
7331
+ "tool.approval_approved",
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
+ (approvedSpan) => {
7341
+ logger15.info({ toolName, toolCallId }, "Tool approved, continuing with execution");
7342
+ approvedSpan.setStatus({ code: SpanStatusCode.OK });
7343
+ approvedSpan.end();
7344
+ }
7345
+ );
7346
+ }
7375
7347
  logger15.debug({ toolName, toolCallId }, "MCP Tool Called");
7376
7348
  try {
7377
7349
  const rawResult = await originalTool.execute(args, { toolCallId });
@@ -7437,7 +7409,8 @@ var Agent = class {
7437
7409
  sessionWrappedTool,
7438
7410
  streamRequestId,
7439
7411
  "mcp",
7440
- relationshipId
7412
+ relationshipId,
7413
+ { needsApproval }
7441
7414
  );
7442
7415
  }
7443
7416
  }
@@ -7476,8 +7449,10 @@ var Agent = class {
7476
7449
  subAgentId: this.config.id
7477
7450
  }
7478
7451
  });
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;
7452
+ const toolRelation = toolsForAgent.data.find((t) => t.toolId === tool3.id);
7453
+ const agentToolRelationHeaders = toolRelation?.headers || void 0;
7454
+ const selectedTools = toolRelation?.selectedTools || void 0;
7455
+ const toolPolicies = toolRelation?.toolPolicies || {};
7481
7456
  let serverConfig;
7482
7457
  if (credentialReferenceId && this.credentialStuffer) {
7483
7458
  const credentialReference = await getCredentialReference(dbClient_default)({
@@ -7608,7 +7583,7 @@ var Agent = class {
7608
7583
  );
7609
7584
  }
7610
7585
  }
7611
- return tools;
7586
+ return { tools, toolPolicies };
7612
7587
  }
7613
7588
  async createMcpConnection(tool3, serverConfig) {
7614
7589
  const client = new McpClient({
@@ -7631,12 +7606,12 @@ var Agent = class {
7631
7606
  if (error?.cause && JSON.stringify(error.cause).includes("ECONNREFUSED")) {
7632
7607
  const errorMessage = "Connection refused. Please check if the MCP server is running.";
7633
7608
  throw new Error(errorMessage);
7634
- } else if (error.message.includes("404")) {
7609
+ }
7610
+ if (error.message.includes("404")) {
7635
7611
  const errorMessage = "Error accessing endpoint (HTTP 404)";
7636
7612
  throw new Error(errorMessage);
7637
- } else {
7638
- throw new Error(`MCP server connection failed: ${error.message}`);
7639
7613
  }
7614
+ throw new Error(`MCP server connection failed: ${error.message}`);
7640
7615
  }
7641
7616
  throw error;
7642
7617
  }
@@ -7656,7 +7631,7 @@ var Agent = class {
7656
7631
  if (functionToolsData.length === 0) {
7657
7632
  return functionTools;
7658
7633
  }
7659
- const { SandboxExecutorFactory } = await import('./SandboxExecutorFactory-NUNGK35F.js');
7634
+ const { SandboxExecutorFactory } = await import('./SandboxExecutorFactory-FVKDJKKZ.js');
7660
7635
  const sandboxExecutor = SandboxExecutorFactory.getInstance();
7661
7636
  for (const functionToolDef of functionToolsData) {
7662
7637
  const functionId = functionToolDef.functionId;
@@ -7950,7 +7925,7 @@ var Agent = class {
7950
7925
  inputSchema: tool3.inputSchema || tool3.parameters || {},
7951
7926
  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
7927
  }));
7953
- const { getConversationScopedArtifacts } = await import('./conversations-YFQ52RQB.js');
7928
+ const { getConversationScopedArtifacts } = await import('./conversations-NZLQK64L.js');
7954
7929
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
7955
7930
  const referenceArtifacts = await getConversationScopedArtifacts({
7956
7931
  tenantId: this.config.tenantId,
@@ -8534,13 +8509,13 @@ ${output}`;
8534
8509
  parser.markToolResult();
8535
8510
  }
8536
8511
  break;
8537
- case "error":
8512
+ case "error": {
8538
8513
  if (event.error instanceof Error) {
8539
8514
  throw event.error;
8540
- } else {
8541
- const errorMessage = event.error?.error?.message;
8542
- throw new Error(errorMessage);
8543
8515
  }
8516
+ const errorMessage = event.error?.error?.message;
8517
+ throw new Error(errorMessage);
8518
+ }
8544
8519
  }
8545
8520
  }
8546
8521
  await parser.finalize();
@@ -9435,17 +9410,16 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9435
9410
  }
9436
9411
  ]
9437
9412
  };
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
9413
  }
9414
+ logger16.warn(
9415
+ {
9416
+ hasToolResult: !!toolResult,
9417
+ hasOutput: !!toolResult?.output,
9418
+ validationPassed: false,
9419
+ output: toolResult?.output
9420
+ },
9421
+ "[DEBUG] Transfer validation FAILED"
9422
+ );
9449
9423
  }
9450
9424
  }
9451
9425
  }
@@ -10345,7 +10319,7 @@ var VercelDataStreamHelper = class _VercelDataStreamHelper {
10345
10319
  }
10346
10320
  const now = Date.now();
10347
10321
  const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
10348
- if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
10322
+ if (operation.type !== "tool_call" && operation.type !== "tool_result" && (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS)) {
10349
10323
  this.queuedEvents.push({ type: "data-operation", event: operation });
10350
10324
  return;
10351
10325
  }
@@ -11524,6 +11498,137 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11524
11498
  });
11525
11499
  }
11526
11500
  });
11501
+ var toolApprovalRoute = createRoute({
11502
+ method: "post",
11503
+ path: "/tool-approvals",
11504
+ tags: ["chat"],
11505
+ summary: "Approve or deny tool execution",
11506
+ description: "Handle user approval/denial of tool execution requests during conversations",
11507
+ security: [{ bearerAuth: [] }],
11508
+ request: {
11509
+ body: {
11510
+ content: {
11511
+ "application/json": {
11512
+ schema: z$1.object({
11513
+ conversationId: z$1.string().describe("The conversation ID"),
11514
+ toolCallId: z$1.string().describe("The tool call ID to respond to"),
11515
+ approved: z$1.boolean().describe("Whether the tool execution is approved"),
11516
+ reason: z$1.string().optional().describe("Optional reason for the decision")
11517
+ })
11518
+ }
11519
+ }
11520
+ }
11521
+ },
11522
+ responses: {
11523
+ 200: {
11524
+ description: "Tool approval response processed successfully",
11525
+ content: {
11526
+ "application/json": {
11527
+ schema: z$1.object({
11528
+ success: z$1.boolean(),
11529
+ message: z$1.string().optional()
11530
+ })
11531
+ }
11532
+ }
11533
+ },
11534
+ 400: {
11535
+ description: "Bad request - invalid tool call ID or conversation ID",
11536
+ content: {
11537
+ "application/json": {
11538
+ schema: z$1.object({
11539
+ error: z$1.string()
11540
+ })
11541
+ }
11542
+ }
11543
+ },
11544
+ 404: {
11545
+ description: "Tool call not found or already processed",
11546
+ content: {
11547
+ "application/json": {
11548
+ schema: z$1.object({
11549
+ error: z$1.string()
11550
+ })
11551
+ }
11552
+ }
11553
+ },
11554
+ 500: {
11555
+ description: "Internal server error",
11556
+ content: {
11557
+ "application/json": {
11558
+ schema: z$1.object({
11559
+ error: z$1.string(),
11560
+ message: z$1.string()
11561
+ })
11562
+ }
11563
+ }
11564
+ }
11565
+ }
11566
+ });
11567
+ app3.openapi(toolApprovalRoute, async (c) => {
11568
+ const tracer2 = trace.getTracer("tool-approval-handler");
11569
+ return tracer2.startActiveSpan("tool_approval_request", async (span) => {
11570
+ try {
11571
+ const executionContext = getRequestExecutionContext(c);
11572
+ const { tenantId, projectId } = executionContext;
11573
+ const requestBody = await c.req.json();
11574
+ const { conversationId, toolCallId, approved, reason } = requestBody;
11575
+ logger22.info(
11576
+ {
11577
+ conversationId,
11578
+ toolCallId,
11579
+ approved,
11580
+ reason,
11581
+ tenantId,
11582
+ projectId
11583
+ },
11584
+ "Processing tool approval request"
11585
+ );
11586
+ const conversation = await getConversation(dbClient_default)({
11587
+ scopes: { tenantId, projectId },
11588
+ conversationId
11589
+ });
11590
+ if (!conversation) {
11591
+ span.setStatus({ code: 1, message: "Conversation not found" });
11592
+ return c.json({ error: "Conversation not found" }, 404);
11593
+ }
11594
+ let success = false;
11595
+ if (approved) {
11596
+ success = pendingToolApprovalManager.approveToolCall(toolCallId);
11597
+ } else {
11598
+ success = pendingToolApprovalManager.denyToolCall(toolCallId, reason);
11599
+ }
11600
+ if (!success) {
11601
+ span.setStatus({ code: 1, message: "Tool call not found" });
11602
+ return c.json({ error: "Tool call not found or already processed" }, 404);
11603
+ }
11604
+ logger22.info({ conversationId, toolCallId, approved }, "Tool approval processed successfully");
11605
+ span.setStatus({ code: 1, message: "Success" });
11606
+ return c.json({
11607
+ success: true,
11608
+ message: approved ? "Tool execution approved" : "Tool execution denied"
11609
+ });
11610
+ } catch (error) {
11611
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
11612
+ logger22.error(
11613
+ {
11614
+ error: errorMessage,
11615
+ stack: error instanceof Error ? error.stack : void 0
11616
+ },
11617
+ "Failed to process tool approval"
11618
+ );
11619
+ span.setStatus({ code: 2, message: errorMessage });
11620
+ return c.json(
11621
+ {
11622
+ error: "Internal server error",
11623
+ message: errorMessage
11624
+ },
11625
+ 500
11626
+ );
11627
+ } finally {
11628
+ span.end();
11629
+ }
11630
+ });
11631
+ });
11527
11632
  var chatDataStream_default = app3;
11528
11633
  var logger23 = getLogger("mcp");
11529
11634
  var MockResponseSingleton = class _MockResponseSingleton {
@@ -11602,7 +11707,8 @@ var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
11602
11707
  })
11603
11708
  );
11604
11709
  return false;
11605
- } else if (Array.isArray(sessionId)) {
11710
+ }
11711
+ if (Array.isArray(sessionId)) {
11606
11712
  res.writeHead(400).end(
11607
11713
  JSON.stringify({
11608
11714
  jsonrpc: "2.0",
@@ -12025,16 +12131,15 @@ app4.openapi(
12025
12131
  c,
12026
12132
  credentialStores
12027
12133
  );
12028
- } else {
12029
- return await handleExistingSessionRequest(
12030
- body,
12031
- executionContext,
12032
- validatedContext,
12033
- req,
12034
- res,
12035
- credentialStores
12036
- );
12037
12134
  }
12135
+ return await handleExistingSessionRequest(
12136
+ body,
12137
+ executionContext,
12138
+ validatedContext,
12139
+ req,
12140
+ res,
12141
+ credentialStores
12142
+ );
12038
12143
  } catch (e) {
12039
12144
  logger23.error(
12040
12145
  {