Elffuss BraidHub

utopia-ia/elffuss-claw public

e2d4c9abe7d2 · 14.0 KiBRawPermalink
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.
3export const name = 'Básico (sin modelo)';
4export async function load() {}
5
6const call = obj => '```tool\n' + JSON.stringify(obj) + '\n```';
7
8const SHELL = (title, body, script) => `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>${title}</title><style>
9body{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}
10button{cursor:pointer}
11</style></head><body>${body}<script>${script}<\/script></body></html>`;
12
13const APPS = {
14 reloj: () => SHELL('Reloj',
15 '<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>',
16 "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);"),
17 notas: () => SHELL('Notas',
18 '<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>',
19 "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')};"),
20 arte: () => SHELL('Arte',
21 '<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>',
22 "const c=document.getElementById('g'),gl=c.getContext('webgl',{alpha:false});" +
23 "const N=9000,S=new Float32Array(N*2);for(let i=0;i<N*2;i++)S[i]=Math.random();" +
24 "const vs='attribute vec2 s;uniform float t,a;uniform vec2 m;varying vec3 C;varying float G;" +
25 "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));" +
26 "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.);" +
27 "float w=0.5+0.5*sin(t*(2.+s.x*4.)+s.y*30.);G=w;" +
28 "C=mix(vec3(1.,.3,.55),vec3(.49,.36,1.),smoothstep(.1,1.2,r));gl_PointSize=1.5+3.*w;}';" +
29 "const fs='precision mediump float;varying vec3 C;varying float G;" +
30 "void main(){float m2=smoothstep(.5,0.,length(gl_PointCoord-.5));gl_FragColor=vec4(C*G,m2*G);}';" +
31 "function sh(t2,s2){const x=gl.createShader(t2);gl.shaderSource(x,s2);gl.compileShader(x);return x}" +
32 "const P=gl.createProgram();gl.attachShader(P,sh(gl.VERTEX_SHADER,vs));gl.attachShader(P,sh(gl.FRAGMENT_SHADER,fs));" +
33 "gl.linkProgram(P);gl.useProgram(P);const B=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,B);" +
34 "gl.bufferData(gl.ARRAY_BUFFER,S,gl.STATIC_DRAW);const L=gl.getAttribLocation(P,'s');" +
35 "gl.enableVertexAttribArray(L);gl.vertexAttribPointer(L,2,gl.FLOAT,false,0,0);" +
36 "gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE);gl.clearColor(0.04,0.05,0.08,1);" +
37 "let mx=0,my=0;addEventListener('pointermove',e=>{mx=(e.clientX/innerWidth-.5)*2;my=-(e.clientY/innerHeight-.5)*2});" +
38 "(function F(n){c.width=innerWidth;c.height=innerHeight;gl.viewport(0,0,c.width,c.height);" +
39 "gl.clear(gl.COLOR_BUFFER_BIT);gl.uniform1f(gl.getUniformLocation(P,'t'),n/1000);" +
40 "gl.uniform1f(gl.getUniformLocation(P,'a'),c.width/c.height);gl.uniform2f(gl.getUniformLocation(P,'m'),mx,my);" +
41 "gl.drawArrays(gl.POINTS,0,N);requestAnimationFrame(F)})(0);"),
42 calculadora: () => SHELL('Calculadora',
43 '<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>',
44 "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)});"),
45};
46
47// CSV → app de gráfico de barras (canvas, sin librerías): primera columna =
48// etiqueta, primera columna numérica = valor.
49function chartApp(fileName, csv) {
50 const lines = csv.trim().split(/\r?\n/).filter(l => l.trim() && !l.startsWith('['));
51 const rows = lines.map(l => l.split(/[,;\t]/).map(c => c.trim()));
52 const head = rows.shift() || [];
53 let valCol = head.findIndex((_, i) =>
54 i > 0 && rows.length && rows.every(r => r[i] !== undefined && r[i] !== '' && !isNaN(parseFloat(r[i]))));
55 if (valCol < 1) valCol = 1;
56 const data = rows.slice(0, 24).map(r => ({ label: r[0], value: parseFloat(r[valCol]) || 0 }));
57 return SHELL('Gráfico ' + fileName,
58 `<h2 style="margin:10px">📊 ${fileName}${head[valCol] ? ' — ' + head[valCol] : ''}</h2><canvas id="c" width="760" height="430" style="max-width:94vw"></canvas>`,
59 `const data=${JSON.stringify(data)};const c=document.getElementById('c'),x=c.getContext('2d');
60const W=c.width,H=c.height,p=48,max=Math.max(...data.map(d=>d.value))||1,bw=(W-p*2)/data.length;
61x.strokeStyle='#30363d';x.beginPath();x.moveTo(p,12);x.lineTo(p,H-p);x.lineTo(W-12,H-p);x.stroke();
62data.forEach((d,i)=>{const h=(H-p-24)*d.value/max,bx=p+8+i*bw;
63const g=x.createLinearGradient(0,H-p-h,0,H-p);g.addColorStop(0,'#ff4d8d');g.addColorStop(1,'#7c5cff');
64x.fillStyle=g;x.fillRect(bx,H-p-h,Math.max(bw-16,4),h);
65x.fillStyle='#e6edf3';x.font='12px system-ui';x.textAlign='center';
66x.fillText(String(d.value),bx+(bw-16)/2,H-p-h-7);
67x.save();x.translate(bx+(bw-16)/2,H-p+13);x.rotate(.5);x.fillStyle='#8b949e';x.textAlign='left';
68x.fillText(String(d.label).slice(0,14),0,0);x.restore();});`);
69}
70
71const generic = desc => SHELL('Boceto',
72 `<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, '&lt;')}</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>`, '');
73
74const HELP = `Estoy en modo básico (sin modelo). Entiendo órdenes directas:
75• «hazme un reloj / una app de notas / una calculadora»
76• «autoriza una carpeta» · «lista los archivos» · «lee <archivo>»
77• «recuérdame dentro de N minutos <algo>» · «lista las tareas»
78• «guarda el secreto <nombre>: <valor>» · «lista los secretos»
79• «abre https://…»
80Para lenguaje libre y apps a medida, carga un modelo en el [selector de modelo](#/modelo) de arriba.`;
81// (El selector de modelo es el desplegable de la cabecera; 🧠 es la Mente. El
82// enlace #/modelo lo enfoca: ver rutas.js.)
83
84export async function chat(history) {
85 const last = history[history.length - 1];
86 const text = (last?.content || '').trim();
87
88 // Tras una herramienta: convertir su resultado en la respuesta…
89 if (text.startsWith('[resultado')) {
90 const body = text.slice(text.indexOf('\n') + 1).trim();
91 if (body.startsWith('ERROR:')) return 'No pude: ' + body.slice(6).trim();
92 // …o encadenar: si lo leído era para un gráfico, generar la app ahora.
93 if (text.startsWith('[resultado fs.read')) {
94 const prevUser = [...history].reverse().find(m => m.role === 'user' && !m.content.startsWith('['));
95 if (prevUser && /(grafic|visualiza|gr[aá]fico|chart|barras)/i.test(prevUser.content)) {
96 const file = prevUser.content.match(/(\S+\.(?:csv|tsv|xlsx?))/i)?.[1] || 'datos';
97 return call({ tool: 'app.create', args: { name: 'gráfico ' + file, html: chartApp(file, body) } });
98 }
99 }
100 return body;
101 }
102
103 const t = text.toLowerCase();
104
105 // web (antes que «abre <app>» para que gane la URL)
106 const url = text.match(/https?:\/\/[^\s"'<>]+/);
107 if (url && /(abre|visita|entra|descarga|mira|lee|busca|ve a)/.test(t))
108 return call({ tool: 'web.fetch', args: { url: url[0] } });
109
110 // crear skill (modo básico: plantilla a partir de la descripción)
111 const mSkill = text.match(/(?:cr[eé]a(?:me)?|hazme|genera)\s+una\s+skill\s+(?:para|de|que)\s+(.+)/i);
112 if (mSkill) {
113 const what = mSkill[1].replace(/[?.!]+$/, '').trim();
114 return call({ tool: 'skill.create', args: { name: what.slice(0, 40), description: 'Skill para ' + what,
115 instructions: 'Cuando el usuario pida «' + what + '», ayúdale paso a paso, sé concreto y usa las herramientas disponibles (archivos, web, apps) cuando aporten.' } });
116 }
117 if (/(lista|ver|muestra|qué|que).*skills/.test(t)) return call({ tool: 'skill.list', args: {} });
118
119 // búsqueda de imágenes
120 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);
121 if (mImg && !url) return call({ tool: 'web.images', args: { query: mImg[1].replace(/[?.!]+$/, '').trim() } });
122 // búsqueda web (texto)
123 const mSearch = text.match(/(?:busca(?:r)?|buscame|google(?:a)?|encuentra|investiga)\s+(?:en\s+(?:internet|la\s+web|google)\s+)?(.+)/i);
124 if (mSearch && !url && /(busca|google|encuentra|investiga)/.test(t))
125 return call({ tool: 'web.search', args: { query: mSearch[1].replace(/[?.!]+$/, '').trim() } });
126
127 // tareas
128 const mTask = text.match(/dentro de (\d+)\s*min(?:uto)?s?\s*(?:que\s*)?(.*)/i);
129 if (mTask && /(recu[eé]rdame|av[ií]same|programa|dentro de \d+ *min)/.test(t))
130 return call({ tool: 'tasks.add', args: { inMinutes: Number(mTask[1]), prompt: mTask[2].trim() || text } });
131 if (/(lista|ver|muestra|qué|que).*(tareas)/.test(t) || t === 'tareas')
132 return call({ tool: 'tasks.list', args: {} });
133
134 // memoria persistente
135 const mRemember = text.match(/\brecuerda (?:que )?(.+)/i);
136 if (mRemember) return call({ tool: 'memory.save', args: { fact: mRemember[1].trim() } });
137 if (/(qué|que) recuerdas|tu memoria|mis recuerdos/.test(t))
138 return call({ tool: 'memory.list', args: {} });
139 const mForget = text.match(/\bolvida (?:el )?(m[a-z0-9]{6})\b/i);
140 if (mForget) return call({ tool: 'memory.forget', args: { id: mForget[1] } });
141
142 // vault
143 const mSecret = text.match(/guarda (?:el |la )?(?:secreto|contraseña) ([\w.@-]+)\s*[:=]\s*(\S+)/i);
144 if (mSecret) return call({ tool: 'vault.set', args: { name: mSecret[1], secret: mSecret[2] } });
145 if (/(lista|ver|muestra).*(secretos|contraseñas)/.test(t))
146 return call({ tool: 'vault.list', args: {} });
147 const mGet = text.match(/(?:dame|lee|cu[aá]l es) (?:el |la )?(?:secreto|contraseña)(?: de)? ([\w.@-]+)/i);
148 if (mGet) return call({ tool: 'vault.get', args: { name: mGet[1] } });
149
150 // datos → gráfico (lee el archivo; el [resultado] de arriba crea la app)
151 const mViz = text.match(/(?:grafica|graficar|visualiza|visualizar|gr[aá]fico|chart|barras)\b.*?(\S+\.(?:csv|tsv|xlsx?))/i);
152 if (mViz) return call({ tool: 'fs.read', args: { path: mViz[1] } });
153
154 // automatización entre carpetas
155 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);
156 if (mWatch && /(vigila|automatiza|observa|monitoriza|cuando)/.test(t) && /(procesa|deja|salida|convierte|→|copia)/.test(t))
157 return call({ tool: 'fs.watch', args: { from: mWatch[1], to: mWatch[2] } });
158 if (/(lista|ver|muestra|qué|que).*(automatizaciones|vigilancias)/.test(t))
159 return call({ tool: 'fs.watch_list', args: {} });
160
161 // copia one-shot entre carpetas
162 const mCopy = text.match(/copia(?:r)?\s+(?:todos\s+)?(?:los\s+)?([\w*.]+)\s+de\s+([\w.-]+)\s+a\s+([\w.-]+)/i);
163 if (mCopy) {
164 let pattern = mCopy[1];
165 if (!pattern.includes('*')) pattern = '*' + (pattern.startsWith('.') ? pattern : '.' + pattern);
166 return call({ tool: 'fs.copy', args: { pattern, from: mCopy[2], to: mCopy[3] } });
167 }
168
169 // archivos
170 if (/(autoriza|elige|selecciona|añade|conecta).*(carpeta|directorio)/.test(t))
171 return call({ tool: 'fs.pick_folder', args: {} });
172 if (/(lista|muestra|qué hay|que hay|enséñame|ver).*(archivos|ficheros|carpeta|directorio)/.test(t))
173 return call({ tool: 'fs.list', args: {} });
174 const mRead = text.match(/lee (?:el (?:archivo|fichero) )?([\w./ -]+\.\w+)/i);
175 if (mRead) return call({ tool: 'fs.read', args: { path: mRead[1].trim() } });
176 const mWrite = text.match(/escribe (?:en )?([\w./-]+\.\w+)\s*[:=]\s*([\s\S]+)/i);
177 if (mWrite) return call({ tool: 'fs.write', args: { path: mWrite[1], content: mWrite[2] } });
178
179 // apps
180 if (/(crea|hazme|haz|genera|quiero|móntame|montame)/.test(t) || /^(reloj|notas|calculadora)$/.test(t)) {
181 const kind = /reloj|hora/.test(t) ? 'reloj' : /nota/.test(t) ? 'notas' : /calcul/.test(t) ? 'calculadora'
182 : /(arte|part[ií]culas|galaxia|aurora|webgl)/.test(t) ? 'arte' : null;
183 if (kind) return call({ tool: 'app.create', args: { name: kind, html: APPS[kind]() } });
184 if (/(app|aplicaci|web|página|pagina|juego|dashboard|panel)/.test(t))
185 return call({ tool: 'app.create', args: { name: 'boceto', html: generic(text) } });
186 }
187 const mOpen = t.match(/abre (?:la app )?([\wáéíóúñ-]+)/);
188 if (mOpen && !url) return call({ tool: 'app.open', args: { name: mOpen[1] } });
189 if (/(lista|ver|muestra|qué|que).*apps/.test(t)) return call({ tool: 'app.list', args: {} });
190
191 if (/^(hola|buenas|hey|hi)\b/.test(t)) return '¡Hola! ' + HELP;
192 return HELP;
193}