Spaces:
Running
Running
DR Tulu 2 WebGPU demo (all in browser)
Browse files- README.md +21 -4
- agent.js +116 -0
- engine.js +41 -0
- index.html +53 -17
- main.js +144 -0
- prompt.json +16 -0
- style.css +50 -23
- tools.js +340 -0
- vendor/wllama/index.js +0 -0
- vendor/wllama/wllama.wasm +3 -0
README.md
CHANGED
|
@@ -1,10 +1,27 @@
|
|
| 1 |
---
|
| 2 |
-
title: DR
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: static
|
|
|
|
| 7 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: DR Tulu 2 WebGPU
|
| 3 |
+
emoji: 🧭
|
| 4 |
+
colorFrom: red
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: static
|
| 7 |
+
app_file: index.html
|
| 8 |
pinned: false
|
| 9 |
+
license: apache-2.0
|
| 10 |
+
short_description: Ai2's 4B deep research agent, running in your browser
|
| 11 |
+
custom_headers:
|
| 12 |
+
cross-origin-embedder-policy: credentialless
|
| 13 |
+
cross-origin-opener-policy: same-origin
|
| 14 |
+
cross-origin-resource-policy: cross-origin
|
| 15 |
+
models:
|
| 16 |
+
- allenai/DR-Tulu2-4B
|
| 17 |
+
- bartowski/allenai_DR-Tulu2-4B-GGUF
|
| 18 |
+
tags:
|
| 19 |
+
- webgpu
|
| 20 |
+
- wllama
|
| 21 |
+
- gguf
|
| 22 |
+
- deep-research
|
| 23 |
+
- agent
|
| 24 |
---
|
| 25 |
|
| 26 |
+
[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).
|
| 27 |
+
The prompt, tool definitions, 150-call budget and final-answer warning come from allenai/dr-tulu2.
|
agent.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// DR Tulu 2 agent logic, ported from allenai/dr-tulu2 (drtulu2-client): the general-web system prompt, the two tools
|
| 2 |
+
// (`search`, `webterminal`), the 150-call budget with its final warning, and Qwen3.5's XML tool-call format.
|
| 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: {
|
| 23 |
+
command: { type: 'string', description: 'A `browse <url>` command, optionally followed by a pipeline.' } }, required: ['command'] } } },
|
| 24 |
+
];
|
| 25 |
+
|
| 26 |
+
// Python's json.dumps(ensure_ascii=False): ", " and ": " separators (what the chat template's `tojson` prints)
|
| 27 |
+
export function pyJson(v) {
|
| 28 |
+
if (v === null) return 'null';
|
| 29 |
+
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') return JSON.stringify(v);
|
| 30 |
+
if (Array.isArray(v)) return '[' + v.map(pyJson).join(', ') + ']';
|
| 31 |
+
return '{' + Object.entries(v).map(([k, x]) => JSON.stringify(k) + ': ' + pyJson(x)).join(', ') + '}';
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
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>';
|
| 35 |
+
|
| 36 |
+
// The first turn exactly as DR-Tulu2-4B's chat_template.jinja renders [system, user] with tools and the generation prompt.
|
| 37 |
+
export function firstPrompt(system, question, tools = TOOLS) {
|
| 38 |
+
let s = '<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>';
|
| 39 |
+
for (const t of tools) s += '\n' + pyJson(t);
|
| 40 |
+
s += '\n</tools>' + TOOL_FORMAT;
|
| 41 |
+
if (system.trim()) s += '\n\n' + system.trim();
|
| 42 |
+
s += '<|im_end|>\n';
|
| 43 |
+
s += '<|im_start|>user\n' + question.trim() + '<|im_end|>\n';
|
| 44 |
+
return s + '<|im_start|>assistant\n<think>\n';
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// Text to append after the model's turn (its stop token <|im_end|> is fed separately): the tool responses as one user
|
| 48 |
+
// turn, then the next generation prompt. Same layout the template gives role="tool" messages.
|
| 49 |
+
export function toolTurn(outputs) {
|
| 50 |
+
let s = '\n<|im_start|>user';
|
| 51 |
+
for (const o of outputs) s += '\n<tool_response>\n' + o.trim() + '\n</tool_response>';
|
| 52 |
+
return s + '<|im_end|>\n<|im_start|>assistant\n<think>\n';
|
| 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.
|
| 74 |
+
export function typedArgs(call) {
|
| 75 |
+
const def = TOOLS.find((t) => t.function.name === call.name);
|
| 76 |
+
if (!def) return null;
|
| 77 |
+
const props = def.function.parameters.properties, out = {};
|
| 78 |
+
for (const [k, v] of Object.entries(call.args)) {
|
| 79 |
+
if (!props[k]) continue;
|
| 80 |
+
out[k] = props[k].type === 'integer' ? parseInt(v, 10) : v;
|
| 81 |
+
}
|
| 82 |
+
for (const r of def.function.parameters.required) if (out[r] === undefined || Number.isNaN(out[r])) return null;
|
| 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);
|
| 96 |
+
if (presence) for (const t of seen) work[t] -= presence;
|
| 97 |
+
// top-k candidates by partial selection
|
| 98 |
+
const k = Math.min(topK > 0 ? topK : n, n), idx = new Int32Array(k), val = new Float32Array(k).fill(-Infinity);
|
| 99 |
+
for (let i = 0; i < n; i++) {
|
| 100 |
+
const x = work[i];
|
| 101 |
+
if (x > val[k - 1]) {
|
| 102 |
+
let j = k - 1;
|
| 103 |
+
while (j > 0 && val[j - 1] < x) { val[j] = val[j - 1]; idx[j] = idx[j - 1]; j--; }
|
| 104 |
+
val[j] = x; idx[j] = i;
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
const mx = val[0], p = new Float64Array(k);
|
| 108 |
+
let sum = 0;
|
| 109 |
+
for (let i = 0; i < k; i++) { p[i] = Math.exp((val[i] - mx) / temperature); sum += p[i]; }
|
| 110 |
+
let cut = k, acc = 0;
|
| 111 |
+
for (let i = 0; i < k; i++) { acc += p[i] / sum; if (acc >= topP) { cut = i + 1; break; } }
|
| 112 |
+
let tot = 0; for (let i = 0; i < cut; i++) tot += p[i];
|
| 113 |
+
let r = rnd() * tot;
|
| 114 |
+
for (let i = 0; i < cut; i++) { r -= p[i]; if (r <= 0) return idx[i]; }
|
| 115 |
+
return idx[cut - 1];
|
| 116 |
+
}
|
engine.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// DR-Tulu2-4B as a GGUF (bartowski Q4_K_M) on wllama: llama.cpp compiled to WebAssembly, with its WebGPU backend.
|
| 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 });
|
| 9 |
+
const tryLoad = async (n_ctx, useCache) => {
|
| 10 |
+
await wllama.loadModelFromUrl(url, {
|
| 11 |
+
n_ctx, n_gpu_layers: gpu ? 999 : 0, connections: 6, cache_type_k: 'f16', cache_type_v: 'f16', useCache,
|
| 12 |
+
progressCallback: ({ loaded, total }) => onProgress?.(loaded, total),
|
| 13 |
+
});
|
| 14 |
+
};
|
| 15 |
+
let useCache = true;
|
| 16 |
+
for (let attempt = 0; ; attempt++) {
|
| 17 |
+
try { await tryLoad(nCtx, useCache); break; } catch (e) {
|
| 18 |
+
console.warn('load failed:', e);
|
| 19 |
+
await wllama.exit().catch(() => {});
|
| 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 |
+
}
|
| 27 |
+
let info = {}; try { info = wllama.getLoadedContextInfo(); } catch { /* optional */ }
|
| 28 |
+
return {
|
| 29 |
+
nCtx, info,
|
| 30 |
+
// Stream a raw completion. `prompt` is the whole transcript so far; llama.cpp reuses the cached prefix, so only new text is read.
|
| 31 |
+
async *complete(prompt, { maxTokens = 6000, signal, sampling = SAMPLING } = {}) {
|
| 32 |
+
const stream = await wllama.createCompletion({ prompt, stream: true, max_tokens: maxTokens, abortSignal: signal, return_progress: true, ...sampling });
|
| 33 |
+
for await (const chunk of stream) {
|
| 34 |
+
const c = chunk.choices?.[0];
|
| 35 |
+
yield { text: c?.text ?? '', finish: c?.finish_reason ?? null, progress: chunk.prompt_progress ?? null, usage: chunk.usage ?? null, timings: chunk.timings ?? null };
|
| 36 |
+
}
|
| 37 |
+
},
|
| 38 |
+
async countTokens(text) { try { return (await wllama.tokenize(text)).length; } catch { return Math.ceil(text.length / 3.2); } },
|
| 39 |
+
async exit() { await wllama.exit(); },
|
| 40 |
+
};
|
| 41 |
+
}
|
index.html
CHANGED
|
@@ -1,19 +1,55 @@
|
|
| 1 |
<!doctype html>
|
| 2 |
-
<html>
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
</html>
|
|
|
|
| 1 |
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>DR Tulu 2 WebGPU</title>
|
| 7 |
+
<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.">
|
| 8 |
+
<link rel="icon" href="data:,">
|
| 9 |
+
<link rel="stylesheet" href="style.css">
|
| 10 |
+
</head>
|
| 11 |
+
<body>
|
| 12 |
+
<main>
|
| 13 |
+
<p id="line"><b><a href="https://huggingface.co/allenai/DR-Tulu2-4B" target="_blank" rel="noopener">DR Tulu 2</a></b>
|
| 14 |
+
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>
|
| 15 |
+
|
| 16 |
+
<form id="ask" autocomplete="off">
|
| 17 |
+
<label for="q" class="sr">Research question</label>
|
| 18 |
+
<textarea id="q" rows="3" maxlength="1500" placeholder="Ask something that needs looking up…" spellcheck="true"></textarea>
|
| 19 |
+
<div id="row">
|
| 20 |
+
<button id="go" type="submit">Research</button>
|
| 21 |
+
<button id="stop" type="button" hidden>Stop</button>
|
| 22 |
+
<span id="examples"></span>
|
| 23 |
+
</div>
|
| 24 |
+
</form>
|
| 25 |
+
|
| 26 |
+
<p id="status" role="status" aria-live="polite">Ready. The model (2.7 GB) downloads once, when you first press Research.</p>
|
| 27 |
+
<div id="bar"><i></i></div>
|
| 28 |
+
|
| 29 |
+
<section id="answer" hidden>
|
| 30 |
+
<h2>Answer</h2>
|
| 31 |
+
<p id="short"></p>
|
| 32 |
+
<div id="report"></div>
|
| 33 |
+
</section>
|
| 34 |
+
|
| 35 |
+
<section id="trail" aria-label="Research steps"></section>
|
| 36 |
+
|
| 37 |
+
<details id="more">
|
| 38 |
+
<summary>How it works, limits and credits</summary>
|
| 39 |
+
<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
|
| 40 |
+
(<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.
|
| 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>
|
| 52 |
+
</main>
|
| 53 |
+
<script type="module" src="main.js"></script>
|
| 54 |
+
</body>
|
| 55 |
</html>
|
main.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 7 |
+
// bartowski's imatrix K-quant of allenai/DR-Tulu2-4B, used as published (no re-hosting)
|
| 8 |
+
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';
|
| 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'],
|
| 16 |
+
['Which open-weight language models above 100B parameters were released in the last six months, and who made them?', 'recent models'],
|
| 17 |
+
];
|
| 18 |
+
|
| 19 |
+
const $ = (id) => document.getElementById(id);
|
| 20 |
+
const ui = { form: $('ask'), q: $('q'), go: $('go'), stop: $('stop'), status: $('status'), bar: $('bar').firstElementChild, answer: $('answer'),
|
| 21 |
+
short: $('short'), report: $('report'), trail: $('trail'), store: $('store'), wipe: $('wipe'), examples: $('examples') };
|
| 22 |
+
const mb = (b) => `${Math.round(b / 1e6)} MB`;
|
| 23 |
+
const tick = () => new Promise((r) => setTimeout(r, 0));
|
| 24 |
+
let aborted = false;
|
| 25 |
+
|
| 26 |
+
function status(text, frac = null, bad = false) {
|
| 27 |
+
ui.status.textContent = text; ui.status.classList.toggle('bad', bad);
|
| 28 |
+
if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// ---------------------------------------------------------------- model
|
| 32 |
+
let enginePromise = null;
|
| 33 |
+
const loadEngine = () => (enginePromise ||= (async () => {
|
| 34 |
+
if (USE_GPU && !navigator.gpu) status('No WebGPU in this browser: running on the CPU (slow).', 0);
|
| 35 |
+
const system = (await (await fetch('prompt.json')).json()).chat_template[0].content;
|
| 36 |
+
if (window.__testEngine) { status('Model ready.', 1); return { engine: window.__testEngine, system }; } // test hook: a stand-in engine
|
| 37 |
+
const engine = await createEngine({ url: GGUF, nCtx: CTX, gpu: USE_GPU && !!navigator.gpu,
|
| 38 |
+
onProgress: (loaded, total) => status(`Downloading the model: ${mb(loaded)} of ${mb(total || GGUF_BYTES)}, first time only`, loaded / (total || GGUF_BYTES)),
|
| 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; }
|
| 46 |
+
|
| 47 |
+
function stepCard(n) {
|
| 48 |
+
const d = el('details', 'step live');
|
| 49 |
+
const s = el('summary'); s.append(el('span', 'n', `${n}.`), el('span', 'tool', 'thinking…'), el('span', 'arg', ''));
|
| 50 |
+
d.append(s); ui.trail.append(d);
|
| 51 |
+
return { d, set(tool, arg) { s.children[1].textContent = tool; s.children[2].textContent = arg || ''; },
|
| 52 |
+
think(text) { let t = d.querySelector('.think'); if (!t) { t = el('div', 'think'); d.append(t); } t.textContent = text; t.scrollTop = t.scrollHeight; },
|
| 53 |
+
result(text) { d.querySelector('pre')?.remove(); d.append(el('pre', '', text)); d.classList.remove('live'); } };
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
function showAnswer(text, short) {
|
| 57 |
+
ui.answer.hidden = false; ui.short.textContent = short || ''; ui.report.textContent = text.trim();
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// ---------------------------------------------------------------- tools (run in this page: tools.js)
|
| 61 |
+
async function callTool(name, args) {
|
| 62 |
+
try { return name === 'search' ? await search(args.query, args.num_results) : await webterminal(args.command); }
|
| 63 |
+
catch (e) { return `Error: the tool failed (${e?.message || e}).`; }
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// ---------------------------------------------------------------- the research loop
|
| 67 |
+
async function research(question) {
|
| 68 |
+
aborted = false;
|
| 69 |
+
ui.answer.hidden = true; ui.trail.replaceChildren();
|
| 70 |
+
const { engine, system } = await loadEngine();
|
| 71 |
+
let transcript = firstPrompt(system, question), calls = 0, step = 0, t0 = performance.now(), genTokens = 0, ctxTokens = await engine.countTokens(transcript);
|
| 72 |
+
const ctl = new AbortController(); ui.stop.onclick = () => { aborted = true; ctl.abort(); };
|
| 73 |
+
for (;;) {
|
| 74 |
+
if (aborted) { status('Stopped.', 0); return; }
|
| 75 |
+
step++;
|
| 76 |
+
const card = stepCard(step);
|
| 77 |
+
status(`Reading the conversation (${ctxTokens.toLocaleString()} tokens)…`, 0);
|
| 78 |
+
let raw = '', finish = null, n = 0, tStart = 0, lastUi = 0;
|
| 79 |
+
try {
|
| 80 |
+
for await (const part of engine.complete(transcript, { maxTokens: Math.min(MAX_NEW, CTX - ctxTokens - 64), signal: ctl.signal })) {
|
| 81 |
+
if (part.progress?.total) status(`Reading the conversation… ${Math.round(100 * part.progress.processed / part.progress.total)}%`, part.progress.processed / part.progress.total);
|
| 82 |
+
if (part.text) { if (!n) tStart = performance.now(); raw += part.text; n++; }
|
| 83 |
+
if (part.finish) finish = part.finish;
|
| 84 |
+
const now = performance.now();
|
| 85 |
+
if (part.text && now - lastUi > 250) {
|
| 86 |
+
lastUi = now; card.think(parseAssistant(raw).thinking);
|
| 87 |
+
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}`);
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
} catch (e) { if (aborted) { card.d.remove(); status('Stopped.', 0); return; } throw e; }
|
| 91 |
+
genTokens += n;
|
| 92 |
+
const parsed = parseAssistant(raw);
|
| 93 |
+
card.think(parsed.thinking);
|
| 94 |
+
if (!parsed.calls.length || !parsed.finished) { // the model answered (or ran out of room): this is the report
|
| 95 |
+
card.d.remove();
|
| 96 |
+
const text = parsed.finished ? parsed.content : parsed.thinking;
|
| 97 |
+
showAnswer(text.replace(/```json[\s\S]*?```\s*$/, ''), extractAnswer(text));
|
| 98 |
+
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);
|
| 99 |
+
return;
|
| 100 |
+
}
|
| 101 |
+
const outputs = [];
|
| 102 |
+
for (const c of parsed.calls) {
|
| 103 |
+
const args = typedArgs(c);
|
| 104 |
+
if (calls >= MAX_TOOL_CALLS) { outputs.push(`Tool not executed: tool-call budget exhausted. ${FINAL_WARNING}`); continue; }
|
| 105 |
+
if (!args) { outputs.push(`Error: invalid call to ${c.name}. Available tools: ${TOOLS.map((t) => t.function.name).join(', ')}.`); continue; }
|
| 106 |
+
calls++;
|
| 107 |
+
card.set(c.name, c.name === 'search' ? args.query : args.command);
|
| 108 |
+
status(`Tool call ${calls}/${MAX_TOOL_CALLS}: ${c.name}…`);
|
| 109 |
+
let out = await callTool(c.name, args);
|
| 110 |
+
if (calls === MAX_TOOL_CALLS) out += `\n\n${FINAL_WARNING}`;
|
| 111 |
+
card.result(out); outputs.push(out);
|
| 112 |
+
}
|
| 113 |
+
card.d.classList.remove('live');
|
| 114 |
+
let next = raw + IM_END + toolTurn(outputs);
|
| 115 |
+
let nextTokens = await engine.countTokens(transcript + next);
|
| 116 |
+
if (nextTokens > CTX - 1500) { // out of context room: make the model write its report now
|
| 117 |
+
next = raw + IM_END + toolTurn(outputs.map(() => `Tool output omitted: the context window is full. ${FINAL_WARNING}`));
|
| 118 |
+
nextTokens = await engine.countTokens(transcript + next);
|
| 119 |
+
}
|
| 120 |
+
transcript += next; ctxTokens = nextTokens;
|
| 121 |
+
await tick();
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
// ---------------------------------------------------------------- UI
|
| 126 |
+
ui.form.addEventListener('submit', async (e) => {
|
| 127 |
+
e.preventDefault();
|
| 128 |
+
const question = ui.q.value.trim();
|
| 129 |
+
if (!question) return;
|
| 130 |
+
ui.go.disabled = true; ui.stop.hidden = false;
|
| 131 |
+
try { await research(question); } catch (err) { console.error(err); status(err?.message || String(err), null, true); }
|
| 132 |
+
ui.go.disabled = false; ui.stop.hidden = true; storage();
|
| 133 |
+
});
|
| 134 |
+
ui.q.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) ui.form.requestSubmit(); });
|
| 135 |
+
for (const [text, label] of EXAMPLES) {
|
| 136 |
+
const b = el('button', '', label); b.type = 'button'; b.title = text;
|
| 137 |
+
b.addEventListener('click', () => { ui.q.value = text; ui.q.focus(); });
|
| 138 |
+
ui.examples.append(b);
|
| 139 |
+
}
|
| 140 |
+
$('repo').href = 'https://huggingface.co/bartowski/allenai_DR-Tulu2-4B-GGUF'; $('repo').textContent = 'bartowski/allenai_DR-Tulu2-4B-GGUF';
|
| 141 |
+
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 = ''; } }
|
| 142 |
+
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.'; });
|
| 143 |
+
storage();
|
| 144 |
+
window.__dr = { loadEngine, research }; // test hook
|
prompt.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "webterminal-plain-answer-v1",
|
| 3 |
+
"input_variables": [
|
| 4 |
+
"question"
|
| 5 |
+
],
|
| 6 |
+
"chat_template": [
|
| 7 |
+
{
|
| 8 |
+
"role": "system",
|
| 9 |
+
"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."
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"role": "user",
|
| 13 |
+
"content": "{question}"
|
| 14 |
+
}
|
| 15 |
+
]
|
| 16 |
+
}
|
style.css
CHANGED
|
@@ -1,28 +1,55 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
| 4 |
}
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
margin-top: 0;
|
| 9 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
}
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
border: 1px solid lightgray;
|
| 23 |
-
border-radius: 16px;
|
| 24 |
-
}
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:root {
|
| 2 |
+
--bg: #f4f2ee; --panel: #ffffff; --ink: #1d1c1a; --muted: #6b6760; --line: #d8d4cc;
|
| 3 |
+
--accent: #b4441b; --accent-ink: #ffffff; --bad: #a3261b; --tool: #2b5f8a;
|
| 4 |
+
color-scheme: light dark;
|
| 5 |
}
|
| 6 |
+
@media (prefers-color-scheme: dark) {
|
| 7 |
+
:root { --bg: #151413; --panel: #1f1d1b; --ink: #ece8e1; --muted: #a29d94; --line: #3a3732;
|
| 8 |
+
--accent: #e0703f; --accent-ink: #151413; --bad: #ff8a7a; --tool: #7db6e8; }
|
|
|
|
| 9 |
}
|
| 10 |
+
* { box-sizing: border-box; }
|
| 11 |
+
html, body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
| 12 |
+
main { display: grid; gap: 10px; padding: 10px 12px 24px; max-width: 860px; margin: 0 auto; }
|
| 13 |
+
#line { margin: 0; font-size: 14px; color: var(--muted); }
|
| 14 |
+
#line b { color: var(--ink); }
|
| 15 |
+
a { color: var(--accent); }
|
| 16 |
|
| 17 |
+
#ask { display: grid; gap: 8px; }
|
| 18 |
+
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; }
|
| 19 |
+
#row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
| 20 |
+
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; }
|
| 21 |
+
button:disabled { opacity: .55; cursor: default; }
|
| 22 |
+
#stop { background: transparent; color: var(--ink); border: 1px solid var(--line); font-weight: 500; }
|
| 23 |
+
#examples { display: flex; flex-wrap: wrap; gap: 6px; }
|
| 24 |
+
#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; }
|
| 25 |
+
#examples button:hover { color: var(--accent); border-color: var(--accent); }
|
| 26 |
|
| 27 |
+
#status { margin: 0; min-height: 1.4em; font-size: 13px; color: var(--muted); font-variant-numeric: tabular-nums; }
|
| 28 |
+
#status.bad { color: var(--bad); }
|
| 29 |
+
#bar { height: 4px; background: var(--line); border-radius: 2px; overflow: hidden; margin-top: -4px; }
|
| 30 |
+
#bar i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .2s; }
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
#answer { background: var(--panel); border: 1px solid var(--line); border-left: 4px solid var(--accent); border-radius: 6px; padding: 8px 14px 12px; }
|
| 33 |
+
#answer h2 { margin: 4px 0; font-size: 13px; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); font-weight: 600; }
|
| 34 |
+
#short { margin: 4px 0 8px; font-size: 20px; font-weight: 600; }
|
| 35 |
+
#short:empty { display: none; }
|
| 36 |
+
#report { white-space: pre-wrap; overflow-wrap: anywhere; }
|
| 37 |
+
|
| 38 |
+
#trail { display: grid; gap: 6px; }
|
| 39 |
+
.step { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 6px 10px; font-size: 13.5px; }
|
| 40 |
+
.step > summary { cursor: pointer; display: flex; gap: 8px; align-items: baseline; }
|
| 41 |
+
.step .n { color: var(--muted); font-variant-numeric: tabular-nums; min-width: 2.2em; }
|
| 42 |
+
.step .tool { color: var(--tool); font-weight: 600; }
|
| 43 |
+
.step .arg { overflow-wrap: anywhere; }
|
| 44 |
+
.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); }
|
| 45 |
+
.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; }
|
| 46 |
+
.live { border-style: dashed; }
|
| 47 |
+
|
| 48 |
+
#more { color: var(--muted); font-size: 13px; }
|
| 49 |
+
#more p { margin: 6px 0; }
|
| 50 |
+
summary { cursor: pointer; }
|
| 51 |
+
#wipe { min-height: 30px; font-weight: 500; color: var(--ink); background: transparent; border: 1px solid var(--line); }
|
| 52 |
+
code { font-size: 12.5px; }
|
| 53 |
+
.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
|
| 54 |
+
:where(button, textarea, summary, a, [tabindex]):focus-visible { outline: 2px solid var(--accent) !important; outline-offset: 2px; }
|
| 55 |
+
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition-duration: 0.01ms !important; } }
|
tools.js
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Free, key-less, in-browser stand-ins for DR Tulu 2's two live tools (allenai/dr-tulu2 uses Serper + Jina with paid keys).
|
| 2 |
+
// search(query, n) -> the harness's text format ("**title**\nsnippet\nSource: url")
|
| 3 |
+
// webterminal(command) -> `browse <url> [| head | tail | rg | grep | sed | wc | sort | uniq | cut]`, run by a small
|
| 4 |
+
// pure-JS pipeline (no shell, no eval; the model's regexes run in a try/catch)
|
| 5 |
+
// Everything happens in the page: pages are read through Jina Reader's anonymous endpoint (CORS-enabled, renders
|
| 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 |
+
}
|
| 33 |
+
|
| 34 |
+
// ------------------------------------------------------------------------------------------ pages
|
| 35 |
+
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();
|
| 43 |
+
export async function fetchPage(url) {
|
| 44 |
+
url = checkUrl(url);
|
| 45 |
+
if (pageCache.has(url)) return pageCache.get(url);
|
| 46 |
+
const tried = []; let text = '';
|
| 47 |
+
try { // tier 1: Jina Reader (renders JS, strips boilerplate)
|
| 48 |
+
const r = await getText(url, { reader: true, timeout: 45000 });
|
| 49 |
+
tried.push(`reader HTTP ${r.status}`);
|
| 50 |
+
if (r.status < 400 && r.text.trim()) text = r.text;
|
| 51 |
+
if (BLOCK.test(text.slice(0, 1500)) && text.length < 3000) text = '';
|
| 52 |
+
} catch (e) { tried.push(`reader ${e.name}`); }
|
| 53 |
+
if (!text.trim()) try { // tier 2: the page itself, when its server allows cross-origin reads
|
| 54 |
+
const r = await getText(url, { timeout: 15000 });
|
| 55 |
+
tried.push(`direct HTTP ${r.status}`);
|
| 56 |
+
if (r.status < 400) text = htmlToText(r.text);
|
| 57 |
+
} catch (e) { tried.push(`direct ${e.name === 'AbortError' ? 'timeout' : 'blocked by CORS'}`); }
|
| 58 |
+
if (!text.trim()) try { // tier 3: Wayback Machine snapshot
|
| 59 |
+
const av = await getText(`https://archive.org/wayback/available?url=${encodeURIComponent(url)}`, { timeout: 15000 });
|
| 60 |
+
const snap = JSON.parse(av.text)?.archived_snapshots?.closest?.url;
|
| 61 |
+
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; }
|
| 62 |
+
else tried.push('archive none');
|
| 63 |
+
} catch (e) { tried.push(`archive ${e.name}`); }
|
| 64 |
+
text = text.trim() || `BLOCKED/EMPTY: could not get readable content from ${url} (${tried.join(', ')}). Try another source.`;
|
| 65 |
+
pageCache.set(url, text); if (pageCache.size > 100) pageCache.delete(pageCache.keys().next().value);
|
| 66 |
+
return text;
|
| 67 |
+
}
|
| 68 |
+
function htmlToText(html) {
|
| 69 |
+
if (!/^\s*(<!doctype|<html)/i.test(html)) return html;
|
| 70 |
+
const d = new DOMParser().parseFromString(html, 'text/html');
|
| 71 |
+
d.querySelectorAll('script,style,noscript,nav,footer,header,aside,form,svg,iframe').forEach((e) => e.remove());
|
| 72 |
+
return (d.body?.innerText || d.body?.textContent || '').replace(/\n{3,}/g, '\n\n');
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// ------------------------------------------------------------------------------------------ search
|
| 76 |
+
const searchCache = new Map();
|
| 77 |
+
const clean = (s) => s.replace(/<[^>]+>/g, '').replace(/"/g, '"').replace(/&/g, '&').replace(/'|'/g, "'").replace(/</g, '<').replace(/>/g, '>');
|
| 78 |
+
|
| 79 |
+
// 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
|
| 80 |
+
// "<site> <https://host › path ›…> <title>", followed by a paragraph with the snippet.
|
| 81 |
+
export function parseBrave(md) {
|
| 82 |
+
const body = md.split('Markdown Content:')[1] || md;
|
| 83 |
+
const flat = body.replace(/!\[[^\]]*\]\([^)]*\)/g, '');
|
| 84 |
+
const rows = [], re = /\[([^\]]*)\]\(https:\/\/search\.brave\.com\/go\/v1#[^)]*\)\s*\n+([^\n[][^\n]*)?/g;
|
| 85 |
+
let m;
|
| 86 |
+
while ((m = re.exec(flat))) {
|
| 87 |
+
const label = m[1].replace(/\s+/g, ' ').trim(), snip = (m[2] || '').trim();
|
| 88 |
+
const hm = label.match(/https?:\/\/\S+/);
|
| 89 |
+
if (!hm) continue;
|
| 90 |
+
// After the host, Brave shows a breadcrumb "› seg › seg › lastseg Title": segments with spaces are page titles, not path pieces.
|
| 91 |
+
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)
|
| 92 |
+
let path = [], title = '', ok = true;
|
| 93 |
+
for (let k = 1; k < parts.length; k++) {
|
| 94 |
+
const last = k === parts.length - 1, seg = parts[k];
|
| 95 |
+
if (!last) { if (ok && seg && !/\s/.test(seg) && !seg.includes('…')) path.push(seg); else ok = false; }
|
| 96 |
+
else { const [first, ...rest] = seg.split(' '); if (ok && first && !first.includes('…') && rest.length) { path.push(first); title = rest.join(' '); } else title = seg; }
|
| 97 |
+
}
|
| 98 |
+
if (parts.length === 1) title = parts[0];
|
| 99 |
+
const href = (hm[0].replace(/…+$/, '') + path.map((x) => '/' + x).join('')).replace(/\/$/, '');
|
| 100 |
+
title = title.trim() || href;
|
| 101 |
+
rows.push({ title, body: snip.replace(/\*\*/g, ''), href });
|
| 102 |
+
}
|
| 103 |
+
return rows;
|
| 104 |
+
}
|
| 105 |
+
async function braveSearch(q) {
|
| 106 |
+
const r = await getText(`https://search.brave.com/search?q=${encodeURIComponent(q)}&source=web`, { reader: true, timeout: 45000 });
|
| 107 |
+
if (r.status >= 400) throw new Error(`brave ${r.status}`);
|
| 108 |
+
return parseBrave(r.text);
|
| 109 |
+
}
|
| 110 |
+
async function wikipedia(q, n) {
|
| 111 |
+
const r = await getText(`https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(q)}&srlimit=${n}&format=json&origin=*`);
|
| 112 |
+
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, ')') }));
|
| 113 |
+
}
|
| 114 |
+
async function openalex(q, n) {
|
| 115 |
+
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`);
|
| 116 |
+
return JSON.parse(r.text).results.map((w) => {
|
| 117 |
+
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;
|
| 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)) {
|
| 179 |
+
let v = j < a.length ? a.slice(j) : args[i];
|
| 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;
|
| 188 |
+
}
|
| 189 |
+
if (!pats.length) pats.push(a); else throw new CmdError(`${name} reads stdin only; file arguments are not allowed`);
|
| 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`;
|
| 200 |
+
if (only && !invert) {
|
| 201 |
+
const g = new RegExp(rx.source, rx.flags + 'g'), out = [];
|
| 202 |
+
ls.forEach((l, k) => { if (hit[k]) for (const m of l.matchAll(g)) if (m[0]) out.push((showN ? `${k + 1}:` : '') + m[0]); });
|
| 203 |
+
return nl(out);
|
| 204 |
+
}
|
| 205 |
+
const keep = new Set();
|
| 206 |
+
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); });
|
| 207 |
+
const out = []; let last = -1;
|
| 208 |
+
for (const k of [...keep].sort((a, b) => a - b)) {
|
| 209 |
+
if ((ctxA || ctxB) && last >= 0 && k !== last + 1) out.push('--');
|
| 210 |
+
out.push((showN ? `${k + 1}${hit[k] ? ':' : '-'}` : '') + ls[k]); last = k;
|
| 211 |
+
}
|
| 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);
|
| 284 |
+
if (['grep', 'egrep', 'rg'].includes(name)) return cmdGrep(name, args, text);
|
| 285 |
+
if (name === 'sed') return cmdSed(args, text);
|
| 286 |
+
if (name === 'wc') return cmdWc(args, 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) {
|
| 301 |
+
const c = command[i];
|
| 302 |
+
if (/\s/.test(c)) { push(); i++; }
|
| 303 |
+
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; }
|
| 304 |
+
else if (c === '"') {
|
| 305 |
+
let j = i + 1; has = true;
|
| 306 |
+
for (;; j++) {
|
| 307 |
+
if (j >= command.length) throw new CmdError('invalid quoting: No closing quotation');
|
| 308 |
+
if (command[j] === '\\' && '"\\$`'.includes(command[j + 1] ?? '')) { cur += command[++j]; continue; }
|
| 309 |
+
if (command[j] === '"') break;
|
| 310 |
+
cur += command[j];
|
| 311 |
+
}
|
| 312 |
+
i = j + 1;
|
| 313 |
+
} else if (c === '\\') { if (i + 1 >= command.length) throw new CmdError('invalid quoting: No escaped character'); cur += command[i + 1]; has = true; i += 2; }
|
| 314 |
+
else { cur += c; has = true; i++; }
|
| 315 |
+
}
|
| 316 |
+
push();
|
| 317 |
+
const stages = []; let st = [];
|
| 318 |
+
for (const t of toks) {
|
| 319 |
+
if (t === '|') { if (!st.length) throw new CmdError('empty pipeline stage'); stages.push(st); st = []; }
|
| 320 |
+
else if ([';', ';;', '&', '&&', '||', '>', '>>', '<', '<<', '(', ')'].includes(t)) throw new CmdError(`shell operator '${t}' is not supported; only | pipes`);
|
| 321 |
+
else st.push(t);
|
| 322 |
+
}
|
| 323 |
+
if (!st.length) throw new CmdError('empty pipeline stage');
|
| 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 |
+
}
|
vendor/wllama/index.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vendor/wllama/wllama.wasm
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b012436a101ede8c877f2d26644c3181429d4fb8da4fd90c356110d86bfd74a6
|
| 3 |
+
size 10838652
|