import { Response } from 'express'; import { FallbackStep, RequestFallbackJourney } from './telemetryTracker'; export type LiveRequestStatus = 'streaming' | 'completed' | 'fallback_completed' | 'failed' | 'cancelled'; export interface LiveRequestInput { messages: any[]; model?: string; requestedModel?: string; temperature?: number; maxTokens?: number; topP?: number; rawBody?: any; } export interface LiveRequestOutput { completionText?: string; finishReason?: string; tokens?: { promptTokens: number; completionTokens: number; totalTokens: number; }; fullResponse?: any; error?: any; } export interface LiveRequestMetadata { headers?: Record; resolvedCustomModelId?: string; resolvedCustomModelName?: string; totalCandidatesAttempted: number; fallbackOccurred: boolean; servedBy?: { tierIndex: number; tierName: string; providerId: string; providerName: string; providerType: string; model: string; maskedKey: string; }; } export interface LiveRequestDebugEvent { time: string; message: string; level: 'info' | 'warn' | 'error'; details?: any; } export interface LiveRequestDebug { stepTraces: FallbackStep[]; keepAlivePingsCount: number; nonStreamingWhitespaceCount: number; events: LiveRequestDebugEvent[]; } export interface LiveRequestLogEntry { id: string; timestamp: string; startTime: number; endTime?: number; method: string; path: string; clientIp?: string; userAgent?: string; status: LiveRequestStatus; statusCode?: number; durationMs: number; isStreaming: boolean; input: LiveRequestInput; output: LiveRequestOutput; metadata: LiveRequestMetadata; debug: LiveRequestDebug; } export class LiveWatcher { private isWatcherActive: boolean = false; private buffer: LiveRequestLogEntry[] = []; private maxCapacity: number = 250; private sseClients: Set = new Set(); public isActive(): boolean { return this.isWatcherActive; } public toggleWatcher(enabled: boolean): { active: boolean; bufferCount: number } { this.isWatcherActive = enabled; if (!enabled) { // Flush memory immediately when toggled off this.flush(); } this.broadcast({ type: 'watcher_status', data: { active: this.isWatcherActive, bufferCount: this.buffer.length, maxCapacity: this.maxCapacity } }); return { active: this.isWatcherActive, bufferCount: this.buffer.length }; } public flush(): void { // Purge in-memory buffer to release RAM this.buffer = []; this.broadcast({ type: 'watcher_flushed', data: { bufferCount: 0 } }); } public getState(): { active: boolean; bufferCount: number; maxCapacity: number; memoryEstimateKb: number; } { // Rough estimate of buffer memory size let approxBytes = 0; try { approxBytes = JSON.stringify(this.buffer).length * 2; } catch { approxBytes = this.buffer.length * 1024; } return { active: this.isWatcherActive, bufferCount: this.buffer.length, maxCapacity: this.maxCapacity, memoryEstimateKb: Math.round(approxBytes / 1024) }; } public getEntries(params?: { status?: string; model?: string; search?: string; limit?: number; }): LiveRequestLogEntry[] { let result = [...this.buffer]; if (params?.status && params.status !== 'all') { result = result.filter(e => e.status === params.status); } if (params?.model && params.model !== 'all') { result = result.filter(e => { const reqModel = e.input.requestedModel || e.input.model || ''; const resModel = e.metadata.resolvedCustomModelName || ''; return reqModel.toLowerCase() === params.model!.toLowerCase() || resModel.toLowerCase() === params.model!.toLowerCase(); }); } if (params?.search && params.search.trim() !== '') { const q = params.search.toLowerCase().trim(); result = result.filter(e => { if (e.id.toLowerCase().includes(q)) return true; if ((e.input.requestedModel || '').toLowerCase().includes(q)) return true; if ((e.output.completionText || '').toLowerCase().includes(q)) return true; // Search inside messages if (Array.isArray(e.input.messages)) { for (const m of e.input.messages) { const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content || ''); if (content.toLowerCase().includes(q)) return true; } } return false; }); } const limit = params?.limit || 250; return result.slice(0, limit); } public startRequest(params: { requestId: string; method: string; path: string; clientIp?: string; userAgent?: string; isStreaming: boolean; body: any; }): void { if (!this.isWatcherActive) return; const entry: LiveRequestLogEntry = { id: params.requestId, timestamp: new Date().toISOString(), startTime: Date.now(), method: params.method, path: params.path, clientIp: params.clientIp, userAgent: params.userAgent, status: params.isStreaming ? 'streaming' : 'completed', // non-streaming will update on finish durationMs: 0, isStreaming: params.isStreaming, input: { messages: params.body?.messages || [], model: params.body?.model, requestedModel: params.body?.model, temperature: params.body?.temperature, maxTokens: params.body?.max_tokens, topP: params.body?.top_p, rawBody: params.body }, output: { completionText: '' }, metadata: { totalCandidatesAttempted: 0, fallbackOccurred: false }, debug: { stepTraces: [], keepAlivePingsCount: 0, nonStreamingWhitespaceCount: 0, events: [ { time: new Date().toISOString(), message: `Request received: ${params.method} ${params.path}`, level: 'info', details: { isStreaming: params.isStreaming, model: params.body?.model } } ] } }; // Prepend to buffer (newest first) this.buffer.unshift(entry); if (this.buffer.length > this.maxCapacity) { this.buffer.length = this.maxCapacity; } this.broadcast({ type: 'request_started', data: entry }); } public recordCandidateStep(requestId: string, step: FallbackStep): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === requestId); if (!entry) return; entry.debug.stepTraces.push(step); entry.metadata.totalCandidatesAttempted = entry.debug.stepTraces.length; if (entry.debug.stepTraces.length > 1) { entry.metadata.fallbackOccurred = true; } entry.debug.events.push({ time: new Date().toISOString(), message: `Candidate attempted: Tier ${step.tierIndex} ('${step.tierName}') Provider: ${step.providerName} (${step.providerType}) Key: ${step.maskedKey} -> ${step.status}`, level: step.status === 'success' ? 'info' : 'warn', details: { durationMs: step.durationMs, error: step.errorMessage, nextAction: step.nextAction } }); this.broadcast({ type: 'candidate_step', requestId, data: step }); } public recordKeepAlive(requestId: string, type: 'sse_comment' | 'whitespace'): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === requestId); if (!entry) return; if (type === 'sse_comment') { entry.debug.keepAlivePingsCount++; } else { entry.debug.nonStreamingWhitespaceCount++; } } public appendStreamChunk(requestId: string, chunkText: string): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === requestId); if (!entry) return; entry.output.completionText = (entry.output.completionText || '') + chunkText; entry.durationMs = Date.now() - entry.startTime; this.broadcast({ type: 'stream_chunk', requestId, chunkText, totalLength: entry.output.completionText.length, durationMs: entry.durationMs }); } public completeRequest(params: { requestId: string; statusCode?: number; journey?: RequestFallbackJourney; responseData?: any; tokens?: { promptTokens: number; completionTokens: number; totalTokens: number }; finishReason?: string; }): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === params.requestId); if (!entry) return; entry.endTime = Date.now(); entry.durationMs = entry.endTime - entry.startTime; entry.statusCode = params.statusCode || 200; const hadFallback = (params.journey?.steps?.length || 0) > 1 || entry.debug.stepTraces.length > 1; entry.status = hadFallback ? 'fallback_completed' : 'completed'; if (params.journey) { entry.metadata.resolvedCustomModelId = params.journey.resolvedModelId; entry.metadata.resolvedCustomModelName = params.journey.resolvedModelName; entry.metadata.fallbackOccurred = params.journey.fallbackOccurred; entry.metadata.totalCandidatesAttempted = params.journey.totalHops; if (params.journey.finalServedBy) { entry.metadata.servedBy = { tierIndex: params.journey.finalServedBy.tierIndex, tierName: params.journey.finalServedBy.tierName, providerId: '', providerName: params.journey.finalServedBy.providerName, providerType: params.journey.finalServedBy.providerType, model: params.journey.finalServedBy.model, maskedKey: params.journey.finalServedBy.maskedKey }; } } if (params.tokens) { entry.output.tokens = params.tokens; } if (params.finishReason) { entry.output.finishReason = params.finishReason; } if (params.responseData) { entry.output.fullResponse = params.responseData; if (!entry.output.completionText && params.responseData.choices?.[0]?.message?.content) { entry.output.completionText = params.responseData.choices[0].message.content; } if (!entry.output.finishReason && params.responseData.choices?.[0]?.finish_reason) { entry.output.finishReason = params.responseData.choices[0].finish_reason; } if (!entry.output.tokens && params.responseData.usage) { entry.output.tokens = { promptTokens: params.responseData.usage.prompt_tokens || 0, completionTokens: params.responseData.usage.completion_tokens || 0, totalTokens: params.responseData.usage.total_tokens || 0 }; } } entry.debug.events.push({ time: new Date().toISOString(), message: `Request completed successfully in ${entry.durationMs}ms`, level: 'info', details: { tokens: entry.output.tokens, status: entry.status, servedBy: entry.metadata.servedBy } }); this.broadcast({ type: 'request_completed', data: entry }); } public failRequest(params: { requestId: string; statusCode?: number; error: any; journey?: RequestFallbackJourney; }): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === params.requestId); if (!entry) return; entry.endTime = Date.now(); entry.durationMs = entry.endTime - entry.startTime; entry.status = 'failed'; entry.statusCode = params.statusCode || 500; entry.output.error = { message: params.error?.message || String(params.error), code: params.error?.code, type: params.error?.type }; if (params.journey) { entry.metadata.resolvedCustomModelId = params.journey.resolvedModelId; entry.metadata.resolvedCustomModelName = params.journey.resolvedModelName; entry.metadata.fallbackOccurred = params.journey.fallbackOccurred; entry.metadata.totalCandidatesAttempted = params.journey.totalHops; } entry.debug.events.push({ time: new Date().toISOString(), message: `Request failed after ${entry.durationMs}ms: ${params.error?.message || params.error}`, level: 'error', details: params.error }); this.broadcast({ type: 'request_failed', data: entry }); } public cancelRequest(requestId: string): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === requestId); if (!entry) return; entry.endTime = Date.now(); entry.durationMs = entry.endTime - entry.startTime; entry.status = 'cancelled'; entry.statusCode = 499; entry.debug.events.push({ time: new Date().toISOString(), message: 'Client closed connection before completion', level: 'warn' }); this.broadcast({ type: 'request_cancelled', data: entry }); } public subscribe(res: Response): void { res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); res.setHeader('Cache-Control', 'no-cache, no-transform'); res.setHeader('Connection', 'keep-alive'); res.setHeader('X-Accel-Buffering', 'no'); if (typeof res.flushHeaders === 'function') { res.flushHeaders(); } // Initial message const snapshot = { type: 'snapshot', state: this.getState(), entries: this.buffer.slice(0, 50), timestamp: new Date().toISOString() }; res.write(`data: ${JSON.stringify(snapshot)}\n\n`); this.sseClients.add(res); res.on('close', () => { this.sseClients.delete(res); }); } private broadcast(payload: any): void { if (this.sseClients.size === 0) return; const message = `data: ${JSON.stringify(payload)}\n\n`; for (const client of this.sseClients) { if (!client.destroyed && !client.writableEnded) { client.write(message); } else { this.sseClients.delete(client); } } } } export const liveWatcher = new LiveWatcher();