Spaces:
Running
Running
Download app.js from evalstate/tool-research-v3: direct link, hf CLI and curl.
- Browser
- Download file 79.8 kB
-
https://huggingface.co/spaces/evalstate/tool-research-v3/resolve/main/app.js
- Command line
-
hf download hf://spaces/evalstate/tool-research-v3/app.js
-
curl -L -o app.js https://huggingface.co/spaces/evalstate/tool-research-v3/resolve/main/app.js
79.8 kB
/* Tool call pipeline: v3 causal pair workbench */
import { REPORT_DATA } from "./data.js";
import {
normalizeToolsInput,
renderAnnotatedPrompt,
renderToolReturnTurn,
buildModelReply,
} from "./renderers.js";
const MODELS = REPORT_DATA.models;
const MBY = Object.fromEntries(MODELS.map(m => [m.key, m]));
const PRESETS = REPORT_DATA.presets;
const SHARED = REPORT_DATA.sharedExcerpts || {};
const REPOS = (REPORT_DATA.meta && REPORT_DATA.meta.repos) || {};
const CURATED_MODELS = [
{ key: "qwen38", name: "Qwen3.8", sub: "XML tags" },
{ key: "gptoss", name: "gpt-oss", sub: "Harmony TS" },
{ key: "gemma4", name: "Gemma 4", sub: "Custom DSL" },
{ key: "mistral4", name: "Mistral L4", sub: "Bracket tokens" },
{ key: "kimi26", name: "Kimi K2.6", sub: "TS helper" },
{ key: "kimi31", name: "Kimi K3.1", sub: "Python XTML" },
{ key: "deepseek41", name: "DeepSeek V4.1", sub: "Typed DSML" },
{ key: "minimax31", name: "MiniMax M3.1", sub: "Recursive XML" },
];
const EXTRA_MODELS = [
{ key: "glm53", name: "GLM-5.3", sub: "arg_key XML" },
{ key: "inkling2", name: "Inkling 2", sub: "Content tokens" },
{ key: "beam", name: "Beam 1.0", sub: "Harmony + XML" },
{ key: "glimmer", name: "Glimmer", sub: "ATEM XML" },
{ key: "hy4", name: "Hy4", sub: "Namespaced XML" },
];
const CURATED_KEYS = new Set(CURATED_MODELS.map(x => x.key));
const EXTRA_BY_KEY = Object.fromEntries(EXTRA_MODELS.map(x => [x.key, x]));
const SHORT_LABELS = Object.fromEntries([...CURATED_MODELS, ...EXTRA_MODELS].map(x => [x.key, x.name]));
const STAGES = [
{
id: 1,
label: "Wrap tool",
summary: "Your client wraps the MCP tool in a <code>tools</code> array. Nothing model-specific has happened yet.",
cta: "Next: render the prompt",
},
{
id: 2,
label: "Render prompt",
summary: "The chat template turns that JSON into text. This is the only description of your tool the model ever sees.",
cta: "Next: generate tokens",
},
{
id: 3,
label: "Generate tokens",
summary: "The model continues the prompt one token at a time until it emits a stop token.",
cta: "Next: parse the response",
},
{
id: 4,
label: "Parse response",
summary: "The serving engine finds the call in the text and rewrites it as structured <code>tool_calls</code>.",
cta: "Next: continue the turn",
},
{
id: 5,
label: "Continue turn",
summary: "Your client runs the tool, and the template renders the result into the next prompt.",
cta: "Compare all 13 models",
},
];
const ICO_COPY = '<svg class="ico" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="7" y="7" width="9" height="9" rx="1.5"></rect><path d="M4 13V5a1.5 1.5 0 0 1 1.5-1.5H13"></path></svg>';
const ICO_CHECK = '<svg class="ico" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="4.5 10.5 8.5 14.5 15.5 6.5"></polyline></svg>';
const ICO_RESET = '<svg class="ico" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4.5 10a5.5 5.5 0 1 0 1.4-3.7"></path><polyline points="4.5 3.5 4.5 7.5 8.5 7.5"></polyline></svg>';
const ICO_CHEV = '<svg viewBox="0 0 18 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="1" y1="6" x2="14" y2="6"></line><polyline points="10.5 2.5 14.5 6 10.5 9.5"></polyline></svg>';
const S = {
view: "workbench", // "workbench" | "compare"
compareScope: "curated", // "curated" | "all"
moreOpen: false,
model: MODELS[0].key,
stage: 1, // 1..5
prevStage: 1,
api: "chat", // "chat" | "messages"
reply: "tool", // "tool" | "text"
tool: "search", // "search" | "ticket"
engine: "vllm", // "vllm" | "sglang" | "llama" | "input"
tmplFile: "main", // "main" | "helper"
leftView: { 2: "template", 4: "parser", 5: "call" },
rightView: { 5: "annotated" },
fieldsOpen: false,
visited: new Set([1]),
stage3Visited: false,
playMode: "play", // "play" | "step" | "all"
shown: 0,
timer: null,
deb: null,
text: "",
edited: false,
parseError: null,
parsed: null,
lastGood: null,
norm: null,
mapPath: p => p,
activePath: null,
ann: null,
annKey: "",
out: null,
outKey: "",
turn: null,
turnKey: "",
prevModelLines: null,
flashModelChange: false,
};
const $ = id => document.getElementById(id);
const esc = s => String(s ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
const sha7 = s => String(s || "").slice(0, 7);
const M = () => MBY[S.model] || MODELS[0];
const P = () => PRESETS[S.tool] || PRESETS.search;
const tools = () => (S.norm && S.norm.tools) || P().tools;
const reducedMotion = () => window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const SELFTEST = new URLSearchParams(location.search).has("selftest");
/* =========================================================================
JSON span parser & canonical path mapping
========================================================================= */
function parseSpans(text) {
let i = 0;
const spans = [];
const ws = () => { while (i < text.length && /\s/.test(text[i])) i++; };
const fail = msg => { const e = new Error(msg); e.pos = i; throw e; };
const str = () => {
const s = i;
i++;
while (i < text.length && text[i] !== '"') {
if (text[i] === "\\") i++;
i++;
}
if (i >= text.length) fail("Unterminated string");
i++;
try { return [JSON.parse(text.slice(s, i)), s, i]; }
catch { i = s; fail("Bad string escape"); }
};
function val(path) {
ws();
const c = text[i];
if (c === "{") {
i++;
const o = {};
ws();
if (text[i] === "}") { i++; return o; }
for (;;) {
ws();
if (text[i] !== '"') fail("Expected a quoted key");
const [k, ks, ke] = str();
const p = path ? path + "." + k : k;
spans.push({ path: p, kind: "key", s: ks, e: ke });
ws();
if (text[i] !== ":") fail("Expected ':'");
i++;
o[k] = val(p);
ws();
if (text[i] === ",") { i++; continue; }
if (text[i] === "}") { i++; return o; }
fail("Expected ',' or '}'");
}
}
if (c === "[") {
i++;
const a = [];
ws();
if (text[i] === "]") { i++; return a; }
for (let n = 0; ; n++) {
a.push(val(path ? path + "." + n : String(n)));
ws();
if (text[i] === ",") { i++; continue; }
if (text[i] === "]") { i++; return a; }
fail("Expected ',' or ']'");
}
}
if (c === '"') {
const [v, s, e] = str();
spans.push({ path, kind: "val", s, e });
return v;
}
const m = /^(-?\d+(\.\d+)?([eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));
if (!m) fail(i >= text.length ? "Unexpected end of input" : "Unexpected character");
const s = i;
i += m[0].length;
spans.push({ path, kind: "val", s, e: i });
return JSON.parse(m[0]);
}
const v = val("");
ws();
if (i < text.length) fail("Trailing text after JSON");
return { value: v, spans };
}
function makePathMap(value) {
const wrapped = value && !Array.isArray(value) && Array.isArray(value.tools);
const list = Array.isArray(value) ? value : wrapped ? value.tools : [value];
const pre = idx => Array.isArray(value) ? String(idx) : wrapped ? `tools.${idx}` : "";
const join = (...parts) => parts.filter(x => x !== "" && x != null).join(".");
return canon => {
const m = /^(\d+)\.function(?:\.(.*))?$/.exec(canon || "");
if (!m) return canon;
const idx = +m[1];
const rest = m[2] || "";
const raw = list[idx] || {};
if (raw && raw.function) return join(pre(idx), "function", rest);
if (raw && raw.input_schema !== undefined) return join(pre(idx), rest.replace(/^parameters(?=\.|$)/, "input_schema"));
if (raw && raw.inputSchema !== undefined) return join(pre(idx), rest.replace(/^parameters(?=\.|$)/, "inputSchema"));
return join(pre(idx), rest);
};
}
const shortPathOf = p => String(p || "")
.replace(/^(tools\.)?\d+\./, "")
.replace(/^function\./, "")
.replace(/^(parameters|inputSchema|input_schema)\.properties\./, "")
.replace(/\.properties\./g, ".");
/* =========================================================================
Tool shape conversions (MCP <-> Chat Completions <-> Messages)
========================================================================= */
const toMcp = t => {
const f = (t && t.function) || t || {};
const o = { name: f.name || "tool" };
if (f.description !== undefined) o.description = f.description;
o.inputSchema = f.parameters || f.inputSchema || f.input_schema || { type: "object", properties: {} };
return o;
};
const toMessages = t => {
const f = (t && t.function) || t || {};
const o = { name: f.name || "tool" };
if (f.description !== undefined) o.description = f.description;
o.input_schema = f.parameters || f.inputSchema || f.input_schema || { type: "object", properties: {} };
return o;
};
const toOpenAI = t => ({ type: "function", function: (t && t.function) || t });
function shapeTools(ts, target) {
if (target === "mcp") return ts.map(toMcp);
if (target === "messages") return ts.map(toMessages);
return ts.map(toOpenAI);
}
function mcpPreset(toolId = S.tool) {
const ts = (PRESETS[toolId] || PRESETS.search).tools;
return ts.length === 1 ? toMcp(ts[0]) : ts.map(toMcp);
}
function maybeConvertToMcp(text) {
let v;
try { v = JSON.parse(text); } catch { return null; }
if (!v || typeof v !== "object") return null;
const isCleanSingleMcp = !Array.isArray(v) && !v.tools && !v.function && !v.result &&
typeof v.name === "string" && v.inputSchema !== undefined &&
v.input_schema === undefined && v.parameters === undefined;
if (isCleanSingleMcp) return null;
let list = null;
if (v.result && Array.isArray(v.result.tools)) list = v.result.tools;
else if (Array.isArray(v.tools)) list = v.tools;
else if (Array.isArray(v)) list = v;
else if (v.function || v.input_schema !== undefined || v.parameters !== undefined ||
(typeof v.name === "string" && v.inputSchema !== undefined)) {
list = [v];
}
if (!list || !list.length) return null;
try {
const norm = normalizeToolsInput(list);
if (!norm.tools || !norm.tools.length) return null;
const mcpList = norm.tools.map(toMcp);
const out = mcpList.length === 1 ? mcpList[0] : mcpList;
return JSON.stringify(out, null, 2);
} catch {
return null;
}
}
function acceptToolText(text, isPreset = false) {
const clean = String(text || "").replace(/\u00a0/g, " ");
S.text = clean;
try {
const parsed = parseSpans(clean);
const norm = normalizeToolsInput(parsed.value);
if (!norm.tools || !norm.tools.length) throw new Error("Expected at least one tool with a name");
S.parsed = parsed;
S.lastGood = parsed;
S.norm = norm;
S.mapPath = makePathMap(parsed.value);
S.parseError = null;
S.edited = !isPreset;
invalidateCaches();
return true;
} catch (e) {
S.parseError = e.message || "Invalid JSON";
S.edited = true;
return false;
}
}
function loadPreset(toolId) {
S.tool = toolId;
const text = JSON.stringify(mcpPreset(toolId), null, 2);
acceptToolText(text, true);
}
/* =========================================================================
Caret helpers & cached model computations
========================================================================= */
function caretOffset(el) {
const sel = getSelection();
if (!sel || !sel.rangeCount || !el.contains(sel.anchorNode)) return null;
const r = sel.getRangeAt(0).cloneRange();
r.selectNodeContents(el);
r.setEnd(sel.anchorNode, sel.anchorOffset);
return r.toString().length;
}
function setCaret(el, off) {
const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
let n;
let acc = 0;
while ((n = w.nextNode())) {
if (acc + n.length >= off) {
const r = document.createRange();
r.setStart(n, Math.max(0, off - acc));
r.collapse(true);
const sel = getSelection();
sel.removeAllRanges();
sel.addRange(r);
return;
}
acc += n.length;
}
}
function invalidateCaches() {
S.ann = null;
S.annKey = "";
S.out = null;
S.outKey = "";
S.turn = null;
S.turnKey = "";
}
function mapAnnotated(a) {
if (!a) return null;
return {
...a,
fields: (a.fields || []).map(f => ({ ...f, path: S.mapPath(f.path) })),
regions: (a.regions || []).map(r => ({
...r,
segments: (r.segments || []).map(g => g.path ? { ...g, path: S.mapPath(g.path) } : g),
})),
};
}
function getAnn(modelKey = S.model) {
const key = `${modelKey}|${S.tool}|${S.text}`;
if (modelKey === S.model && S.ann && S.annKey === key) return S.ann;
const raw = renderAnnotatedPrompt(modelKey, tools(), P().userPrompt);
const mapped = mapAnnotated(raw);
if (modelKey === S.model) {
S.ann = mapped;
S.annKey = key;
}
return mapped;
}
function getOut(modelKey = S.model, reply = S.reply) {
const mode = reply === "tool" ? "call" : "text";
const key = `${modelKey}|${mode}|${S.tool}|${S.text}`;
if (modelKey === S.model && reply === S.reply && S.out && S.outKey === key) return S.out;
const res = buildModelReply(modelKey, tools(), mode, S.tool);
if (modelKey === S.model && reply === S.reply) {
S.out = res;
S.outKey = key;
}
return res;
}
function getTurn(modelKey = S.model) {
const key = `${modelKey}|${S.tool}|${S.text}`;
if (modelKey === S.model && S.turn && S.turnKey === key) return S.turn;
const out = getOut(modelKey, "tool");
let args = P().sampleArgs;
try {
if (out && out.parsedToolCall) args = JSON.parse(out.parsedToolCall.function.arguments);
} catch { /* fall back to preset args */ }
const res = renderToolReturnTurn(modelKey, tools(), P().userPrompt, args, P().sampleToolResult);
if (modelKey === S.model) {
S.turn = res;
S.turnKey = key;
}
return res;
}
/* =========================================================================
Live track signatures (recomputed on model / API / reply / edit change)
========================================================================= */
function firstNonEmptyLine(text) {
const lines = String(text || "").split("\n").map(l => l.trim()).filter(Boolean);
return lines[0] || "";
}
function computeTrackSignatures() {
const sig1 = S.api === "messages" ? "POST /v1/messages" : "POST /v1/chat/completions";
let sig2 = "<tools>";
try {
const ann = getAnn();
const schemaReg = (ann.regions || []).find(r => r.kind === "schema");
const schemaText = schemaReg ? (schemaReg.segments || []).map(g => g.text).join("") : "";
sig2 = firstNonEmptyLine(schemaText) || firstNonEmptyLine(ann.rawPrompt) || "rendered prompt";
} catch { sig2 = "prompt"; }
let sig3 = "";
let sig4 = "";
try {
const out = getOut();
const pieces = out.pieces || [];
const callPiece = pieces.find(p => p.kind === "tok-call" || p.kind === "marker")
|| pieces.find(p => p.kind === "text" && p.text.trim())
|| pieces[0];
if (callPiece) {
const idx = pieces.indexOf(callPiece);
const joined = pieces.slice(idx, idx + 3).map(p => p.text).join("").replace(/\s+/g, " ").trim();
sig3 = joined || callPiece.text.trim();
}
if (S.api === "messages") {
sig4 = `stop_reason: "${out.messagesStopReason}"`;
} else {
sig4 = `finish_reason: "${out.apiFinishReason}"`;
}
} catch {
sig3 = "tokens";
sig4 = S.api === "messages" ? 'stop_reason: "tool_use"' : 'finish_reason: "tool_calls"';
}
let sig5 = "no tool call";
if (S.reply === "tool") {
try {
const tr = getTurn();
const respSegs = (tr.segments || []).filter(g => g.part === "tool_response");
const respText = respSegs.map(g => g.text).join("");
const respLines = respText.split("\n").map(l => l.trim()).filter(Boolean);
sig5 = respLines.find(l => /tool|obs|func|result|return/i.test(l)) || respLines[0] || "tool_response";
} catch {
sig5 = "tool_response";
}
}
return [sig1, sig2, sig3, sig4, sig5];
}
/* =========================================================================
Request builder & JSON / Prompt / Source highlighters
========================================================================= */
function buildRequest(api = S.api) {
const user = [{ role: "user", content: P().userPrompt }];
const ts = tools();
if (api === "messages") {
return {
model: M().id,
max_tokens: 1024,
messages: user,
tools: shapeTools(ts, "messages"),
tool_choice: { type: "auto" },
};
}
return {
model: M().id,
messages: user,
tools: shapeTools(ts, "openai"),
tool_choice: "auto",
};
}
function reqPathToEditor(reqPath) {
const m = /^tools\.(\d+)\.(?:function\.)?(.*)$/.exec(reqPath || "");
if (!m) return null;
const idx = m[1];
const rest = m[2];
const canon = `${idx}.function.${rest.replace(/^input_schema(?=\.|$)/, "parameters")}`;
return S.mapPath(canon);
}
function droppedSet() {
const set = new Set();
try {
const ann = getAnn();
for (const f of ann.fields || []) {
if (f.status === "dropped") set.add(f.path);
}
} catch { /* ignore */ }
return set;
}
function normalizeRolePath(path) {
if (!path) return "";
let p = String(path);
p = p.replace(/^(?:tools\.)?\d+\.(?:function\.)?/, "");
p = p.replace(/^function\./, "");
p = p.replace(/^(?:parameters|input_schema)(?=\.|$)/, "inputSchema");
return p;
}
function roleOfEditorPath(path, kind = "val") {
const p = normalizeRolePath(path);
if (!p) return null;
if (p === "name") return kind === "val" ? "name" : null;
if (p === "description" || /\.description$/.test(p)) return kind === "val" ? "desc" : null;
if (/(?:^|\.)properties\.[^.]+$/.test(p)) return kind === "key" ? "param" : null;
if (p === "inputSchema.type") return null;
if (/\.(?:type|enum|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|pattern|format|default|additionalProperties|required)(?:\.|$)/.test(p)) {
return kind === "val" ? "cons" : null;
}
return null;
}
function hiliteXmlTags(escapedText) {
return escapedText.replace(
/(<\/?(?:tools|tool_call|tool_calls|tool_response|function|parameter|IMPORTANT|arg_key|arg_value|call|invoke)(?:=[^&<>]*?)?>)/g,
'<span class="r-xml">$1</span>'
);
}
function paintEditorHTML(text, spans) {
if (!spans || !spans.length) return esc(text);
const dropped = droppedSet();
let html = "";
let pos = 0;
for (const sp of spans) {
if (sp.s > pos) html += `<span class="jp">${esc(text.slice(pos, sp.s))}</span>`;
const raw = text.slice(sp.s, sp.e);
const role = roleOfEditorPath(sp.path, sp.kind);
const cls = role ? `r-${role}` : (sp.kind === "key" ? "r-key" : "r-env");
const dropCls = dropped.has(sp.path) ? " is-dropped" : "";
html += `<span class="tr-span ${cls}${dropCls}" data-path="${esc(sp.path)}">${esc(raw)}</span>`;
pos = sp.e;
}
if (pos < text.length) html += `<span class="jp">${esc(text.slice(pos))}</span>`;
return html;
}
function renderJsonWithTrace(obj, mapFn = null, hotKey = null, hotValCls = "") {
return renderJsonTextWithTrace(JSON.stringify(obj, null, 2), mapFn, hotKey, hotValCls);
}
function renderJsonTextWithTrace(text, mapFn = null, hotKey = null, hotValCls = "") {
let spans = [];
try { spans = parseSpans(text).spans; } catch { return esc(text); }
const dropped = droppedSet();
let html = "";
let pos = 0;
for (const sp of spans) {
if (sp.s > pos) html += `<span class="jp">${esc(text.slice(pos, sp.s))}</span>`;
const raw = text.slice(sp.s, sp.e);
const mapped = mapFn ? mapFn(sp.path) : null;
let baseCls;
if (mapFn) {
const role = mapped ? roleOfEditorPath(mapped, sp.kind) : null;
baseCls = role ? `r-${role}` : (sp.kind === "key" ? "r-key" : "r-env");
} else {
baseCls = sp.kind === "key" ? "jk" : raw[0] === '"' ? "js" : "jn";
}
const isHot = hotKey && (sp.path === hotKey || sp.path.endsWith("." + hotKey));
const isArg = hotValCls && (sp.path.includes(".arguments") || sp.path.includes(".input."));
const extraCls = isHot ? ` ${hotValCls}` : isArg && sp.kind === "val" ? " tok-arg" : "";
const dropCls = mapped && dropped.has(mapped) ? " is-dropped" : "";
const attr = mapped ? ` data-path="${esc(mapped)}"` : "";
html += `<span class="tr-span ${baseCls}${extraCls}${dropCls}"${attr}>${esc(raw)}</span>`;
pos = sp.e;
}
if (pos < text.length) html += `<span class="jp">${esc(text.slice(pos))}</span>`;
return html;
}
function fmtInlineToks(raw) {
return String(raw ?? "").split("<|\"|>" ).map(esc).join('<span class="tok">◁"▷</span>');
}
function renderSegHTML(g, regionKind = "") {
if (g.k === "tok") {
const title = g.tokenId != null ? ` title="Token ID ${esc(g.tokenId)}"` : "";
return `<span class="tok"${title}>${esc(g.text)}</span>`;
}
if (g.k === "s") {
const role = g.role || roleOfEditorPath(g.path, "val") || roleOfEditorPath(g.path, "key");
const roleCls = role ? ` r-${role}` : "";
const attr = g.path ? ` data-path="${esc(g.path)}"` : "";
return `<span class="tr-span${roleCls}"${attr}>${fmtInlineToks(g.text)}</span>`;
}
if (regionKind === "schema") {
return `<span class="r-scaf">${fmtInlineToks(g.text)}</span>`;
}
if (regionKind === "tmpl") {
return hiliteXmlTags(esc(g.text));
}
return esc(g.text);
}
function renderAnnotatedRegions(regions) {
return (regions || []).map(r => {
const inner = (r.segments || []).map(g => renderSegHTML(g, r.kind || "")).join("");
const sub = r.sub ? `<span class="region-sub">${esc(r.sub)}</span>` : "";
return `<div class="region" data-region="${esc(r.kind || "")}"><div class="region-head"><span class="region-label">${esc(r.label || r.kind || "")}</span>${sub}</div><pre class="region-code">${inner || '<span class="jc">(empty)</span>'}</pre></div>`;
}).join("");
}
function renderSchemaExcerpt(ann) {
const schemaReg = (ann.regions || []).find(r => r.kind === "schema");
if (!schemaReg) return `<pre class="code-well">${esc(ann.rawPrompt || "")}</pre>`;
const inner = (schemaReg.segments || []).map(g => renderSegHTML(g, "schema")).join("");
return `<pre class="code-well">${inner}</pre>`;
}
function hiliteTemplateLine(line, isPy) {
const e = esc(line);
if (isPy) return /^\s*#/.test(line) ? `<span class="jc">${e}</span>` : e;
return e
.replace(/(\{#.*?#\})/g, '<span class="jc">$1</span>')
.replace(/(\{%-?|-?%\}|\{\{-?|-?\}\})/g, '<span class="jd">$1</span>');
}
function renderNumberedLines(src, startLine = 1, hlSet = null, isPy = false) {
const lines = String(src || "").split("\n");
return `<div class="code-lines">${lines.map((line, i) => {
const ln = startLine + i;
const isHl = hlSet && hlSet.has(ln);
return `<div class="cl${isHl ? " hl" : ""}" data-line="${ln}"><span class="cl-n">${ln}</span><span class="cl-t">${hiliteTemplateLine(line, isPy) || " "}</span></div>`;
}).join("")}</div>`;
}
function renderRepoFooterHTML() {
const items = [
["transformers", REPOS.transformers],
["vLLM", REPOS.vllm],
["SGLang", REPOS.sglang],
["llama.cpp", REPOS.llama_cpp],
].filter(([, r]) => r && r.url);
if (!items.length) return "";
const links = items.map(([label, r]) =>
`<a href="${esc(r.url)}" target="_blank" rel="noopener noreferrer">${esc(label)} @ ${esc(r.shortSha || sha7(r.sha))}</a>`
).join(" · ");
return `<span>Pinned sources: ${links}</span>`;
}
function tmplFiles(m) {
const files = [{
id: "main",
name: m.templatePath || "chat_template.jinja",
src: m.chatTemplate || "",
url: m.templateUrl,
hl: m.templateToolLines,
}];
if (m.templateHelperSource) {
files.push({
id: "helper",
name: m.templateHelperPath || "helper.py",
src: m.templateHelperSource,
url: m.templateHelperUrl,
hl: null,
});
}
return files;
}
/* =========================================================================
Stage 1: Wrap tool (MCP editor <-> API request + model schema excerpt)
========================================================================= */
function renderStage1(preserveEditor = false, modelChanged = false) {
const m = M();
$("left-title").textContent = "Your MCP tool";
$("left-subrow").hidden = true;
$("left-actions").innerHTML = `
<div class="seg" id="ctl-preset" role="radiogroup" aria-label="Tool preset">
<button type="button" role="radio" data-v="search" aria-checked="${S.tool === "search"}">search_models</button>
<button type="button" role="radio" data-v="ticket" aria-checked="${S.tool === "ticket"}">create_ticket</button>
</div>
<button type="button" class="text-action is-muted" id="btn-reset-tool"${S.edited ? "" : " hidden"}>${ICO_RESET}<span>Reset</span></button>
`;
if (!preserveEditor || !$("mcp-editor")) {
$("left-body").className = "pane-body";
const spans = S.parseError ? null : (S.parsed && S.parsed.spans);
$("left-body").innerHTML = `
<div class="editor-wrap">
<div id="mcp-editor" class="json-editor" contenteditable="plaintext-only" spellcheck="false" role="textbox" aria-multiline="true" aria-label="MCP tool JSON editor">${paintEditorHTML(S.text, spans)}</div>
<div class="editor-err" id="editor-err"${S.parseError ? "" : " hidden"}>
<span id="editor-err-msg">${esc(S.parseError || "")}</span>
<button type="button" class="text-action" id="btn-reset-err">Reset</button>
</div>
</div>
`;
bindEditorEvents();
} else {
if (modelChanged && !S.parseError) {
const ed = $("mcp-editor");
if (ed) {
const focused = document.activeElement === ed;
const off = focused ? caretOffset(ed) : 0;
const spans = S.parsed && S.parsed.spans;
ed.innerHTML = paintEditorHTML(S.text, spans);
if (focused) setCaret(ed, off);
}
}
const errEl = $("editor-err");
if (errEl) {
errEl.hidden = !S.parseError;
const msgEl = $("editor-err-msg");
if (msgEl) msgEl.textContent = S.parseError || "";
}
}
$("right-title").textContent = "The request your client sends";
$("right-identity").textContent = `${m.label}, ${m.sub}`;
$("right-actions").innerHTML = `<button type="button" class="icon-btn" id="btn-copy-right">${ICO_COPY}<span>Copy</span></button>`;
$("fields-drawer").hidden = true;
const reqObj = buildRequest(S.api);
const endpoint = S.api === "messages" ? "POST /v1/messages" : "POST /v1/chat/completions";
const reqPreviewText = JSON.stringify(reqObj, null, 2).replace(
/"messages": \[\s*\{\s*"role": ("[^"]*"),\s*"content": ("(?:\\.|[^"\\])*")\s*\}\s*\]/,
'"messages": [{ "role": $1, "content": $2 }]'
);
const reqHtml = `<span class="jc">${esc(endpoint)}</span>\n${renderJsonTextWithTrace(reqPreviewText, reqPathToEditor)}`;
let excerptHtml = "";
try {
excerptHtml = renderSchemaExcerpt(getAnn());
} catch (e) {
excerptHtml = `<pre class="code-well"><span class="st-dropped">Could not render schema: ${esc(e.message)}</span></pre>`;
}
$("right-body").className = "pane-body is-split";
$("right-body").innerHTML = `
<div class="split-top">
<pre class="code-well">${reqHtml}</pre>
</div>
<div class="split-bar">
<span class="split-bar-title">What ${esc(m.label)} will read</span>
<button type="button" class="text-action" id="btn-open-full-prompt">Open full prompt</button>
</div>
<div class="split-bottom" id="stage1-excerpt">${excerptHtml}</div>
`;
}
/* =========================================================================
Stage 2: Render prompt (Chat template / API request <-> Annotated prompt)
========================================================================= */
function renderStage2() {
const m = M();
const mode = S.leftView[2] || "template";
$("left-title").textContent = "Chat template";
$("left-actions").innerHTML = `
<div class="seg" id="ctl-s2-left" role="radiogroup" aria-label="Stage 2 left view">
<button type="button" role="radio" data-v="template" aria-checked="${mode === "template"}">Template source</button>
<button type="button" role="radio" data-v="request" aria-checked="${mode === "request"}">API request</button>
</div>
`;
$("left-body").className = "pane-body";
if (mode === "template") {
const files = tmplFiles(m);
if (!files.some(f => f.id === S.tmplFile)) S.tmplFile = "main";
const f = files.find(x => x.id === S.tmplFile) || files[0];
const hasLoop = Array.isArray(f.hl) && f.hl.length === 2;
const hlSet = new Set();
if (hasLoop) {
for (let ln = f.hl[0]; ln <= f.hl[1]; ln++) hlSet.add(ln);
}
if (files.length > 1 || hasLoop) {
$("left-subrow").hidden = false;
const tabsHtml = files.length > 1
? `<div class="subtabs" role="tablist" aria-label="Template files">${files.map(x =>
`<button type="button" class="subtab" role="tab" data-tfile="${esc(x.id)}" aria-selected="${x.id === S.tmplFile}">${esc(x.name)}</button>`
).join("")}</div>`
: `<span class="subtab" aria-selected="true">${esc(f.name)}${hasLoop ? ` (L${f.hl[0]}-${f.hl[1]})` : ""}</span>`;
const jumpHtml = hasLoop
? `<button type="button" class="text-action" id="btn-jump-loop">Jump to tool loop</button>`
: "";
$("left-subrow").innerHTML = `${tabsHtml}${jumpHtml}`;
} else {
$("left-subrow").hidden = true;
}
const isPy = /\.py$/.test(f.name);
const hubLink = f.url
? `<a href="${esc(f.url)}" target="_blank" rel="noopener noreferrer">${esc(m.id)} / ${esc(f.name)}</a>`
: `<span>${esc(f.name)}</span>`;
$("left-body").innerHTML = `
${renderNumberedLines(f.src, 1, hlSet, isPy)}
<div class="pane-foot-meta">${hubLink}${renderRepoFooterHTML()}</div>
`;
if (hasLoop) {
requestAnimationFrame(() => scrollLineIntoView($("left-body"), f.hl[0]));
}
} else {
$("left-subrow").hidden = true;
const reqObj = buildRequest(S.api);
const endpoint = S.api === "messages" ? "POST /v1/messages" : "POST /v1/chat/completions";
$("left-body").innerHTML = `<pre class="code-well"><span class="jc">${esc(endpoint)}</span>\n${renderJsonWithTrace(reqObj, reqPathToEditor)}</pre>`;
}
const ann = getAnn();
const fields = ann.fields || [];
const total = fields.length;
const kept = fields.filter(f => f.status !== "dropped").length;
const dropped = total - kept;
const arrow = S.fieldsOpen ? "▴" : "▾";
const countCls = dropped > 0 ? "text-action st-dropped" : "text-action";
$("right-title").textContent = `The prompt ${SHORT_LABELS[m.key] || m.label} sees`;
$("right-identity").textContent = `${m.label}, ${m.sub}`;
$("right-actions").innerHTML = `
<button type="button" class="${countCls}" id="btn-fields-toggle" aria-expanded="${S.fieldsOpen}">
${kept} of ${total} fields kept ${arrow}
</button>
`;
if (S.fieldsOpen) {
$("fields-drawer").hidden = false;
$("fields-drawer").innerHTML = `
<table class="fields-table">
<thead>
<tr>
<th scope="col">Field</th>
<th scope="col">Status</th>
<th scope="col">In prompt</th>
</tr>
</thead>
<tbody>
${fields.map(f => {
const stCls = f.status === "dropped" ? "st-dropped" : f.status === "rewritten" ? "st-rewritten" : "st-kept";
const stLabel = f.status === "dropped" ? "Dropped" : f.status === "rewritten" ? "Rewritten" : "Kept";
const note = f.status === "dropped"
? `Dropped by ${m.label}'s chat template`
: (f.inPrompt || f.valuePreview || f.note || "Preserved");
return `<tr class="fields-row" data-path="${esc(f.path)}"><td class="field-path">${esc(shortPathOf(f.path))}</td><td class="${stCls}">${stLabel}</td><td>${esc(note)}</td></tr>`;
}).join("")}
</tbody>
</table>
`;
} else {
$("fields-drawer").hidden = true;
}
$("right-body").className = "pane-body";
$("right-body").innerHTML = renderAnnotatedRegions(ann.regions);
}
function scrollLineIntoView(container, lineNum) {
if (!container) return;
const target = container.querySelector(`.cl[data-line="${lineNum}"]`);
if (!target) return;
const delta = target.getBoundingClientRect().top - container.getBoundingClientRect().top - 12;
container.scrollTop = Math.max(0, container.scrollTop + delta);
}
/* =========================================================================
Stage 3: Generate tokens (Prompt boundary <-> Emitted token stream)
========================================================================= */
function stopTimer() {
if (S.timer) {
clearInterval(S.timer);
S.timer = null;
}
}
function renderStage3(autoPlay = false) {
const m = M();
$("left-title").textContent = "Prompt, up to the generation point";
$("left-actions").innerHTML = "";
$("left-subrow").hidden = true;
$("left-body").className = "pane-body";
const ann = getAnn();
$("left-body").innerHTML = renderAnnotatedRegions(ann.regions);
requestAnimationFrame(() => {
const lb = $("left-body");
if (lb) lb.scrollTop = lb.scrollHeight;
});
$("right-title").textContent = "Tokens the model emits";
$("right-identity").textContent = `${m.label}, ${m.sub}`;
$("fields-drawer").hidden = true;
const out = getOut();
const totalPieces = (out.pieces || []).length;
if (reducedMotion() || SELFTEST) {
S.playMode = "all";
S.shown = totalPieces;
stopTimer();
} else if (autoPlay && !S.stage3Visited) {
S.stage3Visited = true;
S.playMode = "play";
S.shown = 0;
} else if (S.shown > totalPieces || S.shown === 0) {
S.shown = totalPieces;
S.playMode = "all";
}
$("right-actions").innerHTML = `
<div class="seg" id="ctl-play" role="radiogroup" aria-label="Token playback">
<button type="button" role="radio" data-v="play" aria-checked="${S.playMode === "play"}">Play</button>
<button type="button" role="radio" data-v="step" aria-checked="${S.playMode === "step"}">Step</button>
<button type="button" role="radio" data-v="all" aria-checked="${S.playMode === "all"}">All</button>
</div>
`;
$("right-body").className = "pane-body is-split";
$("right-body").innerHTML = `
<div class="split-bottom" id="stream-scroll"><pre class="code-well" id="token-stream"></pre></div>
<div class="verdict-bar" id="stream-verdict"></div>
`;
paintTokenStream();
if (S.playMode === "play" && S.shown < totalPieces && !reducedMotion() && !SELFTEST) {
startPlayback();
}
}
function paintTokenStream() {
const out = getOut();
const pieces = out.pieces || [];
const count = Math.min(S.shown, pieces.length);
const el = $("token-stream");
if (!el) return;
const html = pieces.slice(0, count).map((p, idx) => {
const arrive = idx === count - 1 && S.playMode !== "all" ? " tok-arrive" : "";
const title = p.tokenId != null ? ` title="Token ID ${esc(p.tokenId)}"` : "";
if (p.kind === "tok-stop" || p.kind === "stop") return `<span class="tok-stop${arrive}"${title}>${esc(p.text)}</span>`;
if (p.kind === "tok-call") return `<span class="tok-call${arrive}"${title}>${esc(p.text)}</span>`;
if (p.kind === "tok") return `<span class="tok${arrive}"${title}>${esc(p.text)}</span>`;
if (p.kind === "think") return `<span class="tok-think${arrive}">${esc(p.text)}</span>`;
if (p.kind === "marker") return `<span class="tok-marker${arrive}">${esc(p.text)}</span>`;
return `<span class="${arrive ? "tok-arrive" : ""}">${esc(p.text)}</span>`;
}).join("");
const done = count >= pieces.length;
const stopHtml = done && out.stopToken && !pieces.some(p => p.text === out.stopToken)
? `<span class="tok-stop" title="Token ID ${esc(out.stopTokenId ?? "")}">${esc(out.stopToken)}</span>`
: "";
el.innerHTML = html + stopHtml;
const verdict = $("stream-verdict");
if (verdict) {
const finKey = S.api === "messages" ? "stop_reason" : "finish_reason";
const finVal = S.api === "messages" ? out.messagesStopReason : out.apiFinishReason;
const stopId = out.stopTokenId != null ? ` (ID ${out.stopTokenId})` : "";
const statusText = done
? `Stopped on <code>${esc(out.stopToken || "EOS")}</code>${esc(stopId)}. Engine reports <code>stop</code>; parser maps this turn to <code>${finKey}: "${esc(finVal)}"</code>.`
: `Streaming token chunk ${count} of ${pieces.length}.`;
verdict.innerHTML = statusText;
}
}
function startPlayback() {
stopTimer();
const out = getOut();
const total = (out.pieces || []).length;
if (!total) return;
const interval = Math.max(18, Math.min(28, Math.floor(2400 / total)));
S.timer = setInterval(() => {
S.shown = Math.min(total, S.shown + 1);
paintTokenStream();
if (S.shown >= total) {
stopTimer();
}
}, interval);
}
/* =========================================================================
Stage 4: Parse response (Engine parser / Raw tokens <-> API response JSON)
========================================================================= */
function renderExcerptBlock(ex, headingPrefix = "") {
if (!ex) return "";
const hlSet = new Set(ex.hl || []);
const title = headingPrefix ? `${headingPrefix}: ${ex.path}` : ex.path;
const range = ex.start && ex.end ? `L${ex.start}-${ex.end}` : "";
const link = ex.url
? `<a class="excerpt-link" href="${esc(ex.url)}" target="_blank" rel="noopener noreferrer">${esc(title)}</a>`
: `<span class="excerpt-link">${esc(title)}</span>`;
const note = ex.note ? `<p class="excerpt-note">${esc(ex.note)}</p>` : "";
const isPy = /\.py$/.test(ex.path || "");
return `
<div class="excerpt-block">
<div class="excerpt-head">${link}<span class="excerpt-lines">${esc(range)}</span></div>
${note}
${renderNumberedLines(ex.code || "", ex.start || 1, hlSet, isPy)}
</div>
`;
}
function renderStage4() {
const m = M();
const mode = S.leftView[4] || "parser";
$("left-title").textContent = "Engine parser";
$("left-actions").innerHTML = `
<div class="seg" id="ctl-s4-left" role="radiogroup" aria-label="Stage 4 left view">
<button type="button" role="radio" data-v="parser" aria-checked="${mode === "parser"}">Parser source</button>
<button type="button" role="radio" data-v="raw" aria-checked="${mode === "raw"}">Raw tokens</button>
</div>
`;
$("left-body").className = "pane-body";
const out = getOut();
if (mode === "parser") {
$("left-subrow").hidden = false;
const engines = [
["vllm", "vLLM"],
["sglang", "SGLang"],
["llama", "llama.cpp"],
["input", "Input"],
];
$("left-subrow").innerHTML = `
<div class="subtabs" id="eng-tabs" role="tablist" aria-label="Serving engine">
${engines.map(([id, label]) =>
`<button type="button" class="subtab" role="tab" data-eng="${id}" aria-selected="${S.engine === id}">${label}</button>`
).join("")}
</div>
`;
const ex = m.excerpts || {};
let blocks = "";
if (S.engine === "vllm") {
blocks = (ex.vllm || []).map(x => renderExcerptBlock(x, `${m.label} parser`)).join("")
+ renderExcerptBlock(SHARED.vllm_finish_reason, "Finish-reason rewrite");
} else if (S.engine === "sglang") {
blocks = (ex.sglang || []).map(x => renderExcerptBlock(x, `${m.label} detector`)).join("")
+ renderExcerptBlock(SHARED.sglang_finish_reason, "Finish-reason rewrite");
} else if (S.engine === "llama") {
blocks = renderExcerptBlock(SHARED.llama_cpp_finish, "End of generation to finish_reason")
+ `<p class="plain-note">llama.cpp parses calls in C++ per template family. When generation stops and tool calls were extracted, the OpenAI server path rewrites the finish reason to tool_calls.</p>`;
} else {
blocks = renderExcerptBlock(SHARED.transformers_input, "transformers")
+ renderExcerptBlock(SHARED.vllm_input, "vLLM input path");
}
const steps = S.reply === "tool" ? (m.lane || []) : (m.laneText || []);
const stepsHtml = steps.length
? `<div class="steps-section"><h3 class="steps-heading">Expected parse steps (${S.reply === "tool" ? "tool call" : "plain text"})</h3><ol class="parse-steps">${steps.map(st => `<li>${esc(st)}</li>`).join("")}</ol></div>`
: "";
$("left-body").innerHTML = `${blocks}${stepsHtml}<div class="pane-foot-meta">${renderRepoFooterHTML()}</div>`;
} else {
$("left-subrow").hidden = true;
const pieces = out.pieces || [];
const html = pieces.map(p => {
if (p.kind === "tok-stop" || p.kind === "stop") return `<span class="tok-stop">${esc(p.text)}</span>`;
if (p.kind === "tok-call") return `<span class="tok-call">${esc(p.text)}</span>`;
if (p.kind === "tok") return `<span class="tok">${esc(p.text)}</span>`;
if (p.kind === "think") return `<span class="tok-think">${esc(p.text)}</span>`;
if (p.kind === "marker") return `<span class="tok-marker">${esc(p.text)}</span>`;
return esc(p.text);
}).join("");
$("left-body").innerHTML = `<pre class="code-well">${html}</pre>`;
}
$("right-title").textContent = "The response your client gets";
$("right-identity").textContent = `${m.label}, ${m.sub}`;
$("right-actions").innerHTML = `<button type="button" class="icon-btn" id="btn-copy-right">${ICO_COPY}<span>Copy</span></button>`;
$("fields-drawer").hidden = true;
const respObj = S.api === "messages" ? out.messagesResponseJson : out.responseJson;
const hotKey = S.api === "messages" ? "stop_reason" : "finish_reason";
const hotCls = S.reply === "tool" ? "tok-call" : "tok";
$("right-body").className = "pane-body";
$("right-body").innerHTML = `<pre class="code-well">${renderJsonWithTrace(respObj, null, hotKey, hotCls)}</pre>`;
}
/* =========================================================================
Stage 5: Continue turn (Call + result <-> Second prompt)
========================================================================= */
const TURN_PARTS = {
assistant_call: ["Assistant call", "rebuilt from tool_calls"],
tool_response: ["Client tool result", "role: tool"],
next_gen: ["Generation prompt", "model continues here"],
};
function renderStage5() {
const m = M();
const pr = P();
const leftMode = S.leftView[5] || "call";
const rightMode = S.rightView[5] || "annotated";
$("left-title").textContent = "Tool call and result";
$("left-subrow").hidden = true;
$("left-actions").innerHTML = `
<div class="seg" id="ctl-s5-left" role="radiogroup" aria-label="Stage 5 left view">
<button type="button" role="radio" data-v="call" aria-checked="${leftMode === "call"}">Call and result</button>
<button type="button" role="radio" data-v="template" aria-checked="${leftMode === "template"}">Template source</button>
</div>
`;
if (leftMode === "template") {
$("left-body").className = "pane-body";
const f = tmplFiles(m)[0];
const isPy = /\.py$/.test(f.name);
$("left-body").innerHTML = `${renderNumberedLines(f.src, 1, null, isPy)}<div class="pane-foot-meta">${renderRepoFooterHTML()}</div>`;
} else if (S.reply === "text") {
$("left-body").className = "pane-body";
$("left-body").innerHTML = `<p class="plain-note">The model replied with plain text and emitted no tool call, so your client did not run any tool on this turn.</p>`;
} else {
const out = getOut();
const callPayload = S.api === "messages"
? (out.messagesResponseJson.content || []).find(c => c.type === "tool_use") || out.parsedToolCall
: { tool_calls: out.parsedToolCall ? [out.parsedToolCall] : [] };
$("left-body").className = "pane-body is-split";
$("left-body").innerHTML = `
<div class="split-half-top">
<pre class="code-well">${renderJsonWithTrace(callPayload, null, null, "tok-arg")}</pre>
</div>
<div class="split-bar">
<span class="split-bar-title">Client tool result</span>
</div>
<div class="split-half-bottom">
<pre class="code-well">${renderJsonWithTrace(pr.sampleToolResult)}</pre>
</div>
`;
}
$("right-title").textContent = "The second prompt";
$("right-identity").textContent = `${m.label}, ${m.sub}`;
$("fields-drawer").hidden = true;
$("right-actions").innerHTML = `
<div class="seg" id="ctl-s5-right" role="radiogroup" aria-label="Stage 5 right view">
<button type="button" role="radio" data-v="annotated" aria-checked="${rightMode === "annotated"}">Annotated</button>
<button type="button" role="radio" data-v="full" aria-checked="${rightMode === "full"}">Full transcript</button>
</div>
`;
$("right-body").className = "pane-body";
if (S.reply === "text") {
const out = getOut();
const ann = getAnn();
const textReply = out.assistantContent || pr.textReply || "";
if (rightMode === "full") {
$("right-body").innerHTML = `<pre class="code-well">${esc(ann.rawPrompt + textReply + (out.stopToken || ""))}</pre>`;
} else {
$("right-body").innerHTML = `
<div class="region">
<div class="region-head"><span class="region-label">Plain assistant reply</span><span class="region-sub">no tool turn needed</span></div>
<pre class="region-code">${esc(textReply)}<span class="tok-stop">${esc(out.stopToken || "")}</span></pre>
</div>
<p class="plain-note">The next turn starts with a fresh user message rather than a tool result block.</p>
`;
}
return;
}
try {
const tr = getTurn();
if (rightMode === "full") {
$("right-body").innerHTML = `<pre class="code-well">${esc(tr.rawFullPrompt || "")}</pre>`;
} else {
const groups = [];
for (const g of tr.segments || []) {
const last = groups[groups.length - 1];
if (last && last.kind === g.part) {
last.segments.push(g);
} else {
const meta = TURN_PARTS[g.part] || [g.part, ""];
groups.push({ kind: g.part, label: meta[0], sub: meta[1], segments: [g] });
}
}
if (!groups.some(x => x.kind === "next_gen")) {
groups.push({ kind: "next_gen", label: TURN_PARTS.next_gen[0], sub: TURN_PARTS.next_gen[1], segments: [] });
}
$("right-body").innerHTML = renderAnnotatedRegions(groups);
}
} catch (e) {
$("right-body").innerHTML = `<p class="plain-note"><span class="st-dropped">Could not render Turn 2: ${esc(e.message)}</span></p>`;
}
}
/* =========================================================================
Chrome: Model rail, pipeline track, footer, Compare view
========================================================================= */
function updateMoreButton() {
const btn = $("rail-more-btn");
if (!btn) return;
const extra = EXTRA_BY_KEY[S.model];
const line1 = extra ? `${extra.name} ▾` : `More (${EXTRA_MODELS.length}) ▾`;
const line2 = extra ? extra.sub : "other variants";
btn.classList.toggle("is-active", Boolean(extra));
btn.setAttribute("aria-expanded", String(S.moreOpen));
btn.innerHTML = `<span class="rail-name" data-label="${esc(line1)}">${esc(line1)}</span><span class="rail-sub">${esc(line2)}</span>`;
}
function renderMoreMenu() {
const menu = $("rail-more-menu");
if (!menu) return;
menu.innerHTML = EXTRA_MODELS.map(item => {
const m = MBY[item.key];
if (!m) return "";
const cur = S.model === item.key ? " is-current" : "";
return `
<button type="button" class="more-item${cur}" role="menuitem" data-model="${esc(item.key)}">
<span class="more-item-name">${esc(m.label)}</span>
<span class="more-item-sub">${esc(m.sub)}</span>
</button>
`;
}).join("");
}
function positionMoreMenu() {
const btn = $("rail-more-btn");
const menu = $("rail-more-menu");
if (!btn || !menu || menu.hidden) return;
const r = btn.getBoundingClientRect();
const mw = Math.max(menu.offsetWidth || 280, 280);
const top = Math.round(r.bottom + 6);
const left = Math.max(8, Math.min(window.innerWidth - mw - 8, Math.round(r.right - mw)));
menu.style.top = `${top}px`;
menu.style.left = `${left}px`;
}
function openMoreMenu() {
const menu = $("rail-more-menu");
if (!menu) return;
S.moreOpen = true;
renderMoreMenu();
menu.hidden = false;
updateMoreButton();
positionMoreMenu();
}
function closeMoreMenu() {
const menu = $("rail-more-menu");
if (!menu || !S.moreOpen) return;
S.moreOpen = false;
menu.hidden = true;
updateMoreButton();
}
function renderModelRail() {
const rail = $("model-rail");
const indicator = $("rail-indicator");
rail.querySelectorAll(".rail-tab").forEach(el => el.remove());
for (const item of CURATED_MODELS) {
const m = MBY[item.key];
if (!m) continue;
const on = item.key === S.model;
const btn = document.createElement("button");
btn.type = "button";
btn.className = "rail-tab";
btn.setAttribute("role", "tab");
btn.dataset.model = item.key;
btn.title = `${m.label}, ${m.sub}`;
btn.setAttribute("aria-label", `${m.label}, ${item.sub}`);
btn.setAttribute("aria-selected", String(on));
btn.tabIndex = on ? 0 : -1;
btn.innerHTML = `<span class="rail-name" data-label="${esc(item.name)}">${esc(item.name)}</span><span class="rail-sub">${esc(item.sub)}</span>`;
rail.insertBefore(btn, indicator);
}
const moreBtn = document.createElement("button");
moreBtn.type = "button";
moreBtn.id = "rail-more-btn";
moreBtn.className = "rail-tab rail-more";
moreBtn.setAttribute("aria-haspopup", "true");
moreBtn.setAttribute("aria-expanded", "false");
moreBtn.setAttribute("aria-controls", "rail-more-menu");
rail.insertBefore(moreBtn, indicator);
updateMoreButton();
renderMoreMenu();
positionRailIndicator(false);
}
function positionRailIndicator(scrollInto = true) {
const rail = $("model-rail");
const indicator = $("rail-indicator");
const active = rail && (
rail.querySelector('.rail-tab[aria-selected="true"]') ||
rail.querySelector('.rail-more.is-active')
);
if (!rail || !indicator || !active) return;
const x = active.offsetLeft;
const w = active.offsetWidth;
indicator.style.transform = `translateX(${x}px) scaleX(${w})`;
if (scrollInto && rail.scrollWidth > rail.clientWidth) {
active.scrollIntoView({ behavior: reducedMotion() ? "auto" : "smooth", block: "nearest", inline: "center" });
}
}
function renderTrack() {
const sigs = computeTrackSignatures();
const list = $("track-list");
let html = "";
STAGES.forEach((st, idx) => {
const isActive = st.id === S.stage;
const isVisited = S.visited.has(st.id);
if (idx > 0) {
html += `<li class="track-sep" aria-hidden="true">${ICO_CHEV}</li>`;
}
html += `
<li class="track-item${isActive ? " is-active" : ""}">
<button type="button" class="track-btn${isVisited ? " is-visited" : ""}" role="tab" data-stage="${st.id}" aria-selected="${isActive}" tabindex="${isActive ? 0 : -1}">
<span class="track-label"><span class="track-num">${st.id}</span><span class="track-text">. ${esc(st.label)}</span></span>
<span class="track-sig">${esc(sigs[idx])}</span>
</button>
</li>
`;
});
list.innerHTML = html;
}
function renderFooter() {
const st = STAGES[S.stage - 1] || STAGES[0];
$("footer-summary").innerHTML = st.summary;
$("btn-back").hidden = S.stage === 1;
$("btn-next-label").textContent = st.cta;
}
function renderWorkbench(opts = {}) {
const { preserveEditor = false, stageChanged = false, modelChanged = false } = opts;
stopTimer();
renderTrack();
renderFooter();
if (S.stage === 1) renderStage1(preserveEditor, modelChanged);
else if (S.stage === 2) renderStage2();
else if (S.stage === 3) renderStage3(stageChanged);
else if (S.stage === 4) renderStage4();
else renderStage5();
if (stageChanged && !reducedMotion()) {
const dir = S.stage >= S.prevStage ? "enter-fwd" : "enter-back";
for (const id of ["left-body", "right-body"]) {
const el = $(id);
if (!el) continue;
el.classList.remove("enter-fwd", "enter-back");
void el.offsetWidth;
el.classList.add(dir);
}
}
if (modelChanged && !reducedMotion()) {
const rb = $("right-body");
if (rb) {
rb.classList.remove("diff-flash");
void rb.offsetWidth;
rb.classList.add("diff-flash");
}
}
applyLit();
}
function renderCompare() {
const pr = P();
const tbody = $("compare-tbody");
const list = S.compareScope === "all"
? MODELS
: CURATED_MODELS.map(c => MBY[c.key]).filter(Boolean);
const titleEl = $("compare-title");
if (titleEl) {
titleEl.textContent = S.compareScope === "all"
? "How all 13 models write the same tool call"
: "How 8 diverse models write the same tool call";
}
const rows = list.map(m => {
const ann = renderAnnotatedPrompt(m.key, pr.tools, pr.userPrompt);
const schemaReg = (ann.regions || []).find(r => r.kind === "schema");
const schemaText = schemaReg ? (schemaReg.segments || []).map(g => g.text).join("").trim() : "";
const out = buildModelReply(m.key, pr.tools, "call", S.tool);
const callStartIdx = (out.pieces || []).findIndex(p => p.kind === "tok-call" || p.kind === "marker");
const callExcerpt = (out.pieces || [])
.slice(callStartIdx >= 0 ? callStartIdx : 0, (callStartIdx >= 0 ? callStartIdx : 0) + 6)
.map(p => p.text)
.join("")
.trim();
const fields = ann.fields || [];
const dropped = fields.filter(f => f.status === "dropped");
const keptCount = fields.length - dropped.length;
const statusHtml = dropped.length === 0
? `<span class="cmp-status-ok">${keptCount} of ${fields.length}</span>`
: `<span class="cmp-status-drop">${keptCount} of ${fields.length}</span><span class="cmp-dropped-list">Dropped: ${esc(dropped.map(d => shortPathOf(d.path)).join(", "))}</span>`;
return `
<tr data-cmp-model="${esc(m.key)}" class="${m.key === S.model ? "is-current" : ""}" tabindex="0" role="link" aria-label="Inspect ${esc(m.label)} in Stage 2">
<td>
<span class="cmp-model-name">${esc(m.label)}</span>
<span class="cmp-model-sub">${esc(m.sub)}</span>
</td>
<td><pre class="cmp-code">${esc(schemaText.slice(0, 180))}</pre></td>
<td><pre class="cmp-code">${esc(callExcerpt.slice(0, 180))}</pre></td>
<td><span class="cmp-stop">${esc(out.stopToken || m.stopTokenCall || m.eosToken || "")}</span></td>
<td>${statusHtml}</td>
</tr>
`;
}).join("");
tbody.innerHTML = rows;
$("compare-repos").innerHTML = renderRepoFooterHTML();
document.querySelectorAll("#cmp-scope button").forEach(b => {
b.setAttribute("aria-checked", String(b.dataset.v === S.compareScope));
});
document.querySelectorAll("#cmp-tool button").forEach(b => {
b.setAttribute("aria-checked", String(b.dataset.v === S.tool));
});
}
function syncTopBar() {
const isCmp = S.view === "compare";
document.body.classList.toggle("is-workbench", !isCmp);
document.body.classList.toggle("is-compare", isCmp);
$("model-rail-wrap").hidden = isCmp;
$("track-bar").hidden = isCmp;
$("workbench").hidden = isCmp;
$("compare-view").hidden = !isCmp;
$("ctl-reply").hidden = isCmp;
$("nav-workbench").classList.toggle("is-active", !isCmp);
$("nav-compare").classList.toggle("is-active", isCmp);
$("nav-workbench").setAttribute("aria-current", isCmp ? "false" : "page");
$("nav-compare").setAttribute("aria-current", isCmp ? "page" : "false");
document.querySelectorAll("#ctl-api button").forEach(b => {
b.setAttribute("aria-checked", String(b.dataset.v === S.api));
});
document.querySelectorAll("#ctl-reply button").forEach(b => {
b.setAttribute("aria-checked", String(b.dataset.v === S.reply));
});
}
/* =========================================================================
Bi-directional field trace, editor events, clipboard
========================================================================= */
function applyLit() {
const path = S.activePath;
document.querySelectorAll(".tr-span.is-lit, .fields-row.is-lit").forEach(el => {
el.classList.remove("is-lit");
});
if (!path) return;
document.querySelectorAll("[data-path]").forEach(el => {
if (el.dataset.path === path) el.classList.add("is-lit");
});
}
function setLit(path) {
if (S.activePath === path) return;
S.activePath = path;
applyLit();
}
function detectCaretPath(editor) {
if (!S.parsed || !S.parsed.spans) return null;
const off = caretOffset(editor);
if (off == null) return null;
for (const sp of S.parsed.spans) {
if (off >= sp.s && off <= sp.e) return sp.path;
}
return null;
}
function handleEditorText(rawText, convertPasted = false) {
let nextText = rawText;
let converted = false;
if (convertPasted) {
const mcp = maybeConvertToMcp(rawText);
if (mcp) {
nextText = mcp;
converted = true;
}
}
const ok = acceptToolText(nextText, false);
const ed = $("mcp-editor");
if (converted && ed) {
ed.innerHTML = paintEditorHTML(S.text, S.parsed ? S.parsed.spans : null);
}
const resetBtn = $("btn-reset-tool");
if (resetBtn) resetBtn.hidden = !S.edited;
renderStage1(true);
renderTrack();
if (ok) applyLit();
}
function bindEditorEvents() {
const ed = $("mcp-editor");
if (!ed) return;
ed.addEventListener("input", () => {
clearTimeout(S.deb);
S.deb = setTimeout(() => {
const off = caretOffset(ed);
const raw = ed.innerText;
const ok = acceptToolText(raw, false);
if (ok && S.parsed) {
ed.innerHTML = paintEditorHTML(S.text, S.parsed.spans);
if (off != null) setCaret(ed, off);
}
const resetBtn = $("btn-reset-tool");
if (resetBtn) resetBtn.hidden = !S.edited;
renderStage1(true);
renderTrack();
setLit(detectCaretPath(ed));
}, 80);
});
ed.addEventListener("paste", ev => {
const clip = ev.clipboardData && ev.clipboardData.getData("text/plain");
if (!clip) return;
const mcp = maybeConvertToMcp(clip);
if (mcp) {
ev.preventDefault();
handleEditorText(mcp, false);
ed.innerHTML = paintEditorHTML(S.text, S.parsed ? S.parsed.spans : null);
setCaret(ed, 0);
}
});
const syncCaret = () => setLit(detectCaretPath(ed));
ed.addEventListener("keyup", syncCaret);
ed.addEventListener("click", syncCaret);
ed.addEventListener("keydown", ev => {
if (ev.key === "Escape") {
ev.preventDefault();
const activeTrack = document.querySelector('.track-btn[aria-selected="true"]');
if (activeTrack) activeTrack.focus();
}
});
}
function copyRightPane(btn) {
let payload = "";
if (S.stage === 1) {
payload = JSON.stringify(buildRequest(S.api), null, 2);
} else if (S.stage === 4) {
const out = getOut();
const obj = S.api === "messages" ? out.messagesResponseJson : out.responseJson;
payload = JSON.stringify(obj, null, 2);
}
if (!payload) return;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(payload).catch(() => {});
}
if (btn) {
btn.innerHTML = `${ICO_CHECK}<span>Copied</span>`;
setTimeout(() => {
btn.innerHTML = `${ICO_COPY}<span>Copy</span>`;
}, 1200);
}
}
/* =========================================================================
State transitions & hash persistence (replaceState, never pushState)
========================================================================= */
function writeHash() {
if (SELFTEST) return;
const params = new URLSearchParams();
if (S.view === "compare") {
params.set("view", "compare");
params.set("tool", S.tool);
params.set("api", S.api);
} else {
params.set("m", S.model);
params.set("s", String(S.stage));
params.set("api", S.api);
params.set("reply", S.reply);
params.set("tool", S.tool);
params.set("e", S.engine);
}
const next = "#" + params.toString();
if (location.hash !== next) {
history.replaceState(null, "", next);
}
}
function readHash() {
const raw = location.hash.replace(/^#/, "");
if (!raw) return;
const params = new URLSearchParams(raw);
if (params.get("view") === "compare") S.view = "compare";
const m = params.get("m");
if (m && MBY[m]) S.model = m;
const s = Number(params.get("s"));
if (s >= 1 && s <= 5) {
S.stage = s;
S.prevStage = s;
for (let i = 1; i <= s; i++) S.visited.add(i);
}
const api = params.get("api");
if (api === "chat" || api === "messages") S.api = api;
const reply = params.get("reply");
if (reply === "tool" || reply === "text") S.reply = reply;
const tool = params.get("tool");
if (tool && PRESETS[tool]) S.tool = tool;
const eng = params.get("e");
if (["vllm", "sglang", "llama", "input"].includes(eng)) S.engine = eng;
}
function setModel(key) {
if (!MBY[key] || S.model === key) return;
S.model = key;
S.tmplFile = "main";
closeMoreMenu();
invalidateCaches();
document.querySelectorAll('.rail-tab[role="tab"]').forEach(tab => {
const on = tab.dataset.model === key;
tab.setAttribute("aria-selected", String(on));
tab.tabIndex = on ? 0 : -1;
});
updateMoreButton();
renderMoreMenu();
positionRailIndicator(true);
if (S.view === "workbench") renderWorkbench({ preserveEditor: S.stage === 1, modelChanged: true });
else renderCompare();
writeHash();
}
function setCompareScope(scope) {
if (scope !== "curated" && scope !== "all") return;
S.compareScope = scope;
if (S.view === "compare") renderCompare();
}
function setStage(stageNum) {
const next = Math.max(1, Math.min(5, Number(stageNum) || 1));
const changed = next !== S.stage || S.view !== "workbench";
S.prevStage = S.stage;
S.stage = next;
S.visited.add(next);
S.view = "workbench";
syncTopBar();
renderWorkbench({ stageChanged: changed });
positionRailIndicator(false);
writeHash();
}
function setView(view) {
S.view = view === "compare" ? "compare" : "workbench";
closeMoreMenu();
stopTimer();
syncTopBar();
if (S.view === "compare") {
renderCompare();
} else {
renderWorkbench();
positionRailIndicator(false);
}
writeHash();
}
function setApi(api) {
if (api !== "chat" && api !== "messages") return;
S.api = api;
syncTopBar();
if (S.view === "workbench") renderWorkbench({ preserveEditor: S.stage === 1 });
writeHash();
}
function setReply(reply) {
if (reply !== "tool" && reply !== "text") return;
S.reply = reply;
invalidateCaches();
syncTopBar();
if (S.view === "workbench") renderWorkbench({ preserveEditor: S.stage === 1 });
writeHash();
}
function setTool(toolId) {
if (!PRESETS[toolId]) return;
loadPreset(toolId);
if (S.view === "workbench") renderWorkbench({ preserveEditor: false });
else renderCompare();
writeHash();
}
/* =========================================================================
Event wiring & keyboard shortcuts
========================================================================= */
function bindEvents() {
$("nav-workbench").addEventListener("click", ev => {
ev.preventDefault();
setView("workbench");
});
$("nav-compare").addEventListener("click", ev => {
ev.preventDefault();
setView("compare");
});
$("ctl-api").addEventListener("click", ev => {
const btn = ev.target.closest("button[data-v]");
if (btn) setApi(btn.dataset.v);
});
$("ctl-reply").addEventListener("click", ev => {
const btn = ev.target.closest("button[data-v]");
if (btn) setReply(btn.dataset.v);
});
$("cmp-scope").addEventListener("click", ev => {
const btn = ev.target.closest("button[data-v]");
if (btn) setCompareScope(btn.dataset.v);
});
$("cmp-tool").addEventListener("click", ev => {
const btn = ev.target.closest("button[data-v]");
if (btn) setTool(btn.dataset.v);
});
$("model-rail").addEventListener("click", ev => {
if (ev.target.closest("#rail-more-btn")) {
if (S.moreOpen) closeMoreMenu();
else openMoreMenu();
return;
}
const tab = ev.target.closest('.rail-tab[role="tab"]');
if (tab && tab.dataset.model) {
closeMoreMenu();
setModel(tab.dataset.model);
}
});
$("rail-more-menu").addEventListener("click", ev => {
const item = ev.target.closest(".more-item[data-model]");
if (item) {
closeMoreMenu();
setModel(item.dataset.model);
}
});
document.addEventListener("click", ev => {
if (!S.moreOpen) return;
if (ev.target.closest("#rail-more-btn") || ev.target.closest("#rail-more-menu")) return;
closeMoreMenu();
});
$("model-rail").addEventListener("keydown", ev => {
if (ev.key !== "ArrowLeft" && ev.key !== "ArrowRight") return;
const tabs = [...document.querySelectorAll('.rail-tab[role="tab"]')];
const idx = tabs.findIndex(t => t.dataset.model === S.model);
if (idx < 0) return;
ev.preventDefault();
const nextIdx = (idx + (ev.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length;
setModel(tabs[nextIdx].dataset.model);
tabs[nextIdx].focus();
});
$("track-list").addEventListener("click", ev => {
const btn = ev.target.closest(".track-btn");
if (btn) setStage(Number(btn.dataset.stage));
});
$("track-list").addEventListener("keydown", ev => {
if (ev.key !== "ArrowLeft" && ev.key !== "ArrowRight") return;
ev.preventDefault();
const next = Math.max(1, Math.min(5, S.stage + (ev.key === "ArrowRight" ? 1 : -1)));
setStage(next);
const active = document.querySelector(`.track-btn[data-stage="${next}"]`);
if (active) active.focus();
});
$("btn-back").addEventListener("click", () => {
if (S.stage > 1) setStage(S.stage - 1);
});
$("btn-next").addEventListener("click", () => {
if (S.stage < 5) setStage(S.stage + 1);
else setView("compare");
});
$("workbench").addEventListener("click", ev => {
const t = ev.target;
const presetBtn = t.closest("#ctl-preset button[data-v]");
if (presetBtn) { setTool(presetBtn.dataset.v); return; }
if (t.closest("#btn-reset-tool") || t.closest("#btn-reset-err")) {
loadPreset(S.tool);
renderWorkbench({ preserveEditor: false });
return;
}
if (t.closest("#btn-open-full-prompt")) { setStage(2); return; }
const copyBtn = t.closest("#btn-copy-right");
if (copyBtn) { copyRightPane(copyBtn); return; }
const s2Left = t.closest("#ctl-s2-left button[data-v]");
if (s2Left) {
S.leftView[2] = s2Left.dataset.v;
renderStage2();
applyLit();
return;
}
const tfileBtn = t.closest("button[data-tfile]");
if (tfileBtn) {
S.tmplFile = tfileBtn.dataset.tfile;
renderStage2();
return;
}
if (t.closest("#btn-jump-loop")) {
const f = tmplFiles(M()).find(x => x.id === S.tmplFile);
if (f && Array.isArray(f.hl)) scrollLineIntoView($("left-body"), f.hl[0]);
return;
}
if (t.closest("#btn-fields-toggle")) {
S.fieldsOpen = !S.fieldsOpen;
renderStage2();
applyLit();
return;
}
const playBtn = t.closest("#ctl-play button[data-v]");
if (playBtn) {
const v = playBtn.dataset.v;
const total = (getOut().pieces || []).length;
S.playMode = v;
if (v === "all") {
stopTimer();
S.shown = total;
} else if (v === "step") {
stopTimer();
S.shown = S.shown >= total ? 1 : S.shown + 1;
} else {
S.shown = 0;
startPlayback();
}
document.querySelectorAll("#ctl-play button").forEach(b => {
b.setAttribute("aria-checked", String(b.dataset.v === S.playMode));
});
paintTokenStream();
return;
}
const s4Left = t.closest("#ctl-s4-left button[data-v]");
if (s4Left) {
S.leftView[4] = s4Left.dataset.v;
renderStage4();
return;
}
const engBtn = t.closest("button[data-eng]");
if (engBtn) {
S.engine = engBtn.dataset.eng;
renderStage4();
writeHash();
return;
}
const s5Left = t.closest("#ctl-s5-left button[data-v]");
if (s5Left) {
S.leftView[5] = s5Left.dataset.v;
renderStage5();
return;
}
const s5Right = t.closest("#ctl-s5-right button[data-v]");
if (s5Right) {
S.rightView[5] = s5Right.dataset.v;
renderStage5();
return;
}
const traceTarget = t.closest("[data-path]");
if (traceTarget && !t.closest("#mcp-editor")) {
setLit(traceTarget.dataset.path);
}
});
$("workbench").addEventListener("mouseover", ev => {
const el = ev.target.closest("[data-path]");
if (el && !ev.target.closest("#mcp-editor")) {
setLit(el.dataset.path);
}
});
$("workbench").addEventListener("mouseout", ev => {
if (ev.target.closest("[data-path]") && !ev.target.closest("#mcp-editor")) {
setLit(null);
}
});
$("compare-tbody").addEventListener("click", ev => {
const row = ev.target.closest("tr[data-cmp-model]");
if (!row) return;
S.model = row.dataset.cmpModel;
S.tmplFile = "main";
invalidateCaches();
renderModelRail();
setStage(2);
});
$("compare-tbody").addEventListener("keydown", ev => {
if (ev.key !== "Enter" && ev.key !== " ") return;
const row = ev.target.closest("tr[data-cmp-model]");
if (!row) return;
ev.preventDefault();
row.click();
});
window.addEventListener("keydown", ev => {
const elName = (document.activeElement && document.activeElement.tagName) || "";
const inEditor = document.activeElement && (
document.activeElement.isContentEditable ||
elName === "INPUT" ||
elName === "TEXTAREA" ||
elName === "SELECT"
);
if (ev.key === "Escape" && S.moreOpen) {
ev.preventDefault();
closeMoreMenu();
const mb = $("rail-more-btn");
if (mb) mb.focus();
return;
}
if (inEditor || ev.metaKey || ev.ctrlKey || ev.altKey) return;
if (ev.key >= "1" && ev.key <= "5") {
ev.preventDefault();
setStage(Number(ev.key));
} else if (ev.key === "n" || ev.key === "N" || (ev.key === "ArrowRight" && !document.activeElement.closest(".rail-scroll, .track-list"))) {
if (S.view === "workbench" && S.stage < 5) { ev.preventDefault(); setStage(S.stage + 1); }
} else if (ev.key === "p" || ev.key === "P" || (ev.key === "ArrowLeft" && !document.activeElement.closest(".rail-scroll, .track-list"))) {
if (S.view === "workbench" && S.stage > 1) { ev.preventDefault(); setStage(S.stage - 1); }
} else if (ev.key === "[" || ev.key === "]") {
ev.preventDefault();
const idx = MODELS.findIndex(m => m.key === S.model);
const next = (idx + (ev.key === "]" ? 1 : -1) + MODELS.length) % MODELS.length;
setModel(MODELS[next].key);
} else if (ev.key === "a" || ev.key === "A") {
ev.preventDefault();
setApi(S.api === "chat" ? "messages" : "chat");
} else if (ev.key === "r" || ev.key === "R") {
if (S.view === "workbench") {
ev.preventDefault();
setReply(S.reply === "tool" ? "text" : "tool");
}
}
});
window.addEventListener("resize", () => {
positionRailIndicator(false);
if (S.moreOpen) positionMoreMenu();
});
}
/* =========================================================================
Built-in ?selftest=1 verification suite
========================================================================= */
function runSelfTest() {
const errors = [];
const check = (cond, msg) => { if (!cond) errors.push(msg); };
try {
// 1. All 13 models x 2 presets across all 5 stages + Compare
for (const presetId of ["search", "ticket"]) {
setTool(presetId);
for (const m of MODELS) {
setModel(m.key);
for (let st = 1; st <= 5; st++) {
setStage(st);
check($("left-body").innerHTML.length > 10, `Empty left body on ${m.key}/${presetId}/s${st}`);
check($("right-body").innerHTML.length > 10, `Empty right body on ${m.key}/${presetId}/s${st}`);
}
}
setView("compare");
setCompareScope("curated");
check(document.querySelectorAll("#compare-tbody tr").length === 8, `Compare curated rows != 8 for ${presetId}`);
setCompareScope("all");
check(document.querySelectorAll("#compare-tbody tr").length === 13, `Compare all rows != 13 for ${presetId}`);
}
setCompareScope("curated");
// 2. Live track signatures update across model & API switches
setView("workbench");
setTool("search");
setModel("qwen38");
setStage(1);
setApi("chat");
const sigChat = [...document.querySelectorAll(".track-sig")].map(el => el.textContent);
check(sigChat[0] === "POST /v1/chat/completions", `Expected chat endpoint sig, got ${sigChat[0]}`);
check(sigChat[3].includes("finish_reason"), `Expected finish_reason sig, got ${sigChat[3]}`);
setApi("messages");
const sigMsg = [...document.querySelectorAll(".track-sig")].map(el => el.textContent);
check(sigMsg[0] === "POST /v1/messages", `Expected messages endpoint sig, got ${sigMsg[0]}`);
check(sigMsg[3].includes("stop_reason"), `Expected stop_reason sig, got ${sigMsg[3]}`);
setApi("chat");
const qwenSig2 = sigChat[1];
setModel("gemma4");
const gemmaSig2 = [...document.querySelectorAll(".track-sig")][1].textContent;
check(qwenSig2 !== gemmaSig2, `Expected Stage 2 signature to change on model switch (${qwenSig2})`);
// 3. Lenient paste normalizes OpenAI & Messages wrappers to bare MCP
setModel("qwen38");
setStage(1);
const openaiWrap = JSON.stringify({
tools: [{ type: "function", function: { name: "ping", description: "Ping host", parameters: { type: "object", properties: { host: { type: "string" } } } } }]
});
const mcpFromOpenAI = maybeConvertToMcp(openaiWrap);
check(mcpFromOpenAI && JSON.parse(mcpFromOpenAI).inputSchema && !JSON.parse(mcpFromOpenAI).parameters, "OpenAI wrapper did not normalize to bare MCP");
const msgWrap = JSON.stringify({
name: "ping", description: "Ping host", input_schema: { type: "object", properties: { host: { type: "string" } } }
});
const mcpFromMsg = maybeConvertToMcp(msgWrap);
check(mcpFromMsg && JSON.parse(mcpFromMsg).inputSchema && !JSON.parse(mcpFromMsg).input_schema, "Messages wrapper did not normalize to bare MCP");
// 4. Stage 2 Template source has > 5 lines and highlighted .hl lines on qwen38
setTool("search");
setModel("qwen38");
setStage(2);
const lineCount = $("left-body").querySelectorAll(".cl").length;
const hlCount = $("left-body").querySelectorAll(".cl.hl").length;
check(lineCount > 5, `Stage 2 template line count too low: ${lineCount}`);
check(hlCount > 0, `Stage 2 qwen38 missing .hl lines: ${hlCount}`);
// 4b. Curated 8 tabs + More (5) popover opens, selects extra model, updates indicator
setView("workbench");
setModel("qwen38");
setStage(1);
check(document.querySelectorAll('.rail-tab[role="tab"]').length === 8, `Expected 8 curated tabs`);
const moreBtn = $("rail-more-btn");
const moreMenu = $("rail-more-menu");
check(Boolean(moreBtn && moreMenu), "Missing #rail-more-btn or #rail-more-menu");
moreBtn.click();
check(!moreMenu.hidden && moreBtn.getAttribute("aria-expanded") === "true", "More menu did not open");
const glmItem = moreMenu.querySelector('.more-item[data-model="glm53"]');
check(Boolean(glmItem), "Missing glm53 in More menu");
glmItem.click();
check(S.model === "glm53", `Expected glm53 after More selection, got ${S.model}`);
check(moreMenu.hidden && moreBtn.classList.contains("is-active"), "More button did not activate for extra model");
const indTransform = $("rail-indicator").style.transform || "";
check(indTransform.includes("translateX(") && !indTransform.includes("scaleX(0)"), `Rail indicator not positioned on More btn: ${indTransform}`);
// 4c. Role-colored spans in Stage 1 editor, request, and excerpt + dropped on gptoss
setModel("qwen38");
setStage(1);
const ex = $("stage1-excerpt");
check(ex && ex.querySelectorAll(".r-name, .r-param, .r-desc, .r-cons").length >= 4, "Missing role-colored spans in #stage1-excerpt");
check($("mcp-editor").querySelectorAll(".r-name, .r-param, .r-desc, .r-cons").length >= 4, "Missing role-colored spans in #mcp-editor");
setModel("gptoss");
check($("mcp-editor").querySelectorAll(".is-dropped").length >= 2, "Expected dropped minimum/maximum in #mcp-editor for gptoss");
setModel("qwen38");
// 5. CTA progression 1->2->3->4->5 + single .cta + overflow + zero desktop page scroll
setStage(1);
for (let st = 1; st <= 4; st++) {
check(S.stage === st, `Expected stage ${st}, got ${S.stage}`);
$("btn-next").click();
}
check(S.stage === 5, `Expected stage 5 after 4 clicks, got ${S.stage}`);
check(document.querySelectorAll(".cta").length === 1, `Expected 1 .cta, got ${document.querySelectorAll(".cta").length}`);
setStage(1);
check(document.documentElement.scrollWidth <= window.innerWidth + 1,
`Horizontal overflow: scrollWidth=${document.documentElement.scrollWidth} > innerWidth=${window.innerWidth}`);
if (window.innerWidth >= 1024) {
check(document.documentElement.scrollHeight <= window.innerHeight + 1,
`Desktop vertical page scroll: scrollHeight=${document.documentElement.scrollHeight} > innerHeight=${window.innerHeight}`);
}
if (window.innerWidth >= 1280) {
const railEl = $("model-rail");
check(railEl.scrollWidth <= railEl.clientWidth + 1,
`Model rail scrolled at ${window.innerWidth}px: scrollWidth=${railEl.scrollWidth} > clientWidth=${railEl.clientWidth}`);
}
} catch (e) {
errors.push(`Exception: ${e && e.message ? e.message : String(e)}`);
}
const report = {
ok: errors.length === 0,
viewport: `${window.innerWidth}x${window.innerHeight}`,
errors,
};
document.title = report.ok ? `SELFTEST PASS (${report.viewport})` : `SELFTEST FAIL (${errors.length})`;
const pre = document.createElement("pre");
pre.id = "selftest-report";
pre.textContent = JSON.stringify(report, null, 2);
pre.style.display = "none";
document.body.appendChild(pre);
console.log("SELFTEST_RESULT", JSON.stringify(report));
}
/* =========================================================================
Init
========================================================================= */
function init() {
readHash();
loadPreset(S.tool);
renderModelRail();
syncTopBar();
if (S.view === "compare") {
renderCompare();
} else {
renderWorkbench();
}
bindEvents();
if (document.fonts && document.fonts.ready) {
document.fonts.ready.then(() => positionRailIndicator(false));
}
if (SELFTEST) {
setTimeout(runSelfTest, 120);
}
}
init();
/* Tool call pipeline: v3 causal pair workbench */
import { REPORT_DATA } from "./data.js";
import {
normalizeToolsInput,
renderAnnotatedPrompt,
renderToolReturnTurn,
buildModelReply,
} from "./renderers.js";
const MODELS = REPORT_DATA.models;
const MBY = Object.fromEntries(MODELS.map(m => [m.key, m]));
const PRESETS = REPORT_DATA.presets;
const SHARED = REPORT_DATA.sharedExcerpts || {};
const REPOS = (REPORT_DATA.meta && REPORT_DATA.meta.repos) || {};
const CURATED_MODELS = [
{ key: "qwen38", name: "Qwen3.8", sub: "XML tags" },
{ key: "gptoss", name: "gpt-oss", sub: "Harmony TS" },
{ key: "gemma4", name: "Gemma 4", sub: "Custom DSL" },
{ key: "mistral4", name: "Mistral L4", sub: "Bracket tokens" },
{ key: "kimi26", name: "Kimi K2.6", sub: "TS helper" },
{ key: "kimi31", name: "Kimi K3.1", sub: "Python XTML" },
{ key: "deepseek41", name: "DeepSeek V4.1", sub: "Typed DSML" },
{ key: "minimax31", name: "MiniMax M3.1", sub: "Recursive XML" },
];
const EXTRA_MODELS = [
{ key: "glm53", name: "GLM-5.3", sub: "arg_key XML" },
{ key: "inkling2", name: "Inkling 2", sub: "Content tokens" },
{ key: "beam", name: "Beam 1.0", sub: "Harmony + XML" },
{ key: "glimmer", name: "Glimmer", sub: "ATEM XML" },
{ key: "hy4", name: "Hy4", sub: "Namespaced XML" },
];
const CURATED_KEYS = new Set(CURATED_MODELS.map(x => x.key));
const EXTRA_BY_KEY = Object.fromEntries(EXTRA_MODELS.map(x => [x.key, x]));
const SHORT_LABELS = Object.fromEntries([...CURATED_MODELS, ...EXTRA_MODELS].map(x => [x.key, x.name]));
const STAGES = [
{
id: 1,
label: "Wrap tool",
summary: "Your client wraps the MCP tool in a <code>tools</code> array. Nothing model-specific has happened yet.",
cta: "Next: render the prompt",
},
{
id: 2,
label: "Render prompt",
summary: "The chat template turns that JSON into text. This is the only description of your tool the model ever sees.",
cta: "Next: generate tokens",
},
{
id: 3,
label: "Generate tokens",
summary: "The model continues the prompt one token at a time until it emits a stop token.",
cta: "Next: parse the response",
},
{
id: 4,
label: "Parse response",
summary: "The serving engine finds the call in the text and rewrites it as structured <code>tool_calls</code>.",
cta: "Next: continue the turn",
},
{
id: 5,
label: "Continue turn",
summary: "Your client runs the tool, and the template renders the result into the next prompt.",
cta: "Compare all 13 models",
},
];
const ICO_COPY = '<svg class="ico" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="7" y="7" width="9" height="9" rx="1.5"></rect><path d="M4 13V5a1.5 1.5 0 0 1 1.5-1.5H13"></path></svg>';
const ICO_CHECK = '<svg class="ico" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="4.5 10.5 8.5 14.5 15.5 6.5"></polyline></svg>';
const ICO_RESET = '<svg class="ico" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4.5 10a5.5 5.5 0 1 0 1.4-3.7"></path><polyline points="4.5 3.5 4.5 7.5 8.5 7.5"></polyline></svg>';
const ICO_CHEV = '<svg viewBox="0 0 18 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="1" y1="6" x2="14" y2="6"></line><polyline points="10.5 2.5 14.5 6 10.5 9.5"></polyline></svg>';
const S = {
view: "workbench", // "workbench" | "compare"
compareScope: "curated", // "curated" | "all"
moreOpen: false,
model: MODELS[0].key,
stage: 1, // 1..5
prevStage: 1,
api: "chat", // "chat" | "messages"
reply: "tool", // "tool" | "text"
tool: "search", // "search" | "ticket"
engine: "vllm", // "vllm" | "sglang" | "llama" | "input"
tmplFile: "main", // "main" | "helper"
leftView: { 2: "template", 4: "parser", 5: "call" },
rightView: { 5: "annotated" },
fieldsOpen: false,
visited: new Set([1]),
stage3Visited: false,
playMode: "play", // "play" | "step" | "all"
shown: 0,
timer: null,
deb: null,
text: "",
edited: false,
parseError: null,