diff --git a/README.md b/README.md index 1db4ca5..283f298 100644 --- a/README.md +++ b/README.md @@ -163,8 +163,7 @@ Navigate to `http://localhost:3000/admin` in your web browser. - **Tier 2 (Fallback 2):** Additional fallbacks if defined. - Designate a **Default Model** to handle requests that omit or supply an unknown model identifier. 4. **Revolver Playground:** Test prompt execution live and inspect trace metadata (which tier, provider, model, key, and latency were used). -5. **Live Key & Model Fallback Telemetry:** Real-time visibility into active keys, rate-limit cooldown timers, success rates, and live visual breadcrumb tracking of model routing cascades showing where and why models failed, how it fell back across keys and tiers, and what happened next. -6. **Live Request Log Watcher:** In-memory (RAM-only) interactive request inspector. Toggle ON to capture live incoming and served requests with full input prompts, assistant completions (including real-time streaming chunks), metadata, and debug failover traces. Safely capped in a 250-item FIFO buffer, and completely flushes RAM upon toggling OFF. Includes real-time search, status/model filters, and JSON export. +5. **Live Key Telemetry:** Real-time visibility into active keys, rate-limit cooldown timers, and request/error counters. All provider credentials and custom model definitions are persisted automatically in `data/revolver-config.json`. diff --git a/package.json b/package.json index 8127935..9a1add4 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "start": "node dist/index.js", "dev": "ts-node src/index.ts", "watch": "tsc --watch", - "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts" + "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts" }, "keywords": ["openai", "gemini", "api", "rotation"], "author": "", diff --git a/src/adminRoutes.ts b/src/adminRoutes.ts index 4096ff2..6eb89bb 100644 --- a/src/adminRoutes.ts +++ b/src/adminRoutes.ts @@ -2,8 +2,6 @@ import { Router, Request, Response } from 'express'; import { configStore } from './configStore'; import { revolverEngine } from './revolverEngine'; import { ProviderType } from './revolverTypes'; -import { liveWatcher } from './liveWatcher'; -import { telemetryTracker } from './telemetryTracker'; const router = Router(); @@ -189,54 +187,4 @@ router.get('/keys-status', (req: Request, res: Response) => { res.json({ providers: status, timestamp: new Date().toISOString() }); }); -// GET /api/admin/live-logs/state -router.get('/live-logs/state', (req: Request, res: Response) => { - res.json(liveWatcher.getState()); -}); - -// POST /api/admin/live-logs/toggle -router.post('/live-logs/toggle', (req: Request, res: Response) => { - const { enabled } = req.body; - const result = liveWatcher.toggleWatcher(!!enabled); - res.json(result); -}); - -// POST /api/admin/live-logs/flush -router.post('/live-logs/flush', (req: Request, res: Response) => { - liveWatcher.flush(); - res.json({ success: true, message: 'Live request logs flushed from RAM.' }); -}); - -// GET /api/admin/live-logs/entries -router.get('/live-logs/entries', (req: Request, res: Response) => { - const status = req.query.status as string | undefined; - const model = req.query.model as string | undefined; - const search = req.query.search as string | undefined; - const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 100; - const entries = liveWatcher.getEntries({ status, model, search, limit }); - res.json({ - state: liveWatcher.getState(), - entries - }); -}); - -// GET /api/admin/live-logs/stream (SSE) -router.get('/live-logs/stream', (req: Request, res: Response) => { - liveWatcher.subscribe(res); -}); - -// GET /api/admin/telemetry/fallback-traces -router.get('/telemetry/fallback-traces', (req: Request, res: Response) => { - const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 50; - res.json({ - journeys: telemetryTracker.getRecentJourneys(limit), - keys: telemetryTracker.getKeyTelemetry() - }); -}); - -// GET /api/admin/telemetry/stream (SSE) -router.get('/telemetry/stream', (req: Request, res: Response) => { - telemetryTracker.subscribe(res); -}); - export default router; diff --git a/src/adminView.ts b/src/adminView.ts index f1f1569..7add5b6 100644 --- a/src/adminView.ts +++ b/src/adminView.ts @@ -678,153 +678,6 @@ export function renderAdminHtml(): string { padding: 0.3rem 0; border-bottom: 1px solid rgba(255, 255, 255, 0.05); } - - /* Fallback Timeline & Breadcrumb Visualization */ - .journey-card { - background: var(--card-dark); - border: 1px solid var(--border-dark); - border-radius: 10px; - padding: 1rem 1.25rem; - margin-bottom: 0.75rem; - transition: all 0.2s ease; - } - body.light-theme .journey-card { - background: var(--card-light); - border-color: var(--border-light); - } - .journey-card:hover { - border-color: var(--primary-color); - } - .journey-header { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 0.75rem; - flex-wrap: wrap; - gap: 0.5rem; - } - .breadcrumb-cascade { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 0.4rem; - background: rgba(0, 0, 0, 0.2); - border: 1px solid var(--border-dark); - border-radius: 8px; - padding: 0.6rem 0.75rem; - } - body.light-theme .breadcrumb-cascade { - background: rgba(0, 0, 0, 0.03); - border-color: var(--border-light); - } - .cascade-hop { - display: inline-flex; - align-items: center; - gap: 0.35rem; - font-size: 0.75rem; - padding: 3px 8px; - border-radius: 6px; - border: 1px solid transparent; - } - .cascade-hop.success { - background: rgba(3, 218, 198, 0.12); - color: var(--accent-success); - border-color: rgba(3, 218, 198, 0.3); - } - .cascade-hop.failed { - background: rgba(207, 102, 121, 0.12); - color: var(--accent-danger); - border-color: rgba(207, 102, 121, 0.3); - } - .cascade-hop.rate-limited { - background: rgba(255, 183, 77, 0.12); - color: var(--accent-warning); - border-color: rgba(255, 183, 77, 0.3); - } - .cascade-arrow { - color: var(--muted-dark); - font-size: 0.75rem; - } - - /* Live Logs Inspector Layout */ - .log-row-item { - padding: 0.65rem 0.75rem; - border-radius: 8px; - border: 1px solid var(--border-dark); - background: rgba(0, 0, 0, 0.15); - cursor: pointer; - transition: all 0.15s ease; - display: flex; - flex-direction: column; - gap: 0.3rem; - } - body.light-theme .log-row-item { - background: rgba(0, 0, 0, 0.02); - border-color: var(--border-light); - } - .log-row-item:hover { - background: rgba(187, 134, 252, 0.08); - border-color: rgba(187, 134, 252, 0.4); - } - .log-row-item.active { - border-color: var(--primary-color); - background: rgba(187, 134, 252, 0.15); - box-shadow: 0 0 10px rgba(187, 134, 252, 0.2); - } - .code-box { - background: #0d0d0d; - color: #f1f1f1; - border: 1px solid rgba(255, 255, 255, 0.1); - border-radius: 8px; - padding: 0.75rem; - font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace; - font-size: 0.8rem; - overflow-x: auto; - white-space: pre-wrap; - word-break: break-word; - line-height: 1.45; - } - body.light-theme .code-box { - background: #f8f9fa; - color: #212529; - border-color: #dee2e6; - } - .chat-bubble { - border-radius: 8px; - padding: 0.65rem 0.85rem; - margin-bottom: 0.6rem; - font-size: 0.82rem; - line-height: 1.45; - } - .chat-bubble.user { - background: rgba(100, 181, 246, 0.12); - border-left: 3px solid var(--accent-info); - } - .chat-bubble.assistant { - background: rgba(3, 218, 198, 0.12); - border-left: 3px solid var(--accent-success); - } - .chat-bubble.system { - background: rgba(255, 183, 77, 0.12); - border-left: 3px solid var(--accent-warning); - } - .detail-table { - width: 100%; - border-collapse: collapse; - font-size: 0.82rem; - } - .detail-table td { - padding: 0.4rem 0.5rem; - border-bottom: 1px solid var(--border-dark); - } - body.light-theme .detail-table td { - border-bottom-color: var(--border-light); - } - .detail-table td:first-child { - color: var(--muted-dark); - width: 180px; - font-weight: 500; - } @@ -892,11 +745,6 @@ export function renderAdminHtml(): string { Live Key Telemetry - @@ -1013,174 +861,26 @@ export function renderAdminHtml(): string { - +

- Live Provider & Key Health + Live Provider & Key Status

- Real-time health, request counts, success rates, and rate-limit cooldown timers across all keys. + Live status, request volumes, rate-limit cooldowns, and error counts across all keys.

-
- - Live Stream Active - - -
+
- - -
+
- - -
-
-

- - Recent Model Fallback & Failover Journeys -

-

- Visual tracking of where and why models failed, how the revolver cascaded across keys and tiers, and what happened next. -

-
-
-
-

Listening for live fallback journeys...

-
-
- - -
-
-
-

- - Live Request Log Watcher -

-

- Inspect live incoming + served requests in RAM (input, output, metadata, debug data). Flushes from memory when toggled off. -

-
-
-
- Watcher: - -
-
- 0 / 250 in RAM (0 KB) -
- -
-
- - -
-
-
- - -
-
- - -
-
- - -
- -
-
- - -
- -
-
- Captured Requests (0) - Disconnected -
-
-

- Live Watcher is currently idle. Toggle Watcher ON to begin capturing requests in RAM. -

-
-
- - -
-
-
-

- Request Inspector - -

- Select a request from the list to inspect full RAM data -
- -
- - - - - -
-
- -

No request selected.

-

Toggle Watcher ON and select an incoming request from the stream to inspect.

