@inkeep/agents-core 0.37.2 → 0.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/auth/auth-validation-schemas.js +1 -1
  2. package/dist/auth/auth.d.ts +4 -3
  3. package/dist/auth/auth.js +2 -2
  4. package/dist/{auth-detection-7G0Dxt55.d.ts → auth-detection-B8jOnR88.d.ts} +3 -0
  5. package/dist/chunk-3OPS2LN5.js +4 -0
  6. package/dist/{chunk-7CLFCY6J.js → chunk-7IQFIW44.js} +2 -0
  7. package/dist/{chunk-BJLC7EI4.js → chunk-AJCP2QYU.js} +1 -1
  8. package/dist/{chunk-6CYQZ5KX.js → chunk-AUGHKZEB.js} +41 -1
  9. package/dist/{chunk-5QZSNATS.js → chunk-CWAFZVRI.js} +1 -1
  10. package/dist/{chunk-ZSYMSL55.js → chunk-DW4DNYUS.js} +1 -1
  11. package/dist/{chunk-4JZT4QEE.js → chunk-KVVL5WLM.js} +1 -1
  12. package/dist/{chunk-DEYPSEXR.js → chunk-LH6OJIIM.js} +26 -11
  13. package/dist/{chunk-MQMMFK2K.js → chunk-NLLGMFQ6.js} +4 -1
  14. package/dist/{chunk-YSFXXC6K.js → chunk-S4XQEAAF.js} +7 -4
  15. package/dist/{chunk-XHODTX4H.js → chunk-UK63CULA.js} +7 -14
  16. package/dist/{chunk-3HACEHXF.js → chunk-VXHL7CJY.js} +73 -59
  17. package/dist/{client-B3nwdklT.d.ts → client-DG_xZdlN.d.ts} +1 -1
  18. package/dist/client-exports.d.ts +16 -9
  19. package/dist/client-exports.js +11 -5
  20. package/dist/constants/models.d.ts +2 -0
  21. package/dist/constants/models.js +1 -1
  22. package/dist/constants/schema-validation/index.js +1 -1
  23. package/dist/credential-stores/index.d.ts +5 -4
  24. package/dist/credential-stores/index.js +1 -1
  25. package/dist/db/schema.d.ts +2 -2
  26. package/dist/db/schema.js +1 -1
  27. package/dist/db/test-client.d.ts +3 -3
  28. package/dist/db/test-client.js +1 -1
  29. package/dist/index.d.ts +376 -335
  30. package/dist/index.js +223 -122
  31. package/dist/{schema-BhYTubhP.d.ts → schema-DA6PfmoP.d.ts} +83 -7
  32. package/dist/{server-CHLmv-Jb.d.ts → server-BviIeoo5.d.ts} +1 -1
  33. package/dist/types/index.d.ts +2 -2
  34. package/dist/{utility-5USfJ5Xd.d.ts → utility-dsfXkYTu.d.ts} +1040 -387
  35. package/dist/utils/schema-conversion.d.ts +11 -1
  36. package/dist/utils/schema-conversion.js +1 -1
  37. package/dist/validation/index.d.ts +2 -2
  38. package/dist/validation/index.js +2 -2
  39. package/drizzle/0004_cuddly_shooting_star.sql +6 -0
  40. package/drizzle/0005_reflective_starfox.sql +9 -0
  41. package/drizzle/meta/{0002_snapshot.json → 0005_snapshot.json} +70 -14
  42. package/drizzle/meta/_journal.json +14 -0
  43. package/package.json +9 -9
  44. package/dist/{chunk-RUTYLJB7.js → chunk-ZIXAWYZI.js} +1 -1
@@ -1,6 +1,6 @@
1
1
  import { user, session, account, organization, member, invitation, verification } from '../chunk-GENLXHZ4.js';
2
- import { createSelectSchema, createInsertSchema } from 'drizzle-zod';
3
2
  import { z } from '@hono/zod-openapi';
3
+ import { createSelectSchema, createInsertSchema } from 'drizzle-zod';
4
4
 
5
5
  var UserSelectSchema = createSelectSchema(user);
6
6
  var UserInsertSchema = createInsertSchema(user);
@@ -4,13 +4,13 @@ import * as zod from 'zod';
4
4
  import * as better_auth from 'better-auth';
5
5
  import { BetterAuthAdvancedOptions } from 'better-auth';
6
6
  import { GoogleOptions } from 'better-auth/social-providers';
7
- import { D as DatabaseClient } from '../client-B3nwdklT.js';
7
+ import { D as DatabaseClient } from '../client-DG_xZdlN.js';
8
8
  import 'drizzle-orm/node-postgres';
9
9
  import 'drizzle-orm/pglite';
10
- import '../schema-BhYTubhP.js';
10
+ import '../schema-DA6PfmoP.js';
11
11
  import 'drizzle-orm';
12
12
  import 'drizzle-orm/pg-core';
13
- import '../utility-5USfJ5Xd.js';
13
+ import '../utility-dsfXkYTu.js';
14
14
  import '@hono/zod-openapi';
15
15
  import 'drizzle-zod';
16
16
  import './auth-schema.js';
