@app-vitals/agent-admin 1.115.1 → 1.116.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.
@@ -13,8 +13,35 @@ import { UnprocessableEntityError } from "./errors.ts";
13
13
 
14
14
  export type { AgentToken };
15
15
 
16
+ /**
17
+ * What an agent API token is for: `runtime` (the agent process) or `tools`
18
+ * (the model's own process). Stored as a TEXT column (with a DB CHECK), so the
19
+ * allowed values live here and are validated in code.
20
+ */
21
+ export const AGENT_TOKEN_KINDS = ["runtime", "tools"] as const;
22
+ export type AgentTokenKind = (typeof AGENT_TOKEN_KINDS)[number];
23
+
24
+ export function isAgentTokenKind(value: unknown): value is AgentTokenKind {
25
+ return (
26
+ typeof value === "string" &&
27
+ (AGENT_TOKEN_KINDS as readonly string[]).includes(value)
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Narrow a stored kind for display/API output. The DB CHECK constraint makes
33
+ * an unknown value unreachable; if one ever appears it is reported as
34
+ * `runtime` (the column default). Auth never uses this: validate() rejects
35
+ * unknown kinds instead.
36
+ */
37
+ export function agentTokenKindOf(value: string): AgentTokenKind {
38
+ return isAgentTokenKind(value) ? value : "runtime";
39
+ }
40
+
16
41
  export interface AgentTokenValidated {
17
42
  agentId: string;
43
+ /** Optional so exported-type consumers that stub validate() keep compiling. */
44
+ kind?: AgentTokenKind;
18
45
  }
19
46
 
20
47
  function hashToken(raw: string): string {
@@ -34,12 +61,17 @@ export class AgentTokenService {
34
61
  /**
35
62
  * Create a new token for an agent.
36
63
  * Returns the token record plus the raw token — only opportunity to read it.
37
- * Throws UnprocessableEntityError if agentId doesn't reference an existing Agent.
64
+ * Throws UnprocessableEntityError if agentId doesn't reference an existing
65
+ * Agent or kind is not a known AgentTokenKind.
38
66
  */
39
67
  async create(
40
68
  agentId: string,
41
69
  label?: string,
70
+ kind: AgentTokenKind = "runtime",
42
71
  ): Promise<{ token: AgentToken; rawToken: string }> {
72
+ if (!isAgentTokenKind(kind)) {
73
+ throw new UnprocessableEntityError("kind must be runtime or tools");
74
+ }
43
75
  const agent = await this.prisma.agent.findUnique({
44
76
  where: { id: agentId },
45
77
  });
@@ -51,15 +83,16 @@ export class AgentTokenService {
51
83
  const hashed = hashToken(rawToken);
52
84
 
53
85
  const token = await this.prisma.agentToken.create({
54
- data: { agentId, token: hashed, label },
86
+ data: { agentId, token: hashed, label, kind },
55
87
  });
56
88
 
57
89
  return { token, rawToken };
58
90
  }
59
91
 
60
92
  /**
61
- * Validate a raw token. Returns { agentId } if valid and not revoked,
62
- * or null if the token is unknown or revoked.
93
+ * Validate a raw token. Returns { agentId, kind } if valid and not revoked,
94
+ * or null if the token is unknown, revoked, or carries an unrecognized kind
95
+ * (fails closed rather than guessing a capability).
63
96
  */
64
97
  async validate(raw: string): Promise<AgentTokenValidated | null> {
65
98
  const hashed = hashToken(raw);
@@ -67,7 +100,8 @@ export class AgentTokenService {
67
100
  where: { token: hashed },
68
101
  });
69
102
  if (!record || record.revokedAt !== null) return null;
70
- return { agentId: record.agentId };
103
+ if (!isAgentTokenKind(record.kind)) return null;
104
+ return { agentId: record.agentId, kind: record.kind };
71
105
  }
72
106
 
73
107
  /**
@@ -0,0 +1,127 @@
1
+ /**
2
+ * admin/src/agent-tokens.unit.test.ts
3
+ * Unit tests for AgentTokenService kind handling (runtime | tools) against a
4
+ * minimal in-memory Prisma stand-in.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import type { PrismaClient } from "../prisma/client/client.ts";
9
+ import {
10
+ type AgentTokenKind,
11
+ AgentTokenService,
12
+ agentTokenKindOf,
13
+ isAgentTokenKind,
14
+ } from "./agent-tokens.ts";
15
+
16
+ interface Row {
17
+ id: string;
18
+ agentId: string;
19
+ token: string;
20
+ label: string | null;
21
+ kind: string;
22
+ createdAt: Date;
23
+ revokedAt: Date | null;
24
+ }
25
+
26
+ function makeService() {
27
+ const rows: Row[] = [];
28
+ const prisma = {
29
+ agent: { findUnique: async () => ({ id: "agent-1" }) },
30
+ agentToken: {
31
+ create: async ({
32
+ data,
33
+ }: {
34
+ data: {
35
+ agentId: string;
36
+ token: string;
37
+ label?: string;
38
+ kind?: string;
39
+ };
40
+ }) => {
41
+ const row: Row = {
42
+ id: `t${rows.length + 1}`,
43
+ agentId: data.agentId,
44
+ token: data.token,
45
+ label: data.label ?? null,
46
+ // Mirrors the column default when kind is omitted.
47
+ kind: data.kind ?? "runtime",
48
+ createdAt: new Date(),
49
+ revokedAt: null,
50
+ };
51
+ rows.push(row);
52
+ return row;
53
+ },
54
+ findUnique: async ({ where }: { where: { token: string } }) =>
55
+ rows.find((r) => r.token === where.token) ?? null,
56
+ },
57
+ } as unknown as PrismaClient;
58
+ return { service: new AgentTokenService(prisma), rows };
59
+ }
60
+
61
+ describe("AgentTokenService kind", () => {
62
+ it("create() defaults to the runtime kind", async () => {
63
+ const { service } = makeService();
64
+ const { token } = await service.create("agent-1", "label");
65
+ expect(token.kind).toBe("runtime");
66
+ });
67
+
68
+ it("create() stores an explicit tools kind", async () => {
69
+ const { service } = makeService();
70
+ const { token } = await service.create("agent-1", undefined, "tools");
71
+ expect(token.kind).toBe("tools");
72
+ });
73
+
74
+ it("validate() returns the runtime kind for a default token", async () => {
75
+ const { service } = makeService();
76
+ const { rawToken } = await service.create("agent-1");
77
+ expect(await service.validate(rawToken)).toEqual({
78
+ agentId: "agent-1",
79
+ kind: "runtime",
80
+ });
81
+ });
82
+
83
+ it("validate() returns the tools kind for a tools token", async () => {
84
+ const { service } = makeService();
85
+ const { rawToken } = await service.create("agent-1", "t", "tools");
86
+ expect(await service.validate(rawToken)).toEqual({
87
+ agentId: "agent-1",
88
+ kind: "tools",
89
+ });
90
+ });
91
+
92
+ it("validate() returns null for an unknown token", async () => {
93
+ const { service } = makeService();
94
+ expect(await service.validate("nope")).toBeNull();
95
+ });
96
+
97
+ it("create() rejects an unknown kind before writing a row", async () => {
98
+ const { service, rows } = makeService();
99
+ await expect(
100
+ service.create("agent-1", "x", "admin" as AgentTokenKind),
101
+ ).rejects.toThrow("kind must be runtime or tools");
102
+ expect(rows).toHaveLength(0);
103
+ });
104
+
105
+ it("validate() fails closed on a stored kind it does not recognize", async () => {
106
+ const { service, rows } = makeService();
107
+ const { rawToken } = await service.create("agent-1");
108
+ (rows[0] as Row).kind = "admin";
109
+ expect(await service.validate(rawToken)).toBeNull();
110
+ });
111
+ });
112
+
113
+ describe("AgentTokenKind helpers", () => {
114
+ it("isAgentTokenKind() accepts only runtime and tools", () => {
115
+ expect(isAgentTokenKind("runtime")).toBe(true);
116
+ expect(isAgentTokenKind("tools")).toBe(true);
117
+ expect(isAgentTokenKind("admin")).toBe(false);
118
+ expect(isAgentTokenKind("")).toBe(false);
119
+ expect(isAgentTokenKind(undefined)).toBe(false);
120
+ });
121
+
122
+ it("agentTokenKindOf() keeps known kinds and reports unknown as runtime", () => {
123
+ expect(agentTokenKindOf("tools")).toBe("tools");
124
+ expect(agentTokenKindOf("runtime")).toBe("runtime");
125
+ expect(agentTokenKindOf("bogus")).toBe("runtime");
126
+ });
127
+ });
@@ -232,7 +232,9 @@ function makeBaseDeps(
232
232
  listForAgent: async () => [],
233
233
  revoke: async () => ({}) as never,
234
234
  validate: async (raw: string) =>
235
- raw === VALID_BEARER_TOKEN ? { agentId: AGENT_ID } : null,
235
+ raw === VALID_BEARER_TOKEN
236
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
237
+ : null,
236
238
  },
237
239
  agentPluginService: {
238
240
  list: async () => [],
@@ -517,6 +517,7 @@ function makeMockDeps(): AdminDeps {
517
517
  id: TOKEN_ID,
518
518
  agentId: AGENT_ID,
519
519
  token: "sha256hash",
520
+ kind: "runtime" as const,
520
521
  label: "test token",
521
522
  createdAt: new Date("2024-01-01"),
522
523
  revokedAt: null,
@@ -529,6 +530,7 @@ function makeMockDeps(): AdminDeps {
529
530
  id: TOKEN_ID,
530
531
  agentId: AGENT_ID,
531
532
  token: "sha256hashvalue",
533
+ kind: "runtime" as const,
532
534
  label: "test token",
533
535
  createdAt: new Date("2024-01-01"),
534
536
  revokedAt: null,
@@ -538,11 +540,12 @@ function makeMockDeps(): AdminDeps {
538
540
  id: TOKEN_ID,
539
541
  agentId: AGENT_ID,
540
542
  token: "sha256hashvalue",
543
+ kind: "runtime" as const,
541
544
  label: "test token",
542
545
  createdAt: new Date("2024-01-01"),
543
546
  revokedAt: new Date("2024-01-02"),
544
547
  }),
545
- validate: async () => ({ agentId: AGENT_ID }),
548
+ validate: async () => ({ agentId: AGENT_ID, kind: "runtime" as const }),
546
549
  },
547
550
  agentPluginService: {
548
551
  list: async () => [
@@ -1392,7 +1395,10 @@ describe("admin API — GitHub installations snapshot", () => {
1392
1395
 
1393
1396
  it("the agent's own bearer token is accepted (200)", async () => {
1394
1397
  const app = createAdminApp(
1395
- makeDepsWithTokenValidation(async () => ({ agentId: AGENT_ID })),
1398
+ makeDepsWithTokenValidation(async () => ({
1399
+ agentId: AGENT_ID,
1400
+ kind: "runtime" as const,
1401
+ })),
1396
1402
  );
1397
1403
  const res = await put(app, BODY, {
1398
1404
  Cookie: "",
@@ -1403,7 +1409,10 @@ describe("admin API — GitHub installations snapshot", () => {
1403
1409
 
1404
1410
  it("a bearer token owned by a different agent is rejected (403)", async () => {
1405
1411
  const app = createAdminApp(
1406
- makeDepsWithTokenValidation(async () => ({ agentId: "other-agent" })),
1412
+ makeDepsWithTokenValidation(async () => ({
1413
+ agentId: "other-agent",
1414
+ kind: "runtime" as const,
1415
+ })),
1407
1416
  );
1408
1417
  const putRes = await put(app, BODY, {
1409
1418
  Cookie: "",
@@ -1512,6 +1521,78 @@ describe("admin API — tokens", () => {
1512
1521
  expect(body.token).toBeDefined();
1513
1522
  });
1514
1523
 
1524
+ it("POST /agents/:id/tokens with kind tools: list shows the kind", async () => {
1525
+ type Row = {
1526
+ id: string;
1527
+ agentId: string;
1528
+ token: string;
1529
+ label: string | null;
1530
+ kind: "runtime" | "tools";
1531
+ createdAt: Date;
1532
+ revokedAt: Date | null;
1533
+ };
1534
+ const rows: Row[] = [];
1535
+ const base = makeMockDeps();
1536
+ const deps: AdminDeps = {
1537
+ ...base,
1538
+ agentTokenService: {
1539
+ ...base.agentTokenService,
1540
+ create: async (agentId, label, kind = "runtime") => {
1541
+ const token: Row = {
1542
+ id: `tok-${rows.length + 1}`,
1543
+ agentId,
1544
+ token: "hash",
1545
+ label: label ?? null,
1546
+ kind,
1547
+ createdAt: new Date("2024-01-01"),
1548
+ revokedAt: null,
1549
+ };
1550
+ rows.push(token);
1551
+ return { token, rawToken: "raw" };
1552
+ },
1553
+ listForAgent: async () => rows,
1554
+ },
1555
+ };
1556
+ const app = createAdminApp(deps);
1557
+ const headers = {
1558
+ "Content-Type": "application/json",
1559
+ Cookie: `admin_session=${cookie}`,
1560
+ };
1561
+ const created = await app.request(`/agents/${AGENT_ID}/tokens`, {
1562
+ method: "POST",
1563
+ body: JSON.stringify({ label: "tools", kind: "tools" }),
1564
+ headers,
1565
+ });
1566
+ expect(created.status).toBe(201);
1567
+ expect((await created.json()).token.kind).toBe("tools");
1568
+ // Omitted kind defaults to runtime.
1569
+ await app.request(`/agents/${AGENT_ID}/tokens`, {
1570
+ method: "POST",
1571
+ body: JSON.stringify({ label: "default" }),
1572
+ headers,
1573
+ });
1574
+ const list = await app.request(`/agents/${AGENT_ID}/tokens`, { headers });
1575
+ expect(list.status).toBe(200);
1576
+ const { tokens } = await list.json();
1577
+ expect(tokens.map((t: { kind: string }) => t.kind)).toEqual([
1578
+ "tools",
1579
+ "runtime",
1580
+ ]);
1581
+ });
1582
+
1583
+ it("POST /agents/:id/tokens rejects an invalid kind with 400", async () => {
1584
+ const app = createAdminApp(makeMockDeps());
1585
+ const res = await app.request(`/agents/${AGENT_ID}/tokens`, {
1586
+ method: "POST",
1587
+ body: JSON.stringify({ kind: "admin" }),
1588
+ headers: {
1589
+ "Content-Type": "application/json",
1590
+ Cookie: `admin_session=${cookie}`,
1591
+ },
1592
+ });
1593
+ expect(res.status).toBe(400);
1594
+ });
1595
+
1515
1596
  it("GET /agents/:id/tokens returns list WITHOUT rawToken", async () => {
1516
1597
  const app = createAdminApp(makeMockDeps());
1517
1598
  const res = await app.request(`/agents/${AGENT_ID}/tokens`, {
@@ -1862,7 +1943,7 @@ describe("admin API — POST /agents", () => {
1862
1943
  ...makeMockDeps(),
1863
1944
  agentTokenService: {
1864
1945
  ...makeMockDeps().agentTokenService,
1865
- validate: async () => ({ agentId: AGENT_ID }),
1946
+ validate: async () => ({ agentId: AGENT_ID, kind: "runtime" as const }),
1866
1947
  },
1867
1948
  };
1868
1949
  const app = createAdminApp(deps);
@@ -2292,7 +2373,10 @@ describe("admin API — delete agent", () => {
2292
2373
  it("DELETE /agents/:id with per-agent bearer → 403", async () => {
2293
2374
  const provisioner = new RecordingProvisioner();
2294
2375
  const deps: AdminDeps = {
2295
- ...makeDepsWithTokenValidation(async () => ({ agentId: AGENT_ID })),
2376
+ ...makeDepsWithTokenValidation(async () => ({
2377
+ agentId: AGENT_ID,
2378
+ kind: "runtime" as const,
2379
+ })),
2296
2380
  provisioner,
2297
2381
  };
2298
2382
  const app = createAdminApp(deps);
@@ -2317,6 +2401,7 @@ describe("admin API — POST /agents/reconcile", () => {
2317
2401
  it("POST /agents/reconcile with per-agent bearer → 403", async () => {
2318
2402
  const deps = makeDepsWithTokenValidation(async () => ({
2319
2403
  agentId: AGENT_ID,
2404
+ kind: "runtime" as const,
2320
2405
  }));
2321
2406
  const app = createAdminApp(deps);
2322
2407
  const res = await app.request("/agents/reconcile", {
@@ -2548,7 +2633,10 @@ describe("admin API — POST /agents/federation/strip-credentials", () => {
2548
2633
  ...deps,
2549
2634
  agentTokenService: {
2550
2635
  ...deps.agentTokenService,
2551
- validate: async () => ({ agentId: "managed-a" }),
2636
+ validate: async () => ({
2637
+ agentId: "managed-a",
2638
+ kind: "runtime" as const,
2639
+ }),
2552
2640
  },
2553
2641
  });
2554
2642
  const res = await app.request(
@@ -2570,7 +2658,10 @@ describe("admin API — POST /agents/federation/strip-credentials", () => {
2570
2658
  ...deps,
2571
2659
  agentTokenService: {
2572
2660
  ...deps.agentTokenService,
2573
- validate: async () => ({ agentId: "federation" }),
2661
+ validate: async () => ({
2662
+ agentId: "federation",
2663
+ kind: "runtime" as const,
2664
+ }),
2574
2665
  },
2575
2666
  });
2576
2667
  const res = await app.request(
@@ -2658,6 +2749,7 @@ describe("admin API — bearer token auth", () => {
2658
2749
  it("GET /agents/:id/envs accepts a valid bearer token (200)", async () => {
2659
2750
  const deps = makeDepsWithTokenValidation(async () => ({
2660
2751
  agentId: AGENT_ID,
2752
+ kind: "runtime" as const,
2661
2753
  }));
2662
2754
  const app = createAdminApp(deps);
2663
2755
  const res = await app.request(`/agents/${AGENT_ID}/envs`, {
@@ -2669,6 +2761,7 @@ describe("admin API — bearer token auth", () => {
2669
2761
  it("GET /agents/:id/tools accepts a valid bearer token (200)", async () => {
2670
2762
  const deps = makeDepsWithTokenValidation(async () => ({
2671
2763
  agentId: AGENT_ID,
2764
+ kind: "runtime" as const,
2672
2765
  }));
2673
2766
  const app = createAdminApp(deps);
2674
2767
  const res = await app.request(`/agents/${AGENT_ID}/tools`, {
@@ -2747,7 +2840,10 @@ describe("admin API — provision agent", () => {
2747
2840
  it("POST /agents/:id/provision with per-agent bearer → 403 (no provision call)", async () => {
2748
2841
  const provisioner = new RecordingProvisioner();
2749
2842
  const deps: AdminDeps = {
2750
- ...makeDepsWithTokenValidation(async () => ({ agentId: AGENT_ID })),
2843
+ ...makeDepsWithTokenValidation(async () => ({
2844
+ agentId: AGENT_ID,
2845
+ kind: "runtime" as const,
2846
+ })),
2751
2847
  provisioner,
2752
2848
  };
2753
2849
  const app = createAdminApp(deps);
@@ -7028,6 +7124,7 @@ describe("admin API — baked marketplaces report", () => {
7028
7124
  let baked: string[] = [];
7029
7125
  const base = makeDepsWithTokenValidation(async () => ({
7030
7126
  agentId: tokenAgentId,
7127
+ kind: "runtime" as const,
7031
7128
  }));
7032
7129
  const deps: AdminDeps = {
7033
7130
  ...base,
@@ -7144,7 +7241,9 @@ describe("admin API — PATCH /agents/:id githubUsername (GHE-2.1)", () => {
7144
7241
  agentTokenService: {
7145
7242
  ...base.agentTokenService,
7146
7243
  validate: async (t: string) =>
7147
- t === AGENT_KEY ? { agentId: AGENT_ID } : null,
7244
+ t === AGENT_KEY
7245
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
7246
+ : null,
7148
7247
  },
7149
7248
  agentService: {
7150
7249
  ...base.agentService,
@@ -7535,7 +7634,9 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
7535
7634
  agentTokenService: {
7536
7635
  ...base.agentTokenService,
7537
7636
  validate: async (t: string) =>
7538
- t === AGENT_KEY ? { agentId: AGENT_ID } : null,
7637
+ t === AGENT_KEY
7638
+ ? { agentId: AGENT_ID, kind: "runtime" as const }
7639
+ : null,
7539
7640
  },
7540
7641
  githubInstallationRepos,
7541
7642
  githubSync,
package/src/agents-api.ts CHANGED
@@ -70,7 +70,7 @@ 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
75
  import type { AgentService } from "./agents.ts";
76
76
  import {
@@ -3096,6 +3096,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3096
3096
  const { token, rawToken } = await agentTokenService.create(
3097
3097
  agentId,
3098
3098
  body?.label,
3099
+ body?.kind,
3099
3100
  );
3100
3101
  // Return the token record (without the hashed token value) + rawToken
3101
3102
  const { token: _hash, ...tokenMeta } = token;
@@ -3103,6 +3104,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3103
3104
  {
3104
3105
  token: {
3105
3106
  ...tokenMeta,
3107
+ kind: agentTokenKindOf(tokenMeta.kind),
3106
3108
  createdAt: tokenMeta.createdAt.toISOString(),
3107
3109
  revokedAt: tokenMeta.revokedAt
3108
3110
  ? tokenMeta.revokedAt.toISOString()
@@ -3121,6 +3123,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3121
3123
  // Never expose the stored hash — return only metadata
3122
3124
  const tokens = records.map(({ token: _hash, ...meta }) => ({
3123
3125
  ...meta,
3126
+ kind: agentTokenKindOf(meta.kind),
3124
3127
  createdAt: meta.createdAt.toISOString(),
3125
3128
  revokedAt: meta.revokedAt ? meta.revokedAt.toISOString() : null,
3126
3129
  }));
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