@@ -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 => `
-
${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('')}