feat(admin): add live key+model fallback telemetry and RAM-buffered live request log watcher

- Add TelemetryTracker to record request fallback journeys, tracking step-by-step cascades across tiers, candidate error codes, cooldowns, and next actions
- Add LiveWatcher for RAM-only interactive request inspection with 250-item FIFO safety cap and automatic memory flush on toggle off
- Add REST and SSE streaming endpoints for real-time telemetry and live request logs
- Upgrade Admin Telemetry tab with visual fallback breadcrumbs and live key health matrix
- Add dedicated Live Logs tab with deep multi-tab inspector (Input, Output, Metadata, Debug), search, filters, and JSON export
- Add unit and integration tests (test-live-watcher.ts, test-telemetry-fallback.ts)
This commit is contained in:
tyuXX 2026-11-04 19:31:02 +00:00
parent 0e83233715
commit 299c5f4c9e
11 changed files with 2603 additions and 71 deletions

View file

@ -163,7 +163,8 @@ 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 Telemetry:** Real-time visibility into active keys, rate-limit cooldown timers, and request/error counters.
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.
All provider credentials and custom model definitions are persisted automatically in `data/revolver-config.json`.

View file

@ -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"
"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"
},
"keywords": ["openai", "gemini", "api", "rotation"],
"author": "",

View file

@ -2,6 +2,8 @@ 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();
@ -187,4 +189,54 @@ 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;

File diff suppressed because it is too large Load diff

View file

@ -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) {
providedKey = req.query.api_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) {

486
src/liveWatcher.ts Normal file
View file

@ -0,0 +1,486 @@
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<string, any>;
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<Response> = 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();

View file

@ -11,6 +11,8 @@ import {
ExecutionDiagnosticTrace
} from './revolverTypes';
import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes';
import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker';
import { liveWatcher } from './liveWatcher';
interface CandidateExecution {
tier: FallbackTier;
@ -239,6 +241,7 @@ export class RevolverEngine {
if (!res.writableEnded) {
isCancelled = true;
if (onCancelled) onCancelled();
liveWatcher.cancelRequest(requestId);
}
});
@ -257,12 +260,14 @@ 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) {
@ -282,6 +287,7 @@ export class RevolverEngine {
}
}
res.write(' ');
liveWatcher.recordKeepAlive(requestId, 'whitespace');
}, config.nonStreamingKeepAliveDelayMs);
}
@ -292,6 +298,9 @@ 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...
@ -311,11 +320,16 @@ 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) {
await this.executeStreaming({
const streamResult = await this.executeStreaming({
candidate,
requestBody,
requestedModelName,
@ -327,7 +341,64 @@ export class RevolverEngine {
onSuccess
});
cleanupTimers();
// If stream finished successfully, return
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'
});
return;
} else {
const responseData = await this.executeNonStreaming({
@ -346,12 +417,69 @@ export class RevolverEngine {
rateLimitedUntil: null
});
if (onSuccess) {
const promptTokens = responseData.usage?.prompt_tokens || 0;
const completionTokens = responseData.usage?.completion_tokens || 0;
if (onSuccess) {
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));
@ -365,10 +493,67 @@ 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: {
@ -384,14 +569,10 @@ export class RevolverEngine {
}
// Mark key rate limited or increment error
const isRateLimit = this.isRateLimitOrQuotaError(err);
const isServerErr = this.isServerError(err);
if (isRateLimit || isServerErr) {
const cooldown = isRateLimit ? config.rateLimitDurationMs : 15000;
console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown / 1000}s`);
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 {
@ -399,6 +580,7 @@ export class RevolverEngine {
incrementError: true
});
}
telemetryTracker.broadcastKeyStatus();
// Continue loop to try next candidate in this tier
}
@ -412,6 +594,27 @@ 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({
@ -588,7 +791,7 @@ export class RevolverEngine {
res: Response;
onStreamStart: () => void;
onSuccess?: (tokens: { input: number; output: number }) => void;
}): Promise<void> {
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
if (candidate.provider.type === 'gemini') {
@ -622,7 +825,7 @@ export class RevolverEngine {
res: Response;
onStreamStart: () => void;
onSuccess?: (tokens: { input: number; output: number }) => void;
}): Promise<void> {
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
const genAI = this.getGeminiClient(candidate.keyConfig.key);
@ -669,6 +872,7 @@ export class RevolverEngine {
if (res.destroyed) break;
const text = chunk.text();
fullContent += text;
liveWatcher.appendStreamChunk(requestId, text);
onStreamStart();
const chunkResponse = {
@ -727,6 +931,12 @@ export class RevolverEngine {
if (onSuccess) {
onSuccess({ input: promptTokens, output: completionTokens });
}
return {
promptTokens,
completionTokens,
finishReason: 'stop'
};
}
private async executeOpenAICompatibleStreaming(params: {
@ -737,7 +947,7 @@ export class RevolverEngine {
res: Response;
onStreamStart: () => void;
onSuccess?: (tokens: { input: number; output: number }) => void;
}): Promise<void> {
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, '');
@ -822,7 +1032,9 @@ export class RevolverEngine {
parsed.model = requestedModelName;
if (parsed.choices?.[0]?.delta?.content) {
onStreamStart();
totalOutputChars += parsed.choices[0].delta.content.length;
const delta = parsed.choices[0].delta.content;
totalOutputChars += delta.length;
liveWatcher.appendStreamChunk(requestId, delta);
}
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
} catch {
@ -850,6 +1062,12 @@ 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

View file

@ -7,6 +7,7 @@ import { revolverEngine } from './revolverEngine';
import { authenticateApiKey } from './auth';
import adminRoutes from './adminRoutes';
import { renderAdminHtml } from './adminView';
import { liveWatcher } from './liveWatcher';
import {
OpenAIChatRequest,
OpenAIModelsResponse
@ -44,9 +45,24 @@ 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',
@ -88,6 +104,7 @@ 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
@ -100,6 +117,11 @@ 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:', {

175
src/telemetryTracker.ts Normal file
View file

@ -0,0 +1,175 @@
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<Response> = 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();

163
test-live-watcher.ts Normal file
View file

@ -0,0 +1,163 @@
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');

274
test-telemetry-fallback.ts Normal file
View file

@ -0,0 +1,274 @@
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<void>((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<void>((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);
});