import type { FastifyInstance } from 'fastify'; import type { Sql } from '../db.js'; // token-analyzer-ui: context window utilization and token breakdown data. // v1 — global aggregates only. export interface ContextWindowStats { avg_ctx_used: number | null; avg_ctx_max: number | null; avg_utilization_pct: number | null; message_count: number; } export function registerAnalyticsRoutes(app: FastifyInstance, sql: Sql): void { // GET /api/analytics/context — average context window utilization across // completed assistant messages that carry ctx_used/ctx_max. app.get('/api/analytics/context', async () => { const [row] = await sql` SELECT AVG(ctx_used)::DOUBLE PRECISION AS avg_ctx_used, AVG(ctx_max)::DOUBLE PRECISION AS avg_ctx_max, AVG(ctx_used::float / NULLIF(ctx_max, 0))::DOUBLE PRECISION AS avg_utilization_pct, COUNT(*)::INT AS message_count FROM messages WHERE role = 'assistant' AND status = 'complete' AND ctx_used IS NOT NULL AND ctx_max IS NOT NULL AND ctx_max > 0 `; return row ?? { avg_ctx_used: null, avg_ctx_max: null, avg_utilization_pct: null, message_count: 0 }; }); }