@app-vitals/agent-admin 1.108.0 → 1.109.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 (55) hide show
  1. package/Dockerfile +4 -0
  2. package/account-move.example.json +22 -0
  3. package/e2e/real/admin-access.real.e2e.ts +77 -68
  4. package/e2e/real/agent-management.real.e2e.ts +165 -143
  5. package/e2e/real/owner-access.real.e2e.ts +228 -212
  6. package/openapi.platform.json +11 -6
  7. package/package.json +2 -2
  8. package/src/account-agent-create.ts +18 -9
  9. package/src/account-agent-create.unit.test.ts +12 -14
  10. package/src/account-created-notifier.ts +1 -1
  11. package/src/account-move.integration.test.ts +594 -0
  12. package/src/account-move.ts +867 -0
  13. package/src/account-move.unit.test.ts +206 -0
  14. package/src/account-onboarding.integration.test.ts +69 -0
  15. package/src/account-onboarding.ts +29 -3
  16. package/src/account-trial-expiry-sweeper.ts +1 -1
  17. package/src/accounts-api.integration.test.ts +5 -2
  18. package/src/accounts-api.smoke.test.ts +21 -5
  19. package/src/accounts-api.ts +12 -15
  20. package/src/admin-boot-config.ts +2 -0
  21. package/src/admin-boot-config.unit.test.ts +27 -0
  22. package/src/admin-boot.ts +11 -10
  23. package/src/admin-local-agent.smoke.test.ts +65 -0
  24. package/src/admin-ui-account-pages.ts +2 -3
  25. package/src/admin-ui-account-pages.unit.test.ts +5 -3
  26. package/src/admin-ui-account.smoke.test.ts +7 -3
  27. package/src/admin-ui-account.ts +10 -15
  28. package/src/admin-ui-accounts.smoke.test.ts +4 -4
  29. package/src/admin-ui-accounts.ts +7 -11
  30. package/src/admin-ui-pages.ts +16 -5
  31. package/src/admin-ui-pages.unit.test.ts +25 -20
  32. package/src/admin-ui-settings-nav-context.smoke.test.ts +24 -0
  33. package/src/admin-ui-settings.smoke.test.ts +17 -1
  34. package/src/admin-ui.smoke.test.ts +167 -2
  35. package/src/admin-ui.ts +75 -50
  36. package/src/agent-management-access.integration.test.ts +18 -6
  37. package/src/agent-manifest.ts +2 -1
  38. package/src/agent-provisioner.integration.test.ts +10 -10
  39. package/src/agent-provisioner.ts +10 -1
  40. package/src/agent-provisioner.unit.test.ts +110 -36
  41. package/src/agent-templates-api.integration.test.ts +23 -5
  42. package/src/agent-templates-api.ts +11 -8
  43. package/src/agents-api.smoke.test.ts +106 -8
  44. package/src/agents-api.ts +5 -3
  45. package/src/agents.integration.test.ts +112 -2
  46. package/src/agents.ts +37 -6
  47. package/src/caller-scope.integration.test.ts +8 -6
  48. package/src/caller-scope.ts +32 -26
  49. package/src/caller-scope.unit.test.ts +15 -11
  50. package/src/github-enterprise-isolation.unit.test.ts +17 -0
  51. package/src/move-accounts.ts +201 -0
  52. package/src/openapi-schemas.ts +6 -0
  53. package/src/platform-routes.ts +2 -2
  54. package/src/self-serve-config.ts +8 -8
  55. package/src/self-serve-config.unit.test.ts +3 -10