-
- - - - -
-
-
@@ -1431,15 +1131,8 @@ export function renderAdminHtml(): string { document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active')); btn.classList.add('active'); const tabId = btn.getAttribute('data-tab'); - const pane = document.getElementById(tabId); - if (pane) pane.classList.add('active'); - if (tabId === 'telemetry-tab') { - loadTelemetry(); - connectTelemetrySSE(); - } - if (tabId === 'live-logs-tab') { - initLiveLogs(); - } + document.getElementById(tabId).classList.add('active'); + if (tabId === 'telemetry-tab') loadTelemetry(); }); }); @@ -1993,897 +1686,63 @@ export function renderAdminHtml(): string { } }); - // ========================================== - // Telemetry & Live Fallback Tracker - // ========================================== - let telemetryEventSource = null; - let cachedJourneys = []; - let cachedKeys = []; - - function escapeHtml(str) { - if (str === null || str === undefined) return ''; - return String(str) - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); - } - + // Telemetry Tab async function loadTelemetry() { + const container = document.getElementById('telemetry-list'); try { - const res = await apiRequest('/api/admin/telemetry/fallback-traces'); - if (!res.ok) throw new Error('Failed to fetch telemetry data'); + const res = await apiRequest('/api/admin/keys-status'); const data = await res.json(); - cachedKeys = data.keys || []; - cachedJourneys = data.journeys || []; - renderTelemetryKeys(cachedKeys); - renderTelemetryJourneys(cachedJourneys); + container.innerHTML = ''; + + if (!data.providers || data.providers.length === 0) { + container.innerHTML = '

No keys configured.

'; + return; + } + + data.providers.forEach(p => { + const card = document.createElement('div'); + card.className = 'card'; + let keysHtml = ''; + p.keys.forEach((k, idx) => { + const statusBadge = k.isRateLimited + ? ' Rate Limited (' + k.cooldownRemainingSeconds + 's)' + : ' Active'; + + keysHtml += \` +
+
+ Key \${idx + 1}: \${k.maskedKey} + \${statusBadge} +
+
+ Requests: \${k.requestCount} + Errors: \${k.errorCount} + Last used: \${k.lastUsed ? new Date(k.lastUsed).toLocaleTimeString() : 'Never'} +
+
+ \`; + }); + + card.innerHTML = \` +
+ \${p.name} + \${p.type} +
+
\${keysHtml}
+ \`; + container.appendChild(card); + }); } catch (err) { showToast('Telemetry load failed: ' + err.message, 'error'); } } - function connectTelemetrySSE() { - if (telemetryEventSource) return; - try { - telemetryEventSource = new EventSource('/api/admin/telemetry/stream?api_key=' + encodeURIComponent(activeKey)); - - telemetryEventSource.onopen = function() { - const indicator = document.getElementById('telemetry-sse-indicator'); - if (indicator) { - indicator.className = 'badge badge-success'; - indicator.innerHTML = ' Live Stream Active'; - } - }; - - telemetryEventSource.onmessage = function(e) { - try { - const msg = JSON.parse(e.data); - if (msg.type === 'snapshot') { - cachedKeys = msg.keys || []; - cachedJourneys = msg.journeys || []; - renderTelemetryKeys(cachedKeys); - renderTelemetryJourneys(cachedJourneys); - } else if (msg.type === 'key_status_update') { - cachedKeys = msg.keys || []; - renderTelemetryKeys(cachedKeys); - } else if (msg.type === 'fallback_journey') { - cachedJourneys.unshift(msg.data); - if (cachedJourneys.length > 50) cachedJourneys.length = 50; - renderTelemetryJourneys(cachedJourneys); - } - } catch (err) { - console.error('Failed to parse telemetry SSE message:', err); - } - }; - - telemetryEventSource.onerror = function() { - const indicator = document.getElementById('telemetry-sse-indicator'); - if (indicator) { - indicator.className = 'badge badge-warning'; - indicator.innerHTML = ' Reconnecting...'; - } - }; - } catch (err) { - console.error('Telemetry SSE error:', err); - } - } - - function renderTelemetryKeys(keys) { - const container = document.getElementById('telemetry-list'); - if (!container) return; - container.innerHTML = ''; - - if (!keys || keys.length === 0) { - container.innerHTML = '

No provider keys configured.

'; - return; - } - - // Group keys by providerId - const grouped = {}; - keys.forEach(k => { - if (!grouped[k.providerId]) { - grouped[k.providerId] = { - name: k.providerName, - type: k.providerType, - keys: [] - }; - } - grouped[k.providerId].keys.push(k); - }); - - Object.keys(grouped).forEach(pid => { - const prov = grouped[pid]; - const card = document.createElement('div'); - card.className = 'card'; - - let keysHtml = ''; - prov.keys.forEach(k => { - const statusBadge = k.isRateLimited - ? ' Rate Limited (' + k.cooldownRemainingSeconds + 's)' - : ' Active'; - - const rateColor = k.successRatePercent >= 90 ? 'var(--accent-success)' : (k.successRatePercent >= 60 ? 'var(--accent-warning)' : 'var(--accent-danger)'); - - keysHtml += '
' + - '
' + - 'Key ' + (k.keyIndex + 1) + ': ' + escapeHtml(k.maskedKey) + '' + - statusBadge + - '
' + - '
' + - '
Reqs: ' + k.requestCount + '
' + - '
OK: ' + k.successCount + '
' + - '
Errors: ' + k.errorCount + '
' + - '
Rate: ' + k.successRatePercent + '%
' + - '
' + - '
' + - 'Last used: ' + (k.lastUsed ? new Date(k.lastUsed).toLocaleTimeString() : 'Never') + - '
' + - '
'; - }); - - card.innerHTML = '
' + - '' + escapeHtml(prov.name) + '' + - '' + escapeHtml(prov.type) + '' + - '
' + - '
' + keysHtml + '
'; - - container.appendChild(card); - }); - } - - function renderTelemetryJourneys(journeys) { - const container = document.getElementById('telemetry-journeys-list'); - if (!container) return; - container.innerHTML = ''; - - if (!journeys || journeys.length === 0) { - container.innerHTML = '

No model fallback journeys captured yet. Requests sent to custom models will display their key and tier cascade live here.

'; - return; - } - - journeys.forEach(j => { - const card = document.createElement('div'); - card.className = 'journey-card'; - - let statusBadge = ''; - if (j.finalStatus === 'success_direct') { - statusBadge = ' Direct Success'; - } else if (j.finalStatus === 'success_fallback') { - const tierStr = j.finalServedBy ? ' (Tier ' + j.finalServedBy.tierIndex + ')' : ''; - statusBadge = ' Fallback Served' + tierStr + ''; - } else if (j.finalStatus === 'all_tiers_exhausted') { - statusBadge = ' All Tiers Exhausted'; - } else { - statusBadge = ' Cancelled'; - } - - // Build Cascade Breadcrumb - let cascadeHtml = ''; - if (Array.isArray(j.steps)) { - j.steps.forEach((step, idx) => { - const isLast = idx === j.steps.length - 1; - let hopClass = 'cascade-hop'; - let icon = 'fa-check'; - if (step.status === 'success') { - hopClass += ' success'; - icon = 'fa-check'; - } else if (step.status === 'rate_limited') { - hopClass += ' rate-limited'; - icon = 'fa-ban'; - } else { - hopClass += ' failed'; - icon = 'fa-exclamation-triangle'; - } - - const stepLabel = 'Tier ' + step.tierIndex + ' (' + escapeHtml(step.model) + ' / Key #' + (step.keyIndex + 1) + ')'; - const statusDetail = step.status === 'success' ? '200 OK (' + step.durationMs + 'ms)' : (step.statusCode ? step.statusCode + ' ' : '') + step.status + ' (' + step.durationMs + 'ms)'; - - cascadeHtml += '' + - ' ' + - '' + stepLabel + ': ' + escapeHtml(statusDetail) + - ''; - - if (!isLast) { - cascadeHtml += ''; - } - }); - } - - // Build Detail Table for Drawer - let detailRows = ''; - if (Array.isArray(j.steps)) { - j.steps.forEach(step => { - const statusColor = step.status === 'success' ? 'var(--accent-success)' : (step.status === 'rate_limited' ? 'var(--accent-warning)' : 'var(--accent-danger)'); - detailRows += '' + - 'Hop #' + step.stepIndex + '' + - 'Tier ' + step.tierIndex + ' (' + escapeHtml(step.tierName) + ')
' + escapeHtml(step.providerName) + ' (' + escapeHtml(step.providerType) + ')' + - '' + escapeHtml(step.model) + '
Key #' + (step.keyIndex + 1) + ' (' + escapeHtml(step.maskedKey) + ')' + - '' + step.durationMs + ' ms' + - '' + (step.statusCode ? step.statusCode + ' ' : '') + escapeHtml(step.status) + '' + (step.cooldownSeconds ? '
Cooldown: ' + step.cooldownSeconds + 's' : '') + '' + - '' + escapeHtml(step.errorMessage || 'None') + '' + - '' + escapeHtml(step.nextAction || 'None') + '' + - ''; - }); - } - - const tableDrawerId = 'journey-table-' + j.requestId; - const toggleBtnId = 'journey-toggle-btn-' + j.requestId; - - card.innerHTML = '
' + - '
' + - '' + escapeHtml(j.requestId) + '' + - '' + new Date(j.timestamp).toLocaleTimeString() + '' + - 'Model: ' + escapeHtml(j.requestedModel) + '' + - (j.resolvedModelName !== j.requestedModel ? ' → ' + escapeHtml(j.resolvedModelName) + '' : '') + - '' + - '
' + - '
' + - ' ' + j.totalDurationMs + ' ms' + - (j.tokens ? ' ' + j.tokens.totalTokens + ' tok' : '') + - statusBadge + - '
' + - '
' + - '' + - '
' + - '' + - '
' + - ''; - - container.appendChild(card); - - // Bind toggle - const toggleBtn = card.querySelector('#' + toggleBtnId); - const tableDrawer = card.querySelector('#' + tableDrawerId); - if (toggleBtn && tableDrawer) { - toggleBtn.addEventListener('click', () => { - const isHidden = tableDrawer.style.display === 'none'; - tableDrawer.style.display = isHidden ? 'block' : 'none'; - toggleBtn.innerHTML = isHidden - ? ' Hide Step Details' - : ' Step Details (' + (j.steps ? j.steps.length : 0) + ' hops)'; - }); - } - }); - } - document.getElementById('refresh-telemetry-btn').addEventListener('click', loadTelemetry); - // ========================================== - // Live Request Log Watcher (RAM-Only) - // ========================================== - let isWatcherActive = false; - let liveLogs = []; - let selectedLog = null; - let autoScroll = true; - let liveLogsEventSource = null; - let liveSearchQuery = ''; - let liveStatusFilter = 'all'; - let liveModelFilter = 'all'; - - async function initLiveLogs() { - await updateWatcherStatus(); - connectLiveLogsSSE(); - updateModelFilterOptions(); - } - - async function updateWatcherStatus() { - try { - const res = await apiRequest('/api/admin/live-logs/state'); - if (!res.ok) return; - const data = await res.json(); - isWatcherActive = !!data.active; - - const navBadge = document.getElementById('nav-live-badge'); - if (navBadge) { - navBadge.textContent = isWatcherActive ? 'LIVE' : 'OFF'; - navBadge.style.background = isWatcherActive ? 'var(--accent-success)' : 'rgba(255,255,255,0.1)'; - navBadge.style.color = isWatcherActive ? '#000' : 'inherit'; - } - - const ramText = document.getElementById('ram-count-text'); - if (ramText) { - ramText.textContent = data.bufferCount + ' / ' + data.maxCapacity + ' in RAM (' + data.memoryEstimateKb + ' KB)'; - } - - const toggleBtn = document.getElementById('watcher-toggle-btn'); - if (toggleBtn) { - if (isWatcherActive) { - toggleBtn.className = 'nav-btn danger'; - toggleBtn.innerHTML = ' Stop Watching'; - } else { - toggleBtn.className = 'nav-btn primary'; - toggleBtn.innerHTML = ' Start Watching'; - } - } - - // If watcher is active and we have no logs yet, fetch initial entries - if (isWatcherActive && liveLogs.length === 0) { - const entriesRes = await apiRequest('/api/admin/live-logs/entries?limit=100'); - if (entriesRes.ok) { - const entData = await entriesRes.json(); - liveLogs = entData.entries || []; - renderLiveLogsList(); - updateModelFilterOptions(); - } - } - } catch (err) { - console.error('Failed to update watcher status:', err); - } - } - - async function toggleWatcher() { - const targetState = !isWatcherActive; - try { - const res = await apiRequest('/api/admin/live-logs/toggle', { - method: 'POST', - body: { enabled: targetState } - }); - if (!res.ok) throw new Error('Failed to toggle watcher'); - const data = await res.json(); - isWatcherActive = !!data.active; - - if (!isWatcherActive) { - liveLogs = []; - selectedLog = null; - renderLiveLogsList(); - renderInspector(); - showToast('Live Watcher stopped. All request logs flushed from RAM.', 'info'); - } else { - showToast('Live Watcher started! Now capturing requests in RAM.', 'success'); - } - - await updateWatcherStatus(); - } catch (err) { - showToast('Error toggling watcher: ' + err.message, 'error'); - } - } - - async function flushWatcher() { - try { - const res = await apiRequest('/api/admin/live-logs/flush', { method: 'POST' }); - if (!res.ok) throw new Error('Failed to flush watcher logs'); - liveLogs = []; - selectedLog = null; - renderLiveLogsList(); - renderInspector(); - await updateWatcherStatus(); - showToast('RAM request logs purged successfully.', 'info'); - } catch (err) { - showToast('Error flushing watcher: ' + err.message, 'error'); - } - } - - function connectLiveLogsSSE() { - if (liveLogsEventSource) return; - try { - liveLogsEventSource = new EventSource('/api/admin/live-logs/stream?api_key=' + encodeURIComponent(activeKey)); - - liveLogsEventSource.onopen = function() { - const statusElem = document.getElementById('live-connection-status'); - if (statusElem) { - statusElem.className = 'badge badge-success'; - statusElem.innerHTML = ' Connected'; - } - }; - - liveLogsEventSource.onmessage = function(e) { - try { - const msg = JSON.parse(e.data); - handleLiveLogSSEMessage(msg); - } catch (err) { - console.error('Failed to parse live log SSE:', err); - } - }; - - liveLogsEventSource.onerror = function() { - const statusElem = document.getElementById('live-connection-status'); - if (statusElem) { - statusElem.className = 'badge badge-warning'; - statusElem.innerHTML = ' Reconnecting...'; - } - }; - } catch (err) { - console.error('Live logs SSE error:', err); - } - } - - function handleLiveLogSSEMessage(msg) { - if (msg.type === 'snapshot') { - if (msg.state) { - isWatcherActive = msg.state.active; - } - if (Array.isArray(msg.entries)) { - liveLogs = msg.entries; - renderLiveLogsList(); - updateModelFilterOptions(); - } - updateWatcherStatus(); - } else if (msg.type === 'watcher_status') { - isWatcherActive = msg.data.active; - updateWatcherStatus(); - } else if (msg.type === 'watcher_flushed') { - liveLogs = []; - selectedLog = null; - renderLiveLogsList(); - renderInspector(); - updateWatcherStatus(); - } else if (msg.type === 'request_started') { - liveLogs.unshift(msg.data); - if (liveLogs.length > 250) liveLogs.length = 250; - renderLiveLogsList(); - updateModelFilterOptions(); - updateWatcherStatus(); - } else if (msg.type === 'stream_chunk') { - const item = liveLogs.find(l => l.id === msg.requestId); - if (item) { - item.output.completionText = (item.output.completionText || '') + msg.chunkText; - item.durationMs = msg.durationMs || item.durationMs; - if (selectedLog && selectedLog.id === msg.requestId) { - const outText = document.getElementById('insp-output-text'); - if (outText) outText.textContent = item.output.completionText; - } - } - } else if (msg.type === 'candidate_step') { - const item = liveLogs.find(l => l.id === msg.requestId); - if (item) { - item.debug.stepTraces.push(msg.data); - item.metadata.totalCandidatesAttempted = item.debug.stepTraces.length; - if (item.debug.stepTraces.length > 1) item.metadata.fallbackOccurred = true; - if (selectedLog && selectedLog.id === msg.requestId) { - renderInspectorDebugPane(item); - } - } - } else if (msg.type === 'request_completed' || msg.type === 'request_failed' || msg.type === 'request_cancelled') { - const updated = msg.data; - const idx = liveLogs.findIndex(l => l.id === updated.id); - if (idx !== -1) { - liveLogs[idx] = updated; - } else { - liveLogs.unshift(updated); - } - renderLiveLogsList(); - if (selectedLog && selectedLog.id === updated.id) { - selectedLog = updated; - renderInspector(); - } - updateWatcherStatus(); - } - } - - function updateModelFilterOptions() { - const select = document.getElementById('live-model-filter'); - if (!select) return; - const currentVal = select.value; - const models = new Set(); - liveLogs.forEach(l => { - if (l.input && (l.input.requestedModel || l.input.model)) { - models.add(l.input.requestedModel || l.input.model); - } - }); - // Also add custom models from currentConfig - if (currentConfig && Array.isArray(currentConfig.customModels)) { - currentConfig.customModels.forEach(m => models.add(m.name)); - } - - let opts = ''; - models.forEach(m => { - opts += ''; - }); - select.innerHTML = opts; - select.value = currentVal || 'all'; - } - - function renderLiveLogsList() { - const container = document.getElementById('live-requests-list'); - const countElem = document.getElementById('live-displayed-count'); - if (!container) return; - - let filtered = [...liveLogs]; - - if (liveStatusFilter !== 'all') { - filtered = filtered.filter(l => l.status === liveStatusFilter); - } - - if (liveModelFilter !== 'all') { - filtered = filtered.filter(l => { - const reqM = (l.input && (l.input.requestedModel || l.input.model)) || ''; - return reqM.toLowerCase() === liveModelFilter.toLowerCase(); - }); - } - - if (liveSearchQuery.trim() !== '') { - const q = liveSearchQuery.toLowerCase().trim(); - filtered = filtered.filter(l => { - if (l.id.toLowerCase().includes(q)) return true; - const reqM = (l.input && (l.input.requestedModel || l.input.model)) || ''; - if (reqM.toLowerCase().includes(q)) return true; - if ((l.output && l.output.completionText || '').toLowerCase().includes(q)) return true; - if (Array.isArray(l.input?.messages)) { - for (const m of l.input.messages) { - const str = typeof m.content === 'string' ? m.content : JSON.stringify(m.content || ''); - if (str.toLowerCase().includes(q)) return true; - } - } - return false; - }); - } - - if (countElem) countElem.textContent = filtered.length; - container.innerHTML = ''; - - if (filtered.length === 0) { - container.innerHTML = '

' + - (liveLogs.length === 0 - ? 'No requests captured yet. Toggle Watcher ON and send API requests.' - : 'No requests match the current search/filter criteria.') + - '

'; - return; - } - - filtered.forEach(item => { - const row = document.createElement('div'); - row.className = 'log-row-item' + (selectedLog && selectedLog.id === item.id ? ' active' : ''); - - let statusBadge = ''; - if (item.status === 'streaming') { - statusBadge = ' Stream'; - } else if (item.status === 'completed') { - statusBadge = ' ' + (item.statusCode || 200) + ''; - } else if (item.status === 'fallback_completed') { - statusBadge = ' Fallback'; - } else if (item.status === 'failed') { - statusBadge = ' ' + (item.statusCode || 500) + ''; - } else { - statusBadge = ' Cancel'; - } - - const modelName = item.input.requestedModel || item.input.model || 'unknown-model'; - const tokCount = item.output?.tokens?.totalTokens ? item.output.tokens.totalTokens + ' tok' : ''; - - row.innerHTML = '
' + - '' + escapeHtml(item.id.slice(0, 16)) + '...' + - statusBadge + - '
' + - '
' + - '' + escapeHtml(modelName) + '' + - '' + item.durationMs + ' ms' + - '
' + - '
' + - '' + new Date(item.timestamp).toLocaleTimeString() + '' + - '' + tokCount + '' + - '
'; - - row.addEventListener('click', () => { - selectedLog = item; - document.querySelectorAll('.log-row-item').forEach(r => r.classList.remove('active')); - row.classList.add('active'); - renderInspector(); - }); - - container.appendChild(row); - }); - - if (autoScroll && container.firstElementChild) { - container.scrollTop = 0; - } - } - - function renderInspector() { - const emptyState = document.getElementById('inspector-empty-state'); - const tabs = document.getElementById('inspector-tabs'); - const actions = document.getElementById('inspector-actions'); - const title = document.getElementById('inspector-title'); - const subtitle = document.getElementById('inspector-subtitle'); - const badge = document.getElementById('inspector-status-badge'); - - if (!selectedLog) { - if (emptyState) emptyState.style.display = 'block'; - if (tabs) tabs.style.display = 'none'; - if (actions) actions.style.display = 'none'; - if (title) title.textContent = 'Request Inspector'; - if (subtitle) subtitle.textContent = 'Select a request from the list to inspect full RAM data'; - if (badge) badge.innerHTML = ''; - document.querySelectorAll('.insp-pane').forEach(p => p.style.display = 'none'); - return; - } - - if (emptyState) emptyState.style.display = 'none'; - if (tabs) tabs.style.display = 'flex'; - if (actions) actions.style.display = 'flex'; - - if (title) title.textContent = selectedLog.method + ' ' + selectedLog.path; - if (subtitle) subtitle.textContent = selectedLog.id + ' โ€ข ' + new Date(selectedLog.timestamp).toLocaleString() + ' โ€ข ' + selectedLog.durationMs + ' ms'; - - let statusBadge = ''; - if (selectedLog.status === 'streaming') { - statusBadge = ' Streaming'; - } else if (selectedLog.status === 'completed') { - statusBadge = ' 200 OK'; - } else if (selectedLog.status === 'fallback_completed') { - statusBadge = ' Fallback Served'; - } else if (selectedLog.status === 'failed') { - statusBadge = ' Error ' + (selectedLog.statusCode || 500) + ''; - } else { - statusBadge = ' Cancelled'; - } - if (badge) badge.innerHTML = statusBadge; - - renderInspectorInputPane(selectedLog); - renderInspectorOutputPane(selectedLog); - renderInspectorMetadataPane(selectedLog); - renderInspectorDebugPane(selectedLog); - - // Ensure active pane is visible - const activeTabBtn = document.querySelector('.insp-tab-btn.active'); - const activeTabId = activeTabBtn ? activeTabBtn.getAttribute('data-insp-tab') : 'insp-input'; - document.querySelectorAll('.insp-pane').forEach(p => p.style.display = 'none'); - const activePane = document.getElementById(activeTabId); - if (activePane) activePane.style.display = 'block'; - } - - function renderInspectorInputPane(item) { - const pane = document.getElementById('insp-input'); - if (!pane) return; - - let messagesHtml = ''; - if (Array.isArray(item.input.messages) && item.input.messages.length > 0) { - item.input.messages.forEach((msg, idx) => { - const role = (msg.role || 'user').toLowerCase(); - const bubbleClass = 'chat-bubble ' + (role === 'assistant' ? 'assistant' : (role === 'system' ? 'system' : 'user')); - const roleBadgeClass = role === 'assistant' ? 'badge-success' : (role === 'system' ? 'badge-warning' : 'badge-info'); - const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content, null, 2); - - messagesHtml += '
' + - '
' + - '' + escapeHtml(role.toUpperCase()) + '' + - '#' + (idx + 1) + '' + - '
' + - '
' + escapeHtml(content) + '
' + - '
'; - }); - } else { - messagesHtml = '

No messages array present in request payload.

'; - } - - pane.innerHTML = '
' + - '
' + - '
Model: ' + escapeHtml(item.input.requestedModel || item.input.model || 'N/A') + '
' + - '
Stream: ' + (item.isStreaming ? 'Yes (SSE)' : 'No (JSON)') + '
' + - '
Temperature: ' + (item.input.temperature ?? 'default') + '
' + - '
Max Tokens: ' + (item.input.maxTokens ?? 'unlimited') + '
' + - '
Client IP: ' + escapeHtml(item.clientIp || '127.0.0.1') + '
' + - '
' + - '
' + - '

Prompt Messages (' + (item.input.messages ? item.input.messages.length : 0) + ')

' + - '
' + messagesHtml + '
'; - } - - function renderInspectorOutputPane(item) { - const pane = document.getElementById('insp-output'); - if (!pane) return; - - let contentHtml = ''; - if (item.status === 'failed' || item.output.error) { - const errObj = item.output.error || {}; - contentHtml = '
' + - '
Error Response (' + (item.statusCode || 500) + ')
' + - '
' + escapeHtml(errObj.message || JSON.stringify(errObj, null, 2)) + '
' + - '
'; - } else if (item.output.completionText) { - contentHtml = '
' + - '
' + - ' Assistant Response' + - '' + (item.output.finishReason ? 'finish: ' + item.output.finishReason : '') + '' + - '
' + - '
' + escapeHtml(item.output.completionText) + '
' + - '
'; - } else { - contentHtml = '

' + - (item.status === 'streaming' ? 'Streaming response bytes in real time...' : 'No output text returned.') + - '

'; - } - - const tok = item.output?.tokens; - const tokBar = tok ? '
' + - '
Prompt Tokens: ' + tok.promptTokens + '
' + - '
Completion Tokens: ' + tok.completionTokens + '
' + - '
Total Tokens: ' + tok.totalTokens + '
' + - '
' : ''; - - pane.innerHTML = tokBar + contentHtml; - } - - function renderInspectorMetadataPane(item) { - const pane = document.getElementById('insp-metadata'); - if (!pane) return; - - const served = item.metadata.servedBy; - const servedStr = served - ? 'Tier ' + served.tierIndex + ' (' + escapeHtml(served.tierName) + ') โ€ข ' + escapeHtml(served.providerName) + ' (' + escapeHtml(served.providerType) + ') โ€ข ' + escapeHtml(served.model) + ' [Key: ' + escapeHtml(served.maskedKey) + ']' - : 'N/A'; - - pane.innerHTML = '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '
Request ID' + escapeHtml(item.id) + '
Timestamp' + new Date(item.timestamp).toISOString() + ' (' + new Date(item.timestamp).toLocaleString() + ')
Total Latency' + item.durationMs + ' ms
Status Code' + (item.statusCode || 200) + ' (' + escapeHtml(item.status) + ')
Method / Path' + item.method + ' ' + item.path + '
Streaming Mode' + (item.isStreaming ? 'Yes (SSE transfer)' : 'No (standard JSON)') + '
Client IP Address' + escapeHtml(item.clientIp || '127.0.0.1') + '
Client User-Agent' + escapeHtml(item.userAgent || 'None') + '
Requested Model' + escapeHtml(item.input.requestedModel || item.input.model || 'None') + '
Resolved Custom Model' + escapeHtml(item.metadata.resolvedCustomModelName || item.metadata.resolvedCustomModelId || 'Direct Fallback') + '
Fallback Occurred' + (item.metadata.fallbackOccurred ? 'YES' : 'NO (Direct)') + '
Total Hops Tried' + item.metadata.totalCandidatesAttempted + '
Final Serving Key' + servedStr + '
'; - } - - function renderInspectorDebugPane(item) { - const pane = document.getElementById('insp-debug'); - if (!pane) return; - - let stepsHtml = ''; - if (Array.isArray(item.debug.stepTraces) && item.debug.stepTraces.length > 0) { - stepsHtml += '

Candidate Attempts & Failover Cascade

' + - '' + - '' + - '' + - '' + - '' + - '' + - ''; - item.debug.stepTraces.forEach(st => { - const statusCol = st.status === 'success' ? 'var(--accent-success)' : (st.status === 'rate_limited' ? 'var(--accent-warning)' : 'var(--accent-danger)'); - stepsHtml += '' + - '' + - '' + - '' + - '' + - '' + - '' + - ''; - }); - stepsHtml += '
HopTier / ProviderModel / KeyDurationResultNext Action
#' + st.stepIndex + 'Tier ' + st.tierIndex + ' (' + escapeHtml(st.tierName) + ')
' + escapeHtml(st.providerName) + '
' + escapeHtml(st.model) + '
' + escapeHtml(st.maskedKey) + '
' + st.durationMs + ' ms' + (st.statusCode ? st.statusCode + ' ' : '') + escapeHtml(st.status) + '' + (st.errorMessage ? '
' + escapeHtml(st.errorMessage) + '' : '') + '
' + escapeHtml(st.nextAction || '') + '
'; - } - - let eventsHtml = ''; - if (Array.isArray(item.debug.events) && item.debug.events.length > 0) { - eventsHtml += '

Server Execution Events

' + - '
'; - item.debug.events.forEach(ev => { - const lvlColor = ev.level === 'error' ? 'var(--accent-danger)' : (ev.level === 'warn' ? 'var(--accent-warning)' : 'var(--accent-info)'); - eventsHtml += '
' + - '[' + new Date(ev.time).toLocaleTimeString() + '] ' + - '[' + ev.level.toUpperCase() + '] ' + - '' + escapeHtml(ev.message) + '' + - '
'; - }); - eventsHtml += '
'; - } - - const keepaliveSummary = '
' + - '
SSE Keep-Alive Pings: ' + (item.debug.keepAlivePingsCount || 0) + '
' + - '
Whitespace Keep-Alives: ' + (item.debug.nonStreamingWhitespaceCount || 0) + '
' + - '
'; - - pane.innerHTML = keepaliveSummary + stepsHtml + eventsHtml; - } - - // Inspector Sub-tab navigation - document.querySelectorAll('.insp-tab-btn').forEach(btn => { - btn.addEventListener('click', () => { - document.querySelectorAll('.insp-tab-btn').forEach(b => b.classList.remove('active')); - document.querySelectorAll('.insp-pane').forEach(p => p.style.display = 'none'); - btn.classList.add('active'); - const targetId = btn.getAttribute('data-insp-tab'); - const targetPane = document.getElementById(targetId); - if (targetPane) targetPane.style.display = 'block'; - }); - }); - - // Copy / Export Handlers - const copyBtn = document.getElementById('copy-log-json-btn'); - if (copyBtn) { - copyBtn.addEventListener('click', () => { - if (!selectedLog) return; - navigator.clipboard.writeText(JSON.stringify(selectedLog, null, 2)) - .then(() => showToast('Full request inspection copied to clipboard!', 'success')) - .catch(() => showToast('Failed to copy to clipboard', 'error')); - }); - } - - const exportBtn = document.getElementById('export-log-json-btn'); - if (exportBtn) { - exportBtn.addEventListener('click', () => { - if (!selectedLog) return; - const blob = new Blob([JSON.stringify(selectedLog, null, 2)], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = 'request-' + selectedLog.id + '.json'; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - URL.revokeObjectURL(url); - showToast('Exported request inspection as JSON.', 'success'); - }); - } - - // Watcher Toggle Button - const toggleBtn = document.getElementById('watcher-toggle-btn'); - if (toggleBtn) { - toggleBtn.addEventListener('click', toggleWatcher); - } - - // Flush Memory Button - const flushBtn = document.getElementById('flush-watcher-btn'); - if (flushBtn) { - flushBtn.addEventListener('click', flushWatcher); - } - - // Filter & Search Controls - const searchInput = document.getElementById('live-search-input'); - if (searchInput) { - searchInput.addEventListener('input', (e) => { - liveSearchQuery = e.target.value; - renderLiveLogsList(); - }); - } - - const statusFilterSelect = document.getElementById('live-status-filter'); - if (statusFilterSelect) { - statusFilterSelect.addEventListener('change', (e) => { - liveStatusFilter = e.target.value; - renderLiveLogsList(); - }); - } - - const modelFilterSelect = document.getElementById('live-model-filter'); - if (modelFilterSelect) { - modelFilterSelect.addEventListener('change', (e) => { - liveModelFilter = e.target.value; - renderLiveLogsList(); - }); - } - - const autoScrollBtn = document.getElementById('live-auto-scroll-btn'); - if (autoScrollBtn) { - autoScrollBtn.addEventListener('click', () => { - autoScroll = !autoScroll; - autoScrollBtn.innerHTML = autoScroll - ? ' Auto-Scroll: ON' - : ' Auto-Scroll: OFF'; - autoScrollBtn.className = autoScroll ? 'nav-btn' : 'nav-btn warning'; - }); - } - // Initial check initTheme(); if (activeKey) { renderDashboardView(); - updateWatcherStatus(); } else { renderAuthView(); } diff --git a/src/auth.ts b/src/auth.ts index 067e896..3830169 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -20,8 +20,8 @@ export const authenticateApiKey = (req: Request, res: Response, next: NextFuncti providedKey = (req.headers['x-api-key'] as string) || (req.headers['x-admin-key'] as string); } - if (!providedKey && (req.query.api_key || req.query.token || req.query.apiKey)) { - providedKey = (req.query.api_key || req.query.token || req.query.apiKey) as string; + if (!providedKey && req.query.api_key) { + providedKey = req.query.api_key as string; } if (!providedKey) { diff --git a/src/liveWatcher.ts b/src/liveWatcher.ts deleted file mode 100644 index c3f6619..0000000 --- a/src/liveWatcher.ts +++ /dev/null @@ -1,486 +0,0 @@ -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(); diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts index ad93eb4..e0194b7 100644 --- a/src/revolverEngine.ts +++ b/src/revolverEngine.ts @@ -11,8 +11,6 @@ import { ExecutionDiagnosticTrace } from './revolverTypes'; import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes'; -import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker'; -import { liveWatcher } from './liveWatcher'; interface CandidateExecution { tier: FallbackTier; @@ -241,7 +239,6 @@ export class RevolverEngine { if (!res.writableEnded) { isCancelled = true; if (onCancelled) onCancelled(); - liveWatcher.cancelRequest(requestId); } }); @@ -260,14 +257,12 @@ export class RevolverEngine { // Immediately transmit an initial SSE comment ping so Cloudflare Edge receives response bytes instantly if (!res.destroyed && !res.writableEnded) { res.write(': keep-alive\n\n'); - liveWatcher.recordKeepAlive(requestId, 'sse_comment'); } // Keep connection active with periodic SSE comments while waiting for model thinking / generation keepAliveTimer = setInterval(() => { if (!res.destroyed && !res.writableEnded) { res.write(': keep-alive\n\n'); - liveWatcher.recordKeepAlive(requestId, 'sse_comment'); } }, config.keepAliveIntervalMs); } else if (config.enableNonStreamingKeepAlive) { @@ -287,7 +282,6 @@ export class RevolverEngine { } } res.write(' '); - liveWatcher.recordKeepAlive(requestId, 'whitespace'); }, config.nonStreamingKeepAliveDelayMs); } @@ -298,9 +292,6 @@ export class RevolverEngine { throw new Error(`Custom model '${customModel.name}' has no fallback tiers defined.`); } - const journeyStart = Date.now(); - const fallbackSteps: FallbackStep[] = []; - let totalHops = 0; let lastError: any = null; // Traverse tiers: Tier 0 -> Tier 1 -> Tier 2... @@ -320,16 +311,11 @@ export class RevolverEngine { return; } - const candidateStart = Date.now(); - totalHops++; - const isLastCandidateInTier = candidate === candidates[candidates.length - 1]; - const isLastTier = tier === sortedTiers[sortedTiers.length - 1]; - try { console.log(`[REVOLVER] Routing to Provider '${candidate.provider.name}' (${candidate.provider.type}) with model '${candidate.target.model}' [Key ${candidate.keyIndex + 1}/${candidate.provider.keys.length}]`); if (isStreaming) { - const streamResult = await this.executeStreaming({ + await this.executeStreaming({ candidate, requestBody, requestedModelName, @@ -341,64 +327,7 @@ export class RevolverEngine { onSuccess }); cleanupTimers(); - - const stepDuration = Date.now() - candidateStart; - const successStep: FallbackStep = { - stepIndex: totalHops, - timestamp: new Date().toISOString(), - tierIndex: tier.tierIndex, - tierName: tier.name || `Tier ${tier.tierIndex}`, - providerId: candidate.provider.id, - providerName: candidate.provider.name, - providerType: candidate.provider.type, - model: candidate.target.model, - keyIndex: candidate.keyIndex, - maskedKey: this.store.maskKey(candidate.keyConfig.key), - durationMs: stepDuration, - status: 'success', - statusCode: 200, - nextAction: 'Served successfully' - }; - fallbackSteps.push(successStep); - liveWatcher.recordCandidateStep(requestId, successStep); - - const promptTokens = streamResult?.promptTokens || Math.ceil(JSON.stringify(requestBody.messages).length / 4); - const completionTokens = streamResult?.completionTokens || 0; - const journey: RequestFallbackJourney = { - requestId, - timestamp: new Date().toISOString(), - requestedModel: requestBody.model || requestedModelName, - resolvedModelName: customModel.name, - resolvedModelId: customModel.id, - finalStatus: fallbackSteps.length > 1 ? 'success_fallback' : 'success_direct', - totalDurationMs: Date.now() - journeyStart, - totalHops, - fallbackOccurred: fallbackSteps.length > 1, - finalServedBy: { - tierIndex: tier.tierIndex, - tierName: tier.name || `Tier ${tier.tierIndex}`, - providerName: candidate.provider.name, - providerType: candidate.provider.type, - model: candidate.target.model, - maskedKey: this.store.maskKey(candidate.keyConfig.key) - }, - tokens: { - promptTokens, - completionTokens, - totalTokens: promptTokens + completionTokens - }, - steps: fallbackSteps - }; - telemetryTracker.recordJourney(journey); - telemetryTracker.broadcastKeyStatus(); - liveWatcher.completeRequest({ - requestId, - statusCode: 200, - journey, - tokens: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens }, - finishReason: streamResult?.finishReason || 'stop' - }); - + // If stream finished successfully, return return; } else { const responseData = await this.executeNonStreaming({ @@ -417,69 +346,12 @@ export class RevolverEngine { rateLimitedUntil: null }); - const promptTokens = responseData.usage?.prompt_tokens || 0; - const completionTokens = responseData.usage?.completion_tokens || 0; - if (onSuccess) { + const promptTokens = responseData.usage?.prompt_tokens || 0; + const completionTokens = responseData.usage?.completion_tokens || 0; onSuccess({ input: promptTokens, output: completionTokens }); } - const stepDuration = Date.now() - candidateStart; - const successStep: FallbackStep = { - stepIndex: totalHops, - timestamp: new Date().toISOString(), - tierIndex: tier.tierIndex, - tierName: tier.name || `Tier ${tier.tierIndex}`, - providerId: candidate.provider.id, - providerName: candidate.provider.name, - providerType: candidate.provider.type, - model: candidate.target.model, - keyIndex: candidate.keyIndex, - maskedKey: this.store.maskKey(candidate.keyConfig.key), - durationMs: stepDuration, - status: 'success', - statusCode: 200, - nextAction: 'Served successfully' - }; - fallbackSteps.push(successStep); - liveWatcher.recordCandidateStep(requestId, successStep); - - const journey: RequestFallbackJourney = { - requestId, - timestamp: new Date().toISOString(), - requestedModel: requestBody.model || requestedModelName, - resolvedModelName: customModel.name, - resolvedModelId: customModel.id, - finalStatus: fallbackSteps.length > 1 ? 'success_fallback' : 'success_direct', - totalDurationMs: Date.now() - journeyStart, - totalHops, - fallbackOccurred: fallbackSteps.length > 1, - finalServedBy: { - tierIndex: tier.tierIndex, - tierName: tier.name || `Tier ${tier.tierIndex}`, - providerName: candidate.provider.name, - providerType: candidate.provider.type, - model: candidate.target.model, - maskedKey: this.store.maskKey(candidate.keyConfig.key) - }, - tokens: { - promptTokens, - completionTokens, - totalTokens: promptTokens + completionTokens - }, - steps: fallbackSteps - }; - telemetryTracker.recordJourney(journey); - telemetryTracker.broadcastKeyStatus(); - liveWatcher.completeRequest({ - requestId, - statusCode: 200, - journey, - responseData, - tokens: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens }, - finishReason: responseData.choices?.[0]?.finish_reason || 'stop' - }); - if (res.headersSent) { // Chunked keep-alive headers were already emitted res.write(JSON.stringify(responseData)); @@ -493,67 +365,10 @@ export class RevolverEngine { lastError = err; console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message); - const stepDuration = Date.now() - candidateStart; - const isRateLimit = this.isRateLimitOrQuotaError(err); - const isServerErr = this.isServerError(err); - const cooldown = isRateLimit ? config.rateLimitDurationMs : (isServerErr ? 15000 : undefined); - const statusType = isRateLimit ? 'rate_limited' : (isServerErr ? 'server_error' : 'failed'); - - let nextAction = ''; - if (!isLastCandidateInTier) { - nextAction = `Rotating to next key in Tier ${tier.tierIndex}`; - } else if (!isLastTier) { - nextAction = `Tier ${tier.tierIndex} exhausted. Cascading to Fallback Tier ${sortedTiers[sortedTiers.indexOf(tier) + 1]?.tierIndex ?? 'next'}`; - } else { - nextAction = 'All tiers and candidates exhausted'; - } - - const failedStep: FallbackStep = { - stepIndex: totalHops, - timestamp: new Date().toISOString(), - tierIndex: tier.tierIndex, - tierName: tier.name || `Tier ${tier.tierIndex}`, - providerId: candidate.provider.id, - providerName: candidate.provider.name, - providerType: candidate.provider.type, - model: candidate.target.model, - keyIndex: candidate.keyIndex, - maskedKey: this.store.maskKey(candidate.keyConfig.key), - durationMs: stepDuration, - status: statusType, - statusCode: err.status || (isRateLimit ? 429 : 500), - errorMessage: err.message, - rateLimitedUntil: cooldown ? Date.now() + cooldown : null, - cooldownSeconds: cooldown ? Math.ceil(cooldown / 1000) : undefined, - nextAction - }; - fallbackSteps.push(failedStep); - liveWatcher.recordCandidateStep(requestId, failedStep); - // If stream has already started sending content bytes to the client, we cannot fail over cleanly if (streamStarted) { cleanupTimers(); if (onFailure) onFailure('stream_interrupted'); - const journey: RequestFallbackJourney = { - requestId, - timestamp: new Date().toISOString(), - requestedModel: requestBody.model || requestedModelName, - resolvedModelName: customModel.name, - resolvedModelId: customModel.id, - finalStatus: 'all_tiers_exhausted', - totalDurationMs: Date.now() - journeyStart, - totalHops, - fallbackOccurred: true, - steps: fallbackSteps - }; - telemetryTracker.recordJourney(journey); - telemetryTracker.broadcastKeyStatus(); - liveWatcher.failRequest({ - requestId, - statusCode: 500, - error: err, - journey - }); if (!res.destroyed && !res.writableEnded) { res.write(`data: ${JSON.stringify({ error: { @@ -569,10 +384,14 @@ export class RevolverEngine { } // Mark key rate limited or increment error + const isRateLimit = this.isRateLimitOrQuotaError(err); + const isServerErr = this.isServerError(err); + if (isRateLimit || isServerErr) { - console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown! / 1000}s`); + const cooldown = isRateLimit ? config.rateLimitDurationMs : 15000; + console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown / 1000}s`); this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - rateLimitedUntil: Date.now() + cooldown!, + rateLimitedUntil: Date.now() + cooldown, incrementError: true }); } else { @@ -580,7 +399,6 @@ export class RevolverEngine { incrementError: true }); } - telemetryTracker.broadcastKeyStatus(); // Continue loop to try next candidate in this tier } @@ -594,27 +412,6 @@ export class RevolverEngine { if (onFailure) onFailure('all_tiers_exhausted'); const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.'; - const journey: RequestFallbackJourney = { - requestId, - timestamp: new Date().toISOString(), - requestedModel: requestBody.model || requestedModelName, - resolvedModelName: customModel.name, - resolvedModelId: customModel.id, - finalStatus: 'all_tiers_exhausted', - totalDurationMs: Date.now() - journeyStart, - totalHops, - fallbackOccurred: true, - steps: fallbackSteps - }; - telemetryTracker.recordJourney(journey); - telemetryTracker.broadcastKeyStatus(); - liveWatcher.failRequest({ - requestId, - statusCode: 503, - error: lastError || new Error(finalErrorMessage), - journey - }); - if (isStreaming) { if (!res.destroyed && !res.writableEnded) { res.write(`data: ${JSON.stringify({ @@ -791,7 +588,7 @@ export class RevolverEngine { res: Response; onStreamStart: () => void; onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> { + }): Promise { const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; if (candidate.provider.type === 'gemini') { @@ -825,7 +622,7 @@ export class RevolverEngine { res: Response; onStreamStart: () => void; onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> { + }): Promise { const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; const genAI = this.getGeminiClient(candidate.keyConfig.key); @@ -872,7 +669,6 @@ export class RevolverEngine { if (res.destroyed) break; const text = chunk.text(); fullContent += text; - liveWatcher.appendStreamChunk(requestId, text); onStreamStart(); const chunkResponse = { @@ -931,12 +727,6 @@ export class RevolverEngine { if (onSuccess) { onSuccess({ input: promptTokens, output: completionTokens }); } - - return { - promptTokens, - completionTokens, - finishReason: 'stop' - }; } private async executeOpenAICompatibleStreaming(params: { @@ -947,7 +737,7 @@ export class RevolverEngine { res: Response; onStreamStart: () => void; onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> { + }): Promise { const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, ''); @@ -1032,9 +822,7 @@ export class RevolverEngine { parsed.model = requestedModelName; if (parsed.choices?.[0]?.delta?.content) { onStreamStart(); - const delta = parsed.choices[0].delta.content; - totalOutputChars += delta.length; - liveWatcher.appendStreamChunk(requestId, delta); + totalOutputChars += parsed.choices[0].delta.content.length; } res.write(`data: ${JSON.stringify(parsed)}\n\n`); } catch { @@ -1062,12 +850,6 @@ export class RevolverEngine { if (onSuccess) { onSuccess({ input: estimatedInput, output: estimatedOutput }); } - - return { - promptTokens: estimatedInput, - completionTokens: estimatedOutput, - finishReason: 'stop' - }; } // Diagnostic Test Prompt Runner for the Admin Playground diff --git a/src/routes.ts b/src/routes.ts index 97de756..2fdb130 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -7,7 +7,6 @@ import { revolverEngine } from './revolverEngine'; import { authenticateApiKey } from './auth'; import adminRoutes from './adminRoutes'; import { renderAdminHtml } from './adminView'; -import { liveWatcher } from './liveWatcher'; import { OpenAIChatRequest, OpenAIModelsResponse @@ -45,24 +44,9 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { body: body }); - liveWatcher.startRequest({ - requestId, - method: req.method, - path: req.path, - clientIp: (req.headers['x-forwarded-for'] as string) || req.ip || req.socket.remoteAddress, - userAgent: req.get('user-agent'), - isStreaming: !!body?.stream, - body - }); - // Validate request if (!body.messages || !Array.isArray(body.messages)) { requestTracker.recordFailure('invalid_messages'); - liveWatcher.failRequest({ - requestId, - statusCode: 400, - error: new Error('Invalid or missing messages array') - }); res.status(400).json({ error: { message: 'Invalid or missing messages array', @@ -104,7 +88,6 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { if (!isFinished) { isFinished = true; requestTracker.recordCancelled(); - liveWatcher.cancelRequest(requestId); requestLogger.logError(requestId, { message: 'Client cancelled request', path: req.path @@ -117,11 +100,6 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { if (!isFinished) { isFinished = true; requestTracker.recordFailure(error.message); - liveWatcher.failRequest({ - requestId, - statusCode: error.status || 500, - error - }); } console.error('[ERROR] Error in chat completion:', { diff --git a/src/telemetryTracker.ts b/src/telemetryTracker.ts deleted file mode 100644 index 209f72c..0000000 --- a/src/telemetryTracker.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { Response } from 'express'; -import { ProviderType } from './revolverTypes'; -import { configStore } from './configStore'; - -export interface FallbackStep { - stepIndex: number; - timestamp: string; - tierIndex: number; - tierName: string; - providerId: string; - providerName: string; - providerType: ProviderType; - model: string; - keyIndex: number; - maskedKey: string; - durationMs: number; - status: 'success' | 'rate_limited' | 'server_error' | 'network_error' | 'timeout' | 'cancelled' | 'failed'; - statusCode?: number | string; - errorMessage?: string; - rateLimitedUntil?: number | null; - cooldownSeconds?: number; - nextAction?: string; -} - -export interface RequestFallbackJourney { - requestId: string; - timestamp: string; - requestedModel: string; - resolvedModelName: string; - resolvedModelId: string; - finalStatus: 'success_direct' | 'success_fallback' | 'all_tiers_exhausted' | 'cancelled'; - totalDurationMs: number; - totalHops: number; - fallbackOccurred: boolean; - finalServedBy?: { - tierIndex: number; - tierName: string; - providerName: string; - providerType: ProviderType; - model: string; - maskedKey: string; - }; - tokens?: { - promptTokens: number; - completionTokens: number; - totalTokens: number; - }; - steps: FallbackStep[]; -} - -export interface KeyTelemetryItem { - providerId: string; - providerName: string; - providerType: ProviderType; - keyIndex: number; - maskedKey: string; - requestCount: number; - errorCount: number; - successCount: number; - successRatePercent: number; - isRateLimited: boolean; - cooldownRemainingSeconds: number; - lastUsed: string | null; -} - -export class TelemetryTracker { - private recentJourneys: RequestFallbackJourney[] = []; - private maxJourneys: number = 100; - private sseClients: Set = new Set(); - - public recordJourney(journey: RequestFallbackJourney): void { - this.recentJourneys.unshift(journey); - if (this.recentJourneys.length > this.maxJourneys) { - this.recentJourneys.length = this.maxJourneys; - } - - this.broadcast({ - type: 'fallback_journey', - data: journey - }); - } - - public getRecentJourneys(limit = 50): RequestFallbackJourney[] { - return this.recentJourneys.slice(0, limit); - } - - public getKeyTelemetry(): KeyTelemetryItem[] { - const providers = configStore.getProviders(); - const now = Date.now(); - const result: KeyTelemetryItem[] = []; - - for (const p of providers) { - p.keys.forEach((k, idx) => { - const isRateLimited = !!(k.rateLimitedUntil && now < k.rateLimitedUntil); - const cooldownRemainingSeconds = isRateLimited && k.rateLimitedUntil - ? Math.ceil((k.rateLimitedUntil - now) / 1000) - : 0; - const reqCount = k.requestCount || 0; - const errCount = k.errorCount || 0; - const successCount = Math.max(0, reqCount - errCount); - const successRatePercent = reqCount > 0 - ? Math.round((successCount / reqCount) * 100) - : 100; - - result.push({ - providerId: p.id, - providerName: p.name, - providerType: p.type, - keyIndex: idx, - maskedKey: configStore.maskKey(k.key), - requestCount: reqCount, - errorCount: errCount, - successCount, - successRatePercent, - isRateLimited, - cooldownRemainingSeconds, - lastUsed: k.lastUsed ? new Date(k.lastUsed).toISOString() : null - }); - }); - } - - return result; - } - - 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(); - } - - // Send initial snapshot - const initialData = { - type: 'snapshot', - journeys: this.getRecentJourneys(20), - keys: this.getKeyTelemetry(), - timestamp: new Date().toISOString() - }; - res.write(`data: ${JSON.stringify(initialData)}\n\n`); - - this.sseClients.add(res); - - res.on('close', () => { - this.sseClients.delete(res); - }); - } - - public broadcastKeyStatus(): void { - this.broadcast({ - type: 'key_status_update', - keys: this.getKeyTelemetry(), - timestamp: new Date().toISOString() - }); - } - - 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); - } - } - } - - public clear(): void { - this.recentJourneys = []; - } -} - -export const telemetryTracker = new TelemetryTracker(); diff --git a/test-live-watcher.ts b/test-live-watcher.ts deleted file mode 100644 index cc0cb3f..0000000 --- a/test-live-watcher.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { liveWatcher } from './src/liveWatcher'; -import assert from 'assert'; - -console.log('๐Ÿงช Starting LiveWatcher Unit & RAM Retention Tests...\n'); - -// 1. Initial State -console.log('1. Testing initial state (inactive and empty)...'); -assert.strictEqual(liveWatcher.isActive(), false, 'Watcher should initially be inactive'); -assert.strictEqual(liveWatcher.getState().bufferCount, 0, 'Buffer should initially be empty'); -console.log(' โœ“ Watcher starts inactive with 0 items in RAM.'); - -// 2. Toggling ON -console.log('\n2. Testing toggleWatcher(true)...'); -const toggleOnRes = liveWatcher.toggleWatcher(true); -assert.strictEqual(toggleOnRes.active, true, 'Watcher active should be true'); -assert.strictEqual(liveWatcher.isActive(), true); -console.log(' โœ“ Watcher toggled ON.'); - -// 3. Capturing incoming requests -console.log('\n3. Testing request start, chunk accumulation, candidate step, and completion...'); -const reqId = 'test-req-001'; -liveWatcher.startRequest({ - requestId: reqId, - method: 'POST', - path: '/v1/chat/completions', - clientIp: '192.168.1.100', - userAgent: 'TestClient/1.0', - isStreaming: true, - body: { - model: 'custom-pipeline', - messages: [ - { role: 'system', content: 'You are helpful.' }, - { role: 'user', content: 'What is 2+2?' } - ], - temperature: 0.7, - max_tokens: 100 - } -}); - -let entries = liveWatcher.getEntries(); -assert.strictEqual(entries.length, 1, 'Should have 1 entry in RAM'); -assert.strictEqual(entries[0].id, reqId); -assert.strictEqual(entries[0].status, 'streaming'); -assert.strictEqual(entries[0].input.messages.length, 2); - -// Append stream chunks -liveWatcher.appendStreamChunk(reqId, 'The answer '); -liveWatcher.appendStreamChunk(reqId, 'is 4.'); -assert.strictEqual(entries[0].output.completionText, 'The answer is 4.'); - -// Record candidate step -liveWatcher.recordCandidateStep(reqId, { - stepIndex: 1, - timestamp: new Date().toISOString(), - tierIndex: 0, - tierName: 'Main Tier', - providerId: 'prov-1', - providerName: 'Google AI Studio', - providerType: 'gemini', - model: 'gemini-1.5-flash', - keyIndex: 0, - maskedKey: 'AIzaSy...abc', - durationMs: 150, - status: 'success', - statusCode: 200, - nextAction: 'Served successfully' -}); - -// Record keepalive -liveWatcher.recordKeepAlive(reqId, 'sse_comment'); -assert.strictEqual(entries[0].debug.keepAlivePingsCount, 1); - -// Complete request -liveWatcher.completeRequest({ - requestId: reqId, - statusCode: 200, - tokens: { promptTokens: 12, completionTokens: 5, totalTokens: 17 }, - finishReason: 'stop' -}); - -assert.strictEqual(entries[0].status, 'completed'); -assert.strictEqual(entries[0].output.tokens?.totalTokens, 17); -assert.strictEqual(entries[0].output.finishReason, 'stop'); -assert.strictEqual(entries[0].debug.stepTraces.length, 1); -console.log(' โœ“ Request lifecycle, streaming chunks, tokens, and debug step traces captured in RAM.'); - -// 4. Filtering and Search -console.log('\n4. Testing search and filtering...'); -// Add second failed request -liveWatcher.startRequest({ - requestId: 'test-req-002', - method: 'POST', - path: '/v1/chat/completions', - isStreaming: false, - body: { - model: 'groq-model', - messages: [{ role: 'user', content: 'Say hello in French' }] - } -}); -liveWatcher.failRequest({ - requestId: 'test-req-002', - statusCode: 503, - error: new Error('Upstream timeout') -}); - -const completedOnly = liveWatcher.getEntries({ status: 'completed' }); -assert.strictEqual(completedOnly.length, 1); -assert.strictEqual(completedOnly[0].id, 'test-req-001'); - -const failedOnly = liveWatcher.getEntries({ status: 'failed' }); -assert.strictEqual(failedOnly.length, 1); -assert.strictEqual(failedOnly[0].id, 'test-req-002'); - -const searchFrench = liveWatcher.getEntries({ search: 'french' }); -assert.strictEqual(searchFrench.length, 1); -assert.strictEqual(searchFrench[0].id, 'test-req-002'); - -const searchAnswer = liveWatcher.getEntries({ search: 'answer is 4' }); -assert.strictEqual(searchAnswer.length, 1); -assert.strictEqual(searchAnswer[0].id, 'test-req-001'); -console.log(' โœ“ Status filtering and full-text prompt/response search verified.'); - -// 5. FIFO Limit of 250 items -console.log('\n5. Testing 250 items FIFO cap...'); -for (let i = 0; i < 300; i++) { - liveWatcher.startRequest({ - requestId: `bulk-req-${i}`, - method: 'POST', - path: '/v1/chat/completions', - isStreaming: false, - body: { model: 'cap-test', messages: [] } - }); -} -const stateAfterBulk = liveWatcher.getState(); -assert.strictEqual(stateAfterBulk.bufferCount, 250, 'Buffer must be capped at maxCapacity 250'); -const entriesAfterBulk = liveWatcher.getEntries(); -assert.strictEqual(entriesAfterBulk.length, 250); -// Newest should be bulk-req-299 -assert.strictEqual(entriesAfterBulk[0].id, 'bulk-req-299'); -console.log(' โœ“ 250-item FIFO safety cap verified without memory overflow.'); - -// 6. Toggling OFF flushes all RAM -console.log('\n6. Testing toggleWatcher(false) flushes RAM...'); -const toggleOffRes = liveWatcher.toggleWatcher(false); -assert.strictEqual(toggleOffRes.active, false); -assert.strictEqual(toggleOffRes.bufferCount, 0, 'Buffer count must be 0 after toggle off'); -assert.strictEqual(liveWatcher.getEntries().length, 0, 'Buffer entries must be empty'); -assert.strictEqual(liveWatcher.getState().bufferCount, 0); -console.log(' โœ“ Toggling OFF immediately flushes RAM buffer and stops recording.'); - -// 7. Incoming requests while OFF are ignored -console.log('\n7. Testing incoming requests while OFF are not recorded in RAM...'); -liveWatcher.startRequest({ - requestId: 'ignored-req', - method: 'POST', - path: '/v1/chat/completions', - isStreaming: false, - body: { messages: [] } -}); -assert.strictEqual(liveWatcher.getEntries().length, 0, 'Ignored request should not enter buffer'); -console.log(' โœ“ Zero RAM overhead when watcher is OFF.'); - -console.log('\n๐ŸŽ‰ ALL LIVE WATCHER UNIT TESTS PASSED SUCCESSFULLY!\n'); diff --git a/test-telemetry-fallback.ts b/test-telemetry-fallback.ts deleted file mode 100644 index 2b833ee..0000000 --- a/test-telemetry-fallback.ts +++ /dev/null @@ -1,274 +0,0 @@ -import http from 'http'; -import assert from 'assert'; -import app from './src/index'; -import { telemetryTracker, RequestFallbackJourney, FallbackStep } from './src/telemetryTracker'; -import { liveWatcher } from './src/liveWatcher'; -import { configStore } from './src/configStore'; - -const PORT = 3998; -const API_KEY = 'test_password'; - -console.log('๐Ÿงช Starting Telemetry Fallback & Admin HTTP API Test Suite...\n'); - -async function runTests() { - // 0. Start a mock upstream server - const mockUpstream = http.createServer((req, res) => { - let body = ''; - req.on('data', chunk => (body += chunk)); - req.on('end', () => { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - id: 'chatcmpl-mock-123', - object: 'chat.completion', - created: Math.floor(Date.now() / 1000), - model: 'mock-model-v1', - choices: [ - { - index: 0, - message: { role: 'assistant', content: 'Telemetry & live logs verification response.' }, - finish_reason: 'stop' - } - ], - usage: { prompt_tokens: 15, completion_tokens: 10, total_tokens: 25 } - }) - ); - }); - }); - await new Promise((resolve) => mockUpstream.listen(0, resolve)); - const upstreamPort = (mockUpstream.address() as any).port; - const upstreamBaseUrl = `http://localhost:${upstreamPort}`; - - const server = http.createServer(app); - await new Promise((resolve) => server.listen(PORT, resolve)); - - try { - // 1. Unit Test: Fallback Journey Tracking in telemetryTracker - console.log('1. Testing TelemetryTracker fallback journey tracking...'); - - const sampleHops: FallbackStep[] = [ - { - stepIndex: 1, - timestamp: new Date().toISOString(), - tierIndex: 0, - tierName: 'Main Tier (Flash)', - providerId: 'prov-gemini', - providerName: 'Google AI Studio', - providerType: 'gemini', - model: 'gemini-1.5-flash', - keyIndex: 0, - maskedKey: 'AIzaSy...4X9', - durationMs: 120, - status: 'rate_limited', - statusCode: 429, - errorMessage: 'Resource has been exhausted (e.g. check quota).', - rateLimitedUntil: Date.now() + 60000, - cooldownSeconds: 60, - nextAction: 'Rotating to next key in Tier 0' - }, - { - stepIndex: 2, - timestamp: new Date().toISOString(), - tierIndex: 0, - tierName: 'Main Tier (Flash)', - providerId: 'prov-gemini', - providerName: 'Google AI Studio', - providerType: 'gemini', - model: 'gemini-1.5-flash', - keyIndex: 1, - maskedKey: 'AIzaSy...8B2', - durationMs: 95, - status: 'server_error', - statusCode: 503, - errorMessage: 'The model is overloaded. Please try again later.', - rateLimitedUntil: Date.now() + 15000, - cooldownSeconds: 15, - nextAction: 'Tier 0 exhausted. Cascading to Fallback Tier 1' - }, - { - stepIndex: 3, - timestamp: new Date().toISOString(), - tierIndex: 1, - tierName: 'Backup Tier (Groq)', - providerId: 'prov-groq', - providerName: 'Groq Cloud', - providerType: 'groq', - model: 'llama-3.3-70b-versatile', - keyIndex: 0, - maskedKey: 'gsk_...11a', - durationMs: 215, - status: 'success', - statusCode: 200, - nextAction: 'Served successfully' - } - ]; - - const sampleJourney: RequestFallbackJourney = { - requestId: 'req_fallback_trace_001', - timestamp: new Date().toISOString(), - requestedModel: 'smart-pipeline', - resolvedModelName: 'smart-pipeline', - resolvedModelId: 'model-smart-01', - finalStatus: 'success_fallback', - totalDurationMs: 430, - totalHops: 3, - fallbackOccurred: true, - finalServedBy: { - tierIndex: 1, - tierName: 'Backup Tier (Groq)', - providerName: 'Groq Cloud', - providerType: 'groq', - model: 'llama-3.3-70b-versatile', - maskedKey: 'gsk_...11a' - }, - tokens: { - promptTokens: 45, - completionTokens: 30, - totalTokens: 75 - }, - steps: sampleHops - }; - - telemetryTracker.recordJourney(sampleJourney); - - const recent = telemetryTracker.getRecentJourneys(); - assert.strictEqual(recent.length >= 1, true); - const recorded = recent.find(j => j.requestId === 'req_fallback_trace_001'); - assert.ok(recorded, 'Recorded journey must exist'); - assert.strictEqual(recorded.finalStatus, 'success_fallback'); - assert.strictEqual(recorded.totalHops, 3); - assert.strictEqual(recorded.fallbackOccurred, true); - assert.strictEqual(recorded.steps.length, 3); - assert.strictEqual(recorded.steps[0].status, 'rate_limited'); - assert.strictEqual(recorded.steps[0].cooldownSeconds, 60); - assert.strictEqual(recorded.steps[1].status, 'server_error'); - assert.strictEqual(recorded.steps[2].status, 'success'); - console.log(' โœ“ Fallback journey successfully captures multi-tier failures, cooldowns, and next action.'); - - // 2. HTTP Admin Endpoints: Telemetry Traces - console.log('\n2. Testing GET /api/admin/telemetry/fallback-traces...'); - const telRes = await fetch(`http://localhost:${PORT}/api/admin/telemetry/fallback-traces`, { - headers: { 'Authorization': `Bearer ${API_KEY}` } - }); - assert.strictEqual(telRes.status, 200); - const telData = await telRes.json() as any; - assert.ok(Array.isArray(telData.journeys)); - assert.ok(Array.isArray(telData.keys)); - assert.strictEqual(telData.journeys.some((j: any) => j.requestId === 'req_fallback_trace_001'), true); - console.log(' โœ“ GET /api/admin/telemetry/fallback-traces returned journeys and keys successfully.'); - - // 3. HTTP Admin Endpoints: Live Logs State & Toggle - console.log('\n3. Testing GET /api/admin/live-logs/state...'); - const stateRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/state`, { - headers: { 'Authorization': `Bearer ${API_KEY}` } - }); - assert.strictEqual(stateRes.status, 200); - const stateData = await stateRes.json() as any; - assert.strictEqual(typeof stateData.active, 'boolean'); - assert.strictEqual(stateData.maxCapacity, 250); - console.log(' โœ“ Initial live logs state verified.'); - - console.log('\n4. Testing POST /api/admin/live-logs/toggle (ON)...'); - const toggleOnRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/toggle`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${API_KEY}` - }, - body: JSON.stringify({ enabled: true }) - }); - assert.strictEqual(toggleOnRes.status, 200); - const toggleOnData = await toggleOnRes.json() as any; - assert.strictEqual(toggleOnData.active, true); - assert.strictEqual(liveWatcher.isActive(), true); - console.log(' โœ“ Watcher successfully toggled ON via Admin API.'); - - // 5. Send an actual Chat Completion request and verify Live Watcher captures it - console.log('\n5. Sending API completion request and verifying RAM capture in Live Watcher...'); - const uniqueModelName = `test-telemetry-model-${Date.now()}`; - const testProv = configStore.saveProvider({ - name: 'Test Upstream Provider', - type: 'custom', - baseUrl: upstreamBaseUrl, - keys: ['mock-api-key-1'] - }); - - const testModel = configStore.saveCustomModel({ - name: uniqueModelName, - tiers: [ - { - tierIndex: 0, - name: 'Main Tier', - targets: [{ providerId: testProv.id, model: 'mock-model-v1' }] - } - ] - }); - - const completionRes = await fetch(`http://localhost:${PORT}/v1/chat/completions`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${API_KEY}` - }, - body: JSON.stringify({ - model: uniqueModelName, - messages: [{ role: 'user', content: 'Verify live watcher inspection' }] - }) - }); - assert.strictEqual(completionRes.status, 200); - - // Now check GET /api/admin/live-logs/entries - const entriesRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/entries`, { - headers: { 'Authorization': `Bearer ${API_KEY}` } - }); - assert.strictEqual(entriesRes.status, 200); - const entriesData = await entriesRes.json() as any; - assert.strictEqual(entriesData.state.active, true); - assert.strictEqual(entriesData.entries.length >= 1, true); - - const captured = entriesData.entries[0]; - assert.strictEqual(captured.input.messages[0].content, 'Verify live watcher inspection'); - assert.strictEqual(captured.output.completionText, 'Telemetry & live logs verification response.'); - assert.strictEqual(captured.output.tokens.totalTokens, 25); - assert.strictEqual(captured.debug.stepTraces.length >= 1, true); - assert.strictEqual(captured.debug.stepTraces[0].status, 'success'); - console.log(' โœ“ Incoming API request, output, tokens, metadata, and candidate trace successfully inspected from RAM.'); - - // 6. Test Toggling OFF flushes all RAM data - console.log('\n6. Testing POST /api/admin/live-logs/toggle (OFF) flushes RAM data...'); - const toggleOffRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/toggle`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${API_KEY}` - }, - body: JSON.stringify({ enabled: false }) - }); - assert.strictEqual(toggleOffRes.status, 200); - const toggleOffData = await toggleOffRes.json() as any; - assert.strictEqual(toggleOffData.active, false); - assert.strictEqual(toggleOffData.bufferCount, 0); - - const checkFlushRes = await fetch(`http://localhost:${PORT}/api/admin/live-logs/entries`, { - headers: { 'Authorization': `Bearer ${API_KEY}` } - }); - const checkFlushData = await checkFlushRes.json() as any; - assert.strictEqual(checkFlushData.entries.length, 0, 'Buffer entries must be empty after toggle off'); - console.log(' โœ“ Toggling OFF completely purged all logs from memory.'); - - // Cleanup test models - configStore.deleteCustomModel(testModel.id); - configStore.deleteProvider(testProv.id); - - console.log('\n๐ŸŽ‰ ALL TELEMETRY FALLBACK & ADMIN HTTP API TESTS PASSED!\n'); - - } finally { - server.close(); - mockUpstream.close(); - } -} - -runTests().catch((err) => { - console.error('Test failed with error:', err); - process.exit(1); -});