@app-vitals/agent-admin 1.108.1 → 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.
@@ -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
  : {}),
@@ -18,6 +18,9 @@ const ALLOWED = new Set([
18
18
  "admin/src/github-enterprise-api.ts",
19
19
  "admin/src/admin-boot.ts",
20
20
  "admin/src/github-installation-wiring.ts",
21
+ // multi-account-2.6: the account move tool re-scopes rows (id, accountId,
22
+ // role only); the last test below keeps it away from the key column.
23
+ "admin/src/account-move.ts",
21
24
  ]);
22
25
 
23
26
  function sources(dir: string, out: string[] = []): string[] {
@@ -109,6 +112,20 @@ describe("GitHub Enterprise key isolation", () => {
109
112
  }
110
113
  });
111
114
 
115
+ it("the account move tool never selects or returns the private key", () => {
116
+ const src = readFileSync(join(REPO, "admin/src/account-move.ts"), "utf-8");
117
+ expect(src).not.toMatch(
118
+ /privateKeyEncrypted|getPrivateKey|github-enterprise-apps/,
119
+ );
120
+ // Every query on the table names its columns, so the key is never loaded.
121
+ const calls = src.split("gitHubEnterpriseApp.").slice(1);
122
+ expect(calls.length).toBeGreaterThan(0);
123
+ for (const call of calls) {
124
+ const body = call.slice(0, call.indexOf("})") + 2);
125
+ expect(body).toMatch(/select/);
126
+ }
127
+ });
128
+
112
129
  it("the upload field name is only handled by the pem-upload parser", () => {
113
130
  const handlers = files
114
131
  .map((f) => relative(REPO, f))
@@ -0,0 +1,201 @@
1
+ /**
2
+ * admin/src/move-accounts.ts
3
+ *
4
+ * multi-account-2.6: admin CLI that creates accounts and moves members,
5
+ * agents and deployment-wide settings between accounts, driven by a mapping
6
+ * file kept outside the repo. Ships in the admin image; the runbook (order
7
+ * with the task-data move, pausing scheduled jobs, recovery) is
8
+ * docs/account-move.md.
9
+ *
10
+ * bun admin/src/move-accounts.ts --mapping FILE # preview (default)
11
+ * bun admin/src/move-accounts.ts --mapping FILE --apply --receipt OUT
12
+ * bun admin/src/move-accounts.ts --reverse RECEIPT # preview the reverse
13
+ * bun admin/src/move-accounts.ts --reverse RECEIPT --apply
14
+ *
15
+ * Reads DATABASE_URL_SHIPWRIGHT_ADMIN. Exit codes: 0 ok, 1 refused (nothing
16
+ * written), 2 usage or input error, 3 unexpected error (rolled back).
17
+ */
18
+
19
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
20
+ import { parseArgs } from "node:util";
21
+ import type { PrismaClient } from "../prisma/client/client.ts";
22
+ import {
23
+ applyMove,
24
+ applyReverse,
25
+ formatPlan,
26
+ MoveInputError,
27
+ MoveRefusedError,
28
+ parseMapping,
29
+ parseReceipt,
30
+ planMove,
31
+ planReverse,
32
+ } from "./account-move.ts";
33
+ import { createAdminPrismaClient } from "./prisma-client.ts";
34
+
35
+ export const USAGE = `Move accounts, members, agents and deployment-wide settings in the admin database.
36
+
37
+ Usage:
38
+ move-accounts --mapping FILE preview (default, writes nothing)
39
+ move-accounts --mapping FILE --apply --receipt OUT apply in one transaction; OUT must not exist
40
+ move-accounts --reverse RECEIPT preview putting back what RECEIPT moved
41
+ move-accounts --reverse RECEIPT --apply put it back
42
+
43
+ Mapping file (keep it outside the repo; see admin/account-move.example.json):
44
+ { "accounts": [ { "id": "example-account", "name": "Example", "maxAgents": 1,
45
+ "agents": ["example-agent"],
46
+ "members": [ { "email": "owner@example.com", "role": "owner" } ] } ],
47
+ "settings": [ { "setting": "slackConfigToken", "toAccountId": "example-account" } ] }
48
+
49
+ Reads DATABASE_URL_SHIPWRIGHT_ADMIN. See docs/account-move.md.
50
+ Exit codes: 0 ok, 1 refused (nothing written), 2 usage or input error.`;
51
+
52
+ export interface CliDeps {
53
+ /** Injected for tests; otherwise built from DATABASE_URL_SHIPWRIGHT_ADMIN. */
54
+ db?: PrismaClient;
55
+ stdout?: (line: string) => void;
56
+ stderr?: (line: string) => void;
57
+ }
58
+
59
+ class UsageError extends Error {}
60
+
61
+ function readJson(path: string): unknown {
62
+ try {
63
+ return JSON.parse(readFileSync(path, "utf8"));
64
+ } catch (err) {
65
+ throw new MoveInputError(
66
+ `cannot read JSON from ${path}: ${(err as Error).message}`,
67
+ );
68
+ }
69
+ }
70
+
71
+ export async function runMoveAccountsCli(
72
+ argv: string[],
73
+ deps: CliDeps = {},
74
+ ): Promise<number> {
75
+ const out = deps.stdout ?? ((s) => console.log(s));
76
+ const err = deps.stderr ?? ((s) => console.error(s));
77
+ let db = deps.db;
78
+ const ownsDb = db === undefined;
79
+ try {
80
+ const { values } = parseArgs({
81
+ args: argv,
82
+ options: {
83
+ mapping: { type: "string" },
84
+ reverse: { type: "string" },
85
+ receipt: { type: "string" },
86
+ apply: { type: "boolean", default: false },
87
+ help: { type: "boolean", short: "h", default: false },
88
+ },
89
+ strict: true,
90
+ allowPositionals: false,
91
+ });
92
+ if (values.help) {
93
+ out(USAGE);
94
+ return 0;
95
+ }
96
+ if ((values.mapping === undefined) === (values.reverse === undefined)) {
97
+ throw new UsageError("give exactly one of --mapping or --reverse");
98
+ }
99
+ if (values.mapping !== undefined && values.apply) {
100
+ if (values.receipt === undefined) {
101
+ throw new UsageError("--apply with --mapping needs --receipt OUT");
102
+ }
103
+ if (existsSync(values.receipt)) {
104
+ throw new UsageError(
105
+ `receipt ${values.receipt} already exists; never overwrite a receipt, pick a new path`,
106
+ );
107
+ }
108
+ }
109
+ if (values.reverse !== undefined && values.receipt !== undefined) {
110
+ throw new UsageError("--receipt is only for --mapping --apply");
111
+ }
112
+ if (values.mapping === undefined && !values.apply && values.receipt) {
113
+ throw new UsageError("--receipt needs --apply");
114
+ }
115
+
116
+ // Parse the input file before touching the database.
117
+ const mapping =
118
+ values.mapping !== undefined
119
+ ? parseMapping(readJson(values.mapping))
120
+ : undefined;
121
+ const receipt =
122
+ values.reverse !== undefined
123
+ ? parseReceipt(readJson(values.reverse))
124
+ : undefined;
125
+
126
+ if (db === undefined) {
127
+ const url = process.env.DATABASE_URL_SHIPWRIGHT_ADMIN;
128
+ if (!url) {
129
+ throw new UsageError("DATABASE_URL_SHIPWRIGHT_ADMIN is not set");
130
+ }
131
+ db = createAdminPrismaClient(url);
132
+ }
133
+
134
+ if (mapping !== undefined) {
135
+ if (!values.apply) {
136
+ out("PREVIEW (nothing written; add --apply --receipt OUT to move):");
137
+ out(formatPlan(await planMove(db, mapping)));
138
+ return 0;
139
+ }
140
+ const receiptPath = values.receipt as string;
141
+ const applied = await applyMove(db, mapping, {
142
+ // Written before commit so a committed move always has its receipt.
143
+ beforeCommit: (r) =>
144
+ writeFileSync(receiptPath, `${JSON.stringify(r, null, 2)}\n`, {
145
+ flag: "wx",
146
+ }),
147
+ });
148
+ out(`APPLIED. Receipt: ${receiptPath}`);
149
+ out(
150
+ formatPlan({
151
+ changes: applied.changes,
152
+ warnings: applied.warnings,
153
+ skipped: [],
154
+ }),
155
+ );
156
+ return 0;
157
+ }
158
+
159
+ const r = receipt as NonNullable<typeof receipt>;
160
+ if (!values.apply) {
161
+ out("REVERSE PREVIEW (nothing written; add --apply to move back):");
162
+ out(formatPlan(await planReverse(db, r)));
163
+ return 0;
164
+ }
165
+ out("REVERSED:");
166
+ out(formatPlan(await applyReverse(db, r)));
167
+ return 0;
168
+ } catch (e) {
169
+ if (e instanceof MoveRefusedError) {
170
+ err("REFUSED (nothing written):");
171
+ for (const reason of e.reasons) err(` - ${reason}`);
172
+ return 1;
173
+ }
174
+ if (e instanceof UsageError || e instanceof MoveInputError) {
175
+ err(`error: ${e.message}`);
176
+ err("run with --help for usage");
177
+ return 2;
178
+ }
179
+ if (e instanceof TypeError && "code" in e) {
180
+ // parseArgs: unknown or malformed option.
181
+ err(`error: ${e.message}`);
182
+ return 2;
183
+ }
184
+ throw e;
185
+ } finally {
186
+ if (ownsDb && db !== undefined) await db.$disconnect();
187
+ }
188
+ }
189
+
190
+ if (import.meta.main) {
191
+ runMoveAccountsCli(process.argv.slice(2)).then(
192
+ (code) => process.exit(code),
193
+ (e) => {
194
+ console.error(
195
+ "[move-accounts] failed; the transaction rolls back on any error before commit:",
196
+ e,
197
+ );
198
+ process.exit(3);
199
+ },
200
+ );
201
+ }
@@ -189,6 +189,12 @@ export const CreateAgentBodySchema = z
189
189
  .openapi({ example: "true" }),
190
190
  claudeCodeOauthToken: z.string().optional(),
191
191
  anthropicApiKey: z.string().optional(),
192
+ /**
193
+ * Account for the new agent. Platform admins only: with one account it is
194
+ * used when omitted, with several it must be given. Ignored for account
195
+ * owners, whose agents always go to their own account.
196
+ */
197
+ accountId: z.string().min(1).optional().openapi({ example: "acct_123" }),
192
198
  /**
193
199
  * Explicit env values. They override the agent template per key and are
194
200
  * kept as the agent's own (never overwritten by a template reconcile).