@app-vitals/agent-admin 1.107.2 → 1.107.4

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.
Files changed (59) hide show
  1. package/e2e/real/agent-management.real.e2e.ts +195 -0
  2. package/e2e/real/seed.ts +0 -1
  3. package/package.json +2 -2
  4. package/prisma/client/internal/class.ts +4 -4
  5. package/prisma/client/internal/prismaNamespace.ts +1 -5
  6. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -5
  7. package/prisma/client/models/AgentMember.ts +26 -61
  8. package/prisma/client/models/ChatThreadWatch.ts +19 -47
  9. package/prisma/client/models/PushSubscription.ts +15 -43
  10. package/prisma/client/models/UserNotificationPrefs.ts +38 -66
  11. package/prisma/migrations/20261130000000_drop_email_key_columns/migration.sql +49 -0
  12. package/prisma/schema/schema.prisma +11 -15
  13. package/src/account-member-removal.integration.test.ts +31 -44
  14. package/src/account-members.ts +4 -6
  15. package/src/account-onboarding.ts +2 -5
  16. package/src/account-onboarding.unit.test.ts +71 -0
  17. package/src/accounts.ts +1 -3
  18. package/src/admin-dev-login.smoke.test.ts +1 -1
  19. package/src/admin-local-agent.smoke.test.ts +28 -6
  20. package/src/admin-ui-agent-members.smoke.test.ts +31 -7
  21. package/src/admin-ui-pages.ts +23 -1
  22. package/src/admin-ui-pages.unit.test.ts +17 -0
  23. package/src/admin-ui.fixtures.ts +1 -1
  24. package/src/admin-ui.smoke.test.ts +163 -100
  25. package/src/admin-ui.ts +132 -55
  26. package/src/agent-cron-run-stats.smoke.test.ts +1 -1
  27. package/src/agent-deletion.integration.test.ts +1 -1
  28. package/src/agent-management-access.integration.test.ts +269 -0
  29. package/src/agent-members.integration.test.ts +14 -10
  30. package/src/agent-members.ts +28 -18
  31. package/src/agents-api.integration.test.ts +2 -2
  32. package/src/agents-api.smoke.test.ts +68 -13
  33. package/src/agents-api.ts +2 -0
  34. package/src/agents.integration.test.ts +1 -2
  35. package/src/api-auth.ts +31 -1
  36. package/src/api-auth.unit.test.ts +106 -6
  37. package/src/api.smoke.test.ts +1 -1
  38. package/src/caller-scope.ts +21 -0
  39. package/src/caller-scope.unit.test.ts +39 -0
  40. package/src/chat.smoke.test.ts +68 -14
  41. package/src/drop-email-key-columns-migration.integration.test.ts +141 -0
  42. package/src/ensure-account-member.integration.test.ts +17 -232
  43. package/src/ensure-account-member.ts +0 -5
  44. package/src/github-enterprise-client.unit.test.ts +62 -2
  45. package/src/member-rows.ts +24 -0
  46. package/src/member-rows.unit.test.ts +48 -0
  47. package/src/principals-api.integration.test.ts +3 -2
  48. package/src/push-service.integration.test.ts +7 -12
  49. package/src/push-service.ts +28 -39
  50. package/src/push-service.unit.test.ts +8 -8
  51. package/src/slack-provisioning.integration.test.ts +1 -1
  52. package/src/user-notification-prefs.integration.test.ts +5 -16
  53. package/src/user-notification-prefs.ts +12 -18
  54. package/scripts/backfill-member-id.ts +0 -50
  55. package/src/member-id-backfill.integration.test.ts +0 -167
  56. package/src/member-id-backfill.ts +0 -253
  57. package/src/member-id-backfill.unit.test.ts +0 -12
  58. package/src/member-id-stamp.ts +0 -68
  59. package/src/member-id-stamp.unit.test.ts +0 -81
