import type { MirrorLine } from "../live/live.ts";
import { explain, summarize } from "../record/describe.ts";
import type { DecisionEntry, ProfileSnapshotEntry } from "../record/types.ts";
import { aggregate, type Task, type Timeline } from "../timeline/parse.ts";
const esc = (value: unknown): string =>
String(value ?? "").replace(/[&<>"']/gu, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] ?? c);
const money = (value: number): string => (value === 0 ? "$0" : value < 0.01 ? `$${value.toFixed(4)}` : `$${value.toFixed(2)}`);
const tokens = (value: number): string =>
value >= 1_000_000 ? `${(value / 1_000_000).toFixed(1)}M` : value >= 1000 ? `${(value / 1000).toFixed(1)}k` : String(value);
interface Price {
input: number;
output: number;
cacheRead?: number;
cacheWrite?: number;
}
/** Cost of a task's tokens at a member's catalog price (per million tokens), ignoring cache effects. */
function priced(task: Task, price: Price | undefined): number | undefined {
if (!price) return undefined;
let total = 0;
for (const r of task.requests) total += ((r.input + r.cacheRead + r.cacheWrite) * price.input + r.output * price.output) / 1_000_000;
return total;
}
function tierPrice(snapshot: ProfileSnapshotEntry | undefined, tier: string): Price | undefined {
return snapshot?.tiers.find((t) => t.name === tier)?.members.find((m) => m.price)?.price;
}
function decisionBlock(decision: DecisionEntry): string {
const warn = decision.kind === "fallback" || decision.kind === "inactive" || decision.error;
return `${esc(summarize(decision))}
${esc(explain(decision).join("\n"))} `;
}
function mirrorBlock(lines: readonly MirrorLine[]): string {
const rows = lines
.map((line) => {
const tag =
line.kind === "tool-call" ? `→ ${line.tool ?? ""}` : line.kind === "tool-result" ? `${line.isError ? "✗" : "←"} ${line.tool ?? ""}` : line.kind;
return `
${esc(tag.padEnd(14))} ${esc(line.text.replace(/\s+/gu, " ").slice(0, 600))}
`;
})
.join("");
return `transcript mirror (${lines.length} entries, redacted and bounded)
${rows} `;
}
function taskBlock(task: Task, snapshot: ProfileSnapshotEntry | undefined, depth: number): string {
const main = task.decisions.find((d) => d.reason === "user") ?? task.decisions[0];
const tier = main?.tier.chosen ?? "";
const member = main ? `${main.model.provider}/${main.model.id}` : "";
const switches = task.requests.filter((r) => r.switched).length;
const fallback = task.decisions.some((d) => d.kind === "fallback");
const top = snapshot ? priced(task, tierPrice(snapshot, snapshot.topTier)) : undefined;
const base = snapshot ? priced(task, tierPrice(snapshot, snapshot.baselineTier)) : undefined;
const requests = task.requests
.map(
(r) =>
`| ${esc(r.ts.slice(11, 19))} | ${esc(`${r.provider}/${r.model}`)}${r.thinking ? `:${esc(r.thinking)}` : ""}${r.switched ? ' switch' : ""} | ${tokens(r.input)} | ${tokens(r.cacheRead)} | ${tokens(r.output)} | ${money(r.cost)} | ${r.durationMs !== undefined ? `${(r.durationMs / 1000).toFixed(1)}s` : ""} | ${esc(r.error ?? r.stopReason ?? "")} |
`,
)
.join("");
const tools = task.tools
.map(
(t) =>
`${esc(t.name)} ${t.isError ? "✗" : "✓"} ${esc(t.preview.replace(/\s+/gu, " ").slice(0, 160))}`,
)
.join("");
const children = task.children
.map((child) => {
const transcript = child.timeline?.mirror ? mirrorBlock(child.timeline.mirror) : "";
const nested = child.timeline
? child.timeline.tasks.map((t) => taskBlock(t, snapshot, depth + 1)).join("") + transcript
: 'Child session not available (in-memory child, removed file, or its transcript mirror was already swept).
';
return `${decisionBlock(child.decision)}${child.runId ? `
run ${esc(child.runId)}
` : ""}${nested}
`;
})
.join("");
return `
#${task.index}${esc(task.request.replace(/\s+/gu, " ").slice(0, 140) || "(no request text)")}${esc(tier || "—")}${esc(member)}${money(task.cost)}${switches ? `${switches} switch${switches > 1 ? "es" : ""}` : ""}${fallback ? 'fallback' : ""}
${task.decisions.map(decisionBlock).join("")}
${top !== undefined || base !== undefined ? `
Counterfactual (estimate, ignores cache): top tier ${top !== undefined ? money(top) : "n/a"} · baseline ${base !== undefined ? money(base) : "n/a"}
` : ""}
${requests ? `
| time | model | in | cache | out | cost | dur | stop |
${requests}
` : ""}
${tools ? `
` : ""}
${children}
`;
}
function rows(map: Map): string {
return [...map.entries()]
.sort((a, b) => b[1].cost - a[1].cost || b[1].tokens - a[1].tokens)
.map(
([key, v]) =>
`| ${esc(key)} | ${money(v.cost)} | ${tokens(v.tokens)} | ${v.requests} |
`,
)
.join("");
}
/** A self-contained, offline HTML page for one session and its subagent sessions (DESIGN.md 11.4). */
export function renderInspector(timeline: Timeline, title = "Switchboard inspector"): string {
const snapshot = timeline.profiles.at(-1);
const byTier = aggregate(timeline, (_r, d) => d?.tier.chosen || "unrouted");
const byMember = aggregate(timeline, (r) => `${r.provider}/${r.model}`);
const byProvider = aggregate(timeline, (r) => r.provider);
const decisions = timeline.tasks.flatMap((t) => [...t.decisions, ...t.children.map((c) => c.decision)]);
const gated = decisions.filter((d) => d.rules).map((d) => d.rules?.gate.confidence ?? 0);
const hist = [
["<0.5", gated.filter((c) => c < 0.5).length],
["0.5–0.8", gated.filter((c) => c >= 0.5 && c < 0.8).length],
["0.8–0.9", gated.filter((c) => c >= 0.8 && c < 0.9).length],
["≥0.9", gated.filter((c) => c >= 0.9).length],
] as const;
const maxHist = Math.max(1, ...hist.map(([, n]) => n));
let top = 0;
let base = 0;
let priceable = false;
for (const task of timeline.tasks) {
const t = priced(task, tierPrice(snapshot, snapshot?.topTier ?? ""));
const b = priced(task, tierPrice(snapshot, snapshot?.baselineTier ?? ""));
if (t !== undefined) {
top += t;
priceable = true;
}
if (b !== undefined) base += b;
}
const tiers = [...new Set(decisions.map((d) => d.tier.chosen).filter(Boolean))];
const members = [...byMember.keys()];
return `${esc(title)}
${esc(title)}
${esc(timeline.file ?? "")}${timeline.cwd ? ` · ${esc(timeline.cwd)}` : ""}
Cost${money(timeline.totals.cost)}
Tokens${tokens(timeline.totals.tokens)}
Tasks${timeline.tasks.length}
Model switches${timeline.totals.switches}
Fallback rate${timeline.totals.decisions ? Math.round((100 * timeline.totals.fallbacks) / timeline.totals.decisions) : 0}%
If all on top tier${priceable ? money(top) : "n/a"}estimate
If all on baseline${priceable ? money(base) : "n/a"}estimate
By tier
| tier | cost | tokens | responses |
${rows(byTier)}
By model
| model | cost | tokens | responses |
${rows(byMember)}
By provider
| provider | cost | tokens | responses |
${rows(byProvider)}
Gate confidence
${hist.map(([label, n]) => `
${esc(label)}: ${n}
`).join("")}
Tasks
${timeline.tasks.map((task) => taskBlock(task, snapshot, 0)).join("") || '
No tasks.
'}
`;
}