@app-vitals/agent-admin 1.48.0 → 1.49.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.48.0",
3
+ "version": "1.49.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.135.0",
45
- "@app-vitals/agent-lib": "1.48.0",
45
+ "@app-vitals/agent-lib": "1.49.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
@@ -0,0 +1,415 @@
1
+ /**
2
+ * admin/src/admin-ui-agent-template.smoke.test.ts
3
+ * Smoke tests for the ATP-2.4 agent template UI via app.request(): inherited /
4
+ * custom badges on the agent page, detach / reattach, reset to template, and
5
+ * the provisioning form's template defaults and opt-out. In-memory doubles.
6
+ */
7
+
8
+ import { beforeAll, describe, expect, it } from "bun:test";
9
+ import {
10
+ AGENT_ID,
11
+ MOCK_CRON,
12
+ MOCK_TOOL,
13
+ makeMockDeps,
14
+ makeSessionCookie,
15
+ } from "./admin-ui.fixtures.ts";
16
+ import { createAdminUIApp } from "./admin-ui.ts";
17
+ import { resolveDefaultSpecialtyName } from "./specialty-types.ts";
18
+ import type { TemplateView } from "./agent-templates.ts";
19
+
20
+ const TYPE = resolveDefaultSpecialtyName();
21
+ const d = new Date("2024-01-01");
22
+
23
+ let cookie: string;
24
+ beforeAll(async () => {
25
+ cookie = await makeSessionCookie();
26
+ });
27
+
28
+ interface ApiCall {
29
+ path: string;
30
+ method: string;
31
+ body: unknown;
32
+ }
33
+
34
+ /** In-memory stand-in for the agents API app's `request`. */
35
+ function fakeAgentsApi(opts: { status?: number } = {}) {
36
+ const calls: ApiCall[] = [];
37
+ const api = async (path: string, init?: RequestInit) => {
38
+ calls.push({
39
+ path,
40
+ method: init?.method ?? "GET",
41
+ body: init?.body ? JSON.parse(String(init.body)) : undefined,
42
+ });
43
+ const status = opts.status ?? 200;
44
+ return status === 200
45
+ ? Response.json({ ok: true })
46
+ : Response.json({ error: "agent is detached" }, { status });
47
+ };
48
+ return { api, calls };
49
+ }
50
+
51
+ function detailDeps(
52
+ over: {
53
+ detached?: boolean;
54
+ agentsApi?: ReturnType<typeof fakeAgentsApi>["api"];
55
+ } = {},
56
+ ) {
57
+ const base = makeMockDeps();
58
+ return makeMockDeps({
59
+ ...(over.agentsApi ? { agentsApi: over.agentsApi } : {}),
60
+ agentService: {
61
+ ...base.agentService,
62
+ getDetail: async () => ({
63
+ ...(await base.agentService.getDetail(AGENT_ID)),
64
+ id: AGENT_ID,
65
+ name: "Test Agent",
66
+ slackId: null,
67
+ selfHosted: false,
68
+ specialty: TYPE,
69
+ createdAt: d,
70
+ updatedAt: d,
71
+ repos: [],
72
+ reviewAuthorAllowlist: [],
73
+ patchAuthorAllowlist: [],
74
+ restrictSlackToMembers: false,
75
+ missingRequiredEnv: [],
76
+ templateDetached: over.detached ?? false,
77
+ }),
78
+ },
79
+ agentEnvService: {
80
+ ...base.agentEnvService,
81
+ getByAgentId: async () => ({
82
+ env: { TPL_KEY: "a", MINE: "b" },
83
+ secretKeys: [],
84
+ sources: { TPL_KEY: "template", MINE: "custom" },
85
+ }),
86
+ },
87
+ agentToolService: {
88
+ ...base.agentToolService,
89
+ list: async () => [
90
+ { ...MOCK_TOOL, id: "t-tpl", pattern: "Read", source: "template" },
91
+ { ...MOCK_TOOL, id: "t-own", pattern: "Bash(ls:*)", source: "custom" },
92
+ ],
93
+ },
94
+ agentPluginService: {
95
+ ...base.agentPluginService,
96
+ list: async () => [
97
+ {
98
+ id: "p-tpl",
99
+ agentId: AGENT_ID,
100
+ source: "template",
101
+ name: "tpl-plugin",
102
+ version: null,
103
+ enabled: true,
104
+ createdAt: d,
105
+ updatedAt: d,
106
+ },
107
+ ],
108
+ },
109
+ agentCronJobService: {
110
+ ...base.agentCronJobService,
111
+ listWithRunSummary: async () => [
112
+ {
113
+ ...MOCK_CRON,
114
+ id: "c-tpl",
115
+ name: "tpl-cron",
116
+ source: "template",
117
+ lastRun: null,
118
+ runCountToday: 0,
119
+ },
120
+ ],
121
+ },
122
+ });
123
+ }
124
+
125
+ const get = (app: ReturnType<typeof createAdminUIApp>, path: string) =>
126
+ app.request(path, { headers: { Cookie: `admin_session=${cookie}` } });
127
+
128
+ const post = (
129
+ app: ReturnType<typeof createAdminUIApp>,
130
+ path: string,
131
+ fields: Record<string, string> = {},
132
+ ) =>
133
+ app.request(path, {
134
+ method: "POST",
135
+ body: new URLSearchParams(fields).toString(),
136
+ headers: {
137
+ "Content-Type": "application/x-www-form-urlencoded",
138
+ Cookie: `admin_session=${cookie}`,
139
+ },
140
+ });
141
+
142
+ describe("agent page template badges (ATP-2.4)", () => {
143
+ it("marks every env, tool, plugin and cron as inherited or custom", async () => {
144
+ const { api } = fakeAgentsApi();
145
+ const html = await (
146
+ await get(
147
+ createAdminUIApp(detailDeps({ agentsApi: api })),
148
+ `/admin/agents/${AGENT_ID}`,
149
+ )
150
+ ).text();
151
+ // 1 env + 1 tool + 1 plugin + 1 cron inherited; 1 env + 1 tool custom.
152
+ expect(html.match(/data-source="template"/g)).toHaveLength(4);
153
+ expect(html.match(/data-source="custom"/g)).toHaveLength(2);
154
+ expect(html).toContain("badge-template");
155
+ expect(html).toContain("badge-custom");
156
+ });
157
+
158
+ it("shows no template UI when the agents API seam is not wired", async () => {
159
+ const html = await (
160
+ await get(createAdminUIApp(detailDeps()), `/admin/agents/${AGENT_ID}`)
161
+ ).text();
162
+ expect(html).not.toContain("data-source=");
163
+ expect(html).not.toContain("/template/detach");
164
+ });
165
+
166
+ it("an inherited env row flips to custom after it is edited", async () => {
167
+ const sources: Record<string, string> = { TPL_KEY: "template" };
168
+ const base = makeMockDeps();
169
+ const { api } = fakeAgentsApi();
170
+ const app = createAdminUIApp(
171
+ makeMockDeps({
172
+ agentsApi: api,
173
+ agentEnvService: {
174
+ ...base.agentEnvService,
175
+ getByAgentId: async () => ({
176
+ env: { TPL_KEY: "v" },
177
+ secretKeys: [],
178
+ sources: { ...sources },
179
+ }),
180
+ // Mirrors AgentEnvService.patch: an explicit write is custom.
181
+ patch: async (_id: string, env: Record<string, string>) => {
182
+ for (const k of Object.keys(env)) sources[k] = "custom";
183
+ },
184
+ },
185
+ }),
186
+ );
187
+ const before = await (await get(app, `/admin/agents/${AGENT_ID}`)).text();
188
+ expect(before).toContain('data-source="template"');
189
+ await post(app, `/admin/agents/${AGENT_ID}/envs`, {
190
+ key: "TPL_KEY",
191
+ value: "mine",
192
+ });
193
+ const after = await (await get(app, `/admin/agents/${AGENT_ID}`)).text();
194
+ expect(after).not.toContain('data-source="template"');
195
+ expect(after).toContain('data-source="custom"');
196
+ });
197
+ });
198
+
199
+ describe("detach / reattach (ATP-2.4)", () => {
200
+ it("attached agent offers Detach; POST calls the detach endpoint", async () => {
201
+ const { api, calls } = fakeAgentsApi();
202
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
203
+ const html = await (await get(app, `/admin/agents/${AGENT_ID}`)).text();
204
+ expect(html).toContain(`/admin/agents/${AGENT_ID}/template/detach`);
205
+ expect(html).not.toContain(`/template/reattach`);
206
+
207
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/detach`);
208
+ expect(res.status).toBe(302);
209
+ expect(res.headers.get("Location")).toContain(`/admin/agents/${AGENT_ID}`);
210
+ expect(calls).toEqual([
211
+ {
212
+ path: `/agents/${AGENT_ID}/template/detach`,
213
+ method: "POST",
214
+ body: undefined,
215
+ },
216
+ ]);
217
+ });
218
+
219
+ it("detached agent shows a Detached state with Reattach; POST calls the reattach endpoint", async () => {
220
+ const { api, calls } = fakeAgentsApi();
221
+ const app = createAdminUIApp(
222
+ detailDeps({ agentsApi: api, detached: true }),
223
+ );
224
+ const html = await (await get(app, `/admin/agents/${AGENT_ID}`)).text();
225
+ expect(html).toContain("Detached from template");
226
+ expect(html).toContain(`/admin/agents/${AGENT_ID}/template/reattach`);
227
+ expect(html).not.toContain(`/template/detach`);
228
+ // No per-item reset while detached (the API answers 409).
229
+ expect(html).not.toContain(`/template/reset`);
230
+
231
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/reattach`);
232
+ expect(res.status).toBe(302);
233
+ expect(calls.map((c) => c.path)).toEqual([
234
+ `/agents/${AGENT_ID}/template/reattach`,
235
+ ]);
236
+ });
237
+
238
+ it("surfaces an API failure as an error on the agent page", async () => {
239
+ const { api } = fakeAgentsApi({ status: 409 });
240
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
241
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/detach`);
242
+ expect(res.status).toBe(302);
243
+ expect(decodeURIComponent(res.headers.get("Location") ?? "")).toContain(
244
+ "agent is detached",
245
+ );
246
+ });
247
+
248
+ it("is 404-safe without the agents API seam", async () => {
249
+ const res = await post(
250
+ createAdminUIApp(detailDeps()),
251
+ `/admin/agents/${AGENT_ID}/template/detach`,
252
+ );
253
+ expect(res.status).toBe(404);
254
+ });
255
+ });
256
+
257
+ describe("reset to template (ATP-2.4)", () => {
258
+ it("custom rows get a per-item reset; template rows do not", async () => {
259
+ const { api } = fakeAgentsApi();
260
+ const html = await (
261
+ await get(
262
+ createAdminUIApp(detailDeps({ agentsApi: api })),
263
+ `/admin/agents/${AGENT_ID}`,
264
+ )
265
+ ).text();
266
+ // custom env MINE and custom tool Bash(ls:*) -> 2 per-item resets, plus
267
+ // the agent-wide reset.
268
+ expect(html.match(/name="kind" value="(env|tool)"/g)).toHaveLength(2);
269
+ expect(html).toContain(`/admin/agents/${AGENT_ID}/template/reset`);
270
+ });
271
+
272
+ it("POST with kind and key resets one item", async () => {
273
+ const { api, calls } = fakeAgentsApi();
274
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
275
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/reset`, {
276
+ kind: "env",
277
+ key: "MINE",
278
+ });
279
+ expect(res.status).toBe(302);
280
+ expect(calls).toEqual([
281
+ {
282
+ path: `/agents/${AGENT_ID}/template/reset`,
283
+ method: "POST",
284
+ body: { kind: "env", key: "MINE" },
285
+ },
286
+ ]);
287
+ });
288
+
289
+ it("POST without kind/key resets everything", async () => {
290
+ const { api, calls } = fakeAgentsApi();
291
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
292
+ await post(app, `/admin/agents/${AGENT_ID}/template/reset`);
293
+ expect(calls[0]?.body).toEqual({});
294
+ });
295
+
296
+ it("rejects an unknown kind without calling the API", async () => {
297
+ const { api, calls } = fakeAgentsApi();
298
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
299
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/reset`, {
300
+ kind: "bogus",
301
+ key: "x",
302
+ });
303
+ expect(res.status).toBe(302);
304
+ expect(decodeURIComponent(res.headers.get("Location") ?? "")).toContain(
305
+ "Unknown",
306
+ );
307
+ expect(calls).toHaveLength(0);
308
+ });
309
+ });
310
+
311
+ describe("provisioning form (ATP-2.4)", () => {
312
+ const template: TemplateView = {
313
+ id: "t1",
314
+ accountId: null,
315
+ specialty: null,
316
+ createdAt: d,
317
+ updatedAt: d,
318
+ items: [
319
+ {
320
+ kind: "env",
321
+ key: "LOG_LEVEL",
322
+ payload: { value: "debug" },
323
+ updatedAt: d,
324
+ },
325
+ { kind: "tool", key: "Read", payload: {}, updatedAt: d },
326
+ ],
327
+ };
328
+ const templateService = {
329
+ list: async () => [template],
330
+ replace: async () => {
331
+ throw new Error("unused");
332
+ },
333
+ putItem: async () => {
334
+ throw new Error("unused");
335
+ },
336
+ deleteItem: async () => {
337
+ throw new Error("unused");
338
+ },
339
+ delete: async () => {},
340
+ };
341
+
342
+ function createDeps() {
343
+ const created: Array<Record<string, unknown>> = [];
344
+ const patched: Array<Record<string, string>> = [];
345
+ const plain = makeMockDeps();
346
+ const deps = makeMockDeps({
347
+ templateService,
348
+ agentService: {
349
+ ...plain.agentService,
350
+ create: async (
351
+ ...args: Parameters<typeof plain.agentService.create>
352
+ ) => {
353
+ created.push(args[0] as unknown as Record<string, unknown>);
354
+ return plain.agentService.create(...args);
355
+ },
356
+ },
357
+ agentEnvService: {
358
+ ...plain.agentEnvService,
359
+ patch: async (_id: string, env: Record<string, string>) => {
360
+ patched.push(env);
361
+ },
362
+ },
363
+ });
364
+ return { deps, created, patched };
365
+ }
366
+
367
+ it("shows template-provided values as defaults and an opt-out checkbox", async () => {
368
+ const html = await (
369
+ await get(createAdminUIApp(createDeps().deps), "/admin/agents/new")
370
+ ).text();
371
+ expect(html).toContain('name="templateDetached"');
372
+ expect(html).toContain("LOG_LEVEL");
373
+ expect(html).toContain("debug");
374
+ expect(html).toContain("Read");
375
+ expect(html).toContain('name="env"');
376
+ });
377
+
378
+ it("omits the template section when no template service is wired", async () => {
379
+ const html = await (
380
+ await get(createAdminUIApp(makeMockDeps()), "/admin/agents/new")
381
+ ).text();
382
+ expect(html).not.toContain('name="templateDetached"');
383
+ });
384
+
385
+ it("opt-out checkbox sends templateDetached:true", async () => {
386
+ const { deps, created } = createDeps();
387
+ const res = await post(createAdminUIApp(deps), "/admin/agents", {
388
+ name: "Test Agent",
389
+ type: TYPE,
390
+ templateDetached: "true",
391
+ });
392
+ expect(res.status).toBe(302);
393
+ expect(created[0]?.templateDetached).toBe(true);
394
+ });
395
+
396
+ it("without the checkbox the agent follows the template", async () => {
397
+ const { deps, created } = createDeps();
398
+ await post(createAdminUIApp(deps), "/admin/agents", {
399
+ name: "Test Agent",
400
+ type: TYPE,
401
+ });
402
+ expect(created[0]?.templateDetached).not.toBe(true);
403
+ });
404
+
405
+ it("form-entered env values are passed as explicit overrides", async () => {
406
+ const { deps, patched } = createDeps();
407
+ await post(createAdminUIApp(deps), "/admin/agents", {
408
+ name: "Test Agent",
409
+ type: TYPE,
410
+ env: "LOG_LEVEL=info\n# comment\n\nEXTRA = two words",
411
+ });
412
+ expect(patched.some((e) => e.LOG_LEVEL === "info")).toBe(true);
413
+ expect(patched.some((e) => e.EXTRA === "two words")).toBe(true);
414
+ });
415
+ });
@@ -128,6 +128,8 @@ export interface AgentDetail {
128
128
  * state.
129
129
  */
130
130
  bakedMarketplaces?: string[];
131
+ /** ATP-2.4: the agent no longer follows its template. */
132
+ templateDetached?: boolean;
131
133
  }
132
134
 
133
135
  export interface CronJobItem {
@@ -141,6 +143,8 @@ export interface CronJobItem {
141
143
  system: boolean;
142
144
  parentCronId: string | null;
143
145
  preCheck?: string | null;
146
+ /** ATP-2.4: `template` (inherited) or `custom`. */
147
+ source?: string;
144
148
  lastRun?: {
145
149
  startedAt: Date;
146
150
  completedAt: Date | null;
@@ -179,6 +183,8 @@ export interface ToolItem {
179
183
  id: string;
180
184
  pattern: string;
181
185
  enabled: boolean;
186
+ /** ATP-2.4: `template` (inherited) or `custom`. */
187
+ source?: string;
182
188
  createdAt: Date;
183
189
  }
184
190
 
@@ -194,6 +200,8 @@ export interface PluginItem {
194
200
  name: string;
195
201
  version: string | null;
196
202
  enabled: boolean;
203
+ /** ATP-2.4: `template` (inherited) or `custom`. */
204
+ source?: string;
197
205
  createdAt: Date;
198
206
  }
199
207
 
@@ -502,6 +510,16 @@ function runtimeSectionsOnchange(display: "" | "none"): string {
502
510
  .join(";");
503
511
  }
504
512
 
513
+ /** ATP-2.4: one template-provided default on the provisioning form. */
514
+ export interface NewAgentTemplateItem {
515
+ kind: string;
516
+ key: string;
517
+ /** Display value (env only; secrets already masked). */
518
+ value?: string;
519
+ /** Human label of the template scope. */
520
+ scope: string;
521
+ }
522
+
505
523
  export function renderNewLocalAgentPage(
506
524
  userName: string,
507
525
  types: SpecialtyOption[],
@@ -516,6 +534,12 @@ export function renderNewLocalAgentPage(
516
534
  * the self-serve specialty (the server forces it regardless).
517
535
  */
518
536
  selfServe?: { remaining: number; max: number; contactEmail: string };
537
+ /**
538
+ * ATP-2.4: present when agent templates are available. Lists the
539
+ * template-provided defaults and adds the opt-out checkbox; `allowEnv`
540
+ * (platform admins) adds the explicit env override box.
541
+ */
542
+ template?: { items: NewAgentTemplateItem[]; allowEnv: boolean };
519
543
  },
520
544
  ): string {
521
545
  const error = opts?.error;
@@ -591,6 +615,46 @@ export function renderNewLocalAgentPage(
591
615
  </ul>
592
616
  </div>`
593
617
  : "";
618
+ const tplOpts = opts?.template;
619
+ const templateFieldsetHtml = tplOpts
620
+ ? `<fieldset id="template-section" style="border:1px solid #e8e8ee;border-radius:8px;padding:16px">
621
+ <legend style="font-size:13px;font-weight:600;padding:0 8px">Agent template</legend>
622
+ ${
623
+ tplOpts.items.length === 0
624
+ ? `<p style="font-size:13px;color:#6b7280;margin-bottom:12px">No template items apply to new agents.</p>`
625
+ : `<p style="font-size:13px;color:#6b7280;margin-bottom:8px">New agents start with these template defaults${tplOpts.allowEnv ? "; anything you enter below overrides them" : ""}:</p>
626
+ <table class="data-table" style="margin-bottom:12px">
627
+ <thead><tr><th>Kind</th><th>Key</th><th>Default</th><th>Applies to</th></tr></thead>
628
+ <tbody>${tplOpts.items
629
+ .map(
630
+ (i) =>
631
+ `<tr><td>${escapeHtml(i.kind)}</td><td class="mono">${escapeHtml(i.key)}</td><td class="mono">${i.value === undefined ? "—" : escapeHtml(i.value)}</td><td>${escapeHtml(i.scope)}</td></tr>`,
632
+ )
633
+ .join("")}</tbody>
634
+ </table>`
635
+ }
636
+ ${
637
+ tplOpts.allowEnv
638
+ ? `<div class="form-group">
639
+ <label class="form-label" for="env">Env overrides (optional)</label>
640
+ <textarea id="env" name="env" class="form-input mono" rows="3" placeholder="KEY=value (one per line)"></textarea>
641
+ <p style="font-size:12px;color:#6b7280;margin-top:4px">
642
+ Values entered here win over the template defaults above and stay fixed when the template changes.
643
+ </p>
644
+ </div>`
645
+ : ""
646
+ }
647
+ <div class="form-group" style="margin-bottom:0">
648
+ <label style="font-size:13px">
649
+ <input type="checkbox" name="templateDetached" value="true" />
650
+ Start without the template (opt out)
651
+ </label>
652
+ <p style="font-size:12px;color:#6b7280;margin-top:4px">
653
+ The agent gets only its built-in defaults and ignores later template changes until you reattach it.
654
+ </p>
655
+ </div>
656
+ </fieldset>`
657
+ : "";
594
658
  const typeFieldHtml = selfServe
595
659
  ? `<input type="hidden" name="type" value="${escapeHtml(getSelfServeSpecialty())}" />`
596
660
  : `<div class="form-group">
@@ -826,6 +890,7 @@ export function renderNewLocalAgentPage(
826
890
  </div>
827
891
  </div>
828
892
  </fieldset>
893
+ ${templateFieldsetHtml}
829
894
  <div>
830
895
  <button type="submit" class="btn btn-primary">Create agent →</button>
831
896
  <a href="/admin/agents" class="btn btn-secondary" style="margin-left:8px">Cancel</a>
@@ -938,7 +1003,12 @@ function renderGroup(name: string, stat: string, bodyHtml: string): string {
938
1003
  export function renderAgentDetailPage(
939
1004
  agent: AgentDetail,
940
1005
  envResult:
941
- | { env: Record<string, string>; secretKeys: string[] }
1006
+ | {
1007
+ env: Record<string, string>;
1008
+ secretKeys: string[];
1009
+ /** ATP-2.4: row source per key. */
1010
+ sources?: Record<string, string>;
1011
+ }
942
1012
  | Record<string, string>,
943
1013
  crons: CronJobItem[],
944
1014
  tools: ToolItem[],
@@ -995,6 +1065,12 @@ export function renderAgentDetailPage(
995
1065
  * could be listed. Absent means unknown: no coverage warning is shown.
996
1066
  */
997
1067
  installationRepos?: readonly string[];
1068
+ /**
1069
+ * ATP-2.4: present when agent templates are available. Turns on the
1070
+ * inherited/custom badges, the detach/reattach toggle and the per-item
1071
+ * reset controls.
1072
+ */
1073
+ template?: { detached: boolean };
998
1074
  },
999
1075
  ): string {
1000
1076
  // Reference time for relative timestamps — injected by tests for determinism,
@@ -1016,19 +1092,66 @@ export function renderAgentDetailPage(
1016
1092
  : [],
1017
1093
  );
1018
1094
 
1095
+ // ATP-2.4: inherited/custom badge, per-item reset and agent-wide controls.
1096
+ const tpl = opts?.template;
1097
+ const agentPath = `/admin/agents/${escapeHtml(agent.id)}`;
1098
+ const sourceBadge = (source: string | undefined): string =>
1099
+ !tpl || (source !== "template" && source !== "custom")
1100
+ ? ""
1101
+ : source === "template"
1102
+ ? ` <span class="badge badge-template" data-source="template" title="Inherited from the agent template">template</span>`
1103
+ : ` <span class="badge badge-custom" data-source="custom" title="Set on this agent; overrides the template">custom</span>`;
1104
+ const resetForm = (
1105
+ source: string | undefined,
1106
+ kind: string,
1107
+ key: string | null | undefined,
1108
+ ): string =>
1109
+ !tpl || tpl.detached || source !== "custom" || !key
1110
+ ? ""
1111
+ : `<form method="POST" action="${agentPath}/template/reset" style="display:inline;margin-left:4px">
1112
+ <input type="hidden" name="kind" value="${kind}" />
1113
+ <input type="hidden" name="key" value="${escapeHtml(key)}" />
1114
+ <button type="submit" class="btn btn-secondary" style="font-size:11px;padding:3px 8px" title="Drop this agent's override and restore the template value">Reset to template</button>
1115
+ </form>`;
1116
+ const envSources =
1117
+ envResult && "sources" in envResult
1118
+ ? ((envResult as { sources?: Record<string, string> }).sources ?? {})
1119
+ : {};
1120
+ const templateCard = tpl
1121
+ ? `<div class="card" id="template">
1122
+ <div class="card-title">Agent template</div>
1123
+ ${
1124
+ tpl.detached
1125
+ ? `<p style="font-size:13px;margin-bottom:12px"><span class="badge badge-gray">Detached from template</span>
1126
+ Template changes no longer reach this agent. Reattaching reconciles it against the template now; your custom rows are kept.</p>
1127
+ <form method="POST" action="${agentPath}/template/reattach">
1128
+ <button type="submit" class="btn btn-primary">Reattach to template</button>
1129
+ </form>`
1130
+ : `<p style="font-size:13px;margin-bottom:12px"><span class="badge badge-template">Following template</span>
1131
+ Rows marked <em>template</em> are managed from Settings &gt; Templates; editing one makes it <em>custom</em>.</p>
1132
+ <form method="POST" action="${agentPath}/template/detach" style="display:inline">
1133
+ <button type="submit" class="btn btn-secondary">Detach from template</button>
1134
+ </form>
1135
+ <form method="POST" action="${agentPath}/template/reset" style="display:inline;margin-left:8px">
1136
+ <button type="submit" class="btn btn-secondary" title="Drop every override of a key the template defines">Reset all to template</button>
1137
+ </form>`
1138
+ }
1139
+ </div>`
1140
+ : "";
1141
+
1019
1142
  const envRows =
1020
1143
  Object.keys(envVars).length === 0
1021
1144
  ? `<tr><td colspan="3" class="empty-state">No env vars set.</td></tr>`
1022
1145
  : Object.entries(envVars)
1023
1146
  .map(
1024
1147
  ([k]) => `<tr>
1025
- <td class="mono">${escapeHtml(k)}${secretKeySet.has(k) ? ' <span title="Secret">🔒</span>' : ""}</td>
1148
+ <td class="mono">${escapeHtml(k)}${secretKeySet.has(k) ? ' <span title="Secret">🔒</span>' : ""}${sourceBadge(envSources[k])}</td>
1026
1149
  <td class="mono" style="color:#6b7280">••••••••</td>
1027
1150
  <td>
1028
1151
  <form method="POST" action="/admin/agents/${escapeHtml(agent.id)}/envs/delete" style="display:inline">
1029
1152
  <input type="hidden" name="key" value="${escapeHtml(k)}" />
1030
1153
  <button type="submit" class="btn btn-danger" style="font-size:11px;padding:3px 8px">Delete</button>
1031
- </form>
1154
+ </form>${resetForm(envSources[k], "env", k)}
1032
1155
  </td>
1033
1156
  </tr>`,
1034
1157
  )
@@ -1232,13 +1355,13 @@ export function renderAgentDetailPage(
1232
1355
 
1233
1356
  return `<tr>
1234
1357
  <td class="mono">${escapeHtml(c.schedule)}</td>
1235
- <td style="max-width:280px;overflow:hidden;text-overflow:ellipsis">${escapeHtml(c.name ? `${c.name}: ${c.prompt}` : c.prompt)}</td>
1358
+ <td style="max-width:280px;overflow:hidden;text-overflow:ellipsis">${escapeHtml(c.name ? `${c.name}: ${c.prompt}` : c.prompt)}${sourceBadge(c.system ? undefined : c.source)}</td>
1236
1359
  <td class="mono" style="font-size:11px;color:#6b7280;max-width:170px;overflow:hidden;text-overflow:ellipsis">${c.preCheck ? escapeHtml(c.preCheck) : "—"}</td>
1237
1360
  <td>${c.channel ? escapeHtml(c.channel) : c.user ? escapeHtml(c.user) : "—"}</td>
1238
1361
  <td><span class="badge ${c.enabled ? "badge-green" : "badge-gray"}">${c.enabled ? "enabled" : "disabled"}</span></td>
1239
1362
  <td style="font-size:11px">${lastRunHtml}</td>
1240
1363
  <td class="col-created">${escapeHtml(new Date(c.createdAt).toLocaleDateString("en-US", { timeZone: timezone }))}</td>
1241
- <td style="white-space:nowrap">${actions}${editForm}</td>
1364
+ <td style="white-space:nowrap">${actions}${resetForm(c.system ? undefined : c.source, "cron", c.name)}${editForm}</td>
1242
1365
  </tr>
1243
1366
  ${nestedPhasesRow}`;
1244
1367
  }
@@ -1259,7 +1382,7 @@ export function renderAgentDetailPage(
1259
1382
  : tools
1260
1383
  .map(
1261
1384
  (t) => `<tr>
1262
- <td class="mono">${escapeHtml(t.pattern)}</td>
1385
+ <td class="mono">${escapeHtml(t.pattern)}${sourceBadge(t.source)}</td>
1263
1386
  <td><span class="badge ${t.enabled ? "badge-green" : "badge-gray"}">${t.enabled ? "enabled" : "disabled"}</span></td>
1264
1387
  <td>${escapeHtml(new Date(t.createdAt).toLocaleDateString("en-US", { timeZone: timezone }))}</td>
1265
1388
  <td style="white-space:nowrap">
@@ -1269,7 +1392,7 @@ export function renderAgentDetailPage(
1269
1392
  </form>
1270
1393
  <form method="POST" action="/admin/agents/${escapeHtml(agent.id)}/tools/${escapeHtml(t.id)}/delete" style="display:inline;margin-left:4px">
1271
1394
  <button type="submit" class="btn btn-danger" style="font-size:11px;padding:3px 8px">Delete</button>
1272
- </form>
1395
+ </form>${resetForm(t.source, "tool", t.pattern)}
1273
1396
  </td>
1274
1397
  </tr>`,
1275
1398
  )
@@ -1301,7 +1424,7 @@ export function renderAgentDetailPage(
1301
1424
  : plugins
1302
1425
  .map(
1303
1426
  (p) => `<tr>
1304
- <td class="mono">${escapeHtml(p.name)}</td>
1427
+ <td class="mono">${escapeHtml(p.name)}${sourceBadge(p.source)}</td>
1305
1428
  <td class="mono">${p.version ? escapeHtml(p.version) : "latest"}</td>
1306
1429
  <td><span class="badge ${p.enabled ? "badge-green" : "badge-gray"}">${p.enabled ? "enabled" : "disabled"}</span></td>
1307
1430
  <td>${escapeHtml(new Date(p.createdAt).toLocaleDateString("en-US", { timeZone: timezone }))}</td>
@@ -1309,7 +1432,7 @@ export function renderAgentDetailPage(
1309
1432
  <form method="POST" action="/admin/agents/${escapeHtml(agent.id)}/plugins/delete" style="display:inline">
1310
1433
  <input type="hidden" name="pluginId" value="${escapeHtml(p.id)}" />
1311
1434
  <button type="submit" class="btn btn-danger" style="font-size:11px;padding:3px 8px">Remove</button>
1312
- </form>
1435
+ </form>${resetForm(p.source, "plugin", p.name)}
1313
1436
  </td>
1314
1437
  </tr>`,
1315
1438
  )
@@ -2019,7 +2142,7 @@ export function renderAgentDetailPage(
2019
2142
  const configurationGroup = renderGroup(
2020
2143
  "Configuration",
2021
2144
  configurationStat,
2022
- `${envVarsSection}${reposSection}${(opts?.configurationCardsHtml ?? []).join("")}${agentPolicySection}`,
2145
+ `${templateCard}${envVarsSection}${reposSection}${(opts?.configurationCardsHtml ?? []).join("")}${agentPolicySection}`,
2023
2146
  );
2024
2147
  const accessGroup = renderGroup(
2025
2148
  "Access",
@@ -326,6 +326,14 @@ export function baseStyles(): string {
326
326
  background: #fde68a;
327
327
  color: #92400e;
328
328
  }
329
+ .badge-template {
330
+ background: #dbeafe;
331
+ color: #1e40af;
332
+ }
333
+ .badge-custom {
334
+ background: #ede9fe;
335
+ color: #5b21b6;
336
+ }
329
337
 
330
338
  /* ─── Scope pills (filter chips) ────────────────────── */
331
339
  .scope-pill {
package/src/admin-ui.ts CHANGED
@@ -91,6 +91,7 @@ import {
91
91
  renderGithubAppInstallPage,
92
92
  renderGithubAppManifestRedirectPage,
93
93
  renderLoginPage,
94
+ type NewAgentTemplateItem,
94
95
  renderNewLocalAgentPage,
95
96
  renderProvisionCompletePage,
96
97
  renderProvisionXappTokenPage,
@@ -847,6 +848,23 @@ export function createAgentAccessChecks(deps: {
847
848
  /** Marketplace a bare plugin spec resolves to (the bundled one). */
848
849
  const DEFAULT_PLUGIN_MARKETPLACE = "shipwright";
849
850
 
851
+ /**
852
+ * ATP-2.4: parse the create form's `KEY=value` lines (blank lines and `#`
853
+ * comments skipped). Null when a line is malformed.
854
+ */
855
+ function parseEnvLines(raw: string | undefined): Record<string, string> | null {
856
+ const env: Record<string, string> = {};
857
+ for (const line of (raw ?? "").split(/\r?\n/)) {
858
+ const t = line.trim();
859
+ if (t === "" || t.startsWith("#")) continue;
860
+ const eq = t.indexOf("=");
861
+ const key = eq < 0 ? "" : t.slice(0, eq).trim();
862
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) return null;
863
+ env[key] = t.slice(eq + 1).trim();
864
+ }
865
+ return env;
866
+ }
867
+
850
868
  /**
851
869
  * Validate a plugin install spec and return its canonical
852
870
  * "<plugin>@<marketplace>" form. Throws UnprocessableEntityError if malformed.
@@ -1524,6 +1542,38 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1524
1542
  return accountIdFromScope(await callerScopeResolver(userEmail, false));
1525
1543
  }
1526
1544
 
1545
+ // ATP-2.4: the template items a new agent in this scope would inherit,
1546
+ // flattened for display. Best effort: a failing lookup shows none.
1547
+ async function templateDefaultItems(
1548
+ isAdmin: boolean,
1549
+ accountId: string | null,
1550
+ ): Promise<NewAgentTemplateItem[]> {
1551
+ if (!templateService) return [];
1552
+ try {
1553
+ const templates = await templateService.list(
1554
+ isAdmin || accountId === null
1555
+ ? { kind: "admin" }
1556
+ : { kind: "account", accountId },
1557
+ );
1558
+ return templates.flatMap((t) => {
1559
+ const scope = `${t.accountId ? "account" : "all accounts"}, ${t.specialty ?? "all types"}`;
1560
+ return t.items.map((i): NewAgentTemplateItem => {
1561
+ const secret = i.payload.secret === true;
1562
+ return {
1563
+ kind: i.kind,
1564
+ key: i.key,
1565
+ ...(i.kind === "env" && typeof i.payload.value === "string"
1566
+ ? { value: secret ? "***" : i.payload.value }
1567
+ : {}),
1568
+ scope,
1569
+ };
1570
+ });
1571
+ });
1572
+ } catch {
1573
+ return [];
1574
+ }
1575
+ }
1576
+
1527
1577
  app.get("/admin/agents/new", requireAuth, async (c) => {
1528
1578
  const accountId = await resolveCreateAccountId(
1529
1579
  c.var.userEmail,
@@ -1556,6 +1606,17 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1556
1606
  canProvision: provisioner.canProvision,
1557
1607
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
1558
1608
  ...(selfServeOpts ? { selfServe: selfServeOpts } : {}),
1609
+ ...(templateService
1610
+ ? {
1611
+ template: {
1612
+ items: await templateDefaultItems(
1613
+ c.var.isAdmin,
1614
+ accountId,
1615
+ ),
1616
+ allowEnv: c.var.isAdmin === true,
1617
+ },
1618
+ }
1619
+ : {}),
1559
1620
  }),
1560
1621
  );
1561
1622
  });
@@ -1589,8 +1650,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1589
1650
  let ghAppId: string | undefined;
1590
1651
  let ghAppInstallationId: string | undefined;
1591
1652
  let ghAppPrivateKey: string | undefined;
1653
+ let templateDetachedRaw: string | undefined;
1654
+ let envRaw: string | undefined;
1592
1655
  try {
1593
1656
  const formData = await c.req.formData();
1657
+ templateDetachedRaw = formData.get("templateDetached")?.toString();
1658
+ envRaw = formData.get("env")?.toString();
1594
1659
  name = formData.get("name")?.toString()?.trim();
1595
1660
  specialty = formData.get("type")?.toString()?.trim();
1596
1661
  reposRaw = formData.get("repos")?.toString()?.trim();
@@ -1628,6 +1693,15 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1628
1693
  } catch {
1629
1694
  return c.redirect("/admin/agents/new", 302);
1630
1695
  }
1696
+ // ATP-2.4: explicit env entries (platform admins only) override template
1697
+ // defaults per key; the opt-out checkbox starts the agent detached.
1698
+ const explicitEnv = c.var.isAdmin ? parseEnvLines(envRaw) : {};
1699
+ if (explicitEnv === null) {
1700
+ return c.redirect(
1701
+ `/admin/agents/new?error=${encodeURIComponent("Env overrides must be KEY=value lines.")}`,
1702
+ 302,
1703
+ );
1704
+ }
1631
1705
  const connectSlack = connectSlackRaw === "true";
1632
1706
  // SSP-4.2: account users always create self-serve-specialty agents in their own
1633
1707
  // account — any submitted type/accountId is ignored.
@@ -1695,6 +1769,8 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1695
1769
  claudeCodeOauthToken,
1696
1770
  anthropicApiKey,
1697
1771
  ...(accountId !== null ? { accountId } : {}),
1772
+ ...(templateDetachedRaw === "true" ? { templateDetached: true } : {}),
1773
+ ...(Object.keys(explicitEnv).length > 0 ? { env: explicitEnv } : {}),
1698
1774
  // PAI-1.2: owner is the authenticated session user, never form data.
1699
1775
  ownerEmail: c.var.userEmail,
1700
1776
  },
@@ -2333,6 +2409,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2333
2409
  marketplaces,
2334
2410
  githubEnterpriseConfigured: enterpriseConfigured,
2335
2411
  ...(installationRepos ? { installationRepos } : {}),
2412
+ ...(agentsApi
2413
+ ? { template: { detached: agent.templateDetached === true } }
2414
+ : {}),
2336
2415
  },
2337
2416
  ),
2338
2417
  );
@@ -2397,6 +2476,75 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2397
2476
  return c.redirect(`/admin/agents/${agentId}`, 302);
2398
2477
  });
2399
2478
 
2479
+ // ─── Agent template (ATP-2.4) ─────────────────────────────────────────────
2480
+ // Thin forwards to the ATP-2.2 endpoints through the agents API seam, with
2481
+ // the caller's session cookie, so its own auth and 409 rules apply.
2482
+
2483
+ const TEMPLATE_KINDS = ["env", "tool", "plugin", "cron"];
2484
+
2485
+ async function templateAction(
2486
+ c: Context<AdminUIEnv>,
2487
+ action: "detach" | "reattach" | "reset",
2488
+ body?: Record<string, string>,
2489
+ ): Promise<Response> {
2490
+ const agentId = c.req.param("id") ?? "";
2491
+ if (!agentsApi) return new Response("Not found", { status: 404 });
2492
+ if (!(await assertAgentAccess(agentId, c.var.userEmail, c.var.isAdmin))) {
2493
+ return new Response("Forbidden", { status: 403 });
2494
+ }
2495
+ const base = `/admin/agents/${agentId}`;
2496
+ const res = await callApi(
2497
+ c,
2498
+ agentsApi,
2499
+ `/agents/${encodeURIComponent(agentId)}/template/${action}`,
2500
+ {
2501
+ method: "POST",
2502
+ ...(body
2503
+ ? {
2504
+ headers: { "content-type": "application/json" },
2505
+ body: JSON.stringify(body),
2506
+ }
2507
+ : {}),
2508
+ },
2509
+ );
2510
+ if (res?.ok) return c.redirect(base, 302);
2511
+ let message = "Could not update the agent template.";
2512
+ try {
2513
+ const j = (await res?.json()) as { error?: unknown };
2514
+ if (typeof j.error === "string" && j.error) message = j.error;
2515
+ } catch {
2516
+ // keep the generic message
2517
+ }
2518
+ return c.redirect(`${base}?error=${encodeURIComponent(message)}`, 302);
2519
+ }
2520
+
2521
+ app.post("/admin/agents/:id/template/detach", requireAuth, (c) =>
2522
+ templateAction(c, "detach"),
2523
+ );
2524
+
2525
+ app.post("/admin/agents/:id/template/reattach", requireAuth, (c) =>
2526
+ templateAction(c, "reattach"),
2527
+ );
2528
+
2529
+ app.post("/admin/agents/:id/template/reset", requireAuth, async (c) => {
2530
+ let kind = "";
2531
+ let key = "";
2532
+ try {
2533
+ const form = await c.req.formData();
2534
+ kind = form.get("kind")?.toString() ?? "";
2535
+ key = form.get("key")?.toString() ?? "";
2536
+ } catch {
2537
+ // no body: reset everything
2538
+ }
2539
+ if (kind !== "" && (!TEMPLATE_KINDS.includes(kind) || key === "")) {
2540
+ return c.redirect(
2541
+ `/admin/agents/${c.req.param("id")}?error=${encodeURIComponent("Unknown template item to reset.")}`,
2542
+ 302,
2543
+ );
2544
+ }
2545
+ return templateAction(c, "reset", kind === "" ? {} : { kind, key });
2546
+ });
2547
+
2400
2548
  // ─── Repo mutations ───────────────────────────────────────────────────────
2401
2549
 
2402
2550
  app.post("/admin/agents/:id/repos/add", requireAuth, async (c) => {
@@ -3118,6 +3266,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3118
3266
  queueActivityLinks: deps.queueActivityLinks,
3119
3267
  marketplaces,
3120
3268
  githubEnterpriseConfigured: await githubEnterpriseConfigured(c),
3269
+ ...(agentsApi
3270
+ ? { template: { detached: agent.templateDetached === true } }
3271
+ : {}),
3121
3272
  },
3122
3273
  ),
3123
3274
  );
package/src/agent-envs.ts CHANGED
@@ -37,6 +37,8 @@ export interface AgentEnvEntry {
37
37
  interface AgentEnvResult {
38
38
  env: Record<string, string>;
39
39
  secretKeys: string[];
40
+ /** ATP-2.4: row source per key (`template` | `custom`). */
41
+ sources?: Record<string, string>;
40
42
  }
41
43
 
42
44
  // ─── Service ──────────────────────────────────────────────────────────────────
@@ -222,8 +224,10 @@ export class AgentEnvService {
222
224
 
223
225
  const env: Record<string, string> = {};
224
226
  const secretKeys: string[] = [];
227
+ const sources: Record<string, string> = {};
225
228
 
226
229
  for (const row of rows) {
230
+ sources[row.key] = row.source;
227
231
  if (row.secret) {
228
232
  env[row.key] = "***";
229
233
  secretKeys.push(row.key);
@@ -232,7 +236,7 @@ export class AgentEnvService {
232
236
  }
233
237
  }
234
238
 
235
- return { env, secretKeys };
239
+ return { env, secretKeys, sources };
236
240
  }
237
241
 
238
242
  /**
package/src/agents.ts CHANGED
@@ -152,6 +152,8 @@ export interface AgentDetail extends Partial<AgentAnthropicIdentity> {
152
152
  maxFindings?: number;
153
153
  cleanupMergedWorktrees?: boolean;
154
154
  cleanupAfterDays?: number;
155
+ /** ATP-2.4: the agent no longer follows its template. Optional for fixture compat. */
156
+ templateDetached?: boolean;
155
157
  }
156
158
 
157
159
  interface UpdateSelfHostedInput {
@@ -281,6 +283,7 @@ const SUMMARY_SELECT = {
281
283
  anthropicFederationRuleId: true,
282
284
  k8sServiceAccountName: true,
283
285
  podServiceAccountName: true,
286
+ templateDetached: true,
284
287
  } as const;
285
288
 
286
289
  const DETAIL_SELECT = {