Nekochu commited on
Commit
a8293d1
·
verified ·
1 Parent(s): a46a122

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 files
Files changed (6) hide show
  1. agent.js +30 -20
  2. engine.js +2 -2
  3. index.html +3 -3
  4. main.js +101 -56
  5. termworker.js +6 -0
  6. tools.js +281 -76
agent.js CHANGED
@@ -3,20 +3,15 @@
3
  // Pure functions, no DOM and no model: tested in Node against the Python chat template (test_agent.mjs).
4
 
5
  export const MAX_TOOL_CALLS = 150;
6
- export const FINAL_WARNING = `IMPORTANT: This was your last allowed tool call.
7
- Do not call another tool. Give your final report now, with
8
- supporting source URLs, then finish with a fenced JSON block exactly like:
9
- \`\`\`json
10
- {"answer": "your short canonical answer"}
11
- \`\`\``;
12
 
13
  // docstring-derived tool definitions, as the harness exposes them to the model
14
  export const TOOLS = [
15
  { type: 'function', function: { name: 'search',
16
  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.',
17
  parameters: { type: 'object', properties: {
18
- query: { type: 'string', description: 'Focused web search query.' },
19
- num_results: { type: 'integer', description: 'Maximum number of candidate results to return.', default: 10 } }, required: ['query'] } } },
20
  { type: 'function', function: { name: 'webterminal',
21
  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`.',
22
  parameters: { type: 'object', properties: {
@@ -53,21 +48,24 @@ export function toolTurn(outputs) {
53
  }
54
 
55
  // Split the model's raw text (the prompt already ended with "<think>\n") into thinking, visible text and tool calls.
 
56
  export function parseAssistant(raw) {
57
  let thinking = '', rest = raw;
58
  const k = raw.indexOf('</think>');
59
- if (k >= 0) { thinking = raw.slice(0, k).trim(); rest = raw.slice(k + 8); }
60
- const calls = [];
61
- const re = /<tool_call>\s*<function=([^>\n]+)>([\s\S]*?)<\/function>\s*<\/tool_call>/g;
62
- let m;
63
- while ((m = re.exec(rest))) {
64
- const args = {}, pre = /<parameter=([^>\n]+)>\n?([\s\S]*?)\n?<\/parameter>/g;
 
65
  let p;
66
- while ((p = pre.exec(m[2]))) args[p[1].trim()] = p[2];
67
- calls.push({ name: m[1].trim(), args });
 
68
  }
69
- const content = rest.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').replace(/<tool_call>[\s\S]*$/, '').trim();
70
- return { thinking: k >= 0 ? thinking : raw.trim(), content: k >= 0 ? content : '', calls, finished: k >= 0 };
71
  }
72
 
73
  // Typed arguments per the schema (vLLM's parser does this for the harness), then the call as the backend expects it.
@@ -83,13 +81,25 @@ export function typedArgs(call) {
83
  return out;
84
  }
85
 
86
- // The harness's answer extraction: the last fenced ```json {"answer": ...} block.
87
  export function extractAnswer(text) {
88
  const all = [...text.matchAll(/```json\s*([\s\S]*?)```/g)];
89
- 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 */ } }
90
  return null;
91
  }
92
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  // vLLM-style sampler: temperature, top-k, top-p, presence penalty over the tokens generated so far.
94
  export function sample(logits, seen, { temperature = 1.0, topK = 20, topP = 0.95, presence = 1.5 } = {}, rnd = Math.random) {
95
  const n = logits.length, work = new Float32Array(logits);
 
3
  // Pure functions, no DOM and no model: tested in Node against the Python chat template (test_agent.mjs).
4
 
5
  export const MAX_TOOL_CALLS = 150;
6
+ // prompts/final-warning.txt, the text every released eval/training config passes to the harness
7
+ export 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.';
 
 
 
 
8
 
9
  // docstring-derived tool definitions, as the harness exposes them to the model
10
  export const TOOLS = [
11
  { type: 'function', function: { name: 'search',
12
  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.',
13
  parameters: { type: 'object', properties: {
14
+ query: { type: 'string', description: 'Focused web search query.' } }, required: ['query'] } } },
 
15
  { type: 'function', function: { name: 'webterminal',
16
  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`.',
17
  parameters: { type: 'object', properties: {
 
48
  }
49
 
50
  // Split the model's raw text (the prompt already ended with "<think>\n") into thinking, visible text and tool calls.
51
+ // Tolerant like vLLM's qwen3_coder parser: a missing </tool_call>, </function> or </parameter> still yields the call.
52
  export function parseAssistant(raw) {
53
  let thinking = '', rest = raw;
54
  const k = raw.indexOf('</think>');
55
+ if (k >= 0) { thinking = raw.slice(0, k).trim(); rest = raw.slice(k + 8).replace(/<\/think>/g, ''); }
56
+ const calls = [], chunks = rest.split('<tool_call>');
57
+ for (const chunk of chunks.slice(1)) {
58
+ const body = chunk.split('</tool_call>')[0];
59
+ const f = body.match(/<function=([^>\n]+)>([\s\S]*?)(?:<\/function>|$)/);
60
+ if (!f) continue;
61
+ const args = {}, pre = /<parameter=([^>\n]+)>\n?([\s\S]*?)(?:\n?<\/parameter>|\n?(?=<parameter=)|\n?(?=<\/function>)|$)/g;
62
  let p;
63
+ while ((p = pre.exec(f[2]))) { args[p[1].trim()] = p[2]; if (p[0] === '') pre.lastIndex++; }
64
+ for (const k of Object.keys(args)) args[k] = args[k].replace(/\n$/, '');
65
+ calls.push({ name: f[1].trim(), args });
66
  }
67
+ const content = chunks[0].trim();
68
+ return { thinking: k >= 0 ? thinking : raw.replace(/<tool_call>[\s\S]*$/, '').trim(), content, calls, finished: k >= 0 };
69
  }
70
 
71
  // Typed arguments per the schema (vLLM's parser does this for the harness), then the call as the backend expects it.
 
81
  return out;
82
  }
83
 
84
+ // Optional {"answer": ...} fence (the model is not asked for one; used only if it volunteers it).
85
  export function extractAnswer(text) {
86
  const all = [...text.matchAll(/```json\s*([\s\S]*?)```/g)];
87
+ 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 */ } }
88
  return null;
89
  }
90
 
91
+ // The short answer: the extraction step of Ai2's grader (BROWSECOMP_ANSWER_EXTRACTION_PROMPT, prompts/browsecomp-judge.json), run on the final report.
92
+ 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>";
93
+ export const EXTRACT_SAMPLING = { temperature: 0.7, top_p: 0.8, top_k: 20, min_p: 0, presence_penalty: 1.5 }; // training/judging.py _stage
94
+ export function extractionPrompt(question, response) {
95
+ 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';
96
+ }
97
+ export function parseExtraction(out) {
98
+ const m = [...out.matchAll(/<extracted_answer>([\s\S]*?)<\/extracted_answer>/gi)].pop();
99
+ const a = m ? m[1].trim() : '';
100
+ return !a || /^none\.?$/i.test(a) ? null : a;
101
+ }
102
+
103
  // vLLM-style sampler: temperature, top-k, top-p, presence penalty over the tokens generated so far.
104
  export function sample(logits, seen, { temperature = 1.0, topK = 20, topP = 0.95, presence = 1.5 } = {}, rnd = Math.random) {
105
  const n = logits.length, work = new Float32Array(logits);
engine.js CHANGED
@@ -2,7 +2,7 @@
2
  // Sampling, the prompt-prefix cache and the context window are llama.cpp's own (the same server-context as llama-server).
3
  import { Wllama } from './vendor/wllama/index.js';
4
 
5
- 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
6
 
7
  export async function createEngine({ url, nCtx = 32768, gpu = true, onProgress, onStatus }) {
8
  const wllama = new Wllama({ default: new URL('./vendor/wllama/wllama.wasm', import.meta.url).href });
@@ -20,7 +20,7 @@ export async function createEngine({ url, nCtx = 32768, gpu = true, onProgress,
20
  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
21
  onStatus?.('Not enough browser storage to keep the model for next time: loading it without saving…'); useCache = false; continue;
22
  }
23
- if (nCtx > 16384 && attempt < 3) { onStatus?.('Not enough memory for the long context, retrying with a shorter one…'); nCtx = 16384; continue; }
24
  throw e;
25
  }
26
  }
 
2
  // Sampling, the prompt-prefix cache and the context window are llama.cpp's own (the same server-context as llama-server).
3
  import { Wllama } from './vendor/wllama/index.js';
4
 
5
+ 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 settings
6
 
7
  export async function createEngine({ url, nCtx = 32768, gpu = true, onProgress, onStatus }) {
8
  const wllama = new Wllama({ default: new URL('./vendor/wllama/wllama.wasm', import.meta.url).href });
 
20
  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
21
  onStatus?.('Not enough browser storage to keep the model for next time: loading it without saving…'); useCache = false; continue;
22
  }
23
+ if (nCtx > 16384 && attempt < 3) { onStatus?.('Could not load with the long context (memory?), retrying with a 16k one…'); nCtx = 16384; continue; }
24
  throw e;
25
  }
26
  }
index.html CHANGED
@@ -41,11 +41,11 @@
41
  Expect minutes per answer. Open this Space in its own tab (not the embedded view) for multi-threading.</p>
42
  <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
43
  <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:
44
- <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
45
  (it renders JavaScript and gets past most bot walls), with Wikipedia and OpenAlex search and the Wayback Machine as fallbacks.
46
- 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>
47
  <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.
48
- 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>
49
  <p id="store"></p>
50
  <button id="wipe" type="button">Delete downloaded model</button>
51
  </details>
 
41
  Expect minutes per answer. Open this Space in its own tab (not the embedded view) for multi-threading.</p>
42
  <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
43
  <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:
44
+ <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
45
  (it renders JavaScript and gets past most bot walls), with Wikipedia and OpenAlex search and the Wayback Machine as fallbacks.
46
+ 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>
47
  <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.
48
+ 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>
49
  <p id="store"></p>
50
  <button id="wipe" type="button">Delete downloaded model</button>
51
  </details>
main.js CHANGED
@@ -1,6 +1,6 @@
1
  import { createEngine } from './engine.js';
2
- import { search, webterminal } from './tools.js';
3
- import { TOOLS, MAX_TOOL_CALLS, FINAL_WARNING, firstPrompt, toolTurn, parseAssistant, typedArgs, extractAnswer } from './agent.js';
4
 
5
  const q = new URLSearchParams(location.search);
6
  const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null); // test hooks accept same-origin paths only
@@ -9,7 +9,9 @@ const GGUF = local(q.get('gguf')) || 'https://huggingface.co/bartowski/allenai_D
9
  const GGUF_BYTES = 2736583872;
10
  const USE_GPU = q.get('gpu') !== '0';
11
  const IM_END = '<|im_end|>';
12
- const CTX = Number(q.get('ctx')) || 32768, MAX_NEW = 6000; // context tokens, and per assistant turn
 
 
13
  const EXAMPLES = [
14
  ['Who wrote the music for the 2017 Argentine film "Desire", and where was that composer born?', 'film composer'],
15
  ['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'],
@@ -39,7 +41,7 @@ const loadEngine = () => (enginePromise ||= (async () => {
39
  onStatus: (t) => status(t) });
40
  status('Model ready.', 1);
41
  return { engine, system };
42
- })());
43
 
44
  // ---------------------------------------------------------------- transcript
45
  function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }
@@ -54,73 +56,116 @@ function stepCard(n) {
54
  // (the card is closed by the research loop once its tool result is in)
55
  }
56
 
 
 
 
 
 
 
 
 
 
 
57
  function showAnswer(text, short) {
58
- ui.answer.hidden = false; ui.short.textContent = short || ''; ui.report.textContent = text.trim();
59
  }
60
 
61
  // ---------------------------------------------------------------- tools (run in this page: tools.js)
62
- async function callTool(name, args) {
63
- try { return name === 'search' ? await search(args.query, args.num_results) : await webterminal(args.command); }
64
- catch (e) { return `Error: the tool failed (${e?.message || e}).`; }
 
65
  }
66
 
67
  // ---------------------------------------------------------------- the research loop
68
  async function research(question) {
69
  aborted = false;
70
  ui.answer.hidden = true; ui.trail.replaceChildren();
 
71
  const { engine, system } = await loadEngine();
72
- let transcript = firstPrompt(system, question), calls = 0, step = 0, t0 = performance.now(), genTokens = 0, ctxTokens = await engine.countTokens(transcript);
73
- const ctl = new AbortController(); ui.stop.onclick = () => { aborted = true; ctl.abort(); };
74
- for (;;) {
75
- if (aborted) { status('Stopped.', 0); return; }
76
- step++;
77
- const card = stepCard(step);
78
- status(`Reading the conversation (${ctxTokens.toLocaleString()} tokens)…`, 0);
79
  let raw = '', finish = null, n = 0, tStart = 0, lastUi = 0;
80
- try {
81
- for await (const part of engine.complete(transcript, { maxTokens: Math.min(MAX_NEW, CTX - ctxTokens - 64), signal: ctl.signal })) {
82
- if (part.progress?.total) status(`Reading the conversation… ${Math.round(100 * part.progress.processed / part.progress.total)}%`, part.progress.processed / part.progress.total);
83
- if (part.text) { if (!n) tStart = performance.now(); raw += part.text; n++; }
84
- if (part.finish) finish = part.finish;
85
- const now = performance.now();
86
- if (part.text && now - lastUi > 250) {
87
- lastUi = now; card.think(parseAssistant(raw).thinking);
88
- 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}`);
89
- }
90
  }
91
- } catch (e) { if (aborted) { card.d.remove(); status('Stopped.', 0); return; } throw e; }
92
- genTokens += n;
93
- const parsed = parseAssistant(raw);
94
- card.think(parsed.thinking);
95
- if (!parsed.calls.length || !parsed.finished) { // the model answered (or ran out of room): this is the report
96
- card.d.remove();
97
- const text = parsed.finished ? parsed.content : parsed.thinking;
98
- showAnswer(text.replace(/```json[\s\S]*?```\s*$/, ''), extractAnswer(text));
99
- 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);
100
- return;
101
  }
