@inkeep/agents-manage-api 0.39.4 → 0.40.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.
Files changed (123) hide show
  1. package/dist/create-app.d.ts +21 -0
  2. package/dist/create-app.js +144 -0
  3. package/dist/data/agentFull.d.ts +15 -0
  4. package/dist/data/agentFull.js +84 -0
  5. package/dist/data/conversations.d.ts +77 -0
  6. package/dist/data/conversations.js +152 -0
  7. package/dist/data/db/dbClient.d.ts +6 -0
  8. package/dist/data/db/dbClient.js +17 -0
  9. package/dist/env.d.ts +61 -0
  10. package/dist/env.js +55 -0
  11. package/dist/factory.d.ts +17 -2
  12. package/dist/factory.js +35 -2
  13. package/dist/index.d.ts +119 -22
  14. package/dist/index.js +8 -5
  15. package/dist/initialization.d.ts +6 -0
  16. package/dist/initialization.js +79 -0
  17. package/dist/logger.d.ts +2 -0
  18. package/dist/logger.js +3 -0
  19. package/dist/middleware/auth.d.ts +24 -0
  20. package/dist/middleware/auth.js +55 -0
  21. package/dist/middleware/error-handler.d.ts +12 -0
  22. package/dist/middleware/error-handler.js +88 -0
  23. package/dist/middleware/require-permission.d.ts +19 -0
  24. package/dist/middleware/require-permission.js +80 -0
  25. package/dist/middleware/session-auth.d.ts +6 -0
  26. package/dist/middleware/session-auth.js +26 -0
  27. package/dist/middleware/tenant-access.d.ts +12 -0
  28. package/dist/middleware/tenant-access.js +54 -0
  29. package/dist/openapi.d.ts +7 -0
  30. package/dist/openapi.js +157 -0
  31. package/dist/routes/agent.d.ts +9 -0
  32. package/dist/routes/agent.js +244 -0
  33. package/dist/routes/agentFull.d.ts +9 -0
  34. package/dist/routes/agentFull.js +188 -0
  35. package/dist/routes/agentToolRelations.d.ts +9 -0
  36. package/dist/routes/agentToolRelations.js +284 -0
  37. package/dist/routes/apiKeys.d.ts +9 -0
  38. package/dist/routes/apiKeys.js +217 -0
  39. package/dist/routes/artifactComponents.d.ts +9 -0
  40. package/dist/routes/artifactComponents.js +204 -0
  41. package/dist/routes/cliAuth.d.ts +9 -0
  42. package/dist/routes/cliAuth.js +60 -0
  43. package/dist/routes/contextConfigs.d.ts +9 -0
  44. package/dist/routes/contextConfigs.js +175 -0
  45. package/dist/routes/conversations.d.ts +7 -0
  46. package/dist/routes/conversations.js +59 -0
  47. package/dist/routes/credentialStores.d.ts +9 -0
  48. package/dist/routes/credentialStores.js +81 -0
  49. package/dist/routes/credentials.d.ts +9 -0
  50. package/dist/routes/credentials.js +204 -0
  51. package/dist/routes/dataComponents.d.ts +9 -0
  52. package/dist/routes/dataComponents.js +188 -0
  53. package/dist/routes/externalAgents.d.ts +9 -0
  54. package/dist/routes/externalAgents.js +195 -0
  55. package/dist/routes/functionTools.d.ts +9 -0
  56. package/dist/routes/functionTools.js +252 -0
  57. package/dist/routes/functions.d.ts +9 -0
  58. package/dist/routes/functions.js +281 -0
  59. package/dist/routes/index.d.ts +7 -0
  60. package/dist/routes/index.js +54 -0
  61. package/dist/routes/invitations.d.ts +9 -0
  62. package/dist/routes/invitations.js +41 -0
  63. package/dist/routes/mcp.d.ts +7 -0
  64. package/dist/routes/mcp.js +45 -0
  65. package/dist/routes/mcpCatalog.d.ts +13 -0
  66. package/dist/routes/mcpCatalog.js +454 -0
  67. package/dist/routes/oauth.d.ts +10 -0
  68. package/dist/routes/oauth.js +314 -0
  69. package/dist/routes/playgroundToken.d.ts +9 -0
  70. package/dist/routes/playgroundToken.js +108 -0
  71. package/dist/routes/projectFull.d.ts +9 -0
  72. package/dist/routes/projectFull.js +193 -0
  73. package/dist/routes/projects.d.ts +9 -0
  74. package/dist/routes/projects.js +188 -0
  75. package/dist/routes/shared.d.ts +93 -0
  76. package/dist/routes/shared.js +44 -0
  77. package/dist/routes/signoz.d.ts +10 -0
  78. package/dist/routes/signoz.js +155 -0
  79. package/dist/routes/subAgentArtifactComponents.d.ts +9 -0
  80. package/dist/routes/subAgentArtifactComponents.js +198 -0
  81. package/dist/routes/subAgentDataComponents.d.ts +9 -0
  82. package/dist/routes/subAgentDataComponents.js +197 -0
  83. package/dist/routes/subAgentExternalAgentRelations.d.ts +9 -0
  84. package/dist/routes/subAgentExternalAgentRelations.js +213 -0
  85. package/dist/routes/subAgentRelations.d.ts +9 -0
  86. package/dist/routes/subAgentRelations.js +259 -0
  87. package/dist/routes/subAgentTeamAgentRelations.d.ts +9 -0
  88. package/dist/routes/subAgentTeamAgentRelations.js +213 -0
  89. package/dist/routes/subAgentToolRelations.d.ts +9 -0
  90. package/dist/routes/subAgentToolRelations.js +284 -0
  91. package/dist/routes/subAgents.d.ts +9 -0
  92. package/dist/routes/subAgents.js +210 -0
  93. package/dist/routes/thirdPartyMCPServers.d.ts +14 -0
  94. package/dist/routes/thirdPartyMCPServers.js +72 -0
  95. package/dist/routes/tools.d.ts +9 -0
  96. package/dist/routes/tools.js +256 -0
  97. package/dist/routes/userOrganizations.d.ts +9 -0
  98. package/dist/routes/userOrganizations.js +58 -0
  99. package/dist/sso-helpers.d.ts +20 -0
  100. package/dist/sso-helpers.js +51 -0
  101. package/dist/types/app.d.ts +47 -0
  102. package/dist/types/app.js +1 -0
  103. package/dist/utils/cors.d.ts +33 -0
  104. package/dist/utils/cors.js +98 -0
  105. package/dist/utils/oauth-service.d.ts +71 -0
  106. package/dist/utils/oauth-service.js +106 -0
  107. package/dist/utils/signoz-helpers.d.ts +9 -0
  108. package/dist/utils/signoz-helpers.js +33 -0
  109. package/dist/utils/temp-api-keys.d.ts +17 -0
  110. package/dist/utils/temp-api-keys.js +26 -0
  111. package/package.json +6 -13
  112. package/dist/chunk-VBDAOXYI.js +0 -832
  113. package/dist/chunk-VBDAOXYI.js.map +0 -1
  114. package/dist/factory2.d.ts +0 -41
  115. package/dist/factory2.d.ts.map +0 -1
  116. package/dist/factory2.js +0 -37085
  117. package/dist/factory2.js.map +0 -1
  118. package/dist/index.d.ts.map +0 -1
  119. package/dist/index.js.map +0 -1
  120. package/dist/nodefs.js +0 -27
  121. package/dist/nodefs.js.map +0 -1
  122. package/dist/opfs-ahp.js +0 -368
  123. package/dist/opfs-ahp.js.map +0 -1
