@app-vitals/agent-admin 1.84.0 → 1.84.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.84.0",
3
+ "version": "1.84.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -20,6 +20,7 @@
20
20
  "./admin-spec": "./src/admin-spec.ts",
21
21
  "./main": "./src/main.ts",
22
22
  "./openapi-schemas": "./src/openapi-schemas.ts",
23
+ "./platform-routes": "./src/platform-routes.ts",
23
24
  "./prisma-client": "./src/prisma-client.ts",
24
25
  "./specialty-types": "./src/specialty-types.ts",
25
26
  "./brand-tokens.json": "./src/brand-tokens.json",
@@ -43,7 +44,7 @@
43
44
  },
44
45
  "dependencies": {
45
46
  "@anthropic-ai/sdk": "0.137.0",
46
- "@app-vitals/agent-lib": "1.84.0",
47
+ "@app-vitals/agent-lib": "1.84.1",
47
48
  "@hono/zod-openapi": "^1.0.0",
48
49
  "@prisma/adapter-pg": "^7.10.0",
49
50
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -51,7 +51,6 @@ import { AccountOnboardingService } from "./account-onboarding.ts";
51
51
  import { AccountTrialExpirySweeper } from "./account-trial-expiry-sweeper.ts";
52
52
  import { AccountTrialWarningSweeper } from "./account-trial-warning-sweeper.ts";
53
53
  import { AccountService } from "./accounts.ts";
54
- import { createAccountsApp } from "./accounts-api.ts";
55
54
  import {
56
55
  buildDeletionClients,
57
56
  buildProvisioner,
@@ -86,12 +85,10 @@ import { AgentMemberService } from "./agent-members.ts";
86
85
  import { AgentPluginService } from "./agent-plugins.ts";
87
86
  import { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
88
87
  import { AgentTemplateService } from "./agent-templates.ts";
89
- import { createAgentTemplatesApp } from "./agent-templates-api.ts";
90
88
  import { AgentTokenService } from "./agent-tokens.ts";
91
89
  import { AgentToolService } from "./agent-tools.ts";
92
90
  import { AgentService } from "./agents.ts";
93
- import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
94
- import { createAgentRuntimeApp } from "./api.ts";
91
+ import { parseAdminApiKeys } from "./agents-api.ts";
95
92
  import { createAdminAuthMiddleware } from "./api-auth.ts";
96
93
  import {
97
94
  callerScopeDepsFromServices,
@@ -107,7 +104,6 @@ import { isDevAuthAllowed } from "./dev-auth-guard.ts";
107
104
  import { HttpGithubAppProvisioningClient } from "./github-app-provisioning-client.ts";
108
105
  import {
109
106
  createGithubAccessPreview,
110
- createGithubEnterpriseApp,
111
107
  createGithubLookupService,
112
108
  } from "./github-enterprise-api.ts";
113
109
  import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
@@ -125,10 +121,9 @@ import {
125
121
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
126
122
  import { HttpChatClient } from "./http-chat-client.ts";
127
123
  import { HttpOktaAuthClient } from "./okta-auth-client.ts";
128
- import { mountPlatformDoc } from "./platform-doc-route.ts";
124
+ import { mountPlatformApis } from "./platform-routes.ts";
129
125
  import { parsePodServiceAccountConfig } from "./pod-service-account-config.ts";
130
126
  import { PrincipalLookupService } from "./principal-lookup.ts";
131
- import { createPrincipalsApp } from "./principals-api.ts";
132
127
  import { createAdminPrismaClient } from "./prisma-client.ts";
133
128
  import { isPushEnabled } from "./push-sender.ts";
134
129
  import { PushService } from "./push-service.ts";
@@ -486,37 +481,15 @@ export async function startAdmin(
486
481
  // Redirect bare root to the login page — no handler exists at "/" otherwise.
487
482
  root.get("/", (c) => c.redirect("/admin/login", 302));
488
483
 
489
- // 2. Runtime API — admin key | per-agent bearer | session JWT
490
- // Mounted via root.route("/agents", runtimeApp). Hono v4 strips the prefix
491
- // before dispatching, so runtimeApp routes are registered as /:id/config
492
- // and /:id/crons (without the /agents prefix) and resolve correctly at
484
+ // 2.-3b. Platform APIs, mounted in one place (platform-routes.ts):
485
+ // runtime API — root.route("/agents", runtimeApp) — then the admin CRUD API
486
+ // (root.route("/", adminApiApp)), flag-gated GET /doc, accounts
487
+ // (createAccountsApp(...)), principals, templates and github-enterprise.
488
+ // Runtime API: admin key | per-agent bearer | session JWT. Hono v4 strips
489
+ // the /agents prefix before dispatching, so its routes resolve at
493
490
  // GET /agents/:id/config and GET /agents/:id/crons from root.
494
- const runtimeApp = createAgentRuntimeApp({
495
- agentEnvService,
496
- agentCronJobService,
497
- agentService,
498
- agentPluginService,
499
- agentMarketplaceService,
500
- ...(resolvedExtensions.agentPhaseMethodologyService
501
- ? {
502
- agentPhaseMethodologyService:
503
- resolvedExtensions.agentPhaseMethodologyService,
504
- }
505
- : {}),
506
- sessionSecret,
507
- adminApiKeys,
508
- agentTokenService,
509
- anthropicFederationEnabled,
510
- transcriptUploadEnabled: transcriptConfig.enabled,
511
- loopTranscriptAgentIds: transcriptConfig.loopAgentIds,
512
- repoAccessCheckEnabled: repoAccessConfig.enabled,
513
- });
514
-
515
- root.route("/agents", runtimeApp);
516
-
517
- // 3. Admin CRUD API — /agents/:id/* — admin key | per-agent bearer | session JWT
518
- // Routes are now at /agents/:id/* (same prefix as runtime, different sub-paths).
519
- // MUST be mounted before admin-ui (/admin/*) to avoid shadowing.
491
+ // Admin CRUD API (/agents/:id/*) MUST be mounted before admin-ui (/admin/*)
492
+ // to avoid shadowing.
520
493
  // Built before the admin API: GHE-2.4's access preview reads the same Apps.
521
494
  // Strict crypto: no plain-text key storage.
522
495
  const githubAccessPreview = createGithubAccessPreview({
@@ -535,140 +508,141 @@ export async function startAdmin(
535
508
  agentEnv: agentEnvService,
536
509
  openWork: resolvedExtensions.openWork,
537
510
  });
538
- const adminApiApp = createAdminApp({
539
- githubAccessPreview,
540
- ...(resolvedExtensions.openWork
541
- ? { openWork: resolvedExtensions.openWork }
542
- : {}),
543
- githubInstallationRepos,
544
- githubSync,
545
- agentService,
546
- agentEnvService,
547
- agentCronJobService,
548
- agentCronRunService,
549
- agentCronRunStatsService,
550
- agentToolService,
551
- agentTokenService,
552
- agentPluginService,
553
- agentMarketplaceService,
554
- agentMemberService,
555
- callerScopeResolver,
556
- specialtyRegistry,
557
- specialtyDefaults,
558
- agentChatTokenService,
559
- agentGitHubInstallationsService,
511
+ const templateService = new AgentTemplateService(
560
512
  prisma,
561
- provisioner,
562
- serviceIntegrations,
563
- chatService: deletionChatService,
564
- slack: slackClient,
565
- decrypt: crypto.decrypt,
566
- slackConfigTokens,
567
- agentTemplateReconcileService: templateReconcileService,
568
- sessionSecret,
569
- adminApiKeys,
570
- sentryClient: process.env.SENTRY_DSN ? Sentry : undefined,
571
- pool: adminPool,
572
- selfServe,
573
- anthropicFederationEnabled,
574
- podServiceAccountEnabled: parsePodServiceAccountConfig(process.env).enabled,
575
- chatCredentialsEnabled: parseChatCredentialConfig(process.env).enabled,
576
- ...(chatCredentialsClient
577
- ? { chatCredentials: chatCredentialsClient }
578
- : {}),
579
- agentAsk: {
580
- config: agentAskConfig,
581
- store: new AgentAskService(prisma),
582
- },
583
- cronRunNow: {
584
- config: cronRunNowConfig,
585
- store: new CronRunNowService(prisma),
586
- },
587
- ...(chatClient ? { chatClient } : {}),
588
- transcripts: {
589
- config: transcriptConfig,
590
- store: new CronRunTranscriptService(prisma),
591
- },
592
- ...resolvedExtensions.apiDeps,
513
+ crypto,
514
+ specialtyRegistry,
515
+ templateReconcileService,
516
+ );
517
+ // GLC-2.4: the github-enterprise Refresh action marks the cache stale (DB
518
+ // only). It asks the refresher (created further down) to re-discover through
519
+ // this hook.
520
+ const githubRefreshConfig = resolveRefreshConfig(process.env);
521
+ let invalidateGithubDiscovery: () => void = () => {};
522
+ const githubRefreshAction = createGithubRefreshAction({
523
+ cache: githubRepoCache,
524
+ stalenessCapMs: githubRefreshConfig.stalenessCapMs,
525
+ onMarked: () => invalidateGithubDiscovery(),
593
526
  });
594
- root.route("/", adminApiApp);
595
-
596
- // 3a. Platform OpenAPI document — GET /doc, flag-gated (not mounted when off)
597
- mountPlatformDoc(root, {
598
- env: process.env,
599
- auth: createAdminAuthMiddleware({
527
+ const { adminApiApp, githubEnterpriseApp } = mountPlatformApis(root, {
528
+ runtime: {
529
+ agentEnvService,
530
+ agentCronJobService,
531
+ agentService,
532
+ agentPluginService,
533
+ agentMarketplaceService,
534
+ ...(resolvedExtensions.agentPhaseMethodologyService
535
+ ? {
536
+ agentPhaseMethodologyService:
537
+ resolvedExtensions.agentPhaseMethodologyService,
538
+ }
539
+ : {}),
600
540
  sessionSecret,
601
- agentTokenService,
602
541
  adminApiKeys,
542
+ agentTokenService,
543
+ anthropicFederationEnabled,
544
+ transcriptUploadEnabled: transcriptConfig.enabled,
545
+ loopTranscriptAgentIds: transcriptConfig.loopAgentIds,
546
+ repoAccessCheckEnabled: repoAccessConfig.enabled,
547
+ },
548
+ adminApi: {
549
+ githubAccessPreview,
550
+ ...(resolvedExtensions.openWork
551
+ ? { openWork: resolvedExtensions.openWork }
552
+ : {}),
553
+ githubInstallationRepos,
554
+ githubSync,
555
+ agentService,
556
+ agentEnvService,
557
+ agentCronJobService,
558
+ agentCronRunService,
559
+ agentCronRunStatsService,
560
+ agentToolService,
561
+ agentTokenService,
562
+ agentPluginService,
563
+ agentMarketplaceService,
603
564
  agentMemberService,
604
565
  callerScopeResolver,
605
- }),
606
- });
607
-
608
- // 3b. Accounts API — /accounts/* — admin-only, flag-gated (SSP-5.1)
609
- root.route(
610
- "/",
611
- createAccountsApp({
566
+ specialtyRegistry,
567
+ specialtyDefaults,
568
+ agentChatTokenService,
569
+ agentGitHubInstallationsService,
570
+ prisma,
571
+ provisioner,
572
+ serviceIntegrations,
573
+ chatService: deletionChatService,
574
+ slack: slackClient,
575
+ decrypt: crypto.decrypt,
576
+ slackConfigTokens,
577
+ agentTemplateReconcileService: templateReconcileService,
578
+ sessionSecret,
579
+ adminApiKeys,
580
+ sentryClient: process.env.SENTRY_DSN ? Sentry : undefined,
581
+ pool: adminPool,
582
+ selfServe,
583
+ anthropicFederationEnabled,
584
+ podServiceAccountEnabled: parsePodServiceAccountConfig(process.env)
585
+ .enabled,
586
+ chatCredentialsEnabled: parseChatCredentialConfig(process.env).enabled,
587
+ ...(chatCredentialsClient
588
+ ? { chatCredentials: chatCredentialsClient }
589
+ : {}),
590
+ agentAsk: {
591
+ config: agentAskConfig,
592
+ store: new AgentAskService(prisma),
593
+ },
594
+ cronRunNow: {
595
+ config: cronRunNowConfig,
596
+ store: new CronRunNowService(prisma),
597
+ },
598
+ ...(chatClient ? { chatClient } : {}),
599
+ transcripts: {
600
+ config: transcriptConfig,
601
+ store: new CronRunTranscriptService(prisma),
602
+ },
603
+ ...resolvedExtensions.apiDeps,
604
+ },
605
+ doc: {
606
+ env: process.env,
607
+ auth: createAdminAuthMiddleware({
608
+ sessionSecret,
609
+ agentTokenService,
610
+ adminApiKeys,
611
+ agentMemberService,
612
+ callerScopeResolver,
613
+ }),
614
+ },
615
+ accounts: {
612
616
  accountService: new AccountService(prisma),
613
617
  accountLifecycle,
614
618
  selfServe,
615
619
  sessionSecret,
616
620
  adminApiKeys,
617
621
  agentTokenService,
618
- }),
619
- );
620
-
621
- // 3b'. Principals lookup API — /principals/* — admin-only (ACM-1.1)
622
- root.route(
623
- "/",
624
- createPrincipalsApp({
622
+ },
623
+ principals: {
625
624
  lookup: new PrincipalLookupService(prisma),
626
625
  sessionSecret,
627
626
  adminApiKeys,
628
627
  agentTokenService,
629
- }),
630
- );
631
-
632
- // 3b''. Agent templates API — /templates/* — admin or account-scoped (ATP-1.3)
633
- const templateService = new AgentTemplateService(
634
- prisma,
635
- crypto,
636
- specialtyRegistry,
637
- templateReconcileService,
638
- );
639
- root.route(
640
- "/",
641
- createAgentTemplatesApp({
628
+ },
629
+ templates: {
642
630
  templateService,
643
631
  callerScopeResolver,
644
632
  sessionSecret,
645
633
  adminApiKeys,
646
634
  agentTokenService,
647
- }),
648
- );
649
-
650
- // 3b'. GitHub Enterprise Apps API — /github-enterprise/* — admin-only,
651
- // optional (GHE-1.3). With no rows configured it reports unconfigured
652
- // and does nothing else. Strict crypto: no plain-text key storage.
653
- // GLC-2.4: the Refresh action marks the cache stale (DB only). It asks the
654
- // refresher (created further down) to re-discover through this hook.
655
- const githubRefreshConfig = resolveRefreshConfig(process.env);
656
- let invalidateGithubDiscovery: () => void = () => {};
657
- const githubRefreshAction = createGithubRefreshAction({
658
- cache: githubRepoCache,
659
- stalenessCapMs: githubRefreshConfig.stalenessCapMs,
660
- onMarked: () => invalidateGithubDiscovery(),
661
- });
662
- const githubEnterpriseApp = createGithubEnterpriseApp({
663
- refreshAction: githubRefreshAction,
664
- appService: githubEnterpriseAppService,
665
- agentService,
666
- agentEnvService,
667
- sessionSecret,
668
- adminApiKeys,
669
- agentTokenService,
635
+ },
636
+ githubEnterprise: {
637
+ refreshAction: githubRefreshAction,
638
+ appService: githubEnterpriseAppService,
639
+ agentService,
640
+ agentEnvService,
641
+ sessionSecret,
642
+ adminApiKeys,
643
+ agentTokenService,
644
+ },
670
645
  });
671
- root.route("/", githubEnterpriseApp);
672
646
 
673
647
  // 3c. Extension API routes — after every platform API, before the admin UI
674
648
  // (same no-shadowing rule as the admin CRUD API above).
package/src/admin-spec.ts CHANGED
@@ -17,16 +17,10 @@
17
17
  * scripts/generate-admin-spec.ts to produce the composed admin/openapi.json.
18
18
  */
19
19
 
20
+ import { Hono } from "hono";
20
21
  import { NoopAgentProvisioner } from "./agent-provisioner.ts";
21
- import { createAgentTemplatesApp } from "./agent-templates-api.ts";
22
- import {
23
- type AdminDeps,
24
- createAdminApp,
25
- parseAdminApiKeys,
26
- } from "./agents-api.ts";
27
- import { createAgentRuntimeApp } from "./api.ts";
28
- import { createGithubEnterpriseApp } from "./github-enterprise-api.ts";
29
- import { createPrincipalsApp } from "./principals-api.ts";
22
+ import { type AdminDeps, parseAdminApiKeys } from "./agents-api.ts";
23
+ import { mountPlatformApis } from "./platform-routes.ts";
30
24
 
31
25
  /** The admin OpenAPI document shape the spec builders and generators share. */
32
26
  export interface AdminOpenApiDocument {
@@ -43,86 +37,115 @@ export function buildPlatformAdminSpec(): AdminOpenApiDocument {
43
37
  const SESSION_SECRET = "dummy-secret-32chars-for-spec-gen";
44
38
  const adminApiKeys = parseAdminApiKeys("codegen:codegen-key:*");
45
39
 
46
- const runtimeApp = createAgentRuntimeApp({
47
- agentEnvService: {
48
- async getConfigBundle() {
49
- return null;
40
+ const { mounted } = mountPlatformApis(new Hono(), {
41
+ runtime: {
42
+ agentEnvService: {
43
+ async getConfigBundle() {
44
+ return null;
45
+ },
50
46
  },
51
- },
52
- agentCronJobService: {
53
- async list() {
54
- return [];
47
+ agentCronJobService: {
48
+ async list() {
49
+ return [];
50
+ },
55
51
  },
56
- },
57
- agentService: {
58
- async getById() {
59
- return null;
52
+ agentService: {
53
+ async getById() {
54
+ return null;
55
+ },
60
56
  },
61
- },
62
- agentPluginService: {
63
- async listEnabled() {
64
- return [];
57
+ agentPluginService: {
58
+ async listEnabled() {
59
+ return [];
60
+ },
65
61
  },
62
+ adminApiKeys,
63
+ agentTokenService: { validate: async () => null },
64
+ sessionSecret: SESSION_SECRET,
66
65
  },
67
- adminApiKeys,
68
- agentTokenService: { validate: async () => null },
69
- sessionSecret: SESSION_SECRET,
70
- });
71
-
72
- const adminApp = createAdminApp({
73
- agentEnvService: {
74
- upsert: async () => {},
75
- patch: async () => {},
76
- getByAgentId: async () => null,
77
- deleteKey: async () => {},
78
- },
79
- agentCronJobService: {
80
- list: async () => [],
81
- listWithRunSummary: async () => [],
82
- create: async () => ({}) as never,
83
- update: async () => ({}) as never,
84
- delete: async () => {},
85
- get: async () => ({}) as never,
86
- setEnabled: async () => ({}) as never,
87
- updatePreCheck: async () => ({}) as never,
88
- reconcileSystemCrons: async () => ({
89
- created: 0,
90
- updated: 0,
91
- deleted: 0,
92
- }),
66
+ adminApi: {
67
+ agentEnvService: {
68
+ upsert: async () => {},
69
+ patch: async () => {},
70
+ getByAgentId: async () => null,
71
+ deleteKey: async () => {},
72
+ },
73
+ agentCronJobService: {
74
+ list: async () => [],
75
+ listWithRunSummary: async () => [],
76
+ create: async () => ({}) as never,
77
+ update: async () => ({}) as never,
78
+ delete: async () => {},
79
+ get: async () => ({}) as never,
80
+ setEnabled: async () => ({}) as never,
81
+ updatePreCheck: async () => ({}) as never,
82
+ reconcileSystemCrons: async () => ({
83
+ created: 0,
84
+ updated: 0,
85
+ deleted: 0,
86
+ }),
87
+ },
88
+ agentToolService: {
89
+ list: async () => [],
90
+ add: async () => ({}) as never,
91
+ remove: async () => {},
92
+ toggle: async () => ({}) as never,
93
+ },
94
+ agentTokenService: {
95
+ create: async () => ({}) as never,
96
+ listForAgent: async () => [],
97
+ revoke: async () => ({}) as never,
98
+ validate: async () => null,
99
+ },
100
+ agentPluginService: {
101
+ list: async () => [],
102
+ add: async () => ({}) as never,
103
+ remove: async () => {},
104
+ removeByName: async () => {},
105
+ },
106
+ prisma: {
107
+ agent: {
108
+ create: async () => ({}) as never,
109
+ findUnique: async () => null,
110
+ findMany: async () => [],
111
+ delete: async () => ({}) as never,
112
+ },
113
+ } as never,
114
+ provisioner: new NoopAgentProvisioner(),
115
+ sessionSecret: SESSION_SECRET,
116
+ adminApiKeys,
117
+ // Partial on purpose: route registration never calls the services, so
118
+ // only the deps a factory reads at construction time are stubbed.
119
+ } as unknown as AdminDeps,
120
+ accounts: {
121
+ accountService: {} as never,
122
+ accountLifecycle: {} as never,
123
+ sessionSecret: SESSION_SECRET,
124
+ adminApiKeys,
125
+ agentTokenService: { validate: async () => null },
93
126
  },
94
- agentToolService: {
95
- list: async () => [],
96
- add: async () => ({}) as never,
97
- remove: async () => {},
98
- toggle: async () => ({}) as never,
127
+ principals: {
128
+ lookup: {} as never,
129
+ sessionSecret: SESSION_SECRET,
130
+ adminApiKeys,
131
+ agentTokenService: { validate: async () => null },
99
132
  },
100
- agentTokenService: {
101
- create: async () => ({}) as never,
102
- listForAgent: async () => [],
103
- revoke: async () => ({}) as never,
104
- validate: async () => null,
133
+ templates: {
134
+ templateService: {} as never,
135
+ callerScopeResolver: async () => ({ kind: "all" }),
136
+ sessionSecret: SESSION_SECRET,
137
+ adminApiKeys,
138
+ agentTokenService: { validate: async () => null },
105
139
  },
106
- agentPluginService: {
107
- list: async () => [],
108
- add: async () => ({}) as never,
109
- remove: async () => {},
110
- removeByName: async () => {},
140
+ githubEnterprise: {
141
+ appService: {} as never,
142
+ agentService: {} as never,
143
+ agentEnvService: {} as never,
144
+ sessionSecret: SESSION_SECRET,
145
+ adminApiKeys,
146
+ agentTokenService: { validate: async () => null },
111
147
  },
112
- prisma: {
113
- agent: {
114
- create: async () => ({}) as never,
115
- findUnique: async () => null,
116
- findMany: async () => [],
117
- delete: async () => ({}) as never,
118
- },
119
- } as never,
120
- provisioner: new NoopAgentProvisioner(),
121
- sessionSecret: SESSION_SECRET,
122
- adminApiKeys,
123
- // Partial on purpose: route registration never calls the services, so only
124
- // the deps a factory reads at construction time are stubbed.
125
- } as unknown as AdminDeps);
148
+ });
126
149
 
127
150
  const docInfo = {
128
151
  openapi: "3.1.0" as const,
@@ -135,92 +158,39 @@ export function buildPlatformAdminSpec(): AdminOpenApiDocument {
135
158
  servers: [{ url: "http://localhost:3457", description: "Local dev" }],
136
159
  };
137
160
 
138
- // Admin app spec (uses OpenAPI {id} path notation)
139
- const adminSpec = adminApp.getOpenAPI31Document(docInfo);
140
-
141
- // Runtime app spec (uses Hono :id notation — paths are relative to sub-app root)
142
- const runtimeSpec = runtimeApp.getOpenAPI31Document({
143
- openapi: "3.1.0",
144
- info: { title: "runtime (internal)", version: "0.1.0" },
145
- });
146
-
147
- // The runtime app's routes are defined as `/:id/config` and `/:id/crons`.
148
- // When the spec is generated standalone, these appear as `/:id/config` etc.
149
- // We rewrite Hono colon params to OpenAPI curly brace params, then prefix
150
- // with `/agents` to match the root-mounted path.
161
+ // The admin app is the base document (it carries info/servers); every other
162
+ // spec'd app is folded in on top of it. Admin goes first so its paths lead.
163
+ const specApps = mounted.filter((m) => m.inSpec);
164
+ const adminEntry = specApps.find((m) => m.name === "admin");
165
+ if (!adminEntry) throw new Error("platform admin app is not mounted");
166
+ const adminSpec = adminEntry.app.getOpenAPI31Document(docInfo);
151
167
 
152
- // Build runtime paths with OpenAPI notation and /agents prefix.
153
- // Merge at the method level so paths shared between admin and runtime
154
- // (e.g. /agents/{id}/crons has both POST from admin and GET from runtime)
155
- // keep all their HTTP methods.
156
- const adminPaths = (adminSpec.paths ?? {}) as Record<
157
- string,
158
- Record<string, unknown>
159
- >;
160
168
  const mergedPaths: Record<string, Record<string, unknown>> = {
161
- ...adminPaths,
169
+ ...((adminSpec.paths ?? {}) as Record<string, Record<string, unknown>>),
170
+ };
171
+ const schemas: Record<string, unknown> = {
172
+ ...(adminSpec.components?.schemas ?? {}),
162
173
  };
163
174
 
164
- for (const [path, def] of Object.entries(runtimeSpec.paths ?? {})) {
165
- const openApiPath = `/agents${path.replace(/:(\w+)/g, "{$1}")}`;
166
- if (mergedPaths[openApiPath]) {
167
- // Merge methods — runtime GET on /agents/{id}/crons must coexist with
168
- // admin POST on the same path.
175
+ for (const entry of specApps) {
176
+ if (entry === adminEntry) continue;
177
+ const spec = entry.app.getOpenAPI31Document({
178
+ openapi: "3.1.0",
179
+ info: { title: `${entry.name} (internal)`, version: "0.1.0" },
180
+ });
181
+ // A sub-app's paths are relative to its mount prefix and use Hono `:id`
182
+ // params; rewrite to OpenAPI `{id}` and prefix them (runtime -> /agents).
183
+ // Merge at the method level so paths shared between apps (e.g.
184
+ // /agents/{id}/crons: admin POST + runtime GET) keep all their methods.
185
+ const prefix = entry.prefix === "/" ? "" : entry.prefix;
186
+ for (const [path, def] of Object.entries(spec.paths ?? {})) {
187
+ const openApiPath = `${prefix}${path.replace(/:(\w+)/g, "{$1}")}`;
169
188
  mergedPaths[openApiPath] = {
170
189
  ...mergedPaths[openApiPath],
171
190
  ...(def as Record<string, unknown>),
172
191
  };
173
- } else {
174
- mergedPaths[openApiPath] = def as Record<string, unknown>;
175
192
  }
176
- }
177
-
178
- // GHE-1.3: the /github-enterprise routes live in their own app (mounted at
179
- // the root in admin-boot.ts); fold their paths and schemas in.
180
- const gheSpec = createGithubEnterpriseApp({
181
- appService: {} as never,
182
- agentService: {} as never,
183
- agentEnvService: {} as never,
184
- sessionSecret: SESSION_SECRET,
185
- adminApiKeys,
186
- agentTokenService: { validate: async () => null },
187
- }).getOpenAPI31Document({
188
- openapi: "3.1.0",
189
- info: { title: "github-enterprise (internal)", version: "0.1.0" },
190
- });
191
- for (const [path, def] of Object.entries(gheSpec.paths ?? {})) {
192
- mergedPaths[path] = def as Record<string, unknown>;
193
- }
194
-
195
- // ATP-1.3: the /templates routes live in their own app (mounted at the root
196
- // in admin-boot.ts); fold their paths and schemas in.
197
- const templatesSpec = createAgentTemplatesApp({
198
- templateService: {} as never,
199
- callerScopeResolver: async () => ({ kind: "all" }),
200
- sessionSecret: SESSION_SECRET,
201
- adminApiKeys,
202
- agentTokenService: { validate: async () => null },
203
- }).getOpenAPI31Document({
204
- openapi: "3.1.0",
205
- info: { title: "templates (internal)", version: "0.1.0" },
206
- });
207
- for (const [path, def] of Object.entries(templatesSpec.paths ?? {})) {
208
- mergedPaths[path] = def as Record<string, unknown>;
209
- }
210
-
211
- // ACM-1.1: the /principals lookup routes live in their own app (mounted at
212
- // the root in admin-boot.ts); fold their paths and schemas in.
213
- const principalsSpec = createPrincipalsApp({
214
- lookup: {} as never,
215
- sessionSecret: SESSION_SECRET,
216
- adminApiKeys,
217
- agentTokenService: { validate: async () => null },
218
- }).getOpenAPI31Document({
219
- openapi: "3.1.0",
220
- info: { title: "principals (internal)", version: "0.1.0" },
221
- });
222
- for (const [path, def] of Object.entries(principalsSpec.paths ?? {})) {
223
- mergedPaths[path] = def as Record<string, unknown>;
193
+ Object.assign(schemas, spec.components?.schemas ?? {});
224
194
  }
225
195
 
226
196
  return {
@@ -228,13 +198,7 @@ export function buildPlatformAdminSpec(): AdminOpenApiDocument {
228
198
  paths: mergedPaths,
229
199
  components: {
230
200
  ...(adminSpec.components ?? {}),
231
- schemas: {
232
- ...(adminSpec.components?.schemas ?? {}),
233
- ...(runtimeSpec.components?.schemas ?? {}),
234
- ...(gheSpec.components?.schemas ?? {}),
235
- ...(templatesSpec.components?.schemas ?? {}),
236
- ...(principalsSpec.components?.schemas ?? {}),
237
- },
201
+ schemas,
238
202
  },
239
203
  };
240
204
  }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * admin/src/platform-routes.ts
3
+ * The single place the platform admin APIs are mounted on a root app.
4
+ *
5
+ * startAdmin (admin-boot.ts) calls mountPlatformApis with real services and
6
+ * buildPlatformAdminSpec (admin-spec.ts) calls it with stub deps, deriving the
7
+ * OpenAPI document from the returned `mounted` list. Adding a platform sub-app
8
+ * therefore means touching this file only.
9
+ *
10
+ * Mount order is part of the contract: every platform API is mounted here,
11
+ * before extension routes and the admin UI (/admin/*), which startAdmin mounts
12
+ * after this call so nothing shadows them.
13
+ */
14
+
15
+ import type { OpenAPIHono } from "@hono/zod-openapi";
16
+ import type { Hono, MiddlewareHandler } from "hono";
17
+ import { createAccountsApp } from "./accounts-api.ts";
18
+ import { createAgentTemplatesApp } from "./agent-templates-api.ts";
19
+ import { type AdminDeps, createAdminApp } from "./agents-api.ts";
20
+ import { createAgentRuntimeApp } from "./api.ts";
21
+ import { createGithubEnterpriseApp } from "./github-enterprise-api.ts";
22
+ import { mountPlatformDoc } from "./platform-doc-route.ts";
23
+ import { createPrincipalsApp } from "./principals-api.ts";
24
+
25
+ type AgentRuntimeDeps = Parameters<typeof createAgentRuntimeApp>[0];
26
+ type AccountsDeps = Parameters<typeof createAccountsApp>[0];
27
+ type PrincipalsDeps = Parameters<typeof createPrincipalsApp>[0];
28
+ type TemplatesDeps = Parameters<typeof createAgentTemplatesApp>[0];
29
+ type GithubEnterpriseDeps = Parameters<typeof createGithubEnterpriseApp>[0];
30
+
31
+ export interface PlatformApiDeps {
32
+ runtime: AgentRuntimeDeps;
33
+ adminApi: AdminDeps;
34
+ /** Flag-gated GET /doc; omitted when no doc route should be mounted. */
35
+ doc?: {
36
+ env: Record<string, string | undefined>;
37
+ auth: MiddlewareHandler;
38
+ };
39
+ accounts: AccountsDeps;
40
+ principals: PrincipalsDeps;
41
+ templates: TemplatesDeps;
42
+ githubEnterprise: GithubEnterpriseDeps;
43
+ }
44
+
45
+ export interface MountedPlatformApp {
46
+ name: string;
47
+ /** Path prefix the app is mounted under on the root. */
48
+ prefix: string;
49
+ // biome-ignore lint/suspicious/noExplicitAny: apps carry differing Env generics
50
+ app: OpenAPIHono<any>;
51
+ /**
52
+ * Whether the app's routes belong in the committed platform spec
53
+ * (admin/openapi.platform.json). `false` only for apps deliberately kept out
54
+ * of it; each such app must say why in `specExclusion`.
55
+ */
56
+ inSpec: boolean;
57
+ specExclusion?: string;
58
+ }
59
+
60
+ export interface MountedPlatformApis {
61
+ /** Every mounted platform app, in mount order. */
62
+ mounted: MountedPlatformApp[];
63
+ // biome-ignore lint/suspicious/noExplicitAny: see MountedPlatformApp.app
64
+ adminApiApp: OpenAPIHono<any>;
65
+ // biome-ignore lint/suspicious/noExplicitAny: see MountedPlatformApp.app
66
+ githubEnterpriseApp: OpenAPIHono<any>;
67
+ templateService: TemplatesDeps["templateService"];
68
+ }
69
+
70
+ /** Mounts every platform admin API on `root`, in the order the boot relies on. */
71
+ export function mountPlatformApis(
72
+ // biome-ignore lint/suspicious/noExplicitAny: the root app carries arbitrary Env generics
73
+ root: Hono<any>,
74
+ deps: PlatformApiDeps,
75
+ ): MountedPlatformApis {
76
+ const mounted: MountedPlatformApp[] = [];
77
+ const mount = (entry: MountedPlatformApp) => {
78
+ root.route(entry.prefix, entry.app);
79
+ mounted.push(entry);
80
+ };
81
+
82
+ // Runtime API — admin key | per-agent bearer | session JWT. Hono strips the
83
+ // /agents prefix before dispatching, so its routes are /:id/config etc.
84
+ mount({
85
+ name: "runtime",
86
+ prefix: "/agents",
87
+ app: createAgentRuntimeApp(deps.runtime),
88
+ inSpec: true,
89
+ });
90
+
91
+ // Admin CRUD API — /agents/:id/* (same prefix as runtime, different sub-paths).
92
+ const adminApiApp = createAdminApp(deps.adminApi);
93
+ mount({ name: "admin", prefix: "/", app: adminApiApp, inSpec: true });
94
+
95
+ // Platform OpenAPI document — GET /doc, flag-gated (not mounted when off).
96
+ if (deps.doc) mountPlatformDoc(root, deps.doc);
97
+
98
+ mount({
99
+ name: "accounts",
100
+ prefix: "/",
101
+ app: createAccountsApp(deps.accounts),
102
+ inSpec: false,
103
+ specExclusion:
104
+ "flag-gated (self-serve signup); never part of the committed platform spec",
105
+ });
106
+ // The three apps below own disjoint prefixes, so their relative order does
107
+ // not affect routing; it is fixed to keep the committed spec's key order.
108
+ const githubEnterpriseApp = createGithubEnterpriseApp(deps.githubEnterprise);
109
+ mount({
110
+ name: "github-enterprise",
111
+ prefix: "/",
112
+ app: githubEnterpriseApp,
113
+ inSpec: true,
114
+ });
115
+ mount({
116
+ name: "templates",
117
+ prefix: "/",
118
+ app: createAgentTemplatesApp(deps.templates),
119
+ inSpec: true,
120
+ });
121
+ mount({
122
+ name: "principals",
123
+ prefix: "/",
124
+ app: createPrincipalsApp(deps.principals),
125
+ inSpec: true,
126
+ });
127
+
128
+ return {
129
+ mounted,
130
+ adminApiApp,
131
+ githubEnterpriseApp,
132
+ templateService: deps.templates.templateService,
133
+ };
134
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * admin/src/platform-routes.unit.test.ts
3
+ *
4
+ * Guards that startAdmin and buildPlatformAdminSpec share one mount list: every
5
+ * app mounted by mountPlatformApis must contribute its OpenAPI paths to the
6
+ * platform spec, unless it is explicitly excluded with a reason.
7
+ */
8
+
9
+ import { describe, expect, it } from "bun:test";
10
+ import { Hono } from "hono";
11
+ import { buildPlatformAdminSpec } from "./admin-spec.ts";
12
+ import { mountPlatformApis, type PlatformApiDeps } from "./platform-routes.ts";
13
+
14
+ // Capture the mounted list through the spec builder's own stub deps by
15
+ // re-running the mount with minimal deps: factories only read deps lazily.
16
+ function mountWithStubs() {
17
+ const noAuth = { validate: async () => null };
18
+ const common = {
19
+ sessionSecret: "dummy-secret-32chars-for-spec-gen",
20
+ agentTokenService: noAuth,
21
+ };
22
+ const deps = {
23
+ runtime: { ...common },
24
+ adminApi: { ...common, provisioner: undefined },
25
+ accounts: { accountService: {}, accountLifecycle: {}, ...common },
26
+ principals: { lookup: {}, ...common },
27
+ templates: {
28
+ templateService: {},
29
+ callerScopeResolver: async () => ({ kind: "all" }),
30
+ ...common,
31
+ },
32
+ githubEnterprise: {
33
+ appService: {},
34
+ agentService: {},
35
+ agentEnvService: {},
36
+ ...common,
37
+ },
38
+ } as unknown as PlatformApiDeps;
39
+ const root = new Hono();
40
+ return { root, result: mountPlatformApis(root, deps) };
41
+ }
42
+
43
+ const toOpenApiPath = (prefix: string, path: string) =>
44
+ `${prefix === "/" ? "" : prefix}${path.replace(/:(\w+)/g, "{$1}")}`;
45
+
46
+ describe("mountPlatformApis", () => {
47
+ const { result } = mountWithStubs();
48
+ const spec = buildPlatformAdminSpec();
49
+
50
+ it("mounts the expected platform apps in order", () => {
51
+ expect(result.mounted.map((m) => m.name)).toEqual([
52
+ "runtime",
53
+ "admin",
54
+ "accounts",
55
+ "github-enterprise",
56
+ "templates",
57
+ "principals",
58
+ ]);
59
+ });
60
+
61
+ it("returns the apps the admin UI wiring needs", () => {
62
+ expect(result.adminApiApp).toBe(
63
+ result.mounted.find((m) => m.name === "admin")?.app as never,
64
+ );
65
+ expect(result.githubEnterpriseApp).toBe(
66
+ result.mounted.find((m) => m.name === "github-enterprise")?.app as never,
67
+ );
68
+ });
69
+
70
+ it("puts every mounted app's OpenAPI paths into buildPlatformAdminSpec()", () => {
71
+ for (const entry of result.mounted.filter((m) => m.inSpec)) {
72
+ const paths = Object.keys(
73
+ entry.app.getOpenAPI31Document({
74
+ openapi: "3.1.0",
75
+ info: { title: entry.name, version: "0.0.0" },
76
+ }).paths ?? {},
77
+ );
78
+ expect(
79
+ paths.length,
80
+ `${entry.name} has no OpenAPI paths`,
81
+ ).toBeGreaterThan(0);
82
+ for (const path of paths) {
83
+ expect(
84
+ Object.keys(spec.paths),
85
+ `${entry.name}: ${path} missing from the platform spec`,
86
+ ).toContain(toOpenApiPath(entry.prefix, path));
87
+ }
88
+ }
89
+ });
90
+
91
+ it("only leaves an app out of the spec with a stated reason", () => {
92
+ const excluded = result.mounted.filter((m) => !m.inSpec);
93
+ expect(excluded.map((m) => m.name)).toEqual(["accounts"]);
94
+ for (const entry of excluded) {
95
+ expect(entry.specExclusion?.length ?? 0).toBeGreaterThan(0);
96
+ }
97
+ });
98
+ });