@app-vitals/agent-admin 1.45.0 → 1.47.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.
@@ -5,6 +5,7 @@
5
5
  * Styles live in baseStyles() between the "Settings layout" markers.
6
6
  */
7
7
 
8
+ import type { SettingsNavContribution } from "./admin-extension.ts";
8
9
  import { escapeHtml, renderAdminToolbar } from "./admin-ui-styles.ts";
9
10
 
10
11
  export interface SettingsNavItem {
@@ -75,3 +76,26 @@ export function renderSettingsLayout(
75
76
  </div>
76
77
  </div>`;
77
78
  }
79
+
80
+ /**
81
+ * Appends contributed items into the section with the matching label (an
82
+ * unknown section is appended at the end). Pure: the input nav is not mutated.
83
+ */
84
+ export function mergeSettingsNavItems(
85
+ nav: SettingsNav,
86
+ items: SettingsNavContribution[],
87
+ ): SettingsNav {
88
+ const sections: SettingsNavSection[] = nav.sections.map((s) => ({
89
+ label: s.label,
90
+ items: [...s.items],
91
+ }));
92
+ for (const { section, ...item } of items) {
93
+ let target = sections.find((s) => s.label === section);
94
+ if (!target) {
95
+ target = { label: section, items: [] };
96
+ sections.push(target);
97
+ }
98
+ target.items.push(item);
99
+ }
100
+ return { sections };
101
+ }
package/src/admin-ui.ts CHANGED
@@ -53,6 +53,7 @@ import { renderZeroQuotaNotice } from "./admin-ui-account-pages.ts";
53
53
  import { registerAdminAccountsRoutes } from "./admin-ui-accounts.ts";
54
54
  import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
55
55
  import { registerAdminTemplatesRoutes } from "./admin-ui-templates.ts";
56
+ import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
56
57
  import type { AgentTemplateService } from "./agent-templates.ts";
57
58
  import {
58
59
  type GithubAccessPreviewView,
@@ -392,6 +393,8 @@ export interface AdminUIDeps {
392
393
  specialtyRegistry?: SpecialtyTypeResolver;
393
394
  /** Extension-supplied specialty defaults, consulted before the built-in type. */
394
395
  specialtyDefaults?: SpecialtyDefaultsResolver;
396
+ /** ATP-2.2: seeds the resolved agent template inside the create transaction. */
397
+ templateReconcile?: Pick<AgentTemplateReconcileService, "reconcile">;
395
398
  /**
396
399
  * Cleanup deps for the full delete-agent orchestration (POST
397
400
  * /admin/agents/:id/delete → deleteAgentFully()). Matches
@@ -866,6 +869,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
866
869
  accountServices,
867
870
  githubEnterpriseApi,
868
871
  templateService,
872
+ templateReconcile,
869
873
  agentsApi,
870
874
  specialtyRegistry = new SpecialtyTypes(),
871
875
  specialtyDefaults,
@@ -1656,6 +1660,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1656
1660
  specialtyRegistry,
1657
1661
  specialtyDefaults,
1658
1662
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
1663
+ ...(templateReconcile ? { templateReconcile } : {}),
1659
1664
  },
1660
1665
  {
1661
1666
  name,
@@ -52,11 +52,12 @@ import {
52
52
  type MergedTemplateItem,
53
53
  mergeTemplateLayers,
54
54
  resolveSpecialtyDefaultSet,
55
+ type SpecialtyDefaultSet,
55
56
  specialtyDefaultLayer,
56
57
  type TemplateLayerInput,
57
58
  templateLayerForScope,
58
59
  } from "./agent-template-merge.ts";
59
- import { NotFoundError } from "./errors.ts";
60
+ import { ConflictError, NotFoundError } from "./errors.ts";
60
61
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
61
62
  import type {
62
63
  SpecialtyDefaultCron,
@@ -172,43 +173,180 @@ export class AgentTemplateReconcileService {
172
173
  private specialtyDefaults: SpecialtyDefaultsResolver = () => undefined,
173
174
  ) {}
174
175
 
175
- /** Reconcile one agent against its merged template, in one transaction. */
176
- async reconcile(agentId: string): Promise<TemplateReconcileResult> {
177
- return this.prisma.$transaction(async (tx) => {
178
- // Serialize concurrent reconciles of the same agent.
179
- await tx.$queryRaw`SELECT "id" FROM "Agent" WHERE "id" = ${agentId} FOR UPDATE`;
180
- const agent = await tx.agent.findUnique({
181
- where: { id: agentId },
182
- select: { specialty: true, accountId: true, templateDetached: true },
183
- });
184
- if (!agent) throw new NotFoundError(`agent ${agentId} not found`);
185
- if (agent.templateDetached) return emptyResult(agentId, "detached");
176
+ /**
177
+ * Reconcile one agent against its merged template, in one transaction.
178
+ * Pass `tx` to join a caller's transaction instead (createAgent() seeds the
179
+ * template inside its create transaction); a failure then rolls back with
180
+ * the caller's writes.
181
+ */
182
+ async reconcile(
183
+ agentId: string,
184
+ tx?: PrismaTransactionClient,
185
+ ): Promise<TemplateReconcileResult> {
186
+ if (tx) return this.run(tx, agentId);
187
+ return this.prisma.$transaction((t) => this.run(t, agentId));
188
+ }
186
189
 
187
- const defaults = resolveSpecialtyDefaultSet(
188
- agent.specialty,
189
- this.specialtyRegistry,
190
- this.specialtyDefaults,
191
- );
192
- if (!defaults) {
190
+ /**
191
+ * Fan a template change out to the agents that follow it: every attached
192
+ * agent the template's scope covers (deployment-wide = all accounts, an
193
+ * account = that account's agents; a specialty narrows to that type).
194
+ * One transaction per agent; a failing agent is logged and skipped so one
195
+ * bad agent never blocks the rest.
196
+ */
197
+ async reconcileScope(scope: {
198
+ accountId: string | null;
199
+ specialty: string | null;
200
+ }): Promise<{ reconciled: number; failed: number }> {
201
+ const agents = await this.prisma.agent.findMany({
202
+ where: {
203
+ templateDetached: false,
204
+ ...(scope.accountId !== null ? { accountId: scope.accountId } : {}),
205
+ ...(scope.specialty !== null ? { specialty: scope.specialty } : {}),
206
+ },
207
+ select: { id: true },
208
+ });
209
+ let reconciled = 0;
210
+ let failed = 0;
211
+ for (const { id } of agents) {
212
+ try {
213
+ await this.reconcile(id);
214
+ reconciled++;
215
+ } catch (err) {
216
+ failed++;
193
217
  console.error(
194
- `template reconcile: no known type for specialty "${agent.specialty}" (agent ${agentId}) — leaving it untouched`,
218
+ `template fan-out: reconcile of agent ${id} failed:`,
219
+ err instanceof Error ? err.message : String(err),
195
220
  );
196
- return emptyResult(agentId, "unknown_specialty");
197
221
  }
222
+ }
223
+ return { reconciled, failed };
224
+ }
225
+
226
+ /** Set or clear the agent's detach flag (no reconcile). */
227
+ async setDetached(agentId: string, detached: boolean): Promise<void> {
228
+ const { count } = await this.prisma.agent.updateMany({
229
+ where: { id: agentId },
230
+ data: { templateDetached: detached },
231
+ });
232
+ if (count === 0) throw new NotFoundError(`agent ${agentId} not found`);
233
+ }
198
234
 
199
- const merged = await this.resolve(
200
- tx,
201
- agent.accountId,
202
- agent.specialty,
203
- specialtyDefaultLayer(defaults),
235
+ /**
236
+ * Reset to template: drops the agent's custom rows (overrides and
237
+ * tombstones) for every key the merged template defines, or just `only`'s
238
+ * key, then reconciles so the template values come back as template rows.
239
+ * Rows for keys the template does not define stay. One transaction.
240
+ */
241
+ async reset(
242
+ agentId: string,
243
+ only?: { kind: AgentTemplateItemKind; key: string },
244
+ ): Promise<TemplateReconcileResult> {
245
+ return this.prisma.$transaction((tx) => this.run(tx, agentId, { only }));
246
+ }
247
+
248
+ private async run(
249
+ tx: PrismaTransactionClient,
250
+ agentId: string,
251
+ reset?: { only?: { kind: AgentTemplateItemKind; key: string } },
252
+ ): Promise<TemplateReconcileResult> {
253
+ // Serialize concurrent reconciles of the same agent.
254
+ await tx.$queryRaw`SELECT "id" FROM "Agent" WHERE "id" = ${agentId} FOR UPDATE`;
255
+ const agent = await tx.agent.findUnique({
256
+ where: { id: agentId },
257
+ select: { specialty: true, accountId: true, templateDetached: true },
258
+ });
259
+ if (!agent) throw new NotFoundError(`agent ${agentId} not found`);
260
+ if (agent.templateDetached) {
261
+ if (reset) {
262
+ throw new ConflictError(
263
+ `agent ${agentId} is detached from its template; reattach it first`,
264
+ );
265
+ }
266
+ return emptyResult(agentId, "detached");
267
+ }
268
+
269
+ const defaults = resolveSpecialtyDefaultSet(
270
+ agent.specialty,
271
+ this.specialtyRegistry,
272
+ this.specialtyDefaults,
273
+ );
274
+ if (!defaults) {
275
+ console.error(
276
+ `template reconcile: no known type for specialty "${agent.specialty}" (agent ${agentId}) — leaving it untouched`,
204
277
  );
205
- const result = emptyResult(agentId, "reconciled");
206
- // Env goes last: it is the only kind that encrypts on write.
207
- await this.reconcileTools(tx, agentId, merged, result);
208
- await this.reconcilePlugins(tx, agentId, merged, result);
209
- await this.reconcileCrons(tx, agentId, merged, defaults.crons, result);
210
- await this.reconcileEnv(tx, agentId, merged, result);
211
- return result;
278
+ return emptyResult(agentId, "unknown_specialty");
279
+ }
280
+
281
+ const merged = await this.resolve(
282
+ tx,
283
+ agent.accountId,
284
+ agent.specialty,
285
+ specialtyDefaultLayer(defaults),
286
+ );
287
+ if (reset) {
288
+ await this.dropCustomRows(tx, agentId, merged, defaults, reset.only);
289
+ }
290
+ const result = emptyResult(agentId, "reconciled");
291
+ // Env goes last: it is the only kind that encrypts on write.
292
+ await this.reconcileTools(tx, agentId, merged, result);
293
+ await this.reconcilePlugins(tx, agentId, merged, result);
294
+ await this.reconcileCrons(tx, agentId, merged, defaults.crons, result);
295
+ await this.reconcileEnv(tx, agentId, merged, result);
296
+ return result;
297
+ }
298
+
299
+ /** Reset step: delete custom rows (incl. tombstones) the template defines. */
300
+ private async dropCustomRows(
301
+ tx: PrismaTransactionClient,
302
+ agentId: string,
303
+ merged: MergedTemplate,
304
+ defaults: SpecialtyDefaultSet,
305
+ only?: { kind: AgentTemplateItemKind; key: string },
306
+ ): Promise<void> {
307
+ const keys = (kind: AgentTemplateItemKind, all: Iterable<string>) =>
308
+ [...all].filter((k) => !only || (only.kind === kind && only.key === k));
309
+ const systemNames = new Set(defaults.crons.map((c) => c.name));
310
+ await tx.agentTool.deleteMany({
311
+ where: {
312
+ agentId,
313
+ source: "custom",
314
+ pattern: { in: keys("tool", merged.tool.keys()) },
315
+ },
316
+ });
317
+ await tx.agentPlugin.deleteMany({
318
+ where: {
319
+ agentId,
320
+ source: "custom",
321
+ name: { in: keys("plugin", merged.plugin.keys()) },
322
+ },
323
+ });
324
+ await tx.agentCronJob.deleteMany({
325
+ where: {
326
+ agentId,
327
+ system: false,
328
+ source: "custom",
329
+ name: {
330
+ in: keys(
331
+ "cron",
332
+ [...merged.cron.keys()].filter((k) => !systemNames.has(k)),
333
+ ),
334
+ },
335
+ },
336
+ });
337
+ await tx.agentEnv.deleteMany({
338
+ where: {
339
+ agentId,
340
+ source: "custom",
341
+ key: {
342
+ in: keys(
343
+ "env",
344
+ [...merged.env.keys()].filter(
345
+ (k) => !TEMPLATE_ENV_DENYLIST.has(k.toUpperCase()),
346
+ ),
347
+ ),
348
+ },
349
+ },
212
350
  });
213
351
  }
214
352
 
@@ -0,0 +1,368 @@
1
+ /**
2
+ * admin/src/agent-template-triggers.integration.test.ts
3
+ * ATP-2.2: template fan-out on change, detach/reattach, reset-to-template and
4
+ * the /agents/{id}/template/* routes, 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 { AgentCronJobService } from "./agent-cron-jobs.ts";
12
+ import { AgentEnvService } from "./agent-envs.ts";
13
+ import { AgentMemberService } from "./agent-members.ts";
14
+ import { AgentPluginService } from "./agent-plugins.ts";
15
+ import { NoopAgentProvisioner } from "./agent-provisioner.ts";
16
+ import { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
17
+ import { AgentTemplateService } from "./agent-templates.ts";
18
+ import { AgentTokenService } from "./agent-tokens.ts";
19
+ import { AgentToolService } from "./agent-tools.ts";
20
+ import { AgentService } from "./agents.ts";
21
+ import {
22
+ type AdminDeps,
23
+ createAdminApp,
24
+ parseAdminApiKeys,
25
+ } from "./agents-api.ts";
26
+ import { createAdminPrismaClient } from "./prisma-client.ts";
27
+ import type { SpecialtyType } from "./specialty-types.ts";
28
+ import { makeStrictTokenCrypto } from "./token-crypto.ts";
29
+
30
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
31
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
32
+
33
+ const KEY = "ab".repeat(32);
34
+ const TYPE: SpecialtyType = {
35
+ name: "specialist",
36
+ displayName: "Specialist",
37
+ templatesDir: "workspace/",
38
+ tools: ["Read"],
39
+ requiredEnv: [],
40
+ };
41
+ const registry = {
42
+ getType: () => TYPE,
43
+ tryGetType: (s: string) => (s === TYPE.name ? TYPE : undefined),
44
+ listTypes: () => [{ name: TYPE.name, displayName: TYPE.displayName }],
45
+ };
46
+ const admin = { Authorization: "Bearer tok-admin" };
47
+
48
+ describeOrSkip("agent template triggers (integration)", () => {
49
+ let prisma: PrismaClient;
50
+ let engine: AgentTemplateReconcileService;
51
+ let templates: AgentTemplateService;
52
+ const crypto = makeStrictTokenCrypto(KEY);
53
+ if (!crypto) throw new Error("test crypto");
54
+
55
+ beforeEach(async () => {
56
+ prisma = createAdminPrismaClient(TEST_DB as string);
57
+ await prisma.agentTemplateItem.deleteMany();
58
+ await prisma.agentTemplate.deleteMany();
59
+ await prisma.agentCronJob.deleteMany();
60
+ await prisma.agentTool.deleteMany();
61
+ await prisma.agentPlugin.deleteMany();
62
+ await prisma.agentEnv.deleteMany();
63
+ await prisma.agentToken.deleteMany();
64
+ await prisma.agentMember.deleteMany();
65
+ await prisma.agent.deleteMany();
66
+ await prisma.accountInvite.deleteMany();
67
+ await prisma.accountMember.deleteMany();
68
+ await prisma.account.deleteMany();
69
+ engine = new AgentTemplateReconcileService(prisma, crypto, registry);
70
+ templates = new AgentTemplateService(prisma, crypto, registry, engine);
71
+ });
72
+
73
+ afterEach(async () => {
74
+ await prisma.$disconnect();
75
+ });
76
+
77
+ const mkAgent = (name: string, data: Record<string, unknown> = {}) =>
78
+ prisma.agent.create({ data: { name, specialty: "specialist", ...data } });
79
+
80
+ const envOf = async (agentId: string, key: string) => {
81
+ const row = await prisma.agentEnv.findUnique({
82
+ where: { agentId_key: { agentId, key } },
83
+ });
84
+ return row
85
+ ? { value: crypto.decrypt(row.value), source: row.source }
86
+ : null;
87
+ };
88
+
89
+ describe("fan-out on template change", () => {
90
+ it("updates template-sourced rows on following agents, skips detached ones and leaves custom rows alone", async () => {
91
+ const follower = await mkAgent("follower");
92
+ const custom = await mkAgent("custom");
93
+ const detached = await mkAgent("detached", { templateDetached: true });
94
+ await prisma.agentEnv.create({
95
+ data: {
96
+ agentId: custom.id,
97
+ key: "FLAG",
98
+ value: crypto.encrypt("mine"),
99
+ source: "custom",
100
+ },
101
+ });
102
+
103
+ await templates.replace({ kind: "admin" }, {}, [
104
+ { kind: "env", key: "FLAG", payload: { value: "v1" } },
105
+ { kind: "tool", key: "Grep" },
106
+ ]);
107
+ expect(await envOf(follower.id, "FLAG")).toEqual({
108
+ value: "v1",
109
+ source: "template",
110
+ });
111
+ expect(await envOf(custom.id, "FLAG")).toEqual({
112
+ value: "mine",
113
+ source: "custom",
114
+ });
115
+ expect(await envOf(detached.id, "FLAG")).toBeNull();
116
+ expect(
117
+ await prisma.agentTool.count({ where: { agentId: detached.id } }),
118
+ ).toBe(0);
119
+
120
+ // An edit of the template propagates again.
121
+ await templates.replace({ kind: "admin" }, {}, [
122
+ { kind: "env", key: "FLAG", payload: { value: "v2" } },
123
+ ]);
124
+ expect(await envOf(follower.id, "FLAG")).toEqual({
125
+ value: "v2",
126
+ source: "template",
127
+ });
128
+ expect(await envOf(custom.id, "FLAG")).toEqual({
129
+ value: "mine",
130
+ source: "custom",
131
+ });
132
+ expect(await envOf(detached.id, "FLAG")).toBeNull();
133
+ // Grep left the template, so the follower's template-sourced row is gone.
134
+ const grep = await prisma.agentTool.count({
135
+ where: { agentId: follower.id, pattern: "Grep" },
136
+ });
137
+ expect(grep).toBe(0);
138
+ });
139
+
140
+ it("scopes fan-out: an account template touches only that account, a specialty template only that type", async () => {
141
+ const acct = await prisma.account.create({
142
+ data: { name: "A", status: "active", maxAgents: 5 },
143
+ });
144
+ const inAcct = await mkAgent("in", { accountId: acct.id });
145
+ const outside = await mkAgent("out");
146
+
147
+ await templates.replace({ kind: "account", accountId: acct.id }, {}, [
148
+ { kind: "env", key: "ACCT", payload: { value: "1" } },
149
+ ]);
150
+ expect(await envOf(inAcct.id, "ACCT")).not.toBeNull();
151
+ expect(await envOf(outside.id, "ACCT")).toBeNull();
152
+
153
+ await templates.replace({ kind: "admin" }, { specialty: "specialist" }, [
154
+ { kind: "env", key: "TYPED", payload: { value: "1" } },
155
+ ]);
156
+ expect(await envOf(inAcct.id, "TYPED")).not.toBeNull();
157
+ expect(await envOf(outside.id, "TYPED")).not.toBeNull();
158
+ });
159
+
160
+ it("item edits and template deletion fan out too", async () => {
161
+ const agent = await mkAgent("a");
162
+ const { template } = await templates.replace({ kind: "admin" }, {}, []);
163
+ await templates.putItem({ kind: "admin" }, template.id, {
164
+ kind: "env",
165
+ key: "K",
166
+ payload: { value: "1" },
167
+ });
168
+ expect(await envOf(agent.id, "K")).toEqual({
169
+ value: "1",
170
+ source: "template",
171
+ });
172
+
173
+ await templates.deleteItem({ kind: "admin" }, template.id, "env", "K");
174
+ expect(await envOf(agent.id, "K")).toBeNull();
175
+
176
+ await templates.putItem({ kind: "admin" }, template.id, {
177
+ kind: "env",
178
+ key: "K",
179
+ payload: { value: "1" },
180
+ });
181
+ await templates.delete({ kind: "admin" }, template.id);
182
+ expect(await envOf(agent.id, "K")).toBeNull();
183
+ });
184
+
185
+ it("one failing agent does not block the rest, and the template write still succeeds", async () => {
186
+ const bad = await mkAgent("bad", { specialty: "specialist" });
187
+ const good = await mkAgent("good");
188
+ const realReconcile = engine.reconcile.bind(engine);
189
+ engine.reconcile = async (id, tx) => {
190
+ if (id === bad.id) throw new Error("boom");
191
+ return realReconcile(id, tx);
192
+ };
193
+ const originalError = console.error;
194
+ console.error = () => {};
195
+ try {
196
+ await templates.replace({ kind: "admin" }, {}, [
197
+ { kind: "env", key: "K", payload: { value: "1" } },
198
+ ]);
199
+ } finally {
200
+ console.error = originalError;
201
+ }
202
+ expect(await envOf(good.id, "K")).not.toBeNull();
203
+ expect(await prisma.agentTemplate.count()).toBe(1);
204
+ });
205
+ });
206
+
207
+ describe("reset to template", () => {
208
+ it("drops custom overrides and tombstones for template keys, restoring template rows", async () => {
209
+ const agent = await mkAgent("a");
210
+ await templates.replace({ kind: "admin" }, {}, [
211
+ { kind: "env", key: "A", payload: { value: "tpl" } },
212
+ { kind: "env", key: "B", payload: { value: "tpl" } },
213
+ { kind: "tool", key: "Grep" },
214
+ ]);
215
+ await new AgentEnvService(prisma, crypto).patch(agent.id, {
216
+ A: "edited",
217
+ });
218
+ await new AgentToolService(prisma).remove(
219
+ agent.id,
220
+ (
221
+ await prisma.agentTool.findFirstOrThrow({
222
+ where: { agentId: agent.id, pattern: "Grep" },
223
+ })
224
+ ).id,
225
+ );
226
+ await prisma.agentEnv.create({
227
+ data: { agentId: agent.id, key: "OWN", value: crypto.encrypt("x") },
228
+ });
229
+ expect(await envOf(agent.id, "A")).toEqual({
230
+ value: "edited",
231
+ source: "custom",
232
+ });
233
+
234
+ await engine.reset(agent.id, { kind: "env", key: "A" });
235
+ expect(await envOf(agent.id, "A")).toEqual({
236
+ value: "tpl",
237
+ source: "template",
238
+ });
239
+ // Not the targeted key: the tombstone is still there.
240
+ expect(
241
+ (
242
+ await prisma.agentTool.findFirst({
243
+ where: { agentId: agent.id, pattern: "Grep" },
244
+ })
245
+ )?.enabled,
246
+ ).toBe(false);
247
+
248
+ await engine.reset(agent.id);
249
+ expect(
250
+ (
251
+ await prisma.agentTool.findFirst({
252
+ where: { agentId: agent.id, pattern: "Grep" },
253
+ })
254
+ )?.source,
255
+ ).toBe("template");
256
+ // Keys the template does not define are untouched.
257
+ expect(await envOf(agent.id, "OWN")).toEqual({
258
+ value: "x",
259
+ source: "custom",
260
+ });
261
+ });
262
+
263
+ it("refuses a detached agent", async () => {
264
+ const agent = await mkAgent("a", { templateDetached: true });
265
+ await expect(engine.reset(agent.id)).rejects.toThrow(/detached/);
266
+ });
267
+ });
268
+
269
+ describe("/agents/{id}/template routes", () => {
270
+ let app: ReturnType<typeof createAdminApp>;
271
+
272
+ beforeEach(() => {
273
+ app = createAdminApp({
274
+ agentService: new AgentService(prisma, registry as never),
275
+ agentEnvService: new AgentEnvService(prisma, crypto),
276
+ agentCronJobService: new AgentCronJobService(prisma),
277
+ agentToolService: new AgentToolService(prisma),
278
+ agentTokenService: new AgentTokenService(prisma),
279
+ agentPluginService: new AgentPluginService(prisma),
280
+ agentMemberService: new AgentMemberService(prisma),
281
+ specialtyRegistry: registry as never,
282
+ agentTemplateReconcileService: engine,
283
+ prisma,
284
+ provisioner: new NoopAgentProvisioner(),
285
+ sessionSecret: "test-admin-session-secret-32-bytes!",
286
+ adminApiKeys: parseAdminApiKeys("root:tok-admin:*"),
287
+ } as unknown as AdminDeps);
288
+ });
289
+
290
+ const post = (path: string, body?: unknown) =>
291
+ app.request(path, {
292
+ method: "POST",
293
+ headers: { ...admin, "Content-Type": "application/json" },
294
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
295
+ });
296
+
297
+ it("reconcile applies the template; detach stops it; reattach resumes; reset restores", async () => {
298
+ const agent = await mkAgent("a", { templateDetached: true });
299
+ await prisma.agentTemplate
300
+ .create({ data: { accountId: null, specialty: null } })
301
+ .then((t) =>
302
+ prisma.agentTemplateItem.create({
303
+ data: {
304
+ templateId: t.id,
305
+ kind: "env",
306
+ key: "K",
307
+ payload: { value: crypto.encrypt("1") },
308
+ },
309
+ }),
310
+ );
311
+
312
+ let res = await post(`/agents/${agent.id}/template/reconcile`);
313
+ expect(res.status).toBe(200);
314
+ expect(((await res.json()) as { status: string }).status).toBe(
315
+ "detached",
316
+ );
317
+ expect(await envOf(agent.id, "K")).toBeNull();
318
+
319
+ res = await post(`/agents/${agent.id}/template/reattach`);
320
+ expect(res.status).toBe(200);
321
+ expect(await envOf(agent.id, "K")).toEqual({
322
+ value: "1",
323
+ source: "template",
324
+ });
325
+
326
+ await new AgentEnvService(prisma, crypto).patch(agent.id, { K: "mine" });
327
+ res = await post(`/agents/${agent.id}/template/reset`, {
328
+ kind: "env",
329
+ key: "K",
330
+ });
331
+ expect(res.status).toBe(200);
332
+ expect(await envOf(agent.id, "K")).toEqual({
333
+ value: "1",
334
+ source: "template",
335
+ });
336
+
337
+ res = await post(`/agents/${agent.id}/template/detach`);
338
+ expect(await res.json()).toEqual({ templateDetached: true });
339
+ expect(
340
+ (await prisma.agent.findUniqueOrThrow({ where: { id: agent.id } }))
341
+ .templateDetached,
342
+ ).toBe(true);
343
+ res = await post(`/agents/${agent.id}/template/reset`, {});
344
+ expect(res.status).toBe(409);
345
+ });
346
+
347
+ it("404s for an unknown agent", async () => {
348
+ expect((await post("/agents/nope/template/reconcile")).status).toBe(404);
349
+ expect((await post("/agents/nope/template/detach")).status).toBe(404);
350
+ });
351
+
352
+ it("POST /agents with templateDetached:true and env creates a detached agent with the explicit env", async () => {
353
+ const res = await post("/agents", {
354
+ name: "viaapi",
355
+ specialty: "specialist",
356
+ templateDetached: true,
357
+ env: { MINE: "1" },
358
+ });
359
+ expect(res.status).toBe(200);
360
+ const { id } = (await res.json()) as { id: string };
361
+ expect(
362
+ (await prisma.agent.findUniqueOrThrow({ where: { id } }))
363
+ .templateDetached,
364
+ ).toBe(true);
365
+ expect(await envOf(id, "MINE")).toEqual({ value: "1", source: "custom" });
366
+ });
367
+ });
368
+ });