Spaces:
Running
Running
Align with upstream: final warning, query-only search, JSON terminal envelope, tolerant parser, context wrap-up, DuckDuckGo exact URLs, GNU-compatible filters with 5 s limit, short answer extraction
Browse filesFiles changed (6)
- agent.js+30-20
- engine.js+2-2
- index.html+3-3
- main.js+101-56
- termworker.jsAdded+6
- tools.js+281-76
2 unmodified lines34567891011121314151617181920212230 unmodified lines5354555657585960616263646566676869707172739 unmodified lines838485868788899091929394952 unmodified lines// Pure functions, no DOM and no model: tested in Node against the Python chat template (test_agent.mjs).export const MAX_TOOL_CALLS = 150;export const FINAL_WARNING = `IMPORTANT: This was your last allowed tool call.Do not call another tool. Give your final report now, withsupporting source URLs, then finish with a fenced JSON block exactly like:\`\`\`json{"answer": "your short canonical answer"}\`\`\``;// docstring-derived tool definitions, as the harness exposes them to the modelexport const TOOLS = [{ type: 'function', function: { name: 'search',description: 'Find candidate web sources for a query.\n\nUse this for discovery. The returned titles and snippets help select\ncandidate URLs, but must not be treated as verified source evidence.',parameters: { type: 'object', properties: {query: { type: 'string', description: 'Focused web search query.' },num_results: { type: 'integer', description: 'Maximum number of candidate results to return.', default: 10 } }, required: ['query'] } } },{ type: 'function', function: { name: 'webterminal',description: 'Open a source URL and inspect its page contents with a terminal pipeline.\n\nUse this after search: a search snippet is only a lead. Inspect the\nsource itself with commands such as `browse <url> | rg -n -i pattern`.',parameters: { type: 'object', properties: {30 unmodified lines}// Split the model's raw text (the prompt already ended with "<think>\n") into thinking, visible text and tool calls.export function parseAssistant(raw) {let thinking = '', rest = raw;const k = raw.indexOf('</think>');if (k >= 0) { thinking = raw.slice(0, k).trim(); rest = raw.slice(k + 8); }const calls = [];const re = /<tool_call>\s*<function=([^>\n]+)>([\s\S]*?)<\/function>\s*<\/tool_call>/g;let m;while ((m = re.exec(rest))) {const args = {}, pre = /<parameter=([^>\n]+)>\n?([\s\S]*?)\n?<\/parameter>/g;let p;while ((p = pre.exec(m[2]))) args[p[1].trim()] = p[2];calls.push({ name: m[1].trim(), args });}const content = rest.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').replace(/<tool_call>[\s\S]*$/, '').trim();return { thinking: k >= 0 ? thinking : raw.trim(), content: k >= 0 ? content : '', calls, finished: k >= 0 };}// Typed arguments per the schema (vLLM's parser does this for the harness), then the call as the backend expects it.9 unmodified linesreturn out;}// The harness's answer extraction: the last fenced ```json {"answer": ...} block.export function extractAnswer(text) {const all = [...text.matchAll(/```json\s*([\s\S]*?)```/g)];for (let i = all.length - 1; i >= 0; i--) { try { const a = JSON.parse(all[i][1]); if (a && typeof a.answer === 'string') return a.answer; } catch { /* next */ } }return null;}// vLLM-style sampler: temperature, top-k, top-p, presence penalty over the tokens generated so far.export function sample(logits, seen, { temperature = 1.0, topK = 20, topP = 0.95, presence = 1.5 } = {}, rnd = Math.random) {const n = logits.length, work = new Float32Array(logits);2 unmodified lines3456789101112131415161730 unmodified lines4849505152535455565758596061626364656667686970719 unmodified lines818283848586878889909192939495969798991001011021031041052 unmodified lines// Pure functions, no DOM and no model: tested in Node against the Python chat template (test_agent.mjs).export const MAX_TOOL_CALLS = 150;// prompts/final-warning.txt, the text every released eval/training config passes to the harnessexport const FINAL_WARNING = 'IMPORTANT: This was your last allowed tool call. Do not call another tool. Answer the question now using the evidence you have gathered.';// docstring-derived tool definitions, as the harness exposes them to the modelexport const TOOLS = [{ type: 'function', function: { name: 'search',description: 'Find candidate web sources for a query.\n\nUse this for discovery. The returned titles and snippets help select\ncandidate URLs, but must not be treated as verified source evidence.',parameters: { type: 'object', properties: {query: { type: 'string', description: 'Focused web search query.' } }, required: ['query'] } } },{ type: 'function', function: { name: 'webterminal',description: 'Open a source URL and inspect its page contents with a terminal pipeline.\n\nUse this after search: a search snippet is only a lead. Inspect the\nsource itself with commands such as `browse <url> | rg -n -i pattern`.',parameters: { type: 'object', properties: {30 unmodified lines}// Split the model's raw text (the prompt already ended with "<think>\n") into thinking, visible text and tool calls.// Tolerant like vLLM's qwen3_coder parser: a missing </tool_call>, </function> or </parameter> still yields the call.export function parseAssistant(raw) {let thinking = '', rest = raw;const k = raw.indexOf('</think>');if (k >= 0) { thinking = raw.slice(0, k).trim(); rest = raw.slice(k + 8).replace(/<\/think>/g, ''); }const calls = [], chunks = rest.split('<tool_call>');for (const chunk of chunks.slice(1)) {const body = chunk.split('</tool_call>')[0];const f = body.match(/<function=([^>\n]+)>([\s\S]*?)(?:<\/function>|$)/);if (!f) continue;const args = {}, pre = /<parameter=([^>\n]+)>\n?([\s\S]*?)(?:\n?<\/parameter>|\n?(?=<parameter=)|\n?(?=<\/function>)|$)/g;let p;while ((p = pre.exec(f[2]))) { args[p[1].trim()] = p[2]; if (p[0] === '') pre.lastIndex++; }for (const k of Object.keys(args)) args[k] = args[k].replace(/\n$/, '');calls.push({ name: f[1].trim(), args });}const content = chunks[0].trim();return { thinking: k >= 0 ? thinking : raw.replace(/<tool_call>[\s\S]*$/, '').trim(), content, calls, finished: k >= 0 };}// Typed arguments per the schema (vLLM's parser does this for the harness), then the call as the backend expects it.9 unmodified linesreturn out;}// Optional {"answer": ...} fence (the model is not asked for one; used only if it volunteers it).export function extractAnswer(text) {const all = [...text.matchAll(/```json\s*([\s\S]*?)```/g)];for (let i = all.length - 1; i >= 0; i--) { try { const a = JSON.parse(all[i][1]); if (a && (typeof a.answer === 'string' || typeof a.answer === 'number')) return String(a.answer); } catch { /* next */ } }return null;}// The short answer: the extraction step of Ai2's grader (BROWSECOMP_ANSWER_EXTRACTION_PROMPT, prompts/browsecomp-judge.json), run on the final report.const EXTRACT = "I will give you a [question], and a verbose candidate [response] to this [question]. You are to extract the final predicted answer from the [response] to this [question].\n\n[question]: {question}\n\n[response]: {response}\n\nCarefully read the model's reasoning and identify the **final concluded exact answer**. Put 'None' if there is no concluded exact, final answer to extract from the response.\n\nYou should output in the following format:\n<explanation>brief explanation for why this is the final concluded exact answer in the response</explanation>\n<extracted_answer>the exact final answer extracted</extracted_answer>";export const EXTRACT_SAMPLING = { temperature: 0.7, top_p: 0.8, top_k: 20, min_p: 0, presence_penalty: 1.5 }; // training/judging.py _stageexport function extractionPrompt(question, response) {return '<|im_start|>user\n' + EXTRACT.replace('{question}', () => question.trim()).replace('{response}', () => response.trim()) + '<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n';}export function parseExtraction(out) {const m = [...out.matchAll(/<extracted_answer>([\s\S]*?)<\/extracted_answer>/gi)].pop();const a = m ? m[1].trim() : '';return !a || /^none\.?$/i.test(a) ? null : a;}// vLLM-style sampler: temperature, top-k, top-p, presence penalty over the tokens generated so far.export function sample(logits, seen, { temperature = 1.0, topK = 20, topP = 0.95, presence = 1.5 } = {}, rnd = Math.random) {const n = logits.length, work = new Float32Array(logits);
1 unmodified line234567811 unmodified lines202122232425261 unmodified line// Sampling, the prompt-prefix cache and the context window are llama.cpp's own (the same server-context as llama-server).import { Wllama } from './vendor/wllama/index.js';export const SAMPLING = { temperature: 1.0, top_p: 0.95, top_k: 20, presence_penalty: 1.5 }; // DR Tulu 2's BrowseComp-Plus eval settingsexport async function createEngine({ url, nCtx = 32768, gpu = true, onProgress, onStatus }) {const wllama = new Wllama({ default: new URL('./vendor/wllama/wllama.wasm', import.meta.url).href });11 unmodified linesif (useCache && /quota|storage is full|QuotaExceeded/i.test(`${e?.name} ${e?.message}`)) { // no room to keep the model on disk: load it without the cacheonStatus?.('Not enough browser storage to keep the model for next time: loading it without saving…'); useCache = false; continue;}if (nCtx > 16384 && attempt < 3) { onStatus?.('Not enough memory for the long context, retrying with a shorter one…'); nCtx = 16384; continue; }throw e;}}1 unmodified line234567811 unmodified lines202122232425261 unmodified line// Sampling, the prompt-prefix cache and the context window are llama.cpp's own (the same server-context as llama-server).import { Wllama } from './vendor/wllama/index.js';export const SAMPLING = { temperature: 1.0, top_p: 0.95, top_k: 20, min_p: 0, presence_penalty: 1.5 }; // min_p 0: llama.cpp defaults to 0.05 // DR Tulu 2's BrowseComp-Plus eval settingsexport async function createEngine({ url, nCtx = 32768, gpu = true, onProgress, onStatus }) {const wllama = new Wllama({ default: new URL('./vendor/wllama/wllama.wasm', import.meta.url).href });11 unmodified linesif (useCache && /quota|storage is full|QuotaExceeded/i.test(`${e?.name} ${e?.message}`)) { // no room to keep the model on disk: load it without the cacheonStatus?.('Not enough browser storage to keep the model for next time: loading it without saving…'); useCache = false; continue;}if (nCtx > 16384 && attempt < 3) { onStatus?.('Could not load with the long context (memory?), retrying with a 16k one…'); nCtx = 16384; continue; }throw e;}}
40 unmodified lines414243444546474849505140 unmodified linesExpect minutes per answer. Open this Space in its own tab (not the embedded view) for multi-threading.</p><p><b>Agent.</b> The prompt, the two tools (<code>search</code>, <code>webterminal</code>), the 150-call budget and the final-answer warning are from<a href="https://github.com/allenai/dr-tulu2" target="_blank" rel="noopener">allenai/dr-tulu2</a>. Its live mode uses paid Serper and Jina keys; here there is no server at all:<code>search</code> reads Brave Search results and <code>browse</code> reads pages through <a href="https://jina.ai/reader" target="_blank" rel="noopener">Jina Reader</a>'s anonymous, browser-friendly endpoint(it renders JavaScript and gets past most bot walls), with Wikipedia and OpenAlex search and the Wayback Machine as fallbacks.The terminal is a small safe runner written in JavaScript for <code>head tail rg grep sed wc sort uniq cut</code>; there is no shell. Private and local addresses are refused.</p><p><b>Honest limits.</b> A 4-bit-class model on a free search stack is not the paper's setup: results can be thinner than the reported benchmarks, the free services rate-limit (about 20 page reads a minute, so steps can pause), and answers can be wrong. Check the sources it cites.The model runs on your device; your search queries and the URLs it opens are sent to Brave and Jina (anonymously, from your browser).</p><p id="store"></p><button id="wipe" type="button">Delete downloaded model</button></details>40 unmodified lines414243444546474849505140 unmodified linesExpect minutes per answer. Open this Space in its own tab (not the embedded view) for multi-threading.</p><p><b>Agent.</b> The prompt, the two tools (<code>search</code>, <code>webterminal</code>), the 150-call budget and the final-answer warning are from<a href="https://github.com/allenai/dr-tulu2" target="_blank" rel="noopener">allenai/dr-tulu2</a>. Its live mode uses paid Serper and Jina keys; here there is no server at all:<code>search</code> reads DuckDuckGo results (Brave as backup) and <code>browse</code> reads pages through <a href="https://jina.ai/reader" target="_blank" rel="noopener">Jina Reader</a>'s anonymous, browser-friendly endpoint(it renders JavaScript and gets past most bot walls), with Wikipedia and OpenAlex search and the Wayback Machine as fallbacks.The terminal is a small safe runner written in JavaScript for <code>head tail rg grep sed wc sort uniq cut tr nl</code>; there is no shell. Private and local addresses are refused, as are huggingface.co pages (as upstream blocks them). Each filter pipeline is limited to 5 seconds.</p><p><b>Honest limits.</b> A 4-bit-class model on a free search stack is not the paper's setup: results can be thinner than the reported benchmarks, the free services rate-limit (about 20 page reads a minute, so steps can pause), and answers can be wrong. Check the sources it cites.The model runs on your device; your search queries and the URLs it opens are sent to DuckDuckGo/Brave and Jina (anonymously, from your browser).</p><p id="store"></p><button id="wipe" type="button">Delete downloaded model</button></details>
1234562 unmodified lines910111213141523 unmodified lines394041424344458 unmodified lines54555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import { createEngine } from './engine.js';import { search, webterminal } from './tools.js';import { TOOLS, MAX_TOOL_CALLS, FINAL_WARNING, firstPrompt, toolTurn, parseAssistant, typedArgs, extractAnswer } from './agent.js';const q = new URLSearchParams(location.search);const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null); // test hooks accept same-origin paths only2 unmodified linesconst GGUF_BYTES = 2736583872;const USE_GPU = q.get('gpu') !== '0';const IM_END = '<|im_end|>';const CTX = Number(q.get('ctx')) || 32768, MAX_NEW = 6000; // context tokens, and per assistant turnconst EXAMPLES = [['Who wrote the music for the 2017 Argentine film "Desire", and where was that composer born?', 'film composer'],['What is the current world record for the men\'s 100 m freestyle in a 50 m pool, who holds it, and when was it set?', 'sports record'],23 unmodified linesonStatus: (t) => status(t) });status('Model ready.', 1);return { engine, system };})());// ---------------------------------------------------------------- transcriptfunction el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }8 unmodified lines// (the card is closed by the research loop once its tool result is in)}function showAnswer(text, short) {ui.answer.hidden = false; ui.short.textContent = short || ''; ui.report.textContent = text.trim();}// ---------------------------------------------------------------- tools (run in this page: tools.js)async function callTool(name, args) {try { return name === 'search' ? await search(args.query, args.num_results) : await webterminal(args.command); }catch (e) { return `Error: the tool failed (${e?.message || e}).`; }}// ---------------------------------------------------------------- the research loopasync function research(question) {aborted = false;ui.answer.hidden = true; ui.trail.replaceChildren();const { engine, system } = await loadEngine();let transcript = firstPrompt(system, question), calls = 0, step = 0, t0 = performance.now(), genTokens = 0, ctxTokens = await engine.countTokens(transcript);const ctl = new AbortController(); ui.stop.onclick = () => { aborted = true; ctl.abort(); };for (;;) {if (aborted) { status('Stopped.', 0); return; }step++;const card = stepCard(step);status(`Reading the conversation (${ctxTokens.toLocaleString()} tokens)…`, 0);let raw = '', finish = null, n = 0, tStart = 0, lastUi = 0;try {for await (const part of engine.complete(transcript, { maxTokens: Math.min(MAX_NEW, CTX - ctxTokens - 64), signal: ctl.signal })) {if (part.progress?.total) status(`Reading the conversation… ${Math.round(100 * part.progress.processed / part.progress.total)}%`, part.progress.processed / part.progress.total);if (part.text) { if (!n) tStart = performance.now(); raw += part.text; n++; }if (part.finish) finish = part.finish;const now = performance.now();if (part.text && now - lastUi > 250) {lastUi = now; card.think(parseAssistant(raw).thinking);status(`Thinking… ${n} tokens · ${(n * 1000 / Math.max(1, now - tStart)).toFixed(1)} tokens/s · context ${(ctxTokens + n).toLocaleString()} · tool calls ${calls}/${MAX_TOOL_CALLS}`);}}} catch (e) { if (aborted) { card.d.remove(); status('Stopped.', 0); return; } throw e; }genTokens += n;const parsed = parseAssistant(raw);card.think(parsed.thinking);if (!parsed.calls.length || !parsed.finished) { // the model answered (or ran out of room): this is the reportcard.d.remove();const text = parsed.finished ? parsed.content : parsed.thinking;showAnswer(text.replace(/```json[\s\S]*?```\s*$/, ''), extractAnswer(text));status(`Done in ${Math.round((performance.now() - t0) / 1000)} s · ${calls} tool calls · ${genTokens.toLocaleString()} tokens generated${finish === 'length' ? ' · stopped at the length limit' : ''}.`, 1);return;}const outputs = [];for (const c of parsed.calls) {const args = typedArgs(c);if (calls >= MAX_TOOL_CALLS) { outputs.push(`Tool not executed: tool-call budget exhausted. ${FINAL_WARNING}`); continue; }if (!args) { outputs.push(`Error: invalid call to ${c.name}. Available tools: ${TOOLS.map((t) => t.function.name).join(', ')}.`); continue; }calls++;card.set(c.name, c.name === 'search' ? args.query : args.command);status(`Tool call ${calls}/${MAX_TOOL_CALLS}: ${c.name}…`);let out = await callTool(c.name, args);if (calls === MAX_TOOL_CALLS) out += `\n\n${FINAL_WARNING}`;card.result(out); outputs.push(out);}card.d.classList.remove('live'); card.d.open = false;let next = raw + IM_END + toolTurn(outputs);let nextTokens = await engine.countTokens(transcript + next);if (nextTokens > CTX - 1500) { // out of context room: make the model write its report nownext = raw + IM_END + toolTurn(outputs.map(() => `Tool output omitted: the context window is full. ${FINAL_WARNING}`));nextTokens = await engine.countTokens(transcript + next);}transcript += next; ctxTokens = nextTokens;await tick();}}// ---------------------------------------------------------------- UI1234562 unmodified lines9101112131415161723 unmodified lines414243444546478 unmodified lines5657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171import { createEngine } from './engine.js';import { search, webterminal, setSignal } from './tools.js';import { TOOLS, MAX_TOOL_CALLS, FINAL_WARNING, firstPrompt, toolTurn, parseAssistant, typedArgs, extractAnswer, extractionPrompt, parseExtraction, EXTRACT_SAMPLING } from './agent.js';const q = new URLSearchParams(location.search);const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null); // test hooks accept same-origin paths only2 unmodified linesconst GGUF_BYTES = 2736583872;const USE_GPU = q.get('gpu') !== '0';const IM_END = '<|im_end|>';const CTX = Number(q.get('ctx')) || 32768, MAX_NEW = 16384; // context tokens wanted, and per assistant turn (upstream: 32768 per turn of a 262k context)const LEAD_IN = 'Based on the sources I read, here is my final answer.\n\n';const CONTEXT_WARNING = '[TOKEN BUDGET EXCEEDED] You are in the final 10% of the context budget. You should now do your best to compose the final answer.'; // upstream's wording (environment.py)const EXAMPLES = [['Who wrote the music for the 2017 Argentine film "Desire", and where was that composer born?', 'film composer'],['What is the current world record for the men\'s 100 m freestyle in a 50 m pool, who holds it, and when was it set?', 'sports record'],23 unmodified linesonStatus: (t) => status(t) });status('Model ready.', 1);return { engine, system };})().catch((e) => { enginePromise = null; throw e; }));// ---------------------------------------------------------------- transcriptfunction el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }8 unmodified lines// (the card is closed by the research loop once its tool result is in)}// Text with clickable links, built from text nodes and <a> elements only (never innerHTML).function linkify(node, text) {node.replaceChildren(); let last = 0;for (const m of text.matchAll(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s<>)\]"']+[^\s<>)\]"'.,;:!?])/g)) {node.append(text.slice(last, m.index));const a = el('a', '', m[1] || m[3]); a.href = m[2] || m[3]; a.target = '_blank'; a.rel = 'noopener noreferrer'; node.append(a);last = m.index + m[0].length;}node.append(text.slice(last));}function showAnswer(text, short) {ui.answer.hidden = false; ui.short.textContent = short || ''; linkify(ui.report, text.trim());}// ---------------------------------------------------------------- tools (run in this page: tools.js)async function callTool(name, args, signal) {setSignal(signal);try { return name === 'search' ? await search(args.query) : await webterminal(args.command); }catch (e) { if (e?.name === 'AbortError') throw e; return `Error: the tool failed (${e?.message || e}).`; }}// ---------------------------------------------------------------- the research loopasync function research(question) {aborted = false;ui.answer.hidden = true; ui.trail.replaceChildren();const ctl = new AbortController(); ui.stop.onclick = () => { aborted = true; ctl.abort(); }; // Stop works during the download, a generation and a tool callconst { engine, system } = await loadEngine();if (aborted) { status('Stopped.', 0); return; }const nCtx = Math.min(CTX, engine.nCtx || CTX), RESERVE = Math.min(6000, Math.floor(nCtx * 0.2)); // room kept free for the final reportlet transcript = firstPrompt(system, question), calls = 0, step = 0, t0 = performance.now(), genTokens = 0, ctxTokens = await engine.countTokens(transcript), wrapUp = false;// One streamed generation from `prompt` into `card`; returns the raw text and how it ended.async function generate(prompt, card, sampling) {let raw = '', finish = null, n = 0, tStart = 0, lastUi = 0;const used = prompt === transcript ? ctxTokens : await engine.countTokens(prompt), room = nCtx - used - 64;if (room < 128) return { raw: '', finish: 'length', n: 0 };for await (const part of engine.complete(prompt, { maxTokens: Math.min(MAX_NEW, room), signal: ctl.signal, sampling })) {if (part.progress?.total) status(`Reading the conversation… ${Math.round(100 * part.progress.processed / part.progress.total)}%`, part.progress.processed / part.progress.total);if (part.text) { if (!n) tStart = performance.now(); raw += part.text; n++; }if (part.finish) finish = part.finish;const now = performance.now();if (part.text && now - lastUi > 250) {lastUi = now; card.think(parseAssistant(raw).thinking);status(`Thinking… ${n} tokens · ${(n * 1000 / Math.max(1, now - tStart)).toFixed(1)} tokens/s · context ${(used + n).toLocaleString()} · tool calls ${calls}/${MAX_TOOL_CALLS}`);}}genTokens += n;return { raw, finish, n };}try {let final = null; // the report text once the model has written itfor (;;) {step++;const card = stepCard(step);status(`Reading the conversation (${ctxTokens.toLocaleString()} tokens)…`, 0);const { raw } = await generate(transcript, card);const parsed = parseAssistant(raw);card.think(parsed.thinking);if (!(parsed.finished && parsed.calls.length && !wrapUp)) { // a report: the model answered, ran out of room mid-thought, or kept calling tools after the final warningif (parsed.finished && !parsed.calls.length) final = parsed.content || parsed.thinking;else { // close the thinking ourselves and make it write the report (no more tools)status('Asking the model for its final report…');const more = await generate(transcript + parsed.thinking + '\n</think>\n\n' + LEAD_IN, card); // the lead-in keeps it writing prose instead of calling another toolfinal = more.raw.split('<tool_call>')[0].replace(/<\/think>/g, '').trim() || parsed.thinking;}}if (final !== null) {card.d.remove();if (!final.trim()) final = 'The model ran out of room before it could write a report. Try a narrower question.';const volunteered = extractAnswer(final), report = final.replace(volunteered ? /```json[\s\S]*?```\s*$/ : /$^/, '');showAnswer(report, volunteered || '');status(`Done in ${Math.round((performance.now() - t0) / 1000)} s · ${calls} tool calls · ${genTokens.toLocaleString()} tokens generated. Extracting the short answer…`, 1);if (!volunteered && report.trim()) { // the extraction step of Ai2's grader, on the reporttry {let out = ''; for await (const part of engine.complete(extractionPrompt(question, report.slice(-12000)), { maxTokens: 400, signal: ctl.signal, sampling: EXTRACT_SAMPLING })) out += part.text;const short = parseExtraction(out); if (short) ui.short.textContent = short;} catch { /* the report alone is fine */ }}status(`Done in ${Math.round((performance.now() - t0) / 1000)} s · ${calls} tool calls · ${genTokens.toLocaleString()} tokens generated.`, 1);return;}const outputs = [];for (const c of parsed.calls) {const args = typedArgs(c);if (calls >= MAX_TOOL_CALLS) { outputs.push(`Tool not executed: tool-call budget exhausted. ${FINAL_WARNING}`); wrapUp = true; continue; }if (!args) { outputs.push(`Error: invalid call to ${c.name}. Available tools: ${TOOLS.map((t) => t.function.name).join(', ')}.`); continue; }calls++;card.set(c.name, c.name === 'search' ? args.query : args.command);status(`Tool call ${calls}/${MAX_TOOL_CALLS}: ${c.name}…`);let out = await callTool(c.name, args, ctl.signal);if (calls === MAX_TOOL_CALLS) { out += `\n\n${FINAL_WARNING}`; wrapUp = true; }card.result(out); outputs.push(out);}card.d.classList.remove('live'); card.d.open = false;let next = raw + IM_END + toolTurn(outputs);let nextTokens = await engine.countTokens(transcript + next);if (!wrapUp && nextTokens > nCtx * 0.8) { // upstream's token-budget warning, at 80% of what fits hereoutputs[outputs.length - 1] += `\n\n${CONTEXT_WARNING}`; wrapUp = true;next = raw + IM_END + toolTurn(outputs); nextTokens = await engine.countTokens(transcript + next);}if (nextTokens > nCtx - RESERVE) { // still too big: keep the model's turn, drop the tool text, and make it write the reportwrapUp = true;next = raw + IM_END + toolTurn(outputs.map(() => `Tool output omitted: the context window is full. ${FINAL_WARNING}`));nextTokens = await engine.countTokens(transcript + next);}transcript += next; ctxTokens = nextTokens;await tick();}} catch (e) { if (aborted || e?.name === 'AbortError') { status('Stopped.', 0); return; } throw e; }}// ---------------------------------------------------------------- UI
123456// Runs the webterminal filters (tools.js runPipeline) off the main thread so a runaway regex can be terminated.import { runPipeline, RegexError } from './tools.js';onmessage = ({ data }) => { try { postMessage({ ok: true, text: runPipeline(data.stages, data.text) }); } catch (e) { postMessage({ ok: false, message: e.message, regex: e instanceof RegexError }); }};5 unmodified lines678910111213141516171819202122232425262728293031323 unmodified lines3637383940414275 unmodified lines1181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781 unmodified line1801811821831841851861872 unmodified lines19019119219319419519619719819912 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822833 unmodified lines28728828929029129229329429529629729829930023 unmodified lines3243253263273283293303313323333343353363373383393405 unmodified lines// 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.export const MAX_OUTPUT = 10_000; // the model is told terminal output is capped at 10,000 charactersconst 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;const MIN_GAP = 3100; // Jina's anonymous tier allows ~20 requests/minute per IPfunction paced(fn) {const run = chain.then(async () => { const wait = lastCall + MIN_GAP - Date.now(); if (wait > 0) await new Promise((r) => setTimeout(r, wait)); 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++) {const ctl = new AbortController(), t = setTimeout(() => ctl.abort(), timeout);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 new Promise((x) => setTimeout(x, 4000 * (attempt + 1))); continue; }return { status: r.status, text: await r.text() };} finally { clearTimeout(t); }}return { status: 429, text: '' };}3 unmodified lineslet 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' || /\.(local|internal|localhost)$/.test(h) || /^[\d.]+$/.test(h) || h.includes(':')) throw new CmdError('that host is not public');return p.href;}const pageCache = new Map();75 unmodified linesreturn { title: `${w.title} (${w.publication_year})`, body: words.filter(Boolean).join(' ').slice(0, 400), href: w.doi || w.primary_location?.landing_page_url || '' };});}export async function search(query, numResults = 10) {query = (query || '').trim(); const n = Math.max(1, Math.min(parseInt(numResults, 10) || 10, 10));if (!query) return 'Error: query is empty.';const key = query.toLowerCase() + '|' + n; let rows = searchCache.get(key);if (!rows) {rows = [];for (const f of [() => braveSearch(query), () => wikipedia(query, n), () => openalex(query, n)]) {try { rows = (await f()).filter((r) => r.href); } catch { /* next engine */ }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);}return rows.slice(0, n).map((r) => [`**${r.title.trim() || 'Untitled result'}**`, r.body, `Source: ${r.href}`].filter(Boolean).join('\n')).join('\n\n');}// ------------------------------------------------------------------------------------------ terminal pipelineexport class CmdError extends Error {}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, '\\$&');function cmdHeadTail(name, args, text) {let n = 10, bytes = false;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`); n = int(args[i].replace(/^\+/, ''), 'count'); bytes = a === '-c' || a === '--bytes'; }else if ((m = a.match(/^-([nc])([+-]?\d+)$/))) { n = int(m[2].replace(/^\+/, ''), 'count'); 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); return new TextDecoder('utf-8', { fatal: false }).decode(name === 'head' ? b.slice(0, n) : n ? b.slice(-n) : b.slice(0, 0)); }const ls = lines(text), sel = name === 'head' ? ls.slice(0, n) : 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;const pats = [];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' };if (map[a]) a = '-' + map[a];else if (a.startsWith('--max-count=')) { maxc = int(a.split('=')[1], 'count'); continue; }else if (/^--(after-context|before-context|context)=/.test(a)) { const v = int(a.split('=')[1], 'context'), k = a[2]; if (k === 'a') ctxA = v; else if (k === 'b') ctxB = v; else ctxA = ctxB = v; continue; }else if (['--no-heading', '--color=never', '--with-filename', '--no-filename'].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 ('NHhEPIas'.includes(c)) continue;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)) {1 unmodified lineif (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 { const k = int(v, 'context'); if (c === 'A') ctxA = k; else if (c === 'B') ctxB = k; else ctxA = ctxB = k; }} else throw new CmdError(`${name}: unsupported option -${c}`);}continue;2 unmodified lines}if (!pats.length) throw new CmdError(`usage: ${name} [options] PATTERN`);if (smart && !pats.some((p) => /[A-Z]/.test(p))) ci = true;let srcs = pats.map((p) => (fixed ? esc(p) : p.replace(/\(\?i\)/g, '')));if (word) srcs = srcs.map((s) => `\\b(?:${s})\\b`);if (lineX) srcs = srcs.map((s) => `^(?:${s})$`);let rx; try { rx = new RegExp(srcs.map((s) => `(?:${s})`).join('|'), ci ? 'iu' : 'u'); } catch { try { rx = new RegExp(srcs.map((s) => `(?:${s})`).join('|'), ci ? 'i' : ''); } catch (e) { throw new CmdError(`invalid regex: ${e.message}`); } }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`;12 unmodified linesreturn nl(out);}function cmdSed(args, text) {let quiet = false; const scripts = [];for (let i = 0; i < args.length;) {const a = args[i++];if (['-n', '--quiet', '--silent'].includes(a)) quiet = 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 (a.startsWith('-') && a.length > 1) throw new CmdError(`sed: unsupported option ${a}`);else scripts.push(a);}if (scripts.length !== 1) throw new CmdError('sed supports one script: N,Mp N,Md /re/p /re/d s/a/b/[gi]');const s = scripts[0].trim(), ls = lines(text);const emit = (sel, cmd) => { const out = []; ls.forEach((l, k) => { if (cmd === 'd') { if (!sel[k]) out.push(l); } else { if (!quiet) out.push(l); if (sel[k]) out.push(l); } }); return nl(out); };let m = s.match(/^(\d+|\$)?(?:,(\d+|\$))?\s*(!?)(p|d)$/);if (m && (m[1] || m[2] === undefined)) {const n = ls.length, lo = m[1] === '$' ? n : parseInt(m[1] || '1', 10), hi = m[2] === '$' ? n : m[2] ? parseInt(m[2], 10) : m[1] ? lo : n;return emit(ls.map((_, k) => (lo <= k + 1 && k + 1 <= hi) !== !!m[3]), m[4]);}if ((m = s.match(/^\/(.+)\/\s*(p|d)$/))) { let rx; try { rx = new RegExp(m[1]); } catch (e) { throw new CmdError(`invalid regex: ${e.message}`); } return emit(ls.map((l) => rx.test(l)), m[2]); }if ((m = s.match(/^s(.)(.+?)(?<!\\)\1(.*?)(?<!\\)\1([gi]*)$/))) {let rx; try { rx = new RegExp(m[2], (m[4].includes('i') ? 'i' : '') + (m[4].includes('g') ? 'g' : '')); } catch (e) { throw new CmdError(`invalid regex: ${e.message}`); }const rep = m[3].replace(/\$/g, '$$$$').replace(/&/g, '$&').replace(/\\(\d)/g, '$$$1');return quiet ? '' : nl(ls.map((l) => l.replace(rx, rep)));}throw new CmdError('unsupported sed script');}function cmdWc(args, text) {const sel = args.filter((a) => ['-l', '-w', '-c', '-m'].includes(a));if (sel.length !== args.length) throw new CmdError('wc supports -l -w -c -m');const v = { '-l': lines(text).length, '-w': text.split(/\s+/).filter(Boolean).length, '-c': new TextEncoder().encode(text).length, '-m': [...text].length };return (sel.length ? sel : ['-l', '-w', '-c']).map((a) => v[a]).join(' ') + '\n';}function cmdSort(args, text) {let rev = false, uniq = false, num = false;for (const a of args) { if (a === '-r') rev = true; else if (a === '-u') uniq = true; else if (a === '-n') num = true; else if (a !== '-f') throw new CmdError('sort supports -r -u -n -f'); }let ls = lines(text);const key = (l) => { const m = l.match(/^\s*-?\d+(\.\d+)?/); return m ? parseFloat(m[0]) : 0; };ls.sort((a, b) => (num ? key(a) - key(b) || (a < b ? -1 : a > b ? 1 : 0) : a < b ? -1 : a > b ? 1 : 0));if (rev) ls.reverse();if (uniq) ls = [...new Set(ls)];return nl(ls);}function cmdUniq(args, text) {if (args.some((a) => a !== '-c')) throw new CmdError('uniq supports -c');const c = args.includes('-c'), out = []; let prev = null, n = 0;for (const l of [...lines(text), null]) {if (l === prev) { n++; continue; }if (prev !== null) out.push(c ? String(n).padStart(7) + ' ' + prev : prev);prev = l; n = 1;}return nl(out);}function cmdCut(args, text) {let d = '\t', f = null;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 throw new CmdError('cut supports -d and -f');}if (!f) throw new CmdError('cut: need -f');const idx = [];for (const part of f.split(',')) { const [lo, hi] = part.split('-'); if (part.includes('-')) for (let k = parseInt(lo || '1', 10); k <= parseInt(hi || '9999', 10); k++) idx.push(k); else idx.push(parseInt(lo, 10)); }return nl(lines(text).map((l) => { if (!l.includes(d)) return l; const p = l.split(d); return idx.filter((k) => k > 0 && k <= p.length).map((k) => p[k - 1]).join(d); }));}export function runStage(argv, text) {const [name, ...args] = argv;if (name === 'head' || name === 'tail') return cmdHeadTail(name, args, text);3 unmodified linesif (name === 'sort') return cmdSort(args, text);if (name === 'uniq') return cmdUniq(args, text);if (name === 'cut') return cmdCut(args, text);if (name === 'cat' && !args.length) return text;throw new CmdError(`command not available: ${name} (use head, tail, rg, grep, sed, wc, sort, uniq, cut)`);}// 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.export function splitPipeline(command) {if (/[\n\r\0]/.test(command)) throw new CmdError('the command must be a single line');const toks = []; let cur = '', has = false, i = 0;const push = () => { if (has) toks.push(cur); cur = ''; has = false; };while (i < command.length) {23 unmodified linesreturn [...stages, st];}export const truncate = (t) => (t.length <= MAX_OUTPUT ? t : t.slice(0, MAX_OUTPUT) + `\n...[output truncated at ${MAX_OUTPUT} characters]`);export async function webterminal(command) {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 or cut');let text = await fetchPage(stages[0][1]);for (const st of stages.slice(1)) text = runStage(st, text);return text.trim() ? truncate(text) : '(no output)';} catch (e) {return e instanceof CmdError ? `error: ${e.message}` : `error: could not open the page (${e?.name || 'Error'})`;}}5 unmodified lines67891011121314151617181920212223242526272829303132333435363738393 unmodified lines434445464748495075 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392401 unmodified line2422432442452462472482 unmodified lines25125225325425525625712 unmodified lines2702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534543 unmodified lines45845946046146246346446546646746846947047147247347447547623 unmodified lines5005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455 unmodified lines// 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 charactersconst 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 runningconst 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 IPfunction 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: '' };}3 unmodified lineslet 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();75 unmodified linesreturn { 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 pipelineexport 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 islet 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)) {1 unmodified lineif (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;2 unmodified lines}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`;12 unmodified linesreturn 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 -efunction 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);3 unmodified linesif (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) {23 unmodified linesreturn [...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'})`);}}
agent.js+30-20
engine.js+2-2
index.html+3-3
main.js+101-56
termworker.jsAdded+6
tools.js+281-76