@inkeep/agents-run-api 0.24.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,5 @@
1
1
  import { dbClient_default } from './chunk-IBMWBEXH.js';
2
- import { createMessage, getConversationHistory } from '@inkeep/agents-core';
3
- import { nanoid } from 'nanoid';
2
+ import { createMessage, generateId, getConversationHistory } from '@inkeep/agents-core';
4
3
 
5
4
  function createDefaultConversationHistoryConfig(mode = "full") {
6
5
  return {
@@ -35,7 +34,7 @@ async function saveA2AMessageResponse(response, params) {
35
34
  return null;
36
35
  }
37
36
  return await createMessage(dbClient_default)({
38
- id: nanoid(),
37
+ id: generateId(),
39
38
  tenantId: params.tenantId,
40
39
  projectId: params.projectId,
41
40
  conversationId: params.conversationId,
@@ -1 +1 @@
1
- export { createDefaultConversationHistoryConfig, getConversationScopedArtifacts, getFormattedConversationHistory, getFullConversationContext, getScopedHistory, getUserFacingHistory, saveA2AMessageResponse } from './chunk-T5AYIGCU.js';
1
+ export { createDefaultConversationHistoryConfig, getConversationScopedArtifacts, getFormattedConversationHistory, getFullConversationContext, getScopedHistory, getUserFacingHistory, saveA2AMessageResponse } from './chunk-XLUE6U2L.js';
package/dist/index.cjs CHANGED
@@ -4,7 +4,6 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var agentsCore = require('@inkeep/agents-core');
6
6
  var z6 = require('zod');
7
- var nanoid = require('nanoid');
8
7
  var child_process = require('child_process');
9
8
  var crypto = require('crypto');
10
9
  var fs = require('fs');
@@ -192,7 +191,7 @@ async function saveA2AMessageResponse(response, params) {
192
191
  return null;
193
192
  }
194
193
  return await agentsCore.createMessage(dbClient_default)({
195
- id: nanoid.nanoid(),
194
+ id: agentsCore.generateId(),
196
195
  tenantId: params.tenantId,
197
196
  projectId: params.projectId,
198
197
  conversationId: params.conversationId,
@@ -1486,7 +1485,9 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
1486
1485
  if (authHeader?.startsWith("Bearer ")) {
1487
1486
  try {
1488
1487
  executionContext = await extractContextFromApiKey(authHeader.substring(7), baseUrl);
1489
- executionContext.subAgentId = subAgentId;
1488
+ if (subAgentId) {
1489
+ executionContext.subAgentId = subAgentId;
1490
+ }
1490
1491
  logger2.info({}, "Development/test environment - API key authenticated successfully");
1491
1492
  } catch {
1492
1493
  executionContext = createExecutionContext({
@@ -1550,7 +1551,9 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
1550
1551
  return;
1551
1552
  } else if (apiKey) {
1552
1553
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
1553
- executionContext.subAgentId = subAgentId;
1554
+ if (subAgentId) {
1555
+ executionContext.subAgentId = subAgentId;
1556
+ }
1554
1557
  c.set("executionContext", executionContext);
1555
1558
  logger2.info({}, "API key authenticated successfully");
1556
1559
  await next();
@@ -1568,7 +1571,9 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
1568
1571
  }
1569
1572
  try {
1570
1573
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
1571
- executionContext.subAgentId = subAgentId;
1574
+ if (subAgentId) {
1575
+ executionContext.subAgentId = subAgentId;
1576
+ }
1572
1577
  c.set("executionContext", executionContext);
1573
1578
  logger2.debug(
1574
1579
  {
@@ -1597,13 +1602,28 @@ var extractContextFromApiKey = async (apiKey, baseUrl) => {
1597
1602
  message: "Invalid or expired API key"
1598
1603
  });
1599
1604
  }
1605
+ const agent = await agentsCore.getAgentById(dbClient_default)({
1606
+ scopes: {
1607
+ tenantId: apiKeyRecord.tenantId,
1608
+ projectId: apiKeyRecord.projectId,
1609
+ agentId: apiKeyRecord.agentId
1610
+ }
1611
+ });
1612
+ if (!agent) {
1613
+ throw new httpException.HTTPException(401, {
1614
+ message: "Invalid or expired API key"
1615
+ });
1616
+ }
1617
+ logger2.info({ agent }, "agent");
1618
+ logger2.info({ defaultSubAgentId: agent.defaultSubAgentId }, "agent.defaultSubAgentId");
1600
1619
  return createExecutionContext({
1601
1620
  apiKey,
1602
1621
  tenantId: apiKeyRecord.tenantId,
1603
1622
  projectId: apiKeyRecord.projectId,
1604
1623
  agentId: apiKeyRecord.agentId,
1605
1624
  apiKeyId: apiKeyRecord.id,
1606
- baseUrl
1625
+ baseUrl,
1626
+ subAgentId: agent.defaultSubAgentId || void 0
1607
1627
  });
1608
1628
  };
1609
1629
 
@@ -1704,7 +1724,7 @@ async function handleMessageSend(c, agent, request) {
1704
1724
  const executionContext = agentsCore.getRequestExecutionContext(c);
1705
1725
  const { agentId } = executionContext;
1706
1726
  const task = {
1707
- id: nanoid.nanoid(),
1727
+ id: agentsCore.generateId(),
1708
1728
  input: {
1709
1729
  parts: params.message.parts.map((part) => ({
1710
1730
  kind: part.kind,
@@ -1797,7 +1817,7 @@ async function handleMessageSend(c, agent, request) {
1797
1817
  const messageText = params.message.parts.filter((part) => part.kind === "text" && "text" in part && part.text).map((part) => part.text).join(" ");
1798
1818
  try {
1799
1819
  const messageData = {
1800
- id: nanoid.nanoid(),
1820
+ id: agentsCore.generateId(),
1801
1821
  tenantId: agent.tenantId,
1802
1822
  projectId: agent.projectId,
1803
1823
  conversationId: effectiveContextId,
@@ -1879,7 +1899,7 @@ async function handleMessageSend(c, agent, request) {
1879
1899
  },
1880
1900
  artifacts: [
1881
1901
  {
1882
- artifactId: nanoid.nanoid(),
1902
+ artifactId: agentsCore.generateId(),
1883
1903
  parts: [
1884
1904
  {
1885
1905
  kind: "data",
@@ -1908,7 +1928,7 @@ async function handleMessageSend(c, agent, request) {
1908
1928
  if (params.configuration?.blocking === false) {
1909
1929
  const taskResponse = {
1910
1930
  id: task.id,
1911
- contextId: params.message.contextId || nanoid.nanoid(),
1931
+ contextId: params.message.contextId || agentsCore.generateId(),
1912
1932
  status: taskStatus,
1913
1933
  artifacts: result.artifacts,
1914
1934
  kind: "task"
@@ -1920,7 +1940,7 @@ async function handleMessageSend(c, agent, request) {
1920
1940
  });
1921
1941
  }
1922
1942
  const messageResponse = {
1923
- messageId: nanoid.nanoid(),
1943
+ messageId: agentsCore.generateId(),
1924
1944
  parts: result.artifacts?.[0]?.parts || [
1925
1945
  {
1926
1946
  kind: "text",
@@ -1965,7 +1985,7 @@ async function handleMessageStream(c, agent, request) {
1965
1985
  });
1966
1986
  }
1967
1987
  const task = {
1968
- id: nanoid.nanoid(),
1988
+ id: agentsCore.generateId(),
1969
1989
  input: {
1970
1990
  parts: params.message.parts.map((part) => ({
1971
1991
  kind: part.kind,
@@ -1986,7 +2006,7 @@ async function handleMessageStream(c, agent, request) {
1986
2006
  try {
1987
2007
  const initialTask = {
1988
2008
  id: task.id,
1989
- contextId: params.message.contextId || nanoid.nanoid(),
2009
+ contextId: params.message.contextId || agentsCore.generateId(),
1990
2010
  status: {
1991
2011
  state: agentsCore.TaskState.Working,
1992
2012
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -2034,7 +2054,7 @@ async function handleMessageStream(c, agent, request) {
2034
2054
  }
2035
2055
  }
2036
2056
  const messageResponse = {
2037
- messageId: nanoid.nanoid(),
2057
+ messageId: agentsCore.generateId(),
2038
2058
  parts: result.artifacts?.[0]?.parts || [
2039
2059
  {
2040
2060
  kind: "text",
@@ -2100,14 +2120,14 @@ async function handleTasksGet(c, _agent, request) {
2100
2120
  const params = request.params;
2101
2121
  const task = {
2102
2122
  id: params.id,
2103
- contextId: nanoid.nanoid(),
2123
+ contextId: agentsCore.generateId(),
2104
2124
  status: {
2105
2125
  state: agentsCore.TaskState.Completed,
2106
2126
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2107
2127
  },
2108
2128
  artifacts: [
2109
2129
  {
2110
- artifactId: nanoid.nanoid(),
2130
+ artifactId: agentsCore.generateId(),
2111
2131
  parts: [
2112
2132
  {
2113
2133
  kind: "text",
@@ -2206,7 +2226,7 @@ async function handleTasksResubscribe(c, agent, request) {
2206
2226
  try {
2207
2227
  const task = {
2208
2228
  id: params.taskId,
2209
- contextId: nanoid.nanoid(),
2229
+ contextId: agentsCore.generateId(),
2210
2230
  status: {
2211
2231
  state: agentsCore.TaskState.Completed,
2212
2232
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -2463,7 +2483,7 @@ var _ToolSessionManager = class _ToolSessionManager {
2463
2483
  * Create a new tool session for an agent execution
2464
2484
  */
2465
2485
  createSession(tenantId, projectId, contextId, taskId) {
2466
- const sessionId = nanoid.nanoid();
2486
+ const sessionId = agentsCore.generateId();
2467
2487
  return this.createSessionWithId(sessionId, tenantId, projectId, contextId, taskId);
2468
2488
  }
2469
2489
  /**
@@ -5562,7 +5582,7 @@ function errorOp(message, subAgentId, severity = "error", code) {
5562
5582
  };
5563
5583
  }
5564
5584
  function generateToolId() {
5565
- return `tool_${nanoid.nanoid(8)}`;
5585
+ return `tool_${agentsCore.generateId(8)}`;
5566
5586
  }
5567
5587
 
5568
5588
  // src/utils/artifact-component-schema.ts
@@ -6672,7 +6692,7 @@ function createDelegateToAgentTool({
6672
6692
  description: generateDelegateToolDescription(delegateConfig.config),
6673
6693
  inputSchema: z6__default.default.object({ message: z6__default.default.string() }),
6674
6694
  execute: async (input, context) => {
6675
- const delegationId = `del_${nanoid.nanoid()}`;
6695
+ const delegationId = `del_${agentsCore.generateId()}`;
6676
6696
  const activeSpan = api.trace.getActiveSpan();
6677
6697
  if (activeSpan) {
6678
6698
  activeSpan.setAttributes({
@@ -6697,15 +6717,7 @@ function createDelegateToAgentTool({
6697
6717
  const isInternal = delegateConfig.type === "internal";
6698
6718
  let resolvedHeaders = {};
6699
6719
  if (!isInternal) {
6700
- const externalAgent = await agentsCore.getExternalAgent(dbClient_default)({
6701
- scopes: {
6702
- tenantId,
6703
- projectId,
6704
- agentId
6705
- },
6706
- subAgentId: delegateConfig.config.id
6707
- });
6708
- if (externalAgent && (externalAgent.credentialReferenceId || externalAgent.headers) && credentialStoreRegistry) {
6720
+ if ((delegateConfig.config.credentialReferenceId || delegateConfig.config.headers) && credentialStoreRegistry) {
6709
6721
  const contextResolver = new agentsCore.ContextResolver(
6710
6722
  tenantId,
6711
6723
  projectId,
@@ -6721,13 +6733,13 @@ function createDelegateToAgentTool({
6721
6733
  metadata
6722
6734
  };
6723
6735
  let storeReference;
6724
- if (externalAgent.credentialReferenceId) {
6736
+ if (delegateConfig.config.credentialReferenceId) {
6725
6737
  const credentialReference = await agentsCore.getCredentialReference(dbClient_default)({
6726
6738
  scopes: {
6727
6739
  tenantId,
6728
6740
  projectId
6729
6741
  },
6730
- id: externalAgent.credentialReferenceId
6742
+ id: delegateConfig.config.credentialReferenceId
6731
6743
  });
6732
6744
  if (credentialReference) {
6733
6745
  storeReference = {
@@ -6739,7 +6751,7 @@ function createDelegateToAgentTool({
6739
6751
  resolvedHeaders = await credentialStuffer.getCredentialHeaders({
6740
6752
  context: credentialContext,
6741
6753
  storeReference,
6742
- headers: externalAgent.headers || void 0
6754
+ headers: delegateConfig.config.headers || void 0
6743
6755
  });
6744
6756
  }
6745
6757
  } else {
@@ -6769,7 +6781,7 @@ function createDelegateToAgentTool({
6769
6781
  const messageToSend = {
6770
6782
  role: "agent",
6771
6783
  parts: [{ text: input.message, kind: "text" }],
6772
- messageId: nanoid.nanoid(),
6784
+ messageId: agentsCore.generateId(),
6773
6785
  kind: "message",
6774
6786
  contextId,
6775
6787
  metadata: {
@@ -6784,7 +6796,7 @@ function createDelegateToAgentTool({
6784
6796
  };
6785
6797
  logger14.info({ messageToSend }, "messageToSend");
6786
6798
  await agentsCore.createMessage(dbClient_default)({
6787
- id: nanoid.nanoid(),
6799
+ id: agentsCore.generateId(),
6788
6800
  tenantId,
6789
6801
  projectId,
6790
6802
  conversationId: contextId,
@@ -9728,7 +9740,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9728
9740
  };
9729
9741
  }
9730
9742
  const [
9731
- { internalRelations, externalRelations },
9743
+ internalRelations,
9744
+ externalRelations,
9732
9745
  toolsForAgent,
9733
9746
  dataComponents,
9734
9747
  artifactComponents
@@ -9741,6 +9754,14 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9741
9754
  },
9742
9755
  subAgentId: config.subAgentId
9743
9756
  }),
9757
+ agentsCore.getExternalAgentsForSubAgent(dbClient_default)({
9758
+ scopes: {
9759
+ tenantId: config.tenantId,
9760
+ projectId: config.projectId,
9761
+ agentId: config.agentId,
9762
+ subAgentId: config.subAgentId
9763
+ }
9764
+ }),
9744
9765
  agentsCore.getToolsForAgent(dbClient_default)({
9745
9766
  scopes: {
9746
9767
  tenantId: config.tenantId,
@@ -9768,7 +9789,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9768
9789
  ]);
9769
9790
  logger20.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9770
9791
  const enhancedInternalRelations = await Promise.all(
9771
- internalRelations.map(async (relation) => {
9792
+ internalRelations.data.map(async (relation) => {
9772
9793
  try {
9773
9794
  const relatedAgent = await agentsCore.getSubAgentById(dbClient_default)({
9774
9795
  scopes: {
@@ -9787,10 +9808,20 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9787
9808
  },
9788
9809
  subAgentId: relation.id
9789
9810
  });
9811
+ const relatedAgentExternalAgentRelations = await agentsCore.getExternalAgentsForSubAgent(
9812
+ dbClient_default
9813
+ )({
9814
+ scopes: {
9815
+ tenantId: config.tenantId,
9816
+ projectId: config.projectId,
9817
+ agentId: config.agentId,
9818
+ subAgentId: relation.id
9819
+ }
9820
+ });
9790
9821
  const enhancedDescription = generateDescriptionWithTransfers(
9791
9822
  relation.description || "",
9792
- relatedAgentRelations.internalRelations,
9793
- relatedAgentRelations.externalRelations
9823
+ relatedAgentRelations.data,
9824
+ relatedAgentExternalAgentRelations.data
9794
9825
  );
9795
9826
  return { ...relation, description: enhancedDescription };
9796
9827
  }
@@ -9867,14 +9898,17 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9867
9898
  transferRelations: []
9868
9899
  }
9869
9900
  })),
9870
- ...externalRelations.map((relation) => ({
9901
+ ...externalRelations.data.map((relation) => ({
9871
9902
  type: "external",
9872
9903
  config: {
9873
9904
  id: relation.externalAgent.id,
9874
9905
  name: relation.externalAgent.name,
9875
9906
  description: relation.externalAgent.description || "",
9876
9907
  baseUrl: relation.externalAgent.baseUrl,
9877
- relationType: relation.relationType || void 0
9908
+ headers: relation.headers,
9909
+ credentialReferenceId: relation.externalAgent.credentialReferenceId,
9910
+ relationId: relation.id,
9911
+ relationType: "delegate"
9878
9912
  }
9879
9913
  }))
9880
9914
  ],
@@ -9999,7 +10033,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9999
10033
  },
10000
10034
  artifacts: [
10001
10035
  {
10002
- artifactId: nanoid.nanoid(),
10036
+ artifactId: agentsCore.generateId(),
10003
10037
  parts: [
10004
10038
  {
10005
10039
  kind: "data",
@@ -10032,7 +10066,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
10032
10066
  status: { state: agentsCore.TaskState.Completed },
10033
10067
  artifacts: [
10034
10068
  {
10035
- artifactId: nanoid.nanoid(),
10069
+ artifactId: agentsCore.generateId(),
10036
10070
  parts
10037
10071
  }
10038
10072
  ]
@@ -10127,13 +10161,10 @@ function createAgentCard({
10127
10161
  };
10128
10162
  }
10129
10163
  function generateDescriptionWithTransfers(baseDescription, internalRelations, externalRelations) {
10130
- const transfers = [
10131
- ...internalRelations.filter((rel) => rel.relationType === "transfer"),
10132
- ...externalRelations.filter((rel) => rel.relationType === "transfer")
10133
- ];
10164
+ const transfers = [...internalRelations.filter((rel) => rel.relationType === "transfer")];
10134
10165
  const delegates = [
10135
10166
  ...internalRelations.filter((rel) => rel.relationType === "delegate"),
10136
- ...externalRelations.filter((rel) => rel.relationType === "delegate")
10167
+ ...externalRelations.map((data) => data.externalAgent)
10137
10168
  ];
10138
10169
  if (transfers.length === 0 && delegates.length === 0) {
10139
10170
  return baseDescription;
@@ -10152,8 +10183,8 @@ ${transferList}`;
10152
10183
  }
10153
10184
  if (delegates.length > 0) {
10154
10185
  const delegateList = delegates.map((rel) => {
10155
- const name = rel.externalAgent?.name || rel.name;
10156
- const desc = rel.externalAgent?.description || rel.description || "";
10186
+ const name = rel.name;
10187
+ const desc = rel.description || "";
10157
10188
  return `- ${name}: ${desc}`;
10158
10189
  }).join("\n");
10159
10190
  enhancedDescription += `
@@ -10275,7 +10306,7 @@ app.openapi(
10275
10306
  );
10276
10307
  const executionContext = agentsCore.getRequestExecutionContext(c);
10277
10308
  const { tenantId, projectId, agentId, subAgentId } = executionContext;
10278
- console.dir("executionContext", executionContext);
10309
+ logger21.info({ executionContext }, "executionContext");
10279
10310
  if (subAgentId) {
10280
10311
  logger21.info(
10281
10312
  {
@@ -11375,7 +11406,7 @@ var ExecutionHandler = class {
11375
11406
  "ai.subAgent.name": currentAgentId
11376
11407
  });
11377
11408
  await agentsCore.createMessage(dbClient_default)({
11378
- id: nanoid.nanoid(),
11409
+ id: agentsCore.generateId(),
11379
11410
  tenantId,
11380
11411
  projectId,
11381
11412
  conversationId,
@@ -11765,7 +11796,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11765
11796
  });
11766
11797
  }
11767
11798
  await agentsCore.createMessage(dbClient_default)({
11768
- id: nanoid.nanoid(),
11799
+ id: agentsCore.generateId(),
11769
11800
  tenantId,
11770
11801
  projectId,
11771
11802
  conversationId,
@@ -11998,7 +12029,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11998
12029
  });
11999
12030
  }
12000
12031
  await agentsCore.createMessage(dbClient_default)({
12001
- id: nanoid.nanoid(),
12032
+ id: agentsCore.generateId(),
12002
12033
  tenantId,
12003
12034
  projectId,
12004
12035
  conversationId,
@@ -12454,7 +12485,7 @@ var processUserMessage = async (tenantId, projectId, conversationId, query) => {
12454
12485
  });
12455
12486
  }
12456
12487
  await agentsCore.createMessage(dbClient_default)({
12457
- id: nanoid.nanoid(),
12488
+ id: agentsCore.generateId(),
12458
12489
  tenantId,
12459
12490
  projectId,
12460
12491
  conversationId,
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { flushBatchProcessor } from './chunk-TVLDBLRZ.js';
2
- import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-T5AYIGCU.js';
2
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-XLUE6U2L.js';
3
3
  import { dbClient_default } from './chunk-IBMWBEXH.js';
4
4
  import { env } from './chunk-LHCIBW34.js';
5
5
  import { getLogger } from './chunk-A2S7GSHL.js';
6
6
  import { __publicField } from './chunk-PKBMQBKP.js';
7
- import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, commonGetErrorResponses, loggerFactory, getDataComponent, getProject, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getAgentById, getRelatedAgentsForAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, getContextConfigById, getFullAgentDefinition, TemplateEngine, agentHasArtifactComponents, MCPTransportType, SPAN_KEYS, getExternalAgent } from '@inkeep/agents-core';
7
+ import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, generateId, commonGetErrorResponses, loggerFactory, getDataComponent, getProject, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getAgentById, getRelatedAgentsForAgent, getExternalAgentsForSubAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, getContextConfigById, getFullAgentDefinition, TemplateEngine, agentHasArtifactComponents, MCPTransportType, SPAN_KEYS } from '@inkeep/agents-core';
8
8
  import { otel } from '@hono/otel';
9
9
  import { OpenAPIHono, createRoute, z as z$1 } from '@hono/zod-openapi';
10
10
  import { trace, propagation, context, SpanStatusCode } from '@opentelemetry/api';
@@ -16,7 +16,6 @@ import { createMiddleware } from 'hono/factory';
16
16
  import { swaggerUI } from '@hono/swagger-ui';
17
17
  import z5, { z } from 'zod';
18
18
  import { streamSSE, stream } from 'hono/streaming';
19
- import { nanoid } from 'nanoid';
20
19
  import { createUIMessageStream, JsonToSseTransformStream, streamObject, parsePartialJson, generateObject, tool, streamText, generateText } from 'ai';
21
20
  import { createAnthropic, anthropic } from '@ai-sdk/anthropic';
22
21
  import { createGateway, gateway } from '@ai-sdk/gateway';
@@ -67,7 +66,9 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
67
66
  if (authHeader?.startsWith("Bearer ")) {
68
67
  try {
69
68
  executionContext = await extractContextFromApiKey(authHeader.substring(7), baseUrl);
70
- executionContext.subAgentId = subAgentId;
69
+ if (subAgentId) {
70
+ executionContext.subAgentId = subAgentId;
71
+ }
71
72
  logger.info({}, "Development/test environment - API key authenticated successfully");
72
73
  } catch {
73
74
  executionContext = createExecutionContext({
@@ -131,7 +132,9 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
131
132
  return;
132
133
  } else if (apiKey) {
133
134
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
134
- executionContext.subAgentId = subAgentId;
135
+ if (subAgentId) {
136
+ executionContext.subAgentId = subAgentId;
137
+ }
135
138
  c.set("executionContext", executionContext);
136
139
  logger.info({}, "API key authenticated successfully");
137
140
  await next();
@@ -149,7 +152,9 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
149
152
  }
150
153
  try {
151
154
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
152
- executionContext.subAgentId = subAgentId;
155
+ if (subAgentId) {
156
+ executionContext.subAgentId = subAgentId;
157
+ }
153
158
  c.set("executionContext", executionContext);
154
159
  logger.debug(
155
160
  {
@@ -178,13 +183,28 @@ var extractContextFromApiKey = async (apiKey, baseUrl) => {
178
183
  message: "Invalid or expired API key"
179
184
  });
180
185
  }
186
+ const agent = await getAgentById(dbClient_default)({
187
+ scopes: {
188
+ tenantId: apiKeyRecord.tenantId,
189
+ projectId: apiKeyRecord.projectId,
190
+ agentId: apiKeyRecord.agentId
191
+ }
192
+ });
193
+ if (!agent) {
194
+ throw new HTTPException(401, {
195
+ message: "Invalid or expired API key"
196
+ });
197
+ }
198
+ logger.info({ agent }, "agent");
199
+ logger.info({ defaultSubAgentId: agent.defaultSubAgentId }, "agent.defaultSubAgentId");
181
200
  return createExecutionContext({
182
201
  apiKey,
183
202
  tenantId: apiKeyRecord.tenantId,
184
203
  projectId: apiKeyRecord.projectId,
185
204
  agentId: apiKeyRecord.agentId,
186
205
  apiKeyId: apiKeyRecord.id,
187
- baseUrl
206
+ baseUrl,
207
+ subAgentId: agent.defaultSubAgentId || void 0
188
208
  });
189
209
  };
190
210
  function setupOpenAPIRoutes(app7) {
@@ -278,7 +298,7 @@ async function handleMessageSend(c, agent, request) {
278
298
  const executionContext = getRequestExecutionContext(c);
279
299
  const { agentId } = executionContext;
280
300
  const task = {
281
- id: nanoid(),
301
+ id: generateId(),
282
302
  input: {
283
303
  parts: params.message.parts.map((part) => ({
284
304
  kind: part.kind,
@@ -371,7 +391,7 @@ async function handleMessageSend(c, agent, request) {
371
391
  const messageText = params.message.parts.filter((part) => part.kind === "text" && "text" in part && part.text).map((part) => part.text).join(" ");
372
392
  try {
373
393
  const messageData = {
374
- id: nanoid(),
394
+ id: generateId(),
375
395
  tenantId: agent.tenantId,
376
396
  projectId: agent.projectId,
377
397
  conversationId: effectiveContextId,
@@ -453,7 +473,7 @@ async function handleMessageSend(c, agent, request) {
453
473
  },
454
474
  artifacts: [
455
475
  {
456
- artifactId: nanoid(),
476
+ artifactId: generateId(),
457
477
  parts: [
458
478
  {
459
479
  kind: "data",
@@ -482,7 +502,7 @@ async function handleMessageSend(c, agent, request) {
482
502
  if (params.configuration?.blocking === false) {
483
503
  const taskResponse = {
484
504
  id: task.id,
485
- contextId: params.message.contextId || nanoid(),
505
+ contextId: params.message.contextId || generateId(),
486
506
  status: taskStatus,
487
507
  artifacts: result.artifacts,
488
508
  kind: "task"
@@ -494,7 +514,7 @@ async function handleMessageSend(c, agent, request) {
494
514
  });
495
515
  }
496
516
  const messageResponse = {
497
- messageId: nanoid(),
517
+ messageId: generateId(),
498
518
  parts: result.artifacts?.[0]?.parts || [
499
519
  {
500
520
  kind: "text",
@@ -539,7 +559,7 @@ async function handleMessageStream(c, agent, request) {
539
559
  });
540
560
  }
541
561
  const task = {
542
- id: nanoid(),
562
+ id: generateId(),
543
563
  input: {
544
564
  parts: params.message.parts.map((part) => ({
545
565
  kind: part.kind,
@@ -560,7 +580,7 @@ async function handleMessageStream(c, agent, request) {
560
580
  try {
561
581
  const initialTask = {
562
582
  id: task.id,
563
- contextId: params.message.contextId || nanoid(),
583
+ contextId: params.message.contextId || generateId(),
564
584
  status: {
565
585
  state: TaskState.Working,
566
586
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -608,7 +628,7 @@ async function handleMessageStream(c, agent, request) {
608
628
  }
609
629
  }
610
630
  const messageResponse = {
611
- messageId: nanoid(),
631
+ messageId: generateId(),
612
632
  parts: result.artifacts?.[0]?.parts || [
613
633
  {
614
634
  kind: "text",
@@ -674,14 +694,14 @@ async function handleTasksGet(c, _agent, request) {
674
694
  const params = request.params;
675
695
  const task = {
676
696
  id: params.id,
677
- contextId: nanoid(),
697
+ contextId: generateId(),
678
698
  status: {
679
699
  state: TaskState.Completed,
680
700
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
681
701
  },
682
702
  artifacts: [
683
703
  {
684
- artifactId: nanoid(),
704
+ artifactId: generateId(),
685
705
  parts: [
686
706
  {
687
707
  kind: "text",
@@ -780,7 +800,7 @@ async function handleTasksResubscribe(c, agent, request) {
780
800
  try {
781
801
  const task = {
782
802
  id: params.taskId,
783
- contextId: nanoid(),
803
+ contextId: generateId(),
784
804
  status: {
785
805
  state: TaskState.Completed,
786
806
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -1029,7 +1049,7 @@ var _ToolSessionManager = class _ToolSessionManager {
1029
1049
  * Create a new tool session for an agent execution
1030
1050
  */
1031
1051
  createSession(tenantId, projectId, contextId, taskId) {
1032
- const sessionId = nanoid();
1052
+ const sessionId = generateId();
1033
1053
  return this.createSessionWithId(sessionId, tenantId, projectId, contextId, taskId);
1034
1054
  }
1035
1055
  /**
@@ -4105,7 +4125,7 @@ function errorOp(message, subAgentId, severity = "error", code) {
4105
4125
  };
4106
4126
  }
4107
4127
  function generateToolId() {
4108
- return `tool_${nanoid(8)}`;
4128
+ return `tool_${generateId(8)}`;
4109
4129
  }
4110
4130
  var logger11 = getLogger("DataComponentSchema");
4111
4131
  function jsonSchemaToZod(jsonSchema) {
@@ -5202,7 +5222,7 @@ function createDelegateToAgentTool({
5202
5222
  description: generateDelegateToolDescription(delegateConfig.config),
5203
5223
  inputSchema: z5.object({ message: z5.string() }),
5204
5224
  execute: async (input, context) => {
5205
- const delegationId = `del_${nanoid()}`;
5225
+ const delegationId = `del_${generateId()}`;
5206
5226
  const activeSpan = trace.getActiveSpan();
5207
5227
  if (activeSpan) {
5208
5228
  activeSpan.setAttributes({
@@ -5227,15 +5247,7 @@ function createDelegateToAgentTool({
5227
5247
  const isInternal = delegateConfig.type === "internal";
5228
5248
  let resolvedHeaders = {};
5229
5249
  if (!isInternal) {
5230
- const externalAgent = await getExternalAgent(dbClient_default)({
5231
- scopes: {
5232
- tenantId,
5233
- projectId,
5234
- agentId
5235
- },
5236
- subAgentId: delegateConfig.config.id
5237
- });
5238
- if (externalAgent && (externalAgent.credentialReferenceId || externalAgent.headers) && credentialStoreRegistry) {
5250
+ if ((delegateConfig.config.credentialReferenceId || delegateConfig.config.headers) && credentialStoreRegistry) {
5239
5251
  const contextResolver = new ContextResolver(
5240
5252
  tenantId,
5241
5253
  projectId,
@@ -5251,13 +5263,13 @@ function createDelegateToAgentTool({
5251
5263
  metadata
5252
5264
  };
5253
5265
  let storeReference;
5254
- if (externalAgent.credentialReferenceId) {
5266
+ if (delegateConfig.config.credentialReferenceId) {
5255
5267
  const credentialReference = await getCredentialReference(dbClient_default)({
5256
5268
  scopes: {
5257
5269
  tenantId,
5258
5270
  projectId
5259
5271
  },
5260
- id: externalAgent.credentialReferenceId
5272
+ id: delegateConfig.config.credentialReferenceId
5261
5273
  });
5262
5274
  if (credentialReference) {
5263
5275
  storeReference = {
@@ -5269,7 +5281,7 @@ function createDelegateToAgentTool({
5269
5281
  resolvedHeaders = await credentialStuffer.getCredentialHeaders({
5270
5282
  context: credentialContext,
5271
5283
  storeReference,
5272
- headers: externalAgent.headers || void 0
5284
+ headers: delegateConfig.config.headers || void 0
5273
5285
  });
5274
5286
  }
5275
5287
  } else {
@@ -5299,7 +5311,7 @@ function createDelegateToAgentTool({
5299
5311
  const messageToSend = {
5300
5312
  role: "agent",
5301
5313
  parts: [{ text: input.message, kind: "text" }],
5302
- messageId: nanoid(),
5314
+ messageId: generateId(),
5303
5315
  kind: "message",
5304
5316
  contextId,
5305
5317
  metadata: {
@@ -5314,7 +5326,7 @@ function createDelegateToAgentTool({
5314
5326
  };
5315
5327
  logger13.info({ messageToSend }, "messageToSend");
5316
5328
  await createMessage(dbClient_default)({
5317
- id: nanoid(),
5329
+ id: generateId(),
5318
5330
  tenantId,
5319
5331
  projectId,
5320
5332
  conversationId: contextId,
@@ -7343,7 +7355,7 @@ var Agent = class {
7343
7355
  inputSchema: tool3.inputSchema || tool3.parameters || {},
7344
7356
  usageGuidelines: name.startsWith("transfer_to_") || name.startsWith("delegate_to_") ? `Use this tool to ${name.startsWith("transfer_to_") ? "transfer" : "delegate"} to another agent when appropriate.` : "Use this tool when appropriate for the task at hand."
7345
7357
  }));
7346
- const { getConversationScopedArtifacts } = await import('./conversations-6OGSD67W.js');
7358
+ const { getConversationScopedArtifacts } = await import('./conversations-H2TSLD3U.js');
7347
7359
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
7348
7360
  const referenceArtifacts = await getConversationScopedArtifacts({
7349
7361
  tenantId: this.config.tenantId,
@@ -8256,7 +8268,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8256
8268
  };
8257
8269
  }
8258
8270
  const [
8259
- { internalRelations, externalRelations },
8271
+ internalRelations,
8272
+ externalRelations,
8260
8273
  toolsForAgent,
8261
8274
  dataComponents,
8262
8275
  artifactComponents
@@ -8269,6 +8282,14 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8269
8282
  },
8270
8283
  subAgentId: config.subAgentId
8271
8284
  }),
8285
+ getExternalAgentsForSubAgent(dbClient_default)({
8286
+ scopes: {
8287
+ tenantId: config.tenantId,
8288
+ projectId: config.projectId,
8289
+ agentId: config.agentId,
8290
+ subAgentId: config.subAgentId
8291
+ }
8292
+ }),
8272
8293
  getToolsForAgent(dbClient_default)({
8273
8294
  scopes: {
8274
8295
  tenantId: config.tenantId,
@@ -8296,7 +8317,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8296
8317
  ]);
8297
8318
  logger16.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
8298
8319
  const enhancedInternalRelations = await Promise.all(
8299
- internalRelations.map(async (relation) => {
8320
+ internalRelations.data.map(async (relation) => {
8300
8321
  try {
8301
8322
  const relatedAgent = await getSubAgentById(dbClient_default)({
8302
8323
  scopes: {
@@ -8315,10 +8336,20 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8315
8336
  },
8316
8337
  subAgentId: relation.id
8317
8338
  });
8339
+ const relatedAgentExternalAgentRelations = await getExternalAgentsForSubAgent(
8340
+ dbClient_default
8341
+ )({
8342
+ scopes: {
8343
+ tenantId: config.tenantId,
8344
+ projectId: config.projectId,
8345
+ agentId: config.agentId,
8346
+ subAgentId: relation.id
8347
+ }
8348
+ });
8318
8349
  const enhancedDescription = generateDescriptionWithTransfers(
8319
8350
  relation.description || "",
8320
- relatedAgentRelations.internalRelations,
8321
- relatedAgentRelations.externalRelations
8351
+ relatedAgentRelations.data,
8352
+ relatedAgentExternalAgentRelations.data
8322
8353
  );
8323
8354
  return { ...relation, description: enhancedDescription };
8324
8355
  }
@@ -8395,14 +8426,17 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8395
8426
  transferRelations: []
8396
8427
  }
8397
8428
  })),
8398
- ...externalRelations.map((relation) => ({
8429
+ ...externalRelations.data.map((relation) => ({
8399
8430
  type: "external",
8400
8431
  config: {
8401
8432
  id: relation.externalAgent.id,
8402
8433
  name: relation.externalAgent.name,
8403
8434
  description: relation.externalAgent.description || "",
8404
8435
  baseUrl: relation.externalAgent.baseUrl,
8405
- relationType: relation.relationType || void 0
8436
+ headers: relation.headers,
8437
+ credentialReferenceId: relation.externalAgent.credentialReferenceId,
8438
+ relationId: relation.id,
8439
+ relationType: "delegate"
8406
8440
  }
8407
8441
  }))
8408
8442
  ],
@@ -8527,7 +8561,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8527
8561
  },
8528
8562
  artifacts: [
8529
8563
  {
8530
- artifactId: nanoid(),
8564
+ artifactId: generateId(),
8531
8565
  parts: [
8532
8566
  {
8533
8567
  kind: "data",
@@ -8560,7 +8594,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8560
8594
  status: { state: TaskState.Completed },
8561
8595
  artifacts: [
8562
8596
  {
8563
- artifactId: nanoid(),
8597
+ artifactId: generateId(),
8564
8598
  parts
8565
8599
  }
8566
8600
  ]
@@ -8654,13 +8688,10 @@ function createAgentCard({
8654
8688
  };
8655
8689
  }
8656
8690
  function generateDescriptionWithTransfers(baseDescription, internalRelations, externalRelations) {
8657
- const transfers = [
8658
- ...internalRelations.filter((rel) => rel.relationType === "transfer"),
8659
- ...externalRelations.filter((rel) => rel.relationType === "transfer")
8660
- ];
8691
+ const transfers = [...internalRelations.filter((rel) => rel.relationType === "transfer")];
8661
8692
  const delegates = [
8662
8693
  ...internalRelations.filter((rel) => rel.relationType === "delegate"),
8663
- ...externalRelations.filter((rel) => rel.relationType === "delegate")
8694
+ ...externalRelations.map((data) => data.externalAgent)
8664
8695
  ];
8665
8696
  if (transfers.length === 0 && delegates.length === 0) {
8666
8697
  return baseDescription;
@@ -8679,8 +8710,8 @@ ${transferList}`;
8679
8710
  }
8680
8711
  if (delegates.length > 0) {
8681
8712
  const delegateList = delegates.map((rel) => {
8682
- const name = rel.externalAgent?.name || rel.name;
8683
- const desc = rel.externalAgent?.description || rel.description || "";
8713
+ const name = rel.name;
8714
+ const desc = rel.description || "";
8684
8715
  return `- ${name}: ${desc}`;
8685
8716
  }).join("\n");
8686
8717
  enhancedDescription += `
@@ -8800,7 +8831,7 @@ app.openapi(
8800
8831
  );
8801
8832
  const executionContext = getRequestExecutionContext(c);
8802
8833
  const { tenantId, projectId, agentId, subAgentId } = executionContext;
8803
- console.dir("executionContext", executionContext);
8834
+ logger17.info({ executionContext }, "executionContext");
8804
8835
  if (subAgentId) {
8805
8836
  logger17.info(
8806
8837
  {
@@ -9889,7 +9920,7 @@ var ExecutionHandler = class {
9889
9920
  "ai.subAgent.name": currentAgentId
9890
9921
  });
9891
9922
  await createMessage(dbClient_default)({
9892
- id: nanoid(),
9923
+ id: generateId(),
9893
9924
  tenantId,
9894
9925
  projectId,
9895
9926
  conversationId,
@@ -10278,7 +10309,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10278
10309
  });
10279
10310
  }
10280
10311
  await createMessage(dbClient_default)({
10281
- id: nanoid(),
10312
+ id: generateId(),
10282
10313
  tenantId,
10283
10314
  projectId,
10284
10315
  conversationId,
@@ -10507,7 +10538,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10507
10538
  });
10508
10539
  }
10509
10540
  await createMessage(dbClient_default)({
10510
- id: nanoid(),
10541
+ id: generateId(),
10511
10542
  tenantId,
10512
10543
  projectId,
10513
10544
  conversationId,
@@ -10957,7 +10988,7 @@ var processUserMessage = async (tenantId, projectId, conversationId, query) => {
10957
10988
  });
10958
10989
  }
10959
10990
  await createMessage(dbClient_default)({
10960
- id: nanoid(),
10991
+ id: generateId(),
10961
10992
  tenantId,
10962
10993
  projectId,
10963
10994
  conversationId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/agents-run-api",
3
- "version": "0.24.1",
3
+ "version": "0.25.0",
4
4
  "description": "Agents Run API for Inkeep Agent Framework - handles chat, agent execution, and streaming",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -52,7 +52,7 @@
52
52
  "traverse": "^0.6.11",
53
53
  "ts-pattern": "^5.7.1",
54
54
  "zod": "^4.1.11",
55
- "@inkeep/agents-core": "^0.24.1"
55
+ "@inkeep/agents-core": "^0.25.0"
56
56
  },
57
57
  "optionalDependencies": {
58
58
  "keytar": "^7.9.0"
@@ -69,7 +69,7 @@
69
69
  "nodemon": "^3.1.0",
70
70
  "tsx": "^4.7.1",
71
71
  "typescript": "^5.3.3",
72
- "vite": "^7.1.4",
72
+ "vite": "^7.1.11",
73
73
  "vite-tsconfig-paths": "^5.1.4",
74
74
  "vitest": "^3.2.4"
75
75
  },