@inkeep/agents-run-api 0.0.0-dev-20251013202856 → 0.0.0-dev-20251013223711

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.
Files changed (3) hide show
  1. package/dist/index.cjs +402 -328
  2. package/dist/index.js +402 -328
  3. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -3166,8 +3166,14 @@ var AgentSession = class {
3166
3166
  return `Agent ${event.subAgentId} generating response`;
3167
3167
  case "agent_reasoning":
3168
3168
  return `Agent ${event.subAgentId} reasoning through request`;
3169
- case "tool_execution":
3170
- return `Tool execution: ${event.data.toolName || "unknown"}`;
3169
+ case "tool_call":
3170
+ return `Tool call: ${event.data.toolName || "unknown"}`;
3171
+ case "tool_result": {
3172
+ const status = event.data.error ? "failed" : "completed";
3173
+ return `Tool result: ${event.data.toolName || "unknown"} (${status})`;
3174
+ }
3175
+ case "error":
3176
+ return `Error: ${event.data.message}`;
3171
3177
  case "transfer":
3172
3178
  return `Agent transfer: ${event.data.fromSubAgent} \u2192 ${event.data.targetSubAgent}`;
3173
3179
  case "delegation_sent":
@@ -3888,15 +3894,29 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3888
3894
  const activities = [];
3889
3895
  for (const event of events) {
3890
3896
  switch (event.eventType) {
3891
- case "tool_execution": {
3892
- const resultStr = JSON.stringify(event.data.result);
3897
+ case "tool_call": {
3898
+ activities.push(
3899
+ `\u{1F527} **${event.data.toolName}** (called)
3900
+ \u{1F4E5} Input: ${JSON.stringify(event.data.args)}`
3901
+ );
3902
+ break;
3903
+ }
3904
+ case "tool_result": {
3905
+ const resultStr = event.data.error ? `\u274C Error: ${event.data.error}` : JSON.stringify(event.data.result);
3893
3906
  activities.push(
3894
3907
  `\u{1F527} **${event.data.toolName}** ${event.data.duration ? `(${event.data.duration}ms)` : ""}
3895
- \u{1F4E5} Input: ${JSON.stringify(event.data.args)}
3896
3908
  \u{1F4E4} Output: ${resultStr}`
3897
3909
  );
3898
3910
  break;
3899
3911
  }
3912
+ case "error": {
3913
+ activities.push(
3914
+ `\u274C **Error**: ${event.data.message}
3915
+ \u{1F50D} Code: ${event.data.code || "unknown"}
3916
+ \u{1F4CA} Severity: ${event.data.severity || "error"}`
3917
+ );
3918
+ break;
3919
+ }
3900
3920
  // INTERNAL OPERATIONS - DO NOT EXPOSE TO STATUS UPDATES
3901
3921
  case "transfer":
3902
3922
  case "delegation_sent":
@@ -3981,7 +4001,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3981
4001
  }
3982
4002
  });
3983
4003
  const toolCallEvent = this.events.find(
3984
- (event) => event.eventType === "tool_execution" && event.data && "toolId" in event.data && event.data.toolId === artifactData.metadata?.toolCallId
4004
+ (event) => event.eventType === "tool_result" && event.data && "toolCallId" in event.data && event.data.toolCallId === artifactData.metadata?.toolCallId
3985
4005
  );
3986
4006
  const toolContext = toolCallEvent ? {
3987
4007
  toolName: toolCallEvent.data.toolName,
@@ -7604,14 +7624,22 @@ var Agent = class {
7604
7624
  });
7605
7625
  }
7606
7626
  const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_") || toolName.startsWith("delegate_to_");
