@app-vitals/agent-admin 1.40.0 → 1.41.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.
@@ -0,0 +1,293 @@
1
+ /**
2
+ * admin/src/agent-templates-api.ts
3
+ * /templates API (ATP-1.3): list, read, create/replace and delete agent
4
+ * templates and their items.
5
+ *
6
+ * Auth: platform admins (admin key or admin session) manage every template,
7
+ * including deployment-wide ones. A session user with an account (resolved
8
+ * through the caller-scope resolver, never from the request) manages only that
9
+ * account's templates. Every other caller (agent keys, platform.* keys,
10
+ * members without an account) gets 403.
11
+ */
12
+
13
+ import { createRoute, OpenAPIHono } from "@hono/zod-openapi";
14
+ import { HTTPException } from "hono/http-exception";
15
+ import { accountIdFromScope } from "./account-agent-create.ts";
16
+ import type {
17
+ AgentTemplateService,
18
+ TemplateActor,
19
+ TemplateView,
20
+ } from "./agent-templates.ts";
21
+ import type { AgentTokenService } from "./agent-tokens.ts";
22
+ import {
23
+ type AdminApiKey,
24
+ type AdminAuthEnv,
25
+ createAdminAuthMiddleware,
26
+ } from "./api-auth.ts";
27
+ import type { CallerScopeResolver } from "./caller-scope.ts";
28
+ import { ApiError, ForbiddenError } from "./errors.ts";
29
+ import {
30
+ AgentTemplateSchema,
31
+ AgentTemplatesListSchema,
32
+ ErrorSchema,
33
+ ListTemplatesQuerySchema,
34
+ PutTemplateBodySchema,
35
+ TemplateIdParamSchema,
36
+ TemplateItemInputSchema,
37
+ TemplateItemKeyQuerySchema,
38
+ } from "./openapi-schemas.ts";
39
+
40
+ export interface AgentTemplatesApiDeps {
41
+ templateService: Pick<
42
+ AgentTemplateService,
43
+ "list" | "get" | "replace" | "putItem" | "deleteItem" | "delete"
44
+ >;
45
+ callerScopeResolver: CallerScopeResolver;
46
+ sessionSecret: string;
47
+ adminApiKeys?: Map<string, AdminApiKey>;
48
+ agentTokenService: Pick<AgentTokenService, "validate">;
49
+ }
50
+
51
+ const jsonError = { content: { "application/json": { schema: ErrorSchema } } };
52
+
53
+ const errorResponses = {
54
+ 401: { description: "Unauthorized", ...jsonError },
55
+ 403: {
56
+ description:
57
+ "Forbidden (caller has no account, or names another account / the deployment scope)",
58
+ ...jsonError,
59
+ },
60
+ 404: {
61
+ description: "Template not found (or not in the caller's account)",
62
+ ...jsonError,
63
+ },
64
+ };
65
+
66
+ const templateResponse = (description: string) => ({
67
+ description,
68
+ content: { "application/json": { schema: AgentTemplateSchema } },
69
+ });
70
+
71
+ const listTemplatesRoute = createRoute({
72
+ method: "get",
73
+ path: "/templates",
74
+ tags: ["templates"],
75
+ summary: "List agent templates",
76
+ description:
77
+ "Platform admins see every template (optionally narrowed by `accountId` / `specialty`); account callers see only their account's. Secret env values are masked as `***`.",
78
+ request: { query: ListTemplatesQuerySchema },
79
+ responses: {
80
+ 200: {
81
+ description: "Templates",
82
+ content: { "application/json": { schema: AgentTemplatesListSchema } },
83
+ },
84
+ ...errorResponses,
85
+ },
86
+ });
87
+
88
+ const getTemplateRoute = createRoute({
89
+ method: "get",
90
+ path: "/templates/{id}",
91
+ tags: ["templates"],
92
+ summary: "Get an agent template",
93
+ description:
94
+ "Returns the template with its items. Secret env values are masked as `***`; non-secret ones are returned in clear.",
95
+ request: { params: TemplateIdParamSchema },
96
+ responses: { 200: templateResponse("Template"), ...errorResponses },
97
+ });
98
+
99
+ const putTemplateRoute = createRoute({
100
+ method: "put",
101
+ path: "/templates",
102
+ tags: ["templates"],
103
+ summary: "Create or replace an agent template",
104
+ description:
105
+ 'Creates the template for the (accountId, specialty) scope, or replaces the items of the existing one (201 / 200). Account callers may only write their own account (403 otherwise); only platform admins write deployment-wide templates. 422 for an unknown specialty, a denylisted env key (per-agent credentials: Slack tokens, GH_TOKEN, Anthropic credentials, task-store URL/token), an invalid item payload, a cron item without a name key, or a duplicate (kind, key). Env values are encrypted at rest; a secret env item sent as `"***"` keeps its stored value.',
106
+ request: {
107
+ body: {
108
+ content: { "application/json": { schema: PutTemplateBodySchema } },
109
+ },
110
+ },
111
+ responses: {
112
+ 200: templateResponse("Template replaced"),
113
+ 201: templateResponse("Template created"),
114
+ 400: { description: "Bad request", ...jsonError },
115
+ 422: { description: "Validation failed", ...jsonError },
116
+ ...errorResponses,
117
+ },
118
+ });
119
+
120
+ const deleteTemplateRoute = createRoute({
121
+ method: "delete",
122
+ path: "/templates/{id}",
123
+ tags: ["templates"],
124
+ summary: "Delete an agent template",
125
+ description: "Deletes the template and all of its items.",
126
+ request: { params: TemplateIdParamSchema },
127
+ responses: {
128
+ 204: { description: "Template deleted" },
129
+ ...errorResponses,
130
+ },
131
+ });
132
+
133
+ const putItemRoute = createRoute({
134
+ method: "put",
135
+ path: "/templates/{id}/items",
136
+ tags: ["templates"],
137
+ summary: "Add or replace a template item",
138
+ description:
139
+ "Upserts one item by (kind, key) without touching the others. Same validation as PUT /templates (422).",
140
+ request: {
141
+ params: TemplateIdParamSchema,
142
+ body: {
143
+ content: { "application/json": { schema: TemplateItemInputSchema } },
144
+ },
145
+ },
146
+ responses: {
147
+ 200: templateResponse("Template with the item applied"),
148
+ 400: { description: "Bad request", ...jsonError },
149
+ 422: { description: "Validation failed", ...jsonError },
150
+ ...errorResponses,
151
+ },
152
+ });
153
+
154
+ const deleteItemRoute = createRoute({
155
+ method: "delete",
156
+ path: "/templates/{id}/items",
157
+ tags: ["templates"],
158
+ summary: "Remove a template item",
159
+ description:
160
+ "Removes the item identified by the `kind` and `key` query params (a query rather than a path segment because plugin and tool keys can contain `/`). 404 when it does not exist.",
161
+ request: { params: TemplateIdParamSchema, query: TemplateItemKeyQuerySchema },
162
+ responses: {
163
+ 204: { description: "Item removed" },
164
+ ...errorResponses,
165
+ },
166
+ });
167
+
168
+ function serialize(t: TemplateView) {
169
+ return {
170
+ id: t.id,
171
+ accountId: t.accountId,
172
+ specialty: t.specialty,
173
+ items: t.items.map((i) => ({
174
+ kind: i.kind,
175
+ key: i.key,
176
+ payload: i.payload,
177
+ updatedAt: i.updatedAt.toISOString(),
178
+ })),
179
+ createdAt: t.createdAt.toISOString(),
180
+ updatedAt: t.updatedAt.toISOString(),
181
+ };
182
+ }
183
+
184
+ export function createAgentTemplatesApp(
185
+ deps: AgentTemplatesApiDeps,
186
+ ): OpenAPIHono<AdminAuthEnv> {
187
+ const { templateService, callerScopeResolver } = deps;
188
+
189
+ const app = new OpenAPIHono<AdminAuthEnv>({
190
+ defaultHook: (result, c) => {
191
+ if (!result.success) {
192
+ const message = result.error.issues
193
+ .map((i) => `${i.path.join(".")}: ${i.message}`)
194
+ .join(", ");
195
+ return c.json({ error: message }, 400);
196
+ }
197
+ },
198
+ });
199
+
200
+ app.onError((err, c) => {
201
+ if (err instanceof ApiError && err.statusCode < 500) {
202
+ return c.json(
203
+ { error: err.message },
204
+ err.statusCode as 400 | 401 | 403 | 404 | 409 | 422,
205
+ );
206
+ }
207
+ if (err instanceof HTTPException && err.status < 500) {
208
+ return c.json({ error: err.message }, err.status as 400 | 415);
209
+ }
210
+ console.error("[agent-templates-api] unhandled error:", err);
211
+ return c.json({ error: "Internal server error" }, 500);
212
+ });
213
+
214
+ // "/templates/*" also matches the bare "/templates" path in Hono.
215
+ app.use(
216
+ "/templates/*",
217
+ createAdminAuthMiddleware({
218
+ sessionSecret: deps.sessionSecret,
219
+ agentTokenService: deps.agentTokenService,
220
+ adminApiKeys: deps.adminApiKeys,
221
+ callerScopeResolver,
222
+ }),
223
+ );
224
+
225
+ async function resolveActor(c: {
226
+ get: {
227
+ (k: "isAdmin"): boolean;
228
+ (k: "callerEmail"): string | undefined;
229
+ };
230
+ }): Promise<TemplateActor> {
231
+ if (c.get("isAdmin") === true) return { kind: "admin" };
232
+ const email = c.get("callerEmail");
233
+ const accountId =
234
+ email === undefined
235
+ ? null
236
+ : accountIdFromScope(await callerScopeResolver(email, false));
237
+ if (accountId === null) {
238
+ throw new ForbiddenError("Admin or account access required");
239
+ }
240
+ return { kind: "account", accountId };
241
+ }
242
+
243
+ app.openapi(listTemplatesRoute, async (c) => {
244
+ const actor = await resolveActor(c);
245
+ const templates = await templateService.list(actor, c.req.valid("query"));
246
+ return c.json({ templates: templates.map(serialize) }, 200);
247
+ });
248
+
249
+ app.openapi(getTemplateRoute, async (c) => {
250
+ const actor = await resolveActor(c);
251
+ const t = await templateService.get(actor, c.req.valid("param").id);
252
+ return c.json(serialize(t), 200);
253
+ });
254
+
255
+ app.openapi(putTemplateRoute, async (c) => {
256
+ const actor = await resolveActor(c);
257
+ const body = c.req.valid("json");
258
+ const { template, created } = await templateService.replace(
259
+ actor,
260
+ {
261
+ ...(body.accountId !== undefined ? { accountId: body.accountId } : {}),
262
+ ...(body.specialty !== undefined ? { specialty: body.specialty } : {}),
263
+ },
264
+ body.items,
265
+ );
266
+ return c.json(serialize(template), created ? 201 : 200);
267
+ });
268
+
269
+ app.openapi(deleteTemplateRoute, async (c) => {
270
+ const actor = await resolveActor(c);
271
+ await templateService.delete(actor, c.req.valid("param").id);
272
+ return c.body(null, 204);
273
+ });
274
+
275
+ app.openapi(putItemRoute, async (c) => {
276
+ const actor = await resolveActor(c);
277
+ const t = await templateService.putItem(
278
+ actor,
279
+ c.req.valid("param").id,
280
+ c.req.valid("json"),
281
+ );
282
+ return c.json(serialize(t), 200);
283
+ });
284
+
285
+ app.openapi(deleteItemRoute, async (c) => {
286
+ const actor = await resolveActor(c);
287
+ const { kind, key } = c.req.valid("query");
288
+ await templateService.deleteItem(actor, c.req.valid("param").id, kind, key);
289
+ return c.body(null, 204);
290
+ });
291
+
292
+ return app;
293
+ }