@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,432 @@
1
+ /**
2
+ * admin/src/agent-templates.ts
3
+ * AgentTemplateService (ATP-1.3) — CRUD for agent templates and their items.
4
+ *
5
+ * A template is the default env/tool/plugin/cron set for one scope:
6
+ * (accountId | null = deployment-wide, specialty | null = every specialty).
7
+ * Items are keyed by (kind, key): env var name, tool pattern, plugin name or
8
+ * cron name.
9
+ *
10
+ * Authorization is part of the service so every caller shares it: a platform
11
+ * admin ("admin" actor) manages any template; an account-scoped caller
12
+ * ("account" actor) manages only that account's templates. A template outside
13
+ * the actor's account reads as 404 (no existence leak); naming another
14
+ * account, or the deployment scope, in a request is 403.
15
+ *
16
+ * Env values are encrypted at rest (sealTemplateItemPayload) and secret ones
17
+ * are masked as "***" on every read; non-secret ones are returned decrypted.
18
+ */
19
+
20
+ import { z } from "zod";
21
+ import type { PrismaClient } from "../prisma/client/client.ts";
22
+ import {
23
+ AGENT_TEMPLATE_ITEM_KINDS,
24
+ type AgentTemplateItemKind,
25
+ assertTemplateEnvKeyAllowed,
26
+ openTemplateItemPayload,
27
+ sealTemplateItemPayload,
28
+ type TemplateItemPayload,
29
+ } from "./agent-template-items.ts";
30
+ import {
31
+ ConflictError,
32
+ ForbiddenError,
33
+ NotFoundError,
34
+ UnprocessableEntityError,
35
+ } from "./errors.ts";
36
+ import type { SpecialtyTypeResolver } from "./specialty-types.ts";
37
+ import type { TokenCrypto } from "./token-crypto.ts";
38
+
39
+ export const SECRET_MASK = "***";
40
+
41
+ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
42
+
43
+ export type TemplateActor =
44
+ | { kind: "admin" }
45
+ | { kind: "account"; accountId: string };
46
+
47
+ export interface TemplateItemInput {
48
+ kind: AgentTemplateItemKind;
49
+ key: string;
50
+ payload?: Record<string, unknown>;
51
+ }
52
+
53
+ export interface TemplateScopeInput {
54
+ /** Omitted = the actor's own account (account actors) / deployment-wide (admins). */
55
+ accountId?: string | null;
56
+ specialty?: string | null;
57
+ }
58
+
59
+ export interface TemplateItemView {
60
+ kind: AgentTemplateItemKind;
61
+ key: string;
62
+ payload: Record<string, unknown>;
63
+ updatedAt: Date;
64
+ }
65
+
66
+ export interface TemplateView {
67
+ id: string;
68
+ accountId: string | null;
69
+ specialty: string | null;
70
+ createdAt: Date;
71
+ updatedAt: Date;
72
+ items: TemplateItemView[];
73
+ }
74
+
75
+ // ─── Per-kind payload shapes ──────────────────────────────────────────────────
76
+
77
+ const nonEmpty = z.string().trim().min(1);
78
+
79
+ const PAYLOAD_SCHEMAS = {
80
+ env: z.object({ value: z.string(), secret: z.boolean().optional() }),
81
+ tool: z.object({ enabled: z.boolean().optional() }),
82
+ plugin: z.object({
83
+ version: z.string().nullable().optional(),
84
+ enabled: z.boolean().optional(),
85
+ }),
86
+ cron: z.object({
87
+ schedule: nonEmpty,
88
+ prompt: nonEmpty,
89
+ channel: z.string().nullable().optional(),
90
+ user: z.string().nullable().optional(),
91
+ silent: z.boolean().optional(),
92
+ enabled: z.boolean().optional(),
93
+ preCheck: z.string().nullable().optional(),
94
+ }),
95
+ } satisfies Record<AgentTemplateItemKind, z.ZodType>;
96
+
97
+ /** Validates one item and returns its normalized (still plaintext) payload. */
98
+ export function normalizeTemplateItem(
99
+ item: TemplateItemInput,
100
+ ): TemplateItemInput & { payload: Record<string, unknown> } {
101
+ if (!AGENT_TEMPLATE_ITEM_KINDS.includes(item.kind)) {
102
+ throw new UnprocessableEntityError(`unknown item kind ${item.kind}`);
103
+ }
104
+ const key = item.key.trim();
105
+ if (key === "") {
106
+ throw new UnprocessableEntityError(
107
+ item.kind === "cron"
108
+ ? "cron template items need a stable name key"
109
+ : `${item.kind} template items need a key`,
110
+ );
111
+ }
112
+ if (item.kind === "env") {
113
+ if (!ENV_KEY.test(key)) {
114
+ throw new UnprocessableEntityError(
115
+ `env key ${key} must be a valid environment variable name`,
116
+ );
117
+ }
118
+ assertTemplateEnvKeyAllowed(key);
119
+ }
120
+ const defaults = item.kind === "tool" ? {} : undefined;
121
+ const parsed = PAYLOAD_SCHEMAS[item.kind].safeParse(
122
+ item.payload ?? defaults ?? {},
123
+ );
124
+ if (!parsed.success) {
125
+ const detail = parsed.error.issues
126
+ .map((i) => `${i.path.join(".") || "payload"}: ${i.message}`)
127
+ .join(", ");
128
+ throw new UnprocessableEntityError(
129
+ `invalid ${item.kind} item ${key}: ${detail}`,
130
+ );
131
+ }
132
+ return { kind: item.kind, key, payload: parsed.data };
133
+ }
134
+
135
+ // ─── Service ──────────────────────────────────────────────────────────────────
136
+
137
+ type TemplateRow = {
138
+ id: string;
139
+ accountId: string | null;
140
+ specialty: string | null;
141
+ createdAt: Date;
142
+ updatedAt: Date;
143
+ items: {
144
+ kind: string;
145
+ key: string;
146
+ payload: unknown;
147
+ updatedAt: Date;
148
+ }[];
149
+ };
150
+
151
+ export class AgentTemplateService {
152
+ constructor(
153
+ private prisma: PrismaClient,
154
+ private crypto: TokenCrypto,
155
+ private specialtyRegistry: Pick<SpecialtyTypeResolver, "tryGetType">,
156
+ ) {}
157
+
158
+ private toView(row: TemplateRow): TemplateView {
159
+ const items = [...row.items]
160
+ .sort((a, b) =>
161
+ a.kind === b.kind
162
+ ? a.key.localeCompare(b.key)
163
+ : a.kind.localeCompare(b.kind),
164
+ )
165
+ .map((it): TemplateItemView => {
166
+ const kind = it.kind as AgentTemplateItemKind;
167
+ const stored = (it.payload ?? {}) as TemplateItemPayload;
168
+ let payload: Record<string, unknown>;
169
+ if (kind === "env" && stored.secret === true) {
170
+ payload = { ...stored, value: SECRET_MASK };
171
+ } else {
172
+ payload = openTemplateItemPayload(kind, stored, this.crypto);
173
+ }
174
+ return { kind, key: it.key, payload, updatedAt: it.updatedAt };
175
+ });
176
+ return {
177
+ id: row.id,
178
+ accountId: row.accountId,
179
+ specialty: row.specialty,
180
+ createdAt: row.createdAt,
181
+ updatedAt: row.updatedAt,
182
+ items,
183
+ };
184
+ }
185
+
186
+ /** Throws 404 unless the actor may see `template`. */
187
+ private assertVisible(
188
+ actor: TemplateActor,
189
+ template: { id: string; accountId: string | null },
190
+ ): void {
191
+ if (actor.kind === "account" && template.accountId !== actor.accountId) {
192
+ throw new NotFoundError(`template ${template.id} not found`);
193
+ }
194
+ }
195
+
196
+ private async load(actor: TemplateActor, id: string): Promise<TemplateRow> {
197
+ const row = await this.prisma.agentTemplate.findUnique({
198
+ where: { id },
199
+ include: { items: true },
200
+ });
201
+ if (!row) throw new NotFoundError(`template ${id} not found`);
202
+ this.assertVisible(actor, row);
203
+ return row;
204
+ }
205
+
206
+ private validateSpecialty(specialty: string | null): void {
207
+ if (specialty !== null && !this.specialtyRegistry.tryGetType(specialty)) {
208
+ throw new UnprocessableEntityError(`unknown specialty ${specialty}`);
209
+ }
210
+ }
211
+
212
+ /**
213
+ * The payload to store for `item`. A secret env item sent as the mask keeps
214
+ * `prior` (the stored payload of the same key); with nothing to keep it is a
215
+ * 422.
216
+ */
217
+ private seal(
218
+ item: TemplateItemInput & { payload: Record<string, unknown> },
219
+ prior: unknown,
220
+ ): TemplateItemPayload {
221
+ if (
222
+ item.kind === "env" &&
223
+ item.payload.secret === true &&
224
+ item.payload.value === SECRET_MASK
225
+ ) {
226
+ const kept = prior as TemplateItemPayload | undefined;
227
+ if (kept?.secret !== true) {
228
+ throw new UnprocessableEntityError(
229
+ `env ${item.key}: "${SECRET_MASK}" is the mask for an existing secret; send the real value`,
230
+ );
231
+ }
232
+ return kept;
233
+ }
234
+ return sealTemplateItemPayload(
235
+ item.kind,
236
+ item.payload as TemplateItemPayload,
237
+ this.crypto,
238
+ );
239
+ }
240
+
241
+ /**
242
+ * List templates. An account actor sees only its own account's templates
243
+ * (naming another account is 403); an admin sees all, optionally narrowed.
244
+ */
245
+ async list(
246
+ actor: TemplateActor,
247
+ filter: { accountId?: string; specialty?: string } = {},
248
+ ): Promise<TemplateView[]> {
249
+ if (
250
+ actor.kind === "account" &&
251
+ filter.accountId !== undefined &&
252
+ filter.accountId !== actor.accountId
253
+ ) {
254
+ throw new ForbiddenError("cannot access another account's templates");
255
+ }
256
+ const accountId =
257
+ actor.kind === "account" ? actor.accountId : filter.accountId;
258
+ const rows = await this.prisma.agentTemplate.findMany({
259
+ where: {
260
+ ...(accountId !== undefined ? { accountId } : {}),
261
+ ...(filter.specialty !== undefined
262
+ ? { specialty: filter.specialty }
263
+ : {}),
264
+ },
265
+ include: { items: true },
266
+ orderBy: { createdAt: "asc" },
267
+ });
268
+ return rows.map((r) => this.toView(r));
269
+ }
270
+
271
+ async get(actor: TemplateActor, id: string): Promise<TemplateView> {
272
+ return this.toView(await this.load(actor, id));
273
+ }
274
+
275
+ /**
276
+ * Create the template for the scope, or replace the items of the existing
277
+ * one. A secret env item sent with the mask "***" keeps the stored value of
278
+ * the same key (so a GET → edit → PUT round trip does not need the secret).
279
+ */
280
+ async replace(
281
+ actor: TemplateActor,
282
+ scopeInput: TemplateScopeInput,
283
+ itemsInput: TemplateItemInput[],
284
+ ): Promise<{ template: TemplateView; created: boolean }> {
285
+ let accountId: string | null;
286
+ if (actor.kind === "account") {
287
+ if (
288
+ scopeInput.accountId !== undefined &&
289
+ scopeInput.accountId !== actor.accountId
290
+ ) {
291
+ throw new ForbiddenError(
292
+ "cannot manage another account's or deployment-wide templates",
293
+ );
294
+ }
295
+ accountId = actor.accountId;
296
+ } else {
297
+ accountId = scopeInput.accountId ?? null;
298
+ }
299
+ const specialty = scopeInput.specialty ?? null;
300
+ this.validateSpecialty(specialty);
301
+
302
+ const seen = new Set<string>();
303
+ const items = itemsInput.map((raw) => {
304
+ const item = normalizeTemplateItem(raw);
305
+ const id = `${item.kind}:${item.key}`;
306
+ if (seen.has(id)) {
307
+ throw new UnprocessableEntityError(
308
+ `duplicate ${item.kind} item key ${item.key}`,
309
+ );
310
+ }
311
+ seen.add(id);
312
+ return item;
313
+ });
314
+
315
+ if (accountId !== null) {
316
+ const account = await this.prisma.account.findUnique({
317
+ where: { id: accountId },
318
+ select: { id: true },
319
+ });
320
+ if (!account) {
321
+ throw new UnprocessableEntityError(`account ${accountId} not found`);
322
+ }
323
+ }
324
+
325
+ try {
326
+ return await this.prisma.$transaction(async (tx) => {
327
+ const existing = await tx.agentTemplate.findFirst({
328
+ where: { accountId, specialty },
329
+ include: { items: true },
330
+ });
331
+ const stored = new Map(
332
+ (existing?.items ?? []).map((it) => [`${it.kind}:${it.key}`, it]),
333
+ );
334
+ const data = items.map((item) => ({
335
+ kind: item.kind,
336
+ key: item.key,
337
+ payload: this.seal(
338
+ item,
339
+ stored.get(`${item.kind}:${item.key}`)?.payload,
340
+ ),
341
+ }));
342
+
343
+ const templateId = existing
344
+ ? existing.id
345
+ : (await tx.agentTemplate.create({ data: { accountId, specialty } }))
346
+ .id;
347
+ if (existing) {
348
+ await tx.agentTemplateItem.deleteMany({ where: { templateId } });
349
+ await tx.agentTemplate.update({
350
+ where: { id: templateId },
351
+ data: { updatedAt: new Date() },
352
+ });
353
+ }
354
+ if (data.length > 0) {
355
+ await tx.agentTemplateItem.createMany({
356
+ data: data.map((d) => ({ ...d, templateId })),
357
+ });
358
+ }
359
+ const row = await tx.agentTemplate.findUniqueOrThrow({
360
+ where: { id: templateId },
361
+ include: { items: true },
362
+ });
363
+ return { template: this.toView(row), created: !existing };
364
+ });
365
+ } catch (err) {
366
+ if ((err as { code?: string }).code === "P2002") {
367
+ throw new ConflictError(
368
+ "a template for this scope was created concurrently; retry",
369
+ );
370
+ }
371
+ throw err;
372
+ }
373
+ }
374
+
375
+ /** Add or replace one item of a template. */
376
+ async putItem(
377
+ actor: TemplateActor,
378
+ templateId: string,
379
+ input: TemplateItemInput,
380
+ ): Promise<TemplateView> {
381
+ const existing = await this.load(actor, templateId);
382
+ const item = normalizeTemplateItem(input);
383
+ const prior = existing.items.find(
384
+ (it) => it.kind === item.kind && it.key === item.key,
385
+ );
386
+ const payload = this.seal(item, prior?.payload);
387
+ await this.prisma.$transaction([
388
+ this.prisma.agentTemplateItem.upsert({
389
+ where: {
390
+ templateId_kind_key: {
391
+ templateId,
392
+ kind: item.kind,
393
+ key: item.key,
394
+ },
395
+ },
396
+ create: { templateId, kind: item.kind, key: item.key, payload },
397
+ update: { payload },
398
+ }),
399
+ this.prisma.agentTemplate.update({
400
+ where: { id: templateId },
401
+ data: { updatedAt: new Date() },
402
+ }),
403
+ ]);
404
+ return this.get(actor, templateId);
405
+ }
406
+
407
+ /** Remove one item; 404 when the template or the item does not exist. */
408
+ async deleteItem(
409
+ actor: TemplateActor,
410
+ templateId: string,
411
+ kind: AgentTemplateItemKind,
412
+ key: string,
413
+ ): Promise<void> {
414
+ await this.load(actor, templateId);
415
+ const { count } = await this.prisma.agentTemplateItem.deleteMany({
416
+ where: { templateId, kind, key },
417
+ });
418
+ if (count === 0) {
419
+ throw new NotFoundError(`${kind} item ${key} not found`);
420
+ }
421
+ await this.prisma.agentTemplate.update({
422
+ where: { id: templateId },
423
+ data: { updatedAt: new Date() },
424
+ });
425
+ }
426
+
427
+ /** Delete a template and (by cascade) its items. */
428
+ async delete(actor: TemplateActor, id: string): Promise<void> {
429
+ await this.load(actor, id);
430
+ await this.prisma.agentTemplate.delete({ where: { id } });
431
+ }
432
+ }
package/src/api-auth.ts CHANGED
@@ -250,6 +250,9 @@ export function createAdminAuthMiddleware(deps: {
250
250
  if (path === "/agents" || path === "/agents/") {
251
251
  return method === "GET" || method === "POST";
252
252
  }
253
+ // /templates (ATP-1.3): the handlers resolve the caller's account and
254
+ // confine them to it, so the middleware only lets session users through.
255
+ if (path === "/templates" || path.startsWith("/templates/")) return true;
253
256
  const agentId = extractAgentId(path);
254
257
  if (!agentId || !callerScopeResolver) return false;
255
258
  return scopeIncludesAgent(await callerScopeResolver(email, false), agentId);
@@ -1544,3 +1544,87 @@ export const PatchAccountBodySchema = z
1544
1544
  trialExpiresAt: z.string().datetime().nullable().optional(),
1545
1545
  })
