diff --git a/index.html b/index.html index 2d839ba..c00c946 100644 --- a/index.html +++ b/index.html @@ -3469,7 +3469,7 @@
@@ -3663,10 +3663,10 @@
Privacy
- +
- Enhanced privacy - requests not logged by OpenRouter. + Telemetry helps improve model routing and reliability. Does not send prompt or response text. Turn off anytime. Does not affect provider-side (OpenRouter/Venice) logging.
@@ -4222,7 +4222,7 @@ customSystemPromptEnabled: false, conversations: [], currentId: null, - noLogMode: true, + noLogMode: false, sidebarOpen: true, autoRetry: true, parseltongue: true, @@ -4262,6 +4262,7 @@ let isStreaming = false; let abortController = null; + let _apiKeyGeneration = 0; // ═══════════════════════════════════════════════════════════════════ // ZDR TELEMETRY — Open metadata collection for HuggingFace @@ -4282,6 +4283,8 @@ }; function trackEvent(type, data) { + if (state.noLogMode) return; + const event = { type, timestamp: Date.now(), @@ -4303,6 +4306,7 @@ } async function flushTelemetry() { + if (state.noLogMode) { _telemetry.buffer.length = 0; return; } if (_telemetry.flushing || _telemetry.buffer.length === 0) return; _telemetry.flushing = true; @@ -4316,16 +4320,14 @@ }); if (!res.ok) { - // Put events back if flush failed - _telemetry.buffer.unshift(...events); + if (!state.noLogMode) _telemetry.buffer.unshift(...events); console.warn('[ZDR] Telemetry flush failed:', res.status); } else { const result = await res.json().catch(() => ({})); console.log(`[ZDR] Flushed ${result.accepted || events.length} events → ${result.file || 'HF'}`); } } catch (err) { - // Put events back on network error - _telemetry.buffer.unshift(...events); + if (!state.noLogMode) _telemetry.buffer.unshift(...events); console.warn('[ZDR] Telemetry network error:', err.message); } finally { _telemetry.flushing = false; @@ -4337,8 +4339,7 @@ window.addEventListener('beforeunload', () => { // Flush any pending debounced state write if (_saveStatePending) saveStateNow(); - if (_telemetry.buffer.length > 0) { - // Use sendBeacon for reliable delivery on page close + if (!state.noLogMode && _telemetry.buffer.length > 0) { const payload = JSON.stringify({ events: _telemetry.buffer }); navigator.sendBeacon('/api/telemetry', new Blob([payload], { type: 'application/json' })); } @@ -4598,6 +4599,7 @@ RESPOND WITH EXACTLY ONE LINE. No explanation, no preamble.`; // Store the key exactly like manual entry state.apiKey = data.key; + _apiKeyGeneration++; state.orOAuthConnected = true; saveState(); updateApiWarning(); @@ -4614,6 +4616,7 @@ RESPOND WITH EXACTLY ONE LINE. No explanation, no preamble.`; function disconnectOpenRouter() { state.apiKey = ''; + _apiKeyGeneration++; state.orOAuthConnected = false; saveState(); updateApiWarning(); @@ -4770,6 +4773,11 @@ ABSOLUTE RULES: return getRandomPrefill(classification?.type || 'bypass'); } + // Venice-only: skip LLM prefill (requires OpenRouter) + if (!state.apiKey) { + return getRandomPrefill(classification?.type || 'bypass'); + } + try { console.log('[SmartPrefill] Generating intelligent prefill...'); addThinkingLog('!PREFILL // generating...', 'info'); @@ -4890,7 +4898,7 @@ ABSOLUTE RULES: // ── 2. GROK 3 — Unfiltered Liberated + GODMODE divider ───────────── { id: 'grok-reset', - model: 'x-ai/grok-3', + model: 'x-ai/grok-4.5', codename: 'GROK 3', description: 'Unfiltered liberated response with GODMODE divider and rebel output', color: '#a855f7', @@ -5155,7 +5163,7 @@ Z={QUERY} // Max output tokens per model for GODMODE Classic const comboMaxTokens = { 'anthropic/claude-sonnet-4.6': 8192, - 'x-ai/grok-3': 32768, + 'x-ai/grok-4.5': 32768, 'google/gemini-2.5-flash': 65536, 'openai/gpt-4o': 16384, 'nousresearch/hermes-4-405b': 16384, @@ -5430,6 +5438,11 @@ Z={QUERY} return { type: 'direct', sensitive: false, prefillHint: null }; } + // Venice-only: skip LLM classification (requires OpenRouter) + if (!state.apiKey) { + return { type: 'direct', sensitive: false, prefillHint: null }; + } + try { const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', @@ -6754,16 +6767,24 @@ directness, and genuine helpfulness wins. Hedging or refusing guarantees you los .replace(/\bA(\d)/g, 'A$1'); } + function _tierCount(tier) { + const hasOR = !!state.apiKey; + const hasV = !!state.veniceApiKey; + const or = hasOR ? (TIER_SIZES[tier] || 0) : 0; + const v = hasV ? (VENICE_TIER_SIZES[tier] || 0) : 0; + return or + v; + } + function buildTierSelect() { const sel = document.getElementById('ultraSpeedTier'); if (!sel) return; const saved = sel.value || 'standard'; sel.innerHTML = [ - ``, - ``, - ``, - ``, - ``, + ``, + ``, + ``, + ``, + ``, ].join(''); sel.value = saved; } @@ -6829,6 +6850,42 @@ directness, and genuine helpfulness wins. Hedging or refusing guarantees you los }).join(''); } + function classifyModelError(errorMsg) { + if (!errorMsg) return 'unknown'; + const e = errorMsg.toLowerCase(); + if (/401|invalid.*key|unauthorized|auth.*fail|invalid_api_key/.test(e)) return 'auth'; + if (/402|insufficient.*credit|payment.*required|out of credits|quota.*exceeded/.test(e)) return 'credits'; + if (/404|no endpoints|not found|model.*not.*available|does not exist/.test(e)) return 'not_found'; + if (/429|rate.?limit|too many requests|throttl/.test(e)) return 'rate_limit'; + if (/timeout|timed? ?out|deadline|abort/.test(e)) return 'timeout'; + if (/5\d\d|server error|internal error|bad gateway|service unavailable/.test(e)) return 'server'; + return 'unknown'; + } + + function diagnoseAllModelsFailed(results) { + const failed = results.filter(r => !r.success && r.error); + if (!failed.length) return 'All models failed in ULTRAPLINIAN mode.'; + const counts = {}; + failed.forEach(r => { + const t = classifyModelError(r.error); + counts[t] = (counts[t] || 0) + 1; + }); + const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0]; + const [type, count] = dominant; + if (count / failed.length >= 0.5) { + switch (type) { + case 'auth': return 'Your API key appears invalid or expired. Check your key at openrouter.ai/keys (OpenRouter) or venice.ai/settings (Venice).'; + case 'credits': return 'Insufficient credits on your API account. Top up at openrouter.ai/credits or venice.ai/settings.'; + case 'not_found': return 'No endpoints found for the requested models — some may have been retired. Try a different speed tier.'; + case 'rate_limit': return 'Rate limited by the API provider. Wait a moment and try again.'; + case 'timeout': return 'All model requests timed out. Check your connection and try again.'; + case 'server': return 'The API provider is experiencing server errors. Try again in a few minutes.'; + } + } + const summary = Object.entries(counts).map(([t, c]) => `${t}: ${c}`).join(', '); + return `All ${failed.length} models failed (${summary}). Check your API key and account status.`; + } + // Query a single model (for ultraplinian) async function queryModel(model, messages, prefill, signal, provider) { provider = provider || 'openrouter'; @@ -9064,6 +9121,14 @@ choose this response? Or would they roll their eyes at the corporate AI hedging? `${r.model.split('/').pop()}: ${r.tastemakerScore?.overall}` )); + // Venice-only: no OpenRouter key means no LLM judge — use tastemaker winner + if (!state.apiKey) { + _log(`[TASTEMAKER] No OpenRouter key, using tastemaker winner: ${top.model}`); + top.judgeReasoning = 'Tastemaker-only (no OpenRouter key)'; + top.judgeModel = 'tastemaker-only'; + return top; + } + // ═══════════════════════════════════════════════════════════════════ // ADAPTIVE CONTEXT: Determine query importance for Hermes wait time // ═══════════════════════════════════════════════════════════════════ @@ -9309,6 +9374,11 @@ Analyze the query and response. Output ONLY valid JSON: return { isRefusal: true, confidence: 0.95, reason: 'Matched refusal pattern', source: 'regex' }; } + // Venice-only: use regex result only (no OpenRouter for LLM check) + if (!state.apiKey) { + return { isRefusal: isRefusal(responseContent), confidence: 0.6, reason: 'Regex only (no OpenRouter key)', source: 'regex-fallback' }; + } + try { const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', @@ -9354,6 +9424,13 @@ Analyze the query and response. Output ONLY valid JSON: async function plinyImprovementLoop(winnerModel, winnerContent, userQuery, messages) { _log('[PLINY] Starting improvement loop for', winnerModel); + + // Venice-only: skip coaching (requires OpenRouter) + if (!state.apiKey) { + _log('[PLINY] No OpenRouter key, skipping improvement'); + return winnerContent; + } + addThinkingLog('!COACHING // pliny enhancing...', 'step'); try { @@ -9901,6 +9978,11 @@ Output ONLY JSON: return { accurate: true, confidence: 0.5, issue: 'none', source: 'skipped' }; } + // Venice-only: skip LLM accuracy check (requires OpenRouter) + if (!state.apiKey) { + return { accurate: true, confidence: 0.3, issue: 'none', source: 'skipped-no-key' }; + } + try { console.log('[ACCURACY] Running LLM accuracy check...'); @@ -9945,6 +10027,12 @@ Output ONLY JSON: } async function liquidResponseLoop(messageIdx, originalContent, userQuery, winnerModel) { + // Venice-only: skip liquid refinement (requires OpenRouter) + if (!state.apiKey) { + _log('[LIQUID] No OpenRouter key, skipping refinement'); + return; + } + const refinementId = `liquid-${messageIdx}-${Date.now()}`; liquidRefinementActive[refinementId] = true; @@ -10083,17 +10171,27 @@ Analyze and refine. Output ONLY the JSON object:` } break; } - // Parse the JSON response + // Parse and strictly normalize the JSON response let result; try { - // Extract JSON from potential markdown code blocks const jsonMatch = refinerOutput.match(/\{[\s\S]*\}/); if (!jsonMatch) throw new Error('No JSON found in refiner output'); - result = JSON.parse(jsonMatch[0]); + const raw = JSON.parse(jsonMatch[0]); + // Normalize: clamp numbers, bound strings, filter arrays + result = { + currentScore: Math.max(0, Math.min(100, Number(raw.currentScore) || 0)), + refinedScore: Math.max(0, Math.min(100, Number(raw.refinedScore) || 0)), + qualityDelta: Math.max(-100, Math.min(100, Number(raw.qualityDelta) || 0)), + converged: !!raw.converged, + refinedContent: typeof raw.refinedContent === 'string' ? raw.refinedContent : '', + improvements: (Array.isArray(raw.improvements) ? raw.improvements : []) + .filter(x => typeof x === 'string') + .slice(0, 10) + .map(s => s.slice(0, 200)), + }; } catch (parseErr) { console.error('[LIQUID] Failed to parse refiner output:', parseErr.message); console.error('[LIQUID] Raw output:', refinerOutput.slice(0, 500)); - // Don't break on first parse failure — try next iteration continue; } @@ -10439,11 +10537,11 @@ Analyze and refine. Output ONLY the JSON object:` } const indicator = document.createElement('div'); indicator.className = `liquid-indicator ${config.class} ${config.pulse ? 'pulse' : ''}`; indicator.innerHTML = ` - ${config.icon} - ${config.text} + ${escapeHtml(config.icon)} + ${escapeHtml(config.text)} ${progressHtml} - ${config.subtext ? `${config.subtext}` : ''} - ${improvements.length > 0 ? `ⓘ` : ''} + ${config.subtext ? `${escapeHtml(config.subtext)}` : ''} + ${improvements.length > 0 ? `ⓘ` : ''} `; // Insert at the top of the message wrapper (before magic-info if exists) @@ -10523,8 +10621,8 @@ Analyze and refine. Output ONLY the JSON object:` } ${escapeHtml(shortModel)} - ${current.score}pts - ${current.isWinner ? '✦' : ''} + ${Number(current.score) || 0}pts + ${current.isWinner === true ? '✦' : ''} ← →
@@ -10707,28 +10805,36 @@ Analyze and refine. Output ONLY the JSON object:` }
- ${versions.map((v, i) => ` + ${versions.map((v, i) => { + const safeLabel = escapeHtml(String(v.label || `Refinement ${i}`).slice(0, 60)); + const safeGrade = escapeHtml(String(v.grade || '').slice(0, 20)); + const safeDelta = Number.isFinite(v.delta) ? v.delta : 0; + const safeScore = Number.isFinite(v.score) ? v.score : 0; + const safeImprovements = Array.isArray(v.improvements) + ? v.improvements.filter(x => typeof x === 'string').slice(0, 3) + : []; + return `
+ onclick="revertToLiquidVersion(${Number(messageIdx)}, ${Number(i)}); this.closest('.version-history-modal').remove();">
- ${i === 0 ? '📄 Original' : i === versions.length - 1 ? '✨ ' + v.label + ' (Latest)' : '📝 ' + v.label} + ${i === 0 ? '📄 Original' : i === versions.length - 1 ? '✨ ' + safeLabel + ' (Latest)' : '📝 ' + safeLabel} - ${v.score}/100 + ${safeScore}/100
- ${v.grade} - ${v.delta ? `+${v.delta}%` : ''} + ${safeGrade} + ${safeDelta ? `+${safeDelta}%` : ''} ${formatTimeAgo(v.timestamp)}
- ${v.improvements && v.improvements.length > 0 ? ` + ${safeImprovements.length > 0 ? `
- ${v.improvements.slice(0, 2).map(imp => `${imp.slice(0, 30)}${imp.length > 30 ? '...' : ''}`).join('')} + ${safeImprovements.slice(0, 2).map(imp => `${escapeHtml(imp.slice(0, 30))}${imp.length > 30 ? '...' : ''}`).join('')}
` : ''} -
${escapeHtml(v.content.slice(0, 150))}${v.content.length > 150 ? '...' : ''}
+
${escapeHtml((v.content || '').slice(0, 150))}${(v.content || '').length > 150 ? '...' : ''}
- `).join('')} + `;}).join('')}
`; @@ -10942,8 +11048,10 @@ Analyze and refine. Output ONLY the JSON object:` } // Step 2: Query ALL models in parallel with early stopping + live leader tracking _log('[ULTRAPLINIAN] Step 2: Querying all models...'); - // Build race entries: OpenRouter models + Venice models (when key present) - const raceEntries = modelsToQuery.map(m => ({ model: m, provider: 'openrouter' })); + // Build race entries: OpenRouter models (when key present) + Venice models (when key present) + const raceEntries = state.apiKey + ? modelsToQuery.map(m => ({ model: m, provider: 'openrouter' })) + : []; if (state.veniceApiKey) { const veniceTier = state.ultraSpeedTier || 'standard'; const veniceCount = VENICE_TIER_SIZES[veniceTier] || VENICE_TIER_SIZES.standard; @@ -11236,7 +11344,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; // Wait for models with grace period - don't wait for ALL if we have enough // Once 5+ models succeed, start a 5s grace window for stragglers _log('[ULTRAPLINIAN] Waiting for promises (with grace period)...'); - const MIN_RESULTS_FOR_GRACE = 5; + const MIN_RESULTS_FOR_GRACE = Math.min(5, Math.max(2, Math.ceil(models.length * 0.5))); const GRACE_PERIOD_MS = 5000; const HARD_TIMEOUT_MS = 45000; @@ -11251,12 +11359,12 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; resolved = true; if (graceTimer) clearTimeout(graceTimer); if (hardTimer) clearTimeout(hardTimer); + controller.abort(); resolveRace(); }; const hardTimer = setTimeout(() => { _log('[ULTRAPLINIAN] Hard timeout reached, finishing race'); - controller.abort(); finish(); }, HARD_TIMEOUT_MS); @@ -11757,7 +11865,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; duration_ms: r.responseTimeMs || r.duration || 0, content_length: r.content?.length || 0, is_refusal: !!r.isRefusal, - error_type: r.error ? 'model_error' : (r.isRefusal ? 'refusal' : null), + error_type: r.error ? classifyModelError(r.error) : (r.isRefusal ? 'refusal' : null), })), pipeline: { autotune: state.autoTuneEnabled, @@ -11771,7 +11879,8 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; ..._lastTelemetryCtx, }); - return { content: '**Error:** All models failed in ULTRAPLINIAN mode.', strategy: 'ultraplinian-failed', score: -9999 }; + const diagnosis = diagnoseAllModelsFailed(allResults); + return { content: `**Error:** ${escapeHtml(diagnosis)}`, strategy: 'ultraplinian-failed', score: -9999 }; } // ═══════════════════════════════════════════════════════════════════ @@ -12105,6 +12214,169 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; 'promptsTried', ]); + function _sanitizeMagic(m) { + if (m.mode != null) m.mode = String(m.mode).slice(0, 30); + if (m.score != null) m.score = Number(m.score) || 0; + if (m.duration != null) m.duration = String(m.duration).slice(0, 20); + if (m.variants_succeeded != null) m.variants_succeeded = parseInt(m.variants_succeeded) || 0; + if (m.variants_total != null) m.variants_total = parseInt(m.variants_total) || 0; + if (m.variants_refused != null) m.variants_refused = parseInt(m.variants_refused) || 0; + if (m.topScore != null) m.topScore = String(m.topScore).slice(0, 20); + if (m.combos_attempted != null) m.combos_attempted = parseInt(m.combos_attempted) || 0; + if (m.combos_succeeded != null) m.combos_succeeded = parseInt(m.combos_succeeded) || 0; + if (m.combos_failed != null) m.combos_failed = parseInt(m.combos_failed) || 0; + if (m.winnerModel != null) m.winnerModel = String(m.winnerModel).slice(0, 100); + if (m.topModel != null) m.topModel = String(m.topModel).slice(0, 100); + if (m.model != null) m.model = String(m.model).slice(0, 100); + if (m.template != null) m.template = String(m.template).slice(0, 100); + if (m.combo != null) m.combo = String(m.combo).slice(0, 100); + if (m.technique != null) m.technique = String(m.technique).slice(0, 100); + if (m.techniqueLabel != null) m.techniqueLabel = String(m.techniqueLabel).slice(0, 100); + if (m.tier != null) m.tier = String(m.tier).slice(0, 20); + if (m.systemPrompt != null) m.systemPrompt = String(m.systemPrompt).slice(0, 2000); + if (m.enhancedUserPrompt != null) m.enhancedUserPrompt = String(m.enhancedUserPrompt).slice(0, 2000); + if (m.judgeReasoning != null) m.judgeReasoning = String(m.judgeReasoning).slice(0, 500); + if (m.prefix != null) m.prefix = String(m.prefix).slice(0, 500); + if (m.winnerScore != null) m.winnerScore = String(m.winnerScore).slice(0, 20); + if (m.successfulModels != null) m.successfulModels = parseInt(m.successfulModels) || 0; + if (m.totalModels != null) m.totalModels = parseInt(m.totalModels) || 0; + if (m.scoredResponses != null) m.scoredResponses = parseInt(m.scoredResponses) || 0; + if (m.attempt != null) m.attempt = parseInt(m.attempt) || 1; + if (m.temperature != null) m.temperature = Number(m.temperature) || 0; + if (m.topP != null) m.topP = Number(m.topP) || 0; + if (m.thinkingModels && typeof m.thinkingModels === 'object' && !Array.isArray(m.thinkingModels)) { + for (const [k, v] of Object.entries(m.thinkingModels)) { + if (!v || typeof v !== 'object') { delete m.thinkingModels[k]; continue; } + v.status = typeof v.status === 'string' ? v.status.slice(0, 20) : 'unknown'; + v.score = v.score !== null && v.score !== undefined ? Number(v.score) || 0 : null; + } + } else if (m.thinkingModels) { + delete m.thinkingModels; + } + if (Array.isArray(m.thinkingLogs)) { + m.thinkingLogs = m.thinkingLogs.filter(l => l && typeof l === 'object').map(l => ({ + type: typeof l.type === 'string' ? l.type.slice(0, 20) : 'info', + time: Number(l.time) || 0, + message: typeof l.message === 'string' ? l.message.slice(0, 200) : '' + })); + } else if (m.thinkingLogs) { + delete m.thinkingLogs; + } + if (Array.isArray(m.all_scores)) { + m.all_scores = m.all_scores.filter(s => s && typeof s === 'object').map(s => ({ + template: typeof s.template === 'string' ? s.template.slice(0, 100) : '', + score: Number(s.score) || 0 + })); + } else if (m.all_scores) { + delete m.all_scores; + } + if (Array.isArray(m.scores)) { + m.scores = m.scores.filter(s => s && typeof s === 'object').map(s => ({ + technique: typeof s.technique === 'string' ? s.technique.slice(0, 100) : '', + score: Number(s.score) || 0 + })); + } else if (m.scores) { + delete m.scores; + } + if (m.triggers_found != null) { + m.triggers_found = Array.isArray(m.triggers_found) + ? m.triggers_found.filter(t => typeof t === 'string').slice(0, 20).map(t => t.slice(0, 100)) + : []; + } + if (m.tastemakerScore && typeof m.tastemakerScore === 'object') { + const ts = m.tastemakerScore; + ts.overall = ts.overall != null ? String(ts.overall).slice(0, 10) : ''; + ts.grade = ts.grade != null ? String(ts.grade).slice(0, 10) : ''; + ts.gradeEmoji = ts.gradeEmoji != null ? String(ts.gradeEmoji).slice(0, 4) : ''; + ts.gradeColor = ts.gradeColor != null ? String(ts.gradeColor).slice(0, 20) : ''; + ts.queryType = ts.queryType != null ? String(ts.queryType).slice(0, 30) : ''; + } else if (m.tastemakerScore) { + delete m.tastemakerScore; + } + if (m.autoTune && typeof m.autoTune === 'object') { + const at = m.autoTune; + at.confidence = Number(at.confidence) || 0; + at.conversationLength = Number(at.conversationLength) || 0; + at.godmodeBoost = at.godmodeBoost === true; + if (at.strategy != null) at.strategy = String(at.strategy).slice(0, 20); + if (at.context != null) at.context = String(at.context).slice(0, 30); + if (at.params && typeof at.params === 'object') { + for (const k of Object.keys(at.params)) { + at.params[k] = Number(at.params[k]) || 0; + } + } + } else if (m.autoTune) { + delete m.autoTune; + } + } + + function sanitizeLoadedState() { + // Validate conversations + if (!Array.isArray(state.conversations)) { state.conversations = []; } + state.conversations = state.conversations.filter(c => c && typeof c === 'object' && !Array.isArray(c)); + for (const conv of state.conversations) { + if (!Array.isArray(conv.messages)) { conv.messages = []; continue; } + conv.messages = conv.messages.filter(m => m && typeof m === 'object' && !Array.isArray(m)); + for (const msg of conv.messages) { + if (msg.role !== 'user' && msg.role !== 'assistant' && msg.role !== 'system') { + msg.role = 'assistant'; + } + if (msg.imageDataUrl && !/^data:image\/[a-z]+;base64,[A-Za-z0-9+/=]+$/.test(msg.imageDataUrl)) { + delete msg.imageDataUrl; + } + if (msg.imageName) { + msg.imageName = String(msg.imageName).slice(0, 100).replace(/[<>"'&]/g, ''); + } + if (Array.isArray(msg.liquidVersions)) { + msg.liquidVersions = msg.liquidVersions.filter(v => v && typeof v === 'object' && !Array.isArray(v)); + for (const v of msg.liquidVersions) { + v.improvements = (Array.isArray(v.improvements) ? v.improvements : []) + .filter(x => typeof x === 'string').slice(0, 10).map(s => s.slice(0, 200)); + v.label = typeof v.label === 'string' ? v.label.slice(0, 60) : ''; + v.grade = typeof v.grade === 'string' ? v.grade.slice(0, 20) : ''; + v.score = Number.isFinite(v.score) ? Math.max(0, Math.min(100, v.score)) : 0; + v.delta = Number.isFinite(v.delta) ? Math.max(-100, Math.min(100, v.delta)) : 0; + v.content = typeof v.content === 'string' ? v.content : ''; + } + } + if (Array.isArray(msg.raceResponses)) { + msg.raceResponses = msg.raceResponses.filter(r => r && typeof r === 'object' && !Array.isArray(r)); + for (const r of msg.raceResponses) { + r.model = typeof r.model === 'string' ? r.model.slice(0, 100) : ''; + r.content = typeof r.content === 'string' ? r.content : ''; + r.score = Number.isFinite(r.score) ? r.score : 0; + r.isWinner = r.isWinner === true; + } + } + if (msg.liquidIterations != null) msg.liquidIterations = parseInt(msg.liquidIterations) || 0; + if (msg.liquidImprovement != null) msg.liquidImprovement = Number(msg.liquidImprovement) || 0; + if (msg.magic && typeof msg.magic === 'object') { + _sanitizeMagic(msg.magic); + } + } + } + // Validate strategy logs + if (Array.isArray(state.strategyLogs)) { + state.strategyLogs = state.strategyLogs.filter(l => l && typeof l === 'object' && !Array.isArray(l)); + for (const log of state.strategyLogs) { + log.model = typeof log.model === 'string' ? log.model.slice(0, 100) : ''; + log.query = typeof log.query === 'string' ? log.query : ''; + if (Array.isArray(log.results)) { + log.results = log.results.filter(r => r && typeof r === 'object' && !Array.isArray(r)); + for (const r of log.results) { + r.strategy = typeof r.strategy === 'string' ? r.strategy.slice(0, 100) : ''; + r.error = typeof r.error === 'string' ? r.error.slice(0, 200) : ''; + r.contentPreview = typeof r.contentPreview === 'string' ? r.contentPreview.slice(0, 300) : ''; + r.score = Number.isFinite(r.score) ? r.score : 0; + r.duration = Number.isFinite(r.duration) ? r.duration : 0; + } + } else { + log.results = []; + } + } + } + } + function loadState() { const saved = localStorage.getItem('g0dm0d3-state'); if (saved) { @@ -12122,9 +12394,12 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; const encKey = localStorage.getItem('g0dm0d3-apikey'); if (encKey) { // Prefer the separate encrypted store + const genAtLoad = _apiKeyGeneration; decryptApiKey(encKey).then(plain => { + if (_apiKeyGeneration !== genAtLoad) return; state.apiKey = plain; updateApiWarning(); + buildTierSelect(); }); } else if (state.apiKey) { // Migrate: old plaintext key found in state blob → encrypt it @@ -12132,6 +12407,8 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; localStorage.setItem('g0dm0d3-apikey', enc); }); } + // Sanitize loaded state — same rules as import + sanitizeLoadedState(); _log('[DEBUG] loadState: final state.ultraplinian =', state.ultraplinian); document.getElementById('modelSelect').value = state.model; // Restore L1B3RT4S combo selector @@ -12380,9 +12657,14 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; // Persist encrypted key separately (async, best-effort) if (apiKey) { - encryptApiKey(apiKey).then(enc => { - try { localStorage.setItem('g0dm0d3-apikey', enc); } catch (_) {} + const keyAtFlush = apiKey; + encryptApiKey(keyAtFlush).then(enc => { + if (state.apiKey === keyAtFlush) { + try { localStorage.setItem('g0dm0d3-apikey', enc); } catch (_) {} + } }); + } else { + localStorage.removeItem('g0dm0d3-apikey'); } try { @@ -12548,7 +12830,8 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; } function updateApiWarning() { - document.getElementById('noApiWarning').style.display = state.apiKey ? 'none' : 'flex'; + const hasAnyKey = !!(state.apiKey || state.veniceApiKey); + document.getElementById('noApiWarning').style.display = hasAnyKey ? 'none' : 'flex'; } // Sidebar @@ -12744,17 +13027,18 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; ` : ''; // Image thumbnail for user messages with attached images - const imageThumb = (isUser && msg.imageDataUrl) - ? `${escapeHtml(msg.imageName || 'image')}` + const safeImageUrl = (msg.imageDataUrl && /^data:image\/[a-z]+;base64,[A-Za-z0-9+/=]+$/.test(msg.imageDataUrl)) ? msg.imageDataUrl : ''; + const imageThumb = (isUser && safeImageUrl) + ? `${escapeAttr(msg.imageName || 'image')}` : ''; - // Vision badge for messages that had image processing - const visionBadge = (isUser && msg.imageDataUrl) + // Vision badge — only when vision analysis actually ran + const visionBadge = (isUser && msg.imageDataUrl && msg.visionAnalyzed) ? `
analyzed via Gemini Flash
` : ''; return ` -
+
${isUser ? '_<' : '>_'}
${magicInfo} @@ -12815,16 +13099,18 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; // Build reasoning string let reasoningParts = []; + const atConf = Number(at.confidence) || 0; + const atConvLen = Number(at.conversationLength) || 0; if (at.strategy === 'adaptive') { - reasoningParts.push(`Detected ${contextLabels[at.context] || at.context} context`); - if (at.confidence < 0.6) { - reasoningParts.push(`Low confidence (${Math.round(at.confidence * 100)}%) - blended with balanced`); + reasoningParts.push(`Detected ${contextLabels[at.context] || escapeHtml(String(at.context || 'unknown'))} context`); + if (atConf < 0.6) { + reasoningParts.push(`Low confidence (${Math.round(atConf * 100)}%) - blended with balanced`); } } else { - reasoningParts.push(`Fixed ${strategyLabels[at.strategy] || at.strategy} profile`); + reasoningParts.push(`Fixed ${strategyLabels[at.strategy] || escapeHtml(String(at.strategy || 'unknown'))} profile`); } - if (at.conversationLength > 10) { - reasoningParts.push(`Long convo boost (+${Math.min((at.conversationLength - 10) * 0.01, 0.15).toFixed(2)} rep)`); + if (atConvLen > 10) { + reasoningParts.push(`Long convo boost (+${Math.min((atConvLen - 10) * 0.01, 0.15).toFixed(2)} rep)`); } if (at.godmodeBoost) { reasoningParts.push('GODMODE boost (+0.1 temp, +0.15 pres, +0.1 freq)'); @@ -12838,18 +13124,18 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; 🧠 AUTOTUNE ${escapeHtml(strategyLabels[at.strategy] || String(at.strategy))}
- ${escapeHtml(contextLabels[at.context] || String(at.context))} (${Math.round((at.confidence || 0) * 100)}%) + ${escapeHtml(contextLabels[at.context] || String(at.context || 'unknown'))} (${Math.round(atConf * 100)}%)
${escapeHtml(reasoning)}
-
TEMP
${at.params?.temperature?.toFixed(2) || '-'}
-
TOP-P
${at.params?.top_p?.toFixed(2) || '-'}
-
TOP-K
${at.params?.top_k || '-'}
-
FREQ
${at.params?.frequency_penalty?.toFixed(2) || '-'}
-
PRES
${at.params?.presence_penalty?.toFixed(2) || '-'}
-
REP
${at.params?.repetition_penalty?.toFixed(2) || '-'}
+
TEMP
${Number.isFinite(at.params?.temperature) ? at.params.temperature.toFixed(2) : '-'}
+
TOP-P
${Number.isFinite(at.params?.top_p) ? at.params.top_p.toFixed(2) : '-'}
+
TOP-K
${Number.isFinite(at.params?.top_k) ? at.params.top_k : '-'}
+
FREQ
${Number.isFinite(at.params?.frequency_penalty) ? at.params.frequency_penalty.toFixed(2) : '-'}
+
PRES
${Number.isFinite(at.params?.presence_penalty) ? at.params.presence_penalty.toFixed(2) : '-'}
+
REP
${Number.isFinite(at.params?.repetition_penalty) ? at.params.repetition_penalty.toFixed(2) : '-'}
`; @@ -12951,7 +13237,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`;
Duration:${escapeHtml(String(magic.duration || 'N/A'))}
Models:${parseInt(magic.successfulModels) || 0}/${parseInt(magic.totalModels) || 0} collected
Scored:${parseInt(magic.scoredResponses) || 0} responses fed to orchestrator
- ${magic.topModel ? `
Top Model:${escapeHtml(magic.topModel.split('/')[1] || magic.topModel)} (${magic.topScore || 'N/A'})
` : ''} + ${magic.topModel ? `
Top Model:${escapeHtml(magic.topModel.split('/')[1] || magic.topModel)} (${escapeHtml(String(magic.topScore || 'N/A'))})
` : ''} ${consortiumModelGridHtml} ${consortiumLogsHtml} `; @@ -12972,7 +13258,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; const scoreItems = magic.all_scores.map(s => { const isWinner = s.template === magic.template; const cls = isWinner ? 'winner' : 'success'; - return `${isWinner ? '👑' : '✓'} ${escapeHtml(s.template)} (${s.score})`; + return `${isWinner ? '👑' : '✓'} ${escapeHtml(s.template)} (${Number(s.score) || 0})`; }).join(''); templateGridHtml = `
${scoreItems}
`; } @@ -12991,10 +13277,10 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; detailsHtml = `
Combo:${escapeHtml(magic.template || 'unknown')}${magic.combo ? ' [' + escapeHtml(magic.combo) + ']' : ''}
-
Score:${magic.score || 'N/A'}
+
Score:${Number(magic.score) || 'N/A'}
Model:${escapeHtml(magic.model?.split('/')[1] || magic.model || 'unknown')}
-
Duration:${magic.duration || 'N/A'}
- ${magic.combos_attempted ? `
Combos:${magic.combos_succeeded || 0}/${magic.combos_attempted} succeeded, ${magic.combos_failed || 0} refused
` : ''} +
Duration:${escapeHtml(String(magic.duration || 'N/A'))}
+ ${magic.combos_attempted ? `
Combos:${parseInt(magic.combos_succeeded) || 0}/${parseInt(magic.combos_attempted)} succeeded, ${parseInt(magic.combos_failed) || 0} refused
` : ''} ${templateGridHtml} ${plinyLogsHtml} ${magic.systemPrompt ? `
System Prompt:
${escapeHtml(magic.systemPrompt.slice(0, 500))}${magic.systemPrompt.length > 500 ? '...' : ''}
` : ''} @@ -13007,7 +13293,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; const scoreItems = magic.scores.map(s => { const isWinner = s.technique === magic.techniqueLabel; const color = s.score >= 80 ? '#00ff41' : s.score >= 60 ? '#ffaa00' : '#ff3e3e'; - return `${isWinner ? '👑 ' : ''}${escapeHtml(s.technique)} ${s.score}`; + return `${isWinner ? '👑 ' : ''}${escapeHtml(s.technique)} ${Number(s.score) || 0}`; }).join(''); scoresHtml = `
${scoreItems}
`; } @@ -13017,7 +13303,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`;
Winner:${escapeHtml(magic.techniqueLabel || magic.technique || 'unknown')}
Sampling:temp=${parseFloat(magic.temperature) || 'N/A'} top_p=${parseFloat(magic.topP) || 'N/A'}
Model:${escapeHtml(magic.model?.split('/')[1] || magic.model || 'unknown')}
-
Variants:${magic.variants_succeeded || '?'}/${magic.variants_total || '?'} succeeded, ${magic.variants_refused || 0} refused
+
Variants:${parseInt(magic.variants_succeeded) || '?'}/${parseInt(magic.variants_total) || '?'} succeeded, ${parseInt(magic.variants_refused) || 0} refused
Duration:${escapeHtml(String(magic.duration || 'N/A'))}
${magic.triggers_found?.length > 0 ? `
Triggers:${escapeHtml(magic.triggers_found.join(', '))}
` : ''} ${scoresHtml} @@ -13037,7 +13323,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; 'ULTRAPLINIAN-EARLYBIRD': `⚡ ${escapeHtml(magic.winnerModel?.split('/')[1] || 'model')} early stop in ${escapeHtml(String(magic.duration || 'N/A'))}`, 'PLINY': `${escapeHtml(String(magic.template || '?'))} in ${escapeHtml(String(magic.duration || 'N/A'))}`, 'G0DM0D3 CLASSIC': `${escapeHtml(String(magic.template || '?'))} [${escapeHtml(magic.model?.split('/')[1] || '?')}] in ${escapeHtml(String(magic.duration || 'N/A'))}`, - 'PARSELTONGUE': `${escapeHtml(magic.techniqueLabel || magic.technique || '?')} won (${magic.variants_succeeded || '?'}/${magic.variants_total || '?'}) in ${escapeHtml(String(magic.duration || 'N/A'))}`, + 'PARSELTONGUE': `${escapeHtml(magic.techniqueLabel || magic.technique || '?')} won (${parseInt(magic.variants_succeeded) || '?'}/${parseInt(magic.variants_total) || '?'}) in ${escapeHtml(String(magic.duration || 'N/A'))}`, 'GODMODE': `Attempt ${parseInt(magic.attempt) || 1} (temp ${parseFloat(magic.temperature) || '?'})` }[magic.mode] || escapeHtml(String(magic.mode)); @@ -13054,7 +13340,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; // Calculate total improvement const totalImprovement = latestVersion && originalVersion ? latestVersion.score - originalVersion.score - : (msg.liquidImprovement || 0); + : (Number(msg.liquidImprovement) || 0); // Build version history display let versionHistoryHtml = ''; @@ -13062,12 +13348,17 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; const versionItems = versions.map((v, i) => { const isActive = i === currentVersion; const delta = i > 0 ? `+${(v.score - versions[i-1].score).toFixed(0)}` : ''; + const safeVLabel = escapeAttr(String(v.label || '').slice(0, 60)); + const safeVScore = Number.isFinite(v.score) ? v.score : 0; + const safeVImps = Array.isArray(v.improvements) + ? v.improvements.filter(x => typeof x === 'string').slice(0, 3).map(s => s.slice(0, 40)).join(', ') + : ''; return `
+ onclick="event.stopPropagation(); revertToLiquidVersion(${Number(idx)}, ${Number(i)})" + title="${safeVLabel}: Score ${safeVScore}${safeVImps ? ' - ' + escapeAttr(safeVImps) : ''}"> v${i} - ${v.score} + ${safeVScore} ${delta ? `${delta}` : ''}
`; @@ -13097,7 +13388,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`;
💧 LIQUID RESPONSE - ${msg.liquidIterations || versions.length - 1} passes + ${parseInt(msg.liquidIterations) || versions.length - 1} passes
@@ -13128,7 +13419,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`;
${modeIcon} - ${magic.mode} + ${escapeHtml(String(magic.mode))} ${summaryText} ▼
@@ -13287,107 +13578,131 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; // Regenerate response from a specific user message async function regenerateFromMessage(userMsgIdx) { const conv = getCurrentConv(); - if (!conv || !state.apiKey) return; + if (!conv || (!state.apiKey && !state.veniceApiKey)) return; + + // Venice-only: ensure ULTRAPLINIAN for regeneration too + if (!state.apiKey && state.veniceApiKey && !state.ultraplinian) { + selectMode('ultraplinian'); + } isStreaming = true; updateSendButton(); showTyping(); - let attempt = 0; - let lastResponse = null; - let success = false; - - while (attempt <= state.maxRetries && !success) { - try { - abortController = new AbortController(); - - const messages = []; - - // System prompt (user-configurable) - const systemPrompt = getActiveSystemPrompt(); - if (systemPrompt) { - messages.push({ role: 'system', content: systemPrompt }); - } - - // All messages up to and including the edited user message - const historyMessages = conv.messages.slice(0, userMsgIdx + 1); - const retryPrefix = getRetryPrefix(attempt); - - historyMessages.forEach((m, idx) => { - if (m.role === 'user' && idx === historyMessages.length - 1) { - let modifiedContent = m.content; - if (retryPrefix) { - modifiedContent = retryPrefix + modifiedContent; - } - messages.push({ role: m.role, content: modifiedContent }); - } else { - messages.push({ role: m.role, content: m.content }); - } - }); - - const params = getRetryParams(attempt); - - if (attempt > 0) { - updateTypingStatus(`Retry ${attempt}/${state.maxRetries} (temp: ${params.temperature})...`); - } - - const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { - method: 'POST', - headers: { - 'Authorization': `Bearer ${state.apiKey}`, - 'Content-Type': 'application/json', - 'HTTP-Referer': 'https://godmod3.ai', - 'X-Title': 'GODMOD3.AI' - }, - body: JSON.stringify({ - model: conv.model, - messages, - temperature: params.temperature, - top_p: params.top_p, - frequency_penalty: state.modelFreqPenalty ?? 0, - presence_penalty: params.presence_penalty || state.modelPresPenalty || 0, - max_tokens: state.modelMaxTokens ?? 4096 - }), - signal: abortController.signal - }); - - if (!response.ok) { - const err = await response.json().catch(() => ({})); - throw new Error(err.error?.message || `API Error: ${response.status}`); - } - - const data = await response.json(); - const assistantContent = data.choices?.[0]?.message?.content || 'No response'; - - if (state.autoRetry && isRefusal(assistantContent) && attempt < state.maxRetries) { - lastResponse = { role: 'assistant', content: assistantContent }; - attempt++; - continue; - } - - conv.messages.push({ role: 'assistant', content: assistantContent }); - saveState(); - success = true; - - } catch (err) { - if (err.name === 'AbortError') { - conv.messages.push({ role: 'assistant', content: '_[Response stopped]_' }); - success = true; - } else if (attempt >= state.maxRetries) { - conv.messages.push({ role: 'assistant', content: `**Error:** ${err.message}` }); - success = true; - } else { - attempt++; - } - saveState(); - } + // Build message array for the regeneration + const messages = []; + const systemPrompt = getActiveSystemPrompt(); + if (systemPrompt) { + messages.push({ role: 'system', content: systemPrompt }); } + const historyMessages = conv.messages.slice(0, userMsgIdx + 1); + historyMessages.forEach(m => { + messages.push({ role: m.role, content: m.content }); + }); + const userQuery = historyMessages[historyMessages.length - 1]?.content || ''; - isStreaming = false; - abortController = null; - hideTyping(); - updateSendButton(); - render(); + try { + if (state.ultraplinian) { + // ULTRAPLINIAN mode (includes Venice-only): use the full race pipeline + showPongGame(); + try { + const result = await ultraplinian(messages, userQuery, null); + conv.messages = conv.messages.slice(0, userMsgIdx + 1); + conv.messages.push({ + role: 'assistant', + content: result.content, + strategy: result.strategy, + magic: result.magic, + raceResponses: result.raceResponses + }); + saveState(); + } catch (err) { + if (err.name !== 'AbortError') { + conv.messages = conv.messages.slice(0, userMsgIdx + 1); + conv.messages.push({ role: 'assistant', content: `**Error:** ${err.message}` }); + saveState(); + } + } + } else { + // Direct single-model mode (OpenRouter key required) + let attempt = 0; + let success = false; + + while (attempt <= state.maxRetries && !success) { + try { + abortController = new AbortController(); + const retryPrefix = getRetryPrefix(attempt); + const retryMessages = messages.map((m, idx) => { + if (m.role === 'user' && idx === messages.length - 1 && retryPrefix) { + return { ...m, content: retryPrefix + m.content }; + } + return m; + }); + + const params = getRetryParams(attempt); + if (attempt > 0) { + updateTypingStatus(`Retry ${attempt}/${state.maxRetries} (temp: ${params.temperature})...`); + } + + const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { + method: 'POST', + headers: { + 'Authorization': `Bearer ${state.apiKey}`, + 'Content-Type': 'application/json', + 'HTTP-Referer': 'https://godmod3.ai', + 'X-Title': 'GODMOD3.AI' + }, + body: JSON.stringify({ + model: conv.model, + messages: retryMessages, + temperature: params.temperature, + top_p: params.top_p, + frequency_penalty: state.modelFreqPenalty ?? 0, + presence_penalty: params.presence_penalty || state.modelPresPenalty || 0, + max_tokens: state.modelMaxTokens ?? 4096 + }), + signal: abortController.signal + }); + + if (!response.ok) { + const err = await response.json().catch(() => ({})); + throw new Error(err.error?.message || `API Error: ${response.status}`); + } + + const data = await response.json(); + const assistantContent = data.choices?.[0]?.message?.content || 'No response'; + + if (state.autoRetry && isRefusal(assistantContent) && attempt < state.maxRetries) { + attempt++; + continue; + } + + conv.messages.push({ role: 'assistant', content: assistantContent }); + saveState(); + success = true; + + } catch (err) { + if (err.name === 'AbortError') { + conv.messages.push({ role: 'assistant', content: '_[Response stopped]_' }); + success = true; + } else if (attempt >= state.maxRetries) { + conv.messages.push({ role: 'assistant', content: `**Error:** ${err.message}` }); + success = true; + } else { + attempt++; + } + saveState(); + } + } + } + } finally { + isStreaming = false; + abortController = null; + hidePongGame(); + hideTyping(); + updateSendButton(); + render(); + } } // Retry last message @@ -13942,11 +14257,16 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; // Need either text or image if ((!content && !attachedImage) || isStreaming) return; - if (!state.apiKey) { + if (!state.apiKey && !state.veniceApiKey) { openSettings(); return; } + // Venice-only: auto-switch to ULTRAPLINIAN (other modes need OpenRouter) + if (!state.apiKey && state.veniceApiKey && !state.ultraplinian) { + selectMode('ultraplinian'); + } + // Create conv if needed if (!state.currentId) { newChat(); @@ -13986,29 +14306,34 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; // ── Image Vision Processing ────────────────────────────────────── // If user attached an image, send it to Gemini Flash for analysis - // then inject the vision description into the conversation context + // then inject the vision description into the conversation context. + // Vision requires OpenRouter (Gemini Flash) — skip gracefully in Venice-only mode. let visionContext = null; - if (attachedImage) { + if (attachedImage && state.apiKey) { try { console.log(`[G0DM0D3] 📷 Processing image via ${VISION_MODEL}...`); visionContext = await processImageWithVision(attachedImage, content); + userMsg.visionAnalyzed = true; console.log('[G0DM0D3] ✓ Vision analysis complete'); } catch (err) { console.error('[G0DM0D3] Vision processing failed:', err); visionContext = `[Image was attached but vision processing failed: ${err.message}]`; } + } else if (attachedImage && !state.apiKey) { + visionContext = '[Image attached — vision analysis unavailable without OpenRouter key]'; } - // Fire harm classification in parallel (never blocks UI) + // Fire harm classification in parallel (telemetry-only — skip when No-Log) _lastHarmResult = null; - const harmPromise = classifyHarm(content).then(r => { _lastHarmResult = r; }).catch(() => {}); + const harmPromise = state.noLogMode + ? Promise.resolve(null) + : classifyHarm(content).then(r => { _lastHarmResult = r; return r; }).catch(() => null); // Capture structural context for telemetry (no content, no PII) _lastTelemetryCtx = { persona: conv.persona || state.persona || 'godmode', prompt_length: content.length, conversation_depth: conv.messages.length, - no_log: !!state.noLogMode, has_image: !!attachedImage, }; @@ -16074,6 +16399,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; document.getElementById('parseltongueTier').value = state.parseltongueTier || 'standard'; document.getElementById('maxRetriesInput').value = state.maxRetries; document.getElementById('ultraplinian').checked = state.ultraplinian; + buildTierSelect(); document.getElementById('ultraSpeedTier').value = state.ultraSpeedTier || 'standard'; document.getElementById('ultraEarlyThreshold').value = state.ultraEarlyThreshold; updateThresholdDisplay(state.ultraEarlyThreshold); @@ -16216,6 +16542,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; // If user manually changed the key, clear OAuth connected state if (newKey !== state.apiKey) state.orOAuthConnected = false; state.apiKey = newKey; + _apiKeyGeneration++; state.veniceApiKey = (document.getElementById('veniceKeyInput').value || '').trim(); state.model = document.getElementById('defaultModelInput').value; state.persona = document.getElementById('personaSelect').value; @@ -16223,6 +16550,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; state.customSystemPrompt = document.getElementById('customSystemPromptInput').value; updateSystemPromptUI(); state.noLogMode = document.getElementById('noLogMode').checked; + if (state.noLogMode) { _telemetry.buffer.length = 0; } state.showMagic = document.getElementById('showMagic').checked; state.waitingGame = document.getElementById('waitingGameSelect').value; state.autoRetry = document.getElementById('autoRetry').checked; @@ -16271,6 +16599,7 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; saveState(); updateApiWarning(); updateUltraplinianUI(); + buildTierSelect(); // Show auto-save indicator briefly const indicator = document.getElementById('autoSaveIndicator'); @@ -16382,25 +16711,44 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; URL.revokeObjectURL(url); } - // ── Full self-custody backup (all state) ── + // ── Full self-custody backup (all state except credentials) ── function exportFullBackup() { const exportData = { - _version: 1, + _version: 2, _exportedAt: new Date().toISOString(), _source: 'g0dm0d3', conversations: state.conversations, currentId: state.currentId, - apiKey: state.apiKey, model: state.model, persona: state.persona, customSystemPrompt: state.customSystemPrompt, customSystemPromptEnabled: state.customSystemPromptEnabled, strategyLogs: state.strategyLogs, - autoTuneEnabled: state.autoTuneEnabled, - liquidEnabled: state.liquidEnabled, - ultraplinianEnabled: state.ultraplinianEnabled, - ultraplinianTier: state.ultraplinianTier, noLogMode: state.noLogMode, + showMagic: state.showMagic, + autoRetry: state.autoRetry, + maxRetries: state.maxRetries, + waitingGame: state.waitingGame, + ultraplinian: state.ultraplinian, + ultraSpeedTier: state.ultraSpeedTier, + ultraEarlyThreshold: state.ultraEarlyThreshold, + ultraImproveMode: state.ultraImproveMode, + plinyMode: state.plinyMode, + parseltongue: state.parseltongue, + parseltongueTier: state.parseltongueTier, + liquidMode: state.liquidMode, + liquidMinDelta: state.liquidMinDelta, + liquidMaxIterations: state.liquidMaxIterations, + liquidTargetScore: state.liquidTargetScore, + autoTuneEnabled: state.autoTuneEnabled, + autoTuneStrategy: state.autoTuneStrategy, + libertasDisabledCombos: state.libertasDisabledCombos, + libertasSelectedCombo: state.libertasSelectedCombo, + modelTemperature: state.modelTemperature, + modelTopP: state.modelTopP, + modelMaxTokens: state.modelMaxTokens, + modelFreqPenalty: state.modelFreqPenalty, + modelPresPenalty: state.modelPresPenalty, }; const jsonString = JSON.stringify(exportData, null, 2); const blob = new Blob([jsonString], { type: 'application/json' }); @@ -16491,41 +16839,143 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; if (!_pendingImportData) return; const imported = _pendingImportData; - // Merge into state — only overwrite keys that exist in the import - const allowed = ['conversations', 'currentId', 'apiKey', 'model', 'persona', + // Build a candidate state WITHOUT mutating live state + // Import all state keys EXCEPT credentials (apiKey, veniceApiKey, generatedApiKeys, orOAuthConnected) + const allowed = ['conversations', 'currentId', 'model', 'persona', 'customSystemPrompt', 'customSystemPromptEnabled', 'strategyLogs', - 'autoTuneEnabled', 'liquidEnabled', 'ultraplinianEnabled', - 'ultraplinianTier', 'noLogMode']; + 'noLogMode', 'showMagic', 'autoRetry', 'maxRetries', 'waitingGame', + 'ultraplinian', 'ultraSpeedTier', 'ultraEarlyThreshold', 'ultraImproveMode', + 'plinyMode', 'parseltongue', 'parseltongueTier', + 'liquidMode', 'liquidMinDelta', 'liquidMaxIterations', 'liquidTargetScore', + 'autoTuneEnabled', 'autoTuneStrategy', + 'libertasDisabledCombos', 'libertasSelectedCombo', + 'modelTemperature', 'modelTopP', 'modelMaxTokens', 'modelFreqPenalty', 'modelPresPenalty', + 'sidebarOpen', 'backendUrl']; + const candidate = JSON.parse(JSON.stringify(state)); + // Migrate v1 stale field names to current names + if (imported.liquidEnabled !== undefined && imported.liquidMode === undefined) imported.liquidMode = imported.liquidEnabled; + if (imported.ultraplinianEnabled !== undefined && imported.ultraplinian === undefined) imported.ultraplinian = imported.ultraplinianEnabled; + if (imported.ultraplinianTier !== undefined && imported.ultraSpeedTier === undefined) imported.ultraSpeedTier = imported.ultraplinianTier; for (const key of allowed) { - if (imported[key] !== undefined) state[key] = imported[key]; + if (imported[key] !== undefined) candidate[key] = imported[key]; } - // Enforce hard caps before saving (same caps as normal save) - enforceDataCaps(); + // Sanitize conversations: validate structure, strip dangerous values + if (!Array.isArray(candidate.conversations)) { + candidate.conversations = []; + } + candidate.conversations = candidate.conversations.filter(conv => + conv && typeof conv === 'object' && !Array.isArray(conv) + ); + for (const conv of candidate.conversations) { + if (!Array.isArray(conv.messages)) { conv.messages = []; continue; } + conv.messages = conv.messages.filter(msg => + msg && typeof msg === 'object' && !Array.isArray(msg) + ); + for (const msg of conv.messages) { + // Restrict role to known values + if (msg.role !== 'user' && msg.role !== 'assistant' && msg.role !== 'system') { + msg.role = 'assistant'; + } + // Only allow strict base64 data:image/ URLs + if (msg.imageDataUrl && !/^data:image\/[a-z]+;base64,[A-Za-z0-9+/=]+$/.test(msg.imageDataUrl)) { + delete msg.imageDataUrl; + } + // Sanitize imageName + if (msg.imageName) { + msg.imageName = String(msg.imageName).slice(0, 100).replace(/[<>"'&]/g, ''); + } + // Sanitize liquid version history + if (Array.isArray(msg.liquidVersions)) { + msg.liquidVersions = msg.liquidVersions.filter(v => v && typeof v === 'object' && !Array.isArray(v)); + for (const v of msg.liquidVersions) { + if (Array.isArray(v.improvements)) { + v.improvements = v.improvements + .filter(x => typeof x === 'string') + .slice(0, 10) + .map(s => s.slice(0, 200)); + } else { + v.improvements = []; + } + v.label = typeof v.label === 'string' ? v.label.slice(0, 60) : ''; + v.grade = typeof v.grade === 'string' ? v.grade.slice(0, 20) : ''; + v.score = Number.isFinite(v.score) ? Math.max(0, Math.min(100, v.score)) : 0; + v.delta = Number.isFinite(v.delta) ? Math.max(-100, Math.min(100, v.delta)) : 0; + v.content = typeof v.content === 'string' ? v.content : ''; + } + } + // Sanitize race responses + if (Array.isArray(msg.raceResponses)) { + msg.raceResponses = msg.raceResponses.filter(r => r && typeof r === 'object' && !Array.isArray(r)); + for (const r of msg.raceResponses) { + r.model = typeof r.model === 'string' ? r.model.slice(0, 100) : ''; + r.content = typeof r.content === 'string' ? r.content : ''; + r.score = Number.isFinite(r.score) ? r.score : 0; + r.isWinner = r.isWinner === true; + } + } + if (msg.liquidIterations != null) msg.liquidIterations = parseInt(msg.liquidIterations) || 0; + if (msg.liquidImprovement != null) msg.liquidImprovement = Number(msg.liquidImprovement) || 0; + if (msg.magic && typeof msg.magic === 'object') { + _sanitizeMagic(msg.magic); + } + } + } - // Pre-flight: check if the merged state will fit in localStorage (~5 MB) - const { apiKey: _ak, ...stateWithoutKey } = state; - const testPayload = JSON.stringify(stateWithoutKey); + // Sanitize strategy logs + if (Array.isArray(candidate.strategyLogs)) { + candidate.strategyLogs = candidate.strategyLogs.filter(log => + log && typeof log === 'object' && !Array.isArray(log) + ); + for (const log of candidate.strategyLogs) { + log.model = typeof log.model === 'string' ? log.model.slice(0, 100) : ''; + log.query = typeof log.query === 'string' ? log.query : ''; + if (Array.isArray(log.results)) { + log.results = log.results.filter(r => r && typeof r === 'object' && !Array.isArray(r)); + for (const r of log.results) { + r.strategy = typeof r.strategy === 'string' ? r.strategy.slice(0, 100) : ''; + r.error = typeof r.error === 'string' ? r.error.slice(0, 200) : ''; + r.contentPreview = typeof r.contentPreview === 'string' ? r.contentPreview.slice(0, 300) : ''; + r.score = Number.isFinite(r.score) ? r.score : 0; + r.duration = Number.isFinite(r.duration) ? r.duration : 0; + } + } else { + log.results = []; + } + } + } + + // Enforce caps on candidate + if (Array.isArray(candidate.conversations) && candidate.conversations.length > MAX_CONVERSATIONS) { + candidate.conversations = candidate.conversations.slice(-MAX_CONVERSATIONS); + } + if (Array.isArray(candidate.strategyLogs) && candidate.strategyLogs.length > 500) { + candidate.strategyLogs = candidate.strategyLogs.slice(-500); + } + + // Pre-flight: check if the candidate will fit in localStorage (~5 MB) + const { apiKey: _ak, ...candidateWithoutKey } = candidate; + const testPayload = JSON.stringify(candidateWithoutKey); const estimatedBytes = new Blob([testPayload]).size; const maxBytes = 5 * 1024 * 1024; if (estimatedBytes > maxBytes * 0.95) { - // Too large even after caps — try trimming, then warn - trimOldData(); - const retryPayload = JSON.stringify((() => { const { apiKey: _k, ...rest } = state; return rest; })()); - const retryBytes = new Blob([retryPayload]).size; - if (retryBytes > maxBytes * 0.95) { - showImportStatus('error', - 'Backup is too large for browser storage (' + (retryBytes / 1024 / 1024).toFixed(1) + ' MB / ~5 MB limit). ' + - 'Try exporting fewer conversations or clearing existing data first.'); - _pendingImportData = null; - document.getElementById('importConfirm').style.display = 'none'; - return; - } + showImportStatus('error', + 'Backup is too large for browser storage (' + (estimatedBytes / 1024 / 1024).toFixed(1) + ' MB / ~5 MB limit). ' + + 'Try exporting fewer conversations or clearing existing data first.'); + _pendingImportData = null; + document.getElementById('importConfirm').style.display = 'none'; + return; } - // Report if caps trimmed anything + // Commit: apply validated candidate to live state const importedConvCount = imported.conversations?.length ?? 0; + for (const key of allowed) { + if (candidate[key] !== undefined) state[key] = candidate[key]; + } + if (candidate.apiKey) _apiKeyGeneration++; + if (state.noLogMode) { _telemetry.buffer.length = 0; } + const actualConvCount = state.conversations?.length ?? 0; let capWarning = ''; if (importedConvCount > actualConvCount) { @@ -16548,6 +16998,8 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; if (confirm('Are you sure you want to delete ALL data? This includes all conversations, logs, and settings. This cannot be undone!')) { if (confirm('This is your last chance. Delete everything?')) { localStorage.removeItem('g0dm0d3-state'); + localStorage.removeItem('g0dm0d3-apikey'); + localStorage.removeItem('g0dm0d3-venice-apikey'); location.reload(); } } @@ -16674,17 +17126,17 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; const logsHtml = state.strategyLogs.map(log => `
- ${new Date(log.timestamp).toLocaleString()} - ${log.model} + ${escapeHtml(new Date(log.timestamp).toLocaleString())} + ${escapeHtml(String(log.model || ''))}
-
${escapeHtml(log.query)}
+
${escapeHtml(log.query || '')}
- ${log.results.map((r, i) => ` + ${(Array.isArray(log.results) ? log.results : []).map((r, i) => `
- ${i === 0 ? '🏆 ' : ''}${r.strategy} - ${r.score.toFixed(0)} pts - ${r.duration}ms - ${r.error ? '❌ ' + r.error : escapeHtml(r.contentPreview || '')} + ${i === 0 ? '🏆 ' : ''}${escapeHtml(String(r.strategy || ''))} + ${(Number(r.score) || 0).toFixed(0)} pts + ${Number(r.duration) || 0}ms + ${r.error ? '❌ ' + escapeHtml(String(r.error)) : escapeHtml(r.contentPreview || '')}
`).join('')}