@inkeep/agents-run-api 0.0.0-dev-20251009194333 → 0.0.0-dev-20251009221341

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
  });
@@ -807,7 +809,7 @@ function createExecutionContext(params) {
807
809
  graphId: params.graphId,
808
810
  baseUrl: params.baseUrl || process.env.API_URL || "http://localhost:3003",
809
811
  apiKeyId: params.apiKeyId,
810
- agentId: params.agentId
812
+ subAgentId: params.subAgentId
811
813
  };
812
814
  }
813
815
 
@@ -822,7 +824,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
822
824
  const tenantId = c.req.header("x-inkeep-tenant-id");
823
825
  const projectId = c.req.header("x-inkeep-project-id");
824
826
  const graphId = c.req.header("x-inkeep-graph-id");
825
- const agentId = c.req.header("x-inkeep-agent-id");
827
+ const subAgentId = c.req.header("x-inkeep-agent-id");
826
828
  const proto = c.req.header("x-forwarded-proto")?.split(",")[0].trim();
827
829
  const fwdHost = c.req.header("x-forwarded-host")?.split(",")[0].trim();
828
830
  const host = fwdHost ?? c.req.header("host");
@@ -833,7 +835,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
833
835
  if (authHeader?.startsWith("Bearer ")) {
834
836
  try {
835
837
  executionContext = await extractContextFromApiKey(authHeader.substring(7), baseUrl);
836
- executionContext.agentId = agentId;
838
+ executionContext.subAgentId = subAgentId;
837
839
  logger2.info({}, "Development/test environment - API key authenticated successfully");
838
840
  } catch {
839
841
  executionContext = createExecutionContext({
@@ -843,7 +845,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
843
845
  graphId: graphId || "test-graph",
844
846
  apiKeyId: "test-key",
845
847
  baseUrl,
846
- agentId
848
+ subAgentId
847
849
  });
848
850
  logger2.info(
849
851
  {},
@@ -858,7 +860,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
858
860
  graphId: graphId || "test-graph",
859
861
  apiKeyId: "test-key",
860
862
  baseUrl,
861
- agentId
863
+ subAgentId
862
864
  });
863
865
  logger2.info(
864
866
  {},
@@ -889,7 +891,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
889
891
  graphId,
890
892
  apiKeyId: "bypass",
891
893
  baseUrl,
892
- agentId
894
+ subAgentId
893
895
  });
894
896
  c.set("executionContext", executionContext);
895
897
  logger2.info({}, "Bypass secret authenticated successfully");
@@ -897,7 +899,7 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
897
899
  return;
898
900
  } else if (apiKey) {
899
901
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
900
- executionContext.agentId = agentId;
902
+ executionContext.subAgentId = subAgentId;
901
903
  c.set("executionContext", executionContext);
902
904
  logger2.info({}, "API key authenticated successfully");
903
905
  await next();
@@ -915,14 +917,14 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
915
917
  }
916
918
  try {
917
919
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
918
- executionContext.agentId = agentId;
920
+ executionContext.subAgentId = subAgentId;
919
921
  c.set("executionContext", executionContext);
920
922
  logger2.debug(
921
923
  {
922
924
  tenantId: executionContext.tenantId,
923
925
  projectId: executionContext.projectId,
924
926
  graphId: executionContext.graphId,
925
- agentId: executionContext.agentId
927
+ subAgentId: executionContext.subAgentId
926
928
  },
927
929
  "API key authenticated successfully"
928
930
  );
@@ -1097,7 +1099,7 @@ async function handleMessageSend(c, agent, request) {
1097
1099
  logger3.warn(
1098
1100
  {
1099
1101
  taskId: task.id,
1100
- agentId: agent.agentId,
1102
+ subAgentId: agent.subAgentId,
1101
1103
  originalMessage: params.message
1102
1104
  },
1103
1105
  "Created fallback message content for empty delegation message"
@@ -1118,7 +1120,7 @@ async function handleMessageSend(c, agent, request) {
1118
1120
  taskContextId: task.context?.conversationId,
1119
1121
  metadataContextId: params.message.metadata?.conversationId,
1120
1122
  finalContextId: effectiveContextId,
1121
- agentId: agent.agentId
1123
+ subAgentId: agent.subAgentId
1122
1124
  },
1123
1125
  "A2A contextId resolution for delegation"
1124
1126
  );
@@ -1134,11 +1136,11 @@ async function handleMessageSend(c, agent, request) {
1134
1136
  message_id: params.message.messageId || "",
1135
1137
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
1136
1138
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
1137
- agent_id: agent.agentId,
1139
+ agent_id: agent.subAgentId,
1138
1140
  graph_id: graphId || "",
1139
1141
  stream_request_id: params.message.metadata?.stream_request_id
1140
1142
  },
1141
- agentId: agent.agentId,
1143
+ subAgentId: agent.subAgentId,
1142
1144
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1143
1145
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1144
1146
  });
@@ -1161,17 +1163,17 @@ async function handleMessageSend(c, agent, request) {
1161
1163
  };
1162
1164
  if (params.message.metadata?.fromAgentId) {
1163
1165
  messageData.fromAgentId = params.message.metadata.fromAgentId;
1164
- messageData.toAgentId = agent.agentId;
1166
+ messageData.toAgentId = agent.subAgentId;
1165
1167
  } else if (params.message.metadata?.fromExternalAgentId) {
1166
1168
  messageData.fromExternalAgentId = params.message.metadata.fromExternalAgentId;
1167
- messageData.toAgentId = agent.agentId;
1169
+ messageData.toAgentId = agent.subAgentId;
1168
1170
  }
1169
1171
  await agentsCore.createMessage(dbClient_default)(messageData);
