@inkeep/agents-core 0.1.4 → 0.1.7

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 (278) hide show
  1. package/README.md +2 -2
  2. package/SUPPLEMENTAL_TERMS.md +40 -0
  3. package/dist/chunk-BMKWVKI2.js +126 -0
  4. package/dist/chunk-H2F72PDA.js +15 -0
  5. package/dist/chunk-MKBO26DX.js +9 -0
  6. package/dist/chunk-MXQKLGQK.js +925 -0
  7. package/dist/chunk-R3VVJXX7.js +575 -0
  8. package/dist/chunk-SVGQSPW4.js +24 -0
  9. package/dist/client-exports.cjs +1702 -0
  10. package/dist/client-exports.js +202 -246
  11. package/dist/db/schema.cjs +922 -0
  12. package/dist/db/schema.js +1 -696
  13. package/dist/index.cjs +10122 -0
  14. package/dist/index.js +7989 -13
  15. package/dist/types/index.cjs +45 -0
  16. package/dist/types/index.js +2 -6
  17. package/dist/validation/index.cjs +1772 -0
  18. package/dist/validation/index.js +2 -5
  19. package/package.json +11 -6
  20. package/dist/__tests__/integration/helpers.d.ts +0 -5
  21. package/dist/__tests__/integration/helpers.d.ts.map +0 -1
  22. package/dist/__tests__/integration/helpers.js +0 -37
  23. package/dist/__tests__/integration/helpers.js.map +0 -1
  24. package/dist/__tests__/setup.d.ts +0 -3
  25. package/dist/__tests__/setup.d.ts.map +0 -1
  26. package/dist/__tests__/setup.js +0 -29
  27. package/dist/__tests__/setup.js.map +0 -1
  28. package/dist/client-exports.d.ts +0 -300
  29. package/dist/client-exports.d.ts.map +0 -1
  30. package/dist/client-exports.js.map +0 -1
  31. package/dist/context/ContextConfig.d.ts +0 -54
  32. package/dist/context/ContextConfig.d.ts.map +0 -1
  33. package/dist/context/ContextConfig.js +0 -302
  34. package/dist/context/ContextConfig.js.map +0 -1
  35. package/dist/context/ContextFetcher.d.ts +0 -64
  36. package/dist/context/ContextFetcher.d.ts.map +0 -1
  37. package/dist/context/ContextFetcher.js +0 -325
  38. package/dist/context/ContextFetcher.js.map +0 -1
  39. package/dist/context/ContextResolver.d.ts +0 -52
  40. package/dist/context/ContextResolver.d.ts.map +0 -1
  41. package/dist/context/ContextResolver.js +0 -298
  42. package/dist/context/ContextResolver.js.map +0 -1
  43. package/dist/context/TemplateEngine.d.ts +0 -46
  44. package/dist/context/TemplateEngine.d.ts.map +0 -1
  45. package/dist/context/TemplateEngine.js +0 -175
  46. package/dist/context/TemplateEngine.js.map +0 -1
  47. package/dist/context/context.d.ts +0 -8
  48. package/dist/context/context.d.ts.map +0 -1
  49. package/dist/context/context.js +0 -157
  50. package/dist/context/context.js.map +0 -1
  51. package/dist/context/contextCache.d.ts +0 -50
  52. package/dist/context/contextCache.d.ts.map +0 -1
  53. package/dist/context/contextCache.js +0 -175
  54. package/dist/context/contextCache.js.map +0 -1
  55. package/dist/context/index.d.ts +0 -11
  56. package/dist/context/index.d.ts.map +0 -1
  57. package/dist/context/index.js +0 -8
  58. package/dist/context/index.js.map +0 -1
  59. package/dist/credential-stores/CredentialStoreRegistry.d.ts +0 -39
  60. package/dist/credential-stores/CredentialStoreRegistry.d.ts.map +0 -1
  61. package/dist/credential-stores/CredentialStoreRegistry.js +0 -65
  62. package/dist/credential-stores/CredentialStoreRegistry.js.map +0 -1
  63. package/dist/credential-stores/defaults.d.ts +0 -6
  64. package/dist/credential-stores/defaults.d.ts.map +0 -1
  65. package/dist/credential-stores/defaults.js +0 -22
  66. package/dist/credential-stores/defaults.js.map +0 -1
  67. package/dist/credential-stores/index.d.ts +0 -6
  68. package/dist/credential-stores/index.d.ts.map +0 -1
  69. package/dist/credential-stores/index.js +0 -6
  70. package/dist/credential-stores/index.js.map +0 -1
  71. package/dist/credential-stores/keychain-store.d.ts +0 -100
  72. package/dist/credential-stores/keychain-store.d.ts.map +0 -1
  73. package/dist/credential-stores/keychain-store.js +0 -225
  74. package/dist/credential-stores/keychain-store.js.map +0 -1
  75. package/dist/credential-stores/memory-store.d.ts +0 -39
  76. package/dist/credential-stores/memory-store.d.ts.map +0 -1
  77. package/dist/credential-stores/memory-store.js +0 -58
  78. package/dist/credential-stores/memory-store.js.map +0 -1
  79. package/dist/credential-stores/nango-store.d.ts +0 -59
  80. package/dist/credential-stores/nango-store.d.ts.map +0 -1
  81. package/dist/credential-stores/nango-store.js +0 -264
  82. package/dist/credential-stores/nango-store.js.map +0 -1
  83. package/dist/credential-stuffer/CredentialStuffer.d.ts +0 -80
  84. package/dist/credential-stuffer/CredentialStuffer.d.ts.map +0 -1
  85. package/dist/credential-stuffer/CredentialStuffer.js +0 -186
  86. package/dist/credential-stuffer/CredentialStuffer.js.map +0 -1
  87. package/dist/credential-stuffer/index.d.ts +0 -2
  88. package/dist/credential-stuffer/index.d.ts.map +0 -1
  89. package/dist/credential-stuffer/index.js +0 -2
  90. package/dist/credential-stuffer/index.js.map +0 -1
  91. package/dist/data-access/agentDataComponents.d.ts +0 -1
  92. package/dist/data-access/agentDataComponents.d.ts.map +0 -1
  93. package/dist/data-access/agentDataComponents.js +0 -2
  94. package/dist/data-access/agentDataComponents.js.map +0 -1
  95. package/dist/data-access/agentGraphs.d.ts +0 -406
  96. package/dist/data-access/agentGraphs.d.ts.map +0 -1
  97. package/dist/data-access/agentGraphs.js +0 -551
  98. package/dist/data-access/agentGraphs.js.map +0 -1
  99. package/dist/data-access/agentRelations.d.ts +0 -456
  100. package/dist/data-access/agentRelations.d.ts.map +0 -1
  101. package/dist/data-access/agentRelations.js +0 -471
  102. package/dist/data-access/agentRelations.js.map +0 -1
  103. package/dist/data-access/agents.d.ts +0 -218
  104. package/dist/data-access/agents.d.ts.map +0 -1
  105. package/dist/data-access/agents.js +0 -130
  106. package/dist/data-access/agents.js.map +0 -1
  107. package/dist/data-access/apiKeys.d.ts +0 -114
  108. package/dist/data-access/apiKeys.d.ts.map +0 -1
  109. package/dist/data-access/apiKeys.js +0 -185
  110. package/dist/data-access/apiKeys.js.map +0 -1
  111. package/dist/data-access/artifactComponents.d.ts +0 -152
  112. package/dist/data-access/artifactComponents.d.ts.map +0 -1
  113. package/dist/data-access/artifactComponents.js +0 -214
  114. package/dist/data-access/artifactComponents.js.map +0 -1
  115. package/dist/data-access/contextCache.d.ts +0 -68
  116. package/dist/data-access/contextCache.d.ts.map +0 -1
  117. package/dist/data-access/contextCache.js +0 -160
  118. package/dist/data-access/contextCache.js.map +0 -1
  119. package/dist/data-access/contextConfigs.d.ts +0 -110
  120. package/dist/data-access/contextConfigs.d.ts.map +0 -1
  121. package/dist/data-access/contextConfigs.js +0 -156
  122. package/dist/data-access/contextConfigs.js.map +0 -1
  123. package/dist/data-access/conversations.d.ts +0 -125
  124. package/dist/data-access/conversations.d.ts.map +0 -1
  125. package/dist/data-access/conversations.js +0 -244
  126. package/dist/data-access/conversations.js.map +0 -1
  127. package/dist/data-access/credentialReferences.d.ts +0 -86
  128. package/dist/data-access/credentialReferences.d.ts.map +0 -1
  129. package/dist/data-access/credentialReferences.js +0 -175
  130. package/dist/data-access/credentialReferences.js.map +0 -1
  131. package/dist/data-access/dataComponents.d.ts +0 -129
  132. package/dist/data-access/dataComponents.d.ts.map +0 -1
  133. package/dist/data-access/dataComponents.js +0 -213
  134. package/dist/data-access/dataComponents.js.map +0 -1
  135. package/dist/data-access/externalAgents.d.ts +0 -83
  136. package/dist/data-access/externalAgents.d.ts.map +0 -1
  137. package/dist/data-access/externalAgents.js +0 -163
  138. package/dist/data-access/externalAgents.js.map +0 -1
  139. package/dist/data-access/graphFull.d.ts +0 -32
  140. package/dist/data-access/graphFull.d.ts.map +0 -1
  141. package/dist/data-access/graphFull.js +0 -996
  142. package/dist/data-access/graphFull.js.map +0 -1
  143. package/dist/data-access/index.d.ts +0 -21
  144. package/dist/data-access/index.d.ts.map +0 -1
  145. package/dist/data-access/index.js +0 -22
  146. package/dist/data-access/index.js.map +0 -1
  147. package/dist/data-access/ledgerArtifacts.d.ts +0 -49
  148. package/dist/data-access/ledgerArtifacts.d.ts.map +0 -1
  149. package/dist/data-access/ledgerArtifacts.js +0 -112
  150. package/dist/data-access/ledgerArtifacts.js.map +0 -1
  151. package/dist/data-access/messages.d.ts +0 -209
  152. package/dist/data-access/messages.d.ts.map +0 -1
  153. package/dist/data-access/messages.js +0 -100
  154. package/dist/data-access/messages.js.map +0 -1
  155. package/dist/data-access/projects.d.ts +0 -67
  156. package/dist/data-access/projects.d.ts.map +0 -1
  157. package/dist/data-access/projects.js +0 -337
  158. package/dist/data-access/projects.js.map +0 -1
  159. package/dist/data-access/tasks.d.ts +0 -37
  160. package/dist/data-access/tasks.d.ts.map +0 -1
  161. package/dist/data-access/tasks.js +0 -40
  162. package/dist/data-access/tasks.js.map +0 -1
  163. package/dist/data-access/tools.d.ts +0 -277
  164. package/dist/data-access/tools.d.ts.map +0 -1
  165. package/dist/data-access/tools.js +0 -183
  166. package/dist/data-access/tools.js.map +0 -1
  167. package/dist/data-access/validation.d.ts +0 -17
  168. package/dist/data-access/validation.d.ts.map +0 -1
  169. package/dist/data-access/validation.js +0 -52
  170. package/dist/data-access/validation.js.map +0 -1
  171. package/dist/db/clean.d.ts +0 -6
  172. package/dist/db/clean.d.ts.map +0 -1
  173. package/dist/db/clean.js +0 -81
  174. package/dist/db/clean.js.map +0 -1
  175. package/dist/db/client.d.ts +0 -19
  176. package/dist/db/client.d.ts.map +0 -1
  177. package/dist/db/client.js +0 -24
  178. package/dist/db/client.js.map +0 -1
  179. package/dist/db/schema.d.ts +0 -4337
  180. package/dist/db/schema.d.ts.map +0 -1
  181. package/dist/db/schema.js.map +0 -1
  182. package/dist/db/test-client.d.ts +0 -25
  183. package/dist/db/test-client.d.ts.map +0 -1
  184. package/dist/db/test-client.js +0 -136
  185. package/dist/db/test-client.js.map +0 -1
  186. package/dist/env.d.ts +0 -19
  187. package/dist/env.d.ts.map +0 -1
  188. package/dist/env.js +0 -49
  189. package/dist/env.js.map +0 -1
  190. package/dist/index.d.ts +0 -12
  191. package/dist/index.d.ts.map +0 -1
  192. package/dist/index.js.map +0 -1
  193. package/dist/middleware/contextValidation.d.ts +0 -49
  194. package/dist/middleware/contextValidation.d.ts.map +0 -1
  195. package/dist/middleware/contextValidation.js +0 -473
  196. package/dist/middleware/contextValidation.js.map +0 -1
  197. package/dist/middleware/index.d.ts +0 -2
  198. package/dist/middleware/index.d.ts.map +0 -1
  199. package/dist/middleware/index.js +0 -2
  200. package/dist/middleware/index.js.map +0 -1
  201. package/dist/server/BaseServer.d.ts +0 -83
  202. package/dist/server/BaseServer.d.ts.map +0 -1
  203. package/dist/server/BaseServer.js +0 -218
  204. package/dist/server/BaseServer.js.map +0 -1
  205. package/dist/types/a2a.d.ts +0 -373
  206. package/dist/types/a2a.d.ts.map +0 -1
  207. package/dist/types/a2a.js +0 -14
  208. package/dist/types/a2a.js.map +0 -1
  209. package/dist/types/entities.d.ts +0 -147
  210. package/dist/types/entities.d.ts.map +0 -1
  211. package/dist/types/entities.js +0 -2
  212. package/dist/types/entities.js.map +0 -1
  213. package/dist/types/index.d.ts +0 -5
  214. package/dist/types/index.d.ts.map +0 -1
  215. package/dist/types/index.js.map +0 -1
  216. package/dist/types/server.d.ts +0 -116
  217. package/dist/types/server.d.ts.map +0 -1
  218. package/dist/types/server.js +0 -2
  219. package/dist/types/server.js.map +0 -1
  220. package/dist/types/utility.d.ts +0 -213
  221. package/dist/types/utility.d.ts.map +0 -1
  222. package/dist/types/utility.js +0 -9
  223. package/dist/types/utility.js.map +0 -1
  224. package/dist/utils/apiKeys.d.ts +0 -32
  225. package/dist/utils/apiKeys.d.ts.map +0 -1
  226. package/dist/utils/apiKeys.js +0 -117
  227. package/dist/utils/apiKeys.js.map +0 -1
  228. package/dist/utils/auth-detection.d.ts +0 -23
  229. package/dist/utils/auth-detection.d.ts.map +0 -1
  230. package/dist/utils/auth-detection.js +0 -148
  231. package/dist/utils/auth-detection.js.map +0 -1
  232. package/dist/utils/credential-store-utils.d.ts +0 -11
  233. package/dist/utils/credential-store-utils.d.ts.map +0 -1
  234. package/dist/utils/credential-store-utils.js +0 -19
  235. package/dist/utils/credential-store-utils.js.map +0 -1
  236. package/dist/utils/error.d.ts +0 -526
  237. package/dist/utils/error.d.ts.map +0 -1
  238. package/dist/utils/error.js +0 -282
  239. package/dist/utils/error.js.map +0 -1
  240. package/dist/utils/execution.d.ts +0 -18
  241. package/dist/utils/execution.d.ts.map +0 -1
  242. package/dist/utils/execution.js +0 -25
  243. package/dist/utils/execution.js.map +0 -1
  244. package/dist/utils/index.d.ts +0 -9
  245. package/dist/utils/index.d.ts.map +0 -1
  246. package/dist/utils/index.js +0 -9
  247. package/dist/utils/index.js.map +0 -1
  248. package/dist/utils/logger.d.ts +0 -79
  249. package/dist/utils/logger.d.ts.map +0 -1
  250. package/dist/utils/logger.js +0 -102
  251. package/dist/utils/logger.js.map +0 -1
  252. package/dist/utils/logging.d.ts +0 -11
  253. package/dist/utils/logging.d.ts.map +0 -1
  254. package/dist/utils/logging.js +0 -6
  255. package/dist/utils/logging.js.map +0 -1
  256. package/dist/utils/mcp-client.d.ts +0 -48
  257. package/dist/utils/mcp-client.d.ts.map +0 -1
  258. package/dist/utils/mcp-client.js +0 -174
  259. package/dist/utils/mcp-client.js.map +0 -1
  260. package/dist/utils/tracer.d.ts +0 -24
  261. package/dist/utils/tracer.d.ts.map +0 -1
  262. package/dist/utils/tracer.js +0 -110
  263. package/dist/utils/tracer.js.map +0 -1
  264. package/dist/validation/graphFull.d.ts +0 -36
  265. package/dist/validation/graphFull.d.ts.map +0 -1
  266. package/dist/validation/graphFull.js +0 -128
  267. package/dist/validation/graphFull.js.map +0 -1
  268. package/dist/validation/id-validation.d.ts +0 -38
  269. package/dist/validation/id-validation.d.ts.map +0 -1
  270. package/dist/validation/id-validation.js +0 -60
  271. package/dist/validation/id-validation.js.map +0 -1
  272. package/dist/validation/index.d.ts +0 -4
  273. package/dist/validation/index.d.ts.map +0 -1
  274. package/dist/validation/index.js.map +0 -1
  275. package/dist/validation/schemas.d.ts +0 -7238
  276. package/dist/validation/schemas.d.ts.map +0 -1
  277. package/dist/validation/schemas.js +0 -575
  278. package/dist/validation/schemas.js.map +0 -1
