Elffuss BraidHub

utopia-ia/elffuss-claw public

e2d4c9abe7d2 · 3.5 KiBRawPermalink
1// Navegación: fetch directo si el sitio lo permite (CORS); si no, cae al
2// proxy del servidor (/proxy?url=…) que sirve server/serve.py o el nginx
3// de producción.
4import { require as requirePerm } from '../permissions.js';
5import { t } from '../i18n.js';
6
7const MAX = 8000; // caracteres devueltos al agente
8
9function toText(html) {
10 const doc = new DOMParser().parseFromString(html, 'text/html');
11 doc.querySelectorAll('script,style,noscript,svg,iframe').forEach(n => n.remove());
12 const text = (doc.body?.innerText || doc.body?.textContent || '')
13 .replace(/\n{3,}/g, '\n\n').trim();
14 return text || html.slice(0, MAX);
15}
16
17// GET a través del proxy CORS del servidor (o directo si el sitio lo permite).
18async function proxyGet(url) {
19 let lastErr;
20 for (const target of [url, '/proxy?url=' + encodeURIComponent(url)]) {
21 try {
22 const res = await fetch(target);
23 if (!res.ok) throw new Error(`HTTP ${res.status}`);
24 return await res.text();
25 } catch (e) { lastErr = e; }
26 }
27 throw lastErr || new Error('sin respuesta');
28}
29
30export async function fetchUrl({ url } = {}) {
31 if (!/^https?:\/\//.test(url || '')) throw new Error('URL inválida (usa https://…)');
32 await requirePerm('web', url);
33 const text = toText(await proxyGet(url));
34 return `[${url}]\n` + (text.length > MAX ? text.slice(0, MAX) + '\n… (recortado)' : text);
35}
36
37// Búsqueda web REAL. Parseo TOLERANTE (independiente de clases): DuckDuckGo
38// envuelve cada resultado en un enlace con ?uddg=<url real>. Buscamos esos.
39export async function search({ query } = {}) {
40 if (!query) throw new Error('Falta query');
41 await requirePerm('web', t('pdWebSearch', { q: query }));
42 let html = '';
43 for (const ep of ['https://html.duckduckgo.com/html/?q=', 'https://lite.duckduckgo.com/lite/?q=']) {
44 try { html = await proxyGet(ep + encodeURIComponent(query)); if (html.includes('uddg=') || html.includes('result')) break; }
45 catch { /* siguiente endpoint */ }
46 }
47 const doc = new DOMParser().parseFromString(html, 'text/html');
48 const seen = new Set(), out = [];
49 for (const a of doc.querySelectorAll('a[href*="uddg="]')) {
50 const m = a.getAttribute('href').match(/uddg=([^&]+)/);
51 if (!m) continue;
52 const href = decodeURIComponent(m[1]);
53 const title = a.textContent.trim();
54 if (!title || title.length < 3 || seen.has(href)) continue;
55 seen.add(href);
56 // fragmento: el texto del contenedor del resultado, sin el título
57 const block = a.closest('tr, div, article') || a.parentElement;
58 const snip = (block?.textContent || '').replace(title, '').replace(/\s+/g, ' ').trim().slice(0, 160);
59 out.push(`• ${title}\n ${href}${snip ? '\n ' + snip : ''}`);
60 if (out.length >= 8) break;
61 }
62 return out.length ? `Resultados para «${query}»:\n\n` + out.join('\n\n') : `Sin resultados para «${query}».`;
63}
64
65// Búsqueda de IMÁGENES (Openverse, CC) → URLs para montar una galería.
66export async function images({ query } = {}) {
67 if (!query) throw new Error('Falta query');
68 await requirePerm('web', t('pdWebImages', { q: query }));
69 const raw = await proxyGet('https://api.openverse.org/v1/images/?q=' + encodeURIComponent(query) + '&page_size=12');
70 let data;
71 try { data = JSON.parse(raw); } catch { throw new Error('respuesta inesperada del buscador de imágenes'); }
72 const imgs = (data.results || []).map(r => ({ url: r.url, thumb: r.thumbnail || r.url, title: (r.title || '').slice(0, 60), by: r.creator || '' }))
73 .filter(i => i.url);
74 if (!imgs.length) return `Sin imágenes para «${query}».`;
75 return JSON.stringify({ query, images: imgs });
76}