1170
1172
  logger3.info(
1171
1173
  {
1172
1174
  fromAgentId: params.message.metadata.fromAgentId,
1173
1175
  fromExternalAgentId: params.message.metadata.fromExternalAgentId,
1174
- toAgentId: agent.agentId,
1176
+ toAgentId: agent.subAgentId,
1175
1177
  conversationId: effectiveContextId,
1176
1178
  messageType: "a2a-request",
1177
1179
  taskId: task.id
@@ -1184,7 +1186,7 @@ async function handleMessageSend(c, agent, request) {
1184
1186
  error,
1185
1187
  fromAgentId: params.message.metadata.fromAgentId,
1186
1188
  fromExternalAgentId: params.message.metadata.fromExternalAgentId,
1187
- toAgentId: agent.agentId,
1189
+ toAgentId: agent.subAgentId,
1188
1190
  conversationId: effectiveContextId
1189
1191
  },
1190
1192
  "Failed to store A2A message in database"
@@ -1201,7 +1203,7 @@ async function handleMessageSend(c, agent, request) {
1201
1203
  message_id: params.message.messageId || "",
1202
1204
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
1203
1205
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
1204
- agent_id: agent.agentId,
1206
+ agent_id: agent.subAgentId,
1205
1207
  graph_id: graphId || ""
1206
1208
  }
1207
1209
  }
@@ -1235,7 +1237,7 @@ async function handleMessageSend(c, agent, request) {
1235
1237
  kind: "data",
1236
1238
  data: {
1237
1239
  type: "transfer",
1238
- targetAgentId: transferPart.data.target
1240
+ targetSubAgentId: transferPart.data.target
1239
1241
  }
1240
1242
  },
1241
1243
  {
@@ -1535,7 +1537,7 @@ async function handleGetCapabilities(c, agent, request) {
1535
1537
  async function handleGetStatus(c, agent, request) {
1536
1538
  return c.json({
1537
1539
  jsonrpc: "2.0",
1538
- result: { status: "ready", agentId: agent.agentId },
1540
+ result: { status: "ready", subAgentId: agent.subAgentId },
1539
1541
  id: request.id
1540
1542
  });
1541
1543
  }
@@ -1599,7 +1601,6 @@ async function handleTasksResubscribe(c, agent, request) {
1599
1601
  }
1600
1602
  }
1601
1603
  init_dbClient();
1602
- agentsCore.getLogger("agents");
1603
1604
  function createAgentCard({
1604
1605
  dbAgent,
1605
1606
  baseUrl
@@ -1677,7 +1678,7 @@ async function hydrateAgent({
1677
1678
  tenantId: dbAgent.tenantId,
1678
1679
  projectId: dbAgent.projectId,
1679
1680
  graphId,
1680
- agentId: dbAgent.id,
1681
+ subAgentId: dbAgent.id,
1681
1682
  baseUrl,
1682
1683
  apiKey
1683
1684
  });
@@ -1687,7 +1688,7 @@ async function hydrateAgent({
1687
1688
  baseUrl
1688
1689
  });
1689
1690
  return {
1690
- agentId: dbAgent.id,
1691
+ subAgentId: dbAgent.id,
1691
1692
  tenantId: dbAgent.tenantId,
1692
1693
  projectId: dbAgent.projectId,
1693
1694
  graphId,
@@ -1700,13 +1701,13 @@ async function hydrateAgent({
1700
1701
  }
1701
1702
  }
1702
1703
  async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
1703
- const { tenantId, projectId, graphId, agentId, baseUrl, apiKey } = executionContext;
1704
- if (!agentId) {
1704
+ const { tenantId, projectId, graphId, subAgentId, baseUrl, apiKey } = executionContext;
1705
+ if (!subAgentId) {
1705
1706
  throw new Error("Agent ID is required");
1706
1707
  }
1707
- const dbAgent = await agentsCore.getAgentById(dbClient_default)({
1708
+ const dbAgent = await agentsCore.getSubAgentById(dbClient_default)({
1708
1709
  scopes: { tenantId, projectId, graphId },
1709
- agentId
1710
+ subAgentId
1710
1711
  });
1711
1712
  if (!dbAgent) {
1712
1713
  return null;
@@ -1727,7 +1728,7 @@ init_logger();
1727
1728
 
1728
1729
  // src/agents/ModelFactory.ts
1729
1730
  init_logger();
1730
- var logger5 = agentsCore.getLogger("ModelFactory");
1731
+ var logger4 = agentsCore.getLogger("ModelFactory");
1731
1732
  var _ModelFactory = class _ModelFactory {
1732
1733
  /**
1733
1734
  * Create a provider instance with custom configuration
@@ -1789,7 +1790,7 @@ var _ModelFactory = class _ModelFactory {
1789
1790
  }
1790
1791
  const modelString = modelSettings.model.trim();
1791
1792
  const { provider, modelName } = _ModelFactory.parseModelString(modelString);
1792
- logger5.debug(
1793
+ logger4.debug(
1793
1794
  {
1794
1795
  provider,
1795
1796
  model: modelName,
@@ -1800,7 +1801,7 @@ var _ModelFactory = class _ModelFactory {
1800
1801
  );
1801
1802
  const providerConfig = _ModelFactory.extractProviderConfig(modelSettings.providerOptions);
1802
1803
  if (Object.keys(providerConfig).length > 0) {
1803
- logger5.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
1804
+ logger4.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
1804
1805
  const customProvider = _ModelFactory.createProvider(provider, providerConfig);
1805
1806
  return customProvider.languageModel(modelName);
1806
1807
  }
@@ -1919,7 +1920,7 @@ var ModelFactory = _ModelFactory;
1919
1920
 
1920
1921
  // src/agents/ToolSessionManager.ts
1921
1922
  init_logger();
1922
- var logger6 = agentsCore.getLogger("ToolSessionManager");
1923
+ var logger5 = agentsCore.getLogger("ToolSessionManager");
1923
1924
  var _ToolSessionManager = class _ToolSessionManager {
1924
1925
  // 5 minutes
1925
1926
  constructor() {
@@ -1954,7 +1955,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1954
1955
  createdAt: Date.now()
1955
1956
  };
1956
1957
  this.sessions.set(sessionId, session);
1957
- logger6.debug(
1958
+ logger5.debug(
1958
1959
  {
1959
1960
  sessionId,
1960
1961
  tenantId,
@@ -1972,10 +1973,10 @@ var _ToolSessionManager = class _ToolSessionManager {
1972
1973
  */
1973
1974
  ensureGraphSession(sessionId, tenantId, projectId, contextId, taskId) {
1974
1975
  if (this.sessions.has(sessionId)) {
1975
- logger6.debug({ sessionId }, "Graph session already exists, reusing");
1976
+ logger5.debug({ sessionId }, "Graph session already exists, reusing");
1976
1977
  return sessionId;
1977
1978
  }
1978
- logger6.debug(
1979
+ logger5.debug(
1979
1980
  { sessionId, tenantId, contextId, taskId },
1980
1981
  "Creating new graph-scoped tool session"
1981
1982
  );
@@ -1987,7 +1988,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1987
1988
  recordToolResult(sessionId, toolResult) {
1988
1989
  const session = this.sessions.get(sessionId);
1989
1990
  if (!session) {
1990
- logger6.warn(
1991
+ logger5.warn(
1991
1992
  {
1992
1993
  sessionId,
1993
1994
  toolCallId: toolResult.toolCallId,
@@ -1999,7 +2000,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1999
2000
  return;
2000
2001
  }
2001
2002
  session.toolResults.set(toolResult.toolCallId, toolResult);
2002
- logger6.debug(
2003
+ logger5.debug(
2003
2004
  {
2004
2005
  sessionId,
2005
2006
  toolCallId: toolResult.toolCallId,
@@ -2014,7 +2015,7 @@ var _ToolSessionManager = class _ToolSessionManager {
2014
2015
  getToolResult(sessionId, toolCallId) {
2015
2016
  const session = this.sessions.get(sessionId);
2016
2017
  if (!session) {
2017
- logger6.warn(
2018
+ logger5.warn(
2018
2019
  {
2019
2020
  sessionId,
2020
2021
  toolCallId,
@@ -2027,7 +2028,7 @@ var _ToolSessionManager = class _ToolSessionManager {
2027
2028
  }
2028
2029
  const result = session.toolResults.get(toolCallId);
2029
2030
  if (!result) {
2030
- logger6.warn(
2031
+ logger5.warn(
2031
2032
  {
2032
2033
  sessionId,
2033
2034
  toolCallId,
@@ -2037,7 +2038,7 @@ var _ToolSessionManager = class _ToolSessionManager {
2037
2038
  "Tool result not found"
2038
2039
  );
2039
2040
  } else {
2040
- logger6.debug(
2041
+ logger5.debug(
2041
2042
  {
2042
2043
  sessionId,
2043
2044
  toolCallId,
@@ -2076,10 +2077,10 @@ var _ToolSessionManager = class _ToolSessionManager {
2076
2077
  }
2077
2078
  for (const sessionId of expiredSessions) {
2078
2079
  this.sessions.delete(sessionId);
2079
- logger6.debug({ sessionId }, "Cleaned up expired tool session");
2080
+ logger5.debug({ sessionId }, "Cleaned up expired tool session");
2080
2081
  }
2081
2082
  if (expiredSessions.length > 0) {
2082
- logger6.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
2083
+ logger5.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
2083
2084
  }
2084
2085
  }
2085
2086
  };
@@ -2162,7 +2163,7 @@ function extractFullFields(schema) {
2162
2163
  }
2163
2164
 
2164
2165
  // src/services/ArtifactService.ts
2165
- var logger8 = agentsCore.getLogger("ArtifactService");
2166
+ var logger7 = agentsCore.getLogger("ArtifactService");
2166
2167
  var _ArtifactService = class _ArtifactService {
2167
2168
  constructor(context) {
2168
2169
  this.context = context;
@@ -2194,7 +2195,7 @@ var _ArtifactService = class _ArtifactService {
2194
2195
  id: taskId
2195
2196
  });
2196
2197
  if (!task) {
2197
- logger8.warn({ taskId }, "Task not found when fetching artifacts");
2198
+ logger7.warn({ taskId }, "Task not found when fetching artifacts");
2198
2199
  continue;
2199
2200
  }
2200
2201
  const taskArtifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
@@ -2212,21 +2213,21 @@ var _ArtifactService = class _ArtifactService {
2212
2213
  }
2213
2214
  }
2214
2215
  } catch (error) {
2215
- logger8.error({ error, contextId }, "Error loading context artifacts");
2216
+ logger7.error({ error, contextId }, "Error loading context artifacts");
2216
2217
  }
2217
2218
  return artifacts;
2218
2219
  }
2219
2220
  /**
2220
2221
  * Create artifact from tool result and request data
2221
2222
  */
2222
- async createArtifact(request, agentId) {
2223
+ async createArtifact(request, subAgentId) {
2223
2224
  if (!this.context.sessionId) {
2224
- logger8.warn({ request }, "No session ID available for artifact creation");
2225
+ logger7.warn({ request }, "No session ID available for artifact creation");
2225
2226
  return null;
2226
2227
  }
2227
2228
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
2228
2229
  if (!toolResult) {
2229
- logger8.warn(
2230
+ logger7.warn(
2230
2231
  { request, sessionId: this.context.sessionId },
2231
2232
  "Tool result not found for artifact"
2232
2233
  );
@@ -2242,7 +2243,7 @@ var _ArtifactService = class _ArtifactService {
2242
2243
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
2243
2244
  }
2244
2245
  if (!selectedData) {
2245
- logger8.warn(
2246
+ logger7.warn(
2246
2247
  {
2247
2248
  request,
2248
2249
  baseSelector: request.baseSelector
@@ -2287,7 +2288,7 @@ var _ArtifactService = class _ArtifactService {
2287
2288
  type: request.type,
2288
2289
  data: cleanedSummaryData
2289
2290
  };
2290
- await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, agentId);
2291
+ await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, subAgentId);
2291
2292
  await this.cacheArtifact(
2292
2293
  request.artifactId,
2293
2294
  request.toolCallId,
@@ -2296,7 +2297,7 @@ var _ArtifactService = class _ArtifactService {
2296
2297
  );
2297
2298
  return artifactData;
2298
2299
  } catch (error) {
2299
- logger8.error({ error, request }, "Failed to create artifact");
2300
+ logger7.error({ error, request }, "Failed to create artifact");
2300
2301
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
2301
2302
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
2302
2303
  }
@@ -2325,7 +2326,7 @@ var _ArtifactService = class _ArtifactService {
2325
2326
  }
2326
2327
  try {
2327
2328
  if (!this.context.projectId || !this.context.taskId) {
2328
- logger8.warn(
2329
+ logger7.warn(
2329
2330
  { artifactId, toolCallId },
2330
2331
  "No projectId or taskId available for artifact lookup"
2331
2332
  );
@@ -2340,7 +2341,7 @@ var _ArtifactService = class _ArtifactService {
2340
2341
  return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
2341
2342
  }
2342
2343
  } catch (error) {
2343
- logger8.warn(
2344
+ logger7.warn(
2344
2345
  { artifactId, toolCallId, taskId: this.context.taskId, error },
2345
2346
  "Failed to fetch artifact"
2346
2347
  );
@@ -2371,7 +2372,7 @@ var _ArtifactService = class _ArtifactService {
2371
2372
  }
2372
2373
  try {
2373
2374
  if (!this.context.projectId || !this.context.taskId) {
2374
- logger8.warn(
2375
+ logger7.warn(
2375
2376
  { artifactId, toolCallId },
2376
2377
  "No projectId or taskId available for artifact lookup"
2377
2378
  );
@@ -2386,7 +2387,7 @@ var _ArtifactService = class _ArtifactService {
2386
2387
  return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
2387
2388
  }
2388
2389
  } catch (error) {
2389
- logger8.warn(
2390
+ logger7.warn(
2390
2391
  { artifactId, toolCallId, taskId: this.context.taskId, error },
2391
2392
  "Failed to fetch artifact"
2392
2393
  );
@@ -2422,8 +2423,8 @@ var _ArtifactService = class _ArtifactService {
2422
2423
  /**
2423
2424
  * Persist artifact to database via graph session
2424
2425
  */
2425
- async persistArtifact(request, summaryData, fullData, agentId) {
2426
- const effectiveAgentId = agentId || this.context.agentId;
2426
+ async persistArtifact(request, summaryData, fullData, subAgentId) {
2427
+ const effectiveAgentId = subAgentId || this.context.subAgentId;
2427
2428
  if (this.context.streamRequestId && effectiveAgentId && this.context.taskId) {
2428
2429
  await graphSessionManager.recordEvent(
2429
2430
  this.context.streamRequestId,
@@ -2436,7 +2437,7 @@ var _ArtifactService = class _ArtifactService {
2436
2437
  artifactType: request.type,
2437
2438
  summaryData,
2438
2439
  data: fullData,
2439
- agentId: effectiveAgentId,
2440
+ subAgentId: effectiveAgentId,
2440
2441
  metadata: {
2441
2442
  toolCallId: request.toolCallId,
2442
2443
  baseSelector: request.baseSelector,
@@ -2451,14 +2452,14 @@ var _ArtifactService = class _ArtifactService {
2451
2452
  }
2452
2453
  );
2453
2454
  } else {
2454
- logger8.warn(
2455
+ logger7.warn(
2455
2456
  {
2456
2457
  artifactId: request.artifactId,
2457
2458
  hasStreamRequestId: !!this.context.streamRequestId,
2458
2459
  hasAgentId: !!effectiveAgentId,
2459
2460
  hasTaskId: !!this.context.taskId,
2460
- passedAgentId: agentId,
2461
- contextAgentId: this.context.agentId
2461
+ passedAgentId: subAgentId,
2462
+ contextAgentId: this.context.subAgentId
2462
2463
  },
2463
2464
  "Skipping artifact_saved event - missing required context"
2464
2465
  );
@@ -2526,7 +2527,7 @@ var _ArtifactService = class _ArtifactService {
2526
2527
  summaryData = this.filterBySchema(artifact.data, previewSchema);
2527
2528
  fullData = this.filterBySchema(artifact.data, fullSchema);
2528
2529
  } catch (error) {
2529
- logger8.warn(
2530
+ logger7.warn(
2530
2531
  {
2531
2532
  artifactType: artifact.type,
2532
2533
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2564,7 +2565,7 @@ var _ArtifactService = class _ArtifactService {
2564
2565
  artifact: artifactToSave
2565
2566
  });
2566
2567
  if (!result.created && result.existing) {
2567
- logger8.debug(
2568
+ logger7.debug(
2568
2569
  {
2569
2570
  artifactId: artifact.artifactId,
2570
2571
  taskId: this.context.taskId
@@ -2617,7 +2618,7 @@ var _ArtifactService = class _ArtifactService {
2617
2618
  extracted[propName] = this.cleanEscapedContent(rawValue);
2618
2619
  }
2619
2620
  } catch (error) {
2620
- logger8.warn(
2621
+ logger7.warn(
2621
2622
  { propName, selector, error: error instanceof Error ? error.message : "Unknown error" },
2622
2623
  "Failed to extract property"
2623
2624
  );
@@ -2649,7 +2650,7 @@ var _ArtifactService = class _ArtifactService {
2649
2650
  extracted[fieldName] = this.cleanEscapedContent(rawValue);
2650
2651
  }
2651
2652
  } catch (error) {
2652
- logger8.warn(
2653
+ logger7.warn(
2653
2654
  { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
2654
2655
  "Failed to extract schema field"
2655
2656
  );
@@ -2680,7 +2681,7 @@ __publicField(_ArtifactService, "selectorCache", /* @__PURE__ */ new Map());
2680
2681
  var ArtifactService = _ArtifactService;
2681
2682
 
2682
2683
  // src/services/ArtifactParser.ts
2683
- var logger9 = agentsCore.getLogger("ArtifactParser");
2684
+ var logger8 = agentsCore.getLogger("ArtifactParser");
2684
2685
  var _ArtifactParser = class _ArtifactParser {
2685
2686
  constructor(tenantId, options) {
2686
2687
  __publicField(this, "artifactService");
@@ -2768,7 +2769,7 @@ var _ArtifactParser = class _ArtifactParser {
2768
2769
  attrs[key] = value;
2769
2770
  }
2770
2771
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
2771
- logger9.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2772
+ logger8.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2772
2773
  return null;
2773
2774
  }
2774
2775
  return {
@@ -2799,7 +2800,7 @@ var _ArtifactParser = class _ArtifactParser {
2799
2800
  /**
2800
2801
  * Extract artifact data from a create annotation - delegates to service
2801
2802
  */
2802
- async extractFromCreateAnnotation(annotation, agentId) {
2803
+ async extractFromCreateAnnotation(annotation, subAgentId) {
2803
2804
  const request = {
2804
2805
  artifactId: annotation.artifactId,
2805
2806
  toolCallId: annotation.toolCallId,
@@ -2807,21 +2808,21 @@ var _ArtifactParser = class _ArtifactParser {
2807
2808
  baseSelector: annotation.baseSelector,
2808
2809
  detailsSelector: annotation.detailsSelector
2809
2810
  };
2810
- return this.artifactService.createArtifact(request, agentId);
2811
+ return this.artifactService.createArtifact(request, subAgentId);
2811
2812
  }
2812
2813
  /**
2813
2814
  * Parse text with artifact markers into parts array
2814
2815
  * Handles both artifact:ref and artifact:create tags
2815
2816
  * Can work with or without pre-fetched artifact map
2816
2817
  */
2817
- async parseText(text, artifactMap, agentId) {
2818
+ async parseText(text, artifactMap, subAgentId) {
2818
2819
  let processedText = text;
2819
2820
  const createAnnotations = this.parseCreateAnnotations(text);
2820
2821
  const createdArtifactData = /* @__PURE__ */ new Map();
2821
2822
  const failedAnnotations = [];
2822
2823
  for (const annotation of createAnnotations) {
2823
2824
  try {
2824
- const artifactData = await this.extractFromCreateAnnotation(annotation, agentId);
2825
+ const artifactData = await this.extractFromCreateAnnotation(annotation, subAgentId);
2825
2826
  if (artifactData && annotation.raw) {
2826
2827
  createdArtifactData.set(annotation.raw, artifactData);
2827
2828
  } else if (annotation.raw) {
@@ -2829,7 +2830,7 @@ var _ArtifactParser = class _ArtifactParser {
2829
2830
  `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
2830
2831
  );
2831
2832
  processedText = processedText.replace(annotation.raw, "");
2832
- logger9.warn(
2833
+ logger8.warn(
2833
2834
  { annotation, artifactData },
2834
2835
  "Removed failed artifact:create annotation from output"
2835
2836
  );
@@ -2840,11 +2841,11 @@ var _ArtifactParser = class _ArtifactParser {
2840
2841
  if (annotation.raw) {
2841
2842
  processedText = processedText.replace(annotation.raw, "");
2842
2843
  }
2843
- logger9.error({ annotation, error }, "Failed to extract artifact from create annotation");
2844
+ logger8.error({ annotation, error }, "Failed to extract artifact from create annotation");
2844
2845
  }
2845
2846
  }
2846
2847
  if (failedAnnotations.length > 0) {
2847
- logger9.warn(
2848
+ logger8.warn(
2848
2849
  {
2849
2850
  failedCount: failedAnnotations.length,
2850
2851
  failures: failedAnnotations
@@ -2908,7 +2909,7 @@ var _ArtifactParser = class _ArtifactParser {
2908
2909
  /**
2909
2910
  * Process object/dataComponents for artifact components
2910
2911
  */
2911
- async parseObject(obj, artifactMap, agentId) {
2912
+ async parseObject(obj, artifactMap, subAgentId) {
2912
2913
  if (obj?.dataComponents && Array.isArray(obj.dataComponents)) {
2913
2914
  const parts = [];
2914
2915
  for (const component of obj.dataComponents) {
@@ -2932,7 +2933,7 @@ var _ArtifactParser = class _ArtifactParser {
2932
2933
  });
2933
2934
  }
2934
2935
  } else if (this.isArtifactCreateComponent(component)) {
2935
- const createData = await this.extractFromArtifactCreateComponent(component, agentId);
2936
+ const createData = await this.extractFromArtifactCreateComponent(component, subAgentId);
2936
2937
  if (createData) {
2937
2938
  parts.push({
2938
2939
  kind: "data",
@@ -2973,7 +2974,7 @@ var _ArtifactParser = class _ArtifactParser {
2973
2974
  ] : [];
2974
2975
  }
2975
2976
  if (this.isArtifactCreateComponent(obj)) {
2976
- const createData = await this.extractFromArtifactCreateComponent(obj, agentId);
2977
+ const createData = await this.extractFromArtifactCreateComponent(obj, subAgentId);
2977
2978
  return createData ? [
2978
2979
  {
2979
2980
  kind: "data",
@@ -3005,7 +3006,7 @@ var _ArtifactParser = class _ArtifactParser {
3005
3006
  /**
3006
3007
  * Extract artifact from ArtifactCreate component
3007
3008
  */
3008
- async extractFromArtifactCreateComponent(component, agentId) {
3009
+ async extractFromArtifactCreateComponent(component, subAgentId) {
3009
3010
  const props = component.props;
3010
3011
  if (!props) {
3011
3012
  return null;
@@ -3017,7 +3018,7 @@ var _ArtifactParser = class _ArtifactParser {
3017
3018
  baseSelector: props.base_selector,
3018
3019
  detailsSelector: props.details_selector || {}
3019
3020
  };
3020
- return await this.extractFromCreateAnnotation(annotation, agentId);
3021
+ return await this.extractFromCreateAnnotation(annotation, subAgentId);
3021
3022
  }
3022
3023
  /**
3023
3024
  * Get artifact data - delegates to service
@@ -3057,7 +3058,7 @@ __publicField(_ArtifactParser, "INCOMPLETE_CREATE_REGEX", /<artifact:create(?![^
3057
3058
  var ArtifactParser = _ArtifactParser;
3058
3059
 
3059
3060
  // src/services/GraphSession.ts
3060
- var logger10 = agentsCore.getLogger("GraphSession");
3061
+ var logger9 = agentsCore.getLogger("GraphSession");
3061
3062
  var GraphSession = class {
3062
3063
  // Whether to send data operations
3063
3064
  constructor(sessionId, messageId, graphId, tenantId, projectId, contextId) {
@@ -3090,7 +3091,7 @@ var GraphSession = class {
3090
3091
  __publicField(this, "artifactParser");
3091
3092
  // Session-scoped ArtifactParser instance
3092
3093
  __publicField(this, "isEmitOperations", false);
3093
- logger10.debug({ sessionId, messageId, graphId }, "GraphSession created");
3094
+ logger9.debug({ sessionId, messageId, graphId }, "GraphSession created");
3094
3095
  if (tenantId && projectId) {
3095
3096
  toolSessionManager.createSessionWithId(
3096
3097
  sessionId,
@@ -3104,7 +3105,6 @@ var GraphSession = class {
3104
3105
  tenantId,
3105
3106
  projectId,
3106
3107
  sessionId,
3107
- // Same ID as ToolSession
3108
3108
  contextId,
3109
3109
  taskId: `task_${contextId}-${messageId}`,
3110
3110
  streamRequestId: sessionId
@@ -3125,7 +3125,7 @@ var GraphSession = class {
3125
3125
  */
3126
3126
  enableEmitOperations() {
3127
3127
  this.isEmitOperations = true;
3128
- logger10.info(
3128
+ logger9.info(
3129
3129
  { sessionId: this.sessionId },
3130
3130
  "\u{1F50D} DEBUG: Emit operations enabled for GraphSession"
3131
3131
  );
@@ -3142,14 +3142,14 @@ var GraphSession = class {
3142
3142
  label: this.generateEventLabel(event),
3143
3143
  details: {
3144
3144
  timestamp: event.timestamp,
3145
- agentId: event.agentId,
3145
+ subAgentId: event.subAgentId,
3146
3146
  data: event.data
3147
3147
  }
3148
3148
  };
3149
3149
  await streamHelper.writeOperation(formattedOperation);
3150
3150
  }
3151
3151
  } catch (error) {
3152
- logger10.error(
3152
+ logger9.error(
3153
3153
  {
3154
3154
  sessionId: this.sessionId,
3155
3155
  eventType: event.eventType,
@@ -3165,29 +3165,19 @@ var GraphSession = class {
3165
3165
  generateEventLabel(event) {
3166
3166
  switch (event.eventType) {
3167
3167
  case "agent_generate":
3168
- return `Agent ${event.agentId} generating response`;
3168
+ return `Agent ${event.subAgentId} generating response`;
3169
3169
  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
- }
3170
+ return `Agent ${event.subAgentId} reasoning through request`;
3171
+ case "tool_execution":
3172
+ return `Tool execution: ${event.data.toolName || "unknown"}`;
3173
+ case "transfer":
3174
+ return `Agent transfer: ${event.data.fromSubAgent} \u2192 ${event.data.targetSubAgent}`;
3175
+ case "delegation_sent":
3176
+ return `Task delegated: ${event.data.fromSubAgent} \u2192 ${event.data.targetSubAgent}`;
3177
+ case "delegation_returned":
3178
+ return `Task completed: ${event.data.targetSubAgent} \u2192 ${event.data.fromSubAgent}`;
3179
+ case "artifact_saved":
3180
+ return `Artifact saved: ${event.data.artifactType || "unknown type"}`;
3191
3181
  default:
3192
3182
  return `${event.eventType} event`;
3193
3183
  }
@@ -3212,7 +3202,7 @@ var GraphSession = class {
3212
3202
  if (this.statusUpdateState.config.timeInSeconds) {
3213
3203
  this.statusUpdateTimer = setInterval(async () => {
3214
3204
  if (!this.statusUpdateState || this.isEnded) {
3215
- logger10.debug(
3205
+ logger9.debug(
3216
3206
  { sessionId: this.sessionId },
3217
3207
  "Timer triggered but session already cleaned up or ended"
3218
3208
  );
@@ -3224,7 +3214,7 @@ var GraphSession = class {
3224
3214
  }
3225
3215
  await this.checkAndSendTimeBasedUpdate();
3226
3216
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
3227
- logger10.info(
3217
+ logger9.info(
3228
3218
  {
3229
3219
  sessionId: this.sessionId,
3230
3220
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -3235,22 +3225,24 @@ var GraphSession = class {
3235
3225
  }
3236
3226
  /**
3237
3227
  * Record an event in the session and trigger status updates if configured
3228
+ * Generic type parameter T ensures eventType and data are correctly paired
3238
3229
  */
3239
- recordEvent(eventType, agentId, data) {
3230
+ recordEvent(eventType, subAgentId, data) {
3240
3231
  if (this.isEmitOperations) {
3241
- this.sendDataOperation({
3232
+ const dataOpEvent = {
3242
3233
  timestamp: Date.now(),
3243
3234
  eventType,
3244
- agentId,
3235
+ subAgentId,
3245
3236
  data
3246
- });
3237
+ };
3238
+ this.sendDataOperation(dataOpEvent);
3247
3239
  }
3248
3240
  if (this.isEnded) {
3249
- logger10.debug(
3241
+ logger9.debug(
3250
3242
  {
3251
3243
  sessionId: this.sessionId,
3252
3244
  eventType,
3253
- agentId
3245
+ subAgentId
3254
3246
  },
3255
3247
  "Event received after session ended - ignoring"
3256
3248
  );
@@ -3259,59 +3251,62 @@ var GraphSession = class {
3259
3251
  const event = {
3260
3252
  timestamp: Date.now(),
3261
3253
  eventType,
3262
- agentId,
3254
+ subAgentId,
3263
3255
  data
3264
3256
  };
3265
3257
  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) {
3258
+ if (eventType === "artifact_saved") {
3259
+ const artifactData = data;
3260
+ if (artifactData.pendingGeneration) {
3261
+ const artifactId = artifactData.artifactId;
3262
+ if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
3263
+ logger9.warn(
3264
+ {
3265
+ sessionId: this.sessionId,
3266
+ artifactId,
3267
+ pendingCount: this.pendingArtifacts.size,
3268
+ maxAllowed: this.MAX_PENDING_ARTIFACTS
3269
+ },
3270
+ "Too many pending artifacts, skipping processing"
3271
+ );
3272
+ return;
3273
+ }
3274
+ this.pendingArtifacts.add(artifactId);
3275
+ setImmediate(() => {
3276
+ const artifactDataWithAgent = { ...artifactData, subAgentId };
3277
+ this.processArtifact(artifactDataWithAgent).then(() => {
3290
3278
  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
- }
3279
+ this.artifactProcessingErrors.delete(artifactId);
3280
+ }).catch((error) => {
3281
+ const errorCount = (this.artifactProcessingErrors.get(artifactId) || 0) + 1;
3282
+ this.artifactProcessingErrors.set(artifactId, errorCount);
3283
+ if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
3284
+ this.pendingArtifacts.delete(artifactId);
3285
+ logger9.error(
3286
+ {
3287
+ sessionId: this.sessionId,
3288
+ artifactId,
3289
+ errorCount,
3290
+ maxRetries: this.MAX_ARTIFACT_RETRIES,
3291
+ error: error instanceof Error ? error.message : "Unknown error",
3292
+ stack: error instanceof Error ? error.stack : void 0
3293
+ },
3294
+ "Artifact processing failed after max retries, giving up"
3295
+ );
3296
+ } else {
3297
+ logger9.warn(
3298
+ {
3299
+ sessionId: this.sessionId,
3300
+ artifactId,
3301
+ errorCount,
3302
+ error: error instanceof Error ? error.message : "Unknown error"
3303
+ },
3304
+ "Artifact processing failed, may retry"
3305
+ );
3306
+ }
3307
+ });
3313
3308
  });
3314
- });
3309
+ }
3315
3310
  }
3316
3311
  if (!this.isEnded) {
3317
3312
  this.checkStatusUpdates();
@@ -3322,14 +3317,14 @@ var GraphSession = class {
3322
3317
  */
3323
3318
  checkStatusUpdates() {
3324
3319
  if (this.isEnded) {
3325
- logger10.debug(
3320
+ logger9.debug(
3326
3321
  { sessionId: this.sessionId },
3327
3322
  "Session has ended - skipping status update check"
3328
3323
  );
3329
3324
  return;
3330
3325
  }
3331
3326
  if (!this.statusUpdateState) {
3332
- logger10.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
3327
+ logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
3333
3328
  return;
3334
3329
  }
3335
3330
  const statusUpdateState = this.statusUpdateState;
@@ -3340,11 +3335,11 @@ var GraphSession = class {
3340
3335
  */
3341
3336
  async checkAndSendTimeBasedUpdate() {
3342
3337
  if (this.isEnded) {
3343
- logger10.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
3338
+ logger9.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
3344
3339
  return;
3345
3340
  }
3346
3341
  if (!this.statusUpdateState) {
3347
- logger10.debug(
3342
+ logger9.debug(
3348
3343
  { sessionId: this.sessionId },
3349
3344
  "No status updates configured for time-based check"
3350
3345
  );
@@ -3357,7 +3352,7 @@ var GraphSession = class {
3357
3352
  try {
3358
3353
  await this.generateAndSendUpdate();
3359
3354
  } catch (error) {
3360
- logger10.error(
3355
+ logger9.error(
3361
3356
  {
3362
3357
  sessionId: this.sessionId,
3363
3358
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3381,8 +3376,8 @@ var GraphSession = class {
3381
3376
  /**
3382
3377
  * Get events filtered by agent
3383
3378
  */
3384
- getEventsByAgent(agentId) {
3385
- return this.events.filter((event) => event.agentId === agentId);
3379
+ getEventsByAgent(subAgentId) {
3380
+ return this.events.filter((event) => event.subAgentId === subAgentId);
3386
3381
  }
3387
3382
  /**
3388
3383
  * Get summary of session activity
@@ -3397,7 +3392,7 @@ var GraphSession = class {
3397
3392
  );
3398
3393
  const agentCounts = this.events.reduce(
3399
3394
  (counts, event) => {
3400
- counts[event.agentId] = (counts[event.agentId] || 0) + 1;
3395
+ counts[event.subAgentId] = (counts[event.subAgentId] || 0) + 1;
3401
3396
  return counts;
3402
3397
  },
3403
3398
  {}
@@ -3460,29 +3455,29 @@ var GraphSession = class {
3460
3455
  */
3461
3456
  async generateAndSendUpdate() {
3462
3457
  if (this.isEnded) {
3463
- logger10.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
3458
+ logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
3464
3459
  return;
3465
3460
  }
3466
3461
  if (this.isTextStreaming) {
3467
- logger10.debug(
3462
+ logger9.debug(
3468
3463
  { sessionId: this.sessionId },
3469
3464
  "Text is currently streaming - skipping status update"
3470
3465
  );
3471
3466
  return;
3472
3467
  }
3473
3468
  if (this.isGeneratingUpdate) {
3474
- logger10.debug(
3469
+ logger9.debug(
3475
3470
  { sessionId: this.sessionId },
3476
3471
  "Update already in progress - skipping duplicate generation"
3477
3472
  );
3478
3473
  return;
3479
3474
  }
3480
3475
  if (!this.statusUpdateState) {
3481
- logger10.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
3476
+ logger9.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
3482
3477
  return;
3483
3478
  }
3484
3479
  if (!this.graphId) {
3485
- logger10.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
3480
+ logger9.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
3486
3481
  return;
3487
3482
  }
3488
3483
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -3494,7 +3489,7 @@ var GraphSession = class {
3494
3489
  try {
3495
3490
  const streamHelper = getStreamHelper(this.sessionId);
3496
3491
  if (!streamHelper) {
3497
- logger10.warn(
3492
+ logger9.warn(
3498
3493
  { sessionId: this.sessionId },
3499
3494
  "No stream helper found - cannot send status update"
3500
3495
  );
@@ -3514,7 +3509,7 @@ var GraphSession = class {
3514
3509
  if (result.summaries && result.summaries.length > 0) {
3515
3510
  for (const summary of result.summaries) {
3516
3511
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
3517
- logger10.warn(
3512
+ logger9.warn(
3518
3513
  {
3519
3514
  sessionId: this.sessionId,
3520
3515
  summary
@@ -3551,7 +3546,7 @@ var GraphSession = class {
3551
3546
  this.statusUpdateState.lastEventCount = this.events.length;
3552
3547
  }
3553
3548
  } catch (error) {
3554
- logger10.error(
3549
+ logger9.error(
3555
3550
  {
3556
3551
  sessionId: this.sessionId,
3557
3552
  error: error instanceof Error ? error.message : "Unknown error",
@@ -3589,7 +3584,7 @@ var GraphSession = class {
3589
3584
  this.releaseUpdateLock();
3590
3585
  }
3591
3586
  } catch (error) {
3592
- logger10.error(
3587
+ logger9.error(
3593
3588
  {
3594
3589
  sessionId: this.sessionId,
3595
3590
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3667,7 +3662,7 @@ User's Question/Context:
3667
3662
  ${conversationHistory}
3668
3663
  ` : "";
3669
3664
  } catch (error) {
3670
- logger10.warn(
3665
+ logger9.warn(
3671
3666
  { sessionId: this.sessionId, error },
3672
3667
  "Failed to fetch conversation history for structured status update"
3673
3668
  );
@@ -3801,7 +3796,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3801
3796
  return { summaries };
3802
3797
  } catch (error) {
3803
3798
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3804
- logger10.error({ error }, "Failed to generate structured update, using fallback");
3799
+ logger9.error({ error }, "Failed to generate structured update, using fallback");
3805
3800
  return { summaries: [] };
3806
3801
  } finally {
3807
3802
  span.end();
@@ -3827,7 +3822,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3827
3822
  */
3828
3823
  buildZodSchemaFromJson(jsonSchema) {
3829
3824
  const properties = {};
3830
- properties["label"] = z6.z.string().describe(
3825
+ properties.label = z6.z.string().describe(
3831
3826
  '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
3827
  );
3833
3828
  for (const [key, value] of Object.entries(jsonSchema.properties)) {
@@ -3896,11 +3891,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3896
3891
  for (const event of events) {
3897
3892
  switch (event.eventType) {
3898
3893
  case "tool_execution": {
3899
- const data = event.data;
3900
- const resultStr = JSON.stringify(data.result);
3894
+ const resultStr = JSON.stringify(event.data.result);
3901
3895
  activities.push(
3902
- `\u{1F527} **${data.toolName}** ${data.duration ? `(${data.duration}ms)` : ""}
3903
- \u{1F4E5} Input: ${JSON.stringify(data.args)}
3896
+ `\u{1F527} **${event.data.toolName}** ${event.data.duration ? `(${event.data.duration}ms)` : ""}
3897
+ \u{1F4E5} Input: ${JSON.stringify(event.data.args)}
3904
3898
  \u{1F4E4} Output: ${resultStr}`
3905
3899
  );
3906
3900
  break;
@@ -3912,23 +3906,24 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3912
3906
  case "artifact_saved":
3913
3907
  break;
3914
3908
  case "agent_reasoning": {
3915
- const data = event.data;
3916
3909
  activities.push(
3917
3910
  `\u2699\uFE0F **Analyzing request**
3918
- Details: ${JSON.stringify(data.parts, null, 2)}`
3911
+ Details: ${JSON.stringify(event.data.parts, null, 2)}`
3919
3912
  );
3920
3913
  break;
3921
3914
  }
3922
3915
  case "agent_generate": {
3923
- const data = event.data;
3924
3916
  activities.push(
3925
3917
  `\u2699\uFE0F **Preparing response**
3926
- Details: ${JSON.stringify(data.parts, null, 2)}`
3918
+ Details: ${JSON.stringify(event.data.parts, null, 2)}`
3927
3919
  );
3928
3920
  break;
3929
3921
  }
3930
3922
  default: {
3931
- activities.push(`\u{1F4CB} **${event.eventType}**: ${JSON.stringify(event.data, null, 2)}`);
3923
+ const safeEvent = event;
3924
+ activities.push(
3925
+ `\u{1F4CB} **${safeEvent.eventType}**: ${JSON.stringify(safeEvent.data, null, 2)}`
3926
+ );
3932
3927
  break;
3933
3928
  }
3934
3929
  }
@@ -3946,7 +3941,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3946
3941
  "graph_session.id": this.sessionId,
3947
3942
  "artifact.id": artifactData.artifactId,
3948
3943
  "artifact.type": artifactData.artifactType || "unknown",
3949
- "artifact.agent_id": artifactData.agentId || "unknown",
3944
+ "artifact.agent_id": artifactData.subAgentId || "unknown",
3950
3945
  "artifact.tool_call_id": artifactData.metadata?.toolCallId || "unknown",
3951
3946
  "artifact.data": JSON.stringify(artifactData.data, null, 2),
3952
3947
  "tenant.id": artifactData.tenantId || "unknown",
@@ -4005,34 +4000,34 @@ Make it specific and relevant.`;
4005
4000
  let modelToUse = this.statusUpdateState?.summarizerModel;
4006
4001
  if (!modelToUse?.model?.trim()) {
4007
4002
  if (!this.statusUpdateState?.baseModel?.model?.trim()) {
4008
- if (artifactData.agentId && artifactData.tenantId && artifactData.projectId) {
4003
+ if (artifactData.subAgentId && artifactData.tenantId && artifactData.projectId) {
4009
4004
  try {
4010
- const agentData = await agentsCore.getAgentById(dbClient_default)({
4005
+ const agentData = await agentsCore.getSubAgentById(dbClient_default)({
4011
4006
  scopes: {
4012
4007
  tenantId: artifactData.tenantId,
4013
4008
  projectId: artifactData.projectId,
4014
4009
  graphId: this.graphId || ""
4015
4010
  },
4016
- agentId: artifactData.agentId
4011
+ subAgentId: artifactData.subAgentId
4017
4012
  });
4018
4013
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
4019
4014
  modelToUse = agentData.models.base;
4020
- logger10.info(
4015
+ logger9.info(
4021
4016
  {
4022
4017
  sessionId: this.sessionId,
4023
4018
  artifactId: artifactData.artifactId,
4024
- agentId: artifactData.agentId,
4019
+ subAgentId: artifactData.subAgentId,
4025
4020
  model: modelToUse.model
4026
4021
  },
4027
4022
  "Using agent model configuration for artifact name generation"
4028
4023
  );
4029
4024
  }
4030
4025
  } catch (error) {
4031
- logger10.warn(
4026
+ logger9.warn(
4032
4027
  {
4033
4028
  sessionId: this.sessionId,
4034
4029
  artifactId: artifactData.artifactId,
4035
- agentId: artifactData.agentId,
4030
+ subAgentId: artifactData.subAgentId,
4036
4031
  error: error instanceof Error ? error.message : "Unknown error"
4037
4032
  },
4038
4033
  "Failed to get agent model configuration"
@@ -4040,7 +4035,7 @@ Make it specific and relevant.`;
4040
4035
  }
4041
4036
  }
4042
4037
  if (!modelToUse?.model?.trim()) {
4043
- logger10.warn(
4038
+ logger9.warn(
4044
4039
  {
4045
4040
  sessionId: this.sessionId,
4046
4041
  artifactId: artifactData.artifactId
@@ -4122,7 +4117,7 @@ Make it specific and relevant.`;
4122
4117
  return result2;
4123
4118
  } catch (error) {
4124
4119
  lastError = error instanceof Error ? error : new Error(String(error));
4125
- logger10.warn(
4120
+ logger9.warn(
4126
4121
  {
4127
4122
  sessionId: this.sessionId,
4128
4123
  artifactId: artifactData.artifactId,
@@ -4174,7 +4169,7 @@ Make it specific and relevant.`;
4174
4169
  });
4175
4170
  span.setStatus({ code: api.SpanStatusCode.OK });
4176
4171
  } catch (saveError) {
4177
- logger10.error(
4172
+ logger9.error(
4178
4173
  {
4179
4174
  sessionId: this.sessionId,
4180
4175
  artifactId: artifactData.artifactId,
@@ -4202,7 +4197,7 @@ Make it specific and relevant.`;
4202
4197
  metadata: artifactData.metadata || {},
4203
4198
  toolCallId: artifactData.toolCallId
4204
4199
  });
4205
- logger10.info(
4200
+ logger9.info(
4206
4201
  {
4207
4202
  sessionId: this.sessionId,
4208
4203
  artifactId: artifactData.artifactId
@@ -4213,7 +4208,7 @@ Make it specific and relevant.`;
4213
4208
  } catch (fallbackError) {
4214
4209
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
4215
4210
  if (isDuplicateError) ; else {
4216
- logger10.error(
4211
+ logger9.error(
4217
4212
  {
4218
4213
  sessionId: this.sessionId,
4219
4214
  artifactId: artifactData.artifactId,
@@ -4226,7 +4221,7 @@ Make it specific and relevant.`;
4226
4221
  }
4227
4222
  } catch (error) {
4228
4223
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4229
- logger10.error(
4224
+ logger9.error(
4230
4225
  {
4231
4226
  sessionId: this.sessionId,
4232
4227
  artifactId: artifactData.artifactId,
@@ -4245,7 +4240,7 @@ Make it specific and relevant.`;
4245
4240
  */
4246
4241
  setArtifactCache(key, artifact) {
4247
4242
  this.artifactCache.set(key, artifact);
4248
- logger10.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
4243
+ logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
4249
4244
  }
4250
4245
  /**
4251
4246
  * Get session-scoped ArtifactService instance
@@ -4264,7 +4259,7 @@ Make it specific and relevant.`;
4264
4259
  */
4265
4260
  getArtifactCache(key) {
4266
4261
  const artifact = this.artifactCache.get(key);
4267
- logger10.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
4262
+ logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
4268
4263
  return artifact || null;
4269
4264
  }
4270
4265
  /**
@@ -4287,7 +4282,7 @@ var GraphSessionManager = class {
4287
4282
  const sessionId = messageId;
4288
4283
  const session = new GraphSession(sessionId, messageId, graphId, tenantId, projectId, contextId);
4289
4284
  this.sessions.set(sessionId, session);
4290
- logger10.info(
4285
+ logger9.info(
4291
4286
  { sessionId, messageId, graphId, tenantId, projectId, contextId },
4292
4287
  "GraphSession created"
4293
4288
  );
@@ -4301,7 +4296,7 @@ var GraphSessionManager = class {
4301
4296
  if (session) {
4302
4297
  session.initializeStatusUpdates(config, summarizerModel);
4303
4298
  } else {
4304
- logger10.error(
4299
+ logger9.error(
4305
4300
  {
4306
4301
  sessionId,
4307
4302
  availableSessions: Array.from(this.sessions.keys())
@@ -4318,7 +4313,7 @@ var GraphSessionManager = class {
4318
4313
  if (session) {
4319
4314
  session.enableEmitOperations();
4320
4315
  } else {
4321
- logger10.error(
4316
+ logger9.error(
4322
4317
  {
4323
4318
  sessionId,
4324
4319
  availableSessions: Array.from(this.sessions.keys())
@@ -4335,14 +4330,15 @@ var GraphSessionManager = class {
4335
4330
  }
4336
4331
  /**
4337
4332
  * Record an event in a session
4333
+ * Generic type parameter T ensures eventType and data are correctly paired
4338
4334
  */
4339
- recordEvent(sessionId, eventType, agentId, data) {
4335
+ recordEvent(sessionId, eventType, subAgentId, data) {
4340
4336
  const session = this.sessions.get(sessionId);
4341
4337
  if (!session) {
4342
- logger10.warn({ sessionId }, "Attempted to record event in non-existent session");
4338
+ logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
4343
4339
  return;
4344
4340
  }
4345
- session.recordEvent(eventType, agentId, data);
4341
+ session.recordEvent(eventType, subAgentId, data);
4346
4342
  }
4347
4343
  /**
4348
4344
  * End a session and return the final event data
@@ -4350,12 +4346,12 @@ var GraphSessionManager = class {
4350
4346
  endSession(sessionId) {
4351
4347
  const session = this.sessions.get(sessionId);
4352
4348
  if (!session) {
4353
- logger10.warn({ sessionId }, "Attempted to end non-existent session");
4349
+ logger9.warn({ sessionId }, "Attempted to end non-existent session");
4354
4350
  return [];
4355
4351
  }
4356
4352
  const events = session.getEvents();
4357
4353
  const summary = session.getSummary();
4358
- logger10.info({ sessionId, summary }, "GraphSession ended");
4354
+ logger9.info({ sessionId, summary }, "GraphSession ended");
4359
4355
  session.cleanup();
4360
4356
  this.sessions.delete(sessionId);
4361
4357
  return events;
@@ -4463,7 +4459,7 @@ init_logger();
4463
4459
 
4464
4460
  // src/services/IncrementalStreamParser.ts
4465
4461
  init_logger();
4466
- var logger11 = agentsCore.getLogger("IncrementalStreamParser");
4462
+ var logger10 = agentsCore.getLogger("IncrementalStreamParser");
4467
4463
  var _IncrementalStreamParser = class _IncrementalStreamParser {
4468
4464
  // Max number of collected parts to prevent unbounded growth
4469
4465
  constructor(streamHelper, tenantId, contextId, artifactParserOptions) {
@@ -4479,10 +4475,10 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4479
4475
  __publicField(this, "lastStreamedComponents", /* @__PURE__ */ new Map());
4480
4476
  __publicField(this, "componentSnapshots", /* @__PURE__ */ new Map());
4481
4477
  __publicField(this, "artifactMap");
4482
- __publicField(this, "agentId");
4478
+ __publicField(this, "subAgentId");
4483
4479
  this.streamHelper = streamHelper;
4484
4480
  this.contextId = contextId;
4485
- this.agentId = artifactParserOptions?.agentId;
4481
+ this.subAgentId = artifactParserOptions?.subAgentId;
4486
4482
  if (artifactParserOptions?.streamRequestId) {
4487
4483
  const sessionParser = graphSessionManager.getArtifactParser(
4488
4484
  artifactParserOptions.streamRequestId
@@ -4515,7 +4511,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4515
4511
  async initializeArtifactMap() {
4516
4512
  try {
4517
4513
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
4518
- logger11.debug(
4514
+ logger10.debug(
4519
4515
  {
4520
4516
  contextId: this.contextId,
4521
4517
  artifactMapSize: this.artifactMap.size
@@ -4523,7 +4519,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4523
4519
  "Initialized artifact map for streaming"
4524
4520
  );
4525
4521
  } catch (error) {
4526
- logger11.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
4522
+ logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
4527
4523
  this.artifactMap = /* @__PURE__ */ new Map();
4528
4524
  }
4529
4525
  }
@@ -4625,7 +4621,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4625
4621
  dataComponents: [component]
4626
4622
  },
4627
4623
  this.artifactMap,
4628
- this.agentId
4624
+ this.subAgentId
4629
4625
  );
4630
4626
  if (!Array.isArray(parts)) {
4631
4627
  console.warn("parseObject returned non-array:", parts);
@@ -4701,7 +4697,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4701
4697
  dataComponents: [component]
4702
4698
  },
4703
4699
  this.artifactMap,
4704
- this.agentId
4700
+ this.subAgentId
4705
4701
  );
4706
4702
  for (const part of parts) {
4707
4703
  await this.streamPart(part);
@@ -4755,7 +4751,11 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4755
4751
  const safeEnd = this.artifactParser.findSafeTextBoundary(workingBuffer);
4756
4752
  if (safeEnd > 0) {
4757
4753
  const safeText = workingBuffer.slice(0, safeEnd);
4758
- const parts2 = await this.artifactParser.parseText(safeText, this.artifactMap, this.agentId);
4754
+ const parts2 = await this.artifactParser.parseText(
4755
+ safeText,
4756
+ this.artifactMap,
4757
+ this.subAgentId
4758
+ );
4759
4759
  completeParts.push(...parts2);
4760
4760
  return {
4761
4761
  completeParts,
@@ -4770,7 +4770,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4770
4770
  const parts = await this.artifactParser.parseText(
4771
4771
  workingBuffer,
4772
4772
  this.artifactMap,
4773
- this.agentId
4773
+ this.subAgentId
4774
4774
  );
4775
4775
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
4776
4776
  const lastPart = parts[parts.length - 1];
@@ -4844,12 +4844,12 @@ var IncrementalStreamParser = _IncrementalStreamParser;
4844
4844
 
4845
4845
  // src/services/ResponseFormatter.ts
4846
4846
  init_logger();
4847
- var logger12 = agentsCore.getLogger("ResponseFormatter");
4847
+ var logger11 = agentsCore.getLogger("ResponseFormatter");
4848
4848
  var ResponseFormatter = class {
4849
4849
  constructor(tenantId, artifactParserOptions) {
4850
4850
  __publicField(this, "artifactParser");
4851
- __publicField(this, "agentId");
4852
- this.agentId = artifactParserOptions?.agentId;
4851
+ __publicField(this, "subAgentId");
4852
+ this.subAgentId = artifactParserOptions?.subAgentId;
4853
4853
  if (artifactParserOptions?.streamRequestId) {
4854
4854
  const sessionParser = graphSessionManager.getArtifactParser(
4855
4855
  artifactParserOptions.streamRequestId
@@ -4888,7 +4888,7 @@ var ResponseFormatter = class {
4888
4888
  const parts = await this.artifactParser.parseObject(
4889
4889
  responseObject,
4890
4890
  artifactMap,
4891
- this.agentId
4891
+ this.subAgentId
4892
4892
  );
4893
4893
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
4894
4894
  span.setAttributes({
@@ -4903,7 +4903,7 @@ var ResponseFormatter = class {
4903
4903
  return { parts };
4904
4904
  } catch (error) {
4905
4905
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4906
- logger12.error({ error, responseObject }, "Error formatting object response");
4906
+ logger11.error({ error, responseObject }, "Error formatting object response");
4907
4907
  return {
4908
4908
  parts: [{ kind: "data", data: responseObject }]
4909
4909
  };
@@ -4935,7 +4935,11 @@ var ResponseFormatter = class {
4935
4935
  "response.type": "text",
4936
4936
  "response.availableArtifacts": artifactMap.size
4937
4937
  });
4938
- const parts = await this.artifactParser.parseText(responseText, artifactMap, this.agentId);
4938
+ const parts = await this.artifactParser.parseText(
4939
+ responseText,
4940
+ artifactMap,
4941
+ this.subAgentId
4942
+ );
4939
4943
  if (parts.length === 1 && parts[0].kind === "text") {
4940
4944
  return { text: parts[0].text };
4941
4945
  }
@@ -4955,7 +4959,7 @@ var ResponseFormatter = class {
4955
4959
  return { parts };
4956
4960
  } catch (error) {
4957
4961
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4958
- logger12.error({ error, responseText }, "Error formatting response");
4962
+ logger11.error({ error, responseText }, "Error formatting response");
4959
4963
  return { text: responseText };
4960
4964
  } finally {
4961
4965
  span.end();
@@ -5009,20 +5013,20 @@ function agentInitializingOp(sessionId, graphId) {
5009
5013
  }
5010
5014
  };
5011
5015
  }
5012
- function completionOp(agentId, iterations) {
5016
+ function completionOp(subAgentId, iterations) {
5013
5017
  return {
5014
5018
  type: "completion",
5015
5019
  details: {
5016
- agent: agentId,
5020
+ agent: subAgentId,
5017
5021
  iteration: iterations
5018
5022
  }
5019
5023
  };
5020
5024
  }
5021
- function errorOp(message, agentId, severity = "error", code) {
5025
+ function errorOp(message, subAgentId, severity = "error", code) {
5022
5026
  return {
5023
5027
  type: "error",
5024
5028
  message,
5025
- agent: agentId,
5029
+ agent: subAgentId,
5026
5030
  severity,
5027
5031
  code,
5028
5032
  timestamp: Date.now()
@@ -5037,10 +5041,10 @@ init_logger();
5037
5041
 
5038
5042
  // src/utils/data-component-schema.ts
5039
5043
  init_logger();
5040
- var logger13 = agentsCore.getLogger("DataComponentSchema");
5044
+ var logger12 = agentsCore.getLogger("DataComponentSchema");
5041
5045
  function jsonSchemaToZod(jsonSchema) {
5042
5046
  if (!jsonSchema || typeof jsonSchema !== "object") {
5043
- logger13.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
5047
+ logger12.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
5044
5048
  return z6.z.string();
5045
5049
  }
5046
5050
  switch (jsonSchema.type) {
@@ -5067,7 +5071,7 @@ function jsonSchemaToZod(jsonSchema) {
5067
5071
  case "null":
5068
5072
  return z6.z.null();
5069
5073
  default:
5070
- logger13.warn(
5074
+ logger12.warn(
5071
5075
  {
5072
5076
  unsupportedType: jsonSchema.type,
5073
5077
  schema: jsonSchema
@@ -5434,7 +5438,7 @@ function parseEmbeddedJson(data) {
5434
5438
 
5435
5439
  // src/a2a/client.ts
5436
5440
  init_logger();
5437
- var logger14 = agentsCore.getLogger("a2aClient");
5441
+ var logger13 = agentsCore.getLogger("a2aClient");
5438
5442
  var DEFAULT_BACKOFF = {
5439
5443
  initialInterval: 500,
5440
5444
  maxInterval: 6e4,
@@ -5640,7 +5644,7 @@ var A2AClient = class {
5640
5644
  try {
5641
5645
  const res = await fn();
5642
5646
  if (attempt > 0) {
5643
- logger14.info(
5647
+ logger13.info(
5644
5648
  {
5645
5649
  attempts: attempt + 1,
5646
5650
  elapsedTime: Date.now() - start
@@ -5655,7 +5659,7 @@ var A2AClient = class {
5655
5659
  }
5656
5660
  const elapsed = Date.now() - start;
5657
5661
  if (elapsed > maxElapsedTime) {
5658
- logger14.warn(
5662
+ logger13.warn(
5659
5663
  {
5660
5664
  attempts: attempt + 1,
5661
5665
  elapsedTime: elapsed,
@@ -5676,7 +5680,7 @@ var A2AClient = class {
5676
5680
  retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
5677
5681
  }
5678
5682
  const delayMs = Math.min(retryInterval, maxInterval);
5679
- logger14.info(
5683
+ logger13.info(
5680
5684
  {
5681
5685
  attempt: attempt + 1,
5682
5686
  delayMs,
@@ -5761,7 +5765,7 @@ var A2AClient = class {
5761
5765
  }
5762
5766
  const rpcResponse = await httpResponse.json();
5763
5767
  if (rpcResponse.id !== requestId2) {
5764
- logger14.warn(
5768
+ logger13.warn(
5765
5769
  {
5766
5770
  method,
5767
5771
  expectedId: requestId2,
@@ -5960,7 +5964,7 @@ var A2AClient = class {
5960
5964
  try {
5961
5965
  while (true) {
5962
5966
  const { done, value } = await reader.read();
5963
- logger14.info({ done, value }, "parseA2ASseStream");
5967
+ logger13.info({ done, value }, "parseA2ASseStream");
5964
5968
  if (done) {
5965
5969
  if (eventDataBuffer.trim()) {
5966
5970
  const result = this._processSseEventData(
@@ -6050,7 +6054,7 @@ var A2AClient = class {
6050
6054
  init_conversations();
6051
6055
  init_dbClient();
6052
6056
  init_logger();
6053
- var logger15 = agentsCore.getLogger("relationships Tools");
6057
+ var logger14 = agentsCore.getLogger("relationships Tools");
6054
6058
  var generateTransferToolDescription = (config) => {
6055
6059
  return `Hand off the conversation to agent ${config.id}.
6056
6060
 
@@ -6074,7 +6078,7 @@ Delegate a specific task to agent ${config.id} when it seems like the agent can
6074
6078
  var createTransferToAgentTool = ({
6075
6079
  transferConfig,
6076
6080
  callingAgentId,
6077
- agent,
6081
+ subAgent,
6078
6082
  streamRequestId
6079
6083
  }) => {
6080
6084
  return ai.tool({
@@ -6084,11 +6088,11 @@ var createTransferToAgentTool = ({
6084
6088
  const activeSpan = api.trace.getActiveSpan();
6085
6089
  if (activeSpan) {
6086
6090
  activeSpan.setAttributes({
6087
- "transfer.from_agent_id": callingAgentId,
6088
- "transfer.to_agent_id": transferConfig.id ?? "unknown"
6091
+ [agentsCore.SPAN_KEYS.TRANSFER_FROM_SUB_AGENT_ID]: callingAgentId,
6092
+ [agentsCore.SPAN_KEYS.TRANSFER_TO_SUB_AGENT_ID]: transferConfig.id ?? "unknown"
6089
6093
  });
6090
6094
  }
6091
- logger15.info(
6095
+ logger14.info(
6092
6096
  {
6093
6097
  transferTo: transferConfig.id ?? "unknown",
6094
6098
  fromAgent: callingAgentId
@@ -6097,8 +6101,8 @@ var createTransferToAgentTool = ({
6097
6101
  );
6098
6102
  if (streamRequestId) {
6099
6103
  graphSessionManager.recordEvent(streamRequestId, "transfer", callingAgentId, {
6100
- fromAgent: callingAgentId,
6101
- targetAgent: transferConfig.id ?? "unknown",
6104
+ fromSubAgent: callingAgentId,
6105
+ targetSubAgent: transferConfig.id ?? "unknown",
6102
6106
  reason: `Transfer to ${transferConfig.name || transferConfig.id}`
6103
6107
  });
6104
6108
  }
@@ -6120,7 +6124,7 @@ function createDelegateToAgentTool({
6120
6124
  contextId,
6121
6125
  metadata,
6122
6126
  sessionId,
6123
- agent,
6127
+ subAgent,
6124
6128
  credentialStoreRegistry
6125
6129
  }) {
6126
6130
  return ai.tool({
@@ -6131,9 +6135,9 @@ function createDelegateToAgentTool({
6131
6135
  const activeSpan = api.trace.getActiveSpan();
6132
6136
  if (activeSpan) {
6133
6137
  activeSpan.setAttributes({
6134
- "delegation.from_agent_id": callingAgentId,
6135
- "delegation.to_agent_id": delegateConfig.config.id ?? "unknown",
6136
- "delegation.id": delegationId
6138
+ [agentsCore.SPAN_KEYS.DELEGATION_FROM_SUB_AGENT_ID]: callingAgentId,
6139
+ [agentsCore.SPAN_KEYS.DELEGATION_TO_SUB_AGENT_ID]: delegateConfig.config.id ?? "unknown",
6140
+ [agentsCore.SPAN_KEYS.DELEGATION_ID]: delegationId
6137
6141
  });
6138
6142
  }
6139
6143
  if (metadata.streamRequestId) {
@@ -6143,8 +6147,8 @@ function createDelegateToAgentTool({
6143
6147
  callingAgentId,
6144
6148
  {
6145
6149
  delegationId,
6146
- fromAgent: callingAgentId,
6147
- targetAgent: delegateConfig.config.id,
6150
+ fromSubAgent: callingAgentId,
6151
+ targetSubAgent: delegateConfig.config.id,
6148
6152
  taskDescription: input.message
6149
6153
  }
6150
6154
  );
@@ -6158,7 +6162,7 @@ function createDelegateToAgentTool({
6158
6162
  projectId,
6159
6163
  graphId
6160
6164
  },
6161
- agentId: delegateConfig.config.id
6165
+ subAgentId: delegateConfig.config.id
6162
6166
  });
6163
6167
  if (externalAgent && (externalAgent.credentialReferenceId || externalAgent.headers) && credentialStoreRegistry) {
6164
6168
  const contextResolver = new agentsCore.ContextResolver(
@@ -6237,7 +6241,7 @@ function createDelegateToAgentTool({
6237
6241
  ...isInternal ? { fromAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
6238
6242
  }
6239
6243
  };
6240
- logger15.info({ messageToSend }, "messageToSend");
6244
+ logger14.info({ messageToSend }, "messageToSend");
6241
6245
  await agentsCore.createMessage(dbClient_default)({
6242
6246
  id: nanoid.nanoid(),
6243
6247
  tenantId,
@@ -6249,7 +6253,7 @@ function createDelegateToAgentTool({
6249
6253
  },
6250
6254
  visibility: isInternal ? "internal" : "external",
6251
6255
  messageType: "a2a-request",
6252
- fromAgentId: callingAgentId,
6256
+ fromSubAgentId: callingAgentId,
6253
6257
  ...isInternal ? { toAgentId: delegateConfig.config.id } : { toExternalAgentId: delegateConfig.config.id }
6254
6258
  });
6255
6259
  const response = await a2aClient.sendMessage({
@@ -6264,8 +6268,8 @@ function createDelegateToAgentTool({
6264
6268
  conversationId: contextId,
6265
6269
  messageType: "a2a-response",
6266
6270
  visibility: isInternal ? "internal" : "external",
6267
- toAgentId: callingAgentId,
6268
- ...isInternal ? { fromAgentId: delegateConfig.config.id } : { fromExternalAgentId: delegateConfig.config.id }
6271
+ toSubAgentId: callingAgentId,
6272
+ ...isInternal ? { fromSubAgentId: delegateConfig.config.id } : { fromExternalAgentId: delegateConfig.config.id }
6269
6273
  });
6270
6274
  if (sessionId && context?.toolCallId) {
6271
6275
  const toolResult = {
@@ -6284,8 +6288,8 @@ function createDelegateToAgentTool({
6284
6288
  callingAgentId,
6285
6289
  {
6286
6290
  delegationId,
6287
- fromAgent: delegateConfig.config.id,
6288
- targetAgent: callingAgentId,
6291
+ fromSubAgent: delegateConfig.config.id,
6292
+ targetSubAgent: callingAgentId,
6289
6293
  result: response.result
6290
6294
  }
6291
6295
  );
@@ -6300,7 +6304,7 @@ function createDelegateToAgentTool({
6300
6304
 
6301
6305
  // src/agents/SystemPromptBuilder.ts
6302
6306
  init_logger();
6303
- var logger16 = agentsCore.getLogger("SystemPromptBuilder");
6307
+ var logger15 = agentsCore.getLogger("SystemPromptBuilder");
6304
6308
  var SystemPromptBuilder = class {
6305
6309
  constructor(version, versionConfig) {
6306
6310
  this.version = version;
@@ -6316,12 +6320,12 @@ var SystemPromptBuilder = class {
6316
6320
  this.templates.set(name, content);
6317
6321
  }
6318
6322
  this.loaded = true;
6319
- logger16.debug(
6323
+ logger15.debug(
6320
6324
  { templateCount: this.templates.size, version: this.version },
6321
6325
  `Loaded ${this.templates.size} templates for version ${this.version}`
6322
6326
  );
6323
6327
  } catch (error) {
6324
- logger16.error({ error }, `Failed to load templates for version ${this.version}`);
6328
+ logger15.error({ error }, `Failed to load templates for version ${this.version}`);
6325
6329
  throw new Error(`Template loading failed: ${error}`);
6326
6330
  }
6327
6331
  }
@@ -7382,7 +7386,7 @@ function hasToolCallWithPrefix(prefix) {
7382
7386
  return false;
7383
7387
  };
7384
7388
  }
7385
- var logger19 = agentsCore.getLogger("Agent");
7389
+ var logger18 = agentsCore.getLogger("Agent");
7386
7390
  var CONSTANTS = {
7387
7391
  MAX_GENERATION_STEPS: 12,
7388
7392
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -7612,7 +7616,7 @@ var Agent = class {
7612
7616
  }
7613
7617
  getRelationTools(runtimeContext, sessionId) {
7614
7618
  const { transferRelations = [], delegateRelations = [] } = this.config;
7615
- const createToolName = (prefix, agentId) => `${prefix}_to_${agentId.toLowerCase().replace(/\s+/g, "_")}`;
7619
+ const createToolName = (prefix, subAgentId) => `${prefix}_to_${subAgentId.toLowerCase().replace(/\s+/g, "_")}`;
7616
7620
  return Object.fromEntries([
7617
7621
  ...transferRelations.map((agentConfig) => {
7618
7622
  const toolName = createToolName("transfer", agentConfig.id);
@@ -7623,7 +7627,7 @@ var Agent = class {
7623
7627
  createTransferToAgentTool({
7624
7628
  transferConfig: agentConfig,
7625
7629
  callingAgentId: this.config.id,
7626
- agent: this,
7630
+ subAgent: this,
7627
7631
  streamRequestId: runtimeContext?.metadata?.streamRequestId
7628
7632
  }),
7629
7633
  runtimeContext?.metadata?.streamRequestId,
@@ -7652,7 +7656,7 @@ var Agent = class {
7652
7656
  apiKey: runtimeContext?.metadata?.apiKey
7653
7657
  },
7654
7658
  sessionId,
7655
- agent: this,
7659
+ subAgent: this,
7656
7660
  credentialStoreRegistry: this.credentialStoreRegistry
7657
7661
  }),
7658
7662
  runtimeContext?.metadata?.streamRequestId,
@@ -7686,14 +7690,14 @@ var Agent = class {
7686
7690
  for (const toolSet of tools) {
7687
7691
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
7688
7692
  if (!isValidTool(originalTool)) {
7689
- logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7693
+ logger18.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7690
7694
  continue;
7691
7695
  }
7692
7696
  const sessionWrappedTool = ai.tool({
7693
7697
  description: originalTool.description,
7694
7698
  inputSchema: originalTool.inputSchema,
7695
7699
  execute: async (args, { toolCallId }) => {
7696
- logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
7700
+ logger18.debug({ toolName, toolCallId }, "MCP Tool Called");
7697
7701
  try {
7698
7702
  const rawResult = await originalTool.execute(args, { toolCallId });
7699
7703
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -7707,7 +7711,7 @@ var Agent = class {
7707
7711
  });
7708
7712
  return { result: enhancedResult, toolCallId };
7709
7713
  } catch (error) {
7710
- logger19.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7714
+ logger18.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7711
7715
  throw error;
7712
7716
  }
7713
7717
  }
@@ -7752,7 +7756,7 @@ var Agent = class {
7752
7756
  tenantId: this.config.tenantId,
7753
7757
  projectId: this.config.projectId,
7754
7758
  graphId: this.config.graphId,
7755
- agentId: this.config.id
7759
+ subAgentId: this.config.id
7756
7760
  }
7757
7761
  });
7758
7762
  const agentToolRelationHeaders = toolsForAgent.data.find((t) => t.toolId === tool3.id)?.headers || void 0;
@@ -7808,7 +7812,7 @@ var Agent = class {
7808
7812
  headers: agentToolRelationHeaders
7809
7813
  };
7810
7814
  }
7811
- logger19.info(
7815
+ logger18.info(
7812
7816
  {
7813
7817
  toolName: tool3.name,
7814
7818
  credentialReferenceId,
@@ -7833,10 +7837,10 @@ var Agent = class {
7833
7837
  this.mcpClientCache.set(cacheKey, client);
7834
7838
  } catch (error) {
7835
7839
  this.mcpConnectionLocks.delete(cacheKey);
7836
- logger19.error(
7840
+ logger18.error(
7837
7841
  {
7838
7842
  toolName: tool3.name,
7839
- agentId: this.config.id,
7843
+ subAgentId: this.config.id,
7840
7844
  cacheKey,
7841
7845
  error: error instanceof Error ? error.message : String(error)
7842
7846
  },
@@ -7857,10 +7861,10 @@ var Agent = class {
7857
7861
  await client.connect();
7858
7862
  return client;
7859
7863
  } catch (error) {
7860
- logger19.error(
7864
+ logger18.error(
7861
7865
  {
7862
7866
  toolName: tool3.name,
7863
- agentId: this.config.id,
7867
+ subAgentId: this.config.id,
7864
7868
  error: error instanceof Error ? error.message : String(error)
7865
7869
  },
7866
7870
  "Agent failed to connect to MCP server"
@@ -7876,7 +7880,7 @@ var Agent = class {
7876
7880
  tenantId: this.config.tenantId || "default",
7877
7881
  projectId: this.config.projectId || "default",
7878
7882
  graphId: this.config.graphId,
7879
- agentId: this.config.id
7883
+ subAgentId: this.config.id
7880
7884
  }
7881
7885
  });
7882
7886
  const toolsData = toolsForAgent.data || [];
@@ -7890,7 +7894,7 @@ var Agent = class {
7890
7894
  if (toolDef.tool.config?.type === "function") {
7891
7895
  const functionId = toolDef.tool.functionId;
7892
7896
  if (!functionId) {
7893
- logger19.warn({ toolId: toolDef.tool.id }, "Function tool missing functionId reference");
7897
+ logger18.warn({ toolId: toolDef.tool.id }, "Function tool missing functionId reference");
7894
7898
  continue;
7895
7899
  }
7896
7900
  const functionData = await agentsCore.getFunction(dbClient_default)({
@@ -7901,7 +7905,7 @@ var Agent = class {
7901
7905
  }
7902
7906
  });
7903
7907
  if (!functionData) {
7904
- logger19.warn(
7908
+ logger18.warn(
7905
7909
  { functionId, toolId: toolDef.tool.id },
7906
7910
  "Function not found in functions table"
7907
7911
  );
@@ -7912,7 +7916,7 @@ var Agent = class {
7912
7916
  description: toolDef.tool.description || toolDef.tool.name,
7913
7917
  inputSchema: zodSchema,
7914
7918
  execute: async (args, { toolCallId }) => {
7915
- logger19.debug(
7919
+ logger18.debug(
7916
7920
  { toolName: toolDef.tool.name, toolCallId, args },
7917
7921
  "Function Tool Called"
7918
7922
  );
@@ -7932,7 +7936,7 @@ var Agent = class {
7932
7936
  });
7933
7937
  return { result, toolCallId };
7934
7938
  } catch (error) {
7935
- logger19.error(
7939
+ logger18.error(
7936
7940
  { toolName: toolDef.tool.name, toolCallId, error },
7937
7941
  "Function tool execution failed"
7938
7942
  );
@@ -7949,7 +7953,7 @@ var Agent = class {
7949
7953
  }
7950
7954
  }
7951
7955
  } catch (error) {
7952
- logger19.error({ error }, "Failed to load function tools from database");
7956
+ logger18.error({ error }, "Failed to load function tools from database");
7953
7957
  }
7954
7958
  return functionTools;
7955
7959
  }
@@ -7959,7 +7963,7 @@ var Agent = class {
7959
7963
  async getResolvedContext(conversationId, headers) {
7960
7964
  try {
7961
7965
  if (!this.config.contextConfigId) {
7962
- logger19.debug({ graphId: this.config.graphId }, "No context config found for graph");
7966
+ logger18.debug({ graphId: this.config.graphId }, "No context config found for graph");
7963
7967
  return null;
7964
7968
  }
7965
7969
  const contextConfig = await agentsCore.getContextConfigById(dbClient_default)({
@@ -7971,7 +7975,7 @@ var Agent = class {
7971
7975
  id: this.config.contextConfigId
7972
7976
  });
7973
7977
  if (!contextConfig) {
7974
- logger19.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7978
+ logger18.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7975
7979
  return null;
7976
7980
  }
7977
7981
  if (!this.contextResolver) {
@@ -7988,7 +7992,7 @@ var Agent = class {
7988
7992
  $now: (/* @__PURE__ */ new Date()).toISOString(),
7989
7993
  $env: process.env
7990
7994
  };
7991
- logger19.debug(
7995
+ logger18.debug(
7992
7996
  {
7993
7997
  conversationId,
7994
7998
  contextConfigId: contextConfig.id,
@@ -8002,7 +8006,7 @@ var Agent = class {
8002
8006
  );
8003
8007
  return contextWithBuiltins;
8004
8008
  } catch (error) {
8005
- logger19.error(
8009
+ logger18.error(
8006
8010
  {
8007
8011
  conversationId,
8008
8012
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8026,7 +8030,7 @@ var Agent = class {
8026
8030
  });
8027
8031
  return graphDefinition?.graphPrompt || void 0;
8028
8032
  } catch (error) {
8029
- logger19.warn(
8033
+ logger18.warn(
8030
8034
  {
8031
8035
  graphId: this.config.graphId,
8032
8036
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8051,11 +8055,11 @@ var Agent = class {
8051
8055
  if (!graphDefinition) {
8052
8056
  return false;
8053
8057
  }
8054
- return Object.values(graphDefinition.agents).some(
8055
- (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
8058
+ return Object.values(graphDefinition.subAgents).some(
8059
+ (subAgent) => "artifactComponents" in subAgent && subAgent.artifactComponents && subAgent.artifactComponents.length > 0
8056
8060
  );
8057
8061
  } catch (error) {
8058
- logger19.warn(
8062
+ logger18.warn(
8059
8063
  {
8060
8064
  graphId: this.config.graphId,
8061
8065
  tenantId: this.config.tenantId,
@@ -8084,7 +8088,7 @@ var Agent = class {
8084
8088
  preserveUnresolved: false
8085
8089
  });
8086
8090
  } catch (error) {
8087
- logger19.error(
8091
+ logger18.error(
8088
8092
  {
8089
8093
  conversationId,
8090
8094
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8131,7 +8135,7 @@ var Agent = class {
8131
8135
  preserveUnresolved: false
8132
8136
  });
8133
8137
  } catch (error) {
8134
- logger19.error(
8138
+ logger18.error(
8135
8139
  {
8136
8140
  conversationId,
8137
8141
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8146,7 +8150,7 @@ var Agent = class {
8146
8150
  const functionTools = await this.getFunctionTools(streamRequestId || "");
8147
8151
  const relationTools = this.getRelationTools(runtimeContext);
8148
8152
  const allTools = { ...mcpTools, ...functionTools, ...relationTools };
8149
- logger19.info(
8153
+ logger18.info(
8150
8154
  {
8151
8155
  mcpTools: Object.keys(mcpTools),
8152
8156
  functionTools: Object.keys(functionTools),
@@ -8185,7 +8189,7 @@ var Agent = class {
8185
8189
  preserveUnresolved: false
8186
8190
  });
8187
8191
  } catch (error) {
8188
- logger19.error(
8192
+ logger18.error(
8189
8193
  {
8190
8194
  conversationId,
8191
8195
  error: error instanceof Error ? error.message : "Unknown error"
@@ -8218,7 +8222,7 @@ var Agent = class {
8218
8222
  toolCallId: z6.z.string().describe("The tool call ID associated with this artifact.")
8219
8223
  }),
8220
8224
  execute: async ({ artifactId, toolCallId }) => {
8221
- logger19.info({ artifactId, toolCallId }, "get_artifact_full executed");
8225
+ logger18.info({ artifactId, toolCallId }, "get_artifact_full executed");
8222
8226
  const streamRequestId = this.getStreamRequestId();
8223
8227
  const artifactService = graphSessionManager.getArtifactService(streamRequestId);
8224
8228
  if (!artifactService) {
@@ -8252,7 +8256,7 @@ var Agent = class {
8252
8256
  });
8253
8257
  }
8254
8258
  // Provide a default tool set that is always available to the agent.
8255
- async getDefaultTools(_sessionId, streamRequestId) {
8259
+ async getDefaultTools(streamRequestId) {
8256
8260
  const defaultTools = {};
8257
8261
  if (await this.graphHasArtifactComponents()) {
8258
8262
  defaultTools.get_reference_artifact = this.getArtifactTools();
@@ -8478,7 +8482,7 @@ var Agent = class {
8478
8482
  };
8479
8483
  return enhanced;
8480
8484
  } catch (error) {
8481
- logger19.warn({ error }, "Failed to enhance tool result with structure hints");
8485
+ logger18.warn({ error }, "Failed to enhance tool result with structure hints");
8482
8486
  return result;
8483
8487
  }
8484
8488
  }
@@ -8493,7 +8497,7 @@ var Agent = class {
8493
8497
  }
8494
8498
  });
8495
8499
  } catch (error) {
8496
- logger19.error(
8500
+ logger18.error(
8497
8501
  { error, graphId: this.config.graphId },
8498
8502
  "Failed to check graph artifact components"
8499
8503
  );
@@ -8538,7 +8542,7 @@ var Agent = class {
8538
8542
  // Thinking prompt without data components
8539
8543
  this.getFunctionTools(sessionId, streamRequestId),
8540
8544
  Promise.resolve(this.getRelationTools(runtimeContext, sessionId)),
8541
- this.getDefaultTools(sessionId, streamRequestId)
8545
+ this.getDefaultTools(streamRequestId)
8542
8546
  ]);
8543
8547
  childSpan.setStatus({ code: api.SpanStatusCode.OK });
8544
8548
  return result;
@@ -8578,7 +8582,7 @@ var Agent = class {
8578
8582
  currentMessage: userMessage,
8579
8583
  options: historyConfig,
8580
8584
  filters: {
8581
- agentId: this.config.id,
8585
+ subAgentId: this.config.id,
8582
8586
  taskId
8583
8587
  }
8584
8588
  });
@@ -8594,7 +8598,7 @@ var Agent = class {
8594
8598
  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
8599
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
8596
8600
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
8597
- logger19.warn(
8601
+ logger18.warn(
8598
8602
  {
8599
8603
  requestedTimeout: modelSettings.maxDuration * 1e3,
8600
8604
  appliedTimeout: timeoutMs,
@@ -8636,7 +8640,7 @@ var Agent = class {
8636
8640
  }
8637
8641
  );
8638
8642
  } catch (error) {
8639
- logger19.debug({ error }, "Failed to track agent reasoning");
8643
+ logger18.debug({ error }, "Failed to track agent reasoning");
8640
8644
  }
8641
8645
  }
8642
8646
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -8663,7 +8667,7 @@ var Agent = class {
8663
8667
  projectId: session?.projectId,
8664
8668
  artifactComponents: this.artifactComponents,
8665
8669
  streamRequestId: this.getStreamRequestId(),
8666
- agentId: this.config.id
8670
+ subAgentId: this.config.id
8667
8671
  };
8668
8672
  const parser = new IncrementalStreamParser(
8669
8673
  streamHelper,
@@ -8740,7 +8744,7 @@ var Agent = class {
8740
8744
  }
8741
8745
  );
8742
8746
  } catch (error) {
8743
- logger19.debug({ error }, "Failed to track agent reasoning");
8747
+ logger18.debug({ error }, "Failed to track agent reasoning");
8744
8748
  }
8745
8749
  }
8746
8750
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -8912,7 +8916,7 @@ ${output}${structureHintsFormatted}`;
8912
8916
  projectId: session?.projectId,
8913
8917
  artifactComponents: this.artifactComponents,
8914
8918
  streamRequestId: this.getStreamRequestId(),
8915
- agentId: this.config.id
8919
+ subAgentId: this.config.id
8916
8920
  };
8917
8921
  const parser = new IncrementalStreamParser(
8918
8922
  streamHelper,
@@ -8995,7 +8999,7 @@ ${output}${structureHintsFormatted}`;
8995
8999
  contextId,
8996
9000
  artifactComponents: this.artifactComponents,
8997
9001
  streamRequestId: this.getStreamRequestId(),
8998
- agentId: this.config.id
9002
+ subAgentId: this.config.id
8999
9003
  });
9000
9004
  if (response.object) {
9001
9005
  formattedContent = await responseFormatter.formatObjectResponse(
@@ -9032,7 +9036,7 @@ ${output}${structureHintsFormatted}`;
9032
9036
  };
9033
9037
 
9034
9038
  // src/agents/generateTaskHandler.ts
9035
- var logger20 = agentsCore.getLogger("generateTaskHandler");
9039
+ var logger19 = agentsCore.getLogger("generateTaskHandler");
9036
9040
  var createTaskHandler = (config, credentialStoreRegistry) => {
9037
9041
  return async (task) => {
9038
9042
  try {
@@ -9058,14 +9062,14 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9058
9062
  projectId: config.projectId,
9059
9063
  graphId: config.graphId
9060
9064
  },
9061
- agentId: config.agentId
9065
+ subAgentId: config.subAgentId
9062
9066
  }),
9063
9067
  agentsCore.getToolsForAgent(dbClient_default)({
9064
9068
  scopes: {
9065
9069
  tenantId: config.tenantId,
9066
9070
  projectId: config.projectId,
9067
9071
  graphId: config.graphId,
9068
- agentId: config.agentId
9072
+ subAgentId: config.subAgentId
9069
9073
  }
9070
9074
  }),
9071
9075
  agentsCore.getDataComponentsForAgent(dbClient_default)({
@@ -9073,7 +9077,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9073
9077
  tenantId: config.tenantId,
9074
9078
  projectId: config.projectId,
9075
9079
  graphId: config.graphId,
9076
- agentId: config.agentId
9080
+ subAgentId: config.subAgentId
9077
9081
  }
9078
9082
  }),
9079
9083
  agentsCore.getArtifactComponentsForAgent(dbClient_default)({
@@ -9081,21 +9085,21 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9081
9085
  tenantId: config.tenantId,
9082
9086
  projectId: config.projectId,
9083
9087
  graphId: config.graphId,
9084
- agentId: config.agentId
9088
+ subAgentId: config.subAgentId
9085
9089
  }
9086
9090
  })
9087
9091
  ]);
9088
- logger20.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9092
+ logger19.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9089
9093
  const enhancedInternalRelations = await Promise.all(
9090
9094
  internalRelations.map(async (relation) => {
9091
9095
  try {
9092
- const relatedAgent = await agentsCore.getAgentById(dbClient_default)({
9096
+ const relatedAgent = await agentsCore.getSubAgentById(dbClient_default)({
9093
9097
  scopes: {
9094
9098
  tenantId: config.tenantId,
9095
9099
  projectId: config.projectId,
9096
9100
  graphId: config.graphId
9097
9101
  },
9098
- agentId: relation.id
9102
+ subAgentId: relation.id
9099
9103
  });
9100
9104
  if (relatedAgent) {
9101
9105
  const relatedAgentRelations = await agentsCore.getRelatedAgentsForGraph(dbClient_default)({
@@ -9104,7 +9108,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9104
9108
  projectId: config.projectId,
9105
9109
  graphId: config.graphId
9106
9110
  },
9107
- agentId: relation.id
9111
+ subAgentId: relation.id
9108
9112
  });
9109
9113
  const enhancedDescription = generateDescriptionWithTransfers(
9110
9114
  relation.description || "",
@@ -9114,7 +9118,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9114
9118
  return { ...relation, description: enhancedDescription };
9115
9119
  }
9116
9120
  } catch (error) {
9117
- logger20.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
9121
+ logger19.warn({ subAgentId: relation.id, error }, "Failed to enhance agent description");
9118
9122
  }
9119
9123
  return relation;
9120
9124
  })
@@ -9129,7 +9133,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9129
9133
  ) ?? [];
9130
9134
  const agent = new Agent(
9131
9135
  {
9132
- id: config.agentId,
9136
+ id: config.subAgentId,
9133
9137
  tenantId: config.tenantId,
9134
9138
  projectId: config.projectId,
9135
9139
  graphId: config.graphId,
@@ -9140,7 +9144,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9140
9144
  agentPrompt,
9141
9145
  models: models || void 0,
9142
9146
  stopWhen: stopWhen || void 0,
9143
- agentRelations: enhancedInternalRelations.map((relation) => ({
9147
+ subAgentRelations: enhancedInternalRelations.map((relation) => ({
9144
9148
  id: relation.id,
9145
9149
  tenantId: config.tenantId,
9146
9150
  projectId: config.projectId,
@@ -9151,7 +9155,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9151
9155
  description: relation.description,
9152
9156
  agentPrompt: "",
9153
9157
  delegateRelations: [],
9154
- agentRelations: [],
9158
+ subAgentRelations: [],
9155
9159
  transferRelations: []
9156
9160
  })),
9157
9161
  transferRelations: enhancedInternalRelations.filter((relation) => relation.relationType === "transfer").map((relation) => ({
@@ -9165,7 +9169,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9165
9169
  description: relation.description,
9166
9170
  agentPrompt: "",
9167
9171
  delegateRelations: [],
9168
- agentRelations: [],
9172
+ subAgentRelations: [],
9169
9173
  transferRelations: []
9170
9174
  })),
9171
9175
  delegateRelations: [
@@ -9183,7 +9187,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9183
9187
  description: relation.description,
9184
9188
  agentPrompt: "",
9185
9189
  delegateRelations: [],
9186
- agentRelations: [],
9190
+ subAgentRelations: [],
9187
9191
  transferRelations: []
9188
9192
  }
9189
9193
  })),
@@ -9218,11 +9222,11 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9218
9222
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
9219
9223
  if (taskIdMatch) {
9220
9224
  contextId = taskIdMatch[1];
9221
- logger20.info(
9225
+ logger19.info(
9222
9226
  {
9223
9227
  taskId: task.id,
9224
9228
  extractedContextId: contextId,
9225
- agentId: config.agentId
9229
+ subAgentId: config.subAgentId
9226
9230
  },
9227
9231
  "Extracted contextId from task ID for delegation"
9228
9232
  );
@@ -9234,8 +9238,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9234
9238
  const isDelegation = task.context?.metadata?.isDelegation === true;
9235
9239
  agent.setDelegationStatus(isDelegation);
9236
9240
  if (isDelegation) {
9237
- logger20.info(
9238
- { agentId: config.agentId, taskId: task.id },
9241
+ logger19.info(
9242
+ { subAgentId: config.subAgentId, taskId: task.id },
9239
9243
  "Delegated agent - streaming disabled"
9240
9244
  );
9241
9245
  if (streamRequestId && config.tenantId && config.projectId) {
@@ -9332,13 +9336,13 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9332
9336
  };
9333
9337
  };
9334
9338
  var createTaskHandlerConfig = async (params) => {
9335
- const agent = await agentsCore.getAgentById(dbClient_default)({
9339
+ const agent = await agentsCore.getSubAgentById(dbClient_default)({
9336
9340
  scopes: {
9337
9341
  tenantId: params.tenantId,
9338
9342
  projectId: params.projectId,
9339
9343
  graphId: params.graphId
9340
9344
  },
9341
- agentId: params.agentId
9345
+ subAgentId: params.subAgentId
9342
9346
  });
9343
9347
  const agentGraph = await agentsCore.getAgentGraphById(dbClient_default)({
9344
9348
  scopes: {
@@ -9348,7 +9352,7 @@ var createTaskHandlerConfig = async (params) => {
9348
9352
  }
9349
9353
  });
9350
9354
  if (!agent) {
9351
- throw new Error(`Agent not found: ${params.agentId}`);
9355
+ throw new Error(`Agent not found: ${params.subAgentId}`);
9352
9356
  }
9353
9357
  const effectiveModels = await resolveModelConfig(params.graphId, agent);
9354
9358
  const effectiveConversationHistoryConfig = agent.conversationHistoryConfig || { mode: "full" };
@@ -9356,7 +9360,7 @@ var createTaskHandlerConfig = async (params) => {
9356
9360
  tenantId: params.tenantId,
9357
9361
  projectId: params.projectId,
9358
9362
  graphId: params.graphId,
9359
- agentId: params.agentId,
9363
+ subAgentId: params.subAgentId,
9360
9364
  agentSchema: {
9361
9365
  id: agent.id,
9362
9366
  name: agent.name,
@@ -9385,25 +9389,27 @@ async function hydrateGraph({
9385
9389
  apiKey
9386
9390
  }) {
9387
9391
  try {
9388
- if (!dbGraph.defaultAgentId) {
9392
+ if (!dbGraph.defaultSubAgentId) {
9389
9393
  throw new Error(`Graph ${dbGraph.id} does not have a default agent configured`);
9390
9394
  }
9391
- const defaultAgent = await agentsCore.getAgentById(dbClient_default)({
9395
+ const defaultSubAgent = await agentsCore.getSubAgentById(dbClient_default)({
9392
9396
  scopes: {
9393
9397
  tenantId: dbGraph.tenantId,
9394
9398
  projectId: dbGraph.projectId,
9395
9399
  graphId: dbGraph.id
9396
9400
  },
9397
- agentId: dbGraph.defaultAgentId
9401
+ subAgentId: dbGraph.defaultSubAgentId
9398
9402
  });
9399
- if (!defaultAgent) {
9400
- throw new Error(`Default agent ${dbGraph.defaultAgentId} not found for graph ${dbGraph.id}`);
9403
+ if (!defaultSubAgent) {
9404
+ throw new Error(
9405
+ `Default agent ${dbGraph.defaultSubAgentId} not found for graph ${dbGraph.id}`
9406
+ );
9401
9407
  }
9402
9408
  const taskHandlerConfig = await createTaskHandlerConfig({
9403
9409
  tenantId: dbGraph.tenantId,
9404
9410
  projectId: dbGraph.projectId,
9405
9411
  graphId: dbGraph.id,
9406
- agentId: dbGraph.defaultAgentId,
9412
+ subAgentId: dbGraph.defaultSubAgentId,
9407
9413
  baseUrl,
9408
9414
  apiKey
9409
9415
  });
@@ -9432,7 +9438,7 @@ async function hydrateGraph({
9432
9438
  }
9433
9439
  };
9434
9440
  return {
9435
- agentId: dbGraph.id,
9441
+ subAgentId: dbGraph.id,
9436
9442
  // Use graph ID as agent ID for A2A purposes
9437
9443
  tenantId: dbGraph.tenantId,
9438
9444
  projectId: dbGraph.projectId,
@@ -9459,7 +9465,7 @@ async function getRegisteredGraph(executionContext) {
9459
9465
  init_dbClient();
9460
9466
  init_logger();
9461
9467
  var app = new zodOpenapi.OpenAPIHono();
9462
- var logger21 = agentsCore.getLogger("agents");
9468
+ var logger20 = agentsCore.getLogger("agents");
9463
9469
  app.openapi(
9464
9470
  zodOpenapi.createRoute({
9465
9471
  method: "get",
@@ -9497,7 +9503,7 @@ app.openapi(
9497
9503
  tracestate: c.req.header("tracestate"),
9498
9504
  baggage: c.req.header("baggage")
9499
9505
  };
9500
- logger21.info(
9506
+ logger20.info(
9501
9507
  {
9502
9508
  otelHeaders,
9503
9509
  path: c.req.path,
@@ -9506,22 +9512,22 @@ app.openapi(
9506
9512
  "OpenTelemetry headers: well-known agent.json"
9507
9513
  );
9508
9514
  const executionContext = agentsCore.getRequestExecutionContext(c);
9509
- const { tenantId, projectId, graphId, agentId } = executionContext;
9515
+ const { tenantId, projectId, graphId, subAgentId } = executionContext;
9510
9516
  console.dir("executionContext", executionContext);
9511
- if (agentId) {
9512
- logger21.info(
9517
+ if (subAgentId) {
9518
+ logger20.info(
9513
9519
  {
9514
9520
  message: "getRegisteredAgent (agent-level)",
9515
9521
  tenantId,
9516
9522
  projectId,
9517
9523
  graphId,
9518
- agentId
9524
+ subAgentId
9519
9525
  },
9520
9526
  "agent-level well-known agent.json"
9521
9527
  );
9522
9528
  const credentialStores = c.get("credentialStores");
9523
9529
  const agent = await getRegisteredAgent(executionContext, credentialStores);
9524
- logger21.info({ agent }, "agent registered: well-known agent.json");
9530
+ logger20.info({ agent }, "agent registered: well-known agent.json");
9525
9531
  if (!agent) {
9526
9532
  throw agentsCore.createApiError({
9527
9533
  code: "not_found",
@@ -9530,7 +9536,7 @@ app.openapi(
9530
9536
  }
9531
9537
  return c.json(agent.agentCard);
9532
9538
  } else {
9533
- logger21.info(
9539
+ logger20.info(
9534
9540
  {
9535
9541
  message: "getRegisteredGraph (graph-level)",
9536
9542
  tenantId,
@@ -9556,7 +9562,7 @@ app.post("/a2a", async (c) => {
9556
9562
  tracestate: c.req.header("tracestate"),
9557
9563
  baggage: c.req.header("baggage")
9558
9564
  };
9559
- logger21.info(
9565
+ logger20.info(
9560
9566
  {
9561
9567
  otelHeaders,
9562
9568
  path: c.req.path,
@@ -9565,15 +9571,15 @@ app.post("/a2a", async (c) => {
9565
9571
  "OpenTelemetry headers: a2a"
9566
9572
  );
9567
9573
  const executionContext = agentsCore.getRequestExecutionContext(c);
9568
- const { tenantId, projectId, graphId, agentId } = executionContext;
9569
- if (agentId) {
9570
- logger21.info(
9574
+ const { tenantId, projectId, graphId, subAgentId } = executionContext;
9575
+ if (subAgentId) {
9576
+ logger20.info(
9571
9577
  {
9572
9578
  message: "a2a (agent-level)",
9573
9579
  tenantId,
9574
9580
  projectId,
9575
9581
  graphId,
9576
- agentId
9582
+ subAgentId
9577
9583
  },
9578
9584
  "agent-level a2a endpoint"
9579
9585
  );
@@ -9591,7 +9597,7 @@ app.post("/a2a", async (c) => {
9591
9597
  }
9592
9598
  return a2aHandler(c, agent);
9593
9599
  } else {
9594
- logger21.info(
9600
+ logger20.info(
9595
9601
  {
9596
9602
  message: "a2a (graph-level)",
9597
9603
  tenantId,
@@ -9600,7 +9606,7 @@ app.post("/a2a", async (c) => {
9600
9606
  },
9601
9607
  "graph-level a2a endpoint"
9602
9608
  );
9603
- const graph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
9609
+ const graph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
9604
9610
  scopes: { tenantId, projectId, graphId }
9605
9611
  });
9606
9612
  if (!graph) {
@@ -9613,7 +9619,7 @@ app.post("/a2a", async (c) => {
9613
9619
  404
9614
9620
  );
9615
9621
  }
9616
- if (!graph.defaultAgentId) {
9622
+ if (!graph.defaultSubAgentId) {
9617
9623
  return c.json(
9618
9624
  {
9619
9625
  jsonrpc: "2.0",
@@ -9623,10 +9629,10 @@ app.post("/a2a", async (c) => {
9623
9629
  400
9624
9630
  );
9625
9631
  }
9626
- executionContext.agentId = graph.defaultAgentId;
9632
+ executionContext.subAgentId = graph.defaultSubAgentId;
9627
9633
  const credentialStores = c.get("credentialStores");
9628
- const defaultAgent = await getRegisteredAgent(executionContext, credentialStores);
9629
- if (!defaultAgent) {
9634
+ const defaultSubAgent = await getRegisteredAgent(executionContext, credentialStores);
9635
+ if (!defaultSubAgent) {
9630
9636
  return c.json(
9631
9637
  {
9632
9638
  jsonrpc: "2.0",
@@ -9636,7 +9642,7 @@ app.post("/a2a", async (c) => {
9636
9642
  404
9637
9643
  );
9638
9644
  }
9639
- return a2aHandler(c, defaultAgent);
9645
+ return a2aHandler(c, defaultSubAgent);
9640
9646
  }
9641
9647
  });
9642
9648
  var agents_default = app;
@@ -9647,20 +9653,20 @@ init_dbClient();
9647
9653
  // src/a2a/transfer.ts
9648
9654
  init_dbClient();
9649
9655
  init_logger();
9650
- var logger22 = agentsCore.getLogger("Transfer");
9656
+ var logger21 = agentsCore.getLogger("Transfer");
9651
9657
  async function executeTransfer({
9652
9658
  tenantId,
9653
9659
  threadId,
9654
9660
  projectId,
9655
- targetAgentId
9661
+ targetSubAgentId
9656
9662
  }) {
9657
- logger22.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
9663
+ logger21.info({ targetAgent: targetSubAgentId }, "Executing transfer to agent");
9658
9664
  await agentsCore.setActiveAgentForThread(dbClient_default)({
9659
9665
  scopes: { tenantId, projectId },
9660
9666
  threadId,
9661
- agentId: targetAgentId
9667
+ subAgentId: targetSubAgentId
9662
9668
  });
9663
- return { success: true, targetAgentId };
9669
+ return { success: true, targetSubAgentId };
9664
9670
  }
9665
9671
  function isTransferResponse(result) {
9666
9672
  return result?.artifacts.some(
@@ -10240,7 +10246,7 @@ function createMCPStreamHelper() {
10240
10246
  }
10241
10247
 
10242
10248
  // src/handlers/executionHandler.ts
10243
- var logger23 = agentsCore.getLogger("ExecutionHandler");
10249
+ var logger22 = agentsCore.getLogger("ExecutionHandler");
10244
10250
  var ExecutionHandler = class {
10245
10251
  constructor() {
10246
10252
  // Hardcoded error limit - separate from configurable stopWhen
@@ -10276,7 +10282,7 @@ var ExecutionHandler = class {
10276
10282
  if (emitOperations) {
10277
10283
  graphSessionManager.enableEmitOperations(requestId2);
10278
10284
  }
10279
- logger23.info(
10285
+ logger22.info(
10280
10286
  { sessionId: requestId2, graphId, conversationId, emitOperations },
10281
10287
  "Created GraphSession for message execution"
10282
10288
  );
@@ -10291,7 +10297,7 @@ var ExecutionHandler = class {
10291
10297
  );
10292
10298
  }
10293
10299
  } catch (error) {
10294
- logger23.error(
10300
+ logger22.error(
10295
10301
  {
10296
10302
  error: error instanceof Error ? error.message : "Unknown error",
10297
10303
  stack: error instanceof Error ? error.stack : void 0
@@ -10307,7 +10313,7 @@ var ExecutionHandler = class {
10307
10313
  try {
10308
10314
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
10309
10315
  const taskId = `task_${conversationId}-${requestId2}`;
10310
- logger23.info(
10316
+ logger22.info(
10311
10317
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
10312
10318
  "Attempting to create or reuse existing task"
10313
10319
  );
@@ -10317,7 +10323,7 @@ var ExecutionHandler = class {
10317
10323
  tenantId,
10318
10324
  projectId,
10319
10325
  graphId,
10320
- agentId: currentAgentId,
10326
+ subAgentId: currentAgentId,
10321
10327
  contextId: conversationId,
10322
10328
  status: "pending",
10323
10329
  metadata: {
@@ -10331,7 +10337,7 @@ var ExecutionHandler = class {
10331
10337
  agent_id: currentAgentId
10332
10338
  }
10333
10339
  });
10334
- logger23.info(
10340
+ logger22.info(
10335
10341
  {
10336
10342
  taskId,
10337
10343
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -10340,27 +10346,27 @@ var ExecutionHandler = class {
10340
10346
  );
10341
10347
  } catch (error) {
10342
10348
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
10343
- logger23.info(
10349
+ logger22.info(
10344
10350
  { taskId, error: error.message },
10345
10351
  "Task already exists, fetching existing task"
10346
10352
  );
10347
10353
  const existingTask = await agentsCore.getTask(dbClient_default)({ id: taskId });
10348
10354
  if (existingTask) {
10349
10355
  task = existingTask;
10350
- logger23.info(
10356
+ logger22.info(
10351
10357
  { taskId, existingTask },
10352
10358
  "Successfully reused existing task from race condition"
10353
10359
  );
10354
10360
  } else {
10355
- logger23.error({ taskId, error }, "Task constraint failed but task not found");
10361
+ logger22.error({ taskId, error }, "Task constraint failed but task not found");
10356
10362
  throw error;
10357
10363
  }
10358
10364
  } else {
10359
- logger23.error({ taskId, error }, "Failed to create task due to non-constraint error");
10365
+ logger22.error({ taskId, error }, "Failed to create task due to non-constraint error");
10360
10366
  throw error;
10361
10367
  }
10362
10368
  }
10363
- logger23.debug(
10369
+ logger22.debug(
10364
10370
  {
10365
10371
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
10366
10372
  executionType: "create_initial_task",
@@ -10378,7 +10384,7 @@ var ExecutionHandler = class {
10378
10384
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
10379
10385
  while (iterations < maxTransfers) {
10380
10386
  iterations++;
10381
- logger23.info(
10387
+ logger22.info(
10382
10388
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
10383
10389
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
10384
10390
  );
@@ -10386,10 +10392,10 @@ var ExecutionHandler = class {
10386
10392
  scopes: { tenantId, projectId },
10387
10393
  conversationId
10388
10394
  });
10389
- logger23.info({ activeAgent }, "activeAgent");
10390
- if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
10391
- currentAgentId = activeAgent.activeAgentId;
10392
- logger23.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10395
+ logger22.info({ activeAgent }, "activeAgent");
10396
+ if (activeAgent && activeAgent.activeSubAgentId !== currentAgentId) {
10397
+ currentAgentId = activeAgent.activeSubAgentId;
10398
+ logger22.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10393
10399
  }
10394
10400
  const agentBaseUrl = `${baseUrl}/agents`;
10395
10401
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -10430,13 +10436,13 @@ var ExecutionHandler = class {
10430
10436
  });
10431
10437
  if (!messageResponse?.result) {
10432
10438
  errorCount++;
10433
- logger23.error(
10439
+ logger22.error(
10434
10440
  { currentAgentId, iterations, errorCount },
10435
10441
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
10436
10442
  );
10437
10443
  if (errorCount >= this.MAX_ERRORS) {
10438
10444
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
10439
- logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10445
+ logger22.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10440
10446
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
10441
10447
  if (task) {
10442
10448
  await agentsCore.updateTask(dbClient_default)({
@@ -10459,20 +10465,20 @@ var ExecutionHandler = class {
10459
10465
  }
10460
10466
  if (isTransferResponse(messageResponse.result)) {
10461
10467
  const transferResponse = messageResponse.result;
10462
- const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
10468
+ const targetSubAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetSubAgentId;
10463
10469
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
10464
- logger23.info({ targetAgentId, transferReason }, "transfer response");
10470
+ logger22.info({ targetSubAgentId, transferReason }, "transfer response");
10465
10471
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
10466
- const { success, targetAgentId: newAgentId } = await executeTransfer({
10472
+ const { success, targetSubAgentId: newAgentId } = await executeTransfer({
10467
10473
  projectId,
10468
10474
  tenantId,
10469
10475
  threadId: conversationId,
10470
- targetAgentId
10476
+ targetSubAgentId
10471
10477
  });
10472
10478
  if (success) {
10473
10479
  fromAgentId = currentAgentId;
10474
10480
  currentAgentId = newAgentId;
10475
- logger23.info(
10481
+ logger22.info(
10476
10482
  {
10477
10483
  transferFrom: fromAgentId,
10478
10484
  transferTo: currentAgentId,
@@ -10490,7 +10496,7 @@ var ExecutionHandler = class {
10490
10496
  const graphSessionData = graphSessionManager.getSession(requestId2);
10491
10497
  if (graphSessionData) {
10492
10498
  const sessionSummary = graphSessionData.getSummary();
10493
- logger23.info(sessionSummary, "GraphSession data after completion");
10499
+ logger22.info(sessionSummary, "GraphSession data after completion");
10494
10500
  }
10495
10501
  let textContent = "";
10496
10502
  for (const part of responseParts) {
@@ -10522,8 +10528,7 @@ var ExecutionHandler = class {
10522
10528
  },
10523
10529
  visibility: "user-facing",
10524
10530
  messageType: "chat",
10525
- agentId: currentAgentId,
10526
- fromAgentId: currentAgentId,
10531
+ fromSubAgentId: currentAgentId,
10527
10532
  taskId: task.id
10528
10533
  });
10529
10534
  const updateTaskStart = Date.now();
@@ -10544,22 +10549,22 @@ var ExecutionHandler = class {
10544
10549
  }
10545
10550
  });
10546
10551
  const updateTaskEnd = Date.now();
10547
- logger23.info(
10552
+ logger22.info(
10548
10553
  { duration: updateTaskEnd - updateTaskStart },
10549
10554
  "Completed updateTask operation"
10550
10555
  );
10551
10556
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
10552
10557
  await sseHelper.complete();
10553
- logger23.info({}, "Ending GraphSession and cleaning up");
10558
+ logger22.info({}, "Ending GraphSession and cleaning up");
10554
10559
  graphSessionManager.endSession(requestId2);
10555
- logger23.info({}, "Cleaning up streamHelper");
10560
+ logger22.info({}, "Cleaning up streamHelper");
10556
10561
  unregisterStreamHelper(requestId2);
10557
10562
  let response;
10558
10563
  if (sseHelper instanceof MCPStreamHelper) {
10559
10564
  const captured = sseHelper.getCapturedResponse();
10560
10565
  response = captured.text || "No response content";
10561
10566
  }
10562
- logger23.info({}, "ExecutionHandler returning success");
10567
+ logger22.info({}, "ExecutionHandler returning success");
10563
10568
  return { success: true, iterations, response };
10564
10569
  } catch (error) {
10565
10570
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -10570,13 +10575,13 @@ var ExecutionHandler = class {
10570
10575
  });
10571
10576
  }
10572
10577
  errorCount++;
10573
- logger23.warn(
10578
+ logger22.warn(
10574
10579
  { iterations, errorCount },
10575
10580
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
10576
10581
  );
10577
10582
  if (errorCount >= this.MAX_ERRORS) {
10578
10583
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
10579
- logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10584
+ logger22.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10580
10585
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
10581
10586
  if (task) {
10582
10587
  await agentsCore.updateTask(dbClient_default)({
@@ -10597,7 +10602,7 @@ var ExecutionHandler = class {
10597
10602
  }
10598
10603
  }
10599
10604
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
10600
- logger23.error({ maxTransfers, iterations }, errorMessage);
10605
+ logger22.error({ maxTransfers, iterations }, errorMessage);
10601
10606
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
10602
10607
  if (task) {
10603
10608
  await agentsCore.updateTask(dbClient_default)({
@@ -10616,7 +10621,7 @@ var ExecutionHandler = class {
10616
10621
  unregisterStreamHelper(requestId2);
10617
10622
  return { success: false, error: errorMessage, iterations };
10618
10623
  } catch (error) {
10619
- logger23.error({ error }, "Error in execution handler");
10624
+ logger22.error({ error }, "Error in execution handler");
10620
10625
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
10621
10626
  await sseHelper.writeOperation(
10622
10627
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -10644,7 +10649,7 @@ var ExecutionHandler = class {
10644
10649
  // src/routes/chat.ts
10645
10650
  init_logger();
10646
10651
  var app2 = new zodOpenapi.OpenAPIHono();
10647
- var logger24 = agentsCore.getLogger("completionsHandler");
10652
+ var logger23 = agentsCore.getLogger("completionsHandler");
10648
10653
  var chatCompletionsRoute = zodOpenapi.createRoute({
10649
10654
  method: "post",
10650
10655
  path: "/completions",
@@ -10762,7 +10767,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10762
10767
  tracestate: c.req.header("tracestate"),
10763
10768
  baggage: c.req.header("baggage")
10764
10769
  };
10765
- logger24.info(
10770
+ logger23.info(
10766
10771
  {
10767
10772
  otelHeaders,
10768
10773
  path: c.req.path,
@@ -10786,20 +10791,20 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10786
10791
  scopes: { tenantId, projectId, graphId }
10787
10792
  });
10788
10793
  let agentGraph;
10789
- let defaultAgentId;
10794
+ let defaultSubAgentId;
10790
10795
  if (fullGraph) {
10791
10796
  agentGraph = {
10792
10797
  id: fullGraph.id,
10793
10798
  name: fullGraph.name,
10794
10799
  tenantId,
10795
10800
  projectId,
10796
- defaultAgentId: fullGraph.defaultAgentId
10801
+ defaultSubAgentId: fullGraph.defaultSubAgentId
10797
10802
  };
10798
- const agentKeys = Object.keys(fullGraph.agents || {});
10803
+ const agentKeys = Object.keys(fullGraph.subAgents || {});
10799
10804
  const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
10800
- defaultAgentId = fullGraph.defaultAgentId || firstAgentId;
10805
+ defaultSubAgentId = fullGraph.defaultSubAgentId || firstAgentId;
10801
10806
  } else {
10802
- agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
10807
+ agentGraph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
10803
10808
  scopes: { tenantId, projectId, graphId }
10804
10809
  });
10805
10810
  if (!agentGraph) {
@@ -10808,9 +10813,9 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10808
10813
  message: "Agent graph not found"
10809
10814
  });
10810
10815
  }
10811
- defaultAgentId = agentGraph.defaultAgentId || "";
10816
+ defaultSubAgentId = agentGraph.defaultSubAgentId || "";
10812
10817
  }
10813
- if (!defaultAgentId) {
10818
+ if (!defaultSubAgentId) {
10814
10819
  throw agentsCore.createApiError({
10815
10820
  code: "not_found",
10816
10821
  message: "No default agent found in graph"
@@ -10820,7 +10825,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10820
10825
  tenantId,
10821
10826
  projectId,
10822
10827
  id: conversationId,
10823
- activeAgentId: defaultAgentId
10828
+ activeSubAgentId: defaultSubAgentId
10824
10829
  });
10825
10830
  const activeAgent = await agentsCore.getActiveAgentForConversation(dbClient_default)({
10826
10831
  scopes: { tenantId, projectId },
@@ -10830,13 +10835,13 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10830
10835
  agentsCore.setActiveAgentForConversation(dbClient_default)({
10831
10836
  scopes: { tenantId, projectId },
10832
10837
  conversationId,
10833
- agentId: defaultAgentId
10838
+ subAgentId: defaultSubAgentId
10834
10839
  });
10835
10840
  }
10836
- const agentId = activeAgent?.activeAgentId || defaultAgentId;
10837
- const agentInfo = await agentsCore.getAgentById(dbClient_default)({
10841
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
10842
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
10838
10843
  scopes: { tenantId, projectId, graphId },
10839
- agentId
10844
+ subAgentId
10840
10845
  });
10841
10846
  if (!agentInfo) {
10842
10847
  throw agentsCore.createApiError({
@@ -10855,14 +10860,14 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10855
10860
  dbClient: dbClient_default,
10856
10861
  credentialStores
10857
10862
  });
10858
- logger24.info(
10863
+ logger23.info(
10859
10864
  {
10860
10865
  tenantId,
10861
10866
  projectId,
10862
10867
  graphId,
10863
10868
  conversationId,
10864
- defaultAgentId,
10865
- activeAgentId: activeAgent?.activeAgentId || "none",
10869
+ defaultSubAgentId,
10870
+ activeSubAgentId: activeAgent?.activeSubAgentId || "none",
10866
10871
  hasContextConfig: !!agentGraph.contextConfigId,
10867
10872
  hasHeaders: !!body.headers,
10868
10873
  hasValidatedContext: !!validatedContext,
@@ -10903,7 +10908,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10903
10908
  try {
10904
10909
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
10905
10910
  await sseHelper.writeRole();
10906
- logger24.info({ agentId }, "Starting execution");
10911
+ logger23.info({ subAgentId }, "Starting execution");
10907
10912
  const emitOperationsHeader = c.req.header("x-emit-operations");
10908
10913
  const emitOperations = emitOperationsHeader === "true";
10909
10914
  const executionHandler = new ExecutionHandler();
@@ -10911,12 +10916,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10911
10916
  executionContext,
10912
10917
  conversationId,
10913
10918
  userMessage,
10914
- initialAgentId: agentId,
10919
+ initialAgentId: subAgentId,
10915
10920
  requestId: requestId2,
10916
10921
  sseHelper,
10917
10922
  emitOperations
10918
10923
  });
10919
- logger24.info(
10924
+ logger23.info(
10920
10925
  { result },
10921
10926
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10922
10927
  );
@@ -10930,7 +10935,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10930
10935
  }
10931
10936
  await sseHelper.complete();
10932
10937
  } catch (error) {
10933
- logger24.error(
10938
+ logger23.error(
10934
10939
  {
10935
10940
  error: error instanceof Error ? error.message : error,
10936
10941
  stack: error instanceof Error ? error.stack : void 0
@@ -10947,12 +10952,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10947
10952
  );
10948
10953
  await sseHelper.complete();
10949
10954
  } catch (streamError) {
10950
- logger24.error({ streamError }, "Failed to write error to stream");
10955
+ logger23.error({ streamError }, "Failed to write error to stream");
10951
10956
  }
10952
10957
  }
10953
10958
  });
10954
10959
  } catch (error) {
10955
- logger24.error(
10960
+ logger23.error(
10956
10961
  {
10957
10962
  error: error instanceof Error ? error.message : error,
10958
10963
  stack: error instanceof Error ? error.stack : void 0
@@ -10980,7 +10985,7 @@ var chat_default = app2;
10980
10985
  init_dbClient();
10981
10986
  init_logger();
10982
10987
  var app3 = new zodOpenapi.OpenAPIHono();
10983
- var logger25 = agentsCore.getLogger("chatDataStream");
10988
+ var logger24 = agentsCore.getLogger("chatDataStream");
10984
10989
  var chatDataStreamRoute = zodOpenapi.createRoute({
10985
10990
  method: "post",
10986
10991
  path: "/chat",
@@ -11045,7 +11050,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11045
11050
  "project.id": projectId
11046
11051
  });
11047
11052
  }
11048
- const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
11053
+ const agentGraph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
11049
11054
  scopes: { tenantId, projectId, graphId }
11050
11055
  });
11051
11056
  if (!agentGraph) {
@@ -11054,9 +11059,9 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11054
11059
  message: "Agent graph not found"
11055
11060
  });
11056
11061
  }
11057
- const defaultAgentId = agentGraph.defaultAgentId;
11062
+ const defaultSubAgentId = agentGraph.defaultSubAgentId;
11058
11063
  const graphName = agentGraph.name;
11059
- if (!defaultAgentId) {
11064
+ if (!defaultSubAgentId) {
11060
11065
  throw agentsCore.createApiError({
11061
11066
  code: "bad_request",
11062
11067
  message: "Graph does not have a default agent configured"
@@ -11070,13 +11075,13 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11070
11075
  agentsCore.setActiveAgentForConversation(dbClient_default)({
11071
11076
  scopes: { tenantId, projectId },
11072
11077
  conversationId,
11073
- agentId: defaultAgentId
11078
+ subAgentId: defaultSubAgentId
11074
11079
  });
11075
11080
  }
11076
- const agentId = activeAgent?.activeAgentId || defaultAgentId;
11077
- const agentInfo = await agentsCore.getAgentById(dbClient_default)({
11081
+ const subAgentId = activeAgent?.activeSubAgentId || defaultSubAgentId;
11082
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11078
11083
  scopes: { tenantId, projectId, graphId },
11079
- agentId
11084
+ subAgentId
11080
11085
  });
11081
11086
  if (!agentInfo) {
11082
11087
  throw agentsCore.createApiError({
@@ -11097,7 +11102,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11097
11102
  });
11098
11103
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
11099
11104
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
11100
- logger25.info({ userText, lastUserMessage }, "userText");
11105
+ logger24.info({ userText, lastUserMessage }, "userText");
11101
11106
  const messageSpan = api.trace.getActiveSpan();
11102
11107
  if (messageSpan) {
11103
11108
  messageSpan.setAttributes({
@@ -11133,7 +11138,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11133
11138
  executionContext,
11134
11139
  conversationId,
11135
11140
  userMessage: userText,
11136
- initialAgentId: agentId,
11141
+ initialAgentId: subAgentId,
11137
11142
  requestId: `chatds-${Date.now()}`,
11138
11143
  sseHelper: streamHelper,
11139
11144
  emitOperations
@@ -11142,7 +11147,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11142
11147
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
11143
11148
  }
11144
11149
  } catch (err) {
11145
- logger25.error({ err }, "Streaming error");
11150
+ logger24.error({ err }, "Streaming error");
11146
11151
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
11147
11152
  } finally {
11148
11153
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -11163,7 +11168,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11163
11168
  )
11164
11169
  );
11165
11170
  } catch (error) {
11166
- logger25.error({ error }, "chatDataStream error");
11171
+ logger24.error({ error }, "chatDataStream error");
11167
11172
  throw agentsCore.createApiError({
11168
11173
  code: "internal_server_error",
11169
11174
  message: "Failed to process chat completion"
@@ -11178,7 +11183,7 @@ init_logger();
11178
11183
  function createMCPSchema(schema) {
11179
11184
  return schema;
11180
11185
  }
11181
- var logger26 = agentsCore.getLogger("mcp");
11186
+ var logger25 = agentsCore.getLogger("mcp");
11182
11187
  var _MockResponseSingleton = class _MockResponseSingleton {
11183
11188
  constructor() {
11184
11189
  __publicField(this, "mockRes");
@@ -11233,21 +11238,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
11233
11238
  id: 0
11234
11239
  });
11235
11240
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
11236
- logger26.info({ sessionId }, "Spoofing initialization message to set transport state");
11241
+ logger25.info({ sessionId }, "Spoofing initialization message to set transport state");
11237
11242
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
11238
11243
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
11239
11244
  try {
11240
11245
  await transport.handleRequest(req, mockRes, spoofInitMessage);
11241
- logger26.info({ sessionId }, "Successfully spoofed initialization");
11246
+ logger25.info({ sessionId }, "Successfully spoofed initialization");
11242
11247
  } catch (spoofError) {
11243
- logger26.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11248
+ logger25.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11244
11249
  }
11245
11250
  };
11246
11251
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
11247
11252
  const sessionId = req.headers["mcp-session-id"];
11248
- logger26.info({ sessionId }, "Received MCP session ID");
11253
+ logger25.info({ sessionId }, "Received MCP session ID");
11249
11254
  if (!sessionId) {
11250
- logger26.info({ body }, "Missing session ID");
11255
+ logger25.info({ body }, "Missing session ID");
11251
11256
  res.writeHead(400).end(
11252
11257
  JSON.stringify({
11253
11258
  jsonrpc: "2.0",
@@ -11273,7 +11278,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
11273
11278
  scopes: { tenantId, projectId },
11274
11279
  conversationId: sessionId
11275
11280
  });
11276
- logger26.info(
11281
+ logger25.info(
11277
11282
  {
11278
11283
  sessionId,
11279
11284
  conversationFound: !!conversation,
@@ -11284,7 +11289,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
11284
11289
  "Conversation lookup result"
11285
11290
  );
11286
11291
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
11287
- logger26.info(
11292
+ logger25.info(
11288
11293
  { sessionId, conversationId: conversation?.id },
11289
11294
  "MCP session not found or invalid"
11290
11295
  );
@@ -11333,7 +11338,7 @@ var processUserMessage = async (tenantId, projectId, conversationId, query) => {
11333
11338
  messageType: "chat"
11334
11339
  });
11335
11340
  };
11336
- var executeAgentQuery = async (executionContext, conversationId, query, defaultAgentId) => {
11341
+ var executeAgentQuery = async (executionContext, conversationId, query, defaultSubAgentId) => {
11337
11342
  const requestId2 = `mcp-${Date.now()}`;
11338
11343
  const mcpStreamHelper = createMCPStreamHelper();
11339
11344
  const executionHandler = new ExecutionHandler();
@@ -11341,11 +11346,11 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
11341
11346
  executionContext,
11342
11347
  conversationId,
11343
11348
  userMessage: query,
11344
- initialAgentId: defaultAgentId,
11349
+ initialAgentId: defaultSubAgentId,
11345
11350
  requestId: requestId2,
11346
11351
  sseHelper: mcpStreamHelper
11347
11352
  });
11348
- logger26.info(
11353
+ logger25.info(
11349
11354
  { result },
11350
11355
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11351
11356
  );
@@ -11372,7 +11377,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
11372
11377
  var getServer = async (headers, executionContext, conversationId, credentialStores) => {
11373
11378
  const { tenantId, projectId, graphId } = executionContext;
11374
11379
  setupTracing(conversationId, tenantId, graphId);
11375
- const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
11380
+ const agentGraph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
11376
11381
  scopes: { tenantId, projectId, graphId }
11377
11382
  });
11378
11383
  if (!agentGraph) {
@@ -11393,7 +11398,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11393
11398
  },
11394
11399
  async ({ query }) => {
11395
11400
  try {
11396
- if (!agentGraph.defaultAgentId) {
11401
+ if (!agentGraph.defaultSubAgentId) {
11397
11402
  return {
11398
11403
  content: [
11399
11404
  {
@@ -11404,10 +11409,10 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11404
11409
  isError: true
11405
11410
  };
11406
11411
  }
11407
- const defaultAgentId = agentGraph.defaultAgentId;
11408
- const agentInfo = await agentsCore.getAgentById(dbClient_default)({
11412
+ const defaultSubAgentId = agentGraph.defaultSubAgentId;
11413
+ const agentInfo = await agentsCore.getSubAgentById(dbClient_default)({
11409
11414
  scopes: { tenantId, projectId, graphId },
11410
- agentId: defaultAgentId
11415
+ subAgentId: defaultSubAgentId
11411
11416
  });
11412
11417
  if (!agentInfo) {
11413
11418
  return {
@@ -11429,7 +11434,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11429
11434
  dbClient: dbClient_default,
11430
11435
  credentialStores
11431
11436
  });
11432
- logger26.info(
11437
+ logger25.info(
11433
11438
  {
11434
11439
  tenantId,
11435
11440
  projectId,
@@ -11442,7 +11447,7 @@ var getServer = async (headers, executionContext, conversationId, credentialStor
11442
11447
  "parameters"
11443
11448
  );
11444
11449
  await processUserMessage(tenantId, projectId, conversationId, query);
11445
- return executeAgentQuery(executionContext, conversationId, query, defaultAgentId);
11450
+ return executeAgentQuery(executionContext, conversationId, query, defaultSubAgentId);
11446
11451
  } catch (error) {
11447
11452
  return {
11448
11453
  content: [
@@ -11491,9 +11496,9 @@ var validateRequestParameters = (c) => {
11491
11496
  };
11492
11497
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
11493
11498
  const { tenantId, projectId, graphId } = executionContext;
11494
- logger26.info({ body }, "Received initialization request");
11499
+ logger25.info({ body }, "Received initialization request");
11495
11500
  const sessionId = agentsCore.getConversationId();
11496
- const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
11501
+ const agentGraph = await agentsCore.getAgentGraphWithDefaultSubAgent(dbClient_default)({
11497
11502
  scopes: { tenantId, projectId, graphId }
11498
11503
  });
11499
11504
  if (!agentGraph) {
@@ -11506,7 +11511,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11506
11511
  { status: 404 }
11507
11512
  );
11508
11513
  }
11509
- if (!agentGraph.defaultAgentId) {
11514
+ if (!agentGraph.defaultSubAgentId) {
11510
11515
  return c.json(
11511
11516
  {
11512
11517
  jsonrpc: "2.0",
@@ -11520,7 +11525,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11520
11525
  id: sessionId,
11521
11526
  tenantId,
11522
11527
  projectId,
11523
- activeAgentId: agentGraph.defaultAgentId,
11528
+ activeSubAgentId: agentGraph.defaultSubAgentId,
11524
11529
  metadata: {
11525
11530
  sessionData: {
11526
11531
  graphId,
@@ -11531,7 +11536,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11531
11536
  }
11532
11537
  }
11533
11538
  });
11534
- logger26.info(
11539
+ logger25.info(
11535
11540
  { sessionId, conversationId: conversation.id },
11536
11541
  "Created MCP session as conversation"
11537
11542
  );
@@ -11540,9 +11545,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11540
11545
  });
11541
11546
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
11542
11547
  await server.connect(transport);
11543
- logger26.info({ sessionId }, "Server connected for initialization");
11548
+ logger25.info({ sessionId }, "Server connected for initialization");
11544
11549
  res.setHeader("Mcp-Session-Id", sessionId);
11545
- logger26.info(
11550
+ logger25.info(
11546
11551
  {
11547
11552
  sessionId,
11548
11553
  bodyMethod: body?.method,
@@ -11551,7 +11556,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
11551
11556
  "About to handle initialization request"
11552
11557
  );
11553
11558
  await transport.handleRequest(req, res, body);
11554
- logger26.info({ sessionId }, "Successfully handled initialization request");
11559
+ logger25.info({ sessionId }, "Successfully handled initialization request");
11555
11560
  return fetchToNode.toFetchResponse(res);
11556
11561
  };
11557
11562
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -11579,8 +11584,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
11579
11584
  sessionId,
11580
11585
  conversation.metadata?.session_data?.mcpProtocolVersion
11581
11586
  );
11582
- logger26.info({ sessionId }, "Server connected and transport initialized");
11583
- logger26.info(
11587
+ logger25.info({ sessionId }, "Server connected and transport initialized");
11588
+ logger25.info(
11584
11589
  {
11585
11590
  sessionId,
11586
11591
  bodyKeys: Object.keys(body || {}),
@@ -11594,9 +11599,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
11594
11599
  );
11595
11600
  try {
11596
11601
  await transport.handleRequest(req, res, body);
11597
- logger26.info({ sessionId }, "Successfully handled MCP request");
11602
+ logger25.info({ sessionId }, "Successfully handled MCP request");
11598
11603
  } catch (transportError) {
11599
- logger26.error(
11604
+ logger25.error(
11600
11605
  {
11601
11606
  sessionId,
11602
11607
  error: transportError,
@@ -11647,13 +11652,13 @@ app4.openapi(
11647
11652
  }
11648
11653
  const { executionContext } = paramValidation;
11649
11654
  const body = c.get("requestBody") || {};
11650
- logger26.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
11655
+ logger25.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
11651
11656
  const isInitRequest = body.method === "initialize";
11652
11657
  const { req, res } = fetchToNode.toReqRes(c.req.raw);
11653
11658
  const validatedContext = c.get("validatedContext") || {};
11654
11659
  const credentialStores = c.get("credentialStores");
11655
- logger26.info({ validatedContext }, "Validated context");
11656
- logger26.info({ req }, "request");
11660
+ logger25.info({ validatedContext }, "Validated context");
11661
+ logger25.info({ req }, "request");
11657
11662
  if (isInitRequest) {
11658
11663
  return await handleInitializationRequest(
11659
11664
  body,
@@ -11675,7 +11680,7 @@ app4.openapi(
11675
11680
  );
11676
11681
  }
11677
11682
  } catch (e) {
11678
- logger26.error(
11683
+ logger25.error(
11679
11684
  {
11680
11685
  error: e instanceof Error ? e.message : e,
11681
11686
  stack: e instanceof Error ? e.stack : void 0
@@ -11687,7 +11692,7 @@ app4.openapi(
11687
11692
  }
11688
11693
  );
11689
11694
  app4.get("/", async (c) => {
11690
- logger26.info({}, "Received GET MCP request");
11695
+ logger25.info({}, "Received GET MCP request");
11691
11696
  return c.json(
11692
11697
  {
11693
11698
  jsonrpc: "2.0",
@@ -11701,7 +11706,7 @@ app4.get("/", async (c) => {
11701
11706
  );
11702
11707
  });
11703
11708
  app4.delete("/", async (c) => {
11704
- logger26.info({}, "Received DELETE MCP request");
11709
+ logger25.info({}, "Received DELETE MCP request");
11705
11710
  return c.json(
11706
11711
  {
11707
11712
  jsonrpc: "2.0",
@@ -11714,7 +11719,7 @@ app4.delete("/", async (c) => {
11714
11719
  var mcp_default = app4;
11715
11720
 
11716
11721
  // src/app.ts
11717
- var logger27 = agentsCore.getLogger("agents-run-api");
11722
+ var logger26 = agentsCore.getLogger("agents-run-api");
11718
11723
  function createExecutionHono(serverConfig, credentialStores) {
11719
11724
  const app6 = new zodOpenapi.OpenAPIHono();
11720
11725
  app6.use("*", otel.otel());
@@ -11730,7 +11735,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11730
11735
  const body = await c.req.json();
11731
11736
  c.set("requestBody", body);
11732
11737
  } catch (error) {
11733
- logger27.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
11738
+ logger26.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
11734
11739
  }
11735
11740
  }
11736
11741
  return next();
@@ -11781,8 +11786,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11781
11786
  if (!isExpectedError) {
11782
11787
  const errorMessage = err instanceof Error ? err.message : String(err);
11783
11788
  const errorStack = err instanceof Error ? err.stack : void 0;
11784
- if (logger27) {
11785
- logger27.error(
11789
+ if (logger26) {
11790
+ logger26.error(
11786
11791
  {
11787
11792
  error: err,
11788
11793
  message: errorMessage,
@@ -11794,8 +11799,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11794
11799
  );
11795
11800
  }
11796
11801
  } else {
11797
- if (logger27) {
11798
- logger27.error(
11802
+ if (logger26) {
11803
+ logger26.error(
11799
11804
  {
11800
11805
  error: err,
11801
11806
  path: c.req.path,
@@ -11812,8 +11817,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11812
11817
  const response = err.getResponse();
11813
11818
  return response;
11814
11819
  } catch (responseError) {
11815
- if (logger27) {
11816
- logger27.error({ error: responseError }, "Error while handling HTTPException response");
11820
+ if (logger26) {
11821
+ logger26.error({ error: responseError }, "Error while handling HTTPException response");
11817
11822
  }
11818
11823
  }
11819
11824
  }
@@ -11847,7 +11852,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11847
11852
  app6.use("*", async (c, next) => {
11848
11853
  const executionContext = c.get("executionContext");
11849
11854
  if (!executionContext) {
11850
- logger27.debug({}, "Empty execution context");
11855
+ logger26.debug({}, "Empty execution context");
11851
11856
  return next();
11852
11857
  }
11853
11858
  const { tenantId, projectId, graphId } = executionContext;
@@ -11856,7 +11861,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11856
11861
  if (requestBody) {
11857
11862
  conversationId = requestBody.conversationId;
11858
11863
  if (!conversationId) {
11859
- logger27.debug({ requestBody }, "No conversation ID found in request body");
11864
+ logger26.debug({ requestBody }, "No conversation ID found in request body");
11860
11865
  }
11861
11866
  }
11862
11867
  const entries = Object.fromEntries(
@@ -11871,7 +11876,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11871
11876
  })
11872
11877
  );
11873
11878
  if (!Object.keys(entries).length) {
11874
- logger27.debug({}, "Empty entries for baggage");
11879
+ logger26.debug({}, "Empty entries for baggage");
11875
11880
  return next();
11876
11881
  }
11877
11882
  const bag = Object.entries(entries).reduce(