@@ -1,996 +0,0 @@
1
- import { and, eq } from 'drizzle-orm';
2
- import { nanoid } from 'nanoid';
3
- import { agents, projects } from '../db/schema';
4
- import { isExternalAgent, isInternalAgent, validateAndTypeGraphData, validateGraphStructure, } from '../validation/graphFull';
5
- import { deleteAgentGraph, getAgentGraphById, getFullGraphDefinition, updateAgentGraph, upsertAgentGraph, } from './agentGraphs';
6
- import { createAgentRelation, createAgentToolRelation, deleteAgentRelationsByGraph, deleteAgentToolRelationByAgent, upsertAgentRelation, } from './agentRelations';
7
- import { upsertAgent } from './agents';
8
- import { associateArtifactComponentWithAgent, deleteAgentArtifactComponentRelationByAgent, upsertAgentArtifactComponentRelation, upsertArtifactComponent, } from './artifactComponents';
9
- import { upsertContextConfig } from './contextConfigs';
10
- import { upsertCredentialReference } from './credentialReferences';
11
- import { associateDataComponentWithAgent, deleteAgentDataComponentRelationByAgent, upsertAgentDataComponentRelation, upsertDataComponent, } from './dataComponents';
12
- import { upsertExternalAgent } from './externalAgents';
13
- import { upsertAgentToolRelation, upsertTool } from './tools';
14
- // Default no-op logger
15
- const defaultLogger = {
16
- info: () => { },
17
- error: () => { },
18
- };
19
- /**
20
- * Apply execution limits inheritance from project to graph and agents
21
- */
22
- async function applyExecutionLimitsInheritance(db, logger, scopes, graphData) {
23
- const { tenantId, projectId } = scopes;
24
- try {
25
- // Get project stopWhen configuration
26
- const project = await db.query.projects.findFirst({
27
- where: and(eq(projects.tenantId, tenantId), eq(projects.id, projectId)),
28
- });
29
- if (!project?.stopWhen) {
30
- logger.info({ projectId }, 'No project stopWhen configuration found');
31
- return;
32
- }
33
- const projectStopWhen = project.stopWhen;
34
- logger.info({
35
- projectId,
36
- projectStopWhen: projectStopWhen,
37
- }, 'Found project stopWhen configuration');
38
- // Initialize graph stopWhen if not exists
39
- if (!graphData.stopWhen) {
40
- graphData.stopWhen = {};
41
- }
42
- // Inherit transferCountIs from project if graph doesn't have it explicitly set
43
- if (graphData.stopWhen.transferCountIs === undefined &&
44
- projectStopWhen?.transferCountIs !== undefined) {
45
- graphData.stopWhen.transferCountIs = projectStopWhen.transferCountIs;
46
- logger.info({
47
- graphId: graphData.id,
48
- inheritedValue: projectStopWhen.transferCountIs,
49
- }, 'Graph inherited transferCountIs from project');
50
- }
51
- // Set default transferCountIs if still not set
52
- if (graphData.stopWhen.transferCountIs === undefined) {
53
- graphData.stopWhen.transferCountIs = 10;
54
- logger.info({
55
- graphId: graphData.id,
56
- defaultValue: 10,
57
- }, 'Graph set to default transferCountIs');
58
- }
59
- // Propagate stepCountIs from project to agents
60
- if (projectStopWhen?.stepCountIs !== undefined) {
61
- logger.info({
62
- projectId,
63
- stepCountIs: projectStopWhen.stepCountIs,
64
- }, 'Propagating stepCountIs to agents');
65
- for (const [agentId, agentData] of Object.entries(graphData.agents)) {
66
- // Only apply to internal agents (have prompt)
67
- if (isInternalAgent(agentData)) {
68
- const agent = agentData;
69
- // Initialize agent stopWhen if it doesn't exist
70
- if (!agent.stopWhen) {
71
- agent.stopWhen = {};
72
- }
73
- // Set stepCountIs in stopWhen if not explicitly set
74
- if (agent.stopWhen.stepCountIs === undefined) {
75
- agent.stopWhen.stepCountIs = projectStopWhen.stepCountIs;
76
- logger.info({
77
- agentId,
78
- inheritedValue: projectStopWhen.stepCountIs,
79
- }, 'Agent inherited stepCountIs from project');
80
- }
81
- }
82
- }
83
- }
84
- }
85
- catch (error) {
86
- logger.error({
87
- projectId,
88
- error: error instanceof Error ? error.message : 'Unknown error',
89
- }, 'Failed to apply execution limits inheritance');
90
- // Don't throw - inheritance failure shouldn't block graph creation
91
- }
92
- }
93
- /**
94
- * Server-side implementation of createFullGraph that performs actual database operations.
95
- * This function creates a complete graph with all agents, tools, and relationships.
96
- */
97
- export const createFullGraphServerSide = (db, logger = defaultLogger) => async (scopes, graphData) => {
98
- const { tenantId, projectId } = scopes;
99
- const typed = validateAndTypeGraphData(graphData);
100
- // Validate the graph structure
101
- validateGraphStructure(typed);
102
- // Apply inheritance logic for execution limits
103
- await applyExecutionLimitsInheritance(db, logger, { tenantId, projectId }, typed);
104
- try {
105
- // Step 1: Create/update credential references first (tools and context configs depend on them)
106
- if (typed.credentialReferences) {
107
- logger.info({ credentialReferencesCount: typed.credentialReferences.length }, 'Processing credential references');
108
- const credentialRefPromises = typed.credentialReferences.map(async (credData) => {
109
- try {
110
- logger.info({ credId: credData.id }, 'Processing credential reference');
111
- await upsertCredentialReference(db)({
112
- data: {
113
- ...credData,
114
- tenantId,
115
- projectId,
116
- },
117
- });
118
- logger.info({ credId: credData.id }, 'Credential reference processed successfully');
119
- }
120
- catch (error) {
121
- logger.error({ credId: credData.id, error }, 'Failed to create/update credential reference');
122
- throw error;
123
- }
124
- });
125
- await Promise.all(credentialRefPromises);
126
- logger.info({ credentialReferencesCount: typed.credentialReferences.length }, 'All credential references created/updated successfully');
127
- }
128
- // Step 2: Create/update tools (agents depend on them)
129
- const toolPromises = Object.entries(typed.tools).map(async ([toolId, toolData]) => {
130
- try {
131
- logger.info({ toolId }, 'Processing tool');
132
- await upsertTool(db)({
133
- data: {
134
- tenantId,
135
- projectId,
136
- ...toolData,
137
- },
138
- });
139
- logger.info({ toolId }, 'Tool processed successfully');
140
- }
141
- catch (error) {
142
- logger.error({ toolId, error }, 'Failed to create/update tool');
143
- throw error;
144
- }
145
- });
146
- await Promise.all(toolPromises);
147
- logger.info({ toolCount: Object.keys(typed.tools).length }, 'All tools created/updated successfully');
148
- // Step 3: create/update context config
149
- let contextConfigId;
150
- if (typed.contextConfig) {
151
- try {
152
- logger.info({ contextConfigId: typed.contextConfig.id }, 'Processing context config');
153
- const contextConfig = await upsertContextConfig(db)({
154
- data: {
155
- ...typed.contextConfig,
156
- tenantId,
157
- projectId,
158
- },
159
- });
160
- contextConfigId = contextConfig.id;
161
- logger.info({ contextConfigId }, 'Context config processed successfully');
162
- }
163
- catch (error) {
164
- logger.error({ contextConfigId: typed.contextConfig.id, error }, 'Failed to create/update context config');
165
- throw error;
166
- }
167
- }
168
- // Step 4: Create/update dataComponents (agents depend on them)
169
- if (typed.dataComponents && Object.keys(typed.dataComponents).length > 0) {
170
- const dataComponentPromises = Object.entries(typed.dataComponents).map(async ([dataComponentId, dataComponentData]) => {
171
- try {
172
- logger.info({ dataComponentId }, 'Processing data component');
173
- await upsertDataComponent(db)({
174
- data: {
175
- id: dataComponentId,
176
- tenantId,
177
- projectId,
178
- name: dataComponentData.name,
179
- description: dataComponentData.description || '',
180
- props: dataComponentData.props || {},
181
- },
182
- });
183
- logger.info({ dataComponentId }, 'Data component processed successfully');
184
- }
185
- catch (error) {
186
- logger.error({ dataComponentId, error }, 'Failed to create/update dataComponent');
187
- throw error;
188
- }
189
- });
190
- await Promise.all(dataComponentPromises);
191
- logger.info({ dataComponentCount: Object.keys(typed.dataComponents).length }, 'All dataComponents created/updated successfully');
192
- }
193
- // Step 5: Create/update artifactComponents (agents depend on them)
194
- if (typed.artifactComponents && Object.keys(typed.artifactComponents).length > 0) {
195
- const artifactComponentPromises = Object.entries(typed.artifactComponents).map(async ([artifactComponentId, artifactComponentData]) => {
196
- try {
197
- logger.info({ artifactComponentId }, 'Processing artifact component');
198
- await upsertArtifactComponent(db)({
199
- data: {
200
- id: artifactComponentId,
201
- tenantId,
202
- projectId,
203
- name: artifactComponentData.name,
204
- description: artifactComponentData.description || '',
205
- summaryProps: artifactComponentData.summaryProps || {},
206
- fullProps: artifactComponentData.fullProps || {},
207
- },
208
- });
209
- logger.info({ artifactComponentId }, 'Artifact component processed successfully');
210
- }
211
- catch (error) {
212
- logger.error({ artifactComponentId, error }, 'Failed to create/update artifactComponent');
213
- throw error;
214
- }
215
- });
216
- await Promise.all(artifactComponentPromises);
217
- logger.info({ artifactComponentCount: Object.keys(typed.artifactComponents).length }, 'All artifactComponents created/updated successfully');
218
- }
219
- // Step 6: Create/update internal agents
220
- const internalAgentPromises = Object.entries(typed.agents)
221
- .filter(([_, agentData]) => isInternalAgent(agentData)) // Internal agents have prompt
222
- .map(async ([agentId, agentData]) => {
223
- // Type assertion since we've filtered for internal agents
224
- const internalAgent = agentData;
225
- try {
226
- logger.info({ agentId }, 'Processing internal agent');
227
- await upsertAgent(db)({
228
- data: {
229
- id: agentId,
230
- tenantId,
231
- projectId,
232
- name: internalAgent.name || '',
233
- description: internalAgent.description || '',
234
- prompt: internalAgent.prompt || '',
235
- conversationHistoryConfig: internalAgent.conversationHistoryConfig,
236
- models: internalAgent.models,
237
- stopWhen: internalAgent.stopWhen,
238
- },
239
- });
240
- logger.info({ agentId }, 'Internal agent processed successfully');
241
- }
242
- catch (error) {
243
- logger.error({ agentId, error }, 'Failed to create/update internal agent');
244
- throw error;
245
- }
246
- });
247
- await Promise.all(internalAgentPromises);
248
- const internalAgentCount = Object.entries(typed.agents).filter(([_, agentData]) => isInternalAgent(agentData)).length;
249
- logger.info({ internalAgentCount }, 'All internal agents created/updated successfully');
250
- // Step 7: Create/update external agents
251
- const externalAgentPromises = Object.entries(typed.agents)
252
- .filter(([_, agentData]) => isExternalAgent(agentData)) // External agents have baseUrl
253
- .map(async ([agentId, agentData]) => {
254
- // Type assertion since we've filtered for external agents
255
- const externalAgent = agentData;
256
- try {
257
- logger.info({ agentId }, 'Processing external agent');
258
- await upsertExternalAgent(db)({
259
- data: {
260
- id: agentId,
261
- tenantId,
262
- projectId,
263
- name: externalAgent.name,
264
- description: externalAgent.description || '',
265
- baseUrl: externalAgent.baseUrl,
266
- credentialReferenceId: externalAgent.credentialReferenceId || undefined,
267
- headers: externalAgent.headers || undefined,
268
- },
269
- });
270
- logger.info({ agentId }, 'External agent processed successfully');
271
- }
272
- catch (error) {
273
- logger.error({ agentId, error }, 'Failed to create/update external agent');
274
- throw error;
275
- }
276
- });
277
- await Promise.all(externalAgentPromises);
278
- const externalAgentCount = Object.entries(typed.agents).filter(([_, agentData]) => isExternalAgent(agentData)).length;
279
- logger.info({ externalAgentCount }, 'All external agents created/updated successfully');
280
- // Step 8: Create the graph metadata (or update if exists for upsert behavior)
281
- let finalGraphId;
282
- try {
283
- logger.info({ graphId: typed.id }, 'Processing agent graph metadata');
284
- const agentGraph = await upsertAgentGraph(db)({
285
- data: {
286
- id: typed.id || nanoid(),
287
- tenantId,
288
- projectId,
289
- name: typed.name,
290
- defaultAgentId: typed.defaultAgentId,
291
- description: typed.description,
292
- contextConfigId,
293
- models: typed.models,
294
- statusUpdates: typed.statusUpdates,
295
- graphPrompt: typed.graphPrompt,
296
- stopWhen: typed.stopWhen,
297
- },
298
- });
299
- finalGraphId = agentGraph.id;
300
- logger.info({ graphId: finalGraphId }, 'Agent graph metadata processed successfully');
301
- }
302
- catch (error) {
303
- logger.error({ graphId: typed.id, error }, 'Failed to create/update graph metadata');
304
- throw error;
305
- }
306
- // Step 9: Create agent-tool relationships
307
- const agentToolPromises = [];
308
- for (const [agentId, agentData] of Object.entries(typed.agents)) {
309
- if (isInternalAgent(agentData) && agentData.tools && Array.isArray(agentData.tools)) {
310
- for (const toolId of agentData.tools) {
311
- agentToolPromises.push((async () => {
312
- try {
313
- logger.info({ agentId, toolId }, 'Processing agent-tool relation');
314
- await upsertAgentToolRelation(db)({
315
- scopes: { tenantId, projectId },
316
- agentId,
317
- toolId,
318
- });
319
- logger.info({ agentId, toolId }, 'Agent-tool relation processed successfully');
320
- }
321
- catch (error) {
322
- logger.error({ agentId, toolId, error }, 'Failed to create agent-tool relation');
323
- // Don't throw - allow partial success for relations
324
- }
325
- })());
326
- }
327
- }
328
- }
329
- await Promise.all(agentToolPromises);
330
- logger.info({ agentToolCount: Object.keys(typed.agents).length }, 'All agent-tool relations created');
331
- // Step 10: Create agent-dataComponent relationships
332
- const agentDataComponentPromises = [];
333
- for (const [agentId, agentData] of Object.entries(typed.agents)) {
334
- if (isInternalAgent(agentData) && agentData.dataComponents) {
335
- for (const dataComponentId of agentData.dataComponents) {
336
- agentDataComponentPromises.push((async () => {
337
- try {
338
- logger.info({ agentId, dataComponentId }, 'Processing agent-data component relation');
339
- await upsertAgentDataComponentRelation(db)({
340
- scopes: { tenantId, projectId },
341
- agentId,
342
- dataComponentId,
343
- });
344
- logger.info({ agentId, dataComponentId }, 'Agent-data component relation processed successfully');
345
- }
346
- catch (error) {
347
- logger.error({ agentId, dataComponentId, error }, 'Failed to create agent-data component relation');
348
- // Don't throw - allow partial success for relations
349
- }
350
- })());
351
- }
352
- }
353
- }
354
- await Promise.all(agentDataComponentPromises);
355
- logger.info({}, 'All agent-data component relations created');
356
- // Step 11: Create agent-artifactComponent relationships
357
- const agentArtifactComponentPromises = [];
358
- for (const [agentId, agentData] of Object.entries(typed.agents)) {
359
- if (isInternalAgent(agentData) && agentData.artifactComponents) {
360
- for (const artifactComponentId of agentData.artifactComponents) {
361
- agentArtifactComponentPromises.push((async () => {
362
- try {
363
- logger.info({ agentId, artifactComponentId }, 'Processing agent-artifact component relation');
364
- await upsertAgentArtifactComponentRelation(db)({
365
- scopes: { tenantId, projectId },
366
- agentId,
367
- artifactComponentId,
368
- });
369
- logger.info({ agentId, artifactComponentId }, 'Agent-artifact component relation processed successfully');
370
- }
371
- catch (error) {
372
- logger.error({ agentId, artifactComponentId, error }, 'Failed to create agent-artifact component relation');
373
- // Don't throw - allow partial success for relations
374
- }
375
- })());
376
- }
377
- }
378
- }
379
- await Promise.all(agentArtifactComponentPromises);
380
- logger.info({}, 'All agent-artifact component relations created');
381
- // Step 12: Create agent relationships (transfer/delegation)
382
- const agentRelationPromises = [];
383
- for (const [agentId, agentData] of Object.entries(typed.agents)) {
384
- // Create transfer relations
385
- if (isInternalAgent(agentData) && agentData.canTransferTo) {
386
- for (const targetAgentId of agentData.canTransferTo) {
387
- agentRelationPromises.push((async () => {
388
- try {
389
- logger.info({ agentId, targetAgentId, type: 'transfer' }, 'Processing agent transfer relation');
390
- await upsertAgentRelation(db)({
391
- id: nanoid(),
392
- tenantId,
393
- projectId,
394
- graphId: finalGraphId,
395
- sourceAgentId: agentId,
396
- targetAgentId,
397
- relationType: 'transfer',
398
- });
399
- logger.info({ agentId, targetAgentId, type: 'transfer' }, 'Agent transfer relation processed successfully');
400
- }
401
- catch (error) {
402
- logger.error({ agentId, targetAgentId, type: 'transfer', error }, 'Failed to create transfer relation');
403
- }
404
- })());
405
- }
406
- }
407
- // Create delegation relations
408
- if (isInternalAgent(agentData) && agentData.canDelegateTo) {
409
- for (const targetAgentId of agentData.canDelegateTo) {
410
- // Check if the target agent is external by looking it up in the typed.agents
411
- const targetAgentData = typed.agents[targetAgentId];
412
- const isTargetExternal = isExternalAgent(targetAgentData);
413
- agentRelationPromises.push((async () => {
414
- try {
415
- logger.info({ agentId, targetAgentId, type: 'delegate' }, 'Processing agent delegation relation');
416
- await upsertAgentRelation(db)({
417
- id: nanoid(),
418
- tenantId,
419
- projectId,
420
- graphId: finalGraphId,
421
- sourceAgentId: agentId,
422
- targetAgentId: isTargetExternal ? undefined : targetAgentId,
423
- externalAgentId: isTargetExternal ? targetAgentId : undefined,
424
- relationType: 'delegate',
425
- });
426
- logger.info({ agentId, targetAgentId, type: 'delegate' }, 'Agent delegation relation processed successfully');
427
- }
428
- catch (error) {
429
- logger.error({ agentId, targetAgentId, type: 'delegate', error }, 'Failed to create delegation relation');
430
- }
431
- })());
432
- }
433
- }
434
- }
435
- await Promise.all(agentRelationPromises);
436
- logger.info({ agentRelationCount: agentRelationPromises.length }, 'All agent relations created');
437
- // Retrieve and return the created graph
438
- const createdGraph = await getFullGraphDefinition(db)({
439
- scopes: { tenantId, projectId },
440
- graphId: finalGraphId,
441
- });
442
- if (!createdGraph) {
443
- throw new Error('Failed to retrieve created graph');
444
- }
445
- logger.info({ tenantId, graphId: finalGraphId }, 'Full graph created successfully');
446
- return createdGraph;
447
- }
448
- catch (error) {
449
- const errorGraphId = typed.id || 'unknown';
450
- logger.error({ tenantId, graphId: errorGraphId, error }, 'Failed to create full graph');
451
- throw error;
452
- }
453
- };
454
- /**
455
- * Server-side implementation of updateFullGraph that performs actual database operations.
456
- * This function updates a complete graph with all agents, tools, and relationships.
457
- */
458
- export const updateFullGraphServerSide = (db, logger = defaultLogger) => async (scopes, graphData) => {
459
- const { tenantId, projectId } = scopes;
460
- const typedGraphDefinition = validateAndTypeGraphData(graphData);
461
- if (!typedGraphDefinition.id) {
462
- throw new Error('Graph ID is required');
463
- }
464
- logger.info({
465
- tenantId,
466
- graphId: typedGraphDefinition.id,
467
- agentCount: Object.keys(typedGraphDefinition.agents).length,
468
- toolCount: Object.keys(typedGraphDefinition.tools).length,
469
- }, 'Updating full graph in database');
470
- // Validate the graph structure
471
- validateGraphStructure(typedGraphDefinition);
472
- // Apply inheritance logic for execution limits
473
- await applyExecutionLimitsInheritance(db, logger, { tenantId, projectId }, typedGraphDefinition);
474
- try {
475
- // Verify graph exists and get existing models for cascade logic
476
- const existingGraph = await getAgentGraphById(db)({
477
- scopes: { tenantId, projectId },
478
- graphId: typedGraphDefinition.id,
479
- });
480
- if (!existingGraph) {
481
- // If graph doesn't exist, create it (upsert behavior)
482
- logger.info({ graphId: typedGraphDefinition.id }, 'Graph does not exist, creating new graph');
483
- return createFullGraphServerSide(db)(scopes, graphData);
484
- }
485
- // Store existing graph models for cascade comparison
486
- const existingGraphModels = existingGraph.models;
487
- // Step 1: Create/update credential references first (tools and context configs depend on them)
488
- if (typedGraphDefinition.credentialReferences) {
489
- logger.info({ credentialReferencesCount: typedGraphDefinition.credentialReferences.length }, 'Processing credential references');
490
- const credentialRefPromises = typedGraphDefinition.credentialReferences.map(async (credData) => {
491
- try {
492
- logger.info({ credId: credData.id }, 'Processing credential reference');
493
- await upsertCredentialReference(db)({
494
- data: {
495
- ...credData,
496
- tenantId,
497
- projectId,
498
- },
499
- });
500
- logger.info({ credId: credData.id }, 'Credential reference processed successfully');
501
- }
502
- catch (error) {
503
- logger.error({ credId: credData.id, error }, 'Failed to create/update credential reference');
504
- throw error;
505
- }
506
- });
507
- await Promise.all(credentialRefPromises);
508
- logger.info({ credentialReferencesCount: typedGraphDefinition.credentialReferences.length }, 'All credential references created/updated successfully');
509
- }
510
- // Step 2: Create/update tools (agents depend on them)
511
- const toolPromises = Object.entries(typedGraphDefinition.tools).map(async ([toolId, toolData]) => {
512
- try {
513
- logger.info({ toolId }, 'Processing tool');
514
- await upsertTool(db)({
515
- data: {
516
- tenantId,
517
- projectId,
518
- ...toolData,
519
- },
520
- });
521
- logger.info({ toolId }, 'Tool processed successfully');
522
- }
523
- catch (error) {
524
- logger.error({ toolId, error }, 'Failed to create/update tool');
525
- throw error;
526
- }
527
- });
528
- await Promise.all(toolPromises);
529
- logger.info({ toolCount: Object.keys(typedGraphDefinition.tools).length }, 'All tools created/updated successfully');
530
- // Step 3: create/update context config
531
- let contextConfigId;
532
- if (typedGraphDefinition.contextConfig) {
533
- try {
534
- logger.info({ contextConfigId: typedGraphDefinition.contextConfig.id }, 'Processing context config');
535
- const contextConfig = await upsertContextConfig(db)({
536
- data: {
537
- ...typedGraphDefinition.contextConfig,
538
- tenantId,
539
- projectId,
540
- },
541
- });
542
- contextConfigId = contextConfig.id;
543
- logger.info({ contextConfigId }, 'Context config processed successfully');
544
- }
545
- catch (error) {
546
- logger.error({ contextConfigId: typedGraphDefinition.contextConfig.id, error }, 'Failed to create/update context config');
547
- throw error;
548
- }
549
- }
550
- // Step 4: Create/update dataComponents (agents depend on them)
551
- if (typedGraphDefinition.dataComponents &&
552
- Object.keys(typedGraphDefinition.dataComponents).length > 0) {
553
- const dataComponentPromises = Object.entries(typedGraphDefinition.dataComponents).map(async ([dataComponentId, dataComponentData]) => {
554
- try {
555
- logger.info({ dataComponentId }, 'Processing data component');
556
- await upsertDataComponent(db)({
557
- data: {
558
- id: dataComponentId,
559
- tenantId,
560
- projectId,
561
- name: dataComponentData.name,
562
- description: dataComponentData.description || '',
563
- props: dataComponentData.props || {},
564
- },
565
- });
566
- logger.info({ dataComponentId }, 'Data component processed successfully');
567
- }
568
- catch (error) {
569
- logger.error({ dataComponentId, error }, 'Failed to create/update dataComponent');
570
- throw error;
571
- }
572
- });
573
- await Promise.all(dataComponentPromises);
574
- logger.info({ dataComponentCount: Object.keys(typedGraphDefinition.dataComponents).length }, 'All dataComponents created/updated successfully');
575
- }
576
- // Step 5: Create/update artifactComponents (agents depend on them)
577
- if (typedGraphDefinition.artifactComponents &&
578
- Object.keys(typedGraphDefinition.artifactComponents).length > 0) {
579
- const artifactComponentPromises = Object.entries(typedGraphDefinition.artifactComponents).map(async ([artifactComponentId, artifactComponentData]) => {
580
- try {
581
- logger.info({ artifactComponentId }, 'Processing artifact component');
582
- await upsertArtifactComponent(db)({
583
- data: {
584
- id: artifactComponentId,
585
- tenantId,
586
- projectId,
587
- name: artifactComponentData.name,
588
- description: artifactComponentData.description || '',
589
- summaryProps: artifactComponentData.summaryProps || {},
590
- fullProps: artifactComponentData.fullProps || {},
591
- },
592
- });
593
- logger.info({ artifactComponentId }, 'Artifact component processed successfully');
594
- }
595
- catch (error) {
596
- logger.error({ artifactComponentId, error }, 'Failed to create/update artifactComponent');
597
- throw error;
598
- }
599
- });
600
- await Promise.all(artifactComponentPromises);
601
- logger.info({ artifactComponentCount: Object.keys(typedGraphDefinition.artifactComponents).length }, 'All artifactComponents created/updated successfully');
602
- }
603
- // Step 6: Create/update internal agents with model cascade logic
604
- const internalAgentPromises = Object.entries(typedGraphDefinition.agents)
605
- .filter(([_, agentData]) => isInternalAgent(agentData)) // Internal agents have prompt
606
- .map(async ([agentId, agentData]) => {
607
- const internalAgent = agentData;
608
- // Get the existing agent to check for inheritance
609
- let existingAgent = null;
610
- try {
611
- existingAgent = await db.query.agents.findFirst({
612
- where: and(eq(agents.id, agentId), eq(agents.tenantId, tenantId), eq(agents.projectId, projectId)),
613
- columns: {
614
- models: true,
615
- },
616
- });
617
- }
618
- catch (error) {
619
- // Agent might not exist yet, that's ok
620
- }
621
- // Determine final model settings with cascade logic
622
- let finalModelSettings = internalAgent.models === undefined ? {} : internalAgent.models;
623
- // If graph models changed, cascade to agents that were inheriting
624
- if (existingAgent && existingAgent.models && typedGraphDefinition.models) {
625
- const agentModels = existingAgent.models;
626
- const graphModels = typedGraphDefinition.models;
627
- // Check each model type for inheritance and cascade if needed
628
- const modelTypes = ['base', 'structuredOutput', 'summarizer'];
629
- const cascadedModels = { ...finalModelSettings };
630
- for (const modelType of modelTypes) {
631
- // If the agent's current model matches the old graph model (was inheriting)
632
- // and the graph model has changed, cascade the change
633
- if (agentModels[modelType]?.model &&
634
- existingGraphModels?.[modelType]?.model &&
635
- agentModels[modelType].model === existingGraphModels[modelType].model &&
636
- graphModels[modelType]?.model &&
637
- graphModels[modelType].model !== existingGraphModels[modelType].model) {
638
- // Agent was inheriting from graph, cascade the new value
639
- cascadedModels[modelType] = {
640
- ...cascadedModels[modelType],
641
- model: graphModels[modelType].model,
642
- };
643
- logger.info({
644
- agentId,
645
- modelType,
646
- oldModel: agentModels[modelType].model,
647
- newModel: graphModels[modelType].model,
648
- }, 'Cascading model change from graph to agent');
649
- }
650
- }
651
- finalModelSettings = cascadedModels;
652
- }
653
- try {
654
- logger.info({ agentId }, 'Processing internal agent');
655
- await upsertAgent(db)({
656
- data: {
657
- id: agentId,
658
- tenantId,
659
- projectId,
660
- name: internalAgent.name || '',
661
- description: internalAgent.description || '',
662
- prompt: internalAgent.prompt || '',
663
- conversationHistoryConfig: internalAgent.conversationHistoryConfig,
664
- models: finalModelSettings,
665
- stopWhen: internalAgent.stopWhen,
666
- },
667
- });
668
- logger.info({ agentId }, 'Internal agent processed successfully');
669
- }
670
- catch (error) {
671
- logger.error({ agentId, error }, 'Failed to create/update internal agent');
672
- throw error;
673
- }
674
- });
675
- await Promise.all(internalAgentPromises);
676
- const internalAgentCount = Object.entries(typedGraphDefinition.agents).filter(([_, agentData]) => isInternalAgent(agentData)).length;
677
- logger.info({ internalAgentCount }, 'All internal agents created/updated successfully');
678
- // Step 7: Create/update external agents
679
- const externalAgentPromises = Object.entries(typedGraphDefinition.agents)
680
- .filter(([_, agentData]) => isExternalAgent(agentData)) // External agents have baseUrl
681
- .map(async ([agentId, agentData]) => {
682
- // Type assertion since we've filtered for external agents
683
- const externalAgent = agentData;
684
- try {
685
- logger.info({ agentId }, 'Processing external agent');
686
- await upsertExternalAgent(db)({
687
- data: {
688
- id: agentId,
689
- tenantId,
690
- projectId,
691
- name: externalAgent.name,
692
- description: externalAgent.description || '',
693
- baseUrl: externalAgent.baseUrl,
694
- credentialReferenceId: externalAgent.credentialReferenceId || undefined,
695
- headers: externalAgent.headers || undefined,
696
- },
697
- });
698
- logger.info({ agentId }, 'External agent processed successfully');
699
- }
700
- catch (error) {
701
- logger.error({ agentId, error }, 'Failed to create/update external agent');
702
- throw error;
703
- }
704
- });
705
- await Promise.all(externalAgentPromises);
706
- const externalAgentCount = Object.entries(typedGraphDefinition.agents).filter(([_, agentData]) => isExternalAgent(agentData)).length;
707
- logger.info({ externalAgentCount }, 'All external agents created/updated successfully');
708
- // Step 8: Update the graph metadata
709
- await updateAgentGraph(db)({
710
- scopes: { tenantId, projectId },
711
- graphId: typedGraphDefinition.id,
712
- data: {
713
- name: typedGraphDefinition.name,
714
- defaultAgentId: typedGraphDefinition.defaultAgentId,
715
- description: typedGraphDefinition.description,
716
- contextConfigId: contextConfigId,
717
- models: typedGraphDefinition.models,
718
- statusUpdates: typedGraphDefinition.statusUpdates,
719
- graphPrompt: typedGraphDefinition.graphPrompt,
720
- stopWhen: typedGraphDefinition.stopWhen,
721
- },
722
- });
723
- logger.info({ graphId: typedGraphDefinition.id }, 'Graph metadata updated');
724
- // Step 9: Clear and recreate agent-tool relationships
725
- // First, delete existing relationships for all agents in this graph
726
- for (const agentId of Object.keys(typedGraphDefinition.agents)) {
727
- await deleteAgentToolRelationByAgent(db)({
728
- scopes: { tenantId, projectId },
729
- agentId,
730
- });
731
- }
732
- // Then create new relationships
733
- const agentToolPromises = [];
734
- for (const [agentId, agentData] of Object.entries(typedGraphDefinition.agents)) {
735
- if (isInternalAgent(agentData) && agentData.tools && Array.isArray(agentData.tools)) {
736
- for (const toolId of agentData.tools) {
737
- agentToolPromises.push((async () => {
738
- try {
739
- await createAgentToolRelation(db)({
740
- scopes: { tenantId, projectId },
741
- data: {
742
- agentId,
743
- toolId,
744
- },
745
- });
746
- logger.info({ agentId, toolId }, 'Agent-tool relation created');
747
- }
748
- catch (error) {
749
- logger.error({ agentId, toolId, error }, 'Failed to create agent-tool relation');
750
- // Don't throw - allow partial success for relations
751
- }
752
- })());
753
- }
754
- }
755
- }
756
- await Promise.all(agentToolPromises);
757
- logger.info({ agentToolPromisesCount: agentToolPromises.length }, 'All agent-tool relations updated');
758
- // Step 10: Clear and recreate agent-dataComponent relationships
759
- // First, delete existing relationships for all agents in this graph
760
- for (const agentId of Object.keys(typedGraphDefinition.agents)) {
761
- await deleteAgentDataComponentRelationByAgent(db)({
762
- scopes: { tenantId, projectId },
763
- agentId,
764
- });
765
- }
766
- // Then create new agent-dataComponent relationships
767
- const agentDataComponentPromises = [];
768
- for (const [agentId, agentData] of Object.entries(typedGraphDefinition.agents)) {
769
- if (isInternalAgent(agentData) && agentData.dataComponents) {
770
- for (const dataComponentId of agentData.dataComponents) {
771
- agentDataComponentPromises.push((async () => {
772
- try {
773
- await associateDataComponentWithAgent(db)({
774
- scopes: { tenantId, projectId },
775
- agentId,
776
- dataComponentId,
777
- });
778
- logger.info({ agentId, dataComponentId }, 'Agent-dataComponent relation created');
779
- }
780
- catch (error) {
781
- logger.error({ agentId, dataComponentId, error }, 'Failed to create agent-dataComponent relation');
782
- // Don't throw - allow partial success for relations
783
- }
784
- })());
785
- }
786
- }
787
- }
788
- await Promise.all(agentDataComponentPromises);
789
- logger.info({ agentDataComponentPromisesCount: agentDataComponentPromises.length }, 'All agent-dataComponent relations updated');
790
- // Step 11: Clear and recreate agent-artifactComponent relationships
791
- // First, delete existing relationships for all agents in this graph
792
- for (const agentId of Object.keys(typedGraphDefinition.agents)) {
793
- await deleteAgentArtifactComponentRelationByAgent(db)({
794
- scopes: { tenantId, projectId },
795
- agentId,
796
- });
797
- }
798
- // Then create new agent-artifactComponent relationships
799
- const agentArtifactComponentPromises = [];
800
- for (const [agentId, agentData] of Object.entries(typedGraphDefinition.agents)) {
801
- if (isInternalAgent(agentData) && agentData.artifactComponents) {
802
- for (const artifactComponentId of agentData.artifactComponents) {
803
- agentArtifactComponentPromises.push((async () => {
804
- try {
805
- await associateArtifactComponentWithAgent(db)({
806
- scopes: { tenantId, projectId },
807
- agentId,
808
- artifactComponentId,
809
- });
810
- logger.info({ agentId, artifactComponentId }, 'Agent-artifactComponent relation created');
811
- }
812
- catch (error) {
813
- logger.error({ agentId, artifactComponentId, error }, 'Failed to create agent-artifactComponent relation');
814
- // Don't throw - allow partial success for relations
815
- }
816
- })());
817
- }
818
- }
819
- }
820
- await Promise.all(agentArtifactComponentPromises);
821
- logger.info({ agentArtifactComponentPromisesCount: agentArtifactComponentPromises.length }, 'All agent-artifactComponent relations updated');
822
- // Step 12: Clear and recreate agent relationships
823
- // First, delete existing relationships for this graph
824
- await deleteAgentRelationsByGraph(db)({
825
- scopes: { tenantId, projectId },
826
- graphId: typedGraphDefinition.id,
827
- });
828
- // Then create new relationships
829
- const agentRelationPromises = [];
830
- for (const [agentId, agentData] of Object.entries(typedGraphDefinition.agents)) {
831
- // Create transfer relations
832
- if (isInternalAgent(agentData) && agentData.canTransferTo) {
833
- for (const targetAgentId of agentData.canTransferTo) {
834
- agentRelationPromises.push((async () => {
835
- try {
836
- // Check if the target agent is external by looking it up in the typed.agents
837
- const targetAgentData = typedGraphDefinition.agents[targetAgentId];
838
- const isTargetExternal = isExternalAgent(targetAgentData);
839
- const targetField = isTargetExternal ? 'externalAgentId' : 'targetAgentId';
840
- const relationData = {
841
- id: nanoid(),
842
- graphId: typedGraphDefinition.id || '',
843
- sourceAgentId: agentId,
844
- relationType: 'transfer',
845
- [targetField]: targetAgentId,
846
- };
847
- await createAgentRelation(db)({
848
- tenantId,
849
- projectId,
850
- ...relationData,
851
- });
852
- logger.info({ agentId, targetAgentId, isTargetExternal }, 'Transfer relation created');
853
- }
854
- catch (error) {
855
- logger.error({ agentId, targetAgentId, error }, 'Failed to create transfer relation');
856
- }
857
- })());
858
- }
859
- }
860
- // Create delegation relations
861
- if (isInternalAgent(agentData) && agentData.canDelegateTo) {
862
- for (const targetAgentId of agentData.canDelegateTo) {
863
- // External agents can't delegate to other agents
864
- // Check if the target agent is external by looking it up in the typed.agents
865
- const targetAgentData = typedGraphDefinition.agents[targetAgentId];
866
- const isTargetExternal = isExternalAgent(targetAgentData);
867
- const targetField = isTargetExternal ? 'externalAgentId' : 'targetAgentId';
868
- agentRelationPromises.push((async () => {
869
- try {
870
- const relationData = {
871
- id: nanoid(),
872
- graphId: typedGraphDefinition.id || '',
873
- sourceAgentId: agentId,
874
- relationType: 'delegate',
875
- [targetField]: targetAgentId,
876
- };
877
- await createAgentRelation(db)({
878
- tenantId,
879
- projectId,
880
- ...relationData,
881
- });
882
- logger.info({ agentId, targetAgentId }, 'Delegation relation created');
883
- }
884
- catch (error) {
885
- logger.error({ agentId, targetAgentId, error }, 'Failed to create delegation relation');
886
- }
887
- })());
888
- }
889
- }
890
- }
891
- await Promise.all(agentRelationPromises);
892
- logger.info({ agentRelationPromisesCount: agentRelationPromises.length }, 'All agent relations updated');
893
- // Retrieve and return the updated graph
894
- const updatedGraph = await getFullGraphDefinition(db)({
895
- scopes: { tenantId, projectId },
896
- graphId: typedGraphDefinition.id,
897
- });
898
- if (!updatedGraph) {
899
- throw new Error('Failed to retrieve updated graph');
900
- }
901
- logger.info({ graphId: typedGraphDefinition.id }, 'Full graph updated successfully');
902
- return updatedGraph;
903
- }
904
- catch (error) {
905
- logger.error({ graphId: typedGraphDefinition.id, error }, 'Failed to update full graph');
906
- throw error;
907
- }
908
- };
909
- /**
910
- * Get a complete graph definition by ID
911
- */
912
- export const getFullGraph = (db, logger = defaultLogger) => async (params) => {
913
- const { scopes, graphId } = params;
914
- const { tenantId, projectId } = scopes;
915
- logger.info({ tenantId, graphId }, 'Retrieving full graph definition');
916
- try {
917
- const graph = await getFullGraphDefinition(db)({
918
- scopes: { tenantId, projectId },
919
- graphId,
920
- });
921
- if (!graph) {
922
- logger.info({ tenantId, graphId }, 'Graph not found');
923
- return null;
924
- }
925
- logger.info({
926
- tenantId,
927
- graphId,
928
- agentCount: Object.keys(graph.agents).length,
929
- }, 'Full graph retrieved successfully');
930
- return graph;
931
- }
932
- catch (error) {
933
- logger.error({
934
- tenantId,
935
- graphId,
936
- error: error instanceof Error ? error.message : 'Unknown error',
937
- }, 'Failed to retrieve full graph');
938
- throw error;
939
- }
940
- };
941
- /**
942
- * Delete a complete graph and cascade to all related entities
943
- */
944
- export const deleteFullGraph = (db, logger = defaultLogger) => async (params) => {
945
- const { scopes, graphId } = params;
946
- const { tenantId, projectId } = scopes;
947
- logger.info({ tenantId, graphId }, 'Deleting full graph and related entities');
948
- try {
949
- // Get the graph first to ensure it exists
950
- const graph = await getFullGraphDefinition(db)({
951
- scopes: { tenantId, projectId },
952
- graphId,
953
- });
954
- if (!graph) {
955
- logger.info({ tenantId, graphId }, 'Graph not found for deletion');
956
- return false;
957
- }
958
- // Step 1: Delete all agent relations for this graph
959
- await deleteAgentRelationsByGraph(db)({
960
- scopes: { tenantId, projectId },
961
- graphId,
962
- });
963
- logger.info({ tenantId, graphId }, 'Agent relations deleted');
964
- // Step 2: Delete agent-tool relations for agents in this graph
965
- const agentIds = Object.keys(graph.agents);
966
- if (agentIds.length > 0) {
967
- // Delete agent-tool relations for all agents in this graph
968
- for (const agentId of agentIds) {
969
- await deleteAgentToolRelationByAgent(db)({
970
- scopes: { tenantId, projectId },
971
- agentId,
972
- });
973
- }
974
- logger.info({ tenantId, graphId, agentCount: agentIds.length }, 'Agent-tool relations deleted');
975
- }
976
- // Step 3: Delete the graph metadata
977
- await deleteAgentGraph(db)({
978
- scopes: { tenantId, projectId },
979
- graphId,
980
- });
981
- logger.info({ tenantId, graphId }, 'Graph metadata deleted');
982
- // Note: We don't delete agents or tools themselves as they might be used in other graphs
983
- // Only relationships specific to this graph are deleted
984
- logger.info({ tenantId, graphId }, 'Full graph deleted successfully');
985
- return true;
986
- }
987
- catch (error) {
988
- logger.error({
989
- tenantId,
990
- graphId,
991
- error: error instanceof Error ? error.message : 'Unknown error',
992
- }, 'Failed to delete full graph');
993
- throw error;
994
- }
995
- };
996
- //# sourceMappingURL=graphFull.js.map