@app-vitals/agent-admin 1.40.0 → 1.42.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.
@@ -321,3 +321,111 @@ describeOrSkip(
321
321
  });
322
322
  },
323
323
  );
324
+
325
+ describeOrSkip("AgentEnvService source and tombstones (integration)", () => {
326
+ let prisma: PrismaClient;
327
+ let service: AgentEnvService;
328
+
329
+ beforeEach(async () => {
330
+ prisma = makePrisma();
331
+ await prisma.agentToken.deleteMany();
332
+ await prisma.agentCronJob.deleteMany();
333
+ await prisma.agentTool.deleteMany();
334
+ await prisma.agentEnv.deleteMany();
335
+ await prisma.agent.deleteMany();
336
+ service = new AgentEnvService(prisma, identityCrypto);
337
+ });
338
+
339
+ afterEach(async () => {
340
+ await prisma.$disconnect();
341
+ });
342
+
343
+ const rowsOf = (agentId: string) =>
344
+ prisma.agentEnv.findMany({ where: { agentId }, orderBy: { key: "asc" } });
345
+
346
+ it("patch() and upsert() stamp source=custom", async () => {
347
+ const agentId = await createAgent(prisma);
348
+ await service.patch(agentId, { A: "1" });
349
+ expect((await rowsOf(agentId)).map((r) => r.source)).toEqual(["custom"]);
350
+ await service.upsert(agentId, { B: "2" });
351
+ expect((await rowsOf(agentId)).map((r) => r.source)).toEqual(["custom"]);
352
+ });
353
+
354
+ it("patchFromTemplate() writes source=template", async () => {
355
+ const agentId = await createAgent(prisma);
356
+ await service.patchFromTemplate(agentId, { A: "1" });
357
+ const rows = await rowsOf(agentId);
358
+ expect(rows[0]?.source).toBe("template");
359
+ expect(rows[0]?.enabled).toBe(true);
360
+ });
361
+
362
+ it("patch() of a template-sourced key turns it custom", async () => {
363
+ const agentId = await createAgent(prisma);
364
+ await service.patchFromTemplate(agentId, { A: "1" });
365
+ await service.patch(agentId, { A: "2" });
366
+ const rows = await rowsOf(agentId);
367
+ expect(rows[0]?.source).toBe("custom");
368
+ expect((await service.getByAgentId(agentId))?.env).toEqual({ A: "2" });
369
+ });
370
+
371
+ it("patchFromTemplate() does not overwrite a custom or tombstoned key", async () => {
372
+ const agentId = await createAgent(prisma);
373
+ await service.patch(agentId, { C: "mine" });
374
+ await service.patchFromTemplate(agentId, { C: "tpl" });
375
+ expect((await service.getByAgentId(agentId))?.env).toEqual({ C: "mine" });
376
+ await service.patchFromTemplate(agentId, { T: "tpl" });
377
+ await service.deleteKey(agentId, "T");
378
+ await service.patchFromTemplate(agentId, { T: "tpl" });
379
+ const t = (await rowsOf(agentId)).find((r) => r.key === "T");
380
+ expect(t?.enabled).toBe(false);
381
+ expect(t?.source).toBe("custom");
382
+ });
383
+
384
+ it("deleteKey() of a template key leaves a tombstone that no read injects", async () => {
385
+ const agentId = await createAgent(prisma);
386
+ await service.patchFromTemplate(agentId, { T: "tpl" });
387
+ await service.patch(agentId, { K: "keep" });
388
+ await service.deleteKey(agentId, "T");
389
+ const t = (await rowsOf(agentId)).find((r) => r.key === "T");
390
+ expect(t?.enabled).toBe(false);
391
+ expect(t?.source).toBe("custom");
392
+ expect((await service.getByAgentId(agentId))?.env).toEqual({ K: "keep" });
393
+ expect((await service.getConfigBundle(agentId))?.env).toEqual({
394
+ K: "keep",
395
+ });
396
+ expect((await service.listAll())[0]?.env).toEqual({ K: "keep" });
397
+ });
398
+
399
+ it("a tombstone-only agent reads as having no env", async () => {
400
+ const agentId = await createAgent(prisma);
401
+ await service.patchFromTemplate(agentId, { T: "tpl" });
402
+ await service.deleteKey(agentId, "T");
403
+ expect(await service.getByAgentId(agentId)).toBeNull();
404
+ expect(await service.getConfigBundle(agentId)).toBeNull();
405
+ });
406
+
407
+ it("deleteKey() of a custom key removes the row", async () => {
408
+ const agentId = await createAgent(prisma);
409
+ await service.patch(agentId, { K: "v" });
410
+ await service.deleteKey(agentId, "K");
411
+ expect(await rowsOf(agentId)).toEqual([]);
412
+ });
413
+
414
+ it("patch() re-enables a tombstoned key", async () => {
415
+ const agentId = await createAgent(prisma);
416
+ await service.patchFromTemplate(agentId, { T: "tpl" });
417
+ await service.deleteKey(agentId, "T");
418
+ await service.patch(agentId, { T: "again" });
419
+ expect((await service.getByAgentId(agentId))?.env).toEqual({ T: "again" });
420
+ });
421
+
422
+ it("upsert() tombstones template keys it omits", async () => {
423
+ const agentId = await createAgent(prisma);
424
+ await service.patchFromTemplate(agentId, { T: "tpl" });
425
+ await service.upsert(agentId, { K: "v" });
426
+ const t = (await rowsOf(agentId)).find((r) => r.key === "T");
427
+ expect(t?.enabled).toBe(false);
428
+ expect(t?.source).toBe("custom");
429
+ expect((await service.getByAgentId(agentId))?.env).toEqual({ K: "v" });
430
+ });
431
+ });
package/src/agent-envs.ts CHANGED
@@ -84,24 +84,32 @@ export class AgentEnvService {
84
84
  this.assertNoBlockedCredentials(agent, env);
85
85
 
86
86
  const now = this.clock.now();
87
- const rows = Object.entries(env).map(([key, value]) => ({
88
- agentId,
89
- key,
90
- value: this.crypto.encrypt(value),
91
- secret: secretKeys?.has(key) ?? false,
92
- updatedAt: now,
93
- }));
87
+ const keys = Object.keys(env);
94
88
 
89
+ // ATP-1.2: a template row the caller omits is a deletion, so it becomes a
90
+ // tombstone; tombstones the caller does not mention are kept.
95
91
  await this.prisma.$transaction([
96
- this.prisma.agentEnv.deleteMany({ where: { agentId } }),
97
- ...rows.map((row) =>
92
+ this.prisma.agentEnv.updateMany({
93
+ where: {
94
+ agentId,
95
+ source: "template",
96
+ enabled: true,
97
+ key: { notIn: keys },
98
+ },
99
+ data: { enabled: false, source: "custom", updatedAt: now },
100
+ }),
101
+ this.prisma.agentEnv.deleteMany({
102
+ where: { agentId, OR: [{ enabled: true }, { key: { in: keys } }] },
103
+ }),
104
+ ...Object.entries(env).map(([key, value]) =>
98
105
  this.prisma.agentEnv.create({
99
106
  data: {
100
- agentId: row.agentId,
101
- key: row.key,
102
- value: row.value,
103
- secret: row.secret,
104
- updatedAt: row.updatedAt,
107
+ agentId,
108
+ key,
109
+ value: this.crypto.encrypt(value),
110
+ secret: secretKeys?.has(key) ?? false,
111
+ source: "custom",
112
+ updatedAt: now,
105
113
  },
106
114
  }),
107
115
  ),
@@ -137,11 +145,15 @@ export class AgentEnvService {
137
145
  key,
138
146
  value: this.crypto.encrypt(value),
139
147
  secret: secretKeys?.has(key) ?? false,
148
+ source: "custom",
140
149
  updatedAt: now,
141
150
  },
142
151
  update: {
143
152
  value: this.crypto.encrypt(value),
144
153
  secret: secretKeys?.has(key) ?? false,
154
+ // An admin edit takes ownership and re-enables a tombstone.
155
+ source: "custom",
156
+ enabled: true,
145
157
  updatedAt: now,
146
158
  },
147
159
  }),
@@ -149,13 +161,63 @@ export class AgentEnvService {
149
161
  );
150
162
  }
151
163
 
164
+ /**
165
+ * Internal reconcile write path (ATP-1.2); never exposed over HTTP.
166
+ * Upserts template-owned keys with source="template" without flipping
167
+ * source. Keys that are already custom (user edits or tombstones of deleted
168
+ * template rows) are left untouched so a reconcile never overrides or
169
+ * re-adds them.
170
+ */
171
+ async patchFromTemplate(
172
+ agentId: string,
173
+ env: Record<string, string>,
174
+ secretKeys?: Set<string>,
175
+ ): Promise<void> {
176
+ const agent = await this.prisma.agent.findUnique({
177
+ where: { id: agentId },
178
+ });
179
+ if (!agent) {
180
+ throw new UnprocessableEntityError("agent not found");
181
+ }
182
+ this.assertNoBlockedCredentials(agent, env);
183
+
184
+ const customKeys = new Set(
185
+ (
186
+ await this.prisma.agentEnv.findMany({
187
+ where: { agentId, source: "custom" },
188
+ select: { key: true },
189
+ })
190
+ ).map((r) => r.key),
191
+ );
192
+ const now = this.clock.now();
193
+ await this.prisma.$transaction(
194
+ Object.entries(env)
195
+ .filter(([key]) => !customKeys.has(key))
196
+ .map(([key, value]) => {
197
+ const data = {
198
+ value: this.crypto.encrypt(value),
199
+ secret: secretKeys?.has(key) ?? false,
200
+ source: "template",
201
+ updatedAt: now,
202
+ };
203
+ return this.prisma.agentEnv.upsert({
204
+ where: { agentId_key: { agentId, key } },
205
+ create: { agentId, key, ...data },
206
+ update: data,
207
+ });
208
+ }),
209
+ );
210
+ }
211
+
152
212
  /**
153
213
  * Get all env vars for an agent.
154
214
  * Secret values are masked as "***"; their keys are listed in secretKeys.
155
215
  * Returns null if the agent has no env vars set.
156
216
  */
157
217
  async getByAgentId(agentId: string): Promise<AgentEnvResult | null> {
158
- const rows = await this.prisma.agentEnv.findMany({ where: { agentId } });
218
+ const rows = await this.prisma.agentEnv.findMany({
219
+ where: { agentId, enabled: true },
220
+ });
159
221
  if (rows.length === 0) return null;
160
222
 
161
223
  const env: Record<string, string> = {};
@@ -181,7 +243,9 @@ export class AgentEnvService {
181
243
  * Throws 500 if decryption fails.
182
244
  */
183
245
  async getConfigBundle(agentId: string): Promise<AgentEnvBundle | null> {
184
- const rows = await this.prisma.agentEnv.findMany({ where: { agentId } });
246
+ const rows = await this.prisma.agentEnv.findMany({
247
+ where: { agentId, enabled: true },
248
+ });
185
249
  if (rows.length === 0) return null;
186
250
 
187
251
  let env: Record<string, string>;
@@ -206,17 +270,29 @@ export class AgentEnvService {
206
270
 
207
271
  /**
208
272
  * Delete a single env var key for the given agent.
209
- * No-ops if the key does not exist.
273
+ * No-ops if the key does not exist. A template-sourced row becomes a
274
+ * disabled custom tombstone (ATP-1.2) so a later reconcile does not re-add
275
+ * it; a custom row is removed.
210
276
  */
211
277
  async deleteKey(agentId: string, key: string): Promise<void> {
212
- await this.prisma.agentEnv.deleteMany({ where: { agentId, key } });
278
+ await this.prisma.$transaction([
279
+ this.prisma.agentEnv.updateMany({
280
+ where: { agentId, key, source: "template" },
281
+ data: { enabled: false, source: "custom", updatedAt: this.clock.now() },
282
+ }),
283
+ this.prisma.agentEnv.deleteMany({
284
+ where: { agentId, key, source: "custom", enabled: true },
285
+ }),
286
+ ]);
213
287
  }
214
288
 
215
289
  /**
216
290
  * List all agents with their decrypted env vars.
217
291
  */
218
292
  async listAll(): Promise<AgentEnvEntry[]> {
219
- const rows = await this.prisma.agentEnv.findMany();
293
+ const rows = await this.prisma.agentEnv.findMany({
294
+ where: { enabled: true },
295
+ });
220
296
 
221
297
  // Group by agentId
222
298
  const byAgent = new Map<string, typeof rows>();
@@ -154,4 +154,56 @@ describeOrSkip("AgentPluginService (integration)", () => {
154
154
  service.removeByName(agentId2, "shipwright@shipwright"),
155
155
  ).rejects.toBeInstanceOf(NotFoundError);
156
156
  });
157
+
158
+ // ─── ATP-1.2: source / tombstones ──────────────────────────────────────────
159
+
160
+ it("add() stamps source=custom, including on a template row", async () => {
161
+ const agentId = await createAgent(prisma);
162
+ expect((await service.add(agentId, "a@m")).source).toBe("custom");
163
+ await service.addFromTemplate(agentId, "b@m", "1.0.0");
164
+ const edited = await service.add(agentId, "b@m", "2.0.0");
165
+ expect(edited.source).toBe("custom");
166
+ expect(edited.version).toBe("2.0.0");
167
+ });
168
+
169
+ it("addFromTemplate() writes source=template and keeps it on re-run", async () => {
170
+ const agentId = await createAgent(prisma);
171
+ const first = await service.addFromTemplate(agentId, "a@m", "1.0.0");
172
+ expect(first.source).toBe("template");
173
+ const again = await service.addFromTemplate(agentId, "a@m", "1.1.0");
174
+ expect(again.source).toBe("template");
175
+ expect(again.version).toBe("1.1.0");
176
+ });
177
+
178
+ it("addFromTemplate() does not resurrect a tombstone", async () => {
179
+ const agentId = await createAgent(prisma);
180
+ const p = await service.addFromTemplate(agentId, "a@m");
181
+ await service.remove(agentId, p.id);
182
+ const after = await service.addFromTemplate(agentId, "a@m");
183
+ expect(after.enabled).toBe(false);
184
+ expect(after.source).toBe("custom");
185
+ });
186
+
187
+ it("remove() of a template row leaves a disabled custom tombstone hidden from listEnabled()", async () => {
188
+ const agentId = await createAgent(prisma);
189
+ const p = await service.addFromTemplate(agentId, "a@m");
190
+ await service.remove(agentId, p.id);
191
+ const rows = await prisma.agentPlugin.findMany({ where: { agentId } });
192
+ expect(rows).toHaveLength(1);
193
+ expect(rows[0]?.enabled).toBe(false);
194
+ expect(rows[0]?.source).toBe("custom");
195
+ expect(await service.listEnabled(agentId)).toEqual([]);
196
+ });
197
+
198
+ it("removeByName() of a template row leaves a tombstone; of a custom row deletes it", async () => {
199
+ const agentId = await createAgent(prisma);
200
+ await service.addFromTemplate(agentId, "t@m");
201
+ await service.add(agentId, "c@m");
202
+ await service.removeByName(agentId, "t@m");
203
+ await service.removeByName(agentId, "c@m");
204
+ const rows = await prisma.agentPlugin.findMany({ where: { agentId } });
205
+ expect(rows.map((r) => [r.name, r.enabled, r.source])).toEqual([
206
+ ["t@m", false, "custom"],
207
+ ]);
208
+ });
157
209
  });
@@ -56,11 +56,58 @@ export class AgentPluginService {
56
56
  ): Promise<AgentPlugin> {
57
57
  return client.agentPlugin.upsert({
58
58
  where: { agentId_name: { agentId, name } },
59
- create: { agentId, name, version: version ?? null, enabled: true },
60
- update: { version: version ?? null, enabled: true },
59
+ create: {
60
+ agentId,
61
+ name,
62
+ version: version ?? null,
63
+ enabled: true,
64
+ source: "custom",
65
+ },
66
+ update: { version: version ?? null, enabled: true, source: "custom" },
61
67
  });
62
68
  }
63
69
 
70
+ /**
71
+ * Internal reconcile write path (ATP-1.2); never exposed over HTTP.
72
+ * Creates a template-sourced plugin, or refreshes one that is still
73
+ * template-owned. A custom row (user edit or tombstone) is returned
74
+ * untouched so a reconcile neither overrides nor resurrects it.
75
+ */
76
+ async addFromTemplate(
77
+ agentId: string,
78
+ name: string,
79
+ version?: string | null,
80
+ client: PrismaTransactionClient = this.prisma,
81
+ ): Promise<AgentPlugin> {
82
+ const existing = await client.agentPlugin.findUnique({
83
+ where: { agentId_name: { agentId, name } },
84
+ });
85
+ if (existing?.source === "custom") return existing;
86
+ return client.agentPlugin.upsert({
87
+ where: { agentId_name: { agentId, name } },
88
+ create: {
89
+ agentId,
90
+ name,
91
+ version: version ?? null,
92
+ enabled: true,
93
+ source: "template",
94
+ },
95
+ update: { version: version ?? null, enabled: true, source: "template" },
96
+ });
97
+ }
98
+
99
+ /** Delete the row, or tombstone it when it is template-sourced (ATP-1.2). */
100
+ private async removeRow(row: AgentPlugin): Promise<void> {
101
+ if (row.source === "template") {
102
+ await this.prisma.agentPlugin.update({
103
+ where: { id: row.id },
104
+ data: { enabled: false, source: "custom" },
105
+ });
106
+ return;
107
+ }
108
+ await this.prisma.agentPlugin.delete({ where: { id: row.id } });
109
+ }
110
+
64
111
  /**
65
112
  * Remove a plugin by ID. Verifies agentId ownership before deleting.
66
113
  * Throws NotFoundError if the pluginId doesn't exist or belongs to a different agent.
@@ -74,7 +121,7 @@ export class AgentPluginService {
74
121
  throw new NotFoundError(`plugin ${pluginId} not found`);
75
122
  }
76
123
 
77
- await this.prisma.agentPlugin.delete({ where: { id: pluginId } });
124
+ await this.removeRow(existing);
78
125
  }
79
126
 
80
127
  /**
@@ -90,6 +137,6 @@ export class AgentPluginService {
90
137
  throw new NotFoundError(`plugin ${name} not found`);
91
138
  }
92
139
 
93
- await this.prisma.agentPlugin.delete({ where: { id: existing.id } });
140
+ await this.removeRow(existing);
94
141
  }
95
142
  }
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import type { Prisma } from "../prisma/client/client.ts";
14
+ import { ANTHROPIC_CREDENTIAL_KEYS } from "./anthropic-credential-guard.ts";
14
15
  import { UnprocessableEntityError } from "./errors.ts";
15
16
  import type { TokenCrypto } from "./token-crypto.ts";
16
17
 
@@ -53,3 +54,29 @@ export function openTemplateItemPayload(
53
54
  if (kind !== "env" || typeof payload.value !== "string") return payload;
54
55
  return { ...payload, value: crypto.decrypt(payload.value) };
55
56
  }
57
+
58
+ /**
59
+ * Env keys a template may never carry (ATP-1.3): per-agent credentials that
60
+ * are minted for, or provisioned onto, one specific agent. Copying them from a
61
+ * template would hand every agent the same identity.
62
+ */
63
+ export const TEMPLATE_ENV_DENYLIST: ReadonlySet<string> = new Set([
64
+ "SLACK_BOT_TOKEN",
65
+ "SLACK_APP_TOKEN",
66
+ "SLACK_APP_ID",
67
+ "SLACK_SIGNING_SECRET",
68
+ "GH_TOKEN",
69
+ "SHIPWRIGHT_AGENT_API_KEY",
70
+ "SHIPWRIGHT_TASK_STORE_URL",
71
+ "SHIPWRIGHT_TASK_STORE_TOKEN",
72
+ ...ANTHROPIC_CREDENTIAL_KEYS,
73
+ ]);
74
+
75
+ /** Throws UnprocessableEntityError (422) for a denylisted env key (case-insensitive). */
76
+ export function assertTemplateEnvKeyAllowed(key: string): void {
77
+ if (TEMPLATE_ENV_DENYLIST.has(key.toUpperCase())) {
78
+ throw new UnprocessableEntityError(
79
+ `env key ${key} is a per-agent credential and cannot be set in a template`,
80
+ );
81
+ }
82
+ }
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { describe, expect, it } from "bun:test";
7
7
  import {
8
+ assertTemplateEnvKeyAllowed,
8
9
  openTemplateItemPayload,
9
10
  sealTemplateItemPayload,
10
11
  } from "./agent-template-items.ts";
@@ -53,3 +54,17 @@ describe("sealTemplateItemPayload", () => {
53
54
  }
54
55
  });
55
56
  });
57
+
58
+ describe("assertTemplateEnvKeyAllowed", () => {
59
+ it("rejects per-agent credential keys, case-insensitively", () => {
60
+ for (const key of ["SLACK_BOT_TOKEN", "gh_token", "ANTHROPIC_API_KEY"]) {
61
+ expect(() => assertTemplateEnvKeyAllowed(key)).toThrow(
62
+ UnprocessableEntityError,
63
+ );
64
+ }
65
+ });
66
+
67
+ it("allows ordinary keys", () => {
68
+ expect(() => assertTemplateEnvKeyAllowed("LINEAR_API_KEY")).not.toThrow();
69
+ });
70
+ });