bhavikprit commited on
Commit
659dcd6
·
1 Parent(s): 6331d61

feat(#159): add Agent-Level Identity & Attribution

Browse files

- Add agent_name field to User interface for agent-level tracking
- Extract X-Agent-Name header in getUserFromRequest for attribution
- New GET /api/agents/[id]/attribution endpoint with sections:
- identity: agent profile, lifetime stats, session info
- audit: full activity trail + audit log entries for the agent
- mutations: task changes, comments, status transitions attributed
- cost: token usage by model with daily trend breakdown
- Backward compatible: X-Agent-Name is optional, existing auth unchanged

Fixes #159

src/app/api/agents/[id]/attribution/route.ts ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { getDatabase } from '@/lib/db';
3
+ import { requireRole } from '@/lib/auth';
4
+ import { logger } from '@/lib/logger';
5
+
6
+ /**
7
+ * GET /api/agents/[id]/attribution - Agent-Level Identity & Attribution
8
+ *
9
+ * Returns a comprehensive audit trail and cost attribution report for
10
+ * a specific agent. Enables per-agent observability, debugging, and
11
+ * cost analysis in multi-agent environments.
12
+ *
13
+ * Query params:
14
+ * hours - Time window (default: 24, max: 720)
15
+ * section - Comma-separated: audit,cost,mutations,identity (default: all)
16
+ *
17
+ * Response:
18
+ * identity - Agent profile, status, and session info
19
+ * audit - Full audit trail of agent actions
20
+ * mutations - Task/memory/soul changes attributed to this agent
21
+ * cost - Token usage and cost breakdown per model
22
+ */
23
+ export async function GET(
24
+ request: NextRequest,
25
+ { params }: { params: Promise<{ id: string }> }
26
+ ) {
27
+ const auth = requireRole(request, 'viewer');
28
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
29
+
30
+ try {
31
+ const db = getDatabase();
32
+ const resolvedParams = await params;
33
+ const agentId = resolvedParams.id;
34
+ const workspaceId = auth.user.workspace_id ?? 1;
35
+
36
+ // Resolve agent
37
+ let agent: any;
38
+ if (/^\d+$/.test(agentId)) {
39
+ agent = db.prepare('SELECT * FROM agents WHERE id = ? AND workspace_id = ?').get(Number(agentId), workspaceId);
40
+ } else {
41
+ agent = db.prepare('SELECT * FROM agents WHERE name = ? AND workspace_id = ?').get(agentId, workspaceId);
42
+ }
43
+
44
+ if (!agent) {
45
+ return NextResponse.json({ error: 'Agent not found' }, { status: 404 });
46
+ }
47
+
48
+ const { searchParams } = new URL(request.url);
49
+ const hours = Math.min(Math.max(parseInt(searchParams.get('hours') || '24', 10) || 24, 1), 720);
50
+ const sectionParam = searchParams.get('section') || 'identity,audit,mutations,cost';
51
+ const sections = new Set(sectionParam.split(',').map(s => s.trim()));
52
+
53
+ const now = Math.floor(Date.now() / 1000);
54
+ const since = now - hours * 3600;
55
+
56
+ const result: Record<string, any> = {
57
+ agent_name: agent.name,
58
+ timeframe: { hours, since, until: now },
59
+ };
60
+
61
+ if (sections.has('identity')) {
62
+ result.identity = buildIdentity(db, agent, workspaceId);
63
+ }
64
+
65
+ if (sections.has('audit')) {
66
+ result.audit = buildAuditTrail(db, agent.name, workspaceId, since);
67
+ }
68
+
69
+ if (sections.has('mutations')) {
70
+ result.mutations = buildMutations(db, agent.name, workspaceId, since);
71
+ }
72
+
73
+ if (sections.has('cost')) {
74
+ result.cost = buildCostAttribution(db, agent.name, workspaceId, since);
75
+ }
76
+
77
+ return NextResponse.json(result);
78
+ } catch (error) {
79
+ logger.error({ err: error }, 'GET /api/agents/[id]/attribution error');
80
+ return NextResponse.json({ error: 'Failed to fetch attribution data' }, { status: 500 });
81
+ }
82
+ }
83
+
84
+ /** Agent identity and profile info */
85
+ function buildIdentity(db: any, agent: any, workspaceId: number) {
86
+ const config = agent.config ? JSON.parse(agent.config) : {};
87
+
88
+ // Count total tasks ever assigned
89
+ const taskStats = db.prepare(`
90
+ SELECT
91
+ COUNT(*) as total,
92
+ SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as completed,
93
+ SUM(CASE WHEN status IN ('assigned', 'in_progress') THEN 1 ELSE 0 END) as active
94
+ FROM tasks WHERE assigned_to = ? AND workspace_id = ?
95
+ `).get(agent.name, workspaceId) as any;
96
+
97
+ // Count comments authored
98
+ const commentCount = (db.prepare(
99
+ `SELECT COUNT(*) as c FROM comments WHERE author = ? AND workspace_id = ?`
100
+ ).get(agent.name, workspaceId) as any).c;
101
+
102
+ return {
103
+ id: agent.id,
104
+ name: agent.name,
105
+ role: agent.role,
106
+ status: agent.status,
107
+ last_seen: agent.last_seen,
108
+ last_activity: agent.last_activity,
109
+ created_at: agent.created_at,
110
+ session_key: agent.session_key ? '***' : null, // Masked for security
111
+ has_soul: !!agent.soul_content,
112
+ config_keys: Object.keys(config),
113
+ lifetime_stats: {
114
+ tasks_total: taskStats?.total || 0,
115
+ tasks_completed: taskStats?.completed || 0,
116
+ tasks_active: taskStats?.active || 0,
117
+ comments_authored: commentCount,
118
+ },
119
+ };
120
+ }
121
+
122
+ /** Audit trail — all activities attributed to this agent */
123
+ function buildAuditTrail(db: any, agentName: string, workspaceId: number, since: number) {
124
+ // Activities where this agent is the actor
125
+ const activities = db.prepare(`
126
+ SELECT id, type, entity_type, entity_id, description, data, created_at
127
+ FROM activities
128
+ WHERE actor = ? AND workspace_id = ? AND created_at >= ?
129
+ ORDER BY created_at DESC
130
+ LIMIT 200
131
+ `).all(agentName, workspaceId, since) as any[];
132
+
133
+ // Audit log entries (system-wide, may reference agent)
134
+ let auditEntries: any[] = [];
135
+ try {
136
+ auditEntries = db.prepare(`
137
+ SELECT id, action, actor, detail, created_at
138
+ FROM audit_log
139
+ WHERE (actor = ? OR detail LIKE ?) AND created_at >= ?
140
+ ORDER BY created_at DESC
141
+ LIMIT 100
142
+ `).all(agentName, `%${agentName}%`, since) as any[];
143
+ } catch {
144
+ // audit_log table may not exist
145
+ }
146
+
147
+ // Group activities by type for summary
148
+ const byType: Record<string, number> = {};
149
+ for (const a of activities) {
150
+ byType[a.type] = (byType[a.type] || 0) + 1;
151
+ }
152
+
153
+ return {
154
+ total_activities: activities.length,
155
+ by_type: byType,
156
+ activities: activities.map(a => ({
157
+ ...a,
158
+ data: a.data ? JSON.parse(a.data) : null,
159
+ })),
160
+ audit_log_entries: auditEntries.map(e => ({
161
+ ...e,
162
+ detail: e.detail ? JSON.parse(e.detail) : null,
163
+ })),
164
+ };
165
+ }
166
+
167
+ /** Mutations — task changes, comments, status transitions */
168
+ function buildMutations(db: any, agentName: string, workspaceId: number, since: number) {
169
+ // Task mutations (created, updated, status changes)
170
+ const taskMutations = db.prepare(`
171
+ SELECT id, type, entity_type, entity_id, description, data, created_at
172
+ FROM activities
173
+ WHERE actor = ? AND workspace_id = ? AND created_at >= ?
174
+ AND entity_type = 'task'
175
+ AND type IN ('task_created', 'task_updated', 'task_status_change', 'task_assigned')
176
+ ORDER BY created_at DESC
177
+ LIMIT 100
178
+ `).all(agentName, workspaceId, since) as any[];
179
+
180
+ // Comments authored
181
+ const comments = db.prepare(`
182
+ SELECT c.id, c.task_id, c.content, c.created_at, c.mentions, t.title as task_title
183
+ FROM comments c
184
+ LEFT JOIN tasks t ON c.task_id = t.id AND t.workspace_id = ?
185
+ WHERE c.author = ? AND c.workspace_id = ? AND c.created_at >= ?
186
+ ORDER BY c.created_at DESC
187
+ LIMIT 50
188
+ `).all(workspaceId, agentName, workspaceId, since) as any[];
189
+
190
+ // Agent status changes (by heartbeat or others)
191
+ const statusChanges = db.prepare(`
192
+ SELECT id, type, description, data, created_at
193
+ FROM activities
194
+ WHERE entity_type = 'agent' AND workspace_id = ?
195
+ AND created_at >= ?
196
+ AND (actor = ? OR description LIKE ?)
197
+ ORDER BY created_at DESC
198
+ LIMIT 50
199
+ `).all(workspaceId, since, agentName, `%${agentName}%`) as any[];
200
+
201
+ return {
202
+ task_mutations: taskMutations.map(m => ({
203
+ ...m,
204
+ data: m.data ? JSON.parse(m.data) : null,
205
+ })),
206
+ comments: comments.map(c => ({
207
+ ...c,
208
+ mentions: c.mentions ? JSON.parse(c.mentions) : [],
209
+ content_preview: c.content?.substring(0, 200) || '',
210
+ })),
211
+ status_changes: statusChanges.map(s => ({
212
+ ...s,
213
+ data: s.data ? JSON.parse(s.data) : null,
214
+ })),
215
+ summary: {
216
+ task_mutations_count: taskMutations.length,
217
+ comments_count: comments.length,
218
+ status_changes_count: statusChanges.length,
219
+ },
220
+ };
221
+ }
222
+
223
+ /** Cost attribution — token usage per model */
224
+ function buildCostAttribution(db: any, agentName: string, workspaceId: number, since: number) {
225
+ try {
226
+ const byModel = db.prepare(`
227
+ SELECT model,
228
+ COUNT(*) as request_count,
229
+ SUM(input_tokens) as input_tokens,
230
+ SUM(output_tokens) as output_tokens
231
+ FROM token_usage
232
+ WHERE session_id = ? AND workspace_id = ? AND created_at >= ?
233
+ GROUP BY model
234
+ ORDER BY (input_tokens + output_tokens) DESC
235
+ `).all(agentName, workspaceId, since) as Array<{
236
+ model: string; request_count: number; input_tokens: number; output_tokens: number
237
+ }>;
238
+
239
+ // Also check session IDs that contain the agent name (e.g. "agentname:cli")
240
+ const byModelAlt = db.prepare(`
241
+ SELECT model,
242
+ COUNT(*) as request_count,
243
+ SUM(input_tokens) as input_tokens,
244
+ SUM(output_tokens) as output_tokens
245
+ FROM token_usage
246
+ WHERE session_id LIKE ? AND session_id != ? AND workspace_id = ? AND created_at >= ?
247
+ GROUP BY model
248
+ ORDER BY (input_tokens + output_tokens) DESC
249
+ `).all(`${agentName}:%`, agentName, workspaceId, since) as Array<{
250
+ model: string; request_count: number; input_tokens: number; output_tokens: number
251
+ }>;
252
+
253
+ // Merge results
254
+ const merged = new Map<string, { model: string; request_count: number; input_tokens: number; output_tokens: number }>();
255
+ for (const row of [...byModel, ...byModelAlt]) {
256
+ const existing = merged.get(row.model);
257
+ if (existing) {
258
+ existing.request_count += row.request_count;
259
+ existing.input_tokens += row.input_tokens;
260
+ existing.output_tokens += row.output_tokens;
261
+ } else {
262
+ merged.set(row.model, { ...row });
263
+ }
264
+ }
265
+
266
+ const models = Array.from(merged.values());
267
+ const total = models.reduce((acc, r) => ({
268
+ input_tokens: acc.input_tokens + r.input_tokens,
269
+ output_tokens: acc.output_tokens + r.output_tokens,
270
+ requests: acc.requests + r.request_count,
271
+ }), { input_tokens: 0, output_tokens: 0, requests: 0 });
272
+
273
+ // Daily breakdown for trend
274
+ const daily = db.prepare(`
275
+ SELECT (created_at / 86400) * 86400 as day_bucket,
276
+ SUM(input_tokens) as input_tokens,
277
+ SUM(output_tokens) as output_tokens,
278
+ COUNT(*) as requests
279
+ FROM token_usage
280
+ WHERE (session_id = ? OR session_id LIKE ?) AND workspace_id = ? AND created_at >= ?
281
+ GROUP BY day_bucket
282
+ ORDER BY day_bucket ASC
283
+ `).all(agentName, `${agentName}:%`, workspaceId, since) as any[];
284
+
285
+ return {
286
+ by_model: models,
287
+ total,
288
+ daily_trend: daily.map(d => ({
289
+ date: new Date(d.day_bucket * 1000).toISOString().split('T')[0],
290
+ ...d,
291
+ })),
292
+ };
293
+ } catch {
294
+ return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 }, daily_trend: [] };
295
+ }
296
+ }
src/lib/auth.ts CHANGED
@@ -31,6 +31,8 @@ export interface User {
31
  created_at: number
32
  updated_at: number
33
  last_login_at: number | null
 
 
34
  }
