@inkeep/agents-run-api 0.1.3 → 0.1.6

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.
Files changed (157) hide show
  1. package/LICENSE.md +7 -0
  2. package/SUPPLEMENTAL_TERMS.md +40 -0
  3. package/dist/chunk-P6IQZWFC.js +239 -0
  4. package/dist/conversations-EUPRCMQZ.js +1 -0
  5. package/dist/index.cjs +8992 -0
  6. package/dist/index.d.cts +15 -0
  7. package/dist/index.d.ts +13 -21
  8. package/dist/index.js +8644 -27
  9. package/package.json +8 -7
  10. package/dist/AgentExecutionServer.d.ts +0 -28
  11. package/dist/AgentExecutionServer.d.ts.map +0 -1
  12. package/dist/AgentExecutionServer.js +0 -41
  13. package/dist/__tests__/setup.d.ts +0 -4
  14. package/dist/__tests__/setup.d.ts.map +0 -1
  15. package/dist/__tests__/setup.js +0 -80
  16. package/dist/__tests__/utils/testProject.d.ts +0 -18
  17. package/dist/__tests__/utils/testProject.d.ts.map +0 -1
  18. package/dist/__tests__/utils/testProject.js +0 -26
  19. package/dist/__tests__/utils/testRequest.d.ts +0 -8
  20. package/dist/__tests__/utils/testRequest.d.ts.map +0 -1
  21. package/dist/__tests__/utils/testRequest.js +0 -32
  22. package/dist/__tests__/utils/testTenant.d.ts +0 -64
  23. package/dist/__tests__/utils/testTenant.d.ts.map +0 -1
  24. package/dist/__tests__/utils/testTenant.js +0 -71
  25. package/dist/a2a/client.d.ts +0 -182
  26. package/dist/a2a/client.d.ts.map +0 -1
  27. package/dist/a2a/client.js +0 -645
  28. package/dist/a2a/handlers.d.ts +0 -4
  29. package/dist/a2a/handlers.d.ts.map +0 -1
  30. package/dist/a2a/handlers.js +0 -656
  31. package/dist/a2a/transfer.d.ts +0 -18
  32. package/dist/a2a/transfer.d.ts.map +0 -1
  33. package/dist/a2a/transfer.js +0 -22
  34. package/dist/a2a/types.d.ts +0 -63
  35. package/dist/a2a/types.d.ts.map +0 -1
  36. package/dist/a2a/types.js +0 -1
  37. package/dist/agents/Agent.d.ts +0 -154
  38. package/dist/agents/Agent.d.ts.map +0 -1
  39. package/dist/agents/Agent.js +0 -1110
  40. package/dist/agents/ModelFactory.d.ts +0 -62
  41. package/dist/agents/ModelFactory.d.ts.map +0 -1
  42. package/dist/agents/ModelFactory.js +0 -208
  43. package/dist/agents/SystemPromptBuilder.d.ts +0 -14
  44. package/dist/agents/SystemPromptBuilder.d.ts.map +0 -1
  45. package/dist/agents/SystemPromptBuilder.js +0 -62
  46. package/dist/agents/ToolSessionManager.d.ts +0 -61
  47. package/dist/agents/ToolSessionManager.d.ts.map +0 -1
  48. package/dist/agents/ToolSessionManager.js +0 -143
  49. package/dist/agents/artifactTools.d.ts +0 -30
  50. package/dist/agents/artifactTools.d.ts.map +0 -1
  51. package/dist/agents/artifactTools.js +0 -463
  52. package/dist/agents/generateTaskHandler.d.ts +0 -41
  53. package/dist/agents/generateTaskHandler.d.ts.map +0 -1
  54. package/dist/agents/generateTaskHandler.js +0 -350
  55. package/dist/agents/relationTools.d.ts +0 -35
  56. package/dist/agents/relationTools.d.ts.map +0 -1
  57. package/dist/agents/relationTools.js +0 -246
  58. package/dist/agents/types.d.ts +0 -23
  59. package/dist/agents/types.d.ts.map +0 -1
  60. package/dist/agents/types.js +0 -1
  61. package/dist/agents/versions/V1Config.d.ts +0 -21
  62. package/dist/agents/versions/V1Config.d.ts.map +0 -1
  63. package/dist/agents/versions/V1Config.js +0 -285
  64. package/dist/app.d.ts +0 -12
  65. package/dist/app.d.ts.map +0 -1
  66. package/dist/app.js +0 -216
  67. package/dist/data/agentGraph.d.ts +0 -4
  68. package/dist/data/agentGraph.d.ts.map +0 -1
  69. package/dist/data/agentGraph.js +0 -73
  70. package/dist/data/agents.d.ts +0 -4
  71. package/dist/data/agents.d.ts.map +0 -1
  72. package/dist/data/agents.js +0 -78
  73. package/dist/data/conversations.d.ts +0 -59
  74. package/dist/data/conversations.d.ts.map +0 -1
  75. package/dist/data/conversations.js +0 -216
  76. package/dist/data/db/clean.d.ts +0 -6
  77. package/dist/data/db/clean.d.ts.map +0 -1
  78. package/dist/data/db/clean.js +0 -77
  79. package/dist/data/db/dbClient.d.ts +0 -3
  80. package/dist/data/db/dbClient.d.ts.map +0 -1
  81. package/dist/data/db/dbClient.js +0 -13
  82. package/dist/env.d.ts +0 -45
  83. package/dist/env.d.ts.map +0 -1
  84. package/dist/env.js +0 -64
  85. package/dist/handlers/executionHandler.d.ts +0 -36
  86. package/dist/handlers/executionHandler.d.ts.map +0 -1
  87. package/dist/handlers/executionHandler.js +0 -399
  88. package/dist/index.d.ts.map +0 -1
  89. package/dist/instrumentation.d.ts +0 -13
  90. package/dist/instrumentation.d.ts.map +0 -1
  91. package/dist/instrumentation.js +0 -66
  92. package/dist/logger.d.ts +0 -4
  93. package/dist/logger.d.ts.map +0 -1
  94. package/dist/logger.js +0 -32
  95. package/dist/middleware/api-key-auth.d.ts +0 -22
  96. package/dist/middleware/api-key-auth.d.ts.map +0 -1
  97. package/dist/middleware/api-key-auth.js +0 -139
  98. package/dist/middleware/index.d.ts +0 -2
  99. package/dist/middleware/index.d.ts.map +0 -1
  100. package/dist/middleware/index.js +0 -1
  101. package/dist/openapi.d.ts +0 -2
  102. package/dist/openapi.d.ts.map +0 -1
  103. package/dist/openapi.js +0 -36
  104. package/dist/routes/agents.d.ts +0 -10
  105. package/dist/routes/agents.d.ts.map +0 -1
  106. package/dist/routes/agents.js +0 -158
  107. package/dist/routes/chat.d.ts +0 -10
  108. package/dist/routes/chat.d.ts.map +0 -1
  109. package/dist/routes/chat.js +0 -307
  110. package/dist/routes/chatDataStream.d.ts +0 -10
  111. package/dist/routes/chatDataStream.d.ts.map +0 -1
  112. package/dist/routes/chatDataStream.js +0 -179
  113. package/dist/routes/mcp.d.ts +0 -10
  114. package/dist/routes/mcp.d.ts.map +0 -1
  115. package/dist/routes/mcp.js +0 -500
  116. package/dist/server.d.ts +0 -5
  117. package/dist/server.d.ts.map +0 -1
  118. package/dist/server.js +0 -61
  119. package/dist/tracer.d.ts +0 -24
  120. package/dist/tracer.d.ts.map +0 -1
  121. package/dist/tracer.js +0 -107
  122. package/dist/types/chat.d.ts +0 -25
  123. package/dist/types/chat.d.ts.map +0 -1
  124. package/dist/types/chat.js +0 -1
  125. package/dist/types/execution-context.d.ts +0 -14
  126. package/dist/types/execution-context.d.ts.map +0 -1
  127. package/dist/types/execution-context.js +0 -14
  128. package/dist/utils/agent-operations.d.ts +0 -92
  129. package/dist/utils/agent-operations.d.ts.map +0 -1
  130. package/dist/utils/agent-operations.js +0 -78
  131. package/dist/utils/artifact-component-schema.d.ts +0 -29
  132. package/dist/utils/artifact-component-schema.d.ts.map +0 -1
  133. package/dist/utils/artifact-component-schema.js +0 -119
  134. package/dist/utils/artifact-parser.d.ts +0 -71
  135. package/dist/utils/artifact-parser.d.ts.map +0 -1
  136. package/dist/utils/artifact-parser.js +0 -251
  137. package/dist/utils/cleanup.d.ts +0 -19
  138. package/dist/utils/cleanup.d.ts.map +0 -1
  139. package/dist/utils/cleanup.js +0 -66
  140. package/dist/utils/data-component-schema.d.ts +0 -6
  141. package/dist/utils/data-component-schema.d.ts.map +0 -1
  142. package/dist/utils/data-component-schema.js +0 -43
  143. package/dist/utils/graph-session.d.ts +0 -200
  144. package/dist/utils/graph-session.d.ts.map +0 -1
  145. package/dist/utils/graph-session.js +0 -1016
  146. package/dist/utils/incremental-stream-parser.d.ts +0 -57
  147. package/dist/utils/incremental-stream-parser.d.ts.map +0 -1
  148. package/dist/utils/incremental-stream-parser.js +0 -289
  149. package/dist/utils/response-formatter.d.ts +0 -27
  150. package/dist/utils/response-formatter.d.ts.map +0 -1
  151. package/dist/utils/response-formatter.js +0 -160
  152. package/dist/utils/stream-helpers.d.ts +0 -174
  153. package/dist/utils/stream-helpers.d.ts.map +0 -1
  154. package/dist/utils/stream-helpers.js +0 -466
  155. package/dist/utils/stream-registry.d.ts +0 -18
  156. package/dist/utils/stream-registry.d.ts.map +0 -1
  157. package/dist/utils/stream-registry.js +0 -33