@@ -122,6 +122,7 @@ declare function createAuth(config: BetterAuthConfig): better_auth.Auth<{
122
122
  useNumberId?: boolean;
123
123
  generateId?: better_auth.GenerateIdFn | false | "serial" | "uuid";
124
124
  } | undefined;
125
+ trustedProxyHeaders?: boolean | undefined;
125
126
  };
126
127
  trustedOrigins: string[];
127
128
  plugins: [{
package/dist/auth/auth.js CHANGED
@@ -1,5 +1,5 @@
1
- import { generateId } from '../chunk-3HACEHXF.js';
2
- import { env } from '../chunk-RUTYLJB7.js';
1
+ import { generateId } from '../chunk-VXHL7CJY.js';
2
+ import { env } from '../chunk-ZIXAWYZI.js';
3
3
  import { ssoProvider } from '../chunk-GENLXHZ4.js';
4
4
  import { ownerRole, adminRole, memberRole, ac } from '../chunk-JNBVHWXX.js';
5
5
  import { sso } from '@better-auth/sso';
@@ -55,6 +55,8 @@ declare const SPAN_KEYS: {
55
55
  readonly AI_TOOL_CALL_ARGS: "ai.toolCall.args";
56
56
  readonly AI_TOOL_CALL_ID: "ai.toolCall.id";
57
57
  readonly AI_TOOL_TYPE: "ai.toolType";
58
+ readonly AI_TOOL_CALL_MCP_SERVER_ID: "ai.toolCall.mcpServerId";
59
+ readonly AI_TOOL_CALL_MCP_SERVER_NAME: "ai.toolCall.mcpServerName";
58
60
  readonly TOOL_PURPOSE: "tool.purpose";
59
61
  readonly TOOL_NAME: "tool.name";
60
62
  readonly TOOL_CALL_ID: "tool.callId";
@@ -106,6 +108,7 @@ declare const ACTIVITY_STATUS: {
106
108
  readonly SUCCESS: "success";
107
109
  readonly ERROR: "error";
108
110
  readonly PENDING: "pending";
111
+ readonly WARNING: "warning";
109
112
  };
110
113
  /** Agent IDs */
111
114
  declare const AGENT_IDS: {
@@ -0,0 +1,4 @@
1
+ // src/credential-stores/default-constants.ts
2
+ var DEFAULT_NANGO_STORE_ID = "nango-default";
3
+
4
+ export { DEFAULT_NANGO_STORE_ID };
@@ -1,5 +1,7 @@
1
1
  // src/constants/models.ts
2
2
  var ANTHROPIC_MODELS = {
3
+ CLAUDE_OPUS_4_5: "anthropic/claude-opus-4-5",
4
+ CLAUDE_OPUS_4_5_20251101: "anthropic/claude-opus-4-5-20251101",
3
5
  CLAUDE_OPUS_4_1: "anthropic/claude-opus-4-1",
4
6
  CLAUDE_OPUS_4_1_20250805: "anthropic/claude-opus-4-1-20250805",
5
7
  CLAUDE_SONNET_4_5: "anthropic/claude-sonnet-4-5",
@@ -1,5 +1,5 @@
1
1
  import { schemaValidationDefaults } from './chunk-Z64UK4CA.js';
2
- import { loadEnvironmentFiles } from './chunk-RUTYLJB7.js';
2
+ import { loadEnvironmentFiles } from './chunk-ZIXAWYZI.js';
3
3
  import { z } from '@hono/zod-openapi';
4
4
 
5
5
  loadEnvironmentFiles();
@@ -2,6 +2,46 @@ import { getLogger } from './chunk-DN4B564Y.js';
2
2
  import { z } from '@hono/zod-openapi';
3
3
 
4
4
  var logger = getLogger("schema-conversion");
5
+ function jsonSchemaToZod(jsonSchema) {
6
+ if (!jsonSchema || typeof jsonSchema !== "object") {
7
+ logger.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
8
+ return z.string();
9
+ }
10
+ const schemaType = jsonSchema.type;
11
+ switch (schemaType) {
12
+ case "object": {
13
+ const properties = jsonSchema.properties;
14
+ if (properties && typeof properties === "object") {
15
+ const shape = {};
16
+ for (const [key, prop] of Object.entries(properties)) {
17
+ shape[key] = jsonSchemaToZod(prop);
18
+ }
19
+ return z.object(shape);
20
+ }
21
+ return z.record(z.string(), z.string());
22
+ }
23
+ case "array": {
24
+ const items = jsonSchema.items;
25
+ const itemSchema = items ? jsonSchemaToZod(items) : z.string();
26
+ return z.array(itemSchema);
27
+ }
28
+ case "string":
29
+ return z.string();
30
+ case "number":
31
+ case "integer":
32
+ return z.number();
33
+ case "boolean":
34
+ return z.boolean();
35
+ case "null":
36
+ return z.null();
37
+ default:
38
+ logger.warn(
39
+ { unsupportedType: schemaType, schema: jsonSchema },
40
+ "Unsupported JSON schema type, using string fallback"
41
+ );
42
+ return z.string();
43
+ }
44
+ }
5
45
  function convertZodToJsonSchema(zodSchema) {
6
46
  try {
7
47
  const jsonSchema = z.toJSONSchema(zodSchema);
@@ -60,4 +100,4 @@ function extractPreviewFields(schema) {
60
100
  return previewFields;
61
101
  }
62
102
 
63
- export { convertZodToJsonSchema, convertZodToJsonSchemaWithPreview, extractPreviewFields, isZodSchema, preview };
103
+ export { convertZodToJsonSchema, convertZodToJsonSchemaWithPreview, extractPreviewFields, isZodSchema, jsonSchemaToZod, preview };
@@ -1,4 +1,4 @@
1
- import { AgentWithinContextOfProjectSchema, resourceIdSchema, MAX_ID_LENGTH } from './chunk-XHODTX4H.js';
1
+ import { AgentWithinContextOfProjectSchema, resourceIdSchema, MAX_ID_LENGTH } from './chunk-UK63CULA.js';
2
2
  import { z } from '@hono/zod-openapi';
3
3
 
4
4
  // src/validation/cycleDetection.ts
@@ -1,4 +1,4 @@
1
- import { schema_exports, projects } from './chunk-DEYPSEXR.js';
1
+ import { schema_exports, projects } from './chunk-LH6OJIIM.js';
2
2
  import { organization } from './chunk-GENLXHZ4.js';
3
3
  import { dirname, join } from 'path';
4
4
  import { fileURLToPath } from 'url';
@@ -10,7 +10,7 @@ function discoverScopes(resourceMetadata, metadata) {
10
10
  async function discoverMcpMetadata(mcpServerUrl, logger) {
11
11
  try {
12
12
  let resourceMetadata = null;
13
- let authServerUrl = new URL(mcpServerUrl);
13
+ let authServerUrl = new URL("/", mcpServerUrl);
14
14
  try {
15
15
  resourceMetadata = await discoverOAuthProtectedResourceMetadata(mcpServerUrl);
16
16
  if (resourceMetadata?.authorization_servers?.length && resourceMetadata.authorization_servers[0]) {
@@ -83,7 +83,7 @@ var subAgentScoped = {
83
83
  };
84
84
  var uiProperties = {
85
85
  name: varchar("name", { length: 256 }).notNull(),
86
- description: text("description").notNull()
86
+ description: text("description")
87
87
  };
88
88
  var timestamps = {
89
89
  createdAt: timestamp("created_at", { mode: "string" }).notNull().defaultNow(),
@@ -180,7 +180,7 @@ var subAgents = pgTable(
180
180
  {
181
181
  ...agentScoped,
182
182
  ...uiProperties,
183
- prompt: text("prompt").notNull(),
183
+ prompt: text("prompt"),
184
184
  conversationHistoryConfig: jsonb("conversation_history_config").$type().default({
185
185
  mode: "full",
186
186
  limit: 50,
@@ -236,14 +236,10 @@ var externalAgents = pgTable(
236
236
  name: "external_agents_project_fk"
237
237
  }).onDelete("cascade"),
238
238
  foreignKey({
239
- columns: [table.tenantId, table.projectId, table.credentialReferenceId],
240
- foreignColumns: [
241
- credentialReferences.tenantId,
242
- credentialReferences.projectId,
243
- credentialReferences.id
244
- ],
239
+ columns: [table.credentialReferenceId],
240
+ foreignColumns: [credentialReferences.id],
245
241
  name: "external_agents_credential_reference_fk"
246
- }).onDelete("cascade")
242
+ }).onDelete("set null")
247
243
  ]
248
244
  );
249
245
  var tasks = pgTable(
@@ -373,6 +369,8 @@ var tools = pgTable(
373
369
  description: text("description"),
374
370
  config: jsonb("config").$type().notNull(),
375
371
  credentialReferenceId: varchar("credential_reference_id", { length: 256 }),
372
+ credentialScope: varchar("credential_scope", { length: 50 }).notNull().default("project"),
373
+ // 'project' | 'user'
376
374
  headers: jsonb("headers").$type(),
377
375
  imageUrl: text("image_url"),
378
376
  capabilities: jsonb("capabilities").$type(),
@@ -385,7 +383,12 @@ var tools = pgTable(
385
383
  columns: [table.tenantId, table.projectId],
386
384
  foreignColumns: [projects.tenantId, projects.id],
387
385
  name: "tools_project_fk"
388
- }).onDelete("cascade")
386
+ }).onDelete("cascade"),
387
+ foreignKey({
388
+ columns: [table.credentialReferenceId],
389
+ foreignColumns: [credentialReferences.id],
390
+ name: "tools_credential_reference_fk"
391
+ }).onDelete("set null")
389
392
  ]
390
393
  );
391
394
  var functionTools = pgTable(
@@ -651,6 +654,13 @@ var credentialReferences = pgTable(
651
654
  type: varchar("type", { length: 256 }).notNull(),
652
655
  credentialStoreId: varchar("credential_store_id", { length: 256 }).notNull(),
653
656
  retrievalParams: jsonb("retrieval_params").$type(),
657
+ // For user-scoped credentials
658
+ toolId: varchar("tool_id", { length: 256 }),
659
+ // Links to the tool this credential is for
660
+ userId: varchar("user_id", { length: 256 }),
661
+ // User who owns this credential (null = project-scoped)
662
+ createdBy: varchar("created_by", { length: 256 }),
663
+ // User who created this credential
654
664
  ...timestamps
655
665
  },
656
666
  (t) => [
@@ -659,7 +669,12 @@ var credentialReferences = pgTable(
659
669
  columns: [t.tenantId, t.projectId],
660
670
  foreignColumns: [projects.tenantId, projects.id],
661
671
  name: "credential_references_project_fk"
662
- }).onDelete("cascade")
672
+ }).onDelete("cascade"),
673
+ // Unique constraint on id alone to support simple FK references
674
+ // (id is globally unique via nanoid generation)
675
+ unique("credential_references_id_unique").on(t.id),
676
+ // One credential per user per tool (for user-scoped credentials)
677
+ unique("credential_references_tool_user_unique").on(t.toolId, t.userId)
663
678
  ]
664
679
  );
665
680
  var tasksRelations = relations(tasks, ({ one, many }) => ({
@@ -57,6 +57,8 @@ var SPAN_KEYS = {
57
57
  AI_TOOL_CALL_ARGS: "ai.toolCall.args",
58
58
  AI_TOOL_CALL_ID: "ai.toolCall.id",
59
59
  AI_TOOL_TYPE: "ai.toolType",
60
+ AI_TOOL_CALL_MCP_SERVER_ID: "ai.toolCall.mcpServerId",
61
+ AI_TOOL_CALL_MCP_SERVER_NAME: "ai.toolCall.mcpServerName",
60
62
  TOOL_PURPOSE: "tool.purpose",
61
63
  TOOL_NAME: "tool.name",
62
64
  TOOL_CALL_ID: "tool.callId",
@@ -112,7 +114,8 @@ var ACTIVITY_TYPES = {
112
114
  var ACTIVITY_STATUS = {
113
115
  SUCCESS: "success",
114
116
  ERROR: "error",
115
- PENDING: "pending"
117
+ PENDING: "pending",
118
+ WARNING: "warning"
116
119
  };
117
120
  var AGENT_IDS = {
118
121
  USER: "user",
@@ -1,7 +1,8 @@
1
+ import { DEFAULT_NANGO_STORE_ID } from './chunk-3OPS2LN5.js';
1
2
  import { getLogger } from './chunk-DN4B564Y.js';
2
3
  import { CredentialStoreType } from './chunk-YFHT5M2R.js';
3
- import { Nango } from '@nangohq/node';
4
4
  import { z } from '@hono/zod-openapi';
5
+ import { Nango } from '@nangohq/node';
5
6
 
6
7
  // src/credential-stores/CredentialStoreRegistry.ts
7
8
  var CredentialStoreRegistry = class {
@@ -93,7 +94,10 @@ var KeyChainStore = class {
93
94
  return;
94
95
  }
95
96
  try {
96
- this.keytar = (await import('keytar')).default;
97
+ this.keytar = (await import(
98
+ /* webpackIgnore: true */
99
+ 'keytar'
100
+ )).default;
97
101
  this.keytarAvailable = true;
98
102
  this.logger.info(
99
103
  {
@@ -146,7 +150,6 @@ var KeyChainStore = class {
146
150
  }
147
151
  /**
148
152
  * Set a credential in the keychain
149
- * @param metadata - Optional metadata (ignored by keychain store)
150
153
  */
151
154
  async set(key, value, _metadata) {
152
155
  await this.initializationPromise;
@@ -743,7 +746,7 @@ function createDefaultCredentialStores() {
743
746
  stores.push(new InMemoryCredentialStore("memory-default"));
744
747
  if (process.env.NANGO_SECRET_KEY) {
745
748
  stores.push(
746
- createNangoCredentialStore("nango-default", {
749
+ createNangoCredentialStore(DEFAULT_NANGO_STORE_ID, {
747
750
  apiUrl: process.env.NANGO_SERVER_URL || "https://api.nango.dev",
748
751
  secretKey: process.env.NANGO_SECRET_KEY
749
752
  })
@@ -1,4 +1,4 @@
1
- import { subAgents, subAgentRelations, agents, tasks, taskRelations, conversations, messages, contextCache, dataComponents, subAgentDataComponents, artifactComponents, subAgentArtifactComponents, externalAgents, apiKeys, credentialReferences, tools, functionTools, functions, contextConfigs, subAgentToolRelations, subAgentExternalAgentRelations, subAgentTeamAgentRelations, ledgerArtifacts, projects } from './chunk-DEYPSEXR.js';
1
+ import { subAgents, subAgentRelations, agents, tasks, taskRelations, conversations, messages, contextCache, dataComponents, subAgentDataComponents, artifactComponents, subAgentArtifactComponents, externalAgents, apiKeys, credentialReferences, tools, functionTools, functions, contextConfigs, subAgentToolRelations, subAgentExternalAgentRelations, subAgentTeamAgentRelations, ledgerArtifacts, projects } from './chunk-LH6OJIIM.js';
2
2
  import { schemaValidationDefaults } from './chunk-Z64UK4CA.js';
3
3
  import { VALID_RELATION_TYPES, MCPTransportType, TOOL_STATUS_VALUES, CredentialStoreType, MCPServerType } from './chunk-YFHT5M2R.js';
4
4
  import { z } from '@hono/zod-openapi';
@@ -508,17 +508,7 @@ var ApiKeyApiInsertSchema = ApiKeyInsertSchema.omit({
508
508
  // Not set on creation
509
509
  }).openapi("ApiKeyCreate");
510
510
  var ApiKeyApiUpdateSchema = ApiKeyUpdateSchema.openapi("ApiKeyUpdate");
511
- var CredentialReferenceSelectSchema = z.object({
512
- id: z.string(),
513
- tenantId: z.string(),
514
- projectId: z.string(),
515
- name: z.string(),
516
- type: z.string(),
517
- credentialStoreId: z.string(),
518
- retrievalParams: z.record(z.string(), z.unknown()).nullish(),
519
- createdAt: z.string(),
520
- updatedAt: z.string()
521
- });
511
+ var CredentialReferenceSelectSchema = createSelectSchema(credentialReferences);
522
512
  var CredentialReferenceInsertSchema = createInsertSchema(credentialReferences).extend({
523
513
  id: resourceIdSchema,
524
514
  type: z.string(),
@@ -565,7 +555,7 @@ var CreateCredentialInStoreResponseSchema = z.object({
565
555
  var RelatedAgentInfoSchema = z.object({
566
556
  id: z.string(),
567
557
  name: z.string(),
568
- description: z.string()
558
+ description: z.string().nullable()
569
559
  }).openapi("RelatedAgentInfo");
570
560
  var ComponentAssociationSchema = z.object({
571
561
  subAgentId: z.string(),
@@ -588,6 +578,7 @@ var McpToolSchema = ToolInsertSchema.extend({
588
578
  status: ToolStatusSchema.default("unknown"),
589
579
  version: z.string().optional(),
590
580
  expiresAt: z.string().optional(),
581
+ createdBy: z.string().optional(),
591
582
  relationshipId: z.string().optional()
592
583
  }).openapi("McpTool");
593
584
  var MCPToolConfigSchema = McpToolSchema.omit({
@@ -636,6 +627,8 @@ var FetchConfigSchema = z.object({
636
627
  body: z.record(z.string(), z.unknown()).optional(),
637
628
  transform: z.string().optional(),
638
629
  // JSONPath or JS transform function
630
+ requiredToFetch: z.array(z.string()).optional(),
631
+ // Context variables that are required to run the fetch request. If the given variables cannot be resolved, the fetch request will be skipped.
639
632
  timeout: z.number().min(0).optional().default(CONTEXT_FETCHER_HTTP_TIMEOUT_MS_DEFAULT).optional()
640
633
  }).openapi("FetchConfig");
641
634
  var FetchDefinitionSchema = z.object({
@@ -793,7 +786,7 @@ var FullAgentAgentInsertSchema = SubAgentApiInsertSchema.extend({
793
786
  dataComponents: z.array(z.string()).optional(),
794
787
  artifactComponents: z.array(z.string()).optional(),
795
788
  canTransferTo: z.array(z.string()).optional(),
796
- prompt: z.string().trim().nonempty(),
789
+ prompt: z.string().trim().optional(),
797
790
  canDelegateTo: z.array(
798
791
  z.union([
799
792
  z.string(),
@@ -1,4 +1,4 @@
1
- import { loadEnvironmentFiles, env } from './chunk-RUTYLJB7.js';
1
+ import { loadEnvironmentFiles, env } from './chunk-ZIXAWYZI.js';
2
2
  import { getLogger } from './chunk-DN4B564Y.js';
3
3
  import { CredentialStoreType, MCPTransportType } from './chunk-YFHT5M2R.js';
4
4
  import { z } from '@hono/zod-openapi';
@@ -685,6 +685,7 @@ var nimDefault = createOpenAICompatible({
685
685
  var ModelFactory = class _ModelFactory {
686
686
  /**
687
687
  * Create a provider instance with custom configuration
688
+ * Returns a provider with at least languageModel method
688
689
  */
689
690
  static createProvider(provider, config) {
690
691
  switch (provider) {
@@ -695,15 +696,7 @@ var ModelFactory = class _ModelFactory {
695
696
  case "google":
696
697
  return createGoogleGenerativeAI(config);
697
698
  case "openrouter":
698
- return {
699
- ...createOpenRouter(config),
700
- textEmbeddingModel: () => {
701
- throw new Error("OpenRouter does not support text embeddings");
702
- },
703
- imageModel: () => {
704
- throw new Error("OpenRouter does not support image generation");
705
- }
706
- };
699
+ return createOpenRouter(config);
707
700
  case "gateway":
708
701
  return createGateway(config);
709
702
  case "nim": {
@@ -1141,6 +1134,12 @@ function deriveComposioUserId(tenantId, projectId) {
1141
1134
  const SEPARATOR = "||";
1142
1135
  return `${tenantId}${SEPARATOR}${projectId}`;
1143
1136
  }
1137
+ function getComposioUserId(tenantId, projectId, credentialScope, userId) {
1138
+ if (credentialScope === "user" && userId) {
1139
+ return userId;
1140
+ }
1141
+ return deriveComposioUserId(tenantId, projectId);
1142
+ }
1144
1143
  function extractComposioServerId(mcpUrl) {
1145
1144
  if (!mcpUrl.includes("composio.dev")) {
1146
1145
  return null;
@@ -1157,12 +1156,6 @@ function extractComposioServerId(mcpUrl) {
1157
1156
  return null;
1158
1157
  }
1159
1158
  }
1160
- function addUserIdToUrl(url, userId) {
1161
- const urlObj = new URL(url);
1162
- urlObj.searchParams.set("user_id", userId);
1163
- urlObj.searchParams.delete("transport");
1164
- return urlObj.toString();
1165
- }
1166
1159
  async function deleteComposioConnectedAccount(accountId) {
1167
1160
  const composioInstance = getComposioInstance();
1168
1161
  if (!composioInstance) {
@@ -1185,7 +1178,8 @@ async function fetchComposioConnectedAccounts(derivedUserId) {
1185
1178
  }
1186
1179
  try {
1187
1180
  const connectedAccounts = await composioInstance.connectedAccounts.list({
1188
- userIds: [derivedUserId]
1181
+ userIds: [derivedUserId],
1182
+ statuses: ["ACTIVE", "INITIATED"]
1189
1183
  });
1190
1184
  return connectedAccounts;
1191
1185
  } catch (error) {
@@ -1193,7 +1187,7 @@ async function fetchComposioConnectedAccounts(derivedUserId) {
1193
1187
  return null;
1194
1188
  }
1195
1189
  }
1196
- async function isComposioMCPServerAuthenticated(tenantId, projectId, mcpServerUrl) {
1190
+ async function isComposioMCPServerAuthenticated(tenantId, projectId, mcpServerUrl, credentialScope = "project", userId) {
1197
1191
  const composioApiKey = process.env.COMPOSIO_API_KEY;
1198
1192
  if (!composioApiKey) {
1199
1193
  logger4.info({}, "Composio API key not configured, skipping auth check");
@@ -1204,7 +1198,7 @@ async function isComposioMCPServerAuthenticated(tenantId, projectId, mcpServerUr
1204
1198
  logger4.info({ mcpServerUrl }, "Could not extract Composio server ID from URL");
1205
1199
  return false;
1206
1200
  }
1207
- const derivedUserId = deriveComposioUserId(tenantId, projectId);
1201
+ const composioUserId = getComposioUserId(tenantId, projectId, credentialScope, userId);
1208
1202
  const composioInstance = getComposioInstance();
1209
1203
  if (!composioInstance) {
1210
1204
  logger4.info({}, "Composio not configured, skipping auth check");
@@ -1216,7 +1210,7 @@ async function isComposioMCPServerAuthenticated(tenantId, projectId, mcpServerUr
1216
1210
  if (!firstAuthConfigId) {
1217
1211
  return false;
1218
1212
  }
1219
- const connectedAccounts = await fetchComposioConnectedAccounts(derivedUserId);
1213
+ const connectedAccounts = await fetchComposioConnectedAccounts(composioUserId);
1220
1214
  if (!connectedAccounts) {
1221
1215
  return false;
1222
1216
  }
@@ -1277,15 +1271,44 @@ async function ensureComposioAccount(composioMcpServer, derivedUserId, initiated
1277
1271
  return null;
1278
1272
  }
1279
1273
  }
1274
+ async function getComposioOAuthRedirectUrl(tenantId, projectId, mcpServerUrl, credentialScope, userId) {
1275
+ const composioApiKey = process.env.COMPOSIO_API_KEY;
1276
+ if (!composioApiKey) {
1277
+ logger4.info({}, "Composio API key not configured");
1278
+ return null;
1279
+ }
1280
+ const serverId = extractComposioServerId(mcpServerUrl);
1281
+ if (!serverId) {
1282
+ logger4.info({ mcpServerUrl }, "Could not extract Composio server ID from URL");
1283
+ return null;
1284
+ }
1285
+ const composioInstance = getComposioInstance();
1286
+ if (!composioInstance) {
1287
+ logger4.info({}, "Composio not configured");
1288
+ return null;
1289
+ }
1290
+ const composioUserId = getComposioUserId(tenantId, projectId, credentialScope, userId);
1291
+ try {
1292
+ const composioMcpServer = await composioInstance.mcp.get(serverId);
1293
+ const connectedAccounts = await fetchComposioConnectedAccounts(composioUserId);
1294
+ const initiatedAccounts = connectedAccounts?.items.filter((account) => account.status === "INITIATED") ?? [];
1295
+ const redirectUrl = await ensureComposioAccount(
1296
+ composioMcpServer,
1297
+ composioUserId,
1298
+ initiatedAccounts
1299
+ );
1300
+ return redirectUrl;
1301
+ } catch (error) {
1302
+ logger4.error({ error, mcpServerUrl }, "Failed to get Composio OAuth redirect URL");
1303
+ return null;
1304
+ }
1305
+ }
1280
1306
  async function transformComposioServer(composioMcpServer, authenticatedAuthConfigIds, initiatedAccounts, derivedUserId) {
1281
1307
  const isAuthenticated = composioMcpServer.authConfigIds.some(
1282
1308
  (authConfigId) => authenticatedAuthConfigIds.has(authConfigId)
1283
1309
  );
1284
- let url = composioMcpServer.MCPUrl;
1285
1310
  let thirdPartyConnectAccountUrl;
1286
- if (isAuthenticated) {
1287
- url = addUserIdToUrl(url, derivedUserId);
1288
- } else {
1311
+ if (!isAuthenticated) {
1289
1312
  const redirectUrl = await ensureComposioAccount(
1290
1313
  composioMcpServer,
1291
1314
  derivedUserId,
@@ -1295,22 +1318,20 @@ async function transformComposioServer(composioMcpServer, authenticatedAuthConfi
1295
1318
  return null;
1296
1319
  }
1297
1320
  thirdPartyConnectAccountUrl = redirectUrl;
1298
- url = addUserIdToUrl(url, derivedUserId);
1299
1321
  }
1300
1322
  return transformComposioServerData(
1301
1323
  composioMcpServer,
1302
1324
  isAuthenticated,
1303
- url,
1325
+ composioMcpServer.MCPUrl,
1304
1326
  thirdPartyConnectAccountUrl
1305
1327
  );
1306
1328
  }
1307
- async function fetchComposioServers(tenantId, projectId) {
1329
+ async function fetchComposioServers() {
1308
1330
  const composioApiKey = process.env.COMPOSIO_API_KEY;
1309
1331
  if (!composioApiKey) {
1310
1332
  logger4.info({}, "COMPOSIO_API_KEY not configured, skipping Composio servers");
1311
1333
  return [];
1312
1334
  }
1313
- const derivedUserId = deriveComposioUserId(tenantId, projectId);
1314
1335
  const composioInstance = getComposioInstance();
1315
1336
  if (!composioInstance) {
1316
1337
  logger4.info({}, "Composio not configured, returning empty list");
@@ -1323,44 +1344,30 @@ async function fetchComposioServers(tenantId, projectId) {
1323
1344
  page: 1,
1324
1345
  authConfigs: []
1325
1346
  });
1326
- const userConnectedAccounts = await composioInstance.connectedAccounts.list({
1327
- userIds: [derivedUserId]
1328
- });
1329
- const activeAccounts = userConnectedAccounts?.items.filter(
1330
- (account) => account.status === "ACTIVE"
1331
- );
1332
- const initiatedAccounts = userConnectedAccounts?.items.filter(
1333
- (account) => account.status === "INITIATED"
1334
- );
1335
- const authenticatedAuthConfigIds = new Set(
1336
- activeAccounts?.map((account) => account.authConfig.id) ?? []
1337
- );
1338
- const transformedServers = await Promise.all(
1339
- composioMcpServers?.items.map(
1340
- (server) => transformComposioServer(
1341
- server,
1342
- authenticatedAuthConfigIds,
1343
- initiatedAccounts ?? [],
1344
- derivedUserId
1345
- )
1347
+ const transformedServers = composioMcpServers?.items.map(
1348
+ (server) => transformComposioServerData(
1349
+ server,
1350
+ false,
1351
+ // Always false for catalog - we want scope dialog to show
1352
+ server.MCPUrl,
1353
+ // Raw URL without user_id
1354
+ void 0
1355
+ // No OAuth redirect URL for catalog
1346
1356
  )
1347
1357
  );
1348
- const validServers = transformedServers.filter(
1349
- (server) => server !== null
1350
- );
1351
- return validServers;
1358
+ return transformedServers ?? [];
1352
1359
  } catch (error) {
1353
1360
  logger4.error({ error }, "Failed to fetch Composio servers");
1354
1361
  return [];
1355
1362
  }
1356
1363
  }
1357
- async function fetchSingleComposioServer(tenantId, projectId, mcpServerUrl) {
1364
+ async function fetchSingleComposioServer(tenantId, projectId, mcpServerUrl, credentialScope = "project", userId) {
1358
1365
  const composioApiKey = process.env.COMPOSIO_API_KEY;
1359
1366
  if (!composioApiKey) {
1360
1367
  logger4.debug({}, "COMPOSIO_API_KEY not configured");
1361
1368
  return null;
1362
1369
  }
1363
- const derivedUserId = deriveComposioUserId(tenantId, projectId);
1370
+ const composioUserId = getComposioUserId(tenantId, projectId, credentialScope, userId);
1364
1371
  const composioInstance = getComposioInstance();
1365
1372
  if (!composioInstance) {
1366
1373
  logger4.info({}, "Composio not configured, returning null");
@@ -1374,7 +1381,8 @@ async function fetchSingleComposioServer(tenantId, projectId, mcpServerUrl) {
1374
1381
  }
1375
1382
  const composioMcpServer = await composioInstance.mcp.get(serverId);
1376
1383
  const userConnectedAccounts = await composioInstance.connectedAccounts.list({
1377
- userIds: [derivedUserId]
1384
+ userIds: [composioUserId],
1385
+ statuses: ["ACTIVE", "INITIATED"]
1378
1386
  });
1379
1387
  const activeAccounts = userConnectedAccounts?.items.filter(
1380
1388
  (account) => account.status === "ACTIVE"
@@ -1389,7 +1397,7 @@ async function fetchSingleComposioServer(tenantId, projectId, mcpServerUrl) {
1389
1397
  composioMcpServer,
1390
1398
  authenticatedAuthConfigIds,
1391
1399
  initiatedAccounts ?? [],
1392
- derivedUserId
1400
+ composioUserId
1393
1401
  );
1394
1402
  return transformedServer;
1395
1403
  } catch (error) {
@@ -1400,11 +1408,17 @@ async function fetchSingleComposioServer(tenantId, projectId, mcpServerUrl) {
1400
1408
 
1401
1409
  // src/utils/third-party-mcp-servers/third-party-check.ts
1402
1410
  var logger5 = getLogger("third-party-check");
1403
- async function isThirdPartyMCPServerAuthenticated(tenantId, projectId, mcpServerUrl) {
1411
+ async function isThirdPartyMCPServerAuthenticated(tenantId, projectId, mcpServerUrl, credentialScope = "project", userId) {
1404
1412
  const composioServerId = extractComposioServerId(mcpServerUrl);
1405
1413
  if (composioServerId) {
1406
1414
  logger5.debug({ mcpServerUrl }, "Detected Composio MCP server, checking auth status");
1407
- return isComposioMCPServerAuthenticated(tenantId, projectId, mcpServerUrl);
1415
+ return isComposioMCPServerAuthenticated(
1416
+ tenantId,
1417
+ projectId,
1418
+ mcpServerUrl,
1419
+ credentialScope,
1420
+ userId
1421
+ );
1408
1422
  }
1409
1423
  logger5.info({ mcpServerUrl }, "Unknown third-party MCP server provider");
1410
1424
  return false;
@@ -1457,4 +1471,4 @@ function getTracer(serviceName, serviceVersion) {
1457
1471
  }
1458
1472
  }
1459
1473
 
1460
- export { CONVERSATION_HISTORY_DEFAULT_LIMIT, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, ERROR_DOCS_BASE_URL, ErrorCode, MCP_TOOL_CONNECTION_TIMEOUT_MS, MCP_TOOL_INITIAL_RECONNECTION_DELAY_MS, MCP_TOOL_MAX_RECONNECTION_DELAY_MS, MCP_TOOL_MAX_RETRIES, MCP_TOOL_RECONNECTION_DELAY_GROWTH_FACTOR, McpClient, ModelFactory, commonCreateErrorResponses, commonDeleteErrorResponses, commonGetErrorResponses, commonUpdateErrorResponses, createApiError, createExecutionContext, errorResponseSchema, errorSchemaFactory, executionLimitsSharedDefaults, extractComposioServerId, extractPublicId, fetchComposioServers, fetchSingleComposioServer, formatMessagesForLLM, formatMessagesForLLMContext, generateApiKey, generateId, generateServiceToken, getConversationId, getCredentialStoreLookupKeyFromRetrievalParams, getRequestExecutionContext, getTracer, handleApiError, hashApiKey, isApiKeyExpired, isComposioMCPServerAuthenticated, isThirdPartyMCPServerAuthenticated, maskApiKey, normalizeDateString, problemDetailsSchema, setSpanWithError, signTempToken, toISODateString, validateApiKey, validateTargetAgent, validateTenantId, verifyAuthorizationHeader, verifyServiceToken, verifyTempToken };
1474
+ export { CONVERSATION_HISTORY_DEFAULT_LIMIT, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, ERROR_DOCS_BASE_URL, ErrorCode, MCP_TOOL_CONNECTION_TIMEOUT_MS, MCP_TOOL_INITIAL_RECONNECTION_DELAY_MS, MCP_TOOL_MAX_RECONNECTION_DELAY_MS, MCP_TOOL_MAX_RETRIES, MCP_TOOL_RECONNECTION_DELAY_GROWTH_FACTOR, McpClient, ModelFactory, commonCreateErrorResponses, commonDeleteErrorResponses, commonGetErrorResponses, commonUpdateErrorResponses, createApiError, createExecutionContext, errorResponseSchema, errorSchemaFactory, executionLimitsSharedDefaults, extractComposioServerId, extractPublicId, fetchComposioServers, fetchSingleComposioServer, formatMessagesForLLM, formatMessagesForLLMContext, generateApiKey, generateId, generateServiceToken, getComposioOAuthRedirectUrl, getComposioUserId, getConversationId, getCredentialStoreLookupKeyFromRetrievalParams, getRequestExecutionContext, getTracer, handleApiError, hashApiKey, isApiKeyExpired, isComposioMCPServerAuthenticated, isThirdPartyMCPServerAuthenticated, maskApiKey, normalizeDateString, problemDetailsSchema, setSpanWithError, signTempToken, toISODateString, validateApiKey, validateTargetAgent, validateTenantId, verifyAuthorizationHeader, verifyServiceToken, verifyTempToken };
@@ -1,6 +1,6 @@
1
1
  import { NodePgDatabase } from 'drizzle-orm/node-postgres';
2
2
  import { PgliteDatabase } from 'drizzle-orm/pglite';
3
- import { s as schema } from './schema-BhYTubhP.js';
3
+ import { s as schema } from './schema-DA6PfmoP.js';
4
4
 
5
5
  type DatabaseClient = NodePgDatabase<typeof schema> | PgliteDatabase<typeof schema>;
6
6
  interface DatabaseConfig {