| 1 | // Shell del proyecto: un intérprete POSIX-lite que opera SOBRE LOS FICHEROS |
| 2 | // REALES de la carpeta abierta (el FileSystemDirectoryHandle de code.js). No es |
| 3 | // una emulación: `ls`, `cat`, `grep`, `mkdir`, `rm`, `echo > fichero`… tocan el |
| 4 | // disco de verdad y el editor/árbol se refrescan. Es el mismo mundo que ve la |
| 5 | // elfa, así que también lo exponemos como herramienta `terminal.run`. |
| 6 | // |
| 7 | // Runtimes reales (node/npm/python): SOLO con un Bridge local conectado (ver |
| 8 | // bridge.js) se ejecutan de VERDAD en tu máquina — ver `capabilities()`. |
| 9 | import * as code from './tools/code.js'; |
| 10 | import * as bridgeClient from './bridge.js'; |
| 11 | |
| 12 | let cwd = []; // directorio actual, segmentos relativos a la raíz |
| 13 | const history = []; // historial de comandos (para ↑/↓ y `history`) |
| 14 | let onFsChange = () => {}; // el IDE refresca árbol/pestañas tras mutaciones |
| 15 | let onOpenFile = () => {}; // `open <fichero>` lo abre en Monaco |
| 16 | |
| 17 | export function setHooks({ fsChange, openFile } = {}) { |
| 18 | if (fsChange) onFsChange = fsChange; |
| 19 | if (openFile) onOpenFile = openFile; |
| 20 | } |
| 21 | export function reset() { cwd = []; } |
| 22 | export function cwdString() { return '/' + cwd.join('/'); } |
| 23 | export function getHistory() { return history.slice(); } |
| 24 | |
| 25 | // ¿Podemos lanzar runtimes reales? Solo por Bridge local conectado de verdad |
| 26 | // (WebContainers requiere licencia comercial de StackBlitz en producción — |
| 27 | // descartado por ahora, ver bridge.js). |
| 28 | export function capabilities() { |
| 29 | const bridge = bridgeClient.isConnected(); |
| 30 | return { crossOriginIsolated: !!self.crossOriginIsolated, webcontainers: false, bridge, realRuntime: bridge }; |
| 31 | } |
| 32 | |
| 33 | // ---- resolución de rutas ---- |
| 34 | // Combina un argumento con el cwd y normaliza . y .. → segmentos desde la raíz. |
| 35 | function resolve(arg = '') { |
| 36 | const base = arg.startsWith('/') ? [] : [...cwd]; |
| 37 | for (const seg of String(arg).split('/')) { |
| 38 | if (!seg || seg === '.') continue; |
| 39 | if (seg === '..') base.pop(); |
| 40 | else base.push(seg); |
| 41 | } |
| 42 | return base; |
| 43 | } |
| 44 | const root = () => { const h = code.handle(); if (!h) throw new Error('no hay proyecto abierto'); return h; }; |
| 45 | |
| 46 | async function dirHandle(segs, { create = false } = {}) { |
| 47 | let dir = root(); |
| 48 | for (const s of segs) dir = await dir.getDirectoryHandle(s, { create }); |
| 49 | return dir; |
| 50 | } |
| 51 | async function parentAndName(segs) { |
| 52 | const s = [...segs]; const name = s.pop(); |
| 53 | if (name == null) throw new Error('ruta vacía'); |
| 54 | return { parent: await dirHandle(s), name }; |
| 55 | } |
| 56 | async function fileHandle(segs, opts) { |
| 57 | const { parent, name } = await parentAndName(segs); |
| 58 | return parent.getFileHandle(name, opts); |
| 59 | } |
| 60 | async function readText(segs) { return (await (await fileHandle(segs)).getFile()).text(); } |
| 61 | async function writeText(segs, text) { |
| 62 | const fh = await fileHandle(segs, { create: true }); |
| 63 | const w = await fh.createWritable(); await w.write(text); await w.close(); |
| 64 | code.invalidateFileList?.(); onFsChange(); |
| 65 | } |
| 66 | // ¿ruta es directorio? (para `ls fichero`, `grep dir`, `cd`) |
| 67 | async function kindOf(segs) { |
| 68 | if (!segs.length) return 'directory'; |
| 69 | const { parent, name } = await parentAndName(segs); |
| 70 | try { await parent.getDirectoryHandle(name); return 'directory'; } catch {} |
| 71 | try { await parent.getFileHandle(name); return 'file'; } catch {} |
| 72 | return null; |
| 73 | } |
| 74 | |
| 75 | const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']); |
| 76 | const CYAN = s => `\x1b[36m${s}\x1b[0m`, RED = s => `\x1b[31m${s}\x1b[0m`, DIM = s => `\x1b[90m${s}\x1b[0m`, GRN = s => `\x1b[32m${s}\x1b[0m`, YEL = s => `\x1b[33m${s}\x1b[0m`; |
| 77 | const globToRe = g => new RegExp('^' + g.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$', 'i'); |
| 78 | const human = n => n < 1024 ? n + 'B' : n < 1048576 ? (n / 1024).toFixed(1) + 'K' : (n / 1048576).toFixed(1) + 'M'; |
| 79 | |
| 80 | // ---- comandos: (args[], stdin) → stdout (string). Lanzan Error en fallo. ---- |
| 81 | const CMDS = { |
| 82 | help() { |
| 83 | return 'Elffuss shell — opera sobre los ficheros REALES del proyecto:\n' + |
| 84 | ' ' + GRN('ls') + ' [-la] [ruta] ' + GRN('cd') + ' [ruta] ' + GRN('pwd') + ' ' + GRN('tree') + ' [ruta]\n' + |
| 85 | ' ' + GRN('cat') + ' <f...> ' + GRN('head') + '/' + GRN('tail') + ' [-n N] ' + GRN('wc') + ' [-l] ' + GRN('grep') + ' [-in] <patrón> [ruta]\n' + |
| 86 | ' ' + GRN('find') + ' [ruta] [-name g] ' + GRN('echo') + ' <txt> [> f] ' + GRN('mkdir') + '/' + GRN('touch') + '/' + GRN('rm') + ' [-r]/' + GRN('mv') + '/' + GRN('cp') + '\n' + |
| 87 | ' ' + GRN('open') + ' <f> (en el editor) ' + GRN('git') + ' status|log|branch ' + GRN('history') + ' ' + GRN('clear') + '\n' + |
| 88 | ' Soporta tuberías ' + YEL('|') + ' y redirección ' + YEL('>') + ' ' + YEL('>>') + '. ' + |
| 89 | (capabilities().bridge ? GRN('node/npm/python disponibles (Bridge local).') : DIM('node/npm/python: conecta el Bridge local (⚙ Ajustes).')); |
| 90 | }, |
| 91 | pwd() { return cwdString(); }, |
| 92 | async cd(args) { |
| 93 | const target = args.find(a => !a.startsWith('-')); |
| 94 | if (!target || target === '~') { cwd = []; return ''; } |
| 95 | const segs = resolve(target); |
| 96 | if (await kindOf(segs) !== 'directory') throw new Error(`cd: no existe el directorio: ${target}`); |
| 97 | cwd = segs; return ''; |
| 98 | }, |
| 99 | async ls(args) { |
| 100 | const long = args.some(a => /^-\w*l/.test(a)), all = args.some(a => /^-\w*a/.test(a)); |
| 101 | const target = args.find(a => !a.startsWith('-')) || ''; |
| 102 | const segs = resolve(target); |
| 103 | const k = await kindOf(segs); |
| 104 | if (k === 'file') return target; // ls de un fichero |
| 105 | if (k !== 'directory') throw new Error(`ls: no existe: ${target || '.'}`); |
| 106 | const dir = await dirHandle(segs); |
| 107 | const rows = []; |
| 108 | for await (const e of dir.values()) { |
| 109 | if (!all && (e.name.startsWith('.') || IGNORE.has(e.name))) continue; |
| 110 | rows.push(e); |
| 111 | } |
| 112 | rows.sort((a, b) => (a.kind !== b.kind ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name))); |
| 113 | if (!long) return rows.map(e => e.kind === 'directory' ? CYAN(e.name + '/') : e.name).join(' '); |
| 114 | const out = []; |
| 115 | for (const e of rows) { |
| 116 | if (e.kind === 'directory') out.push(`${DIM('dir ')} - ${CYAN(e.name + '/')}`); |
| 117 | else { const f = await e.getFile(); out.push(`${DIM('file')} ${human(f.size).padStart(6)} ${e.name}`); } |
| 118 | } |
| 119 | return out.join('\n'); |
| 120 | }, |
| 121 | async cat(args, stdin) { |
| 122 | const files = args.filter(a => !a.startsWith('-')); |
| 123 | if (!files.length) return stdin; |
| 124 | const parts = []; |
| 125 | for (const f of files) { |
| 126 | try { parts.push(await readText(resolve(f))); } |
| 127 | catch { throw new Error(`cat: ${f}: no existe`); } |
| 128 | } |
| 129 | return parts.join(''); |
| 130 | }, |
| 131 | async head(args, stdin) { |
| 132 | const n = +(args[args.indexOf('-n') + 1]) || 10; |
| 133 | const f = args.find(a => !a.startsWith('-') && !/^\d+$/.test(a)); |
| 134 | const text = f ? await readText(resolve(f)) : stdin; |
| 135 | return text.split('\n').slice(0, n).join('\n'); |
| 136 | }, |
| 137 | async tail(args, stdin) { |
| 138 | const n = +(args[args.indexOf('-n') + 1]) || 10; |
| 139 | const f = args.find(a => !a.startsWith('-') && !/^\d+$/.test(a)); |
| 140 | const text = f ? await readText(resolve(f)) : stdin; |
| 141 | const lines = text.split('\n'); return lines.slice(Math.max(0, lines.length - n)).join('\n'); |
| 142 | }, |
| 143 | async wc(args, stdin) { |
| 144 | const onlyLines = args.includes('-l'); |
| 145 | const f = args.find(a => !a.startsWith('-')); |
| 146 | const text = f ? await readText(resolve(f)) : stdin; |
| 147 | const lines = text === '' ? 0 : text.split('\n').length; |
| 148 | if (onlyLines) return String(lines); |
| 149 | const words = (text.match(/\S+/g) || []).length; |
| 150 | return `${lines}\t${words}\t${text.length}${f ? '\t' + f : ''}`; |
| 151 | }, |
| 152 | async tree(args) { |
| 153 | const target = args.find(a => !a.startsWith('-')) || ''; |
| 154 | return code.tree({ path: resolve(target).join('/'), depth: 3 }); |
| 155 | }, |
| 156 | async grep(args, stdin) { |
| 157 | const insensitive = args.some(a => /^-\w*i/.test(a)), numbers = args.some(a => /^-\w*n/.test(a)); |
| 158 | const rest = args.filter(a => !a.startsWith('-')); |
| 159 | const pattern = rest.shift(); |
| 160 | if (!pattern) throw new Error('grep: falta el patrón'); |
| 161 | const re = new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), insensitive ? 'i' : ''); |
| 162 | const hit = (line, i, prefix = '') => (prefix ? CYAN(prefix) + ':' : '') + (numbers ? DIM(i + 1 + ':') : '') + line.replace(re, m => `\x1b[1;31m${m}\x1b[0m`); |
| 163 | if (!rest.length) { // desde stdin (tubería) |
| 164 | return stdin.split('\n').map((l, i) => re.test(l) ? hit(l, i) : null).filter(x => x != null).join('\n'); |
| 165 | } |
| 166 | const out = []; let scanned = 0; |
| 167 | const scanText = (text, label) => |
| 168 | text.split('\n').forEach((l, i) => { if (re.test(l) && out.length < 400) out.push(hit(l, i, label)); }); |
| 169 | for (const target of rest) { |
| 170 | const segs = resolve(target); |
| 171 | const k = await kindOf(segs); |
| 172 | if (k === 'file') scanText(await readText(segs).catch(() => ''), target); |
| 173 | else if (k === 'directory') { // recursivo |
| 174 | const walk = async (dir, prefix) => { |
| 175 | for await (const e of dir.values()) { |
| 176 | if (IGNORE.has(e.name) || out.length >= 400 || scanned > 600) continue; |
| 177 | const p = prefix ? prefix + '/' + e.name : e.name; |
| 178 | if (e.kind === 'directory') { await walk(e, p); continue; } |
| 179 | const f = await e.getFile(); |
| 180 | if (f.size < 400_000) { scanned++; scanText(await f.text(), (target === '.' ? '' : target.replace(/\/$/, '') + '/') + p); } |
| 181 | } |
| 182 | }; |
| 183 | await walk(await dirHandle(segs), ''); |
| 184 | } else throw new Error(`grep: ${target}: no existe`); |
| 185 | } |
| 186 | return out.join('\n') || DIM('(sin coincidencias)'); |
| 187 | }, |
| 188 | async find(args) { |
| 189 | const nameIdx = args.indexOf('-name'); |
| 190 | const glob = nameIdx >= 0 ? globToRe(args[nameIdx + 1]) : null; |
| 191 | const start = args.find(a => !a.startsWith('-') && a !== (nameIdx >= 0 ? args[nameIdx + 1] : null)) || '.'; |
| 192 | const out = []; let count = 0; |
| 193 | const walk = async (dir, prefix) => { |
| 194 | for await (const e of dir.values()) { |
| 195 | if (IGNORE.has(e.name) || count > 2000) continue; |
| 196 | const p = prefix ? prefix + '/' + e.name : e.name; |
| 197 | count++; |
| 198 | if (!glob || glob.test(e.name)) out.push(e.kind === 'directory' ? CYAN(p) : p); |
| 199 | if (e.kind === 'directory') await walk(e, p); |
| 200 | } |
| 201 | }; |
| 202 | const segs = resolve(start === '.' ? '' : start); |
| 203 | if (await kindOf(segs) !== 'directory') throw new Error(`find: ${start}: no es un directorio`); |
| 204 | await walk(await dirHandle(segs), start === '.' ? '' : start); |
| 205 | return out.join('\n') || DIM('(nada)'); |
| 206 | }, |
| 207 | echo(args) { return args.join(' ').replace(/^["']|["']$/g, ''); }, |
| 208 | async mkdir(args) { |
| 209 | const t = args.find(a => !a.startsWith('-')); if (!t) throw new Error('mkdir: falta el nombre'); |
| 210 | await dirHandle(resolve(t), { create: true }); onFsChange(); return ''; |
| 211 | }, |
| 212 | async touch(args) { |
| 213 | const t = args.find(a => !a.startsWith('-')); if (!t) throw new Error('touch: falta el nombre'); |
| 214 | const segs = resolve(t); |
| 215 | if (await kindOf(segs) == null) await writeText(segs, ''); else onFsChange(); |
| 216 | return ''; |
| 217 | }, |
| 218 | // Soporta comodines (*, ?) y varios objetivos a la vez: `rm mejoras-*.md`. |
| 219 | // Sin esto, un patrón con * se buscaba como nombre LITERAL → «no existe» |
| 220 | // aunque hubiera decenas de coincidencias reales (bug real, visto en uso). |
| 221 | async rm(args) { |
| 222 | const recursive = args.some(a => /^-\w*r/.test(a)); |
| 223 | const targets = args.filter(a => !a.startsWith('-')); |
| 224 | if (!targets.length) throw new Error('rm: falta la ruta'); |
| 225 | const removed = []; |
| 226 | for (const t of targets) { |
| 227 | if (/[*?]/.test(t)) { |
| 228 | const parts = t.split('/'); const pattern = parts.pop(); |
| 229 | const dirSegs = resolve(parts.join('/')); |
| 230 | let dir; try { dir = await dirHandle(dirSegs); } catch { throw new Error(`rm: ${t}: no existe el directorio`); } |
| 231 | const re = globToRe(pattern); |
| 232 | const matches = []; |
| 233 | for await (const e of dir.values()) if (re.test(e.name)) matches.push(e); |
| 234 | if (!matches.length) throw new Error(`rm: ${t}: sin coincidencias`); |
| 235 | for (const e of matches) { |
| 236 | if (e.kind === 'directory' && !recursive) throw new Error(`rm: ${e.name}: es un directorio (usa -r)`); |
| 237 | await dir.removeEntry(e.name, { recursive }); |
| 238 | removed.push((dirSegs.length ? dirSegs.join('/') + '/' : '') + e.name); |
| 239 | } |
| 240 | } else { |
| 241 | const segs = resolve(t); const k = await kindOf(segs); |
| 242 | if (k == null) throw new Error(`rm: ${t}: no existe`); |
| 243 | if (k === 'directory' && !recursive) throw new Error(`rm: ${t}: es un directorio (usa -r)`); |
| 244 | const { parent, name } = await parentAndName(segs); |
| 245 | await parent.removeEntry(name, { recursive }); |
| 246 | removed.push(t); |
| 247 | } |
| 248 | } |
| 249 | code.invalidateFileList?.(); onFsChange(); |
| 250 | return removed.length > 1 ? `Eliminados ${removed.length}: ${removed.join(', ')}` : ''; |
| 251 | }, |
| 252 | async cp(args) { |
| 253 | const rest = args.filter(a => !a.startsWith('-')); |
| 254 | const [src, dst] = rest; if (!src || !dst) throw new Error('cp: uso: cp <origen> <destino>'); |
| 255 | await copyPath(resolve(src), resolve(dst)); onFsChange(); return ''; |
| 256 | }, |
| 257 | async mv(args) { |
| 258 | const rest = args.filter(a => !a.startsWith('-')); |
| 259 | const [src, dst] = rest; if (!src || !dst) throw new Error('mv: uso: mv <origen> <destino>'); |
| 260 | await copyPath(resolve(src), resolve(dst)); |
| 261 | const { parent, name } = await parentAndName(resolve(src)); |
| 262 | await parent.removeEntry(name, { recursive: true }); |
| 263 | code.invalidateFileList?.(); onFsChange(); return ''; |
| 264 | }, |
| 265 | async open(args) { |
| 266 | const t = args.find(a => !a.startsWith('-')); if (!t) throw new Error('open: falta el fichero'); |
| 267 | const segs = resolve(t); |
| 268 | if (await kindOf(segs) !== 'file') throw new Error(`open: ${t}: no es un fichero`); |
| 269 | onOpenFile(segs.join('/')); return DIM(`abriendo ${segs.join('/')} en el editor…`); |
| 270 | }, |
| 271 | history() { return history.map((h, i) => `${DIM((i + 1) + '')} ${h}`).join('\n'); }, |
| 272 | whoami() { return 'elffuss'; }, |
| 273 | date() { return new Date().toString(); }, |
| 274 | clear() { return '\f'; }, // la UI lo interpreta |
| 275 | async git(args) { |
| 276 | const sub = args[0]; |
| 277 | const info = await code.gitInfo(); |
| 278 | if (!info.isRepo) return DIM('no es un repositorio git (no hay .git)'); |
| 279 | if (sub === 'branch' || !sub) return '* ' + GRN(info.branch); |
| 280 | if (sub === 'status') return `En la rama ${GRN(info.branch)}\n` + (info.lastCommit ? DIM(`último commit: ${info.lastCommit.msg}`) : DIM('sin commits todavía')) + '\n' + DIM('(git de solo lectura aquí; commit/push reales no disponibles todavía)'); |
| 281 | // El SHA de verdad (antes ponía «commit <rama>», que no es un commit). |
| 282 | if (sub === 'log') return info.lastCommit ? `${YEL('commit ' + (info.lastCommit.sha || '?'))} ${DIM('(' + info.branch + ')')}\nAutor: ${info.lastCommit.author}\nFecha: ${new Date(info.lastCommit.when).toLocaleString()}\n\n ${info.lastCommit.msg}` : DIM('sin commits'); |
| 283 | return DIM(`git ${sub}: de solo lectura aquí (branch/status/log).`); |
| 284 | }, |
| 285 | }; |
| 286 | // tokenize() ya quitó las comillas originales (p.ej. -e "console.log(1)" llega |
| 287 | // como el arg SUELTO console.log(1)) — para reenviarlo al bridge (que lo pasa |
| 288 | // a `sh -c`) hay que re-entrecomillarlo, si no un espacio o un paréntesis |
| 289 | // rompe el comando al otro lado (bug real: -e "console.log('x')" fallaba). |
| 290 | const shellQuote = s => `'${String(s).replace(/'/g, "'\\''")}'`; |
| 291 | // runtimes REALES solo si hay un Bridge local conectado (⚙ Ajustes) — se |
| 292 | // ejecutan en tu máquina de verdad, en la carpeta configurada del bridge (no |
| 293 | // en el cwd virtual del proyecto). La señal (Ctrl+C en el terminal, parar el |
| 294 | // agente) mata el proceso en el bridge. |
| 295 | for (const r of ['node', 'npm', 'npx', 'python', 'python3', 'pip', 'yarn', 'pnpm', 'bun', 'deno', 'cargo', 'go']) |
| 296 | CMDS[r] = async (args, _stdin, { signal = null } = {}) => { |
| 297 | if (!bridgeClient.isConnected()) { |
| 298 | throw new Error(`${r}: runtime real no disponible.\n${DIM('Descarga y arranca el Bridge local (⚙ Ajustes → 🔌 Bridge local) para ejecución real en tu máquina — se conecta solo en cuanto lo detecte. Mientras tanto, la elfa edita ficheros y tú navegas con los comandos de arriba (help).')}`); |
| 299 | } |
| 300 | const full = r + (args.length ? ' ' + args.map(shellQuote).join(' ') : ''); |
| 301 | let out = ''; |
| 302 | const code = await bridgeClient.exec(full, { onOut: t => { out += t; }, onErr: t => { out += RED(t); }, signal }); |
| 303 | if (code) out += `\n${DIM('(código de salida ' + code + ')')}`; |
| 304 | return out || DIM('(sin salida)'); |
| 305 | }; |
| 306 | |
| 307 | // copia recursiva por handles (la File System API no tiene move nativo) |
| 308 | async function copyPath(srcSegs, dstSegs) { |
| 309 | const k = await kindOf(srcSegs); |
| 310 | if (k == null) throw new Error('origen no existe'); |
| 311 | if (k === 'file') { await writeText(dstSegs, await readText(srcSegs)); return; } |
| 312 | const src = await dirHandle(srcSegs); |
| 313 | await dirHandle(dstSegs, { create: true }); |
| 314 | for await (const e of src.values()) await copyPath([...srcSegs, e.name], [...dstSegs, e.name]); |
| 315 | } |
| 316 | |
| 317 | // ---- parser: tuberías, redirección, comillas ---- |
| 318 | function splitTop(line, sep) { // parte por `sep` respetando comillas |
| 319 | const parts = []; let cur = '', q = ''; |
| 320 | for (const ch of line) { |
| 321 | if (q) { cur += ch; if (ch === q) q = ''; } |
| 322 | else if (ch === '"' || ch === "'") { q = ch; cur += ch; } |
| 323 | else if (ch === sep) { parts.push(cur); cur = ''; } |
| 324 | else cur += ch; |
| 325 | } |
| 326 | parts.push(cur); return parts; |
| 327 | } |
| 328 | function tokenize(seg) { |
| 329 | const toks = []; let cur = '', q = ''; |
| 330 | for (const ch of seg.trim()) { |
| 331 | if (q) { if (ch === q) q = ''; else cur += ch; } |
| 332 | else if (ch === '"' || ch === "'") q = ch; |
| 333 | else if (/\s/.test(ch)) { if (cur) { toks.push(cur); cur = ''; } } |
| 334 | else cur += ch; |
| 335 | } |
| 336 | if (cur) toks.push(cur); |
| 337 | return toks; |
| 338 | } |
| 339 | |
| 340 | // Ejecuta una línea completa (encadenado &&/;, tuberías, redirección). |
| 341 | // `\f` en el retorno = orden de limpiar pantalla (para la UI). |
| 342 | // `signal`: parar (Ctrl+C, o el agente parado) corta el comando en curso y no |
| 343 | // lanza lo que quedaba de la cadena ni de la tubería. |
| 344 | export async function exec(line, { record = true, signal = null } = {}) { |
| 345 | line = line.trim(); |
| 346 | if (!line) return ''; |
| 347 | if (record) history.push(line); |
| 348 | const segments = tokenizeChain(line); |
| 349 | if (segments.length === 1) return runPipeline(segments[0].cmd, signal); |
| 350 | // encadenado: A && B (B solo si A fue bien) · A ; B (B siempre) |
| 351 | const outs = []; let ok = true; |
| 352 | for (const { cmd, op } of segments) { |
| 353 | if (signal?.aborted) break; |
| 354 | if (op === '&&' && !ok) continue; |
| 355 | try { outs.push(await runPipeline(cmd, signal)); ok = true; } |
| 356 | catch (e) { ok = false; outs.push('\x1b[31m' + (e && e.message || e) + '\x1b[0m'); } |
| 357 | } |
| 358 | if (outs.every(o => o === '\f')) return '\f'; |
| 359 | return outs.filter(o => o && o !== '\f').join('\n'); |
| 360 | } |
| 361 | |
| 362 | // Divide la línea en segmentos con su operador previo (&& / ; ), respetando comillas. |
| 363 | function tokenizeChain(line) { |
| 364 | const segs = []; let cur = '', q = '', op = null; |
| 365 | for (let i = 0; i < line.length; i++) { |
| 366 | const ch = line[i]; |
| 367 | if (q) { cur += ch; if (ch === q) q = ''; continue; } |
| 368 | if (ch === '"' || ch === "'") { q = ch; cur += ch; continue; } |
| 369 | if (ch === '&' && line[i + 1] === '&') { segs.push({ cmd: cur.trim(), op }); op = '&&'; cur = ''; i++; continue; } |
| 370 | if (ch === ';') { segs.push({ cmd: cur.trim(), op }); op = ';'; cur = ''; continue; } |
| 371 | cur += ch; |
| 372 | } |
| 373 | if (cur.trim()) segs.push({ cmd: cur.trim(), op }); |
| 374 | return segs.filter(s => s.cmd); |
| 375 | } |
| 376 | |
| 377 | // Ejecuta un pipeline (una etapa o varias unidas por |, con redirección final). |
| 378 | async function runPipeline(line, signal = null) { |
| 379 | const stages = splitTop(line, '|').map(s => s.trim()).filter(Boolean); |
| 380 | let data = ''; |
| 381 | for (let i = 0; i < stages.length; i++) { |
| 382 | if (signal?.aborted) break; |
| 383 | let seg = stages[i], redir = null; |
| 384 | if (i === stages.length - 1) { |
| 385 | const m = seg.match(/(>>?)\s*(\S+)\s*$/); |
| 386 | if (m) { redir = { append: m[1] === '>>', file: m[2] }; seg = seg.slice(0, m.index); } |
| 387 | } |
| 388 | const toks = tokenize(seg); |
| 389 | const name = toks.shift(); |
| 390 | if (!name) continue; |
| 391 | const fn = CMDS[name]; |
| 392 | if (!fn) throw new Error(`${name}: comando no encontrado (prueba ${GRN('help')})`); |
| 393 | data = (await fn(toks, data, { signal })) ?? ''; |
| 394 | if (redir) { |
| 395 | const segs = resolve(redir.file); |
| 396 | const prev = redir.append ? await readText(segs).catch(() => '') : ''; |
| 397 | await writeText(segs, prev + stripAnsi(data)); |
| 398 | data = ''; |
| 399 | } |
| 400 | } |
| 401 | return data; |
| 402 | } |
| 403 | |
| 404 | export const stripAnsi = s => String(s).replace(/\x1b\[[0-9;]*m/g, ''); |
| 405 | |
| 406 | // Entradas de un directorio (para el completado con Tab del terminal). |
| 407 | export async function listDir(dirPart = '') { |
| 408 | const dir = await dirHandle(resolve(dirPart)); |
| 409 | const out = []; |
| 410 | for await (const e of dir.values()) if (!IGNORE.has(e.name)) out.push({ name: e.name, kind: e.kind }); |
| 411 | return out; |
| 412 | } |
| 413 | |
| 414 | // Ejecuta una orden desde la elfa (tool terminal.run): devuelve texto plano. |
| 415 | // `signal` es la del turno del agente: pararlo para también el comando. |
| 416 | export async function runForAgent(command, { signal = null } = {}) { |
| 417 | const out = await exec(command, { record: true, signal }); |
| 418 | return out === '\f' ? '(pantalla limpiada)' : (stripAnsi(out) || '(sin salida)'); |
| 419 | } |