@@ -0,0 +1,269 @@
1
+ /**
2
+ * admin/src/agent-management-access.integration.test.ts
3
+ * Agent management (JSON API) against a real PostgreSQL DB with self-serve on:
4
+ * only platform admins and the owner of the agent's own account may manage an
5
+ * agent; a member of the agent (or of its account) and an owner of another
6
+ * account get 403, while read access is unchanged.
7
+ *
8
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
9
+ */
10
+
11
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
12
+ import { sign } from "hono/jwt";
13
+ import type { PrismaClient } from "../prisma/client/client.ts";
14
+ import { AccountService } from "./accounts.ts";
15
+ import { AgentChatTokenService } from "./agent-chat-tokens.ts";
16
+ import { AgentCronJobService } from "./agent-cron-jobs.ts";
17
+ import { AgentCronRunStatsService } from "./agent-cron-run-stats.ts";
18
+ import { AgentCronRunService } from "./agent-cron-runs.ts";
19
+ import { AgentEnvService } from "./agent-envs.ts";
20
+ import { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
21
+ import { AgentMemberService } from "./agent-members.ts";
22
+ import { AgentPluginService } from "./agent-plugins.ts";
23
+ import type { AgentProvisioner } from "./agent-provisioner.ts";
24
+ import { NoopAgentProvisioner } from "./agent-provisioner.ts";
25
+ import { AgentTokenService } from "./agent-tokens.ts";
26
+ import { AgentToolService } from "./agent-tools.ts";
27
+ import { AgentService } from "./agents.ts";
28
+ import type { AdminDeps } from "./agents-api.ts";
29
+ import { createAdminApp } from "./agents-api.ts";
30
+ import {
31
+ callerScopeDepsFromServices,
32
+ createCallerScopeResolver,
33
+ } from "./caller-scope.ts";
34
+ import { NoopChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
35
+ import { createAdminPrismaClient } from "./prisma-client.ts";
36
+ import type {
37
+ SpecialtyType,
38
+ SpecialtyTypeResolver,
39
+ } from "./specialty-types.ts";
40
+ import { makeTokenCrypto } from "./token-crypto.ts";
41
+
42
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
43
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
44
+
45
+ const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
46
+ const REAL_KEY =
47
+ "0000000000000000000000000000000000000000000000000000000000000001";
48
+
49
+ /** A minimal valid "coding" manifest used to drive seeding assertions below. */
50
+ const CODING_TYPE: SpecialtyType = {
51
+ name: "coding",
52
+ displayName: "Coding Agent",
53
+ templatesDir: "workspace/",
54
+ tools: [
55
+ "Read",
56
+ "Write",
57
+ "Edit",
58
+ "Glob",
59
+ "Grep",
60
+ "Bash",
61
+ "WebSearch",
62
+ "WebFetch",
63
+ "Skill",
64
+ "Agent",
65
+ ],
66
+ requiredEnv: [],
67
+ };
68
+
69
+ function fakeSpecialtyTypes(
70
+ byType: Record<string, SpecialtyType> = { coding: CODING_TYPE },
71
+ ): SpecialtyTypeResolver {
72
+ return {
73
+ getType(specialty: string): SpecialtyType {
74
+ return byType[specialty] ?? (byType.coding as SpecialtyType);
75
+ },
76
+ tryGetType(specialty: string): SpecialtyType | undefined {
77
+ return byType[specialty];
78
+ },
79
+ listTypes() {
80
+ return Object.entries(byType).map(([name, manifest]) => ({
81
+ name,
82
+ displayName: manifest.displayName,
83
+ }));
84
+ },
85
+ };
86
+ }
87
+
88
+ function makeDeps(
89
+ prisma: PrismaClient,
90
+ provisioner: AgentProvisioner = new NoopAgentProvisioner(),
91
+ specialtyRegistry: SpecialtyTypeResolver = fakeSpecialtyTypes(),
92
+ ): AdminDeps {
93
+ const savedKey = process.env.SHIPWRIGHT_ENCRYPTION_KEY;
94
+ process.env.SHIPWRIGHT_ENCRYPTION_KEY = REAL_KEY;
95
+ const crypto = makeTokenCrypto();
96
+ if (savedKey === undefined) {
97
+ delete process.env.SHIPWRIGHT_ENCRYPTION_KEY;
98
+ } else {
99
+ process.env.SHIPWRIGHT_ENCRYPTION_KEY = savedKey;
100
+ }
101
+
102
+ return {
103
+ agentService: new AgentService(prisma),
104
+ agentEnvService: new AgentEnvService(prisma, crypto),
105
+ agentCronJobService: new AgentCronJobService(prisma),
106
+ agentCronRunService: new AgentCronRunService(prisma),
107
+ agentCronRunStatsService: new AgentCronRunStatsService(prisma),
108
+ agentToolService: new AgentToolService(prisma),
109
+ agentTokenService: new AgentTokenService(prisma),
110
+ agentPluginService: new AgentPluginService(prisma),
111
+ agentMemberService: new AgentMemberService(prisma),
112
+ specialtyRegistry,
113
+ agentChatTokenService: new AgentChatTokenService(prisma),
114
+ agentGitHubInstallationsService: new AgentGitHubInstallationsService(
115
+ prisma,
116
+ ),
117
+ prisma,
118
+ provisioner,
119
+ serviceIntegrations: [
120
+ {
121
+ name: "task-store",
122
+ listTokensForAgent: async () => [],
123
+ revokeToken: async () => {},
124
+ },
125
+ ],
126
+ chatService: new NoopChatServiceProvisioningClient(),
127
+ slack: {
128
+ deleteApp: async () => {},
129
+ },
130
+ decrypt: (value: string) => crypto.decrypt(value),
131
+ sessionSecret: SESSION_SECRET,
132
+ };
133
+ }
134
+
135
+ const cookieFor = (email: string, isAdmin: boolean) =>
136
+ sign(
137
+ {
138
+ isAdmin,
139
+ userId: `user-${email}`,
140
+ email,
141
+ iat: Math.floor(Date.now() / 1000),
142
+ exp: Math.floor(Date.now() / 1000) + 3600,
143
+ },
144
+ SESSION_SECRET,
145
+ "HS256",
146
+ );
147
+
148
+ describeOrSkip("agent management access (integration)", () => {
149
+ let prisma: PrismaClient;
150
+ let app: ReturnType<typeof createAdminApp>;
151
+ let agentId: string;
152
+
153
+ const call = async (
154
+ email: string,
155
+ isAdmin: boolean,
156
+ method: string,
157
+ path: string,
158
+ body?: unknown,
159
+ ) =>
160
+ app.request(`/agents/${agentId}${path}`, {
161
+ method,
162
+ body: JSON.stringify(body ?? {}),
163
+ headers: {
164
+ "Content-Type": "application/json",
165
+ Cookie: `admin_session=${await cookieFor(email, isAdmin)}`,
166
+ },
167
+ });
168
+
169
+ beforeEach(async () => {
170
+ prisma = createAdminPrismaClient(TEST_DB as string);
171
+ await prisma.agentWorkQueueSnapshot.deleteMany();
172
+ await prisma.agentPlugin.deleteMany();
173
+ await prisma.agentPhaseMethodology.deleteMany();
174
+ await prisma.agentToken.deleteMany();
175
+ await prisma.agentCronJob.deleteMany();
176
+ await prisma.agentTool.deleteMany();
177
+ await prisma.agentEnv.deleteMany();
178
+ await prisma.agentMember.deleteMany();
179
+ await prisma.agent.deleteMany();
180
+ await prisma.accountMember.deleteMany();
181
+ await prisma.account.deleteMany();
182
+
183
+ const one = await prisma.account.create({ data: { name: "Account One" } });
184
+ const two = await prisma.account.create({ data: { name: "Account Two" } });
185
+ const mk = (accountId: string, email: string, role: string) =>
186
+ prisma.accountMember.create({ data: { accountId, email, role } });
187
+ await mk(one.id, "owner-one@example.com", "owner");
188
+ const member = await mk(one.id, "member-one@example.com", "member");
189
+ await mk(two.id, "owner-two@example.com", "owner");
190
+ agentId = (
191
+ await prisma.agent.create({
192
+ data: { name: "Test Agent", accountId: one.id },
193
+ })
194
+ ).id;
195
+ await prisma.agentMember.create({
196
+ data: { agentId, memberId: member.id },
197
+ });
198
+
199
+ const deps = makeDeps(prisma);
200
+ app = createAdminApp({
201
+ ...deps,
202
+ callerScopeResolver: createCallerScopeResolver(
203
+ callerScopeDepsFromServices({
204
+ accountService: new AccountService(prisma),
205
+ agentMemberService: new AgentMemberService(prisma),
206
+ }),
207
+ true,
208
+ ),
209
+ });
210
+ });
211
+
212
+ afterEach(async () => {
213
+ await prisma.$disconnect();
214
+ });
215
+
216
+ const writes = (): Array<[string, string, unknown?]> => [
217
+ ["PATCH", "", { cleanupAfterDays: 20 }],
218
+ ["POST", "/envs", { key: "K", value: "V" }],
219
+ ["POST", "/tokens", { label: "l" }],
220
+ ["DELETE", ""],
221
+ ];
222
+
223
+ it("member of the agent: reads and asks stay open, every management route is 403", async () => {
224
+ const email = "member-one@example.com";
225
+ expect((await call(email, false, "GET", "")).status).toBe(200);
226
+ expect((await call(email, false, "GET", "/envs")).status).toBe(200);
227
+ for (const [method, path, body] of writes()) {
228
+ const res = await call(email, false, method, path, body);
229
+ expect([method, path, res.status]).toEqual([method, path, 403]);
230
+ }
231
+ const row = await prisma.agent.findUniqueOrThrow({
232
+ where: { id: agentId },
233
+ });
234
+ expect(row.cleanupAfterDays).not.toBe(20);
235
+ expect(await prisma.agentToken.count({ where: { agentId } })).toBe(0);
236
+ });
237
+
238
+ it("owner of another account: no access at all", async () => {
239
+ const email = "owner-two@example.com";
240
+ expect((await call(email, false, "GET", "")).status).toBe(403);
241
+ for (const [method, path, body] of writes()) {
242
+ const res = await call(email, false, method, path, body);
243
+ expect([method, path, res.status]).toEqual([method, path, 403]);
244
+ }
245
+ expect(await prisma.agent.count({ where: { id: agentId } })).toBe(1);
246
+ });
247
+
248
+ it("owner of the agent's account manages it, including delete", async () => {
249
+ const email = "owner-one@example.com";
250
+ expect((await call(email, false, "GET", "")).status).toBe(200);
251
+ expect(
252
+ (await call(email, false, "PATCH", "", { cleanupAfterDays: 20 })).status,
253
+ ).toBe(200);
254
+ expect(
255
+ (await call(email, false, "POST", "/envs", { key: "K", value: "V" }))
256
+ .status,
257
+ ).toBe(201);
258
+ expect((await call(email, false, "DELETE", "")).status).toBe(200);
259
+ expect(await prisma.agent.count({ where: { id: agentId } })).toBe(0);
260
+ });
261
+
262
+ it("platform admin manages any agent", async () => {
263
+ const email = "admin@example.com";
264
+ expect(
265
+ (await call(email, true, "PATCH", "", { cleanupAfterDays: 20 })).status,
266
+ ).toBe(200);
267
+ expect((await call(email, true, "DELETE", "")).status).toBe(200);
268
+ });
269
+ });
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
- import { AgentMemberService } from "./agent-members.ts";
11
+ import { AgentMemberService, NoAccountMemberError } from "./agent-members.ts";
12
12
  import { resetMemberIdFixture } from "./test-support/member-id-test-support.ts";
13
13
  import { createAdminPrismaClient } from "./prisma-client.ts";
14
14
 
@@ -52,9 +52,11 @@ describeOrSkip("AgentMemberService by memberId (integration)", () => {
52
52
  expect(rows.map((r) => r.memberId)).toEqual([bobId]);
53
53
  });
54
54
 
55
- it("add for an email with no AccountMember stores a null memberId", async () => {
56
- const row = await service.add(agentId, "ghost@nowhere.com");
57
- expect(row.memberId).toBeNull();
55
+ it("add for an email with no AccountMember throws and writes nothing", async () => {
56
+ await expect(service.add(agentId, "ghost@nowhere.com")).rejects.toThrow(
57
+ NoAccountMemberError,
58
+ );
59
+ expect(await prisma.agentMember.count()).toBe(0);
58
60
  });
59
61
 
60
62
  it("listByEmail and listByMemberId return the member's agents", async () => {
@@ -71,10 +73,9 @@ describeOrSkip("AgentMemberService by memberId (integration)", () => {
71
73
  expect(await service.exists(agentId, "ghost@nowhere.com")).toBe(false);
72
74
  });
73
75
 
74
- it("skips null-memberId rows on every read without crashing", async () => {
75
- // Legacy row: email only, never backfilled.
76
+ it("rows whose member no longer resolves are skipped on every read", async () => {
76
77
  await prisma.agentMember.create({
77
- data: { agentId, email: "alice@acme.com" },
78
+ data: { agentId, memberId: "gone-member" },
78
79
  });
79
80
  expect(await service.listByEmail("alice@acme.com")).toEqual([]);
80
81
  expect(await service.exists(agentId, "alice@acme.com")).toBe(false);
@@ -83,10 +84,13 @@ describeOrSkip("AgentMemberService by memberId (integration)", () => {
83
84
 
84
85
  it("listByAgentId returns rows with the email resolved through the lookup", async () => {
85
86
  await service.add(agentId, "alice@acme.com");
86
- // Stored email drifted from the member's current email.
87
- await prisma.agentMember.updateMany({ data: { email: "stale@old.com" } });
87
+ // The member's email changed after the row was written.
88
+ await prisma.accountMember.update({
89
+ where: { id: aliceId },
90
+ data: { email: "alice2@acme.com" },
91
+ });
88
92
  const rows = await service.listByAgentId(agentId);
89
- expect(rows.map((r) => r.email)).toEqual(["alice@acme.com"]);
93
+ expect(rows.map((r) => r.email)).toEqual(["alice2@acme.com"]);
90
94
  });
91
95
 
92
96
  it("remove deletes by row id scoped to the agent", async () => {
@@ -2,11 +2,11 @@
2
2
  * agent/src/agent-members.ts
3
3
  * AgentMemberService — authorized human members per agent (access control).
4
4
  *
5
- * ACM-4.1: reads and writes key on AgentMember.memberId (AccountMember.id).
6
- * Callers still pass emails; they are resolved to a member id through the
7
- * AccountMember lookup, and emails handed back are resolved the same way. Rows
8
- * whose memberId is null (not yet backfilled) are skipped. The [agentId, email]
9
- * unique constraint stays in place and still guards duplicate adds.
5
+ * Reads and writes key on AgentMember.memberId (AccountMember.id); the
6
+ * [agentId, memberId] unique constraint guards duplicate adds. Callers still
7
+ * pass emails; they are resolved to a member id through the AccountMember
8
+ * lookup, and emails handed back are resolved the same way (ACM-5.1 dropped the
9
+ * email column).
10
10
  */
11
11
 
12
12
  import type { AgentMember, PrismaClient } from "../prisma/client/client.ts";
@@ -16,6 +16,17 @@ import type { PrismaTransactionClient } from "./prisma-tx.ts";
16
16
 
17
17
  export type { AgentMember };
18
18
 
19
+ /** An AgentMember row plus the member's current email, resolved via the lookup. */
20
+ export type AgentMemberWithEmail = AgentMember & { email: string };
21
+
22
+ /** Thrown when an agent membership is requested for an email with no AccountMember. */
23
+ export class NoAccountMemberError extends Error {
24
+ constructor(readonly email: string) {
25
+ super(`No account member exists for ${email}`);
26
+ this.name = "NoAccountMemberError";
27
+ }
28
+ }
29
+
19
30
  export class AgentMemberService {
20
31
  private readonly lookup: PrincipalLookupService;
21
32
 
@@ -28,20 +39,18 @@ export class AgentMemberService {
28
39
  }
29
40
 
30
41
  /**
31
- * List all memberships for a given agent. Rows with a null memberId, or a
32
- * memberId that no longer resolves, are skipped; `email` on each returned
33
- * row is the member's current email from the lookup.
42
+ * List all memberships for a given agent. Rows whose memberId no longer
43
+ * resolves are skipped; `email` on each returned row is the member's current
44
+ * email from the lookup.
34
45
  */
35
- async listByAgentId(agentId: string): Promise<AgentMember[]> {
36
- const rows = await this.prisma.agentMember.findMany({
37
- where: { agentId, memberId: { not: null } },
38
- });
46
+ async listByAgentId(agentId: string): Promise<AgentMemberWithEmail[]> {
47
+ const rows = await this.prisma.agentMember.findMany({ where: { agentId } });
39
48
  const { principals } = await this.lookup.resolveMany(
40
- rows.flatMap((r) => (r.memberId ? [r.memberId] : [])),
49
+ rows.map((r) => r.memberId),
41
50
  );
42
51
  const emails = new Map(principals.map((p) => [p.id, p.email]));
43
52
  return rows.flatMap((r) => {
44
- const email = r.memberId ? emails.get(r.memberId) : null;
53
+ const email = emails.get(r.memberId);
45
54
  return email ? [{ ...r, email }] : [];
46
55
  });
47
56
  }
@@ -74,9 +83,9 @@ export class AgentMemberService {
74
83
  }
75
84
 
76
85
  /**
77
- * Create a membership row for the given agentId and email, stamped with the
78
- * email's AccountMember id (null when the email has no member yet — such a
79
- * row is skipped by reads until backfilled).
86
+ * Create a membership row for the given agentId and email, keyed on the
87
+ * email's AccountMember id. Throws `NoAccountMemberError` when the email has
88
+ * no AccountMember (a row cannot be written without a member id).
80
89
  * Throws (unique-constraint violation) if the membership already exists —
81
90
  * callers are expected to catch and handle "already a member" as a no-op.
82
91
  *
@@ -94,8 +103,9 @@ export class AgentMemberService {
94
103
  where: { email: normalized },
95
104
  select: { id: true },
96
105
  });
106
+ if (!member) throw new NoAccountMemberError(normalized);
97
107
  return client.agentMember.create({
98
- data: { agentId, email: normalized, memberId: member?.id ?? null },
108
+ data: { agentId, memberId: member.id },
99
109
  });
100
110
  }
101
111
 
@@ -108,7 +108,7 @@ async function seedAgentMember(
108
108
  data: { accountId: account.id, email, role: "member" },
109
109
  });
110
110
  await prisma.agentMember.create({
111
- data: { agentId, email, memberId: member.id },
111
+ data: { agentId, memberId: member.id },
112
112
  });
113
113
  }
114
114
 
@@ -372,7 +372,7 @@ describeOrSkip("admin CRUD API (integration)", () => {
372
372
  data: { agentId: preExisting.id, key: "FOO", value: "encrypted-value" },
373
373
  });
374
374
  const member = await prisma.agentMember.create({
375
- data: { agentId: preExisting.id, email: "member@example.com" },
375
+ data: { agentId: preExisting.id, memberId: "member-1" },
376
376
  });
377
377
 
378
378
  // Re-running `prisma migrate deploy` against an already-migrated schema
@@ -578,7 +578,7 @@ function makeMockDeps(): AdminDeps {
578
578
  id: "member-test-id",
579
579
  agentId,
580
580
  email,
581
- memberId: null,
581
+ memberId: "member-1",
582
582
  createdAt: new Date("2024-01-01"),
583
583
  }),
584
584
  // Default: at least one member, so restrictSlackToMembers tests that
@@ -589,7 +589,7 @@ function makeMockDeps(): AdminDeps {
589
589
  id: "member-test-id",
590
590
  agentId,
591
591
  email: "member@example.com",
592
- memberId: null,
592
+ memberId: "member-1",
593
593
  createdAt: new Date("2024-01-01"),
594
594
  },
595
595
  ],
@@ -3072,7 +3072,7 @@ describe("admin API — restrictSlackToMembers field", () => {
3072
3072
  id: "member-1",
3073
3073
  agentId: AGENT_ID,
3074
3074
  email: "member@example.com",
3075
- memberId: null,
3075
+ memberId: "member-1",
3076
3076
  createdAt: new Date("2024-01-01"),
3077
3077
  },
3078
3078
  ],
@@ -5232,7 +5232,7 @@ describe("non-admin session cookie scoping", () => {
5232
5232
  id: "m1",
5233
5233
  agentId: AGENT_ID,
5234
5234
  email,
5235
- memberId: null,
5235
+ memberId: "member-1",
5236
5236
  createdAt: new Date("2024-01-01"),
5237
5237
  },
5238
5238
  ]
@@ -5476,11 +5476,24 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5476
5476
  expect(((await res.json()) as { error: string }).error).toContain(fragment);
5477
5477
  });
5478
5478
 
5479
- it("account user can delete an agent in their account scope", async () => {
5480
- const { deps } = makeAccountDeps("acct-a");
5479
+ // Management (here: DELETE) needs a platform admin or the owner of the
5480
+ // agent's own account; members and owners of other accounts are 403.
5481
+ const deleteAs = async (
5482
+ role: "owner" | "member",
5483
+ agentAccountId: string | null,
5484
+ callerAccountId = "acct-a",
5485
+ ) => {
5486
+ const { deps } = makeAccountDeps(callerAccountId, role);
5481
5487
  const base = deps.prisma;
5482
5488
  const app = createAdminApp({
5483
5489
  ...deps,
5490
+ agentService: {
5491
+ ...deps.agentService,
5492
+ getDetail: async (id: string) => {
5493
+ const detail = await deps.agentService.getDetail(AGENT_ID);
5494
+ return detail && { ...detail, id, accountId: agentAccountId };
5495
+ },
5496
+ },
5484
5497
  prisma: {
5485
5498
  ...base,
5486
5499
  agent: {
@@ -5497,10 +5510,42 @@ describe("admin API — account users create and delete agents (SSP-4.2)", () =>
5497
5510
  },
5498
5511
  } as unknown as AdminDeps["prisma"],
5499
5512
  });
5500
- const res = await app.request(`/agents/${ACCOUNT_AGENT_ID}`, {
5513
+ return app.request(`/agents/${ACCOUNT_AGENT_ID}`, {
5501
5514
  method: "DELETE",
5502
5515
  headers: { Cookie: `admin_session=${await accountCookie()}` },
5503
5516
  });
5517
+ };
5518
+
5519
+ it("account owner can delete an agent in their own account", async () => {
5520
+ expect((await deleteAs("owner", "acct-a")).status).toBe(200);
5521
+ });
5522
+
5523
+ it("account member gets 403 deleting an agent in their own account", async () => {
5524
+ expect((await deleteAs("member", "acct-a")).status).toBe(403);
5525
+ });
5526
+
5527
+ it("owner of another account gets 403 even when they hold access to the agent", async () => {
5528
+ expect((await deleteAs("owner", "acct-b")).status).toBe(403);
5529
+ });
5530
+
5531
+ it("owner gets 403 when the agent has no account", async () => {
5532
+ expect((await deleteAs("owner", null)).status).toBe(403);
5533
+ });
5534
+
5535
+ it("account member can still read the agent (GET) in their account scope", async () => {
5536
+ const { deps } = makeAccountDeps("acct-a", "member");
5537
+ const res = await createAdminApp({
5538
+ ...deps,
5539
+ agentService: {
5540
+ ...deps.agentService,
5541
+ getDetail: async (id: string) => {
5542
+ const detail = await deps.agentService.getDetail(AGENT_ID);
5543
+ return detail && { ...detail, id, accountId: "acct-a" };
5544
+ },
5545
+ },
5546
+ }).request(`/agents/${ACCOUNT_AGENT_ID}`, {
5547
+ headers: { Cookie: `admin_session=${await accountCookie()}` },
5548
+ });
5504
5549
  expect(res.status).toBe(200);
5505
5550
  });
5506
5551
 
@@ -6241,7 +6286,7 @@ describe("admin API — repo removal blocks open work", () => {
6241
6286
  id: "m1",
6242
6287
  agentId: AGENT_ID,
6243
6288
  email,
6244
- memberId: null,
6289
+ memberId: "member-1",
6245
6290
  createdAt: new Date("2024-01-01"),
6246
6291
  },
6247
6292
  ]
@@ -6315,11 +6360,12 @@ describe("admin API — repo removal blocks open work", () => {
6315
6360
  expect(calls).toEqual([blockCall("a/one")]);
6316
6361
  });
6317
6362
 
6318
- it("DELETE as a session member blocks open work too", async () => {
6319
- const { app, calls } = makeApp(["a/one", "b/two"]);
6363
+ it("DELETE as a session member is 403 and touches nothing", async () => {
6364
+ const { app, calls, repos } = makeApp(["a/one", "b/two"]);
6320
6365
  const res = await memberCall(app, "DELETE", `${url}/a/one`);
6321
- expect(res.status).toBe(200);
6322
- expect(calls).toEqual([blockCall("a/one")]);
6366
+ expect(res.status).toBe(403);
6367
+ expect(calls).toEqual([]);
6368
+ expect(repos()).toEqual(["a/one", "b/two"]);
6323
6369
  });
6324
6370
 
6325
6371
  it("a port failure is a warning and the removal still succeeds", async () => {
@@ -6345,13 +6391,22 @@ describe("admin API — repo removal blocks open work", () => {
6345
6391
 
6346
6392
  it("PATCH that drops repos blocks only the dropped ones", async () => {
6347
6393
  const { app, calls } = makeApp(["a/one", "b/two", "c/three"]);
6348
- const res = await memberCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6394
+ const res = await adminCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6349
6395
  repos: ["b/two"],
6350
6396
  });
6351
6397
  expect(res.status).toBe(200);
6352
6398
  expect(calls).toEqual([blockCall("a/one"), blockCall("c/three")]);
6353
6399
  });
6354
6400
 
6401
+ it("PATCH as a session member is 403 and touches nothing", async () => {
6402
+ const { app, calls } = makeApp(["a/one", "b/two", "c/three"]);
6403
+ const res = await memberCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6404
+ repos: ["b/two"],
6405
+ });
6406
+ expect(res.status).toBe(403);
6407
+ expect(calls).toEqual([]);
6408
+ });
6409
+
6355
6410
  it("adding a repo (POST, or PATCH that only adds) never touches open work", async () => {
6356
6411
  const { app, calls } = makeApp(["a/one"]);
6357
6412
  expect(
package/src/agents-api.ts CHANGED
@@ -2215,6 +2215,8 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2215
2215
  adminApiKeys,
2216
2216
  agentMemberService,
2217
2217
  callerScopeResolver,
2218
+ getAgentAccountId: async (id) =>
2219
+ (await agentService.getDetail(id))?.accountId,
2218
2220
  });
2219
2221
 
2220
2222
  // Platform readers/operators (platform.read / platform.ops admin keys): the
@@ -225,13 +225,12 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
225
225
  const members = await prisma.agentMember.findMany({
226
226
  where: { agentId: result.agent.id },
227
227
  });
228
- expect(members.map((m) => m.email)).toEqual(["dev@example.com"]);
229
228
  // The email got an AccountMember (the only Account), so the row is listed.
230
229
  const record = await prisma.accountMember.findUniqueOrThrow({
231
230
  where: { email: "dev@example.com" },
232
231
  });
233
232
  expect(record.role).toBe("member");
234
- expect(members[0]?.memberId).toBe(record.id);
233
+ expect(members.map((m) => m.memberId)).toEqual([record.id]);
235
234
  });
236
235
 
237
236
  it("a member email that cannot get an account member fails with a message and writes nothing", async () => {
package/src/api-auth.ts CHANGED
@@ -17,6 +17,7 @@ import type { AgentTokenService } from "./agent-tokens.ts";
17
17
  import {
18
18
  type CallerScopeResolver,
19
19
  memberOnlyCallerScopeResolver,
20
+ scopeCanManageAgent,
20
21
  scopeIncludesAgent,
21
22
  } from "./caller-scope.ts";
22
23
  import { ForbiddenError } from "./errors.ts";
@@ -132,6 +133,23 @@ function routeMatchers(routes: readonly PlatformOpsRoute[]) {
132
133
  matchers.some((m) => m.method === method && m.re.test(path));
133
134
  }
134
135
 
136
+ /**
137
+ * Routes a non-admin session caller who merely has access to an agent may
138
+ * use: reads, and asking the agent (chat-style use). Every other method/path
139
+ * on an agent is management and needs scopeCanManageAgent.
140
+ */
141
+ export const MEMBER_USE_ROUTES: readonly PlatformOpsRoute[] = [
142
+ { method: "POST", path: "/agents/{id}/ask" },
143
+ { method: "POST", path: "/agents/{id}/asks" },
144
+ ];
145
+
146
+ const isMemberUseListed = routeMatchers(MEMBER_USE_ROUTES);
147
+ function isMemberUseRoute(method: string, path: string): boolean {
148
+ return (
149
+ method === "GET" || method === "HEAD" || isMemberUseListed(method, path)
150
+ );
151
+ }
152
+
135
153
  const isPlatformOpsRoute = routeMatchers(PLATFORM_OPS_ROUTES);
136
154
  const isAgentCrossRoute = routeMatchers(AGENT_CROSS_ROUTES);
137
155
 
@@ -231,6 +249,12 @@ export function createAdminAuthMiddleware(deps: {
231
249
  * AgentMember-only resolver built from agentMemberService.
232
250
  */
233
251
  callerScopeResolver?: CallerScopeResolver;
252
+ /**
253
+ * The account an agent belongs to (null when none). Needed to let an
254
+ * account owner manage their account's agents; absent, session callers
255
+ * that are not admins never pass the management check (fail closed).
256
+ */
257
+ getAgentAccountId?: (agentId: string) => Promise<string | null | undefined>;
234
258
  }): MiddlewareHandler<AdminAuthEnv> {
235
259
  const { sessionSecret, agentTokenService, adminApiKeys, agentMemberService } =
236
260
  deps;
@@ -255,7 +279,13 @@ export function createAdminAuthMiddleware(deps: {
255
279
  if (path === "/templates" || path.startsWith("/templates/")) return true;
256
280
  const agentId = extractAgentId(path);
257
281
  if (!agentId || !callerScopeResolver) return false;
258
- return scopeIncludesAgent(await callerScopeResolver(email, false), agentId);
282
+ const scope = await callerScopeResolver(email, false);
283
+ if (!scopeIncludesAgent(scope, agentId)) return false;
284
+ if (isMemberUseRoute(method, path)) return true;
285
+ // Everything else on an agent is management: admins (handled earlier) and
286
+ // the owner of the agent's own account only.
287
+ if (!deps.getAgentAccountId) return false;
288
+ return scopeCanManageAgent(scope, await deps.getAgentAccountId(agentId));
259
289
  }
260
290
 
261
291
  return async (c, next) => {