Spaces:
Running
Running
File size: 21,607 Bytes
35ea9cd ca37eed 35ea9cd ca37eed 35ea9cd ca37eed ce96a1b ca37eed ce96a1b ca37eed ce96a1b 35ea9cd ca37eed 35ea9cd ca37eed 35ea9cd b9d7c95 35ea9cd 3748f8d 35ea9cd 3748f8d 35ea9cd ca37eed 35ea9cd ca37eed 35ea9cd 3748f8d 35ea9cd 3748f8d 35ea9cd b9d7c95 35ea9cd ca37eed 35ea9cd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | async function fetchJson(url, options = {}) {
const response = await fetch(url, options);
const contentType = response.headers.get("content-type") || "";
const body = contentType.includes("application/json") ? await response.json() : await response.text();
if (!response.ok) {
const detail = typeof body === "object" ? body.detail || JSON.stringify(body) : body;
throw new Error(`${response.status} ${response.statusText}: ${detail}`);
}
return body;
}
function safeText(value) {
return value == null ? "--" : String(value);
}
function createBadge(text, extraClass = "") {
const badge = document.createElement("span");
badge.className = extraClass ? `badge ${extraClass}` : "badge";
badge.textContent = safeText(text);
return badge;
}
function setHealthPill(status) {
const pills = document.querySelectorAll("[data-health-pill]");
pills.forEach((pill) => {
pill.textContent = status === "healthy" ? "Healthy" : "Unavailable";
pill.classList.toggle("is-pending", status !== "healthy");
});
}
function renderTaskCards(target, tasks) {
if (!target) return;
target.replaceChildren();
Object.entries(tasks).forEach(([taskId, task]) => {
const article = document.createElement("article");
article.className = "task-card";
const difficultyClass = `difficulty-${safeText(task.difficulty).toLowerCase().replace(/[^a-z0-9_-]/g, "")}`;
const difficulty = createBadge(task.difficulty, difficultyClass);
const title = document.createElement("h3");
title.textContent = safeText(task.name);
const content = document.createElement("div");
content.className = "task-card-content";
const expectedField = document.createElement("p");
expectedField.append("Expected field: ");
const expectedFieldValue = document.createElement("strong");
expectedFieldValue.textContent = safeText(task.expected_field || task.output_field);
expectedField.appendChild(expectedFieldValue);
content.append(title, expectedField);
const taskMeta = document.createElement("div");
taskMeta.className = "task-meta";
taskMeta.append(
createBadge(taskId),
createBadge(`${task.ticket_count || 0} incidents`),
);
const taskValues = document.createElement("div");
taskValues.className = "task-values";
(task.allowed_values || task.labels || []).forEach((value) => {
taskValues.appendChild(createBadge(value));
});
article.append(difficulty, content, taskMeta, taskValues);
target.appendChild(article);
});
}
async function initHome() {
const [health, metadata] = await Promise.all([
fetchJson("/health"),
fetchJson("/metadata"),
]);
setHealthPill(health.status);
document.querySelector("[data-total-incidents]").textContent = safeText(metadata.total_tickets);
document.querySelector("[data-task-count]").textContent = safeText(Object.keys(metadata.tasks).length);
renderTaskCards(document.querySelector("[data-task-grid]"), metadata.tasks);
}
async function initStatus() {
const [health, metadata, grader, schema] = await Promise.all([
fetchJson("/health"),
fetchJson("/metadata"),
fetchJson("/grader"),
fetchJson("/schema"),
]);
document.querySelector("[data-health-text]").textContent = health.status;
document.querySelector("[data-total-incidents]").textContent = safeText(metadata.total_tickets);
document.querySelector("[data-schema-count]").textContent = safeText(Object.keys(schema).length);
renderTaskCards(document.querySelector("[data-task-grid]"), metadata.tasks);
const schemaGrid = document.querySelector("[data-schema-grid]");
schemaGrid.replaceChildren();
Object.keys(schema).forEach((name) => {
schemaGrid.appendChild(createBadge(name));
});
document.querySelector("[data-grader-summary]").textContent = grader.scoring;
const graderList = document.querySelector("[data-grader-list]");
graderList.replaceChildren();
Object.entries(grader.tasks).forEach(([task, rule]) => {
const item = document.createElement("li");
const taskName = document.createElement("strong");
taskName.textContent = task;
item.append(taskName, `: ${safeText(rule)}`);
graderList.appendChild(item);
});
}
function buildActionPayload(observation, selectedValue) {
const payload = {
incident_id: observation.incident_id,
task_type: observation.task_type,
};
payload[observation.expected_field] = selectedValue;
return payload;
}
function createEndpointCard(endpoint) {
const card = document.createElement("article");
card.className = "endpoint-card";
const header = document.createElement("div");
header.className = "endpoint-card-header";
header.append(createBadge(endpoint.method, `method-${endpoint.method.toLowerCase()}`));
const path = document.createElement("code");
path.textContent = endpoint.path;
header.appendChild(path);
const title = document.createElement("h3");
title.textContent = endpoint.title;
const description = document.createElement("p");
description.textContent = endpoint.description;
const meta = document.createElement("div");
meta.className = "endpoint-meta";
endpoint.notes.forEach((note) => {
meta.appendChild(createBadge(note));
});
const link = document.createElement("a");
link.className = "button button-secondary endpoint-link";
link.href = endpoint.href;
link.textContent = endpoint.linkText;
card.append(header, title, description, meta, link);
return card;
}
async function initApi() {
const [health, metadata, grader, schema] = await Promise.all([
fetchJson("/health"),
fetchJson("/metadata"),
fetchJson("/grader"),
fetchJson("/schema"),
]);
document.querySelector("[data-api-health]").textContent = health.status === "healthy" ? "Healthy" : "Unavailable";
document.querySelector("[data-api-summary]").textContent =
`${safeText(metadata.total_tickets)} incidents across ${Object.keys(metadata.tasks || {}).length} task families.`;
const endpoints = [
{
method: "GET",
path: "/health",
title: "Health check",
description: "Fast validator ping. Must return a healthy status.",
notes: ["validator", "no body"],
href: "/health",
linkText: "Open raw health",
},
{
method: "GET",
path: "/metadata",
title: "Environment metadata",
description: "Shows name, task inventory, labels, and dataset count.",
notes: ["task inventory", "reviewer-friendly"],
href: "/metadata",
linkText: "Open raw metadata",
},
{
method: "GET",
path: "/schema",
title: "Typed contract schemas",
description: "Exposes action, observation, reward, state, and step result models.",
notes: ["typed models", "OpenEnv spec"],
href: "/schema",
linkText: "Open raw schema",
},
{
method: "POST",
path: "/reset",
title: "Start an episode",
description: "Creates a session and returns the first observation. No grading happens yet.",
notes: ["returns session_id", "body optional"],
href: "/playground",
linkText: "Try in playground",
},
{
method: "POST",
path: "/step?session_id=...",
title: "Submit an answer",
description: "Grades exactly one action and returns reward, done, correctness, and state.",
notes: ["reward 0-1", "single step"],
href: "/playground",
linkText: "Try in playground",
},
{
method: "GET",
path: "/state?session_id=...",
title: "Read episode state",
description: "Reads active or completed episode state for a known session id.",
notes: ["typed state", "debugging"],
href: "/playground",
linkText: "Create session first",
},
{
method: "GET",
path: "/docs",
title: "Generated FastAPI docs",
description: "Full OpenAPI interface generated from the running backend.",
notes: ["developer docs", "OpenAPI"],
href: "/docs",
linkText: "Open FastAPI docs",
},
{
method: "GET",
path: "/openapi.json",
title: "Machine-readable contract",
description: "Raw OpenAPI document used by tools and automated inspectors.",
notes: ["JSON", "tooling"],
href: "/openapi.json",
linkText: "Open raw OpenAPI",
},
];
const endpointGrid = document.querySelector("[data-endpoint-grid]");
endpointGrid.replaceChildren();
endpoints.forEach((endpoint) => {
endpointGrid.appendChild(createEndpointCard(endpoint));
});
const schemaGrid = document.querySelector("[data-api-schema-grid]");
schemaGrid.replaceChildren();
Object.keys(schema).forEach((name) => {
schemaGrid.appendChild(createBadge(name));
});
const graderList = document.querySelector("[data-api-grader-list]");
graderList.replaceChildren();
Object.entries(grader.tasks || {}).forEach(([task, rule]) => {
const item = document.createElement("li");
const taskName = document.createElement("strong");
taskName.textContent = task;
item.append(taskName, `: ${safeText(rule)}`);
graderList.appendChild(item);
});
}
async function initPlayground() {
const resetForm = document.getElementById("reset-form");
const stepForm = document.getElementById("step-form");
const taskTypeInput = document.getElementById("task-type");
const ticketIdInput = document.getElementById("ticket-id");
const ticketOptions = document.getElementById("ticket-options");
const ticketHelper = document.getElementById("ticket-helper");
const expectedFieldInput = document.getElementById("expected-field");
const actionValueSelect = document.getElementById("action-value");
const stepButton = document.getElementById("step-button");
const resetButton = document.getElementById("reset-button");
const sessionIdTarget = document.getElementById("session-id");
const observationOutput = document.getElementById("observation-output");
const resultOutput = document.getElementById("result-output");
const messageTarget = document.getElementById("playground-message");
const summaryIncident = document.getElementById("summary-incident");
const summaryField = document.getElementById("summary-field");
const summaryReward = document.getElementById("summary-reward");
const summaryStatus = document.getElementById("summary-status");
const briefAlert = document.getElementById("brief-alert");
const briefTask = document.getElementById("brief-task");
const briefDifficulty = document.getElementById("brief-difficulty");
const briefExpected = document.getElementById("brief-expected");
const briefAllowedValues = document.getElementById("brief-allowed-values");
const briefContextSignals = document.getElementById("brief-context-signals");
const briefVerdict = document.getElementById("brief-verdict");
const briefAgentAnswer = document.getElementById("brief-agent-answer");
const briefGroundTruth = document.getElementById("brief-ground-truth");
const briefReward = document.getElementById("brief-reward");
const briefReason = document.getElementById("brief-reason");
let sessionId = null;
let observation = null;
let validTickets = [];
const setOutput = (target, data) => {
target.textContent = typeof data === "string" ? data : JSON.stringify(data, null, 2);
};
const setMessage = (message, mode = "neutral") => {
messageTarget.textContent = message;
messageTarget.dataset.mode = mode;
};
const setBusy = (button, isBusy, busyText, idleText) => {
button.disabled = isBusy;
button.textContent = isBusy ? busyText : idleText;
};
const updateSummaryFromObservation = (nextObservation) => {
summaryIncident.textContent = nextObservation.incident_id;
summaryField.textContent = nextObservation.expected_field;
summaryReward.textContent = "--";
summaryStatus.textContent = "Awaiting action";
};
const updateSummaryFromResult = (result) => {
summaryReward.textContent = result.reward?.value ?? "--";
summaryStatus.textContent = result.done ? "Completed" : "In progress";
};
const formatContextValue = (value) => {
if (Array.isArray(value)) return value.join(", ");
if (value && typeof value === "object") return JSON.stringify(value);
if (typeof value === "boolean") return value ? "true" : "false";
return safeText(value);
};
const renderValueChips = (target, values) => {
target.replaceChildren();
values.forEach((value) => {
target.appendChild(createBadge(value));
});
};
const renderContextSignals = (target, context) => {
target.replaceChildren();
Object.entries(context || {}).slice(0, 8).forEach(([key, value]) => {
const chip = document.createElement("span");
chip.className = "context-chip";
const chipKey = document.createElement("strong");
chipKey.textContent = key;
const chipValue = document.createElement("span");
chipValue.textContent = formatContextValue(value);
chip.append(chipKey, chipValue);
target.appendChild(chip);
});
if (target.childElementCount === 0) {
const empty = document.createElement("span");
empty.className = "context-chip";
empty.textContent = "No context signals provided.";
target.appendChild(empty);
}
};
const resetResultBrief = () => {
briefVerdict.textContent = "Waiting for step";
briefVerdict.dataset.outcome = "waiting";
briefAgentAnswer.textContent = "--";
briefGroundTruth.textContent = "--";
briefReward.textContent = "--";
briefReason.textContent = "Submit a step to see the deterministic grader explanation.";
};
const updateBriefFromObservation = (resetResult) => {
const nextObservation = resetResult.observation;
briefAlert.textContent = nextObservation.alert_text;
briefTask.textContent = resetResult.info?.task_name || nextObservation.task_description;
briefDifficulty.textContent = nextObservation.difficulty;
briefExpected.textContent = nextObservation.expected_field;
renderValueChips(briefAllowedValues, nextObservation.allowed_values || []);
renderContextSignals(briefContextSignals, nextObservation.context);
resetResultBrief();
};
const updateBriefFromResult = (result) => {
const correct = Boolean(result.info?.correct);
const rewardValue = Number(result.reward?.value || 0);
const partialCredit = !correct && rewardValue > 0;
briefVerdict.textContent = correct
? "Correct triage decision"
: partialCredit
? "Partial credit"
: "Incorrect decision";
briefVerdict.dataset.outcome = correct ? "correct" : partialCredit ? "partial" : "incorrect";
briefAgentAnswer.textContent = safeText(result.info?.agent_answer);
briefGroundTruth.textContent = safeText(result.info?.ground_truth);
briefReward.textContent = safeText(result.reward?.value);
briefReason.textContent = safeText(result.reward?.reason);
};
const findTicket = (ticketId) => validTickets.find((ticket) => ticket.incident_id === ticketId);
const syncTaskTypeFromTicket = () => {
const ticket = findTicket(ticketIdInput.value.trim());
if (!ticket) return;
taskTypeInput.value = ticket.task_type;
ticketHelper.textContent = `${ticket.incident_id} is a ${ticket.task_type} ${ticket.difficulty} ticket.`;
};
const chooseFirstTicketForTask = () => {
if (!taskTypeInput.value) return;
const ticket = validTickets.find((item) => item.task_type === taskTypeInput.value);
if (ticket) {
ticketIdInput.value = ticket.incident_id;
ticketHelper.textContent = `${ticket.incident_id} selected for ${taskTypeInput.value}.`;
}
};
try {
const ticketData = await fetchJson("/tickets");
validTickets = ticketData.tickets || [];
ticketOptions.replaceChildren();
validTickets.forEach((ticket) => {
const option = document.createElement("option");
option.value = safeText(ticket.incident_id);
option.label = `${safeText(ticket.task_type)} / ${safeText(ticket.task_name)}`;
ticketOptions.appendChild(option);
});
ticketHelper.textContent = `Valid ticket range: ${validTickets[0]?.incident_id || "--"} to ${validTickets.at(-1)?.incident_id || "--"}.`;
} catch (error) {
ticketHelper.textContent = `Could not load ticket list: ${error.message}`;
}
document.querySelectorAll("[data-preset-task]").forEach((button) => {
button.addEventListener("click", () => {
taskTypeInput.value = button.dataset.presetTask;
ticketIdInput.value = button.dataset.presetTicket;
setMessage(`Preset loaded: ${button.dataset.presetTask} / ${button.dataset.presetTicket}. Click Start / Reset Environment.`, "success");
});
});
resetForm.addEventListener("submit", async (event) => {
event.preventDefault();
const formData = new FormData(resetForm);
const payload = {};
for (const [key, value] of formData.entries()) {
if (value !== "") {
payload[key] = key === "seed" ? Number(value) : value;
}
}
const requestedTicket = payload.ticket_id;
const knownTicket = requestedTicket ? findTicket(requestedTicket) : null;
if (requestedTicket && validTickets.length > 0 && !knownTicket) {
const message = `Ticket ${requestedTicket} does not exist. Use one of ${validTickets[0].incident_id} to ${validTickets.at(-1).incident_id}, or click a preset.`;
setOutput(observationOutput, { error: message });
setMessage(message, "error");
return;
}
if (knownTicket && payload.task_type && payload.task_type !== knownTicket.task_type) {
payload.task_type = knownTicket.task_type;
taskTypeInput.value = knownTicket.task_type;
ticketHelper.textContent = `Task type changed to ${knownTicket.task_type} because ${knownTicket.incident_id} belongs to that task.`;
}
try {
setBusy(resetButton, true, "Starting...", "Start / Reset Environment");
setMessage("Reset request sent. Watch the terminal for a [RESET] log.", "neutral");
const result = await fetchJson("/reset", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
sessionId = result.info.session_id;
observation = result.observation;
sessionIdTarget.textContent = sessionId;
expectedFieldInput.value = observation.expected_field;
actionValueSelect.disabled = false;
stepButton.disabled = false;
actionValueSelect.replaceChildren();
observation.allowed_values.forEach((value) => {
const option = document.createElement("option");
option.value = safeText(value);
option.textContent = safeText(value);
actionValueSelect.appendChild(option);
});
setOutput(observationOutput, result);
setOutput(resultOutput, "No step submitted yet.");
updateSummaryFromObservation(observation);
updateBriefFromObservation(result);
setMessage(`Session ready for ${observation.incident_id}. Pick a value and submit the step.`, "success");
} catch (error) {
setOutput(observationOutput, { error: error.message });
setMessage(error.message, "error");
} finally {
setBusy(resetButton, false, "Starting...", "Start / Reset Environment");
}
});
stepForm.addEventListener("submit", async (event) => {
event.preventDefault();
if (!sessionId || !observation) {
setOutput(resultOutput, { error: "Start a session first." });
setMessage("Start a session before submitting a step.", "error");
return;
}
try {
setBusy(stepButton, true, "Submitting...", "Submit Step");
setMessage("Step request sent. Watch the terminal for a [STEP] log.", "neutral");
const result = await fetchJson(`/step?session_id=${encodeURIComponent(sessionId)}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(buildActionPayload(observation, actionValueSelect.value)),
});
setOutput(resultOutput, result);
updateSummaryFromResult(result);
updateBriefFromResult(result);
const reward = result.reward?.value ?? "--";
setMessage(`Step completed with reward ${reward}.`, reward === 1 ? "success" : "neutral");
} catch (error) {
setOutput(resultOutput, { error: error.message });
setMessage(error.message, "error");
} finally {
if (observation) {
setBusy(stepButton, false, "Submitting...", "Submit Step");
}
}
});
ticketIdInput.addEventListener("change", syncTaskTypeFromTicket);
ticketIdInput.addEventListener("blur", syncTaskTypeFromTicket);
taskTypeInput.addEventListener("change", chooseFirstTicketForTask);
}
async function bootstrap() {
const page = document.body.dataset.page;
try {
if (page === "home") {
await initHome();
} else if (page === "status") {
await initStatus();
} else if (page === "playground") {
await initPlayground();
} else if (page === "api") {
await initApi();
}
} catch (error) {
const pageShell = document.querySelector(".page-shell");
const banner = document.createElement("div");
banner.className = "floating-panel";
const title = document.createElement("strong");
title.textContent = "UI data load failed.";
const detail = document.createElement("p");
detail.className = "status-helper";
detail.textContent = error.message;
banner.append(title, detail);
pageShell?.prepend(banner);
}
}
window.addEventListener("DOMContentLoaded", bootstrap);
|