@@ -1,350 +0,0 @@
1
- import { getAgentById, getAgentGraph, getArtifactComponentsForAgent, getDataComponentsForAgent, getRelatedAgentsForGraph, getToolsForAgent, TaskState, } from '@inkeep/agents-core';
2
- import destr from 'destr'; // safe JSON.parse-if-JSON
3
- import { nanoid } from 'nanoid';
4
- import traverse from 'traverse'; // tiny object walker
5
- import dbClient from '../data/db/dbClient';
6
- import { getLogger } from '../logger';
7
- import { Agent } from './Agent';
8
- /** Turn any string value that is valid JSON into an object/array (in place). */
9
- export function parseEmbeddedJson(data) {
10
- return traverse(data).map(function (x) {
11
- if (typeof x === 'string') {
12
- const v = destr(x); // returns original string if not JSON
13
- if (v !== x && (Array.isArray(v) || (v && typeof v === 'object'))) {
14
- this.update(v); // replace the string with the parsed value
15
- }
16
- }
17
- });
18
- }
19
- const logger = getLogger('generateTaskHandler');
20
- export const createTaskHandler = (config, credentialStoreRegistry) => {
21
- return async (task) => {
22
- try {
23
- // Extract the user message from the task
24
- const userMessage = task.input.parts
25
- .filter((part) => part.text)
26
- .map((part) => part.text)
27
- .join(' ');
28
- if (!userMessage.trim()) {
29
- return {
30
- status: {
31
- state: TaskState.Failed,
32
- message: 'No text content found in task input',
33
- },
34
- artifacts: [],
35
- };
36
- }
37
- const [{ internalRelations, externalRelations }, toolsForAgent, dataComponents, artifactComponents,] = await Promise.all([
38
- getRelatedAgentsForGraph(dbClient)({
39
- scopes: {
40
- tenantId: config.tenantId,
41
- projectId: config.projectId,
42
- },
43
- graphId: config.graphId,
44
- agentId: config.agentId,
45
- }),
46
- getToolsForAgent(dbClient)({
47
- scopes: {
48
- tenantId: config.tenantId,
49
- projectId: config.projectId,
50
- },
51
- agentId: config.agentId,
52
- }),
53
- getDataComponentsForAgent(dbClient)({
54
- scopes: {
55
- tenantId: config.tenantId,
56
- projectId: config.projectId,
57
- },
58
- agentId: config.agentId,
59
- }),
60
- getArtifactComponentsForAgent(dbClient)({
61
- scopes: {
62
- tenantId: config.tenantId,
63
- projectId: config.projectId,
64
- },
65
- agentId: config.agentId,
66
- }),
67
- ]);
68
- logger.info({ toolsForAgent, internalRelations, externalRelations }, 'agent stuff');
69
- // Check if this is an internal agent (has prompt)
70
- const agentPrompt = 'prompt' in config.agentSchema ? config.agentSchema.prompt : '';
71
- const models = 'models' in config.agentSchema ? config.agentSchema.models : undefined;
72
- const stopWhen = 'stopWhen' in config.agentSchema ? config.agentSchema.stopWhen : undefined;
73
- const agent = new Agent({
74
- id: config.agentId,
75
- tenantId: config.tenantId,
76
- projectId: config.projectId,
77
- graphId: config.graphId,
78
- baseUrl: config.baseUrl,
79
- apiKey: config.apiKey,
80
- name: config.name,
81
- description: config.description || '',
82
- agentPrompt,
83
- models: models || undefined,
84
- stopWhen: stopWhen || undefined,
85
- agentRelations: internalRelations.map((relation) => ({
86
- id: relation.id,
87
- tenantId: config.tenantId,
88
- projectId: config.projectId,
89
- graphId: config.graphId,
90
- baseUrl: config.baseUrl,
91
- apiKey: config.apiKey,
92
- name: relation.name,
93
- description: relation.description,
94
- agentPrompt: '',
95
- delegateRelations: [],
96
- agentRelations: [],
97
- transferRelations: [],
98
- })),
99
- transferRelations: internalRelations
100
- .filter((relation) => relation.relationType === 'transfer')
101
- .map((relation) => ({
102
- baseUrl: config.baseUrl,
103
- apiKey: config.apiKey,
104
- id: relation.id,
105
- tenantId: config.tenantId,
106
- projectId: config.projectId,
107
- graphId: config.graphId,
108
- name: relation.name,
109
- description: relation.description,
110
- agentPrompt: '',
111
- delegateRelations: [],
112
- agentRelations: [],
113
- transferRelations: [],
114
- })),
115
- delegateRelations: [
116
- // Internal delegate relations
117
- ...internalRelations
118
- .filter((relation) => relation.relationType === 'delegate')
119
- .map((relation) => ({
120
- type: 'internal',
121
- config: {
122
- id: relation.id,
123
- tenantId: config.tenantId,
124
- projectId: config.projectId,
125
- graphId: config.graphId,
126
- baseUrl: config.baseUrl,
127
- apiKey: config.apiKey,
128
- name: relation.name,
129
- description: relation.description,
130
- agentPrompt: '',
131
- delegateRelations: [],
132
- agentRelations: [],
133
- transferRelations: [],
134
- },
135
- })),
136
- // External delegate relations
137
- ...externalRelations.map((relation) => ({
138
- type: 'external',
139
- config: {
140
- id: relation.externalAgent.id,
141
- name: relation.externalAgent.name,
142
- description: relation.externalAgent.description || '',
143
- baseUrl: relation.externalAgent.baseUrl,
144
- relationType: relation.relationType || undefined,
145
- },
146
- })),
147
- ],
148
- tools: toolsForAgent.data.map((item) => ({
149
- ...item.tool,
150
- capabilities: item.tool.capabilities || undefined,
151
- lastHealthCheck: item.tool.lastHealthCheck
152
- ? new Date(item.tool.lastHealthCheck)
153
- : undefined,
154
- lastToolsSync: item.tool.lastToolsSync
155
- ? new Date(item.tool.lastToolsSync)
156
- : undefined,
157
- createdAt: new Date(item.tool.createdAt),
158
- updatedAt: new Date(item.tool.updatedAt),
159
- })) ?? [],
160
- functionTools: [], // All tools are now handled via MCP servers
161
- dataComponents: dataComponents,
162
- artifactComponents: artifactComponents,
163
- contextConfigId: config.contextConfigId || undefined,
164
- conversationHistoryConfig: config.conversationHistoryConfig,
165
- }, credentialStoreRegistry);
166
- // More robust contextId resolution for delegation scenarios
167
- let contextId = task.context?.conversationId;
168
- // If contextId is not set in task.context, try to extract it from the task.id
169
- // Many tasks are created with IDs like "task_math-demo-123456-chatcmpl-789"
170
- if (!contextId || contextId === 'default' || contextId === '') {
171
- const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
172
- if (taskIdMatch) {
173
- contextId = taskIdMatch[1];
174
- logger.info({
175
- taskId: task.id,
176
- extractedContextId: contextId,
177
- agentId: config.agentId,
178
- }, 'Extracted contextId from task ID for delegation');
179
- }
180
- else {
181
- contextId = 'default';
182
- }
183
- }
184
- // Extract streaming context from task metadata and get streamHelper from registry
185
- const streamRequestId = task.context?.metadata?.stream_request_id || task.context?.metadata?.streamRequestId;
186
- // Check if this is a delegation - delegated agents should not stream to user
187
- const isDelegation = task.context?.metadata?.isDelegation === true;
188
- agent.setDelegationStatus(isDelegation);
189
- if (isDelegation) {
190
- logger.info({ agentId: config.agentId, taskId: task.id }, 'Delegated agent - streaming disabled');
191
- }
192
- const response = await agent.generate(userMessage, {
193
- contextId,
194
- metadata: {
195
- conversationId: contextId,
196
- taskId: task.id,
197
- threadId: contextId, // using conversationId as threadId for now
198
- streamRequestId: streamRequestId,
199
- },
200
- });
201
- // Process steps to extract tool calls and results from content arrays
202
- const stepContents = response.steps && Array.isArray(response.steps)
203
- ? response.steps.flatMap((step) => {
204
- return step.content && Array.isArray(step.content) ? step.content : [];
205
- })
206
- : [];
207
- const allToolCalls = stepContents.filter((content) => content.type === 'tool-call');
208
- const allToolResults = stepContents.filter((content) => content.type === 'tool-result');
209
- const allThoughts = stepContents.filter((content) => content.type === 'text');
210
- if (allToolCalls.length > 0) {
211
- for (const toolCall of allToolCalls) {
212
- // Check for transfer tool calls (we support multiple patterns)
213
- if (toolCall.toolName.includes('transfer') ||
214
- toolCall.toolName.includes('transferToRefundAgent')) {
215
- // Look for the tool result
216
- const toolResult = allToolResults.find((result) => result.toolCallId === toolCall.toolCallId);
217
- // Validate transfer result with proper type checking
218
- const isValidTransferResult = (output) => {
219
- return (typeof output === 'object' &&
220
- output !== null &&
221
- 'type' in output &&
222
- 'target' in output &&
223
- output.type === 'transfer' &&
224
- typeof output.target === 'string' &&
225
- (output.reason === undefined || typeof output.reason === 'string'));
226
- };
227
- //In the agent.generate response, response.text is not always populated. In that case, use allThoughts to get the last text part found in the steps array.
228
- const responseText = response.text ||
229
- (response.object ? JSON.stringify(response.object) : '');
230
- const transferReason = responseText ||
231
- allThoughts[allThoughts.length - 1]?.text ||
232
- 'Agent requested transfer. No reason provided.';
233
- if (toolResult?.output && isValidTransferResult(toolResult.output)) {
234
- const transferResult = toolResult.output;
235
- // Return transfer indication in A2A format
236
- return {
237
- status: {
238
- state: TaskState.Completed,
239
- message: `Transfer requested to ${transferResult.target}`,
240
- },
241
- artifacts: [
242
- {
243
- artifactId: nanoid(),
244
- parts: [
245
- {
246
- kind: 'data',
247
- data: {
248
- type: 'transfer',
249
- target: transferResult.target,
250
- task_id: task.id,
251
- reason: transferReason,
252
- original_message: userMessage,
253
- },
254
- },
255
- ],
256
- },
257
- ],
258
- };
259
- }
260
- }
261
- }
262
- }
263
- // Use formatted content parts if available, otherwise fall back to response.text
264
- const parts = (response.formattedContent?.parts || []).map((part) => ({
265
- kind: part.kind,
266
- ...(part.kind === 'text' && { text: part.text }),
267
- ...(part.kind === 'data' && { data: part.data }),
268
- }));
269
- return {
270
- status: { state: TaskState.Completed },
271
- artifacts: [
272
- {
273
- artifactId: nanoid(),
274
- parts,
275
- },
276
- ],
277
- };
278
- }
279
- catch (error) {
280
- console.error('Task handler error:', error);
281
- return {
282
- status: {
283
- state: TaskState.Failed,
284
- message: error instanceof Error ? error.message : 'Unknown error occurred',
285
- },
286
- artifacts: [],
287
- };
288
- }
289
- };
290
- };
291
- /**
292
- * Serializes a TaskHandlerConfig to JSON
293
- */
294
- export const serializeTaskHandlerConfig = (config) => {
295
- return JSON.stringify(config, null, 2);
296
- };
297
- /**
298
- * Deserializes a TaskHandlerConfig from JSON
299
- */
300
- export const deserializeTaskHandlerConfig = (configJson) => {
301
- return JSON.parse(configJson);
302
- };
303
- /**
304
- * Creates a task handler configuration from agent data
305
- */
306
- export const createTaskHandlerConfig = async (params) => {
307
- const agent = await getAgentById(dbClient)({
308
- scopes: {
309
- tenantId: params.tenantId,
310
- projectId: params.projectId,
311
- },
312
- agentId: params.agentId,
313
- });
314
- const agentGraph = await getAgentGraph(dbClient)({
315
- scopes: {
316
- tenantId: params.tenantId,
317
- projectId: params.projectId,
318
- },
319
- graphId: params.graphId,
320
- });
321
- if (!agent) {
322
- throw new Error(`Agent not found: ${params.agentId}`);
323
- }
324
- // Inherit graph models if agent doesn't have one
325
- const effectiveModels = agent.models || agentGraph?.models || undefined;
326
- const effectiveConversationHistoryConfig = agent.conversationHistoryConfig || { mode: 'full' };
327
- return {
328
- tenantId: params.tenantId,
329
- projectId: params.projectId,
330
- graphId: params.graphId,
331
- agentId: params.agentId,
332
- agentSchema: {
333
- id: agent.id,
334
- name: agent.name,
335
- description: agent.description,
336
- prompt: agent.prompt,
337
- models: effectiveModels || null,
338
- conversationHistoryConfig: effectiveConversationHistoryConfig || null,
339
- stopWhen: agent.stopWhen || null,
340
- createdAt: agent.createdAt,
341
- updatedAt: agent.updatedAt,
342
- },
343
- baseUrl: params.baseUrl,
344
- apiKey: params.apiKey,
345
- name: agent.name,
346
- description: agent.description,
347
- conversationHistoryConfig: effectiveConversationHistoryConfig,
348
- contextConfigId: agentGraph?.contextConfigId || undefined,
349
- };
350
- };
@@ -1,35 +0,0 @@
1
- import { type CredentialStoreRegistry } from '@inkeep/agents-core';
2
- import type { AgentConfig, DelegateRelation } from './Agent';
3
- export declare const createTransferToAgentTool: ({ transferConfig, callingAgentId, agent, streamRequestId, }: {
4
- transferConfig: AgentConfig;
5
- callingAgentId: string;
6
- agent: any;
7
- streamRequestId?: string;
8
- }) => import("ai").Tool<Record<string, never>, {
9
- type: string;
10
- target: string;
11
- fromAgentId: string;
12
- }>;
13
- export declare function createDelegateToAgentTool({ delegateConfig, callingAgentId, tenantId, projectId, graphId, contextId, metadata, sessionId, agent, credentialStoreRegistry, }: {
14
- delegateConfig: DelegateRelation;
15
- callingAgentId: string;
16
- tenantId: string;
17
- projectId: string;
18
- graphId: string;
19
- contextId: string;
20
- metadata: {
21
- conversationId: string;
22
- threadId: string;
23
- streamRequestId?: string;
24
- streamBaseUrl?: string;
25
- };
26
- sessionId?: string;
27
- agent: any;
28
- credentialStoreRegistry?: CredentialStoreRegistry;
29
- }): import("ai").Tool<{
30
- message: string;
31
- }, {
32
- toolCallId: any;
33
- result: import("@inkeep/agents-core").Message | import("@inkeep/agents-core").Task;
34
- }>;
35
- //# sourceMappingURL=relationTools.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"relationTools.d.ts","sourceRoot":"","sources":["../../src/agents/relationTools.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,uBAAuB,EAK7B,MAAM,qBAAqB,CAAC;AAW7B,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AA2B7D,eAAO,MAAM,yBAAyB,GAAI,6DAKvC;IACD,cAAc,EAAE,WAAW,CAAC;IAC5B,cAAc,EAAE,MAAM,CAAC;IACvB,KAAK,EAAE,GAAG,CAAC;IACX,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;;;;EAsCA,CAAC;AAEF,wBAAgB,yBAAyB,CAAC,EACxC,cAAc,EACd,cAAc,EACd,QAAQ,EACR,SAAS,EACT,OAAO,EACP,SAAS,EACT,QAAQ,EACR,SAAS,EACT,KAAK,EACL,uBAAuB,GACxB,EAAE;IACD,cAAc,EAAE,gBAAgB,CAAC;IACjC,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE;QACR,cAAc,EAAE,MAAM,CAAC;QACvB,QAAQ,EAAE,MAAM,CAAC;QACjB,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,GAAG,CAAC;IACX,uBAAuB,CAAC,EAAE,uBAAuB,CAAC;CACnD;;;;;GAsNA"}
@@ -1,246 +0,0 @@
1
- import { ContextResolver, CredentialStuffer, createMessage, getCredentialReference, getExternalAgent, } from '@inkeep/agents-core';
2
- import { trace } from '@opentelemetry/api';
3
- import { tool } from 'ai';
4
- import { nanoid } from 'nanoid';
5
- import z from 'zod';
6
- import { A2AClient } from '../a2a/client';
7
- import { saveA2AMessageResponse } from '../data/conversations';
8
- import dbClient from '../data/db/dbClient';
9
- import { getLogger } from '../logger';
10
- import { graphSessionManager } from '../utils/graph-session';
11
- import { toolSessionManager } from './ToolSessionManager';
12
- const logger = getLogger('relationships Tools');
13
- const generateTransferToolDescription = (config) => {
14
- return `Hand off the conversation to agent ${config.id}.
15
-
16
- Agent Information:
17
- - ID: ${config.id}
18
- - Name: ${config.name ?? 'No name provided'}
19
- - Description: ${config.description ?? 'No description provided'}
20
-
21
- Hand off the conversation to agent ${config.id} when the user's request would be better handled by this specialized agent.`;
22
- };
23
- const generateDelegateToolDescription = (config) => {
24
- return `Delegate a specific task to another agent.
25
-
26
- Agent Information:
27
- - ID: ${config.id}
28
- - Name: ${config.name}
29
- - Description: ${config.description || 'No description provided'}
30
-
31
- Delegate a specific task to agent ${config.id} when it seems like the agent can do relevant work.`;
32
- };
33
- export const createTransferToAgentTool = ({ transferConfig, callingAgentId, agent, streamRequestId, }) => {
34
- return tool({
35
- description: generateTransferToolDescription(transferConfig),
36
- inputSchema: z.object({}),
37
- execute: async () => {
38
- // Add span attributes to indicate transfer source and target
39
- const activeSpan = trace.getActiveSpan();
40
- if (activeSpan) {
41
- activeSpan.setAttributes({
42
- 'transfer.from_agent_id': callingAgentId,
43
- 'transfer.to_agent_id': transferConfig.id ?? 'unknown',
44
- });
45
- }
46
- logger.info({
47
- transferTo: transferConfig.id ?? 'unknown',
48
- fromAgent: callingAgentId,
49
- }, 'invoked transferToAgentTool');
50
- // Record transfer event in GraphSession
51
- if (streamRequestId) {
52
- graphSessionManager.recordEvent(streamRequestId, 'transfer', callingAgentId, {
53
- fromAgent: callingAgentId,
54
- targetAgent: transferConfig.id ?? 'unknown',
55
- reason: `Transfer to ${transferConfig.name || transferConfig.id}`,
56
- });
57
- }
58
- return {
59
- type: 'transfer',
60
- target: transferConfig.id ?? 'unknown',
61
- fromAgentId: callingAgentId, // Include the calling agent ID for tracking
62
- };
63
- },
64
- });
65
- };
66
- export function createDelegateToAgentTool({ delegateConfig, callingAgentId, tenantId, projectId, graphId, contextId, metadata, sessionId, agent, credentialStoreRegistry, }) {
67
- return tool({
68
- description: generateDelegateToolDescription(delegateConfig.config),
69
- inputSchema: z.object({ message: z.string() }),
70
- execute: async (input, context) => {
71
- // Generate unique delegation ID for tracking
72
- const delegationId = `del_${nanoid()}`;
73
- // Add span attributes to indicate delegation source and target
74
- const activeSpan = trace.getActiveSpan();
75
- if (activeSpan) {
76
- activeSpan.setAttributes({
77
- 'delegation.from_agent_id': callingAgentId,
78
- 'delegation.to_agent_id': delegateConfig.config.id ?? 'unknown',
79
- 'delegation.id': delegationId,
80
- });
81
- }
82
- // Record delegation sent event in GraphSession
83
- if (metadata.streamRequestId) {
84
- graphSessionManager.recordEvent(metadata.streamRequestId, 'delegation_sent', callingAgentId, {
85
- delegationId,
86
- fromAgent: callingAgentId,
87
- targetAgent: delegateConfig.config.id,
88
- taskDescription: input.message,
89
- });
90
- }
91
- const isInternal = delegateConfig.type === 'internal';
92
- // Get the base URL for the agent
93
- let agentBaseUrl;
94
- let resolvedHeaders = {};
95
- if (!isInternal) {
96
- agentBaseUrl = delegateConfig.config.baseUrl;
97
- // For external agents, fetch configuration
98
- const externalAgent = await getExternalAgent(dbClient)({
99
- scopes: {
100
- tenantId,
101
- projectId,
102
- },
103
- agentId: delegateConfig.config.id,
104
- });
105
- // If the external agent has a credential reference ID or headers, resolve them
106
- if (externalAgent &&
107
- (externalAgent.credentialReferenceId || externalAgent.headers) &&
108
- credentialStoreRegistry) {
109
- const contextResolver = new ContextResolver(tenantId, projectId, dbClient, credentialStoreRegistry);
110
- const credentialStuffer = new CredentialStuffer(credentialStoreRegistry, contextResolver);
111
- const credentialContext = {
112
- tenantId,
113
- projectId,
114
- conversationId: metadata.conversationId,
115
- contextConfigId: contextId,
116
- metadata: metadata,
117
- };
118
- let storeReference;
119
- if (externalAgent.credentialReferenceId) {
120
- // Get credential store configuration
121
- const credentialReference = await getCredentialReference(dbClient)({
122
- scopes: {
123
- tenantId,
124
- projectId,
125
- },
126
- id: externalAgent.credentialReferenceId,
127
- });
128
- if (credentialReference) {
129
- storeReference = {
130
- credentialStoreId: credentialReference.credentialStoreId,
131
- retrievalParams: credentialReference.retrievalParams || {},
132
- };
133
- }
134
- }
135
- // Resolve credentials using CredentialStuffer
136
- resolvedHeaders = await credentialStuffer.getCredentialHeaders({
137
- context: credentialContext,
138
- storeReference,
139
- headers: externalAgent.headers || undefined,
140
- });
141
- }
142
- }
143
- else {
144
- resolvedHeaders = {
145
- Authorization: `Bearer ${delegateConfig.config.apiKey}`,
146
- 'x-inkeep-tenant-id': tenantId,
147
- 'x-inkeep-project-id': projectId,
148
- 'x-inkeep-graph-id': graphId,
149
- 'x-inkeep-agent-id': delegateConfig.config.id,
150
- };
151
- }
152
- // Configure retry behavior for A2A client with custom settings and resolved headers
153
- const a2aClient = new A2AClient(delegateConfig.config.baseUrl, {
154
- headers: resolvedHeaders,
155
- retryConfig: {
156
- strategy: 'backoff',
157
- retryConnectionErrors: true,
158
- statusCodes: ['429', '500', '502', '503', '504'],
159
- backoff: {
160
- initialInterval: 100,
161
- maxInterval: 10000,
162
- exponent: 2,
163
- maxElapsedTime: 20000, // 1 minute max retry time
164
- },
165
- },
166
- });
167
- // Create the message to send to the agent
168
- // Keep streamRequestId for GraphSession access, add isDelegation flag to prevent streaming
169
- const messageToSend = {
170
- role: 'agent',
171
- parts: [{ text: input.message, kind: 'text' }],
172
- messageId: nanoid(),
173
- kind: 'message',
174
- contextId,
175
- metadata: {
176
- ...metadata, // Keep all metadata including streamRequestId
177
- isDelegation: true, // Flag to prevent streaming in delegated agents
178
- delegationId, // Include delegation ID for tracking
179
- ...(isInternal
180
- ? { fromAgentId: callingAgentId }
181
- : { fromExternalAgentId: callingAgentId }),
182
- },
183
- };
184
- logger.info({ messageToSend }, 'messageToSend');
185
- // Record the outgoing message to the agent
186
- await createMessage(dbClient)({
187
- id: nanoid(),
188
- tenantId: tenantId,
189
- projectId: projectId,
190
- conversationId: contextId,
191
- role: 'agent',
192
- content: {
193
- text: input.message,
194
- },
195
- visibility: isInternal ? 'internal' : 'external',
196
- messageType: 'a2a-request',
197
- fromAgentId: callingAgentId,
198
- ...(isInternal
199
- ? { toAgentId: delegateConfig.config.id }
200
- : { toExternalAgentId: delegateConfig.config.id }),
201
- });
202
- const response = await a2aClient.sendMessage({
203
- message: messageToSend,
204
- });
205
- if (response.error) {
206
- throw new Error(response.error.message);
207
- }
208
- // Save the response using the reusable function
209
- await saveA2AMessageResponse(response, {
210
- tenantId,
211
- projectId,
212
- conversationId: contextId,
213
- messageType: 'a2a-response',
214
- visibility: isInternal ? 'internal' : 'external',
215
- toAgentId: callingAgentId,
216
- ...(isInternal
217
- ? { fromAgentId: delegateConfig.config.id }
218
- : { fromExternalAgentId: delegateConfig.config.id }),
219
- });
220
- // Record the delegation result as a tool result for the parent agent
221
- if (sessionId && context?.toolCallId) {
222
- const toolResult = {
223
- toolCallId: context.toolCallId,
224
- toolName: `delegate_to_${delegateConfig.config.id}`,
225
- args: input,
226
- result: response.result,
227
- timestamp: Date.now(),
228
- };
229
- toolSessionManager.recordToolResult(sessionId, toolResult);
230
- }
231
- // Record delegation returned event in GraphSession
232
- if (metadata.streamRequestId) {
233
- graphSessionManager.recordEvent(metadata.streamRequestId, 'delegation_returned', callingAgentId, {
234
- delegationId,
235
- fromAgent: delegateConfig.config.id,
236
- targetAgent: callingAgentId,
237
- result: response.result,
238
- });
239
- }
240
- return {
241
- toolCallId: context?.toolCallId,
242
- result: response.result,
243
- };
244
- },
245
- });
246
- }
@@ -1,23 +0,0 @@
1
- import type { Artifact, ArtifactComponentApiInsert, DataComponentApiInsert } from '@inkeep/agents-core';
2
- export interface VersionConfig<TConfig> {
3
- templateFiles: string[];
4
- assemble(templates: Map<string, string>, config: TConfig): string;
5
- }
6
- export interface SystemPromptV1 {
7
- corePrompt: string;
8
- graphPrompt?: string;
9
- artifacts: Artifact[];
10
- tools: ToolData[];
11
- dataComponents: DataComponentApiInsert[];
12
- artifactComponents?: ArtifactComponentApiInsert[];
13
- isThinkingPreparation?: boolean;
14
- hasTransferRelations?: boolean;
15
- hasDelegateRelations?: boolean;
16
- }
17
- export interface ToolData {
18
- name: string;
19
- description?: string;
20
- inputSchema?: Record<string, unknown>;
21
- usageGuidelines?: string;
22
- }
23
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/agents/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,QAAQ,EACR,0BAA0B,EAC1B,sBAAsB,EACvB,MAAM,qBAAqB,CAAC;AAG7B,MAAM,WAAW,aAAa,CAAC,OAAO;IACpC,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,GAAG,MAAM,CAAC;CACnE;AAED,MAAM,WAAW,cAAc;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,QAAQ,EAAE,CAAC;IACtB,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,cAAc,EAAE,sBAAsB,EAAE,CAAC;IACzC,kBAAkB,CAAC,EAAE,0BAA0B,EAAE,CAAC;IAClD,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B"}
@@ -1 +0,0 @@
1
- export {};