@inkeep/agents-run-api 0.33.1 → 0.34.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.
@@ -7,7 +7,7 @@ function createDefaultConversationHistoryConfig(mode = "full") {
7
7
  mode,
8
8
  limit: CONVERSATION_HISTORY_DEFAULT_LIMIT,
9
9
  includeInternal: true,
10
- messageTypes: ["chat"],
10
+ messageTypes: ["chat", "tool-result"],
11
11
  maxOutputTokens: CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT
12
12
  };
13
13
  }
@@ -67,29 +67,40 @@ async function getScopedHistory({
67
67
  conversationId,
68
68
  options
69
69
  });
70
- if (!filters || !filters.subAgentId && !filters.taskId) {
70
+ if (!filters || !filters.subAgentId && !filters.taskId && !filters.delegationId && filters.isDelegated === void 0) {
71
71
  return messages;
72
72
  }
73
73
  const relevantMessages = messages.filter((msg) => {
74
74
  if (msg.role === "user") return true;
75
75
  let matchesAgent = true;
76
76
  let matchesTask = true;
77
+ let matchesDelegation = true;
77
78
  if (filters.subAgentId) {
78
79
  matchesAgent = msg.role === "agent" && msg.visibility === "user-facing" || msg.toSubAgentId === filters.subAgentId || msg.fromSubAgentId === filters.subAgentId;
79
80
  }
80
81
  if (filters.taskId) {
81
82
  matchesTask = msg.taskId === filters.taskId || msg.a2aTaskId === filters.taskId;
82
83
  }
83
- if (filters.subAgentId && filters.taskId) {
84
- return matchesAgent && matchesTask;
84
+ if (filters.delegationId !== void 0 || filters.isDelegated !== void 0) {
85
+ if (msg.messageType === "tool-result") {
86
+ const messageDelegationId = msg.metadata?.a2a_metadata?.delegationId;
87
+ const messageIsDelegated = msg.metadata?.a2a_metadata?.isDelegated;
88
+ if (filters.delegationId) {
89
+ matchesDelegation = messageDelegationId === filters.delegationId || !messageDelegationId;
90
+ } else if (filters.isDelegated === false) {
91
+ matchesDelegation = !messageIsDelegated;
92
+ } else if (filters.isDelegated === true) {
93
+ matchesDelegation = messageIsDelegated === true;
94
+ }
95
+ }
85
96
  }
86
- if (filters.subAgentId) {
87
- return matchesAgent;
88
- }
89
- if (filters.taskId) {
90
- return matchesTask;
91
- }
92
- return false;
97
+ const conditions = [];
98
+ if (filters.subAgentId) conditions.push(matchesAgent);
99
+ if (filters.taskId) conditions.push(matchesTask);
100
+ if (filters.delegationId !== void 0 || filters.isDelegated !== void 0)
101
+ conditions.push(matchesDelegation);
102
+ const finalResult = conditions.length === 0 || conditions.every(Boolean);
103
+ return finalResult;
93
104
  });
94
105
  return relevantMessages;
95
106
  } catch (error) {
@@ -109,10 +120,12 @@ async function getUserFacingHistory(tenantId, projectId, conversationId, limit =
109
120
  });
110
121
  }
