@inkeep/agents-run-api 0.19.5 → 0.19.7

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,8 +1,8 @@
1
- import { flushBatchProcessor } from './chunk-XO4RG36I.js';
1
+ import { flushBatchProcessor } from './chunk-RZXPMRBA.js';
2
2
  import { getLogger } from './chunk-A2S7GSHL.js';
3
- import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-QRT6EIUX.js';
4
- import { dbClient_default } from './chunk-7IMXW4RD.js';
5
- import { env } from './chunk-NZHNG4A3.js';
3
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-T5AYIGCU.js';
4
+ import { dbClient_default } from './chunk-IBMWBEXH.js';
5
+ import { env } from './chunk-LHCIBW34.js';
6
6
  import { __publicField } from './chunk-PKBMQBKP.js';
7
7
  import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getAgentById, getRelatedAgentsForAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, getProject, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, getContextConfigById, getFullAgentDefinition, TemplateEngine, agentHasArtifactComponents, MCPTransportType, SPAN_KEYS, getExternalAgent } from '@inkeep/agents-core';
8
8
  import { otel } from '@hono/otel';
@@ -3023,7 +3023,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3023
3023
  "agent_session.id": this.sessionId,
3024
3024
  "artifact.id": artifactData.artifactId,
3025
3025
  "artifact.type": artifactData.artifactType || "unknown",
3026
- "artifact.agent_id": artifactData.subAgentId || "unknown",
3026
+ "artifact.sub_agent_id": artifactData.subAgentId || "unknown",
3027
3027
  "artifact.tool_call_id": artifactData.metadata?.toolCallId || "unknown",
3028
3028
  "artifact.data": JSON.stringify(artifactData.data, null, 2),
3029
3029
  "tenant.id": artifactData.tenantId || "unknown",
@@ -6658,7 +6658,7 @@ var Agent = class {
6658
6658
  "conversation.id": this.conversationId,
6659
6659
  "tool.purpose": toolDefinition.description || "No description provided",
6660
6660
  "ai.toolType": toolType || "unknown",
6661
- "ai.agentName": this.config.name || "unknown",
6661
+ "ai.subAgentName": this.config.name || "unknown",
6662
6662
  "agent.id": this.config.agentId || "unknown"
6663
6663
  });
6664
6664
  }
@@ -6945,7 +6945,7 @@ var Agent = class {
6945
6945
  originalToolName: tool3.name
6946
6946
  }),
6947
6947
  "ai.toolType": "mcp",
6948
- "ai.agentName": this.config.name || "unknown",
6948
+ "ai.subAgentName": this.config.name || "unknown",
6949
6949
  "conversation.id": this.conversationId || "unknown",
6950
6950
  "agent.id": this.config.agentId || "unknown",
6951
6951
  "tenant.id": this.config.tenantId || "unknown",
@@ -7310,7 +7310,7 @@ var Agent = class {
7310
7310
  inputSchema: tool3.inputSchema || tool3.parameters || {},
7311
7311
  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."
7312
7312
  }));
