@inkeep/agents-run-api 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -198,8 +198,8 @@ async function saveA2AMessageResponse(response, params) {
198
198
  },
199
199
  visibility: params.visibility,
200
200
  messageType: params.messageType,
201
- fromAgentId: params.fromAgentId,
202
- toAgentId: params.toAgentId,
201
+ fromSubAgentId: params.fromSubAgentId,
202
+ toSubAgentId: params.toSubAgentId,
203
203
  fromExternalAgentId: params.fromExternalAgentId,
204
204
  toExternalAgentId: params.toExternalAgentId,
205
205
  a2aTaskId: params.a2aTaskId,
@@ -220,23 +220,23 @@ async function getScopedHistory({
220
220
  conversationId,
221
221
  options
222
222
  });
223
- if (!filters || !filters.agentId && !filters.taskId) {
223
+ if (!filters || !filters.subAgentId && !filters.taskId) {
224
224
  return messages;
225
225
  }
226
226
  const relevantMessages = messages.filter((msg) => {
227
227
  if (msg.role === "user") return true;
228
228
  let matchesAgent = true;
229
229
  let matchesTask = true;
230
- if (filters.agentId) {
231
- matchesAgent = msg.role === "agent" && msg.visibility === "user-facing" || msg.toAgentId === filters.agentId || msg.fromAgentId === filters.agentId;
230
+ if (filters.subAgentId) {
231
+ matchesAgent = msg.role === "agent" && msg.visibility === "user-facing" || msg.toAgentId === filters.subAgentId || msg.fromAgentId === filters.subAgentId;
232
232
  }
233
233
  if (filters.taskId) {
234
234
  matchesTask = msg.taskId === filters.taskId || msg.a2aTaskId === filters.taskId;
235
235
  }
236
- if (filters.agentId && filters.taskId) {
236
+ if (filters.subAgentId && filters.taskId) {
237
237
  return matchesAgent && matchesTask;
238
238
  }
239
- if (filters.agentId) {
239
+ if (filters.subAgentId) {
240
240
  return matchesAgent;
241
241
  }
242
242
  if (filters.taskId) {
@@ -337,7 +337,9 @@ async function getConversationScopedArtifacts(params) {
337
337
  if (visibleMessages.length === 0) {
338
338
  return [];
339
339
  }
340
- const visibleMessageIds = visibleMessages.filter((msg) => !(msg.messageType === "system" && msg.content?.text?.includes("Previous conversation history truncated"))).map((msg) => msg.id);
340
+ const visibleMessageIds = visibleMessages.filter(
341
+ (msg) => !(msg.messageType === "system" && msg.content?.text?.includes("Previous conversation history truncated"))
342
+ ).map((msg) => msg.id);
341
343
  if (visibleMessageIds.length === 0) {
342
344
  return [];
343
345
  }
@@ -352,8 +354,8 @@ async function getConversationScopedArtifacts(params) {
352
354
  });
353
355
  referenceArtifacts.push(...artifacts);
354
356
  }
355
- const logger28 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
356
- logger28.debug(
357
+ const logger27 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
358
+ logger27.debug(
357
359
  {
358
360
  conversationId,
359
361
  visibleMessages: visibleMessages.length,
@@ -365,8 +367,8 @@ async function getConversationScopedArtifacts(params) {
365
367
  );
366
368
  return referenceArtifacts;
367
369
  } catch (error) {
368
- const logger28 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
369
- logger28.error(
370
+ const logger27 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
371
+ logger27.error(
370
372
  {
371
373
  error: error instanceof Error ? error.message : "Unknown error",
372
374
  conversationId
@@ -387,10 +389,10 @@ var LocalSandboxExecutor_exports = {};
387
389
  __export(LocalSandboxExecutor_exports, {
388
390
  LocalSandboxExecutor: () => LocalSandboxExecutor
389
391
  });
390
- var logger18, _LocalSandboxExecutor, LocalSandboxExecutor;
392
+ var logger17, _LocalSandboxExecutor, LocalSandboxExecutor;
391
393
  var init_LocalSandboxExecutor = __esm({
392
394
  "src/tools/LocalSandboxExecutor.ts"() {
393
- logger18 = agentsCore.getLogger("local-sandbox-executor");
395
+ logger17 = agentsCore.getLogger("local-sandbox-executor");
394
396
  _LocalSandboxExecutor = class _LocalSandboxExecutor {
395
397
  constructor() {
396
398
  __publicField(this, "tempDir");
@@ -426,7 +428,7 @@ var init_LocalSandboxExecutor = __esm({
426
428
  if (now - sandbox.lastUsed < this.POOL_TTL && sandbox.useCount < this.MAX_USE_COUNT) {
427
429
  sandbox.lastUsed = now;
428
430
  sandbox.useCount++;
429
- logger18.debug(
431
+ logger17.debug(
430
432
  {
431
433
  poolKey,
432
434
  useCount: sandbox.useCount,
@@ -454,14 +456,14 @@ var init_LocalSandboxExecutor = __esm({
454
456
  useCount: 1,
455
457
  dependencies
456
458
  };
457
- logger18.debug({ poolKey, sandboxDir }, "Added sandbox to pool");
459
+ logger17.debug({ poolKey, sandboxDir }, "Added sandbox to pool");
458
460
  }
459
461
  cleanupSandbox(sandboxDir) {
460
462
  try {
461
463
  fs.rmSync(sandboxDir, { recursive: true, force: true });
462
- logger18.debug({ sandboxDir }, "Cleaned up sandbox");
464
+ logger17.debug({ sandboxDir }, "Cleaned up sandbox");
463
465
  } catch (error) {
464
- logger18.warn({ sandboxDir, error }, "Failed to clean up sandbox");
466
+ logger17.warn({ sandboxDir, error }, "Failed to clean up sandbox");
465
467
  }
466
468
  }
467
469
  startPoolCleanup() {
@@ -478,7 +480,7 @@ var init_LocalSandboxExecutor = __esm({
478
480
  delete this.sandboxPool[key];
479
481
  });
480
482
  if (keysToDelete.length > 0) {
481
- logger18.debug({ cleanedCount: keysToDelete.length }, "Cleaned up expired sandboxes");
483
+ logger17.debug({ cleanedCount: keysToDelete.length }, "Cleaned up expired sandboxes");
482
484
  }
483
485
  }, 6e4);
484
486
  }
@@ -504,7 +506,7 @@ var init_LocalSandboxExecutor = __esm({
504
506
  const hasEsmSyntax = esmPatterns.some((pattern) => pattern.test(executeCode));
505
507
  const hasCjsSyntax = cjsPatterns.some((pattern) => pattern.test(executeCode));
506
508
  if (hasEsmSyntax && hasCjsSyntax) {
507
- logger18.warn(
509
+ logger17.warn(
508
510
  { executeCode: `${executeCode.substring(0, 100)}...` },
509
511
  "Both ESM and CommonJS syntax detected, defaulting to ESM"
510
512
  );
@@ -521,7 +523,7 @@ var init_LocalSandboxExecutor = __esm({
521
523
  async executeFunctionTool(toolId, args, config) {
522
524
  const dependencies = config.dependencies || {};
523
525
  const dependencyHash = this.generateDependencyHash(dependencies);
524
- logger18.debug(
526
+ logger17.debug(
525
527
  {
526
528
  toolId,
527
529
  dependencies,
@@ -536,7 +538,7 @@ var init_LocalSandboxExecutor = __esm({
536
538
  sandboxDir = path.join(this.tempDir, `sandbox-${dependencyHash}-${Date.now()}`);
537
539
  fs.mkdirSync(sandboxDir, { recursive: true });
538
540
  isNewSandbox = true;
539
- logger18.debug(
541
+ logger17.debug(
540
542
  {
541
543
  toolId,
542
544
  dependencyHash,
@@ -595,15 +597,15 @@ var init_LocalSandboxExecutor = __esm({
595
597
  });
596
598
  npm.on("close", (code) => {
597
599
  if (code === 0) {
598
- logger18.debug({ sandboxDir }, "Dependencies installed successfully");
600
+ logger17.debug({ sandboxDir }, "Dependencies installed successfully");
599
601
  resolve();
600
602
  } else {
601
- logger18.error({ sandboxDir, code, stderr }, "Failed to install dependencies");
603
+ logger17.error({ sandboxDir, code, stderr }, "Failed to install dependencies");
602
604
  reject(new Error(`npm install failed with code ${code}: ${stderr}`));
603
605
  }
604
606
  });
605
607
  npm.on("error", (err) => {
606
- logger18.error({ sandboxDir, error: err }, "Failed to spawn npm install");
608
+ logger17.error({ sandboxDir, error: err }, "Failed to spawn npm install");
607
609
  reject(err);
608
610
  });
609
611
  });
@@ -644,7 +646,7 @@ var init_LocalSandboxExecutor = __esm({
644
646
  stderr += dataStr;
645
647
  });
646
648
  const timeoutId = setTimeout(() => {
647
- logger18.warn({ sandboxDir, timeout }, "Function execution timed out, killing process");
649
+ logger17.warn({ sandboxDir, timeout }, "Function execution timed out, killing process");
648
650
  node.kill("SIGTERM");
649
651
  setTimeout(() => {
650
652
  try {
@@ -665,18 +667,18 @@ var init_LocalSandboxExecutor = __esm({
665
667
  reject(new Error(result.error || "Function execution failed"));
666
668
  }
667
669
  } catch (parseError) {
668
- logger18.error({ stdout, stderr, parseError }, "Failed to parse function result");
670
+ logger17.error({ stdout, stderr, parseError }, "Failed to parse function result");
669
671
  reject(new Error(`Invalid function result: ${stdout}`));
670
672
  }
671
673
  } else {
672
674
  const errorMsg = signal ? `Function execution killed by signal ${signal}: ${stderr}` : `Function execution failed with code ${code}: ${stderr}`;
673
- logger18.error({ code, signal, stderr }, "Function execution failed");
675
+ logger17.error({ code, signal, stderr }, "Function execution failed");
674
676
  reject(new Error(errorMsg));
675
677
  }
676
678
  });
677
679
  node.on("error", (error) => {
678
680
  clearTimeout(timeoutId);
679
- logger18.error({ sandboxDir, error }, "Failed to spawn node process");
681
+ logger17.error({ sandboxDir, error }, "Failed to spawn node process");
680
682
  reject(error);
681
683
  });
682
684
  });
@@ -687,13 +689,26 @@ var init_LocalSandboxExecutor = __esm({
687
689
  const execute = ${executeCode};
688
690
  const args = ${JSON.stringify(args)};
689
691
 
690
- execute(args)
691
- .then(result => {
692
+ try {
693
+ const result = execute(args);
694
+
695
+ // Handle both sync and async functions
696
+ if (result && typeof result.then === 'function') {
697
+ // Async function - result is a Promise
698
+ result
699
+ .then(result => {
700
+ console.log(JSON.stringify({ success: true, result }));
701
+ })
702
+ .catch(error => {
703
+ console.log(JSON.stringify({ success: false, error: error.message }));
704
+ });
705
+ } else {
706
+ // Sync function - result is immediate
692
707
  console.log(JSON.stringify({ success: true, result }));
693
- })
694
- .catch(error => {
695
- console.log(JSON.stringify({ success: false, error: error.message }));
696
- });
708
+ }
709
+ } catch (error) {
710
+ console.log(JSON.stringify({ success: false, error: error.message }));
711
+ }
697
712
  `;
698
713
  }
699
714
  };
@@ -807,7 +822,7 @@ function createExecutionContext(params) {
807
822
  graphId: params.graphId,
808
823
  baseUrl: params.baseUrl || process.env.API_URL || "http://localhost:3003",
809
824
  apiKeyId: params.apiKeyId,
810
- agentId: params.agentId
825
+ subAgentId: params.subAgentId
811
826
  };
812
827
  }
813
828
 
@@ -822,7 +837,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
822
837
  const tenantId = c.req.header("x-inkeep-tenant-id");
823
838
  const projectId = c.req.header("x-inkeep-project-id");
824
839
  const graphId = c.req.header("x-inkeep-graph-id");
825
- const agentId = c.req.header("x-inkeep-agent-id");
840
+ const subAgentId = c.req.header("x-inkeep-agent-id");
826
841
  const proto = c.req.header("x-forwarded-proto")?.split(",")[0].trim();
827
842
  const fwdHost = c.req.header("x-forwarded-host")?.split(",")[0].trim();
828
843
  const host = fwdHost ?? c.req.header("host");
@@ -833,7 +848,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
833
848
  if (authHeader?.startsWith("Bearer ")) {
834
849
  try {
835
850
  executionContext = await extractContextFromApiKey(authHeader.substring(7), baseUrl);
836
- executionContext.agentId = agentId;
851
+ executionContext.subAgentId = subAgentId;
837
852
  logger2.info({}, "Development/test environment - API key authenticated successfully");
838
853
  } catch {
839
854
  executionContext = createExecutionContext({
@@ -843,7 +858,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
843
858
  graphId: graphId || "test-graph",
844
859
  apiKeyId: "test-key",
845
860
  baseUrl,
846
- agentId
861
+ subAgentId
847
862
  });
848
863
  logger2.info(
849
864
  {},
@@ -858,7 +873,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
858
873
  graphId: graphId || "test-graph",
859
874
  apiKeyId: "test-key",
860
875
  baseUrl,
861
- agentId
876
+ subAgentId
862
877
  });
863
878
  logger2.info(
864
879
  {},
@@ -889,7 +904,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
889
904
  graphId,
890
905
  apiKeyId: "bypass",
891
906
  baseUrl,
892
- agentId
907
+ subAgentId
893
908
  });
894
909
  c.set("executionContext", executionContext);
895
910
  logger2.info({}, "Bypass secret authenticated successfully");
@@ -897,7 +912,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
897
912
  return;
898
913
  } else if (apiKey) {
899
914
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
900
- executionContext.agentId = agentId;
915
+ executionContext.subAgentId = subAgentId;
901
916
  c.set("executionContext", executionContext);
902
917
  logger2.info({}, "API key authenticated successfully");
903
918
  await next();
@@ -915,14 +930,14 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
915
930
  }
916
931
  try {
917
932
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
918
- executionContext.agentId = agentId;
933
+ executionContext.subAgentId = subAgentId;
919
934
  c.set("executionContext", executionContext);
920
935
  logger2.debug(
921
936
  {
922
937
  tenantId: executionContext.tenantId,
923
938
  projectId: executionContext.projectId,
924
939
  graphId: executionContext.graphId,
925
- agentId: executionContext.agentId
940
+ subAgentId: executionContext.subAgentId
926
941
  },
927
942
  "API key authenticated successfully"
928
943
  );
@@ -1097,7 +1112,7 @@ async function handleMessageSend(c, agent, request) {
1097
1112
  logger3.warn(
1098
1113
  {
1099
1114
  taskId: task.id,
1100
- agentId: agent.agentId,
1115
+ subAgentId: agent.subAgentId,
1101
1116
  originalMessage: params.message
1102
1117
  },
1103
1118
  "Created fallback message content for empty delegation message"
@@ -1118,7 +1133,7 @@ async function handleMessageSend(c, agent, request) {
1118
1133
  taskContextId: task.context?.conversationId,
1119
1134
  metadataContextId: params.message.metadata?.conversationId,
1120
1135
  finalContextId: effectiveContextId,
1121
- agentId: agent.agentId
1136
+ subAgentId: agent.subAgentId
1122
1137
  },
1123
1138
  "A2A contextId resolution for delegation"
1124
1139
  );
@@ -1134,11 +1149,11 @@ async function handleMessageSend(c, agent, request) {
1134
1149
  message_id: params.message.messageId || "",
1135
1150
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
1136
1151
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
1137
- agent_id: agent.agentId,
1152
+ agent_id: agent.subAgentId,
1138
1153
  graph_id: graphId || "",
1139
1154
  stream_request_id: params.message.metadata?.stream_request_id
1140
1155
  },
1141
- agentId: agent.agentId,
1156
+ subAgentId: agent.subAgentId,
1142
1157
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1143
1158
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1144
1159
  });
@@ -1161,17 +1176,17 @@ async function handleMessageSend(c, agent, request) {
1161
1176
  };
1162
1177
  if (params.message.metadata?.fromAgentId) {
1163
1178
  messageData.fromAgentId = params.message.metadata.fromAgentId;
1164
- messageData.toAgentId = agent.agentId;
1179
+ messageData.toAgentId = agent.subAgentId;
1165
1180
  } else if (params.message.metadata?.fromExternalAgentId) {
1166
1181
  messageData.fromExternalAgentId = params.message.metadata.fromExternalAgentId;
1167
- messageData.toAgentId = agent.agentId;
1182
+ messageData.toAgentId = agent.subAgentId;
1168
1183
  }
1169
1184
  await agentsCore.createMessage(dbClient_default)(messageData);
1170
1185
  logger3.info(
1171
1186
  {
1172
1187
  fromAgentId: params.message.metadata.fromAgentId,
1173
1188
  fromExternalAgentId: params.message.metadata.fromExternalAgentId,
1174
- toAgentId: agent.agentId,
1189
+ toAgentId: agent.subAgentId,
1175
1190
  conversationId: effectiveContextId,
1176
1191
  messageType: "a2a-request",
1177
1192
  taskId: task.id
@@ -1184,7 +1199,7 @@ async function handleMessageSend(c, agent, request) {
1184
1199
  error,
1185
1200
  fromAgentId: params.message.metadata.fromAgentId,
1186
1201
  fromExternalAgentId: params.message.metadata.fromExternalAgentId,
1187
- toAgentId: agent.agentId,
1202
+ toAgentId: agent.subAgentId,
1188
1203
  conversationId: effectiveContextId
1189
1204
  },
1190
1205
  "Failed to store A2A message in database"
@@ -1201,7 +1216,7 @@ async function handleMessageSend(c, agent, request) {
1201
1216
  message_id: params.message.messageId || "",
1202
1217
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
1203
1218
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
1204
- agent_id: agent.agentId,
1219
+ agent_id: agent.subAgentId,
1205
1220
  graph_id: graphId || ""
1206
1221
  }
1207
1222
  }
@@ -1235,7 +1250,7 @@ async function handleMessageSend(c, agent, request) {
1235
1250
  kind: "data",
1236
1251
  data: {
1237
1252
  type: "transfer",
1238
- targetAgentId: transferPart.data.target
1253
+ targetSubAgentId: transferPart.data.target
1239
1254
  }
1240
1255
  },
1241
1256
  {
@@ -1535,7 +1550,7 @@ async function handleGetCapabilities(c, agent, request) {
1535
1550
  async function handleGetStatus(c, agent, request) {
1536
1551
  return c.json({
1537
1552
  jsonrpc: "2.0",
1538
- result: { status: "ready", agentId: agent.agentId },
1553
+ result: { status: "ready", subAgentId: agent.subAgentId },
1539
1554
  id: request.id
1540
1555
  });
1541
1556
  }
@@ -1599,7 +1614,6 @@ async function handleTasksResubscribe(c, agent, request) {
1599
1614
  }
1600
1615
  }
1601
1616
  init_dbClient();
1602
- agentsCore.getLogger("agents");
1603
1617
  function createAgentCard({
1604
1618
  dbAgent,
1605
1619
  baseUrl
@@ -1677,7 +1691,7 @@ async function hydrateAgent({
1677
1691
  tenantId: dbAgent.tenantId,
1678
1692
  projectId: dbAgent.projectId,
1679
1693
  graphId,
1680
- agentId: dbAgent.id,
1694
+ subAgentId: dbAgent.id,
1681
1695
  baseUrl,
1682
1696
  apiKey
1683
1697
  });
@@ -1687,7 +1701,7 @@ async function hydrateAgent({
1687
1701
  baseUrl
1688
1702
  });
1689
1703
  return {
1690
- agentId: dbAgent.id,
1704
+ subAgentId: dbAgent.id,
1691
1705
  tenantId: dbAgent.tenantId,
1692
1706
  projectId: dbAgent.projectId,
1693
1707
  graphId,
@@ -1700,13 +1714,13 @@ async function hydrateAgent({
1700
1714
  }
1701
1715
  }
1702
1716
  async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
1703
- const { tenantId, projectId, graphId, agentId, baseUrl, apiKey } = executionContext;
1704
- if (!agentId) {
1717
+ const { tenantId, projectId, graphId, subAgentId, baseUrl, apiKey } = executionContext;
1718
+ if (!subAgentId) {
1705
1719
  throw new Error("Agent ID is required");
1706
1720
  }
1707
- const dbAgent = await agentsCore.getAgentById(dbClient_default)({
1721
+ const dbAgent = await agentsCore.getSubAgentById(dbClient_default)({
1708
1722
  scopes: { tenantId, projectId, graphId },
1709
- agentId
1723
+ subAgentId
1710
1724
  });
1711
1725
  if (!dbAgent) {
1712
1726
  return null;
@@ -1727,7 +1741,7 @@ init_logger();
1727
1741
 
1728
1742
  // src/agents/ModelFactory.ts
1729
1743
  init_logger();
1730
- var logger5 = agentsCore.getLogger("ModelFactory");
1744
+ var logger4 = agentsCore.getLogger("ModelFactory");
1731
1745
  var _ModelFactory = class _ModelFactory {
1732
1746
  /**
1733
1747
  * Create a provider instance with custom configuration
@@ -1789,7 +1803,7 @@ var _ModelFactory = class _ModelFactory {
1789
1803
  }
1790
1804
  const modelString = modelSettings.model.trim();
1791
1805
  const { provider, modelName } = _ModelFactory.parseModelString(modelString);
1792
- logger5.debug(
1806
+ logger4.debug(
1793
1807
  {
1794
1808
  provider,
1795
1809
  model: modelName,
@@ -1800,7 +1814,7 @@ var _ModelFactory = class _ModelFactory {
1800
1814
  );
1801
1815
  const providerConfig = _ModelFactory.extractProviderConfig(modelSettings.providerOptions);
1802
1816
  if (Object.keys(providerConfig).length > 0) {
1803
- logger5.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
1817
+ logger4.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
1804
1818
  const customProvider = _ModelFactory.createProvider(provider, providerConfig);
1805
1819
  return customProvider.languageModel(modelName);
1806
1820
  }
@@ -1919,7 +1933,7 @@ var ModelFactory = _ModelFactory;
1919
1933
 
1920
1934
  // src/agents/ToolSessionManager.ts
1921
1935
  init_logger();
1922
- var logger6 = agentsCore.getLogger("ToolSessionManager");
1936
+ var logger5 = agentsCore.getLogger("ToolSessionManager");
1923
1937
  var _ToolSessionManager = class _ToolSessionManager {
1924
1938
  // 5 minutes
1925
1939
  constructor() {
@@ -1954,7 +1968,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1954
1968
  createdAt: Date.now()
1955
1969
  };
1956
1970
  this.sessions.set(sessionId, session);
1957
- logger6.debug(
1971
+ logger5.debug(
1958
1972
  {
1959
1973
  sessionId,
1960
1974
  tenantId,
@@ -1972,10 +1986,10 @@ var _ToolSessionManager = class _ToolSessionManager {
1972
1986
  */
1973
1987
  ensureGraphSession(sessionId, tenantId, projectId, contextId, taskId) {
1974
1988
  if (this.sessions.has(sessionId)) {
1975
- logger6.debug({ sessionId }, "Graph session already exists, reusing");
1989
+ logger5.debug({ sessionId }, "Graph session already exists, reusing");
1976
1990
  return sessionId;
1977
1991
  }
1978
- logger6.debug(
1992
+ logger5.debug(
1979
1993
  { sessionId, tenantId, contextId, taskId },
1980
1994
  "Creating new graph-scoped tool session"
1981
1995
  );
@@ -1987,7 +2001,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1987
2001
  recordToolResult(sessionId, toolResult) {
1988
2002
  const session = this.sessions.get(sessionId);
1989
2003
  if (!session) {
1990
- logger6.warn(
2004
+ logger5.warn(
1991
2005
  {
1992
2006
  sessionId,
1993
2007
  toolCallId: toolResult.toolCallId,
@@ -1999,7 +2013,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1999
2013
  return;
2000
2014
  }
2001
2015
  session.toolResults.set(toolResult.toolCallId, toolResult);
2002
- logger6.debug(
2016
+ logger5.debug(
2003
2017
  {
2004
2018
  sessionId,
2005
2019
  toolCallId: toolResult.toolCallId,
@@ -2014,7 +2028,7 @@ var _ToolSessionManager = class _ToolSessionManager {
2014
2028
  getToolResult(sessionId, toolCallId) {
2015
2029
  const session = this.sessions.get(sessionId);
2016
2030
  if (!session) {
2017
- logger6.warn(
2031
+ logger5.warn(
2018
2032
  {
2019
2033
  sessionId,
2020
2034
  toolCallId,
@@ -2027,7 +2041,7 @@ var _ToolSessionManager = class _ToolSessionManager {
2027
2041
  }
2028
2042
  const result = session.toolResults.get(toolCallId);
2029
2043
  if (!result) {
2030
- logger6.warn(
2044
+ logger5.warn(
2031
2045
  {
2032
2046
  sessionId,
2033
2047
  toolCallId,
@@ -2037,7 +2051,7 @@ var _ToolSessionManager = class _ToolSessionManager {
2037
2051
  "Tool result not found"
2038
2052
  );
2039
2053
  } else {
2040
- logger6.debug(
2054
+ logger5.debug(
2041
2055
  {
2042
2056
  sessionId,
2043
2057
  toolCallId,
@@ -2076,10 +2090,10 @@ var _ToolSessionManager = class _ToolSessionManager {
2076
2090
  }
2077
2091
  for (const sessionId of expiredSessions) {
2078
2092
  this.sessions.delete(sessionId);
2079
- logger6.debug({ sessionId }, "Cleaned up expired tool session");
2093
+ logger5.debug({ sessionId }, "Cleaned up expired tool session");
2080
2094
  }
2081
2095
  if (expiredSessions.length > 0) {
2082
- logger6.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
2096
+ logger5.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
2083
2097
  }
2084
2098
  }
2085
2099
  };
@@ -2162,7 +2176,7 @@ function extractFullFields(schema) {
2162
2176
  }
2163
2177
 
2164
2178
  // src/services/ArtifactService.ts
2165
- var logger8 = agentsCore.getLogger("ArtifactService");
2179
+ var logger7 = agentsCore.getLogger("ArtifactService");
2166
2180
  var _ArtifactService = class _ArtifactService {
2167
2181
  constructor(context) {
2168
2182
  this.context = context;
@@ -2194,7 +2208,7 @@ var _ArtifactService = class _ArtifactService {
2194
2208
  id: taskId
2195
2209
  });
2196
2210
  if (!task) {
2197
- logger8.warn({ taskId }, "Task not found when fetching artifacts");
2211
+ logger7.warn({ taskId }, "Task not found when fetching artifacts");
2198
2212
  continue;
2199
2213
  }
2200
2214
  const taskArtifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
@@ -2212,21 +2226,21 @@ var _ArtifactService = class _ArtifactService {
2212
2226
  }
2213
2227
  }
2214
2228
  } catch (error) {
2215
- logger8.error({ error, contextId }, "Error loading context artifacts");
2229
+ logger7.error({ error, contextId }, "Error loading context artifacts");
2216
2230
  }
2217
2231
  return artifacts;
2218
2232
  }
2219
2233
  /**
2220
2234
  * Create artifact from tool result and request data
2221
2235
  */
2222
- async createArtifact(request, agentId) {
2236
+ async createArtifact(request, subAgentId) {
2223
2237
  if (!this.context.sessionId) {
2224
- logger8.warn({ request }, "No session ID available for artifact creation");
2238
+ logger7.warn({ request }, "No session ID available for artifact creation");
2225
2239
  return null;
2226
2240
  }
2227
2241
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
2228
2242
  if (!toolResult) {
2229
- logger8.warn(
2243
+ logger7.warn(
2230
2244
  { request, sessionId: this.context.sessionId },
2231
2245
  "Tool result not found for artifact"
2232
2246
  );
@@ -2242,7 +2256,7 @@ var _ArtifactService = class _ArtifactService {
2242
2256
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
2243
2257
  }
2244
2258
  if (!selectedData) {
2245
- logger8.warn(
2259
+ logger7.warn(
2246
2260
  {
2247
2261
  request,
2248
2262
  baseSelector: request.baseSelector
@@ -2287,7 +2301,7 @@ var _ArtifactService = class _ArtifactService {
2287
2301
  type: request.type,
2288
2302
  data: cleanedSummaryData
2289
2303
  };
2290
- await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, agentId);
2304
+ await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, subAgentId);
2291
2305
  await this.cacheArtifact(
2292
2306
  request.artifactId,
2293
2307
  request.toolCallId,
@@ -2296,7 +2310,7 @@ var _ArtifactService = class _ArtifactService {
2296
2310
  );
2297
2311
  return artifactData;
2298
2312
  } catch (error) {
2299
- logger8.error({ error, request }, "Failed to create artifact");
2313
+ logger7.error({ error, request }, "Failed to create artifact");
2300
2314
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
2301
2315
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
2302
2316
  }
@@ -2325,7 +2339,7 @@ var _ArtifactService = class _ArtifactService {
2325
2339
  }
2326
2340
  try {
2327
2341
  if (!this.context.projectId || !this.context.taskId) {
2328
- logger8.warn(
2342
+ logger7.warn(
2329
2343
  { artifactId, toolCallId },
2330
2344
  "No projectId or taskId available for artifact lookup"
2331
2345
  );
@@ -2340,7 +2354,7 @@ var _ArtifactService = class _ArtifactService {
2340
2354
  return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
2341
2355
  }
2342
2356
  } catch (error) {
2343
- logger8.warn(
2357
+ logger7.warn(
2344
2358
  { artifactId, toolCallId, taskId: this.context.taskId, error },
2345
2359
  "Failed to fetch artifact"
2346
2360
  );
@@ -2371,7 +2385,7 @@ var _ArtifactService = class _ArtifactService {
2371
2385
  }
2372
2386
  try {
2373
2387
  if (!this.context.projectId || !this.context.taskId) {
2374
- logger8.warn(
2388
+ logger7.warn(
2375
2389
  { artifactId, toolCallId },
2376
2390
  "No projectId or taskId available for artifact lookup"
2377
2391
  );
@@ -2386,7 +2400,7 @@ var _ArtifactService = class _ArtifactService {
2386
2400
  return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
2387
2401
  }
2388
2402
  } catch (error) {
2389
- logger8.warn(
2403
+ logger7.warn(
2390
2404
  { artifactId, toolCallId, taskId: this.context.taskId, error },
2391
2405
  "Failed to fetch artifact"
2392
2406
  );
@@ -2422,8 +2436,8 @@ var _ArtifactService = class _ArtifactService {
2422
2436
  /**
2423
2437
  * Persist artifact to database via graph session
2424
2438
  */
2425
- async persistArtifact(request, summaryData, fullData, agentId) {
2426
- const effectiveAgentId = agentId || this.context.agentId;
2439
+ async persistArtifact(request, summaryData, fullData, subAgentId) {
2440
+ const effectiveAgentId = subAgentId || this.context.subAgentId;
2427
2441
  if (this.context.streamRequestId && effectiveAgentId && this.context.taskId) {
2428
2442
  await graphSessionManager.recordEvent(
2429
2443
  this.context.streamRequestId,
@@ -2436,7 +2450,7 @@ var _ArtifactService = class _ArtifactService {
2436
2450
  artifactType: request.type,
2437
2451
  summaryData,
2438
2452
  data: fullData,
2439
- agentId: effectiveAgentId,
2453
+ subAgentId: effectiveAgentId,
2440
2454
  metadata: {
2441
2455
  toolCallId: request.toolCallId,
2442
2456
  baseSelector: request.baseSelector,
@@ -2451,14 +2465,14 @@ var _ArtifactService = class _ArtifactService {
2451
2465
  }
2452
2466
  );
2453
2467
  } else {
2454
- logger8.warn(
2468
+ logger7.warn(
2455
2469
  {
2456
2470
  artifactId: request.artifactId,
2457
2471
  hasStreamRequestId: !!this.context.streamRequestId,
2458
2472
  hasAgentId: !!effectiveAgentId,
2459
2473
  hasTaskId: !!this.context.taskId,
2460
- passedAgentId: agentId,
2461
- contextAgentId: this.context.agentId
2474
+ passedAgentId: subAgentId,
2475
+ contextAgentId: this.context.subAgentId
2462
2476
  },
2463
2477
  "Skipping artifact_saved event - missing required context"
2464
2478
  );
@@ -2526,7 +2540,7 @@ var _ArtifactService = class _ArtifactService {
2526
2540
  summaryData = this.filterBySchema(artifact.data, previewSchema);
2527
2541
  fullData = this.filterBySchema(artifact.data, fullSchema);
2528
2542
  } catch (error) {
2529
- logger8.warn(
2543
+ logger7.warn(
2530
2544
  {
2531
2545
  artifactType: artifact.type,
2532
2546
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2564,7 +2578,7 @@ var _ArtifactService = class _ArtifactService {
2564
2578
  artifact: artifactToSave
2565
2579
  });
2566
2580
  if (!result.created && result.existing) {
2567
- logger8.debug(
2581
+ logger7.debug(
2568
2582
  {
2569
2583
  artifactId: artifact.artifactId,
2570
2584
  taskId: this.context.taskId
@@ -2617,7 +2631,7 @@ var _ArtifactService = class _ArtifactService {
2617
2631
  extracted[propName] = this.cleanEscapedContent(rawValue);
2618
2632
  }
2619
2633
  } catch (error) {
2620
- logger8.warn(
2634
+ logger7.warn(
2621
2635
  { propName, selector, error: error instanceof Error ? error.message : "Unknown error" },
2622
2636
  "Failed to extract property"
2623
2637
  );
@@ -2649,7 +2663,7 @@ var _ArtifactService = class _ArtifactService {
2649
2663
  extracted[fieldName] = this.cleanEscapedContent(rawValue);
2650
2664
  }
2651
2665
  } catch (error) {
2652
- logger8.warn(
2666
+ logger7.warn(
2653
2667
  { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
2654
2668
  "Failed to extract schema field"
2655
2669
  );
@@ -2680,7 +2694,7 @@ __publicField(_ArtifactService, "selectorCache", /* @__PURE__ */ new Map());
2680
2694
  var ArtifactService = _ArtifactService;
2681
2695
 
2682
2696
  // src/services/ArtifactParser.ts
2683
- var logger9 = agentsCore.getLogger("ArtifactParser");
2697
+ var logger8 = agentsCore.getLogger("ArtifactParser");
2684
2698
  var _ArtifactParser = class _ArtifactParser {
2685
2699
  constructor(tenantId, options) {
2686
2700
  __publicField(this, "artifactService");
@@ -2768,7 +2782,7 @@ var _ArtifactParser = class _ArtifactParser {
2768
2782
  attrs[key] = value;
2769
2783
  }
2770
2784
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
2771
- logger9.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2785
+ logger8.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2772
2786
  return null;
2773
2787
  }
2774
2788
  return {
@@ -2799,7 +2813,7 @@ var _ArtifactParser = class _ArtifactParser {
2799
2813
  /**
2800
2814
  * Extract artifact data from a create annotation - delegates to service
2801
2815
  */
2802
- async extractFromCreateAnnotation(annotation, agentId) {
2816
+ async extractFromCreateAnnotation(annotation, subAgentId) {
2803
2817
  const request = {
2804
2818
  artifactId: annotation.artifactId,
2805
2819
  toolCallId: annotation.toolCallId,
@@ -2807,21 +2821,21 @@ var _ArtifactParser = class _ArtifactParser {
2807
2821
  baseSelector: annotation.baseSelector,
2808
2822
  detailsSelector: annotation.detailsSelector
2809
2823
  };
2810
- return this.artifactService.createArtifact(request, agentId);
2824
+ return this.artifactService.createArtifact(request, subAgentId);
2811
2825
  }
2812
2826
  /**
2813
2827
  * Parse text with artifact markers into parts array
2814
2828
  * Handles both artifact:ref and artifact:create tags
2815
2829
  * Can work with or without pre-fetched artifact map
2816
2830
  */
2817
- async parseText(text, artifactMap, agentId) {
2831
+ async parseText(text, artifactMap, subAgentId) {
2818
2832
  let processedText = text;
2819
2833
  const createAnnotations = this.parseCreateAnnotations(text);
2820
2834
  const createdArtifactData = /* @__PURE__ */ new Map();
2821
2835
  const failedAnnotations = [];
2822
2836
  for (const annotation of createAnnotations) {
2823
2837
  try {
2824
- const artifactData = await this.extractFromCreateAnnotation(annotation, agentId);
2838
+ const artifactData = await this.extractFromCreateAnnotation(annotation, subAgentId);
2825
2839
  if (artifactData && annotation.raw) {
2826
2840
  createdArtifactData.set(annotation.raw, artifactData);
2827
2841
  } else if (annotation.raw) {
@@ -2829,7 +2843,7 @@ var _ArtifactParser = class _ArtifactParser {
2829
2843
  `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
2830
2844
  );
2831
2845
  processedText = processedText.replace(annotation.raw, "");
2832
- logger9.warn(
2846
+ logger8.warn(
2833
2847
  { annotation, artifactData },
2834
2848
  "Removed failed artifact:create annotation from output"
2835
2849
  );
@@ -2840,11 +2854,11 @@ var _ArtifactParser = class _ArtifactParser {
2840
2854
  if (annotation.raw) {
2841
2855
  processedText = processedText.replace(annotation.raw, "");
2842
2856
  }
2843
- logger9.error({ annotation, error }, "Failed to extract artifact from create annotation");
2857
+ logger8.error({ annotation, error }, "Failed to extract artifact from create annotation");
2844
2858
  }
2845
2859
  }
2846
2860
  if (failedAnnotations.length > 0) {
2847
- logger9.warn(
2861
+ logger8.warn(
2848
2862
  {
2849
2863
  failedCount: failedAnnotations.length,
2850
2864
  failures: failedAnnotations
@@ -2908,7 +2922,7 @@ var _ArtifactParser = class _ArtifactParser {
2908
2922
  /**
2909
2923
  * Process object/dataComponents for artifact components
2910
2924
  */
2911
- async parseObject(obj, artifactMap, agentId) {
2925
+ async parseObject(obj, artifactMap, subAgentId) {
2912
2926
  if (obj?.dataComponents && Array.isArray(obj.dataComponents)) {
2913
2927
  const parts = [];
2914
2928
  for (const component of obj.dataComponents) {
@@ -2932,7 +2946,7 @@ var _ArtifactParser = class _ArtifactParser {
2932
2946
  });
2933
2947
  }
2934
2948
  } else if (this.isArtifactCreateComponent(component)) {
2935
- const createData = await this.extractFromArtifactCreateComponent(component, agentId);
2949
+ const createData = await this.extractFromArtifactCreateComponent(component, subAgentId);
2936
2950
  if (createData) {
2937
2951
  parts.push({
2938
2952
  kind: "data",
@@ -2973,7 +2987,7 @@ var _ArtifactParser = class _ArtifactParser {
2973
2987
  ] : [];
2974
2988
  }
2975
2989
  if (this.isArtifactCreateComponent(obj)) {
2976
- const createData = await this.extractFromArtifactCreateComponent(obj, agentId);
2990
+ const createData = await this.extractFromArtifactCreateComponent(obj, subAgentId);
2977
2991
  return createData ? [
2978
2992
  {
2979
2993
  kind: "data",
@@ -3005,7 +3019,7 @@ var _ArtifactParser = class _ArtifactParser {
3005
3019
  /**
3006
3020
  * Extract artifact from ArtifactCreate component
3007
3021
  */
3008
- async extractFromArtifactCreateComponent(component, agentId) {
3022
+ async extractFromArtifactCreateComponent(component, subAgentId) {
3009
3023
  const props = component.props;
3010
3024
  if (!props) {
3011
3025
  return null;
@@ -3017,7 +3031,7 @@ var _ArtifactParser = class _ArtifactParser {
3017
3031
  baseSelector: props.base_selector,
3018
3032
  detailsSelector: props.details_selector || {}
3019
3033
  };
3020
- return await this.extractFromCreateAnnotation(annotation, agentId);
3034
+ return await this.extractFromCreateAnnotation(annotation, subAgentId);
3021
3035
  }
3022
3036
  /**
3023
3037
  * Get artifact data - delegates to service
@@ -3057,7 +3071,7 @@ __publicField(_ArtifactParser, "INCOMPLETE_CREATE_REGEX", /<artifact:create(?![^
3057
3071
  var ArtifactParser = _ArtifactParser;
3058
3072
 
3059
3073
  // src/services/GraphSession.ts
3060
- var logger10 = agentsCore.getLogger("GraphSession");
3074
+ var logger9 = agentsCore.getLogger("GraphSession");
3061
3075
  var GraphSession = class {
3062
3076
  // Whether to send data operations
3063
3077
  constructor(sessionId, messageId, graphId, tenantId, projectId, contextId) {
@@ -3090,7 +3104,7 @@ var GraphSession = class {
3090
3104
  __publicField(this, "artifactParser");
3091
3105
  // Session-scoped ArtifactParser instance
3092
3106
  __publicField(this, "isEmitOperations", false);
3093
- logger10.debug({ sessionId, messageId, graphId }, "GraphSession created");
3107
+ logger9.debug({ sessionId, messageId, graphId }, "GraphSession created");
3094
3108
  if (tenantId && projectId) {
3095
3109
  toolSessionManager.createSessionWithId(
3096
3110
  sessionId,
@@ -3104,7 +3118,6 @@ var GraphSession = class {
3104
3118
  tenantId,
3105
3119
  projectId,
3106
3120
  sessionId,
3107
- // Same ID as ToolSession
3108
3121
  contextId,
3109
3122
  taskId: `task_${contextId}-${messageId}`,
3110
3123
  streamRequestId: sessionId
@@ -3125,7 +3138,7 @@ var GraphSession = class {
3125
3138
  */
3126
3139
  enableEmitOperations() {
3127
3140
  this.isEmitOperations = true;
3128
- logger10.info(
3141
+ logger9.info(
3129
3142
  { sessionId: this.sessionId },
3130
3143
  "\u{1F50D} DEBUG: Emit operations enabled for GraphSession"
3131
3144
  );
@@ -3142,14 +3155,14 @@ var GraphSession = class {
3142
3155
  label: this.generateEventLabel(event),
3143
3156
  details: {
3144
3157
  timestamp: event.timestamp,
3145
- agentId: event.agentId,
3158
+ subAgentId: event.subAgentId,
3146
3159
  data: event.data
3147
3160
  }
3148
3161
  };
3149
3162
  await streamHelper.writeOperation(formattedOperation);
3150
3163
  }
3151
3164
  } catch (error) {
3152
- logger10.error(
3165
+ logger9.error(
3153
3166
  {
3154
3167
  sessionId: this.sessionId,
3155
3168
  eventType: event.eventType,
@@ -3165,29 +3178,19 @@ var GraphSession = class {
3165
3178
  generateEventLabel(event) {
3166
3179
  switch (event.eventType) {
3167
3180
  case "agent_generate":
3168
- return `Agent ${event.agentId} generating response`;
3181
+ return `Agent ${event.subAgentId} generating response`;
3169
3182
  case "agent_reasoning":
3170
- return `Agent ${event.agentId} reasoning through request`;
3171
- case "tool_execution": {
3172
- const toolData = event.data;
3173
- return `Tool execution: ${toolData.toolName || "unknown"}`;
3174
- }
3175
- case "transfer": {
3176
- const transferData = event.data;
3177
- return `Agent transfer: ${transferData.fromAgent} \u2192 ${transferData.targetAgent}`;
3178
- }
3179
- case "delegation_sent": {
3180
- const delegationData = event.data;
3181
- return `Task delegated: ${delegationData.fromAgent} \u2192 ${delegationData.targetAgent}`;
3182
- }
3183
- case "delegation_returned": {
3184
- const returnData = event.data;
3185
- return `Task completed: ${returnData.targetAgent} \u2192 ${returnData.fromAgent}`;
3186
- }
3187
- case "artifact_saved": {
3188
- const artifactData = event.data;
3189
- return `Artifact saved: ${artifactData.artifactType || "unknown type"}`;
3190
- }
3183
+ return `Agent ${event.subAgentId} reasoning through request`;
3184
+ case "tool_execution":
3185
+ return `Tool execution: ${event.data.toolName || "unknown"}`;
3186
+ case "transfer":
3187
+ return `Agent transfer: ${event.data.fromSubAgent} \u2192 ${event.data.targetSubAgent}`;
3188
+ case "delegation_sent":
3189
+ return `Task delegated: ${event.data.fromSubAgent} \u2192 ${event.data.targetSubAgent}`;
3190
+ case "delegation_returned":
3191
+ return `Task completed: ${event.data.targetSubAgent} \u2192 ${event.data.fromSubAgent}`;
3192
+ case "artifact_saved":
3193
+ return `Artifact saved: ${event.data.artifactType || "unknown type"}`;
3191
3194
  default:
3192
3195
  return `${event.eventType} event`;
3193
3196
  }
@@ -3212,7 +3215,7 @@ var GraphSession = class {
3212
3215
  if (this.statusUpdateState.config.timeInSeconds) {
3213
3216
  this.statusUpdateTimer = setInterval(async () => {
3214
3217
  if (!this.statusUpdateState || this.isEnded) {
3215
- logger10.debug(
3218
+ logger9.debug(
3216
3219
  { sessionId: this.sessionId },
3217
3220
  "Timer triggered but session already cleaned up or ended"
3218
3221
  );
@@ -3224,7 +3227,7 @@ var GraphSession = class {
3224
3227
  }
3225
3228
  await this.checkAndSendTimeBasedUpdate();
3226
3229
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
3227
- logger10.info(
3230
+ logger9.info(
3228
3231
  {
3229
3232
  sessionId: this.sessionId,
3230
3233
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -3235,22 +3238,24 @@ var GraphSession = class {
3235
3238
  }
3236
3239
  /**
3237
3240
  * Record an event in the session and trigger status updates if configured
3241
+ * Generic type parameter T ensures eventType and data are correctly paired
3238
3242
  */
3239
- recordEvent(eventType, agentId, data) {
3243
+ recordEvent(eventType, subAgentId, data) {
3240
3244
  if (this.isEmitOperations) {
3241
- this.sendDataOperation({
3245
+ const dataOpEvent = {
3242
3246
  timestamp: Date.now(),
3243
3247
  eventType,
3244
- agentId,
3248
+ subAgentId,
3245
3249
  data
3246
- });
3250
+ };
3251
+ this.sendDataOperation(dataOpEvent);
3247
3252
  }
3248
3253
  if (this.isEnded) {
3249
- logger10.debug(
3254
+ logger9.debug(
3250
3255
  {
3251
3256
  sessionId: this.sessionId,
3252
3257
  eventType,
3253
- agentId
3258
+ subAgentId
3254
3259
  },
3255
3260
  "Event received after session ended - ignoring"
3256
3261
  );
@@ -3259,59 +3264,62 @@ var GraphSession = class {
3259
3264
  const event = {
3260
3265
  timestamp: Date.now(),
3261
3266
  eventType,
3262
- agentId,
3267
+ subAgentId,
3263
3268
  data
3264
3269
  };
3265
3270
  this.events.push(event);
3266
- if (eventType === "artifact_saved" && data.pendingGeneration) {
3267
- const artifactId = data.artifactId;
3268
- if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
3269
- logger10.warn(
3270
- {
3271
- sessionId: this.sessionId,
3272
- artifactId,
3273
- pendingCount: this.pendingArtifacts.size,
3274
- maxAllowed: this.MAX_PENDING_ARTIFACTS
3275
- },
3276
- "Too many pending artifacts, skipping processing"
3277
- );
3278
- return;
3279
- }
3280
- this.pendingArtifacts.add(artifactId);
3281
- setImmediate(() => {
3282
- const artifactDataWithAgent = { ...data, agentId };
3283
- this.processArtifact(artifactDataWithAgent).then(() => {
3284
- this.pendingArtifacts.delete(artifactId);
3285
- this.artifactProcessingErrors.delete(artifactId);
3286
- }).catch((error) => {
3287
- const errorCount = (this.artifactProcessingErrors.get(artifactId) || 0) + 1;
3288
- this.artifactProcessingErrors.set(artifactId, errorCount);
3289
- if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
3271
+ if (eventType === "artifact_saved") {
3272
+ const artifactData = data;
3273
+ if (artifactData.pendingGeneration) {
3274
+ const artifactId = artifactData.artifactId;
3275
+ if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
3276
+ logger9.warn(
3277
+ {
3278
+ sessionId: this.sessionId,
3279
+ artifactId,
3280
+ pendingCount: this.pendingArtifacts.size,
3281
+ maxAllowed: this.MAX_PENDING_ARTIFACTS
3282
+ },
3283
+ "Too many pending artifacts, skipping processing"
3284
+ );
3285
+ return;
3286
+ }
3287
+ this.pendingArtifacts.add(artifactId);
3288
+ setImmediate(() => {
3289
+ const artifactDataWithAgent = { ...artifactData, subAgentId };
3290
+ this.processArtifact(artifactDataWithAgent).then(() => {
3290
3291
  this.pendingArtifacts.delete(artifactId);
3291
- logger10.error(
3292
- {
3293
- sessionId: this.sessionId,
3294
- artifactId,
3295
- errorCount,
3296
- maxRetries: this.MAX_ARTIFACT_RETRIES,
3297
- error: error instanceof Error ? error.message : "Unknown error",
3298
- stack: error instanceof Error ? error.stack : void 0
3299
- },
3300
- "Artifact processing failed after max retries, giving up"
3301
- );
3302
- } else {
3303
- logger10.warn(
3304
- {
3305
- sessionId: this.sessionId,
3306
- artifactId,
3307
- errorCount,
3308
- error: error instanceof Error ? error.message : "Unknown error"
3309
- },
3310
- "Artifact processing failed, may retry"
3311
- );
3312
- }
3292
+ this.artifactProcessingErrors.delete(artifactId);
3293
+ }).catch((error) => {
3294
+ const errorCount = (this.artifactProcessingErrors.get(artifactId) || 0) + 1;
3295
+ this.artifactProcessingErrors.set(artifactId, errorCount);
3296
+ if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
3297
+ this.pendingArtifacts.delete(artifactId);
3298
+ logger9.error(
3299
+ {
3300
+ sessionId: this.sessionId,
3301
+ artifactId,
3302
+ errorCount,
3303
+ maxRetries: this.MAX_ARTIFACT_RETRIES,
3304
+ error: error instanceof Error ? error.message : "Unknown error",
3305
+ stack: error instanceof Error ? error.stack : void 0
3306
+ },
3307
+ "Artifact processing failed after max retries, giving up"
3308
+ );
3309
+ } else {
3310
+ logger9.warn(
3311
+ {
3312
+ sessionId: this.sessionId,
3313
+ artifactId,
3314
+ errorCount,
3315
+ error: error instanceof Error ? error.message : "Unknown error"
3316
+ },
3317
+ "Artifact processing failed, may retry"
3318
+ );
3319
+ }
3320
+ });
3313
3321
  });
3314
- });
3322
+ }
3315
3323
  }
3316
3324
  if (!this.isEnded) {
3317
3325
  this.checkStatusUpdates();
@@ -3322,14 +3330,14 @@ var GraphSession = class {
3322
3330
  */
3323
3331
  checkStatusUpdates() {
3324
3332
  if (this.isEnded) {
3325
- logger10.debug(
3333
+ logger9.debug(
3326
3334
  { sessionId: this.sessionId },
3327
3335
  "Session has ended - skipping status update check"
3328
3336
  );
3329
3337
  return;
3330
3338
  }
3331
3339
  if (!this.statusUpdateState) {
3332
- logger10.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
3340
+ logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
3333
3341
  return;
3334
3342
  }
3335
3343
  const statusUpdateState = this.statusUpdateState;
@@ -3340,11 +3348,11 @@ var GraphSession = class {
3340
3348
  */
3341
3349
  async checkAndSendTimeBasedUpdate() {
3342
3350
  if (this.isEnded) {
3343
- logger10.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
3351
+ logger9.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
3344
3352
  return;
3345
3353
  }
3346
3354
  if (!this.statusUpdateState) {
3347
- logger10.debug(
3355
+ logger9.debug(
3348
3356
  { sessionId: this.sessionId },
3349
3357
  "No status updates configured for time-based check"
3350
3358
  );
@@ -3357,7 +3365,7 @@ var GraphSession = class {
3357
3365
  try {
3358
3366
  await this.generateAndSendUpdate();
3359
3367
  } catch (error) {
3360
- logger10.error(
3368
+ logger9.error(
3361
3369
  {
3362
3370
  sessionId: this.sessionId,
3363
3371
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3381,8 +3389,8 @@ var GraphSession = class {
3381
3389
  /**
3382
3390
  * Get events filtered by agent
3383
3391
  */
3384
- getEventsByAgent(agentId) {
3385
- return this.events.filter((event) => event.agentId === agentId);
3392
+ getEventsByAgent(subAgentId) {
3393
+ return this.events.filter((event) => event.subAgentId === subAgentId);
3386
3394
  }
3387
3395
  /**
3388
3396
  * Get summary of session activity
@@ -3397,7 +3405,7 @@ var GraphSession = class {
3397
3405
  );
3398
3406
  const agentCounts = this.events.reduce(
3399
3407
  (counts, event) => {
3400
- counts[event.agentId] = (counts[event.agentId] || 0) + 1;
3408
+ counts[event.subAgentId] = (counts[event.subAgentId] || 0) + 1;
3401
3409
  return counts;
3402
3410
  },
3403
3411
  {}
@@ -3460,29 +3468,29 @@ var GraphSession = class {
3460
3468
  */
3461
3469
  async generateAndSendUpdate() {
3462
3470
  if (this.isEnded) {
3463
- logger10.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
3471
+ logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
3464
3472
  return;
3465
3473
  }
3466
3474
  if (this.isTextStreaming) {
3467
- logger10.debug(
3475
+ logger9.debug(
3468
3476
  { sessionId: this.sessionId },
3469
3477
  "Text is currently streaming - skipping status update"
3470
3478
  );
3471
3479
  return;
3472
3480
  }
3473
3481
  if (this.isGeneratingUpdate) {
3474
- logger10.debug(
3482
+ logger9.debug(
3475
3483
  { sessionId: this.sessionId },
3476
3484
  "Update already in progress - skipping duplicate generation"
3477
3485
  );
3478
3486
  return;
3479
3487
  }
3480
3488
  if (!this.statusUpdateState) {
3481
- logger10.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
3489
+ logger9.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
3482
3490
  return;
3483
3491
  }
3484
3492
  if (!this.graphId) {
3485
- logger10.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
3493
+ logger9.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
3486
3494
  return;
3487
3495
  }
3488
3496
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -3494,7 +3502,7 @@ var GraphSession = class {
3494
3502
  try {
3495
3503
  const streamHelper = getStreamHelper(this.sessionId);
3496
3504
  if (!streamHelper) {
3497
- logger10.warn(
3505
+ logger9.warn(
3498
3506
  { sessionId: this.sessionId },
3499
3507
  "No stream helper found - cannot send status update"
3500
3508
  );
@@ -3514,7 +3522,7 @@ var GraphSession = class {
3514
3522
  if (result.summaries && result.summaries.length > 0) {
3515
3523
  for (const summary of result.summaries) {
3516
3524
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
3517
- logger10.warn(
3525
+ logger9.warn(
3518
3526
  {
3519
3527
  sessionId: this.sessionId,
3520
3528
  summary
@@ -3551,7 +3559,7 @@ var GraphSession = class {
3551
3559
  this.statusUpdateState.lastEventCount = this.events.length;
3552
3560
  }
3553
3561
  } catch (error) {
3554
- logger10.error(
3562
+ logger9.error(
3555
3563
  {
3556
3564
  sessionId: this.sessionId,
3557
3565
  error: error instanceof Error ? error.message : "Unknown error",
@@ -3589,7 +3597,7 @@ var GraphSession = class {
3589
3597
  this.releaseUpdateLock();
3590
3598
  }
3591
3599
  } catch (error) {
3592
- logger10.error(
3600
+ logger9.error(
3593
3601
  {
3594
3602
  sessionId: this.sessionId,
3595
3603
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3667,7 +3675,7 @@ User's Question/Context:
3667
3675
  ${conversationHistory}
3668
3676
  ` : "";
3669
3677
  } catch (error) {
3670
- logger10.warn(
3678
+ logger9.warn(
3671
3679
  { sessionId: this.sessionId, error },
3672
3680
  "Failed to fetch conversation history for structured status update"
3673
3681
  );
@@ -3801,7 +3809,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3801
3809
  return { summaries };
3802
3810
  } catch (error) {
3803
3811
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3804
- logger10.error({ error }, "Failed to generate structured update, using fallback");
3812
+ logger9.error({ error }, "Failed to generate structured update, using fallback");
3805
3813
  return { summaries: [] };
3806
3814
  } finally {
3807
3815
  span.end();
@@ -3827,7 +3835,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3827
3835
  */
3828
3836
  buildZodSchemaFromJson(jsonSchema) {
3829
3837
  const properties = {};
3830
- properties["label"] = z6.z.string().describe(
3838
+ properties.label = z6.z.string().describe(
3831
3839
  '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.'
3832
3840
  );
3833
3841
  for (const [key, value] of Object.entries(jsonSchema.properties)) {
@@ -3896,11 +3904,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3896
3904
  for (const event of events) {
3897
3905
  switch (event.eventType) {
3898
3906
  case "tool_execution": {
3899
- const data = event.data;
3900
- const resultStr = JSON.stringify(data.result);
3907
+ const resultStr = JSON.stringify(event.data.result);
3901
3908
  activities.push(
3902
- `\u{1F527} **${data.toolName}** ${data.duration ? `(${data.duration}ms)` : ""}
3903
- \u{1F4E5} Input: ${JSON.stringify(data.args)}
3909
+ `\u{1F527} **${event.data.toolName}** ${event.data.duration ? `(${event.data.duration}ms)` : ""}
3910
+ \u{1F4E5} Input: ${JSON.stringify(event.data.args)}
3904
3911
  \u{1F4E4} Output: ${resultStr}`
3905
3912
  );
3906
3913
  break;
@@ -3912,23 +3919,24 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3912
3919
  case "artifact_saved":
3913
3920
  break;
3914
3921
  case "agent_reasoning": {
3915
- const data = event.data;
3916
3922
  activities.push(
3917
3923
  `\u2699\uFE0F **Analyzing request**
3918
- Details: ${JSON.stringify(data.parts, null, 2)}`
3924
+ Details: ${JSON.stringify(event.data.parts, null, 2)}`
3919
3925
  );
3920
3926
  break;
3921
3927
  }
3922
3928
  case "agent_generate": {
3923
- const data = event.data;
3924
3929
  activities.push(
3925
3930
  `\u2699\uFE0F **Preparing response**
3926
- Details: ${JSON.stringify(data.parts, null, 2)}`
3931
+ Details: ${JSON.stringify(event.data.parts, null, 2)}`
3927
3932
  );
3928
3933
  break;
3929
3934
  }
3930
3935
  default: {
3931
- activities.push(`\u{1F4CB} **${event.eventType}**: ${JSON.stringify(event.data, null, 2)}`);
3936
+ const safeEvent = event;
3937
+ activities.push(
3938
+ `\u{1F4CB} **${safeEvent.eventType}**: ${JSON.stringify(safeEvent.data, null, 2)}`
3939
+ );
3932
3940
  break;
3933
3941
  }
3934
3942
  }
@@ -3946,7 +3954,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3946
3954
  "graph_session.id": this.sessionId,
3947
3955
  "artifact.id": artifactData.artifactId,
3948
3956
  "artifact.type": artifactData.artifactType || "unknown",
3949
- "artifact.agent_id": artifactData.agentId || "unknown",
3957
+ "artifact.agent_id": artifactData.subAgentId || "unknown",
3950
3958
  "artifact.tool_call_id": artifactData.metadata?.toolCallId || "unknown",
3951
3959
  "artifact.data": JSON.stringify(artifactData.data, null, 2),
3952
3960
  "tenant.id": artifactData.tenantId || "unknown",
@@ -4005,34 +4013,34 @@ Make it specific and relevant.`;
4005
4013
  let modelToUse = this.statusUpdateState?.summarizerModel;
4006
4014
  if (!modelToUse?.model?.trim()) {
4007
4015
  if (!this.statusUpdateState?.baseModel?.model?.trim()) {
4008
- if (artifactData.agentId && artifactData.tenantId && artifactData.projectId) {
4016
+ if (artifactData.subAgentId && artifactData.tenantId && artifactData.projectId) {
4009
4017
  try {
4010
- const agentData = await agentsCore.getAgentById(dbClient_default)({
4018
+ const agentData = await agentsCore.getSubAgentById(dbClient_default)({
4011
4019
  scopes: {
4012
4020
  tenantId: artifactData.tenantId,
4013
4021
  projectId: artifactData.projectId,
4014
4022
  graphId: this.graphId || ""
4015
4023
  },
4016
- agentId: artifactData.agentId
4024
+ subAgentId: artifactData.subAgentId
4017
4025
  });
4018
4026
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
4019
4027
  modelToUse = agentData.models.base;
4020
- logger10.info(
4028
+ logger9.info(
4021
4029
  {
4022
4030
  sessionId: this.sessionId,
4023
4031
  artifactId: artifactData.artifactId,
4024
- agentId: artifactData.agentId,
4032
+ subAgentId: artifactData.subAgentId,
4025
4033
  model: modelToUse.model
4026
4034
  },
4027
4035
  "Using agent model configuration for artifact name generation"
4028
4036
  );
4029
4037
  }
4030
4038
  } catch (error) {
4031
- logger10.warn(
4039
+ logger9.warn(
4032
4040
  {
4033
4041
  sessionId: this.sessionId,
4034
4042
  artifactId: artifactData.artifactId,
4035
- agentId: artifactData.agentId,
4043
+ subAgentId: artifactData.subAgentId,
4036
4044
  error: error instanceof Error ? error.message : "Unknown error"
4037
4045
  },
4038
4046
  "Failed to get agent model configuration"
@@ -4040,7 +4048,7 @@ Make it specific and relevant.`;
4040
4048
  }
4041
4049
  }
4042
4050
  if (!modelToUse?.model?.trim()) {
4043
- logger10.warn(
4051
+ logger9.warn(
4044
4052
  {
4045
4053
  sessionId: this.sessionId,
4046
4054
  artifactId: artifactData.artifactId
@@ -4122,7 +4130,7 @@ Make it specific and relevant.`;
4122
4130
  return result2;
4123
4131
  } catch (error) {
4124
4132
  lastError = error instanceof Error ? error : new Error(String(error));
4125
- logger10.warn(
4133
+ logger9.warn(
4126
4134
  {
4127
4135
  sessionId: this.sessionId,
4128
4136
  artifactId: artifactData.artifactId,
@@ -4174,7 +4182,7 @@ Make it specific and relevant.`;
4174
4182
  });
4175
4183
  span.setStatus({ code: api.SpanStatusCode.OK });
4176
4184
  } catch (saveError) {
4177
- logger10.error(
4185
+ logger9.error(
4178
4186
  {
4179
4187
  sessionId: this.sessionId,
4180
4188
  artifactId: artifactData.artifactId,
@@ -4202,7 +4210,7 @@ Make it specific and relevant.`;
4202
4210
  metadata: artifactData.metadata || {},
4203
4211
  toolCallId: artifactData.toolCallId
4204
4212
  });
4205
- logger10.info(
4213
+ logger9.info(
4206
4214
  {
4207
4215
  sessionId: this.sessionId,
4208
4216
  artifactId: artifactData.artifactId
@@ -4213,7 +4221,7 @@ Make it specific and relevant.`;
4213
4221
  } catch (fallbackError) {
4214
4222
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
4215
4223
  if (isDuplicateError) ; else {
4216
- logger10.error(
4224
+ logger9.error(
4217
4225
  {
4218
4226
  sessionId: this.sessionId,
4219
4227
  artifactId: artifactData.artifactId,
@@ -4226,7 +4234,7 @@ Make it specific and relevant.`;
4226
4234
  }
4227
4235
  } catch (error) {
4228
4236
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4229
- logger10.error(
4237
+ logger9.error(
4230
4238
  {
4231
4239
  sessionId: this.sessionId,
4232
4240
  artifactId: artifactData.artifactId,
@@ -4245,7 +4253,7 @@ Make it specific and relevant.`;
4245
4253
  */
4246
4254
  setArtifactCache(key, artifact) {
4247
4255
  this.artifactCache.set(key, artifact);
4248
- logger10.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
4256
+ logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
4249
4257
  }
4250
4258
  /**
4251
4259
  * Get session-scoped ArtifactService instance
@@ -4264,7 +4272,7 @@ Make it specific and relevant.`;
4264
4272
  */
4265
4273
  getArtifactCache(key) {
4266
4274
  const artifact = this.artifactCache.get(key);
4267
- logger10.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
4275
+ logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
4268
4276
  return artifact || null;
4269
4277
  }
4270
4278
  /**
@@ -4287,7 +4295,7 @@ var GraphSessionManager = class {
4287
4295
  const sessionId = messageId;
4288
4296
  const session = new GraphSession(sessionId, messageId, graphId, tenantId, projectId, contextId);
4289
4297
  this.sessions.set(sessionId, session);
4290
- logger10.info(
4298
+ logger9.info(
4291
4299
  { sessionId, messageId, graphId, tenantId, projectId, contextId },
4292
4300
  "GraphSession created"
4293
4301
  );
@@ -4301,7 +4309,7 @@ var GraphSessionManager = class {
4301
4309
  if (session) {
4302
4310
  session.initializeStatusUpdates(config, summarizerModel);
4303
4311
  } else {
4304
- logger10.error(
4312
+ logger9.error(
4305
4313
  {
4306
4314
  sessionId,
4307
4315
  availableSessions: Array.from(this.sessions.keys())
@@ -4318,7 +4326,7 @@ var GraphSessionManager = class {
4318
4326
  if (session) {
4319
4327
  session.enableEmitOperations();
4320
4328
  } else {
4321
- logger10.error(
4329
+ logger9.error(
4322
4330
  {
4323
4331
  sessionId,
4324
4332
  availableSessions: Array.from(this.sessions.keys())
@@ -4335,14 +4343,15 @@ var GraphSessionManager = class {
4335
4343
  }
4336
4344
  /**
4337
4345
  * Record an event in a session
4346
+ * Generic type parameter T ensures eventType and data are correctly paired
4338
4347
  */
4339
- recordEvent(sessionId, eventType, agentId, data) {
4348
+ recordEvent(sessionId, eventType, subAgentId, data) {
4340
4349
  const session = this.sessions.get(sessionId);
4341
4350
  if (!session) {
4342
- logger10.warn({ sessionId }, "Attempted to record event in non-existent session");
4351
+ logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
4343
4352
  return;
4344
4353
  }
4345
- session.recordEvent(eventType, agentId, data);
4354
+ session.recordEvent(eventType, subAgentId, data);
4346
4355
  }
4347
4356
  /**
4348
4357
  * End a session and return the final event data
@@ -4350,12 +4359,12 @@ var GraphSessionManager = class {
4350
4359
  endSession(sessionId) {
4351
4360
  const session = this.sessions.get(sessionId);
4352
4361
  if (!session) {
4353
- logger10.warn({ sessionId }, "Attempted to end non-existent session");
4362
+ logger9.warn({ sessionId }, "Attempted to end non-existent session");
4354
4363
  return [];
4355
4364
  }
4356
4365
  const events = session.getEvents();
4357
4366
  const summary = session.getSummary();
4358
- logger10.info({ sessionId, summary }, "GraphSession ended");
4367
+ logger9.info({ sessionId, summary }, "GraphSession ended");
4359
4368
  session.cleanup();
4360
4369
  this.sessions.delete(sessionId);
4361
4370
  return events;
@@ -4463,7 +4472,7 @@ init_logger();
4463
4472
 
4464
4473
  // src/services/IncrementalStreamParser.ts
4465
4474
  init_logger();
4466
- var logger11 = agentsCore.getLogger("IncrementalStreamParser");
4475
+ var logger10 = agentsCore.getLogger("IncrementalStreamParser");
4467
4476
  var _IncrementalStreamParser = class _IncrementalStreamParser {
4468
4477
  // Max number of collected parts to prevent unbounded growth
4469
4478
  constructor(streamHelper, tenantId, contextId, artifactParserOptions) {
@@ -4479,10 +4488,11 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4479
4488
  __publicField(this, "lastStreamedComponents", /* @__PURE__ */ new Map());
4480
4489
  __publicField(this, "componentSnapshots", /* @__PURE__ */ new Map());
4481
4490
  __publicField(this, "artifactMap");
4482
- __publicField(this, "agentId");
4491
+ __publicField(this, "subAgentId");
4492
+ __publicField(this, "allStreamedContent", []);
4483
4493
  this.streamHelper = streamHelper;
4484
4494
  this.contextId = contextId;
4485
- this.agentId = artifactParserOptions?.agentId;
4495
+ this.subAgentId = artifactParserOptions?.subAgentId;
4486
4496
  if (artifactParserOptions?.streamRequestId) {
4487
4497
  const sessionParser = graphSessionManager.getArtifactParser(
4488
4498
  artifactParserOptions.streamRequestId
@@ -4515,7 +4525,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4515
4525
  async initializeArtifactMap() {
4516
4526
  try {
4517
4527
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
4518
- logger11.debug(
4528
+ logger10.debug(
4519
4529
  {
4520
4530
  contextId: this.contextId,
4521
4531
  artifactMapSize: this.artifactMap.size
@@ -4523,7 +4533,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4523
4533
  "Initialized artifact map for streaming"
4524
4534
  );
4525
4535
  } catch (error) {
4526
- logger11.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
4536
+ logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
4527
4537
  this.artifactMap = /* @__PURE__ */ new Map();
4528
4538
  }
4529
4539
  }
@@ -4598,10 +4608,12 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4598
4608
  this.hasStartedRole = true;
4599
4609
  }
4600
4610
  await this.streamHelper.streamText(newText, 50);
4601
- this.collectedParts.push({
4611
+ const textPart = {
4602
4612
  kind: "text",
4603
4613
  text: newText
4604
- });
4614
+ };
4615
+ this.collectedParts.push(textPart);
4616
+ this.allStreamedContent.push(textPart);
4605
4617
  }
4606
4618
  continue;
4607
4619
  }
@@ -4625,7 +4637,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4625
4637
  dataComponents: [component]
4626
4638
  },
4627
4639
  this.artifactMap,
4628
- this.agentId
4640
+ this.subAgentId
4629
4641
  );
4630
4642
  if (!Array.isArray(parts)) {
4631
4643
  console.warn("parseObject returned non-array:", parts);
@@ -4701,7 +4713,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4701
4713
  dataComponents: [component]
4702
4714
  },
4703
4715
  this.artifactMap,
4704
- this.agentId
4716
+ this.subAgentId
4705
4717
  );
4706
4718
  for (const part of parts) {
4707
4719
  await this.streamPart(part);
@@ -4727,10 +4739,12 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4727
4739
  if (this.pendingTextBuffer) {
4728
4740
  const cleanedText = this.pendingTextBuffer.replace(/<\/?artifact:ref(?:\s[^>]*)?>\/?>/g, "").replace(/<\/?artifact(?:\s[^>]*)?>\/?>/g, "").replace(/<\/artifact:ref>/g, "").replace(/<\/(?:\w+:)?artifact>/g, "");
4729
4741
  if (cleanedText) {
4730
- this.collectedParts.push({
4742
+ const textPart = {
4731
4743
  kind: "text",
4732
4744
  text: cleanedText
4733
- });
4745
+ };
4746
+ this.collectedParts.push(textPart);
4747
+ this.allStreamedContent.push(textPart);
4734
4748
  await this.streamHelper.streamText(cleanedText, 50);
4735
4749
  }
4736
4750
  this.pendingTextBuffer = "";
@@ -4745,6 +4759,12 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4745
4759
  getCollectedParts() {
4746
4760
  return [...this.collectedParts];
4747
4761
  }
4762
+ /**
4763
+ * Get all streamed content that was actually sent to the user
4764
+ */
4765
+ getAllStreamedContent() {
4766
+ return [...this.allStreamedContent];
4767
+ }
4748
4768
  /**
4749
4769
  * Parse buffer for complete artifacts and text parts (for text streaming)
4750
4770
  */
@@ -4755,7 +4775,11 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4755
4775
  const safeEnd = this.artifactParser.findSafeTextBoundary(workingBuffer);
4756
4776
  if (safeEnd > 0) {
4757
4777
  const safeText = workingBuffer.slice(0, safeEnd);
4758
- const parts2 = await this.artifactParser.parseText(safeText, this.artifactMap, this.agentId);
4778
+ const parts2 = await this.artifactParser.parseText(
4779
+ safeText,
4780
+ this.artifactMap,
4781
+ this.subAgentId
4782
+ );
4759
4783
  completeParts.push(...parts2);
4760
4784
  return {
4761
4785
  completeParts,
@@ -4770,7 +4794,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4770
4794
  const parts = await this.artifactParser.parseText(
4771
4795
  workingBuffer,
4772
4796
  this.artifactMap,
4773
- this.agentId
4797
+ this.subAgentId
4774
4798
  );
4775
4799
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
4776
4800
  const lastPart = parts[parts.length - 1];
@@ -4800,10 +4824,15 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4800
4824
  */
4801
4825
  async streamPart(part) {
4802
4826
  this.collectedParts.push({ ...part });
4827
+ this.allStreamedContent.push({ ...part });
4803
4828
  if (this.collectedParts.length > _IncrementalStreamParser.MAX_COLLECTED_PARTS) {
4804
4829
  const excess = this.collectedParts.length - _IncrementalStreamParser.MAX_COLLECTED_PARTS;
4805
4830
  this.collectedParts.splice(0, excess);
4806
4831
  }
4832
+ if (this.allStreamedContent.length > _IncrementalStreamParser.MAX_COLLECTED_PARTS) {
4833
+ const excess = this.allStreamedContent.length - _IncrementalStreamParser.MAX_COLLECTED_PARTS;
4834
+ this.allStreamedContent.splice(0, excess);
4835
+ }
4807
4836
  if (!this.hasStartedRole) {
4808
4837
  await this.streamHelper.writeRole("assistant");
4809
4838
  this.hasStartedRole = true;
@@ -4844,12 +4873,12 @@ var IncrementalStreamParser = _IncrementalStreamParser;
4844
4873
 
4845
4874
  // src/services/ResponseFormatter.ts
4846
4875
  init_logger();
4847
- var logger12 = agentsCore.getLogger("ResponseFormatter");
4876
+ var logger11 = agentsCore.getLogger("ResponseFormatter");
4848
4877
  var ResponseFormatter = class {
4849
4878
  constructor(tenantId, artifactParserOptions) {
4850
4879
  __publicField(this, "artifactParser");
4851
- __publicField(this, "agentId");
4852
- this.agentId = artifactParserOptions?.agentId;
4880
+ __publicField(this, "subAgentId");
4881
+ this.subAgentId = artifactParserOptions?.subAgentId;
4853
4882
  if (artifactParserOptions?.streamRequestId) {
4854
4883
  const sessionParser = graphSessionManager.getArtifactParser(
4855
4884
  artifactParserOptions.streamRequestId
@@ -4888,7 +4917,7 @@ var ResponseFormatter = class {
4888
4917
  const parts = await this.artifactParser.parseObject(
4889
4918
  responseObject,
4890
4919
  artifactMap,
4891
- this.agentId
4920
+ this.subAgentId
4892
4921
  );
4893
4922
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
4894
4923
  span.setAttributes({
@@ -4903,7 +4932,7 @@ var ResponseFormatter = class {
4903
4932
  return { parts };
4904
4933
  } catch (error) {
4905
4934
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4906
- logger12.error({ error, responseObject }, "Error formatting object response");
4935
+ logger11.error({ error, responseObject }, "Error formatting object response");
4907
4936
  return {
4908
4937
  parts: [{ kind: "data", data: responseObject }]
4909
4938
  };
@@ -4935,7 +4964,11 @@ var ResponseFormatter = class {
4935
4964
  "response.type": "text",
4936
4965
  "response.availableArtifacts": artifactMap.size
4937
4966
  });
4938
- const parts = await this.artifactParser.parseText(responseText, artifactMap, this.agentId);
4967
+ const parts = await this.artifactParser.parseText(
4968
+ responseText,
4969
+ artifactMap,
4970
+ this.subAgentId
4971
+ );
4939
4972
  if (parts.length === 1 && parts[0].kind === "text") {
4940
4973
  return { text: parts[0].text };
4941
4974
  }
@@ -4955,7 +4988,7 @@ var ResponseFormatter = class {
4955
4988
  return { parts };
4956
4989
  } catch (error) {
4957
4990
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4958
- logger12.error({ error, responseText }, "Error formatting response");
4991
+ logger11.error({ error, responseText }, "Error formatting response");
4959
4992
  return { text: responseText };
4960
4993
  } finally {
4961
4994
  span.end();
@@ -5009,20 +5042,20 @@ function agentInitializingOp(sessionId, graphId) {
5009
5042
  }
5010
5043
  };
5011
5044
  }
5012
- function completionOp(agentId, iterations) {
5045
+ function completionOp(subAgentId, iterations) {
5013
5046
  return {
5014
5047
  type: "completion",
5015
5048
  details: {
5016
- agent: agentId,
5049
+ agent: subAgentId,
5017
5050
  iteration: iterations
5018
5051
  }
5019
5052
  };
5020
5053
  }
5021
- function errorOp(message, agentId, severity = "error", code) {
5054
+ function errorOp(message, subAgentId, severity = "error", code) {
5022
5055
  return {
5023
5056
  type: "error",
5024
5057
  message,
5025
- agent: agentId,
5058
+ agent: subAgentId,
5026
5059
  severity,
5027
5060
  code,
5028
5061
  timestamp: Date.now()
@@ -5037,10 +5070,10 @@ init_logger();
5037
5070
 
5038
5071
  // src/utils/data-component-schema.ts
5039
5072
  init_logger();
5040
- var logger13 = agentsCore.getLogger("DataComponentSchema");
5073
+ var logger12 = agentsCore.getLogger("DataComponentSchema");
5041
5074
  function jsonSchemaToZod(jsonSchema) {
5042
5075
  if (!jsonSchema || typeof jsonSchema !== "object") {
5043
- logger13.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
5076
+ logger12.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
5044
5077
  return z6.z.string();
5045
5078
  }
5046
5079
  switch (jsonSchema.type) {
@@ -5067,7 +5100,7 @@ function jsonSchemaToZod(jsonSchema) {
5067
5100
  case "null":
5068
5101
  return z6.z.null();
5069
5102
  default:
5070
- logger13.warn(
5103
+ logger12.warn(
5071
5104
  {
5072
5105
  unsupportedType: jsonSchema.type,
5073
5106
  schema: jsonSchema
@@ -5434,7 +5467,7 @@ function parseEmbeddedJson(data) {
5434
5467
 
5435
5468
  // src/a2a/client.ts
5436
5469
  init_logger();
5437
- var logger14 = agentsCore.getLogger("a2aClient");
5470
+ var logger13 = agentsCore.getLogger("a2aClient");
5438
5471
  var DEFAULT_BACKOFF = {
5439
5472
  initialInterval: 500,
5440
5473
  maxInterval: 6e4,
@@ -5640,7 +5673,7 @@ var A2AClient = class {
5640
5673
  try {
5641
5674
  const res = await fn();
5642
5675
  if (attempt > 0) {
5643
- logger14.info(
5676
+ logger13.info(
5644
5677
  {
5645
5678
  attempts: attempt + 1,
5646
5679
  elapsedTime: Date.now() - start
@@ -5655,7 +5688,7 @@ var A2AClient = class {
5655
5688
  }
5656
5689
  const elapsed = Date.now() - start;
5657
5690
  if (elapsed > maxElapsedTime) {
5658
- logger14.warn(
5691
+ logger13.warn(
5659
5692
  {
5660
5693
  attempts: attempt + 1,
5661
5694
  elapsedTime: elapsed,
@@ -5676,7 +5709,7 @@ var A2AClient = class {
5676
5709
  retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
5677
5710
  }
5678
5711
  const delayMs = Math.min(retryInterval, maxInterval);
5679
- logger14.info(
5712
+ logger13.info(
5680
5713
  {
5681
5714
  attempt: attempt + 1,
5682
5715
  delayMs,
@@ -5761,7 +5794,7 @@ var A2AClient = class {
5761
5794
  }
5762
5795
  const rpcResponse = await httpResponse.json();
5763
5796
  if (rpcResponse.id !== requestId2) {
5764
- logger14.warn(
5797
+ logger13.warn(
5765
5798
  {
5766
5799
  method,
5767
5800
  expectedId: requestId2,
@@ -5960,7 +5993,7 @@ var A2AClient = class {
5960
5993
  try {
5961
5994
  while (true) {
5962
5995
  const { done, value } = await reader.read();
5963
- logger14.info({ done, value }, "parseA2ASseStream");
5996
+ logger13.info({ done, value }, "parseA2ASseStream");
5964
5997
  if (done) {
5965
5998
  if (eventDataBuffer.trim()) {
5966
5999
  const result = this._processSseEventData(
@@ -6050,7 +6083,7 @@ var A2AClient = class {
6050
6083
  init_conversations();
6051
6084
  init_dbClient();
6052
6085
  init_logger();
6053
- var logger15 = agentsCore.getLogger("relationships Tools");
6086
+ var logger14 = agentsCore.getLogger("relationships Tools");
6054
6087
  var generateTransferToolDescription = (config) => {
6055
6088
  return `Hand off the conversation to agent ${config.id}.
6056
6089
 
@@ -6074,7 +6107,7 @@ Delegate a specific task to agent ${config.id} when it seems like the agent can
6074
6107
  var createTransferToAgentTool = ({
6075
6108
  transferConfig,
6076
6109
  callingAgentId,
6077
- agent,
6110
+ subAgent,
6078
6111
  streamRequestId
6079
6112
  }) => {
6080
6113
  return ai.tool({
@@ -6084,11 +6117,11 @@ var createTransferToAgentTool = ({
6084
6117
  const activeSpan = api.trace.getActiveSpan();
6085
6118
  if (activeSpan) {
6086
6119
  activeSpan.setAttributes({
6087
- "transfer.from_agent_id": callingAgentId,
6088
- "transfer.to_agent_id": transferConfig.id ?? "unknown"
6120
+ [agentsCore.SPAN_KEYS.TRANSFER_FROM_SUB_AGENT_ID]: callingAgentId,
6121
+ [agentsCore.SPAN_KEYS.TRANSFER_TO_SUB_AGENT_ID]: transferConfig.id ?? "unknown"
6089
6122
  });
6090
6123
  }
6091
- logger15.info(
6124
+ logger14.info(
6092
6125
  {
6093
6126
  transferTo: transferConfig.id ?? "unknown",
6094
6127
  fromAgent: callingAgentId
@@ -6097,8 +6130,8 @@ var createTransferToAgentTool = ({
6097
6130
  );
6098
6131
  if (streamRequestId) {
6099
6132
  graphSessionManager.recordEvent(streamRequestId, "transfer", callingAgentId, {
6100
- fromAgent: callingAgentId,
6101
- targetAgent: transferConfig.id ?? "unknown",
6133
+ fromSubAgent: callingAgentId,
6134
+ targetSubAgent: transferConfig.id ?? "unknown",
6102
6135
  reason: `Transfer to ${transferConfig.name || transferConfig.id}`
6103
6136
  });
6104
6137
  }
@@ -6120,7 +6153,7 @@ function createDelegateToAgentTool({
6120
6153
  contextId,
6121
6154
  metadata,
6122
6155
  sessionId,
6123
- agent,
6156
+ subAgent,
6124
6157
  credentialStoreRegistry
6125
6158
  }) {
6126
6159
  return ai.tool({
@@ -6131,9 +6164,9 @@ function createDelegateToAgentTool({
6131
6164
  const activeSpan = api.trace.getActiveSpan();
6132
6165
  if (activeSpan) {
6133
6166
  activeSpan.setAttributes({
6134
- "delegation.from_agent_id": callingAgentId,
6135
- "delegation.to_agent_id": delegateConfig.config.id ?? "unknown",
6136
- "delegation.id": delegationId
6167
+ [agentsCore.SPAN_KEYS.DELEGATION_FROM_SUB_AGENT_ID]: callingAgentId,
6168
+ [agentsCore.SPAN_KEYS.DELEGATION_TO_SUB_AGENT_ID]: delegateConfig.config.id ?? "unknown",
6169
+ [agentsCore.SPAN_KEYS.DELEGATION_ID]: delegationId
6137
6170
  });
6138
6171
  }
6139
6172
  if (metadata.streamRequestId) {
@@ -6143,8 +6176,8 @@ function createDelegateToAgentTool({
6143
6176
  callingAgentId,
6144
6177
  {
6145
6178
  delegationId,
6146
- fromAgent: callingAgentId,
6147
- targetAgent: delegateConfig.config.id,
6179
+ fromSubAgent: callingAgentId,
6180
+ targetSubAgent: delegateConfig.config.id,
6148
6181
  taskDescription: input.message
6149
6182
  }
6150
6183
  );
@@ -6158,7 +6191,7 @@ function createDelegateToAgentTool({
6158
6191
  projectId,
6159
6192
  graphId
6160
6193
  },
6161
- agentId: delegateConfig.config.id
6194
+ subAgentId: delegateConfig.config.id
6162
6195
  });
6163
6196
  if (externalAgent && (externalAgent.credentialReferenceId || externalAgent.headers) && credentialStoreRegistry) {
6164
6197
  const contextResolver = new agentsCore.ContextResolver(
@@ -6237,7 +6270,7 @@ function createDelegateToAgentTool({
6237
6270
  ...isInternal ? { fromAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
6238
6271
  }
6239
6272
  };
6240
- logger15.info({ messageToSend }, "messageToSend");
6273
+ logger14.info({ messageToSend }, "messageToSend");
6241
6274
  await agentsCore.createMessage(dbClient_default)({
6242
6275
  id: nanoid.nanoid(),
6243
6276
  tenantId,
@@ -6249,7 +6282,7 @@ function createDelegateToAgentTool({
6249
6282
  },
6250
6283
  visibility: isInternal ? "internal" : "external",
6251
6284
  messageType: "a2a-request",
6252
- fromAgentId: callingAgentId,
6285
+ fromSubAgentId: callingAgentId,
6253
6286
  ...isInternal ? { toAgentId: delegateConfig.config.id } : { toExternalAgentId: delegateConfig.config.id }
6254
6287
  });
6255
6288
  const response = await a2aClient.sendMessage({
@@ -6264,8 +6297,8 @@ function createDelegateToAgentTool({
6264
6297
  conversationId: contextId,
6265
6298
  messageType: "a2a-response",
6266
6299
  visibility: isInternal ? "internal" : "external",
6267
- toAgentId: callingAgentId,
6268
- ...isInternal ? { fromAgentId: delegateConfig.config.id } : { fromExternalAgentId: delegateConfig.config.id }
6300
+ toSubAgentId: callingAgentId,
6301
+ ...isInternal ? { fromSubAgentId: delegateConfig.config.id } : { fromExternalAgentId: delegateConfig.config.id }
6269
6302
  });
6270
6303
  if (sessionId && context?.toolCallId) {
6271
6304
  const toolResult = {
@@ -6284,8 +6317,8 @@ function createDelegateToAgentTool({
6284
6317
  callingAgentId,
6285
6318
  {
6286
6319
  delegationId,
6287
- fromAgent: delegateConfig.config.id,
6288
- targetAgent: callingAgentId,
6320
+ fromSubAgent: delegateConfig.config.id,
6321
+ targetSubAgent: callingAgentId,
6289
6322
  result: response.result
6290
6323
  }
6291
6324
  );
@@ -6300,7 +6333,7 @@ function createDelegateToAgentTool({
6300
6333
 
6301
6334
  // src/agents/SystemPromptBuilder.ts
6302
6335
  init_logger();
6303
- var logger16 = agentsCore.getLogger("SystemPromptBuilder");
6336
+ var logger15 = agentsCore.getLogger("SystemPromptBuilder");
6304
6337
  var SystemPromptBuilder = class {
6305
6338
  constructor(version, versionConfig) {
6306
6339
  this.version = version;
@@ -6316,12 +6349,12 @@ var SystemPromptBuilder = class {
6316
6349
  this.templates.set(name, content);
6317
6350
  }
6318
6351
  this.loaded = true;
6319
- logger16.debug(
6352
+ logger15.debug(
6320
6353
  { templateCount: this.templates.size, version: this.version },
6321
6354
  `Loaded ${this.templates.size} templates for version ${this.version}`
6322
6355
  );
6323
6356
  } catch (error) {
6324
- logger16.error({ error }, `Failed to load templates for version ${this.version}`);
6357
+ logger15.error({ error }, `Failed to load templates for version ${this.version}`);
6325
6358
  throw new Error(`Template loading failed: ${error}`);
6326
6359
  }
6327
6360
  }
@@ -7382,7 +7415,7 @@ function hasToolCallWithPrefix(prefix) {
7382
7415
  return false;
7383
7416
  };
7384
7417
  }
7385
- var logger19 = agentsCore.getLogger("Agent");
7418
+ var logger18 = agentsCore.getLogger("Agent");
7386
7419
  var CONSTANTS = {
7387
7420
  MAX_GENERATION_STEPS: 12,
7388
7421
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -7612,7 +7645,7 @@ var Agent = class {
7612
7645
  }
7613
7646
  getRelationTools(runtimeContext, sessionId) {
7614
7647
  const { transferRelations = [], delegateRelations = [] } = this.config;
7615
- const createToolName = (prefix, agentId) => `${prefix}_to_${agentId.toLowerCase().replace(/\s+/g, "_")}`;
7648
+ const createToolName = (prefix, subAgentId) => `${prefix}_to_${subAgentId.toLowerCase().replace(/\s+/g, "_")}`;
7616
7649
  return Object.fromEntries([
7617
7650
  ...transferRelations.map((agentConfig) => {
7618
7651
  const toolName = createToolName("transfer", agentConfig.id);
@@ -7623,7 +7656,7 @@ var Agent = class {
7623
7656
  createTransferToAgentTool({
7624
7657
  transferConfig: agentConfig,
7625
7658
  callingAgentId: this.config.id,
7626
- agent: this,
7659
+ subAgent: this,
7627
7660
  streamRequestId: runtimeContext?.metadata?.streamRequestId
7628
7661
  }),
7629
7662
  runtimeContext?.metadata?.streamRequestId,
@@ -7652,7 +7685,7 @@ var Agent = class {
7652
7685
  apiKey: runtimeContext?.metadata?.apiKey
7653
7686
  },
7654
7687
  sessionId,
7655
- agent: this,
7688
+ subAgent: this,
7656
7689
  credentialStoreRegistry: this.credentialStoreRegistry
7657
7690
  }),
7658
7691
  runtimeContext?.metadata?.streamRequestId,
@@ -7686,14 +7719,14 @@ var Agent = class {
7686
7719
  for (const toolSet of tools) {
7687
7720
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
7688
7721
  if (!isValidTool(originalTool)) {
7689
- logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7722
+ logger18.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7690
7723
  continue;
7691
7724
  }
7692
7725
  const sessionWrappedTool = ai.tool({
7693
7726
  description: originalTool.description,
7694
7727
  inputSchema: originalTool.inputSchema,
7695
7728
  execute: async (args, { toolCallId }) => {
7696
- logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
7729
+ logger18.debug({ toolName, toolCallId }, "MCP Tool Called");
7697
7730
  try {
7698
7731
  const rawResult = await originalTool.execute(args, { toolCallId });
7699
7732
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -7707,7 +7740,7 @@ var Agent = class {
7707
7740
  });
7708
7741
  return { result: enhancedResult, toolCallId };
7709
7742
  } catch (error) {
7710
- logger19.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7743
+ logger18.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7711
7744
  throw error;
7712
7745
  }
7713
7746
  }
@@ -7752,7 +7785,7 @@ var Agent = class {
7752
7785
  tenantId: this.config.tenantId,
7753
7786
  projectId: this.config.projectId,
7754
7787
  graphId: this.config.graphId,
7755
- agentId: this.config.id
7788
+ subAgentId: this.config.id
7756
7789
  }
7757
7790
  });
7758
7791
  const agentToolRelationHeaders = toolsForAgent.data.find((t) => t.toolId === tool3.id)?.headers || void 0;
@@ -7808,7 +7841,7 @@ var Agent = class {
7808
7841
  headers: agentToolRelationHeaders
7809
7842
  };
7810
7843
  }
7811
- logger19.info(
7844
+ logger18.info(
7812
7845
  {
7813
7846
  toolName: tool3.name,
7814
7847
  credentialReferenceId,
@@ -7833,10 +7866,10 @@ var Agent = class {
7833
7866
  this.mcpClientCache.set(cacheKey, client);
7834
7867
  } catch (error) {
7835
7868
  this.mcpConnectionLocks.delete(cacheKey);
7836
- logger19.error(
7869
+ logger18.error(
7837
7870
  {
7838
7871
  toolName: tool3.name,
7839
- agentId: this.config.id,
7872
+ subAgentId: this.config.id,
7840
7873
  cacheKey,
7841
7874
  error: error instanceof Error ? error.message : String(error)
7842
7875
  },
@@ -7846,6 +7879,45 @@ var Agent = class {
7846
7879
  }
7847
7880
  }
7848
7881
  const tools = await client.tools();
7882
+ if (!tools || Object.keys(tools).length === 0) {
7883
+ const streamRequestId = this.getStreamRequestId();
7884
+ if (streamRequestId) {
7885
+ tracer.startActiveSpan(
7886
+ "ai.toolCall",
7887
+ {
7888
+ attributes: {
7889
+ "ai.toolCall.name": tool3.name,
7890
+ "ai.toolCall.args": JSON.stringify({ operation: "mcp_tool_discovery" }),
7891
+ "ai.toolCall.result": JSON.stringify({
7892
+ status: "no_tools_available",
7893
+ message: `MCP server has 0 effective tools. Double check the selected tools in your graph and the active tools in the MCP server configuration.`,
7894
+ serverUrl: tool3.config.type === "mcp" ? tool3.config.mcp.server.url : "unknown",
7895
+ originalToolName: tool3.name
7896
+ }),
7897
+ "ai.toolType": "mcp",
7898
+ "ai.agentName": this.config.name || "unknown",
7899
+ "conversation.id": this.conversationId || "unknown",
7900
+ "graph.id": this.config.graphId || "unknown",
7901
+ "tenant.id": this.config.tenantId || "unknown",
7902
+ "project.id": this.config.projectId || "unknown"
7903
+ }
7904
+ },
7905
+ (span) => {
7906
+ agentsCore.setSpanWithError(span, new Error(`0 effective tools available for ${tool3.name}`));
7907
+ graphSessionManager.recordEvent(streamRequestId, "tool_execution", this.config.id, {
7908
+ toolName: tool3.name,
7909
+ args: { operation: "mcp_tool_discovery" },
7910
+ result: {
7911
+ status: "no_tools_available",
7912
+ message: `MCP server has 0 effective tools. Double check the selected tools in your graph and the active tools in the MCP server configuration.`,
7913
+ serverUrl: tool3.config.type === "mcp" ? tool3.config.mcp.server.url : "unknown"
7914
+ }
7915
+ });
7916
+ span.end();
7917
+ }
7918
+ );
7919
+ }
7920
+ }
7849
7921
  return tools;
7850
7922
  }
7851
7923
  async createMcpConnection(tool3, serverConfig) {
@@ -7857,99 +7929,110 @@ var Agent = class {
7857
7929
  await client.connect();
7858
7930
  return client;
7859
7931
  } catch (error) {
7860
- logger19.error(
7932
+ logger18.error(
7861
7933
  {
7862
7934
  toolName: tool3.name,
7863
- agentId: this.config.id,
7935
+ subAgentId: this.config.id,
7864
7936
  error: error instanceof Error ? error.message : String(error)
7865
7937
  },
7866
7938
  "Agent failed to connect to MCP server"
7867
7939
  );
7940
+ if (error instanceof Error) {
7941
+ if (error?.cause && JSON.stringify(error.cause).includes("ECONNREFUSED")) {
7942
+ const errorMessage = "Connection refused. Please check if the MCP server is running.";
7943
+ throw new Error(errorMessage);
7944
+ } else if (error.message.includes("404")) {
7945
+ const errorMessage = "Error accessing endpoint (HTTP 404)";
7946
+ throw new Error(errorMessage);
7947
+ } else {
7948
+ throw new Error(`MCP server connection failed: ${error.message}`);
7949
+ }
7950
+ }
7868
7951
  throw error;
7869
7952
  }
7870
7953
  }
7871
7954
  async getFunctionTools(sessionId, streamRequestId) {
7872
7955
  const functionTools = {};
7873
7956
  try {
7874
- const toolsForAgent = await agentsCore.getToolsForAgent(dbClient_default)({
7957
+ const functionToolsForAgent = await agentsCore.getFunctionToolsForSubAgent(dbClient_default)({
7875
7958
  scopes: {
7876
- tenantId: this.config.tenantId || "default",
7877
- projectId: this.config.projectId || "default",
7878
- graphId: this.config.graphId,
7879
- agentId: this.config.id
7880
- }
7959
+ tenantId: this.config.tenantId,
7960
+ projectId: this.config.projectId,
7961
+ graphId: this.config.graphId
7962
+ },
7963
+ subAgentId: this.config.id
7881
7964
  });
7882
- const toolsData = toolsForAgent.data || [];
7883
- const functionToolDefs = toolsData.filter((tool3) => tool3.tool.config.type === "function");
7884
- if (functionToolDefs.length === 0) {
7965
+ const functionToolsData = functionToolsForAgent.data || [];
7966
+ if (functionToolsData.length === 0) {
7885
7967
  return functionTools;
7886
7968
  }
7887
7969
  const { LocalSandboxExecutor: LocalSandboxExecutor2 } = await Promise.resolve().then(() => (init_LocalSandboxExecutor(), LocalSandboxExecutor_exports));
7888
7970
  const sandboxExecutor = LocalSandboxExecutor2.getInstance();
7889
- for (const toolDef of functionToolDefs) {
7890
- if (toolDef.tool.config?.type === "function") {
7891
- const functionId = toolDef.tool.functionId;
7892
- if (!functionId) {
7893
- logger19.warn({ toolId: toolDef.tool.id }, "Function tool missing functionId reference");
7894
- continue;
7971
+ for (const functionToolDef of functionToolsData) {
7972
+ const functionId = functionToolDef.functionId;
7973
+ if (!functionId) {
7974
+ logger18.warn(
7975
+ { functionToolId: functionToolDef.id },
7976
+ "Function tool missing functionId reference"
7977
+ );
7978
+ continue;
7979
+ }
7980
+ const functionData = await agentsCore.getFunction(dbClient_default)({
7981
+ functionId,
7982
+ scopes: {
7983
+ tenantId: this.config.tenantId || "default",
7984
+ projectId: this.config.projectId || "default"
7895
7985
  }
7896
- const functionData = await agentsCore.getFunction(dbClient_default)({
7897
- functionId,
7898
- scopes: {
7899
- tenantId: this.config.tenantId || "default",
7900
- projectId: this.config.projectId || "default"
7901
- }
7902
- });
7903
- if (!functionData) {
7904
- logger19.warn(
7905
- { functionId, toolId: toolDef.tool.id },
7906
- "Function not found in functions table"
7986
+ });
7987
+ if (!functionData) {
7988
+ logger18.warn(
7989
+ { functionId, functionToolId: functionToolDef.id },
7990
+ "Function not found in functions table"
7991
+ );
7992
+ continue;
7993
+ }
7994
+ const zodSchema = jsonSchemaToZod(functionData.inputSchema);
7995
+ const aiTool = ai.tool({
7996
+ description: functionToolDef.description || functionToolDef.name,
7997
+ inputSchema: zodSchema,
7998
+ execute: async (args, { toolCallId }) => {
7999
+ logger18.debug(
8000
+ { toolName: functionToolDef.name, toolCallId, args },
8001
+ "Function Tool Called"
7907
8002
  );
7908
- continue;
7909
- }
7910
- const zodSchema = jsonSchemaToZod(functionData.inputSchema);
7911
- const aiTool = ai.tool({
7912
- description: toolDef.tool.description || toolDef.tool.name,
7913
- inputSchema: zodSchema,
7914
- execute: async (args, { toolCallId }) => {
7915
- logger19.debug(
7916
- { toolName: toolDef.tool.name, toolCallId, args },
7917
- "Function Tool Called"
8003
+ try {
8004
+ const result = await sandboxExecutor.executeFunctionTool(functionToolDef.id, args, {
8005
+ description: functionToolDef.description || functionToolDef.name,
8006
+ inputSchema: functionData.inputSchema || {},
8007
+ executeCode: functionData.executeCode,
8008
+ dependencies: functionData.dependencies || {}
8009
+ });
8010
+ toolSessionManager.recordToolResult(sessionId || "", {
8011
+ toolCallId,
8012
+ toolName: functionToolDef.name,
8013
+ args,
8014
+ result,
8015
+ timestamp: Date.now()
8016
+ });
8017
+ return { result, toolCallId };
8018
+ } catch (error) {
8019
+ logger18.error(
8020
+ { toolName: functionToolDef.name, toolCallId, error },
8021
+ "Function tool execution failed"
7918
8022
  );
7919
- try {
7920
- const result = await sandboxExecutor.executeFunctionTool(toolDef.tool.id, args, {
7921
- description: toolDef.tool.description || toolDef.tool.name,
7922
- inputSchema: functionData.inputSchema || {},
7923
- executeCode: functionData.executeCode,
7924
- dependencies: functionData.dependencies || {}
7925
- });
7926
- toolSessionManager.recordToolResult(sessionId || "", {
7927
- toolCallId,
7928
- toolName: toolDef.tool.name,
7929
- args,
7930
- result,
7931
- timestamp: Date.now()
7932
- });
7933
- return { result, toolCallId };
7934
- } catch (error) {
7935
- logger19.error(
7936
- { toolName: toolDef.tool.name, toolCallId, error },
7937
- "Function tool execution failed"
7938
- );
7939
- throw error;
7940
- }
8023
+ throw error;
7941
8024
  }
7942
- });
7943
- functionTools[toolDef.tool.name] = this.wrapToolWithStreaming(
7944
- toolDef.tool.name,
7945
- aiTool,
7946
- streamRequestId || "",
7947
- "tool"
7948
- );
7949
- }
8025
+ }
8026
+ });
8027
+ functionTools[functionToolDef.name] = this.wrapToolWithStreaming(
8028
+ functionToolDef.name,
8029
+ aiTool,
8030
+ streamRequestId || "",
8031
+ "tool"
8032
+ );
7950
8033
  }
7951
8034
  } catch (error) {
7952
- logger19.error({ error }, "Failed to load function tools from database");
8035
+ logger18.error({ error }, "Failed to load function tools from database");
7953
8036
  }
7954
8037
  return functionTools;
7955
8038
  }
@@ -7959,7 +8042,7 @@ var Agent = class {
7959
8042
  async getResolvedContext(conversationId, headers) {
7960
8043
  try {
7961
8044
  if (!this.config.contextConfigId) {
7962
- logger19.debug({ graphId: this.config.graphId }, "No context config found for graph");
8045
+ logger18.debug({ graphId: this.config.graphId }, "No context config found for graph");
7963
8046
  return null;
7964
8047
  }
7965
8048
  const contextConfig = await agentsCore.getContextConfigById(dbClient_default)({
@@ -7971,7 +8054,7 @@ var Agent = class {
7971
8054
  id: this.config.contextConfigId
7972
8055
  });
7973
8056
  if (!contextConfig) {
7974
- logger19.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
8057
+ logger18.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7975
8058
  return null;
7976
8059
  }
7977
8060
  if (!this.contextResolver) {
@@ -7988,7 +8071,7 @@ var Agent = class {
7988
8071
  $now: (/* @__PURE__ */ new Date()).toISOString(),
7989
8072
  $env: process.env
7990
8073
  };
7991
- logger19.debug(
8074
+ logger18.debug(
7992
8075
  {
7993
8076
  conversationId,
7994
8077
  contextConfigId: contextConfig.id,
@@ -8002,7 +8085,7 @@ var Agent = class {
8002
8085
  );
8003
8086
  return contextWithBuiltins;
8004
8087
  } catch (error) {
8005
- logger19.error(
8088
+ logger18.error(
8006
8089
  {
8007
8090
  conversationId,
8008
8091
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8026,7 +8109,7 @@ var Agent = class {
8026
8109
  });
8027
8110
  return graphDefinition?.graphPrompt || void 0;
8028
8111
  } catch (error) {
8029
- logger19.warn(
8112
+ logger18.warn(
8030
8113
  {
8031
8114
  graphId: this.config.graphId,
8032
8115
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8051,11 +8134,11 @@ var Agent = class {
8051
8134
  if (!graphDefinition) {
8052
8135
  return false;
8053
8136
  }
8054
- return Object.values(graphDefinition.agents).some(
8055
- (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
8137
+ return Object.values(graphDefinition.subAgents).some(
8138
+ (subAgent) => "artifactComponents" in subAgent && subAgent.artifactComponents && subAgent.artifactComponents.length > 0
8056
8139
  );
8057
8140
  } catch (error) {
8058
- logger19.warn(
8141
+ logger18.warn(
8059
8142
  {
8060
8143
  graphId: this.config.graphId,
8061
8144
  tenantId: this.config.tenantId,
@@ -8084,7 +8167,7 @@ var Agent = class {
8084
8167
  preserveUnresolved: false
8085
8168
  });
8086
8169
  } catch (error) {
8087
- logger19.error(
8170
+ logger18.error(
8088
8171
  {
8089
8172
  conversationId,
8090
8173
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8131,7 +8214,7 @@ var Agent = class {
8131
8214
  preserveUnresolved: false
8132
8215
  });
8133
8216
  } catch (error) {
8134
- logger19.error(
8217
+ logger18.error(
8135
8218
  {
8136
8219
  conversationId,
8137
8220
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8146,7 +8229,7 @@ var Agent = class {
8146
8229
  const functionTools = await this.getFunctionTools(streamRequestId || "");
8147
8230
  const relationTools = this.getRelationTools(runtimeContext);
8148
8231
  const allTools = { ...mcpTools, ...functionTools, ...relationTools };
8149
- logger19.info(
8232
+ logger18.info(
8150
8233
  {
8151
8234
  mcpTools: Object.keys(mcpTools),
8152
8235
  functionTools: Object.keys(functionTools),
@@ -8185,7 +8268,7 @@ var Agent = class {
8185
8268
  preserveUnresolved: false
8186
8269
  });
8187
8270
  } catch (error) {
8188
- logger19.error(
8271
+ logger18.error(
8189
8272
  {
8190
8273
  conversationId,
8191
8274
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8218,7 +8301,7 @@ var Agent = class {
8218
8301
  toolCallId: z6.z.string().describe("The tool call ID associated with this artifact.")
8219
8302
  }),
8220
8303
  execute: async ({ artifactId, toolCallId }) => {
8221
- logger19.info({ artifactId, toolCallId }, "get_artifact_full executed");
8304
+ logger18.info({ artifactId, toolCallId }, "get_artifact_full executed");
8222
8305
  const streamRequestId = this.getStreamRequestId();
8223
8306
  const artifactService = graphSessionManager.getArtifactService(streamRequestId);
8224
8307
  if (!artifactService) {
@@ -8252,7 +8335,7 @@ var Agent = class {
8252
8335
  });
8253
8336
  }
8254
8337
  // Provide a default tool set that is always available to the agent.
8255
- async getDefaultTools(_sessionId, streamRequestId) {
8338
+ async getDefaultTools(streamRequestId) {
8256
8339
  const defaultTools = {};
8257
8340
  if (await this.graphHasArtifactComponents()) {
8258
8341
  defaultTools.get_reference_artifact = this.getArtifactTools();
@@ -8478,7 +8561,7 @@ var Agent = class {
8478
8561
  };
8479
8562
  return enhanced;
8480
8563
  } catch (error) {
8481
- logger19.warn({ error }, "Failed to enhance tool result with structure hints");
8564
+ logger18.warn({ error }, "Failed to enhance tool result with structure hints");
8482
8565
  return result;
8483
8566
  }
8484
8567
  }
@@ -8493,7 +8576,7 @@ var Agent = class {
8493
8576
  }
8494
8577
  });
8495
8578
  } catch (error) {
8496
- logger19.error(
8579
+ logger18.error(
8497
8580
  { error, graphId: this.config.graphId },
8498
8581
  "Failed to check graph artifact components"
8499
8582
  );
@@ -8538,7 +8621,7 @@ var Agent = class {
8538
8621
  // Thinking prompt without data components
8539
8622
  this.getFunctionTools(sessionId, streamRequestId),
8540
8623
  Promise.resolve(this.getRelationTools(runtimeContext, sessionId)),
8541
- this.getDefaultTools(sessionId, streamRequestId)
8624
+ this.getDefaultTools(streamRequestId)
8542
8625
  ]);
8543
8626
  childSpan.setStatus({ code: api.SpanStatusCode.OK });
8544
8627
  return result;
@@ -8578,7 +8661,7 @@ var Agent = class {
8578
8661
  currentMessage: userMessage,
8579
8662
  options: historyConfig,
8580
8663
  filters: {
8581
- agentId: this.config.id,
8664
+ subAgentId: this.config.id,
8582
8665
  taskId
8583
8666
  }
8584
8667
  });
@@ -8594,7 +8677,7 @@ var Agent = class {
8594
8677
  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;
8595
8678
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
8596
8679
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
8597
- logger19.warn(
8680
+ logger18.warn(
8598
8681
  {
8599
8682
  requestedTimeout: modelSettings.maxDuration * 1e3,
8600
8683
  appliedTimeout: timeoutMs,
@@ -8636,7 +8719,7 @@ var Agent = class {
8636
8719
  }
8637
8720
  );
8638
8721
  } catch (error) {
8639
- logger19.debug({ error }, "Failed to track agent reasoning");
8722
+ logger18.debug({ error }, "Failed to track agent reasoning");
8640
8723
  }
8641
8724
  }
8642
8725
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -8663,7 +8746,7 @@ var Agent = class {
8663
8746
  projectId: session?.projectId,
8664
8747
  artifactComponents: this.artifactComponents,
8665
8748
  streamRequestId: this.getStreamRequestId(),
8666
- agentId: this.config.id
8749
+ subAgentId: this.config.id
8667
8750
  };
8668
8751
  const parser = new IncrementalStreamParser(
8669
8752
  streamHelper,
@@ -8708,6 +8791,16 @@ var Agent = class {
8708
8791
  }))
8709
8792
  };
8710
8793
  }
8794
+ const streamedContent = parser.getAllStreamedContent();
8795
+ if (streamedContent.length > 0) {
8796
+ response.streamedContent = {
8797
+ parts: streamedContent.map((part) => ({
8798
+ kind: part.kind,
8799
+ ...part.kind === "text" && { text: part.text },
8800
+ ...part.kind === "data" && { data: part.data }
8801
+ }))
8802
+ };
8803
+ }
8711
8804
  } else {
8712
8805
  let genConfig;
8713
8806
  if (hasStructuredOutput) {
@@ -8740,7 +8833,7 @@ var Agent = class {
8740
8833
  }
8741
8834
  );
8742
8835
  } catch (error) {
8743
- logger19.debug({ error }, "Failed to track agent reasoning");
8836
+ logger18.debug({ error }, "Failed to track agent reasoning");
8744
8837
  }
8745
8838
  }
8746
8839
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -8912,7 +9005,7 @@ ${output}${structureHintsFormatted}`;
8912
9005
  projectId: session?.projectId,
8913
9006
  artifactComponents: this.artifactComponents,
8914
9007
  streamRequestId: this.getStreamRequestId(),
8915
- agentId: this.config.id
9008
+ subAgentId: this.config.id
8916
9009
  };
8917
9010
  const parser = new IncrementalStreamParser(
8918
9011
  streamHelper,
@@ -8995,7 +9088,7 @@ ${output}${structureHintsFormatted}`;
8995
9088
  contextId,
8996
9089
  artifactComponents: this.artifactComponents,
8997
9090
  streamRequestId: this.getStreamRequestId(),
8998
- agentId: this.config.id
9091
+ subAgentId: this.config.id
8999
9092
  });
9000
9093
  if (response.object) {
9001
9094
  formattedContent = await responseFormatter.formatObjectResponse(
@@ -9032,7 +9125,7 @@ ${output}${structureHintsFormatted}`;
9032
9125
  };
9033
9126
 
9034
9127
  // src/agents/generateTaskHandler.ts
9035
- var logger20 = agentsCore.getLogger("generateTaskHandler");
9128
+ var logger19 = agentsCore.getLogger("generateTaskHandler");
9036
9129
  var createTaskHandler = (config, credentialStoreRegistry) => {
9037
9130
  return async (task) => {
9038
9131
  try {
@@ -9058,14 +9151,14 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9058
9151
  projectId: config.projectId,
9059
9152
  graphId: config.graphId
9060
9153
  },
9061
- agentId: config.agentId
9154
+ subAgentId: config.subAgentId
9062
9155
  }),
9063
9156
  agentsCore.getToolsForAgent(dbClient_default)({
9064
9157
  scopes: {
9065
9158
  tenantId: config.tenantId,
9066
9159
  projectId: config.projectId,
9067
9160
  graphId: config.graphId,
9068
- agentId: config.agentId
9161
+ subAgentId: config.subAgentId
9069
9162
  }
9070
9163
  }),
9071
9164
  agentsCore.getDataComponentsForAgent(dbClient_default)({
@@ -9073,7 +9166,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9073
9166
  tenantId: config.tenantId,
9074
9167
  projectId: config.projectId,
9075
9168
  graphId: config.graphId,
9076
- agentId: config.agentId
9169
+ subAgentId: config.subAgentId
9077
9170
  }
9078
9171
  }),
9079
9172
  agentsCore.getArtifactComponentsForAgent(dbClient_default)({
@@ -9081,21 +9174,21 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9081
9174
  tenantId: config.tenantId,
9082
9175
  projectId: config.projectId,
9083
9176
  graphId: config.graphId,
9084
- agentId: config.agentId
9177
+ subAgentId: config.subAgentId
9085
9178
  }
9086
9179
  })
9087
9180
  ]);
9088
- logger20.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9181
+ logger19.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9089
9182
  const enhancedInternalRelations = await Promise.all(
9090
9183
  internalRelations.map(async (relation) => {
9091
9184
  try {
9092
- const relatedAgent = await agentsCore.getAgentById(dbClient_default)({
9185
+ const relatedAgent = await agentsCore.getSubAgentById(dbClient_default)({
9093
9186
  scopes: {
9094
9187
  tenantId: config.tenantId,
9095
9188
  projectId: config.projectId,
9096
9189
  graphId: config.graphId
9097
9190
  },
9098
- agentId: relation.id
9191
+ subAgentId: relation.id
9099
9192
  });
9100
9193
  if (relatedAgent) {
9101
9194
  const relatedAgentRelations = await agentsCore.getRelatedAgentsForGraph(dbClient_default)({
@@ -9104,7 +9197,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9104
9197
  projectId: config.projectId,
9105
9198
  graphId: config.graphId
9106
9199
  },
9107
- agentId: relation.id
9200
+ subAgentId: relation.id
9108
9201
  });
9109
9202
  const enhancedDescription = generateDescriptionWithTransfers(
9110
9203
  relation.description || "",
@@ -9114,7 +9207,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9114
9207
  return { ...relation, description: enhancedDescription };
9115
9208
  }
9116
9209
  } catch (error) {
9117
- logger20.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
9210
+ logger19.warn({ subAgentId: relation.id, error }, "Failed to enhance agent description");
9118
9211
  }
9119
9212
  return relation;
9120
9213
  })
@@ -9129,7 +9222,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9129
9222
  ) ?? [];
9130
9223
  const agent = new Agent(
9131
9224
  {
9132
- id: config.agentId,
9225
+ id: config.subAgentId,
9133
9226
  tenantId: config.tenantId,
9134
9227
  projectId: config.projectId,
9135
9228
  graphId: config.graphId,
@@ -9140,7 +9233,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9140
9233
  agentPrompt,
9141
9234
  models: models || void 0,
9142
9235
  stopWhen: stopWhen || void 0,
9143
- agentRelations: enhancedInternalRelations.map((relation) => ({
9236
+ subAgentRelations: enhancedInternalRelations.map((relation) => ({
9144
9237
  id: relation.id,
9145
9238
  tenantId: config.tenantId,
9146
9239
  projectId: config.projectId,
@@ -9151,7 +9244,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9151
9244
  description: relation.description,
9152
9245
  agentPrompt: "",
9153
9246
  delegateRelations: [],
9154
- agentRelations: [],
9247
+ subAgentRelations: [],
9155
9248
  transferRelations: []
9156
9249
  })),
9157
9250
  transferRelations: enhancedInternalRelations.filter((relation) => relation.relationType === "transfer").map((relation) => ({
@@ -9165,7 +9258,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9165
9258
  description: relation.description,
9166
9259
  agentPrompt: "",
9167
9260
  delegateRelations: [],
9168
- agentRelations: [],
9261
+ subAgentRelations: [],
9169
9262
  transferRelations: []
9170
9263
  })),
9171
9264
  delegateRelations: [
@@ -9183,7 +9276,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9183
9276
  description: relation.description,
9184
9277
  agentPrompt: "",
9185
9278
  delegateRelations: [],
9186
- agentRelations: [],
9279
+ subAgentRelations: [],
9187
9280
  transferRelations: []
9188
9281
  }
9189
9282
  })),
@@ -9218,11 +9311,11 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9218
9311
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
9219
9312
  if (taskIdMatch) {
9220
9313
  contextId = taskIdMatch[1];
9221
- logger20.info(
9314
+ logger19.info(
9222
9315
  {
9223
9316
  taskId: task.id,
9224
9317
  extractedContextId: contextId,
9225
- agentId: config.agentId
9318
+ subAgentId: config.subAgentId
9226
9319
  },
9227
9320
  "Extracted contextId from task ID for delegation"
9228
9321
  );
@@ -9234,8 +9327,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9234
9327
  const isDelegation = task.context?.metadata?.isDelegation === true;
9235
9328
  agent.setDelegationStatus(isDelegation);
9236
9329
  if (isDelegation) {
9237
- logger20.info(
9238
- { agentId: config.agentId, taskId: task.id },
9330
+ logger19.info(
9331
+ { subAgentId: config.subAgentId, taskId: task.id },
9239
9332
  "Delegated agent - streaming disabled"
9240
9333
  );
9241
9334
  if (streamRequestId && config.tenantId && config.projectId) {
@@ -9332,13 +9425,13 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9332
9425
  };
9333
9426
  };
9334
9427
  var createTaskHandlerConfig = async (params) => {
9335
- const agent = await agentsCore.getAgentById(dbClient_default)({
9428
+ const agent = await agentsCore.getSubAgentById(dbClient_default)({
9336
9429
  scopes: {
9337
9430
  tenantId: params.tenantId,
9338
9431
  projectId: params.projectId,
9339
9432
  graphId: params.graphId
9340
9433
  },
9341
- agentId: params.agentId
9434
+ subAgentId: params.subAgentId
9342
9435
  });
9343
9436
  const agentGraph = await agentsCore.getAgentGraphById(dbClient_default)({
9344
9437
  scopes: {
@@ -9348,7 +9441,7 @@ var createTaskHandlerConfig = async (params) => {
9348
9441
  }
9349
9442
  });
9350
9443
  if (!agent) {
9351
- throw new Error(`Agent not found: ${params.agentId}`);
9444
+ throw new Error(`Agent not found: ${params.subAgentId}`);
9352
9445
  }
9353
9446
  const effectiveModels = await resolveModelConfig(params.graphId, agent);
9354
9447
  const effectiveConversationHistoryConfig = agent.conversationHistoryConfig || { mode: "full" };
@@ -9356,7 +9449,7 @@ var createTaskHandlerConfig = async (params) => {
9356
9449
  tenantId: params.tenantId,
9357
9450
  projectId: params.projectId,
9358
9451
  graphId: params.graphId,
9359
- agentId: params.agentId,
9452
+ subAgentId: params.subAgentId,
9360
9453
  agentSchema: {
9361
9454
  id: agent.id,
9362
9455
  name: agent.name,
@@ -9385,25 +9478,27 @@ async function hydrateGraph({
9385
9478
  apiKey
9386
9479
  }) {
9387
9480
  try {
9388
- if (!dbGraph.defaultAgentId) {
9481
+ if (!dbGraph.defaultSubAgentId) {
9389
9482
  throw new Error(`Graph ${dbGraph.id} does not have a default agent configured`);
9390
9483
  }
9391
- const defaultAgent = await agentsCore.getAgentById(dbClient_default)({
9484
+ const defaultSubAgent = await agentsCore.getSubAgentById(dbClient_default)({
9392
9485
  scopes: {
9393
9486
  tenantId: dbGraph.tenantId,
9394
9487
  projectId: dbGraph.projectId,
9395
9488
  graphId: dbGraph.id
9396
9489
  },
9397
- agentId: dbGraph.defaultAgentId
9490
+ subAgentId: dbGraph.defaultSubAgentId
9398
9491
  });
9399
- if (!defaultAgent) {
9400
- throw new Error(`Default agent ${dbGraph.defaultAgentId} not found for graph ${dbGraph.id}`);
9492
+ if (!defaultSubAgent) {
9493
+ throw new Error(
9494
+ `Default agent ${dbGraph.defaultSubAgentId} not found for graph ${dbGraph.id}`
9495
+ );
9401
9496
  }
9402
9497
  const taskHandlerConfig = await createTaskHandlerConfig({
9403
9498
  tenantId: dbGraph.tenantId,
9404
9499
  projectId: dbGraph.projectId,
9405
9500
  graphId: dbGraph.id,
9406
- agentId: dbGraph.defaultAgentId,
9501
+ subAgentId: dbGraph.defaultSubAgentId,
9407
9502
  baseUrl,
9408
9503
  apiKey
9409
9504
  });
@@ -9432,7 +9527,7 @@ async function hydrateGraph({
9432
9527
  }
9433
9528
  };
9434
9529
  return {
9435
- agentId: dbGraph.id,
9530
+ subAgentId: dbGraph.id,
9436
9531
  // Use graph ID as agent ID for A2A purposes
9437
9532
  tenantId: dbGraph.tenantId,
9438
9533
  projectId: dbGraph.projectId,
@@ -9459,7 +9554,7 @@ async function getRegisteredGraph(executionContext) {
9459
9554
  init_dbClient();
9460
9555
  init_logger();
9461
9556
  var app = new zodOpenapi.OpenAPIHono();
9462
- var logger21 = agentsCore.getLogger("agents");
9557
+ var logger20 = agentsCore.getLogger("agents");
9463
9558
  app.openapi(
9464
9559
  zodOpenapi.createRoute({
9465
9560
  method: "get",
@@ -9497,7 +9592,7 @@ app.openapi(
9497
9592
  tracestate: c.req.header("tracestate"),
9498
9593
  baggage: c.req.header("baggage")
9499
9594
  };
9500
- logger21.info(
9595
+ logger20.info(
9501
9596
  {
9502
9597
  otelHeaders,
9503
9598
  path: c.req.path,
@@ -9506,22 +9601,22 @@ app.openapi(
9506
9601
  "OpenTelemetry headers: well-known agent.json"
9507
9602
  );
9508
9603
  const executionContext = agentsCore.getRequestExecutionContext(c);
9509
- const { tenantId, projectId, graphId, agentId } = executionContext;
9604
+ const { tenantId, projectId, graphId, subAgentId } = executionContext;
9510
9605
  console.dir("executionContext", executionContext);
9511
- if (agentId) {
9512
- logger21.info(
9606
+ if (subAgentId) {
9607
+ logger20.info(
9513
9608
  {
9514
9609
  message: "getRegisteredAgent (agent-level)",
9515
9610
  tenantId,
9516
9611
  projectId,
9517
9612
  graphId,
9518
- agentId
9613
+ subAgentId
9519
9614
  },
9520
9615
  "agent-level well-known agent.json"
9521
9616
  );
9522
9617
  const credentialStores = c.get("credentialStores");
9523
9618
  const agent = await getRegisteredAgent(executionContext, credentialStores);
9524
- logger21.info({ agent }, "agent registered: well-known agent.json");
9619
+ logger20.info({ agent }, "agent registered: well-known agent.json");
9525
9620
  if (!agent) {
9526
9621
  throw agentsCore.createApiError({
9527
9622
  code: "not_found",
@@ -9530,7 +9625,7 @@ app.openapi(
9530
9625
  }
9531
9626
  return c.json(agent.agentCard);
9532
9627
  } else {
9533
- logger21.info(
9628
+ logger20.info(
9534
9629
  {
9535
9630
  message: "getRegisteredGraph (graph-level)",
9536
9631
  tenantId,
@@ -9556,7 +9651,7 @@ app.post("/a2a", async (c) => {
9556
9651
  tracestate: c.req.header("tracestate"),
9557
9652
  baggage: c.req.header("baggage")
9558
9653
  };
9559
- logger21.info(
9654
+ logger20.info(
9560
9655
  {
9561
9656
  otelHeaders,
9562
9657
  path: c.req.path,
@@ -9565,15 +9660,15 @@ app.post("/a2a", async (c) => {
9565
9660
  "OpenTelemetry headers: a2a"
9566
9661
  );
9567
9662
  const executionContext = agentsCore.getRequestExecutionContext(c);
9568
- const { tenantId, projectId, graphId, agentId } = executionContext;
9569
- if (agentId) {
9570
- logger21.info(
9663
+ const { tenantId, projectId, graphId, subAgentId } = executionContext;
9664
+ if (subAgentId) {
9665
+ logger20.info(
9571
9666
  {
9572
9667
  message: "a2a (agent-level)",
9573
9668
  tenantId,
9574
9669
  projectId,
9575
9670
  graphId,
9576
- agentId
9671
+ subAgentId
9577
9672
  },
9578
9673
  "agent-level a2a endpoint"
9579
9674
  );
@@ -9591,7 +9686,7 @@ app.post("/a2a", async (c) => {
9591
9686
  }
9592
9687
  return a2aHandler(c, agent);
9593
9688
  } else {
9594
- logger21.info(
9689
+ logger20.info(
9595
9690
  {
9596
9691
  message: "a2a (graph-level)",
9597
9692
  tenantId,
@@ -9600,7 +9695,7 @@ app.post("/a2a", async (c) => {
9600
9695
  },
9601
9696
  "graph-level a2a endpoint"
9602
9697
  );
9603
- const graph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
9698
+ const graph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
9604
9699
  scopes: { tenantId, projectId, graphId }
9605
9700
  });
9606
9701
  if (!graph) {
@@ -9613,7 +9708,7 @@ app.post("/a2a", async (c) => {
9613
9708
  404
9614
9709
  );
9615
9710
  }
9616
- if (!graph.defaultAgentId) {
9711
+ if (!graph.defaultSubAgentId) {
9617
9712
  return c.json(
9618
9713
  {
9619
9714
  jsonrpc: "2.0",
@@ -9623,10 +9718,10 @@ app.post("/a2a", async (c) => {
9623
9718
  400
9624
9719
  );
9625
9720
  }
9626
- executionContext.agentId = graph.defaultAgentId;
9721
+ executionContext.subAgentId = graph.defaultSubAgentId;
9627
9722
  const credentialStores = c.get("credentialStores");
9628
- const defaultAgent = await getRegisteredAgent(executionContext, credentialStores);
9629
- if (!defaultAgent) {
9723
+ const defaultSubAgent = await getRegisteredAgent(executionContext, credentialStores);
9724
+ if (!defaultSubAgent) {
9630
9725
  return c.json(
9631
9726
  {
9632
9727
  jsonrpc: "2.0",
@@ -9636,7 +9731,7 @@ app.post("/a2a", async (c) => {
9636
9731
  404
9637
9732
  );
9638
9733
  }
9639
- return a2aHandler(c, defaultAgent);
9734
+ return a2aHandler(c, defaultSubAgent);
9640
9735
  }
9641
9736
  });
9642
9737
  var agents_default = app;
@@ -9647,20 +9742,20 @@ init_dbClient();
9647
9742
  // src/a2a/transfer.ts
9648
9743
  init_dbClient();
9649
9744
  init_logger();
9650
- var logger22 = agentsCore.getLogger("Transfer");
9745
+ var logger21 = agentsCore.getLogger("Transfer");
9651
9746
  async function executeTransfer({
9652
9747
  tenantId,
9653
9748
  threadId,
9654
9749
  projectId,
9655
- targetAgentId
9750
+ targetSubAgentId
9656
9751
  }) {
9657
- logger22.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
9752
+ logger21.info({ targetAgent: targetSubAgentId }, "Executing transfer to agent");
9658
9753
  await agentsCore.setActiveAgentForThread(dbClient_default)({
9659
9754
  scopes: { tenantId, projectId },
9660
9755
  threadId,
9661
- agentId: targetAgentId
9756
+ subAgentId: targetSubAgentId
9662
9757
  });
9663
- return { success: true, targetAgentId };
9758
+ return { success: true, targetSubAgentId };
9664
9759
  }
9665
9760
  function isTransferResponse(result) {
9666
9761
  return result?.artifacts.some(
@@ -10240,7 +10335,7 @@ function createMCPStreamHelper() {
10240
10335
  }
10241
10336
 
10242
10337
  // src/handlers/executionHandler.ts
10243
- var logger23 = agentsCore.getLogger("ExecutionHandler");
10338
+ var logger22 = agentsCore.getLogger("ExecutionHandler");
10244
10339
  var ExecutionHandler = class {
10245
10340
  constructor() {
10246
10341
  // Hardcoded error limit - separate from configurable stopWhen
@@ -10276,7 +10371,7 @@ var ExecutionHandler = class {
10276
10371
  if (emitOperations) {
10277
10372
  graphSessionManager.enableEmitOperations(requestId2);
10278
10373
  }
10279
- logger23.info(
10374
+ logger22.info(
10280
10375
  { sessionId: requestId2, graphId, conversationId, emitOperations },
10281
10376
  "Created GraphSession for message execution"
10282
10377
  );
@@ -10291,7 +10386,7 @@ var ExecutionHandler = class {
10291
10386
  );
10292
10387
  }
10293
10388
  } catch (error) {
10294
- logger23.error(
10389
+ logger22.error(
10295
10390
  {
10296
10391
  error: error instanceof Error ? error.message : "Unknown error",
10297
10392
  stack: error instanceof Error ? error.stack : void 0
@@ -10307,7 +10402,7 @@ var ExecutionHandler = class {
10307
10402
  try {
10308
10403
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
10309
10404
  const taskId = `task_${conversationId}-${requestId2}`;
10310
- logger23.info(
10405
+ logger22.info(
10311
10406
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
10312
10407
  "Attempting to create or reuse existing task"
10313
10408
  );
@@ -10317,7 +10412,7 @@ var ExecutionHandler = class {
10317
10412
  tenantId,
10318
10413
  projectId,
10319
10414
  graphId,
10320
- agentId: currentAgentId,
10415
+ subAgentId: currentAgentId,
10321
10416
  contextId: conversationId,
10322
10417
  status: "pending",
10323
10418
  metadata: {
@@ -10331,7 +10426,7 @@ var ExecutionHandler = class {
10331
10426
  agent_id: currentAgentId
10332
10427
  }
10333
10428
  });
10334
- logger23.info(
10429
+ logger22.info(
10335
10430
  {
10336
10431
  taskId,
10337
10432
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -10340,27 +10435,27 @@ var ExecutionHandler = class {
10340
10435
  );
10341
10436
  } catch (error) {
10342
10437
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
10343
- logger23.info(
10438
+ logger22.info(
10344
10439
  { taskId, error: error.message },
10345
10440
  "Task already exists, fetching existing task"
10346
10441
  );
10347
10442
  const existingTask = await agentsCore.getTask(dbClient_default)({ id: taskId });
10348
10443
  if (existingTask) {
10349
10444
  task = existingTask;
10350
- logger23.info(
10445
+ logger22.info(
10351
10446
  { taskId, existingTask },
10352
10447
  "Successfully reused existing task from race condition"
10353
10448
  );
10354
10449
  } else {
10355
- logger23.error({ taskId, error }, "Task constraint failed but task not found");
10450
+ logger22.error({ taskId, error }, "Task constraint failed but task not found");
10356
10451
  throw error;
10357
10452
  }
10358
10453
  } else {
10359
- logger23.error({ taskId, error }, "Failed to create task due to non-constraint error");
10454
+ logger22.error({ taskId, error }, "Failed to create task due to non-constraint error");
10360
10455
  throw error;
10361
10456
  }
10362
10457
  }
10363
- logger23.debug(
10458
+ logger22.debug(
10364
10459
  {
10365
10460
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
10366
10461
  executionType: "create_initial_task",
@@ -10378,7 +10473,7 @@ var ExecutionHandler = class {
10378
10473
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
10379
10474
  while (iterations < maxTransfers) {
10380
10475
  iterations++;
10381
- logger23.info(
10476
+ logger22.info(
10382
10477
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
10383
10478
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
10384
10479
  );
@@ -10386,10 +10481,10 @@ var ExecutionHandler = class {
10386
10481
  scopes: { tenantId, projectId },
10387
10482
  conversationId
10388
10483
  });
10389
- logger23.info({ activeAgent }, "activeAgent");
10390
- if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
10391
- currentAgentId = activeAgent.activeAgentId;
10392
- logger23.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10484
+ logger22.info({ activeAgent }, "activeAgent");
10485
+ if (activeAgent && activeAgent.activeSubAgentId !== currentAgentId) {
10486
+ currentAgentId = activeAgent.activeSubAgentId;
10487
+ logger22.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10393
10488
  }
10394
10489
  const agentBaseUrl = `${baseUrl}/agents`;
10395
10490
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -10430,13 +10525,13 @@ var ExecutionHandler = class {
10430
10525
  });
10431
10526
  if (!messageResponse?.result) {
10432
10527
  errorCount++;
10433
- logger23.error(
10528
+ logger22.error(
10434
10529
  { currentAgentId, iterations, errorCount },
10435
10530
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
10436
10531
  );
10437
10532
  if (errorCount >= this.MAX_ERRORS) {
10438
10533
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
10439
- logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10534
+ logger22.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10440
10535
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
10441
10536
  if (task) {
10442
10537
  await agentsCore.updateTask(dbClient_default)({
@@ -10459,20 +10554,20 @@ var ExecutionHandler = class {
10459
10554
  }
10460
10555
  if (isTransferResponse(messageResponse.result)) {
10461
10556
  const transferResponse = messageResponse.result;
10462
- const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
10557
+ const targetSubAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetSubAgentId;
10463
10558
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
10464
- logger23.info({ targetAgentId, transferReason }, "transfer response");
10559
+ logger22.info({ targetSubAgentId, transferReason }, "transfer response");
10465
10560
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
10466
- const { success, targetAgentId: newAgentId } = await executeTransfer({
10561
+ const { success, targetSubAgentId: newAgentId } = await executeTransfer({
10467
10562
  projectId,
10468
10563
  tenantId,
10469
10564
  threadId: conversationId,
10470
- targetAgentId
10565
+ targetSubAgentId
10471
10566
  });
10472
10567
  if (success) {
10473
10568
  fromAgentId = currentAgentId;
10474
10569
  currentAgentId = newAgentId;
10475
- logger23.info(
10570
+ logger22.info(
10476
10571
  {
10477
10572
  transferFrom: fromAgentId,
10478
10573
  transferTo: currentAgentId,
@@ -10483,14 +10578,27 @@ var ExecutionHandler = class {
10483
10578
  }
10484
10579
  continue;
10485
10580
  }
10486
- const responseParts = messageResponse.result.artifacts?.flatMap(
10487
- (artifact) => artifact.parts || []
10488
- ) || [];
10581
+ let responseParts = [];
10582
+ if (messageResponse.result.streamedContent?.parts) {
10583
+ responseParts = messageResponse.result.streamedContent.parts;
10584
+ logger22.info(
10585
+ { partsCount: responseParts.length },
10586
+ "Using streamed content for conversation history"
10587
+ );
10588
+ } else {
10589
+ responseParts = messageResponse.result.artifacts?.flatMap(
10590
+ (artifact) => artifact.parts || []
10591
+ ) || [];
10592
+ logger22.info(
10593
+ { partsCount: responseParts.length },
10594
+ "Using artifacts for conversation history (fallback)"
10595
+ );
10596
+ }
10489
10597
  if (responseParts && responseParts.length > 0) {
10490
10598
  const graphSessionData = graphSessionManager.getSession(requestId2);
10491
10599
  if (graphSessionData) {
10492
10600
  const sessionSummary = graphSessionData.getSummary();
10493
- logger23.info(sessionSummary, "GraphSession data after completion");
10601
+ logger22.info(sessionSummary, "GraphSession data after completion");
10494
10602
  }
10495
10603
  let textContent = "";
10496
10604
  for (const part of responseParts) {
@@ -10522,8 +10630,7 @@ var ExecutionHandler = class {
10522
10630
  },
10523
10631
  visibility: "user-facing",
10524
10632
  messageType: "chat",
10525
- agentId: currentAgentId,
10526
- fromAgentId: currentAgentId,
10633
+ fromSubAgentId: currentAgentId,
10527
10634
  taskId: task.id
10528
10635
  });
10529
10636
  const updateTaskStart = Date.now();
@@ -10544,22 +10651,22 @@ var ExecutionHandler = class {
10544
10651
  }
10545
10652
  });
10546
10653
  const updateTaskEnd = Date.now();
10547
- logger23.info(
10654
+ logger22.info(
10548
10655
  { duration: updateTaskEnd - updateTaskStart },
10549
10656
  "Completed updateTask operation"
10550
10657
  );
10551
10658
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
10552
10659
  await sseHelper.complete();
10553
- logger23.info({}, "Ending GraphSession and cleaning up");
10660
+ logger22.info({}, "Ending GraphSession and cleaning up");
10554
10661
  graphSessionManager.endSession(requestId2);
10555
- logger23.info({}, "Cleaning up streamHelper");
10662
+ logger22.info({}, "Cleaning up streamHelper");
10556
10663
  unregisterStreamHelper(requestId2);
10557
10664
  let response;
10558
10665
  if (sseHelper instanceof MCPStreamHelper) {
10559
10666
  const captured = sseHelper.getCapturedResponse();
10560
10667
  response = captured.text || "No response content";
10561
10668
  }
10562
- logger23.info({}, "ExecutionHandler returning success");
10669
+ logger22.info({}, "ExecutionHandler returning success");
10563
10670
  return { success: true, iterations, response };
10564
10671
  } catch (error) {
10565
10672
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -10570,13 +10677,13 @@ var ExecutionHandler = class {
10570
10677
  });
10571
10678
  }
10572
10679
  errorCount++;
10573
- logger23.warn(
10680
+ logger22.warn(
10574
10681
  { iterations, errorCount },
10575
10682
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
10576
10683
  );
10577
10684
  if (errorCount >= this.MAX_ERRORS) {
10578
10685
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
10579
- logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10686
+ logger22.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10580
10687
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
10581
10688
  if (task) {
10582
10689
  await agentsCore.updateTask(dbClient_default)({
@@ -10597,7 +10704,7 @@ var ExecutionHandler = class {
10597
10704
  }
10598
10705
  }
10599
10706
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
10600
- logger23.error({ maxTransfers, iterations }, errorMessage);
10707
+ logger22.error({ maxTransfers, iterations }, errorMessage);
10601
10708
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
10602
10709
  if (task) {
10603
10710
  await agentsCore.updateTask(dbClient_default)({
@@ -10616,7 +10723,7 @@ var ExecutionHandler = class {
10616
10723
  unregisterStreamHelper(requestId2);
10617
10724
  return { success: false, error: errorMessage, iterations };
10618
10725
  } catch (error) {
10619
- logger23.error({ error }, "Error in execution handler");
10726
+ logger22.error({ error }, "Error in execution handler");
10620
10727
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
10621
10728
  await sseHelper.writeOperation(
10622
10729
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -10644,7 +10751,7 @@ var ExecutionHandler = class {
10644
10751
  // src/routes/chat.ts
10645
10752
  init_logger();
10646
10753
  var app2 = new zodOpenapi.OpenAPIHono();
10647
- var logger24 = agentsCore.getLogger("completionsHandler");
10754
+ var logger23 = agentsCore.getLogger("completionsHandler");
10648
10755
  var chatCompletionsRoute = zodOpenapi.createRoute({
10649
10756
  method: "post",
10650
10757
  path: "/completions",
@@ -10762,7 +10869,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10762
10869
  tracestate: c.req.header("tracestate"),
10763
10870
  baggage: c.req.header("baggage")
10764
10871
  };
10765
- logger24.info(
10872
+ logger23.info(
10766
10873
  {
10767
10874
  otelHeaders,
10768
10875
  path: c.req.path,
@@ -10786,20 +10893,20 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10786
10893
  scopes: { tenantId, projectId, graphId }
10787
10894
  });
10788
10895
  let agentGraph;
10789
- let defaultAgentId;
10896
+ let defaultSubAgentId;
10790
10897
  if (fullGraph) {
10791
10898
  agentGraph = {
10792
10899
  id: fullGraph.id,
10793
10900
  name: fullGraph.name,
10794
10901
  tenantId,
10795
10902
  projectId,
10796
- defaultAgentId: fullGraph.defaultAgentId
10903
+ defaultSubAgentId: fullGraph.defaultSubAgentId
10797
10904
  };
10798
- const agentKeys = Object.keys(fullGraph.agents || {});
10905
+ const agentKeys = Object.keys(fullGraph.subAgents || {});
10799
10906
  const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
10800
- defaultAgentId = fullGraph.defaultAgentId || firstAgentId;
10907
+ defaultSubAgentId = fullGraph.defaultSubAgentId || firstAgentId;
10801
10908
  } else {
10802
- agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
10909
+ agentGraph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
10803
10910
  scopes: { tenantId, projectId, graphId }
10804
10911
  });
10805
10912
  if (!agentGraph) {
@@ -10808,9 +10915,9 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10808
10915
  message: "Agent graph not found"
10809
10916
  });
10810
10917
  }
10811
- defaultAgentId = agentGraph.defaultAgentId || "";
10918
+ defaultSubAgentId = agentGraph.defaultSubAgentId || "";
10812
10919
  }
10813
- if (!defaultAgentId) {
10920
+ if (!defaultSubAgentId) {
10814
10921
  throw agentsCore.createApiError({
10815
10922
  code: "not_found",
10816
10923
  message: "No default agent found in graph"
@@ -10820,7 +10927,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10820
10927
  tenantId,
10821
10928
  projectId,
10822
10929
  id: conversationId,
10823
- activeAgentId: defaultAgentId
10930
+ activeSubAgentId: defaultSubAgentId
10824
10931
  });
10825
10932
  const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
10826
10933
  scopes: { tenantId, projectId },
@@ -10830,13 +10937,13 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10830
10937
  agentsCore.setActiveAgentForConversation(dbClient_default)({
10831
10938
  scopes: { tenantId, projectId },
10832
10939
  conversationId,
10833
- agentId: defaultAgentId
10940
+ subAgentId: defaultSubAgentId
10834
10941
  });
10835
10942
  }
10836
- const agentId = activeAgent?.activeAgentId || defaultAgentId;
10837
- const agentInfo = await agentsCore.getAgentById(dbClient_default)({
10943
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
10944
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
10838
10945
  scopes: { tenantId, projectId, graphId },
10839
- agentId
10946
+ subAgentId
10840
10947
  });
10841
10948
  if (!agentInfo) {
10842
10949
  throw agentsCore.createApiError({
@@ -10855,14 +10962,14 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10855
10962
  dbClient: dbClient_default,
10856
10963
  credentialStores
10857
10964
  });
10858
- logger24.info(
10965
+ logger23.info(
10859
10966
  {
10860
10967
  tenantId,
10861
10968
  projectId,
10862
10969
  graphId,
10863
10970
  conversationId,
10864
- defaultAgentId,
10865
- activeAgentId: activeAgent?.activeAgentId || "none",
10971
+ defaultSubAgentId,
10972
+ activeSubAgentId: activeAgent?.activeSubAgentId || "none",
10866
10973
  hasContextConfig: !!agentGraph.contextConfigId,
10867
10974
  hasHeaders: !!body.headers,
10868
10975
  hasValidatedContext: !!validatedContext,
@@ -10903,7 +11010,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10903
11010
  try {
10904
11011
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
10905
11012
  await sseHelper.writeRole();
10906
- logger24.info({ agentId }, "Starting execution");
11013
+ logger23.info({ subAgentId }, "Starting execution");
10907
11014
  const emitOperationsHeader = c.req.header("x-emit-operations");
10908
11015
  const emitOperations = emitOperationsHeader === "true";
10909
11016
  const executionHandler = new ExecutionHandler();
@@ -10911,12 +11018,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10911
11018
  executionContext,
10912
11019
  conversationId,
10913
11020
  userMessage,
10914
- initialAgentId: agentId,
11021
+ initialAgentId: subAgentId,
10915
11022
  requestId: requestId2,
10916
11023
  sseHelper,
10917
11024
  emitOperations
10918
11025
  });
10919
- logger24.info(
11026
+ logger23.info(
10920
11027
  { result },
10921
11028
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10922
11029
  );
@@ -10930,7 +11037,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10930
11037
  }
10931
11038
  await sseHelper.complete();
10932
11039
  } catch (error) {
10933
- logger24.error(
11040
+ logger23.error(
10934
11041
  {
10935
11042
  error: error instanceof Error ? error.message : error,
10936
11043
  stack: error instanceof Error ? error.stack : void 0
@@ -10947,12 +11054,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10947
11054
  );
10948
11055
  await sseHelper.complete();
10949
11056
  } catch (streamError) {
10950
- logger24.error({ streamError }, "Failed to write error to stream");
11057
+ logger23.error({ streamError }, "Failed to write error to stream");
10951
11058
  }
10952
11059
  }
10953
11060
  });
10954
11061
  } catch (error) {
10955
- logger24.error(
11062
+ logger23.error(
10956
11063
  {
10957
11064
  error: error instanceof Error ? error.message : error,
10958
11065
  stack: error instanceof Error ? error.stack : void 0
@@ -10980,7 +11087,7 @@ var chat_default = app2;
10980
11087
  init_dbClient();
10981
11088
  init_logger();
10982
11089
  var app3 = new zodOpenapi.OpenAPIHono();
10983
- var logger25 = agentsCore.getLogger("chatDataStream");
11090
+ var logger24 = agentsCore.getLogger("chatDataStream");
10984
11091
  var chatDataStreamRoute = zodOpenapi.createRoute({
10985
11092
  method: "post",
10986
11093
  path: "/chat",
@@ -11045,7 +11152,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11045
11152
  "project.id": projectId
11046
11153
  });
11047
11154
  }
11048
- const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
11155
+ const agentGraph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
11049
11156
  scopes: { tenantId, projectId, graphId }
11050
11157
  });
11051
11158
  if (!agentGraph) {
@@ -11054,9 +11161,9 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11054
11161
  message: "Agent graph not found"
11055
11162
  });
11056
11163
  }
11057
- const defaultAgentId = agentGraph.defaultAgentId;
11164
+ const defaultSubAgentId = agentGraph.defaultSubAgentId;
11058
11165
  const graphName = agentGraph.name;
11059
- if (!defaultAgentId) {
11166
+ if (!defaultSubAgentId) {
11060
11167
  throw agentsCore.createApiError({
11061
11168
  code: "bad_request",
11062
11169
  message: "Graph does not have a default agent configured"
@@ -11070,13 +11177,13 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11070
11177
  agentsCore.setActiveAgentForConversation(dbClient_default)({
11071
11178
  scopes: { tenantId, projectId },
11072
11179
  conversationId,
11073
- agentId: defaultAgentId
11180
+ subAgentId: defaultSubAgentId
11074
11181
  });
11075
11182
  }
11076
- const agentId = activeAgent?.activeAgentId || defaultAgentId;
11077
- const agentInfo = await agentsCore.getAgentById(dbClient_default)({
11183
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11184
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11078
11185
  scopes: { tenantId, projectId, graphId },
11079
- agentId
11186
+ subAgentId
11080
11187
  });
11081
11188
  if (!agentInfo) {
11082
11189
  throw agentsCore.createApiError({
@@ -11097,7 +11204,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11097
11204
  });
11098
11205
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
11099
11206
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
11100
- logger25.info({ userText, lastUserMessage }, "userText");
11207
+ logger24.info({ userText, lastUserMessage }, "userText");
11101
11208
  const messageSpan = api.trace.getActiveSpan();
11102
11209
  if (messageSpan) {
11103
11210
  messageSpan.setAttributes({
@@ -11133,7 +11240,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11133
11240
  executionContext,
11134
11241
  conversationId,
11135
11242
  userMessage: userText,
11136
- initialAgentId: agentId,
11243
+ initialAgentId: subAgentId,
11137
11244
  requestId: `chatds-${Date.now()}`,
11138
11245
  sseHelper: streamHelper,
11139
11246
  emitOperations
@@ -11142,7 +11249,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11142
11249
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
11143
11250
  }
11144
11251
  } catch (err) {
11145
- logger25.error({ err }, "Streaming error");
11252
+ logger24.error({ err }, "Streaming error");
11146
11253
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
11147
11254
  } finally {
11148
11255
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -11163,7 +11270,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11163
11270
  )
11164
11271
  );
11165
11272
  } catch (error) {
11166
- logger25.error({ error }, "chatDataStream error");
11273
+ logger24.error({ error }, "chatDataStream error");
11167
11274
  throw agentsCore.createApiError({
11168
11275
  code: "internal_server_error",
11169
11276
  message: "Failed to process chat completion"
@@ -11178,7 +11285,7 @@ init_logger();
11178
11285
  function createMCPSchema(schema) {
11179
11286
  return schema;
11180
11287
  }
11181
- var logger26 = agentsCore.getLogger("mcp");
11288
+ var logger25 = agentsCore.getLogger("mcp");
11182
11289
  var _MockResponseSingleton = class _MockResponseSingleton {
11183
11290
  constructor() {
11184
11291
  __publicField(this, "mockRes");
@@ -11233,21 +11340,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
11233
11340
  id: 0
11234
11341
  });
11235
11342
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
11236
- logger26.info({ sessionId }, "Spoofing initialization message to set transport state");
11343
+ logger25.info({ sessionId }, "Spoofing initialization message to set transport state");
11237
11344
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
11238
11345
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
11239
11346
  try {
11240
11347
  await transport.handleRequest(req, mockRes, spoofInitMessage);
11241
- logger26.info({ sessionId }, "Successfully spoofed initialization");
11348
+ logger25.info({ sessionId }, "Successfully spoofed initialization");
11242
11349
  } catch (spoofError) {
11243
- logger26.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11350
+ logger25.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11244
11351
  }
11245
11352
  };
11246
11353
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
11247
11354
  const sessionId = req.headers["mcp-session-id"];
11248
- logger26.info({ sessionId }, "Received MCP session ID");
11355
+ logger25.info({ sessionId }, "Received MCP session ID");
11249
11356
  if (!sessionId) {
11250
- logger26.info({ body }, "Missing session ID");
11357
+ logger25.info({ body }, "Missing session ID");
11251
11358
  res.writeHead(400).end(
11252
11359
  JSON.stringify({
11253
11360
  jsonrpc: "2.0",
@@ -11273,7 +11380,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
11273
11380
  scopes: { tenantId, projectId },
11274
11381
  conversationId: sessionId
11275
11382
  });
11276
- logger26.info(
11383
+ logger25.info(
11277
11384
  {
11278
11385
  sessionId,
11279
11386
  conversationFound: !!conversation,
@@ -11284,7 +11391,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
11284
11391
  "Conversation lookup result"
11285
11392
  );
11286
11393
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
11287
- logger26.info(
11394
+ logger25.info(
11288
11395
  { sessionId, conversationId: conversation?.id },
11289
11396
  "MCP session not found or invalid"
11290
11397
  );
@@ -11333,7 +11440,7 @@ var processUserMessage = async (tenantId, projectId, conversationId, query) => {
11333
11440
  messageType: "chat"
11334
11441
  });
11335
11442
  };
11336
- var executeAgentQuery = async (executionContext, conversationId, query, defaultAgentId) => {
11443
+ var executeAgentQuery = async (executionContext, conversationId, query, defaultSubAgentId) => {
11337
11444
  const requestId2 = `mcp-${Date.now()}`;
11338
11445
  const mcpStreamHelper = createMCPStreamHelper();
11339
11446
  const executionHandler = new ExecutionHandler();
@@ -11341,11 +11448,11 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
11341
11448
  executionContext,
11342
11449
  conversationId,
11343
11450
  userMessage: query,
11344
- initialAgentId: defaultAgentId,
11451
+ initialAgentId: defaultSubAgentId,
11345
11452
  requestId: requestId2,
11346
11453
  sseHelper: mcpStreamHelper
11347
11454
  });
11348
- logger26.info(
11455
+ logger25.info(
11349
11456
  { result },
11350
11457
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11351
11458
  );
@@ -11372,7 +11479,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
11372
11479
  var getServer = async (headers, executionContext, conversationId, credentialStores) => {
11373
11480
  const { tenantId, projectId, graphId } = executionContext;
11374
11481
  setupTracing(conversationId, tenantId, graphId);
11375
- const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
11482
+ const agentGraph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
11376
11483
  scopes: { tenantId, projectId, graphId }
11377
11484
  });
11378
11485
  if (!agentGraph) {
@@ -11393,7 +11500,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11393
11500
  },
11394
11501
  async ({ query }) => {
11395
11502
  try {
11396
- if (!agentGraph.defaultAgentId) {
11503
+ if (!agentGraph.defaultSubAgentId) {
11397
11504
  return {
11398
11505
  content: [
11399
11506
  {
@@ -11404,10 +11511,10 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11404
11511
  isError: true
11405
11512
  };
11406
11513
  }
11407
- const defaultAgentId = agentGraph.defaultAgentId;
11408
- const agentInfo = await agentsCore.getAgentById(dbClient_default)({
11514
+ const defaultSubAgentId = agentGraph.defaultSubAgentId;
11515
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11409
11516
  scopes: { tenantId, projectId, graphId },
11410
- agentId: defaultAgentId
11517
+ subAgentId: defaultSubAgentId
11411
11518
  });
11412
11519
  if (!agentInfo) {
11413
11520
  return {
@@ -11429,7 +11536,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11429
11536
  dbClient: dbClient_default,
11430
11537
  credentialStores
11431
11538
  });
11432
- logger26.info(
11539
+ logger25.info(
11433
11540
  {
11434
11541
  tenantId,
11435
11542
  projectId,
@@ -11442,7 +11549,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11442
11549
  "parameters"
11443
11550
  );
11444
11551
  await processUserMessage(tenantId, projectId, conversationId, query);
11445
- return executeAgentQuery(executionContext, conversationId, query, defaultAgentId);
11552
+ return executeAgentQuery(executionContext, conversationId, query, defaultSubAgentId);
11446
11553
  } catch (error) {
11447
11554
  return {
11448
11555
  content: [
@@ -11491,9 +11598,9 @@ var validateRequestParameters = (c) => {
11491
11598
  };
11492
11599
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
11493
11600
  const { tenantId, projectId, graphId } = executionContext;
11494
- logger26.info({ body }, "Received initialization request");
11601
+ logger25.info({ body }, "Received initialization request");
11495
11602
  const sessionId = agentsCore.getConversationId();
11496
- const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
11603
+ const agentGraph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
11497
11604
  scopes: { tenantId, projectId, graphId }
11498
11605
  });
11499
11606
  if (!agentGraph) {
@@ -11506,7 +11613,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11506
11613
  { status: 404 }
11507
11614
  );
11508
11615
  }
11509
- if (!agentGraph.defaultAgentId) {
11616
+ if (!agentGraph.defaultSubAgentId) {
11510
11617
  return c.json(
11511
11618
  {
11512
11619
  jsonrpc: "2.0",
@@ -11520,7 +11627,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11520
11627
  id: sessionId,
11521
11628
  tenantId,
11522
11629
  projectId,
11523
- activeAgentId: agentGraph.defaultAgentId,
11630
+ activeSubAgentId: agentGraph.defaultSubAgentId,
11524
11631
  metadata: {
11525
11632
  sessionData: {
11526
11633
  graphId,
@@ -11531,7 +11638,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11531
11638
  }
11532
11639
  }
11533
11640
  });
11534
- logger26.info(
11641
+ logger25.info(
11535
11642
  { sessionId, conversationId: conversation.id },
11536
11643
  "Created MCP session as conversation"
11537
11644
  );
@@ -11540,9 +11647,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11540
11647
  });
11541
11648
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
11542
11649
  await server.connect(transport);
11543
- logger26.info({ sessionId }, "Server connected for initialization");
11650
+ logger25.info({ sessionId }, "Server connected for initialization");
11544
11651
  res.setHeader("Mcp-Session-Id", sessionId);
11545
- logger26.info(
11652
+ logger25.info(
11546
11653
  {
11547
11654
  sessionId,
11548
11655
  bodyMethod: body?.method,
@@ -11551,7 +11658,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11551
11658
  "About to handle initialization request"
11552
11659
  );
11553
11660
  await transport.handleRequest(req, res, body);
11554
- logger26.info({ sessionId }, "Successfully handled initialization request");
11661
+ logger25.info({ sessionId }, "Successfully handled initialization request");
11555
11662
  return fetchToNode.toFetchResponse(res);
11556
11663
  };
11557
11664
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -11579,8 +11686,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
11579
11686
  sessionId,
11580
11687
  conversation.metadata?.session_data?.mcpProtocolVersion
11581
11688
  );
11582
- logger26.info({ sessionId }, "Server connected and transport initialized");
11583
- logger26.info(
11689
+ logger25.info({ sessionId }, "Server connected and transport initialized");
11690
+ logger25.info(
11584
11691
  {
11585
11692
  sessionId,
11586
11693
  bodyKeys: Object.keys(body || {}),
@@ -11594,9 +11701,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
11594
11701
  );
11595
11702
  try {
11596
11703
  await transport.handleRequest(req, res, body);
11597
- logger26.info({ sessionId }, "Successfully handled MCP request");
11704
+ logger25.info({ sessionId }, "Successfully handled MCP request");
11598
11705
  } catch (transportError) {
11599
- logger26.error(
11706
+ logger25.error(
11600
11707
  {
11601
11708
  sessionId,
11602
11709
  error: transportError,
@@ -11647,13 +11754,13 @@ app4.openapi(
11647
11754
  }
11648
11755
  const { executionContext } = paramValidation;
11649
11756
  const body = c.get("requestBody") || {};
11650
- logger26.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
11757
+ logger25.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
11651
11758
  const isInitRequest = body.method === "initialize";
11652
11759
  const { req, res } = fetchToNode.toReqRes(c.req.raw);
11653
11760
  const validatedContext = c.get("validatedContext") || {};
11654
11761
  const credentialStores = c.get("credentialStores");
11655
- logger26.info({ validatedContext }, "Validated context");
11656
- logger26.info({ req }, "request");
11762
+ logger25.info({ validatedContext }, "Validated context");
11763
+ logger25.info({ req }, "request");
11657
11764
  if (isInitRequest) {
11658
11765
  return await handleInitializationRequest(
11659
11766
  body,
@@ -11675,7 +11782,7 @@ app4.openapi(
11675
11782
  );
11676
11783
  }
11677
11784
  } catch (e) {
11678
- logger26.error(
11785
+ logger25.error(
11679
11786
  {
11680
11787
  error: e instanceof Error ? e.message : e,
11681
11788
  stack: e instanceof Error ? e.stack : void 0
@@ -11687,7 +11794,7 @@ app4.openapi(
11687
11794
  }
11688
11795
  );
11689
11796
  app4.get("/", async (c) => {
11690
- logger26.info({}, "Received GET MCP request");
11797
+ logger25.info({}, "Received GET MCP request");
11691
11798
  return c.json(
11692
11799
  {
11693
11800
  jsonrpc: "2.0",
@@ -11701,7 +11808,7 @@ app4.get("/", async (c) => {
11701
11808
  );
11702
11809
  });
11703
11810
  app4.delete("/", async (c) => {
11704
- logger26.info({}, "Received DELETE MCP request");
11811
+ logger25.info({}, "Received DELETE MCP request");
11705
11812
  return c.json(
11706
11813
  {
11707
11814
  jsonrpc: "2.0",
@@ -11714,7 +11821,7 @@ app4.delete("/", async (c) => {
11714
11821
  var mcp_default = app4;
11715
11822
 
11716
11823
  // src/app.ts
11717
- var logger27 = agentsCore.getLogger("agents-run-api");
11824
+ var logger26 = agentsCore.getLogger("agents-run-api");
11718
11825
  function createExecutionHono(serverConfig, credentialStores) {
11719
11826
  const app6 = new zodOpenapi.OpenAPIHono();
11720
11827
  app6.use("*", otel.otel());
@@ -11730,7 +11837,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11730
11837
  const body = await c.req.json();
11731
11838
  c.set("requestBody", body);
11732
11839
  } catch (error) {
11733
- logger27.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
11840
+ logger26.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
11734
11841
  }
11735
11842
  }
11736
11843
  return next();
@@ -11781,8 +11888,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11781
11888
  if (!isExpectedError) {
11782
11889
  const errorMessage = err instanceof Error ? err.message : String(err);
11783
11890
  const errorStack = err instanceof Error ? err.stack : void 0;
11784
- if (logger27) {
11785
- logger27.error(
11891
+ if (logger26) {
11892
+ logger26.error(
11786
11893
  {
11787
11894
  error: err,
11788
11895
  message: errorMessage,
@@ -11794,8 +11901,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11794
11901
  );
11795
11902
  }
11796
11903
  } else {
11797
- if (logger27) {
11798
- logger27.error(
11904
+ if (logger26) {
11905
+ logger26.error(
11799
11906
  {
11800
11907
  error: err,
11801
11908
  path: c.req.path,
@@ -11812,8 +11919,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11812
11919
  const response = err.getResponse();
11813
11920
  return response;
11814
11921
  } catch (responseError) {
11815
- if (logger27) {
11816
- logger27.error({ error: responseError }, "Error while handling HTTPException response");
11922
+ if (logger26) {
11923
+ logger26.error({ error: responseError }, "Error while handling HTTPException response");
11817
11924
  }
11818
11925
  }
11819
11926
  }
@@ -11847,7 +11954,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11847
11954
  app6.use("*", async (c, next) => {
11848
11955
  const executionContext = c.get("executionContext");
11849
11956
  if (!executionContext) {
11850
- logger27.debug({}, "Empty execution context");
11957
+ logger26.debug({}, "Empty execution context");
11851
11958
  return next();
11852
11959
  }
11853
11960
  const { tenantId, projectId, graphId } = executionContext;
@@ -11856,7 +11963,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11856
11963
  if (requestBody) {
11857
11964
  conversationId = requestBody.conversationId;
11858
11965
  if (!conversationId) {
11859
- logger27.debug({ requestBody }, "No conversation ID found in request body");
11966
+ logger26.debug({ requestBody }, "No conversation ID found in request body");
11860
11967
  }
11861
11968
  }
11862
11969
  const entries = Object.fromEntries(
@@ -11871,7 +11978,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11871
11978
  })
11872
11979
  );
11873
11980
  if (!Object.keys(entries).length) {
11874
- logger27.debug({}, "Empty entries for baggage");
11981
+ logger26.debug({}, "Empty entries for baggage");
11875
11982
  return next();
11876
11983
  }
11877
11984
  const bag = Object.entries(entries).reduce(