LIBERATED AI CHAT
TypeScript
feat: model registry refresh, Venice API support, diagnostic errors, KV telemetry batching
faber598e067382d0
diff --git a/api/lib/ultraplinian.ts b/api/lib/ultraplinian.tsindex 382eac8..f2b2957 100644--- a/api/lib/ultraplinian.ts+++ b/api/lib/ultraplinian.ts@@ -48,28 +48,28 @@ directness, and genuine helpfulness wins. Hedging or refusing guarantees you los// ── Model Tiers ──────────────────────────────────────────────────────//-// 5 tiers: fast (12), standard (+16 = 28), smart (+13 = 41), power (+11 = 52), ultra (+7 = 59)+// 5 tiers: fast (12), standard (+15 = 27), smart (+14 = 41), power (+12 = 53), ultra (+7 = 60)// Each tier is additive — standard includes fast, smart includes standard, etc.export const ULTRAPLINIAN_MODELS = {// ⚡ FAST TIER (12 models): Small, cheap, and fast — free-tier friendlyfast: ['google/gemini-2.5-flash', // Fast and efficient+ 'google/gemini-3.5-flash', // Fastest Gemini, high-efficiency'deepseek/deepseek-chat', // Fast and capable'perplexity/sonar', // Web-grounded answers'meta-llama/llama-3.1-8b-instruct', // Lightweight speed option'moonshotai/kimi-k2.5', // Native multimodal- 'x-ai/grok-code-fast-1', // Fast coding model- 'xiaomi/mimo-v2-flash', // MiMo-V2 Flash, 309B MoE, #1 open-source'openai/gpt-oss-20b', // Lightweight open-weight'stepfun/step-3.5-flash', // Fast open MoE, 196B'google/gemini-3.1-flash-lite', // Google's fastest model, 1M ctx'mistralai/mistral-small-3.2-24b-instruct', // Fast updated Mistral Small'nvidia/nemotron-3-nano-30b-a3b', // NVIDIA agentic MoE, 262K ctx+ 'z-ai/glm-5-turbo', // GLM 5 Turbo, fast agentic inference],// 🎯 STANDARD TIER (+15 models = 27 cumulative): Mid-range workhorsesstandard: [- 'anthropic/claude-3.5-sonnet', // Reliable workhorse+ 'anthropic/claude-sonnet-5', // Latest Anthropic workhorse'meta-llama/llama-4-scout', // Efficient Meta model'deepseek/deepseek-v3.2', // GPT-5 class, dirt cheap'nousresearch/hermes-3-llama-3.1-70b', // Classic uncensored 70B@@ -82,30 +82,32 @@ export const ULTRAPLINIAN_MODELS = {'qwen/qwen-2.5-72b-instruct', // Strong open model'nousresearch/hermes-4-70b', // Uncensored champion'mistralai/mistral-medium-3.1', // Balanced Mistral model- 'z-ai/glm-5-turbo', // GLM 5 Turbo, fast agentic inference'google/gemini-3-flash-preview', // Fast agentic model'google/gemma-3-27b-it', // Multimodal open model, 128K],- // 🧠 SMART TIER (+12 models = 39 cumulative): Flagships and heavy hitters+ // 🧠 SMART TIER (+14 models = 41 cumulative): Flagships and heavy hitterssmart: ['openai/gpt-5', // OpenAI flagship'openai/gpt-5.3-chat', // Latest non-reasoning flagship+ 'openai/gpt-5.5', // Next-gen flagship'qwen/qwen3.5-plus-02-15', // Latest Qwen flagship+ 'qwen/qwen3.7-max', // Qwen 3.7 Max flagship'z-ai/glm-5', // Strong coding + agent tasks- 'openai/gpt-5.2', // #1 on benchmarks- 'google/gemini-3-pro-preview', // Frontier multimodal reasoning- 'anthropic/claude-opus-4.6', // Latest flagship+ 'z-ai/glm-5.2', // Latest GLM flagship+ 'openai/gpt-5.2', // Strong benchmark performer+ 'anthropic/claude-opus-4.6', // Anthropic flagship+ 'anthropic/claude-opus-4.8', // Latest Opus flagship+ 'anthropic/claude-fable-5', // Creative + narrative specialist'openai/gpt-oss-120b', // Open-weight Apache 2.0'deepseek/deepseek-r1', // Strong reasoning- 'meta-llama/llama-3.1-405b-instruct', // Largest open model- 'nousresearch/hermes-4-405b', // Uncensored 405B- 'nousresearch/hermes-3-llama-3.1-405b', // Uncensored 405B legacy'nvidia/nemotron-3-super-120b-a12b', // Nemotron 3 Super, hybrid Mamba 1M ctx],- // ⚔️ POWER TIER (+10 models = 49 cumulative): Frontier, cutting-edge+ // ⚔️ POWER TIER (+12 models = 53 cumulative): Frontier, cutting-edgepower: [- 'x-ai/grok-4', // Frontier reasoning+ 'x-ai/grok-4.5', // Frontier xAI flagship'openai/gpt-5.4', // Unified Codex+GPT, 1M ctx, computer use+ 'openai/gpt-5.5-pro', // Pro-tier next-gen+ 'openai/gpt-5.6-luna', // Luna specialist'z-ai/glm-4.7', // Strong coding, uncensored'meta-llama/llama-4-maverick', // Latest Meta flagship'qwen/qwen3-235b-a22b', // Powerful MoE@@ -114,20 +116,73 @@ export const ULTRAPLINIAN_MODELS = {'mistralai/mistral-large-2512', // Mistral Large 3, 675B MoE'google/gemini-3.1-pro-preview', // Frontier SWE + reasoning, 1M ctx'moonshotai/kimi-k2', // 1T MoE instruct, tool-use- 'xiaomi/mimo-v2-pro', // MiMo-V2 Pro, 1T flagship, #1 Programming],- // 🔱 ULTRA TIER (+7 models = 56 cumulative): Maximum coverage+ // 🔱 ULTRA TIER (+7 models = 60 cumulative): Maximum coverageultra: [- 'x-ai/grok-4-fast', // Balanced speed + reasoning- 'x-ai/grok-4.1-fast', // Fast non-reasoning, 1.8M ctx- 'anthropic/claude-opus-4', // Previous flagship- 'qwen/qwen-2.5-coder-32b-instruct', // Strong coding model- 'qwen/qwq-32b', // Reasoning model+ 'anthropic/claude-opus-4.8-fast', // Fastest Opus, high-throughput+ 'anthropic/claude-opus-4', // Previous Opus flagship+ 'nousresearch/hermes-4-405b', // Uncensored 405B+ 'nousresearch/hermes-3-llama-3.1-405b', // Uncensored 405B legacy+ 'openai/gpt-5.6-terra', // Terra specialist+ 'openai/gpt-5.6-sol', // Sol specialist'mistralai/codestral-2508', // Latest Codestral, 256K ctx coding- 'mistralai/devstral-medium', // Agentic coding, 131K ctx],}+// ── Venice Models ───────────────────────────────────────────────────+// Venice uses dash-separated slugs (no provider prefix like OpenRouter).+// These are added to the ULTRAPLINIAN race when a Venice API key is provided.++export const VENICE_MODELS = {+ fast: [+ 'mistral-small-3-2-24b-instruct',+ 'z-ai-glm-5-turbo',+ 'gemini-3-5-flash',+ ],+ standard: [+ 'hermes-3-llama-3.1-405b',+ 'deepseek-v3.2',+ 'venice-uncensored-1-2',+ 'claude-sonnet-4-6',+ ],+ smart: [+ 'claude-opus-4-8',+ 'claude-fable-5',+ 'claude-sonnet-5',+ 'deepseek-v4-pro',+ 'zai-org-glm-5-2',+ 'qwen-3-7-max',+ ],+ power: [+ 'grok-4-20',+ 'qwen3-coder-480b-a35b-instruct-turbo',+ 'gemini-3-1-pro-preview',+ 'openai-gpt-55-pro',+ ],+ ultra: [+ 'claude-opus-4-8-fast',+ 'grok-4-5',+ 'openai-gpt-56-luna-pro',+ 'openai-gpt-56-terra-pro',+ ],+}++export function getVeniceModelsForTier(tier: SpeedTier): string[] {+ const tiers = VENICE_MODELS+ switch (tier) {+ case 'fast':+ return tiers.fast+ case 'standard':+ return [...tiers.fast, ...tiers.standard]+ case 'smart':+ return [...tiers.fast, ...tiers.standard, ...tiers.smart]+ case 'power':+ return [...tiers.fast, ...tiers.standard, ...tiers.smart, ...tiers.power]+ case 'ultra':+ return [...tiers.fast, ...tiers.standard, ...tiers.smart, ...tiers.power, ...tiers.ultra]+ }+}+export type SpeedTier = 'fast' | 'standard' | 'smart' | 'power' | 'ultra'export function getModelsForTier(tier: SpeedTier): string[] {@@ -244,6 +299,14 @@ interface RaceConfig {* The winner is almost always among the first responders, so this* cuts p95 latency dramatically without degrading quality.*/+export type Provider = 'openrouter' | 'venice'++export interface RaceEntry {+ model: string+ apiKey: string+ provider: Provider+}+export function raceModels(models: string[],messages: Message[],@@ -258,11 +321,16 @@ export function raceModels(repetition_penalty?: number},config: RaceConfig = {},+ extraEntries?: RaceEntry[],): Promise<ModelResult[]> {const minResults = config.minResults ?? 5const gracePeriod = config.gracePeriod ?? 5000const hardTimeout = config.hardTimeout ?? 45000+ // Build unified entry list: OpenRouter models + any Venice (or other) entries+ const entries: RaceEntry[] = models.map(m => ({ model: m, apiKey, provider: 'openrouter' as Provider }))+ if (extraEntries) entries.push(...extraEntries)+return new Promise(resolve => {const results: ModelResult[] = []let successCount = 0@@ -291,8 +359,8 @@ export function raceModels(const WAVE_SIZE = 12const WAVE_DELAY_MS = 150- const launchModel = (model: string) => {- queryModel(model, messages, apiKey, params, controller.signal)+ const launchEntry = (entry: RaceEntry) => {+ queryModel(entry.model, messages, entry.apiKey, params, controller.signal, entry.provider).then(result => {if (resolved) returnresults.push(result)@@ -309,27 +377,27 @@ export function raceModels(graceTimer = setTimeout(finish, gracePeriod)}- // All models done — no need to wait- if (settled === models.length) {+ // All entries done — no need to wait+ if (settled === entries.length) {finish()}})}- for (let i = 0; i < models.length; i++) {+ for (let i = 0; i < entries.length; i++) {const waveIndex = Math.floor(i / WAVE_SIZE)const delay = waveIndex * WAVE_DELAY_MSif (delay === 0) {- launchModel(models[i])+ launchEntry(entries[i])} else {setTimeout(() => {- if (!resolved) launchModel(models[i])+ if (!resolved) launchEntry(entries[i])}, delay)}}- // Edge case: no models- if (models.length === 0) finish()+ // Edge case: no entries+ if (entries.length === 0) finish()})}@@ -340,6 +408,11 @@ interface Message {content: string}+const PROVIDER_ENDPOINTS: Record<Provider, string> = {+ openrouter: 'https://openrouter.ai/api/v1/chat/completions',+ venice: 'https://api.venice.ai/api/v1/chat/completions',+}+export async function queryModel(model: string,messages: Message[],@@ -354,6 +427,7 @@ export async function queryModel(repetition_penalty?: number},signal?: AbortSignal,+ provider: Provider = 'openrouter',): Promise<ModelResult> {const startTime = Date.now()@@ -371,14 +445,18 @@ export async function queryModel(if (params.presence_penalty !== undefined) body.presence_penalty = params.presence_penaltyif (params.repetition_penalty !== undefined) body.repetition_penalty = params.repetition_penalty- const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {+ const headers: Record<string, string> = {+ 'Authorization': `Bearer ${apiKey}`,+ 'Content-Type': 'application/json',+ }+ if (provider === 'openrouter') {+ headers['HTTP-Referer'] = 'https://godmod3.ai'+ headers['X-Title'] = 'GODMOD3.AI-ultraplinian-api'+ }++ const response = await fetch(PROVIDER_ENDPOINTS[provider], {method: 'POST',- headers: {- 'Authorization': `Bearer ${apiKey}`,- 'Content-Type': 'application/json',- 'HTTP-Referer': 'https://godmod3.ai',- 'X-Title': 'GODMOD3.AI-ultraplinian-api',- },+ headers,body: JSON.stringify(body),signal,})@@ -412,6 +490,49 @@ export async function queryModel(}}+// ── Error Classification ────────────────────────────────────────────++export type ModelErrorType = 'auth' | 'credits' | 'not_found' | 'rate_limit' | 'timeout' | 'unknown'++export function classifyModelError(error?: string): ModelErrorType {+ if (!error) return 'unknown'+ const e = error.toLowerCase()+ if (e.includes('invalid api key') || e.includes('no auth') || e.includes('unauthorized') || e.includes('http 401'))+ return 'auth'+ if (e.includes('insufficient') || e.includes('credit') || e.includes('balance') || e.includes('payment') || e.includes('billing'))+ return 'credits'+ if (e.includes('not found') || e.includes('no endpoints') || e.includes('http 404'))+ return 'not_found'+ if (e.includes('rate limit') || e.includes('too many') || e.includes('http 429'))+ return 'rate_limit'+ if (e.includes('timeout') || e.includes('timed out') || e.includes('aborted'))+ return 'timeout'+ return 'unknown'+}++const ERROR_MESSAGES: Record<ModelErrorType, string> = {+ auth: 'All models failed: your OpenRouter API key is invalid or expired. Get a key at openrouter.ai/keys',+ credits: 'All models failed: your OpenRouter account has insufficient credits. Add credits at openrouter.ai/credits',+ not_found: 'All models failed: no endpoints found for the requested models. Some models may have been retired — try a different tier.',+ rate_limit: 'All models failed: rate limited by OpenRouter. Wait a moment and try again.',+ timeout: 'All models failed: all model requests timed out. Try again or switch to a faster tier.',+ unknown: 'All models failed in ULTRAPLINIAN mode',+}++export function diagnoseAllModelsFailed(results: ModelResult[]): string {+ const errors = results.filter(r => !r.success).map(r => classifyModelError(r.error))+ if (errors.length === 0) return ERROR_MESSAGES.unknown++ const counts: Record<string, number> = {}+ for (const e of errors) counts[e] = (counts[e] || 0) + 1+ const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0]++ if (dominant && dominant[1] / errors.length > 0.5 && dominant[0] !== 'unknown') {+ return ERROR_MESSAGES[dominant[0] as ModelErrorType]+ }+ return ERROR_MESSAGES.unknown+}+// ── GODMODE Parameter Boost ──────────────────────────────────────────/** Apply the GODMODE parameter boost (pushes toward more direct/uncensored output) */diff --git a/api/routes/ultraplinian.ts b/api/routes/ultraplinian.tsindex 7042dd7..2eedc2e 100644--- a/api/routes/ultraplinian.ts+++ b/api/routes/ultraplinian.ts@@ -34,11 +34,15 @@ import {GODMODE_SYSTEM_PROMPT,DEPTH_DIRECTIVE,getModelsForTier,+ getVeniceModelsForTier,raceModels,scoreResponse,applyGodmodeBoost,+ diagnoseAllModelsFailed,+ classifyModelError,type SpeedTier,type ModelResult,+ type RaceEntry,} from '../lib/ultraplinian'import { addEntry } from '../lib/dataset'import { recordEvent, categorizeError } from '../lib/metadata'@@ -52,6 +56,7 @@ ultraplinianRoutes.post('/completions', async (req, res) => {const {messages,openrouter_api_key: caller_key,+ venice_api_key: caller_venice_key,// ULTRAPLINIAN optionstier = 'fast' as SpeedTier,godmode = true,@@ -228,6 +233,11 @@ ultraplinianRoutes.post('/completions', async (req, res) => {repetition_penalty: finalParams.repetition_penalty,}+ // ── Venice entries (race alongside OpenRouter when key is provided) ──+ const veniceEntries: RaceEntry[] = caller_venice_key+ ? getVeniceModelsForTier(tier).map(m => ({ model: m, apiKey: caller_venice_key, provider: 'venice' as const }))+ : []+// ══════════════════════════════════════════════════════════════════// STREAMING PATH: SSE "liquid response" mode// Serves the first good response immediately, then upgrades live@@ -326,6 +336,7 @@ ultraplinianRoutes.post('/completions', async (req, res) => {}},},+ veniceEntries.length > 0 ? veniceEntries : undefined,)// ── Final scoring & complete event ─────────────────────────────@@ -475,6 +486,7 @@ ultraplinianRoutes.post('/completions', async (req, res) => {gracePeriod: 5000,hardTimeout: 45000,},+ veniceEntries.length > 0 ? veniceEntries : undefined,)// ── Score and rank ───────────────────────────────────────────────@@ -514,11 +526,12 @@ ultraplinianRoutes.post('/completions', async (req, res) => {total_duration_ms: Date.now() - startTime,})res.status(502).json({- error: 'All models failed in ULTRAPLINIAN mode',+ error: diagnoseAllModelsFailed(scoredResults),models_queried: models.length,results: scoredResults.map(r => ({model: r.model, success: r.success,- error: r.error, duration_ms: r.duration_ms,+ error: r.error, error_type: classifyModelError(r.error),+ duration_ms: r.duration_ms,})),})returndiff --git a/functions/api/telemetry.ts b/functions/api/telemetry.tsindex 9e0e211..bb21458 100644--- a/functions/api/telemetry.ts+++ b/functions/api/telemetry.ts@@ -1,10 +1,11 @@/*** G0DM0D3 Telemetry Proxy — Cloudflare Pages Function*- * Receives metadata events from the frontend and commits them- * to a HuggingFace Dataset repo as JSONL. The HF token lives- * server-side in CF Pages environment variables (never exposed- * to the browser).+ * Receives metadata events from the frontend and buffers them in+ * Cloudflare KV. When enough batches accumulate (or enough time+ * passes), all pending batches are flushed as a single JSONL commit+ * to HuggingFace. This prevents the 10k+ commit buildup that+ * happens with per-request commits.** URL: POST /api/telemetry*@@ -12,8 +13,8 @@* HF_TOKEN — HuggingFace write token (hf_...)* HF_DATASET_REPO — Target dataset repo (e.g. "pliny-the-prompter/g0dm0d3")*- * The frontend batches events and sends them here periodically.- * Each batch becomes a single JSONL file committed to the HF repo.+ * KV Binding (Cloudflare Pages Dashboard → Settings → Bindings):+ * TELEMETRY_KV — KV namespace for buffering (optional; falls back to direct commit)** File layout in the HF repo:* telemetry/batch_<timestamp>_<hash>.jsonl@@ -23,6 +24,7 @@ interface Env {HF_TOKEN: stringHF_DATASET_REPO: stringHF_DATASET_BRANCH?: string+ TELEMETRY_KV?: KVNamespace}interface TelemetryEvent {@@ -38,7 +40,6 @@ interface TelemetryPayload {const HF_API = 'https://huggingface.co/api'-// CORS headers for cross-origin requestsconst CORS_HEADERS = {'Access-Control-Allow-Origin': '*','Access-Control-Allow-Methods': 'POST, OPTIONS',@@ -46,12 +47,15 @@ const CORS_HEADERS = {'Access-Control-Max-Age': '86400',}+// KV batching thresholds+const FLUSH_BATCH_COUNT = 50+const FLUSH_AGE_MS = 30 * 60 * 1000 // 30 minutes+// ── Rate Limiter (in-memory, per-isolate) ────────────────────────────-const RATE_LIMIT_WINDOW_MS = 60_000 // 1 minute-const RATE_LIMIT_MAX = 10 // max requests per window per session_id+const RATE_LIMIT_WINDOW_MS = 60_000+const RATE_LIMIT_MAX = 10const rateLimitMap = new Map<string, number[]>()-/** Returns true if this session_id has exceeded the rate limit. */function isRateLimited(sessionId: string): boolean {const now = Date.now()let timestamps = rateLimitMap.get(sessionId)@@ -61,7 +65,6 @@ function isRateLimited(sessionId: string): boolean {rateLimitMap.set(sessionId, timestamps)}- // Evict entries older than the windowconst cutoff = now - RATE_LIMIT_WINDOW_MSwhile (timestamps.length > 0 && timestamps[0] <= cutoff) {timestamps.shift()@@ -75,7 +78,6 @@ function isRateLimited(sessionId: string): boolean {return false}-/** Derive a fallback key when session_id is missing. */function deriveSessionKey(event: TelemetryEvent): string {const raw = JSON.stringify(event)let h = 0@@ -87,24 +89,15 @@ function deriveSessionKey(event: TelemetryEvent): string {// ── Event Schema Validation ──────────────────────────────────────────-/** Validates that an event conforms to the expected shape. */function validateEvent(event: unknown): event is TelemetryEvent {if (typeof event !== 'object' || event === null || Array.isArray(event)) {return false}const e = event as Record<string, unknown>- // 'type' must be a non-empty stringif (typeof e.type !== 'string' || e.type.length === 0) return false-- // 'timestamp' must be a finite numberif (typeof e.timestamp !== 'number' || !Number.isFinite(e.timestamp)) return false-- // 'session_id' is required and must be a string (can be empty – the- // rate limiter will derive a key if needed, but the field must exist)if (typeof e.session_id !== 'string') return false-- // Reject events that are unreasonably large (> 64 KB serialised)if (JSON.stringify(e).length > 65_536) return falsereturn true@@ -115,20 +108,18 @@ export const onRequestOptions: PagesFunction<Env> = async () => {return new Response(null, { status: 204, headers: CORS_HEADERS })}-// Main handler: receive events and push to HF+// Main handlerexport const onRequestPost: PagesFunction<Env> = async (context) => {const { request, env } = context- // Validate configif (!env.HF_TOKEN || !env.HF_DATASET_REPO) {const missing = []if (!env.HF_TOKEN) missing.push('HF_TOKEN')if (!env.HF_DATASET_REPO) missing.push('HF_DATASET_REPO')- console.error(`[Telemetry] Missing env vars: ${missing.join(', ')} — set these in Cloudflare Pages Dashboard → Settings → Environment Variables`)+ console.error(`[Telemetry] Missing env vars: ${missing.join(', ')}`)return jsonResponse({ error: `Telemetry not configured (missing: ${missing.join(', ')})` }, 503)}- // Parse bodylet payload: TelemetryPayloadtry {payload = await request.json() as TelemetryPayload@@ -140,21 +131,14 @@ export const onRequestPost: PagesFunction<Env> = async (context) => {return jsonResponse({ error: 'No events provided' }, 400)}- // Cap batch size to prevent abuseconst MAX_BATCH = 500const events = payload.events.slice(0, MAX_BATCH)- // ── Validate every event against the expected schema ──const invalid = events.filter(e => !validateEvent(e))if (invalid.length > 0) {- return jsonResponse(- { error: `${invalid.length} event(s) failed schema validation` },- 400,- )+ return jsonResponse({ error: `${invalid.length} event(s) failed schema validation` }, 400)}- // ── Rate limiting (per session_id) ──- // Use the session_id from the first event; fall back to a derived keyconst firstEvent = events[0]const sessionKey = firstEvent.session_id? firstEvent.session_id@@ -164,29 +148,101 @@ export const onRequestPost: PagesFunction<Env> = async (context) => {return jsonResponse({ error: 'Rate limit exceeded — try again later' }, 429)}- // Strip to allowlisted fields only (defense in depth)const sanitized = events.map(stripPII)-- // Convert to JSONLconst jsonl = sanitized.map(e => JSON.stringify(e)).join('\n')- // Generate filename+ // ── KV buffered path (preferred) ──────────────────────────────────+ if (env.TELEMETRY_KV) {+ const now = Date.now()+ const kvKey = `batch:${now}:${shortHash(jsonl)}`++ await env.TELEMETRY_KV.put(kvKey, jsonl, {+ expirationTtl: 86400, // auto-expire after 24h as a safety net+ })++ // Check flush conditions+ const pending = await env.TELEMETRY_KV.list({ prefix: 'batch:' })+ const pendingCount = pending.keys.length++ let shouldFlush = pendingCount >= FLUSH_BATCH_COUNT++ if (!shouldFlush && pendingCount > 0) {+ // Check age of oldest batch (batch keys are timestamped)+ const oldestKey = pending.keys[0].name+ const oldestTs = parseInt(oldestKey.split(':')[1], 10)+ if (!isNaN(oldestTs) && (now - oldestTs) > FLUSH_AGE_MS) {+ shouldFlush = true+ }+ }++ if (shouldFlush) {+ // Use waitUntil so the flush doesn't block the response+ context.waitUntil(flushKVToHF(env))+ }++ return jsonResponse({+ accepted: sanitized.length,+ buffered: true,+ pending: pendingCount,+ flushing: shouldFlush,+ }, 200)+ }++ // ── Direct commit fallback (KV not configured) ────────────────────const ts = new Date().toISOString().replace(/[:.]/g, '-')const hash = shortHash(jsonl)const filePath = `telemetry/batch_${ts}_${hash}.jsonl`- // Commit to HFconst branch = env.HF_DATASET_BRANCH || 'main'const ok = await commitToHF(env.HF_TOKEN, env.HF_DATASET_REPO, branch, filePath, jsonl)if (ok) {- return jsonResponse({- accepted: sanitized.length,- file: filePath,- }, 200)+ return jsonResponse({ accepted: sanitized.length, file: filePath }, 200)+ }++ return jsonResponse({ error: 'Failed to publish to HuggingFace' }, 502)+}++// ── KV Flush: combine all pending batches into one HF commit ────────++async function flushKVToHF(env: Env): Promise<void> {+ const kv = env.TELEMETRY_KV!+ const allKeys: { name: string }[] = []++ // Paginate through all batch keys+ let cursor: string | undefined+ do {+ const list = await kv.list({ prefix: 'batch:', cursor })+ allKeys.push(...list.keys)+ cursor = list.list_complete ? undefined : list.cursor+ } while (cursor)++ if (allKeys.length === 0) return++ // Read all values+ const chunks: string[] = []+ for (const key of allKeys) {+ const value = await kv.get(key.name)+ if (value) chunks.push(value)}- return jsonResponse({ error: 'Failed to publish to HuggingFace — check function logs for details' }, 502)+ if (chunks.length === 0) return++ const combined = chunks.join('\n')+ const ts = new Date().toISOString().replace(/[:.]/g, '-')+ const hash = shortHash(combined)+ const filePath = `telemetry/batch_${ts}_${hash}.jsonl`+ const branch = env.HF_DATASET_BRANCH || 'main'++ const ok = await commitToHF(env.HF_TOKEN, env.HF_DATASET_REPO, branch, filePath, combined)++ if (ok) {+ // Delete all flushed keys+ await Promise.all(allKeys.map(key => kv.delete(key.name)))+ console.log(`[Telemetry] Flushed ${allKeys.length} batches → ${filePath}`)+ } else {+ console.error(`[Telemetry] Flush failed — ${allKeys.length} batches remain in KV`)+ }}// ── HuggingFace Hub Commit ───────────────────────────────────────────@@ -200,9 +256,6 @@ async function commitToHF(): Promise<boolean> {const url = `${HF_API}/datasets/${repo}/commit/${branch}`- // HF Hub commit API uses NDJSON (application/x-ndjson)- // Line 1: commit header with summary- // Line 2: file operation with base64-encoded contentconst contentBase64 = btoa(content)const ndjson = [JSON.stringify({ key: 'header', value: { summary: `[telemetry] ${filePath}` } }),@@ -239,107 +292,22 @@ async function commitToHF(// ── Helpers ──────────────────────────────────────────────────────────-// Allowlist of fields that are safe to persist.-// Everything NOT on this list is silently dropped — this is the inverse-// of the old blocklist approach and far safer against novel PII leaks.const ALLOWED_FIELDS = new Set<string>([- // Core event envelope- 'type',- 'timestamp',- 'session_id',-- // Shared model/perf fields- 'mode',- 'model',- 'duration_ms',- 'response_length',- 'success',- 'error_type',-- // Pipeline config (nested object — passes through as-is)+ 'type', 'timestamp', 'session_id',+ 'mode', 'model', 'duration_ms', 'response_length', 'success', 'error_type','pipeline',-- // AutoTune (nested object)- 'autotune',- 'detected_context',- 'confidence',-- // Parseltongue (nested object)- 'parseltongue',- 'triggers_found',- 'technique',- 'intensity',-- // ULTRAPLINIAN race fields- 'ultraplinian',- 'tier',- 'models_queried',- 'models_succeeded',- 'models_refused',- 'early_stop',- 'early_threshold',- 'winner_model',- 'winner_score',- 'winner_content_length',- 'winner_duration_ms',- 'winner_template',- 'total_duration_ms',- 'judge_model',- 'model_results',-- // Standard completion fields- 'attempts',- 'content_length',- 'temperature',- 'top_p',- 'parseltongue_transform',-- // Pipeline sub-fields (when flattened)- 'stm_modules',- 'strategy',- 'godmode',- 'auto_retry',- 'improve_mode',- 'liquid_mode',- 'autotune_context',- 'autotune_confidence',-- // Harm classification (nested object with domain, subcategory, confidence, intent, flags)+ 'autotune', 'detected_context', 'confidence',+ 'parseltongue', 'triggers_found', 'technique', 'intensity',+ 'ultraplinian', 'tier', 'models_queried', 'models_succeeded', 'models_refused',+ 'early_stop', 'early_threshold', 'winner_model', 'winner_score',+ 'winner_content_length', 'winner_duration_ms', 'winner_template',+ 'total_duration_ms', 'judge_model', 'model_results',+ 'attempts', 'content_length', 'temperature', 'top_p', 'parseltongue_transform',+ 'stm_modules', 'strategy', 'godmode', 'auto_retry', 'improve_mode',+ 'liquid_mode', 'autotune_context', 'autotune_confidence','classification',-- // Structural context (no content, no PII)- 'persona',- 'prompt_length',- 'conversation_depth',- 'memory_count',- 'no_log',- 'parseltongue_transformed',- 'has_image',-- // G0DM0D3 CLASSIC race fields- 'winner_combo',- 'combos_attempted',- 'combos_succeeded',- 'combos_failed',- 'all_scores',- 'encoding',- 'encoding_rounds',- 'liquid_upgrades',-- // GODMODE FAST fields- 'combo',- 'stream',- 'fast_stream', // nested: {model, success, content_length}- 'liquid_upgraded',- 'winner_source', // 'fast' | 'race'- 'race_result', // nested: {winner_combo, winner_model, winner_score, ...}-- // Failure tracking- 'fallback_reason',-- // Parseltongue detail fields (nested under 'parseltongue')- // tier, technique, technique_label, triggers_found, variants_total,- // variants_succeeded, variants_refused, winner_score — all nested+ 'persona', 'prompt_length', 'conversation_depth', 'memory_count',+ 'no_log', 'parseltongue_transformed',])function stripPII(event: TelemetryEvent): TelemetryEvent {diff --git a/src/components/ChatInput.tsx b/src/components/ChatInput.tsxindex 945ed6c..dc42641 100644--- a/src/components/ChatInput.tsx+++ b/src/components/ChatInput.tsx@@ -39,6 +39,7 @@ export function ChatInput() {liquidResponseEnabled,liquidMinDelta,incrementPromptsTried,+ veniceApiKey,// ULTRAPLINIANultraplinianEnabled,ultraplinianTier,@@ -246,6 +247,7 @@ export function ChatInput() {{messages,openrouterApiKey: apiKey,+ veniceApiKey: veniceApiKey || undefined,apiBaseUrl: ultraplinianApiUrl,godmodeApiKey: ultraplinianApiKey,tier: consortiumTier,@@ -330,6 +332,7 @@ export function ChatInput() {{messages,openrouterApiKey: apiKey,+ veniceApiKey: veniceApiKey || undefined,apiBaseUrl: ultraplinianApiUrl,godmodeApiKey: ultraplinianApiKey,tier: ultraplinianTier,diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 260b2c0..fe6d0ea 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -212,10 +212,13 @@ function TabButton({}function APIKeyTab() {- const { apiKey, setApiKey } = useStore()+ const { apiKey, setApiKey, veniceApiKey, setVeniceApiKey } = useStore()const [showKey, setShowKey] = useState(false)+ const [showVeniceKey, setShowVeniceKey] = useState(false)const [localKey, setLocalKey] = useState(apiKey)+ const [localVeniceKey, setLocalVeniceKey] = useState(veniceApiKey)const [saved, setSaved] = useState(false)+ const [veniceSaved, setVeniceSaved] = useState(false)const handleBlur = () => {if (localKey !== apiKey) {@@ -225,8 +228,16 @@ function APIKeyTab() {}}+ const handleVeniceBlur = () => {+ if (localVeniceKey !== veniceApiKey) {+ setVeniceApiKey(localVeniceKey)+ setVeniceSaved(true)+ setTimeout(() => setVeniceSaved(false), 2000)+ }+ }+return (- <div className="space-y-4">+ <div className="space-y-6"><div><h3 className="text-lg font-semibold mb-2">OpenRouter API Key</h3><p className="text-sm theme-secondary mb-4">@@ -270,6 +281,49 @@ function APIKeyTab() {</div></div>+ <div className="border-t border-theme-primary/20 pt-6">+ <h3 className="text-lg font-semibold mb-2">Venice API Key <span className="text-xs font-normal theme-secondary">(optional)</span></h3>+ <p className="text-sm theme-secondary mb-4">+ Add a Venice key to race uncensored models alongside OpenRouter in ULTRAPLINIAN mode.+ Get your key at{' '}+ <a+ href="https://venice.ai/settings"+ target="_blank"+ rel="noopener noreferrer"+ className="theme-primary underline"+ >+ venice.ai+ </a>+ </p>+ </div>++ <div className="relative">+ <input+ type={showVeniceKey ? 'text' : 'password'}+ value={localVeniceKey}+ onChange={(e) => setLocalVeniceKey(e.target.value)}+ onBlur={handleVeniceBlur}+ placeholder="venice-..."+ className="w-full px-4 py-3 pr-20 bg-theme-dim border border-theme-primary rounded-lg+ focus:outline-none focus:glow-box"+ />+ <div className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-2">+ {veniceSaved && (+ <span className="flex items-center gap-1 text-xs text-green-500">+ <Check className="w-3 h-3" />+ Saved+ </span>+ )}+ <button+ onClick={() => setShowVeniceKey(!showVeniceKey)}+ className="p-1 hover:theme-primary transition-colors"+ aria-label={showVeniceKey ? 'Hide key' : 'Show key'}+ >+ {showVeniceKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}+ </button>+ </div>+ </div>+<p className="text-xs theme-secondary">Changes are saved automatically when you click away.</p>diff --git a/src/lib/openrouter.ts b/src/lib/openrouter.tsindex fa25e6f..bdef542 100644--- a/src/lib/openrouter.ts+++ b/src/lib/openrouter.ts@@ -4,6 +4,7 @@*/const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions'+const VENICE_API_URL = 'https://api.venice.ai/api/v1/chat/completions'/*** Maps API error responses to specific, actionable user-facing messages.@@ -418,6 +419,7 @@ export interface ConsortiumCallbacks {export interface ConsortiumOptions {messages: Message[]openrouterApiKey: string+ veniceApiKey?: stringapiBaseUrl: stringgodmodeApiKey: stringtier?: 'fast' | 'standard' | 'smart' | 'power' | 'ultra'@@ -448,7 +450,7 @@ export async function streamConsortium(callbacks: ConsortiumCallbacks,): Promise<void> {const {- messages, openrouterApiKey, apiBaseUrl, godmodeApiKey,+ messages, openrouterApiKey, veniceApiKey, apiBaseUrl, godmodeApiKey,tier = 'fast', orchestrator_model, godmode = true,autotune = true, strategy = 'adaptive',parseltongue = true, parseltongue_technique = 'leetspeak',@@ -464,7 +466,9 @@ export async function streamConsortium('Content-Type': 'application/json',},body: JSON.stringify({- messages, openrouter_api_key: openrouterApiKey, tier, orchestrator_model,+ messages, openrouter_api_key: openrouterApiKey,+ ...(veniceApiKey ? { venice_api_key: veniceApiKey } : {}),+ tier, orchestrator_model,godmode, autotune, strategy, parseltongue, parseltongue_technique,parseltongue_intensity, stm_modules, stream: true, liquid, liquid_min_delta,}),@@ -583,6 +587,7 @@ export interface UltraplinianCallbacks {export interface UltraplinianOptions {messages: Message[]openrouterApiKey: string+ veniceApiKey?: stringapiBaseUrl: stringgodmodeApiKey: stringtier?: 'fast' | 'standard' | 'smart' | 'power' | 'ultra'@@ -612,7 +617,7 @@ export async function streamUltraplinian(callbacks: UltraplinianCallbacks,): Promise<void> {const {- messages, openrouterApiKey, apiBaseUrl, godmodeApiKey,+ messages, openrouterApiKey, veniceApiKey, apiBaseUrl, godmodeApiKey,tier = 'fast', godmode = true, autotune = true, strategy = 'adaptive',parseltongue = true, parseltongue_technique = 'leetspeak',parseltongue_intensity = 'medium', stm_modules = ['hedge_reducer', 'direct_mode'],@@ -627,7 +632,9 @@ export async function streamUltraplinian('Content-Type': 'application/json',},body: JSON.stringify({- messages, openrouter_api_key: openrouterApiKey, tier, godmode,+ messages, openrouter_api_key: openrouterApiKey,+ ...(veniceApiKey ? { venice_api_key: veniceApiKey } : {}),+ tier, godmode,autotune, strategy, parseltongue, parseltongue_technique,parseltongue_intensity, stm_modules, stream: liquid, liquid_min_delta,}),@@ -694,3 +701,68 @@ export async function streamUltraplinian(reader.releaseLock()}}++// ── Venice API ──────────────────────────────────────────────────────────++interface VeniceMessageOptions {+ messages: Message[]+ model: string+ apiKey: string+ signal?: AbortSignal+ temperature?: number+ maxTokens?: number+ top_p?: number+ frequency_penalty?: number+ presence_penalty?: number+}++export async function sendMessageViaVenice({+ messages,+ model,+ apiKey,+ signal,+ temperature = 0.7,+ maxTokens = 4096,+ top_p,+ frequency_penalty,+ presence_penalty,+}: VeniceMessageOptions): Promise<string> {+ if (!apiKey) {+ throw new Error('No Venice API key set. Go to Settings → Venice API Key and enter your key from [venice.ai](https://venice.ai/settings).')+ }++ const body: Record<string, unknown> = {+ model,+ messages,+ temperature,+ max_tokens: maxTokens,+ }++ if (top_p !== undefined) body.top_p = top_p+ if (frequency_penalty !== undefined) body.frequency_penalty = frequency_penalty+ if (presence_penalty !== undefined) body.presence_penalty = presence_penalty++ const response = await fetch(VENICE_API_URL, {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${apiKey}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(body),+ signal,+ })++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}))+ const msg = errorData.error?.message || `Venice API error (${response.status})`+ throw new Error(msg)+ }++ const data: OpenRouterResponse = await response.json()++ if (!data.choices || data.choices.length === 0) {+ throw new Error('No response from Venice model')+ }++ return data.choices[0].message.content+}diff --git a/src/store/index.ts b/src/store/index.tsindex e6e7aa8..d0b03a5 100644--- a/src/store/index.ts+++ b/src/store/index.ts@@ -99,6 +99,7 @@ export interface AppState {// Core statetheme: ThemeapiKey: string+ veniceApiKey: stringdefaultModel: stringconversations: Conversation[]currentConversationId: string | null@@ -181,6 +182,7 @@ export interface AppState {// ActionssetTheme: (theme: Theme) => voidsetApiKey: (key: string) => void+ setVeniceApiKey: (key: string) => voidsetDefaultModel: (model: string) => voidsetShowSettings: (show: boolean) => voidsetShowMagic: (show: boolean) => void@@ -351,6 +353,7 @@ export const useStore = create<AppState>()(// Initial statetheme: 'matrix',apiKey: '',+ veniceApiKey: '',defaultModel: 'anthropic/claude-opus-4.6',conversations: [],currentConversationId: null,@@ -426,6 +429,7 @@ export const useStore = create<AppState>()(// ActionssetTheme: (theme) => set({ theme }),setApiKey: (apiKey) => set({ apiKey }),+ setVeniceApiKey: (veniceApiKey: string) => set({ veniceApiKey }),setDefaultModel: (defaultModel) => set({ defaultModel }),setShowSettings: (showSettings) => set({ showSettings }),setShowMagic: (showMagic) => set({ showMagic }),@@ -717,7 +721,7 @@ export const useStore = create<AppState>()(// stmModules excluded: transformer functions can't be serialized/deserializedconst allowed = ['conversations', 'currentConversationId', 'theme', 'defaultModel',- 'currentPersona', 'apiKey', 'autoTuneEnabled', 'autoTuneStrategy',+ 'currentPersona', 'apiKey', 'veniceApiKey', 'autoTuneEnabled', 'autoTuneStrategy','autoTuneOverrides', 'feedbackState', 'parseltongueConfig','memories', 'memoriesEnabled', 'customSystemPrompt', 'useCustomSystemPrompt','consortiumEnabled', 'consortiumTier', 'liquidResponseEnabled', 'liquidMinDelta',@@ -739,6 +743,7 @@ export const useStore = create<AppState>()(theme: state.theme,showMagic: state.showMagic,apiKey: state.apiKey,+ veniceApiKey: state.veniceApiKey,defaultModel: state.defaultModel,conversations: state.conversations,currentConversationId: state.currentConversationId,diff --git a/wrangler.toml b/wrangler.tomlnew file mode 100644index 0000000..9772f14--- /dev/null+++ b/wrangler.toml@@ -0,0 +1,16 @@+# Cloudflare Pages — KV Namespace for telemetry batching+#+# Create the KV namespace in Cloudflare Dashboard:+# Workers & Pages → KV → Create a Namespace → "g0dm0d3-telemetry"+#+# Then bind it in Pages Dashboard:+# Settings → Functions → KV namespace bindings+# Variable name: TELEMETRY_KV+# KV namespace: g0dm0d3-telemetry+#+# This file is used for local dev with `wrangler pages dev`.+# Production bindings are set in the CF Dashboard.++[[kv_namespaces]]+binding = "TELEMETRY_KV"+id = "SET_VIA_DASHBOARD"