102
- const outputs = [];
103
- for (const c of parsed.calls) {
104
- const args = typedArgs(c);
105
- if (calls >= MAX_TOOL_CALLS) { outputs.push(`Tool not executed: tool-call budget exhausted. ${FINAL_WARNING}`); continue; }
106
- if (!args) { outputs.push(`Error: invalid call to ${c.name}. Available tools: ${TOOLS.map((t) => t.function.name).join(', ')}.`); continue; }
107
- calls++;
108
- card.set(c.name, c.name === 'search' ? args.query : args.command);
109
- status(`Tool call ${calls}/${MAX_TOOL_CALLS}: ${c.name}…`);
110
- let out = await callTool(c.name, args);
111
- if (calls === MAX_TOOL_CALLS) out += `\n\n${FINAL_WARNING}`;
112
- card.result(out); outputs.push(out);
113
- }
114
- card.d.classList.remove('live'); card.d.open = false;
115
- let next = raw + IM_END + toolTurn(outputs);
116
- let nextTokens = await engine.countTokens(transcript + next);
117
- if (nextTokens > CTX - 1500) { // out of context room: make the model write its report now
118
- next = raw + IM_END + toolTurn(outputs.map(() => `Tool output omitted: the context window is full. ${FINAL_WARNING}`));
119
- nextTokens = await engine.countTokens(transcript + next);
120
- }
121
- transcript += next; ctxTokens = nextTokens;
122
- await tick();
123
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  }
125
 
126
  // ---------------------------------------------------------------- UI
 
1
  import { createEngine } from './engine.js';
2
+ import { search, webterminal, setSignal } from './tools.js';
3
+ import { TOOLS, MAX_TOOL_CALLS, FINAL_WARNING, firstPrompt, toolTurn, parseAssistant, typedArgs, extractAnswer, extractionPrompt, parseExtraction, EXTRACT_SAMPLING } from './agent.js';
4
 
5
  const q = new URLSearchParams(location.search);
6
  const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null); // test hooks accept same-origin paths only
 
