@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.cjs CHANGED
@@ -75,9 +75,11 @@ var init_env = __esm({
75
75
  TURSO_AUTH_TOKEN: z6.z.string().optional(),
76
76
  AGENTS_RUN_API_URL: z6.z.string().optional().default("http://localhost:3003"),
77
77
  LOG_LEVEL: z6.z.enum(["trace", "debug", "info", "warn", "error"]).optional().default("debug"),
78
+ NANGO_SERVER_URL: z6.z.string().optional().default("https://api.nango.dev"),
78
79
  NANGO_SECRET_KEY: z6.z.string().optional(),
79
- OPENAI_API_KEY: z6.z.string().optional(),
80
80
  ANTHROPIC_API_KEY: z6.z.string(),
81
+ OPENAI_API_KEY: z6.z.string().optional(),
82
+ GOOGLE_GENERATIVE_AI_API_KEY: z6.z.string().optional(),
81
83
  INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z6.z.string().optional(),
82
84
  OTEL_BSP_SCHEDULE_DELAY: z6.z.coerce.number().optional().default(500),
83
85
  OTEL_BSP_MAX_EXPORT_BATCH_SIZE: z6.z.coerce.number().optional().default(64)
@@ -3937,7 +3939,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3937
3939
  "agent_session.id": this.sessionId,
3938
3940
  "artifact.id": artifactData.artifactId,
3939
3941
  "artifact.type": artifactData.artifactType || "unknown",
3940
- "artifact.agent_id": artifactData.subAgentId || "unknown",
3942
+ "artifact.sub_agent_id": artifactData.subAgentId || "unknown",
3941
3943
  "artifact.tool_call_id": artifactData.metadata?.toolCallId || "unknown",
3942
3944
  "artifact.data": JSON.stringify(artifactData.data, null, 2),
3943
3945
  "tenant.id": artifactData.tenantId || "unknown",
@@ -7597,7 +7599,7 @@ var Agent = class {
7597
7599
  "conversation.id": this.conversationId,
7598
7600
  "tool.purpose": toolDefinition.description || "No description provided",
7599
7601
  "ai.toolType": toolType || "unknown",
7600
- "ai.agentName": this.config.name || "unknown",
7602
+ "ai.subAgentName": this.config.name || "unknown",
7601
7603
  "agent.id": this.config.agentId || "unknown"
7602
7604
  });
7603
7605
  }
@@ -7884,7 +7886,7 @@ var Agent = class {
7884
7886
  originalToolName: tool3.name
7885
7887
  }),
7886
7888
  "ai.toolType": "mcp",
7887
- "ai.agentName": this.config.name || "unknown",
7889
+ "ai.subAgentName": this.config.name || "unknown",
7888
7890
  "conversation.id": this.conversationId || "unknown",
7889
7891
  "agent.id": this.config.agentId || "unknown",
7890
7892
  "tenant.id": this.config.tenantId || "unknown",