1546
1546
  .openapi("PatchAccountBody");
1547
+
1548
+ // ─── Agent templates (ATP-1.3) ────────────────────────────────────────────────
1549
+
1550
+ export const TemplateItemKindSchema = z
1551
+ .enum(["env", "tool", "plugin", "cron"])
1552
+ .openapi("TemplateItemKind");
1553
+
1554
+ const TemplateItemBaseSchema = z.object({
1555
+ kind: TemplateItemKindSchema,
1556
+ key: z.string().openapi({
1557
+ description:
1558
+ "Env var name, tool pattern, plugin name or cron name (cron items need a stable, non-empty name).",
1559
+ example: "LINEAR_API_KEY",
1560
+ }),
1561
+ payload: z
1562
+ .record(z.string(), z.unknown())
1563
+ .optional()
1564
+ .openapi({
1565
+ description:
1566
+ "Kind-specific fields. env: {value, secret?}; tool: {enabled?}; plugin: {version?, enabled?}; cron: {schedule, prompt, channel?, user?, silent?, enabled?, preCheck?}.",
1567
+ example: { value: "lin_abc", secret: true },
1568
+ }),
1569
+ });
1570
+
1571
+ export const TemplateItemInputSchema =
1572
+ TemplateItemBaseSchema.openapi("TemplateItemInput");
1573
+
1574
+ export const TemplateItemSchema = TemplateItemBaseSchema.extend({
1575
+ payload: z.record(z.string(), z.unknown()).openapi({
1576
+ description: 'Secret env values are returned masked as "***".',
1577
+ }),
1578
+ updatedAt: z
1579
+ .string()
1580
+ .datetime()
1581
+ .openapi({ example: "2026-01-01T00:00:00.000Z" }),
1582
+ }).openapi("TemplateItem");
1583
+
1584
+ export const AgentTemplateSchema = z
1585
+ .object({
1586
+ id: z.string().openapi({ example: "clx1234567890" }),
1587
+ accountId: z.string().nullable().openapi({ example: null }),
1588
+ specialty: z.string().nullable().openapi({ example: "specialist" }),
1589
+ items: z.array(TemplateItemSchema),
1590
+ createdAt: z
1591
+ .string()
1592
+ .datetime()
1593
+ .openapi({ example: "2026-01-01T00:00:00.000Z" }),
1594
+ updatedAt: z
1595
+ .string()
1596
+ .datetime()
1597
+ .openapi({ example: "2026-01-01T00:00:00.000Z" }),
1598
+ })
1599
+ .openapi("AgentTemplate");
1600
+
1601
+ export const AgentTemplatesListSchema = z
1602
+ .object({ templates: z.array(AgentTemplateSchema) })
1603
+ .openapi("AgentTemplatesList");
1604
+
1605
+ export const ListTemplatesQuerySchema = z.object({
1606
+ accountId: z.string().optional().openapi({ example: "clx1234567890" }),
1607
+ specialty: z.string().optional().openapi({ example: "specialist" }),
1608
+ });
1609
+
1610
+ export const PutTemplateBodySchema = z
1611
+ .object({
1612
+ accountId: z.string().nullable().optional().openapi({
1613
+ description:
1614
+ "Owning account; null or omitted = deployment-wide (platform admins only). Account callers may omit it or send their own account.",
1615
+ }),
1616
+ specialty: z.string().nullable().optional().openapi({
1617
+ description: "Specialty the template applies to; null = every specialty.",
1618
+ }),
1619
+ items: z.array(TemplateItemInputSchema),
1620
+ })
1621
+ .openapi("PutTemplateBody");
1622
+
1623
+ export const TemplateIdParamSchema = z.object({
1624
+ id: z.string().openapi({ param: { name: "id", in: "path" } }),
1625
+ });
1626
+
1627
+ export const TemplateItemKeyQuerySchema = z.object({
1628
+ kind: TemplateItemKindSchema,
1629
+ key: z.string().min(1),
1630
+ });