@@ -0,0 +1,206 @@
1
+ /**
2
+ * admin/src/account-move.unit.test.ts
3
+ *
4
+ * multi-account-2.6: mapping and receipt parsing, the CLI's argument handling
5
+ * (every case exits before any database use), the shipped example mapping,
6
+ * and the admin image guard that keeps the tool in the released image.
7
+ */
8
+
9
+ import { describe, expect, it } from "bun:test";
10
+ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import {
14
+ formatPlan,
15
+ MoveInputError,
16
+ parseMapping,
17
+ parseReceipt,
18
+ } from "./account-move.ts";
19
+ import { runMoveAccountsCli, USAGE } from "./move-accounts.ts";
20
+
21
+ const ADMIN = join(import.meta.dir, "..");
22
+ const ROOT = join(ADMIN, "..");
23
+
24
+ describe("parseMapping", () => {
25
+ it("fills defaults and lowercases member emails", () => {
26
+ const m = parseMapping({
27
+ accounts: [
28
+ { id: "example-a", members: [{ email: "Someone@Example.com" }] },
29
+ ],
30
+ });
31
+ expect(m.accounts[0]).toEqual({
32
+ id: "example-a",
33
+ agents: [],
34
+ members: [{ email: "someone@example.com", role: "member" }],
35
+ });
36
+ expect(m.settings).toEqual([]);
37
+ });
38
+
39
+ it.each([
40
+ ["an unknown top-level key", { agents: [] }],
41
+ ["an unknown account key", { accounts: [{ id: "a", owner: "x" }] }],
42
+ ["a bad account id", { accounts: [{ id: "has space" }] }],
43
+ ["a negative agent limit", { accounts: [{ id: "a", maxAgents: -1 }] }],
44
+ [
45
+ "an unknown role",
46
+ {
47
+ accounts: [
48
+ { id: "a", members: [{ email: "x@example.com", role: "admin" }] },
49
+ ],
50
+ },
51
+ ],
52
+ [
53
+ "an unknown setting",
54
+ { settings: [{ setting: "nope", toAccountId: "a" }] },
55
+ ],
56
+ [
57
+ "a specialty on a non-template setting",
58
+ {
59
+ settings: [
60
+ { setting: "slackConfigToken", specialty: "x", toAccountId: "a" },
61
+ ],
62
+ },
63
+ ],
64
+ ["a non-object", "nope"],
65
+ ])("rejects %s", (_label, raw) => {
66
+ expect(() => parseMapping(raw)).toThrow(MoveInputError);
67
+ });
68
+
69
+ it("accepts the shipped example mapping", () => {
70
+ const raw = JSON.parse(
71
+ readFileSync(join(ADMIN, "account-move.example.json"), "utf8"),
72
+ );
73
+ expect(parseMapping(raw).accounts.length).toBeGreaterThan(0);
74
+ });
75
+ });
76
+
77
+ describe("parseReceipt", () => {
78
+ it("round-trips a receipt", () => {
79
+ const receipt = {
80
+ kind: "admin-account-move",
81
+ version: 1,
82
+ appliedAt: "2026-01-01T00:00:00.000Z",
83
+ changes: [
84
+ {
85
+ type: "moveAgent",
86
+ agentId: "a1",
87
+ name: "example-agent",
88
+ from: null,
89
+ to: "example-a",
90
+ },
91
+ ],
92
+ };
93
+ expect(parseReceipt(receipt)).toEqual(receipt as never);
94
+ });
95
+
96
+ it("rejects something that is not a receipt", () => {
97
+ expect(() => parseReceipt({ changes: [] })).toThrow(MoveInputError);
98
+ });
99
+ });
100
+
101
+ describe("formatPlan", () => {
102
+ it("says when there is nothing to change", () => {
103
+ expect(formatPlan({ changes: [], warnings: [], skipped: [] })).toContain(
104
+ "nothing to change",
105
+ );
106
+ });
107
+ });
108
+
109
+ describe("move-accounts CLI argument handling", () => {
110
+ async function cli(args: string[]) {
111
+ const out: string[] = [];
112
+ const err: string[] = [];
113
+ const db = new Proxy(
114
+ {},
115
+ {
116
+ get() {
117
+ throw new Error("the database must not be used");
118
+ },
119
+ },
120
+ );
121
+ const code = await runMoveAccountsCli(args, {
122
+ db: db as never,
123
+ stdout: (s) => out.push(s),
124
+ stderr: (s) => err.push(s),
125
+ });
126
+ return { code, out: out.join("\n"), err: err.join("\n") };
127
+ }
128
+
129
+ it("prints usage with --help", async () => {
130
+ const r = await cli(["--help"]);
131
+ expect(r.code).toBe(0);
132
+ expect(r.out).toBe(USAGE);
133
+ });
134
+
135
+ it.each([
136
+ [[]],
137
+ [["--mapping", "a.json", "--reverse", "b.json"]],
138
+ [["--mapping", "a.json", "--apply"]],
139
+ [["--reverse", "b.json", "--receipt", "c.json"]],
140
+ [["--bogus"]],
141
+ ])("exits 2 on bad arguments %j", async (args) => {
142
+ expect((await cli(args)).code).toBe(2);
143
+ });
144
+
145
+ it("refuses to overwrite an existing receipt", async () => {
146
+ const dir = mkdtempSync(join(tmpdir(), "account-move-unit-"));
147
+ const receipt = join(dir, "r.json");
148
+ writeFileSync(receipt, "{}");
149
+ const r = await cli([
150
+ "--mapping",
151
+ "m.json",
152
+ "--apply",
153
+ "--receipt",
154
+ receipt,
155
+ ]);
156
+ expect(r.code).toBe(2);
157
+ expect(r.err).toContain("already exists");
158
+ });
159
+
160
+ it("exits 2 on an unreadable or invalid mapping", async () => {
161
+ const dir = mkdtempSync(join(tmpdir(), "account-move-unit-"));
162
+ expect((await cli(["--mapping", join(dir, "missing.json")])).code).toBe(2);
163
+ const bad = join(dir, "bad.json");
164
+ writeFileSync(bad, JSON.stringify({ accounts: [{ id: "has space" }] }));
165
+ expect((await cli(["--mapping", bad])).code).toBe(2);
166
+ });
167
+ });
168
+
169
+ describe("account move tool in the admin image", () => {
170
+ const dockerfile = readFileSync(join(ADMIN, "Dockerfile"), "utf8");
171
+ const ignored = readFileSync(join(ROOT, ".dockerignore"), "utf8")
172
+ .split("\n")
173
+ .map((l) => l.trim())
174
+ .filter((l) => l !== "" && !l.startsWith("#"));
175
+
176
+ it("copies the whole build context into the image", () => {
177
+ expect(dockerfile).toMatch(/^COPY \. \.$/m);
178
+ });
179
+
180
+ it.each([
181
+ "admin/src/move-accounts.ts",
182
+ "admin/src/account-move.ts",
183
+ "admin/account-move.example.json",
184
+ ])("keeps %s in the build context", (path) => {
185
+ for (const rule of ignored) {
186
+ const prefix = rule.replace(/^\*\*\//, "").replace(/\/$/, "");
187
+ const parts = path.split("/");
188
+ // .dockerignore here holds only plain names and **/name rules.
189
+ expect(
190
+ parts.some(
191
+ (p, i) => parts.slice(0, i + 1).join("/") === prefix || p === prefix,
192
+ ),
193
+ ).toBe(false);
194
+ }
195
+ });
196
+
197
+ it("runs the tool's --help during the build, after prisma generate", () => {
198
+ const generate = dockerfile.indexOf("prisma generate");
199
+ const guard = dockerfile.indexOf(
200
+ "RUN bun admin/src/move-accounts.ts --help",
201
+ );
202
+ expect(generate).toBeGreaterThan(-1);
203
+ expect(guard).toBeGreaterThan(generate);
204
+ expect(guard).toBeLessThan(dockerfile.indexOf("USER 1000"));
205
+ });
206
+ });
@@ -98,4 +98,73 @@ describeOrSkip("AccountOnboardingService (integration)", () => {
98
98
  expect(results.every((r) => r.accountId === owner.id)).toBe(true);
99
99
  expect(results.filter((r) => r.kind === "joined")).toHaveLength(1);
100
100
  });
101
+
102
+ describe("joinForEmail (signup off)", () => {
103
+ it("returns null for an unknown email and creates nothing", async () => {
104
+ expect(await onboarding.joinForEmail("Stranger@x.com")).toBeNull();
105
+ expect(await prisma.account.count()).toBe(0);
106
+ expect(await prisma.accountMember.count()).toBe(0);
107
+ });
108
+
109
+ it("joins the invited account as member and marks the invite accepted", async () => {
110
+ const owner = await new AccountService(prisma).create(
111
+ "Acme",
112
+ "o@acme.com",
113
+ );
114
+ await new AccountInviteService(prisma).create(
115
+ owner.id,
116
+ "invitee@acme.com",
117
+ "o@acme.com",
118
+ );
119
+ expect(await onboarding.joinForEmail("Invitee@Acme.com")).toEqual({
120
+ kind: "joined",
121
+ accountId: owner.id,
122
+ });
123
+ expect(await prisma.account.count()).toBe(1);
124
+ const member = await prisma.accountMember.findUniqueOrThrow({
125
+ where: { email: "invitee@acme.com" },
126
+ });
127
+ expect(member.role).toBe("member");
128
+ const invite = await prisma.accountInvite.findFirstOrThrow({
129
+ where: { email: "invitee@acme.com" },
130
+ });
131
+ expect(invite.acceptedAt).not.toBeNull();
132
+ });
133
+
134
+ it("returns existing for an account owner with no agents", async () => {
135
+ const owner = await new AccountService(prisma).create(
136
+ "Acme",
137
+ "o@acme.com",
138
+ );
139
+ expect(await onboarding.joinForEmail("O@acme.com")).toEqual({
140
+ kind: "existing",
141
+ accountId: owner.id,
142
+ });
143
+ expect(await prisma.account.count()).toBe(1);
144
+ });
145
+
146
+ it("concurrent joins with a pending invite join once", async () => {
147
+ const owner = await new AccountService(prisma).create(
148
+ "Acme",
149
+ "o@acme.com",
150
+ );
151
+ await new AccountInviteService(prisma).create(
152
+ owner.id,
153
+ "race@acme.com",
154
+ "o@acme.com",
155
+ );
156
+ const results = await Promise.all(
157
+ Array.from({ length: 6 }, () =>
158
+ onboarding.joinForEmail("race@acme.com"),
159
+ ),
160
+ );
161
+ expect(new Set(results.map((r) => r?.accountId))).toEqual(
162
+ new Set([owner.id]),
163
+ );
164
+ expect(await prisma.account.count()).toBe(1);
165
+ expect(
166
+ await prisma.accountMember.count({ where: { email: "race@acme.com" } }),
167
+ ).toBe(1);
168
+ });
169
+ });
101
170
  });