@@ -8606,7 +8608,7 @@ var Agent = class {
8606
8608
  "agent.load_tools",
8607
8609
  {
8608
8610
  attributes: {
8609
- "agent.name": this.config.name,
8611
+ "subAgent.name": this.config.name,
8610
8612
  "session.id": sessionId
8611
8613
  }
8612
8614
  },
@@ -10761,7 +10763,7 @@ var ExecutionHandler = class {
10761
10763
  span.setAttributes({
10762
10764
  "ai.response.content": textContent || "No response content",
10763
10765
  "ai.response.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
10764
- "ai.agent.name": currentAgentId
10766
+ "ai.subAgent.name": currentAgentId
10765
10767
  });
10766
10768
  await agentsCore.createMessage(dbClient_default)({
10767
10769
  id: nanoid.nanoid(),
@@ -11038,174 +11040,191 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11038
11040
  );
11039
11041
  const body = c.get("requestBody") || {};
11040
11042
  const conversationId = body.conversationId || agentsCore.getConversationId();
11041
- const fullAgent = await agentsCore.getFullAgent(dbClient_default)({
11042
- scopes: { tenantId, projectId, agentId }
11043
- });
11044
- let agent;
11045
- let defaultSubAgentId;
11046
- if (fullAgent) {
11047
- agent = {
11048
- id: fullAgent.id,
11049
- name: fullAgent.name,
11050
- tenantId,
11051
- projectId,
11052
- defaultSubAgentId: fullAgent.defaultSubAgentId
11053
- };
11054
- const agentKeys = Object.keys(fullAgent.subAgents || {});
11055
- const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
11056
- defaultSubAgentId = fullAgent.defaultSubAgentId || firstAgentId;
11057
- } else {
11058
- agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11043
+ const activeSpan = api.trace.getActiveSpan();
11044
+ if (activeSpan) {
11045
+ activeSpan.setAttributes({
11046
+ "conversation.id": conversationId,
11047
+ "tenant.id": tenantId,
11048
+ "agent.id": agentId,
11049
+ "project.id": projectId
11050
+ });
11051
+ }
11052
+ let currentBag = api.propagation.getBaggage(api.context.active());
11053
+ if (!currentBag) {
11054
+ currentBag = api.propagation.createBaggage();
11055
+ }
11056
+ currentBag = currentBag.setEntry("conversation.id", { value: conversationId });
11057
+ const ctxWithBaggage = api.propagation.setBaggage(api.context.active(), currentBag);
11058
+ return await api.context.with(ctxWithBaggage, async () => {
11059
+ const fullAgent = await agentsCore.getFullAgent(dbClient_default)({
11059
11060
  scopes: { tenantId, projectId, agentId }
11060
11061
  });
11061
- if (!agent) {
11062
+ let agent;
11063
+ let defaultSubAgentId;
11064
+ if (fullAgent) {
11065
+ agent = {
11066
+ id: fullAgent.id,
11067
+ name: fullAgent.name,
11068
+ tenantId,
11069
+ projectId,
11070
+ defaultSubAgentId: fullAgent.defaultSubAgentId
11071
+ };
11072
+ const agentKeys = Object.keys(fullAgent.subAgents || {});
11073
+ const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
11074
+ defaultSubAgentId = fullAgent.defaultSubAgentId || firstAgentId;
11075
+ } else {
11076
+ agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11077
+ scopes: { tenantId, projectId, agentId }
11078
+ });
11079
+ if (!agent) {
11080
+ throw agentsCore.createApiError({
11081
+ code: "not_found",
11082
+ message: "Agent not found"
11083
+ });
11084
+ }
11085
+ defaultSubAgentId = agent.defaultSubAgentId || "";
11086
+ }
11087
+ if (!defaultSubAgentId) {
11062
11088
  throw agentsCore.createApiError({
11063
11089
  code: "not_found",
11064
- message: "Agent not found"
11090
+ message: "No default agent found in agent"
11065
11091
  });
11066
11092
  }
11067
- defaultSubAgentId = agent.defaultSubAgentId || "";
11068
- }
11069
- if (!defaultSubAgentId) {
11070
- throw agentsCore.createApiError({
11071
- code: "not_found",
11072
- message: "No default agent found in agent"
11093
+ await agentsCore.createOrGetConversation(dbClient_default)({
11094
+ tenantId,
11095
+ projectId,
11096
+ id: conversationId,
11097
+ activeSubAgentId: defaultSubAgentId
11073
11098
  });
11074
- }
11075
- await agentsCore.createOrGetConversation(dbClient_default)({
11076
- tenantId,
11077
- projectId,
11078
- id: conversationId,
11079
- activeSubAgentId: defaultSubAgentId
11080
- });
11081
- const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11082
- scopes: { tenantId, projectId },
11083
- conversationId
11084
- });
11085
- if (!activeAgent) {
11086
- agentsCore.setActiveAgentForConversation(dbClient_default)({
11099
+ const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11087
11100
  scopes: { tenantId, projectId },
11088
- conversationId,
11089
- subAgentId: defaultSubAgentId
11101
+ conversationId
11090
11102
  });
11091
- }
11092
- const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11093
- const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11094
- scopes: { tenantId, projectId, agentId },
11095
- subAgentId
11096
- });
11097
- if (!agentInfo) {
11098
- throw agentsCore.createApiError({
11099
- code: "not_found",
11100
- message: "Agent not found"
11103
+ if (!activeAgent) {
11104
+ agentsCore.setActiveAgentForConversation(dbClient_default)({
11105
+ scopes: { tenantId, projectId },
11106
+ conversationId,
11107
+ subAgentId: defaultSubAgentId
11108
+ });
11109
+ }
11110
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11111
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11112
+ scopes: { tenantId, projectId, agentId },
11113
+ subAgentId
11101
11114
  });
11102
- }
11103
- const validatedContext = c.get("validatedContext") || body.headers || {};
11104
- const credentialStores = c.get("credentialStores");
11105
- await agentsCore.handleContextResolution({
11106
- tenantId,
11107
- projectId,
11108
- agentId,
11109
- conversationId,
11110
- headers: validatedContext,
11111
- dbClient: dbClient_default,
11112
- credentialStores
11113
- });
11114
- logger23.info(
11115
- {
11115
+ if (!agentInfo) {
11116
+ throw agentsCore.createApiError({
11117
+ code: "not_found",
11118
+ message: "Agent not found"
11119
+ });
11120
+ }
11121
+ const validatedContext = c.get("validatedContext") || body.headers || {};
11122
+ const credentialStores = c.get("credentialStores");
11123
+ await agentsCore.handleContextResolution({
11116
11124
  tenantId,
11117
11125
  projectId,
11118
11126
  agentId,
11119
11127
  conversationId,
11120
- defaultSubAgentId,
11121
- activeSubAgentId: activeAgent?.activeSubAgentId || "none",
11122
- hasContextConfig: !!agent.contextConfigId,
11123
- hasHeaders: !!body.headers,
11124
- hasValidatedContext: !!validatedContext,
11125
- validatedContextKeys: Object.keys(validatedContext)
11126
- },
11127
- "parameters"
11128
- );
11129
- const requestId2 = `chatcmpl-${Date.now()}`;
11130
- const timestamp = Math.floor(Date.now() / 1e3);
11131
- const lastUserMessage = body.messages.filter((msg) => msg.role === "user").slice(-1)[0];
11132
- const userMessage = lastUserMessage ? getMessageText(lastUserMessage.content) : "";
11133
- const messageSpan = api.trace.getActiveSpan();
11134
- if (messageSpan) {
11135
- messageSpan.setAttributes({
11136
- "message.content": userMessage,
11137
- "message.timestamp": Date.now()
11128
+ headers: validatedContext,
11129
+ dbClient: dbClient_default,
11130
+ credentialStores
11138
11131
  });
11139
- }
11140
- await agentsCore.createMessage(dbClient_default)({
11141
- id: nanoid.nanoid(),
11142
- tenantId,
11143
- projectId,
11144
- conversationId,
11145
- role: "user",
11146
- content: {
11147
- text: userMessage
11148
- },
11149
- visibility: "user-facing",
11150
- messageType: "chat"
11151
- });
11152
- if (messageSpan) {
11153
- messageSpan.addEvent("user.message.stored", {
11154
- "message.id": conversationId,
11155
- "database.operation": "insert"
11156
- });
11157
- }
11158
- return streaming.streamSSE(c, async (stream2) => {
11159
- try {
11160
- const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
11161
- await sseHelper.writeRole();
11162
- logger23.info({ subAgentId }, "Starting execution");
11163
- const emitOperationsHeader = c.req.header("x-emit-operations");
11164
- const emitOperations = emitOperationsHeader === "true";
11165
- const executionHandler = new ExecutionHandler();
11166
- const result = await executionHandler.execute({
11167
- executionContext,
11132
+ logger23.info(
11133
+ {
11134
+ tenantId,
11135
+ projectId,
11136
+ agentId,
11168
11137
  conversationId,
11169
- userMessage,
11170
- initialAgentId: subAgentId,
11171
- requestId: requestId2,
11172
- sseHelper,
11173
- emitOperations
11138
+ defaultSubAgentId,
11139
+ activeSubAgentId: activeAgent?.activeSubAgentId || "none",
11140
+ hasContextConfig: !!agent.contextConfigId,
11141
+ hasHeaders: !!body.headers,
11142
+ hasValidatedContext: !!validatedContext,
11143
+ validatedContextKeys: Object.keys(validatedContext)
11144
+ },
11145
+ "parameters"
11146
+ );
11147
+ const requestId2 = `chatcmpl-${Date.now()}`;
11148
+ const timestamp = Math.floor(Date.now() / 1e3);
11149
+ const lastUserMessage = body.messages.filter((msg) => msg.role === "user").slice(-1)[0];
11150
+ const userMessage = lastUserMessage ? getMessageText(lastUserMessage.content) : "";
11151
+ const messageSpan = api.trace.getActiveSpan();
11152
+ if (messageSpan) {
11153
+ messageSpan.setAttributes({
11154
+ "message.content": userMessage,
11155
+ "message.timestamp": Date.now()
11174
11156
  });
11175
- logger23.info(
11176
- { result },
11177
- `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11178
- );
11179
- if (!result.success) {
11180
- await sseHelper.writeOperation(
11181
- errorOp(
11182
- "Sorry, I was unable to process your request at this time. Please try again.",
11183
- "system"
11184
- )
11185
- );
11186
- }
11187
- await sseHelper.complete();
11188
- } catch (error) {
11189
- logger23.error(
11190
- {
11191
- error: error instanceof Error ? error.message : error,
11192
- stack: error instanceof Error ? error.stack : void 0
11193
- },
11194
- "Error during streaming execution"
11195
- );
11157
+ }
11158
+ await agentsCore.createMessage(dbClient_default)({
11159
+ id: nanoid.nanoid(),
11160
+ tenantId,
11161
+ projectId,
11162
+ conversationId,
11163
+ role: "user",
11164
+ content: {
11165
+ text: userMessage
11166
+ },
11167
+ visibility: "user-facing",
11168
+ messageType: "chat"
11169
+ });
11170
+ if (messageSpan) {
11171
+ messageSpan.addEvent("user.message.stored", {
11172
+ "message.id": conversationId,
11173
+ "database.operation": "insert"
11174
+ });
11175
+ }
11176
+ return streaming.streamSSE(c, async (stream2) => {
11196
11177
  try {
11197
11178
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
11198
- await sseHelper.writeOperation(
11199
- errorOp(
11200
- "Sorry, I was unable to process your request at this time. Please try again.",
11201
- "system"
11202
- )
11179
+ await sseHelper.writeRole();
11180
+ logger23.info({ subAgentId }, "Starting execution");
11181
+ const emitOperationsHeader = c.req.header("x-emit-operations");
11182
+ const emitOperations = emitOperationsHeader === "true";
11183
+ const executionHandler = new ExecutionHandler();
11184
+ const result = await executionHandler.execute({
11185
+ executionContext,
11186
+ conversationId,
11187
+ userMessage,
11188
+ initialAgentId: subAgentId,
11189
+ requestId: requestId2,
11190
+ sseHelper,
11191
+ emitOperations
11192
+ });
11193
+ logger23.info(
11194
+ { result },
11195
+ `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11203
11196
  );
11197
+ if (!result.success) {
11198
+ await sseHelper.writeOperation(
11199
+ errorOp(
11200
+ "Sorry, I was unable to process your request at this time. Please try again.",
11201
+ "system"
11202
+ )
11203
+ );
11204
+ }
11204
11205
  await sseHelper.complete();
11205
- } catch (streamError) {
11206
- logger23.error({ streamError }, "Failed to write error to stream");
11206
+ } catch (error) {
11207
+ logger23.error(
11208
+ {
11209
+ error: error instanceof Error ? error.message : error,
11210
+ stack: error instanceof Error ? error.stack : void 0
11211
+ },
11212
+ "Error during streaming execution"
11213
+ );
11214
+ try {
11215
+ const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
11216
+ await sseHelper.writeOperation(
11217
+ errorOp(
11218
+ "Sorry, I was unable to process your request at this time. Please try again.",
11219
+ "system"
11220
+ )
11221
+ );
11222
+ await sseHelper.complete();
11223
+ } catch (streamError) {
11224
+ logger23.error({ streamError }, "Failed to write error to stream");
11225
+ }
11207
11226
  }
11208
- }
11227
+ });
11209
11228
  });
11210
11229
  } catch (error) {
11211
11230
  logger23.error(
@@ -11301,123 +11320,131 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11301
11320
  "project.id": projectId
11302
11321
  });
11303
11322
  }
11304
- const agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11305
- scopes: { tenantId, projectId, agentId }
11306
- });
11307
- if (!agent) {
11308
- throw agentsCore.createApiError({
11309
- code: "not_found",
11310
- message: "Agent not found"
11311
- });
11323
+ let currentBag = api.propagation.getBaggage(api.context.active());
11324
+ if (!currentBag) {
11325
+ currentBag = api.propagation.createBaggage();
11312
11326
  }
11313
- const defaultSubAgentId = agent.defaultSubAgentId;
11314
- const agentName = agent.name;
11315
- if (!defaultSubAgentId) {
11316
- throw agentsCore.createApiError({
11317
- code: "bad_request",
11318
- message: "Agent does not have a default agent configured"
11327
+ currentBag = currentBag.setEntry("conversation.id", { value: conversationId });
11328
+ const ctxWithBaggage = api.propagation.setBaggage(api.context.active(), currentBag);
11329
+ return await api.context.with(ctxWithBaggage, async () => {
11330
+ const agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11331
+ scopes: { tenantId, projectId, agentId }
11319
11332
  });
11320
- }
11321
- const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11322
- scopes: { tenantId, projectId },
11323
- conversationId
11324
- });
11325
- if (!activeAgent) {
11326
- agentsCore.setActiveAgentForConversation(dbClient_default)({
11333
+ if (!agent) {
11334
+ throw agentsCore.createApiError({
11335
+ code: "not_found",
11336
+ message: "Agent not found"
11337
+ });
11338
+ }
11339
+ const defaultSubAgentId = agent.defaultSubAgentId;
11340
+ const agentName = agent.name;
11341
+ if (!defaultSubAgentId) {
11342
+ throw agentsCore.createApiError({
11343
+ code: "bad_request",
11344
+ message: "Agent does not have a default agent configured"
11345
+ });
11346
+ }
11347
+ const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11327
11348
  scopes: { tenantId, projectId },
11328
- conversationId,
11329
- subAgentId: defaultSubAgentId
11349
+ conversationId
11330
11350
  });
11331
- }
11332
- const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11333
- const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11334
- scopes: { tenantId, projectId, agentId },
11335
- subAgentId
11336
- });
11337
- if (!agentInfo) {
11338
- throw agentsCore.createApiError({
11339
- code: "not_found",
11340
- message: "Agent not found"
11351
+ if (!activeAgent) {
11352
+ agentsCore.setActiveAgentForConversation(dbClient_default)({
11353
+ scopes: { tenantId, projectId },
11354
+ conversationId,
11355
+ subAgentId: defaultSubAgentId
11356
+ });
11357
+ }
11358
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11359
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11360
+ scopes: { tenantId, projectId, agentId },
11361
+ subAgentId
11341
11362
  });
11342
- }
11343
- const validatedContext = c.get("validatedContext") || body.headers || {};
11344
- const credentialStores = c.get("credentialStores");
11345
- await agentsCore.handleContextResolution({
11346
- tenantId,
11347
- projectId,
11348
- agentId,
11349
- conversationId,
11350
- headers: validatedContext,
11351
- dbClient: dbClient_default,
11352
- credentialStores
11353
- });
11354
- const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
11355
- const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
11356
- logger24.info({ userText, lastUserMessage }, "userText");
11357
- const messageSpan = api.trace.getActiveSpan();
11358
- if (messageSpan) {
11359
- messageSpan.setAttributes({
11360
- "message.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
11361
- "message.content": userText,
11362
- "agent.name": agentName
11363
+ if (!agentInfo) {
11364
+ throw agentsCore.createApiError({
11365
+ code: "not_found",
11366
+ message: "Agent not found"
11367
+ });
11368
+ }
11369
+ const validatedContext = c.get("validatedContext") || body.headers || {};
11370
+ const credentialStores = c.get("credentialStores");
11371
+ await agentsCore.handleContextResolution({
11372
+ tenantId,
11373
+ projectId,
11374
+ agentId,
11375
+ conversationId,
11376
+ headers: validatedContext,
11377
+ dbClient: dbClient_default,
11378
+ credentialStores
11363
11379
  });
11364
- }
11365
- await agentsCore.createMessage(dbClient_default)({
11366
- id: nanoid.nanoid(),
11367
- tenantId,
11368
- projectId,
11369
- conversationId,
11370
- role: "user",
11371
- content: { text: userText },
11372
- visibility: "user-facing",
11373
- messageType: "chat"
11374
- });
11375
- if (messageSpan) {
11376
- messageSpan.addEvent("user.message.stored", {
11377
- "message.id": conversationId,
11378
- "database.operation": "insert"
11380
+ const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
11381
+ const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
11382
+ logger24.info({ userText, lastUserMessage }, "userText");
11383
+ const messageSpan = api.trace.getActiveSpan();
11384
+ if (messageSpan) {
11385
+ messageSpan.setAttributes({
11386
+ "message.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
11387
+ "message.content": userText,
11388
+ "agent.name": agentName
11389
+ });
11390
+ }
11391
+ await agentsCore.createMessage(dbClient_default)({
11392
+ id: nanoid.nanoid(),
11393
+ tenantId,
11394
+ projectId,
11395
+ conversationId,
11396
+ role: "user",
11397
+ content: { text: userText },
11398
+ visibility: "user-facing",
11399
+ messageType: "chat"
11379
11400
  });
11380
- }
11381
- const dataStream = ai.createUIMessageStream({
11382
- execute: async ({ writer }) => {
11383
- const streamHelper = createVercelStreamHelper(writer);
11384
- try {
11385
- const emitOperationsHeader = c.req.header("x-emit-operations");
11386
- const emitOperations = emitOperationsHeader === "true";
11387
- const executionHandler = new ExecutionHandler();
11388
- const result = await executionHandler.execute({
11389
- executionContext,
11390
- conversationId,
11391
- userMessage: userText,
11392
- initialAgentId: subAgentId,
11393
- requestId: `chatds-${Date.now()}`,
11394
- sseHelper: streamHelper,
11395
- emitOperations
11396
- });
11397
- if (!result.success) {
11398
- await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
11399
- }
11400
- } catch (err) {
11401
- logger24.error({ err }, "Streaming error");
11402
- await streamHelper.writeOperation(errorOp("Internal server error", "system"));
11403
- } finally {
11404
- if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
11405
- streamHelper.cleanup();
11401
+ if (messageSpan) {
11402
+ messageSpan.addEvent("user.message.stored", {
11403
+ "message.id": conversationId,
11404
+ "database.operation": "insert"
11405
+ });
11406
+ }
11407
+ const dataStream = ai.createUIMessageStream({
11408
+ execute: async ({ writer }) => {
11409
+ const streamHelper = createVercelStreamHelper(writer);
11410
+ try {
11411
+ const emitOperationsHeader = c.req.header("x-emit-operations");
11412
+ const emitOperations = emitOperationsHeader === "true";
11413
+ const executionHandler = new ExecutionHandler();
11414
+ const result = await executionHandler.execute({
11415
+ executionContext,
11416
+ conversationId,
11417
+ userMessage: userText,
11418
+ initialAgentId: subAgentId,
11419
+ requestId: `chatds-${Date.now()}`,
11420
+ sseHelper: streamHelper,
11421
+ emitOperations
11422
+ });
11423
+ if (!result.success) {
11424
+ await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
11425
+ }
11426
+ } catch (err) {
11427
+ logger24.error({ err }, "Streaming error");
11428
+ await streamHelper.writeOperation(errorOp("Internal server error", "system"));
11429
+ } finally {
11430
+ if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
11431
+ streamHelper.cleanup();
11432
+ }
11406
11433
  }
11407
11434
  }
11408
- }
11435
+ });
11436
+ c.header("content-type", "text/event-stream");
11437
+ c.header("cache-control", "no-cache");
11438
+ c.header("connection", "keep-alive");
11439
+ c.header("x-vercel-ai-data-stream", "v2");
11440
+ c.header("x-accel-buffering", "no");
11441
+ return streaming.stream(
11442
+ c,
11443
+ (stream2) => stream2.pipe(
11444
+ dataStream.pipeThrough(new ai.JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
11445
+ )
11446
+ );
11409
11447
  });
11410
- c.header("content-type", "text/event-stream");
11411
- c.header("cache-control", "no-cache");
11412
- c.header("connection", "keep-alive");
11413
- c.header("x-vercel-ai-data-stream", "v2");
11414
- c.header("x-accel-buffering", "no");
11415
- return streaming.stream(
11416
- c,
11417
- (stream2) => stream2.pipe(
11418
- dataStream.pipeThrough(new ai.JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
11419
- )
11420
- );
11421
11448
  } catch (error) {
11422
11449
  logger24.error({ error }, "chatDataStream error");
11423
11450
  throw agentsCore.createApiError({
@@ -11749,66 +11776,83 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11749
11776
  const { tenantId, projectId, agentId } = executionContext;
11750
11777
  logger25.info({ body }, "Received initialization request");
11751
11778
  const sessionId = agentsCore.getConversationId();
11752
- const agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11753
- scopes: { tenantId, projectId, agentId }
11754
- });
11755
- if (!agent) {
11756
- return c.json(
11757
- {
11758
- jsonrpc: "2.0",
11759
- error: { code: -32001, message: "Agent not found" },
11760
- id: body.id || null
11761
- },
11762
- { status: 404 }
11763
- );
11779
+ const activeSpan = api.trace.getActiveSpan();
11780
+ if (activeSpan) {
11781
+ activeSpan.setAttributes({
11782
+ "conversation.id": sessionId,
11783
+ "tenant.id": tenantId,
11784
+ "agent.id": agentId,
11785
+ "project.id": projectId
11786
+ });
11764
11787
  }
11765
- if (!agent.defaultSubAgentId) {
11766
- return c.json(
11788
+ let currentBag = api.propagation.getBaggage(api.context.active());
11789
+ if (!currentBag) {
11790
+ currentBag = api.propagation.createBaggage();
11791
+ }
11792
+ currentBag = currentBag.setEntry("conversation.id", { value: sessionId });
11793
+ const ctxWithBaggage = api.propagation.setBaggage(api.context.active(), currentBag);
11794
+ return await api.context.with(ctxWithBaggage, async () => {
11795
+ const agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11796
+ scopes: { tenantId, projectId, agentId }
11797
+ });
11798
+ if (!agent) {
11799
+ return c.json(
11800
+ {
11801
+ jsonrpc: "2.0",
11802
+ error: { code: -32001, message: "Agent not found" },
11803
+ id: body.id || null
11804
+ },
11805
+ { status: 404 }
11806
+ );
11807
+ }
11808
+ if (!agent.defaultSubAgentId) {
11809
+ return c.json(
11810
+ {
11811
+ jsonrpc: "2.0",
11812
+ error: { code: -32001, message: "Agent does not have a default agent configured" },
11813
+ id: body.id || null
11814
+ },
11815
+ { status: 400 }
11816
+ );
11817
+ }
11818
+ const conversation = await agentsCore.createOrGetConversation(dbClient_default)({
11819
+ id: sessionId,
11820
+ tenantId,
11821
+ projectId,
11822
+ activeSubAgentId: agent.defaultSubAgentId,
11823
+ metadata: {
11824
+ sessionData: {
11825
+ agentId,
11826
+ sessionType: "mcp",
11827
+ mcpProtocolVersion: c.req.header("mcp-protocol-version"),
11828
+ initialized: false
11829
+ // Track initialization state
11830
+ }
11831
+ }
11832
+ });
11833
+ logger25.info(
11834
+ { sessionId, conversationId: conversation.id },
11835
+ "Created MCP session as conversation"
11836
+ );
11837
+ const transport = new streamableHttp_js.StreamableHTTPServerTransport({
11838
+ sessionIdGenerator: () => sessionId
11839
+ });
11840
+ const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
11841
+ await server.connect(transport);
11842
+ logger25.info({ sessionId }, "Server connected for initialization");
11843
+ res.setHeader("Mcp-Session-Id", sessionId);
11844
+ logger25.info(
11767
11845
  {
11768
- jsonrpc: "2.0",
11769
- error: { code: -32001, message: "Agent does not have a default agent configured" },
11770
- id: body.id || null
11846
+ sessionId,
11847
+ bodyMethod: body?.method,
11848
+ bodyId: body?.id
11771
11849
  },
11772
- { status: 400 }
11850
+ "About to handle initialization request"
11773
11851
  );
11774
- }
11775
- const conversation = await agentsCore.createOrGetConversation(dbClient_default)({
11776
- id: sessionId,
11777
- tenantId,
11778
- projectId,
11779
- activeSubAgentId: agent.defaultSubAgentId,
11780
- metadata: {
11781
- sessionData: {
11782
- agentId,
11783
- sessionType: "mcp",
11784
- mcpProtocolVersion: c.req.header("mcp-protocol-version"),
11785
- initialized: false
11786
- // Track initialization state
11787
- }
11788
- }
11789
- });
11790
- logger25.info(
11791
- { sessionId, conversationId: conversation.id },
11792
- "Created MCP session as conversation"
11793
- );
11794
- const transport = new streamableHttp_js.StreamableHTTPServerTransport({
11795
- sessionIdGenerator: () => sessionId
11852
+ await transport.handleRequest(req, res, body);
11853
+ logger25.info({ sessionId }, "Successfully handled initialization request");
11854
+ return fetchToNode.toFetchResponse(res);
11796
11855
  });
11797
- const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
11798
- await server.connect(transport);
11799
- logger25.info({ sessionId }, "Server connected for initialization");
11800
- res.setHeader("Mcp-Session-Id", sessionId);
11801
- logger25.info(
11802
- {
11803
- sessionId,
11804
- bodyMethod: body?.method,
11805
- bodyId: body?.id
11806
- },
11807
- "About to handle initialization request"
11808
- );
11809
- await transport.handleRequest(req, res, body);
11810
- logger25.info({ sessionId }, "Successfully handled initialization request");
11811
- return fetchToNode.toFetchResponse(res);
11812
11856
  };
11813
11857
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
11814
11858
  const { tenantId, projectId, agentId } = executionContext;