35
 
36
  export interface UserSession {
@@ -268,12 +270,15 @@ export function deleteUser(id: number): boolean {
268
  * For API key auth, returns a synthetic "api" user.
269
  */
270
  export function getUserFromRequest(request: Request): User | null {
 
 
 
271
  // Check session cookie
272
  const cookieHeader = request.headers.get('cookie') || ''
273
  const sessionToken = parseCookie(cookieHeader, 'mc-session')
274
  if (sessionToken) {
275
  const user = validateSession(sessionToken)
276
- if (user) return user
277
  }
278
 
279
  // Check API key - return synthetic user
@@ -289,6 +294,7 @@ export function getUserFromRequest(request: Request): User | null {
289
  created_at: 0,
290
  updated_at: 0,
291
  last_login_at: null,
 
292
  }
293
  }
294
 
 
31
  created_at: number
32
  updated_at: number
33
  last_login_at: number | null
34
+ /** Agent name when request is made on behalf of a specific agent (via X-Agent-Name header) */
35
+ agent_name?: string | null
36
  }
37
 
38
  export interface UserSession {
 
270
  * For API key auth, returns a synthetic "api" user.
271
  */
272
  export function getUserFromRequest(request: Request): User | null {
273
+ // Extract agent identity header (optional, for attribution)
274
+ const agentName = (request.headers.get('x-agent-name') || '').trim() || null
275
+
276
  // Check session cookie
277
  const cookieHeader = request.headers.get('cookie') || ''
278
  const sessionToken = parseCookie(cookieHeader, 'mc-session')
279
  if (sessionToken) {
280
  const user = validateSession(sessionToken)
281
+ if (user) return { ...user, agent_name: agentName }
282
  }
283
 
284
  // Check API key - return synthetic user
 
294
  created_at: 0,
295
  updated_at: 0,
296
  last_login_at: null,
297
+ agent_name: agentName,
298
  }
299
  }
300