@inkeep/agents-run-api 0.19.6 → 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.
Files changed (3) hide show
  1. package/dist/index.cjs +350 -308
  2. package/dist/index.js +350 -308
  3. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -11040,174 +11040,191 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11040
11040
  );
11041
11041
  const body = c.get("requestBody") || {};
11042
11042
  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)({
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)({
11061
11060
  scopes: { tenantId, projectId, agentId }
11062
11061
  });
11063
- 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) {
11064
11088
  throw agentsCore.createApiError({
11065
11089
  code: "not_found",
11066
- message: "Agent not found"
11090
+ message: "No default agent found in agent"
11067
11091
  });
11068
11092
  }
11069
- defaultSubAgentId = agent.defaultSubAgentId || "";
11070
- }
11071
- if (!defaultSubAgentId) {
11072
- throw agentsCore.createApiError({
11073
- code: "not_found",
11074
- message: "No default agent found in agent"
11093
+ await agentsCore.createOrGetConversation(dbClient_default)({
11094
+ tenantId,
11095
+ projectId,
11096
+ id: conversationId,
11097
+ activeSubAgentId: defaultSubAgentId
11075
11098
  });
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)({
11099
+ const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11089
11100
  scopes: { tenantId, projectId },
11090
- conversationId,
11091
- subAgentId: defaultSubAgentId
11101
+ conversationId
11092
11102
  });
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"
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
11103
11114
  });
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
- {
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({
11118
11124
  tenantId,
11119
11125
  projectId,
11120
11126
  agentId,
11121
11127
  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"
11128
+ headers: validatedContext,
11129
+ dbClient: dbClient_default,
11130
+ credentialStores
11158
11131
  });
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,
11132
+ logger23.info(
11133
+ {
11134
+ tenantId,
11135
+ projectId,
11136
+ agentId,
11170
11137
  conversationId,
11171
- userMessage,
11172
- initialAgentId: subAgentId,
11173
- requestId: requestId2,
11174
- sseHelper,
11175
- 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()
11176
11156
  });
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
- );
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) => {
11198
11177
  try {
11199
11178
  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
- )
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`
11205
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
+ }
11206
11205
  await sseHelper.complete();
11207
- } catch (streamError) {
11208
- 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
+ }
11209
11226
  }
11210
- }
11227
+ });
11211
11228
  });
11212
11229
  } catch (error) {
11213
11230
  logger23.error(
@@ -11303,123 +11320,131 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11303
11320
  "project.id": projectId
11304
11321
  });
11305
11322
  }
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
- });
11323
+ let currentBag = api.propagation.getBaggage(api.context.active());
11324
+ if (!currentBag) {
11325
+ currentBag = api.propagation.createBaggage();
11314
11326
  }
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"
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 }
11321
11332
  });
11322
- }
11323
- const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
11324
- scopes: { tenantId, projectId },
11325
- conversationId
11326
- });
11327
- if (!activeAgent) {
11328
- 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)({
11329
11348
  scopes: { tenantId, projectId },
11330
- conversationId,
11331
- subAgentId: defaultSubAgentId
11349
+ conversationId
11332
11350
  });
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"
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
11343
11362
  });
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
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
11365
11379
  });
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"
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"
11381
11400
  });
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();
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
+ }
11408
11433
  }
11409
11434
  }
11410
- }
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
+ );
11411
11447
  });
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
11448
  } catch (error) {
11424
11449
  logger24.error({ error }, "chatDataStream error");
11425
11450
  throw agentsCore.createApiError({
@@ -11751,66 +11776,83 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11751
11776
  const { tenantId, projectId, agentId } = executionContext;
11752
11777
  logger25.info({ body }, "Received initialization request");
11753
11778
  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
- );
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
+ });
11766
11787
  }
11767
- if (!agent.defaultSubAgentId) {
11768
- 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(
11769
11845
  {
11770
- jsonrpc: "2.0",
11771
- error: { code: -32001, message: "Agent does not have a default agent configured" },
11772
- id: body.id || null
11846
+ sessionId,
11847
+ bodyMethod: body?.method,
11848
+ bodyId: body?.id
11773
11849
  },
11774
- { status: 400 }
11850
+ "About to handle initialization request"
11775
11851
  );
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
11852
+ await transport.handleRequest(req, res, body);
11853
+ logger25.info({ sessionId }, "Successfully handled initialization request");
11854
+ return fetchToNode.toFetchResponse(res);
11798
11855
  });
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
11856
  };
11815
11857
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
11816
11858
  const { tenantId, projectId, agentId } = executionContext;