Spaces:
Runtime error
feat(#163): add Agent Self-Diagnostics API endpoint
Browse filesNew GET /api/agents/[id]/diagnostics endpoint enabling agents to
query their own performance data for self-optimization.
Sections (selectable via ?section= query param):
- summary: KPIs (throughput, error rate, activity count)
- tasks: completion breakdown by status/priority, throughput/day
- errors: error frequency by type, recent error details
- activity: activity breakdown with hourly timeline
- trends: current vs previous period comparison with auto-alerts
- tokens: token usage by model with cost totals
Features:
- Scoped to requesting agent only (no cross-agent data access)
- Configurable time window via ?hours= param (1-720h)
- Automatic trend alerts for error spikes, throughput drops, stalls
- Works with existing activities, tasks, and token_usage tables
Fixes #163
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
| 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]/diagnostics - Agent Self-Diagnostics API
|
| 8 |
+
*
|
| 9 |
+
* Provides an agent with its own performance metrics, error analysis,
|
| 10 |
+
* and trend data so it can self-optimize.
|
| 11 |
+
*
|
| 12 |
+
* Query params:
|
| 13 |
+
* hours - Time window in hours (default: 24, max: 720 = 30 days)
|
| 14 |
+
* section - Comma-separated sections to include (default: all)
|
| 15 |
+
* Options: summary, tasks, errors, activity, trends, tokens
|
| 16 |
+
*
|
| 17 |
+
* Response includes:
|
| 18 |
+
* summary - High-level KPIs (throughput, error rate, activity count)
|
| 19 |
+
* tasks - Task completion breakdown by status and priority
|
| 20 |
+
* errors - Error frequency, types, and recent error details
|
| 21 |
+
* activity - Activity breakdown by type with hourly timeline
|
| 22 |
+
* trends - Multi-period comparison for trend detection
|
| 23 |
+
* tokens - Token usage by model with cost estimates
|
| 24 |
+
*/
|
| 25 |
+
export async function GET(
|
| 26 |
+
request: NextRequest,
|
| 27 |
+
{ params }: { params: Promise<{ id: string }> }
|
| 28 |
+
) {
|
| 29 |
+
const auth = requireRole(request, 'viewer');
|
| 30 |
+
if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
|
| 31 |
+
|
| 32 |
+
try {
|
| 33 |
+
const db = getDatabase();
|
| 34 |
+
const resolvedParams = await params;
|
| 35 |
+
const agentId = resolvedParams.id;
|
| 36 |
+
const workspaceId = auth.user.workspace_id ?? 1;
|
| 37 |
+
|
| 38 |
+
// Resolve agent by ID or name
|
| 39 |
+
let agent: any;
|
| 40 |
+
if (/^\d+$/.test(agentId)) {
|
| 41 |
+
agent = db.prepare('SELECT id, name, role, status, last_seen, created_at FROM agents WHERE id = ? AND workspace_id = ?').get(Number(agentId), workspaceId);
|
| 42 |
+
} else {
|
| 43 |
+
agent = db.prepare('SELECT id, name, role, status, last_seen, created_at FROM agents WHERE name = ? AND workspace_id = ?').get(agentId, workspaceId);
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
if (!agent) {
|
| 47 |
+
return NextResponse.json({ error: 'Agent not found' }, { status: 404 });
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
const { searchParams } = new URL(request.url);
|
| 51 |
+
const hours = Math.min(Math.max(parseInt(searchParams.get('hours') || '24', 10) || 24, 1), 720);
|
| 52 |
+
const sectionParam = searchParams.get('section') || 'summary,tasks,errors,activity,trends,tokens';
|
| 53 |
+
const sections = new Set(sectionParam.split(',').map(s => s.trim()));
|
| 54 |
+
|
| 55 |
+
const now = Math.floor(Date.now() / 1000);
|
| 56 |
+
const since = now - hours * 3600;
|
| 57 |
+
|
| 58 |
+
const result: Record<string, any> = {
|
| 59 |
+
agent: { id: agent.id, name: agent.name, role: agent.role, status: agent.status },
|
| 60 |
+
timeframe: { hours, since, until: now },
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
if (sections.has('summary')) {
|
| 64 |
+
result.summary = buildSummary(db, agent.name, workspaceId, since);
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
if (sections.has('tasks')) {
|
| 68 |
+
result.tasks = buildTaskMetrics(db, agent.name, workspaceId, since);
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
if (sections.has('errors')) {
|
| 72 |
+
result.errors = buildErrorAnalysis(db, agent.name, workspaceId, since);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
if (sections.has('activity')) {
|
| 76 |
+
result.activity = buildActivityBreakdown(db, agent.name, workspaceId, since);
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
if (sections.has('trends')) {
|
| 80 |
+
result.trends = buildTrends(db, agent.name, workspaceId, hours);
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
if (sections.has('tokens')) {
|
| 84 |
+
result.tokens = buildTokenMetrics(db, agent.name, workspaceId, since);
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
return NextResponse.json(result);
|
| 88 |
+
} catch (error) {
|
| 89 |
+
logger.error({ err: error }, 'GET /api/agents/[id]/diagnostics error');
|
| 90 |
+
return NextResponse.json({ error: 'Failed to fetch diagnostics' }, { status: 500 });
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
/** High-level KPIs */
|
| 95 |
+
function buildSummary(db: any, agentName: string, workspaceId: number, since: number) {
|
| 96 |
+
const tasksDone = (db.prepare(
|
| 97 |
+
`SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ?`
|
| 98 |
+
).get(agentName, workspaceId, since) as any).c;
|
| 99 |
+
|
| 100 |
+
const tasksTotal = (db.prepare(
|
| 101 |
+
`SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ?`
|
| 102 |
+
).get(agentName, workspaceId) as any).c;
|
| 103 |
+
|
| 104 |
+
const activityCount = (db.prepare(
|
| 105 |
+
`SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ?`
|
| 106 |
+
).get(agentName, workspaceId, since) as any).c;
|
| 107 |
+
|
| 108 |
+
const errorCount = (db.prepare(
|
| 109 |
+
`SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND type LIKE '%error%'`
|
| 110 |
+
).get(agentName, workspaceId, since) as any).c;
|
| 111 |
+
|
| 112 |
+
const errorRate = activityCount > 0 ? Math.round((errorCount / activityCount) * 10000) / 100 : 0;
|
| 113 |
+
|
| 114 |
+
return {
|
| 115 |
+
tasks_completed: tasksDone,
|
| 116 |
+
tasks_total: tasksTotal,
|
| 117 |
+
activity_count: activityCount,
|
| 118 |
+
error_count: errorCount,
|
| 119 |
+
error_rate_percent: errorRate,
|
| 120 |
+
};
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/** Task completion breakdown */
|
| 124 |
+
function buildTaskMetrics(db: any, agentName: string, workspaceId: number, since: number) {
|
| 125 |
+
const byStatus = db.prepare(
|
| 126 |
+
`SELECT status, COUNT(*) as count FROM tasks WHERE assigned_to = ? AND workspace_id = ? GROUP BY status`
|
| 127 |
+
).all(agentName, workspaceId) as Array<{ status: string; count: number }>;
|
| 128 |
+
|
| 129 |
+
const byPriority = db.prepare(
|
| 130 |
+
`SELECT priority, COUNT(*) as count FROM tasks WHERE assigned_to = ? AND workspace_id = ? GROUP BY priority`
|
| 131 |
+
).all(agentName, workspaceId) as Array<{ priority: string; count: number }>;
|
| 132 |
+
|
| 133 |
+
const recentCompleted = db.prepare(
|
| 134 |
+
`SELECT id, title, priority, updated_at FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ? ORDER BY updated_at DESC LIMIT 10`
|
| 135 |
+
).all(agentName, workspaceId, since) as any[];
|
| 136 |
+
|
| 137 |
+
// Estimate throughput: tasks completed per day in the window
|
| 138 |
+
const windowDays = Math.max((Math.floor(Date.now() / 1000) - since) / 86400, 1);
|
| 139 |
+
const completedInWindow = recentCompleted.length;
|
| 140 |
+
const throughputPerDay = Math.round((completedInWindow / windowDays) * 100) / 100;
|
| 141 |
+
|
| 142 |
+
return {
|
| 143 |
+
by_status: Object.fromEntries(byStatus.map(r => [r.status, r.count])),
|
| 144 |
+
by_priority: Object.fromEntries(byPriority.map(r => [r.priority, r.count])),
|
| 145 |
+
recent_completed: recentCompleted,
|
| 146 |
+
throughput_per_day: throughputPerDay,
|
| 147 |
+
};
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
/** Error frequency and analysis */
|
| 151 |
+
function buildErrorAnalysis(db: any, agentName: string, workspaceId: number, since: number) {
|
| 152 |
+
const errorActivities = db.prepare(
|
| 153 |
+
`SELECT type, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%') GROUP BY type ORDER BY count DESC`
|
| 154 |
+
).all(agentName, workspaceId, since) as Array<{ type: string; count: number }>;
|
| 155 |
+
|
| 156 |
+
const recentErrors = db.prepare(
|
| 157 |
+
`SELECT id, type, description, data, created_at FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%') ORDER BY created_at DESC LIMIT 20`
|
| 158 |
+
).all(agentName, workspaceId, since) as any[];
|
| 159 |
+
|
| 160 |
+
return {
|
| 161 |
+
by_type: errorActivities,
|
| 162 |
+
total: errorActivities.reduce((sum, e) => sum + e.count, 0),
|
| 163 |
+
recent: recentErrors.map(e => ({
|
| 164 |
+
...e,
|
| 165 |
+
data: e.data ? JSON.parse(e.data) : null,
|
| 166 |
+
})),
|
| 167 |
+
};
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
/** Activity breakdown with hourly timeline */
|
| 171 |
+
function buildActivityBreakdown(db: any, agentName: string, workspaceId: number, since: number) {
|
| 172 |
+
const byType = db.prepare(
|
| 173 |
+
`SELECT type, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? GROUP BY type ORDER BY count DESC`
|
| 174 |
+
).all(agentName, workspaceId, since) as Array<{ type: string; count: number }>;
|
| 175 |
+
|
| 176 |
+
const timeline = db.prepare(
|
| 177 |
+
`SELECT (created_at / 3600) * 3600 as hour_bucket, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? GROUP BY hour_bucket ORDER BY hour_bucket ASC`
|
| 178 |
+
).all(agentName, workspaceId, since) as Array<{ hour_bucket: number; count: number }>;
|
| 179 |
+
|
| 180 |
+
return {
|
| 181 |
+
by_type: byType,
|
| 182 |
+
timeline: timeline.map(t => ({
|
| 183 |
+
timestamp: t.hour_bucket,
|
| 184 |
+
hour: new Date(t.hour_bucket * 1000).toISOString(),
|
| 185 |
+
count: t.count,
|
| 186 |
+
})),
|
| 187 |
+
};
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
/** Multi-period trend comparison for anomaly/trend detection */
|
| 191 |
+
function buildTrends(db: any, agentName: string, workspaceId: number, hours: number) {
|
| 192 |
+
const now = Math.floor(Date.now() / 1000);
|
| 193 |
+
|
| 194 |
+
// Compare current period vs previous period of same length
|
| 195 |
+
const currentSince = now - hours * 3600;
|
| 196 |
+
const previousSince = currentSince - hours * 3600;
|
| 197 |
+
|
| 198 |
+
const periodMetrics = (since: number, until: number) => {
|
| 199 |
+
const activities = (db.prepare(
|
| 200 |
+
`SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND created_at < ?`
|
| 201 |
+
).get(agentName, workspaceId, since, until) as any).c;
|
| 202 |
+
|
| 203 |
+
const errors = (db.prepare(
|
| 204 |
+
`SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND created_at < ? AND (type LIKE '%error%' OR type LIKE '%fail%')`
|
| 205 |
+
).get(agentName, workspaceId, since, until) as any).c;
|
| 206 |
+
|
| 207 |
+
const tasksCompleted = (db.prepare(
|
| 208 |
+
`SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ? AND updated_at < ?`
|
| 209 |
+
).get(agentName, workspaceId, since, until) as any).c;
|
| 210 |
+
|
| 211 |
+
return { activities, errors, tasks_completed: tasksCompleted };
|
| 212 |
+
};
|
| 213 |
+
|
| 214 |
+
const current = periodMetrics(currentSince, now);
|
| 215 |
+
const previous = periodMetrics(previousSince, currentSince);
|
| 216 |
+
|
| 217 |
+
const pctChange = (cur: number, prev: number) => {
|
| 218 |
+
if (prev === 0) return cur > 0 ? 100 : 0;
|
| 219 |
+
return Math.round(((cur - prev) / prev) * 10000) / 100;
|
| 220 |
+
};
|
| 221 |
+
|
| 222 |
+
return {
|
| 223 |
+
current_period: { since: currentSince, until: now, ...current },
|
| 224 |
+
previous_period: { since: previousSince, until: currentSince, ...previous },
|
| 225 |
+
change: {
|
| 226 |
+
activities_pct: pctChange(current.activities, previous.activities),
|
| 227 |
+
errors_pct: pctChange(current.errors, previous.errors),
|
| 228 |
+
tasks_completed_pct: pctChange(current.tasks_completed, previous.tasks_completed),
|
| 229 |
+
},
|
| 230 |
+
alerts: buildTrendAlerts(current, previous),
|
| 231 |
+
};
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
/** Generate automatic alerts from trend data */
|
| 235 |
+
function buildTrendAlerts(current: { activities: number; errors: number; tasks_completed: number }, previous: { activities: number; errors: number; tasks_completed: number }) {
|
| 236 |
+
const alerts: Array<{ level: string; message: string }> = [];
|
| 237 |
+
|
| 238 |
+
// Error rate spike
|
| 239 |
+
if (current.errors > 0 && previous.errors > 0) {
|
| 240 |
+
const errorIncrease = (current.errors - previous.errors) / previous.errors;
|
| 241 |
+
if (errorIncrease > 0.5) {
|
| 242 |
+
alerts.push({ level: 'warning', message: `Error count increased ${Math.round(errorIncrease * 100)}% vs previous period` });
|
| 243 |
+
}
|
| 244 |
+
} else if (current.errors > 3 && previous.errors === 0) {
|
| 245 |
+
alerts.push({ level: 'warning', message: `New error pattern: ${current.errors} errors (none in previous period)` });
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
// Throughput drop
|
| 249 |
+
if (previous.tasks_completed > 0 && current.tasks_completed === 0) {
|
| 250 |
+
alerts.push({ level: 'info', message: 'No tasks completed in current period (possible stall)' });
|
| 251 |
+
} else if (previous.tasks_completed > 2 && current.tasks_completed < previous.tasks_completed * 0.5) {
|
| 252 |
+
alerts.push({ level: 'info', message: `Task throughput dropped ${Math.round((1 - current.tasks_completed / previous.tasks_completed) * 100)}%` });
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
// Activity drop (possible offline)
|
| 256 |
+
if (previous.activities > 5 && current.activities < previous.activities * 0.25) {
|
| 257 |
+
alerts.push({ level: 'warning', message: `Activity dropped ${Math.round((1 - current.activities / previous.activities) * 100)}% — agent may be stalled` });
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
return alerts;
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
/** Token usage by model */
|
| 264 |
+
function buildTokenMetrics(db: any, agentName: string, workspaceId: number, since: number) {
|
| 265 |
+
try {
|
| 266 |
+
// session_id on token_usage may store agent name or session key
|
| 267 |
+
const byModel = db.prepare(
|
| 268 |
+
`SELECT model, SUM(input_tokens) as input_tokens, SUM(output_tokens) as output_tokens, COUNT(*) as request_count FROM token_usage WHERE session_id = ? AND workspace_id = ? AND created_at >= ? GROUP BY model ORDER BY (input_tokens + output_tokens) DESC`
|
| 269 |
+
).all(agentName, workspaceId, since) as Array<{ model: string; input_tokens: number; output_tokens: number; request_count: number }>;
|
| 270 |
+
|
| 271 |
+
const total = byModel.reduce((acc, r) => ({
|
| 272 |
+
input_tokens: acc.input_tokens + r.input_tokens,
|
| 273 |
+
output_tokens: acc.output_tokens + r.output_tokens,
|
| 274 |
+
requests: acc.requests + r.request_count,
|
| 275 |
+
}), { input_tokens: 0, output_tokens: 0, requests: 0 });
|
| 276 |
+
|
| 277 |
+
return {
|
| 278 |
+
by_model: byModel,
|
| 279 |
+
total,
|
| 280 |
+
};
|
| 281 |
+
} catch {
|
| 282 |
+
// token_usage table may not exist
|
| 283 |
+
return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 } };
|
| 284 |
+
}
|
| 285 |
+
}
|