| 1 | // Terminal de Elffuss Code: xterm.js (VT100 real) + un readline propio que |
| 2 | // ejecuta contra shell.js (los ficheros REALES del proyecto). xterm no trae |
| 3 | // shell: nosotros gestionamos la línea (edición, historial, cursor) y delegamos |
| 4 | // la ejecución en shell.exec. La misma orden la puede lanzar la elfa vía el |
| 5 | // tool `terminal.run`, y su salida aparece aquí. |
| 6 | import * as shell from './shell.js'; |
| 7 | |
| 8 | let term = null, fit = null, ready = false; |
| 9 | let Terminal = null, FitAddon = null; |
| 10 | let line = '', pos = 0, histIdx = -1, busy = false; |
| 11 | let enCurso = null; // AbortController del comando que se está ejecutando |
| 12 | const XT = '@xterm/xterm@5.5.0', FIT = '@xterm/addon-fit@0.10.0'; |
| 13 | |
| 14 | // IMPORTANTE: cargamos xterm como ESM, no UMD. Monaco trae un loader AMD |
| 15 | // (define/require) y la build UMD de xterm se registra como «define anónimo» |
| 16 | // en vez de exponer window.Terminal → «Can only have one anonymous define». |
| 17 | // El import ESM esquiva por completo el define de Monaco. |
| 18 | async function loadXterm() { |
| 19 | if (Terminal) return; |
| 20 | if (!document.getElementById('xterm-css')) { |
| 21 | const l = document.createElement('link'); |
| 22 | l.id = 'xterm-css'; l.rel = 'stylesheet'; l.href = `https://cdn.jsdelivr.net/npm/${XT}/css/xterm.min.css`; |
| 23 | document.head.appendChild(l); |
| 24 | } |
| 25 | const [xt, ft] = await Promise.all([ |
| 26 | import(`https://cdn.jsdelivr.net/npm/${XT}/+esm`), |
| 27 | import(`https://cdn.jsdelivr.net/npm/${FIT}/+esm`), |
| 28 | ]); |
| 29 | Terminal = xt.Terminal || (xt.default && xt.default.Terminal); |
| 30 | FitAddon = ft.FitAddon || (ft.default && ft.default.FitAddon) || ft.default; |
| 31 | } |
| 32 | |
| 33 | const prompt = () => `\x1b[36m${shell.cwdString()}\x1b[0m \x1b[35m❯\x1b[0m `; |
| 34 | const writePrompt = () => term.write('\r\n' + prompt()); |
| 35 | // Redibuja la línea de entrada (prompt + buffer) y coloca el cursor en `pos`. |
| 36 | function redraw() { |
| 37 | term.write('\r\x1b[K' + prompt() + line); |
| 38 | const back = line.length - pos; |
| 39 | if (back > 0) term.write(`\x1b[${back}D`); |
| 40 | } |
| 41 | |
| 42 | async function run(raw) { |
| 43 | const cmd = raw.trim(); |
| 44 | if (!cmd) { writePrompt(); return; } |
| 45 | busy = true; |
| 46 | const ac = (enCurso = new AbortController()); |
| 47 | try { |
| 48 | const out = await shell.exec(cmd, { signal: ac.signal }); |
| 49 | if (out === '\f') term.clear(); |
| 50 | else if (out) term.write('\r\n' + out.replace(/\n/g, '\r\n')); |
| 51 | } catch (e) { |
| 52 | term.write('\r\n\x1b[31m' + String(e && e.message || e).replace(/\n/g, '\r\n') + '\x1b[0m'); |
| 53 | } |
| 54 | if (enCurso === ac) enCurso = null; |
| 55 | busy = false; |
| 56 | writePrompt(); |
| 57 | } |
| 58 | |
| 59 | function onKey(data) { |
| 60 | // Con un comando en marcha solo se atiende Ctrl+C, y PARA el comando. Antes |
| 61 | // se ignoraba todo, también Ctrl+C: un `npm run dev` lanzado aquí no había |
| 62 | // forma de cortarlo, y ni cerrando el bridge se soltaba el terminal. |
| 63 | if (busy) { |
| 64 | if (data === '\x03' && enCurso && !enCurso.signal.aborted) { term.write('^C'); enCurso.abort(); } |
| 65 | return; |
| 66 | } |
| 67 | switch (data) { |
| 68 | case '\r': // Enter |
| 69 | { const cmd = line; line = ''; pos = 0; histIdx = -1; run(cmd); return; } |
| 70 | case '\x7f': // Retroceso |
| 71 | if (pos > 0) { line = line.slice(0, pos - 1) + line.slice(pos); pos--; redraw(); } return; |
| 72 | case '\x1b[3~': // Supr |
| 73 | if (pos < line.length) { line = line.slice(0, pos) + line.slice(pos + 1); redraw(); } return; |
| 74 | case '\x03': // Ctrl+C |
| 75 | term.write('^C'); line = ''; pos = 0; histIdx = -1; writePrompt(); return; |
| 76 | case '\x0c': // Ctrl+L |
| 77 | term.clear(); redraw(); return; |
| 78 | case '\x1b[A': case '\x1b[B': { // arriba / abajo: historial |
| 79 | const h = shell.getHistory(); if (!h.length) return; |
| 80 | if (histIdx === -1) histIdx = h.length; |
| 81 | histIdx = Math.max(0, Math.min(h.length, histIdx + (data === '\x1b[A' ? -1 : 1))); |
| 82 | line = h[histIdx] || ''; pos = line.length; redraw(); return; |
| 83 | } |
| 84 | case '\x1b[C': if (pos < line.length) { pos++; term.write('\x1b[C'); } return; // derecha |
| 85 | case '\x1b[D': if (pos > 0) { pos--; term.write('\x1b[D'); } return; // izquierda |
| 86 | case '\x1b[H': case '\x01': pos = 0; redraw(); return; // Inicio / Ctrl+A |
| 87 | case '\x1b[F': case '\x05': pos = line.length; redraw(); return; // Fin / Ctrl+E |
| 88 | case '\t': complete(); return; // Tab: completar rutas |
| 89 | } |
| 90 | if (data.length !== 1 || data.charCodeAt(0) < 32) return; // control/escape: ignorar |
| 91 | line = line.slice(0, pos) + data + line.slice(pos); pos += data.length; redraw(); |
| 92 | } |
| 93 | |
| 94 | // Completado de rutas simple: mira el último token contra el directorio actual. |
| 95 | async function complete() { |
| 96 | const frag = (line.slice(0, pos).split(/\s+/).pop()) || ''; |
| 97 | const slash = frag.lastIndexOf('/'); |
| 98 | const dirPart = slash >= 0 ? frag.slice(0, slash + 1) : ''; |
| 99 | const base = slash >= 0 ? frag.slice(slash + 1) : frag; |
| 100 | let names; |
| 101 | try { names = await shell.listDir(dirPart); } catch { return; } |
| 102 | const matches = names.filter(n => n.name.startsWith(base)); |
| 103 | if (matches.length === 1) { |
| 104 | const add = matches[0].name.slice(base.length) + (matches[0].kind === 'directory' ? '/' : ' '); |
| 105 | line = line.slice(0, pos) + add + line.slice(pos); pos += add.length; redraw(); |
| 106 | } else if (matches.length > 1) { |
| 107 | term.write('\r\n' + matches.map(m => m.kind === 'directory' ? '\x1b[36m' + m.name + '/\x1b[0m' : m.name).join(' ')); |
| 108 | writePrompt(); term.write(line); if (line.length - pos > 0) term.write(`\x1b[${line.length - pos}D`); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // Monta el terminal en `host` (una vez). Idempotente; refoca si ya existe. |
| 113 | export async function mount(host) { |
| 114 | if (ready) { setTimeout(() => { fit && fit.fit(); term && term.focus(); }, 0); return; } |
| 115 | await loadXterm(); |
| 116 | term = new Terminal({ |
| 117 | fontSize: 12.5, fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', |
| 118 | cursorBlink: true, convertEol: false, scrollback: 2000, |
| 119 | theme: { background: '#0b0d12', foreground: '#e8ebf4', cursor: '#ff4d8d', selectionBackground: '#7c5cff55', |
| 120 | brightBlack: '#6b7280', red: '#ff6b8b', green: '#7ee787', yellow: '#ffd479', blue: '#7c5cff', magenta: '#ff4d8d', cyan: '#56d4dd' }, |
| 121 | }); |
| 122 | fit = new FitAddon(); |
| 123 | term.loadAddon(fit); |
| 124 | term.open(host); |
| 125 | fit.fit(); |
| 126 | host.addEventListener('mousedown', () => setTimeout(() => term.focus(), 0)); |
| 127 | term.onData(onKey); |
| 128 | const cap = shell.capabilities(); |
| 129 | term.write('\x1b[1;35mElffuss shell\x1b[0m \x1b[90m— ficheros reales del proyecto, en tu navegador.\x1b[0m'); |
| 130 | const rtHint = cap.bridge ? '🔌 Bridge local conectado: node/npm/python REALES en tu máquina.' |
| 131 | : 'Escribe \x1b[0m\x1b[32mhelp\x1b[0m\x1b[90m. node/npm/python reales → conecta el Bridge local (⚙ Ajustes).'; |
| 132 | term.write('\r\n\x1b[90m' + rtHint + '\x1b[0m'); |
| 133 | writePrompt(); |
| 134 | ready = true; |
| 135 | setTimeout(() => term.focus(), 0); |
| 136 | } |
| 137 | |
| 138 | export function refit() { if (ready) setTimeout(() => fit && fit.fit(), 0); } |
| 139 | export function focus() { if (ready) term.focus(); } |
| 140 | export function isReady() { return ready; } |
| 141 | export function clearScreen() { if (ready) { term.clear(); line = ''; pos = 0; term.write('\r\x1b[K' + prompt()); term.focus(); } } |
| 142 | |
| 143 | // Eco de una orden lanzada por la elfa (para que el usuario la vea en el terminal). |
| 144 | export function echoAgent(cmd, out) { |
| 145 | if (!ready) return; |
| 146 | term.write('\r\x1b[K' + prompt() + '\x1b[90m' + cmd + ' (elfa)\x1b[0m'); |
| 147 | if (out) term.write('\r\n' + shell.stripAnsi(out).replace(/\n/g, '\r\n')); |
| 148 | writePrompt(); term.write(line); |
| 149 | } |