@app-vitals/agent-admin 1.47.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.
@@ -52,3 +52,25 @@ describe("renderTemplatesPage", () => {
52
52
  expect(html).toMatch(/name="secret" value="1" checked/);
53
53
  });
54
54
  });
55
+
56
+ describe("renderTemplatesPage settings shell (SGL-2.2)", () => {
57
+ it("renders inside the settings layout with Templates active", () => {
58
+ const html = renderTemplatesPage({ ...base, isAdmin: true });
59
+ expect(html).toContain("settings-sidebar");
60
+ expect(html).toContain(
61
+ 'href="/admin/settings/templates" aria-current="page">Templates',
62
+ );
63
+ expect(html).toContain("Agent templates");
64
+ });
65
+
66
+ it("hides the adminOnly GitHub Enterprise item from non-admins", () => {
67
+ const member = renderTemplatesPage(base);
68
+ expect(member).not.toContain(
69
+ 'class="settings-nav-link" href="/admin/settings/github-enterprise"',
70
+ );
71
+ const admin = renderTemplatesPage({ ...base, isAdmin: true });
72
+ expect(admin).toContain(
73
+ 'class="settings-nav-link" href="/admin/settings/github-enterprise"',
74
+ );
75
+ });
76
+ });
@@ -8,6 +8,7 @@
8
8
  * errors (denylisted env key, unknown specialty, bad payload) are shown inline.
9
9
  */
10
10
 
11
+ import type { SettingsNav } from "./admin-ui-settings-layout.ts";
11
12
  import type { Context, Hono, MiddlewareHandler } from "hono";
12
13
  import { accountIdFromScope } from "./account-agent-create.ts";
13
14
  import type { AccountService } from "./accounts.ts";
