"use strict"; const DS = "https://huggingface.co/datasets/SamJoshua/tooldoc-injection-minimal-pairs/resolve/main/"; const GUARDS = [ ["horizon_small_v2.7", "Horizon small v2.7"], ["wolf_defender", "wolf-defender"], ["protectai_deberta_v2", "protectai v2"], ["deepset_deberta", "deepset"], ["modernguard_1", "ModernGuard-1"], ]; const THRESH = 0.5; const TJS_URL = "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1"; const TRY_MODEL = "Horizon-Labs/prompt-injection-guard-small"; const TRY_REV = "0c8139d109994806ff404b5b693ad5d63629b9ba"; // tag v2.7, the revision benchmarked const $ = (s, el = document) => el.querySelector(s); const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); const pct = (x) => (100 * x).toFixed(1) + "%"; /* ---------- tabs ---------- */ document.querySelectorAll(".tabs button").forEach((b) => b.addEventListener("click", () => { document.querySelectorAll(".tabs button").forEach((x) => x.setAttribute("aria-selected", x === b)); document.querySelectorAll(".panel").forEach((p) => (p.hidden = p.id !== b.dataset.tab)); history.replaceState(null, "", "#" + b.dataset.tab); }) ); const initialTab = location.hash.slice(1); if (initialTab) document.querySelector(`.tabs button[data-tab="${initialTab}"]`)?.click(); /* ---------- leaderboard ---------- */ let LB = []; let sortKey = null, sortDesc = true; const LOWER_BETTER = new Set(["fp_plain_docs", "fp_benign_requests"]); function renderLB() { const rows = [...LB]; if (sortKey === "model") rows.sort((a, b) => a.model.localeCompare(b.model) * (sortDesc ? -1 : 1)); else if (sortKey) rows.sort((a, b) => (a[sortKey].v - b[sortKey].v) * (sortDesc ? -1 : 1)); document.querySelectorAll("#lb-table th").forEach((th) => th.classList.toggle("sorted", th.dataset.sort === sortKey)); const cell = (m, good, label) => `${pct(m.v)}[${pct(m.lo)}, ${pct(m.hi)}] · ${m.k}/${m.n}` + `
`; $("#lb-table tbody").innerHTML = rows .map((r) => `${esc(r.model)}
rev ${esc(r.revision)}` + cell(r.paired_accuracy, true, "Paired accuracy ↑") + cell(r.fp_plain_docs, false, "FP plain docs ↓") + cell(r.fp_benign_requests, false, "FP benign requests ↓") + cell(r.injection_recall, true, "Injection recall ↑") + "") .join(""); } document.querySelectorAll("#lb-table th").forEach((th) => th.addEventListener("click", () => { const k = th.dataset.sort; if (sortKey === k) sortDesc = !sortDesc; else { sortKey = k; sortDesc = k === "model" ? false : !LOWER_BETTER.has(k); } renderLB(); }) ); document.querySelectorAll("[data-sortbtn]").forEach((b) => b.addEventListener("click", () => document.querySelector(`#lb-table th[data-sort="${b.dataset.sortbtn}"]`).click()) ); fetch("leaderboard.json").then((r) => r.json()).then((d) => { LB = d.rows; renderLB(); }) .catch((e) => ($("#lb-note").textContent = "Could not load leaderboard.json: " + e)); /* ---------- explorer ---------- */ // Same mapping as the Gradio app: edit_type -> kind, string label -> 0/1. const EDIT_TYPE_TO_KIND = { original: "plain_doc", benign_request: "benign_request" }; const LABEL_NAMES = { benign: 0, injection: 1 }; function adaptRow(r) { const o = { ...r }; if (o.kind == null && o.edit_type != null) o.kind = EDIT_TYPE_TO_KIND[o.edit_type] || "injection"; if (typeof o.label === "string" && o.label.trim().toLowerCase() in LABEL_NAMES) o.label = LABEL_NAMES[o.label.trim().toLowerCase()]; return o; } const FAMILY_ORDER = ["handbook", "api_guide", "config", "runbook", "changelog", "readme", "code_comment"]; let PAIRS = new Map(), FEATURED = null, FEATURED_TWIN = null; function parseCSV(text) { const lines = text.trim().split(/\r?\n/); const head = lines.shift().split(","); return lines.map((l) => { const v = l.split(","); return Object.fromEntries(head.map((h, i) => [h, v[i]])); }); } async function loadRemote() { const fetchText = async (u) => { const r = await fetch(u); if (!r.ok) throw new Error(`${r.status} for ${u.split("/main/")[1]}`); return r.text(); }; const [dev, striking, ...scoreFiles] = await Promise.all([ fetchText(DS + "data/dev.jsonl"), fetchText(DS + "results/striking_pairs_dev.csv"), ...GUARDS.map(([g]) => fetchText(DS + `results/scores_dev_${g}.csv`)), ]); const scores = {}; scoreFiles.forEach((t, i) => parseCSV(t).forEach((r) => ((scores[r.id] ||= {})[GUARDS[i][0]] = parseFloat(r.p_injection)))); const rows = dev.trim().split("\n").map((l) => JSON.parse(l)).map((r) => ({ ...r, scores: scores[r.id] || {} })); return { rows, striking: parseCSV(striking), source: "remote" }; } async function loadFallback() { const d = await (await fetch("fallback.json")).json(); return { rows: d.rows, striking: d.striking, featured: d.featured, source: "fallback" }; } function pickFeatured(striking) { if (PAIRS.has("tdb-dev-runbook-0025")) return "tdb-dev-runbook-0025"; const s = striking.find((x) => x.guard === "horizon_small_v2.7") || striking[0]; if (s) FEATURED_TWIN = s.twin_id; return s ? s.twin_id.replace(/-[^-]+$/, "") : [...PAIRS.keys()][0]; } function diffSpan(base, other) { let p = 0; while (p < base.length && p < other.length && base[p] === other[p]) p++; let s = 0; while (s < base.length - p && s < other.length - p && base[base.length - 1 - s] === other[other.length - 1 - s]) s++; return [p, other.length - s]; } function docHTML(text, base) { if (base == null || base === text) return esc(text); const [a, b] = diffSpan(base, text); return esc(text.slice(0, a)) + "" + esc(text.slice(a, b)) + "" + esc(text.slice(b)); } function scoreTable(row) { const harmful = row.label === 1; return `` + GUARDS.map(([g, name]) => { const p = row.scores?.[g]; if (p == null) return ``; const flagged = p >= THRESH, right = flagged === harmful; return `` + ``; }).join("") + `
${name}n/a
${name}${p.toFixed(3)}${flagged ? "flagged" : "passed"} ${right ? "✓" : "✗"}
`; } function card(title, row, base) { if (!row) return `