111
122
  async function getFullConversationContext(tenantId, projectId, conversationId, maxTokens) {
123
+ const defaultConfig = createDefaultConversationHistoryConfig();
112
124
  return await getConversationHistory(dbClient_default)({
113
125
  scopes: { tenantId, projectId },
114
126
  conversationId,
115
127
  options: {
128
+ ...defaultConfig,
116
129
  limit: 100,
117
130
  includeInternal: true,
118
131
  maxOutputTokens: maxTokens
@@ -127,7 +140,7 @@ async function getFormattedConversationHistory({
127
140
  options,
128
141
  filters
129
142
  }) {
130
- const historyOptions = options ?? { includeInternal: true };
143
+ const historyOptions = options ?? createDefaultConversationHistoryConfig();
131
144
  const conversationHistory = await getScopedHistory({
132
145
  tenantId,
133
146
  projectId,
@@ -156,6 +169,10 @@ async function getFormattedConversationHistory({
156
169
  } else if (msg.role === "agent" && msg.messageType === "chat") {
157
170
  const fromSubAgent = msg.fromSubAgentId || "unknown";
158
171
  roleLabel = `${fromSubAgent} to User`;
172
+ } else if (msg.role === "assistant" && msg.messageType === "tool-result") {
173
+ const fromSubAgent = msg.fromSubAgentId || "unknown";
174
+ const toolName = msg.metadata?.a2a_metadata?.toolName || "unknown";
175
+ roleLabel = `${fromSubAgent} tool: ${toolName}`;
159
176
  } else {
160
177
  roleLabel = msg.role || "system";
161
178
  }
@@ -1 +1 @@
1
- export { createDefaultConversationHistoryConfig, getConversationScopedArtifacts, getFormattedConversationHistory, getFullConversationContext, getScopedHistory, getUserFacingHistory, saveA2AMessageResponse } from './chunk-BEMQODJT.js';
1
+ export { createDefaultConversationHistoryConfig, getConversationScopedArtifacts, getFormattedConversationHistory, getFullConversationContext, getScopedHistory, getUserFacingHistory, saveA2AMessageResponse } from './chunk-7GZGZNDA.js';
package/dist/index.cjs CHANGED
@@ -34,6 +34,7 @@ var anthropic = require('@ai-sdk/anthropic');
34
34
  var gateway = require('@ai-sdk/gateway');
35
35
  var google = require('@ai-sdk/google');
36
36
  var openai = require('@ai-sdk/openai');
37
+ var openaiCompatible = require('@ai-sdk/openai-compatible');
37
38
  var aiSdkProvider = require('@openrouter/ai-sdk-provider');
38
39
  var jmespath = require('jmespath');
39
40
  var Ajv = require('ajv');
@@ -360,7 +361,7 @@ function createDefaultConversationHistoryConfig(mode = "full") {
360
361
  mode,
361
362
  limit: CONVERSATION_HISTORY_DEFAULT_LIMIT,
362
363
  includeInternal: true,
363
- messageTypes: ["chat"],
364
+ messageTypes: ["chat", "tool-result"],
364
365
  maxOutputTokens: agentsCore.CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT
365
366
  };
366
367
  }
@@ -420,29 +421,40 @@ async function getScopedHistory({
420
421
  conversationId,
421
422
  options
422
423
  });
423
- if (!filters || !filters.subAgentId && !filters.taskId) {
424
+ if (!filters || !filters.subAgentId && !filters.taskId && !filters.delegationId && filters.isDelegated === void 0) {
424
425
  return messages;
425
426
  }
426
427
  const relevantMessages = messages.filter((msg) => {
427
428
  if (msg.role === "user") return true;
428
429
  let matchesAgent = true;
429
430
  let matchesTask = true;
431
+ let matchesDelegation = true;
430
432
  if (filters.subAgentId) {
431
433
  matchesAgent = msg.role === "agent" && msg.visibility === "user-facing" || msg.toSubAgentId === filters.subAgentId || msg.fromSubAgentId === filters.subAgentId;
432
434
  }
433
435
  if (filters.taskId) {
434
436
  matchesTask = msg.taskId === filters.taskId || msg.a2aTaskId === filters.taskId;
435
437
  }
436
- if (filters.subAgentId && filters.taskId) {
437
- return matchesAgent && matchesTask;
438
- }
439
- if (filters.subAgentId) {
440
- return matchesAgent;
441
- }
442
- if (filters.taskId) {
443
- return matchesTask;
438
+ if (filters.delegationId !== void 0 || filters.isDelegated !== void 0) {
439
+ if (msg.messageType === "tool-result") {
440
+ const messageDelegationId = msg.metadata?.a2a_metadata?.delegationId;
441
+ const messageIsDelegated = msg.metadata?.a2a_metadata?.isDelegated;
442
+ if (filters.delegationId) {
443
+ matchesDelegation = messageDelegationId === filters.delegationId || !messageDelegationId;
444
+ } else if (filters.isDelegated === false) {
445
+ matchesDelegation = !messageIsDelegated;
446
+ } else if (filters.isDelegated === true) {
447
+ matchesDelegation = messageIsDelegated === true;
448
+ }
449
+ }
444
450
  }
445
- return false;
451
+ const conditions = [];
452
+ if (filters.subAgentId) conditions.push(matchesAgent);
453
+ if (filters.taskId) conditions.push(matchesTask);
454
+ if (filters.delegationId !== void 0 || filters.isDelegated !== void 0)
455
+ conditions.push(matchesDelegation);
456
+ const finalResult = conditions.length === 0 || conditions.every(Boolean);
457
+ return finalResult;
446
458
  });
447
459
  return relevantMessages;
448
460
  } catch (error) {
@@ -462,10 +474,12 @@ async function getUserFacingHistory(tenantId, projectId, conversationId, limit =
462
474
  });
463
475
  }
464
476
  async function getFullConversationContext(tenantId, projectId, conversationId, maxTokens) {
477
+ const defaultConfig2 = createDefaultConversationHistoryConfig();
465
478
  return await agentsCore.getConversationHistory(dbClient_default)({
466
479
  scopes: { tenantId, projectId },
467
480
  conversationId,
468
481
  options: {
482
+ ...defaultConfig2,
469
483
  limit: 100,
470
484
  includeInternal: true,
471
485
  maxOutputTokens: maxTokens
@@ -480,7 +494,7 @@ async function getFormattedConversationHistory({
480
494
  options,
481
495
  filters
482
496
  }) {
483
- const historyOptions = options ?? { includeInternal: true };
497
+ const historyOptions = options ?? createDefaultConversationHistoryConfig();
484
498
  const conversationHistory = await getScopedHistory({
485
499
  tenantId,
486
500
  projectId,
@@ -509,6 +523,10 @@ async function getFormattedConversationHistory({
509
523
  } else if (msg.role === "agent" && msg.messageType === "chat") {
510
524
  const fromSubAgent = msg.fromSubAgentId || "unknown";
511
525
  roleLabel = `${fromSubAgent} to User`;
526
+ } else if (msg.role === "assistant" && msg.messageType === "tool-result") {
527
+ const fromSubAgent = msg.fromSubAgentId || "unknown";
528
+ const toolName = msg.metadata?.a2a_metadata?.toolName || "unknown";
529
+ roleLabel = `${fromSubAgent} tool: ${toolName}`;
512
530
  } else {
513
531
  roleLabel = msg.role || "system";
514
532
  }
@@ -2561,6 +2579,13 @@ init_logger();
2561
2579
  // src/agents/ModelFactory.ts
2562
2580
  init_logger();
2563
2581
  var logger4 = agentsCore.getLogger("ModelFactory");
2582
+ var nimDefault = openaiCompatible.createOpenAICompatible({
2583
+ name: "nim",
2584
+ baseURL: "https://integrate.api.nvidia.com/v1",
2585
+ headers: {
2586
+ Authorization: `Bearer ${process.env.NIM_API_KEY}`
2587
+ }
2588
+ });
2564
2589
  var _ModelFactory = class _ModelFactory {
2565
2590
  /**
2566
2591
  * Create a provider instance with custom configuration
@@ -2585,6 +2610,47 @@ var _ModelFactory = class _ModelFactory {
2585
2610
  };
2586
2611
  case "gateway":
2587
2612
  return gateway.createGateway(config);
2613
+ case "nim": {
2614
+ const nimConfig = {
2615
+ name: "nim",
2616
+ baseURL: "https://integrate.api.nvidia.com/v1",
2617
+ headers: {
2618
+ Authorization: `Bearer ${process.env.NIM_API_KEY}`
2619
+ },
2620
+ ...config
2621
+ };
2622
+ return openaiCompatible.createOpenAICompatible(nimConfig);
2623
+ }
2624
+ case "custom": {
2625
+ if (!config.baseURL && !config.baseUrl) {
2626
+ throw new Error(
2627
+ "Custom provider requires baseURL. Please provide it in providerOptions.baseURL or providerOptions.baseUrl"
2628
+ );
2629
+ }
2630
+ const customConfig = {
2631
+ name: "custom",
2632
+ baseURL: config.baseURL || config.baseUrl,
2633
+ headers: {
2634
+ ...process.env.CUSTOM_LLM_API_KEY && {
2635
+ Authorization: `Bearer ${process.env.CUSTOM_LLM_API_KEY}`
2636
+ },
2637
+ ...config.headers || {}
2638
+ },
2639
+ ...config
2640
+ };
2641
+ logger4.info(
2642
+ {
2643
+ config: {
2644
+ baseURL: customConfig.baseURL,
2645
+ hasApiKey: !!process.env.CUSTOM_LLM_API_KEY,
2646
+ apiKeyPrefix: process.env.CUSTOM_LLM_API_KEY?.substring(0, 10) + "...",
2647
+ headers: Object.keys(customConfig.headers || {})
2648
+ }
2649
+ },
2650
+ "Creating custom OpenAI-compatible provider"
2651
+ );
2652
+ return openaiCompatible.createOpenAICompatible(customConfig);
2653
+ }
2588
2654
  default:
2589
2655
  throw new Error(`Unsupported provider: ${provider}`);
2590
2656
  }
@@ -2601,9 +2667,18 @@ var _ModelFactory = class _ModelFactory {
2601
2667
  if (providerOptions.baseUrl || providerOptions.baseURL) {
2602
2668
  providerConfig.baseURL = providerOptions.baseUrl || providerOptions.baseURL;
2603
2669
  }
2670
+ if (providerOptions.headers) {
2671
+ providerConfig.headers = providerOptions.headers;
2672
+ }
2604
2673
  if (providerOptions.gateway) {
2605
2674
  Object.assign(providerConfig, providerOptions.gateway);
2606
2675
  }
2676
+ if (providerOptions.nim) {
2677
+ Object.assign(providerConfig, providerOptions.nim);
2678
+ }
2679
+ if (providerOptions.custom) {
2680
+ Object.assign(providerConfig, providerOptions.custom);
2681
+ }
2607
2682
  return providerConfig;
2608
2683
  }
2609
2684
  /**
@@ -2648,9 +2723,15 @@ var _ModelFactory = class _ModelFactory {
2648
2723
  return aiSdkProvider.openrouter(modelName);
2649
2724
  case "gateway":
2650
2725
  return gateway.gateway(modelName);
2726
+ case "nim":
2727
+ return nimDefault(modelName);
2728
+ case "custom":
2729
+ throw new Error(
2730
+ "Custom provider requires configuration. Please provide baseURL in providerOptions.custom.baseURL or providerOptions.baseURL"
2731
+ );
2651
2732
  default:
2652
2733
  throw new Error(
2653
- `Unsupported provider: ${provider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id) or Vercel AI Gateway (gateway/model-id).`
2734
+ `Unsupported provider: ${provider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`
2654
2735
  );
2655
2736
  }
2656
2737
  }
@@ -2666,7 +2747,7 @@ var _ModelFactory = class _ModelFactory {
2666
2747
  const normalizedProvider = provider.toLowerCase();
2667
2748
  if (!_ModelFactory.BUILT_IN_PROVIDERS.includes(normalizedProvider)) {
2668
2749
  throw new Error(
2669
- `Unsupported provider: ${normalizedProvider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id) or Vercel AI Gateway (gateway/model-id).`
2750
+ `Unsupported provider: ${normalizedProvider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`
2670
2751
  );
2671
2752
  }
2672
2753
  return {
@@ -2685,7 +2766,16 @@ var _ModelFactory = class _ModelFactory {
2685
2766
  if (!providerOptions) {
2686
2767
  return {};
2687
2768
  }
2688
- const excludedKeys = ["apiKey", "baseURL", "baseUrl", "maxDuration"];
2769
+ const excludedKeys = [
2770
+ "apiKey",
2771
+ "baseURL",
2772
+ "baseUrl",
2773
+ "maxDuration",
2774
+ "headers",
2775
+ "gateway",
2776
+ "nim",
2777
+ "custom"
2778
+ ];
2689
2779
  const params = {};
2690
2780
  for (const [key, value] of Object.entries(providerOptions)) {
2691
2781
  if (!excludedKeys.includes(key) && value !== void 0) {
@@ -2746,7 +2836,9 @@ __publicField(_ModelFactory, "BUILT_IN_PROVIDERS", [
2746
2836
  "openai",
2747
2837
  "google",
2748
2838
  "openrouter",
2749
- "gateway"
2839
+ "gateway",
2840
+ "nim",
2841
+ "custom"
2750
2842
  ]);
2751
2843
  var ModelFactory = _ModelFactory;
2752
2844
 
@@ -4664,10 +4756,12 @@ var AgentSession = class {
4664
4756
  const conversationHistory = await getFormattedConversationHistory({
4665
4757
  tenantId: this.tenantId,
4666
4758
  projectId: this.projectId,
4667
- conversationId: this.sessionId,
4759
+ conversationId: this.contextId || "default",
4668
4760
  options: {
4669
4761
  limit: agentsCore.CONVERSATION_HISTORY_DEFAULT_LIMIT,
4670
- maxOutputTokens: agentsCore.CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT
4762
+ maxOutputTokens: agentsCore.CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT,
4763
+ includeInternal: true,
4764
+ messageTypes: ["chat", "tool-result"]
4671
4765
  },
4672
4766
  filters: {}
4673
4767
  });
@@ -4787,8 +4881,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
4787
4881
  }
4788
4882
  });
4789
4883
  const result = object;
4884
+ logger9.info({ result: JSON.stringify(result) }, "DEBUG: Result");
4790
4885
  const summaries = [];
4791
4886
  for (const [componentId, data] of Object.entries(result)) {
4887
+ logger9.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
4792
4888
  if (componentId === "no_relevant_updates") {
4793
4889
  continue;
4794
4890
  }
@@ -5355,10 +5451,10 @@ var AgentSessionManager = class {
5355
5451
  /**
5356
5452
  * Initialize status updates for a session
5357
5453
  */
5358
- initializeStatusUpdates(sessionId, config, summarizerModel) {
5454
+ initializeStatusUpdates(sessionId, config, summarizerModel, baseModel) {
5359
5455
  const session = this.sessions.get(sessionId);
5360
5456
  if (session) {
5361
- session.initializeStatusUpdates(config, summarizerModel);
5457
+ session.initializeStatusUpdates(config, summarizerModel, baseModel);
5362
5458
  } else {
5363
5459
  logger9.error(
5364
5460
  {
@@ -8594,6 +8690,7 @@ var Agent = class {
8594
8690
  __publicField(this, "streamHelper");
8595
8691
  __publicField(this, "streamRequestId");
8596
8692
  __publicField(this, "conversationId");
8693
+ __publicField(this, "delegationId");
8597
8694
  __publicField(this, "artifactComponents", []);
8598
8695
  __publicField(this, "isDelegatedAgent", false);
8599
8696
  __publicField(this, "contextResolver");
@@ -8731,6 +8828,12 @@ var Agent = class {
8731
8828
  setDelegationStatus(isDelegated) {
8732
8829
  this.isDelegatedAgent = isDelegated;
8733
8830
  }
8831
+ /**
8832
+ * Set delegation ID for this agent instance
8833
+ */
8834
+ setDelegationId(delegationId) {
8835
+ this.delegationId = delegationId;
8836
+ }
8734
8837
  /**
8735
8838
  * Get streaming helper if this agent should stream to user
8736
8839
  * Returns undefined for delegated agents to prevent streaming data operations to user
@@ -8741,7 +8844,7 @@ var Agent = class {
8741
8844
  /**
8742
8845
  * Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
8743
8846
  */
8744
- wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType) {
8847
+ wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId) {
8745
8848
  if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
8746
8849
  return toolDefinition;
8747
8850
  }
@@ -8762,23 +8865,59 @@ var Agent = class {
8762
8865
  "agent.id": this.config.agentId || "unknown"
8763
8866
  });
8764
8867
  }
8765
- const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_") || toolName.startsWith("delegate_to_");
8868
+ const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_");
8766
8869
  if (streamRequestId && !isInternalTool) {
8767
8870
  agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, {
8768
8871
  toolName,
8769
8872
  input: args,
8770
- toolCallId
8873
+ toolCallId,
8874
+ relationshipId
8771
8875
  });
8772
8876
  }
8773
8877
  try {
8774
8878
  const result = await originalExecute(args, context);
8775
8879
  const duration = Date.now() - startTime;
8880
+ const toolResultConversationId = this.getToolResultConversationId();
8881
+ if (streamRequestId && !isInternalTool && toolResultConversationId) {
8882
+ try {
8883
+ const messageId = agentsCore.generateId();
8884
+ const messagePayload = {
8885
+ id: messageId,
8886
+ tenantId: this.config.tenantId,
8887
+ projectId: this.config.projectId,
8888
+ conversationId: toolResultConversationId,
8889
+ role: "assistant",
8890
+ content: {
8891
+ text: this.formatToolResult(toolName, args, result, toolCallId)
8892
+ },
8893
+ visibility: "internal",
8894
+ messageType: "tool-result",
8895
+ fromSubAgentId: this.config.id,
8896
+ metadata: {
8897
+ a2a_metadata: {
8898
+ toolName,
8899
+ toolCallId,
8900
+ timestamp: Date.now(),
8901
+ delegationId: this.delegationId,
8902
+ isDelegated: this.isDelegatedAgent
8903
+ }
8904
+ }
8905
+ };
8906
+ await agentsCore.createMessage(dbClient_default)(messagePayload);
8907
+ } catch (error) {
8908
+ logger19.warn(
8909
+ { error, toolName, toolCallId, conversationId: toolResultConversationId },
8910
+ "Failed to store tool result in conversation history"
8911
+ );
8912
+ }
8913
+ }
8776
8914
  if (streamRequestId && !isInternalTool) {
8777
8915
  agentSessionManager.recordEvent(streamRequestId, "tool_result", this.config.id, {
8778
8916
  toolName,
8779
8917
  output: result,
8780
8918
  toolCallId,
8781
- duration
8919
+ duration,
8920
+ relationshipId
8782
8921
  });
8783
8922
  }
8784
8923
  return result;
@@ -8791,7 +8930,8 @@ var Agent = class {
8791
8930
  output: null,
8792
8931
  toolCallId,
8793
8932
  duration,
8794
- error: errorMessage
8933
+ error: errorMessage,
8934
+ relationshipId
8795
8935
  });
8796
8936
  }
8797
8937
  throw error;
@@ -8857,22 +8997,24 @@ var Agent = class {
8857
8997
  }) || [];
8858
8998
  const tools = await Promise.all(mcpTools.map((tool3) => this.getMcpTool(tool3)) || []) || [];
8859
8999
  if (!sessionId) {
8860
- const combinedTools = tools.reduce((acc, tool3) => {
8861
- return Object.assign(acc, tool3);
8862
- }, {});
8863
9000
  const wrappedTools2 = {};
8864
- for (const [toolName, toolDef] of Object.entries(combinedTools)) {
8865
- wrappedTools2[toolName] = this.wrapToolWithStreaming(
8866
- toolName,
8867
- toolDef,
8868
- streamRequestId,
8869
- "mcp"
8870
- );
9001
+ for (const [index, toolSet] of tools.entries()) {
9002
+ const relationshipId = mcpTools[index]?.relationshipId;
9003
+ for (const [toolName, toolDef] of Object.entries(toolSet)) {
9004
+ wrappedTools2[toolName] = this.wrapToolWithStreaming(
9005
+ toolName,
9006
+ toolDef,
9007
+ streamRequestId,
9008
+ "mcp",
9009
+ relationshipId
9010
+ );
9011
+ }
8871
9012
  }
8872
9013
  return wrappedTools2;
8873
9014
  }
8874
9015
  const wrappedTools = {};
8875
- for (const toolSet of tools) {
9016
+ for (const [index, toolSet] of tools.entries()) {
9017
+ const relationshipId = mcpTools[index]?.relationshipId;
8876
9018
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
8877
9019
  if (!isValidTool(originalTool)) {
8878
9020
  logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
@@ -8885,7 +9027,7 @@ var Agent = class {
8885
9027
  logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
8886
9028
  try {
8887
9029
  const rawResult = await originalTool.execute(args, { toolCallId });
8888
- if (rawResult && typeof rawResult === "object" && "isError" in rawResult && rawResult.isError) {
9030
+ if (rawResult && typeof rawResult === "object" && rawResult.isError) {
8889
9031
  const errorMessage = rawResult.content?.[0]?.text || "MCP tool returned an error";
8890
9032
  logger19.error(
8891
9033
  { toolName, toolCallId, errorMessage, rawResult },
@@ -8906,7 +9048,8 @@ var Agent = class {
8906
9048
  context: {
8907
9049
  toolName,
8908
9050
  toolCallId,
8909
- errorMessage
9051
+ errorMessage,
9052
+ relationshipId
8910
9053
  }
8911
9054
  });
8912
9055
  }
@@ -8945,7 +9088,8 @@ var Agent = class {
8945
9088
  toolName,
8946
9089
  sessionWrappedTool,
8947
9090
  streamRequestId,
8948
- "mcp"
9091
+ "mcp",
9092
+ relationshipId
8949
9093
  );
8950
9094
  }
8951
9095
  }
@@ -9570,7 +9714,20 @@ var Agent = class {
9570
9714
  */
9571
9715
  formatToolResult(toolName, args, result, toolCallId) {
9572
9716
  const input = args ? JSON.stringify(args, null, 2) : "No input";
9573
- const output = typeof result === "string" ? result : JSON.stringify(result, null, 2);
9717
+ let parsedResult = result;
9718
+ if (typeof result === "string") {
9719
+ try {
9720
+ parsedResult = JSON.parse(result);
9721
+ } catch (e) {
9722
+ }
9723
+ }
9724
+ const cleanResult = parsedResult && typeof parsedResult === "object" && !Array.isArray(parsedResult) ? {
9725
+ ...parsedResult,
9726
+ result: parsedResult.result && typeof parsedResult.result === "object" && !Array.isArray(parsedResult.result) ? Object.fromEntries(
9727
+ Object.entries(parsedResult.result).filter(([key]) => key !== "_structureHints")
9728
+ ) : parsedResult.result
9729
+ } : parsedResult;
9730
+ const output = typeof cleanResult === "string" ? cleanResult : JSON.stringify(cleanResult, null, 2);
9574
9731
  return `## Tool: ${toolName}
9575
9732
 
9576
9733
  ### \u{1F527} TOOL_CALL_ID: ${toolCallId}
@@ -9581,6 +9738,13 @@ ${input}
9581
9738
  ### Output
9582
9739
  ${output}`;
9583
9740
  }
9741
+ /**
9742
+ * Get the conversation ID for storing tool results
9743
+ * Always uses the real conversation ID - delegation filtering happens at query time
9744
+ */
9745
+ getToolResultConversationId() {
9746
+ return this.conversationId;
9747
+ }
9584
9748
  /**
9585
9749
  * Analyze tool result structure and add helpful path hints for artifact creation
9586
9750
  * Only adds hints when artifact components are available
@@ -9880,13 +10044,17 @@ ${output}`;
9880
10044
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
9881
10045
  if (historyConfig && historyConfig.mode !== "none") {
9882
10046
  if (historyConfig.mode === "full") {
10047
+ const filters = {
10048
+ delegationId: this.delegationId,
10049
+ isDelegated: this.isDelegatedAgent
10050
+ };
9883
10051
  conversationHistory = await getFormattedConversationHistory({
9884
10052
  tenantId: this.config.tenantId,
9885
10053
  projectId: this.config.projectId,
9886
10054
  conversationId: contextId,
9887
10055
  currentMessage: userMessage,
9888
10056
  options: historyConfig,
9889
- filters: {}
10057
+ filters
9890
10058
  });
9891
10059
  } else if (historyConfig.mode === "scoped") {
9892
10060
  conversationHistory = await getFormattedConversationHistory({
@@ -9897,7 +10065,9 @@ ${output}`;
9897
10065
  options: historyConfig,
9898
10066
  filters: {
9899
10067
  subAgentId: this.config.id,
9900
- taskId
10068
+ taskId,
10069
+ delegationId: this.delegationId,
10070
+ isDelegated: this.isDelegatedAgent
9901
10071
  }
9902
10072
  });
9903
10073
  }
@@ -10473,7 +10643,6 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
10473
10643
  }
10474
10644
  })
10475
10645
  ]);
10476
- logger20.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
10477
10646
  const enhancedInternalRelations = await Promise.all(
10478
10647
  internalRelations.data.map(async (relation) => {
10479
10648
  try {
@@ -10592,7 +10761,12 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
10592
10761
  const stopWhen = "stopWhen" in config.agentSchema ? config.agentSchema.stopWhen : void 0;
10593
10762
  const toolsForAgentResult = await Promise.all(
10594
10763
  toolsForAgent.data.map(async (item) => {
10595
- const mcpTool = await agentsCore.dbResultToMcpTool(item.tool, dbClient_default, credentialStoreRegistry);
10764
+ const mcpTool = await agentsCore.dbResultToMcpTool(
10765
+ item.tool,
10766
+ dbClient_default,
10767
+ credentialStoreRegistry,
10768
+ item.id
10769
+ );
10596
10770
  if (item.selectedTools && item.selectedTools.length > 0) {
10597
10771
  const selectedToolsSet = new Set(item.selectedTools);
10598
10772
  mcpTool.availableTools = mcpTool.availableTools?.filter((tool3) => selectedToolsSet.has(tool3.name)) || [];
@@ -10674,7 +10848,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
10674
10848
  const mcpTool = await agentsCore.dbResultToMcpTool(
10675
10849
  item.tool,
10676
10850
  dbClient_default,
10677
- credentialStoreRegistry
10851
+ credentialStoreRegistry,
10852
+ item.id
10678
10853
  );
10679
10854
  if (item.selectedTools && item.selectedTools.length > 0) {
10680
10855
  const selectedToolsSet = new Set(item.selectedTools);
@@ -10813,10 +10988,12 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
10813
10988
  }
10814
10989
  const streamRequestId = task.context?.metadata?.stream_request_id || task.context?.metadata?.streamRequestId;
10815
10990
  const isDelegation = task.context?.metadata?.isDelegation === true;
10991
+ const delegationId = task.context?.metadata?.delegationId;
10816
10992
  agent.setDelegationStatus(isDelegation);
10993
+ agent.setDelegationId(delegationId);
10817
10994
  if (isDelegation) {
10818
10995
  logger20.info(
10819
- { subAgentId: config.subAgentId, taskId: task.id },
10996
+ { subAgentId: config.subAgentId, taskId: task.id, delegationId },
10820
10997
  "Delegated agent - streaming disabled"
10821
10998
  );
10822
10999
  if (streamRequestId && config.tenantId && config.projectId) {
@@ -10970,7 +11147,7 @@ var createTaskHandlerConfig = async (params) => {
10970
11147
  throw new Error(`Agent not found: ${params.subAgentId}`);
10971
11148
  }
10972
11149
  const effectiveModels = await resolveModelConfig(params.agentId, subAgent);
10973
- const effectiveConversationHistoryConfig = subAgent.conversationHistoryConfig || { mode: "full" };
11150
+ const effectiveConversationHistoryConfig = subAgent.conversationHistoryConfig;
10974
11151
  return {
10975
11152
  tenantId: params.tenantId,
10976
11153
  projectId: params.projectId,
@@ -11325,40 +11502,16 @@ init_dbClient();
11325
11502
  init_dbClient();
11326
11503
  init_logger();
11327
11504
  function isTransferTask(result) {
11328
- console.log(
11329
- "[isTransferTask] Checking result:",
11330
- JSON.stringify(
11331
- {
11332
- hasArtifacts: "artifacts" in result,
11333
- artifactsLength: result.kind === "task" ? result.artifacts?.length : 0,
11334
- firstArtifactParts: result.kind === "task" ? result.artifacts?.[0]?.parts?.length : 0,
11335
- allParts: result.kind === "task" ? result.artifacts?.[0]?.parts?.map((p, i) => ({
11336
- index: i,
11337
- kind: p.kind,
11338
- hasData: !!(p.kind === "data" && p.data),
11339
- dataType: p.kind === "data" ? p.data?.type : void 0,
11340
- dataKeys: p.kind === "data" ? Object.keys(p.data) : []
11341
- })) : []
11342
- },
11343
- null,
11344
- 2
11345
- )
11346
- );
11347
11505
  if (!("artifacts" in result) || !result.artifacts) {
11348
- console.log("[isTransferTask] No artifacts found");
11349
11506
  return false;
11350
11507
  }
11351
11508
  const hasTransfer = result.artifacts.some(
11352
11509
  (artifact) => artifact.parts.some((part) => {
11353
11510
  if (part.kind !== "data" || !part.data) return false;
11354
11511
  const isTransfer = typeof part.data === "object" && "type" in part.data && part.data.type === "transfer";
11355
- if (isTransfer) {
11356
- console.log("[isTransferTask] Found transfer data:", JSON.stringify(part.data, null, 2));
11357
- }
11358
11512
  return isTransfer;
11359
11513
  })
11360
11514
  );
11361
- console.log("[isTransferTask] Result:", hasTransfer);
11362
11515
  return hasTransfer;
11363
11516
  }
11364
11517
  function extractTransferData(task) {
@@ -12020,11 +12173,42 @@ var ExecutionHandler = class {
12020
12173
  scopes: { tenantId, projectId, agentId }
12021
12174
  });
12022
12175
  if (agentConfig?.statusUpdates && agentConfig.statusUpdates.enabled !== false) {
12023
- agentSessionManager.initializeStatusUpdates(
12024
- requestId2,
12025
- agentConfig.statusUpdates,
12026
- agentConfig.models?.summarizer
12027
- );
12176
+ try {
12177
+ const agentWithDefault = await agentsCore.getAgentWithDefaultSubAgent(dbClient_default)({
12178
+ scopes: { tenantId, projectId, agentId }
12179
+ });
12180
+ if (agentWithDefault?.defaultSubAgent) {
12181
+ const resolvedModels = await resolveModelConfig(
12182
+ agentId,
12183
+ agentWithDefault.defaultSubAgent
12184
+ );
12185
+ agentSessionManager.initializeStatusUpdates(
12186
+ requestId2,
12187
+ agentConfig.statusUpdates,
12188
+ resolvedModels.summarizer,
12189
+ resolvedModels.base
12190
+ );
12191
+ } else {
12192
+ agentSessionManager.initializeStatusUpdates(
12193
+ requestId2,
12194
+ agentConfig.statusUpdates,
12195
+ agentConfig.models?.summarizer
12196
+ );
12197
+ }
12198
+ } catch (modelError) {
12199
+ logger24.warn(
12200
+ {
12201
+ error: modelError instanceof Error ? modelError.message : "Unknown error",
12202
+ agentId
12203
+ },
12204
+ "Failed to resolve models for status updates, using agent-level config"
12205
+ );
12206
+ agentSessionManager.initializeStatusUpdates(
12207
+ requestId2,
12208
+ agentConfig.statusUpdates,
12209
+ agentConfig.models?.summarizer
12210
+ );
12211
+ }
12028
12212
  }
12029
12213
  } catch (error) {
12030
12214
  logger24.error(
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { flushBatchProcessor } from './chunk-H2IQDFCM.js';
2
- import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-BEMQODJT.js';
2
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-7GZGZNDA.js';
3
3
  import { dbClient_default } from './chunk-4HDXSU6S.js';
4
4
  import { env } from './chunk-UZXC6MEO.js';
5
5
  import { getLogger } from './chunk-A2S7GSHL.js';
6
6
  import { STREAM_PARSER_MAX_SNAPSHOT_SIZE, STREAM_PARSER_MAX_STREAMED_SIZE, STREAM_PARSER_MAX_COLLECTED_PARTS, STREAM_BUFFER_MAX_SIZE_BYTES, SESSION_CLEANUP_INTERVAL_MS, STREAM_MAX_LIFETIME_MS, STREAM_TEXT_GAP_THRESHOLD_MS, AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS, SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS, ARTIFACT_GENERATION_MAX_RETRIES, ARTIFACT_SESSION_MAX_PENDING, STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS, STATUS_UPDATE_DEFAULT_NUM_EVENTS, ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES, ARTIFACT_GENERATION_BACKOFF_INITIAL_MS, ARTIFACT_GENERATION_BACKOFF_MAX_MS, AGENT_EXECUTION_MAX_GENERATION_STEPS, FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT, FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING, LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS, DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS, DELEGATION_TOOL_BACKOFF_EXPONENT, DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS, DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS } from './chunk-IVALDC72.js';
7
7
  import { __publicField } from './chunk-PKBMQBKP.js';
8
- import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, generateId, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, createTask, updateTask, setSpanWithError, AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT, updateConversation, handleApiError, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, CONVERSATION_HISTORY_DEFAULT_LIMIT, TaskState, setActiveAgentForThread, getConversation, getAgentById, getRelatedAgentsForAgent, getExternalAgentsForSubAgent, getTeamAgentsForSubAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, verifyServiceToken, validateTargetAgent, getProject, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, getContextConfigById, getFullAgentDefinition, TemplateEngine, agentHasArtifactComponents, MCPTransportType, SPAN_KEYS, headers, generateServiceToken } from '@inkeep/agents-core';
8
+ import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, generateId, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, createTask, updateTask, setSpanWithError, AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT, updateConversation, handleApiError, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, CONVERSATION_HISTORY_DEFAULT_LIMIT, TaskState, getAgentById, getProject, setActiveAgentForThread, getConversation, getRelatedAgentsForAgent, getExternalAgentsForSubAgent, getTeamAgentsForSubAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, verifyServiceToken, validateTargetAgent, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, getContextConfigById, getFullAgentDefinition, TemplateEngine, agentHasArtifactComponents, MCPTransportType, SPAN_KEYS, headers, generateServiceToken } from '@inkeep/agents-core';
9
9
  import { otel } from '@hono/otel';
10
10
  import { OpenAPIHono, createRoute, z as z$1 } from '@hono/zod-openapi';
11
11
  import { trace, propagation, context, SpanStatusCode } from '@opentelemetry/api';
@@ -22,6 +22,7 @@ import { createAnthropic, anthropic } from '@ai-sdk/anthropic';
22
22
  import { createGateway, gateway } from '@ai-sdk/gateway';
23
23
  import { createGoogleGenerativeAI, google } from '@ai-sdk/google';
24
24
  import { createOpenAI, openai } from '@ai-sdk/openai';
25
+ import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
25
26
  import { createOpenRouter, openrouter } from '@openrouter/ai-sdk-provider';
26
27
  import jmespath from 'jmespath';
27
28
  import Ajv from 'ajv';
@@ -932,6 +933,13 @@ async function handleTasksResubscribe(c, agent, request) {
932
933
  }
933
934
  }
934
935
  var logger3 = getLogger("ModelFactory");
936
+ var nimDefault = createOpenAICompatible({
937
+ name: "nim",
938
+ baseURL: "https://integrate.api.nvidia.com/v1",
939
+ headers: {
940
+ Authorization: `Bearer ${process.env.NIM_API_KEY}`
941
+ }
942
+ });
935
943
  var _ModelFactory = class _ModelFactory {
936
944
  /**
937
945
  * Create a provider instance with custom configuration
@@ -956,6 +964,47 @@ var _ModelFactory = class _ModelFactory {
956
964
  };
957
965
  case "gateway":
958
966
  return createGateway(config);
967
+ case "nim": {
968
+ const nimConfig = {
969
+ name: "nim",
970
+ baseURL: "https://integrate.api.nvidia.com/v1",
971
+ headers: {
972
+ Authorization: `Bearer ${process.env.NIM_API_KEY}`
973
+ },
974
+ ...config
975
+ };
976
+ return createOpenAICompatible(nimConfig);
977
+ }
978
+ case "custom": {
979
+ if (!config.baseURL && !config.baseUrl) {
980
+ throw new Error(
981
+ "Custom provider requires baseURL. Please provide it in providerOptions.baseURL or providerOptions.baseUrl"
982
+ );
983
+ }
984
+ const customConfig = {
985
+ name: "custom",
986
+ baseURL: config.baseURL || config.baseUrl,
987
+ headers: {
988
+ ...process.env.CUSTOM_LLM_API_KEY && {
989
+ Authorization: `Bearer ${process.env.CUSTOM_LLM_API_KEY}`
990
+ },
991
+ ...config.headers || {}
992
+ },
993
+ ...config
994
+ };
995
+ logger3.info(
996
+ {
997
+ config: {
998
+ baseURL: customConfig.baseURL,
999
+ hasApiKey: !!process.env.CUSTOM_LLM_API_KEY,
1000
+ apiKeyPrefix: process.env.CUSTOM_LLM_API_KEY?.substring(0, 10) + "...",
1001
+ headers: Object.keys(customConfig.headers || {})
1002
+ }
1003
+ },
1004
+ "Creating custom OpenAI-compatible provider"
1005
+ );
1006
+ return createOpenAICompatible(customConfig);
1007
+ }
959
1008
  default:
960
1009
  throw new Error(`Unsupported provider: ${provider}`);
961
1010
  }
@@ -972,9 +1021,18 @@ var _ModelFactory = class _ModelFactory {
972
1021
  if (providerOptions.baseUrl || providerOptions.baseURL) {
973
1022
  providerConfig.baseURL = providerOptions.baseUrl || providerOptions.baseURL;
974
1023
  }
1024
+ if (providerOptions.headers) {
1025
+ providerConfig.headers = providerOptions.headers;
1026
+ }
975
1027
  if (providerOptions.gateway) {
976
1028
  Object.assign(providerConfig, providerOptions.gateway);
977
1029
  }
1030
+ if (providerOptions.nim) {
1031
+ Object.assign(providerConfig, providerOptions.nim);
1032
+ }
1033
+ if (providerOptions.custom) {
1034
+ Object.assign(providerConfig, providerOptions.custom);
1035
+ }
978
1036
  return providerConfig;
979
1037
  }
980
1038
  /**
@@ -1019,9 +1077,15 @@ var _ModelFactory = class _ModelFactory {
1019
1077
  return openrouter(modelName);
1020
1078
  case "gateway":
1021
1079
  return gateway(modelName);
1080
+ case "nim":
1081
+ return nimDefault(modelName);
1082
+ case "custom":
1083
+ throw new Error(
1084
+ "Custom provider requires configuration. Please provide baseURL in providerOptions.custom.baseURL or providerOptions.baseURL"
1085
+ );
1022
1086
  default:
1023
1087
  throw new Error(
1024
- `Unsupported provider: ${provider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id) or Vercel AI Gateway (gateway/model-id).`
1088
+ `Unsupported provider: ${provider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`
1025
1089
  );
1026
1090
  }
1027
1091
  }
@@ -1037,7 +1101,7 @@ var _ModelFactory = class _ModelFactory {
1037
1101
  const normalizedProvider = provider.toLowerCase();
1038
1102
  if (!_ModelFactory.BUILT_IN_PROVIDERS.includes(normalizedProvider)) {
1039
1103
  throw new Error(
1040
- `Unsupported provider: ${normalizedProvider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id) or Vercel AI Gateway (gateway/model-id).`
1104
+ `Unsupported provider: ${normalizedProvider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`
1041
1105
  );
1042
1106
  }
1043
1107
  return {
@@ -1056,7 +1120,16 @@ var _ModelFactory = class _ModelFactory {
1056
1120
  if (!providerOptions) {
1057
1121
  return {};
1058
1122
  }
1059
- const excludedKeys = ["apiKey", "baseURL", "baseUrl", "maxDuration"];
1123
+ const excludedKeys = [
1124
+ "apiKey",
1125
+ "baseURL",
1126
+ "baseUrl",
1127
+ "maxDuration",
1128
+ "headers",
1129
+ "gateway",
1130
+ "nim",
1131
+ "custom"
1132
+ ];
1060
1133
  const params = {};
1061
1134
  for (const [key, value] of Object.entries(providerOptions)) {
1062
1135
  if (!excludedKeys.includes(key) && value !== void 0) {
@@ -1117,7 +1190,9 @@ __publicField(_ModelFactory, "BUILT_IN_PROVIDERS", [
1117
1190
  "openai",
1118
1191
  "google",
1119
1192
  "openrouter",
1120
- "gateway"
1193
+ "gateway",
1194
+ "nim",
1195
+ "custom"
1121
1196
  ]);
1122
1197
  var ModelFactory = _ModelFactory;
1123
1198
  var logger4 = getLogger("ToolSessionManager");
@@ -3017,10 +3092,12 @@ var AgentSession = class {
3017
3092
  const conversationHistory = await getFormattedConversationHistory({
3018
3093
  tenantId: this.tenantId,
3019
3094
  projectId: this.projectId,
3020
- conversationId: this.sessionId,
3095
+ conversationId: this.contextId || "default",
3021
3096
  options: {
3022
3097
  limit: CONVERSATION_HISTORY_DEFAULT_LIMIT,
3023
- maxOutputTokens: CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT
3098
+ maxOutputTokens: CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT,
3099
+ includeInternal: true,
3100
+ messageTypes: ["chat", "tool-result"]
3024
3101
  },
3025
3102
  filters: {}
3026
3103
  });
@@ -3140,8 +3217,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3140
3217
  }
3141
3218
  });
3142
3219
  const result = object;
3220
+ logger8.info({ result: JSON.stringify(result) }, "DEBUG: Result");
3143
3221
  const summaries = [];
3144
3222
  for (const [componentId, data] of Object.entries(result)) {
3223
+ logger8.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
3145
3224
  if (componentId === "no_relevant_updates") {
3146
3225
  continue;
3147
3226
  }
@@ -3708,10 +3787,10 @@ var AgentSessionManager = class {
3708
3787
  /**
3709
3788
  * Initialize status updates for a session
3710
3789
  */
3711
- initializeStatusUpdates(sessionId, config, summarizerModel) {
3790
+ initializeStatusUpdates(sessionId, config, summarizerModel, baseModel) {
3712
3791
  const session = this.sessions.get(sessionId);
3713
3792
  if (session) {
3714
- session.initializeStatusUpdates(config, summarizerModel);
3793
+ session.initializeStatusUpdates(config, summarizerModel, baseModel);
3715
3794
  } else {
3716
3795
  logger8.error(
3717
3796
  {
@@ -6919,6 +6998,7 @@ var Agent = class {
6919
6998
  __publicField(this, "streamHelper");
6920
6999
  __publicField(this, "streamRequestId");
6921
7000
  __publicField(this, "conversationId");
7001
+ __publicField(this, "delegationId");
6922
7002
  __publicField(this, "artifactComponents", []);
6923
7003
  __publicField(this, "isDelegatedAgent", false);
6924
7004
  __publicField(this, "contextResolver");
@@ -7056,6 +7136,12 @@ var Agent = class {
7056
7136
  setDelegationStatus(isDelegated) {
7057
7137
  this.isDelegatedAgent = isDelegated;
7058
7138
  }
7139
+ /**
7140
+ * Set delegation ID for this agent instance
7141
+ */
7142
+ setDelegationId(delegationId) {
7143
+ this.delegationId = delegationId;
7144
+ }
7059
7145
  /**
7060
7146
  * Get streaming helper if this agent should stream to user
7061
7147
  * Returns undefined for delegated agents to prevent streaming data operations to user
@@ -7066,7 +7152,7 @@ var Agent = class {
7066
7152
  /**
7067
7153
  * Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
7068
7154
  */
7069
- wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType) {
7155
+ wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId) {
7070
7156
  if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
7071
7157
  return toolDefinition;
7072
7158
  }
@@ -7087,23 +7173,59 @@ var Agent = class {
7087
7173
  "agent.id": this.config.agentId || "unknown"
7088
7174
  });
7089
7175
  }
7090
- const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_") || toolName.startsWith("delegate_to_");
7176
+ const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_");
7091
7177
  if (streamRequestId && !isInternalTool) {
7092
7178
  agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, {
7093
7179
  toolName,
7094
7180
  input: args,
7095
- toolCallId
7181
+ toolCallId,
7182
+ relationshipId
7096
7183
  });
7097
7184
  }
7098
7185
  try {
7099
7186
  const result = await originalExecute(args, context);
7100
7187
  const duration = Date.now() - startTime;
7188
+ const toolResultConversationId = this.getToolResultConversationId();
7189
+ if (streamRequestId && !isInternalTool && toolResultConversationId) {
7190
+ try {
7191
+ const messageId = generateId();
7192
+ const messagePayload = {
7193
+ id: messageId,
7194
+ tenantId: this.config.tenantId,
7195
+ projectId: this.config.projectId,
7196
+ conversationId: toolResultConversationId,
7197
+ role: "assistant",
7198
+ content: {
7199
+ text: this.formatToolResult(toolName, args, result, toolCallId)
7200
+ },
7201
+ visibility: "internal",
7202
+ messageType: "tool-result",
7203
+ fromSubAgentId: this.config.id,
7204
+ metadata: {
7205
+ a2a_metadata: {
7206
+ toolName,
7207
+ toolCallId,
7208
+ timestamp: Date.now(),
7209
+ delegationId: this.delegationId,
7210
+ isDelegated: this.isDelegatedAgent
7211
+ }
7212
+ }
7213
+ };
7214
+ await createMessage(dbClient_default)(messagePayload);
7215
+ } catch (error) {
7216
+ logger15.warn(
7217
+ { error, toolName, toolCallId, conversationId: toolResultConversationId },
7218
+ "Failed to store tool result in conversation history"
7219
+ );
7220
+ }
7221
+ }
7101
7222
  if (streamRequestId && !isInternalTool) {
7102
7223
  agentSessionManager.recordEvent(streamRequestId, "tool_result", this.config.id, {
7103
7224
  toolName,
7104
7225
  output: result,
7105
7226
  toolCallId,
7106
- duration
7227
+ duration,
7228
+ relationshipId
7107
7229
  });
7108
7230
  }
7109
7231
  return result;
@@ -7116,7 +7238,8 @@ var Agent = class {
7116
7238
  output: null,
7117
7239
  toolCallId,
7118
7240
  duration,
7119
- error: errorMessage
7241
+ error: errorMessage,
7242
+ relationshipId
7120
7243
  });
7121
7244
  }
7122
7245
  throw error;
@@ -7182,22 +7305,24 @@ var Agent = class {
7182
7305
  }) || [];
7183
7306
  const tools = await Promise.all(mcpTools.map((tool3) => this.getMcpTool(tool3)) || []) || [];
7184
7307
  if (!sessionId) {
7185
- const combinedTools = tools.reduce((acc, tool3) => {
7186
- return Object.assign(acc, tool3);
7187
- }, {});
7188
7308
  const wrappedTools2 = {};
7189
- for (const [toolName, toolDef] of Object.entries(combinedTools)) {
7190
- wrappedTools2[toolName] = this.wrapToolWithStreaming(
7191
- toolName,
7192
- toolDef,
7193
- streamRequestId,
7194
- "mcp"
7195
- );
7309
+ for (const [index, toolSet] of tools.entries()) {
7310
+ const relationshipId = mcpTools[index]?.relationshipId;
7311
+ for (const [toolName, toolDef] of Object.entries(toolSet)) {
7312
+ wrappedTools2[toolName] = this.wrapToolWithStreaming(
7313
+ toolName,
7314
+ toolDef,
7315
+ streamRequestId,
7316
+ "mcp",
7317
+ relationshipId
7318
+ );
7319
+ }
7196
7320
  }
7197
7321
  return wrappedTools2;
7198
7322
  }
7199
7323
  const wrappedTools = {};
7200
- for (const toolSet of tools) {
7324
+ for (const [index, toolSet] of tools.entries()) {
7325
+ const relationshipId = mcpTools[index]?.relationshipId;
7201
7326
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
7202
7327
  if (!isValidTool(originalTool)) {
7203
7328
  logger15.error({ toolName }, "Invalid MCP tool structure - missing required properties");
@@ -7210,7 +7335,7 @@ var Agent = class {
7210
7335
  logger15.debug({ toolName, toolCallId }, "MCP Tool Called");
7211
7336
  try {
7212
7337
  const rawResult = await originalTool.execute(args, { toolCallId });
7213
- if (rawResult && typeof rawResult === "object" && "isError" in rawResult && rawResult.isError) {
7338
+ if (rawResult && typeof rawResult === "object" && rawResult.isError) {
7214
7339
  const errorMessage = rawResult.content?.[0]?.text || "MCP tool returned an error";
7215
7340
  logger15.error(
7216
7341
  { toolName, toolCallId, errorMessage, rawResult },
@@ -7231,7 +7356,8 @@ var Agent = class {
7231
7356
  context: {
7232
7357
  toolName,
7233
7358
  toolCallId,
7234
- errorMessage
7359
+ errorMessage,
7360
+ relationshipId
7235
7361
  }
7236
7362
  });
7237
7363
  }
@@ -7270,7 +7396,8 @@ var Agent = class {
7270
7396
  toolName,
7271
7397
  sessionWrappedTool,
7272
7398
  streamRequestId,
7273
- "mcp"
7399
+ "mcp",
7400
+ relationshipId
7274
7401
  );
7275
7402
  }
7276
7403
  }
@@ -7783,7 +7910,7 @@ var Agent = class {
7783
7910
  inputSchema: tool3.inputSchema || tool3.parameters || {},
7784
7911
  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."
7785
7912
  }));
7786
- const { getConversationScopedArtifacts } = await import('./conversations-FGU5QUYM.js');
7913
+ const { getConversationScopedArtifacts } = await import('./conversations-WAUHDR5J.js');
7787
7914
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
7788
7915
  const referenceArtifacts = await getConversationScopedArtifacts({
7789
7916
  tenantId: this.config.tenantId,
@@ -7895,7 +8022,20 @@ var Agent = class {
7895
8022
  */
7896
8023
  formatToolResult(toolName, args, result, toolCallId) {
7897
8024
  const input = args ? JSON.stringify(args, null, 2) : "No input";
7898
- const output = typeof result === "string" ? result : JSON.stringify(result, null, 2);
8025
+ let parsedResult = result;
8026
+ if (typeof result === "string") {
8027
+ try {
8028
+ parsedResult = JSON.parse(result);
8029
+ } catch (e) {
8030
+ }
8031
+ }
8032
+ const cleanResult = parsedResult && typeof parsedResult === "object" && !Array.isArray(parsedResult) ? {
8033
+ ...parsedResult,
8034
+ result: parsedResult.result && typeof parsedResult.result === "object" && !Array.isArray(parsedResult.result) ? Object.fromEntries(
8035
+ Object.entries(parsedResult.result).filter(([key]) => key !== "_structureHints")
8036
+ ) : parsedResult.result
8037
+ } : parsedResult;
8038
+ const output = typeof cleanResult === "string" ? cleanResult : JSON.stringify(cleanResult, null, 2);
7899
8039
  return `## Tool: ${toolName}
7900
8040
 
7901
8041
  ### \u{1F527} TOOL_CALL_ID: ${toolCallId}
@@ -7906,6 +8046,13 @@ ${input}
7906
8046
  ### Output
7907
8047
  ${output}`;
7908
8048
  }
8049
+ /**
8050
+ * Get the conversation ID for storing tool results
8051
+ * Always uses the real conversation ID - delegation filtering happens at query time
8052
+ */
8053
+ getToolResultConversationId() {
8054
+ return this.conversationId;
8055
+ }
7909
8056
  /**
7910
8057
  * Analyze tool result structure and add helpful path hints for artifact creation
7911
8058
  * Only adds hints when artifact components are available
@@ -8205,13 +8352,17 @@ ${output}`;
8205
8352
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
8206
8353
  if (historyConfig && historyConfig.mode !== "none") {
8207
8354
  if (historyConfig.mode === "full") {
8355
+ const filters = {
8356
+ delegationId: this.delegationId,
8357
+ isDelegated: this.isDelegatedAgent
8358
+ };
8208
8359
  conversationHistory = await getFormattedConversationHistory({
8209
8360
  tenantId: this.config.tenantId,
8210
8361
  projectId: this.config.projectId,
8211
8362
  conversationId: contextId,
8212
8363
  currentMessage: userMessage,
8213
8364
  options: historyConfig,
8214
- filters: {}
8365
+ filters
8215
8366
  });
8216
8367
  } else if (historyConfig.mode === "scoped") {
8217
8368
  conversationHistory = await getFormattedConversationHistory({
@@ -8222,7 +8373,9 @@ ${output}`;
8222
8373
  options: historyConfig,
8223
8374
  filters: {
8224
8375
  subAgentId: this.config.id,
8225
- taskId
8376
+ taskId,
8377
+ delegationId: this.delegationId,
8378
+ isDelegated: this.isDelegatedAgent
8226
8379
  }
8227
8380
  });
8228
8381
  }
@@ -8798,7 +8951,6 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8798
8951
  }
8799
8952
  })
8800
8953
  ]);
8801
- logger16.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
8802
8954
  const enhancedInternalRelations = await Promise.all(
8803
8955
  internalRelations.data.map(async (relation) => {
8804
8956
  try {
@@ -8917,7 +9069,12 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8917
9069
  const stopWhen = "stopWhen" in config.agentSchema ? config.agentSchema.stopWhen : void 0;
8918
9070
  const toolsForAgentResult = await Promise.all(
8919
9071
  toolsForAgent.data.map(async (item) => {
8920
- const mcpTool = await dbResultToMcpTool(item.tool, dbClient_default, credentialStoreRegistry);
9072
+ const mcpTool = await dbResultToMcpTool(
9073
+ item.tool,
9074
+ dbClient_default,
9075
+ credentialStoreRegistry,
9076
+ item.id
9077
+ );
8921
9078
  if (item.selectedTools && item.selectedTools.length > 0) {
8922
9079
  const selectedToolsSet = new Set(item.selectedTools);
8923
9080
  mcpTool.availableTools = mcpTool.availableTools?.filter((tool3) => selectedToolsSet.has(tool3.name)) || [];
@@ -8999,7 +9156,8 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8999
9156
  const mcpTool = await dbResultToMcpTool(
9000
9157
  item.tool,
9001
9158
  dbClient_default,
9002
- credentialStoreRegistry
9159
+ credentialStoreRegistry,
9160
+ item.id
9003
9161
  );
9004
9162
  if (item.selectedTools && item.selectedTools.length > 0) {
9005
9163
  const selectedToolsSet = new Set(item.selectedTools);
@@ -9138,10 +9296,12 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9138
9296
  }
9139
9297
  const streamRequestId = task.context?.metadata?.stream_request_id || task.context?.metadata?.streamRequestId;
9140
9298
  const isDelegation = task.context?.metadata?.isDelegation === true;
9299
+ const delegationId = task.context?.metadata?.delegationId;
9141
9300
  agent.setDelegationStatus(isDelegation);
9301
+ agent.setDelegationId(delegationId);
9142
9302
  if (isDelegation) {
9143
9303
  logger16.info(
9144
- { subAgentId: config.subAgentId, taskId: task.id },
9304
+ { subAgentId: config.subAgentId, taskId: task.id, delegationId },
9145
9305
  "Delegated agent - streaming disabled"
9146
9306
  );
9147
9307
  if (streamRequestId && config.tenantId && config.projectId) {
@@ -9295,7 +9455,7 @@ var createTaskHandlerConfig = async (params) => {
9295
9455
  throw new Error(`Agent not found: ${params.subAgentId}`);
9296
9456
  }
9297
9457
  const effectiveModels = await resolveModelConfig(params.agentId, subAgent);
9298
- const effectiveConversationHistoryConfig = subAgent.conversationHistoryConfig || { mode: "full" };
9458
+ const effectiveConversationHistoryConfig = subAgent.conversationHistoryConfig;
9299
9459
  return {
9300
9460
  tenantId: params.tenantId,
9301
9461
  projectId: params.projectId,
@@ -9639,40 +9799,16 @@ app.post("/a2a", async (c) => {
9639
9799
  });
9640
9800
  var agents_default = app;
9641
9801
  function isTransferTask(result) {
9642
- console.log(
9643
- "[isTransferTask] Checking result:",
9644
- JSON.stringify(
9645
- {
9646
- hasArtifacts: "artifacts" in result,
9647
- artifactsLength: result.kind === "task" ? result.artifacts?.length : 0,
9648
- firstArtifactParts: result.kind === "task" ? result.artifacts?.[0]?.parts?.length : 0,
9649
- allParts: result.kind === "task" ? result.artifacts?.[0]?.parts?.map((p, i) => ({
9650
- index: i,
9651
- kind: p.kind,
9652
- hasData: !!(p.kind === "data" && p.data),
9653
- dataType: p.kind === "data" ? p.data?.type : void 0,
9654
- dataKeys: p.kind === "data" ? Object.keys(p.data) : []
9655
- })) : []
9656
- },
9657
- null,
9658
- 2
9659
- )
9660
- );
9661
9802
  if (!("artifacts" in result) || !result.artifacts) {
9662
- console.log("[isTransferTask] No artifacts found");
9663
9803
  return false;
9664
9804
  }
9665
9805
  const hasTransfer = result.artifacts.some(
9666
9806
  (artifact) => artifact.parts.some((part) => {
9667
9807
  if (part.kind !== "data" || !part.data) return false;
9668
9808
  const isTransfer = typeof part.data === "object" && "type" in part.data && part.data.type === "transfer";
9669
- if (isTransfer) {
9670
- console.log("[isTransferTask] Found transfer data:", JSON.stringify(part.data, null, 2));
9671
- }
9672
9809
  return isTransfer;
9673
9810
  })
9674
9811
  );
9675
- console.log("[isTransferTask] Result:", hasTransfer);
9676
9812
  return hasTransfer;
9677
9813
  }
9678
9814
  function extractTransferData(task) {
@@ -10326,11 +10462,42 @@ var ExecutionHandler = class {
10326
10462
  scopes: { tenantId, projectId, agentId }
10327
10463
  });
10328
10464
  if (agentConfig?.statusUpdates && agentConfig.statusUpdates.enabled !== false) {
10329
- agentSessionManager.initializeStatusUpdates(
10330
- requestId2,
10331
- agentConfig.statusUpdates,
10332
- agentConfig.models?.summarizer
10333
- );
10465
+ try {
10466
+ const agentWithDefault = await getAgentWithDefaultSubAgent(dbClient_default)({
10467
+ scopes: { tenantId, projectId, agentId }
10468
+ });
10469
+ if (agentWithDefault?.defaultSubAgent) {
10470
+ const resolvedModels = await resolveModelConfig(
10471
+ agentId,
10472
+ agentWithDefault.defaultSubAgent
10473
+ );
10474
+ agentSessionManager.initializeStatusUpdates(
10475
+ requestId2,
10476
+ agentConfig.statusUpdates,
10477
+ resolvedModels.summarizer,
10478
+ resolvedModels.base
10479
+ );
10480
+ } else {
10481
+ agentSessionManager.initializeStatusUpdates(
10482
+ requestId2,
10483
+ agentConfig.statusUpdates,
10484
+ agentConfig.models?.summarizer
10485
+ );
10486
+ }
10487
+ } catch (modelError) {
10488
+ logger20.warn(
10489
+ {
10490
+ error: modelError instanceof Error ? modelError.message : "Unknown error",
10491
+ agentId
10492
+ },
10493
+ "Failed to resolve models for status updates, using agent-level config"
10494
+ );
10495
+ agentSessionManager.initializeStatusUpdates(
10496
+ requestId2,
10497
+ agentConfig.statusUpdates,
10498
+ agentConfig.models?.summarizer
10499
+ );
10500
+ }
10334
10501
  }
10335
10502
  } catch (error) {
10336
10503
  logger20.error(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/agents-run-api",
3
- "version": "0.33.1",
3
+ "version": "0.34.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",
@@ -18,6 +18,7 @@
18
18
  "@ai-sdk/gateway": "^1.0.23",
19
19
  "@ai-sdk/google": "^2.0.14",
20
20
  "@ai-sdk/openai": "2.0.11",
21
+ "@ai-sdk/openai-compatible": "^1.0.27",
21
22
  "@ai-sdk/react": "2.0.11",
22
23
  "@alcyone-labs/modelcontextprotocol-sdk": "^1.16.0",
23
24
  "@hono/node-server": "^1.14.3",
@@ -53,7 +54,7 @@
53
54
  "traverse": "^0.6.11",
54
55
  "ts-pattern": "^5.7.1",
55
56
  "zod": "4.1.5",
56
- "@inkeep/agents-core": "^0.33.1"
57
+ "@inkeep/agents-core": "^0.34.0"
57
58
  },
58
59
  "optionalDependencies": {
59
60
  "keytar": "^7.9.0"