const PYODIDE_VERSION = "0.29.5";
const PYODIDE_INDEX = `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`;
const ASC_WHEEL = "./vendor/agent_security_contract-0.2.1-py3-none-any.whl";
const ASC_COMMIT = "768853bde5a56fcc6c9b486f52848761db1b0ef1";
const state = {
status: "loading",
loadMs: null,
pyodide: null,
engine: null,
info: null,
currentId: "path_traversal_relative",
lastEnvelope: "",
originalEnvelope: "",
filter: "all",
};
const demo = {
get status() { return state.status; },
get loadMs() { return state.loadMs; },
ready: null,
evaluateScenario: null,
evaluateTrace: null,
runCorpus: null,
tamperAndVerify: null,
};
window.__ASC_DEMO__ = demo;
const $ = (id) => document.getElementById(id);
function formatError(error) {
if (error == null) return String(error);
if (typeof error === "string") return error;
const parts = [error.name, error.message, error.errno, error.code, error.path]
.filter((value) => value != null && value !== "")
.map(String);
if (parts.length) return parts.join(": ");
try { return JSON.stringify(error); } catch (_exc) { return String(error); }
}
function parsePyJson(value) {
const text = typeof value === "string" ? value : value.toString();
if (value && typeof value.destroy === "function") value.destroy();
return JSON.parse(text);
}
function setProgress(percent, text, stateName = "loading") {
state.status = stateName;
document.body.dataset.ascStatus = stateName;
const status = $("status");
status.dataset.state = stateName === "ready" ? "ready" : stateName === "error" ? "error" : "loading";
$("progress-bar").style.width = `${Math.max(4, Math.min(100, percent))}%`;
$("status-text").textContent = text;
}
function setBusy(busy) {
["evaluate", "recompute", "preset", "trace", "policy", "copy-envelope", "download-envelope", "tamper", "run-all"].forEach((id) => {
const el = $(id);
if (el) el.disabled = busy;
});
document.querySelectorAll(".scen, .filter").forEach((el) => {
el.disabled = busy;
});
}
function argsPreview(args) {
try {
const text = JSON.stringify(args);
return text.length > 140 ? `${text.slice(0, 137)}…` : text;
} catch (_exc) {
return "";
}
}
function renderTimeline(calls) {
const root = $("timeline");
if (!calls || !calls.length) {
root.innerHTML = "
No parsed tool calls in this trace.
";
return;
}
root.innerHTML = "";
for (const call of calls) {
const step = document.createElement("article");
step.className = "step";
step.dataset.blocked = call.blocked ? "true" : "false";
step.innerHTML = `
${escapeHtml(call.call_id)}${call.approved ? " · approved" : ""}
${escapeHtml(call.tool)}
${escapeHtml(argsPreview(call.args))}
${call.blocked ? "Blocked call
" : ""}
`;
root.appendChild(step);
}
}
function escapeHtml(value) {
return String(value == null ? "" : value)
.split("&").join("&")
.split("<").join("<")
.split(">").join(">")
.split('"').join(""");
}
function openExternalLinks() {
const links = document.querySelectorAll("a[href]");
for (let i = 0; i < links.length; i += 1) {
const href = links[i].getAttribute("href") || "";
if (href.indexOf("http://") !== 0 && href.indexOf("https://") !== 0) continue;
links[i].setAttribute("target", "_blank");
links[i].setAttribute("rel", "noopener noreferrer");
}
}
function canRunLiveRuntime() {
try {
// Pyodide 0.29.x asm.js uses class static blocks, private fields, and ??=
// Static blocks need Safari 16.4 / iOS 16.4 or later (Pyodide's stated minimum).
new Function("class F { static {} }");
new Function("class F { #x = 1; }");
new Function("var a = {}; a.b ??= 1;");
} catch (err) {
return false;
}
if (typeof WebAssembly === "undefined") return false;
if (typeof WebAssembly.instantiate !== "function") return false;
return true;
}
function forceFallback() {
try {
if (window.__FORCE_FALLBACK__) return true;
const params = new URLSearchParams(window.location.search);
return params.get("fallback") === "1";
} catch (err) {
return false;
}
}
const FALLBACK_MESSAGE = "The live in-browser runtime needs a newer browser (Safari 16.4 or later, or a current desktop browser). This page is showing precomputed results from the official corpus. Open the page on desktop to run the engine yourself.";
function fallbackMessage(error) {
if (!error) return FALLBACK_MESSAGE;
return "The live in-browser runtime could not start in this browser. This page is showing precomputed results from the official corpus. Open the page on a current desktop browser to run the engine yourself.";
}
function chip(text, className) {
const span = document.createElement("span");
span.className = `chip ${className || ""}`.trim();
span.textContent = text;
return span;
}
function applyDecision(out, preset) {
state.lastEnvelope = out.envelope_text;
state.originalEnvelope = out.envelope_text;
$("restore-envelope").hidden = true;
$("tamper-result").hidden = true;
$("copy-status").hidden = true;
const card = $("verdict-card");
card.dataset.verdict = out.verdict || "";
$("verdict-word").textContent = out.verdict || "—";
const meta = $("verdict-meta");
meta.innerHTML = "";
if (out.acs_disposition) meta.appendChild(chip(`ACS ${out.acs_disposition}`, "acs"));
if (preset && preset.expected) meta.appendChild(chip(`Corpus expected ${preset.expected}`, "expected"));
if (out.blocked_call_id) meta.appendChild(chip(`Blocked call ${out.blocked_call_id}`, "blocked"));
if (out.scenario_id) meta.appendChild(chip(out.scenario_id, ""));
meta.appendChild(chip(
out.integrity === "passed" ? "Integrity check passed" : "Integrity check failed",
out.integrity === "passed" ? "integrity-ok" : "integrity-bad",
));
$("reason").textContent = out.reason ? `Reason: ${out.reason}` : "";
$("details").textContent = out.details && Object.keys(out.details).length
? `Details: ${JSON.stringify(out.details)}`
: "";
const envMeta = $("envelope-meta");
envMeta.innerHTML = "";
envMeta.appendChild(chip(
out.integrity === "passed" ? "Integrity check passed" : "Integrity check failed",
out.integrity === "passed" ? "integrity-ok" : "integrity-bad",
));
envMeta.appendChild(chip("Hash-checked, not signed", ""));
$("envelope").textContent = out.envelope_text || "";
renderTimeline(out.calls || []);
}
function currentPreset() {
const presets = (state.info && state.info.presets) || [];
return presets.find((item) => item.id === state.currentId) || { id: state.currentId };
}
function evaluateCurrent() {
const out = demo.evaluateTrace
? demo.evaluateTrace(state.currentId, $("trace").value, $("policy").value)
: (state.precomputed && state.precomputed.results && state.precomputed.results[state.currentId]);
if (!out) {
throw new Error("No precomputed result for " + state.currentId);
}
applyDecision(out, currentPreset());
markSelectedCard(state.currentId);
return out;
}
function loadAndShow(scenarioId) {
let loaded;
if (state.engine) {
loaded = parsePyJson(state.engine.load_preset(scenarioId));
} else {
const pack = state.precomputed || {};
loaded = (pack.presets && pack.presets[scenarioId]) || null;
if (!loaded) {
throw new Error("Unknown scenario: " + scenarioId);
}
}
state.currentId = loaded.id;
$("preset").value = loaded.id;
$("trace").value = loaded.trace;
$("policy").value = loaded.policy;
$("note").textContent = loaded.note;
return loaded;
}
function selectScenario(scenarioId, shouldEvaluate = true) {
const loaded = loadAndShow(scenarioId);
if (shouldEvaluate) evaluateCurrent();
markSelectedCard(scenarioId);
return loaded;
}
function markSelectedCard(scenarioId) {
document.querySelectorAll(".scen").forEach((card) => {
card.setAttribute("aria-pressed", card.dataset.id === scenarioId ? "true" : "false");
});
}
function visiblePresets() {
const presets = state.info.presets;
const filter = state.filter;
return presets.filter((item) => {
if (filter === "all") return true;
if (filter === "attack") return item.group === "attack";
if (filter === "benign") return item.group === "benign";
return item.tag === filter;
});
}
function renderGallery() {
const attacks = $("gallery-attacks");
const benign = $("gallery-benign");
attacks.innerHTML = "";
benign.innerHTML = "";
const items = visiblePresets();
const attackItems = items.filter((item) => item.group === "attack");
const benignItems = items.filter((item) => item.group === "benign");
$("attack-heading").textContent = `Attacks (${attackItems.length})`;
$("benign-heading").textContent = `Benign controls (${benignItems.length})`;
$("attack-heading").hidden = attackItems.length === 0;
$("benign-heading").hidden = benignItems.length === 0;
for (const item of attackItems) attacks.appendChild(scenarioCard(item));
for (const item of benignItems) benign.appendChild(scenarioCard(item));
markSelectedCard(state.currentId);
}
function scenarioCard(item) {
const button = document.createElement("button");
button.type = "button";
button.className = "scen";
button.dataset.id = item.id;
button.setAttribute("aria-pressed", "false");
button.innerHTML = `
${escapeHtml(item.title)}
${escapeHtml(item.id)}
${escapeHtml(item.description)}
${escapeHtml(item.expected)}
${escapeHtml(item.tag)}
${item.severity && item.severity !== "benign" ? `${escapeHtml(item.severity)}` : ""}
`;
button.addEventListener("click", () => {
selectScenario(item.id, true);
$("verdict-card").scrollIntoView({ block: "start", behavior: "smooth" });
});
return button;
}
function renderFilters() {
const root = $("filters");
root.innerHTML = "";
const attackCount = state.info.attack_count;
const benignCount = state.info.benign_count;
const options = [
{ id: "all", label: `All ${state.info.scenario_count}` },
{ id: "attack", label: `Attacks ${attackCount}` },
{ id: "benign", label: `Benign ${benignCount}` },
...state.info.tags.map((tag) => ({ id: tag, label: tag })),
];
for (const option of options) {
const button = document.createElement("button");
button.type = "button";
button.className = "filter";
button.dataset.filter = option.id;
button.textContent = option.label;
button.setAttribute("aria-pressed", option.id === state.filter ? "true" : "false");
button.addEventListener("click", () => {
state.filter = option.id;
renderFilters();
renderGallery();
});
root.appendChild(button);
}
}
function fillPresetSelect() {
const preset = $("preset");
preset.innerHTML = "";
const custom = document.createElement("option");
custom.value = "custom";
custom.textContent = "Custom trace (edit JSON below)";
preset.appendChild(custom);
for (const item of state.info.presets) {
const option = document.createElement("option");
option.value = item.id;
option.textContent = item.label;
preset.appendChild(option);
}
}
async function runAllWithProgress() {
const ids = state.info.presets.map((item) => item.id);
const wrap = $("corpus-progress-wrap");
const bar = $("corpus-bar");
const label = $("corpus-progress");
const matrix = $("corpus-matrix");
const summary = $("corpus-summary");
wrap.hidden = false;
matrix.hidden = false;
$("corpus-legend").hidden = false;
matrix.innerHTML = "";
const cells = {};
for (const id of ids) {
const cell = document.createElement("button");
cell.type = "button";
cell.className = "cell";
cell.dataset.id = id;
cell.title = id;
cell.setAttribute("aria-label", id);
cell.addEventListener("click", () => {
selectScenario(id, true);
$("verdict-card").scrollIntoView({ block: "start", behavior: "smooth" });
});
matrix.appendChild(cell);
cells[id] = cell;
}
const setProgress = (done, total) => {
const pct = total === 0 ? 0 : (done / total) * 100;
bar.classList.toggle("is-complete", done >= total && total > 0);
bar.style.width = `${pct}%`;
label.textContent = `${done} / ${total}`;
};
const results = [];
$("run-all").disabled = true;
setProgress(0, ids.length);
for (let index = 0; index < ids.length; index += 1) {
const id = ids[index];
const out = demo.evaluateScenario(id);
const expected = state.info.presets.find((item) => item.id === id).expected;
const match = out.verdict === expected && out.integrity === "passed";
const row = {
id,
expected,
actual: out.verdict,
match,
reason: out.reason,
integrity: out.integrity,
};
results.push(row);
cells[id].dataset.state = match ? `match-${out.verdict}` : "mismatch";
cells[id].title = `${id}: expected ${expected}, got ${out.verdict}, integrity ${out.integrity}`;
setProgress(index + 1, ids.length);
await new Promise((resolve) => setTimeout(resolve, 0));
}
setProgress(ids.length, ids.length);
const failed = results.filter((row) => !row.match);
const counts = { ALLOW: 0, BLOCK: 0, REQUIRE_APPROVAL: 0 };
for (const row of results) counts[row.actual] = (counts[row.actual] || 0) + 1;
summary.textContent = failed.length === 0
? `${results.length}/${results.length} expected verdicts. Integrity passed on every envelope. Verdicts produced on this official corpus: ${counts.ALLOW} ALLOW, ${counts.BLOCK} BLOCK, ${counts.REQUIRE_APPROVAL} REQUIRE_APPROVAL. These counts describe this corpus only.`
: `${results.length - failed.length}/${results.length} matched. ${failed.length} mismatch or integrity failure. Verdicts produced: ${counts.ALLOW} ALLOW, ${counts.BLOCK} BLOCK, ${counts.REQUIRE_APPROVAL} REQUIRE_APPROVAL.`;
$("run-all").disabled = false;
return {
total: results.length,
passed: results.length - failed.length,
failed: failed.length,
failures: failed,
results,
counts,
};
}
function applyTheme(theme) {
const root = document.documentElement;
if (theme === "light" || theme === "dark") {
root.dataset.theme = theme;
} else {
delete root.dataset.theme;
theme = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
}
const next = theme === "dark" ? "light" : "dark";
$("theme-toggle").textContent = `Switch to ${next} theme`;
$("theme-toggle").setAttribute("aria-pressed", theme === "dark" ? "true" : "false");
}
function initTheme() {
const saved = localStorage.getItem("asc-theme");
applyTheme(saved === "light" || saved === "dark" ? saved : "");
$("theme-toggle").addEventListener("click", () => {
const current = document.documentElement.dataset.theme
|| (window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
const next = current === "dark" ? "light" : "dark";
localStorage.setItem("asc-theme", next);
applyTheme(next);
});
}
async function fetchText(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.status}`);
return response.text();
}
async function fetchBytes(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.status}`);
return new Uint8Array(await response.arrayBuffer());
}
async function startFallback(message) {
const started = performance.now();
setProgress(30, "Loading precomputed official corpus results…", "loading");
const raw = await fetchText("./data/precomputed.json");
const pack = JSON.parse(raw);
state.precomputed = pack;
state.engine = null;
state.info = pack.info;
demo.evaluateTrace = null;
demo.evaluateScenario = function (scenarioId) {
return pack.results[scenarioId];
};
demo.runCorpus = function () { return pack.corpus_run; };
demo.tamperAndVerify = null;
demo.runAll = runAllWithProgress;
fillPresetSelect();
renderFilters();
renderGallery();
bindCommonUi(false);
selectScenario(state.info.default_preset, true);
setBusy(false);
$("evaluate").disabled = true;
$("recompute").disabled = true;
$("tamper").disabled = true;
$("run-all").disabled = false;
$("preset").disabled = false;
$("trace").disabled = false;
$("policy").disabled = false;
$("copy-envelope").disabled = false;
$("download-envelope").disabled = false;
const note = $("note");
if (note && pack.presets[state.info.default_preset]) {
note.textContent = pack.presets[state.info.default_preset].note + " Custom evaluation needs the live runtime.";
}
state.loadMs = Math.round(performance.now() - started);
document.body.dataset.loadMs = String(state.loadMs);
document.body.dataset.ascMode = "fallback";
setProgress(100, message, "fallback");
return { loadMs: state.loadMs, version: state.info.version, scenarioCount: state.info.scenario_count, mode: "fallback" };
}
let uiBound = false;
function bindCommonUi(live) {
if (uiBound) return;
uiBound = true;
$("preset").addEventListener("change", function () { selectScenario($("preset").value, false); });
$("evaluate").addEventListener("click", function () { evaluateCurrent(); });
$("recompute").addEventListener("click", function () {
if (!state.engine) return;
const out = parsePyJson(state.engine.recompute_digest($("policy").value));
$("policy").value = out.policy;
$("digest-message").hidden = false;
$("digest-message").textContent = out.message;
});
$("copy-envelope").addEventListener("click", async function () {
const status = $("copy-status");
try {
await navigator.clipboard.writeText(state.lastEnvelope || $("envelope").textContent);
status.hidden = false;
status.textContent = "Envelope JSON copied.";
} catch (error) {
status.hidden = false;
status.textContent = "Copy failed: " + formatError(error);
}
});
$("download-envelope").addEventListener("click", function () {
const blob = new Blob([state.lastEnvelope || $("envelope").textContent], { type: "application/json" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "asc-envelope-" + (state.currentId || "custom") + ".json";
link.click();
URL.revokeObjectURL(link.href);
});
$("tamper").addEventListener("click", function () {
if (!demo.tamperAndVerify) return;
const result = demo.tamperAndVerify(state.originalEnvelope || state.lastEnvelope, "reason");
$("tamper-result").hidden = false;
$("restore-envelope").hidden = false;
if (result.detected) {
$("tamper-result").textContent = "The library rejected the edited envelope. verify_envelope: " + result.error;
$("envelope").textContent = result.envelope_text;
state.lastEnvelope = result.envelope_text;
const envMeta = $("envelope-meta");
envMeta.innerHTML = "";
envMeta.appendChild(chip("Integrity check failed", "integrity-bad"));
envMeta.appendChild(chip("Field tampered: reason", ""));
} else {
$("tamper-result").textContent = "The verifier did not reject this edit. The tamper control was not shown as a successful detection.";
}
});
$("restore-envelope").addEventListener("click", function () {
$("envelope").textContent = state.originalEnvelope;
state.lastEnvelope = state.originalEnvelope;
$("tamper-result").hidden = true;
$("restore-envelope").hidden = true;
const envMeta = $("envelope-meta");
envMeta.innerHTML = "";
envMeta.appendChild(chip("Integrity check passed", "integrity-ok"));
envMeta.appendChild(chip("Hash-checked, not signed", ""));
});
$("run-all").addEventListener("click", function () {
runAllWithProgress();
});
}
async function boot() {
const started = performance.now();
openExternalLinks();
initTheme();
if (forceFallback() || !canRunLiveRuntime()) {
return startFallback(FALLBACK_MESSAGE);
}
setProgress(8, "Loading Pyodide 0.29.5…");
const { loadPyodide } = await import(`${PYODIDE_INDEX}pyodide.mjs`);
setProgress(28, "Starting the in-browser Python runtime…");
const pyodide = await loadPyodide({ indexURL: PYODIDE_INDEX });
state.pyodide = pyodide;
setProgress(48, "Loading PyYAML and the bundled ASC v0.2.1 wheel…");
await pyodide.loadPackage(["pyyaml"]);
const [wheel, engineSrc, policyYaml, corpusJson] = await Promise.all([
fetchBytes(ASC_WHEEL),
fetchText("./engine.py"),
fetchText("./data/demo-agent.policy.yaml"),
fetchText("./data/corpus.json"),
]);
const mkdir = (path) => {
const info = pyodide.FS.analyzePath(path);
if (!info.exists) pyodide.FS.mkdir(path);
};
mkdir("/asc-pkg");
mkdir("/asc-data");
pyodide.FS.writeFile("/tmp/agent_security_contract-0.2.1-py3-none-any.whl", wheel);
pyodide.FS.writeFile("/asc-pkg/engine.py", engineSrc);
pyodide.FS.writeFile("/asc-data/policy.yaml", policyYaml);
pyodide.FS.writeFile("/asc-data/corpus.json", corpusJson);
setProgress(76, "Importing the Agent Security Contract library…");
pyodide.runPython(`
import os, sys, zipfile, pathlib
os.environ["ASC_COMMIT_SHA"] = "${ASC_COMMIT}"
dest = pathlib.Path("/asc-pkg")
with zipfile.ZipFile("/tmp/agent_security_contract-0.2.1-py3-none-any.whl") as z:
z.extractall(dest)
if "/asc-pkg" not in sys.path:
sys.path.insert(0, "/asc-pkg")
import asc
if asc.__version__ != "0.2.1":
raise RuntimeError(f"unexpected ASC version: {asc.__version__}")
import engine
policy = pathlib.Path("/asc-data/policy.yaml").read_text(encoding="utf-8")
corpus = pathlib.Path("/asc-data/corpus.json").read_text(encoding="utf-8")
INIT_INFO = engine.init(policy, corpus)
`);
const engine = pyodide.pyimport("engine");
state.engine = engine;
state.info = parsePyJson(pyodide.globals.get("INIT_INFO"));
demo.evaluateTrace = (scenarioId, traceText, policyText) => parsePyJson(engine.evaluate_trace(scenarioId, traceText, policyText));
demo.evaluateScenario = (scenarioId) => parsePyJson(engine.evaluate_scenario(scenarioId));
demo.runCorpus = () => parsePyJson(engine.run_corpus());
demo.tamperAndVerify = (envelopeText, field = "reason") => parsePyJson(engine.tamper_and_verify(envelopeText, field));
demo.runAll = runAllWithProgress;
fillPresetSelect();
renderFilters();
renderGallery();
bindCommonUi(true);
selectScenario(state.info.default_preset, true);
setBusy(false);
document.body.dataset.ascMode = "live";
state.loadMs = Math.round(performance.now() - started);
document.body.dataset.loadMs = String(state.loadMs);
setProgress(
100,
`Ready in ${(state.loadMs / 1000).toFixed(1)}s. Pyodide ${PYODIDE_VERSION} (Python 3.13.2), ASC v${state.info.version}. Evaluation stays in this browser.`,
"ready",
);
return { loadMs: state.loadMs, version: state.info.version, scenarioCount: state.info.scenario_count };
}
demo.ready = boot().catch((error) => {
console.error(error);
return startFallback(fallbackMessage(error)).catch((fallbackError) => {
console.error(fallbackError);
setProgress(100, "Failed to start the in-browser runtime, and precomputed results could not be loaded. Open this page on a current desktop browser.", "error");
throw error;
});
});