@app-vitals/agent-admin 1.122.0 → 1.124.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/openapi.platform.json +35 -3
- package/package.json +2 -2
- package/src/admin-ui-account-filter.smoke.test.ts +237 -0
- package/src/admin-ui-pages.ts +62 -0
- package/src/admin-ui.ts +70 -19
- package/src/agent-chat-tokens.ts +2 -0
- package/src/agent-cron-run-stats.ts +6 -0
- package/src/agents-api.integration.test.ts +131 -0
- package/src/agents-api.smoke.test.ts +81 -0
- package/src/agents-api.ts +42 -11
- package/src/agents.ts +3 -1
package/openapi.platform.json
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "1.124.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.
|
|
47
|
+
"@app-vitals/agent-lib": "1.124.0",
|
|
48
48
|
"@hono/zod-openapi": "^1.0.0",
|
|
49
49
|
"@prisma/adapter-pg": "^7.10.0",
|
|
50
50
|
"@prisma/client": "^7.10.0",
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/admin-ui-account-filter.smoke.test.ts
|
|
3
|
+
* Admin account filter on the Agents and Chat pages: two accounts; admin sees
|
|
4
|
+
* all or one account's agents, owners and members are pinned and see no
|
|
5
|
+
* selector. Chat thread/message/upload routes keep their access check
|
|
6
|
+
* regardless of the selection.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { beforeAll, describe, expect, it } from "bun:test";
|
|
10
|
+
import { makeMockDeps, makeSessionCookie } from "./admin-ui.fixtures.ts";
|
|
11
|
+
import { type AdminUIDeps, createAdminUIApp } from "./admin-ui.ts";
|
|
12
|
+
import type { ChatClient, ChatThread } from "./http-chat-client.ts";
|
|
13
|
+
|
|
14
|
+
const SECRET = "test-admin-session-secret-32-bytes!";
|
|
15
|
+
const ACCOUNTS = [
|
|
16
|
+
{ id: "acct-one", name: "Account One" },
|
|
17
|
+
{ id: "acct-two", name: "Account Two" },
|
|
18
|
+
];
|
|
19
|
+
const AGENTS = [
|
|
20
|
+
{ id: "agent-one", name: "Alpha Agent", accountId: "acct-one" },
|
|
21
|
+
{ id: "agent-two", name: "Bravo Agent", accountId: "acct-two" },
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
type Role = "admin" | "owner" | "member";
|
|
25
|
+
const EMAIL: Record<Role, string> = {
|
|
26
|
+
admin: "admin@example.com",
|
|
27
|
+
owner: "owner@example.com",
|
|
28
|
+
member: "member@example.com",
|
|
29
|
+
};
|
|
30
|
+
const cookies = {} as Record<Role, string>;
|
|
31
|
+
|
|
32
|
+
beforeAll(async () => {
|
|
33
|
+
for (const role of ["admin", "owner", "member"] as Role[]) {
|
|
34
|
+
cookies[role] = await makeSessionCookie(
|
|
35
|
+
SECRET,
|
|
36
|
+
`sub-${role}`,
|
|
37
|
+
EMAIL[role],
|
|
38
|
+
role === "admin",
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const thread = (agentId: string): ChatThread => ({
|
|
44
|
+
id: `thread-${agentId}`,
|
|
45
|
+
agentId,
|
|
46
|
+
title: "Thread",
|
|
47
|
+
memberId: null,
|
|
48
|
+
createdAt: "2024-01-01T00:00:00.000Z",
|
|
49
|
+
updatedAt: "2024-01-01T00:00:00.000Z",
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
function deps(): AdminUIDeps {
|
|
53
|
+
const base = makeMockDeps();
|
|
54
|
+
const full = AGENTS.map((a) => ({
|
|
55
|
+
...a,
|
|
56
|
+
slackId: null,
|
|
57
|
+
createdAt: new Date("2024-01-01"),
|
|
58
|
+
}));
|
|
59
|
+
const chatClient: ChatClient = {
|
|
60
|
+
listThreads: async (agentId: string) => ({
|
|
61
|
+
threads: [thread(agentId)],
|
|
62
|
+
total: 1,
|
|
63
|
+
limit: 50,
|
|
64
|
+
offset: 0,
|
|
65
|
+
}),
|
|
66
|
+
getThread: async (id: string) => thread(id.replace("thread-", "")),
|
|
67
|
+
createThread: async (agentId: string) => thread(agentId),
|
|
68
|
+
updateThread: async (id: string) => thread(id.replace("thread-", "")),
|
|
69
|
+
deleteThread: async () => {},
|
|
70
|
+
listMessages: async () => ({
|
|
71
|
+
messages: [],
|
|
72
|
+
total: 0,
|
|
73
|
+
limit: 50,
|
|
74
|
+
offset: 0,
|
|
75
|
+
}),
|
|
76
|
+
createMessage: async () => {
|
|
77
|
+
throw new Error("unused");
|
|
78
|
+
},
|
|
79
|
+
getThreadStats: async () => ({
|
|
80
|
+
messageCount: 0,
|
|
81
|
+
totalInputTokens: 0,
|
|
82
|
+
totalOutputTokens: 0,
|
|
83
|
+
totalCostUsd: 0,
|
|
84
|
+
}),
|
|
85
|
+
getAttachment: async () => null,
|
|
86
|
+
} as ChatClient;
|
|
87
|
+
return makeMockDeps({
|
|
88
|
+
sessionSecret: SECRET,
|
|
89
|
+
chatClient,
|
|
90
|
+
accountServices: {
|
|
91
|
+
accounts: {
|
|
92
|
+
getByMemberEmail: async () => null,
|
|
93
|
+
listWithCounts: async () => ACCOUNTS,
|
|
94
|
+
},
|
|
95
|
+
members: {
|
|
96
|
+
getByEmail: async (email: string) =>
|
|
97
|
+
email === EMAIL.owner
|
|
98
|
+
? { role: "owner" }
|
|
99
|
+
: email === EMAIL.member
|
|
100
|
+
? { role: "member" }
|
|
101
|
+
: null,
|
|
102
|
+
},
|
|
103
|
+
} as never,
|
|
104
|
+
callerScopeResolver: async (email: string, isAdmin: boolean) =>
|
|
105
|
+
isAdmin || email === EMAIL.admin
|
|
106
|
+
? { kind: "all" }
|
|
107
|
+
: {
|
|
108
|
+
kind: "scoped",
|
|
109
|
+
accountId: email === EMAIL.owner ? "acct-one" : null,
|
|
110
|
+
agentIds: ["agent-one"],
|
|
111
|
+
},
|
|
112
|
+
agentService: {
|
|
113
|
+
...base.agentService,
|
|
114
|
+
listAll: async () => full as never,
|
|
115
|
+
listByIds: async (ids: string[]) =>
|
|
116
|
+
full.filter((a) => ids.includes(a.id)) as never,
|
|
117
|
+
listOptions: async () => AGENTS,
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function get(role: Role, path: string): Promise<string> {
|
|
123
|
+
const res = await createAdminUIApp(deps()).request(path, {
|
|
124
|
+
headers: { Cookie: `admin_session=${cookies[role]}` },
|
|
125
|
+
});
|
|
126
|
+
expect(res.status).toBe(200);
|
|
127
|
+
return res.text();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
describe("Agents page account filter", () => {
|
|
131
|
+
it("admin: all accounts by default, with the selector", async () => {
|
|
132
|
+
const html = await get("admin", "/admin/agents");
|
|
133
|
+
expect(html).toContain("Alpha Agent");
|
|
134
|
+
expect(html).toContain("Bravo Agent");
|
|
135
|
+
expect(html).toContain('class="account-filter"');
|
|
136
|
+
expect(html).toContain("All accounts");
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
for (const [id, shown, hidden] of [
|
|
140
|
+
["acct-one", "Alpha Agent", "Bravo Agent"],
|
|
141
|
+
["acct-two", "Bravo Agent", "Alpha Agent"],
|
|
142
|
+
] as const) {
|
|
143
|
+
it(`admin: ${id} shows only its agents`, async () => {
|
|
144
|
+
const html = await get("admin", `/admin/agents?accountId=${id}`);
|
|
145
|
+
expect(html).toContain(shown);
|
|
146
|
+
expect(html).not.toContain(hidden);
|
|
147
|
+
expect(html).toContain(`<option value="${id}" selected>`);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
it("admin: an unknown account falls back to all accounts", async () => {
|
|
152
|
+
const html = await get("admin", "/admin/agents?accountId=nope");
|
|
153
|
+
expect(html).toContain("Alpha Agent");
|
|
154
|
+
expect(html).toContain("Bravo Agent");
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
for (const role of ["owner", "member"] as Role[]) {
|
|
158
|
+
it(`${role}: pinned, no selector, accountId ignored`, async () => {
|
|
159
|
+
const html = await get(role, "/admin/agents?accountId=acct-two");
|
|
160
|
+
expect(html).toContain("Alpha Agent");
|
|
161
|
+
expect(html).not.toContain("Bravo Agent");
|
|
162
|
+
expect(html).not.toContain('class="account-filter"');
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
describe("Chat page account filter", () => {
|
|
168
|
+
it("admin: all agents by default, with the selector", async () => {
|
|
169
|
+
const html = await get("admin", "/admin/chat");
|
|
170
|
+
expect(html).toContain("Alpha Agent");
|
|
171
|
+
expect(html).toContain("Bravo Agent");
|
|
172
|
+
expect(html).toContain('class="account-filter"');
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
for (const [id, shown, hidden] of [
|
|
176
|
+
["acct-one", "Alpha Agent", "Bravo Agent"],
|
|
177
|
+
["acct-two", "Bravo Agent", "Alpha Agent"],
|
|
178
|
+
] as const) {
|
|
179
|
+
it(`admin: ${id} narrows the agent picker`, async () => {
|
|
180
|
+
const html = await get("admin", `/admin/chat?accountId=${id}`);
|
|
181
|
+
expect(html).toContain(shown);
|
|
182
|
+
expect(html).not.toContain(hidden);
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
it("admin: the selection is carried by the picker and search forms", async () => {
|
|
187
|
+
const html = await get(
|
|
188
|
+
"admin",
|
|
189
|
+
"/admin/chat?accountId=acct-one&agentId=agent-one",
|
|
190
|
+
);
|
|
191
|
+
expect(html).toContain('name="accountId" value="acct-one"');
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("admin: an agent outside the selected account is ignored", async () => {
|
|
195
|
+
const html = await get(
|
|
196
|
+
"admin",
|
|
197
|
+
"/admin/chat?accountId=acct-one&agentId=agent-two",
|
|
198
|
+
);
|
|
199
|
+
expect(html).toContain("Alpha Agent");
|
|
200
|
+
expect(html).not.toContain("Bravo Agent");
|
|
201
|
+
expect(html).not.toContain('name="q"');
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
for (const role of ["owner", "member"] as Role[]) {
|
|
205
|
+
it(`${role}: pinned, no selector`, async () => {
|
|
206
|
+
const html = await get(role, "/admin/chat?accountId=acct-two");
|
|
207
|
+
expect(html).toContain("Alpha Agent");
|
|
208
|
+
expect(html).not.toContain("Bravo Agent");
|
|
209
|
+
expect(html).not.toContain('class="account-filter"');
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
it("access checks are unchanged by the selection", async () => {
|
|
214
|
+
const app = createAdminUIApp(deps());
|
|
215
|
+
for (const role of ["owner", "member"] as Role[]) {
|
|
216
|
+
const res = await app.request(
|
|
217
|
+
"/admin/chat/agent-two/threads/thread-agent-two?accountId=acct-two",
|
|
218
|
+
{ headers: { Cookie: `admin_session=${cookies[role]}` } },
|
|
219
|
+
);
|
|
220
|
+
expect(res.status).toBe(403);
|
|
221
|
+
}
|
|
222
|
+
const up = await app.request(
|
|
223
|
+
"/admin/chat/agent-two/threads/thread-agent-two/messages/upload?accountId=acct-one",
|
|
224
|
+
{
|
|
225
|
+
method: "POST",
|
|
226
|
+
headers: { Cookie: `admin_session=${cookies.member}` },
|
|
227
|
+
body: new FormData(),
|
|
228
|
+
},
|
|
229
|
+
);
|
|
230
|
+
expect(up.status).toBe(403);
|
|
231
|
+
const adminRes = await app.request(
|
|
232
|
+
"/admin/chat/agent-two/threads/thread-agent-two?accountId=acct-one",
|
|
233
|
+
{ headers: { Cookie: `admin_session=${cookies.admin}` } },
|
|
234
|
+
);
|
|
235
|
+
expect(adminRes.status).toBe(200);
|
|
236
|
+
});
|
|
237
|
+
});
|
package/src/admin-ui-pages.ts
CHANGED
|
@@ -404,6 +404,39 @@ export function renderLoginPage(opts?: {
|
|
|
404
404
|
});
|
|
405
405
|
}
|
|
406
406
|
|
|
407
|
+
// ─── Admin account filter ─────────────────────────────────────────────────────
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Account selector shown to platform admins on the Agents and Chat pages.
|
|
411
|
+
* A GET form: "All accounts" (empty value) is the default. `hidden` carries
|
|
412
|
+
* other query params (e.g. the selected chat agent) across the switch.
|
|
413
|
+
*/
|
|
414
|
+
export function renderAccountFilter(opts: {
|
|
415
|
+
action: string;
|
|
416
|
+
accounts: { id: string; name: string }[];
|
|
417
|
+
accountId?: string;
|
|
418
|
+
hidden?: Record<string, string | undefined>;
|
|
419
|
+
}): string {
|
|
420
|
+
const options = [
|
|
421
|
+
`<option value=""${opts.accountId ? "" : " selected"}>All accounts</option>`,
|
|
422
|
+
...opts.accounts.map(
|
|
423
|
+
(a) =>
|
|
424
|
+
`<option value="${escapeHtml(a.id)}"${a.id === opts.accountId ? " selected" : ""}>${escapeHtml(a.name)}</option>`,
|
|
425
|
+
),
|
|
426
|
+
].join("");
|
|
427
|
+
const hidden = Object.entries(opts.hidden ?? {})
|
|
428
|
+
.filter(([, v]) => v)
|
|
429
|
+
.map(
|
|
430
|
+
([k, v]) =>
|
|
431
|
+
`<input type="hidden" name="${escapeHtml(k)}" value="${escapeHtml(v as string)}">`,
|
|
432
|
+
)
|
|
433
|
+
.join("");
|
|
434
|
+
return `<form method="GET" action="${escapeHtml(opts.action)}" class="account-filter" style="display:flex;gap:8px;align-items:center;margin:0 0 16px">
|
|
435
|
+
${hidden}<label>Account <select name="accountId" class="form-input" onchange="this.form.submit()">${options}</select></label>
|
|
436
|
+
<noscript><button type="submit" class="btn btn-secondary" style="font-size:12px;padding:4px 10px">Filter</button></noscript>
|
|
437
|
+
</form>`;
|
|
438
|
+
}
|
|
439
|
+
|
|
407
440
|
// ─── Agents list page ─────────────────────────────────────────────────────────
|
|
408
441
|
|
|
409
442
|
export function renderAgentsPage(
|
|
@@ -426,8 +459,20 @@ export function renderAgentsPage(
|
|
|
426
459
|
* mounts /admin/agents/:id/queue-activity; absent/false omits the link.
|
|
427
460
|
*/
|
|
428
461
|
queueActivityLinks?: boolean;
|
|
462
|
+
/** Admin-only account filter (Account selector above the table). */
|
|
463
|
+
accountFilter?: {
|
|
464
|
+
accounts: { id: string; name: string }[];
|
|
465
|
+
accountId?: string;
|
|
466
|
+
};
|
|
429
467
|
},
|
|
430
468
|
): string {
|
|
469
|
+
const accountFilterHtml =
|
|
470
|
+
isAdmin && opts?.accountFilter
|
|
471
|
+
? renderAccountFilter({
|
|
472
|
+
action: "/admin/agents",
|
|
473
|
+
...opts.accountFilter,
|
|
474
|
+
})
|
|
475
|
+
: "";
|
|
431
476
|
const showAccount = isAdmin && opts?.accountNames !== undefined;
|
|
432
477
|
const accountCell = (a: AgentListItem): string => {
|
|
433
478
|
if (!showAccount) return "";
|
|
@@ -490,6 +535,7 @@ export function renderAgentsPage(
|
|
|
490
535
|
</div>
|
|
491
536
|
${successHtml}
|
|
492
537
|
${manualStepsHtml}
|
|
538
|
+
${accountFilterHtml}
|
|
493
539
|
<div class="card">
|
|
494
540
|
<table class="data-table">
|
|
495
541
|
<thead>
|
|
@@ -2708,6 +2754,8 @@ export function renderProvisionXappTokenPage(
|
|
|
2708
2754
|
export interface AgentOption {
|
|
2709
2755
|
id: string;
|
|
2710
2756
|
name: string;
|
|
2757
|
+
/** Owning account; used by the admin account filter. */
|
|
2758
|
+
accountId?: string | null;
|
|
2711
2759
|
}
|
|
2712
2760
|
|
|
2713
2761
|
export function renderProvisionCompletePage(
|
|
@@ -3155,8 +3203,19 @@ export function renderChatPage(
|
|
|
3155
3203
|
threads: ChatThread[] | null,
|
|
3156
3204
|
userName: string,
|
|
3157
3205
|
q?: string,
|
|
3206
|
+
accountFilter?: {
|
|
3207
|
+
accounts: { id: string; name: string }[];
|
|
3208
|
+
accountId?: string;
|
|
3209
|
+
},
|
|
3158
3210
|
): string {
|
|
3159
3211
|
const activePath = "/admin/chat";
|
|
3212
|
+
const accountId = accountFilter?.accountId;
|
|
3213
|
+
const accountFilterHtml = accountFilter
|
|
3214
|
+
? renderAccountFilter({
|
|
3215
|
+
action: "/admin/chat",
|
|
3216
|
+
...accountFilter,
|
|
3217
|
+
})
|
|
3218
|
+
: "";
|
|
3160
3219
|
|
|
3161
3220
|
const agentOptions = agents
|
|
3162
3221
|
.map(
|
|
@@ -3167,6 +3226,7 @@ export function renderChatPage(
|
|
|
3167
3226
|
|
|
3168
3227
|
const agentSelector = `
|
|
3169
3228
|
<form method="GET" action="/admin/chat" class="form-row" style="margin-bottom:24px">
|
|
3229
|
+
${accountId ? `<input type="hidden" name="accountId" value="${escapeHtml(accountId)}">` : ""}
|
|
3170
3230
|
<div class="form-group" style="max-width:320px">
|
|
3171
3231
|
<label class="form-label" for="agentId">Agent</label>
|
|
3172
3232
|
<select name="agentId" id="agentId" class="form-input" onchange="this.form.submit()">
|
|
@@ -3196,6 +3256,7 @@ export function renderChatPage(
|
|
|
3196
3256
|
const searchForm = `
|
|
3197
3257
|
<form method="GET" action="/admin/chat" class="form-row" style="margin-bottom:16px">
|
|
3198
3258
|
<input type="hidden" name="agentId" value="${escapeHtml(selectedAgentId)}">
|
|
3259
|
+
${accountId ? `<input type="hidden" name="accountId" value="${escapeHtml(accountId)}">` : ""}
|
|
3199
3260
|
<div class="form-group" style="max-width:320px">
|
|
3200
3261
|
<input type="text" name="q" class="form-input" placeholder="Search threads…" value="${escapeHtml(q ?? "")}">
|
|
3201
3262
|
</div>
|
|
@@ -3249,6 +3310,7 @@ export function renderChatPage(
|
|
|
3249
3310
|
<div class="page-header">
|
|
3250
3311
|
<h1 class="page-title">Chat</h1>
|
|
3251
3312
|
</div>
|
|
3313
|
+
${accountFilterHtml}
|
|
3252
3314
|
${agentSelector}
|
|
3253
3315
|
${content}
|
|
3254
3316
|
</div>`,
|
package/src/admin-ui.ts
CHANGED
|
@@ -1011,6 +1011,23 @@ function normalizePluginSpec(spec: string): string {
|
|
|
1011
1011
|
return spec.includes("@") ? spec : `${spec}@${DEFAULT_PLUGIN_MARKETPLACE}`;
|
|
1012
1012
|
}
|
|
1013
1013
|
|
|
1014
|
+
interface AccountFilter {
|
|
1015
|
+
accounts: { id: string; name: string }[];
|
|
1016
|
+
accountId?: string;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/** Admin account filter state; an unknown accountId falls back to all accounts. */
|
|
1020
|
+
function adminAccountFilter(
|
|
1021
|
+
accounts: { id: string; name: string }[],
|
|
1022
|
+
requested: string | undefined,
|
|
1023
|
+
): AccountFilter {
|
|
1024
|
+
const list = accounts.map((a) => ({ id: a.id, name: a.name }));
|
|
1025
|
+
const accountId = list.some((a) => a.id === requested)
|
|
1026
|
+
? requested
|
|
1027
|
+
: undefined;
|
|
1028
|
+
return { accounts: list, accountId };
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1014
1031
|
export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
|
|
1015
1032
|
const {
|
|
1016
1033
|
prisma,
|
|
@@ -1708,17 +1725,21 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
|
|
|
1708
1725
|
}
|
|
1709
1726
|
// SSP-5.2: admins get an Account column.
|
|
1710
1727
|
let accountNames: Map<string, string> | undefined;
|
|
1728
|
+
let accountFilter: AccountFilter | undefined;
|
|
1729
|
+
let visibleAgents = agents;
|
|
1711
1730
|
if (c.var.isAdmin && accountServices) {
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1731
|
+
const accountList = await accountServices.accounts.listWithCounts();
|
|
1732
|
+
accountNames = new Map(accountList.map((a) => [a.id, a.name]));
|
|
1733
|
+
accountFilter = adminAccountFilter(accountList, c.req.query("accountId"));
|
|
1734
|
+
const selected = accountFilter.accountId;
|
|
1735
|
+
if (selected) {
|
|
1736
|
+
visibleAgents = agents.filter((a) => a.accountId === selected);
|
|
1737
|
+
}
|
|
1718
1738
|
}
|
|
1719
1739
|
return html(
|
|
1720
|
-
renderAgentsPage(
|
|
1740
|
+
renderAgentsPage(visibleAgents, c.var.userEmail, c.var.isAdmin, tzOf(c), {
|
|
1721
1741
|
accountNames,
|
|
1742
|
+
accountFilter,
|
|
1722
1743
|
queueActivityLinks: deps.queueActivityLinks,
|
|
1723
1744
|
successMsg,
|
|
1724
1745
|
manualSteps,
|
|
@@ -4926,25 +4947,48 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
|
|
|
4926
4947
|
}
|
|
4927
4948
|
|
|
4928
4949
|
app.get("/admin/chat", requireAuth, async (c) => {
|
|
4929
|
-
const
|
|
4950
|
+
const requestedAgentId = c.req.query("agentId") || undefined;
|
|
4930
4951
|
const q = c.req.query("q") || undefined;
|
|
4931
|
-
|
|
4932
|
-
|
|
4933
|
-
|
|
4952
|
+
// Admin account filter: narrows the agent picker only. Every thread,
|
|
4953
|
+
// message and upload route still goes through canAccessChat.
|
|
4954
|
+
let accountFilter: AccountFilter | undefined;
|
|
4955
|
+
let agents: AgentOption[];
|
|
4956
|
+
if (c.var.isAdmin) {
|
|
4957
|
+
agents = await agentService.listOptions();
|
|
4958
|
+
if (accountServices) {
|
|
4959
|
+
accountFilter = adminAccountFilter(
|
|
4960
|
+
await accountServices.accounts.listWithCounts(),
|
|
4961
|
+
c.req.query("accountId"),
|
|
4962
|
+
);
|
|
4963
|
+
const selected = accountFilter.accountId;
|
|
4964
|
+
if (selected) agents = agents.filter((a) => a.accountId === selected);
|
|
4965
|
+
}
|
|
4966
|
+
} else {
|
|
4967
|
+
agents = (await resolveAccessibleAgents(c.var.userEmail, false)).map(
|
|
4968
|
+
(a) => ({
|
|
4934
4969
|
id: a.id,
|
|
4935
4970
|
name: a.name,
|
|
4936
|
-
})
|
|
4937
|
-
|
|
4938
|
-
|
|
4939
|
-
|
|
4940
|
-
|
|
4941
|
-
) {
|
|
4971
|
+
}),
|
|
4972
|
+
);
|
|
4973
|
+
}
|
|
4974
|
+
const inList = agents.some((a) => a.id === requestedAgentId);
|
|
4975
|
+
if (requestedAgentId && !c.var.isAdmin && !inList) {
|
|
4942
4976
|
return new Response("Forbidden", { status: 403 });
|
|
4943
4977
|
}
|
|
4978
|
+
// An admin's stale agent from outside the selected account is ignored.
|
|
4979
|
+
const selectedAgentId =
|
|
4980
|
+
accountFilter?.accountId && !inList ? undefined : requestedAgentId;
|
|
4944
4981
|
|
|
4945
4982
|
if (!chatClient) {
|
|
4946
4983
|
return html(
|
|
4947
|
-
renderChatPage(
|
|
4984
|
+
renderChatPage(
|
|
4985
|
+
agents,
|
|
4986
|
+
selectedAgentId,
|
|
4987
|
+
null,
|
|
4988
|
+
c.var.userEmail,
|
|
4989
|
+
q,
|
|
4990
|
+
accountFilter,
|
|
4991
|
+
),
|
|
4948
4992
|
);
|
|
4949
4993
|
}
|
|
4950
4994
|
|
|
@@ -4966,7 +5010,14 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
|
|
|
4966
5010
|
}
|
|
4967
5011
|
|
|
4968
5012
|
return html(
|
|
4969
|
-
renderChatPage(
|
|
5013
|
+
renderChatPage(
|
|
5014
|
+
agents,
|
|
5015
|
+
selectedAgentId,
|
|
5016
|
+
threads,
|
|
5017
|
+
c.var.userEmail,
|
|
5018
|
+
q,
|
|
5019
|
+
accountFilter,
|
|
5020
|
+
),
|
|
4970
5021
|
);
|
|
4971
5022
|
});
|
|
4972
5023
|
|
package/src/agent-chat-tokens.ts
CHANGED
|
@@ -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(
|
|
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(
|
|
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
|
|
package/src/agents.ts
CHANGED
|
@@ -250,6 +250,8 @@ interface AgentIdAndRepos {
|
|
|
250
250
|
export interface AgentOption {
|
|
251
251
|
id: string;
|
|
252
252
|
name: string;
|
|
253
|
+
/** Owning account; present when the lister selects it (admin account filter). */
|
|
254
|
+
accountId?: string | null;
|
|
253
255
|
}
|
|
254
256
|
|
|
255
257
|
export interface UpdateAgentFieldsInput {
|
|
@@ -663,7 +665,7 @@ export class AgentService {
|
|
|
663
665
|
*/
|
|
664
666
|
async listOptions(): Promise<AgentOption[]> {
|
|
665
667
|
return this.prisma.agent.findMany({
|
|
666
|
-
select: { id: true, name: true },
|
|
668
|
+
select: { id: true, name: true, accountId: true },
|
|
667
669
|
orderBy: { name: "asc" },
|
|
668
670
|
});
|
|
669
671
|
}
|