7313
- const { getConversationScopedArtifacts } = await import('./conversations-OFIM2WLJ.js');
7313
+ const { getConversationScopedArtifacts } = await import('./conversations-6OGSD67W.js');
7314
7314
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
7315
7315
  const referenceArtifacts = await getConversationScopedArtifacts({
7316
7316
  tenantId: this.config.tenantId,
@@ -7667,7 +7667,7 @@ var Agent = class {
7667
7667
  "agent.load_tools",
7668
7668
  {
7669
7669
  attributes: {
7670
- "agent.name": this.config.name,
7670
+ "subAgent.name": this.config.name,
7671
7671
  "session.id": sessionId
7672
7672
  }
7673
7673
  },
@@ -9808,7 +9808,7 @@ var ExecutionHandler = class {
9808
9808
  span.setAttributes({
9809
9809
  "ai.response.content": textContent || "No response content",
9810
9810
  "ai.response.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
9811
- "ai.agent.name": currentAgentId
9811
+ "ai.subAgent.name": currentAgentId
9812
9812
  });
9813
9813
  await createMessage(dbClient_default)({
9814
9814
  id: nanoid(),
@@ -10084,174 +10084,191 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10084
10084
  );
10085
10085
  const body = c.get("requestBody") || {};
10086
10086
  const conversationId = body.conversationId || getConversationId();
10087
- const fullAgent = await getFullAgent(dbClient_default)({
10088
- scopes: { tenantId, projectId, agentId }
10089
- });
10090
- let agent;
10091
- let defaultSubAgentId;
10092
- if (fullAgent) {
10093
- agent = {
10094
- id: fullAgent.id,
10095
- name: fullAgent.name,
10096
- tenantId,
10097
- projectId,
10098
- defaultSubAgentId: fullAgent.defaultSubAgentId
10099
- };
10100
- const agentKeys = Object.keys(fullAgent.subAgents || {});
10101
- const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
10102
- defaultSubAgentId = fullAgent.defaultSubAgentId || firstAgentId;
10103
- } else {
10104
- agent = await getAgentWithDefaultSubAgent(dbClient_default)({
10087
+ const activeSpan = trace.getActiveSpan();
10088
+ if (activeSpan) {
10089
+ activeSpan.setAttributes({
10090
+ "conversation.id": conversationId,
10091
+ "tenant.id": tenantId,
10092
+ "agent.id": agentId,
10093
+ "project.id": projectId
10094
+ });
10095
+ }
10096
+ let currentBag = propagation.getBaggage(context.active());
10097
+ if (!currentBag) {
10098
+ currentBag = propagation.createBaggage();
10099
+ }
10100
+ currentBag = currentBag.setEntry("conversation.id", { value: conversationId });
10101
+ const ctxWithBaggage = propagation.setBaggage(context.active(), currentBag);
10102
+ return await context.with(ctxWithBaggage, async () => {
10103
+ const fullAgent = await getFullAgent(dbClient_default)({
10105
10104
  scopes: { tenantId, projectId, agentId }
10106
10105
  });
10107
- if (!agent) {
10106
+ let agent;
10107
+ let defaultSubAgentId;
10108
+ if (fullAgent) {
10109
+ agent = {
10110
+ id: fullAgent.id,
10111
+ name: fullAgent.name,
10112
+ tenantId,
10113
+ projectId,
10114
+ defaultSubAgentId: fullAgent.defaultSubAgentId
10115
+ };
10116
+ const agentKeys = Object.keys(fullAgent.subAgents || {});
10117
+ const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
10118
+ defaultSubAgentId = fullAgent.defaultSubAgentId || firstAgentId;
10119
+ } else {
10120
+ agent = await getAgentWithDefaultSubAgent(dbClient_default)({
10121
+ scopes: { tenantId, projectId, agentId }
10122
+ });
10123
+ if (!agent) {
10124
+ throw createApiError({
10125
+ code: "not_found",
10126
+ message: "Agent not found"
10127
+ });
10128
+ }
10129
+ defaultSubAgentId = agent.defaultSubAgentId || "";
10130
+ }
10131
+ if (!defaultSubAgentId) {
10108
10132
  throw createApiError({
10109
10133
  code: "not_found",
10110
- message: "Agent not found"
10134
+ message: "No default agent found in agent"
10111
10135
  });
10112
10136
  }
10113
- defaultSubAgentId = agent.defaultSubAgentId || "";
10114
- }
10115
- if (!defaultSubAgentId) {
10116
- throw createApiError({
10117
- code: "not_found",
10118
- message: "No default agent found in agent"
10137
+ await createOrGetConversation(dbClient_default)({
10138
+ tenantId,
10139
+ projectId,
10140
+ id: conversationId,
10141
+ activeSubAgentId: defaultSubAgentId
10119
10142
  });
10120
- }
10121
- await createOrGetConversation(dbClient_default)({
10122
- tenantId,
10123
- projectId,
10124
- id: conversationId,
10125
- activeSubAgentId: defaultSubAgentId
10126
- });
10127
- const activeAgent = await getActiveAgentForConversation(dbClient_default)({
10128
- scopes: { tenantId, projectId },
10129
- conversationId
10130
- });
10131
- if (!activeAgent) {
10132
- setActiveAgentForConversation(dbClient_default)({
10143
+ const activeAgent = await getActiveAgentForConversation(dbClient_default)({
10133
10144
  scopes: { tenantId, projectId },
10134
- conversationId,
10135
- subAgentId: defaultSubAgentId
10145
+ conversationId
10136
10146
  });
10137
- }
10138
- const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
10139
- const agentInfo = await getSubAgentById(dbClient_default)({
10140
- scopes: { tenantId, projectId, agentId },
10141
- subAgentId
10142
- });
10143
- if (!agentInfo) {
10144
- throw createApiError({
10145
- code: "not_found",
10146
- message: "Agent not found"
10147
+ if (!activeAgent) {
10148
+ setActiveAgentForConversation(dbClient_default)({
10149
+ scopes: { tenantId, projectId },
10150
+ conversationId,
10151
+ subAgentId: defaultSubAgentId
10152
+ });
10153
+ }
10154
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
10155
+ const agentInfo = await getSubAgentById(dbClient_default)({
10156
+ scopes: { tenantId, projectId, agentId },
10157
+ subAgentId
10147
10158
  });
10148
- }
10149
- const validatedContext = c.get("validatedContext") || body.headers || {};
10150
- const credentialStores = c.get("credentialStores");
10151
- await handleContextResolution({
10152
- tenantId,
10153
- projectId,
10154
- agentId,
10155
- conversationId,
10156
- headers: validatedContext,
10157
- dbClient: dbClient_default,
10158
- credentialStores
10159
- });
10160
- logger21.info(
10161
- {
10159
+ if (!agentInfo) {
10160
+ throw createApiError({
10161
+ code: "not_found",
10162
+ message: "Agent not found"
10163
+ });
10164
+ }
10165
+ const validatedContext = c.get("validatedContext") || body.headers || {};
10166
+ const credentialStores = c.get("credentialStores");
10167
+ await handleContextResolution({
10162
10168
  tenantId,
10163
10169
  projectId,
10164
10170
  agentId,
10165
10171
  conversationId,
10166
- defaultSubAgentId,
10167
- activeSubAgentId: activeAgent?.activeSubAgentId || "none",
10168
- hasContextConfig: !!agent.contextConfigId,
10169
- hasHeaders: !!body.headers,
10170
- hasValidatedContext: !!validatedContext,
10171
- validatedContextKeys: Object.keys(validatedContext)
10172
- },
10173
- "parameters"
10174
- );
10175
- const requestId2 = `chatcmpl-${Date.now()}`;
10176
- const timestamp = Math.floor(Date.now() / 1e3);
10177
- const lastUserMessage = body.messages.filter((msg) => msg.role === "user").slice(-1)[0];
10178
- const userMessage = lastUserMessage ? getMessageText(lastUserMessage.content) : "";
10179
- const messageSpan = trace.getActiveSpan();
10180
- if (messageSpan) {
10181
- messageSpan.setAttributes({
10182
- "message.content": userMessage,
10183
- "message.timestamp": Date.now()
10172
+ headers: validatedContext,
10173
+ dbClient: dbClient_default,
10174
+ credentialStores
10184
10175
  });
10185
- }
10186
- await createMessage(dbClient_default)({
10187
- id: nanoid(),
10188
- tenantId,
10189
- projectId,
10190
- conversationId,
10191
- role: "user",
10192
- content: {
10193
- text: userMessage
10194
- },
10195
- visibility: "user-facing",
10196
- messageType: "chat"
10197
- });
10198
- if (messageSpan) {
10199
- messageSpan.addEvent("user.message.stored", {
10200
- "message.id": conversationId,
10201
- "database.operation": "insert"
10202
- });
10203
- }
10204
- return streamSSE(c, async (stream2) => {
10205
- try {
10206
- const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
10207
- await sseHelper.writeRole();
10208
- logger21.info({ subAgentId }, "Starting execution");
10209
- const emitOperationsHeader = c.req.header("x-emit-operations");
10210
- const emitOperations = emitOperationsHeader === "true";
10211
- const executionHandler = new ExecutionHandler();
10212
- const result = await executionHandler.execute({
10213
- executionContext,
10176
+ logger21.info(
10177
+ {
10178
+ tenantId,
10179
+ projectId,
10180
+ agentId,
10214
10181
  conversationId,
10215
- userMessage,
10216
- initialAgentId: subAgentId,
10217
- requestId: requestId2,
10218
- sseHelper,
10219
- emitOperations
10182
+ defaultSubAgentId,
10183
+ activeSubAgentId: activeAgent?.activeSubAgentId || "none",
10184
+ hasContextConfig: !!agent.contextConfigId,
10185
+ hasHeaders: !!body.headers,
10186
+ hasValidatedContext: !!validatedContext,
10187
+ validatedContextKeys: Object.keys(validatedContext)
10188
+ },
10189
+ "parameters"
10190
+ );
10191
+ const requestId2 = `chatcmpl-${Date.now()}`;
10192
+ const timestamp = Math.floor(Date.now() / 1e3);
10193
+ const lastUserMessage = body.messages.filter((msg) => msg.role === "user").slice(-1)[0];
10194
+ const userMessage = lastUserMessage ? getMessageText(lastUserMessage.content) : "";
10195
+ const messageSpan = trace.getActiveSpan();
10196
+ if (messageSpan) {
10197
+ messageSpan.setAttributes({
10198
+ "message.content": userMessage,
10199
+ "message.timestamp": Date.now()
10220
10200
  });
10221
- logger21.info(
10222
- { result },
10223
- `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10224
- );
10225
- if (!result.success) {
10226
- await sseHelper.writeOperation(
10227
- errorOp(
10228
- "Sorry, I was unable to process your request at this time. Please try again.",
10229
- "system"
10230
- )
10231
- );
10232
- }
10233
- await sseHelper.complete();
10234
- } catch (error) {
10235
- logger21.error(
10236
- {
10237
- error: error instanceof Error ? error.message : error,
10238
- stack: error instanceof Error ? error.stack : void 0
10239
- },
10240
- "Error during streaming execution"
10241
- );
10201
+ }
10202
+ await createMessage(dbClient_default)({
10203
+ id: nanoid(),
10204
+ tenantId,
10205
+ projectId,
10206
+ conversationId,
10207
+ role: "user",
10208
+ content: {
10209
+ text: userMessage
10210
+ },
10211
+ visibility: "user-facing",
10212
+ messageType: "chat"
10213
+ });
10214
+ if (messageSpan) {
10215
+ messageSpan.addEvent("user.message.stored", {
10216
+ "message.id": conversationId,
10217
+ "database.operation": "insert"
10218
+ });
10219
+ }
10220
+ return streamSSE(c, async (stream2) => {
10242
10221
  try {
10243
10222
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
10244
- await sseHelper.writeOperation(
10245
- errorOp(
10246
- "Sorry, I was unable to process your request at this time. Please try again.",
10247
- "system"
10248
- )
10223
+ await sseHelper.writeRole();
10224
+ logger21.info({ subAgentId }, "Starting execution");
10225
+ const emitOperationsHeader = c.req.header("x-emit-operations");
10226
+ const emitOperations = emitOperationsHeader === "true";
10227
+ const executionHandler = new ExecutionHandler();
10228
+ const result = await executionHandler.execute({
10229
+ executionContext,
10230
+ conversationId,
10231
+ userMessage,
10232
+ initialAgentId: subAgentId,
10233
+ requestId: requestId2,
10234
+ sseHelper,
10235
+ emitOperations
10236
+ });
10237
+ logger21.info(
10238
+ { result },
10239
+ `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10249
10240
  );
10241
+ if (!result.success) {
10242
+ await sseHelper.writeOperation(
10243
+ errorOp(
10244
+ "Sorry, I was unable to process your request at this time. Please try again.",
10245
+ "system"
10246
+ )
10247
+ );
10248
+ }
10250
10249
  await sseHelper.complete();
10251
- } catch (streamError) {
10252
- logger21.error({ streamError }, "Failed to write error to stream");
10250
+ } catch (error) {
10251
+ logger21.error(
10252
+ {
10253
+ error: error instanceof Error ? error.message : error,
10254
+ stack: error instanceof Error ? error.stack : void 0
10255
+ },
10256
+ "Error during streaming execution"
10257
+ );
10258
+ try {
10259
+ const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
10260
+ await sseHelper.writeOperation(
10261
+ errorOp(
10262
+ "Sorry, I was unable to process your request at this time. Please try again.",
10263
+ "system"
10264
+ )
10265
+ );
10266
+ await sseHelper.complete();
10267
+ } catch (streamError) {
10268
+ logger21.error({ streamError }, "Failed to write error to stream");
10269
+ }
10253
10270
  }
10254
- }
10271
+ });
10255
10272
  });
10256
10273
  } catch (error) {
10257
10274
  logger21.error(
@@ -10343,123 +10360,131 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10343
10360
  "project.id": projectId
10344
10361
  });
10345
10362
  }
10346
- const agent = await getAgentWithDefaultSubAgent(dbClient_default)({
10347
- scopes: { tenantId, projectId, agentId }
10348
- });
10349
- if (!agent) {
10350
- throw createApiError({
10351
- code: "not_found",
10352
- message: "Agent not found"
10353
- });
10363
+ let currentBag = propagation.getBaggage(context.active());
10364
+ if (!currentBag) {
10365
+ currentBag = propagation.createBaggage();
10354
10366
  }
10355
- const defaultSubAgentId = agent.defaultSubAgentId;
10356
- const agentName = agent.name;
10357
- if (!defaultSubAgentId) {
10358
- throw createApiError({
10359
- code: "bad_request",
10360
- message: "Agent does not have a default agent configured"
10367
+ currentBag = currentBag.setEntry("conversation.id", { value: conversationId });
10368
+ const ctxWithBaggage = propagation.setBaggage(context.active(), currentBag);
10369
+ return await context.with(ctxWithBaggage, async () => {
10370
+ const agent = await getAgentWithDefaultSubAgent(dbClient_default)({
10371
+ scopes: { tenantId, projectId, agentId }
10361
10372
  });
10362
- }
10363
- const activeAgent = await getActiveAgentForConversation(dbClient_default)({
10364
- scopes: { tenantId, projectId },
10365
- conversationId
10366
- });
10367
- if (!activeAgent) {
10368
- setActiveAgentForConversation(dbClient_default)({
10373
+ if (!agent) {
10374
+ throw createApiError({
10375
+ code: "not_found",
10376
+ message: "Agent not found"
10377
+ });
10378
+ }
10379
+ const defaultSubAgentId = agent.defaultSubAgentId;
10380
+ const agentName = agent.name;
10381
+ if (!defaultSubAgentId) {
10382
+ throw createApiError({
10383
+ code: "bad_request",
10384
+ message: "Agent does not have a default agent configured"
10385
+ });
10386
+ }
10387
+ const activeAgent = await getActiveAgentForConversation(dbClient_default)({
10369
10388
  scopes: { tenantId, projectId },
10370
- conversationId,
10371
- subAgentId: defaultSubAgentId
10389
+ conversationId
10372
10390
  });
10373
- }
10374
- const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
10375
- const agentInfo = await getSubAgentById(dbClient_default)({
10376
- scopes: { tenantId, projectId, agentId },
10377
- subAgentId
10378
- });
10379
- if (!agentInfo) {
10380
- throw createApiError({
10381
- code: "not_found",
10382
- message: "Agent not found"
10391
+ if (!activeAgent) {
10392
+ setActiveAgentForConversation(dbClient_default)({
10393
+ scopes: { tenantId, projectId },
10394
+ conversationId,
10395
+ subAgentId: defaultSubAgentId
10396
+ });
10397
+ }
10398
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
10399
+ const agentInfo = await getSubAgentById(dbClient_default)({
10400
+ scopes: { tenantId, projectId, agentId },
10401
+ subAgentId
10383
10402
  });
10384
- }
10385
- const validatedContext = c.get("validatedContext") || body.headers || {};
10386
- const credentialStores = c.get("credentialStores");
10387
- await handleContextResolution({
10388
- tenantId,
10389
- projectId,
10390
- agentId,
10391
- conversationId,
10392
- headers: validatedContext,
10393
- dbClient: dbClient_default,
10394
- credentialStores
10395
- });
10396
- const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
10397
- const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
10398
- logger22.info({ userText, lastUserMessage }, "userText");
10399
- const messageSpan = trace.getActiveSpan();
10400
- if (messageSpan) {
10401
- messageSpan.setAttributes({
10402
- "message.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
10403
- "message.content": userText,
10404
- "agent.name": agentName
10403
+ if (!agentInfo) {
10404
+ throw createApiError({
10405
+ code: "not_found",
10406
+ message: "Agent not found"
10407
+ });
10408
+ }
10409
+ const validatedContext = c.get("validatedContext") || body.headers || {};
10410
+ const credentialStores = c.get("credentialStores");
10411
+ await handleContextResolution({
10412
+ tenantId,
10413
+ projectId,
10414
+ agentId,
10415
+ conversationId,
10416
+ headers: validatedContext,
10417
+ dbClient: dbClient_default,
10418
+ credentialStores
10405
10419
  });
10406
- }
10407
- await createMessage(dbClient_default)({
10408
- id: nanoid(),
10409
- tenantId,
10410
- projectId,
10411
- conversationId,
10412
- role: "user",
10413
- content: { text: userText },
10414
- visibility: "user-facing",
10415
- messageType: "chat"
10416
- });
10417
- if (messageSpan) {
10418
- messageSpan.addEvent("user.message.stored", {
10419
- "message.id": conversationId,
10420
- "database.operation": "insert"
10420
+ const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
10421
+ const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
10422
+ logger22.info({ userText, lastUserMessage }, "userText");
10423
+ const messageSpan = trace.getActiveSpan();
10424
+ if (messageSpan) {
10425
+ messageSpan.setAttributes({
10426
+ "message.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
10427
+ "message.content": userText,
10428
+ "agent.name": agentName
10429
+ });
10430
+ }
10431
+ await createMessage(dbClient_default)({
10432
+ id: nanoid(),
10433
+ tenantId,
10434
+ projectId,
10435
+ conversationId,
10436
+ role: "user",
10437
+ content: { text: userText },
10438
+ visibility: "user-facing",
10439
+ messageType: "chat"
10421
10440
  });
10422
- }
10423
- const dataStream = createUIMessageStream({
10424
- execute: async ({ writer }) => {
10425
- const streamHelper = createVercelStreamHelper(writer);
10426
- try {
10427
- const emitOperationsHeader = c.req.header("x-emit-operations");
10428
- const emitOperations = emitOperationsHeader === "true";
10429
- const executionHandler = new ExecutionHandler();
10430
- const result = await executionHandler.execute({
10431
- executionContext,
10432
- conversationId,
10433
- userMessage: userText,
10434
- initialAgentId: subAgentId,
10435
- requestId: `chatds-${Date.now()}`,
10436
- sseHelper: streamHelper,
10437
- emitOperations
10438
- });
10439
- if (!result.success) {
10440
- await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
10441
- }
10442
- } catch (err) {
10443
- logger22.error({ err }, "Streaming error");
10444
- await streamHelper.writeOperation(errorOp("Internal server error", "system"));
10445
- } finally {
10446
- if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
10447
- streamHelper.cleanup();
10441
+ if (messageSpan) {
10442
+ messageSpan.addEvent("user.message.stored", {
10443
+ "message.id": conversationId,
10444
+ "database.operation": "insert"
10445
+ });
10446
+ }
10447
+ const dataStream = createUIMessageStream({
10448
+ execute: async ({ writer }) => {
10449
+ const streamHelper = createVercelStreamHelper(writer);
10450
+ try {
10451
+ const emitOperationsHeader = c.req.header("x-emit-operations");
10452
+ const emitOperations = emitOperationsHeader === "true";
10453
+ const executionHandler = new ExecutionHandler();
10454
+ const result = await executionHandler.execute({
10455
+ executionContext,
10456
+ conversationId,
10457
+ userMessage: userText,
10458
+ initialAgentId: subAgentId,
10459
+ requestId: `chatds-${Date.now()}`,
10460
+ sseHelper: streamHelper,
10461
+ emitOperations
10462
+ });
10463
+ if (!result.success) {
10464
+ await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
10465
+ }
10466
+ } catch (err) {
10467
+ logger22.error({ err }, "Streaming error");
10468
+ await streamHelper.writeOperation(errorOp("Internal server error", "system"));
10469
+ } finally {
10470
+ if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
10471
+ streamHelper.cleanup();
10472
+ }
10448
10473
  }
10449
10474
  }
10450
- }
10475
+ });
10476
+ c.header("content-type", "text/event-stream");
10477
+ c.header("cache-control", "no-cache");
10478
+ c.header("connection", "keep-alive");
10479
+ c.header("x-vercel-ai-data-stream", "v2");
10480
+ c.header("x-accel-buffering", "no");
10481
+ return stream(
10482
+ c,
10483
+ (stream2) => stream2.pipe(
10484
+ dataStream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
10485
+ )
10486
+ );
10451
10487
  });
10452
- c.header("content-type", "text/event-stream");
10453
- c.header("cache-control", "no-cache");
10454
- c.header("connection", "keep-alive");
10455
- c.header("x-vercel-ai-data-stream", "v2");
10456
- c.header("x-accel-buffering", "no");
10457
- return stream(
10458
- c,
10459
- (stream2) => stream2.pipe(
10460
- dataStream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
10461
- )
10462
- );
10463
10488
  } catch (error) {
10464
10489
  logger22.error({ error }, "chatDataStream error");
10465
10490
  throw createApiError({
@@ -10787,66 +10812,83 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10787
10812
  const { tenantId, projectId, agentId } = executionContext;
10788
10813
  logger23.info({ body }, "Received initialization request");
10789
10814
  const sessionId = getConversationId();
10790
- const agent = await getAgentWithDefaultSubAgent(dbClient_default)({
10791
- scopes: { tenantId, projectId, agentId }
10792
- });
10793
- if (!agent) {
10794
- return c.json(
10795
- {
10796
- jsonrpc: "2.0",
10797
- error: { code: -32001, message: "Agent not found" },
10798
- id: body.id || null
10799
- },
10800
- { status: 404 }
10801
- );
10815
+ const activeSpan = trace.getActiveSpan();
10816
+ if (activeSpan) {
10817
+ activeSpan.setAttributes({
10818
+ "conversation.id": sessionId,
10819
+ "tenant.id": tenantId,
10820
+ "agent.id": agentId,
10821
+ "project.id": projectId
10822
+ });
10823
+ }
10824
+ let currentBag = propagation.getBaggage(context.active());
10825
+ if (!currentBag) {
10826
+ currentBag = propagation.createBaggage();
10802
10827
  }
10803
- if (!agent.defaultSubAgentId) {
10804
- return c.json(
10828
+ currentBag = currentBag.setEntry("conversation.id", { value: sessionId });
10829
+ const ctxWithBaggage = propagation.setBaggage(context.active(), currentBag);
10830
+ return await context.with(ctxWithBaggage, async () => {
10831
+ const agent = await getAgentWithDefaultSubAgent(dbClient_default)({
10832
+ scopes: { tenantId, projectId, agentId }
10833
+ });
10834
+ if (!agent) {
10835
+ return c.json(
10836
+ {
10837
+ jsonrpc: "2.0",
10838
+ error: { code: -32001, message: "Agent not found" },
10839
+ id: body.id || null
10840
+ },
10841
+ { status: 404 }
10842
+ );
10843
+ }
10844
+ if (!agent.defaultSubAgentId) {
10845
+ return c.json(
10846
+ {
10847
+ jsonrpc: "2.0",
10848
+ error: { code: -32001, message: "Agent does not have a default agent configured" },
10849
+ id: body.id || null
10850
+ },
10851
+ { status: 400 }
10852
+ );
10853
+ }
10854
+ const conversation = await createOrGetConversation(dbClient_default)({
10855
+ id: sessionId,
10856
+ tenantId,
10857
+ projectId,
10858
+ activeSubAgentId: agent.defaultSubAgentId,
10859
+ metadata: {
10860
+ sessionData: {
10861
+ agentId,
10862
+ sessionType: "mcp",
10863
+ mcpProtocolVersion: c.req.header("mcp-protocol-version"),
10864
+ initialized: false
10865
+ // Track initialization state
10866
+ }
10867
+ }
10868
+ });
10869
+ logger23.info(
10870
+ { sessionId, conversationId: conversation.id },
10871
+ "Created MCP session as conversation"
10872
+ );
10873
+ const transport = new StreamableHTTPServerTransport({
10874
+ sessionIdGenerator: () => sessionId
10875
+ });
10876
+ const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
10877
+ await server.connect(transport);
10878
+ logger23.info({ sessionId }, "Server connected for initialization");
10879
+ res.setHeader("Mcp-Session-Id", sessionId);
10880
+ logger23.info(
10805
10881
  {
10806
- jsonrpc: "2.0",
10807
- error: { code: -32001, message: "Agent does not have a default agent configured" },
10808
- id: body.id || null
10882
+ sessionId,
10883
+ bodyMethod: body?.method,
10884
+ bodyId: body?.id
10809
10885
  },
10810
- { status: 400 }
10886
+ "About to handle initialization request"
10811
10887
  );
10812
- }
10813
- const conversation = await createOrGetConversation(dbClient_default)({
10814
- id: sessionId,
10815
- tenantId,
10816
- projectId,
10817
- activeSubAgentId: agent.defaultSubAgentId,
10818
- metadata: {
10819
- sessionData: {
10820
- agentId,
10821
- sessionType: "mcp",
10822
- mcpProtocolVersion: c.req.header("mcp-protocol-version"),
10823
- initialized: false
10824
- // Track initialization state
10825
- }
10826
- }
10827
- });
10828
- logger23.info(
10829
- { sessionId, conversationId: conversation.id },
10830
- "Created MCP session as conversation"
10831
- );
10832
- const transport = new StreamableHTTPServerTransport({
10833
- sessionIdGenerator: () => sessionId
10888
+ await transport.handleRequest(req, res, body);
10889
+ logger23.info({ sessionId }, "Successfully handled initialization request");
10890
+ return toFetchResponse(res);
10834
10891
  });
10835
- const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
10836
- await server.connect(transport);
10837
- logger23.info({ sessionId }, "Server connected for initialization");
10838
- res.setHeader("Mcp-Session-Id", sessionId);
10839
- logger23.info(
10840
- {
10841
- sessionId,
10842
- bodyMethod: body?.method,
10843
- bodyId: body?.id
10844
- },
10845
- "About to handle initialization request"
10846
- );
10847
- await transport.handleRequest(req, res, body);
10848
- logger23.info({ sessionId }, "Successfully handled initialization request");
10849
- return toFetchResponse(res);
10850
10892
  };
10851
10893
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
10852
10894
  const { tenantId, projectId, agentId } = executionContext;