@app-vitals/agent-admin 1.108.1 → 1.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/Dockerfile +4 -0
  2. package/account-move.example.json +22 -0
  3. package/openapi.platform.json +5 -0
  4. package/package.json +2 -2
  5. package/src/account-agent-create.ts +18 -9
  6. package/src/account-agent-create.unit.test.ts +12 -14
  7. package/src/account-move.integration.test.ts +594 -0
  8. package/src/account-move.ts +867 -0
  9. package/src/account-move.unit.test.ts +206 -0
  10. package/src/admin-local-agent.smoke.test.ts +65 -0
  11. package/src/admin-ui-account-pages.ts +2 -3
  12. package/src/admin-ui-account-pages.unit.test.ts +5 -3
  13. package/src/admin-ui-github-enterprise-pages.ts +13 -2
  14. package/src/admin-ui-github-enterprise.smoke.test.ts +20 -1
  15. package/src/admin-ui-github-enterprise.ts +16 -1
  16. package/src/admin-ui-pages.ts +16 -5
  17. package/src/admin-ui-pages.unit.test.ts +25 -20
  18. package/src/admin-ui-slack-config-token-pages.ts +11 -2
  19. package/src/admin-ui-slack-config-token.smoke.test.ts +39 -3
  20. package/src/admin-ui-slack-config-token.ts +51 -9
  21. package/src/admin-ui-templates-pages.ts +7 -1
  22. package/src/admin-ui-templates.smoke.test.ts +31 -5
  23. package/src/admin-ui-templates.ts +43 -8
  24. package/src/admin-ui.smoke.test.ts +6 -7
  25. package/src/admin-ui.ts +39 -27
  26. package/src/agent-templates-api.integration.test.ts +29 -7
  27. package/src/agent-templates.ts +7 -1
  28. package/src/agents-api.smoke.test.ts +106 -8
  29. package/src/agents-api.ts +5 -3
  30. package/src/agents.integration.test.ts +112 -2
  31. package/src/agents.ts +37 -6
  32. package/src/deployment-wide-settings.integration.test.ts +309 -0
  33. package/src/deployment-wide-settings.ts +42 -0
  34. package/src/github-agent-installation-crawler.ts +18 -1
  35. package/src/github-enterprise-api.integration.test.ts +7 -0
  36. package/src/github-enterprise-api.ts +6 -2
  37. package/src/github-enterprise-apps.integration.test.ts +33 -8
  38. package/src/github-enterprise-apps.ts +4 -0
  39. package/src/github-enterprise-isolation.unit.test.ts +17 -0
  40. package/src/github-installation-wiring.ts +34 -5
  41. package/src/github-installation-wiring.unit.test.ts +38 -1
  42. package/src/github-sync-cache.integration.test.ts +9 -2
  43. package/src/installation-repos-service.ts +7 -4
  44. package/src/move-accounts.ts +201 -0
  45. package/src/openapi-schemas.ts +6 -0
  46. package/src/self-serve-config.ts +8 -8
  47. package/src/self-serve-config.unit.test.ts +3 -10
  48. package/src/slack-config-token.integration.test.ts +19 -2
  49. package/src/slack-config-token.ts +6 -1
@@ -91,18 +91,54 @@ export function registerAdminSlackConfigTokenRoutes(
91
91
  return requested === "" ? null : requested;
92
92
  }
93
93
 
94
+ async function allAccounts(): Promise<{ id: string; name: string }[]> {
95
+ return (await deps.accounts?.listWithCounts()) ?? [];
96
+ }
97
+
98
+ /**
99
+ * With several accounts a deployment-wide token cannot be created or
100
+ * changed, so an admin who did not name a scope lands on the first account.
101
+ * An explicit empty accountId still opens the deployment-wide row (it stays
102
+ * readable and removable).
103
+ */
104
+ async function defaultedScope(
105
+ actor: Actor,
106
+ requested: string | undefined,
107
+ ): Promise<string> {
108
+ if (requested !== undefined || actor.kind === "account") {
109
+ return requested ?? "";
110
+ }
111
+ const accounts = await allAccounts();
112
+ return accounts.length > 1 ? (accounts[0]?.id ?? "") : "";
113
+ }
114
+
94
115
  async function accountOptions(
95
116
  actor: Actor,
96
- ): Promise<SlackConfigTokenScopeOption[]> {
117
+ selected: string | null,
118
+ ): Promise<{
119
+ options: SlackConfigTokenScopeOption[];
120
+ deploymentWideBlocked: boolean;
121
+ }> {
97
122
  if (actor.kind === "account") {
98
123
  const acct = await deps.accounts?.getWithCounts(actor.accountId);
99
- return [{ value: actor.accountId, label: acct?.name ?? actor.accountId }];
124
+ return {
125
+ options: [
126
+ { value: actor.accountId, label: acct?.name ?? actor.accountId },
127
+ ],
128
+ deploymentWideBlocked: false,
129
+ };
100
130
  }
101
- const accounts = (await deps.accounts?.listWithCounts()) ?? [];
102
- return [
103
- { value: "", label: "Deployment-wide (all accounts)" },
104
- ...accounts.map((a) => ({ value: a.id, label: a.name })),
105
- ];
131
+ const accounts = await allAccounts();
132
+ const blocked = accounts.length > 1;
133
+ return {
134
+ options: [
135
+ ...(!blocked || selected === null
136
+ ? [{ value: "", label: "Deployment-wide (all accounts)" }]
137
+ : []),
138
+ ...accounts.map((a) => ({ value: a.id, label: a.name })),
139
+ ],
140
+ deploymentWideBlocked: blocked,
141
+ };
106
142
  }
