@inkeep/agents-run-api 0.0.0-dev-20260119170007 → 0.0.0-dev-20260120193424
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/agents/Agent.js +7 -1
- package/dist/create-app.js +9 -4
- package/dist/data/db/dbClient.d.ts +2 -2
- package/dist/env.d.ts +2 -0
- package/dist/env.js +1 -0
- package/dist/middleware/api-key-auth.d.ts +13 -4
- package/dist/middleware/api-key-auth.js +15 -3
- package/dist/middleware/index.d.ts +3 -3
- package/dist/middleware/index.js +3 -3
- package/dist/middleware/projectConfig.d.ts +12 -8
- package/dist/middleware/projectConfig.js +16 -4
- package/dist/routes/webhooks.d.ts +14 -0
- package/dist/routes/webhooks.js +397 -0
- package/dist/utils/token-estimator.d.ts +2 -2
- package/package.json +2 -2
package/dist/agents/Agent.js
CHANGED
|
@@ -1472,9 +1472,15 @@ ${typeof cleanResult === "string" ? cleanResult : JSON.stringify(cleanResult, nu
|
|
|
1472
1472
|
}
|
|
1473
1473
|
}
|
|
1474
1474
|
async generate(userMessage, runtimeContext) {
|
|
1475
|
+
const conversationIdForSpan = runtimeContext?.metadata?.conversationId;
|
|
1475
1476
|
return tracer.startActiveSpan("agent.generate", { attributes: {
|
|
1476
1477
|
"subAgent.id": this.config.id,
|
|
1477
|
-
"subAgent.name": this.config.name
|
|
1478
|
+
"subAgent.name": this.config.name,
|
|
1479
|
+
"tenant.id": this.config.tenantId,
|
|
1480
|
+
"project.id": this.config.projectId,
|
|
1481
|
+
"agent.id": this.config.agentId,
|
|
1482
|
+
"agent.name": this.config.name,
|
|
1483
|
+
...conversationIdForSpan ? { "conversation.id": conversationIdForSpan } : {}
|
|
1478
1484
|
} }, async (span) => {
|
|
1479
1485
|
const { contextId, taskId, streamRequestId, sessionId } = this.setupGenerationContext(runtimeContext);
|
|
1480
1486
|
try {
|
package/dist/create-app.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { getLogger as getLogger$1 } from "./logger.js";
|
|
2
2
|
import { flushBatchProcessor } from "./instrumentation.js";
|
|
3
|
-
import { apiKeyAuth } from "./middleware/api-key-auth.js";
|
|
4
|
-
import { projectConfigMiddleware } from "./middleware/projectConfig.js";
|
|
3
|
+
import { apiKeyAuth, apiKeyAuthExcept } from "./middleware/api-key-auth.js";
|
|
4
|
+
import { projectConfigMiddleware, projectConfigMiddlewareExcept } from "./middleware/projectConfig.js";
|
|
5
5
|
import { setupOpenAPIRoutes } from "./openapi.js";
|
|
6
6
|
import agents_default from "./routes/agents.js";
|
|
7
7
|
import chat_default from "./routes/chat.js";
|
|
8
8
|
import chatDataStream_default from "./routes/chatDataStream.js";
|
|
9
9
|
import mcp_default from "./routes/mcp.js";
|
|
10
|
+
import webhooks_default from "./routes/webhooks.js";
|
|
10
11
|
import { otel } from "@hono/otel";
|
|
11
12
|
import { OpenAPIHono, createRoute } from "@hono/zod-openapi";
|
|
12
13
|
import { handleApiError } from "@inkeep/agents-core";
|
|
@@ -122,11 +123,14 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
122
123
|
exposeHeaders: ["Content-Length"],
|
|
123
124
|
maxAge: 86400
|
|
124
125
|
}));
|
|
125
|
-
|
|
126
|
+
const isWebhookRoute = (path) => {
|
|
127
|
+
return path.includes("/triggers/") && !path.endsWith("/triggers") && !path.endsWith("/triggers/");
|
|
128
|
+
};
|
|
129
|
+
app.use("/tenants/*", apiKeyAuthExcept(isWebhookRoute));
|
|
126
130
|
app.use("/agents/*", apiKeyAuth());
|
|
127
131
|
app.use("/v1/*", apiKeyAuth());
|
|
128
132
|
app.use("/api/*", apiKeyAuth());
|
|
129
|
-
app.use("/tenants/*",
|
|
133
|
+
app.use("/tenants/*", projectConfigMiddlewareExcept(isWebhookRoute));
|
|
130
134
|
app.use("/agents/*", projectConfigMiddleware);
|
|
131
135
|
app.use("/v1/*", projectConfigMiddleware);
|
|
132
136
|
app.use("/api/*", projectConfigMiddleware);
|
|
@@ -174,6 +178,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
|
|
|
174
178
|
app.route("/api", chatDataStream_default);
|
|
175
179
|
app.route("/v1/mcp", mcp_default);
|
|
176
180
|
app.route("/agents", agents_default);
|
|
181
|
+
app.route("/", webhooks_default);
|
|
177
182
|
setupOpenAPIRoutes(app);
|
|
178
183
|
app.use("/tenants/*", async (_c, next) => {
|
|
179
184
|
await next();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as _inkeep_agents_core2 from "@inkeep/agents-core";
|
|
2
2
|
|
|
3
3
|
//#region src/data/db/dbClient.d.ts
|
|
4
|
-
declare const dbClient:
|
|
4
|
+
declare const dbClient: _inkeep_agents_core2.AgentsRunDatabaseClient;
|
|
5
5
|
//#endregion
|
|
6
6
|
export { dbClient as default };
|
package/dist/env.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ declare const envSchema: z.ZodObject<{
|
|
|
17
17
|
INKEEP_AGENTS_MANAGE_API_URL: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
18
18
|
INKEEP_AGENTS_EVAL_API_URL: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
19
19
|
INKEEP_AGENTS_RUN_DATABASE_URL: z.ZodOptional<z.ZodString>;
|
|
20
|
+
INKEEP_AGENTS_MANAGE_DATABASE_URL: z.ZodOptional<z.ZodString>;
|
|
20
21
|
AGENTS_MANAGE_UI_URL: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
21
22
|
LOG_LEVEL: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
|
|
22
23
|
trace: "trace";
|
|
@@ -49,6 +50,7 @@ declare const env: {
|
|
|
49
50
|
OTEL_BSP_MAX_EXPORT_BATCH_SIZE: number;
|
|
50
51
|
NODE_ENV?: "development" | "production" | "test" | undefined;
|
|
51
52
|
INKEEP_AGENTS_RUN_DATABASE_URL?: string | undefined;
|
|
53
|
+
INKEEP_AGENTS_MANAGE_DATABASE_URL?: string | undefined;
|
|
52
54
|
NANGO_SECRET_KEY?: string | undefined;
|
|
53
55
|
OPENAI_API_KEY?: string | undefined;
|
|
54
56
|
GOOGLE_GENERATIVE_AI_API_KEY?: string | undefined;
|
package/dist/env.js
CHANGED
|
@@ -19,6 +19,7 @@ const envSchema = z.object({
|
|
|
19
19
|
INKEEP_AGENTS_MANAGE_API_URL: z.string().optional().default("http://localhost:3002"),
|
|
20
20
|
INKEEP_AGENTS_EVAL_API_URL: z.string().optional().default("http://localhost:3005"),
|
|
21
21
|
INKEEP_AGENTS_RUN_DATABASE_URL: z.string().optional(),
|
|
22
|
+
INKEEP_AGENTS_MANAGE_DATABASE_URL: z.string().optional(),
|
|
22
23
|
AGENTS_MANAGE_UI_URL: z.string().optional().default("http://localhost:3000"),
|
|
23
24
|
LOG_LEVEL: z.enum([
|
|
24
25
|
"trace",
|
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
import { BaseExecutionContext } from "@inkeep/agents-core";
|
|
2
|
-
import * as
|
|
2
|
+
import * as hono1 from "hono";
|
|
3
3
|
|
|
4
4
|
//#region src/middleware/api-key-auth.d.ts
|
|
5
|
-
declare const apiKeyAuth: () =>
|
|
5
|
+
declare const apiKeyAuth: () => hono1.MiddlewareHandler<{
|
|
6
|
+
Variables: {
|
|
7
|
+
executionContext: BaseExecutionContext;
|
|
8
|
+
};
|
|
9
|
+
}, string, {}, Response>;
|
|
10
|
+
/**
|
|
11
|
+
* Creates a middleware that applies API key authentication except for specified route patterns
|
|
12
|
+
* @param skipRouteCheck - Function that returns true if the route should skip authentication
|
|
13
|
+
*/
|
|
14
|
+
declare const apiKeyAuthExcept: (skipRouteCheck: (path: string) => boolean) => hono1.MiddlewareHandler<{
|
|
6
15
|
Variables: {
|
|
7
16
|
executionContext: BaseExecutionContext;
|
|
8
17
|
};
|
|
@@ -11,10 +20,10 @@ declare const apiKeyAuth: () => hono0.MiddlewareHandler<{
|
|
|
11
20
|
* Helper middleware for endpoints that optionally support API key authentication
|
|
12
21
|
* If no auth header is present, it continues without setting the executionContext
|
|
13
22
|
*/
|
|
14
|
-
declare const optionalAuth: () =>
|
|
23
|
+
declare const optionalAuth: () => hono1.MiddlewareHandler<{
|
|
15
24
|
Variables: {
|
|
16
25
|
executionContext?: BaseExecutionContext;
|
|
17
26
|
};
|
|
18
27
|
}, string, {}, Response>;
|
|
19
28
|
//#endregion
|
|
20
|
-
export { apiKeyAuth, optionalAuth };
|
|
29
|
+
export { apiKeyAuth, apiKeyAuthExcept, optionalAuth };
|
|
@@ -184,7 +184,10 @@ async function authenticateRequest(reqData) {
|
|
|
184
184
|
failureMessage: teamAttempt.failureMessage
|
|
185
185
|
};
|
|
186
186
|
}
|
|
187
|
-
|
|
187
|
+
/**
|
|
188
|
+
* Core authentication handler that can be reused across middleware
|
|
189
|
+
*/
|
|
190
|
+
async function apiKeyAuthHandler(c, next) {
|
|
188
191
|
if (c.req.method === "OPTIONS") {
|
|
189
192
|
await next();
|
|
190
193
|
return;
|
|
@@ -223,6 +226,15 @@ const apiKeyAuth = () => createMiddleware(async (c, next) => {
|
|
|
223
226
|
}, "API key authenticated successfully");
|
|
224
227
|
c.set("executionContext", buildExecutionContext(attempt.authResult, reqData));
|
|
225
228
|
await next();
|
|
229
|
+
}
|
|
230
|
+
const apiKeyAuth = () => createMiddleware(apiKeyAuthHandler);
|
|
231
|
+
/**
|
|
232
|
+
* Creates a middleware that applies API key authentication except for specified route patterns
|
|
233
|
+
* @param skipRouteCheck - Function that returns true if the route should skip authentication
|
|
234
|
+
*/
|
|
235
|
+
const apiKeyAuthExcept = (skipRouteCheck) => createMiddleware(async (c, next) => {
|
|
236
|
+
if (skipRouteCheck(c.req.path)) return next();
|
|
237
|
+
return apiKeyAuthHandler(c, next);
|
|
226
238
|
});
|
|
227
239
|
/**
|
|
228
240
|
* Helper middleware for endpoints that optionally support API key authentication
|
|
@@ -234,8 +246,8 @@ const optionalAuth = () => createMiddleware(async (c, next) => {
|
|
|
234
246
|
await next();
|
|
235
247
|
return;
|
|
236
248
|
}
|
|
237
|
-
return
|
|
249
|
+
return apiKeyAuthHandler(c, next);
|
|
238
250
|
});
|
|
239
251
|
|
|
240
252
|
//#endregion
|
|
241
|
-
export { apiKeyAuth, optionalAuth };
|
|
253
|
+
export { apiKeyAuth, apiKeyAuthExcept, optionalAuth };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { apiKeyAuth, optionalAuth } from "./api-key-auth.js";
|
|
2
|
-
import { projectConfigMiddleware } from "./projectConfig.js";
|
|
3
|
-
export { apiKeyAuth, optionalAuth, projectConfigMiddleware };
|
|
1
|
+
import { apiKeyAuth, apiKeyAuthExcept, optionalAuth } from "./api-key-auth.js";
|
|
2
|
+
import { projectConfigMiddleware, projectConfigMiddlewareExcept } from "./projectConfig.js";
|
|
3
|
+
export { apiKeyAuth, apiKeyAuthExcept, optionalAuth, projectConfigMiddleware, projectConfigMiddlewareExcept };
|
package/dist/middleware/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { apiKeyAuth, optionalAuth } from "./api-key-auth.js";
|
|
2
|
-
import { projectConfigMiddleware } from "./projectConfig.js";
|
|
1
|
+
import { apiKeyAuth, apiKeyAuthExcept, optionalAuth } from "./api-key-auth.js";
|
|
2
|
+
import { projectConfigMiddleware, projectConfigMiddlewareExcept } from "./projectConfig.js";
|
|
3
3
|
|
|
4
|
-
export { apiKeyAuth, optionalAuth, projectConfigMiddleware };
|
|
4
|
+
export { apiKeyAuth, apiKeyAuthExcept, optionalAuth, projectConfigMiddleware, projectConfigMiddlewareExcept };
|
|
@@ -1,19 +1,23 @@
|
|
|
1
1
|
import { FullExecutionContext } from "@inkeep/agents-core";
|
|
2
|
-
import * as
|
|
2
|
+
import * as hono0 from "hono";
|
|
3
3
|
|
|
4
4
|
//#region src/middleware/projectConfig.d.ts
|
|
5
|
-
|
|
6
5
|
/**
|
|
7
6
|
* Middleware that fetches the full project definition from the Management API
|
|
8
|
-
* and adds it to the Hono context for use in route handlers.
|
|
9
|
-
*
|
|
10
|
-
* This middleware should be applied after authentication middleware since it
|
|
11
|
-
* requires the execution context to be set.
|
|
12
7
|
*/
|
|
13
|
-
declare const projectConfigMiddleware:
|
|
8
|
+
declare const projectConfigMiddleware: hono0.MiddlewareHandler<{
|
|
9
|
+
Variables: {
|
|
10
|
+
executionContext: FullExecutionContext;
|
|
11
|
+
};
|
|
12
|
+
}, string, {}, Response>;
|
|
13
|
+
/**
|
|
14
|
+
* Creates a middleware that applies project config fetching except for specified route patterns
|
|
15
|
+
* @param skipRouteCheck - Function that returns true if the route should skip the middleware
|
|
16
|
+
*/
|
|
17
|
+
declare const projectConfigMiddlewareExcept: (skipRouteCheck: (path: string) => boolean) => hono0.MiddlewareHandler<{
|
|
14
18
|
Variables: {
|
|
15
19
|
executionContext: FullExecutionContext;
|
|
16
20
|
};
|
|
17
21
|
}, string, {}, Response>;
|
|
18
22
|
//#endregion
|
|
19
|
-
export { projectConfigMiddleware };
|
|
23
|
+
export { projectConfigMiddleware, projectConfigMiddlewareExcept };
|
|
@@ -6,13 +6,13 @@ import { createMiddleware } from "hono/factory";
|
|
|
6
6
|
//#region src/middleware/projectConfig.ts
|
|
7
7
|
const logger = getLogger$1("projectConfigMiddleware");
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
9
|
+
* Core handler that fetches the full project definition from the Management API
|
|
10
10
|
* and adds it to the Hono context for use in route handlers.
|
|
11
11
|
*
|
|
12
|
-
* This
|
|
12
|
+
* This handler should be applied after authentication middleware since it
|
|
13
13
|
* requires the execution context to be set.
|
|
14
14
|
*/
|
|
15
|
-
|
|
15
|
+
async function projectConfigHandler(c, next) {
|
|
16
16
|
const executionContext = c.get("executionContext");
|
|
17
17
|
const { tenantId, projectId, ref } = executionContext;
|
|
18
18
|
logger.debug({
|
|
@@ -74,7 +74,19 @@ const projectConfigMiddleware = createMiddleware(async (c, next) => {
|
|
|
74
74
|
message: "Failed to load project configuration"
|
|
75
75
|
}, 500);
|
|
76
76
|
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Middleware that fetches the full project definition from the Management API
|
|
80
|
+
*/
|
|
81
|
+
const projectConfigMiddleware = createMiddleware(projectConfigHandler);
|
|
82
|
+
/**
|
|
83
|
+
* Creates a middleware that applies project config fetching except for specified route patterns
|
|
84
|
+
* @param skipRouteCheck - Function that returns true if the route should skip the middleware
|
|
85
|
+
*/
|
|
86
|
+
const projectConfigMiddlewareExcept = (skipRouteCheck) => createMiddleware(async (c, next) => {
|
|
87
|
+
if (skipRouteCheck(c.req.path)) return next();
|
|
88
|
+
return projectConfigHandler(c, next);
|
|
77
89
|
});
|
|
78
90
|
|
|
79
91
|
//#endregion
|
|
80
|
-
export { projectConfigMiddleware };
|
|
92
|
+
export { projectConfigMiddleware, projectConfigMiddlewareExcept };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import { CredentialStoreRegistry, FullExecutionContext } from "@inkeep/agents-core";
|
|
3
|
+
|
|
4
|
+
//#region src/routes/webhooks.d.ts
|
|
5
|
+
type AppVariables = {
|
|
6
|
+
credentialStores: CredentialStoreRegistry;
|
|
7
|
+
executionContext: FullExecutionContext;
|
|
8
|
+
requestBody?: unknown;
|
|
9
|
+
};
|
|
10
|
+
declare const app: OpenAPIHono<{
|
|
11
|
+
Variables: AppVariables;
|
|
12
|
+
}, {}, "/">;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { app as default };
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { env } from "../env.js";
|
|
2
|
+
import { getLogger as getLogger$1 } from "../logger.js";
|
|
3
|
+
import dbClient_default from "../data/db/dbClient.js";
|
|
4
|
+
import { createSSEStreamHelper } from "../utils/stream-helpers.js";
|
|
5
|
+
import { ExecutionHandler } from "../handlers/executionHandler.js";
|
|
6
|
+
import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
|
|
7
|
+
import { JsonTransformer, createAgentsManageDatabaseClient, createApiError, createMessage, createOrGetConversation, createTriggerInvocation, generateId, getConversationId, getFullProjectWithRelationIds, getProjectBranchName, getTriggerById, interpolateTemplate, setActiveAgentForConversation, updateTriggerInvocationStatus, verifySigningSecret, verifyTriggerAuth } from "@inkeep/agents-core";
|
|
8
|
+
import { context, propagation, trace } from "@opentelemetry/api";
|
|
9
|
+
import Ajv from "ajv";
|
|
10
|
+
|
|
11
|
+
//#region src/routes/webhooks.ts
|
|
12
|
+
const app = new OpenAPIHono();
|
|
13
|
+
const logger = getLogger$1("webhooks");
|
|
14
|
+
const ajv = new Ajv({ allErrors: true });
|
|
15
|
+
const manageDbClient = createAgentsManageDatabaseClient({ connectionString: env.INKEEP_AGENTS_MANAGE_DATABASE_URL });
|
|
16
|
+
/**
|
|
17
|
+
* Webhook endpoint for trigger invocation
|
|
18
|
+
* POST /tenants/:tenantId/projects/:projectId/agents/:agentId/triggers/:triggerId
|
|
19
|
+
*/
|
|
20
|
+
const triggerWebhookRoute = createRoute({
|
|
21
|
+
method: "post",
|
|
22
|
+
path: "/tenants/:tenantId/projects/:projectId/agents/:agentId/triggers/:triggerId",
|
|
23
|
+
tags: ["webhooks"],
|
|
24
|
+
summary: "Invoke agent via trigger webhook",
|
|
25
|
+
description: "Webhook endpoint for third-party services to invoke an agent via a configured trigger",
|
|
26
|
+
request: {
|
|
27
|
+
params: z.object({
|
|
28
|
+
tenantId: z.string().describe("Tenant ID"),
|
|
29
|
+
projectId: z.string().describe("Project ID"),
|
|
30
|
+
agentId: z.string().describe("Agent ID"),
|
|
31
|
+
triggerId: z.string().describe("Trigger ID")
|
|
32
|
+
}),
|
|
33
|
+
body: { content: { "application/json": { schema: z.record(z.string(), z.unknown()).describe("Webhook payload") } } }
|
|
34
|
+
},
|
|
35
|
+
responses: {
|
|
36
|
+
202: {
|
|
37
|
+
description: "Webhook accepted and trigger invoked",
|
|
38
|
+
content: { "application/json": { schema: z.object({
|
|
39
|
+
success: z.boolean(),
|
|
40
|
+
invocationId: z.string()
|
|
41
|
+
}) } }
|
|
42
|
+
},
|
|
43
|
+
400: {
|
|
44
|
+
description: "Invalid request payload",
|
|
45
|
+
content: { "application/json": { schema: z.object({
|
|
46
|
+
error: z.string(),
|
|
47
|
+
validationErrors: z.array(z.string()).optional()
|
|
48
|
+
}) } }
|
|
49
|
+
},
|
|
50
|
+
401: {
|
|
51
|
+
description: "Missing authentication credentials",
|
|
52
|
+
content: { "application/json": { schema: z.object({ error: z.string() }) } }
|
|
53
|
+
},
|
|
54
|
+
403: {
|
|
55
|
+
description: "Invalid authentication credentials or signature",
|
|
56
|
+
content: { "application/json": { schema: z.object({ error: z.string() }) } }
|
|
57
|
+
},
|
|
58
|
+
404: {
|
|
59
|
+
description: "Trigger not found or disabled",
|
|
60
|
+
content: { "application/json": { schema: z.object({ error: z.string() }) } }
|
|
61
|
+
},
|
|
62
|
+
422: {
|
|
63
|
+
description: "Payload transformation failed",
|
|
64
|
+
content: { "application/json": { schema: z.object({ error: z.string() }) } }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
app.openapi(triggerWebhookRoute, async (c) => {
|
|
69
|
+
const { tenantId, projectId, agentId, triggerId } = c.req.param();
|
|
70
|
+
logger.info({
|
|
71
|
+
tenantId,
|
|
72
|
+
projectId,
|
|
73
|
+
agentId,
|
|
74
|
+
triggerId
|
|
75
|
+
}, "Processing trigger webhook");
|
|
76
|
+
try {
|
|
77
|
+
const trigger = await getTriggerById(manageDbClient)({
|
|
78
|
+
scopes: {
|
|
79
|
+
tenantId,
|
|
80
|
+
projectId,
|
|
81
|
+
agentId
|
|
82
|
+
},
|
|
83
|
+
triggerId
|
|
84
|
+
});
|
|
85
|
+
if (!trigger) throw createApiError({
|
|
86
|
+
code: "not_found",
|
|
87
|
+
message: `Trigger ${triggerId} not found`
|
|
88
|
+
});
|
|
89
|
+
if (!trigger.enabled) throw createApiError({
|
|
90
|
+
code: "not_found",
|
|
91
|
+
message: "Trigger is disabled"
|
|
92
|
+
});
|
|
93
|
+
const bodyText = await c.req.text();
|
|
94
|
+
const payload = bodyText ? JSON.parse(bodyText) : {};
|
|
95
|
+
if (trigger.authentication) {
|
|
96
|
+
const authResult = verifyTriggerAuth(c, trigger.authentication);
|
|
97
|
+
if (!authResult.success) {
|
|
98
|
+
if (authResult.status === 401) return c.json({ error: authResult.message || "Unauthorized" }, 401);
|
|
99
|
+
return c.json({ error: authResult.message || "Forbidden" }, 403);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (trigger.signingSecret) {
|
|
103
|
+
const signatureResult = verifySigningSecret(c, trigger.signingSecret, bodyText);
|
|
104
|
+
if (!signatureResult.success) return c.json({ error: signatureResult.message || "Invalid signature" }, 403);
|
|
105
|
+
}
|
|
106
|
+
if (trigger.inputSchema) {
|
|
107
|
+
const validate = ajv.compile(trigger.inputSchema);
|
|
108
|
+
if (!validate(payload)) {
|
|
109
|
+
const errors = validate.errors?.map((err) => `${err.instancePath} ${err.message}`);
|
|
110
|
+
return c.json({
|
|
111
|
+
error: "Payload validation failed",
|
|
112
|
+
validationErrors: errors
|
|
113
|
+
}, 400);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
let transformedPayload = payload;
|
|
117
|
+
if (trigger.outputTransform) try {
|
|
118
|
+
transformedPayload = await JsonTransformer.transformWithConfig(payload, trigger.outputTransform);
|
|
119
|
+
logger.debug({
|
|
120
|
+
triggerId,
|
|
121
|
+
tenantId,
|
|
122
|
+
projectId
|
|
123
|
+
}, "Payload transformation successful");
|
|
124
|
+
} catch (error) {
|
|
125
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
126
|
+
logger.error({
|
|
127
|
+
triggerId,
|
|
128
|
+
tenantId,
|
|
129
|
+
projectId,
|
|
130
|
+
error: errorMessage
|
|
131
|
+
}, "Payload transformation failed");
|
|
132
|
+
return c.json({ error: `Payload transformation failed: ${errorMessage}` }, 422);
|
|
133
|
+
}
|
|
134
|
+
const interpolatedMessage = trigger.messageTemplate ? interpolateTemplate(trigger.messageTemplate, transformedPayload) : JSON.stringify(transformedPayload);
|
|
135
|
+
const conversationId = getConversationId();
|
|
136
|
+
const invocationId = generateId();
|
|
137
|
+
await createTriggerInvocation(dbClient_default)({
|
|
138
|
+
id: invocationId,
|
|
139
|
+
triggerId,
|
|
140
|
+
tenantId,
|
|
141
|
+
projectId,
|
|
142
|
+
agentId,
|
|
143
|
+
conversationId,
|
|
144
|
+
status: "pending",
|
|
145
|
+
requestPayload: payload,
|
|
146
|
+
transformedPayload
|
|
147
|
+
});
|
|
148
|
+
logger.info({
|
|
149
|
+
tenantId,
|
|
150
|
+
projectId,
|
|
151
|
+
agentId,
|
|
152
|
+
triggerId,
|
|
153
|
+
invocationId,
|
|
154
|
+
conversationId
|
|
155
|
+
}, "Trigger invocation created");
|
|
156
|
+
invokeAgentAsync({
|
|
157
|
+
tenantId,
|
|
158
|
+
projectId,
|
|
159
|
+
agentId,
|
|
160
|
+
triggerId,
|
|
161
|
+
invocationId,
|
|
162
|
+
conversationId,
|
|
163
|
+
userMessage: interpolatedMessage
|
|
164
|
+
}).catch((error) => {
|
|
165
|
+
logger.error({
|
|
166
|
+
error,
|
|
167
|
+
tenantId,
|
|
168
|
+
projectId,
|
|
169
|
+
agentId,
|
|
170
|
+
triggerId,
|
|
171
|
+
invocationId
|
|
172
|
+
}, "Async agent invocation failed");
|
|
173
|
+
});
|
|
174
|
+
logger.info({
|
|
175
|
+
tenantId,
|
|
176
|
+
projectId,
|
|
177
|
+
agentId,
|
|
178
|
+
triggerId,
|
|
179
|
+
invocationId,
|
|
180
|
+
conversationId
|
|
181
|
+
}, "Trigger webhook accepted, agent invocation initiated");
|
|
182
|
+
return c.json({
|
|
183
|
+
success: true,
|
|
184
|
+
invocationId
|
|
185
|
+
}, 202);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
logger.error({
|
|
188
|
+
error,
|
|
189
|
+
tenantId,
|
|
190
|
+
projectId,
|
|
191
|
+
agentId,
|
|
192
|
+
triggerId
|
|
193
|
+
}, "Webhook processing failed");
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
/**
|
|
198
|
+
* Invokes an agent asynchronously for a trigger invocation.
|
|
199
|
+
* This function creates a conversation, stores the user message,
|
|
200
|
+
* and executes the agent using ExecutionHandler.
|
|
201
|
+
* It updates the trigger invocation status based on success/failure.
|
|
202
|
+
*/
|
|
203
|
+
async function invokeAgentAsync(params) {
|
|
204
|
+
const { tenantId, projectId, agentId, triggerId, invocationId, conversationId, userMessage } = params;
|
|
205
|
+
const resolvedRef = {
|
|
206
|
+
type: "branch",
|
|
207
|
+
name: getProjectBranchName(tenantId, projectId),
|
|
208
|
+
hash: "HEAD"
|
|
209
|
+
};
|
|
210
|
+
return await trace.getTracer("trigger-invocation").startActiveSpan("trigger.invocation", { attributes: {
|
|
211
|
+
"conversation.id": conversationId,
|
|
212
|
+
"tenant.id": tenantId,
|
|
213
|
+
"project.id": projectId,
|
|
214
|
+
"agent.id": agentId,
|
|
215
|
+
"invocation.type": "trigger",
|
|
216
|
+
"trigger.id": triggerId,
|
|
217
|
+
"trigger.invocation.id": invocationId,
|
|
218
|
+
"message.content": userMessage,
|
|
219
|
+
"message.timestamp": (/* @__PURE__ */ new Date()).toISOString()
|
|
220
|
+
} }, async (span) => {
|
|
221
|
+
let currentBag = propagation.getBaggage(context.active());
|
|
222
|
+
if (!currentBag) currentBag = propagation.createBaggage();
|
|
223
|
+
currentBag = currentBag.setEntry("conversation.id", { value: conversationId });
|
|
224
|
+
currentBag = currentBag.setEntry("tenant.id", { value: tenantId });
|
|
225
|
+
currentBag = currentBag.setEntry("project.id", { value: projectId });
|
|
226
|
+
currentBag = currentBag.setEntry("agent.id", { value: agentId });
|
|
227
|
+
currentBag = currentBag.setEntry("invocation.type", { value: "trigger" });
|
|
228
|
+
currentBag = currentBag.setEntry("trigger.id", { value: triggerId });
|
|
229
|
+
currentBag = currentBag.setEntry("trigger.invocation.id", { value: invocationId });
|
|
230
|
+
const ctxWithBaggage = propagation.setBaggage(context.active(), currentBag);
|
|
231
|
+
return await context.with(ctxWithBaggage, async () => {
|
|
232
|
+
try {
|
|
233
|
+
logger.info({
|
|
234
|
+
tenantId,
|
|
235
|
+
projectId,
|
|
236
|
+
agentId,
|
|
237
|
+
triggerId,
|
|
238
|
+
invocationId,
|
|
239
|
+
conversationId
|
|
240
|
+
}, "Starting async agent invocation");
|
|
241
|
+
const project = await getFullProjectWithRelationIds(manageDbClient)({ scopes: {
|
|
242
|
+
tenantId,
|
|
243
|
+
projectId
|
|
244
|
+
} });
|
|
245
|
+
if (!project) throw createApiError({
|
|
246
|
+
code: "not_found",
|
|
247
|
+
message: `Project ${projectId} not found`
|
|
248
|
+
});
|
|
249
|
+
const fullAgent = project.agents[agentId];
|
|
250
|
+
if (!fullAgent) throw createApiError({
|
|
251
|
+
code: "not_found",
|
|
252
|
+
message: `Agent ${agentId} not found`
|
|
253
|
+
});
|
|
254
|
+
logger.debug({
|
|
255
|
+
tenantId,
|
|
256
|
+
projectId,
|
|
257
|
+
agentId,
|
|
258
|
+
defaultSubAgentId: fullAgent.defaultSubAgentId,
|
|
259
|
+
subAgentKeys: Object.keys(fullAgent.subAgents || {}),
|
|
260
|
+
subAgentsCount: Object.keys(fullAgent.subAgents || {}).length
|
|
261
|
+
}, "Debug: Agent and sub-agent info");
|
|
262
|
+
const agentKeys = Object.keys(fullAgent.subAgents || {});
|
|
263
|
+
const firstAgentId = agentKeys.length > 0 ? agentKeys[0] : "";
|
|
264
|
+
const defaultSubAgentId = fullAgent.defaultSubAgentId || firstAgentId;
|
|
265
|
+
if (!defaultSubAgentId) throw createApiError({
|
|
266
|
+
code: "not_found",
|
|
267
|
+
message: "No default sub-agent found"
|
|
268
|
+
});
|
|
269
|
+
const executionContext = {
|
|
270
|
+
tenantId,
|
|
271
|
+
projectId,
|
|
272
|
+
agentId,
|
|
273
|
+
baseUrl: env.INKEEP_AGENTS_RUN_API_URL || "http://localhost:8080",
|
|
274
|
+
apiKey: "",
|
|
275
|
+
apiKeyId: "trigger-invocation",
|
|
276
|
+
resolvedRef,
|
|
277
|
+
project,
|
|
278
|
+
metadata: { initiatedBy: {
|
|
279
|
+
type: "api_key",
|
|
280
|
+
id: triggerId
|
|
281
|
+
} }
|
|
282
|
+
};
|
|
283
|
+
await createOrGetConversation(dbClient_default)({
|
|
284
|
+
tenantId,
|
|
285
|
+
projectId,
|
|
286
|
+
id: conversationId,
|
|
287
|
+
agentId,
|
|
288
|
+
activeSubAgentId: defaultSubAgentId,
|
|
289
|
+
ref: executionContext.resolvedRef
|
|
290
|
+
});
|
|
291
|
+
await setActiveAgentForConversation(dbClient_default)({
|
|
292
|
+
scopes: {
|
|
293
|
+
tenantId,
|
|
294
|
+
projectId
|
|
295
|
+
},
|
|
296
|
+
conversationId,
|
|
297
|
+
agentId,
|
|
298
|
+
subAgentId: defaultSubAgentId,
|
|
299
|
+
ref: executionContext.resolvedRef
|
|
300
|
+
});
|
|
301
|
+
logger.info({
|
|
302
|
+
conversationId,
|
|
303
|
+
agentId,
|
|
304
|
+
defaultSubAgentId
|
|
305
|
+
}, "Conversation created and agent set");
|
|
306
|
+
await createMessage(dbClient_default)({
|
|
307
|
+
id: generateId(),
|
|
308
|
+
tenantId,
|
|
309
|
+
projectId,
|
|
310
|
+
conversationId,
|
|
311
|
+
role: "user",
|
|
312
|
+
content: { text: userMessage },
|
|
313
|
+
visibility: "user-facing",
|
|
314
|
+
messageType: "chat"
|
|
315
|
+
});
|
|
316
|
+
logger.info({
|
|
317
|
+
conversationId,
|
|
318
|
+
invocationId
|
|
319
|
+
}, "User message created");
|
|
320
|
+
const requestId = `trigger-${invocationId}`;
|
|
321
|
+
const noOpStreamHelper = createSSEStreamHelper({
|
|
322
|
+
writeSSE: async () => {},
|
|
323
|
+
sleep: async () => {}
|
|
324
|
+
}, requestId, Math.floor(Date.now() / 1e3));
|
|
325
|
+
await new ExecutionHandler().execute({
|
|
326
|
+
executionContext,
|
|
327
|
+
conversationId,
|
|
328
|
+
userMessage,
|
|
329
|
+
initialAgentId: agentId,
|
|
330
|
+
requestId,
|
|
331
|
+
sseHelper: noOpStreamHelper,
|
|
332
|
+
emitOperations: false
|
|
333
|
+
});
|
|
334
|
+
await updateTriggerInvocationStatus(dbClient_default)({
|
|
335
|
+
scopes: {
|
|
336
|
+
tenantId,
|
|
337
|
+
projectId,
|
|
338
|
+
agentId
|
|
339
|
+
},
|
|
340
|
+
triggerId,
|
|
341
|
+
invocationId,
|
|
342
|
+
data: { status: "success" }
|
|
343
|
+
});
|
|
344
|
+
logger.info({
|
|
345
|
+
tenantId,
|
|
346
|
+
projectId,
|
|
347
|
+
agentId,
|
|
348
|
+
triggerId,
|
|
349
|
+
invocationId,
|
|
350
|
+
conversationId
|
|
351
|
+
}, "Agent invocation completed successfully");
|
|
352
|
+
span.end();
|
|
353
|
+
} catch (error) {
|
|
354
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
355
|
+
logger.error({
|
|
356
|
+
error,
|
|
357
|
+
tenantId,
|
|
358
|
+
projectId,
|
|
359
|
+
agentId,
|
|
360
|
+
triggerId,
|
|
361
|
+
invocationId
|
|
362
|
+
}, "Agent invocation failed");
|
|
363
|
+
span.recordException(error instanceof Error ? error : new Error(errorMessage));
|
|
364
|
+
span.setStatus({
|
|
365
|
+
code: 2,
|
|
366
|
+
message: errorMessage
|
|
367
|
+
});
|
|
368
|
+
try {
|
|
369
|
+
await updateTriggerInvocationStatus(dbClient_default)({
|
|
370
|
+
scopes: {
|
|
371
|
+
tenantId,
|
|
372
|
+
projectId,
|
|
373
|
+
agentId
|
|
374
|
+
},
|
|
375
|
+
triggerId,
|
|
376
|
+
invocationId,
|
|
377
|
+
data: {
|
|
378
|
+
status: "failed",
|
|
379
|
+
errorMessage
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
} catch (updateError) {
|
|
383
|
+
logger.error({
|
|
384
|
+
updateError,
|
|
385
|
+
invocationId
|
|
386
|
+
}, "Failed to update trigger invocation status to failed");
|
|
387
|
+
}
|
|
388
|
+
span.end();
|
|
389
|
+
throw error;
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
var webhooks_default = app;
|
|
395
|
+
|
|
396
|
+
//#endregion
|
|
397
|
+
export { webhooks_default as default };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as _inkeep_agents_core1 from "@inkeep/agents-core";
|
|
2
2
|
import { BreakdownComponentDef, ContextBreakdown, calculateBreakdownTotal, createEmptyBreakdown } from "@inkeep/agents-core";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/token-estimator.d.ts
|
|
@@ -17,7 +17,7 @@ interface AssembleResult {
|
|
|
17
17
|
/** The assembled prompt string */
|
|
18
18
|
prompt: string;
|
|
19
19
|
/** Token breakdown for each component */
|
|
20
|
-
breakdown:
|
|
20
|
+
breakdown: _inkeep_agents_core1.ContextBreakdown;
|
|
21
21
|
}
|
|
22
22
|
//#endregion
|
|
23
23
|
export { AssembleResult, type BreakdownComponentDef, type ContextBreakdown, calculateBreakdownTotal, createEmptyBreakdown, estimateTokens };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inkeep/agents-run-api",
|
|
3
|
-
"version": "0.0.0-dev-
|
|
3
|
+
"version": "0.0.0-dev-20260120193424",
|
|
4
4
|
"description": "Agents Run API for Inkeep Agent Framework - handles chat, agent execution, and streaming",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"exports": {
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"hono": "^4.10.4",
|
|
42
42
|
"jmespath": "^0.16.0",
|
|
43
43
|
"llm-info": "^1.0.69",
|
|
44
|
-
"@inkeep/agents-core": "^0.0.0-dev-
|
|
44
|
+
"@inkeep/agents-core": "^0.0.0-dev-20260120193424"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
47
47
|
"@hono/zod-openapi": "^1.1.5",
|