utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | 97ba245c0fe713466b872bb668d5b71683060518bf153ea5143d05d67bf67c3b |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00 |
| Parents | 2e2bee292608 |
3 files changed
modified tests/alltools.mjs +11 −4
| @@ -53,12 +53,19 @@ | ||
| 53 | 53 | ok('terminal.run · echo> + cat (escribe en disco)', r.ok && r.out.includes('hola-tool'), r.out); |
| 54 | 54 | r = await run('terminal.run', { command: 'cat src/app.js | grep lru' }); |
| 55 | 55 | ok('terminal.run · tubería cat|grep', r.ok && /lru/.test(r.out), r.out); |
| 56 | -// 6) web.search — internet real | |
| 56 | +// 6) web.search — internet real. Si el servidor no tiene /proxy (producción | |
| 57 | +// hoy: su nginx no tiene la ruta) los sitios sin CORS no se pueden leer, y | |
| 58 | +// eso lo tiene que DECIR la herramienta: antes contestaba «Sin resultados» | |
| 59 | +// como si no hubiera nada. La primera comprobación es esa honestidad; la | |
| 60 | +// segunda, que de verdad busca (falla mientras falte el proxy, y lo dice). | |
| 61 | +const SIN_PROXY = 'ESTE SERVIDOR NO TIENE /proxy (falta la ruta en el servidor web) — '; | |
| 57 | 62 | r = await run('web.search', { query: 'mdn array map' }); |
| 58 | -ok('web.search · búsqueda en internet real', r.ok && /https?:\/\//.test(r.out) && /Resultados/.test(r.out), r.out); | |
| 63 | +ok('web.search · si no puede buscar, dice por qué (nunca un «Sin resultados» callado)', r.ok ? /Resultados para|Sin resultados/.test(r.out) : /No pude|bloqueó/.test(r.out), r.out); | |
| 64 | +ok('web.search · búsqueda en internet real', r.ok && /https?:\/\//.test(r.out) && /Resultados/.test(r.out), (/no tiene el proxy/.test(r.out) ? SIN_PROXY : '') + r.out); | |
| 59 | 65 | // 7) web.fetch — leer una URL |
| 60 | 66 | r = await run('web.fetch', { url: 'https://example.com' }); |
| 61 | -ok('web.fetch · lee el texto de una URL', r.ok && /example|domain/i.test(r.out), r.out); | |
| 67 | +ok('web.fetch · si no puede leer, dice por qué (no un «HTTP 404» suelto)', r.ok || /No pude leer/.test(r.out), r.out); | |
| 68 | +ok('web.fetch · lee el texto de una URL', r.ok && /example|domain/i.test(r.out), (/no tiene el proxy/.test(r.out) ? SIN_PROXY : '') + r.out); | |
| 62 | 69 | |
| 63 | 70 | // 8) flujo del agente: un mensaje con varias tool-calls se ejecuta entero |
| 64 | 71 | const ev = await p.evaluate(async () => { |
| @@ -70,6 +77,6 @@ | ||
| 70 | 77 | }); |
| 71 | 78 | ok('agente · ejecuta las 2 tool-calls del mismo mensaje', ev === 2, `${ev} ejecutadas`); |
| 72 | 79 | |
| 73 | -console.log(fails ? `\n❌ ${fails} FALLO(S) de ${8}` : '\n✅ TODAS LAS TOOLS OK — code.* + terminal + web + flujo del agente'); | |
| 80 | +console.log(fails ? `\n❌ ${fails} FALLO(S) de ${10}` : '\n✅ TODAS LAS TOOLS OK — code.* + terminal + web + flujo del agente'); | |
| 74 | 81 | await b.close(); |
| 75 | 82 | process.exit(fails ? 1 : 0); |
added tests/web-honest.mjs +91 −0
| @@ -0,0 +1,91 @@ | ||
| 1 | +// web.fetch y web.search dicen POR QUÉ no pueden, en vez de callarlo. | |
| 2 | +// | |
| 3 | +// En producción el servidor no tiene ruta /proxy (nginx contesta 404): los | |
| 4 | +// sitios sin CORS no se pueden leer y DuckDuckGo tampoco. Antes web.fetch daba | |
| 5 | +// «HTTP 404» a secas (se lee como «esa página no existe») y web.search tragaba | |
| 6 | +// los dos fallos y contestaba «Sin resultados», como si no hubiera nada. Ahora: | |
| 7 | +// 1. sin proxy (404): las dos lo dicen, con la causa; | |
| 8 | +// 2. el proxy falla (502): se dice que falló el proxy; | |
| 9 | +// 3. DuckDuckGo pide su verificación anti-bot: es un bloqueo, no una lista vacía; | |
| 10 | +// 4. con resultados, los da (y «Sin resultados» solo cuando el buscador | |
| 11 | +// contestó y no encontró nada); | |
| 12 | +// 5. un sitio con CORS se lee directo, sin pasar por el proxy. | |
| 13 | +// Todo con page.route: ninguna petición sale a internet. | |
| 14 | +// | |
| 15 | +// BASE=http://localhost:8799 node tests/web-honest.mjs | |
| 16 | +import { chromium } from 'playwright'; | |
| 17 | +const BASE = process.env.BASE || 'http://localhost:8799'; | |
| 18 | +let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + String(e).replace(/\n/g, ' ').slice(0, 150) : '')); if (!c) fails++; }; | |
| 19 | + | |
| 20 | +const RESULTADOS = `<html><body><table> | |
| 21 | +<tr><td><a href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fdeveloper.mozilla.org%2Fes%2Fdocs%2FArray%2Fmap&rut=x">Array.prototype.map() - JavaScript | MDN</a></td></tr> | |
| 22 | +<tr><td>El método map() crea un nuevo array con los resultados.</td></tr> | |
| 23 | +</table></body></html>`; | |
| 24 | +const VACIO = '<html><body><table><tr><td>No results.</td></tr></table></body></html>'; | |
| 25 | +const ANTIBOT = '<html><body><div class="anomaly-modal__title">Unfortunately, bots use DuckDuckGo too.</div></body></html>'; | |
| 26 | + | |
| 27 | +const b = await chromium.launch(); | |
| 28 | +async function escenario(proxy, { directoCORS = false } = {}) { | |
| 29 | + const ctx = await b.newContext(); | |
| 30 | + const p = await ctx.newPage(); | |
| 31 | + const alProxy = []; | |
| 32 | + // Los sitios de fuera: sin CORS (el fetch directo falla), salvo que se diga. | |
| 33 | + await p.route(/^https:\/\/(example\.com|html\.duckduckgo\.com|lite\.duckduckgo\.com)\//, r => directoCORS | |
| 34 | + ? r.fulfill({ status: 200, contentType: 'text/html', headers: { 'access-control-allow-origin': '*' }, body: '<html><body><p>Example Domain directo</p></body></html>' }) | |
| 35 | + : r.abort('failed')); | |
| 36 | + await p.route('**/proxy?url=*', r => { alProxy.push(decodeURIComponent(r.request().url().split('url=')[1] || '')); return proxy(r); }); | |
| 37 | + await p.goto(BASE + '/manifest.json'); | |
| 38 | + const llama = (que, args) => p.evaluate(async ({ que, args }) => { | |
| 39 | + const web = await import('/js/tools/web.js'); | |
| 40 | + try { return { ok: true, out: await (que === 'search' ? web.search(args) : web.fetchUrl(args)) }; } | |
| 41 | + catch (e) { return { ok: false, out: String(e.message || e) }; } | |
| 42 | + }, { que, args }); | |
| 43 | + return { ctx, alProxy, llama }; | |
| 44 | +} | |
| 45 | + | |
| 46 | +// 1 · sin proxy en el servidor (lo de producción hoy) | |
| 47 | +{ | |
| 48 | + const { ctx, llama } = await escenario(r => r.fulfill({ status: 404, contentType: 'text/html', body: '<h1>404 Not Found</h1>' })); | |
| 49 | + const f = await llama('fetch', { url: 'https://example.com' }); | |
| 50 | + ok('1 · web.fetch sin proxy: falla diciendo que el servidor no tiene el proxy', !f.ok && /no tiene el proxy de respaldo/.test(f.out) && /404/.test(f.out), f.out); | |
| 51 | + ok(' …y que no es que la página no exista', /No es que la página no exista/.test(f.out), f.out); | |
| 52 | + const s = await llama('search', { query: 'mdn array map' }); | |
| 53 | + ok('1 · web.search sin proxy: falla con la causa, NO «Sin resultados»', !s.ok && /no tiene el proxy de respaldo/.test(s.out) && !/Sin resultados/.test(s.out), s.out); | |
| 54 | + await ctx.close(); | |
| 55 | +} | |
| 56 | +// 2 · el proxy existe pero falla | |
| 57 | +{ | |
| 58 | + const { ctx, llama } = await escenario(r => r.fulfill({ status: 502, contentType: 'text/plain', body: 'proxy: timed out' })); | |
| 59 | + const f = await llama('fetch', { url: 'https://example.com' }); | |
| 60 | + ok('2 · el proxy falla: se dice que falló el proxy (HTTP 502)', !f.ok && /proxy del servidor \(HTTP 502\)/.test(f.out), f.out); | |
| 61 | + await ctx.close(); | |
| 62 | +} | |
| 63 | +// 3 · DuckDuckGo pide la verificación anti-bot | |
| 64 | +{ | |
| 65 | + const { ctx, llama } = await escenario(r => r.fulfill({ status: 202, contentType: 'text/html', body: ANTIBOT })); | |
| 66 | + const s = await llama('search', { query: 'mdn array map' }); | |
| 67 | + ok('3 · la verificación anti-bot es un bloqueo, no «Sin resultados»', !s.ok && /bloqueó la consulta/.test(s.out) && !/Sin resultados/.test(s.out), s.out); | |
| 68 | + await ctx.close(); | |
| 69 | +} | |
| 70 | +// 4 · con resultados, y vacío de verdad | |
| 71 | +{ | |
| 72 | + const { ctx, llama } = await escenario(r => r.fulfill({ status: 200, contentType: 'text/html', body: RESULTADOS })); | |
| 73 | + const s = await llama('search', { query: 'mdn array map' }); | |
| 74 | + ok('4 · con resultados: los da, con su URL', s.ok && /Resultados para «mdn array map»/.test(s.out) && /developer\.mozilla\.org/.test(s.out), s.out); | |
| 75 | + await ctx.close(); | |
| 76 | + const v = await escenario(r => r.fulfill({ status: 200, contentType: 'text/html', body: VACIO })); | |
| 77 | + const sv = await v.llama('search', { query: 'xyzzy-nada' }); | |
| 78 | + ok('4 · y «Sin resultados» cuando el buscador contestó y no encontró nada', sv.ok && /Sin resultados para «xyzzy-nada»/.test(sv.out), sv.out); | |
| 79 | + await v.ctx.close(); | |
| 80 | +} | |
| 81 | +// 5 · un sitio con CORS se lee directo | |
| 82 | +{ | |
| 83 | + const { ctx, alProxy, llama } = await escenario(r => r.fulfill({ status: 404, body: '' }), { directoCORS: true }); | |
| 84 | + const f = await llama('fetch', { url: 'https://example.com' }); | |
| 85 | + ok('5 · con CORS se lee directo y el proxy ni se toca', f.ok && /Example Domain directo/.test(f.out) && alProxy.length === 0, `${f.out} · proxy ${alProxy.length}`); | |
| 86 | + await ctx.close(); | |
| 87 | +} | |
| 88 | + | |
| 89 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ WEB: si no puede leer o buscar, dice por qué'); | |
| 90 | +await b.close(); | |
| 91 | +process.exit(fails ? 1 : 0); |
modified web/js/tools/web.js +33 −8
| @@ -10,13 +10,26 @@ | ||
| 10 | 10 | return ((doc.body?.innerText || doc.body?.textContent || '').replace(/\n{3,}/g, '\n\n').trim()) || html.slice(0, MAX); |
| 11 | 11 | } |
| 12 | 12 | |
| 13 | +// Lee una URL: directa si el sitio permite CORS y, si no, por el proxy del | |
| 14 | +// servidor. Cuando las dos fallan, el error dice POR QUÉ. En especial si el | |
| 15 | +// proxy no existe en este servidor (404): antes salía «HTTP 404» a secas, que | |
| 16 | +// se lee como «esa página no existe», y la búsqueda lo convertía en «Sin | |
| 17 | +// resultados», como si internet no tuviera nada que decir. | |
| 18 | +const hostDe = url => { try { return new URL(url).host; } catch { return url; } }; | |
| 13 | 19 | async function proxyGet(url) { |
| 14 | - let lastErr; | |
| 15 | - for (const target of [url, '/proxy?url=' + encodeURIComponent(url)]) { | |
| 16 | - try { const r = await fetch(target); if (!r.ok) throw new Error('HTTP ' + r.status); return await r.text(); } | |
| 17 | - catch (e) { lastErr = e; } | |
| 20 | + let directo; | |
| 21 | + try { const r = await fetch(url); if (r.ok) return await r.text(); directo = new Error('HTTP ' + r.status); } | |
| 22 | + catch (e) { directo = e; } | |
| 23 | + let r; | |
| 24 | + try { r = await fetch('/proxy?url=' + encodeURIComponent(url)); } | |
| 25 | + catch (e) { throw new Error(`No pude leer ${hostDe(url)}: ni directamente (${directo?.message || 'sin respuesta'}) ni por el proxy del servidor (${e?.message || 'sin respuesta'}).`); } | |
| 26 | + if (r.ok) return await r.text(); | |
| 27 | + if (r.status === 404 || r.status === 405 || r.status === 501) { | |
| 28 | + const e = new Error(`No pude leer ${hostDe(url)}: el sitio no deja leerlo directamente desde el navegador (CORS) y este servidor no tiene el proxy de respaldo (/proxy respondió ${r.status}). No es que la página no exista: desde aquí no se puede leer.`); | |
| 29 | + e.sinProxy = true; | |
| 30 | + throw e; | |
| 18 | 31 | } |
| 19 | - throw lastErr || new Error('sin respuesta'); | |
| 32 | + throw new Error(`No pude leer ${hostDe(url)}: ni directamente (${directo?.message || 'sin respuesta'}) ni por el proxy del servidor (HTTP ${r.status}).`); | |
| 20 | 33 | } |
| 21 | 34 | |
| 22 | 35 | export async function fetchUrl({ url } = {}) { |
| @@ -27,12 +40,24 @@ | ||
| 27 | 40 | |
| 28 | 41 | // Búsqueda REAL en DuckDuckGo. Parseo tolerante: cada resultado es un enlace |
| 29 | 42 | // con ?uddg=<url real>. Independiente de clases (robusto a cambios de HTML). |
| 43 | +// Si ningún buscador contesta se dice por qué, en vez de «Sin resultados» (que | |
| 44 | +// solo vale cuando el buscador SÍ contestó y no encontró nada). Y la página de | |
| 45 | +// verificación anti-bot de DuckDuckGo no es una lista vacía: es un bloqueo. | |
| 46 | +const BLOQUEO_DDG = /anomaly|unusual traffic|are you a human|bots use duckduckgo/i; | |
| 30 | 47 | export async function search({ query } = {}) { |
| 31 | 48 | if (!query) throw new Error('Falta query'); |
| 32 | - let html = ''; | |
| 49 | + let html = '', ultimoError = null, bloqueado = false; | |
| 33 | 50 | for (const ep of ['https://html.duckduckgo.com/html/?q=', 'https://lite.duckduckgo.com/lite/?q=']) { |
| 34 | - try { html = await proxyGet(ep + encodeURIComponent(query)); if (html.includes('uddg=') || html.includes('result')) break; } | |
| 35 | - catch { /* siguiente endpoint */ } | |
| 51 | + try { | |
| 52 | + const h = await proxyGet(ep + encodeURIComponent(query)); | |
| 53 | + if (!h.includes('uddg=') && BLOQUEO_DDG.test(h)) { bloqueado = true; continue; } | |
| 54 | + html = h; | |
| 55 | + if (html.includes('uddg=') || html.includes('result')) break; | |
| 56 | + } catch (e) { ultimoError = e; } | |
| 57 | + } | |
| 58 | + if (!html) { | |
| 59 | + if (bloqueado) throw new Error(`El buscador bloqueó la consulta «${query}» (DuckDuckGo pidió una verificación anti-bot a este servidor): no hay resultados que leer. Prueba más tarde, o lee una URL concreta con web.fetch.`); | |
| 60 | + throw ultimoError || new Error(`No pude consultar el buscador para «${query}».`); | |
| 36 | 61 | } |
| 37 | 62 | const doc = new DOMParser().parseFromString(html, 'text/html'); |
| 38 | 63 | const seen = new Set(), out = []; |