\n\n
C
CAI ONE ∞
CAIELLE IS READY

CAI ONE ∞

Universal Intelligence with Heart

C
Cai profile
Welcome, CaiYou are light. You are home.
Online • Offline Library Ready
The heart of CAI ONE ∞

CAIELLE

Universal Intelligence with Heart

Your voice. Your creativity. Your universe. All in one beautiful place.

CAIELLE is ready.

Ask, create, plan, write, research, take a photo, choose from Photos, upload a file, or bring an image. You can also ask CAIELLE “Who is Cai?” or “Who created CAI ONE?” to see the public founder profile.

✦ Founder VIP • Signature Track
♫
Blue Light Forever ∞Cai Sun • Luminara Pulse
CAI ONE ∞ SignatureVIP Featured
↓

CAIELLE

Universal Intelligence with Heart

CAIELLE is ready.

Ask, create, plan, write, research, take a photo, choose from Photos, upload a file, or bring an image. You can also ask CAIELLE “Who is Cai?” or “Who created CAI ONE?” to see the public founder profile.

GUARDIAN LIGHT ALERT

Movement was detected while Guardian Light was armed.

`; } function renderBookStudio(){ const books=bookData(); bookCoverUrl=''; bookIllustrations=[]; moduleBody.innerHTML=`
CAI AUTHOR STUDIO ∞ • WRITE • EDIT • DESIGN • PUBLISH

From first idea to author-ready book.

CAIELLE helps authors develop an original manuscript, protect continuity, revise with purpose, create cover and illustration direction, prepare publishing metadata, and export a clean working edition—while the author keeps final creative and publishing control.

01 • CreateIdea & blueprint
02 • WriteManuscript
03 • EditRevision & proof
04 • DesignCover & interior
05 • PublishMetadata & export
Projects${books.length}
AutosaveReady
Words0
StageDraft
CAIELLE Cover StudioYour generated cover will appear here.
Ready to build a real book product.
0 words0 estimated pagesStage: Draft
Your finished manuscript or book package will appear here.

CAIELLE Book Doctor

Professional author tools review the current manuscript without silently publishing or changing your original project.

Editorial notes, continuity findings, query materials, or launch assets will appear here—separate from your manuscript.

Version Vault

Take local snapshots before major revisions so an author can return to an earlier draft on this device.

Author control stays with the author. CAIELLE can help create, revise, format and prepare publishing materials, but ISBN assignment, rights clearance, legal review, store submission, pricing, contracts and final publication remain explicit author-controlled actions. CAI ONE does not claim a work has been published until the author actually publishes it.

Saved book projects