9
  const GGUF_BYTES = 2736583872;
10
  const USE_GPU = q.get('gpu') !== '0';
11
  const IM_END = '<|im_end|>';
12
+ 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)
13
+ const LEAD_IN = 'Based on the sources I read, here is my final answer.\n\n';
14
+ 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)
15
  const EXAMPLES = [
16
  ['Who wrote the music for the 2017 Argentine film "Desire", and where was that composer born?', 'film composer'],
17
  ['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'],
 
41
  onStatus: (t) => status(t) });
42
  status('Model ready.', 1);
43
  return { engine, system };
44
+ })().catch((e) => { enginePromise = null; throw e; }));
45
 
46
  // ---------------------------------------------------------------- transcript
47
  function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }
 
56
  // (the card is closed by the research loop once its tool result is in)
57
  }
58
 
59
+ // Text with clickable links, built from text nodes and <a> elements only (never innerHTML).
60
+ function linkify(node, text) {
61
+ node.replaceChildren(); let last = 0;
62
+ for (const m of text.matchAll(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s<>)\]"']+[^\s<>)\]"'.,;:!?])/g)) {
63
+ node.append(text.slice(last, m.index));
64
+ const a = el('a', '', m[1] || m[3]); a.href = m[2] || m[3]; a.target = '_blank'; a.rel = 'noopener noreferrer'; node.append(a);
65
+ last = m.index + m[0].length;
66
+ }
67
+ node.append(text.slice(last));
68
+ }
69
  function showAnswer(text, short) {
70
+ ui.answer.hidden = false; ui.short.textContent = short || ''; linkify(ui.report, text.trim());
71
  }
72
 
73
  // ---------------------------------------------------------------- tools (run in this page: tools.js)
74
+ async function callTool(name, args, signal) {
75
+ setSignal(signal);
76
+ try { return name === 'search' ? await search(args.query) : await webterminal(args.command); }
77
+ catch (e) { if (e?.name === 'AbortError') throw e; return `Error: the tool failed (${e?.message || e}).`; }
78
  }
79
 
80
  // ---------------------------------------------------------------- the research loop
