@inkeep/agents-core 0.2.1 → 0.3.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.
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
1
  export { TaskState } from './chunk-H2F72PDA.js';
2
- import { validateAndTypeGraphData, validateGraphStructure, isInternalAgent, isExternalAgent } from './chunk-GDVT5LPG.js';
3
- export { generateIdFromName, isExternalAgent, isInternalAgent, isValidResourceId, validateAgentRelationships, validateAndTypeGraphData, validateArtifactComponentReferences, validateDataComponentReferences, validateGraphStructure, validateToolReferences } from './chunk-GDVT5LPG.js';
4
- import { ContextConfigApiUpdateSchema } from './chunk-MY4NEHGT.js';
5
- export { AgentApiInsertSchema, AgentApiSelectSchema, AgentApiUpdateSchema, AgentArtifactComponentApiInsertSchema, AgentArtifactComponentApiSelectSchema, AgentArtifactComponentApiUpdateSchema, AgentArtifactComponentInsertSchema, AgentArtifactComponentSelectSchema, AgentArtifactComponentUpdateSchema, AgentDataComponentApiInsertSchema, AgentDataComponentApiSelectSchema, AgentDataComponentApiUpdateSchema, AgentDataComponentInsertSchema, AgentDataComponentSelectSchema, AgentDataComponentUpdateSchema, AgentGraphApiInsertSchema, AgentGraphApiSelectSchema, AgentGraphApiUpdateSchema, AgentGraphInsertSchema, AgentGraphSelectSchema, AgentGraphUpdateSchema, AgentInsertSchema, AgentRelationApiInsertSchema, AgentRelationApiSelectSchema, AgentRelationApiUpdateSchema, AgentRelationInsertSchema, AgentRelationQuerySchema, AgentRelationSelectSchema, AgentRelationUpdateSchema, AgentSelectSchema, AgentStopWhenSchema, AgentToolRelationApiInsertSchema, AgentToolRelationApiSelectSchema, AgentToolRelationApiUpdateSchema, AgentToolRelationInsertSchema, AgentToolRelationSelectSchema, AgentToolRelationUpdateSchema, AgentUpdateSchema, AllAgentSchema, ApiKeyApiCreationResponseSchema, ApiKeyApiInsertSchema, ApiKeyApiSelectSchema, ApiKeyApiUpdateSchema, ApiKeyInsertSchema, ApiKeySelectSchema, ApiKeyUpdateSchema, ArtifactComponentApiInsertSchema, ArtifactComponentApiSelectSchema, ArtifactComponentApiUpdateSchema, ArtifactComponentInsertSchema, ArtifactComponentSelectSchema, ArtifactComponentUpdateSchema, ContextCacheApiInsertSchema, ContextCacheApiSelectSchema, ContextCacheApiUpdateSchema, ContextCacheInsertSchema, ContextCacheSelectSchema, ContextCacheUpdateSchema, ContextConfigApiInsertSchema, ContextConfigApiSelectSchema, ContextConfigApiUpdateSchema, ContextConfigInsertSchema, ContextConfigSelectSchema, ContextConfigUpdateSchema, ConversationApiInsertSchema, ConversationApiSelectSchema, ConversationApiUpdateSchema, ConversationInsertSchema, ConversationSelectSchema, ConversationUpdateSchema, CredentialReferenceApiInsertSchema, CredentialReferenceApiSelectSchema, CredentialReferenceApiUpdateSchema, CredentialReferenceInsertSchema, CredentialReferenceSelectSchema, CredentialReferenceUpdateSchema, DataComponentApiInsertSchema, DataComponentApiSelectSchema, DataComponentApiUpdateSchema, DataComponentBaseSchema, DataComponentInsertSchema, DataComponentSelectSchema, DataComponentUpdateSchema, ErrorResponseSchema, ExistsResponseSchema, ExternalAgentApiInsertSchema, ExternalAgentApiSelectSchema, ExternalAgentApiUpdateSchema, ExternalAgentInsertSchema, ExternalAgentRelationApiInsertSchema, ExternalAgentRelationInsertSchema, ExternalAgentSelectSchema, ExternalAgentUpdateSchema, FetchConfigSchema, FetchDefinitionSchema, FullGraphAgentInsertSchema, FullGraphDefinitionSchema, FullProjectDefinitionSchema, GraphStopWhenSchema, GraphWithinContextOfProjectSchema, HeadersScopeSchema, IdParamsSchema, LedgerArtifactApiInsertSchema, LedgerArtifactApiSelectSchema, LedgerArtifactApiUpdateSchema, LedgerArtifactInsertSchema, LedgerArtifactSelectSchema, LedgerArtifactUpdateSchema, ListResponseSchema, MAX_ID_LENGTH, MCPToolConfigSchema, MIN_ID_LENGTH, McpToolDefinitionSchema, McpToolSchema, McpTransportConfigSchema, MessageApiInsertSchema, MessageApiSelectSchema, MessageApiUpdateSchema, MessageInsertSchema, MessageSelectSchema, MessageUpdateSchema, ModelSchema, ModelSettingsSchema, PaginationQueryParamsSchema, PaginationSchema, ProjectApiInsertSchema, ProjectApiSelectSchema, ProjectApiUpdateSchema, ProjectInsertSchema, ProjectModelSchema, ProjectSelectSchema, ProjectUpdateSchema, RemovedResponseSchema, SingleResponseSchema, StatusComponentSchema, StatusUpdateSchema, StopWhenSchema, TaskApiInsertSchema, TaskApiSelectSchema, TaskApiUpdateSchema, TaskInsertSchema, TaskRelationApiInsertSchema, TaskRelationApiSelectSchema, TaskRelationApiUpdateSchema, TaskRelationInsertSchema, TaskRelationSelectSchema, TaskRelationUpdateSchema, TaskSelectSchema, TaskUpdateSchema, TenantIdParamsSchema, TenantParamsSchema, TenantProjectIdParamsSchema, TenantProjectParamsSchema, ToolApiInsertSchema, ToolApiSelectSchema, ToolApiUpdateSchema, ToolInsertSchema, ToolSelectSchema, ToolStatusSchema, ToolUpdateSchema, URL_SAFE_ID_PATTERN, resourceIdSchema } from './chunk-MY4NEHGT.js';
2
+ import { validateAndTypeGraphData, validateGraphStructure, isInternalAgent, isExternalAgent } from './chunk-XQRFKXVV.js';
3
+ export { generateIdFromName, isExternalAgent, isInternalAgent, isValidResourceId, validateAgentRelationships, validateAndTypeGraphData, validateArtifactComponentReferences, validateDataComponentReferences, validateGraphStructure, validateToolReferences } from './chunk-XQRFKXVV.js';
4
+ import { ContextConfigApiUpdateSchema } from './chunk-LPIKPCE5.js';
5
+ export { AgentApiInsertSchema, AgentApiSelectSchema, AgentApiUpdateSchema, AgentArtifactComponentApiInsertSchema, AgentArtifactComponentApiSelectSchema, AgentArtifactComponentApiUpdateSchema, AgentArtifactComponentInsertSchema, AgentArtifactComponentSelectSchema, AgentArtifactComponentUpdateSchema, AgentDataComponentApiInsertSchema, AgentDataComponentApiSelectSchema, AgentDataComponentApiUpdateSchema, AgentDataComponentInsertSchema, AgentDataComponentSelectSchema, AgentDataComponentUpdateSchema, AgentGraphApiInsertSchema, AgentGraphApiSelectSchema, AgentGraphApiUpdateSchema, AgentGraphInsertSchema, AgentGraphSelectSchema, AgentGraphUpdateSchema, AgentInsertSchema, AgentRelationApiInsertSchema, AgentRelationApiSelectSchema, AgentRelationApiUpdateSchema, AgentRelationInsertSchema, AgentRelationQuerySchema, AgentRelationSelectSchema, AgentRelationUpdateSchema, AgentSelectSchema, AgentStopWhenSchema, AgentToolRelationApiInsertSchema, AgentToolRelationApiSelectSchema, AgentToolRelationApiUpdateSchema, AgentToolRelationInsertSchema, AgentToolRelationSelectSchema, AgentToolRelationUpdateSchema, AgentUpdateSchema, AllAgentSchema, ApiKeyApiCreationResponseSchema, ApiKeyApiInsertSchema, ApiKeyApiSelectSchema, ApiKeyApiUpdateSchema, ApiKeyInsertSchema, ApiKeySelectSchema, ApiKeyUpdateSchema, ArtifactComponentApiInsertSchema, ArtifactComponentApiSelectSchema, ArtifactComponentApiUpdateSchema, ArtifactComponentInsertSchema, ArtifactComponentSelectSchema, ArtifactComponentUpdateSchema, ContextCacheApiInsertSchema, ContextCacheApiSelectSchema, ContextCacheApiUpdateSchema, ContextCacheInsertSchema, ContextCacheSelectSchema, ContextCacheUpdateSchema, ContextConfigApiInsertSchema, ContextConfigApiSelectSchema, ContextConfigApiUpdateSchema, ContextConfigInsertSchema, ContextConfigSelectSchema, ContextConfigUpdateSchema, ConversationApiInsertSchema, ConversationApiSelectSchema, ConversationApiUpdateSchema, ConversationInsertSchema, ConversationSelectSchema, ConversationUpdateSchema, CredentialReferenceApiInsertSchema, CredentialReferenceApiSelectSchema, CredentialReferenceApiUpdateSchema, CredentialReferenceInsertSchema, CredentialReferenceSelectSchema, CredentialReferenceUpdateSchema, DataComponentApiInsertSchema, DataComponentApiSelectSchema, DataComponentApiUpdateSchema, DataComponentBaseSchema, DataComponentInsertSchema, DataComponentSelectSchema, DataComponentUpdateSchema, ErrorResponseSchema, ExistsResponseSchema, ExternalAgentApiInsertSchema, ExternalAgentApiSelectSchema, ExternalAgentApiUpdateSchema, ExternalAgentInsertSchema, ExternalAgentRelationApiInsertSchema, ExternalAgentRelationInsertSchema, ExternalAgentSelectSchema, ExternalAgentUpdateSchema, FetchConfigSchema, FetchDefinitionSchema, FullGraphAgentInsertSchema, FullGraphDefinitionSchema, FullProjectDefinitionSchema, GraphStopWhenSchema, GraphWithinContextOfProjectSchema, HeadersScopeSchema, IdParamsSchema, LedgerArtifactApiInsertSchema, LedgerArtifactApiSelectSchema, LedgerArtifactApiUpdateSchema, LedgerArtifactInsertSchema, LedgerArtifactSelectSchema, LedgerArtifactUpdateSchema, ListResponseSchema, MAX_ID_LENGTH, MCPToolConfigSchema, MIN_ID_LENGTH, McpToolDefinitionSchema, McpToolSchema, McpTransportConfigSchema, MessageApiInsertSchema, MessageApiSelectSchema, MessageApiUpdateSchema, MessageInsertSchema, MessageSelectSchema, MessageUpdateSchema, ModelSchema, ModelSettingsSchema, PaginationQueryParamsSchema, PaginationSchema, ProjectApiInsertSchema, ProjectApiSelectSchema, ProjectApiUpdateSchema, ProjectInsertSchema, ProjectModelSchema, ProjectSelectSchema, ProjectUpdateSchema, RemovedResponseSchema, SingleResponseSchema, StatusComponentSchema, StatusUpdateSchema, StopWhenSchema, TaskApiInsertSchema, TaskApiSelectSchema, TaskApiUpdateSchema, TaskInsertSchema, TaskRelationApiInsertSchema, TaskRelationApiSelectSchema, TaskRelationApiUpdateSchema, TaskRelationInsertSchema, TaskRelationSelectSchema, TaskRelationUpdateSchema, TaskSelectSchema, TaskUpdateSchema, TenantIdParamsSchema, TenantParamsSchema, TenantProjectGraphIdParamsSchema, TenantProjectGraphParamsSchema, TenantProjectIdParamsSchema, TenantProjectParamsSchema, ToolApiInsertSchema, ToolApiSelectSchema, ToolApiUpdateSchema, ToolInsertSchema, ToolSelectSchema, ToolStatusSchema, ToolUpdateSchema, URL_SAFE_ID_PATTERN, resourceIdSchema } from './chunk-LPIKPCE5.js';
6
6
  import { CredentialStoreType, MCPServerType, MCPTransportType } from './chunk-SVGQSPW4.js';
7
7
  export { CredentialStoreType, MCPServerType, MCPTransportType, TOOL_STATUS_VALUES, VALID_RELATION_TYPES } from './chunk-SVGQSPW4.js';
8
- import { schema_exports, agentRelations, agents, externalAgents, agentToolRelations, tools, contextConfigs, agentGraph, agentDataComponents, agentArtifactComponents, dataComponents, artifactComponents, projects, apiKeys, contextCache, conversations, messages, credentialReferences, ledgerArtifacts, tasks, taskRelations } from './chunk-MXQKLGQK.js';
9
- export { agentArtifactComponents, agentArtifactComponentsRelations, agentDataComponents, agentGraph, agentGraphRelations, agentRelations, agentRelationsRelations, agentToolRelations, agentToolRelationsRelations, agents, agentsRelations, apiKeys, apiKeysRelations, artifactComponents, artifactComponentsRelations, contextCache, contextCacheRelations, contextConfigs, contextConfigsRelations, conversations, conversationsRelations, credentialReferences, credentialReferencesRelations, dataComponents, externalAgents, externalAgentsRelations, ledgerArtifacts, ledgerArtifactsContextIdIdx, ledgerArtifactsTaskContextNameUnique, ledgerArtifactsTaskIdIdx, messages, messagesRelations, projects, projectsRelations, taskRelations, taskRelationsRelations, tasks, tasksRelations, tools, toolsRelations } from './chunk-MXQKLGQK.js';
8
+ import { schema_exports, agentRelations, agents, externalAgents, agentToolRelations, tools, contextConfigs, agentGraph, agentDataComponents, agentArtifactComponents, dataComponents, artifactComponents, projects, apiKeys, contextCache, conversations, messages, credentialReferences, ledgerArtifacts, tasks, taskRelations } from './chunk-LFWFXR4O.js';
9
+ export { agentArtifactComponents, agentArtifactComponentsRelations, agentDataComponents, agentDataComponentsRelations, agentGraph, agentGraphRelations, agentRelations, agentRelationsRelations, agentToolRelations, agentToolRelationsRelations, agents, agentsRelations, apiKeys, apiKeysRelations, artifactComponents, artifactComponentsRelations, contextCache, contextCacheRelations, contextConfigs, contextConfigsRelations, conversations, conversationsRelations, credentialReferences, credentialReferencesRelations, dataComponents, dataComponentsRelations, externalAgents, externalAgentsRelations, ledgerArtifacts, ledgerArtifactsContextIdIdx, ledgerArtifactsRelations, ledgerArtifactsTaskContextNameUnique, ledgerArtifactsTaskIdIdx, messages, messagesRelations, projects, projectsRelations, taskRelations, taskRelationsRelations, tasks, tasksRelations, tools, toolsRelations } from './chunk-LFWFXR4O.js';
10
10
  import { __publicField } from './chunk-MKBO26DX.js';