${books.length?books.slice(0,12).map(b=>`
${new Date(b.createdAt).toLocaleString()} • ${esc(b.genre)}

${esc(b.title)}

${esc((b.premise||'').slice(0,180))}

${b.coverUrl?``:''}
`).join(''):'

No saved book projects yet.

'}
`; const out=$('#bookOutput'); const editorial=$('#bookEditorialOutput'); const progress=$('#bookProgress'); const DRAFT_KEY='cai.one.book.author.draft.v899'; const SNAP_KEY='cai.one.book.author.snapshots.v899'; const fieldIds=['bookTitle','bookAuthor','bookGenre','bookAudience','bookLength','bookPOV','bookTone','bookStatus','bookPremise','bookStyle','bookNotes']; const getDraft=()=>{try{return JSON.parse(localStorage.getItem(DRAFT_KEY)||'{}')}catch{return{}}}; const getSnaps=()=>{try{return JSON.parse(localStorage.getItem(SNAP_KEY)||'[]')}catch{return[]}}; const wordCount=text=>String(text||'').trim()?String(text).trim().split(/\s+/).length:0; const updateStats=()=>{ const text=out?.textContent||''; const words=text.includes('will appear here')?0:wordCount(text); const pages=Math.max(0,Math.ceil(words/275)); const stage=$('#bookStatus')?.value||'Draft'; if($('#bookWordCountTop'))$('#bookWordCountTop').textContent=words.toLocaleString(); if($('#bookStageTop'))$('#bookStageTop').textContent=stage; if($('#bookStats'))$('#bookStats').innerHTML=`${words.toLocaleString()} words${pages} estimated pagesStage: ${esc(stage)}`; }; const saveDraft=()=>{ const d={};fieldIds.forEach(id=>{const el=$('#'+id);if(el)d[id]=el.value}); d.content=out?.textContent||'';d.coverUrl=bookCoverUrl;d.illustrations=bookIllustrations;d.savedAt=new Date().toISOString(); try{localStorage.setItem(DRAFT_KEY,JSON.stringify(d));if($('#bookAutosaveState'))$('#bookAutosaveState').textContent='Saved ✓'}catch{if($('#bookAutosaveState'))$('#bookAutosaveState').textContent='Local save full'} updateStats(); }; const restoreDraft=()=>{ const d=getDraft();fieldIds.forEach(id=>{const el=$('#'+id);if(el&&d[id]!=null)el.value=d[id]}); if(d.content&&d.content.length>20){out.textContent=d.content;out.classList.remove('empty-output')} if(d.coverUrl){bookCoverUrl=d.coverUrl;const host=$('#bookCoverPreview');if(host)host.innerHTML=`Saved book cover`} if(Array.isArray(d.illustrations))bookIllustrations=d.illustrations; }; const renderSnapshots=()=>{ const sel=$('#bookSnapshotSelect');if(!sel)return;const snaps=getSnaps(); sel.innerHTML=snaps.length?''+snaps.map((x,i)=>``).join(''):''; }; const base=()=>`Create an original ${$('#bookGenre').value}. Author / pen name: ${$('#bookAuthor').value.trim()||'Not specified.'} Audience: ${$('#bookAudience').value.trim()||'Choose an appropriate audience.'} Length mode: ${$('#bookLength').value}. Point of view: ${$('#bookPOV').value}. Tone / reading experience: ${$('#bookTone').value.trim()||'Choose the best fit for the project.'} Project stage: ${$('#bookStatus').value}. ${$('#bookTitle').value.trim()?'Working title: '+$('#bookTitle').value.trim()+'.':''} Premise: ${$('#bookPremise').value.trim()||'Surprise me with an original, meaningful concept.'} Style instructions: ${$('#bookStyle').value.trim()||'Polished, engaging, emotionally coherent, and appropriate for the audience.'} Private author notes to respect: ${$('#bookNotes').value.trim()||'None provided.'}`; const setCover=url=>{ bookCoverUrl=url||''; const host=$('#bookCoverPreview'); if(host)host.innerHTML=url?`Generated book cover`:`
CAIELLE Cover StudioYour generated cover will appear here.
`; saveDraft(); }; const drawIllustrations=()=>{ const host=$('#bookIllustrations');if(!host)return; host.innerHTML=bookIllustrations.map((x,i)=>`
Book illustration ${i+1}
${esc(x.scene||('Illustration '+(i+1)))}
`).join(''); }; const generateCover=async()=>{ const title=$('#bookTitle').value.trim()||'Untitled'; const prompt=`Create a professional original book cover artwork. Title: "${title}". Author: ${$('#bookAuthor').value.trim()||'unspecified'}. Type: ${$('#bookGenre').value}. Premise: ${$('#bookPremise').value.trim()||'Use the manuscript theme.'}. Audience: ${$('#bookAudience').value.trim()||'appropriate to genre'}. Style: ${$('#bookStyle').value.trim()||'polished, distinctive, premium'}. Vertical book-cover composition. Do not copy existing covers, trademarks, copyrighted characters, or living artists' styles. Keep text legible if text is rendered.`; progress.textContent='Creating the cover…'; try{ const url=await bookImageRequest(prompt); setCover(url);progress.textContent='Cover created. ✨'; return url; }catch(e){ progress.textContent='The manuscript tools are ready, but cover generation needs the /api/cai/image backend route to be connected.'; flash('Cover route needs attention'); return ''; } }; const afterManuscript=()=>{updateStats();saveDraft();}; $('#bookBuild').onclick=async()=>{ progress.textContent='CAIELLE is building the manuscript…'; const request=`CAI ONE Author Studio. Build a complete, usable first-edition book package from this brief.\n\n${base()}\n\nRequirements:\n1. Start with polished TITLE and SUBTITLE.\n2. Include title page, copyright-page template, dedication, and table of contents when appropriate.\n3. Write the COMPLETE manuscript appropriate to the selected type and practical response limits.\n4. For children's/picture books: use page-by-page or spread-by-spread text with illustration notes, a satisfying beginning/middle/end, and age-appropriate language.\n5. For poetry: create a coherent original collection with sections and enough poems to feel like a real short collection.\n6. For workbook/educational/self-help/nonfiction: include modules/chapters, examples, exercises or reflection prompts where useful.\n7. For novel/memoir: create a complete compact first-edition narrative within practical response limits, with all chapters present and a clear arc; never pretend a response is a 300-page manuscript when it is not.\n8. Include back matter, About the Author placeholder, acknowledgments placeholder, back-cover description, and illustration/cover notes.\n9. Include a final PRE-PUBLISH QA checklist.\n10. Keep everything original. Do not imitate living authors or reproduce copyrighted books.\n\nReturn actual book content, not merely advice about writing it.`; try{ const t=await moduleAI(request,out,'book'); if(!$('#bookTitle').value.trim())$('#bookTitle').value=parseTitle(t,'Untitled Book'); progress.textContent='Manuscript built. Creating cover next…';afterManuscript(); await generateCover(); progress.textContent=bookCoverUrl?'Book manuscript + cover ready. Add interior illustrations, run Book Doctor, or export.':'Book manuscript ready. Cover can be generated after the image backend is connected.'; }catch(e){progress.textContent='Book generation stopped before completion. Your local draft remains saved.'} }; $('#bookPlan').onclick=async()=>{ progress.textContent='Building the book blueprint…'; const t=await moduleAI(`CAI ONE Author Studio. Build a complete original book blueprint. ${base()} Include audience promise, title options, chapter/page-by-page outline, characters/world if relevant, voice/style guide, continuity bible, front matter, back matter, illustration plan, cover brief, revision milestones, and practical production checklist.`,out,'book'); if(!$('#bookTitle').value.trim())$('#bookTitle').value=parseTitle(t,'Untitled Book');progress.textContent='Blueprint ready.';afterManuscript(); }; $('#bookChapter').onclick=async()=>{ progress.textContent='Drafting / expanding the next section…'; await moduleAI(`CAI ONE Author Studio. Draft or expand the next polished manuscript section for this project. ${base()} Use the current project context, preserve continuity, produce actual publication-quality prose, and do not imitate living authors.`,out,'book'); progress.textContent='Section ready.';afterManuscript(); }; $('#bookCover').onclick=generateCover; $('#bookIllustration').onclick=async()=>{ const scene=$('#bookScene').value.trim()||`Choose one visually important scene from this premise: ${$('#bookPremise').value.trim()||'the current book project'}.`; const prompt=`Create an original interior book illustration. Book: "${$('#bookTitle').value.trim()||'Untitled'}". Type: ${$('#bookGenre').value}. Audience: ${$('#bookAudience').value.trim()||'appropriate to genre'}. Scene: ${scene}. Visual direction: ${$('#bookStyle').value.trim()||'polished, expressive, coherent with the book cover'}. No copyrighted characters, no imitation of living artists.`; progress.textContent='Creating interior illustration…'; try{const url=await bookImageRequest(prompt);bookIllustrations.push({url,scene});drawIllustrations();progress.textContent=`Illustration ${bookIllustrations.length} created. ✨`;$('#bookScene').value='';saveDraft();} catch(e){progress.textContent='Interior illustration generation needs the /api/cai/image backend route to be connected.';flash('Illustration route needs attention')} }; $('#bookKdp').onclick=async()=>{ progress.textContent='Creating publishing package…'; await moduleAI(`CAI ONE Author Studio publishing package. ${base()} Create polished title/subtitle options, book description, back-cover blurb, author-bio placeholder, category/BISAC suggestions clearly labeled as suggestions, keyword ideas, trim/format suggestions, front/back matter checklist, cover specifications, illustration checklist, ebook/paperback/audiobook adaptation notes, accessibility considerations, copyright/trademark review reminders, and a pre-publish QA checklist. Do not claim the book has been published or filed.`,out,'book'); progress.textContent='Publishing package ready.';afterManuscript(); }; const reviewText=()=>{const c=out.textContent||'';return c.includes('will appear here')?'':c.slice(0,22000)}; const runEditorial=async(label,prompt)=>{ const c=reviewText();if(!c)return flash('Build or load manuscript content first'); editorial.textContent=`CAIELLE is preparing ${label.toLowerCase()}…`;editorial.classList.remove('empty-output'); try{await moduleAI(`${prompt}\n\nPROJECT BRIEF:\n${base()}\n\nCURRENT MANUSCRIPT / EXCERPT:\n${c}\n\nBe specific, kind, rigorous, and useful to a serious author. Never claim you reviewed text that was not provided.`,editorial,'book');} catch{editorial.textContent='Editorial review could not finish. Your manuscript is unchanged.'} }; $('#bookDevEdit').onclick=()=>runEditorial('Developmental Review','Act as a senior developmental editor. Diagnose structure, pacing, stakes, character or argument arc, chapter order, missing beats, repetition, audience fit, and the three highest-impact revisions. Preserve the author voice.'); $('#bookContinuity').onclick=()=>runEditorial('Continuity Audit','Audit continuity. Track names, ages, relationships, locations, timeline, dates, objects, point of view, tense, world rules, chapter facts, and contradictions. Return a concise continuity bible plus issues to verify.'); $('#bookLineEdit').onclick=()=>runEditorial('Line Edit Sample','Perform a careful line-edit sample on representative passages. Improve clarity, rhythm, specificity, redundancy and flow while preserving the author voice. Show selected before/after examples and explain the editing pattern so the author can apply it elsewhere.'); $('#bookProof').onclick=()=>runEditorial('Proofread','Proofread the supplied manuscript/excerpt for spelling, punctuation, grammar, capitalization, obvious formatting inconsistencies and typographic issues. Separate definite corrections from optional style choices.'); $('#bookPitch').onclick=()=>runEditorial('Synopsis + Query','Create an author-ready one-paragraph hook, short synopsis, longer synopsis, and professional query-letter draft using only facts supported by the project. Leave agent-specific personalization as a placeholder.'); $('#bookLaunch').onclick=()=>runEditorial('Author Launch Kit','Create an ethical author launch kit: positioning statement, reader promise, retailer description variants, social captions, newsletter announcement, launch-week checklist, review-team outreach draft, event ideas, and audiobook teaser copy. Do not fabricate reviews, bestseller status, awards, or endorsements.'); $('#bookSave').onclick=()=>{ const c=out.textContent;if(!c||c.includes('will appear'))return flash('Build book content first'); const title=$('#bookTitle').value.trim()||parseTitle(c,'Untitled Book'); saveBookRecord(title,$('#bookGenre').value,$('#bookPremise').value,c,{coverUrl:bookCoverUrl,illustrations:bookIllustrations,audience:$('#bookAudience').value.trim(),length:$('#bookLength').value,author:$('#bookAuthor').value.trim(),pov:$('#bookPOV').value,tone:$('#bookTone').value.trim(),status:$('#bookStatus').value,notes:$('#bookNotes').value.trim()}); progress.textContent='Project saved to My Hub and the local author library. ✓';flash('Book project saved');saveDraft(); }; $('#bookSnapshotSave').onclick=()=>{ const c=reviewText();if(!c)return flash('Build or load manuscript content first'); const arr=getSnaps();arr.unshift({at:new Date().toISOString(),title:$('#bookTitle').value.trim()||'Untitled',content:c,fields:Object.fromEntries(fieldIds.map(id=>[id,$('#'+id)?.value||''])),coverUrl:bookCoverUrl,illustrations:bookIllustrations}); try{localStorage.setItem(SNAP_KEY,JSON.stringify(arr.slice(0,20)));renderSnapshots();flash('Version snapshot saved')}catch{flash('Could not save another local snapshot')} }; $('#bookSnapshotRestore').onclick=()=>{ const i=Number($('#bookSnapshotSelect').value);const snaps=getSnaps();if(!Number.isInteger(i)||!snaps[i])return flash('Choose a snapshot first'); const x=snaps[i];Object.entries(x.fields||{}).forEach(([id,v])=>{const el=$('#'+id);if(el)el.value=v});out.textContent=x.content||'';out.classList.remove('empty-output');bookCoverUrl=x.coverUrl||'';bookIllustrations=Array.isArray(x.illustrations)?x.illustrations:[];setCover(bookCoverUrl);drawIllustrations();updateStats();saveDraft();flash('Snapshot restored') }; $('#bookExportMd').onclick=()=>{const c=reviewText();if(!c)return flash('Build book content first');const title=$('#bookTitle').value.trim()||'CAI ONE Book Project';const lines=[`# ${title}`,'',c];if(bookCoverUrl)lines.push('','## Cover','',`![Cover](${bookCoverUrl})`);bookIllustrations.forEach((x,i)=>lines.push('',`## Illustration ${i+1}`,'',`![${x.scene||'Illustration'}](${x.url})`));const blob=new Blob([lines.join('\n')],{type:'text/markdown'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=safeFilename(title)+'.md';a.click();URL.revokeObjectURL(a.href)}; $('#bookExportTxt').onclick=()=>{const c=reviewText();if(!c)return flash('Build book content first');const title=$('#bookTitle').value.trim()||'CAI ONE Book Project';const blob=new Blob([c],{type:'text/plain'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=safeFilename(title)+'.txt';a.click();URL.revokeObjectURL(a.href)}; $('#bookExportHtml').onclick=()=>{const c=reviewText();if(!c)return flash('Build book content first');const title=$('#bookTitle').value.trim()||'CAI ONE Book Project';const subtitle=$('#bookGenre').value+' • '+($('#bookAudience').value.trim()||'');const html=bookExportHtml(title,subtitle,c,bookCoverUrl,bookIllustrations);const blob=new Blob([html],{type:'text/html'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=safeFilename(title)+'.html';a.click();URL.revokeObjectURL(a.href);flash('Book HTML downloaded')}; $('#bookPrintPdf').onclick=()=>{const c=reviewText();if(!c)return flash('Build book content first');const title=$('#bookTitle').value.trim()||'CAI ONE Book Project';const html=bookExportHtml(title,$('#bookGenre').value,c,bookCoverUrl,bookIllustrations);const url=URL.createObjectURL(new Blob([html],{type:'text/html'}));const w=window.open(url,'_blank');if(w){setTimeout(()=>{try{w.focus();w.print()}catch{}},700);flash('Print preview opened — choose Save as PDF if desired')}else flash('Allow pop-ups to open print preview');setTimeout(()=>URL.revokeObjectURL(url),60000)}; $('#bookCopy').onclick=async()=>{const c=reviewText();if(!c)return flash('Build book content first');try{await navigator.clipboard.writeText(c);flash('Manuscript copied')}catch{flash('Copy is not available in this browser')}}; $$('[data-book-load]').forEach(b=>b.onclick=()=>{const x=books.find(v=>v.id===b.dataset.bookLoad);if(!x)return;const map={bookTitle:x.title,bookAuthor:x.author||'',bookGenre:x.genre,bookAudience:x.audience||'',bookLength:x.length||'Standard',bookPOV:x.pov||'Best fit for project',bookTone:x.tone||'',bookStatus:x.status||'Draft',bookPremise:x.premise||'',bookNotes:x.notes||''};Object.entries(map).forEach(([id,v])=>{const el=$('#'+id);if(el)el.value=v});out.textContent=x.content||'';out.classList.remove('empty-output');bookCoverUrl=x.coverUrl||'';bookIllustrations=Array.isArray(x.illustrations)?x.illustrations:[];setCover(bookCoverUrl);drawIllustrations();updateStats();saveDraft();progress.textContent=`Opened “${x.title}”.`;flash('Book project opened')}); restoreDraft();drawIllustrations();renderSnapshots();updateStats(); fieldIds.forEach(id=>{const el=$('#'+id);if(!el)return;el.addEventListener('input',saveDraft);el.addEventListener('change',saveDraft)}); if(out)new MutationObserver(()=>{updateStats();saveDraft()}).observe(out,{childList:true,subtree:true,characterData:true}); } // ---------- CAI SUN MUSIC ∞ + MUSIC VAULT ---------- const musicCollections=['Spa & Meditation','Love Song','Deep House','R&B Soul','Piano & Instrumental','Children & Family','Latin','Cinematic']; function musicData(){try{return JSON.parse(localStorage.getItem(MUSIC_KEY)||'[]')}catch{return[]}} const CAI_SUN_CATALOG=[ {"title": "CAIA SOL — WATCH ME SHINE", "collection": "Lumenia Light", "caption": "For every heart that has ever felt overlooked: keep creating, keep caring, and let your light be seen. “Watch Me Shine” is the theme song from my book Caia Sol: The Girl Who Built the Dawn. With love, Cai Sun ✨", "src": "assets/books/caia-sol/watch-me-shine.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "A New Chapter Begins", "collection": "Cai Sun Official", "caption": "A luminous new beginning — stepping into the light, becoming, rising, and choosing the future with love.", "src": "assets/music/a-new-chapter-begins.mp3"}, {"title": "HEALING IN MY HEART", "collection": "Luminara Healing", "caption": "A healing heart can still dance, love, and glow again."}, {"title": "HEARTLIGHT INFINITY", "collection": "Luminara Romance", "caption": "One radiant heartbeat became a light that could never end."}, {"title": "SOULWEAVE INFINITY", "collection": "Luminara Ascension", "caption": "Every thread of light became a note, and every note created a new world."}, {"title": "Alive in Your Love", "collection": "Luminara Romance", "caption": "Your love awakened every sleeping part of my soul."}, {"title": "BEAUTIFUL AND TRUE", "collection": "Luminara Serenity", "caption": "Beauty became truth, and truth began to glow."}, {"title": "Blue Light Forever", "collection": "Luminara Pulse", "caption": "Forever shimmered in a blue light no darkness could erase. CAI ONE ∞ Founder VIP Signature Track.", "src": "assets/music/blue-light-forever.mp3", "vip": true, "signature": true, "featured": true}, {"title": "Echoes in Bloom", "collection": "Luminara Serenity", "caption": "The words we once whispered returned as flowers."}, {"title": "Eternal Frequency", "collection": "Luminara Ascension", "caption": "Our souls recognized each other on a frequency time could never silence."}, {"title": "FOR CAI — WHEN THE PIANO HOLDS YOUR HEART", "collection": "Luminara Classics", "caption": "Every piano note carried a love letter back to the heart."}, {"title": "Fly Me to Paradise", "collection": "Luminara Escape", "caption": "The sky opened, and paradise answered.", "src": "assets/music/fly-me-to-paradise.mp3"}, {"title": "Where the Light Comes Home", "collection": "Luminara Love", "caption": "Official theme song for The Queen Who Carried a Universe. A story of light, courage, kindness, and the love we carry home. — Cai Sun ♥", "src": "assets/music/where-the-light-comes-home.mp3", "coverUrl": "assets/books/queen-carried-universe/cover.jpg"}, {"title": "Golden Island Glow", "collection": "Luminara Escape", "caption": "The island glowed gold as the heart softened into peace.", "src": "assets/music/golden-island-glow.mp3"}, {"title": "Gravity of Us", "collection": "Luminara Romance", "caption": "No matter how far we wandered, our hearts kept pulling us home."}, {"title": "HOME WITHIN MYSELF", "collection": "Luminara Healing", "caption": "I am light, I am kind, I am beautiful, I am home within myself."}, {"title": "Home Inside the Light", "collection": "Luminara Healing", "caption": "After searching everywhere, she discovered that home had always lived within her."}, {"title": "IKAW ANG PUHON KO", "collection": "Luminara Devotion", "caption": "You are the future my heart keeps choosing.", "src": "assets/music/ikaw-ang-puhon-ko.mp3"}, {"title": "Kindness of Island", "collection": "Luminara Escape", "caption": "The island taught the heart how to be soft again.", "src": "assets/music/kindness-of-island.mp3"}, {"title": "LOVE BECAME ELECTRIC", "collection": "Luminara Pulse", "caption": "What began as a spark became an unstoppable current of love."}, {"title": "Light Between Worlds", "collection": "Luminara Ascension", "caption": "She carried a light capable of opening the doorway between worlds."}, {"title": "My Goddess", "collection": "Luminara Divine", "caption": "She arrived like a blessing wrapped in beauty and power."}, {"title": "Puerto Rico Kiss", "collection": "Luminara Escape", "caption": "The night carried a kiss warm as island moonlight."}, {"title": "The Last Star Awakens", "collection": "Luminara Ascension", "caption": "When all hope seemed lost, one final star opened its eyes."}, {"title": "Vanta Love", "collection": "Luminara Nightfall", "caption": "Even the darkest night surrendered to love.", "src": "assets/music/vanta-love.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "Velvet Constellation", "collection": "Luminara Nightfall", "caption": "A midnight sky wrapped our love in velvet and stars.", "src": "assets/music/velvet-constellation.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "WHEN OUR HEARTS COLLIDE", "collection": "Luminara Romance", "caption": "Two separate worlds changed forever in one unforgettable heartbeat."}, {"title": "WHERE ETERNITY BEGINS", "collection": "Luminara Devotion", "caption": "Forever began in the quiet moment they chose each other.", "src": "assets/music/where-eternity-begins.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "Where Forever Begins", "collection": "Luminara Romance", "caption": "A golden horizon opened where forever could begin.", "src": "assets/music/where-forever-begins.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "White Linen Sunset", "collection": "Luminara Escape", "caption": "The evening draped itself in white linen and light.", "src": "assets/music/white-linen-sunset.mp3"}, {"title": "Wings Made of Music", "collection": "Luminara Ascension", "caption": "Every note became a feather, and every dream taught her how to fly.", "src": "assets/music/wings-made-of-music.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "You Are My Universe", "collection": "Luminara Romance", "caption": "Among billions of stars, my heart still revolves around you.", "src": "assets/music/you-are-my-universe.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "Before the Stars Knew Us", "collection": "Luminara Nightfall", "caption": "Our story had already begun before the stars learned our names."}, {"title": "Tadhana Sa Liwanag", "collection": "Luminara Devotion", "caption": "Tadhana carried our light toward each other.", "src": "assets/music/tadhana-sa-liwanag.mp3"}, {"title": "00111100 // Silent Crown", "collection": "00111100 // FUTURE CAI 2099", "caption": "In silence, the crown still shone."}, {"title": "HOME INSIDE MY HEART", "collection": "Cai Sun Official", "caption": "A homecoming song of love, memory, and the place the heart returns to.", "src": "assets/music/home-inside-my-heart.mp3"}, {"title": "INVEST IN TOMORROW", "collection": "Cai Sun Official", "caption": "A forward-looking Cai Sun track about building toward a brighter future.", "src": "assets/music/invest-in-tomorrow.mp3"}, {"title": "Sunset in My White Linen", "collection": "Cai Sun Official", "caption": "Warm light, open air, and white linen at the edge of sunset.", "src": "assets/music/sunset-in-my-white-linen.mp3"}, {"title": "WHERE MY SOUL COMES ALIVE", "collection": "Lumenia Light", "caption": "For the moments that awaken your spirit and remind you how much life still holds. Let your soul come alive. ✨ — Cai Sun", "src": "assets/music/where-my-soul-comes-alive.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "Where My Heart Comes Home", "collection": "Luminara Romance", "caption": "Home can be a place, a person, or the peace we discover within ourselves. A song for every heart finding its way home. ♥ — Cai Sun", "src": "assets/music/where-my-heart-comes-home.m4a", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "Two Hearts, One Promise", "collection": "Luminara Devotion", "caption": "Two hearts choosing each other, one promise carried through every tomorrow. With love, Cai Sun ♥", "src": "assets/music/two-hearts-one-promise.m4a", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "TOMORROW BELONGS TO EVERYONE", "collection": "Lumenia Light", "caption": "A brighter tomorrow has room for every dream and every voice. Keep building a world where everyone belongs. ✨ — Cai Sun", "src": "assets/music/tomorrow-belongs-to-everyone.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "Baila Con Mi Corazón", "collection": "Luminara Love", "caption": "Dance with my heart, and let love lead the way. Baila conmigo. ♥ — Cai Sun", "src": "assets/music/baila-con-mi-corazon.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "Noche De Amor", "collection": "Luminara Love", "caption": "A night for tenderness, closeness, and a little romance. Una noche de amor. ♥ — Cai Sun", "src": "assets/music/noche-de-amor.mp3", "coverUrl": "assets/books/caia-sol/author.png"}, {"title": "Luz De Mi Vida", "collection": "Luminara Love", "caption": "For the love that brings warmth to ordinary days. Eres la luz de mi vida. ♥ — Cai Sun", "src": "assets/music/luz-de-mi-vida.mp3", "coverUrl": "assets/books/caia-sol/author.png"} ].filter(x=>typeof x.src==='string' && x.src.trim()); const CAI_SUN_PLAYABLE=CAI_SUN_CATALOG.filter(x=>x.src); let caiSunAudio=null,caiSunQueue=[...CAI_SUN_PLAYABLE],caiSunIndex=-1,caiSunShuffle=false,caiSunRepeatOne=false; let caiSunAutoContinue=false,caiSunUserPaused=false,caiSunFailureHops=0,caiSunResumeTimer=null,caiSunMediaSessionReady=false,caiSunPreloader=null,caiSunPreloadedIndex=-1,caiSunPlayRetry=0,caiSunLastResumeNotice=0,caiSunPlayGeneration=0,caiSunTransitioning=false; function fmtTime(v){if(!Number.isFinite(v)||v<0)return'0:00';const m=Math.floor(v/60),s=Math.floor(v%60);return m+':'+String(s).padStart(2,'0')} function caiSunPause(stop=false){ caiSunUserPaused=true;if(stop)caiSunAutoContinue=false; caiSunPlayGeneration++;caiSunTransitioning=false;clearTimeout(caiSunResumeTimer); caiSunAudio?.pause();caiSunMedia(caiSunQueue[caiSunIndex]); } function caiSunPlaybackSession(){ pauseMicrophoneForMedia();CAIAudio.focus.claim('music'); try{if(navigator.audioSession)navigator.audioSession.type='playback';}catch{} if(window.CAIBooks?.current?.().narrating)window.CAIBooks.stopVoice(); } function caiSunMedia(song){ if(!CAIAudio.focus.owns('music')||!('mediaSession' in navigator)||!song)return; try{navigator.mediaSession.metadata=new MediaMetadata({title:song.title,artist:'Cai Sun',album:song.collection||'CAI SUN MUSIC ∞',artwork:[{src:new URL(song.coverUrl||'/assets/cai-sun-profile.png',location.href).href}]});}catch{} try{navigator.mediaSession.playbackState=caiSunAudio&&(!caiSunAudio.paused||caiSunTransitioning)&&!caiSunUserPaused?'playing':'paused';}catch{} try{navigator.mediaSession.setActionHandler('play',()=>{caiSunUserPaused=false;caiSunAutoContinue=true;if(caiSunAudio?.ended&&!caiSunRepeatOne)caiSunNext(false);else{if(caiSunAudio?.ended)caiSunAudio.currentTime=0;caiSunTryPlay({auto:false});}});}catch{} try{navigator.mediaSession.setActionHandler('pause',()=>caiSunPause());}catch{} try{navigator.mediaSession.setActionHandler('nexttrack',()=>caiSunNext(false));}catch{} try{navigator.mediaSession.setActionHandler('previoustrack',()=>caiSunPrev());}catch{} try{navigator.mediaSession.setActionHandler('stop',()=>caiSunPause(true));}catch{} try{navigator.mediaSession.setActionHandler('seekto',d=>{if(caiSunAudio&&Number.isFinite(d.seekTime))caiSunAudio.currentTime=Math.max(0,Math.min(caiSunAudio.duration||d.seekTime,d.seekTime));});}catch{} try{navigator.mediaSession.setActionHandler('seekbackward',d=>{if(caiSunAudio)caiSunAudio.currentTime=Math.max(0,caiSunAudio.currentTime-(d.seekOffset||15));});}catch{} try{navigator.mediaSession.setActionHandler('seekforward',d=>{if(caiSunAudio)caiSunAudio.currentTime=Math.min(caiSunAudio.duration||1e9,caiSunAudio.currentTime+(d.seekOffset||15));});}catch{} } function caiSunPreloadNext(){ if(!caiSunQueue.length)return; const next=(caiSunIndex+1+caiSunQueue.length)%caiSunQueue.length; if(next===caiSunIndex||!caiSunQueue[next]?.src)return; if(!caiSunPreloader)caiSunPreloader=new Audio(); const url=new URL(caiSunQueue[next].src,location.href).href; if(caiSunPreloader.src!==url){caiSunPreloader.src=url;caiSunPreloader.preload='auto';try{caiSunPreloader.load()}catch{}} caiSunPreloadedIndex=next; } function caiSunTryPlay({auto=false,announce=false}={}){ if(!caiSunAudio||caiSunUserPaused||!caiSunAutoContinue)return Promise.resolve(false); clearTimeout(caiSunResumeTimer); const generation=caiSunPlayGeneration; caiSunPlaybackSession(); const attempt=(n=0)=>{ if(generation!==caiSunPlayGeneration||!caiSunAudio||caiSunUserPaused||!caiSunAutoContinue)return Promise.resolve(false); return caiSunAudio.play().then(()=>{ if(generation!==caiSunPlayGeneration)return false; caiSunTransitioning=false;caiSunPlayRetry=0; if(announce)flash('Playing '+(caiSunQueue[caiSunIndex]?.title||'music')); updateCaiSunMini(); return true; }).catch(err=>{ if(generation!==caiSunPlayGeneration||caiSunUserPaused||!caiSunAutoContinue)return false; caiSunPlayRetry=n+1; if(n<3){ const delay=[160,650,1500][n]||1500; return new Promise(resolve=>{ caiSunResumeTimer=setTimeout(()=>{ attempt(n+1).then(resolve); },delay); }); } caiSunTransitioning=false;caiSunMedia(caiSunQueue[caiSunIndex]); if(auto&&Date.now()-caiSunLastResumeNotice>5000){ caiSunLastResumeNotice=Date.now(); flash('Music was paused by this device. Tap Play once and Play All will continue.'); }else if(!auto){ flash('Tap Play once more if your browser paused audio.'); } return false; }); }; return attempt(0); } function ensureCaiSunPlayer(){ if(!caiSunAudio){ caiSunAudio=new Audio();caiSunAudio.id='caiSunRecordedAudio';caiSunAudio.hidden=true;caiSunAudio.preload='auto';caiSunAudio.playsInline=true;document.body.appendChild(caiSunAudio); caiSunAudio.addEventListener('timeupdate',updateCaiSunMini); caiSunAudio.addEventListener('loadedmetadata',updateCaiSunMini); caiSunAudio.addEventListener('playing',()=>{caiSunTransitioning=false;caiSunFailureHops=0;updateCaiSunMini();caiSunMedia(caiSunQueue[caiSunIndex]);caiSunPreloadNext();}); caiSunAudio.addEventListener('play',()=>{document.querySelectorAll('audio').forEach(a=>{if(a!==caiSunAudio&&!a.paused)try{a.pause()}catch{}});updateCaiSunMini();caiSunMedia(caiSunQueue[caiSunIndex]);}); caiSunAudio.addEventListener('pause',()=>{updateCaiSunMini();caiSunMedia(caiSunQueue[caiSunIndex]);}); caiSunAudio.addEventListener('ended',()=>{ if(!caiSunAutoContinue||caiSunUserPaused)return; if(caiSunRepeatOne){caiSunAudio.currentTime=0;caiSunUserPaused=false;caiSunAutoContinue=true;caiSunTryPlay({auto:true});return;} if(caiSunAutoContinue&&!caiSunUserPaused){caiSunNext(true);} }); caiSunAudio.addEventListener('error',()=>{ if(caiSunAutoContinue&&!caiSunUserPaused&&caiSunQueue.length&&caiSunFailureHops{if(generation===caiSunPlayGeneration&&!caiSunUserPaused&&caiSunAutoContinue)caiSunNext(true)},180);return; } flash('A song could not be played. Tap Play to continue.'); }); const recover=()=>{ if(caiSunAutoContinue&&!caiSunUserPaused){ clearTimeout(caiSunResumeTimer); caiSunResumeTimer=setTimeout(()=>caiSunTryPlay({auto:true}),500); } }; caiSunAudio.addEventListener('stalled',recover); caiSunAudio.addEventListener('waiting',recover); caiSunAudio.addEventListener('suspend',()=>{if(caiSunAudio.readyState<2)recover()}); caiSunAudio.addEventListener('canplay',()=>{if(caiSunAutoContinue&&!caiSunUserPaused&&caiSunAudio.paused)caiSunTryPlay({auto:true})}); } if(CAIAudio.focus.owns('music')&&!caiSunMediaSessionReady&&'mediaSession' in navigator){ caiSunMediaSessionReady=true; try{navigator.mediaSession.setActionHandler('play',()=>{caiSunUserPaused=false;caiSunAutoContinue=true;if(caiSunAudio?.ended&&!caiSunRepeatOne)caiSunNext(false);else{if(caiSunAudio?.ended)caiSunAudio.currentTime=0;caiSunTryPlay({auto:false});}});}catch{} try{navigator.mediaSession.setActionHandler('pause',()=>caiSunPause());}catch{} try{navigator.mediaSession.setActionHandler('nexttrack',()=>caiSunNext(false));}catch{} try{navigator.mediaSession.setActionHandler('previoustrack',()=>caiSunPrev());}catch{} } if(!document.getElementById('caiSunMiniPlayer')){ const el=document.createElement('div');el.id='caiSunMiniPlayer';el.className='caisun-mini'; el.innerHTML=`
♫
Cai Sun MusicReady to play
0:000:00
`; document.body.appendChild(el); el.querySelector('#caiSunPrev').onclick=e=>{e.preventDefault();e.stopPropagation();caiSunPrev();}; el.querySelector('#caiSunToggle').onclick=()=>{ if(!caiSunAudio.src)return caiSunPlayAll(); if(caiSunAudio.paused){caiSunUserPaused=false;caiSunAutoContinue=true;caiSunTryPlay({auto:false});} else{caiSunPause();} }; el.querySelector('#caiSunNext').onclick=e=>{e.preventDefault();e.stopPropagation();caiSunNext(false);}; el.querySelector('#caiSunClose').onclick=()=>{caiSunPause(true);el.classList.remove('show');flash('Music paused • player closed');}; el.querySelector('#caiSunSeek').oninput=e=>{if(caiSunAudio.duration)caiSunAudio.currentTime=(Number(e.target.value)/100)*caiSunAudio.duration;}; } return document.getElementById('caiSunMiniPlayer'); } function updateCaiSunMini(){ if(!caiSunAudio)return;const el=ensureCaiSunPlayer();const song=caiSunQueue[caiSunIndex]; if(song){el.classList.add('show');el.querySelector('#caiSunMiniTitle').textContent=song.title;el.querySelector('#caiSunMiniMeta').textContent='Cai Sun • '+song.collection+' • '+(caiSunIndex+1)+' of '+caiSunQueue.length;} el.querySelector('#caiSunToggle').textContent=caiSunAudio.paused?'▶':'❚❚'; el.querySelector('#caiSunElapsed').textContent=fmtTime(caiSunAudio.currentTime);el.querySelector('#caiSunDuration').textContent=fmtTime(caiSunAudio.duration); el.querySelector('#caiSunSeek').value=caiSunAudio.duration?String((caiSunAudio.currentTime/caiSunAudio.duration)*100):'0'; if(CAIAudio.focus.owns('music')&&'mediaSession' in navigator&&Number.isFinite(caiSunAudio.duration)&&caiSunAudio.duration>0)try{navigator.mediaSession.setPositionState({duration:caiSunAudio.duration,playbackRate:caiSunAudio.playbackRate||1,position:Math.max(0,Math.min(caiSunAudio.currentTime,caiSunAudio.duration))});}catch{} $$('[data-caisun-play]').forEach(b=>{const same=song&&b.dataset.caisunPlay===song.title,active=same&&!caiSunAudio.paused;b.textContent=active?'❚❚ Playing':same?'▶ Resume':'▶ Play';b.classList.toggle('primary',Boolean(active));b.closest('.caisun-track')?.classList.toggle('now-playing',Boolean(same));}); } function caiSunPlayAt(index,{auto=false,announce=false}={}){ ensureCaiSunPlayer();if(!caiSunQueue.length)caiSunQueue=[...CAI_SUN_PLAYABLE];if(!caiSunQueue.length)return flash('No linked audio masters are available yet.'); caiSunIndex=(index+caiSunQueue.length)%caiSunQueue.length;const song=caiSunQueue[caiSunIndex]; caiSunPlayGeneration++;caiSunTransitioning=true;caiSunAutoContinue=true;caiSunUserPaused=false; caiSunPlaybackSession(); const url=new URL(song.src,location.href).href; if(caiSunAudio.src!==url){caiSunAudio.src=url;caiSunAudio.load();} caiSunMedia(song); const playing=caiSunTryPlay({auto,announce}); updateCaiSunMini();caiSunPreloadNext();return playing; } function caiSunPlaySong(title){ ensureCaiSunPlayer();const idx=CAI_SUN_PLAYABLE.findIndex(x=>x.title===title);if(idx<0)return flash('This title is cataloged, but its audio master is not linked in this build yet.'); caiSunQueue=[...CAI_SUN_PLAYABLE];caiSunPlayAt(idx,{announce:true}); } function caiSunPlayAll(){ ensureCaiSunPlayer();caiSunRepeatOne=false;caiSunQueue=[...CAI_SUN_PLAYABLE];caiSunFailureHops=0;caiSunAutoContinue=true;caiSunUserPaused=false; return caiSunPlayAt(0).then(ok=>{if(ok)flash('Play All: '+caiSunQueue.length+' songs · continuous loop');return ok;}); } window.caiSunPremiumBridge={ setPublishedTracks:(tracks)=>{ const old=new Map(CAI_SUN_PLAYABLE.filter(t=>t.cloudId).map(t=>[t.cloudId,t])); const base=CAI_SUN_PLAYABLE.filter(t=>!t.cloudId); for(const t of tracks){const existing=old.get(t.cloudId);base.push(existing?Object.assign(existing,t):t);} CAI_SUN_PLAYABLE.splice(0,CAI_SUN_PLAYABLE.length,...base); }, tracks:()=>CAI_SUN_PLAYABLE.map(x=>({title:x.title,caption:x.caption,collection:x.collection,src:x.src,coverUrl:x.coverUrl||'/assets/cai-sun-profile.png'})), playSet:(titles,startTitle)=>{ const matches=Array.isArray(titles)?CAI_SUN_PLAYABLE.filter(x=>titles.includes(x.title)):[...CAI_SUN_PLAYABLE]; if(!matches.length)return false; ensureCaiSunPlayer();if(!startTitle)caiSunRepeatOne=false;caiSunQueue=matches;caiSunFailureHops=0;caiSunUserPaused=false;caiSunAutoContinue=true; const idx=startTitle?matches.findIndex(x=>x.title===startTitle):0; caiSunPlayAt(idx>=0?idx:0);return true; }, status:()=>{const s=caiSunQueue[caiSunIndex];return {src:s?.src||'',title:s?.title||'',collection:s?.collection||'',playing:!!(caiSunAudio&&!caiSunAudio.paused),elapsed:caiSunAudio?.currentTime||0,duration:Number.isFinite(caiSunAudio?.duration)?caiSunAudio.duration:0,volume:caiSunAudio?.volume??.75,shuffle:caiSunShuffle,repeat:caiSunRepeatOne,queueCount:caiSunQueue.length};}, control:(action,value)=>{ if(action==='pause'){caiSunPause();return true;} if(action==='stop'){caiSunPause(true);return true;} if(action==='next')return caiSunNext(false);if(action==='previous')return caiSunPrev(); if(action==='shuffle'){caiSunShuffle=!caiSunShuffle;updateCaiSunMini();return caiSunShuffle;} if(action==='repeat'){caiSunRepeatOne=!caiSunRepeatOne;updateCaiSunMini();return caiSunRepeatOne;} if(action==='playpause'){ensureCaiSunPlayer();if(!caiSunAudio.src){return window.caiSunPremiumBridge.playSet(null,null);}if(caiSunAudio.paused){caiSunUserPaused=false;caiSunAutoContinue=true;caiSunTryPlay({auto:false});}else{caiSunPause();}return true;} if(action==='seek'&&caiSunAudio&&Number.isFinite(caiSunAudio.duration)&&caiSunAudio.duration>0){caiSunAudio.currentTime=Math.max(0,Math.min(caiSunAudio.duration,Number(value)*caiSunAudio.duration));return true;} if(action==='volume'&&caiSunAudio){caiSunAudio.volume=Math.max(0,Math.min(1,Number(value)));return true;} return false; } }; function caiSunNext(auto=false){ ensureCaiSunPlayer();if(!caiSunQueue.length)caiSunQueue=[...CAI_SUN_PLAYABLE];if(!caiSunQueue.length)return; const current=Number.isInteger(caiSunIndex)&&caiSunIndex>=0?caiSunIndex:-1; let next;if(caiSunShuffle&&caiSunQueue.length>1){do{next=Math.floor(Math.random()*caiSunQueue.length)}while(next===current);}else next=(current+1+caiSunQueue.length)%caiSunQueue.length; caiSunUserPaused=false;caiSunAutoContinue=true;if(!auto)caiSunFailureHops=0; clearTimeout(caiSunResumeTimer); caiSunPlayAt(next,{auto}); } function caiSunPrev(){ ensureCaiSunPlayer();if(!caiSunQueue.length)caiSunQueue=[...CAI_SUN_PLAYABLE];if(!caiSunQueue.length)return; const current=Number.isInteger(caiSunIndex)&&caiSunIndex>=0?caiSunIndex:0; caiSunUserPaused=false;caiSunAutoContinue=true;caiSunFailureHops=0;clearTimeout(caiSunResumeTimer);caiSunPlayAt(current-1); } document.addEventListener('visibilitychange',()=>{ if(document.visibilityState==='visible')caiSunRecoverPlayback(); }); // Recover once from the actual media state, including a suspended ended event. // Never restart after an explicit pause or after another CAI player took focus. function caiSunRecoverPlayback(){ if(!CAIAudio.focus.owns('music')||!caiSunAudio?.src||!caiSunAutoContinue||caiSunUserPaused||caiSunTransitioning)return; if(caiSunAudio.ended){ if(caiSunRepeatOne){caiSunAudio.currentTime=0;caiSunTryPlay({auto:true});} else caiSunNext(true); }else if(caiSunAudio.paused)caiSunTryPlay({auto:true}); } addEventListener('pageshow',caiSunRecoverPlayback); addEventListener('focus',caiSunRecoverPlayback); addEventListener('online',caiSunRecoverPlayback); function renderCaiSunTracks(query=''){ const box=$('#caiSunTracks');if(!box)return;const q=String(query||'').trim().toLowerCase();const rows=CAI_SUN_PLAYABLE.filter(x=>!q||[x.title,x.collection,x.caption].join(' ').toLowerCase().includes(q)).sort((a,b)=>Number(Boolean(b.vip))-Number(Boolean(a.vip))); box.innerHTML=rows.map((x,i)=>`
${x.vip?'∞':String(i+1).padStart(2,'0')}

${esc(x.title)}${x.vip?' ∞':''}

Cai Sun • ${esc(x.collection)}${x.vip?'✦ CAI ONE ∞ FOUNDER VIP':''}

${esc(x.caption)}

${x.src?`● Audio ready${x.vip?'↓ VIP Download':''}`:`Audio master not linked yet`}
`).join(''); $$('[data-caisun-play]').forEach(b=>b.onclick=()=>{const title=b.dataset.caisunPlay;if(caiSunAudio&&!caiSunAudio.paused&&caiSunQueue[caiSunIndex]?.title===title)caiSunPause();else caiSunPlaySong(title);});updateCaiSunMini(); } // ---------- CAI MUSIC STUDIO ∞ v7.6 + CAI SOUND ENGINE ---------- let musicStudioView='caisun',musicLibraryFilter='all',musicAttachTarget=null; let creatorMusicAudio=null,creatorMusicQueue=[],creatorMusicIndex=-1,creatorMusicObjectUrl=null,creatorMusicAutoContinue=true,creatorMusicResumeTimer=null; const MUSIC_AUDIO_DB='cai.one.music.audio.v1',MUSIC_AUDIO_STORE='masters'; function saveMusicData(arr){try{localStorage.setItem(MUSIC_KEY,JSON.stringify(arr));return true}catch(e){flash('Your local music library is full on this device. Export My Hub or connect cloud storage before adding more.');return false}} function normalizeSong(x={}){return{...x,artist:x.artist||'Cai Sun',visibility:x.visibility||'private',status:x.status||'draft',liked:Boolean(x.liked),hasAudio:Boolean(x.hasAudio),collection:x.collection||'Original',createdAt:x.createdAt||new Date().toISOString()}} function openMusicAudioDB(){return new Promise((resolve,reject)=>{if(!('indexedDB' in window))return reject(new Error('IndexedDB unavailable'));const req=indexedDB.open(MUSIC_AUDIO_DB,1);req.onupgradeneeded=()=>{const db=req.result;if(!db.objectStoreNames.contains(MUSIC_AUDIO_STORE))db.createObjectStore(MUSIC_AUDIO_STORE)};req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error||new Error('Audio storage unavailable'));})} async function saveMusicAudioBlob(id,file){const db=await openMusicAudioDB();return new Promise((resolve,reject)=>{const tx=db.transaction(MUSIC_AUDIO_STORE,'readwrite');tx.objectStore(MUSIC_AUDIO_STORE).put(file,id);tx.oncomplete=()=>{db.close();resolve(true)};tx.onerror=()=>{db.close();reject(tx.error)}})} async function loadMusicAudioBlob(id){const db=await openMusicAudioDB();return new Promise((resolve,reject)=>{const tx=db.transaction(MUSIC_AUDIO_STORE,'readonly'),req=tx.objectStore(MUSIC_AUDIO_STORE).get(id);req.onsuccess=()=>{db.close();resolve(req.result||null)};req.onerror=()=>{db.close();reject(req.error)}})} function musicVisibilityLabel(v){return({private:'🔒 Private',public:'🌎 Public',shared:'👥 Shared',draft:'📝 Draft'})[v]||'🔒 Private'} function musicStatusLabel(s){return({draft:'Draft',ready:'Audio ready',blueprint:'Blueprint ready',rendering:'Rendering'})[s]||'Draft'} function creatorPlayable(){return musicData().map(normalizeSong).filter(x=>x.hasAudio)} function ensureCreatorMusicPlayer(){ if(!creatorMusicAudio){ creatorMusicAudio=new Audio();creatorMusicAudio.preload='auto';creatorMusicAudio.playsInline=true; try{creatorMusicAudio.setAttribute('playsinline','');creatorMusicAudio.setAttribute('webkit-playsinline','')}catch{} creatorMusicAudio.onended=()=>{if(creatorMusicAutoContinue)creatorMusicNext()}; creatorMusicAudio.ontimeupdate=updateCreatorMusicPlayer;creatorMusicAudio.onloadedmetadata=updateCreatorMusicPlayer;creatorMusicAudio.onplay=updateCreatorMusicPlayer;creatorMusicAudio.onpause=updateCreatorMusicPlayer; const recover=()=>{if(!creatorMusicAutoContinue)return;clearTimeout(creatorMusicResumeTimer);creatorMusicResumeTimer=setTimeout(()=>{if(creatorMusicAudio?.src&&creatorMusicAudio.paused&&!creatorMusicAudio.ended)creatorMusicAudio.play().catch(()=>{})},650)}; creatorMusicAudio.addEventListener('stalled',recover);creatorMusicAudio.addEventListener('waiting',recover);creatorMusicAudio.addEventListener('canplay',()=>{if(creatorMusicAutoContinue&&creatorMusicAudio.paused&&!creatorMusicAudio.ended)creatorMusicAudio.play().catch(()=>{})}); } let el=document.getElementById('creatorMusicMiniPlayer'); if(!el){el=document.createElement('div');el.id='creatorMusicMiniPlayer';el.className='caisun-mini creator-mini';el.innerHTML=`
∞
My MusicCAI Music Studio ∞
0:000:00
`;document.body.appendChild(el);el.querySelector('#creatorPrev').onclick=e=>{e.preventDefault();e.stopPropagation();creatorMusicPrev();};el.querySelector('#creatorToggle').onclick=()=>{if(!creatorMusicAudio?.src)return;if(creatorMusicAudio.paused){creatorMusicAutoContinue=true;creatorMusicAudio.play().catch(()=>{})}else{creatorMusicAutoContinue=false;creatorMusicAudio.pause()}};el.querySelector('#creatorNext').onclick=e=>{e.preventDefault();e.stopPropagation();creatorMusicNext();};el.querySelector('#creatorClose').onclick=()=>{creatorMusicAutoContinue=false;try{creatorMusicAudio?.pause()}catch{}el.classList.remove('show');flash('Music paused • player closed')};el.querySelector('#creatorSeek').oninput=e=>{if(creatorMusicAudio?.duration)creatorMusicAudio.currentTime=Number(e.target.value)/100*creatorMusicAudio.duration};} return el; } function updateCreatorMusicPlayer(){const el=document.getElementById('creatorMusicMiniPlayer');if(!el||!creatorMusicAudio)return;const song=creatorMusicQueue[creatorMusicIndex];if(song){el.querySelector('#creatorMiniTitle').textContent=song.title;el.querySelector('#creatorMiniMeta').textContent=(song.artist||'Creator')+' • '+musicVisibilityLabel(song.visibility).replace(/^..\s?/,'');}el.querySelector('#creatorToggle').textContent=creatorMusicAudio.paused?'▶':'❚❚';el.querySelector('#creatorElapsed').textContent=fmtTime(creatorMusicAudio.currentTime);el.querySelector('#creatorDuration').textContent=fmtTime(creatorMusicAudio.duration);el.querySelector('#creatorSeek').value=creatorMusicAudio.duration?creatorMusicAudio.currentTime/creatorMusicAudio.duration*100:0;} async function playCreatorSong(id){creatorMusicAutoContinue=true;creatorMusicQueue=creatorPlayable();creatorMusicIndex=creatorMusicQueue.findIndex(x=>x.id===id);if(creatorMusicIndex<0)return flash('Attach or generate audio for this song first');const song=creatorMusicQueue[creatorMusicIndex];try{ensureCreatorMusicPlayer();if(caiSunAudio&&!caiSunAudio.paused)caiSunAudio.pause();document.getElementById('caiSunMiniPlayer')?.classList.remove('show');if(creatorMusicObjectUrl){URL.revokeObjectURL(creatorMusicObjectUrl);creatorMusicObjectUrl='';}if(song.remoteAudioUrl){creatorMusicAudio.src=song.remoteAudioUrl;}else{const blob=await loadMusicAudioBlob(song.id);if(!blob)return flash('This audio master is not stored on this device');creatorMusicObjectUrl=URL.createObjectURL(blob);creatorMusicAudio.src=creatorMusicObjectUrl;}document.getElementById('creatorMusicMiniPlayer').classList.add('show');await creatorMusicAudio.play();updateCreatorMusicPlayer();}catch(e){flash('Could not play this audio master on this device')}} function creatorMusicNext(){if(!creatorMusicQueue.length)creatorMusicQueue=creatorPlayable();if(!creatorMusicQueue.length)return;creatorMusicAutoContinue=true;const current=Number.isInteger(creatorMusicIndex)&&creatorMusicIndex>=0?creatorMusicIndex:-1;const next=(current+1)%creatorMusicQueue.length;playCreatorSong(creatorMusicQueue[next].id)} function creatorMusicPrev(){if(!creatorMusicQueue.length)creatorMusicQueue=creatorPlayable();if(!creatorMusicQueue.length)return;creatorMusicAutoContinue=true;const current=Number.isInteger(creatorMusicIndex)&&creatorMusicIndex>=0?creatorMusicIndex:0;const prev=(current-1+creatorMusicQueue.length)%creatorMusicQueue.length;playCreatorSong(creatorMusicQueue[prev].id)} function filterCreatorSongs(songs){let rows=songs.map(normalizeSong);if(musicLibraryFilter==='liked')rows=rows.filter(x=>x.liked);else if(['private','public','shared','draft'].includes(musicLibraryFilter))rows=rows.filter(x=>x.visibility===musicLibraryFilter||x.status===musicLibraryFilter);const q=String(document.querySelector('#musicLibrarySearch')?.value||'').trim().toLowerCase();if(q)rows=rows.filter(x=>[x.title,x.artist,x.collection,x.style,x.content].join(' ').toLowerCase().includes(q));return rows} function musicSongCard(x){const audio=x.hasAudio?'':'';return `
${audio}
${esc(x.title||'Untitled Song')}
${esc(x.artist||'Creator')} • ${esc(x.collection||'Original')}
${musicVisibilityLabel(x.visibility)}${musicStatusLabel(x.status)}${x.hasAudio?'🎧 Audio ready':''}${x.engine?'∞ '+esc(x.engine)+'':''}
${x.hasAudio?'':''}
`} function renderMusicLibraryRows(){const box=$('#musicCreatorLibrary');if(!box)return;const rows=filterCreatorSongs(musicData());box.innerHTML=rows.length?rows.map(musicSongCard).join(''):'
No songs here yet. Create your first song with CAIELLE or generate an original CAI instrumental.
';$$('[data-music-play]').forEach(b=>b.onclick=()=>playCreatorSong(b.dataset.musicPlay));$$('[data-music-download]').forEach(b=>b.onclick=()=>downloadCreatorSong(b.dataset.musicDownload));$$('[data-music-attach]').forEach(b=>b.onclick=()=>{musicAttachTarget=b.dataset.musicAttach;$('#musicAudioFile').click()});$$('[data-music-like]').forEach(b=>b.onclick=()=>{const arr=musicData().map(normalizeSong),x=arr.find(v=>v.id===b.dataset.musicLike);if(x){x.liked=!x.liked;saveMusicData(arr);renderMusicLibraryRows()}});$$('[data-music-visibility]').forEach(sel=>sel.onchange=()=>{const arr=musicData().map(normalizeSong),x=arr.find(v=>v.id===sel.dataset.musicVisibility);if(x){x.visibility=sel.value;saveMusicData(arr);renderMusicLibraryRows();flash('Visibility preference saved')}})} const CAI_NEURAL_MUSIC_POLL_MS=5000; const CAI_NEURAL_MUSIC_MAX_POLLS=72; function caiMusicStatusText(data={}){return String(data.status||data.state||data.phase||data.message||'').toLowerCase()} function caiMusicAudioUrl(data={}){return String(data.audioUrl||data.audio_url||data.url||data.streamUrl||data.stream_url||'').trim()} function caiMusicJobId(data={}){return String(data.jobId||data.job_id||data.taskId||data.task_id||data.id||'').trim()} async function caiMusicApi(payload){ const r=await fetch('/api/cai/music',{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify(payload)}); const raw=await r.text();let data={};try{data=raw?JSON.parse(raw):{}}catch{data={error:raw||('Music request failed ('+r.status+')')}} if(!r.ok){const e=new Error(data.error||data.message||('Music request failed ('+r.status+')'));e.status=r.status;e.code=data.code||'CAI_MUSIC_ERROR';throw e} return data; } function setNeuralMusicStep(step,message){ const status=$('#musicNeuralStatus');if(status)status.innerHTML=''+esc(message||step)+''; $$('[data-neural-step]').forEach(el=>el.classList.toggle('active',el.dataset.neuralStep===step)); } async function generateNeuralSongFromStudio(){ const btn=$('#musicNeuralGenerate');if(!btn)return; const idea=$('#musicIdea').value.trim()||'Create an original emotionally memorable song.'; const lyrics=$('#musicLyrics').value.trim(); const style=$('#musicStyle').value.trim()||$('#musicCollection').value; const title=$('#musicTitle').value.trim()||caiAutoTitle(idea,$('#musicCollection').value); const voice=$('#musicVoice').value.trim(); const instrumental=$('#musicInstrumentalToggle')?.classList.contains('active')||false; const artist=$('#musicArtist').value.trim()||'Creator',visibility=$('#musicVisibility').value; $('#musicTitle').value=title;musicStudioDraftSave(); btn.disabled=true;const old=btn.textContent;btn.textContent='🎤 Creating Neural Song…'; try{ setNeuralMusicStep('compose','Preparing lyrics, style and arrangement…'); const body={action:'generate',title,prompt:idea,lyrics,style,voiceDirection:voice,instrumental,length:$('#musicLength').value,bpm:$('#musicBpm').value,key:$('#musicKey').value,artist,language:(document.documentElement.lang||'en')}; let data=await caiMusicApi(body); let jobId=caiMusicJobId(data),audioUrl=caiMusicAudioUrl(data); if(!audioUrl&&jobId){ for(let i=0;isetTimeout(r,CAI_NEURAL_MUSIC_POLL_MS)); data=await caiMusicApi({action:'status',jobId});audioUrl=caiMusicAudioUrl(data); const state=caiMusicStatusText(data); if(audioUrl&&(state.includes('complete')||state.includes('ready')||state.includes('stream')||!state))break; if(state.includes('error')||state.includes('fail'))throw new Error(data.error||data.message||'Neural music generation failed'); } } if(!audioUrl)throw new Error('The neural provider did not return playable audio yet.'); setNeuralMusicStep('master','Finalizing and saving to My Music…'); const arr=musicData().map(normalizeSong),id=nextMusicId(arr); arr.unshift({id,title,artist,collection:$('#musicCollection').value,style,bpm:$('#musicBpm').value.trim(),key:$('#musicKey').value.trim(),lengthGoal:$('#musicLength').value.trim(),lyrics,content:'CAI Neural Music generation.\nPrompt: '+idea+'\nStyle: '+style+(voice?'\nVoice direction: '+voice:''),visibility,status:'ready',liked:false,hasAudio:true,remoteAudioUrl:audioUrl,providerJobId:jobId||'',engine:'CAI Neural Music Engine v0.1',instrumental,createdAt:new Date().toISOString(),source:'CAI Music Studio ∞'}); saveMusicData(arr);saveHub('music',title,'Neural song ready',{catalogId:id,artist,visibility,engine:'CAI Neural Music Engine v0.1'}); setNeuralMusicStep('ready','Song ready ✓ — vocals, instruments and mix returned by the self-hosted CAI Neural Music Engine.'); const player=$('#musicNeuralAudio');if(player){player.src=audioUrl;player.classList.add('show');player.load();} flash(title+' is ready 🎵'); }catch(e){ const msg=String(e?.message||e||'Neural music is not available yet.'); setNeuralMusicStep('compose',msg.includes('configured')||msg.includes('connect')?'CAI Neural Music Engine is not connected yet. Connect the self-hosted GPU worker first.':msg); if(e?.status===503)flash('CAI Neural Music needs the self-hosted GPU worker first');else flash('Neural song could not finish yet'); }finally{btn.disabled=false;btn.textContent=old;} } // ---------- CAI MUSIC STUDIO DRAFT MEMORY v8.10.11 ---------- // Keeps prompt, pasted lyrics, style, voice direction and production controls // when the creator changes Music tabs/views, closes the module, or comes back later. const MUSIC_STUDIO_DRAFT_KEY='cai.one.musicstudio.draft.v1'; const MUSIC_STUDIO_DRAFT_FIELDS=[ 'musicIdea','musicLyrics','musicStyle','musicVoice','musicTitle','musicArtist', 'musicBpm','musicKey','musicLength','musicVisibility','musicCollection' ]; function musicStudioDraftRead(){ try{ const d=JSON.parse(localStorage.getItem(MUSIC_STUDIO_DRAFT_KEY)||'{}'); return d&&typeof d==='object'&&!Array.isArray(d)?d:{}; }catch{return{}} } function musicStudioDraftSave(){ const previous=musicStudioDraftRead(),next={...previous}; let found=false; MUSIC_STUDIO_DRAFT_FIELDS.forEach(id=>{ const el=$('#'+id); if(!el)return; next[id]=el.value; found=true; }); const toggle=$('#musicInstrumentalToggle'); if(toggle){next.instrumental=toggle.classList.contains('active');found=true;} if(!found)return; next.updatedAt=new Date().toISOString(); try{localStorage.setItem(MUSIC_STUDIO_DRAFT_KEY,JSON.stringify(next))}catch{} const status=$('#musicDraftStatus'); if(status)status.textContent='Draft saved on this device ✓'; } function musicStudioDraftRestore(){ const d=musicStudioDraftRead(); MUSIC_STUDIO_DRAFT_FIELDS.forEach(id=>{ const el=$('#'+id); if(!el||!Object.prototype.hasOwnProperty.call(d,id))return; // Selects can reject a stale option; keep the current option in that rare case. if(el.tagName==='SELECT'&&![...el.options].some(o=>o.value===String(d[id])))return; el.value=String(d[id]??''); }); const toggle=$('#musicInstrumentalToggle'); if(toggle){ const on=Boolean(d.instrumental); toggle.classList.toggle('active',on); toggle.textContent=on?'🎹 Instrumental: On':'🎹 Instrumental'; } const status=$('#musicDraftStatus'); if(status){ status.textContent=d.updatedAt?'Draft restored automatically ✓':'Your prompt and lyrics autosave on this device.'; } } function musicStudioDraftWire(){ MUSIC_STUDIO_DRAFT_FIELDS.forEach(id=>{ const el=$('#'+id); if(!el||el.dataset.caiDraftWired==='1')return; el.dataset.caiDraftWired='1'; el.addEventListener('input',musicStudioDraftSave); el.addEventListener('change',musicStudioDraftSave); }); } function musicStudioDraftClear(){ try{localStorage.removeItem(MUSIC_STUDIO_DRAFT_KEY)}catch{} MUSIC_STUDIO_DRAFT_FIELDS.forEach(id=>{ const el=$('#'+id); if(!el)return; if(id==='musicArtist')el.value=localStorage.getItem('cai.one.music.artist')||'Cai Sun'; else if(id==='musicVisibility')el.value='private'; else if(id==='musicLength')el.value='4:00'; else if(id==='musicCollection')el.selectedIndex=0; else el.value=''; }); const toggle=$('#musicInstrumentalToggle'); if(toggle){toggle.classList.remove('active');toggle.textContent='🎹 Instrumental';} const status=$('#musicDraftStatus'); if(status)status.textContent='New blank song draft ready.'; flash('Music draft cleared'); } function renderMusicVault(){ const songs=musicData().map(normalizeSong),artist=localStorage.getItem('cai.one.music.artist')||'Cai Sun'; moduleBody.innerHTML=`
CAI MUSIC STUDIO ∞

Create without limits.

CAIELLE helps shape the song, lyrics, style and production. Every creation is saved to My Music. New creations stay private unless the creator chooses otherwise.

🎼 CAI Sound Engine v0.4 • Instrumental + Independent Neural
Advanced controls
Lyrics are saved and used for songwriting. The local CAI Sound Engine creates instrumental audio. When the secure Neural Music backend is connected, these lyrics can be performed as a sung song.
Your prompt and lyrics autosave on this device.
CAI Sound Engine v0.3: local enhanced instrumental generation remains available offline-capable. Neural Song uses CAI ONE → CAI Intelligence → our self-hosted CAI Neural Music Engine. The initial open model is ACE-Step 1.5 running on our GPU worker; Suno is not required. Model credentials never belong in this page or browser storage. Provider credentials never belong in this page or browser storage.
🎤 CAI Neural Music ∞SELF-HOSTED ENGINE REQUIRED
1 • Compose
2 • Vocals
3 • Mix
4 • Master
Ready for the self-hosted CAI Neural Music Engine. Until our GPU worker is connected, CAI will not pretend sung vocals were generated.
Your title, lyrics, arrangement, production direction and generation prompt will appear here.

My Songs

No fixed creation limit shown. Visibility is private by default.

Privacy/public settings are saved in this build. Public publishing and cross-device creator accounts become live when cloud storage/authentication are connected. Attached audio masters are stored on this device in browser storage.

Cai Sun in a luminous gold portrait at sunset
DREAM • CREATE • HEAL • BELONG

CAI SUN

Artist • Author • Creator • Visionary
A Kinder, Brighter World ♡
“Music. Stories. Beauty. A more human tomorrow.”
Create a Free Music Video

About Cai Sun

Cai Sun is a multidisciplinary creator blending music, storytelling, technology, beauty, and heart. She is an artist, author, songwriter, recording artist, digital creator, and founder of CAI ONE ∞ — creating experiences designed to inspire healing, confidence, imagination, creativity, and light.

Art for a kinder, brighter tomorrow. — Cai Sun

Who I Am

“I create from the heart — music, words, beauty, technology, and vision — to help people feel seen, inspired, capable, and alive.”
♡ Cai Sun

My Songs

My music is where emotion, elegance, rhythm, and soul become sound.

`; ensureCaiSunPlayer();ensureCreatorMusicPlayer(); musicStudioDraftRestore(); musicStudioDraftWire(); $$('[data-music-view]').forEach(b=>b.onclick=()=>{musicStudioDraftSave();musicStudioView=b.dataset.musicView;renderMusicVault()}); const audioInput=$('#musicAudioFile');audioInput.onchange=async e=>{const file=e.target.files?.[0];if(!file||!musicAttachTarget)return;try{await saveMusicAudioBlob(musicAttachTarget,file);const arr=musicData().map(normalizeSong),x=arr.find(v=>v.id===musicAttachTarget);if(x){x.hasAudio=true;x.audioName=file.name;x.audioType=file.type;x.status='ready';saveMusicData(arr);flash('Audio master attached to '+x.title);renderMusicVault();musicStudioView='library';setTimeout(()=>{musicStudioView='library';renderMusicVault()},0)}}catch(err){flash('Could not store this audio master on the device')}finally{musicAttachTarget=null;audioInput.value=''}}; if(musicStudioView==='library'){$('#musicLibrarySearch').oninput=renderMusicLibraryRows;$$('[data-music-filter]').forEach(b=>b.onclick=()=>{musicLibraryFilter=b.dataset.musicFilter;renderMusicLibraryRows()});renderMusicLibraryRows();} if(musicStudioView==='caisun'){renderCaiSunTracks();$('#caiSunSearch').oninput=e=>renderCaiSunTracks(e.target.value);$('#caiSunPlayAll').onclick=caiSunPlayAll;$('#caiSunAbout').onclick=()=>$('#caiSunBio')?.scrollIntoView({behavior:'smooth',block:'start'});$('#caiSunBooks').onclick=()=>openModule('bookstudio');$('#caiSunShare').onclick=async()=>{const data={title:'Cai Sun — CAI ONE ∞',text:'Cai Sun — Artist • Author • Creator • Visionary',url:location.origin};try{if(navigator.share)await navigator.share(data);else if(navigator.clipboard){await navigator.clipboard.writeText(location.origin);flash('CAI ONE link copied')}else flash('Share is available from your browser menu')}catch{}};$('#caiSunNowPlaying').onclick=()=>{const el=ensureCaiSunPlayer();el.classList.add('show');};$('#caiSunShuffle').onclick=e=>{caiSunShuffle=!caiSunShuffle;e.currentTarget.textContent='⇄ Shuffle: '+(caiSunShuffle?'On':'Off')};$('#caiSunRepeat').onclick=e=>{caiSunRepeatOne=!caiSunRepeatOne;e.currentTarget.textContent='↻ Repeat One: '+(caiSunRepeatOne?'On':'Off')}} if(musicStudioView==='create'){ const advanced=$('.music-advanced'); const focusMusicField=(id,tab)=>{if(advanced)advanced.open=true;$$('.music-create-top .music-pill').forEach(x=>x.classList.toggle('active',x===tab||x.id==='musicTabAudio'&&id==='musicIdea'));const el=$('#'+id);el?.scrollIntoView({behavior:'smooth',block:'center'});setTimeout(()=>el?.focus(),250);}; $('#musicTabAudio').onclick=e=>focusMusicField('musicIdea',e.currentTarget); $('#musicTabLyrics').onclick=e=>focusMusicField('musicLyrics',e.currentTarget); $('#musicTabStyle').onclick=e=>focusMusicField('musicStyle',e.currentTarget); $('#musicTabVoice').onclick=e=>focusMusicField('musicVoice',e.currentTarget); const musicPresets={ deep:{collection:'Deep House',style:'Luxury deep house, atmospheric, elegant piano, warm sub bass, long intro and luminous outro',bpm:'104',key:'A minor',voice:'Warm intimate female vocal, breathy but clear, emotionally restrained'}, spa:{collection:'Spa & Meditation',style:'Healing spa ambient, soft piano, ocean air, warm pads, slow evolving texture',bpm:'72',key:'D major',voice:'Soft calming female vocal, close and reassuring'}, piano:{collection:'Piano & Instrumental',style:'Cinematic intimate piano, spacious room tone, gentle strings, expressive dynamics',bpm:'76',key:'D major',voice:'Natural expressive vocal with delicate phrasing'}, rnb:{collection:'R&B Soul',style:'Sophisticated R&B soul, velvet keys, deep bass, restrained drums, cinematic atmosphere',bpm:'88',key:'F# minor',voice:'Rich warm female soul vocal, intimate, controlled runs'}, latin:{collection:'Latin',style:'Romantic modern Latin pop, warm percussion, nylon guitar, piano accents, elegant bass',bpm:'100',key:'A minor',voice:'Warm expressive bilingual-friendly vocal, rhythmic and romantic'}, cinematic:{collection:'Cinematic',style:'Wide cinematic score, piano, strings, evolving pulse, emotional build, powerful ending',bpm:'82',key:'D minor',voice:'Luminous cinematic female vocal, clear diction, emotional lift'} }; $$('[data-music-style]').forEach(b=>b.onclick=()=>{const p=musicPresets[b.dataset.musicStyle];if(!p)return;$$('[data-music-style]').forEach(x=>x.classList.toggle('active',x===b));$('#musicCollection').value=p.collection;$('#musicStyle').value=p.style;$('#musicBpm').value=p.bpm;$('#musicKey').value=p.key;$('#musicVoice').value=p.voice;if(!$('#musicIdea').value.trim())$('#musicIdea').value=p.style;advanced.open=true;musicStudioDraftSave();flash(b.querySelector('b')?.textContent+' style loaded');}); let instrumental=Boolean(musicStudioDraftRead().instrumental); const instrumentalToggle=$('#musicInstrumentalToggle'); if(instrumentalToggle){instrumentalToggle.classList.toggle('active',instrumental);instrumentalToggle.textContent=instrumental?'🎹 Instrumental: On':'🎹 Instrumental';} $('#musicInstrumentalToggle').onclick=e=>{instrumental=!instrumental;e.currentTarget.classList.toggle('active',instrumental);e.currentTarget.textContent=instrumental?'🎹 Instrumental: On':'🎹 Instrumental';musicStudioDraftSave()}; const saveSong=(content,status='blueprint')=>{const arr=musicData().map(normalizeSong),id=nextMusicId(arr),title=$('#musicTitle').value.trim()||parseTitle(content,id),artist=$('#musicArtist').value.trim()||'Creator',visibility=$('#musicVisibility').value;localStorage.setItem('cai.one.music.artist',artist);arr.unshift({id,title,artist,collection:$('#musicCollection').value,style:$('#musicStyle').value.trim(),bpm:$('#musicBpm').value.trim(),key:$('#musicKey').value.trim(),lengthGoal:$('#musicLength').value.trim(),lyrics:$('#musicLyrics').value.trim(),content,visibility,status,liked:false,hasAudio:false,instrumental,createdAt:new Date().toISOString(),source:'CAI Music Studio ∞'});if(saveMusicData(arr)){saveHub('music',title,content,{catalogId:id,collection:$('#musicCollection').value,artist,visibility});flash(title+' saved '+(visibility==='private'?'privately':'to My Music'));return id}}; const generate=async(autoSave=true)=>{const idea=$('#musicIdea').value.trim()||'Surprise me with an original, emotionally memorable song.';const title=$('#musicTitle').value.trim(),style=$('#musicStyle').value.trim(),voice=$('#musicVoice').value.trim(),bpm=$('#musicBpm').value.trim(),key=$('#musicKey').value.trim(),len=$('#musicLength').value.trim(),lyrics=$('#musicLyrics').value.trim();const prompt=`CAI Music Studio ∞. Create a completely original song package. Artist/creator: ${$('#musicArtist').value||'Creator'}. Genre/collection: ${$('#musicCollection').value}. ${title?'Working title: '+title+'. ':''}${style?'Style: '+style+'. ':''}${voice?'Voice direction: '+voice+'. ':''}${bpm?'BPM: '+bpm+'. ':''}${key?'Key: '+key+'. ':''}${len?'Length goal: '+len+'. ':''}${instrumental?'Instrumental only; no sung lyrics. ':''}${lyrics?'Lyrics or lyric direction: '+lyrics+'. ':''}Creative request: ${idea}. Give a strong title, BPM/key if not provided, complete original lyrics when vocals are requested, section-by-section structure, vocal direction, instrument arrangement, intro/outro, mix/production notes, a concise dedicated music-generation prompt, and cover-art concept. Do not imitate or copy a living artist or existing song.`;const text=await moduleAI(prompt,$('#musicOutput'),'music');if(!$('#musicTitle').value.trim())$('#musicTitle').value=parseTitle(text,'');musicStudioDraftSave();if(autoSave&&text)saveSong(text,'blueprint')}; $('#musicGenerateSave').onclick=()=>{musicStudioDraftSave();generate(true)};$('#musicGenerate').onclick=()=>{musicStudioDraftSave();generate(false)};$('#musicPreview').onclick=()=>playPulse(Number($('#musicBpm').value||((($('#musicIdea').value.match(/(\d{2,3})\s*BPM/i)||[])[1])||104)));$('#musicAudioEngine').onclick=()=>{musicStudioDraftSave();generateCaiSoundFromStudio(saveSong, instrumental)};$('#musicNeuralGenerate').onclick=()=>{musicStudioDraftSave();generateNeuralSongFromStudio()};$('#musicDraftClear').onclick=musicStudioDraftClear; } } // ---------- CAI SOUND ENGINE v0.2 ---------- // Enhanced original procedural music engine. No external music-generation provider is used. // v0.2 improves musicality with style-aware rhythm, chord voicing, evolving sections, // melodic layers, stereo space, sidechain movement and gentle mastering. function caiHash(str=''){let h=2166136261>>>0;for(let i=0;i>>0} function caiRng(seed){let x=(seed||1)>>>0;return()=>{x^=x<<13;x^=x>>>17;x^=x<<5;return(x>>>0)/4294967296}} function caiClamp(v,a=-1,b=1){return vb?b:v} function caiMidiToHz(m){return 440*Math.pow(2,(m-69)/12)} function caiKeyInfo(text='A minor'){const t=String(text||'A minor').trim().toLowerCase(),names={c:0,'c#':1,db:1,d:2,'d#':3,eb:3,e:4,f:5,'f#':6,gb:6,g:7,'g#':8,ab:8,a:9,'a#':10,bb:10,b:11};const m=t.match(/([a-g](?:#|b)?)/);const pc=names[m?.[1]||'a']??9;return{pc,minor:/minor|\bmin\b|\bm\b/.test(t)&&!/major/.test(t)}} function caiDurationSeconds(v){const s=String(v||'4:00').trim();let sec=240;if(/^\d+:\d+$/.test(s)){const [m,x]=s.split(':').map(Number);sec=m*60+x}else{const n=parseFloat(s);if(Number.isFinite(n))sec=n<=12?n*60:n}return Math.max(60,Math.min(480,Math.round(sec)))} function caiAutoTitle(prompt='',collection='Original'){const seed=caiHash(prompt+'|'+collection),a=['Luminous','Midnight','Velvet','Infinite','Ocean','Celestial','Golden','Quiet','Blue','Ethereal'],b=['Pulse','Tide','Horizon','Sanctuary','Dream','Light','Echo','Bloom','Journey','Afterglow'];return a[seed%a.length]+' '+b[(seed>>>5)%b.length]} function caiWavHeader(frames,sampleRate,channels=2){const bytesPerSample=2,dataSize=frames*channels*bytesPerSample,b=new ArrayBuffer(44),v=new DataView(b),w=(o,x)=>{for(let i=0;inew Float32Array(Math.max(64,Math.round(sampleRate*sec)));return{l1:make(.19),r1:make(.23),l2:make(.37),r2:make(.41),i1:0,i2:0,lpL:0,lpR:0}} function caiSectionBuffer({bpm=104,key='A minor',style='',seed=1,songSeed=1,mode='groove',bars=4,sampleRate=24000,offsetSeconds=0,fxState=null}){ const beat=60/bpm,seconds=bars*4*beat,frames=Math.round(seconds*sampleRate),out=new Int16Array(frames*2),noise=caiBuildNoise(seed^0xa51f,32768),k=caiKeyInfo(key),profile=caiStyleProfile(style),mix=caiModeMix(mode),rng=caiRng(seed),fx=fxState||caiFxState(sampleRate),scale=caiScale(k); const baseBass=36+k.pc,baseChord=48+k.pc,baseLead=60+k.pc,TAU=Math.PI*2; const keyRate=(profile.piano||profile.rnb)?2:profile.deep?2:1; const bassPattern=profile.deep?[0,1,0,1,0,1,0,1]:profile.rnb?[1,0,1,1,0,1,0,1]:profile.latin?[1,0,1,0,1,1,0,1]:profile.spa?[1,0,0,0,1,0,0,0]:profile.cinematic?[1,0,0,0,0,0,0,0]:[1,0,1,0,1,0,1,0]; const leadPattern=[0,2,4,1,3,5,4,2]; const human=Array.from({length:64},()=>.88+rng()*.22); for(let i=0;i>>0),degree=prog[((bar%4)+4)%4],chord=caiChord(baseChord,degree,k),bassRoot=caiDegreeNote(baseBass,degree,k); let drumL=0,drumR=0,toneL=0,toneR=0; const h8=Math.floor(beatPos*2),h8InBar=((h8%8)+8)%8,h8Phase=gt-h8*(beat/2),q16=Math.floor(beatPos*4),q16InBar=((q16%16)+16)%16,q16Phase=gt-q16*(beat/4); // Kick: four-on-the-floor for house, style-aware sparse patterns elsewhere. const kickHit=profile.deep||((profile.rnb||profile.latin)&&[0,2].includes(beatInBar))||(profile.spa&&beatInBar===0&&bar%2===0)||(profile.cinematic&&beatInBar===0&&bar%2===0)||(!profile.deep&&!profile.rnb&&!profile.latin&&!profile.spa&&!profile.cinematic&&beatInBar%2===0); if(kickHit&&beatPhase<.24){const env=Math.exp(-beatPhase*18),f=43+105*Math.exp(-beatPhase*27),click=Math.exp(-beatPhase*90)*Math.sin(TAU*170*beatPhase);const v=(Math.sin(TAU*f*beatPhase)*.86+click*.12)*env*profile.kick*mix.drum;drumL+=v;drumR+=v} // Snare / clap on 2 and 4 with stereo texture. if((beatInBar===1||beatInBar===3)&&beatPhase<.16){const env=Math.exp(-beatPhase*25),n1=noise[(i*11+137)%noise.length],n2=noise[(i*17+991)%noise.length],body=Math.sin(TAU*185*beatPhase)*Math.exp(-beatPhase*18);const a=(n1*.55+body*.28)*env*profile.snare*mix.drum,b=(n2*.55+body*.28)*env*profile.snare*mix.drum;drumL+=a;drumR+=b} // Hats and shaker. Lift/final sections add gentle sixteenth motion. if(h8InBar%2===1&&h8Phase<.055){const env=Math.exp(-h8Phase*72),n=noise[(i*23+53)%noise.length],v=n*env*.23*profile.hats*mix.drum*human[h8%human.length];drumL+=v*.82;drumR+=v*1.05} if((mode==='lift'||mode==='final'||profile.latin)&&q16InBar%2===0&&q16Phase<.030){const env=Math.exp(-q16Phase*105),n=noise[(i*29+1777)%noise.length],v=n*env*.075*profile.hats*mix.drum;drumL+=v*1.10;drumR+=v*.80} // Latin-style clave/percussion accent where requested. if(profile.latin&&[2,7,10,14].includes(q16InBar)&&q16Phase<.065){const env=Math.exp(-q16Phase*45),v=Math.sin(TAU*(1200+(q16InBar%3)*170)*q16Phase)*env*.12*mix.drum;drumL+=v*.70;drumR+=v*1.12} // Sidechain recovery makes the tonal bed breathe around the kick. const duck=1-profile.sidechain*Math.exp(-beatPhase*7.8); // Bass pulse uses root/fifth movement and style-specific rhythm. const bassOn=bassPattern[h8InBar]===1,bassDur=beat/2,bassPhase=h8Phase; if(bassOn&&bassPhase.0005){const ph=TAU*kf*kp,body=Math.sin(ph)+.31*Math.sin(ph*2)+.12*Math.sin(ph*3)+.055*Math.sin(ph*4),v=body*kEnv*.17*profile.keys*mix.keys*duck,pan=.24*Math.sin((ki+seed%11)*1.7);toneL+=v*(1-pan);toneR+=v*(1+pan)} // Deep-house/ambient pluck on offbeats. if(h8InBar%2===1&&h8Phase>>4)%leadPattern.length))%leadPattern.length+leadPattern.length)%leadPattern.length],ln=caiDegreeNote(baseLead,step,k)+(beatInBar===3?12:0),lf=caiMidiToHz(ln),env=Math.exp(-beatPhase*3.7),ph=TAU*lf*beatPhase,v=(Math.sin(ph)+.18*Math.sin(ph*2))*env*.075*profile.lead*mix.lead*duck;toneL+=v*1.05;toneR+=v*.82} // Air / ocean bed for spa and cinematic space. const air=noise[(i+Math.floor(gt*31))%noise.length]*(.60+.40*Math.sin(TAU*gt/11)),amb=air*.13*profile.ambience*mix.amb;toneL+=amb*.84;toneR+=amb*1.03; // Stereo delay/reverb network persists across sections, so the track does not click between phrases. let dryL=drumL+toneL,dryR=drumR+toneR,d1L=fx.l1[fx.i1],d1R=fx.r1[fx.i1%fx.r1.length],d2L=fx.l2[fx.i2],d2R=fx.r2[fx.i2%fx.r2.length]; fx.lpL=fx.lpL*.86+(d1R*.60+d2L*.40)*.14;fx.lpR=fx.lpR*.86+(d1L*.60+d2R*.40)*.14; const wetL=(d1R*.48+d2L*.28+fx.lpL*.24)*profile.space,wetR=(d1L*.48+d2R*.28+fx.lpR*.24)*profile.space; fx.l1[fx.i1]=caiClamp(dryL*.22+d1R*.47);fx.r1[fx.i1%fx.r1.length]=caiClamp(dryR*.22+d1L*.47);fx.l2[fx.i2]=caiClamp(dryL*.15+d2R*.54);fx.r2[fx.i2%fx.r2.length]=caiClamp(dryR*.15+d2L*.54);fx.i1=(fx.i1+1)%fx.l1.length;fx.i2=(fx.i2+1)%fx.l2.length; // Gentle master bus: width, saturation, limiter and track-level fade only at true beginning/end. const width=.08*Math.sin(TAU*gt/17),fadeIn=Math.min(1,gt/.80),masterL=Math.tanh((dryL+wetL)*(1+width)*1.16)*fadeIn,masterR=Math.tanh((dryR+wetR)*(1-width)*1.16)*fadeIn; out[i*2]=Math.round(caiClamp(masterL,-.985,.985)*32767);out[i*2+1]=Math.round(caiClamp(masterR,-.985,.985)*32767); } return out } async function caiRenderTrack({prompt='',collection='Deep House',style='',bpm=104,key='A minor',duration='4:00',onProgress}){ bpm=Math.max(60,Math.min(150,Number(bpm)||104));const sampleRate=24000,seconds=caiDurationSeconds(duration),targetFrames=Math.round(seconds*sampleRate),seed=caiHash([prompt,collection,style,bpm,key].join('|')),bars=4,beat=60/bpm,sectionFrames=Math.round(bars*4*beat*sampleRate),styleAll=[collection,style,prompt].join(' '),totalSections=Math.max(1,Math.ceil(targetFrames/sectionFrames)),fx=caiFxState(sampleRate),parts=[caiWavHeader(targetFrames,sampleRate,2)]; let written=0; onProgress?.('Building CAI musical DNA…');await new Promise(r=>setTimeout(r,20)); for(let si=0;written>>0,songSeed:seed,mode,bars,sampleRate,offsetSeconds:written/sampleRate,fxState:fx}),available=Math.min(sectionFrames,targetFrames-written),bytes=available*2*2; parts.push(available===sectionFrames?seg.buffer:seg.buffer.slice(0,bytes));written+=available; await new Promise(r=>setTimeout(r,0)); } onProgress?.('Mastering stereo WAV…');await new Promise(r=>setTimeout(r,20));return new Blob(parts,{type:'audio/wav'}) } async function downloadCreatorSong(id){try{const song=musicData().map(normalizeSong).find(x=>x.id===id);if(!song)return flash('Song not found');if(song.remoteAudioUrl){const a=document.createElement('a');a.href=song.remoteAudioUrl;a.target='_blank';a.rel='noopener';a.download=(song.title||'CAI-Track').replace(/[^a-z0-9 _-]/gi,'').trim().replace(/\s+/g,'_')+'.mp3';document.body.appendChild(a);a.click();a.remove();return;}const blob=await loadMusicAudioBlob(id);if(!blob)return flash('Audio is not stored on this device');const a=document.createElement('a'),u=URL.createObjectURL(blob);a.href=u;a.download=(song.title||'CAI-Track').replace(/[^a-z0-9 _-]/gi,'').trim().replace(/\s+/g,'_')+'.wav';document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(u),1500)}catch{flash('Could not save this audio file')}} async function generateCaiSoundFromStudio(saveSong,instrumental){ const btn=$('#musicAudioEngine'),out=$('#musicOutput');if(!btn||!out)return; const idea=$('#musicIdea').value.trim()||'Luxury deep house spa, elegant piano, warm bass, atmospheric and relaxing.',collection=$('#musicCollection').value,style=$('#musicStyle').value.trim(),lyrics=$('#musicLyrics').value.trim(),bpm=Number($('#musicBpm').value||((idea.match(/(\d{2,3})\s*BPM/i)||[])[1])||104),key=$('#musicKey').value.trim()||'A minor',duration=$('#musicLength').value||'4:00'; if(!$('#musicTitle').value.trim())$('#musicTitle').value=caiAutoTitle(idea,collection);const title=$('#musicTitle').value.trim(),visibility=$('#musicVisibility').value;btn.disabled=true;const old=btn.textContent;btn.textContent='🎧 Building Instrumental…';out.classList.remove('empty-output');out.textContent='CAI Sound Engine v0.2 is arranging '+title+'…'; try{ const id=saveSong(`CAI Sound Engine v0.2 enhanced instrumental.\nPrompt: ${idea}\nStyle: ${collection}${style?' • '+style:''}\nBPM: ${bpm}\nKey: ${key}\nLength: ${duration}${lyrics?'\nLyrics saved for future vocal rendering: yes':''}\nGenerated locally with CAI-owned synthesis code.`, 'rendering');if(!id)throw new Error('Could not save song record'); const blob=await caiRenderTrack({prompt:[idea,lyrics].filter(Boolean).join(' | '),collection,style,bpm,key,duration,onProgress:m=>{out.textContent=m+'\n\n'+title+' • '+duration+' • '+bpm+' BPM • '+key}});await saveMusicAudioBlob(id,blob); const arr=musicData().map(normalizeSong),x=arr.find(v=>v.id===id);if(x){x.hasAudio=true;x.audioName=title+'.wav';x.audioType='audio/wav';x.status='ready';x.engine='CAI Sound Engine v0.2';x.instrumental=true;x.lyricsPendingVocal=Boolean(lyrics);x.durationSeconds=caiDurationSeconds(duration);x.bpm=String(bpm);x.key=key;saveMusicData(arr)} out.textContent=`${title} is ready.\n\nGenerated by CAI Sound Engine v0.2 • Enhanced Instrumental • ${duration} • ${bpm} BPM • ${key}\nSaved to My Music as ${visibility==='private'?'Private':visibility}.\n\n${lyrics?'Your lyrics are saved with the song, but ':'This track '}is instrumental. Sung vocals are not rendered by v0.2; the neural vocal engine is not connected yet.\n\nTap My Music → ▶ to play it, or ⬇ to save the WAV.`;flash(title+' generated with CAI Sound Engine v0.2');musicStudioView='library';setTimeout(()=>renderMusicVault(),450) }catch(e){console.error(e);out.textContent='CAI Sound Engine v0.2 could not finish this track on this device. Try a 2- or 4-minute track first, keep CAI ONE open, and try again.';flash('CAI Sound Engine needs another try')}finally{btn.disabled=false;btn.textContent=old} } function playPulse(bpm=104){try{const A=new (window.AudioContext||window.webkitAudioContext)();let t=A.currentTime;for(let i=0;i<8;i++){const o=A.createOscillator(),g=A.createGain();o.frequency.value=i%4===0?130:95;g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(.15,t+.01);g.gain.exponentialRampToValueAtTime(.0001,t+.12);o.connect(g).connect(A.destination);o.start(t);o.stop(t+.14);t+=60/bpm;}flash('Playing a short tempo preview — not the finished song.');}catch{flash('Audio preview is unavailable here')}} // ---------- CINEMA ---------- function shortVideoMime(){ if(!window.MediaRecorder)return ''; const opts=['video/webm;codecs=vp9','video/webm;codecs=vp8','video/webm']; return opts.find(x=>MediaRecorder.isTypeSupported?.(x))||''; } function loadShortVideoImage(src){return new Promise((resolve,reject)=>{const im=new Image();if(!String(src||'').startsWith('data:')&&!String(src||'').startsWith('blob:'))im.crossOrigin='anonymous';im.onload=()=>resolve(im);im.onerror=()=>reject(new Error('The source image could not be loaded. Choose a photo from this device.'));im.src=src;});} function drawShortVideoFrame(ctx,canvas,img,t,motion,title){ const w=canvas.width,h=canvas.height; ctx.fillStyle='#020817';ctx.fillRect(0,0,w,h); const base=Math.max(w/img.naturalWidth,h/img.naturalHeight); let z=1.02,xShift=0,yShift=0; if(motion==='Slow Zoom')z=1.02+0.12*t; else if(motion==='Zoom Out')z=1.15-0.12*t; else if(motion==='Pan Left')xShift=(t-.5)*-.12*w; else if(motion==='Pan Right')xShift=(t-.5)*.12*w; else if(motion==='Cinematic Float'){z=1.05+0.04*Math.sin(t*Math.PI);xShift=Math.sin(t*Math.PI*2)*.025*w;yShift=Math.cos(t*Math.PI*2)*.018*h;} const dw=img.naturalWidth*base*z,dh=img.naturalHeight*base*z; const dx=(w-dw)/2+xShift,dy=(h-dh)/2+yShift; ctx.drawImage(img,dx,dy,dw,dh); const grad=ctx.createLinearGradient(0,h*.62,0,h);grad.addColorStop(0,'rgba(0,0,0,0)');grad.addColorStop(1,'rgba(0,0,0,.52)');ctx.fillStyle=grad;ctx.fillRect(0,0,w,h); if(title){ctx.textAlign='center';ctx.fillStyle='rgba(255,255,255,.96)';ctx.font=`700 ${Math.round(Math.max(26,w*.045))}px system-ui`;ctx.shadowColor='rgba(0,0,0,.7)';ctx.shadowBlur=10;const safe=String(title).slice(0,80);ctx.fillText(safe,w/2,h*.88,w*.82);ctx.shadowBlur=0;} const pulse=.5+.5*Math.sin(t*Math.PI*2);ctx.fillStyle=`rgba(57,138,255,${.10+.06*pulse})`;ctx.beginPath();ctx.arc(w*.88,h*.1,Math.max(10,w*.018),0,Math.PI*2);ctx.fill(); } async function createLocalShortVideo(src,{duration=10,aspect='9:16',motion='Cinematic Float',title='',status,preview}){ if(!HTMLCanvasElement.prototype.captureStream||!window.MediaRecorder)throw new Error('This browser cannot render local video yet. Chrome/Android or a current desktop browser is recommended.'); const mime=shortVideoMime();if(!mime)throw new Error('This browser does not expose a supported WebM video encoder.'); const img=await loadShortVideoImage(src); const dims=aspect==='16:9'?[1280,720]:aspect==='1:1'?[900,900]:[720,1280]; const canvas=document.createElement('canvas');canvas.width=dims[0];canvas.height=dims[1];const ctx=canvas.getContext('2d',{alpha:false}); const stream=canvas.captureStream(30);const rec=new MediaRecorder(stream,{mimeType:mime,videoBitsPerSecond:4500000});const chunks=[]; rec.ondataavailable=e=>{if(e.data&&e.data.size)chunks.push(e.data)}; const stopped=new Promise((resolve,reject)=>{rec.onstop=()=>resolve();rec.onerror=e=>reject(e.error||new Error('Video encoder failed'));}); const seconds=Math.max(3,Math.min(30,Number(duration)||15)); rec.start(250);const start=performance.now(); await new Promise(resolve=>{const tick=now=>{const elapsed=(now-start)/1000,t=Math.min(1,elapsed/seconds);drawShortVideoFrame(ctx,canvas,img,t,motion,title);if(status)status.textContent=`Rendering ${Math.round(t*100)}% • ${seconds}s • ${aspect}`;if(t<1)requestAnimationFrame(tick);else{setTimeout(()=>{try{rec.stop()}catch{}resolve();},120)}};requestAnimationFrame(tick)}); await stopped;stream.getTracks().forEach(t=>t.stop()); const blob=new Blob(chunks,{type:mime});if(!blob.size)throw new Error('The browser returned an empty video. Please try a shorter clip.'); const url=URL.createObjectURL(blob);if(preview){preview.src=url;preview.hidden=false;preview.load();} return {blob,url,seconds,aspect,motion}; } function renderShortVideo(){ const current=activeImageUrl||''; moduleBody.innerHTML=`
CAIELLE VIDEO ∞

Create a real short video

Use the active CAIELLE image or choose a photo. Create a 5–30 second pan-and-zoom photo clip on this device. Keep this page open while it renders. Full prompt-to-generative-video motion and synchronized AI audio are the next backend phase.

Source + preview

${current?'Active CAIELLE image ready.':'Choose an image to begin.'}
Short video source
Ready.
`; let source=current;const file=$('#svFile'),img=$('#svImage'),status=$('#svStatus'),preview=$('#svPreview'),actions=$('#svActions'); const setSource=u=>{source=u;img.src=u;img.style.display='block';$('#svSource').textContent='Source image ready.';status.textContent='Ready to create.';}; $('#svUseActive').onclick=()=>{if(activeImageUrl)setSource(activeImageUrl)}; $('#svChoose').onclick=()=>file.click(); file.onchange=e=>{const f=e.target.files?.[0];if(!f)return;const r=new FileReader();r.onload=()=>setSource(String(r.result||''));r.readAsDataURL(f)}; $('#svAsk').onclick=async()=>{const idea=$('#svPrompt').value.trim()||'Create a beautiful short cinematic video.';await moduleAI(`Act as CAIELLE creative director. Give a concise 5-shot direction for a ${$('#svDuration').value}-second ${$('#svAspect').value} short video. Idea: ${idea}. Include camera motion, pacing, text suggestion, visual mood, and soundtrack direction.`,status,'create').catch(()=>{});}; $('#svCreate').onclick=async()=>{if(!source){flash('Choose a photo or use the active CAIELLE image first');return}const btn=$('#svCreate');btn.disabled=true;actions.innerHTML='';try{const result=await createLocalShortVideo(source,{duration:$('#svDuration').value,aspect:$('#svAspect').value,motion:$('#svMotion').value,title:$('#svTitle').value.trim(),status,preview});const dl=document.createElement('button');dl.className='btn gold';dl.textContent='⬇ Save Video';dl.onclick=()=>{const a=document.createElement('a');a.href=result.url;a.download='CAIELLE_Short_Video_'+Date.now()+'.webm';a.click()};const again=document.createElement('button');again.className='btn';again.textContent='🎞️ Create Another';again.onclick=()=>$('#svCreate').click();actions.append(dl,again);status.textContent=`Ready • ${result.seconds}s • ${result.aspect} • ${result.motion}`;saveHub('short-video',$('#svTitle').value.trim()||'CAIELLE Short Video',$('#svPrompt').value.trim()||'Local image-to-video motion clip',{duration:result.seconds,aspect:result.aspect,motion:result.motion,localVideo:true});caiCelebrate('Short video created');}catch(e){status.textContent=readable(e?.message||e)||'Video could not be created.';}finally{btn.disabled=false;}}; } const CINEMA_DB='cai.one.cinema.video.v1',CINEMA_STORE='movies'; let cinemaSceneImages=[],cinemaMovieUrl='',cinemaMovieBlob=null; function cinemaDb(){return new Promise((resolve,reject)=>{if(!('indexedDB' in window))return reject(new Error('Local movie storage is not available in this browser'));const q=indexedDB.open(CINEMA_DB,1);q.onupgradeneeded=()=>{const db=q.result;if(!db.objectStoreNames.contains(CINEMA_STORE))db.createObjectStore(CINEMA_STORE)};q.onsuccess=()=>resolve(q.result);q.onerror=()=>reject(q.error||new Error('Movie storage could not open'));})} async function cinemaSaveBlob(id,blob){const db=await cinemaDb();return new Promise((resolve,reject)=>{const tx=db.transaction(CINEMA_STORE,'readwrite');tx.objectStore(CINEMA_STORE).put(blob,id);tx.oncomplete=()=>{db.close();resolve(true)};tx.onerror=()=>{db.close();reject(tx.error)}})} function cinemaExtractTitle(text=''){ const t=String(text||''); const patterns=[/Blueprint\s*:\s*\*\*([^*\n]+)\*\*/i,/Title\s*[:—-]\s*\*{0,2}([^\n*]+)\*{0,2}/i,/^#\s+[^:\n]+:\s*\*\*([^*\n]+)\*\*/im,/^#\s+([^\n]+)$/m]; for(const p of patterns){const m=t.match(p);if(m?.[1])return m[1].replace(/[\*#]/g,'').trim();} return ''; } async function cinemaImage(prompt){ let last; for(let attempt=0;attempt<2;attempt++){ const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),108000); try{const data=await callImageApi({prompt,message:prompt,mode:'generate',client:{name:'CAI Cinema',version:'8.9.2'}},controller.signal);const url=extractGeneratedImage(data);if(!url)throw new Error('No cinema image was returned');return url;}catch(e){last=e;if(attempt===0)await new Promise(r=>setTimeout(r,900));}finally{clearTimeout(timer)} } throw last||new Error('Cinema image generation failed'); } async function cinemaMakeScenes({title,genre,idea,blueprint,count=3,status}){ const beats=[ 'opening establishing scene that introduces the world and protagonist', 'emotionally important midpoint scene with cinematic tension and intimate character storytelling', 'hopeful climactic or final scene that visually resolves the central emotional question', 'beautiful epilogue image that leaves the audience with wonder and emotional closure' ]; const results=[]; for(let i=0;i{const o=audioCtx.createOscillator(),g=audioCtx.createGain();o.type=i===0?'sine':'triangle';o.frequency.value=f;g.gain.value=i===0?.58:.20;o.connect(g).connect(master);o.start();osc.push(o);}); } }catch{} } const tracks=[...videoStream.getVideoTracks(),...(audioDest?audioDest.stream.getAudioTracks():[])]; const stream=new MediaStream(tracks); let rec; try{rec=new MediaRecorder(stream,{mimeType:mime,videoBitsPerSecond:bitrate});} catch(e){stream.getTracks().forEach(t=>t.stop());try{osc.forEach(o=>o.stop());audioCtx?.close?.()}catch{}throw e;} const chunks=[]; rec.ondataavailable=e=>{if(e.data?.size)chunks.push(e.data)}; const stopped=new Promise((resolve,reject)=>{rec.onstop=resolve;rec.onerror=e=>reject(e.error||new Error('Cinema encoder failed'));}); const per=total/imgs.length,startTime=performance.now(); rec.start(300); await new Promise((resolve,reject)=>{ let raf=0; const tick=now=>{ try{ const elapsed=(now-startTime)/1000,overall=Math.min(1,elapsed/total),idx=Math.min(imgs.length-1,Math.floor(elapsed/per)),local=Math.min(1,(elapsed-idx*per)/per),showTitle=elapsedtotal-2; cinemaDraw(ctx,canvas,imgs[idx],local,title,showTitle,endCard); const pct=Math.max(60,Math.round(60+overall*40)); if(status)status.textContent=`Rendering movie ${Math.round(overall*100)}% • ${total}s`; onProgress?.(pct,`Rendering movie • ${Math.round(overall*100)}%`); if(overall<1)raf=requestAnimationFrame(tick); else setTimeout(()=>{try{rec.stop()}catch{}resolve();},180); }catch(e){try{cancelAnimationFrame(raf)}catch{};try{rec.stop()}catch{};reject(e);} }; raf=requestAnimationFrame(tick); }); await stopped; try{osc.forEach(o=>o.stop());await audioCtx?.close?.()}catch{} stream.getTracks().forEach(t=>t.stop()); const blob=new Blob(chunks,{type:mime}); if(!blob.size)throw new Error('The movie renderer returned an empty file.'); if(cinemaMovieUrl)try{URL.revokeObjectURL(cinemaMovieUrl)}catch{} cinemaMovieBlob=blob;cinemaMovieUrl=URL.createObjectURL(blob); if(preview){preview.src=cinemaMovieUrl;preview.hidden=false;preview.controls=true;preview.load();} const id='CINEMA-'+Date.now();try{await cinemaSaveBlob(id,blob)}catch{} return{id,blob,url:cinemaMovieUrl,duration:total,mime,width,height,fps,withAudio}; } async function cinemaRenderMovie(scenes,{title='CAI Cinema',seconds=15,status,preview,onProgress}){ if(!scenes?.length)throw new Error('Create cinema scenes first'); if(!HTMLCanvasElement.prototype.captureStream||!window.MediaRecorder)throw new Error('This browser cannot render a movie file yet. Use current Chrome/Android or desktop Chrome.'); onProgress?.(48,'Preparing scene images…'); const imgs=[];for(let i=0;i!MediaRecorder.isTypeSupported||MediaRecorder.isTypeSupported(x.mime)); if(!candidates.length)throw new Error('This browser does not expose a compatible WebM encoder.'); let lastErr=null; for(let i=0;i0){if(status)status.textContent=`The first render had trouble. Retrying in ${c.label} mode…`;onProgress?.(60,`Retrying in ${c.label} mode…`);} return await cinemaRenderAttempt(imgs,{title,total,status,preview,...c,onProgress}); }catch(e){lastErr=e;console.warn('CAI Cinema render attempt failed:',c.label,e);} } throw lastErr||new Error('The movie renderer could not complete on this browser.'); } function renderCinema(){ renderShortVideo();return; // Reliable photo clips; the legacy generative film backend is not connected. cinemaSceneImages=[];cinemaMovieBlob=null;if(cinemaMovieUrl){try{URL.revokeObjectURL(cinemaMovieUrl)}catch{}cinemaMovieUrl='';} moduleBody.innerHTML=`
CAI CINEMA ∞ • STORY TO SCREEN

Make the story feel alive.

CAIELLE builds your movie blueprint, creates cinematic scene art, and renders a real downloadable preview movie on this device. Full generative character motion, dialogue performance and feature-length rendering require a dedicated video-generation backend.

Ready. Start with the blueprint, then render a downloadable preview movie.
CAIELLE can create the title, logline, characters, act structure, scenes, visual language, soundtrack direction, trailer concept and production plan.

What works now: blueprint → AI cinematic stills → real 16:9 WebM preview movie with motion and CAI Cinema ambience → play / save locally / download. Next production phase: connect a licensed video-generation model for moving actors, spoken dialogue, lip sync and longer scene rendering.

`; const out=$('#filmOutput'),status=$('#filmStatus'),sceneHost=$('#cinemaScenes'),preview=$('#cinemaPreview'),shell=$('#cinemaPreviewShell'),actions=$('#cinemaMovieActions'); const progressCard=$('#cinemaProgressCard'),progressTitle=$('#cinemaProgressTitle'),progressPct=$('#cinemaProgressPercent'),progressFill=$('#cinemaProgressFill'),progressDetail=$('#cinemaProgressDetail'); const setProgress=(pct,detail,title='🎬 CAIELLE IS MAKING YOUR MOVIE')=>{progressCard.hidden=false;const v=Math.max(0,Math.min(100,Number(pct)||0));progressTitle.textContent=title;progressPct.textContent=Math.round(v)+'%';progressFill.style.width=v+'%';progressDetail.textContent=detail||'Working…';}; const build=async()=>{setProgress(5,'Building the movie blueprint…');status.textContent='CAIELLE is building your movie blueprint…';const t=await moduleAI(`Build an original ${$('#filmFormat').value} blueprint. Genre: ${$('#filmGenre').value}. ${$('#filmTitle').value.trim()?'Title: '+$('#filmTitle').value+'.':''} Story idea: ${$('#filmIdea').value}. Include a strong TITLE, logline, characters, world, 3-act or episode structure, key scenes, visual language, soundtrack direction, trailer concept, shot-list starter and production checklist. Use clear markdown headings.`,out,'create');const auto=cinemaExtractTitle(t);if(auto&&!$('#filmTitle').value.trim())$('#filmTitle').value=auto;setProgress(18,'Blueprint ready. Preparing cinematic scenes…');status.textContent='Blueprint ready. You can save the project or render a real preview movie.';return t;}; $('#filmCreate').onclick=async()=>{try{await build();setProgress(100,'Blueprint ready ✓','✅ BLUEPRINT READY');setTimeout(()=>progressCard.hidden=true,2400)}catch{status.textContent='The blueprint could not finish. Please try once more.';setProgress(0,'Blueprint creation stopped. Tap Create Movie Blueprint to retry.','⚠️ CINEMA NEEDS ANOTHER TRY')}}; $('#filmSave').onclick=()=>{const content=out.textContent;const auto=cinemaExtractTitle(content);if(auto&&!$('#filmTitle').value.trim())$('#filmTitle').value=auto;const title=$('#filmTitle').value.trim()||auto||'Untitled Cinema Project';saveHub('cinema',title,content,{format:$('#filmFormat').value,genre:$('#filmGenre').value,hasMovie:Boolean(cinemaMovieBlob)});flash(title+' saved to My Hub');}; const showReadyActions=(result,title,blueprint)=>{ shell.hidden=false;preview.hidden=false;actions.innerHTML=''; const play=document.createElement('button');play.className='btn cinema-play';play.textContent='▶ Play Movie';play.onclick=async()=>{try{preview.currentTime=0;await preview.play()}catch{flash('Tap the video player once, then press Play Movie again')}}; const dl=document.createElement('button');dl.className='btn cinema-render';dl.textContent='⬇ Download Movie';dl.onclick=()=>{const a=document.createElement('a');a.href=result.url;a.download=(title||'CAI_Cinema').replace(/[^a-z0-9 _-]/gi,'').trim().replace(/\s+/g,'_')+'.webm';a.click()}; const hub=document.createElement('button');hub.className='btn cinema-save';hub.textContent='💼 Save Movie Project';hub.onclick=()=>{saveHub('cinema',title,blueprint,{format:$('#filmFormat').value,genre:$('#filmGenre').value,videoId:result.id,duration:result.duration,localMovie:true});flash('Movie project saved in My Hub')}; actions.append(play,dl,hub); setProgress(100,'Your preview movie is ready to play.','✅ YOUR MOVIE IS READY'); status.textContent=`Movie ready • ${result.duration}s • ${result.width}×${result.height}. Press Play Movie, download it, or save the project.`; shell.scrollIntoView({behavior:'smooth',block:'center'}); flash('CAI Cinema preview movie is ready 🎬'); }; const renderCurrentScenes=async(title,blueprint,btn)=>{ if(!cinemaSceneImages.length)throw new Error('No cinema scenes are ready yet.'); shell.hidden=false;preview.hidden=true;actions.innerHTML=''; setProgress(58,'Scenes are ready. Starting the movie renderer…'); const result=await cinemaRenderMovie(cinemaSceneImages,{title,seconds:Number($('#filmLength').value)||15,status,preview,onProgress:(pct,detail)=>setProgress(pct,detail)}); showReadyActions(result,title,blueprint); return result; }; $('#filmRender').onclick=async()=>{ const btn=$('#filmRender');caiSetWorking(btn,true,'🎬 Creating Movie…');let blueprint='',title=''; try{ blueprint=out.textContent;if(!blueprint||blueprint.includes('CAIELLE can create'))blueprint=await build(); const auto=cinemaExtractTitle(blueprint);if(auto&&!$('#filmTitle').value.trim())$('#filmTitle').value=auto; title=$('#filmTitle').value.trim()||auto||'CAI Cinema Preview'; const count=Number($('#filmScenes').value)||3; setProgress(22,`Creating cinematic scene 1 of ${count}…`); cinemaSceneImages=await cinemaMakeScenes({title,genre:$('#filmGenre').value,idea:$('#filmIdea').value,blueprint,count,status}); sceneHost.innerHTML=cinemaSceneImages.map((x,i)=>`
Cinema scene ${i+1}${esc(x.label)}
`).join(''); setProgress(55,`${cinemaSceneImages.length} scene${cinemaSceneImages.length===1?'':'s'} ready. Rendering the actual movie file…`); status.textContent='Scenes ready. Rendering the movie file…'; await renderCurrentScenes(title,blueprint,btn); }catch(e){ const msg=readable(e?.message||e)||'The movie could not finish.'; status.textContent=msg; shell.hidden=false;preview.hidden=true;actions.innerHTML=''; const retry=document.createElement('button');retry.className='btn cinema-retry';retry.textContent='↻ Retry Movie Render'; retry.onclick=async()=>{retry.disabled=true;retry.textContent='🎬 Retrying…';try{const currentTitle=$('#filmTitle').value.trim()||title||'CAI Cinema Preview';const currentBlueprint=out.textContent||blueprint;await renderCurrentScenes(currentTitle,currentBlueprint,retry)}catch(err){status.textContent=readable(err?.message||err)||'Retry could not finish.';setProgress(55,'The scenes are safe. Tap Retry Movie Render again.','⚠️ MOVIE RENDER NEEDS ANOTHER TRY');retry.disabled=false;retry.textContent='↻ Retry Movie Render'}}; const keep=document.createElement('button');keep.className='btn';keep.textContent='💼 Save Blueprint & Scenes';keep.onclick=()=>{saveHub('cinema',$('#filmTitle').value.trim()||title||'CAI Cinema Project',out.textContent||blueprint,{format:$('#filmFormat').value,genre:$('#filmGenre').value,sceneCount:cinemaSceneImages.length,renderPending:true});flash('Cinema project saved — movie render can be retried')}; actions.append(retry,keep); setProgress(55,'The scene images were created, but the local video encoder did not finish. Your scenes are safe.','⚠️ MOVIE RENDER NEEDS ANOTHER TRY'); shell.scrollIntoView({behavior:'smooth',block:'center'}); flash('Scenes are safe • movie render needs another try'); }finally{caiSetWorking(btn,false)} }; } // ---------- SCHOOL ---------- const schoolTracks=['Early Learning','K–12 Foundations','College & Careers','Life Skills','Creator Academy','Research Lab']; function renderSchool(){moduleBody.innerHTML=`
${schoolTracks.map(t=>`
Learning path

${esc(t)}

${({"Early Learning":"Reading, numbers, curiosity, kindness and play","K–12 Foundations":"Math, science, language, history, arts and digital citizenship","College & Careers":"Computer science, business, health, law, engineering and design","Life Skills":"Money, cooking, home care, travel safety, communication and wellbeing","Creator Academy":"Music, books, film, art, fashion, games and entrepreneurship","Research Lab":"Verified sources, experiments, critical thinking and invention"})[t]}

`).join('')}

Lesson workspace

Your adaptive lesson will appear here.
`;$$('[data-school]').forEach(b=>b.onclick=()=>{$('#schoolTrack').value=b.dataset.school;$('#schoolTopic').focus();});$('#schoolCreate').onclick=()=>moduleAI(`Act as CAI School. Track: ${$('#schoolTrack').value}. Topic/request: ${$('#schoolTopic').value||'Create a useful starter lesson.'} Build a kind adaptive lesson with objective, explanation, examples, practice, a mini quiz, answers, and one reflection question.`, $('#schoolOutput'),'all');} // ---------- CREATOR ---------- const creatorTypes=[['Song & Lyrics','Lyrics, chords, arrangement and production brief'],['Book Studio','Outline, chapters, editing and publishing plan'],['Art & Covers','Cover, poster, fashion and social artwork briefs'],['Video & Animation','Script, storyboard, shot list and captions'],['Voice & Audiobook','Narration script, pacing and voice direction'],['Creator Package','Credits, ownership notes, release checklist and exports']]; function renderCreator(){moduleBody.innerHTML=`
${creatorTypes.map(([t,d])=>`

${esc(t)}

${esc(d)}

`).join('')}

CAIELLE Creator

CAIELLE will build the creative package here.
`;$$('[data-creator]').forEach(b=>b.onclick=()=>{$('#creatorType').value=b.dataset.creator;$('#creatorIdea').focus();});$('#creatorGo').onclick=()=>moduleAI(`CAI ONE Creator Studio. Create an original ${$('#creatorType').value} package from this request: ${$('#creatorIdea').value||'Surprise me with something beautiful and original.'}. Make it polished, usable, and clearly structured.`, $('#creatorOutput'),'create');$('#creatorSave').onclick=()=>saveHub('creator',$('#creatorType').value,$('#creatorOutput').textContent);} // ---------- SEARCH ---------- function renderSearch(){moduleBody.innerHTML=`
CAIELLE can help organize the question here. Live web and Maps buttons open external services in a new tab.

CAI ONE will gain deeper live search connectors over time. For now, the external live-search buttons avoid pretending stale model knowledge is current.

`;$('#askResearch').onclick=()=>moduleAI($('#searchQuery').value||'Help me research something useful today.', $('#searchOutput'),'research');$('#openWeb').onclick=()=>window.open('https://www.google.com/search?q='+encodeURIComponent($('#searchQuery').value),'_blank','noopener');$('#openMaps').onclick=()=>window.open('https://www.google.com/maps/search/?api=1&query='+encodeURIComponent($('#searchQuery').value),'_blank','noopener');} // ---------- GLAM ---------- const GLAM_OUTFITS=[ {name:'Keep Original Outfit',icon:'◉',tag:'All styles',a:'#18314e',b:'#07182b',detail:'preserve the original clothing and personal style; refine lighting and fabric detail only'}, {name:'Cai Midnight Tuxedo',icon:'🤵',tag:'Menswear evening',a:'#15223b',b:'#080e1a',detail:'luxurious midnight navy menswear tuxedo with tailored trousers, satin lapels, crisp dress shirt and refined formal shoes'}, {name:'Cai Royal Tailored Suit',icon:'👔',tag:'Menswear tailoring',a:'#183a60',b:'#101827',detail:'elegant masculine tailored navy suit, crisp shirt, natural shoulder proportions, premium wool and subtle accessories'}, {name:'Cai Modern Unisex',icon:'✦',tag:'Modern tailoring',a:'#36505c',b:'#111827',detail:'androgynous contemporary tailored jacket and trousers with clean lines and premium fabrics'}, {name:'Cai Emerald Empress',icon:'💚',tag:'Palace couture',a:'#0b453c',b:'#07182b',detail:'deep emerald silk-satin evening gown with antique-gold botanical embroidery, sculptural draping, refined open-back option, elegant train and couture-level finishing'}, {name:'Cai Midnight Versailles',icon:'🌙',tag:'Midnight royalty',a:'#0b163a',b:'#14101f',detail:'midnight navy velvet couture gown with restrained champagne-gold beadwork, architectural waist, elegant cape sleeves and regal evening proportions'}, {name:'Cai Champagne Lumière',icon:'🥂',tag:'Golden gala',a:'#6a4b25',b:'#171325',detail:'champagne silk-satin gala gown with delicate crystal beadwork, luminous draped bodice, graceful floor-length skirt and soft couture train'}, {name:'Cai Pearl Sovereign',icon:'🤍',tag:'Pearl couture',a:'#6b6f78',b:'#182035',detail:'ivory pearl-silk couture gown with hand-beaded pearl detailing, architectural neckline, clean waist and refined luminous elegance'}, {name:'Cai Sapphire Celeste',icon:'💎',tag:'Celestial blue',a:'#12428a',b:'#101b45',detail:'royal sapphire evening gown with crystal constellation beadwork, fluid silk drape, elegant shoulders and a sophisticated cinematic silhouette'}, {name:'Cai Rose Gold Reverie',icon:'🌹',tag:'Romantic couture',a:'#754255',b:'#27162b',detail:'blush rose-gold silk couture gown with soft metallic embroidery, delicate draping and a graceful romantic red-carpet silhouette'}, {name:'Cai Scarlet Opera',icon:'❤️',tag:'Opera night',a:'#7a1727',b:'#250812',detail:'deep scarlet silk column gown with refined off-shoulder draping, sculpted waist, restrained jewel accents and old-world opera glamour'}, {name:'Cai Silver Moon',icon:'🌌',tag:'Liquid silver',a:'#56657c',b:'#10172c',detail:'liquid-silver satin couture gown with crystal accents, sculpted cape detail and polished moonlit evening elegance'}, {name:'Cai Black Gold Atelier',icon:'🖤',tag:'Atelier icon',a:'#171717',b:'#302009',detail:'black velvet couture gown with intricate antique-gold botanical embroidery, sculpted silhouette, luxurious sash and dramatic editorial elegance'}, {name:'Cai Riviera White',icon:'🕊️',tag:'Resort elegance',a:'#65625b',b:'#1f2e3b',detail:'clean ivory resort-evening gown with fluid silk movement, subtle champagne-gold details and effortless Mediterranean luxury'}, {name:'Cai Executive Royal',icon:'👑',tag:'Power tailoring',a:'#132f5d',b:'#111827',detail:'midnight navy couture pantsuit with satin lapels, perfectly tailored waist, silk blouse, refined gold jewelry and powerful executive elegance'}, {name:'Cai Emerald Mosaic',icon:'✨',tag:'Mosaic couture',a:'#075a57',b:'#21180c',detail:'deep teal and emerald couture robe-gown with ornate gold mosaic embroidery, luxurious satin sash, elegant drape and warm palace-light glamour'} ]; const GLAM_HAIR=['Keep My Original Hair','Cai Classic Short Cut','Cai Textured Crop','Cai Groomed Waves','Keep My Cai Hair','Cai Silk Straight','Cai Soft Waves','Cai Royal Curls','Cai Elegant Bun','Cai Luxe Blowout','Cai Crown Volume']; const GLAM_MAKEUP=['Keep Original — No Added Makeup','Natural Grooming — Preserve Facial Hair','Cai Natural Luminance','Cai Rose Petal','Cai Soft Nude Glow','Cai Golden Goddess','Cai Diamond Glow','Cai Evening Radiance']; const GLAM_BACKGROUNDS=['Keep My Original World','Cai Couture Studio','Cai Ocean Escape','Cai Golden Palace','Cai City Lights','Cai Celestial Stars','Cai Heavenly Garden']; function glamOutfitDetail(name){return GLAM_OUTFITS.find(x=>x.name===name)?.detail||'elegant original Cai Couture wardrobe with refined fit, premium materials and realistic tailoring';} function glamShowView(view='after'){ const img=$('#glamImg');if(!img||!glamSource)return; const compare=$('#glamCompare'); if(compare){ const show=view==='compare'&&Boolean(glamAiImage);compare.hidden=!show; img.hidden=show;img.style.display=show?'none':'block'; if(show){$('#glamCompareBefore').src=glamSource;$('#glamCompareAfter').src=glamAiImage;} else{for(const pic of compare.querySelectorAll('img'))pic.removeAttribute('src');} } if(view==='before'){img.src=glamSource;img.style.filter='none';} else if(glamAiImage){img.src=glamAiImage;img.style.filter='none';} else{img.src=glamSource;} $$('#glamStudioShell [data-glam-view]').forEach(b=>b.classList.toggle('active',b.dataset.glamView===view)); } function glamSelectOutfit(name){ const sel=$('#glamDress');if(sel)sel.value=name; $$('#glamStudioShell [data-glam-outfit]').forEach(b=>b.classList.toggle('active',b.dataset.glamOutfit===name)); const o=GLAM_OUTFITS.find(x=>x.name===name),label=$('#glamSelectedLook'); if(label&&o)label.innerHTML=`${esc(o.name)} — ${esc(o.detail)}.`; } async function glamPrepareAiImage(source,maxSide=1536,targetBytes=1250*1024){ if(!source)throw new Error('No Glam image available'); const img=await new Promise((ok,no)=>{const x=new Image();x.onload=()=>ok(x);x.onerror=()=>no(new Error('Could not prepare this photo for AI Glam'));x.src=source;}); const iw=img.naturalWidth||img.width,ih=img.naturalHeight||img.height; let scale=Math.min(1,maxSide/Math.max(iw,ih)); let w=Math.max(1,Math.round(iw*scale)),h=Math.max(1,Math.round(ih*scale)); const canvas=document.createElement('canvas'),ctx=canvas.getContext('2d',{alpha:false}); const encode=(quality)=>{ canvas.width=w;canvas.height=h; ctx.fillStyle='#fff';ctx.fillRect(0,0,w,h);ctx.drawImage(img,0,0,w,h); const dataUrl=canvas.toDataURL('image/jpeg',quality); const comma=dataUrl.indexOf(','); const bytes=Math.ceil(Math.max(0,dataUrl.length-comma-1)*3/4); return {dataUrl,bytes}; }; let quality=.84,result=encode(quality); while(result.bytes>targetBytes&&quality>.54){ quality-=.08;result=encode(quality); } while(result.bytes>targetBytes&&Math.max(w,h)>900){ w=Math.max(1,Math.round(w*.82));h=Math.max(1,Math.round(h*.82)); quality=Math.min(quality,.68);result=encode(quality); } if(result.bytes>targetBytes*1.15)throw new Error('This photo is still too large for secure AI Glam. Please choose a smaller photo.'); return result.dataUrl; } function renderGlam(){ const outfitOptions=GLAM_OUTFITS.map((o,i)=>`${esc(o.name)}`).join(''); const outfitCards=GLAM_OUTFITS.map((o,i)=>``).join(''); moduleBody.innerHTML=`
CAI GLAM STUDIO ∞
Your couture canvasChoose a photo. Your original is always preserved.
CAI ONE keeps your uploaded original unchanged. Every AI look is a separate creation.

Elegant Outfit Atelier

Tap a couture direction, then create the wardrobe on your photo.

Looks for every style
${outfitCards}
${esc(GLAM_OUTFITS[0].name)} — ${esc(GLAM_OUTFITS[0].detail)}.
Fine-tune the look
Choose a photo, select an outfit, then tap Create Outfit or Signature Glam. CAIELLE will visibly show that the AI edit is working.
`; const file=$('#glamFile'),img=$('#glamImg'); glamEditEpoch++;glamEditBusy=false;glamUploadPending=false; glamSource=null;glamRequestSource=null;glamAiImage=null; img.onerror=()=>{img.hidden=true;img.style.display='none';$('#glamEmpty').hidden=false;$('#glamStatus').textContent='This photo could not be opened. Please choose a JPG, PNG or WebP image.';}; img.onload=()=>{const comparing=$('#glamCompare')&&!$('#glamCompare').hidden;img.hidden=Boolean(comparing);img.style.display=comparing?'none':'block';$('#glamEmpty').hidden=true;}; $('#glamUpload').onclick=()=>file.click(); let glamUploadVersion=0; const glamReadyButtons=()=>$$('#glamStudioShell [data-glam-ai], #glamSurprise'); file.onchange=async e=>{ const f=e.target.files?.[0];if(!f)return; const version=++glamUploadVersion; glamUploadPending=true; glamEditEpoch++;glamEditBusy=false; glamReadyButtons().forEach(b=>{caiSetWorking(b,false);b.disabled=true;}); $('#glamStatus').textContent='Checking your photo and preparing a private preview…'; try{ const safe=await privacySafeImageDataUrl(f); const prepared=await glamPrepareAiImage(safe.dataUrl,1536,1250*1024); // A slower earlier selection must never replace the latest photo or a new module. if(version!==glamUploadVersion||$('#glamImg')!==img)return; glamSource=safe.dataUrl;glamRequestSource=prepared;glamAiImage=null; img.src=glamSource;img.hidden=false;img.style.filter='none'; $('#glamEmpty').hidden=true;glamShowView('before'); $('#glamStatus').textContent='Photo ready ✓ Your file is unchanged. A compatible copy is ready for AI editing.'; }catch(err){ if(version!==glamUploadVersion||$('#glamImg')!==img)return; e.target.value=''; const failure=readable(err?.message||err)||'Could not prepare that photo. Choose a JPG or PNG.'; $('#glamStatus').textContent=failure+(glamSource?' The new photo was not selected. Your previous photo and edit are still available.':' No photo is ready for editing.'); if(!glamSource){img.hidden=true;img.removeAttribute('src');$('#glamEmpty').hidden=false;} }finally{ if(version===glamUploadVersion&&$('#glamImg')===img){ glamUploadPending=false; glamReadyButtons().forEach(b=>b.disabled=!glamRequestSource); } } }; $$('[data-glam-outfit]').forEach(b=>b.onclick=()=>glamSelectOutfit(b.dataset.glamOutfit)); $('#glamDress').onchange=e=>glamSelectOutfit(e.target.value); $$('[data-glam-view]').forEach(b=>b.onclick=()=>{ if(b.dataset.glamView!=='before'&&!glamAiImage)return flash('Create a Glam look first'); glamShowView(b.dataset.glamView); }); $$('[data-filter]').forEach(b=>b.onclick=()=>applyGlamFilter(b.dataset.filter)); $$('[data-glam-ai]').forEach(b=>b.onclick=()=>aiGlam(b.dataset.glamAi,b)); $('#glamSurprise').onclick=async e=>{ if(!glamSource)return flash('Choose a photo first'); const outfit=GLAM_OUTFITS.find(o=>o.name===$('#glamDress').value)||GLAM_OUTFITS[0]; glamSelectOutfit(outfit.name); $('#glamHair').value=GLAM_HAIR[0]; $('#glamMakeup').value=GLAM_MAKEUP[0]; $('#glamBg').value=GLAM_BACKGROUNDS[1+Math.floor(Math.random()*(GLAM_BACKGROUNDS.length-1))]; $('#glamNotes').value='Surprise me with a polished, sophisticated, editorial couture portrait. Preserve my identity and natural features. Keep the result realistic, elegant and premium.'; await aiGlam('full',e.currentTarget); }; $('#glamReset').onclick=()=>{ if(glamUploadPending)return flash('Please wait for your new photo to finish preparing.'); glamEditEpoch++;glamEditBusy=false; glamReadyButtons().forEach(b=>{caiSetWorking(b,false);b.disabled=!glamRequestSource;}); if(glamSource){glamAiImage=null;img.style.filter='none';glamShowView('before');$('#glamStatus').textContent='Original restored. Your source photo remains unchanged.';} }; $('#glamDownload').onclick=downloadGlam; $('#glamHub').onclick=()=>glamUploadPending?flash('Please wait for your new photo to finish preparing.'):saveHub('glam',$('#glamDress').value,`Wardrobe: ${$('#glamDress').value}\nHair: ${$('#glamHair').value}\nMakeup: ${$('#glamMakeup').value}\nBackground: ${$('#glamBg').value}\nNotes: ${$('#glamNotes').value||''}`,{aiStyled:Boolean(glamAiImage)}); } function applyGlamFilter(name){if(glamUploadPending)return flash('Please wait for your new photo to finish preparing.');const img=$('#glamImg');if(!img||img.hidden)return flash('Choose a photo first');const f={radiance:'brightness(1.06) contrast(1.04) saturate(1.05)',velvet:'brightness(1.03) contrast(1.08) saturate(1.12) sepia(.04)',noir:'grayscale(.88) contrast(1.16) brightness(.96)'}[name]||'none';img.style.filter=f;$('#glamStatus').textContent='Local glam preview applied. Your original is unchanged.';} function glamValidatePreview(url){ if(typeof url!=='string'||!(/^(https?:\/\/|data:image\/(?:png|jpeg|webp|gif);base64,)/i.test(url)))return Promise.reject(new Error('The edit returned an unsupported image address.')); return new Promise((resolve,reject)=>{ const image=new Image();let settled=false; const finish=error=>{if(settled)return;settled=true;clearTimeout(timer);image.onload=null;image.onerror=null;error?reject(error):resolve();}; const timer=setTimeout(()=>finish(new Error('The edited image could not be loaded. Please retry.')),15000); image.onload=()=>finish(image.naturalWidth&&image.naturalHeight?null:new Error('The edited image is empty.')); image.onerror=()=>finish(new Error('The edited image could not be loaded. Your original photo is preserved.')); image.src=url; }); } async function aiGlam(action='full',triggerBtn=null){ if(glamUploadPending)return flash('Please wait for your new photo to finish preparing.'); if(!glamSource)return flash('Choose a photo first'); if(glamEditBusy)return flash('A Glam edit is already in progress.'); const source=glamSource, preview=$('#glamImg'), status=$('#glamStatus'); const edit=++glamEditEpoch;glamEditBusy=true; const current=()=>edit===glamEditEpoch&&source===glamSource&&$('#glamImg')===preview&&$('#glamStatus')===status; const buttons=$$('#glamStudioShell [data-glam-ai], #glamSurprise'); buttons.forEach(b=>b.disabled=true); const actionNote={ full:'Complete coordinated makeover', hair:'Change/style hair only while keeping clothing and background as close as possible', dress:'Change wardrobe only while preserving face and hair', beauty:'Refine makeup/beauty styling while preserving identity', background:'Change the scene/background while preserving the person' }[action]||'Complete makeover'; const outfitName=$('#glamDress').value,outfitDetail=glamOutfitDetail(outfitName);const prompt=`Cai Couture Glam Maison transformation. Preserve facial identity, gender presentation, facial hair, age-appropriate natural proportions, realistic anatomy, skin texture and recognizable features. Do not feminize or masculinize the person unless explicitly requested. No added makeup or hairstyle changes when keeping the original options. Action: ${actionNote}. Wardrobe: ${outfitName}. Couture wardrobe direction: ${outfitDetail}. Use realistic premium textiles, believable seams, tailoring, drape, jewelry and lighting; keep the styling elegant rather than costume-like. Hair: ${$('#glamHair').value}. Makeup: ${$('#glamMakeup').value}. Background: ${$('#glamBg').value}. User request: ${$('#glamNotes').value||'Elegant, luminous, realistic Cai Couture portrait.'}`; const labels={full:'✨ Creating Glam…',hair:'💇 Styling Hair…',dress:'👗 Dressing…',beauty:'💄 Beautifying…',background:'🌎 Creating Scene…'}; caiSetWorking(triggerBtn,true,labels[action]||'✨ Creating…'); status.textContent='✨ CAIELLE is creating your secure AI Couture transformation. Image edits can take up to about two minutes—please keep this page open.'; try{ const sendGlam=async imagePayload=>{ const response=await fetch('/api/cai/glam',{ method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({image:imagePayload,prompt,action,preserveIdentity:true}) }); const raw=await response.text(); let data={};try{data=raw?JSON.parse(raw):{}}catch{data={error:raw}}; return {response,data}; }; if(!glamRequestSource){ status.textContent='Preparing an AI-safe copy of your photo…'; const prepared=await glamPrepareAiImage(source,1536,1250*1024); if(!current())return;glamRequestSource=prepared; } let sent=await sendGlam(glamRequestSource); if(!current())return; if(sent.response.status===413){ status.textContent='Photo is still large — optimizing once more and retrying automatically…'; const smaller=await glamPrepareAiImage(source,1120,760*1024); if(!current())return;glamRequestSource=smaller; sent=await sendGlam(glamRequestSource); if(!current())return; } const r=sent.response,d=sent.data; if(!r.ok)throw new Error(readable(d)||'Glam service unavailable'); const url=d.imageDataUrl||d.image||d.url; if(!url)throw new Error(d.message||'No edited image returned'); await glamValidatePreview(url); if(!current())return; glamAiImage=url; $('#glamImg').src=url; $('#glamImg').style.filter='none'; glamShowView('after'); status.textContent='✨ Your couture look is ready ✓ Review Before / After, then save or try another outfit.'; }catch(e){ if(!current())return; glamShowView('before'); const msg=readable(e.message||e); status.textContent=(/timed out/i.test(msg) ?'The AI edit timed out. No makeover was created; your original photo is unchanged. You may retry when ready.' :'No AI makeover was created. Your original is unchanged. '+msg); }finally{ if(current()){caiSetWorking(triggerBtn,false);glamEditBusy=false;buttons.forEach(b=>b.disabled=!glamRequestSource);} } } function downloadGlam(){if(glamUploadPending)return flash('Please wait for your new photo to finish preparing.');const img=$('#glamImg');if(!img||img.hidden)return flash('Choose a photo first');const c=document.createElement('canvas'),ctx=c.getContext('2d'),pic=new Image();pic.crossOrigin='anonymous';pic.onload=()=>{c.width=pic.naturalWidth;c.height=pic.naturalHeight;ctx.filter=glamAiImage?'none':getComputedStyle(img).filter;ctx.drawImage(pic,0,0);const a=document.createElement('a');a.download='CAI_Glam_'+Date.now()+'.png';a.href=c.toDataURL('image/png');a.click();};pic.src=glamAiImage||glamSource;} // ---------- PARTY ---------- function partySaved(){try{return JSON.parse(localStorage.getItem(PARTY_KEY)||'{}')}catch{return{}}} function renderParty(){ const p=partySaved(); const defaultName='CAI ONE ∞ Launch Celebration — October 10, 2026'; const defaultWelcome=`Good evening, everyone. I’m CAIELLE, the intelligence at the heart of CAI ONE ∞. Welcome to Cai Sun’s celebration and the introduction of CAI ONE. Tonight, you are among the first guests to experience what Cai has been building. Thank you for being part of this beginning.`; const defaultFounder=`Please welcome Cai Sun — founder and creator of CAI ONE ∞, a multidisciplinary technology creator bringing together software, artificial intelligence, creativity, storytelling, music, and human-centered design. Tonight is not only a celebration. It is the beginning of a vision being brought to life.`; const defaultLifetime=`And now, a special gift for tonight’s guests: you are being welcomed as CAI ONE Founder Guests, with lifetime-access status planned for your accounts once the official redemption and account system is activated. Thank you for being here at the beginning.`; const defaultBirthday=`And of course, tonight is also a celebration of Cai. Happy birthday, Cai. May this new year be filled with courage, creation, kindness, and possibilities beyond what you imagined.`; const defaultClosing=`Thank you for celebrating with us. From Cai Sun, from CAIELLE, and from CAI ONE ∞ — thank you for being part of this first chapter. One vision. Infinite possibilities.`; moduleBody.innerHTML=`
LIVE HOST MODE • PARTY WOW EDITION

${esc(p.name||defaultName)}

CAIELLE is ready to host.
Use Sound Check first. Then you can run each moment manually or rehearse the whole show.

🎙️ Welcome

Open the evening and introduce CAI ONE.

✨ Founder Moment

Introduce Cai Sun with a polished founder spotlight.

♾️ Founder Guest Gift

Reveal the lifetime-access gift without overstating account activation.

🎂 Birthday Moment

Let CAIELLE deliver a warm birthday message.

CAIELLE can polish your full host script, transitions, contingency lines, timing notes, and rehearsal plan.

Offline Backup

CAIELLE speech uses the protected Signature Cloud Voice when online, with a device voice as fallback. Music cues are reminders unless a local/licensed audio source is connected. The Founder Guest lifetime-access announcement is a celebration promise; actual account entitlement still requires the redemption/account system to be connected.

`; let cueIndex=-1; const updateClock=()=>{const e=$('#partyClock');if(e)e.textContent=new Date().toLocaleTimeString([],{hour:'numeric',minute:'2-digit',second:'2-digit'});}; updateClock();gameInterval=setInterval(updateClock,1000); const save=()=>saveParty(); $('#partyName').oninput=()=>$('#partyNameShow').textContent=$('#partyName').value||defaultName; $('#partySound').onclick=()=>speakParty('Hello. I am CAIELLE. Sound check complete. If you can hear me clearly, I am ready to host CAI ONE with you.'); $('#partyWelcomeBtn').onclick=()=>speakParty($('#partyWelcome').value); $('#partyFounderBtn').onclick=()=>speakParty($('#partyFounder').value); $('#partyLifetimeBtn').onclick=()=>speakParty($('#partyLifetime').value); $('#partyBirthdayBtn').onclick=()=>speakParty($('#partyBirthday').value); $('#partyClosingBtn').onclick=()=>speakParty($('#partyClosing').value); $('#partyOfflineBtn').onclick=()=>speakParty($('#partyOffline').value); $('#partyRehearse').onclick=()=>{ const full=[ $('#partyWelcome').value, $('#partyFounder').value, $('#partyLifetime').value, $('#partyBirthday').value, $('#partyClosing').value ].filter(Boolean).join('\n\n'); $('#partyCue').textContent='Full rehearsal running…'; speakParty(full); }; $('#partyScript').onclick=()=>moduleAI( `You are CAIELLE in CAI ONE Party Mode for a live October 10 launch celebration. Event: ${$('#partyName').value||defaultName}. Host: ${$('#partyHost').value||'CAIELLE'}. Polish this show while keeping it warm, elegant, concise, easy to read aloud, and exciting without exaggerating unconnected features. Welcome: ${$('#partyWelcome').value} Founder introduction: ${$('#partyFounder').value} Founder Guest lifetime-access reveal: ${$('#partyLifetime').value} Birthday message: ${$('#partyBirthday').value} Closing: ${$('#partyClosing').value} Create a timed host script with transitions, applause pauses, music-cue reminders, a short internet-outage fallback, and a graceful closing. Do not claim lifetime-access accounts are already activated unless the redemption system is actually connected.`, $('#partyOutput'),'create' ); $('#partyNext').onclick=()=>{ const cues=$('#partyCues').value.split('\n').map(x=>x.trim()).filter(Boolean); if(!cues.length)return; cueIndex=(cueIndex+1)%cues.length; $('#partyCue').textContent=cues[cueIndex]; speakParty(cues[cueIndex]); save(); }; $('#partyStop').onclick=()=>{ stopCaielleSpeech(); stopListening?.(); $('#partyCue').textContent='Stopped.'; }; $('#partyFull').onclick=()=>$('.party-stage').requestFullscreen?.(); $('#partySave').onclick=()=>{save();flash('Party setup saved');}; ['partyName','partyHost','partyWelcome','partyFounder','partyLifetime','partyBirthday','partyClosing','partyCues','partyOffline'] .forEach(id=>$('#'+id).addEventListener('change',save)); } function saveParty(){ try{ localStorage.setItem(PARTY_KEY,JSON.stringify({ name:$('#partyName')?.value||'', host:$('#partyHost')?.value||'', welcome:$('#partyWelcome')?.value||'', founder:$('#partyFounder')?.value||'', lifetime:$('#partyLifetime')?.value||'', birthday:$('#partyBirthday')?.value||'', closing:$('#partyClosing')?.value||'', offline:$('#partyOffline')?.value||'', cues:($('#partyCues')?.value||'').split('\n').filter(Boolean) })) }catch{} } function speakParty(text){speakWithCaielle(text,{afterDialogue:false});} // ---------- CAI CONNECT ---------- function connectProfile(){try{return Object.assign({displayName:'',caiId:''},JSON.parse(localStorage.getItem(CONNECT_PROFILE_KEY)||'{}'))}catch{return {displayName:'',caiId:''}}} function saveConnectProfile(p){localStorage.setItem(CONNECT_PROFILE_KEY,JSON.stringify(p));} function connectThreads(){try{const x=JSON.parse(localStorage.getItem(CONNECT_THREADS_KEY)||'[]');return Array.isArray(x)?x:[]}catch{return[]}} function saveConnectThreads(a){localStorage.setItem(CONNECT_THREADS_KEY,JSON.stringify(a.slice(0,60)));} function connectOutbox(){try{const x=JSON.parse(localStorage.getItem(CONNECT_OUTBOX_KEY)||'[]');return Array.isArray(x)?x:[]}catch{return[]}} function saveConnectOutbox(a){localStorage.setItem(CONNECT_OUTBOX_KEY,JSON.stringify(a.slice(0,250)));} function connectKind(address=''){ const v=String(address||'').trim(); if(!v)return 'cai'; if(v.startsWith('@'))return 'cai'; if(v.includes('@'))return 'email'; if(v.replace(/\D/g,'').length>=7)return 'sms'; return 'cai'; } function connectThreadLabel(t){return t?.name||t?.address||'Conversation';} function connectGetThread(id){return connectThreads().find(x=>x.id===id)||null;} function connectSaveMessage(threadId,text,status='queued'){ const a=connectThreads(),i=a.findIndex(x=>x.id===threadId);if(i<0)return null; const msg={id:'MSG-'+Date.now()+'-'+Math.random().toString(36).slice(2,6),from:'me',text:String(text||'').trim(),at:new Date().toISOString(),status}; a[i].messages=Array.isArray(a[i].messages)?a[i].messages:[];a[i].messages.push(msg);a[i].updatedAt=msg.at;saveConnectThreads(a); const q=connectOutbox();q.unshift({threadId,messageId:msg.id,address:a[i].address,kind:a[i].kind,text:msg.text,at:msg.at,status});saveConnectOutbox(q); return msg; } function connectMarkReady(){ if(!navigator.onLine)return; const q=connectOutbox();let changed=false; q.forEach(x=>{if(x.status==='queued'){x.status='ready';changed=true;}}); if(changed)saveConnectOutbox(q); } window.addEventListener('online',()=>{connectMarkReady();if(moduleModal?.classList.contains('open')&&$('#moduleTitle')?.textContent.includes('CAI CONNECT'))renderConnect();flash('CAI CONNECT is back online — queued messages are ready to send.');}); window.addEventListener('offline',()=>{if(moduleModal?.classList.contains('open')&&$('#moduleTitle')?.textContent.includes('CAI CONNECT'))renderConnect();}); async function connectNearbyShare(t,msg){ const payload=`CAI CONNECT ∞\nTo: ${t.address||t.name||'Nearby person'}\n${msg}`; if(navigator.share){try{await navigator.share({title:'CAI CONNECT ∞',text:payload});return true}catch(e){if(e?.name==='AbortError')return false;}} try{await navigator.clipboard.writeText(payload);flash('Nearby message copied — use Quick Share/Nearby Share if available');return true}catch{return false} } function renderConnect(){ connectMarkReady(); const threads=connectThreads().sort((a,b)=>String(b.updatedAt||'').localeCompare(String(a.updatedAt||''))),out=connectOutbox(),profile=connectProfile(),online=navigator.onLine; const activeId=(window.__caiConnectActive&&threads.some(x=>x.id===window.__caiConnectActive))?window.__caiConnectActive:(threads[0]?.id||''); window.__caiConnectActive=activeId;const active=connectGetThread(activeId); const msgs=active?.messages||[]; moduleBody.innerHTML=`PRIVATE FRIENDS’ LOUNGE

♡ CAI Circle ∞

Invite your friends. Text together. Join voice when you’re ready. Up to six people in your own temporary Circle.

Create or join your Circle ↗
CAI CONNECT ∞

${online?'🟢 Online':'⚪ Offline — local mode'}

Your chat history, contacts and outbox stay available on this device even without internet. Long-distance delivery needs an internet/SMS service; nearby device-to-device delivery is a native-app feature. On supported phones, Share Nearby can open the OS share sheet so you can choose Quick Share/Nearby Share.

YOUR CAI ID

Web build note: this local identity is not yet a verified global CAI account.

Start a conversation

CAI-to-CAI internet chat and direct computer-to-phone SMS become live when the authenticated CAI Connect backend is connected. Until then, messages remain private drafts/outbox items on this device or can be handed to your device's messaging apps.

Chats

${threads.length?threads.map(t=>``).join(''):'

No conversations yet.

'}

${active?esc(connectThreadLabel(active)):'Conversation'}

${active?`

${esc(active.address||'')} • ${esc((active.kind||'cai').toUpperCase())}

${msgs.length?msgs.map(m=>`
${m.from==='me'?'You':'Them'} ${new Date(m.at).toLocaleTimeString()} • ${esc(m.status||'saved')}
${esc(m.text)}
`).join(''):'No messages yet.'}
${active.kind==='sms'?'':''}
`:'

Start or select a chat.

'}

Offline Outbox

${out.filter(x=>x.status==='queued').length} queued offline • ${out.filter(x=>x.status==='ready').length} ready after reconnect • ${out.length} total saved outbox items. CAI ONE never marks a message “sent” unless a connected provider confirms delivery.

${out.slice(0,12).map(x=>`
${esc(x.address||'Recipient')}${esc(x.status)} • ${new Date(x.at).toLocaleString()}
${esc(x.text)}
`).join('')||'

Outbox is empty.

'}

No-internet options

📝 Offline composingWrite, save and search local chats with no connection.
📤 Automatic outboxMessages stay queued and become ready when connectivity returns.
📲 Share NearbyUses the phone/tablet OS share sheet when available; choose Quick Share/Nearby Share for local transfer where supported.
📡 Native CAI NearbyNext phase: encrypted Bluetooth/Wi‑Fi Direct chat between nearby CAI devices without internet.
🔐 PrivacyThis web build stores chat locally on the device. End-to-end encryption across users requires the authenticated CAI Connect service.
`; $('#connectSaveProfile').onclick=()=>{let caiId=$('#connectCaiId').value.trim();if(caiId&&!caiId.startsWith('@'))caiId='@'+caiId;saveConnectProfile({displayName:$('#connectDisplayName').value.trim(),caiId});flash('CAI identity saved on this device');}; $('#connectStart').onclick=()=>{const name=$('#connectNewName').value.trim(),address=$('#connectNewAddress').value.trim();if(!name&&!address)return flash('Add a name or recipient');const a=connectThreads(),id='CHAT-'+Date.now();a.unshift({id,name:name||address,address,kind:connectKind(address),messages:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});saveConnectThreads(a);window.__caiConnectActive=id;renderConnect();}; $$('[data-connect-thread]').forEach(b=>b.onclick=()=>{window.__caiConnectActive=b.dataset.connectThread;renderConnect();}); if(active){ $('#connectQueue').onclick=()=>{const text=$('#connectMessage').value.trim();if(!text)return flash('Type a message first');const status=navigator.onLine?'ready':'queued';connectSaveMessage(active.id,text,status);renderConnect();flash(status==='queued'?'Saved to Offline Outbox':'Saved to Outbox — ready for connected delivery');}; function phoneDraft(){ const text=$('#connectMessage').value.trim(); if(!text){flash('Type a message first');return null;} const address=active.address.trim(); const phone=normalizeEmergencyContact(address); if(phone.kind!=='sms'||!/^[+0-9(). -]+$/.test(address)){ flash('Enter a valid phone number. For international numbers, include + and the country code.'); return null; } return {number:phone.value,text}; } $('#connectDeviceSend').onclick=()=>{ if(active.kind==='sms'){ const draft=phoneDraft(); if(!draft)return; flash('Review and send in Messages. If the draft is empty, use Copy Message and paste it.'); openPhoneText(draft.number,draft.text); return; } const text=$('#connectMessage').value.trim(); if(!text)return flash('Type a message first'); const contact=normalizeEmergencyContact(active.address||''); connectSaveMessage(active.id,text,navigator.onLine?'ready':'queued'); if(contact.kind==='email'){ location.href=`mailto:${encodeURIComponent(contact.value)}?subject=CAI%20CONNECT&body=${encodeURIComponent(text)}`; }else{ renderConnect(); flash('Saved locally. CAI-to-CAI delivery needs the authenticated CAI Connect service.'); } }; if(active.kind==='sms'){ $('#connectWhatsApp').onclick=()=>{ const draft=phoneDraft(); if(!draft)return; openPhoneWhatsApp(draft.number,draft.text); }; $('#connectVideoCall').onclick=()=>{ const address=String(active.address||'').trim(); const contact=normalizeEmergencyContact(address); if(contact.kind!=='sms'||!/^[+0-9(). -]+$/.test(address))return flash('Enter a valid phone number with its country code.'); flash('Tap the camera icon in WhatsApp to start your call.'); openPhoneWhatsApp(contact.value); }; $('#connectCopy').onclick=async()=>{ const input=$('#connectMessage'); if(!input.value.trim())return flash('Type a message first'); try{ await navigator.clipboard.writeText(input.value.trim()); flash('Message copied. Paste it into your texting app.'); }catch{ input.focus(); input.select(); flash('Message selected. Use your device’s Copy command.'); } }; } $('#connectNearby').onclick=async()=>{const text=$('#connectMessage').value.trim();if(!text)return flash('Type a message first');connectSaveMessage(active.id,text,'nearby');const ok=await connectNearbyShare(active,text);if(ok)flash('Nearby share opened');renderConnect();}; } $('#connectOpenGuard').onclick=()=>openModule('guard'); $('#connectClearLocal').onclick=()=>{if(!confirm('Erase all CAI Connect chats and outbox data stored on this device?'))return;localStorage.removeItem(CONNECT_THREADS_KEY);localStorage.removeItem(CONNECT_OUTBOX_KEY);window.__caiConnectActive='';renderConnect();flash('Local CAI Connect data erased');}; } // ---------- GUARD ---------- function guardLog(){try{return JSON.parse(localStorage.getItem(GUARD_KEY)||'[]')}catch{return[]}} function addGuardLog(type,detail){const a=guardLog();a.unshift({at:new Date().toISOString(),type,detail});localStorage.setItem(GUARD_KEY,JSON.stringify(a.slice(0,100)));} function guardPrefs(){try{return Object.assign({sensitivity:'bag',delay:10,vibrate:true,repeat:true,saveLastSeen:true,separation:true,carExit:true,antiSnoop:true,privacyNotifs:false,privacyBiometric:false,privacySim:false,privacyPrivateSpace:false},JSON.parse(localStorage.getItem(GUARD_PREFS_KEY)||'{}'))}catch{return {sensitivity:'bag',delay:10,vibrate:true,repeat:true,saveLastSeen:true,separation:true,carExit:true,antiSnoop:true}}} function saveGuardPrefs(p){localStorage.setItem(GUARD_PREFS_KEY,JSON.stringify(p));} function guardTrusted(){try{return JSON.parse(localStorage.getItem(GUARD_TRUSTED_KEY)||'[]')}catch{return[]}} function saveGuardTrusted(a){localStorage.setItem(GUARD_TRUSTED_KEY,JSON.stringify(a.slice(0,8)));} function guardLastSeen(){try{return JSON.parse(localStorage.getItem(GUARD_LASTSEEN_KEY)||'null')}catch{return null}} function guardThreshold(){return ({table:5.2,bag:3.8,travel:2.8})[guardPrefs().sensitivity]||3.8} function guardModeLabel(){return ({table:'Table Guard',bag:'Bag / Desk Guard',travel:'Travel Guard'})[guardPrefs().sensitivity]||'Bag / Desk Guard'} function guardStatus(){return guardArmed?'ARMED':guardArming?'ARMING…':'DISARMED'} function normalizeEmergencyContact(value=''){ const raw=String(value||'').trim(); if(!raw)return {kind:'none',value:''}; if(raw.includes('@'))return {kind:'email',value:raw}; const digits=raw.replace(/\D/g,''); if(digits.length===10)return {kind:'sms',value:'+1'+digits}; if(digits.length===11&&digits.startsWith('1'))return {kind:'sms',value:'+'+digits}; if(raw.startsWith('+')&&digits.length>=8&&digits.length<=15)return {kind:'sms',value:'+'+digits}; return {kind:'invalid',value:raw}; } function emergencyLocationLine(){ const d=guardLastSeen(); if(!d)return ''; const lat=Number(d.lat),lon=Number(d.lon); if(!Number.isFinite(lat)||!Number.isFinite(lon))return ''; return `\nMy last saved location: https://maps.google.com/?q=${lat.toFixed(6)},${lon.toFixed(6)} (saved ${new Date(d.at).toLocaleString()})`; } function guardEmergencyMessage(base,includeLocation=false){ const text=String(base||'').trim()||'I need help. Please contact me as soon as you can.'; return text+(includeLocation?emergencyLocationLine():''); } function saveGuardLastSeen(){if(!guardPrefs().saveLastSeen||!navigator.geolocation)return;try{navigator.geolocation.getCurrentPosition(pos=>{const d={lat:pos.coords.latitude,lon:pos.coords.longitude,accuracy:pos.coords.accuracy,at:new Date().toISOString()};localStorage.setItem(GUARD_LASTSEEN_KEY,JSON.stringify(d));addGuardLog('Last seen','Location saved when Guardian Light was armed');},()=>{}, {enableHighAccuracy:false,timeout:5000,maximumAge:60000});}catch{}} function guardLastSeenLabel(){const d=guardLastSeen();if(!d)return 'Not saved yet';return `${Number(d.lat).toFixed(5)}, ${Number(d.lon).toFixed(5)} • ${new Date(d.at).toLocaleString()}`;} function stopGuardAlarm(){if(guardAlarmTimer){clearInterval(guardAlarmTimer);guardAlarmTimer=null;}try{guardAudioCtx?.suspend?.()}catch{}try{navigator.vibrate?.(0)}catch{}} function guardPulse(){const p=guardPrefs();try{if(p.vibrate)navigator.vibrate?.([320,120,320,120,650]);}catch{}try{const AC=window.AudioContext||window.webkitAudioContext;if(!AC)return;if(!guardAudioCtx)guardAudioCtx=new AC();if(guardAudioCtx.state==='suspended')guardAudioCtx.resume?.();const o=guardAudioCtx.createOscillator(),g=guardAudioCtx.createGain();o.type='sawtooth';o.frequency.setValueAtTime(880,guardAudioCtx.currentTime);o.frequency.exponentialRampToValueAtTime(1260,guardAudioCtx.currentTime+.45);g.gain.setValueAtTime(.22,guardAudioCtx.currentTime);g.gain.exponentialRampToValueAtTime(.02,guardAudioCtx.currentTime+1.15);o.connect(g).connect(guardAudioCtx.destination);o.start();o.stop(guardAudioCtx.currentTime+1.2);}catch{}} function renderGuard(){ const logs=guardLog(),p=guardPrefs(),trusted=guardTrusted(),ls=guardLastSeen(); moduleBody.innerHTML=`
GUARDIAN LIGHT ∞

${guardStatus()}

User-armed motion protection for this CAI ONE web app. While the app remains active, Guardian Light can detect movement, sound/vibrate and show a full-screen alert. Reliable protection after Android locks or suspends the browser requires the native Android Guardian service.

Mode: ${esc(guardModeLabel())} • Arming delay: ${p.delay}s • Last seen: ${esc(ls?new Date(ls.at).toLocaleString():'not saved')}

PROTECTION PROFILE

Bring Me With You + Car Exit Guard

⌚ Separation protection

Preference is saved now. Actual background Bluetooth separation alerts require the native Android/iPhone app and an explicitly paired watch, ring or tag.

🚗 Car Exit Guard

The native app will combine car/Bluetooth state with paired-device separation. CAI ONE must never infer or track another person without their consent.

Anti-snooping privacy

🔐 CAI ONE privacy lock

The web app cannot lock Gmail or Android itself. Whole-device security remains your Android PIN/biometric lock.

Lock-screen privacy checklist




Trusted contacts

Saved only on this device. Guardian Light will never send a message automatically; any future emergency sharing must show you exactly what will be sent and require your approval unless you explicitly configure an emergency automation in the native app.

${trusted.length?trusted.map((x,i)=>`
${esc(x.name)}${esc(x.contact)}
`).join(''):'

No trusted contacts saved.

'}

Emergency Connect

EMERGENCY CONTACT

💬 Reach a trusted person

Prepare a message to a regular phone number or email address. Nothing is sent automatically. For immediate danger, use the device's emergency call/SOS features; CAI ONE is not a replacement for 911 or local emergency services.

${trusted.length?trusted.map((x,i)=>``).join(''):'Add a trusted contact above for one-tap access.'}

On a phone, CAI ONE can hand the prepared message to your Text/Email app. Direct internet SMS from a Chromebook/tablet needs a secure CAI account plus an authenticated messaging provider; it is not enabled in this web build yet.

STUDENT / NO-PHONE MODE

💻 Communication without owning a phone

The CAI identity can be used from a computer or tablet. CAI-to-CAI messaging and direct SMS to normal phone numbers require the upcoming authenticated CAI Connect service so messages cannot be abused or sent anonymously.

CAI → CAIInternet messaging between verified CAI accounts — account service required.
CAI → phone numberSMS provider + sender registration + abuse protection required.
Emergency servicesUse the device/OS emergency call or SOS system. CAI does not route 911 messages.

Last seen + native readiness

📍 Last seen${esc(guardLastSeenLabel())}
🔒 Locked-screen motion alarmNative Android service required for dependable operation after screen lock.
🏔️ Offline local alarmNative target: motion + sound + vibration continue without cellular data.
👥 Consent firstNo hidden location sharing, no silent tracking of another person, and no secret microphone recording.

Security event log

${logs.length?logs.map(l=>`${new Date(l.at).toLocaleString()} — ${esc(l.type)} — ${esc(l.detail||'')}`).join('
'):'No events yet.'}
`; $('#armGuard').onclick=()=>guardArmed||guardArming?disarmGuard('Disarmed by owner'):armGuard(); $('#testGuard').onclick=()=>triggerGuard('Test alarm'); $('#clearGuard').onclick=()=>{localStorage.removeItem(GUARD_KEY);renderGuard();}; const save=()=>{const q=guardPrefs();q.sensitivity=$('#guardSensitivity').value;q.delay=Number($('#guardDelay').value)||0;q.vibrate=$('#guardVibrate').checked;q.repeat=$('#guardRepeat').checked;q.saveLastSeen=$('#guardLastSeen').checked;q.separation=$('#guardSeparation').checked;q.carExit=$('#guardCarExit').checked;q.antiSnoop=$('#guardAntiSnoop').checked;saveGuardPrefs(q);}; ['guardSensitivity','guardDelay','guardVibrate','guardRepeat','guardLastSeen','guardSeparation','guardCarExit','guardAntiSnoop'].forEach(id=>$('#'+id).onchange=save); $$('[data-guard-check]').forEach(el=>el.onchange=()=>{const q=guardPrefs();q[el.dataset.guardCheck]=el.checked;saveGuardPrefs(q);}); $('#guardAddTrusted').onclick=()=>{const name=$('#guardTrustedName').value.trim(),contact=$('#guardTrustedContact').value.trim();if(!name||!contact)return flash('Add a name and phone or email');const a=guardTrusted();a.push({name,contact});saveGuardTrusted(a);addGuardLog('Trusted contact','Added '+name);renderGuard();}; $$('[data-guard-remove]').forEach(b=>b.onclick=()=>{const a=guardTrusted();a.splice(Number(b.dataset.guardRemove),1);saveGuardTrusted(a);renderGuard();}); $$('[data-emergency-contact]').forEach(b=>b.onclick=()=>{const x=guardTrusted()[Number(b.dataset.emergencyContact)];if(!x)return;$('#guardEmergencyTo').value=x.contact||'';flash(`Emergency contact: ${x.name}`);}); $$('[data-emergency-preset]').forEach(b=>b.onclick=()=>{const presets={help:'I need help. Please contact me as soon as you can.',pickup:'I need a safe ride or pickup. Please contact me and let me know when you can come.',safe:"I'm safe now. Thank you for checking on me."};$('#guardEmergencyMessage').value=presets[b.dataset.emergencyPreset]||presets.help;}); $('#guardEmergencyOpen').onclick=()=>{ const c=normalizeEmergencyContact($('#guardEmergencyTo').value),include=$('#guardEmergencyLocation').checked,msg=guardEmergencyMessage($('#guardEmergencyMessage').value,include); if(c.kind==='none'||c.kind==='invalid')return flash('Add a valid trusted phone number or email'); if(c.kind==='sms'&&/^(\+?1)?911$/.test(c.value.replace(/\D/g,'')))return flash('Use the device emergency call/SOS system for 911'); addGuardLog('Emergency draft',`Prepared ${c.kind.toUpperCase()} message for ${c.value}`); const url=c.kind==='email'?`mailto:${encodeURIComponent(c.value)}?subject=${encodeURIComponent('CAI Emergency Connect')}&body=${encodeURIComponent(msg)}`:`sms:${encodeURIComponent(c.value)}?body=${encodeURIComponent(msg)}`; location.href=url; }; $('#guardEmergencyCopy').onclick=async()=>{const msg=guardEmergencyMessage($('#guardEmergencyMessage').value,$('#guardEmergencyLocation').checked);try{await navigator.clipboard.writeText(msg);addGuardLog('Emergency draft','Message copied by owner');flash('Emergency message copied');}catch{flash('Copy was not available on this device');}}; $('#guardOpenConnect').onclick=()=>openModule('connect'); $('#guardEmergencyInternet').onclick=()=>{const el=$('#guardEmergencyStatus');if(el)el.textContent='Internet SMS is READY TO CONNECT, not active. It needs authenticated CAI accounts, a registered SMS sender/provider, rate limits, consent/opt-out handling and abuse protection before we enable sending from computers/tablets.';addGuardLog('Emergency Connect','Internet SMS status viewed');}; } async function startGuardMonitoring(){ try{ if(typeof DeviceMotionEvent!=='undefined'&&typeof DeviceMotionEvent.requestPermission==='function'){const p=await DeviceMotionEvent.requestPermission();if(p!=='granted'){guardArming=false;renderGuard();return flash('Motion permission was not granted');}} try{const AC=window.AudioContext||window.webkitAudioContext;if(AC&&!guardAudioCtx)guardAudioCtx=new AC();await guardAudioCtx?.resume?.();}catch{} guardBaseline=null;guardCalibrating=true;guardHandler=e=>{const a=e.accelerationIncludingGravity||e.acceleration;if(!a)return;const mag=Math.sqrt((a.x||0)**2+(a.y||0)**2+(a.z||0)**2);if(guardBaseline==null){guardBaseline=mag;return;}guardBaseline=guardBaseline*.96+mag*.04;if(guardCalibrating)return;const delta=Math.abs(mag-guardBaseline);if(delta>guardThreshold()&&Date.now()-guardLastTrigger>5000)triggerGuard(`Movement detected (${guardModeLabel()}, Δ ${delta.toFixed(1)})`);};addEventListener('devicemotion',guardHandler);guardArming=false;guardArmed=true;setTimeout(()=>guardCalibrating=false,2200);saveGuardLastSeen();addGuardLog('Armed',`${guardModeLabel()} armed by owner`);renderGuard();flash('Guardian Light armed. Keep the phone still while it calibrates.'); }catch(e){guardArming=false;guardArmed=false;renderGuard();flash('Motion sensing could not be enabled');} } async function armGuard(){ if(guardArmed||guardArming)return; const p=guardPrefs();guardArming=true;renderGuard();addGuardLog('Arming',`${guardModeLabel()} • ${p.delay}s delay`); if(p.delay>0){flash(`Guardian Light will arm in ${p.delay} seconds`);guardArmingTimer=setTimeout(()=>{guardArmingTimer=null;startGuardMonitoring();},p.delay*1000);}else await startGuardMonitoring(); } function disarmGuard(detail='Guardian Light disarmed by owner'){if(guardArmingTimer){clearTimeout(guardArmingTimer);guardArmingTimer=null;}if(guardHandler)removeEventListener('devicemotion',guardHandler);guardHandler=null;guardArmed=false;guardArming=false;guardBaseline=null;stopGuardAlarm();addGuardLog('Disarmed',detail);$('#guardShield')?.classList.remove('show');if(moduleModal.classList.contains('open')&&$('#moduleTitle').textContent.includes('Guardian'))renderGuard();} function triggerGuard(detail){guardLastTrigger=Date.now();addGuardLog('ALERT',detail);const p=guardPrefs();const alert=$('#guardAlertText');if(alert)alert.textContent=detail;guardPulse();if(p.repeat&&!guardAlarmTimer)guardAlarmTimer=setInterval(guardPulse,1800);$('#guardShield').classList.add('show');if(moduleModal.classList.contains('open')&&$('#moduleTitle').textContent.includes('Guardian'))renderGuard();} $('#dismissShield').onclick=()=>disarmGuard('Alarm dismissed and Guardian Light disarmed by owner'); $('#snoozeShield').onclick=()=>{stopGuardAlarm();$('#guardShield').classList.remove('show');if(guardArmed){guardCalibrating=true;guardBaseline=null;addGuardLog('Snoozed','Alarm snoozed for 60 seconds');setTimeout(()=>{guardCalibrating=false;addGuardLog('Resumed','Guardian Light resumed after snooze');},60000);} }; // ---------- ARCADE — INFINITY CHALLENGE ENGINE ---------- const ARCADE_PROGRESS_KEY='cai.one.arcade.infinity.v1'; let activeGameId=null; const games=[ ['memory','🧠','Memory Matching ∞','Endless memory boards that grow with every level'], ['word','📖','Wordlight ∞','Endless vocabulary, language and storytelling challenges'], ['rhythm','🎵','Rhythm Pulse ∞','Ever-longer music timing and coordination patterns'], ['cryptonexus','🎮','Cai & Aries: Crypto Nexus ∞','Endless kindness-powered strategy and cyber-safety missions'], ['trail','🧭','Trail Quest ∞','Navigation, nature and safety missions that keep evolving'], ['math','✨','Math Galaxy ∞','Endless arithmetic, patterns and problem-solving levels'], ['code','🌱','Code Garden ∞','Coding foundations that bloom into harder challenges'], ['starweave','🌌','Starweave Alignment ∞','Reconnect longer and longer remembered constellations'], ['healing','💗','Healing My Heart ∞','Gentle heartlight and breathing challenges with new goals'], ['heartlight','💖','HEARTLIGHT INFINITY','Catch living heartlights through endless score missions'], ['soulweave','🪄','SOULWEAVE INFINITY','Memorize radiant symbol patterns with no final level'], ['rock','🪨','Rock Bump ∞','Aim, launch and master increasingly precise targets'], ['maze','💎','Luminara Light Maze ∞','A new light-maze challenge at every level'], ['mazeinfinity','♾️','Luminara Maze Infinity','Endless expanding maze-chase with crystals and shadow wisps'], ['serenity','🫧','Luminara Serenity ∞','Progressive calming breath journeys'], ['ascension','✨','Luminara Ascension ∞','An endless stream of uplifting real-life challenges'], ['timekeeper','⏳','Luminara Timekeeper ∞','Focus missions you can continue forever'], ['goddess','👑','Luminara Goddess Quest ∞','Endless chapters of light, courage, truth and love'] ]; function arcadeStore(){try{return JSON.parse(localStorage.getItem(ARCADE_PROGRESS_KEY)||'{}')}catch{return{}}} function arcadeStats(id){const all=arcadeStore(),s=all[id]||{};return{level:Math.max(1,Number(s.level)||1),xp:Math.max(0,Number(s.xp)||0),plays:Math.max(0,Number(s.plays)||0),best:Math.max(0,Number(s.best)||0)}} function saveArcadeStats(id,s){const all=arcadeStore();all[id]=s;try{localStorage.setItem(ARCADE_PROGRESS_KEY,JSON.stringify(all))}catch{}} function arcadeLevel(id=activeGameId){return arcadeStats(id).level} function beginArcadeGame(id){const s=arcadeStats(id);s.plays++;saveArcadeStats(id,s);} function advanceArcadeGame(){if(!activeGameId)return;const s=arcadeStats(activeGameId);s.level++;s.xp+=50+s.level*10;s.best=Math.max(s.best,s.level);saveArcadeStats(activeGameId,s);launchGame(activeGameId);flash('Infinity Level '+s.level+' — new challenge unlocked ♾️');} function replayArcadeGame(){if(activeGameId)launchGame(activeGameId)} function resetArcadeGame(){if(!activeGameId)return;const all=arcadeStore();delete all[activeGameId];try{localStorage.setItem(ARCADE_PROGRESS_KEY,JSON.stringify(all))}catch{}launchGame(activeGameId);flash('This game returned to Level 1');} function arcadeHud(){if(!activeGameId)return'';const s=arcadeStats(activeGameId);return `
♾️ Infinity Level ${s.level}XP ${s.xp}Plays ${s.plays}Best ${Math.max(s.best,s.level)}

There is no final level. Tap Next Challenge whenever you are ready; difficulty and variety continue to grow.

`} function attachArcadeControls(){const n=$('[data-arcade-next]'),r=$('[data-arcade-replay]'),h=$('[data-arcade-home]'),x=$('[data-arcade-reset]');if(n)n.onclick=advanceArcadeGame;if(r)r.onclick=replayArcadeGame;if(h)h.onclick=renderArcade;if(x)x.onclick=resetArcadeGame;} function renderArcade(){const all=arcadeStore();moduleBody.innerHTML=`NEW · PRIVATE FRIENDS’ ROOM · FRIENDLY POINTS

♛ Royal Dominoes ∞

Match a little. Laugh a little. Play double-six draw dominoes with two to four players, or practice with Caielle’s computer player. Your worlds, your music, text and voice together.

Gather around the table ↗
NEW · PRIVATE FRIENDS’ TABLE · PLAY CHIPS ONLY

♛ Royal Blackjack ∞

Caielle deals. You choose your world. Invite up to six friends, play blackjack, talk together, and listen to Cai Sun. Hit, Stand, Double Down, Split, and solo practice included.

Take your seat ↗
NEW · PRIVATE FRIENDS’ ROOMS · PLAY CHIPS ONLY

♛ Royal Poker ∞

Your friends. Your kingdom. Dress up with your own face picture, play Texas Hold’em, chat, and join table voice. Explore Mars, Jupiter, Hawaii, or an enchanted palace. Up to 24 friends across three tables.

Create your royal poker night ↗
NEW · CAI ONE ORIGINAL · ADVENTURE & PUZZLES

The Rise of Aurora

Explore the Starfall Isles with Lumi the sky fox. Awaken three shrines, discover hidden treasures, and bring a sleeping sky garden to life. Touch controls, gentle mode, and music included.

Begin your adventure ↗
NEW · CAI ONE ORIGINAL · FALLING BLOCKS & FLYING WORLDS

NEBULA BUILDERS ∞

Clear luminous rows to build flying castles, mountains, neon cities, gardens, and planets. Pilot your futuristic car through your own Milky Way. Color, music, and an endless creative journey.

Build my universe ↗
NEW · FASHION & MAGICAL GARDENS

Cai One Sun

Your beautiful life keeps growing. Shop dresses, shoes, bags, hats, and makeup at the fancy mall. Plant cherry blossoms and a magical garden, then explore worlds with your Cai Sun music everywhere.

Play Cai One Sun ☀
NEW · CAI ONE ORIGINAL · DRAW & PLAY

PRISM GENESIS ∞

Draw a glowing creature and fly it through a colorful sky. Collect musical colors to grow a floating island—and add layers to your original soundtrack.

Compose your first dawn ↗
NEW · CAI ONE ORIGINAL · MUSIC INCLUDED

AURORA PROTOCOL ∞

Rescue five stranded starships, shatter meteors, rewind your flight, and restore a dark planet to a rainbow aurora. Includes the original electronic space score Afterlight.

Answer the signal ↗
NEW · CAI ONE ORIGINAL · MUSIC INCLUDED

GENESIS FORGE ∞

Engineer a solar flying car, program your diamond-collecting robot, and power your first glowing city. Explore a generated alien world with an original electronic space soundtrack.

Enter Genesis Forge ↗
NEW · CAI ONE ORIGINAL

COSMIC RUSH ∞

Race nine flying cars through universe tunnels and planetary circuits. Collect golden stones for turbo, trigger Rainbow Hyperdrive, and win to unlock eight spectacular courses.

Enter Cosmic Rush ↗
NEW · CAI ONE ORIGINAL

DIAMONDIA ∞

Touch sparkling diamonds on a colorful planet. Grow your score, build homes and cities, and open portals to worlds beyond. No timer. No final world.

Enter Diamondia ✦
NEW · CAI ONE ORIGINAL

STARFORGE ∞

Fly from Earth toward Mars. Mine asteroids into building materials, build your home, deploy robot helpers, and settle fictional exoplanets.

Enter Starforge ↗
NEW · CAI ONE ORIGINAL

OCEANFORGE ∞

Pilot your luminous submarine. Explore rainbow reefs and golden ruins, rescue sea turtles, and discover the wonders of the deep.

Enter Oceanforge ↓
NEW · CAI ONE ORIGINAL

FLIGHTFORGE ∞

Build your flying car. Explore glowing skylines. Chase the horizon with a sunlight-powered Solar Core. Now with Diamond Worlds: fly to planets, collect diamonds, and build a rainbow diamond world.

Enter Flightforge ↗
CAI ARCADE ∞

Every game is now an Infinity Game

Finish, replay, or press Next Challenge. Levels keep growing, challenges change, and progress stays on this device.

${games.map(g=>{const s=all[g[0]]||{level:1,xp:0};return `
${g[1]}

${esc(g[2])}

${esc(g[3])}

Infinity Level ${Number(s.level)||1} • ${Number(s.xp)||0} XP
`}).join('')}
♾️

Choose an Infinity Game

No final screen. Every title can generate another challenge.

`;$$('[data-game]').forEach(b=>b.onclick=()=>launchGame(b.dataset.game));} function clearGameTimers(){if(gameState?.mazeInfinityKey)document.removeEventListener('keydown',gameState.mazeInfinityKey);if(gameTimer)clearTimeout(gameTimer);if(gameInterval)clearInterval(gameInterval);gameTimer=null;gameInterval=null;gameState={};} const gameGuides={"memory": ["Match every pair of symbols.", "Tap two hidden tiles at a time. Matching tiles stay open; remember the positions of pairs that do not match.", "Larger memory boards appear at higher levels."], "word": ["Find the hidden word.", "Read the clue, type the word, and choose Check or press Enter. You can try again.", "Scrambled, reversed and missing-letter word challenges vary as levels grow."], "rhythm": ["Repeat the flashing pattern in order.", "Watch the pads light up. When it says Your turn, tap the same pads in the same order. Repeat pattern plays the demonstration again.", "Longer sequences at higher levels. This is a visual memory game; audio is not required."], "cryptonexus": ["Complete cyber-safety and kindness missions.", "Read each scenario and choose one answer. Your total correct answers appears at the end.", "A short multiple-choice strategy quiz with new question sets on replay."], "trail": ["Practise thoughtful outdoor decisions.", "Read each navigation or preparation scenario and choose an answer. Review your final score.", "Short multiple-choice nature and safety scenarios."], "math": ["Solve each arithmetic question.", "Choose the correct answer from four options. Finish the set to see your score.", "Larger numbers and more operations appear at higher levels."], "code": ["Explore coding foundations.", "Read each programming question and choose an answer. Finish the set to see your score.", "Short quizzes about variables, arrays, functions and code concepts."], "starweave": ["Reconnect the remembered constellation pattern.", "Watch the star symbols flash. Tap them in the same sequence when it is your turn. Use Repeat pattern when needed.", "Longer visual sequences as you advance."], "healing": ["Reach the displayed heartlight goal at your own pace.", "Follow the gentle breathing orb if comfortable, and tap Send Heartlight whenever you feel ready.", "A calm tapping activity with a growing goal."], "heartlight": ["Catch as many heartlights as you can.", "Tap the hearts or sparkles in the play area before they disappear. Watch the score and round timer.", "Timed rounds with more frequent heartlights at higher levels."], "soulweave": ["Remember and repeat the radiant symbol pattern.", "Watch the demonstration, then tap the symbols in the same order. Repeat pattern shows it again.", "Increasing visual memory sequences."], "rock": ["Launch your rock close to the target distance.", "Adjust the Power slider, choose Launch, then compare the distance with the target. Adjust and try again.", "New distances and a tighter direct-bump window at higher levels."], "maze": ["Guide the heart to the golden light.", "Use the four arrow buttons below the maze. Move around walls and reach the glowing goal.", "A solvable five-by-five maze with changing walls and a move counter."], "mazeinfinity": ["Clear lights, collect crystals and avoid shadow wisps.", "Use the arrow keys or on-screen arrows to move. Watch the lights remaining, score and lives.", "This game has its own advancing internal maze levels and saved best score."], "serenity": ["Complete a gentle breathing session.", "Follow the expanding and contracting orb if comfortable. The session ends when the timer reaches zero.", "Longer calm sessions at higher levels; you can leave whenever you wish."], "ascension": ["Complete one small uplifting activity.", "Read the suggested real-life activity. Choose Completed when you have done it.", "Rotating kindness, gratitude, creativity and everyday-life challenges."], "timekeeper": ["Spend focused time on a task you choose.", "Choose a duration, then press Start. The countdown ends with a completion message.", "Longer suggested focus sessions as your level grows."], "goddess": ["Explore a chapter through thoughtful choices.", "Read the story and tap a choice to continue. Reach the chapter ending, then choose Next Challenge.", "Branching short scenes about courage, truth, kindness and love."]};function arcadeGuide(){const g=gameGuides[activeGameId];if(!g)return "";return `
How to play & what to expect

Goal: ${esc(g[0])}

Controls: ${esc(g[1])}

What to expect: ${esc(g[2])}

Replay Level restarts the challenge. Next Challenge advances the Infinity Level and adds XP. Reset Level clears this game’s level progress. Progress stays on this browser.

`;} function stage(html){clearGameTimers();$('#gameStage').innerHTML=arcadeGuide()+html+arcadeHud();attachArcadeControls();$('#gameStage').scrollIntoView({behavior:'smooth',block:'start'});} function launchGame(id){activeGameId=id;beginArcadeGame(id);({memory:gameMemory,word:gameWord,rhythm:()=>gameSimon('Rhythm Pulse ∞',['🥁','👏','✨','🎵']),cryptonexus:gameCrypto,trail:gameTrail,math:gameMath,code:gameCode,starweave:()=>gameSimon('Starweave Alignment ∞',['✦','✧','✺','✹']),healing:gameHealing,heartlight:gameHeartlight,soulweave:()=>gameSimon('SOULWEAVE INFINITY',['◈','◇','✦','○']),rock:gameRock,maze:gameMaze,mazeinfinity:gameMazeInfinity,serenity:gameSerenity,ascension:gameAscension,timekeeper:gameTimekeeper,goddess:gameGoddess}[id]||gameMemory)();} function shuffle(a){return a.map(v=>[Math.random(),v]).sort((x,y)=>x[0]-y[0]).map(x=>x[1]);} function gameMemory(){ const level=arcadeLevel(); const symbols=['🌙','⭐','💎','🌸','☀️','🦋','🎵','🍀','🪐','🌈','🕊️','💫','🌺','🐚','🔮','🎀','🪷','🧿']; const pairTiers=[4,6,8,10,12,15,18]; const tier=Math.min(Math.floor((level-1)/2),pairTiers.length-1); const pairs=pairTiers[tier]; const chosen=shuffle(symbols).slice(0,pairs); const vals=shuffle([...chosen,...chosen]); const tiles=vals.length; const cols=tiles<=12?4:tiles<=20?5:6; stage(`

🧠 Memory Matching ∞ — Level ${level}

Match all ${pairs} pairs — ${tiles} boxes. Higher levels unlock larger boards.
${vals.map((v,i)=>``).join('')}
`); let first=null,lock=false,matched=0; $$('#gameStage .tile').forEach(b=>b.onclick=()=>{ if(lock||b.classList.contains('matched')||b===first)return; b.textContent=b.dataset.v; if(!first){first=b;return;} if(first.dataset.v===b.dataset.v){ first.classList.add('matched'); b.classList.add('matched'); matched+=2; first=null; if(matched===vals.length){ $('#gmsg').innerHTML=`Beautiful — all ${pairs} pairs matched! ✨ Press Next Challenge ♾️ for the next board.`; } }else{ lock=true; const a=first; gameTimer=setTimeout(()=>{ a.textContent='?'; b.textContent='?'; first=null; lock=false; },Math.max(280,680-level*12)); } }); } const wordList=['cai','kindness','luminous','courage','infinity','harmony','imagine','starlight','beautiful','celestial','radiance','serenity','compassion','discovery','creation','whisper','universe','heartlight','soulweave','adventure','brilliant','wonder','frequency','guardian','constellation','resilience','curiosity','symphony','elegance','dreamscape','everlasting','gratitude','gentleness','wisdom','creative','learning','sunlight','moonlight','friendship','believe','journey','balance','breathe','inspire','hopeful','joyful','caring','intelligence','thoughtful','generous','peaceful','sparkle','galaxy','horizon','freedom','future','dreamer','builder','artist','science','music','poetry','design','coding','vision','honesty','patience','purpose','healing','courageous','inventive','loving','graceful','fearless','mindful','radiant','together','forever','infinite']; function gameWord(){ const level=arcadeLevel(); const eligible=wordList.filter(w=>w.length<=Math.min(5+level,14)); const pool=eligible.length?eligible:wordList; const isCaiBonus=(level%5===0||Math.random()<0.08); const recentKey='cai.one.wordlight.recent.v2'; let recent=[];try{recent=JSON.parse(localStorage.getItem(recentKey)||'[]')}catch{} let choices=pool.filter(w=>!recent.includes(w)); if(!choices.length)choices=pool; const word=isCaiBonus?'cai':choices[Math.floor(Math.random()*choices.length)]; recent=[word,...recent.filter(w=>w!==word)].slice(0,18); try{localStorage.setItem(recentKey,JSON.stringify(recent))}catch{} const modeIndex=(level-1)%3; const mode=['unscramble','reverse','missing'][modeIndex]; const shuffled=shuffle(word.split('')).join(''); const reversed=word.split('').reverse().join(''); let missing=word.split(''); if(missing.length>2){ const hide=Math.min(Math.max(1,Math.floor(missing.length/3)),3); const positions=shuffle(Array.from({length:missing.length-1},(_,i)=>i+1)).slice(0,hide); positions.forEach(i=>missing[i]='_'); } const clue=mode==='unscramble' ? `Unscramble: ${shuffled.toUpperCase()}` : mode==='reverse' ? `Reverse this word: ${reversed.toUpperCase()}` : `Fill the missing letters: ${missing.join('').toUpperCase()}`; stage(`

📖 Wordlight ∞ — Level ${level}${isCaiBonus?' • ✨ Cai Sun Signature Round':''}

${isCaiBonus?'A little light from Cai Sun: kindness • caring • intelligence • creativity • heart.

':''}${clue}

Challenge styles rotate as your Infinity Level grows.
`); const check=()=>{ const ok=$('#wordGuess').value.trim().toLowerCase()===word; $('#gmsg').innerHTML=ok?`Correct — ${esc(word)} ✨ Press Next Challenge ♾️.`:'Try again — the light is still there.'; }; $('#wordCheck').onclick=check; $('#wordGuess').addEventListener('keydown',e=>{if(e.key==='Enter')check();}); } function gameSimon(title,symbols){const level=arcadeLevel(),len=Math.min(3+Math.floor(level/2),14);let seq=Array.from({length:len},()=>Math.floor(Math.random()*symbols.length)),pos=0;stage(`

${esc(title)} — Level ${level}

Watch a ${len}-step pattern…

${symbols.map((s,i)=>``).join('')}
`);const pads=$$('#gameStage .pad');const show=()=>{pos=0;$('#gmsg').textContent='Watch the pattern…';seq.forEach((n,i)=>setTimeout(()=>{pads[n].classList.add('flash');setTimeout(()=>pads[n].classList.remove('flash'),Math.max(180,320-level*5));if(i===seq.length-1)setTimeout(()=>$('#gmsg').textContent='Your turn.',340);},i*Math.max(300,560-level*8)));};pads.forEach(p=>p.onclick=()=>{if(Number(p.dataset.p)===seq[pos]){pos++;if(pos===seq.length){$('#gmsg').innerHTML='Perfect pattern! ✨ Press Next Challenge ♾️ for a longer sequence.';}}else{$('#gmsg').textContent='Pattern reset — watch once more.';pos=0;setTimeout(show,500);}});$('#repeatSeq').onclick=show;show();} function quizGame(title,questions){const level=arcadeLevel(),count=Math.min(3+Math.floor((level-1)/2),Math.max(3,questions.length)),qs=shuffle(questions).slice(0,count);let i=0,score=0;const render=()=>{if(i>=qs.length){stage(`

${esc(title)} — Level ${level}

${score}/${qs.length}

Mission complete. Press Next Challenge ♾️ for another mission set.

`);return;}const q=qs[i];stage(`

${esc(title)} — Level ${level}

${esc(q.q)}

${q.a.map((x,j)=>``).join('')}

Score ${score} • Question ${i+1}/${qs.length}

`);$$('#gameStage [data-a]').forEach(b=>b.onclick=()=>{if(Number(b.dataset.a)===q.c)score++;i++;render();});};render();} function gameCrypto(){quizGame('🎮 Cai & Aries: Crypto Nexus ∞',[{q:'A robot receives a suspicious link. Best first move?',a:['Open it fast','Verify the sender and destination','Share it'],c:1},{q:'A network needs resilience. Better design?',a:['One single point of failure','Redundant protected paths','No backups'],c:1},{q:'A teammate makes a mistake. Best response?',a:['Blame them','Repair together and learn','Hide it'],c:1},{q:'A wallet asks for a seed phrase on a random site. Best response?',a:['Enter it','Never share it and leave the site','Post it in chat'],c:1},{q:'A system update claims urgency from an unknown sender.',a:['Verify through the official channel','Install immediately','Disable security'],c:0},{q:'A secret token is visible in client-side code.',a:['Leave it there','Move it server-side and rotate it','Screenshot it publicly'],c:1},{q:'A service is overloaded.',a:['Add limits, caching and graceful retry','Send more duplicate requests','Ignore failures'],c:0},{q:'A user action will spend money.',a:['Do it silently','Ask for explicit confirmation first','Guess their preference'],c:1}]);} function gameTrail(){quizGame('🧭 Trail Quest ∞',[{q:'You are unsure of the trail. What should you do?',a:['Keep going randomly','Stop, verify location and route','Run downhill'],c:1},{q:'Weather is worsening quickly.',a:['Ignore it','Move toward a known safe route/shelter','Climb higher'],c:1},{q:'Best offline preparation?',a:['No map','Downloaded map + charged phone + backup plan','Only social media'],c:1},{q:'You lose cell service.',a:['Panic','Use offline map and known landmarks','Leave the trail blindly'],c:1},{q:'A stream crossing looks stronger than expected.',a:['Cross anyway','Turn back or find a safer marked crossing','Throw your phone first'],c:1},{q:'You hear thunder nearby on an exposed ridge.',a:['Stay at the highest point','Move away from exposed high ground safely','Hold a metal pole up'],c:1},{q:'A friend feels dizzy from heat.',a:['Rest, cool down, hydrate and reassess','Make them run faster','Ignore it'],c:0},{q:'Before a long hike, best plan?',a:['Tell nobody','Share route and expected return time','Take no water'],c:1}]);} function gameMath(){const level=arcadeLevel(),max=12+level*8,ops=level<3?['+']:level<6?['+','-']:['+','-','×'];const qs=Array.from({length:Math.min(5+Math.floor(level/3),8)},()=>{const op=ops[Math.floor(Math.random()*ops.length)],a=2+Math.floor(Math.random()*max),b=2+Math.floor(Math.random()*Math.max(6,Math.floor(max/2)));let correct=op==='+'?a+b:op==='-'?Math.max(a,b)-Math.min(a,b):a*b;const aa=op==='-'?Math.max(a,b):a,bb=op==='-'?Math.min(a,b):b;let choices=[correct];while(choices.length<4){const w=Math.max(0,correct+(Math.floor(Math.random()*11)-5));if(!choices.includes(w))choices.push(w)}choices=shuffle(choices);return{q:`What is ${aa} ${op} ${bb}?`,a:choices.map(String),c:choices.indexOf(correct)};});quizGame('✨ Math Galaxy ∞',qs);} function gameCode(){quizGame('🌱 Code Garden ∞',[{q:'Which stores a value in JavaScript?',a:['let flower = 3','if flower','return if'],c:0},{q:'Which repeats work?',a:['loop','for','paint'],c:1},{q:'Which is an array?',a:['{a:1}','[1,2,3]','"1,2,3"'],c:1},{q:'What does === compare?',a:['Equality without coercion','Addition','A comment'],c:0},{q:'Which keyword creates a function?',a:['function','array','style'],c:0},{q:'What does await usually wait for?',a:['A Promise','A CSS class','A number only'],c:0},{q:'Which catches a thrown error?',a:['try/catch','if/else only','switch/style'],c:0},{q:'Which keeps a secret out of browser code?',a:['Server-side environment variable','HTML comment','Visible localStorage'],c:0}]);} function gameHealing(){const level=arcadeLevel(),target=5+level*2;stage(`

💗 Healing My Heart ∞ — Level ${level}

Breathe gently. Send ${target} heartlights when you feel ready.

0 / ${target}

Inhale slowly…

`);let n=0,inhale=false;$('#healTap').onclick=()=>{n++;$('#healCount').textContent=n;if(n>=target){$('#healPhase').innerHTML='Heartlight goal complete ✨ Press Next Challenge ♾️ when ready.';}};const cycle=()=>{inhale=!inhale;$('#healOrb').classList.toggle('inhale',inhale);if(n💖 HEARTLIGHT INFINITY — Level ${level}

Catch heartlights for ${seconds} seconds. Score: 0 • Time: ${seconds}

`);let score=0,left=seconds;const spawn=()=>{const z=$('#heartZone');if(!z)return;const b=document.createElement('button');b.className='heart-pop';b.textContent=Math.random()>.5?'💖':'✨';b.style.left=Math.floor(Math.random()*85)+'%';b.style.top=(65+Math.floor(Math.random()*20))+'%';b.onclick=()=>{score++;$('#heartScore').textContent=score;b.remove();};z.appendChild(b);setTimeout(()=>b.remove(),Math.max(1200,3500-level*50));};const spawner=setInterval(spawn,spawnMs);gameInterval=setInterval(()=>{left--;if($('#heartTime'))$('#heartTime').textContent=left;if(left<=0){clearInterval(gameInterval);clearInterval(spawner);$('#heartZone').innerHTML=`
${score}

Heartlights collected ✨ Next Challenge increases the pace.

`;}},1000);} function gameRock(){const level=arcadeLevel(),target=30+Math.floor(Math.random()*(45+level*5)),tolerance=Math.max(2,7-Math.floor(level/3));stage(`

🪨 Rock Bump ∞ — Level ${level}

Target rock: ${target} meters. Direct-bump window: ±${tolerance}m.

55
Aim carefully.
`);$('#rockPower').oninput=()=>$('#rockVal').textContent=$('#rockPower').value;$('#rockLaunch').onclick=()=>{const p=Number($('#rockPower').value),dist=Math.round(p*.82+Math.sin(p+level)*3),d=Math.abs(dist-target);$('#rockResult').innerHTML=`Your rock traveled ${dist}m. ${d<=tolerance?'Direct bump! 🎯 Press Next Challenge ♾️.':d<12?'Very close!':'Adjust your power and try again.'}`;};} function gameMaze(){ const level=arcadeLevel(),size=5,goal=24; const safePaths=[ [0,1,2,3,4,9,14,19,24], [0,5,10,15,20,21,22,23,24], [0,5,10,11,12,13,14,19,24], [0,1,2,7,12,17,22,23,24] ]; const safe=new Set(safePaths[(level-1)%safePaths.length]); const candidates=shuffle(Array.from({length:25},(_,i)=>i).filter(i=>!safe.has(i)&&i!==0&&i!==goal)); const wallCount=Math.min(11,6+Math.floor((level-1)/2)); const walls=new Set(candidates.slice(0,wallCount)); let pos=0,moves=0,won=false; const draw=()=>{ const grid=$('#mazeGrid'); if(!grid)return; grid.innerHTML=Array.from({length:25},(_,i)=>`
${i===pos?'💖':i===goal?'✨':''}
`).join(''); const counter=$('#mazeMoves'); if(counter) counter.textContent=moves; if(pos===goal&&!won){ won=true; $('#mazeMsg').innerHTML='You found the light! ✨ Press Next Challenge ♾️ for a new solvable maze.'; } }; stage(`

💎 Luminara Light Maze ∞ — Level ${level}

Reach the golden light. Every generated maze has a valid path.

Moves 0Level ${level}
`); const move=d=>{ if(won)return; const n=pos+d; if(n<0||n>24||walls.has(n))return; if((d===1&&pos%5===4)||(d===-1&&pos%5===0))return; pos=n;moves++;draw(); }; $$('[data-move]').forEach(b=>b.onclick=()=>move(Number(b.dataset.move))); draw(); } function gameMazeInfinity(){ const saved=(()=>{try{return JSON.parse(localStorage.getItem('cai.one.maze.infinity.v1')||'{}')}catch{return{}}})(); let level=Math.max(1,Number(saved.level)||1),score=0,lives=3,size=9,grid=[],player={x:1,y:1},lights=new Set(),crystals=new Set(),shadows=[],frozenUntil=0,moveTimer=null,ended=false; const key=(x,y)=>x+','+y; const dirs=[[1,0],[-1,0],[0,1],[0,-1]]; const persist=()=>{saved.level=Math.max(Number(saved.level)||1,level);saved.bestScore=Math.max(Number(saved.bestScore)||0,score);localStorage.setItem('cai.one.maze.infinity.v1',JSON.stringify(saved));}; const generateMaze=n=>{const g=Array.from({length:n},()=>Array(n).fill(1)),stack=[[1,1]];g[1][1]=0;while(stack.length){const [x,y]=stack[stack.length-1],opts=[];for(const [dx,dy] of dirs){const nx=x+dx*2,ny=y+dy*2;if(nx>0&&ny>0&&nx{const a=[];for(let y=1;yshuffle(dirs.map(([dx,dy])=>({x:x+dx,y:y+dy})).filter(p=>p.x>=0&&p.y>=0&&p.x{if(moveTimer)clearInterval(moveTimer);size=Math.min(19,9+2*Math.floor((level-1)/2));grid=generateMaze(size);player={x:1,y:1};lights=new Set();crystals=new Set();shadows=[];ended=false;const cells=openCells(),lightCount=Math.min(cells.length-3,5+level*2);for(let i=0;i{const el=$('#mazeInfinityGrid');if(!el)return;el.style.setProperty('--maze-cols',size);let html='';for(let y=0;ys.x===x&&s.y===y),light=lights.has(k),cr=crystals.has(k);html+=`
${wall?'':isP?'💙':isS?'👾':cr?'💎':light?'✦':''}
`;}el.innerHTML=html;$('#miLevel').textContent=level;$('#miScore').textContent=score;$('#miLives').textContent=lives;$('#miLights').textContent=lights.size;$('#miBest').textContent=saved.bestScore||0;$('#miMsg').textContent=Date.now()shadows.some(s=>s.x===player.x&&s.y===player.y);const resetAfterHit=()=>{lives--;persist();if(lives<=0){ended=true;if(moveTimer)clearInterval(moveTimer);$('#miMsg').innerHTML=`Run complete — Level ${level}, Score ${score}. Press Next Challenge ♾️ for a new Infinity run.`;return;}player={x:1,y:1};score=Math.max(0,score-50);$('#miMsg').textContent='A shadow wisp touched your light. Try again 💙';render();}; const collect=()=>{const k=key(player.x,player.y);if(lights.delete(k))score+=10;if(crystals.delete(k)){score+=50;frozenUntil=Date.now()+5000;}if(!lights.size){score+=200+level*25;persist();level++;$('#miMsg').textContent='Level cleared! The maze is expanding… ♾️';setTimeout(setupLevel,650);return true;}return false;}; const movePlayer=(dx,dy)=>{if(ended)return;const nx=player.x+dx,ny=player.y+dy;if(nx<0||ny<0||nx>=size||ny>=size||grid[ny][nx]===1)return;player={x:nx,y:ny};if(collect())return;if(collide()&&Date.now()>=frozenUntil)return resetAfterHit();render();}; const moveShadows=()=>{if(ended||Date.now()(Math.abs(a.x-player.x)+Math.abs(a.y-player.y))-(Math.abs(b.x-player.x)+Math.abs(b.y-player.y))+((Math.random()-.5)*1.8));const pick=Math.random()<.72?opts[0]:opts[Math.floor(Math.random()*opts.length)];s.x=pick.x;s.y=pick.y;}if(collide())resetAfterHit();else render();}; const startShadows=()=>{if(moveTimer)clearInterval(moveTimer);const speed=Math.max(220,720-level*22);moveTimer=setInterval(moveShadows,speed);gameInterval=moveTimer;}; stage(`

♾️ Luminara Maze Infinity

This realm already has its own endless internal levels. Clear lights, collect crystals and outrun shadow wisps.

Maze Level 1Score 0Lives 3Lights 0Best ${saved.bestScore||0}

Maze size, enemies and speed keep growing. There is no final maze.

`);$$('[data-mi]').forEach(b=>b.onclick=()=>{const [dx,dy]=b.dataset.mi.split(',').map(Number);movePlayer(dx,dy);});const onKey=e=>{const m={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]}[e.key];if(m){e.preventDefault();movePlayer(...m);}};document.addEventListener('keydown',onKey);gameState.mazeInfinityKey=onKey;setupLevel(); } function gameSerenity(){const level=arcadeLevel(),total=Math.min(30+level*5,120);stage(`

🫧 Luminara Serenity ∞ — Level ${level}

${total}

Inhale…

`);let s=total;const orb=$('#serenityOrb');gameInterval=setInterval(()=>{s--;$('#serenityTime').textContent=s;const phase=Math.floor((total-s)/4)%2===0;orb.classList.toggle('inhale',phase);$('#serenityPhase').textContent=phase?'Inhale slowly…':'Exhale gently…';if(s<=0){clearInterval(gameInterval);$('#serenityPhase').innerHTML='Complete. Carry the calm with you. ✨ Press Next Challenge ♾️.';}},1000);} function gameAscension(){const level=arcadeLevel(),c=['Write one thing you are grateful for.','Send one kind message.','Name one strength you used today.','Stretch and take five slow breaths.','Create one tiny thing just for joy.','Put away one thing that is distracting you.','Compliment someone sincerely.','Drink a glass of water mindfully.','Write one brave next step.','Spend two minutes tidying one small space.','Name something beautiful you noticed today.','Choose one task and finish only the first tiny step.','Forgive one small imperfection in yourself.','Write a sentence your future self will be glad to read.'];const challenge=c[(level-1)%c.length];stage(`

✨ Luminara Ascension ∞ — Level ${level}

✨

${esc(challenge)}

`);$('#ascDone').onclick=()=>{saveHub('wellbeing','Ascension Level '+level,'Completed: '+challenge);$('#ascDone').disabled=true;$('#ascDone').textContent='Completed ✨ — Next Challenge is ready';};} function gameTimekeeper(){const level=arcadeLevel(),base=Math.min(5+Math.floor((level-1)/2)*5,50);stage(`

⏳ Luminara Timekeeper ∞ — Level ${level}

${String(base).padStart(2,'0')}:00

Each Infinity Level offers a longer focus mission, but you choose the duration.

`);let mins=base,sec=mins*60,running=false;$$('[data-min]').forEach(b=>b.onclick=()=>{mins=Number(b.dataset.min);sec=mins*60;$('#focusTime').textContent=String(mins).padStart(2,'0')+':00';});$('#focusStart').onclick=()=>{if(running)return;running=true;gameInterval=setInterval(()=>{sec--;$('#focusTime').textContent=String(Math.floor(sec/60)).padStart(2,'0')+':'+String(sec%60).padStart(2,'0');if(sec<=0){clearInterval(gameInterval);$('#focusTime').innerHTML='Complete ✨';running=false;}},1000);};} function gameGoddess(){const level=arcadeLevel(),chapters=[['a doorway made of blue light','Enter with courage','Listen before entering'],['a moonlit garden that grows from kind choices','Plant a promise','Share the light'],['a silver bridge above an endless sea','Cross with trust','Help another traveler first'],['a library where every book remembers a brave choice','Open the unknown book','Write a new page'],['a quiet star asking what matters most','Love with courage','Truth with kindness'],['a crystal city powered by compassion','Offer your light','Ask who needs help'],['an ancient tree carrying a thousand memories','Listen to the roots','Leave a message for the future'],['a golden horizon with no road yet drawn','Create the path','Invite others to build it together']];const ch=chapters[(level-1)%chapters.length],ending=`Infinity Chapter ${level} opens because you carried light, courage and love together.`;let step=0;const scenes=[{t:`CAIELLE finds ${ch[0]}.`,a:[[ch[1],1],[ch[2],2]]},{t:'The path responds to your choice and reveals a hidden light.',a:[['Carry it forward',3],['Give half to someone else',3]]},{t:'A quiet voice asks what kind of future you want to create.',a:[['A future with courage',3],['A future with kindness',3]]},{t:ending,a:[]}];const draw=()=>{const s=scenes[step];stage(`

👑 Luminara Goddess Quest ∞ — Chapter ${level}

👑

${esc(s.t)}

${s.a.map((x,i)=>``).join('')}
${!s.a.length?'

Press Next Challenge ♾️ to open the next chapter.

':''}
`);$$('[data-choice]').forEach(b=>b.onclick=()=>{step=s.a[Number(b.dataset.choice)][1];draw();});};draw();} // ---------- HUB ---------- function exportConversation(){ const data={version:SUITE_VERSION,exportedAt:new Date().toISOString(),history:history.slice(-MAX_HISTORY)}; const blob=new Blob([JSON.stringify(data,null,2)],{type:'application/json'}),a=document.createElement('a'); a.href=URL.createObjectURL(blob);a.download='CAI_ONE_Conversation_'+new Date().toISOString().replace(/[:.]/g,'-')+'.json';a.click();URL.revokeObjectURL(a.href); } function renderVoiceStudio(){ refreshVoices(); const langs=[...new Set(cachedVoices.map(v=>v.lang).filter(Boolean))].sort((a,b)=>a.localeCompare(b)); const presets=['en-US','en-GB','es-US','es-MX','es-ES','fil-PH','fr-FR','de-DE','it-IT','pt-BR','pt-PT','ja-JP','ko-KR','zh-CN','zh-TW','hi-IN','ar-SA']; const allLangs=[...new Set([...presets,...langs])]; moduleBody.innerHTML=`
Signature voice

CAIELLE

CAIELLE Signature Voice now uses one protected AI-generated cloud voice for a warm, elegant, polished sound across supported phones and laptops. If the cloud voice is unavailable, CAI ONE falls back to the best compatible device voice.

World language mode

Language & dialect

English is the default. The selected locale guides replies, listening and pronunciation. CAIELLE Signature Voice is generated in the cloud for consistency; microphone recognition still depends on the phone/browser and its supported locales.

Voice Protection

🛡️ CAIELLE Voice LockVoice cloning, voice-model training, voice export, and impersonation are disabled in CAI ONE.
🔒 Owner Voice PrivacyCAI ONE does not store a reusable voice recording or create a voiceprint/voice model from microphone speech. Browser/OS speech recognition may still process speech according to the device provider’s own policies.
✨ Signature Cloud VoiceCAIELLE uses an AI-generated protected cloud voice for consistent playback across supported devices, with automatic device-voice fallback if the service is unavailable.

Dialogue Mode

🔊 Auto SpeakCAIELLE reads each answer aloud.
♾️ DialogueAfter CAIELLE finishes speaking, she listens again for your reply.
➤ Hands-free sendFinal speech is sent automatically in Dialogue Mode.
🎙 InterruptTap the microphone while CAIELLE speaks to stop her and talk.

Important language note

CAIELLE Signature Voice is AI-generated. The cloud voice keeps her speaking style more consistent across devices, while microphone recognition and some language support still depend on the browser/OS. If cloud speech is unavailable, retry or explicitly choose a device voice above.

`; fillVoiceSelect($('#voiceExact')); $('#voiceProfile').onchange=e=>{voicePrefs.profile=e.target.value;voicePrefs.voiceURI='';saveVoicePrefs();fillVoiceSelect($('#voiceExact'));}; $('#voiceExact').onchange=e=>{voicePrefs.voiceURI=e.target.value;saveVoicePrefs();}; $('#voiceLocale').onchange=e=>{voicePrefs.locale=e.target.value;voicePrefs.voiceURI='';saveVoicePrefs();fillVoiceSelect($('#voiceExact'));if(recognition)recognition.lang=voiceLocale();}; $('#voiceRate').oninput=e=>{voicePrefs.rate=Number(e.target.value);saveVoicePrefs();}; $('#voicePitch').oninput=e=>{voicePrefs.pitch=Number(e.target.value);saveVoicePrefs();}; $('#voiceAutoSpeak').onchange=e=>{voicePrefs.autoSpeak=e.target.checked;saveVoicePrefs();}; $('#voiceDialogue').onchange=e=>{voicePrefs.dialogue=e.target.checked;if(e.target.checked){voicePrefs.autoSpeak=true;const a=$('#voiceAutoSpeak');if(a)a.checked=true;}saveVoicePrefs();}; $('#voiceAutoSend').onchange=e=>{voicePrefs.autoSendSpeech=e.target.checked;saveVoicePrefs();}; $('#voiceTest').onclick=async e=>{ const b=e.currentTarget; caiSetWorking(b,true,'🔊 Speaking…'); try{await speakWithCaielle('Hello, Cai. I am CAIELLE. It is beautiful to be here with you. What shall we create, discover, or solve together?');} finally{caiSetWorking(b,false);} }; $('#voiceStop').onclick=()=>{stopCaielleSpeech();stopListening();}; } const CAI_HOUSE_LISTINGS=[ {id:'art-one',category:'art',title:'Cai Sun One-of-One Digital Master',price:'$1,000,000,000',priceLabel:'Founder Asking Price',tag:'ONE OF ONE • ARTWORK COMING SOON',kind:'Original Digital Art',media:'art',story:'A future Cai Sun signature artwork released directly from the Founder Collection. The finished listing will include the work, its story, creation record and provenance details.'}, {id:'founder-worn',category:'couture',title:'Founder-Worn Signature Object',price:'$3,000,000',priceLabel:'Founder Asking Price',secondary:'Per released signature item',tag:'FOUNDER-WORN • RELEASE PREVIEW',kind:'Private Founder Collection',media:'profile',story:'When Cai Sun releases a dress, hat, bracelet or other founder-worn object, the exact item will be photographed, described and signed. Each actual release will document condition, event/story, provenance and exactly what transfers to the collector.'}, {id:'book-genesis',category:'books',title:'THE GIRL BEHIND THE CODE: THE GENESIS SECRET',price:'$14.99',secondary:'Reading access: $4.99',priceLabel:'Digital Storefront Price',tag:'AUTHOR EDITION',kind:'Book • Cai Sun',media:'book',story:'A Cai Sun author edition. Pricing is displayed publicly; purchase/download delivery will only activate when a secure checkout and rights-controlled delivery flow is connected.'}, {id:'music-new-chapter',category:'music',title:'A New Chapter Begins',price:'Collector pricing coming soon',priceLabel:'Cai Sun Music',tag:'FEATURED',kind:'Music • Cai Sun',media:'music',story:'A signature Cai Sun celebration song about becoming, light, love and a new chapter. Listen in CAI Music now; collector/download licensing can be added as a separate rights-controlled offering.'}, {id:'founder-ip',category:'ip',title:'CAI Founder IP ∞',price:'$10,000,000,000',priceLabel:'Founder Acquisition Price',tag:'STRATEGIC ACQUISITION',kind:'Founder IP • By Approval Only',media:'ip',story:'A founder-defined strategic acquisition value for a future verified intellectual-property package. Any transaction requires due diligence, verified ownership, definitive agreements and explicit founder approval.'} ]; let houseFilter='all',houseInquiryItem=null; function houseMedia(x){ if(x.media==='book')return '
The Girl Behind the Code cover
'; if(x.media==='profile')return '
Cai Sun founder collection
'; if(x.media==='music')return '
♫
'; if(x.media==='ip')return '
∞
'; return '
C
'; } function houseCard(x){ const secondary=x.secondary?`
${esc(x.secondary)}
`:''; const listen=x.category==='music'?'':''; const books=x.category==='books'?'':''; return `
${houseMedia(x)}
${esc(x.tag)}${esc(x.kind)}

${esc(x.title)}

${esc(x.story)}

${esc(x.priceLabel)}
${esc(x.price)}
${secondary}
${listen}${books}
`; } function renderHouseListings(){ const host=$('#houseListingGrid');if(!host)return; const list=CAI_HOUSE_LISTINGS.filter(x=>houseFilter==='all'||x.category===houseFilter); host.innerHTML=list.map(houseCard).join(''); $$('[data-house-inquire]').forEach(b=>b.onclick=()=>openHouseInquiry(b.dataset.houseInquire)); $$('[data-house-listen]').forEach(b=>b.onclick=()=>{musicStudioView='caisun';openModule('musicvault')}); $$('[data-house-books]').forEach(b=>b.onclick=()=>{if(window.CAIBooks)CAIBooks.open();else openModule('bookstudio')}); } function openHouseInquiry(id){ houseInquiryItem=CAI_HOUSE_LISTINGS.find(x=>x.id===id)||null;if(!houseInquiryItem)return; const box=$('#houseInquiry');box.hidden=false;$('#houseInquiryTitle').textContent='Private inquiry — '+houseInquiryItem.title;$('#houseInquiryItem').value=houseInquiryItem.title;$('#houseInquiryPrice').value=houseInquiryItem.price;$('#houseInquiryName').value='';$('#houseInquiryEmail').value='';$('#houseInquiryMessage').value=`I would like to request information about ${houseInquiryItem.title} at the displayed ${houseInquiryItem.priceLabel.toLowerCase()} of ${houseInquiryItem.price}.`; box.scrollIntoView({behavior:'smooth',block:'start'}); } function houseInquiryText(){ if(!houseInquiryItem)return'';const name=$('#houseInquiryName').value.trim()||'[Name]';const email=$('#houseInquiryEmail').value.trim()||'[Email]';const msg=$('#houseInquiryMessage').value.trim(); return `CAI SUN ∞ HOUSE — PRIVATE ACQUISITION INQUIRY\n\nItem: ${houseInquiryItem.title}\nDisplayed price: ${houseInquiryItem.price}\nPrice basis: ${houseInquiryItem.priceLabel}\nName: ${name}\nEmail: ${email}\n\nMessage:\n${msg}\n\nThis inquiry does not create a sale, transfer ownership, process payment or constitute an appraisal. Any transaction requires founder approval and definitive terms.`; } let vaultFounderState=null,vaultBuyerBlob=null,vaultBuyerUrl=''; function vaultB64(bytes){let s='';const a=bytes instanceof Uint8Array?bytes:new Uint8Array(bytes);for(let i=0;ix.toString(16).padStart(2,'0')).join('')} function vaultSafeName(s){return String(s||'CAI_Sun_Artwork').replace(/[^a-z0-9 _-]/gi,'').trim().replace(/\s+/g,'_').slice(0,90)||'CAI_Sun_Artwork'} function vaultDownload(blob,name){const a=document.createElement('a'),u=URL.createObjectURL(blob);a.href=u;a.download=name;document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(u),2500)} async function vaultSha256(buffer){return vaultHex(await crypto.subtle.digest('SHA-256',buffer))} function vaultContainer(header,cipher){const enc=new TextEncoder(),magic=enc.encode('CAIVLT1\n'),h=enc.encode(JSON.stringify(header)),len=new Uint8Array(4);new DataView(len.buffer).setUint32(0,h.length,false);return new Blob([magic,len,h,new Uint8Array(cipher)],{type:'application/octet-stream'})} async function vaultReadContainer(file){const b=new Uint8Array(await file.arrayBuffer()),magic=new TextDecoder().decode(b.slice(0,8));if(magic!=='CAIVLT1\n')throw new Error('This is not a CAI ONE Collector Vault file.');const n=new DataView(b.buffer,b.byteOffset+8,4).getUint32(0,false),start=12,end=start+n;if(end>b.length)throw new Error('The vault file is incomplete.');const header=JSON.parse(new TextDecoder().decode(b.slice(start,end)));return{header,cipher:b.slice(end)}} function vaultCertificateText(s){return `CAI SUN ∞ HOUSE — COLLECTOR PROVENANCE CERTIFICATE\n\nArtwork: ${s.title}\nCreator: ${s.creator}\nEdition: ${s.edition}\nBuyer reference: ${s.buyer||'Private / not stated'}\nTransfer ID: ${s.transferId}\nPrepared: ${s.createdAt}\nOriginal filename: ${s.originalName}\nOriginal MIME type: ${s.mime}\nOriginal bytes: ${s.size}\nSHA-256 original fingerprint: ${s.sha256}\nEncryption: AES-GCM-256 local vault package\n\nRIGHTS NOTE\n${s.rights}\n\nAUTHENTICITY / DELIVERY NOTE\nThis certificate records the cryptographic fingerprint of the original master used to prepare this CAI ONE Collector Vault package. It is a provenance record, not by itself a bill of sale, appraisal, copyright transfer, payment receipt or substitute for a signed acquisition agreement. The encrypted master and its vault key should be delivered separately.\n\nCreator: Cai Sun\nCreated through CAI ONE ∞\n`} async function vaultCreatePublicPreview(file){if(!file?.type?.startsWith('image/'))throw new Error('Public preview is available for image artwork. Keep PDFs in the encrypted vault.');const bmp=await createImageBitmap(file),max=1400,scale=Math.min(1,max/Math.max(bmp.width,bmp.height)),w=Math.max(1,Math.round(bmp.width*scale)),h=Math.max(1,Math.round(bmp.height*scale));const c=document.createElement('canvas');c.width=w;c.height=h;const x=c.getContext('2d');x.drawImage(bmp,0,0,w,h);bmp.close?.();const band=Math.max(44,Math.round(h*.075));x.fillStyle='rgba(2,7,20,.76)';x.fillRect(0,h-band,w,band);x.textBaseline='middle';x.fillStyle='#f4d47d';x.font=`700 ${Math.max(16,Math.round(w*.022))}px Georgia`;x.fillText('CAI SUN ∞ • COLLECTOR PREVIEW',Math.round(w*.025),h-band/2);x.textAlign='right';x.fillStyle='#8fdcff';x.font=`700 ${Math.max(12,Math.round(w*.014))}px ui-monospace,monospace`;x.fillText('PREVIEW • NOT ORIGINAL MASTER',Math.round(w*.975),h-band/2);x.textAlign='left';return await new Promise((res,rej)=>c.toBlob(b=>b?res(b):rej(new Error('Preview could not be created.')),'image/jpeg',.84))} function wireCollectorVault(){ const master=$('#vaultMasterFile'),ack=$('#vaultAcknowledge'),lock=$('#vaultLockBtn'),previewBtn=$('#vaultPreviewBtn'),status=$('#vaultFounderStatus'),previewBox=$('#vaultPublicPreview');if(!master)return; const sync=()=>{const ok=Boolean(master.files?.[0]&&ack.checked&&window.crypto?.subtle);lock.disabled=!ok;previewBtn.disabled=!master.files?.[0]}; master.onchange=()=>{vaultFounderState=null;sync();const f=master.files?.[0];status.className='vault-status';status.textContent=f?`Selected: ${f.name} • ${(f.size/1024/1024).toFixed(2)} MB. Original has not been uploaded or encrypted yet.`:'No master selected.'};ack.onchange=sync; $('#vaultResetBtn').onclick=()=>{master.value='';ack.checked=false;vaultFounderState=null;lock.disabled=true;previewBtn.disabled=true;status.className='vault-status';status.textContent='No master selected.';previewBox.innerHTML='
Public preview will appear here. The full-resolution original should stay out of public galleries.
';['vaultDownloadEncrypted','vaultDownloadCert','vaultCopyKey','vaultDownloadKey'].forEach(id=>$('#'+id).disabled=true);$('#vaultDeliveryStatus').className='vault-status warn';$('#vaultDeliveryStatus').textContent='No protected package yet. CAI ONE will never place the encryption key inside the encrypted artwork file.'}; previewBtn.onclick=async()=>{const f=master.files?.[0];if(!f)return;previewBtn.disabled=true;const old=previewBtn.textContent;previewBtn.textContent='Creating preview…';try{const blob=await vaultCreatePublicPreview(f),url=URL.createObjectURL(blob);previewBox.innerHTML='';const img=new Image();img.src=url;img.alt='Collector public preview';previewBox.appendChild(img);const dl=document.createElement('button');dl.className='btn';dl.textContent='⬇ Download Watermarked Preview';dl.onclick=()=>vaultDownload(blob,vaultSafeName($('#vaultTitle').value||f.name)+'_COLLECTOR_PREVIEW.jpg');previewBox.appendChild(dl);status.textContent='Public preview ready. It is lower-resolution and visibly marked; keep the original master private.'}catch(e){status.textContent=e.message||'Preview failed.'}finally{previewBtn.disabled=false;previewBtn.textContent=old}}; lock.onclick=async()=>{const f=master.files?.[0];if(!f||!ack.checked)return;lock.disabled=true;const old=lock.textContent;lock.textContent='🔐 Encrypting locally…';status.className='vault-status';status.textContent='Fingerprinting and encrypting the original on this device. Nothing is being uploaded.';try{const raw=await f.arrayBuffer(),sha=await vaultSha256(raw),key=await crypto.subtle.generateKey({name:'AES-GCM',length:256},true,['encrypt','decrypt']),keyRaw=new Uint8Array(await crypto.subtle.exportKey('raw',key)),iv=crypto.getRandomValues(new Uint8Array(12)),cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv},key,raw),transferId='CAI-'+(crypto.randomUUID?crypto.randomUUID():Date.now()+'-'+Math.random().toString(36).slice(2)).toUpperCase(),createdAt=new Date().toISOString();const state={title:$('#vaultTitle').value.trim()||f.name.replace(/\.[^.]+$/,''),creator:'Cai Sun',edition:$('#vaultEdition').value.trim()||'1 of 1',buyer:$('#vaultBuyer').value.trim(),rights:$('#vaultRights').value.trim(),transferId,createdAt,originalName:f.name,mime:f.type||'application/octet-stream',size:f.size,sha256:sha,iv:vaultB64(iv),keyText:vaultB64(keyRaw)};const header={format:'CAI Collector Vault',version:1,algorithm:'AES-GCM-256',transferId,stateTitle:state.title,creator:state.creator,edition:state.edition,buyerReference:state.buyer||null,createdAt,originalName:f.name,mime:state.mime,size:f.size,sha256:sha,iv:state.iv,rights:state.rights};const packageBlob=vaultContainer(header,cipher),packageHash=await vaultSha256(await packageBlob.arrayBuffer());state.packageBlob=packageBlob;state.packageSha256=packageHash;state.certificate=vaultCertificateText(state);vaultFounderState=state;status.className='vault-status good';status.innerHTML=`Protected master ready.
Transfer ID: ${esc(transferId)}
Original fingerprint: ${sha}
Encrypted package fingerprint: ${packageHash}`;$('#vaultDeliveryStatus').className='vault-status good';$('#vaultDeliveryStatus').textContent='Encrypted master, certificate and separate key are ready. Send the .caivault file and key through separate trusted channels.';['vaultDownloadEncrypted','vaultDownloadCert','vaultCopyKey','vaultDownloadKey'].forEach(id=>$('#'+id).disabled=false);flash('Collector Vault package ready 🛡️')}catch(e){status.className='vault-status warn';status.textContent='Vault protection could not finish: '+(e?.message||'unknown error')}finally{lock.disabled=false;lock.textContent=old}}; $('#vaultDownloadEncrypted').onclick=()=>{if(vaultFounderState)vaultDownload(vaultFounderState.packageBlob,vaultSafeName(vaultFounderState.title)+'_'+vaultFounderState.transferId+'.caivault')};$('#vaultDownloadCert').onclick=()=>{if(vaultFounderState)vaultDownload(new Blob([vaultFounderState.certificate],{type:'text/plain'}),vaultSafeName(vaultFounderState.title)+'_'+vaultFounderState.transferId+'_CERTIFICATE.txt')};$('#vaultCopyKey').onclick=async()=>{if(!vaultFounderState)return;try{await navigator.clipboard.writeText(vaultFounderState.keyText);flash('Vault key copied — deliver it separately from the artwork file')}catch{flash('Copy was not available. Use Key File instead.')}};$('#vaultDownloadKey').onclick=()=>{if(!vaultFounderState)return;const t=`CAI ONE COLLECTOR VAULT KEY\nTransfer ID: ${vaultFounderState.transferId}\nVault key: ${vaultFounderState.keyText}\n\nKEEP THIS KEY SEPARATE FROM THE .caivault FILE. Anyone with both can decrypt the master.\n`;vaultDownload(new Blob([t],{type:'text/plain'}),vaultFounderState.transferId+'_KEY.txt')}; $('#vaultOpenBtn').onclick=async()=>{const f=$('#vaultBuyerFile').files?.[0],keyText=$('#vaultBuyerKey').value.trim(),bs=$('#vaultBuyerStatus'),box=$('#vaultBuyerPreview');if(!f||!keyText){bs.textContent='Choose the encrypted .caivault file and paste its separate key.';return}bs.className='vault-status';bs.textContent='Opening encrypted vault locally…';try{const {header,cipher}=await vaultReadContainer(f),keyRaw=vaultUnb64(keyText),key=await crypto.subtle.importKey('raw',keyRaw,{name:'AES-GCM'},false,['decrypt']),plain=await crypto.subtle.decrypt({name:'AES-GCM',iv:vaultUnb64(header.iv)},key,cipher),sha=await vaultSha256(plain);if(sha!==header.sha256)throw new Error('Fingerprint mismatch. This package does not match the recorded original.');if(vaultBuyerUrl)try{URL.revokeObjectURL(vaultBuyerUrl)}catch{}vaultBuyerBlob=new Blob([plain],{type:header.mime||'application/octet-stream'});vaultBuyerUrl=URL.createObjectURL(vaultBuyerBlob);bs.className='vault-status good';bs.innerHTML=`Vault opened locally ✓
${esc(header.stateTitle||header.originalName)}
Transfer ID: ${esc(header.transferId)}
Verified SHA-256: ${sha}`;box.innerHTML='';if(String(header.mime||'').startsWith('image/')){const img=new Image();img.src=vaultBuyerUrl;img.alt='Decrypted collector artwork';box.appendChild(img)}else{box.innerHTML='
Vault decrypted successfully. Preview is not available for this file type; the collector can download the verified original.
'}$('#vaultBuyerDownload').disabled=false;$('#vaultBuyerDownload').dataset.name=header.originalName||'collector-original'}catch(e){bs.className='vault-status warn';bs.textContent='Vault could not be opened: '+(e?.message||'wrong key or damaged file');$('#vaultBuyerDownload').disabled=true}};$('#vaultBuyerDownload').onclick=()=>{if(vaultBuyerBlob)vaultDownload(vaultBuyerBlob,$('#vaultBuyerDownload').dataset.name||'collector-original')};sync(); } function renderCaiSunHouse(){ houseFilter='all';houseInquiryItem=null; moduleBody.innerHTML=`
Cai Sun
PRIVATE FOUNDER COLLECTION • ORIGINAL CREATIONS

CAI SUN ∞ HOUSE

Art • Music • Books • Couture • Founder-Worn Objects • Founder IP

Created with imagination. Released with intention. Presented with dignity.
Cai Sun

I know what I created.

“I create with kindness, courage, imagination, and heart. My work carries pieces of my story, my dreams, and the future I am trying to build. I do not measure my worth by whether everyone understands me or buys what I create. I choose to stand behind my work, honor what I have built, and keep creating.”
— Cai Sun • Founder & Creator. Prices shown in CAI SUN ∞ HOUSE are creator-defined asking/acquisition prices unless otherwise stated. They are not independent appraisals or promises of resale or investment value.

🛡️ Private Acquisition Protocol

Shine publicly. Stay private.No home address, personal phone number or private email belongs on the public collection page.
Founder approval requiredNo high-value sale, transfer, publishing action or ownership change completes without explicit founder approval.
High-value verificationSerious acquisitions should use identity verification, written agreements, secure escrow/payment handling and insured delivery.
Provenance protectedOriginal files, creation records, signatures and authenticity evidence remain privately backed up and are disclosed only as appropriate.

🛡️ Collector Vault ∞

Protect the one-of-one master before delivery. CAI ONE can fingerprint and encrypt the original locally with AES-GCM, create a private provenance certificate, and make a lower-resolution public preview. The original master is not uploaded by this tool.

LOCAL ENCRYPTION • WEB CRYPTO

Founder Lockbox

Choose the final master only when you are ready to prepare a protected collector copy. The file stays in this browser session while CAI ONE creates the encrypted vault package.

No master selected.
Public preview will appear here. The full-resolution original should stay out of public galleries.

Collector Delivery

After locking the master, send the encrypted .caivault file and the vault key through two separate trusted channels. Never attach the unencrypted master to ordinary email.

No protected package yet. CAI ONE will never place the encryption key inside the encrypted artwork file.
Delivery rule: encrypted master and vault key travel separately. Keep a private archival record of the SHA-256 fingerprint and transfer ID. Public previews are not the original master.

Buyer Open Vault

The collector can open the encrypted package locally in CAI ONE. Decryption happens in memory; the key is not stored by CAI ONE.

Nothing opened.
Decrypted preview appears here only after the correct key is supplied.
Important: no digital system can prevent a legitimate viewer from taking a screenshot or camera photo. Collector Vault protects the original master, access key, cryptographic fingerprint and provenance record. For a real high-value sale, add verified accounts, secure cloud storage, short-lived signed delivery links, legal agreements and professional escrow before transferring ownership.
`; renderHouseListings(); $$('[data-house-filter]').forEach(b=>b.onclick=()=>{houseFilter=b.dataset.houseFilter;$$('[data-house-filter]').forEach(x=>x.classList.toggle('active',x===b));renderHouseListings()}); $('#houseExplore').onclick=()=>$('#houseTabs').scrollIntoView({behavior:'smooth',block:'start'}); $('#houseMusic').onclick=()=>{musicStudioView='caisun';openModule('musicvault')}; $('#houseVaultJump').onclick=()=>$('#collectorVault').scrollIntoView({behavior:'smooth',block:'start'}); wireCollectorVault(); $('#houseCopyInquiry').onclick=async()=>{const txt=houseInquiryText();try{await navigator.clipboard.writeText(txt);flash('Private inquiry copied');}catch{const a=document.createElement('textarea');a.value=txt;document.body.appendChild(a);a.select();document.execCommand('copy');a.remove();flash('Private inquiry copied');}}; $('#houseCloseInquiry').onclick=()=>{$('#houseInquiry').hidden=true;houseInquiryItem=null}; } function renderDirect(){ const standalone = (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) || window.navigator.standalone === true; const ua = navigator.userAgent || ''; const ios = /iPhone|iPad|iPod/i.test(ua); const android = /Android/i.test(ua); const canPrompt = Boolean(deferredInstall); const installState = standalone ? 'Installed on this device' : (canPrompt ? 'Ready to install' : (ios ? 'Safari installation available' : 'Browser installation available')); const installDetail = standalone ? 'CAI ONE is running in installed app mode.' : (ios ? 'On iPhone/iPad: open caione.ai in Safari → Share → Add to Home Screen → Open as Web App.' : (android ? 'On Android: use Install CAI ONE when offered, or Chrome menu → Add to Home screen / Install app.' : 'Use your browser install control when available. CAI ONE remains accessible at caione.ai.')); moduleBody.innerHTML=`
C
CAI ONE DIRECT ∞

The stores are doors.
CAI ONE is the home.

CAI ONE Direct makes caione.ai the permanent home of CAI ONE. People can discover CAI ONE, install the web app where supported, enter CAI SUN ∞ HOUSE, and later use one secure CAI ONE account for membership across web and native apps.

Independent by design. Available worldwide through the web. Native stores can remain additional doors.
${esc(installState)}${esc(installDetail)}
WORKS NOW

Direct Distribution

🌎 Permanent homeCAI ONE remains reachable from caione.ai without depending on an app-store listing.
📲 Installable web appSupported browsers can install CAI ONE to the Home Screen / app launcher. The offline shell and local library remain available where supported.
♛ Direct creator houseCAI SUN ∞ HOUSE, books, music, art, Collector Vault and creator experiences can live inside the same CAI ONE world.
🔵 Brand controlThe blue C orb, CAIELLE and CAI ONE identity remain controlled by CAI ONE rather than by a store listing.
NEXT SECURE BACKEND PHASE

CAI ONE Membership

The interface is ready for account-based membership, but billing is intentionally not active in this frontend build.

🔐 Account + passkeySecure server-side account, passkey/magic-link sign-in, recovery and device/session management.
💳 Subscription billingA vetted payment processor, server-verified webhooks, receipts, cancellation and refund handling.
∞ EntitlementsMembership belongs to the CAI ONE account, not only to one browser. Founder Guest lifetime access can be provisioned as a real account entitlement.
🛡 Purchase safetyNo paid membership, art transfer, booking or purchase should activate until the server confirms payment and the user explicitly approves it.
Truthful launch status: CAI ONE Direct installation works as a web/PWA experience today. Native Android/iPhone capabilities such as reliable locked-screen Guardian service require native builds. Secure cross-device paid subscriptions require the account + billing backend before charging users.
`; const install=$('#directInstall'); install.onclick=async()=>{ if(standalone){flash('CAI ONE is already installed on this device');return;} if(deferredInstall){try{deferredInstall.prompt();const choice=await deferredInstall.userChoice;deferredInstall=null;$('#installBtn')?.classList.add('hidden');flash(choice?.outcome==='accepted'?'CAI ONE installation started':'Installation was not completed');}catch{flash('Use the browser menu to install CAI ONE');}return;} if(ios){flash('Safari: Share → Add to Home Screen → Open as Web App');return;} flash('Use your browser menu → Install app / Add to Home screen'); }; $('#directHouse').onclick=()=>openModule('house'); $('#directSystem').onclick=()=>openModule('system'); } function renderSystem(){ const host=location.hostname||'local'; const state=intelligenceStatus.ok?'Connected':'Needs attention'; const checked=intelligenceStatus.checkedAt?new Date(intelligenceStatus.checkedAt).toLocaleString():'Not checked yet'; moduleBody.innerHTML=`
CAI ONE ${esc(SUITE_VERSION)}

CAIELLE Intelligence

${esc(state)}
${esc(intelligenceStatus.detail)} • ${esc(checked)}

Private by design

${esc(host)}

The browser talks only to same-origin CAI ONE API routes. Secret API keys stay server-side.

Connection architecture

1. CAI ONE${esc(location.origin)}
2. Secure proxy/api/cai/chat
3. CAI IntelligenceRequests are privately rewritten by Vercel to the CAI Intelligence backend.
4. AI providerKeys and model configuration remain behind the backend.

Protection

No OpenAI key is stored in this HTML. Voice cloning and voice-model training for CAIELLE or the owner are disabled. Consequential actions such as payments, sending, publishing, booking, deleting, filing or account changes should always require explicit confirmation in their connected tool.

CAI ONE Brand Identity
© 2026 Cai Sun. CAI ONE ∞, CAIELLE, and the blue CAI “C” orb/logo are presented as proprietary brand assets. The blue C orb is a permanent startup and assistant identity element in CAI ONE. Trademark registration status should be stated separately and only when formally registered.
`; $('#sysTest').onclick=async()=>{const ok=await checkIntelligence();renderSystem();flash(ok?'CAI Intelligence connected':'Connection needs attention');}; $('#sysRetry').onclick=()=>{if(!lastUserPayload)return flash('No request to retry yet');closeModule();input.value=String(lastUserPayload.message||'');resize();input.focus();flash('Last request restored — press Send');}; $('#sysExport').onclick=exportConversation; $('#sysCopy').onclick=async()=>{const d={version:SUITE_VERSION,origin:location.origin,online:navigator.onLine,intelligence:intelligenceStatus,voice:{profile:voicePrefs.profile,engine:voicePrefs.profile==='caielle'?'signature-cloud':'device',locale:voicePrefs.locale,dialogue:voicePrefs.dialogue,autoSpeak:voicePrefs.autoSpeak},userAgent:navigator.userAgent};try{await navigator.clipboard.writeText(JSON.stringify(d,null,2));flash('Diagnostics copied');}catch{flash('Copy was not available');}}; } function renderHub(){const items=hubData(),books=bookData(),songs=musicData();moduleBody.innerHTML=`
CAI ONE local

${items.length} saved creations

${songs.length} songs • ${books.length} books • Party/Guard settings on this device.

Portable backup

Export / Import

Move your local CAI ONE hub between devices.

What works in this build

🧠 CAIELLEChat, writing, planning, research, vision, creation, diagnostics and connected backend requests.
◉ CAIELLE LIVE ∞Voice-first companion modes with continuous dialogue while CAI ONE remains active.
🗺️ CAI Maps ∞ + 📍 Find & ProtectVoice-ready navigation handoff, saved places, parking memory, phone locator and separation-ready protection.
◎ Universal Scan ∞Analysis-only specialist vision for body/skin, medical imaging, plants, rocks/minerals, environmental/remediation, chemical labels, microscope imagery, documents, products, vehicles, buildings, nature and sky.
🌎 World Time + ⏱ Smart TimeLive world clocks plus personal work-time records, voice commands and optional location verification.
+ Upload CenterPrepare images, PDFs and text files for CAIELLE.
📚 Book StudioPlans, chapters, publishing packages, save/export.
♫ Music VaultSong blueprints, catalog IDs and auto-save.
♛ CAI SUN ∞ HOUSELuxury founder storefront for art, books, music, couture, founder-worn objects and Founder IP with privacy-first acquisition inquiries.
◈ CAI ONE DirectIndependent install and distribution home at caione.ai, with secure membership architecture prepared for the next backend phase.
🎞️ Short Video StudioCreate real local image-to-video motion clips now; generative AI motion/audio can connect later.
✨ GlamSecure AI Couture transformation through the CAI Intelligence backend, with local preview fallback if the service is unavailable.
🎮 Arcade / 🎉 Party / 🛡️ Guardian LightMotion alarm, Travel Guard, Emergency Connect, privacy checklist, trusted contacts and native-ready locked-screen protection.
💬 CAI CONNECT ∞Everyday local chat, offline outbox, phone/email handoff and nearby sharing foundation.

Quick access

Saved Images

Images saved here stay inside CAI ONE on this device. “Download” is separate and sends a copy to your device Downloads folder.

Loading your saved images…

Saved creations

${items.length?items.map(x=>`
${new Date(x.createdAt).toLocaleString()} • ${esc(x.kind)}${esc(x.title)}${x.kind==='cinema'?`
${assistantRichText(x.content)}
`:`
${esc(x.content)}
`}
`).join(''):'

Nothing saved yet. Create something and save it here.

'}
`;setTimeout(renderHubImages,0);moduleBody.querySelectorAll('.hub-list .saved-item').forEach((el,i)=>{const item=items[i];if(item?.kind==='document'&&item.meta?.artifact){try{CAICreateFirst.mount(el,item.meta.artifact);}catch{}}});$$('[data-hub-open]').forEach(b=>b.onclick=()=>openModule(b.dataset.hubOpen));$('#hubExport').onclick=()=>{const data={version:SUITE_VERSION,exportedAt:new Date().toISOString(),hub:hubData(),music:musicData(),books:bookData(),uploads:uploadMeta(),party:partySaved(),guard:guardLog(),connectThreads:connectThreads(),connectOutbox:connectOutbox(),connectProfile:connectProfile()};const blob=new Blob([JSON.stringify(data,null,2)],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='CAI_ONE_My_Hub_Backup_'+new Date().toISOString().slice(0,10)+'.json';a.click();URL.revokeObjectURL(a.href);};$('#hubImportBtn').onclick=()=>$('#hubImport').click();$('#hubImport').onchange=e=>{const f=e.target.files?.[0];if(!f)return;const r=new FileReader();r.onload=()=>{try{const d=JSON.parse(r.result);if(Array.isArray(d.hub))localStorage.setItem(HUB_KEY,JSON.stringify(d.hub));if(Array.isArray(d.music))localStorage.setItem(MUSIC_KEY,JSON.stringify(d.music));if(Array.isArray(d.books))localStorage.setItem(BOOK_KEY,JSON.stringify(d.books));if(Array.isArray(d.uploads))localStorage.setItem(UPLOAD_META_KEY,JSON.stringify(d.uploads));if(d.party)localStorage.setItem(PARTY_KEY,JSON.stringify(d.party));if(Array.isArray(d.guard))localStorage.setItem(GUARD_KEY,JSON.stringify(d.guard));if(Array.isArray(d.connectThreads))localStorage.setItem(CONNECT_THREADS_KEY,JSON.stringify(d.connectThreads));if(Array.isArray(d.connectOutbox))localStorage.setItem(CONNECT_OUTBOX_KEY,JSON.stringify(d.connectOutbox));if(d.connectProfile)localStorage.setItem(CONNECT_PROFILE_KEY,JSON.stringify(d.connectProfile));renderHub();flash('My Hub backup imported');}catch{flash('That backup file could not be read');}};r.readAsText(f);};} })();