81
  async function research(question) {
82
  aborted = false;
83
  ui.answer.hidden = true; ui.trail.replaceChildren();
84
+ const ctl = new AbortController(); ui.stop.onclick = () => { aborted = true; ctl.abort(); }; // Stop works during the download, a generation and a tool call
85
  const { engine, system } = await loadEngine();
86
+ if (aborted) { status('Stopped.', 0); return; }
87
+ const nCtx = Math.min(CTX, engine.nCtx || CTX), RESERVE = Math.min(6000, Math.floor(nCtx * 0.2)); // room kept free for the final report
88
+ let transcript = firstPrompt(system, question), calls = 0, step = 0, t0 = performance.now(), genTokens = 0, ctxTokens = await engine.countTokens(transcript), wrapUp = false;
89
+
90
+ // One streamed generation from `prompt` into `card`; returns the raw text and how it ended.
91
+ async function generate(prompt, card, sampling) {
 
92
  let raw = '', finish = null, n = 0, tStart = 0, lastUi = 0;
93
+ const used = prompt === transcript ? ctxTokens : await engine.countTokens(prompt), room = nCtx - used - 64;
94
+ if (room < 128) return { raw: '', finish: 'length', n: 0 };
95
+ for await (const part of engine.complete(prompt, { maxTokens: Math.min(MAX_NEW, room), signal: ctl.signal, sampling })) {
96
+ if (part.progress?.total) status(`Reading the conversation… ${Math.round(100 * part.progress.processed / part.progress.total)}%`, part.progress.processed / part.progress.total);
97
+ if (part.text) { if (!n) tStart = performance.now(); raw += part.text; n++; }
98
+ if (part.finish) finish = part.finish;
99
+ const now = performance.now();
100
+ if (part.text && now - lastUi > 250) {
101
+ lastUi = now; card.think(parseAssistant(raw).thinking);
102
+ 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}`);
103
  }
 
 
 
 
 
 
 
 
 
 
104
  }
105
+ genTokens += n;
106
+ return { raw, finish, n };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  }
108
+
109
+ try {
110
+ let final = null; // the report text once the model has written it
111
+ for (;;) {
112
+ step++;
113
+ const card = stepCard(step);
114
+ status(`Reading the conversation (${ctxTokens.toLocaleString()} tokens)…`, 0);
115
+ const { raw } = await generate(transcript, card);
116
+ const parsed = parseAssistant(raw);
117
+ card.think(parsed.thinking);
118
+ 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 warning
119
+ if (parsed.finished && !parsed.calls.length) final = parsed.content || parsed.thinking;
120
+ else { // close the thinking ourselves and make it write the report (no more tools)
121
+ status('Asking the model for its final report…');
122
+ 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 tool
123
+ final = more.raw.split('<tool_call>')[0].replace(/<\/think>/g, '').trim() || parsed.thinking;
124
+ }
125
+ }
126
+ if (final !== null) {
127
+ card.d.remove();
128
+ if (!final.trim()) final = 'The model ran out of room before it could write a report. Try a narrower question.';
129
+ const volunteered = extractAnswer(final), report = final.replace(volunteered ? /```json[\s\S]*?```\s*$/ : /$^/, '');
130
+ showAnswer(report, volunteered || '');
131
+ status(`Done in ${Math.round((performance.now() - t0) / 1000)} s · ${calls} tool calls · ${genTokens.toLocaleString()} tokens generated. Extracting the short answer…`, 1);
132
+ if (!volunteered && report.trim()) { // the extraction step of Ai2's grader, on the report
133
+ try {
134
+ 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;
135
+ const short = parseExtraction(out); if (short) ui.short.textContent = short;
136
+ } catch { /* the report alone is fine */ }
137
+ }
138
+ status(`Done in ${Math.round((performance.now() - t0) / 1000)} s · ${calls} tool calls · ${genTokens.toLocaleString()} tokens generated.`, 1);
139
+ return;
140
+ }
141
+ const outputs = [];
142
+ for (const c of parsed.calls) {
143
+ const args = typedArgs(c);
144
+ if (calls >= MAX_TOOL_CALLS) { outputs.push(`Tool not executed: tool-call budget exhausted. ${FINAL_WARNING}`); wrapUp = true; continue; }
145
+ if (!args) { outputs.push(`Error: invalid call to ${c.name}. Available tools: ${TOOLS.map((t) => t.function.name).join(', ')}.`); continue; }
146
+ calls++;
147
+ card.set(c.name, c.name === 'search' ? args.query : args.command);
148
+ status(`Tool call ${calls}/${MAX_TOOL_CALLS}: ${c.name}…`);
149
+ let out = await callTool(c.name, args, ctl.signal);
150
+ if (calls === MAX_TOOL_CALLS) { out += `\n\n${FINAL_WARNING}`; wrapUp = true; }
151
+ card.result(out); outputs.push(out);
152
+ }
153
+ card.d.classList.remove('live'); card.d.open = false;
154
+ let next = raw + IM_END + toolTurn(outputs);
155
+ let nextTokens = await engine.countTokens(transcript + next);
156
+ if (!wrapUp && nextTokens > nCtx * 0.8) { // upstream's token-budget warning, at 80% of what fits here
157
+ outputs[outputs.length - 1] += `\n\n${CONTEXT_WARNING}`; wrapUp = true;
158
+ next = raw + IM_END + toolTurn(outputs); nextTokens = await engine.countTokens(transcript + next);
159
+ }
160
+ if (nextTokens > nCtx - RESERVE) { // still too big: keep the model's turn, drop the tool text, and make it write the report
161
+ wrapUp = true;
162
+ next = raw + IM_END + toolTurn(outputs.map(() => `Tool output omitted: the context window is full. ${FINAL_WARNING}`));
163
+ nextTokens = await engine.countTokens(transcript + next);
164
+ }
165
+ transcript += next; ctxTokens = nextTokens;
166
+ await tick();
167
+ }
168
+ } catch (e) { if (aborted || e?.name === 'AbortError') { status('Stopped.', 0); return; } throw e; }
169
  }
170
 
171
  // ---------------------------------------------------------------- UI
termworker.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ // Runs the webterminal filters (tools.js runPipeline) off the main thread so a runaway regex can be terminated.
2
+ import { runPipeline, RegexError } from './tools.js';
3
+ onmessage = ({ data }) => {
4
+ try { postMessage({ ok: true, text: runPipeline(data.stages, data.text) }); }
5
+ catch (e) { postMessage({ ok: false, message: e.message, regex: e instanceof RegexError }); }
6
+ };
tools.js CHANGED
@@ -6,27 +6,34 @@
6
  // JavaScript and passes most bot walls), search results are Brave Search read the same way, with Wikipedia / OpenAlex
7
  // (both CORS-enabled APIs) as fallbacks. No backend, no keys.
8
 
 
 
9
  export const MAX_OUTPUT = 10_000; // the model is told terminal output is capped at 10,000 characters
10
  const READER = 'https://r.jina.ai/';
11
  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;
12
 
13
  // ------------------------------------------------------------------------------------------ network (rate-limited)
14
- let chain = Promise.resolve(), lastCall = 0;
 
 
 
15
  const MIN_GAP = 3100; // Jina's anonymous tier allows ~20 requests/minute per IP
16
  function paced(fn) {
17
- 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(); });
18
  chain = run.catch(() => {});
19
  return run;
20
  }
21
  async function getText(url, { reader = false, timeout = 30000, headers = {} } = {}) {
22
  for (let attempt = 0; attempt < 3; attempt++) {
23
- const ctl = new AbortController(), t = setTimeout(() => ctl.abort(), timeout);
 
 
24
  try {
25
  const run = reader ? paced : (f) => f();
26
  const r = await run(() => fetch(reader ? READER + url : url, { signal: ctl.signal, headers }));
27
- if (r.status === 429 && attempt < 2) { await new Promise((x) => setTimeout(x, 4000 * (attempt + 1))); continue; }
28
  return { status: r.status, text: await r.text() };
29
- } finally { clearTimeout(t); }
30
  }
31
  return { status: 429, text: '' };
32
  }
@@ -36,7 +43,8 @@ export function checkUrl(u) {
36
  let p; try { p = new URL(u.trim()); } catch { throw new CmdError('not a valid URL'); }
37
  if (!/^https?:$/.test(p.protocol)) throw new CmdError('only http(s) URLs can be opened');
38
  const h = p.hostname.toLowerCase();
39
- if (h === 'localhost' || /\.(local|internal|localhost)$/.test(h) || /^[\d.]+$/.test(h) || h.includes(':')) throw new CmdError('that host is not public');
 
40
  return p.href;
41
  }
42
  const pageCache = new Map();
@@ -118,61 +126,115 @@ async function openalex(q, n) {
118
  return { title: `${w.title} (${w.publication_year})`, body: words.filter(Boolean).join(' ').slice(0, 400), href: w.doi || w.primary_location?.landing_page_url || '' };
119
  });
120
  }
121
- export async function search(query, numResults = 10) {
122
- query = (query || '').trim(); const n = Math.max(1, Math.min(parseInt(numResults, 10) || 10, 10));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  if (!query) return 'Error: query is empty.';
124
- const key = query.toLowerCase() + '|' + n; let rows = searchCache.get(key);
125
  if (!rows) {
126
  rows = [];
127
- for (const f of [() => braveSearch(query), () => wikipedia(query, n), () => openalex(query, n)]) {
128
- try { rows = (await f()).filter((r) => r.href); } catch { /* next engine */ }
129
  if (rows.length) break;
130
  }
131
  if (!rows.length) return `No results for "${query}" (the search engines did not answer). Try a different query.`;
132
  searchCache.set(key, rows); if (searchCache.size > 200) searchCache.delete(searchCache.keys().next().value);
133
  }
134
- return rows.slice(0, n).map((r) => [`**${r.title.trim() || 'Untitled result'}**`, r.body, `Source: ${r.href}`].filter(Boolean).join('\n')).join('\n\n');
 
135
  }
136
 
137
  // ------------------------------------------------------------------------------------------ terminal pipeline
138
  export class CmdError extends Error {}
 
139
  const lines = (t) => (t.endsWith('\n') ? t.slice(0, -1).split('\n') : t ? t.split('\n') : []);
140
  const nl = (ls) => ls.map((l) => l + '\n').join('');
141
  const int = (v, what) => { if (!/^[+-]?\d+$/.test(v)) throw new CmdError(`invalid ${what}: '${v}'`); return parseInt(v, 10); };
142
  const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  function cmdHeadTail(name, args, text) {
145
- let n = 10, bytes = false;
 
146
  for (let i = 0; i < args.length; i++) {
147
  const a = args[i]; let m;
148
  if (/^-\d+$/.test(a)) n = int(a.slice(1), 'count');
149
- 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'; }
150
- else if ((m = a.match(/^-([nc])([+-]?\d+)$/))) { n = int(m[2].replace(/^\+/, ''), 'count'); bytes = m[1] === 'c'; }
151
  else throw new CmdError(`${name} only supports line or byte counts with stdin`);
152
  }
153
- 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)); }
154
- const ls = lines(text), sel = name === 'head' ? ls.slice(0, n) : n ? ls.slice(-n) : [];
 
155
  return sel.length ? nl(sel) : '';
156
  }
157
 
158
  function cmdGrep(name, args, text) {
159
- 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;
160
- const pats = [];
 
161
  for (let i = 0; i < args.length;) {
162
  let a = args[i++];
163
  if (a === '--') { if (!pats.length && i < args.length) pats.push(args[i]); break; }
164
  if (a.startsWith('--')) {
165
- 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' };
166
- if (map[a]) a = '-' + map[a];
167
- else if (a.startsWith('--max-count=')) { maxc = int(a.split('=')[1], 'count'); continue; }
168
- 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; }
169
- else if (['--no-heading', '--color=never', '--with-filename', '--no-filename'].includes(a)) continue;
170
  else throw new CmdError(`${name}: unsupported option ${a}`);
171
  }
172
  if (a.startsWith('-') && a.length > 1) {
173
  for (let j = 1; j < a.length;) {
174
  const c = a[j++];
175
- if ('NHhEPIas'.includes(c)) continue;
 
176
  else if (c === 'i') ci = true; else if (c === 'n') showN = true; else if (c === 'F') fixed = true; else if (c === 'v') invert = true;
177
  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;
178
  else if ('ABCme'.includes(c)) {
@@ -180,8 +242,7 @@ function cmdGrep(name, args, text) {
180
  if (v === undefined) throw new CmdError(`${name}: option -${c} requires an argument`);
181
  if (j >= a.length) i++;
182
  j = a.length;
183
- if (c === 'e') pats.push(v); else if (c === 'm') maxc = int(v, 'count');
184
- else { const k = int(v, 'context'); if (c === 'A') ctxA = k; else if (c === 'B') ctxB = k; else ctxA = ctxB = k; }
185
  } else throw new CmdError(`${name}: unsupported option -${c}`);
186
  }
187
  continue;
@@ -190,10 +251,7 @@ function cmdGrep(name, args, text) {
190
  }
191
  if (!pats.length) throw new CmdError(`usage: ${name} [options] PATTERN`);
192
  if (smart && !pats.some((p) => /[A-Z]/.test(p))) ci = true;
193
- let srcs = pats.map((p) => (fixed ? esc(p) : p.replace(/\(\?i\)/g, '')));
194
- if (word) srcs = srcs.map((s) => `\\b(?:${s})\\b`);
195
- if (lineX) srcs = srcs.map((s) => `^(?:${s})$`);
196
- 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}`); } }
197
  const ls = lines(text), hit = ls.map((l) => rx.test(l) !== invert);
198
  if (maxc !== null) { let seen = 0; hit.forEach((h, k) => { if (h && ++seen > maxc) hit[k] = false; }); }
199
  if (count) return `${hit.filter(Boolean).length}\n`;
@@ -212,72 +270,185 @@ function cmdGrep(name, args, text) {
212
  return nl(out);
213
  }
