@app-vitals/agent-admin 1.116.0 → 1.118.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.116.0",
3
+ "version": "1.118.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.116.0",
47
+ "@app-vitals/agent-lib": "1.118.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -87,6 +87,7 @@ import { AgentPluginService } from "./agent-plugins.ts";
87
87
  import { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
88
88
  import { AgentTemplateService } from "./agent-templates.ts";
89
89
  import { AgentTokenService } from "./agent-tokens.ts";
90
+ import { AgentToolsTokenService } from "./agent-tools-token.ts";
90
91
  import { AgentToolService } from "./agent-tools.ts";
91
92
  import { AgentService } from "./agents.ts";
92
93
  import { parseAdminApiKeys } from "./agents-api.ts";
@@ -141,6 +142,7 @@ import { runStartupPolicyReconcile } from "./startup-policy-reconcile.ts";
141
142
  import { runTemplateSeed } from "./template-seed.ts";
142
143
  import { createTimezoneResolver } from "./timezone-resolver.ts";
143
144
  import { makeStrictTokenCrypto, makeTokenCrypto } from "./token-crypto.ts";
145
+ import { createToolsTokenGuard } from "./tools-token-policy.ts";
144
146
  import {
145
147
  resolveTrialExpirySweepIntervalMs,
146
148
  TrialExpirySweeper,
@@ -240,6 +242,10 @@ export async function startAdmin(
240
242
  const agentCronRunService = new AgentCronRunService(prisma);
241
243
  const agentToolService = new AgentToolService(prisma);
242
244
  const agentTokenService = new AgentTokenService(prisma);
245
+ const toolsTokenService = new AgentToolsTokenService(
246
+ agentTokenService,
247
+ agentEnvService,
248
+ );
243
249
  const agentPluginService = new AgentPluginService(prisma);
244
250
  const agentMarketplaceService = new AgentMarketplaceService(prisma);
245
251
  const agentMemberService = new AgentMemberService(prisma);
@@ -548,6 +554,7 @@ export async function startAdmin(
548
554
  : {}),
549
555
  sessionSecret,
550
556
  adminApiKeys,
557
+ toolsTokenPolicy: resolvedExtensions.toolsTokenPolicy,
551
558
  agentTokenService,
552
559
  anthropicFederationEnabled,
553
560
  repoAccessCheckEnabled: repoAccessConfig.enabled,
@@ -581,8 +588,10 @@ export async function startAdmin(
581
588
  decrypt: crypto.decrypt,
582
589
  slackConfigTokens,
583
590
  agentTemplateReconcileService: templateReconcileService,
591
+ toolsTokenService,
584
592
  sessionSecret,
585
593
  adminApiKeys,
594
+ toolsTokenPolicy: resolvedExtensions.toolsTokenPolicy,
586
595
  sentryClient: process.env.SENTRY_DSN ? Sentry : undefined,
587
596
  pool: adminPool,
588
597
  selfServe,
@@ -661,6 +670,17 @@ export async function startAdmin(
661
670
 
662
671
  // 3c. Extension API routes — after every platform API, before the admin UI
663
672
  // (same no-shadowing rule as the admin CRUD API above).
673
+ // Extension routes authenticate on their own, so the tools-token guard
674
+ // (registered after the platform APIs, so it only sees fall-through
675
+ // requests) applies the route policy to tools-kind bearers here.
676
+ root.use(
677
+ "/agents/*",
678
+ createToolsTokenGuard({
679
+ agentTokenService,
680
+ adminApiKeys,
681
+ extensionRules: resolvedExtensions.toolsTokenPolicy,
682
+ }),
683
+ );
664
684
  mountRouteContributions(root, resolvedExtensions.apiRoutes);
665
685
 
666
686
  // 4. Admin UI — /admin/* — session JWT
@@ -699,6 +719,7 @@ export async function startAdmin(
699
719
  encryptionConfigured: () => makeStrictTokenCrypto() !== null,
700
720
  },
701
721
  templateReconcile: templateReconcileService,
722
+ toolsTokenService,
702
723
  serviceIntegrations,
703
724
  chatService: deletionChatService,
704
725
  slack: slackClient,
@@ -916,6 +937,20 @@ export async function startAdmin(
916
937
  logger: console,
917
938
  });
918
939
 
940
+ // Tools-token backfill: every non-self-hosted agent gets a tools-kind token
941
+ // and env row. Fire-and-forget; per-agent failures are logged, never thrown.
942
+ void agentService
943
+ .list()
944
+ .then((agents) =>
945
+ toolsTokenService.ensureAll(agents.filter((a) => !a.selfHosted)),
946
+ )
947
+ .catch((err) =>
948
+ console.error(
949
+ "[admin] tools token backfill failed:",
950
+ err instanceof Error ? err.message : String(err),
951
+ ),
952
+ );
953
+
919
954
  // Policy-only reconcile (ACP-1.3): a Claude policy change restarts admin via
920
955
  // the chart's policy-hash env var, so rolling only the agents whose policy
921
956
  // wiring drifted happens here. Runs even with no policy configured so agents
@@ -81,6 +81,7 @@ import type {
81
81
  SpecialtyOption,
82
82
  SpecialtyTypeResolver,
83
83
  } from "./specialty-types.ts";
84
+ import type { ToolsTokenPolicyRule } from "./tools-token-policy.ts";
84
85
 
85
86
  /** The platform services an extension may build on. */
86
87
  export interface AdminPlatformServices {
@@ -239,6 +240,14 @@ export interface AdminExtension {
239
240
  backgroundPasses?(ctx: AdminExtensionContext): AdminBackgroundPass[];
240
241
  settingsNavItems?(ctx: AdminExtensionContext): SettingsNavContribution[];
241
242
  openApi?(): AdminOpenApiContribution;
243
+ /**
244
+ * Allow/deny decisions for tools-kind agent tokens on routes this extension
245
+ * adds, keyed by method and `{param}` path template (`subpaths` also covers
246
+ * deeper paths). Optional and additive. A route with no declaration is
247
+ * allowed; a platform deny cannot be lifted from here. See
248
+ * tools-token-policy.ts.
249
+ */
250
+ toolsTokenPolicy?(): ReadonlyArray<ToolsTokenPolicyRule>;
242
251
  }
243
252
 
244
253
  /** The order resolveAdminExtensions calls the context hooks in. */
@@ -261,6 +270,8 @@ export interface ResolvedAdminExtensions {
261
270
  agentDetailCards: AgentDetailCardSlot[];
262
271
  backgroundPasses: AdminBackgroundPass[];
263
272
  settingsNavItems: SettingsNavContribution[];
273
+ /** Every extension's toolsTokenPolicy() rules, concatenated in order. */
274
+ toolsTokenPolicy?: ToolsTokenPolicyRule[];
264
275
  }
265
276
 
266
277
  /**
@@ -308,6 +319,9 @@ export function resolveAdminExtensions(
308
319
  agentDetailCards,
309
320
  backgroundPasses,
310
321
  settingsNavItems,
322
+ toolsTokenPolicy: extensions.flatMap((ext) => [
323
+ ...(ext.toolsTokenPolicy?.() ?? []),
324
+ ]),
311
325
  };
312
326
  }
313
327
 
@@ -54,6 +54,7 @@ describe("resolveAdminExtensions", () => {
54
54
  agentDetailCards: [],
55
55
  backgroundPasses: [],
56
56
  settingsNavItems: [],
57
+ toolsTokenPolicy: [],
57
58
  });
58
59
  });
59
60
 
package/src/admin-ui.ts CHANGED
@@ -128,6 +128,7 @@ import type { AgentTemplateReconcileService } from "./agent-template-reconcile.t
128
128
  import type { AgentTemplateService } from "./agent-templates.ts";
129
129
  import type { AgentTokenService } from "./agent-tokens.ts";
130
130
  import type { AgentToolService } from "./agent-tools.ts";
131
+ import type { ToolsTokenEnsurer } from "./agent-tools-token.ts";
131
132
  import type { AgentService } from "./agents.ts";
132
133
  import {
133
134
  ACCOUNT_REQUIRED_MESSAGE,
@@ -461,6 +462,8 @@ export interface AdminUIDeps {
461
462
  specialtyDefaults?: SpecialtyDefaultsResolver;
462
463
  /** ATP-2.2: seeds the resolved agent template inside the create transaction. */
463
464
  templateReconcile?: Pick<AgentTemplateReconcileService, "reconcile">;
465
+ /** Mints the tools-kind token for a newly created agent. */
466
+ toolsTokenService?: ToolsTokenEnsurer;
464
467
  /**
465
468
  * Cleanup deps for the full delete-agent orchestration (POST
466
469
  * /admin/agents/:id/delete → deleteAgentFully()). Matches
@@ -1022,6 +1025,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1022
1025
  templateService,
1023
1026
  slackConfigToken,
1024
1027
  templateReconcile,
1028
+ toolsTokenService,
1025
1029
  agentsApi,
1026
1030
  specialtyRegistry = new SpecialtyTypes(),
1027
1031
  specialtyDefaults,
@@ -1995,6 +1999,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1995
1999
  specialtyDefaults,
1996
2000
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
1997
2001
  ...(templateReconcile ? { templateReconcile } : {}),
2002
+ ...(toolsTokenService ? { toolsTokenService } : {}),
1998
2003
  },
1999
2004
  {
2000
2005
  name,
package/src/agent-envs.ts CHANGED
@@ -239,6 +239,22 @@ export class AgentEnvService {
239
239
  return { env, secretKeys, sources };
240
240
  }
241
241
 
242
+ /**
243
+ * Decrypted value of one enabled env key, or null when the key is absent,
244
+ * disabled, or cannot be decrypted. Never logs the value.
245
+ */
246
+ async getValue(agentId: string, key: string): Promise<string | null> {
247
+ const row = await this.prisma.agentEnv.findUnique({
248
+ where: { agentId_key: { agentId, key } },
249
+ });
250
+ if (!row?.enabled) return null;
251
+ try {
252
+ return this.crypto.decrypt(row.value);
253
+ } catch {
254
+ return null;
255
+ }
256
+ }
257
+
242
258
  /**
243
259
  * Returns the full env bundle for an agent — stored env vars (decrypted) plus
244
260
  * allowed tools. Always decrypts regardless of the secret flag.
@@ -87,6 +87,7 @@ export const TEMPLATE_ENV_DENYLIST: ReadonlySet<string> = new Set([
87
87
  "SLACK_SIGNING_SECRET",
88
88
  "GH_TOKEN",
89
89
  "SHIPWRIGHT_AGENT_API_KEY",
90
+ "SHIPWRIGHT_AGENT_TOOLS_API_KEY",
90
91
  "SHIPWRIGHT_TASK_STORE_URL",
91
92
  "SHIPWRIGHT_TASK_STORE_TOKEN",
92
93
  ...ANTHROPIC_CREDENTIAL_KEYS,
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Integration tests for AgentToolsTokenService against a real PostgreSQL DB.
3
+ * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
4
+ */
5
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
6
+ import type { PrismaClient } from "../prisma/client/client.ts";
7
+ import { AgentCronJobService } from "./agent-cron-jobs.ts";
8
+ import { AgentEnvService } from "./agent-envs.ts";
9
+ import { AgentMemberService } from "./agent-members.ts";
10
+ import { AgentPluginService } from "./agent-plugins.ts";
11
+ import { AgentToolService } from "./agent-tools.ts";
12
+ import { AgentService, createAgent } from "./agents.ts";
13
+ import { SpecialtyTypes } from "./specialty-types.ts";
14
+ import { AgentTokenService } from "./agent-tokens.ts";
15
+ import {
16
+ AgentToolsTokenService,
17
+ TOOLS_TOKEN_ENV_KEY,
18
+ } from "./agent-tools-token.ts";
19
+ import { createAdminPrismaClient } from "./prisma-client.ts";
20
+ import { identityCrypto } from "./token-crypto.ts";
21
+
22
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
23
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
24
+
25
+ describeOrSkip("AgentToolsTokenService (integration)", () => {
26
+ let prisma: PrismaClient;
27
+ let tokens: AgentTokenService;
28
+ let envs: AgentEnvService;
29
+ let svc: AgentToolsTokenService;
30
+ let errors: string[];
31
+
32
+ beforeEach(async () => {
33
+ prisma = createAdminPrismaClient(TEST_DB as string);
34
+ await prisma.agentToken.deleteMany();
35
+ await prisma.agentCronJob.deleteMany();
36
+ await prisma.agentTool.deleteMany();
37
+ await prisma.agentEnv.deleteMany();
38
+ await prisma.agent.deleteMany();
39
+ tokens = new AgentTokenService(prisma);
40
+ envs = new AgentEnvService(prisma, identityCrypto);
41
+ errors = [];
42
+ svc = new AgentToolsTokenService(tokens, envs, {
43
+ error: (m: string) => void errors.push(m),
44
+ });
45
+ });
46
+
47
+ afterEach(async () => {
48
+ await prisma.$disconnect();
49
+ });
50
+
51
+ async function newAgent(name: string): Promise<string> {
52
+ return (await prisma.agent.create({ data: { name } })).id;
53
+ }
54
+
55
+ it("creates a token and secret env row that validates as tools-kind, idempotently", async () => {
56
+ const id = await newAgent("agent-a");
57
+ expect(await svc.ensureToolsToken(id)).toBe("created");
58
+ const row = await prisma.agentEnv.findUnique({
59
+ where: { agentId_key: { agentId: id, key: TOOLS_TOKEN_ENV_KEY } },
60
+ });
61
+ expect(row?.secret).toBe(true);
62
+ const raw = await envs.getValue(id, TOOLS_TOKEN_ENV_KEY);
63
+ expect(await tokens.validate(raw as string)).toEqual({
64
+ agentId: id,
65
+ kind: "tools",
66
+ });
67
+ expect(await svc.ensureToolsToken(id)).toBe("unchanged");
68
+ expect(await prisma.agentToken.count({ where: { agentId: id } })).toBe(1);
69
+ });
70
+
71
+ it("repairs a revoked token", async () => {
72
+ const id = await newAgent("agent-a");
73
+ await svc.ensureToolsToken(id);
74
+ const [tok] = await tokens.listForAgent(id);
75
+ await tokens.revoke((tok as { id: string }).id);
76
+ expect(await svc.ensureToolsToken(id)).toBe("created");
77
+ const raw = await envs.getValue(id, TOOLS_TOKEN_ENV_KEY);
78
+ expect((await tokens.validate(raw as string))?.kind).toBe("tools");
79
+ });
80
+
81
+ it("backfill leaves the others covered when one agent fails", async () => {
82
+ const a = await newAgent("agent-a");
83
+ const b = await newAgent("agent-b");
84
+ const result = await svc.ensureAll([
85
+ { id: a },
86
+ { id: "missing-agent" },
87
+ { id: b },
88
+ ]);
89
+ expect(result.created.sort()).toEqual([a, b].sort());
90
+ expect(result.failed.map((f) => f.agentId)).toEqual(["missing-agent"]);
91
+ for (const id of [a, b]) {
92
+ expect(await envs.getValue(id, TOOLS_TOKEN_ENV_KEY)).not.toBeNull();
93
+ }
94
+ });
95
+
96
+ it("createAgent provisioning mints the token and env row", async () => {
97
+ const result = await createAgent(
98
+ {
99
+ agentService: new AgentService(prisma),
100
+ agentToolService: new AgentToolService(prisma),
101
+ agentPluginService: new AgentPluginService(prisma),
102
+ agentMemberService: new AgentMemberService(prisma),
103
+ agentEnvService: envs,
104
+ agentCronJobService: new AgentCronJobService(prisma),
105
+ provisioner: { canProvision: false, provision: async () => {} },
106
+ specialtyRegistry: new SpecialtyTypes(),
107
+ toolsTokenService: svc,
108
+ } as never,
109
+ {
110
+ name: "agent-created",
111
+ specialty: "specialist",
112
+ runtime: undefined,
113
+ reposRaw: undefined,
114
+ authorAllowlistRaw: undefined,
115
+ patchAuthorAllowlistRaw: undefined,
116
+ memberEmailsRaw: undefined,
117
+ restrictSlackToMembersRaw: undefined,
118
+ claudeCodeOauthToken: undefined,
119
+ anthropicApiKey: undefined,
120
+ },
121
+ );
122
+ expect(result.ok).toBe(true);
123
+ const id = (result as { agent: { id: string } }).agent.id;
124
+ const raw = await envs.getValue(id, TOOLS_TOKEN_ENV_KEY);
125
+ expect((await tokens.validate(raw as string))?.kind).toBe("tools");
126
+ });
127
+ });
@@ -0,0 +1,80 @@
1
+ /**
2
+ * admin/src/agent-tools-token.ts
3
+ * Mints a tools-kind AgentToken per agent and stores the raw value, encrypted,
4
+ * in the agent's env bundle as SHIPWRIGHT_AGENT_TOOLS_API_KEY (secret).
5
+ *
6
+ * Idempotent: a stored value that still validates as a tools-kind token for
7
+ * the agent means nothing to do. A missing env row, a revoked token, or a
8
+ * value that is not this agent's tools token is repaired by minting a new one.
9
+ * The raw token is never logged.
10
+ */
11
+
12
+ import { SECRET_ENV_VARS } from "@app-vitals/agent-lib/secret-env-vars";
13
+ import type { AgentEnvService } from "./agent-envs.ts";
14
+ import type { AgentTokenService } from "./agent-tokens.ts";
15
+
16
+ export const TOOLS_TOKEN_ENV_KEY = "SHIPWRIGHT_AGENT_TOOLS_API_KEY";
17
+
18
+ export type EnsureToolsTokenResult = "created" | "unchanged";
19
+
20
+ export interface EnsureAllToolsTokensResult {
21
+ created: string[];
22
+ unchanged: string[];
23
+ failed: Array<{ agentId: string; error: string }>;
24
+ }
25
+
26
+ export interface ToolsTokenEnsurer {
27
+ ensureToolsToken(agentId: string): Promise<EnsureToolsTokenResult>;
28
+ }
29
+
30
+ export class AgentToolsTokenService implements ToolsTokenEnsurer {
31
+ constructor(
32
+ private tokens: Pick<AgentTokenService, "create" | "validate">,
33
+ private envs: Pick<AgentEnvService, "patch" | "getValue">,
34
+ private logger: Pick<Console, "error"> = console,
35
+ ) {}
36
+
37
+ async ensureToolsToken(agentId: string): Promise<EnsureToolsTokenResult> {
38
+ const stored = await this.envs.getValue(agentId, TOOLS_TOKEN_ENV_KEY);
39
+ if (stored) {
40
+ const valid = await this.tokens.validate(stored);
41
+ if (valid && valid.agentId === agentId && valid.kind === "tools") {
42
+ return "unchanged";
43
+ }
44
+ }
45
+ const { rawToken } = await this.tokens.create(
46
+ agentId,
47
+ "tools (auto)",
48
+ "tools",
49
+ );
50
+ await this.envs.patch(
51
+ agentId,
52
+ { [TOOLS_TOKEN_ENV_KEY]: rawToken },
53
+ new Set(SECRET_ENV_VARS),
54
+ );
55
+ return "created";
56
+ }
57
+
58
+ /** Ensure every agent; one agent's failure is logged and never stops the rest. */
59
+ async ensureAll(
60
+ agents: ReadonlyArray<{ id: string }>,
61
+ ): Promise<EnsureAllToolsTokensResult> {
62
+ const result: EnsureAllToolsTokensResult = {
63
+ created: [],
64
+ unchanged: [],
65
+ failed: [],
66
+ };
67
+ for (const { id } of agents) {
68
+ try {
69
+ result[await this.ensureToolsToken(id)].push(id);
70
+ } catch (err) {
71
+ const error = err instanceof Error ? err.message : String(err);
72
+ this.logger.error(
73
+ `[agent-tools-token] agent ${id}: ensure failed: ${error}`,
74
+ );
75
+ result.failed.push({ agentId: id, error });
76
+ }
77
+ }
78
+ return result;
79
+ }
80
+ }
@@ -0,0 +1,95 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import type { AgentTokenKind } from "./agent-tokens.ts";
3
+ import {
4
+ AgentToolsTokenService,
5
+ TOOLS_TOKEN_ENV_KEY,
6
+ } from "./agent-tools-token.ts";
7
+
8
+ function setup() {
9
+ const active = new Map<string, { agentId: string; kind: AgentTokenKind }>();
10
+ const env = new Map<string, string>();
11
+ const created: Array<{ agentId: string; kind: AgentTokenKind }> = [];
12
+ const patches: Array<{ key: string; secret: boolean }> = [];
13
+ const errors: string[] = [];
14
+ let n = 0;
15
+ const failFor = new Set<string>();
16
+ const svc = new AgentToolsTokenService(
17
+ {
18
+ create: async (agentId: string, _l?: string, kind = "runtime") => {
19
+ if (failFor.has(agentId)) throw new Error("boom");
20
+ const raw = `raw-${++n}`;
21
+ active.set(raw, { agentId, kind: kind as AgentTokenKind });
22
+ created.push({ agentId, kind: kind as AgentTokenKind });
23
+ return { token: {} as never, rawToken: raw };
24
+ },
25
+ validate: async (raw: string) => active.get(raw) ?? null,
26
+ },
27
+ {
28
+ getValue: async (agentId: string) => env.get(agentId) ?? null,
29
+ patch: async (
30
+ agentId: string,
31
+ e: Record<string, string>,
32
+ secrets?: Set<string>,
33
+ ) => {
34
+ for (const [k, v] of Object.entries(e)) {
35
+ env.set(agentId, v);
36
+ patches.push({ key: k, secret: secrets?.has(k) ?? false });
37
+ }
38
+ },
39
+ },
40
+ { error: (m: string) => void errors.push(m) },
41
+ );
42
+ return { svc, active, env, created, patches, errors, failFor };
43
+ }
44
+
45
+ describe("AgentToolsTokenService.ensureToolsToken", () => {
46
+ it("mints a tools token and stores it as a secret", async () => {
47
+ const t = setup();
48
+ expect(await t.svc.ensureToolsToken("a1")).toBe("created");
49
+ expect(t.created).toEqual([{ agentId: "a1", kind: "tools" }]);
50
+ expect(t.patches).toEqual([{ key: TOOLS_TOKEN_ENV_KEY, secret: true }]);
51
+ });
52
+
53
+ it("is idempotent", async () => {
54
+ const t = setup();
55
+ await t.svc.ensureToolsToken("a1");
56
+ expect(await t.svc.ensureToolsToken("a1")).toBe("unchanged");
57
+ expect(t.created).toHaveLength(1);
58
+ });
59
+
60
+ it("repairs a missing env row", async () => {
61
+ const t = setup();
62
+ await t.svc.ensureToolsToken("a1");
63
+ t.env.delete("a1");
64
+ expect(await t.svc.ensureToolsToken("a1")).toBe("created");
65
+ expect(t.created).toHaveLength(2);
66
+ });
67
+
68
+ it("repairs a revoked token", async () => {
69
+ const t = setup();
70
+ await t.svc.ensureToolsToken("a1");
71
+ t.active.clear();
72
+ expect(await t.svc.ensureToolsToken("a1")).toBe("created");
73
+ });
74
+
75
+ it("replaces a stored value that is not this agent's tools token", async () => {
76
+ const t = setup();
77
+ t.active.set("rt", { agentId: "a1", kind: "runtime" });
78
+ t.env.set("a1", "rt");
79
+ expect(await t.svc.ensureToolsToken("a1")).toBe("created");
80
+ });
81
+
82
+ it("ensureAll logs a failure without stopping the rest or leaking tokens", async () => {
83
+ const t = setup();
84
+ t.failFor.add("bad");
85
+ const r = await t.svc.ensureAll([
86
+ { id: "a1" },
87
+ { id: "bad" },
88
+ { id: "a2" },
89
+ ]);
90
+ expect(r.created).toEqual(["a1", "a2"]);
91
+ expect(r.failed.map((f) => f.agentId)).toEqual(["bad"]);
92
+ expect(t.errors).toHaveLength(1);
93
+ expect(t.errors[0]).not.toContain("raw-");
94
+ });
95
+ });
package/src/agents-api.ts CHANGED
@@ -72,6 +72,10 @@ import { AGENT_TEMPLATE_ITEM_KINDS } from "./agent-template-items.ts";
72
72
  import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
73
73
  import { type AgentTokenService, agentTokenKindOf } from "./agent-tokens.ts";
74
74
  import type { AgentToolService } from "./agent-tools.ts";
75
+ import type {
76
+ AgentToolsTokenService,
77
+ ToolsTokenEnsurer,
78
+ } from "./agent-tools-token.ts";
75
79
  import type { AgentService } from "./agents.ts";
76
80
  import {
77
81
  createAgent,
@@ -178,6 +182,10 @@ import type { SelfServeConfig } from "./self-serve-config.ts";
178
182
  import type { SpecialtyDefaultsResolver } from "./specialty-defaults.ts";
179
183
  import type { SpecialtyTypeResolver } from "./specialty-types.ts";
180
184
  import { managedReconcileTargets } from "./startup-policy-reconcile.ts";
185
+ import {
186
+ assertToolsTokenPreCheck,
187
+ type ToolsTokenPolicyRule,
188
+ } from "./tools-token-policy.ts";
181
189
 
182
190
  // ─── Types ────────────────────────────────────────────────────────────────────
183
191
 
@@ -258,6 +266,10 @@ export interface AdminDeps {
258
266
  specialtyRegistry: SpecialtyTypeResolver;
259
267
  /** Extension-supplied specialty defaults, consulted before the built-in type. */
260
268
  specialtyDefaults?: SpecialtyDefaultsResolver;
269
+ /** Mints and backfills per-agent tools-kind tokens (create, startup, reconcile). */
270
+ toolsTokenService?: Pick<AgentToolsTokenService, "ensureAll"> &
271
+ ToolsTokenEnsurer;
272
+
261
273
  /**
262
274
  * ATP-2.2: per-agent template reconcile engine. Optional (additive): backs
263
275
  * the /agents/{id}/template/* routes (503 when absent) and seeds the
@@ -331,6 +343,8 @@ export interface AdminDeps {
331
343
  sessionSecret: string;
332
344
  /** Parsed SHIPWRIGHT_ADMIN_API_KEYS — optional; absent means env key auth is disabled. */
333
345
  adminApiKeys?: Map<string, AdminApiKey>;
346
+ /** Extension-declared tools-token rules (tools-token-policy.ts). */
347
+ toolsTokenPolicy?: readonly ToolsTokenPolicyRule[];
334
348
  /**
335
349
  * Optional Sentry client for reporting unhandled errors. Undefined means
336
350
  * Sentry is not initialized (SENTRY_DSN unset) — onError simply skips the
@@ -2142,6 +2156,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2142
2156
  callerScopeResolver,
2143
2157
  getAgentAccountId: async (id) =>
2144
2158
  (await agentService.getDetail(id))?.accountId,
2159
+ toolsTokenPolicy: deps.toolsTokenPolicy,
2145
2160
  });
2146
2161
 
2147
2162
  // Platform readers/operators (platform.read / platform.ops admin keys): the
@@ -2182,10 +2197,18 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2182
2197
  );
2183
2198
  }
2184
2199
  const dryRun = c.req.valid("query").dryRun === "true";
2200
+ const agents = await agentService.list();
2185
2201
  const result = await provisioner.reconcile(
2186
- managedReconcileTargets(await agentService.list()),
2202
+ managedReconcileTargets(agents),
2187
2203
  { dryRun },
2188
2204
  );
2205
+ // Backfill tools tokens for managed agents; per-agent failures are logged
2206
+ // inside ensureAll and never fail the reconcile.
2207
+ if (!dryRun && deps.toolsTokenService) {
2208
+ await deps.toolsTokenService.ensureAll(
2209
+ agents.filter((a) => !a.selfHosted),
2210
+ );
2211
+ }
2189
2212
  return c.json(result, 200);
2190
2213
  });
2191
2214
 
@@ -2690,6 +2713,9 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2690
2713
  specialtyRegistry,
2691
2714
  specialtyDefaults,
2692
2715
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
2716
+ ...(deps.toolsTokenService
2717
+ ? { toolsTokenService: deps.toolsTokenService }
2718
+ : {}),
2693
2719
  ...(deps.agentTemplateReconcileService
2694
2720
  ? {
2695
2721
  templateReconcile: {
@@ -2795,6 +2821,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2795
2821
  app.openapi(createCronRoute, async (c) => {
2796
2822
  const { id: agentId } = c.req.valid("param");
2797
2823
  const body = c.req.valid("json");
2824
+ assertToolsTokenPreCheck(c.get("scope"), body.preCheck);
2798
2825
  const cron = await agentCronJobService.create(agentId, body);
2799
2826
  return c.json({ cron: serializeCron(cron) }, 201);
2800
2827
  });
@@ -2870,6 +2897,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2870
2897
  app.openapi(patchCronRoute, async (c) => {
2871
2898
  const { id: agentId, cronId } = c.req.valid("param");
2872
2899
  const body = c.req.valid("json");
2900
+ assertToolsTokenPreCheck(c.get("scope"), body.preCheck);
2873
2901
 
2874
2902
  const hasSchedule = body.schedule != null;
2875
2903
  const hasPrompt = body.prompt != null;
package/src/agents.ts CHANGED
@@ -21,6 +21,7 @@ import type { AgentPluginService } from "./agent-plugins.ts";
21
21
  import type { AgentProvisioner } from "./agent-provisioner.ts";
22
22
  import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
23
23
  import type { AgentToolService } from "./agent-tools.ts";
24
+ import type { ToolsTokenEnsurer } from "./agent-tools-token.ts";
24
25
  import {
25
26
  ANTHROPIC_CREDENTIALS_BLOCKED_CODE,
26
27
  anthropicCredentialKeysIn,
@@ -880,6 +881,12 @@ export interface CreateAgentDeps {
880
881
  * defaults are copied directly.
881
882
  */
882
883
  templateReconcile?: Pick<AgentTemplateReconcileService, "reconcile">;
884
+ /**
885
+ * Mints the agent's tools-kind token and stores it in the env bundle.
886
+ * Optional (additive); a failure is logged and never fails creation
887
+ * (startup and POST /agents/reconcile backfill).
888
+ */
889
+ toolsTokenService?: ToolsTokenEnsurer;
883
890
  }
884
891
 
885
892
  /**
@@ -1278,6 +1285,17 @@ export async function createAgent(
1278
1285
  new Set(SECRET_ENV_VARS),
1279
1286
  );
1280
1287
 
1288
+ if (deps.toolsTokenService) {
1289
+ try {
1290
+ await deps.toolsTokenService.ensureToolsToken(agent.id);
1291
+ } catch (err) {
1292
+ console.error(
1293
+ `[agents] createAgent: failed to mint tools token for agent ${agent.id} (non-fatal):`,
1294
+ err instanceof Error ? err.message : String(err),
1295
+ );
1296
+ }
1297
+ }
1298
+
1281
1299
  if (inCluster) {
1282
1300
  // Kubernetes provisioning is an external side effect that cannot join
1283
1301
  // the DB transaction above — it runs after that transaction has already