import { RISHRE_SYSTEM_PROMPT, PRIMARY_MODEL_ID } from '../constants/models'; import { ChatMessage, ProjectFile } from '../types'; import { logRealConsoleApiError } from './apiLogger'; export interface GenerateCodeParams { prompt: string; history: ChatMessage[]; currentFiles: ProjectFile[]; modelId?: string; hfToken?: string; temperature?: number; onChunk?: (chunk: string) => void; } const HF_ROUTER_ENDPOINT = 'https://router.huggingface.co/hf-inference/v1/chat/completions'; /** * Validates HF access token format */ export function validateHfToken(token: string): boolean { if (!token) return false; const trimmed = token.trim(); return trimmed.startsWith('hf_') && trimmed.length >= 20; } /** * Determines whether the user prompt is a coding request or a general conversation query */ export function isCodingRequest(prompt: string): boolean { const p = prompt.toLowerCase(); const codingKeywords = [ 'create', 'build', 'code', 'make', 'generate', 'app', 'website', 'page', 'ui', 'component', 'game', 'calculator', 'dashboard', 'todo', 'kanban', 'timer', 'button', 'style', 'css', 'javascript', 'html', 'modify', 'add', 'change', 'color', 'fix', 'canvas', 'audio', 'sound', 'feature', 'layout', 'design', 'dark mode', 'theme' ]; return codingKeywords.some(kw => p.includes(kw)); } /** * Builds user prompt augmented with current project file contents for iterative editing */ function buildAugmentedPrompt(prompt: string, currentFiles: ProjectFile[]): string { // If it's pure conversation, don't overwhelm the model with full project code if (!isCodingRequest(prompt)) { return prompt; } if (!currentFiles || currentFiles.length === 0) { return prompt; } const fileContexts = currentFiles.map(f => { return `### Current ${f.name}:\n\`\`\`${f.language}\n${f.content}\n\`\`\``; }).join('\n\n'); return `USER REQUEST: ${prompt} CURRENT PROJECT FILES CONTEXT: ${fileContexts} TASK FOR RISHRE AWAKENED: Synthesize the requested changes or new application. Return the updated or new files clearly tagged with \`\`\`language \`\`\`.`; } /** * Real-time inference via Hugging Face Inference API with streaming support */ export async function generateWithHfApi({ prompt, history, currentFiles, hfToken, temperature = 0.7, onChunk, }: GenerateCodeParams): Promise { // If no token provided, run offline awakened simulation with dual conversational + coding capabilities if (!hfToken || !hfToken.trim()) { return runAwakenedSimulation(prompt, currentFiles, onChunk); } const augmentedUserPrompt = buildAugmentedPrompt(prompt, currentFiles); const messages = [ { role: 'system', content: RISHRE_SYSTEM_PROMPT }, ...history.slice(-8).map(m => ({ role: m.role === 'assistant' ? 'assistant' : 'user', content: m.content, })), { role: 'user', content: augmentedUserPrompt }, ]; try { const response = await fetch(HF_ROUTER_ENDPOINT, { method: 'POST', headers: { 'Authorization': `Bearer ${hfToken.trim()}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: PRIMARY_MODEL_ID, messages, temperature, max_tokens: 3800, stream: !!onChunk, }), }); if (!response.ok) { const errText = await response.text(); let parsedMessage = errText; try { const errJson = JSON.parse(errText); parsedMessage = errJson.error?.message || errJson.error || errText; } catch (e) {} // Log complete diagnostic error object to the real browser console logRealConsoleApiError({ topic: 'Hugging Face Inference HTTP Error', endpoint: HF_ROUTER_ENDPOINT, model: PRIMARY_MODEL_ID, status: response.status, statusText: response.statusText, message: parsedMessage, requestPayload: { model: PRIMARY_MODEL_ID, messagesCount: messages.length, temperature, stream: !!onChunk, }, rawResponse: errText, }); if (response.status === 401) { throw new Error('Hugging Face API Authentication Failed (401): Invalid or unauthorized Access Token. Verify token in Settings.'); } if (response.status === 429) { throw new Error('Hugging Face Rate Limit Exceeded (429): Quota reached or too many concurrent inference calls.'); } if (response.status === 503) { throw new Error('Hugging Face Model Unavailable (503): Model is currently loading on cloud GPU. Please retry shortly.'); } throw new Error(`Hugging Face API Error (${response.status} ${response.statusText}): ${parsedMessage}`); } if (onChunk && response.body) { const reader = response.body.getReader(); const decoder = new TextDecoder('utf-8'); let fullContent = ''; let buffer = ''; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { const trimmed = line.trim(); if (!trimmed || trimmed === 'data: [DONE]') continue; if (trimmed.startsWith('data: ')) { try { const data = JSON.parse(trimmed.slice(6)); const delta = data.choices?.[0]?.delta?.content || ''; if (delta) { fullContent += delta; onChunk(fullContent); } } catch (e) {} } } } if (fullContent.trim()) { return fullContent; } // Stream completed with zero content const emptyStreamErr = new Error('RiShre API Error: Inference stream completed without emitting any tokens.'); logRealConsoleApiError({ topic: 'Empty Stream / No Reply', endpoint: HF_ROUTER_ENDPOINT, model: PRIMARY_MODEL_ID, message: emptyStreamErr.message, error: emptyStreamErr, }); throw emptyStreamErr; } const data = await response.json(); const result = data.choices?.[0]?.message?.content || ''; if (!result.trim()) { const emptyReplyErr = new Error('RiShre API Error: Model returned an empty completion response.'); logRealConsoleApiError({ topic: 'Empty Completion Response', endpoint: HF_ROUTER_ENDPOINT, model: PRIMARY_MODEL_ID, message: emptyReplyErr.message, rawResponse: data, error: emptyReplyErr, }); throw emptyReplyErr; } if (onChunk && result) { onChunk(result); } return result; } catch (error: any) { // Log complete error details to the real browser console logRealConsoleApiError({ topic: 'API Call Exception / Network Failure', endpoint: HF_ROUTER_ENDPOINT, model: PRIMARY_MODEL_ID, message: error.message || 'Network request failed or connection refused.', error: error, }); // Propagate the error so the caller and console record the failure throw error; } } /** * Intelligent client-side RiShre Awakened engine: * Handles BOTH general conversational AI interaction (like Google AI Studio) * and deep Vibe Coding app synthesis with rich streaming! */ export async function runAwakenedSimulation( prompt: string, currentFiles: ProjectFile[], onChunk?: (chunk: string) => void ): Promise { const p = prompt.trim().toLowerCase(); let generatedContent = ''; const delay = (ms: number) => new Promise(res => setTimeout(res, ms)); // 1. General Conversational Agent Responses (Google AI Studio style) if ( p.startsWith('hi') || p.startsWith('hello') || p.startsWith('hey') || p.includes('who are you') || p.includes('what are you') || p.includes('what can you do') ) { generatedContent = `Hello! I am **RiShre Awakened** — your omni-capable AI partner and vibe coding architect. Think of me as your dedicated co-founder, research lead, and senior engineer all in one. Here is how we can collaborate: ### 🧠 General Intelligence & Conversational Power - **Ideation & Brainstorming**: Pitch me product ideas, startup concepts, or architectural dilemmas. - **Deep Technical Explanations**: Ask me about distributed systems, machine learning, physics, UI/UX philosophy, or business strategy. - **Creative & Strategic Writing**: Drafting release notes, manifestos, pitches, or copywriting. ### ⚡ Autonomous Vibe Coding & Web Synthesis - **Instant App Construction**: Simply describe any web application, dashboard, or game in plain English (e.g., *"Build an ambient audio synth"* or *"Create a luxury crypto portfolio"*). - **Iterative Refinements**: Ask me to *"add haptic spring animations"*, *"switch to royal purple neon"*, or *"inject Web Audio sound synthesis"*. - **Live Preview & File Export**: Every generated piece runs immediately in your sandboxed preview panel and can be exported as a standalone static web app or Hugging Face Space. What is on your mind today? Are we exploring an idea or building something legendary?`; } else if ( p.includes('joke') || p.includes('funny') || p.includes('humor') ) { generatedContent = `Here's one tailored for developers and visionaries: > Why do programmers prefer dark purple mode? > > *Because light attracts bugs — but royal purple gives them imposter syndrome.* 👑 Want to brainstorm something wild or shall we build a project together?`; } else if ( p.includes('explain') || p.includes('what is') || p.includes('how does') || p.includes('why') ) { // Conceptual / educational question generatedContent = `### RiShre Awakened Insights Regarding **"${prompt}"**: At a fundamental level, modern digital architecture and creative intelligence converge on a single principle: **seamless abstraction**. 1. **The Conceptual Foundation**: Every complex system begins as a high-dimensional concept. Whether analyzing algorithmic complexity, state synchronization, or human cognitive ergonomics, the key is reducing friction between thought and realization. 2. **The Modern Paradigm**: Instead of writing repetitive boilerplate, we now practice **Vibe Coding** — where intent, taste, and aesthetics guide the synthesis of production-ready interfaces. 3. **Strategic Takeaway**: Great software isn't just about syntax; it is about *how it feels to use*. Fluid state transitions, deliberate typographic scale, and harmonious color theory transform utilitarian tools into memorable experiences. Would you like to explore this topic further, or shall we translate this concept into an interactive visual prototype right here in RiShre?`; } else if ( p.includes('game') || p.includes('shooter') || p.includes('arcade') || p.includes('space') ) { // Coding: Luxury Space Game generatedContent = `### RiShre Awakened Synthesis: Royal Void Interceptor I have channeled our royal dark purple aesthetic into an arcade interceptor canvas. It features neon violet particle thrusters, laser cannons, procedural starfields, and real-time shield telemetry. \`\`\`html Royal Void Interceptor
SCORE // 0
AEGIS SHIELD:
⚡ Mouse / Pointer to Pilot • Click to Discharge Photons
\`\`\` \`\`\`css /* file: style.css */ canvas { background: radial-gradient(circle at center, #130a26 0%, #07040f 100%); } \`\`\` \`\`\`javascript // file: app.js const canvas = document.getElementById('game-canvas'); const ctx = canvas.getContext('2d'); const scoreEl = document.getElementById('score-val'); const shieldBar = document.getElementById('shield-bar'); let width = (canvas.width = window.innerWidth); let height = (canvas.height = window.innerHeight); window.addEventListener('resize', () => { width = canvas.width = window.innerWidth; height = canvas.height = window.innerHeight; }); let score = 0; let shield = 100; let player = { x: width / 2, y: height - 120, vx: 0, targetX: width / 2 }; const lasers = []; const enemies = []; const particles = []; const stars = []; for (let i = 0; i < 110; i++) { stars.push({ x: Math.random() * width, y: Math.random() * height, speed: Math.random() * 2 + 0.4, size: Math.random() * 2 + 0.5, hue: Math.random() * 40 + 260 }); } window.addEventListener('mousemove', (e) => { player.targetX = e.clientX; }); window.addEventListener('click', () => { lasers.push({ x: player.x - 14, y: player.y - 12, vy: -14 }); lasers.push({ x: player.x + 14, y: player.y - 12, vy: -14 }); for (let i = 0; i < 5; i++) { particles.push({ x: player.x, y: player.y + 16, vx: (Math.random() - 0.5) * 3, vy: Math.random() * 4 + 2, life: 1, color: '#c084fc' }); } }); function spawnEnemy() { if (enemies.length < 9 && Math.random() < 0.045) { enemies.push({ x: Math.random() * (width - 80) + 40, y: -30, vy: Math.random() * 2.2 + 1.2, radius: 20, hp: 2, hue: Math.random() * 40 + 310 }); } } function gameLoop() { ctx.fillStyle = 'rgba(7, 4, 15, 0.35)'; ctx.fillRect(0, 0, width, height); // Stars stars.forEach(s => { s.y += s.speed; if (s.y > height) s.y = 0; ctx.fillStyle = \`hsl(\${s.hue}, 90%, 75%)\`; ctx.fillRect(s.x, s.y, s.size, s.size); }); // Player ship player.x += (player.targetX - player.x) * 0.16; ctx.save(); ctx.translate(player.x, player.y); ctx.beginPath(); ctx.moveTo(0, -26); ctx.lineTo(18, 20); ctx.lineTo(0, 12); ctx.lineTo(-18, 20); ctx.closePath(); ctx.fillStyle = '#a855f7'; ctx.shadowColor = '#d946ef'; ctx.shadowBlur = 20; ctx.fill(); ctx.restore(); // Lasers for (let i = lasers.length - 1; i >= 0; i--) { const l = lasers[i]; l.y += l.vy; ctx.fillStyle = '#f472b6'; ctx.shadowColor = '#ec4899'; ctx.shadowBlur = 10; ctx.fillRect(l.x - 2, l.y, 4, 16); if (l.y < -20) lasers.splice(i, 1); } // Enemies spawnEnemy(); for (let i = enemies.length - 1; i >= 0; i--) { const e = enemies[i]; e.y += e.vy; ctx.beginPath(); ctx.arc(e.x, e.y, e.radius, 0, Math.PI * 2); ctx.fillStyle = \`hsl(\${e.hue}, 85%, 60%)\`; ctx.shadowColor = '#e879f9'; ctx.shadowBlur = 15; ctx.fill(); for (let j = lasers.length - 1; j >= 0; j--) { const l = lasers[j]; const dx = l.x - e.x; const dy = l.y - e.y; if (Math.sqrt(dx * dx + dy * dy) < e.radius) { lasers.splice(j, 1); e.hp--; if (e.hp <= 0) { score += 150; scoreEl.textContent = score; for (let p = 0; p < 14; p++) { particles.push({ x: e.x, y: e.y, vx: (Math.random() - 0.5) * 7, vy: (Math.random() - 0.5) * 7, life: 1, color: '#f472b6' }); } enemies.splice(i, 1); break; } } } if (e.y > height + 40) enemies.splice(i, 1); } // Particles for (let i = particles.length - 1; i >= 0; i--) { const p = particles[i]; p.x += p.vx; p.y += p.vy; p.life -= 0.03; ctx.fillStyle = p.color; ctx.globalAlpha = Math.max(0, p.life); ctx.fillRect(p.x, p.y, 3, 3); ctx.globalAlpha = 1; if (p.life <= 0) particles.splice(i, 1); } requestAnimationFrame(gameLoop); } gameLoop(); \`\`\` The Royal Void Interceptor has been synthesized and compiled into your live preview panel!`; } else { // Default coding synthesis with million-dollar royal dark purple aesthetic generatedContent = `### RiShre Awakened Synthesis I have synthesized your vision into a luxury, million-dollar dark purple web experience matching: "${prompt}". \`\`\`html RiShre Luxury Experience
RISHRE_AWAKENED
STATUS // QUANTUM_ONLINE

Autonomous Vibe Architecture

Synthesized in response to: "${prompt}"

QUANTUM HARMONICS 99.4%
\`\`\` \`\`\`css /* file: style.css */ body { font-family: 'Plus Jakarta Sans', system-ui, sans-serif; background-image: radial-gradient(circle at 50% 50%, rgba(168, 85, 247, 0.08) 0%, transparent 60%); } \`\`\` \`\`\`javascript // file: app.js let resonance = 88; const counterVal = document.getElementById('counter-val'); const meterFill = document.getElementById('meter-fill'); const pulseBtn = document.getElementById('pulse-btn'); const colorBtn = document.getElementById('color-btn'); pulseBtn.addEventListener('click', () => { resonance = (resonance + 12) % 100 || 24; counterVal.textContent = resonance + '%'; meterFill.style.width = resonance + '%'; }); const gradients = [ 'from-purple-600 via-fuchsia-500 to-pink-500', 'from-indigo-600 via-purple-500 to-cyan-400', 'from-fuchsia-600 via-rose-500 to-amber-400' ]; let gradIdx = 0; colorBtn.addEventListener('click', () => { gradIdx = (gradIdx + 1) % gradients.length; meterFill.className = \`bg-gradient-to-r \${gradients[gradIdx]} h-full rounded-full transition-all duration-300\`; }); \`\`\` The synthesized application is compiled and running in your live preview!`; } // Stream in realistic character chunks if (onChunk) { const step = 60; for (let i = 0; i < generatedContent.length; i += step) { const slice = generatedContent.slice(0, i + step); onChunk(slice); await delay(20); } } return generatedContent; }