214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  function cmdSed(args, text) {
216
- let quiet = false; const scripts = [];
217
  for (let i = 0; i < args.length;) {
218
  const a = args[i++];
219
  if (['-n', '--quiet', '--silent'].includes(a)) quiet = true;
 
220
  else if (a === '-e' || a === '--expression') { if (i >= args.length) throw new CmdError('sed: -e requires a script'); scripts.push(args[i++]); }
 
221
  else if (a.startsWith('-') && a.length > 1) throw new CmdError(`sed: unsupported option ${a}`);
222
  else scripts.push(a);
223
  }
224
- if (scripts.length !== 1) throw new CmdError('sed supports one script: N,Mp N,Md /re/p /re/d s/a/b/[gi]');
225
- const s = scripts[0].trim(), ls = lines(text);
226
- 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); };
227
- let m = s.match(/^(\d+|\$)?(?:,(\d+|\$))?\s*(!?)(p|d)$/);
228
- if (m && (m[1] || m[2] === undefined)) {
229
- 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;
230
- return emit(ls.map((_, k) => (lo <= k + 1 && k + 1 <= hi) !== !!m[3]), m[4]);
231
- }
232
- 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]); }
233
- if ((m = s.match(/^s(.)(.+?)(?<!\\)\1(.*?)(?<!\\)\1([gi]*)$/))) {
234
- 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}`); }
235
- const rep = m[3].replace(/\$/g, '$$$$').replace(/&/g, '$&').replace(/\\(\d)/g, '$$$1');
236
- return quiet ? '' : nl(ls.map((l) => l.replace(rx, rep)));
 
 
 
 
 
 
 
 
237
  }
238
- throw new CmdError('unsupported sed script');
239
  }
240
 
241
  function cmdWc(args, text) {
242
- const sel = args.filter((a) => ['-l', '-w', '-c', '-m'].includes(a));
243
- if (sel.length !== args.length) throw new CmdError('wc supports -l -w -c -m');
244
- const v = { '-l': lines(text).length, '-w': text.split(/\s+/).filter(Boolean).length, '-c': new TextEncoder().encode(text).length, '-m': [...text].length };
245
- return (sel.length ? sel : ['-l', '-w', '-c']).map((a) => v[a]).join(' ') + '\n';
 
246
  }
247
  function cmdSort(args, text) {
248
- let rev = false, uniq = false, num = false;
249
- 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'); }
 
 
 
250
  let ls = lines(text);
251
- const key = (l) => { const m = l.match(/^\s*-?\d+(\.\d+)?/); return m ? parseFloat(m[0]) : 0; };
252
- ls.sort((a, b) => (num ? key(a) - key(b) || (a < b ? -1 : a > b ? 1 : 0) : a < b ? -1 : a > b ? 1 : 0));
253
- if (rev) ls.reverse();
254
- if (uniq) ls = [...new Set(ls)];
255
  return nl(ls);
256
  }
257
  function cmdUniq(args, text) {
258
- if (args.some((a) => a !== '-c')) throw new CmdError('uniq supports -c');
259
- const c = args.includes('-c'), out = []; let prev = null, n = 0;
260
- for (const l of [...lines(text), null]) {
261
- if (l === prev) { n++; continue; }
262
- if (prev !== null) out.push(c ? String(n).padStart(7) + ' ' + prev : prev);
263
- prev = l; n = 1;
264
- }
265
  return nl(out);
266
  }
 
 
 
 
 
 
 
 
267
  function cmdCut(args, text) {
268
- let d = '\t', f = null;
269
  for (let i = 0; i < args.length;) {
270
  const a = args[i++];
271
  if (a === '-d' && i < args.length) d = args[i++]; else if (a.startsWith('-d') && a.length > 2) d = a.slice(2);
272
  else if (a === '-f' && i < args.length) f = args[i++]; else if (a.startsWith('-f') && a.length > 2) f = a.slice(2);
273
- else throw new CmdError('cut supports -d and -f');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  }
275
- if (!f) throw new CmdError('cut: need -f');
276
- const idx = [];
277
- 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)); }
278
- 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); }));
 
 
279
  }
280
 
 
281
  export function runStage(argv, text) {
282
  const [name, ...args] = argv;
283
  if (name === 'head' || name === 'tail') return cmdHeadTail(name, args, text);
@@ -287,14 +458,19 @@ export function runStage(argv, text) {
287
  if (name === 'sort') return cmdSort(args, text);
288
  if (name === 'uniq') return cmdUniq(args, text);
289
  if (name === 'cut') return cmdCut(args, text);
 
 
290
  if (name === 'cat' && !args.length) return text;
291
- throw new CmdError(`command not available: ${name} (use head, tail, rg, grep, sed, wc, sort, uniq, cut)`);
292
  }
 
293
 
294
  // POSIX-ish word splitting: whitespace separates, '...' is literal, "..." honours \" and \\, a bare \ escapes the next character.
295
  // Splits on standalone `|`. No shell: `( ) ; &` inside a word are literal (a Wikipedia URL may contain parentheses); bare operators are refused.
 
296
  export function splitPipeline(command) {
297
  if (/[\n\r\0]/.test(command)) throw new CmdError('the command must be a single line');
 
298
  const toks = []; let cur = '', has = false, i = 0;
299
  const push = () => { if (has) toks.push(cur); cur = ''; has = false; };
300
  while (i < command.length) {
@@ -324,17 +500,46 @@ export function splitPipeline(command) {
324
  return [...stages, st];
325
  }
326
 
327
- export const truncate = (t) => (t.length <= MAX_OUTPUT ? t : t.slice(0, MAX_OUTPUT) + `\n...[output truncated at ${MAX_OUTPUT} characters]`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
 
 
 
 
 
 
 
 
 
329
  export async function webterminal(command) {
 
 
330
  command = (command || '').trim();
331
  try {
332
  const stages = splitPipeline(command);
333
- 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');
334
- let text = await fetchPage(stages[0][1]);
335
- for (const st of stages.slice(1)) text = runStage(st, text);
336
- return text.trim() ? truncate(text) : '(no output)';
 
 
 
 
337
  } catch (e) {
338
- return e instanceof CmdError ? `error: ${e.message}` : `error: could not open the page (${e?.name || 'Error'})`;
 
339
  }
340
  }
 
6
  // JavaScript and passes most bot walls), search results are Brave Search read the same way, with Wikipedia / OpenAlex
7
  // (both CORS-enabled APIs) as fallbacks. No backend, no keys.
8
 
9
+ import { pyJson } from './agent.js';
10
+
11
  export const MAX_OUTPUT = 10_000; // the model is told terminal output is capped at 10,000 characters
12
  const READER = 'https://r.jina.ai/';
13
  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;
14
 
15
  // ------------------------------------------------------------------------------------------ network (rate-limited)
16
+ let chain = Promise.resolve(), lastCall = 0, outer = null;
17
+ export const setSignal = (sig) => { outer = sig; }; // the page's Stop button aborts whatever tool call is running
18
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
19
+ const stopped = () => { if (outer?.aborted) throw new DOMException('Stopped', 'AbortError'); };
20
  const MIN_GAP = 3100; // Jina's anonymous tier allows ~20 requests/minute per IP
21
  function paced(fn) {
22
+ const run = chain.then(async () => { const wait = lastCall + MIN_GAP - Date.now(); if (wait > 0) await sleep(wait); stopped(); lastCall = Date.now(); return fn(); });
23
  chain = run.catch(() => {});
24
  return run;
25
  }
26
  async function getText(url, { reader = false, timeout = 30000, headers = {} } = {}) {
27
  for (let attempt = 0; attempt < 3; attempt++) {
28
+ stopped();
29
+ const ctl = new AbortController(), t = setTimeout(() => ctl.abort(), timeout), onStop = () => ctl.abort();
30
+ outer?.addEventListener('abort', onStop, { once: true });
31
  try {
32
  const run = reader ? paced : (f) => f();
33
  const r = await run(() => fetch(reader ? READER + url : url, { signal: ctl.signal, headers }));
34
+ if (r.status === 429 && attempt < 2) { await sleep(4000 * (attempt + 1)); continue; }
35
  return { status: r.status, text: await r.text() };
36
+ } finally { clearTimeout(t); outer?.removeEventListener('abort', onStop); }
37
  }
38
  return { status: 429, text: '' };
39
  }
 
43
  let p; try { p = new URL(u.trim()); } catch { throw new CmdError('not a valid URL'); }
44
  if (!/^https?:$/.test(p.protocol)) throw new CmdError('only http(s) URLs can be opened');
45
  const h = p.hostname.toLowerCase();
46
+ if (h === 'localhost' || h.endsWith('.') || /\.(local|internal|localhost)$/.test(h) || /^[\d.]+$/.test(h) || h.includes(':')) throw new CmdError('that host is not public');
47
+ if (/(^|\.)(huggingface\.co|hf\.co)$/.test(h)) throw new CmdError('that domain is not available to this tool');
48
  return p.href;
49
  }
50
  const pageCache = new Map();
 
126
  return { title: `${w.title} (${w.publication_year})`, body: words.filter(Boolean).join(' ').slice(0, 400), href: w.doi || w.primary_location?.landing_page_url || '' };
127
  });
128
  }
129
+ const blocked = (u) => { try { return /(^|\.)(huggingface\.co|hf\.co)$/.test(new URL(u).hostname); } catch { return true; } };
130
+ 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);
131
+
132
+ // DuckDuckGo's HTML results, as Jina renders them: "## [title](https://duckduckgo.com/l/?uddg=<real url>&rut=…)" then a snippet link.
133
+ export function parseDdg(md) {
134
+ const body = md.split('Markdown Content:')[1] || md, rows = [];
135
+ for (const block of body.split(/\n(?=## \[)/).slice(1)) {
136
+ const m = block.match(/^## \[([^\]]+)\]\(https:\/\/duckduckgo\.com\/l\/\?uddg=([^&)]+)/);
137
+ if (!m) continue;
138
+ let href; try { href = decodeURIComponent(m[2]); } catch { continue; }
139
+ const sn = block.split('\n').slice(1).map((l) => l.trim()).find((l) => /^\[(?!!\[)/.test(l) && l.includes('](https://duckduckgo.com/l/'));
140
+ const snippet = sn ? sn.slice(1, sn.lastIndexOf('](https://duckduckgo.com/l/')) : '';
141
+ rows.push({ title: m[1].replace(/\*\*/g, ''), body: snippet, href });
142
+ }
143
+ return rows;
144
+ }
145
+ async function ddgSearch(q) {
146
+ const r = await getText(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`, { reader: true, timeout: 45000 });
147
+ if (r.status >= 400) throw new Error(`ddg ${r.status}`);
148
+ return parseDdg(r.text);
149
+ }
150
+ export async function search(query) {
151
+ query = (query || '').trim(); const n = 10;
152
  if (!query) return 'Error: query is empty.';
153
+ const key = query.toLowerCase(); let rows = searchCache.get(key), repeat = !!rows;
154
  if (!rows) {
155
  rows = [];
156
+ for (const f of [() => ddgSearch(query), () => braveSearch(query), () => wikipedia(query, n), () => openalex(query, n)]) {
157
+ try { rows = (await f()).filter((r) => r.href && !blocked(r.href)); } catch (e) { if (e?.name === 'AbortError') throw e; }
158
  if (rows.length) break;
159
  }
160
  if (!rows.length) return `No results for "${query}" (the search engines did not answer). Try a different query.`;
161
  searchCache.set(key, rows); if (searchCache.size > 200) searchCache.delete(searchCache.keys().next().value);
162
  }
163
+ 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');
164
+ 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;
165
  }
