@app-vitals/agent-admin 1.116.0 → 1.117.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.117.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.117.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";
@@ -240,6 +241,10 @@ export async function startAdmin(
240
241
  const agentCronRunService = new AgentCronRunService(prisma);
241
242
  const agentToolService = new AgentToolService(prisma);
242
243
  const agentTokenService = new AgentTokenService(prisma);
244
+ const toolsTokenService = new AgentToolsTokenService(
245
+ agentTokenService,
246
+ agentEnvService,
247
+ );
243
248
  const agentPluginService = new AgentPluginService(prisma);
244
249
  const agentMarketplaceService = new AgentMarketplaceService(prisma);
245
250
  const agentMemberService = new AgentMemberService(prisma);
@@ -581,6 +586,7 @@ export async function startAdmin(
581
586
  decrypt: crypto.decrypt,
582
587
  slackConfigTokens,
583
588
  agentTemplateReconcileService: templateReconcileService,
589
+ toolsTokenService,
584
590
  sessionSecret,
585
591
  adminApiKeys,
586
592
  sentryClient: process.env.SENTRY_DSN ? Sentry : undefined,
@@ -699,6 +705,7 @@ export async function startAdmin(
699
705
  encryptionConfigured: () => makeStrictTokenCrypto() !== null,
700
706
  },
701
707
  templateReconcile: templateReconcileService,
708
+ toolsTokenService,
702
709
  serviceIntegrations,
703
710
  chatService: deletionChatService,
704
711
  slack: slackClient,
@@ -916,6 +923,20 @@ export async function startAdmin(
916
923
  logger: console,
917
924
  });
918
925
 
926
+ // Tools-token backfill: every non-self-hosted agent gets a tools-kind token
927
+ // and env row. Fire-and-forget; per-agent failures are logged, never thrown.
928
+ void agentService
929
+ .list()
930
+ .then((agents) =>
931
+ toolsTokenService.ensureAll(agents.filter((a) => !a.selfHosted)),
932
+ )
933
+ .catch((err) =>
934
+ console.error(
935
+ "[admin] tools token backfill failed:",
936
+ err instanceof Error ? err.message : String(err),
937
+ ),
938
+ );
939
+
919
940
  // Policy-only reconcile (ACP-1.3): a Claude policy change restarts admin via
920
941
  // the chart's policy-hash env var, so rolling only the agents whose policy
921
942
  // wiring drifted happens here. Runs even with no policy configured so agents
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,
@@ -258,6 +262,10 @@ export interface AdminDeps {
258
262
  specialtyRegistry: SpecialtyTypeResolver;
259
263
  /** Extension-supplied specialty defaults, consulted before the built-in type. */
260
264
  specialtyDefaults?: SpecialtyDefaultsResolver;
265
+ /** Mints and backfills per-agent tools-kind tokens (create, startup, reconcile). */
266
+ toolsTokenService?: Pick<AgentToolsTokenService, "ensureAll"> &
267
+ ToolsTokenEnsurer;
268
+
261
269
  /**
262
270
  * ATP-2.2: per-agent template reconcile engine. Optional (additive): backs
263
271
  * the /agents/{id}/template/* routes (503 when absent) and seeds the
@@ -2182,10 +2190,18 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2182
2190
  );
2183
2191
  }
2184
2192
  const dryRun = c.req.valid("query").dryRun === "true";
2193
+ const agents = await agentService.list();
2185
2194
  const result = await provisioner.reconcile(
2186
- managedReconcileTargets(await agentService.list()),
2195
+ managedReconcileTargets(agents),
2187
2196
  { dryRun },
2188
2197
  );
2198
+ // Backfill tools tokens for managed agents; per-agent failures are logged
2199
+ // inside ensureAll and never fail the reconcile.
2200
+ if (!dryRun && deps.toolsTokenService) {
2201
+ await deps.toolsTokenService.ensureAll(
2202
+ agents.filter((a) => !a.selfHosted),
2203
+ );
2204
+ }
2189
2205
  return c.json(result, 200);
2190
2206
  });
2191
2207
 
@@ -2690,6 +2706,9 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2690
2706
  specialtyRegistry,
2691
2707
  specialtyDefaults,
2692
2708
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
2709
+ ...(deps.toolsTokenService
2710
+ ? { toolsTokenService: deps.toolsTokenService }
2711
+ : {}),
2693
2712
  ...(deps.agentTemplateReconcileService
2694
2713
  ? {
2695
2714
  templateReconcile: {
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