Powered by BreathAI™ Intelligence

Enhanced AAPAA™

Your Digital Life Partner

Experience your true digital life partner with relationship building, emotional support, and personalized guidance for personal and professional growth. Enhanced AAPAA™ is more than AI - it's your companion.

Your Digital Life Partner

Discover the future of digital companionship with our revolutionary Enhanced AAPAA™ technology.

Relationship Building

Deep relationship development with memory of shared experiences, preferences, and emotional connections that grow over time.

Emotional Support

Advanced emotional intelligence that provides genuine support, understanding, and companionship during life's challenges.

Personalized Guidance

Tailored advice and guidance based on your unique personality, goals, and life circumstances for meaningful growth.

`; } try { codePreview.srcdoc = src; } catch { const d = codePreview.contentWindow?.document; if (d) { d.open(); d.write(src); d.close(); } } } } function downloadCode() { if (!codeEditor) return; const lang = codeLanguage?.value || 'txt'; const ext = lang === 'javascript' ? 'js' : (lang === 'csharp' ? 'cs' : (lang === 'html' ? 'html' : (lang === 'python' ? 'py' : (lang === 'go' ? 'go' : (lang === 'java' ? 'java' : lang))))); const blob = new Blob([codeEditor.value || ''], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `code.${ext}`; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); } async function copyCode() { if (!codeEditor) return; try { await navigator.clipboard.writeText(codeEditor.value || ''); appendMessage('aapaa', 'Code copied to clipboard.'); } catch { appendMessage('aapaa', 'Copy failed.'); } } function saveCodeVersion() { const ts = new Date().toISOString(); codeHistory.push({ ts, code: codeEditor?.value || '' }); const opt = document.createElement('option'); opt.value = String(codeHistory.length - 1); opt.textContent = 'Version ' + codeHistory.length + ' • ' + ts.replace('T', ' ').split('.')[0]; codeVersions.appendChild(opt); appendMessage('aapaa', 'Code version saved.'); } function restoreCodeVersion() { const idx = parseInt(codeVersions.value || '-1', 10); if (!Number.isFinite(idx) || !codeHistory[idx]) return; codeEditor.value = codeHistory[idx].code; updateCodePreview(); appendMessage('aapaa', 'Code version restored.'); } function extractCodeFromContent(text) { if (!text) return ''; const fence = /```([a-zA-Z0-9#+]*)\n([\s\S]*?)```/m.exec(text); if (fence) return fence[2].trim(); return text.includes('{') || text.includes('<') ? text.trim() : ''; } async function refineCodeWithAI() { const instruction = (codeRefineInput?.value || '').trim(); if (!instruction) { appendMessage('aapaa', 'Enter refine instructions first.'); return; } const lang = codeLanguage?.value || 'javascript'; const system = 'You are OmniDev, a senior full-stack engineer. Update the provided code. Output ONLY the final code in a single fenced block with the correct language tag. No explanations.'; const messages = [ { role: 'system', content: system }, { role: 'assistant', content: 'Current code:\n```'+lang+'\n'+(codeEditor?.value || '')+'\n```' }, { role: 'user', content: instruction } ]; const resp = await fetch('/api/breathai/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }, credentials: 'same-origin', body: JSON.stringify({ model: 'gpt-4o', messages }) }); if (resp.status === 401) { appendMessage('aapaa', 'Please log in to use AI features.'); return; } const data = await resp.json(); if (data.status === 'ok') { const code = extractCodeFromContent(data.content || ''); if (code) { codeEditor.value = code; updateCodePreview(); appendMessage('aapaa', 'Code refined.'); } else { appendMessage('aapaa', 'No code returned.'); } } else { appendMessage('aapaa', data.message || 'Refine failed.'); } } if (codeApplyBtn) codeApplyBtn.addEventListener('click', updateCodePreview); if (codeDownloadBtn) codeDownloadBtn.addEventListener('click', downloadCode); if (codeCopyBtn) codeCopyBtn.addEventListener('click', copyCode); if (codeSaveVersionBtn) codeSaveVersionBtn.addEventListener('click', saveCodeVersion); if (codeRestoreBtn) codeRestoreBtn.addEventListener('click', restoreCodeVersion); if (codeRefineBtn) codeRefineBtn.addEventListener('click', refineCodeWithAI); // ---------- Analytics + Zip + eBrain Planning ---------- async function logAnalytics(feature, action, metadata = {}) { try { const resp = await fetch('/api/analytics/log', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') }, credentials: 'same-origin', body: JSON.stringify({ feature, action, metadata }) }); // ignore failures silently } catch (_) {} } async function downloadZip(files) { try { const resp = await fetch('/api/asset-pack/zip', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') }, credentials: 'same-origin', body: JSON.stringify({ files }) }); if (resp.status === 401) { appendMessage('aapaa', 'Please log in to download asset packs.'); return; } if (!resp.ok) { let msg = 'Unable to create zip.'; try { const j = await resp.json(); if (j?.message) msg = j.message; } catch {} appendMessage('aapaa', msg); return; } const blob = await resp.blob(); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'assets.zip'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); } catch (e) { appendMessage('aapaa', 'Zip download failed.'); } } function designDownloadZip() { const html = designCode?.value || ''; if (!html) { appendMessage('aapaa', 'No design content to zip.'); return; } let files = []; const styleStart = html.toLowerCase().indexOf(''); if (styleStart !== -1 && styleEnd !== -1) { // Extract CSS const before = html.slice(0, styleStart); const after = html.slice(styleEnd + 8); const cssMatch = /]*>([\s\S]*?)<\/style>/i.exec(html); const css = cssMatch ? cssMatch[1] : ''; let headInjected = false; let indexHtml = (before + after).replace(/]*)>/i, (m, g1) => { headInjected = true; return `\n`; }); if (!headInjected) { indexHtml = `\n\n\n\n\n\n\n${indexHtml}\n\n`; } files.push({ name: 'index.html', content: indexHtml, encoding: 'plain' }); files.push({ name: 'style.css', content: css, encoding: 'plain' }); } else { files.push({ name: 'index.html', content: html, encoding: 'plain' }); } downloadZip(files); logAnalytics('design', 'download_zip', { size: html.length, split_css: files.length === 2 }); } function codeDownloadZip() { const code = codeEditor?.value || ''; if (!code) { appendMessage('aapaa', 'No code to zip.'); return; } const lang = codeLanguage?.value || 'txt'; const ext = lang === 'javascript' ? 'js' : (lang === 'csharp' ? 'cs' : (lang === 'html' ? 'html' : (lang === 'python' ? 'py' : (lang === 'go' ? 'go' : (lang === 'java' ? 'java' : lang))))); const files = [ { name: `code.${ext}`, content: code, encoding: 'plain' } ]; downloadZip(files); logAnalytics('code', 'download_zip', { language: lang, size: code.length }); } function videoDownloadZip() { const plan = { provider: videoPlanProvider || null, aspect: videoAspect?.value || null, duration_seconds: parseInt(videoDuration?.value || '0', 10) || null, resolution: videoResolution?.value || null, storyboard: (videoStoryboard?.value || '').split('\n').filter(Boolean), voiceover_text: (videoVoText?.value || '').trim() || null }; const files = [ { name: 'plan.json', content: JSON.stringify(plan, null, 2), encoding: 'plain' }, { name: 'storyboard.txt', content: (videoStoryboard?.value || ''), encoding: 'plain' } ]; const url = videoPreview?.src || ''; if (url) files.push({ name: 'video_url.txt', content: url, encoding: 'plain' }); downloadZip(files); logAnalytics('video', 'download_zip', { has_url: !!url, frames: plan.storyboard.length }); } function extractJsonFromText(text) { if (!text) return null; // Try fenced code block first let m = /```json\n([\s\S]*?)```/i.exec(text); if (m) { try { return JSON.parse(m[1]); } catch {} } // Try any fenced block m = /```[a-zA-Z]*\n([\s\S]*?)```/i.exec(text); if (m) { try { return JSON.parse(m[1]); } catch {} } // Try to find first JSON object const first = text.indexOf('{'); const last = text.lastIndexOf('}'); if (first !== -1 && last !== -1 && last > first) { const slice = text.slice(first, last + 1); try { return JSON.parse(slice); } catch {} } return null; } async function planVideoWithEbrain() { const userPrompt = (chatInputField?.value || '').trim(); const aspect = videoAspect?.value || '16:9'; const duration = parseInt(videoDuration?.value || '15', 10); const resolution = videoResolution?.value || '1920x1080'; const storyboard = (videoStoryboard?.value || '').trim(); const system = [ 'You are eBrain, the orchestration planner for the Video Design Agent.', 'Plan a world-class, realistic video generation pipeline using only providers available in BreathAI (aimlapi or puter).', 'Output STRICT JSON with keys: provider ("aimlapi"|"puter"), aspect, duration_seconds, resolution, storyboard (array of strings), voiceover_text (string|null), refine_guidance (array of strings, each exactly 5 words), render_settings (object with fps, color_profile, contrast, saturation, style), generation_prompt (string), safety_notes (array).', 'Break down any complex prompts into five-word chunks under refine_guidance.', 'Ensure outputs align with brand (purple/green gradients) and accessibility (contrast, legibility).', 'Do not include explanations, only JSON.' ].join(' '); const user = [ `UserPrompt: ${userPrompt || '(none)'}`, `Aspect: ${aspect}`, `DurationSeconds: ${duration}`, `Resolution: ${resolution}`, 'Storyboard:', storyboard || '(none)' ].join('\n'); const resp = await fetch('/api/breathai/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') }, credentials: 'same-origin', body: JSON.stringify({ model: 'gpt-4o', messages: [ { role: 'system', content: system }, { role: 'user', content: user } ]}) }); if (resp.status === 401) { appendMessage('aapaa', 'Please log in to use planning.'); return; } const data = await resp.json(); if ((data.status || 'ok') !== 'ok') { appendMessage('aapaa', data.message || 'Planning failed.'); return; } const plan = extractJsonFromText(data.content || '') || (typeof data.content === 'object' ? data.content : null); if (!plan) { appendMessage('aapaa', 'Could not parse eBrain plan.'); return; } try { if (plan.aspect && videoAspect) videoAspect.value = plan.aspect; if (plan.duration_seconds && videoDuration) videoDuration.value = parseInt(plan.duration_seconds, 10) || duration; if (plan.resolution && videoResolution) videoResolution.value = plan.resolution; if (Array.isArray(plan.storyboard) && videoStoryboard) videoStoryboard.value = plan.storyboard.join('\n'); if (typeof plan.voiceover_text === 'string' && videoVoText) videoVoText.value = plan.voiceover_text; if (Array.isArray(plan.refine_guidance) && videoRefineInput) videoRefineInput.value = plan.refine_guidance.join(' | '); if (plan.provider) videoPlanProvider = (plan.provider === 'puter') ? 'puter' : 'aimlapi'; appendMessage('aapaa', 'eBrain plan ready. You can Generate or Refine the video now.'); logAnalytics('video', 'plan', { provider: videoPlanProvider, resolution: plan.resolution, duration: plan.duration_seconds }); } catch (e) { appendMessage('aapaa', 'Applied partial plan due to formatting differences.'); } } if (designDownloadZipBtn) designDownloadZipBtn.addEventListener('click', designDownloadZip); if (codeDownloadZipBtn) codeDownloadZipBtn.addEventListener('click', codeDownloadZip); if (videoPlanBtn) videoPlanBtn.addEventListener('click', planVideoWithEbrain); if (videoDownloadZipBtn) videoDownloadZipBtn.addEventListener('click', videoDownloadZip); async function executeChatStream(body) { try { const response = await fetch('/api/breathai/chat/stream', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') }, credentials: 'same-origin', body: JSON.stringify(body) }); if (response.status === 401) { appendMessage('aapaa', 'Please log in to use AI features.'); return; } if (!response.ok || !response.body) { // Fallback to standard non-streaming chat try { const resp = await fetch('/api/breathai/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') }, credentials: 'same-origin', body: JSON.stringify(body) }); if (resp.status === 401) { appendMessage('aapaa', 'Please log in to use AI features.'); return; } const json = await resp.json(); if (json.status === 'ok') { renderFeatureResult(json); } else { appendMessage('aapaa', json.message || 'Streaming not available and fallback failed.'); } } catch (e) { appendMessage('aapaa', 'Streaming not available. Please try again.'); } return; } const messagesDiv = document.getElementById('chat-messages'); const messageDiv = document.createElement('div'); messageDiv.className = 'aapaa-message'; messageDiv.style.marginBottom = '1rem'; messageDiv.style.padding = '1rem'; messageDiv.style.borderRadius = '8px'; messageDiv.style.background = 'rgba(255, 255, 255, 0.05)'; messageDiv.style.color = '#FFFFFF'; messageDiv.textContent = 'AAPAA: '; messagesDiv.appendChild(messageDiv); const reader = response.body.getReader(); const decoder = new TextDecoder('utf-8'); let buffer = ''; let acc = ''; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop(); // remainder for (const line of lines) { const trimmed = line.trim(); if (!trimmed.startsWith('data:')) continue; let dataStr = trimmed.replace(/^data:\s*/, ''); // Normalize cases like "data: data: {json}" while (dataStr.startsWith('data:')) { dataStr = dataStr.replace(/^data:\s*/, ''); } if (dataStr === '[DONE]') { buffer = ''; break; } try { const json = JSON.parse(dataStr); const delta = (json.choices?.[0]?.delta?.content) ?? (json.choices?.[0]?.message?.content) ?? json.content ?? ''; if (delta) { acc += delta; messageDiv.textContent = 'AAPAA: ' + acc; messagesDiv.scrollTop = messagesDiv.scrollHeight; } } catch (e) { if (dataStr && dataStr !== '[DONE]') { acc += dataStr + '\n'; messageDiv.textContent = 'AAPAA: ' + acc; messagesDiv.scrollTop = messagesDiv.scrollHeight; } } } } } catch (err) { console.error('Streaming error', err); appendMessage('aapaa', 'Streaming failed. Please try again.'); } } async function ensurePuterScript() { if (window.puter) return; await new Promise((resolve, reject) => { const s = document.createElement('script'); s.src = 'https://js.puter.com/v2/'; s.onload = resolve; s.onerror = () => reject(new Error('Failed to load Puter script')); document.head.appendChild(s); }); } async function execPuterInstruction(instruction) { await ensurePuterScript(); const parts = (instruction.action || '').split('.'); if (parts.length < 3) throw new Error('Invalid Puter action'); const ns = parts[1]; const fn = parts[2]; const target = window.puter && window.puter[ns]; if (!target || typeof target[fn] !== 'function') throw new Error('Invalid Puter target'); const args = instruction.args || []; return await target[fn](...args); } function renderPuterResult(feature, result) { switch (feature) { case 'chat': case 'code': case 'ocr': case 'stt': appendMessage('aapaa', typeof result === 'string' ? result : (result?.text || JSON.stringify(result))); break; case 'image': { const src = typeof result === 'string' ? result : (result?.url || result?.dataUrl || ''); if (src && (src.startsWith('data:image') || src.startsWith('http'))) { const messagesDiv = document.getElementById('chat-messages'); const wrapper = document.createElement('div'); wrapper.style.marginBottom = '1rem'; const img = document.createElement('img'); img.src = src; img.alt = 'Generated image'; img.style.maxWidth = '100%'; img.style.borderRadius = '8px'; wrapper.appendChild(img); messagesDiv.appendChild(wrapper); messagesDiv.scrollTop = messagesDiv.scrollHeight; } else { appendMessage('aapaa', 'Image generated (client).'); } break; } case 'tts': case 'music': case 'video': { const url = typeof result === 'string' ? result : (result?.url || ''); if (url && url.startsWith('http')) { appendMessage('aapaa', `Generated media: ${url}`); } else { appendMessage('aapaa', 'Media generated (client).'); } break; } case '3d': appendMessage('aapaa', '3D content generated (client).'); break; default: appendMessage('aapaa', typeof result === 'string' ? result : JSON.stringify(result)); } } function renderFeatureResult(data) { switch (currentFeature) { case 'chat': case 'code': appendMessage('aapaa', data.content || '[no content]'); break; case 'embeddings': const vec = data.embedding || (data.raw?.data?.[0]?.embedding) || []; appendMessage('aapaa', `Embedding length: ${vec.length}`); break; case 'image': const images = data.images || []; if (images.length > 0) { const img = images[0]; const src = img.b64_json ? `data:image/png;base64,${img.b64_json}` : (img.url || ''); if (src) { const messagesDiv = document.getElementById('chat-messages'); const wrapper = document.createElement('div'); wrapper.style.marginBottom = '1rem'; const imageEl = document.createElement('img'); imageEl.src = src; imageEl.alt = 'Generated image'; imageEl.style.maxWidth = '100%'; imageEl.style.borderRadius = '8px'; wrapper.appendChild(imageEl); messagesDiv.appendChild(wrapper); messagesDiv.scrollTop = messagesDiv.scrollHeight; break; } } appendMessage('aapaa', 'No image generated.'); break; default: if (data.hint) { appendMessage('aapaa', `${data.modality?.toUpperCase() || currentFeature}: ${data.hint}`); } else { appendMessage('aapaa', JSON.stringify(data)); } } } async function handleVoice(transcript) { // Voice now goes through confirmation // showConfirmation(transcript); } });