166
 
167
  // ------------------------------------------------------------------------------------------ terminal pipeline
168
  export class CmdError extends Error {}
169
+ export class RegexError extends CmdError {}
170
  const lines = (t) => (t.endsWith('\n') ? t.slice(0, -1).split('\n') : t ? t.split('\n') : []);
171
  const nl = (ls) => ls.map((l) => l + '\n').join('');
172
  const int = (v, what) => { if (!/^[+-]?\d+$/.test(v)) throw new CmdError(`invalid ${what}: '${v}'`); return parseInt(v, 10); };
173
  const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
174
+ 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' };
175
+ const posix = (s) => s.replace(/\[:([a-z]+):\]/g, (m, c) => CLASSES[c] ?? m);
176
+
177
+ // Basic regular expressions (grep and sed without -E) to JavaScript syntax: \( \) \| \{ \} \+ \? are operators, bare ( ) | { } + ? are literals.
178
+ function breToJs(s) {
179
+ let out = '', i = 0;
180
+ while (i < s.length) {
181
+ const c = s[i];
182
+ if (c === '[') { // bracket expression: copied as is
183
+ let j = i + 1; if (s[j] === '^') j++; if (s[j] === ']') j++;
184
+ 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++; }
185
+ out += s.slice(i, j + 1); i = j + 1;
186
+ } else if (c === '\\' && i + 1 < s.length) {
187
+ const d = s[i + 1];
188
+ out += '(){}|+?'.includes(d) ? d : '\\' + d; i += 2;
189
+ } else { out += '(){}|+?'.includes(c) ? '\\' + c : c; i++; }
190
+ }
191
+ return out;
192
+ }
193
+ function compile(sources, { ci = false, bre = false, fixed = false, word = false, lineX = false, flags = '' } = {}) {
194
+ 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); });
195
+ if (word) srcs = srcs.map((s) => `\\b(?:${s})\\b`);
196
+ if (lineX) srcs = srcs.map((s) => `^(?:${s})$`);
197
+ const src = srcs.map((s) => `(?:${s})`).join('|'), f = (ci ? 'i' : '') + flags;
198
+ try { return new RegExp(src, f + 'u'); } catch { /* not valid in unicode mode (e.g. a stray escape): retry leniently */ }
199
+ try { return new RegExp(src, f); } catch (e) { throw new RegexError(`invalid regex: ${e.message}`); }
200
+ }
201
 
202
  function cmdHeadTail(name, args, text) {
203
+ let n = 10, plus = false, minus = false, bytes = false;
204
+ const setN = (raw) => { plus = raw.startsWith('+'); minus = raw.startsWith('-'); n = Math.abs(int(raw, 'count')); };
205
  for (let i = 0; i < args.length; i++) {
206
  const a = args[i]; let m;
207
  if (/^-\d+$/.test(a)) n = int(a.slice(1), 'count');
208
+ 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'; }
209
+ else if ((m = a.match(/^-([nc])([+-]?\d+)$/))) { setN(m[2]); bytes = m[1] === 'c'; }
210
  else throw new CmdError(`${name} only supports line or byte counts with stdin`);
211
  }
212
+ 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); }
213
+ const ls = lines(text);
214
+ 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) : [];
215
  return sel.length ? nl(sel) : '';
216
  }
217
 
218
  function cmdGrep(name, args, text) {
219
+ 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';
220
+ const pats = [], sep = { '--after-context': 'A', '--before-context': 'B', '--context': 'C', '--max-count': 'm' };
221
+ const setCtx = (k, v) => { if (k === 'A') ctxA = v; else if (k === 'B') ctxB = v; else ctxA = ctxB = v; };
222
  for (let i = 0; i < args.length;) {
223
  let a = args[i++];
224
  if (a === '--') { if (!pats.length && i < args.length) pats.push(args[i]); break; }
225
  if (a.startsWith('--')) {
226
+ 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': '' };
227
+ if (a in map) { if (!map[a]) { ci = false; continue; } a = '-' + map[a]; }
228
+ 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; }
229
+ 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; }
230
+ else if (['--no-heading', '--color=never', '--with-filename', '--no-filename', '--no-line-number', '--text', '--no-messages'].includes(a)) continue;
231
  else throw new CmdError(`${name}: unsupported option ${a}`);
232
  }
233
  if (a.startsWith('-') && a.length > 1) {
234
  for (let j = 1; j < a.length;) {
235
  const c = a[j++];
236
+ if ('NHhPIasU'.includes(c)) continue;
237
+ else if (c === 'E') ere = true; else if (c === 'G') ere = false;
238
  else if (c === 'i') ci = true; else if (c === 'n') showN = true; else if (c === 'F') fixed = true; else if (c === 'v') invert = true;
239
  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;
240
  else if ('ABCme'.includes(c)) {
 
242
  if (v === undefined) throw new CmdError(`${name}: option -${c} requires an argument`);
243
  if (j >= a.length) i++;
244
  j = a.length;
245
+ if (c === 'e') pats.push(v); else if (c === 'm') maxc = int(v, 'count'); else setCtx(c, int(v, 'context'));
 
246
  } else throw new CmdError(`${name}: unsupported option -${c}`);
247
  }
248
  continue;
 
251
  }