7627
+ if (streamRequestId && !isInternalTool) {
7628
+ agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, {
7629
+ toolName,
7630
+ args,
7631
+ toolCallId: context?.toolCallId,
7632
+ toolId
7633
+ });
7634
+ }
7607
7635
  try {
7608
7636
  const result = await originalExecute(args, context);
7609
7637
  const duration = Date.now() - startTime;
7610
7638
  if (streamRequestId && !isInternalTool) {
7611
- agentSessionManager.recordEvent(streamRequestId, "tool_execution", this.config.id, {
7639
+ agentSessionManager.recordEvent(streamRequestId, "tool_result", this.config.id, {
7612
7640
  toolName,
7613
- args,
7614
7641
  result,
7642
+ toolCallId: context?.toolCallId,
7615
7643
  toolId,
7616
7644
  duration
7617
7645
  });
@@ -7621,12 +7649,13 @@ var Agent = class {
7621
7649
  const duration = Date.now() - startTime;
7622
7650
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
7623
7651
  if (streamRequestId && !isInternalTool) {
7624
- agentSessionManager.recordEvent(streamRequestId, "tool_execution", this.config.id, {
7652
+ agentSessionManager.recordEvent(streamRequestId, "tool_result", this.config.id, {
7625
7653
  toolName,
7626
- args,
7627
- result: { error: errorMessage },
7654
+ result: null,
7655
+ toolCallId: context?.toolCallId,
7628
7656
  toolId,
7629
- duration
7657
+ duration,
7658
+ error: errorMessage
7630
7659
  });
7631
7660
  }
7632
7661
  throw error;
@@ -7895,13 +7924,14 @@ var Agent = class {
7895
7924
  },
7896
7925
  (span) => {
7897
7926
  agentsCore.setSpanWithError(span, new Error(`0 effective tools available for ${tool3.name}`));
7898
- agentSessionManager.recordEvent(streamRequestId, "tool_execution", this.config.id, {
7899
- toolName: tool3.name,
7900
- args: { operation: "mcp_tool_discovery" },
7901
- result: {
7902
- status: "no_tools_available",
7903
- message: `MCP server has 0 effective tools. Double check the selected tools in your agent and the active tools in the MCP server configuration.`,
7904
- serverUrl: tool3.config.type === "mcp" ? tool3.config.mcp.server.url : "unknown"
7927
+ agentSessionManager.recordEvent(streamRequestId, "error", this.config.id, {
7928
+ message: `MCP server has 0 effective tools. Double check the selected tools in your graph and the active tools in the MCP server configuration.`,
7929
+ code: "no_tools_available",
7930
+ severity: "error",
7931
+ context: {
7932
+ toolName: tool3.name,
7933
+ serverUrl: tool3.config.type === "mcp" ? tool3.config.mcp.server.url : "unknown",
7934
+ operation: "mcp_tool_discovery"
7905
7935
  }
7906
7936
  });
7907
7937
  span.end();
@@ -8726,7 +8756,9 @@ var Agent = class {
8726
8756
  if (steps.length >= 2) {
8727
8757
  const previousStep = steps[steps.length - 2];
8728
8758
  if (previousStep && "toolCalls" in previousStep && previousStep.toolCalls) {
8729
- const hasTransferCall = previousStep.toolCalls.some((tc) => tc.toolName.startsWith("transfer_to_"));
8759
+ const hasTransferCall = previousStep.toolCalls.some(
8760
+ (tc) => tc.toolName.startsWith("transfer_to_")
8761
+ );
8730
8762
  if (hasTransferCall && "toolResults" in previousStep && previousStep.toolResults) {
8731
8763
  return true;
8732
8764
  }
@@ -11040,174 +11072,191 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11040
11072
  );
11041
11073
  const body = c.get("requestBody") || {};
11042
11074
  const conversationId = body.conversationId || agentsCore.getConversationId();
11043
- const fullAgent = await agentsCore.getFullAgent(dbClient_default)({
11044
- scopes: { tenantId, projectId, agentId }
11045
- });
11046
- let agent;
11047
- let defaultSubAgentId;
11048
- if (fullAgent) {
11049
- agent = {
11050
- id: fullAgent.id,
11051
- name: fullAgent.name,
11052
- tenantId,
11053
- projectId,
11054
- defaultSubAgentId: fullAgent.defaultSubAgentId
11055
- };
11056
- const agentKeys = Object.keys(fullAgent.subAgents || {});
11057
- const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
11058
- defaultSubAgentId = fullAgent.defaultSubAgentId || firstAgentId;
11059
- } else {
11060
- agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11075
+ const activeSpan = api.trace.getActiveSpan();
11076
+ if (activeSpan) {
11077
+ activeSpan.setAttributes({
11078
+ "conversation.id": conversationId,
11079
+ "tenant.id": tenantId,
11080
+ "agent.id": agentId,
11081
+ "project.id": projectId
11082
+ });
11083
+ }
11084
+ let currentBag = api.propagation.getBaggage(api.context.active());
11085
+ if (!currentBag) {
11086
+ currentBag = api.propagation.createBaggage();
11087
+ }
11088
+ currentBag = currentBag.setEntry("conversation.id", { value: conversationId });
11089
+ const ctxWithBaggage = api.propagation.setBaggage(api.context.active(), currentBag);
11090
+ return await api.context.with(ctxWithBaggage, async () => {
11091
+ const fullAgent = await agentsCore.getFullAgent(dbClient_default)({
11061
11092
  scopes: { tenantId, projectId, agentId }
11062
11093
  });
11063
- if (!agent) {
11094
+ let agent;
11095
+ let defaultSubAgentId;
11096
+ if (fullAgent) {
11097
+ agent = {
11098
+ id: fullAgent.id,
11099
+ name: fullAgent.name,
11100
+ tenantId,
11101
+ projectId,
11102
+ defaultSubAgentId: fullAgent.defaultSubAgentId
11103
+ };
11104
+ const agentKeys = Object.keys(fullAgent.subAgents || {});
11105
+ const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
11106
+ defaultSubAgentId = fullAgent.defaultSubAgentId || firstAgentId;
11107
+ } else {
11108
+ agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11109
+ scopes: { tenantId, projectId, agentId }
11110
+ });
11111
+ if (!agent) {
11112
+ throw agentsCore.createApiError({
11113
+ code: "not_found",
11114
+ message: "Agent not found"
11115
+ });
11116
+ }
11117
+ defaultSubAgentId = agent.defaultSubAgentId || "";
11118
+ }
11119
+ if (!defaultSubAgentId) {
11064
11120
  throw agentsCore.createApiError({
11065
11121
  code: "not_found",
11066
- message: "Agent not found"
11122
+ message: "No default agent found in agent"
11067
11123
  });
11068
11124
  }
11069
- defaultSubAgentId = agent.defaultSubAgentId || "";
11070
- }
11071
- if (!defaultSubAgentId) {
11072
- throw agentsCore.createApiError({
11073
- code: "not_found",
11074
- message: "No default agent found in agent"
11125
+ await agentsCore.createOrGetConversation(dbClient_default)({
11126
+ tenantId,
11127
+ projectId,
11128
+ id: conversationId,
11129
+ activeSubAgentId: defaultSubAgentId
11075
11130
  });
11076
- }
11077
- await agentsCore.createOrGetConversation(dbClient_default)({
11078
- tenantId,
11079
- projectId,
11080
- id: conversationId,
11081
- activeSubAgentId: defaultSubAgentId
11082
- });
11083
- const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11084
- scopes: { tenantId, projectId },
11085
- conversationId
11086
- });
11087
- if (!activeAgent) {
11088
- agentsCore.setActiveAgentForConversation(dbClient_default)({
11131
+ const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11089
11132
  scopes: { tenantId, projectId },
11090
- conversationId,
11091
- subAgentId: defaultSubAgentId
11133
+ conversationId
11092
11134
  });
11093
- }
11094
- const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11095
- const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11096
- scopes: { tenantId, projectId, agentId },
11097
- subAgentId
11098
- });
11099
- if (!agentInfo) {
11100
- throw agentsCore.createApiError({
11101
- code: "not_found",
11102
- message: "Agent not found"
11135
+ if (!activeAgent) {
11136
+ agentsCore.setActiveAgentForConversation(dbClient_default)({
11137
+ scopes: { tenantId, projectId },
11138
+ conversationId,
11139
+ subAgentId: defaultSubAgentId
11140
+ });
11141
+ }
11142
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11143
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11144
+ scopes: { tenantId, projectId, agentId },
11145
+ subAgentId
11103
11146
  });
11104
- }
11105
- const validatedContext = c.get("validatedContext") || body.headers || {};
11106
- const credentialStores = c.get("credentialStores");
11107
- await agentsCore.handleContextResolution({
11108
- tenantId,
11109
- projectId,
11110
- agentId,
11111
- conversationId,
11112
- headers: validatedContext,
11113
- dbClient: dbClient_default,
11114
- credentialStores
11115
- });
11116
- logger23.info(
11117
- {
11147
+ if (!agentInfo) {
11148
+ throw agentsCore.createApiError({
11149
+ code: "not_found",
11150
+ message: "Agent not found"
11151
+ });
11152
+ }
11153
+ const validatedContext = c.get("validatedContext") || body.headers || {};
11154
+ const credentialStores = c.get("credentialStores");
11155
+ await agentsCore.handleContextResolution({
11118
11156
  tenantId,
11119
11157
  projectId,
11120
11158
  agentId,
11121
11159
  conversationId,
11122
- defaultSubAgentId,
11123
- activeSubAgentId: activeAgent?.activeSubAgentId || "none",
11124
- hasContextConfig: !!agent.contextConfigId,
11125
- hasHeaders: !!body.headers,
11126
- hasValidatedContext: !!validatedContext,
11127
- validatedContextKeys: Object.keys(validatedContext)
11128
- },
11129
- "parameters"
11130
- );
11131
- const requestId2 = `chatcmpl-${Date.now()}`;
11132
- const timestamp = Math.floor(Date.now() / 1e3);
11133
- const lastUserMessage = body.messages.filter((msg) => msg.role === "user").slice(-1)[0];
11134
- const userMessage = lastUserMessage ? getMessageText(lastUserMessage.content) : "";
11135
- const messageSpan = api.trace.getActiveSpan();
11136
- if (messageSpan) {
11137
- messageSpan.setAttributes({
11138
- "message.content": userMessage,
11139
- "message.timestamp": Date.now()
11140
- });
11141
- }
11142
- await agentsCore.createMessage(dbClient_default)({
11143
- id: nanoid.nanoid(),
11144
- tenantId,
11145
- projectId,
11146
- conversationId,
11147
- role: "user",
11148
- content: {
11149
- text: userMessage
11150
- },
11151
- visibility: "user-facing",
11152
- messageType: "chat"
11153
- });
11154
- if (messageSpan) {
11155
- messageSpan.addEvent("user.message.stored", {
11156
- "message.id": conversationId,
11157
- "database.operation": "insert"
11160
+ headers: validatedContext,
11161
+ dbClient: dbClient_default,
11162
+ credentialStores
11158
11163
  });
11159
- }
11160
- return streaming.streamSSE(c, async (stream2) => {
11161
- try {
11162
- const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
11163
- await sseHelper.writeRole();
11164
- logger23.info({ subAgentId }, "Starting execution");
11165
- const emitOperationsHeader = c.req.header("x-emit-operations");
11166
- const emitOperations = emitOperationsHeader === "true";
11167
- const executionHandler = new ExecutionHandler();
11168
- const result = await executionHandler.execute({
11169
- executionContext,
11164
+ logger23.info(
11165
+ {
11166
+ tenantId,
11167
+ projectId,
11168
+ agentId,
11170
11169
  conversationId,
11171
- userMessage,
11172
- initialAgentId: subAgentId,
11173
- requestId: requestId2,
11174
- sseHelper,
11175
- emitOperations
11170
+ defaultSubAgentId,
11171
+ activeSubAgentId: activeAgent?.activeSubAgentId || "none",
11172
+ hasContextConfig: !!agent.contextConfigId,
11173
+ hasHeaders: !!body.headers,
11174
+ hasValidatedContext: !!validatedContext,
11175
+ validatedContextKeys: Object.keys(validatedContext)
11176
+ },
11177
+ "parameters"
11178
+ );
11179
+ const requestId2 = `chatcmpl-${Date.now()}`;
11180
+ const timestamp = Math.floor(Date.now() / 1e3);
11181
+ const lastUserMessage = body.messages.filter((msg) => msg.role === "user").slice(-1)[0];
11182
+ const userMessage = lastUserMessage ? getMessageText(lastUserMessage.content) : "";
11183
+ const messageSpan = api.trace.getActiveSpan();
11184
+ if (messageSpan) {
11185
+ messageSpan.setAttributes({
11186
+ "message.content": userMessage,
11187
+ "message.timestamp": Date.now()
11176
11188
  });
11177
- logger23.info(
11178
- { result },
11179
- `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11180
- );
11181
- if (!result.success) {
11182
- await sseHelper.writeOperation(
11183
- errorOp(
11184
- "Sorry, I was unable to process your request at this time. Please try again.",
11185
- "system"
11186
- )
11187
- );
11188
- }
11189
- await sseHelper.complete();
11190
- } catch (error) {
11191
- logger23.error(
11192
- {
11193
- error: error instanceof Error ? error.message : error,
11194
- stack: error instanceof Error ? error.stack : void 0
11195
- },
11196
- "Error during streaming execution"
11197
- );
11189
+ }
11190
+ await agentsCore.createMessage(dbClient_default)({
11191
+ id: nanoid.nanoid(),
11192
+ tenantId,
11193
+ projectId,
11194
+ conversationId,
11195
+ role: "user",
11196
+ content: {
11197
+ text: userMessage
11198
+ },
11199
+ visibility: "user-facing",
11200
+ messageType: "chat"
11201
+ });
11202
+ if (messageSpan) {
11203
+ messageSpan.addEvent("user.message.stored", {
11204
+ "message.id": conversationId,
11205
+ "database.operation": "insert"
11206
+ });
11207
+ }
11208
+ return streaming.streamSSE(c, async (stream2) => {
11198
11209
  try {
11199
11210
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
11200
- await sseHelper.writeOperation(
11201
- errorOp(
11202
- "Sorry, I was unable to process your request at this time. Please try again.",
11203
- "system"
11204
- )
11211
+ await sseHelper.writeRole();
11212
+ logger23.info({ subAgentId }, "Starting execution");
11213
+ const emitOperationsHeader = c.req.header("x-emit-operations");
11214
+ const emitOperations = emitOperationsHeader === "true";
11215
+ const executionHandler = new ExecutionHandler();
11216
+ const result = await executionHandler.execute({
11217
+ executionContext,
11218
+ conversationId,
11219
+ userMessage,
11220
+ initialAgentId: subAgentId,
11221
+ requestId: requestId2,
11222
+ sseHelper,
11223
+ emitOperations
11224
+ });
11225
+ logger23.info(
11226
+ { result },
11227
+ `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11205
11228
  );
11229
+ if (!result.success) {
11230
+ await sseHelper.writeOperation(
11231
+ errorOp(
11232
+ "Sorry, I was unable to process your request at this time. Please try again.",
11233
+ "system"
11234
+ )
11235
+ );
11236
+ }
11206
11237
  await sseHelper.complete();
11207
- } catch (streamError) {
11208
- logger23.error({ streamError }, "Failed to write error to stream");
11238
+ } catch (error) {
11239
+ logger23.error(
11240
+ {
11241
+ error: error instanceof Error ? error.message : error,
11242
+ stack: error instanceof Error ? error.stack : void 0
11243
+ },
11244
+ "Error during streaming execution"
11245
+ );
11246
+ try {
11247
+ const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
11248
+ await sseHelper.writeOperation(
11249
+ errorOp(
11250
+ "Sorry, I was unable to process your request at this time. Please try again.",
11251
+ "system"
11252
+ )
11253
+ );
11254
+ await sseHelper.complete();
11255
+ } catch (streamError) {
11256
+ logger23.error({ streamError }, "Failed to write error to stream");
11257
+ }
11209
11258
  }
11210
- }
11259
+ });
11211
11260
  });
11212
11261
  } catch (error) {
11213
11262
  logger23.error(
@@ -11303,123 +11352,131 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11303
11352
  "project.id": projectId
11304
11353
  });
11305
11354
  }
11306
- const agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11307
- scopes: { tenantId, projectId, agentId }
11308
- });
11309
- if (!agent) {
11310
- throw agentsCore.createApiError({
11311
- code: "not_found",
11312
- message: "Agent not found"
11313
- });
11355
+ let currentBag = api.propagation.getBaggage(api.context.active());
11356
+ if (!currentBag) {
11357
+ currentBag = api.propagation.createBaggage();
11314
11358
  }
11315
- const defaultSubAgentId = agent.defaultSubAgentId;
11316
- const agentName = agent.name;
11317
- if (!defaultSubAgentId) {
11318
- throw agentsCore.createApiError({
11319
- code: "bad_request",
11320
- message: "Agent does not have a default agent configured"
11359
+ currentBag = currentBag.setEntry("conversation.id", { value: conversationId });
11360
+ const ctxWithBaggage = api.propagation.setBaggage(api.context.active(), currentBag);
11361
+ return await api.context.with(ctxWithBaggage, async () => {
11362
+ const agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11363
+ scopes: { tenantId, projectId, agentId }
11321
11364
  });
11322
- }
11323
- const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11324
- scopes: { tenantId, projectId },
11325
- conversationId
11326
- });
11327
- if (!activeAgent) {
11328
- agentsCore.setActiveAgentForConversation(dbClient_default)({
11365
+ if (!agent) {
11366
+ throw agentsCore.createApiError({
11367
+ code: "not_found",
11368
+ message: "Agent not found"
11369
+ });
11370
+ }
11371
+ const defaultSubAgentId = agent.defaultSubAgentId;
11372
+ const agentName = agent.name;
11373
+ if (!defaultSubAgentId) {
11374
+ throw agentsCore.createApiError({
11375
+ code: "bad_request",
11376
+ message: "Agent does not have a default agent configured"
11377
+ });
11378
+ }
11379
+ const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11329
11380
  scopes: { tenantId, projectId },
11330
- conversationId,
11331
- subAgentId: defaultSubAgentId
11381
+ conversationId
11332
11382
  });
11333
- }
11334
- const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11335
- const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11336
- scopes: { tenantId, projectId, agentId },
11337
- subAgentId
11338
- });
11339
- if (!agentInfo) {
11340
- throw agentsCore.createApiError({
11341
- code: "not_found",
11342
- message: "Agent not found"
11383
+ if (!activeAgent) {
11384
+ agentsCore.setActiveAgentForConversation(dbClient_default)({
11385
+ scopes: { tenantId, projectId },
11386
+ conversationId,
11387
+ subAgentId: defaultSubAgentId
11388
+ });
11389
+ }
11390
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11391
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11392
+ scopes: { tenantId, projectId, agentId },
11393
+ subAgentId
11343
11394
  });
11344
- }
11345
- const validatedContext = c.get("validatedContext") || body.headers || {};
11346
- const credentialStores = c.get("credentialStores");
11347
- await agentsCore.handleContextResolution({
11348
- tenantId,
11349
- projectId,
11350
- agentId,
11351
- conversationId,
11352
- headers: validatedContext,
11353
- dbClient: dbClient_default,
11354
- credentialStores
11355
- });
11356
- const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
11357
- const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
11358
- logger24.info({ userText, lastUserMessage }, "userText");
11359
- const messageSpan = api.trace.getActiveSpan();
11360
- if (messageSpan) {
11361
- messageSpan.setAttributes({
11362
- "message.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
11363
- "message.content": userText,
11364
- "agent.name": agentName
11395
+ if (!agentInfo) {
11396
+ throw agentsCore.createApiError({
11397
+ code: "not_found",
11398
+ message: "Agent not found"
11399
+ });
11400
+ }
11401
+ const validatedContext = c.get("validatedContext") || body.headers || {};
11402
+ const credentialStores = c.get("credentialStores");
11403
+ await agentsCore.handleContextResolution({
11404
+ tenantId,
11405
+ projectId,
11406
+ agentId,
11407
+ conversationId,
11408
+ headers: validatedContext,
11409
+ dbClient: dbClient_default,
11410
+ credentialStores
11365
11411
  });
11366
- }
11367
- await agentsCore.createMessage(dbClient_default)({
11368
- id: nanoid.nanoid(),
11369
- tenantId,
11370
- projectId,
11371
- conversationId,
11372
- role: "user",
11373
- content: { text: userText },
11374
- visibility: "user-facing",
11375
- messageType: "chat"
11376
- });
11377
- if (messageSpan) {
11378
- messageSpan.addEvent("user.message.stored", {
11379
- "message.id": conversationId,
11380
- "database.operation": "insert"
11412
+ const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
11413
+ const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
11414
+ logger24.info({ userText, lastUserMessage }, "userText");
11415
+ const messageSpan = api.trace.getActiveSpan();
11416
+ if (messageSpan) {
11417
+ messageSpan.setAttributes({
11418
+ "message.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
11419
+ "message.content": userText,
11420
+ "agent.name": agentName
11421
+ });
11422
+ }
11423
+ await agentsCore.createMessage(dbClient_default)({
11424
+ id: nanoid.nanoid(),
11425
+ tenantId,
11426
+ projectId,
11427
+ conversationId,
11428
+ role: "user",
11429
+ content: { text: userText },
11430
+ visibility: "user-facing",
11431
+ messageType: "chat"
11381
11432
  });
11382
- }
11383
- const dataStream = ai.createUIMessageStream({
11384
- execute: async ({ writer }) => {
11385
- const streamHelper = createVercelStreamHelper(writer);
11386
- try {
11387
- const emitOperationsHeader = c.req.header("x-emit-operations");
11388
- const emitOperations = emitOperationsHeader === "true";
11389
- const executionHandler = new ExecutionHandler();
11390
- const result = await executionHandler.execute({
11391
- executionContext,
11392
- conversationId,
11393
- userMessage: userText,
11394
- initialAgentId: subAgentId,
11395
- requestId: `chatds-${Date.now()}`,
11396
- sseHelper: streamHelper,
11397
- emitOperations
11398
- });
11399
- if (!result.success) {
11400
- await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
11401
- }
11402
- } catch (err) {
11403
- logger24.error({ err }, "Streaming error");
11404
- await streamHelper.writeOperation(errorOp("Internal server error", "system"));
11405
- } finally {
11406
- if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
11407
- streamHelper.cleanup();
11433
+ if (messageSpan) {
11434
+ messageSpan.addEvent("user.message.stored", {
11435
+ "message.id": conversationId,
11436
+ "database.operation": "insert"
11437
+ });
11438
+ }
11439
+ const dataStream = ai.createUIMessageStream({
11440
+ execute: async ({ writer }) => {
11441
+ const streamHelper = createVercelStreamHelper(writer);
11442
+ try {
11443
+ const emitOperationsHeader = c.req.header("x-emit-operations");
11444
+ const emitOperations = emitOperationsHeader === "true";
11445
+ const executionHandler = new ExecutionHandler();
11446
+ const result = await executionHandler.execute({
11447
+ executionContext,
11448
+ conversationId,
11449
+ userMessage: userText,
11450
+ initialAgentId: subAgentId,
11451
+ requestId: `chatds-${Date.now()}`,
11452
+ sseHelper: streamHelper,
11453
+ emitOperations
11454
+ });
11455
+ if (!result.success) {
11456
+ await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
11457
+ }
11458
+ } catch (err) {
11459
+ logger24.error({ err }, "Streaming error");
11460
+ await streamHelper.writeOperation(errorOp("Internal server error", "system"));
11461
+ } finally {
11462
+ if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
11463
+ streamHelper.cleanup();
11464
+ }
11408
11465
  }
11409
11466
  }
11410
- }
11467
+ });
11468
+ c.header("content-type", "text/event-stream");
11469
+ c.header("cache-control", "no-cache");
11470
+ c.header("connection", "keep-alive");
11471
+ c.header("x-vercel-ai-data-stream", "v2");
11472
+ c.header("x-accel-buffering", "no");
11473
+ return streaming.stream(
11474
+ c,
11475
+ (stream2) => stream2.pipe(
11476
+ dataStream.pipeThrough(new ai.JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
11477
+ )
11478
+ );
11411
11479
  });
11412
- c.header("content-type", "text/event-stream");
11413
- c.header("cache-control", "no-cache");
11414
- c.header("connection", "keep-alive");
11415
- c.header("x-vercel-ai-data-stream", "v2");
11416
- c.header("x-accel-buffering", "no");
11417
- return streaming.stream(
11418
- c,
11419
- (stream2) => stream2.pipe(
11420
- dataStream.pipeThrough(new ai.JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
11421
- )
11422
- );
11423
11480
  } catch (error) {
11424
11481
  logger24.error({ error }, "chatDataStream error");
11425
11482
  throw agentsCore.createApiError({
@@ -11751,66 +11808,83 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11751
11808
  const { tenantId, projectId, agentId } = executionContext;
11752
11809
  logger25.info({ body }, "Received initialization request");
11753
11810
  const sessionId = agentsCore.getConversationId();
11754
- const agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11755
- scopes: { tenantId, projectId, agentId }
11756
- });
11757
- if (!agent) {
11758
- return c.json(
11759
- {
11760
- jsonrpc: "2.0",
11761
- error: { code: -32001, message: "Agent not found" },
11762
- id: body.id || null
11763
- },
11764
- { status: 404 }
11765
- );
11811
+ const activeSpan = api.trace.getActiveSpan();
11812
+ if (activeSpan) {
11813
+ activeSpan.setAttributes({
11814
+ "conversation.id": sessionId,
11815
+ "tenant.id": tenantId,
11816
+ "agent.id": agentId,
11817
+ "project.id": projectId
11818
+ });
11819
+ }
11820
+ let currentBag = api.propagation.getBaggage(api.context.active());
11821
+ if (!currentBag) {
11822
+ currentBag = api.propagation.createBaggage();
11766
11823
  }
11767
- if (!agent.defaultSubAgentId) {
11768
- return c.json(
11824
+ currentBag = currentBag.setEntry("conversation.id", { value: sessionId });
11825
+ const ctxWithBaggage = api.propagation.setBaggage(api.context.active(), currentBag);
11826
+ return await api.context.with(ctxWithBaggage, async () => {
11827
+ const agent = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
11828
+ scopes: { tenantId, projectId, agentId }
11829
+ });
11830
+ if (!agent) {
11831
+ return c.json(
11832
+ {
11833
+ jsonrpc: "2.0",
11834
+ error: { code: -32001, message: "Agent not found" },
11835
+ id: body.id || null
11836
+ },
11837
+ { status: 404 }
11838
+ );
11839
+ }
11840
+ if (!agent.defaultSubAgentId) {
11841
+ return c.json(
11842
+ {
11843
+ jsonrpc: "2.0",
11844
+ error: { code: -32001, message: "Agent does not have a default agent configured" },
11845
+ id: body.id || null
11846
+ },
11847
+ { status: 400 }
11848
+ );
11849
+ }
11850
+ const conversation = await agentsCore.createOrGetConversation(dbClient_default)({
11851
+ id: sessionId,
11852
+ tenantId,
11853
+ projectId,
11854
+ activeSubAgentId: agent.defaultSubAgentId,
11855
+ metadata: {
11856
+ sessionData: {
11857
+ agentId,
11858
+ sessionType: "mcp",
11859
+ mcpProtocolVersion: c.req.header("mcp-protocol-version"),
11860
+ initialized: false
11861
+ // Track initialization state
11862
+ }
11863
+ }
11864
+ });
11865
+ logger25.info(
11866
+ { sessionId, conversationId: conversation.id },
11867
+ "Created MCP session as conversation"
11868
+ );
11869
+ const transport = new streamableHttp_js.StreamableHTTPServerTransport({
11870
+ sessionIdGenerator: () => sessionId
11871
+ });
11872
+ const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
11873
+ await server.connect(transport);
11874
+ logger25.info({ sessionId }, "Server connected for initialization");
11875
+ res.setHeader("Mcp-Session-Id", sessionId);
11876
+ logger25.info(
11769
11877
  {
11770
- jsonrpc: "2.0",
11771
- error: { code: -32001, message: "Agent does not have a default agent configured" },
11772
- id: body.id || null
11878
+ sessionId,
11879
+ bodyMethod: body?.method,
11880
+ bodyId: body?.id
11773
11881
  },
11774
- { status: 400 }
11882
+ "About to handle initialization request"
11775
11883
  );
11776
- }
11777
- const conversation = await agentsCore.createOrGetConversation(dbClient_default)({
11778
- id: sessionId,
11779
- tenantId,
11780
- projectId,
11781
- activeSubAgentId: agent.defaultSubAgentId,
11782
- metadata: {
11783
- sessionData: {
11784
- agentId,
11785
- sessionType: "mcp",
11786
- mcpProtocolVersion: c.req.header("mcp-protocol-version"),
11787
- initialized: false
11788
- // Track initialization state
11789
- }
11790
- }
11791
- });
11792
- logger25.info(
11793
- { sessionId, conversationId: conversation.id },
11794
- "Created MCP session as conversation"
11795
- );
11796
- const transport = new streamableHttp_js.StreamableHTTPServerTransport({
11797
- sessionIdGenerator: () => sessionId
11884
+ await transport.handleRequest(req, res, body);
11885
+ logger25.info({ sessionId }, "Successfully handled initialization request");
11886
+ return fetchToNode.toFetchResponse(res);
11798
11887
  });
11799
- const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
11800
- await server.connect(transport);
11801
- logger25.info({ sessionId }, "Server connected for initialization");
11802
- res.setHeader("Mcp-Session-Id", sessionId);
11803
- logger25.info(
11804
- {
11805
- sessionId,
11806
- bodyMethod: body?.method,
11807
- bodyId: body?.id
11808
- },
11809
- "About to handle initialization request"
11810
- );
11811
- await transport.handleRequest(req, res, body);
11812
- logger25.info({ sessionId }, "Successfully handled initialization request");
11813
- return fetchToNode.toFetchResponse(res);
11814
11888
  };
11815
11889
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
11816
11890
  const { tenantId, projectId, agentId } = executionContext;