@inkeep/agents-run-api 0.0.0-dev-20251009192735 → 0.0.0-dev-20251009215610

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { flushBatchProcessor } from './chunk-XO4RG36I.js';
2
2
  import { getLogger } from './chunk-A2S7GSHL.js';
3
- import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-5GUNCN5X.js';
3
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-DQQRVSJS.js';
4
4
  import { dbClient_default } from './chunk-7IMXW4RD.js';
5
5
  import { env } from './chunk-NZHNG4A3.js';
6
6
  import { __publicField } from './chunk-PKBMQBKP.js';
7
- import { getLogger as getLogger$1, getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentGraphWithDefaultAgent, contextValidationMiddleware, getConversationId, getFullGraph, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getAgentById, handleContextResolution, createMessage, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, getAgentGraphById, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getRelatedAgentsForGraph, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, getProject, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunction, getContextConfigById, getFullGraphDefinition, TemplateEngine, graphHasArtifactComponents, MCPTransportType, getExternalAgent } from '@inkeep/agents-core';
7
+ import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentGraphWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullGraph, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, getAgentGraphById, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getRelatedAgentsForGraph, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, getProject, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunction, getContextConfigById, getFullGraphDefinition, TemplateEngine, graphHasArtifactComponents, MCPTransportType, SPAN_KEYS, getExternalAgent } from '@inkeep/agents-core';
8
8
  import { otel } from '@hono/otel';
9
9
  import { OpenAPIHono, createRoute, z as z$1 } from '@hono/zod-openapi';
10
10
  import { trace, propagation, context, SpanStatusCode } from '@opentelemetry/api';
@@ -41,7 +41,7 @@ function createExecutionContext(params) {
41
41
  graphId: params.graphId,
42
42
  baseUrl: params.baseUrl || process.env.API_URL || "http://localhost:3003",
43
43
  apiKeyId: params.apiKeyId,
44
- agentId: params.agentId
44
+ subAgentId: params.subAgentId
45
45
  };
46
46
  }
47
47
 
@@ -56,16 +56,18 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
56
56
  const tenantId = c.req.header("x-inkeep-tenant-id");
57
57
  const projectId = c.req.header("x-inkeep-project-id");
58
58
  const graphId = c.req.header("x-inkeep-graph-id");
59
- const agentId = c.req.header("x-inkeep-agent-id");
60
- const proto = c.req.header("x-forwarded-proto") ?? "http";
61
- const host = c.req.header("x-forwarded-host") ?? c.req.header("host");
62
- const baseUrl = `${proto}://${host}`;
59
+ const subAgentId = c.req.header("x-inkeep-agent-id");
60
+ const proto = c.req.header("x-forwarded-proto")?.split(",")[0].trim();
61
+ const fwdHost = c.req.header("x-forwarded-host")?.split(",")[0].trim();
62
+ const host = fwdHost ?? c.req.header("host");
63
+ const reqUrl = new URL(c.req.url);
64
+ const baseUrl = proto && host ? `${proto}://${host}` : host ? `${reqUrl.protocol}//${host}` : `${reqUrl.origin}`;
63
65
  if (process.env.ENVIRONMENT === "development" || process.env.ENVIRONMENT === "test") {
64
66
  let executionContext;
65
67
  if (authHeader?.startsWith("Bearer ")) {
66
68
  try {
67
69
  executionContext = await extractContextFromApiKey(authHeader.substring(7), baseUrl);
68
- executionContext.agentId = agentId;
70
+ executionContext.subAgentId = subAgentId;
69
71
  logger.info({}, "Development/test environment - API key authenticated successfully");
70
72
  } catch {
71
73
  executionContext = createExecutionContext({
@@ -75,7 +77,7 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
75
77
  graphId: graphId || "test-graph",
76
78
  apiKeyId: "test-key",
77
79
  baseUrl,
78
- agentId
80
+ subAgentId
79
81
  });
80
82
  logger.info(
81
83
  {},
@@ -90,7 +92,7 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
90
92
  graphId: graphId || "test-graph",
91
93
  apiKeyId: "test-key",
92
94
  baseUrl,
93
- agentId
95
+ subAgentId
94
96
  });
95
97
  logger.info(
96
98
  {},
@@ -121,7 +123,7 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
121
123
  graphId,
122
124
  apiKeyId: "bypass",
123
125
  baseUrl,
124
- agentId
126
+ subAgentId
125
127
  });
126
128
  c.set("executionContext", executionContext);
127
129
  logger.info({}, "Bypass secret authenticated successfully");
@@ -129,7 +131,7 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
129
131
  return;
130
132
  } else if (apiKey) {
131
133
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
132
- executionContext.agentId = agentId;
134
+ executionContext.subAgentId = subAgentId;
133
135
  c.set("executionContext", executionContext);
134
136
  logger.info({}, "API key authenticated successfully");
135
137
  await next();
@@ -147,14 +149,14 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
147
149
  }
148
150
  try {
149
151
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
150
- executionContext.agentId = agentId;
152
+ executionContext.subAgentId = subAgentId;
151
153
  c.set("executionContext", executionContext);
152
154
  logger.debug(
153
155
  {
154
156
  tenantId: executionContext.tenantId,
155
157
  projectId: executionContext.projectId,
156
158
  graphId: executionContext.graphId,
157
- agentId: executionContext.agentId
159
+ subAgentId: executionContext.subAgentId
158
160
  },
159
161
  "API key authenticated successfully"
160
162
  );
@@ -322,7 +324,7 @@ async function handleMessageSend(c, agent, request) {
322
324
  logger2.warn(
323
325
  {
324
326
  taskId: task.id,
325
- agentId: agent.agentId,
327
+ subAgentId: agent.subAgentId,
326
328
  originalMessage: params.message
327
329
  },
328
330
  "Created fallback message content for empty delegation message"
@@ -343,7 +345,7 @@ async function handleMessageSend(c, agent, request) {
343
345
  taskContextId: task.context?.conversationId,
344
346
  metadataContextId: params.message.metadata?.conversationId,
345
347
  finalContextId: effectiveContextId,
346
- agentId: agent.agentId
348
+ subAgentId: agent.subAgentId
347
349
  },
348
350
  "A2A contextId resolution for delegation"
349
351
  );
@@ -359,11 +361,11 @@ async function handleMessageSend(c, agent, request) {
359
361
  message_id: params.message.messageId || "",
360
362
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
361
363
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
362
- agent_id: agent.agentId,
364
+ agent_id: agent.subAgentId,
363
365
  graph_id: graphId || "",
364
366
  stream_request_id: params.message.metadata?.stream_request_id
365
367
  },
366
- agentId: agent.agentId,
368
+ subAgentId: agent.subAgentId,
367
369
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
368
370
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
369
371
  });
@@ -386,17 +388,17 @@ async function handleMessageSend(c, agent, request) {
386
388
  };
387
389
  if (params.message.metadata?.fromAgentId) {
388
390
  messageData.fromAgentId = params.message.metadata.fromAgentId;
389
- messageData.toAgentId = agent.agentId;
391
+ messageData.toAgentId = agent.subAgentId;
390
392
  } else if (params.message.metadata?.fromExternalAgentId) {
391
393
  messageData.fromExternalAgentId = params.message.metadata.fromExternalAgentId;
392
- messageData.toAgentId = agent.agentId;
394
+ messageData.toAgentId = agent.subAgentId;
393
395
  }
394
396
  await createMessage(dbClient_default)(messageData);
395
397
  logger2.info(
396
398
  {
397
399
  fromAgentId: params.message.metadata.fromAgentId,
398
400
  fromExternalAgentId: params.message.metadata.fromExternalAgentId,
399
- toAgentId: agent.agentId,
401
+ toAgentId: agent.subAgentId,
400
402
  conversationId: effectiveContextId,
401
403
  messageType: "a2a-request",
402
404
  taskId: task.id
@@ -409,7 +411,7 @@ async function handleMessageSend(c, agent, request) {
409
411
  error,
410
412
  fromAgentId: params.message.metadata.fromAgentId,
411
413
  fromExternalAgentId: params.message.metadata.fromExternalAgentId,
412
- toAgentId: agent.agentId,
414
+ toAgentId: agent.subAgentId,
413
415
  conversationId: effectiveContextId
414
416
  },
415
417
  "Failed to store A2A message in database"
@@ -426,7 +428,7 @@ async function handleMessageSend(c, agent, request) {
426
428
  message_id: params.message.messageId || "",
427
429
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
428
430
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
429
- agent_id: agent.agentId,
431
+ agent_id: agent.subAgentId,
430
432
  graph_id: graphId || ""
431
433
  }
432
434
  }
@@ -460,7 +462,7 @@ async function handleMessageSend(c, agent, request) {
460
462
  kind: "data",
461
463
  data: {
462
464
  type: "transfer",
463
- targetAgentId: transferPart.data.target
465
+ targetSubAgentId: transferPart.data.target
464
466
  }
465
467
  },
466
468
  {
@@ -760,7 +762,7 @@ async function handleGetCapabilities(c, agent, request) {
760
762
  async function handleGetStatus(c, agent, request) {
761
763
  return c.json({
762
764
  jsonrpc: "2.0",
763
- result: { status: "ready", agentId: agent.agentId },
765
+ result: { status: "ready", subAgentId: agent.subAgentId },
764
766
  id: request.id
765
767
  });
766
768
  }
@@ -823,7 +825,6 @@ async function handleTasksResubscribe(c, agent, request) {
823
825
  });
824
826
  }
825
827
  }
