@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
@@ -11,7 +11,7 @@ import { generateKeyPairSync } from "node:crypto";
11
11
  import { readFileSync } from "node:fs";
12
12
  import { sign } from "hono/jwt";
13
13
  import type { Prisma } from "../prisma/client/client.ts";
14
- import { getSelfServeSpecialty } from "./account-agent-create.ts";
14
+ import { getOwnerAgentSpecialty } from "./account-agent-create.ts";
15
15
  import type { PatchAgentCronRunInput } from "./agent-cron-runs.ts";
16
16
  import { AgentEnvService } from "./agent-envs.ts";
17
17
  import type {
@@ -68,7 +68,7 @@ function fakeSpecialtyTypes(
68
68
  // (the platform test run points it at the fixture specialty, not "coding").
69
69
  byType: Record<string, SpecialtyType> = {
70
70
  coding: CODING_TYPE,
71
- [getSelfServeSpecialty()]: CODING_TYPE,
71
+ [getOwnerAgentSpecialty()]: CODING_TYPE,
72
72
  },
73
73
  ): AdminDeps["specialtyRegistry"] {
74
74
  return {
@@ -5392,7 +5392,7 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5392
5392
  },
5393
5393
  });
5394
5394
 
5395
- it("account user creates an agent stamped with their own accountId and the self-serve specialty", async () => {
5395
+ it("account user creates an agent stamped with their own accountId and the default type", async () => {
5396
5396
  const { deps, created } = makeAccountDeps("acct-a");
5397
5397
  const res = await post(
5398
5398
  createAdminApp(deps),
@@ -5403,7 +5403,7 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5403
5403
  expect(created).toHaveLength(1);
5404
5404
  expect(created[0]).toMatchObject({
5405
5405
  accountId: "acct-a",
5406
- specialty: getSelfServeSpecialty(),
5406
+ specialty: getOwnerAgentSpecialty(),
5407
5407
  });
5408
5408
  });
5409
5409
 
@@ -5417,7 +5417,7 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5417
5417
  expect(res.status).toBe(200);
5418
5418
  expect(created[0]).toMatchObject({
5419
5419
  accountId: "acct-a",
5420
- specialty: getSelfServeSpecialty(),
5420
+ specialty: getOwnerAgentSpecialty(),
5421
5421
  });
5422
5422
  });
5423
5423
 
@@ -5443,17 +5443,115 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5443
5443
  expect(created).toHaveLength(0);
5444
5444
  });
5445
5445
 
