@app-vitals/agent-admin 1.132.0 → 1.134.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.
@@ -17,6 +17,7 @@ import type { PrismaClient } from "../prisma/client/client.ts";
17
17
  import type { AdminUIEnv } from "./admin-ui.ts";
18
18
  import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
19
19
  import { AgentEnvService } from "./agent-envs.ts";
20
+ import { AgentGitHubAppService } from "./agent-github-apps.ts";
20
21
  import { AgentPluginService } from "./agent-plugins.ts";
21
22
  import { AgentService } from "./agents.ts";
22
23
  import { createAgentRuntimeApp } from "./api.ts";
@@ -307,6 +308,51 @@ describeOrSkip("github-enterprise API (integration)", () => {
307
308
  expect(((await res.json()) as { error: string }).error).toMatch(/private/i);
308
309
  });
309
310
 
311
+ it("install with several stored apps requires appId and installs the named one", async () => {
312
+ const agent = await prisma.agent.create({ data: { name: "Ghe Agent" } });
313
+ const apps = new AgentGitHubAppService(prisma, identityCrypto);
314
+ for (const [id, slug, clientId] of [
315
+ ["777", "target-app", "Iv1.targetapp0001"],
316
+ ["888", "second-app", "Iv1.secondapp0002"],
317
+ ] as const) {
318
+ await apps.create(agent.id, {
319
+ appId: id,
320
+ slug,
321
+ clientId,
322
+ privateKey: PEM,
323
+ });
324
+ }
325
+ const app = createGithubEnterpriseApp({
326
+ appService,
327
+ agentService: new AgentService(prisma),
328
+ agentEnvService: new AgentEnvService(prisma, identityCrypto),
329
+ agentGitHubAppService: apps,
330
+ sessionSecret: "test-secret-32chars-for-ghe-api!!",
331
+ adminApiKeys: parseAdminApiKeys("root:tok-admin:*"),
332
+ agentTokenService: { validate: async () => null },
333
+ fetchFn: replay({
334
+ "GET /enterprises/acme/installation": "enterprise_installation_success",
335
+ "POST /app/installations/4242/access_tokens": "access_token_success",
336
+ "POST /enterprises/acme/apps/organizations/org-1/installations":
337
+ "install_second_created",
338
+ }),
339
+ apiBase: "https://ghe.test",
340
+ });
341
+ await put(app as never);
342
+ const post = (body: object) =>
343
+ app.request("/github-enterprise/orgs/org-1/install", {
344
+ method: "POST",
345
+ headers: { ...ADMIN, "Content-Type": "application/json" },
346
+ body: JSON.stringify({ agentId: agent.id, ...body }),
347
+ });
348
+ expect((await post({})).status).toBe(422);
349
+ const res = await post({ appId: "888" });
350
+ expect(res.status).toBe(200);
351
+ expect(await res.json()).toMatchObject({
352
+ installation: { appSlug: "second-app" },
353
+ });
354
+ });
355
+
310
356
  it("isolation: no agent-facing path returns the stored key", async () => {
311
357
  const agent = await prisma.agent.create({ data: { name: "Iso Agent" } });
312
358
  const envService = new AgentEnvService(prisma, identityCrypto);
@@ -454,6 +500,79 @@ describeOrSkip("DELETE /orgs/{org}/install (integration)", () => {
454
500
  return { agent, del, blocked };
455
501
  }
456
502
 
503
+ async function setupTwoApps() {
504
+ const appService = new GitHubEnterpriseAppService(
505
+ prisma,
506
+ makeStrictTokenCrypto(ENC_KEY),
507
+ );
508
+ await appService.save({
509
+ role: "installer",
510
+ appId: "12345",
511
+ slug: "example-installer",
512
+ enterpriseSlug: "acme",
513
+ privateKey: PEM,
514
+ });
515
+ const envService = new AgentEnvService(prisma, identityCrypto);
516
+ const agent = await prisma.agent.create({
517
+ data: {
518
+ name: "Uninstall Agent",
519
+ repos: ["acme-eng/a", "acme-eng/b", "other/c"],
520
+ },
521
+ });
522
+ const apps = new AgentGitHubAppService(prisma, identityCrypto);
523
+ for (const [id, slug, clientId] of [
524
+ ["777", "target-app", "Iv1.targetapp0001"],
525
+ ["888", "second-app", "Iv1.secondapp0002"],
526
+ ] as const) {
527
+ await apps.create(agent.id, {
528
+ appId: id,
529
+ slug,
530
+ clientId,
531
+ privateKey: PEM,
532
+ });
533
+ }
534
+ const deleted: string[] = [];
535
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
536
+ const u = new URL(input.toString());
537
+ const key = `${init?.method ?? "GET"} ${u.pathname}`;
538
+ const json = (k: string) =>
539
+ new Response(JSON.stringify(cassette[k]?.body), {
540
+ status: cassette[k]?.status,
541
+ });
542
+ if (key === "GET /enterprises/acme/installation")
543
+ return json("enterprise_installation_success");
544
+ if (key === "POST /app/installations/4242/access_tokens")
545
+ return json("access_token_success");
546
+ if (
547
+ key ===
548
+ "GET /enterprises/acme/apps/organizations/acme-eng/installations"
549
+ )
550
+ return json("org_installations_two_apps");
551
+ const m = key.match(/^DELETE .*\/installations\/(\d+)$/);
552
+ if (m) {
553
+ deleted.push(m[1] as string);
554
+ return new Response(null, { status: 204 });
555
+ }
556
+ throw new Error(`no route for ${key}`);
557
+ }) as typeof fetch;
558
+ const app = createGithubEnterpriseApp({
559
+ appService,
560
+ agentService: new AgentService(prisma),
561
+ agentEnvService: envService,
562
+ agentGitHubAppService: apps,
563
+ sessionSecret: "test-secret-32chars-for-ghe-api!!",
564
+ adminApiKeys: parseAdminApiKeys("root:tok-admin:*"),
565
+ agentTokenService: { validate: async () => null },
566
+ uninstall: {
567
+ agents: new PrismaInstallationAgents(prisma, envService),
568
+ audit: new PrismaInstallationAudit(prisma),
569
+ },
570
+ fetchFn,
571
+ apiBase: "https://ghe.test",
572
+ });
573
+ return { agent, app, deleted };
574
+ }
575
+
457
576
  it("updates the agent's repos and writes an applied audit row", async () => {
458
577
  const { agent, del, blocked } = await setup(204);
459
578
  const res = await del();
@@ -471,6 +590,22 @@ describeOrSkip("DELETE /orgs/{org}/install (integration)", () => {
471
590
  expect(blocked.sort()).toEqual(["acme-eng/a", "acme-eng/b"]);
472
591
  });
473
592
 
593
+ it("with two stored apps only the named app's installation is deleted and repos are kept", async () => {
594
+ const { agent, app, deleted } = await setupTwoApps();
595
+ const q = (extra: string) =>
596
+ app.request(
597
+ `/github-enterprise/orgs/acme-eng/install?agentId=${agent.id}${extra}`,
598
+ { method: "DELETE", headers: ADMIN },
599
+ );
600
+ expect((await q("")).status).toBe(422);
601
+ expect((await q("&appId=888")).status).toBe(200);
602
+ expect(deleted).toEqual(["503"]);
603
+ const row = await prisma.agent.findUniqueOrThrow({
604
+ where: { id: agent.id },
605
+ });
606
+ expect(row.repos).toEqual(["acme-eng/a", "acme-eng/b", "other/c"]);
607
+ });
608
+
474
609
  it("a GitHub refusal writes a failed audit row and keeps the repos", async () => {
475
610
  const { agent, del } = await setup(403);
476
611
  const res = await del();
@@ -123,12 +123,20 @@ const ORGS = "GET /enterprises/acme/apps/installable_organizations";
123
123
  const INSTS = "GET /enterprises/acme/apps/organizations/org-1/installations";
124
124
  const INSTALL = "POST /enterprises/acme/apps/organizations/org-1/installations";
125
125
 
126
+ interface FakeAppRow {
127
+ id: string;
128
+ appId: string;
129
+ slug: string | null;
130
+ clientId: string | null;
131
+ }
132
+
126
133
  function build(
127
134
  opts: {
128
135
  routes?: Record<string, string>;
129
136
  agents?: Record<string, Record<string, string> | null>;
130
137
  refreshAction?: GithubRefreshAction;
131
138
  uninstall?: GithubEnterpriseApiDeps["uninstall"];
139
+ apps?: Record<string, FakeAppRow[]>;
132
140
  } = {},
133
141
  ) {
134
142
  const appService = fakeAppService();
@@ -158,6 +166,14 @@ function build(
158
166
  getByAgentId: async (id: string) =>
159
167
  agents[id] ? ({ env: agents[id] } as never) : null,
160
168
  },
169
+ ...(opts.apps
170
+ ? {
171
+ agentGitHubAppService: {
172
+ list: async (agentId: string) =>
173
+ (opts.apps?.[agentId] ?? []) as never,
174
+ },
175
+ }
176
+ : {}),
161
177
  sessionSecret: "test-secret-32chars-for-ghe-api!!",
162
178
  adminApiKeys: parseAdminApiKeys(
163
179
  "root:tok-admin:*,ro:tok-read:platform.read,bot:tok-agent:agent-1",
@@ -862,6 +878,190 @@ describe("POST install", () => {
862
878
  });
863
879
  });
864
880
 
881
+ const APP_ONE: FakeAppRow = {
882
+ id: "row-1",
883
+ appId: "777",
884
+ slug: "target-app",
885
+ clientId: "Iv1.targetapp0001",
886
+ };
887
+ const APP_TWO: FakeAppRow = {
888
+ id: "row-2",
889
+ appId: "888",
890
+ slug: "second-app",
891
+ clientId: "Iv1.secondapp0002",
892
+ };
893
+
894
+ describe("POST install with several apps", () => {
895
+ const post = (h: ReturnType<typeof build>, body: unknown) =>
896
+ h.app.request("/github-enterprise/orgs/org-1/install", {
897
+ method: "POST",
898
+ headers: JSON_ADMIN,
899
+ body: JSON.stringify(body),
900
+ });
901
+
902
+ it("requires appId when the agent has more than one app and calls nothing", async () => {
903
+ const h = build({ apps: { "agent-1": [APP_ONE, APP_TWO] } });
904
+ await seed(h);
905
+ const res = await post(h, { agentId: "agent-1" });
906
+ expect(res.status).toBe(422);
907
+ expect(((await res.json()) as { error: string }).error).toContain("appId");
908
+ expect(h.calls).not.toContain(INSTALL);
909
+ });
910
+
911
+ it("installs the named app (by app id or row id)", async () => {
912
+ for (const appId of ["888", "row-2"]) {
913
+ const h = build({
914
+ apps: { "agent-1": [APP_ONE, APP_TWO] },
915
+ routes: { [INSTALL]: "install_second_created" },
916
+ });
917
+ await seed(h);
918
+ const res = await post(h, { agentId: "agent-1", appId });
919
+ expect(res.status).toBe(200);
920
+ expect(await res.json()).toMatchObject({
921
+ created: true,
922
+ installation: { id: 602, appSlug: "second-app" },
923
+ });
924
+ }
925
+ });
926
+
927
+ it("an app the agent does not have is 404", async () => {
928
+ const h = build({ apps: { "agent-1": [APP_ONE, APP_TWO] } });
929
+ await seed(h);
930
+ const res = await post(h, { agentId: "agent-1", appId: "999" });
931
+ expect(res.status).toBe(404);
932
+ expect(h.calls).not.toContain(INSTALL);
933
+ });
934
+
935
+ it("defaults to the only app, using its stored client id", async () => {
936
+ const h = build({
937
+ apps: { "agent-1": [APP_ONE] },
938
+ routes: { [INSTALL]: "install_created" },
939
+ });
940
+ await seed(h);
941
+ const res = await post(h, { agentId: "agent-1" });
942
+ expect(res.status).toBe(200);
943
+ expect(h.calls).not.toContain("GET /apps/target-app");
944
+ expect(h.calls).toContain(INSTALL);
945
+ });
946
+
947
+ it("an agent with no app rows keeps the legacy env path (and a mismatched appId is 404)", async () => {
948
+ const h = build({
949
+ apps: {},
950
+ routes: {
951
+ "GET /apps/example-agent-app": "public_app_success",
952
+ [INSTALL]: "install_created",
953
+ },
954
+ });
955
+ await seed(h);
956
+ expect((await post(h, { agentId: "agent-1" })).status).toBe(200);
957
+ expect((await post(h, { agentId: "agent-1", appId: "5" })).status).toBe(
958
+ 404,
959
+ );
960
+ });
961
+ });
962
+
963
+ describe("DELETE install with several apps", () => {
964
+ const INSTS_ROUTE =
965
+ "GET /enterprises/acme/apps/organizations/org-1/installations";
966
+ const DEL_ONE =
967
+ "DELETE /enterprises/acme/apps/organizations/org-1/installations/501";
968
+ const DEL_TWO =
969
+ "DELETE /enterprises/acme/apps/organizations/org-1/installations/503";
970
+
971
+ function harness(apps: FakeAppRow[]) {
972
+ const state = { repos: ["org-1/a", "other/c"], blocked: [] as string[] };
973
+ const h = build({
974
+ apps: { "agent-1": apps },
975
+ routes: {
976
+ [INSTS_ROUTE]: "org_installations_two_apps",
977
+ [DEL_ONE]: "uninstall_success",
978
+ [DEL_TWO]: "uninstall_success",
979
+ },
980
+ uninstall: {
981
+ agents: {
982
+ get: async (id: string) => ({
983
+ id,
984
+ repos: [...state.repos],
985
+ githubUsername: null,
986
+ }),
987
+ setRepos: async (_id: string, repos: string[]) => {
988
+ state.repos = repos;
989
+ },
990
+ },
991
+ audit: { write: async () => "audit-1" },
992
+ openWork: {
993
+ listOpenWork: async () => [],
994
+ blockOpenWork: async (_a: string, repos: readonly string[]) => {
995
+ state.blocked.push(...repos);
996
+ },
997
+ },
998
+ },
999
+ });
1000
+ return { h, state };
1001
+ }
1002
+
1003
+ const del = (h: ReturnType<typeof build>, query: string) =>
1004
+ h.app.request(
1005
+ `/github-enterprise/orgs/org-1/install?agentId=agent-1${query}`,
1006
+ { method: "DELETE", headers: ADMIN },
1007
+ );
1008
+
1009
+ it("requires appId when the agent has more than one app", async () => {
1010
+ const { h } = harness([APP_ONE, APP_TWO]);
1011
+ await seed(h);
1012
+ const res = await del(h, "");
1013
+ expect(res.status).toBe(422);
1014
+ expect(h.calls.some((c) => c.startsWith("DELETE"))).toBe(false);
1015
+ });
1016
+
1017
+ it("deletes only the named app's installation and keeps repos a sibling app still serves", async () => {
1018
+ const { h, state } = harness([APP_ONE, APP_TWO]);
1019
+ await seed(h);
1020
+ const res = await del(h, "&appId=888");
1021
+ expect(res.status).toBe(200);
1022
+ expect(await res.json()).toMatchObject({
1023
+ status: "uninstalled",
1024
+ installationId: 503,
1025
+ repos: [],
1026
+ });
1027
+ expect(h.calls).toContain(DEL_TWO);
1028
+ expect(h.calls).not.toContain(DEL_ONE);
1029
+ expect(state.repos).toEqual(["org-1/a", "other/c"]);
1030
+ expect(state.blocked).toEqual([]);
1031
+ });
1032
+
1033
+ it("an unknown appId is 404 and deletes nothing", async () => {
1034
+ const { h } = harness([APP_ONE, APP_TWO]);
1035
+ await seed(h);
1036
+ const res = await del(h, "&appId=999");
1037
+ expect(res.status).toBe(404);
1038
+ expect(h.calls.some((c) => c.startsWith("DELETE"))).toBe(false);
1039
+ });
1040
+
1041
+ it("cleans up the org's repos and open work when no other app remains installed", async () => {
1042
+ // Only the sibling is absent from the org: the named app is the last one.
1043
+ const { h, state } = harness([
1044
+ APP_ONE,
1045
+ { ...APP_TWO, appId: "999", slug: "absent-app", clientId: null },
1046
+ ]);
1047
+ await seed(h);
1048
+ const res = await del(h, "&appId=777");
1049
+ expect(res.status).toBe(200);
1050
+ expect(h.calls).toContain(DEL_ONE);
1051
+ expect(state.repos).toEqual(["other/c"]);
1052
+ expect(state.blocked).toEqual(["org-1/a"]);
1053
+ });
1054
+
1055
+ it("a single app uninstalls as before", async () => {
1056
+ const { h, state } = harness([APP_ONE]);
1057
+ await seed(h);
1058
+ const res = await del(h, "");
1059
+ expect(res.status).toBe(200);
1060
+ expect(h.calls).toContain(DEL_ONE);
1061
+ expect(state.repos).toEqual(["other/c"]);
1062
+ });
1063
+ });
1064
+
865
1065
  describe("account-scoped routes", () => {
866
1066
  /** Records the accountId every appService method receives. */
867
1067
  function spied() {
@@ -63,6 +63,7 @@ import {
63
63
  import type { GithubRefreshAction } from "./github-refresh-action.ts";
64
64
  import type { GitHubRepoCacheService } from "./github-repo-cache.ts";
65
65
  import {
66
+ type AgentAppIdentity,
66
67
  findAgentInstallation,
67
68
  GITHUB_UNINSTALL_AUDIT_PLAN_HASH,
68
69
  planOrgUninstall,
@@ -92,11 +93,12 @@ export interface GithubEnterpriseApiDeps {
92
93
  agentService: Pick<AgentService, "getSummary">;
93
94
  agentEnvService: Pick<AgentEnvService, "getByAgentId">;
94
95
  /**
95
- * multi-github-apps 1.5: the agent's App is read from the AgentGitHubApp
96
- * table (primary app), falling back to its GH_APP_* env when the agent has no
97
- * row. Optional so existing wiring stays valid.
96
+ * The agent's GitHub Apps (AgentGitHubApp rows). Optional and additive:
97
+ * install/uninstall resolve the named App from it, and fall back to the
98
+ * legacy GH_APP_* env rows when it is absent or the agent has no rows. The
99
+ * agent's primary App (the first row) backs the org-list App lookup.
98
100
  */
99
- agentGitHubAppService?: Pick<AgentGitHubAppService, "getPrimary">;
101
+ agentGitHubAppService?: Pick<AgentGitHubAppService, "list">;
100
102
  sessionSecret: string;
101
103
  adminApiKeys?: Map<string, AdminApiKey>;
102
104
  agentTokenService: Pick<AgentTokenService, "validate">;
@@ -260,6 +262,11 @@ const OrgsResultSchema = z
260
262
  const InstallBodySchema = z
261
263
  .object({
262
264
  agentId: z.string().min(1).openapi({ example: "agent-id" }),
265
+ appId: z.string().min(1).optional().openapi({
266
+ example: "12345",
267
+ description:
268
+ "Which of the agent's GitHub Apps to install: the App's numeric id (or its AgentGitHubApp row id). Required when the agent has more than one App; defaults to the only App otherwise.",
269
+ }),
263
270
  repositorySelection: z.enum(["all", "selected", "none"]).default("all"),
264
271
  repositories: z
265
272
  .array(z.string().min(1))
@@ -288,6 +295,16 @@ const UninstallQuerySchema = AccountQuerySchema.extend({
288
295
  .string()
289
296
  .min(1)
290
297
  .openapi({ param: { name: "agentId", in: "query" }, example: "agent-id" }),
298
+ appId: z
299
+ .string()
300
+ .min(1)
301
+ .optional()
302
+ .openapi({
303
+ param: { name: "appId", in: "query" },
304
+ example: "12345",
305
+ description:
306
+ "Which of the agent's GitHub Apps to uninstall: the App's numeric id (or its AgentGitHubApp row id). Required when the agent has more than one App; defaults to the only App otherwise.",
307
+ }),
291
308
  preview: z
292
309
  .enum(["true", "false"])
293
310
  .optional()
@@ -471,7 +488,7 @@ const installRoute = createRoute({
471
488
  tags,
472
489
  summary: "Install an agent's App on an organization",
473
490
  description:
474
- "Admin-only. Uses the agent's stored GH_APP_CLIENT_ID when set; otherwise resolves the stored GH_APP_SLUG and looks the App up through the public GET /apps/{slug} to get its client id. Installs it on the org with the installer App. 422 for an agent with neither a stored client id nor a slug, and for a private App (not visible to the public lookup) with no stored client id; 409 when the installer App is not configured.",
491
+ "Admin-only. The App is chosen with `appId` (required, 422, when the agent has more than one App; 404 when the agent has no such App). Uses the App's stored client id when set; otherwise resolves the stored GH_APP_SLUG and looks the App up through the public GET /apps/{slug} to get its client id. Installs it on the org with the installer App. 422 for an agent with neither a stored client id nor a slug, and for a private App (not visible to the public lookup) with no stored client id; 409 when the installer App is not configured.",
475
492
  request: {
476
493
  params: OrgParamSchema,
477
494
  query: AccountQuerySchema,
@@ -495,7 +512,7 @@ const uninstallRoute = createRoute({
495
512
  tags,
496
513
  summary: "Uninstall an agent's App from an organization",
497
514
  description:
498
- "Admin-only. Finds the agent App's installation on the org (client id, slug or app id) and deletes it with the installer App, removes that org's repos from the agent's repos, blocks the agent's open tasks and PRs on them through the open-work port (a port failure is a warning) and writes one audit row (uninstall:org). `preview=true` lists the repos and open work that would be affected and changes nothing. 404 when the App is not installed on the org; 422 when more than 10 repos would be removed without `confirmRemovals=true`; 502 (with a failed audit row) when GitHub refuses.",
515
+ "Admin-only. Finds the named App's installation on the org (`appId` is required when the agent has several Apps; the agent's other Apps' installations are untouched; matched by client id, slug or app id) and deletes it with the installer App, removes that org's repos from the agent's repos, blocks the agent's open tasks and PRs on them (both skipped when another App of the agent is still installed on the org) through the open-work port (a port failure is a warning) and writes one audit row (uninstall:org). `preview=true` lists the repos and open work that would be affected and changes nothing. 404 when the App is not installed on the org; 422 when more than 10 repos would be removed without `confirmRemovals=true`; 502 (with a failed audit row) when GitHub refuses.",
499
516
  request: { params: OrgParamSchema, query: UninstallQuerySchema },
500
517
  responses: {
501
518
  200: {
@@ -786,7 +803,9 @@ export function createGithubEnterpriseApp(
786
803
  if (!(await deps.agentService.getSummary(agentId))) {
787
804
  throw new NotFoundError(`agent ${agentId} not found`);
788
805
  }
789
- const primary = await deps.agentGitHubAppService?.getPrimary(agentId);
806
+ const [primary] = deps.agentGitHubAppService
807
+ ? await deps.agentGitHubAppService.list(agentId)
808
+ : [];
790
809
  const env = primary
791
810
  ? overlayGitHubAppEnv({}, primary)
792
811
  : (await deps.agentEnvService.getByAgentId(agentId))?.env;
@@ -822,6 +841,62 @@ export function createGithubEnterpriseApp(
822
841
  }
823
842
  };
824
843
 
844
+ /**
845
+ * The agent's App to install/uninstall. With AgentGitHubApp rows: the named
846
+ * App (appId or row id), the only App when none is named, 422 when several
847
+ * exist and none is named, 404 when the name matches none. Without rows it
848
+ * falls back to the legacy GH_APP_* env App (a named appId must match its
849
+ * GH_APP_ID). `others` are the agent's remaining Apps (empty on fallback).
850
+ */
851
+ const resolveAgentApp = async (
852
+ agentId: string,
853
+ appId: string | undefined,
854
+ ): Promise<
855
+ Awaited<ReturnType<typeof agentApp>> & { others: AgentAppIdentity[] }
856
+ > => {
857
+ const legacy = await agentApp(agentId);
858
+ const rows = deps.agentGitHubAppService
859
+ ? await deps.agentGitHubAppService.list(agentId)
860
+ : [];
861
+ if (rows.length === 0) {
862
+ if (appId !== undefined && String(legacy.appId ?? "") !== appId) {
863
+ throw new NotFoundError(`agent ${agentId} has no App ${appId}`);
864
+ }
865
+ return { ...legacy, others: [] };
866
+ }
867
+ let chosen: (typeof rows)[number] | undefined;
868
+ if (appId === undefined) {
869
+ if (rows.length > 1) {
870
+ throw new UnprocessableEntityError(
871
+ `the agent has ${rows.length} GitHub Apps; pass appId to choose one`,
872
+ );
873
+ }
874
+ chosen = rows[0];
875
+ } else {
876
+ chosen = rows.find((r) => r.appId === appId || r.id === appId);
877
+ if (!chosen) {
878
+ throw new NotFoundError(`agent ${agentId} has no App ${appId}`);
879
+ }
880
+ }
881
+ const row = chosen as (typeof rows)[number];
882
+ const numeric = Number(row.appId);
883
+ const slug = row.slug;
884
+ return {
885
+ slug: slug && SLUG_RE.test(slug) ? slug : null,
886
+ invalid: Boolean(slug) && !SLUG_RE.test(slug as string),
887
+ clientId:
888
+ row.clientId && CLIENT_ID_RE.test(row.clientId) ? row.clientId : null,
889
+ appId: Number.isInteger(numeric) && numeric > 0 ? numeric : null,
890
+ others: rows
891
+ .filter((r) => r !== row)
892
+ .map((r) => ({
893
+ clientId: r.clientId,
894
+ slug: r.slug,
895
+ appId: Number(r.appId) || null,
896
+ })),
897
+ };
898
+ };
899
+
825
900
  const privateAppMessage = (slug: string) =>
826
901
  `the agent's App '${slug}' is private (not visible to the public lookup) and cannot be installed through the enterprise API; store its GH_APP_CLIENT_ID on the agent`;
827
902
 
@@ -1068,7 +1143,7 @@ export function createGithubEnterpriseApp(
1068
1143
  if (!installer) {
1069
1144
  throw new ConflictError("the installer App is not configured");
1070
1145
  }
1071
- const agent = await agentApp(body.agentId);
1146
+ const agent = await resolveAgentApp(body.agentId, body.appId);
1072
1147
  let clientId = agent.clientId;
1073
1148
  if (!clientId) {
1074
1149
  if (agent.invalid) {
@@ -1129,20 +1204,43 @@ export function createGithubEnterpriseApp(
1129
1204
  if (!installer) {
1130
1205
  throw new ConflictError("the installer App is not configured");
1131
1206
  }
1132
- const agent = await agentApp(agentId);
1207
+ const agent = await resolveAgentApp(agentId, query.appId);
1133
1208
  const record = await port.agents.get(agentId);
1134
1209
  if (!record) throw new NotFoundError(`agent ${agentId} not found`);
1135
1210
 
1136
1211
  const client = await clientFor(installer, accountId);
1137
- const installation = findAgentInstallation(
1138
- await client.listOrgInstallations(org),
1139
- { clientId: agent.clientId, slug: agent.slug, appId: agent.appId },
1140
- );
1212
+ const orgInstalls = await client.listOrgInstallations(org);
1213
+ const installation = findAgentInstallation(orgInstalls, {
1214
+ clientId: agent.clientId,
1215
+ slug: agent.slug,
1216
+ appId: agent.appId,
1217
+ });
1141
1218
  if (!installation) {
1142
1219
  throw new NotFoundError(`the agent's App is not installed on org ${org}`);
1143
1220
  }
1144
1221
 
1145
- const plan = planOrgUninstall({ org, agentRepos: record.repos });
1222
+ // Only the named App's installation is deleted. The agent's repos are
1223
+ // shared across its Apps and the helpers here cannot tell which repos a
1224
+ // sibling App covers, so when another App of the agent is still installed
1225
+ // on this org the repo list and open work are left alone (a warning says
1226
+ // so) rather than dropping repos that sibling still serves. Limitation:
1227
+ // the repos are not narrowed to the ones only the removed App covered.
1228
+ const siblingInstalled = agent.others.some((o) =>
1229
+ orgInstalls.some(
1230
+ (i) =>
1231
+ i.id !== installation.id &&
1232
+ findAgentInstallation([i], o) !== undefined,
1233
+ ),
1234
+ );
1235
+ const plan = planOrgUninstall({
1236
+ org,
1237
+ agentRepos: siblingInstalled ? [] : record.repos,
1238
+ });
1239
+ const siblingWarning = siblingInstalled
1240
+ ? [
1241
+ `another App of the agent is still installed on org ${org}; the agent's repos and open work there were kept`,
1242
+ ]
1243
+ : [];
1146
1244
  const work = await previewRepoRemovalWork(
1147
1245
  port.openWork,
1148
1246
  agentId,
@@ -1156,7 +1254,11 @@ export function createGithubEnterpriseApp(
1156
1254
  };
1157
1255
  if (query.preview === "true") {
1158
1256
  return c.json(
1159
- { status: "preview" as const, ...base, warnings: work.warnings },
1257
+ {
1258
+ status: "preview" as const,
1259
+ ...base,
1260
+ warnings: [...siblingWarning, ...work.warnings],
1261
+ },
1160
1262
  200,
1161
1263
  );
1162
1264
  }
@@ -1216,6 +1318,7 @@ export function createGithubEnterpriseApp(
1216
1318
  );
1217
1319
  }
1218
1320
  const warnings = [
1321
+ ...siblingWarning,
1219
1322
  ...work.warnings,
1220
1323
  ...(await blockRepoRemovalWork(
1221
1324
  port.openWork,
@@ -1095,7 +1095,20 @@ const GitHubInstallationSchema = z
1095
1095
  .object({
1096
1096
  owner: z.string().min(1).max(200).openapi({ example: "app-vitals" }),
1097
1097
  installationId: z.number().int().positive().openapi({ example: 12345678 }),
1098
- state: z.string().min(1).max(50).openapi({ example: "active" }),
1098
+ state: z.string().min(1).max(50).openapi({
1099
+ description:
1100
+ 'Installation state, e.g. "ok", "broken", or "shadowed" (a higher-priority app owns the same owner).',
1101
+ example: "active",
1102
+ }),
1103
+ appId: z.string().min(1).max(100).optional().openapi({
1104
+ description:
1105
+ "GitHub App id this installation belongs to. Omitted by older agents, which are treated as the single legacy app.",
1106
+ example: "123456",
1107
+ }),
1108
+ slug: z.string().min(1).max(200).optional().openapi({
1109
+ description: "GitHub App slug, when the agent knows it.",
1110
+ example: "my-agent-app",
1111
+ }),
1099
1112
  lastError: z.string().max(500).nullable().optional().openapi({
1100
1113
  description:
1101
1114
  "Sanitized last error message (max 500 chars). Must not contain credentials.",
@@ -1142,7 +1155,22 @@ export const PutGitHubInstallationsBodySchema = z
1142
1155
  .string()
1143
1156
  .datetime()
1144
1157
  .openapi({ example: "2026-01-01T00:00:00.000Z" }),
1145
- installations: z.array(GitHubInstallationSchema),
1158
+ installations: z
1159
+ .array(GitHubInstallationSchema)
1160
+ .superRefine((rows, ctx) => {
1161
+ const seen = new Set<string>();
1162
+ rows.forEach((r, index) => {
1163
+ const key = `${r.appId ?? ""}\u0000${r.owner.toLowerCase()}`;
1164
+ if (seen.has(key)) {
1165
+ ctx.addIssue({
1166
+ code: "custom",
1167
+ path: [index],
1168
+ message: "duplicate installation for the same app and owner",
1169
+ });
1170
+ }
1171
+ seen.add(key);
1172
+ });
1173
+ }),
1146
1174
  repos: z.array(RepoAccessEntrySchema).optional().openapi({
1147
1175
  description:
1148
1176
  "Per-repo access probe result (COS-44.1). Omit to leave the stored result unchanged; send [] to clear it.",
@@ -20,6 +20,11 @@ export interface SpecialtyDefaultCron {
20
20
  enabled?: boolean;
21
21
  /** Name of another cron in this same list. */
22
22
  parentCron?: string;
23
+ /**
24
+ * Shown in the info tooltip beside this cron on the agent detail page
25
+ * (cron-help.ts). Display only: never stored on the cron row.
26
+ */
27
+ help?: { summary: string; docsHref: string };
23
28
  }
24
29
 
25
30
  /** Any field left undefined falls back to the built-in type for that field. */