@app-vitals/agent-admin 1.115.2 → 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/src/agents-api.ts CHANGED
@@ -70,8 +70,12 @@ import {
70
70
  } from "./agent-provisioner.ts";
71
71
  import { AGENT_TEMPLATE_ITEM_KINDS } from "./agent-template-items.ts";
72
72
  import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
73
- import type { AgentTokenService } from "./agent-tokens.ts";
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: {
@@ -3096,6 +3115,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3096
3115
  const { token, rawToken } = await agentTokenService.create(
3097
3116
  agentId,
3098
3117
  body?.label,
3118
+ body?.kind,
3099
3119
  );
3100
3120
  // Return the token record (without the hashed token value) + rawToken
3101
3121
  const { token: _hash, ...tokenMeta } = token;
@@ -3103,6 +3123,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3103
3123
  {
3104
3124
  token: {
3105
3125
  ...tokenMeta,
3126
+ kind: agentTokenKindOf(tokenMeta.kind),
3106
3127
  createdAt: tokenMeta.createdAt.toISOString(),
3107
3128
  revokedAt: tokenMeta.revokedAt
3108
3129
  ? tokenMeta.revokedAt.toISOString()
@@ -3121,6 +3142,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3121
3142
  // Never expose the stored hash — return only metadata
3122
3143
  const tokens = records.map(({ token: _hash, ...meta }) => ({
3123
3144
  ...meta,
3145
+ kind: agentTokenKindOf(meta.kind),
3124
3146
  createdAt: meta.createdAt.toISOString(),
3125
3147
  revokedAt: meta.revokedAt ? meta.revokedAt.toISOString() : null,
3126
3148
  }));
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
package/src/api-auth.ts CHANGED
@@ -13,7 +13,7 @@ import type { MiddlewareHandler } from "hono";
13
13
  import { getCookie } from "hono/cookie";
14
14
  import { verify } from "hono/jwt";
15
15
  import type { AgentMemberService } from "./agent-members.ts";
16
- import type { AgentTokenService } from "./agent-tokens.ts";
16
+ import type { AgentTokenKind, AgentTokenService } from "./agent-tokens.ts";
17
17
  import {
18
18
  type CallerScopeResolver,
19
19
  memberOnlyCallerScopeResolver,
@@ -39,6 +39,11 @@ export type AdminScopeKind =
39
39
  export interface AdminScope {
40
40
  kind: AdminScopeKind;
41
41
  agentId?: string;
42
+ /**
43
+ * Kind of the DB agent token that authenticated the request. Optional and
44
+ * additive: unset for env-key and session callers, which are never tools-kind.
45
+ */
46
+ tokenKind?: AgentTokenKind;
42
47
  }
43
48
 
44
49
  export type AdminAuthEnv = {
@@ -371,7 +376,11 @@ export function createAdminAuthMiddleware(deps: {
371
376
  // DB token path — per-agent bearer, not an admin.
372
377
  c.set("isAdmin", false);
373
378
  c.set("caller", { name: result.agentId, scope: result.agentId });
374
- c.set("scope", { kind: "agent", agentId: result.agentId });
379
+ c.set("scope", {
380
+ kind: "agent",
381
+ agentId: result.agentId,
382
+ tokenKind: result.kind,
383
+ });
375
384
  return next();
376
385
  }
377
386
 
@@ -11,7 +11,7 @@ import type { Caller } from "@app-vitals/agent-lib/request-context";
11
11
  import { Hono } from "hono";
12
12
  import { sign } from "hono/jwt";
13
13
  import type { AgentTokenService, AgentTokenValidated } from "./agent-tokens.ts";
14
- import type { AdminAuthEnv } from "./api-auth.ts";
14
+ import type { AdminAuthEnv, AdminScope } from "./api-auth.ts";
15
15
  import {
16
16
  AGENT_CROSS_ROUTES,
17
17
  createAdminAuthMiddleware,
@@ -133,7 +133,9 @@ describe("createAdminAuthMiddleware — session cookie", () => {
133
133
  describe("createAdminAuthMiddleware — bearer token", () => {
134
134
  it("passes when a valid bearer token is provided", async () => {
135
135
  const app = buildApp(async (raw) =>
136
- raw === VALID_RAW_TOKEN ? { agentId: AGENT_ID } : null,
136
+ raw === VALID_RAW_TOKEN
137
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
138
+ : null,
137
139
  );
138
140
  const res = await app.request("/test", {
139
141
  headers: { Authorization: `Bearer ${VALID_RAW_TOKEN}` },
@@ -143,6 +145,58 @@ describe("createAdminAuthMiddleware — bearer token", () => {
143
145
  expect(body.ok).toBe(true);
144
146
  });
145
147
 
148
+ it("exposes the token kind on the caller scope", async () => {
149
+ for (const kind of ["runtime", "tools"] as const) {
150
+ let seen: AdminScope | undefined;
151
+ const mock: Pick<AgentTokenService, "validate"> = {
152
+ validate: async () => ({ agentId: AGENT_ID, kind }),
153
+ };
154
+ const app = new Hono<AdminAuthEnv>();
155
+ app.use(
156
+ "*",
157
+ createAdminAuthMiddleware({
158
+ sessionSecret: SESSION_SECRET,
159
+ agentTokenService: mock,
160
+ }),
161
+ );
162
+ app.get("/test", (c) => {
163
+ seen = c.get("scope");
164
+ return c.json({ ok: true });
165
+ });
166
+ const res = await app.request("/test", {
167
+ headers: { Authorization: `Bearer ${VALID_RAW_TOKEN}` },
168
+ });
169
+ expect(res.status).toBe(200);
170
+ expect(seen).toEqual({
171
+ kind: "agent",
172
+ agentId: AGENT_ID,
173
+ tokenKind: kind,
174
+ });
175
+ }
176
+ });
177
+
178
+ it("does not set tokenKind for env-key callers", async () => {
179
+ let seen: AdminScope | undefined;
180
+ const app = new Hono<AdminAuthEnv>();
181
+ app.use(
182
+ "*",
183
+ createAdminAuthMiddleware({
184
+ sessionSecret: SESSION_SECRET,
185
+ agentTokenService: { validate: async () => null },
186
+ adminApiKeys: new Map([["env-key", { name: "env", scope: AGENT_ID }]]),
187
+ }),
188
+ );
189
+ app.get("/test", (c) => {
190
+ seen = c.get("scope");
191
+ return c.json({ ok: true });
192
+ });
193
+ const res = await app.request("/test", {
194
+ headers: { Authorization: "Bearer env-key" },
195
+ });
196
+ expect(res.status).toBe(200);
197
+ expect(seen?.tokenKind).toBeUndefined();
198
+ });
199
+
146
200
  it("returns 401 when bearer token is invalid (validate returns null)", async () => {
147
201
  const app = buildApp(async () => null);
148
202
  const res = await app.request("/test", {
@@ -209,7 +263,9 @@ describe("createAdminAuthMiddleware — bearer token", () => {
209
263
  describe("createAdminAuthMiddleware — bearer token scope enforcement", () => {
210
264
  it("passes when token agentId matches the :id route param", async () => {
211
265
  const app = buildApp(async (raw) =>
212
- raw === VALID_RAW_TOKEN ? { agentId: AGENT_ID } : null,
266
+ raw === VALID_RAW_TOKEN
267
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
268
+ : null,
213
269
  );
214
270
  const res = await app.request(`/agents/${AGENT_ID}/envs`, {
215
271
  headers: { Authorization: `Bearer ${VALID_RAW_TOKEN}` },
@@ -221,7 +277,9 @@ describe("createAdminAuthMiddleware — bearer token scope enforcement", () => {
221
277
 
222
278
  it("returns 403 when token agentId does not match the :id route param", async () => {
223
279
  const app = buildApp(async (raw) =>
224
- raw === VALID_RAW_TOKEN ? { agentId: AGENT_ID } : null,
280
+ raw === VALID_RAW_TOKEN
281
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
282
+ : null,
225
283
  );
226
284
  const res = await app.request("/agents/agent-different-id/envs", {
227
285
  headers: { Authorization: `Bearer ${VALID_RAW_TOKEN}` },
@@ -234,7 +292,9 @@ describe("createAdminAuthMiddleware — bearer token scope enforcement", () => {
234
292
  it("passes for routes without an :id param (no scope to enforce)", async () => {
235
293
  // Unscoped route — token is valid, no :id to compare against
236
294
  const app = buildApp(async (raw) =>
237
- raw === VALID_RAW_TOKEN ? { agentId: AGENT_ID } : null,
295
+ raw === VALID_RAW_TOKEN
296
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
297
+ : null,
238
298
  );
239
299
  const res = await app.request("/test", {
240
300
  headers: { Authorization: `Bearer ${VALID_RAW_TOKEN}` },
@@ -372,7 +432,9 @@ describe("createAdminAuthMiddleware — admin API keys", () => {
372
432
  let validateCalled = false;
373
433
  const app = buildApp(async (raw) => {
374
434
  validateCalled = true;
375
- return raw === VALID_RAW_TOKEN ? { agentId: AGENT_ID } : null;
435
+ return raw === VALID_RAW_TOKEN
436
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
437
+ : null;
376
438
  });
377
439
 
378
440
  const res = await app.request("/test", {
@@ -416,7 +478,9 @@ describe("createAdminAuthMiddleware — shared Caller", () => {
416
478
 
417
479
  it("sets caller = {name: agentId, scope: agentId} for a DB agent token", async () => {
418
480
  const app = buildApp(async (raw) =>
419
- raw === VALID_RAW_TOKEN ? { agentId: AGENT_ID } : null,
481
+ raw === VALID_RAW_TOKEN
482
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
483
+ : null,
420
484
  );
421
485
 
422
486
  const res = await app.request("/test", {
@@ -893,7 +957,9 @@ describe("createAdminAuthMiddleware — agent cross routes", () => {
893
957
  sessionSecret: SESSION_SECRET,
894
958
  agentTokenService: {
895
959
  validate: async (raw) =>
896
- raw === VALID_RAW_TOKEN ? { agentId: AGENT_ID } : null,
960
+ raw === VALID_RAW_TOKEN
961
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
962
+ : null,
897
963
  },
898
964
  adminApiKeys: new Map([
899
965
  [SCOPED_TOKEN, { name: "svc", scope: AGENT_ID }],
@@ -911,9 +977,13 @@ describe("createAdminAuthMiddleware — agent cross routes", () => {
911
977
  ]);
912
978
  });
913
979
 
914
- for (const [label, token] of [
915
- ["env-scoped key", SCOPED_TOKEN],
916
- ["DB token", VALID_RAW_TOKEN],
980
+ for (const [label, token, expectedScope] of [
981
+ ["env-scoped key", SCOPED_TOKEN, { kind: "agent", agentId: AGENT_ID }],
982
+ [
983
+ "DB token",
984
+ VALID_RAW_TOKEN,
985
+ { kind: "agent", agentId: AGENT_ID, tokenKind: "runtime" },
986
+ ],
917
987
  ] as const) {
918
988
  it(`${label} may POST another agent's /ask (handler binds from)`, async () => {
919
989
  const res = await crossApp().request("/agents/other-agent/ask", {
@@ -922,7 +992,7 @@ describe("createAdminAuthMiddleware — agent cross routes", () => {
922
992
  });
923
993
  expect(res.status).toBe(200);
924
994
  expect(await res.json()).toEqual({
925
- scope: { kind: "agent", agentId: AGENT_ID },
995
+ scope: expectedScope,
926
996
  });
927
997
  });
928
998
 
@@ -1036,6 +1036,7 @@ function buildCombinedApp() {
1036
1036
  id: "tok1",
1037
1037
  agentId: COMBINED_AGENT_ID,
1038
1038
  token: "hash",
1039
+ kind: "runtime" as const,
1039
1040
  label: null,
1040
1041
  createdAt: new Date(),
1041
1042
  revokedAt: null,
@@ -1047,6 +1048,7 @@ function buildCombinedApp() {
1047
1048
  id: "tok1",
1048
1049
  agentId: COMBINED_AGENT_ID,
1049
1050
  token: "hash",
1051
+ kind: "runtime" as const,
1050
1052
  label: null,
1051
1053
  createdAt: new Date(),
1052
1054
  revokedAt: new Date(),
@@ -210,6 +210,7 @@ const MOCK_TOKEN = {
210
210
  id: "token-1",
211
211
  agentId: AGENT_ID,
212
212
  token: "hashed",
213
+ kind: "runtime" as const,
213
214
  label: "CI",
214
215
  createdAt: new Date("2024-01-01"),
215
216
  revokedAt: null,
@@ -686,11 +686,19 @@ export const PatchAgentToolBodySchema = z
686
686
  /**
687
687
  * Token metadata returned from list/create (never the hash).
688
688
  */
689
+ export const AgentTokenKindSchema = z
690
+ .enum(["runtime", "tools"])
691
+ .openapi("AgentTokenKind", {
692
+ description:
693
+ "What the token is for: `runtime` (the agent process) or `tools` (the model's own process).",
694
+ });
695
+
689
696
  export const AgentTokenSchema = z
690
697
  .object({
691
698
  id: z.string().openapi({ example: "clx1234567890" }),
692
699
  agentId: z.string().openapi({ example: "clx1234567890" }),
693
700
  label: z.string().nullable().optional().openapi({ example: "ci-runner" }),
701
+ kind: AgentTokenKindSchema,
694
702
  createdAt: z
695
703
  .string()
696
704
  .datetime()
@@ -721,6 +729,9 @@ export const CreateAgentTokenResponseSchema = z
721
729
  export const CreateAgentTokenBodySchema = z
722
730
  .object({
723
731
  label: z.string().optional().openapi({ example: "ci-runner" }),
732
+ kind: AgentTokenKindSchema.optional().openapi({
733
+ description: "Token kind; defaults to `runtime`.",
734
+ }),
724
735
  })
725
736
  .openapi("CreateAgentTokenBody");
726
737
 
@@ -58,6 +58,7 @@ const validToken = {
58
58
  id: "cuid4",
59
59
  agentId: "cuid1",
60
60
  label: "ci-token",
61
+ kind: "runtime" as const,
61
62
  createdAt: now,
62
63
  revokedAt: null,
63
64
  };