@@ -4,7 +4,9 @@
4
4
  * agent provisioning (SSP-3.1).
5
5
  *
6
6
  * A verified email with no account yet either joins the account that invited
7
- * it (as 'member') or gets a brand-new account (as 'owner'). Everything runs
7
+ * it (as 'member') or, when signup is open, gets a brand-new account (as
8
+ * 'owner'). joinForEmail() is the signup-off variant: it never creates an
9
+ * account. Everything runs
8
10
  * in one transaction, and concurrent first logins for the same email are made
9
11
  * idempotent by UNIQUE(AccountMember.email): the losing transaction rolls back
10
12
  * entirely (including any account it created) and re-reads the winner's row.
@@ -36,12 +38,29 @@ export class AccountOnboardingService {
36
38
  * does, else join via pending invite ("joined"), else create ("created").
37
39
  */
38
40
  async provisionForEmail(rawEmail: string): Promise<OnboardingResult> {
41
+ // With allowCreate the result is never null (the last step creates).
42
+ return (await this.resolve(rawEmail, true)) as OnboardingResult;
43
+ }
44
+
45
+ /**
46
+ * Signup-off sign-in: "existing" if the email already belongs to an
47
+ * account, else join via pending invite ("joined"), else null. Never
48
+ * creates an account.
49
+ */
50
+ async joinForEmail(rawEmail: string): Promise<OnboardingResult | null> {
51
+ return this.resolve(rawEmail, false);
52
+ }
53
+
54
+ private async resolve(
55
+ rawEmail: string,
56
+ allowCreate: boolean,
57
+ ): Promise<OnboardingResult | null> {
39
58
  const email = normalizeEmail(rawEmail);
40
59
  let lastErr: unknown;
41
60
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
42
61
  try {
43
62
  return await this.prisma.$transaction((tx) =>
44
- this.provisionInTx(tx, email),
63
+ this.provisionInTx(tx, email, allowCreate),
45
64
  );
46
65
  } catch (err) {
47
66
  if (!isUniqueViolation(err)) throw err;
@@ -59,7 +78,8 @@ export class AccountOnboardingService {
59
78
  private async provisionInTx(
60
79
  tx: Parameters<Parameters<PrismaClient["$transaction"]>[0]>[0],
61
80
  email: string,
62
- ): Promise<OnboardingResult> {
81
+ allowCreate: boolean,
82
+ ): Promise<OnboardingResult | null> {
63
83
  const existing = await tx.accountMember.findUnique({ where: { email } });
64
84
  if (existing) return { kind: "existing", accountId: existing.accountId };
65
85
 
@@ -79,6 +99,12 @@ export class AccountOnboardingService {
79
99
  return { kind: "joined", accountId: invite.accountId };
80
100
  }
81
101
  }
102
+ if (!allowCreate) {
103
+ // A concurrent login may have claimed the invite and committed since
104
+ // the first read (read committed: this statement sees its member row).
105
+ const winner = await tx.accountMember.findUnique({ where: { email } });
106
+ return winner ? { kind: "existing", accountId: winner.accountId } : null;
107
+ }
82
108
 
83
109
  const account = await tx.account.create({
84
110
  data: {
@@ -18,7 +18,7 @@
18
18
  * Idempotent by construction: once an account is trial_expired and its crons
19
19
  * are disabled, neither query matches anything, so a re-run writes nothing.
20
20
  * Never deletes anything (no deleteAgentFully call). Registered via setInterval
21
- * in main.ts, flag-gated on self-serve.
21
+ * in admin-boot.ts; always runs (independent of the self-serve setting).
22
22
  */
23
23
 
24
24
  import type { AccountLifecycle } from "./account-lifecycle.ts";
@@ -24,7 +24,10 @@ import { createAdminPrismaClient } from "./prisma-client.ts";
24
24
  const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
25
25
  const describeOrSkip = TEST_DB ? describe : describe.skip;
26
26
 
27
- describeOrSkip("/accounts API (integration)", () => {
27
+ /** Run with the self-serve setting off and on; the outcome must not differ. */
28
+ const SELF_SERVE = [false, true];
29
+
30
+ describeOrSkip.each(SELF_SERVE)("/accounts API, self-serve=%p", (enabled) => {
28
31
  let prisma: PrismaClient;
29
32
  let accounts: AccountService;
30
33
  let app: ReturnType<typeof createAccountsApp>;
@@ -43,7 +46,7 @@ describeOrSkip("/accounts API (integration)", () => {
43
46
  accounts = new AccountService(prisma);
44
47
  app = createAccountsApp({
45
48
  selfServe: {
46
- enabled: true,
49
+ enabled,
47
50
  defaultMaxAgents: 0,
48
51
  contactEmail: "c@x.com",
49
52
  },
@@ -120,11 +120,27 @@ function req(
120
120
  });
121
121
  }
122
122
 
123
- describe("flag off", () => {
124
- it.each(ROUTES)("%s %s -> 404", async (method, path, body) => {
125
- const { app } = build(false);
126
- const res = await req(app, method, path, adminHeaders, body);
127
- expect(res.status).toBe(404);
123
+ describe("self-serve flag off", () => {
124
+ it.each(ROUTES)(
125
+ "%s %s answers exactly as with the flag on",
126
+ async (method, path, body) => {
127
+ const off = await req(build(false).app, method, path, adminHeaders, body);
128
+ const on = await req(build(true).app, method, path, adminHeaders, body);
129
+ expect(off.status).not.toBe(404);
130
+ expect(off.status).toBe(on.status);
131
+ expect(await off.json()).toEqual(await on.json());
132
+ },
133
+ );
134
+
135
+ it.each(ROUTES)("%s %s: non-admin cookie -> 403", async (m, p, b) => {
136
+ const res = await req(
137
+ build(false).app,
138
+ m,
139
+ p,
140
+ { Cookie: `admin_session=${await cookie(false)}` },
141
+ b,
142
+ );
143
+ expect(res.status).toBe(403);
128
144
  });
129
145
  });
130
146
 
@@ -1,9 +1,8 @@
1
1
  /**
2
2
  * admin/src/accounts-api.ts
3
3
  * Admin-only /accounts API (SSP-5.1): list/get/create/patch self-serve
4
- * accounts. Flag-gated (404 when SHIPWRIGHT_SELF_SERVE_ENABLED is off, checked
5
- * before auth) and admin-only (admin cookie or scope "*" key); every other
6
- * caller class gets 403.
4
+ * accounts. Admin-only (admin cookie or scope "*" key); every other caller
5
+ * class gets 403. Available whether or not self-serve signup is enabled.
7
6
  *
8
7
  * POST /accounts goes through AccountService.create(), which seeds the owner
9
8
  * AccountMember row — so that owner's first login joins this account instead
@@ -50,6 +49,10 @@ interface AccountsApiDeps {
50
49
  * lockdown/restore side effect (SSP-8.2).
51
50
  */
52
51
  accountLifecycle: Pick<AccountLifecycle, "update">;
52
+ /**
53
+ * @deprecated Ignored: the accounts API no longer depends on the self-serve
54
+ * setting. Kept optional so existing callers keep compiling.
55
+ */
53
56
  selfServe?: SelfServeConfig;
54
57
  sessionSecret: string;
55
58
  adminApiKeys?: Map<string, AdminApiKey>;
@@ -61,7 +64,7 @@ const jsonError = { content: { "application/json": { schema: ErrorSchema } } };
61
64
  const errorResponses = {
62
65
  401: { description: "Unauthorized", ...jsonError },
63
66
  403: { description: "Forbidden (non-admin caller)", ...jsonError },
64
- 404: { description: "Not found (or self-serve disabled)", ...jsonError },
67
+ 404: { description: "Not found", ...jsonError },
65
68
  };
66
69
 
67
70
  const listAccountsRoute = createRoute({
@@ -70,7 +73,7 @@ const listAccountsRoute = createRoute({
70
73
  tags: ["accounts"],
71
74
  summary: "List accounts",
72
75
  description:
73
- "Admin-only, flag-gated. Returns every account with agentCount and memberCount.",
76
+ "Admin-only. Returns every account with agentCount and memberCount.",
74
77
  responses: {
75
78
  200: {
76
79
  description: "Accounts",
@@ -85,7 +88,7 @@ const getAccountRoute = createRoute({
85
88
  path: "/accounts/{id}",
86
89
  tags: ["accounts"],
87
90
  summary: "Get an account",
88
- description: "Admin-only, flag-gated.",
91
+ description: "Admin-only.",
89
92
  request: { params: AccountIdParamSchema },
90
93
  responses: {
91
94
  200: {
@@ -102,7 +105,7 @@ const createAccountRoute = createRoute({
102
105
  tags: ["accounts"],
103
106
  summary: "Create an account",
104
107
  description:
105
- "Admin-only, flag-gated. Creates the account and seeds ownerEmail as its owner member, so that owner's first login joins this account. 409 if ownerEmail already belongs to an account.",
108
+ "Admin-only. Creates the account and seeds ownerEmail as its owner member, so that owner's first login joins this account. 409 if ownerEmail already belongs to an account.",
106
109
  request: {
107
110
  body: {
108
111
  content: { "application/json": { schema: CreateAccountBodySchema } },
@@ -125,7 +128,7 @@ const patchAccountRoute = createRoute({
125
128
  tags: ["accounts"],
126
129
  summary: "Update an account",
127
130
  description:
128
- "Admin-only, flag-gated. Updates name, maxAgents, plan, status and/or trialExpiresAt. status=suspended (or trial_expired) disables every enabled cron of the account's agents with a lockdown marker; status=active re-enables exactly those, and requires trialExpiresAt to be cleared or in the future (422 otherwise). Nothing is deleted.",
131
+ "Admin-only. Updates name, maxAgents, plan, status and/or trialExpiresAt. status=suspended (or trial_expired) disables every enabled cron of the account's agents with a lockdown marker; status=active re-enables exactly those, and requires trialExpiresAt to be cleared or in the future (422 otherwise). Nothing is deleted.",
129
132
  request: {
130
133
  params: AccountIdParamSchema,
131
134
  body: {
@@ -175,7 +178,7 @@ function serialize(a: {
175
178
  export function createAccountsApp(
176
179
  deps: AccountsApiDeps,
177
180
  ): OpenAPIHono<AdminAuthEnv> {
178
- const { accountService, selfServe } = deps;
181
+ const { accountService } = deps;
179
182
 
180
183
  const app = new OpenAPIHono<AdminAuthEnv>({
181
184
  defaultHook: (result, c) => {
@@ -208,13 +211,7 @@ export function createAccountsApp(
208
211
  adminApiKeys: deps.adminApiKeys,
209
212
  });
210
213
 
211
- // Flag gate runs before auth so a disabled deployment reveals nothing.
212
- const flagGate: Parameters<typeof app.use>[1] = async (c, next) => {
213
- if (selfServe?.enabled !== true) return c.json({ error: "Not found" }, 404);
214
- return next();
215
- };
216
214
  // "/accounts/*" also matches the bare "/accounts" path in Hono.
217
- app.use("/accounts/*", flagGate);
218
215
  app.use("/accounts/*", authMiddleware);
219
216
 
220
217
  const requireAdmin = (c: { get: (k: "isAdmin") => unknown }) => {
@@ -204,6 +204,8 @@ export function buildProvisioner(
204
204
 
205
205
  return new KubernetesAgentProvisioner(k8s, agentTokenService, {
206
206
  namespace,
207
+ // Tenant pod label + CPU limit only on deployments with open signup.
208
+ tenantPodRestrictions: env.SHIPWRIGHT_SELF_SERVE_ENABLED === "enabled",
207
209
  image,
208
210
  imageTag,
209
211
  ...(images ? { images } : {}),
@@ -41,3 +41,30 @@ describe("buildProvisioner pod label configuration", () => {
41
41
  ).toThrow("reserved key");
42
42
  });
43
43
  });
44
+
45
+ describe("buildProvisioner tenant pod restrictions", () => {
46
+ const config = (env: Record<string, string>) =>
47
+ (
48
+ buildProvisioner(
49
+ { SHIPWRIGHT_K8S_PROVISIONING: "enabled", ...env },
50
+ {} as AgentTokenService,
51
+ ) as unknown as { config: { tenantPodRestrictions?: boolean } }
52
+ ).config;
53
+
54
+ it("are on only when SHIPWRIGHT_SELF_SERVE_ENABLED is exactly enabled", () => {
55
+ expect(
56
+ config({ SHIPWRIGHT_SELF_SERVE_ENABLED: "enabled" })
57
+ .tenantPodRestrictions,
58
+ ).toBe(true);
59
+ });
60
+
61
+ it.each(["", "true", "disabled"])(
62
+ "are off for SHIPWRIGHT_SELF_SERVE_ENABLED=%p and when unset",
63
+ (value) => {
64
+ expect(
65
+ config({ SHIPWRIGHT_SELF_SERVE_ENABLED: value }).tenantPodRestrictions,
66
+ ).toBe(false);
67
+ expect(config({}).tenantPodRestrictions).toBe(false);
68
+ },
69
+ );
70
+ });
package/src/admin-boot.ts CHANGED
@@ -241,15 +241,14 @@ export async function startAdmin(
241
241
  const agentPluginService = new AgentPluginService(prisma);
242
242
  const agentMarketplaceService = new AgentMarketplaceService(prisma);
243
243
  const agentMemberService = new AgentMemberService(prisma);
244
- // Account-aware caller scope (SSP-2.1). Account membership contributes
245
- // agents only when the self-serve flag is on; off → AgentMember-only.
244
+ // Account-aware caller scope (SSP-2.1). Owners get their account's agents
245
+ // whether or not self-serve signup is enabled.
246
246
  const accountService = new AccountService(prisma);
247
247
  const callerScopeResolver = createCallerScopeResolver(
248
248
  callerScopeDepsFromServices({
249
249
  accountService,
250
250
  agentMemberService,
251
251
  }),
252
- process.env.SHIPWRIGHT_SELF_SERVE_ENABLED === "enabled",
253
252
  );
254
253
  const agentChatTokenService = new AgentChatTokenService(prisma);
255
254
  const agentCronRunStatsService = new AgentCronRunStatsService(prisma);
@@ -297,8 +296,9 @@ export async function startAdmin(
297
296
  .then((v) => v.trim())
298
297
  .catch(() => "0.0.0");
299
298
  const adminApiKeys = parseAdminApiKeys(process.env.SHIPWRIGHT_ADMIN_API_KEYS);
300
- // Self-serve provisioning config (SSP-1.3) — read once at startup and
301
- // injected as deps; no consumers yet.
299
+ // Self-serve config (SSP-1.3), read once at startup. `enabled` controls only
300
+ // open signup (an unknown verified user creating an account); the tenant pod
301
+ // restrictions read the same env var in buildProvisioner.
302
302
  const selfServe = parseSelfServeConfig(process.env);
303
303
  // Account status transitions → cron lockdown/restore (SSP-8.2). Shared by
304
304
  // the /accounts PATCH handler, the admin UI and the account sweepers.
@@ -810,11 +810,12 @@ export async function startAdmin(
810
810
  }
811
811
 
812
812
  // Account trial sweepers (SSP-8.2) — the account-level counterparts of the
813
- // two per-agent sweepers above (which keep running unchanged). Flag-gated:
814
- // accounts only exist when self-serve is enabled. Same cadences as the
815
- // per-agent pair: hourly warning, minutely expiry/lockdown. Registered
816
- // HERE, never inside an app factory. No deleteAgentFully call anywhere.
817
- if (selfServe.enabled) {
813
+ // two per-agent sweepers above (which keep running unchanged). Accounts
814
+ // exist whether or not self-serve signup is enabled, so they always run.
815
+ // Same cadences as the per-agent pair: hourly warning, minutely
816
+ // expiry/lockdown. Registered HERE, never inside an app factory. No
817
+ // deleteAgentFully call anywhere.
818
+ {
818
819
  const accountTrialWarningSweeper = new AccountTrialWarningSweeper({
819
820
  accounts: accountService,
820
821
  agentEnvService,
@@ -1671,6 +1671,71 @@ describe("admin UI — account users create / delete agents (SSP-4.2)", () => {
1671
1671
  });
1672
1672
  });
1673
1673
 
1674
+ describe("platform admin account choice", () => {
1675
+ let adminCookie: string;
1676
+ beforeAll(async () => {
1677
+ adminCookie = await makeSessionCookie(true, "admin@example.com");
1678
+ });
1679
+
1680
+ const accountRows = (ids: string[]) =>
1681
+ ids.map((id) => ({ id, name: `Acct ${id}` }));
1682
+
1683
+ function adminDeps(ids: string[]) {
1684
+ const { deps, created } = depsCapturingCreate(null);
1685
+ return {
1686
+ created,
1687
+ deps: {
1688
+ ...deps,
1689
+ accountServices: {
1690
+ accounts: {
1691
+ listWithCounts: async () => accountRows(ids),
1692
+ getByMemberEmail: async () => null,
1693
+ },
1694
+ members: { getByEmail: async () => null },
1695
+ } as never,
1696
+ } as AdminUIDeps,
1697
+ };
1698
+ }
1699
+
1700
+ it("GET /admin/agents/new — shows an account select only with several accounts", async () => {
1701
+ const several = await createAdminUIApp(
1702
+ adminDeps(["a1", "a2"]).deps,
1703
+ ).request("/admin/agents/new", {
1704
+ headers: { Cookie: `admin_session=${adminCookie}` },
1705
+ });
1706
+ const severalHtml = await several.text();
1707
+ expect(severalHtml).toContain('name="accountId"');
1708
+ expect(severalHtml).toContain("Acct a2");
1709
+ expect(severalHtml).toMatch(/<select[^>]*name="type"/);
1710
+
1711
+ const one = await createAdminUIApp(adminDeps(["a1"]).deps).request(
1712
+ "/admin/agents/new",
1713
+ { headers: { Cookie: `admin_session=${adminCookie}` } },
1714
+ );
1715
+ expect(await one.text()).not.toContain('name="accountId"');
1716
+ });
1717
+
1718
+ it("GET /admin/agents/new — an owner never sees an account or type choice", async () => {
1719
+ const { deps } = depsCapturingCreate("acct-a");
1720
+ const res = await createAdminUIApp(deps).request("/admin/agents/new", {
1721
+ headers: { Cookie: `admin_session=${accountCookie}` },
1722
+ });
1723
+ const html = await res.text();
1724
+ expect(html).not.toContain('name="accountId"');
1725
+ expect(html).not.toMatch(/<select[^>]*name="type"/);
1726
+ });
1727
+
1728
+ it("POST /admin/agents — the chosen account and type are used", async () => {
1729
+ const { deps, created } = adminDeps(["a1", "a2"]);
1730
+ const res = await createAdminUIApp(deps).request(
1731
+ "/admin/agents",
1732
+ form(adminCookie, { name: "made", type: TYPE, accountId: "a2" }),
1733
+ );
1734
+ expect(res.status).toBe(302);
1735
+ expect(created[0]).toMatchObject({ accountId: "a2", specialty: TYPE });
1736
+ });
1737
+ });
1738
+
1674
1739
  it("POST /admin/agents — non-admin without an account gets 403", async () => {
1675
1740
  const { deps, created } = depsCapturingCreate(null);
1676
1741
  const res = await createAdminUIApp(deps).request(
@@ -149,8 +149,7 @@ export function renderAccountPage(opts: AccountPageOpts): string {
149
149
  }
150
150
 
151
151
  /** Shown on /admin/agents in place of the create button when maxAgents = 0. */
152
- export function renderZeroQuotaNotice(contactEmail: string): string {
153
- const email = escapeHtml(contactEmail);
154
- return `<div class="alert alert-warning" id="zero-quota-notice">Email ${email} to request a trial</div>
152
+ export function renderZeroQuotaNotice(): string {
153
+ return `<div class="alert alert-warning" id="zero-quota-notice">This account has reached its agent limit.</div>
155
154
  <button type="button" class="btn btn-primary" disabled aria-disabled="true">+ New agent</button>`;
156
155
  }