@app-vitals/agent-admin 1.123.0 → 1.125.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.
@@ -5278,7 +5278,19 @@
5278
5278
  "/agents": {
5279
5279
  "get": {
5280
5280
  "summary": "List all agents",
5281
- "description": "Admin-only. Returns every agent's `id`, `name`, `selfHosted`, and `specialty` — used for metrics name resolution.",
5281
+ "description": "Admin-only. Returns every agent's `id`, `name`, `selfHosted`, and `specialty` — used for metrics name resolution. Optional `accountId` restricts the list to that account's agents; a non-admin caller naming an account other than its own gets 403.",
5282
+ "parameters": [
5283
+ {
5284
+ "schema": {
5285
+ "type": "string",
5286
+ "minLength": 1,
5287
+ "example": "acct_123"
5288
+ },
5289
+ "required": false,
5290
+ "name": "accountId",
5291
+ "in": "query"
5292
+ }
5293
+ ],
5282
5294
  "responses": {
5283
5295
  "200": {
5284
5296
  "description": "List of agents",
@@ -7117,7 +7129,7 @@
7117
7129
  "/agents/all/cron-runs/stats": {
7118
7130
  "get": {
7119
7131
  "summary": "Get aggregated cron-run token stats",
7120
- "description": "Admin-only. Returns token usage and cost aggregated across all agents' cron runs, broken down by agent, cron, model, day, and pipeline phase. Optional `from`/`to` ISO datetime query params bound the range.",
7132
+ "description": "Admin-only. Returns token usage and cost aggregated across all agents' cron runs, broken down by agent, cron, model, day, and pipeline phase. Optional `from`/`to` ISO datetime query params bound the range; optional `accountId` restricts the stats to that account's agents.",
7121
7133
  "parameters": [
7122
7134
  {
7123
7135
  "schema": {
@@ -7138,6 +7150,16 @@
7138
7150
  "required": false,
7139
7151
  "name": "to",
7140
7152
  "in": "query"
7153
+ },
7154
+ {
7155
+ "schema": {
7156
+ "type": "string",
7157
+ "minLength": 1,
7158
+ "example": "acct_123"
7159
+ },
7160
+ "required": false,
7161
+ "name": "accountId",
7162
+ "in": "query"
7141
7163
  }
7142
7164
  ],
7143
7165
  "responses": {
@@ -7373,7 +7395,7 @@
7373
7395
  "/agents/chat-tokens/daily/stats": {
7374
7396
  "get": {
7375
7397
  "summary": "Get aggregated chat token daily stats",
7376
- "description": "Admin-only. Returns Slack chat token usage aggregated across all agents, broken down by agent, model, and day. Optional `from`/`to` YYYY-MM-DD query params bound the range.",
7398
+ "description": "Admin-only. Returns Slack chat token usage aggregated across all agents, broken down by agent, model, and day. Optional `from`/`to` YYYY-MM-DD query params bound the range; optional `accountId` restricts the stats to that account's agents.",
7377
7399
  "parameters": [
7378
7400
  {
7379
7401
  "schema": {
@@ -7394,6 +7416,16 @@
7394
7416
  "required": false,
7395
7417
  "name": "to",
7396
7418
  "in": "query"
7419
+ },
7420
+ {
7421
+ "schema": {
7422
+ "type": "string",
7423
+ "minLength": 1,
7424
+ "example": "acct_123"
7425
+ },
7426
+ "required": false,
7427
+ "name": "accountId",
7428
+ "in": "query"
7397
7429
  }
7398
7430
  ],
7399
7431
  "responses": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.123.0",
3
+ "version": "1.125.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.123.0",
47
+ "@app-vitals/agent-lib": "1.125.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -145,8 +145,8 @@ export interface BuildSettingsNavOptions {
145
145
  }
146
146
 
147
147
  /**
148
- * Base settings nav: Account section (SGL-2.3), Platform section (GitHub
149
- * Enterprise, Templates, admin-only Accounts) plus extension items. Empty
148
+ * Base settings nav: Personal section (Preferences), Account section (Account,
149
+ * admin-only Accounts; SGL-2.3), Platform section (GitHub Enterprise, Templates) plus extension items. Empty
150
150
  * sections are dropped.
151
151
  */
152
152
  export function buildSettingsNav(
@@ -175,28 +175,22 @@ export function buildSettingsNav(
175
175
  ownerOnly: true,
176
176
  });
177
177
  }
178
- if (opts.accounts) {
179
- platform.push({
180
- label: "Accounts",
181
- path: SETTINGS_ACCOUNTS_PATH,
182
- adminOnly: true,
178
+ const sections: SettingsNavSection[] = [];
179
+ if (opts.preferences) {
180
+ sections.push({
181
+ label: "Personal",
182
+ items: [{ label: "Preferences", path: SETTINGS_PREFERENCES_PATH }],
183
183
  });
184
184
  }
185
- const sections: SettingsNavSection[] = [];
186
185
  if (opts.accounts) {
187
186
  sections.push({
188
187
  label: "Account",
189
188
  items: [
190
189
  { label: "Account", path: SETTINGS_ACCOUNT_PATH, ownerOnly: true },
190
+ { label: "Accounts", path: SETTINGS_ACCOUNTS_PATH, adminOnly: true },
191
191
  ],
192
192
  });
193
193
  }
194
- if (opts.preferences) {
195
- const section = sections.find((s) => s.label === "Account");
196
- const item = { label: "Preferences", path: SETTINGS_PREFERENCES_PATH };
197
- if (section) section.items.push(item);
198
- else sections.push({ label: "Account", items: [item] });
199
- }
200
194
  if (platform.length > 0)
201
195
  sections.push({ label: "Platform", items: platform });
202
196
  const base: SettingsNav = { sections };
@@ -225,11 +225,11 @@ describe("filterSettingsNavForRole (ACM-7.2)", () => {
225
225
  test("admin sees every item", () => {
226
226
  expect(labels("admin")).toEqual([
227
227
  "Account",
228
+ "Accounts",
228
229
  "Notifications",
229
230
  "GitHub Enterprise",
230
231
  "Slack config token",
231
232
  "Templates",
232
- "Accounts",
233
233
  "System crons",
234
234
  ]);
235
235
  });
@@ -259,3 +259,44 @@ describe("filterSettingsNavForRole (ACM-7.2)", () => {
259
259
  );
260
260
  });
261
261
  });
262
+
263
+ describe("settings nav reorg: Personal / Account sections", () => {
264
+ const nav = buildSettingsNav({
265
+ preferences: true,
266
+ accounts: true,
267
+ templates: true,
268
+ extraItems: [{ section: "Personal", label: "Profile", path: "/profile" }],
269
+ });
270
+ const section = (n: SettingsNav, label: string) =>
271
+ n.sections.find((s) => s.label === label)?.items.map((i) => i.label);
272
+
273
+ test("Preferences lives under Personal, not Account", () => {
274
+ expect(section(nav, "Personal")).toContain("Preferences");
275
+ expect(section(nav, "Account")).not.toContain("Preferences");
276
+ });
277
+ test("Accounts lives under Account, not Platform", () => {
278
+ expect(section(nav, "Account")).toEqual(["Account", "Accounts"]);
279
+ expect(section(nav, "Platform")).not.toContain("Accounts");
280
+ });
281
+ test("admin sees both Account items; owner sees Account only", () => {
282
+ expect(section(filterSettingsNavForRole(nav, "admin"), "Account")).toEqual([
283
+ "Account",
284
+ "Accounts",
285
+ ]);
286
+ expect(section(filterSettingsNavForRole(nav, "owner"), "Account")).toEqual([
287
+ "Account",
288
+ ]);
289
+ });
290
+ test("a member's resolved nav has no Account section or Accounts item", () => {
291
+ const member = filterSettingsNavForRole(nav, "member");
292
+ expect(member.sections.map((s) => s.label)).not.toContain("Account");
293
+ const labels = member.sections.flatMap((s) => s.items.map((i) => i.label));
294
+ expect(labels).not.toContain("Account");
295
+ expect(labels).not.toContain("Accounts");
296
+ expect(section(member, "Personal")).toContain("Preferences");
297
+ });
298
+ test("an extension item targeting Personal merges into the Preferences section", () => {
299
+ expect(nav.sections.filter((s) => s.label === "Personal")).toHaveLength(1);
300
+ expect(section(nav, "Personal")).toEqual(["Preferences", "Profile"]);
301
+ });
302
+ });
@@ -88,9 +88,9 @@ describe("getSettingsNav in extension adminUiRoutes", () => {
88
88
  );
89
89
  expect(paths(nav)).toEqual([
90
90
  SETTINGS_ACCOUNT_PATH,
91
+ SETTINGS_ACCOUNTS_PATH,
91
92
  SETTINGS_GHE_PATH,
92
93
  SETTINGS_TEMPLATES_PATH,
93
- SETTINGS_ACCOUNTS_PATH,
94
94
  "/admin/ext-page",
95
95
  ]);
96
96
  });
@@ -277,11 +277,11 @@ describe("GET /admin/settings with accounts (SGL-2.3)", () => {
277
277
  expect(res.headers.get("location")).toBe("/admin/notifications");
278
278
  });
279
279
 
280
- it("skips Account for an admin without an account", async () => {
280
+ it("skips Account for an admin without an account, landing on Accounts", async () => {
281
281
  const res = await build(null).request("/admin/settings", {
282
282
  headers: { cookie: await adminCookie() },
283
283
  });
284
284
  expect(res.status).toBe(302);
285
- expect(res.headers.get("location")).toBe("/admin/settings/templates");
285
+ expect(res.headers.get("location")).toBe("/admin/accounts");
286
286
  });
287
287
  });
@@ -143,10 +143,12 @@ export class AgentChatTokenService {
143
143
  from?: string,
144
144
  to?: string,
145
145
  agentId?: string,
146
+ accountId?: string,
146
147
  ): Promise<ChatTokenStats> {
147
148
  const dateFilter = {
148
149
  ...this.buildDateFilter(from, to),
149
150
  ...(agentId ? { agentId } : {}),
151
+ ...(accountId !== undefined ? { agent: { accountId } } : {}),
150
152
  };
151
153
 
152
154
  const [aggregateResult, byAgentRows, byModelRows, dailyRows] =
@@ -327,11 +327,13 @@ export class AgentCronRunStatsService {
327
327
  * @param to ISO string — if provided, only runs with startedAt < to
328
328
  * @param agentId if provided, only that agent's runs (every dimension);
329
329
  * omitted preserves the fleet-wide behavior
330
+ * @param accountId if provided, only runs of agents in that account
330
331
  */
331
332
  async query(
332
333
  from?: string,
333
334
  to?: string,
334
335
  agentId?: string,
336
+ accountId?: string,
335
337
  ): Promise<CronRunTokenStats> {
336
338
  const fromDate = from ? new Date(from) : null;
337
339
  const toDate = to ? new Date(to) : null;
@@ -345,6 +347,10 @@ export class AgentCronRunStatsService {
345
347
  agentId !== undefined
346
348
  ? Prisma.sql`AND r."agentId" = ${agentId}`
347
349
  : Prisma.empty
350
+ } ${
351
+ accountId !== undefined
352
+ ? Prisma.sql`AND r."agentId" IN (SELECT a.id FROM "Agent" a WHERE a."accountId" = ${accountId})`
353
+ : Prisma.empty
348
354
  }`;
349
355
 
350
356
  const [
@@ -855,3 +855,134 @@ describeOrSkip("PATCH /agents/:id podServiceAccountName (integration)", () => {
855
855
  });
856
856
  });
857
857
  });
858
+
859
+ // ─── accountId filter on the agent list and fleet-wide stats ────────────────
860
+
861
+ describeOrSkip("accountId filter (integration)", () => {
862
+ let prisma: PrismaClient;
863
+ let cookie: string;
864
+ let app: ReturnType<typeof createAdminApp>;
865
+ let accountA: string;
866
+ let accountB: string;
867
+ let agentA: string;
868
+ let agentB: string;
869
+
870
+ const getJson = async (path: string) => {
871
+ const res = await app.request(path, {
872
+ headers: { Cookie: `admin_session=${cookie}` },
873
+ });
874
+ return { status: res.status, body: await res.json() };
875
+ };
876
+
877
+ beforeEach(async () => {
878
+ prisma = makePrisma();
879
+ await prisma.agentChatTokenUsageDailyByModel.deleteMany();
880
+ await prisma.agentCronRunSkillUsage.deleteMany();
881
+ await prisma.agentCronRunModelBreakdown.deleteMany();
882
+ await prisma.agentCronRun.deleteMany();
883
+ await prisma.agentCronJob.deleteMany();
884
+ await prisma.agentToken.deleteMany();
885
+ await prisma.agentTool.deleteMany();
886
+ await prisma.agentEnv.deleteMany();
887
+ await prisma.agentMember.deleteMany();
888
+ await prisma.agent.deleteMany();
889
+ await prisma.accountMember.deleteMany();
890
+ await prisma.account.deleteMany();
891
+
892
+ accountA = (await prisma.account.create({ data: { name: "Acct A" } })).id;
893
+ accountB = (await prisma.account.create({ data: { name: "Acct B" } })).id;
894
+ agentA = (
895
+ await prisma.agent.create({
896
+ data: { name: "Agent A", accountId: accountA },
897
+ })
898
+ ).id;
899
+ agentB = (
900
+ await prisma.agent.create({
901
+ data: { name: "Agent B", accountId: accountB },
902
+ })
903
+ ).id;
904
+ cookie = await makeSessionCookie();
905
+ app = createAdminApp(makeDeps(prisma));
906
+ });
907
+
908
+ afterEach(async () => {
909
+ await prisma.$disconnect();
910
+ });
911
+
912
+ it("GET /agents?accountId= returns only that account's agents; no param returns all", async () => {
913
+ const filtered = await getJson(`/agents?accountId=${accountA}`);
914
+ expect(filtered.status).toBe(200);
915
+ expect(filtered.body.map((a: { id: string }) => a.id)).toEqual([agentA]);
916
+
917
+ const all = await getJson("/agents");
918
+ expect(all.body.map((a: { id: string }) => a.id).sort()).toEqual(
919
+ [agentA, agentB].sort(),
920
+ );
921
+ });
922
+
923
+ it("GET /agents/all/cron-runs/stats?accountId= restricts every dimension to that account", async () => {
924
+ const jobs = new AgentCronJobService(prisma);
925
+ const runs = new AgentCronRunService(prisma);
926
+ for (const [agent, n] of [
927
+ [agentA, 10],
928
+ [agentB, 500],
929
+ ] as const) {
930
+ const job = await jobs.create(agent, {
931
+ schedule: "0 9 * * *",
932
+ prompt: "p",
933
+ silent: true,
934
+ });
935
+ const run = await runs.create(job.id, agent, {
936
+ startedAt: new Date("2026-01-10T09:00:00Z"),
937
+ skipped: false,
938
+ });
939
+ await prisma.agentCronRunModelBreakdown.create({
940
+ data: {
941
+ cronRunId: run.id,
942
+ model: "model-a",
943
+ inputTokens: n,
944
+ outputTokens: 0,
945
+ cacheReadTokens: 0,
946
+ cacheCreationTokens: 0,
947
+ costUsd: 0,
948
+ },
949
+ });
950
+ }
951
+
952
+ const a = await getJson(
953
+ `/agents/all/cron-runs/stats?accountId=${accountA}`,
954
+ );
955
+ expect(a.status).toBe(200);
956
+ expect(a.body.totals.input).toBe(10);
957
+ expect(a.body.byAgent.map((r: { key: string }) => r.key)).toEqual([agentA]);
958
+ expect(a.body.byModel.map((r: { key1: string }) => r.key1)).toEqual([
959
+ agentA,
960
+ ]);
961
+
962
+ const all = await getJson("/agents/all/cron-runs/stats");
963
+ expect(all.body.totals.input).toBe(510);
964
+ });
965
+
966
+ it("GET /agents/chat-tokens/daily/stats?accountId= restricts to that account; no param is fleet-wide", async () => {
967
+ const chatTokens = new AgentChatTokenService(prisma);
968
+ const usage = (n: number) => ({
969
+ inputTokens: n,
970
+ outputTokens: 0,
971
+ cacheReadTokens: 0,
972
+ cacheCreationTokens: 0,
973
+ costUsd: 0,
974
+ });
975
+ await chatTokens.upsertDailyByModel(agentA, "2026-01-10", "m", usage(10));
976
+ await chatTokens.upsertDailyByModel(agentB, "2026-01-10", "m", usage(500));
977
+
978
+ const b = await getJson(
979
+ `/agents/chat-tokens/daily/stats?accountId=${accountB}`,
980
+ );
981
+ expect(b.status).toBe(200);
982
+ expect(b.body.totals.input).toBe(500);
983
+ expect(b.body.byAgent.map((r: { key: string }) => r.key)).toEqual([agentB]);
984
+
985
+ const all = await getJson("/agents/chat-tokens/daily/stats");
986
+ expect(all.body.totals.input).toBe(510);
987
+ });
988
+ });
@@ -8193,3 +8193,84 @@ describe("admin API — agent App installation repos and GitHub Sync (IRM-1.2, I
8193
8193
  expect(audits).toEqual([]);
8194
8194
  });
8195
8195
  });
8196
+
8197
+ describe("admin API — accountId filter on the agent list and stats", () => {
8198
+ async function cookieFor(isAdmin: boolean): Promise<string> {
8199
+ return sign(
8200
+ {
8201
+ isAdmin,
8202
+ userId: "user-filter",
8203
+ email: "filter@example.com",
8204
+ iat: Math.floor(Date.now() / 1000),
8205
+ exp: Math.floor(Date.now() / 1000) + 3600,
8206
+ },
8207
+ SESSION_SECRET,
8208
+ "HS256",
8209
+ );
8210
+ }
8211
+
8212
+ function makeDeps(ownAccountId: string): AdminDeps {
8213
+ const base = makeMockDeps();
8214
+ const rows = [
8215
+ { id: "agent-a1", accountId: "acct-a" },
8216
+ { id: "agent-b1", accountId: "acct-b" },
8217
+ ].map((r) => ({
8218
+ ...r,
8219
+ name: r.id,
8220
+ selfHosted: false,
8221
+ specialty: "coding",
8222
+ }));
8223
+ return {
8224
+ ...base,
8225
+ callerScopeResolver: async () => ({
8226
+ kind: "scoped",
8227
+ accountId: ownAccountId,
8228
+ agentIds: ["agent-a1", "agent-b1"],
8229
+ role: "owner",
8230
+ }),
8231
+ agentService: { ...base.agentService, list: async () => rows },
8232
+ };
8233
+ }
8234
+
8235
+ const get = async (deps: AdminDeps, path: string, admin: boolean) =>
8236
+ createAdminApp(deps).request(path, {
8237
+ headers: { Cookie: `admin_session=${await cookieFor(admin)}` },
8238
+ });
8239
+
8240
+ it("a non-admin naming an account outside its own gets 403 on GET /agents", async () => {
8241
+ const res = await get(
8242
+ makeDeps("acct-a"),
8243
+ "/agents?accountId=acct-b",
8244
+ false,
8245
+ );
8246
+ expect(res.status).toBe(403);
8247
+ });
8248
+
8249
+ it("a non-admin naming its own account gets only that account's agents", async () => {
8250
+ const res = await get(
8251
+ makeDeps("acct-a"),
8252
+ "/agents?accountId=acct-a",
8253
+ false,
8254
+ );
8255
+ expect(res.status).toBe(200);
8256
+ const body = (await res.json()) as Array<{ id: string }>;
8257
+ expect(body.map((a) => a.id)).toEqual(["agent-a1"]);
8258
+ });
8259
+
8260
+ it("an admin may filter GET /agents by any account", async () => {
8261
+ const res = await get(makeDeps("acct-a"), "/agents?accountId=acct-b", true);
8262
+ expect(res.status).toBe(200);
8263
+ const body = (await res.json()) as Array<{ id: string }>;
8264
+ expect(body.map((a) => a.id)).toEqual(["agent-b1"]);
8265
+ });
8266
+
8267
+ it("a non-admin naming an account gets 403 on the fleet-wide stats routes", async () => {
8268
+ for (const path of [
8269
+ "/agents/all/cron-runs/stats?accountId=acct-b",
8270
+ "/agents/chat-tokens/daily/stats?accountId=acct-b",
8271
+ ]) {
8272
+ const res = await get(makeDeps("acct-a"), path, false);
8273
+ expect(res.status).toBe(403);
8274
+ }
8275
+ });
8276
+ });
package/src/agents-api.ts CHANGED
@@ -865,12 +865,20 @@ const provisionAgentRoute = createRoute({
865
865
  },
866
866
  });
867
867
 
868
+ /** Optional account narrowing for the fleet-wide list and stats routes. */
869
+ const accountFilterQuerySchema = z
870
+ .object({
871
+ accountId: z.string().min(1).optional().openapi({ example: "acct_123" }),
872
+ })
873
+ .openapi("AccountFilterQuery");
874
+
868
875
  const listAgentsRoute = createRoute({
869
876
  method: "get",
870
877
  path: "/agents",
878
+ request: { query: accountFilterQuerySchema },
871
879
  summary: "List all agents",
872
880
  description:
873
- "Admin-only. Returns every agent's `id`, `name`, `selfHosted`, and `specialty` — used for metrics name resolution.",
881
+ "Admin-only. Returns every agent's `id`, `name`, `selfHosted`, and `specialty` — used for metrics name resolution. Optional `accountId` restricts the list to that account's agents; a non-admin caller naming an account other than its own gets 403.",
874
882
  responses: {
875
883
  200: {
876
884
  description: "List of agents",
@@ -1916,9 +1924,9 @@ const cronRunTokenStatsRoute = createRoute({
1916
1924
  path: "/agents/all/cron-runs/stats",
1917
1925
  summary: "Get aggregated cron-run token stats",
1918
1926
  description:
1919
- "Admin-only. Returns token usage and cost aggregated across all agents' cron runs, broken down by agent, cron, model, day, and pipeline phase. Optional `from`/`to` ISO datetime query params bound the range.",
1927
+ "Admin-only. Returns token usage and cost aggregated across all agents' cron runs, broken down by agent, cron, model, day, and pipeline phase. Optional `from`/`to` ISO datetime query params bound the range; optional `accountId` restricts the stats to that account's agents.",
1920
1928
  request: {
1921
- query: cronRunStatsQuerySchema,
1929
+ query: cronRunStatsQuerySchema.extend(accountFilterQuerySchema.shape),
1922
1930
  },
1923
1931
  responses: {
1924
1932
  200: {
@@ -2003,9 +2011,11 @@ const chatTokenDailyStatsRoute = createRoute({
2003
2011
  path: "/agents/chat-tokens/daily/stats",
2004
2012
  summary: "Get aggregated chat token daily stats",
2005
2013
  description:
2006
- "Admin-only. Returns Slack chat token usage aggregated across all agents, broken down by agent, model, and day. Optional `from`/`to` YYYY-MM-DD query params bound the range.",
2014
+ "Admin-only. Returns Slack chat token usage aggregated across all agents, broken down by agent, model, and day. Optional `from`/`to` YYYY-MM-DD query params bound the range; optional `accountId` restricts the stats to that account's agents.",
2007
2015
  request: {
2008
- query: chatTokenDailyStatsQuerySchema,
2016
+ query: chatTokenDailyStatsQuerySchema.extend(
2017
+ accountFilterQuerySchema.shape,
2018
+ ),
2009
2019
  },
2010
2020
  responses: {
2011
2021
  200: {
@@ -2629,6 +2639,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2629
2639
  if (!isAdminOrSessionMember(c)) {
2630
2640
  throw new ForbiddenError("Admin access required to list agents");
2631
2641
  }
2642
+ const { accountId: accountFilter } = c.req.valid("query");
2632
2643
  // list() also selects the owner and identity IDs for reconcile targets;
2633
2644
  // they are not part of this response.
2634
2645
  const agents = (await agentService.list()).map(
@@ -2641,14 +2652,24 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2641
2652
  ...summary
2642
2653
  }) => summary,
2643
2654
  );
2655
+ const inAccount = <T extends { accountId?: string | null }>(rows: T[]) =>
2656
+ accountFilter === undefined
2657
+ ? rows
2658
+ : rows.filter((a) => a.accountId === accountFilter);
2644
2659
  if (c.get("isAdmin") === true || email === undefined) {
2645
- return c.json(agents, 200);
2660
+ return c.json(inAccount(agents), 200);
2646
2661
  }
2647
2662
  // Non-admin session: only agents the caller has an AgentMember row for.
2648
2663
  const scope = await callerScopeResolver(email, false);
2664
+ if (
2665
+ accountFilter !== undefined &&
2666
+ (scope.kind !== "scoped" || scope.accountId !== accountFilter)
2667
+ ) {
2668
+ throw new ForbiddenError("Cannot filter by another account");
2669
+ }
2649
2670
  const memberAgentIds = new Set(scope.kind === "all" ? [] : scope.agentIds);
2650
2671
  return c.json(
2651
- agents.filter((a) => memberAgentIds.has(a.id)),
2672
+ inAccount(agents.filter((a) => memberAgentIds.has(a.id))),
2652
2673
  200,
2653
2674
  );
2654
2675
  });
@@ -3342,8 +3363,13 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3342
3363
  "Only admin bearers and session users can access cross-agent stats",
3343
3364
  );
3344
3365
  }
3345
- const { from, to } = c.req.valid("query");
3346
- const stats = await agentCronRunStatsService.query(from, to);
3366
+ const { from, to, accountId } = c.req.valid("query");
3367
+ const stats = await agentCronRunStatsService.query(
3368
+ from,
3369
+ to,
3370
+ undefined,
3371
+ accountId,
3372
+ );
3347
3373
  return c.json(stats, 200);
3348
3374
  });
3349
3375
 
@@ -3388,8 +3414,13 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
3388
3414
  "Only admin bearers and session users can access cross-agent stats",
3389
3415
  );
3390
3416
  }
3391
- const { from, to } = c.req.valid("query");
3392
- const stats = await agentChatTokenService.queryStats(from, to);
3417
+ const { from, to, accountId } = c.req.valid("query");
3418
+ const stats = await agentChatTokenService.queryStats(
3419
+ from,
3420
+ to,
3421
+ undefined,
3422
+ accountId,
3423
+ );
3393
3424
  return c.json(stats, 200);
3394
3425
  });
3395
3426