| 1 | // Autonomous CEO brain (shared by Elffuss Code and Elffuss Claw): when the user |
| 2 | // is NOT asking for anything (idle) and a local model is loaded, the elf "works |
| 3 | // on her own" — she surveys the workspace, splits the work across several |
| 4 | // profiles that think IN PARALLEL (each one a line of thought in the Mind view) |
| 5 | // and synthesises improvement proposals. |
| 6 | // |
| 7 | // Deliberately tool-agnostic: each app injects its own workspace adapter |
| 8 | // (`init({ workspace, ... })`) — Code uses code.js (a code project), Claw uses |
| 9 | // fs.js (folders with permission). The core neither knows nor cares which. |
| 10 | // |
| 11 | // Safety: it does NOT modify your files. It leaves the proposals in an additive |
| 12 | // folder (it never touches what already exists) and makes them "float" in the |
| 13 | // Mind. It STOPS the moment it detects user activity and resumes once things |
| 14 | // are idle again. |
| 15 | import { Agent } from './agent.js'; |
| 16 | import { humanizeTool } from './humanize.js'; |
| 17 | |
| 18 | const IDLE_MS = 18000; // no activity for this long → the CEO starts working |
| 19 | const TICK_MS = 3000; // how often we check |
| 20 | // Five minutes between automatic cycles: on a much shorter cooldown, one idle |
| 21 | // afternoon generated THOUSANDS of files. "Think now" (forceCycle) is still |
| 22 | // available without waiting for this. |
| 23 | const COOLDOWN_MS = 300000; |
| 24 | const SOUL_CAP = 25; // loose files before consolidating into archivo.md |
| 25 | |
| 26 | // default profile if the host app does not supply its own |
| 27 | const GENERIC_PROFILES = [ |
| 28 | { id: 'p1', name: 'Revisión', focus: 'qué mejorar de forma concreta y accionable', color: '#7c5cff' }, |
| 29 | { id: 'p2', name: 'Calidad', focus: 'errores, casos borde, cosas que podrían fallar', color: '#49e8ff' }, |
| 30 | ]; |
| 31 | |
| 32 | const slug = s => String(s).toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '') |
| 33 | .replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '').slice(0, 24) || 'perfil'; |
| 34 | |
| 35 | // ── namespace (localStorage) and workspace adapter: supplied by the host app ── |
| 36 | let NS = 'elffuss'; // prefix for the localStorage keys |
| 37 | let ws = null; // { isReady, tree, write, read, list, remove } |
| 38 | let getProvider = () => null; |
| 39 | let isBusy = () => false; // does the user have work queued/in flight? → priority |
| 40 | let defaultProfiles = GENERIC_PROFILES; |
| 41 | const K = suffix => NS + '.' + suffix; |
| 42 | |
| 43 | function loadProfiles() { |
| 44 | try { const s = JSON.parse(localStorage.getItem(K('ceoProfiles'))); if (Array.isArray(s) && s.length) return s; } catch { /* */ } |
| 45 | return defaultProfiles.map(p => ({ ...p })); |
| 46 | } |
| 47 | let profiles = null; |
| 48 | export function getProfiles() { if (!profiles) profiles = loadProfiles(); return profiles; } |
| 49 | export function setProfiles(list) { |
| 50 | const used = new Set(); |
| 51 | profiles = (list || []).filter(p => p && p.name).map(p => { |
| 52 | let id = p.id || slug(p.name); let n = id, i = 2; |
| 53 | while (used.has(n)) n = id + '-' + i++; |
| 54 | used.add(n); |
| 55 | 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' }; |
| 56 | }); |
| 57 | if (!profiles.length) profiles = defaultProfiles.map(p => ({ ...p })); |
| 58 | try { localStorage.setItem(K('ceoProfiles'), JSON.stringify(profiles)); } catch { /* */ } |
| 59 | emit('ceo', { type: 'reprogram', text: 'Perfiles actualizados: ' + profiles.map(p => p.name).join(', '), profiles }); |
| 60 | return profiles; |
| 61 | } |
| 62 | |
| 63 | let enabled = false, running = false, lastActivity = Date.now(), timer = null, lastCycleEnd = 0, cycleN = 0; |
| 64 | |
| 65 | // Reprogrammable MISSION: the user can re-aim the brain from the Mind view |
| 66 | // ("focus on security", "optimise my spreadsheets", "document everything"…). |
| 67 | let DEFAULT_MISSION = 'Revisar el espacio de trabajo y proponer mejoras concretas y accionables.'; |
| 68 | let mission = null; |
| 69 | function ensureMission() { if (mission == null) { try { mission = localStorage.getItem(K('ceoMission')) || DEFAULT_MISSION; } catch { mission = DEFAULT_MISSION; } } } |
| 70 | export function getMission() { ensureMission(); return mission; } |
| 71 | export function setMission(text) { |
| 72 | mission = (text || '').trim() || DEFAULT_MISSION; |
| 73 | try { localStorage.setItem(K('ceoMission'), mission); } catch { /* */ } |
| 74 | emit('ceo', { type: 'reprogram', text: 'Nueva misión recibida: ' + mission }); |
| 75 | lastCycleEnd = 0; lastActivity = Date.now() - IDLE_MS; // start a cycle soon with the new mission |
| 76 | return mission; |
| 77 | } |
| 78 | |
| 79 | // "Soul" folder where the brain creates and stores EVERYTHING (configurable). |
| 80 | let DEFAULT_SOUL = '.elffuss/soul'; |
| 81 | let soulDir = null; |
| 82 | function ensureSoulDir() { if (soulDir == null) { try { soulDir = localStorage.getItem(K('ceoDir')) || DEFAULT_SOUL; } catch { soulDir = DEFAULT_SOUL; } } } |
| 83 | export function getSoulDir() { ensureSoulDir(); return soulDir; } |
| 84 | export function setSoulDir(dir) { |
| 85 | soulDir = (dir || '').trim().replace(/^\/+|\/+$/g, '') || DEFAULT_SOUL; |
| 86 | try { localStorage.setItem(K('ceoDir'), soulDir); } catch { /* */ } |
| 87 | emit('ceo', { type: 'reprogram', text: 'Nueva carpeta-alma: ' + soulDir + '/' }); |
| 88 | return soulDir; |
| 89 | } |
| 90 | |
| 91 | // ── cross-tab semaphore: ONE brain runs, ALL tabs display ────────────────── |
| 92 | // The leader holds an exclusive Web Lock (released on its own when the tab is |
| 93 | // closed); it broadcasts its thoughts over BroadcastChannel so the rest can see |
| 94 | // them. (Isolated per origin by the browser itself: Code and Claw never cross.) |
| 95 | let isLeader = false, bc = null, realEmit = () => {}, crossTabWired = false; |
| 96 | function initCrossTab() { |
| 97 | if (crossTabWired) return; |
| 98 | crossTabWired = true; |
| 99 | try { |
| 100 | bc = new BroadcastChannel(NS + '-ceo'); |
| 101 | bc.onmessage = e => { if (e.data && e.data.kind === 'thought') realEmit(e.data.channel, e.data.ev); }; |
| 102 | } catch { /* no BroadcastChannel */ } |
| 103 | if (navigator.locks && navigator.locks.request) { |
| 104 | navigator.locks.request(NS + '-ceo-leader', { mode: 'exclusive' }, () => new Promise(() => { isLeader = true; })) |
| 105 | .catch(() => { isLeader = true; }); |
| 106 | } else { isLeader = true; } |
| 107 | } |
| 108 | function emit(channel, ev) { |
| 109 | realEmit(channel, ev); |
| 110 | try { bc && bc.postMessage({ kind: 'thought', channel, ev }); } catch { /* ev not serialisable */ } |
| 111 | } |
| 112 | |
| 113 | // init({ workspace, provider, onEvent, isBusy, namespace, defaultProfiles, defaultMission, defaultSoulDir }) |
| 114 | export function init(opts = {}) { |
| 115 | if (opts.workspace) ws = opts.workspace; |
| 116 | if (opts.provider) getProvider = opts.provider; |
| 117 | if (opts.onEvent) realEmit = opts.onEvent; |
| 118 | if (opts.isBusy) isBusy = opts.isBusy; |
| 119 | if (opts.namespace) NS = opts.namespace; |
| 120 | if (opts.defaultProfiles) defaultProfiles = opts.defaultProfiles; |
| 121 | if (opts.defaultMission) DEFAULT_MISSION = opts.defaultMission; |
| 122 | if (opts.defaultSoulDir) DEFAULT_SOUL = opts.defaultSoulDir; |
| 123 | initCrossTab(); |
| 124 | } |
| 125 | export function isThisTabLeader() { return isLeader; } |
| 126 | export function noteActivity() { lastActivity = Date.now(); if (running) running = 'interrupt'; } |
| 127 | export function isEnabled() { return enabled; } |
| 128 | export function isRunning() { return !!running; } |
| 129 | // Play/stop: persisted HERE (single source) — any button that touches it stays |
| 130 | // in sync, and the choice survives a page reload. |
| 131 | export function wasEnabledLastSession() { try { return localStorage.getItem(K('ceoEnabled')) === '1'; } catch { return false; } } |
| 132 | // did the user ever actually decide (play or stop)? This tells "never touched |
| 133 | // it" apart from "paused it on purpose" — only the first should auto-enable |
| 134 | // when the Mind is opened; the second must be RESPECTED, not overridden. |
| 135 | export function hasDecided() { try { return localStorage.getItem(K('ceoEnabled')) != null; } catch { return false; } } |
| 136 | export function enable() { |
| 137 | if (enabled) return; |
| 138 | enabled = true; lastActivity = Date.now(); schedule(); |
| 139 | try { localStorage.setItem(K('ceoEnabled'), '1'); } catch { /* */ } |
| 140 | emit('sys', { type: 'status', text: 'CEO en guardia — trabajaré cuando estés ocioso' }); |
| 141 | } |
| 142 | export function disable() { |
| 143 | enabled = false; running = false; if (timer) clearTimeout(timer); |
| 144 | try { localStorage.setItem(K('ceoEnabled'), '0'); } catch { /* */ } |
| 145 | emit('sys', { type: 'status', text: 'CEO en pausa' }); |
| 146 | } |
| 147 | |
| 148 | function schedule() { if (timer) clearTimeout(timer); timer = setTimeout(tick, TICK_MS); } |
| 149 | |
| 150 | // "Think now" — skips the idle wait. It still respects the semaphore: if |
| 151 | // another tab is the leader, it does not compete for the accelerator. |
| 152 | export async function forceCycle() { |
| 153 | if (!isLeader) { emit('ceo', { type: 'paused', text: 'Otra pestaña lleva el cerebro — ábrela ahí para forzar un ciclo.' }); return false; } |
| 154 | if (running) return false; |
| 155 | // isReady() may be sync (Code: handle in memory) or async (Claw: queries IndexedDB) — always awaited. |
| 156 | if (!(await ws?.isReady()) || !getProvider()) { emit('ceo', { type: 'paused', text: 'Necesito un espacio de trabajo abierto y un modelo cargado.' }); return false; } |
| 157 | try { await runCycle(); } finally { lastCycleEnd = Date.now(); } |
| 158 | return true; |
| 159 | } |
| 160 | |
| 161 | async function tick() { |
| 162 | if (!enabled) return; |
| 163 | const idle = Date.now() - lastActivity; |
| 164 | const rested = Date.now() - lastCycleEnd > COOLDOWN_MS; |
| 165 | const mightRun = isLeader && !running && !isBusy() && idle >= IDLE_MS && rested && getProvider(); |
| 166 | if (mightRun && await ws?.isReady()) { |
| 167 | try { await runCycle(); } catch { /* next cycle */ } |
| 168 | lastCycleEnd = Date.now(); |
| 169 | } |
| 170 | schedule(); |
| 171 | } |
| 172 | |
| 173 | // helper: runs the agent with the current provider over a prompt, emitting |
| 174 | // tokens/tools to a channel. Returns the final text. Tool calls ALWAYS go |
| 175 | // through the same runTool the normal chat uses (the real Agent.handle). |
| 176 | async function think(channel, task) { |
| 177 | const prov = getProvider(); |
| 178 | if (!prov) return ''; |
| 179 | const a = new Agent({ chat: (h, s, cb) => prov.chat(h, s, cb) }); |
| 180 | let out = ''; |
| 181 | await a.handle(task, ev => { |
| 182 | if (running === 'interrupt') throw new Error('interrumpido'); |
| 183 | if (ev.type === 'token') { out += ev.text; emit(channel, { type: 'token', text: ev.text }); } |
| 184 | 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 }); |
| 185 | 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) }); |
| 186 | else if (ev.type === 'text') { out = ev.text; } |
| 187 | }); |
| 188 | return out; |
| 189 | } |
| 190 | |
| 191 | async function runCycle() { |
| 192 | running = true; |
| 193 | cycleN++; |
| 194 | emit('ceo', { type: 'cycle', n: cycleN, text: 'Nuevo ciclo: reviso el espacio de trabajo y reparto el trabajo…' }); |
| 195 | |
| 196 | let tree = ''; |
| 197 | try { tree = await ws.tree({ depth: 2 }); } catch { /* no workspace */ } |
| 198 | emit('ceo', { type: 'survey', text: 'Panorama captado (' + tree.split('\n').length + ' entradas). Delegando…' }); |
| 199 | |
| 200 | const brief = (d) => `MISIÓN del equipo (fijada por el usuario): ${getMission()}\n` + |
| 201 | `Eres el jefe de ${d.name}. Dentro de esa misión, céntrate en: ${d.focus}. ` + |
| 202 | `Explora lo mínimo con tus herramientas y propón UNA mejora CONCRETA y accionable, ` + |
| 203 | `entendible por un humano. Sé breve. No modifiques nada existente: solo la propuesta.`; |
| 204 | const proposals = await Promise.all(getProfiles().map(async d => { |
| 205 | emit(d.id, { type: 'open', name: d.name, focus: d.focus }); |
| 206 | try { const p = await think(d.id, brief(d)); emit(d.id, { type: 'done', text: p }); return { dept: d.name, text: p }; } |
| 207 | catch { emit(d.id, { type: 'done', text: '(interrumpido)' }); return null; } |
| 208 | })); |
| 209 | if (running === 'interrupt') { running = false; emit('ceo', { type: 'paused', text: 'Vuelves tú — dejo lo mío y te cedo el mando.' }); return; } |
| 210 | |
| 211 | const valid = proposals.filter(Boolean).filter(p => p.text && p.text.length > 8); |
| 212 | const md = `# Propuestas de mejora — ciclo ${cycleN}\n\n**Misión:** ${getMission()}\n\n` + |
| 213 | valid.map(p => `## ${p.dept}\n${p.text}\n`).join('\n') + |
| 214 | `\n_— generado por el cerebro CEO de Elffuss mientras estabas ocioso._\n`; |
| 215 | const d = new Date(); |
| 216 | 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')}`; |
| 217 | const topic = slug((valid[0]?.text || 'ciclo').split(/[.,;\n]/)[0]) || 'ciclo'; |
| 218 | const path = `${getSoulDir()}/${stamp}-${topic}.md`; |
| 219 | try { |
| 220 | await rotateSoul(); |
| 221 | await ws.write({ path, content: md }); |
| 222 | emit('ceo', { type: 'built', text: `Propuesta guardada en ${path}`, path, md, proposals: valid }); |
| 223 | } catch (e) { |
| 224 | emit('ceo', { type: 'built', text: 'Propuesta lista (no pude escribir el fichero)', md, proposals: valid }); |
| 225 | } |
| 226 | running = false; |
| 227 | } |
| 228 | |
| 229 | // Rotation: if there are too many loose files, the OLDEST ones are consolidated |
| 230 | // into a single archivo.md and deleted — so we do not end up with thousands. |
| 231 | async function rotateSoul() { |
| 232 | try { |
| 233 | const soul = getSoulDir(); |
| 234 | const names = (await ws.list(soul)).filter(n => n.endsWith('.md') && n !== 'archivo.md'); |
| 235 | if (names.length < SOUL_CAP) return; |
| 236 | names.sort(); // the name starts with the date → chronological order |
| 237 | const excess = names.slice(0, names.length - SOUL_CAP + 1); |
| 238 | let archive = ''; try { archive = await ws.read({ path: `${soul}/archivo.md` }); } catch { archive = '# Archivo histórico del cerebro\n'; } |
| 239 | for (const name of excess) { |
| 240 | try { archive += `\n---\n## ${name}\n${await ws.read({ path: `${soul}/${name}` })}\n`; } catch { /* */ } |
| 241 | } |
| 242 | await ws.write({ path: `${soul}/archivo.md`, content: archive.slice(-80000) }); |
| 243 | for (const name of excess) { try { await ws.remove(soul, name); } catch { /* */ } } |
| 244 | emit('ceo', { type: 'reprogram', text: `Consolidé ${excess.length} propuestas antiguas en archivo.md` }); |
| 245 | } catch { /* soulDir not created yet, or no permission: nothing to rotate */ } |
| 246 | } |