Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(bench): correct transcript parsing for viewer harness

Steven Enamakel59960fca4539
diff --git a/bench/harnesses/viewer/index.html b/bench/harnesses/viewer/index.html
index 6783d7dd5f..ffbbd8dabe 100644
--- a/bench/harnesses/viewer/index.html
+++ b/bench/harnesses/viewer/index.html
@@ -109,6 +109,8 @@ async function task(id, harness, t) {
const flag = (v) => v === null ? "" : v ? h("span", { class: "ok" }, "same") : h("span", { class: "bad" }, "CHANGED");
app.replaceChildren(h("h1", {}, `${harness} · ${t}`),
crumbs(link("#/", "runs"), link(`#/run/${e(id)}`, id), harness, t),
+ h("h2", {}, "Full task transcript (Markdown)"),
+ transcriptBox(`/api/runs/${e(id)}/transcript/${e(harness)}/${e(t)}/last`),
h("p", { class: "mut" }, "‘prefix reused’ is how many of the previous call’s messages this call re-sent byte-for-byte; below the previous count, history was rewritten and provider prefix caching is lost from there."),
table(["#", "status", "msgs", "prefix reused", "system", "tools", "cache ctl", "prompt", "cached", "completion", "first token ms", "total ms", "cost $", "req KB"],
calls.map((c, i) => [
@@ -122,12 +124,31 @@ async function task(id, harness, t) {
const text = (c) => typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => p?.text ?? p?.content ?? JSON.stringify(p)).join("\n") : JSON.stringify(c, null, 2);
+// Collapsed by default (it can be large); loads on first open. Same text the Copy and Download buttons use.
+function transcriptBox(apiPath) {
+ const box = h("div", {});
+ const d = h("details", {}, h("summary", {}, "Show exactly what the provider received and returned"));
+ const holder = h("div", {});
+ d.append(holder);
+ d.addEventListener("toggle", async () => {
+ if (!d.open || holder.childNodes.length) return;
+ const { markdown } = await api(apiPath);
+ const copy = h("button", {}, "Copy");
+ copy.onclick = () => navigator.clipboard.writeText(markdown).then(() => { copy.textContent = "Copied"; });
+ holder.append(h("div", {}, copy, " ", h("a", { href: `${apiPath}?format=md`, target: "_blank" }, "open as .md")), pre(markdown));
+ });
+ box.append(d);
+ return box;
+}
+
async function call(id, harness, t, seq) {
const c = await api(`/api/runs/${e(id)}/call/${e(harness)}/${e(t)}/${seq}`);
const kids = [h("h1", {}, `${harness} · ${t} · call ${seq}`),
crumbs(link("#/", "runs"), link(`#/run/${e(id)}`, id), link(`#/task/${e(id)}/${e(harness)}/${e(t)}`, `${harness}/${t}`), `call ${seq}`),
h("div", {}, [["format", c.format], ["status", c.status], ["msgs", c.message_shas.length], ["tools", c.tool_count],
["cache_control markers", c.cache_control_markers], ["prompt_cache_key", c.prompt_cache_key]].map(([k, v]) => h("span", { class: "tag" }, `${k}: ${v ?? "–"}`))),
+ h("h2", {}, "Raw transcript (Markdown)"),
+ transcriptBox(`/api/runs/${e(id)}/transcript/${e(harness)}/${e(t)}/${seq}`),
h("h2", {}, `System prompt (${fmt(c.system_chars)} chars, ${c.system_sha ?? "none"})`), pre(c.system || "(no system prompt)"),
h("h2", {}, "Sampling & provider params"), pre(c.params),
h("h2", {}, "Request headers"), pre(c.headers),
diff --git a/bench/harnesses/viewer/server.mjs b/bench/harnesses/viewer/server.mjs
index 2f87dc1950..85546e9632 100644
--- a/bench/harnesses/viewer/server.mjs
+++ b/bench/harnesses/viewer/server.mjs
@@ -14,6 +14,7 @@ import http from "node:http";
import path from "node:path";
import readline from "node:readline";
import { fileURLToPath } from "node:url";
+import { toMarkdown } from "./transcript.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const argv = process.argv.slice(2);
@@ -85,6 +86,18 @@ function aggregate(records) {
const capDir = (run, ...rest) => path.join(RESULTS, seg(run), "captures", ...rest.map(seg));
const blob = (run, id) => readJson(path.join(RESULTS, seg(run), "captures", "blobs", `${seg(id)}.json`));
+const loadCall = (run, harness, task, seq) => {
+ const dir = capDir(run, harness, task);
+ const file = seq === "last" ? fs.readdirSync(dir).sort().pop() : `${String(seq).padStart(5, "0")}.json`;
+ const c = readJson(path.join(dir, file));
+ return {
+ ...c,
+ system: c.system_sha ? blob(run, c.system_sha) : "",
+ tools: c.tools_sha ? blob(run, c.tools_sha) : [],
+ messages: c.message_shas.map((id) => blob(run, id)),
+ };
+};
+
const routes = [
[/^\/api\/runs$/, () =>
dirs(RESULTS).filter((d) => fs.existsSync(path.join(RESULTS, d, "runs.jsonl")) || dirs(path.join(RESULTS, d, "captures")).length)
@@ -136,15 +149,11 @@ const routes = [
});
}],
- [/^\/api\/runs\/([^/]+)\/call\/([^/]+)\/([^/]+)\/(\d+)$/, ([run, harness, task, seq]) => {
- const c = readJson(path.join(capDir(run, harness, task), `${String(seq).padStart(5, "0")}.json`));
- return {
- ...c,
- system: c.system_sha ? blob(run, c.system_sha) : "",
- tools: c.tools_sha ? blob(run, c.tools_sha) : [],
- messages: c.message_shas.map((id) => blob(run, id)),
- };
- }],
+ [/^\/api\/runs\/([^/]+)\/call\/([^/]+)\/([^/]+)\/(\d+)$/, ([run, harness, task, seq]) => loadCall(run, harness, task, seq)],
+
+ // Raw transcript as Markdown; `last` is the final call, i.e. the whole conversation of the task.
+ [/^\/api\/runs\/([^/]+)\/transcript\/([^/]+)\/([^/]+)\/(\d+|last)$/, ([run, harness, task, seq]) =>
+ ({ markdown: toMarkdown(loadCall(run, harness, task, seq)) })],
// Two harnesses' system prompts side by side.
[/^\/api\/runs\/([^/]+)\/prompt\/([^/]+)$/, ([run, sha]) => ({ text: blob(run, sha) })],
@@ -164,7 +173,12 @@ const server = http.createServer(async (req, res) => {
}
for (const [re, fn] of routes) {
const m = url.pathname.match(re);
- if (m) return send(200, await fn(m.slice(1).map(decodeURIComponent)));
+ if (m) {
+ const out = await fn(m.slice(1).map(decodeURIComponent));
+ // ?format=md serves the transcript as a plain Markdown document (curl / download).
+ if (url.searchParams.get("format") === "md" && out.markdown) return send(200, out.markdown, "text/markdown; charset=utf-8");
+ return send(200, out);
+ }
}
send(404, { error: "not found" });
} catch (e) {
diff --git a/bench/harnesses/viewer/transcript.mjs b/bench/harnesses/viewer/transcript.mjs
new file mode 100644
index 0000000000..140ffdb229
--- /dev/null
+++ b/bench/harnesses/viewer/transcript.mjs
@@ -0,0 +1,116 @@
+// transcript.mjs — render one captured inference call as Markdown, exactly as the
+// provider received it: system prompt, tool schemas, then every message with its
+// tool calls and results, then what came back. Content is placed verbatim inside
+// fences (never interpreted as Markdown), so what you read is what was sent.
+
+/** A backtick fence longer than any run of backticks in `text`, so content cannot close it. */
+function fence(text, lang = "text") {
+ const longest = Math.max(2, ...[...String(text).matchAll(/`+/g)].map((m) => m[0].length));
+ const f = "`".repeat(longest + 1);
+ return `${f}${lang}\n${text}\n${f}`;
+}
+
+const asText = (c) =>
+ typeof c === "string"
+ ? c
+ : Array.isArray(c)
+ ? c.map((p) => (typeof p === "string" ? p : (p?.text ?? JSON.stringify(p, null, 2)))).join("\n")
+ : c == null
+ ? ""
+ : JSON.stringify(c, null, 2);
+
+function renderMessage(m, i) {
+ const role = m.role ?? m.type ?? "?";
+ const label = m.tool_call_id ? `${role} (answers ${m.tool_call_id})` : m.name ? `${role} (${m.name})` : role;
+ const out = [`### ${i + 1}. ${label}`];
+ const body = asText(m.content ?? m.output ?? "");
+ if (body) out.push(fence(body));
+ if (m.reasoning_content) out.push("reasoning_content:", fence(m.reasoning_content));
+ if (Array.isArray(m.tool_calls) && m.tool_calls.length) {
+ out.push("tool_calls:", fence(JSON.stringify(m.tool_calls, null, 2), "json"));
+ }
+ // Responses-API items (function_call, ...) carry their payload outside `content`.
+ if (!body && !m.tool_calls && !m.role) out.push(fence(JSON.stringify(m, null, 2), "json"));
+ return out.join("\n\n");
+}
+
+/** Assemble the assistant turn from an OpenAI-style SSE stream or a unary JSON body. */
+export function assembleResponse(raw) {
+ if (!raw) return null;
+ const text = [];
+ const reasoning = [];
+ const calls = new Map();
+ const absorb = (delta) => {
+ if (!delta) return;
+ if (delta.content) text.push(delta.content);
+ if (delta.reasoning_content ?? delta.reasoning) reasoning.push(delta.reasoning_content ?? delta.reasoning);
+ for (const t of delta.tool_calls ?? []) {
+ const c = calls.get(t.index ?? 0) ?? { id: null, name: "", arguments: "" };
+ c.id = t.id ?? c.id;
+ c.name += t.function?.name ?? "";
+ c.arguments += t.function?.arguments ?? "";
+ calls.set(t.index ?? 0, c);
+ }
+ };
+ let parsed = false;
+ for (const line of raw.split("\n")) {
+ if (!line.startsWith("data:")) continue;
+ const data = line.slice(5).trim();
+ if (!data || data === "[DONE]") continue;
+ try {
+ const j = JSON.parse(data);
+ parsed = true;
+ absorb(j.choices?.[0]?.delta);
+ } catch {
+ // keep-alive comments and partial lines
+ }
+ }
+ if (!parsed) {
+ try {
+ const j = JSON.parse(raw);
+ absorb(j.choices?.[0]?.message);
+ parsed = true;
+ } catch {
+ return null;
+ }
+ }
+ return { content: text.join(""), reasoning: reasoning.join(""), tool_calls: [...calls.values()] };
+}
+
+/**
+ * @param {object} call a capture with `system`, `tools`, `messages` resolved from blobs
+ */
+export function toMarkdown(call) {
+ const out = [
+ `# ${call.harness} · ${call.task} · call ${call.seq}`,
+ "",
+ `- run: \`${call.run_id}\` format: \`${call.format}\` status: \`${call.status ?? "?"}\``,
+ `- messages: ${call.messages.length}, tools: ${call.tool_count}, request: ${((call.request_bytes ?? 0) / 1024).toFixed(1)} KB`,
+ `- cache: system ${call.same_system_as_prev === null ? "n/a" : call.same_system_as_prev ? "same" : "CHANGED"}, tools ${call.same_tools_as_prev === null ? "n/a" : call.same_tools_as_prev ? "same" : "CHANGED"}, prefix reused ${call.prefix_reused_messages ?? "n/a"}/${call.prev_messages ?? "n/a"}`,
+ "",
+ "## Request parameters (as the harness sent them)",
+ fence(JSON.stringify(call.params ?? {}, null, 2), "json"),
+ "",
+ "## System prompt",
+ call.system ? fence(call.system) : "_none_",
+ "",
+ `## Tools (${call.tool_count})`,
+ call.tools?.length ? fence(JSON.stringify(call.tools, null, 2), "json") : "_none_",
+ "",
+ `## Conversation (${call.messages.length})`,
+ "",
+ ...call.messages.flatMap((m, i) => [renderMessage(m, i), ""]),
+ "## Response",
+ "",
+ ];
+ const a = assembleResponse(call.response);
+ if (a) {
+ out.push("### assistant", "");
+ if (a.reasoning) out.push("reasoning:", fence(a.reasoning), "");
+ if (a.content) out.push(fence(a.content), "");
+ if (a.tool_calls.length) out.push("tool_calls:", fence(JSON.stringify(a.tool_calls, null, 2), "json"), "");
+ } else {
+ out.push(call.response ? fence(call.response) : "_none_", "");
+ }
+ return out.join("\n");
+}
diff --git a/bench/harnesses/viewer/transcript.test.mjs b/bench/harnesses/viewer/transcript.test.mjs
new file mode 100644
index 0000000000..aeea16cb31
--- /dev/null
+++ b/bench/harnesses/viewer/transcript.test.mjs
@@ -0,0 +1,34 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { assembleResponse, toMarkdown } from "./transcript.mjs";
+
+const call = {
+ run_id: "r", harness: "h", task: "t", seq: 3, format: "chat", status: 200, tool_count: 1,
+ same_system_as_prev: true, same_tools_as_prev: true, prefix_reused_messages: 2, prev_messages: 2,
+ params: { temperature: 0 }, system: "You are ``` tricky.", tools: [{ type: "function", function: { name: "shell" } }],
+ messages: [
+ { role: "user", content: "run ls" },
+ { role: "assistant", content: "", tool_calls: [{ id: "c1", function: { name: "shell", arguments: "{}" } }] },
+ { role: "tool", tool_call_id: "c1", content: "a.txt" },
+ ],
+ response:
+ 'data: {"choices":[{"delta":{"reasoning_content":"think"}}]}\n\ndata: {"choices":[{"delta":{"content":"done"}}]}\n\ndata: [DONE]\n',
+};
+
+test("transcript is verbatim, fenced safely, and includes tool calls and results", () => {
+ const md = toMarkdown(call);
+ assert.match(md, /### 1\. user\n\n```text\nrun ls\n```/);
+ assert.match(md, /### 3\. tool \(answers c1\)/);
+ assert.match(md, /"name": "shell"/);
+ // a system prompt containing ``` gets a longer fence, so it cannot terminate early
+ assert.match(md, /````text\nYou are ``` tricky\.\n````/);
+ assert.match(md, /reasoning:\n\n```text\nthink/);
+ assert.match(md, /```text\ndone\n```/);
+});
+
+test("assembleResponse stitches streamed tool call arguments", () => {
+ const a = assembleResponse(
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c9","function":{"name":"sh","arguments":"{\\"a\\""}}]}}]}\n\ndata: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":":1}"}}]}}]}\n\n',
+ );
+ assert.deepEqual(a.tool_calls, [{ id: "c9", name: "sh", arguments: '{"a":1}' }]);
+});