import { downloadVerdictPdf } from "./pdf.js";
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
const SAMPLES = [
["Raise my prices?", "I run a coaching business doing $30k a month with 15 active clients at $2,000 each. I want to raise the price to $3,500. Options: raise for everyone now, raise for new clients only, or keep $2,000. Close rate is about 50% on sales calls. I'm leaning toward raising for everyone because I'm underpaid."],
["First salesperson?", "I'm a solo founder of a B2B SaaS at $25k MRR growing 5% a month. I do every sales call myself (about 20 hours a week) and I'm burning out. Should I hire a full-time account executive at $120k base, hire a part-time commission-only closer, or keep selling myself for six more months? I have $150k in the bank."],
["Second product?", "My agency makes $80k a month building AI automations for dentists. A few clients asked for an AI receptionist product. Should I build the receptionist as a separate SaaS, offer it as an add-on to existing clients only, or stay focused on the agency? Team of 6, about $200k cash."],
["Quit my job?", "I make $180k a year at a tech company. My side business (a paid newsletter) makes $6k a month and grew 8% a month this year. I have 9 months of expenses saved. Should I quit now, quit in 6 months, or keep both and hire a writer?"],
];
const EXAMPLE = "I run a coaching business at $30k a month with 15 clients at $2,000 each. Should I raise to $3,500 for everyone, raise for new clients only, or keep $2,000? Close rate is about 50% and I have $40k in the bank. Success is $45k a month by March. I'm leaning toward raising for everyone because I'm underpaid.";
// The how-to, shown in the side panel while the room is empty and in "How it works".
const GUIDE = `
How to use the Roast Room
Open Claude Code in this folder.
Type /roast-room and your decision.
Answer the Chair's questions. Then watch the council argue it out here.
When the verdict lands, download it as a PDF.
What to put in your question
The decision in one line.
Your options. Two or three. "Keep doing what I do now" counts.
Your numbers. Revenue, cash, and team size.
Your limits. Deadline, hours, and budget.
What success looks like, and by when.
Which way you're leaning, and why. The council tests it.
Left something out? The Chair asks before the council starts.
Full council: your default board (the 7 advisors out of the box), 3 rounds. For big calls that are hard to undo.
Quick: add --quick for 4 advisors and 2 rounds. Uses far less of your plan.
Every council is saved. Open Past sessions to replay one or download its PDF.
Add an advisor: type /newroaster and a name. Change who sits at the table with /roast-room board.
`;
const SHAPES = ["base", "open", "mid", "blink"];
// A seat's cartoon frames live in /portraits/-.webp (or .png, .jpg). A seat added with /newroaster
// may have only a base frame, or none: missing frames fall back to the base frame, then to a
// drawn bust in the seat's color whose mouth and eyes still move.
const portrait = (key, shape = "base") => {
const have = state.byKey[key]?.portraits || {};
return have[shape] || have.base || drawnBust(key, shape);
};
const bustCache = new Map();
function drawnBust(key, shape) {
const id = `${key}-${shape}`;
if (bustCache.has(id)) return bustCache.get(id);
const s = state.byKey[key] || {};
const c = /^#[0-9a-f]{6}$/i.test(s.color || "") ? s.color : "#37bdf8";
const initials = esc((s.initials || s.short || key).slice(0, 3).toUpperCase());
const eyes = shape === "blink"
? ``
: ``;
const mouth = shape === "open" ? ``
: shape === "mid" ? ``
: ``;
const svg = ``;
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
bustCache.set(id, url);
return url;
}
const ROUND_NAME = ["", "Opening", "Debate", "Vote"];
const state = {
seats: [], byKey: {}, board: [], table: [], session: null, options: [], weights: {}, active: [], round: 0,
cards: { 1: {}, 2: {}, 3: {} }, replaying: false, verdict: null, links: [], geo: {}, setup: null, wait: null,
};
// ------------------------------------------------------------- boot
async function boot() {
const r = await refreshSeats();
state.runner = r.runner;
if (r.runner === "api" && !r.hasKey) toast("No ANTHROPIC_API_KEY found in .env. Add it and restart the server.");
renderSeats(state.board);
renderSamples();
bindUI();
new ResizeObserver(() => { layoutStage(); drawLinks(); }).observe($("#stage"));
startBlinking();
reset();
typeIn($("#composer h2"));
typeIn($("#waiting h2"));
const ss = await fetch("/api/sessions").then((x) => x.json());
if (ss.running) attach(ss.running);
else if (ss.live) attach(ss.live);
refreshUsage();
setInterval(watchForLive, 2500);
setInterval(tickWait, 1000);
}
// The roster (every seat, plus the default board) comes from the skill's roster.json.
async function refreshSeats() {
const r = await fetch("/api/seats").then((x) => x.json());
state.seats = r.seats;
state.byKey = Object.fromEntries(r.seats.map((s) => [s.key, s]));
state.board = (r.board?.default || []).filter((k) => state.byKey[k]);
if (!state.board.length) state.board = r.seats.slice(0, 7).map((s) => s.key);
bustCache.clear();
return r;
}
// a council started in Claude Code shows up here on its own
const seenLive = new Set();
async function watchForLive() {
const ss = await fetch("/api/sessions").then((x) => x.json()).catch(() => null);
const id = ss?.live || ss?.running;
if (!id || seenLive.has(id) || id === state.session) return;
seenLive.add(id);
attach(id);
}
// AIS arrival: a heading types in a character at a time, blur to sharp
function typeIn(el) {
if (!el) return;
const text = el.textContent;
el.classList.add("typein");
// characters sit inside a nowrap span per word, so lines only break between words
let i = 0;
el.innerHTML = text.split(" ").map((word) => `${[...word].map((c) => `${esc(c)}`).join("")}`).join(" ");
el.setAttribute("aria-label", text);
}
function renderSamples() {
$("#samples").innerHTML = SAMPLES.map(([t], i) => ``).join("");
$("#samples").addEventListener("click", (e) => {
const b = e.target.closest("button"); if (!b) return;
$("#prompt").value = SAMPLES[b.dataset.i][1];
$("#prompt").focus();
});
}
const MAX_TABLE = 9; // the most busts the table can seat and still read
/** Seat these keys at the table (roster order). Does nothing when they are already seated. */
function renderSeats(keys) {
const order = state.seats.map((s) => s.key);
const want = order.filter((k) => keys.includes(k)).slice(0, MAX_TABLE);
if (want.join() === state.table.join() && $("#seats").children.length) return;
state.table = want;
const seats = want.map((k) => state.byKey[k]);
$("#seats").innerHTML = seats.map((s, i) => `
No sessions yet. Convene the council once and it shows up here.
';
$$("#historyList button[data-id]").forEach((b) => b.addEventListener("click", () => { $("#historyDialog").close(); replay(b.dataset.id); }));
$("#historyDialog").showModal();
}
async function replay(id) {
const j = await fetch(`/api/sessions/${encodeURIComponent(id)}`).then((x) => x.json());
begin(id);
state.replaying = true;
for (const ev of j.events) {
if (["delta", "usage", "seat_error", "end"].includes(ev.type)) continue;
player.push(ev);
}
}
// ------------------------------------------------------------- waiting on Claude Code
// A live council goes quiet for minutes while the seats write in parallel. Instead of a
// frozen table, say what is happening, how long it has been, and what each seat is weighing.
const SAME_TIME = "The advisors all write at the same time in Claude Code. Their lines play here as soon as the round is in.";
function waitCopy(phase) {
const n = state.setup?.mode === "quick" ? 2 : 3;
return {
setup: ["Setting the table", "The Chair is seating the council.", ""],
round1: ["Round 1 of " + n, "The advisors are writing their opening positions.", SAME_TIME],
round2: ["Round 2 of " + n, "The advisors are reading each other's openings and firing back.", SAME_TIME],
round3: ["Round 3 of " + n, "The advisors are voting on the Chair's proposal.", SAME_TIME],
cruxes: ["Between rounds", "The Chair is reading the openings and finding where they disagree.", "The fight shows up here next, then the debate starts."],
draft: ["Between rounds", "The Chair is turning the debate into a proposal for the vote.", "Next, every advisor votes on it."],
skip3: ["Last step", "The Chair is scoring the room and writing the verdict.", "When it lands, you can download it as a PDF."],
verdict: ["Last step", "The Chair is scoring the room and writing the verdict.", "When it lands, you can download it as a PDF."],
}[phase] || ["Working", "The council is working.", ""];
}
const clock = (ms) => { const s = Math.max(0, Math.round(ms / 1000)); return Math.floor(s / 60) + ":" + String(s % 60).padStart(2, "0"); };
function hideWait() {
const w = $("#waitcard");
if (w.hidden) return;
w.hidden = true;
$$(".seat.musing").forEach((e) => e.classList.remove("musing"));
if (state.capWasShown) $("#caption").hidden = false;
if (state.playbarWasShown) $("#playbar").hidden = false;
}
function tickWait() {
const w = state.wait;
const idle = !player.busy && !player.q.length;
if (!w || !idle || state.replaying || !state.session || state.verdict) return hideWait();
const card = $("#waitcard");
if (card.hidden) {
state.capWasShown = !$("#caption").hidden;
$("#caption").hidden = true;
$("#cruxes").hidden = true;
// speed controls do nothing while the room waits, and they would cover the card
state.playbarWasShown = !$("#playbar").hidden;
$("#playbar").hidden = true;
card.hidden = false;
state.museAt = 0;
}
const [step, head, sub] = waitCopy(w.phase);
const elapsed = Date.now() - w.at;
$("#wcStep").textContent = step;
$("#wcTime").textContent = clock(elapsed);
$("#wcHead").textContent = head;
$("#wcSub").textContent = sub;
$("#wcNudge").hidden = elapsed < 4 * 60 * 1000;
const round = Number((w.phase.match(/^round(\d)$/) || [])[1]) || 0;
const bar = $("#wcBar").parentElement;
const muse = $("#wcMuse");
if (round) {
const seats = state.active.length ? state.active : state.table;
const done = seats.filter((k) => state.cards[round][k]).length;
bar.classList.toggle("indeterminate", done === 0);
$("#wcBar").style.width = done ? Math.round((done / seats.length) * 100) + "%" : "";
// every few seconds, show what one of the still-thinking seats is weighing
const pending = seats.filter((k) => !state.cards[round][k]);
if (pending.length && Date.now() - (state.museAt || 0) > 5200) {
state.museAt = Date.now();
state.museIdx = ((state.museIdx ?? -1) + 1) % pending.length;
const s = state.byKey[pending[state.museIdx]];
muse.classList.add("fade");
setTimeout(() => {
muse.innerHTML = "" + esc(s.short) + " is weighing: " + esc(s.question.replace(/^./, (c) => c.toLowerCase())) + (done ? " · " + done + " of " + seats.length + " in" : "");
muse.classList.remove("fade");
$$(".seat").forEach((el) => el.classList.toggle("musing", el.dataset.seat === s.key));
}, 300);
}
} else {
bar.classList.add("indeterminate");
$("#wcBar").style.width = "";
muse.textContent = "";
$$(".seat.musing").forEach((e) => e.classList.remove("musing"));
}
}
function openGuide() {
$("#guideBody").innerHTML = GUIDE;
const d = $("#guideDialog");
if (!d.open) d.showModal();
}
// ------------------------------------------------------------- PDF
async function savePdf(btn) {
const id = btn.dataset.pdf;
btn.disabled = true;
const old = btn.textContent;
btn.textContent = "Making PDF...";
try {
let setup = state.setup, verdict = state.verdict;
if (id) { // a past session from the history list
const j = await fetch("/api/sessions/" + encodeURIComponent(id)).then((x) => x.json());
setup = j.events.find((e) => e.type === "setup");
verdict = [...j.events].reverse().find((e) => e.type === "verdict");
}
if (!setup || !verdict) throw new Error("This council has no verdict yet.");
await downloadVerdictPdf({ setup, verdict, byKey: state.byKey, id: id || state.session });
} catch (e) {
console.error(e);
toast("Couldn't make the PDF: " + (e.message || e));
} finally {
btn.disabled = false;
btn.textContent = old;
}
}
// ------------------------------------------------------------- misc
let toastTimer;
function toast(msg) {
const t = $("#toast");
t.textContent = msg;
t.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => (t.hidden = true), 6000);
}
async function refreshUsage() {
const u = await fetch("/api/usage").then((x) => x.json()).catch(() => null);
if (!u || !u.calls) { $("#usage").textContent = ""; return; }
const k = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`);
$("#usage").textContent = `${u.calls} calls · ${k(u.input + u.cacheRead + u.cacheWrite)} in · ${k(u.output)} out`;
}
boot();