252
  if (!pats.length) throw new CmdError(`usage: ${name} [options] PATTERN`);
253
  if (smart && !pats.some((p) => /[A-Z]/.test(p))) ci = true;
254
+ const rx = compile(pats, { ci, bre: !ere && !fixed, fixed, word, lineX });
 
 
 
255
  const ls = lines(text), hit = ls.map((l) => rx.test(l) !== invert);
256
  if (maxc !== null) { let seen = 0; hit.forEach((h, k) => { if (h && ++seen > maxc) hit[k] = false; }); }
257
  if (count) return `${hit.filter(Boolean).length}\n`;
 
270
  return nl(out);
271
  }
272
 
273
+ // ---- sed: addresses (N, $, /re/, a,b ranges, !), commands p d q s (flags g p i, N), several commands separated by ; or newline or -e
274
+ function parseSed(script, ere) {
275
+ const cmds = []; let i = 0;
276
+ const readDelimited = (d) => {
277
+ let out = '';
278
+ for (; i < script.length; i++) {
279
+ const c = script[i];
280
+ if (c === '\\' && i + 1 < script.length) { out += script[i + 1] === d ? d : c + script[i + 1]; i++; }
281
+ else if (c === d) { i++; return out; }
282
+ else out += c;
283
+ }
284
+ throw new CmdError('sed: unterminated address or s command');
285
+ };
286
+ const addr = () => {
287
+ 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 }; }
288
+ if (script[i] === '$') { i++; return { last: true }; }
289
+ if (script[i] === '/') { i++; return { re: compile([readDelimited('/')], { bre: !ere }) }; }
290
+ return null;
291
+ };
292
+ const ws = () => { while (i < script.length && /[\s;]/.test(script[i])) i++; };
293
+ for (ws(); i < script.length; ws()) {
294
+ const a1 = addr(); let a2 = null, neg = false;
295
+ if (a1 && script[i] === ',') { i++; a2 = addr(); if (!a2) throw new CmdError('sed: bad second address'); }
296
+ while (script[i] === ' ') i++;
297
+ if (script[i] === '!') { neg = true; i++; while (script[i] === ' ') i++; }
298
+ const c = script[i++];
299
+ if (c === 'p' || c === 'd') cmds.push({ a1, a2, neg, cmd: c });
300
+ else if (c === 'q') { while (/\d/.test(script[i] || '')) i++; cmds.push({ a1, a2, neg, cmd: 'q' }); }
301
+ else if (c === 's') {
302
+ const d = script[i++]; if (!d || /[\s\\]/.test(d)) throw new CmdError('sed: bad s command');
303
+ const pat = readDelimited(d), rep = readDelimited(d); let f = '';
304
+ while (i < script.length && /[gpiI0-9]/.test(script[i])) f += script[i++];
305
+ const parts = []; let lit = '';
306
+ for (let k = 0; k < rep.length; k++) {
307
+ const ch = rep[k];
308
+ 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; }
309
+ else if (ch === '&') { parts.push(lit, 0); lit = ''; } else lit += ch;
310
+ }
311
+ parts.push(lit);
312
+ 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) });
313
+ } else throw new CmdError(`sed: unsupported command '${c ?? ''}' (supported: p d q s, with addresses N $ /re/ and ranges)`);
314
+ }
315
+ if (!cmds.length) throw new CmdError('sed: no script');
316
+ return cmds;
317
+ }
318
+ function substitute(line, c) {
319
+ const g = new RegExp(c.rx.source, c.rx.flags.replace('g', '') + 'g'); let out = '', last = 0, count = 0, did = false, m;
320
+ while ((m = g.exec(line))) {
321
+ count++;
322
+ if (!c.nth || count === c.nth) {
323
+ 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;
324
+ if (!c.g) break;
325
+ }
326
+ if (m[0] === '') g.lastIndex++;
327
+ }
328
+ return { text: did ? out + line.slice(last) : line, did };
329
+ }
330
  function cmdSed(args, text) {
331
+ let quiet = false, ere = false; const scripts = [];
332
  for (let i = 0; i < args.length;) {
333
  const a = args[i++];
334
  if (['-n', '--quiet', '--silent'].includes(a)) quiet = true;
335
+ else if (['-E', '-r', '--regexp-extended'].includes(a)) ere = true;
336
  else if (a === '-e' || a === '--expression') { if (i >= args.length) throw new CmdError('sed: -e requires a script'); scripts.push(args[i++]); }
337
+ else if (/^-[nEr]+$/.test(a)) { if (a.includes('n')) quiet = true; if (/[Er]/.test(a)) ere = true; }
338
  else if (a.startsWith('-') && a.length > 1) throw new CmdError(`sed: unsupported option ${a}`);
339
  else scripts.push(a);
340
  }
341
+ if (!scripts.length) throw new CmdError('sed: missing script');
342
+ const cmds = parseSed(scripts.join('\n'), ere), ls = lines(text), out = [], st = cmds.map(() => ({ on: false }));
343
+ const at = (a, num, line) => (a.n !== undefined ? num === a.n : a.last ? num === ls.length : a.re.test(line));
344
+ const picked = (c, k, num, line) => {
345
+ if (!c.a1) return !c.neg;
346
+ let r;
347
+ if (!c.a2) r = at(c.a1, num, line);
348
+ 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; }
349
+ 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); }
350
+ else r = false;
351
+ return r !== c.neg;
352
+ };
353
+ let quit = false;
354
+ for (let ln = 0; ln < ls.length && !quit; ln++) {
355
+ let ps = ls[ln], deleted = false;
356
+ for (let k = 0; k < cmds.length && !deleted; k++) {
357
+ const c = cmds[k]; if (!picked(c, k, ln + 1, ps)) continue;
358
+ if (c.cmd === 'p') out.push(ps); else if (c.cmd === 'd') deleted = true; else if (c.cmd === 'q') { quit = true; break; }
359
+ else { const r = substitute(ps, c); ps = r.text; if (r.did && c.p) out.push(ps); }
360
+ }
361
+ if (!deleted && !quiet) out.push(ps);
362
  }
363
+ return nl(out);
364
  }
365
 
366
  function cmdWc(args, text) {
367
+ const sel = [];
368
+ 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); }
369
+ 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)) };
370
+ const order = ['-l', '-w', '-m', '-c', '-L'], want = sel.length ? order.filter((o) => sel.includes(o)) : ['-l', '-w', '-c'];
371
+ return want.map((a) => (want.length > 1 ? String(v[a]).padStart(7) : v[a])).join(' ') + '\n';
372
  }
373
  function cmdSort(args, text) {
374
+ let rev = false, uniq = false, num = false, fold = false;
375
+ for (const a of args) {
376
+ if (!/^-[ruCnfbd]+$/.test(a)) throw new CmdError('sort supports -r -u -n -f -b');
377
+ 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; }
378
+ }
379
  let ls = lines(text);
380
+ const key = (l) => { const m = l.match(/^\s*[-+]?\d+(\.\d+)?/); return m ? parseFloat(m[0]) : 0; }, f = (l) => (fold ? l.toLowerCase() : l);
381
+ 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);
382
+ ls.sort(rev ? (a, b) => cmp(b, a) : cmp);
383
+ if (uniq) ls = ls.filter((l, k) => k === 0 || (num ? key(l) !== key(ls[k - 1]) : f(l) !== f(ls[k - 1])));
384
  return nl(ls);
385
  }
386
  function cmdUniq(args, text) {
387
+ let c = false, d = false, u = false;
388
+ 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; } }
389
+ const out = []; let prev = null, n = 0;
390
+ const flush = () => { if (prev === null || (d && n < 2) || (u && n > 1)) return; out.push(c ? String(n).padStart(7) + ' ' + prev : prev); };
391
+ for (const l of lines(text)) { if (l === prev) { n++; continue; } flush(); prev = l; n = 1; }
392
+ flush();
 
