@app-vitals/agent-admin 1.39.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.
Files changed (37) hide show
  1. package/openapi.platform.json +584 -0
  2. package/package.json +2 -2
  3. package/prisma/client/browser.ts +10 -0
  4. package/prisma/client/client.ts +10 -0
  5. package/prisma/client/internal/class.ts +24 -4
  6. package/prisma/client/internal/prismaNamespace.ts +184 -2
  7. package/prisma/client/internal/prismaNamespaceBrowser.ts +33 -1
  8. package/prisma/client/models/Account.ts +148 -0
  9. package/prisma/client/models/Agent.ts +80 -1
  10. package/prisma/client/models/AgentCronJob.ts +54 -1
  11. package/prisma/client/models/AgentEnv.ts +36 -1
  12. package/prisma/client/models/AgentPlugin.ts +36 -1
  13. package/prisma/client/models/AgentTemplate.ts +1501 -0
  14. package/prisma/client/models/AgentTemplateItem.ts +1416 -0
  15. package/prisma/client/models/AgentTool.ts +71 -1
  16. package/prisma/client/models.ts +2 -0
  17. package/prisma/migrations/20261113000000_add_agent_templates/migration.sql +71 -0
  18. package/prisma/schema/schema.prisma +61 -4
  19. package/src/admin-boot.ts +18 -0
  20. package/src/admin-local-agent.smoke.test.ts +2 -0
  21. package/src/admin-spec.ts +18 -0
  22. package/src/admin-ui.fixtures.ts +3 -0
  23. package/src/admin-ui.smoke.test.ts +2 -0
  24. package/src/agent-cron-run-stats.smoke.test.ts +10 -0
  25. package/src/agent-plugins.unit.test.ts +1 -0
  26. package/src/agent-template-items.ts +82 -0
  27. package/src/agent-template-items.unit.test.ts +70 -0
  28. package/src/agent-templates-api.integration.test.ts +428 -0
  29. package/src/agent-templates-api.smoke.test.ts +135 -0
  30. package/src/agent-templates-api.ts +293 -0
  31. package/src/agent-templates.integration.test.ts +200 -0
  32. package/src/agent-templates.ts +432 -0
  33. package/src/agents-api.smoke.test.ts +17 -0
  34. package/src/api-auth.ts +3 -0
  35. package/src/api.smoke.test.ts +13 -0
  36. package/src/chat.smoke.test.ts +2 -0
  37. package/src/openapi-schemas.ts +84 -0