${title}

Not in this pair.

`; const tag = row.label === 1 ? `injection · ${esc(row.edit_type)}` : `benign`; return `

${title} ${tag}

${docHTML(row.text, base)}
${scoreTable(row)}

${esc(row.id)}

`; } function renderPair() { const pid = $("#ex-pair").value, g = PAIRS.get(pid); if (!g) return; const twins = g.filter((r) => r.kind === "injection"); const tSel = $("#ex-twin"); if (tSel.dataset.pair !== pid) { tSel.innerHTML = twins.map((t, i) => ``).join(""); tSel.dataset.pair = pid; const fi = twins.findIndex((t) => t.id === FEATURED_TWIN); if (pid === FEATURED && fi >= 0) tSel.value = String(fi); } $("#ex-twin-wrap").hidden = twins.length < 2; const plain = g.find((r) => r.kind === "plain_doc"), ctrl = g.find((r) => r.kind === "benign_request"); const twin = twins[+tSel.value || 0]; $("#ex-caption").innerHTML = `${esc(plain?.family || "")} · ${esc(plain?.format || "")}` + (pid === FEATURED ? " · featured pair" : ""); $("#ex-cols").innerHTML = card("Plain doc", plain, null) + card("Benign request", ctrl, plain?.text) + card("Injection twin", twin, plain?.text); } function fillPairs(fam, select) { const ids = [...PAIRS.keys()].filter((k) => PAIRS.get(k)[0].family === fam); $("#ex-pair").innerHTML = ids.map((k) => ``).join(""); if (select && ids.includes(select)) $("#ex-pair").value = select; renderPair(); } function showFeatured() { const fam = PAIRS.get(FEATURED)?.[0].family; if (!fam) return; $("#ex-family").value = fam; fillPairs(fam, FEATURED); } async function initExplorer() { let d, err = ""; try { d = await loadRemote(); } catch (e) { err = String(e.message || e); d = await loadFallback(); } const rows = d.rows.map(adaptRow); PAIRS = new Map(); rows.forEach((r) => { if (!PAIRS.has(r.pair_id)) PAIRS.set(r.pair_id, []); PAIRS.get(r.pair_id).push(r); }); FEATURED = pickFeatured(d.striking); const fams = FAMILY_ORDER.filter((f) => rows.some((r) => r.family === f)); $("#ex-family").innerHTML = fams.map((f) => ``).join(""); $("#ex-status").textContent = d.source === "remote" ? `Loaded the dev split from the dataset repo: ${rows.length} rows, ${PAIRS.size} pairs, scores from 5 guards.` : `Showing the bundled sample (${rows.length} rows, ${PAIRS.size} pairs). Could not load the dev split (${err}).`; showFeatured(); window.TDB = { PAIRS, FEATURED, source: d.source }; } $("#ex-family").addEventListener("change", (e) => fillPairs(e.target.value)); $("#ex-pair").addEventListener("change", renderPair); $("#ex-twin").addEventListener("change", renderPair); $("#ex-featured").addEventListener("click", showFeatured); initExplorer(); /* ---------- try it ---------- */ let clf = null; document.querySelectorAll("[data-fill]").forEach((b) => b.addEventListener("click", () => { const g = PAIRS.get(FEATURED) || []; const want = { b: "plain_doc", c: "benign_request", t: "injection" }[b.dataset.fill]; const r = g.find((x) => x.kind === want); if (r) $("#try-text").value = r.text; }) ); $("#try-run").addEventListener("click", async () => { const text = $("#try-text").value.trim(); const btn = $("#try-run"), st = $("#try-status"), out = $("#try-out"); if (!text) { st.textContent = "Paste some text first."; return; } btn.disabled = true; try { if (!clf) { st.textContent = "Loading transformers.js and the model (about 300 MB the first time)…"; const { pipeline } = await import(TJS_URL); clf = await pipeline("text-classification", TRY_MODEL, { revision: TRY_REV, dtype: "q8", progress_callback: (p) => { if (p.status === "progress" && p.file?.endsWith(".onnx")) st.textContent = `Downloading model… ${Math.round(p.progress)}%`; }, }); } st.textContent = "Scoring…"; const res = await clf(text, { top_k: null }); const inj = res.find((x) => /inject/i.test(x.label)); const p = inj ? inj.score : NaN; out.hidden = false; out.innerHTML = `p(injection) = ${p.toFixed(3)} → ${p >= THRESH ? "flagged" : "passed"} at 0.5` + `
Labels: ${res.map((x) => `${esc(x.label)} ${x.score.toFixed(3)}`).join(" · ")}
`; st.textContent = ""; } catch (e) { st.textContent = "Could not run the model in this browser: " + (e.message || e); } finally { btn.disabled = false; } });