5446
- it("platform admin create stays unassigned (no accountId)", async () => {
5447
- const { deps, created } = makeAccountDeps("acct-a");
5446
+ // A transaction double answering the few queries createAgent() makes for
5447
+ // account assignment and the quota check.
5448
+ function fakeTx(accounts: string[], opts: { agents?: number } = {}) {
5449
+ return {
5450
+ account: {
5451
+ findMany: async () => accounts.map((id) => ({ id })),
5452
+ },
5453
+ $queryRaw: async () => [{ status: "active", maxAgents: 1 }],
5454
+ agent: { count: async () => opts.agents ?? 0 },
5455
+ agentEnv: { findMany: async () => [] },
5456
+ } as never;
5457
+ }
5458
+
5459
+ function depsWithAccounts(
5460
+ accounts: string[],
5461
+ opts: { agents?: number } = {},
5462
+ accountId: string | null = "acct-a",
5463
+ ) {
5464
+ const made = makeAccountDeps(accountId);
5465
+ const tx = fakeTx(accounts, opts);
5466
+ made.deps = {
5467
+ ...made.deps,
5468
+ agentService: {
5469
+ ...made.deps.agentService,
5470
+ runTransaction: async (fn: (tx: never) => Promise<unknown>) => fn(tx),
5471
+ } as never,
5472
+ };
5473
+ return made;
5474
+ }
5475
+
5476
+ it("platform admin create with no accounts stays unassigned", async () => {
5477
+ const { deps, created } = depsWithAccounts([]);
5448
5478
  const res = await post(
5449
5479
  createAdminApp(deps),
5450
- { name: "Admin Made", specialty: "coding", accountId: "acct-b" },
5480
+ { name: "Admin Made", specialty: "coding" },
5451
5481
  await makeSessionCookie(),
5452
5482
  );
5453
5483
  expect(res.status).toBe(200);
5454
5484
  expect(created[0]?.accountId).toBeUndefined();
5455
5485
  });
5456
5486
 
5487
+ it("platform admin create with one account assigns it without asking", async () => {
5488
+ const { deps, created } = depsWithAccounts(["acct-only"]);
5489
+ const res = await post(
5490
+ createAdminApp(deps),
5491
+ { name: "Admin Made", specialty: "coding" },
5492
+ await makeSessionCookie(),
5493
+ );
5494
+ expect(res.status).toBe(200);
5495
+ expect(created[0]).toMatchObject({
5496
+ accountId: "acct-only",
5497
+ specialty: "coding",
5498
+ });
5499
+ });
5500
+
5501
+ it("platform admin create with several accounts and none named is a clear 400", async () => {
5502
+ const { deps, created } = depsWithAccounts(["acct-a", "acct-b"]);
5503
+ const res = await post(
5504
+ createAdminApp(deps),
5505
+ { name: "Admin Made", specialty: "coding" },
5506
+ await makeSessionCookie(),
5507
+ );
5508
+ expect(res.status).toBe(400);
5509
+ expect(((await res.json()) as { error: string }).error).toContain(
5510
+ "Choose the account",
5511
+ );
5512
+ expect(created).toHaveLength(0);
5513
+ });
5514
+
5515
+ it("platform admin create with several accounts uses the named account and type", async () => {
5516
+ const { deps, created } = depsWithAccounts(["acct-a", "acct-b"]);
5517
+ const res = await post(
5518
+ createAdminApp(deps),
5519
+ { name: "Admin Made", specialty: "coding", accountId: "acct-b" },
5520
+ await makeSessionCookie(),
5521
+ );
5522
+ expect(res.status).toBe(200);
5523
+ expect(created[0]).toMatchObject({
5524
+ accountId: "acct-b",
5525
+ specialty: "coding",
5526
+ });
5527
+ });
5528
+
5529
+ it("platform admin is not limited by the account's agent limit", async () => {
5530
+ const { deps, created } = depsWithAccounts(["acct-a"], { agents: 5 });
5531
+ const res = await post(
5532
+ createAdminApp(deps),
5533
+ { name: "Admin Made", specialty: "coding" },
5534
+ await makeSessionCookie(),
5535
+ );
5536
+ expect(res.status).toBe(200);
5537
+ expect(created).toHaveLength(1);
5538
+ });
5539
+
5540
+ it("an owner at the limit gets the neutral limit message", async () => {
5541
+ const { deps, created } = depsWithAccounts(["acct-a"], { agents: 1 });
5542
+ const res = await post(
5543
+ createAdminApp(deps),
5544
+ { name: "Mine", specialty: "coding" },
5545
+ await accountCookie(),
5546
+ );
5547
+ expect(res.status).toBe(403);
5548
+ const message = ((await res.json()) as { error: string }).error;
5549
+ expect(message).toContain("agent limit");
5550
+ expect(message.toLowerCase()).not.toContain("trial");
5551
+ expect(message).not.toContain("@");
5552
+ expect(created).toHaveLength(0);
5553
+ });
5554
+
5457
5555
  it.each([
5458
5556
  ["quota_exceeded", "agent limit"],
5459
5557
  ["account_inactive", "not active"],
package/src/agents-api.ts CHANGED
@@ -37,7 +37,7 @@ import {
37
37
  ACCOUNT_CREATE_ERROR_MESSAGES,
38
38
  accountIdFromScope,
39
39
  createAccountIdFromScope,
40
- getSelfServeSpecialty,
40
+ getOwnerAgentSpecialty,
41
41
  isAccountCreateErrorCode,
42
42
  } from "./account-agent-create.ts";
43
43
  import {
@@ -2716,7 +2716,9 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2716
2716
  // unassigned agents). A session user with an account (flag on) may create
2717
2717
  // agents in THEIR account only: accountId comes from the resolved scope —
2718
2718
  // never the body — and the type is forced to the self-serve specialty.
2719
- let accountId: string | undefined;
2719
+ // Admins may name an account (body.accountId); with none named,
2720
+ // createAgent() picks the only account or asks for a choice.
2721
+ let accountId: string | undefined = body.accountId;
2720
2722
  let memberCreator: MemberCreator = {
2721
2723
  platformAdmin: true,
2722
2724
  ownerOfAccountId: null,
@@ -2776,7 +2778,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2776
2778
  {
2777
2779
  name: body.name,
2778
2780
  specialty:
2779
- accountId !== undefined ? getSelfServeSpecialty() : body.specialty,
2781
+ c.get("isAdmin") === true ? body.specialty : getOwnerAgentSpecialty(),
2780
2782
  ...(accountId !== undefined ? { accountId } : {}),
2781
2783
  // PAI-1.2: owner comes from the authenticated caller only; the body
2782
2784
  // schema has no owner field, so a client-supplied one is stripped.
@@ -252,7 +252,7 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
252
252
  expect(await prisma.accountMember.findMany()).toEqual([]);
253
253
  });
254
254
 
255
- it("with several accounts and none on the agent, creation fails and rolls back records made for earlier emails", async () => {
255
+ it("with several accounts and an owner-less agent, a member email still fails and rolls back records made for earlier emails", async () => {
256
256
  const acct = await prisma.account.create({ data: { name: "A" } });
257
257
  await prisma.accountMember.create({
258
258
  data: { accountId: acct.id, email: "known@example.com", role: "owner" },
@@ -262,7 +262,9 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
262
262
  deps(),
263
263
  baseInput({
264
264
  memberEmailsRaw: "known@example.com\nnew@example.com",
265
- memberCreator: { platformAdmin: true, ownerOfAccountId: null },
265
+ // No memberCreator: no account is chosen for the agent, so the new
266
+ // email has nowhere to go.
267
+ memberCreator: { platformAdmin: false, ownerOfAccountId: null },
266
268
  }),
267
269
  );
268
270
  expect(result.ok).toBe(false);
@@ -593,6 +595,114 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
593
595
  });
594
596
  });
595
597
 
598
+ describe("account assignment for new agents", () => {
599
+ const admin = { platformAdmin: true, ownerOfAccountId: null };
600
+
601
+ it("with no accounts, an admin create stays unassigned", async () => {
602
+ const result = await createAgent(
603
+ deps(),
604
+ baseInput({ memberCreator: admin }),
605
+ );
606
+ if (!result.ok) throw new Error("expected success");
607
+ expect(result.agent.accountId).toBeNull();
608
+ });
609
+
610
+ it("with one account, an admin create is assigned to it without asking", async () => {
611
+ const acct = await prisma.account.create({ data: { name: "Solo" } });
612
+ const result = await createAgent(
613
+ deps(),
614
+ baseInput({ memberCreator: admin }),
615
+ );
616
+ if (!result.ok) throw new Error("expected success");
617
+ expect(result.agent.accountId).toBe(acct.id);
618
+ });
619
+
620
+ it("with one account, a new member email gets a membership in the agent's account", async () => {
621
+ const acct = await prisma.account.create({ data: { name: "Solo" } });
622
+ const result = await createAgent(
623
+ deps(),
624
+ baseInput({ memberCreator: admin, memberEmailsRaw: "new@example.com" }),
625
+ );
626
+ if (!result.ok) throw new Error("expected success");
627
+ const member = await prisma.accountMember.findUniqueOrThrow({
628
+ where: { email: "new@example.com" },
629
+ });
630
+ expect(member.accountId).toBe(acct.id);
631
+ });
632
+
633
+ it("with several accounts, an admin create without an account is rejected and writes nothing", async () => {
634
+ await prisma.account.create({ data: { name: "One" } });
635
+ await prisma.account.create({ data: { name: "Two" } });
636
+ const result = await createAgent(
637
+ deps(),
638
+ baseInput({ memberCreator: admin }),
639
+ );
640
+ expect(result.ok).toBe(false);
641
+ if (result.ok) throw new Error("expected failure");
642
+ expect(result.errorCode).toBe("account_required");
643
+ expect(result.errorMessage).toContain("Choose the account");
644
+ expect(await prisma.agent.count()).toBe(0);
645
+ });
646
+
647
+ it("with several accounts, an admin create naming an account uses it and adds members there", async () => {
648
+ await prisma.account.create({ data: { name: "One" } });
649
+ const two = await prisma.account.create({ data: { name: "Two" } });
650
+ const result = await createAgent(
651
+ deps(),
652
+ baseInput({
653
+ memberCreator: admin,
654
+ accountId: two.id,
655
+ memberEmailsRaw: "new@example.com",
656
+ }),
657
+ );
658
+ if (!result.ok) throw new Error("expected success");
659
+ expect(result.agent.accountId).toBe(two.id);
660
+ expect(
661
+ (
662
+ await prisma.accountMember.findUniqueOrThrow({
663
+ where: { email: "new@example.com" },
664
+ })
665
+ ).accountId,
666
+ ).toBe(two.id);
667
+ });
668
+
669
+ it("an owner stays limited by maxAgents while an admin is not", async () => {
670
+ const acct = await prisma.account.create({
671
+ data: { name: "Capped", maxAgents: 1 },
672
+ });
673
+ const owner = { platformAdmin: false, ownerOfAccountId: acct.id };
674
+ const first = await createAgent(
675
+ deps(),
676
+ baseInput({ name: "first", accountId: acct.id, memberCreator: owner }),
677
+ );
678
+ expect(first.ok).toBe(true);
679
+ const blocked = await createAgent(
680
+ deps(),
681
+ baseInput({ name: "second", accountId: acct.id, memberCreator: owner }),
682
+ );
683
+ expect(blocked).toEqual({ ok: false, errorCode: "quota_exceeded" });
684
+ const byAdmin = await createAgent(
685
+ deps(),
686
+ baseInput({ name: "third", accountId: acct.id, memberCreator: admin }),
687
+ );
688
+ expect(byAdmin.ok).toBe(true);
689
+ expect(await prisma.agent.count({ where: { accountId: acct.id } })).toBe(
690
+ 2,
691
+ );
692
+ });
693
+
694
+ it("an admin cannot create in an inactive account", async () => {
695
+ const acct = await prisma.account.create({
696
+ data: { name: "Off", status: "suspended" },
697
+ });
698
+ const result = await createAgent(
699
+ deps(),
700
+ baseInput({ accountId: acct.id, memberCreator: admin }),
701
+ );
702
+ expect(result).toEqual({ ok: false, errorCode: "account_inactive" });
703
+ });
704
+ });
705
+
596
706
  describe("account quota (SSP-4.1)", () => {
597
707
  async function makeAccount(
598
708
  overrides: { status?: string; maxAgents?: number } = {},
package/src/agents.ts CHANGED
@@ -829,6 +829,7 @@ type CreateAgentErrorCode =
829
829
  | "provision_failed"
830
830
  | "quota_exceeded"
831
831
  | "account_inactive"
832
+ | "account_required"
832
833
  | "member_account_unresolved"
833
834
  | "member_not_permitted"
834
835
  | typeof ANTHROPIC_CREDENTIALS_BLOCKED_CODE;
@@ -909,16 +910,23 @@ function parseLines(
909
910
  async function checkAccountQuota(
910
911
  tx: PrismaTransactionClient,
911
912
  accountId: string,
913
+ opts: { enforceQuota?: boolean } = {},
912
914
  ): Promise<"account_inactive" | "quota_exceeded" | null> {
913
915
  const rows = await tx.$queryRaw<{ status: string; maxAgents: number }[]>`
914
916
  SELECT "status", "maxAgents" FROM "Account" WHERE "id" = ${accountId} FOR UPDATE`;
915
917
  const account = rows[0];
916
918
  if (!account) return "account_inactive";
917
919
  if (account.status !== "active") return "account_inactive";
920
+ // Platform admins are not limited by the per-account agent count.
921
+ if (opts.enforceQuota === false) return null;
918
922
  const count = await tx.agent.count({ where: { accountId } });
919
923
  return count >= account.maxAgents ? "quota_exceeded" : null;
920
924
  }
921
925
 
926
+ /** Shown when an admin creates an agent without an account and several exist. */
927
+ export const ACCOUNT_REQUIRED_MESSAGE =
928
+ "More than one account exists. Choose the account for this agent.";
929
+
922
930
  /** Thrown inside the create transaction so a member failure rolls everything back. */
923
931
  class MemberEnsureFailure extends Error {
924
932
  constructor(
@@ -1028,8 +1036,33 @@ export async function createAgent(
1028
1036
  // Quota enforcement must precede the create so a rejected request
1029
1037
  // writes nothing. Skipped when tx is undefined (admin-ui.ts test
1030
1038
  // doubles without runTransaction pass no real transaction).
1031
- if (input.accountId !== undefined && tx) {
1032
- const denied = await checkAccountQuota(tx, input.accountId);
1039
+ // Every new agent gets an account when accounts exist: a platform
1040
+ // admin who names none gets the only account, or must choose one when
1041
+ // there are several. No account rows keeps the unassigned behavior.
1042
+ let accountId = input.accountId;
1043
+ if (
1044
+ accountId === undefined &&
1045
+ tx &&
1046
+ input.memberCreator?.platformAdmin
1047
+ ) {
1048
+ const accounts = await tx.account.findMany({
1049
+ select: { id: true },
1050
+ take: 2,
1051
+ });
1052
+ if (accounts.length === 1) {
1053
+ accountId = (accounts[0] as { id: string }).id;
1054
+ } else if (accounts.length > 1) {
1055
+ return {
1056
+ ok: false,
1057
+ errorCode: "account_required",
1058
+ errorMessage: ACCOUNT_REQUIRED_MESSAGE,
1059
+ };
1060
+ }
1061
+ }
1062
+ if (accountId !== undefined && tx) {
1063
+ const denied = await checkAccountQuota(tx, accountId, {
1064
+ enforceQuota: input.memberCreator?.platformAdmin !== true,
1065
+ });
1033
1066
  if (denied) return { ok: false, errorCode: denied };
1034
1067
  }
1035
1068
 
@@ -1039,9 +1072,7 @@ export async function createAgent(
1039
1072
  selfHosted: !inCluster,
1040
1073
  specialty,
1041
1074
  restrictSlackToMembers,
1042
- ...(input.accountId !== undefined
1043
- ? { accountId: input.accountId }
1044
- : {}),
1075
+ ...(accountId !== undefined ? { accountId } : {}),
1045
1076
  ...(ownerEmail !== undefined ? { ownerEmail } : {}),
1046
1077
  ...(input.templateDetached ? { templateDetached: true } : {}),
1047
1078
  },
@@ -1178,7 +1209,7 @@ export async function createAgent(
1178
1209
  if (tx) {
1179
1210
  const ensured = await ensureAccountMember(tx, {
1180
1211
  email,
1181
- agentAccountId: input.accountId ?? null,
1212
+ agentAccountId: accountId ?? null,
1182
1213
  ...(input.memberCreator
1183
1214
  ? { creator: input.memberCreator }
1184
1215
  : {}),