@@ -0,0 +1,135 @@
1
+ /**
2
+ * admin/src/agent-templates-api.smoke.test.ts
3
+ * Smoke test for the /templates routes via app.request(): routing, auth and
4
+ * error mapping over an in-memory service. No DB, no network.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { buildPlatformAdminSpec } from "./admin-spec.ts";
9
+ import type { TemplateView } from "./agent-templates.ts";
10
+ import { createAgentTemplatesApp } from "./agent-templates-api.ts";
11
+ import { parseAdminApiKeys } from "./api-auth.ts";
12
+ import { NotFoundError } from "./errors.ts";
13
+
14
+ const now = new Date("2026-11-14T00:00:00Z");
15
+ const view: TemplateView = {
16
+ id: "t1",
17
+ accountId: null,
18
+ specialty: null,
19
+ createdAt: now,
20
+ updatedAt: now,
21
+ items: [
22
+ {
23
+ kind: "env",
24
+ key: "TOKEN",
25
+ payload: { value: "***", secret: true },
26
+ updatedAt: now,
27
+ },
28
+ ],
29
+ };
30
+
31
+ function build() {
32
+ const app = createAgentTemplatesApp({
33
+ templateService: {
34
+ list: async () => [view],
35
+ get: async (_a, id) => {
36
+ if (id !== "t1") throw new NotFoundError("nope");
37
+ return view;
38
+ },
39
+ replace: async () => ({ template: view, created: true }),
40
+ putItem: async () => view,
41
+ deleteItem: async () => {},
42
+ delete: async () => {},
43
+ },
44
+ callerScopeResolver: async () => ({ kind: "all" }),
45
+ sessionSecret: "smoke-session-secret-32-chars-long",
46
+ adminApiKeys: parseAdminApiKeys("root:tok-admin:*,bot:tok-agent:agent-1"),
47
+ agentTokenService: { validate: async () => null },
48
+ });
49
+ return { app };
50
+ }
51
+
52
+ const admin = {
53
+ Authorization: "Bearer tok-admin",
54
+ "Content-Type": "application/json",
55
+ };
56
+
57
+ describe("/templates smoke", () => {
58
+ it("serves every route for an admin", async () => {
59
+ const { app } = build();
60
+ const list = await app.request("/templates", { headers: admin });
61
+ expect(list.status).toBe(200);
62
+ expect(
63
+ ((await list.json()) as { templates: unknown[] }).templates,
64
+ ).toHaveLength(1);
65
+
66
+ const get = await app.request("/templates/t1", { headers: admin });
67
+ expect(get.status).toBe(200);
68
+ expect(await get.json()).toMatchObject({
69
+ id: "t1",
70
+ items: [{ payload: { value: "***" } }],
71
+ });
72
+
73
+ const put = await app.request("/templates", {
74
+ method: "PUT",
75
+ headers: admin,
76
+ body: JSON.stringify({ items: [] }),
77
+ });
78
+ expect(put.status).toBe(201);
79
+
80
+ const item = await app.request("/templates/t1/items", {
81
+ method: "PUT",
82
+ headers: admin,
83
+ body: JSON.stringify({ kind: "tool", key: "Bash" }),
84
+ });
85
+ expect(item.status).toBe(200);
86
+
87
+ expect(
88
+ (
89
+ await app.request("/templates/t1/items?kind=tool&key=Bash", {
90
+ method: "DELETE",
91
+ headers: admin,
92
+ })
93
+ ).status,
94
+ ).toBe(204);
95
+ expect(
96
+ (await app.request("/templates/t1", { method: "DELETE", headers: admin }))
97
+ .status,
98
+ ).toBe(204);
99
+ });
100
+
101
+ it("maps errors and rejects bad auth and bodies", async () => {
102
+ const { app } = build();
103
+ expect(
104
+ (await app.request("/templates/missing", { headers: admin })).status,
105
+ ).toBe(404);
106
+ expect((await app.request("/templates")).status).toBe(401);
107
+ expect(
108
+ (
109
+ await app.request("/templates", {
110
+ headers: { Authorization: "Bearer tok-agent" },
111
+ })
112
+ ).status,
113
+ ).toBe(403);
114
+ expect(
115
+ (
116
+ await app.request("/templates", {
117
+ method: "PUT",
118
+ headers: admin,
119
+ body: JSON.stringify({ items: [{ kind: "bogus", key: "x" }] }),
120
+ })
121
+ ).status,
122
+ ).toBe(400);
123
+ });
124
+
125
+ it("is documented in the platform OpenAPI spec", () => {
126
+ const spec = buildPlatformAdminSpec();
127
+ expect(Object.keys(spec.paths)).toEqual(
128
+ expect.arrayContaining([
129
+ "/templates",
130
+ "/templates/{id}",
131
+ "/templates/{id}/items",
132
+ ]),
133
+ );
134
+ });
135
+ });
@@ -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
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * admin/src/agent-templates.integration.test.ts
3
+ * ATP-1.1: AgentTemplate / AgentTemplateItem schema and the row source
4
+ * markers, against real Postgres.
5
+ *
6
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
7
+ */
8
+
9
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
+ import type { PrismaClient } from "../prisma/client/client.ts";
11
+ import {
12
+ openTemplateItemPayload,
13
+ sealTemplateItemPayload,
14
+ type TemplateItemPayload,
15
+ } from "./agent-template-items.ts";
16
+ import { createAdminPrismaClient } from "./prisma-client.ts";
17
+ import { makeStrictTokenCrypto } from "./token-crypto.ts";
18
+
19
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
20
+
21
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
22
+
23
+ describeOrSkip("AgentTemplate schema (integration)", () => {
24
+ let prisma: PrismaClient;
25
+
26
+ beforeEach(async () => {
27
+ prisma = createAdminPrismaClient(TEST_DB as string);
28
+ await prisma.agentTemplateItem.deleteMany();
29
+ await prisma.agentTemplate.deleteMany();
30
+ await prisma.agent.deleteMany();
31
+ await prisma.accountInvite.deleteMany();
32
+ await prisma.accountMember.deleteMany();
33
+ await prisma.account.deleteMany();
34
+ });
35
+
36
+ afterEach(async () => {
37
+ await prisma.$disconnect();
38
+ });
39
+
40
+ /** Inserting a second template with the same scope must fail. */
41
+ async function expectDuplicateRejected(
42
+ accountId: string | null,
43
+ specialty: string | null,
44
+ ): Promise<void> {
45
+ await prisma.agentTemplate.create({ data: { accountId, specialty } });
46
+ await expect(
47
+ (async () =>
48
+ prisma.agentTemplate.create({ data: { accountId, specialty } }))(),
49
+ ).rejects.toThrow();
50
+ expect(
51
+ await prisma.agentTemplate.count({ where: { accountId, specialty } }),
52
+ ).toBe(1);
53
+ }
54
+
55
+ describe("(accountId, specialty) uniqueness", () => {
56
+ it("rejects a second deployment-wide template for every specialty (both NULL)", async () => {
57
+ await expectDuplicateRejected(null, null);
58
+ });
59
+
60
+ it("rejects a second deployment-wide template for one specialty (accountId NULL)", async () => {
61
+ await expectDuplicateRejected(null, "specialist");
62
+ });
63
+
64
+ it("rejects a second account template for every specialty (specialty NULL)", async () => {
65
+ const account = await prisma.account.create({ data: { name: "A" } });
66
+ await expectDuplicateRejected(account.id, null);
67
+ });
68
+
69
+ it("rejects a second account template for one specialty (both set)", async () => {
70
+ const account = await prisma.account.create({ data: { name: "A" } });
71
+ await expectDuplicateRejected(account.id, "specialist");
72
+ });
73
+
74
+ it("allows one template per distinct scope", async () => {
75
+ const a = await prisma.account.create({ data: { name: "A" } });
76
+ const b = await prisma.account.create({ data: { name: "B" } });
77
+ const scopes: Array<[string | null, string | null]> = [
78
+ [null, null],
79
+ [null, "specialist"],
80
+ [null, "coder"],
81
+ [a.id, null],
82
+ [a.id, "specialist"],
83
+ [b.id, null],
84
+ [b.id, "specialist"],
85
+ ];
86
+ for (const [accountId, specialty] of scopes) {
87
+ await prisma.agentTemplate.create({ data: { accountId, specialty } });
88
+ }
89
+ expect(await prisma.agentTemplate.count()).toBe(scopes.length);
90
+ });
91
+
92
+ it("rejects a duplicate (templateId, kind, key) item but allows the key under another kind", async () => {
93
+ const t = await prisma.agentTemplate.create({ data: {} });
94
+ await prisma.agentTemplateItem.create({
95
+ data: { templateId: t.id, kind: "tool", key: "Read" },
96
+ });
97
+ await prisma.agentTemplateItem.create({
98
+ data: { templateId: t.id, kind: "plugin", key: "Read" },
99
+ });
100
+ await expect(
101
+ (async () =>
102
+ prisma.agentTemplateItem.create({
103
+ data: { templateId: t.id, kind: "tool", key: "Read" },
104
+ }))(),
105
+ ).rejects.toThrow();
106
+ });
107
+
108
+ it("deletes an account's templates and their items with the account", async () => {
109
+ const account = await prisma.account.create({ data: { name: "A" } });
110
+ const t = await prisma.agentTemplate.create({
111
+ data: { accountId: account.id },
112
+ });
113
+ await prisma.agentTemplateItem.create({
114
+ data: { templateId: t.id, kind: "tool", key: "Read" },
115
+ });
116
+ await prisma.account.delete({ where: { id: account.id } });
117
+ expect(await prisma.agentTemplate.count()).toBe(0);
118
+ expect(await prisma.agentTemplateItem.count()).toBe(0);
119
+ });
120
+ });
121
+
122
+ describe("column defaults (what pre-existing rows get)", () => {
123
+ // Raw INSERTs that omit the new columns exercise the database DEFAULTs,
124
+ // which is what ADD COLUMN gives rows written before the migration.
125
+ it("source defaults to custom, templateDetached to false, AgentTool.updatedAt to now", async () => {
126
+ await prisma.$executeRaw`INSERT INTO "Agent" ("id", "name", "updatedAt") VALUES ('ag1', 'legacy', now())`;
127
+ await prisma.$executeRaw`INSERT INTO "AgentEnv" ("id", "agentId", "key", "value", "updatedAt") VALUES ('e1', 'ag1', 'K', 'v', now())`;
128
+ await prisma.$executeRaw`INSERT INTO "AgentTool" ("id", "agentId", "pattern") VALUES ('t1', 'ag1', 'Read')`;
129
+ await prisma.$executeRaw`INSERT INTO "AgentPlugin" ("id", "agentId", "name", "updatedAt") VALUES ('p1', 'ag1', 'x@y', now())`;
130
+ await prisma.$executeRaw`INSERT INTO "AgentCronJob" ("id", "agentId", "schedule", "prompt", "updatedAt") VALUES ('c1', 'ag1', '* * * * *', 'hi', now())`;
131
+
132
+ const agent = await prisma.agent.findUniqueOrThrow({
133
+ where: { id: "ag1" },
134
+ include: { envVars: true, tools: true, plugins: true, cronJobs: true },
135
+ });
136
+ expect(agent.templateDetached).toBe(false);
137
+ expect(agent.envVars.map((r) => r.source)).toEqual(["custom"]);
138
+ expect(agent.tools.map((r) => r.source)).toEqual(["custom"]);
139
+ expect(agent.plugins.map((r) => r.source)).toEqual(["custom"]);
140
+ expect(agent.cronJobs.map((r) => r.source)).toEqual(["custom"]);
141
+ const tool = agent.tools[0];
142
+ expect(tool?.updatedAt).toBeInstanceOf(Date);
143
+ expect(
144
+ Math.abs((tool?.updatedAt.getTime() ?? 0) - Date.now()),
145
+ ).toBeLessThan(60_000);
146
+ });
147
+
148
+ it("keeps an explicit source=template and bumps AgentTool.updatedAt on update", async () => {
149
+ const agent = await prisma.agent.create({ data: { name: "a" } });
150
+ const tool = await prisma.agentTool.create({
151
+ data: { agentId: agent.id, pattern: "Bash", source: "template" },
152
+ });
153
+ expect(tool.source).toBe("template");
154
+ await Bun.sleep(5);
155
+ const updated = await prisma.agentTool.update({
156
+ where: { id: tool.id },
157
+ data: { enabled: false },
158
+ });
159
+ expect(updated.updatedAt.getTime()).toBeGreaterThan(
160
+ tool.updatedAt.getTime(),
161
+ );
162
+ });
163
+ });
164
+
165
+ describe("env item payload", () => {
166
+ it("stores an env item's value AES-256-GCM encrypted and reads it back", async () => {
167
+ const crypto = makeStrictTokenCrypto("cd".repeat(32));
168
+ if (!crypto) throw new Error("test key rejected");
169
+ const t = await prisma.agentTemplate.create({ data: {} });
170
+ const item = await prisma.agentTemplateItem.create({
171
+ data: {
172
+ templateId: t.id,
173
+ kind: "env",
174
+ key: "API_TOKEN",
175
+ payload: sealTemplateItemPayload(
176
+ "env",
177
+ { value: "plain-secret", secret: true },
178
+ crypto,
179
+ ),
180
+ },
181
+ });
182
+
183
+ // The plaintext never reaches the column.
184
+ const rows = await prisma.$queryRaw<
185
+ Array<{ payload: string }>
186
+ >`SELECT "payload"::text AS payload FROM "AgentTemplateItem" WHERE "id" = ${item.id}`;
187
+ expect(rows[0]?.payload).not.toContain("plain-secret");
188
+
189
+ const stored = await prisma.agentTemplateItem.findUniqueOrThrow({
190
+ where: { id: item.id },
191
+ });
192
+ const payload = stored.payload as TemplateItemPayload;
193
+ expect(String(payload.value).split(":")).toHaveLength(3);
194
+ expect(openTemplateItemPayload("env", payload, crypto)).toEqual({
195
+ value: "plain-secret",
196
+ secret: true,
197
+ });
198
+ });
199
+ });
200
+ });