@@ -0,0 +1,21 @@
1
+ import { Hono } from "hono";
2
+ import { ServerConfig } from "@inkeep/agents-core";
3
+ import { auth, createAuth } from "@inkeep/agents-core/auth";
4
+ import * as hono_types0 from "hono/types";
5
+ import { CredentialStoreRegistry as CredentialStoreRegistry$1 } from "@inkeep/agents-core/credential-stores";
6
+
7
+ //#region src/create-app.d.ts
8
+ type AppVariables = {
9
+ serverConfig: ServerConfig;
10
+ credentialStores: CredentialStoreRegistry$1;
11
+ auth: ReturnType<typeof createAuth> | null;
12
+ user: typeof auth.$Infer.Session.user | null;
13
+ session: typeof auth.$Infer.Session.session | null;
14
+ userId?: string;
15
+ userEmail?: string;
16
+ tenantId?: string;
17
+ tenantRole?: string;
18
+ };
19
+ declare function createManagementHono(serverConfig: ServerConfig, credentialStores: CredentialStoreRegistry$1, auth: ReturnType<typeof createAuth> | null): Hono<hono_types0.BlankEnv, hono_types0.BlankSchema, "/">;
20
+ //#endregion
21
+ export { AppVariables, createManagementHono };
@@ -0,0 +1,144 @@
1
+ import { env } from "./env.js";
2
+ import { getLogger } from "./logger.js";
3
+ import { apiKeyAuth } from "./middleware/auth.js";
4
+ import { errorHandler } from "./middleware/error-handler.js";
5
+ import { sessionAuth } from "./middleware/session-auth.js";
6
+ import { requireTenantAccess } from "./middleware/tenant-access.js";
7
+ import { setupOpenAPIRoutes } from "./openapi.js";
8
+ import cliAuth_default from "./routes/cliAuth.js";
9
+ import routes_default from "./routes/index.js";
10
+ import invitations_default from "./routes/invitations.js";
11
+ import mcp_default from "./routes/mcp.js";
12
+ import oauth_default from "./routes/oauth.js";
13
+ import playgroundToken_default from "./routes/playgroundToken.js";
14
+ import projectFull_default from "./routes/projectFull.js";
15
+ import signoz_default from "./routes/signoz.js";
16
+ import userOrganizations_default from "./routes/userOrganizations.js";
17
+ import { authCorsConfig, defaultCorsConfig, isOriginAllowed, playgroundCorsConfig } from "./utils/cors.js";
18
+ import { OpenAPIHono, createRoute } from "@hono/zod-openapi";
19
+ import { Hono } from "hono";
20
+ import { cors } from "hono/cors";
21
+ import { requestId } from "hono/request-id";
22
+ import { pinoLogger } from "hono-pino";
23
+
24
+ //#region src/create-app.ts
25
+ const logger = getLogger("agents-manage-api");
26
+ logger.info({ logger: logger.getTransports() }, "Logger initialized");
27
+ const isTestEnvironment = () => process.env.ENVIRONMENT === "test";
28
+ function createManagementHono(serverConfig, credentialStores, auth) {
29
+ const app = new OpenAPIHono();
30
+ app.use("*", requestId());
31
+ app.use("*", async (c, next) => {
32
+ c.set("serverConfig", serverConfig);
33
+ c.set("credentialStores", credentialStores);
34
+ c.set("auth", auth);
35
+ return next();
36
+ });
37
+ app.use(pinoLogger({
38
+ pino: getLogger("agents-manage-api").getPinoInstance(),
39
+ http: { onResLevel(c) {
40
+ if (c.res.status >= 500) return "error";
41
+ return "info";
42
+ } }
43
+ }));
44
+ app.onError(errorHandler);
45
+ if (auth) {
46
+ app.use("/api/auth/*", cors(authCorsConfig));
47
+ app.on(["POST", "GET"], "/api/auth/*", (c) => {
48
+ return auth.handler(c.req.raw);
49
+ });
50
+ }
51
+ app.use("/tenants/*/playground/token", cors(playgroundCorsConfig));
52
+ app.use("/tenants/*/signoz/*", cors({
53
+ origin: (origin) => {
54
+ return isOriginAllowed(origin) ? origin : null;
55
+ },
56
+ allowHeaders: [
57
+ "content-type",
58
+ "Content-Type",
59
+ "authorization",
60
+ "Authorization",
61
+ "User-Agent",
62
+ "Cookie",
63
+ "X-Forwarded-Cookie"
64
+ ],
65
+ allowMethods: [
66
+ "GET",
67
+ "POST",
68
+ "OPTIONS"
69
+ ],
70
+ exposeHeaders: ["Content-Length", "Set-Cookie"],
71
+ maxAge: 600,
72
+ credentials: true
73
+ }));
74
+ app.use("*", async (c, next) => {
75
+ if (auth && c.req.path.startsWith("/api/auth/")) return next();
76
+ if (c.req.path.includes("/playground/token")) return next();
77
+ if (c.req.path.includes("/signoz/")) return next();
78
+ return cors(defaultCorsConfig)(c, next);
79
+ });
80
+ app.use("*", async (c, next) => {
81
+ if (env.DISABLE_AUTH || !auth) {
82
+ c.set("user", null);
83
+ c.set("session", null);
84
+ await next();
85
+ return;
86
+ }
87
+ const headers = new Headers(c.req.raw.headers);
88
+ const forwardedCookie = headers.get("x-forwarded-cookie");
89
+ if (forwardedCookie && !headers.get("cookie")) headers.set("cookie", forwardedCookie);
90
+ const session = await auth.api.getSession({ headers });
91
+ if (!session) {
92
+ c.set("user", null);
93
+ c.set("session", null);
94
+ await next();
95
+ return;
96
+ }
97
+ c.set("user", session.user);
98
+ c.set("session", session.session);
99
+ await next();
100
+ });
101
+ app.openapi(createRoute({
102
+ method: "get",
103
+ path: "/health",
104
+ operationId: "health",
105
+ summary: "Health check",
106
+ description: "Check if the management service is healthy",
107
+ responses: { 204: { description: "Service is healthy" } }
108
+ }), (c) => {
109
+ return c.body(null, 204);
110
+ });
111
+ app.use("/tenants/*", async (c, next) => {
112
+ if (env.DISABLE_AUTH || isTestEnvironment()) {
113
+ await next();
114
+ return;
115
+ }
116
+ if (c.req.header("Authorization")?.startsWith("Bearer ")) return apiKeyAuth()(c, next);
117
+ return sessionAuth()(c, next);
118
+ });
119
+ if (env.DISABLE_AUTH || isTestEnvironment()) app.use("/tenants/:tenantId/*", async (c, next) => {
120
+ const tenantId = c.req.param("tenantId");
121
+ if (tenantId) {
122
+ c.set("tenantId", tenantId);
123
+ c.set("userId", "anonymous");
124
+ }
125
+ await next();
126
+ });
127
+ else app.use("/tenants/:tenantId/*", requireTenantAccess());
128
+ app.route("/api/users/:userId/organizations", userOrganizations_default);
129
+ app.route("/api/cli", cliAuth_default);
130
+ app.route("/api/invitations", invitations_default);
131
+ app.route("/tenants/:tenantId", routes_default);
132
+ app.route("/tenants/:tenantId/playground/token", playgroundToken_default);
133
+ app.route("/tenants/:tenantId/signoz", signoz_default);
134
+ app.route("/tenants/:tenantId", projectFull_default);
135
+ app.route("/oauth", oauth_default);
136
+ app.route("/mcp", mcp_default);
137
+ setupOpenAPIRoutes(app);
138
+ const baseApp = new Hono();
139
+ baseApp.route("/", app);
140
+ return baseApp;
141
+ }
142
+
143
+ //#endregion
144
+ export { createManagementHono };
@@ -0,0 +1,15 @@
1
+ import { FullAgentDefinition } from "@inkeep/agents-core";
2
+
3
+ //#region src/data/agentFull.d.ts
4
+
5
+ /**
6
+ * Client-side implementation of createFullAgent that makes HTTP requests to the API endpoint.
7
+ * This function should be used by client code instead of directly accessing the data layer.
8
+ */
9
+ declare const createFullAgent: (tenantId: string, agentData: FullAgentDefinition) => Promise<FullAgentDefinition>;
10
+ /**
11
+ * Client-side implementation of updateFullAgent that makes HTTP requests to the API endpoint.
12
+ */
13
+ declare const updateFullAgent: (tenantId: string, agentId: string, agentData: FullAgentDefinition) => Promise<FullAgentDefinition>;
14
+ //#endregion
15
+ export { createFullAgent, updateFullAgent };
@@ -0,0 +1,84 @@
1
+ import { env } from "../env.js";
2
+ import { getLogger as getLogger$1 } from "../logger.js";
3
+ import { validateAndTypeAgentData } from "@inkeep/agents-core";
4
+
5
+ //#region src/data/agentFull.ts
6
+ const logger = getLogger$1("agentFull");
7
+ /**
8
+ * Client-side implementation of createFullAgent that makes HTTP requests to the API endpoint.
9
+ * This function should be used by client code instead of directly accessing the data layer.
10
+ */
11
+ const createFullAgent = async (tenantId, agentData) => {
12
+ logger.info({
13
+ tenantId,
14
+ agentId: agentData.id,
15
+ subAgentCount: Object.keys(agentData.subAgents || {}).length
16
+ }, "Creating full agent via API endpoint");
17
+ try {
18
+ const endpoint = `${env.INKEEP_AGENTS_MANAGE_API_URL}/tenants/${tenantId}/agent`;
19
+ const response = await fetch(endpoint, {
20
+ method: "POST",
21
+ headers: { "Content-Type": "application/json" },
22
+ body: JSON.stringify(agentData)
23
+ });
24
+ if (!response.ok) {
25
+ const errorText = await response.text();
26
+ throw new Error(`HTTP error ${response.status}: ${errorText}`);
27
+ }
28
+ const result = await response.json();
29
+ logger.info({
30
+ tenantId,
31
+ agentId: agentData.id,
32
+ status: response.status
33
+ }, "Full agent created successfully via API");
34
+ return result.data;
35
+ } catch (error) {
36
+ logger.error({
37
+ tenantId,
38
+ agentId: agentData.id,
39
+ error: error instanceof Error ? error.message : "Unknown error"
40
+ }, "Failed to create full agent via API");
41
+ throw error;
42
+ }
43
+ };
44
+ /**
45
+ * Client-side implementation of updateFullAgent that makes HTTP requests to the API endpoint.
46
+ */
47
+ const updateFullAgent = async (tenantId, agentId, agentData) => {
48
+ const typed = validateAndTypeAgentData(agentData);
49
+ if (agentId !== typed.id) throw new Error(`Agent ID mismatch: expected ${agentId}, got ${typed.id}`);
50
+ logger.info({
51
+ tenantId,
52
+ agentId,
53
+ subAgentCount: Object.keys(agentData.subAgents || {}).length
54
+ }, "Updating full agent via API endpoint");
55
+ try {
56
+ const endpoint = `${env.INKEEP_AGENTS_MANAGE_API_URL}/tenants/${tenantId}/agent/${agentId}`;
57
+ const response = await fetch(endpoint, {
58
+ method: "PUT",
59
+ headers: { "Content-Type": "application/json" },
60
+ body: JSON.stringify(agentData)
61
+ });
62
+ if (!response.ok) {
63
+ const errorText = await response.text();
64
+ throw new Error(`HTTP error ${response.status}: ${errorText}`);
65
+ }
66
+ const result = await response.json();
67
+ logger.info({
68
+ tenantId,
69
+ agentId,
70
+ status: response.status
71
+ }, "Full agent updated successfully via API");
72
+ return result.data;
73
+ } catch (error) {
74
+ logger.error({
75
+ tenantId,
76
+ agentId,
77
+ error: error instanceof Error ? error.message : "Unknown error"
78
+ }, "Failed to update full agent via API");
79
+ throw error;
80
+ }
81
+ };
82
+
83
+ //#endregion
84
+ export { createFullAgent, updateFullAgent };
@@ -0,0 +1,77 @@
1
+ import { AgentConversationHistoryConfig, ConversationHistoryConfig, ConversationScopeOptions } from "@inkeep/agents-core";
2
+
3
+ //#region src/data/conversations.d.ts
4
+
5
+ /**
6
+ * Creates default conversation history configuration
7
+ * @param mode - The conversation history mode ('full' | 'scoped' | 'none')
8
+ * @returns Default AgentConversationHistoryConfig
9
+ */
10
+ declare function createDefaultConversationHistoryConfig(mode?: 'full' | 'scoped' | 'none'): AgentConversationHistoryConfig;
11
+ /**
12
+ * Saves the result of an A2A client sendMessage call as a conversation message
13
+ * @param response - The response from a2aClient.sendMessage()
14
+ * @param params - Parameters for saving the message
15
+ * @returns The saved message or null if no text content was found
16
+ */
17
+ declare function saveA2AMessageResponse(response: any,
18
+ // SendMessageResponse type
19
+ params: {
20
+ tenantId: string;
21
+ projectId: string;
22
+ conversationId: string;
23
+ messageType: 'a2a-response' | 'a2a-request';
24
+ visibility: 'internal' | 'external' | 'user-facing';
25
+ fromSubAgentId?: string;
26
+ toSubAgentId?: string;
27
+ fromExternalAgentId?: string;
28
+ toExternalAgentId?: string;
29
+ a2aTaskId?: string;
30
+ a2aSessionId?: string;
31
+ metadata?: Record<string, unknown>;
32
+ }): Promise<any | null>;
33
+ /**
34
+ * Applies filtering based on sub-agent, task, or both criteria
35
+ * Returns the filtered messages array
36
+ */
37
+ declare function getScopedHistory({
38
+ tenantId,
39
+ projectId,
40
+ conversationId,
41
+ filters,
42
+ options
43
+ }: {
44
+ tenantId: string;
45
+ projectId: string;
46
+ conversationId: string;
47
+ filters?: ConversationScopeOptions;
48
+ options?: ConversationHistoryConfig;
49
+ }): Promise<any[]>;
50
+ /**
51
+ * Get user-facing conversation history (for client display)
52
+ */
53
+ declare function getUserFacingHistory(tenantId: string, projectId: string, conversationId: string, limit?: number): Promise<any[]>;
54
+ /**
55
+ * Get full conversation context (for agent processing)
56
+ */
57
+ declare function getFullConversationContext(tenantId: string, projectId: string, conversationId: string, maxTokens?: number): Promise<any[]>;
58
+ /**
59
+ * Get formatted conversation history for a2a
60
+ */
61
+ declare function getFormattedConversationHistory({
62
+ tenantId,
63
+ projectId,
64
+ conversationId,
65
+ currentMessage,
66
+ options,
67
+ filters
68
+ }: {
69
+ tenantId: string;
70
+ projectId: string;
71
+ conversationId: string;
72
+ currentMessage?: string;
73
+ options?: ConversationHistoryConfig;
74
+ filters?: ConversationScopeOptions;
75
+ }): Promise<string>;
76
+ //#endregion
77
+ export { createDefaultConversationHistoryConfig, getFormattedConversationHistory, getFullConversationContext, getScopedHistory, getUserFacingHistory, saveA2AMessageResponse };
@@ -0,0 +1,152 @@
1
+ import dbClient_default from "./db/dbClient.js";
2
+ import { CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, createMessage, generateId, getConversationHistory } from "@inkeep/agents-core";
3
+
4
+ //#region src/data/conversations.ts
5
+ /**
6
+ * Creates default conversation history configuration
7
+ * @param mode - The conversation history mode ('full' | 'scoped' | 'none')
8
+ * @returns Default AgentConversationHistoryConfig
9
+ */
10
+ function createDefaultConversationHistoryConfig(mode = "full") {
11
+ return {
12
+ mode,
13
+ limit: 50,
14
+ includeInternal: true,
15
+ messageTypes: ["chat"],
16
+ maxOutputTokens: CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT
17
+ };
18
+ }
19
+ /**
20
+ * Extracts text content from A2A Message parts array
21
+ */
22
+ function extractA2AMessageText(parts) {
23
+ return parts.filter((part) => part.kind === "text" && part.text).map((part) => part.text).join("");
24
+ }
25
+ /**
26
+ * Saves the result of an A2A client sendMessage call as a conversation message
27
+ * @param response - The response from a2aClient.sendMessage()
28
+ * @param params - Parameters for saving the message
29
+ * @returns The saved message or null if no text content was found
30
+ */
31
+ async function saveA2AMessageResponse(response, params) {
32
+ if (response.error) throw new Error(response.error.message);
33
+ let messageText = "";
34
+ if (response.result.kind === "message") messageText = extractA2AMessageText(response.result.parts);
35
+ else if (response.result.kind === "task") {
36
+ if (response.result.artifacts && response.result.artifacts.length > 0) {
37
+ const firstArtifact = response.result.artifacts[0];
38
+ if (firstArtifact.parts) messageText = extractA2AMessageText(firstArtifact.parts);
39
+ }
40
+ } else if (typeof response.result === "string") messageText = response.result;
41
+ if (!messageText || messageText.trim() === "") return null;
42
+ return await createMessage(dbClient_default)({
43
+ id: generateId(),
44
+ tenantId: params.tenantId,
45
+ projectId: params.projectId,
46
+ conversationId: params.conversationId,
47
+ role: "agent",
48
+ content: { text: messageText },
49
+ visibility: params.visibility,
50
+ messageType: params.messageType,
51
+ fromSubAgentId: params.fromSubAgentId,
52
+ toSubAgentId: params.toSubAgentId,
53
+ fromExternalAgentId: params.fromExternalAgentId,
54
+ toExternalAgentId: params.toExternalAgentId,
55
+ a2aTaskId: params.a2aTaskId,
56
+ a2aSessionId: params.a2aSessionId,
57
+ metadata: params.metadata
58
+ });
59
+ }
60
+ /**
61
+ * Applies filtering based on sub-agent, task, or both criteria
62
+ * Returns the filtered messages array
63
+ */
64
+ async function getScopedHistory({ tenantId, projectId, conversationId, filters, options }) {
65
+ try {
66
+ const messages = await getConversationHistory(dbClient_default)({
67
+ scopes: {
68
+ tenantId,
69
+ projectId
70
+ },
71
+ conversationId,
72
+ options
73
+ });
74
+ if (!filters || !filters.subAgentId && !filters.taskId) return messages;
75
+ return messages.filter((msg) => {
76
+ if (msg.role === "user") return true;
77
+ let matchesAgent = true;
78
+ let matchesTask = true;
79
+ if (filters.subAgentId) matchesAgent = msg.role === "agent" && msg.visibility === "user-facing" || msg.toSubAgentId === filters.subAgentId || msg.fromSubAgentId === filters.subAgentId;
80
+ if (filters.taskId) matchesTask = msg.taskId === filters.taskId || msg.a2aTaskId === filters.taskId;
81
+ if (filters.subAgentId && filters.taskId) return matchesAgent && matchesTask;
82
+ if (filters.subAgentId) return matchesAgent;
83
+ if (filters.taskId) return matchesTask;
84
+ return false;
85
+ });
86
+ } catch (error) {
87
+ console.error("Failed to fetch scoped messages:", error);
88
+ return [];
89
+ }
90
+ }
91
+ /**
92
+ * Get user-facing conversation history (for client display)
93
+ */
94
+ async function getUserFacingHistory(tenantId, projectId, conversationId, limit = 50) {
95
+ return await getConversationHistory(dbClient_default)({
96
+ scopes: {
97
+ tenantId,
98
+ projectId
99
+ },
100
+ conversationId,
101
+ options: {
102
+ limit,
103
+ includeInternal: false,
104
+ messageTypes: ["chat"]
105
+ }
106
+ });
107
+ }
108
+ /**
109
+ * Get full conversation context (for agent processing)
110
+ */
111
+ async function getFullConversationContext(tenantId, projectId, conversationId, maxTokens) {
112
+ return await getConversationHistory(dbClient_default)({
113
+ scopes: {
114
+ tenantId,
115
+ projectId
116
+ },
117
+ conversationId,
118
+ options: {
119
+ limit: 100,
120
+ includeInternal: true,
121
+ maxOutputTokens: maxTokens
122
+ }
123
+ });
124
+ }
125
+ /**
126
+ * Get formatted conversation history for a2a
127
+ */
128
+ async function getFormattedConversationHistory({ tenantId, projectId, conversationId, currentMessage, options, filters }) {
129
+ const conversationHistory = await getScopedHistory({
130
+ tenantId,
131
+ projectId,
132
+ conversationId,
133
+ filters,
134
+ options: options ?? { includeInternal: true }
135
+ });
136
+ let messagesToFormat = conversationHistory;
137
+ if (currentMessage && conversationHistory.length > 0) {
138
+ if (conversationHistory[conversationHistory.length - 1].content.text === currentMessage) messagesToFormat = conversationHistory.slice(0, -1);
139
+ }
140
+ if (!messagesToFormat.length) return "";
141
+ return `<conversation_history>\n${messagesToFormat.map((msg) => {
142
+ let roleLabel;
143
+ if (msg.role === "user") roleLabel = "user";
144
+ else if (msg.role === "agent" && (msg.messageType === "a2a-request" || msg.messageType === "a2a-response")) roleLabel = `${msg.fromSubAgentId || msg.fromExternalAgentId || "unknown"} to ${msg.toSubAgentId || msg.toExternalAgentId || "unknown"}`;
145
+ else if (msg.role === "agent" && msg.messageType === "chat") roleLabel = `${msg.fromSubAgentId || "unknown"} to User`;
146
+ else roleLabel = msg.role || "system";
147
+ return `${roleLabel}: """${msg.content.text}"""`;
148
+ }).join("\n")}\n</conversation_history>\n`;
149
+ }
150
+
151
+ //#endregion
152
+ export { createDefaultConversationHistoryConfig, getFormattedConversationHistory, getFullConversationContext, getScopedHistory, getUserFacingHistory, saveA2AMessageResponse };
@@ -0,0 +1,6 @@
1
+ import { DatabaseClient } from "@inkeep/agents-core";
2
+
3
+ //#region src/data/db/dbClient.d.ts
4
+ declare let dbClient: DatabaseClient;
5
+ //#endregion
6
+ export { dbClient as default };
@@ -0,0 +1,17 @@
1
+ import { env } from "../../env.js";
2
+ import { createDatabaseClient } from "@inkeep/agents-core";
3
+ import { PGlite } from "@electric-sql/pglite";
4
+ import * as schema from "@inkeep/agents-core/db/schema";
5
+ import { drizzle } from "drizzle-orm/pglite";
6
+
7
+ //#region src/data/db/dbClient.ts
8
+ let dbClient;
9
+ if (env.ENVIRONMENT === "test") dbClient = drizzle({
10
+ client: new PGlite(),
11
+ schema
12
+ });
13
+ else dbClient = createDatabaseClient({ connectionString: env.DATABASE_URL });
14
+ var dbClient_default = dbClient;
15
+
16
+ //#endregion
17
+ export { dbClient_default as default };
package/dist/env.d.ts ADDED
@@ -0,0 +1,61 @@
1
+ import { z } from "@hono/zod-openapi";
2
+
3
+ //#region src/env.d.ts
4
+ declare const envSchema: z.ZodObject<{
5
+ NODE_ENV: z.ZodOptional<z.ZodEnum<{
6
+ development: "development";
7
+ production: "production";
8
+ test: "test";
9
+ }>>;
10
+ ENVIRONMENT: z.ZodOptional<z.ZodEnum<{
11
+ development: "development";
12
+ production: "production";
13
+ test: "test";
14
+ pentest: "pentest";
15
+ }>>;
16
+ INKEEP_AGENTS_MANAGE_API_URL: z.ZodDefault<z.ZodOptional<z.ZodString>>;
17
+ INKEEP_AGENTS_MANAGE_UI_URL: z.ZodDefault<z.ZodOptional<z.ZodString>>;
18
+ DATABASE_URL: z.ZodOptional<z.ZodString>;
19
+ LOG_LEVEL: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
20
+ trace: "trace";
21
+ debug: "debug";
22
+ info: "info";
23
+ warn: "warn";
24
+ error: "error";
25
+ }>>>;
26
+ NANGO_SERVER_URL: z.ZodDefault<z.ZodOptional<z.ZodString>>;
27
+ NANGO_SECRET_KEY: z.ZodOptional<z.ZodString>;
28
+ INKEEP_AGENTS_MANAGE_API_BYPASS_SECRET: z.ZodOptional<z.ZodString>;
29
+ BETTER_AUTH_SECRET: z.ZodOptional<z.ZodString>;
30
+ TENANT_ID: z.ZodDefault<z.ZodOptional<z.ZodString>>;
31
+ INKEEP_AGENTS_MANAGE_UI_USERNAME: z.ZodOptional<z.ZodString>;
32
+ INKEEP_AGENTS_MANAGE_UI_PASSWORD: z.ZodOptional<z.ZodString>;
33
+ DISABLE_AUTH: z.ZodPipe<z.ZodDefault<z.ZodOptional<z.ZodString>>, z.ZodTransform<boolean, string>>;
34
+ INKEEP_AGENTS_TEMP_JWT_PRIVATE_KEY: z.ZodOptional<z.ZodString>;
35
+ SIGNOZ_URL: z.ZodOptional<z.ZodString>;
36
+ SIGNOZ_API_KEY: z.ZodOptional<z.ZodString>;
37
+ PUBLIC_SIGNOZ_URL: z.ZodOptional<z.ZodString>;
38
+ }, z.core.$strip>;
39
+ declare const env: {
40
+ INKEEP_AGENTS_MANAGE_API_URL: string;
41
+ INKEEP_AGENTS_MANAGE_UI_URL: string;
42
+ LOG_LEVEL: "trace" | "debug" | "info" | "warn" | "error";
43
+ NANGO_SERVER_URL: string;
44
+ TENANT_ID: string;
45
+ DISABLE_AUTH: boolean;
46
+ NODE_ENV?: "development" | "production" | "test" | undefined;
47
+ ENVIRONMENT?: "development" | "production" | "test" | "pentest" | undefined;
48
+ DATABASE_URL?: string | undefined;
49
+ NANGO_SECRET_KEY?: string | undefined;
50
+ INKEEP_AGENTS_MANAGE_API_BYPASS_SECRET?: string | undefined;
51
+ BETTER_AUTH_SECRET?: string | undefined;
52
+ INKEEP_AGENTS_MANAGE_UI_USERNAME?: string | undefined;
53
+ INKEEP_AGENTS_MANAGE_UI_PASSWORD?: string | undefined;
54
+ INKEEP_AGENTS_TEMP_JWT_PRIVATE_KEY?: string | undefined;
55
+ SIGNOZ_URL?: string | undefined;
56
+ SIGNOZ_API_KEY?: string | undefined;
57
+ PUBLIC_SIGNOZ_URL?: string | undefined;
58
+ };
59
+ type Env = z.infer<typeof envSchema>;
60
+ //#endregion
61
+ export { Env, env };
package/dist/env.js ADDED
@@ -0,0 +1,55 @@
1
+ import { z } from "@hono/zod-openapi";
2
+ import { loadEnvironmentFiles } from "@inkeep/agents-core";
3
+
4
+ //#region src/env.ts
5
+ loadEnvironmentFiles();
6
+ const envSchema = z.object({
7
+ NODE_ENV: z.enum([
8
+ "development",
9
+ "production",
10
+ "test"
11
+ ]).optional(),
12
+ ENVIRONMENT: z.enum([
13
+ "development",
14
+ "production",
15
+ "pentest",
16
+ "test"
17
+ ]).optional(),
18
+ INKEEP_AGENTS_MANAGE_API_URL: z.string().optional().default("http://localhost:3002"),
19
+ INKEEP_AGENTS_MANAGE_UI_URL: z.string().optional().default("http://localhost:3000"),
20
+ DATABASE_URL: z.string().optional(),
21
+ LOG_LEVEL: z.enum([
22
+ "trace",
23
+ "debug",
24
+ "info",
25
+ "warn",
26
+ "error"
27
+ ]).optional().default("debug"),
28
+ NANGO_SERVER_URL: z.string().optional().default("https://api.nango.dev"),
29
+ NANGO_SECRET_KEY: z.string().optional(),
30
+ INKEEP_AGENTS_MANAGE_API_BYPASS_SECRET: z.string().optional(),
31
+ BETTER_AUTH_SECRET: z.string().optional(),
32
+ TENANT_ID: z.string().optional().default("default"),
33
+ INKEEP_AGENTS_MANAGE_UI_USERNAME: z.string().optional().refine((val) => !val || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val), { message: "Invalid email address" }),
34
+ INKEEP_AGENTS_MANAGE_UI_PASSWORD: z.string().optional().refine((val) => !val || val.length >= 8, { message: "Password must be at least 8 characters" }),
35
+ DISABLE_AUTH: z.string().optional().default("false").transform((val) => val === "true"),
36
+ INKEEP_AGENTS_TEMP_JWT_PRIVATE_KEY: z.string().optional(),
37
+ SIGNOZ_URL: z.string().optional(),
38
+ SIGNOZ_API_KEY: z.string().optional(),
39
+ PUBLIC_SIGNOZ_URL: z.string().optional()
40
+ });
41
+ const parseEnv = () => {
42
+ try {
43
+ return envSchema.parse(process.env);
44
+ } catch (error) {
45
+ if (error instanceof z.ZodError) {
46
+ const missingVars = error.issues.map((issue) => issue.path.join("."));
47
+ throw new Error(`❌ Invalid environment variables: ${missingVars.join(", ")}\n${error.message}`);
48
+ }
49
+ throw error;
50
+ }
51
+ };
52
+ const env = parseEnv();
53
+
54
+ //#endregion
55
+ export { env };
package/dist/factory.d.ts CHANGED
@@ -1,2 +1,17 @@
1
- import { a as createOIDCProvider, i as createAuth0Provider, n as UserAuthConfig, o as initializeDefaultUser, r as createManagementApp, s as createManagementHono, t as SSOProviderConfig } from "./factory2.js";
2
- export { SSOProviderConfig, UserAuthConfig, createAuth0Provider, createManagementApp, createManagementHono, createOIDCProvider, initializeDefaultUser };
1
+ import { createManagementHono } from "./create-app.js";
2
+ import { initializeDefaultUser } from "./initialization.js";
3
+ import { createAuth0Provider, createOIDCProvider } from "./sso-helpers.js";
4
+ import * as hono1 from "hono";
5
+ import { CredentialStore, ServerConfig } from "@inkeep/agents-core";
6
+ import { SSOProviderConfig, UserAuthConfig } from "@inkeep/agents-core/auth";
7
+ import * as hono_types1 from "hono/types";
8
+
9
+ //#region src/factory.d.ts
10
+ declare function createManagementApp(config?: {
11
+ serverConfig?: ServerConfig;
12
+ credentialStores?: CredentialStore[];
13
+ auth?: UserAuthConfig;
14
+ skipInitialization?: boolean;
15
+ }): hono1.Hono<hono_types1.BlankEnv, hono_types1.BlankSchema, "/">;
16
+ //#endregion
17
+ export { type SSOProviderConfig, type UserAuthConfig, createAuth0Provider, createManagementApp, createManagementHono, createOIDCProvider, initializeDefaultUser };