DR-Tulu2-WebGPU / tools.js
Nekochu's picture
Page reading: stub detection, defuddle.md and Wayback tiers
54009a5 verified
Raw History Blame Contribute Delete
36.3 kB
// Free, key-less, in-browser stand-ins for DR Tulu 2's two live tools (allenai/dr-tulu2 uses Serper + Jina with paid keys).
// search(query, n) -> the harness's text format ("**title**\nsnippet\nSource: url")
// webterminal(command) -> `browse <url> [| head | tail | rg | grep | sed | wc | sort | uniq | cut]`, run by a small
// pure-JS pipeline (no shell, no eval; the model's regexes run in a try/catch)
// Everything happens in the page: pages are read through Jina Reader's anonymous endpoint (CORS-enabled, renders
// JavaScript and passes most bot walls), search results are Brave Search read the same way, with Wikipedia / OpenAlex
// (both CORS-enabled APIs) as fallbacks. No backend, no keys.
import { pyJson } from './agent.js';
export const MAX_OUTPUT = 10_000; // the model is told terminal output is capped at 10,000 characters
const READER = 'https://r.jina.ai/';
const BLOCK = /(captcha|verify you are (a )?human|are you a robot|unusual traffic|access denied|just a moment\.\.\.|enable javascript and cookies|cf-chl|attention required|request blocked|bot detection)/i;
// ------------------------------------------------------------------------------------------ network (rate-limited)
let chain = Promise.resolve(), lastCall = 0, outer = null;
export const setSignal = (sig) => { outer = sig; }; // the page's Stop button aborts whatever tool call is running
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const stopped = () => { if (outer?.aborted) throw new DOMException('Stopped', 'AbortError'); };
const MIN_GAP = 3100; // Jina's anonymous tier allows ~20 requests/minute per IP
function paced(fn) {
const run = chain.then(async () => { const wait = lastCall + MIN_GAP - Date.now(); if (wait > 0) await sleep(wait); stopped(); lastCall = Date.now(); return fn(); });
chain = run.catch(() => {});
return run;
}
async function getText(url, { reader = false, timeout = 30000, headers = {} } = {}) {
for (let attempt = 0; attempt < 3; attempt++) {
stopped();
const ctl = new AbortController(), t = setTimeout(() => ctl.abort(), timeout), onStop = () => ctl.abort();
outer?.addEventListener('abort', onStop, { once: true });
try {
const run = reader ? paced : (f) => f();
const r = await run(() => fetch(reader ? READER + url : url, { signal: ctl.signal, headers }));
if (r.status === 429 && attempt < 2) { await sleep(4000 * (attempt + 1)); continue; }
return { status: r.status, text: await r.text() };
} finally { clearTimeout(t); outer?.removeEventListener('abort', onStop); }
}
return { status: 429, text: '' };
}
// ------------------------------------------------------------------------------------------ pages
export function checkUrl(u) {
let p; try { p = new URL(u.trim()); } catch { throw new CmdError('not a valid URL'); }
if (!/^https?:$/.test(p.protocol)) throw new CmdError('only http(s) URLs can be opened');
const h = p.hostname.toLowerCase();
if (h === 'localhost' || h.endsWith('.') || /\.(local|internal|localhost)$/.test(h) || /^[\d.]+$/.test(h) || h.includes(':')) throw new CmdError('that host is not public');
if (/(^|\.)(huggingface\.co|hf\.co)$/.test(h)) throw new CmdError('that domain is not available to this tool');
return p.href;
}
const pageCache = new Map();
// Jina answers 200 even for blocked pages, with a header and a "Warning: Target URL returned error 401": that is a failure, not content.
const usable = (t) => { const body = (t.split('Markdown Content:')[1] ?? t).trim(); return body.length >= 400 && !(BLOCK.test(body.slice(0, 1500)) && body.length < 3000); };
export async function fetchPage(url) {
url = checkUrl(url);
if (pageCache.has(url)) return pageCache.get(url);
const tried = []; let text = '';
const attempt = async (name, fn) => { // run one tier; keep its text only if it is real content
if (text) return;
try { const r = await fn(); tried.push(`${name} HTTP ${r.status}`); if (r.status < 400 && usable(r.text)) text = r.text; }
catch (e) { if (e?.name === 'AbortError' && outer?.aborted) throw e; tried.push(`${name} ${e?.name === 'AbortError' ? 'timeout' : 'unreachable'}`); }
};
await attempt('reader', () => getText(url, { reader: true, timeout: 45000 })); // 1. Jina Reader: renders JavaScript, strips boilerplate
await attempt('defuddle', () => getText('https://defuddle.md/' + url, { timeout: 30000 })); // 2. defuddle.md: another free, CORS-enabled reader; fetches from other IPs than Jina (reads some sites Jina refuses)
await attempt('direct', async () => { const r = await getText(url, { timeout: 15000 }); return { ...r, text: r.status < 400 ? htmlToText(r.text) : '' }; }); // 3. the page itself, when its server allows cross-origin reads
if (!text) try { // 4. newest Wayback Machine snapshot (CORS-enabled API), raw copy first, then through defuddle
const av = await getText(`https://archive.org/wayback/available?url=${encodeURIComponent(url)}`, { timeout: 15000 });
const snap = JSON.parse(av.text)?.archived_snapshots?.closest?.url?.replace(/^http:/, 'https:');
if (snap) {
const raw = snap.replace(/\/web\/(\d+)\//, '/web/$1id_/');
await attempt('archive', async () => { const r = await getText(raw, { timeout: 30000 }); return { ...r, text: r.status < 400 ? htmlToText(r.text) : '' }; });
await attempt('archive via defuddle', () => getText('https://defuddle.md/' + raw, { timeout: 45000 }));
} else tried.push('archive none');
} catch (e) { if (e?.name === 'AbortError' && outer?.aborted) throw e; tried.push('archive unreachable'); }
text = text.trim() || `BLOCKED/EMPTY: could not get readable content from ${url} (${tried.join(', ')}). The site blocks automated readers or needs a login; use a different source.`;
pageCache.set(url, text); if (pageCache.size > 100) pageCache.delete(pageCache.keys().next().value);
return text;
}
function htmlToText(html) {
if (!/^\s*(<!doctype|<html)/i.test(html)) return html;
const d = new DOMParser().parseFromString(html, 'text/html');
d.querySelectorAll('script,style,noscript,nav,footer,header,aside,form,svg,iframe').forEach((e) => e.remove());
return (d.body?.innerText || d.body?.textContent || '').replace(/\n{3,}/g, '\n\n');
}
// ------------------------------------------------------------------------------------------ search
const searchCache = new Map();
const clean = (s) => s.replace(/<[^>]+>/g, '').replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/&#039;|&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>');
// Brave's results page, as Jina renders it to markdown: each organic result is a link to search.brave.com/go/v1#... whose text is
// "<site> <https://host › path ›…> <title>", followed by a paragraph with the snippet.
export function parseBrave(md) {
const body = md.split('Markdown Content:')[1] || md;
const flat = body.replace(/!\[[^\]]*\]\([^)]*\)/g, '');
const rows = [], re = /\[([^\]]*)\]\(https:\/\/search\.brave\.com\/go\/v1#[^)]*\)\s*\n+([^\n[][^\n]*)?/g;
let m;
while ((m = re.exec(flat))) {
const label = m[1].replace(/\s+/g, ' ').trim(), snip = (m[2] || '').trim();
const hm = label.match(/https?:\/\/\S+/);
if (!hm) continue;
// After the host, Brave shows a breadcrumb "› seg › seg › lastseg Title": segments with spaces are page titles, not path pieces.
const parts = label.slice(hm.index + hm[0].length).split(' › ').map((x) => x.trim()); // parts[0] is '' (or the title when there is no breadcrumb)
let path = [], title = '', ok = true;
for (let k = 1; k < parts.length; k++) {
const last = k === parts.length - 1, seg = parts[k];
if (!last) { if (ok && seg && !/\s/.test(seg) && !seg.includes('…')) path.push(seg); else ok = false; }
else { const [first, ...rest] = seg.split(' '); if (ok && first && !first.includes('…') && rest.length) { path.push(first); title = rest.join(' '); } else title = seg; }
}
if (parts.length === 1) title = parts[0];
const href = (hm[0].replace(/…+$/, '') + path.map((x) => '/' + x).join('')).replace(/\/$/, '');
title = title.trim() || href;
rows.push({ title, body: snip.replace(/\*\*/g, ''), href });
}
return rows;
}
async function braveSearch(q) {
const r = await getText(`https://search.brave.com/search?q=${encodeURIComponent(q)}&source=web`, { reader: true, timeout: 45000 });
if (r.status >= 400) throw new Error(`brave ${r.status}`);
return parseBrave(r.text);
}
async function wikipedia(q, n) {
const r = await getText(`https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(q)}&srlimit=${n}&format=json&origin=*`);
return JSON.parse(r.text).query.search.map((h) => ({ title: h.title, body: clean(h.snippet), href: 'https://en.wikipedia.org/wiki/' + encodeURIComponent(h.title.replace(/ /g, '_')).replace(/%2F/g, '/').replace(/%28/g, '(').replace(/%29/g, ')') }));
}
async function openalex(q, n) {
const r = await getText(`https://api.openalex.org/works?search=${encodeURIComponent(q)}&per-page=${n}&select=title,doi,publication_year,primary_location,abstract_inverted_index`);
return JSON.parse(r.text).results.map((w) => {
const inv = w.abstract_inverted_index, words = []; if (inv) for (const [k, ps] of Object.entries(inv)) for (const p of ps) words[p] = k;
return { title: `${w.title} (${w.publication_year})`, body: words.filter(Boolean).join(' ').slice(0, 400), href: w.doi || w.primary_location?.landing_page_url || '' };
});
}
const blocked = (u) => { try { return /(^|\.)(huggingface\.co|hf\.co)$/.test(new URL(u).hostname); } catch { return true; } };
const tidy = (t) => t.replace(/\*\*\*\*/g, ' ').replace(/\*\*/g, '').replace(/^(?:[A-Z][a-z]{2} \d{1,2}, \d{4}|\d+ (?:hours?|days?|weeks?|months?|years?) ago|\d{1,2} [A-Z][a-z]+ \d{4}) [-—·]\s*/, '').replace(/\s+/g, ' ').trim().slice(0, 180);
// DuckDuckGo's HTML results, as Jina renders them: "## [title](https://duckduckgo.com/l/?uddg=<real url>&rut=…)" then a snippet link.
export function parseDdg(md) {
const body = md.split('Markdown Content:')[1] || md, rows = [];
for (const block of body.split(/\n(?=## \[)/).slice(1)) {
const m = block.match(/^## \[([^\]]+)\]\(https:\/\/duckduckgo\.com\/l\/\?uddg=([^&)]+)/);
if (!m) continue;
let href; try { href = decodeURIComponent(m[2]); } catch { continue; }
const sn = block.split('\n').slice(1).map((l) => l.trim()).find((l) => /^\[(?!!\[)/.test(l) && l.includes('](https://duckduckgo.com/l/'));
const snippet = sn ? sn.slice(1, sn.lastIndexOf('](https://duckduckgo.com/l/')) : '';
rows.push({ title: m[1].replace(/\*\*/g, ''), body: snippet, href });
}
return rows;
}
async function ddgSearch(q) {
const r = await getText(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`, { reader: true, timeout: 45000 });
if (r.status >= 400) throw new Error(`ddg ${r.status}`);
return parseDdg(r.text);
}
export async function search(query) {
query = (query || '').trim(); const n = 10;
if (!query) return 'Error: query is empty.';
const key = query.toLowerCase(); let rows = searchCache.get(key), repeat = !!rows;
if (!rows) {
rows = [];
for (const f of [() => ddgSearch(query), () => braveSearch(query), () => wikipedia(query, n), () => openalex(query, n)]) {
try { rows = (await f()).filter((r) => r.href && !blocked(r.href)); } catch (e) { if (e?.name === 'AbortError') throw e; }
if (rows.length) break;
}
if (!rows.length) return `No results for "${query}" (the search engines did not answer). Try a different query.`;
searchCache.set(key, rows); if (searchCache.size > 200) searchCache.delete(searchCache.keys().next().value);
}
const out = rows.slice(0, n).map((r) => [`**${r.title.trim() || 'Untitled result'}**`, tidy(r.body || ''), `Source: ${r.href}`].filter(Boolean).join('\n')).join('\n\n');
return repeat ? `(You already ran this exact search; these are the same results. Open one of these pages or change the query.)\n\n${out}` : out;
}
// ------------------------------------------------------------------------------------------ terminal pipeline
export class CmdError extends Error {}
export class RegexError extends CmdError {}
const lines = (t) => (t.endsWith('\n') ? t.slice(0, -1).split('\n') : t ? t.split('\n') : []);
const nl = (ls) => ls.map((l) => l + '\n').join('');
const int = (v, what) => { if (!/^[+-]?\d+$/.test(v)) throw new CmdError(`invalid ${what}: '${v}'`); return parseInt(v, 10); };
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const CLASSES = { alpha: 'a-zA-Z', digit: '0-9', alnum: 'a-zA-Z0-9', upper: 'A-Z', lower: 'a-z', space: '\\s', blank: ' \\t', punct: '!-\\/:-@\\[-`{-~', xdigit: '0-9A-Fa-f', word: '\\w' };
const posix = (s) => s.replace(/\[:([a-z]+):\]/g, (m, c) => CLASSES[c] ?? m);
// Basic regular expressions (grep and sed without -E) to JavaScript syntax: \( \) \| \{ \} \+ \? are operators, bare ( ) | { } + ? are literals.
function breToJs(s) {
let out = '', i = 0;
while (i < s.length) {
const c = s[i];
if (c === '[') { // bracket expression: copied as is
let j = i + 1; if (s[j] === '^') j++; if (s[j] === ']') j++;
while (j < s.length && s[j] !== ']') { if (s[j] === '[' && s[j + 1] === ':') { const k = s.indexOf(':]', j + 2); if (k > 0) j = k + 1; } j++; }
out += s.slice(i, j + 1); i = j + 1;
} else if (c === '\\' && i + 1 < s.length) {
const d = s[i + 1];
out += '(){}|+?'.includes(d) ? d : '\\' + d; i += 2;
} else { out += '(){}|+?'.includes(c) ? '\\' + c : c; i++; }
}
return out;
}
function compile(sources, { ci = false, bre = false, fixed = false, word = false, lineX = false, flags = '' } = {}) {
let srcs = sources.map((p) => { let q = p; if (!fixed && /^\(\?i\)/.test(q)) { q = q.slice(4); ci = true; } return fixed ? esc(q) : bre ? breToJs(posix(q)) : posix(q); });
if (word) srcs = srcs.map((s) => `\\b(?:${s})\\b`);
if (lineX) srcs = srcs.map((s) => `^(?:${s})$`);
const src = srcs.map((s) => `(?:${s})`).join('|'), f = (ci ? 'i' : '') + flags;
try { return new RegExp(src, f + 'u'); } catch { /* not valid in unicode mode (e.g. a stray escape): retry leniently */ }
try { return new RegExp(src, f); } catch (e) { throw new RegexError(`invalid regex: ${e.message}`); }
}
function cmdHeadTail(name, args, text) {
let n = 10, plus = false, minus = false, bytes = false;
const setN = (raw) => { plus = raw.startsWith('+'); minus = raw.startsWith('-'); n = Math.abs(int(raw, 'count')); };
for (let i = 0; i < args.length; i++) {
const a = args[i]; let m;
if (/^-\d+$/.test(a)) n = int(a.slice(1), 'count');
else if (['-n', '--lines', '-c', '--bytes'].includes(a)) { if (++i >= args.length) throw new CmdError(`${name}: option requires an argument`); setN(args[i]); bytes = a === '-c' || a === '--bytes'; }
else if ((m = a.match(/^-([nc])([+-]?\d+)$/))) { setN(m[2]); bytes = m[1] === 'c'; }
else throw new CmdError(`${name} only supports line or byte counts with stdin`);
}
if (bytes) { const b = new TextEncoder().encode(text); const sel = name === 'head' ? (minus ? b.slice(0, Math.max(0, b.length - n)) : b.slice(0, n)) : plus ? b.slice(Math.max(0, n - 1)) : n ? b.slice(-n) : b.slice(0, 0); return new TextDecoder('utf-8', { fatal: false }).decode(sel); }
const ls = lines(text);
const sel = name === 'head' ? (minus ? ls.slice(0, Math.max(0, ls.length - n)) : ls.slice(0, n)) : plus ? ls.slice(Math.max(0, n - 1)) : n ? ls.slice(-n) : [];
return sel.length ? nl(sel) : '';
}
function cmdGrep(name, args, text) {
let ci = false, ctxA = 0, ctxB = 0, maxc = null, showN = false, fixed = false, invert = false, count = false, only = false, word = false, lineX = false, smart = false, ere = name !== 'grep';
const pats = [], sep = { '--after-context': 'A', '--before-context': 'B', '--context': 'C', '--max-count': 'm' };
const setCtx = (k, v) => { if (k === 'A') ctxA = v; else if (k === 'B') ctxB = v; else ctxA = ctxB = v; };
for (let i = 0; i < args.length;) {
let a = args[i++];
if (a === '--') { if (!pats.length && i < args.length) pats.push(args[i]); break; }
if (a.startsWith('--')) {
const map = { '--ignore-case': 'i', '--line-number': 'n', '--invert-match': 'v', '--count': 'c', '--only-matching': 'o', '--word-regexp': 'w', '--fixed-strings': 'F', '--line-regexp': 'x', '--extended-regexp': 'E', '--smart-case': 'S', '--no-ignore-case': '' };
if (a in map) { if (!map[a]) { ci = false; continue; } a = '-' + map[a]; }
else if (a.includes('=') && sep[a.split('=')[0]]) { const [o, v] = [a.split('=')[0], a.split('=').slice(1).join('=')], k = sep[o]; if (k === 'm') maxc = int(v, 'count'); else setCtx(k, int(v, 'context')); continue; }
else if (sep[a]) { if (i >= args.length) throw new CmdError(`${name}: option ${a} requires an argument`); const k = sep[a], v = args[i++]; if (k === 'm') maxc = int(v, 'count'); else setCtx(k, int(v, 'context')); continue; }
else if (['--no-heading', '--color=never', '--with-filename', '--no-filename', '--no-line-number', '--text', '--no-messages'].includes(a)) continue;
else throw new CmdError(`${name}: unsupported option ${a}`);
}
if (a.startsWith('-') && a.length > 1) {
for (let j = 1; j < a.length;) {
const c = a[j++];
if ('NHhPIasU'.includes(c)) continue;
else if (c === 'E') ere = true; else if (c === 'G') ere = false;
else if (c === 'i') ci = true; else if (c === 'n') showN = true; else if (c === 'F') fixed = true; else if (c === 'v') invert = true;
else if (c === 'c') count = true; else if (c === 'o') only = true; else if (c === 'w') word = true; else if (c === 'x') lineX = true; else if (c === 'S') smart = true;
else if ('ABCme'.includes(c)) {
let v = j < a.length ? a.slice(j) : args[i];
if (v === undefined) throw new CmdError(`${name}: option -${c} requires an argument`);
if (j >= a.length) i++;
j = a.length;
if (c === 'e') pats.push(v); else if (c === 'm') maxc = int(v, 'count'); else setCtx(c, int(v, 'context'));
} else throw new CmdError(`${name}: unsupported option -${c}`);
}
continue;
}
if (!pats.length) pats.push(a); else throw new CmdError(`${name} reads stdin only; file arguments are not allowed`);
}
if (!pats.length) throw new CmdError(`usage: ${name} [options] PATTERN`);
if (smart && !pats.some((p) => /[A-Z]/.test(p))) ci = true;
const rx = compile(pats, { ci, bre: !ere && !fixed, fixed, word, lineX });
const ls = lines(text), hit = ls.map((l) => rx.test(l) !== invert);
if (maxc !== null) { let seen = 0; hit.forEach((h, k) => { if (h && ++seen > maxc) hit[k] = false; }); }
if (count) return `${hit.filter(Boolean).length}\n`;
if (only && !invert) {
const g = new RegExp(rx.source, rx.flags + 'g'), out = [];
ls.forEach((l, k) => { if (hit[k]) for (const m of l.matchAll(g)) if (m[0]) out.push((showN ? `${k + 1}:` : '') + m[0]); });
return nl(out);
}
const keep = new Set();
hit.forEach((h, k) => { if (h) for (let x = Math.max(0, k - ctxB); x < Math.min(ls.length, k + ctxA + 1); x++) keep.add(x); });
const out = []; let last = -1;
for (const k of [...keep].sort((a, b) => a - b)) {
if ((ctxA || ctxB) && last >= 0 && k !== last + 1) out.push('--');
out.push((showN ? `${k + 1}${hit[k] ? ':' : '-'}` : '') + ls[k]); last = k;
}
return nl(out);
}
// ---- sed: addresses (N, $, /re/, a,b ranges, !), commands p d q s (flags g p i, N), several commands separated by ; or newline or -e
function parseSed(script, ere) {
const cmds = []; let i = 0;
const readDelimited = (d) => {
let out = '';
for (; i < script.length; i++) {
const c = script[i];
if (c === '\\' && i + 1 < script.length) { out += script[i + 1] === d ? d : c + script[i + 1]; i++; }
else if (c === d) { i++; return out; }
else out += c;
}
throw new CmdError('sed: unterminated address or s command');
};
const addr = () => {
if (/\d/.test(script[i] || '')) { let j = i; while (/\d/.test(script[j] || '')) j++; const n = parseInt(script.slice(i, j), 10); i = j; return { n }; }
if (script[i] === '$') { i++; return { last: true }; }
if (script[i] === '/') { i++; return { re: compile([readDelimited('/')], { bre: !ere }) }; }
return null;
};
const ws = () => { while (i < script.length && /[\s;]/.test(script[i])) i++; };
for (ws(); i < script.length; ws()) {
const a1 = addr(); let a2 = null, neg = false;
if (a1 && script[i] === ',') { i++; a2 = addr(); if (!a2) throw new CmdError('sed: bad second address'); }
while (script[i] === ' ') i++;
if (script[i] === '!') { neg = true; i++; while (script[i] === ' ') i++; }
const c = script[i++];
if (c === 'p' || c === 'd') cmds.push({ a1, a2, neg, cmd: c });
else if (c === 'q') { while (/\d/.test(script[i] || '')) i++; cmds.push({ a1, a2, neg, cmd: 'q' }); }
else if (c === 's') {
const d = script[i++]; if (!d || /[\s\\]/.test(d)) throw new CmdError('sed: bad s command');
const pat = readDelimited(d), rep = readDelimited(d); let f = '';
while (i < script.length && /[gpiI0-9]/.test(script[i])) f += script[i++];
const parts = []; let lit = '';
for (let k = 0; k < rep.length; k++) {
const ch = rep[k];
if (ch === '\\' && k + 1 < rep.length) { const nx = rep[++k]; if (/\d/.test(nx)) { parts.push(lit, +nx); lit = ''; } else lit += nx === 'n' ? '\n' : nx === 't' ? '\t' : nx; }
else if (ch === '&') { parts.push(lit, 0); lit = ''; } else lit += ch;
}
parts.push(lit);
cmds.push({ a1, a2, neg, cmd: 's', rx: compile([pat], { bre: !ere, ci: /[iI]/.test(f), flags: f.includes('g') ? 'g' : '' }), parts, g: f.includes('g'), p: f.includes('p'), nth: +(f.match(/\d+/)?.[0] || 0) });
} else throw new CmdError(`sed: unsupported command '${c ?? ''}' (supported: p d q s, with addresses N $ /re/ and ranges)`);
}
if (!cmds.length) throw new CmdError('sed: no script');
return cmds;
}
function substitute(line, c) {
const g = new RegExp(c.rx.source, c.rx.flags.replace('g', '') + 'g'); let out = '', last = 0, count = 0, did = false, m;
while ((m = g.exec(line))) {
count++;
if (!c.nth || count === c.nth) {
out += line.slice(last, m.index) + c.parts.map((p) => (typeof p === 'number' ? m[p] ?? '' : p)).join(''); last = m.index + m[0].length; did = true;
if (!c.g) break;
}
if (m[0] === '') g.lastIndex++;
}
return { text: did ? out + line.slice(last) : line, did };
}
function cmdSed(args, text) {
let quiet = false, ere = false; const scripts = [];
for (let i = 0; i < args.length;) {
const a = args[i++];
if (['-n', '--quiet', '--silent'].includes(a)) quiet = true;
else if (['-E', '-r', '--regexp-extended'].includes(a)) ere = true;
else if (a === '-e' || a === '--expression') { if (i >= args.length) throw new CmdError('sed: -e requires a script'); scripts.push(args[i++]); }
else if (/^-[nEr]+$/.test(a)) { if (a.includes('n')) quiet = true; if (/[Er]/.test(a)) ere = true; }
else if (a.startsWith('-') && a.length > 1) throw new CmdError(`sed: unsupported option ${a}`);
else scripts.push(a);
}
if (!scripts.length) throw new CmdError('sed: missing script');
const cmds = parseSed(scripts.join('\n'), ere), ls = lines(text), out = [], st = cmds.map(() => ({ on: false }));
const at = (a, num, line) => (a.n !== undefined ? num === a.n : a.last ? num === ls.length : a.re.test(line));
const picked = (c, k, num, line) => {
if (!c.a1) return !c.neg;
let r;
if (!c.a2) r = at(c.a1, num, line);
else if (st[k].on) { r = true; if (c.a2.n !== undefined ? num >= c.a2.n : at(c.a2, num, line)) st[k].on = false; }
else if (at(c.a1, num, line)) { r = true; st[k].on = !(c.a2.n !== undefined && c.a2.n <= num) && !(c.a2.last && num === ls.length); }
else r = false;
return r !== c.neg;
};
let quit = false;
for (let ln = 0; ln < ls.length && !quit; ln++) {
let ps = ls[ln], deleted = false;
for (let k = 0; k < cmds.length && !deleted; k++) {
const c = cmds[k]; if (!picked(c, k, ln + 1, ps)) continue;
if (c.cmd === 'p') out.push(ps); else if (c.cmd === 'd') deleted = true; else if (c.cmd === 'q') { quit = true; break; }
else { const r = substitute(ps, c); ps = r.text; if (r.did && c.p) out.push(ps); }
}
if (!deleted && !quiet) out.push(ps);
}
return nl(out);
}
function cmdWc(args, text) {
const sel = [];
for (const a of args) { if (!/^-[lwcmL]+$/.test(a)) throw new CmdError('wc supports -l -w -c -m -L'); for (const f of a.slice(1)) sel.push('-' + f); }
const v = { '-l': (text.match(/\n/g) || []).length, '-w': text.split(/\s+/).filter(Boolean).length, '-c': new TextEncoder().encode(text).length, '-m': [...text].length, '-L': Math.max(0, ...text.split('\n').map((l) => [...l].length)) };
const order = ['-l', '-w', '-m', '-c', '-L'], want = sel.length ? order.filter((o) => sel.includes(o)) : ['-l', '-w', '-c'];
return want.map((a) => (want.length > 1 ? String(v[a]).padStart(7) : v[a])).join(' ') + '\n';
}
function cmdSort(args, text) {
let rev = false, uniq = false, num = false, fold = false;
for (const a of args) {
if (!/^-[ruCnfbd]+$/.test(a)) throw new CmdError('sort supports -r -u -n -f -b');
for (const f of a.slice(1)) { if (f === 'r') rev = true; else if (f === 'u') uniq = true; else if (f === 'n') num = true; else if (f === 'f') fold = true; }
}
let ls = lines(text);
const key = (l) => { const m = l.match(/^\s*[-+]?\d+(\.\d+)?/); return m ? parseFloat(m[0]) : 0; }, f = (l) => (fold ? l.toLowerCase() : l);
const cmp = (a, b) => (num ? key(a) - key(b) : 0) || (f(a) < f(b) ? -1 : f(a) > f(b) ? 1 : 0) || (a < b ? -1 : a > b ? 1 : 0);
ls.sort(rev ? (a, b) => cmp(b, a) : cmp);
if (uniq) ls = ls.filter((l, k) => k === 0 || (num ? key(l) !== key(ls[k - 1]) : f(l) !== f(ls[k - 1])));
return nl(ls);
}
function cmdUniq(args, text) {
let c = false, d = false, u = false;
for (const a of args) { if (!/^-[cdu]+$/.test(a)) throw new CmdError('uniq supports -c -d -u'); for (const f of a.slice(1)) { if (f === 'c') c = true; else if (f === 'd') d = true; else u = true; } }
const out = []; let prev = null, n = 0;
const flush = () => { if (prev === null || (d && n < 2) || (u && n > 1)) return; out.push(c ? String(n).padStart(7) + ' ' + prev : prev); };
for (const l of lines(text)) { if (l === prev) { n++; continue; } flush(); prev = l; n = 1; }
flush();
return nl(out);
}
function ranges(spec, what) {
const r = [];
for (const part of spec.split(',')) {
const m = part.match(/^(\d*)(-?)(\d*)$/); if (!m || (!m[1] && !m[3])) throw new CmdError(`cut: invalid ${what} '${part}'`);
const lo = m[1] ? +m[1] : 1, hi = m[2] ? (m[3] ? +m[3] : Infinity) : lo; r.push([lo, hi]);
}
return r;
}
function cmdCut(args, text) {
let d = '\t', f = null, c = null, s = false;
for (let i = 0; i < args.length;) {
const a = args[i++];
if (a === '-d' && i < args.length) d = args[i++]; else if (a.startsWith('-d') && a.length > 2) d = a.slice(2);
else if (a === '-f' && i < args.length) f = args[i++]; else if (a.startsWith('-f') && a.length > 2) f = a.slice(2);
else if ((a === '-c' || a === '-b') && i < args.length) c = args[i++]; else if (/^-[cb]\d/.test(a)) c = a.slice(2);
else if (a === '-s') s = true;
else throw new CmdError('cut supports -d -f -c -b -s');
}
if (c) { const R = ranges(c, 'range'); return nl(lines(text).map((l) => [...l].filter((_, k) => R.some(([lo, hi]) => k + 1 >= lo && k + 1 <= hi)).join(''))); }
if (!f) throw new CmdError('cut: you must specify a list of bytes, characters, or fields');
const R = ranges(f, 'field list');
return nl(lines(text).flatMap((l) => { if (!l.includes(d)) return s ? [] : [l]; const p = l.split(d); return [p.filter((_, k) => R.some(([lo, hi]) => k + 1 >= lo && k + 1 <= hi)).join(d)]; }));
}
function trSet(s) {
let out = ''; s = s.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\\\/g, '\\');
const cls = { alpha: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', digit: '0123456789', lower: 'abcdefghijklmnopqrstuvwxyz', upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', space: ' \t\n\r\f\v', punct: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' };
cls.alnum = cls.alpha + cls.digit;
for (let i = 0; i < s.length;) {
const m = s.slice(i).match(/^\[:([a-z]+):\]/);
if (m && cls[m[1]]) { out += cls[m[1]]; i += m[0].length; }
else if (s[i + 1] === '-' && i + 2 < s.length) { for (let c = s.charCodeAt(i); c <= s.charCodeAt(i + 2); c++) out += String.fromCharCode(c); i += 3; }
else out += s[i++];
}
return [...out];
}
function cmdTr(args, text) {
let del = false, squeeze = false; const sets = [];
for (const a of args) { if (a === '-d') del = true; else if (a === '-s') squeeze = true; else if (/^-[ds]+$/.test(a)) { del ||= a.includes('d'); squeeze ||= a.includes('s'); } else if (a.startsWith('-') && a.length > 1) throw new CmdError('tr supports -d and -s'); else sets.push(a); }
if (!sets.length || sets.length > 2 || (!del && !squeeze && sets.length < 2)) throw new CmdError('tr: need SET1 SET2, or -d SET, or -s SET');
const s1 = trSet(sets[0]), s2 = sets[1] ? trSet(sets[1]) : [];
let out = '', prev = null;
for (const ch of text) {
const k = s1.indexOf(ch); let o = ch, inSet = k >= 0;
if (inSet && del) continue;
if (inSet && s2.length) o = s2[Math.min(k, s2.length - 1)];
if (squeeze && prev === o && (s2.length ? s2.includes(o) : inSet)) continue;
out += o; prev = o;
}
return out;
}
function cmdNl(args, text) {
let all = false;
for (const a of args) { if (a === '-ba') all = true; else if (a !== '-bt') throw new CmdError('nl supports -ba and -bt'); }
let n = 0; return nl(lines(text).map((l) => (l === '' && !all ? ' ' + l : String(++n).padStart(6) + '\t' + l)));
}
export const COMMANDS = new Set(['head', 'tail', 'grep', 'egrep', 'rg', 'sed', 'wc', 'sort', 'uniq', 'cut', 'cat', 'tr', 'nl']);
export function runStage(argv, text) {
const [name, ...args] = argv;
if (name === 'head' || name === 'tail') return cmdHeadTail(name, args, text);
if (['grep', 'egrep', 'rg'].includes(name)) return cmdGrep(name, args, text);
if (name === 'sed') return cmdSed(args, text);
if (name === 'wc') return cmdWc(args, text);
if (name === 'sort') return cmdSort(args, text);
if (name === 'uniq') return cmdUniq(args, text);
if (name === 'cut') return cmdCut(args, text);
if (name === 'tr') return cmdTr(args, text);
if (name === 'nl') return cmdNl(args, text);
if (name === 'cat' && !args.length) return text;
throw new CmdError(`command '${name}' is not allowed; supported commands are: ${[...COMMANDS].join(', ')}`);
}
export const runPipeline = (stages, text) => stages.reduce((t, st) => runStage(st, t), text);
// POSIX-ish word splitting: whitespace separates, '...' is literal, "..." honours \" and \\, a bare \ escapes the next character.
// Splits on standalone `|`. No shell: `( ) ; &` inside a word are literal (a Wikipedia URL may contain parentheses); bare operators are refused.
// A trailing `|| true` / `|| :` is accepted (it only hides the exit status; we have none).
export function splitPipeline(command) {
if (/[\n\r\0]/.test(command)) throw new CmdError('the command must be a single line');
command = command.replace(/\s*\|\|\s*(true|:)\s*$/, '');
const toks = []; let cur = '', has = false, i = 0;
const push = () => { if (has) toks.push(cur); cur = ''; has = false; };
while (i < command.length) {
const c = command[i];
if (/\s/.test(c)) { push(); i++; }
else if (c === "'") { const j = command.indexOf("'", i + 1); if (j < 0) throw new CmdError('invalid quoting: No closing quotation'); cur += command.slice(i + 1, j); has = true; i = j + 1; }
else if (c === '"') {
let j = i + 1; has = true;
for (;; j++) {
if (j >= command.length) throw new CmdError('invalid quoting: No closing quotation');
if (command[j] === '\\' && '"\\$`'.includes(command[j + 1] ?? '')) { cur += command[++j]; continue; }
if (command[j] === '"') break;
cur += command[j];
}
i = j + 1;
} else if (c === '\\') { if (i + 1 >= command.length) throw new CmdError('invalid quoting: No escaped character'); cur += command[i + 1]; has = true; i += 2; }
else { cur += c; has = true; i++; }
}
push();
const stages = []; let st = [];
for (const t of toks) {
if (t === '|') { if (!st.length) throw new CmdError('empty pipeline stage'); stages.push(st); st = []; }
else if ([';', ';;', '&', '&&', '||', '>', '>>', '<', '<<', '(', ')'].includes(t)) throw new CmdError(`shell operator '${t}' is not supported; only | pipes`);
else st.push(t);
}
if (!st.length) throw new CmdError('empty pipeline stage');
return [...stages, st];
}
// Run the filters off the main thread with a hard 5 s limit (upstream's max_runtime): a pathological regex cannot freeze the page.
function runLimited(stages, text, ms = 5000) {
const sync = () => { try { return { ok: true, text: runPipeline(stages, text) }; } catch (e) { return { ok: false, message: e.message, regex: e instanceof RegexError }; } };
if (typeof Worker === 'undefined') return Promise.resolve(sync());
let w; try { w = new Worker(new URL('./termworker.js', import.meta.url), { type: 'module' }); } catch { return Promise.resolve(sync()); }
return new Promise((resolve) => {
const done = (v) => { clearTimeout(t); outer?.removeEventListener('abort', stop); w.terminate(); resolve(v); };
const stop = () => done({ ok: false, message: 'stopped', stopped: true });
const t = setTimeout(() => done({ timeout: true }), ms);
outer?.addEventListener('abort', stop, { once: true });
w.onmessage = (e) => done(e.data);
w.onerror = () => done(sync());
w.postMessage({ stages, text });
});
}
// What the model sees for a terminal call: the JSON envelope Ai2's tool client builds (literegistry_tool_client/output.py),
// with stdout capped at 10,000 characters.
const envelope = (o) => pyJson({ execution_time: o.execution_time, exit_code: o.exit_code, stderr: o.stderr, stdout: o.stdout, success: o.exit_code === 0, truncated: o.truncated, truncated_characters: o.truncated_characters });
export function truncateStdout(stdout) {
if (stdout.length <= MAX_OUTPUT) return { stdout, truncated: false, truncated_characters: 0 };
const missing = stdout.length - MAX_OUTPUT;
return { stdout: stdout.slice(0, MAX_OUTPUT) + `\n[ truncated (${missing} characters missing) ]`, truncated: true, truncated_characters: missing };
}
export async function webterminal(command) {
const t0 = Date.now(), secs = () => +((Date.now() - t0) / 1000).toFixed(4);
const fail = (msg) => `Terminal execution failed: ${msg}`;
command = (command || '').trim();
try {
const stages = splitPipeline(command);
if (stages[0][0] !== 'browse' || stages[0].length !== 2) throw new CmdError('start with `browse <url>`, then optionally pipe into head, tail, rg, grep, sed, wc, sort, uniq, cut, tr or nl');
for (const st of stages.slice(1)) if (!COMMANDS.has(st[0])) throw new CmdError(`command '${st[0]}' is not allowed; supported commands are: ${[...COMMANDS].join(', ')}`);
const text = await fetchPage(stages[0][1]);
const r = await runLimited(stages.slice(1), text);
stopped();
if (r.timeout) return envelope({ execution_time: secs(), exit_code: 124, stderr: 'pipeline timed out after 5 seconds', stdout: '', truncated: false, truncated_characters: 0 });
if (!r.ok) return r.regex ? envelope({ execution_time: secs(), exit_code: 2, stderr: r.message, stdout: '', truncated: false, truncated_characters: 0 }) : fail(r.message);
return envelope({ execution_time: secs(), exit_code: 0, stderr: '', ...truncateStdout(r.text) });
} catch (e) {
if (e?.name === 'AbortError') throw e;
return e instanceof CmdError ? fail(e.message) : fail(`could not open the page (${e?.name || 'Error'})`);
}
}