393
  return nl(out);
394
  }
395
+ function ranges(spec, what) {
396
+ const r = [];
397
+ for (const part of spec.split(',')) {
398
+ const m = part.match(/^(\d*)(-?)(\d*)$/); if (!m || (!m[1] && !m[3])) throw new CmdError(`cut: invalid ${what} '${part}'`);
399
+ const lo = m[1] ? +m[1] : 1, hi = m[2] ? (m[3] ? +m[3] : Infinity) : lo; r.push([lo, hi]);
400
+ }
401
+ return r;
402
+ }
403
  function cmdCut(args, text) {
404
+ let d = '\t', f = null, c = null, s = false;
405
  for (let i = 0; i < args.length;) {
406
  const a = args[i++];
407
  if (a === '-d' && i < args.length) d = args[i++]; else if (a.startsWith('-d') && a.length > 2) d = a.slice(2);
408
  else if (a === '-f' && i < args.length) f = args[i++]; else if (a.startsWith('-f') && a.length > 2) f = a.slice(2);
409
+ else if ((a === '-c' || a === '-b') && i < args.length) c = args[i++]; else if (/^-[cb]\d/.test(a)) c = a.slice(2);
410
+ else if (a === '-s') s = true;
411
+ else throw new CmdError('cut supports -d -f -c -b -s');
412
+ }
413
+ 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(''))); }
414
+ if (!f) throw new CmdError('cut: you must specify a list of bytes, characters, or fields');
415
+ const R = ranges(f, 'field list');
416
+ 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)]; }));
417
+ }
418
+ function trSet(s) {
419
+ let out = ''; s = s.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\\\/g, '\\');
420
+ const cls = { alpha: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', digit: '0123456789', lower: 'abcdefghijklmnopqrstuvwxyz', upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', space: ' \t\n\r\f\v', punct: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' };
421
+ cls.alnum = cls.alpha + cls.digit;
422
+ for (let i = 0; i < s.length;) {
423
+ const m = s.slice(i).match(/^\[:([a-z]+):\]/);
424
+ if (m && cls[m[1]]) { out += cls[m[1]]; i += m[0].length; }
425
+ 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; }
426
+ else out += s[i++];
427
+ }
428
+ return [...out];
429
+ }
430
+ function cmdTr(args, text) {
431
+ let del = false, squeeze = false; const sets = [];
432
+ 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); }
433
+ if (!sets.length || sets.length > 2 || (!del && !squeeze && sets.length < 2)) throw new CmdError('tr: need SET1 SET2, or -d SET, or -s SET');
434
+ const s1 = trSet(sets[0]), s2 = sets[1] ? trSet(sets[1]) : [];
435
+ let out = '', prev = null;
436
+ for (const ch of text) {
437
+ const k = s1.indexOf(ch); let o = ch, inSet = k >= 0;
438
+ if (inSet && del) continue;
439
+ if (inSet && s2.length) o = s2[Math.min(k, s2.length - 1)];
440
+ if (squeeze && prev === o && (s2.length ? s2.includes(o) : inSet)) continue;
441
+ out += o; prev = o;
442
  }
443
+ return out;
444
+ }
445
+ function cmdNl(args, text) {
446
+ let all = false;
447
+ for (const a of args) { if (a === '-ba') all = true; else if (a !== '-bt') throw new CmdError('nl supports -ba and -bt'); }
448
+ let n = 0; return nl(lines(text).map((l) => (l === '' && !all ? ' ' + l : String(++n).padStart(6) + '\t' + l)));
449
  }
450
 
451
+ export const COMMANDS = new Set(['head', 'tail', 'grep', 'egrep', 'rg', 'sed', 'wc', 'sort', 'uniq', 'cut', 'cat', 'tr', 'nl']);
452
  export function runStage(argv, text) {
453
  const [name, ...args] = argv;
454
  if (name === 'head' || name === 'tail') return cmdHeadTail(name, args, text);
 
458
  if (name === 'sort') return cmdSort(args, text);
459
  if (name === 'uniq') return cmdUniq(args, text);
460
  if (name === 'cut') return cmdCut(args, text);
461
+ if (name === 'tr') return cmdTr(args, text);
462
+ if (name === 'nl') return cmdNl(args, text);
463
  if (name === 'cat' && !args.length) return text;
464
+ throw new CmdError(`command '${name}' is not allowed; supported commands are: ${[...COMMANDS].join(', ')}`);
465
  }
466
+ export const runPipeline = (stages, text) => stages.reduce((t, st) => runStage(st, t), text);
467
 
468
  // POSIX-ish word splitting: whitespace separates, '...' is literal, "..." honours \" and \\, a bare \ escapes the next character.
469
  // Splits on standalone `|`. No shell: `( ) ; &` inside a word are literal (a Wikipedia URL may contain parentheses); bare operators are refused.
470
+ // A trailing `|| true` / `|| :` is accepted (it only hides the exit status; we have none).
471
  export function splitPipeline(command) {
472
  if (/[\n\r\0]/.test(command)) throw new CmdError('the command must be a single line');
473
+ command = command.replace(/\s*\|\|\s*(true|:)\s*$/, '');
474
  const toks = []; let cur = '', has = false, i = 0;
475
  const push = () => { if (has) toks.push(cur); cur = ''; has = false; };
476
  while (i < command.length) {
 
500
  return [...stages, st];
501
  }
502
 
503
+ // Run the filters off the main thread with a hard 5 s limit (upstream's max_runtime): a pathological regex cannot freeze the page.
504
+ function runLimited(stages, text, ms = 5000) {
505
+ const sync = () => { try { return { ok: true, text: runPipeline(stages, text) }; } catch (e) { return { ok: false, message: e.message, regex: e instanceof RegexError }; } };
506
+ if (typeof Worker === 'undefined') return Promise.resolve(sync());
507
+ let w; try { w = new Worker(new URL('./termworker.js', import.meta.url), { type: 'module' }); } catch { return Promise.resolve(sync()); }
508
+ return new Promise((resolve) => {
509
+ const done = (v) => { clearTimeout(t); outer?.removeEventListener('abort', stop); w.terminate(); resolve(v); };
510
+ const stop = () => done({ ok: false, message: 'stopped', stopped: true });
511
+ const t = setTimeout(() => done({ timeout: true }), ms);
512
+ outer?.addEventListener('abort', stop, { once: true });
513
+ w.onmessage = (e) => done(e.data);
514
+ w.onerror = () => done(sync());
515
+ w.postMessage({ stages, text });
516
+ });
517
+ }
518
 
519
+ // What the model sees for a terminal call: the JSON envelope Ai2's tool client builds (literegistry_tool_client/output.py),
520
+ // with stdout capped at 10,000 characters.
521
+ 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 });
522
+ export function truncateStdout(stdout) {
523
+ if (stdout.length <= MAX_OUTPUT) return { stdout, truncated: false, truncated_characters: 0 };
524
+ const missing = stdout.length - MAX_OUTPUT;
525
+ return { stdout: stdout.slice(0, MAX_OUTPUT) + `\n[ truncated (${missing} characters missing) ]`, truncated: true, truncated_characters: missing };
526
+ }
527
  export async function webterminal(command) {
528
+ const t0 = Date.now(), secs = () => +((Date.now() - t0) / 1000).toFixed(4);
529
+ const fail = (msg) => `Terminal execution failed: ${msg}`;
530
  command = (command || '').trim();
531
  try {
532
  const stages = splitPipeline(command);
533
+ 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');
534
+ 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(', ')}`);
535
+ const text = await fetchPage(stages[0][1]);
536
+ const r = await runLimited(stages.slice(1), text);
537
+ stopped();
538
+ if (r.timeout) return envelope({ execution_time: secs(), exit_code: 124, stderr: 'pipeline timed out after 5 seconds', stdout: '', truncated: false, truncated_characters: 0 });
539
+ 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);
540
+ return envelope({ execution_time: secs(), exit_code: 0, stderr: '', ...truncateStdout(r.text) });
541
  } catch (e) {
542
+ if (e?.name === 'AbortError') throw e;
543
+ return e instanceof CmdError ? fail(e.message) : fail(`could not open the page (${e?.name || 'Error'})`);
544
  }
545
  }