826
- getLogger$1("agents");
827
828
  function createAgentCard({
828
829
  dbAgent,
829
830
  baseUrl
@@ -901,7 +902,7 @@ async function hydrateAgent({
901
902
  tenantId: dbAgent.tenantId,
902
903
  projectId: dbAgent.projectId,
903
904
  graphId,
904
- agentId: dbAgent.id,
905
+ subAgentId: dbAgent.id,
905
906
  baseUrl,
906
907
  apiKey
907
908
  });
@@ -911,7 +912,7 @@ async function hydrateAgent({
911
912
  baseUrl
912
913
  });
913
914
  return {
914
- agentId: dbAgent.id,
915
+ subAgentId: dbAgent.id,
915
916
  tenantId: dbAgent.tenantId,
916
917
  projectId: dbAgent.projectId,
917
918
  graphId,
@@ -924,13 +925,13 @@ async function hydrateAgent({
924
925
  }
925
926
  }
926
927
  async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
927
- const { tenantId, projectId, graphId, agentId, baseUrl, apiKey } = executionContext;
928
- if (!agentId) {
928
+ const { tenantId, projectId, graphId, subAgentId, baseUrl, apiKey } = executionContext;
929
+ if (!subAgentId) {
929
930
  throw new Error("Agent ID is required");
930
931
  }
931
- const dbAgent = await getAgentById(dbClient_default)({
932
+ const dbAgent = await getSubAgentById(dbClient_default)({
932
933
  scopes: { tenantId, projectId, graphId },
933
- agentId
934
+ subAgentId
934
935
  });
935
936
  if (!dbAgent) {
936
937
  return null;
@@ -944,7 +945,7 @@ async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
944
945
  apiKey
945
946
  });
946
947
  }
947
- var logger4 = getLogger("ModelFactory");
948
+ var logger3 = getLogger("ModelFactory");
948
949
  var _ModelFactory = class _ModelFactory {
949
950
  /**
950
951
  * Create a provider instance with custom configuration
@@ -1006,7 +1007,7 @@ var _ModelFactory = class _ModelFactory {
1006
1007
  }
1007
1008
  const modelString = modelSettings.model.trim();
1008
1009
  const { provider, modelName } = _ModelFactory.parseModelString(modelString);
1009
- logger4.debug(
1010
+ logger3.debug(
1010
1011
  {
1011
1012
  provider,
1012
1013
  model: modelName,
@@ -1017,7 +1018,7 @@ var _ModelFactory = class _ModelFactory {
1017
1018
  );
1018
1019
  const providerConfig = _ModelFactory.extractProviderConfig(modelSettings.providerOptions);
1019
1020
  if (Object.keys(providerConfig).length > 0) {
1020
- logger4.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
1021
+ logger3.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
1021
1022
  const customProvider = _ModelFactory.createProvider(provider, providerConfig);
1022
1023
  return customProvider.languageModel(modelName);
1023
1024
  }
@@ -1133,7 +1134,7 @@ __publicField(_ModelFactory, "BUILT_IN_PROVIDERS", [
1133
1134
  "gateway"
1134
1135
  ]);
1135
1136
  var ModelFactory = _ModelFactory;
1136
- var logger5 = getLogger("ToolSessionManager");
1137
+ var logger4 = getLogger("ToolSessionManager");
1137
1138
  var _ToolSessionManager = class _ToolSessionManager {
1138
1139
  // 5 minutes
1139
1140
  constructor() {
@@ -1168,7 +1169,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1168
1169
  createdAt: Date.now()
1169
1170
  };
1170
1171
  this.sessions.set(sessionId, session);
1171
- logger5.debug(
1172
+ logger4.debug(
1172
1173
  {
1173
1174
  sessionId,
1174
1175
  tenantId,
@@ -1186,10 +1187,10 @@ var _ToolSessionManager = class _ToolSessionManager {
1186
1187
  */
1187
1188
  ensureGraphSession(sessionId, tenantId, projectId, contextId, taskId) {
1188
1189
  if (this.sessions.has(sessionId)) {
1189
- logger5.debug({ sessionId }, "Graph session already exists, reusing");
1190
+ logger4.debug({ sessionId }, "Graph session already exists, reusing");
1190
1191
  return sessionId;
1191
1192
  }
1192
- logger5.debug(
1193
+ logger4.debug(
1193
1194
  { sessionId, tenantId, contextId, taskId },
1194
1195
  "Creating new graph-scoped tool session"
1195
1196
  );
@@ -1201,7 +1202,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1201
1202
  recordToolResult(sessionId, toolResult) {
1202
1203
  const session = this.sessions.get(sessionId);
1203
1204
  if (!session) {
1204
- logger5.warn(
1205
+ logger4.warn(
1205
1206
  {
1206
1207
  sessionId,
1207
1208
  toolCallId: toolResult.toolCallId,
@@ -1213,7 +1214,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1213
1214
  return;
1214
1215
  }
1215
1216
  session.toolResults.set(toolResult.toolCallId, toolResult);
1216
- logger5.debug(
1217
+ logger4.debug(
1217
1218
  {
1218
1219
  sessionId,
1219
1220
  toolCallId: toolResult.toolCallId,
@@ -1228,7 +1229,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1228
1229
  getToolResult(sessionId, toolCallId) {
1229
1230
  const session = this.sessions.get(sessionId);
1230
1231
  if (!session) {
1231
- logger5.warn(
1232
+ logger4.warn(
1232
1233
  {
1233
1234
  sessionId,
1234
1235
  toolCallId,
@@ -1241,7 +1242,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1241
1242
  }
1242
1243
  const result = session.toolResults.get(toolCallId);
1243
1244
  if (!result) {
1244
- logger5.warn(
1245
+ logger4.warn(
1245
1246
  {
1246
1247
  sessionId,
1247
1248
  toolCallId,
@@ -1251,7 +1252,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1251
1252
  "Tool result not found"
1252
1253
  );
1253
1254
  } else {
1254
- logger5.debug(
1255
+ logger4.debug(
1255
1256
  {
1256
1257
  sessionId,
1257
1258
  toolCallId,
@@ -1290,10 +1291,10 @@ var _ToolSessionManager = class _ToolSessionManager {
1290
1291
  }
1291
1292
  for (const sessionId of expiredSessions) {
1292
1293
  this.sessions.delete(sessionId);
1293
- logger5.debug({ sessionId }, "Cleaned up expired tool session");
1294
+ logger4.debug({ sessionId }, "Cleaned up expired tool session");
1294
1295
  }
1295
1296
  if (expiredSessions.length > 0) {
1296
- logger5.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
1297
+ logger4.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
1297
1298
  }
1298
1299
  }
1299
1300
  };
@@ -1363,7 +1364,7 @@ function extractFullFields(schema) {
1363
1364
  }
1364
1365
 
1365
1366
  // src/services/ArtifactService.ts
1366
- var logger7 = getLogger("ArtifactService");
1367
+ var logger6 = getLogger("ArtifactService");
1367
1368
  var _ArtifactService = class _ArtifactService {
1368
1369
  constructor(context) {
1369
1370
  this.context = context;
@@ -1395,7 +1396,7 @@ var _ArtifactService = class _ArtifactService {
1395
1396
  id: taskId
1396
1397
  });
1397
1398
  if (!task) {
1398
- logger7.warn({ taskId }, "Task not found when fetching artifacts");
1399
+ logger6.warn({ taskId }, "Task not found when fetching artifacts");
1399
1400
  continue;
1400
1401
  }
1401
1402
  const taskArtifacts = await getLedgerArtifacts(dbClient_default)({
@@ -1413,21 +1414,21 @@ var _ArtifactService = class _ArtifactService {
1413
1414
  }
1414
1415
  }
1415
1416
  } catch (error) {
1416
- logger7.error({ error, contextId }, "Error loading context artifacts");
1417
+ logger6.error({ error, contextId }, "Error loading context artifacts");
1417
1418
  }
1418
1419
  return artifacts;
1419
1420
  }
1420
1421
  /**
1421
1422
  * Create artifact from tool result and request data
1422
1423
  */
1423
- async createArtifact(request, agentId) {
1424
+ async createArtifact(request, subAgentId) {
1424
1425
  if (!this.context.sessionId) {
1425
- logger7.warn({ request }, "No session ID available for artifact creation");
1426
+ logger6.warn({ request }, "No session ID available for artifact creation");
1426
1427
  return null;
1427
1428
  }
1428
1429
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
1429
1430
  if (!toolResult) {
1430
- logger7.warn(
1431
+ logger6.warn(
1431
1432
  { request, sessionId: this.context.sessionId },
1432
1433
  "Tool result not found for artifact"
1433
1434
  );
@@ -1443,7 +1444,7 @@ var _ArtifactService = class _ArtifactService {
1443
1444
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
1444
1445
  }
1445
1446
  if (!selectedData) {
1446
- logger7.warn(
1447
+ logger6.warn(
1447
1448
  {
1448
1449
  request,
1449
1450
  baseSelector: request.baseSelector
@@ -1488,7 +1489,7 @@ var _ArtifactService = class _ArtifactService {
1488
1489
  type: request.type,
1489
1490
  data: cleanedSummaryData
1490
1491
  };
1491
- await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, agentId);
1492
+ await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, subAgentId);
1492
1493
  await this.cacheArtifact(
1493
1494
  request.artifactId,
1494
1495
  request.toolCallId,
@@ -1497,7 +1498,7 @@ var _ArtifactService = class _ArtifactService {
1497
1498
  );
1498
1499
  return artifactData;
1499
1500
  } catch (error) {
1500
- logger7.error({ error, request }, "Failed to create artifact");
1501
+ logger6.error({ error, request }, "Failed to create artifact");
1501
1502
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
1502
1503
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
1503
1504
  }
@@ -1526,7 +1527,7 @@ var _ArtifactService = class _ArtifactService {
1526
1527
  }
1527
1528
  try {
1528
1529
  if (!this.context.projectId || !this.context.taskId) {
1529
- logger7.warn(
1530
+ logger6.warn(
1530
1531
  { artifactId, toolCallId },
1531
1532
  "No projectId or taskId available for artifact lookup"
1532
1533
  );
@@ -1541,7 +1542,7 @@ var _ArtifactService = class _ArtifactService {
1541
1542
  return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
1542
1543
  }
1543
1544
  } catch (error) {
1544
- logger7.warn(
1545
+ logger6.warn(
1545
1546
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1546
1547
  "Failed to fetch artifact"
1547
1548
  );
@@ -1572,7 +1573,7 @@ var _ArtifactService = class _ArtifactService {
1572
1573
  }
1573
1574
  try {
1574
1575
  if (!this.context.projectId || !this.context.taskId) {
1575
- logger7.warn(
1576
+ logger6.warn(
1576
1577
  { artifactId, toolCallId },
1577
1578
  "No projectId or taskId available for artifact lookup"
1578
1579
  );
@@ -1587,7 +1588,7 @@ var _ArtifactService = class _ArtifactService {
1587
1588
  return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
1588
1589
  }
1589
1590
  } catch (error) {
1590
- logger7.warn(
1591
+ logger6.warn(
1591
1592
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1592
1593
  "Failed to fetch artifact"
1593
1594
  );
@@ -1623,8 +1624,8 @@ var _ArtifactService = class _ArtifactService {
1623
1624
  /**
1624
1625
  * Persist artifact to database via graph session
1625
1626
  */
1626
- async persistArtifact(request, summaryData, fullData, agentId) {
1627
- const effectiveAgentId = agentId || this.context.agentId;
1627
+ async persistArtifact(request, summaryData, fullData, subAgentId) {
1628
+ const effectiveAgentId = subAgentId || this.context.subAgentId;
1628
1629
  if (this.context.streamRequestId && effectiveAgentId && this.context.taskId) {
1629
1630
  await graphSessionManager.recordEvent(
1630
1631
  this.context.streamRequestId,
@@ -1637,7 +1638,7 @@ var _ArtifactService = class _ArtifactService {
1637
1638
  artifactType: request.type,
1638
1639
  summaryData,
1639
1640
  data: fullData,
1640
- agentId: effectiveAgentId,
1641
+ subAgentId: effectiveAgentId,
1641
1642
  metadata: {
1642
1643
  toolCallId: request.toolCallId,
1643
1644
  baseSelector: request.baseSelector,
@@ -1652,14 +1653,14 @@ var _ArtifactService = class _ArtifactService {
1652
1653
  }
1653
1654
  );
1654
1655
  } else {
1655
- logger7.warn(
1656
+ logger6.warn(
1656
1657
  {
1657
1658
  artifactId: request.artifactId,
1658
1659
  hasStreamRequestId: !!this.context.streamRequestId,
1659
1660
  hasAgentId: !!effectiveAgentId,
1660
1661
  hasTaskId: !!this.context.taskId,
1661
- passedAgentId: agentId,
1662
- contextAgentId: this.context.agentId
1662
+ passedAgentId: subAgentId,
1663
+ contextAgentId: this.context.subAgentId
1663
1664
  },
1664
1665
  "Skipping artifact_saved event - missing required context"
1665
1666
  );
@@ -1727,7 +1728,7 @@ var _ArtifactService = class _ArtifactService {
1727
1728
  summaryData = this.filterBySchema(artifact.data, previewSchema);
1728
1729
  fullData = this.filterBySchema(artifact.data, fullSchema);
1729
1730
  } catch (error) {
1730
- logger7.warn(
1731
+ logger6.warn(
1731
1732
  {
1732
1733
  artifactType: artifact.type,
1733
1734
  error: error instanceof Error ? error.message : "Unknown error"
@@ -1765,7 +1766,7 @@ var _ArtifactService = class _ArtifactService {
1765
1766
  artifact: artifactToSave
1766
1767
  });
1767
1768
  if (!result.created && result.existing) {
1768
- logger7.debug(
1769
+ logger6.debug(
1769
1770
  {
1770
1771
  artifactId: artifact.artifactId,
1771
1772
  taskId: this.context.taskId
@@ -1818,7 +1819,7 @@ var _ArtifactService = class _ArtifactService {
1818
1819
  extracted[propName] = this.cleanEscapedContent(rawValue);
1819
1820
  }
1820
1821
  } catch (error) {
1821
- logger7.warn(
1822
+ logger6.warn(
1822
1823
  { propName, selector, error: error instanceof Error ? error.message : "Unknown error" },
1823
1824
  "Failed to extract property"
1824
1825
  );
@@ -1850,7 +1851,7 @@ var _ArtifactService = class _ArtifactService {
1850
1851
  extracted[fieldName] = this.cleanEscapedContent(rawValue);
1851
1852
  }
1852
1853
  } catch (error) {
1853
- logger7.warn(
1854
+ logger6.warn(
1854
1855
  { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
1855
1856
  "Failed to extract schema field"
1856
1857
  );
@@ -1881,7 +1882,7 @@ __publicField(_ArtifactService, "selectorCache", /* @__PURE__ */ new Map());
1881
1882
  var ArtifactService = _ArtifactService;
1882
1883
 
1883
1884
  // src/services/ArtifactParser.ts
1884
- var logger8 = getLogger("ArtifactParser");
1885
+ var logger7 = getLogger("ArtifactParser");
1885
1886
  var _ArtifactParser = class _ArtifactParser {
1886
1887
  constructor(tenantId, options) {
1887
1888
  __publicField(this, "artifactService");
@@ -1969,7 +1970,7 @@ var _ArtifactParser = class _ArtifactParser {
1969
1970
  attrs[key] = value;
1970
1971
  }
1971
1972
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
1972
- logger8.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
1973
+ logger7.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
1973
1974
  return null;
1974
1975
  }
1975
1976
  return {
@@ -2000,7 +2001,7 @@ var _ArtifactParser = class _ArtifactParser {
2000
2001
  /**
2001
2002
  * Extract artifact data from a create annotation - delegates to service
2002
2003
  */
2003
- async extractFromCreateAnnotation(annotation, agentId) {
2004
+ async extractFromCreateAnnotation(annotation, subAgentId) {
2004
2005
  const request = {
2005
2006
  artifactId: annotation.artifactId,
2006
2007
  toolCallId: annotation.toolCallId,
@@ -2008,21 +2009,21 @@ var _ArtifactParser = class _ArtifactParser {
2008
2009
  baseSelector: annotation.baseSelector,
2009
2010
  detailsSelector: annotation.detailsSelector
2010
2011
  };
2011
- return this.artifactService.createArtifact(request, agentId);
2012
+ return this.artifactService.createArtifact(request, subAgentId);
2012
2013
  }
2013
2014
  /**
2014
2015
  * Parse text with artifact markers into parts array
2015
2016
  * Handles both artifact:ref and artifact:create tags
2016
2017
  * Can work with or without pre-fetched artifact map
2017
2018
  */
2018
- async parseText(text, artifactMap, agentId) {
2019
+ async parseText(text, artifactMap, subAgentId) {
2019
2020
  let processedText = text;
2020
2021
  const createAnnotations = this.parseCreateAnnotations(text);
2021
2022
  const createdArtifactData = /* @__PURE__ */ new Map();
2022
2023
  const failedAnnotations = [];
2023
2024
  for (const annotation of createAnnotations) {
2024
2025
  try {
2025
- const artifactData = await this.extractFromCreateAnnotation(annotation, agentId);
2026
+ const artifactData = await this.extractFromCreateAnnotation(annotation, subAgentId);
2026
2027
  if (artifactData && annotation.raw) {
2027
2028
  createdArtifactData.set(annotation.raw, artifactData);
2028
2029
  } else if (annotation.raw) {
@@ -2030,7 +2031,7 @@ var _ArtifactParser = class _ArtifactParser {
2030
2031
  `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
2031
2032
  );
2032
2033
  processedText = processedText.replace(annotation.raw, "");
2033
- logger8.warn(
2034
+ logger7.warn(
2034
2035
  { annotation, artifactData },
2035
2036
  "Removed failed artifact:create annotation from output"
2036
2037
  );
@@ -2041,11 +2042,11 @@ var _ArtifactParser = class _ArtifactParser {
2041
2042
  if (annotation.raw) {
2042
2043
  processedText = processedText.replace(annotation.raw, "");
2043
2044
  }
2044
- logger8.error({ annotation, error }, "Failed to extract artifact from create annotation");
2045
+ logger7.error({ annotation, error }, "Failed to extract artifact from create annotation");
2045
2046
  }
2046
2047
  }
2047
2048
  if (failedAnnotations.length > 0) {
2048
- logger8.warn(
2049
+ logger7.warn(
2049
2050
  {
2050
2051
  failedCount: failedAnnotations.length,
2051
2052
  failures: failedAnnotations
@@ -2109,7 +2110,7 @@ var _ArtifactParser = class _ArtifactParser {
2109
2110
  /**
2110
2111
  * Process object/dataComponents for artifact components
2111
2112
  */
2112
- async parseObject(obj, artifactMap, agentId) {
2113
+ async parseObject(obj, artifactMap, subAgentId) {
2113
2114
  if (obj?.dataComponents && Array.isArray(obj.dataComponents)) {
2114
2115
  const parts = [];
2115
2116
  for (const component of obj.dataComponents) {
@@ -2133,7 +2134,7 @@ var _ArtifactParser = class _ArtifactParser {
2133
2134
  });
2134
2135
  }
2135
2136
  } else if (this.isArtifactCreateComponent(component)) {
2136
- const createData = await this.extractFromArtifactCreateComponent(component, agentId);
2137
+ const createData = await this.extractFromArtifactCreateComponent(component, subAgentId);
2137
2138
  if (createData) {
2138
2139
  parts.push({
2139
2140
  kind: "data",
@@ -2174,7 +2175,7 @@ var _ArtifactParser = class _ArtifactParser {
2174
2175
  ] : [];
2175
2176
  }
2176
2177
  if (this.isArtifactCreateComponent(obj)) {
2177
- const createData = await this.extractFromArtifactCreateComponent(obj, agentId);
2178
+ const createData = await this.extractFromArtifactCreateComponent(obj, subAgentId);
2178
2179
  return createData ? [
2179
2180
  {
2180
2181
  kind: "data",
@@ -2206,7 +2207,7 @@ var _ArtifactParser = class _ArtifactParser {
2206
2207
  /**
2207
2208
  * Extract artifact from ArtifactCreate component
2208
2209
  */
2209
- async extractFromArtifactCreateComponent(component, agentId) {
2210
+ async extractFromArtifactCreateComponent(component, subAgentId) {
2210
2211
  const props = component.props;
2211
2212
  if (!props) {
2212
2213
  return null;
@@ -2218,7 +2219,7 @@ var _ArtifactParser = class _ArtifactParser {
2218
2219
  baseSelector: props.base_selector,
2219
2220
  detailsSelector: props.details_selector || {}
2220
2221
  };
2221
- return await this.extractFromCreateAnnotation(annotation, agentId);
2222
+ return await this.extractFromCreateAnnotation(annotation, subAgentId);
2222
2223
  }
2223
2224
  /**
2224
2225
  * Get artifact data - delegates to service
@@ -2258,7 +2259,7 @@ __publicField(_ArtifactParser, "INCOMPLETE_CREATE_REGEX", /<artifact:create(?![^
2258
2259
  var ArtifactParser = _ArtifactParser;
2259
2260
 
2260
2261
  // src/services/GraphSession.ts
2261
- var logger9 = getLogger("GraphSession");
2262
+ var logger8 = getLogger("GraphSession");
2262
2263
  var GraphSession = class {
2263
2264
  // Whether to send data operations
2264
2265
  constructor(sessionId, messageId, graphId, tenantId, projectId, contextId) {
@@ -2291,7 +2292,7 @@ var GraphSession = class {
2291
2292
  __publicField(this, "artifactParser");
2292
2293
  // Session-scoped ArtifactParser instance
2293
2294
  __publicField(this, "isEmitOperations", false);
2294
- logger9.debug({ sessionId, messageId, graphId }, "GraphSession created");
2295
+ logger8.debug({ sessionId, messageId, graphId }, "GraphSession created");
2295
2296
  if (tenantId && projectId) {
2296
2297
  toolSessionManager.createSessionWithId(
2297
2298
  sessionId,
@@ -2305,7 +2306,6 @@ var GraphSession = class {
2305
2306
  tenantId,
2306
2307
  projectId,
2307
2308
  sessionId,
2308
- // Same ID as ToolSession
2309
2309
  contextId,
2310
2310
  taskId: `task_${contextId}-${messageId}`,
2311
2311
  streamRequestId: sessionId
@@ -2326,7 +2326,7 @@ var GraphSession = class {
2326
2326
  */
2327
2327
  enableEmitOperations() {
2328
2328
  this.isEmitOperations = true;
2329
- logger9.info(
2329
+ logger8.info(
2330
2330
  { sessionId: this.sessionId },
2331
2331
  "\u{1F50D} DEBUG: Emit operations enabled for GraphSession"
2332
2332
  );
@@ -2343,14 +2343,14 @@ var GraphSession = class {
2343
2343
  label: this.generateEventLabel(event),
2344
2344
  details: {
2345
2345
  timestamp: event.timestamp,
2346
- agentId: event.agentId,
2346
+ subAgentId: event.subAgentId,
2347
2347
  data: event.data
2348
2348
  }
2349
2349
  };
2350
2350
  await streamHelper.writeOperation(formattedOperation);
2351
2351
  }
2352
2352
  } catch (error) {
2353
- logger9.error(
2353
+ logger8.error(
2354
2354
  {
2355
2355
  sessionId: this.sessionId,
2356
2356
  eventType: event.eventType,
@@ -2366,29 +2366,19 @@ var GraphSession = class {
2366
2366
  generateEventLabel(event) {
2367
2367
  switch (event.eventType) {
2368
2368
  case "agent_generate":
2369
- return `Agent ${event.agentId} generating response`;
2369
+ return `Agent ${event.subAgentId} generating response`;
2370
2370
  case "agent_reasoning":
2371
- return `Agent ${event.agentId} reasoning through request`;
2372
- case "tool_execution": {
2373
- const toolData = event.data;
2374
- return `Tool execution: ${toolData.toolName || "unknown"}`;
2375
- }
2376
- case "transfer": {
2377
- const transferData = event.data;
2378
- return `Agent transfer: ${transferData.fromAgent} \u2192 ${transferData.targetAgent}`;
2379
- }
2380
- case "delegation_sent": {
2381
- const delegationData = event.data;
2382
- return `Task delegated: ${delegationData.fromAgent} \u2192 ${delegationData.targetAgent}`;
2383
- }
2384
- case "delegation_returned": {
2385
- const returnData = event.data;
2386
- return `Task completed: ${returnData.targetAgent} \u2192 ${returnData.fromAgent}`;
2387
- }
2388
- case "artifact_saved": {
2389
- const artifactData = event.data;
2390
- return `Artifact saved: ${artifactData.artifactType || "unknown type"}`;
2391
- }
2371
+ return `Agent ${event.subAgentId} reasoning through request`;
2372
+ case "tool_execution":
2373
+ return `Tool execution: ${event.data.toolName || "unknown"}`;
2374
+ case "transfer":
2375
+ return `Agent transfer: ${event.data.fromSubAgent} \u2192 ${event.data.targetSubAgent}`;
2376
+ case "delegation_sent":
2377
+ return `Task delegated: ${event.data.fromSubAgent} \u2192 ${event.data.targetSubAgent}`;
2378
+ case "delegation_returned":
2379
+ return `Task completed: ${event.data.targetSubAgent} \u2192 ${event.data.fromSubAgent}`;
2380
+ case "artifact_saved":
2381
+ return `Artifact saved: ${event.data.artifactType || "unknown type"}`;
2392
2382
  default:
2393
2383
  return `${event.eventType} event`;
2394
2384
  }
@@ -2413,7 +2403,7 @@ var GraphSession = class {
2413
2403
  if (this.statusUpdateState.config.timeInSeconds) {
2414
2404
  this.statusUpdateTimer = setInterval(async () => {
2415
2405
  if (!this.statusUpdateState || this.isEnded) {
2416
- logger9.debug(
2406
+ logger8.debug(
2417
2407
  { sessionId: this.sessionId },
2418
2408
  "Timer triggered but session already cleaned up or ended"
2419
2409
  );
@@ -2425,7 +2415,7 @@ var GraphSession = class {
2425
2415
  }
2426
2416
  await this.checkAndSendTimeBasedUpdate();
2427
2417
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
2428
- logger9.info(
2418
+ logger8.info(
2429
2419
  {
2430
2420
  sessionId: this.sessionId,
2431
2421
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -2436,22 +2426,24 @@ var GraphSession = class {
2436
2426
  }
2437
2427
  /**
2438
2428
  * Record an event in the session and trigger status updates if configured
2429
+ * Generic type parameter T ensures eventType and data are correctly paired
2439
2430
  */
2440
- recordEvent(eventType, agentId, data) {
2431
+ recordEvent(eventType, subAgentId, data) {
2441
2432
  if (this.isEmitOperations) {
2442
- this.sendDataOperation({
2433
+ const dataOpEvent = {
2443
2434
  timestamp: Date.now(),
2444
2435
  eventType,
2445
- agentId,
2436
+ subAgentId,
2446
2437
  data
2447
- });
2438
+ };
2439
+ this.sendDataOperation(dataOpEvent);
2448
2440
  }
2449
2441
  if (this.isEnded) {
2450
- logger9.debug(
2442
+ logger8.debug(
2451
2443
  {
2452
2444
  sessionId: this.sessionId,
2453
2445
  eventType,
2454
- agentId
2446
+ subAgentId
2455
2447
  },
2456
2448
  "Event received after session ended - ignoring"
2457
2449
  );
@@ -2460,59 +2452,62 @@ var GraphSession = class {
2460
2452
  const event = {
2461
2453
  timestamp: Date.now(),
2462
2454
  eventType,
2463
- agentId,
2455
+ subAgentId,
2464
2456
  data
2465
2457
  };
2466
2458
  this.events.push(event);
2467
- if (eventType === "artifact_saved" && data.pendingGeneration) {
2468
- const artifactId = data.artifactId;
2469
- if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2470
- logger9.warn(
2471
- {
2472
- sessionId: this.sessionId,
2473
- artifactId,
2474
- pendingCount: this.pendingArtifacts.size,
2475
- maxAllowed: this.MAX_PENDING_ARTIFACTS
2476
- },
2477
- "Too many pending artifacts, skipping processing"
2478
- );
2479
- return;
2480
- }
2481
- this.pendingArtifacts.add(artifactId);
2482
- setImmediate(() => {
2483
- const artifactDataWithAgent = { ...data, agentId };
2484
- this.processArtifact(artifactDataWithAgent).then(() => {
2485
- this.pendingArtifacts.delete(artifactId);
2486
- this.artifactProcessingErrors.delete(artifactId);
2487
- }).catch((error) => {
2488
- const errorCount = (this.artifactProcessingErrors.get(artifactId) || 0) + 1;
2489
- this.artifactProcessingErrors.set(artifactId, errorCount);
2490
- if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2459
+ if (eventType === "artifact_saved") {
2460
+ const artifactData = data;
2461
+ if (artifactData.pendingGeneration) {
2462
+ const artifactId = artifactData.artifactId;
2463
+ if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2464
+ logger8.warn(
2465
+ {
2466
+ sessionId: this.sessionId,
2467
+ artifactId,
2468
+ pendingCount: this.pendingArtifacts.size,
2469
+ maxAllowed: this.MAX_PENDING_ARTIFACTS
2470
+ },
2471
+ "Too many pending artifacts, skipping processing"
2472
+ );
2473
+ return;
2474
+ }
2475
+ this.pendingArtifacts.add(artifactId);
2476
+ setImmediate(() => {
2477
+ const artifactDataWithAgent = { ...artifactData, subAgentId };
2478
+ this.processArtifact(artifactDataWithAgent).then(() => {
2491
2479
  this.pendingArtifacts.delete(artifactId);
2492
- logger9.error(
2493
- {
2494
- sessionId: this.sessionId,
2495
- artifactId,
2496
- errorCount,
2497
- maxRetries: this.MAX_ARTIFACT_RETRIES,
2498
- error: error instanceof Error ? error.message : "Unknown error",
2499
- stack: error instanceof Error ? error.stack : void 0
2500
- },
2501
- "Artifact processing failed after max retries, giving up"
2502
- );
2503
- } else {
2504
- logger9.warn(
2505
- {
2506
- sessionId: this.sessionId,
2507
- artifactId,
2508
- errorCount,
2509
- error: error instanceof Error ? error.message : "Unknown error"
2510
- },
2511
- "Artifact processing failed, may retry"
2512
- );
2513
- }
2480
+ this.artifactProcessingErrors.delete(artifactId);
2481
+ }).catch((error) => {
2482
+ const errorCount = (this.artifactProcessingErrors.get(artifactId) || 0) + 1;
2483
+ this.artifactProcessingErrors.set(artifactId, errorCount);
2484
+ if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2485
+ this.pendingArtifacts.delete(artifactId);
2486
+ logger8.error(
2487
+ {
2488
+ sessionId: this.sessionId,
2489
+ artifactId,
2490
+ errorCount,
2491
+ maxRetries: this.MAX_ARTIFACT_RETRIES,
2492
+ error: error instanceof Error ? error.message : "Unknown error",
2493
+ stack: error instanceof Error ? error.stack : void 0
2494
+ },
2495
+ "Artifact processing failed after max retries, giving up"
2496
+ );
2497
+ } else {
2498
+ logger8.warn(
2499
+ {
2500
+ sessionId: this.sessionId,
2501
+ artifactId,
2502
+ errorCount,
2503
+ error: error instanceof Error ? error.message : "Unknown error"
2504
+ },
2505
+ "Artifact processing failed, may retry"
2506
+ );
2507
+ }
2508
+ });
2514
2509
  });
2515
- });
2510
+ }
2516
2511
  }
2517
2512
  if (!this.isEnded) {
2518
2513
  this.checkStatusUpdates();
@@ -2523,14 +2518,14 @@ var GraphSession = class {
2523
2518
  */
2524
2519
  checkStatusUpdates() {
2525
2520
  if (this.isEnded) {
2526
- logger9.debug(
2521
+ logger8.debug(
2527
2522
  { sessionId: this.sessionId },
2528
2523
  "Session has ended - skipping status update check"
2529
2524
  );
2530
2525
  return;
2531
2526
  }
2532
2527
  if (!this.statusUpdateState) {
2533
- logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2528
+ logger8.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2534
2529
  return;
2535
2530
  }
2536
2531
  const statusUpdateState = this.statusUpdateState;
@@ -2541,11 +2536,11 @@ var GraphSession = class {
2541
2536
  */
2542
2537
  async checkAndSendTimeBasedUpdate() {
2543
2538
  if (this.isEnded) {
2544
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2539
+ logger8.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2545
2540
  return;
2546
2541
  }
2547
2542
  if (!this.statusUpdateState) {
2548
- logger9.debug(
2543
+ logger8.debug(
2549
2544
  { sessionId: this.sessionId },
2550
2545
  "No status updates configured for time-based check"
2551
2546
  );
@@ -2558,7 +2553,7 @@ var GraphSession = class {
2558
2553
  try {
2559
2554
  await this.generateAndSendUpdate();
2560
2555
  } catch (error) {
2561
- logger9.error(
2556
+ logger8.error(
2562
2557
  {
2563
2558
  sessionId: this.sessionId,
2564
2559
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2582,8 +2577,8 @@ var GraphSession = class {
2582
2577
  /**
2583
2578
  * Get events filtered by agent
2584
2579
  */
2585
- getEventsByAgent(agentId) {
2586
- return this.events.filter((event) => event.agentId === agentId);
2580
+ getEventsByAgent(subAgentId) {
2581
+ return this.events.filter((event) => event.subAgentId === subAgentId);
2587
2582
  }
2588
2583
  /**
2589
2584
  * Get summary of session activity
@@ -2598,7 +2593,7 @@ var GraphSession = class {
2598
2593
  );
2599
2594
  const agentCounts = this.events.reduce(
2600
2595
  (counts, event) => {
2601
- counts[event.agentId] = (counts[event.agentId] || 0) + 1;
2596
+ counts[event.subAgentId] = (counts[event.subAgentId] || 0) + 1;
2602
2597
  return counts;
2603
2598
  },
2604
2599
  {}
@@ -2661,29 +2656,29 @@ var GraphSession = class {
2661
2656
  */
2662
2657
  async generateAndSendUpdate() {
2663
2658
  if (this.isEnded) {
2664
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2659
+ logger8.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2665
2660
  return;
2666
2661
  }
2667
2662
  if (this.isTextStreaming) {
2668
- logger9.debug(
2663
+ logger8.debug(
2669
2664
  { sessionId: this.sessionId },
2670
2665
  "Text is currently streaming - skipping status update"
2671
2666
  );
2672
2667
  return;
2673
2668
  }
2674
2669
  if (this.isGeneratingUpdate) {
2675
- logger9.debug(
2670
+ logger8.debug(
2676
2671
  { sessionId: this.sessionId },
2677
2672
  "Update already in progress - skipping duplicate generation"
2678
2673
  );
2679
2674
  return;
2680
2675
  }
2681
2676
  if (!this.statusUpdateState) {
2682
- logger9.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2677
+ logger8.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2683
2678
  return;
2684
2679
  }
2685
2680
  if (!this.graphId) {
2686
- logger9.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
2681
+ logger8.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
2687
2682
  return;
2688
2683
  }
2689
2684
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -2695,7 +2690,7 @@ var GraphSession = class {
2695
2690
  try {
2696
2691
  const streamHelper = getStreamHelper(this.sessionId);
2697
2692
  if (!streamHelper) {
2698
- logger9.warn(
2693
+ logger8.warn(
2699
2694
  { sessionId: this.sessionId },
2700
2695
  "No stream helper found - cannot send status update"
2701
2696
  );
@@ -2715,7 +2710,7 @@ var GraphSession = class {
2715
2710
  if (result.summaries && result.summaries.length > 0) {
2716
2711
  for (const summary of result.summaries) {
2717
2712
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
2718
- logger9.warn(
2713
+ logger8.warn(
2719
2714
  {
2720
2715
  sessionId: this.sessionId,
2721
2716
  summary
@@ -2752,7 +2747,7 @@ var GraphSession = class {
2752
2747
  this.statusUpdateState.lastEventCount = this.events.length;
2753
2748
  }
2754
2749
  } catch (error) {
2755
- logger9.error(
2750
+ logger8.error(
2756
2751
  {
2757
2752
  sessionId: this.sessionId,
2758
2753
  error: error instanceof Error ? error.message : "Unknown error",
@@ -2790,7 +2785,7 @@ var GraphSession = class {
2790
2785
  this.releaseUpdateLock();
2791
2786
  }
2792
2787
  } catch (error) {
2793
- logger9.error(
2788
+ logger8.error(
2794
2789
  {
2795
2790
  sessionId: this.sessionId,
2796
2791
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2868,7 +2863,7 @@ User's Question/Context:
2868
2863
  ${conversationHistory}
2869
2864
  ` : "";
2870
2865
  } catch (error) {
2871
- logger9.warn(
2866
+ logger8.warn(
2872
2867
  { sessionId: this.sessionId, error },
2873
2868
  "Failed to fetch conversation history for structured status update"
2874
2869
  );
@@ -3002,7 +2997,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3002
2997
  return { summaries };
3003
2998
  } catch (error) {
3004
2999
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3005
- logger9.error({ error }, "Failed to generate structured update, using fallback");
3000
+ logger8.error({ error }, "Failed to generate structured update, using fallback");
3006
3001
  return { summaries: [] };
3007
3002
  } finally {
3008
3003
  span.end();
@@ -3028,7 +3023,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3028
3023
  */
3029
3024
  buildZodSchemaFromJson(jsonSchema) {
3030
3025
  const properties = {};
3031
- properties["label"] = z.string().describe(
3026
+ properties.label = z.string().describe(
3032
3027
  'A short 3-5 word phrase, that is a descriptive label for the update component. This Label must be EXTREMELY unique to represent the UNIQUE update we are providing. The SPECIFIC finding, result, or insight discovered (e.g., "Slack bot needs workspace admin role", "Found ingestion requires 3 steps", "Channel history limited to 10k messages"). State the ACTUAL information found, not that you searched. What did you LEARN or DISCOVER? What specific detail is now known? CRITICAL: Only use facts explicitly found in the activities - NEVER invent names, people, organizations, or details that are not present in the actual tool results.'
3033
3028
  );
3034
3029
  for (const [key, value] of Object.entries(jsonSchema.properties)) {
@@ -3097,11 +3092,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3097
3092
  for (const event of events) {
3098
3093
  switch (event.eventType) {
3099
3094
  case "tool_execution": {
3100
- const data = event.data;
3101
- const resultStr = JSON.stringify(data.result);
3095
+ const resultStr = JSON.stringify(event.data.result);
3102
3096
  activities.push(
3103
- `\u{1F527} **${data.toolName}** ${data.duration ? `(${data.duration}ms)` : ""}
3104
- \u{1F4E5} Input: ${JSON.stringify(data.args)}
3097
+ `\u{1F527} **${event.data.toolName}** ${event.data.duration ? `(${event.data.duration}ms)` : ""}
3098
+ \u{1F4E5} Input: ${JSON.stringify(event.data.args)}
3105
3099
  \u{1F4E4} Output: ${resultStr}`
3106
3100
  );
3107
3101
  break;
@@ -3113,23 +3107,24 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3113
3107
  case "artifact_saved":
3114
3108
  break;
3115
3109
  case "agent_reasoning": {
3116
- const data = event.data;
3117
3110
  activities.push(
3118
3111
  `\u2699\uFE0F **Analyzing request**
3119
- Details: ${JSON.stringify(data.parts, null, 2)}`
3112
+ Details: ${JSON.stringify(event.data.parts, null, 2)}`
3120
3113
  );
3121
3114
  break;
3122
3115
  }
3123
3116
  case "agent_generate": {
3124
- const data = event.data;
3125
3117
  activities.push(
3126
3118
  `\u2699\uFE0F **Preparing response**
3127
- Details: ${JSON.stringify(data.parts, null, 2)}`
3119
+ Details: ${JSON.stringify(event.data.parts, null, 2)}`
3128
3120
  );
3129
3121
  break;
3130
3122
  }
3131
3123
  default: {
3132
- activities.push(`\u{1F4CB} **${event.eventType}**: ${JSON.stringify(event.data, null, 2)}`);
3124
+ const safeEvent = event;
3125
+ activities.push(
3126
+ `\u{1F4CB} **${safeEvent.eventType}**: ${JSON.stringify(safeEvent.data, null, 2)}`
3127
+ );
3133
3128
  break;
3134
3129
  }
3135
3130
  }
@@ -3147,7 +3142,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3147
3142
  "graph_session.id": this.sessionId,
3148
3143
  "artifact.id": artifactData.artifactId,
3149
3144
  "artifact.type": artifactData.artifactType || "unknown",
3150
- "artifact.agent_id": artifactData.agentId || "unknown",
3145
+ "artifact.agent_id": artifactData.subAgentId || "unknown",
3151
3146
  "artifact.tool_call_id": artifactData.metadata?.toolCallId || "unknown",
3152
3147
  "artifact.data": JSON.stringify(artifactData.data, null, 2),
3153
3148
  "tenant.id": artifactData.tenantId || "unknown",
@@ -3206,34 +3201,34 @@ Make it specific and relevant.`;
3206
3201
  let modelToUse = this.statusUpdateState?.summarizerModel;
3207
3202
  if (!modelToUse?.model?.trim()) {
3208
3203
  if (!this.statusUpdateState?.baseModel?.model?.trim()) {
3209
- if (artifactData.agentId && artifactData.tenantId && artifactData.projectId) {
3204
+ if (artifactData.subAgentId && artifactData.tenantId && artifactData.projectId) {
3210
3205
  try {
3211
- const agentData = await getAgentById(dbClient_default)({
3206
+ const agentData = await getSubAgentById(dbClient_default)({
3212
3207
  scopes: {
3213
3208
  tenantId: artifactData.tenantId,
3214
3209
  projectId: artifactData.projectId,
3215
3210
  graphId: this.graphId || ""
3216
3211
  },
3217
- agentId: artifactData.agentId
3212
+ subAgentId: artifactData.subAgentId
3218
3213
  });
3219
3214
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
3220
3215
  modelToUse = agentData.models.base;
3221
- logger9.info(
3216
+ logger8.info(
3222
3217
  {
3223
3218
  sessionId: this.sessionId,
3224
3219
  artifactId: artifactData.artifactId,
3225
- agentId: artifactData.agentId,
3220
+ subAgentId: artifactData.subAgentId,
3226
3221
  model: modelToUse.model
3227
3222
  },
3228
3223
  "Using agent model configuration for artifact name generation"
3229
3224
  );
3230
3225
  }
3231
3226
  } catch (error) {
3232
- logger9.warn(
3227
+ logger8.warn(
3233
3228
  {
3234
3229
  sessionId: this.sessionId,
3235
3230
  artifactId: artifactData.artifactId,
3236
- agentId: artifactData.agentId,
3231
+ subAgentId: artifactData.subAgentId,
3237
3232
  error: error instanceof Error ? error.message : "Unknown error"
3238
3233
  },
3239
3234
  "Failed to get agent model configuration"
@@ -3241,7 +3236,7 @@ Make it specific and relevant.`;
3241
3236
  }
3242
3237
  }
3243
3238
  if (!modelToUse?.model?.trim()) {
3244
- logger9.warn(
3239
+ logger8.warn(
3245
3240
  {
3246
3241
  sessionId: this.sessionId,
3247
3242
  artifactId: artifactData.artifactId
@@ -3323,7 +3318,7 @@ Make it specific and relevant.`;
3323
3318
  return result2;
3324
3319
  } catch (error) {
3325
3320
  lastError = error instanceof Error ? error : new Error(String(error));
3326
- logger9.warn(
3321
+ logger8.warn(
3327
3322
  {
3328
3323
  sessionId: this.sessionId,
3329
3324
  artifactId: artifactData.artifactId,
@@ -3375,7 +3370,7 @@ Make it specific and relevant.`;
3375
3370
  });
3376
3371
  span.setStatus({ code: SpanStatusCode.OK });
3377
3372
  } catch (saveError) {
3378
- logger9.error(
3373
+ logger8.error(
3379
3374
  {
3380
3375
  sessionId: this.sessionId,
3381
3376
  artifactId: artifactData.artifactId,
@@ -3403,7 +3398,7 @@ Make it specific and relevant.`;
3403
3398
  metadata: artifactData.metadata || {},
3404
3399
  toolCallId: artifactData.toolCallId
3405
3400
  });
3406
- logger9.info(
3401
+ logger8.info(
3407
3402
  {
3408
3403
  sessionId: this.sessionId,
3409
3404
  artifactId: artifactData.artifactId
@@ -3414,7 +3409,7 @@ Make it specific and relevant.`;
3414
3409
  } catch (fallbackError) {
3415
3410
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
3416
3411
  if (isDuplicateError) ; else {
3417
- logger9.error(
3412
+ logger8.error(
3418
3413
  {
3419
3414
  sessionId: this.sessionId,
3420
3415
  artifactId: artifactData.artifactId,
@@ -3427,7 +3422,7 @@ Make it specific and relevant.`;
3427
3422
  }
3428
3423
  } catch (error) {
3429
3424
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3430
- logger9.error(
3425
+ logger8.error(
3431
3426
  {
3432
3427
  sessionId: this.sessionId,
3433
3428
  artifactId: artifactData.artifactId,
@@ -3446,7 +3441,7 @@ Make it specific and relevant.`;
3446
3441
  */
3447
3442
  setArtifactCache(key, artifact) {
3448
3443
  this.artifactCache.set(key, artifact);
3449
- logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3444
+ logger8.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3450
3445
  }
3451
3446
  /**
3452
3447
  * Get session-scoped ArtifactService instance
@@ -3465,7 +3460,7 @@ Make it specific and relevant.`;
3465
3460
  */
3466
3461
  getArtifactCache(key) {
3467
3462
  const artifact = this.artifactCache.get(key);
3468
- logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3463
+ logger8.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3469
3464
  return artifact || null;
3470
3465
  }
3471
3466
  /**
@@ -3488,7 +3483,7 @@ var GraphSessionManager = class {
3488
3483
  const sessionId = messageId;
3489
3484
  const session = new GraphSession(sessionId, messageId, graphId, tenantId, projectId, contextId);
3490
3485
  this.sessions.set(sessionId, session);
3491
- logger9.info(
3486
+ logger8.info(
3492
3487
  { sessionId, messageId, graphId, tenantId, projectId, contextId },
3493
3488
  "GraphSession created"
3494
3489
  );
@@ -3502,7 +3497,7 @@ var GraphSessionManager = class {
3502
3497
  if (session) {
3503
3498
  session.initializeStatusUpdates(config, summarizerModel);
3504
3499
  } else {
3505
- logger9.error(
3500
+ logger8.error(
3506
3501
  {
3507
3502
  sessionId,
3508
3503
  availableSessions: Array.from(this.sessions.keys())
@@ -3519,7 +3514,7 @@ var GraphSessionManager = class {
3519
3514
  if (session) {
3520
3515
  session.enableEmitOperations();
3521
3516
  } else {
3522
- logger9.error(
3517
+ logger8.error(
3523
3518
  {
3524
3519
  sessionId,
3525
3520
  availableSessions: Array.from(this.sessions.keys())
@@ -3536,14 +3531,15 @@ var GraphSessionManager = class {
3536
3531
  }
3537
3532
  /**
3538
3533
  * Record an event in a session
3534
+ * Generic type parameter T ensures eventType and data are correctly paired
3539
3535
  */
3540
- recordEvent(sessionId, eventType, agentId, data) {
3536
+ recordEvent(sessionId, eventType, subAgentId, data) {
3541
3537
  const session = this.sessions.get(sessionId);
3542
3538
  if (!session) {
3543
- logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
3539
+ logger8.warn({ sessionId }, "Attempted to record event in non-existent session");
3544
3540
  return;
3545
3541
  }
3546
- session.recordEvent(eventType, agentId, data);
3542
+ session.recordEvent(eventType, subAgentId, data);
3547
3543
  }
3548
3544
  /**
3549
3545
  * End a session and return the final event data
@@ -3551,12 +3547,12 @@ var GraphSessionManager = class {
3551
3547
  endSession(sessionId) {
3552
3548
  const session = this.sessions.get(sessionId);
3553
3549
  if (!session) {
3554
- logger9.warn({ sessionId }, "Attempted to end non-existent session");
3550
+ logger8.warn({ sessionId }, "Attempted to end non-existent session");
3555
3551
  return [];
3556
3552
  }
3557
3553
  const events = session.getEvents();
3558
3554
  const summary = session.getSummary();
3559
- logger9.info({ sessionId, summary }, "GraphSession ended");
3555
+ logger8.info({ sessionId, summary }, "GraphSession ended");
3560
3556
  session.cleanup();
3561
3557
  this.sessions.delete(sessionId);
3562
3558
  return events;
@@ -3655,7 +3651,7 @@ async function resolveModelConfig(graphId, agent) {
3655
3651
  }
3656
3652
 
3657
3653
  // src/services/IncrementalStreamParser.ts
3658
- var logger10 = getLogger("IncrementalStreamParser");
3654
+ var logger9 = getLogger("IncrementalStreamParser");
3659
3655
  var _IncrementalStreamParser = class _IncrementalStreamParser {
3660
3656
  // Max number of collected parts to prevent unbounded growth
3661
3657
  constructor(streamHelper, tenantId, contextId, artifactParserOptions) {
@@ -3671,10 +3667,10 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3671
3667
  __publicField(this, "lastStreamedComponents", /* @__PURE__ */ new Map());
3672
3668
  __publicField(this, "componentSnapshots", /* @__PURE__ */ new Map());
3673
3669
  __publicField(this, "artifactMap");
3674
- __publicField(this, "agentId");
3670
+ __publicField(this, "subAgentId");
3675
3671
  this.streamHelper = streamHelper;
3676
3672
  this.contextId = contextId;
3677
- this.agentId = artifactParserOptions?.agentId;
3673
+ this.subAgentId = artifactParserOptions?.subAgentId;
3678
3674
  if (artifactParserOptions?.streamRequestId) {
3679
3675
  const sessionParser = graphSessionManager.getArtifactParser(
3680
3676
  artifactParserOptions.streamRequestId
@@ -3707,7 +3703,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3707
3703
  async initializeArtifactMap() {
3708
3704
  try {
3709
3705
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
3710
- logger10.debug(
3706
+ logger9.debug(
3711
3707
  {
3712
3708
  contextId: this.contextId,
3713
3709
  artifactMapSize: this.artifactMap.size
@@ -3715,7 +3711,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3715
3711
  "Initialized artifact map for streaming"
3716
3712
  );
3717
3713
  } catch (error) {
3718
- logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3714
+ logger9.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3719
3715
  this.artifactMap = /* @__PURE__ */ new Map();
3720
3716
  }
3721
3717
  }
@@ -3817,7 +3813,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3817
3813
  dataComponents: [component]
3818
3814
  },
3819
3815
  this.artifactMap,
3820
- this.agentId
3816
+ this.subAgentId
3821
3817
  );
3822
3818
  if (!Array.isArray(parts)) {
3823
3819
  console.warn("parseObject returned non-array:", parts);
@@ -3893,7 +3889,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3893
3889
  dataComponents: [component]
3894
3890
  },
3895
3891
  this.artifactMap,
3896
- this.agentId
3892
+ this.subAgentId
3897
3893
  );
3898
3894
  for (const part of parts) {
3899
3895
  await this.streamPart(part);
@@ -3947,7 +3943,11 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3947
3943
  const safeEnd = this.artifactParser.findSafeTextBoundary(workingBuffer);
3948
3944
  if (safeEnd > 0) {
3949
3945
  const safeText = workingBuffer.slice(0, safeEnd);
3950
- const parts2 = await this.artifactParser.parseText(safeText, this.artifactMap, this.agentId);
3946
+ const parts2 = await this.artifactParser.parseText(
3947
+ safeText,
3948
+ this.artifactMap,
3949
+ this.subAgentId
3950
+ );
3951
3951
  completeParts.push(...parts2);
3952
3952
  return {
3953
3953
  completeParts,
@@ -3962,7 +3962,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3962
3962
  const parts = await this.artifactParser.parseText(
3963
3963
  workingBuffer,
3964
3964
  this.artifactMap,
3965
- this.agentId
3965
+ this.subAgentId
3966
3966
  );
3967
3967
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
3968
3968
  const lastPart = parts[parts.length - 1];
@@ -4035,12 +4035,12 @@ __publicField(_IncrementalStreamParser, "MAX_COLLECTED_PARTS", 1e4);
4035
4035
  var IncrementalStreamParser = _IncrementalStreamParser;
4036
4036
 
4037
4037
  // src/services/ResponseFormatter.ts
4038
- var logger11 = getLogger("ResponseFormatter");
4038
+ var logger10 = getLogger("ResponseFormatter");
4039
4039
  var ResponseFormatter = class {
4040
4040
  constructor(tenantId, artifactParserOptions) {
4041
4041
  __publicField(this, "artifactParser");
4042
- __publicField(this, "agentId");
4043
- this.agentId = artifactParserOptions?.agentId;
4042
+ __publicField(this, "subAgentId");
4043
+ this.subAgentId = artifactParserOptions?.subAgentId;
4044
4044
  if (artifactParserOptions?.streamRequestId) {
4045
4045
  const sessionParser = graphSessionManager.getArtifactParser(
4046
4046
  artifactParserOptions.streamRequestId
@@ -4079,7 +4079,7 @@ var ResponseFormatter = class {
4079
4079
  const parts = await this.artifactParser.parseObject(
4080
4080
  responseObject,
4081
4081
  artifactMap,
4082
- this.agentId
4082
+ this.subAgentId
4083
4083
  );
4084
4084
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
4085
4085
  span.setAttributes({
@@ -4094,7 +4094,7 @@ var ResponseFormatter = class {
4094
4094
  return { parts };
4095
4095
  } catch (error) {
4096
4096
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4097
- logger11.error({ error, responseObject }, "Error formatting object response");
4097
+ logger10.error({ error, responseObject }, "Error formatting object response");
4098
4098
  return {
4099
4099
  parts: [{ kind: "data", data: responseObject }]
4100
4100
  };
@@ -4126,7 +4126,11 @@ var ResponseFormatter = class {
4126
4126
  "response.type": "text",
4127
4127
  "response.availableArtifacts": artifactMap.size
4128
4128
  });
4129
- const parts = await this.artifactParser.parseText(responseText, artifactMap, this.agentId);
4129
+ const parts = await this.artifactParser.parseText(
4130
+ responseText,
4131
+ artifactMap,
4132
+ this.subAgentId
4133
+ );
4130
4134
  if (parts.length === 1 && parts[0].kind === "text") {
4131
4135
  return { text: parts[0].text };
4132
4136
  }
@@ -4146,7 +4150,7 @@ var ResponseFormatter = class {
4146
4150
  return { parts };
4147
4151
  } catch (error) {
4148
4152
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4149
- logger11.error({ error, responseText }, "Error formatting response");
4153
+ logger10.error({ error, responseText }, "Error formatting response");
4150
4154
  return { text: responseText };
4151
4155
  } finally {
4152
4156
  span.end();
@@ -4200,20 +4204,20 @@ function agentInitializingOp(sessionId, graphId) {
4200
4204
  }
4201
4205
  };
4202
4206
  }
4203
- function completionOp(agentId, iterations) {
4207
+ function completionOp(subAgentId, iterations) {
4204
4208
  return {
4205
4209
  type: "completion",
4206
4210
  details: {
4207
- agent: agentId,
4211
+ agent: subAgentId,
4208
4212
  iteration: iterations
4209
4213
  }
4210
4214
  };
4211
4215
  }
4212
- function errorOp(message, agentId, severity = "error", code) {
4216
+ function errorOp(message, subAgentId, severity = "error", code) {
4213
4217
  return {
4214
4218
  type: "error",
4215
4219
  message,
4216
- agent: agentId,
4220
+ agent: subAgentId,
4217
4221
  severity,
4218
4222
  code,
4219
4223
  timestamp: Date.now()
@@ -4222,10 +4226,10 @@ function errorOp(message, agentId, severity = "error", code) {
4222
4226
  function generateToolId() {
4223
4227
  return `tool_${nanoid(8)}`;
4224
4228
  }
4225
- var logger12 = getLogger("DataComponentSchema");
4229
+ var logger11 = getLogger("DataComponentSchema");
4226
4230
  function jsonSchemaToZod(jsonSchema) {
4227
4231
  if (!jsonSchema || typeof jsonSchema !== "object") {
4228
- logger12.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
4232
+ logger11.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
4229
4233
  return z.string();
4230
4234
  }
4231
4235
  switch (jsonSchema.type) {
@@ -4252,7 +4256,7 @@ function jsonSchemaToZod(jsonSchema) {
4252
4256
  case "null":
4253
4257
  return z.null();
4254
4258
  default:
4255
- logger12.warn(
4259
+ logger11.warn(
4256
4260
  {
4257
4261
  unsupportedType: jsonSchema.type,
4258
4262
  schema: jsonSchema
@@ -4615,7 +4619,7 @@ function parseEmbeddedJson(data) {
4615
4619
  }
4616
4620
 
4617
4621
  // src/a2a/client.ts
4618
- var logger13 = getLogger("a2aClient");
4622
+ var logger12 = getLogger("a2aClient");
4619
4623
  var DEFAULT_BACKOFF = {
4620
4624
  initialInterval: 500,
4621
4625
  maxInterval: 6e4,
@@ -4821,7 +4825,7 @@ var A2AClient = class {
4821
4825
  try {
4822
4826
  const res = await fn();
4823
4827
  if (attempt > 0) {
4824
- logger13.info(
4828
+ logger12.info(
4825
4829
  {
4826
4830
  attempts: attempt + 1,
4827
4831
  elapsedTime: Date.now() - start
@@ -4836,7 +4840,7 @@ var A2AClient = class {
4836
4840
  }
4837
4841
  const elapsed = Date.now() - start;
4838
4842
  if (elapsed > maxElapsedTime) {
4839
- logger13.warn(
4843
+ logger12.warn(
4840
4844
  {
4841
4845
  attempts: attempt + 1,
4842
4846
  elapsedTime: elapsed,
@@ -4857,7 +4861,7 @@ var A2AClient = class {
4857
4861
  retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
4858
4862
  }
4859
4863
  const delayMs = Math.min(retryInterval, maxInterval);
4860
- logger13.info(
4864
+ logger12.info(
4861
4865
  {
4862
4866
  attempt: attempt + 1,
4863
4867
  delayMs,
@@ -4942,7 +4946,7 @@ var A2AClient = class {
4942
4946
  }
4943
4947
  const rpcResponse = await httpResponse.json();
4944
4948
  if (rpcResponse.id !== requestId2) {
4945
- logger13.warn(
4949
+ logger12.warn(
4946
4950
  {
4947
4951
  method,
4948
4952
  expectedId: requestId2,
@@ -5141,7 +5145,7 @@ var A2AClient = class {
5141
5145
  try {
5142
5146
  while (true) {
5143
5147
  const { done, value } = await reader.read();
5144
- logger13.info({ done, value }, "parseA2ASseStream");
5148
+ logger12.info({ done, value }, "parseA2ASseStream");
5145
5149
  if (done) {
5146
5150
  if (eventDataBuffer.trim()) {
5147
5151
  const result = this._processSseEventData(
@@ -5228,7 +5232,7 @@ var A2AClient = class {
5228
5232
  };
5229
5233
 
5230
5234
  // src/agents/relationTools.ts
5231
- var logger14 = getLogger("relationships Tools");
5235
+ var logger13 = getLogger("relationships Tools");
5232
5236
  var generateTransferToolDescription = (config) => {
5233
5237
  return `Hand off the conversation to agent ${config.id}.
5234
5238
 
@@ -5252,7 +5256,7 @@ Delegate a specific task to agent ${config.id} when it seems like the agent can
5252
5256
  var createTransferToAgentTool = ({
5253
5257
  transferConfig,
5254
5258
  callingAgentId,
5255
- agent,
5259
+ subAgent,
5256
5260
  streamRequestId
5257
5261
  }) => {
5258
5262
  return tool({
@@ -5262,11 +5266,11 @@ var createTransferToAgentTool = ({
5262
5266
  const activeSpan = trace.getActiveSpan();
5263
5267
  if (activeSpan) {
5264
5268
  activeSpan.setAttributes({
5265
- "transfer.from_agent_id": callingAgentId,
5266
- "transfer.to_agent_id": transferConfig.id ?? "unknown"
5269
+ [SPAN_KEYS.TRANSFER_FROM_SUB_AGENT_ID]: callingAgentId,
5270
+ [SPAN_KEYS.TRANSFER_TO_SUB_AGENT_ID]: transferConfig.id ?? "unknown"
5267
5271
  });
5268
5272
  }
5269
- logger14.info(
5273
+ logger13.info(
5270
5274
  {
5271
5275
  transferTo: transferConfig.id ?? "unknown",
5272
5276
  fromAgent: callingAgentId
@@ -5275,8 +5279,8 @@ var createTransferToAgentTool = ({
5275
5279
  );
5276
5280
  if (streamRequestId) {
5277
5281
  graphSessionManager.recordEvent(streamRequestId, "transfer", callingAgentId, {
5278
- fromAgent: callingAgentId,
5279
- targetAgent: transferConfig.id ?? "unknown",
5282
+ fromSubAgent: callingAgentId,
5283
+ targetSubAgent: transferConfig.id ?? "unknown",
5280
5284
  reason: `Transfer to ${transferConfig.name || transferConfig.id}`
5281
5285
  });
5282
5286
  }
@@ -5298,7 +5302,7 @@ function createDelegateToAgentTool({
5298
5302
  contextId,
5299
5303
  metadata,
5300
5304
  sessionId,
5301
- agent,
5305
+ subAgent,
5302
5306
  credentialStoreRegistry
5303
5307
  }) {
5304
5308
  return tool({
@@ -5309,9 +5313,9 @@ function createDelegateToAgentTool({
5309
5313
  const activeSpan = trace.getActiveSpan();
5310
5314
  if (activeSpan) {
5311
5315
  activeSpan.setAttributes({
5312
- "delegation.from_agent_id": callingAgentId,
5313
- "delegation.to_agent_id": delegateConfig.config.id ?? "unknown",
5314
- "delegation.id": delegationId
5316
+ [SPAN_KEYS.DELEGATION_FROM_SUB_AGENT_ID]: callingAgentId,
5317
+ [SPAN_KEYS.DELEGATION_TO_SUB_AGENT_ID]: delegateConfig.config.id ?? "unknown",
5318
+ [SPAN_KEYS.DELEGATION_ID]: delegationId
5315
5319
  });
5316
5320
  }
5317
5321
  if (metadata.streamRequestId) {
@@ -5321,8 +5325,8 @@ function createDelegateToAgentTool({
5321
5325
  callingAgentId,
5322
5326
  {
5323
5327
  delegationId,
5324
- fromAgent: callingAgentId,
5325
- targetAgent: delegateConfig.config.id,
5328
+ fromSubAgent: callingAgentId,
5329
+ targetSubAgent: delegateConfig.config.id,
5326
5330
  taskDescription: input.message
5327
5331
  }
5328
5332
  );
@@ -5336,7 +5340,7 @@ function createDelegateToAgentTool({
5336
5340
  projectId,
5337
5341
  graphId
5338
5342
  },
5339
- agentId: delegateConfig.config.id
5343
+ subAgentId: delegateConfig.config.id
5340
5344
  });
5341
5345
  if (externalAgent && (externalAgent.credentialReferenceId || externalAgent.headers) && credentialStoreRegistry) {
5342
5346
  const contextResolver = new ContextResolver(
@@ -5415,7 +5419,7 @@ function createDelegateToAgentTool({
5415
5419
  ...isInternal ? { fromAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
5416
5420
  }
5417
5421
  };
5418
- logger14.info({ messageToSend }, "messageToSend");
5422
+ logger13.info({ messageToSend }, "messageToSend");
5419
5423
  await createMessage(dbClient_default)({
5420
5424
  id: nanoid(),
5421
5425
  tenantId,
@@ -5427,7 +5431,7 @@ function createDelegateToAgentTool({
5427
5431
  },
5428
5432
  visibility: isInternal ? "internal" : "external",
5429
5433
  messageType: "a2a-request",
5430
- fromAgentId: callingAgentId,
5434
+ fromSubAgentId: callingAgentId,
5431
5435
  ...isInternal ? { toAgentId: delegateConfig.config.id } : { toExternalAgentId: delegateConfig.config.id }
5432
5436
  });
5433
5437
  const response = await a2aClient.sendMessage({
@@ -5442,8 +5446,8 @@ function createDelegateToAgentTool({
5442
5446
  conversationId: contextId,
5443
5447
  messageType: "a2a-response",
5444
5448
  visibility: isInternal ? "internal" : "external",
5445
- toAgentId: callingAgentId,
5446
- ...isInternal ? { fromAgentId: delegateConfig.config.id } : { fromExternalAgentId: delegateConfig.config.id }
5449
+ toSubAgentId: callingAgentId,
5450
+ ...isInternal ? { fromSubAgentId: delegateConfig.config.id } : { fromExternalAgentId: delegateConfig.config.id }
5447
5451
  });
5448
5452
  if (sessionId && context?.toolCallId) {
5449
5453
  const toolResult = {
@@ -5462,8 +5466,8 @@ function createDelegateToAgentTool({
5462
5466
  callingAgentId,
5463
5467
  {
5464
5468
  delegationId,
5465
- fromAgent: delegateConfig.config.id,
5466
- targetAgent: callingAgentId,
5469
+ fromSubAgent: delegateConfig.config.id,
5470
+ targetSubAgent: callingAgentId,
5467
5471
  result: response.result
5468
5472
  }
5469
5473
  );
@@ -5477,7 +5481,7 @@ function createDelegateToAgentTool({
5477
5481
  }
5478
5482
 
5479
5483
  // src/agents/SystemPromptBuilder.ts
5480
- var logger15 = getLogger("SystemPromptBuilder");
5484
+ var logger14 = getLogger("SystemPromptBuilder");
5481
5485
  var SystemPromptBuilder = class {
5482
5486
  constructor(version, versionConfig) {
5483
5487
  this.version = version;
@@ -5493,12 +5497,12 @@ var SystemPromptBuilder = class {
5493
5497
  this.templates.set(name, content);
5494
5498
  }
5495
5499
  this.loaded = true;
5496
- logger15.debug(
5500
+ logger14.debug(
5497
5501
  { templateCount: this.templates.size, version: this.version },
5498
5502
  `Loaded ${this.templates.size} templates for version ${this.version}`
5499
5503
  );
5500
5504
  } catch (error) {
5501
- logger15.error({ error }, `Failed to load templates for version ${this.version}`);
5505
+ logger14.error({ error }, `Failed to load templates for version ${this.version}`);
5502
5506
  throw new Error(`Template loading failed: ${error}`);
5503
5507
  }
5504
5508
  }
@@ -6558,7 +6562,7 @@ function hasToolCallWithPrefix(prefix) {
6558
6562
  return false;
6559
6563
  };
6560
6564
  }
6561
- var logger17 = getLogger("Agent");
6565
+ var logger16 = getLogger("Agent");
6562
6566
  var CONSTANTS = {
6563
6567
  MAX_GENERATION_STEPS: 12,
6564
6568
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -6788,7 +6792,7 @@ var Agent = class {
6788
6792
  }
6789
6793
  getRelationTools(runtimeContext, sessionId) {
6790
6794
  const { transferRelations = [], delegateRelations = [] } = this.config;
6791
- const createToolName = (prefix, agentId) => `${prefix}_to_${agentId.toLowerCase().replace(/\s+/g, "_")}`;
6795
+ const createToolName = (prefix, subAgentId) => `${prefix}_to_${subAgentId.toLowerCase().replace(/\s+/g, "_")}`;
6792
6796
  return Object.fromEntries([
6793
6797
  ...transferRelations.map((agentConfig) => {
6794
6798
  const toolName = createToolName("transfer", agentConfig.id);
@@ -6799,7 +6803,7 @@ var Agent = class {
6799
6803
  createTransferToAgentTool({
6800
6804
  transferConfig: agentConfig,
6801
6805
  callingAgentId: this.config.id,
6802
- agent: this,
6806
+ subAgent: this,
6803
6807
  streamRequestId: runtimeContext?.metadata?.streamRequestId
6804
6808
  }),
6805
6809
  runtimeContext?.metadata?.streamRequestId,
@@ -6828,7 +6832,7 @@ var Agent = class {
6828
6832
  apiKey: runtimeContext?.metadata?.apiKey
6829
6833
  },
6830
6834
  sessionId,
6831
- agent: this,
6835
+ subAgent: this,
6832
6836
  credentialStoreRegistry: this.credentialStoreRegistry
6833
6837
  }),
6834
6838
  runtimeContext?.metadata?.streamRequestId,
@@ -6862,14 +6866,14 @@ var Agent = class {
6862
6866
  for (const toolSet of tools) {
6863
6867
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
6864
6868
  if (!isValidTool(originalTool)) {
6865
- logger17.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6869
+ logger16.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6866
6870
  continue;
6867
6871
  }
6868
6872
  const sessionWrappedTool = tool({
6869
6873
  description: originalTool.description,
6870
6874
  inputSchema: originalTool.inputSchema,
6871
6875
  execute: async (args, { toolCallId }) => {
6872
- logger17.debug({ toolName, toolCallId }, "MCP Tool Called");
6876
+ logger16.debug({ toolName, toolCallId }, "MCP Tool Called");
6873
6877
  try {
6874
6878
  const rawResult = await originalTool.execute(args, { toolCallId });
6875
6879
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -6883,7 +6887,7 @@ var Agent = class {
6883
6887
  });
6884
6888
  return { result: enhancedResult, toolCallId };
6885
6889
  } catch (error) {
6886
- logger17.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6890
+ logger16.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6887
6891
  throw error;
6888
6892
  }
6889
6893
  }
@@ -6928,7 +6932,7 @@ var Agent = class {
6928
6932
  tenantId: this.config.tenantId,
6929
6933
  projectId: this.config.projectId,
6930
6934
  graphId: this.config.graphId,
6931
- agentId: this.config.id
6935
+ subAgentId: this.config.id
6932
6936
  }
6933
6937
  });
6934
6938
  const agentToolRelationHeaders = toolsForAgent.data.find((t) => t.toolId === tool3.id)?.headers || void 0;
@@ -6984,7 +6988,7 @@ var Agent = class {
6984
6988
  headers: agentToolRelationHeaders
6985
6989
  };
6986
6990
  }
6987
- logger17.info(
6991
+ logger16.info(
6988
6992
  {
6989
6993
  toolName: tool3.name,
6990
6994
  credentialReferenceId,
@@ -7009,10 +7013,10 @@ var Agent = class {
7009
7013
  this.mcpClientCache.set(cacheKey, client);
7010
7014
  } catch (error) {
7011
7015
  this.mcpConnectionLocks.delete(cacheKey);
7012
- logger17.error(
7016
+ logger16.error(
7013
7017
  {
7014
7018
  toolName: tool3.name,
7015
- agentId: this.config.id,
7019
+ subAgentId: this.config.id,
7016
7020
  cacheKey,
7017
7021
  error: error instanceof Error ? error.message : String(error)
7018
7022
  },
@@ -7033,10 +7037,10 @@ var Agent = class {
7033
7037
  await client.connect();
7034
7038
  return client;
7035
7039
  } catch (error) {
7036
- logger17.error(
7040
+ logger16.error(
7037
7041
  {
7038
7042
  toolName: tool3.name,
7039
- agentId: this.config.id,
7043
+ subAgentId: this.config.id,
7040
7044
  error: error instanceof Error ? error.message : String(error)
7041
7045
  },
7042
7046
  "Agent failed to connect to MCP server"
@@ -7052,7 +7056,7 @@ var Agent = class {
7052
7056
  tenantId: this.config.tenantId || "default",
7053
7057
  projectId: this.config.projectId || "default",
7054
7058
  graphId: this.config.graphId,
7055
- agentId: this.config.id
7059
+ subAgentId: this.config.id
7056
7060
  }
7057
7061
  });
7058
7062
  const toolsData = toolsForAgent.data || [];
@@ -7066,7 +7070,7 @@ var Agent = class {
7066
7070
  if (toolDef.tool.config?.type === "function") {
7067
7071
  const functionId = toolDef.tool.functionId;
7068
7072
  if (!functionId) {
7069
- logger17.warn({ toolId: toolDef.tool.id }, "Function tool missing functionId reference");
7073
+ logger16.warn({ toolId: toolDef.tool.id }, "Function tool missing functionId reference");
7070
7074
  continue;
7071
7075
  }
7072
7076
  const functionData = await getFunction(dbClient_default)({
@@ -7077,7 +7081,7 @@ var Agent = class {
7077
7081
  }
7078
7082
  });
7079
7083
  if (!functionData) {
7080
- logger17.warn(
7084
+ logger16.warn(
7081
7085
  { functionId, toolId: toolDef.tool.id },
7082
7086
  "Function not found in functions table"
7083
7087
  );
@@ -7088,7 +7092,7 @@ var Agent = class {
7088
7092
  description: toolDef.tool.description || toolDef.tool.name,
7089
7093
  inputSchema: zodSchema,
7090
7094
  execute: async (args, { toolCallId }) => {
7091
- logger17.debug(
7095
+ logger16.debug(
7092
7096
  { toolName: toolDef.tool.name, toolCallId, args },
7093
7097
  "Function Tool Called"
7094
7098
  );
@@ -7108,7 +7112,7 @@ var Agent = class {
7108
7112
  });
7109
7113
  return { result, toolCallId };
7110
7114
  } catch (error) {
7111
- logger17.error(
7115
+ logger16.error(
7112
7116
  { toolName: toolDef.tool.name, toolCallId, error },
7113
7117
  "Function tool execution failed"
7114
7118
  );
@@ -7125,7 +7129,7 @@ var Agent = class {
7125
7129
  }
7126
7130
  }
7127
7131
  } catch (error) {
7128
- logger17.error({ error }, "Failed to load function tools from database");
7132
+ logger16.error({ error }, "Failed to load function tools from database");
7129
7133
  }
7130
7134
  return functionTools;
7131
7135
  }
@@ -7135,7 +7139,7 @@ var Agent = class {
7135
7139
  async getResolvedContext(conversationId, headers) {
7136
7140
  try {
7137
7141
  if (!this.config.contextConfigId) {
7138
- logger17.debug({ graphId: this.config.graphId }, "No context config found for graph");
7142
+ logger16.debug({ graphId: this.config.graphId }, "No context config found for graph");
7139
7143
  return null;
7140
7144
  }
7141
7145
  const contextConfig = await getContextConfigById(dbClient_default)({
@@ -7147,7 +7151,7 @@ var Agent = class {
7147
7151
  id: this.config.contextConfigId
7148
7152
  });
7149
7153
  if (!contextConfig) {
7150
- logger17.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7154
+ logger16.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7151
7155
  return null;
7152
7156
  }
7153
7157
  if (!this.contextResolver) {
@@ -7164,7 +7168,7 @@ var Agent = class {
7164
7168
  $now: (/* @__PURE__ */ new Date()).toISOString(),
7165
7169
  $env: process.env
7166
7170
  };
7167
- logger17.debug(
7171
+ logger16.debug(
7168
7172
  {
7169
7173
  conversationId,
7170
7174
  contextConfigId: contextConfig.id,
@@ -7178,7 +7182,7 @@ var Agent = class {
7178
7182
  );
7179
7183
  return contextWithBuiltins;
7180
7184
  } catch (error) {
7181
- logger17.error(
7185
+ logger16.error(
7182
7186
  {
7183
7187
  conversationId,
7184
7188
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7202,7 +7206,7 @@ var Agent = class {
7202
7206
  });
7203
7207
  return graphDefinition?.graphPrompt || void 0;
7204
7208
  } catch (error) {
7205
- logger17.warn(
7209
+ logger16.warn(
7206
7210
  {
7207
7211
  graphId: this.config.graphId,
7208
7212
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7227,11 +7231,11 @@ var Agent = class {
7227
7231
  if (!graphDefinition) {
7228
7232
  return false;
7229
7233
  }
7230
- return Object.values(graphDefinition.agents).some(
7231
- (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
7234
+ return Object.values(graphDefinition.subAgents).some(
7235
+ (subAgent) => "artifactComponents" in subAgent && subAgent.artifactComponents && subAgent.artifactComponents.length > 0
7232
7236
  );
7233
7237
  } catch (error) {
7234
- logger17.warn(
7238
+ logger16.warn(
7235
7239
  {
7236
7240
  graphId: this.config.graphId,
7237
7241
  tenantId: this.config.tenantId,
@@ -7260,7 +7264,7 @@ var Agent = class {
7260
7264
  preserveUnresolved: false
7261
7265
  });
7262
7266
  } catch (error) {
7263
- logger17.error(
7267
+ logger16.error(
7264
7268
  {
7265
7269
  conversationId,
7266
7270
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7307,7 +7311,7 @@ var Agent = class {
7307
7311
  preserveUnresolved: false
7308
7312
  });
7309
7313
  } catch (error) {
7310
- logger17.error(
7314
+ logger16.error(
7311
7315
  {
7312
7316
  conversationId,
7313
7317
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7322,7 +7326,7 @@ var Agent = class {
7322
7326
  const functionTools = await this.getFunctionTools(streamRequestId || "");
7323
7327
  const relationTools = this.getRelationTools(runtimeContext);
7324
7328
  const allTools = { ...mcpTools, ...functionTools, ...relationTools };
7325
- logger17.info(
7329
+ logger16.info(
7326
7330
  {
7327
7331
  mcpTools: Object.keys(mcpTools),
7328
7332
  functionTools: Object.keys(functionTools),
@@ -7343,7 +7347,7 @@ var Agent = class {
7343
7347
  inputSchema: tool3.inputSchema || tool3.parameters || {},
7344
7348
  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."
7345
7349
  }));
7346
- const { getConversationScopedArtifacts } = await import('./conversations-6HJ4FX5F.js');
7350
+ const { getConversationScopedArtifacts } = await import('./conversations-JSORLLWS.js');
7347
7351
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
7348
7352
  const referenceArtifacts = await getConversationScopedArtifacts({
7349
7353
  tenantId: this.config.tenantId,
@@ -7361,7 +7365,7 @@ var Agent = class {
7361
7365
  preserveUnresolved: false
7362
7366
  });
7363
7367
  } catch (error) {
7364
- logger17.error(
7368
+ logger16.error(
7365
7369
  {
7366
7370
  conversationId,
7367
7371
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7394,7 +7398,7 @@ var Agent = class {
7394
7398
  toolCallId: z.string().describe("The tool call ID associated with this artifact.")
7395
7399
  }),
7396
7400
  execute: async ({ artifactId, toolCallId }) => {
7397
- logger17.info({ artifactId, toolCallId }, "get_artifact_full executed");
7401
+ logger16.info({ artifactId, toolCallId }, "get_artifact_full executed");
7398
7402
  const streamRequestId = this.getStreamRequestId();
7399
7403
  const artifactService = graphSessionManager.getArtifactService(streamRequestId);
7400
7404
  if (!artifactService) {
@@ -7428,7 +7432,7 @@ var Agent = class {
7428
7432
  });
7429
7433
  }
7430
7434
  // Provide a default tool set that is always available to the agent.
7431
- async getDefaultTools(_sessionId, streamRequestId) {
7435
+ async getDefaultTools(streamRequestId) {
7432
7436
  const defaultTools = {};
7433
7437
  if (await this.graphHasArtifactComponents()) {
7434
7438
  defaultTools.get_reference_artifact = this.getArtifactTools();
@@ -7654,7 +7658,7 @@ var Agent = class {
7654
7658
  };
7655
7659
  return enhanced;
7656
7660
  } catch (error) {
7657
- logger17.warn({ error }, "Failed to enhance tool result with structure hints");
7661
+ logger16.warn({ error }, "Failed to enhance tool result with structure hints");
7658
7662
  return result;
7659
7663
  }
7660
7664
  }
@@ -7669,7 +7673,7 @@ var Agent = class {
7669
7673
  }
7670
7674
  });
7671
7675
  } catch (error) {
7672
- logger17.error(
7676
+ logger16.error(
7673
7677
  { error, graphId: this.config.graphId },
7674
7678
  "Failed to check graph artifact components"
7675
7679
  );
@@ -7714,7 +7718,7 @@ var Agent = class {
7714
7718
  // Thinking prompt without data components
7715
7719
  this.getFunctionTools(sessionId, streamRequestId),
7716
7720
  Promise.resolve(this.getRelationTools(runtimeContext, sessionId)),
7717
- this.getDefaultTools(sessionId, streamRequestId)
7721
+ this.getDefaultTools(streamRequestId)
7718
7722
  ]);
7719
7723
  childSpan.setStatus({ code: SpanStatusCode.OK });
7720
7724
  return result;
@@ -7754,7 +7758,7 @@ var Agent = class {
7754
7758
  currentMessage: userMessage,
7755
7759
  options: historyConfig,
7756
7760
  filters: {
7757
- agentId: this.config.id,
7761
+ subAgentId: this.config.id,
7758
7762
  taskId
7759
7763
  }
7760
7764
  });
@@ -7770,7 +7774,7 @@ var Agent = class {
7770
7774
  const configuredTimeout = modelSettings.maxDuration ? Math.min(modelSettings.maxDuration * 1e3, MAX_ALLOWED_TIMEOUT_MS) : shouldStreamPhase1 ? CONSTANTS.PHASE_1_TIMEOUT_MS : CONSTANTS.NON_STREAMING_PHASE_1_TIMEOUT_MS;
7771
7775
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
7772
7776
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
7773
- logger17.warn(
7777
+ logger16.warn(
7774
7778
  {
7775
7779
  requestedTimeout: modelSettings.maxDuration * 1e3,
7776
7780
  appliedTimeout: timeoutMs,
@@ -7812,7 +7816,7 @@ var Agent = class {
7812
7816
  }
7813
7817
  );
7814
7818
  } catch (error) {
7815
- logger17.debug({ error }, "Failed to track agent reasoning");
7819
+ logger16.debug({ error }, "Failed to track agent reasoning");
7816
7820
  }
7817
7821
  }
7818
7822
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7839,7 +7843,7 @@ var Agent = class {
7839
7843
  projectId: session?.projectId,
7840
7844
  artifactComponents: this.artifactComponents,
7841
7845
  streamRequestId: this.getStreamRequestId(),
7842
- agentId: this.config.id
7846
+ subAgentId: this.config.id
7843
7847
  };
7844
7848
  const parser = new IncrementalStreamParser(
7845
7849
  streamHelper,
@@ -7916,7 +7920,7 @@ var Agent = class {
7916
7920
  }
7917
7921
  );
7918
7922
  } catch (error) {
7919
- logger17.debug({ error }, "Failed to track agent reasoning");
7923
+ logger16.debug({ error }, "Failed to track agent reasoning");
7920
7924
  }
7921
7925
  }
7922
7926
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -8088,7 +8092,7 @@ ${output}${structureHintsFormatted}`;
8088
8092
  projectId: session?.projectId,
8089
8093
  artifactComponents: this.artifactComponents,
8090
8094
  streamRequestId: this.getStreamRequestId(),
8091
- agentId: this.config.id
8095
+ subAgentId: this.config.id
8092
8096
  };
8093
8097
  const parser = new IncrementalStreamParser(
8094
8098
  streamHelper,
@@ -8171,7 +8175,7 @@ ${output}${structureHintsFormatted}`;
8171
8175
  contextId,
8172
8176
  artifactComponents: this.artifactComponents,
8173
8177
  streamRequestId: this.getStreamRequestId(),
8174
- agentId: this.config.id
8178
+ subAgentId: this.config.id
8175
8179
  });
8176
8180
  if (response.object) {
8177
8181
  formattedContent = await responseFormatter.formatObjectResponse(
@@ -8208,7 +8212,7 @@ ${output}${structureHintsFormatted}`;
8208
8212
  };
8209
8213
 
8210
8214
  // src/agents/generateTaskHandler.ts
8211
- var logger18 = getLogger("generateTaskHandler");
8215
+ var logger17 = getLogger("generateTaskHandler");
8212
8216
  var createTaskHandler = (config, credentialStoreRegistry) => {
8213
8217
  return async (task) => {
8214
8218
  try {
@@ -8234,14 +8238,14 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8234
8238
  projectId: config.projectId,
8235
8239
  graphId: config.graphId
8236
8240
  },
8237
- agentId: config.agentId
8241
+ subAgentId: config.subAgentId
8238
8242
  }),
8239
8243
  getToolsForAgent(dbClient_default)({
8240
8244
  scopes: {
8241
8245
  tenantId: config.tenantId,
8242
8246
  projectId: config.projectId,
8243
8247
  graphId: config.graphId,
8244
- agentId: config.agentId
8248
+ subAgentId: config.subAgentId
8245
8249
  }
8246
8250
  }),
8247
8251
  getDataComponentsForAgent(dbClient_default)({
@@ -8249,7 +8253,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8249
8253
  tenantId: config.tenantId,
8250
8254
  projectId: config.projectId,
8251
8255
  graphId: config.graphId,
8252
- agentId: config.agentId
8256
+ subAgentId: config.subAgentId
8253
8257
  }
8254
8258
  }),
8255
8259
  getArtifactComponentsForAgent(dbClient_default)({
@@ -8257,21 +8261,21 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8257
8261
  tenantId: config.tenantId,
8258
8262
  projectId: config.projectId,
8259
8263
  graphId: config.graphId,
8260
- agentId: config.agentId
8264
+ subAgentId: config.subAgentId
8261
8265
  }
8262
8266
  })
8263
8267
  ]);
8264
- logger18.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
8268
+ logger17.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
8265
8269
  const enhancedInternalRelations = await Promise.all(
8266
8270
  internalRelations.map(async (relation) => {
8267
8271
  try {
8268
- const relatedAgent = await getAgentById(dbClient_default)({
8272
+ const relatedAgent = await getSubAgentById(dbClient_default)({
8269
8273
  scopes: {
8270
8274
  tenantId: config.tenantId,
8271
8275
  projectId: config.projectId,
8272
8276
  graphId: config.graphId
8273
8277
  },
8274
- agentId: relation.id
8278
+ subAgentId: relation.id
8275
8279
  });
8276
8280
  if (relatedAgent) {
8277
8281
  const relatedAgentRelations = await getRelatedAgentsForGraph(dbClient_default)({
@@ -8280,7 +8284,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8280
8284
  projectId: config.projectId,
8281
8285
  graphId: config.graphId
8282
8286
  },
8283
- agentId: relation.id
8287
+ subAgentId: relation.id
8284
8288
  });
8285
8289
  const enhancedDescription = generateDescriptionWithTransfers(
8286
8290
  relation.description || "",
@@ -8290,7 +8294,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8290
8294
  return { ...relation, description: enhancedDescription };
8291
8295
  }
8292
8296
  } catch (error) {
8293
- logger18.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
8297
+ logger17.warn({ subAgentId: relation.id, error }, "Failed to enhance agent description");
8294
8298
  }
8295
8299
  return relation;
8296
8300
  })
@@ -8305,7 +8309,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8305
8309
  ) ?? [];
8306
8310
  const agent = new Agent(
8307
8311
  {
8308
- id: config.agentId,
8312
+ id: config.subAgentId,
8309
8313
  tenantId: config.tenantId,
8310
8314
  projectId: config.projectId,
8311
8315
  graphId: config.graphId,
@@ -8316,7 +8320,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8316
8320
  agentPrompt,
8317
8321
  models: models || void 0,
8318
8322
  stopWhen: stopWhen || void 0,
8319
- agentRelations: enhancedInternalRelations.map((relation) => ({
8323
+ subAgentRelations: enhancedInternalRelations.map((relation) => ({
8320
8324
  id: relation.id,
8321
8325
  tenantId: config.tenantId,
8322
8326
  projectId: config.projectId,
@@ -8327,7 +8331,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8327
8331
  description: relation.description,
8328
8332
  agentPrompt: "",
8329
8333
  delegateRelations: [],
8330
- agentRelations: [],
8334
+ subAgentRelations: [],
8331
8335
  transferRelations: []
8332
8336
  })),
8333
8337
  transferRelations: enhancedInternalRelations.filter((relation) => relation.relationType === "transfer").map((relation) => ({
@@ -8341,7 +8345,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8341
8345
  description: relation.description,
8342
8346
  agentPrompt: "",
8343
8347
  delegateRelations: [],
8344
- agentRelations: [],
8348
+ subAgentRelations: [],
8345
8349
  transferRelations: []
8346
8350
  })),
8347
8351
  delegateRelations: [
@@ -8359,7 +8363,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8359
8363
  description: relation.description,
8360
8364
  agentPrompt: "",
8361
8365
  delegateRelations: [],
8362
- agentRelations: [],
8366
+ subAgentRelations: [],
8363
8367
  transferRelations: []
8364
8368
  }
8365
8369
  })),
@@ -8394,11 +8398,11 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8394
8398
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
8395
8399
  if (taskIdMatch) {
8396
8400
  contextId = taskIdMatch[1];
8397
- logger18.info(
8401
+ logger17.info(
8398
8402
  {
8399
8403
  taskId: task.id,
8400
8404
  extractedContextId: contextId,
8401
- agentId: config.agentId
8405
+ subAgentId: config.subAgentId
8402
8406
  },
8403
8407
  "Extracted contextId from task ID for delegation"
8404
8408
  );
@@ -8410,8 +8414,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8410
8414
  const isDelegation = task.context?.metadata?.isDelegation === true;
8411
8415
  agent.setDelegationStatus(isDelegation);
8412
8416
  if (isDelegation) {
8413
- logger18.info(
8414
- { agentId: config.agentId, taskId: task.id },
8417
+ logger17.info(
8418
+ { subAgentId: config.subAgentId, taskId: task.id },
8415
8419
  "Delegated agent - streaming disabled"
8416
8420
  );
8417
8421
  if (streamRequestId && config.tenantId && config.projectId) {
@@ -8508,13 +8512,13 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8508
8512
  };
8509
8513
  };
8510
8514
  var createTaskHandlerConfig = async (params) => {
8511
- const agent = await getAgentById(dbClient_default)({
8515
+ const agent = await getSubAgentById(dbClient_default)({
8512
8516
  scopes: {
8513
8517
  tenantId: params.tenantId,
8514
8518
  projectId: params.projectId,
8515
8519
  graphId: params.graphId
8516
8520
  },
8517
- agentId: params.agentId
8521
+ subAgentId: params.subAgentId
8518
8522
  });
8519
8523
  const agentGraph = await getAgentGraphById(dbClient_default)({
8520
8524
  scopes: {
@@ -8524,7 +8528,7 @@ var createTaskHandlerConfig = async (params) => {
8524
8528
  }
8525
8529
  });
8526
8530
  if (!agent) {
8527
- throw new Error(`Agent not found: ${params.agentId}`);
8531
+ throw new Error(`Agent not found: ${params.subAgentId}`);
8528
8532
  }
8529
8533
  const effectiveModels = await resolveModelConfig(params.graphId, agent);
8530
8534
  const effectiveConversationHistoryConfig = agent.conversationHistoryConfig || { mode: "full" };
@@ -8532,7 +8536,7 @@ var createTaskHandlerConfig = async (params) => {
8532
8536
  tenantId: params.tenantId,
8533
8537
  projectId: params.projectId,
8534
8538
  graphId: params.graphId,
8535
- agentId: params.agentId,
8539
+ subAgentId: params.subAgentId,
8536
8540
  agentSchema: {
8537
8541
  id: agent.id,
8538
8542
  name: agent.name,
@@ -8560,25 +8564,27 @@ async function hydrateGraph({
8560
8564
  apiKey
8561
8565
  }) {
8562
8566
  try {
8563
- if (!dbGraph.defaultAgentId) {
8567
+ if (!dbGraph.defaultSubAgentId) {
8564
8568
  throw new Error(`Graph ${dbGraph.id} does not have a default agent configured`);
8565
8569
  }
8566
- const defaultAgent = await getAgentById(dbClient_default)({
8570
+ const defaultSubAgent = await getSubAgentById(dbClient_default)({
8567
8571
  scopes: {
8568
8572
  tenantId: dbGraph.tenantId,
8569
8573
  projectId: dbGraph.projectId,
8570
8574
  graphId: dbGraph.id
8571
8575
  },
8572
- agentId: dbGraph.defaultAgentId
8576
+ subAgentId: dbGraph.defaultSubAgentId
8573
8577
  });
8574
- if (!defaultAgent) {
8575
- throw new Error(`Default agent ${dbGraph.defaultAgentId} not found for graph ${dbGraph.id}`);
8578
+ if (!defaultSubAgent) {
8579
+ throw new Error(
8580
+ `Default agent ${dbGraph.defaultSubAgentId} not found for graph ${dbGraph.id}`
8581
+ );
8576
8582
  }
8577
8583
  const taskHandlerConfig = await createTaskHandlerConfig({
8578
8584
  tenantId: dbGraph.tenantId,
8579
8585
  projectId: dbGraph.projectId,
8580
8586
  graphId: dbGraph.id,
8581
- agentId: dbGraph.defaultAgentId,
8587
+ subAgentId: dbGraph.defaultSubAgentId,
8582
8588
  baseUrl,
8583
8589
  apiKey
8584
8590
  });
@@ -8607,7 +8613,7 @@ async function hydrateGraph({
8607
8613
  }
8608
8614
  };
8609
8615
  return {
8610
- agentId: dbGraph.id,
8616
+ subAgentId: dbGraph.id,
8611
8617
  // Use graph ID as agent ID for A2A purposes
8612
8618
  tenantId: dbGraph.tenantId,
8613
8619
  projectId: dbGraph.projectId,
@@ -8632,7 +8638,7 @@ async function getRegisteredGraph(executionContext) {
8632
8638
 
8633
8639
  // src/routes/agents.ts
8634
8640
  var app = new OpenAPIHono();
8635
- var logger19 = getLogger("agents");
8641
+ var logger18 = getLogger("agents");
8636
8642
  app.openapi(
8637
8643
  createRoute({
8638
8644
  method: "get",
@@ -8670,7 +8676,7 @@ app.openapi(
8670
8676
  tracestate: c.req.header("tracestate"),
8671
8677
  baggage: c.req.header("baggage")
8672
8678
  };
8673
- logger19.info(
8679
+ logger18.info(
8674
8680
  {
8675
8681
  otelHeaders,
8676
8682
  path: c.req.path,
@@ -8679,22 +8685,22 @@ app.openapi(
8679
8685
  "OpenTelemetry headers: well-known agent.json"
8680
8686
  );
8681
8687
  const executionContext = getRequestExecutionContext(c);
8682
- const { tenantId, projectId, graphId, agentId } = executionContext;
8688
+ const { tenantId, projectId, graphId, subAgentId } = executionContext;
8683
8689
  console.dir("executionContext", executionContext);
8684
- if (agentId) {
8685
- logger19.info(
8690
+ if (subAgentId) {
8691
+ logger18.info(
8686
8692
  {
8687
8693
  message: "getRegisteredAgent (agent-level)",
8688
8694
  tenantId,
8689
8695
  projectId,
8690
8696
  graphId,
8691
- agentId
8697
+ subAgentId
8692
8698
  },
8693
8699
  "agent-level well-known agent.json"
8694
8700
  );
8695
8701
  const credentialStores = c.get("credentialStores");
8696
8702
  const agent = await getRegisteredAgent(executionContext, credentialStores);
8697
- logger19.info({ agent }, "agent registered: well-known agent.json");
8703
+ logger18.info({ agent }, "agent registered: well-known agent.json");
8698
8704
  if (!agent) {
8699
8705
  throw createApiError({
8700
8706
  code: "not_found",
@@ -8703,7 +8709,7 @@ app.openapi(
8703
8709
  }
8704
8710
  return c.json(agent.agentCard);
8705
8711
  } else {
8706
- logger19.info(
8712
+ logger18.info(
8707
8713
  {
8708
8714
  message: "getRegisteredGraph (graph-level)",
8709
8715
  tenantId,
@@ -8729,7 +8735,7 @@ app.post("/a2a", async (c) => {
8729
8735
  tracestate: c.req.header("tracestate"),
8730
8736
  baggage: c.req.header("baggage")
8731
8737
  };
8732
- logger19.info(
8738
+ logger18.info(
8733
8739
  {
8734
8740
  otelHeaders,
8735
8741
  path: c.req.path,
@@ -8738,15 +8744,15 @@ app.post("/a2a", async (c) => {
8738
8744
  "OpenTelemetry headers: a2a"
8739
8745
  );
8740
8746
  const executionContext = getRequestExecutionContext(c);
8741
- const { tenantId, projectId, graphId, agentId } = executionContext;
8742
- if (agentId) {
8743
- logger19.info(
8747
+ const { tenantId, projectId, graphId, subAgentId } = executionContext;
8748
+ if (subAgentId) {
8749
+ logger18.info(
8744
8750
  {
8745
8751
  message: "a2a (agent-level)",
8746
8752
  tenantId,
8747
8753
  projectId,
8748
8754
  graphId,
8749
- agentId
8755
+ subAgentId
8750
8756
  },
8751
8757
  "agent-level a2a endpoint"
8752
8758
  );
@@ -8764,7 +8770,7 @@ app.post("/a2a", async (c) => {
8764
8770
  }
8765
8771
  return a2aHandler(c, agent);
8766
8772
  } else {
8767
- logger19.info(
8773
+ logger18.info(
8768
8774
  {
8769
8775
  message: "a2a (graph-level)",
8770
8776
  tenantId,
@@ -8773,7 +8779,7 @@ app.post("/a2a", async (c) => {
8773
8779
  },
8774
8780
  "graph-level a2a endpoint"
8775
8781
  );
8776
- const graph = await getAgentGraphWithDefaultAgent(dbClient_default)({
8782
+ const graph = await getAgentGraphWithDefaultSubAgent(dbClient_default)({
8777
8783
  scopes: { tenantId, projectId, graphId }
8778
8784
  });
8779
8785
  if (!graph) {
@@ -8786,7 +8792,7 @@ app.post("/a2a", async (c) => {
8786
8792
  404
8787
8793
  );
8788
8794
  }
8789
- if (!graph.defaultAgentId) {
8795
+ if (!graph.defaultSubAgentId) {
8790
8796
  return c.json(
8791
8797
  {
8792
8798
  jsonrpc: "2.0",
@@ -8796,10 +8802,10 @@ app.post("/a2a", async (c) => {
8796
8802
  400
8797
8803
  );
8798
8804
  }
8799
- executionContext.agentId = graph.defaultAgentId;
8805
+ executionContext.subAgentId = graph.defaultSubAgentId;
8800
8806
  const credentialStores = c.get("credentialStores");
8801
- const defaultAgent = await getRegisteredAgent(executionContext, credentialStores);
8802
- if (!defaultAgent) {
8807
+ const defaultSubAgent = await getRegisteredAgent(executionContext, credentialStores);
8808
+ if (!defaultSubAgent) {
8803
8809
  return c.json(
8804
8810
  {
8805
8811
  jsonrpc: "2.0",
@@ -8809,24 +8815,24 @@ app.post("/a2a", async (c) => {
8809
8815
  404
8810
8816
  );
8811
8817
  }
8812
- return a2aHandler(c, defaultAgent);
8818
+ return a2aHandler(c, defaultSubAgent);
8813
8819
  }
8814
8820
  });
8815
8821
  var agents_default = app;
8816
- var logger20 = getLogger("Transfer");
8822
+ var logger19 = getLogger("Transfer");
8817
8823
  async function executeTransfer({
8818
8824
  tenantId,
8819
8825
  threadId,
8820
8826
  projectId,
8821
- targetAgentId
8827
+ targetSubAgentId
8822
8828
  }) {
8823
- logger20.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8829
+ logger19.info({ targetAgent: targetSubAgentId }, "Executing transfer to agent");
8824
8830
  await setActiveAgentForThread(dbClient_default)({
8825
8831
  scopes: { tenantId, projectId },
8826
8832
  threadId,
8827
- agentId: targetAgentId
8833
+ subAgentId: targetSubAgentId
8828
8834
  });
8829
- return { success: true, targetAgentId };
8835
+ return { success: true, targetSubAgentId };
8830
8836
  }
8831
8837
  function isTransferResponse(result) {
8832
8838
  return result?.artifacts.some(
@@ -9402,7 +9408,7 @@ function createMCPStreamHelper() {
9402
9408
  }
9403
9409
 
9404
9410
  // src/handlers/executionHandler.ts
9405
- var logger21 = getLogger("ExecutionHandler");
9411
+ var logger20 = getLogger("ExecutionHandler");
9406
9412
  var ExecutionHandler = class {
9407
9413
  constructor() {
9408
9414
  // Hardcoded error limit - separate from configurable stopWhen
@@ -9438,7 +9444,7 @@ var ExecutionHandler = class {
9438
9444
  if (emitOperations) {
9439
9445
  graphSessionManager.enableEmitOperations(requestId2);
9440
9446
  }
9441
- logger21.info(
9447
+ logger20.info(
9442
9448
  { sessionId: requestId2, graphId, conversationId, emitOperations },
9443
9449
  "Created GraphSession for message execution"
9444
9450
  );
@@ -9453,7 +9459,7 @@ var ExecutionHandler = class {
9453
9459
  );
9454
9460
  }
9455
9461
  } catch (error) {
9456
- logger21.error(
9462
+ logger20.error(
9457
9463
  {
9458
9464
  error: error instanceof Error ? error.message : "Unknown error",
9459
9465
  stack: error instanceof Error ? error.stack : void 0
@@ -9469,7 +9475,7 @@ var ExecutionHandler = class {
9469
9475
  try {
9470
9476
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
9471
9477
  const taskId = `task_${conversationId}-${requestId2}`;
9472
- logger21.info(
9478
+ logger20.info(
9473
9479
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
9474
9480
  "Attempting to create or reuse existing task"
9475
9481
  );
@@ -9479,7 +9485,7 @@ var ExecutionHandler = class {
9479
9485
  tenantId,
9480
9486
  projectId,
9481
9487
  graphId,
9482
- agentId: currentAgentId,
9488
+ subAgentId: currentAgentId,
9483
9489
  contextId: conversationId,
9484
9490
  status: "pending",
9485
9491
  metadata: {
@@ -9493,7 +9499,7 @@ var ExecutionHandler = class {
9493
9499
  agent_id: currentAgentId
9494
9500
  }
9495
9501
  });
9496
- logger21.info(
9502
+ logger20.info(
9497
9503
  {
9498
9504
  taskId,
9499
9505
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -9502,27 +9508,27 @@ var ExecutionHandler = class {
9502
9508
  );
9503
9509
  } catch (error) {
9504
9510
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
9505
- logger21.info(
9511
+ logger20.info(
9506
9512
  { taskId, error: error.message },
9507
9513
  "Task already exists, fetching existing task"
9508
9514
  );
9509
9515
  const existingTask = await getTask(dbClient_default)({ id: taskId });
9510
9516
  if (existingTask) {
9511
9517
  task = existingTask;
9512
- logger21.info(
9518
+ logger20.info(
9513
9519
  { taskId, existingTask },
9514
9520
  "Successfully reused existing task from race condition"
9515
9521
  );
9516
9522
  } else {
9517
- logger21.error({ taskId, error }, "Task constraint failed but task not found");
9523
+ logger20.error({ taskId, error }, "Task constraint failed but task not found");
9518
9524
  throw error;
9519
9525
  }
9520
9526
  } else {
9521
- logger21.error({ taskId, error }, "Failed to create task due to non-constraint error");
9527
+ logger20.error({ taskId, error }, "Failed to create task due to non-constraint error");
9522
9528
  throw error;
9523
9529
  }
9524
9530
  }
9525
- logger21.debug(
9531
+ logger20.debug(
9526
9532
  {
9527
9533
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9528
9534
  executionType: "create_initial_task",
@@ -9540,7 +9546,7 @@ var ExecutionHandler = class {
9540
9546
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
9541
9547
  while (iterations < maxTransfers) {
9542
9548
  iterations++;
9543
- logger21.info(
9549
+ logger20.info(
9544
9550
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
9545
9551
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
9546
9552
  );
@@ -9548,10 +9554,10 @@ var ExecutionHandler = class {
9548
9554
  scopes: { tenantId, projectId },
9549
9555
  conversationId
9550
9556
  });
9551
- logger21.info({ activeAgent }, "activeAgent");
9552
- if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
9553
- currentAgentId = activeAgent.activeAgentId;
9554
- logger21.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
9557
+ logger20.info({ activeAgent }, "activeAgent");
9558
+ if (activeAgent && activeAgent.activeSubAgentId !== currentAgentId) {
9559
+ currentAgentId = activeAgent.activeSubAgentId;
9560
+ logger20.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
9555
9561
  }
9556
9562
  const agentBaseUrl = `${baseUrl}/agents`;
9557
9563
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -9592,13 +9598,13 @@ var ExecutionHandler = class {
9592
9598
  });
9593
9599
  if (!messageResponse?.result) {
9594
9600
  errorCount++;
9595
- logger21.error(
9601
+ logger20.error(
9596
9602
  { currentAgentId, iterations, errorCount },
9597
9603
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9598
9604
  );
9599
9605
  if (errorCount >= this.MAX_ERRORS) {
9600
9606
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9601
- logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9607
+ logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9602
9608
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9603
9609
  if (task) {
9604
9610
  await updateTask(dbClient_default)({
@@ -9621,20 +9627,20 @@ var ExecutionHandler = class {
9621
9627
  }
9622
9628
  if (isTransferResponse(messageResponse.result)) {
9623
9629
  const transferResponse = messageResponse.result;
9624
- const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
9630
+ const targetSubAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetSubAgentId;
9625
9631
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
9626
- logger21.info({ targetAgentId, transferReason }, "transfer response");
9632
+ logger20.info({ targetSubAgentId, transferReason }, "transfer response");
9627
9633
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
9628
- const { success, targetAgentId: newAgentId } = await executeTransfer({
9634
+ const { success, targetSubAgentId: newAgentId } = await executeTransfer({
9629
9635
  projectId,
9630
9636
  tenantId,
9631
9637
  threadId: conversationId,
9632
- targetAgentId
9638
+ targetSubAgentId
9633
9639
  });
9634
9640
  if (success) {
9635
9641
  fromAgentId = currentAgentId;
9636
9642
  currentAgentId = newAgentId;
9637
- logger21.info(
9643
+ logger20.info(
9638
9644
  {
9639
9645
  transferFrom: fromAgentId,
9640
9646
  transferTo: currentAgentId,
@@ -9652,7 +9658,7 @@ var ExecutionHandler = class {
9652
9658
  const graphSessionData = graphSessionManager.getSession(requestId2);
9653
9659
  if (graphSessionData) {
9654
9660
  const sessionSummary = graphSessionData.getSummary();
9655
- logger21.info(sessionSummary, "GraphSession data after completion");
9661
+ logger20.info(sessionSummary, "GraphSession data after completion");
9656
9662
  }
9657
9663
  let textContent = "";
9658
9664
  for (const part of responseParts) {
@@ -9684,8 +9690,7 @@ var ExecutionHandler = class {
9684
9690
  },
9685
9691
  visibility: "user-facing",
9686
9692
  messageType: "chat",
9687
- agentId: currentAgentId,
9688
- fromAgentId: currentAgentId,
9693
+ fromSubAgentId: currentAgentId,
9689
9694
  taskId: task.id
9690
9695
  });
9691
9696
  const updateTaskStart = Date.now();
@@ -9706,22 +9711,22 @@ var ExecutionHandler = class {
9706
9711
  }
9707
9712
  });
9708
9713
  const updateTaskEnd = Date.now();
9709
- logger21.info(
9714
+ logger20.info(
9710
9715
  { duration: updateTaskEnd - updateTaskStart },
9711
9716
  "Completed updateTask operation"
9712
9717
  );
9713
9718
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
9714
9719
  await sseHelper.complete();
9715
- logger21.info({}, "Ending GraphSession and cleaning up");
9720
+ logger20.info({}, "Ending GraphSession and cleaning up");
9716
9721
  graphSessionManager.endSession(requestId2);
9717
- logger21.info({}, "Cleaning up streamHelper");
9722
+ logger20.info({}, "Cleaning up streamHelper");
9718
9723
  unregisterStreamHelper(requestId2);
9719
9724
  let response;
9720
9725
  if (sseHelper instanceof MCPStreamHelper) {
9721
9726
  const captured = sseHelper.getCapturedResponse();
9722
9727
  response = captured.text || "No response content";
9723
9728
  }
9724
- logger21.info({}, "ExecutionHandler returning success");
9729
+ logger20.info({}, "ExecutionHandler returning success");
9725
9730
  return { success: true, iterations, response };
9726
9731
  } catch (error) {
9727
9732
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -9732,13 +9737,13 @@ var ExecutionHandler = class {
9732
9737
  });
9733
9738
  }
9734
9739
  errorCount++;
9735
- logger21.warn(
9740
+ logger20.warn(
9736
9741
  { iterations, errorCount },
9737
9742
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9738
9743
  );
9739
9744
  if (errorCount >= this.MAX_ERRORS) {
9740
9745
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9741
- logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9746
+ logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9742
9747
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9743
9748
  if (task) {
9744
9749
  await updateTask(dbClient_default)({
@@ -9759,7 +9764,7 @@ var ExecutionHandler = class {
9759
9764
  }
9760
9765
  }
9761
9766
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
9762
- logger21.error({ maxTransfers, iterations }, errorMessage);
9767
+ logger20.error({ maxTransfers, iterations }, errorMessage);
9763
9768
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
9764
9769
  if (task) {
9765
9770
  await updateTask(dbClient_default)({
@@ -9778,7 +9783,7 @@ var ExecutionHandler = class {
9778
9783
  unregisterStreamHelper(requestId2);
9779
9784
  return { success: false, error: errorMessage, iterations };
9780
9785
  } catch (error) {
9781
- logger21.error({ error }, "Error in execution handler");
9786
+ logger20.error({ error }, "Error in execution handler");
9782
9787
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
9783
9788
  await sseHelper.writeOperation(
9784
9789
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -9805,7 +9810,7 @@ var ExecutionHandler = class {
9805
9810
 
9806
9811
  // src/routes/chat.ts
9807
9812
  var app2 = new OpenAPIHono();
9808
- var logger22 = getLogger("completionsHandler");
9813
+ var logger21 = getLogger("completionsHandler");
9809
9814
  var chatCompletionsRoute = createRoute({
9810
9815
  method: "post",
9811
9816
  path: "/completions",
@@ -9923,7 +9928,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9923
9928
  tracestate: c.req.header("tracestate"),
9924
9929
  baggage: c.req.header("baggage")
9925
9930
  };
9926
- logger22.info(
9931
+ logger21.info(
9927
9932
  {
9928
9933
  otelHeaders,
9929
9934
  path: c.req.path,
@@ -9947,20 +9952,20 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9947
9952
  scopes: { tenantId, projectId, graphId }
9948
9953
  });
9949
9954
  let agentGraph;
9950
- let defaultAgentId;
9955
+ let defaultSubAgentId;
9951
9956
  if (fullGraph) {
9952
9957
  agentGraph = {
9953
9958
  id: fullGraph.id,
9954
9959
  name: fullGraph.name,
9955
9960
  tenantId,
9956
9961
  projectId,
9957
- defaultAgentId: fullGraph.defaultAgentId
9962
+ defaultSubAgentId: fullGraph.defaultSubAgentId
9958
9963
  };
9959
- const agentKeys = Object.keys(fullGraph.agents || {});
9964
+ const agentKeys = Object.keys(fullGraph.subAgents || {});
9960
9965
  const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
9961
- defaultAgentId = fullGraph.defaultAgentId || firstAgentId;
9966
+ defaultSubAgentId = fullGraph.defaultSubAgentId || firstAgentId;
9962
9967
  } else {
9963
- agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
9968
+ agentGraph = await getAgentGraphWithDefaultSubAgent(dbClient_default)({
9964
9969
  scopes: { tenantId, projectId, graphId }
9965
9970
  });
9966
9971
  if (!agentGraph) {
@@ -9969,9 +9974,9 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9969
9974
  message: "Agent graph not found"
9970
9975
  });
9971
9976
  }
9972
- defaultAgentId = agentGraph.defaultAgentId || "";
9977
+ defaultSubAgentId = agentGraph.defaultSubAgentId || "";
9973
9978
  }
9974
- if (!defaultAgentId) {
9979
+ if (!defaultSubAgentId) {
9975
9980
  throw createApiError({
9976
9981
  code: "not_found",
9977
9982
  message: "No default agent found in graph"
@@ -9981,7 +9986,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9981
9986
  tenantId,
9982
9987
  projectId,
9983
9988
  id: conversationId,
9984
- activeAgentId: defaultAgentId
9989
+ activeSubAgentId: defaultSubAgentId
9985
9990
  });
9986
9991
  const activeAgent = await getActiveAgentForConversation(dbClient_default)({
9987
9992
  scopes: { tenantId, projectId },
@@ -9991,13 +9996,13 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9991
9996
  setActiveAgentForConversation(dbClient_default)({
9992
9997
  scopes: { tenantId, projectId },
9993
9998
  conversationId,
9994
- agentId: defaultAgentId
9999
+ subAgentId: defaultSubAgentId
9995
10000
  });
9996
10001
  }
9997
- const agentId = activeAgent?.activeAgentId || defaultAgentId;
9998
- const agentInfo = await getAgentById(dbClient_default)({
10002
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
10003
+ const agentInfo = await getSubAgentById(dbClient_default)({
9999
10004
  scopes: { tenantId, projectId, graphId },
10000
- agentId
10005
+ subAgentId
10001
10006
  });
10002
10007
  if (!agentInfo) {
10003
10008
  throw createApiError({
@@ -10016,14 +10021,14 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10016
10021
  dbClient: dbClient_default,
10017
10022
  credentialStores
10018
10023
  });
10019
- logger22.info(
10024
+ logger21.info(
10020
10025
  {
10021
10026
  tenantId,
10022
10027
  projectId,
10023
10028
  graphId,
10024
10029
  conversationId,
10025
- defaultAgentId,
10026
- activeAgentId: activeAgent?.activeAgentId || "none",
10030
+ defaultSubAgentId,
10031
+ activeSubAgentId: activeAgent?.activeSubAgentId || "none",
10027
10032
  hasContextConfig: !!agentGraph.contextConfigId,
10028
10033
  hasHeaders: !!body.headers,
10029
10034
  hasValidatedContext: !!validatedContext,
@@ -10064,7 +10069,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10064
10069
  try {
10065
10070
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
10066
10071
  await sseHelper.writeRole();
10067
- logger22.info({ agentId }, "Starting execution");
10072
+ logger21.info({ subAgentId }, "Starting execution");
10068
10073
  const emitOperationsHeader = c.req.header("x-emit-operations");
10069
10074
  const emitOperations = emitOperationsHeader === "true";
10070
10075
  const executionHandler = new ExecutionHandler();
@@ -10072,12 +10077,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10072
10077
  executionContext,
10073
10078
  conversationId,
10074
10079
  userMessage,
10075
- initialAgentId: agentId,
10080
+ initialAgentId: subAgentId,
10076
10081
  requestId: requestId2,
10077
10082
  sseHelper,
10078
10083
  emitOperations
10079
10084
  });
10080
- logger22.info(
10085
+ logger21.info(
10081
10086
  { result },
10082
10087
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10083
10088
  );
@@ -10091,7 +10096,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10091
10096
  }
10092
10097
  await sseHelper.complete();
10093
10098
  } catch (error) {
10094
- logger22.error(
10099
+ logger21.error(
10095
10100
  {
10096
10101
  error: error instanceof Error ? error.message : error,
10097
10102
  stack: error instanceof Error ? error.stack : void 0
@@ -10108,12 +10113,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10108
10113
  );
10109
10114
  await sseHelper.complete();
10110
10115
  } catch (streamError) {
10111
- logger22.error({ streamError }, "Failed to write error to stream");
10116
+ logger21.error({ streamError }, "Failed to write error to stream");
10112
10117
  }
10113
10118
  }
10114
10119
  });
10115
10120
  } catch (error) {
10116
- logger22.error(
10121
+ logger21.error(
10117
10122
  {
10118
10123
  error: error instanceof Error ? error.message : error,
10119
10124
  stack: error instanceof Error ? error.stack : void 0
@@ -10137,7 +10142,7 @@ var getMessageText = (content) => {
10137
10142
  };
10138
10143
  var chat_default = app2;
10139
10144
  var app3 = new OpenAPIHono();
10140
- var logger23 = getLogger("chatDataStream");
10145
+ var logger22 = getLogger("chatDataStream");
10141
10146
  var chatDataStreamRoute = createRoute({
10142
10147
  method: "post",
10143
10148
  path: "/chat",
@@ -10202,7 +10207,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10202
10207
  "project.id": projectId
10203
10208
  });
10204
10209
  }
10205
- const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
10210
+ const agentGraph = await getAgentGraphWithDefaultSubAgent(dbClient_default)({
10206
10211
  scopes: { tenantId, projectId, graphId }
10207
10212
  });
10208
10213
  if (!agentGraph) {
@@ -10211,9 +10216,9 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10211
10216
  message: "Agent graph not found"
10212
10217
  });
10213
10218
  }
10214
- const defaultAgentId = agentGraph.defaultAgentId;
10219
+ const defaultSubAgentId = agentGraph.defaultSubAgentId;
10215
10220
  const graphName = agentGraph.name;
10216
- if (!defaultAgentId) {
10221
+ if (!defaultSubAgentId) {
10217
10222
  throw createApiError({
10218
10223
  code: "bad_request",
10219
10224
  message: "Graph does not have a default agent configured"
@@ -10227,13 +10232,13 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10227
10232
  setActiveAgentForConversation(dbClient_default)({
10228
10233
  scopes: { tenantId, projectId },
10229
10234
  conversationId,
10230
- agentId: defaultAgentId
10235
+ subAgentId: defaultSubAgentId
10231
10236
  });
10232
10237
  }
10233
- const agentId = activeAgent?.activeAgentId || defaultAgentId;
10234
- const agentInfo = await getAgentById(dbClient_default)({
10238
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
10239
+ const agentInfo = await getSubAgentById(dbClient_default)({
10235
10240
  scopes: { tenantId, projectId, graphId },
10236
- agentId
10241
+ subAgentId
10237
10242
  });
10238
10243
  if (!agentInfo) {
10239
10244
  throw createApiError({
@@ -10254,7 +10259,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10254
10259
  });
10255
10260
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
10256
10261
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
10257
- logger23.info({ userText, lastUserMessage }, "userText");
10262
+ logger22.info({ userText, lastUserMessage }, "userText");
10258
10263
  const messageSpan = trace.getActiveSpan();
10259
10264
  if (messageSpan) {
10260
10265
  messageSpan.setAttributes({
@@ -10290,7 +10295,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10290
10295
  executionContext,
10291
10296
  conversationId,
10292
10297
  userMessage: userText,
10293
- initialAgentId: agentId,
10298
+ initialAgentId: subAgentId,
10294
10299
  requestId: `chatds-${Date.now()}`,
10295
10300
  sseHelper: streamHelper,
10296
10301
  emitOperations
@@ -10299,7 +10304,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10299
10304
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
10300
10305
  }
10301
10306
  } catch (err) {
10302
- logger23.error({ err }, "Streaming error");
10307
+ logger22.error({ err }, "Streaming error");
10303
10308
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
10304
10309
  } finally {
10305
10310
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -10320,7 +10325,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10320
10325
  )
10321
10326
  );
10322
10327
  } catch (error) {
10323
- logger23.error({ error }, "chatDataStream error");
10328
+ logger22.error({ error }, "chatDataStream error");
10324
10329
  throw createApiError({
10325
10330
  code: "internal_server_error",
10326
10331
  message: "Failed to process chat completion"
@@ -10331,7 +10336,7 @@ var chatDataStream_default = app3;
10331
10336
  function createMCPSchema(schema) {
10332
10337
  return schema;
10333
10338
  }
10334
- var logger24 = getLogger("mcp");
10339
+ var logger23 = getLogger("mcp");
10335
10340
  var _MockResponseSingleton = class _MockResponseSingleton {
10336
10341
  constructor() {
10337
10342
  __publicField(this, "mockRes");
@@ -10386,21 +10391,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
10386
10391
  id: 0
10387
10392
  });
10388
10393
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
10389
- logger24.info({ sessionId }, "Spoofing initialization message to set transport state");
10394
+ logger23.info({ sessionId }, "Spoofing initialization message to set transport state");
10390
10395
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
10391
10396
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
10392
10397
  try {
10393
10398
  await transport.handleRequest(req, mockRes, spoofInitMessage);
10394
- logger24.info({ sessionId }, "Successfully spoofed initialization");
10399
+ logger23.info({ sessionId }, "Successfully spoofed initialization");
10395
10400
  } catch (spoofError) {
10396
- logger24.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
10401
+ logger23.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
10397
10402
  }
10398
10403
  };
10399
10404
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10400
10405
  const sessionId = req.headers["mcp-session-id"];
10401
- logger24.info({ sessionId }, "Received MCP session ID");
10406
+ logger23.info({ sessionId }, "Received MCP session ID");
10402
10407
  if (!sessionId) {
10403
- logger24.info({ body }, "Missing session ID");
10408
+ logger23.info({ body }, "Missing session ID");
10404
10409
  res.writeHead(400).end(
10405
10410
  JSON.stringify({
10406
10411
  jsonrpc: "2.0",
@@ -10426,7 +10431,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10426
10431
  scopes: { tenantId, projectId },
10427
10432
  conversationId: sessionId
10428
10433
  });
10429
- logger24.info(
10434
+ logger23.info(
10430
10435
  {
10431
10436
  sessionId,
10432
10437
  conversationFound: !!conversation,
@@ -10437,7 +10442,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10437
10442
  "Conversation lookup result"
10438
10443
  );
10439
10444
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
10440
- logger24.info(
10445
+ logger23.info(
10441
10446
  { sessionId, conversationId: conversation?.id },
10442
10447
  "MCP session not found or invalid"
10443
10448
  );
@@ -10486,7 +10491,7 @@ var processUserMessage = async (tenantId, projectId, conversationId, query) => {
10486
10491
  messageType: "chat"
10487
10492
  });
10488
10493
  };
10489
- var executeAgentQuery = async (executionContext, conversationId, query, defaultAgentId) => {
10494
+ var executeAgentQuery = async (executionContext, conversationId, query, defaultSubAgentId) => {
10490
10495
  const requestId2 = `mcp-${Date.now()}`;
10491
10496
  const mcpStreamHelper = createMCPStreamHelper();
10492
10497
  const executionHandler = new ExecutionHandler();
@@ -10494,11 +10499,11 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
10494
10499
  executionContext,
10495
10500
  conversationId,
10496
10501
  userMessage: query,
10497
- initialAgentId: defaultAgentId,
10502
+ initialAgentId: defaultSubAgentId,
10498
10503
  requestId: requestId2,
10499
10504
  sseHelper: mcpStreamHelper
10500
10505
  });
10501
- logger24.info(
10506
+ logger23.info(
10502
10507
  { result },
10503
10508
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10504
10509
  );
@@ -10525,7 +10530,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
10525
10530
  var getServer = async (headers, executionContext, conversationId, credentialStores) => {
10526
10531
  const { tenantId, projectId, graphId } = executionContext;
10527
10532
  setupTracing(conversationId, tenantId, graphId);
10528
- const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
10533
+ const agentGraph = await getAgentGraphWithDefaultSubAgent(dbClient_default)({
10529
10534
  scopes: { tenantId, projectId, graphId }
10530
10535
  });
10531
10536
  if (!agentGraph) {
@@ -10546,7 +10551,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
10546
10551
  },
10547
10552
  async ({ query }) => {
10548
10553
  try {
10549
- if (!agentGraph.defaultAgentId) {
10554
+ if (!agentGraph.defaultSubAgentId) {
10550
10555
  return {
10551
10556
  content: [
10552
10557
  {
@@ -10557,10 +10562,10 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
10557
10562
  isError: true
10558
10563
  };
10559
10564
  }
10560
- const defaultAgentId = agentGraph.defaultAgentId;
10561
- const agentInfo = await getAgentById(dbClient_default)({
10565
+ const defaultSubAgentId = agentGraph.defaultSubAgentId;
10566
+ const agentInfo = await getSubAgentById(dbClient_default)({
10562
10567
  scopes: { tenantId, projectId, graphId },
10563
- agentId: defaultAgentId
10568
+ subAgentId: defaultSubAgentId
10564
10569
  });
10565
10570
  if (!agentInfo) {
10566
10571
  return {
@@ -10582,7 +10587,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
10582
10587
  dbClient: dbClient_default,
10583
10588
  credentialStores
10584
10589
  });
10585
- logger24.info(
10590
+ logger23.info(
10586
10591
  {
10587
10592
  tenantId,
10588
10593
  projectId,
@@ -10595,7 +10600,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
10595
10600
  "parameters"
10596
10601
  );
10597
10602
  await processUserMessage(tenantId, projectId, conversationId, query);
10598
- return executeAgentQuery(executionContext, conversationId, query, defaultAgentId);
10603
+ return executeAgentQuery(executionContext, conversationId, query, defaultSubAgentId);
10599
10604
  } catch (error) {
10600
10605
  return {
10601
10606
  content: [
@@ -10644,9 +10649,9 @@ var validateRequestParameters = (c) => {
10644
10649
  };
10645
10650
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
10646
10651
  const { tenantId, projectId, graphId } = executionContext;
10647
- logger24.info({ body }, "Received initialization request");
10652
+ logger23.info({ body }, "Received initialization request");
10648
10653
  const sessionId = getConversationId();
10649
- const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
10654
+ const agentGraph = await getAgentGraphWithDefaultSubAgent(dbClient_default)({
10650
10655
  scopes: { tenantId, projectId, graphId }
10651
10656
  });
10652
10657
  if (!agentGraph) {
@@ -10659,7 +10664,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10659
10664
  { status: 404 }
10660
10665
  );
10661
10666
  }
10662
- if (!agentGraph.defaultAgentId) {
10667
+ if (!agentGraph.defaultSubAgentId) {
10663
10668
  return c.json(
10664
10669
  {
10665
10670
  jsonrpc: "2.0",
@@ -10673,7 +10678,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10673
10678
  id: sessionId,
10674
10679
  tenantId,
10675
10680
  projectId,
10676
- activeAgentId: agentGraph.defaultAgentId,
10681
+ activeSubAgentId: agentGraph.defaultSubAgentId,
10677
10682
  metadata: {
10678
10683
  sessionData: {
10679
10684
  graphId,
@@ -10684,7 +10689,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10684
10689
  }
10685
10690
  }
10686
10691
  });
10687
- logger24.info(
10692
+ logger23.info(
10688
10693
  { sessionId, conversationId: conversation.id },
10689
10694
  "Created MCP session as conversation"
10690
10695
  );
@@ -10693,9 +10698,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10693
10698
  });
10694
10699
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
10695
10700
  await server.connect(transport);
10696
- logger24.info({ sessionId }, "Server connected for initialization");
10701
+ logger23.info({ sessionId }, "Server connected for initialization");
10697
10702
  res.setHeader("Mcp-Session-Id", sessionId);
10698
- logger24.info(
10703
+ logger23.info(
10699
10704
  {
10700
10705
  sessionId,
10701
10706
  bodyMethod: body?.method,
@@ -10704,7 +10709,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10704
10709
  "About to handle initialization request"
10705
10710
  );
10706
10711
  await transport.handleRequest(req, res, body);
10707
- logger24.info({ sessionId }, "Successfully handled initialization request");
10712
+ logger23.info({ sessionId }, "Successfully handled initialization request");
10708
10713
  return toFetchResponse(res);
10709
10714
  };
10710
10715
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -10732,8 +10737,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10732
10737
  sessionId,
10733
10738
  conversation.metadata?.session_data?.mcpProtocolVersion
10734
10739
  );
10735
- logger24.info({ sessionId }, "Server connected and transport initialized");
10736
- logger24.info(
10740
+ logger23.info({ sessionId }, "Server connected and transport initialized");
10741
+ logger23.info(
10737
10742
  {
10738
10743
  sessionId,
10739
10744
  bodyKeys: Object.keys(body || {}),
@@ -10747,9 +10752,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10747
10752
  );
10748
10753
  try {
10749
10754
  await transport.handleRequest(req, res, body);
10750
- logger24.info({ sessionId }, "Successfully handled MCP request");
10755
+ logger23.info({ sessionId }, "Successfully handled MCP request");
10751
10756
  } catch (transportError) {
10752
- logger24.error(
10757
+ logger23.error(
10753
10758
  {
10754
10759
  sessionId,
10755
10760
  error: transportError,
@@ -10800,13 +10805,13 @@ app4.openapi(
10800
10805
  }
10801
10806
  const { executionContext } = paramValidation;
10802
10807
  const body = c.get("requestBody") || {};
10803
- logger24.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10808
+ logger23.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10804
10809
  const isInitRequest = body.method === "initialize";
10805
10810
  const { req, res } = toReqRes(c.req.raw);
10806
10811
  const validatedContext = c.get("validatedContext") || {};
10807
10812
  const credentialStores = c.get("credentialStores");
10808
- logger24.info({ validatedContext }, "Validated context");
10809
- logger24.info({ req }, "request");
10813
+ logger23.info({ validatedContext }, "Validated context");
10814
+ logger23.info({ req }, "request");
10810
10815
  if (isInitRequest) {
10811
10816
  return await handleInitializationRequest(
10812
10817
  body,
@@ -10828,7 +10833,7 @@ app4.openapi(
10828
10833
  );
10829
10834
  }
10830
10835
  } catch (e) {
10831
- logger24.error(
10836
+ logger23.error(
10832
10837
  {
10833
10838
  error: e instanceof Error ? e.message : e,
10834
10839
  stack: e instanceof Error ? e.stack : void 0
@@ -10840,7 +10845,7 @@ app4.openapi(
10840
10845
  }
10841
10846
  );
10842
10847
  app4.get("/", async (c) => {
10843
- logger24.info({}, "Received GET MCP request");
10848
+ logger23.info({}, "Received GET MCP request");
10844
10849
  return c.json(
10845
10850
  {
10846
10851
  jsonrpc: "2.0",
@@ -10854,7 +10859,7 @@ app4.get("/", async (c) => {
10854
10859
  );
10855
10860
  });
10856
10861
  app4.delete("/", async (c) => {
10857
- logger24.info({}, "Received DELETE MCP request");
10862
+ logger23.info({}, "Received DELETE MCP request");
10858
10863
  return c.json(
10859
10864
  {
10860
10865
  jsonrpc: "2.0",
@@ -10867,7 +10872,7 @@ app4.delete("/", async (c) => {
10867
10872
  var mcp_default = app4;
10868
10873
 
10869
10874
  // src/app.ts
10870
- var logger25 = getLogger("agents-run-api");
10875
+ var logger24 = getLogger("agents-run-api");
10871
10876
  function createExecutionHono(serverConfig, credentialStores) {
10872
10877
  const app6 = new OpenAPIHono();
10873
10878
  app6.use("*", otel());
@@ -10883,7 +10888,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10883
10888
  const body = await c.req.json();
10884
10889
  c.set("requestBody", body);
10885
10890
  } catch (error) {
10886
- logger25.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
10891
+ logger24.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
10887
10892
  }
10888
10893
  }
10889
10894
  return next();
@@ -10934,8 +10939,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10934
10939
  if (!isExpectedError) {
10935
10940
  const errorMessage = err instanceof Error ? err.message : String(err);
10936
10941
  const errorStack = err instanceof Error ? err.stack : void 0;
10937
- if (logger25) {
10938
- logger25.error(
10942
+ if (logger24) {
10943
+ logger24.error(
10939
10944
  {
10940
10945
  error: err,
10941
10946
  message: errorMessage,
@@ -10947,8 +10952,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10947
10952
  );
10948
10953
  }
10949
10954
  } else {
10950
- if (logger25) {
10951
- logger25.error(
10955
+ if (logger24) {
10956
+ logger24.error(
10952
10957
  {
10953
10958
  error: err,
10954
10959
  path: c.req.path,
@@ -10965,8 +10970,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10965
10970
  const response = err.getResponse();
10966
10971
  return response;
10967
10972
  } catch (responseError) {
10968
- if (logger25) {
10969
- logger25.error({ error: responseError }, "Error while handling HTTPException response");
10973
+ if (logger24) {
10974
+ logger24.error({ error: responseError }, "Error while handling HTTPException response");
10970
10975
  }
10971
10976
  }
10972
10977
  }
@@ -11000,7 +11005,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11000
11005
  app6.use("*", async (c, next) => {
11001
11006
  const executionContext = c.get("executionContext");
11002
11007
  if (!executionContext) {
11003
- logger25.debug({}, "Empty execution context");
11008
+ logger24.debug({}, "Empty execution context");
11004
11009
  return next();
11005
11010
  }
11006
11011
  const { tenantId, projectId, graphId } = executionContext;
@@ -11009,7 +11014,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11009
11014
  if (requestBody) {
11010
11015
  conversationId = requestBody.conversationId;
11011
11016
  if (!conversationId) {
11012
- logger25.debug({ requestBody }, "No conversation ID found in request body");
11017
+ logger24.debug({ requestBody }, "No conversation ID found in request body");
11013
11018
  }
11014
11019
  }
11015
11020
  const entries = Object.fromEntries(
@@ -11024,7 +11029,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11024
11029
  })
11025
11030
  );
11026
11031
  if (!Object.keys(entries).length) {
11027
- logger25.debug({}, "Empty entries for baggage");
11032
+ logger24.debug({}, "Empty entries for baggage");
11028
11033
  return next();
11029
11034
  }
11030
11035
  const bag = Object.entries(entries).reduce(