File size: 11,269 Bytes
2227fb8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | /**
* Web search + scrape for the Worker/x402 side β TypeScript equivalent of
* skillforge/research.py's provider router (Tavily -> Brave -> keyless
* fallback for search; Firecrawl -> keyless fetch for scrape).
*
* skillforge/research.py drives its paid providers through a local MCP
* server process (skillforge/mcp_client.py) β that mechanism doesn't exist
* in a Cloudflare Worker (no subprocess/MCP protocol support), so this
* calls each provider's plain REST API directly with fetch(). Deliberately
* narrower than the Python router: Bright Data and Apify's real REST
* contracts (as opposed to their MCP tool wrappers) weren't confirmed
* against primary sources, so scrape here is Firecrawl -> keyless only,
* same "real, not guessed" standard as everywhere else in this repo. No
* quota guard either (skillforge/research.py's MONTHLY_QUOTA is a durable
* file-backed counter β the Worker has no equivalent durable store wired
* up); each provider's own account-level rate limit is the real backstop.
*/
export interface ResearchEnv {
TAVILY_API_KEY?: string;
BRAVE_API_KEY?: string;
FIRECRAWL_API_KEY?: string;
}
export interface SearchResult {
provider: string;
results: Array<{ title: string; url: string; snippet: string }>;
degraded?: boolean;
}
// ββ minimal, portable HTML tokenizer ββββββββββββββββββββββββββββββββββββββββ
// worker/src runs on BOTH Cloudflare Workers and Deno (worker/deno/deno-entry.ts
// β see worker/README.md's "Cloudflare + Deno Deploy" section: "src/index.ts
// has zero Cloudflare-specific code"), so Cloudflare's own HTMLRewriter global
// isn't usable here β Deno's `deno check` has no declaration for it. This is
// a real, hand-written single-pass tokenizer instead: it never re-scans
// already-consumed input (unlike an iterative regex replace, which is exactly
// the "incomplete multi-character sanitization" class of bug CodeQL flags β
// e.g. stripping "<script>" once from "<scr<script>ipt>" leaves a new,
// unintended "<script>ipt>"), same guarantee Python's stdlib
// html.parser.HTMLParser gives agents/investigate.py's own _TextExtractor.
// script/style are read as HTML5's real "raw text" elements β their content
// is never itself tokenized, only scanned forward for the literal closing
// tag, exactly like a real browser parser (not a heuristic guess).
interface TagToken { type: "open" | "close"; name: string; attrs: Record<string, string>; selfClosing?: boolean; }
interface TextToken { type: "text"; text: string; }
type HtmlToken = TagToken | TextToken;
const RAW_TEXT_TAGS = new Set(["script", "style"]);
const ATTR_RE = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*(?:=\s*("([^"]*)"|'([^']*)'|[^\s"'=<>`]+))?/g;
const NAMED_ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "Β " };
function decodeEntities(s: string): string {
return s.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (whole, ent: string) => {
if (ent[0] === "#") {
const isHex = ent[1] === "x" || ent[1] === "X";
const code = parseInt(ent.slice(isHex ? 2 : 1), isHex ? 16 : 10);
return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
}
return NAMED_ENTITIES[ent] ?? whole;
});
}
function tokenizeHtml(html: string): HtmlToken[] {
const tokens: HtmlToken[] = [];
const n = html.length;
let i = 0;
while (i < n) {
const lt = html.indexOf("<", i);
if (lt === -1) { tokens.push({ type: "text", text: html.slice(i) }); break; }
if (lt > i) tokens.push({ type: "text", text: html.slice(i, lt) });
if (html.startsWith("<!--", lt)) {
const end = html.indexOf("-->", lt + 4);
i = end === -1 ? n : end + 3;
continue;
}
if (html[lt + 1] === "!" || html[lt + 1] === "?") {
const end = html.indexOf(">", lt);
i = end === -1 ? n : end + 1;
continue;
}
const isClose = html[lt + 1] === "/";
const nameStart = isClose ? lt + 2 : lt + 1;
const nameMatch = /^[a-zA-Z][a-zA-Z0-9]*/.exec(html.slice(nameStart));
if (!nameMatch) { tokens.push({ type: "text", text: "<" }); i = lt + 1; continue; }
const name = nameMatch[0].toLowerCase();
const gt = html.indexOf(">", nameStart + name.length);
if (gt === -1) { i = n; break; }
const rawAttrs = html.slice(nameStart + name.length, gt);
const selfClosing = /\/\s*$/.test(rawAttrs);
const attrs: Record<string, string> = {};
if (!isClose) {
ATTR_RE.lastIndex = 0;
let am: RegExpExecArray | null;
while ((am = ATTR_RE.exec(rawAttrs))) {
if (!am[1]) continue;
attrs[am[1].toLowerCase()] = am[3] ?? am[4] ?? am[2] ?? "";
}
}
tokens.push(isClose ? { type: "close", name, attrs: {} } : { type: "open", name, attrs, selfClosing });
i = gt + 1;
if (!isClose && RAW_TEXT_TAGS.has(name) && !selfClosing) {
const closeRe = new RegExp(`</${name}\\s*>`, "i");
const rest = html.slice(i);
const cm = closeRe.exec(rest);
if (cm) {
if (cm.index > 0) tokens.push({ type: "text", text: rest.slice(0, cm.index) });
tokens.push({ type: "close", name, attrs: {} });
i += cm.index + cm[0].length;
} else {
tokens.push({ type: "text", text: rest });
i = n;
}
}
}
return tokens;
}
/** Visible text only β script/style content is skipped via real tag-depth
* tracking (see tokenizeHtml's raw-text handling above), never re-scanned. */
function extractText(html: string): string {
let depth = 0;
let out = "";
for (const tok of tokenizeHtml(html)) {
if (tok.type === "open" && RAW_TEXT_TAGS.has(tok.name) && !tok.selfClosing) { depth++; continue; }
if (tok.type === "close" && RAW_TEXT_TAGS.has(tok.name)) { depth = Math.max(0, depth - 1); continue; }
if (tok.type === "text" && depth === 0) out += tok.text;
}
return decodeEntities(out);
}
async function tavilySearch(apiKey: string, query: string, maxResults: number): Promise<SearchResult> {
const res = await fetch("https://api.tavily.com/search", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ query, max_results: maxResults }),
});
if (!res.ok) throw new Error(`tavily HTTP ${res.status}`);
const data: any = await res.json();
const rows: any[] = Array.isArray(data?.results) ? data.results : [];
return { provider: "tavily", results: rows.map((r) => ({ title: r.title || "", url: r.url || "", snippet: (r.content || "").slice(0, 200) })) };
}
async function braveSearch(apiKey: string, query: string, maxResults: number): Promise<SearchResult> {
const url = `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=${maxResults}`;
const res = await fetch(url, { headers: { Accept: "application/json", "X-Subscription-Token": apiKey } });
if (!res.ok) throw new Error(`brave HTTP ${res.status}`);
const data: any = await res.json();
const rows: any[] = Array.isArray(data?.web?.results) ? data.web.results : [];
return { provider: "brave-search", results: rows.map((r) => ({ title: r.title || "", url: r.url || "", snippet: (r.description || "").slice(0, 200) })) };
}
// Keyless fallback β DDG HTML scrape only (skillforge/research.py also tries
// several SearXNG instances first; simplified here to one real, documented
// fallback rather than porting a multi-instance list unverified for Workers).
async function ddgSearch(query: string, maxResults: number): Promise<SearchResult> {
try {
const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`;
const res = await fetch(url, { headers: { "User-Agent": "VAPE-PrivateEye/1.0" } });
if (!res.ok) throw new Error(`ddg HTTP ${res.status}`);
const body = await res.text();
const results: Array<{ title: string; url: string; snippet: string }> = [];
let depth = 0; // >0 while inside a matched <a class="result__a">
let currentHref: string | null = null;
let currentTitle = "";
for (const tok of tokenizeHtml(body)) {
if (tok.type === "open" && tok.name === "a") {
const classes = (tok.attrs["class"] || "").split(/\s+/);
if (depth === 0 && classes.includes("result__a")) {
depth = 1;
currentHref = tok.attrs["href"] || null;
currentTitle = "";
} else if (depth > 0) {
depth++; // nested <a> β real HTML disallows this, defensive only
}
} else if (tok.type === "close" && tok.name === "a" && depth > 0) {
depth--;
if (depth === 0) {
if (currentHref && results.length < maxResults) {
let realUrl = currentHref;
try {
const parsed = new URL(currentHref.startsWith("//") ? `https:${currentHref}` : currentHref);
realUrl = parsed.searchParams.get("uddg") || currentHref;
} catch { /* keep raw href */ }
results.push({ title: decodeEntities(currentTitle).trim(), url: decodeURIComponent(realUrl), snippet: "" });
}
currentHref = null;
currentTitle = "";
}
} else if (tok.type === "text" && depth > 0) {
currentTitle += tok.text;
}
if (results.length >= maxResults && depth === 0) break;
}
return { provider: "ddg-keyless", results, degraded: results.length === 0 };
} catch {
return { provider: "keyless", results: [], degraded: true };
}
}
export async function webSearch(env: ResearchEnv, query: string, maxResults = 5): Promise<SearchResult> {
if (env.TAVILY_API_KEY) {
try { return await tavilySearch(env.TAVILY_API_KEY, query, maxResults); } catch { /* fall through */ }
}
if (env.BRAVE_API_KEY) {
try { return await braveSearch(env.BRAVE_API_KEY, query, maxResults); } catch { /* fall through */ }
}
return ddgSearch(query, maxResults);
}
export interface ScrapeResult {
provider: string;
content: string | null;
}
async function firecrawlScrape(apiKey: string, url: string): Promise<ScrapeResult> {
const res = await fetch("https://api.firecrawl.dev/v2/scrape", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ url, formats: ["markdown"] }),
});
if (!res.ok) throw new Error(`firecrawl HTTP ${res.status}`);
const data: any = await res.json();
return { provider: "firecrawl", content: data?.data?.markdown ?? null };
}
async function keylessFetch(url: string): Promise<ScrapeResult> {
try {
const res = await fetch(url, { headers: { "User-Agent": "VAPE-PrivateEye/1.0" } });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const html = await res.text();
const cleaned = extractText(html).replace(/\s+/g, " ").trim();
return { provider: "fetch-keyless", content: cleaned.slice(0, 8000) };
} catch {
return { provider: "fetch-keyless", content: null };
}
}
export async function webScrape(env: ResearchEnv, url: string): Promise<ScrapeResult> {
if (env.FIRECRAWL_API_KEY) {
try { return await firecrawlScrape(env.FIRECRAWL_API_KEY, url); } catch { /* fall through */ }
}
return keylessFetch(url);
}
|