`;
}
function renderQuick() {
const q = S.quick, p = S.proposal, fresh = p && p.minute === S.desk.minute;
if (S.desk.done || !S.card || S.desk.minute == null) return void ($("quick").innerHTML = "");
const left = S.desk.calls_left ?? 0;
$("quick").innerHTML = `
Quick playthe desk's optimizer, three clicks a wake-up
${S.auto ? `Autopilot: turn ${S.desk.turn}, ${esc(short(d0(), S.desk.minute))}` : "Or repeat all three at every wake-up to the end"}
This is what the anchor reference does at each wake-up; it scores R = 1 on most windows. ${left < 14 ? `${left} calls left this turn.` : "Beat it by hand with the tools above."}
Prices and forecasts appear here once you ask for them: each one is a call, as it is for an agent. The battery, its charge and the settled dollars come from the market\'s run.
`).join("")}` : ""}`;
}
/** One-click reads under the chart: the desk forecast for the next DAM still open, today's DAM prices, and
* the latest SCED prices; each is an ordinary call. */
function asks() {
const now = S.desk.minute ?? -1080, n = S.card.dates.length;
const open = now < -840 ? 0 : Math.floor((now + 840) / 1440) + 1, today = now < 0 ? -1 : Math.floor(now / 1440);
return [
...(open < n ? [[`Desk DAM forecast, D${open}`, "get_forecasts", { kind: "price", market: "dam", day: `D${open}` }]] : []),
[`DAM prices, D${today}`, "get_prices", { market: "dam", day: `D${today}` }],
["Latest SCED prices", "get_prices", { market: "sced" }],
];
}
function planOf(p) {
const hrs = (p.schedule.hourly_mw || []).map((s) => {
const [h, v] = s.split(":");
const mm = /HE(\d+)(?:@D(\d+))?/.exec(h);
return [60 * (+mm[1] - 1) + 1440 * +(mm[2] || 0), +v];
});
const from = minuteOf(p.schedule.from, d0());
const x0 = Math.floor(Math.max(0, from) / 60) * 60, n = 24;
const mwv = Array.from({ length: n }, (_, i) => hrs.find(([t]) => t === x0 + 60 * i)?.[1] ?? 0);
return { x0, mw: mwv };
}
function renderPlan() {
const p = S.proposal, days = Object.keys(S.plan).sort();
const fresh = p && p.minute === S.desk.minute;
const prop = p ? `
The optimizer's latest proposal
Asked ${esc(at(d0(), p.minute))}${fresh || S.desk.done ? "" : ", before your last wake-up: ask again for a fresh one"}.
${render("optimize", {}, p)}
${fresh && !S.desk.done ? `` : ""}
` : `
The optimizer
Optimize co-optimises the DAM and real time on a price view (by default the desk's forecast) and proposes curves, reserve offers and a COP. It submits nothing.
Every call you make and every wake-up you get, with the exact text an agent would read.
';
}
function renderBrief() {
const key = `${S.card?.task_id}|${S.brief.length}|${S.desk.max_turns}`;
if ($("p-brief").dataset.key === key) return;
$("p-brief").dataset.key = key;
$("p-brief").innerHTML = `
The desk brief. This is the system prompt every benchmark model got for this window, word for word. You play under the same rules: ${S.desk.max_turns || 100} turns, ${S.desk.calls_per_turn || 14} tool calls per turn, a clock that is frozen while you work, and the same grade.
Code: hub/openenv on GitHub. Prices and system data: ERCOT public reports (ERCOT does not endorse this work). Weather: NWS alerts and IEM ASOS observations.
`;
}
function renderPlate() {
const c = S.card;
if (!c) return;
const busy = S.phase === "run";
$("plate").innerHTML = `
${g.valid ? "" : "No submission was accepted, so the reward is 0. "}${g.capture != null ? `That is ${pct(g.capture)} of what perfect hindsight could have earned on this window` : "Hindsight could not earn more than idle on this window"}${refs.p_operator_actual != null ? `, against ${pct(cOf(refs.p_operator_actual))} for the battery's real operator` : ""}.
${ms.length ? `You would rank ${rank} of ${ms.length + 1}. Best: ${esc(S.models[best[0]]?.name || best[0])} at ${pct(best[1])}.` : ""}
C = (P − P_idle) / (P_hindsight − P_idle). The operator's numbers come from ERCOT's 60-day disclosures; the models' from the v4 benchmark, each in its native harness.
`;
showEnd();
strip(ms, g.capture ?? 0, cOf(refs.p_anchor));
}
function showEnd() {
$("end").hidden = false;
if (matchMedia("(max-width: 760px)").matches) requestAnimationFrame(() => $("end").scrollIntoView({ block: "start", behavior: reduced ? "auto" : "smooth" }));
}
/** Each model's C on this window as a dot, yours larger, on an axis drawn at the card's own width. */
function strip(ms, mine, anchor) {
const svg = $("end-strip"), W = Math.max(240, svg.clientWidth || 560), H = 64;
const cs = [...ms.map((r) => r[1]), mine, anchor ?? 0];
const cmin = Math.min(0, ...cs), cmax = Math.max(0.5, ...cs);
const sx = (v) => 12 + ((v - cmin) / (cmax - cmin)) * (W - 24);
const ticks = [-0.5, -0.25, 0, 0.25, 0.5, 0.75, 1, 1.25].filter((v) => v >= cmin - 1e-9 && v <= cmax + 1e-9);
const dots = ms.map(([k, cv], i) => `${esc(S.models[k]?.name || k)} ${pct(cv)}`).join("");
const best = ms[0], bx = best ? sx(best[1]) : 0, yx = sx(mine);
svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
svg.innerHTML = `${ticks.map((v) => `${Math.round(v * 100)}%`).join("")}${dots}${best && Math.abs(bx - yx) > 60 ? `${esc(S.models[best[0]]?.tag || best[0])}` : ""}You`;
}
/* ---------------- the stage, the transport and the loop ---------------- */
function loop(now) {
const dt = Math.min(0.1, (now - (loop.last || now)) / 1000);
loop.last = now;
S.wall += dt;
if (S.anim) {
const u = Math.min(1, (now - S.anim.start) / S.anim.dur), e = u < 0.5 ? 2 * u * u : 1 - (-2 * u + 2) ** 2 / 2;
S.t = S.anim.a + (S.anim.b - S.anim.a) * e;
if (u >= 1) {
S.anim = null;
S.phase = S.desk.done ? "over" : "turn";
if (S.desk.done) finish();
renderAll();
}
} else if (S.playing) {
const to = S.desk.done ? T1() : S.desk.minute;
S.t = Math.min(to, S.t + dt * 60 * 3);
if (S.t >= to) S.playing = false;
}
const active = S.anim || S.playing || now - S.lastInput < 2500 || S.wall < 3;
if (S.site?.stage && !document.hidden && (active || now - (loop.drawn || 0) > 66)) {
loop.drawn = now;
const f = S.site.frame(S.t, dt, S.wall);
tag(f);
weather(f);
}
readout();
scrubHandle();
run();
requestAnimationFrame(loop);
}
function battery(t) {
const v = S.view;
if (!v || t < 0 || !v.m.length) return { mw: 0, soc: v?.soc?.[0] ?? site().soc0, pre: t < 0 };
const k = Math.max(0, Math.min(v.m.length - 1, Math.floor(t / 5))), u = Math.min(1, (t - 5 * k) / 5);
return { mw: v.m[k], soc: v.soc[k] + ((v.soc[k + 1] ?? v.soc[k]) - v.soc[k]) * u };
}
function tag(f) {
const y = S.site.yard();
let el = $("tags").firstElementChild;
if (!el) {
$("tags").innerHTML = '
';
el = $("tags").firstElementChild;
}
const b = battery(S.t), mwv = b.mw;
const text = b.pre ? "Waiting at its starting charge" : S.t >= T1() ? "Window over" : mwv > 1.5 ? `Discharging ${mw(mwv)}` : mwv < -1.5 ? `Charging ${mw(mwv)}` : "Idle";
const pctv = Math.max(0, Math.min(1, b.soc / site().emax));
const key = `${text}|${Math.round(pctv * 200)}`;
if (el.dataset.key !== key) {
el.dataset.key = key;
el.className = `tag ${mwv > 1.5 ? "discharge" : mwv < -1.5 ? "charge" : ""}`;
el.querySelector(".what span").textContent = text;
el.querySelector(".bar b").style.width = `${(100 * pctv).toFixed(1)}%`;
el.querySelector(".v").textContent = `${Math.round(b.soc)} of ${Math.round(site().emax)} MWh`;
}
const show = y && y.vis && $("boot").classList.contains("gone") && $("end").hidden;
el.style.display = show ? "" : "none";
if (show) el.style.transform = `translate(${y.x}px, ${y.y}px) translate(-50%, -100%)`;
}
function weather(f) {
const chips = [];
const sky = S.site.sky(f);
if (sky) chips.push(`${esc(sky)}`);
const t = S.t, seen = new Set();
for (const e of [...(S.view?.events || [])].reverse()) {
if (e.t_min > t || chips.length > 3) continue;
if (e.kind === "weather" && (e.severity === "Warning" || e.severity === "Watch" || /Warning|Watch/.test(e.event || ""))) {
const end = minuteOf(e.expires, d0());
if ((end == null || end > t) && !seen.has(e.event)) seen.add(e.event) && chips.push(`NWS ${esc(e.event)}`);
} else if (e.kind === "notice" && t - e.t_min < 240 && /Watch|Emergency|Advisory|EEA|OCN/i.test(e.level || "") && !seen.has(e.title)) {
seen.add(e.title) && chips.push(`ERCOT ${esc(e.level)}`);
}
}
const html = chips.join("");
if ($("wx").dataset.html !== html) ($("wx").dataset.html = html), ($("wx").innerHTML = html);
}
function run() {
const on = S.phase === "run" && !!S.anim;
const text = on ? `The market runs: ${short(d0(), Math.floor(S.t / 5) * 5)} → ${short(d0(), S.anim.b)}` : "";
if ($("run").dataset.text !== text) {
$("run").dataset.text = text;
$("run").querySelector("span").textContent = text;
$("run").classList.toggle("on", on);
}
}
function readout() {
if (S.desk.minute == null) {
$("readout").innerHTML = $("readout").dataset.html = "";
$("play").disabled = true;
return;
}
const now = S.desk.done ? T1() : S.desk.minute;
const back = S.t < (now ?? 0) - 1 && !S.anim;
const html = S.card ? `${esc(short(d0(), Math.floor(S.t)))}${back ? `replay · now ${esc(short(d0(), now))}` : S.anim ? "market running" : S.desk.done ? "settled" : "now"}` : "";
if ($("readout").dataset.html !== html) ($("readout").dataset.html = html), ($("readout").innerHTML = html);
const icon = S.playing ? "M4 2.5h3v11H4zM9 2.5h3v11H9z" : "M4 2.5v11l9.5-5.5z";
if ($("play-icon").getAttribute("d") !== icon) $("play-icon").setAttribute("d", icon);
$("play").disabled = !back && !S.playing;
}
const NS = "http://www.w3.org/2000/svg";
function drawScrub() {
const host = $("scrub");
if (!S.card) return;
const W = Math.max(200, host.clientWidth), H = host.clientHeight || 42, PAD = 8, TY = 15;
const t0 = -1080, t1 = T1(), X = (t) => PAD + ((t - t0) / (t1 - t0)) * (W - 2 * PAD);
const now = S.desk.done ? t1 : S.desk.minute ?? t0;
const ticks = S.wakes.map((w) => {
const why = w.reasons || [], cls = why.some((r) => EVENTFUL.has(r)) ? "ev" : why.length === 1 && why[0] === "reminder" ? "rem" : why.every((r) => r === "checkpoint") ? "ck" : "";
return ``;
}).join("");
const days = [];
for (let j = -1; j < S.card.dates.length; j++) {
const a = Math.max(t0, 1440 * j), b = Math.min(t1, 1440 * j + 1440);
if (j >= 0) days.push(``);
days.push(`${esc(W < 420 ? day(d0(), a).split(" ")[0] : day(d0(), a))}`);
}
host.innerHTML = ``;
host.dataset.w = W;
}
function scrubHandle() {
const host = $("scrub"), h = $("sc-h");
if (!h || !S.card) return;
const W = +host.dataset.w, PAD = 8, t0 = -1080, t1 = T1(), X = (t) => PAD + ((t - t0) / (t1 - t0)) * (W - 2 * PAD);
const x = X(S.t).toFixed(1);
if (h.getAttribute("cx") !== x) {
h.setAttribute("cx", x);
$("sc-played").setAttribute("width", Math.max(0, X(S.t) - PAD).toFixed(1));
host.setAttribute("aria-valuenow", String(Math.round(S.t)));
}
}
function transport() {
const host = $("scrub");
const seek = (e) => {
if (!S.card || S.anim) return;
const r = host.getBoundingClientRect(), PAD = 8, t0 = -1080, t1 = T1();
const t = t0 + ((e.clientX - r.left - PAD) / (r.width - 2 * PAD)) * (t1 - t0);
const now = S.desk.done ? t1 : S.desk.minute;
S.t = Math.max(t0, Math.min(now, t));
S.playing = false;
S.lastInput = performance.now();
};
host.addEventListener("pointerdown", (e) => {
host.setPointerCapture(e.pointerId);
seek(e);
host.onpointermove = seek;
});
host.addEventListener("pointerup", () => (host.onpointermove = null));
host.addEventListener("keydown", (e) => {
if (!["ArrowLeft", "ArrowRight", "End"].includes(e.key) || S.anim) return;
e.preventDefault();
const now = S.desk.done ? T1() : S.desk.minute;
S.t = e.key === "End" ? now : Math.max(-1080, Math.min(now, S.t + (e.key === "ArrowRight" ? 60 : -60)));
S.lastInput = performance.now();
});
$("play").addEventListener("click", () => {
if (S.playing) return void (S.playing = false);
const now = S.desk.done ? T1() : S.desk.minute;
if (S.t >= now - 1) S.t = -1080;
S.playing = true;
});
$("stage").addEventListener("pointerdown", () => (S.lastInput = performance.now()));
$("stage").addEventListener("wheel", () => (S.lastInput = performance.now()), { passive: true });
new ResizeObserver(() => drawScrub()).observe(host);
}
/* ---------------- toolbar, cameras, tabs ---------------- */
function toolbar() {
$("toolbar").innerHTML = TOOLBAR.map((t) => (t === "|" ? '' : t === "grow" ? '' : ``)).join("");
$("toolbar").addEventListener("click", (e) => {
const b = e.target.closest("[data-tool]");
if (!b || b.disabled) return;
const t = b.dataset.tool;
if (t === "end_turn") return endTurn("");
if (t === "get_asset_status") return call("get_asset_status", {});
dialog(t);
});
document.addEventListener("click", (e) => {
const q = e.target.closest("[data-q]");
if (q && !q.disabled) {
if (q.dataset.q === "opt") quickOptimize();
else if (q.dataset.q === "send") quickSubmit();
else if (q.dataset.q === "end") quickEnd();
else if (q.dataset.q === "auto") autopilot();
return;
}
const ask = e.target.closest("[data-ask]");
if (ask && S.phase === "turn" && !S.busy) {
const [name, args] = JSON.parse(ask.dataset.ask);
return call(name, args);
}
const fill = e.target.closest("[data-fill]");
if (fill && S.phase === "turn") return dialog(fill.dataset.fill, { fill: true });
const act = e.target.closest("[data-act]");
if (act?.dataset.act === "close") return void ($("end").hidden = true);
if (act?.dataset.act === "results") return showEnd();
if (act?.dataset.act === "again") return S.card && restart(S.card);
if (act?.dataset.act === "pick") return picker();
if (act?.dataset.act === "resume") return resume();
if (act?.dataset.act === "restart") return restart(S.card);
});
$("w-pick").addEventListener("click", picker);
}
function cams() {
$("cams").classList.add("glass");
$("cams").innerHTML = CAMS.map(([k, label]) => ``).join("");
$("cams").addEventListener("click", (e) => {
const b = e.target.closest("[data-cam]");
if (!b || !S.site) return;
S.site.camera(b.dataset.cam);
camPressed(b.dataset.cam);
S.lastInput = performance.now();
});
}
function camPressed(k) {
for (const b of $("cams").querySelectorAll("button")) b.setAttribute("aria-pressed", String(b.dataset.cam === k));
}
function tabs() {
document.querySelector(".tabs").addEventListener("click", (e) => {
const b = e.target.closest("[data-tab]");
if (b) setTab(b.dataset.tab);
});
}
function setTab(tab) {
S.tab = tab;
for (const b of document.querySelectorAll(".tabs [data-tab]")) b.setAttribute("aria-selected", String(b.dataset.tab === tab));
for (const p of document.querySelectorAll(".panel")) p.hidden = p.dataset.panel !== tab;
if (tab === "calls") S.unseen = 0;
if (tab === "market") renderMarket();
renderCalls();
}
function flash(name) {
if (["get_prices", "get_forecasts"].includes(name)) setTab("market");
else if (["submit_dam_offers", "submit_rt_offers", "update_cop"].includes(name)) setTab("plan");
else setTab("calls");
}
function log(e) {
if (e.kind === "call") e.n = S.log.filter((x) => x.kind === "call").length + 1;
S.log.push(e);
if (S.tab !== "calls") S.unseen++;
}
/* ---------------- dialogs ---------------- */
const DAYS = ["D-1", "D0", "D1", "D2"];
const SEGS = {
market: ["dam", "rt", "sced", "as_dam", "as_rt", "asdc"], point: ["node", "hub"], step: ["", "5m", "15m", "1h"],
kind: ["price", "as_price", "load", "wind", "solar", "net_load", "outages", "weather"], fmarket: ["dam", "rt"], detail: ["summary", "hourly"],
ckind: ["dam", "rt", "cop"],
};
const FORMS = {
get_prices: { title: "Prices", text: "Posted prices only: the DAM by hour, real-time settlement prices every 15 minutes, SCED prices every 5 minutes, at your node or your hub; and the AS prices and demand curves.", fields: [["market", "seg", "market", "dam"], ["point", "seg", "point", "node"], ["day", "seg", DAYS, "D0"], ["step", "seg", "step", ""], ["start", "text", "start (optional)", ""], ["end", "text", "end (optional)", ""]] },
get_forecasts: { title: "Forecasts", text: "As-issued forecasts: the desk's price forecast (P10, P50, P90; modelled), ERCOT's load, wind, solar and net load, outage capacity and NWS alerts.", fields: [["kind", "seg", "kind", "price"], ["market", "seg", "fmarket", "dam"], ["day", "seg", DAYS.slice(1), "D0"], ["vintage", "text", "vintage", "latest"]] },
get_grid_conditions: { title: "Grid conditions", text: "System conditions on the 5-minute grid: reserves (PRC), system lambda, load, wind, solar, the EEA level and recent ERCOT notices.", fields: [["start", "text", "start (optional)", ""], ["end", "text", "end (optional)", ""]] },
get_position: { title: "Position", text: "Your book: DAM awards, real-time dispatch, the curves in force, your COP and the shadow statement.", fields: [["day", "seg", DAYS.slice(1), "D0"], ["detail", "seg", "detail", "summary"]] },
optimize: { title: "Optimize", text: "Co-optimises the DAM and real time on your price view and proposes curves, reserve offers and a COP, with projected profit. It submits nothing and never sees prices that have not posted. The fields start at the anchor's settings; the tool's own defaults are risk 0.5 and a physical DAM position.", fields: [["price_view", "text", 'price view ("desk" or JSON)', "desk"], ["risk", "range", "risk: 0 acts on the median, up to 2 widens curves to the scenario range", 1.5], ["dam_position", "seg", ["spread", "physical"], "spread"], ["end_soc_mwh", "text", "end state of charge, MWh (optional)", ""], ["max_cycles", "text", "max cycles (optional)", ""]] },
submit_dam_offers: { title: "DA offers", text: "DAM offers for an operating day: one Energy Bid/Offer Curve per hour, 2–10 [MW, $/MWh] points from max charge (negative MW) to max discharge, due before 10:00 the day before. Reserve offers ride in as_offers.", fields: [["day", "seg", DAYS.slice(1), "D0"], ["curves", "json", "curves", [{ hours: "HE18-HE21", points: [[0, -250], [0, 80], [100, 81], [100, 5000]] }]], ["as_offers", "json", "as_offers (optional)", null]] },
submit_rt_offers: { title: "RT offers", text: "Real-time curves from 18:00 the day before until each hour ends; each change applies from the next 5-minute SCED run.", fields: [["day", "seg", DAYS.slice(1), "D0"], ["curves", "json", "curves", [{ hours: "HE18-HE21", points: [[0, -250], [0, 80], [100, 81], [100, 2000]] }]], ["as_offers", "json", "as_offers (optional)", null]] },
update_cop: { title: "COP", text: "Your Current Operating Plan per hour: status, HSL/LSL, HBSOC and MinSOC/MaxSOC. An hour freezes 60 minutes before it starts.", fields: [["day", "seg", DAYS.slice(1), "D0"], ["rows", "json", "rows", [{ hours: "HE01-HE24", hbsoc_mwh: 50 }]]] },
check_submission: { title: "Check", text: "Validate a DAM, RT or COP submission without sending it, with ERCOT-style codes; for DAM curves, where they would clear at the desk's P50.", fields: [["kind", "seg", "ckind", "dam"], ["payload", "json", "payload: the arguments of the matching submit tool", { day: "D0", curves: [{ hours: "HE18-HE21", points: [[0, -250], [0, 80], [100, 81], [100, 5000]] }] }]] },
set_reminder: { title: "Reminder", text: "Wake yourself at a time on the 5-minute grid. Ending your turn waits until the next wake-up: a milestone, an event, or your reminder.", fields: [["at", "text", 'at ("D0 14:00", "18:30" or "Tue 08-18 09:00")', "D0 09:00"], ["note", "text", "note", ""]] },
};
function dialogs() {
$("dialog").addEventListener("click", (e) => e.target.closest("[data-close]") && closeDialog());
$("picker").addEventListener("click", (e) => e.target.closest("[data-close]") && ($("picker").hidden = true));
addEventListener("keydown", (e) => {
if (e.key === "Escape") (closeDialog(), ($("picker").hidden = true));
});
}
function closeDialog() {
$("dialog").hidden = true;
}
function proposalArgs(tool) {
const p = S.proposal;
if (!p) return null;
const key = { submit_dam_offers: ["dam_curves", "dam_as_offers"], submit_rt_offers: ["rt_curves", "rt_as_offers"] }[tool];
if (key) {
const curves = (p[key[0]] || []).filter((g) => tool === "submit_dam_offers" || S.desk.minute >= 1440 * +g.day.slice(1) - 360);
const dayKey = curves[0]?.day || "D0";
const as = (p[key[1]] || []).filter((a) => a.day === dayKey).map(({ day: _d, ...a }) => a);
return { day: dayKey, curves: curves.filter((g) => g.day === dayKey).map((g) => ({ hours: g.hours, points: g.points })), as_offers: as.length ? as : null };
}
if (tool === "update_cop" && p.cop?.length) return { day: p.cop[0].day, rows: p.cop.filter((r) => r.day === p.cop[0].day).map((r) => ({ hours: r.hours, hbsoc_mwh: r.hbsoc_mwh })) };
return null;
}
function dialog(tool, { fill = false } = {}) {
const spec = FORMS[tool], form = $("form");
const all = tool === "*";
const pre = fill ? proposalArgs(tool) : null;
const vals = {};
const segHtml = (name, opts, cur) => `
${opts.map((o) => ``).join("")}
`;
let body;
if (all) {
const names = Object.keys(S.tools).filter((n) => n !== "end_turn");
body = `Input schema`;
} else {
body = spec.fields.map(([name, kind, label, def]) => {
const v = pre && name in pre ? pre[name] : def;
vals[name] = v;
if (kind === "seg") return `
`;
place($("dialog"));
$("dialog").hidden = false;
if (all) {
const pickTool = () => {
const t = S.tools[$("f-tool").value];
$("f-desc").textContent = t?.description || "";
$("f-schema").textContent = JSON.stringify(t?.input_schema || {}, null, 1);
};
$("f-tool").addEventListener("change", pickTool);
pickTool();
}
form.querySelectorAll("[data-seg]").forEach((g) => g.addEventListener("click", (e) => {
const b = e.target.closest("button[data-v]");
if (!b) return;
for (const x of g.querySelectorAll("button")) x.setAttribute("aria-pressed", String(x === b));
}));
form.querySelector("input[type=range]")?.addEventListener("input", (e) => ($(`f-${e.target.id.slice(2)}-v`).textContent = e.target.value));
$("f-fill")?.addEventListener("click", () => {
const p = proposalArgs(tool);
if (!p) return;
for (const [k, v] of Object.entries(p)) {
const ta = $(`f-${k}`);
if (ta) ta.value = v == null ? "" : JSON.stringify(v, null, 1);
const seg = form.querySelector(`[data-seg="${k}"]`);
if (seg) for (const x of seg.querySelectorAll("button")) x.setAttribute("aria-pressed", String(x.dataset.v === v));
}
});
const collect = () => {
if (all) return [$("f-tool").value, JSON.parse($("f-args").value || "{}")];
const args = {};
for (const [name, kind] of spec.fields) {
if (kind === "seg") {
const v = form.querySelector(`[data-seg="${name}"] [aria-pressed="true"]`)?.dataset.v;
if (v) args[name] = v;
} else if (kind === "range") args[name] = +$(`f-${name}`).value;
else if (kind === "json") {
const s = $(`f-${name}`).value.trim();
if (s) args[name] = JSON.parse(s);
} else {
const s = $(`f-${name}`).value.trim();
if (s) args[name] = name === "end_soc_mwh" || name === "max_cycles" ? +s : s;
}
}
if (tool === "optimize") {
const pv = args.price_view;
const out = { price_view: pv && pv.startsWith("{") ? JSON.parse(pv) : pv || "desk", risk: args.risk, constraints: { dam_position: args.dam_position } };
if (args.end_soc_mwh != null) out.constraints.end_soc_mwh = args.end_soc_mwh;
if (args.max_cycles != null) out.constraints.max_cycles = args.max_cycles;
return [tool, out];
}
if (tool === "get_forecasts" && args.kind !== "price" && args.kind !== "as_price") delete args.market;
if (tool === "get_prices" && args.market.startsWith("as")) delete args.point;
return [tool, args];
};
const send = async (asCheck) => {
let name, args;
try {
[name, args] = collect();
} catch (e) {
$("f-err").textContent = `Arguments: ${e.message}`;
return;
}
if (asCheck) [name, args] = ["check_submission", { kind: { submit_dam_offers: "dam", submit_rt_offers: "rt", update_cop: "cop" }[tool], payload: args }];
closeDialog();
await call(name, args);
if (!asCheck && ["get_prices", "get_forecasts"].includes(name)) setTab("market");
};
form.onsubmit = (e) => (e.preventDefault(), send(false));
$("f-check")?.addEventListener("click", () => send(true));
form.querySelector("input, textarea, select, button")?.focus();
}
function picker() {
const box = $("pk");
const fronts = {};
for (const c of S.cards) (fronts[c.front.date] ||= []).push(c);
box.innerHTML = `
Choose a window
The v4 benchmark's 32 windows: four real batteries across eight Texas weather fronts, three operating days each. Hollow dots are before the models' training cutoffs, filled after.
`;
box.onclick = (e) => {
const b = e.target.closest("[data-i]");
if (!b) return;
$("picker").hidden = true;
restart(S.cards[+b.dataset.i]);
};
place($("picker"));
$("picker").hidden = false;
}
/** A dialog covers the part of the frame the Space's window shows: on a phone the frame is as tall as the page. */
function place(el) {
let f = null;
try {
f = window.frameElement;
} catch {}
if (!f) return;
const r = f.getBoundingClientRect(), top = Math.max(0, -r.top), bottom = Math.min(r.height, parent.innerHeight - r.top);
Object.assign(el.style, { top: `${top}px`, height: `${Math.max(240, bottom - top)}px` });
}
/* ---------------- dropped sessions ---------------- */
function dropped(text, { capacity = false } = {}) {
if (S.ended && !capacity) return;
S.ended = true;
S.auto = false;
S.anim = null;
S.busy = false;
const n = S.moves.length;
$("drop").innerHTML = `${esc(text)} ${capacity ? "" : n ? `Your ${n} move${n === 1 ? "" : "s"} are kept: the desk is deterministic, so replaying them restores this exact moment.` : ""}${!capacity && n ? '' : ""}`;
$("drop").hidden = false;
$("boot").classList.add("gone");
renderAll();
}
function hideDrop() {
$("drop").hidden = true;
}
async function resume() {
const moves = S.moves.slice();
S.session.close();
S.session = session();
await open(S.card, { moves });
}
async function restart(card) {
S.auto = false;
S.session.close();
S.session = session();
await open(card);
}
/* ---------------- helpers ---------------- */
function dateSpan(dates) {
const a = new Date(`${dates[0]}T12:00:00Z`), b = new Date(`${dates.at(-1)}T12:00:00Z`);
const M = (x) => x.toLocaleString("en-US", { month: "short", timeZone: "UTC" });
return a.getUTCMonth() === b.getUTCMonth() ? `${a.getUTCDate()}–${b.getUTCDate()} ${M(b)} ${b.getUTCFullYear()}` : `${a.getUTCDate()} ${M(a)}–${b.getUTCDate()} ${M(b)} ${b.getUTCFullYear()}`;
}
const cap = (s) => (s ? s[0].toUpperCase() + s.slice(1) : "");
const when = (label) => {
const m = minuteOf(label, d0());
return m == null ? label : short(d0(), m);
};
/** The frame in the Try Environment tab fills the Space's window below the tab's controls, down to FIT_MIN, so a page or
* an embed 820 px tall shows the whole desk without scrolling. On a phone the page is one tall column: the frame takes
* the page's full height, so only the Space's page scrolls. */
function fitFrame() {
let f = null;
try {
f = window.frameElement;
} catch {}
if (!f || !f.getClientRects().length) return;
if (matchMedia("(max-width: 760px)").matches) return void (f.style.height = `${document.documentElement.scrollHeight}px`);
const top = f.getBoundingClientRect().top + parent.scrollY;
f.style.height = `${Math.max(FIT_MIN, Math.floor(parent.innerHeight - top - FIT_GAP))}px`;
}
new ResizeObserver(fitFrame).observe(document.body);
try {
parent.addEventListener("resize", fitFrame);
} catch {}
main().catch((e) => {
console.error(e);
$("boot").querySelector("span").textContent = `The page could not start: ${e.message}`;
});