| 1 | // «Modo básico»: cerebro determinista sin modelo — cubre las demos clave sin |
| 2 | // descargar nada. Para lenguaje libre, carga un modelo en el selector de modelo. |
| 3 | // `tr` y no `t`: dentro de chat() `t` es el texto en minúsculas. |
| 4 | import { t as tr, chipEnEspanol } from '../i18n.js'; |
| 5 | export const name = 'Básico (sin modelo)'; |
| 6 | export async function load() {} |
| 7 | |
| 8 | const call = obj => '```tool\n' + JSON.stringify(obj) + '\n```'; |
| 9 | |
| 10 | const SHELL = (title, body, script) => `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>${title}</title><style> |
| 11 | body{font-family:system-ui;background:#0d1117;color:#e6edf3;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;gap:16px} |
| 12 | button{cursor:pointer} |
| 13 | </style></head><body>${body}<script>${script}<\/script></body></html>`; |
| 14 | |
| 15 | const APPS = { |
| 16 | reloj: () => SHELL('Reloj', |
| 17 | '<h1 id="t" style="font-size:14vw;margin:0;font-variant-numeric:tabular-nums"></h1><p id="d" style="color:#8b949e;font-size:1.2rem"></p>', |
| 18 | "const f=()=>{const n=new Date();document.getElementById('t').textContent=n.toLocaleTimeString('es-ES');document.getElementById('d').textContent=n.toLocaleDateString('es-ES',{weekday:'long',day:'numeric',month:'long',year:'numeric'})};f();setInterval(f,1000);"), |
| 19 | notas: () => SHELL('Notas', |
| 20 | '<h2>📝 Notas</h2><textarea id="n" style="width:82vw;height:60vh;background:#161b22;color:#e6edf3;border:1px solid #30363d;border-radius:10px;padding:14px;font-size:16px;resize:none" placeholder="Escribe aquí…"></textarea><p id="s" style="color:#8b949e;font-size:.85rem"></p>', |
| 21 | "let mem={};let store;try{store=localStorage;store.getItem('x')}catch(e){store={getItem:k=>mem[k],setItem:(k,v)=>mem[k]=v}}const n=document.getElementById('n'),s=document.getElementById('s');n.value=store.getItem('elffuss.notas')||'';n.oninput=()=>{store.setItem('elffuss.notas',n.value);s.textContent='guardado '+new Date().toLocaleTimeString('es-ES')};"), |
| 22 | arte: () => SHELL('Arte', |
| 23 | '<canvas id="g" style="position:fixed;inset:0;width:100vw;height:100vh"></canvas><p style="position:fixed;bottom:12px;left:0;right:0;text-align:center;color:#8b949e;font-size:.8rem">mueve el ratón ✨</p>', |
| 24 | "const c=document.getElementById('g'),gl=c.getContext('webgl',{alpha:false});" + |
| 25 | "const N=9000,S=new Float32Array(N*2);for(let i=0;i<N*2;i++)S[i]=Math.random();" + |
| 26 | "const vs='attribute vec2 s;uniform float t,a;uniform vec2 m;varying vec3 C;varying float G;" + |
| 27 | "void main(){float r=0.1+1.2*pow(s.y,0.7);float g=s.x*6.283+r*3.0+t*(0.2+0.4/(r+0.2));" + |
| 28 | "vec2 p=vec2(cos(g),sin(g))*r;p.y*=0.7;p+=m*(0.05+r*0.08);gl_Position=vec4(p.x/a,p.y,0.,1.);" + |
| 29 | "float w=0.5+0.5*sin(t*(2.+s.x*4.)+s.y*30.);G=w;" + |
| 30 | "C=mix(vec3(1.,.3,.55),vec3(.49,.36,1.),smoothstep(.1,1.2,r));gl_PointSize=1.5+3.*w;}';" + |
| 31 | "const fs='precision mediump float;varying vec3 C;varying float G;" + |
| 32 | "void main(){float m2=smoothstep(.5,0.,length(gl_PointCoord-.5));gl_FragColor=vec4(C*G,m2*G);}';" + |
| 33 | "function sh(t2,s2){const x=gl.createShader(t2);gl.shaderSource(x,s2);gl.compileShader(x);return x}" + |
| 34 | "const P=gl.createProgram();gl.attachShader(P,sh(gl.VERTEX_SHADER,vs));gl.attachShader(P,sh(gl.FRAGMENT_SHADER,fs));" + |
| 35 | "gl.linkProgram(P);gl.useProgram(P);const B=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,B);" + |
| 36 | "gl.bufferData(gl.ARRAY_BUFFER,S,gl.STATIC_DRAW);const L=gl.getAttribLocation(P,'s');" + |
| 37 | "gl.enableVertexAttribArray(L);gl.vertexAttribPointer(L,2,gl.FLOAT,false,0,0);" + |
| 38 | "gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE);gl.clearColor(0.04,0.05,0.08,1);" + |
| 39 | "let mx=0,my=0;addEventListener('pointermove',e=>{mx=(e.clientX/innerWidth-.5)*2;my=-(e.clientY/innerHeight-.5)*2});" + |
| 40 | "(function F(n){c.width=innerWidth;c.height=innerHeight;gl.viewport(0,0,c.width,c.height);" + |
| 41 | "gl.clear(gl.COLOR_BUFFER_BIT);gl.uniform1f(gl.getUniformLocation(P,'t'),n/1000);" + |
| 42 | "gl.uniform1f(gl.getUniformLocation(P,'a'),c.width/c.height);gl.uniform2f(gl.getUniformLocation(P,'m'),mx,my);" + |
| 43 | "gl.drawArrays(gl.POINTS,0,N);requestAnimationFrame(F)})(0);"), |
| 44 | calculadora: () => SHELL('Calculadora', |
| 45 | '<div><input id="p" readonly style="width:288px;font-size:1.6rem;text-align:right;background:#161b22;color:#e6edf3;border:1px solid #30363d;border-radius:10px;padding:10px;margin-bottom:10px;box-sizing:border-box"><div id="k" style="display:grid;grid-template-columns:repeat(4,64px);gap:8px"></div></div>', |
| 46 | "const p=document.getElementById('p'),k=document.getElementById('k');'789/456*123-0.=+C'.split('').forEach(c=>{const b=document.createElement('button');b.textContent=c;b.style.cssText='font-size:1.3rem;padding:14px;border-radius:10px;border:1px solid #30363d;background:#21262d;color:#e6edf3';b.onclick=()=>{if(c==='C')p.value='';else if(c==='='){try{p.value=/^[-+*/.() 0-9]+$/.test(p.value)?String(Function('return ('+p.value+')')()):'error'}catch(e){p.value='error'}}else p.value+=c};k.appendChild(b)});"), |
| 47 | }; |
| 48 | |
| 49 | // CSV → app de gráfico de barras (canvas, sin librerías): primera columna = |
| 50 | // etiqueta, primera columna numérica = valor. |
| 51 | function chartApp(fileName, csv) { |
| 52 | const lines = csv.trim().split(/\r?\n/).filter(l => l.trim() && !l.startsWith('[')); |
| 53 | const rows = lines.map(l => l.split(/[,;\t]/).map(c => c.trim())); |
| 54 | const head = rows.shift() || []; |
| 55 | let valCol = head.findIndex((_, i) => |
| 56 | i > 0 && rows.length && rows.every(r => r[i] !== undefined && r[i] !== '' && !isNaN(parseFloat(r[i])))); |
| 57 | if (valCol < 1) valCol = 1; |
| 58 | const data = rows.slice(0, 24).map(r => ({ label: r[0], value: parseFloat(r[valCol]) || 0 })); |
| 59 | return SHELL('Gráfico ' + fileName, |
| 60 | `<h2 style="margin:10px">📊 ${fileName}${head[valCol] ? ' — ' + head[valCol] : ''}</h2><canvas id="c" width="760" height="430" style="max-width:94vw"></canvas>`, |
| 61 | `const data=${JSON.stringify(data)};const c=document.getElementById('c'),x=c.getContext('2d'); |
| 62 | const W=c.width,H=c.height,p=48,max=Math.max(...data.map(d=>d.value))||1,bw=(W-p*2)/data.length; |
| 63 | x.strokeStyle='#30363d';x.beginPath();x.moveTo(p,12);x.lineTo(p,H-p);x.lineTo(W-12,H-p);x.stroke(); |
| 64 | data.forEach((d,i)=>{const h=(H-p-24)*d.value/max,bx=p+8+i*bw; |
| 65 | const g=x.createLinearGradient(0,H-p-h,0,H-p);g.addColorStop(0,'#ff4d8d');g.addColorStop(1,'#7c5cff'); |
| 66 | x.fillStyle=g;x.fillRect(bx,H-p-h,Math.max(bw-16,4),h); |
| 67 | x.fillStyle='#e6edf3';x.font='12px system-ui';x.textAlign='center'; |
| 68 | x.fillText(String(d.value),bx+(bw-16)/2,H-p-h-7); |
| 69 | x.save();x.translate(bx+(bw-16)/2,H-p+13);x.rotate(.5);x.fillStyle='#8b949e';x.textAlign='left'; |
| 70 | x.fillText(String(d.label).slice(0,14),0,0);x.restore();});`); |
| 71 | } |
| 72 | |
| 73 | const generic = desc => SHELL('Boceto', |
| 74 | `<div style="max-width:560px;text-align:center;padding:20px"><h2>✳ Boceto de app</h2><p style="color:#8b949e">Esto es un boceto del modo básico. Pediste:</p><blockquote style="background:#161b22;border-left:3px solid #ff4d8d;padding:12px;border-radius:8px;text-align:left">${desc.replace(/</g, '<')}</blockquote><p style="color:#8b949e">Carga un modelo (en el selector de modelo, arriba) y Elffuss generará esta app de verdad, a medida.</p></div>`, ''); |
| 75 | |
| 76 | // La ayuda va en el idioma de la página (i18n: basicHelp). Las órdenes que |
| 77 | // entiende este motor son en español, y en inglés se dice así, con su traducción |
| 78 | // al lado. (El selector de modelo es el desplegable de la cabecera; 🧠 es la |
| 79 | // Mente. El enlace #/modelo lo enfoca: ver rutas.js.) |
| 80 | const HELP = () => tr('basicHelp'); |
| 81 | |
| 82 | export async function chat(history) { |
| 83 | const last = history[history.length - 1]; |
| 84 | // Una sugerencia de la página (chip) en otro idioma se entiende como la misma |
| 85 | // en español, que es como entiende las órdenes este motor. Solo el texto exacto |
| 86 | // de una sugerencia: lo que se escribe a mano sigue tal cual. |
| 87 | const text = (chipEnEspanol(last?.content) || last?.content || '').trim(); |
| 88 | |
| 89 | // Tras una herramienta: convertir su resultado en la respuesta… |
| 90 | if (text.startsWith('[resultado')) { |
| 91 | const body = text.slice(text.indexOf('\n') + 1).trim(); |
| 92 | if (body.startsWith('ERROR:')) return tr('basicCouldNot', { err: body.slice(6).trim() }); |
| 93 | // …o encadenar: si lo leído era para un gráfico, generar la app ahora. |
| 94 | if (text.startsWith('[resultado fs.read')) { |
| 95 | const prevUser = [...history].reverse().find(m => m.role === 'user' && !m.content.startsWith('[')); |
| 96 | if (prevUser && /(grafic|visualiza|gr[aá]fico|chart|barras)/i.test(prevUser.content)) { |
| 97 | const file = prevUser.content.match(/(\S+\.(?:csv|tsv|xlsx?))/i)?.[1] || 'datos'; |
| 98 | return call({ tool: 'app.create', args: { name: 'gráfico ' + file, html: chartApp(file, body) } }); |
| 99 | } |
| 100 | } |
| 101 | return body; |
| 102 | } |
| 103 | |
| 104 | const t = text.toLowerCase(); |
| 105 | |
| 106 | // web (antes que «abre <app>» para que gane la URL) |
| 107 | const url = text.match(/https?:\/\/[^\s"'<>]+/); |
| 108 | if (url && /(abre|visita|entra|descarga|mira|lee|busca|ve a)/.test(t)) |
| 109 | return call({ tool: 'web.fetch', args: { url: url[0] } }); |
| 110 | |
| 111 | // crear skill (modo básico: plantilla a partir de la descripción) |
| 112 | const mSkill = text.match(/(?:cr[eé]a(?:me)?|hazme|genera)\s+una\s+skill\s+(?:para|de|que)\s+(.+)/i); |
| 113 | if (mSkill) { |
| 114 | const what = mSkill[1].replace(/[?.!]+$/, '').trim(); |
| 115 | return call({ tool: 'skill.create', args: { name: what.slice(0, 40), description: 'Skill para ' + what, |
| 116 | instructions: 'Cuando el usuario pida «' + what + '», ayúdale paso a paso, sé concreto y usa las herramientas disponibles (archivos, web, apps) cuando aporten.' } }); |
| 117 | } |
| 118 | if (/(lista|ver|muestra|qué|que).*skills/.test(t)) return call({ tool: 'skill.list', args: {} }); |
| 119 | |
| 120 | // búsqueda de imágenes |
| 121 | const mImg = text.match(/(?:busca(?:r)?|encuentra|ens[eé]ñame|muestra|quiero)\b.*?\b(?:fotos?|im[aá]genes?|gr[aá]ficos?|dibujos?|fotograf[ií]as?)\s+(?:de\s+)?(.+)/i); |
| 122 | if (mImg && !url) return call({ tool: 'web.images', args: { query: mImg[1].replace(/[?.!]+$/, '').trim() } }); |
| 123 | // búsqueda web (texto) |
| 124 | const mSearch = text.match(/(?:busca(?:r)?|buscame|google(?:a)?|encuentra|investiga)\s+(?:en\s+(?:internet|la\s+web|google)\s+)?(.+)/i); |
| 125 | if (mSearch && !url && /(busca|google|encuentra|investiga)/.test(t)) |
| 126 | return call({ tool: 'web.search', args: { query: mSearch[1].replace(/[?.!]+$/, '').trim() } }); |
| 127 | |
| 128 | // tareas |
| 129 | const mTask = text.match(/dentro de (\d+)\s*min(?:uto)?s?\s*(?:que\s*)?(.*)/i); |
| 130 | if (mTask && /(recu[eé]rdame|av[ií]same|programa|dentro de \d+ *min)/.test(t)) |
| 131 | return call({ tool: 'tasks.add', args: { inMinutes: Number(mTask[1]), prompt: mTask[2].trim() || text } }); |
| 132 | if (/(lista|ver|muestra|qué|que).*(tareas)/.test(t) || t === 'tareas') |
| 133 | return call({ tool: 'tasks.list', args: {} }); |
| 134 | |
| 135 | // memoria persistente |
| 136 | const mRemember = text.match(/\brecuerda (?:que )?(.+)/i); |
| 137 | if (mRemember) return call({ tool: 'memory.save', args: { fact: mRemember[1].trim() } }); |
| 138 | if (/(qué|que) recuerdas|tu memoria|mis recuerdos/.test(t)) |
| 139 | return call({ tool: 'memory.list', args: {} }); |
| 140 | const mForget = text.match(/\bolvida (?:el )?(m[a-z0-9]{6})\b/i); |
| 141 | if (mForget) return call({ tool: 'memory.forget', args: { id: mForget[1] } }); |
| 142 | |
| 143 | // vault |
| 144 | const mSecret = text.match(/guarda (?:el |la )?(?:secreto|contraseña) ([\w.@-]+)\s*[:=]\s*(\S+)/i); |
| 145 | if (mSecret) return call({ tool: 'vault.set', args: { name: mSecret[1], secret: mSecret[2] } }); |
| 146 | if (/(lista|ver|muestra).*(secretos|contraseñas)/.test(t)) |
| 147 | return call({ tool: 'vault.list', args: {} }); |
| 148 | const mGet = text.match(/(?:dame|lee|cu[aá]l es) (?:el |la )?(?:secreto|contraseña)(?: de)? ([\w.@-]+)/i); |
| 149 | if (mGet) return call({ tool: 'vault.get', args: { name: mGet[1] } }); |
| 150 | |
| 151 | // datos → gráfico (lee el archivo; el [resultado] de arriba crea la app) |
| 152 | const mViz = text.match(/(?:grafica|graficar|visualiza|visualizar|gr[aá]fico|chart|barras)\b.*?(\S+\.(?:csv|tsv|xlsx?))/i); |
| 153 | if (mViz) return call({ tool: 'fs.read', args: { path: mViz[1] } }); |
| 154 | |
| 155 | // automatización entre carpetas |
| 156 | const mWatch = text.match(/(?:vigila|automatiza|observa|monitoriza|cuando\s+(?:deje|ponga|caiga)\s+(?:un\s+)?(?:archivo|fichero)?\s*(?:en)?)\s+(?:la\s+carpeta\s+)?([\w.-]+).*?\b(?:en|a|hacia)\s+(?:la\s+carpeta\s+)?([\w.-]+)/i); |
| 157 | if (mWatch && /(vigila|automatiza|observa|monitoriza|cuando)/.test(t) && /(procesa|deja|salida|convierte|→|copia)/.test(t)) |
| 158 | return call({ tool: 'fs.watch', args: { from: mWatch[1], to: mWatch[2] } }); |
| 159 | if (/(lista|ver|muestra|qué|que).*(automatizaciones|vigilancias)/.test(t)) |
| 160 | return call({ tool: 'fs.watch_list', args: {} }); |
| 161 | |
| 162 | // copia one-shot entre carpetas |
| 163 | const mCopy = text.match(/copia(?:r)?\s+(?:todos\s+)?(?:los\s+)?([\w*.]+)\s+de\s+([\w.-]+)\s+a\s+([\w.-]+)/i); |
| 164 | if (mCopy) { |
| 165 | let pattern = mCopy[1]; |
| 166 | if (!pattern.includes('*')) pattern = '*' + (pattern.startsWith('.') ? pattern : '.' + pattern); |
| 167 | return call({ tool: 'fs.copy', args: { pattern, from: mCopy[2], to: mCopy[3] } }); |
| 168 | } |
| 169 | |
| 170 | // archivos |
| 171 | if (/(autoriza|elige|selecciona|añade|conecta).*(carpeta|directorio)/.test(t)) |
| 172 | return call({ tool: 'fs.pick_folder', args: {} }); |
| 173 | if (/(lista|muestra|qué hay|que hay|enséñame|ver).*(archivos|ficheros|carpeta|directorio)/.test(t)) |
| 174 | return call({ tool: 'fs.list', args: {} }); |
| 175 | const mRead = text.match(/lee (?:el (?:archivo|fichero) )?([\w./ -]+\.\w+)/i); |
| 176 | if (mRead) return call({ tool: 'fs.read', args: { path: mRead[1].trim() } }); |
| 177 | const mWrite = text.match(/escribe (?:en )?([\w./-]+\.\w+)\s*[:=]\s*([\s\S]+)/i); |
| 178 | if (mWrite) return call({ tool: 'fs.write', args: { path: mWrite[1], content: mWrite[2] } }); |
| 179 | |
| 180 | // apps |
| 181 | if (/(crea|hazme|haz|genera|quiero|móntame|montame)/.test(t) || /^(reloj|notas|calculadora)$/.test(t)) { |
| 182 | const kind = /reloj|hora/.test(t) ? 'reloj' : /nota/.test(t) ? 'notas' : /calcul/.test(t) ? 'calculadora' |
| 183 | : /(arte|part[ií]culas|galaxia|aurora|webgl)/.test(t) ? 'arte' : null; |
| 184 | if (kind) return call({ tool: 'app.create', args: { name: kind, html: APPS[kind]() } }); |
| 185 | if (/(app|aplicaci|web|página|pagina|juego|dashboard|panel)/.test(t)) |
| 186 | return call({ tool: 'app.create', args: { name: 'boceto', html: generic(text) } }); |
| 187 | } |
| 188 | const mOpen = t.match(/abre (?:la app )?([\wáéíóúñ-]+)/); |
| 189 | if (mOpen && !url) return call({ tool: 'app.open', args: { name: mOpen[1] } }); |
| 190 | if (/(lista|ver|muestra|qué|que).*apps/.test(t)) return call({ tool: 'app.list', args: {} }); |
| 191 | |
| 192 | if (/^(hola|buenas|hey|hi)\b/.test(t)) return tr('basicHi') + HELP(); |
| 193 | return HELP(); |
| 194 | } |