Elffuss BraidHub

utopia-ia/elffuss public

4e3eafecd7b2 · 13.4 KiBRawPermalink
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.
15import { Agent } from './agent.js';
16import { humanizeTool } from './humanize.js';
17
18const IDLE_MS = 18000; // 18 s sin actividad → el CEO se pone a trabajar
19const 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.
22const COOLDOWN_MS = 300000;
23const SOUL_CAP = 25; // ficheros sueltos antes de consolidar en archivo.md
24
25// perfil por defecto si la app anfitriona no da los suyos
26const 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
31const 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 ──
35let NS = 'elffuss'; // prefijo de las claves de localStorage
36let ws = null; // { isReady, tree, write, read, list, remove }
37let getProvider = () => null;
38let isBusy = () => false; // ¿el usuario tiene trabajo en cola/procesándose? → prioridad
39let defaultProfiles = GENERIC_PROFILES;
40const K = suffix => NS + '.' + suffix;
41
42function 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}
46let profiles = null;
47export function getProfiles() { if (!profiles) profiles = loadProfiles(); return profiles; }
48export 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
62let 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»…).
66let DEFAULT_MISSION = 'Revisar el espacio de trabajo y proponer mejoras concretas y accionables.';
67let mission = null;
68function ensureMission() { if (mission == null) { try { mission = localStorage.getItem(K('ceoMission')) || DEFAULT_MISSION; } catch { mission = DEFAULT_MISSION; } } }
69export function getMission() { ensureMission(); return mission; }
70export 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).
79let DEFAULT_SOUL = '.elffuss/soul';
80let soulDir = null;
81function ensureSoulDir() { if (soulDir == null) { try { soulDir = localStorage.getItem(K('ceoDir')) || DEFAULT_SOUL; } catch { soulDir = DEFAULT_SOUL; } } }
82export function getSoulDir() { ensureSoulDir(); return soulDir; }
83export 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.)
94let isLeader = false, bc = null, realEmit = () => {}, crossTabWired = false;
95function 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}
107function 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 })
113export 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}
124export function isThisTabLeader() { return isLeader; }
125export function noteActivity() { lastActivity = Date.now(); if (running) running = 'interrupt'; }
126export function isEnabled() { return enabled; }
127export 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.
130export 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.
134export function hasDecided() { try { return localStorage.getItem(K('ceoEnabled')) != null; } catch { return false; } }
135export 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}
141export 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
147function 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.
151export 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
160async 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).
175async 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
190async 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.
230async 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}