Spaces:
Running
Running
DR Tulu 2 WebGPU demo (all in browser)
Browse filesFiles changed (10)
- README.md+21-4
- agent.jsAdded+116
- engine.jsAdded+41
- index.html+53-17
- main.jsAdded+144
- prompt.jsonAdded+16
- style.css+50-23
- tools.jsAdded+340
- vendor/wllama/index.jsAdded
- vendor/wllama/wllama.wasmAdded+3
12342345678910111213141516171819202122232425102627---title: DR Tulu2 WebGPUemoji: 📊colorFrom: graytitle: DR Tulu 2 WebGPUemoji: 🧭colorFrom: redcolorTo: indigosdk: staticapp_file: index.htmlpinned: falselicense: apache-2.0short_description: Ai2's 4B deep research agent, running in your browsercustom_headers: cross-origin-embedder-policy: credentialless cross-origin-opener-policy: same-origin cross-origin-resource-policy: cross-originmodels: - allenai/DR-Tulu2-4B - bartowski/allenai_DR-Tulu2-4B-GGUFtags: - webgpu - wllama - gguf - deep-research - agent---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference[DR Tulu 2](https://github.com/allenai/dr-tulu2), Ai2's 4B open deep research agent, running entirely in your browser: the model is bartowski's Q4_K_M GGUF on wllama (llama.cpp WebAssembly + WebGPU), and its `search` / `webterminal` tools run in the page too (Brave results and Jina Reader, no keys, no server).The prompt, tool definitions, 150-call budget and final-answer warning come from allenai/dr-tulu2.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116// DR Tulu 2 agent logic, ported from allenai/dr-tulu2 (drtulu2-client): the general-web system prompt, the two tools// (`search`, `webterminal`), the 150-call budget with its final warning, and Qwen3.5's XML tool-call format.// 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: { command: { type: 'string', description: 'A `browse <url>` command, optionally followed by a pipeline.' } }, required: ['command'] } } },];
// Python's json.dumps(ensure_ascii=False): ", " and ": " separators (what the chat template's `tojson` prints)export function pyJson(v) { if (v === null) return 'null'; if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') return JSON.stringify(v); if (Array.isArray(v)) return '[' + v.map(pyJson).join(', ') + ']'; return '{' + Object.entries(v).map(([k, x]) => JSON.stringify(k) + ': ' + pyJson(x)).join(', ') + '}';}
const TOOL_FORMAT = '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>';
// The first turn exactly as DR-Tulu2-4B's chat_template.jinja renders [system, user] with tools and the generation prompt.export function firstPrompt(system, question, tools = TOOLS) { let s = '<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>'; for (const t of tools) s += '\n' + pyJson(t); s += '\n</tools>' + TOOL_FORMAT; if (system.trim()) s += '\n\n' + system.trim(); s += '<|im_end|>\n'; s += '<|im_start|>user\n' + question.trim() + '<|im_end|>\n'; return s + '<|im_start|>assistant\n<think>\n';}
// Text to append after the model's turn (its stop token <|im_end|> is fed separately): the tool responses as one user// turn, then the next generation prompt. Same layout the template gives role="tool" messages.export function toolTurn(outputs) { let s = '\n<|im_start|>user'; for (const o of outputs) s += '\n<tool_response>\n' + o.trim() + '\n</tool_response>'; return s + '<|im_end|>\n<|im_start|>assistant\n<think>\n';}
// 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.export function typedArgs(call) { const def = TOOLS.find((t) => t.function.name === call.name); if (!def) return null; const props = def.function.parameters.properties, out = {}; for (const [k, v] of Object.entries(call.args)) { if (!props[k]) continue; out[k] = props[k].type === 'integer' ? parseInt(v, 10) : v; } for (const r of def.function.parameters.required) if (out[r] === undefined || Number.isNaN(out[r])) return null; return 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); if (presence) for (const t of seen) work[t] -= presence; // top-k candidates by partial selection const k = Math.min(topK > 0 ? topK : n, n), idx = new Int32Array(k), val = new Float32Array(k).fill(-Infinity); for (let i = 0; i < n; i++) { const x = work[i]; if (x > val[k - 1]) { let j = k - 1; while (j > 0 && val[j - 1] < x) { val[j] = val[j - 1]; idx[j] = idx[j - 1]; j--; } val[j] = x; idx[j] = i; } } const mx = val[0], p = new Float64Array(k); let sum = 0; for (let i = 0; i < k; i++) { p[i] = Math.exp((val[i] - mx) / temperature); sum += p[i]; } let cut = k, acc = 0; for (let i = 0; i < k; i++) { acc += p[i] / sum; if (acc >= topP) { cut = i + 1; break; } } let tot = 0; for (let i = 0; i < cut; i++) tot += p[i]; let r = rnd() * tot; for (let i = 0; i < cut; i++) { r -= p[i]; if (r <= 0) return idx[i]; } return idx[cut - 1];}1234567891011121314151617181920212223242526272829303132333435363738394041// DR-Tulu2-4B as a GGUF (bartowski Q4_K_M) on wllama: llama.cpp compiled to WebAssembly, with its WebGPU backend.// 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 settings
export 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 }); const tryLoad = async (n_ctx, useCache) => { await wllama.loadModelFromUrl(url, { n_ctx, n_gpu_layers: gpu ? 999 : 0, connections: 6, cache_type_k: 'f16', cache_type_v: 'f16', useCache, progressCallback: ({ loaded, total }) => onProgress?.(loaded, total), }); }; let useCache = true; for (let attempt = 0; ; attempt++) { try { await tryLoad(nCtx, useCache); break; } catch (e) { console.warn('load failed:', e); await wllama.exit().catch(() => {}); if (useCache && /quota|storage is full|QuotaExceeded/i.test(`${e?.name} ${e?.message}`)) { // no room to keep the model on disk: load it without the cache onStatus?.('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; } } let info = {}; try { info = wllama.getLoadedContextInfo(); } catch { /* optional */ } return { nCtx, info, // Stream a raw completion. `prompt` is the whole transcript so far; llama.cpp reuses the cached prefix, so only new text is read. async *complete(prompt, { maxTokens = 6000, signal, sampling = SAMPLING } = {}) { const stream = await wllama.createCompletion({ prompt, stream: true, max_tokens: maxTokens, abortSignal: signal, return_progress: true, ...sampling }); for await (const chunk of stream) { const c = chunk.choices?.[0]; yield { text: c?.text ?? '', finish: c?.finish_reason ?? null, progress: chunk.prompt_progress ?? null, usage: chunk.usage ?? null, timings: chunk.timings ?? null }; } }, async countTokens(text) { try { return (await wllama.tokenize(text)).length; } catch { return Math.ceil(text.length / 3.2); } }, async exit() { await wllama.exit(); }, };}1234567891011121314151617182345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455<!doctype html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>My static Space</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="card"> <h1>Welcome to your static Space!</h1> <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p> <p> Also don't forget to check the <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>. </p> </div> </body><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>DR Tulu 2 WebGPU</title><meta name="description" content="Ai2's open 4B deep research agent, DR-Tulu2-4B, thinking on your own GPU in the browser reading the web through free, key-less services."><link rel="icon" href="data:,"><link rel="stylesheet" href="style.css"></head><body><main> <p id="line"><b><a href="https://huggingface.co/allenai/DR-Tulu2-4B" target="_blank" rel="noopener">DR Tulu 2</a></b> is a 4B deep research agent from Ai2. Everything runs in this page: the model on <b>your GPU</b>, and its web search and page reading through free, key-less services.</p>
<form id="ask" autocomplete="off"> <label for="q" class="sr">Research question</label> <textarea id="q" rows="3" maxlength="1500" placeholder="Ask something that needs looking up…" spellcheck="true"></textarea> <div id="row"> <button id="go" type="submit">Research</button> <button id="stop" type="button" hidden>Stop</button> <span id="examples"></span> </div> </form>
<p id="status" role="status" aria-live="polite">Ready. The model (2.7 GB) downloads once, when you first press Research.</p> <div id="bar"><i></i></div>
<section id="answer" hidden> <h2>Answer</h2> <p id="short"></p> <div id="report"></div> </section>
<section id="trail" aria-label="Research steps"></section>
<details id="more"> <summary>How it works, limits and credits</summary> <p><b>Model.</b> <a href="https://huggingface.co/allenai/DR-Tulu2-4B" target="_blank" rel="noopener">allenai/DR-Tulu2-4B</a> (Apache-2.0), reinforcement-learned on Qwen3.5-4B, runs in your browser as a 4-bit K-quant GGUF (<a id="repo" target="_blank" rel="noopener">bartowski's Q4_K_M</a>) on <a href="https://github.com/ngxson/wllama" target="_blank" rel="noopener">wllama</a>, llama.cpp compiled to WebAssembly with its WebGPU backend. It needs about 4 GB of free memory; without WebGPU it runs on the CPU, slowly. Expect 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></main><script type="module" src="main.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import { 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 only// bartowski's imatrix K-quant of allenai/DR-Tulu2-4B, used as published (no re-hosting)const GGUF = local(q.get('gguf')) || 'https://huggingface.co/bartowski/allenai_DR-Tulu2-4B-GGUF/resolve/main/allenai_DR-Tulu2-4B-Q4_K_M.gguf';const 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'], ['Which open-weight language models above 100B parameters were released in the last six months, and who made them?', 'recent models'],];
const $ = (id) => document.getElementById(id);const ui = { form: $('ask'), q: $('q'), go: $('go'), stop: $('stop'), status: $('status'), bar: $('bar').firstElementChild, answer: $('answer'), short: $('short'), report: $('report'), trail: $('trail'), store: $('store'), wipe: $('wipe'), examples: $('examples') };const mb = (b) => `${Math.round(b / 1e6)} MB`;const tick = () => new Promise((r) => setTimeout(r, 0));let aborted = false;
function status(text, frac = null, bad = false) { ui.status.textContent = text; ui.status.classList.toggle('bad', bad); if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`;}
// ---------------------------------------------------------------- modellet enginePromise = null;const loadEngine = () => (enginePromise ||= (async () => { if (USE_GPU && !navigator.gpu) status('No WebGPU in this browser: running on the CPU (slow).', 0); const system = (await (await fetch('prompt.json')).json()).chat_template[0].content; if (window.__testEngine) { status('Model ready.', 1); return { engine: window.__testEngine, system }; } // test hook: a stand-in engine const engine = await createEngine({ url: GGUF, nCtx: CTX, gpu: USE_GPU && !!navigator.gpu, onProgress: (loaded, total) => status(`Downloading the model: ${mb(loaded)} of ${mb(total || GGUF_BYTES)}, first time only`, loaded / (total || GGUF_BYTES)), onStatus: (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; }
function stepCard(n) { const d = el('details', 'step live'); const s = el('summary'); s.append(el('span', 'n', `${n}.`), el('span', 'tool', 'thinking…'), el('span', 'arg', '')); d.append(s); ui.trail.append(d); return { d, set(tool, arg) { s.children[1].textContent = tool; s.children[2].textContent = arg || ''; }, think(text) { let t = d.querySelector('.think'); if (!t) { t = el('div', 'think'); d.append(t); } t.textContent = text; t.scrollTop = t.scrollHeight; }, result(text) { d.querySelector('pre')?.remove(); d.append(el('pre', '', text)); d.classList.remove('live'); } };}
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 report card.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'); 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 now 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(); }}
// ---------------------------------------------------------------- UIui.form.addEventListener('submit', async (e) => { e.preventDefault(); const question = ui.q.value.trim(); if (!question) return; ui.go.disabled = true; ui.stop.hidden = false; try { await research(question); } catch (err) { console.error(err); status(err?.message || String(err), null, true); } ui.go.disabled = false; ui.stop.hidden = true; storage();});ui.q.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) ui.form.requestSubmit(); });for (const [text, label] of EXAMPLES) { const b = el('button', '', label); b.type = 'button'; b.title = text; b.addEventListener('click', () => { ui.q.value = text; ui.q.focus(); }); ui.examples.append(b);}$('repo').href = 'https://huggingface.co/bartowski/allenai_DR-Tulu2-4B-GGUF'; $('repo').textContent = 'bartowski/allenai_DR-Tulu2-4B-GGUF';async function storage() { try { const e = await navigator.storage.estimate(); ui.store.textContent = `This site stores ${mb(e.usage || 0)} in this browser.`; } catch { ui.store.textContent = ''; } }ui.wipe.addEventListener('click', async () => { try { const root = await navigator.storage.getDirectory(); for await (const [name] of root.entries()) await root.removeEntry(name, { recursive: true }); } catch { /* nothing cached */ } enginePromise = null; ui.store.textContent = 'Deleted. The model downloads again next time.'; });storage();window.__dr = { loadEngine, research }; // test hook12345678910111213141516{ "name": "webterminal-plain-answer-v1", "input_variables": [ "question" ], "chat_template": [ { "role": "system", "content": "You are a deep research agent. You have two tools.\n\n`search(query)` discovers candidate documents and URLs. Its output contains only tiny snippets.\n\n`webterminal(command)` reads document content. After search returns a plausible URL, inspect it with webterminal before relying on it or citing it. Use focused pipelines such as `browse <url> | rg -n -i '<pattern>'` or `browse <url> | head -n 80`; a bare `browse <url>` is only for an initial scan.\n\nWEBTERMINAL COMMAND SYNTAX: `command` must be one plain, single-line shell command. For `browse`, copy the URL as raw text: for example, `browse https://en.wikipedia.org/wiki/Desire_(film) | rg -n -i '2017|argentin'`. Never pass a Markdown link such as `[title](https://example.com)`, angle-bracket markup, escaped parentheses or backslashes, or a `\\` line continuation. Put literal spaces on both sides of every pipe (` | `).\n\nWhen using webterminal, it is important to search through a page multiple times with focused `rg`, `grep`, or `sed` commands. Webterminal output is constrained to 10,000 characters: make each command select the most relevant lines and surrounding context, otherwise its output may be truncated before the evidence you need.\n\nYou have a limited budget of 150 total `search` and `webterminal` calls. You will receive a warning after your last allowed call. When that warning arrives, do not call another tool: consolidate the evidence already gathered and make your best attempt to answer the question." }, { "role": "user", "content": "{question}" } ]}12312345567867891011121314151611121314151617181920212223242526181920212223242728293031262728323334353637383940414243444546474849505152535455body { padding: 2rem; font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;:root { --bg: #f4f2ee; --panel: #ffffff; --ink: #1d1c1a; --muted: #6b6760; --line: #d8d4cc; --accent: #b4441b; --accent-ink: #ffffff; --bad: #a3261b; --tool: #2b5f8a; color-scheme: light dark;}
h1 { font-size: 16px; margin-top: 0;@media (prefers-color-scheme: dark) { :root { --bg: #151413; --panel: #1f1d1b; --ink: #ece8e1; --muted: #a29d94; --line: #3a3732; --accent: #e0703f; --accent-ink: #151413; --bad: #ff8a7a; --tool: #7db6e8; }}* { box-sizing: border-box; }html, body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }main { display: grid; gap: 10px; padding: 10px 12px 24px; max-width: 860px; margin: 0 auto; }#line { margin: 0; font-size: 14px; color: var(--muted); }#line b { color: var(--ink); }a { color: var(--accent); }
p { color: rgb(107, 114, 128); font-size: 15px; margin-bottom: 10px; margin-top: 5px;}#ask { display: grid; gap: 8px; }textarea { width: 100%; resize: vertical; min-height: 4.2em; padding: 8px 10px; font: inherit; color: var(--ink); background: var(--panel); border: 1px solid var(--line); border-radius: 6px; }#row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }button { font: inherit; font-weight: 600; min-height: 38px; padding: 0 16px; cursor: pointer; color: var(--accent-ink); background: var(--accent); border: 0; border-radius: 5px; }button:disabled { opacity: .55; cursor: default; }#stop { background: transparent; color: var(--ink); border: 1px solid var(--line); font-weight: 500; }#examples { display: flex; flex-wrap: wrap; gap: 6px; }#examples button { min-height: 28px; padding: 0 10px; font-size: 13px; font-weight: 400; color: var(--muted); background: transparent; border: 1px solid var(--line); border-radius: 14px; }#examples button:hover { color: var(--accent); border-color: var(--accent); }
.card { max-width: 620px; margin: 0 auto; padding: 16px; border: 1px solid lightgray; border-radius: 16px;}#status { margin: 0; min-height: 1.4em; font-size: 13px; color: var(--muted); font-variant-numeric: tabular-nums; }#status.bad { color: var(--bad); }#bar { height: 4px; background: var(--line); border-radius: 2px; overflow: hidden; margin-top: -4px; }#bar i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .2s; }
.card p:last-child { margin-bottom: 0;}#answer { background: var(--panel); border: 1px solid var(--line); border-left: 4px solid var(--accent); border-radius: 6px; padding: 8px 14px 12px; }#answer h2 { margin: 4px 0; font-size: 13px; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); font-weight: 600; }#short { margin: 4px 0 8px; font-size: 20px; font-weight: 600; }#short:empty { display: none; }#report { white-space: pre-wrap; overflow-wrap: anywhere; }
#trail { display: grid; gap: 6px; }.step { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 6px 10px; font-size: 13.5px; }.step > summary { cursor: pointer; display: flex; gap: 8px; align-items: baseline; }.step .n { color: var(--muted); font-variant-numeric: tabular-nums; min-width: 2.2em; }.step .tool { color: var(--tool); font-weight: 600; }.step .arg { overflow-wrap: anywhere; }.step pre { margin: 6px 0 2px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12.5px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; max-height: 16em; overflow: auto; color: var(--muted); }.think { color: var(--muted); font-size: 13px; border-left: 2px solid var(--line); padding: 2px 10px; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 9em; overflow: auto; }.live { border-style: dashed; }
#more { color: var(--muted); font-size: 13px; }#more p { margin: 6px 0; }summary { cursor: pointer; }#wipe { min-height: 30px; font-weight: 500; color: var(--ink); background: transparent; border: 1px solid var(--line); }code { font-size: 12.5px; }.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }:where(button, textarea, summary, a, [tabindex]):focus-visible { outline: 2px solid var(--accent) !important; outline-offset: 2px; }@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition-duration: 0.01ms !important; } }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340// 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.
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: '' };}
// ------------------------------------------------------------------------------------------ pagesexport 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' || /\.(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();export async function fetchPage(url) { url = checkUrl(url); if (pageCache.has(url)) return pageCache.get(url); const tried = []; let text = ''; try { // tier 1: Jina Reader (renders JS, strips boilerplate) const r = await getText(url, { reader: true, timeout: 45000 }); tried.push(`reader HTTP ${r.status}`); if (r.status < 400 && r.text.trim()) text = r.text; if (BLOCK.test(text.slice(0, 1500)) && text.length < 3000) text = ''; } catch (e) { tried.push(`reader ${e.name}`); } if (!text.trim()) try { // tier 2: the page itself, when its server allows cross-origin reads const r = await getText(url, { timeout: 15000 }); tried.push(`direct HTTP ${r.status}`); if (r.status < 400) text = htmlToText(r.text); } catch (e) { tried.push(`direct ${e.name === 'AbortError' ? 'timeout' : 'blocked by CORS'}`); } if (!text.trim()) try { // tier 3: Wayback Machine snapshot const av = await getText(`https://archive.org/wayback/available?url=${encodeURIComponent(url)}`, { timeout: 15000 }); const snap = JSON.parse(av.text)?.archived_snapshots?.closest?.url; if (snap) { const r = await getText(snap.replace(/^http:/, 'https:'), { reader: true, timeout: 45000 }); tried.push(`archive HTTP ${r.status}`); if (r.status < 400) text = r.text; } else tried.push('archive none'); } catch (e) { tried.push(`archive ${e.name}`); } text = text.trim() || `BLOCKED/EMPTY: could not get readable content from ${url} (${tried.join(', ')}). Try another 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');}
// ------------------------------------------------------------------------------------------ searchconst searchCache = new Map();const clean = (s) => s.replace(/<[^>]+>/g, '').replace(/"/g, '"').replace(/&/g, '&').replace(/'|'/g, "'").replace(/</g, '<').replace(/>/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 || '' }; });}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)) { 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 { 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; } 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; 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`; 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);}
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); 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 === '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) { 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];}
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'})`; }}123version https://git-lfs.github.com/spec/v1oid sha256:b012436a101ede8c877f2d26644c3181429d4fb8da4fd90c356110d86bfd74a6size 10838652README.md+21-4
agent.jsAdded+116
engine.jsAdded+41
index.html+53-17
main.jsAdded+144
prompt.jsonAdded+16
style.css+50-23
tools.jsAdded+340
vendor/wllama/index.jsAdded
vendor/wllama/wllama.wasmAdded+3