@@ -39,6 +40,8 @@ export interface AdminTemplatesRouteDeps {
39
40
  "list" | "replace" | "putItem" | "deleteItem" | "delete"
40
41
  >;
41
42
  callerScopeResolver: CallerScopeResolver;
43
+ /** Settings sidebar nav (SGL-2.2). */
44
+ settingsNav?: SettingsNav;
42
45
  /** Optional: without it admins can only pick deployment-wide. */
43
46
  accounts?: Pick<AccountService, "listWithCounts" | "getWithCounts">;
44
47
  specialtyRegistry: Pick<SpecialtyTypeResolver, "listTypes">;
@@ -141,6 +144,8 @@ export function registerAdminTemplatesRoutes(
141
144
  return deps.html(
142
145
  renderTemplatesPage({
143
146
  userEmail: c.var.userEmail,
147
+ isAdmin: c.var.isAdmin === true,
148
+ ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
144
149
  accountOptions: await accountOptions(actor),
145
150
  specialtyOptions: specialtyOptions(),
146
151
  accountId: scope.accountId,
package/src/admin-ui.ts CHANGED
@@ -42,6 +42,7 @@ import type { AccountOnboardingService } from "./account-onboarding.ts";
42
42
  import type { AccountService } from "./accounts.ts";
43
43
  import {
44
44
  type AgentDetailCardSlot,
45
+ type SettingsNavContribution,
45
46
  renderAgentDetailCardSlots,
46
47
  } from "./admin-extension.ts";
47
48
  import { registerAccountRoutes } from "./admin-ui-account.ts";
@@ -51,6 +52,10 @@ import {
51
52
  } from "./admin-ui-account-nav.ts";
52
53
  import { renderZeroQuotaNotice } from "./admin-ui-account-pages.ts";
53
54
  import { registerAdminAccountsRoutes } from "./admin-ui-accounts.ts";
55
+ import {
56
+ buildSettingsNav,
57
+ firstVisibleSettingsItem,
58
+ } from "./admin-ui-settings-layout.ts";
54
59
  import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
55
60
  import { registerAdminTemplatesRoutes } from "./admin-ui-templates.ts";
56
61
  import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
@@ -86,6 +91,7 @@ import {
86
91
  renderGithubAppInstallPage,
87
92
  renderGithubAppManifestRedirectPage,
88
93
  renderLoginPage,
94
+ type NewAgentTemplateItem,
89
95
  renderNewLocalAgentPage,
90
96
  renderProvisionCompletePage,
91
97
  renderProvisionXappTokenPage,
@@ -316,6 +322,11 @@ export interface AdminUIDeps {
316
322
  * group); absent renders none.
317
323
  */
318
324
  agentDetailCards?: readonly AgentDetailCardSlot[];
325
+ /**
326
+ * Optional extension items for the settings sidebar (SGL-2.1/2.2,
327
+ * ResolvedAdminExtensions.settingsNavItems); absent adds none.
328
+ */
329
+ settingsNavItems?: readonly SettingsNavContribution[];
319
330
  /**
320
331
  * True when an extension mounts /admin/agents/:id/queue-activity (the coding
321
332
  * extension, AEP-3.6); the agents list and agent detail render their Queue &
@@ -837,6 +848,23 @@ export function createAgentAccessChecks(deps: {
837
848
  /** Marketplace a bare plugin spec resolves to (the bundled one). */
838
849
  const DEFAULT_PLUGIN_MARKETPLACE = "shipwright";
839
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
+
840
868
  /**
841
869
  * Validate a plugin install spec and return its canonical
842
870
  * "<plugin>@<marketplace>" form. Throws UnprocessableEntityError if malformed.
@@ -915,11 +943,22 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
915
943
 
916
944
  // GHE-1.4: the admin-only "Settings" toolbar entry. Registered before the
917
945
  // Account middleware; the two merge their flags in the shared store.
918
- if (githubEnterpriseApi) {
946
+ // SGL-2.2: shown to admins and to account members.
947
+ if (githubEnterpriseApi || templateService) {
919
948
  app.use("/admin/*", async (c, next) => {
920
949
  const token = getCookie(c, SESSION_COOKIE);
921
950
  const user = token ? await getSessionUser(token, sessionSecret) : null;
922
- return runWithSettingsNav(user?.isAdmin === true, () => next());
951
+ let show = user?.isAdmin === true;
952
+ if (user && !show && accountServices) {
953
+ try {
954
+ show =
955
+ (await accountServices.accounts.getByMemberEmail(user.email)) !==
956
+ null;
957
+ } catch {
958
+ // nav is cosmetic — never fail the page over the lookup
959
+ }
960
+ }
961
+ return runWithSettingsNav(show, () => next());
923
962
  });
924
963
  }
925
964
 
@@ -1503,6 +1542,38 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1503
1542
  return accountIdFromScope(await callerScopeResolver(userEmail, false));
1504
1543
  }
1505
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
+
1506
1577
  app.get("/admin/agents/new", requireAuth, async (c) => {
1507
1578
  const accountId = await resolveCreateAccountId(
1508
1579
  c.var.userEmail,
@@ -1535,6 +1606,17 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1535
1606
  canProvision: provisioner.canProvision,
1536
1607
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
1537
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
+ : {}),
1538
1620
  }),
1539
1621
  );
1540
1622
  });
@@ -1568,8 +1650,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1568
1650
  let ghAppId: string | undefined;
1569
1651
  let ghAppInstallationId: string | undefined;
1570
1652
  let ghAppPrivateKey: string | undefined;
1653
+ let templateDetachedRaw: string | undefined;
1654
+ let envRaw: string | undefined;
1571
1655
  try {
1572
1656
  const formData = await c.req.formData();
1657
+ templateDetachedRaw = formData.get("templateDetached")?.toString();
1658
+ envRaw = formData.get("env")?.toString();
1573
1659
  name = formData.get("name")?.toString()?.trim();
1574
1660
  specialty = formData.get("type")?.toString()?.trim();
1575
1661
  reposRaw = formData.get("repos")?.toString()?.trim();
@@ -1607,6 +1693,15 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1607
1693
  } catch {
1608
1694
  return c.redirect("/admin/agents/new", 302);
1609
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
+ }
1610
1705
  const connectSlack = connectSlackRaw === "true";
1611
1706
  // SSP-4.2: account users always create self-serve-specialty agents in their own
1612
1707
  // account — any submitted type/accountId is ignored.
@@ -1674,6 +1769,8 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1674
1769
  claudeCodeOauthToken,
1675
1770
  anthropicApiKey,
1676
1771
  ...(accountId !== null ? { accountId } : {}),
1772
+ ...(templateDetachedRaw === "true" ? { templateDetached: true } : {}),
1773
+ ...(Object.keys(explicitEnv).length > 0 ? { env: explicitEnv } : {}),
1677
1774
  // PAI-1.2: owner is the authenticated session user, never form data.
1678
1775
  ownerEmail: c.var.userEmail,
1679
1776
  },
@@ -2312,6 +2409,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2312
2409
  marketplaces,
2313
2410
  githubEnterpriseConfigured: enterpriseConfigured,
2314
2411
  ...(installationRepos ? { installationRepos } : {}),
2412
+ ...(agentsApi
2413
+ ? { template: { detached: agent.templateDetached === true } }
2414
+ : {}),
2315
2415
  },
2316
2416
  ),
2317
2417
  );
@@ -2376,6 +2476,75 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2376
2476
  return c.redirect(`/admin/agents/${agentId}`, 302);
2377
2477
  });
2378
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
+
2379
2548
  // ─── Repo mutations ───────────────────────────────────────────────────────
2380
2549
 
2381
2550
  app.post("/admin/agents/:id/repos/add", requireAuth, async (c) => {
@@ -3097,6 +3266,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3097
3266
  queueActivityLinks: deps.queueActivityLinks,
3098
3267
  marketplaces,
3099
3268
  githubEnterpriseConfigured: await githubEnterpriseConfigured(c),
3269
+ ...(agentsApi
3270
+ ? { template: { detached: agent.templateDetached === true } }
3271
+ : {}),
3100
3272
  },
3101
3273
  ),
3102
3274
  );
@@ -3714,9 +3886,32 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3714
3886
 
3715
3887
  // ─── Enterprise GitHub apps settings (GHE-1.4) ───────────────────────────
3716
3888
 
3889
+ const settingsNav = buildSettingsNav({
3890
+ githubEnterprise: Boolean(githubEnterpriseApi),
3891
+ templates: Boolean(templateService),
3892
+ extraItems: deps.settingsNavItems ?? [],
3893
+ });
3894
+
3895
+ // SGL-2.2: /admin/settings lands on the first nav item the viewer can see.
3896
+ if (githubEnterpriseApi || templateService) {
3897
+ app.get("/admin/settings", requireAuth, (c) => {
3898
+ const first = firstVisibleSettingsItem(
3899
+ settingsNav,
3900
+ c.var.isAdmin === true,
3901
+ );
3902
+ if (!first) {
3903
+ return new Response("No settings are available for your account.", {
3904
+ status: 404,
3905
+ });
3906
+ }
3907
+ return c.redirect(first.path, 302);
3908
+ });
3909
+ }
3910
+
3717
3911
  if (githubEnterpriseApi) {
3718
3912
  registerAdminGithubEnterpriseRoutes(app, {
3719
3913
  requireAuth,
3914
+ settingsNav,
3720
3915
  api: githubEnterpriseApi,
3721
3916
  html,
3722
3917
  });
@@ -3728,6 +3923,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3728
3923
  registerAdminTemplatesRoutes(app, {
3729
3924
  requireAuth,
3730
3925
  templateService,
3926
+ settingsNav,
3731
3927
  callerScopeResolver,
3732
3928
  ...(accountServices ? { accounts: accountServices.accounts } : {}),
3733
3929
  specialtyRegistry,
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 = {