Changesets · Branches · Tags · Compare
| Changeset | 7539d8cfd64c1759f2aeca5175265132ce361700246f61e53bf7bf0c380e5a71 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-07-15 11:16 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-07-15 11:16 +02:00 |
| Parents | 1804cf8342e8 |
3 files changed
added core/ceo.js +245 −0
| @@ -0,0 +1,245 @@ | ||
| 1 | +// Cerebro CEO autónomo (compartido por Elffuss Code y Elffuss Claw): cuando el | |
| 2 | +// usuario NO está pidiendo nada (ocioso) y hay un modelo local cargado, la elfa | |
| 3 | +// «trabaja por su cuenta» — revisa el espacio de trabajo, reparte el trabajo en | |
| 4 | +// varios perfiles que piensan EN PARALELO (cada uno una línea de pensamiento en | |
| 5 | +// la vista Mente) y sintetiza propuestas de mejora. | |
| 6 | +// | |
| 7 | +// Agnóstico de herramientas a propósito: cada app inyecta su propio adaptador | |
| 8 | +// de workspace (`init({ workspace, ... })`) — Code usa code.js (proyecto de | |
| 9 | +// código), Claw usa fs.js (carpetas con permiso). El core no sabe ni le importa | |
| 10 | +// cuál es. | |
| 11 | +// | |
| 12 | +// Seguridad: NO modifica tus ficheros. Deja las propuestas en una carpeta | |
| 13 | +// aditiva (nunca toca lo existente) y las hace «flotar» en la Mente. Se PARA en | |
| 14 | +// cuanto detecta actividad del usuario y reanuda al volver a estar ocioso. | |
| 15 | +import { Agent } from './agent.js'; | |
| 16 | +import { humanizeTool } from './humanize.js'; | |
| 17 | + | |
| 18 | +const IDLE_MS = 18000; // 18 s sin actividad → el CEO se pone a trabajar | |
| 19 | +const TICK_MS = 3000; // frecuencia de comprobación | |
| 20 | +// 5 min entre ciclos automáticos: con 45s, una tarde ociosa generaba MILES de | |
| 21 | +// ficheros. «Pensar ahora» (forceCycle) sigue disponible sin esperar esto. | |
| 22 | +const COOLDOWN_MS = 300000; | |
| 23 | +const SOUL_CAP = 25; // ficheros sueltos antes de consolidar en archivo.md | |
| 24 | + | |
| 25 | +// perfil por defecto si la app anfitriona no da los suyos | |
| 26 | +const GENERIC_PROFILES = [ | |
| 27 | + { id: 'p1', name: 'Revisión', focus: 'qué mejorar de forma concreta y accionable', color: '#7c5cff' }, | |
| 28 | + { id: 'p2', name: 'Calidad', focus: 'errores, casos borde, cosas que podrían fallar', color: '#49e8ff' }, | |
| 29 | +]; | |
| 30 | + | |
| 31 | +const slug = s => String(s).toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '') | |
| 32 | + .replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '').slice(0, 24) || 'perfil'; | |
| 33 | + | |
| 34 | +// ── namespace (localStorage) y adaptador de workspace: los da la app anfitriona ── | |
| 35 | +let NS = 'elffuss'; // prefijo de las claves de localStorage | |
| 36 | +let ws = null; // { isReady, tree, write, read, list, remove } | |
| 37 | +let getProvider = () => null; | |
| 38 | +let isBusy = () => false; // ¿el usuario tiene trabajo en cola/procesándose? → prioridad | |
| 39 | +let defaultProfiles = GENERIC_PROFILES; | |
| 40 | +const K = suffix => NS + '.' + suffix; | |
| 41 | + | |
| 42 | +function loadProfiles() { | |
| 43 | + try { const s = JSON.parse(localStorage.getItem(K('ceoProfiles'))); if (Array.isArray(s) && s.length) return s; } catch { /* */ } | |
| 44 | + return defaultProfiles.map(p => ({ ...p })); | |
| 45 | +} | |
| 46 | +let profiles = null; | |
| 47 | +export function getProfiles() { if (!profiles) profiles = loadProfiles(); return profiles; } | |
| 48 | +export function setProfiles(list) { | |
| 49 | + const used = new Set(); | |
| 50 | + profiles = (list || []).filter(p => p && p.name).map(p => { | |
| 51 | + let id = p.id || slug(p.name); let n = id, i = 2; | |
| 52 | + while (used.has(n)) n = id + '-' + i++; | |
| 53 | + used.add(n); | |
| 54 | + return { id: n, name: String(p.name).slice(0, 40), focus: String(p.focus || '').slice(0, 200), color: /^#[0-9a-f]{6}$/i.test(p.color || '') ? p.color : '#7c5cff' }; | |
| 55 | + }); | |
| 56 | + if (!profiles.length) profiles = defaultProfiles.map(p => ({ ...p })); | |
| 57 | + try { localStorage.setItem(K('ceoProfiles'), JSON.stringify(profiles)); } catch { /* */ } | |
| 58 | + emit('ceo', { type: 'reprogram', text: 'Perfiles actualizados: ' + profiles.map(p => p.name).join(', '), profiles }); | |
| 59 | + return profiles; | |
| 60 | +} | |
| 61 | + | |
| 62 | +let enabled = false, running = false, lastActivity = Date.now(), timer = null, lastCycleEnd = 0, cycleN = 0; | |
| 63 | + | |
| 64 | +// MISIÓN reprogramable: el usuario puede reorientar el cerebro desde la Mente | |
| 65 | +// («céntrate en seguridad», «optimiza mis Excel», «documenta todo»…). | |
| 66 | +let DEFAULT_MISSION = 'Revisar el espacio de trabajo y proponer mejoras concretas y accionables.'; | |
| 67 | +let mission = null; | |
| 68 | +function ensureMission() { if (mission == null) { try { mission = localStorage.getItem(K('ceoMission')) || DEFAULT_MISSION; } catch { mission = DEFAULT_MISSION; } } } | |
| 69 | +export function getMission() { ensureMission(); return mission; } | |
| 70 | +export function setMission(text) { | |
| 71 | + mission = (text || '').trim() || DEFAULT_MISSION; | |
| 72 | + try { localStorage.setItem(K('ceoMission'), mission); } catch { /* */ } | |
| 73 | + emit('ceo', { type: 'reprogram', text: 'Nueva misión recibida: ' + mission }); | |
| 74 | + lastCycleEnd = 0; lastActivity = Date.now() - IDLE_MS; // que arranque un ciclo pronto con la nueva misión | |
| 75 | + return mission; | |
| 76 | +} | |
| 77 | + | |
| 78 | +// Carpeta-«alma» donde el cerebro crea y guarda TODO (configurable). | |
| 79 | +let DEFAULT_SOUL = '.elffuss/soul'; | |
| 80 | +let soulDir = null; | |
| 81 | +function ensureSoulDir() { if (soulDir == null) { try { soulDir = localStorage.getItem(K('ceoDir')) || DEFAULT_SOUL; } catch { soulDir = DEFAULT_SOUL; } } } | |
| 82 | +export function getSoulDir() { ensureSoulDir(); return soulDir; } | |
| 83 | +export function setSoulDir(dir) { | |
| 84 | + soulDir = (dir || '').trim().replace(/^\/+|\/+$/g, '') || DEFAULT_SOUL; | |
| 85 | + try { localStorage.setItem(K('ceoDir'), soulDir); } catch { /* */ } | |
| 86 | + emit('ceo', { type: 'reprogram', text: 'Nueva carpeta-alma: ' + soulDir + '/' }); | |
| 87 | + return soulDir; | |
| 88 | +} | |
| 89 | + | |
| 90 | +// ── semáforo cross-pestaña: UN SOLO cerebro ejecuta, TODAS visualizan ─────── | |
| 91 | +// El líder tiene un Web Lock exclusivo (se libera solo al cerrar la pestaña); | |
| 92 | +// difunde sus pensamientos por BroadcastChannel para que el resto los vea. | |
| 93 | +// (Aislado por origen por el propio navegador: Code y Claw nunca se cruzan.) | |
| 94 | +let isLeader = false, bc = null, realEmit = () => {}, crossTabWired = false; | |
| 95 | +function initCrossTab() { | |
| 96 | + if (crossTabWired) return; | |
| 97 | + crossTabWired = true; | |
| 98 | + try { | |
| 99 | + bc = new BroadcastChannel(NS + '-ceo'); | |
| 100 | + bc.onmessage = e => { if (e.data && e.data.kind === 'thought') realEmit(e.data.channel, e.data.ev); }; | |
| 101 | + } catch { /* sin BroadcastChannel */ } | |
| 102 | + if (navigator.locks && navigator.locks.request) { | |
| 103 | + navigator.locks.request(NS + '-ceo-leader', { mode: 'exclusive' }, () => new Promise(() => { isLeader = true; })) | |
| 104 | + .catch(() => { isLeader = true; }); | |
| 105 | + } else { isLeader = true; } | |
| 106 | +} | |
| 107 | +function emit(channel, ev) { | |
| 108 | + realEmit(channel, ev); | |
| 109 | + try { bc && bc.postMessage({ kind: 'thought', channel, ev }); } catch { /* ev no serializable */ } | |
| 110 | +} | |
| 111 | + | |
| 112 | +// init({ workspace, provider, onEvent, isBusy, namespace, defaultProfiles, defaultMission, defaultSoulDir }) | |
| 113 | +export function init(opts = {}) { | |
| 114 | + if (opts.workspace) ws = opts.workspace; | |
| 115 | + if (opts.provider) getProvider = opts.provider; | |
| 116 | + if (opts.onEvent) realEmit = opts.onEvent; | |
| 117 | + if (opts.isBusy) isBusy = opts.isBusy; | |
| 118 | + if (opts.namespace) NS = opts.namespace; | |
| 119 | + if (opts.defaultProfiles) defaultProfiles = opts.defaultProfiles; | |
| 120 | + if (opts.defaultMission) DEFAULT_MISSION = opts.defaultMission; | |
| 121 | + if (opts.defaultSoulDir) DEFAULT_SOUL = opts.defaultSoulDir; | |
| 122 | + initCrossTab(); | |
| 123 | +} | |
| 124 | +export function isThisTabLeader() { return isLeader; } | |
| 125 | +export function noteActivity() { lastActivity = Date.now(); if (running) running = 'interrupt'; } | |
| 126 | +export function isEnabled() { return enabled; } | |
| 127 | +export function isRunning() { return !!running; } | |
| 128 | +// Play/stop: persistido AQUÍ (fuente única) — cualquier botón que lo toque | |
| 129 | +// queda sincronizado, y la elección sobrevive a recargar la página. | |
| 130 | +export function wasEnabledLastSession() { try { return localStorage.getItem(K('ceoEnabled')) === '1'; } catch { return false; } } | |
| 131 | +// ¿el usuario llegó a decidir alguna vez (play o stop)? Distingue «nunca lo | |
| 132 | +// tocó» de «lo pausó a propósito» — solo lo primero debe auto-activarse al | |
| 133 | +// abrir la Mente; lo segundo hay que RESPETARLO, no pisarlo. | |
| 134 | +export function hasDecided() { try { return localStorage.getItem(K('ceoEnabled')) != null; } catch { return false; } } | |
| 135 | +export function enable() { | |
| 136 | + if (enabled) return; | |
| 137 | + enabled = true; lastActivity = Date.now(); schedule(); | |
| 138 | + try { localStorage.setItem(K('ceoEnabled'), '1'); } catch { /* */ } | |
| 139 | + emit('sys', { type: 'status', text: 'CEO en guardia — trabajaré cuando estés ocioso' }); | |
| 140 | +} | |
| 141 | +export function disable() { | |
| 142 | + enabled = false; running = false; if (timer) clearTimeout(timer); | |
| 143 | + try { localStorage.setItem(K('ceoEnabled'), '0'); } catch { /* */ } | |
| 144 | + emit('sys', { type: 'status', text: 'CEO en pausa' }); | |
| 145 | +} | |
| 146 | + | |
| 147 | +function schedule() { if (timer) clearTimeout(timer); timer = setTimeout(tick, TICK_MS); } | |
| 148 | + | |
| 149 | +// «Pensar ahora» — salta la espera de ociosidad. Sigue respetando el | |
| 150 | +// semáforo: si otra pestaña es la líder, no compite por la GPU. | |
| 151 | +export async function forceCycle() { | |
| 152 | + if (!isLeader) { emit('ceo', { type: 'paused', text: 'Otra pestaña lleva el cerebro — ábrela ahí para forzar un ciclo.' }); return false; } | |
| 153 | + if (running) return false; | |
| 154 | + // isReady() puede ser síncrona (Code: handle en memoria) o async (Claw: consulta IndexedDB) — se espera siempre. | |
| 155 | + if (!(await ws?.isReady()) || !getProvider()) { emit('ceo', { type: 'paused', text: 'Necesito un espacio de trabajo abierto y un modelo cargado.' }); return false; } | |
| 156 | + try { await runCycle(); } finally { lastCycleEnd = Date.now(); } | |
| 157 | + return true; | |
| 158 | +} | |
| 159 | + | |
| 160 | +async function tick() { | |
| 161 | + if (!enabled) return; | |
| 162 | + const idle = Date.now() - lastActivity; | |
| 163 | + const rested = Date.now() - lastCycleEnd > COOLDOWN_MS; | |
| 164 | + const mightRun = isLeader && !running && !isBusy() && idle >= IDLE_MS && rested && getProvider(); | |
| 165 | + if (mightRun && await ws?.isReady()) { | |
| 166 | + try { await runCycle(); } catch { /* siguiente ciclo */ } | |
| 167 | + lastCycleEnd = Date.now(); | |
| 168 | + } | |
| 169 | + schedule(); | |
| 170 | +} | |
| 171 | + | |
| 172 | +// helper: corre el agente con el proveedor actual sobre un prompt, emitiendo | |
| 173 | +// tokens/herramientas a un canal. Devuelve el texto final. Las tool-calls pasan | |
| 174 | +// SIEMPRE por el mismo runTool que usa el chat normal (Agent.handle real). | |
| 175 | +async function think(channel, task) { | |
| 176 | + const prov = getProvider(); | |
| 177 | + if (!prov) return ''; | |
| 178 | + const a = new Agent({ chat: (h, s, cb) => prov.chat(h, s, cb) }); | |
| 179 | + let out = ''; | |
| 180 | + await a.handle(task, ev => { | |
| 181 | + if (running === 'interrupt') throw new Error('interrumpido'); | |
| 182 | + if (ev.type === 'token') { out += ev.text; emit(channel, { type: 'token', text: ev.text }); } | |
| 183 | + else if (ev.type === 'tool') emit(channel, { type: 'tool', text: humanizeTool(ev.call.tool, ev.call.args), tool: ev.call.tool, path: ev.call.args?.path || null }); | |
| 184 | + else if (ev.type === 'tool_result') emit(channel, { type: 'tool_result', tool: ev.tool, text: String(ev.result || '').replace(/\s+/g, ' ').trim().slice(0, 100) }); | |
| 185 | + else if (ev.type === 'text') { out = ev.text; } | |
| 186 | + }); | |
| 187 | + return out; | |
| 188 | +} | |
| 189 | + | |
| 190 | +async function runCycle() { | |
| 191 | + running = true; | |
| 192 | + cycleN++; | |
| 193 | + emit('ceo', { type: 'cycle', n: cycleN, text: 'Nuevo ciclo: reviso el espacio de trabajo y reparto el trabajo…' }); | |
| 194 | + | |
| 195 | + let tree = ''; | |
| 196 | + try { tree = await ws.tree({ depth: 2 }); } catch { /* sin workspace */ } | |
| 197 | + emit('ceo', { type: 'survey', text: 'Panorama captado (' + tree.split('\n').length + ' entradas). Delegando…' }); | |
| 198 | + | |
| 199 | + const brief = (d) => `MISIÓN del equipo (fijada por el usuario): ${getMission()}\n` + | |
| 200 | + `Eres el jefe de ${d.name}. Dentro de esa misión, céntrate en: ${d.focus}. ` + | |
| 201 | + `Explora lo mínimo con tus herramientas y propón UNA mejora CONCRETA y accionable, ` + | |
| 202 | + `entendible por un humano. Sé breve. No modifiques nada existente: solo la propuesta.`; | |
| 203 | + const proposals = await Promise.all(getProfiles().map(async d => { | |
| 204 | + emit(d.id, { type: 'open', name: d.name, focus: d.focus }); | |
| 205 | + try { const p = await think(d.id, brief(d)); emit(d.id, { type: 'done', text: p }); return { dept: d.name, text: p }; } | |
| 206 | + catch { emit(d.id, { type: 'done', text: '(interrumpido)' }); return null; } | |
| 207 | + })); | |
| 208 | + if (running === 'interrupt') { running = false; emit('ceo', { type: 'paused', text: 'Vuelves tú — dejo lo mío y te cedo el mando.' }); return; } | |
| 209 | + | |
| 210 | + const valid = proposals.filter(Boolean).filter(p => p.text && p.text.length > 8); | |
| 211 | + const md = `# Propuestas de mejora — ciclo ${cycleN}\n\n**Misión:** ${getMission()}\n\n` + | |
| 212 | + valid.map(p => `## ${p.dept}\n${p.text}\n`).join('\n') + | |
| 213 | + `\n_— generado por el cerebro CEO de Elffuss mientras estabas ocioso._\n`; | |
| 214 | + const d = new Date(); | |
| 215 | + const stamp = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}`; | |
| 216 | + const topic = slug((valid[0]?.text || 'ciclo').split(/[.,;\n]/)[0]) || 'ciclo'; | |
| 217 | + const path = `${getSoulDir()}/${stamp}-${topic}.md`; | |
| 218 | + try { | |
| 219 | + await rotateSoul(); | |
| 220 | + await ws.write({ path, content: md }); | |
| 221 | + emit('ceo', { type: 'built', text: `Propuesta guardada en ${path}`, path, md, proposals: valid }); | |
| 222 | + } catch (e) { | |
| 223 | + emit('ceo', { type: 'built', text: 'Propuesta lista (no pude escribir el fichero)', md, proposals: valid }); | |
| 224 | + } | |
| 225 | + running = false; | |
| 226 | +} | |
| 227 | + | |
| 228 | +// Rotación: si hay demasiados ficheros sueltos, los MÁS ANTIGUOS se consolidan | |
| 229 | +// (recopilan) en un único archivo.md y se borran — para no acabar con miles. | |
| 230 | +async function rotateSoul() { | |
| 231 | + try { | |
| 232 | + const soul = getSoulDir(); | |
| 233 | + const names = (await ws.list(soul)).filter(n => n.endsWith('.md') && n !== 'archivo.md'); | |
| 234 | + if (names.length < SOUL_CAP) return; | |
| 235 | + names.sort(); // el nombre empieza por fecha → orden cronológico | |
| 236 | + const excess = names.slice(0, names.length - SOUL_CAP + 1); | |
| 237 | + let archive = ''; try { archive = await ws.read({ path: `${soul}/archivo.md` }); } catch { archive = '# Archivo histórico del cerebro\n'; } | |
| 238 | + for (const name of excess) { | |
| 239 | + try { archive += `\n---\n## ${name}\n${await ws.read({ path: `${soul}/${name}` })}\n`; } catch { /* */ } | |
| 240 | + } | |
| 241 | + await ws.write({ path: `${soul}/archivo.md`, content: archive.slice(-80000) }); | |
| 242 | + for (const name of excess) { try { await ws.remove(soul, name); } catch { /* */ } } | |
| 243 | + emit('ceo', { type: 'reprogram', text: `Consolidé ${excess.length} propuestas antiguas en archivo.md` }); | |
| 244 | + } catch { /* soulDir aún sin crear o sin permiso: nada que rotar */ } | |
| 245 | +} |
added core/humanize.js +48 −0
| @@ -0,0 +1,48 @@ | ||
| 1 | +// Frase legible por humano para una tool-call («leyendo app.js…»). Compartido | |
| 2 | +// por el cerebro CEO (ceo.js) y el streaming en vivo del chat — así nunca se | |
| 3 | +// le enseña JSON crudo al usuario, siempre la misma redacción. Cubre los | |
| 4 | +// nombres de herramienta de Elffuss Code (code.*, terminal.*) y de Elffuss | |
| 5 | +// Claw (fs.*, app.*, web.*, skill.*, memory.*, tasks.*) — un tool desconocido | |
| 6 | +// cae al genérico «nombre argumento» sin romper nada. | |
| 7 | +export function humanizeTool(name, args) { | |
| 8 | + const p = args?.path, q = args?.query, c = args?.command, n = args?.name; | |
| 9 | + switch (name) { | |
| 10 | + case 'code.read': case 'fs.read': return `leyendo ${p}…`; | |
| 11 | + case 'code.write': case 'fs.write': return `escribiendo ${p}…`; | |
| 12 | + case 'code.tree': return `explorando ${p || 'el proyecto'}…`; | |
| 13 | + case 'fs.list': return `explorando ${p || 'la carpeta'}…`; | |
| 14 | + case 'code.search': return `buscando «${q}»…`; | |
| 15 | + case 'fs.pick_folder': return 'pidiendo acceso a una carpeta…'; | |
| 16 | + case 'fs.copy': return `copiando ${args?.pattern || 'archivos'}…`; | |
| 17 | + case 'fs.watch': return `vigilando ${args?.from || 'una carpeta'}…`; | |
| 18 | + case 'terminal.run': return `ejecutando: ${c}`; | |
| 19 | + case 'app.create': return `creando la app «${n}»…`; | |
| 20 | + case 'app.open': return `abriendo la app «${n}»…`; | |
| 21 | + case 'skill.create': return `creando la skill «${n}»…`; | |
| 22 | + case 'memory.save': return `recordando: ${args?.fact}…`; | |
| 23 | + case 'tasks.add': return 'programando una tarea…'; | |
| 24 | + case 'web.search': return `buscando en internet «${q}»…`; | |
| 25 | + case 'web.images': return `buscando imágenes de «${q}»…`; | |
| 26 | + case 'web.fetch': return `leyendo ${p || args?.url}…`; | |
| 27 | + default: return name + (p || q || c || n ? ' ' + (p || q || c || n) : ''); | |
| 28 | + } | |
| 29 | +} | |
| 30 | + | |
| 31 | +// Detecta si el buffer que va llegando EN STREAMING ha entrado en un bloque de | |
| 32 | +// tool-call (```tool { … }) y, si es así, devuelve una frase humana en vez del | |
| 33 | +// JSON crudo — «preparando una acción…» hasta que el nombre de la tool sea | |
| 34 | +// legible, luego «leyendo app.js…» tan pronto como el campo aparezca, aunque | |
| 35 | +// el JSON todavía no haya cerrado. | |
| 36 | +export function humanizeStreamPreview(buf) { | |
| 37 | + if (buf.search(/```/) === -1 && !/^\s*\{\s*"tool"/.test(buf)) return null; | |
| 38 | + const toolM = buf.match(/"tool"\s*:\s*"([\w.]+)"/); | |
| 39 | + if (!toolM) return 'preparando una acción…'; | |
| 40 | + const pathM = buf.match(/"path"\s*:\s*"((?:[^"\\]|\\.)*)"/); | |
| 41 | + const queryM = buf.match(/"query"\s*:\s*"((?:[^"\\]|\\.)*)"/); | |
| 42 | + const cmdM = buf.match(/"command"\s*:\s*"((?:[^"\\]|\\.)*)"/); | |
| 43 | + const nameM = buf.match(/"name"\s*:\s*"((?:[^"\\]|\\.)*)"/); | |
| 44 | + const out = humanizeTool(toolM[1], { path: pathM?.[1], query: queryM?.[1], command: cmdM?.[1], name: nameM?.[1] }); | |
| 45 | + // el nombre de la tool ya se ve pero su campo (path/query/…) aún no llegó: | |
| 46 | + // mejor el genérico que un «leyendo undefined…» a medio streamear | |
| 47 | + return /undefined/.test(out) ? 'preparando una acción…' : out; | |
| 48 | +} |
added core/mind.js +609 −0
| @@ -0,0 +1,609 @@ | ||
| 1 | +// Vista «Mente de Elffuss» — el pensamiento subyacente del cerebro CEO en un | |
| 2 | +// mundo 3D de fantasía psicodélica trance, con la CIUDAD real del proyecto | |
| 3 | +// (motor VibeCodeViewer) flotando por debajo. | |
| 4 | +// · cada línea/tool-call que llega nace como una ESTRELLA de texto (color por | |
| 5 | +// PERFIL, tamaño/tipografía según lo que ocurre) que se desvanece sola. | |
| 6 | +// · los perfiles (nombre, foco, color) se editan desde ⚙ — el usuario los crea | |
| 7 | +// a su gusto. | |
| 8 | +// · «≡ historial»: panel con TODO lo que ha llegado, sin recortar. | |
| 9 | +// · cuando lee/escribe un fichero real, un haz baja hasta él en la ciudad. | |
| 10 | +// · overlay PERSISTENTE (música/animación no reinician al salir y volver). | |
| 11 | +import * as THREE from 'three'; | |
| 12 | +import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; | |
| 13 | +import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; | |
| 14 | +import { RenderPass } from 'three/addons/postprocessing/RenderPass.js'; | |
| 15 | +import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js'; | |
| 16 | +import { OutputPass } from 'three/addons/postprocessing/OutputPass.js'; | |
| 17 | +import * as ceo from './ceo.js'; | |
| 18 | +import * as db from './db.js'; | |
| 19 | +import { renderMarkdown } from './md.js'; | |
| 20 | + | |
| 21 | +const SOUNDCLOUD = 'https://soundcloud.com/dekel-official/dekel-baoba-festival-2023'; | |
| 22 | +const CEO_COLOR = '#ff4d8d'; | |
| 23 | + | |
| 24 | +let open = false, built = false, raf = null; | |
| 25 | +let overlay, S, widget, onOpenFile = () => {}, onExecute = () => {}; | |
| 26 | +// Ciudad de fondo (vista real del workspace) y semilla de pensamientos previos: | |
| 27 | +// AMBOS opcionales e inyectados por la app anfitriona — Code tiene un motor | |
| 28 | +// VibeCodeViewer sobre su proyecto único; Claw (v1) no lo ofrece y la Mente | |
| 29 | +// funciona igual de bien sin ciudad de fondo. | |
| 30 | +let loadThoughts = async () => []; // () => [{path, md}] | |
| 31 | +let buildCityFn = null; // (scene) => {cityWrap, cityCity, cityModel} | null | |
| 32 | +export function init({ loadThoughts: lt, buildCity: bc } = {}) { | |
| 33 | + if (lt) loadThoughts = lt; | |
| 34 | + if (bc) buildCityFn = bc; | |
| 35 | +} | |
| 36 | +let anchorMap = new Map(); // id de perfil (+ 'ceo') → Vector3 (anclas del mundo) | |
| 37 | +const anchors = []; // { el, pos } — solo etiquetas de propuestas forjadas | |
| 38 | +let nodesGroup, thoughtNodes = []; | |
| 39 | +let starGroup, stars = []; // estrellas de pensamiento efímeras | |
| 40 | +const lineBuf = new Map(); // canal → texto acumulado hasta la línea completa | |
| 41 | +const streamed = new Map(); // canal → ¿llegaron tokens? (evita duplicar el texto final) | |
| 42 | +let cityWrap = null, cityCity = null, cityModel = null; | |
| 43 | +let beams = [], fileActivity = []; | |
| 44 | + | |
| 45 | +export function isOpen() { return open; } | |
| 46 | +export function setOpenFile(fn) { onOpenFile = fn; } | |
| 47 | +export function setExecuteProposal(fn) { onExecute = fn; } | |
| 48 | + | |
| 49 | +const escHtml = s => String(s).replace(/[<>&]/g, c => ({ '<': '<', '>': '>', '&': '&' }[c])); | |
| 50 | +const profileOf = channel => channel === 'ceo' | |
| 51 | + ? { id: 'ceo', name: 'CEO', color: CEO_COLOR } | |
| 52 | + : ceo.getProfiles().find(p => p.id === channel) || { id: channel, name: channel, color: '#7c5cff' }; | |
| 53 | + | |
| 54 | +// ── música con Widget API (persistente: pausa al salir, reanuda al volver) ── | |
| 55 | +function mountMusic(root) { | |
| 56 | + const wrap = document.createElement('div'); | |
| 57 | + wrap.className = 'mind-music'; | |
| 58 | + const url = 'https://w.soundcloud.com/player/?url=' + encodeURIComponent(SOUNDCLOUD) + | |
| 59 | + '&auto_play=true&hide_related=true&show_comments=false&show_user=false&show_reposts=false&visual=false&color=%23ff4d8d'; | |
| 60 | + wrap.innerHTML = '<iframe id="mind-sc" title="música" width="100%" height="120" frameborder="no" allow="autoplay" src="' + url + '"></iframe>' + | |
| 61 | + '<div class="mind-music-cap">▶ Dekel · Baoba Festival — modo trance</div>'; | |
| 62 | + root.appendChild(wrap); | |
| 63 | + const iframe = wrap.querySelector('#mind-sc'); | |
| 64 | + const initWidget = () => { try { widget = window.SC.Widget(iframe); } catch { /* aún no */ } }; | |
| 65 | + if (window.SC && window.SC.Widget) initWidget(); | |
| 66 | + else { const s = document.createElement('script'); s.src = 'https://w.soundcloud.com/player/api.js'; s.onload = initWidget; document.head.appendChild(s); } | |
| 67 | +} | |
| 68 | + | |
| 69 | +// ══ ESTRELLAS de pensamiento: cada línea/tool-call nace, brilla y se apaga ══ | |
| 70 | +function makeTextSprite(text, color, { fontSize = 16, bold = false, glow = 10 } = {}) { | |
| 71 | + const pad = 8; | |
| 72 | + const probe = document.createElement('canvas').getContext('2d'); | |
| 73 | + probe.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`; | |
| 74 | + const w = Math.ceil(probe.measureText(text).width) + pad * 2; | |
| 75 | + const h = fontSize + pad * 2; | |
| 76 | + const cv = document.createElement('canvas'); cv.width = w; cv.height = h; | |
| 77 | + const g = cv.getContext('2d'); | |
| 78 | + g.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`; | |
| 79 | + g.textBaseline = 'middle'; | |
| 80 | + g.shadowColor = color; g.shadowBlur = glow; | |
| 81 | + g.fillStyle = color; | |
| 82 | + g.fillText(text, pad, h / 2 + 1); | |
| 83 | + const tex = new THREE.CanvasTexture(cv); | |
| 84 | + const mat = new THREE.SpriteMaterial({ map: tex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }); | |
| 85 | + const sprite = new THREE.Sprite(mat); | |
| 86 | + const scale = 0.09; | |
| 87 | + sprite.scale.set(w * scale, h * scale, 1); | |
| 88 | + return sprite; | |
| 89 | +} | |
| 90 | + | |
| 91 | +// kind: 'line' (charla normal) · 'tool' (tool-call) · 'event' (ciclo/estado) · 'built' (propuesta forjada) | |
| 92 | +const KIND_STYLE = { | |
| 93 | + line: { fontSize: 13, bold: false, glow: 8, life: 6, jitter: 15 }, | |
| 94 | + tool: { fontSize: 17, bold: true, glow: 16, life: 9, jitter: 9 }, | |
| 95 | + event: { fontSize: 20, bold: true, glow: 14, life: 7, jitter: 6 }, | |
| 96 | + built: { fontSize: 26, bold: true, glow: 22, life: 13, jitter: 4 }, | |
| 97 | +}; | |
| 98 | +function spawnStar(channel, text, kind = 'line') { | |
| 99 | + if (!starGroup || !text) return; | |
| 100 | + const prof = profileOf(channel); | |
| 101 | + const st = KIND_STYLE[kind] || KIND_STYLE.line; | |
| 102 | + const anchor = anchorMap.get(prof.id) || new THREE.Vector3(0, 20, 0); | |
| 103 | + const j = st.jitter; | |
| 104 | + const label = kind === 'tool' ? '⟐ ' + text : kind === 'event' ? '★ ' + text : kind === 'built' ? '✦ ' + text : text; | |
| 105 | + const sprite = makeTextSprite(label.slice(0, kind === 'line' ? 52 : 72), prof.color, st); | |
| 106 | + sprite.position.copy(anchor).add(new THREE.Vector3((Math.random() - 0.5) * j, (Math.random() - 0.5) * j * 0.6, (Math.random() - 0.5) * j)); | |
| 107 | + sprite.material.opacity = 0; | |
| 108 | + starGroup.add(sprite); | |
| 109 | + stars.push({ obj: sprite, born: elapsed, life: st.life, seed: Math.random() * 1000, up: kind === 'built' ? 0.5 : 0.22 }); | |
| 110 | + if (stars.length > 160) { const old = stars.shift(); starGroup.remove(old.obj); old.obj.material.map.dispose(); old.obj.material.dispose(); } | |
| 111 | +} | |
| 112 | + | |
| 113 | +// ── historial COMPLETO (todo lo que llega, sin recortar) — PERSISTENTE: antes | |
| 114 | +// vivía solo en el DOM/memoria y una recarga de página lo borraba entero. | |
| 115 | +const LOG_CAP = 500; | |
| 116 | +let logHistory = []; // [{channel, text}] — se guarda en IndexedDB | |
| 117 | +let logSaveTimer = null; | |
| 118 | +function saveLogSoon() { | |
| 119 | + clearTimeout(logSaveTimer); | |
| 120 | + logSaveTimer = setTimeout(() => db.set('kv', 'mindLog', logHistory).catch(() => {}), 400); | |
| 121 | +} | |
| 122 | +function renderLogRow(channel, text) { | |
| 123 | + const body = document.getElementById('mind-log-body'); | |
| 124 | + if (!body) return; | |
| 125 | + const prof = profileOf(channel); | |
| 126 | + const row = document.createElement('div'); | |
| 127 | + row.className = 'ml-row'; | |
| 128 | + row.innerHTML = `<span class="ml-dot" style="background:${prof.color}"></span><b style="color:${prof.color}">${escHtml(prof.name)}</b> <span class="ml-t">${escHtml(text)}</span>`; | |
| 129 | + body.appendChild(row); | |
| 130 | + while (body.children.length > LOG_CAP) body.removeChild(body.firstChild); | |
| 131 | + body.scrollTop = body.scrollHeight; | |
| 132 | +} | |
| 133 | +function logLine(channel, text) { | |
| 134 | + logHistory.push({ channel, text }); | |
| 135 | + if (logHistory.length > LOG_CAP) logHistory = logHistory.slice(-LOG_CAP); | |
| 136 | + saveLogSoon(); | |
| 137 | + renderLogRow(channel, text); | |
| 138 | +} | |
| 139 | +async function loadPersistedLog() { | |
| 140 | + try { | |
| 141 | + const saved = await db.get('kv', 'mindLog'); | |
| 142 | + if (!Array.isArray(saved) || !saved.length) return; | |
| 143 | + logHistory = saved; | |
| 144 | + for (const { channel, text } of saved) renderLogRow(channel, text); | |
| 145 | + } catch { /* aún no hay historial guardado */ } | |
| 146 | +} | |
| 147 | + | |
| 148 | +function flushLine(channel, force = false) { | |
| 149 | + const buf = (lineBuf.get(channel) || '').trim(); | |
| 150 | + if (!buf && !force) return; | |
| 151 | + if (buf) { spawnStar(channel, buf, 'line'); logLine(channel, buf); } | |
| 152 | + lineBuf.set(channel, ''); | |
| 153 | +} | |
| 154 | + | |
| 155 | +// alimenta estrellas + historial + haces sobre la ciudad (ceo.js → aquí) | |
| 156 | +export function pushThought(channel, ev) { | |
| 157 | + if (!open) return; | |
| 158 | + if (channel === 'sys') { logLine('ceo', ev.text); return; } | |
| 159 | + if (channel === 'ceo') { | |
| 160 | + if (ev.type === 'cycle') { logLine('ceo', '● ' + ev.text); spawnStar('ceo', ev.text, 'event'); } | |
| 161 | + else if (ev.type === 'survey') { logLine('ceo', ev.text); } | |
| 162 | + else if (ev.type === 'reprogram') { logLine('ceo', '⚙ ' + ev.text); spawnStar('ceo', ev.text, 'event'); if (ev.profiles) rebuildWorld(); } | |
| 163 | + else if (ev.type === 'paused') { logLine('ceo', ev.text); spawnStar('ceo', ev.text, 'event'); } | |
| 164 | + else if (ev.type === 'built') { logLine('ceo', '✦ ' + ev.text); spawnStar('ceo', ev.text, 'built'); addThoughtNode(ev); } | |
| 165 | + else logLine('ceo', ev.text || ''); | |
| 166 | + return; | |
| 167 | + } | |
| 168 | + if (ev.type === 'open') { lineBuf.set(channel, ''); streamed.set(channel, false); } | |
| 169 | + else if (ev.type === 'token') { | |
| 170 | + streamed.set(channel, true); | |
| 171 | + lineBuf.set(channel, (lineBuf.get(channel) || '') + ev.text); | |
| 172 | + const buf = lineBuf.get(channel); | |
| 173 | + if (/\n/.test(ev.text) || buf.length > 90) flushLine(channel); | |
| 174 | + } else if (ev.type === 'tool') { | |
| 175 | + flushLine(channel); | |
| 176 | + spawnStar(channel, ev.text, 'tool'); | |
| 177 | + logLine(channel, '⟐ ' + ev.text); | |
| 178 | + if (ev.path) fileBeam(ev.path, /escrib/i.test(ev.text) ? 'write' : 'read'); | |
| 179 | + } else if (ev.type === 'tool_result') { | |
| 180 | + // el RESULTADO real de la tool (lo que de verdad se leyó/escribió/ejecutó), | |
| 181 | + // enlazado justo debajo de su tool-call — no solo el nombre de la acción. | |
| 182 | + const t = '→ ' + (ev.text || '(sin salida)'); | |
| 183 | + spawnStar(channel, t, 'line'); | |
| 184 | + logLine(channel, t); | |
| 185 | + } else if (ev.type === 'done') { | |
| 186 | + flushLine(channel, true); | |
| 187 | + // el proveedor puede devolver el texto final SIN pasar por tokens (sin | |
| 188 | + // streaming) → si no vimos ningún token, esto es lo único que lo muestra. | |
| 189 | + if (ev.text && !streamed.get(channel)) { spawnStar(channel, ev.text, 'line'); logLine(channel, ev.text); } | |
| 190 | + } | |
| 191 | +} | |
| 192 | + | |
| 193 | +// ── nodos de pensamiento clicables (cada .md forjado = un punto brillante) ── | |
| 194 | +function addThoughtNode({ path, md, text }) { | |
| 195 | + if (!nodesGroup) return; | |
| 196 | + const i = thoughtNodes.length; | |
| 197 | + const a = i * 2.399963; // ángulo áureo | |
| 198 | + const r = 30 + i * 5; | |
| 199 | + const mesh = new THREE.Mesh( | |
| 200 | + new THREE.IcosahedronGeometry(3.2, 0), | |
| 201 | + new THREE.MeshBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.95, blending: THREE.AdditiveBlending, depthWrite: false })); | |
| 202 | + mesh.position.set(Math.cos(a) * r, 6 + Math.sin(i * 0.7) * 10, Math.sin(a) * r); | |
| 203 | + mesh.userData = { path, md, text }; | |
| 204 | + nodesGroup.add(mesh); | |
| 205 | + thoughtNodes.push(mesh); | |
| 206 | + const lab = document.createElement('div'); | |
| 207 | + lab.className = 'mind-node-label'; | |
| 208 | + lab.textContent = (path || 'pensamiento').split('/').pop(); | |
| 209 | + // clicable ella misma — antes SOLO el raycast contra la diminuta malla 3D | |
| 210 | + // abría el panel, fácil de fallar; la etiqueta es el blanco visible real. | |
| 211 | + lab.addEventListener('click', () => selectThoughtNode(mesh)); | |
| 212 | + document.getElementById('mind-anchors').appendChild(lab); | |
| 213 | + anchors.push({ el: lab, pos: mesh.position }); | |
| 214 | + mesh.userData.label = lab; | |
| 215 | +} | |
| 216 | + | |
| 217 | +async function loadExistingThoughts() { | |
| 218 | + try { for (const it of await loadThoughts()) addThoughtNode(it); } catch { /* aún no hay */ } | |
| 219 | +} | |
| 220 | + | |
| 221 | +// selección de un nodo de propuesta — desde la malla 3D (raycast) o su etiqueta | |
| 222 | +function selectThoughtNode(mesh) { showThoughtPanel(mesh); focusOn(mesh.position, 26); } | |
| 223 | + | |
| 224 | +function showThoughtPanel(node) { | |
| 225 | + const root = document.getElementById('mind-panel'); | |
| 226 | + const md = node.userData.md || node.userData.text || '(sin contenido)'; | |
| 227 | + const path = node.userData.path || 'pensamiento'; | |
| 228 | + root.innerHTML = `<div class="mp-head">${escHtml(path)}<button id="mp-x">✕</button></div>` + | |
| 229 | + `<div class="mp-body">${renderMarkdown(md)}</div>` + | |
| 230 | + `<div class="mp-actions">` + | |
| 231 | + `<button id="mp-exec" class="mp-exec">▶ Ejecutar esta propuesta</button>` + | |
| 232 | + (node.userData.path ? `<button id="mp-open" class="mp-open">Abrir en el editor</button>` : '') + | |
| 233 | + `</div>`; | |
| 234 | + root.classList.add('show'); | |
| 235 | + root.querySelector('#mp-x').onclick = () => root.classList.remove('show'); | |
| 236 | + root.querySelector('#mp-exec').onclick = () => { onExecute(md); root.classList.remove('show'); }; | |
| 237 | + const openBtn = root.querySelector('#mp-open'); | |
| 238 | + if (openBtn) openBtn.onclick = () => { onOpenFile(node.userData.path); root.classList.remove('show'); }; | |
| 239 | +} | |
| 240 | + | |
| 241 | +// ══ perfiles: anclas 3D + leyenda (recalculadas al abrir o al reprogramar) ══ | |
| 242 | +function computeAnchors() { | |
| 243 | + const map = new Map(); | |
| 244 | + map.set('ceo', new THREE.Vector3(0, 46, 0)); | |
| 245 | + const profs = ceo.getProfiles(); | |
| 246 | + const n = Math.max(profs.length, 1); | |
| 247 | + profs.forEach((p, i) => { | |
| 248 | + const a = (i / n) * Math.PI * 2; | |
| 249 | + map.set(p.id, new THREE.Vector3(Math.cos(a) * 70, 8 + (i % 2) * 20, Math.sin(a) * 70)); | |
| 250 | + }); | |
| 251 | + return map; | |
| 252 | +} | |
| 253 | +function renderLegend() { | |
| 254 | + const el = document.getElementById('mind-legend'); | |
| 255 | + if (!el) return; | |
| 256 | + const profs = ceo.getProfiles(); | |
| 257 | + el.innerHTML = `<div class="ml-item" data-id="ceo"><span class="ml-sw" style="background:${CEO_COLOR}"></span>CEO</div>` + | |
| 258 | + profs.map(p => `<div class="ml-item" data-id="${p.id}"><span class="ml-sw" style="background:${p.color}"></span>${escHtml(p.name)}</div>`).join(''); | |
| 259 | + el.querySelectorAll('.ml-item').forEach(row => { | |
| 260 | + row.onclick = () => { const pos = anchorMap.get(row.dataset.id); if (pos) focusOn(pos, 46); }; | |
| 261 | + }); | |
| 262 | +} | |
| 263 | +// vuelo suave de la cámara hacia un punto — así «clic en algo → la cámara se centra» | |
| 264 | +let flyTo = null; | |
| 265 | +function focusOn(pos, distance = 40) { | |
| 266 | + if (!S) return; | |
| 267 | + const dir = new THREE.Vector3().subVectors(S.camera.position, S.controls.target); | |
| 268 | + if (dir.lengthSq() < 0.001) dir.set(0, 0.3, 1); | |
| 269 | + dir.normalize().multiplyScalar(distance); | |
| 270 | + flyTo = { fromPos: S.camera.position.clone(), toPos: pos.clone().add(dir), fromTarget: S.controls.target.clone(), toTarget: pos.clone(), t0: elapsed, dur: 1.1 }; | |
| 271 | +} | |
| 272 | +const easeInOut = k => k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2; | |
| 273 | +function rebuildWorld() { anchorMap = computeAnchors(); renderLegend(); } | |
| 274 | + | |
| 275 | +// ── panel ⚙: reprograma misión, carpeta-alma y PERFILES (editables) ────── | |
| 276 | +function wireConfig(root) { | |
| 277 | + const btn = root.querySelector('#mind-config'); | |
| 278 | + const cfg = root.querySelector('#mind-cfg'); | |
| 279 | + const profRowHtml = p => `<div class="cfg-prof" data-id="${escHtml(p.id || '')}"> | |
| 280 | + <input type="color" class="cp-color" value="${p.color || '#7c5cff'}"> | |
| 281 | + <input type="text" class="cp-name" value="${escHtml(p.name || '')}" placeholder="Nombre"> | |
| 282 | + <input type="text" class="cp-focus" value="${escHtml(p.focus || '')}" placeholder="En qué se centra"> | |
| 283 | + <button class="cp-del" title="quitar">✕</button></div>`; | |
| 284 | + const notifState = () => (!('Notification' in window)) ? { txt: 'no soportadas por este navegador', can: false } | |
| 285 | + : Notification.permission === 'granted' ? { txt: '✓ concedidas — avisaré cuando encuentre algo bueno', can: false } | |
| 286 | + : Notification.permission === 'denied' ? { txt: '✕ bloqueadas — actívalas en los ajustes del sitio del navegador', can: false } | |
| 287 | + : { txt: 'aún no pedidas', can: true }; | |
| 288 | + const draw = () => { | |
| 289 | + const profs = ceo.getProfiles(); | |
| 290 | + const ns = notifState(); | |
| 291 | + cfg.innerHTML = | |
| 292 | + '<div class="cfg-head">⚙ Reprogramar el cerebro<button id="cfg-x">✕</button></div>' + | |
| 293 | + '<div class="cfg-notif">🔔 Notificaciones del navegador: ' + escHtml(ns.txt) + (ns.can ? ' <button id="cfg-notif-ask" class="cfg-notif-btn">Activar</button>' : '') + '</div>' + | |
| 294 | + '<label>Misión (qué quieres que haga por su cuenta)</label>' + | |
| 295 | + '<textarea id="cfg-mission" rows="3">' + escHtml(ceo.getMission()) + '</textarea>' + | |
| 296 | + '<label>Carpeta-alma (dentro del proyecto)</label>' + | |
| 297 | + '<input id="cfg-dir" value="' + escHtml(ceo.getSoulDir()) + '">' + | |
| 298 | + '<label>Perfiles — cada uno piensa en paralelo, con el color de su estrella</label>' + | |
| 299 | + '<div id="cfg-profiles">' + profs.map(profRowHtml).join('') + '</div>' + | |
| 300 | + '<button id="cfg-add-prof" class="cfg-add">+ nuevo perfil</button>' + | |
| 301 | + '<div class="cfg-actions"><button id="cfg-think-now" class="cfg-ghost">Pensar ahora</button>' + | |
| 302 | + '<button id="cfg-save" class="cfg-save">Reprogramar</button></div>' + | |
| 303 | + '<div class="cfg-note">La elfa trabajará según esto cuando estés ocioso y volcará todo en esa carpeta.</div>'; | |
| 304 | + cfg.querySelector('#cfg-x').onclick = () => cfg.classList.remove('show'); | |
| 305 | + cfg.querySelector('#cfg-notif-ask')?.addEventListener('click', () => { Notification.requestPermission().then(draw); }); | |
| 306 | + cfg.querySelector('#cfg-add-prof').onclick = () => { | |
| 307 | + cfg.querySelector('#cfg-profiles').insertAdjacentHTML('beforeend', profRowHtml({ color: '#ff9f45', name: '', focus: '' })); | |
| 308 | + wireRows(); | |
| 309 | + }; | |
| 310 | + cfg.querySelector('#cfg-think-now').onclick = () => { ceo.forceCycle(); cfg.classList.remove('show'); }; | |
| 311 | + cfg.querySelector('#cfg-save').onclick = () => { | |
| 312 | + // preserva el id original de cada perfil (si no, cada guardado los | |
| 313 | + // regeneraría desde el nombre y los ciclos en curso perderían el hilo) | |
| 314 | + const rows = [...cfg.querySelectorAll('.cfg-prof')].map(r => ({ | |
| 315 | + id: r.dataset.id || undefined, | |
| 316 | + color: r.querySelector('.cp-color').value, | |
| 317 | + name: r.querySelector('.cp-name').value.trim(), | |
| 318 | + focus: r.querySelector('.cp-focus').value.trim(), | |
| 319 | + })); | |
| 320 | + ceo.setMission(cfg.querySelector('#cfg-mission').value); | |
| 321 | + ceo.setSoulDir(cfg.querySelector('#cfg-dir').value); | |
| 322 | + ceo.setProfiles(rows); | |
| 323 | + if (!ceo.isEnabled()) ceo.enable(); | |
| 324 | + cfg.classList.remove('show'); | |
| 325 | + }; | |
| 326 | + wireRows(); | |
| 327 | + function wireRows() { cfg.querySelectorAll('.cp-del').forEach(b => { b.onclick = () => b.closest('.cfg-prof').remove(); }); } | |
| 328 | + }; | |
| 329 | + btn.onclick = () => { if (cfg.classList.contains('show')) cfg.classList.remove('show'); else { draw(); cfg.classList.add('show'); } }; | |
| 330 | +} | |
| 331 | +function wireHistory(root) { | |
| 332 | + const btn = root.querySelector('#mind-history'), panel = root.querySelector('#mind-log'); | |
| 333 | + btn.onclick = () => panel.classList.toggle('show'); | |
| 334 | + panel.querySelector('#ml-x').onclick = () => panel.classList.remove('show'); | |
| 335 | +} | |
| 336 | + | |
| 337 | +// play/stop del cerebro, visible dentro de la Mente. La elección la persiste | |
| 338 | +// ceo.js (misma clave que usa el clic en la elfa) → sobrevive a recargar. | |
| 339 | +function wirePlayStop(root) { | |
| 340 | + const btn = root.querySelector('#mind-playstop'); | |
| 341 | + const paint = () => { | |
| 342 | + const on = ceo.isEnabled(); | |
| 343 | + btn.textContent = on ? '⏸ pausar cerebro' : '▶ reanudar cerebro'; | |
| 344 | + btn.classList.toggle('paused', !on); | |
| 345 | + }; | |
| 346 | + btn.onclick = () => { if (ceo.isEnabled()) ceo.disable(); else ceo.enable(); paint(); }; | |
| 347 | + paint(); | |
| 348 | +} | |
| 349 | + | |
| 350 | +// ══ ciudad de fondo (motor de la app anfitriona, por debajo del mundo) ══════ | |
| 351 | +async function buildBackgroundCity(scene) { | |
| 352 | + if (!buildCityFn) return; | |
| 353 | + try { | |
| 354 | + const city = await buildCityFn(scene); | |
| 355 | + if (!city) return; | |
| 356 | + cityWrap = city.cityWrap; cityCity = city.cityCity; cityModel = city.cityModel; | |
| 357 | + } catch { /* sigue sin ciudad de fondo */ } | |
| 358 | +} | |
| 359 | +// haz de luz que baja hasta el fichero real en la ciudad + resalta su celda | |
| 360 | +function fileBeam(path, kind) { | |
| 361 | + if (!cityModel || !cityCity || !S) return; | |
| 362 | + const rel = String(path).replace(/^\.?\//, ''); | |
| 363 | + const f = cityModel.fileByRel.get(rel); | |
| 364 | + if (!f) return; | |
| 365 | + const local = new THREE.Vector3(f.box.cx, f.box.cy, f.box.cz); | |
| 366 | + const world = cityWrap.localToWorld(local.clone()); | |
| 367 | + const top = world.clone(); top.y += 50; | |
| 368 | + const geo = new THREE.BufferGeometry().setFromPoints([top, world]); | |
| 369 | + const mat = new THREE.LineBasicMaterial({ color: kind === 'write' ? 0xff4d8d : 0x49e8ff, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false }); | |
| 370 | + const line = new THREE.Line(geo, mat); | |
| 371 | + S.scene.add(line); | |
| 372 | + beams.push({ obj: line, born: elapsed, life: 1.4 }); | |
| 373 | + fileActivity.push({ id: f.id, born: elapsed, life: 2.2 }); | |
| 374 | +} | |
| 375 | + | |
| 376 | +// ── mundo psicodélico ─────────────────────────────────────────────────────── | |
| 377 | +function buildScene(canvas, W, H) { | |
| 378 | + const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true }); | |
| 379 | + renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); | |
| 380 | + renderer.setSize(W, H, false); | |
| 381 | + renderer.toneMapping = THREE.ACESFilmicToneMapping; | |
| 382 | + const scene = new THREE.Scene(); | |
| 383 | + const camera = new THREE.PerspectiveCamera(60, W / H, 0.1, 2000); | |
| 384 | + camera.position.set(0, 40, 150); | |
| 385 | + const controls = new OrbitControls(camera, canvas); | |
| 386 | + controls.enableDamping = true; controls.dampingFactor = 0.06; controls.autoRotate = false; | |
| 387 | + controls.enablePan = false; controls.minDistance = 60; controls.maxDistance = 420; | |
| 388 | + | |
| 389 | + const N = 14000; | |
| 390 | + const pos = new Float32Array(N * 3), rad = new Float32Array(N); | |
| 391 | + let s = 987654321; const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647; | |
| 392 | + for (let i = 0; i < N; i++) { | |
| 393 | + const arm = Math.floor(rnd() * 4); | |
| 394 | + const r = Math.pow(rnd(), 0.6) * 120 + 6; | |
| 395 | + const a = arm * (Math.PI / 2) + r * 0.03 + (rnd() - 0.5) * 0.5; | |
| 396 | + const y = (rnd() - 0.5) * (14 - r * 0.06); | |
| 397 | + pos[i * 3] = Math.cos(a) * r; pos[i * 3 + 1] = y; pos[i * 3 + 2] = Math.sin(a) * r; rad[i] = r; | |
| 398 | + } | |
| 399 | + const geo = new THREE.BufferGeometry(); | |
| 400 | + geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); | |
| 401 | + geo.setAttribute('aRad', new THREE.BufferAttribute(rad, 1)); | |
| 402 | + const mat = new THREE.ShaderMaterial({ | |
| 403 | + uniforms: { uTime: { value: 0 }, uBass: { value: 0 }, uMid: { value: 0 } }, | |
| 404 | + transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, | |
| 405 | + vertexShader: `uniform float uTime, uBass, uMid; attribute float aRad; varying vec3 vC; | |
| 406 | + vec3 hsv(float h){ vec3 k=vec3(1.,2./3.,1./3.); vec3 p=abs(fract(h+k)*6.-3.); return clamp(p-1.,0.,1.);} | |
| 407 | + float hash(vec3 p){ p=fract(p*0.3183099+0.1); p*=17.0; return fract(p.x*p.y*p.z*(p.x+p.y+p.z)); } | |
| 408 | + float vnoise(vec3 x){ vec3 i=floor(x),f=fract(x); f=f*f*(3.0-2.0*f); | |
| 409 | + return mix(mix(mix(hash(i+vec3(0,0,0)),hash(i+vec3(1,0,0)),f.x),mix(hash(i+vec3(0,1,0)),hash(i+vec3(1,1,0)),f.x),f.y), | |
| 410 | + mix(mix(hash(i+vec3(0,0,1)),hash(i+vec3(1,0,1)),f.x),mix(hash(i+vec3(0,1,1)),hash(i+vec3(1,1,1)),f.x),f.y),f.z); } | |
| 411 | + float fbm(vec3 p){ float a=0.5,s=0.0; for(int i=0;i<4;i++){ s+=a*vnoise(p); p*=2.02; a*=0.5;} return s; } | |
| 412 | + void main(){ | |
| 413 | + vec3 pos=position; | |
| 414 | + float n=fbm(pos*0.03 + vec3(0.0,uTime*0.18,0.0)); | |
| 415 | + pos += normalize(pos+0.001) * (n-0.5) * (5.0 + uMid*4.0 + uBass*7.0); | |
| 416 | + float sw = uTime*0.14 + aRad*0.015 + uBass*0.18; | |
| 417 | + float cs=cos(sw), sn=sin(sw); | |
| 418 | + pos.xz = mat2(cs,-sn,sn,cs) * pos.xz; | |
| 419 | + pos *= (1.0 + uBass*0.05); | |
| 420 | + float h=fract(aRad*0.004+uTime*0.03+n*0.12); vC=hsv(h)*(1.3-aRad*0.004)*(0.95+uMid*0.18+uBass*0.12); | |
| 421 | + vec4 mv=modelViewMatrix*vec4(pos,1.0); gl_PointSize=(2.2+60.0/-mv.z)*(1.0+uBass*0.18); gl_Position=projectionMatrix*mv; }`, | |
| 422 | + fragmentShader: `varying vec3 vC; void main(){ vec2 d=gl_PointCoord-0.5; float m=smoothstep(0.5,0.0,length(d)); gl_FragColor=vec4(vC*2.0,m); }`, | |
| 423 | + }); | |
| 424 | + const galaxy = new THREE.Points(geo, mat); scene.add(galaxy); | |
| 425 | + const core = new THREE.LineSegments(new THREE.WireframeGeometry(new THREE.IcosahedronGeometry(18, 1)), | |
| 426 | + new THREE.LineBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false })); | |
| 427 | + scene.add(core); | |
| 428 | + const rings = []; | |
| 429 | + for (let i = 0; i < 24; i++) { | |
| 430 | + const ring = new THREE.Mesh(new THREE.TorusGeometry(22, 0.5, 8, 80), | |
| 431 | + new THREE.MeshBasicMaterial({ color: 0x7c5cff, transparent: true, opacity: 0.45, blending: THREE.AdditiveBlending, depthWrite: false })); | |
| 432 | + ring.rotation.x = Math.PI / 2; ring.position.y = -70 + i * 6; ring.userData.i = i; | |
| 433 | + scene.add(ring); rings.push(ring); | |
| 434 | + } | |
| 435 | + nodesGroup = new THREE.Group(); scene.add(nodesGroup); | |
| 436 | + starGroup = new THREE.Group(); scene.add(starGroup); | |
| 437 | + const composer = new EffectComposer(renderer); | |
| 438 | + composer.setSize(W, H); composer.addPass(new RenderPass(scene, camera)); | |
| 439 | + const bloom = new UnrealBloomPass(new THREE.Vector2(W, H), 1.1, 0.5, 0.2); | |
| 440 | + composer.addPass(bloom); composer.addPass(new OutputPass()); | |
| 441 | + return { renderer, scene, camera, controls, composer, bloom, mat, galaxy, core, rings }; | |
| 442 | +} | |
| 443 | + | |
| 444 | +export async function openMind() { | |
| 445 | + if (open) return; | |
| 446 | + open = true; | |
| 447 | + if (built) { overlay.style.display = ''; try { widget?.play(); } catch {} startLoop(); return; } | |
| 448 | + | |
| 449 | + overlay = document.createElement('div'); | |
| 450 | + overlay.id = 'mind-overlay'; | |
| 451 | + overlay.innerHTML = | |
| 452 | + '<canvas id="mind-canvas"></canvas>' + | |
| 453 | + '<div id="mind-title">MENTE DE ELFFUSS</div>' + | |
| 454 | + '<div id="mind-legend"></div>' + | |
| 455 | + '<button id="mind-playstop" title="pausar/reanudar el cerebro"></button>' + | |
| 456 | + '<button id="mind-config" title="reprogramar el cerebro">⚙ cerebro</button>' + | |
| 457 | + '<button id="mind-history" title="ver todo lo que ha llegado">≡ historial</button>' + | |
| 458 | + '<button id="mind-close" title="salir">✕ salir</button>' + | |
| 459 | + '<div id="mind-anchors"></div><div id="mind-panel"></div><div id="mind-cfg"></div>' + | |
| 460 | + '<div id="mind-log"><div class="ml-head">Historial completo<button id="ml-x">✕</button></div><div id="mind-log-body"></div></div>'; | |
| 461 | + document.body.appendChild(overlay); | |
| 462 | + wireConfig(overlay); wireHistory(overlay); wirePlayStop(overlay); | |
| 463 | + mountMusic(overlay); | |
| 464 | + anchors.length = 0; thoughtNodes = []; stars = []; lineBuf.clear(); | |
| 465 | + rebuildWorld(); | |
| 466 | + | |
| 467 | + const canvas = overlay.querySelector('#mind-canvas'); | |
| 468 | + S = buildScene(canvas, window.innerWidth, window.innerHeight); | |
| 469 | + buildBackgroundCity(S.scene); | |
| 470 | + await loadExistingThoughts(); | |
| 471 | + await loadPersistedLog(); // el historial de «≡ historial» sobrevive a recargas | |
| 472 | + | |
| 473 | + const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(); | |
| 474 | + let downXY = null; | |
| 475 | + canvas.addEventListener('pointerdown', e => { downXY = [e.clientX, e.clientY]; }); | |
| 476 | + canvas.addEventListener('pointerup', e => { | |
| 477 | + if (!downXY) return; const moved = Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]); downXY = null; | |
| 478 | + if (moved > 5 || !thoughtNodes.length) return; | |
| 479 | + ptr.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1); | |
| 480 | + ray.setFromCamera(ptr, S.camera); | |
| 481 | + const hit = ray.intersectObjects(thoughtNodes)[0]; | |
| 482 | + if (hit) selectThoughtNode(hit.object); | |
| 483 | + }); | |
| 484 | + | |
| 485 | + const onResize = () => { | |
| 486 | + const w = window.innerWidth, h = window.innerHeight; | |
| 487 | + S.renderer.setSize(w, h, false); S.composer.setSize(w, h); S.bloom.resolution.set(w, h); | |
| 488 | + S.camera.aspect = w / h; S.camera.updateProjectionMatrix(); | |
| 489 | + }; | |
| 490 | + window.addEventListener('resize', onResize); S.onResize = onResize; | |
| 491 | + overlay.querySelector('#mind-close').addEventListener('click', closeMind); | |
| 492 | + S.onKey = e => { if (e.key === 'Escape') closeMind(); }; | |
| 493 | + document.addEventListener('keydown', S.onKey); | |
| 494 | + built = true; | |
| 495 | + startLoop(); | |
| 496 | +} | |
| 497 | + | |
| 498 | +// Etiquetas de propuestas: se proyectan del mundo 3D a la pantalla, así que | |
| 499 | +// con muchas acumuladas acaban solapándose ilegibles según el ángulo de | |
| 500 | +// cámara. Aquí: cap a las más cercanas y reparto anti-solape (empuja hacia | |
| 501 | +// abajo la que choca con otra ya colocada), para que se apilen separadas. | |
| 502 | +const MAX_LABELS = 14, LABEL_W = 90, LABEL_H = 20; | |
| 503 | +function projectAnchors() { | |
| 504 | + const w = window.innerWidth, h = window.innerHeight, v = new THREE.Vector3(); | |
| 505 | + const projected = []; | |
| 506 | + for (const a of anchors) { | |
| 507 | + v.copy(a.pos).project(S.camera); | |
| 508 | + if (v.z > 1) { a.el.style.display = 'none'; continue; } // detrás de la cámara | |
| 509 | + projected.push({ a, x: (v.x * 0.5 + 0.5) * w, y: (-v.y * 0.5 + 0.5) * h, depth: v.z }); | |
| 510 | + } | |
| 511 | + projected.sort((p1, p2) => p1.depth - p2.depth); // las más cercanas a la cámara, prioridad | |
| 512 | + projected.forEach((p, i) => { p.a.el.style.display = i < MAX_LABELS ? '' : 'none'; }); | |
| 513 | + const visible = projected.slice(0, MAX_LABELS).sort((p1, p2) => p1.x - p2.x || p1.y - p2.y); | |
| 514 | + const placed = []; | |
| 515 | + for (const p of visible) { | |
| 516 | + let y = p.y; | |
| 517 | + for (const q of placed) if (Math.abs(q.x - p.x) < LABEL_W && Math.abs(q.y - y) < LABEL_H) y = q.y + LABEL_H; | |
| 518 | + placed.push({ x: p.x, y }); | |
| 519 | + p.a.el.style.left = p.x + 'px'; p.a.el.style.top = y + 'px'; | |
| 520 | + p.a.el.style.transform = 'translate(-50%,-50%)'; | |
| 521 | + } | |
| 522 | +} | |
| 523 | +const wob = (t, seed, freq = 0.1) => Math.sin(t * freq + seed) * 0.6 + Math.sin(t * freq * 0.43 + seed * 2.1) * 0.3 + Math.sin(t * freq * 0.19 + seed * 4.7) * 0.1; | |
| 524 | + | |
| 525 | +let elapsed = 0, lastMs = 0, smBass = 0, smMid = 0; | |
| 526 | +function startLoop() { | |
| 527 | + if (raf) return; | |
| 528 | + const loop = (ms) => { | |
| 529 | + raf = requestAnimationFrame(loop); | |
| 530 | + const dt = lastMs ? (ms - lastMs) / 1000 : 0; | |
| 531 | + elapsed += dt; lastMs = ms; | |
| 532 | + const t = elapsed; | |
| 533 | + const beat = 60 / 138; | |
| 534 | + const bp = (t % beat) / beat; | |
| 535 | + const bassRaw = Math.pow(1 - bp, 3); | |
| 536 | + const midRaw = 0.5 + 0.5 * Math.sin(t * 6.0); | |
| 537 | + smBass += (bassRaw - smBass) * 0.05; | |
| 538 | + smMid += (midRaw - smMid) * 0.06; | |
| 539 | + S.mat.uniforms.uTime.value = t; | |
| 540 | + S.mat.uniforms.uBass.value = smBass; | |
| 541 | + S.mat.uniforms.uMid.value = smMid; | |
| 542 | + S.galaxy.rotation.y = t * 0.05; | |
| 543 | + S.galaxy.rotation.x = wob(t, 1.7, 0.05) * 0.15; | |
| 544 | + S.galaxy.rotation.z = wob(t, 5.2, 0.04) * 0.1; | |
| 545 | + S.galaxy.scale.setScalar(1 + smBass * 0.02); | |
| 546 | + const pulse = 1 + smBass * 0.05 + Math.sin(t * 0.9) * 0.03; | |
| 547 | + S.core.scale.setScalar(pulse); S.core.rotation.y = t * 0.16; S.core.rotation.x = t * 0.09; | |
| 548 | + S.core.position.x = wob(t, 3.1, 0.11) * 6; S.core.position.z = wob(t, 9.4, 0.09) * 6; | |
| 549 | + S.core.material.color.setHSL((t * 0.04) % 1, 0.9, 0.6); | |
| 550 | + for (const r of S.rings) { | |
| 551 | + r.position.y += 0.14 + smBass * 0.12; | |
| 552 | + if (r.position.y > 74) r.position.y -= 144; | |
| 553 | + r.position.x = wob(t, r.userData.i * 1.3 + 1, 0.08) * 3; | |
| 554 | + r.scale.setScalar(1 + smBass * 0.12 + Math.sin(t * 0.8 + r.userData.i) * 0.04); | |
| 555 | + r.material.opacity = 0.2 + smBass * 0.16; | |
| 556 | + r.material.color.setHSL((t * 0.05 + r.userData.i * 0.03) % 1, 0.85, 0.6); | |
| 557 | + } | |
| 558 | + for (let i = 0; i < thoughtNodes.length; i++) { const n = thoughtNodes[i]; n.rotation.y = t + i; n.scale.setScalar(1 + Math.sin(t * 2 + i) * 0.14); } | |
| 559 | + // estrellas: nacen (fade-in), viven, se apagan solas y se reciclan | |
| 560 | + for (let i = stars.length - 1; i >= 0; i--) { | |
| 561 | + const st = stars[i], age = t - st.born; | |
| 562 | + if (age > st.life) { starGroup.remove(st.obj); st.obj.material.map.dispose(); st.obj.material.dispose(); stars.splice(i, 1); continue; } | |
| 563 | + const fadeIn = Math.min(1, age / 0.5), fadeOut = Math.min(1, (st.life - age) / (st.life * 0.35)); | |
| 564 | + st.obj.material.opacity = Math.min(fadeIn, fadeOut); | |
| 565 | + st.obj.position.y += st.up * dt; | |
| 566 | + st.obj.position.x += Math.sin(t * 0.6 + st.seed) * 0.3 * dt; | |
| 567 | + } | |
| 568 | + // haces sobre la ciudad + celdas de fichero resaltadas por actividad | |
| 569 | + for (let i = beams.length - 1; i >= 0; i--) { | |
| 570 | + const b = beams[i], age = t - b.born; | |
| 571 | + if (age > b.life) { S.scene.remove(b.obj); b.obj.geometry.dispose(); b.obj.material.dispose(); beams.splice(i, 1); continue; } | |
| 572 | + b.obj.material.opacity = 0.9 * Math.max(0, 1 - age / b.life); | |
| 573 | + } | |
| 574 | + if (cityCity) for (let i = fileActivity.length - 1; i >= 0; i--) { | |
| 575 | + const a = fileActivity[i], age = t - a.born; | |
| 576 | + if (age > a.life) { cityCity.paintFile(a.id, 0); fileActivity.splice(i, 1); continue; } | |
| 577 | + cityCity.paintFile(a.id, Math.max(0, 1 - age / a.life)); | |
| 578 | + } | |
| 579 | + if (flyTo) { | |
| 580 | + const k = Math.min(1, (t - flyTo.t0) / flyTo.dur), e = easeInOut(k); | |
| 581 | + S.camera.position.lerpVectors(flyTo.fromPos, flyTo.toPos, e); | |
| 582 | + S.controls.target.lerpVectors(flyTo.fromTarget, flyTo.toTarget, e); | |
| 583 | + if (k >= 1) flyTo = null; | |
| 584 | + } | |
| 585 | + S.controls.update(); | |
| 586 | + projectAnchors(); | |
| 587 | + S.composer.render(); | |
| 588 | + }; | |
| 589 | + loop(performance.now()); | |
| 590 | +} | |
| 591 | + | |
| 592 | +export function closeMind() { | |
| 593 | + open = false; | |
| 594 | + if (raf) { cancelAnimationFrame(raf); raf = null; } | |
| 595 | + lastMs = 0; | |
| 596 | + try { widget?.pause(); } catch {} | |
| 597 | + if (overlay) overlay.style.display = 'none'; | |
| 598 | +} | |
| 599 | + | |
| 600 | +// para tests/depuración | |
| 601 | +export function _debug() { | |
| 602 | + return { | |
| 603 | + starCount: stars.length, hasCity: !!cityCity, profileCount: ceo.getProfiles().length, | |
| 604 | + beamCount: beams.length, fileActivityCount: fileActivity.length, | |
| 605 | + cameraPos: S ? [S.camera.position.x, S.camera.position.y, S.camera.position.z] : null, | |
| 606 | + flying: !!flyTo, | |
| 607 | + }; | |
| 608 | +} | |
| 609 | +export function _debugFocusOn(id) { const p = anchorMap.get(id); if (p) focusOn(p, 46); } |