107
143
 
108
144
  async function renderPage(
@@ -112,12 +148,15 @@ export function registerAdminSlackConfigTokenRoutes(
112
148
  flash: { error?: string; notice?: string; status?: number } = {},
113
149
  ): Promise<Response> {
114
150
  const row = await deps.tokens.get(accountId);
151
+ const scopes = await accountOptions(actor, accountId);
115
152
  return deps.html(
116
153
  renderSlackConfigTokenPage({
117
154
  userEmail: c.var.userEmail,
118
155
  isAdmin: c.var.isAdmin === true,
119
156
  ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
120
- accountOptions: await accountOptions(actor),
157
+ accountOptions: scopes.options,
158
+ deploymentWideBlocked:
159
+ scopes.deploymentWideBlocked && accountId === null,
121
160
  accountId: accountId ?? "",
122
161
  status: row
123
162
  ? {
@@ -196,7 +235,10 @@ export function registerAdminSlackConfigTokenRoutes(
196
235
  let accountId: string | null;
197
236
  try {
198
237
  actor = await resolveActor(c);
199
- accountId = resolveScope(actor, c.req.query("accountId")?.trim() ?? "");
238
+ accountId = resolveScope(
239
+ actor,
240
+ await defaultedScope(actor, c.req.query("accountId")?.trim()),
241
+ );
200
242
  } catch {
201
243
  return new Response("Forbidden", { status: 403 });
202
244
  }
@@ -64,6 +64,8 @@ export interface TemplatesPageOpts {
64
64
  /** Items of the template at the selected scope (empty when none exists yet). */
65
65
  items: TemplateItemRow[];
66
66
  templateExists: boolean;
67
+ /** Deployment-wide scope selected while several accounts exist (read/remove only). */
68
+ deploymentWideBlocked?: boolean;
67
69
  error?: string;
68
70
  notice?: string;
69
71
  }
@@ -169,6 +171,10 @@ export function renderTemplatesPage(o: TemplatesPageOpts): string {
169
171
  const del = o.templateExists
170
172
  ? `<form method="POST" action="${BASE}/delete" style="margin:8px 0">${scopeFields(o)}<button type="submit" class="btn btn-danger">Delete this template</button></form>`
171
173
  : `<p class="help-text">No template exists for this scope yet. Adding an item creates it.</p>`;
174
+ const blocked =
175
+ o.deploymentWideBlocked === true
176
+ ? `<div class="alert alert-error">There is more than one account, so a deployment-wide template cannot be created or changed. Choose an account above. An existing deployment-wide template can still be removed.</div>`
177
+ : "";
172
178
  return renderAdminPage({
173
179
  title: "Templates — Settings — Shipwright Admin",
174
180
  body: renderSettingsLayout({
@@ -179,7 +185,7 @@ export function renderTemplatesPage(o: TemplatesPageOpts): string {
179
185
  active: BASE,
180
186
  isAdmin: o.isAdmin ?? false,
181
187
  isOwner: true,
182
- body: `${error}${notice}
188
+ body: `${error}${notice}${blocked}
183
189
  <div class="card">
184
190
  <p class="help-text">Default env vars, tools, plugins, crons and plugin marketplaces for new agents in a scope. Secret values are masked after saving; leave <code>***</code> to keep the stored value.</p>
185
191
  ${scopePicker(o)}
@@ -99,6 +99,8 @@ function setup(
99
99
  scope?: CallerScope;
100
100
  /** Role of u@x.com in acct-1; default "owner" (a non-admin is an owner). */
101
101
  role?: "owner" | "member";
102
+ /** Number of accounts listed; default 2. */
103
+ accounts?: number;
102
104
  } = {},
103
105
  ): { app: Hono<AdminUIEnv> } & ReturnType<typeof fakeService> {
104
106
  const svc = fakeService();
@@ -128,7 +130,7 @@ function setup(
128
130
  [
129
131
  { id: "acct-1", name: "Acme" },
130
132
  { id: "acct-2", name: "Globex" },
131
- ] as never,
133
+ ].slice(0, opts.accounts ?? 2) as never,
132
134
  getWithCounts: async (id: string) =>
133
135
  ({ id, name: id === "acct-1" ? "Acme" : "Globex" }) as never,
134
136
  },
@@ -160,7 +162,7 @@ const ownerScope: CallerScope = {
160
162
  describe("/admin/settings/templates smoke", () => {
161
163
  it("renders the page with the scope picker for an admin", async () => {
162
164
  const { app } = setup();
163
- const res = await app.request(BASE);
165
+ const res = await app.request(`${BASE}?accountId=`);
164
166
  expect(res.status).toBe(200);
165
167
  const html = await res.text();
166
168
  expect(html).toContain("Deployment-wide");
@@ -171,7 +173,7 @@ describe("/admin/settings/templates smoke", () => {
171
173
  });
172
174
 
173
175
  it("creates a deployment-wide secret env var and shows it masked", async () => {
174
- const { app, rows, secrets } = setup();
176
+ const { app, rows, secrets } = setup({ accounts: 1 });
175
177
  const res = await app.request(
176
178
  `${BASE}/items`,
177
179
  form({
@@ -297,7 +299,7 @@ describe("/admin/settings/templates smoke", () => {
297
299
  });
298
300
 
299
301
  it('shows a "from Helm values" badge only on seeded items (TMK-3.2)', async () => {
300
- const { app, rows } = setup();
302
+ const { app, rows } = setup({ accounts: 1 });
301
303
  rows.push({
302
304
  id: "t-seed",
303
305
  accountId: null,
@@ -370,7 +372,7 @@ describe("/admin/settings/templates marketplace items (TMK-3.1)", () => {
370
372
  const scope = { accountId: "", specialty: "" };
371
373
 
372
374
  it("creates a marketplace item with name, source and ref and lists it", async () => {
373
- const { app, rows } = setup();
375
+ const { app, rows } = setup({ accounts: 1 });
374
376
  const res = await app.request(
375
377
  `${BASE}/items`,
376
378
  form({
@@ -446,3 +448,27 @@ describe("/admin/settings/templates marketplace items (TMK-3.1)", () => {
446
448
  expect(rows[0]?.items).toHaveLength(0);
447
449
  });
448
450
  });
451
+
452
+ describe("/admin/settings/templates with several accounts", () => {
453
+ it("opens the first account when none is named and hides the deployment-wide option", async () => {
454
+ const { app } = setup();
455
+ const html = await (await app.request(BASE)).text();
456
+ expect(html).toContain('<option value="acct-1" selected>Acme</option>');
457
+ expect(html).not.toContain("Deployment-wide (all accounts)");
458
+ expect(html).not.toContain("cannot be created or changed");
459
+ });
460
+
461
+ it("still opens the deployment-wide scope on request, with a notice", async () => {
462
+ const { app } = setup();
463
+ const html = await (await app.request(`${BASE}?accountId=`)).text();
464
+ expect(html).toContain("Deployment-wide (all accounts)");
465
+ expect(html).toContain("cannot be created or changed");
466
+ });
467
+
468
+ it("with one account the deployment-wide scope is the default", async () => {
469
+ const { app } = setup({ accounts: 1 });
470
+ const html = await (await app.request(BASE)).text();
471
+ expect(html).toContain("Deployment-wide (all accounts)");
472
+ expect(html).not.toContain("cannot be created or changed");
473
+ });
474
+ });
@@ -118,18 +118,50 @@ export function registerAdminTemplatesRoutes(
118
118
  );
119
119
  }
120
120
 
121
+ /**
122
+ * With several accounts a deployment-wide template cannot be created or
123
+ * changed, so an admin who did not name an account lands on the first one.
124
+ * An explicit empty accountId still opens the deployment-wide scope (its
125
+ * templates stay readable and removable).
126
+ */
127
+ async function defaultedAccount(
128
+ actor: TemplateActor,
129
+ requested: string | undefined,
130
+ ): Promise<string> {
131
+ if (requested !== undefined || actor.kind === "account") {
132
+ return requested ?? "";
133
+ }
134
+ const accounts = (await deps.accounts?.listWithCounts()) ?? [];
135
+ return accounts.length > 1 ? (accounts[0]?.id ?? "") : "";
136
+ }
137
+
121
138
  async function accountOptions(
122
139
  actor: TemplateActor,
123
- ): Promise<TemplateScopeOption[]> {
140
+ selected: string,
141
+ ): Promise<{
142
+ options: TemplateScopeOption[];
143
+ deploymentWideBlocked: boolean;
144
+ }> {
124
145
  if (actor.kind === "account") {
125
146
  const acct = await deps.accounts?.getWithCounts(actor.accountId);
126
- return [{ value: actor.accountId, label: acct?.name ?? actor.accountId }];
147
+ return {
148
+ options: [
149
+ { value: actor.accountId, label: acct?.name ?? actor.accountId },
150
+ ],
151
+ deploymentWideBlocked: false,
152
+ };
127
153
  }
128
154
  const accounts = (await deps.accounts?.listWithCounts()) ?? [];
129
- return [
130
- { value: "", label: "Deployment-wide (all accounts)" },
131
- ...accounts.map((a) => ({ value: a.id, label: a.name })),
132
- ];
155
+ const blocked = accounts.length > 1;
156
+ return {
157
+ options: [
158
+ ...(!blocked || selected === ""
159
+ ? [{ value: "", label: "Deployment-wide (all accounts)" }]
160
+ : []),
161
+ ...accounts.map((a) => ({ value: a.id, label: a.name })),
162
+ ],
163
+ deploymentWideBlocked: blocked,
164
+ };
133
165
  }
134
166
 
135
167
  function specialtyOptions(): TemplateScopeOption[] {
@@ -148,12 +180,15 @@ export function registerAdminTemplatesRoutes(
148
180
  flash: { error?: string; notice?: string; status?: number } = {},
149
181
  ): Promise<Response> {
150
182
  const template = await findTemplate(actor, scope);
183
+ const scopes = await accountOptions(actor, scope.accountId);
151
184
  return deps.html(
152
185
  renderTemplatesPage({
153
186
  userEmail: c.var.userEmail,
154
187
  isAdmin: c.var.isAdmin === true,
155
188
  ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
156
- accountOptions: await accountOptions(actor),
189
+ accountOptions: scopes.options,
190
+ deploymentWideBlocked:
191
+ scopes.deploymentWideBlocked && scope.accountId === "",
157
192
  specialtyOptions: specialtyOptions(),
158
193
  accountId: scope.accountId,
159
194
  specialty: scope.specialty,
@@ -281,7 +316,7 @@ export function registerAdminTemplatesRoutes(
281
316
  try {
282
317
  scope = resolveScope(
283
318
  actor,
284
- c.req.query("accountId")?.trim() ?? "",
319
+ await defaultedAccount(actor, c.req.query("accountId")?.trim()),
285
320
  c.req.query("specialty")?.trim() ?? "",
286
321
  );
287
322
  } catch {
@@ -8325,11 +8325,7 @@ describe("admin UI — agents list account features, self-serve off and on", ()
8325
8325
  const base = makeMockDeps();
8326
8326
  return createAdminUIApp(
8327
8327
  makeMockDeps({
8328
- selfServe: {
8329
- enabled,
8330
- defaultMaxAgents: 0,
8331
- contactEmail: "quota@example.com",
8332
- },
8328
+ selfServe: { enabled, defaultMaxAgents: 0 },
8333
8329
  callerScopeResolver: async () => ({
8334
8330
  kind: "scoped" as const,
8335
8331
  accountId: "acct-a",
@@ -8368,7 +8364,7 @@ describe("admin UI — agents list account features, self-serve off and on", ()
8368
8364
  expect(body).toContain('href="/admin/accounts/acct-a"');
8369
8365
  });
8370
8366
 
8371
- it(`self-serve ${label}: an owner of a zero-limit account sees the contact notice`, async () => {
8367
+ it(`self-serve ${label}: an owner of a zero-limit account sees the limit notice`, async () => {
8372
8368
  const cookie = await makeSessionCookie(
8373
8369
  SESSION_SECRET,
8374
8370
  "google-sub-owner",
@@ -8379,7 +8375,10 @@ describe("admin UI — agents list account features, self-serve off and on", ()
8379
8375
  headers: { Cookie: `admin_session=${cookie}` },
8380
8376
  });
8381
8377
  expect(res.status).toBe(200);
8382
- expect(await res.text()).toContain("quota@example.com");
8378
+ const body = await res.text();
8379
+ expect(body).toContain("This account has reached its agent limit.");
8380
+ expect(body).not.toContain("request a trial");
8381
+ expect(body).not.toContain("quota@example.com");
8383
8382
  });
8384
8383
  }
8385
8384
  });
package/src/admin-ui.ts CHANGED
@@ -32,7 +32,7 @@ import { sign, verify } from "hono/jwt";
32
32
  import {
33
33
  accountIdFromScope,
34
34
  createAccountIdFromScope,
35
- getSelfServeSpecialty,
35
+ getOwnerAgentSpecialty,
36
36
  } from "./account-agent-create.ts";
37
37
  import type { AccountCreatedNotifier } from "./account-created-notifier.ts";
38
38
  import { fireAccountCreatedNotification } from "./account-created-notifier.ts";
@@ -129,7 +129,11 @@ import type { AgentTemplateService } from "./agent-templates.ts";
129
129
  import type { AgentTokenService } from "./agent-tokens.ts";
130
130
  import type { AgentToolService } from "./agent-tools.ts";
131
131
  import type { AgentService } from "./agents.ts";
132
- import { createAgent, describeRepoNameCollision } from "./agents.ts";
132
+ import {
133
+ ACCOUNT_REQUIRED_MESSAGE,
134
+ createAgent,
135
+ describeRepoNameCollision,
136
+ } from "./agents.ts";
133
137
  import { AnthropicCredentialsBlockedError } from "./anthropic-credential-guard.ts";
134
138
  import {
135
139
  audioContentTypeForFilename,
@@ -176,10 +180,7 @@ import {
176
180
  sanitizeStartUrl,
177
181
  } from "./pwa.ts";
178
182
  import { secretsEqual } from "./secrets-equal.ts";
179
- import {
180
- DEFAULT_SELF_SERVE_CONTACT_EMAIL,
181
- type SelfServeConfig,
182
- } from "./self-serve-config.ts";
183
+ import type { SelfServeConfig } from "./self-serve-config.ts";
183
184
  import {
184
185
  SETUP_RESUME_COOKIE,
185
186
  SETUP_RESUME_TTL_SECONDS,
@@ -1624,17 +1625,14 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1624
1625
  // malformed/tampered query param — render without the panel
1625
1626
  }
1626
1627
  }
1627
- // SSP-3.2: a zero-quota account sees a request-a-trial message and a
1628
- // disabled create button instead of the create CTA.
1629
- let zeroQuotaContactEmail: string | undefined;
1630
- if (accountServices) {
1628
+ // SSP-3.2: a zero-quota account sees a limit message and a disabled
1629
+ // create button instead of the create CTA. Platform admins are not limited.
1630
+ let zeroQuota = false;
1631
+ if (accountServices && !c.var.isAdmin) {
1631
1632
  const account = await accountServices.accounts.getByMemberEmail(
1632
1633
  c.var.userEmail,
1633
1634
  );
1634
- if (account && account.maxAgents === 0) {
1635
- zeroQuotaContactEmail =
1636
- selfServe?.contactEmail ?? DEFAULT_SELF_SERVE_CONTACT_EMAIL;
1637
- }
1635
+ zeroQuota = account?.maxAgents === 0;
1638
1636
  }
1639
1637
  // SSP-5.2: admins get an Account column.
1640
1638
  let accountNames: Map<string, string> | undefined;
@@ -1652,9 +1650,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1652
1650
  queueActivityLinks: deps.queueActivityLinks,
1653
1651
  successMsg,
1654
1652
  manualSteps,
1655
- zeroQuotaNotice: zeroQuotaContactEmail
1656
- ? renderZeroQuotaNotice(zeroQuotaContactEmail)
1657
- : undefined,
1653
+ zeroQuotaNotice: zeroQuota ? renderZeroQuotaNotice() : undefined,
1658
1654
  }),
1659
1655
  );
1660
1656
  });
@@ -1694,8 +1690,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1694
1690
  "In-cluster provisioning is not enabled on this admin service — create a self-hosted agent instead.",
1695
1691
  provision_failed:
1696
1692
  "Failed to provision the agent's cluster resources — the agent was not created.",
1697
- quota_exceeded: "This account has reached its agent limit.",
1693
+ quota_exceeded:
1694
+ "This account has reached its agent limit. Delete an agent to free a slot.",
1698
1695
  account_inactive: "This account is not active.",
1696
+ account_required: ACCOUNT_REQUIRED_MESSAGE,
1699
1697
  ...deps.agentDetailErrorMessages,
1700
1698
  };
1701
1699
 
@@ -1754,9 +1752,15 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1754
1752
  if (!c.var.isAdmin && accountId === null) {
1755
1753
  return new Response("Forbidden", { status: 403 });
1756
1754
  }
1757
- let selfServeOpts:
1758
- | { remaining: number; max: number; contactEmail: string }
1759
- | undefined;
1755
+ let selfServeOpts: { remaining: number; max: number } | undefined;
1756
+ // Platform admins pick the account when more than one exists.
1757
+ let accountChoices: { id: string; name: string }[] | undefined;
1758
+ if (c.var.isAdmin && accountServices) {
1759
+ const all = await accountServices.accounts.listWithCounts();
1760
+ if (all.length > 1) {
1761
+ accountChoices = all.map((a) => ({ id: a.id, name: a.name }));
1762
+ }
1763
+ }
1760
1764
  if (accountId !== null && accountService) {
1761
1765
  const [account, count] = await Promise.all([
1762
1766
  accountService.getById(accountId),
@@ -1765,8 +1769,6 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1765
1769
  selfServeOpts = {
1766
1770
  remaining: Math.max(0, (account?.maxAgents ?? 0) - count),
1767
1771
  max: account?.maxAgents ?? 0,
1768
- contactEmail:
1769
- selfServe?.contactEmail ?? DEFAULT_SELF_SERVE_CONTACT_EMAIL,
1770
1772
  };
1771
1773
  }
1772
1774
  const rawError = c.req.query("error") ?? undefined;
@@ -1782,6 +1784,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1782
1784
  accountId,
1783
1785
  ),
1784
1786
  ...(selfServeOpts ? { selfServe: selfServeOpts } : {}),
1787
+ ...(accountChoices ? { accountChoices } : {}),
1785
1788
  ...(templateService
1786
1789
  ? {
1787
1790
  template: {
@@ -1806,6 +1809,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1806
1809
  }
1807
1810
  let name: string | undefined;
1808
1811
  let specialty: string | undefined;
1812
+ let chosenAccountId: string | undefined;
1809
1813
  let reposRaw: string | undefined;
1810
1814
  let authorAllowlistRaw: string | undefined;
1811
1815
  let patchAuthorAllowlistRaw: string | undefined;
@@ -1832,6 +1836,8 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1832
1836
  envRaw = formData.get("env")?.toString();
1833
1837
  name = formData.get("name")?.toString()?.trim();
1834
1838
  specialty = formData.get("type")?.toString()?.trim();
1839
+ chosenAccountId =
1840
+ formData.get("accountId")?.toString()?.trim() || undefined;
1835
1841
  reposRaw = formData.get("repos")?.toString()?.trim();
1836
1842
  authorAllowlistRaw = formData.get("authorAllowlist")?.toString()?.trim();
1837
1843
  patchAuthorAllowlistRaw = formData
@@ -1878,9 +1884,13 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1878
1884
  );
1879
1885
  }
1880
1886
  const connectSlack = connectSlackRaw === "true";
1881
- // SSP-4.2: account users always create self-serve-specialty agents in their own
1882
- // account — any submitted type/accountId is ignored.
1883
- if (accountId !== null) specialty = getSelfServeSpecialty();
1887
+ // Account owners always create the default agent type in their own
1888
+ // account — any submitted type/accountId is ignored. Platform admins
1889
+ // choose the type, and the account when several exist.
1890
+ const targetAccountId = c.var.isAdmin
1891
+ ? chosenAccountId
1892
+ : (accountId ?? undefined);
1893
+ if (accountId !== null) specialty = getOwnerAgentSpecialty();
1884
1894
  // Absent/unrecognized runtime means self-hosted — the historical behavior
1885
1895
  // of this form. createAgent() below re-derives this same value itself
1886
1896
  // (it owns the runtime/provisioning validation); it's recomputed here
@@ -1943,7 +1953,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1943
1953
  restrictSlackToMembersRaw,
1944
1954
  claudeCodeOauthToken,
1945
1955
  anthropicApiKey,
1946
- ...(accountId !== null ? { accountId } : {}),
1956
+ ...(targetAccountId !== undefined
1957
+ ? { accountId: targetAccountId }
1958
+ : {}),
1947
1959
  ...(templateDetachedRaw === "true" ? { templateDetached: true } : {}),
1948
1960
  ...(Object.keys(explicitEnv).length > 0 ? { env: explicitEnv } : {}),
1949
1961
  // PAI-1.2: owner is the authenticated session user, never form data.
@@ -111,6 +111,7 @@ describeOrSkip("/templates (integration)", () => {
111
111
  describe("validation", () => {
112
112
  it("422 for an unknown specialty", async () => {
113
113
  const res = await call("PUT", "/templates", admin, {
114
+ accountId: accountA,
114
115
  specialty: "nope",
115
116
  items: [],
116
117
  });
@@ -130,6 +131,7 @@ describeOrSkip("/templates (integration)", () => {
130
131
  "gh_token",
131
132
  ])("422 for denylisted env key %s", async (key) => {
132
133
  const res = await call("PUT", "/templates", admin, {
134
+ accountId: accountA,
133
135
  items: [{ kind: "env", key, payload: { value: "x" } }],
134
136
  });
135
137
  expect(res.status).toBe(422);
@@ -138,6 +140,7 @@ describeOrSkip("/templates (integration)", () => {
138
140
 
139
141
  it("422 for a cron item without a name key", async () => {
140
142
  const res = await call("PUT", "/templates", admin, {
143
+ accountId: accountA,
141
144
  items: [
142
145
  {
143
146
  kind: "cron",
@@ -151,6 +154,7 @@ describeOrSkip("/templates (integration)", () => {
151
154
 
152
155
  it("422 for a cron item missing schedule or prompt", async () => {
153
156
  const res = await call("PUT", "/templates", admin, {
157
+ accountId: accountA,
154
158
  items: [{ kind: "cron", key: "brief", payload: { prompt: "x" } }],
155
159
  });
156
160
  expect(res.status).toBe(422);
@@ -163,12 +167,14 @@ describeOrSkip("/templates (integration)", () => {
163
167
  payload: { schedule: "0 9 * * *", prompt: "brief" },
164
168
  };
165
169
  const dup = await call("PUT", "/templates", admin, {
170
+ accountId: accountA,
166
171
  items: [cron, cron],
167
172
  });
168
173
  expect(dup.status).toBe(422);
169
174
  expect(await prisma.agentTemplate.count()).toBe(0);
170
175
 
171
176
  const ok = await call("PUT", "/templates", admin, {
177
+ accountId: accountA,
172
178
  items: [cron, { kind: "tool", key: "brief" }],
173
179
  });
174
180
  expect(ok.status).toBe(201);
@@ -176,6 +182,7 @@ describeOrSkip("/templates (integration)", () => {
176
182
 
177
183
  it("400 for an unknown item kind", async () => {
178
184
  const res = await call("PUT", "/templates", admin, {
185
+ accountId: accountA,
179
186
  items: [{ kind: "bogus", key: "x" }],
180
187
  });
181
188
  expect(res.status).toBe(400);
@@ -191,7 +198,10 @@ describeOrSkip("/templates (integration)", () => {
191
198
 
192
199
  it("round-trips a marketplace item unchanged", async () => {
193
200
  const item = mkt("example-plugins", { source: "example-org/plugins" });
194
- const put = await call("PUT", "/templates", admin, { items: [item] });
201
+ const put = await call("PUT", "/templates", admin, {
202
+ accountId: accountA,
203
+ items: [item],
204
+ });
195
205
  expect([200, 201]).toContain(put.status);
196
206
  const list = (await (await call("GET", "/templates", admin)).json()) as {
197
207
  templates: {
@@ -210,7 +220,10 @@ describeOrSkip("/templates (integration)", () => {
210
220
  });
211
221
 
212
222
  it("supports item upsert and delete", async () => {
213
- const put = await call("PUT", "/templates", admin, { items: [] });
223
+ const put = await call("PUT", "/templates", admin, {
224
+ accountId: accountA,
225
+ items: [],
226
+ });
214
227
  const { id } = (await put.json()) as { id: string };
215
228
  const up = await call(
216
229
  "PUT",
@@ -235,6 +248,7 @@ describeOrSkip("/templates (integration)", () => {
235
248
  ["invalid ref", "m", { source: "o/r", ref: "a..b" }],
236
249
  ])("422 for %s", async (_label, key, payload) => {
237
250
  const res = await call("PUT", "/templates", admin, {
251
+ accountId: accountA,
238
252
  items: [mkt(key, payload)],
239
253
  });
240
254
  expect(res.status).toBe(422);
@@ -244,6 +258,7 @@ describeOrSkip("/templates (integration)", () => {
244
258
  it("422 for a duplicate marketplace key in one body", async () => {
245
259
  const item = mkt("m", { source: "o/r" });
246
260
  const res = await call("PUT", "/templates", admin, {
261
+ accountId: accountA,
247
262
  items: [item, item],
248
263
  });
249
264
  expect(res.status).toBe(422);
@@ -265,6 +280,7 @@ describeOrSkip("/templates (integration)", () => {
265
280
  describe("crypto and masking", () => {
266
281
  it("encrypts env values at rest and masks secrets on GET", async () => {
267
282
  const put = await call("PUT", "/templates", admin, {
283
+ accountId: accountA,
268
284
  specialty: "specialist",
269
285
  items: [
270
286
  {
@@ -306,6 +322,7 @@ describeOrSkip("/templates (integration)", () => {
306
322
  const list = await call("GET", "/templates", admin);
307
323
  expect(JSON.stringify(await list.json())).not.toContain("lin_secret");
308
324
  const put2 = await call("PUT", "/templates", admin, {
325
+ accountId: accountA,
309
326
  specialty: "specialist",
310
327
  items: [
311
328
  {
@@ -320,6 +337,7 @@ describeOrSkip("/templates (integration)", () => {
320
337
 
321
338
  it("keeps the stored secret when the mask is sent back", async () => {
322
339
  const put = await call("PUT", "/templates", admin, {
340
+ accountId: accountA,
323
341
  items: [
324
342
  {
325
343
  kind: "env",
@@ -330,6 +348,7 @@ describeOrSkip("/templates (integration)", () => {
330
348
  });
331
349
  const { id } = (await put.json()) as { id: string };
332
350
  const again = await call("PUT", "/templates", admin, {
351
+ accountId: accountA,
333
352
  items: [
334
353
  { kind: "env", key: "K", payload: { value: "***", secret: true } },
335
354
  ],
@@ -343,6 +362,7 @@ describeOrSkip("/templates (integration)", () => {
343
362
  );
344
363
 
345
364
  const bad = await call("PUT", "/templates", admin, {
365
+ accountId: accountA,
346
366
  items: [
347
367
  { kind: "env", key: "NEW", payload: { value: "***", secret: true } },
348
368
  ],
@@ -382,7 +402,8 @@ describeOrSkip("/templates (integration)", () => {
382
402
  expect(replaced.items.map((i) => i.kind)).toEqual(["cron", "plugin"]);
383
403
  expect(await prisma.agentTemplate.count()).toBe(1);
384
404
 
385
- await call("PUT", "/templates", admin, { items: [] }); // deployment-wide
405
+ // A deployment-wide row that predates the second account.
406
+ await prisma.agentTemplate.create({ data: { accountId: null } });
386
407
  const all = (await (await call("GET", "/templates", admin)).json()) as {
387
408
  templates: unknown[];
388
409
  };
@@ -449,9 +470,9 @@ describeOrSkip("/templates (integration)", () => {
449
470
  items: [],
450
471
  })
451
472
  ).json()) as { id: string };
452
- const global = (await (
453
- await call("PUT", "/templates", admin, { items: [] })
454
- ).json()) as { id: string };
473
+ const global = await prisma.agentTemplate.create({
474
+ data: { accountId: null },
475
+ });
455
476
  const b = await cookie("b@example.com");
456
477
 
457
478
  // Reading/changing another account's or a global template: 404 (no leak).
@@ -505,7 +526,8 @@ describeOrSkip("/templates (integration)", () => {
505
526
  expect((await call("GET", "/templates", {})).status).toBe(401);
506
527
  });
507
528
 
508
- it("an admin session manages deployment-wide templates", async () => {
529
+ it("an admin session manages deployment-wide templates while there is one account", async () => {
530
+ await prisma.account.delete({ where: { id: accountB } });
509
531
  const h = await cookie("root@example.com", true);
510
532
  const res = await call("PUT", "/templates", h, { items: [] });
511
533
  expect(res.status).toBe(201);
@@ -28,6 +28,7 @@ import {
28
28
  sealTemplateItemPayload,
29
29
  type TemplateItemPayload,
30
30
  } from "./agent-template-items.ts";
31
+ import { assertDeploymentWideAllowed } from "./deployment-wide-settings.ts";
31
32
  import {
32
33
  ConflictError,
33
34
  ForbiddenError,
@@ -397,7 +398,9 @@ export class AgentTemplateService {
397
398
  return item;
398
399
  });
399
400
 
400
- if (accountId !== null) {
401
+ if (accountId === null) {
402
+ await assertDeploymentWideAllowed(this.prisma, "an agent template");
403
+ } else {
401
404
  const account = await this.prisma.account.findUnique({
402
405
  where: { id: accountId },
403
406
  select: { id: true },
@@ -470,6 +473,9 @@ export class AgentTemplateService {
470
473
  input: TemplateItemInput,
471
474
  ): Promise<TemplateView> {
472
475
  const existing = await this.load(actor, templateId);
476
+ if (existing.accountId === null) {
477
+ await assertDeploymentWideAllowed(this.prisma, "an agent template");
478
+ }
473
479
  const item = normalizeTemplateItem(input);
474
480
  const prior = existing.items.find(
475
481
  (it) => it.kind === item.kind && it.key === item.key,