11
11
  import { z as z$1 } from 'zod';
12
12
  import jmespath from 'jmespath';
13
13
  import { createClient } from '@libsql/client';
14
14
  import { drizzle } from 'drizzle-orm/libsql';
15
- import { and, eq, desc, count, isNotNull, inArray, sql, asc, like } from 'drizzle-orm';
15
+ import { and, eq, desc, count, isNotNull, inArray, sql, asc } from 'drizzle-orm';
16
16
  import { customAlphabet, nanoid } from 'nanoid';
17
17
  import crypto, { scrypt, randomBytes, timingSafeEqual } from 'crypto';
18
18
  import { promisify } from 'util';
@@ -29,6 +29,12 @@ import { tool } from 'ai';
29
29
  import { asyncExitHook, gracefulExit } from 'exit-hook';
30
30
  import { match } from 'ts-pattern';
31
31
  import { Nango } from '@nangohq/node';
32
+ import fs from 'fs';
33
+ import os from 'os';
34
+ import path from 'path';
35
+ import dotenv from 'dotenv';
36
+ import { expand } from 'dotenv-expand';
37
+ import { findUpSync } from 'find-up';
32
38
 
33
39
  // src/utils/logger.ts
34
40
  var ConsoleLogger = class {
@@ -418,8 +424,8 @@ var _TemplateEngine = class _TemplateEngine {
418
424
  * Process variable substitutions {{variable.path}} using JMESPath
419
425
  */
420
426
  static processVariables(template, context, options) {
421
- return template.replace(/\{\{([^}]+)\}\}/g, (match2, path) => {
422
- const trimmedPath = path.trim();
427
+ return template.replace(/\{\{([^}]+)\}\}/g, (match2, path2) => {
428
+ const trimmedPath = path2.trim();
423
429
  try {
424
430
  if (trimmedPath.startsWith("$")) {
425
431
  return _TemplateEngine.processBuiltinVariable(trimmedPath);
@@ -784,6 +790,7 @@ var getAgentRelationById = (db) => async (params) => {
784
790
  where: and(
785
791
  eq(agentRelations.tenantId, params.scopes.tenantId),
786
792
  eq(agentRelations.projectId, params.scopes.projectId),
793
+ eq(agentRelations.graphId, params.scopes.graphId),
787
794
  eq(agentRelations.id, params.relationId)
788
795
  )
789
796
  });
@@ -794,7 +801,8 @@ var listAgentRelations = (db) => async (params) => {
794
801
  const offset = (page - 1) * limit;
795
802
  const whereClause = and(
796
803
  eq(agentRelations.tenantId, params.scopes.tenantId),
797
- eq(agentRelations.projectId, params.scopes.projectId)
804
+ eq(agentRelations.projectId, params.scopes.projectId),
805
+ eq(agentRelations.graphId, params.scopes.graphId)
798
806
  );
799
807
  const [data, totalResult] = await Promise.all([
800
808
  db.select().from(agentRelations).where(whereClause).limit(limit).offset(offset).orderBy(desc(agentRelations.createdAt)),
@@ -809,8 +817,8 @@ var getAgentRelations = (db) => async (params) => {
809
817
  where: and(
810
818
  eq(agentRelations.tenantId, params.scopes.tenantId),
811
819
  eq(agentRelations.projectId, params.scopes.projectId),
812
- eq(agentRelations.graphId, params.graphId),
813
- eq(agentRelations.sourceAgentId, params.agentId)
820
+ eq(agentRelations.graphId, params.scopes.graphId),
821
+ eq(agentRelations.sourceAgentId, params.scopes.agentId)
814
822
  )
815
823
  });
816
824
  };
@@ -819,7 +827,7 @@ var getAgentRelationsByGraph = (db) => async (params) => {
819
827
  where: and(
820
828
  eq(agentRelations.tenantId, params.scopes.tenantId),
821
829
  eq(agentRelations.projectId, params.scopes.projectId),
822
- eq(agentRelations.graphId, params.graphId)
830
+ eq(agentRelations.graphId, params.scopes.graphId)
823
831
  )
824
832
  });
825
833
  };
@@ -830,6 +838,7 @@ var getAgentRelationsBySource = (db) => async (params) => {
830
838
  const whereClause = and(
831
839
  eq(agentRelations.tenantId, params.scopes.tenantId),
832
840
  eq(agentRelations.projectId, params.scopes.projectId),
841
+ eq(agentRelations.graphId, params.scopes.graphId),
833
842
  eq(agentRelations.sourceAgentId, params.sourceAgentId)
834
843
  );
835
844
  const [data, totalResult] = await Promise.all([
@@ -850,6 +859,7 @@ var getAgentRelationsByTarget = (db) => async (params) => {
850
859
  const whereClause = and(
851
860
  eq(agentRelations.tenantId, params.scopes.tenantId),
852
861
  eq(agentRelations.projectId, params.scopes.projectId),
862
+ eq(agentRelations.graphId, params.scopes.graphId),
853
863
  eq(agentRelations.targetAgentId, params.targetAgentId)
854
864
  );
855
865
  const [data, totalResult] = await Promise.all([
@@ -870,6 +880,7 @@ var getExternalAgentRelations = (db) => async (params) => {
870
880
  const whereClause = and(
871
881
  eq(agentRelations.tenantId, params.scopes.tenantId),
872
882
  eq(agentRelations.projectId, params.scopes.projectId),
883
+ eq(agentRelations.graphId, params.scopes.graphId),
873
884
  eq(agentRelations.externalAgentId, params.externalAgentId)
874
885
  );
875
886
  const [data, totalResult] = await Promise.all([
@@ -893,11 +904,12 @@ var getRelatedAgentsForGraph = (db) => async (params) => {
893
904
  and(
894
905
  eq(agentRelations.tenantId, params.scopes.tenantId),
895
906
  eq(agentRelations.projectId, params.scopes.projectId),
896
- eq(agentRelations.graphId, params.graphId),
907
+ eq(agentRelations.graphId, params.scopes.graphId),
897
908
  eq(agentRelations.sourceAgentId, params.agentId),
898
909
  isNotNull(agentRelations.targetAgentId),
899
910
  eq(agents.tenantId, params.scopes.tenantId),
900
- eq(agents.projectId, params.scopes.projectId)
911
+ eq(agents.projectId, params.scopes.projectId),
912
+ eq(agents.graphId, params.scopes.graphId)
901
913
  )
902
914
  );
903
915
  const externalRelations = await db.select({
@@ -913,11 +925,12 @@ var getRelatedAgentsForGraph = (db) => async (params) => {
913
925
  and(
914
926
  eq(agentRelations.tenantId, params.scopes.tenantId),
915
927
  eq(agentRelations.projectId, params.scopes.projectId),
916
- eq(agentRelations.graphId, params.graphId),
928
+ eq(agentRelations.graphId, params.scopes.graphId),
917
929
  eq(agentRelations.sourceAgentId, params.agentId),
918
930
  isNotNull(agentRelations.externalAgentId),
919
931
  eq(externalAgents.tenantId, params.scopes.tenantId),
920
- eq(externalAgents.projectId, params.scopes.projectId)
932
+ eq(externalAgents.projectId, params.scopes.projectId),
933
+ eq(externalAgents.graphId, params.scopes.graphId)
921
934
  )
922
935
  );
923
936
  return {
@@ -943,7 +956,7 @@ var getAgentRelationByParams = (db) => async (params) => {
943
956
  const whereConditions = [
944
957
  eq(agentRelations.tenantId, params.scopes.tenantId),
945
958
  eq(agentRelations.projectId, params.scopes.projectId),
946
- eq(agentRelations.graphId, params.graphId),
959
+ eq(agentRelations.graphId, params.scopes.graphId),
947
960
  eq(agentRelations.sourceAgentId, params.sourceAgentId),
948
961
  eq(agentRelations.relationType, params.relationType)
949
962
  ];
@@ -959,8 +972,7 @@ var getAgentRelationByParams = (db) => async (params) => {
959
972
  };
960
973
  var upsertAgentRelation = (db) => async (params) => {
961
974
  const existing = await getAgentRelationByParams(db)({
962
- scopes: { tenantId: params.tenantId, projectId: params.projectId },
963
- graphId: params.graphId,
975
+ scopes: { tenantId: params.tenantId, projectId: params.projectId, graphId: params.graphId },
964
976
  sourceAgentId: params.sourceAgentId,
965
977
  targetAgentId: params.targetAgentId,
966
978
  externalAgentId: params.externalAgentId,
@@ -986,6 +998,7 @@ var updateAgentRelation = (db) => async (params) => {
986
998
  and(
987
999
  eq(agentRelations.tenantId, params.scopes.tenantId),
988
1000
  eq(agentRelations.projectId, params.scopes.projectId),
1001
+ eq(agentRelations.graphId, params.scopes.graphId),
989
1002
  eq(agentRelations.id, params.relationId)
990
1003
  )
991
1004
  ).returning();
@@ -996,6 +1009,7 @@ var deleteAgentRelation = (db) => async (params) => {
996
1009
  and(
997
1010
  eq(agentRelations.tenantId, params.scopes.tenantId),
998
1011
  eq(agentRelations.projectId, params.scopes.projectId),
1012
+ eq(agentRelations.graphId, params.scopes.graphId),
999
1013
  eq(agentRelations.id, params.relationId)
1000
1014
  )
1001
1015
  );
@@ -1005,7 +1019,7 @@ var deleteAgentRelationsByGraph = (db) => async (params) => {
1005
1019
  const result = await db.delete(agentRelations).where(
1006
1020
  and(
1007
1021
  eq(agentRelations.tenantId, params.scopes.tenantId),
1008
- eq(agentRelations.graphId, params.graphId)
1022
+ eq(agentRelations.graphId, params.scopes.graphId)
1009
1023
  )
1010
1024
  );
1011
1025
  return (result.rowsAffected || 0) > 0;
@@ -1016,6 +1030,7 @@ var createAgentToolRelation = (db) => async (params) => {
1016
1030
  id: finalRelationId,
1017
1031
  tenantId: params.scopes.tenantId,
1018
1032
  projectId: params.scopes.projectId,
1033
+ graphId: params.scopes.graphId,
1019
1034
  agentId: params.data.agentId,
1020
1035
  toolId: params.data.toolId,
1021
1036
  selectedTools: params.data.selectedTools
@@ -1031,6 +1046,7 @@ var updateAgentToolRelation = (db) => async (params) => {
1031
1046
  and(
1032
1047
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1033
1048
  eq(agentToolRelations.projectId, params.scopes.projectId),
1049
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1034
1050
  eq(agentToolRelations.id, params.relationId)
1035
1051
  )
1036
1052
  ).returning();
@@ -1041,6 +1057,7 @@ var deleteAgentToolRelation = (db) => async (params) => {
1041
1057
  and(
1042
1058
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1043
1059
  eq(agentToolRelations.projectId, params.scopes.projectId),
1060
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1044
1061
  eq(agentToolRelations.id, params.relationId)
1045
1062
  )
1046
1063
  );
@@ -1050,7 +1067,9 @@ var deleteAgentToolRelationByAgent = (db) => async (params) => {
1050
1067
  const result = await db.delete(agentToolRelations).where(
1051
1068
  and(
1052
1069
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1053
- eq(agentToolRelations.agentId, params.agentId)
1070
+ eq(agentToolRelations.projectId, params.scopes.projectId),
1071
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1072
+ eq(agentToolRelations.agentId, params.scopes.agentId)
1054
1073
  )
1055
1074
  );
1056
1075
  return (result.rowsAffected || 0) > 0;
@@ -1060,6 +1079,7 @@ var getAgentToolRelationById = (db) => async (params) => {
1060
1079
  where: and(
1061
1080
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1062
1081
  eq(agentToolRelations.projectId, params.scopes.projectId),
1082
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1063
1083
  eq(agentToolRelations.id, params.relationId)
1064
1084
  )
1065
1085
  });
@@ -1073,14 +1093,14 @@ var getAgentToolRelationByAgent = (db) => async (params) => {
1073
1093
  and(
1074
1094
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1075
1095
  eq(agentToolRelations.projectId, params.scopes.projectId),
1076
- eq(agentToolRelations.agentId, params.agentId)
1096
+ eq(agentToolRelations.agentId, params.scopes.agentId)
1077
1097
  )
1078
1098
  ).limit(limit).offset(offset).orderBy(desc(agentToolRelations.createdAt)),
1079
1099
  db.select({ count: count() }).from(agentToolRelations).where(
1080
1100
  and(
1081
1101
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1082
1102
  eq(agentToolRelations.projectId, params.scopes.projectId),
1083
- eq(agentToolRelations.agentId, params.agentId)
1103
+ eq(agentToolRelations.agentId, params.scopes.agentId)
1084
1104
  )
1085
1105
  )
1086
1106
  ]);
@@ -1100,6 +1120,7 @@ var getAgentToolRelationByTool = (db) => async (params) => {
1100
1120
  and(
1101
1121
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1102
1122
  eq(agentToolRelations.projectId, params.scopes.projectId),
1123
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1103
1124
  eq(agentToolRelations.toolId, params.toolId)
1104
1125
  )
1105
1126
  ).limit(limit).offset(offset).orderBy(desc(agentToolRelations.createdAt)),
@@ -1107,6 +1128,7 @@ var getAgentToolRelationByTool = (db) => async (params) => {
1107
1128
  and(
1108
1129
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1109
1130
  eq(agentToolRelations.projectId, params.scopes.projectId),
1131
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1110
1132
  eq(agentToolRelations.toolId, params.toolId)
1111
1133
  )
1112
1134
  )
@@ -1126,13 +1148,15 @@ var listAgentToolRelations = (db) => async (params) => {
1126
1148
  db.select().from(agentToolRelations).where(
1127
1149
  and(
1128
1150
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1129
- eq(agentToolRelations.projectId, params.scopes.projectId)
1151
+ eq(agentToolRelations.projectId, params.scopes.projectId),
1152
+ eq(agentToolRelations.graphId, params.scopes.graphId)
1130
1153
  )
1131
1154
  ).limit(limit).offset(offset).orderBy(desc(agentToolRelations.createdAt)),
1132
1155
  db.select({ count: count() }).from(agentToolRelations).where(
1133
1156
  and(
1134
1157
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1135
- eq(agentToolRelations.projectId, params.scopes.projectId)
1158
+ eq(agentToolRelations.projectId, params.scopes.projectId),
1159
+ eq(agentToolRelations.graphId, params.scopes.graphId)
1136
1160
  )
1137
1161
  )
1138
1162
  ]);
@@ -1143,26 +1167,6 @@ var listAgentToolRelations = (db) => async (params) => {
1143
1167
  pagination: { page, limit, total, pages }
1144
1168
  };
1145
1169
  };
1146
- var listAgentToolRelationsByAgent = (db) => async (params) => {
1147
- const page = params.pagination?.page || 1;
1148
- const limit = Math.min(params.pagination?.limit || 10, 100);
1149
- const offset = (page - 1) * limit;
1150
- const whereClause = and(
1151
- eq(agentToolRelations.tenantId, params.scopes.tenantId),
1152
- eq(agentToolRelations.projectId, params.scopes.projectId),
1153
- eq(agentToolRelations.agentId, params.agentId)
1154
- );
1155
- const [data, totalResult] = await Promise.all([
1156
- db.select().from(agentToolRelations).where(whereClause).limit(limit).offset(offset).orderBy(desc(agentToolRelations.createdAt)),
1157
- db.select({ count: count() }).from(agentToolRelations).where(whereClause)
1158
- ]);
1159
- const total = totalResult[0]?.count || 0;
1160
- const pages = Math.ceil(total / limit);
1161
- return {
1162
- data,
1163
- pagination: { page, limit, total, pages }
1164
- };
1165
- };
1166
1170
  var getToolsForAgent = (db) => async (params) => {
1167
1171
  const page = params.pagination?.page || 1;
1168
1172
  const limit = Math.min(params.pagination?.limit || 10, 100);
@@ -1193,14 +1197,16 @@ var getToolsForAgent = (db) => async (params) => {
1193
1197
  and(
1194
1198
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1195
1199
  eq(agentToolRelations.projectId, params.scopes.projectId),
1196
- eq(agentToolRelations.agentId, params.agentId)
1200
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1201
+ eq(agentToolRelations.agentId, params.scopes.agentId)
1197
1202
  )
1198
1203
  ).limit(limit).offset(offset).orderBy(desc(agentToolRelations.createdAt)),
1199
1204
  db.select({ count: count() }).from(agentToolRelations).where(
1200
1205
  and(
1201
1206
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1202
1207
  eq(agentToolRelations.projectId, params.scopes.projectId),
1203
- eq(agentToolRelations.agentId, params.agentId)
1208
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1209
+ eq(agentToolRelations.agentId, params.scopes.agentId)
1204
1210
  )
1205
1211
  )
1206
1212
  ]);
@@ -1229,6 +1235,9 @@ var getAgentsForTool = (db) => async (params) => {
1229
1235
  name: agents.name,
1230
1236
  description: agents.description,
1231
1237
  prompt: agents.prompt,
1238
+ conversationHistoryConfig: agents.conversationHistoryConfig,
1239
+ models: agents.models,
1240
+ stopWhen: agents.stopWhen,
1232
1241
  createdAt: agents.createdAt,
1233
1242
  updatedAt: agents.updatedAt
1234
1243
  }
@@ -1236,6 +1245,7 @@ var getAgentsForTool = (db) => async (params) => {
1236
1245
  and(
1237
1246
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1238
1247
  eq(agentToolRelations.projectId, params.scopes.projectId),
1248
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1239
1249
  eq(agentToolRelations.toolId, params.toolId)
1240
1250
  )
1241
1251
  ).limit(limit).offset(offset).orderBy(desc(agentToolRelations.createdAt)),
@@ -1243,6 +1253,7 @@ var getAgentsForTool = (db) => async (params) => {
1243
1253
  and(
1244
1254
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
1245
1255
  eq(agentToolRelations.projectId, params.scopes.projectId),
1256
+ eq(agentToolRelations.graphId, params.scopes.graphId),
1246
1257
  eq(agentToolRelations.toolId, params.toolId)
1247
1258
  )
1248
1259
  )
@@ -1259,7 +1270,8 @@ var validateInternalAgent = (db) => async (params) => {
1259
1270
  and(
1260
1271
  eq(agents.tenantId, params.scopes.tenantId),
1261
1272
  eq(agents.projectId, params.scopes.projectId),
1262
- eq(agents.id, params.agentId)
1273
+ eq(agents.graphId, params.scopes.graphId),
1274
+ eq(agents.id, params.scopes.agentId)
1263
1275
  )
1264
1276
  ).limit(1);
1265
1277
  return result.length > 0;
@@ -1269,7 +1281,8 @@ var validateExternalAgent = (db) => async (params) => {
1269
1281
  and(
1270
1282
  eq(externalAgents.tenantId, params.scopes.tenantId),
1271
1283
  eq(externalAgents.projectId, params.scopes.projectId),
1272
- eq(externalAgents.id, params.agentId)
1284
+ eq(externalAgents.graphId, params.scopes.graphId),
1285
+ eq(externalAgents.id, params.scopes.agentId)
1273
1286
  )
1274
1287
  ).limit(1);
1275
1288
  return result.length > 0;
@@ -1279,6 +1292,7 @@ var getAgentById = (db) => async (params) => {
1279
1292
  where: and(
1280
1293
  eq(agents.tenantId, params.scopes.tenantId),
1281
1294
  eq(agents.projectId, params.scopes.projectId),
1295
+ eq(agents.graphId, params.scopes.graphId),
1282
1296
  eq(agents.id, params.agentId)
1283
1297
  )
1284
1298
  });
@@ -1288,7 +1302,8 @@ var listAgents = (db) => async (params) => {
1288
1302
  return await db.query.agents.findMany({
1289
1303
  where: and(
1290
1304
  eq(agents.tenantId, params.scopes.tenantId),
1291
- eq(agents.projectId, params.scopes.projectId)
1305
+ eq(agents.projectId, params.scopes.projectId),
1306
+ eq(agents.graphId, params.scopes.graphId)
1292
1307
  )
1293
1308
  });
1294
1309
  };
@@ -1298,7 +1313,8 @@ var listAgentsPaginated = (db) => async (params) => {
1298
1313
  const offset = (page - 1) * limit;
1299
1314
  const whereClause = and(
1300
1315
  eq(agents.tenantId, params.scopes.tenantId),
1301
- eq(agents.projectId, params.scopes.projectId)
1316
+ eq(agents.projectId, params.scopes.projectId),
1317
+ eq(agents.graphId, params.scopes.graphId)
1302
1318
  );
1303
1319
  const [data, totalResult] = await Promise.all([
1304
1320
  db.select().from(agents).where(whereClause).limit(limit).offset(offset).orderBy(desc(agents.createdAt)),
@@ -1330,13 +1346,18 @@ var updateAgent = (db) => async (params) => {
1330
1346
  and(
1331
1347
  eq(agents.tenantId, params.scopes.tenantId),
1332
1348
  eq(agents.projectId, params.scopes.projectId),
1349
+ eq(agents.graphId, params.scopes.graphId),
1333
1350
  eq(agents.id, params.agentId)
1334
1351
  )
1335
1352
  ).returning();
1336
1353
  return agent[0] ?? null;
1337
1354
  };
1338
1355
  var upsertAgent = (db) => async (params) => {
1339
- const scopes = { tenantId: params.data.tenantId, projectId: params.data.projectId };
1356
+ const scopes = {
1357
+ tenantId: params.data.tenantId,
1358
+ projectId: params.data.projectId,
1359
+ graphId: params.data.graphId
1360
+ };
1340
1361
  const existing = await getAgentById(db)({
1341
1362
  scopes,
1342
1363
  agentId: params.data.id
@@ -1367,6 +1388,7 @@ var deleteAgent = (db) => async (params) => {
1367
1388
  and(
1368
1389
  eq(agents.tenantId, params.scopes.tenantId),
1369
1390
  eq(agents.projectId, params.scopes.projectId),
1391
+ eq(agents.graphId, params.scopes.graphId),
1370
1392
  eq(agents.id, params.agentId)
1371
1393
  )
1372
1394
  );
@@ -1384,36 +1406,11 @@ var getAgentsByIds = (db) => async (params) => {
1384
1406
  and(
1385
1407
  eq(agents.tenantId, params.scopes.tenantId),
1386
1408
  eq(agents.projectId, params.scopes.projectId),
1409
+ eq(agents.graphId, params.scopes.graphId),
1387
1410
  inArray(agents.id, params.agentIds)
1388
1411
  )
1389
1412
  );
1390
1413
  };
1391
- var getAgentInGraphContext = (db) => async (params) => {
1392
- return await db.select({
1393
- id: agents.id,
1394
- name: agents.name,
1395
- description: agents.description,
1396
- prompt: agents.prompt,
1397
- tenantId: agents.tenantId,
1398
- graphId: agentRelations.graphId,
1399
- sourceAgentId: agentRelations.sourceAgentId
1400
- }).from(agents).innerJoin(
1401
- agentRelations,
1402
- and(
1403
- eq(agents.tenantId, agentRelations.tenantId),
1404
- eq(agents.projectId, agentRelations.projectId),
1405
- eq(agents.id, agentRelations.sourceAgentId),
1406
- eq(agentRelations.graphId, params.graphId)
1407
- )
1408
- ).where(
1409
- and(
1410
- eq(agents.tenantId, params.scopes.tenantId),
1411
- eq(agents.projectId, params.scopes.projectId),
1412
- eq(agents.id, params.agentId),
1413
- eq(agentRelations.graphId, params.graphId)
1414
- )
1415
- );
1416
- };
1417
1414
  var getContextConfigById = (db) => async (params) => {
1418
1415
  return await db.query.contextConfigs.findFirst({
1419
1416
  where: and(
@@ -1568,6 +1565,8 @@ var getExternalAgent = (db) => async (params) => {
1568
1565
  const result = await db.query.externalAgents.findFirst({
1569
1566
  where: and(
1570
1567
  eq(externalAgents.tenantId, params.scopes.tenantId),
1568
+ eq(externalAgents.projectId, params.scopes.projectId),
1569
+ eq(externalAgents.graphId, params.scopes.graphId),
1571
1570
  eq(externalAgents.id, params.agentId)
1572
1571
  )
1573
1572
  });
@@ -1577,6 +1576,8 @@ var getExternalAgentByUrl = (db) => async (params) => {
1577
1576
  const result = await db.query.externalAgents.findFirst({
1578
1577
  where: and(
1579
1578
  eq(externalAgents.tenantId, params.scopes.tenantId),
1579
+ eq(externalAgents.projectId, params.scopes.projectId),
1580
+ eq(externalAgents.graphId, params.scopes.graphId),
1580
1581
  eq(externalAgents.baseUrl, params.baseUrl)
1581
1582
  )
1582
1583
  });
@@ -1584,7 +1585,11 @@ var getExternalAgentByUrl = (db) => async (params) => {
1584
1585
  };
1585
1586
  var listExternalAgents = (db) => async (params) => {
1586
1587
  return await db.query.externalAgents.findMany({
1587
- where: eq(externalAgents.tenantId, params.scopes.tenantId),
1588
+ where: and(
1589
+ eq(externalAgents.tenantId, params.scopes.tenantId),
1590
+ eq(externalAgents.projectId, params.scopes.projectId),
1591
+ eq(externalAgents.graphId, params.scopes.graphId)
1592
+ ),
1588
1593
  orderBy: [asc(externalAgents.name)]
1589
1594
  });
1590
1595
  };
@@ -1593,8 +1598,20 @@ var listExternalAgentsPaginated = (db) => async (params) => {
1593
1598
  const limit = Math.min(params.pagination?.limit || 10, 100);
1594
1599
  const offset = (page - 1) * limit;
1595
1600
  const [data, totalResult] = await Promise.all([
1596
- db.select().from(externalAgents).where(eq(externalAgents.tenantId, params.scopes.tenantId)).limit(limit).offset(offset).orderBy(desc(externalAgents.createdAt)),
1597
- db.select({ count: count() }).from(externalAgents).where(eq(externalAgents.tenantId, params.scopes.tenantId))
1601
+ db.select().from(externalAgents).where(
1602
+ and(
1603
+ eq(externalAgents.tenantId, params.scopes.tenantId),
1604
+ eq(externalAgents.projectId, params.scopes.projectId),
1605
+ eq(externalAgents.graphId, params.scopes.graphId)
1606
+ )
1607
+ ).limit(limit).offset(offset).orderBy(desc(externalAgents.createdAt)),
1608
+ db.select({ count: count() }).from(externalAgents).where(
1609
+ and(
1610
+ eq(externalAgents.tenantId, params.scopes.tenantId),
1611
+ eq(externalAgents.projectId, params.scopes.projectId),
1612
+ eq(externalAgents.graphId, params.scopes.graphId)
1613
+ )
1614
+ )
1598
1615
  ]);
1599
1616
  const total = typeof totalResult[0]?.count === "string" ? parseInt(totalResult[0].count, 10) : totalResult[0]?.count || 0;
1600
1617
  const pages = Math.ceil(total / limit);
@@ -1620,13 +1637,19 @@ var updateExternalAgent = (db) => async (params) => {
1620
1637
  const result = await db.update(externalAgents).set(updateData).where(
1621
1638
  and(
1622
1639
  eq(externalAgents.tenantId, params.scopes.tenantId),
1640
+ eq(externalAgents.projectId, params.scopes.projectId),
1641
+ eq(externalAgents.graphId, params.scopes.graphId),
1623
1642
  eq(externalAgents.id, params.agentId)
1624
1643
  )
1625
1644
  ).returning();
1626
1645
  return result[0] || null;
1627
1646
  };
1628
1647
  var upsertExternalAgent = (db) => async (params) => {
1629
- const scopes = { tenantId: params.data.tenantId, projectId: params.data.projectId };
1648
+ const scopes = {
1649
+ tenantId: params.data.tenantId,
1650
+ projectId: params.data.projectId,
1651
+ graphId: params.data.graphId
1652
+ };
1630
1653
  const existing = await getExternalAgent(db)({
1631
1654
  scopes,
1632
1655
  agentId: params.data.id
@@ -1656,6 +1679,8 @@ var deleteExternalAgent = (db) => async (params) => {
1656
1679
  const result = await db.delete(externalAgents).where(
1657
1680
  and(
1658
1681
  eq(externalAgents.tenantId, params.scopes.tenantId),
1682
+ eq(externalAgents.projectId, params.scopes.projectId),
1683
+ eq(externalAgents.graphId, params.scopes.graphId),
1659
1684
  eq(externalAgents.id, params.agentId)
1660
1685
  )
1661
1686
  ).returning();
@@ -1674,27 +1699,24 @@ var externalAgentUrlExists = (db) => async (params) => {
1674
1699
  return agent !== null;
1675
1700
  };
1676
1701
  var countExternalAgents = (db) => async (params) => {
1677
- const result = await db.select({ count: count() }).from(externalAgents).where(eq(externalAgents.tenantId, params.scopes.tenantId));
1702
+ const result = await db.select({ count: count() }).from(externalAgents).where(
1703
+ and(
1704
+ eq(externalAgents.tenantId, params.scopes.tenantId),
1705
+ eq(externalAgents.projectId, params.scopes.projectId),
1706
+ eq(externalAgents.graphId, params.scopes.graphId)
1707
+ )
1708
+ );
1678
1709
  const countValue = result[0]?.count;
1679
1710
  return typeof countValue === "string" ? parseInt(countValue, 10) : countValue || 0;
1680
1711
  };
1681
1712
 
1682
1713
  // src/data-access/agentGraphs.ts
1683
- var getAgentGraph = (db) => async (params) => {
1684
- return await db.query.agentGraph.findFirst({
1685
- where: and(
1686
- eq(agentGraph.tenantId, params.scopes.tenantId),
1687
- eq(agentGraph.projectId, params.scopes.projectId),
1688
- eq(agentGraph.id, params.graphId)
1689
- )
1690
- });
1691
- };
1692
1714
  var getAgentGraphById = (db) => async (params) => {
1693
1715
  const result = await db.query.agentGraph.findFirst({
1694
1716
  where: and(
1695
1717
  eq(agentGraph.tenantId, params.scopes.tenantId),
1696
1718
  eq(agentGraph.projectId, params.scopes.projectId),
1697
- eq(agentGraph.id, params.graphId)
1719
+ eq(agentGraph.id, params.scopes.graphId)
1698
1720
  )
1699
1721
  });
1700
1722
  return result ?? null;
@@ -1704,7 +1726,7 @@ var getAgentGraphWithDefaultAgent = (db) => async (params) => {
1704
1726
  where: and(
1705
1727
  eq(agentGraph.tenantId, params.scopes.tenantId),
1706
1728
  eq(agentGraph.projectId, params.scopes.projectId),
1707
- eq(agentGraph.id, params.graphId)
1729
+ eq(agentGraph.id, params.scopes.graphId)
1708
1730
  ),
1709
1731
  with: {
1710
1732
  defaultAgent: true
@@ -1797,7 +1819,7 @@ var updateAgentGraph = (db) => async (params) => {
1797
1819
  and(
1798
1820
  eq(agentGraph.tenantId, params.scopes.tenantId),
1799
1821
  eq(agentGraph.projectId, params.scopes.projectId),
1800
- eq(agentGraph.id, params.graphId)
1822
+ eq(agentGraph.id, params.scopes.graphId)
1801
1823
  )
1802
1824
  ).returning();
1803
1825
  return graph[0] ?? null;
@@ -1807,7 +1829,7 @@ var deleteAgentGraph = (db) => async (params) => {
1807
1829
  and(
1808
1830
  eq(agentGraph.tenantId, params.scopes.tenantId),
1809
1831
  eq(agentGraph.projectId, params.scopes.projectId),
1810
- eq(agentGraph.id, params.graphId)
1832
+ eq(agentGraph.id, params.scopes.graphId)
1811
1833
  )
1812
1834
  ).returning();
1813
1835
  return result.length > 0;
@@ -1834,17 +1856,14 @@ var getGraphAgentInfos = (db) => async ({
1834
1856
  agentId
1835
1857
  }) => {
1836
1858
  const { tenantId, projectId } = scopes;
1837
- const graph = await getAgentGraph(db)({
1838
- scopes: { tenantId, projectId },
1839
- graphId
1859
+ const graph = await getAgentGraphById(db)({
1860
+ scopes: { tenantId, projectId, graphId }
1840
1861
  });
1841
1862
  if (!graph) {
1842
1863
  throw new Error(`Agent graph with ID ${graphId} not found for tenant ${tenantId}`);
1843
1864
  }
1844
1865
  const relations = await getAgentRelations(db)({
1845
- scopes: { tenantId, projectId },
1846
- graphId,
1847
- agentId
1866
+ scopes: { tenantId, projectId, graphId, agentId }
1848
1867
  });
1849
1868
  const targetAgentIds = relations.map((relation) => relation.targetAgentId).filter((id) => id !== null);
1850
1869
  if (targetAgentIds.length === 0) {
@@ -1853,7 +1872,7 @@ var getGraphAgentInfos = (db) => async ({
1853
1872
  const agentInfos = await Promise.all(
1854
1873
  targetAgentIds.map(async (targetAgentId) => {
1855
1874
  const agent = await getAgentById(db)({
1856
- scopes: { tenantId, projectId },
1875
+ scopes: { tenantId, projectId, graphId },
1857
1876
  agentId: targetAgentId
1858
1877
  });
1859
1878
  if (agent !== void 0) {
@@ -1865,55 +1884,35 @@ var getGraphAgentInfos = (db) => async ({
1865
1884
  return agentInfos.filter((agent) => agent !== null);
1866
1885
  };
1867
1886
  var getFullGraphDefinition = (db) => async ({
1868
- scopes: { tenantId, projectId },
1869
- graphId
1887
+ scopes: { tenantId, projectId, graphId }
1870
1888
  }) => {
1871
1889
  const graph = await getAgentGraphById(db)({
1872
- scopes: { tenantId, projectId },
1873
- graphId
1890
+ scopes: { tenantId, projectId, graphId }
1874
1891
  });
1875
1892
  if (!graph) {
1876
1893
  return null;
1877
1894
  }
1878
1895
  const graphRelations = await getAgentRelationsByGraph(db)({
1879
- scopes: { tenantId, projectId },
1880
- graphId
1896
+ scopes: { tenantId, projectId, graphId }
1897
+ });
1898
+ const graphAgents = await db.query.agents.findMany({
1899
+ where: and(
1900
+ eq(agents.tenantId, tenantId),
1901
+ eq(agents.projectId, projectId),
1902
+ eq(agents.graphId, graphId)
1903
+ )
1881
1904
  });
1882
- const internalAgentIds = /* @__PURE__ */ new Set();
1883
1905
  const externalAgentIds = /* @__PURE__ */ new Set();
1884
- internalAgentIds.add(graph.defaultAgentId);
1885
1906
  for (const relation of graphRelations) {
1886
- if (relation.sourceAgentId) {
1887
- internalAgentIds.add(relation.sourceAgentId);
1888
- }
1889
- if (relation.targetAgentId) {
1890
- internalAgentIds.add(relation.targetAgentId);
1891
- }
1892
1907
  if (relation.externalAgentId) {
1893
1908
  externalAgentIds.add(relation.externalAgentId);
1894
1909
  }
1895
1910
  }
1896
- const agentsWithTools = await db.selectDistinct({ agentId: agentToolRelations.agentId }).from(agentToolRelations).innerJoin(tools, eq(agentToolRelations.toolId, tools.id)).where(
1897
- and(
1898
- eq(agentToolRelations.tenantId, tenantId),
1899
- eq(agentToolRelations.projectId, projectId),
1900
- // We need to find tools that belong to this graph
1901
- // Tools created as part of a graph have IDs that include the graph ID
1902
- like(tools.id, `%${graphId}%`)
1903
- )
1904
- );
1905
- for (const agentTool of agentsWithTools) {
1906
- internalAgentIds.add(agentTool.agentId);
1907
- }
1908
- const graphAgents = await Promise.all(
1909
- Array.from(internalAgentIds).map(async (agentId) => {
1910
- const agent = await getAgentById(db)({
1911
- scopes: { tenantId, projectId },
1912
- agentId
1913
- });
1911
+ const processedAgents = await Promise.all(
1912
+ graphAgents.map(async (agent) => {
1914
1913
  if (!agent) return null;
1915
1914
  const agentRelationsList = graphRelations.filter(
1916
- (relation) => relation.sourceAgentId === agentId
1915
+ (relation) => relation.sourceAgentId === agent.id
1917
1916
  );
1918
1917
  const canTransferTo = agentRelationsList.filter((rel) => rel.relationType === "transfer" || rel.relationType === "transfer_to").map((rel) => rel.targetAgentId).filter((id) => id !== null);
1919
1918
  const canDelegateTo = agentRelationsList.filter((rel) => rel.relationType === "delegate" || rel.relationType === "delegate_to").map((rel) => rel.targetAgentId || rel.externalAgentId).filter((id) => id !== null);
@@ -1930,19 +1929,19 @@ var getFullGraphDefinition = (db) => async ({
1930
1929
  lastToolsSync: tools.lastToolsSync,
1931
1930
  selectedTools: agentToolRelations.selectedTools
1932
1931
  }).from(agentToolRelations).innerJoin(tools, eq(agentToolRelations.toolId, tools.id)).where(
1933
- and(eq(agentToolRelations.tenantId, tenantId), eq(agentToolRelations.agentId, agentId))
1932
+ and(eq(agentToolRelations.tenantId, tenantId), eq(agentToolRelations.agentId, agent.id))
1934
1933
  );
1935
1934
  const agentDataComponentRelations = await db.query.agentDataComponents.findMany({
1936
1935
  where: and(
1937
1936
  eq(agentDataComponents.tenantId, tenantId),
1938
- eq(agentDataComponents.agentId, agentId)
1937
+ eq(agentDataComponents.agentId, agent.id)
1939
1938
  )
1940
1939
  });
1941
1940
  const agentDataComponentIds = agentDataComponentRelations.map((rel) => rel.dataComponentId);
1942
1941
  const agentArtifactComponentRelations = await db.query.agentArtifactComponents.findMany({
1943
1942
  where: and(
1944
1943
  eq(agentArtifactComponents.tenantId, tenantId),
1945
- eq(agentArtifactComponents.agentId, agentId)
1944
+ eq(agentArtifactComponents.agentId, agent.id)
1946
1945
  )
1947
1946
  });
1948
1947
  const agentArtifactComponentIds = agentArtifactComponentRelations.map(
@@ -1985,7 +1984,7 @@ var getFullGraphDefinition = (db) => async ({
1985
1984
  const externalAgents2 = await Promise.all(
1986
1985
  Array.from(externalAgentIds).map(async (agentId) => {
1987
1986
  const agent = await getExternalAgent(db)({
1988
- scopes: { tenantId, projectId },
1987
+ scopes: { tenantId, projectId, graphId },
1989
1988
  agentId
1990
1989
  });
1991
1990
  if (!agent) return null;
@@ -1997,7 +1996,7 @@ var getFullGraphDefinition = (db) => async ({
1997
1996
  };
1998
1997
  })
1999
1998
  );
2000
- const validAgents = [...graphAgents, ...externalAgents2].filter(
1999
+ const validAgents = [...processedAgents, ...externalAgents2].filter(
2001
2000
  (agent) => agent !== null
2002
2001
  );
2003
2002
  const agentsObject = {};
@@ -2043,6 +2042,7 @@ var getFullGraphDefinition = (db) => async ({
2043
2042
  }
2044
2043
  let dataComponentsObject = {};
2045
2044
  try {
2045
+ const internalAgentIds = graphAgents.map((agent) => agent.id);
2046
2046
  const agentIds = Array.from(internalAgentIds);
2047
2047
  dataComponentsObject = await fetchComponentRelationships(db)(
2048
2048
  { tenantId, projectId },
@@ -2065,6 +2065,7 @@ var getFullGraphDefinition = (db) => async ({
2065
2065
  }
2066
2066
  let artifactComponentsObject = {};
2067
2067
  try {
2068
+ const internalAgentIds = graphAgents.map((agent) => agent.id);
2068
2069
  const agentIds = Array.from(internalAgentIds);
2069
2070
  artifactComponentsObject = await fetchComponentRelationships(db)(
2070
2071
  { tenantId, projectId },
@@ -2171,16 +2172,14 @@ var getFullGraphDefinition = (db) => async ({
2171
2172
  return result;
2172
2173
  };
2173
2174
  var upsertAgentGraph = (db) => async (params) => {
2174
- const scopes = { tenantId: params.data.tenantId, projectId: params.data.projectId };
2175
2175
  const graphId = params.data.id || nanoid();
2176
+ const scopes = { tenantId: params.data.tenantId, projectId: params.data.projectId, graphId };
2176
2177
  const existing = await getAgentGraphById(db)({
2177
- scopes,
2178
- graphId
2178
+ scopes
2179
2179
  });
2180
2180
  if (existing) {
2181
2181
  return await updateAgentGraph(db)({
2182
2182
  scopes,
2183
- graphId,
2184
2183
  data: {
2185
2184
  name: params.data.name,
2186
2185
  defaultAgentId: params.data.defaultAgentId,
@@ -2526,7 +2525,8 @@ var getArtifactComponentsForAgent = (db) => async (params) => {
2526
2525
  and(
2527
2526
  eq(artifactComponents.tenantId, params.scopes.tenantId),
2528
2527
  eq(artifactComponents.projectId, params.scopes.projectId),
2529
- eq(agentArtifactComponents.agentId, params.agentId)
2528
+ eq(agentArtifactComponents.graphId, params.scopes.graphId),
2529
+ eq(agentArtifactComponents.agentId, params.scopes.agentId)
2530
2530
  )
2531
2531
  ).orderBy(desc(artifactComponents.createdAt));
2532
2532
  };
@@ -2535,7 +2535,8 @@ var associateArtifactComponentWithAgent = (db) => async (params) => {
2535
2535
  id: nanoid(),
2536
2536
  tenantId: params.scopes.tenantId,
2537
2537
  projectId: params.scopes.projectId,
2538
- agentId: params.agentId,
2538
+ graphId: params.scopes.graphId,
2539
+ agentId: params.scopes.agentId,
2539
2540
  artifactComponentId: params.artifactComponentId,
2540
2541
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
2541
2542
  }).returning();
@@ -2547,7 +2548,8 @@ var removeArtifactComponentFromAgent = (db) => async (params) => {
2547
2548
  and(
2548
2549
  eq(agentArtifactComponents.tenantId, params.scopes.tenantId),
2549
2550
  eq(agentArtifactComponents.projectId, params.scopes.projectId),
2550
- eq(agentArtifactComponents.agentId, params.agentId),
2551
+ eq(agentArtifactComponents.graphId, params.scopes.graphId),
2552
+ eq(agentArtifactComponents.agentId, params.scopes.agentId),
2551
2553
  eq(agentArtifactComponents.artifactComponentId, params.artifactComponentId)
2552
2554
  )
2553
2555
  ).returning();
@@ -2561,13 +2563,15 @@ var deleteAgentArtifactComponentRelationByAgent = (db) => async (params) => {
2561
2563
  const result = await db.delete(agentArtifactComponents).where(
2562
2564
  and(
2563
2565
  eq(agentArtifactComponents.tenantId, params.scopes.tenantId),
2564
- eq(agentArtifactComponents.agentId, params.agentId)
2566
+ eq(agentArtifactComponents.graphId, params.scopes.graphId),
2567
+ eq(agentArtifactComponents.agentId, params.scopes.agentId)
2565
2568
  )
2566
2569
  );
2567
2570
  return (result.rowsAffected || 0) > 0;
2568
2571
  };
2569
2572
  var getAgentsUsingArtifactComponent = (db) => async (params) => {
2570
2573
  return await db.select({
2574
+ graphId: agentArtifactComponents.graphId,
2571
2575
  agentId: agentArtifactComponents.agentId,
2572
2576
  createdAt: agentArtifactComponents.createdAt
2573
2577
  }).from(agentArtifactComponents).where(
@@ -2583,7 +2587,8 @@ var isArtifactComponentAssociatedWithAgent = (db) => async (params) => {
2583
2587
  and(
2584
2588
  eq(agentArtifactComponents.tenantId, params.scopes.tenantId),
2585
2589
  eq(agentArtifactComponents.projectId, params.scopes.projectId),
2586
- eq(agentArtifactComponents.agentId, params.agentId),
2590
+ eq(agentArtifactComponents.graphId, params.scopes.graphId),
2591
+ eq(agentArtifactComponents.agentId, params.scopes.agentId),
2587
2592
  eq(agentArtifactComponents.artifactComponentId, params.artifactComponentId)
2588
2593
  )
2589
2594
  ).limit(1);
@@ -2594,7 +2599,7 @@ var graphHasArtifactComponents = (db) => async (params) => {
2594
2599
  and(
2595
2600
  eq(agentArtifactComponents.tenantId, params.scopes.tenantId),
2596
2601
  eq(agentArtifactComponents.projectId, params.scopes.projectId),
2597
- eq(agentRelations.graphId, params.graphId)
2602
+ eq(agentRelations.graphId, params.scopes.graphId)
2598
2603
  )
2599
2604
  ).limit(1);
2600
2605
  const total = result[0]?.count || 0;
@@ -2616,7 +2621,8 @@ var countArtifactComponentsForAgent = (db) => async (params) => {
2616
2621
  and(
2617
2622
  eq(agentArtifactComponents.tenantId, params.scopes.tenantId),
2618
2623
  eq(agentArtifactComponents.projectId, params.scopes.projectId),
2619
- eq(agentArtifactComponents.agentId, params.agentId)
2624
+ eq(agentArtifactComponents.graphId, params.scopes.graphId),
2625
+ eq(agentArtifactComponents.agentId, params.scopes.agentId)
2620
2626
  )
2621
2627
  );
2622
2628
  const total = result[0]?.count || 0;
@@ -3236,7 +3242,8 @@ var getDataComponentsForAgent = (db) => async (params) => {
3236
3242
  and(
3237
3243
  eq(dataComponents.tenantId, params.scopes.tenantId),
3238
3244
  eq(dataComponents.projectId, params.scopes.projectId),
3239
- eq(agentDataComponents.agentId, params.agentId)
3245
+ eq(agentDataComponents.graphId, params.scopes.graphId),
3246
+ eq(agentDataComponents.agentId, params.scopes.agentId)
3240
3247
  )
3241
3248
  ).orderBy(desc(dataComponents.createdAt));
3242
3249
  };
@@ -3245,7 +3252,8 @@ var associateDataComponentWithAgent = (db) => async (params) => {
3245
3252
  id: nanoid(),
3246
3253
  tenantId: params.scopes.tenantId,
3247
3254
  projectId: params.scopes.projectId,
3248
- agentId: params.agentId,
3255
+ graphId: params.scopes.graphId,
3256
+ agentId: params.scopes.agentId,
3249
3257
  dataComponentId: params.dataComponentId
3250
3258
  }).returning();
3251
3259
  return association[0];
@@ -3255,7 +3263,8 @@ var removeDataComponentFromAgent = (db) => async (params) => {
3255
3263
  and(
3256
3264
  eq(agentDataComponents.tenantId, params.scopes.tenantId),
3257
3265
  eq(agentDataComponents.projectId, params.scopes.projectId),
3258
- eq(agentDataComponents.agentId, params.agentId),
3266
+ eq(agentDataComponents.graphId, params.scopes.graphId),
3267
+ eq(agentDataComponents.agentId, params.scopes.agentId),
3259
3268
  eq(agentDataComponents.dataComponentId, params.dataComponentId)
3260
3269
  )
3261
3270
  ).returning();
@@ -3265,7 +3274,8 @@ var deleteAgentDataComponentRelationByAgent = (db) => async (params) => {
3265
3274
  const result = await db.delete(agentDataComponents).where(
3266
3275
  and(
3267
3276
  eq(agentDataComponents.tenantId, params.scopes.tenantId),
3268
- eq(agentDataComponents.agentId, params.agentId)
3277
+ eq(agentDataComponents.graphId, params.scopes.graphId),
3278
+ eq(agentDataComponents.agentId, params.scopes.agentId)
3269
3279
  )
3270
3280
  );
3271
3281
  return (result.rowsAffected || 0) > 0;
@@ -3287,7 +3297,8 @@ var isDataComponentAssociatedWithAgent = (db) => async (params) => {
3287
3297
  and(
3288
3298
  eq(agentDataComponents.tenantId, params.scopes.tenantId),
3289
3299
  eq(agentDataComponents.projectId, params.scopes.projectId),
3290
- eq(agentDataComponents.agentId, params.agentId),
3300
+ eq(agentDataComponents.graphId, params.scopes.graphId),
3301
+ eq(agentDataComponents.agentId, params.scopes.agentId),
3291
3302
  eq(agentDataComponents.dataComponentId, params.dataComponentId)
3292
3303
  )
3293
3304
  ).limit(1);
@@ -3448,6 +3459,7 @@ var addToolToAgent = (db) => async (params) => {
3448
3459
  id,
3449
3460
  tenantId: params.scopes.tenantId,
3450
3461
  projectId: params.scopes.projectId,
3462
+ graphId: params.scopes.graphId,
3451
3463
  agentId: params.agentId,
3452
3464
  toolId: params.toolId,
3453
3465
  selectedTools: params.selectedTools,
@@ -3461,6 +3473,7 @@ var removeToolFromAgent = (db) => async (params) => {
3461
3473
  and(
3462
3474
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
3463
3475
  eq(agentToolRelations.projectId, params.scopes.projectId),
3476
+ eq(agentToolRelations.graphId, params.scopes.graphId),
3464
3477
  eq(agentToolRelations.agentId, params.agentId),
3465
3478
  eq(agentToolRelations.toolId, params.toolId)
3466
3479
  )
@@ -3472,6 +3485,7 @@ var upsertAgentToolRelation = (db) => async (params) => {
3472
3485
  where: and(
3473
3486
  eq(agentToolRelations.tenantId, params.scopes.tenantId),
3474
3487
  eq(agentToolRelations.projectId, params.scopes.projectId),
3488
+ eq(agentToolRelations.graphId, params.scopes.graphId),
3475
3489
  eq(agentToolRelations.agentId, params.agentId),
3476
3490
  eq(agentToolRelations.toolId, params.toolId)
3477
3491
  )
@@ -3528,11 +3542,15 @@ var getHealthyToolsForAgent = (db) => async (params) => {
3528
3542
  }).from(tools).innerJoin(
3529
3543
  agentToolRelations,
3530
3544
  and(
3531
- eq(tools.id, agentToolRelations.toolId),
3532
- eq(agentToolRelations.agentId, params.agentId),
3533
- eq(agentToolRelations.tenantId, params.scopes.tenantId)
3545
+ eq(tools.tenantId, params.scopes.tenantId),
3546
+ eq(tools.projectId, params.scopes.projectId),
3547
+ eq(agentToolRelations.tenantId, params.scopes.tenantId),
3548
+ eq(agentToolRelations.projectId, params.scopes.projectId),
3549
+ eq(agentToolRelations.graphId, params.scopes.graphId),
3550
+ eq(agentToolRelations.agentId, params.scopes.agentId),
3551
+ eq(tools.id, agentToolRelations.toolId)
3534
3552
  )
3535
- ).where(and(eq(tools.tenantId, params.scopes.tenantId), eq(tools.status, "healthy")));
3553
+ ).where(eq(tools.status, "healthy"));
3536
3554
  return healthyTools.map((row) => row.tool);
3537
3555
  };
3538
3556
 
@@ -3627,59 +3645,37 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
3627
3645
  validateGraphStructure(typed);
3628
3646
  await applyExecutionLimitsInheritance(db, logger11, { tenantId, projectId }, typed);
3629
3647
  try {
3630
- if (typed.credentialReferences && Object.keys(typed.credentialReferences).length > 0) {
3631
- logger11.info(
3632
- { credentialReferencesCount: Object.keys(typed.credentialReferences).length },
3633
- "Processing credential references"
3634
- );
3635
- const credentialRefPromises = Object.entries(typed.credentialReferences).map(
3636
- async ([_credId, credData]) => {
3637
- try {
3638
- logger11.info({ credId: credData.id }, "Processing credential reference");
3639
- await upsertCredentialReference(db)({
3640
- data: {
3641
- ...credData,
3642
- tenantId,
3643
- projectId
3644
- }
3645
- });
3646
- logger11.info({ credId: credData.id }, "Credential reference processed successfully");
3647
- } catch (error) {
3648
- logger11.error(
3649
- { credId: credData.id, error },
3650
- "Failed to create/update credential reference"
3651
- );
3652
- throw error;
3653
- }
3654
- }
3655
- );
3656
- await Promise.all(credentialRefPromises);
3657
- logger11.info(
3658
- { credentialReferencesCount: Object.keys(typed.credentialReferences).length },
3659
- "All credential references created/updated successfully"
3660
- );
3661
- }
3662
- const toolPromises = Object.entries(typed.tools || {}).map(async ([toolId, toolData]) => {
3663
- try {
3664
- logger11.info({ toolId }, "Processing tool");
3665
- await upsertTool(db)({
3666
- data: {
3667
- tenantId,
3668
- projectId,
3669
- ...toolData
3670
- }
3671
- });
3672
- logger11.info({ toolId }, "Tool processed successfully");
3673
- } catch (error) {
3674
- logger11.error({ toolId, error }, "Failed to create/update tool");
3675
- throw error;
3676
- }
3677
- });
3678
- await Promise.all(toolPromises);
3679
3648
  logger11.info(
3680
- { toolCount: Object.keys(typed.tools || {}).length },
3681
- "All tools created/updated successfully"
3649
+ {},
3650
+ "CredentialReferences are project-scoped - skipping credential reference creation in graph"
3682
3651
  );
3652
+ logger11.info({}, "Tools are project-scoped - skipping tool creation in graph");
3653
+ let finalGraphId;
3654
+ try {
3655
+ const graphId = typed.id || nanoid();
3656
+ logger11.info({ graphId }, "Creating agent graph metadata");
3657
+ const agentGraph2 = await upsertAgentGraph(db)({
3658
+ data: {
3659
+ id: graphId,
3660
+ tenantId,
3661
+ projectId,
3662
+ name: typed.name,
3663
+ defaultAgentId: typed.defaultAgentId,
3664
+ description: typed.description,
3665
+ contextConfigId: void 0,
3666
+ // Will be updated later if context config exists
3667
+ models: typed.models,
3668
+ statusUpdates: typed.statusUpdates,
3669
+ graphPrompt: typed.graphPrompt,
3670
+ stopWhen: typed.stopWhen
3671
+ }
3672
+ });
3673
+ finalGraphId = agentGraph2.id;
3674
+ logger11.info({ graphId: finalGraphId }, "Agent graph metadata created successfully");
3675
+ } catch (error) {
3676
+ logger11.error({ graphId: typed.id, error }, "Failed to create/update graph metadata");
3677
+ throw error;
3678
+ }
3683
3679
  let contextConfigId;
3684
3680
  if (typed.contextConfig) {
3685
3681
  try {
@@ -3701,66 +3697,14 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
3701
3697
  throw error;
3702
3698
  }
3703
3699
  }
3704
- if (typed.dataComponents && Object.keys(typed.dataComponents).length > 0) {
3705
- const dataComponentPromises = Object.entries(typed.dataComponents).map(
3706
- async ([dataComponentId, dataComponentData]) => {
3707
- try {
3708
- logger11.info({ dataComponentId }, "Processing data component");
3709
- await upsertDataComponent(db)({
3710
- data: {
3711
- id: dataComponentId,
3712
- tenantId,
3713
- projectId,
3714
- name: dataComponentData.name,
3715
- description: dataComponentData.description || "",
3716
- props: dataComponentData.props || {}
3717
- }
3718
- });
3719
- logger11.info({ dataComponentId }, "Data component processed successfully");
3720
- } catch (error) {
3721
- logger11.error({ dataComponentId, error }, "Failed to create/update dataComponent");
3722
- throw error;
3723
- }
3724
- }
3725
- );
3726
- await Promise.all(dataComponentPromises);
3727
- logger11.info(
3728
- { dataComponentCount: Object.keys(typed.dataComponents).length },
3729
- "All dataComponents created/updated successfully"
3730
- );
3731
- }
3732
- if (typed.artifactComponents && Object.keys(typed.artifactComponents).length > 0) {
3733
- const artifactComponentPromises = Object.entries(typed.artifactComponents).map(
3734
- async ([artifactComponentId, artifactComponentData]) => {
3735
- try {
3736
- logger11.info({ artifactComponentId }, "Processing artifact component");
3737
- await upsertArtifactComponent(db)({
3738
- data: {
3739
- id: artifactComponentId,
3740
- tenantId,
3741
- projectId,
3742
- name: artifactComponentData.name,
3743
- description: artifactComponentData.description || "",
3744
- summaryProps: artifactComponentData.summaryProps || {},
3745
- fullProps: artifactComponentData.fullProps || {}
3746
- }
3747
- });
3748
- logger11.info({ artifactComponentId }, "Artifact component processed successfully");
3749
- } catch (error) {
3750
- logger11.error(
3751
- { artifactComponentId, error },
3752
- "Failed to create/update artifactComponent"
3753
- );
3754
- throw error;
3755
- }
3756
- }
3757
- );
3758
- await Promise.all(artifactComponentPromises);
3759
- logger11.info(
3760
- { artifactComponentCount: Object.keys(typed.artifactComponents).length },
3761
- "All artifactComponents created/updated successfully"
3762
- );
3763
- }
3700
+ logger11.info(
3701
+ {},
3702
+ "DataComponents are project-scoped - skipping dataComponent creation in graph"
3703
+ );
3704
+ logger11.info(
3705
+ {},
3706
+ "ArtifactComponents are project-scoped - skipping artifactComponent creation in graph"
3707
+ );
3764
3708
  const internalAgentPromises = Object.entries(typed.agents).filter(([_, agentData]) => isInternalAgent(agentData)).map(async ([agentId, agentData]) => {
3765
3709
  const internalAgent = agentData;
3766
3710
  try {
@@ -3770,6 +3714,7 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
3770
3714
  id: agentId,
3771
3715
  tenantId,
3772
3716
  projectId,
3717
+ graphId: finalGraphId,
3773
3718
  name: internalAgent.name || "",
3774
3719
  description: internalAgent.description || "",
3775
3720
  prompt: internalAgent.prompt || "",
@@ -3798,6 +3743,7 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
3798
3743
  id: agentId,
3799
3744
  tenantId,
3800
3745
  projectId,
3746
+ graphId: finalGraphId,
3801
3747
  name: externalAgent.name,
3802
3748
  description: externalAgent.description || "",
3803
3749
  baseUrl: externalAgent.baseUrl,
@@ -3816,29 +3762,24 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
3816
3762
  ([_, agentData]) => isExternalAgent(agentData)
3817
3763
  ).length;
3818
3764
  logger11.info({ externalAgentCount }, "All external agents created/updated successfully");
3819
- let finalGraphId;
3820
- try {
3821
- logger11.info({ graphId: typed.id }, "Processing agent graph metadata");
3822
- const agentGraph2 = await upsertAgentGraph(db)({
3823
- data: {
3824
- id: typed.id || nanoid(),
3825
- tenantId,
3826
- projectId,
3827
- name: typed.name,
3828
- defaultAgentId: typed.defaultAgentId,
3829
- description: typed.description,
3830
- contextConfigId,
3831
- models: typed.models,
3832
- statusUpdates: typed.statusUpdates,
3833
- graphPrompt: typed.graphPrompt,
3834
- stopWhen: typed.stopWhen
3835
- }
3836
- });
3837
- finalGraphId = agentGraph2.id;
3838
- logger11.info({ graphId: finalGraphId }, "Agent graph metadata processed successfully");
3839
- } catch (error) {
3840
- logger11.error({ graphId: typed.id, error }, "Failed to create/update graph metadata");
3841
- throw error;
3765
+ if (contextConfigId) {
3766
+ try {
3767
+ logger11.info(
3768
+ { graphId: finalGraphId, contextConfigId },
3769
+ "Updating graph with context config"
3770
+ );
3771
+ await updateAgentGraph(db)({
3772
+ scopes: { tenantId, projectId, graphId: finalGraphId },
3773
+ data: { contextConfigId }
3774
+ });
3775
+ logger11.info({ graphId: finalGraphId }, "Graph updated with context config");
3776
+ } catch (error) {
3777
+ logger11.error(
3778
+ { graphId: finalGraphId, error },
3779
+ "Failed to update graph with context config"
3780
+ );
3781
+ throw error;
3782
+ }
3842
3783
  }
3843
3784
  const agentToolPromises = [];
3844
3785
  for (const [agentId, agentData] of Object.entries(typed.agents)) {
@@ -3850,7 +3791,7 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
3850
3791
  const selectedTools = agentData.selectedTools?.[toolId];
3851
3792
  logger11.info({ agentId, toolId }, "Processing agent-tool relation");
3852
3793
  await upsertAgentToolRelation(db)({
3853
- scopes: { tenantId, projectId },
3794
+ scopes: { tenantId, projectId, graphId: finalGraphId },
3854
3795
  agentId,
3855
3796
  toolId,
3856
3797
  selectedTools
@@ -3881,8 +3822,7 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
3881
3822
  "Processing agent-data component relation"
3882
3823
  );
3883
3824
  await upsertAgentDataComponentRelation(db)({
3884
- scopes: { tenantId, projectId },
3885
- agentId,
3825
+ scopes: { tenantId, projectId, graphId: finalGraphId, agentId },
3886
3826
  dataComponentId
3887
3827
  });
3888
3828
  logger11.info(
@@ -3914,8 +3854,7 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
3914
3854
  "Processing agent-artifact component relation"
3915
3855
  );
3916
3856
  await upsertAgentArtifactComponentRelation(db)({
3917
- scopes: { tenantId, projectId },
3918
- agentId,
3857
+ scopes: { tenantId, projectId, graphId: finalGraphId, agentId },
3919
3858
  artifactComponentId
3920
3859
  });
3921
3860
  logger11.info(
@@ -4011,8 +3950,7 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4011
3950
  "All agent relations created"
4012
3951
  );
4013
3952
  const createdGraph = await getFullGraphDefinition(db)({
4014
- scopes: { tenantId, projectId },
4015
- graphId: finalGraphId
3953
+ scopes: { tenantId, projectId, graphId: finalGraphId }
4016
3954
  });
4017
3955
  if (!createdGraph) {
4018
3956
  throw new Error("Failed to retrieve created graph");
@@ -4035,8 +3973,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4035
3973
  {
4036
3974
  tenantId,
4037
3975
  graphId: typedGraphDefinition.id,
4038
- agentCount: Object.keys(typedGraphDefinition.agents).length,
4039
- toolCount: Object.keys(typedGraphDefinition.tools || {}).length
3976
+ agentCount: Object.keys(typedGraphDefinition.agents).length
4040
3977
  },
4041
3978
  "Updating full graph in database"
4042
3979
  );
@@ -4049,8 +3986,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4049
3986
  );
4050
3987
  try {
4051
3988
  const existingGraph = await getAgentGraphById(db)({
4052
- scopes: { tenantId, projectId },
4053
- graphId: typedGraphDefinition.id
3989
+ scopes: { tenantId, projectId, graphId: typedGraphDefinition.id }
4054
3990
  });
4055
3991
  if (!existingGraph) {
4056
3992
  logger11.info(
@@ -4060,65 +3996,40 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4060
3996
  return createFullGraphServerSide(db)(scopes, graphData);
4061
3997
  }
4062
3998
  const existingGraphModels = existingGraph.models;
4063
- if (typedGraphDefinition.credentialReferences && Object.keys(typedGraphDefinition.credentialReferences).length > 0) {
4064
- logger11.info(
4065
- {
4066
- credentialReferencesCount: Object.keys(typedGraphDefinition.credentialReferences).length
4067
- },
4068
- "Processing credential references"
4069
- );
4070
- const credentialRefPromises = Object.entries(typedGraphDefinition.credentialReferences).map(
4071
- async ([_credId, credData]) => {
4072
- try {
4073
- logger11.info({ credId: credData.id }, "Processing credential reference");
4074
- await upsertCredentialReference(db)({
4075
- data: {
4076
- ...credData,
4077
- tenantId,
4078
- projectId
4079
- }
4080
- });
4081
- logger11.info({ credId: credData.id }, "Credential reference processed successfully");
4082
- } catch (error) {
4083
- logger11.error(
4084
- { credId: credData.id, error },
4085
- "Failed to create/update credential reference"
4086
- );
4087
- throw error;
4088
- }
3999
+ logger11.info(
4000
+ {},
4001
+ "CredentialReferences are project-scoped - skipping credential reference update in graph"
4002
+ );
4003
+ logger11.info({}, "Tools are project-scoped - skipping tool creation in graph update");
4004
+ let finalGraphId;
4005
+ try {
4006
+ const graphId = typedGraphDefinition.id || nanoid();
4007
+ logger11.info({ graphId }, "Getting/creating agent graph metadata");
4008
+ const agentGraph2 = await upsertAgentGraph(db)({
4009
+ data: {
4010
+ id: graphId,
4011
+ tenantId,
4012
+ projectId,
4013
+ name: typedGraphDefinition.name,
4014
+ defaultAgentId: typedGraphDefinition.defaultAgentId,
4015
+ description: typedGraphDefinition.description,
4016
+ contextConfigId: void 0,
4017
+ // Will be updated later if context config exists
4018
+ models: typedGraphDefinition.models,
4019
+ statusUpdates: typedGraphDefinition.statusUpdates,
4020
+ graphPrompt: typedGraphDefinition.graphPrompt,
4021
+ stopWhen: typedGraphDefinition.stopWhen
4089
4022
  }
4023
+ });
4024
+ finalGraphId = agentGraph2.id;
4025
+ logger11.info({ graphId: finalGraphId }, "Agent graph metadata ready");
4026
+ } catch (error) {
4027
+ logger11.error(
4028
+ { graphId: typedGraphDefinition.id, error },
4029
+ "Failed to get/update graph metadata"
4090
4030
  );
4091
- await Promise.all(credentialRefPromises);
4092
- logger11.info(
4093
- {
4094
- credentialReferencesCount: Object.keys(typedGraphDefinition.credentialReferences).length
4095
- },
4096
- "All credential references created/updated successfully"
4097
- );
4031
+ throw error;
4098
4032
  }
4099
- const toolPromises = Object.entries(typedGraphDefinition.tools || {}).map(
4100
- async ([toolId, toolData]) => {
4101
- try {
4102
- logger11.info({ toolId }, "Processing tool");
4103
- await upsertTool(db)({
4104
- data: {
4105
- tenantId,
4106
- projectId,
4107
- ...toolData
4108
- }
4109
- });
4110
- logger11.info({ toolId }, "Tool processed successfully");
4111
- } catch (error) {
4112
- logger11.error({ toolId, error }, "Failed to create/update tool");
4113
- throw error;
4114
- }
4115
- }
4116
- );
4117
- await Promise.all(toolPromises);
4118
- logger11.info(
4119
- { toolCount: Object.keys(typedGraphDefinition.tools || {}).length },
4120
- "All tools created/updated successfully"
4121
- );
4122
4033
  let contextConfigId;
4123
4034
  if (typedGraphDefinition.contextConfig) {
4124
4035
  try {
@@ -4143,66 +4054,11 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4143
4054
  throw error;
4144
4055
  }
4145
4056
  }
4146
- if (typedGraphDefinition.dataComponents && Object.keys(typedGraphDefinition.dataComponents).length > 0) {
4147
- const dataComponentPromises = Object.entries(typedGraphDefinition.dataComponents).map(
4148
- async ([dataComponentId, dataComponentData]) => {
4149
- try {
4150
- logger11.info({ dataComponentId }, "Processing data component");
4151
- await upsertDataComponent(db)({
4152
- data: {
4153
- id: dataComponentId,
4154
- tenantId,
4155
- projectId,
4156
- name: dataComponentData.name,
4157
- description: dataComponentData.description || "",
4158
- props: dataComponentData.props || {}
4159
- }
4160
- });
4161
- logger11.info({ dataComponentId }, "Data component processed successfully");
4162
- } catch (error) {
4163
- logger11.error({ dataComponentId, error }, "Failed to create/update dataComponent");
4164
- throw error;
4165
- }
4166
- }
4167
- );
4168
- await Promise.all(dataComponentPromises);
4169
- logger11.info(
4170
- { dataComponentCount: Object.keys(typedGraphDefinition.dataComponents).length },
4171
- "All dataComponents created/updated successfully"
4172
- );
4173
- }
4174
- if (typedGraphDefinition.artifactComponents && Object.keys(typedGraphDefinition.artifactComponents).length > 0) {
4175
- const artifactComponentPromises = Object.entries(
4176
- typedGraphDefinition.artifactComponents
4177
- ).map(async ([artifactComponentId, artifactComponentData]) => {
4178
- try {
4179
- logger11.info({ artifactComponentId }, "Processing artifact component");
4180
- await upsertArtifactComponent(db)({
4181
- data: {
4182
- id: artifactComponentId,
4183
- tenantId,
4184
- projectId,
4185
- name: artifactComponentData.name,
4186
- description: artifactComponentData.description || "",
4187
- summaryProps: artifactComponentData.summaryProps || {},
4188
- fullProps: artifactComponentData.fullProps || {}
4189
- }
4190
- });
4191
- logger11.info({ artifactComponentId }, "Artifact component processed successfully");
4192
- } catch (error) {
4193
- logger11.error(
4194
- { artifactComponentId, error },
4195
- "Failed to create/update artifactComponent"
4196
- );
4197
- throw error;
4198
- }
4199
- });
4200
- await Promise.all(artifactComponentPromises);
4201
- logger11.info(
4202
- { artifactComponentCount: Object.keys(typedGraphDefinition.artifactComponents).length },
4203
- "All artifactComponents created/updated successfully"
4204
- );
4205
- }
4057
+ logger11.info({}, "DataComponents are project-scoped - skipping dataComponent update in graph");
4058
+ logger11.info(
4059
+ {},
4060
+ "ArtifactComponents are project-scoped - skipping artifactComponent update in graph"
4061
+ );
4206
4062
  const internalAgentPromises = Object.entries(typedGraphDefinition.agents).filter(([_, agentData]) => isInternalAgent(agentData)).map(async ([agentId, agentData]) => {
4207
4063
  const internalAgent = agentData;
4208
4064
  let existingAgent = null;
@@ -4251,6 +4107,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4251
4107
  id: agentId,
4252
4108
  tenantId,
4253
4109
  projectId,
4110
+ graphId: finalGraphId,
4254
4111
  name: internalAgent.name || "",
4255
4112
  description: internalAgent.description || "",
4256
4113
  prompt: internalAgent.prompt || "",
@@ -4279,6 +4136,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4279
4136
  id: agentId,
4280
4137
  tenantId,
4281
4138
  projectId,
4139
+ graphId: finalGraphId,
4282
4140
  name: externalAgent.name,
4283
4141
  description: externalAgent.description || "",
4284
4142
  baseUrl: externalAgent.baseUrl,
@@ -4298,8 +4156,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4298
4156
  ).length;
4299
4157
  logger11.info({ externalAgentCount }, "All external agents created/updated successfully");
4300
4158
  await updateAgentGraph(db)({
4301
- scopes: { tenantId, projectId },
4302
- graphId: typedGraphDefinition.id,
4159
+ scopes: { tenantId, projectId, graphId: typedGraphDefinition.id },
4303
4160
  data: {
4304
4161
  name: typedGraphDefinition.name,
4305
4162
  defaultAgentId: typedGraphDefinition.defaultAgentId,
@@ -4314,8 +4171,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4314
4171
  logger11.info({ graphId: typedGraphDefinition.id }, "Graph metadata updated");
4315
4172
  for (const agentId of Object.keys(typedGraphDefinition.agents)) {
4316
4173
  await deleteAgentToolRelationByAgent(db)({
4317
- scopes: { tenantId, projectId },
4318
- agentId
4174
+ scopes: { tenantId, projectId, graphId: finalGraphId, agentId }
4319
4175
  });
4320
4176
  }
4321
4177
  const agentToolPromises = [];
@@ -4327,7 +4183,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4327
4183
  try {
4328
4184
  const selectedTools = agentData.selectedTools?.[toolId];
4329
4185
  await createAgentToolRelation(db)({
4330
- scopes: { tenantId, projectId },
4186
+ scopes: { tenantId, projectId, graphId: finalGraphId },
4331
4187
  data: {
4332
4188
  agentId,
4333
4189
  toolId,
@@ -4350,8 +4206,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4350
4206
  );
4351
4207
  for (const agentId of Object.keys(typedGraphDefinition.agents)) {
4352
4208
  await deleteAgentDataComponentRelationByAgent(db)({
4353
- scopes: { tenantId, projectId },
4354
- agentId
4209
+ scopes: { tenantId, projectId, graphId: finalGraphId, agentId }
4355
4210
  });
4356
4211
  }
4357
4212
  const agentDataComponentPromises = [];
@@ -4362,8 +4217,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4362
4217
  (async () => {
4363
4218
  try {
4364
4219
  await associateDataComponentWithAgent(db)({
4365
- scopes: { tenantId, projectId },
4366
- agentId,
4220
+ scopes: { tenantId, projectId, graphId: finalGraphId, agentId },
4367
4221
  dataComponentId
4368
4222
  });
4369
4223
  logger11.info({ agentId, dataComponentId }, "Agent-dataComponent relation created");
@@ -4385,8 +4239,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4385
4239
  );
4386
4240
  for (const agentId of Object.keys(typedGraphDefinition.agents)) {
4387
4241
  await deleteAgentArtifactComponentRelationByAgent(db)({
4388
- scopes: { tenantId, projectId },
4389
- agentId
4242
+ scopes: { tenantId, projectId, graphId: finalGraphId, agentId }
4390
4243
  });
4391
4244
  }
4392
4245
  const agentArtifactComponentPromises = [];
@@ -4397,8 +4250,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4397
4250
  (async () => {
4398
4251
  try {
4399
4252
  await associateArtifactComponentWithAgent(db)({
4400
- scopes: { tenantId, projectId },
4401
- agentId,
4253
+ scopes: { tenantId, projectId, graphId: finalGraphId, agentId },
4402
4254
  artifactComponentId
4403
4255
  });
4404
4256
  logger11.info(
@@ -4422,8 +4274,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4422
4274
  "All agent-artifactComponent relations updated"
4423
4275
  );
4424
4276
  await deleteAgentRelationsByGraph(db)({
4425
- scopes: { tenantId, projectId },
4426
- graphId: typedGraphDefinition.id
4277
+ scopes: { tenantId, projectId, graphId: typedGraphDefinition.id }
4427
4278
  });
4428
4279
  const agentRelationPromises = [];
4429
4280
  for (const [agentId, agentData] of Object.entries(typedGraphDefinition.agents)) {
@@ -4499,8 +4350,7 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4499
4350
  "All agent relations updated"
4500
4351
  );
4501
4352
  const updatedGraph = await getFullGraphDefinition(db)({
4502
- scopes: { tenantId, projectId },
4503
- graphId: typedGraphDefinition.id
4353
+ scopes: { tenantId, projectId, graphId: typedGraphDefinition.id }
4504
4354
  });
4505
4355
  if (!updatedGraph) {
4506
4356
  throw new Error("Failed to retrieve updated graph");
@@ -4513,22 +4363,21 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
4513
4363
  }
4514
4364
  };
4515
4365
  var getFullGraph = (db, logger11 = defaultLogger) => async (params) => {
4516
- const { scopes, graphId } = params;
4366
+ const { scopes } = params;
4517
4367
  const { tenantId, projectId } = scopes;
4518
- logger11.info({ tenantId, graphId }, "Retrieving full graph definition");
4368
+ logger11.info({ tenantId, graphId: scopes.graphId }, "Retrieving full graph definition");
4519
4369
  try {
4520
4370
  const graph = await getFullGraphDefinition(db)({
4521
- scopes: { tenantId, projectId },
4522
- graphId
4371
+ scopes: { tenantId, projectId, graphId: scopes.graphId }
4523
4372
  });
4524
4373
  if (!graph) {
4525
- logger11.info({ tenantId, graphId }, "Graph not found");
4374
+ logger11.info({ tenantId, graphId: scopes.graphId }, "Graph not found");
4526
4375
  return null;
4527
4376
  }
4528
4377
  logger11.info(
4529
4378
  {
4530
4379
  tenantId,
4531
- graphId,
4380
+ graphId: scopes.graphId,
4532
4381
  agentCount: Object.keys(graph.agents).length
4533
4382
  },
4534
4383
  "Full graph retrieved successfully"
@@ -4538,7 +4387,7 @@ var getFullGraph = (db, logger11 = defaultLogger) => async (params) => {
4538
4387
  logger11.error(
4539
4388
  {
4540
4389
  tenantId,
4541
- graphId,
4390
+ graphId: scopes.graphId,
4542
4391
  error: error instanceof Error ? error.message : "Unknown error"
4543
4392
  },
4544
4393
  "Failed to retrieve full graph"
@@ -4547,29 +4396,25 @@ var getFullGraph = (db, logger11 = defaultLogger) => async (params) => {
4547
4396
  }
4548
4397
  };
4549
4398
  var deleteFullGraph = (db, logger11 = defaultLogger) => async (params) => {
4550
- const { scopes, graphId } = params;
4551
- const { tenantId, projectId } = scopes;
4399
+ const { tenantId, projectId, graphId } = params.scopes;
4552
4400
  logger11.info({ tenantId, graphId }, "Deleting full graph and related entities");
4553
4401
  try {
4554
4402
  const graph = await getFullGraphDefinition(db)({
4555
- scopes: { tenantId, projectId },
4556
- graphId
4403
+ scopes: { tenantId, projectId, graphId }
4557
4404
  });
4558
4405
  if (!graph) {
4559
4406
  logger11.info({ tenantId, graphId }, "Graph not found for deletion");
4560
4407
  return false;
4561
4408
  }
4562
4409
  await deleteAgentRelationsByGraph(db)({
4563
- scopes: { tenantId, projectId },
4564
- graphId
4410
+ scopes: { tenantId, projectId, graphId }
4565
4411
  });
4566
4412
  logger11.info({ tenantId, graphId }, "Agent relations deleted");
4567
4413
  const agentIds = Object.keys(graph.agents);
4568
4414
  if (agentIds.length > 0) {
4569
4415
  for (const agentId of agentIds) {
4570
4416
  await deleteAgentToolRelationByAgent(db)({
4571
- scopes: { tenantId, projectId },
4572
- agentId
4417
+ scopes: { tenantId, projectId, graphId, agentId }
4573
4418
  });
4574
4419
  }
4575
4420
  logger11.info(
@@ -4578,8 +4423,7 @@ var deleteFullGraph = (db, logger11 = defaultLogger) => async (params) => {
4578
4423
  );
4579
4424
  }
4580
4425
  await deleteAgentGraph(db)({
4581
- scopes: { tenantId, projectId },
4582
- graphId
4426
+ scopes: { tenantId, projectId, graphId }
4583
4427
  });
4584
4428
  logger11.info({ tenantId, graphId }, "Graph metadata deleted");
4585
4429
  logger11.info({ tenantId, graphId }, "Full graph deleted successfully");
@@ -5288,8 +5132,7 @@ var createFullProjectServerSide = (db, logger11 = defaultLogger2) => async (scop
5288
5132
  db,
5289
5133
  logger11
5290
5134
  )({
5291
- scopes: { tenantId, projectId: typed.id },
5292
- projectId: typed.id
5135
+ scopes: { tenantId, projectId: typed.id }
5293
5136
  });
5294
5137
  } catch (error) {
5295
5138
  logger11.error(
@@ -5595,8 +5438,7 @@ var updateFullProjectServerSide = (db, logger11 = defaultLogger2) => async (scop
5595
5438
  db,
5596
5439
  logger11
5597
5440
  )({
5598
- scopes: { tenantId, projectId: typed.id },
5599
- projectId: typed.id
5441
+ scopes: { tenantId, projectId: typed.id }
5600
5442
  });
5601
5443
  } catch (error) {
5602
5444
  logger11.error(
@@ -5611,8 +5453,8 @@ var updateFullProjectServerSide = (db, logger11 = defaultLogger2) => async (scop
5611
5453
  }
5612
5454
  };
5613
5455
  var getFullProject = (db, logger11 = defaultLogger2) => async (params) => {
5614
- const { scopes, projectId } = params;
5615
- const { tenantId } = scopes;
5456
+ const { scopes } = params;
5457
+ const { tenantId, projectId } = scopes;
5616
5458
  logger11.info({ tenantId, projectId }, "Retrieving full project definition");
5617
5459
  try {
5618
5460
  const project = await getProject(db)({
@@ -5766,18 +5608,10 @@ var getFullProject = (db, logger11 = defaultLogger2) => async (params) => {
5766
5608
  "Retrieving full graph definition"
5767
5609
  );
5768
5610
  const fullGraph = await getFullGraph(db)({
5769
- scopes: { tenantId, projectId },
5770
- graphId: graph.id
5611
+ scopes: { tenantId, projectId, graphId: graph.id }
5771
5612
  });
5772
5613
  if (fullGraph) {
5773
- const {
5774
- tools: _tools,
5775
- dataComponents: _dataComponents,
5776
- artifactComponents: _artifactComponents,
5777
- contextConfig: _contextConfig,
5778
- credentialReferences: _credentialReferences,
5779
- ...graphWithoutProjectResources
5780
- } = fullGraph;
5614
+ const { contextConfig: _contextConfig, ...graphWithoutProjectResources } = fullGraph;
5781
5615
  graphs[graph.id] = graphWithoutProjectResources;
5782
5616
  logger11.info(
5783
5617
  { tenantId, projectId, graphId: graph.id },
@@ -5832,16 +5666,15 @@ var getFullProject = (db, logger11 = defaultLogger2) => async (params) => {
5832
5666
  }
5833
5667
  };
5834
5668
  var deleteFullProject = (db, logger11 = defaultLogger2) => async (params) => {
5835
- const { scopes, projectId } = params;
5836
- const { tenantId } = scopes;
5669
+ const { scopes } = params;
5670
+ const { tenantId, projectId } = scopes;
5837
5671
  logger11.info({ tenantId, projectId }, "Deleting full project and related entities");
5838
5672
  try {
5839
5673
  const project = await getFullProject(
5840
5674
  db,
5841
5675
  logger11
5842
5676
  )({
5843
- scopes: { tenantId, projectId },
5844
- projectId
5677
+ scopes: { tenantId, projectId }
5845
5678
  });
5846
5679
  if (!project) {
5847
5680
  logger11.info({ tenantId, projectId }, "Project not found for deletion");
@@ -5863,8 +5696,7 @@ var deleteFullProject = (db, logger11 = defaultLogger2) => async (params) => {
5863
5696
  db,
5864
5697
  logger11
5865
5698
  )({
5866
- scopes: { tenantId, projectId },
5867
- graphId
5699
+ scopes: { tenantId, projectId, graphId }
5868
5700
  });
5869
5701
  logger11.info(
5870
5702
  { tenantId, projectId, graphId },
@@ -7279,8 +7111,7 @@ async function validateRequestContext({
7279
7111
  }) {
7280
7112
  try {
7281
7113
  const agentGraph2 = await getAgentGraphWithDefaultAgent(dbClient)({
7282
- scopes: { tenantId, projectId },
7283
- graphId
7114
+ scopes: { tenantId, projectId, graphId }
7284
7115
  });
7285
7116
  if (!agentGraph2?.contextConfigId) {
7286
7117
  logger7.debug({ graphId }, "No context config found for graph, skipping validation");
@@ -7420,13 +7251,11 @@ function contextValidationMiddleware(dbClient) {
7420
7251
  },
7421
7252
  "Request context validation failed"
7422
7253
  );
7423
- return c.json(
7424
- {
7425
- error: "Invalid request context",
7426
- details: validationResult.errors
7427
- },
7428
- 400
7429
- );
7254
+ const errorMessage = `Invalid request context: ${validationResult.errors.map((e) => `${e.field}: ${e.message}`).join(", ")}`;
7255
+ throw createApiError({
7256
+ code: "bad_request",
7257
+ message: errorMessage
7258
+ });
7430
7259
  }
7431
7260
  c.set("validatedContext", validationResult.validatedContext);
7432
7261
  logger7.debug(
@@ -7445,13 +7274,10 @@ function contextValidationMiddleware(dbClient) {
7445
7274
  },
7446
7275
  "Context validation middleware error"
7447
7276
  );
7448
- return c.json(
7449
- {
7450
- error: "Context validation failed",
7451
- message: "Internal validation error"
7452
- },
7453
- 500
7454
- );
7277
+ throw createApiError({
7278
+ code: "internal_server_error",
7279
+ message: "Context validation failed"
7280
+ });
7455
7281
  }
7456
7282
  };
7457
7283
  }
@@ -7827,7 +7653,15 @@ async function handleContextConfigChange(tenantId, projectId, conversationId, gr
7827
7653
  );
7828
7654
  }
7829
7655
  }
7830
- async function handleContextResolution(tenantId, projectId, conversationId, graphId, requestContext, dbClient, credentialStores) {
7656
+ async function handleContextResolution({
7657
+ tenantId,
7658
+ projectId,
7659
+ graphId,
7660
+ conversationId,
7661
+ requestContext,
7662
+ dbClient,
7663
+ credentialStores
7664
+ }) {
7831
7665
  return tracer.startActiveSpan(
7832
7666
  "context.handle_context_resolution",
7833
7667
  {
@@ -7840,8 +7674,7 @@ async function handleContextResolution(tenantId, projectId, conversationId, grap
7840
7674
  let trigger;
7841
7675
  try {
7842
7676
  agentGraph2 = await getAgentGraphWithDefaultAgent(dbClient)({
7843
- scopes: { tenantId, projectId },
7844
- graphId
7677
+ scopes: { tenantId, projectId, graphId }
7845
7678
  });
7846
7679
  if (!agentGraph2?.contextConfigId) {
7847
7680
  logger9.debug({ graphId }, "No context config found for graph");
@@ -8550,5 +8383,52 @@ function createDefaultCredentialStores() {
8550
8383
  stores.push(createKeyChainStore("keychain-default"));
8551
8384
  return stores;
8552
8385
  }
8386
+ var loadEnvironmentFiles = () => {
8387
+ const environmentFiles = [];
8388
+ const currentEnv = path.resolve(process.cwd(), ".env");
8389
+ if (fs.existsSync(currentEnv)) {
8390
+ environmentFiles.push(currentEnv);
8391
+ }
8392
+ const rootEnv = findUpSync(".env", { cwd: path.dirname(process.cwd()) });
8393
+ if (rootEnv) {
8394
+ if (rootEnv !== currentEnv) {
8395
+ environmentFiles.push(rootEnv);
8396
+ }
8397
+ }
8398
+ const userConfigPath = path.join(os.homedir(), ".inkeep", "config");
8399
+ if (fs.existsSync(userConfigPath)) {
8400
+ dotenv.config({ path: userConfigPath, override: true, quiet: true });
8401
+ }
8402
+ if (environmentFiles.length > 0) {
8403
+ dotenv.config({
8404
+ path: environmentFiles,
8405
+ override: false,
8406
+ quiet: true
8407
+ });
8408
+ expand({ processEnv: process.env });
8409
+ }
8410
+ };
8411
+ loadEnvironmentFiles();
8412
+ var envSchema = z$1.object({
8413
+ ENVIRONMENT: z$1.enum(["development", "production", "pentest", "test"]).optional(),
8414
+ DB_FILE_NAME: z$1.string(),
8415
+ OTEL_TRACES_FORCE_FLUSH_ENABLED: z$1.coerce.boolean().optional()
8416
+ });
8417
+ var parseEnv = () => {
8418
+ try {
8419
+ const parsedEnv = envSchema.parse(process.env);
8420
+ return parsedEnv;
8421
+ } catch (error) {
8422
+ if (error instanceof z$1.ZodError) {
8423
+ const missingVars = error.issues.map((issue) => issue.path.join("."));
8424
+ throw new Error(
8425
+ `\u274C Invalid environment variables: ${missingVars.join(", ")}
8426
+ ${error.message}`
8427
+ );
8428
+ }
8429
+ throw error;
8430
+ }
8431
+ };
8432
+ parseEnv();
8553
8433
 
8554
- export { ConsoleLogger, ContextCache, ContextConfigBuilder, ContextFetcher, ContextResolver, CredentialStoreRegistry, CredentialStuffer, ERROR_DOCS_BASE_URL, ErrorCode, HTTP_REQUEST_PARTS, InMemoryCredentialStore, KeyChainStore, McpClient, NangoCredentialStore, NoOpLogger, TemplateEngine, addLedgerArtifacts, addToolToAgent, associateArtifactComponentWithAgent, associateDataComponentWithAgent, cleanupTenantCache, clearContextConfigCache, clearConversationCache, commonCreateErrorResponses, commonDeleteErrorResponses, commonGetErrorResponses, commonUpdateErrorResponses, configureLogging, contextConfig, contextValidationMiddleware, countApiKeys, countArtifactComponents, countArtifactComponentsForAgent, countContextConfigs, countCredentialReferences, countDataComponents, countExternalAgents, countLedgerArtifactsByTask, countMessagesByConversation, countProjects, createAgent, createAgentGraph, createAgentRelation, createAgentToolRelation, createApiError, createApiKey, createArtifactComponent, createContextConfig, createConversation, createCredentialReference, createDataComponent, createDatabaseClient, createDefaultCredentialStores, createExecutionContext, createExternalAgent, createExternalAgentRelation, createFullGraphServerSide, createFullProjectServerSide, createInMemoryDatabaseClient, createKeyChainStore, createMessage, createNangoCredentialStore, createOrGetConversation, createProject, createTask, createTool, createValidatedDataAccess, dbResultToMcpTool, deleteAgent, deleteAgentArtifactComponentRelationByAgent, deleteAgentDataComponentRelationByAgent, deleteAgentGraph, deleteAgentRelation, deleteAgentRelationsByGraph, deleteAgentToolRelation, deleteAgentToolRelationByAgent, deleteApiKey, deleteArtifactComponent, deleteContextConfig, deleteConversation, deleteCredentialReference, deleteDataComponent, deleteExternalAgent, deleteFullGraph, deleteFullProject, deleteLedgerArtifactsByContext, deleteLedgerArtifactsByTask, deleteMessage, deleteProject, deleteTool, detectAuthenticationRequired, determineContextTrigger, discoverOAuthEndpoints, errorResponseSchema, errorSchemaFactory, externalAgentExists, externalAgentUrlExists, extractPublicId, fetchComponentRelationships, fetchDefinition, generateAndCreateApiKey, generateApiKey, getActiveAgentForConversation, getAgentById, getAgentGraph, getAgentGraphById, getAgentGraphWithDefaultAgent, getAgentInGraphContext, getAgentRelationById, getAgentRelationByParams, getAgentRelations, getAgentRelationsByGraph, getAgentRelationsBySource, getAgentRelationsByTarget, getAgentToolRelationByAgent, getAgentToolRelationById, getAgentToolRelationByTool, getAgentsByIds, getAgentsForTool, getAgentsUsingArtifactComponent, getAgentsUsingDataComponent, getApiKeyById, getApiKeyByPublicId, getArtifactComponentById, getArtifactComponentsForAgent, getCacheEntry, getCachedValidator, getContextConfigById, getContextConfigCacheEntries, getContextConfigsByName, getConversation, getConversationCacheEntries, getConversationHistory, getCredentialReference, getCredentialReferenceById, getCredentialReferenceWithTools, getCredentialStoreLookupKeyFromRetrievalParams, getDataComponent, getDataComponentsForAgent, getExternalAgent, getExternalAgentByUrl, getExternalAgentRelations, getFullGraph, getFullGraphDefinition, getFullProject, getGraphAgentInfos, getHealthyToolsForAgent, getLedgerArtifacts, getLedgerArtifactsByContext, getLogger, getMessageById, getMessagesByConversation, getMessagesByTask, getProject, getProjectResourceCounts, getRelatedAgentsForGraph, getRequestExecutionContext, getTask, getToolById, getToolsByStatus, getToolsForAgent, getTracer, getVisibleMessages, graphHasArtifactComponents, handleApiError, handleContextConfigChange, handleContextResolution, hasApiKey, hasContextConfig, hasCredentialReference, hashApiKey, invalidateInvocationDefinitionsCache, invalidateRequestContextCache, isApiKeyExpired, isArtifactComponentAssociatedWithAgent, isDataComponentAssociatedWithAgent, isValidHttpRequest, listAgentGraphs, listAgentGraphsPaginated, listAgentRelations, listAgentToolRelations, listAgentToolRelationsByAgent, listAgents, listAgentsPaginated, listApiKeys, listApiKeysPaginated, listArtifactComponents, listArtifactComponentsPaginated, listContextConfigs, listContextConfigsPaginated, listConversations, listCredentialReferences, listCredentialReferencesPaginated, listDataComponents, listDataComponentsPaginated, listExternalAgents, listExternalAgentsPaginated, listMessages, listProjects, listProjectsPaginated, listTaskIdsByContextId, listTools, listToolsByStatus, loggerFactory, maskApiKey, problemDetailsSchema, projectExists, projectExistsInTable, projectHasResources, removeArtifactComponentFromAgent, removeDataComponentFromAgent, removeToolFromAgent, setActiveAgentForConversation, setActiveAgentForThread, setCacheEntry, setSpanWithError, updateAgent, updateAgentGraph, updateAgentRelation, updateAgentToolRelation, updateApiKey, updateApiKeyLastUsed, updateArtifactComponent, updateContextConfig, updateConversation, updateConversationActiveAgent, updateCredentialReference, updateDataComponent, updateExternalAgent, updateFullGraphServerSide, updateFullProjectServerSide, updateMessage, updateProject, updateTask, updateTool, updateToolStatus, upsertAgent, upsertAgentArtifactComponentRelation, upsertAgentDataComponentRelation, upsertAgentGraph, upsertAgentRelation, upsertAgentToolRelation, upsertArtifactComponent, upsertContextConfig, upsertCredentialReference, upsertDataComponent, upsertExternalAgent, upsertTool, validateAgainstJsonSchema, validateAndGetApiKey, validateApiKey, validateExternalAgent, validateHttpRequestHeaders, validateInternalAgent, validateProjectExists, validateRequestContext, validationHelper, withProjectValidation };
8434
+ export { ConsoleLogger, ContextCache, ContextConfigBuilder, ContextFetcher, ContextResolver, CredentialStoreRegistry, CredentialStuffer, ERROR_DOCS_BASE_URL, ErrorCode, HTTP_REQUEST_PARTS, InMemoryCredentialStore, KeyChainStore, McpClient, NangoCredentialStore, NoOpLogger, TemplateEngine, addLedgerArtifacts, addToolToAgent, associateArtifactComponentWithAgent, associateDataComponentWithAgent, cleanupTenantCache, clearContextConfigCache, clearConversationCache, commonCreateErrorResponses, commonDeleteErrorResponses, commonGetErrorResponses, commonUpdateErrorResponses, configureLogging, contextConfig, contextValidationMiddleware, countApiKeys, countArtifactComponents, countArtifactComponentsForAgent, countContextConfigs, countCredentialReferences, countDataComponents, countExternalAgents, countLedgerArtifactsByTask, countMessagesByConversation, countProjects, createAgent, createAgentGraph, createAgentRelation, createAgentToolRelation, createApiError, createApiKey, createArtifactComponent, createContextConfig, createConversation, createCredentialReference, createDataComponent, createDatabaseClient, createDefaultCredentialStores, createExecutionContext, createExternalAgent, createExternalAgentRelation, createFullGraphServerSide, createFullProjectServerSide, createInMemoryDatabaseClient, createKeyChainStore, createMessage, createNangoCredentialStore, createOrGetConversation, createProject, createTask, createTool, createValidatedDataAccess, dbResultToMcpTool, deleteAgent, deleteAgentArtifactComponentRelationByAgent, deleteAgentDataComponentRelationByAgent, deleteAgentGraph, deleteAgentRelation, deleteAgentRelationsByGraph, deleteAgentToolRelation, deleteAgentToolRelationByAgent, deleteApiKey, deleteArtifactComponent, deleteContextConfig, deleteConversation, deleteCredentialReference, deleteDataComponent, deleteExternalAgent, deleteFullGraph, deleteFullProject, deleteLedgerArtifactsByContext, deleteLedgerArtifactsByTask, deleteMessage, deleteProject, deleteTool, detectAuthenticationRequired, determineContextTrigger, discoverOAuthEndpoints, errorResponseSchema, errorSchemaFactory, externalAgentExists, externalAgentUrlExists, extractPublicId, fetchComponentRelationships, fetchDefinition, generateAndCreateApiKey, generateApiKey, getActiveAgentForConversation, getAgentById, getAgentGraphById, getAgentGraphWithDefaultAgent, getAgentRelationById, getAgentRelationByParams, getAgentRelations, getAgentRelationsByGraph, getAgentRelationsBySource, getAgentRelationsByTarget, getAgentToolRelationByAgent, getAgentToolRelationById, getAgentToolRelationByTool, getAgentsByIds, getAgentsForTool, getAgentsUsingArtifactComponent, getAgentsUsingDataComponent, getApiKeyById, getApiKeyByPublicId, getArtifactComponentById, getArtifactComponentsForAgent, getCacheEntry, getCachedValidator, getContextConfigById, getContextConfigCacheEntries, getContextConfigsByName, getConversation, getConversationCacheEntries, getConversationHistory, getCredentialReference, getCredentialReferenceById, getCredentialReferenceWithTools, getCredentialStoreLookupKeyFromRetrievalParams, getDataComponent, getDataComponentsForAgent, getExternalAgent, getExternalAgentByUrl, getExternalAgentRelations, getFullGraph, getFullGraphDefinition, getFullProject, getGraphAgentInfos, getHealthyToolsForAgent, getLedgerArtifacts, getLedgerArtifactsByContext, getLogger, getMessageById, getMessagesByConversation, getMessagesByTask, getProject, getProjectResourceCounts, getRelatedAgentsForGraph, getRequestExecutionContext, getTask, getToolById, getToolsByStatus, getToolsForAgent, getTracer, getVisibleMessages, graphHasArtifactComponents, handleApiError, handleContextConfigChange, handleContextResolution, hasApiKey, hasContextConfig, hasCredentialReference, hashApiKey, invalidateInvocationDefinitionsCache, invalidateRequestContextCache, isApiKeyExpired, isArtifactComponentAssociatedWithAgent, isDataComponentAssociatedWithAgent, isValidHttpRequest, listAgentGraphs, listAgentGraphsPaginated, listAgentRelations, listAgentToolRelations, listAgents, listAgentsPaginated, listApiKeys, listApiKeysPaginated, listArtifactComponents, listArtifactComponentsPaginated, listContextConfigs, listContextConfigsPaginated, listConversations, listCredentialReferences, listCredentialReferencesPaginated, listDataComponents, listDataComponentsPaginated, listExternalAgents, listExternalAgentsPaginated, listMessages, listProjects, listProjectsPaginated, listTaskIdsByContextId, listTools, listToolsByStatus, loadEnvironmentFiles, loggerFactory, maskApiKey, problemDetailsSchema, projectExists, projectExistsInTable, projectHasResources, removeArtifactComponentFromAgent, removeDataComponentFromAgent, removeToolFromAgent, setActiveAgentForConversation, setActiveAgentForThread, setCacheEntry, setSpanWithError, updateAgent, updateAgentGraph, updateAgentRelation, updateAgentToolRelation, updateApiKey, updateApiKeyLastUsed, updateArtifactComponent, updateContextConfig, updateConversation, updateConversationActiveAgent, updateCredentialReference, updateDataComponent, updateExternalAgent, updateFullGraphServerSide, updateFullProjectServerSide, updateMessage, updateProject, updateTask, updateTool, updateToolStatus, upsertAgent, upsertAgentArtifactComponentRelation, upsertAgentDataComponentRelation, upsertAgentGraph, upsertAgentRelation, upsertAgentToolRelation, upsertArtifactComponent, upsertContextConfig, upsertCredentialReference, upsertDataComponent, upsertExternalAgent, upsertTool, validateAgainstJsonSchema, validateAndGetApiKey, validateApiKey, validateExternalAgent, validateHttpRequestHeaders, validateInternalAgent, validateProjectExists, validateRequestContext, validationHelper, withProjectValidation };